5 Commits

Author SHA1 Message Date
dhanabalan
c070c9763e Added commented line 2025-08-12 17:55:03 +05:30
dhanabalan
2116ea422e Added unnecessary blank line in QualityValidationResource.php 2025-08-12 17:44:58 +05:30
dhanabalan
acc98ad876 Add EbReadingPolicy.php from master branch 2025-08-12 17:33:11 +05:30
dhanabalan
45898b2fa2 removed unwanted space from quality validation 2025-08-12 16:59:51 +05:30
dhanabalan
390e013ccb Add TimescaleDB migration for QDS 2025-08-12 16:14:41 +05:30
153 changed files with 2087 additions and 7320 deletions

View File

@@ -30,11 +30,252 @@ class SendInvoiceReport extends Command
* Execute the console command.
*/
// public function handle()
// {
// $schedule = $this->argument('schedule_type');
// $plantid = $this->argument('plant');
// $mailRules = \App\Models\AlertMailRule::where('module', 'InvoiceValidation')->get()->groupBy('rule_name');
// $startDate = now()->setTime(8, 0, 0);
// $endDate = now()->copy()->addDay()->setTime(8, 0, 0);
// $plants = InvoiceValidation::select('plant_id')->distinct()->pluck('plant_id');
// $serialTableData = [];
// $materialTableData = [];
// $bundleTableData = [];
// $noSerial = 1;
// $noMaterial = 1;
// $noBundle = 1;
// foreach ($plants as $plantId) {
// $plant = Plant::find($plantId);
// $plantName = $plant ? $plant->name : $plantId;
// //..Serial Invoice
// $totalSerialCount = InvoiceValidation::where('plant_id', $plantId)
// ->whereNull('quantity')
// ->whereBetween('created_at', [$startDate, $endDate])
// ->distinct('invoice_number')
// ->count('invoice_number');
// $scannedSerialCount = InvoiceValidation::select('invoice_number')
// ->where('plant_id', $plantId)
// ->whereNull('quantity')
// ->whereBetween('updated_at', [$startDate, $endDate])
// ->groupBy('invoice_number')
// ->havingRaw(
// "COUNT(*) = SUM(CASE WHEN scanned_status = 'Scanned' THEN 1 ELSE 0 END)"
// )
// ->count();
// $serialTableData[] = [
// 'no' => $noSerial++,
// 'plant' => $plantName,
// 'totalInvoice' => $totalSerialCount,
// 'scannedInvoice' => $scannedSerialCount,
// ];
// //..Individual Invoice
// $TotalMatCount = InvoiceValidation::where('plant_id', $plantId)
// ->where('quantity', 1)
// ->whereBetween('created_at', [$startDate, $endDate])
// ->distinct('invoice_number')
// ->count('invoice_number');
// $scannedMatCount = InvoiceValidation::select('invoice_number')
// ->where('plant_id', $plantId)
// ->where('quantity', 1)
// ->whereBetween('updated_at', [$startDate, $endDate])
// ->groupBy('invoice_number')
// ->havingRaw(
// "COUNT(*) = SUM(CASE WHEN serial_number IS NOT NULL AND serial_number != '' THEN 1 ELSE 0 END)"
// )
// ->count();
// $materialTableData[] = [
// 'no' => $noMaterial++,
// 'plant' => $plantName,
// 'totalInvoice' => $TotalMatCount,
// 'scannedInvoice' => $scannedMatCount,
// ];
// //..BUndle Invoice
// $totalBundleCount = InvoiceValidation::where('plant_id', $plantId)
// ->where('quantity', '>', 1)
// ->whereBetween('created_at', [$startDate, $endDate])
// ->distinct('invoice_number')
// ->count('invoice_number');
// $scannedBundleCount = InvoiceValidation::select('invoice_number')
// ->where('plant_id', $plantId)
// ->where('quantity', '>', 1)
// ->whereBetween('updated_at', [$startDate, $endDate])
// ->groupBy('invoice_number')
// ->havingRaw(
// "COUNT(*) = SUM(CASE WHEN serial_number IS NOT NULL AND serial_number != '' THEN 1 ELSE 0 END)"
// )
// ->count();
// $bundleTableData[] = [
// 'no' => $noBundle++,
// 'plant' => $plantName,
// 'totalInvoice' => $totalBundleCount,
// 'scannedInvoice' => $scannedBundleCount,
// ];
// }
// // Send to SerialInvoiceMail recipients
// if ($mailRules->has('SerialInvoiceMail')) {
// $emails = $mailRules['SerialInvoiceMail']->pluck('email')->unique()->toArray();
// foreach ($emails as $email) {
// Mail::to($email)->send(new test($serialTableData, [], []));
// }
// }
// // Send to MaterialInvoiceMail recipients (material + bundle table)
// if ($mailRules->has('MaterialInvoiceMail')) {
// $emails = $mailRules['MaterialInvoiceMail']->pluck('email')->unique()->toArray();
// foreach ($emails as $email) {
// Mail::to($email)->send(new test([], $materialTableData, $bundleTableData));
// }
// }
// // Send to InvoiceMail recipients (all three tables)
// if ($mailRules->has('InvoiceMail')) {
// $emails = $mailRules['InvoiceMail']->pluck('email')->unique()->toArray();
// foreach ($emails as $email) {
// Mail::to($email)->send(new test($serialTableData, $materialTableData, $bundleTableData));
// }
// }
// //$this->info(json_encode($materialTableData));
// }
// public function handle()
// {
// $schedule = $this->argument('schedule_type');
// $plantId = $this->argument('plant');
// $mailRules = \App\Models\AlertMailRule::where('module', 'InvoiceValidation')->get()->groupBy('rule_name');
// $startDate = now()->setTime(8, 0, 0);
// $endDate = now()->copy()->addDay()->setTime(8, 0, 0);
// $serialTableData = [];
// $materialTableData = [];
// $bundleTableData = [];
// $plant = Plant::find($plantId);
// $plantName = $plant ? $plant->name : $plantId;
// // Serial Invoice
// $totalSerialCount = InvoiceValidation::where('plant_id', $plantId)
// ->whereNull('quantity')
// ->whereBetween('created_at', [$startDate, $endDate])
// ->distinct('invoice_number')
// ->count('invoice_number');
// $scannedSerialCount = InvoiceValidation::select('invoice_number')
// ->where('plant_id', $plantId)
// ->whereNull('quantity')
// ->whereBetween('updated_at', [$startDate, $endDate])
// ->groupBy('invoice_number')
// ->havingRaw(
// "COUNT(*) = SUM(CASE WHEN scanned_status = 'Scanned' THEN 1 ELSE 0 END)"
// )
// ->count();
// $serialTableData[] = [
// 'no' => 1,
// 'plant' => $plantName,
// 'totalInvoice' => $totalSerialCount,
// 'scannedInvoice' => $scannedSerialCount,
// ];
// // Individual Material Invoice
// $TotalMatCount = InvoiceValidation::where('plant_id', $plantId)
// ->where('quantity', 1)
// ->whereBetween('created_at', [$startDate, $endDate])
// ->distinct('invoice_number')
// ->count('invoice_number');
// $scannedMatCount = InvoiceValidation::select('invoice_number')
// ->where('plant_id', $plantId)
// ->where('quantity', 1)
// ->whereBetween('updated_at', [$startDate, $endDate])
// ->groupBy('invoice_number')
// ->havingRaw(
// "COUNT(*) = SUM(CASE WHEN serial_number IS NOT NULL AND serial_number != '' THEN 1 ELSE 0 END)"
// )
// ->count();
// $materialTableData[] = [
// 'no' => 1,
// 'plant' => $plantName,
// 'totalInvoice' => $TotalMatCount,
// 'scannedInvoice' => $scannedMatCount,
// ];
// // Bundle Invoice
// $totalBundleCount = InvoiceValidation::where('plant_id', $plantId)
// ->where('quantity', '>', 1)
// ->whereBetween('created_at', [$startDate, $endDate])
// ->distinct('invoice_number')
// ->count('invoice_number');
// $scannedBundleCount = InvoiceValidation::select('invoice_number')
// ->where('plant_id', $plantId)
// ->where('quantity', '>', 1)
// ->whereBetween('updated_at', [$startDate, $endDate])
// ->groupBy('invoice_number')
// ->havingRaw(
// "COUNT(*) = SUM(CASE WHEN serial_number IS NOT NULL AND serial_number != '' THEN 1 ELSE 0 END)"
// )
// ->count();
// $bundleTableData[] = [
// 'no' => 1,
// 'plant' => $plantName,
// 'totalInvoice' => $totalBundleCount,
// 'scannedInvoice' => $scannedBundleCount,
// ];
// // Send to SerialInvoiceMail recipients
// if ($mailRules->has('SerialInvoiceMail')) {
// $emails = $mailRules['SerialInvoiceMail']->pluck('email')->unique()->toArray();
// foreach ($emails as $email) {
// Mail::to($email)->send(new test($serialTableData, [], []));
// }
// }
// // Send to MaterialInvoiceMail recipients (material + bundle table)
// if ($mailRules->has('MaterialInvoiceMail')) {
// $emails = $mailRules['MaterialInvoiceMail']->pluck('email')->unique()->toArray();
// foreach ($emails as $email) {
// Mail::to($email)->send(new test([], $materialTableData, $bundleTableData));
// }
// }
// // Send to InvoiceMail recipients (all three tables)
// if ($mailRules->has('InvoiceMail')) {
// $emails = $mailRules['InvoiceMail']->pluck('email')->unique()->toArray();
// foreach ($emails as $email) {
// Mail::to($email)->send(new test($serialTableData, $materialTableData, $bundleTableData));
// }
// }
// // $this->table(
// // ['No', 'Plant', 'Total Invoice', 'Scanned Invoice'],
// // $serialTableData
// // );
// }
public function handle()
{
$schedule = $this->argument('schedule_type');
//$scheduleType = $this->argument('scheduleType');
$plantIdArg = (int) $this->argument('plant'); // can be 0 for all plants
$mailRules = \App\Models\AlertMailRule::where('module', 'InvoiceValidation')->get()->groupBy('rule_name');
@@ -62,8 +303,7 @@ class SendInvoiceReport extends Command
$startDate = now()->setTime(8, 0, 0);
$endDate = now()->copy()->addDay()->setTime(8, 0, 0);
}
foreach ($plantIds as $plantId)
{
foreach ($plantIds as $plantId) {
$plant = Plant::find($plantId);
$plantName = $plant ? $plant->name : $plantId;
@@ -82,27 +322,11 @@ class SendInvoiceReport extends Command
->havingRaw("COUNT(*) = SUM(CASE WHEN scanned_status = 'Scanned' THEN 1 ELSE 0 END)")
->count();
$serialInvoiceQuan = InvoiceValidation::where('plant_id', $plantId)
->where('quantity', null)
->whereBetween('created_at', [$startDate, $endDate])
->count();
$scannedInvoiceQuan = InvoiceValidation::where('plant_id', $plantId)
->where('scanned_status', 'Scanned')
->where(function($query) {
$query->whereNull('quantity')
->orWhere('quantity', 0);
})
->whereBetween('updated_at', [$startDate, $endDate])
->count();
$serialTableData[] = [
'no' => $no,
'plant' => $plantName,
'totalInvoice' => $totalSerialCount,
'scannedInvoice' => $scannedSerialCount,
'totalInvoiceQuan' => $serialInvoiceQuan,
'scannedInvoiceQuan' => $scannedInvoiceQuan,
];
// Material Invoice
@@ -120,25 +344,11 @@ class SendInvoiceReport extends Command
->havingRaw("COUNT(*) = SUM(CASE WHEN serial_number IS NOT NULL AND serial_number != '' THEN 1 ELSE 0 END)")
->count();
$totalMatInvoiceQuan = InvoiceValidation::where('plant_id', $plantId)
->where('quantity', 1)
->whereBetween('created_at', [$startDate, $endDate])
->count();
$scannedMatInvoiceQuan = InvoiceValidation::where('plant_id', $plantId)
->where('quantity', 1)
->whereNotNull('serial_number')
->where('serial_number','!=', '')
->whereBetween('updated_at', [$startDate, $endDate])
->count();
$materialTableData[] = [
'no' => $no,
'plant' => $plantName,
'totalInvoice' => $totalMatCount,
'scannedInvoice' => $scannedMatCount,
'totalInvoiceQuan' => $totalMatInvoiceQuan,
'scannedInvoiceQuan' => $scannedMatInvoiceQuan,
];
// Bundle Invoice
@@ -156,49 +366,29 @@ class SendInvoiceReport extends Command
->havingRaw("COUNT(*) = SUM(CASE WHEN serial_number IS NOT NULL AND serial_number != '' THEN 1 ELSE 0 END)")
->count();
$totalBundleInvoiceQuan = InvoiceValidation::where('plant_id', $plantId)
->where('quantity', '>', 1)
->whereBetween('created_at', [$startDate, $endDate])
->count();
$scannedBundleInvoiceQuan = InvoiceValidation::where('plant_id', $plantId)
->where('quantity', '>', 1)
->whereNotNull('serial_number')
->where('serial_number','!=', '')
->whereBetween('updated_at', [$startDate, $endDate])
->count();
$bundleTableData[] = [
'no' => $no,
'plant' => $plantName,
'totalInvoice' => $totalBundleCount,
'scannedInvoice' => $scannedBundleCount,
'totalInvoiceQuan' => $totalBundleInvoiceQuan,
'scannedInvoiceQuan' => $scannedBundleInvoiceQuan,
];
$no++;
}
$mail = new test($serialTableData, $materialTableData, $bundleTableData, $schedule);
$contentVars = $mail->content()->with;
$this->info($contentVars['greeting'] ?? 'Invoice Report');
// Send to SerialInvoiceMail recipients
if ($mailRules->has('SerialInvoiceMail')) {
$emails = $mailRules['SerialInvoiceMail']->pluck('email')->unique()->toArray();
foreach ($emails as $email) {
Mail::to($email)->send(new test($serialTableData, [], [], $schedule));
Mail::to($email)->send(new test($serialTableData, [], []));
}
}
// Send to MaterialInvoiceMail recipients (material + bundle table)
if ($mailRules->has('MaterialInvoiceMail')) {
$emails = $mailRules['MaterialInvoiceMail']->pluck('email')->unique()->toArray();
foreach ($emails as $email) {
Mail::to($email)->send(new test([], $materialTableData, $bundleTableData, $schedule));
Mail::to($email)->send(new test([], $materialTableData, $bundleTableData));
}
}
@@ -206,21 +396,19 @@ class SendInvoiceReport extends Command
if ($mailRules->has('InvoiceMail')) {
$emails = $mailRules['InvoiceMail']->pluck('email')->unique()->toArray();
foreach ($emails as $email) {
Mail::to($email)->send(new test($serialTableData, $materialTableData, $bundleTableData, $schedule));
Mail::to($email)->send(new test($serialTableData, $materialTableData, $bundleTableData));
}
}
// Show preview in console
$this->info('--- Serial Invoice Table ---');
$this->table(['#', 'Plant', 'Total Invoice', 'Scanned Invoice','TotalInvoice Quantity', 'ScannedInvoice Quantity'], $serialTableData);
$this->table(['#', 'Plant', 'Total Invoice', 'Scanned Invoice'], $serialTableData);
$this->info('--- Material Invoice Table ---');
$this->table(['#', 'Plant', 'Total Invoice', 'Scanned Invoice','TotalInvoice Quantity', 'ScannedInvoice Quantity'], $materialTableData);
$this->table(['#', 'Plant', 'Total Invoice', 'Scanned Invoice'], $materialTableData);
$this->info('--- Bundle Invoice Table ---');
$this->table(['#', 'Plant', 'Total Invoice', 'Scanned Invoice','TotalInvoice Quantity', 'ScannedInvoice Quantity'], $bundleTableData);
$this->info($contentVars['wishes'] ?? '');
$this->table(['#', 'Plant', 'Total Invoice', 'Scanned Invoice'], $bundleTableData);
}

View File

@@ -33,6 +33,77 @@ class SendProductionReport extends Command
* Execute the console command.
*/
// public function handle()
// {
// $scheduleType = $this->argument('schedule_type');
// $plantId = $this->argument('plant');
// $mailRules = \App\Models\AlertMailRule::where('module', 'ProductionQuantities')
// ->where('rule_name', 'ProductionMail')
// ->where('plant', $plantId)
// ->where('schedule_type', $scheduleType)
// ->get();
// $emails = $mailRules->pluck('email')->unique()->toArray();
// $plant = Plant::find($plantId);
// if (!$plant) {
// $this->error("Invalid plant ID: $plantId");
// return;
// }
// $lines = Line::where('plant_id', $plantId)->get();
// $startDate = now()->setTime(8, 0, 0);
// $endDate = now()->copy()->addDay()->setTime(8, 0, 0);
// $PlanstartDate = now()->setTime(8, 0, 0);
// $planendDate = now()->copy()->addDay()->setTime(7, 59, 00);
// $tableData = [];
// $no = 1;
// foreach ($lines as $line) {
// $lineId = $line->id;
// $lineName = $line->name;
// $targetQuantity = ProductionPlan::where('plant_id', $plantId)
// ->where('line_id', $lineId)
// ->whereBetween('created_at', [$PlanstartDate, $planendDate])
// ->sum('plan_quantity');
// $productionQuantity = ProductionQuantity::where('plant_id', $plantId)
// ->where('line_id', $lineId)
// ->whereBetween('created_at', [$startDate, $endDate])
// ->count();
// $tableData[] = [
// 'no' => $no++,
// 'plant' => $plant->name,
// 'line' => $lineName,
// 'targetQuantity' => $targetQuantity,
// 'productionQuantity' => $productionQuantity,
// ];
// }
// // $this->table(
// // ['No', 'Plant', 'Line', 'Target Quantity', 'Production Quantity'],
// // $tableData
// // );
// if (!empty($emails)) {
// foreach ($emails as $email) {
// Mail::to($email)->send(new ProductionMail($tableData));
// }
// } else {
// $this->info('No recipients found for ProductionMailAlert.');
// }
// $this->info("Production report sent to " . count($emails) . " recipient(s).");
// }
public function handle()
{
$scheduleType = $this->argument('schedule_type');
@@ -75,6 +146,55 @@ class SendProductionReport extends Command
$tableData = [];
$no = 1;
// foreach ($plants as $plant) {
// $lines = Line::where('plant_id', $plant->id)->get();
// foreach ($lines as $line) {
// $targetQuantity = ProductionPlan::where('plant_id', $plant->id)
// ->where('line_id', $line->id)
// ->whereBetween('created_at', [$PlanstartDate, $planendDate])
// ->sum('plan_quantity');
// $productionQuantity = ProductionQuantity::where('plant_id', $plant->id)
// ->where('line_id', $line->id)
// ->whereBetween('created_at', [$startDate, $endDate])
// ->count();
// $tableData[] = [
// 'no' => $no++,
// 'plant' => $plant->name,
// 'line' => $line->name,
// 'targetQuantity' => $targetQuantity,
// 'productionQuantity' => $productionQuantity,
// ];
// }
// }
// $fgTableData = []; // store FG Line related data
// foreach ($plants as $plant) {
// // ✅ Only get FG Lines
// $fgLines = Line::where('plant_id', $plant->id)
// ->where('type', 'FG Line')
// ->get();
// foreach ($fgLines as $line) {
// $validationCount = \App\Models\QualityValidation::where('plant_id', $plant->id)
// ->where('line_id', $line->id)
// ->whereBetween('created_at', [$startDate, $endDate])
// ->count();
// $fgTableData[] = [
// 'no' => $no++,
// 'plant' => $plant->name,
// 'line' => $line->name,
// 'targetQuantity' => $targetQuantity,
// 'productionQuantity' => $validationCount,
// ];
// }
// }
//..
//.
foreach ($plants as $plant)
@@ -112,38 +232,20 @@ class SendProductionReport extends Command
//$this->table(['No', 'Plant', 'Line', 'Target Quantity', 'Production Quantity'], $fgTableData);
///$this->table(['No', 'Plant', 'Line', 'Target Quantity', 'Production Quantity'], $fgTableData);
// $this->table(['No', 'Plant', 'Line', 'Target Quantity', 'Production Quantity'], $tableData);
$this->table(['No', 'Plant', 'Line', 'Target Quantity', 'Production Quantity'], $tableData);
// if (!empty($emails)) {
// foreach ($emails as $email) {
// Mail::to($email)->send(new ProductionMail($tableData));
// }
// } else {
// $this->info('No recipients found for ProductionMailAlert.');
// }
// $this->info("Production report sent to " . count($emails) . " recipient(s).");
// Preview in console
$mail = new ProductionMail($scheduleType, $tableData);
$contentVars = $mail->content()->with;
$this->info($contentVars['greeting'] ?? 'Production Report');
$this->table(
['No', 'Plant', 'Line', 'Type', 'Target Quantity', 'Production Quantity'],
$tableData
);
$this->info($contentVars['wishes'] ?? '');
// Send mails
if (!empty($emails)) {
foreach ($emails as $email) {
Mail::to($email)->send(new ProductionMail($scheduleType, $tableData));
Mail::to($email)->send(new ProductionMail($tableData));
}
$this->info("Production report sent to " . count($emails) . " recipient(s).");
} else {
$this->warn('No recipients found for ProductionMailAlert.');
$this->info('No recipients found for ProductionMailAlert.');
}
$this->info("Production report sent to " . count($emails) . " recipient(s).");
}
}

View File

@@ -22,7 +22,7 @@ class ConfigurationExporter extends Exporter
// Increment and return the row number
return ++$rowNumber;
}),
ExportColumn::make('plant.code')
ExportColumn::make('plant.name')
->label('PLANT'),
ExportColumn::make('line.name')
->label('LINE'),

View File

@@ -1,74 +0,0 @@
<?php
namespace App\Filament\Exports;
use App\Models\EquipmentMaster;
use Filament\Actions\Exports\ExportColumn;
use Filament\Actions\Exports\Exporter;
use Filament\Actions\Exports\Models\Export;
class EquipmentMasterExporter extends Exporter
{
protected static ?string $model = EquipmentMaster::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.name')
->label('PLANT'),
ExportColumn::make('machine.name')
->label('MACHINE NAME'),
ExportColumn::make('name')
->label('NAME'),
ExportColumn::make('description')
->label('DESCRIPTION'),
ExportColumn::make('make')
->label('MAKE'),
ExportColumn::make('model')
->label('MODEL'),
ExportColumn::make('equipment_number')
->label('EQUIPMENT NUMBER'),
ExportColumn::make('instrument_serial_number')
->label('INSTRUMENT SERIAL NUMBER'),
ExportColumn::make('calibrated_on')
->label('CALIBRATED ON'),
ExportColumn::make('frequency')
->label('FREQUENCY'),
ExportColumn::make('next_calibration_date')
->label('NEXT CALIBRATION DATE'),
ExportColumn::make('calibrated_by')
->label('CALIBRATED BY'),
ExportColumn::make('calibration_certificate')
->label('CALIBRATION CERTIFICATE'),
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 equipment master export has completed and ' . number_format($export->successful_rows) . ' ' . str('row')->plural($export->successful_rows) . ' exported.';
if ($failedRowsCount = $export->getFailedRowsCount()) {
$body .= ' ' . number_format($failedRowsCount) . ' ' . str('row')->plural($failedRowsCount) . ' failed to export.';
}
return $body;
}
}

View File

@@ -1,56 +0,0 @@
<?php
namespace App\Filament\Exports;
use App\Models\GrMaster;
use Filament\Actions\Exports\ExportColumn;
use Filament\Actions\Exports\Exporter;
use Filament\Actions\Exports\Models\Export;
class GrMasterExporter extends Exporter
{
protected static ?string $model = GrMaster::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.name')
->label('PLANT'),
ExportColumn::make('item.code')
->label('ITEM'),
ExportColumn::make('serial_number')
->label('SERIAL NUMBER'),
ExportColumn::make('gr_number')
->label('GR 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 gr master export has completed and ' . number_format($export->successful_rows) . ' ' . str('row')->plural($export->successful_rows) . ' exported.';
if ($failedRowsCount = $export->getFailedRowsCount()) {
$body .= ' ' . number_format($failedRowsCount) . ' ' . str('row')->plural($failedRowsCount) . ' failed to export.';
}
return $body;
}
}

View File

@@ -30,48 +30,8 @@ class LineExporter extends Exporter
->label('NAME'),
ExportColumn::make('type')
->label('TYPE'),
ExportColumn::make('no_of_operation')
->label('NO OF OPERATION'),
ExportColumn::make('workGroup1.name')
->label('WORK GROUP CENTER 1'),
ExportColumn::make('workGroup1.operation_number')
->label('OPERATION NUMBER 1'),
ExportColumn::make('workGroup2.name')
->label('WORK GROUP CENTER 2'),
ExportColumn::make('workGroup2.operation_number')
->label('OPERATION NUMBER 2'),
ExportColumn::make('workGroup3.name')
->label('WORK GROUP CENTER 3'),
ExportColumn::make('workGroup3.operation_number')
->label('OPERATION NUMBER 3'),
ExportColumn::make('workGroup4.name')
->label('WORK GROUP CENTER 4'),
ExportColumn::make('workGroup4.operation_number')
->label('OPERATION NUMBER 4'),
ExportColumn::make('workGroup5.name')
->label('WORK GROUP CENTER 5'),
ExportColumn::make('workGroup5.operation_number')
->label('OPERATION NUMBER 5'),
ExportColumn::make('workGroup6.name')
->label('WORK GROUP CENTER 6'),
ExportColumn::make('workGroup6.operation_number')
->label('OPERATION NUMBER 6'),
ExportColumn::make('workGroup7.name')
->label('WORK GROUP CENTER 7'),
ExportColumn::make('workGroup7.operation_number')
->label('OPERATION NUMBER 7'),
ExportColumn::make('workGroup8.name')
->label('WORK GROUP CENTER 8'),
ExportColumn::make('workGroup8.operation_number')
->label('OPERATION NUMBER 8'),
ExportColumn::make('workGroup9.name')
->label('WORK GROUP CENTER 9'),
ExportColumn::make('workGroup9.operation_number')
->label('OPERATION NUMBER 9'),
ExportColumn::make('workGroup10.name')
->label('WORK GROUP CENTER 10'),
ExportColumn::make('workGroup10.operation_number')
->label('OPERATION NUMBER 10'),
ExportColumn::make('group_work_center')
->label('GROUP WORK CENTER'),
ExportColumn::make('created_at')
->label('CREATED AT'),
ExportColumn::make('updated_at')

View File

@@ -30,8 +30,6 @@ class MachineExporter extends Exporter
->label('MACHINE'),
ExportColumn::make('work_center')
->label('WORK CENTER'),
ExportColumn::make('workGroupMaster.name')
->label('WORK GROUP CENTER'),
ExportColumn::make('created_at')
->label('CREATED AT'),
ExportColumn::make('updated_at')

View File

@@ -0,0 +1,92 @@
<?php
namespace App\Filament\Exports;
use App\Models\MfmReading;
use Filament\Actions\Exports\ExportColumn;
use Filament\Actions\Exports\Exporter;
use Filament\Actions\Exports\Models\Export;
class MfmReadingExporter extends Exporter
{
protected static ?string $model = MfmReading::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.name')
->label('PLANT'),
ExportColumn::make('mfmMeter.name')
->label('MFM METER NAME'),
ExportColumn::make('apparent_energy_received')
->label('APPARENT ENERGY RECEIVED'),
ExportColumn::make('reactive_energy_received')
->label('REACTIVE ENERGY RECEIVED'),
ExportColumn::make('active_energy_received')
->label('ACTIVE ENERGY RECEIVED'),
ExportColumn::make('active_power_r')
->label('ACTIVE POWER R'),
ExportColumn::make('active_power_y')
->label('ACTIVE POWER Y'),
ExportColumn::make('active_power_b')
->label('ACTIVE POWER B'),
ExportColumn::make('active_power_total')
->label('ACTIVE POWER TOTAL'),
ExportColumn::make('voltage_ry')
->label('VOLTAGE RY'),
ExportColumn::make('voltage_yb')
->label('VOLTAGE YB'),
ExportColumn::make('voltage_br')
->label('VOLTAGE BR'),
ExportColumn::make('current_r')
->label('CURRENT R'),
ExportColumn::make('current_y')
->label('CURRENT Y'),
ExportColumn::make('current_b')
->label('CURRENT B'),
ExportColumn::make('current_n')
->label('CURRENT N'),
ExportColumn::make('voltage_r_n')
->label('VOLTAGE R N'),
ExportColumn::make('voltage_y_n')
->label('VOLTAGE Y N'),
ExportColumn::make('voltage_b_n')
->label('VOLTAGE B N'),
ExportColumn::make('frequency')
->label('FREQUENCY'),
ExportColumn::make('power_factor_r')
->label('POWER FACTOR R'),
ExportColumn::make('power_factor_y')
->label('POWER FACTOR Y'),
ExportColumn::make('power_factor_b')
->label('POWER FACTOR B'),
ExportColumn::make('power_factor_total')
->label('POWER FACTOR TOTAL'),
ExportColumn::make('created_at')
->label('CREATED AT'),
ExportColumn::make('updated_at')
->label('UPDATED AT'),
ExportColumn::make('deleted_at')
->label('DELETED AT')
->enabledByDefault(false),
];
}
public static function getCompletedNotificationBody(Export $export): string
{
$body = 'Your mfm reading export has completed and ' . number_format($export->successful_rows) . ' ' . str('row')->plural($export->successful_rows) . ' exported.';
if ($failedRowsCount = $export->getFailedRowsCount()) {
$body .= ' ' . number_format($failedRowsCount) . ' ' . str('row')->plural($failedRowsCount) . ' failed to export.';
}
return $body;
}
}

View File

@@ -22,14 +22,12 @@ class MotorTestingMasterExporter extends Exporter
// Increment and return the row number
return ++$rowNumber;
}),
ExportColumn::make('plant.code')
ExportColumn::make('plant.name')
->label('PLANT'),
ExportColumn::make('item.category')
->label('CATEGORY'),
ExportColumn::make('item.code')
->label('ITEM CODE'),
ExportColumn::make('subassembly_code')
->label('SUBASSEMBLY CODE'),
ExportColumn::make('item.description')
->label('DESCRIPTION'),
ExportColumn::make('isi_model')
@@ -71,9 +69,9 @@ class MotorTestingMasterExporter extends Exporter
ExportColumn::make('res_br_ul')
->label('RESISTANCE BR UL'),
ExportColumn::make('lock_volt_limit')
->label('LOCK VOLT LIMIT'),
->label('LOCK VOLT Limit'),
ExportColumn::make('leak_cur_limit')
->label('LEAK CURRENT LIMIT'),
->label('Leak CURRENT Limit'),
ExportColumn::make('lock_cur_ll')
->label('LOCK CURRENT LL'),
ExportColumn::make('lock_cur_ul')

View File

@@ -2,35 +2,30 @@
namespace App\Filament\Exports;
use App\Models\WorkGroupMaster;
use App\Models\TempLiveReading;
use Filament\Actions\Exports\ExportColumn;
use Filament\Actions\Exports\Exporter;
use Filament\Actions\Exports\Models\Export;
class WorkGroupMasterExporter extends Exporter
class TempLiveReadingExporter extends Exporter
{
protected static ?string $model = WorkGroupMaster::class;
protected static ?string $model = TempLiveReading::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;
}),
->label('NO')
->state(function ($record) use (&$rowNumber) {
return ++$rowNumber;
}),
ExportColumn::make('plant.name')
->label('PLANT'),
ExportColumn::make('name')
->label('NAME'),
ExportColumn::make('description')
->label('DESCRIPTION'),
ExportColumn::make('operation_number')
->label('OPERATION NUMBER'),
ExportColumn::make('created_by')
->label('CREATED BY'),
ExportColumn::make('mfmMeter.name')
->label('MFM METER NAME'),
ExportColumn::make('register_data')
->label('REGISTER DATA'),
ExportColumn::make('created_at')
->label('CREATED AT'),
ExportColumn::make('updated_at')
@@ -38,12 +33,14 @@ class WorkGroupMasterExporter extends Exporter
ExportColumn::make('deleted_at')
->label('DELETED AT')
->enabledByDefault(false),
ExportColumn::make('created_by')
->label('CREATED BY'),
];
}
public static function getCompletedNotificationBody(Export $export): string
{
$body = 'Your work group master export has completed and ' . number_format($export->successful_rows) . ' ' . str('row')->plural($export->successful_rows) . ' exported.';
$body = 'Your temp live reading export has completed and ' . number_format($export->successful_rows) . ' ' . str('row')->plural($export->successful_rows) . ' exported.';
if ($failedRowsCount = $export->getFailedRowsCount()) {
$body .= ' ' . number_format($failedRowsCount) . ' ' . str('row')->plural($failedRowsCount) . ' failed to export.';

View File

@@ -30,25 +30,23 @@ class TestingPanelReadingExporter extends Exporter
->label('LINE'),
ExportColumn::make('machine.name')
->label('MACHINE'),
ExportColumn::make('motorTestingMaster.item.code')
ExportColumn::make('item.code')
->label('ITEM CODE'),
ExportColumn::make('motorTestingMaster.item.description')
ExportColumn::make('item.description')
->label('MODEL'),
ExportColumn::make('output')
->label('OUTPUT'),
ExportColumn::make('serial_number')
->label('SERIAL NUMBER'),
ExportColumn::make('winded_serial_number')
->label('WINDED SERIAL NUMBER'),
ExportColumn::make('motorTestingMaster.kw')
ExportColumn::make('item.kw')
->label('KW'),
ExportColumn::make('motorTestingMaster.hp')
ExportColumn::make('item.hp')
->label('HP'),
ExportColumn::make('motorTestingMaster.phase')
ExportColumn::make('item.phase')
->label('PHASE'),
ExportColumn::make('motorTestingMaster.connection')
ExportColumn::make('item.connection')
->label('CONNECTION'),
ExportColumn::make('motorTestingMaster.isi_model')
ExportColumn::make('item.isi_model')
->label('ISI MODEL'),
ExportColumn::make('before_fr_volt')
->label('BEFORE FR VOLT'),

View File

@@ -1,58 +0,0 @@
<?php
namespace App\Filament\Exports;
use App\Models\User;
use Filament\Actions\Exports\ExportColumn;
use Filament\Actions\Exports\Exporter;
use Filament\Actions\Exports\Models\Export;
class UserExporter extends Exporter
{
protected static ?string $model = User::class;
public static function getColumns(): array
{
static $rowNumber = 0;
return [
// ExportColumn::make('id')
// ->label('ID'),
ExportColumn::make('no')
->label('NO')
->state(function ($record) use (&$rowNumber) {
// Increment and return the row number
return ++$rowNumber;
}),
ExportColumn::make('name')
->label('NAME'),
ExportColumn::make('email')
->label('E-MAIL'),
ExportColumn::make('password')
->label('PASSWORD'),
ExportColumn::make('roles')
->label('ROLES')
->state(function ($record) {
// Assuming Spatie\Permission: roles() relationship
return $record->roles->pluck('name')->join(', ');
}),
ExportColumn::make('created_at')
->label('CREATED AT'),
ExportColumn::make('updated_at')
->label('UPDATED AT'),
ExportColumn::make('deleted_at')
->enabledByDefault(false)
->label('DELETED AT'),
];
}
public static function getCompletedNotificationBody(Export $export): string
{
$body = 'Your user 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

@@ -41,15 +41,15 @@ class ConfigurationImporter extends Importer
ImportColumn::make('line')
->requiredMapping()
->relationship(resolveUsing: 'name')
->exampleHeader('Line')
->exampleHeader('Plant')
->example(['4 inch pump line'])
->label('Line')
->rules(['required']),
ImportColumn::make('plant')
->requiredMapping()
->relationship(resolveUsing: 'code')
->relationship(resolveUsing: 'name')
->exampleHeader('Plant')
->example(['1000'])
->example(['Ransar Industries-I'])
->label('Plant')
->rules(['required']),
];

View File

@@ -36,6 +36,7 @@ class DeviceMasterImporter extends Importer
->requiredMapping()
->exampleHeader('IP Address')
->label('IP Address')
->example('172.31.76.67')
->rules(['required', 'ip']),
ImportColumn::make('created_by')
->requiredMapping()

View File

@@ -1,109 +0,0 @@
<?php
namespace App\Filament\Imports;
use App\Models\EquipmentMaster;
use Filament\Actions\Imports\ImportColumn;
use Filament\Actions\Imports\Importer;
use Filament\Actions\Imports\Models\Import;
class EquipmentMasterImporter extends Importer
{
protected static ?string $model = EquipmentMaster::class;
public static function getColumns(): array
{
return [
ImportColumn::make('plant')
->requiredMapping()
->exampleHeader('Plant Name')
->example('Ransar Industries-I')
->label('Plant Name')
->relationship(resolveUsing:'name')
->rules(['required']),
ImportColumn::make('machine')
->requiredMapping()
->exampleHeader('Machine Name')
->example('1006378')
->label('Machine Name')
->relationship(resolveUsing:'name')
->rules(['required']),
ImportColumn::make('name')
->label('Name')
->exampleHeader('Name')
->example('463605 E-E-078'),
ImportColumn::make('description')
->label('Description')
->exampleHeader('Description')
->example('FIN.6INCH.HOUSING LOWER 150R3+ CI RUN-OUT CHECKING FIXTURE'),
ImportColumn::make('make')
->label('Make')
->exampleHeader('Make')
->example('Ok'),
ImportColumn::make('model')
->label('Model')
->exampleHeader('Model')
->example('Ok'),
ImportColumn::make('equipment_number')
->label('Equipment Number')
->exampleHeader('Equipment Number')
->example('463605 E-E-078'),
ImportColumn::make('instrument_serial_number')
->label('Instrument Serial Number')
->exampleHeader('Instrument Serial Number')
->example('131548498'),
ImportColumn::make('calibrated_on')
->label('Calibrated On')
->exampleHeader('Calibrated On')
->example('01-09-2025 08:00:00')
->requiredMapping()
->rules(['required', 'datetime']),
ImportColumn::make('frequency')
->label('Frequency')
->exampleHeader('Frequency')
->example('15')
->requiredMapping()
->numeric()
->rules(['required', 'integer']),
ImportColumn::make('next_calibration_date')
->label('Next Calibration Date')
->exampleHeader('Next Calibration Date')
->requiredMapping()
->example('16-09-2025 08:00:00')
->rules(['required', 'datetime']),
ImportColumn::make('calibrated_by')
->label('Calibration By')
->example('Sri Venkateswara Tools')
->exampleHeader('Calibration By'),
ImportColumn::make('calibration_certificate')
->label('Calibration Certificate')
->example('1231CRI651')
->exampleHeader('Calibration Certificate'),
ImportColumn::make('created_by')
->label('Created By')
->example('RAS00296')
->exampleHeader('Created By'),
];
}
public function resolveRecord(): ?EquipmentMaster
{
// return EquipmentMaster::firstOrNew([
// // Update existing records, matching them by `$this->data['column_name']`
// 'email' => $this->data['email'],
// ]);
return new EquipmentMaster();
}
public static function getCompletedNotificationBody(Import $import): string
{
$body = 'Your equipment master import has completed and ' . number_format($import->successful_rows) . ' ' . str('row')->plural($import->successful_rows) . ' imported.';
if ($failedRowsCount = $import->getFailedRowsCount()) {
$body .= ' ' . number_format($failedRowsCount) . ' ' . str('row')->plural($failedRowsCount) . ' failed to import.';
}
return $body;
}
}

View File

@@ -4,7 +4,6 @@ namespace App\Filament\Imports;
use App\Models\Line;
use App\Models\Plant;
use App\Models\WorkGroupMaster;
use Filament\Actions\Imports\Exceptions\RowImportFailedException;
use Filament\Actions\Imports\ImportColumn;
use Filament\Actions\Imports\Importer;
@@ -30,61 +29,11 @@ class LineImporter extends Importer
->example('Domestic Assembly')
->label('Line Type')
->rules(['required']),
ImportColumn::make('no_of_operation')
ImportColumn::make('group_work_center')
->requiredMapping()
->exampleHeader('No of Operation')
->example('10')
->label('No of Operation'),
ImportColumn::make('work_group1_id')
->requiredMapping()
->exampleHeader('Work Group Center 1')
->example('RMGCGABC')
->label('Work Group Center 1'),
ImportColumn::make('work_group2_id')
->requiredMapping()
->exampleHeader('Work Group Center 2')
->example('RMGCGABC1')
->label('Work Group Center 2'),
ImportColumn::make('work_group3_id')
->requiredMapping()
->exampleHeader('Work Group Center 3')
->example('RMGCGABC2')
->label('Work Group Center 3'),
ImportColumn::make('work_group4_id')
->requiredMapping()
->exampleHeader('Work Group Center 4')
->example('RMGCGABC1')
->label('Work Group Center 4'),
ImportColumn::make('work_group5_id')
->requiredMapping()
->exampleHeader('Work Group Center 5')
->example('RMGCGABC5')
->label('Work Group Center 5'),
ImportColumn::make('work_group6_id')
->requiredMapping()
->exampleHeader('Work Group Center 6')
->example('RMGCGABC6')
->label('Work Group Center 6'),
ImportColumn::make('work_group7_id')
->requiredMapping()
->exampleHeader('Work Group Center 7')
->example('RMGCGABC7')
->label('Work Group Center 7'),
ImportColumn::make('work_group8_id')
->requiredMapping()
->exampleHeader('Work Group Center 8')
->example('RMGCGABC8')
->label('Work Group Center 8'),
ImportColumn::make('work_group9_id')
->requiredMapping()
->exampleHeader('Work Group Center 9')
->example('RMGCGABC9')
->label('Work Group Center 9'),
ImportColumn::make('work_group10_id')
->requiredMapping()
->exampleHeader('Work Group Center 10')
->example('RMGCGABC10')
->label('Work Group Center 10'),
->exampleHeader('Group Work Center')
->example('RMGCEABC')
->label('Group Work Center'),
ImportColumn::make('plant')
->requiredMapping()
->exampleHeader('Plant Name')
@@ -98,110 +47,34 @@ class LineImporter extends Importer
public function resolveRecord(): ?Line
{
$warnMsg = [];
$plant = Plant::where('name', $this->data['plant'])->first();
if (!$plant) {
throw new RowImportFailedException("Plant '{$this->data['plant']}' not found");
$warnMsg[] = "Plant '" . $this->data['plant'] . "' not found";
}
if (Str::length($this->data['name'] ?? '') <= 0) {
throw new RowImportFailedException("Line name not found");
if (Str::length($this->data['name']) < 0) {
$warnMsg[] = "Line name not found";
}
if (Str::length($this->data['type'] ?? '') <= 0) {
throw new RowImportFailedException("Line type not found");
if (Str::length($this->data['type']) < 0) {
$warnMsg[] = "Line type not found";
}
$noOfOps = (int) ($this->data['no_of_operation'] ?? 0);
if (($noOfOps == null || $noOfOps == '' || !is_numeric($noOfOps)) && $noOfOps != 0) {
throw new RowImportFailedException("'No of Operation' is required and must be a number $noOfOps");
}
if ($noOfOps > 10)
{
throw new RowImportFailedException("Invalid 'No Of Operation' value: {$noOfOps}, maximum allowed is 10");
}
// Validate required work groups
$missingGroups = [];
for ($i = 1; $i <= $noOfOps; $i++) {
if (empty($this->data["work_group{$i}_id"])) {
$missingGroups[] = "work_group{$i}_id";
}
}
if (!empty($missingGroups)) {
throw new RowImportFailedException(
"Invalid data: Required work groups missing values in: " . implode(', ', $missingGroups)
);
}
// Ensure no extra work groups are filled
$invalidGroups = [];
for ($i = $noOfOps + 1; $i <= 10; $i++) {
if (!empty($this->data["work_group{$i}_id"])) {
$invalidGroups[] = "work_group{$i}_id";
}
}
if (!empty($invalidGroups)) {
throw new RowImportFailedException(
"Invalid data: Only first {$noOfOps} work groups should be filled, but values found in: " . implode(', ', $invalidGroups)
);
}
for ($i = 1; $i <= 10; $i++) {
$workGroupName = $this->data["work_group{$i}_id"] ?? null;
if (!$workGroupName) {
continue;
}
$workGroupRecord = WorkGroupMaster::where('name', $workGroupName)
->where('plant_id', $plant->id)
->first();
if (!$workGroupRecord) {
throw new RowImportFailedException("Work group '{$workGroupName}' not found in plant '{$this->data['plant']}'");
}
$existsInLines = Line::where('plant_id', $plant->id)
->where('name', '!=', $this->data['name'])
->where("work_group{$i}_id", $workGroupRecord->id)
->first();
if ($existsInLines) {
$warnMsg[] = "Work group '{$workGroupName}' is already assigned to another line in plant '{$this->data['plant']}'";
}
$this->data["work_group{$i}_id"] = $workGroupRecord->id;
}
if (!empty($warnMsg))
{
if (!empty($warnMsg)) {
throw new RowImportFailedException(implode(', ', $warnMsg));
}
Line::updateOrCreate(
[
return Line::updateOrCreate([
'name' => $this->data['name'],
'plant_id' => $plant->id
],
[
'type' => $this->data['type'],
'no_of_operation' => $noOfOps,
'work_group1_id' => $this->data['work_group1_id'] ?? null,
'work_group2_id' => $this->data['work_group2_id'] ?? null,
'work_group3_id' => $this->data['work_group3_id'] ?? null,
'work_group4_id' => $this->data['work_group4_id'] ?? null,
'work_group5_id' => $this->data['work_group5_id'] ?? null,
'work_group6_id' => $this->data['work_group6_id'] ?? null,
'work_group7_id' => $this->data['work_group7_id'] ?? null,
'work_group8_id' => $this->data['work_group8_id'] ?? null,
'work_group9_id' => $this->data['work_group9_id'] ?? null,
'work_group10_id' => $this->data['work_group10_id'] ?? null,
'group_work_center' => $this->data['group_work_center']
]
);
// return Line::firstOrNew([
// // Update existing records, matching them by `$this->data['column_name']`
// 'email' => $this->data['email'],
// ]);
return null;
// return new Line();
}
public static function getCompletedNotificationBody(Import $import): string

View File

@@ -35,7 +35,7 @@ class LineStopImporter extends Importer
public function resolveRecord(): ?LineStop
{
$warnMsg = [];
if (Str::length($this->data['code']) < 3 || !ctype_alnum($this->data['code'])) {
if (Str::length($this->data['code']) < 6 || !ctype_alnum($this->data['code'])) {
$warnMsg[] = "Invalid line stop code found";
}
if (Str::length($this->data['reason']) < 5) {

View File

@@ -5,7 +5,6 @@ namespace App\Filament\Imports;
use App\Models\Line;
use App\Models\Machine;
use App\Models\Plant;
use App\Models\WorkGroupMaster;
use Filament\Actions\Imports\Exceptions\RowImportFailedException;
use Filament\Actions\Imports\ImportColumn;
use Filament\Actions\Imports\Importer;
@@ -29,15 +28,7 @@ class MachineImporter extends Importer
->requiredMapping()
->exampleHeader('Work Center')
->example('RMGCE001')
->label('Work Center')
->rules(['required']),
ImportColumn::make('workGroupMaster')
->requiredMapping()
->relationship(resolveUsing: 'name')
->exampleHeader('Work Group Center')
->example(['RMGCGABC'])
->label('Work Group Center')
->rules(['required']),
->label('Work Center'),
ImportColumn::make('line')
->requiredMapping()
->relationship(resolveUsing: 'name')
@@ -62,52 +53,26 @@ class MachineImporter extends Importer
$line = null;
$machine = $this->data['name'];
$workCenter = $this->data['work_center'];
$groupWorkCenter = WorkGroupMaster::where('name', $this->data['workGroupMaster'])->first();
if (!$plant) {
$warnMsg[] = "Plant not found!";
$warnMsg[] = "Plant not found";
}
else {
$line = Line::where('name', $this->data['line'])->where('plant_id', $plant->id)->first();
if ($line) {
$grpWrkCnr = $line->no_of_operation;
if (!$grpWrkCnr || $grpWrkCnr < 1)//Str::length($grpWrkCnr) < 1)
$grpWrkCnr = $line->group_work_center;
if (!$grpWrkCnr || Str::length($grpWrkCnr) < 1)
{
$warnMsg[] = "Group work center line not found!";
}
else if (!$groupWorkCenter) {
$warnMsg[] = "Group work center not found!";
}
else {
$dupMachine = Machine::where('plant_id', $plant->id)->where('work_center', '!=', $workCenter)->where('name', $machine)->first();
if ($dupMachine) {
$warnMsg[] = "Duplicate machine name found!";
}
else {
$isValidGroupWork = false;
for ($i = 1; $i <= $line->no_of_operation; $i++) {
$column = "work_group{$i}_id";
if (!empty($line->$column)) {
if ($line->$column == $groupWorkCenter->id) {
$isValidGroupWork = true;
break;
}
}
}
if (!$isValidGroupWork) {
$warnMsg[] = "Group work center does not match with line!";
}
}
$warnMsg[] = "Group work center line not found";
}
}
else
{
$warnMsg[] = "Line not found!";
$warnMsg[] = "Line not found";
}
}
if (Str::length($machine) <= 0) {
$warnMsg[] = "Machine name not found!";
$warnMsg[] = "Machine name not found";
}
if (!empty($warnMsg)) {
@@ -116,13 +81,12 @@ class MachineImporter extends Importer
Machine::updateOrCreate(
[
'name' => $machine,
'plant_id' => $plant->id,
'work_center' => $workCenter
'line_id' => $line->id
],
[
'line_id' => $line->id,
'name' => $machine,
'work_group_master_id' => $groupWorkCenter->id
'work_center' => $workCenter
]
);
return null;

View File

@@ -15,13 +15,13 @@ class MfmMeterImporter extends Importer
{
return [
ImportColumn::make('plant')
->requiredMapping()
->requiredMapping()
->exampleHeader('Plant Name')
->example('Ransar Industries-I')
->label('Plant Name')
->relationship(resolveUsing:'name')
->rules(['required']),
ImportColumn::make('Device Name')
ImportColumn::make('devicemaster')
->requiredMapping()
->exampleHeader('Device Name')
->example('REG001')

View File

@@ -0,0 +1,186 @@
<?php
namespace App\Filament\Imports;
use App\Models\MfmReading;
use Filament\Actions\Imports\ImportColumn;
use Filament\Actions\Imports\Importer;
use Filament\Actions\Imports\Models\Import;
class MfmReadingImporter extends Importer
{
protected static ?string $model = MfmReading::class;
public static function getColumns(): array
{
return [
ImportColumn::make('plant')
->requiredMapping()
->exampleHeader('Plant Name')
->example('Ransar Industries-I')
->label('Plant Name')
->relationship(resolveUsing:'name')
->rules(['required']),
ImportColumn::make('mfmMeter')
->requiredMapping()
->exampleHeader('Mfm Meter Name')
->example('Display SSB')
->label('Display SSB')
->relationship(resolveUsing:'name')
->rules(['required']),
ImportColumn::make('apparent_energy_received')
->requiredMapping()
->exampleHeader('Apparent Energy Received')
->example('1084610')
->label('Apparent Energy Received')
->rules(['required']),
ImportColumn::make('reactive_energy_received')
->requiredMapping()
->exampleHeader('Reactive Energy Received')
->example('347496.9')
->label('Reactive Energy Received')
->rules(['required']),
ImportColumn::make('active_energy_received')
->requiredMapping()
->exampleHeader('Active Energy Received')
->example('611717.1')
->label('Active Energy Received')
->rules(['required']),
ImportColumn::make('active_power_r')
->requiredMapping()
->exampleHeader('Active Power R')
->example('3.974')
->label('Active Power R')
->rules(['required']),
ImportColumn::make('active_power_y')
->requiredMapping()
->exampleHeader('Active Power Y')
->example('0.796')
->label('Active Power Y')
->rules(['required']),
ImportColumn::make('active_power_b')
->requiredMapping()
->exampleHeader('Active Power B')
->example('1.397')
->label('Active Power B')
->rules(['required']),
ImportColumn::make('active_power_total')
->requiredMapping()
->exampleHeader('Active Power Total')
->example('6.433')
->label('Active Power Total')
->rules(['required']),
ImportColumn::make('voltage_ry')
->requiredMapping()
->exampleHeader('Voltage RY')
->example('413.308')
->label('Voltage RY')
->rules(['required']),
ImportColumn::make('voltage_yb')
->requiredMapping()
->exampleHeader('Voltage YB')
->example('415.305')
->label('Voltage YB')
->rules(['required']),
ImportColumn::make('voltage_br')
->requiredMapping()
->exampleHeader('Voltage BR')
->example('415.216')
->label('Voltage BR')
->rules(['required']),
ImportColumn::make('current_r')
->requiredMapping()
->exampleHeader('Current R')
->example('17.446')
->label('Current R')
->rules(['required']),
ImportColumn::make('current_y')
->requiredMapping()
->exampleHeader('Current Y')
->example('4.801')
->label('Current Y')
->rules(['required']),
ImportColumn::make('current_b')
->requiredMapping()
->exampleHeader('Current B')
->example('7.04')
->label('Current B')
->rules(['required']),
ImportColumn::make('current_n')
->requiredMapping()
->exampleHeader('Current N')
->example('14.063')
->label('Current N')
->rules(['required']),
ImportColumn::make('voltage_r_n')
->requiredMapping()
->exampleHeader('Voltage R N')
->example('237.898')
->label('Voltage R N')
->rules(['required']),
ImportColumn::make('voltage_y_n')
->requiredMapping()
->exampleHeader('Voltage Y N')
->example('239.518')
->label('Voltage Y N')
->rules(['required']),
ImportColumn::make('voltage_b_n')
->requiredMapping()
->exampleHeader('Voltage B N')
->example('240.798')
->label('Voltage B N')
->rules(['required']),
ImportColumn::make('frequency')
->requiredMapping()
->exampleHeader('Frequency')
->example('50.228')
->label('Frequency')
->rules(['required']),
ImportColumn::make('power_factor_r')
->requiredMapping()
->exampleHeader('Power Factor R')
->example('0.988')
->label('Power Factor R')
->rules(['required']),
ImportColumn::make('power_factor_y')
->requiredMapping()
->exampleHeader('Power Factor Y')
->example('0.764')
->label('Power Factor Y')
->rules(['required']),
ImportColumn::make('power_factor_b')
->requiredMapping()
->exampleHeader('Power Factor B')
->example('0.849')
->label('Power Factor B')
->rules(['required']),
ImportColumn::make('power_factor_total')
->requiredMapping()
->exampleHeader('Power Factor Total')
->example('0.919')
->label('Power Factor Total')
->rules(['required']),
];
}
public function resolveRecord(): ?MfmReading
{
// return MfmReading::firstOrNew([
// // Update existing records, matching them by `$this->data['column_name']`
// 'email' => $this->data['email'],
// ]);
return new MfmReading();
}
public static function getCompletedNotificationBody(Import $import): string
{
$body = 'Your mfm reading import has completed and ' . number_format($import->successful_rows) . ' ' . str('row')->plural($import->successful_rows) . ' imported.';
if ($failedRowsCount = $import->getFailedRowsCount()) {
$body .= ' ' . number_format($failedRowsCount) . ' ' . str('row')->plural($failedRowsCount) . ' failed to import.';
}
return $body;
}
}

View File

@@ -2,17 +2,11 @@
namespace App\Filament\Imports;
use App\Models\Item;
use App\Models\MotorTestingMaster;
use App\Models\Plant;
use App\Models\User;
use DateTime;
use Filament\Actions\Imports\Exceptions\RowImportFailedException;
use Filament\Actions\Imports\ImportColumn;
use Filament\Actions\Imports\Importer;
use Filament\Actions\Imports\Models\Import;
use Filament\Facades\Filament;
use Str;
class MotorTestingMasterImporter extends Importer
{
@@ -28,14 +22,7 @@ class MotorTestingMasterImporter extends Importer
->label('Item Code')
->relationship(resolveUsing: 'code')
->rules(['required']),
ImportColumn::make('subassembly_code')
->requiredMapping()
->exampleHeader('SubAssembly Code')
->example(['123456'])
->label('SubAssembly Code')
->rules(['required']),
ImportColumn::make('isi_model')
->requiredMapping()
->boolean()
->exampleHeader('ISI Model')
->example(['Y','N','Y'])
@@ -157,8 +144,8 @@ class MotorTestingMasterImporter extends Importer
->rules(['required']),
ImportColumn::make('leak_cur_limit')
->requiredMapping()
->exampleHeader('Leak Current Limit')
->label('Leak Current Limit')
->exampleHeader('Leakage Current Limit')
->label('Leakage Current Limit')
->example(['50','50','50'])
->rules(['required']),
ImportColumn::make('lock_cur_ll')
@@ -212,9 +199,9 @@ class MotorTestingMasterImporter extends Importer
ImportColumn::make('plant')
->requiredMapping()
->exampleHeader('Plant')
->example(['1000','1010','1020'])
->example(['Ransar Industries-I','Ransar Industries-I','Ransar Industries-I'])
->label('Plant')
->relationship(resolveUsing: 'code')
->relationship(resolveUsing: 'name')
->rules(['required']),
ImportColumn::make('created_by')
->requiredMapping()
@@ -233,245 +220,12 @@ class MotorTestingMasterImporter extends Importer
public function resolveRecord(): ?MotorTestingMaster
{
$warnMsg = [];
$plantCod = trim($this->data['plant']);
$iCode = trim($this->data['item']);
$sCode = trim($this->data['subassembly_code']);
$isiModel = (trim($this->data['isi_model']) == "1") ? true : false;
$phase = trim($this->data['phase']);
$kw = trim($this->data['kw']);
$hp = trim($this->data['hp']);
$volt = trim($this->data['volt']);
$current = trim($this->data['current']);
$rpm = trim($this->data['rpm']);
$torque = trim($this->data['torque']);
$frequency = trim($this->data['frequency']);
$connection = trim($this->data['connection']);
$insResType = trim($this->data['ins_res_type']);
$insResLimit = trim($this->data['ins_res_limit']);
$routineTestTime = trim($this->data['routine_test_time']);
$resRyLl = trim($this->data['res_ry_ll']);
$resRyUl = trim($this->data['res_ry_ul']);
$resYbLl = trim($this->data['res_yb_ll']);
$resYbUl = trim($this->data['res_yb_ul']);
$resBrLl = trim($this->data['res_br_ll']);
$resBrUl = trim($this->data['res_br_ul']);
$lockVoltLimit = trim($this->data['lock_volt_limit']);
$leakCurLimit = trim($this->data['leak_cur_limit']);
$lockCurLl = trim($this->data['lock_cur_ll']);
$lockCurUl = trim($this->data['lock_cur_ul']);
$noloadCurLl = trim($this->data['noload_cur_ll']);
$noloadCurUl = trim($this->data['noload_cur_ul']);
$noloadPowLl = trim($this->data['noload_pow_ll']);
$noloadPowUl = trim($this->data['noload_pow_ul']);
$noloadSpdLl = trim($this->data['noload_spd_ll']);
$noloadSpdUl = trim($this->data['noload_spd_ul']);
$createdBy = trim($this->data['created_by']);
$updatedBy = trim($this->data['updated_by']);
// return MotorTestingMaster::firstOrNew([
// // Update existing records, matching them by `$this->data['column_name']`
// 'email' => $this->data['email'],
// ]);
$plant = null;
if (Str::length($plantCod) < 4 || !is_numeric($plantCod) || !preg_match('/^[1-9]\d{3,}$/', $plantCod))
{
$warnMsg[] = "Invalid plant code found";
}
else if (Str::length($iCode) < 6 || !ctype_alnum($iCode))
{
$warnMsg[] = "Invalid item code found";
}
else if (Str::length($sCode) < 6 || !ctype_alnum($sCode))
{
$warnMsg[] = "Invalid sub-assembly code found";
}
else
{
$plant = Plant::where('code', $plantCod)->first();
$codeExist = Item::where('code', $iCode)->first();
if ($plant)
{
$iCode = Item::where('code', $iCode)->where('plant_id', $plant->id)->first();
}
if (!$plant)
{
$warnMsg[] = "Plant not found";
}
else if (!$codeExist)
{
$warnMsg[] = "Item code not found";
}
else if (!$iCode)
{
$warnMsg[] = "Item code not found for choosed plant";
}
else
{
// if (Str::length($isiModel) <= 0 || $isiModel == "0" || $isiModel == "1") {
// $warnMsg[] = "Invalid ISI Model found";
// }
// else
// {
// $isiModel = ($isiModel == "1");
// }
if (Str::length($phase) <= 0 || ($phase != "Single" && $phase != "Three")) {//!is_string($phase) ||
$warnMsg[] = "Invalid phase found";
}
if (Str::length($hp) <= 0 || !is_numeric($hp)) {
$warnMsg[] = "Invalid HP found";
}
if (Str::length($kw) <= 0 || !is_numeric($kw)) {
$warnMsg[] = "Invalid KW found";
}
if (Str::length($volt) <= 0 || !is_numeric($volt)) {
$warnMsg[] = "Invalid volt found";
}
if (Str::length($current) <= 0 || !is_numeric($current)) {
$warnMsg[] = "Invalid current found";
}
if (Str::length($rpm) <= 0 || !is_numeric($rpm)) {
$warnMsg[] = "Invalid RPM found";
}
if (Str::length($torque) <= 0 || !is_numeric($torque)) {
$warnMsg[] = "Invalid torque found";
}
if (Str::length($frequency) <= 0 || !is_numeric($frequency)) {
$warnMsg[] = "Invalid frequency found";
}
if (Str::length($connection) <= 0 || ($connection != "Star-Delta" && $connection != "Star" && $connection != "Delta")) {
$warnMsg[] = "Invalid connection found";
}
if (Str::length($insResLimit) <= 0 || !is_numeric($insResLimit)) {
$warnMsg[] = "Invalid insulation resistance limit found";
}
if (Str::length($insResType) <= 0 || ($insResType != "O" && $insResType != "M" && $insResType != "G")) {
$warnMsg[] = "Invalid insulation resistance type found";
}
if (Str::length($routineTestTime) <= 0 || !isValidTimeFormat($routineTestTime)) {
$warnMsg[] = "Invalid routine test time found";
}
if (Str::length($resRyLl) <= 0 || !is_numeric($resRyLl)) {
$warnMsg[] = "Invalid resistance RY lower limit found";
}
if (Str::length($resRyUl) <= 0 || !is_numeric($resRyUl)) {
$warnMsg[] = "Invalid resistance RY upper limit found";
}
if (Str::length($resYbLl) <= 0 || !is_numeric($resYbLl)) {
$warnMsg[] = "Invalid resistance YB lower limit found";
}
if (Str::length($resYbUl) <= 0 || !is_numeric($resYbUl)) {
$warnMsg[] = "Invalid resistance YB upper limit found";
}
if (Str::length($resBrLl) <= 0 || !is_numeric($resBrLl)) {
$warnMsg[] = "Invalid resistance BR lower limit found";
}
if (Str::length($resBrUl) <= 0 || !is_numeric($resBrUl)) {
$warnMsg[] = "Invalid resistance BR upper limit found";
}
if (Str::length($lockVoltLimit) <= 0 || !is_numeric($lockVoltLimit)) {
$warnMsg[] = "Invalid locked volt limit found";
}
if (Str::length($leakCurLimit) <= 0 || !is_numeric($leakCurLimit)) {
$warnMsg[] = "Invalid leakage current limit found";
}
if (Str::length($lockCurLl) <= 0 || !is_numeric($lockCurLl)) {
$warnMsg[] = "Invalid locked current lower limit found";
}
if (Str::length($lockCurUl) <= 0 || !is_numeric($lockCurUl)) {
$warnMsg[] = "Invalid locked current upper limit found";
}
if (Str::length($noloadCurLl) <= 0 || !is_numeric($noloadCurLl)) {
$warnMsg[] = "Invalid no load current lower limit found";
}
if (Str::length($noloadCurUl) <= 0 || !is_numeric($noloadCurUl)) {
$warnMsg[] = "Invalid no load current upper limit found";
}
if (Str::length($noloadPowLl) <= 0 || !is_numeric($noloadPowLl)) {
$warnMsg[] = "Invalid no load power lower limit found";
}
if (Str::length($noloadPowUl) <= 0 || !is_numeric($noloadPowUl)) {
$warnMsg[] = "Invalid no load power upper limit found";
}
if (Str::length($noloadSpdLl) <= 0 || !is_numeric($noloadSpdLl)) {
$warnMsg[] = "Invalid no load speed lower limit found";
}
if (Str::length($noloadSpdUl) <= 0 || !is_numeric($noloadSpdUl)) {
$warnMsg[] = "Invalid no load speed upper limit found";
}
$oldCode = MotorTestingMaster::where('item_id', $iCode->id)->where('plant_id', $plant->id)->first();
if ($oldCode) {
$created = $oldCode->created_by ? User::where('name', $oldCode->created_by)->first() : null;
if (!$created) {
$warnMsg[] = "Created by not found on update";
}
$updated = User::where('name', $updatedBy)->first();
if (!$updated) {
$warnMsg[] = "Updated by not found on update";
}
}
else
{
$created = User::where('name', $createdBy)->first();
if (!$created) {
$warnMsg[] = "Created by not found";
}
$updated = User::where('name', $updatedBy)->first();
if (!$updated) {
$warnMsg[] = "Updated by not found";
}
}
}
}
if (!empty($warnMsg)) {
throw new RowImportFailedException(implode(', ', $warnMsg));
}
MotorTestingMaster::updateOrCreate([
'plant_id' => $plant->id,
'item_id' => $iCode->id
],
[
'subassembly_code' => $sCode,
'isi_model' => $isiModel,
'phase' => $phase,
'kw' => $kw,
'hp' => $hp,
'volt' => $volt,
'current' => $current,
'rpm' => $rpm,
'torque' => $torque,
'frequency' => $frequency,
'connection' => $connection,
'ins_res_limit' => $insResLimit,
'ins_res_type' => $insResType,
'routine_test_time' => $routineTestTime,
'res_ry_ll' => $resRyLl,
'res_ry_ul' => $resRyUl,
'res_yb_ll' => $resYbLl,
'res_yb_ul' => $resYbUl,
'res_br_ll' => $resBrLl,
'res_br_ul' => $resBrUl,
'lock_volt_limit' => $lockVoltLimit,
'leak_cur_limit' => $leakCurLimit,
'lock_cur_ll' => $lockCurLl,
'lock_cur_ul' => $lockCurUl,
'noload_cur_ll' => $noloadCurLl,
'noload_cur_ul' => $noloadCurUl,
'noload_pow_ll' => $noloadPowLl,
'noload_pow_ul' => $noloadPowUl,
'noload_spd_ll' => $noloadSpdLl,
'noload_spd_ul' => $noloadSpdUl,
'created_by' => $created->name,
'updated_by' => $updated->name,
]
);
return null;
// // return MotorTestingMaster::firstOrNew([
// // // Update existing records, matching them by `$this->data['column_name']`
// // 'email' => $this->data['email'],
// // ]);
// return new MotorTestingMaster();
return new MotorTestingMaster();
}
public static function getCompletedNotificationBody(Import $import): string
@@ -485,13 +239,3 @@ class MotorTestingMasterImporter extends Importer
return $body;
}
}
function isValidTimeFormat($time) {
// If time starts with a single digit hour without leading zero, pad it
if (preg_match('/^\d(:\d{2}:\d{2})$/', $time, $matches)) {
$time = '0' . $time;
}
$dateTime = DateTime::createFromFormat('H:i:s', $time);
return $dateTime && $dateTime->format('H:i:s') === $time;
}

View File

@@ -12,21 +12,10 @@ use Filament\Actions\Imports\Importer;
use Filament\Actions\Imports\Models\Import;
use Str;
class PalletValidationImporter extends Importer
{
protected static ?string $model = PalletValidation::class;
// public static function canQueue(): bool
// {
// return true; // allows this importer to be queued
// }
// public static function getChunkSize(): ?int
// {
// return 1000;
// }
public static function getColumns(): array
{
return [

View File

@@ -59,9 +59,9 @@ class ProductionQuantityImporter extends Importer
->rules(['required']),
ImportColumn::make('block_reference')
->requiredMapping() // Or optionalMapping() if not always present
->exampleHeader('Block')
->exampleHeader('Block Name')
->example(['Block A', 'Block A'])
->label('Block')
->label('Block Name')
->rules(['required']), // Or remove if not required
ImportColumn::make('shift')
->requiredMapping()

View File

@@ -193,9 +193,9 @@ class QualityValidationImporter extends Importer
$line = Line::where('name', $this->data['line'])->where('plant_id', $plant->id)->first();
$uniqueCode = trim($this->data['sticker_master_id_code']);// stickerMaster.item
$stickMaster = StickerMaster::select('id')->with('item')
->whereHas('item', function ($query) use ($uniqueCode, $plant) {
$query->where('code', $uniqueCode)->where('plant_id', $plant->id);
})->value('id');
->whereHas('item', function ($query) use ($uniqueCode, $plant) {
$query->where('code', $uniqueCode)->where('plant_id', $plant->id);
})->value('id');
}
if (!$line) {
@@ -281,13 +281,11 @@ class QualityValidationImporter extends Importer
QualityValidation::updateOrCreate([
'plant_id' => $plant->id,
'sticker_master_id' => $stickMaster,//->id
'serial_number' => $this->data['serial_number']
],
[
'line_id' => $line->id,
'sticker_master_id' => $stickMaster,//->id
'uom' => $this->data['uom'],
'production_order' => $this->data['production_order'],
'serial_number' => $this->data['serial_number'],
'serial_number_motor' => $this->data['serial_number_motor'],
'serial_number_pump' => $this->data['serial_number_pump'],
'serial_number_pumpset' => $this->data['serial_number_pumpset'],

View File

@@ -2,14 +2,14 @@
namespace App\Filament\Imports;
use App\Models\GrMaster;
use App\Models\TempLiveReading;
use Filament\Actions\Imports\ImportColumn;
use Filament\Actions\Imports\Importer;
use Filament\Actions\Imports\Models\Import;
class GrMasterImporter extends Importer
class TempLiveReadingImporter extends Importer
{
protected static ?string $model = GrMaster::class;
protected static ?string $model = TempLiveReading::class;
public static function getColumns(): array
{
@@ -21,24 +21,18 @@ class GrMasterImporter extends Importer
->label('Plant Name')
->relationship(resolveUsing:'name')
->rules(['required']),
ImportColumn::make('item')
ImportColumn::make('mfmMeter')
->requiredMapping()
->exampleHeader('Item Code')
->example('630214')
->label('Item Code')
->exampleHeader('Mfm Meter Name')
->example('Display SSB')
->label('Mfm Meter Name')
->relationship(resolveUsing:'name')
->rules(['required']),
ImportColumn::make('serial_number')
ImportColumn::make('register_data')
->requiredMapping()
->exampleHeader('Serial Number')
->example('11023567567567')
->label('Serial Number')
->rules(['required']),
ImportColumn::make('gr_number')
->requiredMapping()
->exampleHeader('GR Number')
->example('67345237')
->label('GR Number')
->exampleHeader('Register Data')
->example('65165,5646,561,561')
->label('Register Data')
->rules(['required']),
ImportColumn::make('created_by')
->requiredMapping()
@@ -46,23 +40,22 @@ class GrMasterImporter extends Importer
->example('Admin')
->label('Created By')
->rules(['required']),
//ImportColumn::make('updated_by'),
];
}
public function resolveRecord(): ?GrMaster
public function resolveRecord(): ?TempLiveReading
{
// return GrMaster::firstOrNew([
// return TempLiveReading::firstOrNew([
// // Update existing records, matching them by `$this->data['column_name']`
// 'email' => $this->data['email'],
// ]);
return new GrMaster();
return new TempLiveReading();
}
public static function getCompletedNotificationBody(Import $import): string
{
$body = 'Your gr master import has completed and ' . number_format($import->successful_rows) . ' ' . str('row')->plural($import->successful_rows) . ' imported.';
$body = 'Your temp live reading import has completed and ' . number_format($import->successful_rows) . ' ' . str('row')->plural($import->successful_rows) . ' imported.';
if ($failedRowsCount = $import->getFailedRowsCount()) {
$body .= ' ' . number_format($failedRowsCount) . ' ' . str('row')->plural($failedRowsCount) . ' failed to import.';

View File

@@ -14,11 +14,11 @@ class TestingPanelReadingImporter extends Importer
public static function getColumns(): array
{
return [
ImportColumn::make('machine')
ImportColumn::make('item')
->requiredMapping()
->relationship()
->rules(['required']),
ImportColumn::make('motorTestingMaster.item.code')
ImportColumn::make('machine')
->requiredMapping()
->relationship()
->rules(['required']),
@@ -28,9 +28,6 @@ class TestingPanelReadingImporter extends Importer
ImportColumn::make('serial_number')
->requiredMapping()
->rules(['required']),
ImportColumn::make('winded_serial_number')
->requiredMapping()
->rules(['required']),
ImportColumn::make('before_fr_volt'),
ImportColumn::make('before_fr_cur'),
ImportColumn::make('before_fr_pow'),

View File

@@ -1,114 +0,0 @@
<?php
namespace App\Filament\Imports;
use App\Models\User;
use Filament\Actions\Imports\Exceptions\RowImportFailedException;
use Filament\Actions\Imports\ImportColumn;
use Filament\Actions\Imports\Importer;
use Filament\Actions\Imports\Models\Import;
use Spatie\Permission\Models\Role;
use Str;
class UserImporter extends Importer
{
protected static ?string $model = User::class;
public static function getColumns(): array
{
return [
ImportColumn::make('name')
->requiredMapping()
->exampleHeader('Name')
->example('RAW00001')
->label('Name')
->rules(['required']),//, 'max:255'
ImportColumn::make('email')
->requiredMapping()
->exampleHeader('E-mail')
->example('RAW00001@cripumps.com')
->label('E-mail')
->rules(['required', 'email']),//, 'max:255'
ImportColumn::make('password')
->requiredMapping()
->exampleHeader('Password')
->example('RAW00001')
->label('Password')
->rules(['required']),//, 'max:255'
ImportColumn::make('roles')
->requiredMapping()
->exampleHeader('Roles')
->example('Employee')
->label('Roles')
->rules(['nullable', 'string']), // Optional roles
];
}
public function resolveRecord(): ?User
{
$warnMsg = [];
if (Str::length($this->data['name']) < 1) {
$warnMsg[] = "User name not found!";
}
// || !is_numeric($this->data['code']) || !preg_match('/^[1-9]\d{3,}$/', $this->data['code'])
if (Str::length($this->data['email']) < 5) {
$warnMsg[] = "Invalid email found!";
}
if (Str::length($this->data['password']) < 3) {
$warnMsg[] = "Invalid password found!";
}
// Validate roles if provided
$roles = [];
if (!empty($this->data['roles'])) {
$roles = collect(explode(',', $this->data['roles']))
->map(fn($role) => trim($role))
->filter()
->toArray();
foreach ($roles as $roleName) {
if (!Role::where('name', $roleName)->exists()) {
$warnMsg[] = "Role : '{$roleName}' does not exist!";
}
}
}
else {
$warnMsg[] = "User roles not found!";
}
if (!empty($warnMsg)) {
throw new RowImportFailedException(implode(', ', $warnMsg));
}
$user = User::updateOrCreate([
'email' => $this->data['email'],
],
[
'name' => $this->data['name'],
'password' => $this->data['password'],
]);
// Assign roles
if (!empty($roles)) {
$user->syncRoles($roles);
}
return null;
// return User::firstOrNew([
// // Update existing records, matching them by `$this->data['column_name']`
// 'email' => $this->data['email'],
// ]);
//return new User();
}
public static function getCompletedNotificationBody(Import $import): string
{
$body = 'Your user import has completed and ' . number_format($import->successful_rows) . ' ' . str('row')->plural($import->successful_rows) . ' imported.';
if ($failedRowsCount = $import->getFailedRowsCount()) {
$body .= ' ' . number_format($failedRowsCount) . ' ' . str('row')->plural($failedRowsCount) . ' failed to import.';
}
return $body;
}
}

View File

@@ -1,154 +0,0 @@
<?php
namespace App\Filament\Imports;
use App\Models\Plant;
use App\Models\User;
use App\Models\WorkGroupMaster;
use Filament\Actions\Imports\Exceptions\RowImportFailedException;
use Filament\Actions\Imports\ImportColumn;
use Filament\Actions\Imports\Importer;
use Filament\Actions\Imports\Models\Import;
use Str;
class WorkGroupMasterImporter extends Importer
{
protected static ?string $model = WorkGroupMaster::class;
public static function getColumns(): array
{
return [
ImportColumn::make('plant')
->requiredMapping()
->exampleHeader('Plant Name')
->example('Ransar Industries-I')
->label('Plant Name')
->relationship(resolveUsing:'name')
->rules(['required']),
ImportColumn::make('name')
->requiredMapping()
->exampleHeader('Name')
->example('RMGCEABC')
->label('Name')
->rules(['required']),
ImportColumn::make('description')
->requiredMapping()
->exampleHeader('Description')
->example('Testing Model 1')
->label('Description')
->rules(['required']),
ImportColumn::make('operation_number')
->requiredMapping()
->exampleHeader('Operation Number')
->example('0020')
->label('Operation Number')
->rules(['required']),
ImportColumn::make('created_by')
->requiredMapping()
->exampleHeader('Created By')
->example('Admin')
->label('Created By')
->rules(['required']),
];
}
public function resolveRecord(): ?WorkGroupMaster
{
// return WorkGroupMaster::firstOrNew([
// // Update existing records, matching them by `$this->data['column_name']`
// 'email' => $this->data['email'],
// ]);
$warnMsg = [];
$plant = Plant::where('name', $this->data['plant'])->first();
if (!$plant) {
$warnMsg[] = "Plant not found";
}
if (Str::length($this->data['name']) <= 0) { //|| !ctype_alnum($this->data['description'])
$warnMsg[] = "Invalid name found";
}
if (Str::length(trim($this->data['description'])) <= 0) {
$warnMsg[] = "Invalid description found";
}
$desc = trim($this->data['description']);
if (Str::length($desc) > 44) {
$warnMsg[] = "Description should be less than 44 digits.";
}
if (Str::length($this->data['operation_number']) <= 0) {
$warnMsg[] = "Invalid operation number found";
}
if(!is_numeric($this->data['operation_number']))
{
$warnMsg[] = "Invalid operation number found must be numeric";
}
$user = User::where('name', $this->data['created_by'])->first();
if (!$user) {
$warnMsg[] = "Operator ID not found";
}
if (!empty($warnMsg)) {
throw new RowImportFailedException(implode(', ', $warnMsg));
}
else
{
//Check (plant_id, name)
$existingByName = WorkGroupMaster::where('plant_id', $plant->id)
->where('name', $this->data['name'])
->first();
if ($existingByName) {
throw new RowImportFailedException("Work group name already exists for this plant!");
}
//Check (plant_id, operation_number)
$existingByOpNum = WorkGroupMaster::where('plant_id', $plant->id)
->where('operation_number', $this->data['operation_number'])
->where('name', $this->data['name'])
->first();
if ($existingByOpNum) {
throw new RowImportFailedException("Operation number already exists for this plant!");
}
//Check (plant_id)
$existingByOperator = WorkGroupMaster::where('plant_id', $plant->id)
->where('name', $this->data['name'])
->first();
if ($existingByOperator) {
throw new RowImportFailedException("Already work group name assigned to another plant!");
}
}
WorkGroupMaster::updateOrCreate([
'plant_id' => $plant->id,
'name' => $this->data['name'],
'description' => $this->data['description'],
'operation_number' => $this->data['operation_number'],
'created_by' => $this->data['created_by'],
]);
return null;
//return new WorkGroupMaster();
}
public static function getCompletedNotificationBody(Import $import): string
{
$body = 'Your work group master import has completed and ' . number_format($import->successful_rows) . ' ' . str('row')->plural($import->successful_rows) . ' imported.';
if ($failedRowsCount = $import->getFailedRowsCount()) {
$body .= ' ' . number_format($failedRowsCount) . ' ' . str('row')->plural($failedRowsCount) . ' failed to import.';
}
return $body;
}
}

View File

@@ -12,15 +12,11 @@ class CreateAlertMailRule extends CreateRecord
protected function mutateFormDataBeforeCreate(array $data): array
{
if ($data['is_active']) {
$data['plant'] = 0;
}
return $data;
}
protected function getRedirectUrl(): string
{
return $this->getResource()::getUrl('create');
}
}

View File

@@ -9,9 +9,4 @@ use Filament\Resources\Pages\CreateRecord;
class CreateBlock extends CreateRecord
{
protected static string $resource = BlockResource::class;
protected function getRedirectUrl(): string
{
return $this->getResource()::getUrl('create');
}
}

View File

@@ -28,7 +28,7 @@ class CheckPointNameResource extends Resource
protected static ?string $navigationGroup = 'Master Entries';
protected static ?int $navigationSort = 15;
protected static ?int $navigationSort = 14;
public static function form(Form $form): Form
{

View File

@@ -29,7 +29,7 @@ class CheckPointTimeResource extends Resource
protected static ?string $navigationGroup = 'Master Entries';
protected static ?int $navigationSort = 16;
protected static ?int $navigationSort = 15;
public static function form(Form $form): Form
{

View File

@@ -9,9 +9,4 @@ use Filament\Resources\Pages\CreateRecord;
class CreateCompany extends CreateRecord
{
protected static string $resource = CompanyResource::class;
protected function getRedirectUrl(): string
{
return $this->getResource()::getUrl('create');
}
}

View File

@@ -9,9 +9,4 @@ use Filament\Resources\Pages\CreateRecord;
class CreateConfiguration extends CreateRecord
{
protected static string $resource = ConfigurationResource::class;
protected function getRedirectUrl(): string
{
return $this->getResource()::getUrl('create');
}
}

View File

@@ -9,9 +9,4 @@ use Filament\Resources\Pages\CreateRecord;
class CreateDeviceMaster extends CreateRecord
{
protected static string $resource = DeviceMasterResource::class;
protected function getRedirectUrl(): string
{
return $this->getResource()::getUrl('create');
}
}

View File

@@ -9,9 +9,4 @@ use Filament\Resources\Pages\CreateRecord;
class CreateEbReading extends CreateRecord
{
protected static string $resource = EbReadingResource::class;
protected function getRedirectUrl(): string
{
return $this->getResource()::getUrl('create');
}
}

View File

@@ -1,505 +0,0 @@
<?php
namespace App\Filament\Resources;
use App\Filament\Exports\EquipmentMasterExporter;
use App\Filament\Imports\EquipmentMasterImporter;
use App\Filament\Resources\EquipmentMasterResource\Pages;
use App\Filament\Resources\EquipmentMasterResource\RelationManagers;
use App\Models\EquipmentMaster;
use Carbon\Carbon;
use Filament\Forms\Components\Actions\Action;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use Filament\Facades\Filament;
use Filament\Notifications\Notification;
use Filament\Tables\Actions\ImportAction;
use Filament\Tables\Actions\ExportAction;
use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;
use Storage;
use Illuminate\Validation\Rule;
class EquipmentMasterResource extends Resource
{
protected static ?string $model = EquipmentMaster::class;
protected static ?string $navigationIcon = 'heroicon-o-rectangle-stack';
protected static ?string $navigationGroup = 'Testing Panel';
protected static ?int $navigationSort = 2;
public static function form(Form $form): Form
{
return $form
->schema([
Forms\Components\Select::make('plant_id')
->label('Plant')
->reactive()
->relationship('plant', 'name')
->required(),
Forms\Components\Select::make('machine_id')
//->relationship('machine', 'name')
->label('Work Center')
->reactive()
->options(function (callable $get) {
$plantId = $get('plant_id');
if (empty($plantId)) {
return [];
}
return \App\Models\Machine::where('plant_id', $plantId)->pluck('work_center', 'id');
})
->required(),
Forms\Components\TextInput::make('name')
->label('Name'),
Forms\Components\TextInput::make('description')
->label('Description'),
Forms\Components\TextInput::make('make')
->label('Make'),
Forms\Components\TextInput::make('model')
->label('Model'),
Forms\Components\TextInput::make('equipment_number')
->label('Equipment Number')
->reactive()
->rules(function (callable $get) {
return [
Rule::unique('equipment_masters', 'equipment_number')
->where(function ($query) use ($get) {
return $query->where('plant_id', $get('plant_id'));
})
->ignore($get('id')),
];
})
->afterStateUpdated(function ($state, callable $set) {
if (! $state) {
return;
}
$model = EquipmentMaster::where('equipment_number', $state)->first();
if ($model?->attachment) {
$set('attachment', $model->attachment);
} else {
$set('attachment', null);
}
}),
//->afterStateUpdated(function ($state, callable $set) {
// if (! $state) {
// return;
// }
// $model = EquipmentMaster::where('equipment_number', $state)->first();
// if ($model?->attachment) {
// $set('attachment', $model->attachment);
// } else {
// $set('attachment', null);
// }
// }),
Forms\Components\TextInput::make('instrument_serial_number')
->label('Instrument Serial Number'),
// Forms\Components\DateTimePicker::make('calibrated_on')
// ->label('Calibrated On')
// ->required(),
// Forms\Components\TextInput::make('frequency')
// ->label('Frequency')
// ->required()
// ->numeric()
// ->default(1),
// Forms\Components\DateTimePicker::make('next_calibration_date')
// ->label('Next Calibration Date')
// ->required(),
Forms\Components\DateTimePicker::make('calibrated_on')
->label('Calibrated On')
->required()
->reactive()
->afterStateUpdated(function ($state, callable $set, callable $get) {
$frequency = $get('frequency') ?? '1';
$nextDate = self::calculateNextCalibrationDate($state, $frequency);
$set('next_calibration_date', $nextDate);
}),
// ->afterStateUpdated(function ($state, callable $get, callable $set) {
// $frequency = (int) $get('frequency');
// if ($state && $frequency != 0) {
// $calibratedOn = $state instanceof Carbon ? $state : Carbon::parse($state);
// $nextDate = $calibratedOn->copy()->addDays($frequency);
// $set('next_calibration_date', $nextDate);
// } else {
// $set('next_calibration_date', null);
// }
// }),
Forms\Components\TextInput::make('frequency')
->label('Frequency (days)')
->required()
->numeric()
->minValue(1)
->default(1)
->reactive()
->afterStateUpdated(function ($state, callable $set, callable $get) {
$calibratedOn = $get('calibrated_on');
$nextDate = self::calculateNextCalibrationDate($calibratedOn, $state);
$set('next_calibration_date', $nextDate);
}),
// ->afterStateUpdated(function ($state, callable $get, callable $set) {
// $calibratedOn = $get('calibrated_on');
// $frequency = (int) $state;
// if ($calibratedOn && $frequency !== 0) {
// $calibratedOn = $calibratedOn instanceof Carbon ? $calibratedOn : Carbon::parse($calibratedOn);
// $nextDate = $calibratedOn->copy()->addDays($frequency);
// $set('next_calibration_date', $nextDate);
// }
// else
// {
// $set('next_calibration_date', null);
// }
// }),
Forms\Components\DateTimePicker::make('next_calibration_date')
->label('Next Calibration Date')
->readOnly()
->required(),
Forms\Components\TextInput::make('calibrated_by')
->label('Calibrated By'),
Forms\Components\Textarea::make('calibration_certificate')
->label('Calibration Certificate'),
Forms\Components\FileUpload::make('attachment')
->label('PDF Upload')
->acceptedFileTypes(['application/pdf'])
->storeFiles(false)
->disk('local')
->directory('uploads/temp')
->preserveFilenames()
->reactive(),
// Forms\Components\Actions::make([
// Action::make('uploadNow')
// ->label('Upload PDF Now')
// ->action(function ($get, callable $set) {
// $uploadedFiles = $get('attachment');
// if (is_array($uploadedFiles) && count($uploadedFiles) > 0) {
// $uploaded = reset($uploadedFiles);
// if ($uploaded instanceof TemporaryUploadedFile) {
// $originalName = $uploaded->getClientOriginalName();
// $storedPath = $uploaded->storeAs(
// 'uploads/temp',
// $originalName,
// 'local'
// );
// }
// }
// }),
// ]),
// Forms\Components\Actions::make([
// Action::make('downloadAttachment')
// ->label('Download PDF')
// ->action(function ($get) {
// $uploadedFiles = $get('attachment');
// $equipmentNumber = $get('equipment_number');
// if (!$equipmentNumber) {
// Notification::make()
// ->title('No equipment number entered')
// ->danger()
// ->send();
// return;
// }
// $files = Storage::disk('local')->files('uploads/temp');
// $fileToDownload = null;
// foreach ($files as $file) {
// if (str_contains($file, $equipmentNumber)) {
// $fileToDownload = $file;
// break;
// }
// }
// if (!$fileToDownload) {
// Notification::make()
// ->title('PDF not found for this equipment')
// ->danger()
// ->send();
// return;
// }
// return response()->download(Storage::disk('local')->path($fileToDownload));
// }),
// ]),
Forms\Components\Actions::make([
Action::make('uploadNow')
->label('Upload PDF Now')
// ->action(function ($get, callable $set) {
// $uploadedFiles = $get('attachment');
// if (is_array($uploadedFiles) && count($uploadedFiles) > 0) {
// $uploaded = reset($uploadedFiles);
// if ($uploaded instanceof TemporaryUploadedFile) {
// $originalName = $uploaded->getClientOriginalName();
// $storedPath = $uploaded->storeAs(
// 'uploads/temp',
// $originalName,
// 'local'
// );
// }
// }
// }),
->action(function ($get, callable $set) {
$uploadedFiles = $get('attachment');
if (is_array($uploadedFiles) && count($uploadedFiles) > 0) {
$uploaded = reset($uploadedFiles);
if ($uploaded instanceof TemporaryUploadedFile) {
$originalName = $uploaded->getClientOriginalName();
$storedPath = $uploaded->storeAs(
'uploads/temp',
$originalName,
'local'
);
Notification::make()
->title('PDF uploaded successfully')
->success()
->send();
return;
}
}
else
{
Notification::make()
->title('No file selected to upload')
->warning()
->send();
return;
}
}),
Action::make('downloadAttachment')
->label('Download PDF')
->action(function ($get) {
$equipmentNumber = $get('equipment_number');
if (!$equipmentNumber) {
Notification::make()
->title('No equipment number entered')
->danger()
->send();
return;
}
$files = Storage::disk('local')->files('uploads/temp');
$fileToDownload = null;
foreach ($files as $file) {
if (str_contains($file, $equipmentNumber)) {
$fileToDownload = $file;
break;
}
}
if (!$fileToDownload) {
Notification::make()
->title('PDF not found for this equipment')
->danger()
->send();
return;
}
return response()->download(Storage::disk('local')->path($fileToDownload));
}),
])
->columns(2),
Forms\Components\Hidden::make('created_by')
->label('Created By')
->default(Filament::auth()->user()?->name),
Forms\Components\Hidden::make('updated_by')
->label('Updated By'),
]);
}
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')
->alignCenter()
->sortable(),
Tables\Columns\TextColumn::make('machine.work_center')
->label('Work Center')
->alignCenter()
->sortable(),
Tables\Columns\TextColumn::make('name')
->label('Name')
->alignCenter()
->sortable(),
Tables\Columns\TextColumn::make('description')
->label('Description')
->alignCenter()
->sortable(),
Tables\Columns\TextColumn::make('make')
->label('Make')
->alignCenter()
->sortable(),
Tables\Columns\TextColumn::make('model')
->label('Model')
->alignCenter()
->sortable(),
Tables\Columns\TextColumn::make('equipment_number')
->label('Equipment Number')
->alignCenter()
->sortable(),
Tables\Columns\TextColumn::make('instrument_serial_number')
->label('Instrument Serial Number')
->alignCenter()
->sortable(),
Tables\Columns\TextColumn::make('calibrated_on')
->label('Calibrated On')
->alignCenter()
->dateTime()
->sortable(),
Tables\Columns\TextColumn::make('frequency')
->label('Frequency')
->alignCenter()
->sortable(),
Tables\Columns\TextColumn::make('next_calibration_date')
->label('Next Calibration Date')
->alignCenter()
->dateTime()
->sortable(),
Tables\Columns\TextColumn::make('calibrated_by')
->label('Calibrated By')
->alignCenter()
->sortable(),
Tables\Columns\TextColumn::make('calibration_certificate')
->label('Calibration Certificate')
->alignCenter()
->sortable(),
Tables\Columns\TextColumn::make('created_by')
->label('Created Bys')
->alignCenter()
->sortable(),
Tables\Columns\TextColumn::make('updated_by')
->label('Updated By')
->alignCenter()
->sortable(),
Tables\Columns\TextColumn::make('created_at')
->label('Created At')
->dateTime()
->alignCenter()
->sortable()
->toggleable(isToggledHiddenByDefault: true),
Tables\Columns\TextColumn::make('updated_at')
->label('Updated At')
->dateTime()
->alignCenter()
->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(EquipmentMasterImporter::class)
->visible(function() {
return Filament::auth()->user()->can('view import equipment master');
}),
ExportAction::make()
->exporter(EquipmentMasterExporter::class)
->visible(function() {
return Filament::auth()->user()->can('view export equipment master');
}),
]);
}
public static function getRelations(): array
{
return [
//
];
}
public static function getPages(): array
{
return [
'index' => Pages\ListEquipmentMasters::route('/'),
'create' => Pages\CreateEquipmentMaster::route('/create'),
'view' => Pages\ViewEquipmentMaster::route('/{record}'),
'edit' => Pages\EditEquipmentMaster::route('/{record}/edit'),
];
}
public static function getEloquentQuery(): Builder
{
return parent::getEloquentQuery()
->withoutGlobalScopes([
SoftDeletingScope::class,
]);
}
protected static function calculateNextCalibrationDate(?string $startDateTime, ?string $durationDays): ?string
{
if (!$startDateTime || !$durationDays) {
return null;
}
try
{
$startDateTimeCarbon = Carbon::parse($startDateTime);
$durationDays = str_replace(',', '.', $durationDays);
if(!is_numeric($durationDays))
{
return null;
}
$nextCalibrationDate = $startDateTimeCarbon->addDays(floatval($durationDays));
return $nextCalibrationDate->format('Y-m-d H:i:s');
}
catch (\Exception $e)
{
return null;
}
}
}

View File

@@ -1,17 +0,0 @@
<?php
namespace App\Filament\Resources\EquipmentMasterResource\Pages;
use App\Filament\Resources\EquipmentMasterResource;
use Filament\Actions;
use Filament\Resources\Pages\CreateRecord;
class CreateEquipmentMaster extends CreateRecord
{
protected static string $resource = EquipmentMasterResource::class;
protected function getRedirectUrl(): string
{
return $this->getResource()::getUrl('create');
}
}

View File

@@ -1,22 +0,0 @@
<?php
namespace App\Filament\Resources\EquipmentMasterResource\Pages;
use App\Filament\Resources\EquipmentMasterResource;
use Filament\Actions;
use Filament\Resources\Pages\EditRecord;
class EditEquipmentMaster extends EditRecord
{
protected static string $resource = EquipmentMasterResource::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\EquipmentMasterResource\Pages;
use App\Filament\Resources\EquipmentMasterResource;
use Filament\Actions;
use Filament\Resources\Pages\ListRecords;
class ListEquipmentMasters extends ListRecords
{
protected static string $resource = EquipmentMasterResource::class;
protected function getHeaderActions(): array
{
return [
Actions\CreateAction::make(),
];
}
}

View File

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

View File

@@ -1,339 +0,0 @@
<?php
namespace App\Filament\Resources;
use App\Filament\Exports\GrMasterExporter;
use App\Filament\Imports\GrMasterImporter;
use App\Filament\Resources\GrMasterResource\Pages;
use App\Filament\Resources\GrMasterResource\RelationManagers;
use App\Models\GrMaster;
use App\Models\Item;
use App\Models\Plant;
use Filament\Facades\Filament;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use Filament\Notifications\Notification;
use Filament\Forms\Components\Actions\Action;
use Storage;
use Smalot\PdfParser\Parser;
use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;
use Filament\Tables\Actions\ImportAction;
use Filament\Tables\Actions\ExportAction;
use Illuminate\Validation\Rule;
class GrMasterResource extends Resource
{
protected static ?string $model = GrMaster::class;
protected static ?string $navigationIcon = 'heroicon-o-rectangle-stack';
public static function form(Form $form): Form
{
return $form
->schema([
Forms\Components\Select::make('plant_id')
->label('Plant')
->reactive()
->relationship('plant', 'name')
->required(),
Forms\Components\Select::make('item_id')
->label('Item Code')
//->relationship('item', 'id')
->reactive()
->searchable()
->options(function (callable $get) {
$plantId = $get('plant_id');
if (empty($plantId)) {
return [];
}
return Item::where('plant_id', $plantId)->pluck('code', 'id');
})
->required(),
Forms\Components\TextInput::make('gr_number')
->label('GR Number')
->required(),
Forms\Components\TextInput::make('serial_number')
->label('Serial Number')
->rule(function (callable $get) {
return Rule::unique('gr_masters', 'serial_number')
->where('plant_id', $get('plant_id'))
->ignore($get('id')); // Ignore current record during updates
}),
Forms\Components\FileUpload::make('attachment')
->label('PDF Upload')
->acceptedFileTypes(['application/pdf'])
->storeFiles(false)
->disk('local')
->directory('uploads/temp')
->preserveFilenames()
->reactive(),
Forms\Components\Actions::make([
Action::make('uploadNow')
->label('Upload PDF Now')
->action(function ($get, callable $set) {
$uploadedFiles = $get('attachment');
if (is_array($uploadedFiles) && count($uploadedFiles) > 0)
{
$uploaded = reset($uploadedFiles);
if ($uploaded instanceof TemporaryUploadedFile) {
$grNumber = $get('gr_number');
$safeName = preg_replace('/[^A-Za-z0-9_\-]/', '_', $grNumber);
// $originalName = $uploaded->getClientOriginalName();
// $path = 'uploads/GRNumber/' . $originalName;
$finalFileName = $safeName . '.pdf';
$finalPath = 'uploads/GRNumber/' . $finalFileName;
if (Storage::disk('local')->exists($finalPath)) {
Notification::make()
->title('Duplicate File')
->body("The file '{$finalFileName}' already exists in uploads/GRNumber.")
->warning()
->send();
return; // Stop here
}
$storedPath = $uploaded->storeAs(
'uploads/GRNumber',
$finalFileName,
'local'
);
// $fullPath = storage_path('app/' . $storedPath);
$fullPath = storage_path('app/private/' . $storedPath);
$parser = new Parser();
//$pdf = $parser->parseContent(file_get_contents($uploaded->getRealPath()));
$pdf = $parser->parseFile($fullPath);
$text = $pdf->getText();
//dd($text);
if (preg_match('/Item code\s*:\s*(\S+)/i', $text, $matches)) {
$item1 = $matches[1];
}
else
{
Notification::make()
->title('Item Code Not Found')
->body('Could not find Item code in uploaded PDF.')
->warning()
->send();
return;
}
$processOrder = $get('gr_number');
$itemId = $get('item_id');
$plant = $get('plant_id');
$item = Item::find($itemId);
$plant = Plant::find($plant);
if ($item)
{
$itemCode = $item->code;
}
else
{
$itemCode = null;
Notification::make()
->title('Item Not Found')
->body("Item not found in uploaded pdf.")
->warning()
->send();
return;
}
$storedPath = $uploaded->storeAs(
'uploads/GRNumber',
$finalFileName,
'local'
);
if($itemCode == $item1)
{
Notification::make()
->title('Success')
->body("Gr Number '$processOrder' PDF uploaded successfully.")
->success()
->send();
return;
}
else
{
if (Storage::disk('local')->exists($storedPath)) {
Storage::disk('local')->delete($storedPath);
}
Notification::make()
->title('Item Code not matched')
->body("Item Code: {$item->code} not matched with the uploaded pdf code $item1.")
->danger()
->send();
return;
}
}
}
else
{
Notification::make()
->title('No file selected to upload')
->warning()
->send();
return;
}
}),
Action::make('downloadAttachment')
->label('Download PDF')
->action(function ($get) {
$equipmentNumber = $get('gr_number');
if (!$equipmentNumber) {
Notification::make()
->title('No GR Number entered')
->danger()
->send();
return;
}
$files = Storage::disk('local')->files('uploads/GRNumber');
$fileToDownload = null;
foreach ($files as $file) {
if (str_contains($file, $equipmentNumber)) {
$fileToDownload = $file;
break;
}
}
if (!$fileToDownload) {
Notification::make()
->title('PDF not found for this process order')
->danger()
->send();
return;
}
return response()->download(Storage::disk('local')->path($fileToDownload));
}),
]),
Forms\Components\Hidden::make('created_by')
->label('Created By')
->default(Filament::auth()->user()?->name),
Forms\Components\Hidden::make('updated_by')
->default(Filament::auth()->user()?->name),
]);
}
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')
->alignCenter()
->sortable(),
Tables\Columns\TextColumn::make('item.code')
->label('Item Code')
->alignCenter()
->sortable(),
Tables\Columns\TextColumn::make('gr_number')
->label('GR Number')
->alignCenter()
->sortable(),
Tables\Columns\TextColumn::make('serial_number')
->label('Serial Number')
->alignCenter()
->sortable(),
Tables\Columns\TextColumn::make('created_at')
->label('Created At')
->alignCenter()
->dateTime()
->sortable()
->toggleable(isToggledHiddenByDefault: true),
Tables\Columns\TextColumn::make('updated_at')
->label('Updated At')
->alignCenter()
->dateTime()
->sortable()
->toggleable(isToggledHiddenByDefault: true),
Tables\Columns\TextColumn::make('deleted_at')
->label('Deleted At')
->alignCenter()
->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(GrMasterImporter::class)
->visible(function() {
return Filament::auth()->user()->can('view import gr master');
}),
ExportAction::make()
->exporter(GrMasterExporter::class)
->visible(function() {
return Filament::auth()->user()->can('view export gr master');
}),
]);
}
public static function getRelations(): array
{
return [
//
];
}
public static function getPages(): array
{
return [
'index' => Pages\ListGrMasters::route('/'),
'create' => Pages\CreateGrMaster::route('/create'),
'view' => Pages\ViewGrMaster::route('/{record}'),
'edit' => Pages\EditGrMaster::route('/{record}/edit'),
];
}
public static function getEloquentQuery(): Builder
{
return parent::getEloquentQuery()
->withoutGlobalScopes([
SoftDeletingScope::class,
]);
}
}

View File

@@ -1,12 +0,0 @@
<?php
namespace App\Filament\Resources\GrMasterResource\Pages;
use App\Filament\Resources\GrMasterResource;
use Filament\Actions;
use Filament\Resources\Pages\CreateRecord;
class CreateGrMaster extends CreateRecord
{
protected static string $resource = GrMasterResource::class;
}

View File

@@ -1,22 +0,0 @@
<?php
namespace App\Filament\Resources\GrMasterResource\Pages;
use App\Filament\Resources\GrMasterResource;
use Filament\Actions;
use Filament\Resources\Pages\EditRecord;
class EditGrMaster extends EditRecord
{
protected static string $resource = GrMasterResource::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\GrMasterResource\Pages;
use App\Filament\Resources\GrMasterResource;
use Filament\Actions;
use Filament\Resources\Pages\ListRecords;
class ListGrMasters extends ListRecords
{
protected static string $resource = GrMasterResource::class;
protected function getHeaderActions(): array
{
return [
Actions\CreateAction::make(),
];
}
}

View File

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

View File

@@ -28,7 +28,7 @@ class GuardNameResource extends Resource
protected static ?string $navigationGroup = 'Master Entries';
protected static ?int $navigationSort = 14;
protected static ?int $navigationSort = 13;
public static function form(Form $form): Form
{

View File

@@ -481,6 +481,7 @@ class InvoiceValidationResource extends Resource
$duplicateSerialCodes = array_unique($duplicateSerials);
if (!empty($uniqueInvalidCodes)) {
Notification::make()
->title('Invalid Item Codes')
@@ -538,17 +539,17 @@ class InvoiceValidationResource extends Resource
return;
}
$uniqueCodes = array_unique($materialCodes);
$uniqueCodes = array_unique($materialCodes);
$matchedItems = StickerMaster::with('item')
->whereHas('item', function ($query) use ($uniqueCodes) {
$query->whereIn('code', $uniqueCodes);
})
->get();
$matchedItems = StickerMaster::with('item')
->whereHas('item', function ($query) use ($uniqueCodes) {
$query->whereIn('code', $uniqueCodes);
})
->get();
$matchedCodes = $matchedItems->pluck('item.code')->toArray();
$matchedCodes = $matchedItems->pluck('item.code')->toArray();
$missingCodes = array_diff($uniqueCodes, $matchedCodes);
$missingCodes = array_diff($uniqueCodes, $matchedCodes);
if (!empty($missingCodes))
{
@@ -614,6 +615,7 @@ class InvoiceValidationResource extends Resource
->visible(function() {
return Filament::auth()->user()->can('view import serial invoice');
}),
Tables\Actions\Action::make('Import Invoice Material')
->label('Import Material Invoice')
->form([

View File

@@ -61,11 +61,6 @@ class CreateInvoiceValidation extends CreateRecord
];
}
protected function getRedirectUrl(): string
{
return $this->getResource()::getUrl('create');
}
public function processInvoice($invoiceNumber)
{
$invoiceNumber = trim($invoiceNumber);
@@ -111,7 +106,6 @@ class CreateInvoiceValidation extends CreateRecord
->info()
->seconds(1)
->send();
$this->dispatch('playNotificationSound');
$this->form->fill([
'plant_id' => $plantId,
@@ -147,7 +141,6 @@ class CreateInvoiceValidation extends CreateRecord
->warning()
->seconds(2)
->send();
$this->dispatch('playNotificationSound');
$filename = $invoiceNumber . '.xlsx';
$directory = 'uploads/temp';
@@ -167,7 +160,6 @@ class CreateInvoiceValidation extends CreateRecord
->info()
->seconds(1)
->send();
$this->dispatch('playNotificationSound');
// $hasRecords = InvoiceValidation::where('invoice_number', $invoiceNumber)->where('plant_id', $plantId)->first()->stickerMasterRelation->material_type ?? null;
// $this->dispatch( (!empty($hasRecords) && $hasRecords) ? 'refreshMaterialInvoiceData' : 'refreshInvoiceData', invoiceNumber: $invoiceNumber, plantId: $plantId); //$this->invoiceNumber
$this->dispatch('refreshMaterialInvoiceData', invoiceNumber: $invoiceNumber, plantId: $plantId);
@@ -194,7 +186,6 @@ class CreateInvoiceValidation extends CreateRecord
->danger()
->seconds(2)
->send();
$this->dispatch('playWarnSound');
if ($disk->exists($filePath)) {
$disk->delete($filePath);
@@ -258,7 +249,6 @@ class CreateInvoiceValidation extends CreateRecord
->body('Uploaded Excel sheet is empty or<br>contains no valid data.')
->seconds(2)
->send();
$this->dispatch('playWarnSound');
if ($disk->exists($filePath)) {
$disk->delete($filePath);
}
@@ -274,7 +264,6 @@ class CreateInvoiceValidation extends CreateRecord
->danger()
->seconds(2)
->send();
$this->dispatch('playWarnSound');
if ($disk->exists($filePath)) {
$disk->delete($filePath);
@@ -291,7 +280,6 @@ class CreateInvoiceValidation extends CreateRecord
->danger()
->seconds(2)
->send();
$this->dispatch('playWarnSound');
if ($disk->exists($filePath)) {
$disk->delete($filePath);
@@ -308,7 +296,6 @@ class CreateInvoiceValidation extends CreateRecord
->danger()
->seconds(2)
->send();
$this->dispatch('playWarnSound');
if ($disk->exists($filePath)) {
$disk->delete($filePath);
@@ -341,7 +328,6 @@ class CreateInvoiceValidation extends CreateRecord
->danger()
->seconds(2)
->send();
$this->dispatch('playWarnSound');
if ($disk->exists($filePath)) {
$disk->delete($filePath);
@@ -372,7 +358,6 @@ class CreateInvoiceValidation extends CreateRecord
->danger()
->seconds(2)
->send();
$this->dispatch('playWarnSound');
if ($disk->exists($filePath)) {
$disk->delete($filePath);
@@ -398,7 +383,6 @@ class CreateInvoiceValidation extends CreateRecord
->danger()
->seconds(2)
->send();
$this->dispatch('playWarnSound');
if ($disk->exists($filePath)) {
$disk->delete($filePath);
@@ -464,7 +448,6 @@ class CreateInvoiceValidation extends CreateRecord
->danger()
->seconds(2)
->send();
$this->dispatch('playWarnSound');
};
$showValidationNotification($nonNumericQtyCodes, "The following item codes contains invalid bundle quantity:");
@@ -710,7 +693,6 @@ class CreateInvoiceValidation extends CreateRecord
->success()
->seconds(1)
->send();
Notification::make()
->title("Start the scanning process!")
->body("'$inserted' new material invoice records were inserted.")
@@ -718,7 +700,6 @@ class CreateInvoiceValidation extends CreateRecord
// ->success()
->seconds(1)
->send();
$this->dispatch('playNotificationSound');
// Update total quantity in the form
$totalQuantity = InvoiceValidation::where('invoice_number', $invoiceNumber)->where('plant_id', $plantId)->count();
@@ -756,7 +737,6 @@ class CreateInvoiceValidation extends CreateRecord
->danger()
->seconds(2)
->send();
$this->dispatch('playWarnSound');
$totalQuantity = InvoiceValidation::where('invoice_number', $invoiceNumber)->where('plant_id', $plantId)->count();
$scannedQuantity = InvoiceValidation::where('invoice_number', $invoiceNumber)->whereNotNull('serial_number')->where('serial_number', '!=', '')->where('plant_id', $plantId)->count();
@@ -786,7 +766,6 @@ class CreateInvoiceValidation extends CreateRecord
->seconds(2)
->send();
$this->dispatch('playWarnSound');
$this->form->fill([
'plant_id' => $plantId,
'invoice_number' => $invoiceNumber,
@@ -821,7 +800,6 @@ class CreateInvoiceValidation extends CreateRecord
->warning()
->seconds(2)
->send();
$this->dispatch('playNotificationSound');
$filename = $invoiceNumber . '.xlsx';
$directory = 'uploads/temp';
@@ -832,7 +810,6 @@ class CreateInvoiceValidation extends CreateRecord
//$fullPath = $disk->path($filePath);
$disk->delete($filePath);
}
$this->dispatch('playNotificationSound');
$this->dispatch('refreshCompletedInvoice', invoiceNumber: $invoiceNumber, plantId: $plantId, isSerial: true);
}
else
@@ -842,7 +819,6 @@ class CreateInvoiceValidation extends CreateRecord
->info()
->seconds(1)
->send();
$this->dispatch('playNotificationSound');
$this->dispatch('refreshInvoiceData', invoiceNumber: $invoiceNumber, plantId: $plantId);
if($updateStatus == '1')
@@ -870,7 +846,6 @@ class CreateInvoiceValidation extends CreateRecord
->danger()
->seconds(2)
->send();
$this->dispatch('playWarnSound');
if ($disk->exists($filePath)) {
$disk->delete($filePath);
@@ -942,7 +917,6 @@ class CreateInvoiceValidation extends CreateRecord
->body('Uploaded excel sheet is empty or<br>contains no valid data.')
->seconds(2)
->send();
$this->dispatch('playWarnSound');
if ($disk->exists($filePath)) {
$disk->delete($filePath);
@@ -960,8 +934,6 @@ class CreateInvoiceValidation extends CreateRecord
->seconds(2)
->send();
$this->dispatch('playWarnSound');
if ($disk->exists($filePath)) {
$disk->delete($filePath);
}
@@ -994,8 +966,6 @@ class CreateInvoiceValidation extends CreateRecord
->seconds(2)
->send();
$this->dispatch('playWarnSound');
if ($disk->exists($filePath)) {
$disk->delete($filePath);
}
@@ -1025,7 +995,6 @@ class CreateInvoiceValidation extends CreateRecord
->danger()
->seconds(2)
->send();
$this->dispatch('playWarnSound');
if ($disk->exists($filePath)) {
$disk->delete($filePath);
@@ -1050,7 +1019,6 @@ class CreateInvoiceValidation extends CreateRecord
->danger()
->seconds(2)
->send();
$this->dispatch('playWarnSound');
if ($disk->exists($filePath)) {
$disk->delete($filePath);
@@ -1059,7 +1027,7 @@ class CreateInvoiceValidation extends CreateRecord
}
$missPackCodes = $matchedItems
->filter(fn ($sticker) => empty($sticker->tube_sticker_motor) && empty($sticker->pack_slip_motor) && empty($sticker->tube_sticker_pump) && empty($sticker->pack_slip_pump) && empty($sticker->tube_sticker_pumpset) && empty($sticker->pack_slip_pumpset) && empty($sticker->panel_box_code)) //filter invalid
->filter(fn ($sticker) => empty($sticker->tube_sticker_motor) && empty($sticker->tube_sticker_pump) && empty($sticker->tube_sticker_pumpset) && empty($sticker->panel_box_code)) //filter invalid
->pluck('item.code')
->toArray();
@@ -1075,7 +1043,6 @@ class CreateInvoiceValidation extends CreateRecord
->danger()
->seconds(2)
->send();
$this->dispatch('playWarnSound');
if ($disk->exists($filePath)) {
$disk->delete($filePath);
@@ -1093,8 +1060,6 @@ class CreateInvoiceValidation extends CreateRecord
->seconds(2)
->send();
$this->dispatch('playWarnSound');
if ($disk->exists($filePath)) {
$disk->delete($filePath);
}
@@ -1110,7 +1075,6 @@ class CreateInvoiceValidation extends CreateRecord
->danger()
->seconds(2)
->send();
$this->dispatch('playWarnSound');
if ($disk->exists($filePath)) {
$disk->delete($filePath);
@@ -1128,8 +1092,6 @@ class CreateInvoiceValidation extends CreateRecord
->seconds(2)
->send();
$this->dispatch('playWarnSound');
if ($disk->exists($filePath)) {
$disk->delete($filePath);
}
@@ -1209,8 +1171,6 @@ class CreateInvoiceValidation extends CreateRecord
->seconds(1)
->send();
$this->dispatch('playNotificationSound');
// Update total quantity in the form
$totalQuantity = InvoiceValidation::where('invoice_number', $invoiceNumber)->where('plant_id', $plantId)->count();
$scannedQuantity = InvoiceValidation::where('invoice_number', $invoiceNumber)->where('scanned_status', 'Scanned')->where('plant_id', $plantId)->count();
@@ -1248,7 +1208,6 @@ class CreateInvoiceValidation extends CreateRecord
->danger()
->seconds(2)
->send();
$this->dispatch('playWarnSound');
$totalQuantity = InvoiceValidation::where('invoice_number', $invoiceNumber)->where('plant_id', $plantId)->count();
$scannedQuantity = InvoiceValidation::where('invoice_number', $invoiceNumber)->where('scanned_status', 'Scanned')->where('plant_id', $plantId)->count();
@@ -1277,8 +1236,6 @@ class CreateInvoiceValidation extends CreateRecord
->seconds(2)
->send();
$this->dispatch('playWarnSound');
$this->form->fill([
'plant_id' => $plantId,
'invoice_number' => $invoiceNumber,
@@ -1317,7 +1274,7 @@ class CreateInvoiceValidation extends CreateRecord
->danger()
->seconds(2)
->send();
$this->dispatch('playWarnSound');
$this->form->fill([
'plant_id' => $plantId,
'invoice_number' => $invoiceNumber,
@@ -1336,9 +1293,7 @@ class CreateInvoiceValidation extends CreateRecord
->danger()
->seconds(2)
->send();
$this->dispatch('playWarnSound');
return;
}
// Extract filename without extension (e.g., "3RA0018732")
@@ -1351,7 +1306,6 @@ class CreateInvoiceValidation extends CreateRecord
->danger()
->seconds(2)
->send();
$this->dispatch('playWarnSound');
return;
}
@@ -1381,8 +1335,6 @@ class CreateInvoiceValidation extends CreateRecord
->seconds(2)
->send();
$this->dispatch('playWarnSound');
if ($disk->exists($filePath)) {
$disk->delete($filePath);
}
@@ -1487,7 +1439,6 @@ class CreateInvoiceValidation extends CreateRecord
->body('Uploaded Excel sheet is empty or<br>contains no valid data.')
->seconds(2)
->send();
$this->dispatch('playWarnSound');
if ($disk->exists($filePath)) {
$disk->delete($filePath);
}
@@ -1503,7 +1454,6 @@ class CreateInvoiceValidation extends CreateRecord
->danger()
->seconds(2)
->send();
$this->dispatch('playWarnSound');
if ($disk->exists($filePath)) {
$disk->delete($filePath);
@@ -1520,7 +1470,6 @@ class CreateInvoiceValidation extends CreateRecord
->danger()
->seconds(2)
->send();
$this->dispatch('playWarnSound');
if ($disk->exists($filePath)) {
$disk->delete($filePath);
@@ -1538,8 +1487,6 @@ class CreateInvoiceValidation extends CreateRecord
->seconds(2)
->send();
$this->dispatch('playWarnSound');
if ($disk->exists($filePath)) {
$disk->delete($filePath);
}
@@ -1571,7 +1518,6 @@ class CreateInvoiceValidation extends CreateRecord
->danger()
->seconds(2)
->send();
$this->dispatch('playWarnSound');
if ($disk->exists($filePath)) {
$disk->delete($filePath);
@@ -1602,7 +1548,7 @@ class CreateInvoiceValidation extends CreateRecord
->danger()
->seconds(2)
->send();
$this->dispatch('playWarnSound');
if ($disk->exists($filePath)) {
$disk->delete($filePath);
}
@@ -1626,7 +1572,6 @@ class CreateInvoiceValidation extends CreateRecord
->danger()
->seconds(2)
->send();
$this->dispatch('playWarnSound');
if ($disk->exists($filePath)) {
$disk->delete($filePath);
@@ -1686,7 +1631,6 @@ class CreateInvoiceValidation extends CreateRecord
->danger()
->seconds(2)
->send();
$this->dispatch('playWarnSound');
};
$showValidationNotification($nonNumericQtyCodes, "The following item codes contains invalid bundle quantity:");
@@ -1939,7 +1883,6 @@ class CreateInvoiceValidation extends CreateRecord
->body('Uploaded excel sheet is empty or<br>contains no valid data.')
->seconds(2)
->send();
$this->dispatch('playWarnSound');
if ($disk->exists($filePath)) {
$disk->delete($filePath);
@@ -1956,7 +1899,6 @@ class CreateInvoiceValidation extends CreateRecord
->danger()
->seconds(2)
->send();
$this->dispatch('playWarnSound');
if ($disk->exists($filePath)) {
$disk->delete($filePath);
@@ -1999,7 +1941,6 @@ class CreateInvoiceValidation extends CreateRecord
->danger()
->seconds(2)
->send();
$this->dispatch('playWarnSound');
if ($disk->exists($filePath)) {
$disk->delete($filePath);
@@ -2030,7 +1971,6 @@ class CreateInvoiceValidation extends CreateRecord
->danger()
->seconds(2)
->send();
$this->dispatch('playWarnSound');
if ($disk->exists($filePath)) {
$disk->delete($filePath);
@@ -2055,7 +1995,6 @@ class CreateInvoiceValidation extends CreateRecord
->danger()
->seconds(2)
->send();
$this->dispatch('playWarnSound');
if ($disk->exists($filePath)) {
$disk->delete($filePath);
@@ -2064,7 +2003,7 @@ class CreateInvoiceValidation extends CreateRecord
}
$missPackCodes = $matchedItems
->filter(fn ($sticker) => empty($sticker->tube_sticker_motor) && empty($sticker->pack_slip_motor) && empty($sticker->tube_sticker_pump) && empty($sticker->pack_slip_pump) && empty($sticker->tube_sticker_pumpset) && empty($sticker->pack_slip_pumpset) && empty($sticker->panel_box_code))
->filter(fn ($sticker) => empty($sticker->tube_sticker_motor) && empty($sticker->tube_sticker_pump) && empty($sticker->tube_sticker_pumpset) && empty($sticker->panel_box_code))
->pluck('item.code')
->toArray();
@@ -2080,7 +2019,6 @@ class CreateInvoiceValidation extends CreateRecord
->danger()
->seconds(2)
->send();
$this->dispatch('playWarnSound');
if ($disk->exists($filePath)) {
$disk->delete($filePath);
@@ -2097,7 +2035,6 @@ class CreateInvoiceValidation extends CreateRecord
->danger()
->seconds(2)
->send();
$this->dispatch('playWarnSound');
if ($disk->exists($filePath)) {
$disk->delete($filePath);
@@ -2114,7 +2051,6 @@ class CreateInvoiceValidation extends CreateRecord
->danger()
->seconds(2)
->send();
$this->dispatch('playWarnSound');
if ($disk->exists($filePath)) {
$disk->delete($filePath);
@@ -2131,7 +2067,6 @@ class CreateInvoiceValidation extends CreateRecord
->danger()
->seconds(2)
->send();
$this->dispatch('playWarnSound');
if ($disk->exists($filePath)) {
$disk->delete($filePath);
@@ -2149,7 +2084,6 @@ class CreateInvoiceValidation extends CreateRecord
->danger()
->seconds(2)
->send();
$this->dispatch('playWarnSound');
if ($disk->exists($filePath)) {
$disk->delete($filePath);
@@ -2194,7 +2128,6 @@ class CreateInvoiceValidation extends CreateRecord
// ->success()
->seconds(1)
->send();
$this->dispatch('playNotificationSound');
// Update total quantity in the form
$totalQuantity = InvoiceValidation::where('invoice_number', $invoiceNumber)->where('plant_id', $plantId)->count();
@@ -2233,7 +2166,6 @@ class CreateInvoiceValidation extends CreateRecord
->danger()
->seconds(2)
->send();
$this->dispatch('playWarnSound');
$totalQuantity = InvoiceValidation::where('invoice_number', $invoiceNumber)->where('plant_id', $plantId)->count();
$scannedQuantity = InvoiceValidation::where('invoice_number', $invoiceNumber)->where('scanned_status', 'Scanned')->where('plant_id', $plantId)->count();
@@ -2261,7 +2193,6 @@ class CreateInvoiceValidation extends CreateRecord
->danger()
->seconds(2)
->send();
$this->dispatch('playWarnSound');
if ($disk->exists($filePath)) {
$disk->delete($filePath);
@@ -2325,7 +2256,6 @@ class CreateInvoiceValidation extends CreateRecord
->danger()
->seconds(2)
->send();
$this->dispatch('playWarnSound');
$this->form->fill([
'plant_id' => $plantId,
@@ -2350,7 +2280,6 @@ class CreateInvoiceValidation extends CreateRecord
->warning()
->seconds(2)
->send();
$this->dispatch('playNotificationSound');
$this->form->fill([
'plant_id' => $plantId,
@@ -2410,7 +2339,6 @@ class CreateInvoiceValidation extends CreateRecord
->body('Scan valid Material QR code proceed!<br>Sample formats are:<br>123456|12345|12345678|1/1 (or)<br>123456|12345|12345678|1 (or)<br>123456|12345678-1')
->seconds(2)
->send();
$this->dispatch('playWarnSound');
$this->form->fill([
'plant_id' => $plantId,
@@ -2430,7 +2358,6 @@ class CreateInvoiceValidation extends CreateRecord
->body('Scan valid Material QR code proceed!<br>Sample formats are:<br>123456|12345|12345678|1/1 (or)<br>123456|12345|12345678|1 (or)<br>123456|12345678-1')
->seconds(2)
->send();
$this->dispatch('playWarnSound');
$this->form->fill([
'plant_id' => $plantId,
@@ -2450,7 +2377,6 @@ class CreateInvoiceValidation extends CreateRecord
->body('Scan valid Material QR code proceed!<br>Sample formats are:<br>123456|12345|12345678|1/1 (or)<br>123456|12345|12345678|1 (or)<br>123456|12345678-1')
->seconds(2)
->send();
$this->dispatch('playWarnSound');
$this->form->fill([
'plant_id' => $plantId,
@@ -2477,7 +2403,6 @@ class CreateInvoiceValidation extends CreateRecord
->body('Scan valid Material QR code proceed!<br>Sample formats are:<br>123456|12345|12345678|1/1 (or)<br>123456|12345|12345678|1 (or)<br>123456|12345678-1')
->seconds(2)
->send();
$this->dispatch('playWarnSound');
$this->form->fill([
'plant_id' => $plantId,
@@ -2497,7 +2422,6 @@ class CreateInvoiceValidation extends CreateRecord
->body('Scan valid Material QR code proceed!<br>Sample formats are:<br>123456|12345|12345678|1/1 (or)<br>123456|12345|12345678|1 (or)<br>123456|12345678-1')
->seconds(2)
->send();
$this->dispatch('playWarnSound');
$this->form->fill([
'plant_id' => $plantId,
@@ -2524,7 +2448,6 @@ class CreateInvoiceValidation extends CreateRecord
->body('Scan valid Material QR code proceed!<br>Sample formats are:<br>123456|12345|12345678|1/1 (or)<br>123456|12345|12345678|1 (or)<br>123456|12345678-1')
->seconds(2)
->send();
$this->dispatch('playWarnSound');
$this->form->fill([
'plant_id' => $plantId,
@@ -2544,7 +2467,6 @@ class CreateInvoiceValidation extends CreateRecord
->body('Scan valid Material QR code proceed!<br>Sample formats are:<br>123456|12345|12345678|1/1 (or)<br>123456|12345|12345678|1 (or)<br>123456|12345678-1')
->seconds(2)
->send();
$this->dispatch('playWarnSound');
$this->form->fill([
'plant_id' => $plantId,
@@ -2570,8 +2492,6 @@ class CreateInvoiceValidation extends CreateRecord
->seconds(1)
->send();
$this->dispatch('playWarnSound');
$this->form->fill([
'plant_id' => $plantId,
'invoice_number' => $invoiceNumber,
@@ -2595,7 +2515,6 @@ class CreateInvoiceValidation extends CreateRecord
->danger()
->seconds(2)
->send();
$this->dispatch('playWarnSound');
$this->form->fill([
'plant_id' => $plantId,
@@ -2619,7 +2538,6 @@ class CreateInvoiceValidation extends CreateRecord
->danger()
->seconds(2)
->send();
$this->dispatch('playWarnSound');
$this->form->fill([
'plant_id' => $plantId,
@@ -2642,7 +2560,6 @@ class CreateInvoiceValidation extends CreateRecord
->danger()
->seconds(2)
->send();
$this->dispatch('playWarnSound');
$this->form->fill([
'plant_id' => $plantId,
@@ -2670,7 +2587,7 @@ class CreateInvoiceValidation extends CreateRecord
->danger()
->seconds(2)
->send();
$this->dispatch('playWarnSound');
$this->form->fill([
'plant_id' => $plantId,
'invoice_number' => $invoiceNumber,
@@ -2696,7 +2613,6 @@ class CreateInvoiceValidation extends CreateRecord
->danger()
->seconds(2)
->send();
$this->dispatch('playWarnSound');
$this->form->fill([
'plant_id' => $plantId,
@@ -2718,7 +2634,6 @@ class CreateInvoiceValidation extends CreateRecord
->danger()
->seconds(2)
->send();
$this->dispatch('playWarnSound');
$this->form->fill([
'plant_id' => $plantId,
@@ -2741,7 +2656,6 @@ class CreateInvoiceValidation extends CreateRecord
->body('Scan valid Quantity Material QR code proceed!<br>Ex:123456|12345|12345678|1/1')
->seconds(2)
->send();
$this->dispatch('playWarnSound');
$this->form->fill([
'plant_id' => $plantId,
@@ -2803,7 +2717,6 @@ class CreateInvoiceValidation extends CreateRecord
->danger()
->seconds(2)
->send();
$this->dispatch('playWarnSound');
$this->form->fill([
'plant_id' => $plantId,
@@ -2833,8 +2746,6 @@ class CreateInvoiceValidation extends CreateRecord
->seconds(2)
->send();
$this->dispatch('playWarnSound');
$this->form->fill([
'plant_id' => $plantId,
'invoice_number' => $invoiceNumber,
@@ -2874,8 +2785,6 @@ class CreateInvoiceValidation extends CreateRecord
->seconds(2)
->send();
$this->dispatch('playNotificationSound');
$this->form->fill([
'plant_id' => $plantId,
'invoice_number' => $invoiceNumber,
@@ -2921,8 +2830,6 @@ class CreateInvoiceValidation extends CreateRecord
->seconds(2)
->send();
$this->dispatch('playNotificationSound');
$this->form->fill([
'plant_id' => $plantId,
'invoice_number' => $invoiceNumber,
@@ -2966,8 +2873,6 @@ class CreateInvoiceValidation extends CreateRecord
->seconds(2)
->send();
$this->dispatch('playWarnSound');
$this->form->fill([
'plant_id' => $plantId,
'invoice_number' => $invoiceNumber,
@@ -3001,14 +2906,12 @@ class CreateInvoiceValidation extends CreateRecord
if (!$record) {
Notification::make()
->title('<b><span style="color:red;">Serial Number Not Found<br>Serial \''.$serialNumber.'\' not found in database for choosed plant.</span></b>')
// ->body("Serial '$serialNumber' not found in database for choosed plant.")..........
->title('Serial Number Not Found')
->body("Serial '$serialNumber' not found in database for choosed plant.")
->danger()
->seconds(2)
->send();
$this->dispatch('play-warn-sound');
$this->form->fill([
'plant_id' => $plantId,
'invoice_number' => $invoiceNumber,
@@ -3025,14 +2928,12 @@ class CreateInvoiceValidation extends CreateRecord
if (!$record) {
Notification::make()
->title('<b><span style="color:red;">Unknown: Serial Number<br>Serial \''.$serialNumber.'\' not found in invoice.</span></b>')
// ->body("Serial '$serialNumber' not found in invoice.")
->title('Unknown: Serial Number')
->body("Serial '$serialNumber' not found in invoice.")
->danger()
->seconds(2)
->send();
$this->dispatch('playWarnSound');
$this->form->fill([
'plant_id' => $plantId,
'invoice_number' => $invoiceNumber,
@@ -3059,8 +2960,6 @@ class CreateInvoiceValidation extends CreateRecord
->seconds(2)
->send();
$this->dispatch('playWarnSound');
$this->form->fill([
'plant_id' => $plantId,
'invoice_number' => $invoiceNumber,
@@ -3077,13 +2976,6 @@ class CreateInvoiceValidation extends CreateRecord
$hasPumpSetQr = $record->stickerMasterRelation->tube_sticker_pumpset ?? null;
$hasCapacitorQr = $record->stickerMasterRelation->panel_box_code ?? null;
if (!$hasMotorQr && !$hasPumpQr && !$hasPumpSetQr && !$hasCapacitorQr)
{
$hasMotorQr = $record->stickerMasterRelation->pack_slip_motor ?? null;
$hasPumpQr = $record->stickerMasterRelation->pack_slip_pump ?? null;
$hasPumpSetQr = $record->stickerMasterRelation->pack_slip_pumpset ?? null;
}
$hadMotorQr = $record->motor_scanned_status ?? null;
$hadPumpQr = $record->pump_scanned_status ?? null;
$hadPumpSetQr = $record->scanned_status_set ?? null;
@@ -3092,23 +2984,21 @@ class CreateInvoiceValidation extends CreateRecord
if (!$hasMotorQr && !$hasPumpQr && !$hasPumpSetQr && !$hasCapacitorQr)
{
Notification::make()
->title('Invalid: Item Code')
->body("Scanned 'Item Code' doesn't have valid package type to proceed!")
->danger()
->seconds(2)
->send();
->title('Invalid: Item Code')
->body("Scanned 'Item Code' doesn't have valid package type to proceed!")
->danger()
->seconds(2)
->send();
$this->dispatch('playWarnSound');
$this->form->fill([
'plant_id' => $plantId,
'invoice_number' => $invoiceNumber,
'serial_number' => null,
'total_quantity' => $totQuan,
'update_invoice' => false,
'scanned_quantity'=> $scanSQuan,
]);
return;
$this->form->fill([
'plant_id' => $plantId,
'invoice_number' => $invoiceNumber,
'serial_number' => null,
'total_quantity' => $totQuan,
'update_invoice' => false,
'scanned_quantity'=> $scanSQuan,
]);
return;
}
if ($isMarkM) {
@@ -3120,8 +3010,6 @@ class CreateInvoiceValidation extends CreateRecord
->danger()
->seconds(2)
->send();
$this->dispatch('playWarnSound');
$this->form->fill([
'plant_id' => $plantId,
@@ -3142,8 +3030,6 @@ class CreateInvoiceValidation extends CreateRecord
->seconds(2)
->send();
$this->dispatch('playWarnSound');
$this->form->fill([
'plant_id' => $plantId,
'invoice_number' => $invoiceNumber,
@@ -3206,8 +3092,6 @@ class CreateInvoiceValidation extends CreateRecord
->success()
->seconds(2)
->send();
$this->dispatch('playNotificationSound');
$filename = $invoiceNumber . '.xlsx';
$directory = 'uploads/temp';
@@ -3237,8 +3121,6 @@ class CreateInvoiceValidation extends CreateRecord
->seconds(2)
->send();
$this->dispatch('playWarnSound');
$this->form->fill([
'plant_id' => $plantId,
'invoice_number' => $invoiceNumber,
@@ -3257,7 +3139,6 @@ class CreateInvoiceValidation extends CreateRecord
->danger()
->seconds(2)
->send();
$this->dispatch('playWarnSound');
$this->form->fill([
'plant_id' => $plantId,
@@ -3322,8 +3203,6 @@ class CreateInvoiceValidation extends CreateRecord
->seconds(2)
->send();
$this->dispatch('playNotificationSound');
$filename = $invoiceNumber . '.xlsx';
$directory = 'uploads/temp';
$disk = Storage::disk('local');
@@ -3354,8 +3233,6 @@ class CreateInvoiceValidation extends CreateRecord
->seconds(2)
->send();
$this->dispatch('playWarnSound');
$this->form->fill([
'plant_id' => $plantId,
'invoice_number' => $invoiceNumber,
@@ -3375,8 +3252,6 @@ class CreateInvoiceValidation extends CreateRecord
->seconds(2)
->send();
$this->dispatch('playWarnSound');
$this->form->fill([
'plant_id' => $plantId,
'invoice_number' => $invoiceNumber,
@@ -3417,8 +3292,6 @@ class CreateInvoiceValidation extends CreateRecord
->seconds(2)
->send();
$this->dispatch('playWarnSound');
$this->form->fill([
'plant_id' => $plantId,
'invoice_number' => $invoiceNumber,
@@ -3438,8 +3311,6 @@ class CreateInvoiceValidation extends CreateRecord
->seconds(2)
->send();
$this->dispatch('playWarnSound');
$this->form->fill([
'plant_id' => $plantId,
'invoice_number' => $invoiceNumber,
@@ -3503,8 +3374,6 @@ class CreateInvoiceValidation extends CreateRecord
->seconds(2)
->send();
$this->dispatch('playNotificationSound');
$filename = $invoiceNumber . '.xlsx';
$directory = 'uploads/temp';
$disk = Storage::disk('local');

View File

@@ -9,9 +9,4 @@ use Filament\Resources\Pages\CreateRecord;
class CreateItem extends CreateRecord
{
protected static string $resource = ItemResource::class;
protected function getRedirectUrl(): string
{
return $this->getResource()::getUrl('create');
}
}

View File

@@ -7,7 +7,6 @@ use App\Filament\Imports\LineImporter;
use App\Filament\Resources\LineResource\Pages;
use App\Filament\Resources\LineResource\RelationManagers;
use App\Models\Line;
use App\Models\WorkGroupMaster;
use Filament\Facades\Filament;
use Filament\Forms;
use Filament\Forms\Form;
@@ -176,770 +175,12 @@ class LineResource extends Resource
])
->hint(fn ($get) => $get('lTypeError') ? $get('lTypeError') : null)
->hintColor('danger'),
Forms\Components\TextInput::make('no_of_operation')
->label('No of Operation')
->required()
->numeric()
->reactive()
->minValue(0)
->maxValue(10)
->placeholder('Scan the valid No Of Operatrion')
->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
$partValidationColumns = [
'work_group1_id', 'work_group2_id', 'work_group3_id', 'work_group4_id',
'work_group5_id', 'work_group6_id', 'work_group7_id', 'work_group8_id',
'work_group9_id', 'work_group10_id',
];
foreach ($partValidationColumns as $column) {
$set($column . '_visible', false);
$set($column, null);
}
if (is_numeric($state) && $state > 0) {
for ($i = 1; $i <= (int) $state; $i++) {
$set("work_group{$i}_id_visible", true);
}
}
})
->afterStateHydrated(function (callable $set, $state) {
for ($i = 1; $i <= 10; $i++) {
$set("work_group{$i}_id_visible", $state >= $i);
}
}),
Forms\Components\Hidden::make('work_group1_id'),
Forms\Components\TextInput::make('work_group1_actual_id')
->label('Work Group Center 1')
->hidden(fn (callable $get) => !$get('work_group1_id_visible'))
->default('')
->reactive()
->required()
->afterStateHydrated(function (callable $set, $record) {
if ($record && $record->workGroup1) {
$set('work_group1_actual_id', $record->workGroup1->name);
}
})
->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
// $workGroup1Id = $get('work_group1_actual_id');
$plantId = $get('plant_id');
$lineName = $get('name');
if ($state == null || trim($state) == '') {
$set('work_group1_id_error', null);
$set('work_group1_id', null);
return;
}
$set('work_group1_id_error', null);
$set('work_group1_id', null);
if (!$plantId) {
$set('work_group1_id_error', 'Invalid plant name.');
return;
}
$workGroupRecord = WorkGroupMaster::where('plant_id', $plantId)
->where('name', $state)
->first();
if (!$workGroupRecord) {
$set('work_group1_id_error', 'Work group does not exist for this plant in master.');
return;
}
// $existsInLines = Line::where(function ($query) use ($workGroupRecord) {
// for ($i = 1; $i <= 10; $i++) {
// $query->orWhere("work_group{$i}_id", $workGroupRecord->id);
// }
// })->count();
$existsInLines = Line::where('plant_id', $plantId)
->where('name', '!=', $lineName) // Exclude current line
->where(function ($query) use ($workGroupRecord) {
for ($i = 1; $i <= 10; $i++) {
$query->orWhere("work_group{$i}_id", $workGroupRecord->id);
}
})
->count();
if ($existsInLines > 0) {
\Filament\Notifications\Notification::make()
->title('Work Group Already Assigned')
->body("The work group '{$state}' is already assigned to a line.")
->danger()
->send();
$set('work_group1_actual_id', '');
$set('work_group1_id', null);
return;
}
else
{
$set('work_group1_id_error', null);
$set('work_group1_id', $workGroupRecord->id);
}
})
->extraAttributes(fn ($get) => [
'class' => $get('work_group1_id_error') ? 'border-red-500' : '',
])
->hint(fn ($get) => $get('work_group1_id_error'))
->hintColor('danger'),
Forms\Components\Hidden::make('work_group2_id'),
Forms\Components\TextInput::make('work_group2_actual_id')
->label('Work Group Center 2')
->hidden(fn (callable $get) => !$get('work_group2_id_visible'))
->default('')
->required()
->reactive()
->afterStateHydrated(function (callable $set, $record) {
if ($record && $record->workGroup2) {
$set('work_group2_actual_id', $record->workGroup2->name);
}
})
->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
// $workGroup1Id = $get('work_group1_actual_id');
$plantId = $get('plant_id');
$lineName = $get('name');
if ($state == null || trim($state) == '') {
$set('work_group2_id_error', null);
$set('work_group2_id', null);
return;
}
$set('work_group2_id_error', null);
$set('work_group2_id', null);
if (!$plantId) {
$set('work_group2_id_error', 'Invalid plant name.');
return;
}
$workGroupRecord = WorkGroupMaster::where('plant_id', $plantId)
->where('name', $state)
->first();
if (!$workGroupRecord) {
$set('work_group2_id_error', 'Work group does not exist for this plant in master.');
return;
}
$existsInLines = Line::where('plant_id', $plantId)
->where('name', '!=', $lineName) // Exclude current line
->where(function ($query) use ($workGroupRecord) {
for ($i = 1; $i <= 10; $i++) {
$query->orWhere("work_group{$i}_id", $workGroupRecord->id);
}
})
->count();
if ($existsInLines > 0) {
\Filament\Notifications\Notification::make()
->title('Work Group Already Assigned')
->body("The work group '{$state}' is already assigned to a line.")
->danger()
->send();
$set('work_group2_actual_id', '');
$set('work_group2_id', null);
return;
}
else
{
$set('work_group2_id_error', null);
$set('work_group2_id', $workGroupRecord->id);
}
})
->extraAttributes(fn ($get) => [
'class' => $get('work_group2_id_error') ? 'border-red-500' : '',
])
->hint(fn ($get) => $get('work_group2_id_error'))
->hintColor('danger'),
Forms\Components\Hidden::make('work_group3_id'),
Forms\Components\TextInput::make('work_group3_actual_id')
->label('Work Group Center 3')
->hidden(fn (callable $get) => !$get('work_group3_id_visible'))
->default('')
->required()
->reactive()
->afterStateHydrated(function (callable $set, $record) {
if ($record && $record->workGroup3) {
$set('work_group3_actual_id', $record->workGroup3->name);
}
})
->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
// $workGroup1Id = $get('work_group1_actual_id');
$plantId = $get('plant_id');
$lineName = $get('name');
if ($state == null || trim($state) == '') {
$set('work_group3_id_error', null);
$set('work_group3_id', null);
return;
}
$set('work_group3_id_error', null);
$set('work_group3_id', null);
if (!$plantId) {
$set('work_group3_id_error', 'Invalid plant name.');
return;
}
$workGroupRecord = WorkGroupMaster::where('plant_id', $plantId)
->where('name', $state)
->first();
if (!$workGroupRecord) {
$set('work_group3_id_error', 'Work group does not exist for this plant in master.');
return;
}
$existsInLines = Line::where('plant_id', $plantId)
->where('name', '!=', $lineName) // Exclude current line
->where(function ($query) use ($workGroupRecord) {
for ($i = 1; $i <= 10; $i++) {
$query->orWhere("work_group{$i}_id", $workGroupRecord->id);
}
})
->count();
if ($existsInLines > 0) {
\Filament\Notifications\Notification::make()
->title('Work Group Already Assigned')
->body("The work group '{$state}' is already assigned to a line.")
->danger()
->send();
$set('work_group3_actual_id', '');
$set('work_group3_id', null);
return;
}
else
{
$set('work_group3_id_error', null);
$set('work_group3_id', $workGroupRecord->id);
}
})
->extraAttributes(fn ($get) => [
'class' => $get('work_group3_id_error') ? 'border-red-500' : '',
])
->hint(fn ($get) => $get('work_group3_id_error'))
->hintColor('danger'),
Forms\Components\Hidden::make('work_group4_id'),
Forms\Components\TextInput::make('work_group4_actual_id')
->label('Work Group Center 4')
->hidden(fn (callable $get) => !$get('work_group4_id_visible'))
->default('')
->required()
->reactive()
->afterStateHydrated(function (callable $set, $record) {
if ($record && $record->workGroup4) {
$set('work_group4_actual_id', $record->workGroup4->name);
}
})
->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
// $workGroup1Id = $get('work_group1_actual_id');
$plantId = $get('plant_id');
$lineName = $get('name');
if ($state == null || trim($state) == '') {
$set('work_group4_id_error', null);
$set('work_group4_id', null);
return;
}
$set('work_group4_id_error', null);
$set('work_group4_id', null);
if (!$plantId) {
$set('work_group4_id_error', 'Invalid plant name.');
return;
}
$workGroupRecord = WorkGroupMaster::where('plant_id', $plantId)
->where('name', $state)
->first();
if (!$workGroupRecord) {
$set('work_group4_id_error', 'Work group does not exist for this plant in master.');
return;
}
$existsInLines = Line::where('plant_id', $plantId)
->where('name', '!=', $lineName) // Exclude current line
->where(function ($query) use ($workGroupRecord) {
for ($i = 1; $i <= 10; $i++) {
$query->orWhere("work_group{$i}_id", $workGroupRecord->id);
}
})
->count();
if ($existsInLines > 0) {
\Filament\Notifications\Notification::make()
->title('Work Group Already Assigned')
->body("The work group '{$state}' is already assigned to a line.")
->danger()
->send();
$set('work_group4_actual_id', '');
$set('work_group4_id', null);
return;
}
else
{
$set('work_group4_id_error', null);
$set('work_group4_id', $workGroupRecord->id);
}
})
->extraAttributes(fn ($get) => [
'class' => $get('work_group4_id_error') ? 'border-red-500' : '',
])
->hint(fn ($get) => $get('work_group4_id_error'))
->hintColor('danger'),
Forms\Components\Hidden::make('work_group5_id'),
Forms\Components\TextInput::make('work_group5_actual_id')
->label('Work Group Center 5')
->hidden(fn (callable $get) => !$get('work_group5_id_visible'))
->default('')
->required()
->reactive()
->afterStateHydrated(function (callable $set, $record) {
if ($record && $record->workGroup5) {
$set('work_group5_actual_id', $record->workGroup5->name);
}
})
->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
// $workGroup1Id = $get('work_group1_actual_id');
$plantId = $get('plant_id');
$lineName = $get('name');
if ($state == null || trim($state) == '') {
$set('work_group5_id_error', null);
$set('work_group5_id', null);
return;
}
$set('work_group5_id_error', null);
$set('work_group5_id', null);
if (!$plantId) {
$set('work_group5_id_error', 'Invalid plant name.');
return;
}
$workGroupRecord = WorkGroupMaster::where('plant_id', $plantId)
->where('name', $state)
->first();
if (!$workGroupRecord) {
$set('work_group5_id_error', 'Work group does not exist for this plant in master.');
return;
}
$existsInLines = Line::where('plant_id', $plantId)
->where('name', '!=', $lineName) // Exclude current line
->where(function ($query) use ($workGroupRecord) {
for ($i = 1; $i <= 10; $i++) {
$query->orWhere("work_group{$i}_id", $workGroupRecord->id);
}
})
->count();
if ($existsInLines > 0) {
\Filament\Notifications\Notification::make()
->title('Work Group Already Assigned')
->body("The work group '{$state}' is already assigned to a line.")
->danger()
->send();
$set('work_group5_actual_id', '');
$set('work_group5_id', null);
return;
}
else
{
$set('work_group5_id_error', null);
$set('work_group5_id', $workGroupRecord->id);
}
})
->extraAttributes(fn ($get) => [
'class' => $get('work_group5_id_error') ? 'border-red-500' : '',
])
->hint(fn ($get) => $get('work_group5_id_error'))
->hintColor('danger'),
Forms\Components\Hidden::make('work_group6_id'),
Forms\Components\TextInput::make('work_group6_actual_id')
->label('Work Group Center 6')
->hidden(fn (callable $get) => !$get('work_group6_id_visible'))
->default('')
->required()
->reactive()
->afterStateHydrated(function (callable $set, $record) {
if ($record && $record->workGroup6) {
$set('work_group6_actual_id', $record->workGroup6->name);
}
})
->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
// $workGroup1Id = $get('work_group1_actual_id');
$plantId = $get('plant_id');
$lineName = $get('name');
if ($state == null || trim($state) == '') {
$set('work_group6_id_error', null);
$set('work_group6_id', null);
return;
}
$set('work_group6_id_error', null);
$set('work_group6_id', null);
if (!$plantId) {
$set('work_group6_id_error', 'Invalid plant name.');
return;
}
$workGroupRecord = WorkGroupMaster::where('plant_id', $plantId)
->where('name', $state)
->first();
if (!$workGroupRecord) {
$set('work_group6_id_error', 'Work group does not exist for this plant in master.');
return;
}
$existsInLines = Line::where('plant_id', $plantId)
->where('name', '!=', $lineName) // Exclude current line
->where(function ($query) use ($workGroupRecord) {
for ($i = 1; $i <= 10; $i++) {
$query->orWhere("work_group{$i}_id", $workGroupRecord->id);
}
})
->count();
if ($existsInLines > 0) {
\Filament\Notifications\Notification::make()
->title('Work Group Already Assigned')
->body("The work group '{$state}' is already assigned to a line.")
->danger()
->send();
$set('work_group6_actual_id', '');
$set('work_group6_id', null);
return;
}
else
{
$set('work_group6_id_error', null);
$set('work_group6_id', $workGroupRecord->id);
}
})
->extraAttributes(fn ($get) => [
'class' => $get('work_group6_id_error') ? 'border-red-500' : '',
])
->hint(fn ($get) => $get('work_group6_id_error'))
->hintColor('danger'),
Forms\Components\Hidden::make('work_group7_id'),
Forms\Components\TextInput::make('work_group7_actual_id')
->label('Work Group Center 7')
->hidden(fn (callable $get) => !$get('work_group7_id_visible'))
->default('')
->required()
->reactive()
->afterStateHydrated(function (callable $set, $record) {
if ($record && $record->workGroup7) {
$set('work_group7_actual_id', $record->workGroup7->name);
}
})
->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
// $workGroup1Id = $get('work_group1_actual_id');
$plantId = $get('plant_id');
$lineName = $get('name');
if ($state == null || trim($state) == '') {
$set('work_group7_id_error', null);
$set('work_group7_id', null);
return;
}
$set('work_group7_id_error', null);
$set('work_group7_id', null);
if (!$plantId) {
$set('work_group7_id_error', 'Invalid plant name.');
return;
}
$workGroupRecord = WorkGroupMaster::where('plant_id', $plantId)
->where('name', $state)
->first();
if (!$workGroupRecord) {
$set('work_group7_id_error', 'Work group does not exist for this plant in master.');
return;
}
$existsInLines = Line::where('plant_id', $plantId)
->where('name', '!=', $lineName) // Exclude current line
->where(function ($query) use ($workGroupRecord) {
for ($i = 1; $i <= 10; $i++) {
$query->orWhere("work_group{$i}_id", $workGroupRecord->id);
}
})
->count();
if ($existsInLines > 0) {
\Filament\Notifications\Notification::make()
->title('Work Group Already Assigned')
->body("The work group '{$state}' is already assigned to a line.")
->danger()
->send();
$set('work_group7_actual_id', '');
$set('work_group7_id', null);
return;
}
else
{
$set('work_group7_id_error', null);
$set('work_group7_id', $workGroupRecord->id);
}
})
->extraAttributes(fn ($get) => [
'class' => $get('work_group7_id_error') ? 'border-red-500' : '',
])
->hint(fn ($get) => $get('work_group7_id_error'))
->hintColor('danger'),
Forms\Components\Hidden::make('work_group8_id'),
Forms\Components\TextInput::make('work_group8_actual_id')
->label('Work Group Center 8')
->hidden(fn (callable $get) => !$get('work_group8_id_visible'))
->default('')
->required()
->reactive()
->afterStateHydrated(function (callable $set, $record) {
if ($record && $record->workGroup8) {
$set('work_group8_actual_id', $record->workGroup8->name);
}
})
->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
// $workGroup1Id = $get('work_group1_actual_id');
$plantId = $get('plant_id');
$lineName = $get('name');
if ($state == null || trim($state) == '') {
$set('work_group8_id_error', null);
$set('work_group8_id', null);
return;
}
$set('work_group8_id_error', null);
$set('work_group8_id', null);
if (!$plantId) {
$set('work_group8_id_error', 'Invalid plant name.');
return;
}
$workGroupRecord = WorkGroupMaster::where('plant_id', $plantId)
->where('name', $state)
->first();
if (!$workGroupRecord) {
$set('work_group8_id_error', 'Work group does not exist for this plant in master.');
return;
}
$existsInLines = Line::where('plant_id', $plantId)
->where('name', '!=', $lineName) // Exclude current line
->where(function ($query) use ($workGroupRecord) {
for ($i = 1; $i <= 10; $i++) {
$query->orWhere("work_group{$i}_id", $workGroupRecord->id);
}
})
->count();
if ($existsInLines > 0) {
\Filament\Notifications\Notification::make()
->title('Work Group Already Assigned')
->body("The work group '{$state}' is already assigned to a line.")
->danger()
->send();
$set('work_group8_actual_id', '');
$set('work_group8_id', null);
return;
}
else
{
$set('work_group8_id_error', null);
$set('work_group8_id', $workGroupRecord->id);
}
})
->extraAttributes(fn ($get) => [
'class' => $get('work_group8_id_error') ? 'border-red-500' : '',
])
->hint(fn ($get) => $get('work_group8_id_error'))
->hintColor('danger'),
Forms\Components\Hidden::make('work_group9_id'),
Forms\Components\TextInput::make('work_group9_actual_id')
->label('Work Group Center 9')
->hidden(fn (callable $get) => !$get('work_group9_id_visible'))
->default('')
->required()
->reactive()
->afterStateHydrated(function (callable $set, $record) {
if ($record && $record->workGroup9) {
$set('work_group9_actual_id', $record->workGroup9->name);
}
})
->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
// $workGroup1Id = $get('work_group1_actual_id');
$plantId = $get('plant_id');
$lineName = $get('name');
if ($state == null || trim($state) == '') {
$set('work_group9_id_error', null);
$set('work_group9_id', null);
return;
}
$set('work_group9_id_error', null);
$set('work_group9_id', null);
if (!$plantId) {
$set('work_group9_id_error', 'Invalid plant name.');
return;
}
$workGroupRecord = WorkGroupMaster::where('plant_id', $plantId)
->where('name', $state)
->first();
if (!$workGroupRecord) {
$set('work_group9_id_error', 'Work group does not exist for this plant in master.');
return;
}
$existsInLines = Line::where('plant_id', $plantId)
->where('name', '!=', $lineName) // Exclude current line
->where(function ($query) use ($workGroupRecord) {
for ($i = 1; $i <= 10; $i++) {
$query->orWhere("work_group{$i}_id", $workGroupRecord->id);
}
})
->count();
if ($existsInLines > 0) {
\Filament\Notifications\Notification::make()
->title('Work Group Already Assigned')
->body("The work group '{$state}' is already assigned to a line.")
->danger()
->send();
$set('work_group9_actual_id', '');
$set('work_group9_id', null);
return;
}
else
{
$set('work_group9_id_error', null);
$set('work_group9_id', $workGroupRecord->id);
}
})
->extraAttributes(fn ($get) => [
'class' => $get('work_group9_id_error') ? 'border-red-500' : '',
])
->hint(fn ($get) => $get('work_group9_id_error'))
->hintColor('danger'),
Forms\Components\Hidden::make('work_group10_id'),
Forms\Components\TextInput::make('work_group10_actual_id')
->label('Work Group Center 10')
->hidden(fn (callable $get) => !$get('work_group10_id_visible'))
->default('')
->required()
->reactive()
->afterStateHydrated(function (callable $set, $record) {
if ($record && $record->workGroup10) {
$set('work_group10_actual_id', $record->workGroup10->name);
}
})
->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
// $workGroup1Id = $get('work_group1_actual_id');
$plantId = $get('plant_id');
$lineName = $get('name');
if ($state == null || trim($state) == '') {
$set('work_group10_id_error', null);
$set('work_group10_id', null);
return;
}
$set('work_group10_id_error', null);
$set('work_group10_id', null);
if (!$plantId) {
$set('work_group10_id_error', 'Invalid plant name.');
return;
}
$workGroupRecord = WorkGroupMaster::where('plant_id', $plantId)
->where('name', $state)
->first();
if (!$workGroupRecord) {
$set('work_group10_id_error', 'Work group does not exist for this plant in master.');
return;
}
$existsInLines = Line::where('plant_id', $plantId)
->where('name', '!=', $lineName) // Exclude current line
->where(function ($query) use ($workGroupRecord) {
for ($i = 1; $i <= 10; $i++) {
$query->orWhere("work_group{$i}_id", $workGroupRecord->id);
}
})
->count();
if ($existsInLines > 0) {
\Filament\Notifications\Notification::make()
->title('Work Group Already Assigned')
->body("The work group '{$state}' is already assigned to a line.")
->danger()
->send();
$set('work_group10_actual_id', '');
$set('work_group10_id', null);
return;
}
else
{
$set('work_group10_id_error', null);
$set('work_group10_id', $workGroupRecord->id);
}
})
->extraAttributes(fn ($get) => [
'class' => $get('work_group10_id_error') ? 'border-red-500' : '',
])
->hint(fn ($get) => $get('work_group10_id_error'))
->hintColor('danger'),
// Forms\Components\TextInput::make('group_work_center')
// ->label('Group Work Center')
// ->placeholder('Scan the valid Group Work Center'),
Forms\Components\TextInput::make('id')
->hidden()
->readOnly(),
Forms\Components\TextInput::make('group_work_center')
->label('Group Work Center')
->placeholder('Scan the valid Group Work Center'),
Forms\Components\TextInput::make('id')
->hidden()
->readOnly(),
])
->columns(2),
]);
@@ -976,107 +217,8 @@ class LineResource extends Resource
->alignCenter()
->sortable()
->searchable(),
Tables\Columns\TextColumn::make('no_of_operation')
->label('No of Operation')
->alignCenter()
->searchable(),
Tables\Columns\TextColumn::make('workGroup1.name')
->label('Work Group Center 1')
->alignCenter()
->sortable()
->searchable(),
Tables\Columns\TextColumn::make('workGroup1.operation_number')
->label('Operation Number 1')
->alignCenter()
->sortable()
->searchable(),
Tables\Columns\TextColumn::make('workGroup2.name')
->label('Work Group Center 2')
->alignCenter()
->sortable()
->searchable(),
Tables\Columns\TextColumn::make('workGroup2.operation_number')
->label('Operation Number 2')
->alignCenter()
->sortable()
->searchable(),
Tables\Columns\TextColumn::make('workGroup3.name')
->label('Work Group Center 3')
->alignCenter()
->sortable()
->searchable(),
Tables\Columns\TextColumn::make('workGroup3.operation_number')
->label('Operation Number 3')
->alignCenter()
->sortable()
->searchable(),
Tables\Columns\TextColumn::make('workGroup4.name')
->label('Work Group Center 4')
->alignCenter()
->sortable()
->searchable(),
Tables\Columns\TextColumn::make('workGroup4.operation_number')
->label('Operation Number 4')
->alignCenter()
->sortable()
->searchable(),
Tables\Columns\TextColumn::make('workGroup5.name')
->label('Work Group Center 5')
->alignCenter()
->sortable()
->searchable(),
Tables\Columns\TextColumn::make('workGroup5.operation_number')
->label('Operation Number 5')
->alignCenter()
->sortable()
->searchable(),
Tables\Columns\TextColumn::make('workGroup6.name')
->label('Work Group Center 6')
->alignCenter()
->sortable()
->searchable(),
Tables\Columns\TextColumn::make('workGroup6.operation_number')
->label('Operation Number 6')
->alignCenter()
->sortable()
->searchable(),
Tables\Columns\TextColumn::make('workGroup7.name')
->label('Work Group Center 7')
->alignCenter()
->sortable()
->searchable(),
Tables\Columns\TextColumn::make('workGroup7.operation_number')
->label('Operation Number 7')
->alignCenter()
->sortable()
->searchable(),
Tables\Columns\TextColumn::make('workGroup8.name')
->label('Work Group Center 8')
->alignCenter()
->sortable()
->searchable(),
Tables\Columns\TextColumn::make('workGroup8.operation_number')
->label('Operation Number 8')
->alignCenter()
->sortable()
->searchable(),
Tables\Columns\TextColumn::make('workGroup9.name')
->label('Work Group Center 9')
->alignCenter()
->sortable()
->searchable(),
Tables\Columns\TextColumn::make('workGroup9.operation_number')
->label('Operation Number 9')
->alignCenter()
->sortable()
->searchable(),
Tables\Columns\TextColumn::make('workGroup10.name')
->label('Work Group Center 10')
->alignCenter()
->sortable()
->searchable(),
Tables\Columns\TextColumn::make('workGroup10.operation_number')
->label('Operation Number 10')
Tables\Columns\TextColumn::make('group_work_center')
->label('Group Work Center')
->alignCenter()
->sortable()
->searchable(),

View File

@@ -5,76 +5,8 @@ namespace App\Filament\Resources\LineResource\Pages;
use App\Filament\Resources\LineResource;
use Filament\Actions;
use Filament\Resources\Pages\CreateRecord;
use Illuminate\Validation\ValidationException;
class CreateLine extends CreateRecord
{
protected static string $resource = LineResource::class;
protected function getRedirectUrl(): string
{
return $this->getResource()::getUrl('create');
}
protected function beforeCreate(): void
{
$errors = [];
if (!empty($this->data['lPlantError'])) {
$errors['lPlantError'] = ['Fix the errors before submitting.'];
}
if (!empty($this->data['lNameError'])) {
$errors['lNameError'] = ['Fix the errors before submitting.'];
}
if (!empty($this->data['lTypeError'])) {
$errors['lTypeError'] = ['Fix the errors before submitting.'];
}
if (!empty($this->data['work_group1_id_error'])) {
$errors['work_group1_id_error'] = ['Fix the errors before submitting.'];
}
if (!empty($this->data['work_group2_id_error'])) {
$errors['work_group2_id_error'] = ['Fix the errors before submitting.'];
}
if (!empty($this->data['work_group3_id_error'])) {
$errors['work_group1_id_error'] = ['Fix the errors before submitting.'];
}
if (!empty($this->data['work_group4_id_error'])) {
$errors['work_group4_id_error'] = ['Fix the errors before submitting.'];
}
if (!empty($this->data['work_group5_id_error'])) {
$errors['work_group5_id_error'] = ['Fix the errors before submitting.'];
}
if (!empty($this->data['work_group6_id_error'])) {
$errors['work_group6_id_error'] = ['Fix the errors before submitting.'];
}
if (!empty($this->data['work_group7_id_error'])) {
$errors['work_group7_id_error'] = ['Fix the errors before submitting.'];
}
if (!empty($this->data['work_group8_id_error'])) {
$errors['work_group8_id_error'] = ['Fix the errors before submitting.'];
}
if (!empty($this->data['work_group9_id_error'])) {
$errors['work_group9_id_error'] = ['Fix the errors before submitting.'];
}
//..warranty
if (!empty($this->data['work_group10_id_error'])) {
$errors['work_group10_id_error'] = ['Fix the errors before submitting.'];
}
if (!empty($errors)) {
throw ValidationException::withMessages($errors);
}
}
}

View File

@@ -9,9 +9,4 @@ use Filament\Resources\Pages\CreateRecord;
class CreateLineStop extends CreateRecord
{
protected static string $resource = LineStopResource::class;
protected function getRedirectUrl(): string
{
return $this->getResource()::getUrl('create');
}
}

View File

@@ -21,9 +21,7 @@ class CreateLocatorInvoiceValidation extends CreateRecord
protected static string $view = 'filament.resources.pallet-validation-resource.pages.create-locator-invoice-validation';
public $plantId;
public $invoice_number;
public $pallet_number;
public $serial_number, $snoCount;
@@ -31,13 +29,8 @@ class CreateLocatorInvoiceValidation extends CreateRecord
public $locator_number;
public array $matchedSerialNumbersForRemoval = [];
public bool $showRemoveSerialsModal = false;
protected function getRedirectUrl(): string
{
return $this->getResource()::getUrl('create');
}
public function processinvoiceSNo()
{

View File

@@ -9,9 +9,4 @@ use Filament\Resources\Pages\CreateRecord;
class CreateLocator extends CreateRecord
{
protected static string $resource = LocatorResource::class;
protected function getRedirectUrl(): string
{
return $this->getResource()::getUrl('create');
}
}

View File

@@ -8,7 +8,6 @@ use App\Filament\Resources\MachineResource\Pages;
use App\Filament\Resources\MachineResource\RelationManagers;
use App\Models\Line;
use App\Models\Machine;
use App\Models\WorkGroupMaster;
use Filament\Facades\Filament;
use Filament\Forms;
use Filament\Forms\Form;
@@ -31,7 +30,7 @@ class MachineResource extends Resource
protected static ?string $navigationGroup = 'Master Entries';
protected static ?int $navigationSort = 12;
protected static ?int $navigationSort = 11;
public static function form(Form $form): Form
{
@@ -50,8 +49,6 @@ class MachineResource extends Resource
$plantId = $get('plant_id');
if (!$plantId) {
$set('mPlantError', 'Please select a plant first.');
$set('line_id', null);
$set('work_group_master_id', null);
return;
}
else
@@ -74,7 +71,9 @@ class MachineResource extends Resource
return [];
}
return Line::where('plant_id', $get('plant_id'))->where('no_of_operation', '>', 0)->pluck('name', 'id')->toArray();
return Line::where('plant_id', $get('plant_id'))
->pluck('name', 'id')
->toArray();
})
->default(function () {
return optional(Machine::latest()->first())->line_id;
@@ -84,18 +83,17 @@ class MachineResource extends Resource
$lineId = $get('line_id');
if (!$lineId) {
$set('mLineError', 'Please select a line first.');
$set('work_group_master_id', null);
return;
}
else
{
// $grpWrkCnr = Line::find($lineId)->group_work_center;
// if (!$grpWrkCnr || Str::length($grpWrkCnr) < 1)
// {
// $set('mLineError', 'Please select a group work center line.');
// $set('line_id', null);
// return;
// }
$grpWrkCnr = Line::find($lineId)->group_work_center;
if (!$grpWrkCnr || Str::length($grpWrkCnr) < 1)
{
$set('mLineError', 'Please select a group work center line.');
$set('line_id', null);
return;
}
$set('mLineError', null);
}
})
@@ -104,73 +102,19 @@ class MachineResource extends Resource
])
->hint(fn ($get) => $get('mLineError') ? $get('mLineError') : null)
->hintColor('danger'),
Forms\Components\Select::make('work_group_master_id')
->label('Group Work Center')
->relationship('workGroupMaster', 'name')
->required()
->reactive()
->options(function (callable $get) {
if (!$get('plant_id') || !$get('line_id')) {
return [];
}
$line = Line::find($get('line_id'));
$workGroupIds = [];
for ($i = 1; $i <= $line->no_of_operation; $i++) {
$column = "work_group{$i}_id";
if (!empty($line->$column)) {
$workGroupIds[] = $line->$column;
}
}
return WorkGroupMaster::where('plant_id', $get('plant_id'))->whereIn('id', $workGroupIds)->pluck('name', 'id')->toArray();
})
->default(function () {
return optional(Machine::latest()->first())->work_group_master_id;
})
->disabled(fn (Get $get) => !empty($get('id')))
->afterStateUpdated(function ($state, callable $set, callable $get) {
$lineId = $get('line_id');
if (!$lineId) {
$set('mGroupWorkError', 'Please select a line first.');
return;
}
else
{
// $grpWrkCnr = Line::find($lineId)->group_work_center;
// if (!$grpWrkCnr || Str::length($grpWrkCnr) < 1)
// {
// $set('mGroupWorkError', 'Please select a group work center line.');
// $set('line_id', null);
// return;
// }
$set('mGroupWorkError', null);
}
})
->extraAttributes(fn ($get) => [
'class' => $get('mGroupWorkError') ? 'border-red-500' : '',
])
->hint(fn ($get) => $get('mGroupWorkError') ? $get('mGroupWorkError') : null)
->hintColor('danger'),
Forms\Components\TextInput::make('name')
->label('Name')
->placeholder('Scan the valid Machine Name')
->required()
->rule(function (callable $get) {
return Rule::unique('machines', 'name')
//->where('line_id', $get('line_id'))
->where('line_id', $get('line_id'))
->where('plant_id', $get('plant_id'))
->ignore($get('id')); // Ignore current record during updates
}),
Forms\Components\TextInput::make('work_center')
->label('Work Center')
->placeholder('Scan the valid Work Center')
->required()
->rule(function (callable $get) {
return Rule::unique('machines', 'work_center')
->where('plant_id', $get('plant_id'))
->ignore($get('id')); // Ignore current record during updates
}),
->placeholder('Scan the valid Work Center'),
Forms\Components\TextInput::make('id')
->hidden()
->readOnly(),
@@ -191,26 +135,21 @@ class MachineResource extends Resource
}),
Tables\Columns\TextColumn::make('plant.name')
->label('Plant')
->alignCenter()
->searchable(),
->searchable()
->alignCenter(),
Tables\Columns\TextColumn::make('line.name')
->label('Line')
->alignCenter()
->searchable(),
->searchable()
->alignCenter(),
Tables\Columns\TextColumn::make('name')
->label('Name')
->alignCenter()
->searchable(),
->searchable()
->alignCenter(),
Tables\Columns\TextColumn::make('work_center')
->label('Work Center')
->alignCenter()
->searchable()
->sortable(),
Tables\Columns\TextColumn::make('workGroupMaster.name')
->label('Work Group Center')
->alignCenter()
->searchable()
->sortable(),
->sortable()
->searchable(),
Tables\Columns\TextColumn::make('created_at')
->label('Created At')
->alignCenter()

View File

@@ -9,9 +9,4 @@ use Filament\Resources\Pages\CreateRecord;
class CreateMachine extends CreateRecord
{
protected static string $resource = MachineResource::class;
protected function getRedirectUrl(): string
{
return $this->getResource()::getUrl('create');
}
}

View File

@@ -116,7 +116,7 @@ class MfmMeterResource extends Resource
Tables\Actions\RestoreBulkAction::make(),
]),
])
->headerActions([
->headerActions([
ImportAction::make()
->importer(MfmMeterImporter::class)
->visible(function() {

View File

@@ -9,9 +9,4 @@ use Filament\Resources\Pages\CreateRecord;
class CreateMfmMeter extends CreateRecord
{
protected static string $resource = MfmMeterResource::class;
protected function getRedirectUrl(): string
{
return $this->getResource()::getUrl('create');
}
}

View File

@@ -9,9 +9,4 @@ use Filament\Resources\Pages\CreateRecord;
class CreateMfmParameter extends CreateRecord
{
protected static string $resource = MfmParameterResource::class;
protected function getRedirectUrl(): string
{
return $this->getResource()::getUrl('create');
}
}

View File

@@ -2,6 +2,8 @@
namespace App\Filament\Resources;
use App\Filament\Exports\MfmReadingExporter;
use App\Filament\Imports\MfmReadingImporter;
use App\Filament\Resources\MfmReadingResource\Pages;
use App\Filament\Resources\MfmReadingResource\RelationManagers;
use App\Models\MfmReading;
@@ -12,6 +14,9 @@ use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use Filament\Tables\Actions\ImportAction;
use Filament\Tables\Actions\ExportAction;
use Filament\Facades\Filament;
class MfmReadingResource extends Resource
{
@@ -196,6 +201,18 @@ class MfmReadingResource extends Resource
Tables\Actions\ForceDeleteBulkAction::make(),
Tables\Actions\RestoreBulkAction::make(),
]),
])
->headerActions([
ImportAction::make()
->importer(MfmReadingImporter::class)
->visible(function() {
return Filament::auth()->user()->can('view import mfm reading');
}),
ExportAction::make()
->exporter(MfmReadingExporter::class)
->visible(function() {
return Filament::auth()->user()->can('view export mfm reading');
}),
]);
}

View File

@@ -9,9 +9,4 @@ use Filament\Resources\Pages\CreateRecord;
class CreateMfmReading extends CreateRecord
{
protected static string $resource = MfmReadingResource::class;
protected function getRedirectUrl(): string
{
return $this->getResource()::getUrl('create');
}
}

View File

@@ -9,9 +9,4 @@ use Filament\Resources\Pages\CreateRecord;
class CreateModuleList extends CreateRecord
{
protected static string $resource = ModuleListResource::class;
protected function getRedirectUrl(): string
{
return $this->getResource()::getUrl('create');
}
}

View File

@@ -9,13 +9,8 @@ use App\Filament\Resources\MotorTestingMasterResource\RelationManagers;
use App\Models\Configuration;
use App\Models\Item;
use App\Models\MotorTestingMaster;
use App\Models\Plant;
use Filament\Facades\Filament;
use Filament\Forms;
use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\Radio;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Form;
use Filament\Forms\Get;
use Filament\Resources\Resource;
@@ -25,7 +20,6 @@ use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use Filament\Tables\Actions\ImportAction;
use Filament\Tables\Actions\ExportAction;
use Filament\Tables\Filters\Filter;
use Illuminate\Validation\Rule;
class MotorTestingMasterResource extends Resource
@@ -34,9 +28,9 @@ class MotorTestingMasterResource extends Resource
protected static ?string $navigationIcon = 'heroicon-o-rectangle-stack';
protected static ?string $navigationGroup = 'Testing Panel';
protected static ?string $navigationGroup = 'Master Entries';
protected static ?int $navigationSort = 1;
protected static ?int $navigationSort = 12;
public static function form(Form $form): Form
{
@@ -67,11 +61,6 @@ class MotorTestingMasterResource extends Resource
])
->hint(fn ($get) => $get('mTmError') ? $get('mTmError') : null)
->hintColor('danger'),
Forms\Components\TimePicker::make('routine_test_time')
->label('Routine Test Time')
->default('00:40:00')
->required()
->reactive(),
Forms\Components\Select::make('item_id')
->label('Item Code')
//->relationship('item', 'name')
@@ -93,39 +82,11 @@ class MotorTestingMasterResource extends Resource
->where('plant_id', $get('plant_id'))
->ignore($get('id')); // Ignore current record during updates
}),
Forms\Components\TextInput::make('subassembly_code')
->label('Subassembly Code')
Forms\Components\TimePicker::make('routine_test_time')
->label('Routine Test Time')
->default('00:40:00')
->required()
->placeholder('Scan the valid code')
->reactive()
->alphaNum()
->minLength(6)
->afterStateUpdated(function ($state, callable $set, callable $get) {
$code = $get('subassembly_code');
if (!$code) {
$set('iCodeError', 'Scan the valid Subassembly Code.');
return;
}
else
{
if (strlen($code) < 6) {
$set('iCodeError', 'Subassembly code must be at least 6 digits.');
return;
}
else if (!preg_match('/^[a-zA-Z0-9]{6,}$/', $code)) {
$set('code',null);
$set('iCodeError', 'Subassembly code must contain only alpha-numeric characters.');
return;
}
$set('iCodeError', null);
}
})
->extraAttributes(fn ($get) => [
'class' => $get('iCodeError') ? 'border-red-500' : '',
])
->hint(fn ($get) => $get('iCodeError') ? $get('iCodeError') : null)
->hintColor('danger'),
->reactive(),
Forms\Components\Select::make('isi_model')
->label('ISI Model')
->options([
@@ -141,6 +102,11 @@ class MotorTestingMasterResource extends Resource
->options(function (callable $get) {
$plantId = $get('plant_id');
// if (!$plantId || !$lineId)
// {
// return [];
// }
if ($plantId)
{
return Configuration::where('plant_id', $plantId)
@@ -317,32 +283,26 @@ class MotorTestingMasterResource extends Resource
}),
Tables\Columns\TextColumn::make('plant.name')
->label('Plant')
->searchable()
->alignCenter()
->searchable()
->sortable(),
Tables\Columns\TextColumn::make('item.category')
->label('Category')
->searchable()
->alignCenter()
->searchable()
->sortable(),
Tables\Columns\TextColumn::make('item.code')
->label('Item Code')
->searchable()
->alignCenter()
->sortable(),
Tables\Columns\TextColumn::make('subassembly_code')
->label('Subassembly Code')
->searchable()
->alignCenter()
->sortable(),
Tables\Columns\TextColumn::make('item.description')
->label('Model')
->searchable()
->alignCenter()
->searchable()
->sortable(),
Tables\Columns\IconColumn::make('isi_model')
->label('ISI Model')
->searchable()
->alignCenter()
->boolean(),
Tables\Columns\TextColumn::make('phase')
@@ -372,7 +332,6 @@ class MotorTestingMasterResource extends Resource
->alignCenter(),
Tables\Columns\TextColumn::make('connection')
->label('Connection')
->searchable()
->alignCenter(),
Tables\Columns\TextColumn::make('ins_res_limit')
->label('Insulation Resistance Limit')
@@ -432,25 +391,19 @@ class MotorTestingMasterResource extends Resource
->label('No Load Speed UL')
->alignCenter(),
Tables\Columns\TextColumn::make('created_at')
->label('Created At')
->dateTime()
->alignCenter()
->sortable(),
Tables\Columns\TextColumn::make('created_by')
->label('Created By')
->searchable()
->alignCenter()
->sortable(),
->alignCenter(),
Tables\Columns\TextColumn::make('updated_at')
->label('Updated At')
->dateTime()
->alignCenter()
->sortable(),
Tables\Columns\TextColumn::make('updated_by')
->label('Updated By')
->searchable()
->alignCenter()
->sortable(),
->alignCenter(),
Tables\Columns\TextColumn::make('deleted_at')
->dateTime()
->alignCenter()
@@ -459,287 +412,7 @@ class MotorTestingMasterResource extends Resource
])
->filters([
Tables\Filters\TrashedFilter::make(),
Filter::make('advanced_filters')
->label('Advanced Filters')
->form([
Select::make('Plant')
->label('Select Plant')
->nullable()
->options(function () {
return Plant::pluck('name', 'id');
})
->reactive()
->afterStateUpdated(function ($state, callable $set, callable $get) {
$set('Item', null);
$set('isi_type', null);
$set('created_by', null);
$set('updated_by', null);
}),
Select::make('Item')
->label('Search by Item Code')
->nullable()
->options(function (callable $get) {
$pId = $get('Plant');
return Item::whereHas('motorTestingMasters', function ($query) use ($pId) {
if ($pId) {
$query->where('plant_id', $pId);
}
})->pluck('code', 'id');
})
->searchable()
->reactive(),
TextInput::make('description')
->label('Description')
->placeholder('Enter Description'),
Radio::make('isi_type')
->label('ISI Model ?')
->boolean()
->options([
'All' => 'All',
'Y' => 'Y',
'N' => 'N'
])
->default(null)
->inlineLabel(false)
->inline(),
Select::make('phase_type')
->label('Select Phase')
->nullable()
->options(function (callable $get) {
$plantId = $get('plant_id');
if ($plantId)
{
return Configuration::where('plant_id', $plantId)
->where('c_name', 'MOTOR_PHASE')
->orderBy('created_at')
->pluck('c_value', 'c_value')
->toArray();
}
else
{
return Configuration::where('c_name', 'MOTOR_PHASE')
->orderBy('created_at')
->pluck('c_value', 'c_value')
->toArray();
}
})
->afterStateUpdated(function ($state, callable $set, callable $get) {
if ($state == 'Single' && $get('connection_type') == 'Star-Delta') {
$set('phase_type', 'Three');
}
})
->reactive(),
Select::make('connection_type')
->label('Select Connection')
->nullable()
->options(function (callable $get) {
$plantId = $get('plant_id');
if ($plantId)
{
return Configuration::where('plant_id', $plantId)
->where('c_name', 'MOTOR_CONNECTION')
->orderBy('created_at')
->pluck('c_value', 'c_value')
->toArray();
}
else
{
return Configuration::where('c_name', 'MOTOR_CONNECTION')
->orderBy('created_at')
->pluck('c_value', 'c_value')
->toArray();
}
})
->afterStateUpdated(function ($state, callable $set) {
if ($state == 'Star-Delta') {
$set('phase_type', 'Three');
}
})
->reactive(),
Select::make('created_by')
->label('Created By')
->nullable()
->options(function (callable $get) {
$plantId = $get('Plant');
if (!$plantId)
{
return MotorTestingMaster::whereNotNull('created_by')->select('created_by')->distinct()->pluck('created_by', 'created_by');
}
else
{
return MotorTestingMaster::where('plant_id', $plantId)->whereNotNull('created_by')->select('created_by')->distinct()->pluck('created_by', 'created_by');
}
})
->searchable()
->reactive(),
DateTimePicker::make(name: 'created_from')
->label('Created From')
->placeholder(placeholder: 'Select From DateTime')
->reactive()
->native(false),
DateTimePicker::make('created_to')
->label('Created To')
->placeholder(placeholder: 'Select To DateTime')
->reactive()
->native(false),
Select::make('updated_by')
->label('Updated By')
->nullable()
->options(function (callable $get) {
$plantId = $get('Plant');
if (!$plantId)
{
return MotorTestingMaster::whereNotNull('updated_by')->select('updated_by')->distinct()->pluck('updated_by', 'updated_by');
}
else
{
return MotorTestingMaster::where('plant_id', $plantId)->whereNotNull('updated_by')->select('updated_by')->distinct()->pluck('updated_by', 'updated_by');
}
})
->searchable()
->reactive(),
DateTimePicker::make(name: 'updated_from')
->label('Updated From')
->placeholder(placeholder: 'Select From DateTime')
->reactive()
->native(false),
DateTimePicker::make('updated_to')
->label('Updated To')
->placeholder(placeholder: 'Select To DateTime')
->reactive()
->native(false),
])
->query(function ($query, array $data) {
// Hide all records initially if no filters are applied
if (empty($data['Plant']) && empty($data['Item']) && empty($data['description']) && empty($data['isi_type']) && empty($data['phase_type']) && empty($data['connection_type']) && empty($data['created_by']) && empty($data['created_from']) && empty($data['created_to']) && empty($data['updated_by']) && empty($data['updated_from']) && empty($data['updated_to'])) {// || $data['isi_type'] == 'All')
return $query->whereRaw('1 = 0');
}
if (!empty($data['Plant'])) {
$query->where('plant_id', $data['Plant']);
}
if (!empty($data['Item'])) {
$itemIds = Item::where('id', $data['Item'])
->pluck('id')
->toArray();
if (!empty($itemIds)) {
$query->whereIn('item_id', $itemIds);
}
}
if (!empty($data['description'])) {
$pId = $data['Plant'] ?? null;
$descIds = Item::where('description', 'like', '%' . $data['description'] . '%')->whereHas('motorTestingMasters', function ($query) use ($pId) {
if ($pId) { $query->where('plant_id', $pId); }
})->pluck('id')->toArray();
if (!empty($descIds)) {
$query->whereIn('item_id', $descIds);
}
}
if ($data['isi_type'] == 'Y') {
$query->where('isi_model', true);
}
else if ($data['isi_type'] == 'N') {
$query->where('isi_model', false);
}
if (!empty($data['phase_type'])) {
$query->where('phase', $data['phase_type']);
}
if (!empty($data['connection_type'])) {
$query->where('connection', $data['connection_type']);
}
if (!empty($data['created_by'])) {
$query->where('created_by', $data['created_by']);
}
if (!empty($data['created_from'])) {
$query->where('created_at', '>=', $data['created_from']);
}
if (!empty($data['created_to'])) {
$query->where('created_at', '<=', $data['created_to']);
}
if (!empty($data['updated_by'])) {
$query->where('updated_by', $data['updated_by']);
}
if (!empty($data['updated_from'])) {
$query->where('updated_at', '>=', $data['updated_from']);
}
if (!empty($data['updated_to'])) {
$query->where('updated_at', '<=', $data['updated_to']);
}
})
->indicateUsing(function (array $data) {
$indicators = [];
if (!empty($data['Plant'])) {
$indicators[] = 'Plant: ' . Plant::where('id', $data['Plant'])->value('name');
}
if (!empty($data['Item'])) {
$itemCode = Item::find($data['Item'])->code ?? 'Unknown';
$indicators[] = 'Item Codes: ' . $itemCode;
}
if (!empty($data['description'])) {
$indicators[] = 'Description: ' . $data['description'];
}
if ($data['isi_type'] == 'Y') {
$indicators[] = 'ISI Model: Yes';
}
else if ($data['isi_type'] == 'N') {
$indicators[] = 'ISI Model: No';
}
if (!empty($data['phase_type'])) {
$indicators[] = 'Phase: ' . $data['phase_type'];
}
if (!empty($data['connection_type'])) {
$indicators[] = 'Connection: ' . $data['connection_type'];
}
if (!empty($data['created_by'])) {
$indicators[] = 'Created By: ' . $data['created_by'];
}
if (!empty($data['created_from'])) {
$indicators[] = 'Created From: ' . $data['created_from'];
}
if (!empty($data['created_to'])) {
$indicators[] = 'Created To: ' . $data['created_to'];
}
if (!empty($data['updated_by'])) {
$indicators[] = 'Updated By: ' . $data['updated_by'];
}
if (!empty($data['updated_from'])) {
$indicators[] = 'Updated From: ' . $data['updated_from'];
}
if (!empty($data['updated_to'])) {
$indicators[] = 'Updated To: ' . $data['updated_to'];
}
return $indicators;
})
])
->filtersFormMaxHeight('280px')
->actions([
Tables\Actions\ViewAction::make(),
Tables\Actions\EditAction::make(),

View File

@@ -9,9 +9,4 @@ use Filament\Resources\Pages\CreateRecord;
class CreateMotorTestingMaster extends CreateRecord
{
protected static string $resource = MotorTestingMasterResource::class;
protected function getRedirectUrl(): string
{
return $this->getResource()::getUrl('create');
}
}

View File

@@ -14,33 +14,24 @@ use Illuminate\View\View;
class CreatePalletValidation extends CreateRecord
{
public $plantId;
public $pallet_number;
public $palletNo;
public $pendingPallet;
public $snoCount = 0;
public $pallet_number_locked = false;
public $serial_number;
protected static string $view = 'filament.resources.pallet-validation-resource.pages.create-pallet-validation';
protected static string $resource = PalletValidationResource::class;
protected $listeners = [
'updateSnoQuantity' => 'handleUpdateSnoQuantity',
];
public ?array $data = null;
protected function getRedirectUrl(): string
{
return $this->getResource()::getUrl('create');
}
public function processPalletSNo()
{

View File

@@ -9,9 +9,4 @@ use Filament\Resources\Pages\CreateRecord;
class CreatePlant extends CreateRecord
{
protected static string $resource = PlantResource::class;
protected function getRedirectUrl(): string
{
return $this->getResource()::getUrl('create');
}
}

View File

@@ -1,360 +0,0 @@
<?php
namespace App\Filament\Resources;
use App\Filament\Resources\ProcessOrderResource\Pages;
use App\Filament\Resources\ProcessOrderResource\RelationManagers;
use App\Models\ProcessOrder;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use Storage;
use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;
use Filament\Notifications\Notification;
use Filament\Forms\Components\Actions\Action;
use Filament\Facades\Filament;
use Smalot\PdfParser\Parser;
class ProcessOrderResource extends Resource
{
protected static ?string $model = ProcessOrder::class;
protected static ?string $navigationIcon = 'heroicon-o-rectangle-stack';
protected static ?string $navigationGroup = 'Process Order';
public static function form(Form $form): Form
{
return $form
->schema([
Forms\Components\Select::make('plant_id')
->label('Plant')
->reactive()
->relationship('plant', 'name')
->required(),
Forms\Components\Select::make('item_id')
->label('Item Code')
// ->relationship('item', 'id')
// ->required(),
->reactive()
->searchable()
->options(function (callable $get) {
$plantId = $get('plant_id');
if (empty($plantId)) {
return [];
}
return \App\Models\Item::where('plant_id', $plantId)->pluck('code', 'id');
})
->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
$plantId = $get('plant_id');
$itemId = $get('item_id');
// dd($plantId);
if ($plantId && $itemId) {
// Get the item code using item_id
$itemCode = \App\Models\Item::where('id', $itemId)->value('code');
if ($itemCode) {
// Now get the item description using plant_id + code
$item = \App\Models\Item::where('plant_id', $plantId)
->where('code', $itemCode)
->first();
$set('item_description', $item?->description);
} else {
$set('item_description', null);
}
} else {
$set('item_description', null);
}
})
->required(),
Forms\Components\TextInput::make('item_description')
->label('Description')
->required()
->reactive(),
// ->readOnly(true),
Forms\Components\TextInput::make('process_order')
->label('Process Order')
->required(),
Forms\Components\FileUpload::make('attachment')
->label('PDF Upload')
->acceptedFileTypes(['application/pdf'])
->storeFiles(false)
->disk('local')
->directory('uploads/temp')
->preserveFilenames()
->reactive(),
Forms\Components\Actions::make([
Action::make('uploadNow')
->label('Upload PDF Now')
->action(function ($get, callable $set) {
$uploadedFiles = $get('attachment');
if (is_array($uploadedFiles) && count($uploadedFiles) > 0)
{
$uploaded = reset($uploadedFiles);
if ($uploaded instanceof TemporaryUploadedFile) {
$originalName = $uploaded->getClientOriginalName();
$path = 'uploads/ProcessOrder/' . $originalName;
// Check if file already exists
if (Storage::disk('local')->exists($path)) {
Notification::make()
->title('Duplicate File')
->body("The file '{$originalName}' already exists in uploads/ProcessOrder.")
->warning()
->send();
return; // Stop here
}
$storedPath = $uploaded->storeAs(
'uploads/ProcessOrder',
$originalName,
'local'
);
// $fullPath = storage_path('app/' . $storedPath);
$fullPath = storage_path('app/' . $storedPath);
// Parse PDF using smalot/pdfparser
$parser = new Parser();
$pdf = $parser->parseContent(file_get_contents($uploaded->getRealPath()));
$text = $pdf->getText();
// if (preg_match('/Batch ID:\s*(\d+)\s*--/i', $text, $matches))
// {
// $batchId = $matches[1];
// }
if (preg_match('/Batch ID:\s*(\d+)(?:\s*--)?/i', $text, $matches)) {
$batchId = $matches[1];
}
else
{
$batchId = null;
}
// Get the value of process_order field
$processOrder = $get('process_order');
if ($batchId != $processOrder) {
Notification::make()
->title('Mismatch')
->body("Batch ID ($batchId) does not match Process Order ($processOrder)")
->danger()
->send();
return;
}
if ($batchId == $processOrder)
{
// If batch matches, store the PDF permanently
$storedPath = $uploaded->storeAs(
'uploads/ProcessOrder',
$originalName,
'local'
);
Notification::make()
->title('Success')
->body("Batch ID matches Process Order: $batchId. PDF uploaded successfully.")
->success()
->send();
return;
}
}
}
else
{
Notification::make()
->title('No file selected to upload')
->warning()
->send();
return;
}
}),
Action::make('downloadAttachment')
->label('Download PDF')
->action(function ($get) {
$equipmentNumber = $get('process_order');
if (!$equipmentNumber) {
Notification::make()
->title('No process order entered')
->danger()
->send();
return;
}
$files = Storage::disk('local')->files('uploads/ProcessOrder');
$fileToDownload = null;
foreach ($files as $file) {
if (str_contains($file, $equipmentNumber)) {
$fileToDownload = $file;
break;
}
}
if (!$fileToDownload) {
Notification::make()
->title('PDF not found for this process order')
->danger()
->send();
return;
}
return response()->download(Storage::disk('local')->path($fileToDownload));
}),
// Action::make('removeAttachment')
// ->label('Remove PDF')
// ->action(function ($get) {
// $equipmentNumber = $get('process_order');
// if (!$equipmentNumber) {
// Notification::make()
// ->title('No process order entered')
// ->danger()
// ->send();
// return;
// }
// // Get all files from uploads/temp
// $files = Storage::disk('local')->files('uploads/ProcessOrder');
// $fileToDelete = null;
// foreach ($files as $file) {
// if (str_contains($file, $equipmentNumber)) {
// $fileToDelete = $file;
// break;
// }
// }
// if (!$fileToDelete) {
// Notification::make()
// ->title('PDF not found for this process order')
// ->danger()
// ->send();
// return;
// }
// // Delete the matched file
// Storage::disk('local')->delete($fileToDelete);
// Notification::make()
// ->title('PDF removed successfully')
// ->body("File for process order {$equipmentNumber} has been deleted.")
// ->success()
// ->send();
// }),
]),
Forms\Components\Hidden::make('created_by')
->label('Created By')
->default(Filament::auth()->user()?->name),
Forms\Components\Hidden::make('updated_by')
->default(Filament::auth()->user()?->name),
]);
}
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')
->alignCenter()
->sortable(),
Tables\Columns\TextColumn::make('item.code')
->label('Item')
->alignCenter()
->sortable(),
Tables\Columns\TextColumn::make('item.description')
->label('Description')
->alignCenter()
->sortable(),
Tables\Columns\TextColumn::make('created_at')
->label('Created At')
->alignCenter()
->dateTime()
->sortable()
->toggleable(isToggledHiddenByDefault: true),
Tables\Columns\TextColumn::make('created_by')
->label('Created By')
->alignCenter()
->sortable(),
Tables\Columns\TextColumn::make('updated_at')
->label('Updated At')
->alignCenter()
->dateTime()
->sortable()
->toggleable(isToggledHiddenByDefault: true),
Tables\Columns\TextColumn::make('updated_by')
->label('Updated By')
->alignCenter()
->sortable()
->toggleable(isToggledHiddenByDefault: true),
Tables\Columns\TextColumn::make('deleted_at')
->label('Deleted At')
->alignCenter()
->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(),
]),
]);
}
public static function getRelations(): array
{
return [
//
];
}
public static function getPages(): array
{
return [
'index' => Pages\ListProcessOrders::route('/'),
'create' => Pages\CreateProcessOrder::route('/create'),
'view' => Pages\ViewProcessOrder::route('/{record}'),
'edit' => Pages\EditProcessOrder::route('/{record}/edit'),
];
}
public static function getEloquentQuery(): Builder
{
return parent::getEloquentQuery()
->withoutGlobalScopes([
SoftDeletingScope::class,
]);
}
}

View File

@@ -1,12 +0,0 @@
<?php
namespace App\Filament\Resources\ProcessOrderResource\Pages;
use App\Filament\Resources\ProcessOrderResource;
use Filament\Actions;
use Filament\Resources\Pages\CreateRecord;
class CreateProcessOrder extends CreateRecord
{
protected static string $resource = ProcessOrderResource::class;
}

View File

@@ -1,22 +0,0 @@
<?php
namespace App\Filament\Resources\ProcessOrderResource\Pages;
use App\Filament\Resources\ProcessOrderResource;
use Filament\Actions;
use Filament\Resources\Pages\EditRecord;
class EditProcessOrder extends EditRecord
{
protected static string $resource = ProcessOrderResource::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\ProcessOrderResource\Pages;
use App\Filament\Resources\ProcessOrderResource;
use Filament\Actions;
use Filament\Resources\Pages\ListRecords;
class ListProcessOrders extends ListRecords
{
protected static string $resource = ProcessOrderResource::class;
protected function getHeaderActions(): array
{
return [
Actions\CreateAction::make(),
];
}
}

View File

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

View File

@@ -2093,52 +2093,10 @@ class QualityValidationResource extends Resource
return;
}
// if ($state == $expectedValue)
// {
// $set('part_validation5_error', null);
// }
// else if (strpos($state, '/') != false) {
// $parts = explode('/', $state);
// if (count($parts) >= 2) {
// $segmentToValidate = $parts[1];
// }
// else
// {
// $segmentToValidate = null;
// }
// }
// else
// {
// $set('part_validation5_error', "Invalid input for part validation 5.");
// $set('part_validation5', null);
// return;
// }
if ($state == $expectedValue)
{
$set('part_validation5_error', null);
}
else if (strpos($state, '/') != false)
{
$parts = explode('/', $state);
if (count($parts) >= 2)
{
$segmentToValidate = $parts[1];
if ($segmentToValidate == $expectedValue) {
$set('part_validation5_error', null);
$set('part_validation5', $segmentToValidate);
} else {
$set('part_validation5_error', "Invalid input for part validation 5.");
$set('part_validation5', null);
return;
}
}
else
{
$set('part_validation5_error', "Invalid input format for part validation 5.");
$set('part_validation5', null);
return;
}
}
else
{
$set('part_validation5_error', "Invalid input for part validation 5.");
@@ -2183,7 +2141,6 @@ class QualityValidationResource extends Resource
->sortable(),
Tables\Columns\TextColumn::make('line.name')
->label('Line')
->searchable()
->alignCenter()
->sortable(),
Tables\Columns\TextColumn::make('production_order')
@@ -2411,6 +2368,7 @@ class QualityValidationResource extends Resource
->placeholder(placeholder: 'Select To DateTime')
->reactive()
->native(false),
])
->query(function ($query, array $data) {
// Hide all records initially if no filters are applied
@@ -2459,8 +2417,6 @@ class QualityValidationResource extends Resource
$query->whereIn('sticker_master_id', $stickerMasterIds);
}
}
//$query->orderBy('created_at', 'asc');
})
->indicateUsing(function (array $data) {
$indicators = [];
@@ -2531,8 +2487,7 @@ class QualityValidationResource extends Resource
}),
]);
}
//,,
// public static function mutateFormDataBeforeCreate(array $data): array
// {
// $user =Filament::auth()->user();

View File

@@ -21,11 +21,6 @@ class CreateReworkLocatorInvoiceValidation extends CreateRecord
protected static string $resource = ReworkLocatorInvoiceValidationResource::class;
protected function getRedirectUrl(): string
{
return $this->getResource()::getUrl('create');
}
public function processInvoiceRework($invoiceNo)
{
$plantId = $this->form->getState()['plant'];

View File

@@ -9,9 +9,4 @@ use Filament\Resources\Pages\CreateRecord;
class CreateShift extends CreateRecord
{
protected static string $resource = ShiftResource::class;
protected function getRedirectUrl(): string
{
return $this->getResource()::getUrl('create');
}
}

View File

@@ -3,12 +3,12 @@
namespace App\Filament\Resources;
use App\Filament\Exports\StickerMasterExporter;
//use App\Filament\Imports\ShiftImporter;
use App\Filament\Imports\ShiftImporter;
use App\Filament\Imports\StickerMasterImporter;
use App\Filament\Resources\StickerMasterResource\Pages;
//use App\Filament\Resources\StickerMasterResource\RelationManagers;
use App\Filament\Resources\StickerMasterResource\RelationManagers;
use App\Models\StickerMaster;
//use Closure;
use Closure;
use Filament\Facades\Filament;
use Filament\Forms;
use Filament\Forms\Form;
@@ -18,7 +18,6 @@ use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use Filament\Forms\Get;
use Filament\Forms\Set;
use Filament\Tables\Actions\ExportAction;
use Filament\Tables\Actions\ImportAction;
// use Illuminate\Validation\Rule;
@@ -36,401 +35,383 @@ class StickerMasterResource extends Resource
public static function form(Form $form): Form
{
return $form
->schema([
Forms\Components\Select::make('plant_id')
->relationship('plant', 'name')
->reactive()
->nullable()
->default(function () {
return optional(StickerMaster::latest()->first())->plant_id;
})
->disabled(fn (Get $get) => !empty($get('id'))) //disable in edit if user try to change
->afterStateUpdated(fn (callable $set) =>
$set('item_id', null) & //when plant changed remove all the data which is in text input box
$set('item_description', null) &
$set('item_error', null) &
$set('panel_box_code', null) &
$set('load_rate', null) &
$set('bundle_quantity', null) &
$set('material_type', null) &
$set('part_validation1', null) &
$set('part_validation2', null) &
$set('part_validation3', null) &
$set('part_validation4', null) &
$set('part_validation5', null) &
$set('laser_part_validation1', null) &
$set('laser_part_validation2', null) &
$set('serial_number_motor', false) &
$set('serial_number_pump', false) &
$set('serial_number_pumpset', false) &
$set('pack_slip_motor', false) &
$set('pack_slip_pump', false) &
$set('pack_slip_pumpset', false) &
$set('name_plate_motor', false) &
$set('name_plate_pump', false) &
$set('name_plate_pumpset', false) &
$set('tube_sticker_motor', false) &
$set('tube_sticker_pump', false) &
$set('tube_sticker_pumpset', false) &
$set('warranty_card', false)
)
->required(),
->schema([
Forms\Components\Select::make('plant_id')
->relationship('plant', 'name')
->reactive()
->nullable()
->default(function () {
return optional(StickerMaster::latest()->first())->plant_id;
})
->disabled(fn (Get $get) => !empty($get('id'))) //disable in edit if user try to change
->afterStateUpdated(fn (callable $set) =>
$set('item_id', null) & //when plant changed remove all the data which is in text input box
$set('item_description', null) &
$set('item_error', null) &
$set('panel_box_code', null) &
$set('load_rate', null) &
$set('bundle_quantity', null) &
$set('material_type', null) &
$set('part_validation1', null) &
$set('part_validation2', null) &
$set('part_validation3', null) &
$set('part_validation4', null) &
$set('part_validation5', null) &
$set('laser_part_validation1', null) &
$set('laser_part_validation2', null) &
$set('serial_number_motor', false) &
$set('serial_number_pump', false) &
$set('serial_number_pumpset', false) &
$set('pack_slip_motor', false) &
$set('pack_slip_pump', false) &
$set('pack_slip_pumpset', false) &
$set('name_plate_motor', false) &
$set('name_plate_pump', false) &
$set('name_plate_pumpset', false) &
$set('tube_sticker_motor', false) &
$set('tube_sticker_pump', false) &
$set('tube_sticker_pumpset', false) &
$set('warranty_card', false)
)
->required(),
Forms\Components\Select::make('item_id')
->label('Item Code')
->options(function (callable $get) {
if (!$get('plant_id')) {
return [];
}
Forms\Components\Select::make('item_id')
->label('Item Code')
->options(function (callable $get) {
if (!$get('plant_id')) {
return [];
}
return \App\Models\Item::where('plant_id', $get('plant_id'))
->pluck('code', 'id')
->toArray();
})
// ->rule(function (callable $get) {
// return Rule::unique('items', 'code')
// ->where('plant_id', $get('plant_id'))
// ->ignore($get('id')); // Ignore current record during updates
// })
->required()
->nullable()
->searchable()
->reactive()
// ->disabled(fn (Get $get) => !empty($get('id')))
->live(debounce: 500) // Enable live updates
->afterStateUpdated(function ($state, callable $set, callable $get) {
$plantId = $get('plant_id');
$itemId = $get('item_id');
return \App\Models\Item::where('plant_id', $get('plant_id'))
->pluck('code', 'id')
->toArray();
})
// ->rule(function (callable $get) {
// return Rule::unique('items', 'code')
// ->where('plant_id', $get('plant_id'))
// ->ignore($get('id')); // Ignore current record during updates
// })
->required()
->nullable()
->searchable()
->reactive()
// ->disabled(fn (Get $get) => !empty($get('id')))
->live(debounce: 500) // Enable live updates
->afterStateUpdated(function ($state, callable $set, callable $get) {
//If plant_id is changed or empty, reset everything
if (blank($plantId)) {
$set('item_id', null);
$set('item_error', null);
$set('item_description', null);
return;
}
$plantId = $get('plant_id');
$itemId = $get('item_id');
if (blank($itemId)) {
$set('item_error', null);
$set('item_description', null);
return;
}
//If plant_id is changed or empty, reset everything
if (blank($plantId)) {
$set('item_id', null);
$set('item_error', null);
$set('item_description', null);
return;
}
$availableItems = \App\Models\Item::where('plant_id', $plantId)->exists();
if (!$availableItems) {
$set('item_error', null);
return;
}
if (blank($itemId)) {
$set('item_error', null);
$set('item_description', null);
return;
}
// Ensure `item_id` is not cleared
if (!$plantId || !$itemId) {
$set('item_description', null);
return;
}
$availableItems = \App\Models\Item::where('plant_id', $plantId)->exists();
if (!$availableItems) {
$set('item_error', null);
return;
}
// Check if item exists for the selected plant
$item = \App\Models\Item::where('plant_id', $plantId)
->where('id', $itemId)
->first();
// Ensure `item_id` is not cleared
if (!$plantId || !$itemId) {
$set('item_description', null);
return;
}
if ($item) {
$set('item_description', $item->description);
} else {
$set('item_description', null);
}
// Check if item exists for the selected plant
$item = \App\Models\Item::where('plant_id', $plantId)
->where('id', $itemId)
->first();
$duplicateSticker = StickerMaster::where('plant_id', $plantId)
->where('item_id', $itemId)
->exists();
if(!$get('id'))
{
$set('item_error', $duplicateSticker ? 'Item Code already exists for the selected plant.' : null);
}
})
->extraAttributes(fn ($get) => [
'class' => $get('item_error') ? 'border-red-500' : '',
])
->hint(fn ($get) => $get('item_error') ? $get('item_error') : null)
->hintColor('danger'),
if ($item) {
$set('item_description', $item->description);
} else {
$set('item_description', null);
}
Forms\Components\TextInput::make('item_description')
->label('Description')
->required()
->afterStateHydrated(function ($component, $state, Get $get, Set $set) {
if ($get('id')) {
$itemId = StickerMaster::where('id', $get('id'))->first()?->item_id;
if ($itemId) {
$item = \App\Models\Item::where('id', $itemId)->first()?->description;
if ($item) {
$set('item_description', $item);
} else {
$set('item_description', null);
}
} else {
$set('item_description', null);
}
}
})
->reactive()
->readOnly(true),
$duplicateSticker = StickerMaster::where('plant_id', $plantId)
->where('item_id', $itemId)
->exists();
if(!$get('id'))
{
$set('item_error', $duplicateSticker ? 'Item Code already exists for the selected plant.' : null);
}
})
->extraAttributes(fn ($get) => [
'class' => $get('item_error') ? 'border-red-500' : '',
])
->hint(fn ($get) => $get('item_error') ? $get('item_error') : null)
->hintColor('danger'),
Forms\Components\TextInput::make('part_validation1')
->label('Part Validation 1')
->nullable(),
Forms\Components\TextInput::make('part_validation2')
->label('Part Validation 2')
->nullable(),
Forms\Components\TextInput::make('item_description')
->label('Description')
->required()
->reactive()
->readOnly(true),
Forms\Components\TextInput::make('part_validation3')
->label('Part Validation 3')
->nullable(),
Forms\Components\TextInput::make('part_validation1')
->nullable(),
Forms\Components\TextInput::make('part_validation4')
->label('Part Validation 4')
->nullable(),
Forms\Components\TextInput::make('part_validation2')
->nullable(),
Forms\Components\TextInput::make('part_validation5')
->label('Part Validation 5 (Capacitor QR)')
->nullable(),
Forms\Components\TextInput::make('part_validation3')
->nullable(),
Forms\Components\TextInput::make('laser_part_validation1')
->label('Laser Part Validation 1')
->nullable(),
Forms\Components\TextInput::make('part_validation4')
->nullable(),
Forms\Components\TextInput::make('laser_part_validation2')
->label('Laser Part Validation 2')
->nullable(),
Forms\Components\TextInput::make('part_validation5')
->nullable(),
Forms\Components\TextInput::make('panel_box_code')
->label('Panel Box Code')
->readOnly(fn (callable $get) => $get('material_type'))
->nullable(),
Forms\Components\TextInput::make('laser_part_validation1')
->nullable(),
Forms\Components\TextInput::make('load_rate')
->label('Load Rate')
->default(0)
->required()
->disabled(function ($get) {
return $get('material_type');
})
->integer(),
Forms\Components\TextInput::make('laser_part_validation2')
->nullable(),
Forms\Components\Select::make('material_type')
->label('Material Type')
->options([
'1' => 'Individual',
'2' => 'Bundle',
'3' => 'Quantity',
])
->reactive()
->afterStateUpdated(function ($state, callable $set, callable $get) {
Forms\Components\TextInput::make('panel_box_code')
->label('Panel Box Code')
->readOnly(fn (callable $get) => $get('material_type'))
->nullable(),
if ($state)
{
$set('panel_box_code', null);
$set('load_rate', 0);
}
Forms\Components\TextInput::make('load_rate')
->label('Load Rate')
->default(0)
->disabled(function ($get) {
return $get('material_type');
})
->integer()
->nullable(),
if ($state !== "2")
{
$set('bundle_quantity', null);
}
else
{
$set('bundle_quantity', 2);
}
//$plantId = $get('plant_id');
})
->nullable(),
Forms\Components\TextInput::make('bundle_quantity')
->label('Bundle Quantity')
->integer()
->readOnly(fn (callable $get) => $get('material_type') !== "2")
->nullable()
->minValue(2)
->reactive()
->afterStateUpdated(function ($state, callable $set,callable $get) {
if($get('material_type') !== "2")
{
$set('bundle_quantity', null);
}
else if ($get('bundle_quantity') < 2)
{
$set('bundle_quantity', 2);
}
}),
Forms\Components\Select::make('material_type')
->label('Material Type')
->options([
'1' => 'Individual',
'2' => 'Bundle',
'3' => 'Quantity',
])
->reactive()
->afterStateUpdated(function ($state, callable $set, callable $get) {
Forms\Components\Checkbox::make('serial_number_motor')
->reactive()
->disabled(function ($get) {
return $get('serial_number_pumpset');
})
->afterStateUpdated(function ($state, callable $set,callable $get) {
if ($get('serial_number_pumpset'))
{
$set('serial_number_motor', false);
}
})
->dehydrateStateUsing(fn ($state): mixed => $state ? $state : null),
if ($state)
{
$set('panel_box_code', null);
$set('load_rate', 0);
}
Forms\Components\Checkbox::make('serial_number_pump')
->reactive()
->disabled(function ($get) {
return $get('serial_number_pumpset');
})
->afterStateUpdated(function ($state, callable $set,callable $get) {
if ($get('serial_number_pumpset'))
{
$set('serial_number_pump', false);
}
})
->dehydrateStateUsing(fn ($state) => $state ? $state : null),
if ($state !== "2")
{
$set('bundle_quantity', null);
}
else
{
$set('bundle_quantity', 2);
}
//$plantId = $get('plant_id');
})
->nullable(),
Forms\Components\Checkbox::make('serial_number_pumpset')
->reactive()
->disabled(function ($get) {
return $get('serial_number_motor') || $get('serial_number_pump');
})
->afterStateUpdated(function ($state, callable $set,callable $get) {
if ($get('serial_number_pumpset'))
{
$set('serial_number_motor', false);
$set('serial_number_pump', false);
}
})
->dehydrateStateUsing(fn ($state) => $state ? $state : null),
Forms\Components\TextInput::make('bundle_quantity')
->label('Bundle Quantity')
->integer()
->readOnly(fn (callable $get) => $get('material_type') !== "2")
->nullable()
->minValue(2)
->reactive()
->afterStateUpdated(function ($state, callable $set,callable $get) {
if($get('material_type') !== "2")
{
$set('bundle_quantity', null);
}
else if ($get('bundle_quantity') < 2)
{
$set('bundle_quantity', 2);
}
}),
Forms\Components\Checkbox::make('pack_slip_motor')
->reactive()
->disabled(function ($get) {
return $get('pack_slip_pumpset');
})
->afterStateUpdated(function ($state, callable $set,callable $get) {
if ($get('pack_slip_pumpset'))
{
$set('pack_slip_motor', false);
}
})
->dehydrateStateUsing(fn ($state) => $state ? $state : null),
Forms\Components\Checkbox::make('serial_number_motor')
->reactive()
->disabled(function ($get) {
return $get('serial_number_pumpset');
})
->afterStateUpdated(function ($state, callable $set,callable $get) {
if ($get('serial_number_pumpset'))
{
$set('serial_number_motor', false);
}
})
->dehydrateStateUsing(fn ($state): mixed => $state ? $state : null),
Forms\Components\Checkbox::make('pack_slip_pump')
->reactive()
->disabled(function ($get) {
return $get('pack_slip_pumpset');
})
->afterStateUpdated(function ($state, callable $set,callable $get) {
if ($get('pack_slip_pumpset'))
{
$set('pack_slip_pump', false);
}
})
->dehydrateStateUsing(fn ($state) => $state ? $state : null),
Forms\Components\Checkbox::make('serial_number_pump')
->reactive()
->disabled(function ($get) {
return $get('serial_number_pumpset');
})
->afterStateUpdated(function ($state, callable $set,callable $get) {
if ($get('serial_number_pumpset'))
{
$set('serial_number_pump', false);
}
})
->dehydrateStateUsing(fn ($state) => $state ? $state : null),
Forms\Components\Checkbox::make('pack_slip_pumpset')
->reactive()
->disabled(function ($get) {
return $get('pack_slip_motor') || $get('pack_slip_pump');
})
->afterStateUpdated(function ($state, callable $set,callable $get) {
if ($get('pack_slip_pumpset'))
{
$set('pack_slip_motor', false);
$set('pack_slip_pump', false);
}
})
->dehydrateStateUsing(fn ($state) => $state ? $state : null),
Forms\Components\Checkbox::make('serial_number_pumpset')
->reactive()
->disabled(function ($get) {
return $get('serial_number_motor') || $get('serial_number_pump');
})
->afterStateUpdated(function ($state, callable $set,callable $get) {
if ($get('serial_number_pumpset'))
{
$set('serial_number_motor', false);
$set('serial_number_pump', false);
}
})
->dehydrateStateUsing(fn ($state) => $state ? $state : null),
Forms\Components\Checkbox::make('name_plate_motor')
->reactive()
->disabled(function ($get) {
return $get('name_plate_pumpset');
})
->afterStateUpdated(function ($state, callable $set,callable $get) {
if ($get('name_plate_pumpset'))
{
$set('name_plate_motor', false);
}
})
->dehydrateStateUsing(fn ($state) => $state ? $state : null),
Forms\Components\Checkbox::make('pack_slip_motor')
->reactive()
->disabled(function ($get) {
return $get('pack_slip_pumpset');
})
->afterStateUpdated(function ($state, callable $set,callable $get) {
if ($get('pack_slip_pumpset'))
{
$set('pack_slip_motor', false);
}
})
->dehydrateStateUsing(fn ($state) => $state ? $state : null),
Forms\Components\Checkbox::make('name_plate_pump')
->reactive()
->disabled(function ($get) {
return $get('name_plate_pumpset');
})
->afterStateUpdated(function ($state, callable $set,callable $get) {
if ($get('name_plate_pumpset'))
{
$set('name_plate_pump', false);
}
})
->dehydrateStateUsing(fn ($state) => $state ? $state : null),
Forms\Components\Checkbox::make('pack_slip_pump')
->reactive()
->disabled(function ($get) {
return $get('pack_slip_pumpset');
})
->afterStateUpdated(function ($state, callable $set,callable $get) {
if ($get('pack_slip_pumpset'))
{
$set('pack_slip_pump', false);
}
})
->dehydrateStateUsing(fn ($state) => $state ? $state : null),
Forms\Components\Checkbox::make('name_plate_pumpset')
->reactive()
->disabled(function ($get) {
return $get('name_plate_motor') || $get('name_plate_pump');
})
->afterStateUpdated(function ($state, callable $set,callable $get) {
if ($get('name_plate_pumpset'))
{
$set('name_plate_motor', false);
$set('name_plate_pump', false);
}
})
->dehydrateStateUsing(fn ($state) => $state ? $state : null),
Forms\Components\Checkbox::make('pack_slip_pumpset')
->reactive()
->disabled(function ($get) {
return $get('pack_slip_motor') || $get('pack_slip_pump');
})
->afterStateUpdated(function ($state, callable $set,callable $get) {
if ($get('pack_slip_pumpset'))
{
$set('pack_slip_motor', false);
$set('pack_slip_pump', false);
}
})
->dehydrateStateUsing(fn ($state) => $state ? $state : null),
Forms\Components\Checkbox::make('tube_sticker_motor')
->reactive()
->disabled(function ($get) {
return $get('tube_sticker_pumpset');
})
->afterStateUpdated(function ($state, callable $set,callable $get) {
if ($get('tube_sticker_pumpset'))
{
$set('tube_sticker_motor', false);
}
})
->dehydrateStateUsing(fn ($state) => $state ? $state : null),
Forms\Components\Checkbox::make('name_plate_motor')
->reactive()
->disabled(function ($get) {
return $get('name_plate_pumpset');
})
->afterStateUpdated(function ($state, callable $set,callable $get) {
if ($get('name_plate_pumpset'))
{
$set('name_plate_motor', false);
}
})
->dehydrateStateUsing(fn ($state) => $state ? $state : null),
Forms\Components\Checkbox::make('tube_sticker_pump')
->reactive()
->disabled(function ($get) {
return $get('tube_sticker_pumpset');
})
->afterStateUpdated(function ($state, callable $set,callable $get) {
if ($get('tube_sticker_pumpset'))
{
$set('tube_sticker_pump', false);
}
})
->dehydrateStateUsing(fn ($state) => $state ? $state : null),
Forms\Components\Checkbox::make('name_plate_pump')
->reactive()
->disabled(function ($get) {
return $get('name_plate_pumpset');
})
->afterStateUpdated(function ($state, callable $set,callable $get) {
if ($get('name_plate_pumpset'))
{
$set('name_plate_pump', false);
}
})
->dehydrateStateUsing(fn ($state) => $state ? $state : null),
Forms\Components\Checkbox::make('tube_sticker_pumpset')
->nullable()
->reactive()
->disabled(function ($get) {
return $get('tube_sticker_motor') || $get('tube_sticker_pump');
})
->afterStateUpdated(function ($state, callable $set,callable $get) {
if ($get('tube_sticker_pumpset'))
{
$set('tube_sticker_motor', false);
$set('tube_sticker_pump', false);
}
})
->dehydrateStateUsing(fn ($state) => $state ? $state : null), //to pass null value
Forms\Components\Checkbox::make('name_plate_pumpset')
->reactive()
->disabled(function ($get) {
return $get('name_plate_motor') || $get('name_plate_pump');
})
->afterStateUpdated(function ($state, callable $set,callable $get) {
if ($get('name_plate_pumpset'))
{
$set('name_plate_motor', false);
$set('name_plate_pump', false);
}
})
->dehydrateStateUsing(fn ($state) => $state ? $state : null),
Forms\Components\Checkbox::make('warranty_card')
->nullable()
->dehydrateStateUsing(fn ($state) => $state ? $state : null),
Forms\Components\Checkbox::make('tube_sticker_motor')
->reactive()
->disabled(function ($get) {
return $get('tube_sticker_pumpset');
})
->afterStateUpdated(function ($state, callable $set,callable $get) {
if ($get('tube_sticker_pumpset'))
{
$set('tube_sticker_motor', false);
}
})
->dehydrateStateUsing(fn ($state) => $state ? $state : null),
Forms\Components\TextInput::make('id')
->hidden()
->readOnly(),
]);
Forms\Components\Checkbox::make('tube_sticker_pump')
->reactive()
->disabled(function ($get) {
return $get('tube_sticker_pumpset');
})
->afterStateUpdated(function ($state, callable $set,callable $get) {
if ($get('tube_sticker_pumpset'))
{
$set('tube_sticker_pump', false);
}
})
->dehydrateStateUsing(fn ($state) => $state ? $state : null),
Forms\Components\Checkbox::make('tube_sticker_pumpset')
->nullable()
->reactive()
->disabled(function ($get) {
return $get('tube_sticker_motor') || $get('tube_sticker_pump');
})
->afterStateUpdated(function ($state, callable $set,callable $get) {
if ($get('tube_sticker_pumpset'))
{
$set('tube_sticker_motor', false);
$set('tube_sticker_pump', false);
}
})
->dehydrateStateUsing(fn ($state) => $state ? $state : null), //to pass null value
Forms\Components\Checkbox::make('warranty_card')
->nullable()
->dehydrateStateUsing(fn ($state) => $state ? $state : null),
Forms\Components\TextInput::make('id')
->hidden()
->readOnly(),
]);
}
public static function table(Table $table): Table
@@ -443,13 +424,13 @@ class StickerMasterResource extends Resource
// ->numeric()
// ->sortable(),
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;
}),
->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')
->alignCenter()

View File

@@ -21,9 +21,4 @@ class CreateStickerMaster extends CreateRecord
]);
}
}
protected function getRedirectUrl(): string
{
return $this->getResource()::getUrl('create');
}
}

View File

@@ -113,19 +113,19 @@ class TempLiveReadingResource extends Resource
Tables\Actions\ForceDeleteBulkAction::make(),
Tables\Actions\RestoreBulkAction::make(),
]),
])
->headerActions([
ImportAction::make()
->importer(TempLiveReadingImporter::class)
->visible(function() {
return Filament::auth()->user()->can('view import temp live reading');
}),
ExportAction::make()
->exporter(TempLiveReadingExporter::class)
->visible(function() {
return Filament::auth()->user()->can('view export temp live reading');
}),
]);
// ->headerActions([
// ImportAction::make()
// ->importer(TempLiveReadingImporter::class)
// ->visible(function() {
// return Filament::auth()->user()->can('view import temp live reading');
// }),
// ExportAction::make()
// ->exporter(TempLiveReadingExporter::class)
// ->visible(function() {
// return Filament::auth()->user()->can('view export temp live reading');
// }),
// ]);
}
public static function getRelations(): array

View File

@@ -14,9 +14,4 @@ class CreateTempLiveReading extends CreateRecord
{
return 'Create Live Readings';
}
protected function getRedirectUrl(): string
{
return $this->getResource()::getUrl('create');
}
}

View File

@@ -6,12 +6,15 @@ use AlperenErsoy\FilamentExport\Actions\FilamentExportBulkAction;
use App\Filament\Exports\TestingPanelReadingExporter;
use App\Filament\Imports\TestingPanelReadingImporter;
use App\Filament\Resources\TestingPanelReadingResource\Pages;
use App\Filament\Resources\TestingPanelReadingResource\RelationManagers;
use App\Models\Configuration;
use App\Models\Item;
use App\Models\Line;
use App\Models\Machine;
use App\Models\MotorTestingMaster;
use App\Models\Plant;
use App\Models\QualityValidation;
use App\Models\StickerMaster;
use App\Models\TestingPanelReading;
use Barryvdh\DomPDF\Facade\Pdf;
use Filament\Facades\Filament;
@@ -39,8 +42,6 @@ class TestingPanelReadingResource extends Resource
protected static ?string $navigationGroup = 'Testing Panel';
protected static ?int $navigationSort = 3;
public static function form(Form $form): Form
{
return $form
@@ -154,8 +155,6 @@ class TestingPanelReadingResource extends Resource
Forms\Components\TextInput::make('serial_number')
->label('Serial Number')
->required(),
Forms\Components\TextInput::make('winded_serial_number')
->label('Winded Serial Number'),
Forms\Components\TextInput::make('before_fr_volt')
->label('Before FR Volt'),
Forms\Components\TextInput::make('before_fr_cur')
@@ -286,10 +285,6 @@ class TestingPanelReadingResource extends Resource
->label('Serial Number')
->alignCenter()
->sortable(),
Tables\Columns\TextColumn::make('winded_serial_number')
->label('Winded Serial Number')
->alignCenter()
->sortable(),
Tables\Columns\TextColumn::make('motorTestingMaster.kw')
->label('KW')
->alignCenter(),
@@ -802,150 +797,274 @@ class TestingPanelReadingResource extends Resource
Tables\Actions\ForceDeleteBulkAction::make(),
Tables\Actions\RestoreBulkAction::make(),
BulkAction::make('export_pdf')
->label('Export Readings PDF')
->action(function ($records)
->label('Export Readings PDF')
->action(function ($records)
{
//$records->load('item');
$records->load('motorTestingMaster.item');
$plantId = $records->first()?->plant_id;
$plant = $plantId ? Plant::find($plantId) : null;
// Check if all records are Star-Delta type
$isAllStarDelta = $records->every(function ($record) {
return $record->motorTestingMaster?->connection === 'Star-Delta';
});
// $hasStarDelta = $records->contains(function ($record) {
// return $record->motorTestingMaster?->connection === 'Star-Delta';
// });
//dd($isAllStarDelta);
if(!$isAllStarDelta)
{
//$records->load('item');
$records->load('motorTestingMaster.item');
$plantId = $records->first()?->plant_id;
$mappedData = collect($records)->map(function ($record) {
return [
// 'Date' => $record['created_at'] ?? '',
'Date' =>date('Y-m-d', strtotime($record['created_at'] ?? '')),
'Output' => $record['output'] ?? '',
'Motor SNo' => $record['serial_number'] ?? '',
'Item Code' => $record->motorTestingMaster->item->code ?? '',
'Motor Type' => $record->motorTestingMaster->item->description ?? '',
$plant = $plantId ? Plant::find($plantId) : null;
'kw' => $record->motorTestingMaster->kw ?? '',
'hp' => $record->motorTestingMaster->hp ?? '',
'phase' => $record->motorTestingMaster->phase ?? '',
'isi_model' => $record->motorTestingMaster->isi_model ?? '',
// Check if all records are Star-Delta type
$isAllStarDelta = $records->every(function ($record) {
return $record->motorTestingMaster?->connection === 'Star-Delta';
// BEFORE FREE RUN
'Voltage_Before' => $record['before_fr_volt'] ?? '',
'Current_Before' => $record['before_fr_cur'] ?? '',
'Power_Before' => $record['before_fr_pow'] ?? '',
'Resistance_RY' => $record['before_fr_res_ry'] ?? '',
'Resistance_YB' => $record['before_fr_res_yb'] ?? '',
'Resistance_BR' => $record['before_fr_res_br'] ?? '',
'Insulation_Resistance' => $record['before_fr_ir'] ?? '',
'Frequency_Before' => $record['before_fr_freq'] ?? '',
'Speed_Before' => $record['before_fr_speed'] ?? '',
// AFTER FREE RUN
'Voltage_After' => $record['after_fr_vol'] ?? '',
'Current_After' => $record['after_fr_cur'] ?? '',
'Power_After' => $record['after_fr_pow'] ?? '',
'IR_Hot' => $record['after_fr_ir_hot'] ?? '',
'IR_Cool' => $record['after_fr_ir_cool'] ?? '',
'Leakage_Current' => $record['after_fr_leak_cur'] ?? '',
'Frequency_After' => $record['after_fr_freq'] ?? '',
'Speed_After' => $record['after_fr_speed'] ?? '',
// LOCKED ROTOR TEST
'Voltage_Locked' => $record['locked_rt_volt'] ?? '',
'Current_Locked' => $record['locked_rt_cur'] ?? '',
'Power_Locked' => $record['locked_rt_pow'] ?? '',
// Last 8 columns
'No_Load_Pickup_Voltage' => $record['no_load_pickup_volt'] ?? '',
'Room_Temp' => $record['room_temperature'] ?? '',
'High_Voltage_Test' => $record['hv_test'] ?? '',
'Batch_Number' => $record['batch_number'] ?? '',
'Batch_Count' => $record['batch_count'] ?? '',
'Result' => $record['result'] ?? '',
'Remark' => $record['remark'] ?? '',
'Tested_By' => $record['tested_by'] ?? '',
];
});
}
else
{
$mappedData = collect($records)->map(function ($record) {
return [
//'Date' => $record['created_at'] ?? '',
'Date' =>date('Y-m-d', strtotime($record['created_at'] ?? '')),
'Output' => $record['output'] ?? '',
'Motor SNo' => $record['serial_number'] ?? '',
'Item Code' => $record->motorTestingMaster->item->code ?? '',
'Motor Type' => $record->motorTestingMaster->item->description ?? '',
'kw' => $record->motorTestingMaster->kw ?? '',
'hp' => $record->motorTestingMaster->hp ?? '',
'phase' => $record->motorTestingMaster->phase ?? '',
'isi_model' => $record->motorTestingMaster->isi_model ?? '',
// BEFORE FREE RUN
'Voltage_Before' => $record['before_fr_volt'] ?? '',
'Current_Before' => $record['before_fr_cur'] ?? '',
'Power_Before' => $record['before_fr_pow'] ?? '',
'Resistance_RY' => $record['before_fr_res_ry'] ?? '',
'Resistance_YB' => $record['before_fr_res_yb'] ?? '',
'Resistance_BR' => $record['before_fr_res_br'] ?? '',
'Insulation_Resistance_R' => $record['before_fr_ir_r'] ?? '',
'Insulation_Resistance_Y' => $record['before_fr_ir_y'] ?? '',
'Insulation_Resistance_B' => $record['before_fr_ir_b'] ?? '',
'Frequency_Before' => $record['before_fr_freq'] ?? '',
'Speed_Before' => $record['before_fr_speed'] ?? '',
// AFTER FREE RUN
'Voltage_After' => $record['after_fr_vol'] ?? '',
'Current_After' => $record['after_fr_cur'] ?? '',
'Power_After' => $record['after_fr_pow'] ?? '',
'IR_Hot_R' => $record['after_fr_ir_hot_r'] ?? '',
'IR_Hot_Y' => $record['after_fr_ir_hot_y'] ?? '',
'IR_Hot_B' => $record['after_fr_ir_hot_b'] ?? '',
'IR_Cool_R' => $record['after_fr_ir_cool_r'] ?? '',
'IR_Cool_Y' => $record['after_fr_ir_cool_y'] ?? '',
'IR_Cool_B' => $record['after_fr_ir_cool_b'] ?? '',
'Leakage_Current' => $record['after_fr_leak_cur'] ?? '',
'Frequency_After' => $record['after_fr_freq'] ?? '',
'Speed_After' => $record['after_fr_speed'] ?? '',
// LOCKED ROTOR TEST
'Voltage_Locked' => $record['locked_rt_volt'] ?? '',
'Current_Locked' => $record['locked_rt_cur'] ?? '',
'Power_Locked' => $record['locked_rt_pow'] ?? '',
// Last 8 columns
'No_Load_Pickup_Voltage' => $record['no_load_pickup_volt'] ?? '',
'Room_Temp' => $record['room_temperature'] ?? '',
'High_Voltage_Test' => $record['hv_test'] ?? '',
'Batch_Number' => $record['batch_number'] ?? '',
'Batch_Count' => $record['batch_count'] ?? '',
'Result' => $record['result'] ?? '',
'Remark' => $record['remark'] ?? '',
'Tested_By' => $record['tested_by'] ?? '',
];
});
// $hasStarDelta = $records->contains(function ($record) {
// return $record->motorTestingMaster?->connection === 'Star-Delta';
// });
}
$view = $isAllStarDelta ? 'exports.export-three-phase-pdf' : 'exports.testingpanel-pdf';
//dd($isAllStarDelta);
if(!$isAllStarDelta)
{
$mappedData = collect($records)->map(function ($record) {
$pdf = Pdf::loadView($view, [
'records' => $mappedData,
'plant' => $plant,
]);
// $pdf = Pdf::loadView('exports.testingpanel-pdf',[
// // ['records' => $mappedData]
// 'records' => $mappedData,
// 'plant' => $plant,
// ]);
return response()->streamDownload(
fn () => print($pdf->stream()),
'TestingPanelReading.pdf'
);
})
->icon('heroicon-o-document-arrow-down'),
BulkAction::make('export_isi_pdf')
->label('Export ISI Readings PDF')
->action(function ($records)
{
$records->load('motorTestingMaster.item');
$plantId = $records->first()?->plant_id;
$plant = $plantId ? Plant::find($plantId) : null;
$isAllStarDelta = $records->every(function ($record) {
return $record->motorTestingMaster?->connection === 'Star-Delta';
});
// $hasStarDelta = $records->contains(function ($record) {
// return $record->motorTestingMaster?->connection === 'Star-Delta';
// });
//dd($isAllStarDelta);
if(!$isAllStarDelta)
{
$mappedData = collect($records)->map(function ($record) {
return [
// 'Date' => $record['created_at'] ?? '',
'Date' =>date('Y-m-d', strtotime($record['created_at'] ?? '')),
'Output' => $record['output'] ?? '',
'Motor SNo' => $record['serial_number'] ?? '',
'Item Code' => $record->motorTestingMaster->item->code ?? '',
'Motor Type' => $record->motorTestingMaster->item->description ?? '',
// 'Date' => $record['created_at'] ?? '',
'Date' =>date('Y-m-d', strtotime($record['created_at'] ?? '')),
'Output' => $record['output'] ?? '',
'Motor SNo' => $record['serial_number'] ?? '',
'Item Code' => $record->motorTestingMaster->item->code ?? '',
'Motor Type' => $record->motorTestingMaster->item->description ?? '',
'kw' => $record->motorTestingMaster->kw ?? '',
'hp' => $record->motorTestingMaster->hp ?? '',
'phase' => $record->motorTestingMaster->phase ?? '',
'isi_model' => $record->motorTestingMaster->isi_model ?? '',
'kw' => $record->motorTestingMaster->kw ?? '',
'hp' => $record->motorTestingMaster->hp ?? '',
'phase' => $record->motorTestingMaster->phase ?? '',
'isi_model' => $record->motorTestingMaster->isi_model ?? '',
// BEFORE FREE RUN
'Voltage_Before' => $record['before_fr_volt'] ?? '',
'Current_Before' => $record['before_fr_cur'] ?? '',
'Power_Before' => $record['before_fr_pow'] ?? '',
'Resistance_RY' => $record['before_fr_res_ry'] ?? '',
'Resistance_YB' => $record['before_fr_res_yb'] ?? '',
'Resistance_BR' => $record['before_fr_res_br'] ?? '',
'Insulation_Resistance' => $record['before_fr_ir'] ?? '',
'Frequency_Before' => $record['before_fr_freq'] ?? '',
'Speed_Before' => $record['before_fr_speed'] ?? '',
// AFTER FREE RUN
'Voltage_After' => $record['after_fr_vol'] ?? '',
'Current_After' => $record['after_fr_cur'] ?? '',
'Power_After' => $record['after_fr_pow'] ?? '',
'IR_Hot' => $record['after_fr_ir_hot'] ?? '',
'IR_Cool' => $record['after_fr_ir_cool'] ?? '',
'Leakage_Current' => $record['after_fr_leak_cur'] ?? '',
'Frequency_After' => $record['after_fr_freq'] ?? '',
'Speed_After' => $record['after_fr_speed'] ?? '',
// AFTER FREE RUN
'Voltage_After' => $record['after_fr_vol'] ?? '',
'Current_After' => $record['after_fr_cur'] ?? '',
'Power_After' => $record['after_fr_pow'] ?? '',
'IR_Hot' => $record['after_fr_ir_hot'] ?? '',
'IR_Cool' => $record['after_fr_ir_cool'] ?? '',
'Leakage_Current' => $record['after_fr_leak_cur'] ?? '',
'Frequency_After' => $record['after_fr_freq'] ?? '',
'Speed_After' => $record['after_fr_speed'] ?? '',
// LOCKED ROTOR TEST
'Voltage_Locked' => $record['locked_rt_volt'] ?? '',
'Current_Locked' => $record['locked_rt_cur'] ?? '',
'Power_Locked' => $record['locked_rt_pow'] ?? '',
// LOCKED ROTOR TEST
'Voltage_Locked' => $record['locked_rt_volt'] ?? '',
'Current_Locked' => $record['locked_rt_cur'] ?? '',
'Power_Locked' => $record['locked_rt_pow'] ?? '',
// Last 8 columns
'No_Load_Pickup_Voltage' => $record['no_load_pickup_volt'] ?? '',
'Room_Temp' => $record['room_temperature'] ?? '',
'High_Voltage_Test' => $record['hv_test'] ?? '',
'Batch_Number' => $record['batch_number'] ?? '',
'Batch_Count' => $record['batch_count'] ?? '',
'Result' => $record['result'] ?? '',
'Remark' => $record['remark'] ?? '',
'Tested_By' => $record['tested_by'] ?? '',
];
// Last 8 columns
'No_Load_Pickup_Voltage' => $record['no_load_pickup_volt'] ?? '',
'Room_Temp' => $record['room_temperature'] ?? '',
'High_Voltage_Test' => $record['hv_test'] ?? '',
'Result' => $record['result'] ?? '',
'Remark' => $record['remark'] ?? '',
];
});
}
else
{
$mappedData = collect($records)->map(function ($record) {
}
else
{
$mappedData = collect($records)->map(function ($record) {
return [
//'Date' => $record['created_at'] ?? '',
'Date' =>date('Y-m-d', strtotime($record['created_at'] ?? '')),
'Output' => $record['output'] ?? '',
'Motor SNo' => $record['serial_number'] ?? '',
'Item Code' => $record->motorTestingMaster->item->code ?? '',
'Motor Type' => $record->motorTestingMaster->item->description ?? '',
// 'Date' => $record['created_at'] ?? '',
'Date' =>date('Y-m-d', strtotime($record['created_at'] ?? '')),
'Output' => $record['output'] ?? '',
'Motor SNo' => $record['serial_number'] ?? '',
'Item Code' => $record->motorTestingMaster->item->code ?? '',
'Motor Type' => $record->motorTestingMaster->item->description ?? '',
'kw' => $record->motorTestingMaster->kw ?? '',
'hp' => $record->motorTestingMaster->hp ?? '',
'phase' => $record->motorTestingMaster->phase ?? '',
'isi_model' => $record->motorTestingMaster->isi_model ?? '',
'kw' => $record->motorTestingMaster->kw ?? '',
'hp' => $record->motorTestingMaster->hp ?? '',
'phase' => $record->motorTestingMaster->phase ?? '',
'isi_model' => $record->motorTestingMaster->isi_model ?? '',
// BEFORE FREE RUN
'Voltage_Before' => $record['before_fr_volt'] ?? '',
'Current_Before' => $record['before_fr_cur'] ?? '',
'Power_Before' => $record['before_fr_pow'] ?? '',
'Resistance_RY' => $record['before_fr_res_ry'] ?? '',
'Resistance_YB' => $record['before_fr_res_yb'] ?? '',
'Resistance_BR' => $record['before_fr_res_br'] ?? '',
'Insulation_Resistance_R' => $record['before_fr_ir_r'] ?? '',
'Insulation_Resistance_Y' => $record['before_fr_ir_y'] ?? '',
'Insulation_Resistance_B' => $record['before_fr_ir_b'] ?? '',
'Frequency_Before' => $record['before_fr_freq'] ?? '',
'Speed_Before' => $record['before_fr_speed'] ?? '',
// AFTER FREE RUN
'Voltage_After' => $record['after_fr_vol'] ?? '',
'Current_After' => $record['after_fr_cur'] ?? '',
'Power_After' => $record['after_fr_pow'] ?? '',
'IR_Hot_R' => $record['after_fr_ir_hot_r'] ?? '',
'IR_Hot_Y' => $record['after_fr_ir_hot_y'] ?? '',
'IR_Hot_B' => $record['after_fr_ir_hot_b'] ?? '',
'IR_Cool_R' => $record['after_fr_ir_cool_r'] ?? '',
'IR_Cool_Y' => $record['after_fr_ir_cool_y'] ?? '',
'IR_Cool_B' => $record['after_fr_ir_cool_b'] ?? '',
'Leakage_Current' => $record['after_fr_leak_cur'] ?? '',
'Frequency_After' => $record['after_fr_freq'] ?? '',
'Speed_After' => $record['after_fr_speed'] ?? '',
// AFTER FREE RUN
'Voltage_After' => $record['after_fr_vol'] ?? '',
'Current_After' => $record['after_fr_cur'] ?? '',
'Power_After' => $record['after_fr_pow'] ?? '',
'IR_Hot_R' => $record['after_fr_ir_hot_r'] ?? '',
'IR_Hot_Y' => $record['after_fr_ir_hot_y'] ?? '',
'IR_Hot_B' => $record['after_fr_ir_hot_b'] ?? '',
'IR_Cool_R' => $record['after_fr_ir_cool_r'] ?? '',
'IR_Cool_Y' => $record['after_fr_ir_cool_y'] ?? '',
'IR_Cool_B' => $record['after_fr_ir_cool_b'] ?? '',
'Leakage_Current' => $record['after_fr_leak_cur'] ?? '',
'Frequency_After' => $record['after_fr_freq'] ?? '',
'Speed_After' => $record['after_fr_speed'] ?? '',
// LOCKED ROTOR TEST
'Voltage_Locked' => $record['locked_rt_volt'] ?? '',
'Current_Locked' => $record['locked_rt_cur'] ?? '',
'Power_Locked' => $record['locked_rt_pow'] ?? '',
// LOCKED ROTOR TEST
'Voltage_Locked' => $record['locked_rt_volt'] ?? '',
'Current_Locked' => $record['locked_rt_cur'] ?? '',
'Power_Locked' => $record['locked_rt_pow'] ?? '',
// Last 8 columns
'No_Load_Pickup_Voltage' => $record['no_load_pickup_volt'] ?? '',
'Room_Temp' => $record['room_temperature'] ?? '',
'High_Voltage_Test' => $record['hv_test'] ?? '',
'Result' => $record['result'] ?? '',
'Remark' => $record['remark'] ?? '',
];
});
}
// Last 8 columns
'No_Load_Pickup_Voltage' => $record['no_load_pickup_volt'] ?? '',
'Room_Temp' => $record['room_temperature'] ?? '',
'High_Voltage_Test' => $record['hv_test'] ?? '',
'Batch_Number' => $record['batch_number'] ?? '',
'Batch_Count' => $record['batch_count'] ?? '',
'Result' => $record['result'] ?? '',
'Remark' => $record['remark'] ?? '',
'Tested_By' => $record['tested_by'] ?? '',
];
});
}
$view = $isAllStarDelta ? 'exports.export-three-phase-pdf' : 'exports.testingpanel-pdf';
$view = $isAllStarDelta ? 'exports.export-isi-three-phase-pdf' : 'exports.export-isi-pdf';
$pdf = Pdf::loadView($view, [
'records' => $mappedData,
'plant' => $plant,
]);
// $pdf = Pdf::loadView('exports.testingpanel-pdf',[
// $pdf = Pdf::loadView('exports.export-isi-pdf',[
// // ['records' => $mappedData]
// 'records' => $mappedData,
// 'plant' => $plant,
@@ -957,132 +1076,9 @@ class TestingPanelReadingResource extends Resource
'TestingPanelReading.pdf'
);
})
->icon('heroicon-o-document-arrow-down'),
BulkAction::make('export_isi_pdf')
->label('Export ISI Readings PDF')
->action(function ($records)
{
$records->load('motorTestingMaster.item');
$plantId = $records->first()?->plant_id;
})
->icon('heroicon-o-document-arrow-down'),
$plant = $plantId ? Plant::find($plantId) : null;
$isAllStarDelta = $records->every(function ($record) {
return $record->motorTestingMaster?->connection === 'Star-Delta';
});
// $hasStarDelta = $records->contains(function ($record) {
// return $record->motorTestingMaster?->connection === 'Star-Delta';
// });
//dd($isAllStarDelta);
if(!$isAllStarDelta)
{
$mappedData = collect($records)->map(function ($record) {
return [
// 'Date' => $record['created_at'] ?? '',
'Date' =>date('Y-m-d', strtotime($record['created_at'] ?? '')),
'Output' => $record['output'] ?? '',
'Motor SNo' => $record['serial_number'] ?? '',
'Item Code' => $record->motorTestingMaster->item->code ?? '',
'Motor Type' => $record->motorTestingMaster->item->description ?? '',
'kw' => $record->motorTestingMaster->kw ?? '',
'hp' => $record->motorTestingMaster->hp ?? '',
'phase' => $record->motorTestingMaster->phase ?? '',
'isi_model' => $record->motorTestingMaster->isi_model ?? '',
// AFTER FREE RUN
'Voltage_After' => $record['after_fr_vol'] ?? '',
'Current_After' => $record['after_fr_cur'] ?? '',
'Power_After' => $record['after_fr_pow'] ?? '',
'IR_Hot' => $record['after_fr_ir_hot'] ?? '',
'IR_Cool' => $record['after_fr_ir_cool'] ?? '',
'Leakage_Current' => $record['after_fr_leak_cur'] ?? '',
'Frequency_After' => $record['after_fr_freq'] ?? '',
'Speed_After' => $record['after_fr_speed'] ?? '',
// LOCKED ROTOR TEST
'Voltage_Locked' => $record['locked_rt_volt'] ?? '',
'Current_Locked' => $record['locked_rt_cur'] ?? '',
'Power_Locked' => $record['locked_rt_pow'] ?? '',
// Last 8 columns
'No_Load_Pickup_Voltage' => $record['no_load_pickup_volt'] ?? '',
'Room_Temp' => $record['room_temperature'] ?? '',
'High_Voltage_Test' => $record['hv_test'] ?? '',
'Result' => $record['result'] ?? '',
'Remark' => $record['remark'] ?? '',
];
});
}
else
{
$mappedData = collect($records)->map(function ($record) {
return [
// 'Date' => $record['created_at'] ?? '',
'Date' =>date('Y-m-d', strtotime($record['created_at'] ?? '')),
'Output' => $record['output'] ?? '',
'Motor SNo' => $record['serial_number'] ?? '',
'Item Code' => $record->motorTestingMaster->item->code ?? '',
'Motor Type' => $record->motorTestingMaster->item->description ?? '',
'kw' => $record->motorTestingMaster->kw ?? '',
'hp' => $record->motorTestingMaster->hp ?? '',
'phase' => $record->motorTestingMaster->phase ?? '',
'isi_model' => $record->motorTestingMaster->isi_model ?? '',
// AFTER FREE RUN
'Voltage_After' => $record['after_fr_vol'] ?? '',
'Current_After' => $record['after_fr_cur'] ?? '',
'Power_After' => $record['after_fr_pow'] ?? '',
'IR_Hot_R' => $record['after_fr_ir_hot_r'] ?? '',
'IR_Hot_Y' => $record['after_fr_ir_hot_y'] ?? '',
'IR_Hot_B' => $record['after_fr_ir_hot_b'] ?? '',
'IR_Cool_R' => $record['after_fr_ir_cool_r'] ?? '',
'IR_Cool_Y' => $record['after_fr_ir_cool_y'] ?? '',
'IR_Cool_B' => $record['after_fr_ir_cool_b'] ?? '',
'Leakage_Current' => $record['after_fr_leak_cur'] ?? '',
'Frequency_After' => $record['after_fr_freq'] ?? '',
'Speed_After' => $record['after_fr_speed'] ?? '',
// LOCKED ROTOR TEST
'Voltage_Locked' => $record['locked_rt_volt'] ?? '',
'Current_Locked' => $record['locked_rt_cur'] ?? '',
'Power_Locked' => $record['locked_rt_pow'] ?? '',
// Last 8 columns
'No_Load_Pickup_Voltage' => $record['no_load_pickup_volt'] ?? '',
'Room_Temp' => $record['room_temperature'] ?? '',
'High_Voltage_Test' => $record['hv_test'] ?? '',
'Result' => $record['result'] ?? '',
'Remark' => $record['remark'] ?? '',
];
});
}
$view = $isAllStarDelta ? 'exports.export-isi-three-phase-pdf' : 'exports.export-isi-pdf';
$pdf = Pdf::loadView($view, [
'records' => $mappedData,
'plant' => $plant,
]);
// $pdf = Pdf::loadView('exports.export-isi-pdf',[
// // ['records' => $mappedData]
// 'records' => $mappedData,
// 'plant' => $plant,
// ]);
return response()->streamDownload(
fn () => print($pdf->stream()),
'TestingPanelReading.pdf'
);
})
->icon('heroicon-o-document-arrow-down'),
]),
])

View File

@@ -2,18 +2,13 @@
namespace App\Filament\Resources;
use App\Filament\Exports\UserExporter;
use App\Filament\Imports\UserImporter;
use App\Filament\Resources\UserResource\Pages;
use App\Filament\Resources\UserResource\RelationManagers;
use App\Models\User;
use Filament\Facades\Filament;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Actions\ExportAction;
use Filament\Tables\Actions\ImportAction;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
@@ -85,7 +80,6 @@ class UserResource extends Resource
// ->label('ID')
// ->numeric()
// ->sortable(),
Tables\Columns\TextColumn::make('No.')
->label('No.')
->getStateUsing(function ($record, $livewire, $column, $rowLoop) {
@@ -97,23 +91,18 @@ class UserResource extends Resource
Tables\Columns\TextColumn::make('name')
->label('User Name')
->alignCenter()
->searchable()
->sortable(),
->sortable()
->searchable(),
Tables\Columns\TextColumn::make('email')
->label('Email')
->alignCenter()
->searchable()
->sortable(),
->sortable()
->searchable(),
Tables\Columns\TextColumn::make('email_verified_at')
->label('Email Verified At')
->dateTime()
->alignCenter()
->sortable(),
Tables\Columns\TextColumn::make('roles.name')
->label('Roles')
->alignCenter()
->searchable()
->sortable(),
Tables\Columns\TextColumn::make('created_at')
->label('Created At')
->dateTime()
@@ -145,18 +134,6 @@ class UserResource extends Resource
Tables\Actions\ForceDeleteBulkAction::make(),
Tables\Actions\RestoreBulkAction::make(),
]),
])
->headerActions([
ImportAction::make()
->importer(UserImporter::class)
->visible(function() {
return Filament::auth()->user()->can('view import user');
}),
ExportAction::make()
->exporter(UserExporter::class)
->visible(function() {
return Filament::auth()->user()->can('view export user');
}),
]);
}

View File

@@ -9,9 +9,4 @@ use Filament\Resources\Pages\CreateRecord;
class CreateUser extends CreateRecord
{
protected static string $resource = UserResource::class;
protected function getRedirectUrl(): string
{
return $this->getResource()::getUrl('create');
}
}

View File

@@ -1,206 +0,0 @@
<?php
namespace App\Filament\Resources;
use App\Filament\Exports\WorkGroupMasterExporter;
use App\Filament\Imports\WorkGroupMasterImporter;
use App\Filament\Resources\WorkGroupMasterResource\Pages;
use App\Filament\Resources\WorkGroupMasterResource\RelationManagers;
use App\Models\Line;
use App\Models\WorkGroupMaster;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use Filament\Forms\Components\Section;
use Filament\Facades\Filament;
use Filament\Tables\Actions\ImportAction;
use Filament\Tables\Actions\ExportAction;
use Illuminate\Validation\Rule;
class WorkGroupMasterResource extends Resource
{
protected static ?string $model = WorkGroupMaster::class;
protected static ?string $navigationIcon = 'heroicon-o-rectangle-stack';
protected static ?string $navigationGroup = 'Master Entries';
protected static ?int $navigationSort = 11;
public static function form(Form $form): Form
{
return $form
->schema([
Section::make('')
->schema([
Forms\Components\Select::make('plant_id')
->label('Plant')
->relationship('plant', 'name')
->reactive()
->columnSpan(1)
->required()
->afterStateUpdated(function ($state, $set, callable $get) {
$plantId = $get('plant_id');
if (!$plantId) {
$set('pqPlantError', 'Please select a plant first.');
$set('name', null);
$set('description', null);
$set('operation_number', null);
return;
}
$set('validationError', null);
$set('pqPlantError', null);
$set('name', null);
$set('description', null);
$set('operation_number', null);
})
->hint(fn ($get) => $get('pqPlantError') ? $get('pqPlantError') : null)
->hintColor('danger'),
Forms\Components\TextInput::make('name')
->label('Name')
->required()
->columnSpan(1)
->reactive()
->rule(function (callable $get) {
return Rule::unique('work_group_masters', 'name')
->where('plant_id', $get('plant_id'))
->ignore($get('id'));
}),
Forms\Components\TextInput::make('operation_number')
->label('Operation Number')
->numeric()
->columnSpan(1)
->reactive()
->required()
->rule(function (callable $get) {
return Rule::unique('work_group_masters', 'operation_number')
->where('plant_id', $get('plant_id'))
->ignore($get('id'));
}),
Forms\Components\TextInput::make('description')
->label('Description')
->required()
->reactive()
->columnSpan(['default' => 1, 'sm' => 3]),
Forms\Components\Hidden::make('created_by')
->default(Filament::auth()->user()?->name),
])
->columns(['default' => 1, 'sm' => 3]),
]);
}
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')
->alignCenter()
->searchable()
->sortable(),
Tables\Columns\TextColumn::make('name')
->label('Name')
->alignCenter()
->searchable()
->sortable(),
Tables\Columns\TextColumn::make('description')
->label('Description')
->alignCenter()
->searchable()
->sortable(),
Tables\Columns\TextColumn::make('operation_number')
->label('Operation Number')
->alignCenter()
->searchable()
->sortable(),
Tables\Columns\TextColumn::make('created_by')
->label('Created By')
->alignCenter()
->searchable()
->sortable(),
Tables\Columns\TextColumn::make('created_at')
->label('Created At')
->alignCenter()
->dateTime()
->sortable()
->toggleable(isToggledHiddenByDefault: true),
Tables\Columns\TextColumn::make('updated_at')
->label('Updated At')
->alignCenter()
->dateTime()
->sortable()
->toggleable(isToggledHiddenByDefault: true),
Tables\Columns\TextColumn::make('deleted_at')
->label('Deleted At')
->alignCenter()
->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(WorkGroupMasterImporter::class)
->visible(function() {
return Filament::auth()->user()->can('view import work group master');
}),
ExportAction::make()
->exporter(WorkGroupMasterExporter::class)
->visible(function() {
return Filament::auth()->user()->can('view export work group master');
}),
]);
}
public static function getRelations(): array
{
return [
//
];
}
public static function getPages(): array
{
return [
'index' => Pages\ListWorkGroupMasters::route('/'),
'create' => Pages\CreateWorkGroupMaster::route('/create'),
'view' => Pages\ViewWorkGroupMaster::route('/{record}'),
'edit' => Pages\EditWorkGroupMaster::route('/{record}/edit'),
];
}
public static function getEloquentQuery(): Builder
{
return parent::getEloquentQuery()
->withoutGlobalScopes([
SoftDeletingScope::class,
]);
}
}

View File

@@ -1,19 +0,0 @@
<?php
namespace App\Filament\Resources\WorkGroupMasterResource\Pages;
use App\Filament\Resources\WorkGroupMasterResource;
use App\Models\WorkGroupMaster;
use Filament\Actions;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\CreateRecord;
class CreateWorkGroupMaster extends CreateRecord
{
protected static string $resource = WorkGroupMasterResource::class;
protected function getRedirectUrl(): string
{
return $this->getResource()::getUrl('create');
}
}

View File

@@ -1,22 +0,0 @@
<?php
namespace App\Filament\Resources\WorkGroupMasterResource\Pages;
use App\Filament\Resources\WorkGroupMasterResource;
use Filament\Actions;
use Filament\Resources\Pages\EditRecord;
class EditWorkGroupMaster extends EditRecord
{
protected static string $resource = WorkGroupMasterResource::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\WorkGroupMasterResource\Pages;
use App\Filament\Resources\WorkGroupMasterResource;
use Filament\Actions;
use Filament\Resources\Pages\ListRecords;
class ListWorkGroupMasters extends ListRecords
{
protected static string $resource = WorkGroupMasterResource::class;
protected function getHeaderActions(): array
{
return [
Actions\CreateAction::make(),
];
}
}

View File

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

View File

@@ -0,0 +1,90 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Gemini\Laravel\Facades\Gemini;
class ChatbotController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index()
{
//
}
/**
* Store a newly created resource in storage.
*/
// public function handleMessage(Request $request)
// {
// $request->validate(['message' => 'required|string']);
// $userMessage = $request->input('message');
// try {
// $result = Gemini::geminiPro()->generateContent($userMessage);
// $reply = $result->text() ?? 'Sorry, no response from Gemini AI.';
// } catch (\Exception $e) {
// \Log::error('Gemini API Exception: ' . $e->getMessage(), ['trace' => $e->getTraceAsString()]);
// if (config('app.debug')) {
// return response()->json(['reply' => 'Error: ' . $e->getMessage()], 500);
// }
// return response()->json(['reply' => 'Error communicating with Gemini AI. Please try again later.'], 500);
// }
// return response()->json(['reply' => $reply]);
// }
// public function handleMessage(Request $request)
// {
// $request->validate([
// 'message' => 'required|string'
// ]);
// $apiKey = env('GEMINI_API_KEY'); // Put this in .env
// $response = Http::withHeaders([
// 'Content-Type' => 'application/json',
// 'x-goog-api-key' => $apiKey
// ])->post('https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent', [
// 'contents' => [
// ['parts' => [['text' => $request->message]]]
// ]
// ]);
// if ($response->successful()) {
// return response()->json([
// 'reply' => $response->json()['candidates'][0]['content']['parts'][0]['text'] ?? 'No response.'
// ]);
// }
// return response()->json(['reply' => 'Failed to fetch response.'], 500);
// }
/**
* Display the specified resource.
*/
public function show(string $id)
{
//
}
/**
* Update the specified resource in storage.
*/
public function update(Request $request, string $id)
{
//
}
/**
* Remove the specified resource from storage.
*/
public function destroy(string $id)
{
//
}
}

View File

@@ -1,143 +0,0 @@
<?php
namespace App\Http\Controllers;
use App\Models\EquipmentMaster;
use App\Models\Machine;
use App\Models\Plant;
use Illuminate\Http\Request;
class EquipmentMasterController extends Controller
{
/**
* Display a listing of the resource.
*/
public function equipmentMasterData(Request $request)
{
$expectedUser = env('API_AUTH_USER');
$expectedPw = env('API_AUTH_PW');
$header_auth = $request->header('Authorization');
$expectedToken = $expectedUser . ':' . $expectedPw;
if ("Bearer " . $expectedToken != $header_auth) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => 'Invalid authorization token!'
], 403);
}
$plantCode = $request->header('plant-code');
$workCenter = $request->header('work-center');
if (!$plantCode) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Plant Code value can't be empty"
], 404);
}
else if (!$workCenter) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Work Center value can't be empty"
], 404);
}
$plant = Plant::where('code', $plantCode)->first();
if (!$plant)
{
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Plant Code '{$plantCode}' not found!"
], 404);
}
$plantId = $plant->id;
$machine = Machine::where('work_center', $workCenter)->first();
$machinePlant = Machine::where('work_center', $workCenter)
->where('plant_id', $plantId)
->first();
if (!$machine)
{
return response()->json([
'status_code' => 'ERROR',
'status_description' => "work center '{$workCenter}' not found!"
], 404);
}
if (!$machinePlant) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Work center '{$workCenter}' not found for the plant code '{$plant->code}'!"
], 404);
}
$machineId = $machine->id;
$machineExists = EquipmentMaster::where('plant_id', $plantId)
->where('machine_id', $machineId)
->first();
if (!$machineExists) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Work center '{$machine->work_center}' not found for the plant code '{$plant->code}' in Equipment Master!"
], 404);
}
$equipments = EquipmentMaster::where('plant_id', $plant->id)
->where('machine_id', $machineId)
->get([
// 'name',
'make',
'model',
'equipment_number',
'calibrated_on',
'next_calibration_date',
'calibrated_by',
]);
return response()->json([
'equipments' => $equipments
], 200);
}
/**
* Store a newly created resource in storage.
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*/
public function show(string $id)
{
//
}
/**
* Update the specified resource in storage.
*/
public function update(Request $request, string $id)
{
//
}
/**
* Remove the specified resource from storage.
*/
public function destroy(string $id)
{
//
}
}

View File

@@ -40,6 +40,18 @@ class InvoiceValidationController extends Controller
try
{
$plantCode = $request->header('plant-code');
$invoiceNo = $request->header('invoice-number');
$lineQuan = $request->header('line-quantity');
if (!$plantCode) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Plant Code value can't be empty"
], 404);
}
$data = $request->all();
if (!isset($data['plant_code']) || trim($data['plant_code']) == '')
@@ -58,7 +70,8 @@ class InvoiceValidationController extends Controller
}
$plant = Plant::where('code', $data['plant_code'])->first();
if (!$plant) {
if (!$plant)
{
return response()->json([
'status_code' => 'ERROR',
'status_description' => 'Plant not found!'

View File

@@ -41,11 +41,11 @@ class MachineController extends Controller
], 403);
}
$machines = Machine::with('plant')->with('workGroupMaster')->orderBy('plant_id')->get();
$machines = Machine::with('plant')->with('line')->orderBy('plant_id')->get();
$machinesData = $machines->map(function($machine) {
return [
'plant_code' => $machine->plant ? (String)$machine->plant->code : "",
'group_work_center' => $machine->workGroupMaster ? (String)$machine->workGroupMaster->name : "",
'group_work_center' => $machine->line->group_work_center ?? "",
'work_center' => $machine->work_center ?? "",
];
});

View File

@@ -73,6 +73,68 @@ class PalletController extends Controller
// $mpdf->Output('qr-label.pdf', 'I');
}
// public function downloadQrPdf($palletNo)
// {
// $qrCode = new QrCode($palletNo);
// $output = new Output\Png();
// $qrBinary = $output->output($qrCode, 100);
// $qrBase64 = base64_encode($qrBinary);
// $htmlBlock = '
// <table class="sticker-table">
// <tr>
// <td class="qr-cell">
// <img class="qr" src="data:image/png;base64,' . $qrBase64 . '" alt="QR" />
// </td>
// <td class="text-cell">
// ' . htmlspecialchars($palletNo) . '
// </td>
// </tr>
// </table>';
// return '
// <html>
// <head>
// <style>
// body { margin: 0; padding: 0; width: 60mm; height: auto; font-size: 10pt; font-family: DejaVu Sans, sans-serif; }
// .sticker-table { width: 60mm; height: 14mm; border-collapse: collapse;}
// .qr-cell { width: 14mm;}
// .text-cell { text-align: left; vertical-align: middle; font-size: 22pt; padding-left: 1mm; padding-top: 2mm; white-space: nowrap; font-weight: bold; }
// img.qr { width: 19mm; height: 19mm; display: block; margin-left: -2mm;}
// </style>
// </head>
// <body>
// ' . $htmlBlock . $htmlBlock . '
// <script>
// window.onload = function () {
// window.print();
// setTimeout(function () {
// window.close();
// }, 1000); // Wait 1 second before closing
// };
// </script>
// </body>
// </html>';
// // $mpdf = new Mpdf([
// // 'mode' => 'utf-8',
// // 'format' => [60, 14],
// // 'margin_left' => 0,
// // 'margin_right' => 0,
// // 'margin_top' => 0,
// // 'margin_bottom' => 0,
// // // 'tempDir' => '/var/www/storage/mpdf-tmp',
// // ]);
// // $mpdf->WriteHTML($html);
// // // Output PDF to browser for printing
// // $mpdf->Output('qr-label.pdf', 'I');
// }
/**
* Store a newly created resource in storage.
*/
public function downloadQrPdf($palletNo)
{
$qrCode = new QrCode($palletNo);
@@ -80,7 +142,7 @@ class PalletController extends Controller
$qrBinary = $output->output($qrCode, 100);
$qrBase64 = base64_encode($qrBinary);
$htmlBlock = '
$htmlBlock = '
<table class="sticker-table">
<tr>
<td class="qr-cell">
@@ -92,48 +154,43 @@ class PalletController extends Controller
</tr>
</table>';
return '
<html>
<head>
<style>
body { margin: 0; padding: 0; width: 60mm; height: auto; font-size: 10pt; font-family: DejaVu Sans, sans-serif; }
.sticker-table { width: 60mm; height: 14mm; border-collapse: collapse; page-break-after: always; }
.qr-cell { width: 14mm; text-align: right; vertical-align: bottom; padding-left: -8mm; padding-top: 0mm; }
.text-cell { text-align: left; vertical-align: middle; font-size: 22pt; padding-left: 1mm; padding-top: 2mm; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; font-weight: bold; }
img.qr { width: 19mm; height: 19mm; display: block; }
</style>
</head>
<body>
' . $htmlBlock . $htmlBlock . '
<script>
window.onload = function () {
window.print();
setTimeout(function () {
window.close();
}, 1000); // Wait 1 second before closing
};
</script>
</body>
</html>';
$html = '
<html>
<head>
<style>
body { margin: 0; padding: 0; width: 60mm; height: auto; font-size: 10pt; font-family: DejaVu Sans, sans-serif; }
.sticker-table { width: 60mm; height: 14mm; border-collapse: collapse; page-break-after: always; }
.qr-cell { width: 14mm; text-align: right; vertical-align: bottom; padding-left: 0mm; padding-top: 0mm; }
.text-cell { text-align: left; vertical-align: middle; font-size: 22pt; padding-left: 1mm; padding-top: 2mm; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; font-weight: bold; }
img.qr { width: 16mm; height: 16mm; display: block; margin-left: -2mm;}
</style>
</head>
<body>
' . $htmlBlock . $htmlBlock . '
<script>
window.onload = function () {
window.print();
setTimeout(function () {
window.close();
}, 1000); // Wait 1 second before closing
};
</script>
</body>
</html>';
// $mpdf = new Mpdf([
// 'mode' => 'utf-8',
// 'format' => [60, 14],
// 'margin_left' => 0,
// 'margin_right' => 0,
// 'margin_top' => 0,
// 'margin_bottom' => 0,
// // 'tempDir' => '/var/www/storage/mpdf-tmp',
// ]);
$mpdf = new Mpdf([
'mode' => 'utf-8',
'format' => [60, 14],
'margin_left' => 0,
'margin_right' => 0,
'margin_top' => 0,
'margin_bottom' => 0,
// 'tempDir' => '/var/www/storage/mpdf-tmp',
]);
// $mpdf->WriteHTML($html);
// // Output PDF to browser for printing
// $mpdf->Output('qr-label.pdf', 'I');
$mpdf->WriteHTML($html);
$mpdf->Output('qr-label.pdf', 'I');
}
/**
* Store a newly created resource in storage.
*/
public function store(Request $request)
{
//

View File

@@ -1,94 +0,0 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Storage;
class PdfController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index()
{
//
}
/**
* Store a newly created resource in storage.
*/
public function getPdf(Request $request)
{
// Validate input
// $request->validate([
// 'filename' => 'required|string',
// ]);
$expectedUser = env('API_AUTH_USER');
$expectedPw = env('API_AUTH_PW');
$header_auth = $request->header('Authorization');
$expectedToken = $expectedUser . ':' . $expectedPw;
if ("Bearer " . $expectedToken != $header_auth)
{
return response()->json([
'status_code' => 'ERROR',
'status_description' => 'Invalid authorization token!'
], 403);
}
$filename = $request->header('process-order');
if (!$filename)
{
return response()->json(['error' => 'Missing file-name header'], 400);
}
$filename = basename($filename);
// Ensure the file has .pdf extension
if (!str_ends_with(strtolower($filename), '.pdf')) {
$filename .= '.pdf';
}
$filePath = "uploads/ProcessOrder/" . $filename;
if (!Storage::disk('local')->exists($filePath)) {
return response()->json(['error' => 'File not found'], 404);
}
$file = Storage::disk('local')->get($filePath);
$mimeType = Storage::disk('local')->mimeType($filePath);
return Response::make($file, 200, [
'Content-Type' => $mimeType,
'Content-Disposition' => 'inline; filename="' . $filename . '"',
]);
}
/**
* Display the specified resource.
*/
public function show(string $id)
{
//
}
/**
* Update the specified resource in storage.
*/
public function update(Request $request, string $id)
{
//
}
/**
* Remove the specified resource from storage.
*/
public function destroy(string $id)
{
//
}
}

View File

@@ -1,291 +0,0 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Str;
use Illuminate\Support\Facades\Schema;
class SapFileController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index()
{
//
}
/**
* Store a newly created resource in storage.
*/
// public function store(Request $request)
// {
// //
// }
public function getSapData(Request $request)
{
}
public function readFiles(Request $request)
{
$expectedUser = env('API_AUTH_USER');
$expectedPw = env('API_AUTH_PW');
$header_auth = $request->header('Authorization');
$expectedToken = $expectedUser . ':' . $expectedPw;
if ("Bearer " . $expectedToken != $header_auth)
{
return response()->json([
'status_code' => 'ERROR',
'status_description' => 'Invalid authorization token!'
], 403);
}
$plantCode = $request->header('plant-code');
if ($plantCode == null || $plantCode == '')
{
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Plant code can't be empty!"
], 400);
}
else if (Str::length($plantCode) < 4 || !is_numeric($plantCode) || !preg_match('/^[1-9]\d{3,}$/', $plantCode))
{
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Invalid plant code found!"
], 400);
}
$path = "/LaserPRD/{$plantCode}";
// $isDir = is_dir($path);
// $isReadable = is_readable($path);
// Check if folder exists
if (!is_dir($path)) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Folder for plant-code {$plantCode} not found!"
], 404);
}
if (!is_readable($path)) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Folder for plant-code {$plantCode} exists but is not readable!"
], 500);
}
// Scan folder
$allFiles = scandir($path);
if ($allFiles === false) {
return response()->json([
'status' => 'error',
'status_description' => 'Failed to scan directory',
], 500);
}
$files = array_filter($allFiles, function($item) use ($path) {
$fullPath = $path . '/' . $item;
return @is_file($fullPath) && pathinfo($item, PATHINFO_EXTENSION) === 'txt';
});
if (empty($files)) {
return response()->json([
'status' => 'error',
'status_description' => 'No text files found',
], 404);
}
// $data = [];
// foreach ($files as $file)
// {
// $filePath = $path . '/' . $file;
// $content = file_get_contents($filePath);
// $data[] = [
// 'filename' => $file,
// 'content' => $content,
// ];
// }
// return response()->json([
// 'status' => 'success',
// 'files' => $data,
// ]);
//$fileName = 'RMGLAS02-1725800-1.txt';
$fileName = array_values($files)[0];
$filePath = $path . '/' . $fileName;
$lines = file($filePath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$headerLine = array_shift($lines); // removes first line
if (!$lines) {
return response()->json(['status' => 'ERROR', 'message' => 'File is empty'], 400);
}
// Debug: return first 5 lines to check reading
// return response()->json([
// 'status' => 'DEBUG_LINES',
// 'file' => $fileName,
// 'lines_sample' => array_slice($lines, 0, 5) // first 5 lines
// ]);
if (!file_exists($filePath) || !is_readable($filePath)) {
return response()->json([
'status' => 'ERROR',
'message' => "File {$fileName} not found or not readable"
], 500);
}
// $table = 'class_characteristics';
// $columns = Schema::getColumnListing($table); // returns lowercase column names
// $rows = [];
// foreach ($lines as $line) {
// $values = str_getcsv($line); // split by comma
// $row = [];
// foreach ($columns as $index => $column) {
// $value = $values[$index] ?? null; // if missing, set null
// if ($value === '') $value = null; // empty string -> null
// $row[$column] = $value;
// }
// $rows[] = $row;
// }
// return response()->json([
// 'status' => 'DEBUG_ROWS',
// 'rows_sample' => array_slice($rows, 0, 5),
// ]);
// Insert into database
// foreach ($rows as $row) {
// \App\Models\ClassCharacteristic::create($row);
// }
// return response()->json([
// 'status' => 'SUCCESS',
// 'rows_imported' => count($rows),
// ]);
// Prepare arrays
// $serialNumbers = [];
// $remainingRows = [];
// foreach ($lines as $line)
// {
// $values = str_getcsv($line);
// // Debug: make sure CSV split is correct
// if (count($values) < 6) {
// return response()->json([
// 'status' => 'ERROR',
// 'message' => 'In text file has fewer than 6 columns',
// 'line' => $line
// ], 400);
// }
// $serialNumbers[] = $values[5] ?? null;
// $remainingRow = $values;
// unset($remainingRow[5]);
// // $remainingRow = array_values($remainingRow); // reindex
// // $remainingRows[] = $remainingRow;
// $remainingRow = array_values($remainingRow); // reindex
// // Only add unique remaining rows
// if (!in_array($remainingRow, $remainingRows, true)) {
// $remainingRows[] = $remainingRow;
// }
// }
// return response()->json([
// 'status' => 'SUCCESS',
// 'serial_numbers' => $serialNumbers,
// 'remaining_rows_sample' => array_slice($remainingRows, 0, 5), // just first 5 for debug
// ]);
$serialNumbers = [];
$remainingRow = null;
$invalidSerials = [];
foreach ($lines as $line) {
$values = str_getcsv($line);
if (count($values) < 6) {
return response()->json([
'status' => 'ERROR',
'message' => 'Text file row has fewer than 6 columns',
'line' => $line
], 400);
}
// Collect serial number
// $serialNumbers[] = $values[5] ?? null;
$serial = $values[5] ?? null;
$serialNumbers[] = $serial;
if ($serial == null || strlen($serial) < 13) {
$invalidSerials[] = $serialNumbers;
}
// Store remaining row only once
if ($remainingRow == null) {
$remainingRow = $values;
unset($remainingRow[5]); // remove serial number
$remainingRow = array_values($remainingRow); // reindex
}
}
if (!empty($invalidSerials)) {
return response()->json([
'status' => 'ERROR',
'status_description' => 'Some serial numbers are invalid (less than 13 characters)',
'invalid_serials' => $invalidSerials
], 400);
}
return response()->json([
'status' => 'SUCCESS',
'serial_numbers' => $serialNumbers,
'remaining_row' => $remainingRow, // only one copy
]);
}
/**
* Display the specified resource.
*/
public function show(string $id)
{
//
}
/**
* Update the specified resource in storage.
*/
public function update(Request $request, string $id)
{
//
}
/**
* Remove the specified resource from storage.
*/
public function destroy(string $id)
{
//
}
}

View File

@@ -8,7 +8,6 @@ use App\Models\Machine;
use App\Models\MotorTestingMaster;
use App\Models\Plant;
use App\Models\TestingPanelReading;
use App\Models\WorkGroupMaster;
use DB;
use Filament\Notifications\Notification;
use Illuminate\Http\Request;
@@ -48,6 +47,7 @@ class TestingPanelController extends Controller
], 403);
}
$data = $request->all();
if ($data['plant_code'] == null || $data['plant_code'] == '')
@@ -78,32 +78,19 @@ class TestingPanelController extends Controller
$plantId = $plant->id;
if ($data['line_name'] == null || $data['line_name'] == '')
{
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Group work center can't be empty!"
], 400);
}
else if (Str::length($data['line_name']) < 0)
{
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Invalid group work center found!"
], 400);
}
$gWorkCenter = WorkGroupMaster::where('name', $data['line_name'])->first();
if (!$gWorkCenter)
$line = Line::where('group_work_center', $data['line_name'])->first();
if (!$line)
{
//return response("Line not found.", 400)->header('Content-Type', 'text/plain');
return response()->json([
'status_code' => 'ERROR',
'status_description' => 'Group work center not found!'
], 400);
}
$gWorkCenter = WorkGroupMaster::where('name', $data['line_name'])->where('plant_id', $plantId)->first();
if (!$gWorkCenter)
$line = Line::where('group_work_center', $data['line_name'])->where('plant_id', $plantId)->first();
if (!$line)
{
//return response( "Line not found for the specified plant : {$data['plant_code']}",400)->header('Content-Type', 'text/plain');
return response()->json([
@@ -112,26 +99,13 @@ class TestingPanelController extends Controller
], 400);
}
$gWorkCenterId = $gWorkCenter->id;
if ($data['machine_name'] == null || $data['machine_name'] == '')
{
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Work center can't be empty!"
], 400);
}
else if (Str::length($data['machine_name']) < 0)
{
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Invalid work center found!"
], 400);
}
$lineId = $line->id;
$machine = Machine::where('work_center', $data['machine_name'])->first();
if (!$machine)
{
// return response('Machine not found', 400)->header('Content-Type', 'text/plain');
return response()->json([
'status_code' => 'ERROR',
'status_description' => 'Work center not found!'
@@ -139,15 +113,18 @@ class TestingPanelController extends Controller
}
$machine = Machine::where('work_center', $data['machine_name'])->where('plant_id', $plantId)->first();
if (!$machine)
{
// return response("Machine not found for the specified plant : {$data['plant_code']}", 400)->header('Content-Type', 'text/plain');
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Work center not found for the specified plant : '{$data['plant_code']}'!"
], 400);
}
$machine = Machine::where('work_center', $data['machine_name'])->where('work_group_master_id', $gWorkCenterId)->first();
$machine = Machine::where('work_center', $data['machine_name'])->where('line_id', $lineId)->first();
if (!$machine)
{
// return response("Machine not found for the specified line : {$data['line_name']}", 400)->header('Content-Type', 'text/plain');
@@ -158,15 +135,17 @@ class TestingPanelController extends Controller
}
$machine = Machine::where('work_center', $data['machine_name'])->where('plant_id', $plantId)->where('work_group_master_id', $gWorkCenterId)->first();
$machine = Machine::where('work_center', $data['machine_name'])->where('plant_id', $plantId)->where('line_id', $lineId)->first();
if (!$machine) {
// return response('Machine not found for the specified plant and line', 400)
// ->header('Content-Type', 'text/plain');
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Work center not found for the specified Plant : '{$data['plant_code']}' and Group work center : '{$data['line_name']}'!"
'status_description' => 'Work center not found for the specified plant and group work center!'
], 400);
}
$lineId = $machine->line_id;
$machineId = $machine->id;
try
@@ -283,13 +262,13 @@ class TestingPanelController extends Controller
$updateCountString = (string)$newUpdateCount;
$row = [
$row =
[
'plant_id' => $plantId,
'line_id' => $lineId,
'machine_id' => $machineId,
'motor_testing_master_id'=> $motorTestingMasterId,
'serial_number' => $serial['serial_number'] ?? null,
'winded_serial_number' => $serial['winded_serial_number'] ?? null,
'output' => $serial['output'] ?? null,
'before_fr_volt' => $serial['before_fr_volt'] ?? null,
'before_fr_cur' => $serial['before_fr_cur'] ?? null,
@@ -479,7 +458,6 @@ class TestingPanelController extends Controller
}
$output = [
"mot_subassembly_code" => $motorTestingMaster->subassembly_code ?? "",
"mot_model_name" => $description,
"mot_non_isi_model" => $motorTestingMaster->isi_model ? "0" :"1",
"mot_phase" => $motorTestingMaster->phase ?? "",
@@ -510,7 +488,7 @@ class TestingPanelController extends Controller
"mot_noload_pow_ll" => $motorTestingMaster->noload_pow_ll ?? "",
"mot_noload_pow_ul" => $motorTestingMaster->noload_pow_ul ?? "",
"mot_noload_spd_ll" => $motorTestingMaster->noload_spd_ll ?? "",
"mot_noload_spd_ul" => $motorTestingMaster->noload_spd_ul ?? ""
"mot_noload_spd_ul" => $motorTestingMaster->noload_spd_ul ?? "",
];
return response()->json($output, 200);

View File

@@ -1,34 +0,0 @@
<?php
namespace App\Livewire;
use Livewire\Component;
use Livewire\Attributes\On;
class NotificationSound extends Component
{
protected $listeners = ['playNotificationSound' => 'playSound', 'playWarnSound' => 'playWarnSound', 'beepSound' => 'beepSound'];
public function playSound()
{
$this->dispatch('play-notification-sound');
}
public function playWarnSound()
{
//dd('test');
$this->dispatch('play-warn-sound');
}
public function beepSound()
{
//dd('test');
$this->dispatch('play-beep-sound');
}
public function render()
{
return view('livewire.notification-sound');
}
}

View File

@@ -2,7 +2,6 @@
namespace App\Mail;
use DateTime;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
@@ -15,14 +14,12 @@ class ProductionMail extends Mailable
use Queueable, SerializesModels;
public $tableData;
public $scheduleType;
/**
* Create a new message instance.
*/
public function __construct($scheduleType,$tableData = [])
public function __construct($tableData = [])
{
$this->scheduleType = $scheduleType;
$this->tableData = $tableData ?? [];
}
@@ -39,57 +36,19 @@ class ProductionMail extends Mailable
/**
* Get the message content definition.
*/
// public function content(): Content
// {
// return new Content(
// view: 'mail.production_report',
// with: [
// 'company' => "CRI Digital Manufacturing Solutions",
// 'greeting' => "Dear Sir/Madam,<br><br>Kindly find the attached production report status details for the 'Target Quantity' and 'Production Quantity' count,",
// // 'greeting' => "Dear Sir/Madam,<br><br>Kindly find the attached production report status details for the 'Target Quantity' and 'Production Quantity' count,<br>" . $reportPeriod,
// 'tableData' => $this->tableData,
// 'wishes' => "Thanks & Regards,<br>CRI Digital Manufacturing Solutions"
// ],
// );
// }
public function content(): Content
{
$greeting = "Dear Sir/Madam,<br><br>Kindly find the attached production report status details for the 'Target Quantity' and 'Production Quantity' count,";
if ($this->scheduleType == 'Daily') {
$fromDate = (new DateTime('yesterday 08:00'))->format('d/m/Y H:i') . ':000';
$toDate = (new DateTime('today 07:59'))->format('d/m/Y H:i') . ':999';
$reportPeriod = "The following report presents results from: $fromDate to $toDate.";
$greeting .= $reportPeriod;
}
if ($this->scheduleType == 'Hourly') {
$now = now();
$fromHour = $now->copy()->subHour()->format('H:i:s');
$toHour = $now->format('H:i:s');
$reportDate = $now->format('d/m/Y');
$greeting .= "The following report presents results from: $reportDate, $fromHour to $toHour.";
}
if ($this->scheduleType == 'Live') {
$now = now();
$fromMinute = $now->copy()->subMinute()->format('d/m/Y H:i:s');
$toMinute = $now->format('d/m/Y H:i:s');
$greeting .= "The following report presents results from: $fromMinute to $toMinute.";
}
return new Content(
return new Content(
view: 'mail.production_report',
with: [
'company' => "CRI Digital Manufacturing Solutions",
'greeting' => $greeting,
'greeting' => "Dear Sir/Madam,<br><br>Kindly find the attached production report status details for the 'Target Quantity' and 'Production Quantity' count,",
'tableData' => $this->tableData,
'wishes' => "Thanks & Regards,<br>CRI Digital Manufacturing Solutions"
],
);
}
/**
* Get the attachments for the message.
*

View File

@@ -2,7 +2,6 @@
namespace App\Mail;
use DateTime;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
@@ -17,16 +16,16 @@ class test extends Mailable
public $materialTableData;
public $bundleTableData;
public $schedule;
/**
* Create a new message instance.
*/
public function __construct($serialTableData, $materialTableData, $bundleTableData, $schedule)
// public function __construct($tableData = [])
// {
// $this->tableData = $tableData ?? [];
// }
public function __construct($serialTableData, $materialTableData, $bundleTableData)
{
$this->schedule = $schedule;
$this->serialTableData = $serialTableData;
$this->materialTableData = $materialTableData;
$this->bundleTableData = $bundleTableData;
@@ -45,54 +44,18 @@ class test extends Mailable
/**
* Get the message content definition.
*/
// public function content(): Content
// {
// return new Content(
// view: 'mail.test_mail',
// with: [
// 'company' => "CRI Digital Manufacturing Solutions",
// 'greeting' => "Dear Sir/Madam,<br><br>Kindly find the attached invoice status details for the 'Total Number of Invoices' and 'Scanned Number of Invoices' count,",
// //'tableData' => $this->tableData,
// 'serialTableData' => $this->serialTableData,
// 'materialTableData' => $this->materialTableData,
// 'bundleTableData' => $this->bundleTableData,
// 'wishes' => "Thanks & Regards,<br>CRI Digital Manufacturing Solutions"
// ],
// );
// }
public function content(): Content
{
$greeting = "Dear Sir/Madam,<br><br>Kindly find the attached invoice status details for the 'Total Number of Invoices' and 'Scanned Number of Invoices' count,";
if ($this->schedule == 'Daily') {
$fromDate = (new DateTime('yesterday 08:00'))->format('d/m/Y H:i') . ':000';
$toDate = (new DateTime('today 07:59'))->format('d/m/Y H:i') . ':999';
$reportPeriod = "The following report presents results from: $fromDate to $toDate.";
//$greeting .= $reportPeriod;
$greeting .= "<br><br>$reportPeriod";
}
if ($this->schedule == 'Hourly') {
$now = now();
$fromHour = $now->copy()->subHour()->format('H:i:s');
$toHour = $now->format('H:i:s');
$reportDate = $now->format('d/m/Y');
$greeting .= "The following report presents results from: $reportDate, $fromHour to $toHour.";
}
if ($this->schedule == 'Live') {
$now = now();
$fromMinute = $now->copy()->subMinute()->format('d/m/Y H:i:s');
$toMinute = $now->format('d/m/Y H:i:s');
$greeting .= "The following report presents results from: $fromMinute to $toMinute.";
}
return new Content(
view: 'mail.test_mail',
with: [
// with: [
// 'name' => "CRI Digital Manufacturing Solutions<br><br>Dear Sir/Madam,<br><br> Kindly find the attached invoice status details for the 'Total Number Of Invoices' and 'Scanned Number Of Invoices' count,",
// 'tableData' => $this->tableData,
// 'wishes' => "Thanks & Regards<br><br>CRI Digital Manufacturing Solutions"
// ],
with: [
'company' => "CRI Digital Manufacturing Solutions",
'greeting' => $greeting,
//'greeting' => "Dear Sir/Madam,<br><br>Kindly find the attached invoice status details for the 'Total Number of Invoices' and 'Scanned Number of Invoices' count,",
'greeting' => "Dear Sir/Madam,<br><br>Kindly find the attached invoice status details for the 'Total Number of Invoices' and 'Scanned Number of Invoices' count,",
//'tableData' => $this->tableData,
'serialTableData' => $this->serialTableData,
'materialTableData' => $this->materialTableData,

View File

@@ -1,40 +0,0 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\SoftDeletes;
class EquipmentMaster extends Model
{
use SoftDeletes;
protected $fillable = [
'plant_id',
'machine_id',
'name',
'description',
'make',
'model',
'equipment_number',
'instrument_serial_number',
'calibrated_on',
'frequency',
'next_calibration_date',
'calibrated_by',
'calibration_certificate',
'created_by',
'updated_by',
];
public function plant(): BelongsTo
{
return $this->belongsTo(Plant::class);
}
public function machine(): BelongsTo
{
return $this->belongsTo(Machine::class);
}
}

View File

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

Some files were not shown because too many files have changed in this diff Show More