Refactor: Clean up imports and enhance form/table structure in InvoiceDataValidation and InvoiceOutValidation resources
Some checks failed
Scan for leaked secrets using Kingfisher / kingfisher-secrets-scan (push) Successful in 11s
Scan for leaked secrets using Kingfisher / kingfisher-secrets-scan (pull_request) Successful in 10s
Laravel Larastan / larastan (pull_request) Failing after 2m1s
Laravel Pint / pint (pull_request) Failing after 2m7s
Gemini PR Review / review (pull_request) Failing after 44s

This commit is contained in:
dhanabalan
2025-11-27 10:59:00 +05:30
parent c16c967757
commit 95c909b6ac
2 changed files with 237 additions and 205 deletions

View File

@@ -4,27 +4,23 @@ namespace App\Filament\Resources;
use App\Filament\Exports\InvoiceDataValidationExporter;
use App\Filament\Resources\InvoiceDataValidationResource\Pages;
use App\Filament\Resources\InvoiceDataValidationResource\RelationManagers;
use App\Models\InvoiceDataValidation;
use App\Models\Plant;
use DB;
use Filament\Facades\Filament;
use Filament\Forms;
use Filament\Forms\Components\FileUpload;
use Filament\Forms\Form;
use Filament\Forms\Get;
use Filament\Notifications\Notification;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Actions\ExportAction;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
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 Maatwebsite\Excel\Facades\Excel;
use App\Models\StickerMaster;
use App\Models\User;
use DB;
use Filament\Tables\Actions\ExportAction;
class InvoiceDataValidationResource extends Resource
{
@@ -67,6 +63,7 @@ class InvoiceDataValidationResource extends Resource
->label('Created By')
->default(Filament::auth()->user()?->name),
Forms\Components\Hidden::make('updated_by')
->label('Updated By')
->default(Filament::auth()->user()?->name),
]);
}
@@ -77,10 +74,12 @@ class InvoiceDataValidationResource extends Resource
->columns([
Tables\Columns\TextColumn::make('No.')
->label('No.')
->alignCenter()
->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.code')
@@ -100,8 +99,8 @@ class InvoiceDataValidationResource extends Resource
->sortable(),
Tables\Columns\TextColumn::make('document_number')
->label('Document Number')
->searchable()
->alignCenter()
->searchable()
->sortable(),
Tables\Columns\TextColumn::make('document_date')
->label('Document Date')
@@ -127,15 +126,27 @@ class InvoiceDataValidationResource extends Resource
Tables\Columns\TextColumn::make('created_at')
->label('Created At')
->alignCenter()
->searchable()
->dateTime()
->sortable()
->toggleable(isToggledHiddenByDefault: true),
->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()
->sortable()
->toggleable(isToggledHiddenByDefault: true),
->sortable(),
// ->toggleable(isToggledHiddenByDefault: true),
Tables\Columns\TextColumn::make('updated_by')
->label('Updated By')
->alignCenter()
->searchable()
->sortable(),
Tables\Columns\TextColumn::make('deleted_at')
->label('Deleted At')
->alignCenter()
@@ -169,7 +180,7 @@ class InvoiceDataValidationResource extends Resource
->reactive()
->required()
->disk('local')
//->visible(fn (Get $get) => !empty($get('plant_id')))
// ->visible(fn (Get $get) => !empty($get('plant_id')))
->directory('uploads/temp'),
])
->action(function (array $data) {
@@ -191,12 +202,10 @@ class InvoiceDataValidationResource extends Resource
$fullPath = Storage::disk('local')->path($path);
if ($fullPath && file_exists($fullPath))
{
if ($fullPath && file_exists($fullPath)) {
$rows = Excel::toArray(null, $fullPath)[0];
if ((count($rows) - 1) <= 0)
{
if ((count($rows) - 1) <= 0) {
Notification::make()
->title('Records Not Found')
->body("Import the valid 'Invoice Data' file to proceed..!")
@@ -206,6 +215,7 @@ class InvoiceDataValidationResource extends Resource
if ($disk->exists($path)) {
$disk->delete($path);
}
return;
}
@@ -223,43 +233,40 @@ class InvoiceDataValidationResource extends Resource
$invalidLocation = [];
$seenPlantDoc = [];
//$duplicateEntries = [];
// $duplicateEntries = [];
$duplicateEntriesExcel = [];
foreach ($rows as $index => $row)
{
if ($index == 0) continue; // Skip header
foreach ($rows as $index => $row) {
if ($index == 0) {
continue;
} // Skip header
$DisChaDesc = trim($row[3]);
$plantCode = trim($row[4]);
$CustomerCode = trim($row[5]);
$DocNo = trim($row[6]);
$DocDate = trim($row[7]);
$CusTradeName = trim($row[9]);
$CusLocation = trim($row[10]);
$Location = trim($row[36]);
$DisChaDesc = trim($row[3]);
$plantCode = trim($row[4]);
$CustomerCode = trim($row[5]);
$DocNo = trim($row[6]);
$DocDate = trim($row[7]);
$CusTradeName = trim($row[9]);
$CusLocation = trim($row[10]);
$Location = trim($row[36]);
// if (empty($plantCode)) $invalidPlantCode[] = "Row {$index}";
if (empty($DisChaDesc)){
if (empty($DisChaDesc)) {
$invalidDisChaDesc[] = "Row {$index}";
}
if (empty($CustomerCode)){
if (empty($CustomerCode)) {
$invalidCustomerCode[] = "Row {$index}";
}
if (empty($DocNo))
{
if (empty($DocNo)) {
$invalidDocNo[] = "Row {$index}";
}
if (empty($CusTradeName))
{
if (empty($CusTradeName)) {
$invalidCusTradeName[] = "Row {$index}";
}
if (empty($CusLocation))
{
if (empty($CusLocation)) {
$invalidCusLocation[] = "Row {$index}";
}
if (empty($Location))
{
if (empty($Location)) {
$invalidLocation[] = "Row {$index}";
}
// if (empty($createdBy)) $invalidUser[] = "Row {$index}";
@@ -267,11 +274,9 @@ class InvoiceDataValidationResource extends Resource
if (strlen($plantCode) < 4) {
$invalidPlantCode[] = $plantCode;
}
if (!is_numeric($plantCode)) {
if (! is_numeric($plantCode)) {
$invalidPlantType[] = $plantCode;
}
else if (!Plant::where('code', $plantCode)->first())
{
} elseif (! Plant::where('code', $plantCode)->first()) {
$invalidPlaCoFound[] = $plantCode;
}
@@ -288,25 +293,36 @@ class InvoiceDataValidationResource extends Resource
// $duplicateEntries[] = "Duplicate record: Document Number '{$DocNo}' already exists for Plant '{$plant->name}'";
// }
//Also check duplicates within the same file ---
$uniqueKey = $plantCode . '_' . $DocNo;
// Also check duplicates within the same file ---
$uniqueKey = $plantCode.'_'.$DocNo;
if (in_array($uniqueKey, $seenPlantDoc)) {
$duplicateEntriesExcel[] = "Duplicate in file at Row {$index}: Document Number '{$DocNo}' already exists for Plant '{$plant->name}'";
}
$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 = '';
//if (!empty($invalidDisChaDesc)) $errorMsg .= 'Missing Distribution Channel Description in rows: ' . implode(', ', $invalidDisChaDesc) . '<br>';
if (!empty($invalidCustomerCode)) $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($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>';
// if (!empty($invalidDisChaDesc)) $errorMsg .= 'Missing Distribution Channel Description in rows: ' . implode(', ', $invalidDisChaDesc) . '<br>';
if (! empty($invalidCustomerCode)) {
$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($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()
->title('Missing Mandatory Fields')
@@ -317,45 +333,43 @@ class InvoiceDataValidationResource extends Resource
if ($disk->exists($path)) {
$disk->delete($path);
}
return;
}
else if (!empty($invalidPlantCode))
{
} elseif (! empty($invalidPlantCode)) {
$invalidPlantCode = array_unique($invalidPlantCode);
Notification::make()
->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()
->send();
if ($disk->exists($path)) {
$disk->delete($path);
}
return;
}
else if (!empty($invalidPlantType))
{
} elseif (! empty($invalidPlantType)) {
$invalidPlantType = array_unique($invalidPlantType);
Notification::make()
->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()
->send();
if ($disk->exists($path)) {
$disk->delete($path);
}
return;
}
else if (!empty($invalidPlaCoFound))
{
} elseif (! empty($invalidPlaCoFound)) {
$invalidPlaCoFound = array_unique($invalidPlaCoFound);
Notification::make()
->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()
->send();
if ($disk->exists($path)) {
$disk->delete($path);
}
return;
}
@@ -401,11 +415,10 @@ class InvoiceDataValidationResource extends Resource
// return;
// }
if (!empty($duplicateEntriesExcel))
{
if (! empty($duplicateEntriesExcel)) {
$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)) {
$docNo = $matches[1];
$plantName = $matches[2] ?? 'Unknown';
@@ -415,8 +428,7 @@ class InvoiceDataValidationResource extends Resource
$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
$uniqueDocNumbers = array_unique($docNumbers);
$count = count($uniqueDocNumbers);
@@ -425,13 +437,13 @@ class InvoiceDataValidationResource extends Resource
$errorMsg .= "Duplicate Document Numbers for Plant <b>{$plant}</b> : {$count} Document Numbers already exist in uploaded file<br>";
} else {
$errorMsg .= "Duplicate Document Numbers for Plant <b>{$plant}</b> : '"
. implode(', ', $uniqueDocNumbers)
. "' already exist in uploaded file<br>";
.implode(', ', $uniqueDocNumbers)
."' already exist in uploaded file<br>";
}
}
Notification::make()
//->title('Duplicate Document Number in Uploaded File')
// ->title('Duplicate Document Number in Uploaded File')
->body($errorMsg)
->danger()
->send();
@@ -439,6 +451,7 @@ class InvoiceDataValidationResource extends Resource
if ($disk->exists($path)) {
$disk->delete($path);
}
return;
}
@@ -455,33 +468,34 @@ class InvoiceDataValidationResource extends Resource
DB::beginTransaction();
try
{
try {
foreach ($rows as $index => $row) {
if ($index == 0) continue;
if ($index == 0) {
continue;
}
$rowNumber = $index + 1;
try {
$DisChaDesc = trim($row[3]);
$plantCode = trim($row[4]);
$DisChaDesc = trim($row[3]);
$plantCode = trim($row[4]);
$CustomerCode = trim($row[5]);
$DocNo = trim($row[6]);
$DocDate = trim($row[7]);
$DocNo = trim($row[6]);
$DocDate = trim($row[7]);
$CusTradeName = trim($row[9]);
$CusLocation = trim($row[10]);
$Location = trim($row[36]);
$CusLocation = trim($row[10]);
$Location = trim($row[36]);
if (empty($DocNo)) {
throw new \Exception("Row '{$rowNumber}' Missing QR Code");
}
$plant = Plant::where('code', $plantCode)->first();
if (!$plant) {
if (! $plant) {
throw new \Exception("Invalid plant code : '{$plantCode}'");
}
if (!empty($DocDate)) {
if (! empty($DocDate)) {
if (preg_match('/^\d{2}[-\/]\d{2}[-\/]\d{4}$/', $DocDate)) {
[$day, $month, $year] = preg_split('/[-\/]/', $DocDate);
$formattedDate = "{$year}-{$month}-{$day}";
@@ -503,26 +517,26 @@ class InvoiceDataValidationResource extends Resource
if ($record) {
$record->update([
'distribution_channel_desc' => $DisChaDesc,
'customer_code' => $CustomerCode,
'document_date' => $formattedDate,
'customer_trade_name' => $CusTradeName,
'customer_location' => $CusLocation,
'location' => $Location,
'updated_by' => $operatorName
'customer_code' => $CustomerCode,
'document_date' => $formattedDate,
'customer_trade_name' => $CusTradeName,
'customer_location' => $CusLocation,
'location' => $Location,
'updated_by' => $operatorName,
]);
$inserted = $record;
} else {
// Record does not exist, create with 'created_by'
$inserted = InvoiceDataValidation::create([
'plant_id' => $plant->id,
'document_number' => $DocNo,
'plant_id' => $plant->id,
'document_number' => $DocNo,
'distribution_channel_desc' => $DisChaDesc,
'customer_code' => $CustomerCode,
'document_date' => $formattedDate,
'customer_trade_name' => $CusTradeName,
'customer_location' => $CusLocation,
'location' => $Location,
'created_by' => $operatorName
'customer_code' => $CustomerCode,
'document_date' => $formattedDate,
'customer_trade_name' => $CusTradeName,
'customer_location' => $CusLocation,
'location' => $Location,
'created_by' => $operatorName,
]);
}
// $inserted = InvoiceDataValidation::create([
@@ -536,7 +550,7 @@ class InvoiceDataValidationResource extends Resource
// 'created_by' => $operatorName
// ]);
if (!$inserted) {
if (! $inserted) {
throw new \Exception("{$curStat} failed for Document Number : {$DocNo}");
}
@@ -545,7 +559,7 @@ class InvoiceDataValidationResource extends Resource
$failedRecords[] = [
'row' => $rowNumber,
'document_number' => $DocNo ?? null,
'error' => $e->getMessage()
'error' => $e->getMessage(),
];
}
}
@@ -554,13 +568,13 @@ class InvoiceDataValidationResource extends Resource
if (count($failedRecords) > 0) {
$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
->implode("\n");
Notification::make()
->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()
->send();
} else {
@@ -570,9 +584,7 @@ class InvoiceDataValidationResource extends Resource
->success()
->send();
}
}
catch (\Exception $e)
{
} catch (\Exception $e) {
DB::rollBack();
Notification::make()
->title('Import Failed')
@@ -582,14 +594,14 @@ class InvoiceDataValidationResource extends Resource
}
}
})
->visible(function() {
->visible(function () {
return Filament::auth()->user()->can('view import invoice data validation');
}),
ExportAction::make()
->label('Export Invoice Data')
->color('warning')
->exporter(InvoiceDataValidationExporter::class)
->visible(function() {
->visible(function () {
return Filament::auth()->user()->can('view export invoice data validation');
}),
]);