diff --git a/app/Filament/Exports/BlockExporter.php b/app/Filament/Exports/BlockExporter.php index 08bd1d0..b48b17c 100644 --- a/app/Filament/Exports/BlockExporter.php +++ b/app/Filament/Exports/BlockExporter.php @@ -24,26 +24,27 @@ class BlockExporter extends Exporter // Increment and return the row number return ++$rowNumber; }), - ExportColumn::make('plant.name') - ->label('PLANT'), + ExportColumn::make('plant.code') + ->label('PLANT CODE'), ExportColumn::make('name') - ->label('NAME'), + ->label('BLOCK NAME'), ExportColumn::make('created_at') ->label('CREATED AT'), ExportColumn::make('updated_at') - ->label('UPDATED AT'), + ->label('UPDATED AT') + ->enabledByDefault(true), ExportColumn::make('deleted_at') - ->enabledByDefault(false) - ->label('DELETED AT'), + ->label('DELETED AT') + ->enabledByDefault(false), ]; } public static function getCompletedNotificationBody(Export $export): string { - $body = 'Your block export has completed and ' . number_format($export->successful_rows) . ' ' . str('row')->plural($export->successful_rows) . ' exported.'; + $body = 'Your block export has completed and '.number_format($export->successful_rows).' '.str('row')->plural($export->successful_rows).' exported.'; if ($failedRowsCount = $export->getFailedRowsCount()) { - $body .= ' ' . number_format($failedRowsCount) . ' ' . str('row')->plural($failedRowsCount) . ' failed to export.'; + $body .= ' '.number_format($failedRowsCount).' '.str('row')->plural($failedRowsCount).' failed to export.'; } return $body; diff --git a/app/Filament/Exports/CharacteristicValueExporter.php b/app/Filament/Exports/CharacteristicValueExporter.php index 49b51b2..9d899b0 100644 --- a/app/Filament/Exports/CharacteristicValueExporter.php +++ b/app/Filament/Exports/CharacteristicValueExporter.php @@ -14,6 +14,7 @@ class CharacteristicValueExporter extends Exporter public static function getColumns(): array { static $rowNumber = 0; + return [ ExportColumn::make('no') ->label('NO') @@ -22,30 +23,30 @@ class CharacteristicValueExporter extends Exporter return ++$rowNumber; }), ExportColumn::make('plant.code') - ->label('PLANT CODE'), + ->label('PLANT CODE'), ExportColumn::make('line.name') - ->label('LINE NAME'), + ->label('LINE NAME'), ExportColumn::make('item.code') - ->label('ITEM CODE'), + ->label('ITEM CODE'), ExportColumn::make('machine.name') - ->label('WORK CENTER'), + ->label('WORK CENTER'), ExportColumn::make('process_order') - ->label('PROCESS ORDER'), + ->label('PROCESS ORDER'), ExportColumn::make('coil_number') - ->label('COIL NUMBER'), + ->label('COIL NUMBER'), ExportColumn::make('status') - ->label('STATUS'), + ->label('STATUS'), ExportColumn::make('created_at') - ->label('CREATED AT'), + ->label('CREATED AT'), ExportColumn::make('updated_at') - ->label('UPDATED AT'), + ->label('UPDATED AT'), ExportColumn::make('created_by') - ->label('CREATED BY'), + ->label('CREATED BY'), ExportColumn::make('updated_by') - ->label('UPDATED BY'), + ->label('UPDATED BY'), ExportColumn::make('deleted_at') - ->enabledByDefault(false) - ->label('DELETED AT'), + ->enabledByDefault(false) + ->label('DELETED AT'), ]; } diff --git a/app/Filament/Exports/CheckPointNameExporter.php b/app/Filament/Exports/CheckPointNameExporter.php index 315c90d..566ace1 100644 --- a/app/Filament/Exports/CheckPointNameExporter.php +++ b/app/Filament/Exports/CheckPointNameExporter.php @@ -24,8 +24,8 @@ class CheckPointNameExporter extends Exporter // Increment and return the row number return ++$rowNumber; }), - ExportColumn::make('plant.name') - ->label('PLANT'), + ExportColumn::make('plant.code') + ->label('PLANT CODE'), ExportColumn::make('name') ->label('CHECK POINT NAME'), ExportColumn::make('created_at') @@ -42,10 +42,10 @@ class CheckPointNameExporter extends Exporter public static function getCompletedNotificationBody(Export $export): string { - $body = 'Your check point name export has completed and ' . number_format($export->successful_rows) . ' ' . str('row')->plural($export->successful_rows) . ' exported.'; + $body = 'Your check point name export has completed and '.number_format($export->successful_rows).' '.str('row')->plural($export->successful_rows).' exported.'; if ($failedRowsCount = $export->getFailedRowsCount()) { - $body .= ' ' . number_format($failedRowsCount) . ' ' . str('row')->plural($failedRowsCount) . ' failed to export.'; + $body .= ' '.number_format($failedRowsCount).' '.str('row')->plural($failedRowsCount).' failed to export.'; } return $body; diff --git a/app/Filament/Exports/CheckPointTimeExporter.php b/app/Filament/Exports/CheckPointTimeExporter.php index 42193f1..86b9adc 100644 --- a/app/Filament/Exports/CheckPointTimeExporter.php +++ b/app/Filament/Exports/CheckPointTimeExporter.php @@ -24,8 +24,8 @@ class CheckPointTimeExporter extends Exporter // Increment and return the row number return ++$rowNumber; }), - ExportColumn::make('plant.name') - ->label('PLANT'), + ExportColumn::make('plant.code') + ->label('PLANT CODE'), ExportColumn::make('checkPointNames1.name') ->label('CHECK POINT 1'), ExportColumn::make('checkPointNames2.name') @@ -50,10 +50,10 @@ class CheckPointTimeExporter extends Exporter public static function getCompletedNotificationBody(Export $export): string { - $body = 'Your check point time export has completed and ' . number_format($export->successful_rows) . ' ' . str('row')->plural($export->successful_rows) . ' exported.'; + $body = 'Your check point time export has completed and '.number_format($export->successful_rows).' '.str('row')->plural($export->successful_rows).' exported.'; if ($failedRowsCount = $export->getFailedRowsCount()) { - $body .= ' ' . number_format($failedRowsCount) . ' ' . str('row')->plural($failedRowsCount) . ' failed to export.'; + $body .= ' '.number_format($failedRowsCount).' '.str('row')->plural($failedRowsCount).' failed to export.'; } return $body; diff --git a/app/Filament/Exports/ConfigurationExporter.php b/app/Filament/Exports/ConfigurationExporter.php index 4dcf751..d794e27 100644 --- a/app/Filament/Exports/ConfigurationExporter.php +++ b/app/Filament/Exports/ConfigurationExporter.php @@ -17,11 +17,11 @@ class ConfigurationExporter extends Exporter return [ ExportColumn::make('no') - ->label('NO') - ->state(function ($record) use (&$rowNumber) { - // Increment and return the row number - return ++$rowNumber; - }), + ->label('NO') + ->state(function ($record) use (&$rowNumber) { + // Increment and return the row number + return ++$rowNumber; + }), ExportColumn::make('plant.code') ->label('PLANT'), ExportColumn::make('line.name') @@ -46,10 +46,10 @@ class ConfigurationExporter extends Exporter public static function getCompletedNotificationBody(Export $export): string { - $body = 'Your configuration export has completed and ' . number_format($export->successful_rows) . ' ' . str('row')->plural($export->successful_rows) . ' exported.'; + $body = 'Your configuration export has completed and '.number_format($export->successful_rows).' '.str('row')->plural($export->successful_rows).' exported.'; if ($failedRowsCount = $export->getFailedRowsCount()) { - $body .= ' ' . number_format($failedRowsCount) . ' ' . str('row')->plural($failedRowsCount) . ' failed to export.'; + $body .= ' '.number_format($failedRowsCount).' '.str('row')->plural($failedRowsCount).' failed to export.'; } return $body; diff --git a/app/Filament/Exports/DeviceMasterExporter.php b/app/Filament/Exports/DeviceMasterExporter.php index f7da31a..7dc7d99 100644 --- a/app/Filament/Exports/DeviceMasterExporter.php +++ b/app/Filament/Exports/DeviceMasterExporter.php @@ -14,6 +14,7 @@ class DeviceMasterExporter extends Exporter public static function getColumns(): array { static $rowNumber = 0; + return [ ExportColumn::make('no') ->label('NO') @@ -21,32 +22,32 @@ class DeviceMasterExporter extends Exporter // Increment and return the row number return ++$rowNumber; }), - ExportColumn::make('plant.name') - ->label('PLANT'), + ExportColumn::make('plant.code') + ->label('PLANT CODE'), ExportColumn::make('name') - ->label('DEVICE NAME'), + ->label('DEVICE NAME'), ExportColumn::make('mac_address') - ->label('MAC ADDRESS'), + ->label('MAC ADDRESS'), ExportColumn::make('ip_address') - ->label('IP ADDRESS'), + ->label('IP ADDRESS'), ExportColumn::make('created_at') - ->label('CREATED AT'), + ->label('CREATED AT'), ExportColumn::make('updated_at') - ->label('UPDATED AT'), + ->label('UPDATED AT'), ExportColumn::make('deleted_at') - ->enabledByDefault(false) - ->label('DELETED AT'), + ->enabledByDefault(false) + ->label('DELETED AT'), ExportColumn::make('created_by') - ->label('CREATED BY'), + ->label('CREATED BY'), ]; } public static function getCompletedNotificationBody(Export $export): string { - $body = 'Your device master export has completed and ' . number_format($export->successful_rows) . ' ' . str('row')->plural($export->successful_rows) . ' exported.'; + $body = 'Your device master export has completed and '.number_format($export->successful_rows).' '.str('row')->plural($export->successful_rows).' exported.'; if ($failedRowsCount = $export->getFailedRowsCount()) { - $body .= ' ' . number_format($failedRowsCount) . ' ' . str('row')->plural($failedRowsCount) . ' failed to export.'; + $body .= ' '.number_format($failedRowsCount).' '.str('row')->plural($failedRowsCount).' failed to export.'; } return $body; diff --git a/app/Filament/Exports/EbReadingExporter.php b/app/Filament/Exports/EbReadingExporter.php index 0519430..f294314 100644 --- a/app/Filament/Exports/EbReadingExporter.php +++ b/app/Filament/Exports/EbReadingExporter.php @@ -10,116 +10,118 @@ use Filament\Actions\Exports\Models\Export; class EbReadingExporter extends Exporter { protected static ?string $model = EbReading::class; - static $rowNumber = 0; + + public static $rowNumber = 0; + public static function getColumns(): array { return [ - ExportColumn::make('no') + ExportColumn::make('no') ->label('NO') ->state(function ($record) use (&$rowNumber) { // Increment and return the row number return ++$rowNumber; }), - ExportColumn::make('plant.name') - ->label('PLANT'), + ExportColumn::make('plant.code') + ->label('PLANT CODE'), ExportColumn::make('lcd_segment_check') - ->label('LCD SEGMENT CHECK'), + ->label('LCD SEGMENT CHECK'), ExportColumn::make('meter_serial_no') - ->label('METER SERIAL NO'), + ->label('METER SERIAL NO'), ExportColumn::make('eb_date_time') - ->label('EB DATE TIME'), + ->label('EB DATE TIME'), ExportColumn::make('ph_seq_of_volt') - ->label('PH SEQ OF VOLT'), + ->label('PH SEQ OF VOLT'), ExportColumn::make('ph_assoc_conn_check') - ->label('PH ASSOC CONN CHECK'), + ->label('PH ASSOC CONN CHECK'), ExportColumn::make('instantaneous_ph_volt') - ->label('INSTANTANEOUS PH VOLT'), + ->label('INSTANTANEOUS PH VOLT'), ExportColumn::make('instantaneous_curr') - ->label('INSTANTANEOUS CURR'), + ->label('INSTANTANEOUS CURR'), ExportColumn::make('instantaneous_freq') - ->label('INSTANTANEOUS FREQ'), + ->label('INSTANTANEOUS FREQ'), ExportColumn::make('instantaneous_kw_with_sign') - ->label('INSTANTANEOUS KW WITH SIGN'), + ->label('INSTANTANEOUS KW WITH SIGN'), ExportColumn::make('instantaneous_kva') - ->label('INSTANTANEOUS KVA'), + ->label('INSTANTANEOUS KVA'), ExportColumn::make('instantaneous_kv_ar') - ->label('INSTANTANEOUS KV AR'), + ->label('INSTANTANEOUS KV AR'), ExportColumn::make('instantaneous_pf_with_sign') - ->label('INSTANTANEOUS PF WITH SIGN'), + ->label('INSTANTANEOUS PF WITH SIGN'), ExportColumn::make('rd_with_elapsed_time_kva') - ->label('RD WITH ELAPSED TIME KVA'), + ->label('RD WITH ELAPSED TIME KVA'), ExportColumn::make('cum_active_import_energy') - ->label('CUM ACTIVE IMPORT ENERGY'), + ->label('CUM ACTIVE IMPORT ENERGY'), ExportColumn::make('tod1_active_energy_6_9') - ->label('TOD1 ACTIVE ENERGY 6-9'), + ->label('TOD1 ACTIVE ENERGY 6-9'), ExportColumn::make('tod2_active_energy_18_21') - ->label('TOD2 ACTIVE ENERGY 18-21'), + ->label('TOD2 ACTIVE ENERGY 18-21'), ExportColumn::make('tod3_active_energy_21_22') - ->label('TOD3 ACTIVE ENERGY 21-22'), + ->label('TOD3 ACTIVE ENERGY 21-22'), ExportColumn::make('tod4_active_energy_5_6_9_18') - ->label('TOD4 ACTIVE ENERGY 5-6-9-18'), + ->label('TOD4 ACTIVE ENERGY 5-6-9-18'), ExportColumn::make('tod5_active_energy_22_5') - ->label('TOD5 ACTIVE ENERGY 22-5'), + ->label('TOD5 ACTIVE ENERGY 22-5'), ExportColumn::make('cum_reac_lag_energy') - ->label('CUM REAC LAG ENERGY'), + ->label('CUM REAC LAG ENERGY'), ExportColumn::make('cum_reac_lead_energy') - ->label('CUM REAC LEAD ENERGY'), + ->label('CUM REAC LEAD ENERGY'), ExportColumn::make('cum_appar_energy') - ->label('CUM APPAR ENERGY'), + ->label('CUM APPAR ENERGY'), ExportColumn::make('tod1_appar_energy_6_9') - ->label('TOD1 APPAR ENERGY 6-9'), + ->label('TOD1 APPAR ENERGY 6-9'), ExportColumn::make('tod2_appar_energy_18_21') - ->label('TOD2 APPAR ENERGY 18-21'), + ->label('TOD2 APPAR ENERGY 18-21'), ExportColumn::make('tod3_appar_energy_21_22') - ->label('TOD3 APPAR ENERGY 21-22'), + ->label('TOD3 APPAR ENERGY 21-22'), ExportColumn::make('tod4_appar_energy_5_6_9_18') - ->label('TOD4 APPAR ENERGY 5-6-9-18'), + ->label('TOD4 APPAR ENERGY 5-6-9-18'), ExportColumn::make('tod5_appar_energy_22_5') - ->label('TOD5 APPAR ENERGY 22-5'), + ->label('TOD5 APPAR ENERGY 22-5'), ExportColumn::make('avg_pow_factor') - ->label('AVG POW FACTOR'), + ->label('AVG POW FACTOR'), ExportColumn::make('avg_freq_15min_last_ip') - ->label('AVG FREQ 15MIN LAST IP'), + ->label('AVG FREQ 15MIN LAST IP'), ExportColumn::make('net_kv_arh_high') - ->label('NET KV ARH HIGH'), + ->label('NET KV ARH HIGH'), ExportColumn::make('net_kv_arh_low') - ->label('NET KV ARH LOW'), + ->label('NET KV ARH LOW'), ExportColumn::make('cum_md_kva') - ->label('CUM MD KVA'), + ->label('CUM MD KVA'), ExportColumn::make('present_md_kva') - ->label('PRESENT MD KVA'), + ->label('PRESENT MD KVA'), ExportColumn::make('present_md_kva_date_time') - ->label('PRESENT MD KVA DATE TIME'), + ->label('PRESENT MD KVA DATE TIME'), ExportColumn::make('tod1_md_kva_6_9') - ->label('TOD1 MD KVA 6-9'), + ->label('TOD1 MD KVA 6-9'), ExportColumn::make('tod2_md_kva_18_21') - ->label('TOD2 MD KVA 18-21'), + ->label('TOD2 MD KVA 18-21'), ExportColumn::make('tod3_md_kva_21_22') - ->label('TOD3 MD KVA 21-22'), + ->label('TOD3 MD KVA 21-22'), ExportColumn::make('tod4_md_kva_5_6_9_18') - ->label('TOD4 MD KVA 5-6-9-18'), + ->label('TOD4 MD KVA 5-6-9-18'), ExportColumn::make('tod5_md_kva_22_5') - ->label('TOD5 MD KVA 22-5'), + ->label('TOD5 MD KVA 22-5'), ExportColumn::make('total_pow_off_hours') - ->label('TOTAL POW OFF HOURS'), + ->label('TOTAL POW OFF HOURS'), ExportColumn::make('programming_count') - ->label('PROGRAMMING COUNT'), + ->label('PROGRAMMING COUNT'), ExportColumn::make('last_occ_res_event_type') - ->label('LAST OCC RES EVENT TYPE'), + ->label('LAST OCC RES EVENT TYPE'), ExportColumn::make('last_occ_res_event_date_time') - ->label('LAST OCC RES EVENT DATE TIME'), + ->label('LAST OCC RES EVENT DATE TIME'), ExportColumn::make('tamper_count') - ->label('TAMPER COUNT'), + ->label('TAMPER COUNT'), ExportColumn::make('reset_count') - ->label('RESET COUNT'), + ->label('RESET COUNT'), ExportColumn::make('last_md_reset_date_time') - ->label('LAST MD RESET DATE TIME'), + ->label('LAST MD RESET DATE TIME'), ExportColumn::make('electrician_sign') - ->label('ELECTRICIAN SIGN'), + ->label('ELECTRICIAN SIGN'), ExportColumn::make('created_at') - ->label('CREATED AT'), + ->label('CREATED AT'), ExportColumn::make('updated_at') - ->label('UPDATED AT'), + ->label('UPDATED AT'), ExportColumn::make('deleted_at') ->enabledByDefault(false), ExportColumn::make('updated_by') @@ -129,10 +131,10 @@ class EbReadingExporter extends Exporter public static function getCompletedNotificationBody(Export $export): string { - $body = 'Your eb reading export has completed and ' . number_format($export->successful_rows) . ' ' . str('row')->plural($export->successful_rows) . ' exported.'; + $body = 'Your eb reading export has completed and '.number_format($export->successful_rows).' '.str('row')->plural($export->successful_rows).' exported.'; if ($failedRowsCount = $export->getFailedRowsCount()) { - $body .= ' ' . number_format($failedRowsCount) . ' ' . str('row')->plural($failedRowsCount) . ' failed to export.'; + $body .= ' '.number_format($failedRowsCount).' '.str('row')->plural($failedRowsCount).' failed to export.'; } return $body; diff --git a/app/Filament/Exports/EquipmentMasterExporter.php b/app/Filament/Exports/EquipmentMasterExporter.php index c5783ea..408a044 100644 --- a/app/Filament/Exports/EquipmentMasterExporter.php +++ b/app/Filament/Exports/EquipmentMasterExporter.php @@ -14,59 +14,60 @@ class EquipmentMasterExporter extends Exporter public static function getColumns(): array { static $rowNumber = 0; + return [ - ExportColumn::make('no') + ExportColumn::make('no') ->label('NO') ->state(function ($record) use (&$rowNumber) { // Increment and return the row number return ++$rowNumber; }), - ExportColumn::make('plant.name') - ->label('PLANT'), + ExportColumn::make('plant.code') + ->label('PLANT CODE'), ExportColumn::make('machine.name') - ->label('MACHINE NAME'), + ->label('MACHINE NAME'), ExportColumn::make('name') - ->label('NAME'), + ->label('NAME'), ExportColumn::make('description') - ->label('DESCRIPTION'), + ->label('DESCRIPTION'), ExportColumn::make('make') - ->label('MAKE'), + ->label('MAKE'), ExportColumn::make('model') - ->label('MODEL'), + ->label('MODEL'), ExportColumn::make('equipment_number') - ->label('EQUIPMENT NUMBER'), + ->label('EQUIPMENT NUMBER'), ExportColumn::make('instrument_serial_number') - ->label('INSTRUMENT SERIAL NUMBER'), + ->label('INSTRUMENT SERIAL NUMBER'), ExportColumn::make('calibrated_on') - ->label('CALIBRATED ON'), + ->label('CALIBRATED ON'), ExportColumn::make('frequency') - ->label('FREQUENCY'), + ->label('FREQUENCY'), ExportColumn::make('next_calibration_date') - ->label('NEXT CALIBRATION DATE'), + ->label('NEXT CALIBRATION DATE'), ExportColumn::make('calibrated_by') - ->label('CALIBRATED BY'), + ->label('CALIBRATED BY'), ExportColumn::make('calibration_certificate') - ->label('CALIBRATION CERTIFICATE'), + ->label('CALIBRATION CERTIFICATE'), ExportColumn::make('created_at') - ->label('CREATED AT'), + ->label('CREATED AT'), ExportColumn::make('updated_at') - ->label('UPDATED AT'), + ->label('UPDATED AT'), ExportColumn::make('created_by') - ->label('CREATED BY'), + ->label('CREATED BY'), ExportColumn::make('updated_by') - ->label('UPDATED BY'), + ->label('UPDATED BY'), ExportColumn::make('deleted_at') - ->label('DELETED AT') - ->enabledByDefault(false), + ->label('DELETED AT') + ->enabledByDefault(false), ]; } public static function getCompletedNotificationBody(Export $export): string { - $body = 'Your equipment master export has completed and ' . number_format($export->successful_rows) . ' ' . str('row')->plural($export->successful_rows) . ' exported.'; + $body = 'Your equipment master export has completed and '.number_format($export->successful_rows).' '.str('row')->plural($export->successful_rows).' exported.'; if ($failedRowsCount = $export->getFailedRowsCount()) { - $body .= ' ' . number_format($failedRowsCount) . ' ' . str('row')->plural($failedRowsCount) . ' failed to export.'; + $body .= ' '.number_format($failedRowsCount).' '.str('row')->plural($failedRowsCount).' failed to export.'; } return $body; diff --git a/app/Filament/Exports/GrMasterExporter.php b/app/Filament/Exports/GrMasterExporter.php index 9c6c417..88be4a2 100644 --- a/app/Filament/Exports/GrMasterExporter.php +++ b/app/Filament/Exports/GrMasterExporter.php @@ -14,6 +14,7 @@ class GrMasterExporter extends Exporter public static function getColumns(): array { static $rowNumber = 0; + return [ ExportColumn::make('no') ->label('NO') @@ -21,36 +22,36 @@ class GrMasterExporter extends Exporter // Increment and return the row number return ++$rowNumber; }), - ExportColumn::make('plant.name') - ->label('PLANT'), + ExportColumn::make('plant.code') + ->label('PLANT CODE'), ExportColumn::make('item.code') - ->label('ITEM'), + ->label('ITEM CODE'), ExportColumn::make('serial_number') - ->label('SERIAL NUMBER'), + ->label('SERIAL NUMBER'), ExportColumn::make('gr_number') - ->label('GR NUMBER'), + ->label('GR NUMBER'), ExportColumn::make('status') - ->label('STATUS'), + ->label('STATUS'), ExportColumn::make('created_at') - ->label('CREATED AT'), + ->label('CREATED AT'), ExportColumn::make('updated_at') - ->label('UPDATED AT'), + ->label('UPDATED AT'), ExportColumn::make('created_by') - ->label('CREATED BY'), + ->label('CREATED BY'), ExportColumn::make('updated_by') - ->label('UPDATED BY'), + ->label('UPDATED BY'), ExportColumn::make('deleted_at') - ->label('DELETED AT') - ->enabledByDefault(false), + ->label('DELETED AT') + ->enabledByDefault(false), ]; } public static function getCompletedNotificationBody(Export $export): string { - $body = 'Your gr master export has completed and ' . number_format($export->successful_rows) . ' ' . str('row')->plural($export->successful_rows) . ' exported.'; + $body = 'Your gr master export has completed and '.number_format($export->successful_rows).' '.str('row')->plural($export->successful_rows).' exported.'; if ($failedRowsCount = $export->getFailedRowsCount()) { - $body .= ' ' . number_format($failedRowsCount) . ' ' . str('row')->plural($failedRowsCount) . ' failed to export.'; + $body .= ' '.number_format($failedRowsCount).' '.str('row')->plural($failedRowsCount).' failed to export.'; } return $body; diff --git a/app/Filament/Exports/GuardNameExporter.php b/app/Filament/Exports/GuardNameExporter.php index 5337331..e03ac25 100644 --- a/app/Filament/Exports/GuardNameExporter.php +++ b/app/Filament/Exports/GuardNameExporter.php @@ -24,8 +24,8 @@ class GuardNameExporter extends Exporter // Increment and return the row number return ++$rowNumber; }), - ExportColumn::make('plant.name') - ->label('PLANT'), + ExportColumn::make('plant.code') + ->label('PLANT CODE'), ExportColumn::make('name') ->label('GUARD NAME'), ExportColumn::make('identification1') @@ -46,10 +46,10 @@ class GuardNameExporter extends Exporter public static function getCompletedNotificationBody(Export $export): string { - $body = 'Your guard name export has completed and ' . number_format($export->successful_rows) . ' ' . str('row')->plural($export->successful_rows) . ' exported.'; + $body = 'Your guard name export has completed and '.number_format($export->successful_rows).' '.str('row')->plural($export->successful_rows).' exported.'; if ($failedRowsCount = $export->getFailedRowsCount()) { - $body .= ' ' . number_format($failedRowsCount) . ' ' . str('row')->plural($failedRowsCount) . ' failed to export.'; + $body .= ' '.number_format($failedRowsCount).' '.str('row')->plural($failedRowsCount).' failed to export.'; } return $body; diff --git a/app/Filament/Exports/GuardPatrolEntryExporter.php b/app/Filament/Exports/GuardPatrolEntryExporter.php index cb26e48..95e5eb9 100644 --- a/app/Filament/Exports/GuardPatrolEntryExporter.php +++ b/app/Filament/Exports/GuardPatrolEntryExporter.php @@ -24,8 +24,8 @@ class GuardPatrolEntryExporter extends Exporter }), // ExportColumn::make('id') // ->label('ID'), - ExportColumn::make('plant.name') - ->label('PLANT'), + ExportColumn::make('plant.code') + ->label('PLANT CODE'), ExportColumn::make('guardNames.name') ->label('GUARD NAME'), ExportColumn::make('checkPointNames.name') @@ -54,10 +54,10 @@ class GuardPatrolEntryExporter extends Exporter public static function getCompletedNotificationBody(Export $export): string { - $body = 'Your guard patrol entry export has completed and ' . number_format($export->successful_rows) . ' ' . str('row')->plural($export->successful_rows) . ' exported.'; + $body = 'Your guard patrol entry export has completed and '.number_format($export->successful_rows).' '.str('row')->plural($export->successful_rows).' exported.'; if ($failedRowsCount = $export->getFailedRowsCount()) { - $body .= ' ' . number_format($failedRowsCount) . ' ' . str('row')->plural($failedRowsCount) . ' failed to export.'; + $body .= ' '.number_format($failedRowsCount).' '.str('row')->plural($failedRowsCount).' failed to export.'; } return $body; diff --git a/app/Filament/Exports/LineExporter.php b/app/Filament/Exports/LineExporter.php index ceca456..045fadc 100644 --- a/app/Filament/Exports/LineExporter.php +++ b/app/Filament/Exports/LineExporter.php @@ -24,12 +24,12 @@ class LineExporter extends Exporter // Increment and return the row number return ++$rowNumber; }), - ExportColumn::make('plant.name') - ->label('PLANT'), + ExportColumn::make('plant.code') + ->label('PLANT CODE'), ExportColumn::make('name') - ->label('NAME'), + ->label('LINE NAME'), ExportColumn::make('type') - ->label('TYPE'), + ->label('LINE TYPE'), ExportColumn::make('no_of_operation') ->label('NO OF OPERATION'), ExportColumn::make('workGroup1.name') @@ -84,10 +84,10 @@ class LineExporter extends Exporter public static function getCompletedNotificationBody(Export $export): string { - $body = 'Your line export has completed and ' . number_format($export->successful_rows) . ' ' . str('row')->plural($export->successful_rows) . ' exported.'; + $body = 'Your line export has completed and '.number_format($export->successful_rows).' '.str('row')->plural($export->successful_rows).' exported.'; if ($failedRowsCount = $export->getFailedRowsCount()) { - $body .= ' ' . number_format($failedRowsCount) . ' ' . str('row')->plural($failedRowsCount) . ' failed to export.'; + $body .= ' '.number_format($failedRowsCount).' '.str('row')->plural($failedRowsCount).' failed to export.'; } return $body; diff --git a/app/Filament/Exports/MachineExporter.php b/app/Filament/Exports/MachineExporter.php index 9c32526..7541ba1 100644 --- a/app/Filament/Exports/MachineExporter.php +++ b/app/Filament/Exports/MachineExporter.php @@ -22,12 +22,12 @@ class MachineExporter extends Exporter // Increment and return the row number return ++$rowNumber; }), - ExportColumn::make('plant.name') - ->label('PLANT'), + ExportColumn::make('plant.code') + ->label('PLANT CODE'), ExportColumn::make('line.name') - ->label('LINE'), + ->label('LINE NAME'), ExportColumn::make('name') - ->label('MACHINE'), + ->label('MACHINE NAME'), ExportColumn::make('work_center') ->label('WORK CENTER'), ExportColumn::make('workGroupMaster.name') @@ -44,10 +44,10 @@ class MachineExporter extends Exporter public static function getCompletedNotificationBody(Export $export): string { - $body = 'Your machine export has completed and ' . number_format($export->successful_rows) . ' ' . str('row')->plural($export->successful_rows) . ' exported.'; + $body = 'Your machine export has completed and '.number_format($export->successful_rows).' '.str('row')->plural($export->successful_rows).' exported.'; if ($failedRowsCount = $export->getFailedRowsCount()) { - $body .= ' ' . number_format($failedRowsCount) . ' ' . str('row')->plural($failedRowsCount) . ' failed to export.'; + $body .= ' '.number_format($failedRowsCount).' '.str('row')->plural($failedRowsCount).' failed to export.'; } return $body; diff --git a/app/Filament/Exports/MfmMeterExporter.php b/app/Filament/Exports/MfmMeterExporter.php index c7366be..9d83256 100644 --- a/app/Filament/Exports/MfmMeterExporter.php +++ b/app/Filament/Exports/MfmMeterExporter.php @@ -14,39 +14,40 @@ class MfmMeterExporter extends Exporter public static function getColumns(): array { static $rowNumber = 0; + return [ ExportColumn::make('no') - ->label('NO') - ->state(function ($record) use (&$rowNumber) { - // Increment and return the row number - return ++$rowNumber; - }), - ExportColumn::make('plant.name') - ->label('PLANT'), + ->label('NO') + ->state(function ($record) use (&$rowNumber) { + // Increment and return the row number + return ++$rowNumber; + }), + ExportColumn::make('plant.code') + ->label('PLANT CODE'), ExportColumn::make('device.name') - ->label('DEVICE NAME'), + ->label('DEVICE NAME'), ExportColumn::make('sequence') - ->label('SEQUENCE'), + ->label('SEQUENCE'), ExportColumn::make('name') - ->label('NAME'), + ->label('METER NAME'), ExportColumn::make('created_at') - ->label('CREATED AT'), + ->label('CREATED AT'), ExportColumn::make('updated_at') - ->label('UPDATED AT'), + ->label('UPDATED AT'), ExportColumn::make('deleted_at') - ->label('DELETED AT') - ->enabledByDefault(false), + ->label('DELETED AT') + ->enabledByDefault(false), ExportColumn::make('created_by') - ->label('CREATED BY'), + ->label('CREATED BY'), ]; } public static function getCompletedNotificationBody(Export $export): string { - $body = 'Your mfm meter export has completed and ' . number_format($export->successful_rows) . ' ' . str('row')->plural($export->successful_rows) . ' exported.'; + $body = 'Your mfm meter export has completed and '.number_format($export->successful_rows).' '.str('row')->plural($export->successful_rows).' exported.'; if ($failedRowsCount = $export->getFailedRowsCount()) { - $body .= ' ' . number_format($failedRowsCount) . ' ' . str('row')->plural($failedRowsCount) . ' failed to export.'; + $body .= ' '.number_format($failedRowsCount).' '.str('row')->plural($failedRowsCount).' failed to export.'; } return $body; diff --git a/app/Filament/Exports/MfmParameterExporter.php b/app/Filament/Exports/MfmParameterExporter.php index b6e07f3..fd28873 100644 --- a/app/Filament/Exports/MfmParameterExporter.php +++ b/app/Filament/Exports/MfmParameterExporter.php @@ -14,48 +14,49 @@ class MfmParameterExporter extends Exporter public static function getColumns(): array { static $rowNumber = 0; + return [ ExportColumn::make('no') - ->label('NO') - ->state(function ($record) use (&$rowNumber) { - // Increment and return the row number - return ++$rowNumber; - }), - ExportColumn::make('plant.name') - ->label('PLANT'), + ->label('NO') + ->state(function ($record) use (&$rowNumber) { + // Increment and return the row number + return ++$rowNumber; + }), + ExportColumn::make('plant.code') + ->label('PLANT CODE'), ExportColumn::make('deviceName.name') - ->label('Device Name'), + ->label('Device Name'), ExportColumn::make('name') - ->label('NAME'), + ->label('PARAMETER NAME'), ExportColumn::make('mfmMeter.name') - ->label('MFM METER'), + ->label('MFM METER'), ExportColumn::make('register_id') - ->label('REGISTER ID'), + ->label('REGISTER ID'), ExportColumn::make('identifier') - ->label('IDENTIFIER'), + ->label('IDENTIFIER'), ExportColumn::make('byte_to_convert') - ->label('BYTE TO CONVERT'), + ->label('BYTE TO CONVERT'), ExportColumn::make('type_to_convert') - ->label('TYPE TO CONVERT'), + ->label('TYPE TO CONVERT'), ExportColumn::make('decimal_to_display') - ->label('DECIMAL TO DISPLAY'), + ->label('DECIMAL TO DISPLAY'), ExportColumn::make('created_at') - ->label('CREATED AT'), + ->label('CREATED AT'), ExportColumn::make('updated_at') - ->label('UPDATED AT'), + ->label('UPDATED AT'), ExportColumn::make('deleted_at') - ->label('DELETED AT') - ->enabledByDefault(false), + ->label('DELETED AT') + ->enabledByDefault(false), ]; } public static function getCompletedNotificationBody(Export $export): string { - $body = 'Your mfm parameter export has completed and ' . number_format($export->successful_rows) . ' ' . str('row')->plural($export->successful_rows) . ' exported.'; + $body = 'Your mfm parameter export has completed and '.number_format($export->successful_rows).' '.str('row')->plural($export->successful_rows).' exported.'; if ($failedRowsCount = $export->getFailedRowsCount()) { - $body .= ' ' . number_format($failedRowsCount) . ' ' . str('row')->plural($failedRowsCount) . ' failed to export.'; + $body .= ' '.number_format($failedRowsCount).' '.str('row')->plural($failedRowsCount).' failed to export.'; } return $body; diff --git a/app/Filament/Exports/MotorTestingMasterExporter.php b/app/Filament/Exports/MotorTestingMasterExporter.php index c4914b2..6b22a9e 100644 --- a/app/Filament/Exports/MotorTestingMasterExporter.php +++ b/app/Filament/Exports/MotorTestingMasterExporter.php @@ -17,13 +17,13 @@ class MotorTestingMasterExporter extends Exporter return [ ExportColumn::make('no') - ->label('NO') - ->state(function ($record) use (&$rowNumber) { - // Increment and return the row number - return ++$rowNumber; - }), + ->label('NO') + ->state(function ($record) use (&$rowNumber) { + // Increment and return the row number + return ++$rowNumber; + }), ExportColumn::make('plant.code') - ->label('PLANT'), + ->label('PLANT CODE'), ExportColumn::make('item.category') ->label('CATEGORY'), ExportColumn::make('item.code') @@ -106,10 +106,10 @@ class MotorTestingMasterExporter extends Exporter public static function getCompletedNotificationBody(Export $export): string { - $body = 'Your motor testing master export has completed and ' . number_format($export->successful_rows) . ' ' . str('row')->plural($export->successful_rows) . ' exported.'; + $body = 'Your motor testing master export has completed and '.number_format($export->successful_rows).' '.str('row')->plural($export->successful_rows).' exported.'; if ($failedRowsCount = $export->getFailedRowsCount()) { - $body .= ' ' . number_format($failedRowsCount) . ' ' . str('row')->plural($failedRowsCount) . ' failed to export.'; + $body .= ' '.number_format($failedRowsCount).' '.str('row')->plural($failedRowsCount).' failed to export.'; } return $body; diff --git a/app/Filament/Exports/ProductionLineStopExporter.php b/app/Filament/Exports/ProductionLineStopExporter.php index 3cd7107..04a7dc7 100644 --- a/app/Filament/Exports/ProductionLineStopExporter.php +++ b/app/Filament/Exports/ProductionLineStopExporter.php @@ -37,13 +37,13 @@ class ProductionLineStopExporter extends Exporter ExportColumn::make('stop_min') ->label('STOP MINUTE'), ExportColumn::make('line.name') - ->label('LINE'), + ->label('LINE NAME'), ExportColumn::make('shift.block.name') - ->label('BLOCK'), + ->label('BLOCK NAME'), ExportColumn::make('shift.name') - ->label('SHIFT'), - ExportColumn::make('plant.name') - ->label('PLANT'), + ->label('SHIFT NAME'), + ExportColumn::make('plant.code') + ->label('PLANT CODE'), ExportColumn::make('operator_id') ->label('OPERATOR ID'), ExportColumn::make('created_at') @@ -58,10 +58,10 @@ class ProductionLineStopExporter extends Exporter public static function getCompletedNotificationBody(Export $export): string { - $body = 'Your production line stop export has completed and ' . number_format($export->successful_rows) . ' ' . str('row')->plural($export->successful_rows) . ' exported.'; + $body = 'Your production line stop export has completed and '.number_format($export->successful_rows).' '.str('row')->plural($export->successful_rows).' exported.'; if ($failedRowsCount = $export->getFailedRowsCount()) { - $body .= ' ' . number_format($failedRowsCount) . ' ' . str('row')->plural($failedRowsCount) . ' failed to export.'; + $body .= ' '.number_format($failedRowsCount).' '.str('row')->plural($failedRowsCount).' failed to export.'; } return $body; diff --git a/app/Filament/Exports/ProductionPlanExporter.php b/app/Filament/Exports/ProductionPlanExporter.php index 2f9437f..2b79f07 100644 --- a/app/Filament/Exports/ProductionPlanExporter.php +++ b/app/Filament/Exports/ProductionPlanExporter.php @@ -29,13 +29,13 @@ class ProductionPlanExporter extends Exporter ExportColumn::make('production_quantity') ->label('PRODUCTION QUANTITY'), ExportColumn::make('line.name') - ->label('LINE'), + ->label('LINE NAME'), ExportColumn::make('shift.block.name') - ->label('BLOCK'), + ->label('BLOCK NAME'), ExportColumn::make('shift.name') - ->label('SHIFT'), - ExportColumn::make('plant.name') - ->label('PLANT'), + ->label('SHIFT NAME'), + ExportColumn::make('plant.code') + ->label('PLANT CODE'), ExportColumn::make('operator_id') ->label('OPERATOR ID'), ExportColumn::make('created_at') @@ -50,10 +50,10 @@ class ProductionPlanExporter extends Exporter public static function getCompletedNotificationBody(Export $export): string { - $body = 'Your production plan export has completed and ' . number_format($export->successful_rows) . ' ' . str('row')->plural($export->successful_rows) . ' exported.'; + $body = 'Your production plan export has completed and '.number_format($export->successful_rows).' '.str('row')->plural($export->successful_rows).' exported.'; if ($failedRowsCount = $export->getFailedRowsCount()) { - $body .= ' ' . number_format($failedRowsCount) . ' ' . str('row')->plural($failedRowsCount) . ' failed to export.'; + $body .= ' '.number_format($failedRowsCount).' '.str('row')->plural($failedRowsCount).' failed to export.'; } return $body; diff --git a/app/Filament/Exports/ProductionQuantityExporter.php b/app/Filament/Exports/ProductionQuantityExporter.php index cad95ab..eabffe8 100644 --- a/app/Filament/Exports/ProductionQuantityExporter.php +++ b/app/Filament/Exports/ProductionQuantityExporter.php @@ -33,13 +33,13 @@ class ProductionQuantityExporter extends Exporter ExportColumn::make('item.uom') ->label('UNIT OF MEASURE'), ExportColumn::make('line.name') - ->label('LINE'), + ->label('LINE NAME'), ExportColumn::make('shift.block.name') - ->label('BLOCK'), + ->label('BLOCK NAME'), ExportColumn::make('shift.name') - ->label('SHIFT'), - ExportColumn::make('plant.name') - ->label('PLANT'), + ->label('SHIFT NAME'), + ExportColumn::make('plant.code') + ->label('PLANT CODE'), ExportColumn::make('sap_msg_status') ->label('SAP MESSAGE STATUS'), ExportColumn::make('sap_msg_description') @@ -58,10 +58,10 @@ class ProductionQuantityExporter extends Exporter public static function getCompletedNotificationBody(Export $export): string { - $body = 'Your production quantity export has completed and ' . number_format($export->successful_rows) . ' ' . str('row')->plural($export->successful_rows) . ' exported.'; + $body = 'Your production quantity export has completed and '.number_format($export->successful_rows).' '.str('row')->plural($export->successful_rows).' exported.'; if ($failedRowsCount = $export->getFailedRowsCount()) { - $body .= ' ' . number_format($failedRowsCount) . ' ' . str('row')->plural($failedRowsCount) . ' failed to export.'; + $body .= ' '.number_format($failedRowsCount).' '.str('row')->plural($failedRowsCount).' failed to export.'; } return $body; diff --git a/app/Filament/Exports/QualityValidationExporter.php b/app/Filament/Exports/QualityValidationExporter.php index 7137efa..7d8f995 100644 --- a/app/Filament/Exports/QualityValidationExporter.php +++ b/app/Filament/Exports/QualityValidationExporter.php @@ -24,10 +24,10 @@ class QualityValidationExporter extends Exporter // Increment and return the row number return ++$rowNumber; }), - ExportColumn::make('plant.name') - ->label('PLANT'), + ExportColumn::make('plant.code') + ->label('PLANT CODE'), ExportColumn::make('line.name') - ->label('LINE'), + ->label('LINE NAME'), ExportColumn::make('production_order') ->label('PRODUCTION ORDER'), ExportColumn::make('serial_number') @@ -54,14 +54,14 @@ class QualityValidationExporter extends Exporter ->label('NAME PLATE PUMP'), ExportColumn::make('name_plate_pumpset') ->label('NAME PLATE PUMPSET'), + ExportColumn::make('warranty_card') + ->label('WARRANTY CARD'), ExportColumn::make('tube_sticker_motor') ->label('TUBE STICKER MOTOR'), ExportColumn::make('tube_sticker_pump') ->label('TUBE STICKER PUMP'), ExportColumn::make('tube_sticker_pumpset') ->label('TUBE STICKER PUMPSET'), - ExportColumn::make('warranty_card') - ->label('WARRANTY CARD'), ExportColumn::make('part_validation1') ->label('PART VALIDATION 1'), ExportColumn::make('part_validation2') @@ -90,10 +90,10 @@ class QualityValidationExporter extends Exporter public static function getCompletedNotificationBody(Export $export): string { - $body = 'Your quality validation export has completed and ' . number_format($export->successful_rows) . ' ' . str('row')->plural($export->successful_rows) . ' exported.'; + $body = 'Your quality validation export has completed and '.number_format($export->successful_rows).' '.str('row')->plural($export->successful_rows).' exported.'; if ($failedRowsCount = $export->getFailedRowsCount()) { - $body .= ' ' . number_format($failedRowsCount) . ' ' . str('row')->plural($failedRowsCount) . ' failed to export.'; + $body .= ' '.number_format($failedRowsCount).' '.str('row')->plural($failedRowsCount).' failed to export.'; } return $body; diff --git a/app/Filament/Exports/SerialValidationExporter.php b/app/Filament/Exports/SerialValidationExporter.php index 07d9f94..8e349f8 100644 --- a/app/Filament/Exports/SerialValidationExporter.php +++ b/app/Filament/Exports/SerialValidationExporter.php @@ -14,15 +14,16 @@ class SerialValidationExporter extends Exporter public static function getColumns(): array { static $rowNumber = 0; + return [ - ExportColumn::make('no') + ExportColumn::make('no') ->label('NO') ->state(function ($record) use (&$rowNumber) { // Increment and return the row number return ++$rowNumber; }), - ExportColumn::make('plant.name') - ->label('PLANT'), + ExportColumn::make('plant.code') + ->label('PLANT CODE'), ExportColumn::make('invoice_number') ->label('INVOICE NUMBER'), ExportColumn::make('serial_number') @@ -55,10 +56,10 @@ class SerialValidationExporter extends Exporter ->label('OPERATOR ID'), ExportColumn::make('created_at') ->label('CREATED AT'), - //->dateTimeFormat('d-m-Y H:i:s'), + // ->dateTimeFormat('d-m-Y H:i:s'), ExportColumn::make('updated_at') ->label('UPDATED AT'), - //->dateTimeFormat('d-m-Y H:i:s'), + // ->dateTimeFormat('d-m-Y H:i:s'), ExportColumn::make('deleted_at') ->enabledByDefault(false) ->label('DELETED AT'), @@ -67,10 +68,10 @@ class SerialValidationExporter extends Exporter public static function getCompletedNotificationBody(Export $export): string { - $body = 'Your serial validation export has completed and ' . number_format($export->successful_rows) . ' ' . str('row')->plural($export->successful_rows) . ' exported.'; + $body = 'Your serial validation export has completed and '.number_format($export->successful_rows).' '.str('row')->plural($export->successful_rows).' exported.'; if ($failedRowsCount = $export->getFailedRowsCount()) { - $body .= ' ' . number_format($failedRowsCount) . ' ' . str('row')->plural($failedRowsCount) . ' failed to export.'; + $body .= ' '.number_format($failedRowsCount).' '.str('row')->plural($failedRowsCount).' failed to export.'; } return $body; diff --git a/app/Filament/Exports/ShiftExporter.php b/app/Filament/Exports/ShiftExporter.php index 61f3847..1f4fd8c 100644 --- a/app/Filament/Exports/ShiftExporter.php +++ b/app/Filament/Exports/ShiftExporter.php @@ -25,11 +25,11 @@ class ShiftExporter extends Exporter return ++$rowNumber; }), ExportColumn::make('block.name') - ->label('BLOCK'), - ExportColumn::make('plant.name') - ->label('PLANT'), + ->label('BLOCK NAME'), + ExportColumn::make('plant.code') + ->label('PLANT CODE'), ExportColumn::make('name') - ->label('NAME'), + ->label('SHIFT NAME'), ExportColumn::make('start_time') ->label('START TIME'), ExportColumn::make('duration') @@ -50,10 +50,10 @@ class ShiftExporter extends Exporter public static function getCompletedNotificationBody(Export $export): string { - $body = 'Your shift export has completed and ' . number_format($export->successful_rows) . ' ' . str('row')->plural($export->successful_rows) . ' exported.'; + $body = 'Your shift export has completed and '.number_format($export->successful_rows).' '.str('row')->plural($export->successful_rows).' exported.'; if ($failedRowsCount = $export->getFailedRowsCount()) { - $body .= ' ' . number_format($failedRowsCount) . ' ' . str('row')->plural($failedRowsCount) . ' failed to export.'; + $body .= ' '.number_format($failedRowsCount).' '.str('row')->plural($failedRowsCount).' failed to export.'; } return $body; diff --git a/app/Filament/Exports/TestingPanelReadingExporter.php b/app/Filament/Exports/TestingPanelReadingExporter.php index 761fb35..a14393f 100644 --- a/app/Filament/Exports/TestingPanelReadingExporter.php +++ b/app/Filament/Exports/TestingPanelReadingExporter.php @@ -24,18 +24,18 @@ class TestingPanelReadingExporter extends Exporter // Increment and return the row number return ++$rowNumber; }), - ExportColumn::make('plant.name') - ->label('PLANT'), + ExportColumn::make('plant.code') + ->label('PLANT CODE'), ExportColumn::make('line.name') - ->label('LINE'), + ->label('LINE NAME'), ExportColumn::make('machine.name') - ->label('MACHINE'), + ->label('MACHINE NAME'), ExportColumn::make('motorTestingMaster.item.code') ->label('ITEM CODE'), ExportColumn::make('motorTestingMaster.item.description') - ->label('MODEL'), + ->label('MODEL DESCRIPTION'), ExportColumn::make('output') - ->label('OUTPUT'), + ->label('OUTPUT NAME'), ExportColumn::make('serial_number') ->label('SERIAL NUMBER'), ExportColumn::make('winded_serial_number') @@ -125,7 +125,7 @@ class TestingPanelReadingExporter extends Exporter ExportColumn::make('rework_count') ->label('REWORK COUNT'), ExportColumn::make('update_count') - ->label('UPDATE COUNT'), + ->label('UPDATED COUNT'), ExportColumn::make('output_flag') ->label('OUTPUT FLAG'), ExportColumn::make('tested_by') @@ -146,10 +146,10 @@ class TestingPanelReadingExporter extends Exporter public static function getCompletedNotificationBody(Export $export): string { - $body = 'Your testing panel reading export has completed and ' . number_format($export->successful_rows) . ' ' . str('row')->plural($export->successful_rows) . ' exported.'; + $body = 'Your testing panel reading export has completed and '.number_format($export->successful_rows).' '.str('row')->plural($export->successful_rows).' exported.'; if ($failedRowsCount = $export->getFailedRowsCount()) { - $body .= ' ' . number_format($failedRowsCount) . ' ' . str('row')->plural($failedRowsCount) . ' failed to export.'; + $body .= ' '.number_format($failedRowsCount).' '.str('row')->plural($failedRowsCount).' failed to export.'; } return $body; diff --git a/app/Filament/Exports/WeightValidationExporter.php b/app/Filament/Exports/WeightValidationExporter.php index 53adfdd..2f65337 100644 --- a/app/Filament/Exports/WeightValidationExporter.php +++ b/app/Filament/Exports/WeightValidationExporter.php @@ -24,8 +24,8 @@ class WeightValidationExporter extends Exporter // Increment and return the row number return ++$rowNumber; }), - ExportColumn::make('plant.name') - ->label('PLANT'), + ExportColumn::make('plant.code') + ->label('PLANT CODE'), ExportColumn::make('item.code') ->label('ITEM CODE'), ExportColumn::make('obd_number') @@ -58,10 +58,10 @@ class WeightValidationExporter extends Exporter public static function getCompletedNotificationBody(Export $export): string { - $body = 'Your weight validation export has completed and ' . number_format($export->successful_rows) . ' ' . str('row')->plural($export->successful_rows) . ' exported.'; + $body = 'Your weight validation export has completed and '.number_format($export->successful_rows).' '.str('row')->plural($export->successful_rows).' exported.'; if ($failedRowsCount = $export->getFailedRowsCount()) { - $body .= ' ' . number_format($failedRowsCount) . ' ' . str('row')->plural($failedRowsCount) . ' failed to export.'; + $body .= ' '.number_format($failedRowsCount).' '.str('row')->plural($failedRowsCount).' failed to export.'; } return $body; diff --git a/app/Filament/Exports/WorkGroupMasterExporter.php b/app/Filament/Exports/WorkGroupMasterExporter.php index ef1ff60..053cd2d 100644 --- a/app/Filament/Exports/WorkGroupMasterExporter.php +++ b/app/Filament/Exports/WorkGroupMasterExporter.php @@ -14,6 +14,7 @@ class WorkGroupMasterExporter extends Exporter public static function getColumns(): array { static $rowNumber = 0; + return [ ExportColumn::make('no') ->label('NO') @@ -21,32 +22,32 @@ class WorkGroupMasterExporter extends Exporter // Increment and return the row number return ++$rowNumber; }), - ExportColumn::make('plant.name') - ->label('PLANT'), + ExportColumn::make('plant.code') + ->label('PLANT CODE'), ExportColumn::make('name') - ->label('NAME'), + ->label('WORK GROUP NAME'), ExportColumn::make('description') - ->label('DESCRIPTION'), + ->label('WORK GROUP DESCRIPTION'), ExportColumn::make('operation_number') - ->label('OPERATION NUMBER'), + ->label('OPERATION NUMBER'), ExportColumn::make('created_by') - ->label('CREATED BY'), + ->label('CREATED BY'), ExportColumn::make('created_at') - ->label('CREATED AT'), + ->label('CREATED AT'), ExportColumn::make('updated_at') - ->label('UPDATED AT'), + ->label('UPDATED AT'), ExportColumn::make('deleted_at') - ->label('DELETED AT') - ->enabledByDefault(false), + ->label('DELETED AT') + ->enabledByDefault(false), ]; } public static function getCompletedNotificationBody(Export $export): string { - $body = 'Your work group master export has completed and ' . number_format($export->successful_rows) . ' ' . str('row')->plural($export->successful_rows) . ' exported.'; + $body = 'Your work group master export has completed and '.number_format($export->successful_rows).' '.str('row')->plural($export->successful_rows).' exported.'; if ($failedRowsCount = $export->getFailedRowsCount()) { - $body .= ' ' . number_format($failedRowsCount) . ' ' . str('row')->plural($failedRowsCount) . ' failed to export.'; + $body .= ' '.number_format($failedRowsCount).' '.str('row')->plural($failedRowsCount).' failed to export.'; } return $body; diff --git a/app/Filament/Imports/BlockImporter.php b/app/Filament/Imports/BlockImporter.php index ad0bc98..4e3cc93 100644 --- a/app/Filament/Imports/BlockImporter.php +++ b/app/Filament/Imports/BlockImporter.php @@ -8,7 +8,6 @@ use Filament\Actions\Imports\Exceptions\RowImportFailedException; use Filament\Actions\Imports\ImportColumn; use Filament\Actions\Imports\Importer; use Filament\Actions\Imports\Models\Import; -use Notification; use Str; class BlockImporter extends Importer @@ -20,16 +19,16 @@ class BlockImporter extends Importer return [ ImportColumn::make('name') ->requiredMapping() - ->exampleHeader('Block Name') + ->exampleHeader('BLOCK NAME') ->example('Block A') - ->label('Block Name') + ->label('BLOCK NAME') ->rules(['required']), ImportColumn::make('plant') ->requiredMapping() - ->exampleHeader('Plant Name') - ->example('Ransar Industries-I') - ->label('Plant Name') - ->relationship(resolveUsing:'name') + ->exampleHeader('PLANT CODE') + ->example('1000') + ->label('PLANT CODE') + ->relationship(resolveUsing: 'code') ->rules(['required']), ]; } @@ -37,21 +36,28 @@ class BlockImporter extends Importer public function resolveRecord(): ?Block { $warnMsg = []; - $plant = Plant::where('name', $this->data['plant'])->first(); - if (!$plant) { - $warnMsg[] = "Plant not found"; - // $warnMsg[] = "Plant '" . $this->data['plant'] . "' not found"; + $plantCod = $this->data['plant']; + $plant = null; + if (Str::length($plantCod) < 4 || ! is_numeric($plantCod) || ! preg_match('/^[1-9]\d{3,}$/', $plantCod)) { + $warnMsg[] = 'Invalid plant code found'; + } else { + $plant = Plant::where('code', $plantCod)->first(); + if (! $plant) { + $warnMsg[] = 'Plant not found'; + // $warnMsg[] = "Plant '" . $plantCod . "' not found"; + } } if (Str::length($this->data['name']) < 0) { - $warnMsg[] = "Block name not found"; + $warnMsg[] = 'Block name not found'; } - if (!empty($warnMsg)) { + if (! empty($warnMsg)) { throw new RowImportFailedException(implode(', ', $warnMsg)); } + return Block::updateOrCreate([ 'name' => $this->data['name'], - 'plant_id' => $plant->id + 'plant_id' => $plant->id, ]); // return Block::firstOrNew([ // // Update existing records, matching them by `$this->data['column_name']` @@ -63,10 +69,10 @@ class BlockImporter extends Importer public static function getCompletedNotificationBody(Import $import): string { - $body = 'Your block import has completed and ' . number_format($import->successful_rows) . ' ' . str('row')->plural($import->successful_rows) . ' imported.'; + $body = 'Your block import has completed and '.number_format($import->successful_rows).' '.str('row')->plural($import->successful_rows).' imported.'; if ($failedRowsCount = $import->getFailedRowsCount()) { - $body .= ' ' . number_format($failedRowsCount) . ' ' . str('row')->plural($failedRowsCount) . ' failed to import.'; + $body .= ' '.number_format($failedRowsCount).' '.str('row')->plural($failedRowsCount).' failed to import.'; } return $body; diff --git a/app/Filament/Imports/CheckPointNameImporter.php b/app/Filament/Imports/CheckPointNameImporter.php index 9f447bc..96ce37e 100644 --- a/app/Filament/Imports/CheckPointNameImporter.php +++ b/app/Filament/Imports/CheckPointNameImporter.php @@ -20,10 +20,10 @@ class CheckPointNameImporter extends Importer return [ ImportColumn::make('plant') ->requiredMapping() - ->exampleHeader('Plant Name') - ->example('Ransar Industries-I') - ->label('Plant Name') - ->relationship(resolveUsing: 'name') + ->exampleHeader('Plant Code') + ->example('1000') + ->label('Plant Code') + ->relationship(resolveUsing: 'code') ->rules(['required']), ImportColumn::make('name') ->requiredMapping() @@ -43,27 +43,33 @@ class CheckPointNameImporter extends Importer public function resolveRecord(): ?CheckPointName { $warnMsg = []; - $plant = Plant::where('name', $this->data['plant'])->first(); - if (!$plant) { - $warnMsg[] = "Plant not found"; // '" . $this->data['plant'] . "' + $plantCod = $this->data['plant']; + $plant = null; + if (Str::length($plantCod) < 4 || ! is_numeric($plantCod) || ! preg_match('/^[1-9]\d{3,}$/', $plantCod)) { + $warnMsg[] = 'Invalid plant code found'; + } else { + $plant = Plant::where('code', $plantCod)->first(); + if (! $plant) { + $warnMsg[] = 'Plant not found'; // '" . $plantCod . "' + } } 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']; 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)); } return CheckPointName::updateOrCreate([ 'name' => $this->data['name'], - 'plant_id' => $plant->id - ], - [ - 'created_by' => $this->data['created_by'] + 'plant_id' => $plant->id, + ], + [ + 'created_by' => $this->data['created_by'], ] ); // // return CheckPointName::firstOrNew([ @@ -76,10 +82,10 @@ class CheckPointNameImporter extends Importer public static function getCompletedNotificationBody(Import $import): string { - $body = 'Your check point name import has completed and ' . number_format($import->successful_rows) . ' ' . str('row')->plural($import->successful_rows) . ' imported.'; + $body = 'Your check point name import has completed and '.number_format($import->successful_rows).' '.str('row')->plural($import->successful_rows).' imported.'; if ($failedRowsCount = $import->getFailedRowsCount()) { - $body .= ' ' . number_format($failedRowsCount) . ' ' . str('row')->plural($failedRowsCount) . ' failed to import.'; + $body .= ' '.number_format($failedRowsCount).' '.str('row')->plural($failedRowsCount).' failed to import.'; } return $body; diff --git a/app/Filament/Imports/CheckPointTimeImporter.php b/app/Filament/Imports/CheckPointTimeImporter.php index b981ce1..946587b 100644 --- a/app/Filament/Imports/CheckPointTimeImporter.php +++ b/app/Filament/Imports/CheckPointTimeImporter.php @@ -21,10 +21,10 @@ class CheckPointTimeImporter extends Importer return [ ImportColumn::make('plant') ->requiredMapping() - ->exampleHeader('Plant Name') - ->example('Ransar Industries-I') - ->label('Plant Name') - ->relationship(resolveUsing: 'name') + ->exampleHeader('Plant Code') + ->example('1000') + ->label('Plant Code') + ->relationship(resolveUsing: 'code') ->rules(['required']), ImportColumn::make('checkPointNames1') ->requiredMapping() @@ -73,50 +73,51 @@ class CheckPointTimeImporter extends Importer public function resolveRecord(): ?CheckPointTime { $warnMsg = []; - $plant = Plant::where('name', $this->data['plant'])->first(); + $plantCod = $this->data['plant']; + $plant = null; $checkPointNames1 = null; $checkPointNames2 = null; - if (!$plant) { - $warnMsg[] = "Plant not found"; // '" . $this->data['plant'] . "' - } - else - { - $checkPointNames1 = CheckPointName::where('name', $this->data['checkPointNames1'])->first(); - if (!$checkPointNames1) { - $warnMsg[] = "Check point 1 not found"; - } - else - { - $checkPointNames2 = CheckPointName::where('name', $this->data['checkPointNames2'])->first(); - if (!$checkPointNames2) { - $warnMsg[] = "Check point 2 not found"; - } - else - { - if ($checkPointNames1->id === $checkPointNames2->id) { - $warnMsg[] = "Check point 1 and 2 can't be the same"; + 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'; // '" . $plantCod . "' + } else { + $checkPointNames1 = CheckPointName::where('name', $this->data['checkPointNames1'])->first(); + if (! $checkPointNames1) { + $warnMsg[] = 'Check point 1 not found'; + } else { + $checkPointNames2 = CheckPointName::where('name', $this->data['checkPointNames2'])->first(); + if (! $checkPointNames2) { + $warnMsg[] = 'Check point 2 not found'; + } else { + if ($checkPointNames1->id === $checkPointNames2->id) { + $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) { - $warnMsg[] = "Invalid sequence number found"; + if (Str::length($this->data['sequence_number']) < 1 || ! is_numeric($this->data['sequence_number']) || $this->data['sequence_number'] <= 0) { + $warnMsg[] = 'Invalid sequence number found'; } - if (Str::length($this->data['time_lapse']) < 1 || !is_numeric($this->data['time_lapse']) || $this->data['time_lapse'] <= 0) { - $warnMsg[] = "Invalid time lapse found"; + if (Str::length($this->data['time_lapse']) < 1 || ! is_numeric($this->data['time_lapse']) || $this->data['time_lapse'] <= 0) { + $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) { - $warnMsg[] = "Invalid time lapse cushioning found"; + 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'; } $createdBy = $this->data['created_by']; 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)); } @@ -124,12 +125,12 @@ class CheckPointTimeImporter extends Importer 'plant_id' => $plant->id, 'check_point1_id' => $checkPointNames1->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_cushioning' => $this->data['time_lapse_cushioning'], - 'created_by' => $this->data['created_by'] + [ + 'time_lapse' => $this->data['time_lapse'], + 'time_lapse_cushioning' => $this->data['time_lapse_cushioning'], + 'created_by' => $this->data['created_by'], ] ); // // return CheckPointTime::firstOrNew([ @@ -142,10 +143,10 @@ class CheckPointTimeImporter extends Importer public static function getCompletedNotificationBody(Import $import): string { - $body = 'Your check point time import has completed and ' . number_format($import->successful_rows) . ' ' . str('row')->plural($import->successful_rows) . ' imported.'; + $body = 'Your check point time import has completed and '.number_format($import->successful_rows).' '.str('row')->plural($import->successful_rows).' imported.'; if ($failedRowsCount = $import->getFailedRowsCount()) { - $body .= ' ' . number_format($failedRowsCount) . ' ' . str('row')->plural($failedRowsCount) . ' failed to import.'; + $body .= ' '.number_format($failedRowsCount).' '.str('row')->plural($failedRowsCount).' failed to import.'; } return $body; diff --git a/app/Filament/Imports/ConfigurationImporter.php b/app/Filament/Imports/ConfigurationImporter.php index bc0f1a9..0e5193e 100644 --- a/app/Filament/Imports/ConfigurationImporter.php +++ b/app/Filament/Imports/ConfigurationImporter.php @@ -62,15 +62,15 @@ class ConfigurationImporter extends Importer // 'email' => $this->data['email'], // ]); - return new Configuration(); + return new Configuration; } public static function getCompletedNotificationBody(Import $import): string { - $body = 'Your configuration import has completed and ' . number_format($import->successful_rows) . ' ' . str('row')->plural($import->successful_rows) . ' imported.'; + $body = 'Your configuration import has completed and '.number_format($import->successful_rows).' '.str('row')->plural($import->successful_rows).' imported.'; if ($failedRowsCount = $import->getFailedRowsCount()) { - $body .= ' ' . number_format($failedRowsCount) . ' ' . str('row')->plural($failedRowsCount) . ' failed to import.'; + $body .= ' '.number_format($failedRowsCount).' '.str('row')->plural($failedRowsCount).' failed to import.'; } return $body; diff --git a/app/Filament/Imports/DeviceMasterImporter.php b/app/Filament/Imports/DeviceMasterImporter.php index 8b72103..0560b72 100644 --- a/app/Filament/Imports/DeviceMasterImporter.php +++ b/app/Filament/Imports/DeviceMasterImporter.php @@ -16,10 +16,10 @@ class DeviceMasterImporter extends Importer return [ ImportColumn::make('plant') ->requiredMapping() - ->exampleHeader('Plant Name') - ->example('Ransar Industries-I') - ->label('Plant Name') - ->relationship(resolveUsing:'name') + ->exampleHeader('Plant Code') + ->example('1000') + ->label('Plant Code') + ->relationship(resolveUsing: 'code') ->rules(['required']), ImportColumn::make('name') ->requiredMapping() @@ -53,15 +53,15 @@ class DeviceMasterImporter extends Importer // 'email' => $this->data['email'], // ]); - return new DeviceMaster(); + return new DeviceMaster; } public static function getCompletedNotificationBody(Import $import): string { - $body = 'Your device master import has completed and ' . number_format($import->successful_rows) . ' ' . str('row')->plural($import->successful_rows) . ' imported.'; + $body = 'Your device master import has completed and '.number_format($import->successful_rows).' '.str('row')->plural($import->successful_rows).' imported.'; if ($failedRowsCount = $import->getFailedRowsCount()) { - $body .= ' ' . number_format($failedRowsCount) . ' ' . str('row')->plural($failedRowsCount) . ' failed to import.'; + $body .= ' '.number_format($failedRowsCount).' '.str('row')->plural($failedRowsCount).' failed to import.'; } return $body; diff --git a/app/Filament/Imports/EbReadingImporter.php b/app/Filament/Imports/EbReadingImporter.php index 731878a..eff8fe1 100644 --- a/app/Filament/Imports/EbReadingImporter.php +++ b/app/Filament/Imports/EbReadingImporter.php @@ -16,10 +16,10 @@ class EbReadingImporter extends Importer return [ ImportColumn::make('plant') ->requiredMapping() - ->exampleHeader('Plant Name') - ->example('Ransar Industries-I') - ->label('Plant Name') - ->relationship(resolveUsing:'name') + ->exampleHeader('Plant Code') + ->example('1000') + ->label('Plant Code') + ->relationship(resolveUsing: 'code') ->rules(['required']), ImportColumn::make('lcd_segment_check') ->label('LCD Segment Check') @@ -227,15 +227,15 @@ class EbReadingImporter extends Importer // 'email' => $this->data['email'], // ]); - return new EbReading(); + return new EbReading; } public static function getCompletedNotificationBody(Import $import): string { - $body = 'Your eb reading import has completed and ' . number_format($import->successful_rows) . ' ' . str('row')->plural($import->successful_rows) . ' imported.'; + $body = 'Your eb reading import has completed and '.number_format($import->successful_rows).' '.str('row')->plural($import->successful_rows).' imported.'; if ($failedRowsCount = $import->getFailedRowsCount()) { - $body .= ' ' . number_format($failedRowsCount) . ' ' . str('row')->plural($failedRowsCount) . ' failed to import.'; + $body .= ' '.number_format($failedRowsCount).' '.str('row')->plural($failedRowsCount).' failed to import.'; } return $body; diff --git a/app/Filament/Imports/EquipmentMasterImporter.php b/app/Filament/Imports/EquipmentMasterImporter.php index 3634fd1..2cee4db 100644 --- a/app/Filament/Imports/EquipmentMasterImporter.php +++ b/app/Filament/Imports/EquipmentMasterImporter.php @@ -16,17 +16,17 @@ class EquipmentMasterImporter extends Importer return [ ImportColumn::make('plant') ->requiredMapping() - ->exampleHeader('Plant Name') - ->example('Ransar Industries-I') - ->label('Plant Name') - ->relationship(resolveUsing:'name') + ->exampleHeader('Plant Code') + ->example('1000') + ->label('Plant Code') + ->relationship(resolveUsing: 'code') ->rules(['required']), ImportColumn::make('machine') ->requiredMapping() ->exampleHeader('Machine Name') ->example('1006378') ->label('Machine Name') - ->relationship(resolveUsing:'name') + ->relationship(resolveUsing: 'name') ->rules(['required']), ImportColumn::make('name') ->label('Name') @@ -93,15 +93,15 @@ class EquipmentMasterImporter extends Importer // 'email' => $this->data['email'], // ]); - return new EquipmentMaster(); + return new EquipmentMaster; } public static function getCompletedNotificationBody(Import $import): string { - $body = 'Your equipment master import has completed and ' . number_format($import->successful_rows) . ' ' . str('row')->plural($import->successful_rows) . ' imported.'; + $body = 'Your equipment master import has completed and '.number_format($import->successful_rows).' '.str('row')->plural($import->successful_rows).' imported.'; if ($failedRowsCount = $import->getFailedRowsCount()) { - $body .= ' ' . number_format($failedRowsCount) . ' ' . str('row')->plural($failedRowsCount) . ' failed to import.'; + $body .= ' '.number_format($failedRowsCount).' '.str('row')->plural($failedRowsCount).' failed to import.'; } return $body; diff --git a/app/Filament/Imports/GrMasterImporter.php b/app/Filament/Imports/GrMasterImporter.php index 092ec2f..8540a0e 100644 --- a/app/Filament/Imports/GrMasterImporter.php +++ b/app/Filament/Imports/GrMasterImporter.php @@ -3,14 +3,14 @@ namespace App\Filament\Imports; 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\Importer; use Filament\Actions\Imports\Models\Import; -use App\Models\Plant; -use App\Models\Item; use Str; -use Filament\Actions\Imports\Exceptions\RowImportFailedException; -use App\Models\User; class GrMasterImporter extends Importer { @@ -21,17 +21,17 @@ class GrMasterImporter extends Importer return [ ImportColumn::make('plant') ->requiredMapping() - ->exampleHeader('Plant Name') - ->example('Ransar Industries-I') - ->label('Plant Name') - ->relationship(resolveUsing:'name') + ->exampleHeader('Plant Code') + ->example('1000') + ->label('Plant Code') + ->relationship(resolveUsing: 'code') ->rules(['required']), ImportColumn::make('item') ->requiredMapping() ->exampleHeader('Item Code') ->example('630214') ->label('Item Code') - ->relationship(resolveUsing:'code') + ->relationship(resolveUsing: 'code') ->rules(['required']), ImportColumn::make('serial_number') ->requiredMapping() @@ -51,7 +51,7 @@ class GrMasterImporter extends Importer ->example('Admin') ->label('Created By') ->rules(['required']), - //ImportColumn::make('updated_by'), + // ImportColumn::make('updated_by'), ]; } @@ -63,44 +63,47 @@ class GrMasterImporter extends Importer // ]); $warnMsg = []; - - $plant = Plant::where('name', $this->data['plant'])->first(); - - if (!$plant) { - $warnMsg[] = "Plant not found"; - } - + $plantCod = $this->data['plant']; + $plant = null; $item = null; - if ($plant) { - $item = Item::where('code', $this->data['item'])->where('plant_id', $plant->id)->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) { + $warnMsg[] = 'Plant not found'; + } else { + $item = Item::where('code', $this->data['item'])->where('plant_id', $plant->id)->first(); + } + if (! $item) { + $warnMsg[] = 'Item not found'; + } } - if (!$item) { - $warnMsg[] = "Item not found"; - } - if (Str::length($this->data['serial_number']) < 9 || !ctype_alnum($this->data['serial_number'])) { - $warnMsg[] = "Invalid serial number found"; + + if (Str::length($this->data['serial_number']) < 9 || ! ctype_alnum($this->data['serial_number'])) { + $warnMsg[] = 'Invalid serial number found'; } 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(); - if (!$user) { - $warnMsg[] = "User not found"; + if (! $user) { + $warnMsg[] = 'User not found'; } - if (!empty($warnMsg)) { + if (! empty($warnMsg)) { throw new RowImportFailedException(implode(', ', $warnMsg)); - } - else { //if (empty($warnMsg)) + } else { // if (empty($warnMsg)) $grMaster = GrMaster::where('plant_id', $plant->id) - ->where('serial_number', $this->data['serial_number']) - ->latest() - ->first(); + ->where('serial_number', $this->data['serial_number']) + ->latest() + ->first(); if ($grMaster) { - throw new RowImportFailedException("Serial number already exist!"); + throw new RowImportFailedException('Serial number already exist!'); } } @@ -113,15 +116,15 @@ class GrMasterImporter extends Importer ]); return null; - //return new GrMaster(); + // return new GrMaster(); } public static function getCompletedNotificationBody(Import $import): string { - $body = 'Your gr master import has completed and ' . number_format($import->successful_rows) . ' ' . str('row')->plural($import->successful_rows) . ' imported.'; + $body = 'Your gr master import has completed and '.number_format($import->successful_rows).' '.str('row')->plural($import->successful_rows).' imported.'; if ($failedRowsCount = $import->getFailedRowsCount()) { - $body .= ' ' . number_format($failedRowsCount) . ' ' . str('row')->plural($failedRowsCount) . ' failed to import.'; + $body .= ' '.number_format($failedRowsCount).' '.str('row')->plural($failedRowsCount).' failed to import.'; } return $body; diff --git a/app/Filament/Imports/GuardNameImporter.php b/app/Filament/Imports/GuardNameImporter.php index 416fad5..276fa9f 100644 --- a/app/Filament/Imports/GuardNameImporter.php +++ b/app/Filament/Imports/GuardNameImporter.php @@ -20,10 +20,10 @@ class GuardNameImporter extends Importer return [ ImportColumn::make('plant') ->requiredMapping() - ->exampleHeader('Plant Name') - ->example('Ransar Industries-I') - ->label('Plant Name') - ->relationship(resolveUsing: 'name') + ->exampleHeader('Plant Code') + ->example('1000') + ->label('Plant Code') + ->relationship(resolveUsing: 'code') ->rules(['required']), ImportColumn::make('name') ->requiredMapping() @@ -54,32 +54,38 @@ class GuardNameImporter extends Importer public function resolveRecord(): ?GuardName { $warnMsg = []; - $plant = Plant::where('name', $this->data['plant'])->first(); - if (!$plant) { - $warnMsg[] = "Plant not found"; // '" . $this->data['plant'] . "' + $plantCod = $this->data['plant']; + $plant = null; + if (Str::length($plantCod) < 4 || ! is_numeric($plantCod) || ! preg_match('/^[1-9]\d{3,}$/', $plantCod)) { + $warnMsg[] = 'Invalid plant code found'; + } else { + $plant = Plant::where('code', $plantCod)->first(); + if (! $plant) { + $warnMsg[] = 'Plant not found'; // '" . $plantCod . "' + } } 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) { - $warnMsg[] = "Invalid identification-1 found"; + $warnMsg[] = 'Invalid identification-1 found'; } $createdBy = $this->data['created_by']; 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)); } return GuardName::updateOrCreate([ 'name' => $this->data['name'], - 'plant_id' => $plant->id + 'plant_id' => $plant->id, ], - [ - 'identification1' => $this->data['identification1'], - 'identification2' => $this->data['identification2'], - 'created_by' => $this->data['created_by'] + [ + 'identification1' => $this->data['identification1'], + 'identification2' => $this->data['identification2'], + 'created_by' => $this->data['created_by'], ] ); @@ -87,15 +93,15 @@ class GuardNameImporter extends Importer // // // Update existing records, matching them by `$this->data['column_name']` // // 'email' => $this->data['email'], // // ]); - //return new GuardName(); + // return new GuardName(); } public static function getCompletedNotificationBody(Import $import): string { - $body = 'Your guard name import has completed and ' . number_format($import->successful_rows) . ' ' . str('row')->plural($import->successful_rows) . ' imported.'; + $body = 'Your guard name import has completed and '.number_format($import->successful_rows).' '.str('row')->plural($import->successful_rows).' imported.'; if ($failedRowsCount = $import->getFailedRowsCount()) { - $body .= ' ' . number_format($failedRowsCount) . ' ' . str('row')->plural($failedRowsCount) . ' failed to import.'; + $body .= ' '.number_format($failedRowsCount).' '.str('row')->plural($failedRowsCount).' failed to import.'; } return $body; diff --git a/app/Filament/Imports/GuardPatrolEntryImporter.php b/app/Filament/Imports/GuardPatrolEntryImporter.php index b99f6a8..a9b8979 100644 --- a/app/Filament/Imports/GuardPatrolEntryImporter.php +++ b/app/Filament/Imports/GuardPatrolEntryImporter.php @@ -23,10 +23,10 @@ class GuardPatrolEntryImporter extends Importer return [ ImportColumn::make('plant') ->requiredMapping() - ->exampleHeader('Plant Name') - ->example('Ransar Industries-I') - ->label('Plant Name') - ->relationship(resolveUsing: 'name') + ->exampleHeader('Plant Code') + ->example('1000') + ->label('Plant Code') + ->relationship(resolveUsing: 'code') ->rules(['required']), ImportColumn::make('guardNames') ->requiredMapping() @@ -68,61 +68,60 @@ class GuardPatrolEntryImporter extends Importer public function resolveRecord(): ?GuardPatrolEntry { $warnMsg = []; - $plant = Plant::where('name', $this->data['plant'])->first(); + $plantCod = $this->data['plant']; + $plant = null; $guardNames = null; $checkPointNames = null; - $patrolDateTime = null; //$fdateTime = null; - if (!$plant) { - $warnMsg[] = "Plant not found"; // '" . $this->data['plant'] . "' - } - else - { - $guardNames = GuardName::where('plant_id', $plant->id)->where('name', $this->data['guardNames'])->first(); - if (!$guardNames) { - $warnMsg[] = "Guard name not found"; - } - else - { - $checkPointNames = CheckPointName::where('plant_id', $plant->id)->where('name', $this->data['checkPointNames'])->first(); - if (!$checkPointNames) { - $warnMsg[] = "Check point name not found"; - } - else - { - $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' + $patrolDateTime = null; // $fdateTime = null; - foreach ($formats as $format) { - try { - $patrolDateTime = Carbon::createFromFormat($format, $patrolTime); - break; - } catch (\Exception $e) { - // Optionally collect warning messages - // $warnMsg[] = "Date format mismatch with format: $format"; + 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'; // '" . $plantCod . "' + } else { + $guardNames = GuardName::where('plant_id', $plant->id)->where('name', $this->data['guardNames'])->first(); + if (! $guardNames) { + $warnMsg[] = 'Guard name not found'; + } else { + $checkPointNames = CheckPointName::where('plant_id', $plant->id)->where('name', $this->data['checkPointNames'])->first(); + if (! $checkPointNames) { + $warnMsg[] = 'Check point name not found'; + } else { + $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' + + foreach ($formats as $format) { + try { + $patrolDateTime = Carbon::createFromFormat($format, $patrolTime); + break; + } catch (\Exception $e) { + // Optionally collect warning messages + // $warnMsg[] = "Date format mismatch with format: $format"; + } } - } - if (!isset($patrolDateTime)) { - // throw new \Exception('Invalid date time format'); - $warnMsg[] = "Invalid 'Patrol DateTime' format. Expected DD-MM-YYYY HH:MM:SS"; - } - 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(); - if ($guardEntryFound) { - $warnMsg[] = "Duplicate guard patrol entry found"; + if (! isset($patrolDateTime)) { + // throw new \Exception('Invalid date time format'); + $warnMsg[] = "Invalid 'Patrol DateTime' format. Expected DD-MM-YYYY HH:MM:SS"; + } 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(); + if ($guardEntryFound) { + $warnMsg[] = 'Duplicate guard patrol entry found'; + } } } } } } - $createdBy = Filament::auth()->user()->name;// ?? 'Admin' - if (!$createdBy) { - $warnMsg[] = "Invalid created by name found"; + $createdBy = Filament::auth()->user()->name; // ?? 'Admin' + if (! $createdBy) { + $warnMsg[] = 'Invalid created by name found'; } - if (!empty($warnMsg)) { + if (! empty($warnMsg)) { throw new RowImportFailedException(implode(', ', $warnMsg)); } @@ -130,14 +129,15 @@ class GuardPatrolEntryImporter extends Importer 'plant_id' => $plant->id, 'guard_name_id' => $guardNames->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, - 'created_by' => $createdBy, - 'updated_by' => $createdBy + [ + 'reader_code' => null, + 'created_by' => $createdBy, + 'updated_by' => $createdBy, ] ); + return null; // // return GuardPatrolEntry::firstOrNew([ // // // Update existing records, matching them by `$this->data['column_name']` @@ -149,10 +149,10 @@ class GuardPatrolEntryImporter extends Importer public static function getCompletedNotificationBody(Import $import): string { - $body = 'Your guard patrol entry import has completed and ' . number_format($import->successful_rows) . ' ' . str('row')->plural($import->successful_rows) . ' imported.'; + $body = 'Your guard patrol entry import has completed and '.number_format($import->successful_rows).' '.str('row')->plural($import->successful_rows).' imported.'; if ($failedRowsCount = $import->getFailedRowsCount()) { - $body .= ' ' . number_format($failedRowsCount) . ' ' . str('row')->plural($failedRowsCount) . ' failed to import.'; + $body .= ' '.number_format($failedRowsCount).' '.str('row')->plural($failedRowsCount).' failed to import.'; } return $body; diff --git a/app/Filament/Imports/LineImporter.php b/app/Filament/Imports/LineImporter.php index f412cf3..30ec799 100644 --- a/app/Filament/Imports/LineImporter.php +++ b/app/Filament/Imports/LineImporter.php @@ -87,10 +87,10 @@ class LineImporter extends Importer ->label('Work Group Center 10'), ImportColumn::make('plant') ->requiredMapping() - ->exampleHeader('Plant Name') - ->example('Ransar Industries-I') - ->label('Plant Name') - ->relationship(resolveUsing:'name') + ->exampleHeader('Plant Code') + ->example('1000') + ->label('Plant Code') + ->relationship(resolveUsing: 'code') ->rules(['required']), ]; } @@ -98,28 +98,33 @@ class LineImporter extends Importer public function resolveRecord(): ?Line { $warnMsg = []; + $plantCod = $this->data['plant']; + $plant = null; - $plant = Plant::where('name', $this->data['plant'])->first(); - if (!$plant) { - throw new RowImportFailedException("Plant '{$this->data['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(); + if (! $plant) { + throw new RowImportFailedException('Plant not found'); + } } 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) { - throw new RowImportFailedException("Line type not found"); + throw new RowImportFailedException('Line type not found'); } $noOfOps = (int) ($this->data['no_of_operation'] ?? 0); - if (($noOfOps == null || $noOfOps == '' || !is_numeric($noOfOps)) && $noOfOps != 0) { + if (($noOfOps == null || $noOfOps == '' || ! is_numeric($noOfOps)) && $noOfOps != 0) { 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"); } @@ -130,28 +135,28 @@ class LineImporter extends Importer $missingGroups[] = "work_group{$i}_id"; } } - if (!empty($missingGroups)) { + if (! empty($missingGroups)) { throw new RowImportFailedException( - "Invalid data: Required work groups missing values in: " . implode(', ', $missingGroups) + 'Invalid data: Required work groups missing values in: '.implode(', ', $missingGroups) ); } // Ensure no extra work groups are filled $invalidGroups = []; for ($i = $noOfOps + 1; $i <= 10; $i++) { - if (!empty($this->data["work_group{$i}_id"])) { + if (! empty($this->data["work_group{$i}_id"])) { $invalidGroups[] = "work_group{$i}_id"; } } - if (!empty($invalidGroups)) { + if (! empty($invalidGroups)) { throw new RowImportFailedException( - "Invalid data: Only first {$noOfOps} work groups should be filled, but values found in: " . implode(', ', $invalidGroups) + "Invalid data: Only first {$noOfOps} work groups should be filled, but values found in: ".implode(', ', $invalidGroups) ); } for ($i = 1; $i <= 10; $i++) { $workGroupName = $this->data["work_group{$i}_id"] ?? null; - if (!$workGroupName) { + if (! $workGroupName) { continue; } @@ -159,8 +164,8 @@ class LineImporter extends Importer ->where('plant_id', $plant->id) ->first(); - if (!$workGroupRecord) { - throw new RowImportFailedException("Work group '{$workGroupName}' not found in plant '{$this->data['plant']}'"); + if (! $workGroupRecord) { + throw new RowImportFailedException("Work group '{$workGroupName}' not found in plant '{$plantCod}'"); } $existsInLines = Line::where('plant_id', $plant->id) @@ -169,35 +174,34 @@ class LineImporter extends Importer ->first(); 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; } - if (!empty($warnMsg)) - { + if (! empty($warnMsg)) { throw new RowImportFailedException(implode(', ', $warnMsg)); } Line::updateOrCreate( [ 'name' => $this->data['name'], - 'plant_id' => $plant->id + 'plant_id' => $plant->id, ], [ 'type' => $this->data['type'], 'no_of_operation' => $noOfOps, - 'work_group1_id' => $this->data['work_group1_id'] ?? null, - 'work_group2_id' => $this->data['work_group2_id'] ?? null, - 'work_group3_id' => $this->data['work_group3_id'] ?? null, - 'work_group4_id' => $this->data['work_group4_id'] ?? null, - 'work_group5_id' => $this->data['work_group5_id'] ?? null, - 'work_group6_id' => $this->data['work_group6_id'] ?? null, - 'work_group7_id' => $this->data['work_group7_id'] ?? null, - 'work_group8_id' => $this->data['work_group8_id'] ?? null, - 'work_group9_id' => $this->data['work_group9_id'] ?? null, - 'work_group10_id' => $this->data['work_group10_id'] ?? null, + 'work_group1_id' => $this->data['work_group1_id'] ?? null, + 'work_group2_id' => $this->data['work_group2_id'] ?? null, + 'work_group3_id' => $this->data['work_group3_id'] ?? null, + 'work_group4_id' => $this->data['work_group4_id'] ?? null, + 'work_group5_id' => $this->data['work_group5_id'] ?? null, + 'work_group6_id' => $this->data['work_group6_id'] ?? null, + 'work_group7_id' => $this->data['work_group7_id'] ?? null, + 'work_group8_id' => $this->data['work_group8_id'] ?? null, + 'work_group9_id' => $this->data['work_group9_id'] ?? null, + 'work_group10_id' => $this->data['work_group10_id'] ?? null, ] ); @@ -206,10 +210,10 @@ class LineImporter extends Importer public static function getCompletedNotificationBody(Import $import): string { - $body = 'Your line import has completed and ' . number_format($import->successful_rows) . ' ' . str('row')->plural($import->successful_rows) . ' imported.'; + $body = 'Your line import has completed and '.number_format($import->successful_rows).' '.str('row')->plural($import->successful_rows).' imported.'; if ($failedRowsCount = $import->getFailedRowsCount()) { - $body .= ' ' . number_format($failedRowsCount) . ' ' . str('row')->plural($failedRowsCount) . ' failed to import.'; + $body .= ' '.number_format($failedRowsCount).' '.str('row')->plural($failedRowsCount).' failed to import.'; } return $body; diff --git a/app/Filament/Imports/LocatorInvoiceValidationImporter.php b/app/Filament/Imports/LocatorInvoiceValidationImporter.php index 5817365..f9ad60c 100644 --- a/app/Filament/Imports/LocatorInvoiceValidationImporter.php +++ b/app/Filament/Imports/LocatorInvoiceValidationImporter.php @@ -10,7 +10,6 @@ use Filament\Actions\Imports\Exceptions\RowImportFailedException; use Filament\Actions\Imports\ImportColumn; use Filament\Actions\Imports\Importer; use Filament\Actions\Imports\Models\Import; -use Filament\Facades\Filament; use Str; class LocatorInvoiceValidationImporter extends Importer @@ -115,53 +114,49 @@ class LocatorInvoiceValidationImporter extends Importer $scannedBy = $this->data['scanned_by']; $updatedBy = $this->data['updated_by']; - 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', $this->data['plant'])->first(); - if (!$plant) { - $warnMsg[] = "Plant not found"; - } - else - { - if (Str::length($invoiceNo) < 5 || !ctype_alnum($invoiceNo)) { - $warnMsg[] = "Invalid invoice number 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(); + if (! $plant) { + $warnMsg[] = 'Plant not found'; + } else { + if (Str::length($invoiceNo) < 5 || ! ctype_alnum($invoiceNo)) { + $warnMsg[] = 'Invalid invoice number found'; } - if (Str::length($serialNo) < 9 || Str::length($serialNo) > 20 || !ctype_alnum($serialNo)) { - $warnMsg[] = "Invalid serial number found"; + if (Str::length($serialNo) < 9 || Str::length($serialNo) > 20 || ! ctype_alnum($serialNo)) { + $warnMsg[] = 'Invalid serial number found'; } 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) { - $warnMsg[] = "Invalid locator number found"; + $warnMsg[] = 'Invalid locator number found'; } if (Str::length($scannedStat) > 0 && $scannedStat != 'Scanned') { - $warnMsg[] = "Invalid scanned status found"; + $warnMsg[] = 'Invalid scanned status found'; } if ($uploadStat != 'Y' && $uploadStat != 'N') { - $warnMsg[] = "Invalid upload status found"; + $warnMsg[] = 'Invalid upload status found'; } $created = User::where('name', $createdBy)->first(); - if (!$created) { - $warnMsg[] = "Created by not found"; + if (! $created) { + $warnMsg[] = 'Created by not found'; } if (Str::length($scannedBy) > 0) { $scanned = User::where('name', $scannedBy)->first(); - if (!$scanned) { - $warnMsg[] = "Scanned by not found"; + if (! $scanned) { + $warnMsg[] = 'Scanned by not found'; } } if (Str::length($updatedBy) > 0) { $updated = User::where('name', $updatedBy)->first(); - if (!$updated) { - $warnMsg[] = "Updated by not found"; + if (! $updated) { + $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' foreach ($formats as $format) { try { @@ -173,13 +168,12 @@ class LocatorInvoiceValidationImporter extends Importer } } - if (!isset($cDateTime)) { + if (! isset($cDateTime)) { // throw new \Exception('Invalid date time format'); $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) { try { $sDateTime = Carbon::createFromFormat($format, $scannedAt); @@ -190,13 +184,12 @@ class LocatorInvoiceValidationImporter extends Importer } } - if (!isset($sDateTime)) { + if (! isset($sDateTime)) { $warnMsg[] = "Invalid 'Scanned DateTime' format. Expected DD-MM-YYYY HH:MM:SS"; } } - if (Str::length($updatedAt) > 0) - { + if (Str::length($updatedAt) > 0) { foreach ($formats as $format) { try { $uDateTime = Carbon::createFromFormat($format, $updatedAt); @@ -207,11 +200,9 @@ class LocatorInvoiceValidationImporter extends Importer } } - if (!isset($uDateTime)) { + if (! isset($uDateTime)) { $warnMsg[] = "Invalid 'Updated DateTime' format. Expected DD-MM-YYYY HH:MM:SS"; - } - else - { + } else { if (isset($cDateTime) && isset($uDateTime)) { if ($cDateTime->greaterThan($uDateTime)) { $warnMsg[] = "'Created DataTime' is greater than 'Updated DateTime'."; @@ -226,14 +217,14 @@ class LocatorInvoiceValidationImporter extends Importer // $warnMsg[] = "Invalid locator quantity found"; // } - if (!empty($warnMsg)) { + if (! empty($warnMsg)) { throw new RowImportFailedException(implode(', ', $warnMsg)); } LocatorInvoiceValidation::updateOrCreate( [ 'plant_id' => $plant->id, - 'serial_number' => $serialNo + 'serial_number' => $serialNo, ], [ '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, 'created_by' => $createdBy, 'scanned_by' => $scannedBy, - 'updated_by' => $updatedBy + 'updated_by' => $updatedBy, ] ); + return null; // // return LocatorInvoiceValidation::firstOrNew([ // // // Update existing records, matching them by `$this->data['column_name']` @@ -260,10 +252,10 @@ class LocatorInvoiceValidationImporter extends Importer public static function getCompletedNotificationBody(Import $import): string { - $body = 'Your locator invoice validation import has completed and ' . number_format($import->successful_rows) . ' ' . str('row')->plural($import->successful_rows) . ' imported.'; + $body = 'Your locator invoice validation import has completed and '.number_format($import->successful_rows).' '.str('row')->plural($import->successful_rows).' imported.'; if ($failedRowsCount = $import->getFailedRowsCount()) { - $body .= ' ' . number_format($failedRowsCount) . ' ' . str('row')->plural($failedRowsCount) . ' failed to import.'; + $body .= ' '.number_format($failedRowsCount).' '.str('row')->plural($failedRowsCount).' failed to import.'; } return $body; diff --git a/app/Filament/Imports/MachineImporter.php b/app/Filament/Imports/MachineImporter.php index b4f2550..ae809ac 100644 --- a/app/Filament/Imports/MachineImporter.php +++ b/app/Filament/Imports/MachineImporter.php @@ -21,9 +21,9 @@ class MachineImporter extends Importer return [ ImportColumn::make('name') ->requiredMapping() - ->exampleHeader('Machine') + ->exampleHeader('Machine Name') ->example(['1600251']) - ->label('Machine') + ->label('Machine Name') ->rules(['required']), ImportColumn::make('work_center') ->requiredMapping() @@ -41,16 +41,16 @@ class MachineImporter extends Importer ImportColumn::make('line') ->requiredMapping() ->relationship(resolveUsing: 'name') - ->exampleHeader('Line') + ->exampleHeader('Line Name') ->example(['4 inch pump line']) - ->label('Line') + ->label('Line Name') ->rules(['required']), ImportColumn::make('plant') ->requiredMapping() - ->relationship(resolveUsing: 'name') - ->exampleHeader('Plant') - ->example(['Ransar Industries-I']) - ->label('Plant') + ->relationship(resolveUsing: 'code') + ->exampleHeader('Plant Code') + ->example(['1000']) + ->label('Plant Code') ->rules(['required']), ]; } @@ -58,74 +58,74 @@ class MachineImporter extends Importer public function resolveRecord(): ?Machine { $warnMsg = []; - $plant = Plant::where('name', $this->data['plant'])->first(); + $plantCod = $this->data['plant']; + $plant = null; $line = null; $machine = $this->data['name']; $workCenter = $this->data['work_center']; $groupWorkCenter = WorkGroupMaster::where('name', $this->data['workGroupMaster'])->first(); - if (!$plant) { - $warnMsg[] = "Plant not found!"; - } - else { - $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(); - if ($line) { - $grpWrkCnr = $line->no_of_operation; - if (!$grpWrkCnr || $grpWrkCnr < 1)//Str::length($grpWrkCnr) < 1) - { - $warnMsg[] = "Group work center line not found!"; - } - else if (!$groupWorkCenter) { - $warnMsg[] = "Group work center not found!"; - } - else { - $dupMachine = Machine::where('plant_id', $plant->id)->where('work_center', '!=', $workCenter)->where('name', $machine)->first(); - if ($dupMachine) { - $warnMsg[] = "Duplicate machine name found!"; - } - else { - $isValidGroupWork = false; - for ($i = 1; $i <= $line->no_of_operation; $i++) { - $column = "work_group{$i}_id"; - if (!empty($line->$column)) { - if ($line->$column == $groupWorkCenter->id) { - $isValidGroupWork = true; - break; + 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 { + $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(); + if ($line) { + $grpWrkCnr = $line->no_of_operation; + if (! $grpWrkCnr || $grpWrkCnr < 1) {// Str::length($grpWrkCnr) < 1) + $warnMsg[] = 'Group work center line not found!'; + } elseif (! $groupWorkCenter) { + $warnMsg[] = 'Group work center not found!'; + } else { + $dupMachine = Machine::where('plant_id', $plant->id)->where('work_center', '!=', $workCenter)->where('name', $machine)->first(); + if ($dupMachine) { + $warnMsg[] = 'Duplicate machine name found!'; + } else { + $isValidGroupWork = false; + for ($i = 1; $i <= $line->no_of_operation; $i++) { + $column = "work_group{$i}_id"; + if (! empty($line->$column)) { + if ($groupWorkCenter->id == $line->$column) { + $isValidGroupWork = true; + break; + } } } - } - if (!$isValidGroupWork) { - $warnMsg[] = "Group work center does not match with line!"; + if (! $isValidGroupWork) { + $warnMsg[] = 'Group work center does not match with line!'; + } } } + } else { + $warnMsg[] = 'Line not found!'; } } - else - { - $warnMsg[] = "Line not found!"; - } } if (Str::length($machine) <= 0) { - $warnMsg[] = "Machine name not found!"; + $warnMsg[] = 'Machine name not found!'; } - if (!empty($warnMsg)) { + if (! empty($warnMsg)) { throw new RowImportFailedException(implode(', ', $warnMsg)); } Machine::updateOrCreate( [ 'plant_id' => $plant->id, - 'work_center' => $workCenter + 'work_center' => $workCenter, ], [ 'line_id' => $line->id, 'name' => $machine, - 'work_group_master_id' => $groupWorkCenter->id + 'work_group_master_id' => $groupWorkCenter->id, ] ); + return null; // // return Machine::firstOrNew([ // // // Update existing records, matching them by `$this->data['column_name']` @@ -137,10 +137,10 @@ class MachineImporter extends Importer public static function getCompletedNotificationBody(Import $import): string { - $body = 'Your machine import has completed and ' . number_format($import->successful_rows) . ' ' . str('row')->plural($import->successful_rows) . ' imported.'; + $body = 'Your machine import has completed and '.number_format($import->successful_rows).' '.str('row')->plural($import->successful_rows).' imported.'; if ($failedRowsCount = $import->getFailedRowsCount()) { - $body .= ' ' . number_format($failedRowsCount) . ' ' . str('row')->plural($failedRowsCount) . ' failed to import.'; + $body .= ' '.number_format($failedRowsCount).' '.str('row')->plural($failedRowsCount).' failed to import.'; } return $body; diff --git a/app/Filament/Imports/MfmMeterImporter.php b/app/Filament/Imports/MfmMeterImporter.php index 90d4358..d9dfdf5 100644 --- a/app/Filament/Imports/MfmMeterImporter.php +++ b/app/Filament/Imports/MfmMeterImporter.php @@ -15,18 +15,18 @@ class MfmMeterImporter extends Importer { return [ ImportColumn::make('plant') - ->requiredMapping() - ->exampleHeader('Plant Name') - ->example('Ransar Industries-I') - ->label('Plant Name') - ->relationship(resolveUsing:'name') + ->requiredMapping() + ->exampleHeader('Plant Code') + ->example('1000') + ->label('Plant Code') + ->relationship(resolveUsing: 'code') ->rules(['required']), ImportColumn::make('Device Name') ->requiredMapping() ->exampleHeader('Device Name') ->example('REG001') ->label('Device Name') - ->relationship(resolveUsing:'name') + ->relationship(resolveUsing: 'name') ->rules(['required']), ImportColumn::make('sequence') ->requiredMapping() @@ -56,15 +56,15 @@ class MfmMeterImporter extends Importer // 'email' => $this->data['email'], // ]); - return new MfmMeter(); + return new MfmMeter; } public static function getCompletedNotificationBody(Import $import): string { - $body = 'Your mfm meter import has completed and ' . number_format($import->successful_rows) . ' ' . str('row')->plural($import->successful_rows) . ' imported.'; + $body = 'Your mfm meter import has completed and '.number_format($import->successful_rows).' '.str('row')->plural($import->successful_rows).' imported.'; if ($failedRowsCount = $import->getFailedRowsCount()) { - $body .= ' ' . number_format($failedRowsCount) . ' ' . str('row')->plural($failedRowsCount) . ' failed to import.'; + $body .= ' '.number_format($failedRowsCount).' '.str('row')->plural($failedRowsCount).' failed to import.'; } return $body; diff --git a/app/Filament/Imports/MfmParameterImporter.php b/app/Filament/Imports/MfmParameterImporter.php index e8a0e88..057b4bd 100644 --- a/app/Filament/Imports/MfmParameterImporter.php +++ b/app/Filament/Imports/MfmParameterImporter.php @@ -16,24 +16,24 @@ class MfmParameterImporter extends Importer return [ ImportColumn::make('plant') ->requiredMapping() - ->exampleHeader('Plant Name') - ->example('Ransar Industries-I') - ->label('Plant Name') - ->relationship(resolveUsing:'name') + ->exampleHeader('Plant Code') + ->example('1000') + ->label('Plant Code') + ->relationship(resolveUsing: 'code') ->rules(['required']), ImportColumn::make('deviceName') ->requiredMapping() ->exampleHeader('Device Name') ->example('REG001') ->label('Device Name') - ->relationship(resolveUsing:'name') + ->relationship(resolveUsing: 'name') ->rules(['required']), ImportColumn::make('mfmMeter') ->requiredMapping() ->exampleHeader('Mfm Meter Sequence') ->example('1') ->label('Mfm Meter Sequence') - ->relationship(resolveUsing:'sequence') + ->relationship(resolveUsing: 'sequence') ->rules(['required']), ImportColumn::make('name') ->requiredMapping() @@ -82,15 +82,15 @@ class MfmParameterImporter extends Importer // 'email' => $this->data['email'], // ]); - return new MfmParameter(); + return new MfmParameter; } public static function getCompletedNotificationBody(Import $import): string { - $body = 'Your mfm parameter import has completed and ' . number_format($import->successful_rows) . ' ' . str('row')->plural($import->successful_rows) . ' imported.'; + $body = 'Your mfm parameter import has completed and '.number_format($import->successful_rows).' '.str('row')->plural($import->successful_rows).' imported.'; if ($failedRowsCount = $import->getFailedRowsCount()) { - $body .= ' ' . number_format($failedRowsCount) . ' ' . str('row')->plural($failedRowsCount) . ' failed to import.'; + $body .= ' '.number_format($failedRowsCount).' '.str('row')->plural($failedRowsCount).' failed to import.'; } return $body; diff --git a/app/Filament/Imports/MotorTestingMasterImporter.php b/app/Filament/Imports/MotorTestingMasterImporter.php index 48f5b1d..c7497c4 100644 --- a/app/Filament/Imports/MotorTestingMasterImporter.php +++ b/app/Filament/Imports/MotorTestingMasterImporter.php @@ -24,7 +24,7 @@ class MotorTestingMasterImporter extends Importer ImportColumn::make('item') ->requiredMapping() ->exampleHeader('Item Code') - ->example(['123456','123457','123458']) + ->example(['123456', '123457', '123458']) ->label('Item Code') ->relationship(resolveUsing: 'code') ->rules(['required']), @@ -38,181 +38,181 @@ class MotorTestingMasterImporter extends Importer ->requiredMapping() ->boolean() ->exampleHeader('ISI Model') - ->example(['Y','N','Y']) + ->example(['Y', 'N', 'Y']) ->label('ISI Model') ->rules(['boolean']), ImportColumn::make('phase') ->requiredMapping() ->exampleHeader('Phase') - ->example(['Single','Three','Single']) + ->example(['Single', 'Three', 'Single']) ->label('Phase') ->rules(['required']), ImportColumn::make('hp') ->requiredMapping() ->exampleHeader('HP') - ->example(['5','10','5']) + ->example(['5', '10', '5']) ->label('HP') ->rules(['required']), ImportColumn::make('kw') ->requiredMapping() ->exampleHeader('KW') - ->example(['5','7.5','5']) + ->example(['5', '7.5', '5']) ->label('KW') ->rules(['required']), ImportColumn::make('volt') ->requiredMapping() ->exampleHeader('Volt') - ->example(['230','380','230']) + ->example(['230', '380', '230']) ->label('Volt') ->rules(['required']), ImportColumn::make('current') ->requiredMapping() ->exampleHeader('Current') - ->example(['7','21.8','7']) + ->example(['7', '21.8', '7']) ->label('Current') ->rules(['required']), ImportColumn::make('rpm') ->requiredMapping() ->exampleHeader('RPM') - ->example(['2500','3420','2500']) + ->example(['2500', '3420', '2500']) ->label('RPM') ->rules(['required']), ImportColumn::make('torque') ->requiredMapping() ->exampleHeader('Torque') - ->example(['0.5','1.25','0.5']) + ->example(['0.5', '1.25', '0.5']) ->label('Torque') ->rules(['required']), ImportColumn::make('frequency') ->requiredMapping() ->exampleHeader('Frequency') ->label('Frequency') - ->example(['50','60','50']) + ->example(['50', '60', '50']) ->rules(['required']), ImportColumn::make('connection') ->requiredMapping() ->exampleHeader('Connection') ->label('Connection') - ->example(['Star','Star-Delta','Delta']) + ->example(['Star', 'Star-Delta', 'Delta']) ->rules(['required']), ImportColumn::make('ins_res_limit') ->requiredMapping() ->exampleHeader('Insulation Resistance Limit') ->label('Insulation Resistance Limit') - ->example(['1000','2','1000']) + ->example(['1000', '2', '1000']) ->rules(['required']), ImportColumn::make('ins_res_type') ->requiredMapping() ->exampleHeader('Insulation Resistance Type') ->label('Insulation Resistance Type') - ->example(['O','G','O']) + ->example(['O', 'G', 'O']) ->rules(['required']), ImportColumn::make('routine_test_time') ->requiredMapping() ->exampleHeader('Routine Test Time') ->label('Routine Test Time') - ->example(['00:40:00','00:40:00','00:40:00']) + ->example(['00:40:00', '00:40:00', '00:40:00']) ->rules(['required']), ImportColumn::make('res_ry_ll') ->requiredMapping() ->exampleHeader('Resistance RY LL') ->label('Resistance RY LL') - ->example(['0.05','0.05','0.05']) + ->example(['0.05', '0.05', '0.05']) ->rules(['required']), ImportColumn::make('res_ry_ul') ->requiredMapping() ->exampleHeader('Resistance RY UL') ->label('Resistance RY UL') - ->example(['99','99','99']) + ->example(['99', '99', '99']) ->rules(['required']), ImportColumn::make('res_yb_ll') ->requiredMapping() ->exampleHeader('Resistance YB LL') ->label('Resistance YB LL') - ->example(['0.05','0.05','0.05']) + ->example(['0.05', '0.05', '0.05']) ->rules(['required']), ImportColumn::make('res_yb_ul') ->requiredMapping() ->exampleHeader('Resistance YB UL') ->label('Resistance YB UL') - ->example(['99','99','99']) + ->example(['99', '99', '99']) ->rules(['required']), ImportColumn::make('res_br_ll') ->requiredMapping() ->exampleHeader('Resistance BR LL') ->label('Resistance BR LL') - ->example(['0.05','0.05','0.05']) + ->example(['0.05', '0.05', '0.05']) ->rules(['required']), ImportColumn::make('res_br_ul') ->requiredMapping() ->exampleHeader('Resistance BR UL') ->label('Resistance BR UL') - ->example(['99','99','99']) + ->example(['99', '99', '99']) ->rules(['required']), ImportColumn::make('lock_volt_limit') ->requiredMapping() ->exampleHeader('Lock Volt Limit') ->label('Lock Volt Limit') - ->example(['80','100','80']) + ->example(['80', '100', '80']) ->rules(['required']), ImportColumn::make('leak_cur_limit') ->requiredMapping() ->exampleHeader('Leak Current Limit') ->label('Leak Current Limit') - ->example(['50','50','50']) + ->example(['50', '50', '50']) ->rules(['required']), ImportColumn::make('lock_cur_ll') ->requiredMapping() ->exampleHeader('Lock Current LL') ->label('Lock Current LL') - ->example(['10','12.5','10']) + ->example(['10', '12.5', '10']) ->rules(['required']), ImportColumn::make('lock_cur_ul') ->requiredMapping() ->exampleHeader('Lock Current UL') ->label('Lock Current UL') - ->example(['15','14.6','15']) + ->example(['15', '14.6', '15']) ->rules(['required']), ImportColumn::make('noload_cur_ll') ->requiredMapping() ->exampleHeader('No Load Current LL') ->label('No Load Current LL') - ->example(['3','5.9','3']) + ->example(['3', '5.9', '3']) ->rules(['required']), ImportColumn::make('noload_cur_ul') ->requiredMapping() ->exampleHeader('No Load Current UL') ->label('No Load Current UL') - ->example(['15','6.9','15']) + ->example(['15', '6.9', '15']) ->rules(['required']), ImportColumn::make('noload_pow_ll') ->requiredMapping() ->exampleHeader('No Load Power LL') ->label('No Load Power LL') - ->example(['250','850','250']) + ->example(['250', '850', '250']) ->rules(['required']), ImportColumn::make('noload_pow_ul') ->requiredMapping() ->exampleHeader('No Load Power UL') ->label('No Load Power UL') - ->example(['500','1200','500']) + ->example(['500', '1200', '500']) ->rules(['required']), ImportColumn::make('noload_spd_ll') ->requiredMapping() ->exampleHeader('No Load Speed LL') ->label('No Load Speed LL') - ->example(['2000','2500','2000']) + ->example(['2000', '2500', '2000']) ->rules(['required']), ImportColumn::make('noload_spd_ul') ->requiredMapping() ->exampleHeader('No Load Speed UL') ->label('No Load Speed UL') - ->example(['4000','3500','4000']) + ->example(['4000', '3500', '4000']) ->rules(['required']), ImportColumn::make('plant') ->requiredMapping() ->exampleHeader('Plant') - ->example(['1000','1010','1020']) + ->example(['1000', '1010', '1020']) ->label('Plant') ->relationship(resolveUsing: 'code') ->rules(['required']), @@ -237,7 +237,7 @@ class MotorTestingMasterImporter extends Importer $plantCod = trim($this->data['plant']); $iCode = trim($this->data['item']); $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']); $kw = trim($this->data['kw']); $hp = trim($this->data['hp']); @@ -270,40 +270,25 @@ class MotorTestingMasterImporter extends Importer $updatedBy = trim($this->data['updated_by']); $plant = null; - if (Str::length($plantCod) < 4 || !is_numeric($plantCod) || !preg_match('/^[1-9]\d{3,}$/', $plantCod)) - { - $warnMsg[] = "Invalid plant code found"; - } - else if (Str::length($iCode) < 6 || !ctype_alnum($iCode)) - { - $warnMsg[] = "Invalid item code found"; - } - else if (Str::length($sCode) < 6 || !ctype_alnum($sCode)) - { - $warnMsg[] = "Invalid sub-assembly code found"; - } - else - { + if (Str::length($plantCod) < 4 || ! is_numeric($plantCod) || ! preg_match('/^[1-9]\d{3,}$/', $plantCod)) { + $warnMsg[] = 'Invalid plant code found'; + } elseif (Str::length($iCode) < 6 || ! ctype_alnum($iCode)) { + $warnMsg[] = 'Invalid item code found'; + } elseif (Str::length($sCode) < 6 || ! ctype_alnum($sCode)) { + $warnMsg[] = 'Invalid sub-assembly code found'; + } else { $plant = Plant::where('code', $plantCod)->first(); $codeExist = Item::where('code', $iCode)->first(); - if ($plant) - { + if ($plant) { $iCode = Item::where('code', $iCode)->where('plant_id', $plant->id)->first(); } - if (!$plant) - { - $warnMsg[] = "Plant not found"; - } - else if (!$codeExist) - { - $warnMsg[] = "Item code not found"; - } - else if (!$iCode) - { - $warnMsg[] = "Item code not found for choosed plant"; - } - else - { + if (! $plant) { + $warnMsg[] = 'Plant not found'; + } elseif (! $codeExist) { + $warnMsg[] = 'Item code not found'; + } elseif (! $iCode) { + $warnMsg[] = 'Item code not found for choosed plant'; + } else { // if (Str::length($isiModel) <= 0 || $isiModel == "0" || $isiModel == "1") { // $warnMsg[] = "Invalid ISI Model found"; // } @@ -311,125 +296,123 @@ class MotorTestingMasterImporter extends Importer // { // $isiModel = ($isiModel == "1"); // } - if (Str::length($phase) <= 0 || ($phase != "Single" && $phase != "Three")) {//!is_string($phase) || - $warnMsg[] = "Invalid phase found"; + if (Str::length($phase) <= 0 || ($phase != 'Single' && $phase != 'Three')) {// !is_string($phase) || + $warnMsg[] = 'Invalid phase found'; } - if (Str::length($hp) <= 0 || !is_numeric($hp)) { - $warnMsg[] = "Invalid HP found"; + if (Str::length($hp) <= 0 || ! is_numeric($hp)) { + $warnMsg[] = 'Invalid HP found'; } - if (Str::length($kw) <= 0 || !is_numeric($kw)) { - $warnMsg[] = "Invalid KW found"; + if (Str::length($kw) <= 0 || ! is_numeric($kw)) { + $warnMsg[] = 'Invalid KW found'; } - if (Str::length($volt) <= 0 || !is_numeric($volt)) { - $warnMsg[] = "Invalid volt found"; + if (Str::length($volt) <= 0 || ! is_numeric($volt)) { + $warnMsg[] = 'Invalid volt found'; } - if (Str::length($current) <= 0 || !is_numeric($current)) { - $warnMsg[] = "Invalid current found"; + if (Str::length($current) <= 0 || ! is_numeric($current)) { + $warnMsg[] = 'Invalid current found'; } - if (Str::length($rpm) <= 0 || !is_numeric($rpm)) { - $warnMsg[] = "Invalid RPM found"; + if (Str::length($rpm) <= 0 || ! is_numeric($rpm)) { + $warnMsg[] = 'Invalid RPM found'; } - if (Str::length($torque) <= 0 || !is_numeric($torque)) { - $warnMsg[] = "Invalid torque found"; + if (Str::length($torque) <= 0 || ! is_numeric($torque)) { + $warnMsg[] = 'Invalid torque found'; } - if (Str::length($frequency) <= 0 || !is_numeric($frequency)) { - $warnMsg[] = "Invalid frequency found"; + if (Str::length($frequency) <= 0 || ! is_numeric($frequency)) { + $warnMsg[] = 'Invalid frequency found'; } - if (Str::length($connection) <= 0 || ($connection != "Star-Delta" && $connection != "Star" && $connection != "Delta")) { - $warnMsg[] = "Invalid connection found"; + if (Str::length($connection) <= 0 || ($connection != 'Star-Delta' && $connection != 'Star' && $connection != 'Delta')) { + $warnMsg[] = 'Invalid connection found'; } - if (Str::length($insResLimit) <= 0 || !is_numeric($insResLimit)) { - $warnMsg[] = "Invalid insulation resistance limit found"; + if (Str::length($insResLimit) <= 0 || ! is_numeric($insResLimit)) { + $warnMsg[] = 'Invalid insulation resistance limit found'; } - if (Str::length($insResType) <= 0 || ($insResType != "O" && $insResType != "M" && $insResType != "G")) { - $warnMsg[] = "Invalid insulation resistance type found"; + if (Str::length($insResType) <= 0 || ($insResType != 'O' && $insResType != 'M' && $insResType != 'G')) { + $warnMsg[] = 'Invalid insulation resistance type found'; } - if (Str::length($routineTestTime) <= 0 || !isValidTimeFormat($routineTestTime)) { - $warnMsg[] = "Invalid routine test time found"; + if (Str::length($routineTestTime) <= 0 || ! isValidTimeFormat($routineTestTime)) { + $warnMsg[] = 'Invalid routine test time found'; } - if (Str::length($resRyLl) <= 0 || !is_numeric($resRyLl)) { - $warnMsg[] = "Invalid resistance RY lower limit found"; + if (Str::length($resRyLl) <= 0 || ! is_numeric($resRyLl)) { + $warnMsg[] = 'Invalid resistance RY lower limit found'; } - if (Str::length($resRyUl) <= 0 || !is_numeric($resRyUl)) { - $warnMsg[] = "Invalid resistance RY upper limit found"; + if (Str::length($resRyUl) <= 0 || ! is_numeric($resRyUl)) { + $warnMsg[] = 'Invalid resistance RY upper limit found'; } - if (Str::length($resYbLl) <= 0 || !is_numeric($resYbLl)) { - $warnMsg[] = "Invalid resistance YB lower limit found"; + if (Str::length($resYbLl) <= 0 || ! is_numeric($resYbLl)) { + $warnMsg[] = 'Invalid resistance YB lower limit found'; } - if (Str::length($resYbUl) <= 0 || !is_numeric($resYbUl)) { - $warnMsg[] = "Invalid resistance YB upper limit found"; + if (Str::length($resYbUl) <= 0 || ! is_numeric($resYbUl)) { + $warnMsg[] = 'Invalid resistance YB upper limit found'; } - if (Str::length($resBrLl) <= 0 || !is_numeric($resBrLl)) { - $warnMsg[] = "Invalid resistance BR lower limit found"; + if (Str::length($resBrLl) <= 0 || ! is_numeric($resBrLl)) { + $warnMsg[] = 'Invalid resistance BR lower limit found'; } - if (Str::length($resBrUl) <= 0 || !is_numeric($resBrUl)) { - $warnMsg[] = "Invalid resistance BR upper limit found"; + if (Str::length($resBrUl) <= 0 || ! is_numeric($resBrUl)) { + $warnMsg[] = 'Invalid resistance BR upper limit found'; } - if (Str::length($lockVoltLimit) <= 0 || !is_numeric($lockVoltLimit)) { - $warnMsg[] = "Invalid locked volt limit found"; + if (Str::length($lockVoltLimit) <= 0 || ! is_numeric($lockVoltLimit)) { + $warnMsg[] = 'Invalid locked volt limit found'; } - if (Str::length($leakCurLimit) <= 0 || !is_numeric($leakCurLimit)) { - $warnMsg[] = "Invalid leakage current limit found"; + if (Str::length($leakCurLimit) <= 0 || ! is_numeric($leakCurLimit)) { + $warnMsg[] = 'Invalid leakage current limit found'; } - if (Str::length($lockCurLl) <= 0 || !is_numeric($lockCurLl)) { - $warnMsg[] = "Invalid locked current lower limit found"; + if (Str::length($lockCurLl) <= 0 || ! is_numeric($lockCurLl)) { + $warnMsg[] = 'Invalid locked current lower limit found'; } - if (Str::length($lockCurUl) <= 0 || !is_numeric($lockCurUl)) { - $warnMsg[] = "Invalid locked current upper limit found"; + if (Str::length($lockCurUl) <= 0 || ! is_numeric($lockCurUl)) { + $warnMsg[] = 'Invalid locked current upper limit found'; } - if (Str::length($noloadCurLl) <= 0 || !is_numeric($noloadCurLl)) { - $warnMsg[] = "Invalid no load current lower limit found"; + if (Str::length($noloadCurLl) <= 0 || ! is_numeric($noloadCurLl)) { + $warnMsg[] = 'Invalid no load current lower limit found'; } - if (Str::length($noloadCurUl) <= 0 || !is_numeric($noloadCurUl)) { - $warnMsg[] = "Invalid no load current upper limit found"; + if (Str::length($noloadCurUl) <= 0 || ! is_numeric($noloadCurUl)) { + $warnMsg[] = 'Invalid no load current upper limit found'; } - if (Str::length($noloadPowLl) <= 0 || !is_numeric($noloadPowLl)) { - $warnMsg[] = "Invalid no load power lower limit found"; + if (Str::length($noloadPowLl) <= 0 || ! is_numeric($noloadPowLl)) { + $warnMsg[] = 'Invalid no load power lower limit found'; } - if (Str::length($noloadPowUl) <= 0 || !is_numeric($noloadPowUl)) { - $warnMsg[] = "Invalid no load power upper limit found"; + if (Str::length($noloadPowUl) <= 0 || ! is_numeric($noloadPowUl)) { + $warnMsg[] = 'Invalid no load power upper limit found'; } - if (Str::length($noloadSpdLl) <= 0 || !is_numeric($noloadSpdLl)) { - $warnMsg[] = "Invalid no load speed lower limit found"; + if (Str::length($noloadSpdLl) <= 0 || ! is_numeric($noloadSpdLl)) { + $warnMsg[] = 'Invalid no load speed lower limit found'; } - if (Str::length($noloadSpdUl) <= 0 || !is_numeric($noloadSpdUl)) { - $warnMsg[] = "Invalid no load speed upper limit found"; + if (Str::length($noloadSpdUl) <= 0 || ! is_numeric($noloadSpdUl)) { + $warnMsg[] = 'Invalid no load speed upper limit found'; } $oldCode = MotorTestingMaster::where('item_id', $iCode->id)->where('plant_id', $plant->id)->first(); if ($oldCode) { $created = $oldCode->created_by ? User::where('name', $oldCode->created_by)->first() : null; - if (!$created) { - $warnMsg[] = "Created by not found on update"; + if (! $created) { + $warnMsg[] = 'Created by not found on update'; } $updated = User::where('name', $updatedBy)->first(); - if (!$updated) { - $warnMsg[] = "Updated by not found on update"; + if (! $updated) { + $warnMsg[] = 'Updated by not found on update'; } - } - else - { + } else { $created = User::where('name', $createdBy)->first(); - if (!$created) { - $warnMsg[] = "Created by not found"; + if (! $created) { + $warnMsg[] = 'Created by not found'; } $updated = User::where('name', $updatedBy)->first(); - if (!$updated) { - $warnMsg[] = "Updated by not found"; + if (! $updated) { + $warnMsg[] = 'Updated by not found'; } } } } - if (!empty($warnMsg)) { + if (! empty($warnMsg)) { throw new RowImportFailedException(implode(', ', $warnMsg)); } MotorTestingMaster::updateOrCreate([ 'plant_id' => $plant->id, - 'item_id' => $iCode->id - ], + 'item_id' => $iCode->id, + ], [ 'subassembly_code' => $sCode, 'isi_model' => $isiModel, @@ -465,6 +448,7 @@ class MotorTestingMasterImporter extends Importer 'updated_by' => $updated->name, ] ); + return null; // // return MotorTestingMaster::firstOrNew([ // // // Update existing records, matching them by `$this->data['column_name']` @@ -476,22 +460,24 @@ class MotorTestingMasterImporter extends Importer public static function getCompletedNotificationBody(Import $import): string { - $body = 'Your motor testing master import has completed and ' . number_format($import->successful_rows) . ' ' . str('row')->plural($import->successful_rows) . ' imported.'; + $body = 'Your motor testing master import has completed and '.number_format($import->successful_rows).' '.str('row')->plural($import->successful_rows).' imported.'; if ($failedRowsCount = $import->getFailedRowsCount()) { - $body .= ' ' . number_format($failedRowsCount) . ' ' . str('row')->plural($failedRowsCount) . ' failed to import.'; + $body .= ' '.number_format($failedRowsCount).' '.str('row')->plural($failedRowsCount).' failed to import.'; } return $body; } } -function isValidTimeFormat($time) { +function isValidTimeFormat($time) +{ // If time starts with a single digit hour without leading zero, pad it if (preg_match('/^\d(:\d{2}:\d{2})$/', $time, $matches)) { - $time = '0' . $time; + $time = '0'.$time; } $dateTime = DateTime::createFromFormat('H:i:s', $time); + return $dateTime && $dateTime->format('H:i:s') === $time; } diff --git a/app/Filament/Imports/PalletValidationImporter.php b/app/Filament/Imports/PalletValidationImporter.php index c733573..4aa5c30 100644 --- a/app/Filament/Imports/PalletValidationImporter.php +++ b/app/Filament/Imports/PalletValidationImporter.php @@ -12,7 +12,6 @@ use Filament\Actions\Imports\Importer; use Filament\Actions\Imports\Models\Import; use Str; - class PalletValidationImporter extends Importer { protected static ?string $model = PalletValidation::class; @@ -122,49 +121,45 @@ class PalletValidationImporter extends Importer $scannedBy = $this->data['scanned_by']; $updatedBy = $this->data['updated_by']; - 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', $this->data['plant'])->first(); - if (!$plant) { - $warnMsg[] = "Plant not found"; - } - else - { - if (Str::length($serialNo) < 9 || Str::length($serialNo) > 20 || !ctype_alnum($serialNo)) { - $warnMsg[] = "Invalid serial number 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(); + if (! $plant) { + $warnMsg[] = 'Plant not found'; + } else { + if (Str::length($serialNo) < 9 || Str::length($serialNo) > 20 || ! ctype_alnum($serialNo)) { + $warnMsg[] = 'Invalid serial number found'; } 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') { - $warnMsg[] = "Invalid pallet status found"; + $warnMsg[] = 'Invalid pallet status found'; } 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) { - $warnMsg[] = "Pallet and locator number found"; + $warnMsg[] = 'Pallet and locator number found'; } - if (Str::length($locatorQty) < 0 || !is_numeric($locatorQty) || $locatorQty < 0 || $locatorQty > 2) { - $warnMsg[] = "Invalid locator quantity found"; + if (Str::length($locatorQty) < 0 || ! is_numeric($locatorQty) || $locatorQty < 0 || $locatorQty > 2) { + $warnMsg[] = 'Invalid locator quantity found'; } $created = User::where('name', $createdBy)->first(); - if (!$created) { - $warnMsg[] = "Created by not found"; + if (! $created) { + $warnMsg[] = 'Created by not found'; } $scanned = User::where('name', $scannedBy)->first(); - if (!$scanned) { - $warnMsg[] = "Scanned by not found"; + if (! $scanned) { + $warnMsg[] = 'Scanned by not found'; } $updated = User::where('name', $updatedBy)->first(); - if (!$updated) { - $warnMsg[] = "Updated by not found"; + if (! $updated) { + $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' foreach ($formats as $format) { try { @@ -176,7 +171,7 @@ class PalletValidationImporter extends Importer } } - if (!isset($cDateTime)) { + if (! isset($cDateTime)) { // throw new \Exception('Invalid date time format'); $warnMsg[] = "Invalid 'Created DateTime' format. Expected DD-MM-YYYY HH:MM:SS"; } @@ -191,13 +186,12 @@ class PalletValidationImporter extends Importer } } - if (!isset($sDateTime)) { + if (! isset($sDateTime)) { $warnMsg[] = "Invalid 'Scanned DateTime' format. Expected DD-MM-YYYY HH:MM:SS"; } foreach ($formats as $format) { - try - { + try { $uDateTime = Carbon::createFromFormat($format, $updatedAt); break; } catch (\Exception $e) { @@ -206,11 +200,9 @@ class PalletValidationImporter extends Importer } } - if (!isset($uDateTime)) { + if (! isset($uDateTime)) { $warnMsg[] = "Invalid 'Updated DateTime' format. Expected DD-MM-YYYY HH:MM:SS"; - } - else - { + } else { if (isset($cDateTime) && isset($uDateTime)) { if ($cDateTime->greaterThan($uDateTime)) { $warnMsg[] = "'Created DataTime' is greater than 'Updated DateTime'."; @@ -224,14 +216,14 @@ class PalletValidationImporter extends Importer // $warnMsg[] = "Invalid locator quantity found"; // } - if (!empty($warnMsg)) { + if (! empty($warnMsg)) { throw new RowImportFailedException(implode(', ', $warnMsg)); } PalletValidation::updateOrCreate( [ 'plant_id' => $plant->id, - 'serial_number' => $serialNo + 'serial_number' => $serialNo, ], [ 'pallet_number' => $palletNo, @@ -243,9 +235,10 @@ class PalletValidationImporter extends Importer 'updated_at' => $uDateTime->format('Y-m-d H:i:s'), 'created_by' => $createdBy, 'scanned_by' => $scannedBy, - 'updated_by' => $updatedBy + 'updated_by' => $updatedBy, ] ); + return null; // // return PalletValidation::firstOrNew([ // // // Update existing records, matching them by `$this->data['column_name']` @@ -257,10 +250,10 @@ class PalletValidationImporter extends Importer public static function getCompletedNotificationBody(Import $import): string { - $body = 'Your pallet validation import has completed and ' . number_format($import->successful_rows) . ' ' . str('row')->plural($import->successful_rows) . ' imported.'; + $body = 'Your pallet validation import has completed and '.number_format($import->successful_rows).' '.str('row')->plural($import->successful_rows).' imported.'; if ($failedRowsCount = $import->getFailedRowsCount()) { - $body .= ' ' . number_format($failedRowsCount) . ' ' . str('row')->plural($failedRowsCount) . ' failed to import.'; + $body .= ' '.number_format($failedRowsCount).' '.str('row')->plural($failedRowsCount).' failed to import.'; } return $body; diff --git a/app/Filament/Imports/PlantImporter.php b/app/Filament/Imports/PlantImporter.php index f55d1b6..b03a13c 100644 --- a/app/Filament/Imports/PlantImporter.php +++ b/app/Filament/Imports/PlantImporter.php @@ -23,7 +23,7 @@ class PlantImporter extends Importer ->exampleHeader('Plant Code') ->example('1000') ->label('Plant Code') - ->rules(['required']), //, 'integer' + ->rules(['required']), // , 'integer' ImportColumn::make('name') ->requiredMapping() ->exampleHeader('Plant Name') @@ -41,7 +41,7 @@ class PlantImporter extends Importer ->exampleHeader('Company Name') ->example('C.R.I. Pumps Private Limited') ->label('Company Name') - ->relationship(resolveUsing:'name') + ->relationship(resolveUsing: 'name') ->rules(['required']), ]; } @@ -50,41 +50,40 @@ class PlantImporter extends Importer { $warnMsg = []; $company = Company::where('name', $this->data['company'])->first(); - if (!$company) { - $warnMsg[] = "Company name not found"; + if (! $company) { + $warnMsg[] = 'Company name not found'; } 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'])) { - $warnMsg[] = "Invalid plant code found"; + 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'; } 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)); } $plantCN = Plant::where('code', $this->data['code'])->where('name', $this->data['name'])->first(); - if (!$plantCN) { + if (! $plantCN) { $plantCode = Plant::where('code', $this->data['code'])->first(); $plantName = Plant::where('name', $this->data['name'])->first(); if ($plantName) { - throw new RowImportFailedException("Duplicate plant name found"); - } - else if ($plantCode) { - throw new RowImportFailedException("Duplicate plant code found"); + throw new RowImportFailedException('Duplicate plant name found'); + } elseif ($plantCode) { + throw new RowImportFailedException('Duplicate plant code found'); } } return Plant::updateOrCreate([ - 'code' => $this->data['code'], - 'name' => $this->data['name'], - ], + 'code' => $this->data['code'], + 'name' => $this->data['name'], + ], [ 'address' => $this->data['address'], - 'company_id' => $company->id + 'company_id' => $company->id, ] ); // return Plant::firstOrNew([ @@ -97,10 +96,10 @@ class PlantImporter extends Importer public static function getCompletedNotificationBody(Import $import): string { - $body = 'Your plant import has completed and ' . number_format($import->successful_rows) . ' ' . str('row')->plural($import->successful_rows) . ' imported.'; + $body = 'Your plant import has completed and '.number_format($import->successful_rows).' '.str('row')->plural($import->successful_rows).' imported.'; if ($failedRowsCount = $import->getFailedRowsCount()) { - $body .= ' ' . number_format($failedRowsCount) . ' ' . str('row')->plural($failedRowsCount) . ' failed to import.'; + $body .= ' '.number_format($failedRowsCount).' '.str('row')->plural($failedRowsCount).' failed to import.'; } return $body; diff --git a/app/Filament/Imports/ProductionLineStopImporter.php b/app/Filament/Imports/ProductionLineStopImporter.php index 10c4e6d..b456d3f 100644 --- a/app/Filament/Imports/ProductionLineStopImporter.php +++ b/app/Filament/Imports/ProductionLineStopImporter.php @@ -15,6 +15,7 @@ use Filament\Actions\Imports\ImportColumn; use Filament\Actions\Imports\Importer; use Filament\Actions\Imports\Models\Import; use Filament\Facades\Filament; +use Str; class ProductionLineStopImporter extends Importer { @@ -28,7 +29,7 @@ class ProductionLineStopImporter extends Importer ->exampleHeader('From DateTime') ->example(['01-01-2025 00:00:00', '01-01-2025 20:00:00']) ->label('From DateTime') - ->rules(['required']), //, 'date_format:"d-m-Y H:i:s"' + ->rules(['required']), // , 'date_format:"d-m-Y H:i:s"' ImportColumn::make('to_datetime') ->requiredMapping() ->exampleHeader('To DateTime') @@ -45,7 +46,7 @@ class ProductionLineStopImporter extends Importer ImportColumn::make('stop_min') ->requiredMapping() ->exampleHeader('Stop Min') - ->example(['25','0']) + ->example(['25', '0']) ->label('Stop Min') ->numeric() ->rules(['required', 'integer']), @@ -54,14 +55,14 @@ class ProductionLineStopImporter extends Importer ->exampleHeader('Line Stop Code') ->example(['A7R', 'A1R']) ->label('Line Stop Code') - ->relationship(resolveUsing:'code') + ->relationship(resolveUsing: 'code') ->rules(['required']), ImportColumn::make('line') ->requiredMapping() ->exampleHeader('Line Name') ->example(['4 inch pump line', '4 inch pump line']) ->label('Line Name') - ->relationship(resolveUsing:'name') + ->relationship(resolveUsing: 'name') ->rules(['required']), ImportColumn::make('block_reference') ->requiredMapping() // Or optionalMapping() if not always present @@ -78,10 +79,10 @@ class ProductionLineStopImporter extends Importer ->rules(['required']), ImportColumn::make('plant') ->requiredMapping() - ->exampleHeader('Plant Name') - ->example(['Ransar Industries-I', 'Ransar Industries-I']) - ->label('Plant Name') - ->relationship(resolveUsing:'name') + ->exampleHeader('Plant Code') + ->example(['1000', '1000']) + ->label('Plant Code') + ->relationship(resolveUsing: 'code') ->rules(['required']), ImportColumn::make('operator_id') ->requiredMapping() @@ -95,61 +96,62 @@ class ProductionLineStopImporter extends Importer public function resolveRecord(): ?ProductionLineStop { $warnMsg = []; - $plant = Plant::where('name', $this->data['plant'])->first(); + $plantCod = $this->data['plant']; + $plant = null; $line = null; $block = null; - if (!$plant) { - $warnMsg[] = "Plant not found"; - } - else { - $line = Line::where('name', $this->data['line'])->where('plant_id', $plant->id)->first(); - //block_reference - $block = Block::where('name', $this->data['block_reference'])->where('plant_id', $plant->id)->first(); - } - if (!$line) { - $warnMsg[] = "Line not found"; - } $shift = null; - if (!$block) { - $warnMsg[] = "Block 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(); + if (! $plant) { + $warnMsg[] = 'Plant not found'; + } else { + $line = Line::where('name', $this->data['line'])->where('plant_id', $plant->id)->first(); + // block_reference + $block = Block::where('name', $this->data['block_reference'])->where('plant_id', $plant->id)->first(); + } } - else { + if (! $line) { + $warnMsg[] = 'Line not found'; + } + if (! $block) { + $warnMsg[] = 'Block not found'; + } elseif ($plant) { $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(); - if (!$shift) { - $warnMsg[] = "Shift not found"; + // $shift = Shift::where('id', $this->data['shift'])->where('plant_id', $plant->id)->first(); + if (! $shift) { + $warnMsg[] = 'Shift not found'; } $linestop = LineStop::where('code', $this->data['linestop'])->first(); - if (!$linestop) { - $warnMsg[] = "Line stop code not found"; + if (! $linestop) { + $warnMsg[] = 'Line stop code not found'; } $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; - if (!$stophour && !$stopmin) { - $warnMsg[] = "Invalid stop hour/minute found"; - } - else if (!$stophour) { - $warnMsg[] = "Invalid stop hour found"; - } - else if (!$stopmin) { - $warnMsg[] = "Invalid stop min found"; - } - else { - $stophour = (int)$this->data['stop_hour']; - $stopmin = (int)$this->data['stop_min']; + if (! $stophour && ! $stopmin) { + $warnMsg[] = 'Invalid stop hour/minute found'; + } elseif (! $stophour) { + $warnMsg[] = 'Invalid stop hour found'; + } elseif (! $stopmin) { + $warnMsg[] = 'Invalid stop min found'; + } else { + $stophour = (int) $this->data['stop_hour']; + $stopmin = (int) $this->data['stop_min']; if ($stophour == 0 && $stopmin == 0) { - $warnMsg[] = "Invalid stop hour/minute found"; + $warnMsg[] = 'Invalid stop hour/minute found'; } } $validHourMin = ($stophour == 0 && $stopmin == 0) ? false : true; - if (!$validHourMin) { - $warnMsg[] = "Invalid stop hour/minute found"; + if (! $validHourMin) { + $warnMsg[] = 'Invalid stop hour/minute found'; } $fromDate = $this->data['from_datetime']; $toDate = $this->data['to_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' $fdateTime = null; $tdateTime = null; @@ -175,14 +177,14 @@ class ProductionLineStopImporter extends Importer } // $fDateOnly = ''; - if (!isset($fdateTime)) { + if (! isset($fdateTime)) { // throw new \Exception('Invalid date time format'); $warnMsg[] = "Invalid 'From DateTime' format. Expected DD-MM-YYYY HH:MM:SS"; } // else { // $fDateOnly = $fdateTime->toDateString(); // } - if (!isset($tdateTime)) { + if (! isset($tdateTime)) { $warnMsg[] = "Invalid 'To DateTime' format. Expected DD-MM-YYYY HH:MM:SS"; } @@ -200,11 +202,11 @@ class ProductionLineStopImporter extends Importer // } $user = User::where('name', $this->data['operator_id'])->first(); - if (!$user) { - $warnMsg[] = "Operator ID not found"; + if (! $user) { + $warnMsg[] = 'Operator ID not found'; } - if (!empty($warnMsg)) { + if (! empty($warnMsg)) { throw new RowImportFailedException(implode(', ', $warnMsg)); } @@ -213,12 +215,13 @@ class ProductionLineStopImporter extends Importer 'line_id' => $line->id, 'shift_id' => $shift->id, 'linestop_id' => $linestop->id, - 'from_datetime' => $fdateTime->format('Y-m-d H:i:s'),//$this->data['from_datetime'], - 'to_datetime' => $tdateTime->format('Y-m-d H:i:s'),//$this->data['to_datetime'], - 'stop_hour' => (int)$this->data['stop_hour'], - 'stop_min' => (int)$this->data['stop_min'], + 'from_datetime' => $fdateTime->format('Y-m-d H:i:s'), // $this->data['from_datetime'], + 'to_datetime' => $tdateTime->format('Y-m-d H:i:s'), // $this->data['to_datetime'], + 'stop_hour' => (int) $this->data['stop_hour'], + 'stop_min' => (int) $this->data['stop_min'], 'operator_id' => $this->data['operator_id'], ]); + return null; // return ProductionLineStop::firstOrNew([ // // Update existing records, matching them by `$this->data['column_name']` @@ -230,10 +233,10 @@ class ProductionLineStopImporter extends Importer public static function getCompletedNotificationBody(Import $import): string { - $body = 'Your production line stop import has completed and ' . number_format($import->successful_rows) . ' ' . str('row')->plural($import->successful_rows) . ' imported.'; + $body = 'Your production line stop import has completed and '.number_format($import->successful_rows).' '.str('row')->plural($import->successful_rows).' imported.'; if ($failedRowsCount = $import->getFailedRowsCount()) { - $body .= ' ' . number_format($failedRowsCount) . ' ' . str('row')->plural($failedRowsCount) . ' failed to import.'; + $body .= ' '.number_format($failedRowsCount).' '.str('row')->plural($failedRowsCount).' failed to import.'; } return $body; diff --git a/app/Filament/Imports/ProductionPlanImporter.php b/app/Filament/Imports/ProductionPlanImporter.php index a71fe7b..54d27c9 100644 --- a/app/Filament/Imports/ProductionPlanImporter.php +++ b/app/Filament/Imports/ProductionPlanImporter.php @@ -48,7 +48,7 @@ class ProductionPlanImporter extends Importer ->exampleHeader('Line Name') ->example(['4 inch pump line', '4 inch pump line']) ->label('Line Name') - ->relationship(resolveUsing:'name') + ->relationship(resolveUsing: 'name') ->rules(['required']), ImportColumn::make('block_reference') ->requiredMapping() // Or optionalMapping() if not always present @@ -58,17 +58,17 @@ class ProductionPlanImporter extends Importer ->rules(['required']), // Or remove if not required ImportColumn::make('shift') ->requiredMapping() - ->exampleHeader('Shift Name') //ID - ->example(['Day', 'Night']) //'2', '7' + ->exampleHeader('Shift Name') // ID + ->example(['Day', 'Night']) // '2', '7' ->label('Shift Name') // ID ->relationship(resolveUsing: 'name') ->rules(['required']), ImportColumn::make('plant') ->requiredMapping() - ->exampleHeader('Plant Name') - ->example(['Ransar Industries-I', 'Ransar Industries-I']) - ->label('Plant Name') - ->relationship(resolveUsing:'name') + ->exampleHeader('Plant Code') + ->example(['1000', '1000']) + ->label('Plant Code') + ->relationship(resolveUsing: 'code') ->rules(['required']), ImportColumn::make('updated_at') ->requiredMapping() @@ -88,42 +88,51 @@ class ProductionPlanImporter extends Importer public function resolveRecord(): ?ProductionPlan { $warnMsg = []; - $plant = Plant::where('name', $this->data['plant'])->first(); + $plantCod = $this->data['plant']; + $plant = null; $line = 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(); - //block_reference + // block_reference $block = Block::where('name', $this->data['block_reference'])->where('plant_id', $plant->id)->first(); } - if (!$line) { - $warnMsg[] = "Line not found"; + + if (! $line) { + $warnMsg[] = 'Line not found'; } + $shift = null; - if (!$block) { - $warnMsg[] = "Block not found"; - } - else { + if (! $block) { + $warnMsg[] = 'Block not found'; + } elseif ($plant) { $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(); - if (!$shift) { - $warnMsg[] = "Shift not found"; + + // $shift = Shift::where('id', $this->data['shift'])->where('plant_id', $plant->id)->first(); + if (! $shift) { + $warnMsg[] = 'Shift not found'; } - if (Str::length($this->data['plan_quantity']) < 0 || !is_numeric($this->data['plan_quantity']) || $this->data['plan_quantity'] <= 0) { - $warnMsg[] = "Invalid plan quantity found"; + if (Str::length($this->data['plan_quantity']) < 0 || ! is_numeric($this->data['plan_quantity']) || $this->data['plan_quantity'] <= 0) { + $warnMsg[] = 'Invalid plan quantity found'; } - if (Str::length($this->data['production_quantity']) < 0 || !is_numeric($this->data['production_quantity']) || $this->data['production_quantity'] < 0) { - $warnMsg[] = "Invalid production quantity found"; + if (Str::length($this->data['production_quantity']) < 0 || ! is_numeric($this->data['production_quantity']) || $this->data['production_quantity'] < 0) { + $warnMsg[] = 'Invalid production quantity found'; } $fromDate = $this->data['created_at']; $toDate = $this->data['updated_at']; - $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' $fdateTime = null; $tdateTime = null; @@ -149,14 +158,13 @@ class ProductionPlanImporter extends Importer } $fDateOnly = ''; - if (!isset($fdateTime)) { + if (! isset($fdateTime)) { // throw new \Exception('Invalid date time format'); $warnMsg[] = "Invalid 'Created DateTime' format. Expected DD-MM-YYYY HH:MM:SS"; - } - else { + } else { $fDateOnly = $fdateTime->toDateString(); } - if (!isset($tdateTime)) { + if (! isset($tdateTime)) { $warnMsg[] = "Invalid 'Updated DateTime' format. Expected DD-MM-YYYY HH:MM:SS"; } @@ -174,21 +182,20 @@ class ProductionPlanImporter extends Importer // } $user = User::where('name', $this->data['operator_id'])->first(); - if (!$user) { - $warnMsg[] = "Operator ID not found"; + if (! $user) { + $warnMsg[] = 'Operator ID not found'; } - if (!empty($warnMsg)) { + if (! empty($warnMsg)) { throw new RowImportFailedException(implode(', ', $warnMsg)); - } - else { //if (empty($warnMsg)) + } else { // if (empty($warnMsg)) $productionPlan = ProductionPlan::where('plant_id', $plant->id) - ->where('shift_id', $shift->id) - ->where('line_id', $line->id) - ->whereDate('created_at', $fDateOnly) + ->where('shift_id', $shift->id) + ->where('line_id', $line->id) + ->whereDate('created_at', $fDateOnly) // ->where('plan_quantity', $productionQuantity->plan_quantity) - ->latest() - ->first(); + ->latest() + ->first(); if ($productionPlan) { // if($productionPlan->production_quantity) @@ -205,6 +212,7 @@ class ProductionPlanImporter extends Importer 'operator_id' => $this->data['operator_id'], ]); $productionPlan->save(); + return null; } } @@ -215,10 +223,11 @@ class ProductionPlanImporter extends Importer 'shift_id' => $shift->id, 'plan_quantity' => $this->data['plan_quantity'], 'production_quantity' => $this->data['production_quantity'], - 'created_at' => $fdateTime->format('Y-m-d H:i:s'),//$this->data['created_at'], - 'updated_at' => $tdateTime->format('Y-m-d H:i:s'),//$this->data['updated_at'], + 'created_at' => $fdateTime->format('Y-m-d H:i:s'), // $this->data['created_at'], + 'updated_at' => $tdateTime->format('Y-m-d H:i:s'), // $this->data['updated_at'], 'operator_id' => $this->data['operator_id'], ]); + return null; // return ProductionPlan::firstOrNew([ // // Update existing records, matching them by `$this->data['column_name']` @@ -230,10 +239,10 @@ class ProductionPlanImporter extends Importer public static function getCompletedNotificationBody(Import $import): string { - $body = 'Your production plan import has completed and ' . number_format($import->successful_rows) . ' ' . str('row')->plural($import->successful_rows) . ' imported.'; + $body = 'Your production plan import has completed and '.number_format($import->successful_rows).' '.str('row')->plural($import->successful_rows).' imported.'; if ($failedRowsCount = $import->getFailedRowsCount()) { - $body .= ' ' . number_format($failedRowsCount) . ' ' . str('row')->plural($failedRowsCount) . ' failed to import.'; + $body .= ' '.number_format($failedRowsCount).' '.str('row')->plural($failedRowsCount).' failed to import.'; } return $body; diff --git a/app/Filament/Imports/ProductionQuantityImporter.php b/app/Filament/Imports/ProductionQuantityImporter.php index 13a688f..0ea9100 100644 --- a/app/Filament/Imports/ProductionQuantityImporter.php +++ b/app/Filament/Imports/ProductionQuantityImporter.php @@ -42,7 +42,7 @@ class ProductionQuantityImporter extends Importer ->exampleHeader('Item Code') ->example(['123456', '123456']) ->label('Item Code') - ->relationship(resolveUsing:'code') + ->relationship(resolveUsing: 'code') ->rules(['required']), ImportColumn::make('serial_number') ->requiredMapping() @@ -55,27 +55,27 @@ class ProductionQuantityImporter extends Importer ->exampleHeader('Line Name') ->example(['4 inch pump line', '4 inch pump line']) ->label('Line Name') - ->relationship(resolveUsing:'name') + ->relationship(resolveUsing: 'name') ->rules(['required']), ImportColumn::make('block_reference') ->requiredMapping() // Or optionalMapping() if not always present - ->exampleHeader('Block') + ->exampleHeader('Block Name') ->example(['Block A', 'Block A']) - ->label('Block') + ->label('Block Name') ->rules(['required']), // Or remove if not required ImportColumn::make('shift') ->requiredMapping() ->exampleHeader('Shift Name') ->example(['Day', 'Night']) ->label('Shift Name') - ->relationship(resolveUsing:'name') + ->relationship(resolveUsing: 'name') ->rules(['required']), ImportColumn::make('plant') ->requiredMapping() - ->exampleHeader('Plant Name') - ->example(['Ransar Industries-I', 'Ransar Industries-I']) - ->label('Plant Name') - ->relationship(resolveUsing:'name') + ->exampleHeader('Plant Code') + ->example(['1000', '1000']) + ->label('Plant Code') + ->relationship(resolveUsing: 'code') ->rules(['required']), ImportColumn::make('updated_at') ->requiredMapping() @@ -95,49 +95,57 @@ class ProductionQuantityImporter extends Importer public function resolveRecord(): ?ProductionQuantity { $warnMsg = []; - $plant = Plant::where('name', $this->data['plant'])->first(); + $plantCod = $this->data['plant']; + $plant = null; $line = null; $block = null; - if (!$plant) { - $warnMsg[] = "Plant not found"; + $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(); } - else { + + if (! $plant) { + $warnMsg[] = 'Plant not found'; + } else { $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(); } - if (!$line) { - $warnMsg[] = "Line not found"; + + if (! $line) { + $warnMsg[] = 'Line not found'; } - $shift = null; - if (!$block) { - $warnMsg[] = "Block not found"; - } - else { + if (! $block) { + $warnMsg[] = 'Block not found'; + } elseif ($plant) { $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(); - if (!$shift) { - $warnMsg[] = "Shift not found"; + + // $shift = Shift::where('id', $this->data['shift'])->where('plant_id', $plant->id)->first(); + if (! $shift) { + $warnMsg[] = 'Shift not found'; } + $item = null; if ($plant) { $item = Item::where('code', $this->data['item'])->where('plant_id', $plant->id)->first(); } - if (!$item) { - $warnMsg[] = "Item not found"; + if (! $item) { + $warnMsg[] = 'Item not found'; } - if (Str::length($this->data['serial_number']) < 9 || !ctype_alnum($this->data['serial_number'])) { - $warnMsg[] = "Invalid serial number found"; + if (Str::length($this->data['serial_number']) < 9 || ! ctype_alnum($this->data['serial_number'])) { + $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']))) { - $warnMsg[] = "Invalid production order 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']))) { + $warnMsg[] = 'Invalid production order found'; } $fromDate = $this->data['created_at']; $toDate = $this->data['updated_at']; - $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' $fdateTime = null; $tdateTime = null; @@ -163,14 +171,14 @@ class ProductionQuantityImporter extends Importer } // $fDateOnly = ''; - if (!isset($fdateTime)) { + if (! isset($fdateTime)) { // throw new \Exception('Invalid date time format'); $warnMsg[] = "Invalid 'Created DateTime' format. Expected DD-MM-YYYY HH:MM:SS"; } // else { // $fDateOnly = $fdateTime->toDateString(); // } - if (!isset($tdateTime)) { + if (! isset($tdateTime)) { $warnMsg[] = "Invalid 'Updated DateTime' format. Expected DD-MM-YYYY HH:MM:SS"; } @@ -187,21 +195,20 @@ class ProductionQuantityImporter extends Importer // } $user = User::where('name', $this->data['operator_id'])->first(); - if (!$user) { - $warnMsg[] = "Operator ID not found"; + if (! $user) { + $warnMsg[] = 'Operator ID not found'; } - if (!empty($warnMsg)) { + if (! empty($warnMsg)) { throw new RowImportFailedException(implode(', ', $warnMsg)); - } - else { //if (empty($warnMsg)) + } else { // if (empty($warnMsg)) $productionQuan = ProductionQuantity::where('plant_id', $plant->id) - ->where('serial_number', $this->data['serial_number']) - ->latest() - ->first(); + ->where('serial_number', $this->data['serial_number']) + ->latest() + ->first(); if ($productionQuan) { - throw new RowImportFailedException("Serial number already exist!"); + throw new RowImportFailedException('Serial number already exist!'); } } @@ -212,10 +219,11 @@ class ProductionQuantityImporter extends Importer 'line_id' => $line->id, 'item_id' => $item->id, 'production_order' => $this->data['production_order'] ?? null, - 'created_at' => $fdateTime->format('Y-m-d H:i:s'),//$this->data['created_at'], - 'updated_at' => $tdateTime->format('Y-m-d H:i:s'),//$this->data['updated_at'], + 'created_at' => $fdateTime->format('Y-m-d H:i:s'), // $this->data['created_at'], + 'updated_at' => $tdateTime->format('Y-m-d H:i:s'), // $this->data['updated_at'], 'operator_id' => $this->data['operator_id'], ]); + // ProductionQuantity::updateOrCreate([ // 'serial_number' => $this->data['serial_number'], // 'plant_id' => $plant->id, @@ -236,10 +244,10 @@ class ProductionQuantityImporter extends Importer public static function getCompletedNotificationBody(Import $import): string { - $body = 'Your production quantity import has completed and ' . number_format($import->successful_rows) . ' ' . str('row')->plural($import->successful_rows) . ' imported.'; + $body = 'Your production quantity import has completed and '.number_format($import->successful_rows).' '.str('row')->plural($import->successful_rows).' imported.'; if ($failedRowsCount = $import->getFailedRowsCount()) { - $body .= ' ' . number_format($failedRowsCount) . ' ' . str('row')->plural($failedRowsCount) . ' failed to import.'; + $body .= ' '.number_format($failedRowsCount).' '.str('row')->plural($failedRowsCount).' failed to import.'; } return $body; @@ -259,7 +267,7 @@ class ProductionQuantityImporter extends Importer 'line_id' => $this->resolveLineId($row['line']), 'shift_id' => $this->resolveShiftId($row['shift']), 'plant_id' => $this->resolvePlantId($row['plant']), - 'updated_at' => $row['updated_at'] + 'updated_at' => $row['updated_at'], ]); } finally { // Always disable flag even if errors occur diff --git a/app/Filament/Imports/QualityValidationImporter.php b/app/Filament/Imports/QualityValidationImporter.php index b4a1dfd..80234cf 100644 --- a/app/Filament/Imports/QualityValidationImporter.php +++ b/app/Filament/Imports/QualityValidationImporter.php @@ -14,7 +14,6 @@ use Filament\Actions\Imports\ImportColumn; use Filament\Actions\Imports\Importer; use Filament\Actions\Imports\Models\Import; use Filament\Facades\Filament; -use Illuminate\Validation\Rule; use Str; class QualityValidationImporter extends Importer @@ -35,16 +34,16 @@ class QualityValidationImporter extends Importer ->exampleHeader('Item Code') ->example('123456') ->label('Item Code'), - // ->relationship( - // name: 'stickerMaster', - // resolveUsing: function ($state) { - // $state = trim($state); - // $item = Item::where('code', $state)->first(); - // return $item - // ? StickerMaster::where('item_id', $item->id)->value('id') - // : null; - // } - // ), + // ->relationship( + // name: 'stickerMaster', + // resolveUsing: function ($state) { + // $state = trim($state); + // $item = Item::where('code', $state)->first(); + // return $item + // ? StickerMaster::where('item_id', $item->id)->value('id') + // : null; + // } + // ), ImportColumn::make('production_order') ->requiredMapping() ->exampleHeader('Production Order') @@ -101,6 +100,11 @@ class QualityValidationImporter extends Importer ->exampleHeader('Name Plate PumpSet') ->example('1') ->label('Name Plate PumpSet'), + ImportColumn::make('warranty_card') + ->requiredMapping() + ->exampleHeader('Warranty Card') + ->example('1') + ->label('Warranty Card'), ImportColumn::make('tube_sticker_motor') ->requiredMapping() ->exampleHeader('Tube Sticker Motor') @@ -116,11 +120,6 @@ class QualityValidationImporter extends Importer ->exampleHeader('Tube Sticker PumpSet') ->example('1') ->label('Tube Sticker PumpSet'), - ImportColumn::make('warranty_card') - ->requiredMapping() - ->exampleHeader('Warranty Card') - ->example('1') - ->label('Warranty Card'), ImportColumn::make('part_validation1') ->requiredMapping() ->exampleHeader('Part Validation 1') @@ -156,14 +155,14 @@ class QualityValidationImporter extends Importer ->exampleHeader('Line Name') ->example('4 inch pump line') ->label('Line Name') - ->relationship(resolveUsing:'name') + ->relationship(resolveUsing: 'name') ->rules(['required']), ImportColumn::make('plant') ->requiredMapping() - ->exampleHeader('Plant Name') - ->example('Ransar Industries-I') - ->label('Plant Name') - ->relationship(resolveUsing:'name') + ->exampleHeader('Plant Code') + ->example('1000') + ->label('Plant Code') + ->relationship(resolveUsing: 'code') ->rules(['required']), ImportColumn::make('updated_at') ->requiredMapping() @@ -183,35 +182,41 @@ class QualityValidationImporter extends Importer public function resolveRecord(): ?QualityValidation { $warnMsg = []; - $plant = Plant::where('name', $this->data['plant'])->first(); + $plantCod = $this->data['plant']; + $plant = null; $line = null; $stickMaster = 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(); - $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') ->whereHas('item', function ($query) use ($uniqueCode, $plant) { $query->where('code', $uniqueCode)->where('plant_id', $plant->id); })->value('id'); } - if (!$line) { - $warnMsg[] = "Line not found"; + if (! $line) { + $warnMsg[] = 'Line not found'; } - if (!$stickMaster) { - $warnMsg[] = "Sticker item code not found"; + if (! $stickMaster) { + $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) { - $warnMsg[] = "Invalid production order found"; + 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'; } - if (!ctype_alnum($this->data['serial_number']) || Str::length($this->data['serial_number']) < 9) { - $warnMsg[] = "Invalid serial number found"; + if (! ctype_alnum($this->data['serial_number']) || Str::length($this->data['serial_number']) < 9) { + $warnMsg[] = 'Invalid serial number found'; } // dd($stickMaster); @@ -220,13 +225,13 @@ class QualityValidationImporter extends Importer // } $user = User::where('name', $this->data['operator_id'])->first(); - if (!$user) { - $warnMsg[] = "Operator ID not found"; + if (! $user) { + $warnMsg[] = 'Operator ID not found'; } $fromDate = $this->data['created_at']; $toDate = $this->data['updated_at']; - $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' $fdateTime = null; $tdateTime = null; @@ -252,14 +257,14 @@ class QualityValidationImporter extends Importer } // $fDateOnly = ''; - if (!isset($fdateTime)) { + if (! isset($fdateTime)) { // throw new \Exception('Invalid date time format'); $warnMsg[] = "Invalid 'Created DateTime' format. Expected DD-MM-YYYY HH:MM:SS"; } // else { // $fDateOnly = $fdateTime->toDateString(); // } - if (!isset($tdateTime)) { + if (! isset($tdateTime)) { $warnMsg[] = "Invalid 'Updated DateTime' format. Expected DD-MM-YYYY HH:MM:SS"; } @@ -275,41 +280,41 @@ class QualityValidationImporter extends Importer // $warnMsg[] = "Invalid 'Updated DateTime' format. Expected DD-MM-YYYY HH:MM:SS"; // } - if (!empty($warnMsg)) { + if (! empty($warnMsg)) { throw new RowImportFailedException(implode(', ', $warnMsg)); } QualityValidation::updateOrCreate([ 'plant_id' => $plant->id, - 'sticker_master_id' => $stickMaster,//->id - 'serial_number' => $this->data['serial_number'] + 'sticker_master_id' => $stickMaster, // ->id + 'serial_number' => $this->data['serial_number'], ], - [ - 'line_id' => $line->id, - 'uom' => $this->data['uom'], - 'production_order' => $this->data['production_order'], - 'serial_number_motor' => $this->data['serial_number_motor'], - 'serial_number_pump' => $this->data['serial_number_pump'], - 'serial_number_pumpset' => $this->data['serial_number_pumpset'], - 'pack_slip_motor' => $this->data['pack_slip_motor'], - 'pack_slip_pump' => $this->data['pack_slip_pump'], - 'pack_slip_pumpset' => $this->data['pack_slip_pumpset'], - 'name_plate_motor' => $this->data['name_plate_motor'], - 'name_plate_pump' => $this->data['name_plate_pump'], - 'name_plate_pumpset' => $this->data['name_plate_pumpset'], - 'tube_sticker_motor' => $this->data['tube_sticker_motor'], - 'tube_sticker_pump' => $this->data['tube_sticker_pump'], - 'tube_sticker_pumpset' => $this->data['tube_sticker_pumpset'], - 'warranty_card' => $this->data['warranty_card'], - 'part_validation1' => $this->data['part_validation1'], - 'part_validation2' => $this->data['part_validation2'], - 'part_validation3' => $this->data['part_validation3'], - 'part_validation4' => $this->data['part_validation4'], - 'part_validation5' => $this->data['part_validation5'], - 'created_at' => $fdateTime->format('Y-m-d H:i:s'),//$this->data['created_at'], - 'updated_at' => $tdateTime->format('Y-m-d H:i:s'),//$this->data['updated_at'], - 'operator_id' => $this->data['operator_id'], - ]); + [ + 'line_id' => $line->id, + 'uom' => $this->data['uom'], + 'production_order' => $this->data['production_order'], + 'serial_number_motor' => $this->data['serial_number_motor'], + 'serial_number_pump' => $this->data['serial_number_pump'], + 'serial_number_pumpset' => $this->data['serial_number_pumpset'], + 'pack_slip_motor' => $this->data['pack_slip_motor'], + 'pack_slip_pump' => $this->data['pack_slip_pump'], + 'pack_slip_pumpset' => $this->data['pack_slip_pumpset'], + 'name_plate_motor' => $this->data['name_plate_motor'], + 'name_plate_pump' => $this->data['name_plate_pump'], + 'name_plate_pumpset' => $this->data['name_plate_pumpset'], + 'tube_sticker_motor' => $this->data['tube_sticker_motor'], + 'tube_sticker_pump' => $this->data['tube_sticker_pump'], + 'tube_sticker_pumpset' => $this->data['tube_sticker_pumpset'], + 'warranty_card' => $this->data['warranty_card'], + 'part_validation1' => $this->data['part_validation1'], + 'part_validation2' => $this->data['part_validation2'], + 'part_validation3' => $this->data['part_validation3'], + 'part_validation4' => $this->data['part_validation4'], + 'part_validation5' => $this->data['part_validation5'], + 'created_at' => $fdateTime->format('Y-m-d H:i:s'), // $this->data['created_at'], + 'updated_at' => $tdateTime->format('Y-m-d H:i:s'), // $this->data['updated_at'], + 'operator_id' => $this->data['operator_id'], + ]); return null; // return QualityValidation::firstOrNew([ @@ -322,10 +327,10 @@ class QualityValidationImporter extends Importer public static function getCompletedNotificationBody(Import $import): string { - $body = 'Your quality validation import has completed and ' . number_format($import->successful_rows) . ' ' . str('row')->plural($import->successful_rows) . ' imported.'; + $body = 'Your quality validation import has completed and '.number_format($import->successful_rows).' '.str('row')->plural($import->successful_rows).' imported.'; if ($failedRowsCount = $import->getFailedRowsCount()) { - $body .= ' ' . number_format($failedRowsCount) . ' ' . str('row')->plural($failedRowsCount) . ' failed to import.'; + $body .= ' '.number_format($failedRowsCount).' '.str('row')->plural($failedRowsCount).' failed to import.'; } return $body; diff --git a/app/Filament/Imports/ReworkLocatorInvoiceValidationImporter.php b/app/Filament/Imports/ReworkLocatorInvoiceValidationImporter.php index 730c225..3149167 100644 --- a/app/Filament/Imports/ReworkLocatorInvoiceValidationImporter.php +++ b/app/Filament/Imports/ReworkLocatorInvoiceValidationImporter.php @@ -134,55 +134,51 @@ class ReworkLocatorInvoiceValidationImporter extends Importer $updatedBy = $this->data['updated_by']; $reworkedBy = $this->data['reworked_by']; - 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', $this->data['plant'])->first(); - if (!$plant) { - $warnMsg[] = "Plant not found"; - } - else - { - if (Str::length($invoiceNo) < 5 || !ctype_alnum($invoiceNo)) { - $warnMsg[] = "Invalid invoice number 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(); + if (! $plant) { + $warnMsg[] = 'Plant not found'; + } else { + if (Str::length($invoiceNo) < 5 || ! ctype_alnum($invoiceNo)) { + $warnMsg[] = 'Invalid invoice number found'; } - if (Str::length($serialNo) < 9 || Str::length($serialNo) > 20 || !ctype_alnum($serialNo)) { - $warnMsg[] = "Invalid serial number found"; + if (Str::length($serialNo) < 9 || Str::length($serialNo) > 20 || ! ctype_alnum($serialNo)) { + $warnMsg[] = 'Invalid serial number found'; } 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) { - $warnMsg[] = "Invalid locator number found"; + $warnMsg[] = 'Invalid locator number found'; } if ($scannedStat != 'Scanned') { - $warnMsg[] = "Invalid scanned status found"; + $warnMsg[] = 'Invalid scanned status found'; } if ($uploadStat != 'Y' && $uploadStat != 'N') { - $warnMsg[] = "Invalid upload status found"; + $warnMsg[] = 'Invalid upload status found'; } $created = User::where('name', $createdBy)->first(); - if (!$created) { - $warnMsg[] = "Created by not found"; + if (! $created) { + $warnMsg[] = 'Created by not found'; } $scanned = User::where('name', $scannedBy)->first(); - if (!$scanned) { - $warnMsg[] = "Scanned by not found"; + if (! $scanned) { + $warnMsg[] = 'Scanned by not found'; } if (Str::length($updatedBy) > 0) { $updated = User::where('name', $updatedBy)->first(); - if (!$updated) { - $warnMsg[] = "Updated by not found"; + if (! $updated) { + $warnMsg[] = 'Updated by not found'; } } $reworked = User::where('name', $reworkedBy)->first(); - if (!$reworked) { - $warnMsg[] = "Reworked by not found"; + if (! $reworked) { + $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' foreach ($formats as $format) { try { @@ -194,7 +190,7 @@ class ReworkLocatorInvoiceValidationImporter extends Importer } } - if (!isset($cDateTime)) { + if (! isset($cDateTime)) { // throw new \Exception('Invalid date time format'); $warnMsg[] = "Invalid 'Created DateTime' format. Expected DD-MM-YYYY HH:MM:SS"; } @@ -209,7 +205,7 @@ class ReworkLocatorInvoiceValidationImporter extends Importer } } - if (!isset($sDateTime)) { + if (! isset($sDateTime)) { $warnMsg[] = "Invalid 'Scanned DateTime' format. Expected DD-MM-YYYY HH:MM:SS"; } @@ -223,11 +219,9 @@ class ReworkLocatorInvoiceValidationImporter extends Importer } } - if (!isset($uDateTime)) { + if (! isset($uDateTime)) { $warnMsg[] = "Invalid 'Updated DateTime' format. Expected DD-MM-YYYY HH:MM:SS"; - } - else - { + } else { if (isset($cDateTime) && isset($uDateTime)) { if ($cDateTime->greaterThan($uDateTime)) { $warnMsg[] = "'Created DataTime' is greater than 'Updated DateTime'."; @@ -245,11 +239,9 @@ class ReworkLocatorInvoiceValidationImporter extends Importer } } - if (!isset($rDateTime)) { + if (! isset($rDateTime)) { $warnMsg[] = "Invalid 'Reworked DateTime' format. Expected DD-MM-YYYY HH:MM:SS"; - } - else - { + } else { if (isset($cDateTime) && isset($rDateTime)) { if ($cDateTime->greaterThan($rDateTime)) { $warnMsg[] = "'Created DataTime' is greater than 'Reworked DateTime'."; @@ -260,10 +252,10 @@ class ReworkLocatorInvoiceValidationImporter extends Importer } // if (!is_numeric($locatorQuantity) || $locatorQuantity < 0 || $locatorQuantity > 2) { - // $warnMsg[] = "Invalid locator quantity found"; + // $warnMsg[] = "Invalid locator quantity found"; // } - if (!empty($warnMsg)) { + if (! empty($warnMsg)) { throw new RowImportFailedException(implode(', ', $warnMsg)); } @@ -283,10 +275,11 @@ class ReworkLocatorInvoiceValidationImporter extends Importer 'created_by' => $createdBy, 'scanned_by' => $scannedBy, 'updated_by' => $updatedBy, - 'reworked_by' => $reworkedBy - ] - ); - return null; + 'reworked_by' => $reworkedBy, + ] + ); + + return null; // // return ReworkLocatorInvoiceValidation::firstOrNew([ // // // Update existing records, matching them by `$this->data['column_name']` // // 'email' => $this->data['email'], @@ -297,10 +290,10 @@ class ReworkLocatorInvoiceValidationImporter extends Importer public static function getCompletedNotificationBody(Import $import): string { - $body = 'Your rework locator invoice validation import has completed and ' . number_format($import->successful_rows) . ' ' . str('row')->plural($import->successful_rows) . ' imported.'; + $body = 'Your rework locator invoice validation import has completed and '.number_format($import->successful_rows).' '.str('row')->plural($import->successful_rows).' imported.'; if ($failedRowsCount = $import->getFailedRowsCount()) { - $body .= ' ' . number_format($failedRowsCount) . ' ' . str('row')->plural($failedRowsCount) . ' failed to import.'; + $body .= ' '.number_format($failedRowsCount).' '.str('row')->plural($failedRowsCount).' failed to import.'; } return $body; diff --git a/app/Filament/Imports/ShiftImporter.php b/app/Filament/Imports/ShiftImporter.php index 4b43b0e..f3e3055 100644 --- a/app/Filament/Imports/ShiftImporter.php +++ b/app/Filament/Imports/ShiftImporter.php @@ -18,79 +18,89 @@ class ShiftImporter extends Importer public static function getColumns(): array { return [ - ImportColumn::make('name') - ->requiredMapping() - ->exampleHeader('Shift Name') - ->example('Day') - ->label('Shift Name') - ->rules(['required']), - ImportColumn::make('start_time') - ->requiredMapping() - ->exampleHeader('Start Time') - ->example('08:00:00') - ->label('Start Time') - ->rules(['required']), - ImportColumn::make('duration') - ->requiredMapping() - ->numeric() - ->exampleHeader('Shift Duration') - ->example('11.30') - ->label('Shift Duration') - ->rules(['required']), - ImportColumn::make('end_time') - ->requiredMapping() - ->exampleHeader('End Time') - ->example('19:30:00') - ->label('End Time') - ->rules(['required']), - ImportColumn::make('block') - ->requiredMapping() - ->exampleHeader('Block Name') - ->example('Block A') - ->label('Block Name') - ->relationship(resolveUsing:'name') - ->rules(['required']), - ImportColumn::make('plant') - ->requiredMapping() - ->exampleHeader('Plant Name') - ->example('Ransar Industries-I') - ->label('Plant Name') - ->relationship(resolveUsing:'name') - ->rules(['required']), - ImportColumn::make('status') - ->requiredMapping() - ->exampleHeader('Active Status') - ->example('Active') - ->label('Active Status') - ->rules(['required']), + ImportColumn::make('name') + ->requiredMapping() + ->exampleHeader('Shift Name') + ->example('Day') + ->label('Shift Name') + ->rules(['required']), + ImportColumn::make('start_time') + ->requiredMapping() + ->exampleHeader('Start Time') + ->example('08:00:00') + ->label('Start Time') + ->rules(['required']), + ImportColumn::make('duration') + ->requiredMapping() + ->numeric() + ->exampleHeader('Shift Duration') + ->example('11.30') + ->label('Shift Duration') + ->rules(['required']), + ImportColumn::make('end_time') + ->requiredMapping() + ->exampleHeader('End Time') + ->example('19:30:00') + ->label('End Time') + ->rules(['required']), + ImportColumn::make('block') + ->requiredMapping() + ->exampleHeader('Block Name') + ->example('Block A') + ->label('Block Name') + ->relationship(resolveUsing: 'name') + ->rules(['required']), + ImportColumn::make('plant') + ->requiredMapping() + ->exampleHeader('Plant Code') + ->example('1000') + ->label('Plant Code') + ->relationship(resolveUsing: 'code') + ->rules(['required']), + ImportColumn::make('status') + ->requiredMapping() + ->exampleHeader('Active Status') + ->example('Active') + ->label('Active Status') + ->rules(['required']), ]; } public function resolveRecord(): ?Shift { $warnMsg = []; - $plant = Plant::where('name', $this->data['plant'])->first(); - if (!$plant) { - $warnMsg[] = "Plant not found"; - } - $block = Block::where('name', $this->data['block'])->where('plant_id', $plant->id)->first(); - if (!$block) { - $warnMsg[] = "Block not found"; - } - if (Str::length($this->data['duration']) < 0 || !is_numeric($this->data['duration'])) { - $warnMsg[] = "Invalid duration found"; - } - if (Str::length($this->data['start_time']) < 0) { - $warnMsg[] = "Invalid start time found"; - } - if (Str::length($this->data['end_time']) < 0) { - $warnMsg[] = "Invalid end time found"; - } - if (Str::length($this->data['status']) < 0 || $this->data['status'] != 'Active') { - $warnMsg[] = "Invalid shift status found"; + $plantCod = $this->data['plant']; + $plant = null; + $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 (!empty($warnMsg)) { + if (! $plant) { + $warnMsg[] = 'Plant not found'; + } else { + $block = Block::where('name', $this->data['block'])->where('plant_id', $plant->id)->first(); + } + + if (! $block) { + $warnMsg[] = 'Block not found'; + } + if (Str::length($this->data['duration']) < 0 || ! is_numeric($this->data['duration'])) { + $warnMsg[] = 'Invalid duration found'; + } + if (Str::length($this->data['start_time']) < 0) { + $warnMsg[] = 'Invalid start time found'; + } + if (Str::length($this->data['end_time']) < 0) { + $warnMsg[] = 'Invalid end time found'; + } + if (Str::length($this->data['status']) < 0 || $this->data['status'] != 'Active') { + $warnMsg[] = 'Invalid shift status found'; + } + + if (! empty($warnMsg)) { throw new RowImportFailedException(implode(', ', $warnMsg)); } @@ -105,8 +115,9 @@ class ShiftImporter extends Importer 'start_time' => $this->data['start_time'], 'duration' => $this->data['duration'], 'end_time' => $this->data['end_time'], - 'status' => $this->data['status'] + 'status' => $this->data['status'], ]); + return $shift; } else { // Safe to create new @@ -117,7 +128,7 @@ class ShiftImporter extends Importer 'start_time' => $this->data['start_time'], 'duration' => $this->data['duration'], 'end_time' => $this->data['end_time'], - 'status' => $this->data['status'] + 'status' => $this->data['status'], ]); } // return Shift::firstOrNew([ @@ -130,10 +141,10 @@ class ShiftImporter extends Importer public static function getCompletedNotificationBody(Import $import): string { - $body = 'Your shift import has completed and ' . number_format($import->successful_rows) . ' ' . str('row')->plural($import->successful_rows) . ' imported.'; + $body = 'Your shift import has completed and '.number_format($import->successful_rows).' '.str('row')->plural($import->successful_rows).' imported.'; if ($failedRowsCount = $import->getFailedRowsCount()) { - $body .= ' ' . number_format($failedRowsCount) . ' ' . str('row')->plural($failedRowsCount) . ' failed to import.'; + $body .= ' '.number_format($failedRowsCount).' '.str('row')->plural($failedRowsCount).' failed to import.'; } return $body; diff --git a/app/Filament/Imports/StickerPrintingImporter.php b/app/Filament/Imports/StickerPrintingImporter.php index 17bf171..e70e51d 100644 --- a/app/Filament/Imports/StickerPrintingImporter.php +++ b/app/Filament/Imports/StickerPrintingImporter.php @@ -2,15 +2,14 @@ namespace App\Filament\Imports; +use App\Models\Plant; use App\Models\StickerPrinting; +use Filament\Actions\Imports\Exceptions\RowImportFailedException; use Filament\Actions\Imports\ImportColumn; use Filament\Actions\Imports\Importer; 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 Str; class StickerPrintingImporter extends Importer { @@ -49,33 +48,29 @@ class StickerPrintingImporter extends Importer // ]); $warnMsg = []; - $plant = Plant::where('code', $this->data['plant'])->first(); - - 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!"); - } - + $plantCod = $this->data['plant']; + $plant = null; $serial = $this->data['serial_number']; - // --- Check duplicate in DB --- - $existsInDB = StickerPrinting::where('plant_id', $plant->id) - ->where('serial_number', $serial) - ->first(); - - if ($existsInDB) { - //throw new RowImportFailedException("Serial number '{$serial}' already exists in DB for this plant!"); - $warnMsg[] = "Serial number '{$serial}' already exists in DB for this 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!'; + } } - if (!empty($warnMsg)) { + if (Str::length($serial) < 9 || ! ctype_alnum($serial)) { + $warnMsg[] = 'Invalid serial number found'; + } 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)) { throw new RowImportFailedException(implode(', ', $warnMsg)); } @@ -84,21 +79,21 @@ class StickerPrintingImporter extends Importer 'reference_number' => $this->data['reference_number'], 'serial_number' => $this->data['serial_number'], 'created_at' => now(), - 'updated_at' =>now(), + 'updated_at' => now(), 'created_by' => Filament::auth()->user()?->name, ]); return null; - //return new StickerPrinting(); + // return new StickerPrinting(); } public static function getCompletedNotificationBody(Import $import): string { - $body = 'Your sticker printing import has completed and ' . number_format($import->successful_rows) . ' ' . str('row')->plural($import->successful_rows) . ' imported.'; + $body = 'Your sticker printing import has completed and '.number_format($import->successful_rows).' '.str('row')->plural($import->successful_rows).' imported.'; if ($failedRowsCount = $import->getFailedRowsCount()) { - $body .= ' ' . number_format($failedRowsCount) . ' ' . str('row')->plural($failedRowsCount) . ' failed to import.'; + $body .= ' '.number_format($failedRowsCount).' '.str('row')->plural($failedRowsCount).' failed to import.'; } return $body; diff --git a/app/Filament/Imports/TestingPanelReadingImporter.php b/app/Filament/Imports/TestingPanelReadingImporter.php index 5f107fa..ccc3882 100644 --- a/app/Filament/Imports/TestingPanelReadingImporter.php +++ b/app/Filament/Imports/TestingPanelReadingImporter.php @@ -80,11 +80,17 @@ class TestingPanelReadingImporter extends Importer ->rules(['required']), ImportColumn::make('line') ->requiredMapping() - ->relationship() + ->relationship(resolveUsing: 'name') + ->exampleHeader('Line Name') + ->example(['4 inch pump line']) + ->label('Line Name') ->rules(['required']), ImportColumn::make('plant') ->requiredMapping() - ->relationship() + ->relationship(resolveUsing: 'code') + ->exampleHeader('Plant Code') + ->example(['1000']) + ->label('Plant Code') ->rules(['required']), ImportColumn::make('tested_by'), ImportColumn::make('updated_by'), @@ -101,15 +107,15 @@ class TestingPanelReadingImporter extends Importer // 'email' => $this->data['email'], // ]); - return new TestingPanelReading(); + return new TestingPanelReading; } public static function getCompletedNotificationBody(Import $import): string { - $body = 'Your testing panel reading import has completed and ' . number_format($import->successful_rows) . ' ' . str('row')->plural($import->successful_rows) . ' imported.'; + $body = 'Your testing panel reading import has completed and '.number_format($import->successful_rows).' '.str('row')->plural($import->successful_rows).' imported.'; if ($failedRowsCount = $import->getFailedRowsCount()) { - $body .= ' ' . number_format($failedRowsCount) . ' ' . str('row')->plural($failedRowsCount) . ' failed to import.'; + $body .= ' '.number_format($failedRowsCount).' '.str('row')->plural($failedRowsCount).' failed to import.'; } return $body; diff --git a/app/Filament/Imports/UserImporter.php b/app/Filament/Imports/UserImporter.php index 59a7d9b..fecfe8e 100644 --- a/app/Filament/Imports/UserImporter.php +++ b/app/Filament/Imports/UserImporter.php @@ -29,19 +29,19 @@ class UserImporter extends Importer ->exampleHeader('Name') ->example('RAW00001') ->label('Name') - ->rules(['required']),//, 'max:255' + ->rules(['required']), // , 'max:255' ImportColumn::make('email') ->requiredMapping() ->exampleHeader('E-Mail') ->example('RAW00001@cripumps.com') ->label('E-Mail') - ->rules(['required', 'email']),//, 'max:255' + ->rules(['required', 'email']), // , 'max:255' ImportColumn::make('password') ->requiredMapping() ->exampleHeader('Password') ->example('RAW00001') ->label('Password') - ->rules(['required']),//, 'max:255' + ->rules(['required']), // , 'max:255' ImportColumn::make('roles') ->requiredMapping() ->exampleHeader('Roles') @@ -54,65 +54,61 @@ class UserImporter extends Importer public function resolveRecord(): ?User { $warnMsg = []; + $plantCod = $this->data['plant']; $plant = null; - if (Str::length($this->data['plant']) > 0) { - 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!"; - } - else { - $plant = Plant::where('code', $this->data['plant'])->first(); - if (!$plant) { - $warnMsg[] = "Plant not found"; - } - else { - $plant = $plant->id ?? 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 { + $plant = $plant->id ?? null; } } - if (Str::length($this->data['name']) < 1) { - $warnMsg[] = "User name not found!"; + if (Str::length($this->data['name']) < 3) { + $warnMsg[] = 'Invalid user name found!'; } // || !is_numeric($this->data['code']) || !preg_match('/^[1-9]\d{3,}$/', $this->data['code']) if (Str::length($this->data['email']) < 5) { - $warnMsg[] = "Invalid email found!"; + $warnMsg[] = 'Invalid email found!'; } if (Str::length($this->data['password']) < 3) { - $warnMsg[] = "Invalid password found!"; + $warnMsg[] = 'Invalid password found!'; } // Validate roles if provided $roles = []; - if (!empty($this->data['roles'])) { + if (! empty($this->data['roles'])) { $roles = collect(explode(',', $this->data['roles'])) - ->map(fn($role) => trim($role)) + ->map(fn ($role) => trim($role)) ->filter() ->toArray(); foreach ($roles as $roleName) { - if (!Role::where('name', $roleName)->exists()) { + if (! Role::where('name', $roleName)->exists()) { $warnMsg[] = "Role : '{$roleName}' does not exist!"; } } - } - else { - $warnMsg[] = "User roles not found!"; + } else { + $warnMsg[] = 'User roles not found!'; } - if (!empty($warnMsg)) { + if (! empty($warnMsg)) { throw new RowImportFailedException(implode(', ', $warnMsg)); } $user = User::updateOrCreate([ 'email' => $this->data['email'], ], - [ - 'name' => $this->data['name'], - 'password' => $this->data['password'], - 'plant_id' => $plant, - ]); + [ + 'name' => $this->data['name'], + 'password' => $this->data['password'], + 'plant_id' => $plant, + ]); // Assign roles - if (!empty($roles)) { + if (! empty($roles)) { $user->syncRoles($roles); } @@ -122,15 +118,15 @@ class UserImporter extends Importer // 'email' => $this->data['email'], // ]); - //return new User(); + // return new User(); } public static function getCompletedNotificationBody(Import $import): string { - $body = 'Your user import has completed and ' . number_format($import->successful_rows) . ' ' . str('row')->plural($import->successful_rows) . ' imported.'; + $body = 'Your user import has completed and '.number_format($import->successful_rows).' '.str('row')->plural($import->successful_rows).' imported.'; if ($failedRowsCount = $import->getFailedRowsCount()) { - $body .= ' ' . number_format($failedRowsCount) . ' ' . str('row')->plural($failedRowsCount) . ' failed to import.'; + $body .= ' '.number_format($failedRowsCount).' '.str('row')->plural($failedRowsCount).' failed to import.'; } return $body; diff --git a/app/Filament/Imports/WeightValidationImporter.php b/app/Filament/Imports/WeightValidationImporter.php index 44fc76b..4dc32aa 100644 --- a/app/Filament/Imports/WeightValidationImporter.php +++ b/app/Filament/Imports/WeightValidationImporter.php @@ -75,10 +75,10 @@ class WeightValidationImporter extends Importer ->rules(['required']), ImportColumn::make('plant') ->requiredMapping() - ->exampleHeader('Plant Name') - ->example('Ransar Industries-I') - ->label('PLANT NAME') - ->relationship(resolveUsing: 'name') + ->exampleHeader('Plant Code') + ->example('1000') + ->label('PLANT CODE') + ->relationship(resolveUsing: 'code') ->rules(['required']), ImportColumn::make('scanned_by') ->requiredMapping() @@ -92,82 +92,95 @@ class WeightValidationImporter extends Importer public function resolveRecord(): ?WeightValidation { $warnMsg = []; - $plant = Plant::where('name', $this->data['plant'])->first(); - if (!$plant) { - $warnMsg[] = "Plant not found"; - } - $item = null; - if ($plant) { - if (Str::length($this->data['item']) < 6 || !ctype_alnum($this->data['item'])) { - $warnMsg[] = "Invalid item code found"; + $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) { + $warnMsg[] = 'Plant not found'; + } else { + $plantId = $plant->id; } - else - { - $item = Item::where('code', $this->data['item'])->where('plant_id', $plant->id)->first(); - if (!$item) { - $warnMsg[] = "Item code not found"; + } + + if (Str::length($iCode) < 6 || ! ctype_alnum($iCode)) { + $warnMsg[] = 'Invalid item code found'; + } else { + $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']; - if (Str::length($obdNum) < 8 || !ctype_alnum($obdNum)) { - $warnMsg[] = "Invalid OBD number found"; + if (Str::length($obdNum) < 8 || ! ctype_alnum($obdNum)) { + $warnMsg[] = 'Invalid OBD number found'; } $lineNum = $this->data['line_number']; - if (Str::length($lineNum) < 1 || !is_numeric($lineNum)) { - $warnMsg[] = "Invalid line number found"; + if (Str::length($lineNum) < 1 || ! is_numeric($lineNum)) { + $warnMsg[] = 'Invalid line number found'; } $batchNum = $this->data['batch_number']; - if (Str::length($batchNum) < 8 || !is_numeric($batchNum)) { - $warnMsg[] = "Invalid batch number found"; + if (Str::length($batchNum) < 8 || ! is_numeric($batchNum)) { + $warnMsg[] = 'Invalid batch number found'; } $heatNum = $this->data['heat_number']; if (Str::length($heatNum) < 4) { - $warnMsg[] = "Invalid heat number found"; + $warnMsg[] = 'Invalid heat number found'; } $actWeight = $this->data['obd_weight']; - if (Str::length($actWeight) < 1 || !is_numeric($actWeight)) { - $warnMsg[] = "Invalid actual weight found"; + if (Str::length($actWeight) < 1 || ! is_numeric($actWeight)) { + $warnMsg[] = 'Invalid actual weight found'; } $vehicleNum = $this->data['vehicle_number']; - if (Str::length($vehicleNum) < 10 || !ctype_alnum($vehicleNum)) { - $warnMsg[] = "Invalid vehicle number found"; + if (Str::length($vehicleNum) < 10 || ! ctype_alnum($vehicleNum)) { + $warnMsg[] = 'Invalid vehicle number found'; } $bundleNum = $this->data['bundle_number']; - if (Str::length($bundleNum) < 1 || !is_numeric($bundleNum)) { - $warnMsg[] = "Invalid bundle number found"; + if (Str::length($bundleNum) < 1 || ! is_numeric($bundleNum)) { + $warnMsg[] = 'Invalid bundle number found'; } $pickWeight = $this->data['picked_weight']; - if (Str::length($pickWeight) < 1 || !is_numeric($pickWeight)) { - $warnMsg[] = "Invalid picked weight found"; + if (Str::length($pickWeight) < 1 || ! is_numeric($pickWeight)) { + $warnMsg[] = 'Invalid picked weight found'; } $scanBy = $this->data['scanned_by']; - if (Str::length($scanBy) < 3 || !ctype_alnum($scanBy)) { - $warnMsg[] = "Invalid scanned by name found"; + if (Str::length($scanBy) < 3 || ! ctype_alnum($scanBy)) { + $warnMsg[] = 'Invalid scanned by name found'; } - if (!empty($warnMsg)) { + if (! empty($warnMsg)) { throw new RowImportFailedException(implode(', ', $warnMsg)); } return WeightValidation::updateOrCreate([ - 'plant_id' => $plant->id, - 'obd_number' => $obdNum, - 'line_number' => $lineNum - ], + 'plant_id' => $plantId, + 'obd_number' => $obdNum, + 'line_number' => $lineNum, + ], [ - 'item_id' => $item->id, + 'item_id' => $itemId, 'batch_number' => $batchNum, 'heat_number' => $heatNum, 'obd_weight' => $actWeight, 'vehicle_number' => $vehicleNum, 'bundle_number' => $bundleNum, 'picked_weight' => $pickWeight, - 'scanned_by' => $scanBy + 'scanned_by' => $scanBy, ] ); // return WeightValidation::firstOrNew([ @@ -180,10 +193,10 @@ class WeightValidationImporter extends Importer public static function getCompletedNotificationBody(Import $import): string { - $body = 'Your weight validation import has completed and ' . number_format($import->successful_rows) . ' ' . str('row')->plural($import->successful_rows) . ' imported.'; + $body = 'Your weight validation import has completed and '.number_format($import->successful_rows).' '.str('row')->plural($import->successful_rows).' imported.'; if ($failedRowsCount = $import->getFailedRowsCount()) { - $body .= ' ' . number_format($failedRowsCount) . ' ' . str('row')->plural($failedRowsCount) . ' failed to import.'; + $body .= ' '.number_format($failedRowsCount).' '.str('row')->plural($failedRowsCount).' failed to import.'; } return $body; diff --git a/app/Filament/Imports/WorkGroupMasterImporter.php b/app/Filament/Imports/WorkGroupMasterImporter.php index 3c38a96..e0d417b 100644 --- a/app/Filament/Imports/WorkGroupMasterImporter.php +++ b/app/Filament/Imports/WorkGroupMasterImporter.php @@ -20,22 +20,22 @@ class WorkGroupMasterImporter extends Importer return [ ImportColumn::make('plant') ->requiredMapping() - ->exampleHeader('Plant Name') - ->example('Ransar Industries-I') - ->label('Plant Name') - ->relationship(resolveUsing:'name') + ->exampleHeader('Plant Code') + ->example('1000') + ->label('Plant Code') + ->relationship(resolveUsing: 'code') ->rules(['required']), ImportColumn::make('name') ->requiredMapping() - ->exampleHeader('Name') + ->exampleHeader('Work Group Name') ->example('RMGCEABC') - ->label('Name') + ->label('Work Group Name') ->rules(['required']), ImportColumn::make('description') ->requiredMapping() - ->exampleHeader('Description') + ->exampleHeader('Work Group Description') ->example('Testing Model 1') - ->label('Description') + ->label('Work Group Description') ->rules(['required']), ImportColumn::make('operation_number') ->requiredMapping() @@ -52,8 +52,6 @@ class WorkGroupMasterImporter extends Importer ]; } - - public function resolveRecord(): ?WorkGroupMaster { // return WorkGroupMaster::firstOrNew([ @@ -61,75 +59,81 @@ class WorkGroupMasterImporter extends Importer // 'email' => $this->data['email'], // ]); $warnMsg = []; - $plant = Plant::where('name', $this->data['plant'])->first(); - if (!$plant) { - $warnMsg[] = "Plant not found"; + $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) { + $warnMsg[] = 'Plant not found'; + } else { + $plantId = $plant->id; + } } - if (Str::length($this->data['name']) <= 0) { //|| !ctype_alnum($this->data['description']) - $warnMsg[] = "Invalid name found"; + if (Str::length($this->data['name']) <= 0) { // || !ctype_alnum($this->data['description']) + $warnMsg[] = 'Invalid work group name found'; } if (Str::length(trim($this->data['description'])) <= 0) { - $warnMsg[] = "Invalid description found"; + $warnMsg[] = 'Invalid work group description found'; } $desc = trim($this->data['description']); 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) { - $warnMsg[] = "Invalid operation number found"; + $warnMsg[] = 'Invalid operation number found'; } - if(!is_numeric($this->data['operation_number'])) - { - $warnMsg[] = "Invalid operation number found must be numeric"; + if (! is_numeric($this->data['operation_number'])) { + $warnMsg[] = 'Invalid operation number found must be numeric'; } $user = User::where('name', $this->data['created_by'])->first(); - if (!$user) { - $warnMsg[] = "Operator ID not found"; + if (! $user) { + $warnMsg[] = 'Operator ID not found'; } - if (!empty($warnMsg)) { + if (! empty($warnMsg)) { throw new RowImportFailedException(implode(', ', $warnMsg)); - } - else - { - //Check (plant_id, name) - $existingByName = WorkGroupMaster::where('plant_id', $plant->id) + } else { + // Check (plant_id, name) + $existingByName = WorkGroupMaster::where('plant_id', $plantId) ->where('name', $this->data['name']) ->first(); 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) - $existingByOpNum = WorkGroupMaster::where('plant_id', $plant->id) + // Check (plant_id, operation_number) + $existingByOpNum = WorkGroupMaster::where('plant_id', $plantId) ->where('operation_number', $this->data['operation_number']) ->where('name', $this->data['name']) ->first(); 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) - $existingByOperator = WorkGroupMaster::where('plant_id', $plant->id) + // Check (plant_id) + $existingByOperator = WorkGroupMaster::where('plant_id', $plantId) ->where('name', $this->data['name']) ->first(); 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([ - 'plant_id' => $plant->id, + 'plant_id' => $plantId, 'name' => $this->data['name'], 'description' => $this->data['description'], 'operation_number' => $this->data['operation_number'], @@ -138,15 +142,15 @@ class WorkGroupMasterImporter extends Importer return null; - //return new WorkGroupMaster(); + // return new WorkGroupMaster(); } public static function getCompletedNotificationBody(Import $import): string { - $body = 'Your work group master import has completed and ' . number_format($import->successful_rows) . ' ' . str('row')->plural($import->successful_rows) . ' imported.'; + $body = 'Your work group master import has completed and '.number_format($import->successful_rows).' '.str('row')->plural($import->successful_rows).' imported.'; if ($failedRowsCount = $import->getFailedRowsCount()) { - $body .= ' ' . number_format($failedRowsCount) . ' ' . str('row')->plural($failedRowsCount) . ' failed to import.'; + $body .= ' '.number_format($failedRowsCount).' '.str('row')->plural($failedRowsCount).' failed to import.'; } return $body; diff --git a/app/Filament/Resources/CharacteristicValueResource.php b/app/Filament/Resources/CharacteristicValueResource.php index f3a0925..5f04806 100644 --- a/app/Filament/Resources/CharacteristicValueResource.php +++ b/app/Filament/Resources/CharacteristicValueResource.php @@ -5,26 +5,25 @@ namespace App\Filament\Resources; use App\Filament\Exports\CharacteristicValueExporter; use App\Filament\Imports\CharacteristicValueImporter; use App\Filament\Resources\CharacteristicValueResource\Pages; -use App\Filament\Resources\CharacteristicValueResource\RelationManagers; use App\Models\CharacteristicValue; use App\Models\Item; use App\Models\Line; use App\Models\Machine; use App\Models\Plant; +use Filament\Facades\Filament; use Filament\Forms; +use Filament\Forms\Components\DateTimePicker; +use Filament\Forms\Components\Select; +use Filament\Forms\Components\TextInput; use Filament\Forms\Form; use Filament\Resources\Resource; use Filament\Tables; +use Filament\Tables\Actions\ExportAction; +use Filament\Tables\Actions\ImportAction; +use Filament\Tables\Filters\Filter; use Filament\Tables\Table; use Illuminate\Database\Eloquent\Builder; 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 { @@ -65,7 +64,7 @@ class CharacteristicValueResource extends Resource Forms\Components\Select::make('line_id') ->label('Line') ->options(function (callable $get) { - if (!$get('plant_id')) { + if (! $get('plant_id')) { return []; } @@ -86,7 +85,7 @@ class CharacteristicValueResource extends Resource Forms\Components\Select::make('item_id') ->label('Item') ->options(function (callable $get) { - if (!$get('plant_id') || !$get('line_id')) { + if (! $get('plant_id') || ! $get('line_id')) { return []; } @@ -107,7 +106,7 @@ class CharacteristicValueResource extends Resource Forms\Components\Select::make('machine_id') ->label('Machine') ->options(function (callable $get) { - if (!$get('plant_id') || !$get('line_id') || !$get('item_id')) { + if (! $get('plant_id') || ! $get('line_id') || ! $get('item_id')) { return []; } @@ -192,7 +191,7 @@ class CharacteristicValueResource extends Resource ->label('Status') ->options([ 'Ok' => 'OK', - 'NotOk' => 'Not Ok' + 'NotOk' => 'Not Ok', ]) ->reactive() ->required(), @@ -287,186 +286,198 @@ class CharacteristicValueResource extends Resource // ]) ->filters([ - Tables\Filters\TrashedFilter::make(), - Filter::make('advanced_filters') - ->label('Advanced Filters') - ->form([ - Select::make('Plant') - ->label('Select Plant') - ->nullable() - ->options(function (callable $get) { - $userHas = Filament::auth()->user()->plant_id; - return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); - }) - ->reactive() - ->afterStateUpdated(function ($state, callable $set, callable $get) { - $set('Item', null); - }), - Select::make('Line') - ->label('Select Line') - ->nullable() - ->options(function (callable $get) { + Tables\Filters\TrashedFilter::make(), + Filter::make('advanced_filters') + ->label('Advanced Filters') + ->form([ + Select::make('Plant') + ->label('Select Plant') + ->nullable() + ->options(function (callable $get) { + $userHas = Filament::auth()->user()->plant_id; + + return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); + }) + ->reactive() + ->afterStateUpdated(function ($state, callable $set, callable $get) { + $set('Item', null); + }), + Select::make('Line') + ->label('Select Line') + ->nullable() + ->options(function (callable $get) { $plantId = $get('Plant'); - if(empty($plantId)) { + if (empty($plantId)) { return []; } return Line::where('plant_id', $plantId)->pluck('name', 'id'); - //return $plantId ? 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) { - $set('Item', null); - }), - Select::make('Item') - ->label('Item Code') - ->nullable() - ->searchable() - ->options(function (callable $get) { + ->reactive() + ->afterStateUpdated(function ($state, callable $set, callable $get) { + $set('Item', null); + }), + Select::make('Item') + ->label('Item Code') + ->nullable() + ->searchable() + ->options(function (callable $get) { $plantId = $get('Plant'); - if(empty($plantId)) { + if (empty($plantId)) { return []; } return Item::where('plant_id', $plantId)->pluck('code', 'id'); - //return $plantId ? 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) { - $set('process_order', null); - }), - Select::make('Machine') - ->label('Select Machine') - ->nullable() - ->options(function (callable $get) { + ->reactive() + ->afterStateUpdated(function ($state, callable $set, callable $get) { + $set('process_order', null); + }), + Select::make('Machine') + ->label('Select Machine') + ->nullable() + ->options(function (callable $get) { $plantId = $get('Plant'); $lineId = $get('Line'); - if(empty($plantId) || empty($lineId)) { + if (empty($plantId) || empty($lineId)) { return []; } return Machine::where('plant_id', $plantId)->where('line_id', $lineId)->pluck('work_center', 'id'); - //return $plantId ? 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) { - $set('process_order', null); - }), - TextInput::make('process_order') - ->label('Process Order') - ->placeholder('Enter Process Order'), - TextInput::make('coil_number') - ->label('Coil Number') - ->placeholder(placeholder: 'Enter Coil Number'), - Select::make('status') - ->label('Status') - ->options([ - 'Ok' => 'OK', - 'NotOk' => 'Not Ok' - ]), - DateTimePicker::make(name: 'created_from') - ->label('Created From') - ->placeholder(placeholder: 'Select From DateTime') - ->reactive() - ->native(false), - DateTimePicker::make('created_to') - ->label('Created To') - ->placeholder(placeholder: 'Select To DateTime') - ->reactive() - ->native(false), - ]) - ->query(function ($query, array $data) { - // Hide all records initially if no filters are applied - if (empty($data['Plant']) && empty($data['Line']) && empty($data['Item']) && empty($data['Machine']) && empty($data['process_order']) && empty($data['coil_number']) && empty($data['status']) && empty($data['created_from']) && empty($data['created_to'])) { - return $query->whereRaw('1 = 0'); - } + ->reactive() + ->afterStateUpdated(function ($state, callable $set, callable $get) { + $set('process_order', null); + }), + TextInput::make('process_order') + ->label('Process Order') + ->placeholder('Enter Process Order'), + TextInput::make('coil_number') + ->label('Coil Number') + ->placeholder(placeholder: 'Enter Coil Number'), + Select::make('status') + ->label('Status') + ->options([ + 'Ok' => 'OK', + 'NotOk' => 'Not Ok', + ]), + DateTimePicker::make(name: 'created_from') + ->label('Created From') + ->placeholder(placeholder: 'Select From DateTime') + ->reactive() + ->native(false), + DateTimePicker::make('created_to') + ->label('Created To') + ->placeholder(placeholder: 'Select To DateTime') + ->reactive() + ->native(false), + ]) + ->query(function ($query, array $data) { + // Hide all records initially if no filters are applied + if (empty($data['Plant']) && empty($data['Line']) && empty($data['Item']) && empty($data['Machine']) && empty($data['process_order']) && empty($data['coil_number']) && empty($data['status']) && empty($data['created_from']) && empty($data['created_to'])) { + return $query->whereRaw('1 = 0'); + } - if (!empty($data['Plant'])) { - $query->where('plant_id', $data['Plant']); - } + if (! empty($data['Plant'])) { + $query->where('plant_id', $data['Plant']); + } else { + $userHas = Filament::auth()->user()->plant_id; - if (!empty($data['Line'])) { - $query->where('line_id', $data['Line']); - } + if ($userHas && strlen($userHas) > 0) { + return $query->whereRaw('1 = 0'); + } + } - if (!empty($data['Item'])) { - $query->where('item_id', $data['Item']); - } + if (! empty($data['Line'])) { + $query->where('line_id', $data['Line']); + } - if (!empty($data['Machine'])) { - $query->where('machine_id', $data['Machine']); - } + if (! empty($data['Item'])) { + $query->where('item_id', $data['Item']); + } - if (!empty($data['process_order'])) { - $query->where('process_order', $data['process_order']); - } + if (! empty($data['Machine'])) { + $query->where('machine_id', $data['Machine']); + } - if (!empty($data['coil_number'])) { - $query->where('coil_number', $data['coil_number']); - } + if (! empty($data['process_order'])) { + $query->where('process_order', $data['process_order']); + } - if (!empty($data['status'])) { - $query->where('status', $data['status']); - } + if (! empty($data['coil_number'])) { + $query->where('coil_number', $data['coil_number']); + } - if (!empty($data['created_from'])) { - $query->where('created_at', '>=', $data['created_from']); - } + if (! empty($data['status'])) { + $query->where('status', $data['status']); + } - if (!empty($data['created_to'])) { - $query->where('created_at', '<=', $data['created_to']); - } + if (! empty($data['created_from'])) { + $query->where('created_at', '>=', $data['created_from']); + } + if (! empty($data['created_to'])) { + $query->where('created_at', '<=', $data['created_to']); + } - //$query->orderBy('created_at', 'asc'); - }) - ->indicateUsing(function (array $data) { - $indicators = []; + // $query->orderBy('created_at', 'asc'); + }) + ->indicateUsing(function (array $data) { + $indicators = []; - if (!empty($data['Plant'])) { - $indicators[] = 'Plant: ' . Plant::where('id', $data['Plant'])->value('name'); - } + if (! empty($data['Plant'])) { + $indicators[] = 'Plant: '.Plant::where('id', $data['Plant'])->value('name'); + } else { + $userHas = Filament::auth()->user()->plant_id; - if (!empty($data['Line'])) { - $indicators[] = 'Line: ' . Line::where('id', $data['Line'])->value('name'); - } + if ($userHas && strlen($userHas) > 0) { + return 'Plant: Choose plant to filter records.'; + } + } - if (!empty($data['Item'])) { - $indicators[] = 'Item: ' . Item::where('id', $data['Item'])->value('code'); - } + if (! empty($data['Line'])) { + $indicators[] = 'Line: '.Line::where('id', $data['Line'])->value('name'); + } - if (!empty($data['Machine'])) { - $indicators[] = 'Machine: ' . Machine::where('id', $data['Machine'])->value('work_center'); - } + if (! empty($data['Item'])) { + $indicators[] = 'Item: '.Item::where('id', $data['Item'])->value('code'); + } - if (!empty($data['process_order'])) { - $indicators[] = 'Process Order: ' . $data['process_order']; - } + if (! empty($data['Machine'])) { + $indicators[] = 'Machine: '.Machine::where('id', $data['Machine'])->value('work_center'); + } - if (!empty($data['coil_number'])) { - $indicators[] = 'Coil Number: ' . $data['coil_number']; - } + if (! empty($data['process_order'])) { + $indicators[] = 'Process Order: '.$data['process_order']; + } - if (!empty($data['status'])) { - $indicators[] = 'Status: ' . $data['status']; - } + if (! empty($data['coil_number'])) { + $indicators[] = 'Coil Number: '.$data['coil_number']; + } - if (!empty($data['created_from'])) { - $indicators[] = 'From: ' . $data['created_from']; - } + if (! empty($data['status'])) { + $indicators[] = 'Status: '.$data['status']; + } - if (!empty($data['created_to'])) { - $indicators[] = 'To: ' . $data['created_to']; - } + if (! empty($data['created_from'])) { + $indicators[] = 'From: '.$data['created_from']; + } - return $indicators; - }) + if (! empty($data['created_to'])) { + $indicators[] = 'To: '.$data['created_to']; + } + + return $indicators; + }), ]) ->filtersFormMaxHeight('280px') ->actions([ diff --git a/app/Filament/Resources/EbReadingResource.php b/app/Filament/Resources/EbReadingResource.php index 4ed9256..038b518 100644 --- a/app/Filament/Resources/EbReadingResource.php +++ b/app/Filament/Resources/EbReadingResource.php @@ -5,23 +5,22 @@ namespace App\Filament\Resources; use App\Filament\Exports\EbReadingExporter; use App\Filament\Imports\EbReadingImporter; use App\Filament\Resources\EbReadingResource\Pages; -use App\Filament\Resources\EbReadingResource\RelationManagers; use App\Models\EbReading; use App\Models\Plant; +use Filament\Facades\Filament; use Filament\Forms; +use Filament\Forms\Components\DateTimePicker; +use Filament\Forms\Components\Select; +use Filament\Forms\Components\TextInput; use Filament\Forms\Form; use Filament\Resources\Resource; use Filament\Tables; +use Filament\Tables\Actions\ExportAction; +use Filament\Tables\Actions\ImportAction; +use Filament\Tables\Filters\Filter; use Filament\Tables\Table; use Illuminate\Database\Eloquent\Builder; 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 { @@ -39,6 +38,7 @@ class EbReadingResource extends Resource ->relationship('plant', 'name') ->options(function (callable $get) { $userHas = Filament::auth()->user()->plant_id; + return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); }) ->required(), @@ -154,6 +154,7 @@ class EbReadingResource extends Resource $paginator = $livewire->getTableRecords(); $perPage = method_exists($paginator, 'perPage') ? $paginator->perPage() : 10; $currentPage = method_exists($paginator, 'currentPage') ? $paginator->currentPage() : 1; + return ($currentPage - 1) * $perPage + $rowLoop->iteration; }), Tables\Columns\TextColumn::make('plant.name') @@ -334,6 +335,7 @@ class EbReadingResource extends Resource // }) ->options(function (callable $get) { $userHas = Filament::auth()->user()->plant_id; + return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); }) ->reactive() @@ -359,19 +361,25 @@ class EbReadingResource extends Resource return $query->whereRaw('1 = 0'); } - if (!empty($data['Plant'])) { + if (! empty($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'])) { $query->where('created_at', '>=', $data['created_from']); } - if (!empty($data['created_to'])) { + if (! empty($data['created_to'])) { $query->where('created_at', '<=', $data['created_to']); } - if (!empty($data['electrician_sign'])) { + if (! empty($data['electrician_sign'])) { $query->where('electrician_sign', $data['electrician_sign']); } @@ -379,24 +387,30 @@ class EbReadingResource extends Resource ->indicateUsing(function (array $data) { $indicators = []; - if (!empty($data['Plant'])) { - $indicators[] = 'Plant: ' . Plant::where('id', $data['Plant'])->value('name'); + if (! empty($data['Plant'])) { + $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'])) { - $indicators[] = 'Created By: ' . $data['electrician_sign']; + if (! empty($data['electrician_sign'])) { + $indicators[] = 'Created By: '.$data['electrician_sign']; } - if (!empty($data['created_from'])) { - $indicators[] = 'From: ' . $data['created_from']; + if (! empty($data['created_from'])) { + $indicators[] = 'From: '.$data['created_from']; } - if (!empty($data['created_to'])) { - $indicators[] = 'To: ' . $data['created_to']; + if (! empty($data['created_to'])) { + $indicators[] = 'To: '.$data['created_to']; } return $indicators; - }) + }), ]) ->filtersFormMaxHeight('280px') ->actions([ @@ -415,14 +429,14 @@ class EbReadingResource extends Resource ->label('Import EB Readings') ->color('warning') ->importer(EbReadingImporter::class) - ->visible(function() { + ->visible(function () { return Filament::auth()->user()->can('view import eb reading'); }), ExportAction::make() ->label('Export EB Readings') ->color('warning') ->exporter(EbReadingExporter::class) - ->visible(function() { + ->visible(function () { return Filament::auth()->user()->can('view export eb reading'); }), ]); diff --git a/app/Filament/Resources/GuardPatrolEntryResource.php b/app/Filament/Resources/GuardPatrolEntryResource.php index 7d0a258..7e59817 100644 --- a/app/Filament/Resources/GuardPatrolEntryResource.php +++ b/app/Filament/Resources/GuardPatrolEntryResource.php @@ -5,7 +5,6 @@ namespace App\Filament\Resources; use App\Filament\Exports\GuardPatrolEntryExporter; use App\Filament\Imports\GuardPatrolEntryImporter; use App\Filament\Resources\GuardPatrolEntryResource\Pages; -use App\Filament\Resources\GuardPatrolEntryResource\RelationManagers; use App\Models\CheckPointName; use App\Models\Configuration; use App\Models\GuardName; @@ -17,7 +16,6 @@ use Filament\Forms; use Filament\Forms\Components\DateTimePicker; use Filament\Forms\Components\FileUpload; use Filament\Forms\Components\Select; -use Filament\Forms\Components\Tabs\Tab; use Filament\Forms\Components\TextInput; use Filament\Forms\Form; use Filament\Forms\Get; @@ -54,21 +52,21 @@ class GuardPatrolEntryResource extends Resource ->reactive() ->options(function (callable $get) { $userHas = Filament::auth()->user()->plant_id; + return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); }) ->default(function () { return optional(GuardPatrolEntry::where('created_by', Filament::auth()->user()?->name)->latest()->first())->plant_id; }) - ->disabled(fn (Get $get) => !empty($get('id'))) + ->disabled(fn (Get $get) => ! empty($get('id'))) ->afterStateUpdated(function ($state, callable $set, callable $get) { $plantId = $get('plant_id'); - if (!$plantId) { + if (! $plantId) { // $set('gPePlantError', 'Please select a plant first.'); $set('gPePlantError', 'Please select a plant first.'); + return; - } - else - { + } else { $set('patrol_time', now()->format('Y-m-d H:i:s')); $set('updated_by', Filament::auth()->user()?->name); $set('gPePlantError', null); @@ -84,7 +82,7 @@ class GuardPatrolEntryResource extends Resource // ->relationship('guardNames', 'name') ->options(function (callable $get) { $plantId = $get('plant_id'); - if (!$plantId) { + if (! $plantId) { return []; } @@ -97,15 +95,14 @@ class GuardPatrolEntryResource extends Resource ->default(function () { return optional(GuardPatrolEntry::where('created_by', Filament::auth()->user()?->name)->latest()->first())->guard_name_id; }) - ->disabled(fn (Get $get) => !empty($get('id'))) + ->disabled(fn (Get $get) => ! empty($get('id'))) ->afterStateUpdated(function ($state, callable $set, callable $get) { $guardName = $get('guard_name_id'); - if (!$guardName) { + if (! $guardName) { $set('gPeGuardNameError', 'Please select a guard name first.'); + return; - } - else - { + } else { $set('patrol_time', now()->format('Y-m-d H:i:s')); $set('updated_by', Filament::auth()->user()?->name); $set('gPeGuardNameError', null); @@ -116,7 +113,7 @@ class GuardPatrolEntryResource extends Resource ]) ->hint(fn ($get) => $get('gPeGuardNameError') ? $get('gPeGuardNameError') : null) ->hintColor('danger'), - Forms\Components\Hidden::make('check_point_name')//TextInput + Forms\Components\Hidden::make('check_point_name')// TextInput ->label('Check Point Name') ->reactive() ->afterStateUpdated(function ($state, callable $set, callable $get) { @@ -131,7 +128,7 @@ class GuardPatrolEntryResource extends Resource // ->relationship('checkPointNames', 'name') ->options(function (callable $get) { $plantId = $get('plant_id'); - if (!$plantId) { + if (! $plantId) { return []; } @@ -144,16 +141,15 @@ class GuardPatrolEntryResource extends Resource // ->default(function () { // return optional(GuardPatrolEntry::where('created_by', Filament::auth()->user()?->name)->latest()->first())->check_point_name_id; // }) - ->disabled(fn (Get $get) => !empty($get('id'))) + ->disabled(fn (Get $get) => ! empty($get('id'))) ->afterStateUpdated(function ($state, callable $set, callable $get) { $checkPointName = $get('check_point_name_id'); - if (!$checkPointName) { + if (! $checkPointName) { $set('check_point_name_id', null); $set('gPeCheckPointNameError', 'Please select a check point name first.'); + return; - } - else - { + } else { $set('patrol_time', now()->format('Y-m-d H:i:s')); $set('updated_by', Filament::auth()->user()?->name); $set('gPeCheckPointNameError', null); @@ -173,11 +169,10 @@ class GuardPatrolEntryResource extends Resource }), Forms\Components\TextInput::make('reader_code') ->label('Reader Code') - ->hidden(fn (Get $get) => !$get('id')) + ->hidden(fn (Get $get) => ! $get('id')) ->reactive() ->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('updated_by', Filament::auth()->user()?->name); @@ -186,7 +181,7 @@ class GuardPatrolEntryResource extends Resource ->label('Patrol Time') ->reactive() ->default(fn () => now()) - ->readOnly(fn (Get $get) => !$get('id')) + ->readOnly(fn (Get $get) => ! $get('id')) ->afterStateUpdated(function ($state, callable $set, callable $get) { $set('updated_by', Filament::auth()->user()?->name); }) @@ -225,6 +220,7 @@ class GuardPatrolEntryResource extends Resource $paginator = $livewire->getTableRecords(); $perPage = method_exists($paginator, 'perPage') ? $paginator->perPage() : 10; $currentPage = method_exists($paginator, 'currentPage') ? $paginator->currentPage() : 1; + return ($currentPage - 1) * $perPage + $rowLoop->iteration; }), // Tables\Columns\TextColumn::make('id') @@ -235,11 +231,11 @@ class GuardPatrolEntryResource extends Resource ->label('Plant') ->alignCenter() ->sortable(), - Tables\Columns\TextColumn::make('guardNames.name') //guard_name_id + Tables\Columns\TextColumn::make('guardNames.name') // guard_name_id ->label('Guard Name') ->alignCenter() ->sortable(), - Tables\Columns\TextColumn::make('checkPointNames.name') //check_point_name_id + Tables\Columns\TextColumn::make('checkPointNames.name') // check_point_name_id ->label('Check Point Name') ->alignCenter() ->sortable(), @@ -288,18 +284,19 @@ class GuardPatrolEntryResource extends Resource // }) ->options(function (callable $get) { $userHas = Filament::auth()->user()->plant_id; + return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); }) ->reactive(), - // ->afterStateUpdated(function ($state, callable $set, callable $get) { - // $set('sticker_master_id', null); - // $set('sap_msg_status', null); - // }), + // ->afterStateUpdated(function ($state, callable $set, callable $get) { + // $set('sticker_master_id', null); + // $set('sap_msg_status', null); + // }), Select::make('Guard Name') ->label('Select Guard Name') ->options(function (callable $get) { $plantId = $get('Plant'); - if (!$plantId) { + if (! $plantId) { return []; } @@ -310,7 +307,7 @@ class GuardPatrolEntryResource extends Resource ->label('Select Check Point Name') ->options(function (callable $get) { $plantId = $get('Plant'); - if (!$plantId) { + if (! $plantId) { return []; } @@ -322,11 +319,11 @@ class GuardPatrolEntryResource extends Resource ->placeholder('Select Created By') ->options(function (callable $get) { $plantId = $get('Plant'); - if (!$plantId) { + if (! $plantId) { return []; } - return GuardPatrolEntry::where('plant_id', $plantId)->orderBy('patrol_time', 'asc')->get()->unique('created_by')->pluck('created_by', 'created_by')->toArray();//, 'id' + return GuardPatrolEntry::where('plant_id', $plantId)->orderBy('patrol_time', 'asc')->get()->unique('created_by')->pluck('created_by', 'created_by')->toArray(); // , 'id' }) ->reactive(), DateTimePicker::make(name: 'From Patrol Time') @@ -341,66 +338,78 @@ class GuardPatrolEntryResource extends Resource ->placeholder(placeholder: 'Select To Patrol Time') ->reactive() ->native(false), - ]) - ->query(function ($query, array $data) { - //Hide all records initially if no filters are applied - if (empty($data['Plant']) && empty($data['Guard Name']) && empty($data['Check Point Name']) && empty($data['Created By']) && empty($data['From Patrol Time']) && empty($data['To Patrol Time'])) { - return $query->whereRaw('1 = 0'); - } + ]) + ->query(function ($query, array $data) { + // Hide all records initially if no filters are applied + if (empty($data['Plant']) && empty($data['Guard Name']) && empty($data['Check Point Name']) && empty($data['Created By']) && empty($data['From Patrol Time']) && empty($data['To Patrol Time'])) { + return $query->whereRaw('1 = 0'); + } - if (!empty($data['Plant'])) { - $query->where('plant_id', $data['Plant']); - } + if (! empty($data['Plant'])) { + $query->where('plant_id', $data['Plant']); + } else { + $userHas = Filament::auth()->user()->plant_id; - if (!empty($data['Guard Name'])) { - $query->where('guard_name_id', $data['Guard Name']); - } + if ($userHas && strlen($userHas) > 0) { + return $query->whereRaw('1 = 0'); + } + } - if (!empty($data['Check Point Name'])) { - $query->where('check_point_name_id', $data['Check Point Name']); - } + if (! empty($data['Guard Name'])) { + $query->where('guard_name_id', $data['Guard Name']); + } - if (!empty($data['Created By'])) { - $query->where('created_by', $data['Created By']); - } + if (! empty($data['Check Point Name'])) { + $query->where('check_point_name_id', $data['Check Point Name']); + } - if (!empty($data['From Patrol Time'])) { - $query->where('patrol_time', '>=', $data['From Patrol Time']); - } + if (! empty($data['Created By'])) { + $query->where('created_by', $data['Created By']); + } - if (!empty($data['To Patrol Time'])) { - $query->where('patrol_time', '<=', $data['To Patrol Time']); - } - }) - ->indicateUsing(function (array $data) { - $indicators = []; + if (! empty($data['From Patrol Time'])) { + $query->where('patrol_time', '>=', $data['From Patrol Time']); + } - if (!empty($data['Plant'])) { - $indicators[] = 'Plant: ' . Plant::where('id', $data['Plant'])->value('name'); - } + if (! empty($data['To Patrol Time'])) { + $query->where('patrol_time', '<=', $data['To Patrol Time']); + } + }) + ->indicateUsing(function (array $data) { + $indicators = []; - if (!empty($data['Guard Name'])) { - $indicators[] = 'Guard Name: ' . GuardName::where('plant_id', $data['Plant'])->where('id', $data['Guard Name'])->value('name'); - } + if (! empty($data['Plant'])) { + $indicators[] = 'Plant: '.Plant::where('id', $data['Plant'])->value('name'); + } else { + $userHas = Filament::auth()->user()->plant_id; - if (!empty($data['Check Point Name'])) { - $indicators[] = 'Check Point Name: ' . CheckPointName::where('plant_id', $data['Plant'])->where('id', $data['Check Point Name'])->value('name'); - } + if ($userHas && strlen($userHas) > 0) { + return 'Plant: Choose plant to filter records.'; + } + } - if (!empty($data['Created By'])) { - $indicators[] = 'Created By: ' . $data['Created By']; - } + if (! empty($data['Guard Name'])) { + $indicators[] = 'Guard Name: '.GuardName::where('plant_id', $data['Plant'])->where('id', $data['Guard Name'])->value('name'); + } - if (!empty($data['From Patrol Time'])) { - $indicators[] = 'From: ' . $data['From Patrol Time']; - } + if (! empty($data['Check Point Name'])) { + $indicators[] = 'Check Point Name: '.CheckPointName::where('plant_id', $data['Plant'])->where('id', $data['Check Point Name'])->value('name'); + } - if (!empty($data['To Patrol Time'])) { - $indicators[] = 'To: ' . $data['To Patrol Time']; - } + if (! empty($data['Created By'])) { + $indicators[] = 'Created By: '.$data['Created By']; + } - return $indicators; - }) + if (! empty($data['From Patrol Time'])) { + $indicators[] = 'From: '.$data['From Patrol Time']; + } + + if (! empty($data['To Patrol Time'])) { + $indicators[] = 'To: '.$data['To Patrol Time']; + } + + return $indicators; + }), ]) ->filtersFormMaxHeight('280px') ->actions([ @@ -422,6 +431,7 @@ class GuardPatrolEntryResource extends Resource // ->options(Plant::pluck('name', 'id')->toArray()) ->options(function (callable $get) { $userHas = Filament::auth()->user()->plant_id; + return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); }) ->label('Select Plant') @@ -433,12 +443,11 @@ class GuardPatrolEntryResource extends Resource ->afterStateUpdated(function ($state, callable $set, callable $get) { $plantId = $get('plant_id'); $set('guard_patrol_entry', null); - if (!$plantId) { + if (! $plantId) { $set('gPeSelectPlantError', 'Please select a plant first.'); + return; - } - else - { + } else { $set('gPeSelectPlantError', null); } }) @@ -455,7 +464,7 @@ class GuardPatrolEntryResource extends Resource ->reactive() ->required() ->disk('local') - ->visible(fn (Get $get) => !empty($get('plant_id'))) + ->visible(fn (Get $get) => ! empty($get('plant_id'))) ->directory('uploads/temp') // Allow only .xlsx and .xls ->acceptedFileTypes(['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/vnd.ms-excel']) @@ -465,7 +474,7 @@ class GuardPatrolEntryResource extends Resource ]) // Server-side validation for extra safety ->rules(['mimes:xlsx,xls']), - ]) + ]) ->action(function (array $data) { $uploadedFile = $data['guard_patrol_entry']; @@ -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'); - if(!$folderPath) - { + if (! $folderPath) { Notification::make() ->title('Upload Folder Path Not Found!') ->body('Please set the folder path in configuration for Guard Patrol Entry.') ->danger() ->send(); + return; } $fullFolderPath = "uploads/$folderPath"; // 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); } @@ -504,12 +512,10 @@ class GuardPatrolEntryResource extends Resource $fullPath = Storage::disk('local')->path($path); - if ($fullPath && file_exists($fullPath)) - { + if ($fullPath && file_exists($fullPath)) { $rows = Excel::toArray(null, $fullPath)[0]; - if((count($rows) - 1) <= 0) - { + if ((count($rows) - 1) <= 0) { Notification::make() ->title('Invalid Guard Patrol Entry Found') ->body('Uploaded excel sheet is empty or
contains no valid data.') @@ -519,19 +525,21 @@ class GuardPatrolEntryResource extends Resource if ($disk->exists($path)) { $disk->delete($path); } + return; } - $invalidRows=[]; - $invalidGuardCheckPoints=[]; - $unknownGuards=[]; - $unknownCheckPoints=[]; - $invalidPatrolTimes=[]; + $invalidRows = []; + $invalidGuardCheckPoints = []; + $unknownGuards = []; + $unknownCheckPoints = []; + $invalidPatrolTimes = []; $validRowsFound = false; - foreach ($rows as $index => $row) - { - if ($index === 0) continue; // Skip header + foreach ($rows as $index => $row) { + if ($index === 0) { + continue; + } // Skip header $rowNumber = trim($row[0]); $guardName = trim($row[1]); @@ -539,35 +547,34 @@ class GuardPatrolEntryResource extends Resource $readerCode = trim($row[3]); $patrolTime = trim($row[4]); - if (empty($rowNumber)) { continue; } + if (empty($rowNumber)) { + continue; + } if (empty($guardName) || empty($checkPointName) || empty($readerCode) || empty($patrolTime)) { $invalidRows[] = $rowNumber; + continue; - } - else - { - if(Str::length($guardName) < 3 || Str::length($checkPointName) < 3 || Str::length($readerCode) < 3 || Str::length($patrolTime) < 3) - { + } else { + if (Str::length($guardName) < 3 || Str::length($checkPointName) < 3 || Str::length($readerCode) < 3 || Str::length($patrolTime) < 3) { $invalidGuardCheckPoints[] = $rowNumber; + continue; - } - else - { + } else { $isValidRow = true; $guardNames = GuardName::where('plant_id', $plantId)->where('name', $guardName)->first(); - if (!$guardNames) { + if (! $guardNames) { $unknownGuards[] = $guardName; $isValidRow = false; } $checkPointNames = CheckPointName::where('plant_id', $plantId)->where('name', $checkPointName)->first(); - if (!$checkPointNames) { + if (! $checkPointNames) { $unknownCheckPoints[] = $checkPointName; $isValidRow = false; } - $formats = ['d-m-Y H:i:s', 'd-m-Y H:i']; //'07-05-2025 08:00' or '07-05-2025 08:00:00' + $formats = ['d-m-Y H:i:s', 'd-m-Y H:i']; // '07-05-2025 08:00' or '07-05-2025 08:00:00' $patrolDateTime = null; foreach ($formats as $format) { try { @@ -579,13 +586,13 @@ class GuardPatrolEntryResource extends Resource } } - if (!isset($patrolDateTime)) { + if (! isset($patrolDateTime)) { $invalidPatrolTimes[] = $rowNumber; $isValidRow = false; - //$warnMsg[] = "Invalid 'Patrol DateTime' format. Expected DD-MM-YYYY HH:MM:SS"; + // $warnMsg[] = "Invalid 'Patrol DateTime' format. Expected DD-MM-YYYY HH:MM:SS"; } - if ($isValidRow && !$validRowsFound) { + if ($isValidRow && ! $validRowsFound) { $validRowsFound = true; } } @@ -593,38 +600,40 @@ class GuardPatrolEntryResource extends Resource } $uniqueInvalidRows = array_unique($invalidRows); - if (!empty($uniqueInvalidRows)) { + if (! empty($uniqueInvalidRows)) { Notification::make() ->title('Invalid Guard Patrol Entry Found') - ->body('The following rows contain empty values (Guard name or Check point name or Reader code or Patrol time):
' . implode(', ', $uniqueInvalidRows)) + ->body('The following rows contain empty values (Guard name or Check point name or Reader code or Patrol time):
'.implode(', ', $uniqueInvalidRows)) ->danger() ->send(); if ($disk->exists($path)) { $disk->delete($path); } + return; } - //should contain minimum 13 digit alpha numeric values + // should contain minimum 13 digit alpha numeric values $uniqueInvalidGuardCheckPoints = array_unique($invalidGuardCheckPoints); - if (!empty($uniqueInvalidGuardCheckPoints)) { + if (! empty($uniqueInvalidGuardCheckPoints)) { Notification::make() ->title('Invalid Guard Patrol Entry Found') - ->body('The following rows contain invalid values (Guard name or Check point name or Reader code or Patrol time):
' . implode(', ', $uniqueInvalidGuardCheckPoints)) + ->body('The following rows contain invalid values (Guard name or Check point name or Reader code or Patrol time):
'.implode(', ', $uniqueInvalidGuardCheckPoints)) ->danger() ->send(); if ($disk->exists($path)) { $disk->delete($path); } + return; } $invalidDataFound = false; $uniqueUnknownGuards = array_unique($unknownGuards); - if (!empty($uniqueUnknownGuards)) { + if (! empty($uniqueUnknownGuards)) { Notification::make() ->title('Unknown Guard Names Found') - ->body("The following guard names aren't exist in master data:
" . implode(', ', $uniqueUnknownGuards)) + ->body("The following guard names aren't exist in master data:
".implode(', ', $uniqueUnknownGuards)) ->danger() ->send(); if ($disk->exists($path)) { @@ -634,10 +643,10 @@ class GuardPatrolEntryResource extends Resource } $uniqueUnknownCheckPoints = array_unique($unknownCheckPoints); - if (!empty($uniqueUnknownCheckPoints)) { + if (! empty($uniqueUnknownCheckPoints)) { Notification::make() ->title('Unknown Check Point Names Found') - ->body("The following check point names aren't exist in master data:
" . implode(', ', $uniqueUnknownCheckPoints)) + ->body("The following check point names aren't exist in master data:
".implode(', ', $uniqueUnknownCheckPoints)) ->danger() ->send(); if ($disk->exists($path)) { @@ -647,10 +656,10 @@ class GuardPatrolEntryResource extends Resource } $uniqueInvalidPatrolTimes = array_unique($invalidPatrolTimes); - if (!empty($uniqueInvalidPatrolTimes)) { + if (! empty($uniqueInvalidPatrolTimes)) { Notification::make() ->title('Invalid Patrol Time Format Found') - ->body("The following rows contains invalid patrol time format (Expected 'DD-MM-YYYY HH:MM:SS'):
" . implode(', ', $uniqueInvalidPatrolTimes)) + ->body("The following rows contains invalid patrol time format (Expected 'DD-MM-YYYY HH:MM:SS'):
".implode(', ', $uniqueInvalidPatrolTimes)) ->danger() ->send(); if ($disk->exists($path)) { @@ -663,24 +672,26 @@ class GuardPatrolEntryResource extends Resource return; } - if (!$validRowsFound) { + if (! $validRowsFound) { Notification::make() ->title('Invalid Guard Patrol Entry Found') ->body('Uploaded excel sheet is empty or
contains no valid data.') ->danger() ->send(); - if ($disk->exists($path)) { - $disk->delete($path); - } + if ($disk->exists($path)) { + $disk->delete($path); + } + return; } $validCnt = 0; $dupCnt = 0; $validRowsFound = false; - foreach ($rows as $index => $row) - { - if ($index === 0) continue; // Skip header + foreach ($rows as $index => $row) { + if ($index === 0) { + continue; + } // Skip header $rowNumber = trim($row[0]); $guardName = trim($row[1]); @@ -688,7 +699,9 @@ class GuardPatrolEntryResource extends Resource $readerCode = trim($row[3]); $patrolTime = trim($row[4]); - if (empty($rowNumber)) { continue; } + if (empty($rowNumber)) { + continue; + } if (empty($guardName) || empty($checkPointName) || empty($readerCode) || empty($patrolTime)) { continue; @@ -696,7 +709,7 @@ class GuardPatrolEntryResource extends Resource $isValidRow = true; - $formats = ['d-m-Y H:i:s', 'd-m-Y H:i']; //'07-05-2025 08:00' or '07-05-2025 08:00:00' + $formats = ['d-m-Y H:i:s', 'd-m-Y H:i']; // '07-05-2025 08:00' or '07-05-2025 08:00:00' $patrolDateTime = null; foreach ($formats as $format) { try { @@ -707,7 +720,7 @@ class GuardPatrolEntryResource extends Resource } } - if (!isset($patrolDateTime)) { + if (! isset($patrolDateTime)) { $isValidRow = false; } @@ -718,23 +731,22 @@ class GuardPatrolEntryResource extends Resource $guardEntryFound = GuardPatrolEntry::where('plant_id', $plantId)->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) { - //$warnMsg[] = "Duplicate guard patrol entry found"; + // $warnMsg[] = "Duplicate guard patrol entry found"; $dupCnt++; + continue; - } - else - { + } else { $validCnt++; GuardPatrolEntry::updateOrCreate([ 'plant_id' => $plantId, 'guard_name_id' => $guardNames->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, - 'created_by' => $user, - 'updated_by' => $user + [ + 'reader_code' => $readerCode, + 'created_by' => $user, + 'updated_by' => $user, ] ); $validRowsFound = true; @@ -742,31 +754,25 @@ class GuardPatrolEntryResource extends Resource } } - if (!$validRowsFound && $dupCnt > 0) { + if (! $validRowsFound && $dupCnt > 0) { Notification::make() ->title('Duplicate Guard Patrol Entry Found') ->body("Uploaded excel sheet contains '{$dupCnt}' duplicate entries!
Please check the uploaded file and try again.") ->danger() ->send(); - if ($disk->exists($path)) - { + if ($disk->exists($path)) { $disk->delete($path); } - } - else if ($validRowsFound && $validCnt > 0) - { - //session(['guard_patrol_entry_path' => $fullPath]); + } elseif ($validRowsFound && $validCnt > 0) { + // session(['guard_patrol_entry_path' => $fullPath]); Notification::make() ->title("Success: '{$validCnt}' guard patrol entries imported successfully.") ->success() ->send(); - if ($disk->exists($path)) - { + if ($disk->exists($path)) { $disk->delete($path); } - } - else - { + } else { Notification::make() ->title('Failed: Something went wrong while uploading guard patrol entries!') ->danger() @@ -777,7 +783,7 @@ class GuardPatrolEntryResource extends Resource } } }) - ->visible(function() { + ->visible(function () { return Filament::auth()->user()->can('view import guard patrol entries'); }), ImportAction::make() @@ -785,14 +791,14 @@ class GuardPatrolEntryResource extends Resource // ->hidden() ->color('warning') ->importer(GuardPatrolEntryImporter::class) - ->visible(function() { + ->visible(function () { return Filament::auth()->user()->can('view import guard patrol entry'); }), ExportAction::make() ->label('Export Guard Patrol Entry') ->color('warning') ->exporter(GuardPatrolEntryExporter::class) - ->visible(function() { + ->visible(function () { return Filament::auth()->user()->can('view export guard patrol entry'); }), ]); diff --git a/app/Filament/Resources/InvoiceValidationResource.php b/app/Filament/Resources/InvoiceValidationResource.php index ce941cc..0a62e86 100644 --- a/app/Filament/Resources/InvoiceValidationResource.php +++ b/app/Filament/Resources/InvoiceValidationResource.php @@ -1181,6 +1181,12 @@ class InvoiceValidationResource extends Resource if (! empty($data['Plant'])) { // $plant = $data['Plant'] ?? null $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'])) { @@ -1218,6 +1224,12 @@ class InvoiceValidationResource extends Resource if (! empty($data['Plant'])) { $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'])) { diff --git a/app/Filament/Resources/LocatorInvoiceValidationResource.php b/app/Filament/Resources/LocatorInvoiceValidationResource.php index 69943ff..112f818 100644 --- a/app/Filament/Resources/LocatorInvoiceValidationResource.php +++ b/app/Filament/Resources/LocatorInvoiceValidationResource.php @@ -5,35 +5,33 @@ namespace App\Filament\Resources; use App\Filament\Exports\LocatorInvoiceValidationExporter; use App\Filament\Imports\LocatorInvoiceValidationImporter; use App\Filament\Resources\LocatorInvoiceValidationResource\Pages; -use App\Filament\Resources\LocatorInvoiceValidationResource\RelationManagers; use App\Models\Configuration; use App\Models\InvoiceValidation; use App\Models\LocatorInvoiceValidation; use App\Models\PalletValidation; use App\Models\Plant; -use App\Models\StickerMaster; use Filament\Facades\Filament; use Filament\Forms; +use Filament\Forms\Components\DateTimePicker; use Filament\Forms\Components\FileUpload; 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\Get; use Filament\Notifications\Notification; use Filament\Resources\Resource; use Filament\Tables; +use Filament\Tables\Actions\ExportAction; +use Filament\Tables\Actions\ImportAction; +use Filament\Tables\Filters\Filter; use Filament\Tables\Table; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\SoftDeletingScope; use Maatwebsite\Excel\Facades\Excel; -use Filament\Tables\Actions\ExportAction; -use Filament\Tables\Actions\ImportAction; use Storage; use Str; -use Filament\Forms\Components\DateTimePicker; -use Filament\Tables\Filters\Filter; -use Filament\Forms\Components\TextInput; class LocatorInvoiceValidationResource extends Resource { @@ -50,372 +48,366 @@ class LocatorInvoiceValidationResource extends Resource return $form ->schema([ Section::make('') - ->schema([ - Forms\Components\Select::make('plant_id') - ->label('Plant') - ->reactive() - ->relationship('plant', 'name') - ->options(function (callable $get) { - $userHas = Filament::auth()->user()->plant_id; - 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')) - ->required() - ->afterStateUpdated(function ($state, callable $set, callable $get) { - $plantId = $get('plant_id'); - if ($plantId) - { - $set('plant', $plantId); - $set('invoice_number', null); - $set('pallet_number', null); - $set('serial_number', null); - $set('sno_quantity', 0); - $set('scan_quantity', 0); - $set('pend_quantity', 0); - } - else - { - $set('plant', null); - $set('invoice_number', null); - $set('pallet_number', null); - $set('serial_number', null); - $set('sno_quantity', 0); - $set('scan_quantity', 0); - $set('pend_quantity', 0); - } - }), + ->schema([ + Forms\Components\Select::make('plant_id') + ->label('Plant') + ->reactive() + ->relationship('plant', 'name') + ->options(function (callable $get) { + $userHas = Filament::auth()->user()->plant_id; - Forms\Components\Hidden::make('plant') - ->reactive(), + 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')) + ->required() + ->afterStateUpdated(function ($state, callable $set, callable $get) { + $plantId = $get('plant_id'); + if ($plantId) { + $set('plant', $plantId); + $set('invoice_number', null); + $set('pallet_number', null); + $set('serial_number', null); + $set('sno_quantity', 0); + $set('scan_quantity', 0); + $set('pend_quantity', 0); + } else { + $set('plant', null); + $set('invoice_number', null); + $set('pallet_number', null); + $set('serial_number', null); + $set('sno_quantity', 0); + $set('scan_quantity', 0); + $set('pend_quantity', 0); + } + }), - Forms\Components\TextInput::make('invoice_number') - ->label('Scan Invoice No') - ->required() - ->reactive() - ->extraAttributes([ - 'x-data' => '{ value: "" }', - 'x-model' => 'value', - 'x-on:keydown.enter.prevent' => '$wire.processinvoiceSNo()', + Forms\Components\Hidden::make('plant') + ->reactive(), + + Forms\Components\TextInput::make('invoice_number') + ->label('Scan Invoice No') + ->required() + ->reactive() + ->extraAttributes([ + 'x-data' => '{ value: "" }', + 'x-model' => 'value', + 'x-on:keydown.enter.prevent' => '$wire.processinvoiceSNo()', + ]) + ->readOnly(fn (callable $get) => ! $get('plant') || $get('pallet_number') || $get('serial_number')) + ->afterStateUpdated(function ($state, callable $set, callable $get) { + $plantId = $get('plant'); + $invNo = $get('invoice_number'); + $snoCount = 0; + $pendingCount = 0; + $scannedCount = 0; + if (! $plantId) { + $set('invoice_number', null); + $set('pallet_number', null); + } elseif ($invNo) { + $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(); + + $scannedCount = LocatorInvoiceValidation::where('invoice_number', $invNo)->where('plant_id', $plantId)->where('scanned_status', '=', 'Scanned')->count(); + } + $set('update_invoice', null); + $set('pallet_number', null); + $set('serial_number', null); + $set('sno_quantity', $snoCount); + $set('scan_quantity', $scannedCount); + $set('pend_quantity', $pendingCount); + }), + Forms\Components\TextInput::make('pallet_number') + ->label('Scan Pallet No') + ->reactive() + ->minLength(10) + // ->readOnly(fn (callable $get) => !$get('plant') || !$get('invoice_number') || $get('serial_number')) + ->readOnly(function (callable $get) { + $invoiceNumber = $get('invoice_number'); + $plantId = $get('plant'); + $invoiceExist = false; + + if (! empty($invoiceNumber) && ! empty($plantId)) { + $records = LocatorInvoiceValidation::where('plant_id', $plantId) + ->where('invoice_number', $invoiceNumber) + ->get(); + + $allScanned = true; + foreach ($records as $record) { + if (($record->scanned_status == null) || trim($record->scanned_status) == '') { + $allScanned = false; + break; + } + } + + if (count($records) > 0 && ! $allScanned) { + $invoiceExist = true; + } + } + + return $invoiceExist == false || ! $get('plant') || ! $get('invoice_number') || $get('serial_number'); + }) + ->extraAttributes([ + 'wire:keydown.enter.prevent' => 'processPalletNo()', + ]) + ->afterStateUpdated(function ($state, callable $set, callable $get) { + $plantId = $get('plant'); + if (! $plantId) { + $set('invoice_number', null); + $set('pallet_number', null); + } + $set('update_locator_invoice', null); + }), + Forms\Components\TextInput::make('serial_number') + ->label('Scan Serial No') + ->reactive() + ->minLength(9) + // ->readOnly(fn (callable $get) => !$get('plant') || !$get('invoice_number') || $get('pallet_number')) + ->readOnly(function (callable $get) { + $invoiceNumber = $get('invoice_number'); + $plantId = $get('plant'); + $invoiceExist = false; + + if (! empty($invoiceNumber) && ! empty($plantId)) { + $records = LocatorInvoiceValidation::where('plant_id', $plantId) + ->where('invoice_number', $invoiceNumber) + ->get(); + + $allScanned = true; + foreach ($records as $record) { + if (($record->scanned_status == null) || trim($record->scanned_status) == '') { + $allScanned = false; + break; + } + } + + if (count($records) > 0 && ! $allScanned) { + $invoiceExist = true; + } + } + + return $invoiceExist == false || ! $get('plant') || ! $get('invoice_number') || $get('pallet_number'); + }) + ->extraAttributes([ + 'x-data' => '{ value: "" }', + 'x-model' => 'value', + 'x-on:keydown.enter.prevent' => '$wire.processSerialNo()', + ]), + Forms\Components\TextInput::make('sno_quantity') + ->label('Invoice Quantity') + ->default(0) + ->readOnly(), + + Forms\Components\TextInput::make('scan_quantity') + ->label('Scanned Quantity') + ->default(0) + ->readOnly(), + + Forms\Components\TextInput::make('pend_quantity') + ->label('Pending Quantity') + ->default(0) + ->readOnly(), + + // Forms\Components\View::make('forms.components.update-invoice-button'), + + ToggleButtons::make('update_invoice') + ->label('Update Invoice?') + ->boolean() + ->grouped() + ->reactive() + ->hidden(function (callable $get) { + $invoiceNumber = $get('invoice_number'); + $plantId = $get('plant'); + $invoiceExist = false; + + if (! empty($invoiceNumber) && ! empty($plantId)) { + + $records = LocatorInvoiceValidation::where('plant_id', $plantId) + ->where('invoice_number', $invoiceNumber) + ->get(); + + $allScanned = true; + + foreach ($records as $record) { + if (($record->scanned_status == null) || trim($record->scanned_status) == '') { + $allScanned = false; + break; + } + } + + if (count($records) > 0 && ! $allScanned) { + $invoiceExist = true; + } + } + + return $get('update_invoice') == '0' || $invoiceExist == false || ! empty($get('pallet_number')) || ! empty($get('serial_number')); // $get('invoice_number') == null + }), + + Forms\Components\TextInput::make('id') + ->hidden() + ->readOnly(), + + ToggleButtons::make('update_locator_invoice') + ->label('Update Partial Pallet?') + ->boolean() + ->grouped() + ->reactive() + ->hidden(function (callable $get) { + $palletNumber = $get('pallet_number'); + $plantId = $get('plant'); + $isPalletValid = false; + + if (! empty($palletNumber) && ! empty($plantId)) { + $pallet = PalletValidation::where('plant_id', $plantId) + ->where('pallet_number', $palletNumber) + ->first(); + $isPalletValid = $pallet !== null; + } + + return ! $isPalletValid || $get('update_locator_invoice') == '0' || ! empty($get('serial_number')); + }) + ->afterStateUpdated(function ($state, callable $set, callable $get, $livewire) { + $plantId = $get('plant'); + + $palletNumber = $get('pallet_number'); + + $serialNumber = $get('serial_number'); + + $invoiceNumber = $get('invoice_number'); + + $operatorName = Filament::auth()->user()->name; + + if ($state !== '1') { + $set('update_locator_invoice', '0'); + $set('pallet_number', null); + + return; + } + + $palletRecord = PalletValidation::where('plant_id', $plantId) + ->where('pallet_number', $palletNumber) + ->first(); + + if (! $palletRecord) { + Notification::make() + ->title("Pallet number '{$palletNumber}' does not exist.") + ->danger() + ->duration(5000) + ->send(); + + return; + } + + $palletRecords = PalletValidation::where('plant_id', $plantId) + ->where('pallet_number', $palletNumber) + ->get(); + + $allCompleted = true; + foreach ($palletRecords as $record) { + if ($record->pallet_status != 'Completed') { + $allCompleted = false; + break; + } + } + + if (! $allCompleted) { + Notification::make() + ->title("Pallet number '{$palletNumber}' is not completed in masters") + ->danger() + ->duration(5000) + ->send(); + + return; + } + + // if ($allCompleted) + // { + // $serialNumbers = $palletRecords->pluck('serial_number') + // ->map(function ($serial) { + // return trim($serial); + // }) + // ->all(); + + // $InvoiceSerialNumbers = LocatorInvoiceValidation::where('plant_id', $plantId) + // ->where('invoice_number', $invoiceNumber) + // ->pluck('serial_number') + // ->all(); + + // $missingSerialNumbers = array_diff($InvoiceSerialNumbers, $serialNumbers); + + // $allmatchedSerialNumbers = array_unique(array_merge($InvoiceSerialNumbers, $serialNumbers)); + + // if (!empty($missingSerialNumbers)) + // { + + // $matchedSerialNumbers = array_diff($serialNumbers, $missingSerialNumbers); + + // foreach ($matchedSerialNumbers as $serial) + // { + // $invoiceRecord = LocatorInvoiceValidation::where('plant_id', $plantId) + // ->where('invoice_number', $invoiceNumber) + // ->where('serial_number', $serial) + // ->first(); + + // if ($invoiceRecord) + // { + // $invoiceRecord->scanned_status = 'Scanned'; + // $invoiceRecord->pallet_number = $palletNumber; + // $invoiceRecord->scanned_at = now(); + // $invoiceRecord->scanned_by = $operatorName; + // $invoiceRecord->save(); + + // Notification::make() + // ->title("Pallet number '{$palletNumber}' scanned successfully") + // ->success() + // ->duration(800) + // ->send(); + // } + + // PalletValidation::where('plant_id', $plantId) + // ->where('pallet_number', $palletNumber) + // ->where('serial_number', $serial) + // ->forceDelete(); + + // $livewire('loadData', $invoiceNumber, $plantId); + // } + // } + // else + // { + // foreach ($allmatchedSerialNumbers as $serial) + // { + // $invoiceRecord = LocatorInvoiceValidation::where('plant_id', $plantId) + // ->where('invoice_number', $invoiceNumber) + // ->where('serial_number', $serial) + // ->first(); + + // if ($invoiceRecord) + // { + // $invoiceRecord->scanned_status = 'Scanned'; + // $invoiceRecord->pallet_number = $palletNumber; + // $invoiceRecord->scanned_at = now(); + // $invoiceRecord->scanned_by = $operatorName; + // $invoiceRecord->save(); + + // Notification::make() + // ->title("Pallet number '{$palletNumber}' scanned successfully") + // ->success() + // ->duration(800) + // ->send(); + // } + + // PalletValidation::where('plant_id', $plantId) + // ->where('pallet_number', $palletNumber) + // ->where('serial_number', $serial) + // ->forceDelete(); + + // $this->dispatch('loadData', $invoiceNumber, $plantId); + // } + // } + // } + }), ]) - ->readOnly(fn (callable $get) => !$get('plant') || $get('pallet_number') || $get('serial_number')) - ->afterStateUpdated(function ($state, callable $set, callable $get) { - $plantId = $get('plant'); - $invNo = $get('invoice_number'); - $snoCount = 0; - $pendingCount = 0; - $scannedCount = 0; - if (!$plantId) { - $set('invoice_number', null); - $set('pallet_number', null); - } - else if ($invNo) - { - $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(); - - $scannedCount = LocatorInvoiceValidation::where('invoice_number', $invNo)->where('plant_id', $plantId)->where('scanned_status', '=', 'Scanned')->count(); - } - $set('update_invoice', null); - $set('pallet_number', null); - $set('serial_number', null); - $set('sno_quantity', $snoCount); - $set('scan_quantity', $scannedCount); - $set('pend_quantity', $pendingCount); - }), - Forms\Components\TextInput::make('pallet_number') - ->label('Scan Pallet No') - ->reactive() - ->minLength(10) - // ->readOnly(fn (callable $get) => !$get('plant') || !$get('invoice_number') || $get('serial_number')) - ->readOnly(function (callable $get) { - $invoiceNumber = $get('invoice_number'); - $plantId = $get('plant'); - $invoiceExist = false; - - if (!empty($invoiceNumber) && !empty($plantId)) { - $records = LocatorInvoiceValidation::where('plant_id', $plantId) - ->where('invoice_number', $invoiceNumber) - ->get(); - - $allScanned = true; - foreach ($records as $record) - { - if (($record->scanned_status == null) || trim($record->scanned_status) == '') { - $allScanned = false; - break; - } - } - - if (count($records) > 0 && !$allScanned) { - $invoiceExist = true; - } - } - - return $invoiceExist == false || !$get('plant') || !$get('invoice_number') || $get('serial_number'); - }) - ->extraAttributes([ - 'wire:keydown.enter.prevent' => 'processPalletNo()', - ]) - ->afterStateUpdated(function ($state, callable $set, callable $get) { - $plantId = $get('plant'); - if (!$plantId) { - $set('invoice_number', null); - $set('pallet_number', null); - } - $set('update_locator_invoice', null); - }), - Forms\Components\TextInput::make('serial_number') - ->label('Scan Serial No') - ->reactive() - ->minLength(9) - // ->readOnly(fn (callable $get) => !$get('plant') || !$get('invoice_number') || $get('pallet_number')) - ->readOnly(function (callable $get) { - $invoiceNumber = $get('invoice_number'); - $plantId = $get('plant'); - $invoiceExist = false; - - if (!empty($invoiceNumber) && !empty($plantId)) { - $records = LocatorInvoiceValidation::where('plant_id', $plantId) - ->where('invoice_number', $invoiceNumber) - ->get(); - - $allScanned = true; - foreach ($records as $record) - { - if (($record->scanned_status == null) || trim($record->scanned_status) == '') { - $allScanned = false; - break; - } - } - - if (count($records) > 0 && !$allScanned) { - $invoiceExist = true; - } - } - - return $invoiceExist == false || !$get('plant') || !$get('invoice_number') || $get('pallet_number'); - }) - ->extraAttributes([ - 'x-data' => '{ value: "" }', - 'x-model' => 'value', - 'x-on:keydown.enter.prevent' => '$wire.processSerialNo()', - ]), - Forms\Components\TextInput::make('sno_quantity') - ->label('Invoice Quantity') - ->default(0) - ->readOnly(), - - Forms\Components\TextInput::make('scan_quantity') - ->label('Scanned Quantity') - ->default(0) - ->readOnly(), - - Forms\Components\TextInput::make('pend_quantity') - ->label('Pending Quantity') - ->default(0) - ->readOnly(), - - //Forms\Components\View::make('forms.components.update-invoice-button'), - - ToggleButtons::make('update_invoice') - ->label('Update Invoice?') - ->boolean() - ->grouped() - ->reactive() - ->hidden(function (callable $get) { - $invoiceNumber = $get('invoice_number'); - $plantId = $get('plant'); - $invoiceExist = false; - - if (!empty($invoiceNumber) && !empty($plantId)) { - - $records = LocatorInvoiceValidation::where('plant_id', $plantId) - ->where('invoice_number', $invoiceNumber) - ->get(); - - $allScanned = true; - - foreach ($records as $record) - { - if (($record->scanned_status == null) || trim($record->scanned_status) == '') { - $allScanned = false; - break; - } - } - - if (count($records) > 0 && !$allScanned) { - $invoiceExist = true; - } - } - - return $get('update_invoice') == '0' || $invoiceExist == false || !empty($get('pallet_number')) || !empty($get('serial_number')); //$get('invoice_number') == null - }), - - Forms\Components\TextInput::make('id') - ->hidden() - ->readOnly(), - - ToggleButtons::make('update_locator_invoice') - ->label('Update Partial Pallet?') - ->boolean() - ->grouped() - ->reactive() - ->hidden(function (callable $get) { - $palletNumber = $get('pallet_number'); - $plantId = $get('plant'); - $isPalletValid = false; - - if (!empty($palletNumber) && !empty($plantId)) { - $pallet = PalletValidation::where('plant_id', $plantId) - ->where('pallet_number', $palletNumber) - ->first(); - $isPalletValid = $pallet !== null; - } - - return !$isPalletValid || $get('update_locator_invoice') == '0' || !empty($get('serial_number')); - }) - ->afterStateUpdated(function ($state, callable $set, callable $get, $livewire) { - $plantId = $get('plant'); - - $palletNumber = $get('pallet_number'); - - $serialNumber = $get('serial_number'); - - $invoiceNumber = $get('invoice_number'); - - $operatorName = Filament::auth()->user()->name; - - if ($state !== '1') { - $set('update_locator_invoice', '0'); - $set('pallet_number', null); - return; - } - - $palletRecord = PalletValidation::where('plant_id', $plantId) - ->where('pallet_number', $palletNumber) - ->first(); - - if (!$palletRecord) - { - Notification::make() - ->title("Pallet number '{$palletNumber}' does not exist.") - ->danger() - ->duration(5000) - ->send(); - return; - } - - $palletRecords = PalletValidation::where('plant_id', $plantId) - ->where('pallet_number', $palletNumber) - ->get(); - - $allCompleted = true; - foreach ($palletRecords as $record) { - if ($record->pallet_status != 'Completed') { - $allCompleted = false; - break; - } - } - - if (!$allCompleted) - { - Notification::make() - ->title("Pallet number '{$palletNumber}' is not completed in masters") - ->danger() - ->duration(5000) - ->send(); - return; - } - - // if ($allCompleted) - // { - // $serialNumbers = $palletRecords->pluck('serial_number') - // ->map(function ($serial) { - // return trim($serial); - // }) - // ->all(); - - // $InvoiceSerialNumbers = LocatorInvoiceValidation::where('plant_id', $plantId) - // ->where('invoice_number', $invoiceNumber) - // ->pluck('serial_number') - // ->all(); - - // $missingSerialNumbers = array_diff($InvoiceSerialNumbers, $serialNumbers); - - // $allmatchedSerialNumbers = array_unique(array_merge($InvoiceSerialNumbers, $serialNumbers)); - - // if (!empty($missingSerialNumbers)) - // { - - // $matchedSerialNumbers = array_diff($serialNumbers, $missingSerialNumbers); - - // foreach ($matchedSerialNumbers as $serial) - // { - // $invoiceRecord = LocatorInvoiceValidation::where('plant_id', $plantId) - // ->where('invoice_number', $invoiceNumber) - // ->where('serial_number', $serial) - // ->first(); - - // if ($invoiceRecord) - // { - // $invoiceRecord->scanned_status = 'Scanned'; - // $invoiceRecord->pallet_number = $palletNumber; - // $invoiceRecord->scanned_at = now(); - // $invoiceRecord->scanned_by = $operatorName; - // $invoiceRecord->save(); - - // Notification::make() - // ->title("Pallet number '{$palletNumber}' scanned successfully") - // ->success() - // ->duration(800) - // ->send(); - // } - - // PalletValidation::where('plant_id', $plantId) - // ->where('pallet_number', $palletNumber) - // ->where('serial_number', $serial) - // ->forceDelete(); - - // $livewire('loadData', $invoiceNumber, $plantId); - // } - // } - // else - // { - // foreach ($allmatchedSerialNumbers as $serial) - // { - // $invoiceRecord = LocatorInvoiceValidation::where('plant_id', $plantId) - // ->where('invoice_number', $invoiceNumber) - // ->where('serial_number', $serial) - // ->first(); - - // if ($invoiceRecord) - // { - // $invoiceRecord->scanned_status = 'Scanned'; - // $invoiceRecord->pallet_number = $palletNumber; - // $invoiceRecord->scanned_at = now(); - // $invoiceRecord->scanned_by = $operatorName; - // $invoiceRecord->save(); - - // Notification::make() - // ->title("Pallet number '{$palletNumber}' scanned successfully") - // ->success() - // ->duration(800) - // ->send(); - // } - - // PalletValidation::where('plant_id', $plantId) - // ->where('pallet_number', $palletNumber) - // ->where('serial_number', $serial) - // ->forceDelete(); - - // $this->dispatch('loadData', $invoiceNumber, $plantId); - // } - // } - // } - }) - ]) - ->columns(5), + ->columns(5), ]); } @@ -431,6 +423,7 @@ class LocatorInvoiceValidationResource extends Resource $paginator = $livewire->getTableRecords(); $perPage = method_exists($paginator, 'perPage') ? $paginator->perPage() : 10; $currentPage = method_exists($paginator, 'currentPage') ? $paginator->currentPage() : 1; + return ($currentPage - 1) * $perPage + $rowLoop->iteration; }), Tables\Columns\TextColumn::make('plant.name') @@ -504,6 +497,7 @@ class LocatorInvoiceValidationResource extends Resource // ->options(Plant::pluck('name', 'id')->toArray()) ->options(function (callable $get) { $userHas = Filament::auth()->user()->plant_id; + return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); }) ->label('Select Plant') @@ -524,7 +518,7 @@ class LocatorInvoiceValidationResource extends Resource ->reactive() ->required() ->disk('local') - ->visible(fn (Get $get) => !empty($get('plant_id'))) + ->visible(fn (Get $get) => ! empty($get('plant_id'))) ->directory('uploads/temp'), ]) ->action(function (array $data) { @@ -541,13 +535,12 @@ class LocatorInvoiceValidationResource extends Resource // $originalNameOnly = pathinfo($originalName, PATHINFO_FILENAME); $folderPath = Configuration::where('c_name', 'INVOICE_FOLDER_PATH') - ->value('c_value'); + ->value('c_value'); $fullFolderPath = "uploads/$folderPath"; // 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); } @@ -555,12 +548,10 @@ class LocatorInvoiceValidationResource extends Resource $fullPath = Storage::disk('local')->path($path); - if ($fullPath && file_exists($fullPath)) - { + if ($fullPath && file_exists($fullPath)) { $rows = Excel::toArray(null, $fullPath)[0]; - if((count($rows) - 1) <= 0) - { + if ((count($rows) - 1) <= 0) { Notification::make() ->title('Invalid Locator Invoice Found') ->body('Uploaded excel sheet is empty or
contains no valid data.') @@ -571,37 +562,31 @@ class LocatorInvoiceValidationResource extends Resource if ($disk->exists($path)) { $disk->delete($path); } + return; } - $invalidSerialCodes=[]; + $invalidSerialCodes = []; $duplicateSerials = []; $seenSerialNumbers = []; $validRowsFound = false; - foreach ($rows as $index => $row) - { - if ($index === 0) continue; // Skip header + foreach ($rows as $index => $row) { + if ($index === 0) { + continue; + } // Skip header $serialNumber = trim($row[0]); - if (empty($serialNumber)) - { + if (empty($serialNumber)) { continue; - } - else - { - if(Str::length($serialNumber) < 9 || Str::length($serialNumber) > 20 || !ctype_alnum($serialNumber)) - { + } else { + if (Str::length($serialNumber) < 9 || Str::length($serialNumber) > 20 || ! ctype_alnum($serialNumber)) { $invalidSerialCodes[] = $serialNumber; - } - else - { + } else { if (in_array($serialNumber, $seenSerialNumbers)) { $duplicateSerials[] = $serialNumber; - } - else - { + } else { $seenSerialNumbers[] = $serialNumber; $validRowsFound = true; } @@ -611,10 +596,10 @@ class LocatorInvoiceValidationResource extends Resource $uniqueSerialCodes = array_unique($invalidSerialCodes); - if (!empty($uniqueSerialCodes)) { + if (! empty($uniqueSerialCodes)) { Notification::make() ->title('Invalid Serial Numbers Found') - ->body('The following serial numbers should contain minimum 9 digit (and maximum 20 digit) alpha numeric values:
' . implode(', ', $uniqueSerialCodes)) + ->body('The following serial numbers should contain minimum 9 digit (and maximum 20 digit) alpha numeric values:
'.implode(', ', $uniqueSerialCodes)) ->danger() ->duration(5000) ->send(); @@ -622,15 +607,16 @@ class LocatorInvoiceValidationResource extends Resource if ($disk->exists($path)) { $disk->delete($path); } + return; } $duplicateSerialCodes = array_unique($duplicateSerials); - if (!empty($duplicateSerialCodes)) { + if (! empty($duplicateSerialCodes)) { Notification::make() ->title('Duplicate Serial Numbers Found') - ->body('The following serial numbers are already exist in imported excel:
' . implode(', ', $duplicateSerialCodes)) + ->body('The following serial numbers are already exist in imported excel:
'.implode(', ', $duplicateSerialCodes)) ->danger() ->duration(5000) ->send(); @@ -638,10 +624,11 @@ class LocatorInvoiceValidationResource extends Resource if ($disk->exists($path)) { $disk->delete($path); } + return; } - if (!$validRowsFound) { + if (! $validRowsFound) { Notification::make() ->title('Invalid Locator Invoice Found') ->body('Uploaded excel sheet is empty or
contains no valid data.') @@ -652,6 +639,7 @@ class LocatorInvoiceValidationResource extends Resource if ($disk->exists($path)) { $disk->delete($path); } + return; } @@ -663,10 +651,10 @@ class LocatorInvoiceValidationResource extends Resource ->pluck('serial_number') ->toArray(); - if (!empty($existingSerials)) { + if (! empty($existingSerials)) { Notification::make() ->title('Duplicate Serial Numbers Found') - ->body('The following serial numbers already exist with a different invoice number:
' . implode(', ', $existingSerials)) + ->body('The following serial numbers already exist with a different invoice number:
'.implode(', ', $existingSerials)) ->danger() ->duration(5000) ->send(); @@ -674,10 +662,9 @@ class LocatorInvoiceValidationResource extends Resource if ($disk->exists($path)) { $disk->delete($path); } + return; - } - else - { + } else { // Save full file path to session session(['uploaded_invoice_path' => $fullPath]); Notification::make() @@ -688,7 +675,7 @@ class LocatorInvoiceValidationResource extends Resource } } }) - ->visible(function() { + ->visible(function () { return Filament::auth()->user()->can('view import dispatch serial invoice validation'); }), @@ -696,244 +683,255 @@ class LocatorInvoiceValidationResource extends Resource ->importer(LocatorInvoiceValidationImporter::class) ->label('Import Locator Invoice') ->color('warning') - ->visible(function() { + ->visible(function () { return Filament::auth()->user()->can('view import locator invoice validation'); }), ExportAction::make() ->exporter(LocatorInvoiceValidationExporter::class) ->label('Export Locator Invoice') ->color('warning') - ->visible(function() { + ->visible(function () { return Filament::auth()->user()->can('view export locator invoice validation'); }), ]) - - // ->filters([ - // Tables\Filters\TrashedFilter::make(), - // ]) - - ->filters([ + ->filters([ Tables\Filters\TrashedFilter::make(), Filter::make('advanced_filters') - ->label('Advanced Filters') - ->form([ - Select::make('Plant') - ->label('Select Plant') - ->nullable() - // ->options(function () { - // return Plant::pluck('name', 'id'); - // }) - ->options(function (callable $get) { + ->label('Advanced Filters') + ->form([ + Select::make('Plant') + ->label('Select Plant') + ->nullable() + // ->options(function () { + // return Plant::pluck('name', 'id'); + // }) + ->options(function (callable $get) { + $userHas = Filament::auth()->user()->plant_id; + + return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); + }) + ->reactive() + ->afterStateUpdated(function ($state, callable $set, callable $get): void { + $set('pallet_number', null); + $set('invoice_number', null); + $set('serial_number', null); + $set('scanned_status', null); + $set('locator_number', null); + $set('created_from', null); + $set('created_to', null); + $set('created_by', null); + $set('scanned_from', null); + $set('scanned_to', null); + $set('scanned_by', null); + }), + Select::make('invoice_number') + ->label('Invoice Number') + ->options(function (callable $get) { + $plantId = $get('Plant'); + if (! $plantId) { + return []; + } + + return LocatorInvoiceValidation::where('plant_id', $plantId) + ->whereNotNull('invoice_number') + ->where('invoice_number', '!=', '') + ->orderBy('invoice_number', 'asc') + ->get() + ->unique('invoice_number') + ->pluck('invoice_number', 'invoice_number') + ->toArray(); + }) + ->searchable() + ->reactive(), + TextInput::make('serial_number') + ->label('Serial Number') + ->placeholder(placeholder: 'Enter Serial Number'), + + Select::make('pallet_number') + ->label('Pallet Number') + ->options(function (callable $get) { + $plantId = $get('Plant'); + if (! $plantId) { + return []; + } + + return LocatorInvoiceValidation::where('plant_id', $plantId) + ->whereNotNull('pallet_number') + ->where('pallet_number', '!=', '') + ->orderBy('pallet_number', 'asc') + ->get() + ->unique('pallet_number') + ->pluck('pallet_number', 'pallet_number') + ->toArray(); + }) + ->searchable() + ->reactive(), + Select::make('locator_number') + ->label('Locator Number') + ->options(function (callable $get) { + $plantId = $get('Plant'); + if (! $plantId) { + return []; + } + + return LocatorInvoiceValidation::where('plant_id', $plantId) + ->whereNotNull('locator_number') + ->where('locator_number', '!=', '') + ->orderBy('locator_number', 'asc') + ->get() + ->unique('locator_number') + ->pluck('locator_number', 'locator_number') + ->toArray(); + }) + ->searchable() + ->reactive(), + Select::make('scanned_status') + ->label('Scanned Status') + ->options([ + 'Scanned' => 'Scanned', + ]), + DateTimePicker::make(name: 'created_from') + ->label('Created From') + ->placeholder(placeholder: 'Select From DateTime') + ->reactive() + ->native(false), + DateTimePicker::make('created_to') + ->label('Created To') + ->placeholder(placeholder: 'Select To DateTime') + ->reactive() + ->native(false), + TextInput::make('created_by') + ->label('Created By') + ->placeholder(placeholder: 'Enter Created By'), + DateTimePicker::make(name: 'scanned_from') + ->label('Scanned From') + ->placeholder(placeholder: 'Select From DateTime') + ->reactive() + ->native(false), + DateTimePicker::make('scanned_to') + ->label('Scanned To') + ->placeholder(placeholder: 'Select To DateTime') + ->reactive() + ->native(false), + TextInput::make('scanned_by') + ->label('Scanned By') + ->placeholder(placeholder: 'Enter Scanned By'), + ]) + ->query(function ($query, array $data) { + // Hide all records initially if no filters are applied + if (empty($data['Plant']) && empty($data['invoice_number']) && empty($data['serial_number']) && empty($data['pallet_number']) && empty($data['locator_number']) && empty($data['scanned_status']) && empty($data['created_from']) && empty($data['created_to']) && empty($data['created_by']) && empty($data['scanned_from']) && empty($data['scanned_to']) && empty($data['scanned_by'])) { + return $query->whereRaw('1 = 0'); + } + + if (! empty($data['Plant'])) { // $plant = $data['Plant'] ?? null + $query->where('plant_id', $data['Plant']); + } else { $userHas = Filament::auth()->user()->plant_id; - return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); - }) - ->reactive() - ->afterStateUpdated(function ($state, callable $set, callable $get): void { - $set('pallet_number', null); - $set('invoice_number', null); - $set('serial_number', null); - $set('scanned_status', null); - $set('locator_number', null); - $set('created_from', null); - $set('created_to', null); - $set('created_by', null); - $set('scanned_from', null); - $set('scanned_to', null); - $set('scanned_by', null); - }), - Select::make('invoice_number') - ->label('Invoice Number') - ->options(function (callable $get) { - $plantId = $get('Plant'); - if (!$plantId) { - return []; + + if ($userHas && strlen($userHas) > 0) { + return $query->whereRaw('1 = 0'); } - return LocatorInvoiceValidation::where('plant_id', $plantId) - ->whereNotNull('invoice_number') - ->where('invoice_number','!=', '') - ->orderBy('invoice_number', 'asc') - ->get() - ->unique('invoice_number') - ->pluck('invoice_number', 'invoice_number') - ->toArray(); - }) - ->searchable() - ->reactive(), - TextInput::make('serial_number') - ->label('Serial Number') - ->placeholder(placeholder: 'Enter Serial Number'), + } - Select::make('pallet_number') - ->label('Pallet Number') - ->options(function (callable $get) { - $plantId = $get('Plant'); - if (!$plantId) { - return []; + if (! empty($data['invoice_number'])) { + $query->where('invoice_number', $data['invoice_number']); + } + + if (! empty($data['serial_number'])) { + $query->where('serial_number', $data['serial_number']); + } + + if (! empty($data['pallet_number'])) { + $query->where('pallet_number', $data['pallet_number']); + } + + if (! empty($data['locator_number'])) { + $query->where('locator_number', $data['locator_number']); + } + if (! empty($data['scanned_status'])) { + $query->where('scanned_status', $data['scanned_status']); + } + + if (! empty($data['created_from'])) { + $query->where('created_at', '>=', $data['created_from']); + } + + if (! empty($data['created_to'])) { + $query->where('created_at', '<=', $data['created_to']); + } + + if (! empty($data['created_by'])) { + $query->where('created_by', $data['created_by']); + } + + if (! empty($data['scanned_from'])) { + $query->where('scanned_at', '>=', $data['scanned_from']); + } + + if (! empty($data['scanned_to'])) { + $query->where('scanned_at', '<=', $data['scanned_to']); + } + + if (! empty($data['scanned_by'])) { + $query->where('scanned_by', $data['scanned_by']); + } + }) + ->indicateUsing(function (array $data) { + $indicators = []; + + if (! empty($data['Plant'])) { + $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.'; } - return LocatorInvoiceValidation::where('plant_id', $plantId) - ->whereNotNull('pallet_number') - ->where('pallet_number','!=', '') - ->orderBy('pallet_number', 'asc') - ->get() - ->unique('pallet_number') - ->pluck('pallet_number', 'pallet_number') - ->toArray(); - }) - ->searchable() - ->reactive(), - Select::make('locator_number') - ->label('Locator Number') - ->options(function (callable $get) { - $plantId = $get('Plant'); - if (!$plantId) { - return []; - } - return LocatorInvoiceValidation::where('plant_id', $plantId) - ->whereNotNull('locator_number') - ->where('locator_number','!=', '') - ->orderBy('locator_number', 'asc') - ->get() - ->unique('locator_number') - ->pluck('locator_number', 'locator_number') - ->toArray(); - }) - ->searchable() - ->reactive(), - Select::make('scanned_status') - ->label('Scanned Status') - ->options([ - 'Scanned' => 'Scanned', - ]), - DateTimePicker::make(name: 'created_from') - ->label('Created From') - ->placeholder(placeholder: 'Select From DateTime') - ->reactive() - ->native(false), - DateTimePicker::make('created_to') - ->label('Created To') - ->placeholder(placeholder: 'Select To DateTime') - ->reactive() - ->native(false), - TextInput::make('created_by') - ->label('Created By') - ->placeholder(placeholder: 'Enter Created By'), - DateTimePicker::make(name: 'scanned_from') - ->label('Scanned From') - ->placeholder(placeholder: 'Select From DateTime') - ->reactive() - ->native(false), - DateTimePicker::make('scanned_to') - ->label('Scanned To') - ->placeholder(placeholder: 'Select To DateTime') - ->reactive() - ->native(false), - TextInput::make('scanned_by') - ->label('Scanned By') - ->placeholder(placeholder: 'Enter Scanned By'), - ]) - ->query(function ($query, array $data) { - // Hide all records initially if no filters are applied - if (empty($data['Plant']) && empty($data['invoice_number']) && empty($data['serial_number']) && empty($data['pallet_number']) && empty($data['locator_number']) && empty($data['scanned_status']) && empty($data['created_from']) && empty($data['created_to']) && empty($data['created_by']) && empty($data['scanned_from']) && empty($data['scanned_to']) && empty($data['scanned_by'])) { - return $query->whereRaw('1 = 0'); - } + } - if (!empty($data['Plant'])) { //$plant = $data['Plant'] ?? null - $query->where('plant_id', $data['Plant']); - } + if (! empty($data['invoice_number'])) { + $indicators[] = 'Invoice Number: '.$data['invoice_number']; + } - if (!empty($data['invoice_number'])) { - $query->where('invoice_number', $data['invoice_number']); - } + if (! empty($data['serial_number'])) { + $indicators[] = 'Serial Number: '.$data['serial_number']; + } - if (!empty($data['serial_number'])) { - $query->where('serial_number', $data['serial_number']); - } + if (! empty($data['pallet_number'])) { + $indicators[] = 'Pallet Number: '.$data['pallet_number']; + } - if (!empty($data['pallet_number'])) { - $query->where('pallet_number', $data['pallet_number']); - } + if (! empty($data['locator_number'])) { + $indicators[] = 'Locator Number: '.$data['locator_number']; + } - if (!empty($data['locator_number'])) { - $query->where('locator_number', $data['locator_number']); - } - if (!empty($data['scanned_status'])) { - $query->where('scanned_status', $data['scanned_status']); - } + if (! empty($data['scanned_status'])) { + $indicators[] = 'Scanned Status: '.$data['scanned_status']; + } - if (!empty($data['created_from'])) { - $query->where('created_at', '>=', $data['created_from']); - } + if (! empty($data['created_from'])) { + $indicators[] = 'From: '.$data['created_from']; + } - if (!empty($data['created_to'])) { - $query->where('created_at', '<=', $data['created_to']); - } + if (! empty($data['created_to'])) { + $indicators[] = 'To: '.$data['created_to']; + } - if (!empty($data['created_by'])) { - $query->where('created_by', $data['created_by']); - } + if (! empty($data['created_by'])) { + $indicators[] = 'Created By: '.$data['created_by']; + } + if (! empty($data['scanned_from'])) { + $indicators[] = 'Scanned From: '.$data['scanned_from']; + } + if (! empty($data['scanned_to'])) { + $indicators[] = 'Scanned To: '.$data['scanned_to']; + } + if (! empty($data['scanned_by'])) { + $indicators[] = 'Scanned By: '.$data['scanned_by']; + } - if (!empty($data['scanned_from'])) { - $query->where('scanned_at', '>=', $data['scanned_from']); - } - - if (!empty($data['scanned_to'])) { - $query->where('scanned_at', '<=', $data['scanned_to']); - } - - if (!empty($data['scanned_by'])) { - $query->where('scanned_by', $data['scanned_by']); - } - }) - ->indicateUsing(function (array $data) { - $indicators = []; - - if (!empty($data['Plant'])) { - $indicators[] = 'Plant: ' . Plant::where('id', $data['Plant'])->value('name'); - } - - if (!empty($data['invoice_number'])) { - $indicators[] = 'Invoice Number: ' . $data['invoice_number']; - } - - if (!empty($data['serial_number'])) { - $indicators[] = 'Serial Number: ' . $data['serial_number']; - } - - if (!empty($data['pallet_number'])) { - $indicators[] = 'Pallet Number: ' . $data['pallet_number']; - } - - if (!empty($data['locator_number'])) { - $indicators[] = 'Locator Number: ' . $data['locator_number']; - } - - if (!empty($data['scanned_status'])) { - $indicators[] = 'Scanned Status: ' . $data['scanned_status']; - } - - if (!empty($data['created_from'])) { - $indicators[] = 'From: ' . $data['created_from']; - } - - if (!empty($data['created_to'])) { - $indicators[] = 'To: ' . $data['created_to']; - } - - if (!empty($data['created_by'])) { - $indicators[] = 'Created By: ' . $data['created_by']; - } - if (!empty($data['scanned_from'])) { - $indicators[] = 'Scanned From: ' . $data['scanned_from']; - } - if (!empty($data['scanned_to'])) { - $indicators[] = 'Scanned To: ' . $data['scanned_to']; - } - if (!empty($data['scanned_by'])) { - $indicators[] = 'Scanned By: ' . $data['scanned_by']; - } - - return $indicators; - }) + return $indicators; + }), ]) ->filtersFormMaxHeight('280px') ->actions([ diff --git a/app/Filament/Resources/LocatorResource.php b/app/Filament/Resources/LocatorResource.php index 68f16d8..3509655 100644 --- a/app/Filament/Resources/LocatorResource.php +++ b/app/Filament/Resources/LocatorResource.php @@ -5,21 +5,20 @@ namespace App\Filament\Resources; use App\Filament\Exports\LocatorExporter; use App\Filament\Imports\LocatorImporter; use App\Filament\Resources\LocatorResource\Pages; -use App\Filament\Resources\LocatorResource\RelationManagers; use App\Models\Locator; use App\Models\PalletValidation; 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\Forms; +use Filament\Forms\Components\DateTimePicker; use Filament\Forms\Components\Select; +use Filament\Forms\Components\TextInput; use Filament\Forms\Form; +use Filament\Forms\Get; use Filament\Resources\Resource; use Filament\Tables; use Filament\Tables\Actions\ExportAction; +use Filament\Tables\Actions\ImportAction; use Filament\Tables\Filters\Filter; use Filament\Tables\Table; use Illuminate\Database\Eloquent\Builder; @@ -48,25 +47,25 @@ class LocatorResource extends Resource ->reactive() ->options(function (callable $get) { $userHas = Filament::auth()->user()->plant_id; + return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); }) ->default(function () { return optional(Locator::latest()->first())->plant_id; }) - ->disabled(fn (Get $get) => !empty($get('id'))) + ->disabled(fn (Get $get) => ! empty($get('id'))) // ->afterStateUpdated(fn ($set) => $set('block_id', null) & $set('name', null) & $set('start_time', null) & $set('duration', null) & $set('end_time', null)) ->afterStateUpdated(function ($state, callable $set, callable $get) { $plantId = $get('plant_id'); // Ensure `linestop_id` is not cleared - if (!$plantId) { + if (! $plantId) { $set('locPlantError', 'Please select a plant first.'); $set('locator_number', null); $set('locator_quantity', 0); $set('operator_id', Filament::auth()->user()?->name); + return; - } - else - { + } else { $set('locPlantError', null); $set('locator_number', null); $set('locator_quantity', 0); @@ -86,21 +85,20 @@ class LocatorResource extends Resource ->afterStateUpdated(function ($state, callable $set, callable $get) { $plantId = $get('plant_id'); $locator = $get('locator_number'); - if (!$plantId) { + if (! $plantId) { $set('locNameError', 'Please select a plant first.'); $set('locator_number', null); $set('locator_quantity', 0); $set('operator_id', Filament::auth()->user()?->name); + return; - } - else if (!$locator || Str::length($locator) < 7) { + } elseif (! $locator || Str::length($locator) < 7) { $set('locNameError', 'Please scan the valid locator number.'); $set('locator_quantity', 0); $set('operator_id', Filament::auth()->user()?->name); + return; - } - else - { + } else { $set('locNameError', null); $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); @@ -145,6 +143,7 @@ class LocatorResource extends Resource $paginator = $livewire->getTableRecords(); $perPage = method_exists($paginator, 'perPage') ? $paginator->perPage() : 10; $currentPage = method_exists($paginator, 'currentPage') ? $paginator->currentPage() : 1; + return ($currentPage - 1) * $perPage + $rowLoop->iteration; }), Tables\Columns\TextColumn::make('plant.name') @@ -184,149 +183,163 @@ class LocatorResource extends Resource ->filters([ Tables\Filters\TrashedFilter::make(), Filter::make('advanced_filters') - ->label('Advanced Filters') - ->form([ - Select::make('Plant') - ->label('Select Plant') - ->nullable() - // ->options(function () { - // return Plant::pluck('name', 'id'); - // }) - ->options(function (callable $get) { + ->label('Advanced Filters') + ->form([ + Select::make('Plant') + ->label('Select Plant') + ->nullable() + // ->options(function () { + // return Plant::pluck('name', 'id'); + // }) + ->options(function (callable $get) { + $userHas = Filament::auth()->user()->plant_id; + + return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); + }) + ->reactive() + ->afterStateUpdated(function ($state, callable $set, callable $get): void { + $set('locator_number', null); + $set('locator_quantity', null); + $set('created_from', null); + $set('created_to', null); + $set('created_by', null); + $set('updated_from', null); + $set('updated_to', null); + }), + Select::make('locator_number') + ->label('Locator Number') + ->options(function (callable $get) { + $plantId = $get('Plant'); + if (! $plantId) { + return []; + } + + return Locator::where('plant_id', $plantId)->orderBy('locator_number', 'asc')->get()->unique('locator_number')->pluck('locator_number', 'locator_number')->toArray(); + // ->whereNotNull('locator_number') + // ->where('locator_number','!=', '') + }) + ->searchable() + ->reactive(), + Select::make('locator_quantity') + ->label('Locator Quantity') + ->options([ + 0 => 0, + 1 => 1, + 2 => 2, + ]) + ->reactive(), + DateTimePicker::make(name: 'created_from') + ->label('Created From') + ->placeholder(placeholder: 'Select From DateTime') + ->reactive() + ->native(false), + DateTimePicker::make('created_to') + ->label('Created To') + ->placeholder(placeholder: 'Select To DateTime') + ->reactive() + ->native(false), + TextInput::make('created_by') + ->label('Created By') + ->reactive() + ->placeholder(placeholder: 'Enter Created By'), + DateTimePicker::make(name: 'updated_from') + ->label('Updated From') + ->placeholder(placeholder: 'Select From DateTime') + ->reactive() + ->native(false), + DateTimePicker::make('updated_to') + ->label('Updated To') + ->placeholder(placeholder: 'Select To DateTime') + ->reactive() + ->native(false), + ]) + ->query(function ($query, array $data) { + // Hide all records initially if no filters are applied + if (empty($data['Plant']) && empty($data['locator_number']) && $data['locator_quantity'] == null && empty($data['created_from']) && empty($data['created_to']) && empty($data['created_by']) && empty($data['updated_from']) && empty($data['updated_to'])) { + return $query->whereRaw('1 = 0'); + } + + if (! empty($data['Plant'])) { // $plant = $data['Plant'] ?? null + $query->where('plant_id', $data['Plant']); + } else { $userHas = Filament::auth()->user()->plant_id; - return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); - }) - ->reactive() - ->afterStateUpdated(function ($state, callable $set, callable $get): void { - $set('locator_number', null); - $set('locator_quantity', null); - $set('created_from', null); - $set('created_to', null); - $set('created_by', null); - $set('updated_from', null); - $set('updated_to', null); - }), - Select::make('locator_number') - ->label('Locator Number') - ->options(function (callable $get) { - $plantId = $get('Plant'); - if (!$plantId) { - return []; + + if ($userHas && strlen($userHas) > 0) { + return $query->whereRaw('1 = 0'); } - return Locator::where('plant_id', $plantId)->orderBy('locator_number', 'asc')->get()->unique('locator_number')->pluck('locator_number', 'locator_number')->toArray(); - // ->whereNotNull('locator_number') - // ->where('locator_number','!=', '') - }) - ->searchable() - ->reactive(), - Select::make('locator_quantity') - ->label('Locator Quantity') - ->options([ - 0 => 0, - 1 => 1, - 2 => 2, - ]) - ->reactive(), - DateTimePicker::make(name: 'created_from') - ->label('Created From') - ->placeholder(placeholder: 'Select From DateTime') - ->reactive() - ->native(false), - DateTimePicker::make('created_to') - ->label('Created To') - ->placeholder(placeholder: 'Select To DateTime') - ->reactive() - ->native(false), - TextInput::make('created_by') - ->label('Created By') - ->reactive() - ->placeholder(placeholder: 'Enter Created By'), - DateTimePicker::make(name: 'updated_from') - ->label('Updated From') - ->placeholder(placeholder: 'Select From DateTime') - ->reactive() - ->native(false), - DateTimePicker::make('updated_to') - ->label('Updated To') - ->placeholder(placeholder: 'Select To DateTime') - ->reactive() - ->native(false), - ]) - ->query(function ($query, array $data) { - // Hide all records initially if no filters are applied - if (empty($data['Plant']) && empty($data['locator_number']) && $data['locator_quantity'] == null && empty($data['created_from']) && empty($data['created_to']) && empty($data['created_by']) && empty($data['updated_from']) && empty($data['updated_to'])) { - return $query->whereRaw('1 = 0'); - } + } - if (!empty($data['Plant'])) { //$plant = $data['Plant'] ?? null - $query->where('plant_id', $data['Plant']); - } + if (! empty($data['locator_number'])) { + $query->where('locator_number', $data['locator_number']); + } - if (!empty($data['locator_number'])) { - $query->where('locator_number', $data['locator_number']); - } + if ($data['locator_quantity'] != null && $data['locator_quantity'] != '') { // isset($data['locator_quantity']) && + $query->where('locator_quantity', $data['locator_quantity']); // (int) + } - if ($data['locator_quantity'] != null && $data['locator_quantity'] != '') { //isset($data['locator_quantity']) && - $query->where('locator_quantity', $data['locator_quantity']);//(int) - } + if (! empty($data['created_from'])) { + $query->where('created_at', '>=', $data['created_from']); + } - if (!empty($data['created_from'])) { - $query->where('created_at', '>=', $data['created_from']); - } + if (! empty($data['created_to'])) { + $query->where('created_at', '<=', $data['created_to']); + } - if (!empty($data['created_to'])) { - $query->where('created_at', '<=', $data['created_to']); - } + if (! empty($data['created_by'])) { + $query->where('operator_id', $data['created_by']); + } - if (!empty($data['created_by'])) { - $query->where('operator_id', $data['created_by']); - } + if (! empty($data['updated_from'])) { + $query->where('updated_at', '>=', $data['updated_from']); + } - if (!empty($data['updated_from'])) { - $query->where('updated_at', '>=', $data['updated_from']); - } + if (! empty($data['updated_to'])) { + $query->where('updated_at', '<=', $data['updated_to']); + } + }) + ->indicateUsing(function (array $data) { + $indicators = []; - if (!empty($data['updated_to'])) { - $query->where('updated_at', '<=', $data['updated_to']); - } - }) - ->indicateUsing(function (array $data) { - $indicators = []; + if (! empty($data['Plant'])) { + $indicators[] = 'Plant: '.Plant::where('id', $data['Plant'])->value('name'); + } else { + $userHas = Filament::auth()->user()->plant_id; - if (!empty($data['Plant'])) { - $indicators[] = 'Plant: ' . Plant::where('id', $data['Plant'])->value('name'); - } + if ($userHas && strlen($userHas) > 0) { + return 'Plant: Choose plant to filter records.'; + } + } - if (!empty($data['locator_number'])) { - $indicators[] = 'Locator Number: ' . $data['locator_number']; - } + if (! empty($data['locator_number'])) { + $indicators[] = 'Locator Number: '.$data['locator_number']; + } - if ($data['locator_quantity'] != null && $data['locator_quantity'] != '') { //isset($data['locator_quantity']) && - $indicators[] = 'Locator Quantity: ' . $data['locator_quantity']; - } + if ($data['locator_quantity'] != null && $data['locator_quantity'] != '') { // isset($data['locator_quantity']) && + $indicators[] = 'Locator Quantity: '.$data['locator_quantity']; + } - if (!empty($data['created_from'])) { - $indicators[] = 'From: ' . $data['created_from']; - } + if (! empty($data['created_from'])) { + $indicators[] = 'From: '.$data['created_from']; + } - if (!empty($data['created_to'])) { - $indicators[] = 'To: ' . $data['created_to']; - } + if (! empty($data['created_to'])) { + $indicators[] = 'To: '.$data['created_to']; + } - if (!empty($data['created_by'])) { - $indicators[] = 'Created By: ' . $data['created_by']; - } + if (! empty($data['created_by'])) { + $indicators[] = 'Created By: '.$data['created_by']; + } - if (!empty($data['updated_from'])) { - $indicators[] = 'Updated From: ' . $data['updated_from']; - } + if (! empty($data['updated_from'])) { + $indicators[] = 'Updated From: '.$data['updated_from']; + } - if (!empty($data['updated_to'])) { - $indicators[] = 'Updated To: ' . $data['updated_to']; - } + if (! empty($data['updated_to'])) { + $indicators[] = 'Updated To: '.$data['updated_to']; + } - return $indicators; - }) + return $indicators; + }), ]) ->filtersFormMaxHeight('280px') ->actions([ @@ -345,14 +358,14 @@ class LocatorResource extends Resource ->label('Import Locators') ->color('warning') ->importer(LocatorImporter::class) - ->visible(function() { + ->visible(function () { return Filament::auth()->user()->can('view import locator'); }), ExportAction::make() ->label('Export Locators') ->color('warning') ->exporter(LocatorExporter::class) - ->visible(function() { + ->visible(function () { return Filament::auth()->user()->can('view export locator'); }), ]); diff --git a/app/Filament/Resources/MachineResource.php b/app/Filament/Resources/MachineResource.php index c99a1f0..00c1db9 100644 --- a/app/Filament/Resources/MachineResource.php +++ b/app/Filament/Resources/MachineResource.php @@ -5,7 +5,6 @@ namespace App\Filament\Resources; use App\Filament\Exports\MachineExporter; use App\Filament\Imports\MachineImporter; use App\Filament\Resources\MachineResource\Pages; -use App\Filament\Resources\MachineResource\RelationManagers; use App\Models\Line; use App\Models\Machine; use App\Models\Plant; @@ -16,11 +15,11 @@ use Filament\Forms\Form; use Filament\Forms\Get; use Filament\Resources\Resource; use Filament\Tables; +use Filament\Tables\Actions\ExportAction; +use Filament\Tables\Actions\ImportAction; use Filament\Tables\Table; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\SoftDeletingScope; -use Filament\Tables\Actions\ImportAction; -use Filament\Tables\Actions\ExportAction; use Illuminate\Validation\Rule; use Str; @@ -45,22 +44,22 @@ class MachineResource extends Resource ->reactive() ->options(function (callable $get) { $userHas = Filament::auth()->user()->plant_id; + return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); }) ->default(function () { return optional(Machine::latest()->first())->plant_id; }) - ->disabled(fn (Get $get) => !empty($get('id'))) + ->disabled(fn (Get $get) => ! empty($get('id'))) ->afterStateUpdated(function ($state, callable $set, callable $get) { $plantId = $get('plant_id'); - if (!$plantId) { + if (! $plantId) { $set('mPlantError', 'Please select a plant first.'); $set('line_id', null); $set('work_group_master_id', null); + return; - } - else - { + } else { $set('mPlantError', null); } }) @@ -75,7 +74,7 @@ class MachineResource extends Resource ->required() ->reactive() ->options(function (callable $get) { - if (!$get('plant_id')) { + if (! $get('plant_id')) { return []; } @@ -84,16 +83,15 @@ class MachineResource extends Resource ->default(function () { return optional(Machine::latest()->first())->line_id; }) - ->disabled(fn (Get $get) => !empty($get('id'))) + ->disabled(fn (Get $get) => ! empty($get('id'))) ->afterStateUpdated(function ($state, callable $set, callable $get) { $lineId = $get('line_id'); - if (!$lineId) { + if (! $lineId) { $set('mLineError', 'Please select a line first.'); $set('work_group_master_id', null); + return; - } - else - { + } else { // $grpWrkCnr = Line::find($lineId)->group_work_center; // if (!$grpWrkCnr || Str::length($grpWrkCnr) < 1) // { @@ -115,7 +113,7 @@ class MachineResource extends Resource ->required() ->reactive() ->options(function (callable $get) { - if (!$get('plant_id') || !$get('line_id')) { + if (! $get('plant_id') || ! $get('line_id')) { return []; } @@ -123,7 +121,7 @@ class MachineResource extends Resource $workGroupIds = []; for ($i = 1; $i <= $line->no_of_operation; $i++) { $column = "work_group{$i}_id"; - if (!empty($line->$column)) { + if (! empty($line->$column)) { $workGroupIds[] = $line->$column; } } @@ -133,15 +131,14 @@ class MachineResource extends Resource ->default(function () { return optional(Machine::latest()->first())->work_group_master_id; }) - ->disabled(fn (Get $get) => !empty($get('id'))) + ->disabled(fn (Get $get) => ! empty($get('id'))) ->afterStateUpdated(function ($state, callable $set, callable $get) { $lineId = $get('line_id'); - if (!$lineId) { + if (! $lineId) { $set('mGroupWorkError', 'Please select a line first.'); + return; - } - else - { + } else { // $grpWrkCnr = Line::find($lineId)->group_work_center; // if (!$grpWrkCnr || Str::length($grpWrkCnr) < 1) // { @@ -164,7 +161,7 @@ class MachineResource extends Resource ->required() ->rule(function (callable $get) { return Rule::unique('machines', 'name') - //->where('line_id', $get('line_id')) + // ->where('line_id', $get('line_id')) ->where('plant_id', $get('plant_id')) ->ignore($get('id')); // Ignore current record during updates }), @@ -194,6 +191,7 @@ class MachineResource extends Resource $paginator = $livewire->getTableRecords(); $perPage = method_exists($paginator, 'perPage') ? $paginator->perPage() : 10; $currentPage = method_exists($paginator, 'currentPage') ? $paginator->currentPage() : 1; + return ($currentPage - 1) * $perPage + $rowLoop->iteration; }), Tables\Columns\TextColumn::make('plant.name') @@ -254,14 +252,14 @@ class MachineResource extends Resource ->label('Import Machines') ->color('warning') ->importer(MachineImporter::class) - ->visible(function() { + ->visible(function () { return Filament::auth()->user()->can('view import machine'); }), ExportAction::make() ->label('Export Machines') ->color('warning') ->exporter(MachineExporter::class) - ->visible(function() { + ->visible(function () { return Filament::auth()->user()->can('view export machine'); }), ]); diff --git a/app/Filament/Resources/MfmParameterResource.php b/app/Filament/Resources/MfmParameterResource.php index 07dd55d..2c60311 100644 --- a/app/Filament/Resources/MfmParameterResource.php +++ b/app/Filament/Resources/MfmParameterResource.php @@ -36,30 +36,84 @@ class MfmParameterResource extends Resource Forms\Components\Select::make('plant_id') ->label('Plant') ->relationship('plant', 'name') + ->reactive() ->options(function (callable $get) { $userHas = Filament::auth()->user()->plant_id; 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(), Forms\Components\Select::make('device_master_id') ->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(), Forms\Components\Select::make('mfm_meter_id') ->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(), Forms\Components\TextInput::make('name') ->label('Parameter Name') + ->reactive() ->required(), Forms\Components\TextInput::make('register_id') ->label('Register ID') + ->reactive() ->required(), Forms\Components\TextInput::make('identifier') ->label('Identifier') + ->reactive() ->required(), Forms\Components\TextInput::make('byte_to_convert') ->label('Byte To Convert') + ->reactive() ->default(2) ->required(), Forms\Components\TextInput::make('type_to_convert') @@ -67,6 +121,7 @@ class MfmParameterResource extends Resource ->required(), Forms\Components\TextInput::make('decimal_to_display') ->label('Decimal To Display') + ->reactive() ->default(1) ->required(), ]) diff --git a/app/Filament/Resources/MotorTestingMasterResource.php b/app/Filament/Resources/MotorTestingMasterResource.php index 1c4de36..4b6d6bf 100644 --- a/app/Filament/Resources/MotorTestingMasterResource.php +++ b/app/Filament/Resources/MotorTestingMasterResource.php @@ -5,7 +5,6 @@ namespace App\Filament\Resources; use App\Filament\Exports\MotorTestingMasterExporter; use App\Filament\Imports\MotorTestingMasterImporter; use App\Filament\Resources\MotorTestingMasterResource\Pages; -use App\Filament\Resources\MotorTestingMasterResource\RelationManagers; use App\Models\Configuration; use App\Models\Item; use App\Models\MotorTestingMaster; @@ -20,12 +19,12 @@ use Filament\Forms\Form; use Filament\Forms\Get; use Filament\Resources\Resource; use Filament\Tables; +use Filament\Tables\Actions\ExportAction; +use Filament\Tables\Actions\ImportAction; +use Filament\Tables\Filters\Filter; use Filament\Tables\Table; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\SoftDeletingScope; -use Filament\Tables\Actions\ImportAction; -use Filament\Tables\Actions\ExportAction; -use Filament\Tables\Filters\Filter; use Illuminate\Validation\Rule; class MotorTestingMasterResource extends Resource @@ -49,20 +48,20 @@ class MotorTestingMasterResource extends Resource ->reactive() ->options(function (callable $get) { $userHas = Filament::auth()->user()->plant_id; + return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); }) ->default(function () { return optional(MotorTestingMaster::latest()->first())->plant_id; }) - ->disabled(fn (Get $get) => !empty($get('id'))) + ->disabled(fn (Get $get) => ! empty($get('id'))) ->afterStateUpdated(function ($state, callable $set, callable $get) { $plantId = $get('plant_id'); - if (!$plantId) { + if (! $plantId) { $set('mTmError', 'Please select a plant first.'); + return; - } - else - { + } else { $set('mTmError', null); } }) @@ -78,10 +77,10 @@ class MotorTestingMasterResource extends Resource ->reactive(), Forms\Components\Select::make('item_id') ->label('Item Code') - //->relationship('item', 'name') + // ->relationship('item', 'name') ->options(function (callable $get) { $plantId = $get('plant_id'); - if (!$plantId) { + if (! $plantId) { return []; } @@ -106,19 +105,19 @@ class MotorTestingMasterResource extends Resource ->minLength(6) ->afterStateUpdated(function ($state, callable $set, callable $get) { $code = $get('subassembly_code'); - if (!$code) { + if (! $code) { $set('iCodeError', 'Scan the valid Subassembly Code.'); + return; - } - else - { + } else { if (strlen($code) < 6) { $set('iCodeError', 'Subassembly code must be at least 6 digits.'); + return; - } - else if (!preg_match('/^[a-zA-Z0-9]{6,}$/', $code)) { - $set('code',null); + } elseif (! preg_match('/^[a-zA-Z0-9]{6,}$/', $code)) { + $set('code', null); $set('iCodeError', 'Subassembly code must contain only alpha-numeric characters.'); + return; } $set('iCodeError', null); @@ -143,24 +142,21 @@ class MotorTestingMasterResource extends Resource Forms\Components\Select::make('phase') ->label('Phase') ->options(function (callable $get) { - $plantId = $get('plant_id'); + $plantId = $get('plant_id'); - if ($plantId) - { - return Configuration::where('plant_id', $plantId) - ->where('c_name', 'MOTOR_PHASE') - ->orderBy('created_at') - ->pluck('c_value', 'c_value') - ->toArray(); - } - else - { - return Configuration::where('c_name', 'MOTOR_PHASE') - ->orderBy('created_at') - ->pluck('c_value', 'c_value') - ->toArray(); - } - }) + if ($plantId) { + return Configuration::where('plant_id', $plantId) + ->where('c_name', 'MOTOR_PHASE') + ->orderBy('created_at') + ->pluck('c_value', 'c_value') + ->toArray(); + } else { + return Configuration::where('c_name', 'MOTOR_PHASE') + ->orderBy('created_at') + ->pluck('c_value', 'c_value') + ->toArray(); + } + }) ->selectablePlaceholder(false) ->afterStateUpdated(function ($state, callable $set, callable $get) { @@ -197,16 +193,13 @@ class MotorTestingMasterResource extends Resource ->selectablePlaceholder(false) ->options(function (callable $get) { $plantId = $get('plant_id'); - if ($plantId) - { + if ($plantId) { return Configuration::where('plant_id', $plantId) - ->where('c_name', 'MOTOR_CONNECTION') - ->orderBy('created_at') - ->pluck('c_value', 'c_value') - ->toArray(); - } - else - { + ->where('c_name', 'MOTOR_CONNECTION') + ->orderBy('created_at') + ->pluck('c_value', 'c_value') + ->toArray(); + } else { return Configuration::where('c_name', 'MOTOR_CONNECTION') ->orderBy('created_at') ->pluck('c_value', 'c_value') @@ -230,16 +223,13 @@ class MotorTestingMasterResource extends Resource ->selectablePlaceholder(false) ->options(function (callable $get) { $plantId = $get('plant_id'); - if ($plantId) - { + if ($plantId) { return Configuration::where('plant_id', $plantId) - ->where('c_name', 'INSULATION_RESISTANCE_TYPE') - ->orderBy('created_at') - ->pluck('c_value', 'c_value') - ->toArray(); - } - else - { + ->where('c_name', 'INSULATION_RESISTANCE_TYPE') + ->orderBy('created_at') + ->pluck('c_value', 'c_value') + ->toArray(); + } else { return Configuration::where('c_name', 'INSULATION_RESISTANCE_TYPE') ->orderBy('created_at') ->pluck('c_value', 'c_value') @@ -317,6 +307,7 @@ class MotorTestingMasterResource extends Resource $paginator = $livewire->getTableRecords(); $perPage = method_exists($paginator, 'perPage') ? $paginator->perPage() : 10; $currentPage = method_exists($paginator, 'currentPage') ? $paginator->currentPage() : 1; + return ($currentPage - 1) * $perPage + $rowLoop->iteration; }), Tables\Columns\TextColumn::make('plant.name') @@ -474,6 +465,7 @@ class MotorTestingMasterResource extends Resource // }) ->options(function (callable $get) { $userHas = Filament::auth()->user()->plant_id; + return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); }) ->reactive() @@ -488,6 +480,7 @@ class MotorTestingMasterResource extends Resource ->nullable() ->options(function (callable $get) { $pId = $get('Plant'); + return Item::whereHas('motorTestingMasters', function ($query) use ($pId) { if ($pId) { $query->where('plant_id', $pId); @@ -505,7 +498,7 @@ class MotorTestingMasterResource extends Resource ->options([ 'All' => 'All', 'Y' => 'Y', - 'N' => 'N' + 'N' => 'N', ]) ->default(null) ->inlineLabel(false) @@ -516,16 +509,13 @@ class MotorTestingMasterResource extends Resource ->options(function (callable $get) { $plantId = $get('plant_id'); - if ($plantId) - { + if ($plantId) { return Configuration::where('plant_id', $plantId) ->where('c_name', 'MOTOR_PHASE') ->orderBy('created_at') ->pluck('c_value', 'c_value') ->toArray(); - } - else - { + } else { return Configuration::where('c_name', 'MOTOR_PHASE') ->orderBy('created_at') ->pluck('c_value', 'c_value') @@ -544,16 +534,13 @@ class MotorTestingMasterResource extends Resource ->nullable() ->options(function (callable $get) { $plantId = $get('plant_id'); - if ($plantId) - { + if ($plantId) { return Configuration::where('plant_id', $plantId) ->where('c_name', 'MOTOR_CONNECTION') ->orderBy('created_at') ->pluck('c_value', 'c_value') ->toArray(); - } - else - { + } else { return Configuration::where('c_name', 'MOTOR_CONNECTION') ->orderBy('created_at') ->pluck('c_value', 'c_value') @@ -571,12 +558,9 @@ class MotorTestingMasterResource extends Resource ->nullable() ->options(function (callable $get) { $plantId = $get('Plant'); - if (!$plantId) - { + if (! $plantId) { 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'); } }) @@ -597,12 +581,9 @@ class MotorTestingMasterResource extends Resource ->nullable() ->options(function (callable $get) { $plantId = $get('Plant'); - if (!$plantId) - { + if (! $plantId) { 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'); } }) @@ -625,127 +606,139 @@ class MotorTestingMasterResource extends Resource return $query->whereRaw('1 = 0'); } - if (!empty($data['Plant'])) { + if (! empty($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'])) { $itemIds = Item::where('id', $data['Item']) ->pluck('id') ->toArray(); - if (!empty($itemIds)) { + if (! empty($itemIds)) { $query->whereIn('item_id', $itemIds); } } - if (!empty($data['description'])) { + if (! empty($data['description'])) { $pId = $data['Plant'] ?? null; - $descIds = Item::where('description', 'like', '%' . $data['description'] . '%')->whereHas('motorTestingMasters', function ($query) use ($pId) { - if ($pId) { $query->where('plant_id', $pId); } - })->pluck('id')->toArray(); + $descIds = Item::where('description', 'like', '%'.$data['description'].'%')->whereHas('motorTestingMasters', function ($query) use ($pId) { + if ($pId) { + $query->where('plant_id', $pId); + } + })->pluck('id')->toArray(); - if (!empty($descIds)) { + if (! empty($descIds)) { $query->whereIn('item_id', $descIds); } } if ($data['isi_type'] == 'Y') { $query->where('isi_model', true); - } - else if ($data['isi_type'] == 'N') { + } elseif ($data['isi_type'] == 'N') { $query->where('isi_model', false); } - if (!empty($data['phase_type'])) { + if (! empty($data['phase_type'])) { $query->where('phase', $data['phase_type']); } - if (!empty($data['connection_type'])) { + if (! empty($data['connection_type'])) { $query->where('connection', $data['connection_type']); } - if (!empty($data['created_by'])) { + if (! empty($data['created_by'])) { $query->where('created_by', $data['created_by']); } - if (!empty($data['created_from'])) { + if (! empty($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']); } - if (!empty($data['updated_by'])) { + if (! empty($data['updated_by'])) { $query->where('updated_by', $data['updated_by']); } - if (!empty($data['updated_from'])) { + if (! empty($data['updated_from'])) { $query->where('updated_at', '>=', $data['updated_from']); } - if (!empty($data['updated_to'])) { + if (! empty($data['updated_to'])) { $query->where('updated_at', '<=', $data['updated_to']); } }) ->indicateUsing(function (array $data) { $indicators = []; - if (!empty($data['Plant'])) { - $indicators[] = 'Plant: ' . Plant::where('id', $data['Plant'])->value('name'); + if (! empty($data['Plant'])) { + $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'])) { $itemCode = Item::find($data['Item'])->code ?? 'Unknown'; - $indicators[] = 'Item Codes: ' . $itemCode; + $indicators[] = 'Item Codes: '.$itemCode; } - if (!empty($data['description'])) { - $indicators[] = 'Description: ' . $data['description']; + if (! empty($data['description'])) { + $indicators[] = 'Description: '.$data['description']; } if ($data['isi_type'] == 'Y') { $indicators[] = 'ISI Model: Yes'; - } - else if ($data['isi_type'] == 'N') { + } elseif ($data['isi_type'] == 'N') { $indicators[] = 'ISI Model: No'; } - if (!empty($data['phase_type'])) { - $indicators[] = 'Phase: ' . $data['phase_type']; + if (! empty($data['phase_type'])) { + $indicators[] = 'Phase: '.$data['phase_type']; } - if (!empty($data['connection_type'])) { - $indicators[] = 'Connection: ' . $data['connection_type']; + if (! empty($data['connection_type'])) { + $indicators[] = 'Connection: '.$data['connection_type']; } - if (!empty($data['created_by'])) { - $indicators[] = 'Created By: ' . $data['created_by']; + if (! empty($data['created_by'])) { + $indicators[] = 'Created By: '.$data['created_by']; } - if (!empty($data['created_from'])) { - $indicators[] = 'Created From: ' . $data['created_from']; + if (! empty($data['created_from'])) { + $indicators[] = 'Created From: '.$data['created_from']; } - if (!empty($data['created_to'])) { - $indicators[] = 'Created To: ' . $data['created_to']; + if (! empty($data['created_to'])) { + $indicators[] = 'Created To: '.$data['created_to']; } - if (!empty($data['updated_by'])) { - $indicators[] = 'Updated By: ' . $data['updated_by']; + if (! empty($data['updated_by'])) { + $indicators[] = 'Updated By: '.$data['updated_by']; } - if (!empty($data['updated_from'])) { - $indicators[] = 'Updated From: ' . $data['updated_from']; + if (! empty($data['updated_from'])) { + $indicators[] = 'Updated From: '.$data['updated_from']; } - if (!empty($data['updated_to'])) { - $indicators[] = 'Updated To: ' . $data['updated_to']; + if (! empty($data['updated_to'])) { + $indicators[] = 'Updated To: '.$data['updated_to']; } return $indicators; - }) + }), ]) ->filtersFormMaxHeight('280px') ->actions([ @@ -764,14 +757,14 @@ class MotorTestingMasterResource extends Resource ->label('Import Motor Testing Masters') ->color('warning') ->importer(MotorTestingMasterImporter::class) - ->visible(function() { + ->visible(function () { return Filament::auth()->user()->can('view import motor testing master'); }), ExportAction::make() ->label('Export Motor Testing Masters') ->color('warning') ->exporter(MotorTestingMasterExporter::class) - ->visible(function() { + ->visible(function () { return Filament::auth()->user()->can('view export motor testing master'); }), ]); diff --git a/app/Filament/Resources/PalletValidationResource.php b/app/Filament/Resources/PalletValidationResource.php index 242c29c..395bfc8 100644 --- a/app/Filament/Resources/PalletValidationResource.php +++ b/app/Filament/Resources/PalletValidationResource.php @@ -5,31 +5,24 @@ namespace App\Filament\Resources; use App\Filament\Exports\PalletValidationExporter; use App\Filament\Imports\PalletValidationImporter; use App\Filament\Resources\PalletValidationResource\Pages; -use App\Filament\Resources\PalletValidationResource\RelationManagers; -use App\Models\Item; use App\Models\LocatorInvoiceValidation; use App\Models\PalletValidation; use App\Models\Plant; -use App\Models\StickerMaster; use Filament\Facades\Filament; 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\Form; use Filament\Resources\Resource; use Filament\Tables; +use Filament\Tables\Actions\ExportAction; +use Filament\Tables\Actions\ImportAction; +use Filament\Tables\Filters\Filter; use Filament\Tables\Table; use Illuminate\Database\Eloquent\Builder; 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 { @@ -47,148 +40,147 @@ class PalletValidationResource extends Resource return $form ->schema([ Section::make('') - ->schema([ - Forms\Components\Select::make('plant_id') - ->label('Plant') - ->relationship('plant', 'name') - ->required() - ->reactive() - ->options(function (callable $get) { - $userHas = Filament::auth()->user()->plant_id; - return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); - }) - ->afterStateUpdated(function ($state, callable $set) { - $set('pallet_number', null); - $set('serial_number', null); - $set('removeSno_number', null); - $set('Sno_quantity', 0); - $set('pending_pallet_list', null); - }), - Forms\Components\TextInput::make('pallet_number') - ->label('Scan Pallet No') - ->reactive() - ->required() - ->readonly() //fn ($get) => (bool)$get('pallet_number_locked') || $get('serial_number') || $get('removeSno_number') - ->extraAttributes([ - 'x-data' => '{ value: "" }', - 'x-model' => 'value', - 'x-on:keydown.enter.prevent' => '$wire.processPalletNo()', - ]) - ->suffixAction(fn ($get,$set) => - Forms\Components\Actions\Action::make('addPallet') - ->label('') - ->button() - ->icon('heroicon-o-plus') - ->color('primary') - ->extraAttributes([ - 'class' => 'p-1 w-7 h-7', - ]) - ->action(function ($get, $set, $livewire) { - $plantId = $get('plant_id'); + ->schema([ + Forms\Components\Select::make('plant_id') + ->label('Plant') + ->relationship('plant', 'name') + ->required() + ->reactive() + ->options(function (callable $get) { + $userHas = Filament::auth()->user()->plant_id; - session(['pallet_clicked_time' => now()->toDateTimeString()]); - - session(['pallet_created_by' => Filament::auth()->user()->name]); - - $year = now()->format('y'); - $month = now()->format('m'); - $prefix = "EP-{$year}{$month}"; - - $lastPallet1 = PalletValidation::where('pallet_number', 'like', "{$prefix}%")->orderByDesc('pallet_number')->first(); //->where('plant_id', $plantId) - $lastPallet2 = LocatorInvoiceValidation::where('pallet_number', 'like', "{$prefix}%")->orderByDesc('pallet_number')->first(); - $newNumber = '001'; // $lastPallet ? str_pad(intval(substr($lastPallet->pallet_number, -3)) + 1, 3, '0', STR_PAD_LEFT) : '001'; - if ($lastPallet1 && $lastPallet2) { - $serialPart1 = substr($lastPallet1->pallet_number, strlen($prefix)); - $serialPart2 = substr($lastPallet2->pallet_number, strlen($prefix)); - if (intval($serialPart1) > intval($serialPart2)) { - $newNumber = str_pad(intval($serialPart1) + 1, strlen($serialPart1), '0', STR_PAD_LEFT); - } else { - $newNumber = str_pad(intval($serialPart2) + 1, strlen($serialPart2), '0', STR_PAD_LEFT); - } - } - else if ($lastPallet1) { - $serialPart1 = substr($lastPallet1->pallet_number, strlen($prefix)); - // OR - // $serialPart = str_replace($prefix, '', $lastPallet->pallet_number); - $newNumber = str_pad(intval($serialPart1) + 1, strlen($serialPart1), '0', STR_PAD_LEFT); - } - else if ($lastPallet2) { - $serialPart2 = substr($lastPallet2->pallet_number, strlen($prefix)); - // OR - // $serialPart = str_replace($prefix, '', $lastPallet->pallet_number); - $newNumber = str_pad(intval($serialPart2) + 1, strlen($serialPart2), '0', STR_PAD_LEFT); - } - - $newPalletNumber = "{$prefix}{$newNumber}"; - - $set('pallet_number', $newPalletNumber); - $set('pallet_number_locked', true); - $set('plant_id', $plantId); - - $livewire->redirectToQrPdf($newPalletNumber); - }) - ), - - Forms\Components\TextInput::make('serial_number') - ->label('Scan Serial No') - ->reactive() - ->minLength(9) - ->readOnly(fn (callable $get) => !$get('pallet_number') || $get('removeSno_number')) - ->extraAttributes([ - 'x-on:keydown.enter.prevent' => '$wire.processPalletSNo()', - ]), - Forms\Components\TextInput::make('removeSno_number') - ->label('Remove Serial No') - ->reactive() - ->minLength(9) - ->readOnly(fn (callable $get) => !$get('pallet_number') || $get('serial_number')) - ->extraAttributes([ - 'x-data' => '{ value: "" }', - 'x-model' => 'value', - 'x-on:keydown.enter.prevent' => '$wire.processRemoveSNo()', - ]), - - Forms\Components\TextInput::make('Sno_quantity') - ->label('SNo. Quantity') - ->readOnly() - ->default('0'), - Forms\Components\Hidden::make('created_by') - ->default(Filament::auth()->user()?->name), - Forms\Components\Hidden::make('scanned_by') - ->default(Filament::auth()->user()?->name), - Forms\Components\Hidden::make('pallet_number_locked') - ->default(false), - Forms\Components\Select::make('pending_pallet_list') - ->label('Pending Pallet List') - ->reactive() - ->afterStateUpdated(function ($state, callable $set) { - $set('pallet_number', $state); - $set('pallet_number_locked', false); - }) - ->options(function ($get) { - - $plantId = $get('plant_id'); - - if (!$plantId) { - return []; - } - return PalletValidation::query() - ->where('plant_id', $plantId) - ->where(function($query) { - $query->whereNull('pallet_status') - ->orWhere('pallet_status', ''); + return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); }) - ->whereNotNull('pallet_number') - ->orderBy('pallet_number', 'asc') - ->pluck('pallet_number') - ->unique() - ->mapWithKeys(fn($number) => [$number => $number]) - ->toArray(); - }), + ->afterStateUpdated(function ($state, callable $set) { + $set('pallet_number', null); + $set('serial_number', null); + $set('removeSno_number', null); + $set('Sno_quantity', 0); + $set('pending_pallet_list', null); + }), + Forms\Components\TextInput::make('pallet_number') + ->label('Scan Pallet No') + ->reactive() + ->required() + ->readonly() // fn ($get) => (bool)$get('pallet_number_locked') || $get('serial_number') || $get('removeSno_number') + ->extraAttributes([ + 'x-data' => '{ value: "" }', + 'x-model' => 'value', + 'x-on:keydown.enter.prevent' => '$wire.processPalletNo()', + ]) + ->suffixAction(fn ($get, $set) => Forms\Components\Actions\Action::make('addPallet') + ->label('') + ->button() + ->icon('heroicon-o-plus') + ->color('primary') + ->extraAttributes([ + 'class' => 'p-1 w-7 h-7', + ]) + ->action(function ($get, $set, $livewire) { + $plantId = $get('plant_id'); - Forms\Components\View::make('forms.components.save-pallet-button') - ]) - ->columns(5), + session(['pallet_clicked_time' => now()->toDateTimeString()]); + + session(['pallet_created_by' => Filament::auth()->user()->name]); + + $year = now()->format('y'); + $month = now()->format('m'); + $prefix = "EP-{$year}{$month}"; + + $lastPallet1 = PalletValidation::where('pallet_number', 'like', "{$prefix}%")->orderByDesc('pallet_number')->first(); // ->where('plant_id', $plantId) + $lastPallet2 = LocatorInvoiceValidation::where('pallet_number', 'like', "{$prefix}%")->orderByDesc('pallet_number')->first(); + $newNumber = '001'; // $lastPallet ? str_pad(intval(substr($lastPallet->pallet_number, -3)) + 1, 3, '0', STR_PAD_LEFT) : '001'; + if ($lastPallet1 && $lastPallet2) { + $serialPart1 = substr($lastPallet1->pallet_number, strlen($prefix)); + $serialPart2 = substr($lastPallet2->pallet_number, strlen($prefix)); + if (intval($serialPart1) > intval($serialPart2)) { + $newNumber = str_pad(intval($serialPart1) + 1, strlen($serialPart1), '0', STR_PAD_LEFT); + } else { + $newNumber = str_pad(intval($serialPart2) + 1, strlen($serialPart2), '0', STR_PAD_LEFT); + } + } elseif ($lastPallet1) { + $serialPart1 = substr($lastPallet1->pallet_number, strlen($prefix)); + // OR + // $serialPart = str_replace($prefix, '', $lastPallet->pallet_number); + $newNumber = str_pad(intval($serialPart1) + 1, strlen($serialPart1), '0', STR_PAD_LEFT); + } elseif ($lastPallet2) { + $serialPart2 = substr($lastPallet2->pallet_number, strlen($prefix)); + // OR + // $serialPart = str_replace($prefix, '', $lastPallet->pallet_number); + $newNumber = str_pad(intval($serialPart2) + 1, strlen($serialPart2), '0', STR_PAD_LEFT); + } + + $newPalletNumber = "{$prefix}{$newNumber}"; + + $set('pallet_number', $newPalletNumber); + $set('pallet_number_locked', true); + $set('plant_id', $plantId); + + $livewire->redirectToQrPdf($newPalletNumber); + }) + ), + + Forms\Components\TextInput::make('serial_number') + ->label('Scan Serial No') + ->reactive() + ->minLength(9) + ->readOnly(fn (callable $get) => ! $get('pallet_number') || $get('removeSno_number')) + ->extraAttributes([ + 'x-on:keydown.enter.prevent' => '$wire.processPalletSNo()', + ]), + Forms\Components\TextInput::make('removeSno_number') + ->label('Remove Serial No') + ->reactive() + ->minLength(9) + ->readOnly(fn (callable $get) => ! $get('pallet_number') || $get('serial_number')) + ->extraAttributes([ + 'x-data' => '{ value: "" }', + 'x-model' => 'value', + 'x-on:keydown.enter.prevent' => '$wire.processRemoveSNo()', + ]), + + Forms\Components\TextInput::make('Sno_quantity') + ->label('SNo. Quantity') + ->readOnly() + ->default('0'), + Forms\Components\Hidden::make('created_by') + ->default(Filament::auth()->user()?->name), + Forms\Components\Hidden::make('scanned_by') + ->default(Filament::auth()->user()?->name), + Forms\Components\Hidden::make('pallet_number_locked') + ->default(false), + Forms\Components\Select::make('pending_pallet_list') + ->label('Pending Pallet List') + ->reactive() + ->afterStateUpdated(function ($state, callable $set) { + $set('pallet_number', $state); + $set('pallet_number_locked', false); + }) + ->options(function ($get) { + + $plantId = $get('plant_id'); + + if (! $plantId) { + return []; + } + + return PalletValidation::query() + ->where('plant_id', $plantId) + ->where(function ($query) { + $query->whereNull('pallet_status') + ->orWhere('pallet_status', ''); + }) + ->whereNotNull('pallet_number') + ->orderBy('pallet_number', 'asc') + ->pluck('pallet_number') + ->unique() + ->mapWithKeys(fn ($number) => [$number => $number]) + ->toArray(); + }), + + Forms\Components\View::make('forms.components.save-pallet-button'), + ]) + ->columns(5), Forms\Components\TextInput::make('id') ->hidden() ->readOnly(), @@ -199,8 +191,7 @@ class PalletValidationResource extends Resource public static function table(Table $table): Table { return $table - - ->columns([ + ->columns([ // Tables\Columns\TextColumn::make('id') // ->label('ID') // ->numeric() @@ -212,6 +203,7 @@ class PalletValidationResource extends Resource $paginator = $livewire->getTableRecords(); $perPage = method_exists($paginator, 'perPage') ? $paginator->perPage() : 10; $currentPage = method_exists($paginator, 'currentPage') ? $paginator->currentPage() : 1; + return ($currentPage - 1) * $perPage + $rowLoop->iteration; }), Tables\Columns\TextColumn::make('plant.name') @@ -286,6 +278,7 @@ class PalletValidationResource extends Resource // }) ->options(function (callable $get) { $userHas = Filament::auth()->user()->plant_id; + return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); }) ->reactive() @@ -306,19 +299,20 @@ class PalletValidationResource extends Resource ->label('Pallet Number') ->options(function (callable $get) { $plantId = $get('Plant'); - if (!$plantId) { + if (! $plantId) { return []; } + return PalletValidation::where('plant_id', $plantId) // ->whereNotNull('pallet_number') // ->where('pallet_number', '!=', '') - ->where('pallet_number', 'like', 'EP-' . '%') + ->where('pallet_number', 'like', 'EP-'.'%') // ->where(function($query) { // $query->where('pallet_number', '!=', null)->where('pallet_number', '!=', ''); // }) ->orderBy('pallet_number', 'desc') ->get() - //->unique('pallet_number') + // ->unique('pallet_number') ->pluck('pallet_number', 'pallet_number') ->toArray(); }) @@ -336,12 +330,13 @@ class PalletValidationResource extends Resource ->label('Locator Number') ->options(function (callable $get) { $plantId = $get('Plant'); - if (!$plantId) { + if (! $plantId) { return []; } + return PalletValidation::where('plant_id', $plantId) ->whereNotNull('locator_number') - ->where('locator_number','!=', '') + ->where('locator_number', '!=', '') ->orderBy('locator_number', 'asc') ->get() ->unique('locator_number') @@ -391,23 +386,29 @@ class PalletValidationResource extends Resource return $query->whereRaw('1 = 0'); } - if (!empty($data['Plant'])) { //$plant = $data['Plant'] ?? null + if (! empty($data['Plant'])) { // $plant = $data['Plant'] ?? null $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'])) { $query->where('pallet_number', $data['pallet_number']); } - if (!empty($data['serial_number'])) { + if (! empty($data['serial_number'])) { $query->where('serial_number', $data['serial_number']); } - if (!empty($data['pallet_status'])) { + if (! empty($data['pallet_status'])) { $query->where('pallet_status', $data['pallet_status']); } - if (!empty($data['locator_number'])) { + if (! empty($data['locator_number'])) { $query->where('locator_number', $data['locator_number']); } @@ -415,87 +416,93 @@ class PalletValidationResource extends Resource // $query->where('locator_quantity', $data['locator_quantity']); // } - if ($data['locator_quantity'] != null && $data['locator_quantity'] != '') { //isset($data['locator_quantity']) && - $query->where('locator_quantity', $data['locator_quantity']);//(int) + if ($data['locator_quantity'] != null && $data['locator_quantity'] != '') { // isset($data['locator_quantity']) && + $query->where('locator_quantity', $data['locator_quantity']); // (int) } - if (!empty($data['created_from'])) { + if (! empty($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']); } - if (!empty($data['created_by'])) { + if (! empty($data['created_by'])) { $query->where('created_by', $data['created_by']); } - if (!empty($data['scanned_from'])) { + if (! empty($data['scanned_from'])) { $query->where('scanned_at', '>=', $data['scanned_from']); } - if (!empty($data['scanned_to'])) { + if (! empty($data['scanned_to'])) { $query->where('scanned_at', '<=', $data['scanned_to']); } - if (!empty($data['scanned_by'])) { + if (! empty($data['scanned_by'])) { $query->where('scanned_by', $data['scanned_by']); } }) ->indicateUsing(function (array $data) { $indicators = []; - if (!empty($data['Plant'])) { - $indicators[] = 'Plant: ' . Plant::where('id', $data['Plant'])->value('name'); + if (! empty($data['Plant'])) { + $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'])) { - $indicators[] = 'Pallet Number: ' . $data['pallet_number']; + if (! empty($data['pallet_number'])) { + $indicators[] = 'Pallet Number: '.$data['pallet_number']; } - if (!empty($data['serial_number'])) { - $indicators[] = 'Serial Number: ' . $data['serial_number']; + if (! empty($data['serial_number'])) { + $indicators[] = 'Serial Number: '.$data['serial_number']; } - if (!empty($data['pallet_status'])) { - $indicators[] = 'Pallet Status: ' . $data['pallet_status']; + if (! empty($data['pallet_status'])) { + $indicators[] = 'Pallet Status: '.$data['pallet_status']; } - if (!empty($data['locator_number'])) { - $indicators[] = 'Locator Number: ' . $data['locator_number']; + if (! empty($data['locator_number'])) { + $indicators[] = 'Locator Number: '.$data['locator_number']; } // if (!empty($data['locator_quantity'])) { // $indicators[] = 'Locator Quantity: ' . $data['locator_quantity']; // } - if ($data['locator_quantity'] != null && $data['locator_quantity'] != '') { //isset($data['locator_quantity']) && - $indicators[] = 'Locator Quantity: ' . $data['locator_quantity']; + if ($data['locator_quantity'] != null && $data['locator_quantity'] != '') { // isset($data['locator_quantity']) && + $indicators[] = 'Locator Quantity: '.$data['locator_quantity']; } - if (!empty($data['created_from'])) { - $indicators[] = 'From: ' . $data['created_from']; + if (! empty($data['created_from'])) { + $indicators[] = 'From: '.$data['created_from']; } - if (!empty($data['created_to'])) { - $indicators[] = 'To: ' . $data['created_to']; + if (! empty($data['created_to'])) { + $indicators[] = 'To: '.$data['created_to']; } - if (!empty($data['created_by'])) { - $indicators[] = 'Created By: ' . $data['created_by']; + if (! empty($data['created_by'])) { + $indicators[] = 'Created By: '.$data['created_by']; } - if (!empty($data['scanned_from'])) { - $indicators[] = 'Scanned From: ' . $data['scanned_from']; + if (! empty($data['scanned_from'])) { + $indicators[] = 'Scanned From: '.$data['scanned_from']; } - if (!empty($data['scanned_to'])) { - $indicators[] = 'Scanned To: ' . $data['scanned_to']; + if (! empty($data['scanned_to'])) { + $indicators[] = 'Scanned To: '.$data['scanned_to']; } - if (!empty($data['scanned_by'])) { - $indicators[] = 'Scanned By: ' . $data['scanned_by']; + if (! empty($data['scanned_by'])) { + $indicators[] = 'Scanned By: '.$data['scanned_by']; } return $indicators; - }) + }), ]) ->filtersFormMaxHeight('280px') ->actions([ @@ -515,64 +522,66 @@ class PalletValidationResource extends Resource ->label('Re-Print Pallet QR') ->form([ Forms\Components\Section::make() - ->schema([ - Forms\Components\Select::make('plant') - ->label('Select Plant') - // ->options(Plant::pluck('name', 'id')->toArray()) - ->options(function (callable $get) { - $userHas = Filament::auth()->user()->plant_id; - return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); - }) - ->required() - ->reactive() - ->columnSpan(2), - Forms\Components\Select::make('pallet_list') - ->label('Select Pallet') - ->searchable() - ->required() - ->reactive() - ->columnSpan(1) - //->optionsLimit(500) - ->options(function (callable $get) { - $plantId = $get('plant'); + ->schema([ + Forms\Components\Select::make('plant') + ->label('Select Plant') + // ->options(Plant::pluck('name', 'id')->toArray()) + ->options(function (callable $get) { + $userHas = Filament::auth()->user()->plant_id; - if (!$plantId) { - return []; - } + return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); + }) + ->required() + ->reactive() + ->columnSpan(2), + Forms\Components\Select::make('pallet_list') + ->label('Select Pallet') + ->searchable() + ->required() + ->reactive() + ->columnSpan(1) + // ->optionsLimit(500) + ->options(function (callable $get) { + $plantId = $get('plant'); - return PalletValidation::query()->where('plant_id', $plantId) - // ->whereNotNull('pallet_number') - // ->where('pallet_number', '!=', '') - ->where('pallet_number', 'like', 'EP-' . '%') - ->select('pallet_number') - ->distinct() - ->orderBy('pallet_number', 'desc') - ->pluck('pallet_number', 'pallet_number') - ->toArray(); - }), - ]) - ->columns(['default' => 1, 'sm' => 3]), + if (! $plantId) { + return []; + } + + return PalletValidation::query()->where('plant_id', $plantId) + // ->whereNotNull('pallet_number') + // ->where('pallet_number', '!=', '') + ->where('pallet_number', 'like', 'EP-'.'%') + ->select('pallet_number') + ->distinct() + ->orderBy('pallet_number', 'desc') + ->pluck('pallet_number', 'pallet_number') + ->toArray(); + }), + ]) + ->columns(['default' => 1, 'sm' => 3]), ]) - ->action(function (array $data) { + ->action(function (array $data) { $selectedPalletNumber = $data['pallet_list']; + return redirect()->route('download-reprint-qr-pdf', ['palletNo' => $selectedPalletNumber]); }) - ->visible(function() { + ->visible(function () { return Filament::auth()->user()->can('view reprint pallet number'); }), ImportAction::make() ->importer(PalletValidationImporter::class) ->label('Import Pallet') ->color('warning') - ->visible(function() { + ->visible(function () { return Filament::auth()->user()->can('view import pallet validation'); }), ExportAction::make() ->exporter(PalletValidationExporter::class) ->label('Export Pallet') ->color('warning') - ->visible(function() { + ->visible(function () { return Filament::auth()->user()->can('view export pallet validation'); }), ]); diff --git a/app/Filament/Resources/ProcessOrderResource.php b/app/Filament/Resources/ProcessOrderResource.php index 7cae49d..e806411 100644 --- a/app/Filament/Resources/ProcessOrderResource.php +++ b/app/Filament/Resources/ProcessOrderResource.php @@ -5,11 +5,15 @@ namespace App\Filament\Resources; use App\Filament\Exports\ProcessOrderExporter; use App\Filament\Imports\ProcessOrderImporter; use App\Filament\Resources\ProcessOrderResource\Pages; +use App\Models\Item; use App\Models\Plant; use App\Models\ProcessOrder; use Filament\Facades\Filament; use Filament\Forms; 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\Get; use Filament\Forms\Set; @@ -18,19 +22,13 @@ use Filament\Resources\Resource; use Filament\Tables; use Filament\Tables\Actions\ExportAction; use Filament\Tables\Actions\ImportAction; +use Filament\Tables\Filters\Filter; use Filament\Tables\Table; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\SoftDeletingScope; use Livewire\Features\SupportFileUploads\TemporaryUploadedFile; use Smalot\PdfParser\Parser; 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 Dom\Text; @@ -173,16 +171,16 @@ class ProcessOrderResource extends Resource $plantId = $get('plant_id'); $itemId = $get('item_id'); $processOrder = $value; - //$currentId = $get('id'); // current editing record id + // $currentId = $get('id'); // current editing record id if (! $plantId || ! $processOrder) { return; } - $existing = ProcessOrder::where('plant_id', $plantId) - ->where('process_order', $processOrder) - ->where('item_id', '!=', $itemId) - ->first(); + $existing = ProcessOrder::where('plant_id', $plantId) + ->where('process_order', $processOrder) + ->where('item_id', '!=', $itemId) + ->first(); if ($existing) { @@ -288,14 +286,14 @@ class ProcessOrderResource extends Resource ->disk('local') ->directory('uploads/temp') ->preserveFilenames() - ->visible(function() { + ->visible(function () { return Filament::auth()->user()->can('view process order packing slip'); }) ->reactive(), Forms\Components\Actions::make([ Action::make('uploadNow') ->label('Upload PDF Now') - ->visible(function() { + ->visible(function () { return Filament::auth()->user()->can('view process order packing slip'); }) ->action(function ($get, callable $set) { @@ -385,7 +383,7 @@ class ProcessOrderResource extends Resource Action::make('downloadAttachment') ->label('Download PDF') - ->visible(function() { + ->visible(function () { return Filament::auth()->user()->can('view process order packing slip'); }) ->action(function ($get) { @@ -482,6 +480,7 @@ class ProcessOrderResource extends Resource $paginator = $livewire->getTableRecords(); $perPage = method_exists($paginator, 'perPage') ? $paginator->perPage() : 10; $currentPage = method_exists($paginator, 'currentPage') ? $paginator->currentPage() : 1; + return ($currentPage - 1) * $perPage + $rowLoop->iteration; }), Tables\Columns\TextColumn::make('plant.name') @@ -561,133 +560,141 @@ class ProcessOrderResource extends Resource ->sortable() ->toggleable(isToggledHiddenByDefault: true), ]) - // ->filters([ - // Tables\Filters\TrashedFilter::make(), - // ]) ->filters([ - Tables\Filters\TrashedFilter::make(), - Filter::make('advanced_filters') - ->label('Advanced Filters') - ->form([ - Select::make('Plant') - ->label('Select Plant') - ->nullable() - ->options(function (callable $get) { - $userHas = Filament::auth()->user()->plant_id; - return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); - }) - ->reactive() - ->afterStateUpdated(function ($state, callable $set, callable $get) { - $set('Item', null); - }), - Select::make('Item') - ->label('Item Code') - ->nullable() - ->searchable() - ->options(function (callable $get) { + Tables\Filters\TrashedFilter::make(), + Filter::make('advanced_filters') + ->label('Advanced Filters') + ->form([ + Select::make('Plant') + ->label('Select Plant') + ->nullable() + ->options(function (callable $get) { + $userHas = Filament::auth()->user()->plant_id; + + return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); + }) + ->reactive() + ->afterStateUpdated(function ($state, callable $set, callable $get) { + $set('Item', null); + }), + Select::make('Item') + ->label('Search by Item Code') + ->nullable() + ->searchable() + ->reactive() + ->options(function (callable $get) { $plantId = $get('Plant'); - if(empty($plantId)) { - return []; - } - - return Item::where('plant_id', $plantId)->pluck('code', 'id'); - - //return $plantId ? Item::where('plant_id', $plantId)->pluck('code', 'id') : []; + return Item::whereHas('processOrders', function ($query) use ($plantId) { + if ($plantId) { + $query->where('plant_id', $plantId); + } + })->pluck('code', 'id'); }) - ->reactive() - ->afterStateUpdated(function ($state, callable $set, callable $get) { - $set('process_order', null); - }), - TextInput::make('process_order') - ->label('Process Order') - ->placeholder('Enter Process Order'), - TextInput::make('sfg_number') - ->label('Sfg Number') - ->placeholder(placeholder: 'Enter Sfg Number'), - TextInput::make('machine_name') - ->label('Machine Name') - ->placeholder(placeholder: 'Enter Machine Name'), - DateTimePicker::make(name: 'created_from') - ->label('Created From') - ->placeholder(placeholder: 'Select From DateTime') - ->reactive() - ->native(false), - DateTimePicker::make('created_to') - ->label('Created To') - ->placeholder(placeholder: 'Select To DateTime') - ->reactive() - ->native(false), - ]) - ->query(function ($query, array $data) { - // Hide all records initially if no filters are applied - if (empty($data['Plant']) && empty($data['Item']) && empty($data['process_order']) && empty($data['sfg_number']) && empty($data['created_from']) && empty($data['created_to']) && empty($data['machine_name'])) { - return $query->whereRaw('1 = 0'); - } + ->afterStateUpdated(function ($state, callable $set, callable $get) { + $set('process_order', null); + }), + TextInput::make('process_order') + ->label('Process Order') + ->placeholder('Enter Process Order'), + TextInput::make('sfg_number') + ->label('Sfg Number') + ->placeholder(placeholder: 'Enter Sfg Number'), + TextInput::make('machine_name') + ->label('Machine Name') + ->placeholder(placeholder: 'Enter Machine Name'), + DateTimePicker::make(name: 'created_from') + ->label('Created From') + ->placeholder(placeholder: 'Select From DateTime') + ->reactive() + ->native(false), + DateTimePicker::make('created_to') + ->label('Created To') + ->placeholder(placeholder: 'Select To DateTime') + ->reactive() + ->native(false), + ]) + ->query(function ($query, array $data) { + // Hide all records initially if no filters are applied + if (empty($data['Plant']) && empty($data['Item']) && empty($data['process_order']) && empty($data['sfg_number']) && empty($data['created_from']) && empty($data['created_to']) && empty($data['machine_name'])) { + return $query->whereRaw('1 = 0'); + } - if (!empty($data['Plant'])) { - $query->where('plant_id', $data['Plant']); - } + if (! empty($data['Plant'])) { + $query->where('plant_id', $data['Plant']); + } else { + $userHas = Filament::auth()->user()->plant_id; - if (!empty($data['Item'])) { - $query->where('item_id', $data['Item']); - } + if ($userHas && strlen($userHas) > 0) { + return $query->whereRaw('1 = 0'); + } + } - if (!empty($data['process_order'])) { - $query->where('process_order', $data['process_order']); - } + if (! empty($data['Item'])) { + $query->where('item_id', $data['Item']); + } - if (!empty($data['sfg_number'])) { - $query->where('sfg_number', $data['sfg_number']); - } + if (! empty($data['process_order'])) { + $query->where('process_order', $data['process_order']); + } - if (!empty($data['machine_name'])) { - // $query->where('machine_name', $data['machine_name']); - $query->where('machine_name', 'like', '%' . $data['machine_name'] . '%'); - } + if (! empty($data['sfg_number'])) { + $query->where('sfg_number', $data['sfg_number']); + } - if (!empty($data['created_from'])) { - $query->where('created_at', '>=', $data['created_from']); - } + if (! empty($data['machine_name'])) { + // $query->where('machine_name', $data['machine_name']); + $query->where('machine_name', 'like', '%'.$data['machine_name'].'%'); + } - if (!empty($data['created_to'])) { - $query->where('created_at', '<=', $data['created_to']); - } - //$query->orderBy('created_at', 'asc'); - }) - ->indicateUsing(function (array $data) { - $indicators = []; + if (! empty($data['created_from'])) { + $query->where('created_at', '>=', $data['created_from']); + } - if (!empty($data['Plant'])) { - $indicators[] = 'Plant: ' . Plant::where('id', $data['Plant'])->value('name'); - } + if (! empty($data['created_to'])) { + $query->where('created_at', '<=', $data['created_to']); + } + // $query->orderBy('created_at', 'asc'); + }) + ->indicateUsing(function (array $data) { + $indicators = []; - if (!empty($data['Item'])) { - $indicators[] = 'Item: ' . Item::where('id', $data['Item'])->value('code'); - } + if (! empty($data['Plant'])) { + $indicators[] = 'Plant: '.Plant::where('id', $data['Plant'])->value('name'); + } else { + $userHas = Filament::auth()->user()->plant_id; - if (!empty($data['process_order'])) { - $indicators[] = 'Process Order: ' . $data['process_order']; - } + if ($userHas && strlen($userHas) > 0) { + return 'Plant: Choose plant to filter records.'; + } + } - if (!empty($data['sfg_number'])) { - $indicators[] = 'Sfg Number: ' . $data['sfg_number']; - } + if (! empty($data['Item'])) { + $indicators[] = 'Item: '.Item::where('id', $data['Item'])->value('code'); + } - if (!empty($data['machine_name'])) { - $indicators[] = 'Machine Name: ' . $data['machine_name']; - } + if (! empty($data['process_order'])) { + $indicators[] = 'Process Order: '.$data['process_order']; + } - if (!empty($data['created_from'])) { - $indicators[] = 'From: ' . $data['created_from']; - } + if (! empty($data['sfg_number'])) { + $indicators[] = 'Sfg Number: '.$data['sfg_number']; + } - if (!empty($data['created_to'])) { - $indicators[] = 'To: ' . $data['created_to']; - } + if (! empty($data['machine_name'])) { + $indicators[] = 'Machine Name: '.$data['machine_name']; + } - return $indicators; - }) + if (! empty($data['created_from'])) { + $indicators[] = 'From: '.$data['created_from']; + } + + if (! empty($data['created_to'])) { + $indicators[] = 'To: '.$data['created_to']; + } + + return $indicators; + }), ]) ->filtersFormMaxHeight('280px') ->actions([ @@ -730,16 +737,16 @@ class ProcessOrderResource extends Resource ->required() ->searchable() ->options(function (callable $get) { - $plantId = $get('plant'); + $plantId = $get('plant'); - if(empty($plantId)) { - return []; - } + if (empty($plantId)) { + return []; + } - return Item::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') : []; - }) + // return $plantId ? Item::where('plant_id', $plantId)->pluck('code', 'id') : []; + }) ->reactive() ->afterStateUpdated(function ($state, callable $set, callable $get) { $set('process_order', null); @@ -763,30 +770,31 @@ class ProcessOrderResource extends Resource ->required() ->searchable() ->options(function (callable $get) { - $plantId = $get('plant'); - $itemId = $get('Item'); - $processOrder = $get('process_order'); + $plantId = $get('plant'); + $itemId = $get('Item'); + $processOrder = $get('process_order'); - if(empty($plantId) || empty($itemId) || empty($processOrder)) { - return []; - } + if (empty($plantId) || empty($itemId) || empty($processOrder)) { + return []; + } - return ProcessOrder::where('plant_id', $plantId) - ->where('item_id', $itemId) - ->where('process_order', $processOrder) - ->pluck('coil_number', 'coil_number'); + return ProcessOrder::where('plant_id', $plantId) + ->where('item_id', $itemId) + ->where('process_order', $processOrder) + ->pluck('coil_number', 'coil_number'); - //return $plantId ? 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) { $plantId = $get('plant'); $itemId = $get('Item'); $processOrder = $get('process_order'); - if(!$plantId || !$itemId || !$processOrder || !$state) { + if (! $plantId || ! $itemId || ! $processOrder || ! $state) { $set('received_quantity', null); $set('machine_name', null); + return; } @@ -815,12 +823,13 @@ class ProcessOrderResource extends Resource // }) ->action(function (array $data) { $username = Filament::auth()->user()->name; + return redirect()->route('download-reprint-process-pdf', [ - 'plant' => $data['plant'], - 'item' => $data['Item'], + 'plant' => $data['plant'], + 'item' => $data['Item'], 'process_order' => $data['process_order'], - 'coil_number' => $data['coil_number'], - 'name' => $username, + 'coil_number' => $data['coil_number'], + 'name' => $username, ]); }) ->visible(function () { diff --git a/app/Filament/Resources/ProductCharacteristicsMasterResource.php b/app/Filament/Resources/ProductCharacteristicsMasterResource.php index 06e123a..0074024 100644 --- a/app/Filament/Resources/ProductCharacteristicsMasterResource.php +++ b/app/Filament/Resources/ProductCharacteristicsMasterResource.php @@ -5,7 +5,6 @@ namespace App\Filament\Resources; use App\Filament\Exports\ProductCharacteristicsMasterExporter; use App\Filament\Imports\ProductCharacteristicsMasterImporter; use App\Filament\Resources\ProductCharacteristicsMasterResource\Pages; -use App\Filament\Resources\ProductCharacteristicsMasterResource\RelationManagers; use App\Models\Item; use App\Models\Line; use App\Models\Machine; @@ -14,19 +13,19 @@ use App\Models\ProductCharacteristicsMaster; use App\Models\WorkGroupMaster; use Filament\Facades\Filament; 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\Get; use Filament\Resources\Resource; use Filament\Tables; +use Filament\Tables\Actions\ExportAction; +use Filament\Tables\Actions\ImportAction; +use Filament\Tables\Filters\Filter; use Filament\Tables\Table; use Illuminate\Database\Eloquent\Builder; 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 { @@ -45,13 +44,14 @@ class ProductCharacteristicsMasterResource extends Resource ->relationship('plant', 'name') ->options(function (callable $get) { $userHas = Filament::auth()->user()->plant_id; + return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); }) ->reactive() ->required(), Forms\Components\Select::make('item_id') ->label('Item Code') - //->relationship('item', 'code') + // ->relationship('item', 'code') ->searchable() ->reactive() ->options(function (callable $get) { @@ -59,6 +59,7 @@ class ProductCharacteristicsMasterResource extends Resource if (empty($plantId)) { return []; } + return \App\Models\Item::where('plant_id', $plantId)->pluck('code', 'id'); }) ->required(), @@ -70,23 +71,24 @@ class ProductCharacteristicsMasterResource extends Resource if (empty($plantId)) { return []; } + return Line::where('plant_id', $plantId)->pluck('name', 'id'); }) ->afterStateUpdated(function ($state, callable $set, callable $get) { $set('machine_id', null); - if (!$get('work_group_master_id')) { + if (! $get('work_group_master_id')) { $set('machine_id', null); } }) ->required(), - // ->relationship('line', 'name'), + // ->relationship('line', 'name'), Forms\Components\Select::make('work_group_master_id') ->label('Group Work Center') ->required() ->reactive() ->options(function (callable $get) { - if (!$get('plant_id') || !$get('line_id')) { + if (! $get('plant_id') || ! $get('line_id')) { return []; } @@ -94,23 +96,22 @@ class ProductCharacteristicsMasterResource extends Resource $workGroupIds = []; for ($i = 1; $i <= $line->no_of_operation; $i++) { $column = "work_group{$i}_id"; - if (!empty($line->$column)) { + if (! empty($line->$column)) { $workGroupIds[] = $line->$column; } } return WorkGroupMaster::where('plant_id', $get('plant_id'))->whereIn('id', $workGroupIds)->pluck('name', 'id')->toArray(); }) - ->disabled(fn (Get $get) => !empty($get('id'))) + ->disabled(fn (Get $get) => ! empty($get('id'))) ->afterStateUpdated(function ($state, callable $set, callable $get) { $lineId = $get('line_id'); - if (!$lineId) { + if (! $lineId) { $set('mGroupWorkError', 'Please select a line first.'); $set('machine_id', null); + return; - } - else - { + } else { // $grpWrkCnr = Line::find($lineId)->group_work_center; // if (!$grpWrkCnr || Str::length($grpWrkCnr) < 1) // { @@ -130,7 +131,7 @@ class ProductCharacteristicsMasterResource extends Resource ->hintColor('danger'), Forms\Components\Select::make('machine_id') ->label('Work Center') - //->relationship('machine', 'name'), + // ->relationship('machine', 'name'), ->searchable() ->reactive() ->options(function (callable $get) { @@ -148,7 +149,7 @@ class ProductCharacteristicsMasterResource extends Resource ->pluck('work_center', 'id'); }) ->afterStateUpdated(function ($state, callable $set, callable $get) { - if (!$get('plant_id') || !$get('line_id') || !$get('work_group_master_id')) { + if (! $get('plant_id') || ! $get('line_id') || ! $get('work_group_master_id')) { $set('machine_id', null); } }) @@ -157,7 +158,7 @@ class ProductCharacteristicsMasterResource extends Resource ->label('Characteristics Type') ->options([ 'Product' => 'Product', - 'Process' => 'Process', + 'Process' => 'Process', ]) ->reactive() ->required(), @@ -167,7 +168,7 @@ class ProductCharacteristicsMasterResource extends Resource ->label('Inspection Type') ->options([ 'Visual' => 'Visual', - 'Value' => 'Value', + 'Value' => 'Value', ]) ->reactive() ->required(), @@ -208,9 +209,9 @@ class ProductCharacteristicsMasterResource extends Resource $upper = $get('upper'); $middle = $value; - if (!is_null($lower) && !is_null($upper) && !is_null($middle)) { - if (!($lower <= $middle && $middle <= $upper)) { - $fail("Middle must be between Lower and Upper (Lower ≤ Middle ≤ Upper)."); + if (! is_null($lower) && ! is_null($upper) && ! is_null($middle)) { + if (! ($lower <= $middle && $middle <= $upper)) { + $fail('Middle must be between Lower and Upper (Lower ≤ Middle ≤ Upper).'); } } }; @@ -233,6 +234,7 @@ class ProductCharacteristicsMasterResource extends Resource $paginator = $livewire->getTableRecords(); $perPage = method_exists($paginator, 'perPage') ? $paginator->perPage() : 10; $currentPage = method_exists($paginator, 'currentPage') ? $paginator->currentPage() : 1; + return ($currentPage - 1) * $perPage + $rowLoop->iteration; }), Tables\Columns\TextColumn::make('plant.name') @@ -317,201 +319,207 @@ class ProductCharacteristicsMasterResource extends Resource ->sortable() ->toggleable(isToggledHiddenByDefault: true), ]) - // ->filters([ - // Tables\Filters\TrashedFilter::make(), - // ]) ->filters([ + Tables\Filters\TrashedFilter::make(), + Filter::make('advanced_filters') + ->label('Advanced Filters') + ->form([ + Select::make('Plant') + ->label('Select Plant') + ->nullable() + ->options(function (callable $get) { + $userHas = Filament::auth()->user()->plant_id; - Tables\Filters\TrashedFilter::make(), - Filter::make('advanced_filters') - ->label('Advanced Filters') - ->form([ - Select::make('Plant') - ->label('Select Plant') - ->nullable() - ->options(function (callable $get) { - $userHas = Filament::auth()->user()->plant_id; - return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); - }) - ->reactive() - ->afterStateUpdated(function ($state, callable $set, callable $get) { - $set('Item', null); - }), - Select::make('Line') - ->label('Select Line') - ->nullable() - ->options(function (callable $get) { + return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); + }) + ->reactive() + ->afterStateUpdated(function ($state, callable $set, callable $get) { + $set('Item', null); + }), + Select::make('Line') + ->label('Select Line') + ->nullable() + ->options(function (callable $get) { $plantId = $get('Plant'); - if(empty($plantId)) { + if (empty($plantId)) { return []; } return Line::where('plant_id', $plantId)->pluck('name', 'id'); - //return $plantId ? 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) { - $set('Item', null); - }), - Select::make('Item') - ->label('Item Code') - ->nullable() - ->searchable() - ->options(function (callable $get) { + ->reactive() + ->afterStateUpdated(function ($state, callable $set, callable $get) { + $set('Item', null); + }), + Select::make('Item') + ->label('Search by Item Code') + ->nullable() + ->searchable() + ->options(function (callable $get) { $plantId = $get('Plant'); - if(empty($plantId)) { - return []; - } - - return Item::where('plant_id', $plantId)->pluck('code', 'id'); - - //return $plantId ? Item::where('plant_id', $plantId)->pluck('code', 'id') : []; + return Item::whereHas('productCharacteristicsMasters', function ($query) use ($plantId) { + if ($plantId) { + $query->where('plant_id', $plantId); + } + })->pluck('code', 'id'); }) - ->reactive() - ->afterStateUpdated(function ($state, callable $set, callable $get) { - $set('process_order', null); - }), - Select::make('work_group_master') - ->label('Select Work Group Master') - ->nullable() - ->options(function (callable $get) { + ->reactive(), + // ->afterStateUpdated(function ($state, callable $set, callable $get) { + // $set('process_order', null); + // }), + Select::make('work_group_master') + ->label('Select Work Group Master') + ->nullable() + ->options(function (callable $get) { $plantId = $get('Plant'); - if(empty($plantId)) { + if (empty($plantId)) { return []; } return WorkGroupMaster::where('plant_id', $plantId)->pluck('name', 'id'); - //return $plantId ? 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) { - $set('Machine', null); - }), - Select::make('Machine') - ->label('Select Machine') - ->nullable() - ->options(function (callable $get) { + ->reactive() + ->afterStateUpdated(function ($state, callable $set, callable $get) { + $set('Machine', null); + }), + Select::make('Machine') + ->label('Select Machine') + ->nullable() + ->options(function (callable $get) { $plantId = $get('Plant'); $lineId = $get('Line'); - if(empty($plantId) || empty($lineId)) { + if (empty($plantId) || empty($lineId)) { return []; } return Machine::where('plant_id', $plantId)->where('line_id', $lineId)->pluck('work_center', 'id'); - //return $plantId ? 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) { // $set('process_order', null); // }), - // TextInput::make('process_order') - // ->label('Process Order') - // ->placeholder('Enter Process Order'), - // TextInput::make('coil_number') - // ->label('Coil Number') - // ->placeholder(placeholder: 'Enter Coil Number'), - Select::make('characteristics_type') - ->label('Characteristics Type') - ->options([ - 'Product' => 'Product', - 'Process' => 'Process' - ]), - DateTimePicker::make(name: 'created_from') - ->label('Created From') - ->placeholder(placeholder: 'Select From DateTime') - ->reactive() - ->native(false), - DateTimePicker::make('created_to') - ->label('Created To') - ->placeholder(placeholder: 'Select To DateTime') - ->reactive() - ->native(false), - ]) - ->query(function ($query, array $data) { - // Hide all records initially if no filters are applied - if (empty($data['Plant']) && empty($data['Line']) && empty($data['Item']) && empty($data['work_group_master']) && empty($data['Machine']) && empty($data['characteristics_type']) && empty($data['created_from']) && empty($data['created_to'])) { - return $query->whereRaw('1 = 0'); - } + // TextInput::make('process_order') + // ->label('Process Order') + // ->placeholder('Enter Process Order'), + // TextInput::make('coil_number') + // ->label('Coil Number') + // ->placeholder(placeholder: 'Enter Coil Number'), + Select::make('characteristics_type') + ->label('Characteristics Type') + ->options([ + 'Product' => 'Product', + 'Process' => 'Process', + ]), + DateTimePicker::make(name: 'created_from') + ->label('Created From') + ->placeholder(placeholder: 'Select From DateTime') + ->reactive() + ->native(false), + DateTimePicker::make('created_to') + ->label('Created To') + ->placeholder(placeholder: 'Select To DateTime') + ->reactive() + ->native(false), + ]) + ->query(function ($query, array $data) { + // Hide all records initially if no filters are applied + if (empty($data['Plant']) && empty($data['Line']) && empty($data['Item']) && empty($data['work_group_master']) && empty($data['Machine']) && empty($data['characteristics_type']) && empty($data['created_from']) && empty($data['created_to'])) { + return $query->whereRaw('1 = 0'); + } - if (!empty($data['Plant'])) { - $query->where('plant_id', $data['Plant']); - } + if (! empty($data['Plant'])) { + $query->where('plant_id', $data['Plant']); + } else { + $userHas = Filament::auth()->user()->plant_id; - if (!empty($data['Line'])) { - $query->where('line_id', $data['Line']); - } + if ($userHas && strlen($userHas) > 0) { + return $query->whereRaw('1 = 0'); + } + } - if (!empty($data['Item'])) { - $query->where('item_id', $data['Item']); - } + if (! empty($data['Line'])) { + $query->where('line_id', $data['Line']); + } - if (!empty($data['work_group_master'])) { - $query->where('work_group_master_id', $data['work_group_master']); - } + if (! empty($data['Item'])) { + $query->where('item_id', $data['Item']); + } - if (!empty($data['Machine'])) { - $query->where('machine_id', $data['Machine']); - } + if (! empty($data['work_group_master'])) { + $query->where('work_group_master_id', $data['work_group_master']); + } - if (!empty($data['characteristics_type'])) { - $query->where('characteristics_type', $data['characteristics_type']); - } + if (! empty($data['Machine'])) { + $query->where('machine_id', $data['Machine']); + } - if (!empty($data['created_from'])) { - $query->where('created_at', '>=', $data['created_from']); - } + if (! empty($data['characteristics_type'])) { + $query->where('characteristics_type', $data['characteristics_type']); + } - if (!empty($data['created_to'])) { - $query->where('created_at', '<=', $data['created_to']); - } + if (! empty($data['created_from'])) { + $query->where('created_at', '>=', $data['created_from']); + } + if (! empty($data['created_to'])) { + $query->where('created_at', '<=', $data['created_to']); + } - //$query->orderBy('created_at', 'asc'); - }) - ->indicateUsing(function (array $data) { - $indicators = []; + // $query->orderBy('created_at', 'asc'); + }) + ->indicateUsing(function (array $data) { + $indicators = []; - if (!empty($data['Plant'])) { - $indicators[] = 'Plant: ' . Plant::where('id', $data['Plant'])->value('name'); - } + if (! empty($data['Plant'])) { + $indicators[] = 'Plant: '.Plant::where('id', $data['Plant'])->value('name'); + } else { + $userHas = Filament::auth()->user()->plant_id; - if (!empty($data['Line'])) { - $indicators[] = 'Line: ' . Line::where('id', $data['Line'])->value('name'); - } + if ($userHas && strlen($userHas) > 0) { + return 'Plant: Choose plant to filter records.'; + } + } - if (!empty($data['Item'])) { - $indicators[] = 'Item: ' . Item::where('id', $data['Item'])->value('code'); - } + if (! empty($data['Line'])) { + $indicators[] = 'Line: '.Line::where('id', $data['Line'])->value('name'); + } - if (!empty($data['work_group_master'])) { - $indicators[] = 'Work Group Master: ' . WorkGroupMaster::where('id', $data['work_group_master'])->value('name'); - } + if (! empty($data['Item'])) { + $indicators[] = 'Item: '.Item::where('id', $data['Item'])->value('code'); + } - if (!empty($data['Machine'])) { - $indicators[] = 'Machine: ' . Machine::where('id', $data['Machine'])->value('work_center'); - } + if (! empty($data['work_group_master'])) { + $indicators[] = 'Work Group Master: '.WorkGroupMaster::where('id', $data['work_group_master'])->value('name'); + } - if (!empty($data['characteristics_type'])) { - $indicators[] = 'Characteristics Type: ' . $data['characteristics_type']; - } + if (! empty($data['Machine'])) { + $indicators[] = 'Machine: '.Machine::where('id', $data['Machine'])->value('work_center'); + } - if (!empty($data['created_from'])) { - $indicators[] = 'From: ' . $data['created_from']; - } + if (! empty($data['characteristics_type'])) { + $indicators[] = 'Characteristics Type: '.$data['characteristics_type']; + } - if (!empty($data['created_to'])) { - $indicators[] = 'To: ' . $data['created_to']; - } + if (! empty($data['created_from'])) { + $indicators[] = 'From: '.$data['created_from']; + } - return $indicators; - }) + if (! empty($data['created_to'])) { + $indicators[] = 'To: '.$data['created_to']; + } + + return $indicators; + }), ]) ->filtersFormMaxHeight('280px') ->actions([ @@ -530,14 +538,14 @@ class ProductCharacteristicsMasterResource extends Resource ->label('Import Product Characteristics Masters') ->color('warning') ->importer(ProductCharacteristicsMasterImporter::class) - ->visible(function() { + ->visible(function () { return Filament::auth()->user()->can('view import product characteristics master'); }), ExportAction::make() ->label('Export Product Characteristics Masters') ->color('warning') ->exporter(ProductCharacteristicsMasterExporter::class) - ->visible(function() { + ->visible(function () { return Filament::auth()->user()->can('view export product characteristics master'); }), ]); diff --git a/app/Filament/Resources/ProductionLineStopResource.php b/app/Filament/Resources/ProductionLineStopResource.php index d064fd1..60cb6c1 100644 --- a/app/Filament/Resources/ProductionLineStopResource.php +++ b/app/Filament/Resources/ProductionLineStopResource.php @@ -6,30 +6,28 @@ use AlperenErsoy\FilamentExport\Actions\FilamentExportBulkAction; use App\Filament\Exports\ProductionLineStopExporter; use App\Filament\Imports\ProductionLineStopImporter; use App\Filament\Resources\ProductionLineStopResource\Pages; -use App\Filament\Resources\ProductionLineStopResource\RelationManagers; use App\Models\Block; use App\Models\Line; use App\Models\LineStop; use App\Models\Plant; use App\Models\ProductionLineStop; use App\Models\Shift; +use Carbon\Carbon; +use Filament\Facades\Filament; 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\Get; use Filament\Resources\Resource; use Filament\Tables; +use Filament\Tables\Actions\ExportAction; use Filament\Tables\Actions\ImportAction; +use Filament\Tables\Filters\Filter; use Filament\Tables\Table; use Illuminate\Database\Eloquent\Builder; 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 { @@ -56,22 +54,22 @@ class ProductionLineStopResource extends Resource ->reactive() ->options(function (callable $get) { $userHas = Filament::auth()->user()->plant_id; + return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); }) ->default(function () { return optional(ProductionLineStop::latest()->first())->plant_id; }) - ->disabled(fn (Get $get) => !empty($get('id'))) + ->disabled(fn (Get $get) => ! empty($get('id'))) // ->afterStateUpdated(fn ($set) => $set('block_name', null)) ->afterStateUpdated(function ($state, callable $set, callable $get) { $plantId = $get('plant_id'); $set('block_name', null); - if (!$plantId) { + if (! $plantId) { $set('plsPlantError', 'Please select a plant first.'); + return; - } - else - { + } else { $set('plsPlantError', null); } }) @@ -85,29 +83,28 @@ class ProductionLineStopResource extends Resource // ->nullable() ->label('Block') ->options(function (callable $get) { - if (!$get('plant_id')) { + if (! $get('plant_id')) { return []; } - // return \App\Models\Block::where('plant_id', $get('plant_id')) - return Block::where('plant_id', $get('plant_id')) + // return \App\Models\Block::where('plant_id', $get('plant_id')) + return Block::where('plant_id', $get('plant_id')) ->pluck('name', 'id') ->toArray(); }) ->reactive() ->default(function () { $latestShiftId = optional(ProductionLineStop::latest()->first())->shift_id; + return optional(Shift::where('id', $latestShiftId)->first())->block_id; }) // ->afterStateUpdated(fn ($set) => $set('shift_id', null)) ->afterStateUpdated(function ($state, callable $set, callable $get) { - if($get('id')) - { + if ($get('id')) { $getShift = ProductionLineStop::where('id', $get('id'))->first(); // $getBlock = \App\Models\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('plsBlockError', null); } @@ -116,12 +113,11 @@ class ProductionLineStopResource extends Resource $blockId = $get('block_name'); $set('shift_id', null); - if (!$blockId) { + if (! $blockId) { $set('plsBlockError', 'Please select a block first.'); + return; - } - else - { + } else { $set('plsBlockError', null); } }) @@ -135,12 +131,12 @@ class ProductionLineStopResource extends Resource ->required() // ->nullable() ->options(function (callable $get) { - if (!$get('plant_id') || !$get('block_name')) { + if (! $get('plant_id') || ! $get('block_name')) { return []; } - return Shift::where('plant_id', $get('plant_id')) - ->where('block_id', $get('block_name')) + return Shift::where('plant_id', $get('plant_id')) + ->where('block_id', $get('block_name')) ->pluck('name', 'id') ->toArray(); }) @@ -150,11 +146,9 @@ class ProductionLineStopResource extends Resource }) // ->afterStateUpdated(fn ($set) => $set('line_id', null)) ->afterStateUpdated(function ($state, callable $set, callable $get) { - if($get('id')) - { + if ($get('id')) { $getShift = ProductionLineStop::where('id', $get('id'))->first(); - if($getShift->shift_id) - { + if ($getShift->shift_id) { $set('shift_id', $getShift->shift_id); $set('plsShiftError', null); } @@ -163,12 +157,11 @@ class ProductionLineStopResource extends Resource $shiftId = $get('shift_id'); $set('line_id', null); - if (!$shiftId) { + if (! $shiftId) { $set('plsShiftError', 'Please select a shift first.'); + return; - } - else - { + } else { $set('plsShiftError', null); } }) @@ -182,12 +175,12 @@ class ProductionLineStopResource extends Resource ->required() // ->nullable() ->options(function (callable $get) { - if (!$get('plant_id') || !$get('block_name') || !$get('shift_id')) { + if (! $get('plant_id') || ! $get('block_name') || ! $get('shift_id')) { return []; } - // return \App\Models\Line::where('plant_id', $get('plant_id')) - return Line::where('plant_id', $get('plant_id')) + // return \App\Models\Line::where('plant_id', $get('plant_id')) + return Line::where('plant_id', $get('plant_id')) ->pluck('name', 'id') ->toArray(); }) @@ -196,11 +189,9 @@ class ProductionLineStopResource extends Resource return optional(ProductionLineStop::latest()->first())->line_id; }) ->afterStateUpdated(function ($state, callable $set, callable $get) { - if($get('id')) - { + if ($get('id')) { $getShift = ProductionLineStop::where('id', $get('id'))->first(); - if($getShift->line_id) - { + if ($getShift->line_id) { $set('line_id', $getShift->line_id); $set('plsLineError', null); } @@ -210,12 +201,11 @@ class ProductionLineStopResource extends Resource $set('linestop_id', null); $set('lineStop_reason', null); - if (!$lineId) { + if (! $lineId) { $set('plsLineError', 'Please select a line first.'); + return; - } - else - { + } else { $set('plsLineError', null); } }) @@ -251,8 +241,9 @@ class ProductionLineStopResource extends Resource $lineStopId = $get('linestop_id'); // Get entered linestop_id // Ensure `linestop_id` is not cleared - if (!$lineStopId) { + if (! $lineStopId) { $set('lineStop_reason', null); + return; } @@ -275,16 +266,14 @@ class ProductionLineStopResource extends Resource ->before('to_datetime') ->reactive() // ->closeOnDateSelection() - ->afterStateUpdated(fn ($state, callable $set, callable $get) => - self::updateStopDuration($get, $set) - ), + ->afterStateUpdated(fn ($state, callable $set, callable $get) => self::updateStopDuration($get, $set) + ), Forms\Components\DateTimePicker::make('to_datetime') ->label('To DateTime') ->required() ->after('from_datetime') ->reactive() - ->afterStateUpdated(fn ($state, callable $set, callable $get) => - self::updateStopDuration($get, $set) //self means it calling the function within the class + ->afterStateUpdated(fn ($state, callable $set, callable $get) => self::updateStopDuration($get, $set) // self means it calling the function within the class ) ->extraAttributes(fn ($get) => [ 'class' => $get('plsToDateError') ? 'border-red-500' : '', @@ -293,7 +282,7 @@ class ProductionLineStopResource extends Resource ->hintColor('danger'), Forms\Components\TextInput::make('stop_hour') ->required() - ->label( 'Stop Hour') + ->label('Stop Hour') // ->dehydrated(false) // Don't send to backend ->readOnly(true) ->numeric(), @@ -318,24 +307,21 @@ class ProductionLineStopResource extends Resource $from = $get('from_datetime'); $to = $get('to_datetime'); - // Carbon is a PHP date and time library. + // Carbon is a PHP date and time library. if ($from && $to) { - $fromTime = Carbon::parse($from); //Carbon::parse($from) converts the from datetime string into a Carbon objec + $fromTime = Carbon::parse($from); // Carbon::parse($from) converts the from datetime string into a Carbon objec $toTime = Carbon::parse($to); if ($fromTime->lt($toTime)) { $diffInMinutes = $fromTime->diffInMinutes($toTime); // $set('stop_hour', floor($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_min', null); $set('plsToDateError', 'Time difference must be atlease a minute.'); - } - else - { + } else { $set('stop_hour', floor($diffInMinutes / 60)); $set('stop_min', $diffInMinutes % 60); $set('plsToDateError', null); @@ -363,6 +349,7 @@ class ProductionLineStopResource extends Resource $paginator = $livewire->getTableRecords(); $perPage = method_exists($paginator, 'perPage') ? $paginator->perPage() : 10; $currentPage = method_exists($paginator, 'currentPage') ? $paginator->currentPage() : 1; + return ($currentPage - 1) * $perPage + $rowLoop->iteration; }), Tables\Columns\TextColumn::make('linestop.code') @@ -433,8 +420,7 @@ class ProductionLineStopResource extends Resource Filter::make('advanced_filters') ->label('Advanced Filters') ->form([ - - //plant + // plant Select::make('Plant') ->label('Select Plant') ->nullable() @@ -443,6 +429,7 @@ class ProductionLineStopResource extends Resource // }) ->options(function (callable $get) { $userHas = Filament::auth()->user()->plant_id; + return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); }) ->reactive() @@ -453,31 +440,33 @@ class ProductionLineStopResource extends Resource $set('line_stop_id', null); }), - //line + // line Select::make('Line') ->label('Select line') ->nullable() ->options(function (callable $get) { $plantId = $get('Plant'); - if (!$plantId ) { + if (! $plantId) { return []; } + return Line::where('plant_id', $plantId) - ->pluck('name', 'id'); + ->pluck('name', 'id'); }) ->reactive(), - //block + // block Select::make('Block') ->label('Select Block') ->nullable() ->options(function (callable $get) { $plantId = $get('Plant'); - if (!$plantId ) { + if (! $plantId) { return []; } + return Block::where('plant_id', $get('Plant'))->pluck('name', 'id'); }) ->reactive() @@ -485,7 +474,7 @@ class ProductionLineStopResource extends Resource $set('Shift', null); }), - //shift + // shift Select::make('Shift') ->label('Select Shift') ->nullable() @@ -493,7 +482,7 @@ class ProductionLineStopResource extends Resource $plantId = $get('Plant'); $blockId = $get('Block'); - if (!$plantId || !$blockId) { + if (! $plantId || ! $blockId) { return []; // Return empty if plant or block is not selected } @@ -503,12 +492,13 @@ class ProductionLineStopResource extends Resource }) ->reactive(), - Select::make('line_stop_id') //linestop_id + Select::make('line_stop_id') // linestop_id ->label('Search by Line Stop Code') ->nullable() // ->options(fn () => LineStop::orderBy('code')->whereHas('productionLineStops')->pluck('code', 'id')) ->options(function (callable $get) { $pId = $get('Plant'); + return LineStop::orderBy('code')->whereHas('productionLineStops', function ($query) use ($pId) { if ($pId) { $query->where('plant_id', $pId); @@ -535,19 +525,25 @@ class ProductionLineStopResource extends Resource return $query->whereRaw('1 = 0'); } - if ($plant = $data['Plant'] ?? null) { - $query->where('plant_id', $plant); + if (! empty($data['Plant'])) {// if ($plant = $data['Plant'] ?? null) { + $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) { - $query->where('shift_id', $shift); + if (! empty($data['Shift'])) {// if ($shift = $data['Shift'] ?? null) { + $query->where('shift_id', $data['Shift']); } - if ($line = $data['Line'] ?? null) { - $query->where('line_id', $line); + if (! empty($data['Line'])) {// if ($line = $data['Line'] ?? null) { + $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 // $lineStop = \App\Models\LineStop::where('code', 'like', "%{$code}%")->first(); @@ -558,48 +554,54 @@ class ProductionLineStopResource extends Resource // // 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', $code); + $query->where('linestop_id', $data['line_stop_id']); } - if ($from = $data['created_from'] ?? null) { - $query->where('created_at', '>=', $from); + if (! empty($data['created_from'])) {// if ($from = $data['created_from'] ?? null) { + $query->where('created_at', '>=', $data['created_from']); } - if ($to = $data['created_to'] ?? null) { - $query->where('created_at', '<=', $to); + if (! empty($data['created_to'])) {// if ($to = $data['created_to'] ?? null) { + $query->where('created_at', '<=', $data['created_to']); } // return $query; }) ->indicateUsing(function (array $data) { $indicators = []; - if (!empty($data['Plant'])) { - $indicators[] = 'Plant: ' . Plant::where('id', $data['Plant'])->value('name'); + if (! empty($data['Plant'])) { + $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'])) { - $indicators[] = 'Shift: ' . Shift::where('id', $data['Shift'])->value('name'); + if (! empty($data['Shift'])) { + $indicators[] = 'Shift: '.Shift::where('id', $data['Shift'])->value('name'); } - if (!empty($data['Line'])) { - $indicators[] = 'Line: ' . Line::where('id', $data['Line'])->value('name'); + if (! empty($data['Line'])) { + $indicators[] = 'Line: '.Line::where('id', $data['Line'])->value('name'); } - if (!empty($data['created_from'])) { - $indicators[] = 'From: ' . $data['created_from']; + if (! empty($data['created_from'])) { + $indicators[] = 'From: '.$data['created_from']; } - if (!empty($data['created_to'])) { - $indicators[] = 'To: ' . $data['created_to']; + if (! empty($data['created_to'])) { + $indicators[] = 'To: '.$data['created_to']; } - if (!empty($data['line_stop_id'])) { + if (! empty($data['line_stop_id'])) { $lineStopCod = LineStop::find($data['line_stop_id'])->code ?? 'Unknown'; - $indicators[] = 'Line Stop Code: ' . $lineStopCod; + $indicators[] = 'Line Stop Code: '.$lineStopCod; } return $indicators; - }) + }), ]) ->filtersFormMaxHeight('280px') ->actions([ @@ -611,7 +613,7 @@ class ProductionLineStopResource extends Resource Tables\Actions\DeleteBulkAction::make(), Tables\Actions\ForceDeleteBulkAction::make(), Tables\Actions\RestoreBulkAction::make(), - FilamentExportBulkAction::make('export') + FilamentExportBulkAction::make('export'), ]), ]) ->headerActions([ @@ -619,14 +621,14 @@ class ProductionLineStopResource extends Resource ->label('Import Production Line Stops') ->color('warning') ->importer(ProductionLineStopImporter::class) - ->visible(function() { + ->visible(function () { return Filament::auth()->user()->can('view import production line stop'); }), ExportAction::make() ->label('Export Production Line Stops') ->color('warning') ->exporter(ProductionLineStopExporter::class) - ->visible(function() { + ->visible(function () { return Filament::auth()->user()->can('view export production line stop'); }), ]); diff --git a/app/Filament/Resources/ProductionPlanResource.php b/app/Filament/Resources/ProductionPlanResource.php index f1e45f7..d4845ca 100644 --- a/app/Filament/Resources/ProductionPlanResource.php +++ b/app/Filament/Resources/ProductionPlanResource.php @@ -6,7 +6,6 @@ use AlperenErsoy\FilamentExport\Actions\FilamentExportBulkAction; use App\Filament\Exports\ProductionPlanExporter; use App\Filament\Imports\ProductionPlanImporter; use App\Filament\Resources\ProductionPlanResource\Pages; -use App\Filament\Resources\ProductionPlanResource\RelationManagers; use App\Models\Block; use App\Models\Line; use App\Models\Plant; @@ -16,19 +15,18 @@ use Carbon\Carbon; use Filament\Facades\Filament; 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\Get; use Filament\Resources\Resource; use Filament\Tables; +use Filament\Tables\Actions\ExportAction; use Filament\Tables\Actions\ImportAction; +use Filament\Tables\Filters\Filter; use Filament\Tables\Table; use Illuminate\Database\Eloquent\Builder; 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 { @@ -55,22 +53,22 @@ class ProductionPlanResource extends Resource ->reactive() ->options(function (callable $get) { $userHas = Filament::auth()->user()->plant_id; + return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); }) ->default(function () { return optional(ProductionPlan::latest()->first())->plant_id; }) - ->disabled(fn (Get $get) => !empty($get('id'))) + ->disabled(fn (Get $get) => ! empty($get('id'))) // ->afterStateUpdated(fn ($set) => $set('block_name', null)) ->afterStateUpdated(function ($state, callable $set, callable $get) { $plantId = $get('plant_id'); $set('block_name', null); - if (!$plantId) { + if (! $plantId) { $set('ppPlantError', 'Please select a plant first.'); + return; - } - else - { + } else { $set('ppPlantError', null); } }) @@ -84,7 +82,7 @@ class ProductionPlanResource extends Resource // ->nullable() ->label('Block') ->options(function (callable $get) { - if (!$get('plant_id')) { + if (! $get('plant_id')) { return []; } @@ -95,16 +93,15 @@ class ProductionPlanResource extends Resource ->reactive() ->default(function () { $latestShiftId = optional(ProductionPlan::latest()->first())->shift_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) { - if($get('id')) - { + if ($get('id')) { $getShift = ProductionPlan::where('id', $get('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('ppBlockError', null); } @@ -113,12 +110,11 @@ class ProductionPlanResource extends Resource $blockId = $get('block_name'); $set('shift_id', null); - if (!$blockId) { + if (! $blockId) { $set('ppBlockError', 'Please select a block first.'); + return; - } - else - { + } else { $set('ppBlockError', null); } }) @@ -133,7 +129,7 @@ class ProductionPlanResource extends Resource // ->nullable() ->autofocus(true) ->options(function (callable $get) { - if (!$get('plant_id') || !$get('block_name')) { + if (! $get('plant_id') || ! $get('block_name')) { return []; } @@ -148,11 +144,9 @@ class ProductionPlanResource extends Resource }) // ->afterStateUpdated(fn ($set) => $set('line_id', null)) ->afterStateUpdated(function ($state, callable $set, callable $get) { - if($get('id')) - { + if ($get('id')) { $getShift = ProductionPlan::where('id', $get('id'))->first(); - if($getShift->shift_id) - { + if ($getShift->shift_id) { $set('shift_id', $getShift->shift_id); $set('ppShiftError', null); } @@ -161,12 +155,11 @@ class ProductionPlanResource extends Resource $curShiftId = $get('shift_id'); $set('line_id', null); - if (!$curShiftId) { + if (! $curShiftId) { $set('ppShiftError', 'Please select a shift first.'); + return; - } - else - { + } else { $set('ppShiftError', null); } }) @@ -185,7 +178,7 @@ class ProductionPlanResource extends Resource // ->toArray() // Convert collection to array // ) ->options(function (callable $get) { - if (!$get('plant_id') || !$get('block_name') || !$get('shift_id')) { + if (! $get('plant_id') || ! $get('block_name') || ! $get('shift_id')) { return []; } @@ -198,17 +191,13 @@ class ProductionPlanResource extends Resource // return optional(ProductionPlan::latest()->first())->line_id; // }) ->afterStateUpdated(function ($state, callable $set, callable $get) { - if($get('id')) - { + if ($get('id')) { $getShift = ProductionPlan::where('id', $get('id'))->first(); - if($getShift->line_id) - { + if ($getShift->line_id) { $set('line_id', $getShift->line_id); $set('ppLineError', null); } - } - else - { + } else { $currentDT = Carbon::now()->toDateTimeString(); $set('created_at', $currentDT); $set('update_date', null); @@ -217,44 +206,39 @@ class ProductionPlanResource extends Resource $lineId = $get('line_id'); // $set('plan_quantity', null); - if (!$lineId) { + if (! $lineId) { $set('ppLineError', 'Please select a line first.'); - return; - } - else - { - $isUpdate = !empty($get('id')); - if (!$isUpdate) - { - $exists = ProductionPlan::where('plant_id', $get('plant_id')) - ->where('shift_id', $get('shift_id')) - ->where('line_id', $get('line_id')) - ->whereDate('created_at', today()) - ->latest() - ->exists(); - if ($exists) - { - $set('line_id', null); - $set('ppLineError', 'Production plan already updated.'); - return; - } - else - { - $existShifts = ProductionPlan::where('plant_id', $get('plant_id')) + return; + } else { + $isUpdate = ! empty($get('id')); + if (! $isUpdate) { + $exists = ProductionPlan::where('plant_id', $get('plant_id')) ->where('shift_id', $get('shift_id')) ->where('line_id', $get('line_id')) - ->whereDate('created_at', Carbon::yesterday()) + ->whereDate('created_at', today()) ->latest() ->exists(); - if ($existShifts) //if ($existShifts->count() > 0) - { - //$currentDate = date('Y-m-d'); + if ($exists) { + $set('line_id', null); + $set('ppLineError', 'Production plan already updated.'); + + return; + } else { + $existShifts = ProductionPlan::where('plant_id', $get('plant_id')) + ->where('shift_id', $get('shift_id')) + ->where('line_id', $get('line_id')) + ->whereDate('created_at', Carbon::yesterday()) + ->latest() + ->exists(); + + if ($existShifts) { // if ($existShifts->count() > 0) + // $currentDate = date('Y-m-d'); $yesterday = date('Y-m-d', strtotime('-1 days')); $shiftId = Shift::where('id', $get('shift_id')) - ->first(); + ->first(); [$hRs, $miNs] = explode('.', $shiftId->duration) + [0, 0]; $hRs = (int) $hRs; @@ -262,27 +246,26 @@ class ProductionPlanResource extends Resource $totalMinutes = $hRs * 60 + $miNs; - $from_dt = $yesterday . ' ' . $shiftId->start_time; + $from_dt = $yesterday.' '.$shiftId->start_time; - $to_dt = date('Y-m-d H:i:s', strtotime($from_dt . " + $totalMinutes minutes")); + $to_dt = date('Y-m-d H:i:s', strtotime($from_dt." + $totalMinutes minutes")); $currentDateTime = date('Y-m-d H:i:s'); // Check if current date time is within the range if ($currentDateTime >= $from_dt && $currentDateTime < $to_dt) { - //echo "Choosed a valid shift..."; + // echo "Choosed a valid shift..."; $set('line_id', null); $set('ppLineError', 'Production plan already updated.'); + // $set('ppLineError', 'Valid (From: '.$from_dt.', To: '.$to_dt.')'); return; - } - else - { + } else { $currentDate = date('Y-m-d'); $shiftId = Shift::where('id', $get('shift_id')) - ->first(); + ->first(); [$hRs, $miNs] = explode('.', $shiftId->duration) + [0, 0]; $hRs = (int) $hRs; @@ -290,33 +273,33 @@ class ProductionPlanResource extends Resource $totalMinutes = $hRs * 60 + $miNs; - $from_dt = $currentDate . ' ' . $shiftId->start_time; + $from_dt = $currentDate.' '.$shiftId->start_time; - $to_dt = date('Y-m-d H:i:s', strtotime($from_dt . " + $totalMinutes minutes")); + $to_dt = date('Y-m-d H:i:s', strtotime($from_dt." + $totalMinutes minutes")); $currentDateTime = date('Y-m-d H:i:s'); // Check if current date time is within the range - if (!($currentDateTime >= $from_dt && $currentDateTime < $to_dt)) { - //echo "Choosed a valid shift..."; + if (! ($currentDateTime >= $from_dt && $currentDateTime < $to_dt)) { + // echo "Choosed a valid shift..."; $set('line_id', null); $set('ppLineError', 'Choosed a invalid shift.'); + // $set('ppLineError', 'Valid (From: '.$from_dt.', To: '.$to_dt.')'); return; } } $set('ppLineError', null); + return; - } - else - { - //$currentDate = date('Y-m-d'); + } else { + // $currentDate = date('Y-m-d'); $yesterday = date('Y-m-d', strtotime('-1 days')); $shiftId = Shift::where('id', $get('shift_id')) - ->first(); + ->first(); [$hRs, $miNs] = explode('.', $shiftId->duration) + [0, 0]; $hRs = (int) $hRs; @@ -324,30 +307,29 @@ class ProductionPlanResource extends Resource $totalMinutes = $hRs * 60 + $miNs; - $from_dt = $yesterday . ' ' . $shiftId->start_time; + $from_dt = $yesterday.' '.$shiftId->start_time; - $to_dt = date('Y-m-d H:i:s', strtotime($from_dt . " + $totalMinutes minutes")); + $to_dt = date('Y-m-d H:i:s', strtotime($from_dt." + $totalMinutes minutes")); $currentDateTime = date('Y-m-d H:i:s'); // Check if current date time is within the range if ($currentDateTime >= $from_dt && $currentDateTime < $to_dt) { - //echo "Choosed a valid shift..."; + // echo "Choosed a valid shift..."; // here i'm updating created as yesterday $set('created_at', $from_dt); $set('update_date', '1'); $set('ppLineError', null); + // $set('ppLineError', 'Valid (From: '.$from_dt.', To: '.$to_dt.')'); return; - } - else - { + } else { $currentDate = date('Y-m-d'); $shiftId = Shift::where('id', $get('shift_id')) - ->first(); + ->first(); [$hRs, $miNs] = explode('.', $shiftId->duration) + [0, 0]; $hRs = (int) $hRs; @@ -355,24 +337,26 @@ class ProductionPlanResource extends Resource $totalMinutes = $hRs * 60 + $miNs; - $from_dt = $currentDate . ' ' . $shiftId->start_time; + $from_dt = $currentDate.' '.$shiftId->start_time; - $to_dt = date('Y-m-d H:i:s', strtotime($from_dt . " + $totalMinutes minutes")); + $to_dt = date('Y-m-d H:i:s', strtotime($from_dt." + $totalMinutes minutes")); $currentDateTime = date('Y-m-d H:i:s'); // Check if current date time is within the range - if (!($currentDateTime >= $from_dt && $currentDateTime < $to_dt)) { - //echo "Choosed a valid shift..."; + if (! ($currentDateTime >= $from_dt && $currentDateTime < $to_dt)) { + // echo "Choosed a valid shift..."; $set('line_id', null); $set('ppLineError', 'Choosed a invalid shift.'); + // $set('ppLineError', 'Valid (From: '.$from_dt.', To: '.$to_dt.')'); return; } } $set('ppLineError', null); + return; } @@ -449,21 +433,18 @@ class ProductionPlanResource extends Resource ->afterStateUpdated(function ($state, callable $set, callable $get) { $planQuan = $get('plan_quantity'); - if(!$get('update_date') ) - { - if(!$get('id')) - { + if (! $get('update_date')) { + if (! $get('id')) { $currentDT = Carbon::now()->toDateTimeString(); $set('created_at', $currentDT); } } - if (!$planQuan) { + if (! $planQuan) { $set('ppPlanQuanError', 'Scan the valid plan quantity.'); + return; - } - else - { + } else { $set('ppPlanQuanError', null); } }) @@ -476,7 +457,7 @@ class ProductionPlanResource extends Resource ->required() ->integer() ->label('Production Quantity') - ->readOnly(fn (callable $get) => !$get('id')) + ->readOnly(fn (callable $get) => ! $get('id')) ->default(0), Forms\Components\TextInput::make('id') ->hidden() @@ -493,7 +474,7 @@ class ProductionPlanResource extends Resource ->readOnly(), Forms\Components\Hidden::make('operator_id') ->default(Filament::auth()->user()->name), - ]) + ]) ->columns(2), ]); } @@ -529,6 +510,7 @@ class ProductionPlanResource extends Resource $paginator = $livewire->getTableRecords(); $perPage = method_exists($paginator, 'perPage') ? $paginator->perPage() : 10; $currentPage = method_exists($paginator, 'currentPage') ? $paginator->currentPage() : 1; + return ($currentPage - 1) * $perPage + $rowLoop->iteration; }), Tables\Columns\TextColumn::make('plan_quantity') @@ -544,7 +526,7 @@ class ProductionPlanResource extends Resource Tables\Columns\TextColumn::make('line.name') ->label('Line') ->alignCenter() - ->sortable(),// ->searchable(), + ->sortable(), // ->searchable(), Tables\Columns\TextColumn::make('shift.block.name') ->label('Block') ->alignCenter() @@ -552,11 +534,11 @@ class ProductionPlanResource extends Resource Tables\Columns\TextColumn::make('shift.name') ->label('Shift') ->alignCenter() - ->sortable(),// ->searchable(), + ->sortable(), // ->searchable(), Tables\Columns\TextColumn::make('plant.name') ->label('Plant') ->alignCenter() - ->sortable(),// ->searchable(), + ->sortable(), // ->searchable(), Tables\Columns\TextColumn::make('created_at') ->label('Created At') ->dateTime() @@ -584,7 +566,7 @@ class ProductionPlanResource extends Resource Filter::make('advanced_filters') ->label('Advanced Filters') ->form([ - //plant + // plant Select::make('Plant') ->label('Select Plant') ->nullable() @@ -593,6 +575,7 @@ class ProductionPlanResource extends Resource // }) ->options(function (callable $get) { $userHas = Filament::auth()->user()->plant_id; + return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); }) ->reactive() @@ -602,31 +585,33 @@ class ProductionPlanResource extends Resource $set('Shift', null); }), - //line + // line Select::make('Line') ->label('Select line') ->nullable() ->options(function (callable $get) { $plantId = $get('Plant'); - if (!$plantId ) { + if (! $plantId) { return []; } + return Line::where('plant_id', $plantId) - ->pluck('name', 'id'); + ->pluck('name', 'id'); }) ->reactive(), - //block + // block Select::make('Block') ->label('Select Block') ->nullable() ->options(function (callable $get) { $plantId = $get('Plant'); - if (!$plantId ) { + if (! $plantId) { return []; } + return Block::where('plant_id', $get('Plant'))->pluck('name', 'id'); }) ->reactive() @@ -634,7 +619,7 @@ class ProductionPlanResource extends Resource $set('Shift', null); }), - //shift + // shift Select::make('Shift') ->label('Select Shift') ->nullable() @@ -642,7 +627,7 @@ class ProductionPlanResource extends Resource $plantId = $get('Plant'); $blockId = $get('Block'); - if (!$plantId || !$blockId) { + if (! $plantId || ! $blockId) { return []; // Return empty if plant or block is not selected } @@ -669,52 +654,65 @@ class ProductionPlanResource extends Resource return $query->whereRaw('1 = 0'); } - if ($plant = $data['Plant'] ?? null) { - $query->where('plant_id', $plant); + if (! empty($data['Plant'])) {// if ($plant = $data['Plant'] ?? null) { + $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) { - $query->where('shift_id', $shift); + if (! empty($data['Shift'])) {// if ($shift = $data['Shift'] ?? null) { + $query->where('shift_id', $data['Shift']); } - if ($line = $data['Line'] ?? null) { - $query->where('line_id', $line); + if (! empty($data['Line'])) {// if ($line = $data['Line'] ?? null) { + $query->where('line_id', $data['Line']); } - if ($from = $data['created_from'] ?? null) { - $query->where('created_at', '>=', $from); + if (! empty($data['created_from'])) {// if ($from = $data['created_from'] ?? null) { + $query->where('created_at', '>=', $data['created_from']); } - if ($to = $data['created_to'] ?? null) { - $query->where('created_at', '<=', $to); + if (! empty($data['created_to'])) {// if ($to = $data['created_to'] ?? null) { + $query->where('created_at', '<=', $data['created_to']); } + return $query; }) ->indicateUsing(function (array $data) { $indicators = []; - if (!empty($data['Plant'])) { - $indicators[] = 'Plant: ' . Plant::where('id', $data['Plant'])->value('name'); + if (! empty($data['Plant'])) { + $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'])) { - $indicators[] = 'Shift: ' . Shift::where('id', $data['Shift'])->value('name'); + if (! empty($data['Shift'])) { + $indicators[] = 'Shift: '.Shift::where('id', $data['Shift'])->value('name'); } - if (!empty($data['Line'])) { - $indicators[] = 'Line: ' . Line::where('id', $data['Line'])->value('name'); + if (! empty($data['Line'])) { + $indicators[] = 'Line: '.Line::where('id', $data['Line'])->value('name'); } - if (!empty($data['created_from'])) { - $indicators[] = 'From: ' . $data['created_from']; + if (! empty($data['created_from'])) { + $indicators[] = 'From: '.$data['created_from']; } - if (!empty($data['created_to'])) { - $indicators[] = 'To: ' . $data['created_to']; + if (! empty($data['created_to'])) { + $indicators[] = 'To: '.$data['created_to']; } return $indicators; - }) + }), ]) ->filtersFormMaxHeight('280px') ->actions([ @@ -726,7 +724,7 @@ class ProductionPlanResource extends Resource Tables\Actions\DeleteBulkAction::make(), Tables\Actions\ForceDeleteBulkAction::make(), Tables\Actions\RestoreBulkAction::make(), - FilamentExportBulkAction::make('export') + FilamentExportBulkAction::make('export'), ]), ]) ->headerActions([ @@ -734,14 +732,14 @@ class ProductionPlanResource extends Resource ->label('Import Production Plans') ->color('warning') ->importer(ProductionPlanImporter::class) - ->visible(function() { + ->visible(function () { return Filament::auth()->user()->can('view import production plan'); }), ExportAction::make() ->label('Export Production Plans') ->color('warning') ->exporter(ProductionPlanExporter::class) - ->visible(function() { + ->visible(function () { return Filament::auth()->user()->can('view export production plan'); }), ]); diff --git a/app/Filament/Resources/ProductionQuantityResource.php b/app/Filament/Resources/ProductionQuantityResource.php index 2da4d1b..1cada28 100644 --- a/app/Filament/Resources/ProductionQuantityResource.php +++ b/app/Filament/Resources/ProductionQuantityResource.php @@ -6,8 +6,6 @@ use AlperenErsoy\FilamentExport\Actions\FilamentExportBulkAction as ActionsFilam use App\Filament\Exports\ProductionQuantityExporter; use App\Filament\Imports\ProductionQuantityImporter; use App\Filament\Resources\ProductionQuantityResource\Pages; -use App\Filament\Resources\ProductionQuantityResource\RelationManagers; -use App\Forms\Components\PlantSelect; use App\Models\Block; use App\Models\Item; use App\Models\Line; @@ -18,41 +16,36 @@ use Carbon\Carbon; use Filament\Facades\Filament; use Filament\Forms; 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\Select; use Filament\Forms\Components\TextInput; -use Filament\Forms\Concerns\InteractsWithForms; +use Filament\Forms\Form; +use Filament\Forms\Get; use Filament\Notifications\Notification; +use Filament\Resources\Resource; +use Filament\Tables; use Filament\Tables\Actions\ExportAction; -use Livewire\Livewire; -// use Filament\Forms\Components\View; -use Filament\Tables\Actions\FilamentExportBulkAction; +use Filament\Tables\Actions\ImportAction; 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 { - protected static ?string $model = ProductionQuantity::class; protected static ?string $navigationIcon = 'heroicon-o-rectangle-stack'; // protected static ?string $navigationParentItem = 'Display Transactions'; - // protected static string $view = 'filament.pages.hourly-production'; + // protected static string $view = 'filament.pages.hourly-production'; protected static ?string $navigationGroup = 'Production'; protected static ?int $navigationSort = 1; - // public $plant_id; public static function form(Form $form): Form { @@ -64,30 +57,29 @@ class ProductionQuantityResource extends Resource ->relationship('plant', 'name') ->required() // ->nullable() - ->reactive() + ->reactive() // ->statePath('filters') - ->columnSpan(2) //1 - ->options(function (callable $get) { + ->columnSpan(2) // 1 + ->options(function (callable $get) { $userHas = Filament::auth()->user()->plant_id; + 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(function () { return optional(ProductionQuantity::latest()->first())->plant_id; }) - ->disabled(fn (Get $get) => !empty($get('id'))) + ->disabled(fn (Get $get) => ! empty($get('id'))) // ->afterStateUpdated(fn ($set) => $set('block_name', null)) - ->afterStateUpdated(function ($state, $set, callable $get,$livewire) { + ->afterStateUpdated(function ($state, $set, callable $get, $livewire) { $plantId = $get('plant_id'); $set('block_name', null); - if (!$plantId) - { + if (! $plantId) { $set('pqPlantError', 'Please select a plant first.'); + return; - } - else - { + } else { $set('validationError', null); $set('pqPlantError', null); } @@ -127,7 +119,7 @@ class ProductionQuantityResource extends Resource // ->nullable() ->columnSpan(1) ->options(function (callable $get) { - if (!$get('plant_id')) { + if (! $get('plant_id')) { return []; } @@ -138,15 +130,14 @@ class ProductionQuantityResource extends Resource ->reactive() ->default(function () { $latestShiftId = optional(ProductionQuantity::latest()->first())->shift_id; + return optional(Shift::where('id', $latestShiftId)->first())->block_id; }) ->afterStateUpdated(function ($state, callable $set, callable $get) { - if($get('id')) - { + if ($get('id')) { $getShift = ProductionQuantity::where('id', $get('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('pqBlockError', null); } @@ -158,12 +149,11 @@ class ProductionQuantityResource extends Resource // session(['select_plant' => $get('plant_id')]); // session()->forget('select_line'); - if (!$blockId) { + if (! $blockId) { $set('pqBlockError', 'Please select a block first.'); + return; - } - else - { + } else { $set('validationError', null); $set('pqBlockError', null); } @@ -179,7 +169,7 @@ class ProductionQuantityResource extends Resource ->columnSpan(1) // ->nullable() ->options(function (callable $get) { - if (!$get('plant_id') || !$get('block_name')) { + if (! $get('plant_id') || ! $get('block_name')) { return []; } @@ -192,13 +182,11 @@ class ProductionQuantityResource extends Resource ->default(function () { return optional(ProductionQuantity::latest()->first())->shift_id; }) - //->afterStateUpdated(fn ($set) => $set('line_id', null)) + // ->afterStateUpdated(fn ($set) => $set('line_id', null)) ->afterStateUpdated(function ($state, callable $set, callable $get) { - if($get('id')) - { + if ($get('id')) { $getShift = ProductionQuantity::where('id', $get('id'))->first(); - if($getShift->shift_id) - { + if ($getShift->shift_id) { $set('shift_id', $getShift->shift_id); $set('pqShiftError', null); } @@ -207,12 +195,11 @@ class ProductionQuantityResource extends Resource $curShiftId = $get('shift_id'); $set('line_id', null); - if (!$curShiftId) { + if (! $curShiftId) { $set('pqShiftError', 'Please select a shift first.'); + return; - } - else - { + } else { $set('validationError', null); $set('pqShiftError', null); } @@ -233,7 +220,7 @@ class ProductionQuantityResource extends Resource // ->toArray() // Convert collection to array // ) ->options(function (callable $get) { - if (!$get('plant_id') || !$get('block_name') || !$get('shift_id')) { + if (! $get('plant_id') || ! $get('block_name') || ! $get('shift_id')) { return []; } @@ -246,11 +233,9 @@ class ProductionQuantityResource extends Resource return optional(ProductionQuantity::latest()->first())->line_id; }) ->afterStateUpdated(function ($state, callable $set, callable $get) { - if($get('id')) - { + if ($get('id')) { $getShift = ProductionQuantity::where('id', $get('id'))->first(); - if($getShift->line_id) - { + if ($getShift->line_id) { $set('line_id', $getShift->line_id); $set('pqLineError', null); } @@ -259,16 +244,15 @@ class ProductionQuantityResource extends Resource $lineId = $get('line_id'); $set('item_code', null); - // session(['select_line' => $get('line_id')]); + // session(['select_line' => $get('line_id')]); session(['select_line' => $state]); - if (!$lineId) { + if (! $lineId) { $set('pqLineError', 'Please select a line first.'); + return; - } - else - { + } else { $set('validationError', null); $set('pqLineError', null); $set('item_id', null); @@ -276,7 +260,7 @@ class ProductionQuantityResource extends Resource $set('serial_number', null); $exists = ProductionQuantity::where('plant_id', $get('plant_id')) - //->where('shift_id', $get('shift_id')) + // ->where('shift_id', $get('shift_id')) ->where('line_id', $get('line_id')) ->latest() // Orders by created_at DESC ->first(); @@ -296,7 +280,7 @@ class ProductionQuantityResource extends Resource // 'x-on:change' => "\$wire.dispatch('filtersUpdated')", // Dispatch Livewire event from Alpine.js // ]) ->extraAttributes([ - 'x-on:change' => "\$wire.dispatch('filtersUpdated', { lineId: \$event.target.value })" + 'x-on:change' => "\$wire.dispatch('filtersUpdated', { lineId: \$event.target.value })", ]) ->extraAttributes(fn ($get) => [ 'class' => $get('pqLineError') ? 'border-red-500' : '', @@ -319,7 +303,7 @@ class ProductionQuantityResource extends Resource ->minLength(7) ->maxLength(14) ->columnSpan(2) - //->rules(['regex:/^[1-9][0-9]{6,}$/']) + // ->rules(['regex:/^[1-9][0-9]{6,}$/']) // ->disabled(function ($get) { // return $get('item_code'); // }) @@ -328,21 +312,20 @@ class ProductionQuantityResource extends Resource // $latestProductionOrder = ProductionQuantity::latest()->first()->production_order; // return $latestProductionOrder ?? null; $latestProduction = ProductionQuantity::latest()->first(); + return $latestProduction ? $latestProduction->production_order : null; }) ->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_id', null); $set('serial_number', 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); + return; - } - else - { + } else { $set('item_code', null); $set('item_id', null); // $set('item_description', null); @@ -350,6 +333,7 @@ class ProductionQuantityResource extends Resource $set('production_order', $state); $set('prodOrdError', null); $set('validationError', null); + return; // if (empty($state)) { // } @@ -923,17 +907,17 @@ class ProductionQuantityResource extends Resource ->required(), Forms\Components\Hidden::make('sap_msg_status'), Forms\Components\Hidden::make('sap_msg_description'), - //->unique(ignoreRecord: true), - // ->autocapitalize('characters'), - // ->columnSpanFull(), - Forms\Components\TextInput::make('recent_qr') //item_description + // ->unique(ignoreRecord: true), + // ->autocapitalize('characters'), + // ->columnSpanFull(), + Forms\Components\TextInput::make('recent_qr') // item_description ->label('Last scanned QR') ->reactive() ->columnSpan(2) ->default(function () { // Get the latest 'item_id' foreign key from 'production_quantities' table $latestProductionQuantity = ProductionQuantity::latest()->first(); - if (!$latestProductionQuantity) { + if (! $latestProductionQuantity) { return null; // Return null if no production quantities exist } @@ -953,7 +937,7 @@ class ProductionQuantityResource extends Resource Forms\Components\Hidden::make('operator_id') ->default(Filament::auth()->user()->name), ]) - ->columns(12), //6 + ->columns(12), // 6 ]); } @@ -971,20 +955,21 @@ class ProductionQuantityResource extends Resource $paginator = $livewire->getTableRecords(); $perPage = method_exists($paginator, 'perPage') ? $paginator->perPage() : 10; $currentPage = method_exists($paginator, 'currentPage') ? $paginator->currentPage() : 1; + return ($currentPage - 1) * $perPage + $rowLoop->iteration; }), Tables\Columns\TextColumn::make('production_order') ->label('Production Order') ->alignCenter() - ->sortable(),// ->searchable(), + ->sortable(), // ->searchable(), Tables\Columns\TextColumn::make('serial_number') ->label('Serial Number') ->alignCenter() - ->sortable(),// ->searchable(), + ->sortable(), // ->searchable(), Tables\Columns\TextColumn::make('item.code') ->label('Item Code') ->alignCenter() - ->sortable(),// ->searchable(), + ->sortable(), // ->searchable(), Tables\Columns\TextColumn::make('item.uom') ->label('Unit of Measure') ->alignCenter() @@ -1040,7 +1025,7 @@ class ProductionQuantityResource extends Resource Filter::make('advanced_filters') ->label('Advanced Filters') ->form([ - //plant + // plant Select::make('Plant') ->label('Select Plant') ->nullable() @@ -1049,6 +1034,7 @@ class ProductionQuantityResource extends Resource // }) ->options(function (callable $get) { $userHas = Filament::auth()->user()->plant_id; + return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); }) ->reactive() @@ -1061,34 +1047,36 @@ class ProductionQuantityResource extends Resource $set('operator_id', null); }), - //line + // line Select::make('Line') ->label('Select line') ->nullable() ->options(function (callable $get) { $plantId = $get('Plant'); - if (!$plantId ) { + if (! $plantId) { return []; } + return Line::where('plant_id', $plantId) - ->pluck('name', 'id'); + ->pluck('name', 'id'); }) ->reactive() ->afterStateUpdated(function ($state, callable $set, callable $get) { $set('operator_id', null); }), - //block + // block Select::make('Block') ->label('Select Block') ->nullable() ->options(function (callable $get) { $plantId = $get('Plant'); - if (!$plantId ) { + if (! $plantId) { return []; } + return Block::where('plant_id', $get('Plant'))->pluck('name', 'id'); }) ->reactive() @@ -1097,7 +1085,7 @@ class ProductionQuantityResource extends Resource $set('operator_id', null); }), - //shift + // shift Select::make('Shift') ->label('Select Shift') ->nullable() @@ -1105,7 +1093,7 @@ class ProductionQuantityResource extends Resource $plantId = $get('Plant'); $blockId = $get('Block'); - if (!$plantId || !$blockId) { + if (! $plantId || ! $blockId) { return []; // Return empty if plant or block is not selected } @@ -1132,11 +1120,10 @@ class ProductionQuantityResource extends Resource ->options(function (callable $get) { $plantId = $get('Plant'); - if (!$plantId ) { - return Item::distinct()->whereHas('productionQuantities')->pluck('code', 'id'); - } - else { - return Item::where('plant_id', $plantId)->whereHas('productionQuantities')->distinct()->pluck('code', 'id'); + if (! $plantId) { + return Item::whereHas('productionQuantities')->distinct()->pluck('code', 'id'); + } else { + return Item::whereHas('productionQuantities')->where('plant_id', $plantId)->distinct()->pluck('code', 'id'); } // return Item::whereHas('stickerMasters', function ($query) use ($pId) { // if ($pId) { @@ -1154,10 +1141,9 @@ class ProductionQuantityResource extends Resource ->options(function (callable $get) { $plantId = $get('Plant'); - if (!$plantId ) { + if (! $plantId) { 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'); } }) @@ -1171,24 +1157,15 @@ class ProductionQuantityResource extends Resource $plantId = $get('Plant'); $lineId = $get('Line'); $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'); - } - else if ($plantId && !$lineId && !$shiftId) - { + } elseif ($plantId && ! $lineId && ! $shiftId) { return ProductionQuantity::where('plant_id', $plantId)->whereNotNull('operator_id')->select('operator_id')->distinct()->pluck('operator_id', 'operator_id'); - } - else if ($plantId && $lineId && !$shiftId) - { + } elseif ($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'); - } - else if ($plantId && !$lineId && $shiftId) - { + } elseif ($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'); - } - 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'); } }) @@ -1212,44 +1189,50 @@ class ProductionQuantityResource extends Resource return $query->whereRaw('1 = 0'); } - if ($plant = $data['Plant'] ?? null) { - $query->where('plant_id', $plant); + if (! empty($data['Plant'])) {// if ($plant = $data['Plant'] ?? null) { + $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) { - $query->where('shift_id', $shift); + if (! empty($data['Shift'])) {// if ($shift = $data['Shift'] ?? null) { + $query->where('shift_id', $data['Shift']); } - if ($line = $data['Line'] ?? null) { - $query->where('line_id', $line); + if (! empty($data['Line'])) {// if ($line = $data['Line'] ?? null) { + $query->where('line_id', $data['Line']); } - if (!empty($data['production_order'])) { - $query->where('production_order', 'like', '%' . $data['production_order'] . '%'); + if (! empty($data['production_order'])) { + $query->where('production_order', 'like', '%'.$data['production_order'].'%'); } - if (!empty($data['serial_number'])) { - $query->where('serial_number', 'like', '%' . $data['serial_number'] . '%'); + if (! empty($data['serial_number'])) { + $query->where('serial_number', 'like', '%'.$data['serial_number'].'%'); } - if (!empty($data['Item'])) { + if (! empty($data['Item'])) { $query->where('item_id', $data['Item']); } - if (!empty($data['sap_msg_status'])) { + if (! empty($data['sap_msg_status'])) { $query->where('sap_msg_status', $data['sap_msg_status']); } - if (!empty($data['operator_id'])) { + if (! empty($data['operator_id'])) { $query->where('operator_id', $data['operator_id']); } - if ($from = $data['created_from'] ?? null) { - $query->where('created_at', '>=', $from); + if (! empty($data['created_from'])) {// if ($from = $data['created_from'] ?? null) { + $query->where('created_at', '>=', $data['created_from']); } - if ($to = $data['created_to'] ?? null) { - $query->where('created_at', '<=', $to); + if (! empty($data['created_to'])) {// if ($to = $data['created_to'] ?? null) { + $query->where('created_at', '<=', $data['created_to']); } // return $query; @@ -1257,48 +1240,54 @@ class ProductionQuantityResource extends Resource ->indicateUsing(function (array $data) { $indicators = []; - if (!empty($data['Plant'])) { - $indicators[] = 'Plant: ' . Plant::where('id', $data['Plant'])->value('name'); + if (! empty($data['Plant'])) { + $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'])) { - $indicators[] = 'Shift: ' . Shift::where('id', $data['Shift'])->value('name'); + if (! empty($data['Shift'])) { + $indicators[] = 'Shift: '.Shift::where('id', $data['Shift'])->value('name'); } - if (!empty($data['Line'])) { - $indicators[] = 'Line: ' . Line::where('id', $data['Line'])->value('name'); + if (! empty($data['Line'])) { + $indicators[] = 'Line: '.Line::where('id', $data['Line'])->value('name'); } - if (!empty($data['production_order'])) { - $indicators[] = 'Production Order: ' . $data['production_order']; + if (! empty($data['production_order'])) { + $indicators[] = 'Production Order: '.$data['production_order']; } - if (!empty($data['serial_number'])) { - $indicators[] = 'Serial Number: ' . $data['serial_number']; + if (! empty($data['serial_number'])) { + $indicators[] = 'Serial Number: '.$data['serial_number']; } - if (!empty($data['Item'])) { - $indicators[] = 'Item Code: ' . Item::where('id', $data['Item'])->value('code'); + if (! empty($data['Item'])) { + $indicators[] = 'Item Code: '.Item::where('id', $data['Item'])->value('code'); } - if (!empty($data['sap_msg_status'])) { - $indicators[] = 'SAP Message Status: ' . $data['sap_msg_status']; + if (! empty($data['sap_msg_status'])) { + $indicators[] = 'SAP Message Status: '.$data['sap_msg_status']; } - if (!empty($data['operator_id'])) { - $indicators[] = 'Created By: ' . $data['operator_id']; + if (! empty($data['operator_id'])) { + $indicators[] = 'Created By: '.$data['operator_id']; } - if (!empty($data['created_from'])) { - $indicators[] = 'From: ' . $data['created_from']; + if (! empty($data['created_from'])) { + $indicators[] = 'From: '.$data['created_from']; } - if (!empty($data['created_to'])) { - $indicators[] = 'To: ' . $data['created_to']; + if (! empty($data['created_to'])) { + $indicators[] = 'To: '.$data['created_to']; } return $indicators; - }) + }), ]) ->filtersFormMaxHeight('280px') ->actions([ @@ -1311,7 +1300,7 @@ class ProductionQuantityResource extends Resource Tables\Actions\ForceDeleteBulkAction::make(), Tables\Actions\RestoreBulkAction::make(), ActionsFilamentExportBulkAction::make('export') - ->defaultPageOrientation('landscape'), + ->defaultPageOrientation('landscape'), ]), ]) ->headerActions([ @@ -1319,16 +1308,16 @@ class ProductionQuantityResource extends Resource ->label('Import Production Quantities') ->color('warning') ->importer(ProductionQuantityImporter::class) - ->visible(function() { + ->visible(function () { return Filament::auth()->user()->can('view import production quantities'); }), - // ->chunkSize(250), - // ->maxRows(100000), + // ->chunkSize(250), + // ->maxRows(100000), ExportAction::make() ->label('Export Production Quantities') ->color('warning') ->exporter(ProductionQuantityExporter::class) - ->visible(function() { + ->visible(function () { return Filament::auth()->user()->can('view export production quantities'); }), ]); @@ -1370,7 +1359,6 @@ class ProductionQuantityResource extends Resource return 'Production Reports'; } - // public function triggerChartUpdate(): void // { // if (session()->has('select_plant') && session()->has('select_line')) { diff --git a/app/Filament/Resources/QualityValidationResource.php b/app/Filament/Resources/QualityValidationResource.php index e0bc91a..8a418a8 100644 --- a/app/Filament/Resources/QualityValidationResource.php +++ b/app/Filament/Resources/QualityValidationResource.php @@ -5,7 +5,6 @@ namespace App\Filament\Resources; use App\Filament\Exports\QualityValidationExporter; use App\Filament\Imports\QualityValidationImporter; use App\Filament\Resources\QualityValidationResource\Pages; -use App\Filament\Resources\QualityValidationResource\RelationManagers; // use App\Jobs\SendInvalidQualityMailJob; use App\Mail\InvalidQualityMail; use App\Models\AlertMailRule; @@ -16,30 +15,23 @@ use App\Models\QualityValidation; use App\Models\StickerMaster; // use App\Models\User; // use App\Notifications\StatusUpdated; -use Carbon\Carbon; -use Closure; use Filament\Facades\Filament; use Filament\Forms; -use Filament\Forms\Components\DatePicker; use Filament\Forms\Components\DateTimePicker; use Filament\Forms\Components\Select; use Filament\Forms\Components\TextInput; use Filament\Forms\Form; +use Filament\Notifications\Notification; use Filament\Resources\Resource; use Filament\Tables; use Filament\Tables\Actions\ExportAction; use Filament\Tables\Actions\ImportAction; -use Filament\Tables\Filters\SelectFilter; +use Filament\Tables\Filters\Filter; use Filament\Tables\Table; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Factories\Relationship; use Illuminate\Database\Eloquent\SoftDeletingScope; -use Filament\Tables\Filters\Filter; -use Illuminate\Database\Eloquent\Model; -use Illuminate\Validation\ValidationException; -use Filament\Notifications\Notification; use Illuminate\Support\Facades\Mail; -use Storage; class QualityValidationResource extends Resource { @@ -50,6 +42,7 @@ class QualityValidationResource extends Resource protected static ?string $navigationGroup = 'Display'; public $isSubmitted = false; + public $data = []; public static function form(Form $form): Form @@ -62,6 +55,7 @@ class QualityValidationResource extends Resource ->reactive() ->options(function (callable $get) { $userHas = Filament::auth()->user()->plant_id; + return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); }) ->afterStateUpdated(function (callable $set, callable $get, $state) { @@ -77,20 +71,19 @@ class QualityValidationResource extends Resource $set('plant', $state); $pId = $get('plant_id'); - if (!$pId) { + if (! $pId) { $set('pqPlantError', 'Please select a plant first.'); - } - else { + } else { $set('pqPlantError', null); } $pId = $get('line_id'); - if (!$pId) { + if (! $pId) { $set('pqLineError', null); } }) ->required() - //->default(fn () => request()->query('plant_id')) + // ->default(fn () => request()->query('plant_id')) ->default(fn ($get) => $get('plant') ?? session('last_selected_plant_id')) ->extraAttributes(fn ($get) => [ 'class' => $get('pqPlantError') ? 'border-red-500' : '', @@ -106,15 +99,14 @@ class QualityValidationResource extends Resource ->required() ->options(function (callable $get) { $plantId = $get('plant_id'); - if (!$plantId) - { + if (! $plantId) { return []; } return Line::where('plant_id', $plantId) - ->where('type', 'FG Line') // Filter by type - ->pluck('name', 'id') - ->toArray(); + ->where('type', 'FG Line') // Filter by type + ->pluck('name', 'id') + ->toArray(); }) ->afterStateUpdated(function (callable $set, callable $get, $state) { $set('item_id', null); @@ -123,7 +115,7 @@ class QualityValidationResource extends Resource $set('line', $state); $pId = $get('line_id'); - if (!$pId) { + if (! $pId) { $set('pqLineError', 'Please select a line.'); } else { $set('pqLineError', null); @@ -151,17 +143,14 @@ class QualityValidationResource extends Resource ->reactive() ->readOnly(fn (callable $get) => $get('item_id')) ->afterStateUpdated(function (callable $set, callable $get, ?string $state) { - if(!is_numeric($get('production_order')) || !preg_match('/^[1-9][0-9]{6,13}$/', $get('production_order'))) - { - $set('prodOrdError', "Must be a numeric value with 7 to 14 digits."); + if (! is_numeric($get('production_order')) || ! preg_match('/^[1-9][0-9]{6,13}$/', $get('production_order'))) { + $set('prodOrdError', 'Must be a numeric value with 7 to 14 digits.'); $set('production_order', null); $set('item_id', null); $set('sticker_master_id', null); $set('uom', null); $set('serial_number', null); - } - else - { + } else { $set('prodOrdError', null); $set('production_order', $state); $set('production', $state); @@ -224,28 +213,25 @@ class QualityValidationResource extends Resource $set('show_validation_image', false); $set('validation1_image_url', null); - if (!$pId) { + if (! $pId) { $set('pqLineError', 'Please select a line.'); } else { $set('pqLineError', null); } $pOrder = $get('production_order'); - if (!$pOrder) - { + if (! $pOrder) { $set('prodOrdError', "Production Order can't be empty."); $set('production_order', null); $set('part_validation_type', null); $set('show_validation_image', false); $set('validation1_image_url', null); - } - else - { + } else { $set('prodOrdError', null); } $serialFields = [ - 'serial_number_motor_qr', 'serial_number_pump_qr', 'serial_number_pumpset_qr', 'pack_slip_motor_qr', 'pack_slip_pump_qr', 'pack_slip_pumpset_qr', 'name_plate_motor_qr', 'name_plate_pump_qr', 'name_plate_pumpset_qr', 'tube_sticker_motor_qr', 'tube_sticker_pump_qr', 'tube_sticker_pumpset_qr', 'warranty_card_qr' + 'serial_number_motor_qr', 'serial_number_pump_qr', 'serial_number_pumpset_qr', 'pack_slip_motor_qr', 'pack_slip_pump_qr', 'pack_slip_pumpset_qr', 'name_plate_motor_qr', 'name_plate_pump_qr', 'name_plate_pumpset_qr', 'tube_sticker_motor_qr', 'tube_sticker_pump_qr', 'tube_sticker_pumpset_qr', 'warranty_card_qr', ]; $set('serial_number', null); @@ -253,22 +239,23 @@ class QualityValidationResource extends Resource $serialnumber = ['serial_number_motor_qr', 'serial_number_pump_qr', 'serial_number_pumpset_qr']; $partValidationColumns = [ - 'part_validation1', 'part_validation2', 'part_validation3', 'part_validation4', 'part_validation5' + 'part_validation1', 'part_validation2', 'part_validation3', 'part_validation4', 'part_validation5', ]; foreach ($serialFields as $field) { - $set($field . '_visible', false); + $set($field.'_visible', false); $set($field, null); } foreach ($partValidationColumns as $column) { - $set($column . '_visible', false); + $set($column.'_visible', false); $set($column, null); } // Proceed with validation logic for new scanned QR code - if (!$state || trim($state) == '') { + if (! $state || trim($state) == '') { $set('validationError', null); + return; } @@ -279,10 +266,11 @@ class QualityValidationResource extends Resource $set('show_validation_image', false); $set('part_validation_type_options', []); $set('validation1_image_url', null); + return; } - if (!preg_match('/^[a-zA-Z0-9]{6,}+\|[1-9][a-zA-Z0-9]{8,}+(\|)?$/', $state)) { + if (! preg_match('/^[a-zA-Z0-9]{6,}+\|[1-9][a-zA-Z0-9]{8,}+(\|)?$/', $state)) { // if (strpos($state, '|') == false) { // $set('validationError', 'Scan valid QR code. (Ex: Item_Code|Serial_Number)'); // $set('item_id', null); @@ -292,47 +280,46 @@ class QualityValidationResource extends Resource // } // else // { - $splits = explode('|', $state); - $iCode = trim($splits[0]); - $sNumber = isset($splits[1]) ? trim($splits[1]) : null; + $splits = explode('|', $state); + $iCode = trim($splits[0]); + $sNumber = isset($splits[1]) ? trim($splits[1]) : null; - if (!ctype_alnum($iCode)) { - $set('validationError', 'Item code must contain alpha-numeric values.'); - $set('part_validation_type', null); - $set('show_validation_image', false); - $set('part_validation_type_options', []); - $set('validation1_image_url', null); - return; - } - else if (strlen($iCode) < 6) { - $set('validationError', 'Item code must be at least 6 digits.'); - $set('part_validation_type', null); - $set('show_validation_image', false); - $set('part_validation_type_options', []); - $set('validation1_image_url', null); - return; - } - else if (!ctype_alnum($sNumber)) { - $set('validationError', 'Serial Number must contain alpha-numeric values.'); - $set('part_validation_type', null); - $set('show_validation_image', false); - $set('part_validation_type_options', []); - $set('validation1_image_url', null); - return; - } - else if (strlen($sNumber) < 9) { - $set('validationError', 'Serial Number must be at least 9 digits.'); - $set('part_validation_type', null); - $set('show_validation_image', false); - $set('part_validation_type_options', []); - $set('validation1_image_url', null); - return; - } + if (! ctype_alnum($iCode)) { + $set('validationError', 'Item code must contain alpha-numeric values.'); + $set('part_validation_type', null); + $set('show_validation_image', false); + $set('part_validation_type_options', []); + $set('validation1_image_url', null); + + return; + } elseif (strlen($iCode) < 6) { + $set('validationError', 'Item code must be at least 6 digits.'); + $set('part_validation_type', null); + $set('show_validation_image', false); + $set('part_validation_type_options', []); + $set('validation1_image_url', null); + + return; + } elseif (! ctype_alnum($sNumber)) { + $set('validationError', 'Serial Number must contain alpha-numeric values.'); + $set('part_validation_type', null); + $set('show_validation_image', false); + $set('part_validation_type_options', []); + $set('validation1_image_url', null); + + return; + } elseif (strlen($sNumber) < 9) { + $set('validationError', 'Serial Number must be at least 9 digits.'); + $set('part_validation_type', null); + $set('show_validation_image', false); + $set('part_validation_type_options', []); + $set('validation1_image_url', null); + + return; + } // } - } - else - { + } else { $set('validationError', null); } @@ -353,61 +340,60 @@ class QualityValidationResource extends Resource $set('show_validation_image', false); $set('part_validation_type_options', []); $set('validation1_image_url', null); + return; - } - else if (!ctype_alnum($itemCode)) { + } elseif (! ctype_alnum($itemCode)) { $set('validationError', 'Item Code should contain alpha-numeric values.'); $set('item_id', null); $set('part_validation_type', null); $set('show_validation_image', false); $set('part_validation_type_options', []); $set('validation1_image_url', null); + return; - } - else if ($serialNumber == '') { + } elseif ($serialNumber == '') { $set('validationError', 'Waiting for full QR scan...'); + return; - } - else if (strlen($serialNumber) < 9) { + } elseif (strlen($serialNumber) < 9) { $set('validationError', 'Serial Number must be at least 9 digits.'); $set('part_validation_type', null); $set('show_validation_image', false); $set('part_validation_type_options', []); $set('validation1_image_url', null); + return; - } - else if (!ctype_alnum($serialNumber)) { + } elseif (! ctype_alnum($serialNumber)) { $set('validationError', 'Serial Number should contain alpha-numeric values.'); $set('item_id', null); $set('part_validation_type', null); $set('show_validation_image', false); $set('part_validation_type_options', []); $set('validation1_image_url', null); + return; - } - else - { + } else { $set('validationError', null); } $plantId = $get('plant_id'); // Get selected plant - if (!$plantId) { + if (! $plantId) { $set('validationError', 'Please select a plant first.'); $set('item_id', null); $set('part_validation_type', null); $set('show_validation_image', false); $set('part_validation_type_options', []); $set('validation1_image_url', null); + return; } // Check if the item exists for the selected plant $stickerMaster = StickerMaster::where('plant_id', $plantId)->whereHas('item', function ($query) use ($itemCode) { - $query->where('code', $itemCode); - })->first(); + $query->where('code', $itemCode); + })->first(); - - if (!$stickerMaster) { + if (! $stickerMaster) { $set('validationError', 'Item code does not exist in master data.'); $set('sticker_master_id', null); $set('uom', null); @@ -416,11 +402,10 @@ class QualityValidationResource extends Resource $set('show_validation_image', false); $set('part_validation_type_options', []); $set('validation1_image_url', null); + return; - } - else - { - if (!$stickerMaster->item->uom) { + } else { + if (! $stickerMaster->item->uom) { $set('validationError', "Item code does not have 'UOM' in master data."); $set('sticker_master_id', null); $set('uom', null); @@ -428,11 +413,10 @@ class QualityValidationResource extends Resource $set('part_validation_type', null); $set('show_validation_image', false); $set('validation1_image_url', null); + return; - } - else if(!is_numeric($get('production_order')) || !preg_match('/^[1-9][0-9]{6,13}$/', $get('production_order'))) - { - $set('prodOrdError', "Must be a numeric value."); + } elseif (! is_numeric($get('production_order')) || ! preg_match('/^[1-9][0-9]{6,13}$/', $get('production_order'))) { + $set('prodOrdError', 'Must be a numeric value.'); $set('item_id', null); $set('sticker_master_id', null); $set('uom', null); @@ -441,6 +425,7 @@ class QualityValidationResource extends Resource $set('show_validation_image', false); $set('part_validation_type_options', []); $set('validation1_image_url', null); + return; } @@ -458,6 +443,7 @@ class QualityValidationResource extends Resource if ($userInput != null && $userInput != $expectedValue) { $set('validationError', "Invalid input for $field. Expected: $expectedValue"); + return; // Stop execution if any validation fails } } @@ -475,19 +461,19 @@ class QualityValidationResource extends Resource // } // })->exists(); - - if ($serialExists && !$get('id')) { + if ($serialExists && ! $get('id')) { $set('validationError', 'Serial number already exists in quality validation.'); - //$set('item_id', "$itemCode|$previousSerialNumber"); - // $set('item_id', null); + // $set('item_id', "$itemCode|$previousSerialNumber"); + // $set('item_id', null); $set('sticker_master_id', null); $set('uom', null); $set('serial_number', null); + return; } // Clear validation error if all inputs match - $set('validationError', null); + $set('validationError', null); // $visibleColumns = []; // foreach ($serialFields as $column) { @@ -505,30 +491,30 @@ class QualityValidationResource extends Resource foreach ($serialFields as $column) { - $colFld = $column; + $colFld = $column; if (str_ends_with($colFld, '_qr')) { $colFld = substr($colFld, 0, -3); } if ($stickerMaster->$colFld != null) { - $set($column . '_visible', true); + $set($column.'_visible', true); } else { - $set($column . '_visible', false); + $set($column.'_visible', false); } } foreach ($partValidationColumns as $column) { if ($stickerMaster->$column != null) { - $set($column . '_visible', true); + $set($column.'_visible', true); } else { - $set($column . '_visible', false); + $set($column.'_visible', false); } } foreach ($serialnumber as $field) { if ($get("{$field}_visible")) { $set($field, $serialNumber); - $colFld = $field; + $colFld = $field; if (str_ends_with($colFld, '_qr')) { $colFld = substr($colFld, 0, -3); } @@ -540,36 +526,38 @@ class QualityValidationResource extends Resource // Find item based on scanned code $item = Item::where('code', $itemCode) - ->where('plant_id', $plantId)->first(); + ->where('plant_id', $plantId)->first(); - if (!$item) { + if (! $item) { $set('part_validation_type_options', []); + return; } // Find sticker master $sticker = StickerMaster::where('plant_id', $plantId) - ->where('item_id', $item->id) - ->first(); + ->where('item_id', $item->id) + ->first(); - if (!$sticker) { + if (! $sticker) { $set('part_validation_type_options', []); + return; } // Build dynamic options $options = []; - if (!empty($sticker->part_validation1)) { + if (! empty($sticker->part_validation1)) { $options['part_validation1'] = 'Part Validation 1'; } - if (!empty($sticker->part_validation2)) { + if (! empty($sticker->part_validation2)) { $options['part_validation2'] = 'Part Validation 2'; } - if (!empty($sticker->part_validation3)) { + if (! empty($sticker->part_validation3)) { $options['part_validation3'] = 'Part Validation 3'; } - if (!empty($sticker->part_validation4)) { + if (! empty($sticker->part_validation4)) { $options['part_validation4'] = 'Part Validation 4'; } @@ -663,59 +651,61 @@ class QualityValidationResource extends Resource $set('show_validation_image', false); $set('validation1_image_url', null); }) - ->visible(fn ($get) => !empty($get('part_validation_type_options'))) + ->visible(fn ($get) => ! empty($get('part_validation_type_options'))) ->suffixAction( - Forms\Components\Actions\Action::make('toggleValidationImage') - ->icon(fn (callable $get) => $get('show_validation_image') ? 'heroicon-o-eye-slash' : 'heroicon-o-eye') - ->tooltip('View Validation Image') - ->action(function (callable $get, $set) { + Forms\Components\Actions\Action::make('toggleValidationImage') + ->icon(fn (callable $get) => $get('show_validation_image') ? 'heroicon-o-eye-slash' : 'heroicon-o-eye') + ->tooltip('View Validation Image') + ->action(function (callable $get, $set) { - $currentState = $get('show_validation_image'); - $set('show_validation_image', !$currentState); + $currentState = $get('show_validation_image'); + $set('show_validation_image', ! $currentState); - if ($currentState == true) { - $set('validation1_image_url', null); - return; - } + if ($currentState == true) { + $set('validation1_image_url', null); - $partvalidationType = $get('part_validation_type'); - $plantId1 = $get('plant_id'); + return; + } - $plantCode1 = Plant::where('id', $plantId1)->value('code'); + $partvalidationType = $get('part_validation_type'); + $plantId1 = $get('plant_id'); - $itemState = $get('item_id'); - $parts = explode('|', $itemState); - $itemCode = trim($parts[0]); + $plantCode1 = Plant::where('id', $plantId1)->value('code'); - $itemId1 = Item::where('code', $itemCode) - ->where('plant_id', $plantId1) - ->first(); + $itemState = $get('item_id'); + $parts = explode('|', $itemState); + $itemCode = trim($parts[0]); - $itemId2 = $itemId1?->id; + $itemId1 = Item::where('code', $itemCode) + ->where('plant_id', $plantId1) + ->first(); - $sticker = StickerMaster::where('plant_id', $plantId1) - ->where('item_id', $itemId2) - ->first(); + $itemId2 = $itemId1?->id; - if (!$sticker) { - Notification::make() - ->title('Sticker Master Missing') - ->body('No Sticker Master found for selected Plant & Item.') - ->danger() - ->send(); - return; - } + $sticker = StickerMaster::where('plant_id', $plantId1) + ->where('item_id', $itemId2) + ->first(); - $value = $sticker->{$partvalidationType}; - $fileName = "{$value}.png"; + if (! $sticker) { + Notification::make() + ->title('Sticker Master Missing') + ->body('No Sticker Master found for selected Plant & Item.') + ->danger() + ->send(); - $imageUrl = route('part.validation.image', [ - 'filename' => $fileName - ]); + return; + } - $set('validation1_image_url', $imageUrl); - }) - ), + $value = $sticker->{$partvalidationType}; + $fileName = "{$value}.png"; + + $imageUrl = route('part.validation.image', [ + 'filename' => $fileName, + ]); + + $set('validation1_image_url', $imageUrl); + }) + ), // Forms\Components\Actions::make([ // Forms\Components\Actions\Action::make('openValidation') @@ -737,7 +727,6 @@ class QualityValidationResource extends Resource // $plantCode1 = Plant::where('id', $plantId1)->value('code'); - // $itemState = $get('item_id'); // $parts = explode('|', $itemState); @@ -783,12 +772,12 @@ class QualityValidationResource extends Resource // ->visible(fn ($get) => !empty($get('part_validation_type_options'))), Forms\Components\Hidden::make('validation1_image_url') - ->reactive(), + ->reactive(), Forms\Components\View::make('components.part-validation-error-icon') - ->statePath('validation1_image_url') // bind state directly - ->visible(fn ($get) => $get('show_validation_image') == true) - ->reactive(), + ->statePath('validation1_image_url') // bind state directly + ->visible(fn ($get) => $get('show_validation_image') == true) + ->reactive(), Forms\Components\Hidden::make('serial_number') ->required(), @@ -798,8 +787,8 @@ class QualityValidationResource extends Resource Forms\Components\TextInput::make('serial_number_motor_qr') ->label('Serial Number Motor') ->reactive() - ->readOnly(fn (callable $get) => !$get('id')) - ->hidden(fn (callable $get) => !$get('serial_number_motor_qr_visible')) // Controls visibility + ->readOnly(fn (callable $get) => ! $get('id')) + ->hidden(fn (callable $get) => ! $get('serial_number_motor_qr_visible')) // Controls visibility ->default(''), Forms\Components\Hidden::make('serial_number_pump'), @@ -808,7 +797,7 @@ class QualityValidationResource extends Resource ->label('Serial Number Pump') ->reactive() ->required() - ->hidden(fn (callable $get) => !$get('serial_number_pump_qr_visible')) + ->hidden(fn (callable $get) => ! $get('serial_number_pump_qr_visible')) ->default('') ->afterStateUpdated(function (callable $set, callable $get, ?string $state) { @@ -816,67 +805,65 @@ class QualityValidationResource extends Resource if (empty($state)) { $set('serial_number_pump_error', null); + return; } - if (strpos($state, '|') == false) - { - if (preg_match('/^[1-9][a-zA-Z0-9]{8,}$/', $state)) - { + if (strpos($state, '|') == false) { + if (preg_match('/^[1-9][a-zA-Z0-9]{8,}$/', $state)) { $visibleSerialNumber = $get('serial_number'); $serialNumber = $state; - if ($visibleSerialNumber != $serialNumber) - { + if ($visibleSerialNumber != $serialNumber) { $set('serial_number_pump_error', 'Serial number does not match.'); $set('serial_number_pump_qr', null); + return; - } - else { + } else { $set('serial_number_pump_error', null); $set('serial_number_pump_qr', $serialNumber); $set('serial_number_pump', '1'); + return; } } if (strlen($state) < 9) { $set('serial_number_pump_error', 'Serial Number must be at least 9 digits.'); + return; - } - else if (!ctype_alnum($state)) { + } elseif (! ctype_alnum($state)) { $set('serial_number_pump_error', 'Serial Number must contain alpha-numeric values.'); + return; } - } - else if (strpos($state, '|') == true && !preg_match('/^([a-zA-Z0-9]{6,})\|([1-9][a-zA-Z0-9]{8,})(?:\/[MmPpCc])?\|?$/', $state)) - { + } elseif (strpos($state, '|') == true && ! preg_match('/^([a-zA-Z0-9]{6,})\|([1-9][a-zA-Z0-9]{8,})(?:\/[MmPpCc])?\|?$/', $state)) { $splits = explode('|', $state); $iCode = trim($splits[0]); $sNumber = isset($splits[1]) ? trim($splits[1]) : null; - if (!ctype_alnum($iCode)) { + if (! ctype_alnum($iCode)) { $set('serial_number_pump_error', 'Item code must contain alpha-numeric values.'); + return; - } - else if (strlen($iCode) < 6) { + } elseif (strlen($iCode) < 6) { $set('serial_number_pump_error', 'Item code must be at least 6 digits.'); + return; - } - else if (strlen($sNumber) < 9) { + } elseif (strlen($sNumber) < 9) { $set('serial_number_pump_error', 'Serial Number must be at least 9 digits.'); + return; - } - else if (!ctype_alnum($sNumber)) { + } elseif (! ctype_alnum($sNumber)) { $set('serial_number_pump_error', 'Serial Number must contain alpha-numeric values.'); + return; } $set('serial_number_pump_error', 'Scan valid QR code.'); + return; - } - else - { + } else { $set('serial_number_pump_error', null); } @@ -898,30 +885,30 @@ class QualityValidationResource extends Resource $expectedItemCode = trim((string) $get('item_id')); - if ($itemCode != $expectedItemCode) - { + if ($itemCode != $expectedItemCode) { $set('serial_number_pump_error', 'Item code does not match.'); + return; } - $set('serial_number_pump_qr', $serialNumber); - $set('serial_number_pump', '1'); + $set('serial_number_pump_qr', $serialNumber); + $set('serial_number_pump', '1'); // $isMatch = in_array($serialNumber, $visibleSerialNumbers, true); $isMatch = ($visibleSerialNumber == $serialNumber); - if (!$serialNumber || trim($serialNumber) == '') { + if (! $serialNumber || trim($serialNumber) == '') { $set('serial_number_pump_error', null); + return; } - if (!$isMatch) - { + if (! $isMatch) { $set('serial_number_pump_error', 'Serial number does not match.'); $set('serial_number_pump_qr', null); + return; - } - else { + } else { $set('serial_number_pump_error', null); $set('serial_number_pump_qr', $serialNumber); $set('serial_number_pump', '1'); @@ -930,23 +917,23 @@ class QualityValidationResource extends Resource ->extraAttributes(fn ($get) => [ 'class' => $get('serial_number_pump_error') ? 'border-red-500' : '', ]) - ->hint(fn ($get) => $get('serial_number_pump_error') ? $get('serial_number_pump_error') : null) - ->hintColor('danger'), + ->hint(fn ($get) => $get('serial_number_pump_error') ? $get('serial_number_pump_error') : null) + ->hintColor('danger'), Forms\Components\Hidden::make('serial_number_pumpset'), Forms\Components\TextInput::make('serial_number_pumpset_qr') ->label('Serial Number PumpSet') ->reactive() - ->readOnly(fn (callable $get) => !$get('id')) - ->hidden(fn (callable $get) => !$get('serial_number_pumpset_qr_visible')) + ->readOnly(fn (callable $get) => ! $get('id')) + ->hidden(fn (callable $get) => ! $get('serial_number_pumpset_qr_visible')) ->default(''), Forms\Components\Hidden::make('pack_slip_motor'), Forms\Components\TextInput::make('pack_slip_motor_qr') ->label('Pack Slip Motor') - ->hidden(fn (callable $get) => !$get('pack_slip_motor_qr_visible')) + ->hidden(fn (callable $get) => ! $get('pack_slip_motor_qr_visible')) ->default('') ->reactive() ->required() @@ -956,67 +943,65 @@ class QualityValidationResource extends Resource if (empty($state)) { $set('pack_slip_motor_error', null); + return; } - if (strpos($state, '|') == false) - { - if (preg_match('/^[1-9][a-zA-Z0-9]{8,}$/', $state)) - { + if (strpos($state, '|') == false) { + if (preg_match('/^[1-9][a-zA-Z0-9]{8,}$/', $state)) { $visibleSerialNumber = $get('serial_number'); $serialNumber = $state; - if ($visibleSerialNumber != $serialNumber) - { + if ($visibleSerialNumber != $serialNumber) { $set('pack_slip_motor_error', 'Serial number does not match.'); $set('pack_slip_motor_qr', null); + return; - } - else { + } else { $set('pack_slip_motor_error', null); $set('pack_slip_motor_qr', $serialNumber); $set('pack_slip_motor', '1'); + return; } } if (strlen($state) < 9) { $set('pack_slip_motor_error', 'Serial Number must be at least 9 digits.'); + return; - } - else if (!ctype_alnum($state)) { + } elseif (! ctype_alnum($state)) { $set('pack_slip_motor_error', 'Serial Number must contain alpha-numeric values.'); + return; } - } - else if (strpos($state, '|') == true && !preg_match('/^([a-zA-Z0-9]{6,})\|([1-9][a-zA-Z0-9]{8,})(?:\/[MmPpCc])?\|?$/', $state)) - { + } elseif (strpos($state, '|') == true && ! preg_match('/^([a-zA-Z0-9]{6,})\|([1-9][a-zA-Z0-9]{8,})(?:\/[MmPpCc])?\|?$/', $state)) { $splits = explode('|', $state); $iCode = trim($splits[0]); $sNumber = isset($splits[1]) ? trim($splits[1]) : null; - if (!ctype_alnum($iCode)) { + if (! ctype_alnum($iCode)) { $set('pack_slip_motor_error', 'Item code must contain alpha-numeric values.'); + return; - } - else if (strlen($iCode) < 6) { + } elseif (strlen($iCode) < 6) { $set('pack_slip_motor_error', 'Item code must be at least 6 digits.'); + return; - } - else if (strlen($sNumber) < 9) { + } elseif (strlen($sNumber) < 9) { $set('pack_slip_motor_error', 'Serial Number must be at least 9 digits.'); + return; - } - else if (!ctype_alnum($sNumber)) { + } elseif (! ctype_alnum($sNumber)) { $set('pack_slip_motor_error', 'Serial Number must contain alpha-numeric values.'); + return; } $set('pack_slip_motor_error', 'Scan valid QR code'); + return; - } - else - { + } else { $set('pack_slip_motor_error', null); } @@ -1034,52 +1019,51 @@ class QualityValidationResource extends Resource // $get('serial_number_pumpset_qr_visible') ? trim((string) $get('serial_number_pumpset')) : null, // ]); - $visibleSerialNumber = $get('serial_number'); + $visibleSerialNumber = $get('serial_number'); - $expectedItemCode = trim((string) $get('item_id')); + $expectedItemCode = trim((string) $get('item_id')); - if ($itemCode != $expectedItemCode) { - $set('pack_slip_motor_error', 'Item code does not match.'); - return; - } + if ($itemCode != $expectedItemCode) { + $set('pack_slip_motor_error', 'Item code does not match.'); - $set('pack_slip_motor_qr', $serialNumber); + return; + } - $set('pack_slip_motor', '1'); + $set('pack_slip_motor_qr', $serialNumber); + $set('pack_slip_motor', '1'); // $isMatch = in_array($serialNumber, $visibleSerialNumbers, true); $isMatch = ($visibleSerialNumber == $serialNumber); - if (!$serialNumber || trim($serialNumber) == '') { + if (! $serialNumber || trim($serialNumber) == '') { $set('pack_slip_motor_error', null); + return; } - if (!$isMatch) - { + if (! $isMatch) { $set('pack_slip_motor_error', 'Serial number does not match.'); $set('pack_slip_motor_qr', null); + return; - } - else { + } else { $set('pack_slip_motor_error', null); $set('pack_slip_motor_qr', $serialNumber); $set('pack_slip_motor', '1'); } - }) - - ->extraAttributes(fn ($get) => [ - 'class' => $get('pack_slip_motor_error') ? 'border-red-500' : '', - ]) - ->hint(fn ($get) => $get('pack_slip_motor_error') ? $get('pack_slip_motor_error') : null) - ->hintColor('danger'), + }) + ->extraAttributes(fn ($get) => [ + 'class' => $get('pack_slip_motor_error') ? 'border-red-500' : '', + ]) + ->hint(fn ($get) => $get('pack_slip_motor_error') ? $get('pack_slip_motor_error') : null) + ->hintColor('danger'), Forms\Components\Hidden::make('pack_slip_pump'), Forms\Components\TextInput::make('pack_slip_pump_qr') ->label('Pack Slip Pump') - ->hidden(fn (callable $get) => !$get('pack_slip_pump_qr_visible')) + ->hidden(fn (callable $get) => ! $get('pack_slip_pump_qr_visible')) ->default('') ->required() ->reactive() @@ -1089,67 +1073,65 @@ class QualityValidationResource extends Resource if (empty($state)) { $set('pack_slip_pump_error', null); + return; } - if (strpos($state, '|') == false) - { - if (preg_match('/^[1-9][a-zA-Z0-9]{8,}$/', $state)) - { + if (strpos($state, '|') == false) { + if (preg_match('/^[1-9][a-zA-Z0-9]{8,}$/', $state)) { $visibleSerialNumber = $get('serial_number'); $serialNumber = $state; - if ($visibleSerialNumber != $serialNumber) - { + if ($visibleSerialNumber != $serialNumber) { $set('pack_slip_pump_error', 'Serial number does not match.'); $set('pack_slip_pump_qr', null); + return; - } - else { + } else { $set('pack_slip_pump_error', null); $set('pack_slip_pump_qr', $serialNumber); $set('pack_slip_pump', '1'); + return; } } if (strlen($state) < 9) { $set('pack_slip_pump_error', 'Serial Number must be at least 9 digits.'); + return; - } - else if (!ctype_alnum($state)) { + } elseif (! ctype_alnum($state)) { $set('pack_slip_pump_error', 'Serial Number must contain alpha-numeric values.'); + return; } - } - else if (strpos($state, '|') == true && !preg_match('/^([a-zA-Z0-9]{6,})\|([1-9][a-zA-Z0-9]{8,})(?:\/[MmPpCc])?\|?$/', $state)) - { + } elseif (strpos($state, '|') == true && ! preg_match('/^([a-zA-Z0-9]{6,})\|([1-9][a-zA-Z0-9]{8,})(?:\/[MmPpCc])?\|?$/', $state)) { $splits = explode('|', $state); $iCode = trim($splits[0]); $sNumber = isset($splits[1]) ? trim($splits[1]) : null; - if (!ctype_alnum($iCode)) { + if (! ctype_alnum($iCode)) { $set('pack_slip_pump_error', 'Item code must contain alpha-numeric values.'); + return; - } - else if (strlen($iCode) < 6) { + } elseif (strlen($iCode) < 6) { $set('pack_slip_pump_error', 'Item code must be at least 6 digits.'); + return; - } - else if (strlen($sNumber) < 9) { + } elseif (strlen($sNumber) < 9) { $set('pack_slip_pump_error', 'Serial Number must be at least 9 digits.'); + return; - } - else if (!ctype_alnum($sNumber)) { + } elseif (! ctype_alnum($sNumber)) { $set('pack_slip_pump_error', 'Serial Number must contain alpha-numeric values.'); + return; } $set('pack_slip_pump_error', 'Scan valid QR code.'); + return; - } - else - { + } else { $set('pack_slip_pump_error', null); } @@ -1168,47 +1150,48 @@ class QualityValidationResource extends Resource // ]); $visibleSerialNumber = $get('serial_number'); - $expectedItemCode = trim((string) $get('item_id')); + $expectedItemCode = trim((string) $get('item_id')); - if ($itemCode != $expectedItemCode) { - $set('pack_slip_pump_error', 'Item code does not match.'); - return; - } + if ($itemCode != $expectedItemCode) { + $set('pack_slip_pump_error', 'Item code does not match.'); - $set('pack_slip_pump_qr', $serialNumber); - $set('pack_slip_pump', '1'); + return; + } + + $set('pack_slip_pump_qr', $serialNumber); + $set('pack_slip_pump', '1'); // $isMatch = in_array($serialNumber, $visibleSerialNumbers, true); $isMatch = ($visibleSerialNumber == $serialNumber); - if (!$serialNumber || trim($serialNumber) == '') { + if (! $serialNumber || trim($serialNumber) == '') { $set('pack_slip_pump_error', null); + return; } - if (!$isMatch) - { + if (! $isMatch) { $set('pack_slip_pump_error', 'Serial number does not match.'); $set('pack_slip_pump_qr', null); + return; - } - else { + } else { $set('pack_slip_pump_error', null); $set('pack_slip_pump_qr', $serialNumber); $set('pack_slip_pump', '1'); } - }) + }) ->extraAttributes(fn ($get) => [ 'class' => $get('pack_slip_pump_error') ? 'border-red-500' : '', ]) - ->hint(fn ($get) => $get('pack_slip_pump_error') ? $get('pack_slip_pump_error') : null) - ->hintColor('danger'), + ->hint(fn ($get) => $get('pack_slip_pump_error') ? $get('pack_slip_pump_error') : null) + ->hintColor('danger'), Forms\Components\Hidden::make('pack_slip_pumpset'), Forms\Components\TextInput::make('pack_slip_pumpset_qr') ->label('Pack Slip PumpSet') - ->hidden(fn (callable $get) => !$get('pack_slip_pumpset_qr_visible')) + ->hidden(fn (callable $get) => ! $get('pack_slip_pumpset_qr_visible')) ->default('') ->required() ->reactive() @@ -1218,67 +1201,65 @@ class QualityValidationResource extends Resource if (empty($state)) { $set('pack_slip_pumpset_error', null); + return; } - if (strpos($state, '|') == false) - { - if (preg_match('/^[1-9][a-zA-Z0-9]{8,}$/', $state)) - { + if (strpos($state, '|') == false) { + if (preg_match('/^[1-9][a-zA-Z0-9]{8,}$/', $state)) { $visibleSerialNumber = $get('serial_number'); $serialNumber = $state; - if ($visibleSerialNumber != $serialNumber) - { + if ($visibleSerialNumber != $serialNumber) { $set('pack_slip_pumpset_error', 'Serial number does not match.'); $set('pack_slip_pumpset_qr', null); + return; - } - else { + } else { $set('pack_slip_pumpset_error', null); $set('pack_slip_pumpset_qr', $serialNumber); $set('pack_slip_pumpset', '1'); + return; } } if (strlen($state) < 9) { $set('pack_slip_pumpset_error', 'Serial Number must be at least 9 digits.'); + return; - } - else if (!ctype_alnum($state)) { + } elseif (! ctype_alnum($state)) { $set('pack_slip_pumpset_error', 'Serial Number must contain alpha-numeric values.'); + return; } - } - else if (strpos($state, '|') == true && !preg_match('/^([a-zA-Z0-9]{6,})\|([1-9][a-zA-Z0-9]{8,})(?:\/[MmPpCc])?\|?$/', $state)) - { + } elseif (strpos($state, '|') == true && ! preg_match('/^([a-zA-Z0-9]{6,})\|([1-9][a-zA-Z0-9]{8,})(?:\/[MmPpCc])?\|?$/', $state)) { $splits = explode('|', $state); $iCode = trim($splits[0]); $sNumber = isset($splits[1]) ? trim($splits[1]) : null; - if (!ctype_alnum($iCode)) { + if (! ctype_alnum($iCode)) { $set('pack_slip_pumpset_error', 'Item code must contain alpha-numeric values.'); + return; - } - else if (strlen($iCode) < 6) { + } elseif (strlen($iCode) < 6) { $set('pack_slip_pumpset_error', 'Item code must be at least 6 digits.'); + return; - } - else if (strlen($sNumber) < 9) { + } elseif (strlen($sNumber) < 9) { $set('pack_slip_pumpset_error', 'Serial Number must be at least 9 digits.'); + return; - } - else if (!ctype_alnum($sNumber)) { + } elseif (! ctype_alnum($sNumber)) { $set('pack_slip_pumpset_error', 'Serial Number must contain alpha-numeric values.'); + return; } $set('pack_slip_pumpset_error', 'Scan valid QR code.'); + return; - } - else - { + } else { $set('pack_slip_pumpset_error', null); } @@ -1298,48 +1279,49 @@ class QualityValidationResource extends Resource $visibleSerialNumber = $get('serial_number'); - $expectedItemCode = trim((string) $get('item_id')); + $expectedItemCode = trim((string) $get('item_id')); - if ($itemCode != $expectedItemCode) { - $set('pack_slip_pumpset_error', 'Item code does not match.'); - return; - } + if ($itemCode != $expectedItemCode) { + $set('pack_slip_pumpset_error', 'Item code does not match.'); - $set('pack_slip_pumpset_qr', $serialNumber); - $set('pack_slip_pumpset', '1'); + return; + } + + $set('pack_slip_pumpset_qr', $serialNumber); + $set('pack_slip_pumpset', '1'); // $isMatch = in_array($serialNumber, $visibleSerialNumbers, true); $isMatch = ($visibleSerialNumber == $serialNumber); - if (!$serialNumber || trim($serialNumber) == '') { + if (! $serialNumber || trim($serialNumber) == '') { $set('pack_slip_pumpset_error', null); + return; } - if (!$isMatch) - { + if (! $isMatch) { $set('pack_slip_pumpset_error', 'Serial number does not match.'); $set('pack_slip_pumpset_qr', null); + return; - } - else { + } else { $set('pack_slip_pumpset_error', null); $set('pack_slip_pumpset_qr', $serialNumber); $set('pack_slip_pumpset', '1'); } - }) + }) ->extraAttributes(fn ($get) => [ 'class' => $get('pack_slip_pumpset_error') ? 'border-red-500' : '', ]) - ->hint(fn ($get) => $get('pack_slip_pumpset_error') ? $get('pack_slip_pumpset_error') : null) - ->hintColor('danger'), + ->hint(fn ($get) => $get('pack_slip_pumpset_error') ? $get('pack_slip_pumpset_error') : null) + ->hintColor('danger'), Forms\Components\Hidden::make('name_plate_motor'), Forms\Components\TextInput::make('name_plate_motor_qr') ->label('Name Plate Motor') - ->hidden(fn (callable $get) => !$get('name_plate_motor_qr_visible')) + ->hidden(fn (callable $get) => ! $get('name_plate_motor_qr_visible')) ->default('') ->required() ->reactive() @@ -1349,67 +1331,65 @@ class QualityValidationResource extends Resource if (empty($state)) { $set('name_plate_motor_error', null); + return; } - if (strpos($state, '|') == false) - { - if (preg_match('/^[1-9][a-zA-Z0-9]{8,}$/', $state)) - { + if (strpos($state, '|') == false) { + if (preg_match('/^[1-9][a-zA-Z0-9]{8,}$/', $state)) { $visibleSerialNumber = $get('serial_number'); $serialNumber = $state; - if ($visibleSerialNumber != $serialNumber) - { + if ($visibleSerialNumber != $serialNumber) { $set('name_plate_motor_error', 'Serial number does not match.'); $set('name_plate_motor_qr', null); + return; - } - else { + } else { $set('name_plate_motor_error', null); $set('name_plate_motor_qr', $serialNumber); $set('name_plate_motor', '1'); + return; } } if (strlen($state) < 9) { $set('name_plate_motor_error', 'Serial Number must be at least 9 digits.'); + return; - } - else if (!ctype_alnum($state)) { + } elseif (! ctype_alnum($state)) { $set('name_plate_motor_error', 'Serial Number must contain alpha-numeric values.'); + return; } - } - else if (strpos($state, '|') == true && !preg_match('/^([a-zA-Z0-9]{6,})\|([1-9][a-zA-Z0-9]{8,})(?:\/[MmPpCc])?\|?$/', $state)) - { + } elseif (strpos($state, '|') == true && ! preg_match('/^([a-zA-Z0-9]{6,})\|([1-9][a-zA-Z0-9]{8,})(?:\/[MmPpCc])?\|?$/', $state)) { $splits = explode('|', $state); $iCode = trim($splits[0]); $sNumber = isset($splits[1]) ? trim($splits[1]) : null; - if (!ctype_alnum($iCode)) { + if (! ctype_alnum($iCode)) { $set('name_plate_motor_error', 'Item code must contain alpha-numeric values.'); + return; - } - else if (strlen($iCode) < 6) { + } elseif (strlen($iCode) < 6) { $set('name_plate_motor_error', 'Item code must be at least 6 digits.'); + return; - } - else if (strlen($sNumber) < 9) { + } elseif (strlen($sNumber) < 9) { $set('name_plate_motor_error', 'Serial Number must be at least 9 digits.'); + return; - } - else if (!ctype_alnum($sNumber)) { + } elseif (! ctype_alnum($sNumber)) { $set('name_plate_motor_error', 'Serial Number must contain alpha-numeric values.'); + return; } $set('name_plate_motor_error', 'Scan valid QR code.'); + return; - } - else - { + } else { $set('name_plate_motor_error', null); } @@ -1428,47 +1408,48 @@ class QualityValidationResource extends Resource // ]); $visibleSerialNumber = $get('serial_number'); - $expectedItemCode = trim((string) $get('item_id')); + $expectedItemCode = trim((string) $get('item_id')); - if ($itemCode != $expectedItemCode) { - $set('name_plate_motor_error', 'Item code does not match.'); - return; - } + if ($itemCode != $expectedItemCode) { + $set('name_plate_motor_error', 'Item code does not match.'); - $set('name_plate_motor_error', $serialNumber); + return; + } + + $set('name_plate_motor_error', $serialNumber); // $isMatch = in_array($serialNumber, $visibleSerialNumbers, true); $isMatch = ($visibleSerialNumber == $serialNumber); - if (!$serialNumber || trim($serialNumber) == '') { + if (! $serialNumber || trim($serialNumber) == '') { $set('name_plate_motor_error', null); + return; } - if (!$isMatch) - { + if (! $isMatch) { $set('name_plate_motor_error', 'Serial number does not match.'); $set('name_plate_motor_qr', null); + return; - } - else { + } else { $set('name_plate_motor_error', null); $set('name_plate_motor_qr', $serialNumber); $set('name_plate_motor', '1'); } - }) + }) ->extraAttributes(fn ($get) => [ 'class' => $get('name_plate_motor_error') ? 'border-red-500' : '', ]) - ->hint(fn ($get) => $get('name_plate_motor_error') ? $get('name_plate_motor_error') : null) - ->hintColor('danger'), + ->hint(fn ($get) => $get('name_plate_motor_error') ? $get('name_plate_motor_error') : null) + ->hintColor('danger'), Forms\Components\Hidden::make('name_plate_pump'), Forms\Components\TextInput::make('name_plate_pump_qr') ->label('Name Plate Pump') - ->hidden(fn (callable $get) => !$get('name_plate_pump_qr_visible')) + ->hidden(fn (callable $get) => ! $get('name_plate_pump_qr_visible')) ->default('') ->required() ->reactive() @@ -1478,67 +1459,65 @@ class QualityValidationResource extends Resource if (empty($state)) { $set('name_plate_pump_error', null); + return; } - if (strpos($state, '|') == false) - { - if (preg_match('/^[1-9][a-zA-Z0-9]{8,}$/', $state)) - { + if (strpos($state, '|') == false) { + if (preg_match('/^[1-9][a-zA-Z0-9]{8,}$/', $state)) { $visibleSerialNumber = $get('serial_number'); $serialNumber = $state; - if ($visibleSerialNumber != $serialNumber) - { + if ($visibleSerialNumber != $serialNumber) { $set('name_plate_pump_error', 'Serial number does not match.'); $set('name_plate_pump_qr', null); + return; - } - else { + } else { $set('name_plate_pump_error', null); $set('name_plate_pump_qr', $serialNumber); $set('name_plate_pump', '1'); + return; } } if (strlen($state) < 9) { $set('name_plate_pump_error', 'Serial Number must be at least 9 digits.'); + return; - } - else if (!ctype_alnum($state)) { + } elseif (! ctype_alnum($state)) { $set('name_plate_pump_error', 'Serial Number must contain alpha-numeric values.'); + return; } - } - else if (strpos($state, '|') == true && !preg_match('/^([a-zA-Z0-9]{6,})\|([1-9][a-zA-Z0-9]{8,})(?:\/[MmPpCc])?\|?$/', $state)) - { + } elseif (strpos($state, '|') == true && ! preg_match('/^([a-zA-Z0-9]{6,})\|([1-9][a-zA-Z0-9]{8,})(?:\/[MmPpCc])?\|?$/', $state)) { $splits = explode('|', $state); $iCode = trim($splits[0]); $sNumber = isset($splits[1]) ? trim($splits[1]) : null; - if (!ctype_alnum($iCode)) { + if (! ctype_alnum($iCode)) { $set('name_plate_pump_error', 'Item code must contain alpha-numeric values.'); + return; - } - else if (strlen($iCode) < 6) { + } elseif (strlen($iCode) < 6) { $set('name_plate_pump_error', 'Item code must be at least 6 digits.'); + return; - } - else if (strlen($sNumber) < 9) { + } elseif (strlen($sNumber) < 9) { $set('name_plate_pump_error', 'Serial Number must be at least 9 digits.'); + return; - } - else if (!ctype_alnum($sNumber)) { + } elseif (! ctype_alnum($sNumber)) { $set('name_plate_pump_error', 'Serial Number must contain alpha-numeric values.'); + return; } $set('name_plate_pump_error', 'Scan valid QR code.'); + return; - } - else - { + } else { $set('name_plate_pump_error', null); } @@ -1557,47 +1536,48 @@ class QualityValidationResource extends Resource // ]); $visibleSerialNumber = $get('serial_number'); - $expectedItemCode = trim((string) $get('item_id')); + $expectedItemCode = trim((string) $get('item_id')); - if ($itemCode != $expectedItemCode) { - $set('name_plate_pump_error', 'Item code does not match.'); - return; - } + if ($itemCode != $expectedItemCode) { + $set('name_plate_pump_error', 'Item code does not match.'); - $set('name_plate_pump_error', $serialNumber); + return; + } + + $set('name_plate_pump_error', $serialNumber); // $isMatch = in_array($serialNumber, $visibleSerialNumbers, true); $isMatch = ($visibleSerialNumber == $serialNumber); - if (!$serialNumber || trim($serialNumber) == '') { + if (! $serialNumber || trim($serialNumber) == '') { $set('name_plate_pump_error', null); + return; } - if (!$isMatch) - { + if (! $isMatch) { $set('name_plate_pump_error', 'Serial number does not match.'); $set('name_plate_pump_qr', null); + return; - } - else { + } else { $set('name_plate_pump_error', null); $set('name_plate_pump_qr', $serialNumber); $set('name_plate_pump', '1'); } - }) + }) ->extraAttributes(fn ($get) => [ 'class' => $get('name_plate_pump_error') ? 'border-red-500' : '', ]) - ->hint(fn ($get) => $get('name_plate_pump_error') ? $get('name_plate_pump_error') : null) - ->hintColor('danger'), + ->hint(fn ($get) => $get('name_plate_pump_error') ? $get('name_plate_pump_error') : null) + ->hintColor('danger'), Forms\Components\Hidden::make('name_plate_pumpset'), Forms\Components\TextInput::make('name_plate_pumpset_qr') ->label('Name Plate PumpSet') - ->hidden(fn (callable $get) => !$get('name_plate_pumpset_qr_visible')) + ->hidden(fn (callable $get) => ! $get('name_plate_pumpset_qr_visible')) ->default('') ->required() ->reactive() @@ -1607,67 +1587,65 @@ class QualityValidationResource extends Resource if (empty($state)) { $set('name_plate_pumpset_error', null); + return; } - if (strpos($state, '|') == false) - { - if (preg_match('/^[1-9][a-zA-Z0-9]{8,}$/', $state)) - { + if (strpos($state, '|') == false) { + if (preg_match('/^[1-9][a-zA-Z0-9]{8,}$/', $state)) { $visibleSerialNumber = $get('serial_number'); $serialNumber = $state; - if ($visibleSerialNumber != $serialNumber) - { + if ($visibleSerialNumber != $serialNumber) { $set('name_plate_pumpset_error', 'Serial number does not match.'); $set('name_plate_pumpset_qr', null); + return; - } - else { + } else { $set('name_plate_pumpset_error', null); $set('name_plate_pumpset_qr', $serialNumber); $set('name_plate_pumpset', '1'); + return; } } if (strlen($state) < 9) { $set('name_plate_pumpset_error', 'Serial Number must be at least 9 digits.'); + return; - } - else if (!ctype_alnum($state)) { + } elseif (! ctype_alnum($state)) { $set('name_plate_pumpset_error', 'Serial Number must contain alpha-numeric values.'); + return; } - } - else if (strpos($state, '|') == true && !preg_match('/^([a-zA-Z0-9]{6,})\|([1-9][a-zA-Z0-9]{8,})(?:\/[MmPpCc])?\|?$/', $state)) - { + } elseif (strpos($state, '|') == true && ! preg_match('/^([a-zA-Z0-9]{6,})\|([1-9][a-zA-Z0-9]{8,})(?:\/[MmPpCc])?\|?$/', $state)) { $splits = explode('|', $state); $iCode = trim($splits[0]); $sNumber = isset($splits[1]) ? trim($splits[1]) : null; - if (!ctype_alnum($iCode)) { + if (! ctype_alnum($iCode)) { $set('name_plate_pumpset_error', 'Item code must contain alpha-numeric values.'); + return; - } - else if (strlen($iCode) < 6) { + } elseif (strlen($iCode) < 6) { $set('name_plate_pumpset_error', 'Item code must be at least 6 digits.'); + return; - } - else if (strlen($sNumber) < 9) { + } elseif (strlen($sNumber) < 9) { $set('name_plate_pumpset_error', 'Serial Number must be at least 9 digits.'); + return; - } - else if (!ctype_alnum($sNumber)) { + } elseif (! ctype_alnum($sNumber)) { $set('name_plate_pumpset_error', 'Serial Number must contain alpha-numeric values.'); + return; } $set('name_plate_pumpset_error', 'Scan valid QR code.'); + return; - } - else - { + } else { $set('name_plate_pumpset_error', null); } @@ -1686,36 +1664,37 @@ class QualityValidationResource extends Resource // ]); $visibleSerialNumber = $get('serial_number'); - $expectedItemCode = trim((string) $get('item_id')); + $expectedItemCode = trim((string) $get('item_id')); - if ($itemCode != $expectedItemCode) { - $set('name_plate_pumpset_error', 'Item code does not match.'); - return; - } + if ($itemCode != $expectedItemCode) { + $set('name_plate_pumpset_error', 'Item code does not match.'); - $set('name_plate_pumpset_error', $serialNumber); + return; + } + + $set('name_plate_pumpset_error', $serialNumber); // $isMatch = in_array($serialNumber, $visibleSerialNumbers, true); $isMatch = ($visibleSerialNumber == $serialNumber); - if (!$serialNumber || trim($serialNumber) == '') { + if (! $serialNumber || trim($serialNumber) == '') { $set('name_plate_pumpset_error', null); + return; } - if (!$isMatch) - { + if (! $isMatch) { $set('name_plate_pumpset_error', 'Serial number does not match.'); $set('name_plate_pumpset_qr', null); + return; - } - else { + } else { $set('name_plate_pumpset_error', null); $set('name_plate_pumpset_qr', $serialNumber); $set('name_plate_pumpset', '1'); } - }) + }) ->extraAttributes(fn ($get) => [ 'class' => $get('name_plate_pumpset_error') ? 'border-red-500' : '', ]) @@ -1726,7 +1705,7 @@ class QualityValidationResource extends Resource Forms\Components\TextInput::make('tube_sticker_motor_qr') ->label('Tube Sticker Motor') - ->hidden(fn (callable $get) => !$get('tube_sticker_motor_qr_visible')) + ->hidden(fn (callable $get) => ! $get('tube_sticker_motor_qr_visible')) ->default('') ->required() ->reactive() @@ -1737,7 +1716,7 @@ class QualityValidationResource extends Resource // $mPorder = $get('production_order'); // $mPlantId = $get('plant_id'); - //$plant = Plant::find($mPlantId); + // $plant = Plant::find($mPlantId); // $plantCodePart4 = $plant?->code; // $mlineId = $get('line_id'); @@ -1747,67 +1726,65 @@ class QualityValidationResource extends Resource if (empty($state)) { $set('tube_sticker_motor_error', null); + return; } - if (strpos($state, '|') == false) - { - if (preg_match('/^[1-9][a-zA-Z0-9]{8,}$/', $state)) - { + if (strpos($state, '|') == false) { + if (preg_match('/^[1-9][a-zA-Z0-9]{8,}$/', $state)) { $visibleSerialNumber = $get('serial_number'); $serialNumber = $state; - if ($visibleSerialNumber != $serialNumber) - { + if ($visibleSerialNumber != $serialNumber) { $set('tube_sticker_motor_error', 'Serial number does not match.'); $set('tube_sticker_motor_qr', null); + return; - } - else { + } else { $set('tube_sticker_motor_error', null); $set('tube_sticker_motor_qr', $serialNumber); $set('tube_sticker_motor', '1'); + return; } } if (strlen($state) < 9) { $set('tube_sticker_motor_error', 'Serial Number must be at least 9 digits.'); + return; - } - else if (!ctype_alnum($state)) { + } elseif (! ctype_alnum($state)) { $set('tube_sticker_motor_error', 'Serial Number must contain alpha-numeric values.'); + return; } - } - else if (strpos($state, '|') == true && !preg_match('/^([a-zA-Z0-9]{6,})\|([1-9][a-zA-Z0-9]{8,})(?:\/[MmPpCc])?\|?$/', $state)) - { + } elseif (strpos($state, '|') == true && ! preg_match('/^([a-zA-Z0-9]{6,})\|([1-9][a-zA-Z0-9]{8,})(?:\/[MmPpCc])?\|?$/', $state)) { $splits = explode('|', $state); $iCode = trim($splits[0]); $sNumber = isset($splits[1]) ? trim($splits[1]) : null; - if (!ctype_alnum($iCode)) { + if (! ctype_alnum($iCode)) { $set('tube_sticker_motor_error', 'Item code must contain alpha-numeric values.'); + return; - } - else if (strlen($iCode) < 6) { + } elseif (strlen($iCode) < 6) { $set('tube_sticker_motor_error', 'Item code must be at least 6 digits.'); + return; - } - else if (strlen($sNumber) < 9) { + } elseif (strlen($sNumber) < 9) { $set('tube_sticker_motor_error', 'Serial Number must be at least 9 digits.'); + return; - } - else if (!ctype_alnum($sNumber)) { + } elseif (! ctype_alnum($sNumber)) { $set('tube_sticker_motor_error', 'Serial Number must contain alpha-numeric values.'); + return; } $set('tube_sticker_motor_error', 'Scan valid QR code.'); + return; - } - else - { + } else { $set('tube_sticker_motor_error', null); } @@ -1826,25 +1803,26 @@ class QualityValidationResource extends Resource // ]); $visibleSerialNumber = $get('serial_number'); - $expectedItemCode = trim((string) $get('item_id')); + $expectedItemCode = trim((string) $get('item_id')); - if ($itemCode != $expectedItemCode) { - $set('tube_sticker_motor_error', 'Item code does not match.'); - return; - } + if ($itemCode != $expectedItemCode) { + $set('tube_sticker_motor_error', 'Item code does not match.'); - $set('tube_sticker_motor_error', $serialNumber); + return; + } + + $set('tube_sticker_motor_error', $serialNumber); // $isMatch = in_array($serialNumber, $visibleSerialNumbers, true); $isMatch = ($visibleSerialNumber == $serialNumber); - if (!$serialNumber || trim($serialNumber) == '') { + if (! $serialNumber || trim($serialNumber) == '') { $set('tube_sticker_motor_error', null); + return; } - if (!$isMatch) - { + if (! $isMatch) { $set('tube_sticker_motor_error', 'Serial number does not match.'); // $mailData = \App\Filament\Resources\QualityValidationResource::getMailData($mPlantId); @@ -1865,26 +1843,26 @@ class QualityValidationResource extends Resource // \Log::warning("No recipients found for plant {$mPlantName}, module Serial, rule invalid_serial."); // } $set('tube_sticker_motor_qr', null); + return; - } - else { + } else { $set('tube_sticker_motor_error', null); $set('tube_sticker_motor_qr', $serialNumber); $set('tube_sticker_motor', '1'); } - }) + }) ->extraAttributes(fn ($get) => [ 'class' => $get('tube_sticker_motor_error') ? 'border-red-500' : '', ]) - ->hint(fn ($get) => $get('tube_sticker_motor_error') ? $get('tube_sticker_motor_error') : null) - ->hintColor('danger'), + ->hint(fn ($get) => $get('tube_sticker_motor_error') ? $get('tube_sticker_motor_error') : null) + ->hintColor('danger'), - Forms\Components\Hidden::make('tube_sticker_pump'), + Forms\Components\Hidden::make('tube_sticker_pump'), - Forms\Components\TextInput::make('tube_sticker_pump_qr') + Forms\Components\TextInput::make('tube_sticker_pump_qr') ->label('Tube Sticker Pump') - ->hidden(fn (callable $get) => !$get('tube_sticker_pump_qr_visible')) + ->hidden(fn (callable $get) => ! $get('tube_sticker_pump_qr_visible')) ->default('') ->required() ->reactive() @@ -1912,71 +1890,69 @@ class QualityValidationResource extends Resource // $mPlantName = $mailData['plant_name']; // $emails = $mailData['emails']; - //$mUserName = Filament::auth()->user()->name; + // $mUserName = Filament::auth()->user()->name; if (empty($state)) { $set('tube_sticker_pump_error', null); + return; } - if (strpos($state, '|') == false) - { - if (preg_match('/^[1-9][a-zA-Z0-9]{8,}$/', $state)) - { + if (strpos($state, '|') == false) { + if (preg_match('/^[1-9][a-zA-Z0-9]{8,}$/', $state)) { $visibleSerialNumber = $get('serial_number'); $serialNumber = $state; - if ($visibleSerialNumber != $serialNumber) - { + if ($visibleSerialNumber != $serialNumber) { $set('tube_sticker_pump_error', 'Serial number does not match.'); $set('tube_sticker_pump_qr', null); + return; - } - else { + } else { $set('tube_sticker_pump_error', null); $set('tube_sticker_pump_qr', $serialNumber); $set('tube_sticker_pump', '1'); + return; } } if (strlen($state) < 9) { $set('tube_sticker_pump_error', 'Serial Number must be at least 9 digits.'); + return; - } - else if (!ctype_alnum($state)) { + } elseif (! ctype_alnum($state)) { $set('tube_sticker_pump_error', 'Serial Number must contain alpha-numeric values.'); + return; } - } - else if (strpos($state, '|') == true && !preg_match('/^([a-zA-Z0-9]{6,})\|([1-9][a-zA-Z0-9]{8,})(?:\/[MmPpCc])?\|?$/', $state)) - { + } elseif (strpos($state, '|') == true && ! preg_match('/^([a-zA-Z0-9]{6,})\|([1-9][a-zA-Z0-9]{8,})(?:\/[MmPpCc])?\|?$/', $state)) { $splits = explode('|', $state); $iCode = trim($splits[0]); $sNumber = isset($splits[1]) ? trim($splits[1]) : null; - if (!ctype_alnum($iCode)) { + if (! ctype_alnum($iCode)) { $set('tube_sticker_pump_error', 'Item code must contain alpha-numeric values.'); + return; - } - else if (strlen($iCode) < 6) { + } elseif (strlen($iCode) < 6) { $set('tube_sticker_pump_error', 'Item code must be at least 6 digits.'); + return; - } - else if (strlen($sNumber) < 9) { + } elseif (strlen($sNumber) < 9) { $set('tube_sticker_pump_error', 'Serial Number must be at least 9 digits.'); + return; - } - else if (!ctype_alnum($sNumber)) { + } elseif (! ctype_alnum($sNumber)) { $set('tube_sticker_pump_error', 'Serial Number must contain alpha-numeric values.'); + return; } $set('tube_sticker_pump_error', 'Scan valid QR code.'); + return; - } - else - { + } else { $set('tube_sticker_pump_error', null); } @@ -1999,6 +1975,7 @@ class QualityValidationResource extends Resource if ($itemCode != $expectedItemCode) { $set('tube_sticker_pump_error', 'Item code does not match.'); + return; } @@ -2007,13 +1984,13 @@ class QualityValidationResource extends Resource // $isMatch = in_array($serialNumber, $visibleSerialNumbers, true); $isMatch = ($visibleSerialNumber == $serialNumber); - if (!$serialNumber || trim($serialNumber) == '') { + if (! $serialNumber || trim($serialNumber) == '') { $set('tube_sticker_pump_error', null); + return; } - if (!$isMatch) - { + if (! $isMatch) { $set('tube_sticker_pump_error', 'Serial number does not match.'); $set('tube_sticker_pump_qr', null); // $user = User::where('name', $mUserName)->first(); @@ -2022,7 +1999,6 @@ class QualityValidationResource extends Resource // $user->notify(new StatusUpdated($state)); // } - // $currentUser = Filament::auth()->user(); // if ($currentUser) { @@ -2032,28 +2008,25 @@ class QualityValidationResource extends Resource // $livewire->dispatch('refreshFilamentNotifications'); // } + // Notification::make() + // ->title('Status Updated') + // ->body("Serial number scanned: $state") + // ->danger() + // ->sendToDatabase($currentUser); - // Notification::make() - // ->title('Status Updated') - // ->body("Serial number scanned: $state") - // ->danger() - // ->sendToDatabase($currentUser); + // $user->notify(new StatusUpdated($state)); - //$user->notify(new StatusUpdated($state)); + // Notification::send($user, new StatusUpdated($state)); - //Notification::send($user, new StatusUpdated($state)); - - - //dd($user); + // dd($user); // $user->notify(new StatusUpdated($state)); // Inside a Filament page or resource - //$this->notify('success', "Serial number scanned: $state"); + // $this->notify('success', "Serial number scanned: $state"); // dispatch(new SendInvalidQualityMailJob( // $state, $mPorder, $mPlantId, $mlineId, $mUserName, 'InvalidTubeStickerPump' // ))->afterResponse(); - // $mailData = \App\Filament\Resources\QualityValidationResource::getMailData($mPlantId); // $mPlantName = $mailData['plant_name']; @@ -2073,25 +2046,24 @@ class QualityValidationResource extends Resource // } return; - } - else { + } else { $set('tube_sticker_pump_error', null); $set('tube_sticker_pump_qr', $serialNumber); $set('tube_sticker_pump', '1'); } - }) + }) ->extraAttributes(fn ($get) => [ 'class' => $get('tube_sticker_pump_error') ? 'border-red-500' : '', ]) - ->hint(fn ($get) => $get('tube_sticker_pump_error') ? $get('tube_sticker_pump_error') : null) - ->hintColor('danger'), + ->hint(fn ($get) => $get('tube_sticker_pump_error') ? $get('tube_sticker_pump_error') : null) + ->hintColor('danger'), Forms\Components\Hidden::make('tube_sticker_pumpset'), Forms\Components\TextInput::make('tube_sticker_pumpset_qr') ->label('Tube Sticker PumpSet') - ->hidden(fn (callable $get) => !$get('tube_sticker_pumpset_qr_visible')) + ->hidden(fn (callable $get) => ! $get('tube_sticker_pumpset_qr_visible')) ->default('') ->required() ->reactive() @@ -2102,7 +2074,7 @@ class QualityValidationResource extends Resource $mPorder = $get('production_order'); $mPlantId = $get('plant_id'); - //$plant = Plant::find($mPlantId); + // $plant = Plant::find($mPlantId); // $plantCodePart4 = $plant?->code; $mlineId = $get('line_id'); @@ -2112,67 +2084,65 @@ class QualityValidationResource extends Resource if (empty($state)) { $set('tube_sticker_pumpset_error', null); + return; } - if (strpos($state, '|') == false) - { - if (preg_match('/^[1-9][a-zA-Z0-9]{8,}$/', $state)) - { + if (strpos($state, '|') == false) { + if (preg_match('/^[1-9][a-zA-Z0-9]{8,}$/', $state)) { $visibleSerialNumber = $get('serial_number'); $serialNumber = $state; - if ($visibleSerialNumber != $serialNumber) - { + if ($visibleSerialNumber != $serialNumber) { $set('tube_sticker_pumpset_error', 'Serial number does not match.'); $set('tube_sticker_pumpset_qr', null); + return; - } - else { + } else { $set('tube_sticker_pumpset_error', null); $set('tube_sticker_pumpset_qr', $serialNumber); $set('tube_sticker_pumpset', '1'); + return; } } if (strlen($state) < 9) { $set('tube_sticker_pumpset_error', 'Serial Number must be at least 9 digits.'); + return; - } - else if (!ctype_alnum($state)) { + } elseif (! ctype_alnum($state)) { $set('tube_sticker_pumpset_error', 'Serial Number must contain alpha-numeric values.'); + return; } - } - else if (strpos($state, '|') == true && !preg_match('/^([a-zA-Z0-9]{6,})\|([1-9][a-zA-Z0-9]{8,})(?:\/[MmPpCc])?\|?$/', $state)) - { + } elseif (strpos($state, '|') == true && ! preg_match('/^([a-zA-Z0-9]{6,})\|([1-9][a-zA-Z0-9]{8,})(?:\/[MmPpCc])?\|?$/', $state)) { $splits = explode('|', $state); $iCode = trim($splits[0]); $sNumber = isset($splits[1]) ? trim($splits[1]) : null; - if (!ctype_alnum($iCode)) { + if (! ctype_alnum($iCode)) { $set('tube_sticker_pumpset_error', 'Item code must contain alpha-numeric values.'); + return; - } - else if (strlen($iCode) < 6) { + } elseif (strlen($iCode) < 6) { $set('tube_sticker_pumpset_error', 'Item code must be at least 6 digits.'); + return; - } - else if (strlen($sNumber) < 9) { + } elseif (strlen($sNumber) < 9) { $set('tube_sticker_pumpset_error', 'Serial Number must be at least 9 digits.'); + return; - } - else if (!ctype_alnum($sNumber)) { + } elseif (! ctype_alnum($sNumber)) { $set('tube_sticker_pumpset_error', 'Serial Number must contain alpha-numeric values.'); + return; } $set('tube_sticker_pumpset_error', 'Scan valid QR code.'); + return; - } - else - { + } else { $set('tube_sticker_pumpset_error', null); } @@ -2181,8 +2151,8 @@ class QualityValidationResource extends Resource $itemCode = trim($parts[0]); $serialNumber = trim($parts[1]); - // $serialNumber = preg_replace('/\/[MmPpCc]$/', '', $serialNumber); // Remove - $serialNumber = preg_replace('/\/[MmPpCc]$/', '', $serialNumber); // Remove + // $serialNumber = preg_replace('/\/[MmPpCc]$/', '', $serialNumber); // Remove + $serialNumber = preg_replace('/\/[MmPpCc]$/', '', $serialNumber); // Remove // Retrieve visible serial numbers // $visibleSerialNumbers = array_filter([ // $get('serial_number_motor_qr_visible') ? trim((string) $get('serial_number_motor')) : null, @@ -2191,27 +2161,28 @@ class QualityValidationResource extends Resource // ]); $visibleSerialNumber = $get('serial_number'); - //dd($parts); + // dd($parts); - $expectedItemCode = trim((string) $get('item_id')); + $expectedItemCode = trim((string) $get('item_id')); - if ($itemCode != $expectedItemCode) { - $set('tube_sticker_pumpset_error', 'Item code does not match.'); - return; - } + if ($itemCode != $expectedItemCode) { + $set('tube_sticker_pumpset_error', 'Item code does not match.'); - $set('tube_sticker_pumpset_error', $serialNumber); + return; + } + + $set('tube_sticker_pumpset_error', $serialNumber); // $isMatch = in_array($serialNumber, $visibleSerialNumbers, true); $isMatch = ($visibleSerialNumber == $serialNumber); - if (!$serialNumber || trim($serialNumber) == '') { + if (! $serialNumber || trim($serialNumber) == '') { $set('tube_sticker_pumpset_error', null); + return; } - if (!$isMatch) - { + if (! $isMatch) { $set('tube_sticker_pumpset_error', 'Serial number does not match.'); // $mailData = \App\Filament\Resources\QualityValidationResource::getMailData($mPlantId); @@ -2231,26 +2202,26 @@ class QualityValidationResource extends Resource // \Log::warning("No recipients found for plant {$mPlantName}, module Serial, rule invalid_serial."); // } $set('tube_sticker_pumpset_qr', null); + return; - } - else { + } else { $set('tube_sticker_pumpset_error', null); $set('tube_sticker_pumpset_qr', $serialNumber); $set('tube_sticker_pumpset', '1'); } - }) + }) ->extraAttributes(fn ($get) => [ 'class' => $get('tube_sticker_pumpset_error') ? 'border-red-500' : '', ]) - ->hint(fn ($get) => $get('tube_sticker_pumpset_error') ? $get('tube_sticker_pumpset_error') : null) - ->hintColor('danger'), + ->hint(fn ($get) => $get('tube_sticker_pumpset_error') ? $get('tube_sticker_pumpset_error') : null) + ->hintColor('danger'), Forms\Components\Hidden::make('warranty_card'), Forms\Components\TextInput::make('warranty_card_qr') ->label('Warranty Card') - ->hidden(fn (callable $get) => !$get('warranty_card_qr_visible')) + ->hidden(fn (callable $get) => ! $get('warranty_card_qr_visible')) ->default('') ->required() ->reactive() @@ -2260,67 +2231,65 @@ class QualityValidationResource extends Resource if (empty($state)) { $set('warranty_card_error', null); + return; } - if (strpos($state, '|') == false) - { - if (preg_match('/^[1-9][a-zA-Z0-9]{8,}$/', $state)) - { + if (strpos($state, '|') == false) { + if (preg_match('/^[1-9][a-zA-Z0-9]{8,}$/', $state)) { $visibleSerialNumber = $get('serial_number'); $serialNumber = $state; - if ($visibleSerialNumber != $serialNumber) - { + if ($visibleSerialNumber != $serialNumber) { $set('warranty_card_error', 'Serial number does not match.'); $set('warranty_card_qr', null); + return; - } - else { + } else { $set('warranty_card_error', null); $set('warranty_card_qr', $serialNumber); $set('warranty_card', '1'); + return; } } if (strlen($state) < 9) { $set('warranty_card_error', 'Serial Number must be at least 9 digits.'); + return; - } - else if (!ctype_alnum($state)) { + } elseif (! ctype_alnum($state)) { $set('warranty_card_error', 'Serial Number must contain alpha-numeric values.'); + return; } - } - else if (strpos($state, '|') == true && !preg_match('/^([a-zA-Z0-9]{6,})\|([1-9][a-zA-Z0-9]{8,})(?:\/[MmPpCc])?\|?$/', $state)) - { + } elseif (strpos($state, '|') == true && ! preg_match('/^([a-zA-Z0-9]{6,})\|([1-9][a-zA-Z0-9]{8,})(?:\/[MmPpCc])?\|?$/', $state)) { $splits = explode('|', $state); $iCode = trim($splits[0]); $sNumber = isset($splits[1]) ? trim($splits[1]) : null; - if (!ctype_alnum($iCode)) { + if (! ctype_alnum($iCode)) { $set('warranty_card_error', 'Item code must contain alpha-numeric values.'); + return; - } - else if (strlen($iCode) < 6) { + } elseif (strlen($iCode) < 6) { $set('warranty_card_error', 'Item code must be at least 6 digits.'); + return; - } - else if (strlen($sNumber) < 9) { + } elseif (strlen($sNumber) < 9) { $set('warranty_card_error', 'Serial Number must be at least 9 digits.'); + return; - } - else if (!ctype_alnum($sNumber)) { + } elseif (! ctype_alnum($sNumber)) { $set('warranty_card_error', 'Serial Number must contain alpha-numeric values.'); + return; } $set('warranty_card_error', 'Scan valid QR code.'); + return; - } - else - { + } else { $set('warranty_card_error', null); } @@ -2340,44 +2309,45 @@ class QualityValidationResource extends Resource $visibleSerialNumber = $get('serial_number'); - $expectedItemCode = trim((string) $get('item_id')); + $expectedItemCode = trim((string) $get('item_id')); - if ($itemCode != $expectedItemCode) { - $set('warranty_card_error', 'Item code does not match.'); - return; - } + if ($itemCode != $expectedItemCode) { + $set('warranty_card_error', 'Item code does not match.'); - $set('warranty_card_error', $serialNumber); + return; + } + + $set('warranty_card_error', $serialNumber); // $isMatch = in_array($serialNumber, $visibleSerialNumbers, true); $isMatch = ($visibleSerialNumber == $serialNumber); - if (!$serialNumber || trim($serialNumber) == '') { + if (! $serialNumber || trim($serialNumber) == '') { $set('warranty_card_error', null); + return; } - if (!$isMatch) - { + if (! $isMatch) { $set('warranty_card_error', 'Serial number does not match.'); $set('warranty_card_qr', null); + return; - } - else { + } else { $set('warranty_card_error', null); $set('warranty_card_qr', $serialNumber); $set('warranty_card', '1'); } - }) + }) ->extraAttributes(fn ($get) => [ 'class' => $get('warranty_card_error') ? 'border-red-500' : '', ]) - ->hint(fn ($get) => $get('warranty_card_error') ? $get('warranty_card_error') : null) - ->hintColor('danger'), + ->hint(fn ($get) => $get('warranty_card_error') ? $get('warranty_card_error') : null) + ->hintColor('danger'), Forms\Components\TextInput::make('part_validation1') - ->hidden(fn (callable $get) => !$get('part_validation1_visible')) + ->hidden(fn (callable $get) => ! $get('part_validation1_visible')) ->default('') ->reactive() ->required() @@ -2395,14 +2365,13 @@ class QualityValidationResource extends Resource $mLine = Line::find($mlineId); $mLinePart = $mLine?->name; - $stickerMasterId = $get('sticker_master_id'); - if (!$stickerMasterId) { + if (! $stickerMasterId) { return; } $stickerMaster = StickerMaster::find($stickerMasterId); - if (!$stickerMaster) { + if (! $stickerMaster) { return; } @@ -2410,18 +2379,16 @@ class QualityValidationResource extends Resource if ($state == null || trim($state) == '') { $set('part_validation1_error', null); + return; } - if ($state == $expectedValue) - { + if ($state == $expectedValue) { $set('part_validation1_error', null); - } - else - { - $set('part_validation1_error', "Invalid input for part validation 1."); + } else { + $set('part_validation1_error', 'Invalid input for part validation 1.'); - //.Mail + // .Mail $mailData = \App\Filament\Resources\QualityValidationResource::getMailData($mPlantId); @@ -2429,20 +2396,17 @@ class QualityValidationResource extends Resource $emails = $mailData['emails']; $mUserName = Filament::auth()->user()->name; - if (!empty($emails)) - { - //Mail::to($emails)->send(new InvalidSerialMail($serNo, $invoiceNumber, $mPlantName, $mInvoiceType)); + if (! empty($emails)) { + // Mail::to($emails)->send(new InvalidSerialMail($serNo, $invoiceNumber, $mPlantName, $mInvoiceType)); Mail::to($emails)->send( new InvalidQualityMail($state, $mPorder, $mPlantName, $mLinePart, $mUserName, 'InvalidPartNumber') ); - } - else - { + } else { \Log::warning("No recipients found for plant {$mPlantName}, module Serial, rule invalid_serial."); } $set('part_validation1', null); - $fileName = $expectedValue . ".png"; // or .jpg based on your file + $fileName = $expectedValue.'.png'; // or .jpg based on your file $fullPath = storage_path("app/private/uploads/PartValidation/{$fileName}"); // dd($fullPath); @@ -2455,13 +2419,14 @@ class QualityValidationResource extends Resource if (file_exists($fullPath)) { $imageUrl = route('part.validation.image', [ // 'plant' => $plantCodePart1, - 'filename' => $fileName + 'filename' => $fileName, ]); } else { - $imageUrl = asset("images/not_found.png"); + $imageUrl = asset('images/not_found.png'); } $set('part_validation1_error_image', $imageUrl); + return; } }) @@ -2473,14 +2438,13 @@ class QualityValidationResource extends Resource Forms\Components\Hidden::make('part_validation1_error_image'), - Forms\Components\View::make('components.part-validation1-error-icon') ->visible(fn ($get) => $get('part_validation1_error') != null) ->statePath('part_validation1_error_image') ->reactive(), Forms\Components\TextInput::make('part_validation2') - ->hidden(fn (callable $get) => !$get('part_validation2_visible')) + ->hidden(fn (callable $get) => ! $get('part_validation2_visible')) ->default('') ->required() ->reactive() @@ -2498,12 +2462,12 @@ class QualityValidationResource extends Resource $mLinePart = $mLine?->name; $stickerMasterId = $get('sticker_master_id'); - if (!$stickerMasterId) { + if (! $stickerMasterId) { return; } $stickerMaster = StickerMaster::find($stickerMasterId); - if (!$stickerMaster) { + if (! $stickerMaster) { return; } @@ -2511,36 +2475,31 @@ class QualityValidationResource extends Resource if ($state == null || trim($state) == '') { $set('part_validation2_error', null); + return; } - if ($state == $expectedValue) - { + if ($state == $expectedValue) { $set('part_validation2_error', null); - } - else - { - $set('part_validation2_error', "Invalid input for part validation 2."); + } else { + $set('part_validation2_error', 'Invalid input for part validation 2.'); $mailData = \App\Filament\Resources\QualityValidationResource::getMailData($mPlantId); $mPlantName = $mailData['plant_name']; $emails = $mailData['emails']; $mUserName = Filament::auth()->user()->name; - if (!empty($emails)) - { - //Mail::to($emails)->send(new InvalidSerialMail($serNo, $invoiceNumber, $mPlantName, $mInvoiceType)); + if (! empty($emails)) { + // Mail::to($emails)->send(new InvalidSerialMail($serNo, $invoiceNumber, $mPlantName, $mInvoiceType)); Mail::to($emails)->send( - new InvalidQualityMail($state, $mPorder, $mPlantName,$mLinePart, $mUserName, 'InvalidPartNumber2') + new InvalidQualityMail($state, $mPorder, $mPlantName, $mLinePart, $mUserName, 'InvalidPartNumber2') ); - } - else - { + } else { \Log::warning("No recipients found for plant {$mPlantName}, module Serial, rule invalid_serial."); } $set('part_validation2', null); - $fileName = $expectedValue . ".png"; // or .jpg based on your file + $fileName = $expectedValue.'.png'; // or .jpg based on your file $fullPath = storage_path("app/private/uploads/PartValidation/{$plantCodePart2}/{$fileName}"); // if (!file_exists($fullPath)) { @@ -2555,10 +2514,11 @@ class QualityValidationResource extends Resource // Generate URL through custom route $imageUrl = route('part.validation.image', [ 'plant' => $plantCodePart2, - 'filename' => $fileName + 'filename' => $fileName, ]); $set('part_validation2_error_image', $imageUrl); + return; } }) @@ -2578,14 +2538,14 @@ class QualityValidationResource extends Resource ->reactive(), Forms\Components\TextInput::make('part_validation3') - ->hidden(fn (callable $get) => !$get('part_validation3_visible')) + ->hidden(fn (callable $get) => ! $get('part_validation3_visible')) ->default('') ->required() ->reactive() ->afterStateUpdated(function (callable $set, callable $get, ?string $state) { $stickerMasterId = $get('sticker_master_id'); - $mPorder = $get('production_order'); + $mPorder = $get('production_order'); $mPlantId = $get('plant_id'); $plant = Plant::find($mPlantId); @@ -2596,51 +2556,44 @@ class QualityValidationResource extends Resource $mLine = Line::find($mlineId); $mLinePart = $mLine?->name; - - if (!$stickerMasterId) { + if (! $stickerMasterId) { return; } $stickerMaster = StickerMaster::find($stickerMasterId); - if (!$stickerMaster) - { + if (! $stickerMaster) { return; } if ($state == null || trim($state) == '') { $set('part_validation3_error', null); + return; } $expectedValue = $stickerMaster->part_validation3; - if ($state == $expectedValue) - { + if ($state == $expectedValue) { $set('part_validation3_error', null); - } - else - { - $set('part_validation3_error', "Invalid input for part validation 3."); + } else { + $set('part_validation3_error', 'Invalid input for part validation 3.'); $mailData = \App\Filament\Resources\QualityValidationResource::getMailData($mPlantId); $mPlantName = $mailData['plant_name']; $emails = $mailData['emails']; $mUserName = Filament::auth()->user()->name; - if (!empty($emails)) - { - //Mail::to($emails)->send(new InvalidSerialMail($serNo, $invoiceNumber, $mPlantName, $mInvoiceType)); + if (! empty($emails)) { + // Mail::to($emails)->send(new InvalidSerialMail($serNo, $invoiceNumber, $mPlantName, $mInvoiceType)); Mail::to($emails)->send( - new InvalidQualityMail($state, $mPorder, $mPlantName,$mLinePart, $mUserName, 'InvalidPartNumber3') + new InvalidQualityMail($state, $mPorder, $mPlantName, $mLinePart, $mUserName, 'InvalidPartNumber3') ); - } - else - { + } else { \Log::warning("No recipients found for plant {$mPlantName}, module Serial, rule invalid_serial."); } $set('part_validation3', null); - $fileName = $expectedValue . ".png"; // or .jpg based on your file - //$fullPath = storage_path("app/private/uploads/PartValidation/{$plantCodePart3}/{$fileName}"); + $fileName = $expectedValue.'.png'; // or .jpg based on your file + // $fullPath = storage_path("app/private/uploads/PartValidation/{$plantCodePart3}/{$fileName}"); // if (!file_exists($fullPath)) { // Notification::make() @@ -2654,10 +2607,11 @@ class QualityValidationResource extends Resource // Generate URL through custom route $imageUrl = route('part.validation.image', [ 'plant' => $plantCodePart3, - 'filename' => $fileName + 'filename' => $fileName, ]); $set('part_validation2_error_image', $imageUrl); + return; } }) @@ -2677,7 +2631,7 @@ class QualityValidationResource extends Resource ->reactive(), Forms\Components\TextInput::make('part_validation4') - ->hidden(fn (callable $get) => !$get('part_validation4_visible')) + ->hidden(fn (callable $get) => ! $get('part_validation4_visible')) ->default('') ->required() ->reactive() @@ -2694,55 +2648,50 @@ class QualityValidationResource extends Resource $mLine = Line::find($mlineId); $mLinePart = $mLine?->name; - if (!$stickerMasterId) { + if (! $stickerMasterId) { return; } $stickerMaster = StickerMaster::find($stickerMasterId); - if (!$stickerMaster) { + if (! $stickerMaster) { return; } $expectedValue = $stickerMaster->part_validation4; - // If input is empty, reset the error + // If input is empty, reset the error if ($state == null || trim($state) == '') { $set('part_validation4_error', null); + return; } - if ($state == $expectedValue) - { + if ($state == $expectedValue) { $set('part_validation4_error', null); - } - else - { - $set('part_validation4_error', "Invalid input for part validation 4."); + } else { + $set('part_validation4_error', 'Invalid input for part validation 4.'); $mailData = \App\Filament\Resources\QualityValidationResource::getMailData($mPlantId); $mPlantName = $mailData['plant_name']; $emails = $mailData['emails']; $mUserName = Filament::auth()->user()->name; - if (!empty($emails)) - { - //Mail::to($emails)->send(new InvalidSerialMail($serNo, $invoiceNumber, $mPlantName, $mInvoiceType)); + if (! empty($emails)) { + // Mail::to($emails)->send(new InvalidSerialMail($serNo, $invoiceNumber, $mPlantName, $mInvoiceType)); Mail::to($emails)->send( - new InvalidQualityMail($state, $mPorder, $mPlantName,$mLinePart, $mUserName, 'InvalidPartNumber4') + new InvalidQualityMail($state, $mPorder, $mPlantName, $mLinePart, $mUserName, 'InvalidPartNumber4') ); - } - else - { + } else { \Log::warning("No recipients found for plant {$mPlantName}, module Serial, rule invalid_serial."); } $set('part_validation4', null); - $fileName = $expectedValue . ".png"; // or .jpg based on your file + $fileName = $expectedValue.'.png'; // or .jpg based on your file $fullPath = storage_path("app/private/uploads/PartValidation/{$plantCodePart4}/{$fileName}"); // Generate URL through custom route $imageUrl = route('part.validation.image', [ 'plant' => $plantCodePart4, - 'filename' => $fileName + 'filename' => $fileName, ]); $set('part_validation4_error_image', $imageUrl); @@ -2766,7 +2715,7 @@ class QualityValidationResource extends Resource ->reactive(), Forms\Components\TextInput::make('part_validation5') - ->hidden(fn (callable $get) => !$get('part_validation5_visible')) + ->hidden(fn (callable $get) => ! $get('part_validation5_visible')) ->default('') ->required() ->reactive() @@ -2776,20 +2725,21 @@ class QualityValidationResource extends Resource $mPorder = $get('production_order'); $mPlantId = $get('plant_id'); - if (!$stickerMasterId) { + if (! $stickerMasterId) { return; } $stickerMaster = StickerMaster::find($stickerMasterId); - if (!$stickerMaster) { + if (! $stickerMaster) { return; } $expectedValue = $stickerMaster->part_validation5; - // If input is empty, reset the error + // If input is empty, reset the error if ($state == null || trim($state) == '') { $set('part_validation5_error', null); + return; } @@ -2813,35 +2763,29 @@ class QualityValidationResource extends Resource // $set('part_validation5', null); // return; // } - if ($state == $expectedValue) - { + if ($state == $expectedValue) { $set('part_validation5_error', null); - } - else if (strpos($state, '/') != false) - { + } elseif (strpos($state, '/') != false) { $parts = explode('/', $state); - if (count($parts) >= 2) - { + if (count($parts) >= 2) { $segmentToValidate = $parts[1]; if ($segmentToValidate == $expectedValue) { $set('part_validation5_error', null); $set('part_validation5', $segmentToValidate); } else { - $set('part_validation5_error', "Invalid input for part validation 5."); + $set('part_validation5_error', 'Invalid input for part validation 5.'); $set('part_validation5', null); + return; } - } - else - { - $set('part_validation5_error', "Invalid input format for part validation 5."); + } else { + $set('part_validation5_error', 'Invalid input format for part validation 5.'); $set('part_validation5', null); + return; } - } - else - { - $set('part_validation5_error', "Invalid input for part validation 5."); + } else { + $set('part_validation5_error', 'Invalid input for part validation 5.'); // $mailData = \App\Filament\Resources\QualityValidationResource::getMailData($mPlantId); // $mPlantName = $mailData['plant_name']; @@ -2859,6 +2803,7 @@ class QualityValidationResource extends Resource // \Log::warning("No recipients found for plant {$mPlantName}, module Serial, rule invalid_serial."); // } $set('part_validation5', null); + return; } @@ -2885,11 +2830,11 @@ class QualityValidationResource extends Resource ->pluck('email') ->toArray(); - if (!empty($globalEmails)) { + if (! empty($globalEmails)) { return [ - 'plant_id' => 0, + 'plant_id' => 0, 'plant_name' => 'All Plants', - 'emails' => $globalEmails, + 'emails' => $globalEmails, ]; } @@ -2903,9 +2848,9 @@ class QualityValidationResource extends Resource ->toArray(); return [ - 'plant_id' => $plantId, + 'plant_id' => $plantId, 'plant_name' => $mPlantName, - 'emails' => $emails, + 'emails' => $emails, ]; } @@ -2924,6 +2869,7 @@ class QualityValidationResource extends Resource $paginator = $livewire->getTableRecords(); $perPage = method_exists($paginator, 'perPage') ? $paginator->perPage() : 10; $currentPage = method_exists($paginator, 'currentPage') ? $paginator->currentPage() : 1; + return ($currentPage - 1) * $perPage + $rowLoop->iteration; }), Tables\Columns\TextColumn::make('plant.name') @@ -3056,207 +3002,214 @@ class QualityValidationResource extends Resource ->filters([ - Tables\Filters\TrashedFilter::make(), - Filter::make('advanced_filters') - ->label('Advanced Filters') - ->form([ - Select::make('Plant') - ->label('Select Plant') - ->nullable() - // ->options(function () { - // return Plant::pluck('name', 'id'); - // }) - ->options(function (callable $get) { - $userHas = Filament::auth()->user()->plant_id; - return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); - }) - ->reactive() - ->afterStateUpdated(function ($state, callable $set, callable $get) { - $set('sticker_master_id', null); - $set('sap_msg_status', null); - $set('Line', null); - $set('operator_id', null); - }), - Select::make('Line') - ->label('Select Line') - ->nullable() - ->options(function (callable $get) { - $plantId = $get('Plant'); - if (!$plantId) - { - return []; - } + Tables\Filters\TrashedFilter::make(), + Filter::make('advanced_filters') + ->label('Advanced Filters') + ->form([ + Select::make('Plant') + ->label('Select Plant') + ->nullable() + // ->options(function () { + // return Plant::pluck('name', 'id'); + // }) + ->options(function (callable $get) { + $userHas = Filament::auth()->user()->plant_id; - return Line::where('plant_id', $plantId) - ->where('type', 'FG Line') // Filter by type - ->pluck('name', 'id') - ->toArray(); - }) - ->reactive() - ->afterStateUpdated(function ($state, callable $set, callable $get) { - $set('sticker_master_id', null); - $set('sap_msg_status', null); - $set('operator_id', null); - }), - TextInput::make('production_order') - ->label('Production Order') - ->placeholder('Enter Production Order'), - TextInput::make('serial_number') - ->label('Serial Number') - ->placeholder(placeholder: 'Enter Serial Number'), - Select::make('sticker_master_id') - ->label('Search by Item Code') - ->nullable() - ->options(function (callable $get) { - $pId = $get('Plant'); - return Item::whereHas('stickerMasters', function ($query) use ($pId) { - if ($pId) { - $query->where('plant_id', $pId); + return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); + }) + ->reactive() + ->afterStateUpdated(function ($state, callable $set, callable $get) { + $set('sticker_master_id', null); + $set('sap_msg_status', null); + $set('Line', null); + $set('operator_id', null); + }), + Select::make('Line') + ->label('Select Line') + ->nullable() + ->options(function (callable $get) { + $plantId = $get('Plant'); + if (! $plantId) { + return []; } - $query->whereHas('qualityValidations'); - })->pluck('code', 'id'); - }) - ->searchable() - ->reactive(), - Select::make('sap_msg_status') - ->label('Select SAP Message Status') - ->nullable() - ->options(function (callable $get) { - $plantId = $get('Plant'); - if (!$plantId ) { - return QualityValidation::whereNotNull('sap_msg_status')->select('sap_msg_status')->distinct()->pluck('sap_msg_status', 'sap_msg_status'); - } - else { - return QualityValidation::where('plant_id', $plantId)->whereNotNull('sap_msg_status')->select('sap_msg_status')->distinct()->pluck('sap_msg_status', 'sap_msg_status'); - } - }) - // ->options(QualityValidation::whereNotNull('sap_msg_status')->select('sap_msg_status')->distinct()->pluck('sap_msg_status', 'sap_msg_status')) - ->reactive(), - Select::make('operator_id') - ->label('Created By') - ->nullable() - ->options(function (callable $get) { - $plantId = $get('Plant'); - $lineId = $get('Line'); - if (!$plantId && !$lineId) - { - return QualityValidation::whereNotNull('operator_id')->select('operator_id')->distinct()->pluck('operator_id', 'operator_id'); - } - else if ($plantId && !$lineId) - { - return QualityValidation::where('plant_id', $plantId)->whereNotNull('operator_id')->select('operator_id')->distinct()->pluck('operator_id', 'operator_id'); - } - else// if ($plantId && $lineId) - { - return QualityValidation::where('plant_id', $plantId)->where('line_id', $lineId)->whereNotNull('operator_id')->select('operator_id')->distinct()->pluck('operator_id', 'operator_id'); - } - }) - ->searchable() - ->reactive(), - DateTimePicker::make(name: 'created_from') - ->label('Created From') - ->placeholder(placeholder: 'Select From DateTime') - ->reactive() - ->native(false), - DateTimePicker::make('created_to') - ->label('Created To') - ->placeholder(placeholder: 'Select To DateTime') - ->reactive() - ->native(false), - ]) - ->query(function ($query, array $data) { - // Hide all records initially if no filters are applied - if (empty($data['Plant']) && empty($data['production_order']) && empty($data['serial_number']) && empty($data['sap_msg_status']) && empty($data['created_from']) && empty($data['created_to']) && empty($data['operator_id']) && empty($data['sticker_master_id'])) { - return $query->whereRaw('1 = 0'); - } + return Line::where('plant_id', $plantId) + ->where('type', 'FG Line') // Filter by type + ->pluck('name', 'id') + ->toArray(); + }) + ->reactive() + ->afterStateUpdated(function ($state, callable $set, callable $get) { + $set('sticker_master_id', null); + $set('sap_msg_status', null); + $set('operator_id', null); + }), + TextInput::make('production_order') + ->label('Production Order') + ->placeholder('Enter Production Order'), + TextInput::make('serial_number') + ->label('Serial Number') + ->placeholder(placeholder: 'Enter Serial Number'), + Select::make('sticker_master_id') + ->label('Search by Item Code') + ->nullable() + ->options(function (callable $get) { + $pId = $get('Plant'); - if (!empty($data['Plant'])) { - $query->where('plant_id', $data['Plant']); - } + return Item::whereHas('stickerMasters', function ($query) use ($pId) { + if ($pId) { + $query->where('plant_id', $pId); + } + $query->whereHas('qualityValidations'); + })->pluck('code', 'id'); + }) + ->searchable() + ->reactive(), + Select::make('sap_msg_status') + ->label('Select SAP Message Status') + ->nullable() + ->options(function (callable $get) { + $plantId = $get('Plant'); - if (!empty($data['Line'])) { - $query->where('line_id', $data['Line']); - } - - if (!empty($data['production_order'])) { - $query->where('production_order', $data['production_order']); - } - - if (!empty($data['serial_number'])) { - $query->where('serial_number', $data['serial_number']); - } - - if (!empty($data['sap_msg_status'])) { - $query->where('sap_msg_status', $data['sap_msg_status']); - } - - if (!empty($data['created_from'])) { - $query->where('created_at', '>=', $data['created_from']); - } - - if (!empty($data['created_to'])) { - $query->where('created_at', '<=', $data['created_to']); - } - - if (!empty($data['operator_id'])) { - $query->where('operator_id', $data['operator_id']); - } - - if (!empty($data['sticker_master_id'])) { - $stickerMasterIds = StickerMaster::where('item_id', $data['sticker_master_id']) - ->pluck('id') - ->toArray(); - - if (!empty($stickerMasterIds)) { - $query->whereIn('sticker_master_id', $stickerMasterIds); + if (! $plantId) { + return QualityValidation::whereNotNull('sap_msg_status')->select('sap_msg_status')->distinct()->pluck('sap_msg_status', 'sap_msg_status'); + } else { + return QualityValidation::where('plant_id', $plantId)->whereNotNull('sap_msg_status')->select('sap_msg_status')->distinct()->pluck('sap_msg_status', 'sap_msg_status'); + } + }) + // ->options(QualityValidation::whereNotNull('sap_msg_status')->select('sap_msg_status')->distinct()->pluck('sap_msg_status', 'sap_msg_status')) + ->reactive(), + Select::make('operator_id') + ->label('Created By') + ->nullable() + ->options(function (callable $get) { + $plantId = $get('Plant'); + $lineId = $get('Line'); + if (! $plantId && ! $lineId) { + return QualityValidation::whereNotNull('operator_id')->select('operator_id')->distinct()->pluck('operator_id', 'operator_id'); + } elseif ($plantId && ! $lineId) { + return QualityValidation::where('plant_id', $plantId)->whereNotNull('operator_id')->select('operator_id')->distinct()->pluck('operator_id', 'operator_id'); + } else { // if ($plantId && $lineId) + return QualityValidation::where('plant_id', $plantId)->where('line_id', $lineId)->whereNotNull('operator_id')->select('operator_id')->distinct()->pluck('operator_id', 'operator_id'); + } + }) + ->searchable() + ->reactive(), + DateTimePicker::make(name: 'created_from') + ->label('Created From') + ->placeholder(placeholder: 'Select From DateTime') + ->reactive() + ->native(false), + DateTimePicker::make('created_to') + ->label('Created To') + ->placeholder(placeholder: 'Select To DateTime') + ->reactive() + ->native(false), + ]) + ->query(function ($query, array $data) { + // Hide all records initially if no filters are applied + if (empty($data['Plant']) && empty($data['production_order']) && empty($data['serial_number']) && empty($data['sap_msg_status']) && empty($data['created_from']) && empty($data['created_to']) && empty($data['operator_id']) && empty($data['sticker_master_id'])) { + return $query->whereRaw('1 = 0'); } - } - //$query->orderBy('created_at', 'asc'); - }) - ->indicateUsing(function (array $data) { - $indicators = []; + if (! empty($data['Plant'])) { + $query->where('plant_id', $data['Plant']); + } else { + $userHas = Filament::auth()->user()->plant_id; - if (!empty($data['Plant'])) { - $indicators[] = 'Plant: ' . Plant::where('id', $data['Plant'])->value('name'); - } + if ($userHas && strlen($userHas) > 0) { + return $query->whereRaw('1 = 0'); + } + } - if (!empty($data['Line'])) { - $indicators[] = 'Line: ' . Line::where('id', $data['Line'])->value('name'); - } + if (! empty($data['Line'])) { + $query->where('line_id', $data['Line']); + } - if (!empty($data['production_order'])) { - $indicators[] = 'Production Order: ' . $data['production_order']; - } + if (! empty($data['production_order'])) { + $query->where('production_order', $data['production_order']); + } - if (!empty($data['serial_number'])) { - $indicators[] = 'Serial Number: ' . $data['serial_number']; - } + if (! empty($data['serial_number'])) { + $query->where('serial_number', $data['serial_number']); + } - if (!empty($data['sticker_master_id'])) { - $itemCode = Item::find($data['sticker_master_id'])->code ?? 'Unknown'; - $indicators[] = 'Item Codes: ' . $itemCode; - } + if (! empty($data['sap_msg_status'])) { + $query->where('sap_msg_status', $data['sap_msg_status']); + } - if (!empty($data['sap_msg_status'])) { - $indicators[] = 'SAP Message Status: ' . $data['sap_msg_status']; - } + if (! empty($data['created_from'])) { + $query->where('created_at', '>=', $data['created_from']); + } - if (!empty($data['operator_id'])) { - $indicators[] = 'Created By: ' . $data['operator_id']; - } + if (! empty($data['created_to'])) { + $query->where('created_at', '<=', $data['created_to']); + } - if (!empty($data['created_from'])) { - $indicators[] = 'From: ' . $data['created_from']; - } + if (! empty($data['operator_id'])) { + $query->where('operator_id', $data['operator_id']); + } - if (!empty($data['created_to'])) { - $indicators[] = 'To: ' . $data['created_to']; - } + if (! empty($data['sticker_master_id'])) { + $stickerMasterIds = StickerMaster::where('item_id', $data['sticker_master_id']) + ->pluck('id') + ->toArray(); - return $indicators; - }) + if (! empty($stickerMasterIds)) { + $query->whereIn('sticker_master_id', $stickerMasterIds); + } + } + + // $query->orderBy('created_at', 'asc'); + }) + ->indicateUsing(function (array $data) { + $indicators = []; + + if (! empty($data['Plant'])) { + $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'])) { + $indicators[] = 'Line: '.Line::where('id', $data['Line'])->value('name'); + } + + if (! empty($data['production_order'])) { + $indicators[] = 'Production Order: '.$data['production_order']; + } + + if (! empty($data['serial_number'])) { + $indicators[] = 'Serial Number: '.$data['serial_number']; + } + + if (! empty($data['sticker_master_id'])) { + $itemCode = Item::find($data['sticker_master_id'])->code ?? 'Unknown'; + $indicators[] = 'Item Codes: '.$itemCode; + } + + if (! empty($data['sap_msg_status'])) { + $indicators[] = 'SAP Message Status: '.$data['sap_msg_status']; + } + + if (! empty($data['operator_id'])) { + $indicators[] = 'Created By: '.$data['operator_id']; + } + + if (! empty($data['created_from'])) { + $indicators[] = 'From: '.$data['created_from']; + } + + if (! empty($data['created_to'])) { + $indicators[] = 'To: '.$data['created_to']; + } + + return $indicators; + }), ]) ->filtersFormMaxHeight('280px') ->actions([ @@ -3266,9 +3219,9 @@ class QualityValidationResource extends Resource ->bulkActions([ Tables\Actions\BulkActionGroup::make([ - Tables\Actions\DeleteBulkAction::make(), - Tables\Actions\ForceDeleteBulkAction::make(), - Tables\Actions\RestoreBulkAction::make(), + Tables\Actions\DeleteBulkAction::make(), + Tables\Actions\ForceDeleteBulkAction::make(), + Tables\Actions\RestoreBulkAction::make(), ]), ]) ->headerActions([ @@ -3276,20 +3229,19 @@ class QualityValidationResource extends Resource ->label('Import Quality Validations') ->color('warning') ->importer(QualityValidationImporter::class) - ->visible(function() { + ->visible(function () { return Filament::auth()->user()->can('view import quality validation'); }), ExportAction::make() ->label('Export Quality Validations') ->color('warning') ->exporter(QualityValidationExporter::class) - ->visible(function() { + ->visible(function () { return Filament::auth()->user()->can('view export quality validation'); }), ]); } - // public static function mutateFormDataBeforeCreate(array $data): array // { // $user =Filament::auth()->user(); diff --git a/app/Filament/Resources/ReworkLocatorInvoiceValidationResource.php b/app/Filament/Resources/ReworkLocatorInvoiceValidationResource.php index 332f8f1..4f05334 100644 --- a/app/Filament/Resources/ReworkLocatorInvoiceValidationResource.php +++ b/app/Filament/Resources/ReworkLocatorInvoiceValidationResource.php @@ -5,30 +5,28 @@ namespace App\Filament\Resources; use App\Filament\Exports\ReworkLocatorInvoiceValidationExporter; use App\Filament\Imports\ReworkLocatorInvoiceValidationImporter; use App\Filament\Resources\ReworkLocatorInvoiceValidationResource\Pages; -use App\Filament\Resources\ReworkLocatorInvoiceValidationResource\RelationManagers; -use App\Models\InvoiceValidation; use App\Models\LocatorInvoiceValidation; use App\Models\PalletValidation; use App\Models\Plant; use App\Models\ReworkLocatorInvoiceValidation; use Filament\Facades\Filament; 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\Get; +use Filament\Notifications\Notification; use Filament\Resources\Resource; use Filament\Tables; +use Filament\Tables\Actions\ExportAction; +use Filament\Tables\Actions\ImportAction; +use Filament\Tables\Filters\Filter; use Filament\Tables\Table; use Illuminate\Database\Eloquent\Builder; 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 { @@ -45,238 +43,163 @@ class ReworkLocatorInvoiceValidationResource extends Resource return $form ->schema([ Section::make('') - ->schema([ - Forms\Components\Select::make('plant_id') - ->label('Plant') - ->reactive() - ->relationship('plant', 'name') - ->disabled(fn (Get $get) => $get('rework_type')) - ->required() - ->options(function (callable $get) { - $userHas = Filament::auth()->user()->plant_id; - 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) { - $plantId = $get('plant_id'); - if ($plantId) - { - $set('plant', $plantId); - $set('invoice_number', null); - $set('scan_pallet_no', null); - $set('scan_serial_no', null); - $set('rework_type', null); - } - else - { - $set('plant', null); - $set('invoice_number', null); - $set('scan_pallet_no', null); - $set('scan_serial_no', null); - $set('rework_type', null); - } - }), - Forms\Components\Hidden::make('plant') - ->reactive(), - Forms\Components\TextInput::make('invoice_number') - ->label('Scan Invoice No') - ->required( fn ($get) => $get('rework_type') == 'invoice') - ->readOnly(fn (callable $get) => (!$get('plant') || $get('rework_type') != 'invoice' || $get('scan_pallet_no') || $get('scan_serial_no'))) - // ->readOnly(fn ($get) => $get('rework_type') == 'pallet') - ->reactive() - ->extraAttributes([ - 'wire:keydown.enter' => 'processInvoiceRework($event.target.value)', - ]), - Forms\Components\TextInput::make('scan_pallet_no') - ->label('Scan Pallet No') - ->required( fn ($get) => $get('rework_type') == 'pallet') - ->readOnly(fn ($get) => $get('rework_type') == 'invoice') - ->minLength(10) - ->reactive() - ->readOnly(fn (callable $get) => (!$get('plant') || !$get('rework_type') || ($get('rework_type') == 'invoice' && !$get('invoice_number')) || $get('scan_serial_no'))) - ->extraAttributes([ - 'wire:keydown.enter' => 'processPalletno($event.target.value)', - ]), - Forms\Components\TextInput::make('scan_serial_no') - ->label('Scan Serial No') - ->readOnly(fn (callable $get) => (!$get('plant') || !$get('rework_type') || ($get('rework_type') == 'invoice' && !$get('invoice_number')) || ($get('rework_type') == 'invoice' && $get('scan_pallet_no')) || ($get('rework_type') == 'pallet' && !$get('scan_pallet_no')))) - ->minLength(9) - ->reactive() - ->extraAttributes([ - 'wire:keydown.enter' => 'processSno($event.target.value)', - ]), - Forms\Components\Radio::make('rework_type') - ->label('Rework Type') - ->options([ - 'invoice' => 'Invoice', - 'pallet' => 'Pallet', - ]) - ->reactive() - ->required() - ->disabled(fn (Get $get) => ($get('invoice_number') || $get('scan_pallet_no') || $get('scan_serial_no'))) - ->hidden(fn (callable $get) => !$get('plant')) - ->inline() - ->inlineLabel(false) - // ->default('invoice') - ->afterStateUpdated(function ($state, callable $set) { - if ($state == 'pallet') { - $set('reworkType', $state); - $set('invoice_number', null); - $set('scan_pallet_no', null); - $set('scan_serial_no', null); - } elseif ($state == 'invoice') { - $set('reworkType', $state); - $set('invoice_number', null); - $set('scan_pallet_no', null); - $set('scan_serial_no', null); - } - else { - $set('reworkType', null); - $set('invoice_number', null); - $set('scan_pallet_no', null); - $set('scan_serial_no', null); - } - }), - Forms\Components\Hidden::make('reworkType') - ->reactive(), + ->schema([ + Forms\Components\Select::make('plant_id') + ->label('Plant') + ->reactive() + ->relationship('plant', 'name') + ->disabled(fn (Get $get) => $get('rework_type')) + ->required() + ->options(function (callable $get) { + $userHas = Filament::auth()->user()->plant_id; - ToggleButtons::make('update_invoice') - ->label('Rework entire invoice?') - ->boolean() - ->grouped() - ->reactive() - ->hidden(fn (callable $get) => (!$get('plant') || $get('rework_type') != 'invoice' || !$get('invoice_number') || $get('update_invoice') == '0' || $get('scan_pallet_no') || $get('scan_serial_no'))) - ->afterStateUpdated(function ($state, callable $set, callable $get, $livewire) { - $plantId = $get('plant'); - - $invoiceNumber = $get('invoice_number'); - - $rows = LocatorInvoiceValidation::where('invoice_number', $invoiceNumber) - ->where('plant_id', $plantId) - ->get(); - - $notCompletedCount = LocatorInvoiceValidation::where('invoice_number', $invoiceNumber) - ->where('plant_id', $plantId) - ->where(function($query) { - $query->whereNull('scanned_status') - ->orWhere('scanned_status', ''); - }) - ->count(); - - $isScanningComplete = true; - foreach ($rows as $row) - { - if ($row->scanned_status != 'Scanned') { - $isScanningComplete = false; - break; + 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) { + $plantId = $get('plant_id'); + if ($plantId) { + $set('plant', $plantId); + $set('invoice_number', null); + $set('scan_pallet_no', null); + $set('scan_serial_no', null); + $set('rework_type', null); + } else { + $set('plant', null); + $set('invoice_number', null); + $set('scan_pallet_no', null); + $set('scan_serial_no', null); + $set('rework_type', null); } - } - - if (!$isScanningComplete) - { - Notification::make() - ->title("Scanned invoice number: '$invoiceNumber' does not completed the scanning process!
Has '$notCompletedCount' pending serial number to scan!
Please, scan the valid completed invoice number to proceed...") - ->danger() - ->duration(5000) - ->send(); - - $set('invoice_number', null); - $set('update_invoice', null); - return; - } - }), - - ToggleButtons::make('update_pallet') - ->label('Rework entire pallet?') - ->boolean() - ->grouped() - ->reactive() - ->hidden(fn (callable $get) => (!$get('plant') || $get('rework_type') != 'pallet' || $get('update_pallet') == '0' || !$get('scan_pallet_no') || $get('scan_serial_no'))) - ->afterStateUpdated(function ($state, callable $set, callable $get, $livewire) { - $plantId = $get('plant'); - - $palletNumber = trim($get('scan_pallet_no')); - $serialNo = trim($get('scan_serial_no')); - $updatePalletStatus = $get('update_pallet') ?? null; - - if ($updatePalletStatus == 0) - { - return; - } - - if (strlen($palletNumber) < 10) - { - Notification::make() - ->title("Invalid: Pallet Number") - ->body("Pallet number '$palletNumber' must be at least 10 digits.") - ->danger() - ->duration(5000) - ->send(); - - $livewire->dispatch('loadData', '', '', $plantId, 'pallet'); - $set('scan_serial_no', null); - $set('scan_pallet_no', null); - $set('update_pallet', null); - return; - } - - $PalletSerialNumbers = PalletValidation::where('plant_id', $plantId)->where('pallet_number', $palletNumber)->first(); - - if (!$PalletSerialNumbers) - { - Notification::make() - ->title('Pallet Not Found') - ->body("Pallet number '$palletNumber' doesn't exist in pallet table!

Scan the valid exist 'Pallet Number' to proceed..!") - ->danger() - ->duration(5000) - ->send(); - - $livewire->dispatch('loadData', '', '', $plantId, 'pallet'); - $set('scan_serial_no', null); - $set('scan_pallet_no', null); - $set('update_pallet', null); - return; - } - - $rows = PalletValidation::where('pallet_number', $palletNumber) - ->where('plant_id', $plantId) - ->get(); - - $isScanningComplete = true; - foreach ($rows as $row) - { - if ($row->pallet_status != 'Completed') { - $isScanningComplete = false; - break; + }), + Forms\Components\Hidden::make('plant') + ->reactive(), + Forms\Components\TextInput::make('invoice_number') + ->label('Scan Invoice No') + ->required(fn ($get) => $get('rework_type') == 'invoice') + ->readOnly(fn (callable $get) => (! $get('plant') || $get('rework_type') != 'invoice' || $get('scan_pallet_no') || $get('scan_serial_no'))) + // ->readOnly(fn ($get) => $get('rework_type') == 'pallet') + ->reactive() + ->extraAttributes([ + 'wire:keydown.enter' => 'processInvoiceRework($event.target.value)', + ]), + Forms\Components\TextInput::make('scan_pallet_no') + ->label('Scan Pallet No') + ->required(fn ($get) => $get('rework_type') == 'pallet') + ->readOnly(fn ($get) => $get('rework_type') == 'invoice') + ->minLength(10) + ->reactive() + ->readOnly(fn (callable $get) => (! $get('plant') || ! $get('rework_type') || ($get('rework_type') == 'invoice' && ! $get('invoice_number')) || $get('scan_serial_no'))) + ->extraAttributes([ + 'wire:keydown.enter' => 'processPalletno($event.target.value)', + ]), + Forms\Components\TextInput::make('scan_serial_no') + ->label('Scan Serial No') + ->readOnly(fn (callable $get) => (! $get('plant') || ! $get('rework_type') || ($get('rework_type') == 'invoice' && ! $get('invoice_number')) || ($get('rework_type') == 'invoice' && $get('scan_pallet_no')) || ($get('rework_type') == 'pallet' && ! $get('scan_pallet_no')))) + ->minLength(9) + ->reactive() + ->extraAttributes([ + 'wire:keydown.enter' => 'processSno($event.target.value)', + ]), + Forms\Components\Radio::make('rework_type') + ->label('Rework Type') + ->options([ + 'invoice' => 'Invoice', + 'pallet' => 'Pallet', + ]) + ->reactive() + ->required() + ->disabled(fn (Get $get) => ($get('invoice_number') || $get('scan_pallet_no') || $get('scan_serial_no'))) + ->hidden(fn (callable $get) => ! $get('plant')) + ->inline() + ->inlineLabel(false) + // ->default('invoice') + ->afterStateUpdated(function ($state, callable $set) { + if ($state == 'pallet') { + $set('reworkType', $state); + $set('invoice_number', null); + $set('scan_pallet_no', null); + $set('scan_serial_no', null); + } elseif ($state == 'invoice') { + $set('reworkType', $state); + $set('invoice_number', null); + $set('scan_pallet_no', null); + $set('scan_serial_no', null); + } else { + $set('reworkType', null); + $set('invoice_number', null); + $set('scan_pallet_no', null); + $set('scan_serial_no', null); } - } + }), + Forms\Components\Hidden::make('reworkType') + ->reactive(), - if(count($rows) <= 0) { - $isScanningComplete = false; - } + ToggleButtons::make('update_invoice') + ->label('Rework entire invoice?') + ->boolean() + ->grouped() + ->reactive() + ->hidden(fn (callable $get) => (! $get('plant') || $get('rework_type') != 'invoice' || ! $get('invoice_number') || $get('update_invoice') == '0' || $get('scan_pallet_no') || $get('scan_serial_no'))) + ->afterStateUpdated(function ($state, callable $set, callable $get, $livewire) { + $plantId = $get('plant'); - if (!$isScanningComplete) - { - Notification::make() - ->title('Pallet Not Completed') - ->body("Scanned pallet number '$palletNumber' doesn't completed the master packing!

Please, scan the valid completed pallet number to proceed..!") - ->danger() - ->duration(5000) - ->send(); + $invoiceNumber = $get('invoice_number'); - $livewire->dispatch('loadData', '', '', $plantId, 'pallet'); - $set('scan_serial_no', null); - $set('scan_pallet_no', null); - $set('update_pallet', null); - return; - } - else - { - $locatExist = ($PalletSerialNumbers->locator_number != null && $PalletSerialNumbers->locator_number != '') ? $PalletSerialNumbers->locator_number : ''; - if ($locatExist) - { + $rows = LocatorInvoiceValidation::where('invoice_number', $invoiceNumber) + ->where('plant_id', $plantId) + ->get(); + + $notCompletedCount = LocatorInvoiceValidation::where('invoice_number', $invoiceNumber) + ->where('plant_id', $plantId) + ->where(function ($query) { + $query->whereNull('scanned_status') + ->orWhere('scanned_status', ''); + }) + ->count(); + + $isScanningComplete = true; + foreach ($rows as $row) { + if ($row->scanned_status != 'Scanned') { + $isScanningComplete = false; + break; + } + } + + if (! $isScanningComplete) { Notification::make() - ->title('Locator Pallet Found') - ->body("Scanned pallet number '$palletNumber' exist in locator number '$locatExist'.

Remove scanned 'Pallet' from 'Locator' to proceed re-master packing..!") + ->title("Scanned invoice number: '$invoiceNumber' does not completed the scanning process!
Has '$notCompletedCount' pending serial number to scan!
Please, scan the valid completed invoice number to proceed...") + ->danger() + ->duration(5000) + ->send(); + + $set('invoice_number', null); + $set('update_invoice', null); + + return; + } + }), + + ToggleButtons::make('update_pallet') + ->label('Rework entire pallet?') + ->boolean() + ->grouped() + ->reactive() + ->hidden(fn (callable $get) => (! $get('plant') || $get('rework_type') != 'pallet' || $get('update_pallet') == '0' || ! $get('scan_pallet_no') || $get('scan_serial_no'))) + ->afterStateUpdated(function ($state, callable $set, callable $get, $livewire) { + $plantId = $get('plant'); + + $palletNumber = trim($get('scan_pallet_no')); + $serialNo = trim($get('scan_serial_no')); + $updatePalletStatus = $get('update_pallet') ?? null; + + if ($updatePalletStatus == 0) { + return; + } + + if (strlen($palletNumber) < 10) { + Notification::make() + ->title('Invalid: Pallet Number') + ->body("Pallet number '$palletNumber' must be at least 10 digits.") ->danger() ->duration(5000) ->send(); @@ -285,71 +208,134 @@ class ReworkLocatorInvoiceValidationResource extends Resource $set('scan_serial_no', null); $set('scan_pallet_no', null); $set('update_pallet', null); + return; } - else - { - if (strlen($serialNo) > 0 && (strlen($serialNo) < 9 || strlen($serialNo) > 20)) - { + + $PalletSerialNumbers = PalletValidation::where('plant_id', $plantId)->where('pallet_number', $palletNumber)->first(); + + if (! $PalletSerialNumbers) { + Notification::make() + ->title('Pallet Not Found') + ->body("Pallet number '$palletNumber' doesn't exist in pallet table!

Scan the valid exist 'Pallet Number' to proceed..!") + ->danger() + ->duration(5000) + ->send(); + + $livewire->dispatch('loadData', '', '', $plantId, 'pallet'); + $set('scan_serial_no', null); + $set('scan_pallet_no', null); + $set('update_pallet', null); + + return; + } + + $rows = PalletValidation::where('pallet_number', $palletNumber) + ->where('plant_id', $plantId) + ->get(); + + $isScanningComplete = true; + foreach ($rows as $row) { + if ($row->pallet_status != 'Completed') { + $isScanningComplete = false; + break; + } + } + + if (count($rows) <= 0) { + $isScanningComplete = false; + } + + if (! $isScanningComplete) { + Notification::make() + ->title('Pallet Not Completed') + ->body("Scanned pallet number '$palletNumber' doesn't completed the master packing!

Please, scan the valid completed pallet number to proceed..!") + ->danger() + ->duration(5000) + ->send(); + + $livewire->dispatch('loadData', '', '', $plantId, 'pallet'); + $set('scan_serial_no', null); + $set('scan_pallet_no', null); + $set('update_pallet', null); + + return; + } else { + $locatExist = ($PalletSerialNumbers->locator_number != null && $PalletSerialNumbers->locator_number != '') ? $PalletSerialNumbers->locator_number : ''; + if ($locatExist) { Notification::make() - ->title("Invalid: Serial Number") - ->body("Serial number '$serialNo' should contain minimum 9 digits and maximum 20 digits.") + ->title('Locator Pallet Found') + ->body("Scanned pallet number '$palletNumber' exist in locator number '$locatExist'.

Remove scanned 'Pallet' from 'Locator' to proceed re-master packing..!") ->danger() ->duration(5000) ->send(); - $livewire->dispatch('loadData', '', $palletNumber, $plantId, 'pallet'); - $set('scan_serial_no', null); - $set('update_pallet', null); - return; - } - else if (strlen($serialNo) > 0 && !ctype_alnum($serialNo)) - { - Notification::make() - ->title("Invalid: Serial Number") - ->body("Serial number '$serialNo' must contain alpha-numeric values only.") - ->danger() - ->duration(5000) - ->send(); - - $livewire->dispatch('loadData', '', $palletNumber, $plantId, 'pallet'); - $set('scan_serial_no', null); - $set('update_pallet', null); - return; - } - - if ($updatePalletStatus == 1) - { - foreach ($rows as $row) - { - $row->forceDelete(); // Delete the row from the original table - } - - Notification::make() - ->title('Completed: Rework Pallet') - ->body("Scanned pallet number '$palletNumber' successfully removed from pallet table.

Please, scan the next pallet number to re-master packing..!") - ->success() - ->duration(800) - ->send(); - $livewire->dispatch('loadData', '', '', $plantId, 'pallet'); $set('scan_serial_no', null); $set('scan_pallet_no', null); $set('update_pallet', null); + return; + } else { + if (strlen($serialNo) > 0 && (strlen($serialNo) < 9 || strlen($serialNo) > 20)) { + Notification::make() + ->title('Invalid: Serial Number') + ->body("Serial number '$serialNo' should contain minimum 9 digits and maximum 20 digits.") + ->danger() + ->duration(5000) + ->send(); + + $livewire->dispatch('loadData', '', $palletNumber, $plantId, 'pallet'); + $set('scan_serial_no', null); + $set('update_pallet', null); + + return; + } elseif (strlen($serialNo) > 0 && ! ctype_alnum($serialNo)) { + Notification::make() + ->title('Invalid: Serial Number') + ->body("Serial number '$serialNo' must contain alpha-numeric values only.") + ->danger() + ->duration(5000) + ->send(); + + $livewire->dispatch('loadData', '', $palletNumber, $plantId, 'pallet'); + $set('scan_serial_no', null); + $set('update_pallet', null); + + return; + } + + if ($updatePalletStatus == 1) { + foreach ($rows as $row) { + $row->forceDelete(); // Delete the row from the original table + } + + Notification::make() + ->title('Completed: Rework Pallet') + ->body("Scanned pallet number '$palletNumber' successfully removed from pallet table.

Please, scan the next pallet number to re-master packing..!") + ->success() + ->duration(800) + ->send(); + + $livewire->dispatch('loadData', '', '', $plantId, 'pallet'); + $set('scan_serial_no', null); + $set('scan_pallet_no', null); + $set('update_pallet', null); + + return; + } } } - } - }), - Forms\Components\Hidden::make('created_by') - ->default(Filament::auth()->user()?->name), - Forms\Components\Hidden::make('scanned_by') - ->default(Filament::auth()->user()?->name), - Forms\Components\TextInput::make('id') - ->hidden() - ->readOnly(), - ]) - ->columns(5) + }), + Forms\Components\Hidden::make('created_by') + ->default(Filament::auth()->user()?->name), + Forms\Components\Hidden::make('scanned_by') + ->default(Filament::auth()->user()?->name), + Forms\Components\TextInput::make('id') + ->hidden() + ->readOnly(), + ]) + ->columns(5), ]); } @@ -364,6 +350,7 @@ class ReworkLocatorInvoiceValidationResource extends Resource $paginator = $livewire->getTableRecords(); $perPage = method_exists($paginator, 'perPage') ? $paginator->perPage() : 10; $currentPage = method_exists($paginator, 'currentPage') ? $paginator->currentPage() : 1; + return ($currentPage - 1) * $perPage + $rowLoop->iteration; }), Tables\Columns\TextColumn::make('plant.name') @@ -444,207 +431,221 @@ class ReworkLocatorInvoiceValidationResource extends Resource ->importer(ReworkLocatorInvoiceValidationImporter::class) ->label('Import Rework Invoice') ->color('warning') - ->visible(function() { + ->visible(function () { return Filament::auth()->user()->can('view import rework invoice validation'); }), ExportAction::make() ->exporter(ReworkLocatorInvoiceValidationExporter::class) ->label('Export Rework Invoice') ->color('warning') - ->visible(function() { + ->visible(function () { return Filament::auth()->user()->can('view export rework invoice validation'); }), ]) - // ->filters([ - // Tables\Filters\TrashedFilter::make(), - // ]) ->filters([ Tables\Filters\TrashedFilter::make(), Filter::make('advanced_filters') - ->label('Advanced Filters') - ->form([ - Select::make('Plant') - ->label('Select Plant') - ->nullable() - // ->options(function () { - // return Plant::pluck('name', 'id'); - // }) - ->options(function (callable $get) { + ->label('Advanced Filters') + ->form([ + Select::make('Plant') + ->label('Select Plant') + ->nullable() + // ->options(function () { + // return Plant::pluck('name', 'id'); + // }) + ->options(function (callable $get) { + $userHas = Filament::auth()->user()->plant_id; + + return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); + }) + ->reactive() + ->afterStateUpdated(function ($state, callable $set, callable $get): void { + $set('pallet_number', null); + $set('invoice_number', null); + $set('serial_number', null); + $set('scanned_status', null); + $set('locator_number', null); + $set('created_from', null); + $set('created_to', null); + $set('created_by', null); + $set('scanned_from', null); + $set('scanned_to', null); + $set('scanned_by', null); + }), + Select::make('invoice_number') + ->label('Invoice Number') + ->options(function (callable $get) { + $plantId = $get('Plant'); + if (! $plantId) { + return []; + } + + return ReworkLocatorInvoiceValidation::where('plant_id', $plantId) + ->whereNotNull('invoice_number') + ->where('invoice_number', '!=', '') + ->orderBy('invoice_number', 'asc') + ->get() + ->unique('invoice_number') + ->pluck('invoice_number', 'invoice_number') + ->toArray(); + }) + ->searchable() + ->reactive(), + TextInput::make('serial_number') + ->label('Serial Number') + ->placeholder(placeholder: 'Enter Serial Number'), + Select::make('pallet_number') + ->label('Pallet Number') + ->options(function (callable $get) { + $plantId = $get('Plant'); + if (! $plantId) { + return []; + } + + return ReworkLocatorInvoiceValidation::where('plant_id', $plantId) + ->whereNotNull('pallet_number') + ->where('pallet_number', '!=', '') + ->orderBy('pallet_number', 'asc') + ->get() + ->unique('pallet_number') + ->pluck('pallet_number', 'pallet_number') + ->toArray(); + }) + ->searchable() + ->reactive(), + Select::make('locator_number') + ->label('Locator Number') + ->options(function (callable $get) { + $plantId = $get('Plant'); + if (! $plantId) { + return []; + } + + return ReworkLocatorInvoiceValidation::where('plant_id', $plantId) + ->whereNotNull('locator_number') + ->where('locator_number', '!=', '') + ->orderBy('locator_number', 'asc') + ->get() + ->unique('locator_number') + ->pluck('locator_number', 'locator_number') + ->toArray(); + }) + ->searchable() + ->reactive(), + Select::make('scanned_status') + ->label('Scanned Status') + ->options([ + 'Scanned' => 'Scanned', + ]), + DateTimePicker::make(name: 'rework_from') + ->label('Rework From') + ->placeholder(placeholder: 'Select From DateTime') + ->reactive() + ->native(false), + DateTimePicker::make('rework_to') + ->label('Rework To') + ->placeholder(placeholder: 'Select To DateTime') + ->reactive() + ->native(false), + TextInput::make('rework_by') + ->label('Rework By') + ->placeholder(placeholder: 'Enter Rework By'), + ]) + ->query(function ($query, array $data) { + // Hide all records initially if no filters are applied + if (empty($data['Plant']) && empty($data['invoice_number']) && empty($data['serial_number']) && empty($data['pallet_number']) && empty($data['locator_number']) && empty($data['scanned_status']) && empty($data['rework_from']) && empty($data['rework_to']) && empty($data['rework_by'])) { + return $query->whereRaw('1 = 0'); + } + + if (! empty($data['Plant'])) { // $plant = $data['Plant'] ?? null + $query->where('plant_id', $data['Plant']); + } else { $userHas = Filament::auth()->user()->plant_id; - return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); - }) - ->reactive() - ->afterStateUpdated(function ($state, callable $set, callable $get): void { - $set('pallet_number', null); - $set('invoice_number', null); - $set('serial_number', null); - $set('scanned_status', null); - $set('locator_number', null); - $set('created_from', null); - $set('created_to', null); - $set('created_by', null); - $set('scanned_from', null); - $set('scanned_to', null); - $set('scanned_by', null); - }), - Select::make('invoice_number') - ->label('Invoice Number') - ->options(function (callable $get) { - $plantId = $get('Plant'); - if (!$plantId) { - return []; + + if ($userHas && strlen($userHas) > 0) { + return $query->whereRaw('1 = 0'); } - return ReworkLocatorInvoiceValidation::where('plant_id', $plantId) - ->whereNotNull('invoice_number') - ->where('invoice_number','!=', '') - ->orderBy('invoice_number', 'asc') - ->get() - ->unique('invoice_number') - ->pluck('invoice_number', 'invoice_number') - ->toArray(); - }) - ->searchable() - ->reactive(), - TextInput::make('serial_number') - ->label('Serial Number') - ->placeholder(placeholder: 'Enter Serial Number'), - Select::make('pallet_number') - ->label('Pallet Number') - ->options(function (callable $get) { - $plantId = $get('Plant'); - if (!$plantId) { - return []; + } + + if (! empty($data['invoice_number'])) { + $query->where('invoice_number', $data['invoice_number']); + } + + if (! empty($data['serial_number'])) { + $query->where('serial_number', $data['serial_number']); + } + + if (! empty($data['pallet_number'])) { + $query->where('pallet_number', $data['pallet_number']); + } + + if (! empty($data['locator_number'])) { + $query->where('locator_number', $data['locator_number']); + } + if (! empty($data['scanned_status'])) { + $query->where('scanned_status', $data['scanned_status']); + } + + if (! empty($data['rework_from'])) { + $query->where('reworked_at', '>=', $data['rework_from']); + } + + if (! empty($data['rework_to'])) { + $query->where('reworked_at', '<=', $data['rework_to']); + } + + if (! empty($data['rework_by'])) { + $query->where('reworked_by', $data['rework_by']); + } + + }) + ->indicateUsing(function (array $data) { + $indicators = []; + + if (! empty($data['Plant'])) { + $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.'; } - return ReworkLocatorInvoiceValidation::where('plant_id', $plantId) - ->whereNotNull('pallet_number') - ->where('pallet_number','!=', '') - ->orderBy('pallet_number', 'asc') - ->get() - ->unique('pallet_number') - ->pluck('pallet_number', 'pallet_number') - ->toArray(); - }) - ->searchable() - ->reactive(), - Select::make('locator_number') - ->label('Locator Number') - ->options(function (callable $get) { - $plantId = $get('Plant'); - if (!$plantId) { - return []; - } - return ReworkLocatorInvoiceValidation::where('plant_id', $plantId) - ->whereNotNull('locator_number') - ->where('locator_number','!=', '') - ->orderBy('locator_number', 'asc') - ->get() - ->unique('locator_number') - ->pluck('locator_number', 'locator_number') - ->toArray(); - }) - ->searchable() - ->reactive(), - Select::make('scanned_status') - ->label('Scanned Status') - ->options([ - 'Scanned' => 'Scanned', - ]), - DateTimePicker::make(name: 'rework_from') - ->label('Rework From') - ->placeholder(placeholder: 'Select From DateTime') - ->reactive() - ->native(false), - DateTimePicker::make('rework_to') - ->label('Rework To') - ->placeholder(placeholder: 'Select To DateTime') - ->reactive() - ->native(false), - TextInput::make('rework_by') - ->label('Rework By') - ->placeholder(placeholder: 'Enter Rework By'), - ]) - ->query(function ($query, array $data) { - // Hide all records initially if no filters are applied - if (empty($data['Plant']) && empty($data['invoice_number']) && empty($data['serial_number']) && empty($data['pallet_number']) && empty($data['locator_number']) && empty($data['scanned_status']) && empty($data['rework_from']) && empty($data['rework_to']) && empty($data['rework_by'])) { - return $query->whereRaw('1 = 0'); - } + } - if (!empty($data['Plant'])) { //$plant = $data['Plant'] ?? null - $query->where('plant_id', $data['Plant']); - } + if (! empty($data['invoice_number'])) { + $indicators[] = 'Invoice Number: '.$data['invoice_number']; + } - if (!empty($data['invoice_number'])) { - $query->where('invoice_number', $data['invoice_number']); - } + if (! empty($data['serial_number'])) { + $indicators[] = 'Serial Number: '.$data['serial_number']; + } - if (!empty($data['serial_number'])) { - $query->where('serial_number', $data['serial_number']); - } + if (! empty($data['pallet_number'])) { + $indicators[] = 'Pallet Number: '.$data['pallet_number']; + } - if (!empty($data['pallet_number'])) { - $query->where('pallet_number', $data['pallet_number']); - } + if (! empty($data['locator_number'])) { + $indicators[] = 'Locator Number: '.$data['locator_number']; + } - if (!empty($data['locator_number'])) { - $query->where('locator_number', $data['locator_number']); - } - if (!empty($data['scanned_status'])) { - $query->where('scanned_status', $data['scanned_status']); - } + if (! empty($data['scanned_status'])) { + $indicators[] = 'Scanned Status: '.$data['scanned_status']; + } - if (!empty($data['rework_from'])) { - $query->where('reworked_at', '>=', $data['rework_from']); - } + if (! empty($data['rework_from'])) { + $indicators[] = 'From: '.$data['rework_from']; + } - if (!empty($data['rework_to'])) { - $query->where('reworked_at', '<=', $data['rework_to']); - } + if (! empty($data['rework_to'])) { + $indicators[] = 'To: '.$data['rework_to']; + } - if (!empty($data['rework_by'])) { - $query->where('reworked_by', $data['rework_by']); - } + if (! empty($data['rework_by'])) { + $indicators[] = 'Reworked By: '.$data['rework_by']; + } - }) - ->indicateUsing(function (array $data) { - $indicators = []; - - if (!empty($data['Plant'])) { - $indicators[] = 'Plant: ' . Plant::where('id', $data['Plant'])->value('name'); - } - - if (!empty($data['invoice_number'])) { - $indicators[] = 'Invoice Number: ' . $data['invoice_number']; - } - - if (!empty($data['serial_number'])) { - $indicators[] = 'Serial Number: ' . $data['serial_number']; - } - - if (!empty($data['pallet_number'])) { - $indicators[] = 'Pallet Number: ' . $data['pallet_number']; - } - - if (!empty($data['locator_number'])) { - $indicators[] = 'Locator Number: ' . $data['locator_number']; - } - - if (!empty($data['scanned_status'])) { - $indicators[] = 'Scanned Status: ' . $data['scanned_status']; - } - - if (!empty($data['rework_from'])) { - $indicators[] = 'From: ' . $data['rework_from']; - } - - if (!empty($data['rework_to'])) { - $indicators[] = 'To: ' . $data['rework_to']; - } - - if (!empty($data['rework_by'])) { - $indicators[] = 'Reworked By: ' . $data['rework_by']; - } - return $indicators; - }) + return $indicators; + }), ]) ->filtersFormMaxHeight('280px') ->actions([ diff --git a/app/Filament/Resources/SerialValidationResource.php b/app/Filament/Resources/SerialValidationResource.php index fc3d097..84fb38f 100644 --- a/app/Filament/Resources/SerialValidationResource.php +++ b/app/Filament/Resources/SerialValidationResource.php @@ -4,183 +4,226 @@ namespace App\Filament\Resources; use App\Filament\Exports\SerialValidationExporter; use App\Filament\Resources\SerialValidationResource\Pages; -use App\Filament\Resources\SerialValidationResource\RelationManagers; use App\Models\Item; use App\Models\Plant; use App\Models\SerialValidation; use App\Models\StickerMaster; -use Filament\Tables\Actions\ExportAction; +use Filament\Facades\Filament; use Filament\Forms; -use Filament\Forms\Form; -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\DateTimePicker; use Filament\Forms\Components\FileUpload; use Filament\Forms\Components\Radio; use Filament\Forms\Components\Section; use Filament\Forms\Components\Select; use Filament\Forms\Components\TextInput; use Filament\Forms\Components\ToggleButtons; -use Filament\Facades\Filament; +use Filament\Forms\Form; +use Filament\Forms\Get; 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 Maatwebsite\Excel\Facades\Excel; use Str; -use Filament\Tables\Filters\Filter; -use Filament\Forms\Components\DateTimePicker; class SerialValidationResource extends Resource { protected static ?string $model = SerialValidation::class; protected static ?string $navigationIcon = 'heroicon-o-rectangle-stack'; + protected static ?string $navigationGroup = 'Serial Validation'; - public $invoiceNumber; + + public $invoiceNumber; public static function form(Form $form): Form { return $form ->schema([ - Section::make('') - ->schema([ - Forms\Components\Select::make('plant_id') - ->relationship('plant', 'name') - ->required() - ->reactive() - ->columnSpan(1) - ->options(function (callable $get) { - $userHas = Filament::auth()->user()->plant_id; - return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); - }) - ->default(function () { - return optional(SerialValidation::latest()->first())->plant_id; - }) - ->disabled(fn (Get $get) => !empty($get('id'))) - // ->afterStateUpdated(fn ($set) => $set('block_id', null) & $set('name', null) & $set('start_time', null) & $set('duration', null) & $set('end_time', null)) - ->afterStateUpdated(function ($state, callable $set, callable $get) { - $plantId = $get('plant_id'); - $set('update_invoice', null); - // Ensure `linestop_id` is not cleared - if (!$plantId) { - $set('invoice_number', null); - $set('serial_number', null); - $set('total_quantity', null); - $set('scanned_quantity', null); - $set('ivPlantError', 'Please select a plant first.'); - return; - } - else - { - $set('ivPlantError', null); - } - }) - ->extraAttributes(fn ($get) => [ - 'class' => $get('ivPlantError') ? 'border-red-500' : '', - ]) - ->hint(fn ($get) => $get('ivPlantError') ? $get('ivPlantError') : null) - ->hintColor('danger'), + Section::make('') + ->schema([ + Forms\Components\Select::make('plant_id') + ->relationship('plant', 'name') + ->required() + ->reactive() + ->columnSpan(1) + ->options(function (callable $get) { + $userHas = Filament::auth()->user()->plant_id; - Forms\Components\TextInput::make('invoice_number') - ->label('Invoice Number') - // ->required() - ->reactive() - //->disabled() - ->columnSpan(1) - //->readOnly(fn (callable $get) => !empty($get('serial_number'))) - //->disabled(fn (Get $get) => !empty($get('serial_number'))) - ->extraAttributes([ - 'x-data' => '{ value: "" }', - 'x-model' => 'value', - 'x-on:keydown.enter.prevent' => '$wire.processInvoice(value)', - ]) - // ->afterStateHydrated(function (TextInput $component, string $state) { - // $component->state(ucwords($state)); - // }) - ->afterStateUpdated(function ($state, callable $set, callable $get) { - $invNo = $get('invoice_number'); - $set('serial_number', null); - $set('update_invoice', null); - // if (!$invNo) { return; } else { } - }), - - Forms\Components\TextInput::make('serial_number') - ->label('Serial Number') - ->reactive() - // ->readOnly(fn (callable $get) => empty($get('invoice_number'))) - //->disabled(fn (Get $get) => empty($get('invoice_number'))) - ->extraAttributes([ - 'id' => 'serial_number_input', - 'x-data' => '{ value: "" }', - 'x-model' => 'value', - 'wire:keydown.enter.prevent' => 'processSerialNumber(value)', // Using wire:keydown - ]) - ->afterStateUpdated(function ($state, callable $set, callable $get) { - $set('update_invoice', 0); - // $this->dispatch('focus-serial-number'); - // if (!$invNo) { return; } else { } - }) - ->columnSpan(1), - Forms\Components\TextInput::make('total_quantity') - ->label('Total Quantity') - ->readOnly(true) - ->columnSpan(1), - Forms\Components\TextInput::make('scanned_quantity') - ->label('Scanned Quantity') - ->readOnly(true) - ->columnSpan(1), - ToggleButtons::make('update_invoice') - ->label('Update Invoice?') - ->boolean() - ->grouped() - ->reactive() - ->hidden(fn (callable $get) => ($get('invoice_number') == null || $get('update_invoice') == '0') || !empty($get('serial_number'))) - ->afterStateUpdated(function ($state, callable $set, callable $get) { - if (!$get('plant_id')) - { - $set('update_invoice', null); - return; - } - - if ($get('update_invoice') == "1") - { - $totQuan = SerialValidation::where('invoice_number', $get('invoice_number'))->where('plant_id', $get('plant_id'))->count(); - if ($totQuan <= 0) - { + return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); + }) + ->default(function () { + return optional(SerialValidation::latest()->first())->plant_id; + }) + ->disabled(fn (Get $get) => ! empty($get('id'))) + // ->afterStateUpdated(fn ($set) => $set('block_id', null) & $set('name', null) & $set('start_time', null) & $set('duration', null) & $set('end_time', null)) + ->afterStateUpdated(function ($state, callable $set, callable $get) { + $plantId = $get('plant_id'); $set('update_invoice', null); - return; + // Ensure `linestop_id` is not cleared + if (! $plantId) { + $set('invoice_number', null); + $set('serial_number', null); + $set('total_quantity', null); + $set('scanned_quantity', null); + $set('ivPlantError', 'Please select a plant first.'); + + return; + } else { + $set('ivPlantError', null); + } + }) + ->extraAttributes(fn ($get) => [ + 'class' => $get('ivPlantError') ? 'border-red-500' : '', + ]) + ->hint(fn ($get) => $get('ivPlantError') ? $get('ivPlantError') : null) + ->hintColor('danger'), + + Forms\Components\TextInput::make('invoice_number') + ->label('Invoice Number') + // ->required() + ->reactive() + // ->disabled() + ->columnSpan(1) + // ->readOnly(fn (callable $get) => !empty($get('serial_number'))) + // ->disabled(fn (Get $get) => !empty($get('serial_number'))) + ->extraAttributes([ + 'x-data' => '{ value: "" }', + 'x-model' => 'value', + 'x-on:keydown.enter.prevent' => '$wire.processInvoice(value)', + ]) + // ->afterStateHydrated(function (TextInput $component, string $state) { + // $component->state(ucwords($state)); + // }) + ->afterStateUpdated(function ($state, callable $set, callable $get) { + $invNo = $get('invoice_number'); + $set('serial_number', null); + $set('update_invoice', null); + // if (!$invNo) { return; } else { } + }), + + Forms\Components\TextInput::make('serial_number') + ->label('Serial Number') + ->reactive() + // ->readOnly(fn (callable $get) => empty($get('invoice_number'))) + // ->disabled(fn (Get $get) => empty($get('invoice_number'))) + ->extraAttributes([ + 'id' => 'serial_number_input', + 'x-data' => '{ value: "" }', + 'x-model' => 'value', + // '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), - $totMQuan = SerialValidation::where('invoice_number', $get('invoice_number'))->whereNotNull('quantity')->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(); + 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) { + $get('serial_number'); - if ($totMQuan > 0) - { - if ($totQuan == $scanMQuan) - { + }) + ->columnSpan(1), + Forms\Components\TextInput::make('total_quantity') + ->label('Total Quantity') + ->readOnly(true) + ->columnSpan(1), + Forms\Components\TextInput::make('scanned_quantity') + ->label('Scanned Quantity') + ->readOnly(true) + ->columnSpan(1), + ToggleButtons::make('update_invoice') + ->label('Update Invoice?') + ->boolean() + ->grouped() + ->reactive() + ->hidden(fn (callable $get) => ($get('invoice_number') == null || $get('update_invoice') == '0') || ! empty($get('serial_number'))) + ->afterStateUpdated(function ($state, callable $set, callable $get) { + if (! $get('plant_id')) { $set('update_invoice', null); + return; } - } - else - { - if ($totQuan == $scanSQuan) - { - $set('update_invoice', null); - return; + + if ($get('update_invoice') == '1') { + $totQuan = SerialValidation::where('invoice_number', $get('invoice_number'))->where('plant_id', $get('plant_id'))->count(); + if ($totQuan <= 0) { + $set('update_invoice', null); + + return; + } + + $totMQuan = SerialValidation::where('invoice_number', $get('invoice_number'))->whereNotNull('quantity')->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(); + + if ($totMQuan > 0) { + if ($totQuan == $scanMQuan) { + $set('update_invoice', null); + + return; + } + } else { + if ($totQuan == $scanSQuan) { + $set('update_invoice', null); + + return; + } + } } - } - } - }) - ->disabled(fn (Get $get) => empty($get('invoice_number'))), - Forms\Components\TextInput::make('id') - ->hidden() - ->readOnly(true), - ]) - ->columns(5), + }) + ->disabled(fn (Get $get) => empty($get('invoice_number'))), + Forms\Components\TextInput::make('id') + ->hidden() + ->readOnly(true), + ]) + ->columns(5), ]); } @@ -194,6 +237,7 @@ class SerialValidationResource extends Resource $paginator = $livewire->getTableRecords(); $perPage = method_exists($paginator, 'perPage') ? $paginator->perPage() : 10; $currentPage = method_exists($paginator, 'currentPage') ? $paginator->currentPage() : 1; + return ($currentPage - 1) * $perPage + $rowLoop->iteration; }), Tables\Columns\TextColumn::make('invoice_number') @@ -285,19 +329,20 @@ class SerialValidationResource extends Resource ->form([ Select::make('plant_id') // ->options(Plant::pluck('name', 'id')->toArray()) // Fetch plant names and IDs - ->options(function (callable $get) { - $userHas = Filament::auth()->user()->plant_id; - return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); - }) - ->label('Select Plant') - ->required() - ->default(function () { - return optional(SerialValidation::latest()->first())->plant_id; - }) - ->afterStateUpdated(function ($state, callable $set, callable $get) { - $set('invoice_serial_number', null); - }) - ->reactive(), + ->options(function (callable $get) { + $userHas = Filament::auth()->user()->plant_id; + + return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); + }) + ->label('Select Plant') + ->required() + ->default(function () { + return optional(SerialValidation::latest()->first())->plant_id; + }) + ->afterStateUpdated(function ($state, callable $set, callable $get) { + $set('invoice_serial_number', null); + }) + ->reactive(), FileUpload::make('invoice_serial_number') ->label('Invoice Serial Number') @@ -306,8 +351,8 @@ class SerialValidationResource extends Resource ->storeFiles(false) // prevent auto-storing, we will store manually ->reactive() ->required() - ->disk('local') //'local' refers to the local storage disk defined in config/filesystems.php, typically pointing to storage/app. - ->visible(fn (Get $get) => !empty($get('plant_id'))) + ->disk('local') // 'local' refers to the local storage disk defined in config/filesystems.php, typically pointing to storage/app. + ->visible(fn (Get $get) => ! empty($get('plant_id'))) ->directory('uploads/temp'), ]) ->action(function (array $data) { @@ -330,42 +375,37 @@ class SerialValidationResource extends Resource // /home/iot-dev/projects/pds/storage/app/private/uploads/temp/3RA0018735.xlsx $totQuan = SerialValidation::where('invoice_number', $originalNameOnly)->count(); - if ($totQuan > 0) - { + if ($totQuan > 0) { $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(); - $plantName = $invoiceFirst ? (String)$invoiceFirst->plant->name : null; + $plantName = $invoiceFirst ? (string) $invoiceFirst->plant->name : null; Notification::make() ->title("Serial invoice number : '$originalNameOnly' already completed the scanning process for plant : '$plantName'.") ->danger() ->send(); - if ($disk->exists($path)) - { + if ($disk->exists($path)) { $disk->delete($path); } + return; - } - else - { + } else { $invoiceFirst = SerialValidation::with('plant')->where('invoice_number', $originalNameOnly)->first(); // $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; - if ($plantId != $invoicePlantId) - { + if ($plantId != $invoicePlantId) { Notification::make() ->title("Serial invoice number : '$originalNameOnly' already exists for plant : '$plantName'.
Choose the valid 'Plant' to proceed!") ->danger() ->send(); - if ($disk->exists($path)) - { + if ($disk->exists($path)) { $disk->delete($path); } + return; } } @@ -374,26 +414,23 @@ class SerialValidationResource extends Resource $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(); - if ($totQuan > 0 && $totQuan == $scanSQuan) - { + if ($totQuan > 0 && $totQuan == $scanSQuan) { Notification::make() ->title('Serial invoice already completed the scanning process for selected plant.') ->danger() ->send(); - if ($disk->exists($path)) - { + if ($disk->exists($path)) { $disk->delete($path); } + return; } - if ($fullPath && file_exists($fullPath)) - { + if ($fullPath && file_exists($fullPath)) { $rows = Excel::toArray(null, $fullPath)[0]; - if ((count($rows) - 1) <= 0) - { + if ((count($rows) - 1) <= 0) { Notification::make() ->title('Records Not Found') ->body("Import the valid 'Serial Invoice' file to proceed..!") @@ -403,6 +440,7 @@ class SerialValidationResource extends Resource if ($disk->exists($path)) { $disk->delete($path); } + return; } @@ -414,9 +452,10 @@ class SerialValidationResource extends Resource $seenSerialNumbers = []; $validRowsFound = false; - foreach ($rows as $index => $row) - { - if ($index == 0) continue; // Skip header + foreach ($rows as $index => $row) { + if ($index == 0) { + continue; + } // Skip header $materialCode = trim($row[0]); $serialNumber = trim($row[1]); @@ -425,24 +464,16 @@ class SerialValidationResource extends Resource continue; } - if (!empty($materialCode)) - { - if (Str::length($materialCode) < 6 || !ctype_alnum($materialCode)) - { + if (! empty($materialCode)) { + if (Str::length($materialCode) < 6 || ! ctype_alnum($materialCode)) { $invalidMatCodes[] = $materialCode; - } - else - { + } else { if (empty($serialNumber)) { $missingSerials[] = $materialCode; - } - else if (Str::length($serialNumber) < 9 || !ctype_alnum($serialNumber)) - { + } elseif (Str::length($serialNumber) < 9 || ! ctype_alnum($serialNumber)) { $invalidSerialCodes[] = $serialNumber; - } - else - { + } else { if (in_array($serialNumber, $seenSerialNumbers)) { $duplicateSerials[] = $serialNumber; } else { @@ -452,9 +483,7 @@ class SerialValidationResource extends Resource } } } - } - else - { + } else { continue; } } @@ -467,52 +496,53 @@ class SerialValidationResource extends Resource $duplicateSerialCodes = array_unique($duplicateSerials); - if (!empty($uniqueInvalidCodes)) { + if (! empty($uniqueInvalidCodes)) { Notification::make() ->title('Invalid Item Codes') - ->body('The following item codes should contain minimum 6 digit alpha numeric values:
' . implode(', ', $uniqueInvalidCodes)) + ->body('The following item codes should contain minimum 6 digit alpha numeric values:
'.implode(', ', $uniqueInvalidCodes)) ->danger() ->send(); if ($disk->exists($path)) { $disk->delete($path); } + return; - } - else if (!empty($uniqueMissingSerials)) { + } elseif (! empty($uniqueMissingSerials)) { Notification::make() ->title('Missing Serial Numbers') - ->body("The following item codes doesn't have valid serial number:
" . implode(', ', $uniqueMissingSerials)) + ->body("The following item codes doesn't have valid serial number:
".implode(', ', $uniqueMissingSerials)) ->danger() ->send(); if ($disk->exists($path)) { $disk->delete($path); } + return; - } - else if (!empty($uniqueSerialCodes)) { + } elseif (! empty($uniqueSerialCodes)) { Notification::make() ->title('Invalid Serial Number') - ->body('The following serial numbers should contain minimum 9 digit alpha numeric values:
' . implode(', ', $uniqueSerialCodes)) + ->body('The following serial numbers should contain minimum 9 digit alpha numeric values:
'.implode(', ', $uniqueSerialCodes)) ->danger() ->send(); if ($disk->exists($path)) { $disk->delete($path); } + return; - } - else if (!empty($duplicateSerialCodes)) { + } elseif (! empty($duplicateSerialCodes)) { Notification::make() ->title('Duplicate Serial Numbers') - ->body('The following serial numbers are already exist in imported excel:
' . implode(', ', $duplicateSerialCodes)) + ->body('The following serial numbers are already exist in imported excel:
'.implode(', ', $duplicateSerialCodes)) ->danger() ->send(); if ($disk->exists($path)) { $disk->delete($path); } + return; } - if (!$validRowsFound) { + if (! $validRowsFound) { Notification::make() ->title('Invalid Serial Invoice') ->danger() // This makes the notification red to indicate an error @@ -521,26 +551,26 @@ class SerialValidationResource extends Resource if ($disk->exists($path)) { $disk->delete($path); } + return; } $uniqueCodes = array_unique($materialCodes); $matchedItems = StickerMaster::with('item') - ->whereHas('item', function ($query) use ($uniqueCodes) { - $query->whereIn('code', $uniqueCodes); - }) - ->get(); + ->whereHas('item', function ($query) use ($uniqueCodes) { + $query->whereIn('code', $uniqueCodes); + }) + ->get(); $matchedCodes = $matchedItems->pluck('item.code')->toArray(); $missingCodes = array_diff($uniqueCodes, $matchedCodes); - if (!empty($missingCodes)) - { + if (! empty($missingCodes)) { $missingCount = count($missingCodes); - $message = $missingCount > 10 ? "'$missingCount' item codes are not found in database." : 'The following item codes are not found in database:
' . implode(', ', $missingCodes); + $message = $missingCount > 10 ? "'$missingCount' item codes are not found in database." : 'The following item codes are not found in database:
'.implode(', ', $missingCodes); Notification::make() ->title('Unknown Item Codes') @@ -551,43 +581,41 @@ class SerialValidationResource extends Resource if ($disk->exists($path)) { $disk->delete($path); } + return; } // Check which codes have a material_type set (not null) $invalidCodes = $matchedItems - ->filter(fn ($sticker) => !empty($sticker->material_type)) //filter invalid + ->filter(fn ($sticker) => ! empty($sticker->material_type)) // filter invalid ->pluck('item.code') ->toArray(); - if (count($invalidCodes) > 10) - { + if (count($invalidCodes) > 10) { Notification::make() ->title('Invalid item codes found') - ->body('' . count($invalidCodes) . 'item codes found have material type.') + ->body(''.count($invalidCodes).'item codes found have material type.') ->danger() ->send(); if ($disk->exists($path)) { $disk->delete($path); } + return; - } - else if (count($invalidCodes) > 0) - { + } elseif (count($invalidCodes) > 0) { Notification::make() ->title('Invalid item codes found') - ->body('Material invoice Item Codes found : ' . implode(', ', $invalidCodes)) + ->body('Material invoice Item Codes found : '.implode(', ', $invalidCodes)) ->danger() ->send(); if ($disk->exists($path)) { $disk->delete($path); } + return; - } - else - { + } else { // Save full file path to session session(['uploaded_invoice_path' => $fullPath]); Notification::make() @@ -597,7 +625,7 @@ class SerialValidationResource extends Resource } } }) - ->visible(function() { + ->visible(function () { return Filament::auth()->user()->can('view import serial validation invoice'); }), // Tables\Actions\Action::make('Import Invoice Material') @@ -921,7 +949,6 @@ class SerialValidationResource extends Resource // $excelCode = trim($row[0]); // $excelMatQty = trim($row[1]); - // if ($excelCode == $code && is_numeric($excelMatQty)) { // $totalExcelQty += $excelMatQty; // Sum up the quantities // } @@ -984,216 +1011,224 @@ class SerialValidationResource extends Resource ->label('Export Serial Invoices') ->color('warning') ->exporter(SerialValidationExporter::class) - ->visible(function() { + ->visible(function () { return Filament::auth()->user()->can('view export serial validation invoice'); }), ]) - // ->filters([ - // Tables\Filters\TrashedFilter::make(), - // ]) - ->filters([ + ->filters([ Tables\Filters\TrashedFilter::make(), Filter::make('advanced_filters') - ->label('Advanced Filters') - ->form([ - Radio::make('invoice_type') - ->label('Type ?') - ->boolean() - ->options([ - 'Serial' => 'Serial' - ]) - ->default('Serial') - ->inlineLabel(false) - ->inline(), - Select::make('Plant') - ->label('Select Plant') - ->nullable() - // ->options(function () { - // return Plant::pluck('name', 'id'); - // }) - ->options(function (callable $get) { - $userHas = Filament::auth()->user()->plant_id; - return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); - }) - ->reactive() - ->afterStateUpdated(function ($state, callable $set, callable $get): void { - $set('sticker_master_id', null); - $set('operator_id', null); - }), - TextInput::make('invoice_number') - ->label('Invoice Number') - // ->readOnly() - ->placeholder(placeholder: 'Enter Invoice Number'), - TextInput::make('serial_number') - ->label('Serial Number') - ->placeholder(placeholder: 'Enter Serial Number'), - Select::make('sticker_master_id') - ->label('Search by Item Code') - ->nullable() - ->options(function (callable $get) { - $pId = $get('Plant'); - // if (empty($pId)) { - // return []; - // } - return Item::whereHas('stickerMasters', function ($query) use ($pId) { - if ($pId) { - $query->where('plant_id', $pId); + ->label('Advanced Filters') + ->form([ + Radio::make('invoice_type') + ->label('Type ?') + ->boolean() + ->options([ + 'Serial' => 'Serial', + ]) + ->default('Serial') + ->inlineLabel(false) + ->inline(), + Select::make('Plant') + ->label('Select Plant') + ->nullable() + // ->options(function () { + // return Plant::pluck('name', 'id'); + // }) + ->options(function (callable $get) { + $userHas = Filament::auth()->user()->plant_id; + + return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); + }) + ->reactive() + ->afterStateUpdated(function ($state, callable $set, callable $get): void { + $set('sticker_master_id', null); + $set('operator_id', null); + }), + TextInput::make('invoice_number') + ->label('Invoice Number') + // ->readOnly() + ->placeholder(placeholder: 'Enter Invoice Number'), + TextInput::make('serial_number') + ->label('Serial Number') + ->placeholder(placeholder: 'Enter Serial Number'), + Select::make('sticker_master_id') + ->label('Search by Item Code') + ->nullable() + ->options(function (callable $get) { + $pId = $get('Plant'); + + // if (empty($pId)) { + // return []; + // } + return Item::whereHas('stickerMasters', function ($query) use ($pId) { + if ($pId) { + $query->where('plant_id', $pId); + } + $query->whereHas('invoiceValidations'); + })->pluck('code', 'id'); + }) + ->searchable() + ->reactive(), + Select::make('scanned_status') + ->label('Scanned Status') + ->nullable() + ->options([ + 'Scanned' => 'Scanned', + 'Pending' => 'Pending', + ]) + ->searchable() + ->reactive(), + Select::make('operator_id') + ->label('Created By') + ->nullable() + ->options(function (callable $get) { + $plantId = $get('Plant'); + if (! $plantId) { + return SerialValidation::whereNotNull('operator_id')->select('operator_id')->distinct()->pluck('operator_id', 'operator_id'); + } else { + return SerialValidation::where('plant_id', $plantId)->whereNotNull('operator_id')->select('operator_id')->distinct()->pluck('operator_id', 'operator_id'); } - $query->whereHas('invoiceValidations'); - })->pluck('code', 'id'); - }) - ->searchable() - ->reactive(), - Select::make('scanned_status') - ->label('Scanned Status') - ->nullable() - ->options([ - 'Scanned' => 'Scanned', - 'Pending' => 'Pending', - ]) - ->searchable() - ->reactive(), - Select::make('operator_id') - ->label('Created By') - ->nullable() - ->options(function (callable $get) { - $plantId = $get('Plant'); - if (!$plantId) - { - return SerialValidation::whereNotNull('operator_id')->select('operator_id')->distinct()->pluck('operator_id', 'operator_id'); + }) + ->searchable() + ->reactive(), + DateTimePicker::make(name: 'created_from') + ->label('Created From') + ->placeholder(placeholder: 'Select From DateTime') + ->reactive() + ->native(false), + DateTimePicker::make('created_to') + ->label('Created To') + ->placeholder(placeholder: 'Select To DateTime') + ->reactive() + ->native(false), + ]) + ->query(function ($query, array $data) { + // 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'])) { + Notification::make() + ->title('Please, choose invoice type to filter.') + ->danger() + ->send(); } - else - { - return SerialValidation::where('plant_id', $plantId)->whereNotNull('operator_id')->select('operator_id')->distinct()->pluck('operator_id', 'operator_id'); - } - }) - ->searchable() - ->reactive(), - DateTimePicker::make(name: 'created_from') - ->label('Created From') - ->placeholder(placeholder: 'Select From DateTime') - ->reactive() - ->native(false), - DateTimePicker::make('created_to') - ->label('Created To') - ->placeholder(placeholder: 'Select To DateTime') - ->reactive() - ->native(false), - ]) - ->query(function ($query, array $data) { - // 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'])) - { - Notification::make() - ->title('Please, choose invoice type to filter.') - ->danger() - ->send(); + + return $query->whereRaw('1 = 0'); } - return $query->whereRaw('1 = 0'); - } - if ($data['invoice_type'] == 'Serial') { - $query->whereNull('quantity'); + if ($data['invoice_type'] == 'Serial') { + $query->whereNull('quantity'); - if (!empty($data['scanned_status'])) { - if ($data['scanned_status'] == 'Scanned') { - $query->whereNotNull('scanned_status')->where('scanned_status', '!=', ''); - } elseif ($data['scanned_status'] == 'Pending') { - //$query->whereNull('scanned_status')->orWhere('scanned_status', ''); - $query->where(function ($query) use ($data) { - // if (empty($data['scanned_status']) || $data['scanned_status'] == 'Pending') { - $query->whereNull('scanned_status')->orWhere('scanned_status', '!=', 'Scanned'); - // } - }); + if (! empty($data['scanned_status'])) { + if ($data['scanned_status'] == 'Scanned') { + $query->whereNotNull('scanned_status')->where('scanned_status', '!=', ''); + } elseif ($data['scanned_status'] == 'Pending') { + // $query->whereNull('scanned_status')->orWhere('scanned_status', ''); + $query->where(function ($query) { + // if (empty($data['scanned_status']) || $data['scanned_status'] == 'Pending') { + $query->whereNull('scanned_status')->orWhere('scanned_status', '!=', 'Scanned'); + // } + }); + } + } + } elseif ($data['invoice_type'] == 'Material') { + $query->whereNotNull('quantity'); // ->where('quantity', '>', 0) + + if (! empty($data['scanned_status'])) { + if ($data['scanned_status'] == 'Scanned') { + $query->whereNotNull('serial_number')->where('serial_number', '!=', ''); + } elseif ($data['scanned_status'] == 'Pending') { + $query->where(function ($query) { + $query->whereNull('serial_number')->orWhere('serial_number', '=', ''); + }); + } } } - } elseif ($data['invoice_type'] == 'Material') { - $query->whereNotNull('quantity');//->where('quantity', '>', 0) - if (!empty($data['scanned_status'])) { - if ($data['scanned_status'] == 'Scanned') { - $query->whereNotNull('serial_number')->where('serial_number', '!=', ''); - } elseif ($data['scanned_status'] == 'Pending') { - $query->where(function ($query) use ($data) { - $query->whereNull('serial_number')->orWhere('serial_number', '=', ''); - }); + if (! empty($data['Plant'])) { // $plant = $data['Plant'] ?? null + $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['Plant'])) { //$plant = $data['Plant'] ?? null - $query->where('plant_id', $data['Plant']); - } - - if (!empty($data['invoice_number'])) { - $query->where('invoice_number', 'like', '%' . $data['invoice_number'] . '%'); - } - - if (!empty($data['serial_number'])) { - $query->where('serial_number', 'like', '%' . $data['serial_number'] . '%'); - } - - if (!empty($data['created_from'])) { - $query->where('created_at', '>=', $data['created_from']); - } - - if (!empty($data['created_to'])) { - $query->where('created_at', '<=', $data['created_to']); - } - - if (!empty($data['operator_id'])) { - $query->where('operator_id', $data['operator_id']); - } - - if (!empty($data['sticker_master_id'])) { - $stickerMasterIds = StickerMaster::where('item_id', $data['sticker_master_id']) - ->pluck('id') - ->toArray(); - - if (!empty($stickerMasterIds)) { - $query->whereIn('sticker_master_id', $stickerMasterIds); + if (! empty($data['invoice_number'])) { + $query->where('invoice_number', 'like', '%'.$data['invoice_number'].'%'); } - } - }) - ->indicateUsing(function (array $data) { - $indicators = []; - if (!empty($data['Plant'])) { - $indicators[] = 'Plant: ' . Plant::where('id', $data['Plant'])->value('name'); - } + if (! empty($data['serial_number'])) { + $query->where('serial_number', 'like', '%'.$data['serial_number'].'%'); + } - if (!empty($data['invoice_number'])) { - $indicators[] = 'Invoice Number: ' . $data['invoice_number']; - } + if (! empty($data['created_from'])) { + $query->where('created_at', '>=', $data['created_from']); + } - if (!empty($data['serial_number'])) { - $indicators[] = 'Serial Number: ' . $data['serial_number']; - } + if (! empty($data['created_to'])) { + $query->where('created_at', '<=', $data['created_to']); + } - if (!empty($data['sticker_master_id'])) { - $itemCode = Item::find($data['sticker_master_id'])->code ?? 'Unknown'; - $indicators[] = 'Item Code: ' . $itemCode; - } + if (! empty($data['operator_id'])) { + $query->where('operator_id', $data['operator_id']); + } - if (!empty($data['operator_id'])) { - $indicators[] = 'Created By: ' . $data['operator_id']; - } + if (! empty($data['sticker_master_id'])) { + $stickerMasterIds = StickerMaster::where('item_id', $data['sticker_master_id']) + ->pluck('id') + ->toArray(); - if (!empty($data['created_from'])) { - $indicators[] = 'From: ' . $data['created_from']; - } + if (! empty($stickerMasterIds)) { + $query->whereIn('sticker_master_id', $stickerMasterIds); + } + } + }) + ->indicateUsing(function (array $data) { + $indicators = []; - if (!empty($data['created_to'])) { - $indicators[] = 'To: ' . $data['created_to']; - } + if (! empty($data['Plant'])) { + $indicators[] = 'Plant: '.Plant::where('id', $data['Plant'])->value('name'); + } else { + $userHas = Filament::auth()->user()->plant_id; - if (!empty($data['scanned_status'])) { - $indicators[] = 'Scanned Status: ' . $data['scanned_status']; - } + if ($userHas && strlen($userHas) > 0) { + return 'Plant: Choose plant to filter records.'; + } + } - return $indicators; - }) + if (! empty($data['invoice_number'])) { + $indicators[] = 'Invoice Number: '.$data['invoice_number']; + } + + if (! empty($data['serial_number'])) { + $indicators[] = 'Serial Number: '.$data['serial_number']; + } + + if (! empty($data['sticker_master_id'])) { + $itemCode = Item::find($data['sticker_master_id'])->code ?? 'Unknown'; + $indicators[] = 'Item Code: '.$itemCode; + } + + if (! empty($data['operator_id'])) { + $indicators[] = 'Created By: '.$data['operator_id']; + } + + if (! empty($data['created_from'])) { + $indicators[] = 'From: '.$data['created_from']; + } + + if (! empty($data['created_to'])) { + $indicators[] = 'To: '.$data['created_to']; + } + + if (! empty($data['scanned_status'])) { + $indicators[] = 'Scanned Status: '.$data['scanned_status']; + } + + return $indicators; + }), ]) ->filtersFormMaxHeight('280px') ->actions([ diff --git a/app/Filament/Resources/TestingPanelReadingResource.php b/app/Filament/Resources/TestingPanelReadingResource.php index f7a19aa..865b064 100644 --- a/app/Filament/Resources/TestingPanelReadingResource.php +++ b/app/Filament/Resources/TestingPanelReadingResource.php @@ -2,8 +2,7 @@ namespace App\Filament\Resources; -use AlperenErsoy\FilamentExport\Actions\FilamentExportBulkAction; -use App\Exports\TestingPanelReadingExport; +use App\Exports\MotorFreeRunExport; use App\Filament\Exports\TestingPanelReadingExporter; use App\Filament\Imports\TestingPanelReadingImporter; use App\Filament\Resources\TestingPanelReadingResource\Pages; @@ -23,19 +22,24 @@ use Filament\Forms\Components\Select; use Filament\Forms\Components\TextInput; use Filament\Forms\Form; use Filament\Forms\Get; -use Filament\Notifications\Collection as NotificationsCollection; +use Filament\Notifications\Notification; use Filament\Resources\Resource; use Filament\Tables; +use Filament\Tables\Actions\Action; 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 Illuminate\Database\Eloquent\Builder; 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\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 { @@ -45,7 +49,7 @@ class TestingPanelReadingResource extends Resource protected static ?string $navigationGroup = 'Testing Panel'; - protected static ?int $navigationSort = 3; + protected static ?int $navigationSort = 3; public static function form(Form $form): Form { @@ -58,23 +62,23 @@ class TestingPanelReadingResource extends Resource ->reactive() ->options(function (callable $get) { $userHas = Filament::auth()->user()->plant_id; + return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); }) ->default(function () { return optional(TestingPanelReading::latest()->first())->plant_id; }) - ->disabled(fn (Get $get) => !empty($get('id'))) + ->disabled(fn (Get $get) => ! empty($get('id'))) ->afterStateUpdated(function ($state, callable $set, callable $get) { $plantId = $get('plant_id'); - if (!$plantId) { + if (! $plantId) { $set('line_id', null); $set('item_id', null); $set('machine_id', null); $set('tPrError', 'Please select a plant first.'); + return; - } - else - { + } else { $set('line_id', null); $set('item_id', null); $set('machine_id', null); @@ -91,9 +95,10 @@ class TestingPanelReadingResource extends Resource ->relationship('line', 'name') ->options(function (callable $get) { $plantId = $get('plant_id'); - if (!$plantId) { + if (! $plantId) { return []; } + return Line::where('plant_id', $plantId) ->pluck('name', 'id') ->toArray(); @@ -101,7 +106,7 @@ class TestingPanelReadingResource extends Resource ->default(function () { return optional(TestingPanelReading::latest()->first())->line_id; }) - ->disabled(fn (Get $get) => !empty($get('id'))) + ->disabled(fn (Get $get) => ! empty($get('id'))) ->required() ->reactive() ->afterStateUpdated(fn (callable $set) => $set('item_id', null)), @@ -110,9 +115,10 @@ class TestingPanelReadingResource extends Resource ->relationship('machine', 'name') ->options(function (callable $get) { $lineId = $get('line_id'); - if (!$lineId) { + if (! $lineId) { return []; } + // Only show machines for the selected line return Machine::where('line_id', $lineId) ->pluck('name', 'id') @@ -121,12 +127,12 @@ class TestingPanelReadingResource extends Resource ->default(function () { return optional(TestingPanelReading::latest()->first())->machine_id; }) - ->disabled(fn (Get $get) => !empty($get('id'))) + ->disabled(fn (Get $get) => ! empty($get('id'))) ->required() ->reactive(), Forms\Components\Select::make('motor_testing_master_id') ->label('Item Code') - //->relationship('motorTestingMaster', 'item.code') + // ->relationship('motorTestingMaster', 'item.code') // ->options(function (callable $get) { // $plantId = $get('plant_id'); // if (!$plantId) { @@ -141,9 +147,10 @@ class TestingPanelReadingResource extends Resource // }) ->options(function (callable $get) { $plantId = $get('plant_id'); - if (!$plantId) { + if (! $plantId) { return []; } + return MotorTestingMaster::query() ->join('items', 'motor_testing_masters.item_id', '=', 'items.id') ->where('motor_testing_masters.plant_id', $plantId) @@ -259,6 +266,7 @@ class TestingPanelReadingResource extends Resource public static function table(Table $table): Table { + return $table ->columns([ // Tables\Columns\TextColumn::make('id') @@ -271,6 +279,7 @@ class TestingPanelReadingResource extends Resource $paginator = $livewire->getTableRecords(); $perPage = method_exists($paginator, 'perPage') ? $paginator->perPage() : 10; $currentPage = method_exists($paginator, 'currentPage') ? $paginator->currentPage() : 1; + return ($currentPage - 1) * $perPage + $rowLoop->iteration; }), Tables\Columns\TextColumn::make('plant.name') @@ -463,7 +472,6 @@ class TestingPanelReadingResource extends Resource ->toggleable(isToggledHiddenByDefault: true), ]) ->filters([ - Tables\Filters\TrashedFilter::make(), Filter::make('advanced_filters') ->label('Advanced Filters') @@ -485,8 +493,7 @@ class TestingPanelReadingResource extends Resource ->nullable() ->options(function (callable $get) { $plantId = $get('Plant'); - if (!$plantId) - { + if (! $plantId) { return []; } @@ -509,14 +516,12 @@ class TestingPanelReadingResource extends Resource ->whereHas('motorTestingMasters') ->pluck('code', 'id') ->toArray(); - } - else - { + } else { return Item::whereHas('motorTestingMasters') - ->pluck('code', 'id') - ->toArray(); + ->pluck('code', 'id') + ->toArray(); } - //return []; + // return []; }) ->reactive(), Select::make('machine_name') @@ -525,9 +530,10 @@ class TestingPanelReadingResource extends Resource $plantId = $get('Plant'); $lineId = $get('Line'); - if (!$plantId || !$lineId) { + if (! $plantId || ! $lineId) { return []; } + return Machine::where('plant_id', $plantId) ->where('line_id', $lineId) ->pluck('name', 'id') @@ -548,6 +554,7 @@ class TestingPanelReadingResource extends Resource if ($plantId) { $query->where('plant_id', $plantId); } + return $query->pluck('description', 'description')->toArray(); }) @@ -595,23 +602,20 @@ class TestingPanelReadingResource extends Resource // } // }) // ->reactive(), - //... + // ... Select::make('connection') ->label('Connection') ->required() ->default('Star') ->options(function (callable $get) { $plantId = $get('Plant'); - if ($plantId) - { + if ($plantId) { return Configuration::where('plant_id', $plantId) - ->where('c_name', 'MOTOR_CONNECTION') - ->orderBy('created_at') - ->pluck('c_value', 'c_value') - ->toArray(); - } - else - { + ->where('c_name', 'MOTOR_CONNECTION') + ->orderBy('created_at') + ->pluck('c_value', 'c_value') + ->toArray(); + } else { return Configuration::where('c_name', 'MOTOR_CONNECTION') ->orderBy('created_at') ->pluck('c_value', 'c_value') @@ -620,7 +624,7 @@ class TestingPanelReadingResource extends Resource }) ->selectablePlaceholder(false) ->reactive(), - //.. + // .. TextInput::make('remark') ->label('Remark') ->reactive(), @@ -652,153 +656,156 @@ class TestingPanelReadingResource extends Resource ->placeholder(placeholder: 'Select To DateTime') ->reactive() ->native(false), - ]) - ->query(function ($query, array $data) { + ]) + ->query(function ($query, array $data) { - // dd($data); - // Hide all records initially if no filters are applied - if (empty($data['Plant']) && empty($data['Line']) && empty($data['item_code']) && empty($data['machine_name']) && empty($data['item_description']) && empty($data['serial_number']) && empty($data['output']) && empty($data['phase']) && empty($data['connection']) && empty($data['remark']) && empty($data['batch_no'])&& empty($data['result']) && empty($data['created_from']) && empty($data['created_to'])) { - return $query->whereRaw('1 = 0'); - } - - // if (empty($data['Plant']) && empty($data['Line']) && empty($data['item_code']) && empty($data['machine_name']) && empty($data['item_description']) && empty($data['serial_number']) && empty($data['output']) && empty($data['phase']) && !empty($data['connection']) && empty($data['remark']) && empty($data['batch_no'])&& empty($data['result']) && empty($data['created_from']) && empty($data['created_to'])) { - // return $query->whereRaw('1 = 0'); - // } - - if (!empty($data['Plant'])) { - $query->where('plant_id', $data['Plant']); - } - - if (!empty($data['Line'])) { - $query->where('line_id', $data['Line']); - } - - if (!empty($data['item_code'])) { - // $query->where('item_id', $data['item_code']); - $query->whereHas('motorTestingMaster', function ($subQuery) use ($data) { - $subQuery->where('item_id', $data['item_code']); - }); - } - - if (!empty($data['machine_name'])) { - $query->where('machine_id', $data['machine_name']); - } - - if (!empty($data['serial_number'])) { - $query->where('serial_number', $data['serial_number']); - } - - if (!empty($data['item_description'])) { - $item = Item::where('description', $data['item_description'])->first(); - - if ($item) { - $query->whereHas('motorTestingMaster', function ($subQuery) use ($item) { - $subQuery->where('item_id', $item->id); - }); - } else { - $query->whereRaw('1 = 0'); + // dd($data); + // Hide all records initially if no filters are applied + if (empty($data['Plant']) && empty($data['Line']) && empty($data['item_code']) && empty($data['machine_name']) && empty($data['item_description']) && empty($data['serial_number']) && empty($data['output']) && empty($data['phase']) && empty($data['connection']) && empty($data['remark']) && empty($data['batch_no']) && empty($data['result']) && empty($data['created_from']) && empty($data['created_to'])) { + return $query->whereRaw('1 = 0'); } - } - if (!empty($data['output'])) - { - $query->where('output',$data['output']); - } + // if (empty($data['Plant']) && empty($data['Line']) && empty($data['item_code']) && empty($data['machine_name']) && empty($data['item_description']) && empty($data['serial_number']) && empty($data['output']) && empty($data['phase']) && !empty($data['connection']) && empty($data['remark']) && empty($data['batch_no'])&& empty($data['result']) && empty($data['created_from']) && empty($data['created_to'])) { + // return $query->whereRaw('1 = 0'); + // } - // if (!empty($data['phase'])) - // { - // //$query->where('phase',$data['phase']); - // $query->whereHas('motorTestingMaster', function ($subQuery) use ($data) { - // $subQuery->where('phase', $data['phase']); - // }); - // } + if (! empty($data['Plant'])) { + $query->where('plant_id', $data['Plant']); + } else { + $userHas = Filament::auth()->user()->plant_id; - if (!empty($data['connection'])) - { - //$query->where('connection',$data['connection']); - $query->whereHas('motorTestingMaster', function ($subQuery) use ($data) { - $subQuery->where('connection', $data['connection']); - }); - } + if ($userHas && strlen($userHas) > 0) { + return $query->whereRaw('1 = 0'); + } + } - if (!empty($data['remark'])) - { - $query->where('remark',$data['remark']); - } + if (! empty($data['Line'])) { + $query->where('line_id', $data['Line']); + } - if (!empty($data['batch_number'])) - { - $query->where('batch_number',$data['batch_number']); - } + if (! empty($data['item_code'])) { + // $query->where('item_id', $data['item_code']); + $query->whereHas('motorTestingMaster', function ($subQuery) use ($data) { + $subQuery->where('item_id', $data['item_code']); + }); + } - if (!empty($data['result'])) - { - $query->where('result', $data['result']); - } + if (! empty($data['machine_name'])) { + $query->where('machine_id', $data['machine_name']); + } + if (! empty($data['serial_number'])) { + $query->where('serial_number', $data['serial_number']); + } - if (!empty($data['created_from'])) - { - $query->where('created_at', '>=', $data['created_from']); - } + if (! empty($data['item_description'])) { + $item = Item::where('description', $data['item_description'])->first(); - if (!empty($data['created_to'])) - { - $query->where('created_at', '<=', $data['created_to']); - } - }) - ->indicateUsing(function (array $data) { - $indicators = []; + if ($item) { + $query->whereHas('motorTestingMaster', function ($subQuery) use ($item) { + $subQuery->where('item_id', $item->id); + }); + } else { + $query->whereRaw('1 = 0'); + } + } - if (!empty($data['Plant'])) { - $indicators[] = 'Plant: ' . Plant::where('id', $data['Plant'])->value('name'); - } - if (!empty($data['Line'])) { - $indicators[] = 'Line: ' . Line::where('id', $data['Line'])->value('name'); - } - if (!empty($data['item_code'])) { - $indicators[] = 'Item Code: ' . Item::where('id', $data['item_code'])->value('code'); - } - if (!empty($data['machine_name'])) { - $indicators[] = 'Machine: ' . Machine::where('id', $data['machine_name'])->value('name'); - } - if (!empty($data['output'])) { - $indicators[] = 'Output: ' . $data['output']; - } - if (!empty($data['item_description'])) { - $indicators[] = 'Model: ' . $data['item_description']; - } - // if (!empty($data['phase'])) { - // $indicators[] = 'Phase: ' . $data['phase']; - // } - // if (!empty($data['connection'])) { - // $indicators[] = 'Connection: ' . $data['connection']; - // } - if (!empty($data['remark'])) { - $indicators[] = 'Remark: ' . $data['remark']; - } - if (!empty($data['batch_number'])) { - $indicators[] = 'Batch Number: ' . $data['batch_number']; - } - if (!empty($data['result'])) - { - $indicators[] = 'Result: ' . $data['result']; - } + if (! empty($data['output'])) { + $query->where('output', $data['output']); + } - if (!empty($data['serial_number'])) { - $indicators[] = 'Serial Number: ' . $data['serial_number']; - } + // if (!empty($data['phase'])) + // { + // //$query->where('phase',$data['phase']); + // $query->whereHas('motorTestingMaster', function ($subQuery) use ($data) { + // $subQuery->where('phase', $data['phase']); + // }); + // } - if (!empty($data['created_from'])) { - $indicators[] = 'From: ' . $data['created_from']; - } + if (! empty($data['connection'])) { + // $query->where('connection',$data['connection']); + $query->whereHas('motorTestingMaster', function ($subQuery) use ($data) { + $subQuery->where('connection', $data['connection']); + }); + } - if (!empty($data['created_to'])) { - $indicators[] = 'To: ' . $data['created_to']; - } + if (! empty($data['remark'])) { + $query->where('remark', $data['remark']); + } - return $indicators; - }) + if (! empty($data['batch_number'])) { + $query->where('batch_number', $data['batch_number']); + } + + if (! empty($data['result'])) { + $query->where('result', $data['result']); + } + + if (! empty($data['created_from'])) { + $query->where('created_at', '>=', $data['created_from']); + } + + if (! empty($data['created_to'])) { + $query->where('created_at', '<=', $data['created_to']); + } + }) + ->indicateUsing(function (array $data) { + $indicators = []; + + if (! empty($data['Plant'])) { + $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'])) { + $indicators[] = 'Line: '.Line::where('id', $data['Line'])->value('name'); + } + if (! empty($data['item_code'])) { + $indicators[] = 'Item Code: '.Item::where('id', $data['item_code'])->value('code'); + } + if (! empty($data['machine_name'])) { + $indicators[] = 'Machine: '.Machine::where('id', $data['machine_name'])->value('name'); + } + if (! empty($data['output'])) { + $indicators[] = 'Output: '.$data['output']; + } + if (! empty($data['item_description'])) { + $indicators[] = 'Model: '.$data['item_description']; + } + // if (!empty($data['phase'])) { + // $indicators[] = 'Phase: ' . $data['phase']; + // } + // if (!empty($data['connection'])) { + // $indicators[] = 'Connection: ' . $data['connection']; + // } + if (! empty($data['remark'])) { + $indicators[] = 'Remark: '.$data['remark']; + } + if (! empty($data['batch_number'])) { + $indicators[] = 'Batch Number: '.$data['batch_number']; + } + if (! empty($data['result'])) { + $indicators[] = 'Result: '.$data['result']; + } + + if (! empty($data['serial_number'])) { + $indicators[] = 'Serial Number: '.$data['serial_number']; + } + + if (! empty($data['created_from'])) { + $indicators[] = 'From: '.$data['created_from']; + } + + if (! empty($data['created_to'])) { + $indicators[] = 'To: '.$data['created_to']; + } + + return $indicators; + }), ]) ->filtersFormMaxHeight('280px') ->actions([ @@ -810,168 +817,355 @@ class TestingPanelReadingResource extends Resource Tables\Actions\DeleteBulkAction::make(), Tables\Actions\ForceDeleteBulkAction::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') - ->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' - ); + ->label('Export Selected to Excel') + ->action(function ($records) { + // $ids = $records->pluck('id')->toArray(); + // $query = TestingPanelReading::whereIn('id', $ids); + $templatePath = storage_path('app/private/uploads/temp/MotorTestingPanelReportTemplate.xlsx'); + return Excel::download(new MotorFreeRunExport($records, $templatePath), 'MotorFreeRunData.xlsx'); }) ->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') ->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'); $plantId = $records->first()?->plant_id; @@ -984,13 +1178,12 @@ class TestingPanelReadingResource extends Resource // return $record->motorTestingMaster?->connection === 'Star-Delta'; // }); - //dd($isAllStarDelta); - if(!$isAllStarDelta) - { + // dd($isAllStarDelta); + if (! $isAllStarDelta) { $mappedData = collect($records)->map(function ($record) { - return [ + return [ // 'Date' => $record['created_at'] ?? '', - 'Date' =>date('Y-m-d', strtotime($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 ?? '', @@ -1024,13 +1217,11 @@ class TestingPanelReadingResource extends Resource 'Remark' => $record['remark'] ?? '', ]; }); - } - else - { + } else { $mappedData = collect($records)->map(function ($record) { - return [ + return [ // 'Date' => $record['created_at'] ?? '', - 'Date' =>date('Y-m-d', strtotime($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 ?? '', @@ -1070,7 +1261,6 @@ class TestingPanelReadingResource extends Resource }); } - $view = $isAllStarDelta ? 'exports.export-isi-three-phase-pdf' : 'exports.export-isi-pdf'; $pdf = Pdf::loadView($view, [ @@ -1086,24 +1276,27 @@ class TestingPanelReadingResource extends Resource // ]); return response()->streamDownload( - fn () => print($pdf->stream()), + fn () => print ($pdf->stream()), 'TestingPanelReading.pdf' ); }) ->icon('heroicon-o-document-arrow-down'), ]), - ]) ->headerActions([ ImportAction::make() + ->label('Import Testing Panel Readings') + ->color('warning') ->importer(TestingPanelReadingImporter::class) - ->visible(function() { + ->visible(function () { return Filament::auth()->user()->can('view import testing panel reading'); }), ExportAction::make() + ->label('Export Testing Panel Readings') + ->color('warning') ->exporter(TestingPanelReadingExporter::class) - ->visible(function() { + ->visible(function () { return Filament::auth()->user()->can('view export testing panel reading'); }), ]); diff --git a/app/Filament/Resources/WeightValidationResource.php b/app/Filament/Resources/WeightValidationResource.php index 881827a..b07f263 100644 --- a/app/Filament/Resources/WeightValidationResource.php +++ b/app/Filament/Resources/WeightValidationResource.php @@ -5,14 +5,10 @@ namespace App\Filament\Resources; use App\Filament\Exports\WeightValidationExporter; use App\Filament\Imports\WeightValidationImporter; use App\Filament\Resources\WeightValidationResource\Pages; -use App\Filament\Resources\WeightValidationResource\RelationManagers; use App\Models\Item; -use App\Models\Line; use App\Models\Plant; -use App\Models\QualityValidation; use App\Models\StickerMaster; use App\Models\WeightValidation; -use Filament\Actions\Action; use Filament\Facades\Filament; use Filament\Forms; use Filament\Forms\Components\DateTimePicker; @@ -26,14 +22,13 @@ use Filament\Resources\Resource; use Filament\Tables; use Filament\Tables\Actions\ExportAction; use Filament\Tables\Actions\ImportAction; +use Filament\Tables\Filters\Filter; use Filament\Tables\Table; -use Filament\Widgets\StatsOverviewWidget\Stat; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\SoftDeletingScope; use Illuminate\Support\Facades\Storage; use Maatwebsite\Excel\Facades\Excel; use Str; -use Filament\Tables\Filters\Filter; class WeightValidationResource extends Resource { @@ -51,6 +46,7 @@ class WeightValidationResource extends Resource ->relationship('plant', 'name') ->options(function (callable $get) { $userHas = Filament::auth()->user()->plant_id; + return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); }) ->required(), @@ -80,7 +76,7 @@ class WeightValidationResource extends Resource Forms\Components\TextInput::make('picked_weight') ->label('Picked Weight'), Forms\Components\TextInput::make('scanned_by') - ->label('Scanned By') + ->label('Scanned By'), ]); } @@ -98,6 +94,7 @@ class WeightValidationResource extends Resource $paginator = $livewire->getTableRecords(); $perPage = method_exists($paginator, 'perPage') ? $paginator->perPage() : 10; $currentPage = method_exists($paginator, 'currentPage') ? $paginator->currentPage() : 1; + return ($currentPage - 1) * $perPage + $rowLoop->iteration; }), Tables\Columns\TextColumn::make('plant.name') @@ -157,9 +154,6 @@ class WeightValidationResource extends Resource ->sortable() ->toggleable(isToggledHiddenByDefault: true), ]) - // ->filters([ - // Tables\Filters\TrashedFilter::make(), - // ]) ->filters([ Tables\Filters\TrashedFilter::make(), Filter::make('advanced_filters') @@ -173,25 +167,41 @@ class WeightValidationResource extends Resource // }) ->options(function (callable $get) { $userHas = Filament::auth()->user()->plant_id; + return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); }) ->reactive(), - // ->afterStateUpdated(function ($state, callable $set, callable $get) { - // $set('sticker_master_id', null); - // $set('sap_msg_status', null); - // }), - Select::make('Item Code') + // ->afterStateUpdated(function ($state, callable $set, callable $get) { + // $set('sticker_master_id', null); + // $set('sap_msg_status', null); + // }), + + Select::make('Item Code') ->label('Search by Item Code') ->nullable() + // ->options(function (callable $get) { + // $plantId = $get('Plant'); + // if (! $plantId) { + // return []; + // } + + // return Item::where('plant_id', $plantId)->pluck('code', 'id'); + // }) ->options(function (callable $get) { $plantId = $get('Plant'); - if (!$plantId) { + if (! $plantId) { 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() ->reactive(), + TextInput::make('Obd Number') ->label('OBD Number') ->placeholder('Enter OBD Number'), @@ -201,7 +211,7 @@ class WeightValidationResource extends Resource ->options(function (callable $get) { $plantId = $get('Plant'); - if (!$plantId) { + if (! $plantId) { return []; } @@ -243,125 +253,137 @@ class WeightValidationResource extends Resource ->placeholder(placeholder: 'Select From DateTime') ->reactive() ->native(false), + DateTimePicker::make('created_to') ->label('Created To') ->placeholder(placeholder: 'Select To DateTime') ->reactive() ->native(false), - ]) - ->query(function ($query, array $data) { - //Hide all records initially if no filters are applied - if (empty($data['Plant']) && empty($data['Item Code']) && empty($data['Line']) && empty($data['Obd Number']) && empty($data['Batch']) && empty($data['Actual Weight']) && empty($data['Vehicle Number']) && empty($data['Heat Number']) && empty($data['Bundle Number']) && empty($data['Scanned By']) && empty($data['created_from']) && empty($data['created_to'])) { - return $query->whereRaw('1 = 0'); - } + ]) + ->query(function ($query, array $data) { + // Hide all records initially if no filters are applied + if (empty($data['Plant']) && empty($data['Item Code']) && empty($data['Line']) && empty($data['Obd Number']) && empty($data['Batch']) && empty($data['Actual Weight']) && empty($data['Vehicle Number']) && empty($data['Heat Number']) && empty($data['Bundle Number']) && empty($data['Scanned By']) && empty($data['created_from']) && empty($data['created_to'])) { + return $query->whereRaw('1 = 0'); + } - if (!empty($data['Plant'])) { - $query->where('plant_id', $data['Plant']); - } + if (! empty($data['Plant'])) { + $query->where('plant_id', $data['Plant']); + } else { + $userHas = Filament::auth()->user()->plant_id; - if (!empty($data['Item Code'])) { - $query->where('item_id', $data['Item Code']); - } + if ($userHas && strlen($userHas) > 0) { + return $query->whereRaw('1 = 0'); + } + } - if (!empty($data['Line'])) { - $query->where('line_number', $data['Line']); - } + if (! empty($data['Item Code'])) { + $query->where('item_id', $data['Item Code']); + } - if (!empty($data['Obd Number'])) { - $query->where('obd_number', $data['Obd Number']); - } + if (! empty($data['Line'])) { + $query->where('line_number', $data['Line']); + } - if (!empty($data['Batch'])) { - $query->where('batch_number', $data['Batch']); - } + if (! empty($data['Obd Number'])) { + $query->where('obd_number', $data['Obd Number']); + } - if (!empty($data['Actual Weight'])) { - $query->where('actual_weight', $data['Actual Weight']); - } + if (! empty($data['Batch'])) { + $query->where('batch_number', $data['Batch']); + } - if (!empty($data['Vehicle Number'])) { - $query->where('vehicle_number',$data['Vehicle Number']); - } + if (! empty($data['Actual Weight'])) { + $query->where('actual_weight', $data['Actual Weight']); + } - if (!empty($data['Heat Number'])) { - $query->where('heat_number',$data['Heat Number']); - } + if (! empty($data['Vehicle Number'])) { + $query->where('vehicle_number', $data['Vehicle Number']); + } - if (!empty($data['Bundle Number'])) { - $query->where('bundle_number',$data['Bundle Number']); - } + if (! empty($data['Heat Number'])) { + $query->where('heat_number', $data['Heat Number']); + } - if (!empty($data['Scanned By'])) { - $query->where('scanned_by', $data['Scanned By']); - } + if (! empty($data['Bundle Number'])) { + $query->where('bundle_number', $data['Bundle Number']); + } + if (! empty($data['Scanned By'])) { + $query->where('scanned_by', $data['Scanned By']); + } - if (!empty($data['created_from'])) { - $query->where('created_at', '>=', $data['created_from']); - } + if (! empty($data['created_from'])) { + $query->where('created_at', '>=', $data['created_from']); + } - if (!empty($data['created_to'])) { - $query->where('created_at', '<=', $data['created_to']); - } - }) - ->indicateUsing(function (array $data) { - $indicators = []; + if (! empty($data['created_to'])) { + $query->where('created_at', '<=', $data['created_to']); + } + }) + ->indicateUsing(function (array $data) { + $indicators = []; - if (!empty($data['Plant'])) { - $indicators[] = 'Plant: ' . Plant::where('id', $data['Plant'])->value('name'); - } + if (! empty($data['Plant'])) { + $indicators[] = 'Plant: '.Plant::where('id', $data['Plant'])->value('name'); + } else { + $userHas = Filament::auth()->user()->plant_id; - if (!empty($data['Item Code'])) { - $indicators[] = 'Item Code: ' . $data['Item Code']; - } + if ($userHas && strlen($userHas) > 0) { + return 'Plant: Choose plant to filter records.'; + } + } - if (!empty($data['Line'])) { - $indicators[] = 'Line: ' . $data['Line']; - } + if (! empty($data['Item Code'])) { + $indicators[] = 'Item Code: '.$data['Item Code']; + } - if (!empty($data['Obd Number'])) { - $indicators[] = 'OBD Number: ' . $data['Obd Number']; - } + if (! empty($data['Line'])) { + $indicators[] = 'Line: '.$data['Line']; + } - if (!empty($data['Batch'])) { - $indicators[] = 'Batch Number: ' . $data['Batch']; - } + if (! empty($data['Obd Number'])) { + $indicators[] = 'OBD Number: '.$data['Obd Number']; + } - if (!empty($data['Actual Weight'])) { - $indicators[] = 'Actual Weight: ' . $data['Actual Weight']; - } + if (! empty($data['Batch'])) { + $indicators[] = 'Batch Number: '.$data['Batch']; + } - if (!empty($data['Vehicle Number'])) { - $indicators[] = 'Vehicle Number: ' . $data['Vehicle Number']; - } + if (! empty($data['Actual Weight'])) { + $indicators[] = 'Actual Weight: '.$data['Actual Weight']; + } - if (!empty($data['Heat Number'])) { - $indicators[] = 'Heat Number: ' . $data['Heat Number']; - } + if (! empty($data['Vehicle Number'])) { + $indicators[] = 'Vehicle Number: '.$data['Vehicle Number']; + } - if (!empty($data['Bundle Number'])) { - $indicators[] = 'Bundle Number: ' . $data['Bundle Number']; - } + if (! empty($data['Heat Number'])) { + $indicators[] = 'Heat Number: '.$data['Heat Number']; + } - if (!empty($data['Scanned By'])) { - $indicators[] = 'Scanned By: ' . $data['Scanned By']; - } + if (! empty($data['Bundle Number'])) { + $indicators[] = 'Bundle Number: '.$data['Bundle Number']; + } - if (!empty($data['created_from'])) { - $indicators[] = 'From: ' . $data['created_from']; - } + if (! empty($data['Scanned By'])) { + $indicators[] = 'Scanned By: '.$data['Scanned By']; + } - if (!empty($data['created_to'])) { - $indicators[] = 'To: ' . $data['created_to']; - } + if (! empty($data['created_from'])) { + $indicators[] = 'From: '.$data['created_from']; + } - if (!empty($data['sticker_master_id'])) { - $itemCode = Item::find($data['sticker_master_id'])->code ?? 'Unknown'; - $indicators[] = 'Item Codes: ' . $itemCode; - } + if (! empty($data['created_to'])) { + $indicators[] = 'To: '.$data['created_to']; + } - return $indicators; - }) + if (! empty($data['sticker_master_id'])) { + $itemCode = Item::find($data['sticker_master_id'])->code ?? 'Unknown'; + $indicators[] = 'Item Codes: '.$itemCode; + } + + return $indicators; + }), ]) ->filtersFormMaxHeight('280px') ->actions([ @@ -383,6 +405,7 @@ class WeightValidationResource extends Resource // ->options(Plant::pluck('name', 'id')->toArray()) ->options(function (callable $get) { $userHas = Filament::auth()->user()->plant_id; + return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); }) ->label('Select Plant') @@ -401,8 +424,8 @@ class WeightValidationResource extends Resource ->storeFiles(false) // prevent auto-storing, we will store manually ->reactive() ->required() - ->disk('local') //'local' refers to the local storage disk defined in config/filesystems.php, typically pointing to storage/app. - ->visible(fn (Get $get) => !empty($get('plant_id'))) + ->disk('local') // 'local' refers to the local storage disk defined in config/filesystems.php, typically pointing to storage/app. + ->visible(fn (Get $get) => ! empty($get('plant_id'))) ->directory('uploads/temp'), ]) ->action(function (array $data) { @@ -425,20 +448,20 @@ class WeightValidationResource extends Resource // /home/iot-dev/projects/pds/storage/app/private/uploads/temp/3RA0018735.xlsx - $totQuan = WeightValidation::where('obd_number',$originalNameOnly)->where('plant_id', $plantId)->count(); - $scanSQuan = WeightValidation::where('obd_number',$originalNameOnly)->where('plant_id', $plantId)->whereNotNull('vehicle_number')->where('vehicle_number', '!=', '')->count(); + $totQuan = WeightValidation::where('obd_number', $originalNameOnly)->where('plant_id', $plantId)->count(); + $scanSQuan = WeightValidation::where('obd_number', $originalNameOnly)->where('plant_id', $plantId)->whereNotNull('vehicle_number')->where('vehicle_number', '!=', '')->count(); - if($totQuan == $scanSQuan && $totQuan > 0) { + if ($totQuan == $scanSQuan && $totQuan > 0) { Notification::make() ->title('Completed: OBD invoice') ->body('OBD invoice already completed the scanning process for selected plant.') ->danger() ->send(); - if ($disk->exists($path)) - { + if ($disk->exists($path)) { $disk->delete($path); } + return; } @@ -458,7 +481,7 @@ class WeightValidationResource extends Resource if ($fullPath && file_exists($fullPath)) { $rows = Excel::toArray(null, $fullPath)[0]; - if((count($rows) - 1) <= 0) { + if ((count($rows) - 1) <= 0) { Notification::make() ->title('Records Not Found') ->body("Import the valid 'OBD Invoice' file to proceed..!") @@ -469,6 +492,7 @@ class WeightValidationResource extends Resource if ($disk->exists($path)) { $disk->delete($path); } + return; } @@ -482,9 +506,10 @@ class WeightValidationResource extends Resource $lineNumbers = []; $validRowsFound = false; - foreach ($rows as $index => $row) - { - if ($index === 0) continue; // Skip header + foreach ($rows as $index => $row) { + if ($index === 0) { + continue; + } // Skip header $materialCode = trim($row[0]); $lineNumber = trim($row[1]); @@ -496,32 +521,24 @@ class WeightValidationResource extends Resource continue; } - if (!empty($materialCode)) { - if(Str::length($materialCode) < 6 || !ctype_alnum($materialCode)) - { + if (! empty($materialCode)) { + if (Str::length($materialCode) < 6 || ! ctype_alnum($materialCode)) { $invalidMatCodes[] = $materialCode; + continue; - } - else - { + } else { $materialCodes[] = $materialCode; $validData = true; - if(Str::length($lineNumber) < 1 || !is_numeric($lineNumber)) - { + if (Str::length($lineNumber) < 1 || ! is_numeric($lineNumber)) { $validData = false; $invalidLines[] = $materialCode; - } - else if (in_array($lineNumber, $lineNumbers)) - { + } elseif (in_array($lineNumber, $lineNumbers)) { $duplicateLines[] = $materialCode; - } - else - { + } else { $lineNumbers[] = $lineNumber; } - if(Str::length($batchNumber) < 8 || !is_numeric($batchNumber))//ctype_alnum - { + if (Str::length($batchNumber) < 8 || ! is_numeric($batchNumber)) {// ctype_alnum $validData = false; $invalidBatch[] = $materialCode; } @@ -530,29 +547,25 @@ class WeightValidationResource extends Resource // $validData = false; // $invalidHeat[] = $materialCode; // } - if(Str::length($actualWeight) < 1 || !is_numeric($actualWeight))//ctype_alnum - { + if (Str::length($actualWeight) < 1 || ! is_numeric($actualWeight)) {// ctype_alnum $validData = false; $invalidWeight[] = $materialCode; } - if ($validData) - { + if ($validData) { $validRowsFound = true; } } - } - else - { + } else { continue; } } $uniqueInvalidCodes = array_unique($invalidMatCodes); - if (!empty($uniqueInvalidCodes)) { + if (! empty($uniqueInvalidCodes)) { Notification::make() ->title('Invalid: Item Codes') - ->body('The following item codes should contain minimum 6 digit alpha numeric values:
' . implode(', ', $uniqueInvalidCodes)) + ->body('The following item codes should contain minimum 6 digit alpha numeric values:
'.implode(', ', $uniqueInvalidCodes)) ->danger() ->seconds(2) ->send(); @@ -560,51 +573,55 @@ class WeightValidationResource extends Resource if ($disk->exists($path)) { $disk->delete($path); } + return; } $uniqueInvalidLines = array_unique($invalidLines); - if (!empty($uniqueInvalidLines)) { + if (! empty($uniqueInvalidLines)) { Notification::make() - ->title('Invalid: Line Numbers') - ->body('Line number should contain minimum 1 digit numeric values!
Following item codes has invalid line number:
' . implode(', ', $uniqueInvalidLines)) - ->danger() - ->seconds(2) - ->send(); + ->title('Invalid: Line Numbers') + ->body('Line number should contain minimum 1 digit numeric values!
Following item codes has invalid line number:
'.implode(', ', $uniqueInvalidLines)) + ->danger() + ->seconds(2) + ->send(); if ($disk->exists($path)) { $disk->delete($path); } + return; } $uniqueDupLines = array_unique($duplicateLines); - if (!empty($uniqueDupLines)) { + if (! empty($uniqueDupLines)) { Notification::make() - ->title('Duplicate: Line Numbers') - ->body('The following item codes contains duplicate line numbers in invoice excel:
' . implode(', ', $uniqueDupLines)) - ->danger() - ->seconds(2) - ->send(); + ->title('Duplicate: Line Numbers') + ->body('The following item codes contains duplicate line numbers in invoice excel:
'.implode(', ', $uniqueDupLines)) + ->danger() + ->seconds(2) + ->send(); if ($disk->exists($path)) { $disk->delete($path); } + return; } $uniqueInvalidBatch = array_unique($invalidBatch); - if (!empty($uniqueInvalidBatch)) { + if (! empty($uniqueInvalidBatch)) { Notification::make() - ->title('Invalid: Batch Numbers') - ->body('Batch number should contain minimum 8 digit numeric values!
Following item codes has invalid batch number:
' . implode(', ', $uniqueInvalidBatch)) - ->danger() - ->seconds(2) - ->send(); + ->title('Invalid: Batch Numbers') + ->body('Batch number should contain minimum 8 digit numeric values!
Following item codes has invalid batch number:
'.implode(', ', $uniqueInvalidBatch)) + ->danger() + ->seconds(2) + ->send(); if ($disk->exists($path)) { $disk->delete($path); } + return; } @@ -624,23 +641,24 @@ class WeightValidationResource extends Resource // } $uniqueInvalidWeight = array_unique($invalidWeight); - if (!empty($uniqueInvalidWeight)) { + if (! empty($uniqueInvalidWeight)) { Notification::make() - ->title('Invalid: Actual Weights') - ->body('Actual weight should contain minimum 1 digit numeric value!
Following item codes has invalid actual weight:
' . implode(', ', $uniqueInvalidWeight)) - ->danger() - ->seconds(2) - ->send(); + ->title('Invalid: Actual Weights') + ->body('Actual weight should contain minimum 1 digit numeric value!
Following item codes has invalid actual weight:
'.implode(', ', $uniqueInvalidWeight)) + ->danger() + ->seconds(2) + ->send(); if ($disk->exists($path)) { $disk->delete($path); } + return; } $uniqueCodes = array_unique($materialCodes); - //itemNotFound. + // itemNotFound. $matchedItems = Item::whereIn('code', $uniqueCodes)->get(); // // Get all codes that exist in the database for the given plant_id @@ -653,37 +671,13 @@ class WeightValidationResource extends Resource // ->pluck('item.code') // ->toArray(); - $matchedCodes = $matchedItems->pluck('code')->toArray(); //item.code + $matchedCodes = $matchedItems->pluck('code')->toArray(); // item.code $missingCodes = array_diff($uniqueCodes, $matchedCodes); - if (!empty($missingCodes)) { + if (! empty($missingCodes)) { $missingCount = count($missingCodes); - $message = $missingCount > 10 ? "'$missingCount' item codes are not found in database." : 'The following item codes are not found in database:
' . implode(', ', $missingCodes); - - Notification::make() - ->title('Unknown: Item Codes') - ->body($message) - ->danger() - ->seconds(2) - ->send(); - - if ($disk->exists($path)) { - $disk->delete($path); - } - return; - } - - //plantNotFound - $matchedItems = Item::whereIn('code', $uniqueCodes)->where('plant_id', $plantId)->get(); - - $matchedCodes = $matchedItems->pluck('code')->toArray(); - $missingCodes = array_diff($uniqueCodes, $matchedCodes); - - if (!empty($missingCodes)) { - $missingCount = count($missingCodes); - - $message = $missingCount > 10 ? "'$missingCount' item codes are not found in database for choosed plant." : 'The following item codes are not found in database for choosed plant:
' . implode(', ', $missingCodes); + $message = $missingCount > 10 ? "'$missingCount' item codes are not found in database." : 'The following item codes are not found in database:
'.implode(', ', $missingCodes); Notification::make() ->title('Unknown: Item Codes') @@ -695,10 +689,36 @@ class WeightValidationResource extends Resource if ($disk->exists($path)) { $disk->delete($path); } + return; } - if (!$validRowsFound) { + // plantNotFound + $matchedItems = Item::whereIn('code', $uniqueCodes)->where('plant_id', $plantId)->get(); + + $matchedCodes = $matchedItems->pluck('code')->toArray(); + $missingCodes = array_diff($uniqueCodes, $matchedCodes); + + if (! empty($missingCodes)) { + $missingCount = count($missingCodes); + + $message = $missingCount > 10 ? "'$missingCount' item codes are not found in database for choosed plant." : 'The following item codes are not found in database for choosed plant:
'.implode(', ', $missingCodes); + + Notification::make() + ->title('Unknown: Item Codes') + ->body($message) + ->danger() + ->seconds(2) + ->send(); + + if ($disk->exists($path)) { + $disk->delete($path); + } + + return; + } + + if (! $validRowsFound) { Notification::make() ->title('Invalid OBD Invoice') ->danger() // This makes the notification red to indicate an error @@ -709,30 +729,32 @@ class WeightValidationResource extends Resource if ($disk->exists($path)) { $disk->delete($path); } + return; } $updateInv = WeightValidation::where('plant_id', $plantId)->where('obd_number', $originalNameOnly)->first()?->exists(); - $availLines = WeightValidation::where('plant_id', $plantId)->where('obd_number', $originalNameOnly)->where(function($query) { + $availLines = WeightValidation::where('plant_id', $plantId)->where('obd_number', $originalNameOnly)->where(function ($query) { $query->whereNull('vehicle_number')->orWhere('vehicle_number', ''); })->pluck('line_number')->toArray(); - $updated = WeightValidation::where('plant_id', $plantId)->where('obd_number', $originalNameOnly)->where(function($query) { + $updated = WeightValidation::where('plant_id', $plantId)->where('obd_number', $originalNameOnly)->where(function ($query) { $query->whereNull('vehicle_number')->orWhere('vehicle_number', ''); })->count(); - WeightValidation::where('plant_id', $plantId)->where('obd_number', $originalNameOnly)->where(function($query) { + WeightValidation::where('plant_id', $plantId)->where('obd_number', $originalNameOnly)->where(function ($query) { $query->whereNull('vehicle_number')->orWhere('vehicle_number', ''); }) - ->forceDelete(); + ->forceDelete(); $inserted = 0; // $updated = 0; - foreach ($rows as $index => $row) - { + foreach ($rows as $index => $row) { // Skip header - if ($index === 0) { continue; } + if ($index === 0) { + continue; + } $materialCode = trim($row[0]); $lineNumber = trim($row[1]); @@ -744,31 +766,27 @@ class WeightValidationResource extends Resource continue; } - if (!empty($materialCode)) { + if (! empty($materialCode)) { $recordExist = WeightValidation::where('plant_id', $plantId)->where('obd_number', $originalNameOnly)->where('line_number', $lineNumber)->first(); $masItem = Item::where('plant_id', $plantId)->where('code', $materialCode)->first(); - if($recordExist) { + if ($recordExist) { $skipUpd = $recordExist->vehicle_number ?? null; - if($skipUpd) - { + if ($skipUpd) { continue; - } - else - { + } else { if ($masItem) { $recordExist->update([ 'item_id' => $masItem->id, 'batch_number' => $batchNumber, - //'heat_number' => $heatNumber, + // 'heat_number' => $heatNumber, 'obd_weight' => $actualWeight, 'updated_at' => now(), ]); $updated++; } } - } - else { + } else { if ($masItem) { WeightValidation::create([ 'item_id' => $masItem->id, @@ -776,15 +794,12 @@ class WeightValidationResource extends Resource 'obd_number' => $originalNameOnly, 'line_number' => $lineNumber, 'batch_number' => $batchNumber, - //'heat_number' => $heatNumber, + // 'heat_number' => $heatNumber, 'obd_weight' => $actualWeight, ]); - if (in_array($lineNumber, $availLines)) - { + if (in_array($lineNumber, $availLines)) { continue; - } - else - { + } else { $inserted++; } } @@ -792,10 +807,10 @@ class WeightValidationResource extends Resource } } - if($updateInv) { + if ($updateInv) { if ($updated > 0) { Notification::make() - ->title("Start the scanning process!") + ->title('Start the scanning process!') ->body("'$updated' OBD lines were updated and
'$inserted' OBD lines were inserted for
imported OBD Invoice : '$originalNameOnly'.") ->info() // ->success() @@ -806,24 +821,20 @@ class WeightValidationResource extends Resource $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(); - if ($totalQuantity === $scannedQuantity) - { + if ($totalQuantity === $scannedQuantity) { if ($disk->exists($path)) { $disk->delete($path); } // $this->dispatch('refreshCompletedInvoice', invoiceNumber: $originalNameOnly, plantId: $plantId); - } - else - { + } else { if ($disk->exists($path)) { $disk->delete($path); } // $this->dispatch('refreshInvoiceData', invoiceNumber: $originalNameOnly, plantId: $plantId); } - } - else if ($inserted > 0) { + } elseif ($inserted > 0) { Notification::make() - ->title("Start the scanning process!") + ->title('Start the scanning process!') ->body("'$inserted' OBD lines were inserted for imported OBD Invoice : '$originalNameOnly'.") ->info() // ->success() @@ -834,24 +845,20 @@ class WeightValidationResource extends Resource $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(); - if ($totalQuantity === $scannedQuantity) - { + if ($totalQuantity === $scannedQuantity) { if ($disk->exists($path)) { $disk->delete($path); } // $this->dispatch('refreshCompletedInvoice', invoiceNumber: $originalNameOnly, plantId: $plantId); - } - else - { + } else { if ($disk->exists($path)) { $disk->delete($path); } // $this->dispatch('refreshInvoiceData', invoiceNumber: $originalNameOnly, plantId: $plantId); } - } - else { + } else { Notification::make() - ->title("Import Failed: OBD Invoice") + ->title('Import Failed: OBD Invoice') ->body("No exist records were updated for imported OBD Invoice : '$originalNameOnly'.") ->danger() ->seconds(2) @@ -863,14 +870,14 @@ class WeightValidationResource extends Resource if ($disk->exists($path)) { $disk->delete($path); } + // $this->dispatch('refreshEmptyInvoice', invoiceNumber: $originalNameOnly, plantId: $plantId); return; } - } - else { + } else { if ($inserted > 0) { Notification::make() - ->title("Start the scanning process!") + ->title('Start the scanning process!') ->body("'$inserted' OBD lines were inserted for imported OBD Invoice : '$originalNameOnly'.") ->info() // ->success() @@ -881,24 +888,20 @@ class WeightValidationResource extends Resource $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(); - if ($totalQuantity === $scannedQuantity) - { + if ($totalQuantity === $scannedQuantity) { if ($disk->exists($path)) { $disk->delete($path); } // $this->dispatch('refreshCompletedInvoice', invoiceNumber: $originalNameOnly, plantId: $plantId); - } - else - { + } else { if ($disk->exists($path)) { $disk->delete($path); } // $this->dispatch('refreshInvoiceData', invoiceNumber: $originalNameOnly, plantId: $plantId); } - } - else { + } else { Notification::make() - ->title("Import Failed: OBD Invoice") + ->title('Import Failed: OBD Invoice') ->body("No new records were inserted for imported OBD Invoice : '$originalNameOnly'.") ->danger() ->seconds(2) @@ -910,27 +913,28 @@ class WeightValidationResource extends Resource if ($disk->exists($path)) { $disk->delete($path); } + // $this->dispatch('refreshEmptyInvoice', invoiceNumber: $originalNameOnly, plantId: $plantId); return; } } } }) - ->visible(function() { + ->visible(function () { return Filament::auth()->user()->can('view import obd number validations'); }), ImportAction::make() ->label('Import OBD Invoice') ->color('warning') ->importer(WeightValidationImporter::class) - ->visible(function() { + ->visible(function () { return Filament::auth()->user()->can('view import weight validation'); }), ExportAction::make() ->label('Export OBD Invoices') ->color('warning') ->exporter(WeightValidationExporter::class) - ->visible(function() { + ->visible(function () { return Filament::auth()->user()->can('view export weight validation'); }), ]); diff --git a/app/Models/Item.php b/app/Models/Item.php index c0631c6..e906241 100644 --- a/app/Models/Item.php +++ b/app/Models/Item.php @@ -3,15 +3,15 @@ namespace App\Models; use Illuminate\Database\Eloquent\Model; -use Illuminate\Database\Eloquent\SoftDeletes; use Illuminate\Database\Eloquent\Relations\BelongsTo; +use Illuminate\Database\Eloquent\SoftDeletes; class Item extends Model { use SoftDeletes; protected $fillable = [ - "plant_id", + 'plant_id', 'category', 'code', 'description', @@ -43,4 +43,19 @@ class Item extends Model { 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); + } }