Files
pds/app/Filament/Imports/ItemImporter.php

100 lines
3.5 KiB
PHP

<?php
namespace App\Filament\Imports;
use App\Models\Item;
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 ItemImporter extends Importer
{
protected static ?string $model = Item::class;
public static function getColumns(): array
{
return [
ImportColumn::make('code')
->requiredMapping()
->exampleHeader('Item Code')
->example('123456')
->label('Item Code')
->rules(['required']),
ImportColumn::make('description')
->requiredMapping()
->exampleHeader('Description')
->example('Testing Model Description 1')
->label('Description')
->rules(['required']),
ImportColumn::make('hourly_quantity')
->requiredMapping()
->exampleHeader('Hourly Quantity')
->example('25')
->label('Hourly Quantity')
->numeric()
->rules(['required', 'integer']),
ImportColumn::make('uom')
->requiredMapping()
->exampleHeader('Unit of Measure')
->example('EA')
->label('Unit of Measure'),
ImportColumn::make('plant')
->requiredMapping()
->exampleHeader('Plant Name')
->example('Ransar Industries-I')
->label('Plant Name')
->relationship(resolveUsing: 'name')
->rules(['required']),
];
}
public function resolveRecord(): ?Item
{
$warnMsg = [];
$plant = Plant::where('name', $this->data['plant'])->first();
if (!$plant) {
$warnMsg[] = "Plant not found"; // '" . $this->data['plant'] . "'
}
if (Str::length($this->data['code']) < 6 || !ctype_alnum($this->data['code'])) {
$warnMsg[] = "Invalid item code found";
}
// if (Str::length($this->data['uom']) <= 0) {
// $warnMsg[] = "Invalid unit of measure found";
// }
if (Str::length($this->data['description']) < 5) {
$warnMsg[] = "Invalid description found";
}
if (Str::length($this->data['hourly_quantity']) < 0 || !is_numeric($this->data['hourly_quantity']) || $this->data['hourly_quantity'] <= 0) {
$warnMsg[] = "Invalid hourly quantity found";
}
if (!empty($warnMsg)) {
throw new RowImportFailedException(implode(', ', $warnMsg));
}
return Item::updateOrCreate([
'code' => $this->data['code'],
'plant_id' => $plant->id
],
[
'description' => $this->data['description'],
'hourly_quantity' => $this->data['hourly_quantity'],
'uom' => $this->data['uom']
]
);
// return new Item;
}
public static function getCompletedNotificationBody(Import $import): string
{
$body = 'Your item 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;
}
}