Added external serial number import button in production order
Some checks failed
Scan for leaked secrets using Kingfisher / kingfisher-secrets-scan (push) Successful in 16s
Gemini PR Review / Gemini PR Review (pull_request) Failing after 17s
Scan for leaked secrets using Kingfisher / kingfisher-secrets-scan (pull_request) Successful in 15s
Laravel Pint / pint (pull_request) Successful in 6m59s
Laravel Larastan / larastan (pull_request) Failing after 9m30s

This commit is contained in:
dhanabalan
2026-12-03 12:00:00 +05:30
parent d52d30d337
commit 82914ee77b

View File

@@ -27,6 +27,11 @@ use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Tables\Filters\Filter;
use Str;
use Illuminate\Support\Facades\Storage;
use Filament\Forms\Components\FileUpload;
use Filament\Notifications\Notification;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;
class ProductionOrderResource extends Resource
@@ -134,7 +139,12 @@ class ProductionOrderResource extends Resource
$prefix = $year.$monthNumber;
$last = ProductionOrder::where('production_order', 'like', "{$prefix}%")->orderByDesc('production_order')->first(); // ProductionOrder::where('production_order', 'like', $prefix.'%')->orderBy('production_order', 'desc')->first();
$last = ProductionOrder::where('production_order', 'like', "{$prefix}%")->where(function ($query) {
$query->whereNull('outer_status')
->orWhere('outer_status', '')
->orWhere('outer_status', '0');
})->orderByDesc('production_order')->first();
// ProductionOrder::where('production_order', 'like', $prefix.'%')->orderBy('production_order', 'desc')->first();
if ($last) {
$lastSeq = substr($last->production_order, -4);
@@ -149,8 +159,15 @@ class ProductionOrderResource extends Resource
$prefixSerial = $plantCode.$year.$month;
$last = ProductionOrder::where('to_serial_number', 'like', "{$prefixSerial}%")->orderByDesc('to_serial_number')->first();
// $last = ProductionOrder::where('to_serial_number', 'like', "{$prefixSerial}%")->orderByDesc('to_serial_number')->first();
$last = ProductionOrder::where('to_serial_number', 'like', "{$prefixSerial}%")->where(function ($query) {
$query->whereNull('outer_status')
->orWhere('outer_status', '')
->orWhere('outer_status', '0');
})->orderByDesc('to_serial_number')->first();
// where('outer_status', '0')->
if ($last) {
$lastSeq = (int) substr($last->to_serial_number, -6);
$startSeq = $lastSeq + 1;
@@ -297,7 +314,7 @@ class ProductionOrderResource extends Resource
->alignCenter()
->sortable(),
Tables\Columns\TextColumn::make('outer_status')
->label('Status')
->label('External Serial Number')
->searchable()
->alignCenter()
->sortable(),
@@ -501,6 +518,429 @@ class ProductionOrderResource extends Resource
]),
])
->headerActions([
Tables\Actions\Action::make('Import External Serial Number')
->label('Import External Serial Number')
->form([
Select::make('plant_id')
->options(function (callable $get) {
$userHas = Filament::auth()->user()->plant_id;
return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::orderBy('code')->pluck('name', 'id')->toArray();
})
->searchable()
->label('Search by Plant Name')
->required()
->afterStateUpdated(function ($state, callable $set, callable $get) {
$set('external_serial_number', null);
$plantId = $get('plant_id');
if (! $plantId) {
$set('external_serial_number', null);
return;
}
$plantCode = Plant::find($plantId)?->code ?? null;
$directory = "uploads/ExternalSerialNo";
if ($plantId && ! Storage::disk('local')->exists($directory)) {
Storage::disk('local')->makeDirectory($directory);
}
})
->reactive(),
FileUpload::make('external_serial_number')
->label('Choose External Serial Number')
->required()
->acceptedFileTypes([
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
])
->rules(['mimes:xlsx', 'max:50'])
->maxSize(50)
->preserveFilenames()
->reactive()
->storeFiles(false)
->disk('local')
->visible(fn (Get $get) => ! empty($get('plant_id')))
->directory(function (callable $get) {
$plant = Plant::find($get('plant_id'));
$plantCode = $plant?->code ?? null;
return "uploads/ExternalSerialNo";
})
->uploadingMessage('Uploading...')
->helperText('Only .xlsx files are allowed (Excel files).'),
])
->action(function (array $data) {
$uploadedFile = $data['external_serial_number'];
$disk = Storage::disk('local');
$plantId = $data['plant_id'];
$plant = Plant::findOrFail($plantId);
$plantCode = (string) $plant->code;
$originalName = $uploadedFile->getClientOriginalName();
if (strtolower(pathinfo($originalName, PATHINFO_EXTENSION)) != 'xlsx') {
throw new \Exception('Only XLSX files are allowed.');
}
$path = $uploadedFile->storeAs("uploads/ExternalSerialNo", '.xlsx','local');
try {
$fullPath = $disk->path($path);
$rows = Excel::toArray(null, $fullPath)[0] ?? [];
if (count($rows) <= 1) {
Notification::make()
->title('Records Not Found')
->body('Uploaded Excel file does not contain any records.')
->danger()
->send();
return;
}
$productionOrders = [];
$invalidPlantCodes = [];
$invalidMatCodes = [];
$invalidPOrder = [];
$invalidQuan = [];
$invalidFromSerial = [];
$invalidToSerial = [];
$invalidToGreaterSerial = [];
$invalidSerialCountQuan = [];
$missingSerials = [];
$duplicateSerials = [];
$seenSerialNumbers = [];
$validRowsFound = false;
$excelSerialRanges = [];
$duplicateExcelSerials = [];
$userName = Filament::auth()->user()?->name;
foreach ($rows as $index => $row) {
if ($index === 0) {
continue;
}
$excelPlantCode = trim((string) ($row[0] ?? ''));
$itemCode = trim((string) ($row[1] ?? ''));
$quantity = trim((string) ($row[2] ?? ''));
$productionOrder = trim((string) ($row[3] ?? ''));
$fromSerial = trim((string) ($row[4] ?? ''));
$toSerial = trim((string) ($row[5] ?? ''));
if ($excelPlantCode == '' && $itemCode == '' && $quantity == '' && $productionOrder == '' && $fromSerial == '' && $toSerial == ''
) {
continue;
}
$plant = Plant::where('code', $excelPlantCode)->first();
if(!$plant){
$invalidPlantCodes[] = $excelPlantCode;
}
else{
$plantId = $plant->id;
$item = Item::where('plant_id', $plantId)->where('code', $itemCode)->first();
if(!$item){
$invalidMatCodes[] = $itemCode;
}
else{
$itemId = $item->id;
}
}
if($productionOrder == '' || $productionOrder == null){
$invalidPOrder[] = $productionOrder;
}
elseif ($productionOrder && Str::length($productionOrder) < 7) {
$invalidPOrder[] = $productionOrder;
}
if (!ctype_digit($quantity) || (int) $quantity <= 0) {
$invalidQuan[] = $quantity;
}
if (Str::length($fromSerial) < 9 || ! ctype_alnum($fromSerial)) {
$invalidFromSerial[] = $fromSerial;
}
if (Str::length($toSerial) < 9 || ! ctype_alnum($toSerial)) {
$invalidToSerial[] = $toSerial;
}
$fromNumber = (int) $fromSerial;
$toNumber = (int) $toSerial;
if ($fromNumber > $toNumber) {
$invalidToGreaterSerial = $fromNumber;
}
$serialCount = ($toNumber - $fromNumber) + 1;
if ($serialCount != (int) $quantity) {
$invalidSerialCountQuan [] = $fromNumber;
}
$existingOrders = ProductionOrder::where('plant_id', $plantId)
->where('outer_status', '1')
->whereRaw('CAST(from_serial_number AS NUMERIC) <= CAST(? AS NUMERIC)', [$toSerial])
->whereRaw('CAST(to_serial_number AS NUMERIC) >= CAST(? AS NUMERIC)', [$fromSerial])
->get(['from_serial_number', 'to_serial_number']);
$duplicateSerialRanges = [];
foreach ($existingOrders as $order) {
$start = bccomp($fromSerial, $order->from_serial_number) > 0
? $fromSerial
: $order->from_serial_number;
$end = bccomp($toSerial, $order->to_serial_number) < 0
? $toSerial
: $order->to_serial_number;
for ($serial = $start; bccomp($serial, $end) <= 0; $serial = bcadd($serial, '1')) {
$duplicateSerialRanges[] = $serial;
}
}
if (ctype_digit($fromSerial) && ctype_digit($toSerial) && strlen($fromSerial) >= 9 && strlen($toSerial) >= 9 && bccomp($fromSerial, $toSerial) <= 0)
{
foreach ($excelSerialRanges as $range) {
// Check duplicates only for the same plant
if (
$range['plant_code'] == $excelPlantCode &&
bccomp($fromSerial, $range['to']) <= 0 &&
bccomp($toSerial, $range['from']) >= 0
) {
$start = bccomp($fromSerial, $range['from']) > 0
? $fromSerial
: $range['from'];
$end = bccomp($toSerial, $range['to']) < 0
? $toSerial
: $range['to'];
for (
$serial = $start;
bccomp($serial, $end) <= 0;
$serial = bcadd($serial, '1')
) {
$duplicateExcelSerials[] = $serial;
}
}
}
$excelSerialRanges[] = [
'plant_code' => $excelPlantCode,
'from' => $fromSerial,
'to' => $toSerial,
];
}
$productionOrders[] = [
'plant_id' => $plantId,
'item_id' => $itemId,
'quantity' => (int) $quantity,
'production_order' => $productionOrder,
'from_serial_number' => $fromSerial,
'to_serial_number' => $toSerial,
'outer_status' => '1',
'created_at' => now(),
'created_by' => $userName,
'updated_at' => now(),
'updated_by' => $userName,
];
}
$uniquePlantCodes = array_unique($invalidPlantCodes);
$uniqueInvalidCodes = array_unique($invalidMatCodes);
$uniquePOrders = array_unique($invalidPOrder);
$uniqueQuantities = array_unique($invalidQuan);
$uniqueFromSerials = array_unique($invalidFromSerial);
$uniqueToSerials = array_unique($invalidToSerial);
$uniqueGreaterSerials = array_unique($invalidToGreaterSerial);
$uniqueSerialCountErrors = array_unique($invalidSerialCountQuan);
$duplicateSerialRanges = array_unique($duplicateSerialRanges);
$duplicateExcelSerials = array_unique($duplicateExcelSerials);
if (!empty($duplicateExcelSerials)) {
Notification::make()
->title('Duplicate Serial Numbers')
->body('Duplicate serial numbers found within the excel sheet same plant: ' .
implode(', ', $duplicateExcelSerials))
->danger()
->send();
if ($disk->exists($path)) {
$disk->delete($path);
}
return;
}
if (!empty($duplicateSerialRanges)) {
Notification::make()
->title('Duplicate Serial Number Ranges')
->body('Duplicate serial numbers: ' . implode(', ', $duplicateSerialRanges))
->danger()
->send();
if ($disk->exists($path)) {
$disk->delete($path);
}
return;
}
else if (!empty($uniquePlantCodes)) {
Notification::make()
->title('Invalid Plant Codes')
->body('The following plant codes are not found:<br>' . implode(', ', $uniquePlantCodes))
->danger()
->send();
if ($disk->exists($path)) {
$disk->delete($path);
}
return;
} elseif (!empty($uniqueInvalidCodes)) {
Notification::make()
->title('Invalid Item Codes')
->body('The following item codes are not found:<br>' . implode(', ', $uniqueInvalidCodes))
->danger()
->send();
if ($disk->exists($path)) {
$disk->delete($path);
}
return;
} elseif (!empty($uniquePOrders)) {
Notification::make()
->title('Invalid Production Orders')
->body('The following production orders must contain at least 7 digits:<br>' . implode(', ', $uniquePOrders))
->danger()
->send();
if ($disk->exists($path)) {
$disk->delete($path);
}
return;
} elseif (!empty($uniqueQuantities)) {
Notification::make()
->title('Invalid Quantity')
->body('The following quantities must be positive whole numbers:<br>' . implode(', ', $uniqueQuantities))
->danger()
->send();
if ($disk->exists($path)) {
$disk->delete($path);
}
return;
} elseif (!empty($uniqueFromSerials)) {
Notification::make()
->title('Invalid From Serial Number')
->body('The following From Serial Numbers must contain at least 9 alphanumeric characters:<br>' . implode(', ', $uniqueFromSerials))
->danger()
->send();
if ($disk->exists($path)) {
$disk->delete($path);
}
return;
} elseif (!empty($uniqueToSerials)) {
Notification::make()
->title('Invalid To Serial Number')
->body('The following To Serial Numbers must contain at least 9 alphanumeric characters:<br>' . implode(', ', $uniqueToSerials))
->danger()
->send();
if ($disk->exists($path)) {
$disk->delete($path);
}
return;
} elseif (!empty($uniqueGreaterSerials)) {
Notification::make()
->title('Invalid Serial Range')
->body('From Serial Number must be less than or equal to To Serial Number:<br>' . implode(', ', $uniqueGreaterSerials))
->danger()
->send();
if ($disk->exists($path)) {
$disk->delete($path);
}
return;
} elseif (!empty($uniqueSerialCountErrors)) {
Notification::make()
->title('Serial Count Mismatch')
->body('The serial number range does not match the specified quantity:<br>' . implode(', ', $uniqueSerialCountErrors))
->danger()
->send();
if ($disk->exists($path)) {
$disk->delete($path);
}
return;
}
DB::transaction(function () use ($productionOrders) {
DB::table('production_orders')->insert($productionOrders);
});
Notification::make()
->title('Production Orders Imported Successfully')
->body("External Serial Number production orders imported successfully.")
->success()
->persistent()
->send();
} finally {
if ($disk->exists($path)) {
$disk->delete($path);
}
}
})
->visible(function () {
return Filament::auth()->user()->can('view import external serial number');
}),
ImportAction::make()
->label('Import Production Orders')
->color('warning')