ranjith-dev #187

Merged
jothi merged 54 commits from ranjith-dev into master 2026-01-14 06:37:24 +00:00
75 changed files with 6222 additions and 5858 deletions

View File

@@ -24,17 +24,18 @@ class BlockExporter extends Exporter
// Increment and return the row number // Increment and return the row number
return ++$rowNumber; return ++$rowNumber;
}), }),
ExportColumn::make('plant.name') ExportColumn::make('plant.code')
->label('PLANT'), ->label('PLANT CODE'),
ExportColumn::make('name') ExportColumn::make('name')
->label('NAME'), ->label('BLOCK NAME'),
ExportColumn::make('created_at') ExportColumn::make('created_at')
->label('CREATED AT'), ->label('CREATED AT'),
ExportColumn::make('updated_at') ExportColumn::make('updated_at')
->label('UPDATED AT'), ->label('UPDATED AT')
->enabledByDefault(true),
ExportColumn::make('deleted_at') ExportColumn::make('deleted_at')
->enabledByDefault(false) ->label('DELETED AT')
->label('DELETED AT'), ->enabledByDefault(false),
]; ];
} }

View File

@@ -14,6 +14,7 @@ class CharacteristicValueExporter extends Exporter
public static function getColumns(): array public static function getColumns(): array
{ {
static $rowNumber = 0; static $rowNumber = 0;
return [ return [
ExportColumn::make('no') ExportColumn::make('no')
->label('NO') ->label('NO')

View File

@@ -24,8 +24,8 @@ class CheckPointNameExporter extends Exporter
// Increment and return the row number // Increment and return the row number
return ++$rowNumber; return ++$rowNumber;
}), }),
ExportColumn::make('plant.name') ExportColumn::make('plant.code')
->label('PLANT'), ->label('PLANT CODE'),
ExportColumn::make('name') ExportColumn::make('name')
->label('CHECK POINT NAME'), ->label('CHECK POINT NAME'),
ExportColumn::make('created_at') ExportColumn::make('created_at')

View File

@@ -24,8 +24,8 @@ class CheckPointTimeExporter extends Exporter
// Increment and return the row number // Increment and return the row number
return ++$rowNumber; return ++$rowNumber;
}), }),
ExportColumn::make('plant.name') ExportColumn::make('plant.code')
->label('PLANT'), ->label('PLANT CODE'),
ExportColumn::make('checkPointNames1.name') ExportColumn::make('checkPointNames1.name')
->label('CHECK POINT 1'), ->label('CHECK POINT 1'),
ExportColumn::make('checkPointNames2.name') ExportColumn::make('checkPointNames2.name')

View File

@@ -14,6 +14,7 @@ class DeviceMasterExporter extends Exporter
public static function getColumns(): array public static function getColumns(): array
{ {
static $rowNumber = 0; static $rowNumber = 0;
return [ return [
ExportColumn::make('no') ExportColumn::make('no')
->label('NO') ->label('NO')
@@ -21,8 +22,8 @@ class DeviceMasterExporter extends Exporter
// Increment and return the row number // Increment and return the row number
return ++$rowNumber; return ++$rowNumber;
}), }),
ExportColumn::make('plant.name') ExportColumn::make('plant.code')
->label('PLANT'), ->label('PLANT CODE'),
ExportColumn::make('name') ExportColumn::make('name')
->label('DEVICE NAME'), ->label('DEVICE NAME'),
ExportColumn::make('mac_address') ExportColumn::make('mac_address')

View File

@@ -10,7 +10,9 @@ use Filament\Actions\Exports\Models\Export;
class EbReadingExporter extends Exporter class EbReadingExporter extends Exporter
{ {
protected static ?string $model = EbReading::class; protected static ?string $model = EbReading::class;
static $rowNumber = 0;
public static $rowNumber = 0;
public static function getColumns(): array public static function getColumns(): array
{ {
return [ return [
@@ -20,8 +22,8 @@ class EbReadingExporter extends Exporter
// Increment and return the row number // Increment and return the row number
return ++$rowNumber; return ++$rowNumber;
}), }),
ExportColumn::make('plant.name') ExportColumn::make('plant.code')
->label('PLANT'), ->label('PLANT CODE'),
ExportColumn::make('lcd_segment_check') ExportColumn::make('lcd_segment_check')
->label('LCD SEGMENT CHECK'), ->label('LCD SEGMENT CHECK'),
ExportColumn::make('meter_serial_no') ExportColumn::make('meter_serial_no')

View File

@@ -14,6 +14,7 @@ class EquipmentMasterExporter extends Exporter
public static function getColumns(): array public static function getColumns(): array
{ {
static $rowNumber = 0; static $rowNumber = 0;
return [ return [
ExportColumn::make('no') ExportColumn::make('no')
->label('NO') ->label('NO')
@@ -21,8 +22,8 @@ class EquipmentMasterExporter extends Exporter
// Increment and return the row number // Increment and return the row number
return ++$rowNumber; return ++$rowNumber;
}), }),
ExportColumn::make('plant.name') ExportColumn::make('plant.code')
->label('PLANT'), ->label('PLANT CODE'),
ExportColumn::make('machine.name') ExportColumn::make('machine.name')
->label('MACHINE NAME'), ->label('MACHINE NAME'),
ExportColumn::make('name') ExportColumn::make('name')

View File

@@ -14,6 +14,7 @@ class GrMasterExporter extends Exporter
public static function getColumns(): array public static function getColumns(): array
{ {
static $rowNumber = 0; static $rowNumber = 0;
return [ return [
ExportColumn::make('no') ExportColumn::make('no')
->label('NO') ->label('NO')
@@ -21,10 +22,10 @@ class GrMasterExporter extends Exporter
// Increment and return the row number // Increment and return the row number
return ++$rowNumber; return ++$rowNumber;
}), }),
ExportColumn::make('plant.name') ExportColumn::make('plant.code')
->label('PLANT'), ->label('PLANT CODE'),
ExportColumn::make('item.code') ExportColumn::make('item.code')
->label('ITEM'), ->label('ITEM CODE'),
ExportColumn::make('serial_number') ExportColumn::make('serial_number')
->label('SERIAL NUMBER'), ->label('SERIAL NUMBER'),
ExportColumn::make('gr_number') ExportColumn::make('gr_number')

View File

@@ -24,8 +24,8 @@ class GuardNameExporter extends Exporter
// Increment and return the row number // Increment and return the row number
return ++$rowNumber; return ++$rowNumber;
}), }),
ExportColumn::make('plant.name') ExportColumn::make('plant.code')
->label('PLANT'), ->label('PLANT CODE'),
ExportColumn::make('name') ExportColumn::make('name')
->label('GUARD NAME'), ->label('GUARD NAME'),
ExportColumn::make('identification1') ExportColumn::make('identification1')

View File

@@ -24,8 +24,8 @@ class GuardPatrolEntryExporter extends Exporter
}), }),
// ExportColumn::make('id') // ExportColumn::make('id')
// ->label('ID'), // ->label('ID'),
ExportColumn::make('plant.name') ExportColumn::make('plant.code')
->label('PLANT'), ->label('PLANT CODE'),
ExportColumn::make('guardNames.name') ExportColumn::make('guardNames.name')
->label('GUARD NAME'), ->label('GUARD NAME'),
ExportColumn::make('checkPointNames.name') ExportColumn::make('checkPointNames.name')

View File

@@ -24,12 +24,12 @@ class LineExporter extends Exporter
// Increment and return the row number // Increment and return the row number
return ++$rowNumber; return ++$rowNumber;
}), }),
ExportColumn::make('plant.name') ExportColumn::make('plant.code')
->label('PLANT'), ->label('PLANT CODE'),
ExportColumn::make('name') ExportColumn::make('name')
->label('NAME'), ->label('LINE NAME'),
ExportColumn::make('type') ExportColumn::make('type')
->label('TYPE'), ->label('LINE TYPE'),
ExportColumn::make('no_of_operation') ExportColumn::make('no_of_operation')
->label('NO OF OPERATION'), ->label('NO OF OPERATION'),
ExportColumn::make('workGroup1.name') ExportColumn::make('workGroup1.name')

View File

@@ -22,12 +22,12 @@ class MachineExporter extends Exporter
// Increment and return the row number // Increment and return the row number
return ++$rowNumber; return ++$rowNumber;
}), }),
ExportColumn::make('plant.name') ExportColumn::make('plant.code')
->label('PLANT'), ->label('PLANT CODE'),
ExportColumn::make('line.name') ExportColumn::make('line.name')
->label('LINE'), ->label('LINE NAME'),
ExportColumn::make('name') ExportColumn::make('name')
->label('MACHINE'), ->label('MACHINE NAME'),
ExportColumn::make('work_center') ExportColumn::make('work_center')
->label('WORK CENTER'), ->label('WORK CENTER'),
ExportColumn::make('workGroupMaster.name') ExportColumn::make('workGroupMaster.name')

View File

@@ -14,6 +14,7 @@ class MfmMeterExporter extends Exporter
public static function getColumns(): array public static function getColumns(): array
{ {
static $rowNumber = 0; static $rowNumber = 0;
return [ return [
ExportColumn::make('no') ExportColumn::make('no')
->label('NO') ->label('NO')
@@ -21,14 +22,14 @@ class MfmMeterExporter extends Exporter
// Increment and return the row number // Increment and return the row number
return ++$rowNumber; return ++$rowNumber;
}), }),
ExportColumn::make('plant.name') ExportColumn::make('plant.code')
->label('PLANT'), ->label('PLANT CODE'),
ExportColumn::make('device.name') ExportColumn::make('device.name')
->label('DEVICE NAME'), ->label('DEVICE NAME'),
ExportColumn::make('sequence') ExportColumn::make('sequence')
->label('SEQUENCE'), ->label('SEQUENCE'),
ExportColumn::make('name') ExportColumn::make('name')
->label('NAME'), ->label('METER NAME'),
ExportColumn::make('created_at') ExportColumn::make('created_at')
->label('CREATED AT'), ->label('CREATED AT'),
ExportColumn::make('updated_at') ExportColumn::make('updated_at')

View File

@@ -14,6 +14,7 @@ class MfmParameterExporter extends Exporter
public static function getColumns(): array public static function getColumns(): array
{ {
static $rowNumber = 0; static $rowNumber = 0;
return [ return [
ExportColumn::make('no') ExportColumn::make('no')
->label('NO') ->label('NO')
@@ -21,12 +22,12 @@ class MfmParameterExporter extends Exporter
// Increment and return the row number // Increment and return the row number
return ++$rowNumber; return ++$rowNumber;
}), }),
ExportColumn::make('plant.name') ExportColumn::make('plant.code')
->label('PLANT'), ->label('PLANT CODE'),
ExportColumn::make('deviceName.name') ExportColumn::make('deviceName.name')
->label('Device Name'), ->label('Device Name'),
ExportColumn::make('name') ExportColumn::make('name')
->label('NAME'), ->label('PARAMETER NAME'),
ExportColumn::make('mfmMeter.name') ExportColumn::make('mfmMeter.name')
->label('MFM METER'), ->label('MFM METER'),
ExportColumn::make('register_id') ExportColumn::make('register_id')

View File

@@ -23,7 +23,7 @@ class MotorTestingMasterExporter extends Exporter
return ++$rowNumber; return ++$rowNumber;
}), }),
ExportColumn::make('plant.code') ExportColumn::make('plant.code')
->label('PLANT'), ->label('PLANT CODE'),
ExportColumn::make('item.category') ExportColumn::make('item.category')
->label('CATEGORY'), ->label('CATEGORY'),
ExportColumn::make('item.code') ExportColumn::make('item.code')

View File

@@ -37,13 +37,13 @@ class ProductionLineStopExporter extends Exporter
ExportColumn::make('stop_min') ExportColumn::make('stop_min')
->label('STOP MINUTE'), ->label('STOP MINUTE'),
ExportColumn::make('line.name') ExportColumn::make('line.name')
->label('LINE'), ->label('LINE NAME'),
ExportColumn::make('shift.block.name') ExportColumn::make('shift.block.name')
->label('BLOCK'), ->label('BLOCK NAME'),
ExportColumn::make('shift.name') ExportColumn::make('shift.name')
->label('SHIFT'), ->label('SHIFT NAME'),
ExportColumn::make('plant.name') ExportColumn::make('plant.code')
->label('PLANT'), ->label('PLANT CODE'),
ExportColumn::make('operator_id') ExportColumn::make('operator_id')
->label('OPERATOR ID'), ->label('OPERATOR ID'),
ExportColumn::make('created_at') ExportColumn::make('created_at')

View File

@@ -29,13 +29,13 @@ class ProductionPlanExporter extends Exporter
ExportColumn::make('production_quantity') ExportColumn::make('production_quantity')
->label('PRODUCTION QUANTITY'), ->label('PRODUCTION QUANTITY'),
ExportColumn::make('line.name') ExportColumn::make('line.name')
->label('LINE'), ->label('LINE NAME'),
ExportColumn::make('shift.block.name') ExportColumn::make('shift.block.name')
->label('BLOCK'), ->label('BLOCK NAME'),
ExportColumn::make('shift.name') ExportColumn::make('shift.name')
->label('SHIFT'), ->label('SHIFT NAME'),
ExportColumn::make('plant.name') ExportColumn::make('plant.code')
->label('PLANT'), ->label('PLANT CODE'),
ExportColumn::make('operator_id') ExportColumn::make('operator_id')
->label('OPERATOR ID'), ->label('OPERATOR ID'),
ExportColumn::make('created_at') ExportColumn::make('created_at')

View File

@@ -33,13 +33,13 @@ class ProductionQuantityExporter extends Exporter
ExportColumn::make('item.uom') ExportColumn::make('item.uom')
->label('UNIT OF MEASURE'), ->label('UNIT OF MEASURE'),
ExportColumn::make('line.name') ExportColumn::make('line.name')
->label('LINE'), ->label('LINE NAME'),
ExportColumn::make('shift.block.name') ExportColumn::make('shift.block.name')
->label('BLOCK'), ->label('BLOCK NAME'),
ExportColumn::make('shift.name') ExportColumn::make('shift.name')
->label('SHIFT'), ->label('SHIFT NAME'),
ExportColumn::make('plant.name') ExportColumn::make('plant.code')
->label('PLANT'), ->label('PLANT CODE'),
ExportColumn::make('sap_msg_status') ExportColumn::make('sap_msg_status')
->label('SAP MESSAGE STATUS'), ->label('SAP MESSAGE STATUS'),
ExportColumn::make('sap_msg_description') ExportColumn::make('sap_msg_description')

View File

@@ -24,10 +24,10 @@ class QualityValidationExporter extends Exporter
// Increment and return the row number // Increment and return the row number
return ++$rowNumber; return ++$rowNumber;
}), }),
ExportColumn::make('plant.name') ExportColumn::make('plant.code')
->label('PLANT'), ->label('PLANT CODE'),
ExportColumn::make('line.name') ExportColumn::make('line.name')
->label('LINE'), ->label('LINE NAME'),
ExportColumn::make('production_order') ExportColumn::make('production_order')
->label('PRODUCTION ORDER'), ->label('PRODUCTION ORDER'),
ExportColumn::make('serial_number') ExportColumn::make('serial_number')
@@ -54,14 +54,14 @@ class QualityValidationExporter extends Exporter
->label('NAME PLATE PUMP'), ->label('NAME PLATE PUMP'),
ExportColumn::make('name_plate_pumpset') ExportColumn::make('name_plate_pumpset')
->label('NAME PLATE PUMPSET'), ->label('NAME PLATE PUMPSET'),
ExportColumn::make('warranty_card')
->label('WARRANTY CARD'),
ExportColumn::make('tube_sticker_motor') ExportColumn::make('tube_sticker_motor')
->label('TUBE STICKER MOTOR'), ->label('TUBE STICKER MOTOR'),
ExportColumn::make('tube_sticker_pump') ExportColumn::make('tube_sticker_pump')
->label('TUBE STICKER PUMP'), ->label('TUBE STICKER PUMP'),
ExportColumn::make('tube_sticker_pumpset') ExportColumn::make('tube_sticker_pumpset')
->label('TUBE STICKER PUMPSET'), ->label('TUBE STICKER PUMPSET'),
ExportColumn::make('warranty_card')
->label('WARRANTY CARD'),
ExportColumn::make('part_validation1') ExportColumn::make('part_validation1')
->label('PART VALIDATION 1'), ->label('PART VALIDATION 1'),
ExportColumn::make('part_validation2') ExportColumn::make('part_validation2')

View File

@@ -14,6 +14,7 @@ class SerialValidationExporter extends Exporter
public static function getColumns(): array public static function getColumns(): array
{ {
static $rowNumber = 0; static $rowNumber = 0;
return [ return [
ExportColumn::make('no') ExportColumn::make('no')
->label('NO') ->label('NO')
@@ -21,8 +22,8 @@ class SerialValidationExporter extends Exporter
// Increment and return the row number // Increment and return the row number
return ++$rowNumber; return ++$rowNumber;
}), }),
ExportColumn::make('plant.name') ExportColumn::make('plant.code')
->label('PLANT'), ->label('PLANT CODE'),
ExportColumn::make('invoice_number') ExportColumn::make('invoice_number')
->label('INVOICE NUMBER'), ->label('INVOICE NUMBER'),
ExportColumn::make('serial_number') ExportColumn::make('serial_number')

View File

@@ -25,11 +25,11 @@ class ShiftExporter extends Exporter
return ++$rowNumber; return ++$rowNumber;
}), }),
ExportColumn::make('block.name') ExportColumn::make('block.name')
->label('BLOCK'), ->label('BLOCK NAME'),
ExportColumn::make('plant.name') ExportColumn::make('plant.code')
->label('PLANT'), ->label('PLANT CODE'),
ExportColumn::make('name') ExportColumn::make('name')
->label('NAME'), ->label('SHIFT NAME'),
ExportColumn::make('start_time') ExportColumn::make('start_time')
->label('START TIME'), ->label('START TIME'),
ExportColumn::make('duration') ExportColumn::make('duration')

View File

@@ -24,18 +24,18 @@ class TestingPanelReadingExporter extends Exporter
// Increment and return the row number // Increment and return the row number
return ++$rowNumber; return ++$rowNumber;
}), }),
ExportColumn::make('plant.name') ExportColumn::make('plant.code')
->label('PLANT'), ->label('PLANT CODE'),
ExportColumn::make('line.name') ExportColumn::make('line.name')
->label('LINE'), ->label('LINE NAME'),
ExportColumn::make('machine.name') ExportColumn::make('machine.name')
->label('MACHINE'), ->label('MACHINE NAME'),
ExportColumn::make('motorTestingMaster.item.code') ExportColumn::make('motorTestingMaster.item.code')
->label('ITEM CODE'), ->label('ITEM CODE'),
ExportColumn::make('motorTestingMaster.item.description') ExportColumn::make('motorTestingMaster.item.description')
->label('MODEL'), ->label('MODEL DESCRIPTION'),
ExportColumn::make('output') ExportColumn::make('output')
->label('OUTPUT'), ->label('OUTPUT NAME'),
ExportColumn::make('serial_number') ExportColumn::make('serial_number')
->label('SERIAL NUMBER'), ->label('SERIAL NUMBER'),
ExportColumn::make('winded_serial_number') ExportColumn::make('winded_serial_number')
@@ -125,7 +125,7 @@ class TestingPanelReadingExporter extends Exporter
ExportColumn::make('rework_count') ExportColumn::make('rework_count')
->label('REWORK COUNT'), ->label('REWORK COUNT'),
ExportColumn::make('update_count') ExportColumn::make('update_count')
->label('UPDATE COUNT'), ->label('UPDATED COUNT'),
ExportColumn::make('output_flag') ExportColumn::make('output_flag')
->label('OUTPUT FLAG'), ->label('OUTPUT FLAG'),
ExportColumn::make('tested_by') ExportColumn::make('tested_by')

View File

@@ -24,8 +24,8 @@ class WeightValidationExporter extends Exporter
// Increment and return the row number // Increment and return the row number
return ++$rowNumber; return ++$rowNumber;
}), }),
ExportColumn::make('plant.name') ExportColumn::make('plant.code')
->label('PLANT'), ->label('PLANT CODE'),
ExportColumn::make('item.code') ExportColumn::make('item.code')
->label('ITEM CODE'), ->label('ITEM CODE'),
ExportColumn::make('obd_number') ExportColumn::make('obd_number')

View File

@@ -14,6 +14,7 @@ class WorkGroupMasterExporter extends Exporter
public static function getColumns(): array public static function getColumns(): array
{ {
static $rowNumber = 0; static $rowNumber = 0;
return [ return [
ExportColumn::make('no') ExportColumn::make('no')
->label('NO') ->label('NO')
@@ -21,12 +22,12 @@ class WorkGroupMasterExporter extends Exporter
// Increment and return the row number // Increment and return the row number
return ++$rowNumber; return ++$rowNumber;
}), }),
ExportColumn::make('plant.name') ExportColumn::make('plant.code')
->label('PLANT'), ->label('PLANT CODE'),
ExportColumn::make('name') ExportColumn::make('name')
->label('NAME'), ->label('WORK GROUP NAME'),
ExportColumn::make('description') ExportColumn::make('description')
->label('DESCRIPTION'), ->label('WORK GROUP DESCRIPTION'),
ExportColumn::make('operation_number') ExportColumn::make('operation_number')
->label('OPERATION NUMBER'), ->label('OPERATION NUMBER'),
ExportColumn::make('created_by') ExportColumn::make('created_by')

View File

@@ -8,7 +8,6 @@ use Filament\Actions\Imports\Exceptions\RowImportFailedException;
use Filament\Actions\Imports\ImportColumn; use Filament\Actions\Imports\ImportColumn;
use Filament\Actions\Imports\Importer; use Filament\Actions\Imports\Importer;
use Filament\Actions\Imports\Models\Import; use Filament\Actions\Imports\Models\Import;
use Notification;
use Str; use Str;
class BlockImporter extends Importer class BlockImporter extends Importer
@@ -20,16 +19,16 @@ class BlockImporter extends Importer
return [ return [
ImportColumn::make('name') ImportColumn::make('name')
->requiredMapping() ->requiredMapping()
->exampleHeader('Block Name') ->exampleHeader('BLOCK NAME')
->example('Block A') ->example('Block A')
->label('Block Name') ->label('BLOCK NAME')
->rules(['required']), ->rules(['required']),
ImportColumn::make('plant') ImportColumn::make('plant')
->requiredMapping() ->requiredMapping()
->exampleHeader('Plant Name') ->exampleHeader('PLANT CODE')
->example('Ransar Industries-I') ->example('1000')
->label('Plant Name') ->label('PLANT CODE')
->relationship(resolveUsing:'name') ->relationship(resolveUsing: 'code')
->rules(['required']), ->rules(['required']),
]; ];
} }
@@ -37,21 +36,28 @@ class BlockImporter extends Importer
public function resolveRecord(): ?Block public function resolveRecord(): ?Block
{ {
$warnMsg = []; $warnMsg = [];
$plant = Plant::where('name', $this->data['plant'])->first(); $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) { if (! $plant) {
$warnMsg[] = "Plant not found"; $warnMsg[] = 'Plant not found';
// $warnMsg[] = "Plant '" . $this->data['plant'] . "' not found"; // $warnMsg[] = "Plant '" . $plantCod . "' not found";
}
} }
if (Str::length($this->data['name']) < 0) { if (Str::length($this->data['name']) < 0) {
$warnMsg[] = "Block name not found"; $warnMsg[] = 'Block name not found';
} }
if (! empty($warnMsg)) { if (! empty($warnMsg)) {
throw new RowImportFailedException(implode(', ', $warnMsg)); throw new RowImportFailedException(implode(', ', $warnMsg));
} }
return Block::updateOrCreate([ return Block::updateOrCreate([
'name' => $this->data['name'], 'name' => $this->data['name'],
'plant_id' => $plant->id 'plant_id' => $plant->id,
]); ]);
// return Block::firstOrNew([ // return Block::firstOrNew([
// // Update existing records, matching them by `$this->data['column_name']` // // Update existing records, matching them by `$this->data['column_name']`

View File

@@ -20,10 +20,10 @@ class CheckPointNameImporter extends Importer
return [ return [
ImportColumn::make('plant') ImportColumn::make('plant')
->requiredMapping() ->requiredMapping()
->exampleHeader('Plant Name') ->exampleHeader('Plant Code')
->example('Ransar Industries-I') ->example('1000')
->label('Plant Name') ->label('Plant Code')
->relationship(resolveUsing: 'name') ->relationship(resolveUsing: 'code')
->rules(['required']), ->rules(['required']),
ImportColumn::make('name') ImportColumn::make('name')
->requiredMapping() ->requiredMapping()
@@ -43,16 +43,22 @@ class CheckPointNameImporter extends Importer
public function resolveRecord(): ?CheckPointName public function resolveRecord(): ?CheckPointName
{ {
$warnMsg = []; $warnMsg = [];
$plant = Plant::where('name', $this->data['plant'])->first(); $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) { if (! $plant) {
$warnMsg[] = "Plant not found"; // '" . $this->data['plant'] . "' $warnMsg[] = 'Plant not found'; // '" . $plantCod . "'
}
} }
if (Str::length($this->data['name']) < 3) { // || !ctype_alnum($this->data['name']) if (Str::length($this->data['name']) < 3) { // || !ctype_alnum($this->data['name'])
$warnMsg[] = "Invalid check point name found"; $warnMsg[] = 'Invalid check point name found';
} }
$createdBy = $this->data['created_by']; $createdBy = $this->data['created_by'];
if (Str::length($createdBy) < 3) { // || !ctype_alnum($createdBy) if (Str::length($createdBy) < 3) { // || !ctype_alnum($createdBy)
$warnMsg[] = "Invalid created by name found"; $warnMsg[] = 'Invalid created by name found';
} }
if (! empty($warnMsg)) { if (! empty($warnMsg)) {
throw new RowImportFailedException(implode(', ', $warnMsg)); throw new RowImportFailedException(implode(', ', $warnMsg));
@@ -60,10 +66,10 @@ class CheckPointNameImporter extends Importer
return CheckPointName::updateOrCreate([ return CheckPointName::updateOrCreate([
'name' => $this->data['name'], 'name' => $this->data['name'],
'plant_id' => $plant->id 'plant_id' => $plant->id,
], ],
[ [
'created_by' => $this->data['created_by'] 'created_by' => $this->data['created_by'],
] ]
); );
// // return CheckPointName::firstOrNew([ // // return CheckPointName::firstOrNew([

View File

@@ -21,10 +21,10 @@ class CheckPointTimeImporter extends Importer
return [ return [
ImportColumn::make('plant') ImportColumn::make('plant')
->requiredMapping() ->requiredMapping()
->exampleHeader('Plant Name') ->exampleHeader('Plant Code')
->example('Ransar Industries-I') ->example('1000')
->label('Plant Name') ->label('Plant Code')
->relationship(resolveUsing: 'name') ->relationship(resolveUsing: 'code')
->rules(['required']), ->rules(['required']),
ImportColumn::make('checkPointNames1') ImportColumn::make('checkPointNames1')
->requiredMapping() ->requiredMapping()
@@ -73,49 +73,50 @@ class CheckPointTimeImporter extends Importer
public function resolveRecord(): ?CheckPointTime public function resolveRecord(): ?CheckPointTime
{ {
$warnMsg = []; $warnMsg = [];
$plant = Plant::where('name', $this->data['plant'])->first(); $plantCod = $this->data['plant'];
$plant = null;
$checkPointNames1 = null; $checkPointNames1 = null;
$checkPointNames2 = null; $checkPointNames2 = 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) { if (! $plant) {
$warnMsg[] = "Plant not found"; // '" . $this->data['plant'] . "' $warnMsg[] = 'Plant not found'; // '" . $plantCod . "'
} } else {
else
{
$checkPointNames1 = CheckPointName::where('name', $this->data['checkPointNames1'])->first(); $checkPointNames1 = CheckPointName::where('name', $this->data['checkPointNames1'])->first();
if (! $checkPointNames1) { if (! $checkPointNames1) {
$warnMsg[] = "Check point 1 not found"; $warnMsg[] = 'Check point 1 not found';
} } else {
else
{
$checkPointNames2 = CheckPointName::where('name', $this->data['checkPointNames2'])->first(); $checkPointNames2 = CheckPointName::where('name', $this->data['checkPointNames2'])->first();
if (! $checkPointNames2) { if (! $checkPointNames2) {
$warnMsg[] = "Check point 2 not found"; $warnMsg[] = 'Check point 2 not found';
} } else {
else
{
if ($checkPointNames1->id === $checkPointNames2->id) { if ($checkPointNames1->id === $checkPointNames2->id) {
$warnMsg[] = "Check point 1 and 2 can't be the same"; $warnMsg[] = "Check point 1 and 2 can't be the same";
} }
} }
} }
} }
}
if (Str::length($this->data['sequence_number']) < 1 || ! is_numeric($this->data['sequence_number']) || $this->data['sequence_number'] <= 0) { if (Str::length($this->data['sequence_number']) < 1 || ! is_numeric($this->data['sequence_number']) || $this->data['sequence_number'] <= 0) {
$warnMsg[] = "Invalid sequence number found"; $warnMsg[] = 'Invalid sequence number found';
} }
if (Str::length($this->data['time_lapse']) < 1 || ! is_numeric($this->data['time_lapse']) || $this->data['time_lapse'] <= 0) { if (Str::length($this->data['time_lapse']) < 1 || ! is_numeric($this->data['time_lapse']) || $this->data['time_lapse'] <= 0) {
$warnMsg[] = "Invalid time lapse found"; $warnMsg[] = 'Invalid time lapse found';
} }
if (Str::length($this->data['time_lapse_cushioning']) < 1 || ! is_numeric($this->data['time_lapse_cushioning']) || $this->data['time_lapse_cushioning'] <= 0) { if (Str::length($this->data['time_lapse_cushioning']) < 1 || ! is_numeric($this->data['time_lapse_cushioning']) || $this->data['time_lapse_cushioning'] <= 0) {
$warnMsg[] = "Invalid time lapse cushioning found"; $warnMsg[] = 'Invalid time lapse cushioning found';
} }
$createdBy = $this->data['created_by']; $createdBy = $this->data['created_by'];
if (Str::length($createdBy) < 3) { // || !ctype_alnum($createdBy) if (Str::length($createdBy) < 3) { // || !ctype_alnum($createdBy)
$warnMsg[] = "Invalid created by name found"; $warnMsg[] = 'Invalid created by name found';
} }
if (! empty($warnMsg)) { if (! empty($warnMsg)) {
throw new RowImportFailedException(implode(', ', $warnMsg)); throw new RowImportFailedException(implode(', ', $warnMsg));
} }
@@ -124,12 +125,12 @@ class CheckPointTimeImporter extends Importer
'plant_id' => $plant->id, 'plant_id' => $plant->id,
'check_point1_id' => $checkPointNames1->id, 'check_point1_id' => $checkPointNames1->id,
'check_point2_id' => $checkPointNames2->id, 'check_point2_id' => $checkPointNames2->id,
'sequence_number' => $this->data['sequence_number'] 'sequence_number' => $this->data['sequence_number'],
], ],
[ [
'time_lapse' => $this->data['time_lapse'], 'time_lapse' => $this->data['time_lapse'],
'time_lapse_cushioning' => $this->data['time_lapse_cushioning'], 'time_lapse_cushioning' => $this->data['time_lapse_cushioning'],
'created_by' => $this->data['created_by'] 'created_by' => $this->data['created_by'],
] ]
); );
// // return CheckPointTime::firstOrNew([ // // return CheckPointTime::firstOrNew([

View File

@@ -62,7 +62,7 @@ class ConfigurationImporter extends Importer
// 'email' => $this->data['email'], // 'email' => $this->data['email'],
// ]); // ]);
return new Configuration(); return new Configuration;
} }
public static function getCompletedNotificationBody(Import $import): string public static function getCompletedNotificationBody(Import $import): string

View File

@@ -16,10 +16,10 @@ class DeviceMasterImporter extends Importer
return [ return [
ImportColumn::make('plant') ImportColumn::make('plant')
->requiredMapping() ->requiredMapping()
->exampleHeader('Plant Name') ->exampleHeader('Plant Code')
->example('Ransar Industries-I') ->example('1000')
->label('Plant Name') ->label('Plant Code')
->relationship(resolveUsing:'name') ->relationship(resolveUsing: 'code')
->rules(['required']), ->rules(['required']),
ImportColumn::make('name') ImportColumn::make('name')
->requiredMapping() ->requiredMapping()
@@ -53,7 +53,7 @@ class DeviceMasterImporter extends Importer
// 'email' => $this->data['email'], // 'email' => $this->data['email'],
// ]); // ]);
return new DeviceMaster(); return new DeviceMaster;
} }
public static function getCompletedNotificationBody(Import $import): string public static function getCompletedNotificationBody(Import $import): string

View File

@@ -16,10 +16,10 @@ class EbReadingImporter extends Importer
return [ return [
ImportColumn::make('plant') ImportColumn::make('plant')
->requiredMapping() ->requiredMapping()
->exampleHeader('Plant Name') ->exampleHeader('Plant Code')
->example('Ransar Industries-I') ->example('1000')
->label('Plant Name') ->label('Plant Code')
->relationship(resolveUsing:'name') ->relationship(resolveUsing: 'code')
->rules(['required']), ->rules(['required']),
ImportColumn::make('lcd_segment_check') ImportColumn::make('lcd_segment_check')
->label('LCD Segment Check') ->label('LCD Segment Check')
@@ -227,7 +227,7 @@ class EbReadingImporter extends Importer
// 'email' => $this->data['email'], // 'email' => $this->data['email'],
// ]); // ]);
return new EbReading(); return new EbReading;
} }
public static function getCompletedNotificationBody(Import $import): string public static function getCompletedNotificationBody(Import $import): string

View File

@@ -16,10 +16,10 @@ class EquipmentMasterImporter extends Importer
return [ return [
ImportColumn::make('plant') ImportColumn::make('plant')
->requiredMapping() ->requiredMapping()
->exampleHeader('Plant Name') ->exampleHeader('Plant Code')
->example('Ransar Industries-I') ->example('1000')
->label('Plant Name') ->label('Plant Code')
->relationship(resolveUsing:'name') ->relationship(resolveUsing: 'code')
->rules(['required']), ->rules(['required']),
ImportColumn::make('machine') ImportColumn::make('machine')
->requiredMapping() ->requiredMapping()
@@ -93,7 +93,7 @@ class EquipmentMasterImporter extends Importer
// 'email' => $this->data['email'], // 'email' => $this->data['email'],
// ]); // ]);
return new EquipmentMaster(); return new EquipmentMaster;
} }
public static function getCompletedNotificationBody(Import $import): string public static function getCompletedNotificationBody(Import $import): string

View File

@@ -3,14 +3,14 @@
namespace App\Filament\Imports; namespace App\Filament\Imports;
use App\Models\GrMaster; use App\Models\GrMaster;
use App\Models\Item;
use App\Models\Plant;
use App\Models\User;
use Filament\Actions\Imports\Exceptions\RowImportFailedException;
use Filament\Actions\Imports\ImportColumn; use Filament\Actions\Imports\ImportColumn;
use Filament\Actions\Imports\Importer; use Filament\Actions\Imports\Importer;
use Filament\Actions\Imports\Models\Import; use Filament\Actions\Imports\Models\Import;
use App\Models\Plant;
use App\Models\Item;
use Str; use Str;
use Filament\Actions\Imports\Exceptions\RowImportFailedException;
use App\Models\User;
class GrMasterImporter extends Importer class GrMasterImporter extends Importer
{ {
@@ -21,10 +21,10 @@ class GrMasterImporter extends Importer
return [ return [
ImportColumn::make('plant') ImportColumn::make('plant')
->requiredMapping() ->requiredMapping()
->exampleHeader('Plant Name') ->exampleHeader('Plant Code')
->example('Ransar Industries-I') ->example('1000')
->label('Plant Name') ->label('Plant Code')
->relationship(resolveUsing:'name') ->relationship(resolveUsing: 'code')
->rules(['required']), ->rules(['required']),
ImportColumn::make('item') ImportColumn::make('item')
->requiredMapping() ->requiredMapping()
@@ -63,44 +63,47 @@ class GrMasterImporter extends Importer
// ]); // ]);
$warnMsg = []; $warnMsg = [];
$plantCod = $this->data['plant'];
$plant = Plant::where('name', $this->data['plant'])->first(); $plant = null;
if (!$plant) {
$warnMsg[] = "Plant not found";
}
$item = null; $item = null;
if ($plant) {
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';
} else {
$item = Item::where('code', $this->data['item'])->where('plant_id', $plant->id)->first(); $item = Item::where('code', $this->data['item'])->where('plant_id', $plant->id)->first();
} }
if (! $item) { if (! $item) {
$warnMsg[] = "Item not found"; $warnMsg[] = 'Item not found';
} }
}
if (Str::length($this->data['serial_number']) < 9 || ! ctype_alnum($this->data['serial_number'])) { if (Str::length($this->data['serial_number']) < 9 || ! ctype_alnum($this->data['serial_number'])) {
$warnMsg[] = "Invalid serial number found"; $warnMsg[] = 'Invalid serial number found';
} }
if (empty($this->data['gr_number'])) { if (empty($this->data['gr_number'])) {
$warnMsg[] = "GR Number cannot be empty."; $warnMsg[] = 'GR Number cannot be empty.';
} }
$user = User::where('name', $this->data['created_by'])->first(); $user = User::where('name', $this->data['created_by'])->first();
if (! $user) { if (! $user) {
$warnMsg[] = "User not found"; $warnMsg[] = 'User not found';
} }
if (! empty($warnMsg)) { if (! empty($warnMsg)) {
throw new RowImportFailedException(implode(', ', $warnMsg)); throw new RowImportFailedException(implode(', ', $warnMsg));
} } else { // if (empty($warnMsg))
else { //if (empty($warnMsg))
$grMaster = GrMaster::where('plant_id', $plant->id) $grMaster = GrMaster::where('plant_id', $plant->id)
->where('serial_number', $this->data['serial_number']) ->where('serial_number', $this->data['serial_number'])
->latest() ->latest()
->first(); ->first();
if ($grMaster) { if ($grMaster) {
throw new RowImportFailedException("Serial number already exist!"); throw new RowImportFailedException('Serial number already exist!');
} }
} }

View File

@@ -20,10 +20,10 @@ class GuardNameImporter extends Importer
return [ return [
ImportColumn::make('plant') ImportColumn::make('plant')
->requiredMapping() ->requiredMapping()
->exampleHeader('Plant Name') ->exampleHeader('Plant Code')
->example('Ransar Industries-I') ->example('1000')
->label('Plant Name') ->label('Plant Code')
->relationship(resolveUsing: 'name') ->relationship(resolveUsing: 'code')
->rules(['required']), ->rules(['required']),
ImportColumn::make('name') ImportColumn::make('name')
->requiredMapping() ->requiredMapping()
@@ -54,19 +54,25 @@ class GuardNameImporter extends Importer
public function resolveRecord(): ?GuardName public function resolveRecord(): ?GuardName
{ {
$warnMsg = []; $warnMsg = [];
$plant = Plant::where('name', $this->data['plant'])->first(); $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) { if (! $plant) {
$warnMsg[] = "Plant not found"; // '" . $this->data['plant'] . "' $warnMsg[] = 'Plant not found'; // '" . $plantCod . "'
}
} }
if (Str::length($this->data['name']) < 3) { // || !ctype_alnum($this->data['name']) if (Str::length($this->data['name']) < 3) { // || !ctype_alnum($this->data['name'])
$warnMsg[] = "Invalid guard name found"; $warnMsg[] = 'Invalid guard name found';
} }
if (Str::length($this->data['identification1']) < 5) { if (Str::length($this->data['identification1']) < 5) {
$warnMsg[] = "Invalid identification-1 found"; $warnMsg[] = 'Invalid identification-1 found';
} }
$createdBy = $this->data['created_by']; $createdBy = $this->data['created_by'];
if (Str::length($createdBy) < 3) { // || !ctype_alnum($createdBy) if (Str::length($createdBy) < 3) { // || !ctype_alnum($createdBy)
$warnMsg[] = "Invalid created by name found"; $warnMsg[] = 'Invalid created by name found';
} }
if (! empty($warnMsg)) { if (! empty($warnMsg)) {
throw new RowImportFailedException(implode(', ', $warnMsg)); throw new RowImportFailedException(implode(', ', $warnMsg));
@@ -74,12 +80,12 @@ class GuardNameImporter extends Importer
return GuardName::updateOrCreate([ return GuardName::updateOrCreate([
'name' => $this->data['name'], 'name' => $this->data['name'],
'plant_id' => $plant->id 'plant_id' => $plant->id,
], ],
[ [
'identification1' => $this->data['identification1'], 'identification1' => $this->data['identification1'],
'identification2' => $this->data['identification2'], 'identification2' => $this->data['identification2'],
'created_by' => $this->data['created_by'] 'created_by' => $this->data['created_by'],
] ]
); );

View File

@@ -23,10 +23,10 @@ class GuardPatrolEntryImporter extends Importer
return [ return [
ImportColumn::make('plant') ImportColumn::make('plant')
->requiredMapping() ->requiredMapping()
->exampleHeader('Plant Name') ->exampleHeader('Plant Code')
->example('Ransar Industries-I') ->example('1000')
->label('Plant Name') ->label('Plant Code')
->relationship(resolveUsing: 'name') ->relationship(resolveUsing: 'code')
->rules(['required']), ->rules(['required']),
ImportColumn::make('guardNames') ImportColumn::make('guardNames')
->requiredMapping() ->requiredMapping()
@@ -68,27 +68,27 @@ class GuardPatrolEntryImporter extends Importer
public function resolveRecord(): ?GuardPatrolEntry public function resolveRecord(): ?GuardPatrolEntry
{ {
$warnMsg = []; $warnMsg = [];
$plant = Plant::where('name', $this->data['plant'])->first(); $plantCod = $this->data['plant'];
$plant = null;
$guardNames = null; $guardNames = null;
$checkPointNames = null; $checkPointNames = null;
$patrolDateTime = null; // $fdateTime = null; $patrolDateTime = null; // $fdateTime = 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) { if (! $plant) {
$warnMsg[] = "Plant not found"; // '" . $this->data['plant'] . "' $warnMsg[] = 'Plant not found'; // '" . $plantCod . "'
} } else {
else
{
$guardNames = GuardName::where('plant_id', $plant->id)->where('name', $this->data['guardNames'])->first(); $guardNames = GuardName::where('plant_id', $plant->id)->where('name', $this->data['guardNames'])->first();
if (! $guardNames) { if (! $guardNames) {
$warnMsg[] = "Guard name not found"; $warnMsg[] = 'Guard name not found';
} } else {
else
{
$checkPointNames = CheckPointName::where('plant_id', $plant->id)->where('name', $this->data['checkPointNames'])->first(); $checkPointNames = CheckPointName::where('plant_id', $plant->id)->where('name', $this->data['checkPointNames'])->first();
if (! $checkPointNames) { if (! $checkPointNames) {
$warnMsg[] = "Check point name not found"; $warnMsg[] = 'Check point name not found';
} } else {
else
{
$patrolTime = $this->data['patrol_time']; // $fromDate = $this->data['from_datetime']; $patrolTime = $this->data['patrol_time']; // $fromDate = $this->data['from_datetime'];
$formats = ['d-m-Y H:i', 'd-m-Y H:i:s']; // '07-05-2025 08:00' or '07-05-2025 08:00:00' $formats = ['d-m-Y H:i', 'd-m-Y H:i:s']; // '07-05-2025 08:00' or '07-05-2025 08:00:00'
@@ -105,12 +105,11 @@ class GuardPatrolEntryImporter extends Importer
if (! isset($patrolDateTime)) { if (! isset($patrolDateTime)) {
// throw new \Exception('Invalid date time format'); // throw new \Exception('Invalid date time format');
$warnMsg[] = "Invalid 'Patrol DateTime' format. Expected DD-MM-YYYY HH:MM:SS"; $warnMsg[] = "Invalid 'Patrol DateTime' format. Expected DD-MM-YYYY HH:MM:SS";
} } else {
else
{
$guardEntryFound = GuardPatrolEntry::where('plant_id', $plant->id)->where('guard_name_id', $guardNames->id)->where('check_point_name_id', $checkPointNames->id)->where('patrol_time', $patrolDateTime->format('Y-m-d H:i:s'))->first(); $guardEntryFound = GuardPatrolEntry::where('plant_id', $plant->id)->where('guard_name_id', $guardNames->id)->where('check_point_name_id', $checkPointNames->id)->where('patrol_time', $patrolDateTime->format('Y-m-d H:i:s'))->first();
if ($guardEntryFound) { if ($guardEntryFound) {
$warnMsg[] = "Duplicate guard patrol entry found"; $warnMsg[] = 'Duplicate guard patrol entry found';
}
} }
} }
} }
@@ -119,7 +118,7 @@ class GuardPatrolEntryImporter extends Importer
$createdBy = Filament::auth()->user()->name; // ?? 'Admin' $createdBy = Filament::auth()->user()->name; // ?? 'Admin'
if (! $createdBy) { if (! $createdBy) {
$warnMsg[] = "Invalid created by name found"; $warnMsg[] = 'Invalid created by name found';
} }
if (! empty($warnMsg)) { if (! empty($warnMsg)) {
@@ -130,14 +129,15 @@ class GuardPatrolEntryImporter extends Importer
'plant_id' => $plant->id, 'plant_id' => $plant->id,
'guard_name_id' => $guardNames->id, 'guard_name_id' => $guardNames->id,
'check_point_name_id' => $checkPointNames->id, 'check_point_name_id' => $checkPointNames->id,
'patrol_time' => $patrolDateTime->format('Y-m-d H:i:s') 'patrol_time' => $patrolDateTime->format('Y-m-d H:i:s'),
], ],
[ [
'reader_code' => null, 'reader_code' => null,
'created_by' => $createdBy, 'created_by' => $createdBy,
'updated_by' => $createdBy 'updated_by' => $createdBy,
] ]
); );
return null; return null;
// // return GuardPatrolEntry::firstOrNew([ // // return GuardPatrolEntry::firstOrNew([
// // // Update existing records, matching them by `$this->data['column_name']` // // // Update existing records, matching them by `$this->data['column_name']`

View File

@@ -87,10 +87,10 @@ class LineImporter extends Importer
->label('Work Group Center 10'), ->label('Work Group Center 10'),
ImportColumn::make('plant') ImportColumn::make('plant')
->requiredMapping() ->requiredMapping()
->exampleHeader('Plant Name') ->exampleHeader('Plant Code')
->example('Ransar Industries-I') ->example('1000')
->label('Plant Name') ->label('Plant Code')
->relationship(resolveUsing:'name') ->relationship(resolveUsing: 'code')
->rules(['required']), ->rules(['required']),
]; ];
} }
@@ -98,18 +98,24 @@ class LineImporter extends Importer
public function resolveRecord(): ?Line public function resolveRecord(): ?Line
{ {
$warnMsg = []; $warnMsg = [];
$plantCod = $this->data['plant'];
$plant = null;
$plant = Plant::where('name', $this->data['plant'])->first(); 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) { if (! $plant) {
throw new RowImportFailedException("Plant '{$this->data['plant']}' not found"); throw new RowImportFailedException('Plant not found');
}
} }
if (Str::length($this->data['name'] ?? '') <= 0) { if (Str::length($this->data['name'] ?? '') <= 0) {
throw new RowImportFailedException("Line name not found"); throw new RowImportFailedException('Line name not found');
} }
if (Str::length($this->data['type'] ?? '') <= 0) { if (Str::length($this->data['type'] ?? '') <= 0) {
throw new RowImportFailedException("Line type not found"); throw new RowImportFailedException('Line type not found');
} }
$noOfOps = (int) ($this->data['no_of_operation'] ?? 0); $noOfOps = (int) ($this->data['no_of_operation'] ?? 0);
@@ -118,8 +124,7 @@ class LineImporter extends Importer
throw new RowImportFailedException("'No of Operation' is required and must be a number $noOfOps"); throw new RowImportFailedException("'No of Operation' is required and must be a number $noOfOps");
} }
if ($noOfOps > 10) if ($noOfOps > 10) {
{
throw new RowImportFailedException("Invalid 'No Of Operation' value: {$noOfOps}, maximum allowed is 10"); throw new RowImportFailedException("Invalid 'No Of Operation' value: {$noOfOps}, maximum allowed is 10");
} }
@@ -132,7 +137,7 @@ class LineImporter extends Importer
} }
if (! empty($missingGroups)) { if (! empty($missingGroups)) {
throw new RowImportFailedException( throw new RowImportFailedException(
"Invalid data: Required work groups missing values in: " . implode(', ', $missingGroups) 'Invalid data: Required work groups missing values in: '.implode(', ', $missingGroups)
); );
} }
@@ -160,7 +165,7 @@ class LineImporter extends Importer
->first(); ->first();
if (! $workGroupRecord) { if (! $workGroupRecord) {
throw new RowImportFailedException("Work group '{$workGroupName}' not found in plant '{$this->data['plant']}'"); throw new RowImportFailedException("Work group '{$workGroupName}' not found in plant '{$plantCod}'");
} }
$existsInLines = Line::where('plant_id', $plant->id) $existsInLines = Line::where('plant_id', $plant->id)
@@ -169,21 +174,20 @@ class LineImporter extends Importer
->first(); ->first();
if ($existsInLines) { if ($existsInLines) {
$warnMsg[] = "Work group '{$workGroupName}' is already assigned to another line in plant '{$this->data['plant']}'"; $warnMsg[] = "Work group '{$workGroupName}' is already assigned to another line in plant '{$plantCod}'";
} }
$this->data["work_group{$i}_id"] = $workGroupRecord->id; $this->data["work_group{$i}_id"] = $workGroupRecord->id;
} }
if (!empty($warnMsg)) if (! empty($warnMsg)) {
{
throw new RowImportFailedException(implode(', ', $warnMsg)); throw new RowImportFailedException(implode(', ', $warnMsg));
} }
Line::updateOrCreate( Line::updateOrCreate(
[ [
'name' => $this->data['name'], 'name' => $this->data['name'],
'plant_id' => $plant->id 'plant_id' => $plant->id,
], ],
[ [
'type' => $this->data['type'], 'type' => $this->data['type'],

View File

@@ -10,7 +10,6 @@ use Filament\Actions\Imports\Exceptions\RowImportFailedException;
use Filament\Actions\Imports\ImportColumn; use Filament\Actions\Imports\ImportColumn;
use Filament\Actions\Imports\Importer; use Filament\Actions\Imports\Importer;
use Filament\Actions\Imports\Models\Import; use Filament\Actions\Imports\Models\Import;
use Filament\Facades\Filament;
use Str; use Str;
class LocatorInvoiceValidationImporter extends Importer class LocatorInvoiceValidationImporter extends Importer
@@ -116,48 +115,44 @@ class LocatorInvoiceValidationImporter extends Importer
$updatedBy = $this->data['updated_by']; $updatedBy = $this->data['updated_by'];
if (Str::length($plantCod) < 4 || ! is_numeric($plantCod) || ! preg_match('/^[1-9]\d{3,}$/', $plantCod)) { if (Str::length($plantCod) < 4 || ! is_numeric($plantCod) || ! preg_match('/^[1-9]\d{3,}$/', $plantCod)) {
$warnMsg[] = "Invalid plant code found"; $warnMsg[] = 'Invalid plant code found';
} } else {
else $plant = Plant::where('code', $plantCod)->first();
{
$plant = Plant::where('code', $this->data['plant'])->first();
if (! $plant) { if (! $plant) {
$warnMsg[] = "Plant not found"; $warnMsg[] = 'Plant not found';
} } else {
else
{
if (Str::length($invoiceNo) < 5 || ! ctype_alnum($invoiceNo)) { if (Str::length($invoiceNo) < 5 || ! ctype_alnum($invoiceNo)) {
$warnMsg[] = "Invalid invoice number found"; $warnMsg[] = 'Invalid invoice number found';
} }
if (Str::length($serialNo) < 9 || Str::length($serialNo) > 20 || ! ctype_alnum($serialNo)) { if (Str::length($serialNo) < 9 || Str::length($serialNo) > 20 || ! ctype_alnum($serialNo)) {
$warnMsg[] = "Invalid serial number found"; $warnMsg[] = 'Invalid serial number found';
} }
if (Str::length($palletNo) > 0 && Str::length($palletNo) < 10) { if (Str::length($palletNo) > 0 && Str::length($palletNo) < 10) {
$warnMsg[] = "Invalid pallet number found"; $warnMsg[] = 'Invalid pallet number found';
} }
if (Str::length($locatorNo) > 0 && Str::length($locatorNo) < 7) { if (Str::length($locatorNo) > 0 && Str::length($locatorNo) < 7) {
$warnMsg[] = "Invalid locator number found"; $warnMsg[] = 'Invalid locator number found';
} }
if (Str::length($scannedStat) > 0 && $scannedStat != 'Scanned') { if (Str::length($scannedStat) > 0 && $scannedStat != 'Scanned') {
$warnMsg[] = "Invalid scanned status found"; $warnMsg[] = 'Invalid scanned status found';
} }
if ($uploadStat != 'Y' && $uploadStat != 'N') { if ($uploadStat != 'Y' && $uploadStat != 'N') {
$warnMsg[] = "Invalid upload status found"; $warnMsg[] = 'Invalid upload status found';
} }
$created = User::where('name', $createdBy)->first(); $created = User::where('name', $createdBy)->first();
if (! $created) { if (! $created) {
$warnMsg[] = "Created by not found"; $warnMsg[] = 'Created by not found';
} }
if (Str::length($scannedBy) > 0) { if (Str::length($scannedBy) > 0) {
$scanned = User::where('name', $scannedBy)->first(); $scanned = User::where('name', $scannedBy)->first();
if (! $scanned) { if (! $scanned) {
$warnMsg[] = "Scanned by not found"; $warnMsg[] = 'Scanned by not found';
} }
} }
if (Str::length($updatedBy) > 0) { if (Str::length($updatedBy) > 0) {
$updated = User::where('name', $updatedBy)->first(); $updated = User::where('name', $updatedBy)->first();
if (! $updated) { if (! $updated) {
$warnMsg[] = "Updated by not found"; $warnMsg[] = 'Updated by not found';
} }
} }
@@ -178,8 +173,7 @@ class LocatorInvoiceValidationImporter extends Importer
$warnMsg[] = "Invalid 'Created DateTime' format. Expected DD-MM-YYYY HH:MM:SS"; $warnMsg[] = "Invalid 'Created DateTime' format. Expected DD-MM-YYYY HH:MM:SS";
} }
if (Str::length($scannedAt) > 0) if (Str::length($scannedAt) > 0) {
{
foreach ($formats as $format) { foreach ($formats as $format) {
try { try {
$sDateTime = Carbon::createFromFormat($format, $scannedAt); $sDateTime = Carbon::createFromFormat($format, $scannedAt);
@@ -195,8 +189,7 @@ class LocatorInvoiceValidationImporter extends Importer
} }
} }
if (Str::length($updatedAt) > 0) if (Str::length($updatedAt) > 0) {
{
foreach ($formats as $format) { foreach ($formats as $format) {
try { try {
$uDateTime = Carbon::createFromFormat($format, $updatedAt); $uDateTime = Carbon::createFromFormat($format, $updatedAt);
@@ -209,9 +202,7 @@ class LocatorInvoiceValidationImporter extends Importer
if (! isset($uDateTime)) { if (! isset($uDateTime)) {
$warnMsg[] = "Invalid 'Updated DateTime' format. Expected DD-MM-YYYY HH:MM:SS"; $warnMsg[] = "Invalid 'Updated DateTime' format. Expected DD-MM-YYYY HH:MM:SS";
} } else {
else
{
if (isset($cDateTime) && isset($uDateTime)) { if (isset($cDateTime) && isset($uDateTime)) {
if ($cDateTime->greaterThan($uDateTime)) { if ($cDateTime->greaterThan($uDateTime)) {
$warnMsg[] = "'Created DataTime' is greater than 'Updated DateTime'."; $warnMsg[] = "'Created DataTime' is greater than 'Updated DateTime'.";
@@ -233,7 +224,7 @@ class LocatorInvoiceValidationImporter extends Importer
LocatorInvoiceValidation::updateOrCreate( LocatorInvoiceValidation::updateOrCreate(
[ [
'plant_id' => $plant->id, 'plant_id' => $plant->id,
'serial_number' => $serialNo 'serial_number' => $serialNo,
], ],
[ [
'invoice_number' => $invoiceNo, 'invoice_number' => $invoiceNo,
@@ -246,9 +237,10 @@ class LocatorInvoiceValidationImporter extends Importer
'updated_at' => (Str::length($updatedAt) > 0) ? $uDateTime->format('Y-m-d H:i:s') : null, 'updated_at' => (Str::length($updatedAt) > 0) ? $uDateTime->format('Y-m-d H:i:s') : null,
'created_by' => $createdBy, 'created_by' => $createdBy,
'scanned_by' => $scannedBy, 'scanned_by' => $scannedBy,
'updated_by' => $updatedBy 'updated_by' => $updatedBy,
] ]
); );
return null; return null;
// // return LocatorInvoiceValidation::firstOrNew([ // // return LocatorInvoiceValidation::firstOrNew([
// // // Update existing records, matching them by `$this->data['column_name']` // // // Update existing records, matching them by `$this->data['column_name']`

View File

@@ -21,9 +21,9 @@ class MachineImporter extends Importer
return [ return [
ImportColumn::make('name') ImportColumn::make('name')
->requiredMapping() ->requiredMapping()
->exampleHeader('Machine') ->exampleHeader('Machine Name')
->example(['1600251']) ->example(['1600251'])
->label('Machine') ->label('Machine Name')
->rules(['required']), ->rules(['required']),
ImportColumn::make('work_center') ImportColumn::make('work_center')
->requiredMapping() ->requiredMapping()
@@ -41,16 +41,16 @@ class MachineImporter extends Importer
ImportColumn::make('line') ImportColumn::make('line')
->requiredMapping() ->requiredMapping()
->relationship(resolveUsing: 'name') ->relationship(resolveUsing: 'name')
->exampleHeader('Line') ->exampleHeader('Line Name')
->example(['4 inch pump line']) ->example(['4 inch pump line'])
->label('Line') ->label('Line Name')
->rules(['required']), ->rules(['required']),
ImportColumn::make('plant') ImportColumn::make('plant')
->requiredMapping() ->requiredMapping()
->relationship(resolveUsing: 'name') ->relationship(resolveUsing: 'code')
->exampleHeader('Plant') ->exampleHeader('Plant Code')
->example(['Ransar Industries-I']) ->example(['1000'])
->label('Plant') ->label('Plant Code')
->rules(['required']), ->rules(['required']),
]; ];
} }
@@ -58,37 +58,37 @@ class MachineImporter extends Importer
public function resolveRecord(): ?Machine public function resolveRecord(): ?Machine
{ {
$warnMsg = []; $warnMsg = [];
$plant = Plant::where('name', $this->data['plant'])->first(); $plantCod = $this->data['plant'];
$plant = null;
$line = null; $line = null;
$machine = $this->data['name']; $machine = $this->data['name'];
$workCenter = $this->data['work_center']; $workCenter = $this->data['work_center'];
$groupWorkCenter = WorkGroupMaster::where('name', $this->data['workGroupMaster'])->first(); $groupWorkCenter = WorkGroupMaster::where('name', $this->data['workGroupMaster'])->first();
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) { if (! $plant) {
$warnMsg[] = "Plant not found!"; $warnMsg[] = 'Plant not found!';
} } else {
else {
$groupWorkCenter = WorkGroupMaster::where('name', $this->data['workGroupMaster'])->where('plant_id', $plant->id)->first(); $groupWorkCenter = WorkGroupMaster::where('name', $this->data['workGroupMaster'])->where('plant_id', $plant->id)->first();
$line = Line::where('name', $this->data['line'])->where('plant_id', $plant->id)->first(); $line = Line::where('name', $this->data['line'])->where('plant_id', $plant->id)->first();
if ($line) { if ($line) {
$grpWrkCnr = $line->no_of_operation; $grpWrkCnr = $line->no_of_operation;
if (!$grpWrkCnr || $grpWrkCnr < 1)//Str::length($grpWrkCnr) < 1) if (! $grpWrkCnr || $grpWrkCnr < 1) {// Str::length($grpWrkCnr) < 1)
{ $warnMsg[] = 'Group work center line not found!';
$warnMsg[] = "Group work center line not found!"; } elseif (! $groupWorkCenter) {
} $warnMsg[] = 'Group work center not found!';
else if (!$groupWorkCenter) { } else {
$warnMsg[] = "Group work center not found!";
}
else {
$dupMachine = Machine::where('plant_id', $plant->id)->where('work_center', '!=', $workCenter)->where('name', $machine)->first(); $dupMachine = Machine::where('plant_id', $plant->id)->where('work_center', '!=', $workCenter)->where('name', $machine)->first();
if ($dupMachine) { if ($dupMachine) {
$warnMsg[] = "Duplicate machine name found!"; $warnMsg[] = 'Duplicate machine name found!';
} } else {
else {
$isValidGroupWork = false; $isValidGroupWork = false;
for ($i = 1; $i <= $line->no_of_operation; $i++) { for ($i = 1; $i <= $line->no_of_operation; $i++) {
$column = "work_group{$i}_id"; $column = "work_group{$i}_id";
if (! empty($line->$column)) { if (! empty($line->$column)) {
if ($line->$column == $groupWorkCenter->id) { if ($groupWorkCenter->id == $line->$column) {
$isValidGroupWork = true; $isValidGroupWork = true;
break; break;
} }
@@ -96,19 +96,18 @@ class MachineImporter extends Importer
} }
if (! $isValidGroupWork) { if (! $isValidGroupWork) {
$warnMsg[] = "Group work center does not match with line!"; $warnMsg[] = 'Group work center does not match with line!';
} }
} }
} }
} else {
$warnMsg[] = 'Line not found!';
} }
else
{
$warnMsg[] = "Line not found!";
} }
} }
if (Str::length($machine) <= 0) { if (Str::length($machine) <= 0) {
$warnMsg[] = "Machine name not found!"; $warnMsg[] = 'Machine name not found!';
} }
if (! empty($warnMsg)) { if (! empty($warnMsg)) {
@@ -118,14 +117,15 @@ class MachineImporter extends Importer
Machine::updateOrCreate( Machine::updateOrCreate(
[ [
'plant_id' => $plant->id, 'plant_id' => $plant->id,
'work_center' => $workCenter 'work_center' => $workCenter,
], ],
[ [
'line_id' => $line->id, 'line_id' => $line->id,
'name' => $machine, 'name' => $machine,
'work_group_master_id' => $groupWorkCenter->id 'work_group_master_id' => $groupWorkCenter->id,
] ]
); );
return null; return null;
// // return Machine::firstOrNew([ // // return Machine::firstOrNew([
// // // Update existing records, matching them by `$this->data['column_name']` // // // Update existing records, matching them by `$this->data['column_name']`

View File

@@ -16,10 +16,10 @@ class MfmMeterImporter extends Importer
return [ return [
ImportColumn::make('plant') ImportColumn::make('plant')
->requiredMapping() ->requiredMapping()
->exampleHeader('Plant Name') ->exampleHeader('Plant Code')
->example('Ransar Industries-I') ->example('1000')
->label('Plant Name') ->label('Plant Code')
->relationship(resolveUsing:'name') ->relationship(resolveUsing: 'code')
->rules(['required']), ->rules(['required']),
ImportColumn::make('Device Name') ImportColumn::make('Device Name')
->requiredMapping() ->requiredMapping()
@@ -56,7 +56,7 @@ class MfmMeterImporter extends Importer
// 'email' => $this->data['email'], // 'email' => $this->data['email'],
// ]); // ]);
return new MfmMeter(); return new MfmMeter;
} }
public static function getCompletedNotificationBody(Import $import): string public static function getCompletedNotificationBody(Import $import): string

View File

@@ -16,10 +16,10 @@ class MfmParameterImporter extends Importer
return [ return [
ImportColumn::make('plant') ImportColumn::make('plant')
->requiredMapping() ->requiredMapping()
->exampleHeader('Plant Name') ->exampleHeader('Plant Code')
->example('Ransar Industries-I') ->example('1000')
->label('Plant Name') ->label('Plant Code')
->relationship(resolveUsing:'name') ->relationship(resolveUsing: 'code')
->rules(['required']), ->rules(['required']),
ImportColumn::make('deviceName') ImportColumn::make('deviceName')
->requiredMapping() ->requiredMapping()
@@ -82,7 +82,7 @@ class MfmParameterImporter extends Importer
// 'email' => $this->data['email'], // 'email' => $this->data['email'],
// ]); // ]);
return new MfmParameter(); return new MfmParameter;
} }
public static function getCompletedNotificationBody(Import $import): string public static function getCompletedNotificationBody(Import $import): string

View File

@@ -237,7 +237,7 @@ class MotorTestingMasterImporter extends Importer
$plantCod = trim($this->data['plant']); $plantCod = trim($this->data['plant']);
$iCode = trim($this->data['item']); $iCode = trim($this->data['item']);
$sCode = trim($this->data['subassembly_code']); $sCode = trim($this->data['subassembly_code']);
$isiModel = (trim($this->data['isi_model']) == "1") ? true : false; $isiModel = (trim($this->data['isi_model']) == '1') ? true : false;
$phase = trim($this->data['phase']); $phase = trim($this->data['phase']);
$kw = trim($this->data['kw']); $kw = trim($this->data['kw']);
$hp = trim($this->data['hp']); $hp = trim($this->data['hp']);
@@ -270,40 +270,25 @@ class MotorTestingMasterImporter extends Importer
$updatedBy = trim($this->data['updated_by']); $updatedBy = trim($this->data['updated_by']);
$plant = null; $plant = null;
if (Str::length($plantCod) < 4 || !is_numeric($plantCod) || !preg_match('/^[1-9]\d{3,}$/', $plantCod)) if (Str::length($plantCod) < 4 || ! is_numeric($plantCod) || ! preg_match('/^[1-9]\d{3,}$/', $plantCod)) {
{ $warnMsg[] = 'Invalid plant code found';
$warnMsg[] = "Invalid plant code found"; } elseif (Str::length($iCode) < 6 || ! ctype_alnum($iCode)) {
} $warnMsg[] = 'Invalid item code found';
else if (Str::length($iCode) < 6 || !ctype_alnum($iCode)) } elseif (Str::length($sCode) < 6 || ! ctype_alnum($sCode)) {
{ $warnMsg[] = 'Invalid sub-assembly code found';
$warnMsg[] = "Invalid item code found"; } else {
}
else if (Str::length($sCode) < 6 || !ctype_alnum($sCode))
{
$warnMsg[] = "Invalid sub-assembly code found";
}
else
{
$plant = Plant::where('code', $plantCod)->first(); $plant = Plant::where('code', $plantCod)->first();
$codeExist = Item::where('code', $iCode)->first(); $codeExist = Item::where('code', $iCode)->first();
if ($plant) if ($plant) {
{
$iCode = Item::where('code', $iCode)->where('plant_id', $plant->id)->first(); $iCode = Item::where('code', $iCode)->where('plant_id', $plant->id)->first();
} }
if (!$plant) if (! $plant) {
{ $warnMsg[] = 'Plant not found';
$warnMsg[] = "Plant not found"; } elseif (! $codeExist) {
} $warnMsg[] = 'Item code not found';
else if (!$codeExist) } elseif (! $iCode) {
{ $warnMsg[] = 'Item code not found for choosed plant';
$warnMsg[] = "Item code not found"; } else {
}
else if (!$iCode)
{
$warnMsg[] = "Item code not found for choosed plant";
}
else
{
// if (Str::length($isiModel) <= 0 || $isiModel == "0" || $isiModel == "1") { // if (Str::length($isiModel) <= 0 || $isiModel == "0" || $isiModel == "1") {
// $warnMsg[] = "Invalid ISI Model found"; // $warnMsg[] = "Invalid ISI Model found";
// } // }
@@ -311,89 +296,89 @@ class MotorTestingMasterImporter extends Importer
// { // {
// $isiModel = ($isiModel == "1"); // $isiModel = ($isiModel == "1");
// } // }
if (Str::length($phase) <= 0 || ($phase != "Single" && $phase != "Three")) {//!is_string($phase) || if (Str::length($phase) <= 0 || ($phase != 'Single' && $phase != 'Three')) {// !is_string($phase) ||
$warnMsg[] = "Invalid phase found"; $warnMsg[] = 'Invalid phase found';
} }
if (Str::length($hp) <= 0 || ! is_numeric($hp)) { if (Str::length($hp) <= 0 || ! is_numeric($hp)) {
$warnMsg[] = "Invalid HP found"; $warnMsg[] = 'Invalid HP found';
} }
if (Str::length($kw) <= 0 || ! is_numeric($kw)) { if (Str::length($kw) <= 0 || ! is_numeric($kw)) {
$warnMsg[] = "Invalid KW found"; $warnMsg[] = 'Invalid KW found';
} }
if (Str::length($volt) <= 0 || ! is_numeric($volt)) { if (Str::length($volt) <= 0 || ! is_numeric($volt)) {
$warnMsg[] = "Invalid volt found"; $warnMsg[] = 'Invalid volt found';
} }
if (Str::length($current) <= 0 || ! is_numeric($current)) { if (Str::length($current) <= 0 || ! is_numeric($current)) {
$warnMsg[] = "Invalid current found"; $warnMsg[] = 'Invalid current found';
} }
if (Str::length($rpm) <= 0 || ! is_numeric($rpm)) { if (Str::length($rpm) <= 0 || ! is_numeric($rpm)) {
$warnMsg[] = "Invalid RPM found"; $warnMsg[] = 'Invalid RPM found';
} }
if (Str::length($torque) <= 0 || ! is_numeric($torque)) { if (Str::length($torque) <= 0 || ! is_numeric($torque)) {
$warnMsg[] = "Invalid torque found"; $warnMsg[] = 'Invalid torque found';
} }
if (Str::length($frequency) <= 0 || ! is_numeric($frequency)) { if (Str::length($frequency) <= 0 || ! is_numeric($frequency)) {
$warnMsg[] = "Invalid frequency found"; $warnMsg[] = 'Invalid frequency found';
} }
if (Str::length($connection) <= 0 || ($connection != "Star-Delta" && $connection != "Star" && $connection != "Delta")) { if (Str::length($connection) <= 0 || ($connection != 'Star-Delta' && $connection != 'Star' && $connection != 'Delta')) {
$warnMsg[] = "Invalid connection found"; $warnMsg[] = 'Invalid connection found';
} }
if (Str::length($insResLimit) <= 0 || ! is_numeric($insResLimit)) { if (Str::length($insResLimit) <= 0 || ! is_numeric($insResLimit)) {
$warnMsg[] = "Invalid insulation resistance limit found"; $warnMsg[] = 'Invalid insulation resistance limit found';
} }
if (Str::length($insResType) <= 0 || ($insResType != "O" && $insResType != "M" && $insResType != "G")) { if (Str::length($insResType) <= 0 || ($insResType != 'O' && $insResType != 'M' && $insResType != 'G')) {
$warnMsg[] = "Invalid insulation resistance type found"; $warnMsg[] = 'Invalid insulation resistance type found';
} }
if (Str::length($routineTestTime) <= 0 || ! isValidTimeFormat($routineTestTime)) { if (Str::length($routineTestTime) <= 0 || ! isValidTimeFormat($routineTestTime)) {
$warnMsg[] = "Invalid routine test time found"; $warnMsg[] = 'Invalid routine test time found';
} }
if (Str::length($resRyLl) <= 0 || ! is_numeric($resRyLl)) { if (Str::length($resRyLl) <= 0 || ! is_numeric($resRyLl)) {
$warnMsg[] = "Invalid resistance RY lower limit found"; $warnMsg[] = 'Invalid resistance RY lower limit found';
} }
if (Str::length($resRyUl) <= 0 || ! is_numeric($resRyUl)) { if (Str::length($resRyUl) <= 0 || ! is_numeric($resRyUl)) {
$warnMsg[] = "Invalid resistance RY upper limit found"; $warnMsg[] = 'Invalid resistance RY upper limit found';
} }
if (Str::length($resYbLl) <= 0 || ! is_numeric($resYbLl)) { if (Str::length($resYbLl) <= 0 || ! is_numeric($resYbLl)) {
$warnMsg[] = "Invalid resistance YB lower limit found"; $warnMsg[] = 'Invalid resistance YB lower limit found';
} }
if (Str::length($resYbUl) <= 0 || ! is_numeric($resYbUl)) { if (Str::length($resYbUl) <= 0 || ! is_numeric($resYbUl)) {
$warnMsg[] = "Invalid resistance YB upper limit found"; $warnMsg[] = 'Invalid resistance YB upper limit found';
} }
if (Str::length($resBrLl) <= 0 || ! is_numeric($resBrLl)) { if (Str::length($resBrLl) <= 0 || ! is_numeric($resBrLl)) {
$warnMsg[] = "Invalid resistance BR lower limit found"; $warnMsg[] = 'Invalid resistance BR lower limit found';
} }
if (Str::length($resBrUl) <= 0 || ! is_numeric($resBrUl)) { if (Str::length($resBrUl) <= 0 || ! is_numeric($resBrUl)) {
$warnMsg[] = "Invalid resistance BR upper limit found"; $warnMsg[] = 'Invalid resistance BR upper limit found';
} }
if (Str::length($lockVoltLimit) <= 0 || ! is_numeric($lockVoltLimit)) { if (Str::length($lockVoltLimit) <= 0 || ! is_numeric($lockVoltLimit)) {
$warnMsg[] = "Invalid locked volt limit found"; $warnMsg[] = 'Invalid locked volt limit found';
} }
if (Str::length($leakCurLimit) <= 0 || ! is_numeric($leakCurLimit)) { if (Str::length($leakCurLimit) <= 0 || ! is_numeric($leakCurLimit)) {
$warnMsg[] = "Invalid leakage current limit found"; $warnMsg[] = 'Invalid leakage current limit found';
} }
if (Str::length($lockCurLl) <= 0 || ! is_numeric($lockCurLl)) { if (Str::length($lockCurLl) <= 0 || ! is_numeric($lockCurLl)) {
$warnMsg[] = "Invalid locked current lower limit found"; $warnMsg[] = 'Invalid locked current lower limit found';
} }
if (Str::length($lockCurUl) <= 0 || ! is_numeric($lockCurUl)) { if (Str::length($lockCurUl) <= 0 || ! is_numeric($lockCurUl)) {
$warnMsg[] = "Invalid locked current upper limit found"; $warnMsg[] = 'Invalid locked current upper limit found';
} }
if (Str::length($noloadCurLl) <= 0 || ! is_numeric($noloadCurLl)) { if (Str::length($noloadCurLl) <= 0 || ! is_numeric($noloadCurLl)) {
$warnMsg[] = "Invalid no load current lower limit found"; $warnMsg[] = 'Invalid no load current lower limit found';
} }
if (Str::length($noloadCurUl) <= 0 || ! is_numeric($noloadCurUl)) { if (Str::length($noloadCurUl) <= 0 || ! is_numeric($noloadCurUl)) {
$warnMsg[] = "Invalid no load current upper limit found"; $warnMsg[] = 'Invalid no load current upper limit found';
} }
if (Str::length($noloadPowLl) <= 0 || ! is_numeric($noloadPowLl)) { if (Str::length($noloadPowLl) <= 0 || ! is_numeric($noloadPowLl)) {
$warnMsg[] = "Invalid no load power lower limit found"; $warnMsg[] = 'Invalid no load power lower limit found';
} }
if (Str::length($noloadPowUl) <= 0 || ! is_numeric($noloadPowUl)) { if (Str::length($noloadPowUl) <= 0 || ! is_numeric($noloadPowUl)) {
$warnMsg[] = "Invalid no load power upper limit found"; $warnMsg[] = 'Invalid no load power upper limit found';
} }
if (Str::length($noloadSpdLl) <= 0 || ! is_numeric($noloadSpdLl)) { if (Str::length($noloadSpdLl) <= 0 || ! is_numeric($noloadSpdLl)) {
$warnMsg[] = "Invalid no load speed lower limit found"; $warnMsg[] = 'Invalid no load speed lower limit found';
} }
if (Str::length($noloadSpdUl) <= 0 || ! is_numeric($noloadSpdUl)) { if (Str::length($noloadSpdUl) <= 0 || ! is_numeric($noloadSpdUl)) {
$warnMsg[] = "Invalid no load speed upper limit found"; $warnMsg[] = 'Invalid no load speed upper limit found';
} }
$oldCode = MotorTestingMaster::where('item_id', $iCode->id)->where('plant_id', $plant->id)->first(); $oldCode = MotorTestingMaster::where('item_id', $iCode->id)->where('plant_id', $plant->id)->first();
@@ -401,22 +386,20 @@ class MotorTestingMasterImporter extends Importer
if ($oldCode) { if ($oldCode) {
$created = $oldCode->created_by ? User::where('name', $oldCode->created_by)->first() : null; $created = $oldCode->created_by ? User::where('name', $oldCode->created_by)->first() : null;
if (! $created) { if (! $created) {
$warnMsg[] = "Created by not found on update"; $warnMsg[] = 'Created by not found on update';
} }
$updated = User::where('name', $updatedBy)->first(); $updated = User::where('name', $updatedBy)->first();
if (! $updated) { if (! $updated) {
$warnMsg[] = "Updated by not found on update"; $warnMsg[] = 'Updated by not found on update';
} }
} } else {
else
{
$created = User::where('name', $createdBy)->first(); $created = User::where('name', $createdBy)->first();
if (! $created) { if (! $created) {
$warnMsg[] = "Created by not found"; $warnMsg[] = 'Created by not found';
} }
$updated = User::where('name', $updatedBy)->first(); $updated = User::where('name', $updatedBy)->first();
if (! $updated) { if (! $updated) {
$warnMsg[] = "Updated by not found"; $warnMsg[] = 'Updated by not found';
} }
} }
} }
@@ -428,7 +411,7 @@ class MotorTestingMasterImporter extends Importer
MotorTestingMaster::updateOrCreate([ MotorTestingMaster::updateOrCreate([
'plant_id' => $plant->id, 'plant_id' => $plant->id,
'item_id' => $iCode->id 'item_id' => $iCode->id,
], ],
[ [
'subassembly_code' => $sCode, 'subassembly_code' => $sCode,
@@ -465,6 +448,7 @@ class MotorTestingMasterImporter extends Importer
'updated_by' => $updated->name, 'updated_by' => $updated->name,
] ]
); );
return null; return null;
// // return MotorTestingMaster::firstOrNew([ // // return MotorTestingMaster::firstOrNew([
// // // Update existing records, matching them by `$this->data['column_name']` // // // Update existing records, matching them by `$this->data['column_name']`
@@ -486,12 +470,14 @@ class MotorTestingMasterImporter extends Importer
} }
} }
function isValidTimeFormat($time) { function isValidTimeFormat($time)
{
// If time starts with a single digit hour without leading zero, pad it // If time starts with a single digit hour without leading zero, pad it
if (preg_match('/^\d(:\d{2}:\d{2})$/', $time, $matches)) { if (preg_match('/^\d(:\d{2}:\d{2})$/', $time, $matches)) {
$time = '0'.$time; $time = '0'.$time;
} }
$dateTime = DateTime::createFromFormat('H:i:s', $time); $dateTime = DateTime::createFromFormat('H:i:s', $time);
return $dateTime && $dateTime->format('H:i:s') === $time; return $dateTime && $dateTime->format('H:i:s') === $time;
} }

View File

@@ -12,7 +12,6 @@ use Filament\Actions\Imports\Importer;
use Filament\Actions\Imports\Models\Import; use Filament\Actions\Imports\Models\Import;
use Str; use Str;
class PalletValidationImporter extends Importer class PalletValidationImporter extends Importer
{ {
protected static ?string $model = PalletValidation::class; protected static ?string $model = PalletValidation::class;
@@ -123,45 +122,41 @@ class PalletValidationImporter extends Importer
$updatedBy = $this->data['updated_by']; $updatedBy = $this->data['updated_by'];
if (Str::length($plantCod) < 4 || ! is_numeric($plantCod) || ! preg_match('/^[1-9]\d{3,}$/', $plantCod)) { if (Str::length($plantCod) < 4 || ! is_numeric($plantCod) || ! preg_match('/^[1-9]\d{3,}$/', $plantCod)) {
$warnMsg[] = "Invalid plant code found"; $warnMsg[] = 'Invalid plant code found';
} } else {
else $plant = Plant::where('code', $plantCod)->first();
{
$plant = Plant::where('code', $this->data['plant'])->first();
if (! $plant) { if (! $plant) {
$warnMsg[] = "Plant not found"; $warnMsg[] = 'Plant not found';
} } else {
else
{
if (Str::length($serialNo) < 9 || Str::length($serialNo) > 20 || ! ctype_alnum($serialNo)) { if (Str::length($serialNo) < 9 || Str::length($serialNo) > 20 || ! ctype_alnum($serialNo)) {
$warnMsg[] = "Invalid serial number found"; $warnMsg[] = 'Invalid serial number found';
} }
if (Str::length($palletNo) > 0 && Str::length($palletNo) < 10) { if (Str::length($palletNo) > 0 && Str::length($palletNo) < 10) {
$warnMsg[] = "Invalid pallet number found"; $warnMsg[] = 'Invalid pallet number found';
} }
if (Str::length($palletStat) > 0 && $palletStat != 'Completed') { if (Str::length($palletStat) > 0 && $palletStat != 'Completed') {
$warnMsg[] = "Invalid pallet status found"; $warnMsg[] = 'Invalid pallet status found';
} }
if (Str::length($locatorNo) > 0 && Str::length($locatorNo) < 7) { if (Str::length($locatorNo) > 0 && Str::length($locatorNo) < 7) {
$warnMsg[] = "Invalid locator number found"; $warnMsg[] = 'Invalid locator number found';
} }
if (Str::length($palletNo) <= 0 && Str::length($locatorNo) <= 0) { if (Str::length($palletNo) <= 0 && Str::length($locatorNo) <= 0) {
$warnMsg[] = "Pallet and locator number found"; $warnMsg[] = 'Pallet and locator number found';
} }
if (Str::length($locatorQty) < 0 || ! is_numeric($locatorQty) || $locatorQty < 0 || $locatorQty > 2) { if (Str::length($locatorQty) < 0 || ! is_numeric($locatorQty) || $locatorQty < 0 || $locatorQty > 2) {
$warnMsg[] = "Invalid locator quantity found"; $warnMsg[] = 'Invalid locator quantity found';
} }
$created = User::where('name', $createdBy)->first(); $created = User::where('name', $createdBy)->first();
if (! $created) { if (! $created) {
$warnMsg[] = "Created by not found"; $warnMsg[] = 'Created by not found';
} }
$scanned = User::where('name', $scannedBy)->first(); $scanned = User::where('name', $scannedBy)->first();
if (! $scanned) { if (! $scanned) {
$warnMsg[] = "Scanned by not found"; $warnMsg[] = 'Scanned by not found';
} }
$updated = User::where('name', $updatedBy)->first(); $updated = User::where('name', $updatedBy)->first();
if (! $updated) { if (! $updated) {
$warnMsg[] = "Updated by not found"; $warnMsg[] = 'Updated by not found';
} }
$formats = ['d-m-Y H:i', 'd-m-Y H:i:s']; // '07-05-2025 08:00' or '07-05-2025 08:00:00' $formats = ['d-m-Y H:i', 'd-m-Y H:i:s']; // '07-05-2025 08:00' or '07-05-2025 08:00:00'
@@ -196,8 +191,7 @@ class PalletValidationImporter extends Importer
} }
foreach ($formats as $format) { foreach ($formats as $format) {
try try {
{
$uDateTime = Carbon::createFromFormat($format, $updatedAt); $uDateTime = Carbon::createFromFormat($format, $updatedAt);
break; break;
} catch (\Exception $e) { } catch (\Exception $e) {
@@ -208,9 +202,7 @@ class PalletValidationImporter extends Importer
if (! isset($uDateTime)) { if (! isset($uDateTime)) {
$warnMsg[] = "Invalid 'Updated DateTime' format. Expected DD-MM-YYYY HH:MM:SS"; $warnMsg[] = "Invalid 'Updated DateTime' format. Expected DD-MM-YYYY HH:MM:SS";
} } else {
else
{
if (isset($cDateTime) && isset($uDateTime)) { if (isset($cDateTime) && isset($uDateTime)) {
if ($cDateTime->greaterThan($uDateTime)) { if ($cDateTime->greaterThan($uDateTime)) {
$warnMsg[] = "'Created DataTime' is greater than 'Updated DateTime'."; $warnMsg[] = "'Created DataTime' is greater than 'Updated DateTime'.";
@@ -231,7 +223,7 @@ class PalletValidationImporter extends Importer
PalletValidation::updateOrCreate( PalletValidation::updateOrCreate(
[ [
'plant_id' => $plant->id, 'plant_id' => $plant->id,
'serial_number' => $serialNo 'serial_number' => $serialNo,
], ],
[ [
'pallet_number' => $palletNo, 'pallet_number' => $palletNo,
@@ -243,9 +235,10 @@ class PalletValidationImporter extends Importer
'updated_at' => $uDateTime->format('Y-m-d H:i:s'), 'updated_at' => $uDateTime->format('Y-m-d H:i:s'),
'created_by' => $createdBy, 'created_by' => $createdBy,
'scanned_by' => $scannedBy, 'scanned_by' => $scannedBy,
'updated_by' => $updatedBy 'updated_by' => $updatedBy,
] ]
); );
return null; return null;
// // return PalletValidation::firstOrNew([ // // return PalletValidation::firstOrNew([
// // // Update existing records, matching them by `$this->data['column_name']` // // // Update existing records, matching them by `$this->data['column_name']`

View File

@@ -51,16 +51,16 @@ class PlantImporter extends Importer
$warnMsg = []; $warnMsg = [];
$company = Company::where('name', $this->data['company'])->first(); $company = Company::where('name', $this->data['company'])->first();
if (! $company) { if (! $company) {
$warnMsg[] = "Company name not found"; $warnMsg[] = 'Company name not found';
} }
if (Str::length($this->data['name']) < 0) { if (Str::length($this->data['name']) < 0) {
$warnMsg[] = "Plant name not found"; $warnMsg[] = 'Plant name not found';
} }
if (Str::length($this->data['code']) < 4 || ! is_numeric($this->data['code']) || ! preg_match('/^[1-9]\d{3,}$/', $this->data['code'])) { if (Str::length($this->data['code']) < 4 || ! is_numeric($this->data['code']) || ! preg_match('/^[1-9]\d{3,}$/', $this->data['code'])) {
$warnMsg[] = "Invalid plant code found"; $warnMsg[] = 'Invalid plant code found';
} }
if (Str::length($this->data['address']) < 3) { if (Str::length($this->data['address']) < 3) {
$warnMsg[] = "Invalid address found"; $warnMsg[] = 'Invalid address found';
} }
if (! empty($warnMsg)) { if (! empty($warnMsg)) {
throw new RowImportFailedException(implode(', ', $warnMsg)); throw new RowImportFailedException(implode(', ', $warnMsg));
@@ -71,10 +71,9 @@ class PlantImporter extends Importer
$plantCode = Plant::where('code', $this->data['code'])->first(); $plantCode = Plant::where('code', $this->data['code'])->first();
$plantName = Plant::where('name', $this->data['name'])->first(); $plantName = Plant::where('name', $this->data['name'])->first();
if ($plantName) { if ($plantName) {
throw new RowImportFailedException("Duplicate plant name found"); throw new RowImportFailedException('Duplicate plant name found');
} } elseif ($plantCode) {
else if ($plantCode) { throw new RowImportFailedException('Duplicate plant code found');
throw new RowImportFailedException("Duplicate plant code found");
} }
} }
@@ -84,7 +83,7 @@ class PlantImporter extends Importer
], ],
[ [
'address' => $this->data['address'], 'address' => $this->data['address'],
'company_id' => $company->id 'company_id' => $company->id,
] ]
); );
// return Plant::firstOrNew([ // return Plant::firstOrNew([

View File

@@ -15,6 +15,7 @@ use Filament\Actions\Imports\ImportColumn;
use Filament\Actions\Imports\Importer; use Filament\Actions\Imports\Importer;
use Filament\Actions\Imports\Models\Import; use Filament\Actions\Imports\Models\Import;
use Filament\Facades\Filament; use Filament\Facades\Filament;
use Str;
class ProductionLineStopImporter extends Importer class ProductionLineStopImporter extends Importer
{ {
@@ -78,10 +79,10 @@ class ProductionLineStopImporter extends Importer
->rules(['required']), ->rules(['required']),
ImportColumn::make('plant') ImportColumn::make('plant')
->requiredMapping() ->requiredMapping()
->exampleHeader('Plant Name') ->exampleHeader('Plant Code')
->example(['Ransar Industries-I', 'Ransar Industries-I']) ->example(['1000', '1000'])
->label('Plant Name') ->label('Plant Code')
->relationship(resolveUsing:'name') ->relationship(resolveUsing: 'code')
->rules(['required']), ->rules(['required']),
ImportColumn::make('operator_id') ImportColumn::make('operator_id')
->requiredMapping() ->requiredMapping()
@@ -95,56 +96,57 @@ class ProductionLineStopImporter extends Importer
public function resolveRecord(): ?ProductionLineStop public function resolveRecord(): ?ProductionLineStop
{ {
$warnMsg = []; $warnMsg = [];
$plant = Plant::where('name', $this->data['plant'])->first(); $plantCod = $this->data['plant'];
$plant = null;
$line = null; $line = null;
$block = null; $block = null;
$shift = 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) { if (! $plant) {
$warnMsg[] = "Plant not found"; $warnMsg[] = 'Plant not found';
} } else {
else {
$line = Line::where('name', $this->data['line'])->where('plant_id', $plant->id)->first(); $line = Line::where('name', $this->data['line'])->where('plant_id', $plant->id)->first();
// block_reference // block_reference
$block = Block::where('name', $this->data['block_reference'])->where('plant_id', $plant->id)->first(); $block = Block::where('name', $this->data['block_reference'])->where('plant_id', $plant->id)->first();
} }
}
if (! $line) { if (! $line) {
$warnMsg[] = "Line not found"; $warnMsg[] = 'Line not found';
} }
$shift = null;
if (! $block) { if (! $block) {
$warnMsg[] = "Block not found"; $warnMsg[] = 'Block not found';
} } elseif ($plant) {
else {
$shift = Shift::where('name', $this->data['shift'])->where('plant_id', $plant->id)->where('block_id', $block->id)->first(); $shift = Shift::where('name', $this->data['shift'])->where('plant_id', $plant->id)->where('block_id', $block->id)->first();
} }
// $shift = Shift::where('id', $this->data['shift'])->where('plant_id', $plant->id)->first(); // $shift = Shift::where('id', $this->data['shift'])->where('plant_id', $plant->id)->first();
if (! $shift) { if (! $shift) {
$warnMsg[] = "Shift not found"; $warnMsg[] = 'Shift not found';
} }
$linestop = LineStop::where('code', $this->data['linestop'])->first(); $linestop = LineStop::where('code', $this->data['linestop'])->first();
if (! $linestop) { if (! $linestop) {
$warnMsg[] = "Line stop code not found"; $warnMsg[] = 'Line stop code not found';
} }
$stophour = is_numeric($this->data['stop_hour']) && $this->data['stop_hour'] >= 0; $stophour = is_numeric($this->data['stop_hour']) && $this->data['stop_hour'] >= 0;
$stopmin = is_numeric($this->data['stop_min']) && $this->data['stop_min'] >= 0 && $this->data['stop_min'] <= 60; $stopmin = is_numeric($this->data['stop_min']) && $this->data['stop_min'] >= 0 && $this->data['stop_min'] <= 60;
if (! $stophour && ! $stopmin) { if (! $stophour && ! $stopmin) {
$warnMsg[] = "Invalid stop hour/minute found"; $warnMsg[] = 'Invalid stop hour/minute found';
} } elseif (! $stophour) {
else if (!$stophour) { $warnMsg[] = 'Invalid stop hour found';
$warnMsg[] = "Invalid stop hour found"; } elseif (! $stopmin) {
} $warnMsg[] = 'Invalid stop min found';
else if (!$stopmin) { } else {
$warnMsg[] = "Invalid stop min found";
}
else {
$stophour = (int) $this->data['stop_hour']; $stophour = (int) $this->data['stop_hour'];
$stopmin = (int) $this->data['stop_min']; $stopmin = (int) $this->data['stop_min'];
if ($stophour == 0 && $stopmin == 0) { if ($stophour == 0 && $stopmin == 0) {
$warnMsg[] = "Invalid stop hour/minute found"; $warnMsg[] = 'Invalid stop hour/minute found';
} }
} }
$validHourMin = ($stophour == 0 && $stopmin == 0) ? false : true; $validHourMin = ($stophour == 0 && $stopmin == 0) ? false : true;
if (! $validHourMin) { if (! $validHourMin) {
$warnMsg[] = "Invalid stop hour/minute found"; $warnMsg[] = 'Invalid stop hour/minute found';
} }
$fromDate = $this->data['from_datetime']; $fromDate = $this->data['from_datetime'];
$toDate = $this->data['to_datetime']; $toDate = $this->data['to_datetime'];
@@ -201,7 +203,7 @@ class ProductionLineStopImporter extends Importer
$user = User::where('name', $this->data['operator_id'])->first(); $user = User::where('name', $this->data['operator_id'])->first();
if (! $user) { if (! $user) {
$warnMsg[] = "Operator ID not found"; $warnMsg[] = 'Operator ID not found';
} }
if (! empty($warnMsg)) { if (! empty($warnMsg)) {
@@ -219,6 +221,7 @@ class ProductionLineStopImporter extends Importer
'stop_min' => (int) $this->data['stop_min'], 'stop_min' => (int) $this->data['stop_min'],
'operator_id' => $this->data['operator_id'], 'operator_id' => $this->data['operator_id'],
]); ]);
return null; return null;
// return ProductionLineStop::firstOrNew([ // return ProductionLineStop::firstOrNew([
// // Update existing records, matching them by `$this->data['column_name']` // // Update existing records, matching them by `$this->data['column_name']`

View File

@@ -65,10 +65,10 @@ class ProductionPlanImporter extends Importer
->rules(['required']), ->rules(['required']),
ImportColumn::make('plant') ImportColumn::make('plant')
->requiredMapping() ->requiredMapping()
->exampleHeader('Plant Name') ->exampleHeader('Plant Code')
->example(['Ransar Industries-I', 'Ransar Industries-I']) ->example(['1000', '1000'])
->label('Plant Name') ->label('Plant Code')
->relationship(resolveUsing:'name') ->relationship(resolveUsing: 'code')
->rules(['required']), ->rules(['required']),
ImportColumn::make('updated_at') ImportColumn::make('updated_at')
->requiredMapping() ->requiredMapping()
@@ -88,36 +88,45 @@ class ProductionPlanImporter extends Importer
public function resolveRecord(): ?ProductionPlan public function resolveRecord(): ?ProductionPlan
{ {
$warnMsg = []; $warnMsg = [];
$plant = Plant::where('name', $this->data['plant'])->first(); $plantCod = $this->data['plant'];
$plant = null;
$line = null; $line = null;
$block = null; $block = null;
if (!$plant) {
$warnMsg[] = "Plant not found"; 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();
} }
else {
if (! $plant) {
$warnMsg[] = 'Plant not found';
} else {
$line = Line::where('name', $this->data['line'])->where('plant_id', $plant->id)->first(); $line = Line::where('name', $this->data['line'])->where('plant_id', $plant->id)->first();
// block_reference // block_reference
$block = Block::where('name', $this->data['block_reference'])->where('plant_id', $plant->id)->first(); $block = Block::where('name', $this->data['block_reference'])->where('plant_id', $plant->id)->first();
} }
if (! $line) { if (! $line) {
$warnMsg[] = "Line not found"; $warnMsg[] = 'Line not found';
} }
$shift = null; $shift = null;
if (! $block) { if (! $block) {
$warnMsg[] = "Block not found"; $warnMsg[] = 'Block not found';
} } elseif ($plant) {
else {
$shift = Shift::where('name', $this->data['shift'])->where('plant_id', $plant->id)->where('block_id', $block->id)->first(); $shift = Shift::where('name', $this->data['shift'])->where('plant_id', $plant->id)->where('block_id', $block->id)->first();
} }
// $shift = Shift::where('id', $this->data['shift'])->where('plant_id', $plant->id)->first(); // $shift = Shift::where('id', $this->data['shift'])->where('plant_id', $plant->id)->first();
if (! $shift) { if (! $shift) {
$warnMsg[] = "Shift not found"; $warnMsg[] = 'Shift not found';
} }
if (Str::length($this->data['plan_quantity']) < 0 || ! is_numeric($this->data['plan_quantity']) || $this->data['plan_quantity'] <= 0) { if (Str::length($this->data['plan_quantity']) < 0 || ! is_numeric($this->data['plan_quantity']) || $this->data['plan_quantity'] <= 0) {
$warnMsg[] = "Invalid plan quantity found"; $warnMsg[] = 'Invalid plan quantity found';
} }
if (Str::length($this->data['production_quantity']) < 0 || ! is_numeric($this->data['production_quantity']) || $this->data['production_quantity'] < 0) { if (Str::length($this->data['production_quantity']) < 0 || ! is_numeric($this->data['production_quantity']) || $this->data['production_quantity'] < 0) {
$warnMsg[] = "Invalid production quantity found"; $warnMsg[] = 'Invalid production quantity found';
} }
$fromDate = $this->data['created_at']; $fromDate = $this->data['created_at'];
@@ -152,8 +161,7 @@ class ProductionPlanImporter extends Importer
if (! isset($fdateTime)) { if (! isset($fdateTime)) {
// throw new \Exception('Invalid date time format'); // throw new \Exception('Invalid date time format');
$warnMsg[] = "Invalid 'Created DateTime' format. Expected DD-MM-YYYY HH:MM:SS"; $warnMsg[] = "Invalid 'Created DateTime' format. Expected DD-MM-YYYY HH:MM:SS";
} } else {
else {
$fDateOnly = $fdateTime->toDateString(); $fDateOnly = $fdateTime->toDateString();
} }
if (! isset($tdateTime)) { if (! isset($tdateTime)) {
@@ -175,13 +183,12 @@ class ProductionPlanImporter extends Importer
$user = User::where('name', $this->data['operator_id'])->first(); $user = User::where('name', $this->data['operator_id'])->first();
if (! $user) { if (! $user) {
$warnMsg[] = "Operator ID not found"; $warnMsg[] = 'Operator ID not found';
} }
if (! empty($warnMsg)) { if (! empty($warnMsg)) {
throw new RowImportFailedException(implode(', ', $warnMsg)); throw new RowImportFailedException(implode(', ', $warnMsg));
} } else { // if (empty($warnMsg))
else { //if (empty($warnMsg))
$productionPlan = ProductionPlan::where('plant_id', $plant->id) $productionPlan = ProductionPlan::where('plant_id', $plant->id)
->where('shift_id', $shift->id) ->where('shift_id', $shift->id)
->where('line_id', $line->id) ->where('line_id', $line->id)
@@ -205,6 +212,7 @@ class ProductionPlanImporter extends Importer
'operator_id' => $this->data['operator_id'], 'operator_id' => $this->data['operator_id'],
]); ]);
$productionPlan->save(); $productionPlan->save();
return null; return null;
} }
} }
@@ -219,6 +227,7 @@ class ProductionPlanImporter extends Importer
'updated_at' => $tdateTime->format('Y-m-d H:i:s'), // $this->data['updated_at'], 'updated_at' => $tdateTime->format('Y-m-d H:i:s'), // $this->data['updated_at'],
'operator_id' => $this->data['operator_id'], 'operator_id' => $this->data['operator_id'],
]); ]);
return null; return null;
// return ProductionPlan::firstOrNew([ // return ProductionPlan::firstOrNew([
// // Update existing records, matching them by `$this->data['column_name']` // // Update existing records, matching them by `$this->data['column_name']`

View File

@@ -59,9 +59,9 @@ class ProductionQuantityImporter extends Importer
->rules(['required']), ->rules(['required']),
ImportColumn::make('block_reference') ImportColumn::make('block_reference')
->requiredMapping() // Or optionalMapping() if not always present ->requiredMapping() // Or optionalMapping() if not always present
->exampleHeader('Block') ->exampleHeader('Block Name')
->example(['Block A', 'Block A']) ->example(['Block A', 'Block A'])
->label('Block') ->label('Block Name')
->rules(['required']), // Or remove if not required ->rules(['required']), // Or remove if not required
ImportColumn::make('shift') ImportColumn::make('shift')
->requiredMapping() ->requiredMapping()
@@ -72,10 +72,10 @@ class ProductionQuantityImporter extends Importer
->rules(['required']), ->rules(['required']),
ImportColumn::make('plant') ImportColumn::make('plant')
->requiredMapping() ->requiredMapping()
->exampleHeader('Plant Name') ->exampleHeader('Plant Code')
->example(['Ransar Industries-I', 'Ransar Industries-I']) ->example(['1000', '1000'])
->label('Plant Name') ->label('Plant Code')
->relationship(resolveUsing:'name') ->relationship(resolveUsing: 'code')
->rules(['required']), ->rules(['required']),
ImportColumn::make('updated_at') ImportColumn::make('updated_at')
->requiredMapping() ->requiredMapping()
@@ -95,43 +95,51 @@ class ProductionQuantityImporter extends Importer
public function resolveRecord(): ?ProductionQuantity public function resolveRecord(): ?ProductionQuantity
{ {
$warnMsg = []; $warnMsg = [];
$plant = Plant::where('name', $this->data['plant'])->first(); $plantCod = $this->data['plant'];
$plant = null;
$line = null; $line = null;
$block = null; $block = null;
if (!$plant) { $shift = null;
$warnMsg[] = "Plant not found"; 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();
} }
else {
if (! $plant) {
$warnMsg[] = 'Plant not found';
} else {
$line = Line::where('name', $this->data['line'])->where('plant_id', $plant->id)->first(); $line = Line::where('name', $this->data['line'])->where('plant_id', $plant->id)->first();
// block_reference // block_reference
$block = Block::where('name', $this->data['block_reference'])->where('plant_id', $plant->id)->first(); $block = Block::where('name', $this->data['block_reference'])->where('plant_id', $plant->id)->first();
} }
if (! $line) { if (! $line) {
$warnMsg[] = "Line not found"; $warnMsg[] = 'Line not found';
} }
$shift = null;
if (! $block) { if (! $block) {
$warnMsg[] = "Block not found"; $warnMsg[] = 'Block not found';
} } elseif ($plant) {
else {
$shift = Shift::where('name', $this->data['shift'])->where('plant_id', $plant->id)->where('block_id', $block->id)->first(); $shift = Shift::where('name', $this->data['shift'])->where('plant_id', $plant->id)->where('block_id', $block->id)->first();
} }
// $shift = Shift::where('id', $this->data['shift'])->where('plant_id', $plant->id)->first(); // $shift = Shift::where('id', $this->data['shift'])->where('plant_id', $plant->id)->first();
if (! $shift) { if (! $shift) {
$warnMsg[] = "Shift not found"; $warnMsg[] = 'Shift not found';
} }
$item = null; $item = null;
if ($plant) { if ($plant) {
$item = Item::where('code', $this->data['item'])->where('plant_id', $plant->id)->first(); $item = Item::where('code', $this->data['item'])->where('plant_id', $plant->id)->first();
} }
if (! $item) { if (! $item) {
$warnMsg[] = "Item not found"; $warnMsg[] = 'Item not found';
} }
if (Str::length($this->data['serial_number']) < 9 || ! ctype_alnum($this->data['serial_number'])) { if (Str::length($this->data['serial_number']) < 9 || ! ctype_alnum($this->data['serial_number'])) {
$warnMsg[] = "Invalid serial number found"; $warnMsg[] = 'Invalid serial number found';
} }
if (Str::length($this->data['production_order']) > 0 && (Str::length($this->data['production_order']) < 7 || Str::length($this->data['production_order']) > 14 || ! is_numeric($this->data['production_order']))) { if (Str::length($this->data['production_order']) > 0 && (Str::length($this->data['production_order']) < 7 || Str::length($this->data['production_order']) > 14 || ! is_numeric($this->data['production_order']))) {
$warnMsg[] = "Invalid production order found"; $warnMsg[] = 'Invalid production order found';
} }
$fromDate = $this->data['created_at']; $fromDate = $this->data['created_at'];
@@ -188,20 +196,19 @@ class ProductionQuantityImporter extends Importer
$user = User::where('name', $this->data['operator_id'])->first(); $user = User::where('name', $this->data['operator_id'])->first();
if (! $user) { if (! $user) {
$warnMsg[] = "Operator ID not found"; $warnMsg[] = 'Operator ID not found';
} }
if (! empty($warnMsg)) { if (! empty($warnMsg)) {
throw new RowImportFailedException(implode(', ', $warnMsg)); throw new RowImportFailedException(implode(', ', $warnMsg));
} } else { // if (empty($warnMsg))
else { //if (empty($warnMsg))
$productionQuan = ProductionQuantity::where('plant_id', $plant->id) $productionQuan = ProductionQuantity::where('plant_id', $plant->id)
->where('serial_number', $this->data['serial_number']) ->where('serial_number', $this->data['serial_number'])
->latest() ->latest()
->first(); ->first();
if ($productionQuan) { if ($productionQuan) {
throw new RowImportFailedException("Serial number already exist!"); throw new RowImportFailedException('Serial number already exist!');
} }
} }
@@ -216,6 +223,7 @@ class ProductionQuantityImporter extends Importer
'updated_at' => $tdateTime->format('Y-m-d H:i:s'), // $this->data['updated_at'], 'updated_at' => $tdateTime->format('Y-m-d H:i:s'), // $this->data['updated_at'],
'operator_id' => $this->data['operator_id'], 'operator_id' => $this->data['operator_id'],
]); ]);
// ProductionQuantity::updateOrCreate([ // ProductionQuantity::updateOrCreate([
// 'serial_number' => $this->data['serial_number'], // 'serial_number' => $this->data['serial_number'],
// 'plant_id' => $plant->id, // 'plant_id' => $plant->id,
@@ -259,7 +267,7 @@ class ProductionQuantityImporter extends Importer
'line_id' => $this->resolveLineId($row['line']), 'line_id' => $this->resolveLineId($row['line']),
'shift_id' => $this->resolveShiftId($row['shift']), 'shift_id' => $this->resolveShiftId($row['shift']),
'plant_id' => $this->resolvePlantId($row['plant']), 'plant_id' => $this->resolvePlantId($row['plant']),
'updated_at' => $row['updated_at'] 'updated_at' => $row['updated_at'],
]); ]);
} finally { } finally {
// Always disable flag even if errors occur // Always disable flag even if errors occur

View File

@@ -14,7 +14,6 @@ use Filament\Actions\Imports\ImportColumn;
use Filament\Actions\Imports\Importer; use Filament\Actions\Imports\Importer;
use Filament\Actions\Imports\Models\Import; use Filament\Actions\Imports\Models\Import;
use Filament\Facades\Filament; use Filament\Facades\Filament;
use Illuminate\Validation\Rule;
use Str; use Str;
class QualityValidationImporter extends Importer class QualityValidationImporter extends Importer
@@ -101,6 +100,11 @@ class QualityValidationImporter extends Importer
->exampleHeader('Name Plate PumpSet') ->exampleHeader('Name Plate PumpSet')
->example('1') ->example('1')
->label('Name Plate PumpSet'), ->label('Name Plate PumpSet'),
ImportColumn::make('warranty_card')
->requiredMapping()
->exampleHeader('Warranty Card')
->example('1')
->label('Warranty Card'),
ImportColumn::make('tube_sticker_motor') ImportColumn::make('tube_sticker_motor')
->requiredMapping() ->requiredMapping()
->exampleHeader('Tube Sticker Motor') ->exampleHeader('Tube Sticker Motor')
@@ -116,11 +120,6 @@ class QualityValidationImporter extends Importer
->exampleHeader('Tube Sticker PumpSet') ->exampleHeader('Tube Sticker PumpSet')
->example('1') ->example('1')
->label('Tube Sticker PumpSet'), ->label('Tube Sticker PumpSet'),
ImportColumn::make('warranty_card')
->requiredMapping()
->exampleHeader('Warranty Card')
->example('1')
->label('Warranty Card'),
ImportColumn::make('part_validation1') ImportColumn::make('part_validation1')
->requiredMapping() ->requiredMapping()
->exampleHeader('Part Validation 1') ->exampleHeader('Part Validation 1')
@@ -160,10 +159,10 @@ class QualityValidationImporter extends Importer
->rules(['required']), ->rules(['required']),
ImportColumn::make('plant') ImportColumn::make('plant')
->requiredMapping() ->requiredMapping()
->exampleHeader('Plant Name') ->exampleHeader('Plant Code')
->example('Ransar Industries-I') ->example('1000')
->label('Plant Name') ->label('Plant Code')
->relationship(resolveUsing:'name') ->relationship(resolveUsing: 'code')
->rules(['required']), ->rules(['required']),
ImportColumn::make('updated_at') ImportColumn::make('updated_at')
->requiredMapping() ->requiredMapping()
@@ -183,13 +182,19 @@ class QualityValidationImporter extends Importer
public function resolveRecord(): ?QualityValidation public function resolveRecord(): ?QualityValidation
{ {
$warnMsg = []; $warnMsg = [];
$plant = Plant::where('name', $this->data['plant'])->first(); $plantCod = $this->data['plant'];
$plant = null;
$line = null; $line = null;
$stickMaster = null; $stickMaster = null;
if (!$plant) { if (Str::length($plantCod) < 4 || ! is_numeric($plantCod) || ! preg_match('/^[1-9]\d{3,}$/', $plantCod)) {
$warnMsg[] = "Plant not found"; $warnMsg[] = 'Invalid plant code found';
} else {
$plant = Plant::where('code', $plantCod)->first();
} }
else {
if (! $plant) {
$warnMsg[] = 'Plant not found';
} else {
$line = Line::where('name', $this->data['line'])->where('plant_id', $plant->id)->first(); $line = Line::where('name', $this->data['line'])->where('plant_id', $plant->id)->first();
$uniqueCode = trim($this->data['sticker_master_id_code']); // stickerMaster.item $uniqueCode = trim($this->data['sticker_master_id_code']); // stickerMaster.item
$stickMaster = StickerMaster::select('id')->with('item') $stickMaster = StickerMaster::select('id')->with('item')
@@ -199,19 +204,19 @@ class QualityValidationImporter extends Importer
} }
if (! $line) { if (! $line) {
$warnMsg[] = "Line not found"; $warnMsg[] = 'Line not found';
} }
if (! $stickMaster) { if (! $stickMaster) {
$warnMsg[] = "Sticker item code not found"; $warnMsg[] = 'Sticker item code not found';
} }
if (! is_numeric($this->data['production_order']) || Str::length($this->data['production_order']) < 7 || Str::length($this->data['production_order']) > 14) { if (! is_numeric($this->data['production_order']) || Str::length($this->data['production_order']) < 7 || Str::length($this->data['production_order']) > 14) {
$warnMsg[] = "Invalid production order found"; $warnMsg[] = 'Invalid production order found';
} }
if (! ctype_alnum($this->data['serial_number']) || Str::length($this->data['serial_number']) < 9) { if (! ctype_alnum($this->data['serial_number']) || Str::length($this->data['serial_number']) < 9) {
$warnMsg[] = "Invalid serial number found"; $warnMsg[] = 'Invalid serial number found';
} }
// dd($stickMaster); // dd($stickMaster);
@@ -221,7 +226,7 @@ class QualityValidationImporter extends Importer
$user = User::where('name', $this->data['operator_id'])->first(); $user = User::where('name', $this->data['operator_id'])->first();
if (! $user) { if (! $user) {
$warnMsg[] = "Operator ID not found"; $warnMsg[] = 'Operator ID not found';
} }
$fromDate = $this->data['created_at']; $fromDate = $this->data['created_at'];
$toDate = $this->data['updated_at']; $toDate = $this->data['updated_at'];
@@ -282,7 +287,7 @@ class QualityValidationImporter extends Importer
QualityValidation::updateOrCreate([ QualityValidation::updateOrCreate([
'plant_id' => $plant->id, 'plant_id' => $plant->id,
'sticker_master_id' => $stickMaster, // ->id 'sticker_master_id' => $stickMaster, // ->id
'serial_number' => $this->data['serial_number'] 'serial_number' => $this->data['serial_number'],
], ],
[ [
'line_id' => $line->id, 'line_id' => $line->id,

View File

@@ -135,51 +135,47 @@ class ReworkLocatorInvoiceValidationImporter extends Importer
$reworkedBy = $this->data['reworked_by']; $reworkedBy = $this->data['reworked_by'];
if (Str::length($plantCod) < 4 || ! is_numeric($plantCod) || ! preg_match('/^[1-9]\d{3,}$/', $plantCod)) { if (Str::length($plantCod) < 4 || ! is_numeric($plantCod) || ! preg_match('/^[1-9]\d{3,}$/', $plantCod)) {
$warnMsg[] = "Invalid plant code found"; $warnMsg[] = 'Invalid plant code found';
} } else {
else $plant = Plant::where('code', $plantCod)->first();
{
$plant = Plant::where('code', $this->data['plant'])->first();
if (! $plant) { if (! $plant) {
$warnMsg[] = "Plant not found"; $warnMsg[] = 'Plant not found';
} } else {
else
{
if (Str::length($invoiceNo) < 5 || ! ctype_alnum($invoiceNo)) { if (Str::length($invoiceNo) < 5 || ! ctype_alnum($invoiceNo)) {
$warnMsg[] = "Invalid invoice number found"; $warnMsg[] = 'Invalid invoice number found';
} }
if (Str::length($serialNo) < 9 || Str::length($serialNo) > 20 || ! ctype_alnum($serialNo)) { if (Str::length($serialNo) < 9 || Str::length($serialNo) > 20 || ! ctype_alnum($serialNo)) {
$warnMsg[] = "Invalid serial number found"; $warnMsg[] = 'Invalid serial number found';
} }
if (Str::length($palletNo) > 0 && Str::length($palletNo) < 10) { if (Str::length($palletNo) > 0 && Str::length($palletNo) < 10) {
$warnMsg[] = "Invalid pallet number found"; $warnMsg[] = 'Invalid pallet number found';
} }
if (Str::length($locatorNo) > 0 && Str::length($locatorNo) < 7) { if (Str::length($locatorNo) > 0 && Str::length($locatorNo) < 7) {
$warnMsg[] = "Invalid locator number found"; $warnMsg[] = 'Invalid locator number found';
} }
if ($scannedStat != 'Scanned') { if ($scannedStat != 'Scanned') {
$warnMsg[] = "Invalid scanned status found"; $warnMsg[] = 'Invalid scanned status found';
} }
if ($uploadStat != 'Y' && $uploadStat != 'N') { if ($uploadStat != 'Y' && $uploadStat != 'N') {
$warnMsg[] = "Invalid upload status found"; $warnMsg[] = 'Invalid upload status found';
} }
$created = User::where('name', $createdBy)->first(); $created = User::where('name', $createdBy)->first();
if (! $created) { if (! $created) {
$warnMsg[] = "Created by not found"; $warnMsg[] = 'Created by not found';
} }
$scanned = User::where('name', $scannedBy)->first(); $scanned = User::where('name', $scannedBy)->first();
if (! $scanned) { if (! $scanned) {
$warnMsg[] = "Scanned by not found"; $warnMsg[] = 'Scanned by not found';
} }
if (Str::length($updatedBy) > 0) { if (Str::length($updatedBy) > 0) {
$updated = User::where('name', $updatedBy)->first(); $updated = User::where('name', $updatedBy)->first();
if (! $updated) { if (! $updated) {
$warnMsg[] = "Updated by not found"; $warnMsg[] = 'Updated by not found';
} }
} }
$reworked = User::where('name', $reworkedBy)->first(); $reworked = User::where('name', $reworkedBy)->first();
if (! $reworked) { if (! $reworked) {
$warnMsg[] = "Reworked by not found"; $warnMsg[] = 'Reworked by not found';
} }
$formats = ['d-m-Y H:i', 'd-m-Y H:i:s']; // '07-05-2025 08:00' or '07-05-2025 08:00:00' $formats = ['d-m-Y H:i', 'd-m-Y H:i:s']; // '07-05-2025 08:00' or '07-05-2025 08:00:00'
@@ -225,9 +221,7 @@ class ReworkLocatorInvoiceValidationImporter extends Importer
if (! isset($uDateTime)) { if (! isset($uDateTime)) {
$warnMsg[] = "Invalid 'Updated DateTime' format. Expected DD-MM-YYYY HH:MM:SS"; $warnMsg[] = "Invalid 'Updated DateTime' format. Expected DD-MM-YYYY HH:MM:SS";
} } else {
else
{
if (isset($cDateTime) && isset($uDateTime)) { if (isset($cDateTime) && isset($uDateTime)) {
if ($cDateTime->greaterThan($uDateTime)) { if ($cDateTime->greaterThan($uDateTime)) {
$warnMsg[] = "'Created DataTime' is greater than 'Updated DateTime'."; $warnMsg[] = "'Created DataTime' is greater than 'Updated DateTime'.";
@@ -247,9 +241,7 @@ class ReworkLocatorInvoiceValidationImporter extends Importer
if (! isset($rDateTime)) { if (! isset($rDateTime)) {
$warnMsg[] = "Invalid 'Reworked DateTime' format. Expected DD-MM-YYYY HH:MM:SS"; $warnMsg[] = "Invalid 'Reworked DateTime' format. Expected DD-MM-YYYY HH:MM:SS";
} } else {
else
{
if (isset($cDateTime) && isset($rDateTime)) { if (isset($cDateTime) && isset($rDateTime)) {
if ($cDateTime->greaterThan($rDateTime)) { if ($cDateTime->greaterThan($rDateTime)) {
$warnMsg[] = "'Created DataTime' is greater than 'Reworked DateTime'."; $warnMsg[] = "'Created DataTime' is greater than 'Reworked DateTime'.";
@@ -283,9 +275,10 @@ class ReworkLocatorInvoiceValidationImporter extends Importer
'created_by' => $createdBy, 'created_by' => $createdBy,
'scanned_by' => $scannedBy, 'scanned_by' => $scannedBy,
'updated_by' => $updatedBy, 'updated_by' => $updatedBy,
'reworked_by' => $reworkedBy 'reworked_by' => $reworkedBy,
] ]
); );
return null; return null;
// // return ReworkLocatorInvoiceValidation::firstOrNew([ // // return ReworkLocatorInvoiceValidation::firstOrNew([
// // // Update existing records, matching them by `$this->data['column_name']` // // // Update existing records, matching them by `$this->data['column_name']`

View File

@@ -52,10 +52,10 @@ class ShiftImporter extends Importer
->rules(['required']), ->rules(['required']),
ImportColumn::make('plant') ImportColumn::make('plant')
->requiredMapping() ->requiredMapping()
->exampleHeader('Plant Name') ->exampleHeader('Plant Code')
->example('Ransar Industries-I') ->example('1000')
->label('Plant Name') ->label('Plant Code')
->relationship(resolveUsing:'name') ->relationship(resolveUsing: 'code')
->rules(['required']), ->rules(['required']),
ImportColumn::make('status') ImportColumn::make('status')
->requiredMapping() ->requiredMapping()
@@ -69,25 +69,35 @@ class ShiftImporter extends Importer
public function resolveRecord(): ?Shift public function resolveRecord(): ?Shift
{ {
$warnMsg = []; $warnMsg = [];
$plant = Plant::where('name', $this->data['plant'])->first(); $plantCod = $this->data['plant'];
if (!$plant) { $plant = null;
$warnMsg[] = "Plant not found"; $block = 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';
} else {
$block = Block::where('name', $this->data['block'])->where('plant_id', $plant->id)->first(); $block = Block::where('name', $this->data['block'])->where('plant_id', $plant->id)->first();
}
if (! $block) { if (! $block) {
$warnMsg[] = "Block not found"; $warnMsg[] = 'Block not found';
} }
if (Str::length($this->data['duration']) < 0 || ! is_numeric($this->data['duration'])) { if (Str::length($this->data['duration']) < 0 || ! is_numeric($this->data['duration'])) {
$warnMsg[] = "Invalid duration found"; $warnMsg[] = 'Invalid duration found';
} }
if (Str::length($this->data['start_time']) < 0) { if (Str::length($this->data['start_time']) < 0) {
$warnMsg[] = "Invalid start time found"; $warnMsg[] = 'Invalid start time found';
} }
if (Str::length($this->data['end_time']) < 0) { if (Str::length($this->data['end_time']) < 0) {
$warnMsg[] = "Invalid end time found"; $warnMsg[] = 'Invalid end time found';
} }
if (Str::length($this->data['status']) < 0 || $this->data['status'] != 'Active') { if (Str::length($this->data['status']) < 0 || $this->data['status'] != 'Active') {
$warnMsg[] = "Invalid shift status found"; $warnMsg[] = 'Invalid shift status found';
} }
if (! empty($warnMsg)) { if (! empty($warnMsg)) {
@@ -105,8 +115,9 @@ class ShiftImporter extends Importer
'start_time' => $this->data['start_time'], 'start_time' => $this->data['start_time'],
'duration' => $this->data['duration'], 'duration' => $this->data['duration'],
'end_time' => $this->data['end_time'], 'end_time' => $this->data['end_time'],
'status' => $this->data['status'] 'status' => $this->data['status'],
]); ]);
return $shift; return $shift;
} else { } else {
// Safe to create new // Safe to create new
@@ -117,7 +128,7 @@ class ShiftImporter extends Importer
'start_time' => $this->data['start_time'], 'start_time' => $this->data['start_time'],
'duration' => $this->data['duration'], 'duration' => $this->data['duration'],
'end_time' => $this->data['end_time'], 'end_time' => $this->data['end_time'],
'status' => $this->data['status'] 'status' => $this->data['status'],
]); ]);
} }
// return Shift::firstOrNew([ // return Shift::firstOrNew([

View File

@@ -2,15 +2,14 @@
namespace App\Filament\Imports; namespace App\Filament\Imports;
use App\Models\Plant;
use App\Models\StickerPrinting; use App\Models\StickerPrinting;
use Filament\Actions\Imports\Exceptions\RowImportFailedException;
use Filament\Actions\Imports\ImportColumn; use Filament\Actions\Imports\ImportColumn;
use Filament\Actions\Imports\Importer; use Filament\Actions\Imports\Importer;
use Filament\Actions\Imports\Models\Import; use Filament\Actions\Imports\Models\Import;
use Filament\Actions\Imports\Exceptions\RowImportFailedException;
use App\Models\Plant;
use App\Models\User;
use Str;
use Filament\Facades\Filament; use Filament\Facades\Filament;
use Str;
class StickerPrintingImporter extends Importer class StickerPrintingImporter extends Importer
{ {
@@ -49,30 +48,26 @@ class StickerPrintingImporter extends Importer
// ]); // ]);
$warnMsg = []; $warnMsg = [];
$plant = Plant::where('code', $this->data['plant'])->first(); $plantCod = $this->data['plant'];
$plant = null;
if (Str::length($this->data['serial_number']) < 9 || !ctype_alnum($this->data['serial_number'])) {
$warnMsg[] = "Invalid serial number found";
}
$existing = StickerPrinting::where('plant_id', $plant->id)
->where('serial_number', $this->data['serial_number'])
->first();
if ($existing) {
$warnMsg[] = "Serial number already exists for this plant!";//throw new RowImportFailedException("Serial number already exists for this plant!");
}
$serial = $this->data['serial_number']; $serial = $this->data['serial_number'];
// --- Check duplicate in DB --- if (Str::length($plantCod) < 4 || ! is_numeric($plantCod) || ! preg_match('/^[1-9]\d{3,}$/', $plantCod)) {
$existsInDB = StickerPrinting::where('plant_id', $plant->id) $warnMsg[] = 'Invalid plant code found';
->where('serial_number', $serial) } else {
->first(); $plant = Plant::where('code', $plantCod)->first();
if (! $plant) {
$warnMsg[] = 'Plant not found!';
}
}
if ($existsInDB) { if (Str::length($serial) < 9 || ! ctype_alnum($serial)) {
//throw new RowImportFailedException("Serial number '{$serial}' already exists in DB for this plant!"); $warnMsg[] = 'Invalid serial number found';
$warnMsg[] = "Serial number '{$serial}' already exists in DB for this plant!"; } elseif ($plant) {
$existing = StickerPrinting::where('plant_id', $plant->id)->where('serial_number', $serial)->first();
if ($existing) {
$warnMsg[] = "Serial number '{$serial}' already exists for plant '{$plantCod}'!"; // throw new RowImportFailedException("Serial number already exists for this plant!");
}
} }
if (! empty($warnMsg)) { if (! empty($warnMsg)) {

View File

@@ -80,11 +80,17 @@ class TestingPanelReadingImporter extends Importer
->rules(['required']), ->rules(['required']),
ImportColumn::make('line') ImportColumn::make('line')
->requiredMapping() ->requiredMapping()
->relationship() ->relationship(resolveUsing: 'name')
->exampleHeader('Line Name')
->example(['4 inch pump line'])
->label('Line Name')
->rules(['required']), ->rules(['required']),
ImportColumn::make('plant') ImportColumn::make('plant')
->requiredMapping() ->requiredMapping()
->relationship() ->relationship(resolveUsing: 'code')
->exampleHeader('Plant Code')
->example(['1000'])
->label('Plant Code')
->rules(['required']), ->rules(['required']),
ImportColumn::make('tested_by'), ImportColumn::make('tested_by'),
ImportColumn::make('updated_by'), ImportColumn::make('updated_by'),
@@ -101,7 +107,7 @@ class TestingPanelReadingImporter extends Importer
// 'email' => $this->data['email'], // 'email' => $this->data['email'],
// ]); // ]);
return new TestingPanelReading(); return new TestingPanelReading;
} }
public static function getCompletedNotificationBody(Import $import): string public static function getCompletedNotificationBody(Import $import): string

View File

@@ -54,31 +54,28 @@ class UserImporter extends Importer
public function resolveRecord(): ?User public function resolveRecord(): ?User
{ {
$warnMsg = []; $warnMsg = [];
$plantCod = $this->data['plant'];
$plant = null; $plant = null;
if (Str::length($this->data['plant']) > 0) { if (Str::length($plantCod) < 4 || ! is_numeric($plantCod) || ! preg_match('/^[1-9]\d{3,}$/', $plantCod)) {
if (Str::length($this->data['plant']) < 4 || !is_numeric($this->data['plant']) || !preg_match('/^[1-9]\d{3,}$/', $this->data['plant'])) { $warnMsg[] = 'Invalid plant code found!';
$warnMsg[] = "Invalid plant code found!"; } else {
} $plant = Plant::where('code', $plantCod)->first();
else {
$plant = Plant::where('code', $this->data['plant'])->first();
if (! $plant) { if (! $plant) {
$warnMsg[] = "Plant not found"; $warnMsg[] = 'Plant not found';
} } else {
else {
$plant = $plant->id ?? null; $plant = $plant->id ?? null;
} }
} }
}
if (Str::length($this->data['name']) < 1) { if (Str::length($this->data['name']) < 3) {
$warnMsg[] = "User name not found!"; $warnMsg[] = 'Invalid user name found!';
} }
// || !is_numeric($this->data['code']) || !preg_match('/^[1-9]\d{3,}$/', $this->data['code']) // || !is_numeric($this->data['code']) || !preg_match('/^[1-9]\d{3,}$/', $this->data['code'])
if (Str::length($this->data['email']) < 5) { if (Str::length($this->data['email']) < 5) {
$warnMsg[] = "Invalid email found!"; $warnMsg[] = 'Invalid email found!';
} }
if (Str::length($this->data['password']) < 3) { if (Str::length($this->data['password']) < 3) {
$warnMsg[] = "Invalid password found!"; $warnMsg[] = 'Invalid password found!';
} }
// Validate roles if provided // Validate roles if provided
$roles = []; $roles = [];
@@ -93,9 +90,8 @@ class UserImporter extends Importer
$warnMsg[] = "Role : '{$roleName}' does not exist!"; $warnMsg[] = "Role : '{$roleName}' does not exist!";
} }
} }
} } else {
else { $warnMsg[] = 'User roles not found!';
$warnMsg[] = "User roles not found!";
} }
if (! empty($warnMsg)) { if (! empty($warnMsg)) {

View File

@@ -75,10 +75,10 @@ class WeightValidationImporter extends Importer
->rules(['required']), ->rules(['required']),
ImportColumn::make('plant') ImportColumn::make('plant')
->requiredMapping() ->requiredMapping()
->exampleHeader('Plant Name') ->exampleHeader('Plant Code')
->example('Ransar Industries-I') ->example('1000')
->label('PLANT NAME') ->label('PLANT CODE')
->relationship(resolveUsing: 'name') ->relationship(resolveUsing: 'code')
->rules(['required']), ->rules(['required']),
ImportColumn::make('scanned_by') ImportColumn::make('scanned_by')
->requiredMapping() ->requiredMapping()
@@ -92,62 +92,75 @@ class WeightValidationImporter extends Importer
public function resolveRecord(): ?WeightValidation public function resolveRecord(): ?WeightValidation
{ {
$warnMsg = []; $warnMsg = [];
$plant = Plant::where('name', $this->data['plant'])->first(); $plantCod = $this->data['plant'];
$iCode = $this->data['item'];
$plantId = null;
$itemId = 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) { if (! $plant) {
$warnMsg[] = "Plant not found"; $warnMsg[] = 'Plant not found';
} else {
$plantId = $plant->id;
} }
$item = null;
if ($plant) {
if (Str::length($this->data['item']) < 6 || !ctype_alnum($this->data['item'])) {
$warnMsg[] = "Invalid item code found";
} }
else
{ if (Str::length($iCode) < 6 || ! ctype_alnum($iCode)) {
$item = Item::where('code', $this->data['item'])->where('plant_id', $plant->id)->first(); $warnMsg[] = 'Invalid item code found';
if (!$item) { } else {
$warnMsg[] = "Item code not found"; $itemCode = Item::where('code', $iCode)->first();
if (! $itemCode) {
$warnMsg[] = 'Item code not found';
} else {
if ($plantId) {
$itemAgainstPlant = Item::where('code', $iCode)->where('plant_id', $plantId)->first();
if (! $itemAgainstPlant) {
$warnMsg[] = 'Item code not found for the given plant';
} else {
$itemId = $itemAgainstPlant->id;
} }
} }
} }
else { //if (!$item)
$warnMsg[] = "Item code not found";
} }
$obdNum = $this->data['obd_number']; $obdNum = $this->data['obd_number'];
if (Str::length($obdNum) < 8 || ! ctype_alnum($obdNum)) { if (Str::length($obdNum) < 8 || ! ctype_alnum($obdNum)) {
$warnMsg[] = "Invalid OBD number found"; $warnMsg[] = 'Invalid OBD number found';
} }
$lineNum = $this->data['line_number']; $lineNum = $this->data['line_number'];
if (Str::length($lineNum) < 1 || ! is_numeric($lineNum)) { if (Str::length($lineNum) < 1 || ! is_numeric($lineNum)) {
$warnMsg[] = "Invalid line number found"; $warnMsg[] = 'Invalid line number found';
} }
$batchNum = $this->data['batch_number']; $batchNum = $this->data['batch_number'];
if (Str::length($batchNum) < 8 || ! is_numeric($batchNum)) { if (Str::length($batchNum) < 8 || ! is_numeric($batchNum)) {
$warnMsg[] = "Invalid batch number found"; $warnMsg[] = 'Invalid batch number found';
} }
$heatNum = $this->data['heat_number']; $heatNum = $this->data['heat_number'];
if (Str::length($heatNum) < 4) { if (Str::length($heatNum) < 4) {
$warnMsg[] = "Invalid heat number found"; $warnMsg[] = 'Invalid heat number found';
} }
$actWeight = $this->data['obd_weight']; $actWeight = $this->data['obd_weight'];
if (Str::length($actWeight) < 1 || ! is_numeric($actWeight)) { if (Str::length($actWeight) < 1 || ! is_numeric($actWeight)) {
$warnMsg[] = "Invalid actual weight found"; $warnMsg[] = 'Invalid actual weight found';
} }
$vehicleNum = $this->data['vehicle_number']; $vehicleNum = $this->data['vehicle_number'];
if (Str::length($vehicleNum) < 10 || ! ctype_alnum($vehicleNum)) { if (Str::length($vehicleNum) < 10 || ! ctype_alnum($vehicleNum)) {
$warnMsg[] = "Invalid vehicle number found"; $warnMsg[] = 'Invalid vehicle number found';
} }
$bundleNum = $this->data['bundle_number']; $bundleNum = $this->data['bundle_number'];
if (Str::length($bundleNum) < 1 || ! is_numeric($bundleNum)) { if (Str::length($bundleNum) < 1 || ! is_numeric($bundleNum)) {
$warnMsg[] = "Invalid bundle number found"; $warnMsg[] = 'Invalid bundle number found';
} }
$pickWeight = $this->data['picked_weight']; $pickWeight = $this->data['picked_weight'];
if (Str::length($pickWeight) < 1 || ! is_numeric($pickWeight)) { if (Str::length($pickWeight) < 1 || ! is_numeric($pickWeight)) {
$warnMsg[] = "Invalid picked weight found"; $warnMsg[] = 'Invalid picked weight found';
} }
$scanBy = $this->data['scanned_by']; $scanBy = $this->data['scanned_by'];
if (Str::length($scanBy) < 3 || ! ctype_alnum($scanBy)) { if (Str::length($scanBy) < 3 || ! ctype_alnum($scanBy)) {
$warnMsg[] = "Invalid scanned by name found"; $warnMsg[] = 'Invalid scanned by name found';
} }
if (! empty($warnMsg)) { if (! empty($warnMsg)) {
@@ -155,19 +168,19 @@ class WeightValidationImporter extends Importer
} }
return WeightValidation::updateOrCreate([ return WeightValidation::updateOrCreate([
'plant_id' => $plant->id, 'plant_id' => $plantId,
'obd_number' => $obdNum, 'obd_number' => $obdNum,
'line_number' => $lineNum 'line_number' => $lineNum,
], ],
[ [
'item_id' => $item->id, 'item_id' => $itemId,
'batch_number' => $batchNum, 'batch_number' => $batchNum,
'heat_number' => $heatNum, 'heat_number' => $heatNum,
'obd_weight' => $actWeight, 'obd_weight' => $actWeight,
'vehicle_number' => $vehicleNum, 'vehicle_number' => $vehicleNum,
'bundle_number' => $bundleNum, 'bundle_number' => $bundleNum,
'picked_weight' => $pickWeight, 'picked_weight' => $pickWeight,
'scanned_by' => $scanBy 'scanned_by' => $scanBy,
] ]
); );
// return WeightValidation::firstOrNew([ // return WeightValidation::firstOrNew([

View File

@@ -20,22 +20,22 @@ class WorkGroupMasterImporter extends Importer
return [ return [
ImportColumn::make('plant') ImportColumn::make('plant')
->requiredMapping() ->requiredMapping()
->exampleHeader('Plant Name') ->exampleHeader('Plant Code')
->example('Ransar Industries-I') ->example('1000')
->label('Plant Name') ->label('Plant Code')
->relationship(resolveUsing:'name') ->relationship(resolveUsing: 'code')
->rules(['required']), ->rules(['required']),
ImportColumn::make('name') ImportColumn::make('name')
->requiredMapping() ->requiredMapping()
->exampleHeader('Name') ->exampleHeader('Work Group Name')
->example('RMGCEABC') ->example('RMGCEABC')
->label('Name') ->label('Work Group Name')
->rules(['required']), ->rules(['required']),
ImportColumn::make('description') ImportColumn::make('description')
->requiredMapping() ->requiredMapping()
->exampleHeader('Description') ->exampleHeader('Work Group Description')
->example('Testing Model 1') ->example('Testing Model 1')
->label('Description') ->label('Work Group Description')
->rules(['required']), ->rules(['required']),
ImportColumn::make('operation_number') ImportColumn::make('operation_number')
->requiredMapping() ->requiredMapping()
@@ -52,8 +52,6 @@ class WorkGroupMasterImporter extends Importer
]; ];
} }
public function resolveRecord(): ?WorkGroupMaster public function resolveRecord(): ?WorkGroupMaster
{ {
// return WorkGroupMaster::firstOrNew([ // return WorkGroupMaster::firstOrNew([
@@ -61,75 +59,81 @@ class WorkGroupMasterImporter extends Importer
// 'email' => $this->data['email'], // 'email' => $this->data['email'],
// ]); // ]);
$warnMsg = []; $warnMsg = [];
$plant = Plant::where('name', $this->data['plant'])->first(); $plantCod = $this->data['plant'];
$plantId = 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) { if (! $plant) {
$warnMsg[] = "Plant not found"; $warnMsg[] = 'Plant not found';
} else {
$plantId = $plant->id;
}
} }
if (Str::length($this->data['name']) <= 0) { // || !ctype_alnum($this->data['description']) if (Str::length($this->data['name']) <= 0) { // || !ctype_alnum($this->data['description'])
$warnMsg[] = "Invalid name found"; $warnMsg[] = 'Invalid work group name found';
} }
if (Str::length(trim($this->data['description'])) <= 0) { if (Str::length(trim($this->data['description'])) <= 0) {
$warnMsg[] = "Invalid description found"; $warnMsg[] = 'Invalid work group description found';
} }
$desc = trim($this->data['description']); $desc = trim($this->data['description']);
if (Str::length($desc) > 44) { if (Str::length($desc) > 44) {
$warnMsg[] = "Description should be less than 44 digits."; $warnMsg[] = ' work group description should be less than 44 digits.';
} }
if (Str::length($this->data['operation_number']) <= 0) { if (Str::length($this->data['operation_number']) <= 0) {
$warnMsg[] = "Invalid operation number found"; $warnMsg[] = 'Invalid operation number found';
} }
if(!is_numeric($this->data['operation_number'])) if (! is_numeric($this->data['operation_number'])) {
{ $warnMsg[] = 'Invalid operation number found must be numeric';
$warnMsg[] = "Invalid operation number found must be numeric";
} }
$user = User::where('name', $this->data['created_by'])->first(); $user = User::where('name', $this->data['created_by'])->first();
if (! $user) { if (! $user) {
$warnMsg[] = "Operator ID not found"; $warnMsg[] = 'Operator ID not found';
} }
if (! empty($warnMsg)) { if (! empty($warnMsg)) {
throw new RowImportFailedException(implode(', ', $warnMsg)); throw new RowImportFailedException(implode(', ', $warnMsg));
} } else {
else
{
// Check (plant_id, name) // Check (plant_id, name)
$existingByName = WorkGroupMaster::where('plant_id', $plant->id) $existingByName = WorkGroupMaster::where('plant_id', $plantId)
->where('name', $this->data['name']) ->where('name', $this->data['name'])
->first(); ->first();
if ($existingByName) { if ($existingByName) {
throw new RowImportFailedException("Work group name already exists for this plant!"); throw new RowImportFailedException('Work group name already exists for this plant!');
} }
// Check (plant_id, operation_number) // Check (plant_id, operation_number)
$existingByOpNum = WorkGroupMaster::where('plant_id', $plant->id) $existingByOpNum = WorkGroupMaster::where('plant_id', $plantId)
->where('operation_number', $this->data['operation_number']) ->where('operation_number', $this->data['operation_number'])
->where('name', $this->data['name']) ->where('name', $this->data['name'])
->first(); ->first();
if ($existingByOpNum) { if ($existingByOpNum) {
throw new RowImportFailedException("Operation number already exists for this plant!"); throw new RowImportFailedException('Operation number already exists for this plant!');
} }
// Check (plant_id) // Check (plant_id)
$existingByOperator = WorkGroupMaster::where('plant_id', $plant->id) $existingByOperator = WorkGroupMaster::where('plant_id', $plantId)
->where('name', $this->data['name']) ->where('name', $this->data['name'])
->first(); ->first();
if ($existingByOperator) { if ($existingByOperator) {
throw new RowImportFailedException("Already work group name assigned to another plant!"); throw new RowImportFailedException('Already work group name assigned to another plant!');
} }
} }
WorkGroupMaster::updateOrCreate([ WorkGroupMaster::updateOrCreate([
'plant_id' => $plant->id, 'plant_id' => $plantId,
'name' => $this->data['name'], 'name' => $this->data['name'],
'description' => $this->data['description'], 'description' => $this->data['description'],
'operation_number' => $this->data['operation_number'], 'operation_number' => $this->data['operation_number'],

View File

@@ -5,26 +5,25 @@ namespace App\Filament\Resources;
use App\Filament\Exports\CharacteristicValueExporter; use App\Filament\Exports\CharacteristicValueExporter;
use App\Filament\Imports\CharacteristicValueImporter; use App\Filament\Imports\CharacteristicValueImporter;
use App\Filament\Resources\CharacteristicValueResource\Pages; use App\Filament\Resources\CharacteristicValueResource\Pages;
use App\Filament\Resources\CharacteristicValueResource\RelationManagers;
use App\Models\CharacteristicValue; use App\Models\CharacteristicValue;
use App\Models\Item; use App\Models\Item;
use App\Models\Line; use App\Models\Line;
use App\Models\Machine; use App\Models\Machine;
use App\Models\Plant; use App\Models\Plant;
use Filament\Facades\Filament;
use Filament\Forms; use Filament\Forms;
use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Form; use Filament\Forms\Form;
use Filament\Resources\Resource; use Filament\Resources\Resource;
use Filament\Tables; use Filament\Tables;
use Filament\Tables\Actions\ExportAction;
use Filament\Tables\Actions\ImportAction;
use Filament\Tables\Filters\Filter;
use Filament\Tables\Table; use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope; use Illuminate\Database\Eloquent\SoftDeletingScope;
use Filament\Facades\Filament;
use Filament\Forms\Components\DateTimePicker;
use Filament\Tables\Filters\Filter;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Tables\Actions\ExportAction;
use Filament\Tables\Actions\ImportAction;
class CharacteristicValueResource extends Resource class CharacteristicValueResource extends Resource
{ {
@@ -192,7 +191,7 @@ class CharacteristicValueResource extends Resource
->label('Status') ->label('Status')
->options([ ->options([
'Ok' => 'OK', 'Ok' => 'OK',
'NotOk' => 'Not Ok' 'NotOk' => 'Not Ok',
]) ])
->reactive() ->reactive()
->required(), ->required(),
@@ -296,6 +295,7 @@ class CharacteristicValueResource extends Resource
->nullable() ->nullable()
->options(function (callable $get) { ->options(function (callable $get) {
$userHas = Filament::auth()->user()->plant_id; $userHas = Filament::auth()->user()->plant_id;
return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray();
}) })
->reactive() ->reactive()
@@ -368,7 +368,7 @@ class CharacteristicValueResource extends Resource
->label('Status') ->label('Status')
->options([ ->options([
'Ok' => 'OK', 'Ok' => 'OK',
'NotOk' => 'Not Ok' 'NotOk' => 'Not Ok',
]), ]),
DateTimePicker::make(name: 'created_from') DateTimePicker::make(name: 'created_from')
->label('Created From') ->label('Created From')
@@ -389,6 +389,12 @@ class CharacteristicValueResource extends Resource
if (! empty($data['Plant'])) { if (! empty($data['Plant'])) {
$query->where('plant_id', $data['Plant']); $query->where('plant_id', $data['Plant']);
} else {
$userHas = Filament::auth()->user()->plant_id;
if ($userHas && strlen($userHas) > 0) {
return $query->whereRaw('1 = 0');
}
} }
if (! empty($data['Line'])) { if (! empty($data['Line'])) {
@@ -423,7 +429,6 @@ class CharacteristicValueResource extends Resource
$query->where('created_at', '<=', $data['created_to']); $query->where('created_at', '<=', $data['created_to']);
} }
// $query->orderBy('created_at', 'asc'); // $query->orderBy('created_at', 'asc');
}) })
->indicateUsing(function (array $data) { ->indicateUsing(function (array $data) {
@@ -431,6 +436,12 @@ class CharacteristicValueResource extends Resource
if (! empty($data['Plant'])) { if (! empty($data['Plant'])) {
$indicators[] = 'Plant: '.Plant::where('id', $data['Plant'])->value('name'); $indicators[] = 'Plant: '.Plant::where('id', $data['Plant'])->value('name');
} else {
$userHas = Filament::auth()->user()->plant_id;
if ($userHas && strlen($userHas) > 0) {
return 'Plant: Choose plant to filter records.';
}
} }
if (! empty($data['Line'])) { if (! empty($data['Line'])) {
@@ -466,7 +477,7 @@ class CharacteristicValueResource extends Resource
} }
return $indicators; return $indicators;
}) }),
]) ])
->filtersFormMaxHeight('280px') ->filtersFormMaxHeight('280px')
->actions([ ->actions([

View File

@@ -5,23 +5,22 @@ namespace App\Filament\Resources;
use App\Filament\Exports\EbReadingExporter; use App\Filament\Exports\EbReadingExporter;
use App\Filament\Imports\EbReadingImporter; use App\Filament\Imports\EbReadingImporter;
use App\Filament\Resources\EbReadingResource\Pages; use App\Filament\Resources\EbReadingResource\Pages;
use App\Filament\Resources\EbReadingResource\RelationManagers;
use App\Models\EbReading; use App\Models\EbReading;
use App\Models\Plant; use App\Models\Plant;
use Filament\Facades\Filament;
use Filament\Forms; use Filament\Forms;
use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Form; use Filament\Forms\Form;
use Filament\Resources\Resource; use Filament\Resources\Resource;
use Filament\Tables; use Filament\Tables;
use Filament\Tables\Actions\ExportAction;
use Filament\Tables\Actions\ImportAction;
use Filament\Tables\Filters\Filter;
use Filament\Tables\Table; use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope; use Illuminate\Database\Eloquent\SoftDeletingScope;
use Filament\Tables\Actions\ImportAction;
use Filament\Tables\Actions\ExportAction;
use Filament\Facades\Filament;
use Filament\Tables\Filters\Filter;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\DateTimePicker;
class EbReadingResource extends Resource class EbReadingResource extends Resource
{ {
@@ -39,6 +38,7 @@ class EbReadingResource extends Resource
->relationship('plant', 'name') ->relationship('plant', 'name')
->options(function (callable $get) { ->options(function (callable $get) {
$userHas = Filament::auth()->user()->plant_id; $userHas = Filament::auth()->user()->plant_id;
return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray();
}) })
->required(), ->required(),
@@ -154,6 +154,7 @@ class EbReadingResource extends Resource
$paginator = $livewire->getTableRecords(); $paginator = $livewire->getTableRecords();
$perPage = method_exists($paginator, 'perPage') ? $paginator->perPage() : 10; $perPage = method_exists($paginator, 'perPage') ? $paginator->perPage() : 10;
$currentPage = method_exists($paginator, 'currentPage') ? $paginator->currentPage() : 1; $currentPage = method_exists($paginator, 'currentPage') ? $paginator->currentPage() : 1;
return ($currentPage - 1) * $perPage + $rowLoop->iteration; return ($currentPage - 1) * $perPage + $rowLoop->iteration;
}), }),
Tables\Columns\TextColumn::make('plant.name') Tables\Columns\TextColumn::make('plant.name')
@@ -334,6 +335,7 @@ class EbReadingResource extends Resource
// }) // })
->options(function (callable $get) { ->options(function (callable $get) {
$userHas = Filament::auth()->user()->plant_id; $userHas = Filament::auth()->user()->plant_id;
return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray();
}) })
->reactive() ->reactive()
@@ -361,6 +363,12 @@ class EbReadingResource extends Resource
if (! empty($data['Plant'])) { if (! empty($data['Plant'])) {
$query->where('plant_id', $data['Plant']); $query->where('plant_id', $data['Plant']);
} else {
$userHas = Filament::auth()->user()->plant_id;
if ($userHas && strlen($userHas) > 0) {
return $query->whereRaw('1 = 0');
}
} }
if (! empty($data['created_from'])) { if (! empty($data['created_from'])) {
@@ -381,6 +389,12 @@ class EbReadingResource extends Resource
if (! empty($data['Plant'])) { if (! empty($data['Plant'])) {
$indicators[] = 'Plant: '.Plant::where('id', $data['Plant'])->value('name'); $indicators[] = 'Plant: '.Plant::where('id', $data['Plant'])->value('name');
} else {
$userHas = Filament::auth()->user()->plant_id;
if ($userHas && strlen($userHas) > 0) {
return 'Plant: Choose plant to filter records.';
}
} }
if (! empty($data['electrician_sign'])) { if (! empty($data['electrician_sign'])) {
@@ -396,7 +410,7 @@ class EbReadingResource extends Resource
} }
return $indicators; return $indicators;
}) }),
]) ])
->filtersFormMaxHeight('280px') ->filtersFormMaxHeight('280px')
->actions([ ->actions([

View File

@@ -5,7 +5,6 @@ namespace App\Filament\Resources;
use App\Filament\Exports\GuardPatrolEntryExporter; use App\Filament\Exports\GuardPatrolEntryExporter;
use App\Filament\Imports\GuardPatrolEntryImporter; use App\Filament\Imports\GuardPatrolEntryImporter;
use App\Filament\Resources\GuardPatrolEntryResource\Pages; use App\Filament\Resources\GuardPatrolEntryResource\Pages;
use App\Filament\Resources\GuardPatrolEntryResource\RelationManagers;
use App\Models\CheckPointName; use App\Models\CheckPointName;
use App\Models\Configuration; use App\Models\Configuration;
use App\Models\GuardName; use App\Models\GuardName;
@@ -17,7 +16,6 @@ use Filament\Forms;
use Filament\Forms\Components\DateTimePicker; use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\FileUpload; use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\Select; use Filament\Forms\Components\Select;
use Filament\Forms\Components\Tabs\Tab;
use Filament\Forms\Components\TextInput; use Filament\Forms\Components\TextInput;
use Filament\Forms\Form; use Filament\Forms\Form;
use Filament\Forms\Get; use Filament\Forms\Get;
@@ -54,6 +52,7 @@ class GuardPatrolEntryResource extends Resource
->reactive() ->reactive()
->options(function (callable $get) { ->options(function (callable $get) {
$userHas = Filament::auth()->user()->plant_id; $userHas = Filament::auth()->user()->plant_id;
return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray();
}) })
->default(function () { ->default(function () {
@@ -65,10 +64,9 @@ class GuardPatrolEntryResource extends Resource
if (! $plantId) { if (! $plantId) {
// $set('gPePlantError', 'Please select a plant first.'); // $set('gPePlantError', 'Please select a plant first.');
$set('gPePlantError', 'Please select a plant first.'); $set('gPePlantError', 'Please select a plant first.');
return; return;
} } else {
else
{
$set('patrol_time', now()->format('Y-m-d H:i:s')); $set('patrol_time', now()->format('Y-m-d H:i:s'));
$set('updated_by', Filament::auth()->user()?->name); $set('updated_by', Filament::auth()->user()?->name);
$set('gPePlantError', null); $set('gPePlantError', null);
@@ -102,10 +100,9 @@ class GuardPatrolEntryResource extends Resource
$guardName = $get('guard_name_id'); $guardName = $get('guard_name_id');
if (! $guardName) { if (! $guardName) {
$set('gPeGuardNameError', 'Please select a guard name first.'); $set('gPeGuardNameError', 'Please select a guard name first.');
return; return;
} } else {
else
{
$set('patrol_time', now()->format('Y-m-d H:i:s')); $set('patrol_time', now()->format('Y-m-d H:i:s'));
$set('updated_by', Filament::auth()->user()?->name); $set('updated_by', Filament::auth()->user()?->name);
$set('gPeGuardNameError', null); $set('gPeGuardNameError', null);
@@ -150,10 +147,9 @@ class GuardPatrolEntryResource extends Resource
if (! $checkPointName) { if (! $checkPointName) {
$set('check_point_name_id', null); $set('check_point_name_id', null);
$set('gPeCheckPointNameError', 'Please select a check point name first.'); $set('gPeCheckPointNameError', 'Please select a check point name first.');
return; return;
} } else {
else
{
$set('patrol_time', now()->format('Y-m-d H:i:s')); $set('patrol_time', now()->format('Y-m-d H:i:s'));
$set('updated_by', Filament::auth()->user()?->name); $set('updated_by', Filament::auth()->user()?->name);
$set('gPeCheckPointNameError', null); $set('gPeCheckPointNameError', null);
@@ -176,8 +172,7 @@ class GuardPatrolEntryResource extends Resource
->hidden(fn (Get $get) => ! $get('id')) ->hidden(fn (Get $get) => ! $get('id'))
->reactive() ->reactive()
->afterStateUpdated(function ($state, callable $set, callable $get) { ->afterStateUpdated(function ($state, callable $set, callable $get) {
if(!$get('id')) if (! $get('id')) {
{
$set('patrol_time', now()->format('Y-m-d H:i:s')); $set('patrol_time', now()->format('Y-m-d H:i:s'));
} }
$set('updated_by', Filament::auth()->user()?->name); $set('updated_by', Filament::auth()->user()?->name);
@@ -225,6 +220,7 @@ class GuardPatrolEntryResource extends Resource
$paginator = $livewire->getTableRecords(); $paginator = $livewire->getTableRecords();
$perPage = method_exists($paginator, 'perPage') ? $paginator->perPage() : 10; $perPage = method_exists($paginator, 'perPage') ? $paginator->perPage() : 10;
$currentPage = method_exists($paginator, 'currentPage') ? $paginator->currentPage() : 1; $currentPage = method_exists($paginator, 'currentPage') ? $paginator->currentPage() : 1;
return ($currentPage - 1) * $perPage + $rowLoop->iteration; return ($currentPage - 1) * $perPage + $rowLoop->iteration;
}), }),
// Tables\Columns\TextColumn::make('id') // Tables\Columns\TextColumn::make('id')
@@ -288,6 +284,7 @@ class GuardPatrolEntryResource extends Resource
// }) // })
->options(function (callable $get) { ->options(function (callable $get) {
$userHas = Filament::auth()->user()->plant_id; $userHas = Filament::auth()->user()->plant_id;
return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray();
}) })
->reactive(), ->reactive(),
@@ -350,6 +347,12 @@ class GuardPatrolEntryResource extends Resource
if (! empty($data['Plant'])) { if (! empty($data['Plant'])) {
$query->where('plant_id', $data['Plant']); $query->where('plant_id', $data['Plant']);
} else {
$userHas = Filament::auth()->user()->plant_id;
if ($userHas && strlen($userHas) > 0) {
return $query->whereRaw('1 = 0');
}
} }
if (! empty($data['Guard Name'])) { if (! empty($data['Guard Name'])) {
@@ -377,6 +380,12 @@ class GuardPatrolEntryResource extends Resource
if (! empty($data['Plant'])) { if (! empty($data['Plant'])) {
$indicators[] = 'Plant: '.Plant::where('id', $data['Plant'])->value('name'); $indicators[] = 'Plant: '.Plant::where('id', $data['Plant'])->value('name');
} else {
$userHas = Filament::auth()->user()->plant_id;
if ($userHas && strlen($userHas) > 0) {
return 'Plant: Choose plant to filter records.';
}
} }
if (! empty($data['Guard Name'])) { if (! empty($data['Guard Name'])) {
@@ -400,7 +409,7 @@ class GuardPatrolEntryResource extends Resource
} }
return $indicators; return $indicators;
}) }),
]) ])
->filtersFormMaxHeight('280px') ->filtersFormMaxHeight('280px')
->actions([ ->actions([
@@ -422,6 +431,7 @@ class GuardPatrolEntryResource extends Resource
// ->options(Plant::pluck('name', 'id')->toArray()) // ->options(Plant::pluck('name', 'id')->toArray())
->options(function (callable $get) { ->options(function (callable $get) {
$userHas = Filament::auth()->user()->plant_id; $userHas = Filament::auth()->user()->plant_id;
return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray();
}) })
->label('Select Plant') ->label('Select Plant')
@@ -435,10 +445,9 @@ class GuardPatrolEntryResource extends Resource
$set('guard_patrol_entry', null); $set('guard_patrol_entry', null);
if (! $plantId) { if (! $plantId) {
$set('gPeSelectPlantError', 'Please select a plant first.'); $set('gPeSelectPlantError', 'Please select a plant first.');
return; return;
} } else {
else
{
$set('gPeSelectPlantError', null); $set('gPeSelectPlantError', null);
} }
}) })
@@ -482,21 +491,20 @@ class GuardPatrolEntryResource extends Resource
$folderPath = Configuration::where('c_name', 'GUARD_PATROL_ENTRY_FOLDER_PATH')->where('plant_id', $plantId)->value('c_value'); $folderPath = Configuration::where('c_name', 'GUARD_PATROL_ENTRY_FOLDER_PATH')->where('plant_id', $plantId)->value('c_value');
if(!$folderPath) if (! $folderPath) {
{
Notification::make() Notification::make()
->title('Upload Folder Path Not Found!') ->title('Upload Folder Path Not Found!')
->body('Please set the folder path in configuration for Guard Patrol Entry.') ->body('Please set the folder path in configuration for Guard Patrol Entry.')
->danger() ->danger()
->send(); ->send();
return; return;
} }
$fullFolderPath = "uploads/$folderPath"; $fullFolderPath = "uploads/$folderPath";
// Check if the folder exists, if not, create it // Check if the folder exists, if not, create it
if (!Storage::disk('local')->exists($fullFolderPath)) if (! Storage::disk('local')->exists($fullFolderPath)) {
{
Storage::disk('local')->makeDirectory($fullFolderPath); Storage::disk('local')->makeDirectory($fullFolderPath);
} }
@@ -504,12 +512,10 @@ class GuardPatrolEntryResource extends Resource
$fullPath = Storage::disk('local')->path($path); $fullPath = Storage::disk('local')->path($path);
if ($fullPath && file_exists($fullPath)) if ($fullPath && file_exists($fullPath)) {
{
$rows = Excel::toArray(null, $fullPath)[0]; $rows = Excel::toArray(null, $fullPath)[0];
if((count($rows) - 1) <= 0) if ((count($rows) - 1) <= 0) {
{
Notification::make() Notification::make()
->title('Invalid Guard Patrol Entry Found') ->title('Invalid Guard Patrol Entry Found')
->body('Uploaded excel sheet is empty or<br>contains no valid data.') ->body('Uploaded excel sheet is empty or<br>contains no valid data.')
@@ -519,6 +525,7 @@ class GuardPatrolEntryResource extends Resource
if ($disk->exists($path)) { if ($disk->exists($path)) {
$disk->delete($path); $disk->delete($path);
} }
return; return;
} }
@@ -529,9 +536,10 @@ class GuardPatrolEntryResource extends Resource
$invalidPatrolTimes = []; $invalidPatrolTimes = [];
$validRowsFound = false; $validRowsFound = false;
foreach ($rows as $index => $row) foreach ($rows as $index => $row) {
{ if ($index === 0) {
if ($index === 0) continue; // Skip header continue;
} // Skip header
$rowNumber = trim($row[0]); $rowNumber = trim($row[0]);
$guardName = trim($row[1]); $guardName = trim($row[1]);
@@ -539,21 +547,20 @@ class GuardPatrolEntryResource extends Resource
$readerCode = trim($row[3]); $readerCode = trim($row[3]);
$patrolTime = trim($row[4]); $patrolTime = trim($row[4]);
if (empty($rowNumber)) { continue; } if (empty($rowNumber)) {
continue;
}
if (empty($guardName) || empty($checkPointName) || empty($readerCode) || empty($patrolTime)) { if (empty($guardName) || empty($checkPointName) || empty($readerCode) || empty($patrolTime)) {
$invalidRows[] = $rowNumber; $invalidRows[] = $rowNumber;
continue; continue;
} } else {
else if (Str::length($guardName) < 3 || Str::length($checkPointName) < 3 || Str::length($readerCode) < 3 || Str::length($patrolTime) < 3) {
{
if(Str::length($guardName) < 3 || Str::length($checkPointName) < 3 || Str::length($readerCode) < 3 || Str::length($patrolTime) < 3)
{
$invalidGuardCheckPoints[] = $rowNumber; $invalidGuardCheckPoints[] = $rowNumber;
continue; continue;
} } else {
else
{
$isValidRow = true; $isValidRow = true;
$guardNames = GuardName::where('plant_id', $plantId)->where('name', $guardName)->first(); $guardNames = GuardName::where('plant_id', $plantId)->where('name', $guardName)->first();
if (! $guardNames) { if (! $guardNames) {
@@ -602,6 +609,7 @@ class GuardPatrolEntryResource extends Resource
if ($disk->exists($path)) { if ($disk->exists($path)) {
$disk->delete($path); $disk->delete($path);
} }
return; return;
} }
@@ -616,6 +624,7 @@ class GuardPatrolEntryResource extends Resource
if ($disk->exists($path)) { if ($disk->exists($path)) {
$disk->delete($path); $disk->delete($path);
} }
return; return;
} }
@@ -672,15 +681,17 @@ class GuardPatrolEntryResource extends Resource
if ($disk->exists($path)) { if ($disk->exists($path)) {
$disk->delete($path); $disk->delete($path);
} }
return; return;
} }
$validCnt = 0; $validCnt = 0;
$dupCnt = 0; $dupCnt = 0;
$validRowsFound = false; $validRowsFound = false;
foreach ($rows as $index => $row) foreach ($rows as $index => $row) {
{ if ($index === 0) {
if ($index === 0) continue; // Skip header continue;
} // Skip header
$rowNumber = trim($row[0]); $rowNumber = trim($row[0]);
$guardName = trim($row[1]); $guardName = trim($row[1]);
@@ -688,7 +699,9 @@ class GuardPatrolEntryResource extends Resource
$readerCode = trim($row[3]); $readerCode = trim($row[3]);
$patrolTime = trim($row[4]); $patrolTime = trim($row[4]);
if (empty($rowNumber)) { continue; } if (empty($rowNumber)) {
continue;
}
if (empty($guardName) || empty($checkPointName) || empty($readerCode) || empty($patrolTime)) { if (empty($guardName) || empty($checkPointName) || empty($readerCode) || empty($patrolTime)) {
continue; continue;
@@ -720,21 +733,20 @@ class GuardPatrolEntryResource extends Resource
if ($guardEntryFound) { if ($guardEntryFound) {
// $warnMsg[] = "Duplicate guard patrol entry found"; // $warnMsg[] = "Duplicate guard patrol entry found";
$dupCnt++; $dupCnt++;
continue; continue;
} } else {
else
{
$validCnt++; $validCnt++;
GuardPatrolEntry::updateOrCreate([ GuardPatrolEntry::updateOrCreate([
'plant_id' => $plantId, 'plant_id' => $plantId,
'guard_name_id' => $guardNames->id, 'guard_name_id' => $guardNames->id,
'check_point_name_id' => $checkPointNames->id, 'check_point_name_id' => $checkPointNames->id,
'patrol_time' => $patrolDateTime->format('Y-m-d H:i:s') 'patrol_time' => $patrolDateTime->format('Y-m-d H:i:s'),
], ],
[ [
'reader_code' => $readerCode, 'reader_code' => $readerCode,
'created_by' => $user, 'created_by' => $user,
'updated_by' => $user 'updated_by' => $user,
] ]
); );
$validRowsFound = true; $validRowsFound = true;
@@ -748,25 +760,19 @@ class GuardPatrolEntryResource extends Resource
->body("Uploaded excel sheet contains '{$dupCnt}' duplicate entries!<br>Please check the uploaded file and try again.") ->body("Uploaded excel sheet contains '{$dupCnt}' duplicate entries!<br>Please check the uploaded file and try again.")
->danger() ->danger()
->send(); ->send();
if ($disk->exists($path)) if ($disk->exists($path)) {
{
$disk->delete($path); $disk->delete($path);
} }
} } elseif ($validRowsFound && $validCnt > 0) {
else if ($validRowsFound && $validCnt > 0)
{
// session(['guard_patrol_entry_path' => $fullPath]); // session(['guard_patrol_entry_path' => $fullPath]);
Notification::make() Notification::make()
->title("Success: '{$validCnt}' guard patrol entries imported successfully.") ->title("Success: '{$validCnt}' guard patrol entries imported successfully.")
->success() ->success()
->send(); ->send();
if ($disk->exists($path)) if ($disk->exists($path)) {
{
$disk->delete($path); $disk->delete($path);
} }
} } else {
else
{
Notification::make() Notification::make()
->title('Failed: Something went wrong while uploading guard patrol entries!') ->title('Failed: Something went wrong while uploading guard patrol entries!')
->danger() ->danger()

View File

@@ -1181,6 +1181,12 @@ class InvoiceValidationResource extends Resource
if (! empty($data['Plant'])) { // $plant = $data['Plant'] ?? null if (! empty($data['Plant'])) { // $plant = $data['Plant'] ?? null
$query->where('plant_id', $data['Plant']); $query->where('plant_id', $data['Plant']);
} else {
$userHas = Filament::auth()->user()->plant_id;
if ($userHas && strlen($userHas) > 0) {
return $query->whereRaw('1 = 0');
}
} }
if (! empty($data['invoice_number'])) { if (! empty($data['invoice_number'])) {
@@ -1218,6 +1224,12 @@ class InvoiceValidationResource extends Resource
if (! empty($data['Plant'])) { if (! empty($data['Plant'])) {
$indicators[] = 'Plant: '.Plant::where('id', $data['Plant'])->value('name'); $indicators[] = 'Plant: '.Plant::where('id', $data['Plant'])->value('name');
} else {
$userHas = Filament::auth()->user()->plant_id;
if ($userHas && strlen($userHas) > 0) {
return 'Plant: Choose plant to filter records.';
}
} }
if (! empty($data['invoice_number'])) { if (! empty($data['invoice_number'])) {

View File

@@ -5,35 +5,33 @@ namespace App\Filament\Resources;
use App\Filament\Exports\LocatorInvoiceValidationExporter; use App\Filament\Exports\LocatorInvoiceValidationExporter;
use App\Filament\Imports\LocatorInvoiceValidationImporter; use App\Filament\Imports\LocatorInvoiceValidationImporter;
use App\Filament\Resources\LocatorInvoiceValidationResource\Pages; use App\Filament\Resources\LocatorInvoiceValidationResource\Pages;
use App\Filament\Resources\LocatorInvoiceValidationResource\RelationManagers;
use App\Models\Configuration; use App\Models\Configuration;
use App\Models\InvoiceValidation; use App\Models\InvoiceValidation;
use App\Models\LocatorInvoiceValidation; use App\Models\LocatorInvoiceValidation;
use App\Models\PalletValidation; use App\Models\PalletValidation;
use App\Models\Plant; use App\Models\Plant;
use App\Models\StickerMaster;
use Filament\Facades\Filament; use Filament\Facades\Filament;
use Filament\Forms; use Filament\Forms;
use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\FileUpload; use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\Section; use Filament\Forms\Components\Section;
use Filament\Forms\Components\Select; use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\ToggleButtons; use Filament\Forms\Components\ToggleButtons;
use Filament\Forms\Form; use Filament\Forms\Form;
use Filament\Forms\Get; use Filament\Forms\Get;
use Filament\Notifications\Notification; use Filament\Notifications\Notification;
use Filament\Resources\Resource; use Filament\Resources\Resource;
use Filament\Tables; use Filament\Tables;
use Filament\Tables\Actions\ExportAction;
use Filament\Tables\Actions\ImportAction;
use Filament\Tables\Filters\Filter;
use Filament\Tables\Table; use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope; use Illuminate\Database\Eloquent\SoftDeletingScope;
use Maatwebsite\Excel\Facades\Excel; use Maatwebsite\Excel\Facades\Excel;
use Filament\Tables\Actions\ExportAction;
use Filament\Tables\Actions\ImportAction;
use Storage; use Storage;
use Str; use Str;
use Filament\Forms\Components\DateTimePicker;
use Filament\Tables\Filters\Filter;
use Filament\Forms\Components\TextInput;
class LocatorInvoiceValidationResource extends Resource class LocatorInvoiceValidationResource extends Resource
{ {
@@ -57,14 +55,14 @@ class LocatorInvoiceValidationResource extends Resource
->relationship('plant', 'name') ->relationship('plant', 'name')
->options(function (callable $get) { ->options(function (callable $get) {
$userHas = Filament::auth()->user()->plant_id; $userHas = Filament::auth()->user()->plant_id;
return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray();
}) })
->disabled(fn (Get $get) => $get('invoice_number')) ->disabled(fn (Get $get) => $get('invoice_number'))
->required() ->required()
->afterStateUpdated(function ($state, callable $set, callable $get) { ->afterStateUpdated(function ($state, callable $set, callable $get) {
$plantId = $get('plant_id'); $plantId = $get('plant_id');
if ($plantId) if ($plantId) {
{
$set('plant', $plantId); $set('plant', $plantId);
$set('invoice_number', null); $set('invoice_number', null);
$set('pallet_number', null); $set('pallet_number', null);
@@ -72,9 +70,7 @@ class LocatorInvoiceValidationResource extends Resource
$set('sno_quantity', 0); $set('sno_quantity', 0);
$set('scan_quantity', 0); $set('scan_quantity', 0);
$set('pend_quantity', 0); $set('pend_quantity', 0);
} } else {
else
{
$set('plant', null); $set('plant', null);
$set('invoice_number', null); $set('invoice_number', null);
$set('pallet_number', null); $set('pallet_number', null);
@@ -107,9 +103,7 @@ class LocatorInvoiceValidationResource extends Resource
if (! $plantId) { if (! $plantId) {
$set('invoice_number', null); $set('invoice_number', null);
$set('pallet_number', null); $set('pallet_number', null);
} } elseif ($invNo) {
else if ($invNo)
{
$snoCount = LocatorInvoiceValidation::where('plant_id', $plantId)->where('invoice_number', $invNo)->count(); $snoCount = LocatorInvoiceValidation::where('plant_id', $plantId)->where('invoice_number', $invNo)->count();
$pendingCount = LocatorInvoiceValidation::where('invoice_number', $invNo)->where('plant_id', $plantId)->whereNull('scanned_status')->orWhere('scanned_status', '=', '')->count(); $pendingCount = LocatorInvoiceValidation::where('invoice_number', $invNo)->where('plant_id', $plantId)->whereNull('scanned_status')->orWhere('scanned_status', '=', '')->count();
@@ -139,8 +133,7 @@ class LocatorInvoiceValidationResource extends Resource
->get(); ->get();
$allScanned = true; $allScanned = true;
foreach ($records as $record) foreach ($records as $record) {
{
if (($record->scanned_status == null) || trim($record->scanned_status) == '') { if (($record->scanned_status == null) || trim($record->scanned_status) == '') {
$allScanned = false; $allScanned = false;
break; break;
@@ -181,8 +174,7 @@ class LocatorInvoiceValidationResource extends Resource
->get(); ->get();
$allScanned = true; $allScanned = true;
foreach ($records as $record) foreach ($records as $record) {
{
if (($record->scanned_status == null) || trim($record->scanned_status) == '') { if (($record->scanned_status == null) || trim($record->scanned_status) == '') {
$allScanned = false; $allScanned = false;
break; break;
@@ -236,8 +228,7 @@ class LocatorInvoiceValidationResource extends Resource
$allScanned = true; $allScanned = true;
foreach ($records as $record) foreach ($records as $record) {
{
if (($record->scanned_status == null) || trim($record->scanned_status) == '') { if (($record->scanned_status == null) || trim($record->scanned_status) == '') {
$allScanned = false; $allScanned = false;
break; break;
@@ -289,6 +280,7 @@ class LocatorInvoiceValidationResource extends Resource
if ($state !== '1') { if ($state !== '1') {
$set('update_locator_invoice', '0'); $set('update_locator_invoice', '0');
$set('pallet_number', null); $set('pallet_number', null);
return; return;
} }
@@ -296,13 +288,13 @@ class LocatorInvoiceValidationResource extends Resource
->where('pallet_number', $palletNumber) ->where('pallet_number', $palletNumber)
->first(); ->first();
if (!$palletRecord) if (! $palletRecord) {
{
Notification::make() Notification::make()
->title("Pallet number '{$palletNumber}' does not exist.") ->title("Pallet number '{$palletNumber}' does not exist.")
->danger() ->danger()
->duration(5000) ->duration(5000)
->send(); ->send();
return; return;
} }
@@ -318,13 +310,13 @@ class LocatorInvoiceValidationResource extends Resource
} }
} }
if (!$allCompleted) if (! $allCompleted) {
{
Notification::make() Notification::make()
->title("Pallet number '{$palletNumber}' is not completed in masters") ->title("Pallet number '{$palletNumber}' is not completed in masters")
->danger() ->danger()
->duration(5000) ->duration(5000)
->send(); ->send();
return; return;
} }
@@ -413,7 +405,7 @@ class LocatorInvoiceValidationResource extends Resource
// } // }
// } // }
// } // }
}) }),
]) ])
->columns(5), ->columns(5),
@@ -431,6 +423,7 @@ class LocatorInvoiceValidationResource extends Resource
$paginator = $livewire->getTableRecords(); $paginator = $livewire->getTableRecords();
$perPage = method_exists($paginator, 'perPage') ? $paginator->perPage() : 10; $perPage = method_exists($paginator, 'perPage') ? $paginator->perPage() : 10;
$currentPage = method_exists($paginator, 'currentPage') ? $paginator->currentPage() : 1; $currentPage = method_exists($paginator, 'currentPage') ? $paginator->currentPage() : 1;
return ($currentPage - 1) * $perPage + $rowLoop->iteration; return ($currentPage - 1) * $perPage + $rowLoop->iteration;
}), }),
Tables\Columns\TextColumn::make('plant.name') Tables\Columns\TextColumn::make('plant.name')
@@ -504,6 +497,7 @@ class LocatorInvoiceValidationResource extends Resource
// ->options(Plant::pluck('name', 'id')->toArray()) // ->options(Plant::pluck('name', 'id')->toArray())
->options(function (callable $get) { ->options(function (callable $get) {
$userHas = Filament::auth()->user()->plant_id; $userHas = Filament::auth()->user()->plant_id;
return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray();
}) })
->label('Select Plant') ->label('Select Plant')
@@ -546,8 +540,7 @@ class LocatorInvoiceValidationResource extends Resource
$fullFolderPath = "uploads/$folderPath"; $fullFolderPath = "uploads/$folderPath";
// Check if the folder exists, if not, create it // Check if the folder exists, if not, create it
if (!Storage::disk('local')->exists($fullFolderPath)) if (! Storage::disk('local')->exists($fullFolderPath)) {
{
Storage::disk('local')->makeDirectory($fullFolderPath); Storage::disk('local')->makeDirectory($fullFolderPath);
} }
@@ -555,12 +548,10 @@ class LocatorInvoiceValidationResource extends Resource
$fullPath = Storage::disk('local')->path($path); $fullPath = Storage::disk('local')->path($path);
if ($fullPath && file_exists($fullPath)) if ($fullPath && file_exists($fullPath)) {
{
$rows = Excel::toArray(null, $fullPath)[0]; $rows = Excel::toArray(null, $fullPath)[0];
if((count($rows) - 1) <= 0) if ((count($rows) - 1) <= 0) {
{
Notification::make() Notification::make()
->title('Invalid Locator Invoice Found') ->title('Invalid Locator Invoice Found')
->body('Uploaded excel sheet is empty or<br>contains no valid data.') ->body('Uploaded excel sheet is empty or<br>contains no valid data.')
@@ -571,6 +562,7 @@ class LocatorInvoiceValidationResource extends Resource
if ($disk->exists($path)) { if ($disk->exists($path)) {
$disk->delete($path); $disk->delete($path);
} }
return; return;
} }
@@ -579,29 +571,22 @@ class LocatorInvoiceValidationResource extends Resource
$seenSerialNumbers = []; $seenSerialNumbers = [];
$validRowsFound = false; $validRowsFound = false;
foreach ($rows as $index => $row) foreach ($rows as $index => $row) {
{ if ($index === 0) {
if ($index === 0) continue; // Skip header continue;
} // Skip header
$serialNumber = trim($row[0]); $serialNumber = trim($row[0]);
if (empty($serialNumber)) if (empty($serialNumber)) {
{
continue; continue;
} } else {
else if (Str::length($serialNumber) < 9 || Str::length($serialNumber) > 20 || ! ctype_alnum($serialNumber)) {
{
if(Str::length($serialNumber) < 9 || Str::length($serialNumber) > 20 || !ctype_alnum($serialNumber))
{
$invalidSerialCodes[] = $serialNumber; $invalidSerialCodes[] = $serialNumber;
} } else {
else
{
if (in_array($serialNumber, $seenSerialNumbers)) { if (in_array($serialNumber, $seenSerialNumbers)) {
$duplicateSerials[] = $serialNumber; $duplicateSerials[] = $serialNumber;
} } else {
else
{
$seenSerialNumbers[] = $serialNumber; $seenSerialNumbers[] = $serialNumber;
$validRowsFound = true; $validRowsFound = true;
} }
@@ -622,6 +607,7 @@ class LocatorInvoiceValidationResource extends Resource
if ($disk->exists($path)) { if ($disk->exists($path)) {
$disk->delete($path); $disk->delete($path);
} }
return; return;
} }
@@ -638,6 +624,7 @@ class LocatorInvoiceValidationResource extends Resource
if ($disk->exists($path)) { if ($disk->exists($path)) {
$disk->delete($path); $disk->delete($path);
} }
return; return;
} }
@@ -652,6 +639,7 @@ class LocatorInvoiceValidationResource extends Resource
if ($disk->exists($path)) { if ($disk->exists($path)) {
$disk->delete($path); $disk->delete($path);
} }
return; return;
} }
@@ -674,10 +662,9 @@ class LocatorInvoiceValidationResource extends Resource
if ($disk->exists($path)) { if ($disk->exists($path)) {
$disk->delete($path); $disk->delete($path);
} }
return; return;
} } else {
else
{
// Save full file path to session // Save full file path to session
session(['uploaded_invoice_path' => $fullPath]); session(['uploaded_invoice_path' => $fullPath]);
Notification::make() Notification::make()
@@ -707,11 +694,6 @@ class LocatorInvoiceValidationResource extends Resource
return Filament::auth()->user()->can('view export locator invoice validation'); return Filament::auth()->user()->can('view export locator invoice validation');
}), }),
]) ])
// ->filters([
// Tables\Filters\TrashedFilter::make(),
// ])
->filters([ ->filters([
Tables\Filters\TrashedFilter::make(), Tables\Filters\TrashedFilter::make(),
Filter::make('advanced_filters') Filter::make('advanced_filters')
@@ -725,6 +707,7 @@ class LocatorInvoiceValidationResource extends Resource
// }) // })
->options(function (callable $get) { ->options(function (callable $get) {
$userHas = Filament::auth()->user()->plant_id; $userHas = Filament::auth()->user()->plant_id;
return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray();
}) })
->reactive() ->reactive()
@@ -748,6 +731,7 @@ class LocatorInvoiceValidationResource extends Resource
if (! $plantId) { if (! $plantId) {
return []; return [];
} }
return LocatorInvoiceValidation::where('plant_id', $plantId) return LocatorInvoiceValidation::where('plant_id', $plantId)
->whereNotNull('invoice_number') ->whereNotNull('invoice_number')
->where('invoice_number', '!=', '') ->where('invoice_number', '!=', '')
@@ -770,6 +754,7 @@ class LocatorInvoiceValidationResource extends Resource
if (! $plantId) { if (! $plantId) {
return []; return [];
} }
return LocatorInvoiceValidation::where('plant_id', $plantId) return LocatorInvoiceValidation::where('plant_id', $plantId)
->whereNotNull('pallet_number') ->whereNotNull('pallet_number')
->where('pallet_number', '!=', '') ->where('pallet_number', '!=', '')
@@ -788,6 +773,7 @@ class LocatorInvoiceValidationResource extends Resource
if (! $plantId) { if (! $plantId) {
return []; return [];
} }
return LocatorInvoiceValidation::where('plant_id', $plantId) return LocatorInvoiceValidation::where('plant_id', $plantId)
->whereNotNull('locator_number') ->whereNotNull('locator_number')
->where('locator_number', '!=', '') ->where('locator_number', '!=', '')
@@ -839,6 +825,12 @@ class LocatorInvoiceValidationResource extends Resource
if (! empty($data['Plant'])) { // $plant = $data['Plant'] ?? null if (! empty($data['Plant'])) { // $plant = $data['Plant'] ?? null
$query->where('plant_id', $data['Plant']); $query->where('plant_id', $data['Plant']);
} else {
$userHas = Filament::auth()->user()->plant_id;
if ($userHas && strlen($userHas) > 0) {
return $query->whereRaw('1 = 0');
}
} }
if (! empty($data['invoice_number'])) { if (! empty($data['invoice_number'])) {
@@ -889,6 +881,12 @@ class LocatorInvoiceValidationResource extends Resource
if (! empty($data['Plant'])) { if (! empty($data['Plant'])) {
$indicators[] = 'Plant: '.Plant::where('id', $data['Plant'])->value('name'); $indicators[] = 'Plant: '.Plant::where('id', $data['Plant'])->value('name');
} else {
$userHas = Filament::auth()->user()->plant_id;
if ($userHas && strlen($userHas) > 0) {
return 'Plant: Choose plant to filter records.';
}
} }
if (! empty($data['invoice_number'])) { if (! empty($data['invoice_number'])) {
@@ -933,7 +931,7 @@ class LocatorInvoiceValidationResource extends Resource
} }
return $indicators; return $indicators;
}) }),
]) ])
->filtersFormMaxHeight('280px') ->filtersFormMaxHeight('280px')
->actions([ ->actions([

View File

@@ -5,21 +5,20 @@ namespace App\Filament\Resources;
use App\Filament\Exports\LocatorExporter; use App\Filament\Exports\LocatorExporter;
use App\Filament\Imports\LocatorImporter; use App\Filament\Imports\LocatorImporter;
use App\Filament\Resources\LocatorResource\Pages; use App\Filament\Resources\LocatorResource\Pages;
use App\Filament\Resources\LocatorResource\RelationManagers;
use App\Models\Locator; use App\Models\Locator;
use App\Models\PalletValidation; use App\Models\PalletValidation;
use App\Models\Plant; use App\Models\Plant;
use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Get;
use Filament\Tables\Actions\ImportAction;
use Filament\Facades\Filament; use Filament\Facades\Filament;
use Filament\Forms; use Filament\Forms;
use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\Select; use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Form; use Filament\Forms\Form;
use Filament\Forms\Get;
use Filament\Resources\Resource; use Filament\Resources\Resource;
use Filament\Tables; use Filament\Tables;
use Filament\Tables\Actions\ExportAction; use Filament\Tables\Actions\ExportAction;
use Filament\Tables\Actions\ImportAction;
use Filament\Tables\Filters\Filter; use Filament\Tables\Filters\Filter;
use Filament\Tables\Table; use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Builder;
@@ -48,6 +47,7 @@ class LocatorResource extends Resource
->reactive() ->reactive()
->options(function (callable $get) { ->options(function (callable $get) {
$userHas = Filament::auth()->user()->plant_id; $userHas = Filament::auth()->user()->plant_id;
return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray();
}) })
->default(function () { ->default(function () {
@@ -63,10 +63,9 @@ class LocatorResource extends Resource
$set('locator_number', null); $set('locator_number', null);
$set('locator_quantity', 0); $set('locator_quantity', 0);
$set('operator_id', Filament::auth()->user()?->name); $set('operator_id', Filament::auth()->user()?->name);
return; return;
} } else {
else
{
$set('locPlantError', null); $set('locPlantError', null);
$set('locator_number', null); $set('locator_number', null);
$set('locator_quantity', 0); $set('locator_quantity', 0);
@@ -91,16 +90,15 @@ class LocatorResource extends Resource
$set('locator_number', null); $set('locator_number', null);
$set('locator_quantity', 0); $set('locator_quantity', 0);
$set('operator_id', Filament::auth()->user()?->name); $set('operator_id', Filament::auth()->user()?->name);
return; return;
} } elseif (! $locator || Str::length($locator) < 7) {
else if (!$locator || Str::length($locator) < 7) {
$set('locNameError', 'Please scan the valid locator number.'); $set('locNameError', 'Please scan the valid locator number.');
$set('locator_quantity', 0); $set('locator_quantity', 0);
$set('operator_id', Filament::auth()->user()?->name); $set('operator_id', Filament::auth()->user()?->name);
return; return;
} } else {
else
{
$set('locNameError', null); $set('locNameError', null);
$set('locator_quantity', PalletValidation::where('locator_number', $locator)->where('plant_id', $plantId)->distinct('pallet_number')->count('pallet_number')); $set('locator_quantity', PalletValidation::where('locator_number', $locator)->where('plant_id', $plantId)->distinct('pallet_number')->count('pallet_number'));
$set('operator_id', Filament::auth()->user()?->name); $set('operator_id', Filament::auth()->user()?->name);
@@ -145,6 +143,7 @@ class LocatorResource extends Resource
$paginator = $livewire->getTableRecords(); $paginator = $livewire->getTableRecords();
$perPage = method_exists($paginator, 'perPage') ? $paginator->perPage() : 10; $perPage = method_exists($paginator, 'perPage') ? $paginator->perPage() : 10;
$currentPage = method_exists($paginator, 'currentPage') ? $paginator->currentPage() : 1; $currentPage = method_exists($paginator, 'currentPage') ? $paginator->currentPage() : 1;
return ($currentPage - 1) * $perPage + $rowLoop->iteration; return ($currentPage - 1) * $perPage + $rowLoop->iteration;
}), }),
Tables\Columns\TextColumn::make('plant.name') Tables\Columns\TextColumn::make('plant.name')
@@ -194,6 +193,7 @@ class LocatorResource extends Resource
// }) // })
->options(function (callable $get) { ->options(function (callable $get) {
$userHas = Filament::auth()->user()->plant_id; $userHas = Filament::auth()->user()->plant_id;
return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray();
}) })
->reactive() ->reactive()
@@ -213,6 +213,7 @@ class LocatorResource extends Resource
if (! $plantId) { if (! $plantId) {
return []; return [];
} }
return Locator::where('plant_id', $plantId)->orderBy('locator_number', 'asc')->get()->unique('locator_number')->pluck('locator_number', 'locator_number')->toArray(); return Locator::where('plant_id', $plantId)->orderBy('locator_number', 'asc')->get()->unique('locator_number')->pluck('locator_number', 'locator_number')->toArray();
// ->whereNotNull('locator_number') // ->whereNotNull('locator_number')
// ->where('locator_number','!=', '') // ->where('locator_number','!=', '')
@@ -260,6 +261,12 @@ class LocatorResource extends Resource
if (! empty($data['Plant'])) { // $plant = $data['Plant'] ?? null if (! empty($data['Plant'])) { // $plant = $data['Plant'] ?? null
$query->where('plant_id', $data['Plant']); $query->where('plant_id', $data['Plant']);
} else {
$userHas = Filament::auth()->user()->plant_id;
if ($userHas && strlen($userHas) > 0) {
return $query->whereRaw('1 = 0');
}
} }
if (! empty($data['locator_number'])) { if (! empty($data['locator_number'])) {
@@ -295,6 +302,12 @@ class LocatorResource extends Resource
if (! empty($data['Plant'])) { if (! empty($data['Plant'])) {
$indicators[] = 'Plant: '.Plant::where('id', $data['Plant'])->value('name'); $indicators[] = 'Plant: '.Plant::where('id', $data['Plant'])->value('name');
} else {
$userHas = Filament::auth()->user()->plant_id;
if ($userHas && strlen($userHas) > 0) {
return 'Plant: Choose plant to filter records.';
}
} }
if (! empty($data['locator_number'])) { if (! empty($data['locator_number'])) {
@@ -326,7 +339,7 @@ class LocatorResource extends Resource
} }
return $indicators; return $indicators;
}) }),
]) ])
->filtersFormMaxHeight('280px') ->filtersFormMaxHeight('280px')
->actions([ ->actions([

View File

@@ -5,7 +5,6 @@ namespace App\Filament\Resources;
use App\Filament\Exports\MachineExporter; use App\Filament\Exports\MachineExporter;
use App\Filament\Imports\MachineImporter; use App\Filament\Imports\MachineImporter;
use App\Filament\Resources\MachineResource\Pages; use App\Filament\Resources\MachineResource\Pages;
use App\Filament\Resources\MachineResource\RelationManagers;
use App\Models\Line; use App\Models\Line;
use App\Models\Machine; use App\Models\Machine;
use App\Models\Plant; use App\Models\Plant;
@@ -16,11 +15,11 @@ use Filament\Forms\Form;
use Filament\Forms\Get; use Filament\Forms\Get;
use Filament\Resources\Resource; use Filament\Resources\Resource;
use Filament\Tables; use Filament\Tables;
use Filament\Tables\Actions\ExportAction;
use Filament\Tables\Actions\ImportAction;
use Filament\Tables\Table; use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope; use Illuminate\Database\Eloquent\SoftDeletingScope;
use Filament\Tables\Actions\ImportAction;
use Filament\Tables\Actions\ExportAction;
use Illuminate\Validation\Rule; use Illuminate\Validation\Rule;
use Str; use Str;
@@ -45,6 +44,7 @@ class MachineResource extends Resource
->reactive() ->reactive()
->options(function (callable $get) { ->options(function (callable $get) {
$userHas = Filament::auth()->user()->plant_id; $userHas = Filament::auth()->user()->plant_id;
return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray();
}) })
->default(function () { ->default(function () {
@@ -57,10 +57,9 @@ class MachineResource extends Resource
$set('mPlantError', 'Please select a plant first.'); $set('mPlantError', 'Please select a plant first.');
$set('line_id', null); $set('line_id', null);
$set('work_group_master_id', null); $set('work_group_master_id', null);
return; return;
} } else {
else
{
$set('mPlantError', null); $set('mPlantError', null);
} }
}) })
@@ -90,10 +89,9 @@ class MachineResource extends Resource
if (! $lineId) { if (! $lineId) {
$set('mLineError', 'Please select a line first.'); $set('mLineError', 'Please select a line first.');
$set('work_group_master_id', null); $set('work_group_master_id', null);
return; return;
} } else {
else
{
// $grpWrkCnr = Line::find($lineId)->group_work_center; // $grpWrkCnr = Line::find($lineId)->group_work_center;
// if (!$grpWrkCnr || Str::length($grpWrkCnr) < 1) // if (!$grpWrkCnr || Str::length($grpWrkCnr) < 1)
// { // {
@@ -138,10 +136,9 @@ class MachineResource extends Resource
$lineId = $get('line_id'); $lineId = $get('line_id');
if (! $lineId) { if (! $lineId) {
$set('mGroupWorkError', 'Please select a line first.'); $set('mGroupWorkError', 'Please select a line first.');
return; return;
} } else {
else
{
// $grpWrkCnr = Line::find($lineId)->group_work_center; // $grpWrkCnr = Line::find($lineId)->group_work_center;
// if (!$grpWrkCnr || Str::length($grpWrkCnr) < 1) // if (!$grpWrkCnr || Str::length($grpWrkCnr) < 1)
// { // {
@@ -194,6 +191,7 @@ class MachineResource extends Resource
$paginator = $livewire->getTableRecords(); $paginator = $livewire->getTableRecords();
$perPage = method_exists($paginator, 'perPage') ? $paginator->perPage() : 10; $perPage = method_exists($paginator, 'perPage') ? $paginator->perPage() : 10;
$currentPage = method_exists($paginator, 'currentPage') ? $paginator->currentPage() : 1; $currentPage = method_exists($paginator, 'currentPage') ? $paginator->currentPage() : 1;
return ($currentPage - 1) * $perPage + $rowLoop->iteration; return ($currentPage - 1) * $perPage + $rowLoop->iteration;
}), }),
Tables\Columns\TextColumn::make('plant.name') Tables\Columns\TextColumn::make('plant.name')

View File

@@ -36,30 +36,84 @@ class MfmParameterResource extends Resource
Forms\Components\Select::make('plant_id') Forms\Components\Select::make('plant_id')
->label('Plant') ->label('Plant')
->relationship('plant', 'name') ->relationship('plant', 'name')
->reactive()
->options(function (callable $get) { ->options(function (callable $get) {
$userHas = Filament::auth()->user()->plant_id; $userHas = Filament::auth()->user()->plant_id;
return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray();
}) })
->afterStateUpdated(function (callable $set) {
$set('device_master_id', null);
$set('mfm_meter_id', null);
$set('name', null);
$set('register_id', null);
$set('identifier', null);
$set('byte_to_convert', null);
$set('type_to_convert', null);
$set('decimal_to_display', null);
})
->required(), ->required(),
Forms\Components\Select::make('device_master_id') Forms\Components\Select::make('device_master_id')
->label('Device Master') ->label('Device Master')
->relationship('deviceName', 'name') //->relationship('deviceName', 'name')
->options(function (callable $get) {
$plantId = $get('plant_id');
if (!$plantId) {
return [];
}
return \App\Models\DeviceMaster::where('plant_id', $plantId)
->pluck('name', 'id');
})
->afterStateUpdated(function (callable $set) {
$set('mfm_meter_id', null);
$set('name', null);
$set('register_id', null);
$set('identifier', null);
$set('byte_to_convert', null);
$set('type_to_convert', null);
$set('decimal_to_display', null);
})
->reactive()
->required(), ->required(),
Forms\Components\Select::make('mfm_meter_id') Forms\Components\Select::make('mfm_meter_id')
->label('Mfm Meter') ->label('Mfm Meter')
->relationship('mfmMeter', 'sequence') // ->relationship('mfmMeter', 'sequence')
->options(function (callable $get) {
$plantId = $get('plant_id');
if (!$plantId) {
return [];
}
return \App\Models\MfmMeter::where('plant_id', $plantId)
->pluck('sequence', 'id');
})
->afterStateUpdated(function (callable $set) {
$set('name', null);
$set('register_id', null);
$set('identifier', null);
$set('byte_to_convert', null);
$set('type_to_convert', null);
$set('decimal_to_display', null);
})
->reactive()
->required(), ->required(),
Forms\Components\TextInput::make('name') Forms\Components\TextInput::make('name')
->label('Parameter Name') ->label('Parameter Name')
->reactive()
->required(), ->required(),
Forms\Components\TextInput::make('register_id') Forms\Components\TextInput::make('register_id')
->label('Register ID') ->label('Register ID')
->reactive()
->required(), ->required(),
Forms\Components\TextInput::make('identifier') Forms\Components\TextInput::make('identifier')
->label('Identifier') ->label('Identifier')
->reactive()
->required(), ->required(),
Forms\Components\TextInput::make('byte_to_convert') Forms\Components\TextInput::make('byte_to_convert')
->label('Byte To Convert') ->label('Byte To Convert')
->reactive()
->default(2) ->default(2)
->required(), ->required(),
Forms\Components\TextInput::make('type_to_convert') Forms\Components\TextInput::make('type_to_convert')
@@ -67,6 +121,7 @@ class MfmParameterResource extends Resource
->required(), ->required(),
Forms\Components\TextInput::make('decimal_to_display') Forms\Components\TextInput::make('decimal_to_display')
->label('Decimal To Display') ->label('Decimal To Display')
->reactive()
->default(1) ->default(1)
->required(), ->required(),
]) ])

View File

@@ -5,7 +5,6 @@ namespace App\Filament\Resources;
use App\Filament\Exports\MotorTestingMasterExporter; use App\Filament\Exports\MotorTestingMasterExporter;
use App\Filament\Imports\MotorTestingMasterImporter; use App\Filament\Imports\MotorTestingMasterImporter;
use App\Filament\Resources\MotorTestingMasterResource\Pages; use App\Filament\Resources\MotorTestingMasterResource\Pages;
use App\Filament\Resources\MotorTestingMasterResource\RelationManagers;
use App\Models\Configuration; use App\Models\Configuration;
use App\Models\Item; use App\Models\Item;
use App\Models\MotorTestingMaster; use App\Models\MotorTestingMaster;
@@ -20,12 +19,12 @@ use Filament\Forms\Form;
use Filament\Forms\Get; use Filament\Forms\Get;
use Filament\Resources\Resource; use Filament\Resources\Resource;
use Filament\Tables; use Filament\Tables;
use Filament\Tables\Actions\ExportAction;
use Filament\Tables\Actions\ImportAction;
use Filament\Tables\Filters\Filter;
use Filament\Tables\Table; use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope; use Illuminate\Database\Eloquent\SoftDeletingScope;
use Filament\Tables\Actions\ImportAction;
use Filament\Tables\Actions\ExportAction;
use Filament\Tables\Filters\Filter;
use Illuminate\Validation\Rule; use Illuminate\Validation\Rule;
class MotorTestingMasterResource extends Resource class MotorTestingMasterResource extends Resource
@@ -49,6 +48,7 @@ class MotorTestingMasterResource extends Resource
->reactive() ->reactive()
->options(function (callable $get) { ->options(function (callable $get) {
$userHas = Filament::auth()->user()->plant_id; $userHas = Filament::auth()->user()->plant_id;
return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray();
}) })
->default(function () { ->default(function () {
@@ -59,10 +59,9 @@ class MotorTestingMasterResource extends Resource
$plantId = $get('plant_id'); $plantId = $get('plant_id');
if (! $plantId) { if (! $plantId) {
$set('mTmError', 'Please select a plant first.'); $set('mTmError', 'Please select a plant first.');
return; return;
} } else {
else
{
$set('mTmError', null); $set('mTmError', null);
} }
}) })
@@ -108,17 +107,17 @@ class MotorTestingMasterResource extends Resource
$code = $get('subassembly_code'); $code = $get('subassembly_code');
if (! $code) { if (! $code) {
$set('iCodeError', 'Scan the valid Subassembly Code.'); $set('iCodeError', 'Scan the valid Subassembly Code.');
return; return;
} } else {
else
{
if (strlen($code) < 6) { if (strlen($code) < 6) {
$set('iCodeError', 'Subassembly code must be at least 6 digits.'); $set('iCodeError', 'Subassembly code must be at least 6 digits.');
return; return;
} } elseif (! preg_match('/^[a-zA-Z0-9]{6,}$/', $code)) {
else if (!preg_match('/^[a-zA-Z0-9]{6,}$/', $code)) {
$set('code', null); $set('code', null);
$set('iCodeError', 'Subassembly code must contain only alpha-numeric characters.'); $set('iCodeError', 'Subassembly code must contain only alpha-numeric characters.');
return; return;
} }
$set('iCodeError', null); $set('iCodeError', null);
@@ -145,16 +144,13 @@ class MotorTestingMasterResource extends Resource
->options(function (callable $get) { ->options(function (callable $get) {
$plantId = $get('plant_id'); $plantId = $get('plant_id');
if ($plantId) if ($plantId) {
{
return Configuration::where('plant_id', $plantId) return Configuration::where('plant_id', $plantId)
->where('c_name', 'MOTOR_PHASE') ->where('c_name', 'MOTOR_PHASE')
->orderBy('created_at') ->orderBy('created_at')
->pluck('c_value', 'c_value') ->pluck('c_value', 'c_value')
->toArray(); ->toArray();
} } else {
else
{
return Configuration::where('c_name', 'MOTOR_PHASE') return Configuration::where('c_name', 'MOTOR_PHASE')
->orderBy('created_at') ->orderBy('created_at')
->pluck('c_value', 'c_value') ->pluck('c_value', 'c_value')
@@ -197,16 +193,13 @@ class MotorTestingMasterResource extends Resource
->selectablePlaceholder(false) ->selectablePlaceholder(false)
->options(function (callable $get) { ->options(function (callable $get) {
$plantId = $get('plant_id'); $plantId = $get('plant_id');
if ($plantId) if ($plantId) {
{
return Configuration::where('plant_id', $plantId) return Configuration::where('plant_id', $plantId)
->where('c_name', 'MOTOR_CONNECTION') ->where('c_name', 'MOTOR_CONNECTION')
->orderBy('created_at') ->orderBy('created_at')
->pluck('c_value', 'c_value') ->pluck('c_value', 'c_value')
->toArray(); ->toArray();
} } else {
else
{
return Configuration::where('c_name', 'MOTOR_CONNECTION') return Configuration::where('c_name', 'MOTOR_CONNECTION')
->orderBy('created_at') ->orderBy('created_at')
->pluck('c_value', 'c_value') ->pluck('c_value', 'c_value')
@@ -230,16 +223,13 @@ class MotorTestingMasterResource extends Resource
->selectablePlaceholder(false) ->selectablePlaceholder(false)
->options(function (callable $get) { ->options(function (callable $get) {
$plantId = $get('plant_id'); $plantId = $get('plant_id');
if ($plantId) if ($plantId) {
{
return Configuration::where('plant_id', $plantId) return Configuration::where('plant_id', $plantId)
->where('c_name', 'INSULATION_RESISTANCE_TYPE') ->where('c_name', 'INSULATION_RESISTANCE_TYPE')
->orderBy('created_at') ->orderBy('created_at')
->pluck('c_value', 'c_value') ->pluck('c_value', 'c_value')
->toArray(); ->toArray();
} } else {
else
{
return Configuration::where('c_name', 'INSULATION_RESISTANCE_TYPE') return Configuration::where('c_name', 'INSULATION_RESISTANCE_TYPE')
->orderBy('created_at') ->orderBy('created_at')
->pluck('c_value', 'c_value') ->pluck('c_value', 'c_value')
@@ -317,6 +307,7 @@ class MotorTestingMasterResource extends Resource
$paginator = $livewire->getTableRecords(); $paginator = $livewire->getTableRecords();
$perPage = method_exists($paginator, 'perPage') ? $paginator->perPage() : 10; $perPage = method_exists($paginator, 'perPage') ? $paginator->perPage() : 10;
$currentPage = method_exists($paginator, 'currentPage') ? $paginator->currentPage() : 1; $currentPage = method_exists($paginator, 'currentPage') ? $paginator->currentPage() : 1;
return ($currentPage - 1) * $perPage + $rowLoop->iteration; return ($currentPage - 1) * $perPage + $rowLoop->iteration;
}), }),
Tables\Columns\TextColumn::make('plant.name') Tables\Columns\TextColumn::make('plant.name')
@@ -474,6 +465,7 @@ class MotorTestingMasterResource extends Resource
// }) // })
->options(function (callable $get) { ->options(function (callable $get) {
$userHas = Filament::auth()->user()->plant_id; $userHas = Filament::auth()->user()->plant_id;
return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray();
}) })
->reactive() ->reactive()
@@ -488,6 +480,7 @@ class MotorTestingMasterResource extends Resource
->nullable() ->nullable()
->options(function (callable $get) { ->options(function (callable $get) {
$pId = $get('Plant'); $pId = $get('Plant');
return Item::whereHas('motorTestingMasters', function ($query) use ($pId) { return Item::whereHas('motorTestingMasters', function ($query) use ($pId) {
if ($pId) { if ($pId) {
$query->where('plant_id', $pId); $query->where('plant_id', $pId);
@@ -505,7 +498,7 @@ class MotorTestingMasterResource extends Resource
->options([ ->options([
'All' => 'All', 'All' => 'All',
'Y' => 'Y', 'Y' => 'Y',
'N' => 'N' 'N' => 'N',
]) ])
->default(null) ->default(null)
->inlineLabel(false) ->inlineLabel(false)
@@ -516,16 +509,13 @@ class MotorTestingMasterResource extends Resource
->options(function (callable $get) { ->options(function (callable $get) {
$plantId = $get('plant_id'); $plantId = $get('plant_id');
if ($plantId) if ($plantId) {
{
return Configuration::where('plant_id', $plantId) return Configuration::where('plant_id', $plantId)
->where('c_name', 'MOTOR_PHASE') ->where('c_name', 'MOTOR_PHASE')
->orderBy('created_at') ->orderBy('created_at')
->pluck('c_value', 'c_value') ->pluck('c_value', 'c_value')
->toArray(); ->toArray();
} } else {
else
{
return Configuration::where('c_name', 'MOTOR_PHASE') return Configuration::where('c_name', 'MOTOR_PHASE')
->orderBy('created_at') ->orderBy('created_at')
->pluck('c_value', 'c_value') ->pluck('c_value', 'c_value')
@@ -544,16 +534,13 @@ class MotorTestingMasterResource extends Resource
->nullable() ->nullable()
->options(function (callable $get) { ->options(function (callable $get) {
$plantId = $get('plant_id'); $plantId = $get('plant_id');
if ($plantId) if ($plantId) {
{
return Configuration::where('plant_id', $plantId) return Configuration::where('plant_id', $plantId)
->where('c_name', 'MOTOR_CONNECTION') ->where('c_name', 'MOTOR_CONNECTION')
->orderBy('created_at') ->orderBy('created_at')
->pluck('c_value', 'c_value') ->pluck('c_value', 'c_value')
->toArray(); ->toArray();
} } else {
else
{
return Configuration::where('c_name', 'MOTOR_CONNECTION') return Configuration::where('c_name', 'MOTOR_CONNECTION')
->orderBy('created_at') ->orderBy('created_at')
->pluck('c_value', 'c_value') ->pluck('c_value', 'c_value')
@@ -571,12 +558,9 @@ class MotorTestingMasterResource extends Resource
->nullable() ->nullable()
->options(function (callable $get) { ->options(function (callable $get) {
$plantId = $get('Plant'); $plantId = $get('Plant');
if (!$plantId) if (! $plantId) {
{
return MotorTestingMaster::whereNotNull('created_by')->select('created_by')->distinct()->pluck('created_by', 'created_by'); return MotorTestingMaster::whereNotNull('created_by')->select('created_by')->distinct()->pluck('created_by', 'created_by');
} } else {
else
{
return MotorTestingMaster::where('plant_id', $plantId)->whereNotNull('created_by')->select('created_by')->distinct()->pluck('created_by', 'created_by'); return MotorTestingMaster::where('plant_id', $plantId)->whereNotNull('created_by')->select('created_by')->distinct()->pluck('created_by', 'created_by');
} }
}) })
@@ -597,12 +581,9 @@ class MotorTestingMasterResource extends Resource
->nullable() ->nullable()
->options(function (callable $get) { ->options(function (callable $get) {
$plantId = $get('Plant'); $plantId = $get('Plant');
if (!$plantId) if (! $plantId) {
{
return MotorTestingMaster::whereNotNull('updated_by')->select('updated_by')->distinct()->pluck('updated_by', 'updated_by'); return MotorTestingMaster::whereNotNull('updated_by')->select('updated_by')->distinct()->pluck('updated_by', 'updated_by');
} } else {
else
{
return MotorTestingMaster::where('plant_id', $plantId)->whereNotNull('updated_by')->select('updated_by')->distinct()->pluck('updated_by', 'updated_by'); return MotorTestingMaster::where('plant_id', $plantId)->whereNotNull('updated_by')->select('updated_by')->distinct()->pluck('updated_by', 'updated_by');
} }
}) })
@@ -627,6 +608,12 @@ class MotorTestingMasterResource extends Resource
if (! empty($data['Plant'])) { if (! empty($data['Plant'])) {
$query->where('plant_id', $data['Plant']); $query->where('plant_id', $data['Plant']);
} else {
$userHas = Filament::auth()->user()->plant_id;
if ($userHas && strlen($userHas) > 0) {
return $query->whereRaw('1 = 0');
}
} }
if (! empty($data['Item'])) { if (! empty($data['Item'])) {
@@ -642,7 +629,9 @@ class MotorTestingMasterResource extends Resource
if (! empty($data['description'])) { if (! empty($data['description'])) {
$pId = $data['Plant'] ?? null; $pId = $data['Plant'] ?? null;
$descIds = Item::where('description', 'like', '%'.$data['description'].'%')->whereHas('motorTestingMasters', function ($query) use ($pId) { $descIds = Item::where('description', 'like', '%'.$data['description'].'%')->whereHas('motorTestingMasters', function ($query) use ($pId) {
if ($pId) { $query->where('plant_id', $pId); } if ($pId) {
$query->where('plant_id', $pId);
}
})->pluck('id')->toArray(); })->pluck('id')->toArray();
if (! empty($descIds)) { if (! empty($descIds)) {
@@ -652,8 +641,7 @@ class MotorTestingMasterResource extends Resource
if ($data['isi_type'] == 'Y') { if ($data['isi_type'] == 'Y') {
$query->where('isi_model', true); $query->where('isi_model', true);
} } elseif ($data['isi_type'] == 'N') {
else if ($data['isi_type'] == 'N') {
$query->where('isi_model', false); $query->where('isi_model', false);
} }
@@ -694,6 +682,12 @@ class MotorTestingMasterResource extends Resource
if (! empty($data['Plant'])) { if (! empty($data['Plant'])) {
$indicators[] = 'Plant: '.Plant::where('id', $data['Plant'])->value('name'); $indicators[] = 'Plant: '.Plant::where('id', $data['Plant'])->value('name');
} else {
$userHas = Filament::auth()->user()->plant_id;
if ($userHas && strlen($userHas) > 0) {
return 'Plant: Choose plant to filter records.';
}
} }
if (! empty($data['Item'])) { if (! empty($data['Item'])) {
@@ -707,8 +701,7 @@ class MotorTestingMasterResource extends Resource
if ($data['isi_type'] == 'Y') { if ($data['isi_type'] == 'Y') {
$indicators[] = 'ISI Model: Yes'; $indicators[] = 'ISI Model: Yes';
} } elseif ($data['isi_type'] == 'N') {
else if ($data['isi_type'] == 'N') {
$indicators[] = 'ISI Model: No'; $indicators[] = 'ISI Model: No';
} }
@@ -745,7 +738,7 @@ class MotorTestingMasterResource extends Resource
} }
return $indicators; return $indicators;
}) }),
]) ])
->filtersFormMaxHeight('280px') ->filtersFormMaxHeight('280px')
->actions([ ->actions([

View File

@@ -5,31 +5,24 @@ namespace App\Filament\Resources;
use App\Filament\Exports\PalletValidationExporter; use App\Filament\Exports\PalletValidationExporter;
use App\Filament\Imports\PalletValidationImporter; use App\Filament\Imports\PalletValidationImporter;
use App\Filament\Resources\PalletValidationResource\Pages; use App\Filament\Resources\PalletValidationResource\Pages;
use App\Filament\Resources\PalletValidationResource\RelationManagers;
use App\Models\Item;
use App\Models\LocatorInvoiceValidation; use App\Models\LocatorInvoiceValidation;
use App\Models\PalletValidation; use App\Models\PalletValidation;
use App\Models\Plant; use App\Models\Plant;
use App\Models\StickerMaster;
use Filament\Facades\Filament; use Filament\Facades\Filament;
use Filament\Forms; use Filament\Forms;
use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\Section; use Filament\Forms\Components\Section;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Form; use Filament\Forms\Form;
use Filament\Resources\Resource; use Filament\Resources\Resource;
use Filament\Tables; use Filament\Tables;
use Filament\Tables\Actions\ExportAction;
use Filament\Tables\Actions\ImportAction;
use Filament\Tables\Filters\Filter;
use Filament\Tables\Table; use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope; use Illuminate\Database\Eloquent\SoftDeletingScope;
use Filament\Forms\Components\Actions;
use Filament\Tables\Actions\ExportAction;
use Filament\Tables\Actions\ImportAction;
use Log;
use Filament\Tables\Actions\Action;
use Filament\Forms\Components\DateTimePicker;
use Filament\Tables\Filters\Filter;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
class PalletValidationResource extends Resource class PalletValidationResource extends Resource
{ {
@@ -55,6 +48,7 @@ class PalletValidationResource extends Resource
->reactive() ->reactive()
->options(function (callable $get) { ->options(function (callable $get) {
$userHas = Filament::auth()->user()->plant_id; $userHas = Filament::auth()->user()->plant_id;
return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray();
}) })
->afterStateUpdated(function ($state, callable $set) { ->afterStateUpdated(function ($state, callable $set) {
@@ -74,8 +68,7 @@ class PalletValidationResource extends Resource
'x-model' => 'value', 'x-model' => 'value',
'x-on:keydown.enter.prevent' => '$wire.processPalletNo()', 'x-on:keydown.enter.prevent' => '$wire.processPalletNo()',
]) ])
->suffixAction(fn ($get,$set) => ->suffixAction(fn ($get, $set) => Forms\Components\Actions\Action::make('addPallet')
Forms\Components\Actions\Action::make('addPallet')
->label('') ->label('')
->button() ->button()
->icon('heroicon-o-plus') ->icon('heroicon-o-plus')
@@ -105,14 +98,12 @@ class PalletValidationResource extends Resource
} else { } else {
$newNumber = str_pad(intval($serialPart2) + 1, strlen($serialPart2), '0', STR_PAD_LEFT); $newNumber = str_pad(intval($serialPart2) + 1, strlen($serialPart2), '0', STR_PAD_LEFT);
} }
} } elseif ($lastPallet1) {
else if ($lastPallet1) {
$serialPart1 = substr($lastPallet1->pallet_number, strlen($prefix)); $serialPart1 = substr($lastPallet1->pallet_number, strlen($prefix));
// OR // OR
// $serialPart = str_replace($prefix, '', $lastPallet->pallet_number); // $serialPart = str_replace($prefix, '', $lastPallet->pallet_number);
$newNumber = str_pad(intval($serialPart1) + 1, strlen($serialPart1), '0', STR_PAD_LEFT); $newNumber = str_pad(intval($serialPart1) + 1, strlen($serialPart1), '0', STR_PAD_LEFT);
} } elseif ($lastPallet2) {
else if ($lastPallet2) {
$serialPart2 = substr($lastPallet2->pallet_number, strlen($prefix)); $serialPart2 = substr($lastPallet2->pallet_number, strlen($prefix));
// OR // OR
// $serialPart = str_replace($prefix, '', $lastPallet->pallet_number); // $serialPart = str_replace($prefix, '', $lastPallet->pallet_number);
@@ -172,6 +163,7 @@ class PalletValidationResource extends Resource
if (! $plantId) { if (! $plantId) {
return []; return [];
} }
return PalletValidation::query() return PalletValidation::query()
->where('plant_id', $plantId) ->where('plant_id', $plantId)
->where(function ($query) { ->where(function ($query) {
@@ -186,7 +178,7 @@ class PalletValidationResource extends Resource
->toArray(); ->toArray();
}), }),
Forms\Components\View::make('forms.components.save-pallet-button') Forms\Components\View::make('forms.components.save-pallet-button'),
]) ])
->columns(5), ->columns(5),
Forms\Components\TextInput::make('id') Forms\Components\TextInput::make('id')
@@ -199,7 +191,6 @@ class PalletValidationResource extends Resource
public static function table(Table $table): Table public static function table(Table $table): Table
{ {
return $table return $table
->columns([ ->columns([
// Tables\Columns\TextColumn::make('id') // Tables\Columns\TextColumn::make('id')
// ->label('ID') // ->label('ID')
@@ -212,6 +203,7 @@ class PalletValidationResource extends Resource
$paginator = $livewire->getTableRecords(); $paginator = $livewire->getTableRecords();
$perPage = method_exists($paginator, 'perPage') ? $paginator->perPage() : 10; $perPage = method_exists($paginator, 'perPage') ? $paginator->perPage() : 10;
$currentPage = method_exists($paginator, 'currentPage') ? $paginator->currentPage() : 1; $currentPage = method_exists($paginator, 'currentPage') ? $paginator->currentPage() : 1;
return ($currentPage - 1) * $perPage + $rowLoop->iteration; return ($currentPage - 1) * $perPage + $rowLoop->iteration;
}), }),
Tables\Columns\TextColumn::make('plant.name') Tables\Columns\TextColumn::make('plant.name')
@@ -286,6 +278,7 @@ class PalletValidationResource extends Resource
// }) // })
->options(function (callable $get) { ->options(function (callable $get) {
$userHas = Filament::auth()->user()->plant_id; $userHas = Filament::auth()->user()->plant_id;
return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray();
}) })
->reactive() ->reactive()
@@ -309,6 +302,7 @@ class PalletValidationResource extends Resource
if (! $plantId) { if (! $plantId) {
return []; return [];
} }
return PalletValidation::where('plant_id', $plantId) return PalletValidation::where('plant_id', $plantId)
// ->whereNotNull('pallet_number') // ->whereNotNull('pallet_number')
// ->where('pallet_number', '!=', '') // ->where('pallet_number', '!=', '')
@@ -339,6 +333,7 @@ class PalletValidationResource extends Resource
if (! $plantId) { if (! $plantId) {
return []; return [];
} }
return PalletValidation::where('plant_id', $plantId) return PalletValidation::where('plant_id', $plantId)
->whereNotNull('locator_number') ->whereNotNull('locator_number')
->where('locator_number', '!=', '') ->where('locator_number', '!=', '')
@@ -393,6 +388,12 @@ class PalletValidationResource extends Resource
if (! empty($data['Plant'])) { // $plant = $data['Plant'] ?? null if (! empty($data['Plant'])) { // $plant = $data['Plant'] ?? null
$query->where('plant_id', $data['Plant']); $query->where('plant_id', $data['Plant']);
} else {
$userHas = Filament::auth()->user()->plant_id;
if ($userHas && strlen($userHas) > 0) {
return $query->whereRaw('1 = 0');
}
} }
if (! empty($data['pallet_number'])) { if (! empty($data['pallet_number'])) {
@@ -448,6 +449,12 @@ class PalletValidationResource extends Resource
if (! empty($data['Plant'])) { if (! empty($data['Plant'])) {
$indicators[] = 'Plant: '.Plant::where('id', $data['Plant'])->value('name'); $indicators[] = 'Plant: '.Plant::where('id', $data['Plant'])->value('name');
} else {
$userHas = Filament::auth()->user()->plant_id;
if ($userHas && strlen($userHas) > 0) {
return 'Plant: Choose plant to filter records.';
}
} }
if (! empty($data['pallet_number'])) { if (! empty($data['pallet_number'])) {
@@ -495,7 +502,7 @@ class PalletValidationResource extends Resource
} }
return $indicators; return $indicators;
}) }),
]) ])
->filtersFormMaxHeight('280px') ->filtersFormMaxHeight('280px')
->actions([ ->actions([
@@ -521,6 +528,7 @@ class PalletValidationResource extends Resource
// ->options(Plant::pluck('name', 'id')->toArray()) // ->options(Plant::pluck('name', 'id')->toArray())
->options(function (callable $get) { ->options(function (callable $get) {
$userHas = Filament::auth()->user()->plant_id; $userHas = Filament::auth()->user()->plant_id;
return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray();
}) })
->required() ->required()
@@ -555,6 +563,7 @@ class PalletValidationResource extends Resource
]) ])
->action(function (array $data) { ->action(function (array $data) {
$selectedPalletNumber = $data['pallet_list']; $selectedPalletNumber = $data['pallet_list'];
return redirect()->route('download-reprint-qr-pdf', ['palletNo' => $selectedPalletNumber]); return redirect()->route('download-reprint-qr-pdf', ['palletNo' => $selectedPalletNumber]);
}) })

View File

@@ -5,11 +5,15 @@ namespace App\Filament\Resources;
use App\Filament\Exports\ProcessOrderExporter; use App\Filament\Exports\ProcessOrderExporter;
use App\Filament\Imports\ProcessOrderImporter; use App\Filament\Imports\ProcessOrderImporter;
use App\Filament\Resources\ProcessOrderResource\Pages; use App\Filament\Resources\ProcessOrderResource\Pages;
use App\Models\Item;
use App\Models\Plant; use App\Models\Plant;
use App\Models\ProcessOrder; use App\Models\ProcessOrder;
use Filament\Facades\Filament; use Filament\Facades\Filament;
use Filament\Forms; use Filament\Forms;
use Filament\Forms\Components\Actions\Action; use Filament\Forms\Components\Actions\Action;
use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Form; use Filament\Forms\Form;
use Filament\Forms\Get; use Filament\Forms\Get;
use Filament\Forms\Set; use Filament\Forms\Set;
@@ -18,19 +22,13 @@ use Filament\Resources\Resource;
use Filament\Tables; use Filament\Tables;
use Filament\Tables\Actions\ExportAction; use Filament\Tables\Actions\ExportAction;
use Filament\Tables\Actions\ImportAction; use Filament\Tables\Actions\ImportAction;
use Filament\Tables\Filters\Filter;
use Filament\Tables\Table; use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope; use Illuminate\Database\Eloquent\SoftDeletingScope;
use Livewire\Features\SupportFileUploads\TemporaryUploadedFile; use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;
use Smalot\PdfParser\Parser; use Smalot\PdfParser\Parser;
use Storage; use Storage;
use Filament\Forms\Components\DateTimePicker;
use Filament\Tables\Filters\Filter;
use Filament\Forms\Components\Select;
use App\Models\Line;
use Filament\Forms\Components\TextInput;
use App\Models\Item;
use App\Models\User;
// use App\Models\PalletValidation; // use App\Models\PalletValidation;
// use Dom\Text; // use Dom\Text;
@@ -482,6 +480,7 @@ class ProcessOrderResource extends Resource
$paginator = $livewire->getTableRecords(); $paginator = $livewire->getTableRecords();
$perPage = method_exists($paginator, 'perPage') ? $paginator->perPage() : 10; $perPage = method_exists($paginator, 'perPage') ? $paginator->perPage() : 10;
$currentPage = method_exists($paginator, 'currentPage') ? $paginator->currentPage() : 1; $currentPage = method_exists($paginator, 'currentPage') ? $paginator->currentPage() : 1;
return ($currentPage - 1) * $perPage + $rowLoop->iteration; return ($currentPage - 1) * $perPage + $rowLoop->iteration;
}), }),
Tables\Columns\TextColumn::make('plant.name') Tables\Columns\TextColumn::make('plant.name')
@@ -561,9 +560,6 @@ class ProcessOrderResource extends Resource
->sortable() ->sortable()
->toggleable(isToggledHiddenByDefault: true), ->toggleable(isToggledHiddenByDefault: true),
]) ])
// ->filters([
// Tables\Filters\TrashedFilter::make(),
// ])
->filters([ ->filters([
Tables\Filters\TrashedFilter::make(), Tables\Filters\TrashedFilter::make(),
Filter::make('advanced_filters') Filter::make('advanced_filters')
@@ -574,6 +570,7 @@ class ProcessOrderResource extends Resource
->nullable() ->nullable()
->options(function (callable $get) { ->options(function (callable $get) {
$userHas = Filament::auth()->user()->plant_id; $userHas = Filament::auth()->user()->plant_id;
return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray();
}) })
->reactive() ->reactive()
@@ -581,21 +578,19 @@ class ProcessOrderResource extends Resource
$set('Item', null); $set('Item', null);
}), }),
Select::make('Item') Select::make('Item')
->label('Item Code') ->label('Search by Item Code')
->nullable() ->nullable()
->searchable() ->searchable()
->reactive()
->options(function (callable $get) { ->options(function (callable $get) {
$plantId = $get('Plant'); $plantId = $get('Plant');
if(empty($plantId)) { return Item::whereHas('processOrders', function ($query) use ($plantId) {
return []; if ($plantId) {
$query->where('plant_id', $plantId);
} }
})->pluck('code', 'id');
return Item::where('plant_id', $plantId)->pluck('code', 'id');
//return $plantId ? Item::where('plant_id', $plantId)->pluck('code', 'id') : [];
}) })
->reactive()
->afterStateUpdated(function ($state, callable $set, callable $get) { ->afterStateUpdated(function ($state, callable $set, callable $get) {
$set('process_order', null); $set('process_order', null);
}), }),
@@ -627,6 +622,12 @@ class ProcessOrderResource extends Resource
if (! empty($data['Plant'])) { if (! empty($data['Plant'])) {
$query->where('plant_id', $data['Plant']); $query->where('plant_id', $data['Plant']);
} else {
$userHas = Filament::auth()->user()->plant_id;
if ($userHas && strlen($userHas) > 0) {
return $query->whereRaw('1 = 0');
}
} }
if (! empty($data['Item'])) { if (! empty($data['Item'])) {
@@ -660,6 +661,12 @@ class ProcessOrderResource extends Resource
if (! empty($data['Plant'])) { if (! empty($data['Plant'])) {
$indicators[] = 'Plant: '.Plant::where('id', $data['Plant'])->value('name'); $indicators[] = 'Plant: '.Plant::where('id', $data['Plant'])->value('name');
} else {
$userHas = Filament::auth()->user()->plant_id;
if ($userHas && strlen($userHas) > 0) {
return 'Plant: Choose plant to filter records.';
}
} }
if (! empty($data['Item'])) { if (! empty($data['Item'])) {
@@ -687,7 +694,7 @@ class ProcessOrderResource extends Resource
} }
return $indicators; return $indicators;
}) }),
]) ])
->filtersFormMaxHeight('280px') ->filtersFormMaxHeight('280px')
->actions([ ->actions([
@@ -787,6 +794,7 @@ class ProcessOrderResource extends Resource
if (! $plantId || ! $itemId || ! $processOrder || ! $state) { if (! $plantId || ! $itemId || ! $processOrder || ! $state) {
$set('received_quantity', null); $set('received_quantity', null);
$set('machine_name', null); $set('machine_name', null);
return; return;
} }
@@ -815,6 +823,7 @@ class ProcessOrderResource extends Resource
// }) // })
->action(function (array $data) { ->action(function (array $data) {
$username = Filament::auth()->user()->name; $username = Filament::auth()->user()->name;
return redirect()->route('download-reprint-process-pdf', [ return redirect()->route('download-reprint-process-pdf', [
'plant' => $data['plant'], 'plant' => $data['plant'],
'item' => $data['Item'], 'item' => $data['Item'],

View File

@@ -5,7 +5,6 @@ namespace App\Filament\Resources;
use App\Filament\Exports\ProductCharacteristicsMasterExporter; use App\Filament\Exports\ProductCharacteristicsMasterExporter;
use App\Filament\Imports\ProductCharacteristicsMasterImporter; use App\Filament\Imports\ProductCharacteristicsMasterImporter;
use App\Filament\Resources\ProductCharacteristicsMasterResource\Pages; use App\Filament\Resources\ProductCharacteristicsMasterResource\Pages;
use App\Filament\Resources\ProductCharacteristicsMasterResource\RelationManagers;
use App\Models\Item; use App\Models\Item;
use App\Models\Line; use App\Models\Line;
use App\Models\Machine; use App\Models\Machine;
@@ -14,19 +13,19 @@ use App\Models\ProductCharacteristicsMaster;
use App\Models\WorkGroupMaster; use App\Models\WorkGroupMaster;
use Filament\Facades\Filament; use Filament\Facades\Filament;
use Filament\Forms; use Filament\Forms;
use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Form; use Filament\Forms\Form;
use Filament\Forms\Get; use Filament\Forms\Get;
use Filament\Resources\Resource; use Filament\Resources\Resource;
use Filament\Tables; use Filament\Tables;
use Filament\Tables\Actions\ExportAction;
use Filament\Tables\Actions\ImportAction;
use Filament\Tables\Filters\Filter;
use Filament\Tables\Table; use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope; use Illuminate\Database\Eloquent\SoftDeletingScope;
use Filament\Tables\Actions\ImportAction;
use Filament\Tables\Actions\ExportAction;
use Filament\Forms\Components\DateTimePicker;
use Filament\Tables\Filters\Filter;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
class ProductCharacteristicsMasterResource extends Resource class ProductCharacteristicsMasterResource extends Resource
{ {
@@ -45,6 +44,7 @@ class ProductCharacteristicsMasterResource extends Resource
->relationship('plant', 'name') ->relationship('plant', 'name')
->options(function (callable $get) { ->options(function (callable $get) {
$userHas = Filament::auth()->user()->plant_id; $userHas = Filament::auth()->user()->plant_id;
return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray();
}) })
->reactive() ->reactive()
@@ -59,6 +59,7 @@ class ProductCharacteristicsMasterResource extends Resource
if (empty($plantId)) { if (empty($plantId)) {
return []; return [];
} }
return \App\Models\Item::where('plant_id', $plantId)->pluck('code', 'id'); return \App\Models\Item::where('plant_id', $plantId)->pluck('code', 'id');
}) })
->required(), ->required(),
@@ -70,6 +71,7 @@ class ProductCharacteristicsMasterResource extends Resource
if (empty($plantId)) { if (empty($plantId)) {
return []; return [];
} }
return Line::where('plant_id', $plantId)->pluck('name', 'id'); return Line::where('plant_id', $plantId)->pluck('name', 'id');
}) })
->afterStateUpdated(function ($state, callable $set, callable $get) { ->afterStateUpdated(function ($state, callable $set, callable $get) {
@@ -107,10 +109,9 @@ class ProductCharacteristicsMasterResource extends Resource
if (! $lineId) { if (! $lineId) {
$set('mGroupWorkError', 'Please select a line first.'); $set('mGroupWorkError', 'Please select a line first.');
$set('machine_id', null); $set('machine_id', null);
return; return;
} } else {
else
{
// $grpWrkCnr = Line::find($lineId)->group_work_center; // $grpWrkCnr = Line::find($lineId)->group_work_center;
// if (!$grpWrkCnr || Str::length($grpWrkCnr) < 1) // if (!$grpWrkCnr || Str::length($grpWrkCnr) < 1)
// { // {
@@ -210,7 +211,7 @@ class ProductCharacteristicsMasterResource extends Resource
if (! is_null($lower) && ! is_null($upper) && ! is_null($middle)) { if (! is_null($lower) && ! is_null($upper) && ! is_null($middle)) {
if (! ($lower <= $middle && $middle <= $upper)) { if (! ($lower <= $middle && $middle <= $upper)) {
$fail("Middle must be between Lower and Upper (Lower ≤ Middle ≤ Upper)."); $fail('Middle must be between Lower and Upper (Lower ≤ Middle ≤ Upper).');
} }
} }
}; };
@@ -233,6 +234,7 @@ class ProductCharacteristicsMasterResource extends Resource
$paginator = $livewire->getTableRecords(); $paginator = $livewire->getTableRecords();
$perPage = method_exists($paginator, 'perPage') ? $paginator->perPage() : 10; $perPage = method_exists($paginator, 'perPage') ? $paginator->perPage() : 10;
$currentPage = method_exists($paginator, 'currentPage') ? $paginator->currentPage() : 1; $currentPage = method_exists($paginator, 'currentPage') ? $paginator->currentPage() : 1;
return ($currentPage - 1) * $perPage + $rowLoop->iteration; return ($currentPage - 1) * $perPage + $rowLoop->iteration;
}), }),
Tables\Columns\TextColumn::make('plant.name') Tables\Columns\TextColumn::make('plant.name')
@@ -317,11 +319,7 @@ class ProductCharacteristicsMasterResource extends Resource
->sortable() ->sortable()
->toggleable(isToggledHiddenByDefault: true), ->toggleable(isToggledHiddenByDefault: true),
]) ])
// ->filters([
// Tables\Filters\TrashedFilter::make(),
// ])
->filters([ ->filters([
Tables\Filters\TrashedFilter::make(), Tables\Filters\TrashedFilter::make(),
Filter::make('advanced_filters') Filter::make('advanced_filters')
->label('Advanced Filters') ->label('Advanced Filters')
@@ -331,6 +329,7 @@ class ProductCharacteristicsMasterResource extends Resource
->nullable() ->nullable()
->options(function (callable $get) { ->options(function (callable $get) {
$userHas = Filament::auth()->user()->plant_id; $userHas = Filament::auth()->user()->plant_id;
return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray();
}) })
->reactive() ->reactive()
@@ -356,24 +355,22 @@ class ProductCharacteristicsMasterResource extends Resource
$set('Item', null); $set('Item', null);
}), }),
Select::make('Item') Select::make('Item')
->label('Item Code') ->label('Search by Item Code')
->nullable() ->nullable()
->searchable() ->searchable()
->options(function (callable $get) { ->options(function (callable $get) {
$plantId = $get('Plant'); $plantId = $get('Plant');
if(empty($plantId)) { return Item::whereHas('productCharacteristicsMasters', function ($query) use ($plantId) {
return []; if ($plantId) {
$query->where('plant_id', $plantId);
} }
})->pluck('code', 'id');
return Item::where('plant_id', $plantId)->pluck('code', 'id');
//return $plantId ? Item::where('plant_id', $plantId)->pluck('code', 'id') : [];
}) })
->reactive() ->reactive(),
->afterStateUpdated(function ($state, callable $set, callable $get) { // ->afterStateUpdated(function ($state, callable $set, callable $get) {
$set('process_order', null); // $set('process_order', null);
}), // }),
Select::make('work_group_master') Select::make('work_group_master')
->label('Select Work Group Master') ->label('Select Work Group Master')
->nullable() ->nullable()
@@ -421,7 +418,7 @@ class ProductCharacteristicsMasterResource extends Resource
->label('Characteristics Type') ->label('Characteristics Type')
->options([ ->options([
'Product' => 'Product', 'Product' => 'Product',
'Process' => 'Process' 'Process' => 'Process',
]), ]),
DateTimePicker::make(name: 'created_from') DateTimePicker::make(name: 'created_from')
->label('Created From') ->label('Created From')
@@ -442,6 +439,12 @@ class ProductCharacteristicsMasterResource extends Resource
if (! empty($data['Plant'])) { if (! empty($data['Plant'])) {
$query->where('plant_id', $data['Plant']); $query->where('plant_id', $data['Plant']);
} else {
$userHas = Filament::auth()->user()->plant_id;
if ($userHas && strlen($userHas) > 0) {
return $query->whereRaw('1 = 0');
}
} }
if (! empty($data['Line'])) { if (! empty($data['Line'])) {
@@ -472,7 +475,6 @@ class ProductCharacteristicsMasterResource extends Resource
$query->where('created_at', '<=', $data['created_to']); $query->where('created_at', '<=', $data['created_to']);
} }
// $query->orderBy('created_at', 'asc'); // $query->orderBy('created_at', 'asc');
}) })
->indicateUsing(function (array $data) { ->indicateUsing(function (array $data) {
@@ -480,6 +482,12 @@ class ProductCharacteristicsMasterResource extends Resource
if (! empty($data['Plant'])) { if (! empty($data['Plant'])) {
$indicators[] = 'Plant: '.Plant::where('id', $data['Plant'])->value('name'); $indicators[] = 'Plant: '.Plant::where('id', $data['Plant'])->value('name');
} else {
$userHas = Filament::auth()->user()->plant_id;
if ($userHas && strlen($userHas) > 0) {
return 'Plant: Choose plant to filter records.';
}
} }
if (! empty($data['Line'])) { if (! empty($data['Line'])) {
@@ -511,7 +519,7 @@ class ProductCharacteristicsMasterResource extends Resource
} }
return $indicators; return $indicators;
}) }),
]) ])
->filtersFormMaxHeight('280px') ->filtersFormMaxHeight('280px')
->actions([ ->actions([

View File

@@ -6,30 +6,28 @@ use AlperenErsoy\FilamentExport\Actions\FilamentExportBulkAction;
use App\Filament\Exports\ProductionLineStopExporter; use App\Filament\Exports\ProductionLineStopExporter;
use App\Filament\Imports\ProductionLineStopImporter; use App\Filament\Imports\ProductionLineStopImporter;
use App\Filament\Resources\ProductionLineStopResource\Pages; use App\Filament\Resources\ProductionLineStopResource\Pages;
use App\Filament\Resources\ProductionLineStopResource\RelationManagers;
use App\Models\Block; use App\Models\Block;
use App\Models\Line; use App\Models\Line;
use App\Models\LineStop; use App\Models\LineStop;
use App\Models\Plant; use App\Models\Plant;
use App\Models\ProductionLineStop; use App\Models\ProductionLineStop;
use App\Models\Shift; use App\Models\Shift;
use Carbon\Carbon;
use Filament\Facades\Filament;
use Filament\Forms; use Filament\Forms;
use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\Section;
use Filament\Forms\Components\Select;
use Filament\Forms\Form; use Filament\Forms\Form;
use Filament\Forms\Get; use Filament\Forms\Get;
use Filament\Resources\Resource; use Filament\Resources\Resource;
use Filament\Tables; use Filament\Tables;
use Filament\Tables\Actions\ExportAction;
use Filament\Tables\Actions\ImportAction; use Filament\Tables\Actions\ImportAction;
use Filament\Tables\Filters\Filter;
use Filament\Tables\Table; use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope; use Illuminate\Database\Eloquent\SoftDeletingScope;
use Carbon\Carbon;
use Filament\Facades\Filament;
use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\Section;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Tables\Actions\ExportAction;
use Filament\Tables\Filters\Filter;
class ProductionLineStopResource extends Resource class ProductionLineStopResource extends Resource
{ {
@@ -56,6 +54,7 @@ class ProductionLineStopResource extends Resource
->reactive() ->reactive()
->options(function (callable $get) { ->options(function (callable $get) {
$userHas = Filament::auth()->user()->plant_id; $userHas = Filament::auth()->user()->plant_id;
return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray();
}) })
->default(function () { ->default(function () {
@@ -68,10 +67,9 @@ class ProductionLineStopResource extends Resource
$set('block_name', null); $set('block_name', null);
if (! $plantId) { if (! $plantId) {
$set('plsPlantError', 'Please select a plant first.'); $set('plsPlantError', 'Please select a plant first.');
return; return;
} } else {
else
{
$set('plsPlantError', null); $set('plsPlantError', null);
} }
}) })
@@ -97,17 +95,16 @@ class ProductionLineStopResource extends Resource
->reactive() ->reactive()
->default(function () { ->default(function () {
$latestShiftId = optional(ProductionLineStop::latest()->first())->shift_id; $latestShiftId = optional(ProductionLineStop::latest()->first())->shift_id;
return optional(Shift::where('id', $latestShiftId)->first())->block_id; return optional(Shift::where('id', $latestShiftId)->first())->block_id;
}) })
// ->afterStateUpdated(fn ($set) => $set('shift_id', null)) // ->afterStateUpdated(fn ($set) => $set('shift_id', null))
->afterStateUpdated(function ($state, callable $set, callable $get) { ->afterStateUpdated(function ($state, callable $set, callable $get) {
if($get('id')) if ($get('id')) {
{
$getShift = ProductionLineStop::where('id', $get('id'))->first(); $getShift = ProductionLineStop::where('id', $get('id'))->first();
// $getBlock = \App\Models\Shift::where('id', $getShift->shift_id)->first(); // $getBlock = \App\Models\Shift::where('id', $getShift->shift_id)->first();
$getBlock = Shift::where('id', $getShift->shift_id)->first(); $getBlock = Shift::where('id', $getShift->shift_id)->first();
if($getBlock->block_id) if ($getBlock->block_id) {
{
$set('block_name', $getBlock->block_id); $set('block_name', $getBlock->block_id);
$set('plsBlockError', null); $set('plsBlockError', null);
} }
@@ -118,10 +115,9 @@ class ProductionLineStopResource extends Resource
if (! $blockId) { if (! $blockId) {
$set('plsBlockError', 'Please select a block first.'); $set('plsBlockError', 'Please select a block first.');
return; return;
} } else {
else
{
$set('plsBlockError', null); $set('plsBlockError', null);
} }
}) })
@@ -150,11 +146,9 @@ class ProductionLineStopResource extends Resource
}) })
// ->afterStateUpdated(fn ($set) => $set('line_id', null)) // ->afterStateUpdated(fn ($set) => $set('line_id', null))
->afterStateUpdated(function ($state, callable $set, callable $get) { ->afterStateUpdated(function ($state, callable $set, callable $get) {
if($get('id')) if ($get('id')) {
{
$getShift = ProductionLineStop::where('id', $get('id'))->first(); $getShift = ProductionLineStop::where('id', $get('id'))->first();
if($getShift->shift_id) if ($getShift->shift_id) {
{
$set('shift_id', $getShift->shift_id); $set('shift_id', $getShift->shift_id);
$set('plsShiftError', null); $set('plsShiftError', null);
} }
@@ -165,10 +159,9 @@ class ProductionLineStopResource extends Resource
if (! $shiftId) { if (! $shiftId) {
$set('plsShiftError', 'Please select a shift first.'); $set('plsShiftError', 'Please select a shift first.');
return; return;
} } else {
else
{
$set('plsShiftError', null); $set('plsShiftError', null);
} }
}) })
@@ -196,11 +189,9 @@ class ProductionLineStopResource extends Resource
return optional(ProductionLineStop::latest()->first())->line_id; return optional(ProductionLineStop::latest()->first())->line_id;
}) })
->afterStateUpdated(function ($state, callable $set, callable $get) { ->afterStateUpdated(function ($state, callable $set, callable $get) {
if($get('id')) if ($get('id')) {
{
$getShift = ProductionLineStop::where('id', $get('id'))->first(); $getShift = ProductionLineStop::where('id', $get('id'))->first();
if($getShift->line_id) if ($getShift->line_id) {
{
$set('line_id', $getShift->line_id); $set('line_id', $getShift->line_id);
$set('plsLineError', null); $set('plsLineError', null);
} }
@@ -212,10 +203,9 @@ class ProductionLineStopResource extends Resource
if (! $lineId) { if (! $lineId) {
$set('plsLineError', 'Please select a line first.'); $set('plsLineError', 'Please select a line first.');
return; return;
} } else {
else
{
$set('plsLineError', null); $set('plsLineError', null);
} }
}) })
@@ -253,6 +243,7 @@ class ProductionLineStopResource extends Resource
// Ensure `linestop_id` is not cleared // Ensure `linestop_id` is not cleared
if (! $lineStopId) { if (! $lineStopId) {
$set('lineStop_reason', null); $set('lineStop_reason', null);
return; return;
} }
@@ -275,16 +266,14 @@ class ProductionLineStopResource extends Resource
->before('to_datetime') ->before('to_datetime')
->reactive() ->reactive()
// ->closeOnDateSelection() // ->closeOnDateSelection()
->afterStateUpdated(fn ($state, callable $set, callable $get) => ->afterStateUpdated(fn ($state, callable $set, callable $get) => self::updateStopDuration($get, $set)
self::updateStopDuration($get, $set)
), ),
Forms\Components\DateTimePicker::make('to_datetime') Forms\Components\DateTimePicker::make('to_datetime')
->label('To DateTime') ->label('To DateTime')
->required() ->required()
->after('from_datetime') ->after('from_datetime')
->reactive() ->reactive()
->afterStateUpdated(fn ($state, callable $set, callable $get) => ->afterStateUpdated(fn ($state, callable $set, callable $get) => self::updateStopDuration($get, $set) // self means it calling the function within the class
self::updateStopDuration($get, $set) //self means it calling the function within the class
) )
->extraAttributes(fn ($get) => [ ->extraAttributes(fn ($get) => [
'class' => $get('plsToDateError') ? 'border-red-500' : '', 'class' => $get('plsToDateError') ? 'border-red-500' : '',
@@ -328,14 +317,11 @@ class ProductionLineStopResource extends Resource
$diffInMinutes = $fromTime->diffInMinutes($toTime); $diffInMinutes = $fromTime->diffInMinutes($toTime);
// $set('stop_hour', floor($diffInMinutes / 60)); // $set('stop_hour', floor($diffInMinutes / 60));
// $set('stop_min', $diffInMinutes % 60); // $set('stop_min', $diffInMinutes % 60);
if((floor($diffInMinutes / 60) === 0.0) && ($diffInMinutes % 60 === 0)) if ((floor($diffInMinutes / 60) === 0.0) && ($diffInMinutes % 60 === 0)) {
{
$set('stop_hour', null); $set('stop_hour', null);
$set('stop_min', null); $set('stop_min', null);
$set('plsToDateError', 'Time difference must be atlease a minute.'); $set('plsToDateError', 'Time difference must be atlease a minute.');
} } else {
else
{
$set('stop_hour', floor($diffInMinutes / 60)); $set('stop_hour', floor($diffInMinutes / 60));
$set('stop_min', $diffInMinutes % 60); $set('stop_min', $diffInMinutes % 60);
$set('plsToDateError', null); $set('plsToDateError', null);
@@ -363,6 +349,7 @@ class ProductionLineStopResource extends Resource
$paginator = $livewire->getTableRecords(); $paginator = $livewire->getTableRecords();
$perPage = method_exists($paginator, 'perPage') ? $paginator->perPage() : 10; $perPage = method_exists($paginator, 'perPage') ? $paginator->perPage() : 10;
$currentPage = method_exists($paginator, 'currentPage') ? $paginator->currentPage() : 1; $currentPage = method_exists($paginator, 'currentPage') ? $paginator->currentPage() : 1;
return ($currentPage - 1) * $perPage + $rowLoop->iteration; return ($currentPage - 1) * $perPage + $rowLoop->iteration;
}), }),
Tables\Columns\TextColumn::make('linestop.code') Tables\Columns\TextColumn::make('linestop.code')
@@ -433,7 +420,6 @@ class ProductionLineStopResource extends Resource
Filter::make('advanced_filters') Filter::make('advanced_filters')
->label('Advanced Filters') ->label('Advanced Filters')
->form([ ->form([
// plant // plant
Select::make('Plant') Select::make('Plant')
->label('Select Plant') ->label('Select Plant')
@@ -443,6 +429,7 @@ class ProductionLineStopResource extends Resource
// }) // })
->options(function (callable $get) { ->options(function (callable $get) {
$userHas = Filament::auth()->user()->plant_id; $userHas = Filament::auth()->user()->plant_id;
return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray();
}) })
->reactive() ->reactive()
@@ -463,6 +450,7 @@ class ProductionLineStopResource extends Resource
if (! $plantId) { if (! $plantId) {
return []; return [];
} }
return Line::where('plant_id', $plantId) return Line::where('plant_id', $plantId)
->pluck('name', 'id'); ->pluck('name', 'id');
}) })
@@ -478,6 +466,7 @@ class ProductionLineStopResource extends Resource
if (! $plantId) { if (! $plantId) {
return []; return [];
} }
return Block::where('plant_id', $get('Plant'))->pluck('name', 'id'); return Block::where('plant_id', $get('Plant'))->pluck('name', 'id');
}) })
->reactive() ->reactive()
@@ -509,6 +498,7 @@ class ProductionLineStopResource extends Resource
// ->options(fn () => LineStop::orderBy('code')->whereHas('productionLineStops')->pluck('code', 'id')) // ->options(fn () => LineStop::orderBy('code')->whereHas('productionLineStops')->pluck('code', 'id'))
->options(function (callable $get) { ->options(function (callable $get) {
$pId = $get('Plant'); $pId = $get('Plant');
return LineStop::orderBy('code')->whereHas('productionLineStops', function ($query) use ($pId) { return LineStop::orderBy('code')->whereHas('productionLineStops', function ($query) use ($pId) {
if ($pId) { if ($pId) {
$query->where('plant_id', $pId); $query->where('plant_id', $pId);
@@ -535,19 +525,25 @@ class ProductionLineStopResource extends Resource
return $query->whereRaw('1 = 0'); return $query->whereRaw('1 = 0');
} }
if ($plant = $data['Plant'] ?? null) { if (! empty($data['Plant'])) {// if ($plant = $data['Plant'] ?? null) {
$query->where('plant_id', $plant); $query->where('plant_id', $data['Plant']);
} else {
$userHas = Filament::auth()->user()->plant_id;
if ($userHas && strlen($userHas) > 0) {
return $query->whereRaw('1 = 0');
}
} }
if ($shift = $data['Shift'] ?? null) { if (! empty($data['Shift'])) {// if ($shift = $data['Shift'] ?? null) {
$query->where('shift_id', $shift); $query->where('shift_id', $data['Shift']);
} }
if ($line = $data['Line'] ?? null) { if (! empty($data['Line'])) {// if ($line = $data['Line'] ?? null) {
$query->where('line_id', $line); $query->where('line_id', $data['Line']);
} }
if ($code = $data['line_stop_id'] ?? null) { if (! empty($data['line_stop_id'])) { // if ($code = $data['line_stop_id'] ?? null) {
// Find the linestop_id by code entered // Find the linestop_id by code entered
// $lineStop = \App\Models\LineStop::where('code', 'like', "%{$code}%")->first(); // $lineStop = \App\Models\LineStop::where('code', 'like', "%{$code}%")->first();
@@ -558,15 +554,15 @@ class ProductionLineStopResource extends Resource
// // If no match found, you can either handle it as an error or return no results // // If no match found, you can either handle it as an error or return no results
// $query->where('linestop_id', null); // This will return no results if no match // $query->where('linestop_id', null); // This will return no results if no match
// } // }
$query->where('linestop_id', $code); $query->where('linestop_id', $data['line_stop_id']);
} }
if ($from = $data['created_from'] ?? null) { if (! empty($data['created_from'])) {// if ($from = $data['created_from'] ?? null) {
$query->where('created_at', '>=', $from); $query->where('created_at', '>=', $data['created_from']);
} }
if ($to = $data['created_to'] ?? null) { if (! empty($data['created_to'])) {// if ($to = $data['created_to'] ?? null) {
$query->where('created_at', '<=', $to); $query->where('created_at', '<=', $data['created_to']);
} }
// return $query; // return $query;
}) })
@@ -575,6 +571,12 @@ class ProductionLineStopResource extends Resource
if (! empty($data['Plant'])) { if (! empty($data['Plant'])) {
$indicators[] = 'Plant: '.Plant::where('id', $data['Plant'])->value('name'); $indicators[] = 'Plant: '.Plant::where('id', $data['Plant'])->value('name');
} else {
$userHas = Filament::auth()->user()->plant_id;
if ($userHas && strlen($userHas) > 0) {
return 'Plant: Choose plant to filter records.';
}
} }
if (! empty($data['Shift'])) { if (! empty($data['Shift'])) {
@@ -599,7 +601,7 @@ class ProductionLineStopResource extends Resource
} }
return $indicators; return $indicators;
}) }),
]) ])
->filtersFormMaxHeight('280px') ->filtersFormMaxHeight('280px')
->actions([ ->actions([
@@ -611,7 +613,7 @@ class ProductionLineStopResource extends Resource
Tables\Actions\DeleteBulkAction::make(), Tables\Actions\DeleteBulkAction::make(),
Tables\Actions\ForceDeleteBulkAction::make(), Tables\Actions\ForceDeleteBulkAction::make(),
Tables\Actions\RestoreBulkAction::make(), Tables\Actions\RestoreBulkAction::make(),
FilamentExportBulkAction::make('export') FilamentExportBulkAction::make('export'),
]), ]),
]) ])
->headerActions([ ->headerActions([

View File

@@ -6,7 +6,6 @@ use AlperenErsoy\FilamentExport\Actions\FilamentExportBulkAction;
use App\Filament\Exports\ProductionPlanExporter; use App\Filament\Exports\ProductionPlanExporter;
use App\Filament\Imports\ProductionPlanImporter; use App\Filament\Imports\ProductionPlanImporter;
use App\Filament\Resources\ProductionPlanResource\Pages; use App\Filament\Resources\ProductionPlanResource\Pages;
use App\Filament\Resources\ProductionPlanResource\RelationManagers;
use App\Models\Block; use App\Models\Block;
use App\Models\Line; use App\Models\Line;
use App\Models\Plant; use App\Models\Plant;
@@ -16,19 +15,18 @@ use Carbon\Carbon;
use Filament\Facades\Filament; use Filament\Facades\Filament;
use Filament\Forms; use Filament\Forms;
use Filament\Forms\Components\DateTimePicker; use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\Section;
use Filament\Forms\Components\Select;
use Filament\Forms\Form; use Filament\Forms\Form;
use Filament\Forms\Get; use Filament\Forms\Get;
use Filament\Resources\Resource; use Filament\Resources\Resource;
use Filament\Tables; use Filament\Tables;
use Filament\Tables\Actions\ExportAction;
use Filament\Tables\Actions\ImportAction; use Filament\Tables\Actions\ImportAction;
use Filament\Tables\Filters\Filter;
use Filament\Tables\Table; use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope; use Illuminate\Database\Eloquent\SoftDeletingScope;
use Filament\Forms\Components\Section;
use Filament\Forms\Components\Select;
use Filament\Tables\Actions\ExportAction;
use Filament\Tables\Filters\Filter;
use Illuminate\Support\Facades\Request;
class ProductionPlanResource extends Resource class ProductionPlanResource extends Resource
{ {
@@ -55,6 +53,7 @@ class ProductionPlanResource extends Resource
->reactive() ->reactive()
->options(function (callable $get) { ->options(function (callable $get) {
$userHas = Filament::auth()->user()->plant_id; $userHas = Filament::auth()->user()->plant_id;
return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray();
}) })
->default(function () { ->default(function () {
@@ -67,10 +66,9 @@ class ProductionPlanResource extends Resource
$set('block_name', null); $set('block_name', null);
if (! $plantId) { if (! $plantId) {
$set('ppPlantError', 'Please select a plant first.'); $set('ppPlantError', 'Please select a plant first.');
return; return;
} } else {
else
{
$set('ppPlantError', null); $set('ppPlantError', null);
} }
}) })
@@ -95,16 +93,15 @@ class ProductionPlanResource extends Resource
->reactive() ->reactive()
->default(function () { ->default(function () {
$latestShiftId = optional(ProductionPlan::latest()->first())->shift_id; $latestShiftId = optional(ProductionPlan::latest()->first())->shift_id;
return optional(Shift::where('id', $latestShiftId)->first())->block_id; return optional(Shift::where('id', $latestShiftId)->first())->block_id;
}) })
// ->afterStateUpdated(fn ($set) => $set('shift_id', null)) // ->afterStateUpdated(fn ($set) => $set('shift_id', null))
->afterStateUpdated(function ($state, callable $set, callable $get) { ->afterStateUpdated(function ($state, callable $set, callable $get) {
if($get('id')) if ($get('id')) {
{
$getShift = ProductionPlan::where('id', $get('id'))->first(); $getShift = ProductionPlan::where('id', $get('id'))->first();
$getBlock = Shift::where('id', $getShift->shift_id)->first(); $getBlock = Shift::where('id', $getShift->shift_id)->first();
if($getBlock->block_id) if ($getBlock->block_id) {
{
$set('block_name', $getBlock->block_id); $set('block_name', $getBlock->block_id);
$set('ppBlockError', null); $set('ppBlockError', null);
} }
@@ -115,10 +112,9 @@ class ProductionPlanResource extends Resource
if (! $blockId) { if (! $blockId) {
$set('ppBlockError', 'Please select a block first.'); $set('ppBlockError', 'Please select a block first.');
return; return;
} } else {
else
{
$set('ppBlockError', null); $set('ppBlockError', null);
} }
}) })
@@ -148,11 +144,9 @@ class ProductionPlanResource extends Resource
}) })
// ->afterStateUpdated(fn ($set) => $set('line_id', null)) // ->afterStateUpdated(fn ($set) => $set('line_id', null))
->afterStateUpdated(function ($state, callable $set, callable $get) { ->afterStateUpdated(function ($state, callable $set, callable $get) {
if($get('id')) if ($get('id')) {
{
$getShift = ProductionPlan::where('id', $get('id'))->first(); $getShift = ProductionPlan::where('id', $get('id'))->first();
if($getShift->shift_id) if ($getShift->shift_id) {
{
$set('shift_id', $getShift->shift_id); $set('shift_id', $getShift->shift_id);
$set('ppShiftError', null); $set('ppShiftError', null);
} }
@@ -163,10 +157,9 @@ class ProductionPlanResource extends Resource
if (! $curShiftId) { if (! $curShiftId) {
$set('ppShiftError', 'Please select a shift first.'); $set('ppShiftError', 'Please select a shift first.');
return; return;
} } else {
else
{
$set('ppShiftError', null); $set('ppShiftError', null);
} }
}) })
@@ -198,17 +191,13 @@ class ProductionPlanResource extends Resource
// return optional(ProductionPlan::latest()->first())->line_id; // return optional(ProductionPlan::latest()->first())->line_id;
// }) // })
->afterStateUpdated(function ($state, callable $set, callable $get) { ->afterStateUpdated(function ($state, callable $set, callable $get) {
if($get('id')) if ($get('id')) {
{
$getShift = ProductionPlan::where('id', $get('id'))->first(); $getShift = ProductionPlan::where('id', $get('id'))->first();
if($getShift->line_id) if ($getShift->line_id) {
{
$set('line_id', $getShift->line_id); $set('line_id', $getShift->line_id);
$set('ppLineError', null); $set('ppLineError', null);
} }
} } else {
else
{
$currentDT = Carbon::now()->toDateTimeString(); $currentDT = Carbon::now()->toDateTimeString();
$set('created_at', $currentDT); $set('created_at', $currentDT);
$set('update_date', null); $set('update_date', null);
@@ -219,13 +208,11 @@ class ProductionPlanResource extends Resource
if (! $lineId) { if (! $lineId) {
$set('ppLineError', 'Please select a line first.'); $set('ppLineError', 'Please select a line first.');
return; return;
} } else {
else
{
$isUpdate = ! empty($get('id')); $isUpdate = ! empty($get('id'));
if (!$isUpdate) if (! $isUpdate) {
{
$exists = ProductionPlan::where('plant_id', $get('plant_id')) $exists = ProductionPlan::where('plant_id', $get('plant_id'))
->where('shift_id', $get('shift_id')) ->where('shift_id', $get('shift_id'))
->where('line_id', $get('line_id')) ->where('line_id', $get('line_id'))
@@ -233,14 +220,12 @@ class ProductionPlanResource extends Resource
->latest() ->latest()
->exists(); ->exists();
if ($exists) if ($exists) {
{
$set('line_id', null); $set('line_id', null);
$set('ppLineError', 'Production plan already updated.'); $set('ppLineError', 'Production plan already updated.');
return; return;
} } else {
else
{
$existShifts = ProductionPlan::where('plant_id', $get('plant_id')) $existShifts = ProductionPlan::where('plant_id', $get('plant_id'))
->where('shift_id', $get('shift_id')) ->where('shift_id', $get('shift_id'))
->where('line_id', $get('line_id')) ->where('line_id', $get('line_id'))
@@ -248,8 +233,7 @@ class ProductionPlanResource extends Resource
->latest() ->latest()
->exists(); ->exists();
if ($existShifts) //if ($existShifts->count() > 0) if ($existShifts) { // if ($existShifts->count() > 0)
{
// $currentDate = date('Y-m-d'); // $currentDate = date('Y-m-d');
$yesterday = date('Y-m-d', strtotime('-1 days')); $yesterday = date('Y-m-d', strtotime('-1 days'));
@@ -274,11 +258,10 @@ class ProductionPlanResource extends Resource
$set('line_id', null); $set('line_id', null);
$set('ppLineError', 'Production plan already updated.'); $set('ppLineError', 'Production plan already updated.');
// $set('ppLineError', 'Valid (From: '.$from_dt.', To: '.$to_dt.')'); // $set('ppLineError', 'Valid (From: '.$from_dt.', To: '.$to_dt.')');
return; return;
} } else {
else
{
$currentDate = date('Y-m-d'); $currentDate = date('Y-m-d');
$shiftId = Shift::where('id', $get('shift_id')) $shiftId = Shift::where('id', $get('shift_id'))
@@ -302,16 +285,16 @@ class ProductionPlanResource extends Resource
$set('line_id', null); $set('line_id', null);
$set('ppLineError', 'Choosed a invalid shift.'); $set('ppLineError', 'Choosed a invalid shift.');
// $set('ppLineError', 'Valid (From: '.$from_dt.', To: '.$to_dt.')'); // $set('ppLineError', 'Valid (From: '.$from_dt.', To: '.$to_dt.')');
return; return;
} }
} }
$set('ppLineError', null); $set('ppLineError', null);
return; return;
} } else {
else
{
// $currentDate = date('Y-m-d'); // $currentDate = date('Y-m-d');
$yesterday = date('Y-m-d', strtotime('-1 days')); $yesterday = date('Y-m-d', strtotime('-1 days'));
@@ -339,11 +322,10 @@ class ProductionPlanResource extends Resource
$set('update_date', '1'); $set('update_date', '1');
$set('ppLineError', null); $set('ppLineError', null);
// $set('ppLineError', 'Valid (From: '.$from_dt.', To: '.$to_dt.')'); // $set('ppLineError', 'Valid (From: '.$from_dt.', To: '.$to_dt.')');
return; return;
} } else {
else
{
$currentDate = date('Y-m-d'); $currentDate = date('Y-m-d');
$shiftId = Shift::where('id', $get('shift_id')) $shiftId = Shift::where('id', $get('shift_id'))
@@ -367,12 +349,14 @@ class ProductionPlanResource extends Resource
$set('line_id', null); $set('line_id', null);
$set('ppLineError', 'Choosed a invalid shift.'); $set('ppLineError', 'Choosed a invalid shift.');
// $set('ppLineError', 'Valid (From: '.$from_dt.', To: '.$to_dt.')'); // $set('ppLineError', 'Valid (From: '.$from_dt.', To: '.$to_dt.')');
return; return;
} }
} }
$set('ppLineError', null); $set('ppLineError', null);
return; return;
} }
@@ -449,10 +433,8 @@ class ProductionPlanResource extends Resource
->afterStateUpdated(function ($state, callable $set, callable $get) { ->afterStateUpdated(function ($state, callable $set, callable $get) {
$planQuan = $get('plan_quantity'); $planQuan = $get('plan_quantity');
if(!$get('update_date') ) if (! $get('update_date')) {
{ if (! $get('id')) {
if(!$get('id'))
{
$currentDT = Carbon::now()->toDateTimeString(); $currentDT = Carbon::now()->toDateTimeString();
$set('created_at', $currentDT); $set('created_at', $currentDT);
} }
@@ -460,10 +442,9 @@ class ProductionPlanResource extends Resource
if (! $planQuan) { if (! $planQuan) {
$set('ppPlanQuanError', 'Scan the valid plan quantity.'); $set('ppPlanQuanError', 'Scan the valid plan quantity.');
return; return;
} } else {
else
{
$set('ppPlanQuanError', null); $set('ppPlanQuanError', null);
} }
}) })
@@ -529,6 +510,7 @@ class ProductionPlanResource extends Resource
$paginator = $livewire->getTableRecords(); $paginator = $livewire->getTableRecords();
$perPage = method_exists($paginator, 'perPage') ? $paginator->perPage() : 10; $perPage = method_exists($paginator, 'perPage') ? $paginator->perPage() : 10;
$currentPage = method_exists($paginator, 'currentPage') ? $paginator->currentPage() : 1; $currentPage = method_exists($paginator, 'currentPage') ? $paginator->currentPage() : 1;
return ($currentPage - 1) * $perPage + $rowLoop->iteration; return ($currentPage - 1) * $perPage + $rowLoop->iteration;
}), }),
Tables\Columns\TextColumn::make('plan_quantity') Tables\Columns\TextColumn::make('plan_quantity')
@@ -593,6 +575,7 @@ class ProductionPlanResource extends Resource
// }) // })
->options(function (callable $get) { ->options(function (callable $get) {
$userHas = Filament::auth()->user()->plant_id; $userHas = Filament::auth()->user()->plant_id;
return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray();
}) })
->reactive() ->reactive()
@@ -612,6 +595,7 @@ class ProductionPlanResource extends Resource
if (! $plantId) { if (! $plantId) {
return []; return [];
} }
return Line::where('plant_id', $plantId) return Line::where('plant_id', $plantId)
->pluck('name', 'id'); ->pluck('name', 'id');
}) })
@@ -627,6 +611,7 @@ class ProductionPlanResource extends Resource
if (! $plantId) { if (! $plantId) {
return []; return [];
} }
return Block::where('plant_id', $get('Plant'))->pluck('name', 'id'); return Block::where('plant_id', $get('Plant'))->pluck('name', 'id');
}) })
->reactive() ->reactive()
@@ -669,25 +654,32 @@ class ProductionPlanResource extends Resource
return $query->whereRaw('1 = 0'); return $query->whereRaw('1 = 0');
} }
if ($plant = $data['Plant'] ?? null) { if (! empty($data['Plant'])) {// if ($plant = $data['Plant'] ?? null) {
$query->where('plant_id', $plant); $query->where('plant_id', $data['Plant']);
} else {
$userHas = Filament::auth()->user()->plant_id;
if ($userHas && strlen($userHas) > 0) {
return $query->whereRaw('1 = 0');
}
} }
if ($shift = $data['Shift'] ?? null) { if (! empty($data['Shift'])) {// if ($shift = $data['Shift'] ?? null) {
$query->where('shift_id', $shift); $query->where('shift_id', $data['Shift']);
} }
if ($line = $data['Line'] ?? null) { if (! empty($data['Line'])) {// if ($line = $data['Line'] ?? null) {
$query->where('line_id', $line); $query->where('line_id', $data['Line']);
} }
if ($from = $data['created_from'] ?? null) { if (! empty($data['created_from'])) {// if ($from = $data['created_from'] ?? null) {
$query->where('created_at', '>=', $from); $query->where('created_at', '>=', $data['created_from']);
} }
if ($to = $data['created_to'] ?? null) { if (! empty($data['created_to'])) {// if ($to = $data['created_to'] ?? null) {
$query->where('created_at', '<=', $to); $query->where('created_at', '<=', $data['created_to']);
} }
return $query; return $query;
}) })
->indicateUsing(function (array $data) { ->indicateUsing(function (array $data) {
@@ -695,6 +687,12 @@ class ProductionPlanResource extends Resource
if (! empty($data['Plant'])) { if (! empty($data['Plant'])) {
$indicators[] = 'Plant: '.Plant::where('id', $data['Plant'])->value('name'); $indicators[] = 'Plant: '.Plant::where('id', $data['Plant'])->value('name');
} else {
$userHas = Filament::auth()->user()->plant_id;
if ($userHas && strlen($userHas) > 0) {
return 'Plant: Choose plant to filter records.';
}
} }
if (! empty($data['Shift'])) { if (! empty($data['Shift'])) {
@@ -714,7 +712,7 @@ class ProductionPlanResource extends Resource
} }
return $indicators; return $indicators;
}) }),
]) ])
->filtersFormMaxHeight('280px') ->filtersFormMaxHeight('280px')
->actions([ ->actions([
@@ -726,7 +724,7 @@ class ProductionPlanResource extends Resource
Tables\Actions\DeleteBulkAction::make(), Tables\Actions\DeleteBulkAction::make(),
Tables\Actions\ForceDeleteBulkAction::make(), Tables\Actions\ForceDeleteBulkAction::make(),
Tables\Actions\RestoreBulkAction::make(), Tables\Actions\RestoreBulkAction::make(),
FilamentExportBulkAction::make('export') FilamentExportBulkAction::make('export'),
]), ]),
]) ])
->headerActions([ ->headerActions([

View File

@@ -6,8 +6,6 @@ use AlperenErsoy\FilamentExport\Actions\FilamentExportBulkAction as ActionsFilam
use App\Filament\Exports\ProductionQuantityExporter; use App\Filament\Exports\ProductionQuantityExporter;
use App\Filament\Imports\ProductionQuantityImporter; use App\Filament\Imports\ProductionQuantityImporter;
use App\Filament\Resources\ProductionQuantityResource\Pages; use App\Filament\Resources\ProductionQuantityResource\Pages;
use App\Filament\Resources\ProductionQuantityResource\RelationManagers;
use App\Forms\Components\PlantSelect;
use App\Models\Block; use App\Models\Block;
use App\Models\Item; use App\Models\Item;
use App\Models\Line; use App\Models\Line;
@@ -18,29 +16,25 @@ use Carbon\Carbon;
use Filament\Facades\Filament; use Filament\Facades\Filament;
use Filament\Forms; use Filament\Forms;
use Filament\Forms\Components\DateTimePicker; use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\Hidden;
use Filament\Forms\Form;
use Filament\Forms\Get;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Actions\ImportAction;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use Filament\Forms\Components\Section; use Filament\Forms\Components\Section;
use Filament\Forms\Components\Select; use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput; use Filament\Forms\Components\TextInput;
use Filament\Forms\Concerns\InteractsWithForms; use Filament\Forms\Form;
use Filament\Forms\Get;
use Filament\Notifications\Notification; use Filament\Notifications\Notification;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Actions\ExportAction; use Filament\Tables\Actions\ExportAction;
use Livewire\Livewire; use Filament\Tables\Actions\ImportAction;
// use Filament\Forms\Components\View;
use Filament\Tables\Actions\FilamentExportBulkAction;
use Filament\Tables\Filters\Filter; use Filament\Tables\Filters\Filter;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;
// use Filament\Forms\Components\View;
use Livewire\Livewire;
class ProductionQuantityResource extends Resource class ProductionQuantityResource extends Resource
{ {
protected static ?string $model = ProductionQuantity::class; protected static ?string $model = ProductionQuantity::class;
protected static ?string $navigationIcon = 'heroicon-o-rectangle-stack'; protected static ?string $navigationIcon = 'heroicon-o-rectangle-stack';
@@ -52,7 +46,6 @@ class ProductionQuantityResource extends Resource
protected static ?int $navigationSort = 1; protected static ?int $navigationSort = 1;
// public $plant_id; // public $plant_id;
public static function form(Form $form): Form public static function form(Form $form): Form
{ {
@@ -69,6 +62,7 @@ class ProductionQuantityResource extends Resource
->columnSpan(2) // 1 ->columnSpan(2) // 1
->options(function (callable $get) { ->options(function (callable $get) {
$userHas = Filament::auth()->user()->plant_id; $userHas = Filament::auth()->user()->plant_id;
return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray();
}) })
// ->default(fn () => optional(ProductionQuantity::latest()->first())->plant_id) // ->default(fn () => optional(ProductionQuantity::latest()->first())->plant_id)
@@ -81,13 +75,11 @@ class ProductionQuantityResource extends Resource
->afterStateUpdated(function ($state, $set, callable $get, $livewire) { ->afterStateUpdated(function ($state, $set, callable $get, $livewire) {
$plantId = $get('plant_id'); $plantId = $get('plant_id');
$set('block_name', null); $set('block_name', null);
if (!$plantId) if (! $plantId) {
{
$set('pqPlantError', 'Please select a plant first.'); $set('pqPlantError', 'Please select a plant first.');
return; return;
} } else {
else
{
$set('validationError', null); $set('validationError', null);
$set('pqPlantError', null); $set('pqPlantError', null);
} }
@@ -138,15 +130,14 @@ class ProductionQuantityResource extends Resource
->reactive() ->reactive()
->default(function () { ->default(function () {
$latestShiftId = optional(ProductionQuantity::latest()->first())->shift_id; $latestShiftId = optional(ProductionQuantity::latest()->first())->shift_id;
return optional(Shift::where('id', $latestShiftId)->first())->block_id; return optional(Shift::where('id', $latestShiftId)->first())->block_id;
}) })
->afterStateUpdated(function ($state, callable $set, callable $get) { ->afterStateUpdated(function ($state, callable $set, callable $get) {
if($get('id')) if ($get('id')) {
{
$getShift = ProductionQuantity::where('id', $get('id'))->first(); $getShift = ProductionQuantity::where('id', $get('id'))->first();
$getBlock = Shift::where('id', $getShift->shift_id)->first(); $getBlock = Shift::where('id', $getShift->shift_id)->first();
if($getBlock->block_id) if ($getBlock->block_id) {
{
$set('block_name', $getBlock->block_id); $set('block_name', $getBlock->block_id);
$set('pqBlockError', null); $set('pqBlockError', null);
} }
@@ -160,10 +151,9 @@ class ProductionQuantityResource extends Resource
if (! $blockId) { if (! $blockId) {
$set('pqBlockError', 'Please select a block first.'); $set('pqBlockError', 'Please select a block first.');
return; return;
} } else {
else
{
$set('validationError', null); $set('validationError', null);
$set('pqBlockError', null); $set('pqBlockError', null);
} }
@@ -194,11 +184,9 @@ class ProductionQuantityResource extends Resource
}) })
// ->afterStateUpdated(fn ($set) => $set('line_id', null)) // ->afterStateUpdated(fn ($set) => $set('line_id', null))
->afterStateUpdated(function ($state, callable $set, callable $get) { ->afterStateUpdated(function ($state, callable $set, callable $get) {
if($get('id')) if ($get('id')) {
{
$getShift = ProductionQuantity::where('id', $get('id'))->first(); $getShift = ProductionQuantity::where('id', $get('id'))->first();
if($getShift->shift_id) if ($getShift->shift_id) {
{
$set('shift_id', $getShift->shift_id); $set('shift_id', $getShift->shift_id);
$set('pqShiftError', null); $set('pqShiftError', null);
} }
@@ -209,10 +197,9 @@ class ProductionQuantityResource extends Resource
if (! $curShiftId) { if (! $curShiftId) {
$set('pqShiftError', 'Please select a shift first.'); $set('pqShiftError', 'Please select a shift first.');
return; return;
} } else {
else
{
$set('validationError', null); $set('validationError', null);
$set('pqShiftError', null); $set('pqShiftError', null);
} }
@@ -246,11 +233,9 @@ class ProductionQuantityResource extends Resource
return optional(ProductionQuantity::latest()->first())->line_id; return optional(ProductionQuantity::latest()->first())->line_id;
}) })
->afterStateUpdated(function ($state, callable $set, callable $get) { ->afterStateUpdated(function ($state, callable $set, callable $get) {
if($get('id')) if ($get('id')) {
{
$getShift = ProductionQuantity::where('id', $get('id'))->first(); $getShift = ProductionQuantity::where('id', $get('id'))->first();
if($getShift->line_id) if ($getShift->line_id) {
{
$set('line_id', $getShift->line_id); $set('line_id', $getShift->line_id);
$set('pqLineError', null); $set('pqLineError', null);
} }
@@ -265,10 +250,9 @@ class ProductionQuantityResource extends Resource
if (! $lineId) { if (! $lineId) {
$set('pqLineError', 'Please select a line first.'); $set('pqLineError', 'Please select a line first.');
return; return;
} } else {
else
{
$set('validationError', null); $set('validationError', null);
$set('pqLineError', null); $set('pqLineError', null);
$set('item_id', null); $set('item_id', null);
@@ -296,7 +280,7 @@ class ProductionQuantityResource extends Resource
// 'x-on:change' => "\$wire.dispatch('filtersUpdated')", // Dispatch Livewire event from Alpine.js // 'x-on:change' => "\$wire.dispatch('filtersUpdated')", // Dispatch Livewire event from Alpine.js
// ]) // ])
->extraAttributes([ ->extraAttributes([
'x-on:change' => "\$wire.dispatch('filtersUpdated', { lineId: \$event.target.value })" 'x-on:change' => "\$wire.dispatch('filtersUpdated', { lineId: \$event.target.value })",
]) ])
->extraAttributes(fn ($get) => [ ->extraAttributes(fn ($get) => [
'class' => $get('pqLineError') ? 'border-red-500' : '', 'class' => $get('pqLineError') ? 'border-red-500' : '',
@@ -328,21 +312,20 @@ class ProductionQuantityResource extends Resource
// $latestProductionOrder = ProductionQuantity::latest()->first()->production_order; // $latestProductionOrder = ProductionQuantity::latest()->first()->production_order;
// return $latestProductionOrder ?? null; // return $latestProductionOrder ?? null;
$latestProduction = ProductionQuantity::latest()->first(); $latestProduction = ProductionQuantity::latest()->first();
return $latestProduction ? $latestProduction->production_order : null; return $latestProduction ? $latestProduction->production_order : null;
}) })
->afterStateUpdated(function ($state, callable $get, callable $set): void { ->afterStateUpdated(function ($state, callable $get, callable $set): void {
if(!is_numeric($get('production_order')) || !preg_match('/^[1-9][0-9]{6,13}$/', $get('production_order'))) if (! is_numeric($get('production_order')) || ! preg_match('/^[1-9][0-9]{6,13}$/', $get('production_order'))) {
{
$set('item_code', null); $set('item_code', null);
$set('item_id', null); $set('item_id', null);
$set('serial_number', null); $set('serial_number', null);
$set('production_order', null); $set('production_order', null);
$set('prodOrdError', "Must be a numeric value with 7 to 14 digits."); $set('prodOrdError', 'Must be a numeric value with 7 to 14 digits.');
$set('validationError', null); $set('validationError', null);
return; return;
} } else {
else
{
$set('item_code', null); $set('item_code', null);
$set('item_id', null); $set('item_id', null);
// $set('item_description', null); // $set('item_description', null);
@@ -350,6 +333,7 @@ class ProductionQuantityResource extends Resource
$set('production_order', $state); $set('production_order', $state);
$set('prodOrdError', null); $set('prodOrdError', null);
$set('validationError', null); $set('validationError', null);
return; return;
// if (empty($state)) { // if (empty($state)) {
// } // }
@@ -971,6 +955,7 @@ class ProductionQuantityResource extends Resource
$paginator = $livewire->getTableRecords(); $paginator = $livewire->getTableRecords();
$perPage = method_exists($paginator, 'perPage') ? $paginator->perPage() : 10; $perPage = method_exists($paginator, 'perPage') ? $paginator->perPage() : 10;
$currentPage = method_exists($paginator, 'currentPage') ? $paginator->currentPage() : 1; $currentPage = method_exists($paginator, 'currentPage') ? $paginator->currentPage() : 1;
return ($currentPage - 1) * $perPage + $rowLoop->iteration; return ($currentPage - 1) * $perPage + $rowLoop->iteration;
}), }),
Tables\Columns\TextColumn::make('production_order') Tables\Columns\TextColumn::make('production_order')
@@ -1049,6 +1034,7 @@ class ProductionQuantityResource extends Resource
// }) // })
->options(function (callable $get) { ->options(function (callable $get) {
$userHas = Filament::auth()->user()->plant_id; $userHas = Filament::auth()->user()->plant_id;
return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray();
}) })
->reactive() ->reactive()
@@ -1071,6 +1057,7 @@ class ProductionQuantityResource extends Resource
if (! $plantId) { if (! $plantId) {
return []; return [];
} }
return Line::where('plant_id', $plantId) return Line::where('plant_id', $plantId)
->pluck('name', 'id'); ->pluck('name', 'id');
}) })
@@ -1089,6 +1076,7 @@ class ProductionQuantityResource extends Resource
if (! $plantId) { if (! $plantId) {
return []; return [];
} }
return Block::where('plant_id', $get('Plant'))->pluck('name', 'id'); return Block::where('plant_id', $get('Plant'))->pluck('name', 'id');
}) })
->reactive() ->reactive()
@@ -1133,10 +1121,9 @@ class ProductionQuantityResource extends Resource
$plantId = $get('Plant'); $plantId = $get('Plant');
if (! $plantId) { if (! $plantId) {
return Item::distinct()->whereHas('productionQuantities')->pluck('code', 'id'); return Item::whereHas('productionQuantities')->distinct()->pluck('code', 'id');
} } else {
else { return Item::whereHas('productionQuantities')->where('plant_id', $plantId)->distinct()->pluck('code', 'id');
return Item::where('plant_id', $plantId)->whereHas('productionQuantities')->distinct()->pluck('code', 'id');
} }
// return Item::whereHas('stickerMasters', function ($query) use ($pId) { // return Item::whereHas('stickerMasters', function ($query) use ($pId) {
// if ($pId) { // if ($pId) {
@@ -1156,8 +1143,7 @@ class ProductionQuantityResource extends Resource
if (! $plantId) { if (! $plantId) {
return ProductionQuantity::whereNotNull('sap_msg_status')->select('sap_msg_status')->distinct()->pluck('sap_msg_status', 'sap_msg_status'); return ProductionQuantity::whereNotNull('sap_msg_status')->select('sap_msg_status')->distinct()->pluck('sap_msg_status', 'sap_msg_status');
} } else {
else {
return ProductionQuantity::where('plant_id', $plantId)->whereNotNull('sap_msg_status')->select('sap_msg_status')->distinct()->pluck('sap_msg_status', 'sap_msg_status'); return ProductionQuantity::where('plant_id', $plantId)->whereNotNull('sap_msg_status')->select('sap_msg_status')->distinct()->pluck('sap_msg_status', 'sap_msg_status');
} }
}) })
@@ -1171,24 +1157,15 @@ class ProductionQuantityResource extends Resource
$plantId = $get('Plant'); $plantId = $get('Plant');
$lineId = $get('Line'); $lineId = $get('Line');
$shiftId = $get('Shift'); $shiftId = $get('Shift');
if (!$plantId && !$lineId && !$shiftId) if (! $plantId && ! $lineId && ! $shiftId) {
{
return ProductionQuantity::whereNotNull('operator_id')->select('operator_id')->distinct()->pluck('operator_id', 'operator_id'); return ProductionQuantity::whereNotNull('operator_id')->select('operator_id')->distinct()->pluck('operator_id', 'operator_id');
} } elseif ($plantId && ! $lineId && ! $shiftId) {
else if ($plantId && !$lineId && !$shiftId)
{
return ProductionQuantity::where('plant_id', $plantId)->whereNotNull('operator_id')->select('operator_id')->distinct()->pluck('operator_id', 'operator_id'); return ProductionQuantity::where('plant_id', $plantId)->whereNotNull('operator_id')->select('operator_id')->distinct()->pluck('operator_id', 'operator_id');
} } elseif ($plantId && $lineId && ! $shiftId) {
else if ($plantId && $lineId && !$shiftId)
{
return ProductionQuantity::where('plant_id', $plantId)->where('line_id', $lineId)->whereNotNull('operator_id')->select('operator_id')->distinct()->pluck('operator_id', 'operator_id'); return ProductionQuantity::where('plant_id', $plantId)->where('line_id', $lineId)->whereNotNull('operator_id')->select('operator_id')->distinct()->pluck('operator_id', 'operator_id');
} } elseif ($plantId && ! $lineId && $shiftId) {
else if ($plantId && !$lineId && $shiftId)
{
return ProductionQuantity::where('plant_id', $plantId)->where('shift_id', $shiftId)->whereNotNull('operator_id')->select('operator_id')->distinct()->pluck('operator_id', 'operator_id'); return ProductionQuantity::where('plant_id', $plantId)->where('shift_id', $shiftId)->whereNotNull('operator_id')->select('operator_id')->distinct()->pluck('operator_id', 'operator_id');
} } else { // if ($plantId && $lineId && $shiftId)
else// if ($plantId && $lineId && $shiftId)
{
return ProductionQuantity::where('plant_id', $plantId)->where('line_id', $lineId)->where('shift_id', $shiftId)->whereNotNull('operator_id')->select('operator_id')->distinct()->pluck('operator_id', 'operator_id'); return ProductionQuantity::where('plant_id', $plantId)->where('line_id', $lineId)->where('shift_id', $shiftId)->whereNotNull('operator_id')->select('operator_id')->distinct()->pluck('operator_id', 'operator_id');
} }
}) })
@@ -1212,16 +1189,22 @@ class ProductionQuantityResource extends Resource
return $query->whereRaw('1 = 0'); return $query->whereRaw('1 = 0');
} }
if ($plant = $data['Plant'] ?? null) { if (! empty($data['Plant'])) {// if ($plant = $data['Plant'] ?? null) {
$query->where('plant_id', $plant); $query->where('plant_id', $data['Plant']);
} else {
$userHas = Filament::auth()->user()->plant_id;
if ($userHas && strlen($userHas) > 0) {
return $query->whereRaw('1 = 0');
}
} }
if ($shift = $data['Shift'] ?? null) { if (! empty($data['Shift'])) {// if ($shift = $data['Shift'] ?? null) {
$query->where('shift_id', $shift); $query->where('shift_id', $data['Shift']);
} }
if ($line = $data['Line'] ?? null) { if (! empty($data['Line'])) {// if ($line = $data['Line'] ?? null) {
$query->where('line_id', $line); $query->where('line_id', $data['Line']);
} }
if (! empty($data['production_order'])) { if (! empty($data['production_order'])) {
@@ -1244,12 +1227,12 @@ class ProductionQuantityResource extends Resource
$query->where('operator_id', $data['operator_id']); $query->where('operator_id', $data['operator_id']);
} }
if ($from = $data['created_from'] ?? null) { if (! empty($data['created_from'])) {// if ($from = $data['created_from'] ?? null) {
$query->where('created_at', '>=', $from); $query->where('created_at', '>=', $data['created_from']);
} }
if ($to = $data['created_to'] ?? null) { if (! empty($data['created_to'])) {// if ($to = $data['created_to'] ?? null) {
$query->where('created_at', '<=', $to); $query->where('created_at', '<=', $data['created_to']);
} }
// return $query; // return $query;
@@ -1259,6 +1242,12 @@ class ProductionQuantityResource extends Resource
if (! empty($data['Plant'])) { if (! empty($data['Plant'])) {
$indicators[] = 'Plant: '.Plant::where('id', $data['Plant'])->value('name'); $indicators[] = 'Plant: '.Plant::where('id', $data['Plant'])->value('name');
} else {
$userHas = Filament::auth()->user()->plant_id;
if ($userHas && strlen($userHas) > 0) {
return 'Plant: Choose plant to filter records.';
}
} }
if (! empty($data['Shift'])) { if (! empty($data['Shift'])) {
@@ -1298,7 +1287,7 @@ class ProductionQuantityResource extends Resource
} }
return $indicators; return $indicators;
}) }),
]) ])
->filtersFormMaxHeight('280px') ->filtersFormMaxHeight('280px')
->actions([ ->actions([
@@ -1370,7 +1359,6 @@ class ProductionQuantityResource extends Resource
return 'Production Reports'; return 'Production Reports';
} }
// public function triggerChartUpdate(): void // public function triggerChartUpdate(): void
// { // {
// if (session()->has('select_plant') && session()->has('select_line')) { // if (session()->has('select_plant') && session()->has('select_line')) {

File diff suppressed because it is too large Load Diff

View File

@@ -5,30 +5,28 @@ namespace App\Filament\Resources;
use App\Filament\Exports\ReworkLocatorInvoiceValidationExporter; use App\Filament\Exports\ReworkLocatorInvoiceValidationExporter;
use App\Filament\Imports\ReworkLocatorInvoiceValidationImporter; use App\Filament\Imports\ReworkLocatorInvoiceValidationImporter;
use App\Filament\Resources\ReworkLocatorInvoiceValidationResource\Pages; use App\Filament\Resources\ReworkLocatorInvoiceValidationResource\Pages;
use App\Filament\Resources\ReworkLocatorInvoiceValidationResource\RelationManagers;
use App\Models\InvoiceValidation;
use App\Models\LocatorInvoiceValidation; use App\Models\LocatorInvoiceValidation;
use App\Models\PalletValidation; use App\Models\PalletValidation;
use App\Models\Plant; use App\Models\Plant;
use App\Models\ReworkLocatorInvoiceValidation; use App\Models\ReworkLocatorInvoiceValidation;
use Filament\Facades\Filament; use Filament\Facades\Filament;
use Filament\Forms; use Filament\Forms;
use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\Section;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\ToggleButtons;
use Filament\Forms\Form; use Filament\Forms\Form;
use Filament\Forms\Get;
use Filament\Notifications\Notification;
use Filament\Resources\Resource; use Filament\Resources\Resource;
use Filament\Tables; use Filament\Tables;
use Filament\Tables\Actions\ExportAction;
use Filament\Tables\Actions\ImportAction;
use Filament\Tables\Filters\Filter;
use Filament\Tables\Table; use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope; use Illuminate\Database\Eloquent\SoftDeletingScope;
use Filament\Forms\Components\Section;
use Filament\Forms\Components\ToggleButtons;
use Filament\Forms\Get;
use Filament\Notifications\Notification;
use Filament\Tables\Actions\ExportAction;
use Filament\Tables\Actions\ImportAction;
use Filament\Forms\Components\DateTimePicker;
use Filament\Tables\Filters\Filter;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Select;
class ReworkLocatorInvoiceValidationResource extends Resource class ReworkLocatorInvoiceValidationResource extends Resource
{ {
@@ -54,20 +52,18 @@ class ReworkLocatorInvoiceValidationResource extends Resource
->required() ->required()
->options(function (callable $get) { ->options(function (callable $get) {
$userHas = Filament::auth()->user()->plant_id; $userHas = Filament::auth()->user()->plant_id;
return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray();
}) })
->afterStateUpdated(function ($state, callable $set, callable $get) { ->afterStateUpdated(function ($state, callable $set, callable $get) {
$plantId = $get('plant_id'); $plantId = $get('plant_id');
if ($plantId) if ($plantId) {
{
$set('plant', $plantId); $set('plant', $plantId);
$set('invoice_number', null); $set('invoice_number', null);
$set('scan_pallet_no', null); $set('scan_pallet_no', null);
$set('scan_serial_no', null); $set('scan_serial_no', null);
$set('rework_type', null); $set('rework_type', null);
} } else {
else
{
$set('plant', null); $set('plant', null);
$set('invoice_number', null); $set('invoice_number', null);
$set('scan_pallet_no', null); $set('scan_pallet_no', null);
@@ -128,8 +124,7 @@ class ReworkLocatorInvoiceValidationResource extends Resource
$set('invoice_number', null); $set('invoice_number', null);
$set('scan_pallet_no', null); $set('scan_pallet_no', null);
$set('scan_serial_no', null); $set('scan_serial_no', null);
} } else {
else {
$set('reworkType', null); $set('reworkType', null);
$set('invoice_number', null); $set('invoice_number', null);
$set('scan_pallet_no', null); $set('scan_pallet_no', null);
@@ -163,16 +158,14 @@ class ReworkLocatorInvoiceValidationResource extends Resource
->count(); ->count();
$isScanningComplete = true; $isScanningComplete = true;
foreach ($rows as $row) foreach ($rows as $row) {
{
if ($row->scanned_status != 'Scanned') { if ($row->scanned_status != 'Scanned') {
$isScanningComplete = false; $isScanningComplete = false;
break; break;
} }
} }
if (!$isScanningComplete) if (! $isScanningComplete) {
{
Notification::make() Notification::make()
->title("Scanned invoice number: '$invoiceNumber' does not completed the scanning process!<br>Has '$notCompletedCount' pending serial number to scan!<br>Please, scan the valid completed invoice number to proceed...") ->title("Scanned invoice number: '$invoiceNumber' does not completed the scanning process!<br>Has '$notCompletedCount' pending serial number to scan!<br>Please, scan the valid completed invoice number to proceed...")
->danger() ->danger()
@@ -181,6 +174,7 @@ class ReworkLocatorInvoiceValidationResource extends Resource
$set('invoice_number', null); $set('invoice_number', null);
$set('update_invoice', null); $set('update_invoice', null);
return; return;
} }
}), }),
@@ -198,15 +192,13 @@ class ReworkLocatorInvoiceValidationResource extends Resource
$serialNo = trim($get('scan_serial_no')); $serialNo = trim($get('scan_serial_no'));
$updatePalletStatus = $get('update_pallet') ?? null; $updatePalletStatus = $get('update_pallet') ?? null;
if ($updatePalletStatus == 0) if ($updatePalletStatus == 0) {
{
return; return;
} }
if (strlen($palletNumber) < 10) if (strlen($palletNumber) < 10) {
{
Notification::make() Notification::make()
->title("Invalid: Pallet Number") ->title('Invalid: Pallet Number')
->body("Pallet number '$palletNumber' must be at least 10 digits.") ->body("Pallet number '$palletNumber' must be at least 10 digits.")
->danger() ->danger()
->duration(5000) ->duration(5000)
@@ -216,13 +208,13 @@ class ReworkLocatorInvoiceValidationResource extends Resource
$set('scan_serial_no', null); $set('scan_serial_no', null);
$set('scan_pallet_no', null); $set('scan_pallet_no', null);
$set('update_pallet', null); $set('update_pallet', null);
return; return;
} }
$PalletSerialNumbers = PalletValidation::where('plant_id', $plantId)->where('pallet_number', $palletNumber)->first(); $PalletSerialNumbers = PalletValidation::where('plant_id', $plantId)->where('pallet_number', $palletNumber)->first();
if (!$PalletSerialNumbers) if (! $PalletSerialNumbers) {
{
Notification::make() Notification::make()
->title('Pallet Not Found') ->title('Pallet Not Found')
->body("Pallet number '$palletNumber' doesn't exist in pallet table!<br><br>Scan the valid exist 'Pallet Number' to proceed..!") ->body("Pallet number '$palletNumber' doesn't exist in pallet table!<br><br>Scan the valid exist 'Pallet Number' to proceed..!")
@@ -234,6 +226,7 @@ class ReworkLocatorInvoiceValidationResource extends Resource
$set('scan_serial_no', null); $set('scan_serial_no', null);
$set('scan_pallet_no', null); $set('scan_pallet_no', null);
$set('update_pallet', null); $set('update_pallet', null);
return; return;
} }
@@ -242,8 +235,7 @@ class ReworkLocatorInvoiceValidationResource extends Resource
->get(); ->get();
$isScanningComplete = true; $isScanningComplete = true;
foreach ($rows as $row) foreach ($rows as $row) {
{
if ($row->pallet_status != 'Completed') { if ($row->pallet_status != 'Completed') {
$isScanningComplete = false; $isScanningComplete = false;
break; break;
@@ -254,8 +246,7 @@ class ReworkLocatorInvoiceValidationResource extends Resource
$isScanningComplete = false; $isScanningComplete = false;
} }
if (!$isScanningComplete) if (! $isScanningComplete) {
{
Notification::make() Notification::make()
->title('Pallet Not Completed') ->title('Pallet Not Completed')
->body("Scanned pallet number '$palletNumber' doesn't completed the master packing!<br><br>Please, scan the valid completed pallet number to proceed..!") ->body("Scanned pallet number '$palletNumber' doesn't completed the master packing!<br><br>Please, scan the valid completed pallet number to proceed..!")
@@ -267,13 +258,11 @@ class ReworkLocatorInvoiceValidationResource extends Resource
$set('scan_serial_no', null); $set('scan_serial_no', null);
$set('scan_pallet_no', null); $set('scan_pallet_no', null);
$set('update_pallet', null); $set('update_pallet', null);
return; return;
} } else {
else
{
$locatExist = ($PalletSerialNumbers->locator_number != null && $PalletSerialNumbers->locator_number != '') ? $PalletSerialNumbers->locator_number : ''; $locatExist = ($PalletSerialNumbers->locator_number != null && $PalletSerialNumbers->locator_number != '') ? $PalletSerialNumbers->locator_number : '';
if ($locatExist) if ($locatExist) {
{
Notification::make() Notification::make()
->title('Locator Pallet Found') ->title('Locator Pallet Found')
->body("Scanned pallet number '$palletNumber' exist in locator number '$locatExist'.<br><br>Remove scanned 'Pallet' from 'Locator' to proceed re-master packing..!") ->body("Scanned pallet number '$palletNumber' exist in locator number '$locatExist'.<br><br>Remove scanned 'Pallet' from 'Locator' to proceed re-master packing..!")
@@ -285,14 +274,12 @@ class ReworkLocatorInvoiceValidationResource extends Resource
$set('scan_serial_no', null); $set('scan_serial_no', null);
$set('scan_pallet_no', null); $set('scan_pallet_no', null);
$set('update_pallet', null); $set('update_pallet', null);
return; return;
} } else {
else if (strlen($serialNo) > 0 && (strlen($serialNo) < 9 || strlen($serialNo) > 20)) {
{
if (strlen($serialNo) > 0 && (strlen($serialNo) < 9 || strlen($serialNo) > 20))
{
Notification::make() Notification::make()
->title("Invalid: Serial Number") ->title('Invalid: Serial Number')
->body("Serial number '$serialNo' should contain minimum 9 digits and maximum 20 digits.") ->body("Serial number '$serialNo' should contain minimum 9 digits and maximum 20 digits.")
->danger() ->danger()
->duration(5000) ->duration(5000)
@@ -301,12 +288,11 @@ class ReworkLocatorInvoiceValidationResource extends Resource
$livewire->dispatch('loadData', '', $palletNumber, $plantId, 'pallet'); $livewire->dispatch('loadData', '', $palletNumber, $plantId, 'pallet');
$set('scan_serial_no', null); $set('scan_serial_no', null);
$set('update_pallet', null); $set('update_pallet', null);
return; return;
} } elseif (strlen($serialNo) > 0 && ! ctype_alnum($serialNo)) {
else if (strlen($serialNo) > 0 && !ctype_alnum($serialNo))
{
Notification::make() Notification::make()
->title("Invalid: Serial Number") ->title('Invalid: Serial Number')
->body("Serial number '$serialNo' must contain alpha-numeric values only.") ->body("Serial number '$serialNo' must contain alpha-numeric values only.")
->danger() ->danger()
->duration(5000) ->duration(5000)
@@ -315,13 +301,12 @@ class ReworkLocatorInvoiceValidationResource extends Resource
$livewire->dispatch('loadData', '', $palletNumber, $plantId, 'pallet'); $livewire->dispatch('loadData', '', $palletNumber, $plantId, 'pallet');
$set('scan_serial_no', null); $set('scan_serial_no', null);
$set('update_pallet', null); $set('update_pallet', null);
return; return;
} }
if ($updatePalletStatus == 1) if ($updatePalletStatus == 1) {
{ foreach ($rows as $row) {
foreach ($rows as $row)
{
$row->forceDelete(); // Delete the row from the original table $row->forceDelete(); // Delete the row from the original table
} }
@@ -336,6 +321,7 @@ class ReworkLocatorInvoiceValidationResource extends Resource
$set('scan_serial_no', null); $set('scan_serial_no', null);
$set('scan_pallet_no', null); $set('scan_pallet_no', null);
$set('update_pallet', null); $set('update_pallet', null);
return; return;
} }
} }
@@ -349,7 +335,7 @@ class ReworkLocatorInvoiceValidationResource extends Resource
->hidden() ->hidden()
->readOnly(), ->readOnly(),
]) ])
->columns(5) ->columns(5),
]); ]);
} }
@@ -364,6 +350,7 @@ class ReworkLocatorInvoiceValidationResource extends Resource
$paginator = $livewire->getTableRecords(); $paginator = $livewire->getTableRecords();
$perPage = method_exists($paginator, 'perPage') ? $paginator->perPage() : 10; $perPage = method_exists($paginator, 'perPage') ? $paginator->perPage() : 10;
$currentPage = method_exists($paginator, 'currentPage') ? $paginator->currentPage() : 1; $currentPage = method_exists($paginator, 'currentPage') ? $paginator->currentPage() : 1;
return ($currentPage - 1) * $perPage + $rowLoop->iteration; return ($currentPage - 1) * $perPage + $rowLoop->iteration;
}), }),
Tables\Columns\TextColumn::make('plant.name') Tables\Columns\TextColumn::make('plant.name')
@@ -455,9 +442,6 @@ class ReworkLocatorInvoiceValidationResource extends Resource
return Filament::auth()->user()->can('view export rework invoice validation'); return Filament::auth()->user()->can('view export rework invoice validation');
}), }),
]) ])
// ->filters([
// Tables\Filters\TrashedFilter::make(),
// ])
->filters([ ->filters([
Tables\Filters\TrashedFilter::make(), Tables\Filters\TrashedFilter::make(),
Filter::make('advanced_filters') Filter::make('advanced_filters')
@@ -471,6 +455,7 @@ class ReworkLocatorInvoiceValidationResource extends Resource
// }) // })
->options(function (callable $get) { ->options(function (callable $get) {
$userHas = Filament::auth()->user()->plant_id; $userHas = Filament::auth()->user()->plant_id;
return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray();
}) })
->reactive() ->reactive()
@@ -494,6 +479,7 @@ class ReworkLocatorInvoiceValidationResource extends Resource
if (! $plantId) { if (! $plantId) {
return []; return [];
} }
return ReworkLocatorInvoiceValidation::where('plant_id', $plantId) return ReworkLocatorInvoiceValidation::where('plant_id', $plantId)
->whereNotNull('invoice_number') ->whereNotNull('invoice_number')
->where('invoice_number', '!=', '') ->where('invoice_number', '!=', '')
@@ -515,6 +501,7 @@ class ReworkLocatorInvoiceValidationResource extends Resource
if (! $plantId) { if (! $plantId) {
return []; return [];
} }
return ReworkLocatorInvoiceValidation::where('plant_id', $plantId) return ReworkLocatorInvoiceValidation::where('plant_id', $plantId)
->whereNotNull('pallet_number') ->whereNotNull('pallet_number')
->where('pallet_number', '!=', '') ->where('pallet_number', '!=', '')
@@ -533,6 +520,7 @@ class ReworkLocatorInvoiceValidationResource extends Resource
if (! $plantId) { if (! $plantId) {
return []; return [];
} }
return ReworkLocatorInvoiceValidation::where('plant_id', $plantId) return ReworkLocatorInvoiceValidation::where('plant_id', $plantId)
->whereNotNull('locator_number') ->whereNotNull('locator_number')
->where('locator_number', '!=', '') ->where('locator_number', '!=', '')
@@ -571,6 +559,12 @@ class ReworkLocatorInvoiceValidationResource extends Resource
if (! empty($data['Plant'])) { // $plant = $data['Plant'] ?? null if (! empty($data['Plant'])) { // $plant = $data['Plant'] ?? null
$query->where('plant_id', $data['Plant']); $query->where('plant_id', $data['Plant']);
} else {
$userHas = Filament::auth()->user()->plant_id;
if ($userHas && strlen($userHas) > 0) {
return $query->whereRaw('1 = 0');
}
} }
if (! empty($data['invoice_number'])) { if (! empty($data['invoice_number'])) {
@@ -610,6 +604,12 @@ class ReworkLocatorInvoiceValidationResource extends Resource
if (! empty($data['Plant'])) { if (! empty($data['Plant'])) {
$indicators[] = 'Plant: '.Plant::where('id', $data['Plant'])->value('name'); $indicators[] = 'Plant: '.Plant::where('id', $data['Plant'])->value('name');
} else {
$userHas = Filament::auth()->user()->plant_id;
if ($userHas && strlen($userHas) > 0) {
return 'Plant: Choose plant to filter records.';
}
} }
if (! empty($data['invoice_number'])) { if (! empty($data['invoice_number'])) {
@@ -643,8 +643,9 @@ class ReworkLocatorInvoiceValidationResource extends Resource
if (! empty($data['rework_by'])) { if (! empty($data['rework_by'])) {
$indicators[] = 'Reworked By: '.$data['rework_by']; $indicators[] = 'Reworked By: '.$data['rework_by'];
} }
return $indicators; return $indicators;
}) }),
]) ])
->filtersFormMaxHeight('280px') ->filtersFormMaxHeight('280px')
->actions([ ->actions([

View File

@@ -4,40 +4,41 @@ namespace App\Filament\Resources;
use App\Filament\Exports\SerialValidationExporter; use App\Filament\Exports\SerialValidationExporter;
use App\Filament\Resources\SerialValidationResource\Pages; use App\Filament\Resources\SerialValidationResource\Pages;
use App\Filament\Resources\SerialValidationResource\RelationManagers;
use App\Models\Item; use App\Models\Item;
use App\Models\Plant; use App\Models\Plant;
use App\Models\SerialValidation; use App\Models\SerialValidation;
use App\Models\StickerMaster; use App\Models\StickerMaster;
use Filament\Tables\Actions\ExportAction; use Filament\Facades\Filament;
use Filament\Forms; use Filament\Forms;
use Filament\Forms\Form; use Filament\Forms\Components\DateTimePicker;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use Filament\Forms\Get;
use Filament\Forms\Components\FileUpload; use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\Radio; use Filament\Forms\Components\Radio;
use Filament\Forms\Components\Section; use Filament\Forms\Components\Section;
use Filament\Forms\Components\Select; use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput; use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\ToggleButtons; use Filament\Forms\Components\ToggleButtons;
use Filament\Facades\Filament; use Filament\Forms\Form;
use Filament\Forms\Get;
use Filament\Notifications\Notification; use Filament\Notifications\Notification;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Actions\ExportAction;
use Filament\Tables\Filters\Filter;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use Illuminate\Support\Facades\Storage; use Illuminate\Support\Facades\Storage;
use Maatwebsite\Excel\Facades\Excel; use Maatwebsite\Excel\Facades\Excel;
use Str; use Str;
use Filament\Tables\Filters\Filter;
use Filament\Forms\Components\DateTimePicker;
class SerialValidationResource extends Resource class SerialValidationResource extends Resource
{ {
protected static ?string $model = SerialValidation::class; protected static ?string $model = SerialValidation::class;
protected static ?string $navigationIcon = 'heroicon-o-rectangle-stack'; protected static ?string $navigationIcon = 'heroicon-o-rectangle-stack';
protected static ?string $navigationGroup = 'Serial Validation'; protected static ?string $navigationGroup = 'Serial Validation';
public $invoiceNumber; public $invoiceNumber;
public static function form(Form $form): Form public static function form(Form $form): Form
@@ -53,6 +54,7 @@ class SerialValidationResource extends Resource
->columnSpan(1) ->columnSpan(1)
->options(function (callable $get) { ->options(function (callable $get) {
$userHas = Filament::auth()->user()->plant_id; $userHas = Filament::auth()->user()->plant_id;
return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray();
}) })
->default(function () { ->default(function () {
@@ -70,10 +72,9 @@ class SerialValidationResource extends Resource
$set('total_quantity', null); $set('total_quantity', null);
$set('scanned_quantity', null); $set('scanned_quantity', null);
$set('ivPlantError', 'Please select a plant first.'); $set('ivPlantError', 'Please select a plant first.');
return; return;
} } else {
else
{
$set('ivPlantError', null); $set('ivPlantError', null);
} }
}) })
@@ -115,12 +116,58 @@ class SerialValidationResource extends Resource
'id' => 'serial_number_input', 'id' => 'serial_number_input',
'x-data' => '{ value: "" }', 'x-data' => '{ value: "" }',
'x-model' => 'value', 'x-model' => 'value',
'wire:keydown.enter.prevent' => 'processSerialNumber(value)', // Using wire:keydown // 'x-data' => '{}',
// 'x-on:keydown.enter.prevent' => "
// let v = (\$event.target.value || '').replace(/[\\r\\n\\s]+$/g, '').trim().toLowerCase();
// if (!v.endsWith('/c')) {
// \$wire.processSerialNumber(v);
// }
// ",
// 'wire:keydown.enter.prevent' => 'processSerialNumber(value)', // Using wire:keydown
'x-on:keydown.enter.prevent' => "
let serial = \$event.target.value;
if (serial.trim() != '') {
\$wire.dispatch('process-scan', serial);
}
",
])
->afterStateUpdated(function ($state, callable $set, callable $get, $livewire) {
$set('update_invoice', 0);
// if (str_ends_with(strtolower($state), '/c')) {
// $livewire->dispatch('focus-capacitor');
// }
})
->columnSpan(1),
Forms\Components\TextInput::make('capacitor')
->label('Capacitor')
->reactive()
// ->hidden(fn (callable $get) => !str_ends_with(strtolower($get('serial_number')), '/c'))
->visible(fn (callable $get) => str_ends_with(strtolower($get('serial_number')), '/c')
)
->extraAttributes([
'id' => 'focus-capacitor-input',
'x-data' => "{
getItemCode() {
return this.\$el.dataset.itemCode || '';
}
}",
'x-init' => '
// Nothing needed here now, listener runs globally
',
// Trigger processing with Enter key
'x-on:keydown.enter.prevent' => "
\$wire.processCapacitor(
\$el.querySelector('input').value,
getItemCode()
)
",
// 'x-on:keydown.enter.prevent' => 'processCapacitor(value)',
]) ])
->afterStateUpdated(function ($state, callable $set, callable $get) { ->afterStateUpdated(function ($state, callable $set, callable $get) {
$set('update_invoice', 0); $get('serial_number');
// $this->dispatch('focus-serial-number');
// if (!$invNo) { return; } else { }
}) })
->columnSpan(1), ->columnSpan(1),
Forms\Components\TextInput::make('total_quantity') Forms\Components\TextInput::make('total_quantity')
@@ -138,18 +185,17 @@ class SerialValidationResource extends Resource
->reactive() ->reactive()
->hidden(fn (callable $get) => ($get('invoice_number') == null || $get('update_invoice') == '0') || ! empty($get('serial_number'))) ->hidden(fn (callable $get) => ($get('invoice_number') == null || $get('update_invoice') == '0') || ! empty($get('serial_number')))
->afterStateUpdated(function ($state, callable $set, callable $get) { ->afterStateUpdated(function ($state, callable $set, callable $get) {
if (!$get('plant_id')) if (! $get('plant_id')) {
{
$set('update_invoice', null); $set('update_invoice', null);
return; return;
} }
if ($get('update_invoice') == "1") if ($get('update_invoice') == '1') {
{
$totQuan = SerialValidation::where('invoice_number', $get('invoice_number'))->where('plant_id', $get('plant_id'))->count(); $totQuan = SerialValidation::where('invoice_number', $get('invoice_number'))->where('plant_id', $get('plant_id'))->count();
if ($totQuan <= 0) if ($totQuan <= 0) {
{
$set('update_invoice', null); $set('update_invoice', null);
return; return;
} }
@@ -157,19 +203,16 @@ class SerialValidationResource extends Resource
$scanMQuan = SerialValidation::where('invoice_number', $get('invoice_number'))->whereNotNull('serial_number')->where('serial_number', '!=', '')->where('plant_id', $get('plant_id'))->count(); $scanMQuan = SerialValidation::where('invoice_number', $get('invoice_number'))->whereNotNull('serial_number')->where('serial_number', '!=', '')->where('plant_id', $get('plant_id'))->count();
$scanSQuan = SerialValidation::where('invoice_number', $get('invoice_number'))->where('scanned_status', 'Scanned')->where('plant_id', $get('plant_id'))->count(); $scanSQuan = SerialValidation::where('invoice_number', $get('invoice_number'))->where('scanned_status', 'Scanned')->where('plant_id', $get('plant_id'))->count();
if ($totMQuan > 0) if ($totMQuan > 0) {
{ if ($totQuan == $scanMQuan) {
if ($totQuan == $scanMQuan)
{
$set('update_invoice', null); $set('update_invoice', null);
return; return;
} }
} } else {
else if ($totQuan == $scanSQuan) {
{
if ($totQuan == $scanSQuan)
{
$set('update_invoice', null); $set('update_invoice', null);
return; return;
} }
} }
@@ -194,6 +237,7 @@ class SerialValidationResource extends Resource
$paginator = $livewire->getTableRecords(); $paginator = $livewire->getTableRecords();
$perPage = method_exists($paginator, 'perPage') ? $paginator->perPage() : 10; $perPage = method_exists($paginator, 'perPage') ? $paginator->perPage() : 10;
$currentPage = method_exists($paginator, 'currentPage') ? $paginator->currentPage() : 1; $currentPage = method_exists($paginator, 'currentPage') ? $paginator->currentPage() : 1;
return ($currentPage - 1) * $perPage + $rowLoop->iteration; return ($currentPage - 1) * $perPage + $rowLoop->iteration;
}), }),
Tables\Columns\TextColumn::make('invoice_number') Tables\Columns\TextColumn::make('invoice_number')
@@ -287,6 +331,7 @@ class SerialValidationResource extends Resource
// ->options(Plant::pluck('name', 'id')->toArray()) // Fetch plant names and IDs // ->options(Plant::pluck('name', 'id')->toArray()) // Fetch plant names and IDs
->options(function (callable $get) { ->options(function (callable $get) {
$userHas = Filament::auth()->user()->plant_id; $userHas = Filament::auth()->user()->plant_id;
return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray();
}) })
->label('Select Plant') ->label('Select Plant')
@@ -330,42 +375,37 @@ class SerialValidationResource extends Resource
// /home/iot-dev/projects/pds/storage/app/private/uploads/temp/3RA0018735.xlsx // /home/iot-dev/projects/pds/storage/app/private/uploads/temp/3RA0018735.xlsx
$totQuan = SerialValidation::where('invoice_number', $originalNameOnly)->count(); $totQuan = SerialValidation::where('invoice_number', $originalNameOnly)->count();
if ($totQuan > 0) if ($totQuan > 0) {
{
$scanSQuan = SerialValidation::where('invoice_number', $originalNameOnly)->where('scanned_status', 'Scanned')->count(); $scanSQuan = SerialValidation::where('invoice_number', $originalNameOnly)->where('scanned_status', 'Scanned')->count();
if ($totQuan == $scanSQuan) if ($totQuan == $scanSQuan) {
{
$invoiceFirst = SerialValidation::with('plant')->where('invoice_number', $originalNameOnly)->first(); $invoiceFirst = SerialValidation::with('plant')->where('invoice_number', $originalNameOnly)->first();
$plantName = $invoiceFirst ? (String)$invoiceFirst->plant->name : null; $plantName = $invoiceFirst ? (string) $invoiceFirst->plant->name : null;
Notification::make() Notification::make()
->title("Serial invoice number : '$originalNameOnly' already completed the scanning process for plant : '$plantName'.") ->title("Serial invoice number : '$originalNameOnly' already completed the scanning process for plant : '$plantName'.")
->danger() ->danger()
->send(); ->send();
if ($disk->exists($path)) if ($disk->exists($path)) {
{
$disk->delete($path); $disk->delete($path);
} }
return; return;
} } else {
else
{
$invoiceFirst = SerialValidation::with('plant')->where('invoice_number', $originalNameOnly)->first(); $invoiceFirst = SerialValidation::with('plant')->where('invoice_number', $originalNameOnly)->first();
// $plantCode = $invoiceFirst ? (String)$invoiceFirst->plant->code : null; // $plantCode = $invoiceFirst ? (String)$invoiceFirst->plant->code : null;
$plantName = $invoiceFirst ? (String)$invoiceFirst->plant->name : null; $plantName = $invoiceFirst ? (string) $invoiceFirst->plant->name : null;
$invoicePlantId = $invoiceFirst->plant_id; $invoicePlantId = $invoiceFirst->plant_id;
if ($plantId != $invoicePlantId) if ($plantId != $invoicePlantId) {
{
Notification::make() Notification::make()
->title("Serial invoice number : '$originalNameOnly' already exists for plant : '$plantName'.<br>Choose the valid 'Plant' to proceed!") ->title("Serial invoice number : '$originalNameOnly' already exists for plant : '$plantName'.<br>Choose the valid 'Plant' to proceed!")
->danger() ->danger()
->send(); ->send();
if ($disk->exists($path)) if ($disk->exists($path)) {
{
$disk->delete($path); $disk->delete($path);
} }
return; return;
} }
} }
@@ -374,26 +414,23 @@ class SerialValidationResource extends Resource
$totQuan = SerialValidation::where('invoice_number', $originalNameOnly)->where('plant_id', $plantId)->count(); $totQuan = SerialValidation::where('invoice_number', $originalNameOnly)->where('plant_id', $plantId)->count();
$scanSQuan = SerialValidation::where('invoice_number', $originalNameOnly)->where('scanned_status', 'Scanned')->where('plant_id', $plantId)->count(); $scanSQuan = SerialValidation::where('invoice_number', $originalNameOnly)->where('scanned_status', 'Scanned')->where('plant_id', $plantId)->count();
if ($totQuan > 0 && $totQuan == $scanSQuan) if ($totQuan > 0 && $totQuan == $scanSQuan) {
{
Notification::make() Notification::make()
->title('Serial invoice already completed the scanning process for selected plant.') ->title('Serial invoice already completed the scanning process for selected plant.')
->danger() ->danger()
->send(); ->send();
if ($disk->exists($path)) if ($disk->exists($path)) {
{
$disk->delete($path); $disk->delete($path);
} }
return; return;
} }
if ($fullPath && file_exists($fullPath)) if ($fullPath && file_exists($fullPath)) {
{
$rows = Excel::toArray(null, $fullPath)[0]; $rows = Excel::toArray(null, $fullPath)[0];
if ((count($rows) - 1) <= 0) if ((count($rows) - 1) <= 0) {
{
Notification::make() Notification::make()
->title('Records Not Found') ->title('Records Not Found')
->body("Import the valid 'Serial Invoice' file to proceed..!") ->body("Import the valid 'Serial Invoice' file to proceed..!")
@@ -403,6 +440,7 @@ class SerialValidationResource extends Resource
if ($disk->exists($path)) { if ($disk->exists($path)) {
$disk->delete($path); $disk->delete($path);
} }
return; return;
} }
@@ -414,9 +452,10 @@ class SerialValidationResource extends Resource
$seenSerialNumbers = []; $seenSerialNumbers = [];
$validRowsFound = false; $validRowsFound = false;
foreach ($rows as $index => $row) foreach ($rows as $index => $row) {
{ if ($index == 0) {
if ($index == 0) continue; // Skip header continue;
} // Skip header
$materialCode = trim($row[0]); $materialCode = trim($row[0]);
$serialNumber = trim($row[1]); $serialNumber = trim($row[1]);
@@ -425,24 +464,16 @@ class SerialValidationResource extends Resource
continue; continue;
} }
if (!empty($materialCode)) if (! empty($materialCode)) {
{ if (Str::length($materialCode) < 6 || ! ctype_alnum($materialCode)) {
if (Str::length($materialCode) < 6 || !ctype_alnum($materialCode))
{
$invalidMatCodes[] = $materialCode; $invalidMatCodes[] = $materialCode;
} } else {
else
{
if (empty($serialNumber)) { if (empty($serialNumber)) {
$missingSerials[] = $materialCode; $missingSerials[] = $materialCode;
} } elseif (Str::length($serialNumber) < 9 || ! ctype_alnum($serialNumber)) {
else if (Str::length($serialNumber) < 9 || !ctype_alnum($serialNumber))
{
$invalidSerialCodes[] = $serialNumber; $invalidSerialCodes[] = $serialNumber;
} } else {
else
{
if (in_array($serialNumber, $seenSerialNumbers)) { if (in_array($serialNumber, $seenSerialNumbers)) {
$duplicateSerials[] = $serialNumber; $duplicateSerials[] = $serialNumber;
} else { } else {
@@ -452,9 +483,7 @@ class SerialValidationResource extends Resource
} }
} }
} }
} } else {
else
{
continue; continue;
} }
} }
@@ -476,9 +505,9 @@ class SerialValidationResource extends Resource
if ($disk->exists($path)) { if ($disk->exists($path)) {
$disk->delete($path); $disk->delete($path);
} }
return; return;
} } elseif (! empty($uniqueMissingSerials)) {
else if (!empty($uniqueMissingSerials)) {
Notification::make() Notification::make()
->title('Missing Serial Numbers') ->title('Missing Serial Numbers')
->body("The following item codes doesn't have valid serial number:<br>".implode(', ', $uniqueMissingSerials)) ->body("The following item codes doesn't have valid serial number:<br>".implode(', ', $uniqueMissingSerials))
@@ -487,9 +516,9 @@ class SerialValidationResource extends Resource
if ($disk->exists($path)) { if ($disk->exists($path)) {
$disk->delete($path); $disk->delete($path);
} }
return; return;
} } elseif (! empty($uniqueSerialCodes)) {
else if (!empty($uniqueSerialCodes)) {
Notification::make() Notification::make()
->title('Invalid Serial Number') ->title('Invalid Serial Number')
->body('The following serial numbers should contain minimum 9 digit alpha numeric values:<br>'.implode(', ', $uniqueSerialCodes)) ->body('The following serial numbers should contain minimum 9 digit alpha numeric values:<br>'.implode(', ', $uniqueSerialCodes))
@@ -498,9 +527,9 @@ class SerialValidationResource extends Resource
if ($disk->exists($path)) { if ($disk->exists($path)) {
$disk->delete($path); $disk->delete($path);
} }
return; return;
} } elseif (! empty($duplicateSerialCodes)) {
else if (!empty($duplicateSerialCodes)) {
Notification::make() Notification::make()
->title('Duplicate Serial Numbers') ->title('Duplicate Serial Numbers')
->body('The following serial numbers are already exist in imported excel:<br>'.implode(', ', $duplicateSerialCodes)) ->body('The following serial numbers are already exist in imported excel:<br>'.implode(', ', $duplicateSerialCodes))
@@ -509,6 +538,7 @@ class SerialValidationResource extends Resource
if ($disk->exists($path)) { if ($disk->exists($path)) {
$disk->delete($path); $disk->delete($path);
} }
return; return;
} }
@@ -521,6 +551,7 @@ class SerialValidationResource extends Resource
if ($disk->exists($path)) { if ($disk->exists($path)) {
$disk->delete($path); $disk->delete($path);
} }
return; return;
} }
@@ -536,8 +567,7 @@ class SerialValidationResource extends Resource
$missingCodes = array_diff($uniqueCodes, $matchedCodes); $missingCodes = array_diff($uniqueCodes, $matchedCodes);
if (!empty($missingCodes)) if (! empty($missingCodes)) {
{
$missingCount = count($missingCodes); $missingCount = count($missingCodes);
$message = $missingCount > 10 ? "'$missingCount' item codes are not found in database." : 'The following item codes are not found in database:<br>'.implode(', ', $missingCodes); $message = $missingCount > 10 ? "'$missingCount' item codes are not found in database." : 'The following item codes are not found in database:<br>'.implode(', ', $missingCodes);
@@ -551,6 +581,7 @@ class SerialValidationResource extends Resource
if ($disk->exists($path)) { if ($disk->exists($path)) {
$disk->delete($path); $disk->delete($path);
} }
return; return;
} }
@@ -560,8 +591,7 @@ class SerialValidationResource extends Resource
->pluck('item.code') ->pluck('item.code')
->toArray(); ->toArray();
if (count($invalidCodes) > 10) if (count($invalidCodes) > 10) {
{
Notification::make() Notification::make()
->title('Invalid item codes found') ->title('Invalid item codes found')
->body(''.count($invalidCodes).'item codes found have material type.') ->body(''.count($invalidCodes).'item codes found have material type.')
@@ -571,10 +601,9 @@ class SerialValidationResource extends Resource
if ($disk->exists($path)) { if ($disk->exists($path)) {
$disk->delete($path); $disk->delete($path);
} }
return; return;
} } elseif (count($invalidCodes) > 0) {
else if (count($invalidCodes) > 0)
{
Notification::make() Notification::make()
->title('Invalid item codes found') ->title('Invalid item codes found')
->body('Material invoice Item Codes found : '.implode(', ', $invalidCodes)) ->body('Material invoice Item Codes found : '.implode(', ', $invalidCodes))
@@ -584,10 +613,9 @@ class SerialValidationResource extends Resource
if ($disk->exists($path)) { if ($disk->exists($path)) {
$disk->delete($path); $disk->delete($path);
} }
return; return;
} } else {
else
{
// Save full file path to session // Save full file path to session
session(['uploaded_invoice_path' => $fullPath]); session(['uploaded_invoice_path' => $fullPath]);
Notification::make() Notification::make()
@@ -921,7 +949,6 @@ class SerialValidationResource extends Resource
// $excelCode = trim($row[0]); // $excelCode = trim($row[0]);
// $excelMatQty = trim($row[1]); // $excelMatQty = trim($row[1]);
// if ($excelCode == $code && is_numeric($excelMatQty)) { // if ($excelCode == $code && is_numeric($excelMatQty)) {
// $totalExcelQty += $excelMatQty; // Sum up the quantities // $totalExcelQty += $excelMatQty; // Sum up the quantities
// } // }
@@ -988,9 +1015,6 @@ class SerialValidationResource extends Resource
return Filament::auth()->user()->can('view export serial validation invoice'); return Filament::auth()->user()->can('view export serial validation invoice');
}), }),
]) ])
// ->filters([
// Tables\Filters\TrashedFilter::make(),
// ])
->filters([ ->filters([
Tables\Filters\TrashedFilter::make(), Tables\Filters\TrashedFilter::make(),
Filter::make('advanced_filters') Filter::make('advanced_filters')
@@ -1000,7 +1024,7 @@ class SerialValidationResource extends Resource
->label('Type ?') ->label('Type ?')
->boolean() ->boolean()
->options([ ->options([
'Serial' => 'Serial' 'Serial' => 'Serial',
]) ])
->default('Serial') ->default('Serial')
->inlineLabel(false) ->inlineLabel(false)
@@ -1013,6 +1037,7 @@ class SerialValidationResource extends Resource
// }) // })
->options(function (callable $get) { ->options(function (callable $get) {
$userHas = Filament::auth()->user()->plant_id; $userHas = Filament::auth()->user()->plant_id;
return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray();
}) })
->reactive() ->reactive()
@@ -1032,6 +1057,7 @@ class SerialValidationResource extends Resource
->nullable() ->nullable()
->options(function (callable $get) { ->options(function (callable $get) {
$pId = $get('Plant'); $pId = $get('Plant');
// if (empty($pId)) { // if (empty($pId)) {
// return []; // return [];
// } // }
@@ -1058,12 +1084,9 @@ class SerialValidationResource extends Resource
->nullable() ->nullable()
->options(function (callable $get) { ->options(function (callable $get) {
$plantId = $get('Plant'); $plantId = $get('Plant');
if (!$plantId) if (! $plantId) {
{
return SerialValidation::whereNotNull('operator_id')->select('operator_id')->distinct()->pluck('operator_id', 'operator_id'); return SerialValidation::whereNotNull('operator_id')->select('operator_id')->distinct()->pluck('operator_id', 'operator_id');
} } else {
else
{
return SerialValidation::where('plant_id', $plantId)->whereNotNull('operator_id')->select('operator_id')->distinct()->pluck('operator_id', 'operator_id'); return SerialValidation::where('plant_id', $plantId)->whereNotNull('operator_id')->select('operator_id')->distinct()->pluck('operator_id', 'operator_id');
} }
}) })
@@ -1083,13 +1106,13 @@ class SerialValidationResource extends Resource
->query(function ($query, array $data) { ->query(function ($query, array $data) {
// Hide all records initially if no filters are applied // Hide all records initially if no filters are applied
if (empty($data['invoice_type']) || (empty($data['Plant']) && empty($data['invoice_number']) && empty($data['serial_number']) && empty($data['created_from']) && empty($data['created_to']) && empty($data['operator_id']) && empty($data['scanned_status']) && empty($data['sticker_master_id']))) { if (empty($data['invoice_type']) || (empty($data['Plant']) && empty($data['invoice_number']) && empty($data['serial_number']) && empty($data['created_from']) && empty($data['created_to']) && empty($data['operator_id']) && empty($data['scanned_status']) && empty($data['sticker_master_id']))) {
if (empty($data['invoice_type'])) if (empty($data['invoice_type'])) {
{
Notification::make() Notification::make()
->title('Please, choose invoice type to filter.') ->title('Please, choose invoice type to filter.')
->danger() ->danger()
->send(); ->send();
} }
return $query->whereRaw('1 = 0'); return $query->whereRaw('1 = 0');
} }
@@ -1101,7 +1124,7 @@ class SerialValidationResource extends Resource
$query->whereNotNull('scanned_status')->where('scanned_status', '!=', ''); $query->whereNotNull('scanned_status')->where('scanned_status', '!=', '');
} elseif ($data['scanned_status'] == 'Pending') { } elseif ($data['scanned_status'] == 'Pending') {
// $query->whereNull('scanned_status')->orWhere('scanned_status', ''); // $query->whereNull('scanned_status')->orWhere('scanned_status', '');
$query->where(function ($query) use ($data) { $query->where(function ($query) {
// if (empty($data['scanned_status']) || $data['scanned_status'] == 'Pending') { // if (empty($data['scanned_status']) || $data['scanned_status'] == 'Pending') {
$query->whereNull('scanned_status')->orWhere('scanned_status', '!=', 'Scanned'); $query->whereNull('scanned_status')->orWhere('scanned_status', '!=', 'Scanned');
// } // }
@@ -1115,7 +1138,7 @@ class SerialValidationResource extends Resource
if ($data['scanned_status'] == 'Scanned') { if ($data['scanned_status'] == 'Scanned') {
$query->whereNotNull('serial_number')->where('serial_number', '!=', ''); $query->whereNotNull('serial_number')->where('serial_number', '!=', '');
} elseif ($data['scanned_status'] == 'Pending') { } elseif ($data['scanned_status'] == 'Pending') {
$query->where(function ($query) use ($data) { $query->where(function ($query) {
$query->whereNull('serial_number')->orWhere('serial_number', '=', ''); $query->whereNull('serial_number')->orWhere('serial_number', '=', '');
}); });
} }
@@ -1124,6 +1147,12 @@ class SerialValidationResource extends Resource
if (! empty($data['Plant'])) { // $plant = $data['Plant'] ?? null if (! empty($data['Plant'])) { // $plant = $data['Plant'] ?? null
$query->where('plant_id', $data['Plant']); $query->where('plant_id', $data['Plant']);
} else {
$userHas = Filament::auth()->user()->plant_id;
if ($userHas && strlen($userHas) > 0) {
return $query->whereRaw('1 = 0');
}
} }
if (! empty($data['invoice_number'])) { if (! empty($data['invoice_number'])) {
@@ -1161,6 +1190,12 @@ class SerialValidationResource extends Resource
if (! empty($data['Plant'])) { if (! empty($data['Plant'])) {
$indicators[] = 'Plant: '.Plant::where('id', $data['Plant'])->value('name'); $indicators[] = 'Plant: '.Plant::where('id', $data['Plant'])->value('name');
} else {
$userHas = Filament::auth()->user()->plant_id;
if ($userHas && strlen($userHas) > 0) {
return 'Plant: Choose plant to filter records.';
}
} }
if (! empty($data['invoice_number'])) { if (! empty($data['invoice_number'])) {
@@ -1193,7 +1228,7 @@ class SerialValidationResource extends Resource
} }
return $indicators; return $indicators;
}) }),
]) ])
->filtersFormMaxHeight('280px') ->filtersFormMaxHeight('280px')
->actions([ ->actions([

View File

@@ -2,8 +2,7 @@
namespace App\Filament\Resources; namespace App\Filament\Resources;
use AlperenErsoy\FilamentExport\Actions\FilamentExportBulkAction; use App\Exports\MotorFreeRunExport;
use App\Exports\TestingPanelReadingExport;
use App\Filament\Exports\TestingPanelReadingExporter; use App\Filament\Exports\TestingPanelReadingExporter;
use App\Filament\Imports\TestingPanelReadingImporter; use App\Filament\Imports\TestingPanelReadingImporter;
use App\Filament\Resources\TestingPanelReadingResource\Pages; use App\Filament\Resources\TestingPanelReadingResource\Pages;
@@ -23,19 +22,24 @@ use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput; use Filament\Forms\Components\TextInput;
use Filament\Forms\Form; use Filament\Forms\Form;
use Filament\Forms\Get; use Filament\Forms\Get;
use Filament\Notifications\Collection as NotificationsCollection; use Filament\Notifications\Notification;
use Filament\Resources\Resource; use Filament\Resources\Resource;
use Filament\Tables; use Filament\Tables;
use Filament\Tables\Actions\Action;
use Filament\Tables\Actions\BulkAction; use Filament\Tables\Actions\BulkAction;
use Filament\Tables\Actions\ExportAction;
use Filament\Tables\Actions\ImportAction;
use Filament\Tables\Filters\Filter;
use Filament\Tables\Table; use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope; use Illuminate\Database\Eloquent\SoftDeletingScope;
use Filament\Tables\Actions\ImportAction;
use Filament\Tables\Actions\ExportAction;
use Filament\Tables\Filters\Filter;
use Maatwebsite\Excel\Facades\Excel;
use Filament\Tables\Actions\Action;
use Illuminate\Support\Collection; use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Response;
// use Barryvdh\Snappy\Facades\SnappyPdf as PDF;
use Maatwebsite\Excel\Facades\Excel;
// use App\Exports\TestingPanelReadingExport;
use PhpOffice\PhpSpreadsheet\IOFactory; // For loading Excel file
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
class TestingPanelReadingResource extends Resource class TestingPanelReadingResource extends Resource
{ {
@@ -58,6 +62,7 @@ class TestingPanelReadingResource extends Resource
->reactive() ->reactive()
->options(function (callable $get) { ->options(function (callable $get) {
$userHas = Filament::auth()->user()->plant_id; $userHas = Filament::auth()->user()->plant_id;
return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray();
}) })
->default(function () { ->default(function () {
@@ -71,10 +76,9 @@ class TestingPanelReadingResource extends Resource
$set('item_id', null); $set('item_id', null);
$set('machine_id', null); $set('machine_id', null);
$set('tPrError', 'Please select a plant first.'); $set('tPrError', 'Please select a plant first.');
return; return;
} } else {
else
{
$set('line_id', null); $set('line_id', null);
$set('item_id', null); $set('item_id', null);
$set('machine_id', null); $set('machine_id', null);
@@ -94,6 +98,7 @@ class TestingPanelReadingResource extends Resource
if (! $plantId) { if (! $plantId) {
return []; return [];
} }
return Line::where('plant_id', $plantId) return Line::where('plant_id', $plantId)
->pluck('name', 'id') ->pluck('name', 'id')
->toArray(); ->toArray();
@@ -113,6 +118,7 @@ class TestingPanelReadingResource extends Resource
if (! $lineId) { if (! $lineId) {
return []; return [];
} }
// Only show machines for the selected line // Only show machines for the selected line
return Machine::where('line_id', $lineId) return Machine::where('line_id', $lineId)
->pluck('name', 'id') ->pluck('name', 'id')
@@ -144,6 +150,7 @@ class TestingPanelReadingResource extends Resource
if (! $plantId) { if (! $plantId) {
return []; return [];
} }
return MotorTestingMaster::query() return MotorTestingMaster::query()
->join('items', 'motor_testing_masters.item_id', '=', 'items.id') ->join('items', 'motor_testing_masters.item_id', '=', 'items.id')
->where('motor_testing_masters.plant_id', $plantId) ->where('motor_testing_masters.plant_id', $plantId)
@@ -259,6 +266,7 @@ class TestingPanelReadingResource extends Resource
public static function table(Table $table): Table public static function table(Table $table): Table
{ {
return $table return $table
->columns([ ->columns([
// Tables\Columns\TextColumn::make('id') // Tables\Columns\TextColumn::make('id')
@@ -271,6 +279,7 @@ class TestingPanelReadingResource extends Resource
$paginator = $livewire->getTableRecords(); $paginator = $livewire->getTableRecords();
$perPage = method_exists($paginator, 'perPage') ? $paginator->perPage() : 10; $perPage = method_exists($paginator, 'perPage') ? $paginator->perPage() : 10;
$currentPage = method_exists($paginator, 'currentPage') ? $paginator->currentPage() : 1; $currentPage = method_exists($paginator, 'currentPage') ? $paginator->currentPage() : 1;
return ($currentPage - 1) * $perPage + $rowLoop->iteration; return ($currentPage - 1) * $perPage + $rowLoop->iteration;
}), }),
Tables\Columns\TextColumn::make('plant.name') Tables\Columns\TextColumn::make('plant.name')
@@ -463,7 +472,6 @@ class TestingPanelReadingResource extends Resource
->toggleable(isToggledHiddenByDefault: true), ->toggleable(isToggledHiddenByDefault: true),
]) ])
->filters([ ->filters([
Tables\Filters\TrashedFilter::make(), Tables\Filters\TrashedFilter::make(),
Filter::make('advanced_filters') Filter::make('advanced_filters')
->label('Advanced Filters') ->label('Advanced Filters')
@@ -485,8 +493,7 @@ class TestingPanelReadingResource extends Resource
->nullable() ->nullable()
->options(function (callable $get) { ->options(function (callable $get) {
$plantId = $get('Plant'); $plantId = $get('Plant');
if (!$plantId) if (! $plantId) {
{
return []; return [];
} }
@@ -509,9 +516,7 @@ class TestingPanelReadingResource extends Resource
->whereHas('motorTestingMasters') ->whereHas('motorTestingMasters')
->pluck('code', 'id') ->pluck('code', 'id')
->toArray(); ->toArray();
} } else {
else
{
return Item::whereHas('motorTestingMasters') return Item::whereHas('motorTestingMasters')
->pluck('code', 'id') ->pluck('code', 'id')
->toArray(); ->toArray();
@@ -528,6 +533,7 @@ class TestingPanelReadingResource extends Resource
if (! $plantId || ! $lineId) { if (! $plantId || ! $lineId) {
return []; return [];
} }
return Machine::where('plant_id', $plantId) return Machine::where('plant_id', $plantId)
->where('line_id', $lineId) ->where('line_id', $lineId)
->pluck('name', 'id') ->pluck('name', 'id')
@@ -548,6 +554,7 @@ class TestingPanelReadingResource extends Resource
if ($plantId) { if ($plantId) {
$query->where('plant_id', $plantId); $query->where('plant_id', $plantId);
} }
return $query->pluck('description', 'description')->toArray(); return $query->pluck('description', 'description')->toArray();
}) })
@@ -602,16 +609,13 @@ class TestingPanelReadingResource extends Resource
->default('Star') ->default('Star')
->options(function (callable $get) { ->options(function (callable $get) {
$plantId = $get('Plant'); $plantId = $get('Plant');
if ($plantId) if ($plantId) {
{
return Configuration::where('plant_id', $plantId) return Configuration::where('plant_id', $plantId)
->where('c_name', 'MOTOR_CONNECTION') ->where('c_name', 'MOTOR_CONNECTION')
->orderBy('created_at') ->orderBy('created_at')
->pluck('c_value', 'c_value') ->pluck('c_value', 'c_value')
->toArray(); ->toArray();
} } else {
else
{
return Configuration::where('c_name', 'MOTOR_CONNECTION') return Configuration::where('c_name', 'MOTOR_CONNECTION')
->orderBy('created_at') ->orderBy('created_at')
->pluck('c_value', 'c_value') ->pluck('c_value', 'c_value')
@@ -667,6 +671,12 @@ class TestingPanelReadingResource extends Resource
if (! empty($data['Plant'])) { if (! empty($data['Plant'])) {
$query->where('plant_id', $data['Plant']); $query->where('plant_id', $data['Plant']);
} else {
$userHas = Filament::auth()->user()->plant_id;
if ($userHas && strlen($userHas) > 0) {
return $query->whereRaw('1 = 0');
}
} }
if (! empty($data['Line'])) { if (! empty($data['Line'])) {
@@ -700,8 +710,7 @@ class TestingPanelReadingResource extends Resource
} }
} }
if (!empty($data['output'])) if (! empty($data['output'])) {
{
$query->where('output', $data['output']); $query->where('output', $data['output']);
} }
@@ -713,37 +722,30 @@ class TestingPanelReadingResource extends Resource
// }); // });
// } // }
if (!empty($data['connection'])) if (! empty($data['connection'])) {
{
// $query->where('connection',$data['connection']); // $query->where('connection',$data['connection']);
$query->whereHas('motorTestingMaster', function ($subQuery) use ($data) { $query->whereHas('motorTestingMaster', function ($subQuery) use ($data) {
$subQuery->where('connection', $data['connection']); $subQuery->where('connection', $data['connection']);
}); });
} }
if (!empty($data['remark'])) if (! empty($data['remark'])) {
{
$query->where('remark', $data['remark']); $query->where('remark', $data['remark']);
} }
if (!empty($data['batch_number'])) if (! empty($data['batch_number'])) {
{
$query->where('batch_number', $data['batch_number']); $query->where('batch_number', $data['batch_number']);
} }
if (!empty($data['result'])) if (! empty($data['result'])) {
{
$query->where('result', $data['result']); $query->where('result', $data['result']);
} }
if (! empty($data['created_from'])) {
if (!empty($data['created_from']))
{
$query->where('created_at', '>=', $data['created_from']); $query->where('created_at', '>=', $data['created_from']);
} }
if (!empty($data['created_to'])) if (! empty($data['created_to'])) {
{
$query->where('created_at', '<=', $data['created_to']); $query->where('created_at', '<=', $data['created_to']);
} }
}) })
@@ -752,6 +754,12 @@ class TestingPanelReadingResource extends Resource
if (! empty($data['Plant'])) { if (! empty($data['Plant'])) {
$indicators[] = 'Plant: '.Plant::where('id', $data['Plant'])->value('name'); $indicators[] = 'Plant: '.Plant::where('id', $data['Plant'])->value('name');
} else {
$userHas = Filament::auth()->user()->plant_id;
if ($userHas && strlen($userHas) > 0) {
return 'Plant: Choose plant to filter records.';
}
} }
if (! empty($data['Line'])) { if (! empty($data['Line'])) {
$indicators[] = 'Line: '.Line::where('id', $data['Line'])->value('name'); $indicators[] = 'Line: '.Line::where('id', $data['Line'])->value('name');
@@ -780,8 +788,7 @@ class TestingPanelReadingResource extends Resource
if (! empty($data['batch_number'])) { if (! empty($data['batch_number'])) {
$indicators[] = 'Batch Number: '.$data['batch_number']; $indicators[] = 'Batch Number: '.$data['batch_number'];
} }
if (!empty($data['result'])) if (! empty($data['result'])) {
{
$indicators[] = 'Result: '.$data['result']; $indicators[] = 'Result: '.$data['result'];
} }
@@ -798,7 +805,7 @@ class TestingPanelReadingResource extends Resource
} }
return $indicators; return $indicators;
}) }),
]) ])
->filtersFormMaxHeight('280px') ->filtersFormMaxHeight('280px')
->actions([ ->actions([
@@ -810,168 +817,355 @@ class TestingPanelReadingResource extends Resource
Tables\Actions\DeleteBulkAction::make(), Tables\Actions\DeleteBulkAction::make(),
Tables\Actions\ForceDeleteBulkAction::make(), Tables\Actions\ForceDeleteBulkAction::make(),
Tables\Actions\RestoreBulkAction::make(), Tables\Actions\RestoreBulkAction::make(),
// BulkAction::make('exportExcel')
// ->label('Export Selected to Excel')
// ->icon('heroicon-o-document-arrow-down')
// ->action(function (Collection $records) {
// return Excel::download(
// new MotorFreeRunExport($records),
// 'Motor_Free_Run_Register.xlsx'
// );
// }),
BulkAction::make('export_pdf') BulkAction::make('export_pdf')
->label('Export Readings PDF') ->label('Export Selected to Excel')
->action(function ($records) ->action(function ($records) {
{ // $ids = $records->pluck('id')->toArray();
//$records->load('item'); // $query = TestingPanelReading::whereIn('id', $ids);
$records->load('motorTestingMaster.item'); $templatePath = storage_path('app/private/uploads/temp/MotorTestingPanelReportTemplate.xlsx');
$plantId = $records->first()?->plant_id;
$plant = $plantId ? Plant::find($plantId) : null;
// Check if all records are Star-Delta type
$isAllStarDelta = $records->every(function ($record) {
return $record->motorTestingMaster?->connection === 'Star-Delta';
});
// $hasStarDelta = $records->contains(function ($record) {
// return $record->motorTestingMaster?->connection === 'Star-Delta';
// });
//dd($isAllStarDelta);
if(!$isAllStarDelta)
{
$mappedData = collect($records)->map(function ($record) {
return [
// 'Date' => $record['created_at'] ?? '',
'Date' =>date('Y-m-d', strtotime($record['created_at'] ?? '')),
'Output' => $record['output'] ?? '',
'Motor SNo' => $record['serial_number'] ?? '',
'Item Code' => $record->motorTestingMaster->item->code ?? '',
'Motor Type' => $record->motorTestingMaster->item->description ?? '',
'kw' => $record->motorTestingMaster->kw ?? '',
'hp' => $record->motorTestingMaster->hp ?? '',
'phase' => $record->motorTestingMaster->phase ?? '',
'isi_model' => $record->motorTestingMaster->isi_model ?? '',
// BEFORE FREE RUN
'Voltage_Before' => $record['before_fr_volt'] ?? '',
'Current_Before' => $record['before_fr_cur'] ?? '',
'Power_Before' => $record['before_fr_pow'] ?? '',
'Resistance_RY' => $record['before_fr_res_ry'] ?? '',
'Resistance_YB' => $record['before_fr_res_yb'] ?? '',
'Resistance_BR' => $record['before_fr_res_br'] ?? '',
'Insulation_Resistance' => $record['before_fr_ir'] ?? '',
'Frequency_Before' => $record['before_fr_freq'] ?? '',
'Speed_Before' => $record['before_fr_speed'] ?? '',
// AFTER FREE RUN
'Voltage_After' => $record['after_fr_vol'] ?? '',
'Current_After' => $record['after_fr_cur'] ?? '',
'Power_After' => $record['after_fr_pow'] ?? '',
'IR_Hot' => $record['after_fr_ir_hot'] ?? '',
'IR_Cool' => $record['after_fr_ir_cool'] ?? '',
'Leakage_Current' => $record['after_fr_leak_cur'] ?? '',
'Frequency_After' => $record['after_fr_freq'] ?? '',
'Speed_After' => $record['after_fr_speed'] ?? '',
// LOCKED ROTOR TEST
'Voltage_Locked' => $record['locked_rt_volt'] ?? '',
'Current_Locked' => $record['locked_rt_cur'] ?? '',
'Power_Locked' => $record['locked_rt_pow'] ?? '',
// Last 8 columns
'No_Load_Pickup_Voltage' => $record['no_load_pickup_volt'] ?? '',
'Room_Temp' => $record['room_temperature'] ?? '',
'High_Voltage_Test' => $record['hv_test'] ?? '',
'Batch_Number' => $record['batch_number'] ?? '',
'Batch_Count' => $record['batch_count'] ?? '',
'Result' => $record['result'] ?? '',
'Remark' => $record['remark'] ?? '',
'Tested_By' => $record['tested_by'] ?? '',
];
});
}
else
{
$mappedData = collect($records)->map(function ($record) {
return [
//'Date' => $record['created_at'] ?? '',
'Date' =>date('Y-m-d', strtotime($record['created_at'] ?? '')),
'Output' => $record['output'] ?? '',
'Motor SNo' => $record['serial_number'] ?? '',
'Item Code' => $record->motorTestingMaster->item->code ?? '',
'Motor Type' => $record->motorTestingMaster->item->description ?? '',
'kw' => $record->motorTestingMaster->kw ?? '',
'hp' => $record->motorTestingMaster->hp ?? '',
'phase' => $record->motorTestingMaster->phase ?? '',
'isi_model' => $record->motorTestingMaster->isi_model ?? '',
// BEFORE FREE RUN
'Voltage_Before' => $record['before_fr_volt'] ?? '',
'Current_Before' => $record['before_fr_cur'] ?? '',
'Power_Before' => $record['before_fr_pow'] ?? '',
'Resistance_RY' => $record['before_fr_res_ry'] ?? '',
'Resistance_YB' => $record['before_fr_res_yb'] ?? '',
'Resistance_BR' => $record['before_fr_res_br'] ?? '',
'Insulation_Resistance_R' => $record['before_fr_ir_r'] ?? '',
'Insulation_Resistance_Y' => $record['before_fr_ir_y'] ?? '',
'Insulation_Resistance_B' => $record['before_fr_ir_b'] ?? '',
'Frequency_Before' => $record['before_fr_freq'] ?? '',
'Speed_Before' => $record['before_fr_speed'] ?? '',
// AFTER FREE RUN
'Voltage_After' => $record['after_fr_vol'] ?? '',
'Current_After' => $record['after_fr_cur'] ?? '',
'Power_After' => $record['after_fr_pow'] ?? '',
'IR_Hot_R' => $record['after_fr_ir_hot_r'] ?? '',
'IR_Hot_Y' => $record['after_fr_ir_hot_y'] ?? '',
'IR_Hot_B' => $record['after_fr_ir_hot_b'] ?? '',
'IR_Cool_R' => $record['after_fr_ir_cool_r'] ?? '',
'IR_Cool_Y' => $record['after_fr_ir_cool_y'] ?? '',
'IR_Cool_B' => $record['after_fr_ir_cool_b'] ?? '',
'Leakage_Current' => $record['after_fr_leak_cur'] ?? '',
'Frequency_After' => $record['after_fr_freq'] ?? '',
'Speed_After' => $record['after_fr_speed'] ?? '',
// LOCKED ROTOR TEST
'Voltage_Locked' => $record['locked_rt_volt'] ?? '',
'Current_Locked' => $record['locked_rt_cur'] ?? '',
'Power_Locked' => $record['locked_rt_pow'] ?? '',
// Last 8 columns
'No_Load_Pickup_Voltage' => $record['no_load_pickup_volt'] ?? '',
'Room_Temp' => $record['room_temperature'] ?? '',
'High_Voltage_Test' => $record['hv_test'] ?? '',
'Batch_Number' => $record['batch_number'] ?? '',
'Batch_Count' => $record['batch_count'] ?? '',
'Result' => $record['result'] ?? '',
'Remark' => $record['remark'] ?? '',
'Tested_By' => $record['tested_by'] ?? '',
];
});
}
$view = $isAllStarDelta ? 'exports.export-three-phase-pdf' : 'exports.testingpanel-pdf';
$pdf = Pdf::loadView($view, [
'records' => $mappedData,
'plant' => $plant,
]);
// $pdf = Pdf::loadView('exports.testingpanel-pdf',[
// // ['records' => $mappedData]
// 'records' => $mappedData,
// 'plant' => $plant,
// ]);
return response()->streamDownload(
fn () => print($pdf->stream()),
'TestingPanelReading.pdf'
);
return Excel::download(new MotorFreeRunExport($records, $templatePath), 'MotorFreeRunData.xlsx');
}) })
->icon('heroicon-o-document-arrow-down'), ->icon('heroicon-o-document-arrow-down'),
// BulkAction::make('export_pdf')
// ->label('Export Readings PDF'),
// ->action(function ($records)
// {
// //$records->load('item');
// $records->load('motorTestingMaster.item');
// $plantId = $records->first()?->plant_id;
// $plant = $plantId ? Plant::find($plantId) : null;
// // Check if all records are Star-Delta type
// $isAllStarDelta = $records->every(function ($record) {
// return $record->motorTestingMaster?->connection === 'Star-Delta';
// });
// // $hasStarDelta = $records->contains(function ($record) {
// // return $record->motorTestingMaster?->connection === 'Star-Delta';
// // });
// //dd($isAllStarDelta);
// if(!$isAllStarDelta)
// {
// $mappedData = collect($records)->map(function ($record) {
// return [
// // 'Date' => $record['created_at'] ?? '',
// 'Date' =>date('Y-m-d', strtotime($record['created_at'] ?? '')),
// 'Output' => $record['output'] ?? '',
// 'Motor SNo' => $record['serial_number'] ?? '',
// 'Item Code' => $record->motorTestingMaster->item->code ?? '',
// 'Motor Type' => $record->motorTestingMaster->item->description ?? '',
// 'kw' => $record->motorTestingMaster->kw ?? '',
// 'hp' => $record->motorTestingMaster->hp ?? '',
// 'phase' => $record->motorTestingMaster->phase ?? '',
// 'isi_model' => $record->motorTestingMaster->isi_model ?? '',
// // BEFORE FREE RUN
// 'Voltage_Before' => $record['before_fr_volt'] ?? '',
// 'Current_Before' => $record['before_fr_cur'] ?? '',
// 'Power_Before' => $record['before_fr_pow'] ?? '',
// 'Resistance_RY' => $record['before_fr_res_ry'] ?? '',
// 'Resistance_YB' => $record['before_fr_res_yb'] ?? '',
// 'Resistance_BR' => $record['before_fr_res_br'] ?? '',
// 'Insulation_Resistance' => $record['before_fr_ir'] ?? '',
// 'Frequency_Before' => $record['before_fr_freq'] ?? '',
// 'Speed_Before' => $record['before_fr_speed'] ?? '',
// // AFTER FREE RUN
// 'Voltage_After' => $record['after_fr_vol'] ?? '',
// 'Current_After' => $record['after_fr_cur'] ?? '',
// 'Power_After' => $record['after_fr_pow'] ?? '',
// 'IR_Hot' => $record['after_fr_ir_hot'] ?? '',
// 'IR_Cool' => $record['after_fr_ir_cool'] ?? '',
// 'Leakage_Current' => $record['after_fr_leak_cur'] ?? '',
// 'Frequency_After' => $record['after_fr_freq'] ?? '',
// 'Speed_After' => $record['after_fr_speed'] ?? '',
// // LOCKED ROTOR TEST
// 'Voltage_Locked' => $record['locked_rt_volt'] ?? '',
// 'Current_Locked' => $record['locked_rt_cur'] ?? '',
// 'Power_Locked' => $record['locked_rt_pow'] ?? '',
// // Last 8 columns
// 'No_Load_Pickup_Voltage' => $record['no_load_pickup_volt'] ?? '',
// 'Room_Temp' => $record['room_temperature'] ?? '',
// 'High_Voltage_Test' => $record['hv_test'] ?? '',
// 'Batch_Number' => $record['batch_number'] ?? '',
// 'Batch_Count' => $record['batch_count'] ?? '',
// 'Result' => $record['result'] ?? '',
// 'Remark' => $record['remark'] ?? '',
// 'Tested_By' => $record['tested_by'] ?? '',
// ];
// });
// }
// else
// {
// $mappedData = collect($records)->map(function ($record) {
// return [
// //'Date' => $record['created_at'] ?? '',
// 'Date' =>date('Y-m-d', strtotime($record['created_at'] ?? '')),
// 'Output' => $record['output'] ?? '',
// 'Motor SNo' => $record['serial_number'] ?? '',
// 'Item Code' => $record->motorTestingMaster->item->code ?? '',
// 'Motor Type' => $record->motorTestingMaster->item->description ?? '',
// 'kw' => $record->motorTestingMaster->kw ?? '',
// 'hp' => $record->motorTestingMaster->hp ?? '',
// 'phase' => $record->motorTestingMaster->phase ?? '',
// 'isi_model' => $record->motorTestingMaster->isi_model ?? '',
// // BEFORE FREE RUN
// 'Voltage_Before' => $record['before_fr_volt'] ?? '',
// 'Current_Before' => $record['before_fr_cur'] ?? '',
// 'Power_Before' => $record['before_fr_pow'] ?? '',
// 'Resistance_RY' => $record['before_fr_res_ry'] ?? '',
// 'Resistance_YB' => $record['before_fr_res_yb'] ?? '',
// 'Resistance_BR' => $record['before_fr_res_br'] ?? '',
// 'Insulation_Resistance_R' => $record['before_fr_ir_r'] ?? '',
// 'Insulation_Resistance_Y' => $record['before_fr_ir_y'] ?? '',
// 'Insulation_Resistance_B' => $record['before_fr_ir_b'] ?? '',
// 'Frequency_Before' => $record['before_fr_freq'] ?? '',
// 'Speed_Before' => $record['before_fr_speed'] ?? '',
// // AFTER FREE RUN
// 'Voltage_After' => $record['after_fr_vol'] ?? '',
// 'Current_After' => $record['after_fr_cur'] ?? '',
// 'Power_After' => $record['after_fr_pow'] ?? '',
// 'IR_Hot_R' => $record['after_fr_ir_hot_r'] ?? '',
// 'IR_Hot_Y' => $record['after_fr_ir_hot_y'] ?? '',
// 'IR_Hot_B' => $record['after_fr_ir_hot_b'] ?? '',
// 'IR_Cool_R' => $record['after_fr_ir_cool_r'] ?? '',
// 'IR_Cool_Y' => $record['after_fr_ir_cool_y'] ?? '',
// 'IR_Cool_B' => $record['after_fr_ir_cool_b'] ?? '',
// 'Leakage_Current' => $record['after_fr_leak_cur'] ?? '',
// 'Frequency_After' => $record['after_fr_freq'] ?? '',
// 'Speed_After' => $record['after_fr_speed'] ?? '',
// // LOCKED ROTOR TEST
// 'Voltage_Locked' => $record['locked_rt_volt'] ?? '',
// 'Current_Locked' => $record['locked_rt_cur'] ?? '',
// 'Power_Locked' => $record['locked_rt_pow'] ?? '',
// // Last 8 columns
// 'No_Load_Pickup_Voltage' => $record['no_load_pickup_volt'] ?? '',
// 'Room_Temp' => $record['room_temperature'] ?? '',
// 'High_Voltage_Test' => $record['hv_test'] ?? '',
// 'Batch_Number' => $record['batch_number'] ?? '',
// 'Batch_Count' => $record['batch_count'] ?? '',
// 'Result' => $record['result'] ?? '',
// 'Remark' => $record['remark'] ?? '',
// 'Tested_By' => $record['tested_by'] ?? '',
// ];
// });
// }
// $view = $isAllStarDelta ? 'exports.export-three-phase-pdf' : 'exports.testingpanel-pdf';
// $pdf = Pdf::loadView($view, [
// 'records' => $mappedData,
// 'plant' => $plant,
// ]);
// // $pdf = Pdf::loadView('exports.testingpanel-pdf',[
// // // ['records' => $mappedData]
// // 'records' => $mappedData,
// // 'plant' => $plant,
// // ]);
// return response()->streamDownload(
// fn () => print($pdf->stream()),
// 'TestingPanelReading.pdf'
// );
// // return $pdf->download('TestingPanelReading.pdf');
// })
// ->action(function ($records) {
// // Load related item data
// $records->load('motorTestingMaster.item');
// $plantId = $records->first()?->plant_id;
// $plant = $plantId ? Plant::find($plantId) : null;
// // Check if all records are Star-Delta type
// $isAllStarDelta = $records->every(fn($record) => $record->motorTestingMaster?->connection === 'Star-Delta');
// // Map records for export
// $mappedData = $records->map(function ($record) use ($isAllStarDelta) {
// if (!$isAllStarDelta) {
// return [
// 'Date' => date('Y-m-d', strtotime($record['created_at'] ?? '')),
// 'Output' => $record['output'] ?? '',
// 'Motor SNo' => $record['serial_number'] ?? '',
// 'Item Code' => $record->motorTestingMaster->item->code ?? '',
// 'Motor Type' => $record->motorTestingMaster->item->description ?? '',
// 'kw' => $record->motorTestingMaster->kw ?? '',
// 'hp' => $record->motorTestingMaster->hp ?? '',
// 'phase' => $record->motorTestingMaster->phase ?? '',
// 'isi_model' => $record->motorTestingMaster->isi_model ?? '',
// 'Voltage_Before' => $record['before_fr_volt'] ?? '',
// 'Current_Before' => $record['before_fr_cur'] ?? '',
// 'Power_Before' => $record['before_fr_pow'] ?? '',
// 'Resistance_RY' => $record['before_fr_res_ry'] ?? '',
// 'Resistance_YB' => $record['before_fr_res_yb'] ?? '',
// 'Resistance_BR' => $record['before_fr_res_br'] ?? '',
// 'Insulation_Resistance' => $record['before_fr_ir'] ?? '',
// 'Frequency_Before' => $record['before_fr_freq'] ?? '',
// 'Speed_Before' => $record['before_fr_speed'] ?? '',
// 'Voltage_After' => $record['after_fr_vol'] ?? '',
// 'Current_After' => $record['after_fr_cur'] ?? '',
// 'Power_After' => $record['after_fr_pow'] ?? '',
// 'IR_Hot' => $record['after_fr_ir_hot'] ?? '',
// 'IR_Cool' => $record['after_fr_ir_cool'] ?? '',
// 'Leakage_Current' => $record['after_fr_leak_cur'] ?? '',
// 'Frequency_After' => $record['after_fr_freq'] ?? '',
// 'Speed_After' => $record['after_fr_speed'] ?? '',
// 'Voltage_Locked' => $record['locked_rt_volt'] ?? '',
// 'Current_Locked' => $record['locked_rt_cur'] ?? '',
// 'Power_Locked' => $record['locked_rt_pow'] ?? '',
// 'No_Load_Pickup_Voltage' => $record['no_load_pickup_volt'] ?? '',
// 'Room_Temp' => $record['room_temperature'] ?? '',
// 'High_Voltage_Test' => $record['hv_test'] ?? '',
// 'Batch_Number' => $record['batch_number'] ?? '',
// 'Batch_Count' => $record['batch_count'] ?? '',
// 'Result' => $record['result'] ?? '',
// 'Remark' => $record['remark'] ?? '',
// 'Tested_By' => $record['tested_by'] ?? '',
// ];
// } else {
// // Star-Delta records
// return [
// 'Date' => date('Y-m-d', strtotime($record['created_at'] ?? '')),
// 'Output' => $record['output'] ?? '',
// 'Motor SNo' => $record['serial_number'] ?? '',
// 'Item Code' => $record->motorTestingMaster->item->code ?? '',
// 'Motor Type' => $record->motorTestingMaster->item->description ?? '',
// 'kw' => $record->motorTestingMaster->kw ?? '',
// 'hp' => $record->motorTestingMaster->hp ?? '',
// 'phase' => $record->motorTestingMaster->phase ?? '',
// 'isi_model' => $record->motorTestingMaster->isi_model ?? '',
// 'Voltage_Before' => $record['before_fr_volt'] ?? '',
// 'Current_Before' => $record['before_fr_cur'] ?? '',
// 'Power_Before' => $record['before_fr_pow'] ?? '',
// 'Resistance_RY' => $record['before_fr_res_ry'] ?? '',
// 'Resistance_YB' => $record['before_fr_res_yb'] ?? '',
// 'Resistance_BR' => $record['before_fr_res_br'] ?? '',
// 'Insulation_Resistance_R' => $record['before_fr_ir_r'] ?? '',
// 'Insulation_Resistance_Y' => $record['before_fr_ir_y'] ?? '',
// 'Insulation_Resistance_B' => $record['before_fr_ir_b'] ?? '',
// 'Frequency_Before' => $record['before_fr_freq'] ?? '',
// 'Speed_Before' => $record['before_fr_speed'] ?? '',
// 'Voltage_After' => $record['after_fr_vol'] ?? '',
// 'Current_After' => $record['after_fr_cur'] ?? '',
// 'Power_After' => $record['after_fr_pow'] ?? '',
// 'IR_Hot_R' => $record['after_fr_ir_hot_r'] ?? '',
// 'IR_Hot_Y' => $record['after_fr_ir_hot_y'] ?? '',
// 'IR_Hot_B' => $record['after_fr_ir_hot_b'] ?? '',
// 'IR_Cool_R' => $record['after_fr_ir_cool_r'] ?? '',
// 'IR_Cool_Y' => $record['after_fr_ir_cool_y'] ?? '',
// 'IR_Cool_B' => $record['after_fr_ir_cool_b'] ?? '',
// 'Leakage_Current' => $record['after_fr_leak_cur'] ?? '',
// 'Frequency_After' => $record['after_fr_freq'] ?? '',
// 'Speed_After' => $record['after_fr_speed'] ?? '',
// 'Voltage_Locked' => $record['locked_rt_volt'] ?? '',
// 'Current_Locked' => $record['locked_rt_cur'] ?? '',
// 'Power_Locked' => $record['locked_rt_pow'] ?? '',
// 'No_Load_Pickup_Voltage' => $record['no_load_pickup_volt'] ?? '',
// 'Room_Temp' => $record['room_temperature'] ?? '',
// 'High_Voltage_Test' => $record['hv_test'] ?? '',
// 'Batch_Number' => $record['batch_number'] ?? '',
// 'Batch_Count' => $record['batch_count'] ?? '',
// 'Result' => $record['result'] ?? '',
// 'Remark' => $record['remark'] ?? '',
// 'Tested_By' => $record['tested_by'] ?? '',
// ];
// }
// });
// // Excel template path
// $templatePath = storage_path('app/private/uploads/temp/MotorTestingPanelReportTemplate.xlsx');
// // Check if template exists
// if (!file_exists($templatePath)) {
// Notification::make()
// ->title('Template Not Found')
// ->danger()
// ->body('The Excel template file does not exist. Please upload it first.')
// ->send();
// return; // Stop further execution
// }
// // Export Excel
// // return Excel::download(
// // new MotorFreeRunExport(collect($mappedData)),
// // 'TestingPanelReading.xlsx',
// // \Maatwebsite\Excel\Excel::XLSX,
// // [
// // 'template' => $templatePath,
// // ]
// // );
// // Load the template
// $spreadsheet = IOFactory::load($templatePath);
// $sheet = $spreadsheet->getActiveSheet();
// // Insert mapped data starting from row 3
// $row = 7;
// foreach ($mappedData as $dataRow) {
// $col = 'A';
// foreach ($dataRow as $cell) {
// $sheet->setCellValue($col . $row, $cell);
// $col++;
// }
// $row++;
// }
// // Download the modified template as Excel
// $writer = new Xlsx($spreadsheet);
// return response()->streamDownload(function() use ($writer) {
// $writer->save('php://output');
// }, 'TestingPanelReading.xlsx');
// })
// ->action(function ($records) {
// // If no template, notify
// $templatePath = storage_path('app/private/uploads/temp/MotorTestingPanelReportTemplate.xlsx');
// if (!file_exists($templatePath)) {
// Notification::make()
// ->title('Template Not Found')
// ->danger()
// ->body('The Excel template file does not exist. Please upload it first.')
// ->send();
// return;
// }
// // Just export the raw data (fast, chunked)
// return Excel::download(new MotorFreeRunExport($records->pluck('id')), 'MotorFreeRunData.xlsx');
// })
// ->icon('heroicon-o-document-arrow-down'), c
BulkAction::make('export_isi_pdf') BulkAction::make('export_isi_pdf')
->label('Export ISI Readings PDF') ->label('Export ISI Readings PDF')
->action(function ($records) ->action(function ($records) {
{ // Increase memory and execution time
// ini_set('memory_limit', '1024M');
// set_time_limit(300);
$records->load('motorTestingMaster.item'); $records->load('motorTestingMaster.item');
$plantId = $records->first()?->plant_id; $plantId = $records->first()?->plant_id;
@@ -985,8 +1179,7 @@ class TestingPanelReadingResource extends Resource
// }); // });
// dd($isAllStarDelta); // dd($isAllStarDelta);
if(!$isAllStarDelta) if (! $isAllStarDelta) {
{
$mappedData = collect($records)->map(function ($record) { $mappedData = collect($records)->map(function ($record) {
return [ return [
// 'Date' => $record['created_at'] ?? '', // 'Date' => $record['created_at'] ?? '',
@@ -1024,9 +1217,7 @@ class TestingPanelReadingResource extends Resource
'Remark' => $record['remark'] ?? '', 'Remark' => $record['remark'] ?? '',
]; ];
}); });
} } else {
else
{
$mappedData = collect($records)->map(function ($record) { $mappedData = collect($records)->map(function ($record) {
return [ return [
// 'Date' => $record['created_at'] ?? '', // 'Date' => $record['created_at'] ?? '',
@@ -1070,7 +1261,6 @@ class TestingPanelReadingResource extends Resource
}); });
} }
$view = $isAllStarDelta ? 'exports.export-isi-three-phase-pdf' : 'exports.export-isi-pdf'; $view = $isAllStarDelta ? 'exports.export-isi-three-phase-pdf' : 'exports.export-isi-pdf';
$pdf = Pdf::loadView($view, [ $pdf = Pdf::loadView($view, [
@@ -1093,15 +1283,18 @@ class TestingPanelReadingResource extends Resource
}) })
->icon('heroicon-o-document-arrow-down'), ->icon('heroicon-o-document-arrow-down'),
]), ]),
]) ])
->headerActions([ ->headerActions([
ImportAction::make() ImportAction::make()
->label('Import Testing Panel Readings')
->color('warning')
->importer(TestingPanelReadingImporter::class) ->importer(TestingPanelReadingImporter::class)
->visible(function () { ->visible(function () {
return Filament::auth()->user()->can('view import testing panel reading'); return Filament::auth()->user()->can('view import testing panel reading');
}), }),
ExportAction::make() ExportAction::make()
->label('Export Testing Panel Readings')
->color('warning')
->exporter(TestingPanelReadingExporter::class) ->exporter(TestingPanelReadingExporter::class)
->visible(function () { ->visible(function () {
return Filament::auth()->user()->can('view export testing panel reading'); return Filament::auth()->user()->can('view export testing panel reading');

View File

@@ -5,14 +5,10 @@ namespace App\Filament\Resources;
use App\Filament\Exports\WeightValidationExporter; use App\Filament\Exports\WeightValidationExporter;
use App\Filament\Imports\WeightValidationImporter; use App\Filament\Imports\WeightValidationImporter;
use App\Filament\Resources\WeightValidationResource\Pages; use App\Filament\Resources\WeightValidationResource\Pages;
use App\Filament\Resources\WeightValidationResource\RelationManagers;
use App\Models\Item; use App\Models\Item;
use App\Models\Line;
use App\Models\Plant; use App\Models\Plant;
use App\Models\QualityValidation;
use App\Models\StickerMaster; use App\Models\StickerMaster;
use App\Models\WeightValidation; use App\Models\WeightValidation;
use Filament\Actions\Action;
use Filament\Facades\Filament; use Filament\Facades\Filament;
use Filament\Forms; use Filament\Forms;
use Filament\Forms\Components\DateTimePicker; use Filament\Forms\Components\DateTimePicker;
@@ -26,14 +22,13 @@ use Filament\Resources\Resource;
use Filament\Tables; use Filament\Tables;
use Filament\Tables\Actions\ExportAction; use Filament\Tables\Actions\ExportAction;
use Filament\Tables\Actions\ImportAction; use Filament\Tables\Actions\ImportAction;
use Filament\Tables\Filters\Filter;
use Filament\Tables\Table; use Filament\Tables\Table;
use Filament\Widgets\StatsOverviewWidget\Stat;
use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope; use Illuminate\Database\Eloquent\SoftDeletingScope;
use Illuminate\Support\Facades\Storage; use Illuminate\Support\Facades\Storage;
use Maatwebsite\Excel\Facades\Excel; use Maatwebsite\Excel\Facades\Excel;
use Str; use Str;
use Filament\Tables\Filters\Filter;
class WeightValidationResource extends Resource class WeightValidationResource extends Resource
{ {
@@ -51,6 +46,7 @@ class WeightValidationResource extends Resource
->relationship('plant', 'name') ->relationship('plant', 'name')
->options(function (callable $get) { ->options(function (callable $get) {
$userHas = Filament::auth()->user()->plant_id; $userHas = Filament::auth()->user()->plant_id;
return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray();
}) })
->required(), ->required(),
@@ -80,7 +76,7 @@ class WeightValidationResource extends Resource
Forms\Components\TextInput::make('picked_weight') Forms\Components\TextInput::make('picked_weight')
->label('Picked Weight'), ->label('Picked Weight'),
Forms\Components\TextInput::make('scanned_by') Forms\Components\TextInput::make('scanned_by')
->label('Scanned By') ->label('Scanned By'),
]); ]);
} }
@@ -98,6 +94,7 @@ class WeightValidationResource extends Resource
$paginator = $livewire->getTableRecords(); $paginator = $livewire->getTableRecords();
$perPage = method_exists($paginator, 'perPage') ? $paginator->perPage() : 10; $perPage = method_exists($paginator, 'perPage') ? $paginator->perPage() : 10;
$currentPage = method_exists($paginator, 'currentPage') ? $paginator->currentPage() : 1; $currentPage = method_exists($paginator, 'currentPage') ? $paginator->currentPage() : 1;
return ($currentPage - 1) * $perPage + $rowLoop->iteration; return ($currentPage - 1) * $perPage + $rowLoop->iteration;
}), }),
Tables\Columns\TextColumn::make('plant.name') Tables\Columns\TextColumn::make('plant.name')
@@ -157,9 +154,6 @@ class WeightValidationResource extends Resource
->sortable() ->sortable()
->toggleable(isToggledHiddenByDefault: true), ->toggleable(isToggledHiddenByDefault: true),
]) ])
// ->filters([
// Tables\Filters\TrashedFilter::make(),
// ])
->filters([ ->filters([
Tables\Filters\TrashedFilter::make(), Tables\Filters\TrashedFilter::make(),
Filter::make('advanced_filters') Filter::make('advanced_filters')
@@ -173,6 +167,7 @@ class WeightValidationResource extends Resource
// }) // })
->options(function (callable $get) { ->options(function (callable $get) {
$userHas = Filament::auth()->user()->plant_id; $userHas = Filament::auth()->user()->plant_id;
return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray();
}) })
->reactive(), ->reactive(),
@@ -180,18 +175,33 @@ class WeightValidationResource extends Resource
// $set('sticker_master_id', null); // $set('sticker_master_id', null);
// $set('sap_msg_status', null); // $set('sap_msg_status', null);
// }), // }),
Select::make('Item Code') Select::make('Item Code')
->label('Search by Item Code') ->label('Search by Item Code')
->nullable() ->nullable()
// ->options(function (callable $get) {
// $plantId = $get('Plant');
// if (! $plantId) {
// return [];
// }
// return Item::where('plant_id', $plantId)->pluck('code', 'id');
// })
->options(function (callable $get) { ->options(function (callable $get) {
$plantId = $get('Plant'); $plantId = $get('Plant');
if (! $plantId) { if (! $plantId) {
return []; return [];
} }
return Item::where('plant_id', $plantId)->pluck('code', 'id');
return Item::whereHas('weightValidations', function ($query) use ($plantId) {
if ($plantId) {
$query->where('plant_id', $plantId);
}
})->pluck('code', 'id');
}) })
->searchable() ->searchable()
->reactive(), ->reactive(),
TextInput::make('Obd Number') TextInput::make('Obd Number')
->label('OBD Number') ->label('OBD Number')
->placeholder('Enter OBD Number'), ->placeholder('Enter OBD Number'),
@@ -243,6 +253,7 @@ class WeightValidationResource extends Resource
->placeholder(placeholder: 'Select From DateTime') ->placeholder(placeholder: 'Select From DateTime')
->reactive() ->reactive()
->native(false), ->native(false),
DateTimePicker::make('created_to') DateTimePicker::make('created_to')
->label('Created To') ->label('Created To')
->placeholder(placeholder: 'Select To DateTime') ->placeholder(placeholder: 'Select To DateTime')
@@ -257,6 +268,12 @@ class WeightValidationResource extends Resource
if (! empty($data['Plant'])) { if (! empty($data['Plant'])) {
$query->where('plant_id', $data['Plant']); $query->where('plant_id', $data['Plant']);
} else {
$userHas = Filament::auth()->user()->plant_id;
if ($userHas && strlen($userHas) > 0) {
return $query->whereRaw('1 = 0');
}
} }
if (! empty($data['Item Code'])) { if (! empty($data['Item Code'])) {
@@ -295,7 +312,6 @@ class WeightValidationResource extends Resource
$query->where('scanned_by', $data['Scanned By']); $query->where('scanned_by', $data['Scanned By']);
} }
if (! empty($data['created_from'])) { if (! empty($data['created_from'])) {
$query->where('created_at', '>=', $data['created_from']); $query->where('created_at', '>=', $data['created_from']);
} }
@@ -309,6 +325,12 @@ class WeightValidationResource extends Resource
if (! empty($data['Plant'])) { if (! empty($data['Plant'])) {
$indicators[] = 'Plant: '.Plant::where('id', $data['Plant'])->value('name'); $indicators[] = 'Plant: '.Plant::where('id', $data['Plant'])->value('name');
} else {
$userHas = Filament::auth()->user()->plant_id;
if ($userHas && strlen($userHas) > 0) {
return 'Plant: Choose plant to filter records.';
}
} }
if (! empty($data['Item Code'])) { if (! empty($data['Item Code'])) {
@@ -361,7 +383,7 @@ class WeightValidationResource extends Resource
} }
return $indicators; return $indicators;
}) }),
]) ])
->filtersFormMaxHeight('280px') ->filtersFormMaxHeight('280px')
->actions([ ->actions([
@@ -383,6 +405,7 @@ class WeightValidationResource extends Resource
// ->options(Plant::pluck('name', 'id')->toArray()) // ->options(Plant::pluck('name', 'id')->toArray())
->options(function (callable $get) { ->options(function (callable $get) {
$userHas = Filament::auth()->user()->plant_id; $userHas = Filament::auth()->user()->plant_id;
return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray();
}) })
->label('Select Plant') ->label('Select Plant')
@@ -435,10 +458,10 @@ class WeightValidationResource extends Resource
->danger() ->danger()
->send(); ->send();
if ($disk->exists($path)) if ($disk->exists($path)) {
{
$disk->delete($path); $disk->delete($path);
} }
return; return;
} }
@@ -469,6 +492,7 @@ class WeightValidationResource extends Resource
if ($disk->exists($path)) { if ($disk->exists($path)) {
$disk->delete($path); $disk->delete($path);
} }
return; return;
} }
@@ -482,9 +506,10 @@ class WeightValidationResource extends Resource
$lineNumbers = []; $lineNumbers = [];
$validRowsFound = false; $validRowsFound = false;
foreach ($rows as $index => $row) foreach ($rows as $index => $row) {
{ if ($index === 0) {
if ($index === 0) continue; // Skip header continue;
} // Skip header
$materialCode = trim($row[0]); $materialCode = trim($row[0]);
$lineNumber = trim($row[1]); $lineNumber = trim($row[1]);
@@ -497,31 +522,23 @@ class WeightValidationResource extends Resource
} }
if (! empty($materialCode)) { if (! empty($materialCode)) {
if(Str::length($materialCode) < 6 || !ctype_alnum($materialCode)) if (Str::length($materialCode) < 6 || ! ctype_alnum($materialCode)) {
{
$invalidMatCodes[] = $materialCode; $invalidMatCodes[] = $materialCode;
continue; continue;
} } else {
else
{
$materialCodes[] = $materialCode; $materialCodes[] = $materialCode;
$validData = true; $validData = true;
if(Str::length($lineNumber) < 1 || !is_numeric($lineNumber)) if (Str::length($lineNumber) < 1 || ! is_numeric($lineNumber)) {
{
$validData = false; $validData = false;
$invalidLines[] = $materialCode; $invalidLines[] = $materialCode;
} } elseif (in_array($lineNumber, $lineNumbers)) {
else if (in_array($lineNumber, $lineNumbers))
{
$duplicateLines[] = $materialCode; $duplicateLines[] = $materialCode;
} } else {
else
{
$lineNumbers[] = $lineNumber; $lineNumbers[] = $lineNumber;
} }
if(Str::length($batchNumber) < 8 || !is_numeric($batchNumber))//ctype_alnum if (Str::length($batchNumber) < 8 || ! is_numeric($batchNumber)) {// ctype_alnum
{
$validData = false; $validData = false;
$invalidBatch[] = $materialCode; $invalidBatch[] = $materialCode;
} }
@@ -530,20 +547,16 @@ class WeightValidationResource extends Resource
// $validData = false; // $validData = false;
// $invalidHeat[] = $materialCode; // $invalidHeat[] = $materialCode;
// } // }
if(Str::length($actualWeight) < 1 || !is_numeric($actualWeight))//ctype_alnum if (Str::length($actualWeight) < 1 || ! is_numeric($actualWeight)) {// ctype_alnum
{
$validData = false; $validData = false;
$invalidWeight[] = $materialCode; $invalidWeight[] = $materialCode;
} }
if ($validData) if ($validData) {
{
$validRowsFound = true; $validRowsFound = true;
} }
} }
} } else {
else
{
continue; continue;
} }
} }
@@ -560,6 +573,7 @@ class WeightValidationResource extends Resource
if ($disk->exists($path)) { if ($disk->exists($path)) {
$disk->delete($path); $disk->delete($path);
} }
return; return;
} }
@@ -575,6 +589,7 @@ class WeightValidationResource extends Resource
if ($disk->exists($path)) { if ($disk->exists($path)) {
$disk->delete($path); $disk->delete($path);
} }
return; return;
} }
@@ -590,6 +605,7 @@ class WeightValidationResource extends Resource
if ($disk->exists($path)) { if ($disk->exists($path)) {
$disk->delete($path); $disk->delete($path);
} }
return; return;
} }
@@ -605,6 +621,7 @@ class WeightValidationResource extends Resource
if ($disk->exists($path)) { if ($disk->exists($path)) {
$disk->delete($path); $disk->delete($path);
} }
return; return;
} }
@@ -635,6 +652,7 @@ class WeightValidationResource extends Resource
if ($disk->exists($path)) { if ($disk->exists($path)) {
$disk->delete($path); $disk->delete($path);
} }
return; return;
} }
@@ -671,6 +689,7 @@ class WeightValidationResource extends Resource
if ($disk->exists($path)) { if ($disk->exists($path)) {
$disk->delete($path); $disk->delete($path);
} }
return; return;
} }
@@ -695,6 +714,7 @@ class WeightValidationResource extends Resource
if ($disk->exists($path)) { if ($disk->exists($path)) {
$disk->delete($path); $disk->delete($path);
} }
return; return;
} }
@@ -709,6 +729,7 @@ class WeightValidationResource extends Resource
if ($disk->exists($path)) { if ($disk->exists($path)) {
$disk->delete($path); $disk->delete($path);
} }
return; return;
} }
@@ -729,10 +750,11 @@ class WeightValidationResource extends Resource
$inserted = 0; $inserted = 0;
// $updated = 0; // $updated = 0;
foreach ($rows as $index => $row) foreach ($rows as $index => $row) {
{
// Skip header // Skip header
if ($index === 0) { continue; } if ($index === 0) {
continue;
}
$materialCode = trim($row[0]); $materialCode = trim($row[0]);
$lineNumber = trim($row[1]); $lineNumber = trim($row[1]);
@@ -750,12 +772,9 @@ class WeightValidationResource extends Resource
$masItem = Item::where('plant_id', $plantId)->where('code', $materialCode)->first(); $masItem = Item::where('plant_id', $plantId)->where('code', $materialCode)->first();
if ($recordExist) { if ($recordExist) {
$skipUpd = $recordExist->vehicle_number ?? null; $skipUpd = $recordExist->vehicle_number ?? null;
if($skipUpd) if ($skipUpd) {
{
continue; continue;
} } else {
else
{
if ($masItem) { if ($masItem) {
$recordExist->update([ $recordExist->update([
'item_id' => $masItem->id, 'item_id' => $masItem->id,
@@ -767,8 +786,7 @@ class WeightValidationResource extends Resource
$updated++; $updated++;
} }
} }
} } else {
else {
if ($masItem) { if ($masItem) {
WeightValidation::create([ WeightValidation::create([
'item_id' => $masItem->id, 'item_id' => $masItem->id,
@@ -779,12 +797,9 @@ class WeightValidationResource extends Resource
// 'heat_number' => $heatNumber, // 'heat_number' => $heatNumber,
'obd_weight' => $actualWeight, 'obd_weight' => $actualWeight,
]); ]);
if (in_array($lineNumber, $availLines)) if (in_array($lineNumber, $availLines)) {
{
continue; continue;
} } else {
else
{
$inserted++; $inserted++;
} }
} }
@@ -795,7 +810,7 @@ class WeightValidationResource extends Resource
if ($updateInv) { if ($updateInv) {
if ($updated > 0) { if ($updated > 0) {
Notification::make() Notification::make()
->title("Start the scanning process!") ->title('Start the scanning process!')
->body("'$updated' OBD lines were updated and<br>'$inserted' OBD lines were inserted for<br>imported OBD Invoice : '$originalNameOnly'.") ->body("'$updated' OBD lines were updated and<br>'$inserted' OBD lines were inserted for<br>imported OBD Invoice : '$originalNameOnly'.")
->info() ->info()
// ->success() // ->success()
@@ -806,24 +821,20 @@ class WeightValidationResource extends Resource
$totalQuantity = WeightValidation::where('obd_number', $originalNameOnly)->where('plant_id', $plantId)->count(); $totalQuantity = WeightValidation::where('obd_number', $originalNameOnly)->where('plant_id', $plantId)->count();
$scannedQuantity = WeightValidation::where('obd_number', $originalNameOnly)->where('plant_id', $plantId)->whereNotNull('vehicle_number')->where('vehicle_number', '!=', '')->count(); $scannedQuantity = WeightValidation::where('obd_number', $originalNameOnly)->where('plant_id', $plantId)->whereNotNull('vehicle_number')->where('vehicle_number', '!=', '')->count();
if ($totalQuantity === $scannedQuantity) if ($totalQuantity === $scannedQuantity) {
{
if ($disk->exists($path)) { if ($disk->exists($path)) {
$disk->delete($path); $disk->delete($path);
} }
// $this->dispatch('refreshCompletedInvoice', invoiceNumber: $originalNameOnly, plantId: $plantId); // $this->dispatch('refreshCompletedInvoice', invoiceNumber: $originalNameOnly, plantId: $plantId);
} } else {
else
{
if ($disk->exists($path)) { if ($disk->exists($path)) {
$disk->delete($path); $disk->delete($path);
} }
// $this->dispatch('refreshInvoiceData', invoiceNumber: $originalNameOnly, plantId: $plantId); // $this->dispatch('refreshInvoiceData', invoiceNumber: $originalNameOnly, plantId: $plantId);
} }
} } elseif ($inserted > 0) {
else if ($inserted > 0) {
Notification::make() Notification::make()
->title("Start the scanning process!") ->title('Start the scanning process!')
->body("'$inserted' OBD lines were inserted for imported OBD Invoice : '$originalNameOnly'.") ->body("'$inserted' OBD lines were inserted for imported OBD Invoice : '$originalNameOnly'.")
->info() ->info()
// ->success() // ->success()
@@ -834,24 +845,20 @@ class WeightValidationResource extends Resource
$totalQuantity = WeightValidation::where('obd_number', $originalNameOnly)->where('plant_id', $plantId)->count(); $totalQuantity = WeightValidation::where('obd_number', $originalNameOnly)->where('plant_id', $plantId)->count();
$scannedQuantity = WeightValidation::where('obd_number', $originalNameOnly)->where('plant_id', $plantId)->whereNotNull('vehicle_number')->where('vehicle_number', '!=', '')->count(); $scannedQuantity = WeightValidation::where('obd_number', $originalNameOnly)->where('plant_id', $plantId)->whereNotNull('vehicle_number')->where('vehicle_number', '!=', '')->count();
if ($totalQuantity === $scannedQuantity) if ($totalQuantity === $scannedQuantity) {
{
if ($disk->exists($path)) { if ($disk->exists($path)) {
$disk->delete($path); $disk->delete($path);
} }
// $this->dispatch('refreshCompletedInvoice', invoiceNumber: $originalNameOnly, plantId: $plantId); // $this->dispatch('refreshCompletedInvoice', invoiceNumber: $originalNameOnly, plantId: $plantId);
} } else {
else
{
if ($disk->exists($path)) { if ($disk->exists($path)) {
$disk->delete($path); $disk->delete($path);
} }
// $this->dispatch('refreshInvoiceData', invoiceNumber: $originalNameOnly, plantId: $plantId); // $this->dispatch('refreshInvoiceData', invoiceNumber: $originalNameOnly, plantId: $plantId);
} }
} } else {
else {
Notification::make() Notification::make()
->title("Import Failed: OBD Invoice") ->title('Import Failed: OBD Invoice')
->body("No exist records were updated for imported OBD Invoice : '$originalNameOnly'.") ->body("No exist records were updated for imported OBD Invoice : '$originalNameOnly'.")
->danger() ->danger()
->seconds(2) ->seconds(2)
@@ -863,14 +870,14 @@ class WeightValidationResource extends Resource
if ($disk->exists($path)) { if ($disk->exists($path)) {
$disk->delete($path); $disk->delete($path);
} }
// $this->dispatch('refreshEmptyInvoice', invoiceNumber: $originalNameOnly, plantId: $plantId); // $this->dispatch('refreshEmptyInvoice', invoiceNumber: $originalNameOnly, plantId: $plantId);
return; return;
} }
} } else {
else {
if ($inserted > 0) { if ($inserted > 0) {
Notification::make() Notification::make()
->title("Start the scanning process!") ->title('Start the scanning process!')
->body("'$inserted' OBD lines were inserted for imported OBD Invoice : '$originalNameOnly'.") ->body("'$inserted' OBD lines were inserted for imported OBD Invoice : '$originalNameOnly'.")
->info() ->info()
// ->success() // ->success()
@@ -881,24 +888,20 @@ class WeightValidationResource extends Resource
$totalQuantity = WeightValidation::where('obd_number', $originalNameOnly)->where('plant_id', $plantId)->count(); $totalQuantity = WeightValidation::where('obd_number', $originalNameOnly)->where('plant_id', $plantId)->count();
$scannedQuantity = WeightValidation::where('obd_number', $originalNameOnly)->where('plant_id', $plantId)->whereNotNull('vehicle_number')->where('vehicle_number', '!=', '')->count(); $scannedQuantity = WeightValidation::where('obd_number', $originalNameOnly)->where('plant_id', $plantId)->whereNotNull('vehicle_number')->where('vehicle_number', '!=', '')->count();
if ($totalQuantity === $scannedQuantity) if ($totalQuantity === $scannedQuantity) {
{
if ($disk->exists($path)) { if ($disk->exists($path)) {
$disk->delete($path); $disk->delete($path);
} }
// $this->dispatch('refreshCompletedInvoice', invoiceNumber: $originalNameOnly, plantId: $plantId); // $this->dispatch('refreshCompletedInvoice', invoiceNumber: $originalNameOnly, plantId: $plantId);
} } else {
else
{
if ($disk->exists($path)) { if ($disk->exists($path)) {
$disk->delete($path); $disk->delete($path);
} }
// $this->dispatch('refreshInvoiceData', invoiceNumber: $originalNameOnly, plantId: $plantId); // $this->dispatch('refreshInvoiceData', invoiceNumber: $originalNameOnly, plantId: $plantId);
} }
} } else {
else {
Notification::make() Notification::make()
->title("Import Failed: OBD Invoice") ->title('Import Failed: OBD Invoice')
->body("No new records were inserted for imported OBD Invoice : '$originalNameOnly'.") ->body("No new records were inserted for imported OBD Invoice : '$originalNameOnly'.")
->danger() ->danger()
->seconds(2) ->seconds(2)
@@ -910,6 +913,7 @@ class WeightValidationResource extends Resource
if ($disk->exists($path)) { if ($disk->exists($path)) {
$disk->delete($path); $disk->delete($path);
} }
// $this->dispatch('refreshEmptyInvoice', invoiceNumber: $originalNameOnly, plantId: $plantId); // $this->dispatch('refreshEmptyInvoice', invoiceNumber: $originalNameOnly, plantId: $plantId);
return; return;
} }

View File

@@ -3,15 +3,15 @@
namespace App\Models; namespace App\Models;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\SoftDeletes;
class Item extends Model class Item extends Model
{ {
use SoftDeletes; use SoftDeletes;
protected $fillable = [ protected $fillable = [
"plant_id", 'plant_id',
'category', 'category',
'code', 'code',
'description', 'description',
@@ -43,4 +43,19 @@ class Item extends Model
{ {
return $this->hasMany(TestingPanelReading::class); return $this->hasMany(TestingPanelReading::class);
} }
public function processOrders()
{
return $this->hasMany(ProcessOrder::class);
}
public function productCharacteristicsMasters()
{
return $this->hasMany(ProductCharacteristicsMaster::class);
}
public function weightValidations()
{
return $this->hasMany(WeightValidation::class);
}
} }