Skip to content

Commit

Permalink
Add The New Behaviuor
Browse files Browse the repository at this point in the history
  • Loading branch information
Abdelhammied committed Jan 22, 2025
1 parent 1f8c869 commit 4daa7bc
Show file tree
Hide file tree
Showing 4 changed files with 81 additions and 57 deletions.
2 changes: 1 addition & 1 deletion packages/actions/src/Concerns/CanExportRecords.php
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ protected function setUp(): void
return;
}

$user = auth()->user();
$user = auth(Export::getAuthGuard())->user();

if ($action->hasColumnMapping()) {
$columnMap = collect($data['columnMap'])
Expand Down
108 changes: 54 additions & 54 deletions packages/actions/src/Concerns/CanImportRecords.php
Original file line number Diff line number Diff line change
Expand Up @@ -52,18 +52,18 @@ trait CanImportRecords

protected ?string $job = null;

protected int | Closure $chunkSize = 100;
protected int|Closure $chunkSize = 100;

protected int | Closure | null $maxRows = null;
protected int|Closure|null $maxRows = null;

protected int | Closure | null $headerOffset = null;
protected int|Closure|null $headerOffset = null;

protected string | Closure | null $csvDelimiter = null;
protected string|Closure|null $csvDelimiter = null;

/**
* @var array<string, mixed> | Closure
*/
protected array | Closure $options = [];
protected array|Closure $options = [];

/**
* @var array<string | array<mixed> | Closure>
Expand All @@ -74,24 +74,24 @@ protected function setUp(): void
{
parent::setUp();

$this->label(fn (ImportAction | ImportTableAction $action): string => __('filament-actions::import.label', ['label' => $action->getPluralModelLabel()]));
$this->label(fn(ImportAction|ImportTableAction $action): string => __('filament-actions::import.label', ['label' => $action->getPluralModelLabel()]));

$this->modalHeading(fn (ImportAction | ImportTableAction $action): string => __('filament-actions::import.modal.heading', ['label' => $action->getPluralModelLabel()]));
$this->modalHeading(fn(ImportAction|ImportTableAction $action): string => __('filament-actions::import.modal.heading', ['label' => $action->getPluralModelLabel()]));

$this->modalDescription(fn (ImportAction | ImportTableAction $action): Htmlable => $action->getModalAction('downloadExample'));
$this->modalDescription(fn(ImportAction|ImportTableAction $action): Htmlable => $action->getModalAction('downloadExample'));

$this->modalSubmitActionLabel(__('filament-actions::import.modal.actions.import.label'));

$this->groupedIcon(FilamentIcon::resolve('actions::import-action.grouped') ?? 'heroicon-m-arrow-up-tray');

$this->form(fn (ImportAction | ImportTableAction $action): array => array_merge([
$this->form(fn(ImportAction|ImportTableAction $action): array => array_merge([
FileUpload::make('file')
->label(__('filament-actions::import.modal.form.file.label'))
->placeholder(__('filament-actions::import.modal.form.file.placeholder'))
->acceptedFileTypes(['text/csv', 'text/x-csv', 'application/csv', 'application/x-csv', 'text/comma-separated-values', 'text/x-comma-separated-values', 'text/plain', 'application/vnd.ms-excel'])
->rules($action->getFileValidationRules())
->afterStateUpdated(function (FileUpload $component, Component $livewire, Forms\Set $set, ?TemporaryUploadedFile $state) use ($action) {
if (! $state instanceof TemporaryUploadedFile) {
if (!$state instanceof TemporaryUploadedFile) {
return;
}

Expand All @@ -105,7 +105,7 @@ protected function setUp(): void

$csvStream = $this->getUploadedFileStream($state);

if (! $csvStream) {
if (!$csvStream) {
return;
}

Expand All @@ -127,12 +127,12 @@ protected function setUp(): void

$set('columnMap', array_reduce($action->getImporter()::getColumns(), function (array $carry, ImportColumn $column) use ($lowercaseCsvColumnKeys, $lowercaseCsvColumnValues) {
$carry[$column->getName()] = $lowercaseCsvColumnKeys[
Arr::first(
array_intersect(
$lowercaseCsvColumnValues,
$column->getGuesses(),
),
)
Arr::first(
array_intersect(
$lowercaseCsvColumnValues,
$column->getGuesses(),
),
)
] ?? null;

return $carry;
Expand All @@ -148,13 +148,13 @@ protected function setUp(): void
->schema(function (Forms\Get $get) use ($action): array {
$csvFile = Arr::first((array) ($get('file') ?? []));

if (! $csvFile instanceof TemporaryUploadedFile) {
if (!$csvFile instanceof TemporaryUploadedFile) {
return [];
}

$csvStream = $this->getUploadedFileStream($csvFile);

if (! $csvStream) {
if (!$csvStream) {
return [];
}

Expand All @@ -170,21 +170,21 @@ protected function setUp(): void
$csvColumnOptions = array_combine($csvColumns, $csvColumns);

return array_map(
fn (ImportColumn $column): Select => $column->getSelect()->options($csvColumnOptions),
fn(ImportColumn $column): Select => $column->getSelect()->options($csvColumnOptions),
$action->getImporter()::getColumns(),
);
})
->statePath('columnMap')
->visible(fn (Forms\Get $get): bool => Arr::first((array) ($get('file') ?? [])) instanceof TemporaryUploadedFile),
->visible(fn(Forms\Get $get): bool => Arr::first((array) ($get('file') ?? [])) instanceof TemporaryUploadedFile),
], $action->getImporter()::getOptionsFormComponents()));

$this->action(function (ImportAction | ImportTableAction $action, array $data) {
$this->action(function (ImportAction|ImportTableAction $action, array $data) {
/** @var TemporaryUploadedFile $csvFile */
$csvFile = $data['file'];

$csvStream = $this->getUploadedFileStream($csvFile);

if (! $csvStream) {
if (!$csvStream) {
return;
}

Expand Down Expand Up @@ -212,7 +212,7 @@ protected function setUp(): void
return;
}

$user = auth()->user();
$user = auth(Import::getAuthGuard())->user();

$import = app(Import::class);
$import->user()->associate($user);
Expand All @@ -239,7 +239,7 @@ protected function setUp(): void
$import->unsetRelation('user');

$importJobs = collect($importChunks)
->map(fn (array $importChunk): object => app($job, [
->map(fn(array $importChunk): object => app($job, [
'import' => $import,
'rows' => base64_encode(serialize($importChunk)),
'columnMap' => $data['columnMap'],
Expand All @@ -259,22 +259,22 @@ protected function setUp(): void
->allowFailures()
->when(
filled($jobQueue = $importer->getJobQueue()),
fn (PendingBatch $batch) => $batch->onQueue($jobQueue),
fn(PendingBatch $batch) => $batch->onQueue($jobQueue),
)
->when(
filled($jobConnection = $importer->getJobConnection()),
fn (PendingBatch $batch) => $batch->onConnection($jobConnection),
fn(PendingBatch $batch) => $batch->onConnection($jobConnection),
)
->when(
filled($jobBatchName = $importer->getJobBatchName()),
fn (PendingBatch $batch) => $batch->name($jobBatchName),
fn(PendingBatch $batch) => $batch->name($jobBatchName),
)
->finally(function () use ($columnMap, $import, $jobConnection, $options) {
$import->touch('completed_at');

event(new ImportCompleted($import, $columnMap, $options));

if (! $import->user instanceof Authenticatable) {
if (!$import->user instanceof Authenticatable) {
return;
}

Expand All @@ -284,20 +284,20 @@ protected function setUp(): void
->title($import->importer::getCompletedNotificationTitle($import))
->body($import->importer::getCompletedNotificationBody($import))
->when(
! $failedRowsCount,
fn (Notification $notification) => $notification->success(),
!$failedRowsCount,
fn(Notification $notification) => $notification->success(),
)
->when(
$failedRowsCount && ($failedRowsCount < $import->total_rows),
fn (Notification $notification) => $notification->warning(),
fn(Notification $notification) => $notification->warning(),
)
->when(
$failedRowsCount === $import->total_rows,
fn (Notification $notification) => $notification->danger(),
fn(Notification $notification) => $notification->danger(),
)
->when(
$failedRowsCount,
fn (Notification $notification) => $notification->actions([
fn(Notification $notification) => $notification->actions([
NotificationAction::make('downloadFailedRowsCsv')
->label(trans_choice('filament-actions::import.notifications.completed.actions.download_failed_rows_csv.label', $failedRowsCount, [
'count' => Number::format($failedRowsCount),
Expand All @@ -309,11 +309,11 @@ protected function setUp(): void
)
->when(
($jobConnection === 'sync') ||
(blank($jobConnection) && (config('queue.default') === 'sync')),
fn (Notification $notification) => $notification
(blank($jobConnection) && (config('queue.default') === 'sync')),
fn(Notification $notification) => $notification
->persistent()
->send(),
fn (Notification $notification) => $notification->sendToDatabase($import->user, isEventDispatched: true),
fn(Notification $notification) => $notification->sendToDatabase($import->user, isEventDispatched: true),
);
})
->dispatch();
Expand All @@ -334,9 +334,9 @@ protected function setUp(): void

$this->registerModalActions([
(match (true) {
$this instanceof TableAction => TableAction::class,
default => Action::class,
})::make('downloadExample')
$this instanceof TableAction => TableAction::class,
default => Action::class,
})::make('downloadExample')
->label(__('filament-actions::import.modal.actions.download_example.label'))
->link()
->action(function (): StreamedResponse {
Expand All @@ -350,18 +350,18 @@ protected function setUp(): void
}

$csv->insertOne(array_map(
fn (ImportColumn $column): string => $column->getExampleHeader(),
fn(ImportColumn $column): string => $column->getExampleHeader(),
$columns,
));

$columnExamples = array_map(
fn (ImportColumn $column): array => $column->getExamples(),
fn(ImportColumn $column): array => $column->getExamples(),
$columns,
);

$exampleRowsCount = array_reduce(
$columnExamples,
fn (int $count, array $exampleData): int => max($count, count($exampleData)),
fn(int $count, array $exampleData): int => max($count, count($exampleData)),
initial: 0,
);

Expand Down Expand Up @@ -389,7 +389,7 @@ protected function setUp(): void

$this->successNotificationTitle(__('filament-actions::import.notifications.started.title'));

$this->model(fn (ImportAction | ImportTableAction $action): string => $action->getImporter()::getModel());
$this->model(fn(ImportAction|ImportTableAction $action): string => $action->getImporter()::getModel());
}

/**
Expand Down Expand Up @@ -454,7 +454,7 @@ protected function detectCsvEncoding(mixed $resource): ?string
];

foreach ($encodings as $encoding) {
if (! mb_check_encoding($fileHeader, $encoding)) {
if (!mb_check_encoding($fileHeader, $encoding)) {
continue;
}

Expand Down Expand Up @@ -489,28 +489,28 @@ public function job(?string $job): static
return $this;
}

public function chunkSize(int | Closure $size): static
public function chunkSize(int|Closure $size): static
{
$this->chunkSize = $size;

return $this;
}

public function maxRows(int | Closure | null $rows): static
public function maxRows(int|Closure|null $rows): static
{
$this->maxRows = $rows;

return $this;
}

public function headerOffset(int | Closure | null $offset): static
public function headerOffset(int|Closure|null $offset): static
{
$this->headerOffset = $offset;

return $this;
}

public function csvDelimiter(string | Closure | null $delimiter): static
public function csvDelimiter(string|Closure|null $delimiter): static
{
$this->csvDelimiter = $delimiter;

Expand Down Expand Up @@ -555,7 +555,7 @@ public function getCsvDelimiter(?CsvReader $reader = null): ?string

protected function guessCsvDelimiter(?CsvReader $reader = null): ?string
{
if (! $reader) {
if (!$reader) {
return null;
}

Expand All @@ -567,7 +567,7 @@ protected function guessCsvDelimiter(?CsvReader $reader = null): ?string
/**
* @param array<string, mixed> | Closure $options
*/
public function options(array | Closure $options): static
public function options(array|Closure $options): static
{
$this->options = $options;

Expand All @@ -585,7 +585,7 @@ public function getOptions(): array
/**
* @param string | array<mixed> | Closure $rules
*/
public function fileRules(string | array | Closure $rules): static
public function fileRules(string|array|Closure $rules): static
{
$this->fileValidationRules = [
...$this->fileValidationRules,
Expand All @@ -606,7 +606,7 @@ public function getFileValidationRules(): array
function (string $attribute, mixed $value, Closure $fail) {
$csvStream = $this->getUploadedFileStream($value);

if (! $csvStream) {
if (!$csvStream) {
return;
}

Expand Down Expand Up @@ -634,7 +634,7 @@ function (string $attribute, mixed $value, Closure $fail) {
return;
}

$filledDuplicateCsvColumns = array_filter($duplicateCsvColumns, fn ($value): bool => filled($value));
$filledDuplicateCsvColumns = array_filter($duplicateCsvColumns, fn($value): bool => filled($value));

$fail(trans_choice('filament-actions::import.modal.form.file.rules.duplicate_columns', count($filledDuplicateCsvColumns), [
'columns' => implode(', ', $filledDuplicateCsvColumns),
Expand Down
14 changes: 13 additions & 1 deletion packages/actions/src/Exports/Models/Export.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ class Export extends Model

protected static bool $hasPolymorphicUserRelationship = false;

protected static string|null $authGuard = null;

public function user(): BelongsTo
{
if (static::hasPolymorphicUserRelationship()) {
Expand All @@ -51,7 +53,7 @@ public function user(): BelongsTo
return $this->belongsTo($authenticatable::class);
}

if (! class_exists(User::class)) {
if (!class_exists(User::class)) {
throw new Exception('No [App\\Models\\User] model found. Please bind an authenticatable model to the [Illuminate\\Contracts\\Auth\\Authenticatable] interface in a service provider\'s [register()] method.');
}

Expand Down Expand Up @@ -89,6 +91,16 @@ public static function hasPolymorphicUserRelationship(): bool
return static::$hasPolymorphicUserRelationship;
}

public static function useAuthGuard(string $authGuard = null): void
{
static::$authGuard = $authGuard;
}

public static function getAuthGuard(): ?string
{
return static::$authGuard;
}

public function getFileDisk(): Filesystem
{
return Storage::disk($this->file_disk);
Expand Down
Loading

0 comments on commit 4daa7bc

Please sign in to comment.