5 Commits

Author SHA1 Message Date
ee101f80ea Merge pull request 'Updated error response codes in updateGR and related methods to return 404 for various validation errors and Added sfg_number duplicate warning' (#13) from ranjith-dev into master
All checks were successful
Scan for leaked secrets using Kingfisher / kingfisher-secrets-scan (push) Successful in 11s
Reviewed-on: #13
2025-11-27 03:08:14 +00:00
37a99d03c1 Merge pull request 'Enhanced storeProcessOrderData method with improved validation and error handling for plant code, item code, coil number, order quantity, received quantity, SFG number, machine ID, and created by' (#12) from ranjith-dev into master
All checks were successful
Scan for leaked secrets using Kingfisher / kingfisher-secrets-scan (push) Successful in 11s
Reviewed-on: #12
2025-11-26 14:21:05 +00:00
5fdced003a Merge pull request 'ranjith-dev' (#11) from ranjith-dev into master
All checks were successful
Scan for leaked secrets using Kingfisher / kingfisher-secrets-scan (push) Successful in 11s
Reviewed-on: #11
2025-11-26 14:17:41 +00:00
0b0bb90efb Merge pull request 'Added POST API logs to view the structure in command prompt' (#10) from ranjith-dev into master
All checks were successful
Scan for leaked secrets using Kingfisher / kingfisher-secrets-scan (push) Successful in 10s
Reviewed-on: #10
2025-11-26 11:43:09 +00:00
32ce6da2c1 Merge pull request 'Add Larastan configuration and dependencies for static analysis' (#9) from ranjith-dev into master
All checks were successful
Scan for leaked secrets using Kingfisher / kingfisher-secrets-scan (push) Successful in 12s
Reviewed-on: #9
2025-11-26 09:11:36 +00:00
31 changed files with 2133 additions and 3332 deletions

View File

@@ -1,31 +0,0 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class LogClear extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'app:log-clear';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Command description';
/**
* Execute the console command.
*/
public function handle()
{
file_put_contents(storage_path('logs/laravel.log'), '');
$this->info('Laravel log cleared!');
}
}

View File

@@ -1,54 +0,0 @@
<?php
namespace App\Filament\Exports;
use App\Models\StickerPrinting;
use Filament\Actions\Exports\ExportColumn;
use Filament\Actions\Exports\Exporter;
use Filament\Actions\Exports\Models\Export;
class StickerPrintingExporter extends Exporter
{
protected static ?string $model = StickerPrinting::class;
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.code')
->label('PLANT CODE'),
ExportColumn::make('reference_number')
->label('REFERENCE NUMBER'),
ExportColumn::make('serial_number')
->label('SERIAL NUMBER'),
ExportColumn::make('created_at')
->label('CREATED AT'),
ExportColumn::make('updated_at')
->label('UPDATED AT'),
ExportColumn::make('created_by')
->label('CREATED BY'),
ExportColumn::make('updated_by')
->label('UPDATED BY'),
ExportColumn::make('deleted_at')
->label('DELETED AT')
->enabledByDefault(false),
];
}
public static function getCompletedNotificationBody(Export $export): string
{
$body = 'Your sticker printing 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.';
}
return $body;
}
}

View File

@@ -1,106 +0,0 @@
<?php
namespace App\Filament\Imports;
use App\Models\StickerPrinting;
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;
class StickerPrintingImporter extends Importer
{
protected static ?string $model = StickerPrinting::class;
public static function getColumns(): array
{
return [
ImportColumn::make('plant')
->requiredMapping()
->exampleHeader('PLANT CODE')
->example('1000')
->label('PLANT CODE')
->relationship(resolveUsing: 'code')
->rules(['required']),
ImportColumn::make('reference_number')
->exampleHeader('REFERENCE NUMBER')
->example('REF123456')
->label('REFERENCE NUMBER'),
ImportColumn::make('serial_number')
->exampleHeader('SERIAL NUMBER')
->example('135245325212')
->label('SERIAL NUMBER'),
// ImportColumn::make('created_by')
// ->exampleHeader('CREATED BY')
// ->example('RAW01234')
// ->label('CREATED BY'),
];
}
public function resolveRecord(): ?StickerPrinting
{
// return StickerPrinting::firstOrNew([
// // Update existing records, matching them by `$this->data['column_name']`
// 'email' => $this->data['email'],
// ]);
$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!");
}
$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 (!empty($warnMsg)) {
throw new RowImportFailedException(implode(', ', $warnMsg));
}
StickerPrinting::Create([
'plant_id' => $plant->id,
'reference_number' => $this->data['reference_number'],
'serial_number' => $this->data['serial_number'],
'created_at' => now(),
'updated_at' =>now(),
'created_by' => Filament::auth()->user()?->name,
]);
return null;
//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.';
if ($failedRowsCount = $import->getFailedRowsCount()) {
$body .= ' ' . number_format($failedRowsCount) . ' ' . str('row')->plural($failedRowsCount) . ' failed to import.';
}
return $body;
}
}

View File

@@ -50,7 +50,7 @@ class AlertMailRuleResource extends Resource
'InvoiceValidation' => 'InvoiceValidation', 'InvoiceValidation' => 'InvoiceValidation',
'InvoiceDataReport' => 'InvoiceDataReport', 'InvoiceDataReport' => 'InvoiceDataReport',
'ProductionQuantities' => 'ProductionQuantities', 'ProductionQuantities' => 'ProductionQuantities',
'QualityValidation' => 'QualityValidation', //'Calibration' => 'Calibration',
]), ]),
Forms\Components\Select::make('rule_name') Forms\Components\Select::make('rule_name')
->label('Rule Name') ->label('Rule Name')
@@ -60,7 +60,7 @@ class AlertMailRuleResource extends Resource
'MaterialInvoiceMail' => 'Material Invoice Mail', 'MaterialInvoiceMail' => 'Material Invoice Mail',
'ProductionMail' => 'Production Mail', 'ProductionMail' => 'Production Mail',
'InvoiceDataMail' => 'Invoice Data Mail', 'InvoiceDataMail' => 'Invoice Data Mail',
'QualityMail' => 'Quality Mail', //'CalibrationMail' => 'Calibration Mail',
]) ])
->required(), ->required(),
Forms\Components\TextInput::make('email') Forms\Components\TextInput::make('email')

View File

@@ -4,23 +4,27 @@ namespace App\Filament\Resources;
use App\Filament\Exports\InvoiceDataValidationExporter; use App\Filament\Exports\InvoiceDataValidationExporter;
use App\Filament\Resources\InvoiceDataValidationResource\Pages; use App\Filament\Resources\InvoiceDataValidationResource\Pages;
use App\Filament\Resources\InvoiceDataValidationResource\RelationManagers;
use App\Models\InvoiceDataValidation; use App\Models\InvoiceDataValidation;
use App\Models\Plant;
use DB;
use Filament\Facades\Filament;
use Filament\Forms; use Filament\Forms;
use Filament\Forms\Components\FileUpload;
use Filament\Forms\Form; use Filament\Forms\Form;
use Filament\Forms\Get;
use Filament\Notifications\Notification;
use Filament\Resources\Resource; use Filament\Resources\Resource;
use Filament\Tables; use Filament\Tables;
use Filament\Tables\Actions\ExportAction;
use Filament\Tables\Table; use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope; use Illuminate\Database\Eloquent\SoftDeletingScope;
use Filament\Facades\Filament;
use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\Select;
use Filament\Notifications\Notification;
use App\Models\Plant;
use Filament\Forms\Get;
use Illuminate\Support\Facades\Storage; use Illuminate\Support\Facades\Storage;
use Maatwebsite\Excel\Facades\Excel; use Maatwebsite\Excel\Facades\Excel;
use App\Models\StickerMaster;
use App\Models\User;
use DB;
use Filament\Tables\Actions\ExportAction;
class InvoiceDataValidationResource extends Resource class InvoiceDataValidationResource extends Resource
{ {
@@ -63,7 +67,6 @@ class InvoiceDataValidationResource extends Resource
->label('Created By') ->label('Created By')
->default(Filament::auth()->user()?->name), ->default(Filament::auth()->user()?->name),
Forms\Components\Hidden::make('updated_by') Forms\Components\Hidden::make('updated_by')
->label('Updated By')
->default(Filament::auth()->user()?->name), ->default(Filament::auth()->user()?->name),
]); ]);
} }
@@ -74,12 +77,10 @@ class InvoiceDataValidationResource extends Resource
->columns([ ->columns([
Tables\Columns\TextColumn::make('No.') Tables\Columns\TextColumn::make('No.')
->label('No.') ->label('No.')
->alignCenter()
->getStateUsing(function ($record, $livewire, $column, $rowLoop) { ->getStateUsing(function ($record, $livewire, $column, $rowLoop) {
$paginator = $livewire->getTableRecords(); $paginator = $livewire->getTableRecords();
$perPage = method_exists($paginator, 'perPage') ? $paginator->perPage() : 10; $perPage = method_exists($paginator, 'perPage') ? $paginator->perPage() : 10;
$currentPage = method_exists($paginator, 'currentPage') ? $paginator->currentPage() : 1; $currentPage = method_exists($paginator, 'currentPage') ? $paginator->currentPage() : 1;
return ($currentPage - 1) * $perPage + $rowLoop->iteration; return ($currentPage - 1) * $perPage + $rowLoop->iteration;
}), }),
Tables\Columns\TextColumn::make('plant.code') Tables\Columns\TextColumn::make('plant.code')
@@ -99,8 +100,8 @@ class InvoiceDataValidationResource extends Resource
->sortable(), ->sortable(),
Tables\Columns\TextColumn::make('document_number') Tables\Columns\TextColumn::make('document_number')
->label('Document Number') ->label('Document Number')
->alignCenter()
->searchable() ->searchable()
->alignCenter()
->sortable(), ->sortable(),
Tables\Columns\TextColumn::make('document_date') Tables\Columns\TextColumn::make('document_date')
->label('Document Date') ->label('Document Date')
@@ -126,26 +127,13 @@ class InvoiceDataValidationResource extends Resource
Tables\Columns\TextColumn::make('created_at') Tables\Columns\TextColumn::make('created_at')
->label('Created At') ->label('Created At')
->alignCenter() ->alignCenter()
->searchable()
->dateTime()
->sortable(),
// ->toggleable(isToggledHiddenByDefault: true),
Tables\Columns\TextColumn::make('created_by')
->label('Created By')
->alignCenter()
->searchable()
->sortable(),
Tables\Columns\TextColumn::make('updated_at')
->label('Updated At')
->alignCenter()
->searchable()
->dateTime() ->dateTime()
->sortable() ->sortable()
->toggleable(isToggledHiddenByDefault: true), ->toggleable(isToggledHiddenByDefault: true),
Tables\Columns\TextColumn::make('updated_by') Tables\Columns\TextColumn::make('updated_at')
->label('Updated By') ->label('Updated At')
->alignCenter() ->alignCenter()
->searchable() ->dateTime()
->sortable() ->sortable()
->toggleable(isToggledHiddenByDefault: true), ->toggleable(isToggledHiddenByDefault: true),
Tables\Columns\TextColumn::make('deleted_at') Tables\Columns\TextColumn::make('deleted_at')
@@ -181,7 +169,7 @@ class InvoiceDataValidationResource extends Resource
->reactive() ->reactive()
->required() ->required()
->disk('local') ->disk('local')
// ->visible(fn (Get $get) => !empty($get('plant_id'))) //->visible(fn (Get $get) => !empty($get('plant_id')))
->directory('uploads/temp'), ->directory('uploads/temp'),
]) ])
->action(function (array $data) { ->action(function (array $data) {
@@ -203,10 +191,12 @@ class InvoiceDataValidationResource extends Resource
$fullPath = Storage::disk('local')->path($path); $fullPath = Storage::disk('local')->path($path);
if ($fullPath && file_exists($fullPath)) { if ($fullPath && file_exists($fullPath))
{
$rows = Excel::toArray(null, $fullPath)[0]; $rows = Excel::toArray(null, $fullPath)[0];
if ((count($rows) - 1) <= 0) { if ((count($rows) - 1) <= 0)
{
Notification::make() Notification::make()
->title('Records Not Found') ->title('Records Not Found')
->body("Import the valid 'Invoice Data' file to proceed..!") ->body("Import the valid 'Invoice Data' file to proceed..!")
@@ -216,7 +206,6 @@ class InvoiceDataValidationResource extends Resource
if ($disk->exists($path)) { if ($disk->exists($path)) {
$disk->delete($path); $disk->delete($path);
} }
return; return;
} }
@@ -234,40 +223,43 @@ class InvoiceDataValidationResource extends Resource
$invalidLocation = []; $invalidLocation = [];
$seenPlantDoc = []; $seenPlantDoc = [];
// $duplicateEntries = []; //$duplicateEntries = [];
$duplicateEntriesExcel = []; $duplicateEntriesExcel = [];
foreach ($rows as $index => $row) { foreach ($rows as $index => $row)
if ($index == 0) { {
continue; if ($index == 0) continue; // Skip header
} // Skip header
$DisChaDesc = trim($row[3]); $DisChaDesc = trim($row[3]);
$plantCode = trim($row[4]); $plantCode = trim($row[4]);
$CustomerCode = trim($row[5]); $CustomerCode = trim($row[5]);
$DocNo = trim($row[6]); $DocNo = trim($row[6]);
$DocDate = trim($row[7]); $DocDate = trim($row[7]);
$CusTradeName = trim($row[9]); $CusTradeName = trim($row[9]);
$CusLocation = trim($row[10]); $CusLocation = trim($row[10]);
$Location = trim($row[36]); $Location = trim($row[36]);
// if (empty($plantCode)) $invalidPlantCode[] = "Row {$index}"; // if (empty($plantCode)) $invalidPlantCode[] = "Row {$index}";
if (empty($DisChaDesc)) { if (empty($DisChaDesc)){
$invalidDisChaDesc[] = "Row {$index}"; $invalidDisChaDesc[] = "Row {$index}";
} }
if (empty($CustomerCode)) { if (empty($CustomerCode)){
$invalidCustomerCode[] = "Row {$index}"; $invalidCustomerCode[] = "Row {$index}";
} }
if (empty($DocNo)) { if (empty($DocNo))
{
$invalidDocNo[] = "Row {$index}"; $invalidDocNo[] = "Row {$index}";
} }
if (empty($CusTradeName)) { if (empty($CusTradeName))
{
$invalidCusTradeName[] = "Row {$index}"; $invalidCusTradeName[] = "Row {$index}";
} }
if (empty($CusLocation)) { if (empty($CusLocation))
{
$invalidCusLocation[] = "Row {$index}"; $invalidCusLocation[] = "Row {$index}";
} }
if (empty($Location)) { if (empty($Location))
{
$invalidLocation[] = "Row {$index}"; $invalidLocation[] = "Row {$index}";
} }
// if (empty($createdBy)) $invalidUser[] = "Row {$index}"; // if (empty($createdBy)) $invalidUser[] = "Row {$index}";
@@ -275,9 +267,11 @@ class InvoiceDataValidationResource extends Resource
if (strlen($plantCode) < 4) { if (strlen($plantCode) < 4) {
$invalidPlantCode[] = $plantCode; $invalidPlantCode[] = $plantCode;
} }
if (! is_numeric($plantCode)) { if (!is_numeric($plantCode)) {
$invalidPlantType[] = $plantCode; $invalidPlantType[] = $plantCode;
} elseif (! Plant::where('code', $plantCode)->first()) { }
else if (!Plant::where('code', $plantCode)->first())
{
$invalidPlaCoFound[] = $plantCode; $invalidPlaCoFound[] = $plantCode;
} }
@@ -294,36 +288,25 @@ class InvoiceDataValidationResource extends Resource
// $duplicateEntries[] = "Duplicate record: Document Number '{$DocNo}' already exists for Plant '{$plant->name}'"; // $duplicateEntries[] = "Duplicate record: Document Number '{$DocNo}' already exists for Plant '{$plant->name}'";
// } // }
// Also check duplicates within the same file --- //Also check duplicates within the same file ---
$uniqueKey = $plantCode.'_'.$DocNo; $uniqueKey = $plantCode . '_' . $DocNo;
if (in_array($uniqueKey, $seenPlantDoc)) { if (in_array($uniqueKey, $seenPlantDoc)) {
$duplicateEntriesExcel[] = "Duplicate in file at Row {$index}: Document Number '{$DocNo}' already exists for Plant '{$plant->name}'"; $duplicateEntriesExcel[] = "Duplicate in file at Row {$index}: Document Number '{$DocNo}' already exists for Plant '{$plant->name}'";
} }
$seenPlantDoc[] = $uniqueKey; $seenPlantDoc[] = $uniqueKey;
} }
if (! empty($invalidCustomerCode) || ! empty($invalidDocNo) || ! empty($invalidDocDate) || ! empty($invalidCusTradeName) || ! empty($invalidCusLocation)) { if (!empty($invalidCustomerCode) || !empty($invalidDocNo) || !empty($invalidDocDate) || !empty($invalidCusTradeName) || !empty($invalidCusLocation))
{
$errorMsg = ''; $errorMsg = '';
// if (!empty($invalidDisChaDesc)) $errorMsg .= 'Missing Distribution Channel Description in rows: ' . implode(', ', $invalidDisChaDesc) . '<br>'; //if (!empty($invalidDisChaDesc)) $errorMsg .= 'Missing Distribution Channel Description in rows: ' . implode(', ', $invalidDisChaDesc) . '<br>';
if (! empty($invalidCustomerCode)) { if (!empty($invalidCustomerCode)) $errorMsg .= 'Missing Customer Code in rows: ' . implode(', ', $invalidCustomerCode) . '<br>';
$errorMsg .= 'Missing Customer Code in rows: '.implode(', ', $invalidCustomerCode).'<br>'; if (!empty($invalidDocNo)) $errorMsg .= 'Missing Document Number in rows: ' . implode(', ', $invalidDocNo) . '<br>';
} if (!empty($invalidDocDate)) $errorMsg .= 'Missing Document Date in rows: ' . implode(', ', $invalidDocDate) . '<br>';
if (! empty($invalidDocNo)) { if (!empty($invalidCusTradeName)) $errorMsg .= 'Missing Customer Trade Name in rows: ' . implode(', ', $invalidCusTradeName) . '<br>';
$errorMsg .= 'Missing Document Number in rows: '.implode(', ', $invalidDocNo).'<br>'; if (!empty($invalidCusLocation)) $errorMsg .= 'Missing Customer Location in rows: ' . implode(', ', $invalidCusLocation) . '<br>';
} if (!empty($invalidLocation)) $errorMsg .= 'Missing Location in rows: ' . implode(', ', $invalidLocation) . '<br>';
if (! empty($invalidDocDate)) {
$errorMsg .= 'Missing Document Date in rows: '.implode(', ', $invalidDocDate).'<br>';
}
if (! empty($invalidCusTradeName)) {
$errorMsg .= 'Missing Customer Trade Name in rows: '.implode(', ', $invalidCusTradeName).'<br>';
}
if (! empty($invalidCusLocation)) {
$errorMsg .= 'Missing Customer Location in rows: '.implode(', ', $invalidCusLocation).'<br>';
}
if (! empty($invalidLocation)) {
$errorMsg .= 'Missing Location in rows: '.implode(', ', $invalidLocation).'<br>';
}
Notification::make() Notification::make()
->title('Missing Mandatory Fields') ->title('Missing Mandatory Fields')
@@ -334,43 +317,45 @@ class InvoiceDataValidationResource extends Resource
if ($disk->exists($path)) { if ($disk->exists($path)) {
$disk->delete($path); $disk->delete($path);
} }
return; return;
} elseif (! empty($invalidPlantCode)) { }
else if (!empty($invalidPlantCode))
{
$invalidPlantCode = array_unique($invalidPlantCode); $invalidPlantCode = array_unique($invalidPlantCode);
Notification::make() Notification::make()
->title('Invalid Plant Codes') ->title('Invalid Plant Codes')
->body('The following plant codes should contain minimum 4 digits:<br>'.implode(', ', $invalidPlantCode)) ->body('The following plant codes should contain minimum 4 digits:<br>' . implode(', ', $invalidPlantCode))
->danger() ->danger()
->send(); ->send();
if ($disk->exists($path)) { if ($disk->exists($path)) {
$disk->delete($path); $disk->delete($path);
} }
return; return;
} elseif (! empty($invalidPlantType)) { }
else if (!empty($invalidPlantType))
{
$invalidPlantType = array_unique($invalidPlantType); $invalidPlantType = array_unique($invalidPlantType);
Notification::make() Notification::make()
->title('Invalid Plant Codes') ->title('Invalid Plant Codes')
->body('The following plant codes should contain numeric values:<br>'.implode(', ', $invalidPlantType)) ->body('The following plant codes should contain numeric values:<br>' . implode(', ', $invalidPlantType))
->danger() ->danger()
->send(); ->send();
if ($disk->exists($path)) { if ($disk->exists($path)) {
$disk->delete($path); $disk->delete($path);
} }
return; return;
} elseif (! empty($invalidPlaCoFound)) { }
else if (!empty($invalidPlaCoFound))
{
$invalidPlaCoFound = array_unique($invalidPlaCoFound); $invalidPlaCoFound = array_unique($invalidPlaCoFound);
Notification::make() Notification::make()
->title('Invalid Plant Codes') ->title('Invalid Plant Codes')
->body('The following plant codes not found in plants:<br>'.implode(', ', $invalidPlaCoFound)) ->body('The following plant codes not found in plants:<br>' . implode(', ', $invalidPlaCoFound))
->danger() ->danger()
->send(); ->send();
if ($disk->exists($path)) { if ($disk->exists($path)) {
$disk->delete($path); $disk->delete($path);
} }
return; return;
} }
@@ -416,10 +401,11 @@ class InvoiceDataValidationResource extends Resource
// return; // return;
// } // }
if (! empty($duplicateEntriesExcel)) { if (!empty($duplicateEntriesExcel))
{
$duplicateGroupedByPlantExcel = []; $duplicateGroupedByPlantExcel = [];
foreach ($duplicateEntriesExcel as $message) {// "/Document Number '([^']+)' already exist(?:s)?(?: for Plant (.+))?/" foreach ($duplicateEntriesExcel as $message) {//"/Document Number '([^']+)' already exist(?:s)?(?: for Plant (.+))?/"
if (preg_match("/Document Number '([^']+)' already exists for Plant '([^']+)'/", $message, $matches)) { if (preg_match("/Document Number '([^']+)' already exists for Plant '([^']+)'/", $message, $matches)) {
$docNo = $matches[1]; $docNo = $matches[1];
$plantName = $matches[2] ?? 'Unknown'; $plantName = $matches[2] ?? 'Unknown';
@@ -429,7 +415,8 @@ class InvoiceDataValidationResource extends Resource
$errorMsg = 'Duplicate Document Number found in Uploaded File :<br>'; $errorMsg = 'Duplicate Document Number found in Uploaded File :<br>';
foreach ($duplicateGroupedByPlantExcel as $plant => $docNumbers) { foreach ($duplicateGroupedByPlantExcel as $plant => $docNumbers)
{
// Remove duplicate document numbers for each plant // Remove duplicate document numbers for each plant
$uniqueDocNumbers = array_unique($docNumbers); $uniqueDocNumbers = array_unique($docNumbers);
$count = count($uniqueDocNumbers); $count = count($uniqueDocNumbers);
@@ -438,13 +425,13 @@ class InvoiceDataValidationResource extends Resource
$errorMsg .= "Duplicate Document Numbers for Plant <b>{$plant}</b> : {$count} Document Numbers already exist in uploaded file<br>"; $errorMsg .= "Duplicate Document Numbers for Plant <b>{$plant}</b> : {$count} Document Numbers already exist in uploaded file<br>";
} else { } else {
$errorMsg .= "Duplicate Document Numbers for Plant <b>{$plant}</b> : '" $errorMsg .= "Duplicate Document Numbers for Plant <b>{$plant}</b> : '"
.implode(', ', $uniqueDocNumbers) . implode(', ', $uniqueDocNumbers)
."' already exist in uploaded file<br>"; . "' already exist in uploaded file<br>";
} }
} }
Notification::make() Notification::make()
// ->title('Duplicate Document Number in Uploaded File') //->title('Duplicate Document Number in Uploaded File')
->body($errorMsg) ->body($errorMsg)
->danger() ->danger()
->send(); ->send();
@@ -452,7 +439,6 @@ class InvoiceDataValidationResource extends Resource
if ($disk->exists($path)) { if ($disk->exists($path)) {
$disk->delete($path); $disk->delete($path);
} }
return; return;
} }
@@ -469,34 +455,33 @@ class InvoiceDataValidationResource extends Resource
DB::beginTransaction(); DB::beginTransaction();
try { try
{
foreach ($rows as $index => $row) { foreach ($rows as $index => $row) {
if ($index == 0) { if ($index == 0) continue;
continue;
}
$rowNumber = $index + 1; $rowNumber = $index + 1;
try { try {
$DisChaDesc = trim($row[3]); $DisChaDesc = trim($row[3]);
$plantCode = trim($row[4]); $plantCode = trim($row[4]);
$CustomerCode = trim($row[5]); $CustomerCode = trim($row[5]);
$DocNo = trim($row[6]); $DocNo = trim($row[6]);
$DocDate = trim($row[7]); $DocDate = trim($row[7]);
$CusTradeName = trim($row[9]); $CusTradeName = trim($row[9]);
$CusLocation = trim($row[10]); $CusLocation = trim($row[10]);
$Location = trim($row[36]); $Location = trim($row[36]);
if (empty($DocNo)) { if (empty($DocNo)) {
throw new \Exception("Row '{$rowNumber}' Missing QR Code"); throw new \Exception("Row '{$rowNumber}' Missing QR Code");
} }
$plant = Plant::where('code', $plantCode)->first(); $plant = Plant::where('code', $plantCode)->first();
if (! $plant) { if (!$plant) {
throw new \Exception("Invalid plant code : '{$plantCode}'"); throw new \Exception("Invalid plant code : '{$plantCode}'");
} }
if (! empty($DocDate)) { if (!empty($DocDate)) {
if (preg_match('/^\d{2}[-\/]\d{2}[-\/]\d{4}$/', $DocDate)) { if (preg_match('/^\d{2}[-\/]\d{2}[-\/]\d{4}$/', $DocDate)) {
[$day, $month, $year] = preg_split('/[-\/]/', $DocDate); [$day, $month, $year] = preg_split('/[-\/]/', $DocDate);
$formattedDate = "{$year}-{$month}-{$day}"; $formattedDate = "{$year}-{$month}-{$day}";
@@ -518,26 +503,26 @@ class InvoiceDataValidationResource extends Resource
if ($record) { if ($record) {
$record->update([ $record->update([
'distribution_channel_desc' => $DisChaDesc, 'distribution_channel_desc' => $DisChaDesc,
'customer_code' => $CustomerCode, 'customer_code' => $CustomerCode,
'document_date' => $formattedDate, 'document_date' => $formattedDate,
'customer_trade_name' => $CusTradeName, 'customer_trade_name' => $CusTradeName,
'customer_location' => $CusLocation, 'customer_location' => $CusLocation,
'location' => $Location, 'location' => $Location,
'updated_by' => $operatorName, 'updated_by' => $operatorName
]); ]);
$inserted = $record; $inserted = $record;
} else { } else {
// Record does not exist, create with 'created_by' // Record does not exist, create with 'created_by'
$inserted = InvoiceDataValidation::create([ $inserted = InvoiceDataValidation::create([
'plant_id' => $plant->id, 'plant_id' => $plant->id,
'document_number' => $DocNo, 'document_number' => $DocNo,
'distribution_channel_desc' => $DisChaDesc, 'distribution_channel_desc' => $DisChaDesc,
'customer_code' => $CustomerCode, 'customer_code' => $CustomerCode,
'document_date' => $formattedDate, 'document_date' => $formattedDate,
'customer_trade_name' => $CusTradeName, 'customer_trade_name' => $CusTradeName,
'customer_location' => $CusLocation, 'customer_location' => $CusLocation,
'location' => $Location, 'location' => $Location,
'created_by' => $operatorName, 'created_by' => $operatorName
]); ]);
} }
// $inserted = InvoiceDataValidation::create([ // $inserted = InvoiceDataValidation::create([
@@ -551,7 +536,7 @@ class InvoiceDataValidationResource extends Resource
// 'created_by' => $operatorName // 'created_by' => $operatorName
// ]); // ]);
if (! $inserted) { if (!$inserted) {
throw new \Exception("{$curStat} failed for Document Number : {$DocNo}"); throw new \Exception("{$curStat} failed for Document Number : {$DocNo}");
} }
@@ -560,7 +545,7 @@ class InvoiceDataValidationResource extends Resource
$failedRecords[] = [ $failedRecords[] = [
'row' => $rowNumber, 'row' => $rowNumber,
'document_number' => $DocNo ?? null, 'document_number' => $DocNo ?? null,
'error' => $e->getMessage(), 'error' => $e->getMessage()
]; ];
} }
} }
@@ -569,13 +554,13 @@ class InvoiceDataValidationResource extends Resource
if (count($failedRecords) > 0) { if (count($failedRecords) > 0) {
$failedSummary = collect($failedRecords) $failedSummary = collect($failedRecords)
->map(fn ($f) => "Row {$f['row']} ({$f['document_number']}) : {$f['error']}") ->map(fn($f) => "Row {$f['row']} ({$f['document_number']}) : {$f['error']}")
->take(5) // limit preview to first 5 errors ->take(5) // limit preview to first 5 errors
->implode("\n"); ->implode("\n");
Notification::make() Notification::make()
->title('Partial Import Warning') ->title('Partial Import Warning')
->body("'{$successCount}' records inserted. ".count($failedRecords)." failed.\n\n{$failedSummary}") ->body("'{$successCount}' records inserted. " . count($failedRecords) . " failed.\n\n{$failedSummary}")
->warning() ->warning()
->send(); ->send();
} else { } else {
@@ -585,7 +570,9 @@ class InvoiceDataValidationResource extends Resource
->success() ->success()
->send(); ->send();
} }
} catch (\Exception $e) { }
catch (\Exception $e)
{
DB::rollBack(); DB::rollBack();
Notification::make() Notification::make()
->title('Import Failed') ->title('Import Failed')
@@ -595,14 +582,14 @@ class InvoiceDataValidationResource extends Resource
} }
} }
}) })
->visible(function () { ->visible(function() {
return Filament::auth()->user()->can('view import invoice data validation'); return Filament::auth()->user()->can('view import invoice data validation');
}), }),
ExportAction::make() ExportAction::make()
->label('Export Invoice Data') ->label('Export Invoice Data')
->color('warning') ->color('warning')
->exporter(InvoiceDataValidationExporter::class) ->exporter(InvoiceDataValidationExporter::class)
->visible(function () { ->visible(function() {
return Filament::auth()->user()->can('view export invoice data validation'); return Filament::auth()->user()->can('view export invoice data validation');
}), }),
]); ]);

View File

@@ -4,25 +4,27 @@ namespace App\Filament\Resources;
use App\Filament\Exports\InvoiceOutValidationExporter; use App\Filament\Exports\InvoiceOutValidationExporter;
use App\Filament\Resources\InvoiceOutValidationResource\Pages; use App\Filament\Resources\InvoiceOutValidationResource\Pages;
use App\Filament\Resources\InvoiceOutValidationResource\RelationManagers;
use App\Models\InvoiceOutValidation; use App\Models\InvoiceOutValidation;
use App\Models\Plant; use App\Models\Plant;
use App\Models\User;
use Carbon\Carbon; use Carbon\Carbon;
use DB; use DB;
use Filament\Facades\Filament;
use Filament\Forms; use Filament\Forms;
use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\Section;
use Filament\Forms\Form; use Filament\Forms\Form;
use Filament\Notifications\Notification;
use Filament\Resources\Resource; use Filament\Resources\Resource;
use Filament\Tables; use Filament\Tables;
use Filament\Tables\Actions\ExportAction;
use Filament\Tables\Table; use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope; use Illuminate\Database\Eloquent\SoftDeletingScope;
use Filament\Facades\Filament;
use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\Section;
use Filament\Notifications\Notification;
use Maatwebsite\Excel\Facades\Excel; use Maatwebsite\Excel\Facades\Excel;
use PhpOffice\PhpSpreadsheet\Shared\Date as ExcelDate;
use Storage; use Storage;
use Filament\Tables\Actions\ExportAction;
use PhpOffice\PhpSpreadsheet\Shared\Date as ExcelDate;
class InvoiceOutValidationResource extends Resource class InvoiceOutValidationResource extends Resource
{ {
@@ -37,25 +39,24 @@ class InvoiceOutValidationResource extends Resource
return $form return $form
->schema([ ->schema([
Section::make('') Section::make('')
->schema([ ->schema([
Forms\Components\Select::make('plant_id') Forms\Components\Select::make('plant_id')
->label('Plant') ->label('Plant')
->relationship('plant', 'name') ->relationship('plant', 'name')
->required(), ->required(),
Forms\Components\TextInput::make('qr_code') Forms\Components\TextInput::make('qr_code')
->label('QR Code'), ->label('QR Code'),
Forms\Components\DateTimePicker::make('scanned_at') Forms\Components\DateTimePicker::make('scanned_at')
->label('Scanned At'), ->label('Scanned At'),
Forms\Components\TextInput::make('scanned_by') Forms\Components\TextInput::make('scanned_by')
->label('Scanned By'), ->label('Scanned By'),
Forms\Components\Hidden::make('created_by') Forms\Components\Hidden::make('created_by')
->label('Created By') ->label('Created By')
->default(Filament::auth()->user()?->name), ->default(Filament::auth()->user()?->name),
Forms\Components\Hidden::make('updated_by') Forms\Components\Hidden::make('updated_by')
->label('Updated By') ->default(Filament::auth()->user()?->name),
->default(Filament::auth()->user()?->name), ])
]) ->columns(4),
->columns(4),
]); ]);
} }
@@ -65,18 +66,15 @@ class InvoiceOutValidationResource extends Resource
->columns([ ->columns([
Tables\Columns\TextColumn::make('No.') Tables\Columns\TextColumn::make('No.')
->label('No.') ->label('No.')
->alignCenter()
->getStateUsing(function ($record, $livewire, $column, $rowLoop) { ->getStateUsing(function ($record, $livewire, $column, $rowLoop) {
$paginator = $livewire->getTableRecords(); $paginator = $livewire->getTableRecords();
$perPage = method_exists($paginator, 'perPage') ? $paginator->perPage() : 10; $perPage = method_exists($paginator, 'perPage') ? $paginator->perPage() : 10;
$currentPage = method_exists($paginator, 'currentPage') ? $paginator->currentPage() : 1; $currentPage = method_exists($paginator, 'currentPage') ? $paginator->currentPage() : 1;
return ($currentPage - 1) * $perPage + $rowLoop->iteration; return ($currentPage - 1) * $perPage + $rowLoop->iteration;
}), }),
Tables\Columns\TextColumn::make('plant.code') Tables\Columns\TextColumn::make('plant.code')
->label('Plant') ->label('Plant')
->alignCenter() ->alignCenter()
->searchable()
->sortable(), ->sortable(),
Tables\Columns\TextColumn::make('qr_code') Tables\Columns\TextColumn::make('qr_code')
->label('QR Code') ->label('QR Code')
@@ -95,33 +93,27 @@ class InvoiceOutValidationResource extends Resource
->alignCenter() ->alignCenter()
->sortable(), ->sortable(),
Tables\Columns\TextColumn::make('created_at') Tables\Columns\TextColumn::make('created_at')
->label('Created At')
->dateTime()
->searchable() ->searchable()
->alignCenter() ->dateTime()
->sortable(), ->sortable(),
// ->toggleable(isToggledHiddenByDefault: true), //->toggleable(isToggledHiddenByDefault: true),
Tables\Columns\TextColumn::make('created_by') Tables\Columns\TextColumn::make('created_by')
->label('Created By') ->label('Created By')
->searchable() ->searchable()
->alignCenter() ->alignCenter()
->sortable(), ->sortable(),
Tables\Columns\TextColumn::make('updated_at') Tables\Columns\TextColumn::make('updated_at')
->label('Updated At')
->dateTime() ->dateTime()
->searchable() ->searchable()
->alignCenter() ->sortable(),
->sortable() // ->toggleable(isToggledHiddenByDefault: true),
->toggleable(isToggledHiddenByDefault: true),
Tables\Columns\TextColumn::make('updated_by') Tables\Columns\TextColumn::make('updated_by')
->label('Updated By') ->label('Updated By')
->searchable() ->searchable()
->alignCenter() ->alignCenter()
->sortable() ->sortable(),
->toggleable(isToggledHiddenByDefault: true),
Tables\Columns\TextColumn::make('deleted_at') Tables\Columns\TextColumn::make('deleted_at')
->dateTime() ->dateTime()
->alignCenter()
->sortable() ->sortable()
->toggleable(isToggledHiddenByDefault: true), ->toggleable(isToggledHiddenByDefault: true),
]) ])
@@ -151,7 +143,7 @@ class InvoiceOutValidationResource extends Resource
->reactive() ->reactive()
->required() ->required()
->disk('local') ->disk('local')
// ->visible(fn (Get $get) => !empty($get('plant_id'))) //->visible(fn (Get $get) => !empty($get('plant_id')))
->directory('uploads/temp'), ->directory('uploads/temp'),
]) ])
->action(function (array $data) { ->action(function (array $data) {
@@ -173,10 +165,12 @@ class InvoiceOutValidationResource extends Resource
$fullPath = Storage::disk('local')->path($path); $fullPath = Storage::disk('local')->path($path);
if ($fullPath && file_exists($fullPath)) { if ($fullPath && file_exists($fullPath))
{
$rows = Excel::toArray(null, $fullPath)[0]; $rows = Excel::toArray(null, $fullPath)[0];
if ((count($rows) - 1) <= 0) { if ((count($rows) - 1) <= 0)
{
Notification::make() Notification::make()
->title('Records Not Found') ->title('Records Not Found')
->body("Import the valid 'Invoice Data' file to proceed..!") ->body("Import the valid 'Invoice Data' file to proceed..!")
@@ -186,7 +180,6 @@ class InvoiceOutValidationResource extends Resource
if ($disk->exists($path)) { if ($disk->exists($path)) {
$disk->delete($path); $disk->delete($path);
} }
return; return;
} }
@@ -199,34 +192,27 @@ class InvoiceOutValidationResource extends Resource
$userNotFound = []; $userNotFound = [];
$seenPlantQr = []; $seenPlantQr = [];
$duplicateQrExcel = []; $duplicateQrExcel = [];
// $duplicateQrDb = []; //$duplicateQrDb = [];
foreach ($rows as $index => $row) { foreach ($rows as $index => $row)
if ($index == 0) { {
continue; if ($index == 0) continue;
}
$qrCode = trim($row[1]); $qrCode = trim($row[1]);
$plantCode = trim($row[2]); $plantCode = trim($row[2]);
$scannedAt = trim($row[3]); $scannedAt = trim($row[3]);
$scannedby = trim($row[4]); $scannedby = trim($row[4]);
if (empty($plantCode)) { if (empty($plantCode)) $invalidPlantCode[] = "Row {$index}";
$invalidPlantCode[] = "Row {$index}"; if (empty($qrCode)) $invalidqrCode[] = "Row {$index}";
} if (empty($scannedAt)) $invalidScannedAt[] = "Row {$index}";
if (empty($qrCode)) { if (empty($scannedby)) $invalidScannedBy[] = "Row {$index}";
$invalidqrCode[] = "Row {$index}";
}
if (empty($scannedAt)) {
$invalidScannedAt[] = "Row {$index}";
}
if (empty($scannedby)) {
$invalidScannedBy[] = "Row {$index}";
}
if (strlen($plantCode) < 4) { if (strlen($plantCode) < 4) {
$invalidPlantCode[] = $plantCode; $invalidPlantCode[] = $plantCode;
} elseif (! Plant::where('code', $plantCode)->first()) { }
else if(!Plant::where('code', $plantCode)->first())
{
$invalidPlaCoFound[] = $plantCode; $invalidPlaCoFound[] = $plantCode;
} }
@@ -234,7 +220,7 @@ class InvoiceOutValidationResource extends Resource
$plantId = $plant->id; $plantId = $plant->id;
$uniqueKey = $plantCode.'_'.$qrCode; $uniqueKey = $plantCode . '_' . $qrCode;
if (in_array($uniqueKey, $seenPlantQr)) { if (in_array($uniqueKey, $seenPlantQr)) {
$duplicateQrExcel[] = "Duplicate in file at Row {$index}: Document Number '{$qrCode}' already exists for Plant '{$plant->name}'"; $duplicateQrExcel[] = "Duplicate in file at Row {$index}: Document Number '{$qrCode}' already exists for Plant '{$plant->name}'";
@@ -251,18 +237,13 @@ class InvoiceOutValidationResource extends Resource
// } // }
} }
if (! empty($invalidqrCode) || ! empty($invalidScannedAt) || ! empty($invalidScannedBy) || ! empty($invalidUser)) { if (!empty($invalidqrCode) || !empty($invalidScannedAt) || !empty($invalidScannedBy) || !empty($invalidUser))
{
$errorMsg = ''; $errorMsg = '';
if (! empty($invalidqrCode)) { if (!empty($invalidqrCode)) $errorMsg .= 'Missing Qr code in rows: '.implode(', ', $invalidqrCode) . '<br>';
$errorMsg .= 'Missing Qr code in rows: '.implode(', ', $invalidqrCode).'<br>'; if (!empty($invalidScannedAt)) $errorMsg .= 'Missing Scanned At in rows: '.implode(', ', $invalidScannedAt) . '<br>';
} if (!empty($invalidScannedBy)) $errorMsg .= 'Missing Scanned By in rows: '.implode(', ', $invalidScannedBy) . '<br>';
if (! empty($invalidScannedAt)) {
$errorMsg .= 'Missing Scanned At in rows: '.implode(', ', $invalidScannedAt).'<br>';
}
if (! empty($invalidScannedBy)) {
$errorMsg .= 'Missing Scanned By in rows: '.implode(', ', $invalidScannedBy).'<br>';
}
Notification::make() Notification::make()
->title('Missing Mandatory Fields') ->title('Missing Mandatory Fields')
@@ -273,56 +254,53 @@ class InvoiceOutValidationResource extends Resource
if ($disk->exists($path)) { if ($disk->exists($path)) {
$disk->delete($path); $disk->delete($path);
} }
return; return;
} }
if (! empty($invalidPlantCode)) { if (!empty($invalidPlantCode)) {
$invalidPlantCode = array_unique($invalidPlantCode); $invalidPlantCode = array_unique($invalidPlantCode);
Notification::make() Notification::make()
->title('Invalid Plant Codes') ->title('Invalid Plant Codes')
->body('The following plant codes should contain minimum 4 digits:<br>'.implode(', ', $invalidPlantCode)) ->body('The following plant codes should contain minimum 4 digits:<br>' . implode(', ', $invalidPlantCode))
->danger() ->danger()
->send(); ->send();
if ($disk->exists($path)) { if ($disk->exists($path)) {
$disk->delete($path); $disk->delete($path);
} }
return; return;
} }
if (! empty($invalidPlaCoFound)) { if (!empty($invalidPlaCoFound)) {
$invalidPlaCoFound = array_unique($invalidPlaCoFound); $invalidPlaCoFound = array_unique($invalidPlaCoFound);
Notification::make() Notification::make()
->title('Invalid Plant Codes') ->title('Invalid Plant Codes')
->body('The following plant codes not found in plants:<br>'.implode(', ', $invalidPlaCoFound)) ->body('The following plant codes not found in plants:<br>' . implode(', ', $invalidPlaCoFound))
->danger() ->danger()
->send(); ->send();
if ($disk->exists($path)) { if ($disk->exists($path)) {
$disk->delete($path); $disk->delete($path);
} }
return; return;
} }
if (! empty($userNotFound)) { if (!empty($userNotFound)) {
$userNotFound = array_unique($userNotFound); $userNotFound = array_unique($userNotFound);
Notification::make() Notification::make()
->title('Invalid User') ->title('Invalid User')
->body('The following user not found:<br>'.implode(', ', $userNotFound)) ->body('The following user not found:<br>' . implode(', ', $userNotFound))
->danger() ->danger()
->send(); ->send();
if ($disk->exists($path)) { if ($disk->exists($path)) {
$disk->delete($path); $disk->delete($path);
} }
return; return;
} }
if (! empty($duplicateQrExcel)) { if (!empty($duplicateQrExcel))
{
$duplicateGroupedByPlantQr = []; $duplicateGroupedByPlantQr = [];
foreach ($duplicateQrExcel as $message) {// "/Document Numbers '([^']+)' already exists for Plant Code (\S+)/" foreach ($duplicateQrExcel as $message) {//"/Document Numbers '([^']+)' already exists for Plant Code (\S+)/"
if (preg_match("/Document Number '([^']+)' already exists for Plant '([^']+)'/", $message, $matches)) { if (preg_match("/Document Number '([^']+)' already exists for Plant '([^']+)'/", $message, $matches)) {
$qrCode = $matches[1]; $qrCode = $matches[1];
$plantCode = $matches[2]; $plantCode = $matches[2];
@@ -340,13 +318,13 @@ class InvoiceOutValidationResource extends Resource
$errorMsg .= "Duplicate Document Numbers for Plant <b>{$plantCode}</b> : {$count} Document Numbers already exist in uploaded file<br>"; $errorMsg .= "Duplicate Document Numbers for Plant <b>{$plantCode}</b> : {$count} Document Numbers already exist in uploaded file<br>";
} else { } else {
$errorMsg .= "Duplicate Document Numbers for Plant <b>{$plantCode}</b> : '" $errorMsg .= "Duplicate Document Numbers for Plant <b>{$plantCode}</b> : '"
.implode(', ', $uniqueQrCodes) . implode(', ', $uniqueQrCodes)
."' already exist in uploaded file<br>"; . "' already exist in uploaded file<br>";
} }
} }
Notification::make() Notification::make()
// ->title('Duplicate Document Number in Uploaded File') //->title('Duplicate Document Number in Uploaded File')
->body($errorMsg) ->body($errorMsg)
->danger() ->danger()
->send(); ->send();
@@ -402,16 +380,15 @@ class InvoiceOutValidationResource extends Resource
DB::beginTransaction(); DB::beginTransaction();
try { try
{
foreach ($rows as $index => $row) { foreach ($rows as $index => $row) {
if ($index == 0) { if ($index == 0) continue;
continue;
}
$rowNumber = $index + 1; $rowNumber = $index + 1;
try { try {
$qrcode = trim($row[1]); $qrcode = trim($row[1]);
$plantCode = trim($row[2]); $plantCode = trim($row[2]);
$scannedAt = trim($row[3]); $scannedAt = trim($row[3]);
$scannedBy = trim($row[4]); $scannedBy = trim($row[4]);
@@ -421,12 +398,12 @@ class InvoiceOutValidationResource extends Resource
} }
$plant = Plant::where('code', $plantCode)->first(); $plant = Plant::where('code', $plantCode)->first();
if (! $plant) { if (!$plant) {
throw new \Exception("Invalid plant code : '{$plantCode}'"); throw new \Exception("Invalid plant code : '{$plantCode}'");
} }
$formattedDate = null; $formattedDate = null;
if (! empty($scannedAt)) { if (!empty($scannedAt)) {
try { try {
// $formattedDate = Carbon::createFromFormat('d-m-Y H:i:s', $scannedAt) // $formattedDate = Carbon::createFromFormat('d-m-Y H:i:s', $scannedAt)
// ->format('Y-m-d H:i:s'); // ->format('Y-m-d H:i:s');
@@ -453,7 +430,7 @@ class InvoiceOutValidationResource extends Resource
$record->update([ $record->update([
'scanned_at' => $formattedDate, 'scanned_at' => $formattedDate,
'scanned_by' => $scannedBy, 'scanned_by' => $scannedBy,
'updated_by' => $operatorName, 'updated_by' => $operatorName
]); ]);
$inserted = $record; $inserted = $record;
} else { } else {
@@ -463,7 +440,7 @@ class InvoiceOutValidationResource extends Resource
'qr_code' => $qrcode, 'qr_code' => $qrcode,
'scanned_at' => $formattedDate, 'scanned_at' => $formattedDate,
'scanned_by' => $scannedBy, 'scanned_by' => $scannedBy,
'created_by' => $operatorName, 'created_by' => $operatorName
]); ]);
} }
// $inserted = InvoiceOutValidation::create([ // $inserted = InvoiceOutValidation::create([
@@ -474,7 +451,7 @@ class InvoiceOutValidationResource extends Resource
// 'created_by' => $operatorName // 'created_by' => $operatorName
// ]); // ]);
if (! $inserted) { if (!$inserted) {
throw new \Exception("{$curStat} failed for QR : {$qrcode}"); throw new \Exception("{$curStat} failed for QR : {$qrcode}");
} }
@@ -483,7 +460,7 @@ class InvoiceOutValidationResource extends Resource
$failedRecords[] = [ $failedRecords[] = [
'row' => $rowNumber, 'row' => $rowNumber,
'qrcode' => $qrcode ?? null, 'qrcode' => $qrcode ?? null,
'error' => $e->getMessage(), 'error' => $e->getMessage()
]; ];
} }
} }
@@ -492,13 +469,13 @@ class InvoiceOutValidationResource extends Resource
if (count($failedRecords) > 0) { if (count($failedRecords) > 0) {
$failedSummary = collect($failedRecords) $failedSummary = collect($failedRecords)
->map(fn ($f) => "Row {$f['row']} ({$f['qrcode']}) : {$f['error']}") ->map(fn($f) => "Row {$f['row']} ({$f['qrcode']}) : {$f['error']}")
->take(5) // limit preview to first 5 errors ->take(5) // limit preview to first 5 errors
->implode("\n"); ->implode("\n");
Notification::make() Notification::make()
->title('Partial Import Warning') ->title('Partial Import Warning')
->body("'{$successCount}' records inserted. ".count($failedRecords)." failed.\n\n{$failedSummary}") ->body("'{$successCount}' records inserted. " . count($failedRecords) . " failed.\n\n{$failedSummary}")
->warning() ->warning()
->send(); ->send();
} else { } else {
@@ -508,7 +485,9 @@ class InvoiceOutValidationResource extends Resource
->success() ->success()
->send(); ->send();
} }
} catch (\Exception $e) { }
catch (\Exception $e)
{
DB::rollBack(); DB::rollBack();
Notification::make() Notification::make()
->title('Import Failed') ->title('Import Failed')
@@ -518,14 +497,14 @@ class InvoiceOutValidationResource extends Resource
} }
} }
}) })
->visible(function () { ->visible(function() {
return Filament::auth()->user()->can('view import invoice out validation'); return Filament::auth()->user()->can('view import invoice out validation');
}), }),
ExportAction::make() ExportAction::make()
->label('Export Invoice Out Data') ->label('Export Invoice Out Data')
->color('warning') ->color('warning')
->exporter(InvoiceOutValidationExporter::class) ->exporter(InvoiceOutValidationExporter::class)
->visible(function () { ->visible(function() {
return Filament::auth()->user()->can('view export invoice out validation'); return Filament::auth()->user()->can('view export invoice out validation');
}), }),
]); ]);

View File

@@ -12,24 +12,24 @@ use App\Models\StickerMaster;
use Filament\Actions\Exports\Enums\ExportFormat; use Filament\Actions\Exports\Enums\ExportFormat;
use Filament\Facades\Filament; use Filament\Facades\Filament;
use Filament\Forms; use Filament\Forms;
use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\FileUpload; use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\Section;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput; use Filament\Forms\Components\TextInput;
use Filament\Forms\Form; use Filament\Forms\Form;
use Filament\Forms\Get; use Filament\Forms\Get;
use Filament\Notifications\Notification;
use Filament\Resources\Resource; use Filament\Resources\Resource;
use Filament\Tables; use Filament\Tables;
use Filament\Tables\Actions\ExportAction; use Filament\Tables\Actions\ExportAction;
use Filament\Tables\Actions\ImportAction; use Filament\Tables\Actions\ImportAction;
use Filament\Tables\Filters\Filter;
use Filament\Tables\Table; use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope; use Illuminate\Database\Eloquent\SoftDeletingScope;
use Filament\Forms\Components\Section;
use Filament\Forms\Components\Select;
use Filament\Notifications\Notification;
use Illuminate\Validation\Rule; use Illuminate\Validation\Rule;
use Maatwebsite\Excel\Facades\Excel; use Maatwebsite\Excel\Facades\Excel;
use Storage;
use Str;
class ItemResource extends Resource class ItemResource extends Resource
{ {
@@ -48,125 +48,125 @@ class ItemResource extends Resource
Section::make('') Section::make('')
->schema([ ->schema([
Forms\Components\Select::make('plant_id') Forms\Components\Select::make('plant_id')
->relationship('plant', 'name') ->relationship('plant', 'name')
->required() ->required()
// ->preload() // ->preload()
// ->nullable(), // ->nullable(),
->reactive() ->reactive()
->options(function (callable $get) { ->options(function (callable $get) {
$userHas = Filament::auth()->user()->plant_id; $userHas = Filament::auth()->user()->plant_id;
return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray();
return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); })
}) ->default(function () {
->default(function () { return optional(Item::latest()->first())->plant_id;
return optional(Item::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(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) { ->afterStateUpdated(function ($state, callable $set, callable $get) {
$plantId = $get('plant_id'); $plantId = $get('plant_id');
// Ensure `linestop_id` is not cleared // Ensure `linestop_id` is not cleared
if (! $plantId) { if (!$plantId) {
$set('iPlantError', 'Please select a plant first.'); $set('iPlantError', 'Please select a plant first.');
return;
}
else
{
$set('iPlantError', null);
}
})
->extraAttributes(fn ($get) => [
'class' => $get('iPlantError') ? 'border-red-500' : '',
])
->hint(fn ($get) => $get('iPlantError') ? $get('iPlantError') : null)
->hintColor('danger'),
Forms\Components\TextInput::make('category')
->label('Category')
->placeholder('Scan the Category'),
Forms\Components\TextInput::make('code')
->required()
->placeholder('Scan the valid code')
->autofocus(true)
// ->unique(ignoreRecord: true)
->alphaNum()
->minLength(6)
// ->autocapitalize('characters')
->reactive()
->disabled(fn (Get $get) => !empty($get('id')))
->afterStateUpdated(function ($state, callable $set, callable $get) {
$code = $get('code');
// Ensure `linestop_id` is not cleared
if (!$code) {
$set('iCodeError', 'Scan the valid code.');
return;
}
else
{
if (strlen($code) < 6) {
$set('iCodeError', 'Item code must be at least 6 digits.');
return; return;
} else {
$set('iPlantError', null);
} }
}) else if (!preg_match('/^[a-zA-Z0-9]{6,}$/', $code)) {
->extraAttributes(fn ($get) => [ $set('code',null);
'class' => $get('iPlantError') ? 'border-red-500' : '', $set('iCodeError', 'Item code must contain only alpha-numeric characters.');
])
->hint(fn ($get) => $get('iPlantError') ? $get('iPlantError') : null)
->hintColor('danger'),
Forms\Components\TextInput::make('category')
->label('Category')
->placeholder('Scan the Category'),
Forms\Components\TextInput::make('code')
->required()
->placeholder('Scan the valid code')
->autofocus(true)
// ->unique(ignoreRecord: true)
->alphaNum()
->minLength(6)
// ->autocapitalize('characters')
->reactive()
->disabled(fn (Get $get) => ! empty($get('id')))
->afterStateUpdated(function ($state, callable $set, callable $get) {
$code = $get('code');
// Ensure `linestop_id` is not cleared
if (! $code) {
$set('iCodeError', 'Scan the valid code.');
return; return;
} else {
if (strlen($code) < 6) {
$set('iCodeError', 'Item code must be at least 6 digits.');
return;
} elseif (! preg_match('/^[a-zA-Z0-9]{6,}$/', $code)) {
$set('code', null);
$set('iCodeError', 'Item code must contain only alpha-numeric characters.');
return;
}
$set('iCodeError', null);
} }
}) $set('iCodeError', null);
->extraAttributes(fn ($get) => [ }
'class' => $get('iCodeError') ? 'border-red-500' : '', })
]) ->extraAttributes(fn ($get) => [
->hint(fn ($get) => $get('iCodeError') ? $get('iCodeError') : null) 'class' => $get('iCodeError') ? 'border-red-500' : '',
->hintColor('danger') ])
->rule(function (callable $get) { ->hint(fn ($get) => $get('iCodeError') ? $get('iCodeError') : null)
return Rule::unique('items', 'code') ->hintColor('danger')
->where('plant_id', $get('plant_id')) ->rule(function (callable $get) {
->ignore($get('id')); // Ignore current record during updates return Rule::unique('items', 'code')
}), ->where('plant_id', $get('plant_id'))
Forms\Components\TextInput::make('hourly_quantity') ->ignore($get('id')); // Ignore current record during updates
->required() }),
->label('Hourly Quantity') Forms\Components\TextInput::make('hourly_quantity')
->placeholder('Scan the valid quantity') ->required()
->integer() ->label('Hourly Quantity')
->default(1) ->placeholder('Scan the valid quantity')
->minValue(1) ->integer()
->reactive() ->default(1)
->afterStateUpdated(function ($state, callable $set, callable $get) { ->minValue(1)
$hourQuan = $get('hourly_quantity'); ->reactive()
// Ensure `linestop_id` is not cleared ->afterStateUpdated(function ($state, callable $set, callable $get) {
if (! $hourQuan) { $hourQuan = $get('hourly_quantity');
$set('iHourQuanError', 'Scan the valid hourly quantity.'); // Ensure `linestop_id` is not cleared
if (!$hourQuan) {
$set('iHourQuanError', 'Scan the valid hourly quantity.');
return;
}
else
{
if (!preg_match('/^[0-9]{1,}$/', $hourQuan)) {
$set('hourly_quantity',null);
$set('iHourQuanError', 'Quantity must be integer value.');
return; return;
} else {
if (! preg_match('/^[0-9]{1,}$/', $hourQuan)) {
$set('hourly_quantity', null);
$set('iHourQuanError', 'Quantity must be integer value.');
return;
}
$set('iHourQuanError', null);
} }
}) $set('iHourQuanError', null);
->extraAttributes(fn ($get) => [ }
'class' => $get('iHourQuanError') ? 'border-red-500' : '', })
]) ->extraAttributes(fn ($get) => [
->hint(fn ($get) => $get('iHourQuanError') ? $get('iHourQuanError') : null) 'class' => $get('iHourQuanError') ? 'border-red-500' : '',
->hintColor('danger'), ])
Forms\Components\TextInput::make('uom') ->hint(fn ($get) => $get('iHourQuanError') ? $get('iHourQuanError') : null)
->required() ->hintColor('danger'),
->label('Unit of Measure') Forms\Components\TextInput::make('uom')
->placeholder('Scan the valid uom'), ->required()
->label('Unit of Measure')
->placeholder('Scan the valid uom'),
Forms\Components\TextInput::make('description') Forms\Components\TextInput::make('description')
->placeholder('Scan the valid description') ->placeholder('Scan the valid description')
->required() ->required()
->minLength(5) ->minLength(5)
->columnSpan(['default' => 1, 'sm' => 1]), ->columnSpan(['default' => 1, 'sm' => 1]),
// ->columnSpanFull(), // ->columnSpanFull(),
Forms\Components\TextInput::make('id') Forms\Components\TextInput::make('id')
->hidden() ->hidden()
->readOnly(), ->readOnly(),
]) ])
->columns(3), ->columns(3),
]); ]);
@@ -187,7 +187,6 @@ class ItemResource extends Resource
$paginator = $livewire->getTableRecords(); $paginator = $livewire->getTableRecords();
$perPage = method_exists($paginator, 'perPage') ? $paginator->perPage() : 10; $perPage = method_exists($paginator, 'perPage') ? $paginator->perPage() : 10;
$currentPage = method_exists($paginator, 'currentPage') ? $paginator->currentPage() : 1; $currentPage = method_exists($paginator, 'currentPage') ? $paginator->currentPage() : 1;
return ($currentPage - 1) * $perPage + $rowLoop->iteration; return ($currentPage - 1) * $perPage + $rowLoop->iteration;
}), }),
Tables\Columns\TextColumn::make('plant.name') Tables\Columns\TextColumn::make('plant.name')
@@ -239,135 +238,7 @@ class ItemResource extends Resource
]) ])
->filters([ ->filters([
Tables\Filters\TrashedFilter::make(), 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)->orderBy('code')->pluck('name', 'id')->toArray() : Plant::orderBy('code')->pluck('name', 'id')->toArray();
})
->reactive()
->afterStateUpdated(function ($state, callable $set, callable $get): void {
$set('code', null);
$set('operator_id', null);
}),
Select::make('code')
->label('Search by Item Code')
->nullable()
// ->options(function (callable $get) {
// $plantId = $get('Plant');
// return $plantId
// ? Item::where('plant_id', $plantId)->pluck('code', 'id')
// : Item::pluck('code', 'id');
// })
->options(function (callable $get) {
$plantId = $get('Plant');
return $plantId ? Item::where('plant_id', $plantId)->pluck('code', 'id') : [];
})
->searchable()
->reactive(),
TextInput::make('description')
->label('Search by Description')
->placeholder(placeholder: 'Enter Description'),
TextInput::make('category')
->label('Search by Category')
->placeholder(placeholder: 'Enter Category'),
TextInput::make('uom')
->label('Search by UOM')
->placeholder(placeholder: 'Enter UOM'),
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['code']) &&
empty($data['description']) &&
empty($data['uom']) &&
empty($data['category']) &&
empty($data['created_from']) &&
empty($data['created_to'])
) {
return $query->whereRaw('1 = 0');
}
if (! empty($data['Plant'])) { // $plant = $data['Plant'] ?? null
$query->where('plant_id', $data['Plant']);
}
if (! empty($data['code'])) {
$query->where('id', $data['code']);
}
if (! empty($data['description'])) {
$query->where('description', '%'.$data['description'].'%');
}
if (! empty($data['uom'])) {
$query->where('uom', 'like', '%'.$data['uom'].'%');
}
if (! empty($data['category'])) {
$query->where('category', '%'.$data['category'].'%');
}
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');
}
if (! empty($data['code'])) {
$indicators[] = 'Item Code: '.Item::where('id', $data['code'])->value('code');
}
if (! empty($data['description'])) {
$indicators[] = 'Description: '.$data['description'];
}
if (! empty($data['uom'])) {
$indicators[] = 'UOM: '.$data['uom'];
}
if (! empty($data['category'])) {
$indicators[] = 'Category: '.$data['category'];
}
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([ ->actions([
Tables\Actions\ViewAction::make(), Tables\Actions\ViewAction::make(),
Tables\Actions\EditAction::make(), Tables\Actions\EditAction::make(),
@@ -380,6 +251,7 @@ class ItemResource extends Resource
]), ]),
]) ])
->headerActions([ ->headerActions([
// Tables\Actions\Action::make('Import Items') // Tables\Actions\Action::make('Import Items')
// ->label('Import Items') // ->label('Import Items')
// ->form([ // ->form([
@@ -530,6 +402,7 @@ class ItemResource extends Resource
// return; // return;
// } // }
// $uniqueCodes = array_unique($materialCodes); // $uniqueCodes = array_unique($materialCodes);
// $matchedItems = StickerMaster::with('item') // $matchedItems = StickerMaster::with('item')
@@ -610,23 +483,23 @@ class ItemResource extends Resource
->label('Import Items') ->label('Import Items')
->color('warning') ->color('warning')
->importer(ItemImporter::class) ->importer(ItemImporter::class)
->visible(function () { ->visible(function() {
return Filament::auth()->user()->can('view import item'); return Filament::auth()->user()->can('view import item');
}), }),
// ->maxRows(100000), // ->maxRows(100000),
ExportAction::make() ExportAction::make()
// ->columnMapping(true) // ->columnMapping(true)
->label('Export Items') ->label('Export Items')
->color('warning') ->color('warning')
// ->fileName("Items Report " . date('Y-m-d H:i:s')) // ->fileName("Items Report " . date('Y-m-d H:i:s'))
->exporter(ItemExporter::class) ->exporter(ItemExporter::class)
->visible(function () { ->visible(function() {
return Filament::auth()->user()->can('view export item'); return Filament::auth()->user()->can('view export item');
}), }),
// ->formats([ // ->formats([
// ExportFormat::Xlsx, // ExportFormat::Xlsx,
// ExportFormat::Csv, // ExportFormat::Csv,
// ]), // ]),
]); ]);
} }

View File

@@ -159,7 +159,6 @@ class MachineResource extends Resource
->hintColor('danger'), ->hintColor('danger'),
Forms\Components\TextInput::make('name') Forms\Components\TextInput::make('name')
->label('Name') ->label('Name')
->minLength(5)
->placeholder('Scan the valid Machine Name') ->placeholder('Scan the valid Machine Name')
->required() ->required()
->rule(function (callable $get) { ->rule(function (callable $get) {
@@ -170,7 +169,6 @@ class MachineResource extends Resource
}), }),
Forms\Components\TextInput::make('work_center') Forms\Components\TextInput::make('work_center')
->label('Work Center') ->label('Work Center')
->minLength(6)
->placeholder('Scan the valid Work Center') ->placeholder('Scan the valid Work Center')
->required() ->required()
->rule(function (callable $get) { ->rule(function (callable $get) {

View File

@@ -46,22 +46,6 @@ class ProcessOrderResource extends Resource
return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray(); return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray();
}) })
->afterStateUpdated(function ($state, $set, callable $get, $livewire) {
$plantId = $get('plant_id');
$set('coil_number', null);
$set('sfg_number', null);
$set('machine_name', null);
if (! $plantId) {
$set('poPlantError', 'Please select a plant first.');
$set('coilNumberError', null);
$set('sfgNumberError', null);
}
})
->extraAttributes(fn ($get) => [
'class' => $get('poPlantError') ? 'border-red-500' : '',
])
->hint(fn ($get) => $get('poPlantError') ? $get('poPlantError') : null)
->hintColor('danger')
->required(), ->required(),
Forms\Components\Select::make('item_id') Forms\Components\Select::make('item_id')
->label('Item Code') ->label('Item Code')
@@ -109,7 +93,6 @@ class ProcessOrderResource extends Resource
->afterStateHydrated(function ($component, $state, Get $get, Set $set) { ->afterStateHydrated(function ($component, $state, Get $get, Set $set) {
$itemId = $get('item_id'); $itemId = $get('item_id');
if ($get('id')) { if ($get('id')) {
$item = \App\Models\Item::where('id', $itemId)->first()?->description; $item = \App\Models\Item::where('id', $itemId)->first()?->description;
if ($item) { if ($item) {
$set('item_description', $item); $set('item_description', $item);
@@ -123,66 +106,12 @@ class ProcessOrderResource extends Resource
->hidden() ->hidden()
->readOnly(), ->readOnly(),
// ->readOnly(true), // ->readOnly(true),
Forms\Components\TextInput::make('process_order') Forms\Components\TextInput::make('process_order')
->label('Process Order') ->label('Process Order')
->reactive()
->afterStateUpdated(function ($state, $set, callable $get, $livewire) {
$plantId = $get('plant_id');
$set('coil_number', null);
$set('sfg_number', null);
$set('machine_name', null);
if (! $plantId) {
$set('poPlantError', 'Please select a plant first.');
$set('process_order', null);
$set('coilNumberError', null);
$set('sfgNumberError', null);
}
})
->required(), ->required(),
Forms\Components\TextInput::make('coil_number') Forms\Components\TextInput::make('coil_number')
->label('Coil Number') ->label('Coil Number')
->default('0') ->default('0')
->reactive()
->afterStateUpdated(function ($state, $set, callable $get, $livewire) {
$plantId = $get('plant_id');
$processOrder = $get('process_order');
$coilNo = $get('coil_number');
if (! $plantId) {
$set('poPlantError', 'Please select a plant first.');
$set('coil_number', null);
$set('sfg_number', null);
$set('machine_name', null);
$set('coilNumberError', null);
$set('sfgNumberError', null);
} elseif (! $processOrder) {
$set('coil_number', null);
$set('sfg_number', null);
$set('machine_name', null);
$set('poPlantError', null);
$set('coilNumberError', null);
$set('sfgNumberError', null);
} elseif ($coilNo || $coilNo == '0') {
$existing = ProcessOrder::where('plant_id', $plantId)
->where('process_order', $processOrder)
->where('coil_number', $coilNo)
->first();
if ($existing) {
$set('poPlantError', null);
$set('coil_number', null);
$set('coilNumberError', "Duplicate Coil : '{$coilNo}' found!");
} else {
$set('poPlantError', null);
$set('coilNumberError', null);
}
}
})
->extraAttributes(fn ($get) => [
'class' => $get('coilNumberError') ? 'border-red-500' : '',
])
->hint(fn ($get) => $get('coilNumberError') ? $get('coilNumberError') : null)
->hintColor('danger')
->required(), ->required(),
Forms\Components\TextInput::make('order_quantity') Forms\Components\TextInput::make('order_quantity')
->label('Order Quantity') ->label('Order Quantity')
@@ -193,38 +122,10 @@ class ProcessOrderResource extends Resource
->required(), ->required(),
Forms\Components\TextInput::make('sfg_number') Forms\Components\TextInput::make('sfg_number')
->label('SFG Number') ->label('SFG Number')
->reactive() ->required(),
->afterStateUpdated(function ($state, $set, callable $get, $livewire) {
$plantId = $get('plant_id');
$sfgNo = $get('sfg_number');
if (! $plantId) {
$set('poPlantError', 'Please select a plant first.');
$set('sfg_number', null);
$set('machine_name', null);
$set('sfgNumberError', null); // 'Please select a plant first.'
} elseif ($sfgNo) {
$existing = ProcessOrder::where('plant_id', $plantId)
->where('sfg_number', $sfgNo)
->first();
if ($existing) {
$set('poPlantError', null);
$set('sfg_number', null);
$set('machine_name', null);
$set('sfgNumberError', "Duplicate SFG : '{$sfgNo}' found!");
} else {
$set('poPlantError', null);
$set('sfgNumberError', null);
}
}
})
->extraAttributes(fn ($get) => [
'class' => $get('sfgNumberError') ? 'border-red-500' : '',
])
->hint(fn ($get) => $get('sfgNumberError') ? $get('sfgNumberError') : null)
->hintColor('danger'),
Forms\Components\TextInput::make('machine_name') Forms\Components\TextInput::make('machine_name')
->label('Machine ID'), ->label('Machine ID')
->required(),
Forms\Components\FileUpload::make('attachment') Forms\Components\FileUpload::make('attachment')
->label('PDF Upload') ->label('PDF Upload')
->acceptedFileTypes(['application/pdf']) ->acceptedFileTypes(['application/pdf'])
@@ -469,7 +370,8 @@ class ProcessOrderResource extends Resource
->label('Created At') ->label('Created At')
->alignCenter() ->alignCenter()
->dateTime() ->dateTime()
->sortable(), ->sortable()
->toggleable(isToggledHiddenByDefault: true),
Tables\Columns\TextColumn::make('created_by') Tables\Columns\TextColumn::make('created_by')
->label('Created By') ->label('Created By')
->alignCenter() ->alignCenter()

File diff suppressed because it is too large Load Diff

View File

@@ -1,199 +0,0 @@
<?php
namespace App\Filament\Resources;
use App\Filament\Resources\StickerPrintingResource\Pages;
use App\Models\Plant;
use App\Models\StickerPrinting;
use Filament\Facades\Filament;
use Filament\Forms;
use Filament\Forms\Components\Section;
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\Tables\Actions\ExportAction;
use Filament\Tables\Actions\ImportAction;
use App\Filament\Exports\StickerPrintingExporter;
use App\Filament\Imports\StickerPrintingImporter;
use Filament\Forms\Components\Actions\Action;
class StickerPrintingResource extends Resource
{
protected static ?string $model = StickerPrinting::class;
protected static ?string $navigationIcon = 'heroicon-o-rectangle-stack';
public static function form(Form $form): Form
{
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();
})
->required()
->afterStateUpdated(function ($state, callable $set, callable $get) {
$plantId = $get('plant_id');
if (!$plantId) {
$set('reference_number', null);
$set('serial_number', null);
$set('ivPlantError', 'Please select a plant first.');
} else {
$set('ivPlantError', null);
$set('reference_number', null);
$set('serial_number', null);
}
})
->extraAttributes(fn ($get) => [
'class' => $get('ivPlantError') ? 'border-red-500' : '',
])
->hint(fn ($get) => $get('ivPlantError') ? $get('ivPlantError') : null)
->hintColor('danger'),
Forms\Components\TextInput::make('reference_number')
->label('Reference Number')
->reactive()
->readOnly(fn (callable $get) => !empty($get('serial_number')))
->extraAttributes([
'id' => 'invoice_number_input',
'x-data' => '{ value: "" }',
'x-model' => 'value',
'wire:keydown.enter.prevent' => 'processRef(value)',
])
->required(),
Forms\Components\TextInput::make('serial_number')
->label('Serial Number')
->reactive()
// ->required()
->readOnly(fn (callable $get) => empty($get('reference_number')))
->extraAttributes([
'id' => 'serial_number_input',
'x-data' => '{ value: "" }',
'x-model' => 'value',
'wire:keydown.enter.prevent' => 'processSno(value)',
//'x-on:keydown.enter.prevent' => '$wire.processInvoice(value)',
]),
//->required(),
Forms\Components\View::make('forms.components.print-button'),
Forms\Components\Hidden::make('created_by')
->label('Created By')
->default(Filament::auth()->user()?->name),
Forms\Components\Hidden::make('updated_by')
->label('Updated By')
->default(Filament::auth()->user()?->name),
])
->columns(4),
]);
}
public static function table(Table $table): Table
{
return $table
->columns([
Tables\Columns\TextColumn::make('No.')
->label('No.')
->getStateUsing(function ($record, $livewire, $column, $rowLoop) {
$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')
->label('Plant')
->searchable()
->sortable(),
Tables\Columns\TextColumn::make('reference_number')
->label('Reference Number')
->searchable()
->sortable(),
Tables\Columns\TextColumn::make('serial_number')
->label('Serial Number')
->searchable()
->sortable(),
Tables\Columns\TextColumn::make('created_by')
->label('Created By')
->searchable()
->sortable(),
Tables\Columns\TextColumn::make('created_at')
->dateTime()
->sortable()
->toggleable(isToggledHiddenByDefault: true),
Tables\Columns\TextColumn::make('updated_at')
->dateTime()
->sortable()
->toggleable(isToggledHiddenByDefault: true),
Tables\Columns\TextColumn::make('deleted_at')
->dateTime()
->sortable()
->toggleable(isToggledHiddenByDefault: true),
])
->filters([
Tables\Filters\TrashedFilter::make(),
])
->actions([
Tables\Actions\ViewAction::make(),
Tables\Actions\EditAction::make(),
])
->bulkActions([
Tables\Actions\BulkActionGroup::make([
Tables\Actions\DeleteBulkAction::make(),
Tables\Actions\ForceDeleteBulkAction::make(),
Tables\Actions\RestoreBulkAction::make(),
]),
])
->headerActions([
ImportAction::make()
->importer(StickerPrintingImporter::class)
->label('Import Sticker Printing')
->color('warning')
->visible(function () {
return Filament::auth()->user()->can('view import sticker printing');
}),
ExportAction::make()
->exporter(StickerPrintingExporter::class)
->label('Export Sticker Printing')
->color('warning')
->visible(function () {
return Filament::auth()->user()->can('view export sticker printing');
}),
]);
}
public static function getRelations(): array
{
return [
//
];
}
public static function getPages(): array
{
return [
'index' => Pages\ListStickerPrintings::route('/'),
'create' => Pages\CreateStickerPrinting::route('/create'),
'view' => Pages\ViewStickerPrinting::route('/{record}'),
'edit' => Pages\EditStickerPrinting::route('/{record}/edit'),
];
}
public static function getEloquentQuery(): Builder
{
return parent::getEloquentQuery()
->withoutGlobalScopes([
SoftDeletingScope::class,
]);
}
}

View File

@@ -1,244 +0,0 @@
<?php
namespace App\Filament\Resources\StickerPrintingResource\Pages;
use App\Filament\Resources\StickerPrintingResource;
use Filament\Resources\Pages\CreateRecord;
use PDF;
use SimpleSoftwareIO\QrCode\Facades\QrCode;
use Filament\Facades\Filament;
use App\Models\StickerPrinting;
use Filament\Notifications\Notification;
use Str;
class CreateStickerPrinting extends CreateRecord
{
protected static string $resource = StickerPrintingResource::class;
protected static string $view = 'filament.resources.sticker-printing-resource.pages.create-sticker-printing';
public $plantId;
public $ref_number;
public $ref;
public $serial_number;
public function getFormActions(): array
{
return [
$this->getCancelFormAction(),
];
}
protected function getRedirectUrl(): string
{
return $this->getResource()::getUrl('create');
}
public function loadRecords()
{
$this->records = StickerPrinting::where('reference_number', $this->refNumber)
->where('plant_id', $this->plantId)
->latest()
->get();
}
public function processRef($value)
{
//$this->ref_number = $value;
$ref = $this->form->getState()['reference_number'] ?? null;
$user = Filament::auth()->user();
$operatorName = $user->name;
$plantId = $this->form->getState()['plant_id'];
$this->plantId = $plantId;
$this->dispatch('refreshEmptySticker', $plantId, $ref);
$this->dispatch('focus-serial-number');
}
public function processSno($value)
{
$this->serial_number = $value;
$plant = $this->form->getState()['plant_id'] ?? null;
$ref = $this->form->getState()['reference_number'] ?? null;
$sNumber = $this->form->getState()['serial_number'] ?? null;
$pattern1 = '/^(?<item_code>[^|]+)\|(?<serial_number>[^|]+)\|?$/i';
$pattern2 = '/^(?<item_code>[^|]+)\|(?<serial_number>[^|]+)\|(?<batch_number>.+)$/i';
$pattern3 = '/^(?<serial_number>[^|]+)$/i';
if (preg_match($pattern1, $sNumber, $matches) || preg_match($pattern2, $sNumber, $matches) || preg_match($pattern3, $sNumber, $matches)) {
$serial = $matches['serial_number'];
if (Str::length($serial) < 9) {
Notification::make()
->title('Invalid Serial Number')
->body("Serial number should conatin minimum 9 digits '$serial'.")
->warning()
->send();
$this->form->fill([
'plant_id' => $plant,
'reference_number' => $ref,
'serial_number' => '',
]);
return;
}
else if(!ctype_alnum($serial)) {
Notification::make()
->title('Invalid Serial Number')
->body("Serial number should be alphanumeric '$serial'.")
->warning()
->send();
$this->form->fill([
'plant_id' => $plant,
'reference_number' => $ref,
'serial_number' => '',
]);
return;
}
$extractedSerialNumber = $matches['serial_number'];
$sNumber = $extractedSerialNumber;
}
else
{
Notification::make()
->title('Invalid Format')
->body("Serial number must be in the format 'itemcode|serialnumber' or 'itemcode|serialnumber|batchnumber'. or just 'serialnumber'.")
->warning()
->send();
// Reset only serial number field
$this->form->fill([
'plant_id' => $plant,
'reference_number' => $ref,
'serial_number' => '',
]);
return;
}
if ($plant == null || trim($plant) == '' || $ref == null || trim($ref) == '' || $sNumber == null || trim($sNumber) == '')
{
Notification::make()
->title('Unknown: Incomplete Data!')
->body("Please ensure Plant, Reference Number, and Serial Number are provided.")
->danger()
->seconds(3)
->send();
return;
}
$exists = StickerPrinting::where('plant_id', $plant)
->where('serial_number', $sNumber)
->first();
if ($exists) {
Notification::make()
->title('Duplicate Serial Number!')
->body("Serial Number {$sNumber} already exists for this plant.")
->danger()
->seconds(3)
->send();
// Reset only serial number field
$this->form->fill([
'plant_id' => $plant,
'reference_number' => $ref,
'serial_number' => '',
]);
return;
}
StickerPrinting::create([
'plant_id' => $plant,
'reference_number' => $ref,
'serial_number' => $sNumber,
'created_by' => Filament::auth()->user()->name,
]);
$this->dispatch('addStickerToList', $plant, $ref, $sNumber);
$this->form->fill([
'plant_id' => $plant,
'reference_number' => $ref,
'serial_number' => '',
]);
}
public function printSticker() {
$plantId = $this->form->getState()['plant_id'];
$plantId = trim($plantId) ?? null;
$refNumber = trim($this->form->getState()['reference_number'])?? null;
$refNumber = trim($refNumber) ?? null;
$serialNumber = trim($this->form->getState()['serial_number'])?? null;
$serialNumber = trim($serialNumber) ?? null;
// dd($plantId, $refNumber, $serialNumber);
$serialNumbers = StickerPrinting::where('plant_id', $plantId)
->where('reference_number', $refNumber)
->pluck('serial_number')
->toArray();
if (empty($serialNumbers))
{
Notification::make()
->title('No Serial Numbers found!')
->body('Please check the selected Plant & Reference Number.')
->danger()
->send();
return;
}
// Encode as JSON string in QR Code
// $qrData = json_encode([
// 'serial_numbers' => $serialNumbers,
// ]);
//$qrData = implode(',', $serialNumbers);
$qrData = implode("\n", $serialNumbers);
$qrCode = base64_encode(
QrCode::format('png')
->size(1200) // smaller, still high res
->margin(6) // white border
->errorCorrection('Q')// medium-high correction
->generate($qrData)
);
// Send data to Pdf view
$pdf = PDF::loadView('pdf.qrcode', [
'qrCode' => $qrCode,
'referenceNumber' => $refNumber,
]);
return response()->streamDownload(function () use ($pdf) {
echo $pdf->output();
}, "qr-sticker.pdf");
}
}

View File

@@ -1,22 +0,0 @@
<?php
namespace App\Filament\Resources\StickerPrintingResource\Pages;
use App\Filament\Resources\StickerPrintingResource;
use Filament\Actions;
use Filament\Resources\Pages\EditRecord;
class EditStickerPrinting extends EditRecord
{
protected static string $resource = StickerPrintingResource::class;
protected function getHeaderActions(): array
{
return [
Actions\ViewAction::make(),
Actions\DeleteAction::make(),
Actions\ForceDeleteAction::make(),
Actions\RestoreAction::make(),
];
}
}

View File

@@ -1,19 +0,0 @@
<?php
namespace App\Filament\Resources\StickerPrintingResource\Pages;
use App\Filament\Resources\StickerPrintingResource;
use Filament\Actions;
use Filament\Resources\Pages\ListRecords;
class ListStickerPrintings extends ListRecords
{
protected static string $resource = StickerPrintingResource::class;
protected function getHeaderActions(): array
{
return [
Actions\CreateAction::make(),
];
}
}

View File

@@ -1,19 +0,0 @@
<?php
namespace App\Filament\Resources\StickerPrintingResource\Pages;
use App\Filament\Resources\StickerPrintingResource;
use Filament\Actions;
use Filament\Resources\Pages\ViewRecord;
class ViewStickerPrinting extends ViewRecord
{
protected static string $resource = StickerPrintingResource::class;
protected function getHeaderActions(): array
{
return [
Actions\EditAction::make(),
];
}
}

View File

@@ -631,11 +631,10 @@ class PdfController extends Controller
], 404); ], 404);
} }
Log::info('Process Order POST API called >>', ['request_data' => $request->all()]);
$plantCode = $request->header('plant-code'); $plantCode = $request->header('plant-code');
$processOrder = $request->header('process-order'); $processOrder = $request->header('process-order');
$data = $request->all();
Log::info('Process Order POST API >>', ['plant-code' => $plantCode, 'process-order' => $processOrder, 'post-data' => $data]);
if ($plantCode == null || $plantCode == '' || ! $plantCode) { if ($plantCode == null || $plantCode == '' || ! $plantCode) {
return response()->json([ return response()->json([
@@ -666,6 +665,8 @@ class PdfController extends Controller
$plantId = $plant->id; $plantId = $plant->id;
$data = $request->all();
$itemCode = $data['item_code'] ?? ''; $itemCode = $data['item_code'] ?? '';
$coilNo = $data['coil_number'] ?? ''; $coilNo = $data['coil_number'] ?? '';
$orderQty = $data['order_quantity'] ?? 0; $orderQty = $data['order_quantity'] ?? 0;
@@ -713,19 +714,19 @@ class PdfController extends Controller
], 404); ], 404);
} }
// if ($sfgNo == null || $sfgNo == '' || ! $sfgNo) { if ($sfgNo == null || $sfgNo == '' || ! $sfgNo) {
// return response()->json([ return response()->json([
// 'status_code' => 'ERROR', 'status_code' => 'ERROR',
// 'status_description' => "SFG number can't be empty!", 'status_description' => "SFG number can't be empty!",
// ], 404); ], 404);
// } }
// if ($machineId == null || $machineId == '' || ! $machineId) { if ($machineId == null || $machineId == '' || ! $machineId) {
// return response()->json([ return response()->json([
// 'status_code' => 'ERROR', 'status_code' => 'ERROR',
// 'status_description' => "Machine ID can't be empty!", 'status_description' => "Machine ID can't be empty!",
// ], 404); ], 404);
// } }
if ($createdBy == null || $createdBy == '' || ! $createdBy) { if ($createdBy == null || $createdBy == '' || ! $createdBy) {
return response()->json([ return response()->json([
@@ -777,23 +778,19 @@ class PdfController extends Controller
], 404); ], 404);
} }
$itemId = $itemPlant->id; $existing = ProcessOrder::where('plant_id', $plantId)
->where('sfg_number', $sfgNo)
->first();
if ($sfgNo != null && $sfgNo != '' && Str::length($sfgNo) > 0 && $sfgNo) { if ($existing) {
$existing = ProcessOrder::where('plant_id', $plantId) return response()->json([
->where('sfg_number', $sfgNo) 'status_code' => 'ERROR',
->first(); 'status_description' => "SFG number '{$sfgNo}' already exist for the plant code '{$plantCode}'!",
], 404);
if ($existing) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "SFG number '{$sfgNo}' already exist for the plant code '{$plantCode}'!",
], 404);
}
} else {
$sfgNo = null;
} }
$itemId = $itemPlant->id;
$existing = ProcessOrder::where('plant_id', $plantId) $existing = ProcessOrder::where('plant_id', $plantId)
->where('process_order', $processOrder) ->where('process_order', $processOrder)
->where('item_id', '!=', $itemId) ->where('item_id', '!=', $itemId)

View File

@@ -2,6 +2,7 @@
namespace App\Livewire; namespace App\Livewire;
use App\Filament\Resources\InvoiceValidationResource\Pages\CreateInvoiceValidation;
use App\Models\InvoiceValidation; use App\Models\InvoiceValidation;
use App\Models\StickerMaster; use App\Models\StickerMaster;
use Filament\Facades\Filament; use Filament\Facades\Filament;
@@ -33,14 +34,14 @@ class InvoiceDataTable extends Component
public bool $showCapacitorInput = false; public bool $showCapacitorInput = false;
// protected $listeners = ['refreshInvoiceData' => 'loadData',]; // protected $listeners = ['refreshInvoiceData' => 'loadData',];
protected $listeners = [ protected $listeners = [
'refreshCompletedInvoice' => 'loadCompletedData', 'refreshCompletedInvoice' => 'loadCompletedData',
'refreshEmptyInvoice' => 'loadEmptyData', 'refreshEmptyInvoice' => 'loadEmptyData',
'refreshInvoiceData' => 'loadData', 'refreshInvoiceData' => 'loadData',
'refreshMaterialInvoiceData' => 'loadMaterialData', 'refreshMaterialInvoiceData' => 'loadMaterialData',
'openCapacitorModal' => 'showCapacitorInputBox', 'openCapacitorModal' => 'showCapacitorInputBox'
]; ];
public $capacitorInput = ''; public $capacitorInput = '';
@@ -95,83 +96,101 @@ class InvoiceDataTable extends Component
$this->materialInvoice = false; $this->materialInvoice = false;
// $this->showCapacitorInput = false; // $this->showCapacitorInput = false;
// ->where('serial_number', '!=', '') //->where('serial_number', '!=', '')
$this->invoiceData = InvoiceValidation::where('invoice_number', $this->invoiceNumber) $this->invoiceData = InvoiceValidation::where('invoice_number', $this->invoiceNumber)
->where('plant_id', $plantId)->where('scanned_status', null) ->where('plant_id', $plantId)->where('scanned_status', null)
->get() ->get()
->map(function ($record) { ->map(function ($record) {
return [ return [
'sticker_master_id' => $record->sticker_master_id, 'sticker_master_id' => $record->sticker_master_id,
'serial_number' => $record->serial_number, 'serial_number' => $record->serial_number,
'motor_scanned_status' => $record->motor_scanned_status ?? '', 'motor_scanned_status' => $record->motor_scanned_status ?? '',
'pump_scanned_status' => $record->pump_scanned_status ?? '', 'pump_scanned_status' => $record->pump_scanned_status ?? '',
'capacitor_scanned_status' => $record->capacitor_scanned_status ?? '', 'capacitor_scanned_status' => $record->capacitor_scanned_status ?? '',
'scanned_status_set' => $record->scanned_status_set ?? '', 'scanned_status_set' => $record->scanned_status_set ?? '',
'scanned_status' => $record->scanned_status ?? '', 'scanned_status' => $record->scanned_status ?? '',
'panel_box_supplier' => $record->panel_box_supplier ?? '', 'panel_box_supplier' => $record->panel_box_supplier ?? '',
'panel_box_serial_number' => $record->panel_box_serial_number ?? '', 'panel_box_serial_number' => $record->panel_box_serial_number ?? '',
'created_at' => $record->created_at, 'created_at' => $record->created_at,
'operator_id' => $record->operator_id, 'operator_id' => $record->operator_id,
]; ];
}) })
->toArray(); ->toArray();
$this->packageCount = 0; $this->packageCount = 0;
// Loop through and replace 'code' using related StickerMaster > Item > code //Loop through and replace 'code' using related StickerMaster > Item > code
foreach ($this->invoiceData as &$row) { foreach ($this->invoiceData as &$row) {
$stickCount = 0; $stickCount = 0;
$scannedCount = 0; $scannedCount = 0;
// $stickerMaster = \App\Models\StickerMaster::with('item')->find($row['sticker_master_id'] ?? null); // $stickerMaster = \App\Models\StickerMaster::with('item')->find($row['sticker_master_id'] ?? null);
$row['code'] = StickerMaster::with('item')->find($row['sticker_master_id'] ?? null)?->item?->code ?? 'N/A'; $row['code'] = StickerMaster::with('item')->find($row['sticker_master_id'] ?? null)?->item?->code ?? 'N/A';
$curStick = StickerMaster::where('id', $row['sticker_master_id'])->first(); $curStick = StickerMaster::where('id', $row['sticker_master_id'])->first();
if ($curStick) { if ($curStick)
if (Str::length($curStick->panel_box_code) > 0) { {
$stickCount++; if ($curStick->tube_sticker_motor == 1 || $curStick->tube_sticker_pump == 1 || $curStick->tube_sticker_pumpset == 1 || Str::length($curStick->panel_box_code) > 0)
{
if ($curStick->tube_sticker_motor == 1)
{
$stickCount++;
}
if ($curStick->tube_sticker_pump == 1)
{
$stickCount++;
}
if ($curStick->tube_sticker_pumpset == 1)
{
$stickCount++;
}
if (Str::length($curStick->panel_box_code) > 0)
{
$stickCount++;
}
} }
if ($curStick->tube_sticker_motor == 1 || $curStick->tube_sticker_pump == 1 || $curStick->tube_sticker_pumpset == 1) { else if ($curStick->pack_slip_motor == 1 || $curStick->pack_slip_pump == 1 || $curStick->pack_slip_pumpset == 1)
if ($curStick->tube_sticker_motor == 1) { {
if ($curStick->pack_slip_motor == 1)
{
$stickCount++; $stickCount++;
} }
if ($curStick->tube_sticker_pump == 1 || ($curStick->tube_sticker_pumpset != 1 && $curStick->tube_sticker_pump != 1 && $curStick->pack_slip_pump == 1)) { if ($curStick->pack_slip_pump == 1)
{
$stickCount++; $stickCount++;
} }
if ($curStick->tube_sticker_pumpset == 1) { if ($curStick->pack_slip_pumpset == 1)
$stickCount++; {
}
} elseif ($curStick->pack_slip_motor == 1 || $curStick->pack_slip_pump == 1 || $curStick->pack_slip_pumpset == 1) {
if ($curStick->pack_slip_motor == 1) {
$stickCount++;
}
if ($curStick->pack_slip_pump == 1) {
$stickCount++;
}
if ($curStick->pack_slip_pumpset == 1) {
$stickCount++; $stickCount++;
} }
} }
} }
if ($row['motor_scanned_status'] == 1) { if ($row['motor_scanned_status'] == 1)
{
$scannedCount++; $scannedCount++;
} }
if ($row['pump_scanned_status'] == 1) { if ($row['pump_scanned_status'] == 1)
{
$scannedCount++; $scannedCount++;
} }
if ($row['capacitor_scanned_status'] == 1) { if ($row['capacitor_scanned_status'] == 1)
{
$scannedCount++; $scannedCount++;
} }
if ($row['scanned_status_set'] == 1) { if ($row['scanned_status_set'] == 1)
{
$scannedCount++; $scannedCount++;
} }
$this->packageCount += $stickCount - $scannedCount; $this->packageCount += $stickCount - $scannedCount;
} }
if ($onCapFocus) { if ($onCapFocus)
{
$this->dispatch('focus-capacitor-input'); $this->dispatch('focus-capacitor-input');
} else { }
else
{
$this->dispatch('focus-serial-number'); $this->dispatch('focus-serial-number');
} }
} }
@@ -188,36 +207,43 @@ class InvoiceDataTable extends Component
$this->materialInvoice = true; $this->materialInvoice = true;
// $this->showCapacitorInput = false; // $this->showCapacitorInput = false;
// ->where('serial_number', '!=', '') //->where('serial_number', '!=', '')
$this->invoiceData = InvoiceValidation::where('invoice_number', $this->invoiceNumber)->where('plant_id', $plantId)->where('serial_number', null) $this->invoiceData = InvoiceValidation::where('invoice_number', $this->invoiceNumber)->where('plant_id', $plantId)->where('serial_number', null)
->get() ->get()
->map(function ($record) { ->map(function ($record) {
return [ return [
'sticker_master_id' => $record->sticker_master_id, 'sticker_master_id' => $record->sticker_master_id,
// 'material_type' => StickerMaster::where('id', $record->sticker_master_id)->first()->material_type ?? '', // 'material_type' => StickerMaster::where('id', $record->sticker_master_id)->first()->material_type ?? '',
'quantity' => $record->quantity ?? '', 'quantity' => $record->quantity ?? '',
'serial_number' => $record->serial_number ?? '', 'serial_number' => $record->serial_number ?? '',
'batch_number' => $record->batch_number ?? '', 'batch_number' => $record->batch_number ?? '',
'created_at' => $record->created_at, 'created_at' => $record->created_at,
'operator_id' => $record->operator_id, 'operator_id' => $record->operator_id,
]; ];
}) })
->toArray(); ->toArray();
// Loop through and replace 'code' using related StickerMaster > Item > code //Loop through and replace 'code' using related StickerMaster > Item > code
foreach ($this->invoiceData as &$row) { foreach ($this->invoiceData as &$row) {
// $stickerMaster = \App\Models\StickerMaster::with('item')->find($row['sticker_master_id'] ?? null); // $stickerMaster = \App\Models\StickerMaster::with('item')->find($row['sticker_master_id'] ?? null);
$row['code'] = StickerMaster::with('item')->find($row['sticker_master_id'] ?? null)?->item?->code ?? 'N/A'; $row['code'] = StickerMaster::with('item')->find($row['sticker_master_id'] ?? null)?->item?->code ?? 'N/A';
$matType = StickerMaster::where('id', $row['sticker_master_id'] ?? null)->first()->material_type ?? ''; $matType = StickerMaster::where('id', $row['sticker_master_id'] ?? null)->first()->material_type ?? '';
if ($matType === 1) { if ($matType === 1)
{
$row['material_type'] = 'Individual'; $row['material_type'] = 'Individual';
} elseif ($matType === 2) { }
else if ($matType === 2)
{
$row['material_type'] = 'Bundle'; $row['material_type'] = 'Bundle';
} elseif ($matType === 3) { }
else if ($matType === 3)
{
$row['material_type'] = 'Quantity'; $row['material_type'] = 'Quantity';
} else { }
else
{
$row['material_type'] = 'N/A'; $row['material_type'] = 'N/A';
} }
} }
$this->dispatch('focus-serial-number'); $this->dispatch('focus-serial-number');
} }
@@ -249,11 +275,11 @@ class InvoiceDataTable extends Component
$user = Filament::auth()->user(); $user = Filament::auth()->user();
$operatorName = $user->name; $operatorName = $user->name;
if (! $this->capacitorInput) { if (!$this->capacitorInput) {
return; return;
} }
if (! preg_match('/^[^\/]+\/[^\/]+\/.+$/', $this->capacitorInput)) { if (!preg_match('/^[^\/]+\/[^\/]+\/.+$/', $this->capacitorInput)) {
Notification::make() Notification::make()
->title('Invalid Panel Box QR Format:') ->title('Invalid Panel Box QR Format:')
->body('Scan the valid panel box QR code to proceed!') ->body('Scan the valid panel box QR code to proceed!')
@@ -261,7 +287,6 @@ class InvoiceDataTable extends Component
// ->duration(3000) // ->duration(3000)
->seconds(2) ->seconds(2)
->send(); ->send();
return; return;
} }
@@ -273,9 +298,9 @@ class InvoiceDataTable extends Component
$existsInStickerMaster = StickerMaster::where('panel_box_code', $itemCode)->where('plant_id', $this->plantId)->whereHas('item', function ($query) { $existsInStickerMaster = StickerMaster::where('panel_box_code', $itemCode)->where('plant_id', $this->plantId)->whereHas('item', function ($query) {
$query->where('code', $this->currentItemCode); $query->where('code', $this->currentItemCode);
}) })
->exists(); ->exists();
if (! $existsInStickerMaster) { if (!$existsInStickerMaster) {
Notification::make() Notification::make()
->title('Unknown: Panel Box Code') ->title('Unknown: Panel Box Code')
->body("Unknown panel box code: $itemCode found for item code: $this->currentItemCode") ->body("Unknown panel box code: $itemCode found for item code: $this->currentItemCode")
@@ -284,12 +309,12 @@ class InvoiceDataTable extends Component
->seconds(2) ->seconds(2)
->send(); ->send();
$this->capacitorInput = ''; $this->capacitorInput = '';
return; return;
} }
foreach ($this->invoiceData as &$row) { foreach ($this->invoiceData as &$row) {
if (($row['code'] ?? '') === $this->currentItemCode && ($row['serial_number'] ?? '') === $this->currentSerialNumber) { if (($row['code'] ?? '') === $this->currentItemCode && ($row['serial_number'] ?? '') === $this->currentSerialNumber)
{
$row['panel_box_supplier'] = $supplier; $row['panel_box_supplier'] = $supplier;
$row['panel_box_item_code'] = $itemCode; $row['panel_box_item_code'] = $itemCode;
$row['panel_box_serial_number'] = $serialNumber; $row['panel_box_serial_number'] = $serialNumber;
@@ -318,41 +343,47 @@ class InvoiceDataTable extends Component
$packCnt = 1; $packCnt = 1;
$scanCnt = 1; $scanCnt = 1;
// if ($hadMotorQr === $hasMotorQr && $hadPumpQr === $hasPumpQr && $hadPumpSetQr === $hasPumpSetQr) // if ($hadMotorQr === $hasMotorQr && $hadPumpQr === $hasPumpQr && $hadPumpSetQr === $hasPumpSetQr)
if ($hasMotorQr || $hasPumpQr || $hasPumpSetQr) { if ($hasMotorQr || $hasPumpQr || $hasPumpSetQr)
{
$packCnt = $hasMotorQr ? $packCnt + 1 : $packCnt; $packCnt = $hasMotorQr ? $packCnt + 1 : $packCnt;
$packCnt = $hasPumpQr ? $packCnt + 1 : $packCnt; $packCnt = $hasPumpQr ? $packCnt + 1 : $packCnt;
$packCnt = $hasPumpSetQr ? $packCnt + 1 : $packCnt; $packCnt = $hasPumpSetQr ? $packCnt + 1 : $packCnt;
$scanCnt = $hadMotorQr ? $scanCnt + 1 : $scanCnt; $scanCnt = $hadMotorQr ? $scanCnt + 1: $scanCnt;
$scanCnt = $hadPumpQr ? $scanCnt + 1 : $scanCnt; $scanCnt = $hadPumpQr ? $scanCnt + 1: $scanCnt;
$scanCnt = $hadPumpSetQr ? $scanCnt + 1 : $scanCnt; $scanCnt = $hadPumpSetQr ? $scanCnt + 1: $scanCnt;
if ($packCnt === $scanCnt) { if ($packCnt === $scanCnt)
{
$matchingValidation->update([ $matchingValidation->update([
'panel_box_supplier' => $supplier, 'panel_box_supplier' => $supplier,
'panel_box_item_code' => $itemCode, 'panel_box_item_code' => $itemCode,
'panel_box_serial_number' => $serialNumber, 'panel_box_serial_number' => $serialNumber,
'capacitor_scanned_status' => 1, 'capacitor_scanned_status' => 1,
'scanned_status' => 'Scanned', 'scanned_status' => 'Scanned',
'operator_id' => $operatorName, 'operator_id'=> $operatorName,
]); ]);
} else { }
else
{
$matchingValidation->update([ $matchingValidation->update([
'panel_box_supplier' => $supplier, 'panel_box_supplier' => $supplier,
'panel_box_item_code' => $itemCode, 'panel_box_item_code' => $itemCode,
'panel_box_serial_number' => $serialNumber, 'panel_box_serial_number' => $serialNumber,
'capacitor_scanned_status' => 1, 'capacitor_scanned_status' => 1,
'operator_id' => $operatorName, 'operator_id'=> $operatorName,
]); ]);
} }
} else { }
else
{
$matchingValidation->update([ $matchingValidation->update([
'panel_box_supplier' => $supplier, 'panel_box_supplier' => $supplier,
'panel_box_item_code' => $itemCode, 'panel_box_item_code' => $itemCode,
'panel_box_serial_number' => $serialNumber, 'panel_box_serial_number' => $serialNumber,
'capacitor_scanned_status' => 1, 'capacitor_scanned_status' => 1,
'scanned_status' => 'Scanned', 'scanned_status' => 'Scanned',
'operator_id' => $operatorName, 'operator_id'=> $operatorName,
]); ]);
} }
@@ -367,14 +398,15 @@ class InvoiceDataTable extends Component
$totalQuantity = InvoiceValidation::where('invoice_number', $matchingValidation->invoice_number)->where('plant_id', $this->plantId)->count(); $totalQuantity = InvoiceValidation::where('invoice_number', $matchingValidation->invoice_number)->where('plant_id', $this->plantId)->count();
$scannedQuantity = InvoiceValidation::where('invoice_number', $matchingValidation->invoice_number)->where('plant_id', $this->plantId)->where('scanned_status', 'Scanned')->count(); $scannedQuantity = InvoiceValidation::where('invoice_number', $matchingValidation->invoice_number)->where('plant_id', $this->plantId)->where('scanned_status', 'Scanned')->count();
// $this->form->fill([ // $this->form->fill([
// 'plant_id' => $matchingValidation->plant_id, // 'plant_id' => $matchingValidation->plant_id,
// 'invoice_number' => $matchingValidation->invoice_number, // 'invoice_number' => $matchingValidation->invoice_number,
// 'serial_number' => null, // 'serial_number' => null,
// 'total_quantity' => $totalQuantity, // 'total_quantity' => $totalQuantity,
// 'scanned_quantity'=> $scannedQuantity, // 'scanned_quantity'=> $scannedQuantity,
// ]); // ]);
if ($totalQuantity === $scannedQuantity) { if ($totalQuantity === $scannedQuantity)
{
Notification::make() Notification::make()
->title('Completed: Serial Invoice') ->title('Completed: Serial Invoice')
->body("Serial invoice '$matchingValidation->invoice_number' completed the scanning process.<br>Scan the next 'Serial Invoice' to proceed!") ->body("Serial invoice '$matchingValidation->invoice_number' completed the scanning process.<br>Scan the next 'Serial Invoice' to proceed!")
@@ -382,7 +414,9 @@ class InvoiceDataTable extends Component
->seconds(2) ->seconds(2)
->send(); ->send();
$this->loadCompletedData($matchingValidation->invoice_number, $matchingValidation->plant_id, true); $this->loadCompletedData($matchingValidation->invoice_number, $matchingValidation->plant_id, true);
} else { }
else
{
$this->loadData($matchingValidation->invoice_number, $matchingValidation->plant_id, false); $this->loadData($matchingValidation->invoice_number, $matchingValidation->plant_id, false);
} }
} }
@@ -393,7 +427,7 @@ class InvoiceDataTable extends Component
$this->showCapacitorInput = false; $this->showCapacitorInput = false;
$this->capacitorInput = ''; $this->capacitorInput = '';
$this->dispatch('updateScannedQuantity'); $this->dispatch('updateScannedQuantity');
// $this->loadData($this->invoiceNumber, $this->plantId); //$this->loadData($this->invoiceNumber, $this->plantId);
$this->dispatch('focus-serial-number'); $this->dispatch('focus-serial-number');
} }
@@ -401,4 +435,5 @@ class InvoiceDataTable extends Component
{ {
return view('livewire.invoice-data-table'); return view('livewire.invoice-data-table');
} }
} }

View File

@@ -1,55 +0,0 @@
<?php
namespace App\Livewire;
use Livewire\Component;
use App\Models\StickerPrinting;
class StickerPrintData extends Component
{
public $plantId;
public $refNumber;
public $serialNumber;
public bool $materialInvoice = false;
public $records = [];
protected $listeners = [
'refreshEmptySticker' => 'loadStickerData',
'addStickerToList' => 'loadSticker'
];
public function loadStickerData($plantId, $refNumber)
{
$this->plantId = $plantId;
$this->refNumber = $refNumber;
$this->materialInvoice = true;
$this->records = StickerPrinting::where('plant_id', $plantId)
->where('reference_number', $refNumber)
->orderBy('created_at', 'asc')
->get(['serial_number', 'created_by']);
}
public function loadSticker($plantId, $refNumber, $serialNumber)
{
$this->plantId = $plantId;
$this->refNumber = $refNumber;
$this->materialInvoice = true;
$this->records = StickerPrinting::where('plant_id', $plantId)
->where('reference_number', $refNumber)
->orderBy('created_at', 'asc')
->get(['serial_number', 'created_by']);
}
public function render()
{
return view('livewire.sticker-print-data');
}
}

View File

@@ -2,13 +2,13 @@
namespace App\Mail; namespace App\Mail;
use App\Models\InvoiceDataValidation;
use DateTime;
use Illuminate\Bus\Queueable; use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable; use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content; use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope; use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels; use Illuminate\Queue\SerializesModels;
use DateTime;
class InvoiceDataMail extends Mailable class InvoiceDataMail extends Mailable
{ {
@@ -23,7 +23,7 @@ class InvoiceDataMail extends Mailable
/** /**
* Create a new message instance. * Create a new message instance.
*/ */
public function __construct($scheduleType, $tableData, $mailSubject) public function __construct($scheduleType, $tableData = [], $mailSubject)
{ {
$this->scheduleType = $scheduleType; $this->scheduleType = $scheduleType;
$this->tableData = $tableData ?? []; $this->tableData = $tableData ?? [];
@@ -48,19 +48,17 @@ class InvoiceDataMail extends Mailable
$greeting = 'Dear Sir/Madam,<br><br>We are sending here with list of "Despatch pending sale invoice & STO invoice as on date"'; $greeting = 'Dear Sir/Madam,<br><br>We are sending here with list of "Despatch pending sale invoice & STO invoice as on date"';
if ($this->scheduleType == 'Daily') { if ($this->scheduleType == 'Daily') {
$firstRecord = InvoiceDataValidation::orderBy('document_date', 'asc')->first(); // 'desc' $firstRecord = \App\Models\InvoiceDataValidation::orderBy('document_date', 'asc')->first();
//$lastRecord = \App\Models\InvoiceDataValidation::orderBy('document_date', 'desc')->first();
$startDate = null; if ($firstRecord) {
if ($firstRecord && $firstRecord?->document_date != null && $firstRecord?->document_date != '') {
$startDate = \Carbon\Carbon::parse($firstRecord->document_date)->startOfDay(); $startDate = \Carbon\Carbon::parse($firstRecord->document_date)->startOfDay();
// $endDate = \Carbon\Carbon::parse($lastRecord->document_date)->endOfDay(); //$endDate = \Carbon\Carbon::parse($lastRecord->document_date)->endOfDay();
} else {
$startDate = now()->subDay()->setTime(10, 0, 0);
} }
$endDate = now()->setTime(10, 0, 0); $endDate = now()->setTime(10, 0, 0);
// $fromDate = (new DateTime('yesterday 10:00'))->format('d/m/Y H:i') . ':000';//08:00 // $fromDate = (new DateTime('yesterday 10:00'))->format('d/m/Y H:i') . ':000';//08:00
// $toDate = (new DateTime('today 09:59')) ->format('d/m/Y H:i') . ':999';//07:59 // $toDate = (new DateTime('today 09:59'))->format('d/m/Y H:i') . ':999';//07:59
$reportPeriod = "from: $startDate to $endDate\".<br><br>Please arrange to despatch the same immediately."; $reportPeriod = "from: $startDate to $endDate\".<br><br>Please arrange to despatch the same immediately.";
$greeting .= $reportPeriod; $greeting .= $reportPeriod;
} }
@@ -76,17 +74,17 @@ class InvoiceDataMail extends Mailable
if ($this->scheduleType == 'Live') { if ($this->scheduleType == 'Live') {
$now = now(); $now = now();
$fromMinute = $now->copy()->subMinute()->format('d/m/Y H:i:s'); $fromMinute = $now->copy()->subMinute()->format('d/m/Y H:i:s');
$toMinute = $now->format('d/m/Y H:i:s'); $toMinute = $now->format('d/m/Y H:i:s');
$greeting .= "from: $fromMinute to $toMinute. <br><br>Please arrange to despatch the same immediately."; $greeting .= "from: $fromMinute to $toMinute. <br><br>Please arrange to despatch the same immediately.";
} }
return new Content( return new Content(
view: 'mail.invoice_data_report', view: 'mail.invoice_data_report',
with: [ with: [
'company' => 'CRI Digital Manufacturing Solutions', 'company' => "CRI Digital Manufacturing Solutions",
'greeting' => $greeting, 'greeting' => $greeting,
'tableData' => $this->tableData, 'tableData' => $this->tableData,
'wishes' => 'Thanks & Regards,<br>CRI Digital Manufacturing Solutions', 'wishes' => "Thanks & Regards,<br>CRI Digital Manufacturing Solutions"
], ],
); );
} }

View File

@@ -1,29 +0,0 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\SoftDeletes;
class StickerPrinting extends Model
{
//
use SoftDeletes;
protected $fillable = [
'plant_id',
'reference_number',
'serial_number',
'created_at',
'updated_at',
'created_by',
'updated_by',
];
public function plant(): BelongsTo
{
return $this->belongsTo(Plant::class);
}
}

View File

@@ -1,107 +0,0 @@
<?php
namespace App\Policies;
use Illuminate\Auth\Access\Response;
use App\Models\StickerPrinting;
use App\Models\User;
class StickerPrintingPolicy
{
/**
* Determine whether the user can view any models.
*/
public function viewAny(User $user): bool
{
return $user->checkPermissionTo('view-any StickerPrinting');
}
/**
* Determine whether the user can view the model.
*/
public function view(User $user, StickerPrinting $stickerprinting): bool
{
return $user->checkPermissionTo('view StickerPrinting');
}
/**
* Determine whether the user can create models.
*/
public function create(User $user): bool
{
return $user->checkPermissionTo('create StickerPrinting');
}
/**
* Determine whether the user can update the model.
*/
public function update(User $user, StickerPrinting $stickerprinting): bool
{
return $user->checkPermissionTo('update StickerPrinting');
}
/**
* Determine whether the user can delete the model.
*/
public function delete(User $user, StickerPrinting $stickerprinting): bool
{
return $user->checkPermissionTo('delete StickerPrinting');
}
/**
* Determine whether the user can delete any models.
*/
public function deleteAny(User $user): bool
{
return $user->checkPermissionTo('delete-any StickerPrinting');
}
/**
* Determine whether the user can restore the model.
*/
public function restore(User $user, StickerPrinting $stickerprinting): bool
{
return $user->checkPermissionTo('restore StickerPrinting');
}
/**
* Determine whether the user can restore any models.
*/
public function restoreAny(User $user): bool
{
return $user->checkPermissionTo('restore-any StickerPrinting');
}
/**
* Determine whether the user can replicate the model.
*/
public function replicate(User $user, StickerPrinting $stickerprinting): bool
{
return $user->checkPermissionTo('replicate StickerPrinting');
}
/**
* Determine whether the user can reorder the models.
*/
public function reorder(User $user): bool
{
return $user->checkPermissionTo('reorder StickerPrinting');
}
/**
* Determine whether the user can permanently delete the model.
*/
public function forceDelete(User $user, StickerPrinting $stickerprinting): bool
{
return $user->checkPermissionTo('force-delete StickerPrinting');
}
/**
* Determine whether the user can permanently delete any models.
*/
public function forceDeleteAny(User $user): bool
{
return $user->checkPermissionTo('force-delete-any StickerPrinting');
}
}

View File

@@ -2,19 +2,19 @@
namespace App\Providers; namespace App\Providers;
use App\Models\AlertMailRule;
use App\Models\User; use App\Models\User;
use App\Policies\PermissionPolicy; use Filament\Facades\FilamentView;
use App\Policies\RolePolicy;
use Filament\Support\Assets\Js;
use Filament\Support\Facades\FilamentAsset;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Support\Facades\Gate; use Illuminate\Support\Facades\Gate;
use Illuminate\Support\ServiceProvider;
use App\Policies\RolePolicy;
use App\Policies\PermissionPolicy;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
use Filament\Support\Facades\FilamentAsset;
use Filament\Support\Assets\Js;
use Illuminate\Support\Facades\View; use Illuminate\Support\Facades\View;
use Illuminate\Support\Facades\Vite; use Illuminate\Support\Facades\Vite;
use Illuminate\Support\ServiceProvider;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;
// use Doctrine\DBAL\Types\Type; // use Doctrine\DBAL\Types\Type;
@@ -28,6 +28,7 @@ class AppServiceProvider extends ServiceProvider
// //
} }
/** /**
* Bootstrap any application services. * Bootstrap any application services.
*/ */
@@ -41,21 +42,21 @@ class AppServiceProvider extends ServiceProvider
// }); // });
Gate::before(function (User $user, string $ability) { Gate::before(function (User $user, string $ability) {
return $user->isSuperAdmin() ? true : null; return $user->isSuperAdmin() ? true: null;
}); });
// FilamentAsset::register([ // FilamentAsset::register([
// Js::make('chart-js-plugins', Vite::asset('resources/js/filament-chart-js-plugins.js'))->module(), // Js::make('chart-js-plugins', Vite::asset('resources/js/filament-chart-js-plugins.js'))->module(),
// ]); // ]);
FilamentAsset::register([ FilamentAsset::register([
Js::make('chart-js-plugins', Vite::asset('resources/js/filament-chart-js-plugins.js'))->module(), Js::make('chart-js-plugins', Vite::asset('resources/js/filament-chart-js-plugins.js'))->module(),
]); ]);
// if (env('APP_MODE') === 'admin') {
// FilamentAsset::register([
// Js::make('chart-js-plugins', Vite::asset('resources/js/filament-chart-js-plugins.js'))->module(),
// ]);
// }
// if (env('APP_MODE') === 'admin') {
// FilamentAsset::register([
// Js::make('chart-js-plugins', Vite::asset('resources/js/filament-chart-js-plugins.js'))->module(),
// ]);
// }
// URL::forceScheme('https'); // URL::forceScheme('https');
@@ -69,82 +70,5 @@ class AppServiceProvider extends ServiceProvider
ini_set('max_execution_time', 300); // 300 seconds = 5 minutes ini_set('max_execution_time', 300); // 300 seconds = 5 minutes
ini_set('memory_limit', '512M'); // 512MB ini_set('memory_limit', '512M'); // 512MB
// $schedule = app(Schedule::class);
// $productionRules = AlertMailRule::where('module', 'ProductionQuantities')
// ->where('rule_name', 'ProductionMail')
// ->select('plant', 'schedule_type')
// ->distinct()
// ->get();
// foreach ($productionRules as $rule) {
// $type = $rule->schedule_type;
// $plantId = $rule->plant;
// $command = $schedule->command('send:production-report', [$type, $plantId]);
// // ->appendOutputTo(storage_path('logs/scheduler.log'));
// switch ($type) {
// case 'Live':
// $command->everyMinute();
// break;
// case 'Hourly':
// $command->hourly();
// break;
// case 'Daily':
// $command->dailyAt('07:59');
// break;
// }
// }
// // Invoice report scheduling
// $invoiceRules = AlertMailRule::where('module', 'InvoiceValidation')
// ->select('plant', 'schedule_type')
// ->distinct()
// ->get();
// foreach ($invoiceRules as $rule) {
// $type = $rule->schedule_type;
// $plantId = $rule->plant;
// $command = $schedule->command('send:invoice-report', [$type, $plantId]);
// switch ($type) {
// case 'Live':
// $command->everyMinute();
// break;
// case 'Hourly':
// $command->hourly();
// break;
// case 'Daily':
// $command->dailyAt('07:59');
// break;
// }
// }
// // Invoice Data Report Scheduling
// $invoiceDataRules = AlertMailRule::where('module', 'InvoiceDataReport')
// ->select('plant', 'schedule_type')
// ->distinct()
// ->get();
// foreach ($invoiceDataRules as $rule) {
// $type = $rule->schedule_type;
// $plantId = $rule->plant;
// $command = $schedule->command('send:invoice-data-report', [$type, $plantId]);
// switch ($type) {
// case 'Live':
// $command->everyMinute();
// break;
// case 'Hourly':
// $command->hourly();
// break;
// case 'Daily':
// $command->dailyAt('10:00');
// break;
// }
// }
} }
} }

View File

@@ -213,8 +213,6 @@ return [
'user_model' => \App\Models\User::class, 'user_model' => \App\Models\User::class,
// 'user_model_class' => \App\Models\User::class,
'policies_namespace' => 'App\Policies', 'policies_namespace' => 'App\Policies',
], ],
]; ];

View File

@@ -1,40 +0,0 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
$sql = <<<'SQL'
CREATE TABLE sticker_printings (
id BIGINT GENERATED always AS IDENTITY PRIMARY KEY,
plant_id BIGINT NOT NULL,
reference_number TEXT DEFAULT NULL,
serial_number TEXT DEFAULT NULL,
created_at TIMESTAMP NOT NULL DEFAULT NOW(),
updated_at TIMESTAMP NOT NULL DEFAULT NOW(),
created_by TEXT DEFAULT NULL,
updated_by TEXT DEFAULT NULL,
deleted_at TIMESTAMP,
FOREIGN KEY (plant_id) REFERENCES plants (id)
);
SQL;
DB::statement($sql);
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('sticker_printings');
}
};

View File

@@ -169,7 +169,6 @@ class PermissionSeeder extends Seeder
Permission::updateOrCreate(['name' => 'view import process order']); Permission::updateOrCreate(['name' => 'view import process order']);
Permission::updateOrCreate(['name' => 'view export process order']); Permission::updateOrCreate(['name' => 'view export process order']);
Permission::updateOrCreate(['name' => 'view import sticker printing']);
Permission::updateOrCreate(['name' => 'view export sticker printing']);
} }
} }

View File

@@ -1,24 +0,0 @@
<x-filament::page>
<form wire:submit.prevent="create" class="space-y-6">
{{-- Form Section --}}
<div class="filament-form space-y-6">
{{ $this->form }}
</div>
{{-- <livewire:notification-sound /> --}}
{{-- Livewire Component (Invoice Table) --}}
<div class="bg-white shadow rounded-xl p-4">
<livewire:sticker-print-data :ref-data="$ref_number" />
</div>
{{-- Actions --}}
<div class="filament-actions mt-6">
<x-filament::actions>
@foreach ($this->getFormActions() as $action)
{{ $action }}
@endforeach
</x-filament::actions>
</div>
</form>
</x-filament::page>

View File

@@ -1,23 +0,0 @@
{{-- <div class="flex flex-col items-start space-y-2">
<button
type="button"
wire:click="printSticker"
class="mt-15 px-2 py-1 border border-primary-500 text-primary-600 rounded hover:bg-primary-50 hover:border-primary-700 transition text-sm"
>
Print
</button>
</div> --}}
<div class="flex flex-col items-start space-y-2">
<button
type="button"
wire:click="printSticker"
class="px-2 py-1 border border-primary-500 text-primary-600 bg-white rounded hover:bg-primary-50 hover:border-primary-700 transition text-sm"
style="margin-top: 10mm;"
>
Print
</button>
</div>

View File

@@ -1,81 +0,0 @@
{{-- <div class="overflow-x-auto overflow-y-visible" style="height: 385px;">
<table class="table-auto w-full border-collapse border">
<thead class="bg-gray-100">
<tr>
<th class="border p-2">No</th>
<th class="border p-2">Reference No</th>
<th class="border p-2">Serial Number</th>
<th class="border p-2">Created By</th>
</tr>
</thead>
<tbody>
@forelse($records as $index => $record)
<tr>
<td class="border p-2 text-center">{{ $index + 1 }}</td>
<td class="border p-2 text-center">{{ $refNumber }}</td>
<td class="border p-2 text-center">{{ $record['serial_number'] }}</td>
<td class="border p-2 text-center">{{ $record->created_by }}</td>
</tr>
@empty
<tr>
<td class="border p-2 text-center" colspan="4">No serial numbers found.</td>
</tr>
@endforelse
</tbody>
</table>
</div> --}}
<div>
<h3 class="text-lg font-semibold mb-2">Sticker Printing Table</h3>
<div
wire:loading.remove
@if(!$materialInvoice) style="display:none" @endif
class="overflow-x-auto overflow-y-visible"
style="height: 385px;"
>
<table class="table-auto w-full border-collapse border">
{{-- <thead class="bg-gray-100"> --}}
<thead class="bg-gray-100 text-xs">
<tr>
<th class="border p-2">No</th>
<th class="border p-2">Reference No</th>
<th class="border p-2">Serial Number</th>
<th class="border p-2">Created By</th>
</tr>
</thead>
{{-- <tbody> --}}
<tbody class="text-xs">
@forelse($records as $index => $record)
<tr>
<td class="border p-2 text-center">{{ $index + 1 }}</td>
<td class="border p-2 text-center">{{ $refNumber }}</td>
<td class="border p-2 text-center">{{ $record['serial_number'] }}</td>
<td class="border p-2 text-center">{{ $record->created_by }}</td>
</tr>
@empty
<tr>
<td class="border p-2 text-center" colspan="4">No serial numbers found.</td>
</tr>
@endforelse
</tbody>
</table>
</div>
<script>
window.addEventListener('focus-serial-number', () => {
setTimeout(() => {
const container = document.getElementById('serial_number_input');
const input = container?.querySelector('input'); // gets the actual input inside
if (input) {
input.focus();
input.select();
}
}, 50);
});
</script>

View File

@@ -1,92 +0,0 @@
{{-- <!DOCTYPE html>
<html>
<head>
<style>
body { text-align: center; font-family: Arial, sans-serif; }
.qr-container { margin-top: 30px; }
</style>
</head>
<body>
<div class="qr-container">
<img src="data:image/png;base64,{{ $qrCode }}" width="250" height="250">
</div>
</body>
</html> --}}
{{-- <!DOCTYPE html>
<html>
<head>
<style>
@page {
margin: 0;
size: 100mm 100mm;
}
body {
margin: 0;
padding: 0;
width: 100mm;
height: 100mm;
display: flex;
justify-content: center;
align-items: center;
}
img {
width: 100mm;
height: 100mm;
}
</style>
</head>
<body>
<img src="data:image/png;base64,{{ $qrCode }}" />
</body>
</html> --}}
<!DOCTYPE html>
<html>
<head>
<style>
@page {
margin: 0;
size: 100mm 100mm;
}
body {
margin: 0;
padding: 0;
width: 100mm;
height: 100mm;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
text-align: center;
font-size: 12px;
font-family: Arial, sans-serif;
}
img {
width: 90mm; /* QR CODE REDUCED TO FIT TEXT */
height: 90mm;
}
.ref-text {
margin-top: 3mm;
font-size: 16px; /* Increased Font Size */
font-weight: bold;
}
</style>
</head>
<body>
<div class="ref-text">
{{ $referenceNumber }}
</div>
<img src="data:image/png;base64,{{ $qrCode }}" />
</body>
</html>

View File

@@ -1,11 +1,10 @@
<?php <?php
use Illuminate\Foundation\Inspiring;
use Illuminate\Support\Facades\Artisan;
use App\Models\AlertMailRule; use App\Models\AlertMailRule;
use Illuminate\Console\Scheduling\Schedule; use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Inspiring;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Schema;
Artisan::command('inspire', function () { Artisan::command('inspire', function () {
$this->comment(Inspiring::quote()); $this->comment(Inspiring::quote());
@@ -18,6 +17,9 @@ app()->booted(function () {
$schedule = app(Schedule::class); $schedule = app(Schedule::class);
// $schedule->command('report:send-daily-production')->dailyAt('07:59'); // $schedule->command('report:send-daily-production')->dailyAt('07:59');
if (Schema::hasTable('alert_mail_rules')) {
// Production report scheduling // Production report scheduling
$productionRules = AlertMailRule::where('module', 'ProductionQuantities') $productionRules = AlertMailRule::where('module', 'ProductionQuantities')
->where('rule_name', 'ProductionMail') ->where('rule_name', 'ProductionMail')
@@ -94,4 +96,5 @@ app()->booted(function () {
break; break;
} }
} }
}
}); });