All checks were successful
Scan for leaked secrets using Kingfisher / kingfisher-secrets-scan (push) Successful in 10s
81 lines
2.5 KiB
PHP
81 lines
2.5 KiB
PHP
<?php
|
|
|
|
namespace App\Filament\Imports;
|
|
|
|
use App\Models\Block;
|
|
use App\Models\Plant;
|
|
use Filament\Actions\Imports\Exceptions\RowImportFailedException;
|
|
use Filament\Actions\Imports\ImportColumn;
|
|
use Filament\Actions\Imports\Importer;
|
|
use Filament\Actions\Imports\Models\Import;
|
|
use Str;
|
|
|
|
class BlockImporter extends Importer
|
|
{
|
|
protected static ?string $model = Block::class;
|
|
|
|
public static function getColumns(): array
|
|
{
|
|
return [
|
|
ImportColumn::make('name')
|
|
->requiredMapping()
|
|
->exampleHeader('BLOCK NAME')
|
|
->example('Block A')
|
|
->label('BLOCK NAME')
|
|
->rules(['required']),
|
|
ImportColumn::make('plant')
|
|
->requiredMapping()
|
|
->exampleHeader('PLANT CODE')
|
|
->example('1000')
|
|
->label('PLANT CODE')
|
|
->relationship(resolveUsing: 'code')
|
|
->rules(['required']),
|
|
];
|
|
}
|
|
|
|
public function resolveRecord(): ?Block
|
|
{
|
|
$warnMsg = [];
|
|
$plantCod = $this->data['plant'];
|
|
$plant = null;
|
|
if (Str::length($plantCod) < 4 || ! is_numeric($plantCod) || ! preg_match('/^[1-9]\d{3,}$/', $plantCod)) {
|
|
$warnMsg[] = 'Invalid plant code found';
|
|
} else {
|
|
$plant = Plant::where('code', $plantCod)->first();
|
|
if (! $plant) {
|
|
$warnMsg[] = 'Plant not found';
|
|
// $warnMsg[] = "Plant '" . $plantCod . "' not found";
|
|
}
|
|
}
|
|
if (Str::length($this->data['name']) < 0) {
|
|
$warnMsg[] = 'Block name not found';
|
|
}
|
|
|
|
if (! empty($warnMsg)) {
|
|
throw new RowImportFailedException(implode(', ', $warnMsg));
|
|
}
|
|
|
|
return Block::updateOrCreate([
|
|
'name' => $this->data['name'],
|
|
'plant_id' => $plant->id,
|
|
]);
|
|
// return Block::firstOrNew([
|
|
// // Update existing records, matching them by `$this->data['column_name']`
|
|
// 'email' => $this->data['email'],
|
|
// ]);
|
|
|
|
// return new Block();
|
|
}
|
|
|
|
public static function getCompletedNotificationBody(Import $import): string
|
|
{
|
|
$body = 'Your block import has completed and '.number_format($import->successful_rows).' '.str('row')->plural($import->successful_rows).' imported.';
|
|
|
|
if ($failedRowsCount = $import->getFailedRowsCount()) {
|
|
$body .= ' '.number_format($failedRowsCount).' '.str('row')->plural($failedRowsCount).' failed to import.';
|
|
}
|
|
|
|
return $body;
|
|
}
|
|
}
|