Initial commit for new repo
All checks were successful
Scan for leaked secrets using Kingfisher / kingfisher-secrets-scan (push) Successful in 1m4s

This commit is contained in:
dhanabalan
2025-12-16 17:05:04 +05:30
commit 3f0d529640
862 changed files with 141157 additions and 0 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,8 @@
<?php
namespace App\Http\Controllers;
abstract class Controller
{
//
}

View File

@@ -0,0 +1,143 @@
<?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

@@ -0,0 +1,836 @@
<?php
namespace App\Http\Controllers;
use App\Models\InvoiceValidation;
use App\Models\Item;
use App\Models\Plant;
use App\Models\StickerMaster;
use Illuminate\Http\Request;
use Str;
class InvoiceValidationController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index()
{
//
}
/**
* Store a newly created resource in storage.
*/
public function serialInvoice(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);
}
try
{
$data = $request->all();
if (!isset($data['plant_code']) || trim($data['plant_code']) == '')
{
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Plant code can't be empty!"
], 400);
}
else if (Str::length($data['plant_code']) < 4 || !is_numeric($data['plant_code']) || !preg_match('/^[1-9]\d{3,}$/', $data['plant_code']))
{
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Invalid plant code found!"
], 400);
}
$plant = Plant::where('code', $data['plant_code'])->first();
if (!$plant) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => 'Plant not found!'
], 400);
}
$plantId = $plant->id;
if (!isset($data['item_codes']) || !is_array($data['item_codes']) || count($data['item_codes']) == 0)
{
return response()->json([
'status_code' => 'ERROR',
'status_description' => 'item_codes is required and must be a non-empty array!'
], 400);
}
//..Checking invoice number for empty or invalid length
$invoiceNumber = $data['invoice_number'] ?? null;
if (!$invoiceNumber || trim($invoiceNumber) == '')
{
return response()->json([
'status_code' => 'ERROR',
'status_description' => 'invoice_number is required!'
], 400);
}
else if (strlen(trim($invoiceNumber)) < 7)
{
return response()->json([
'status_code' => 'ERROR',
'status_description' => 'invoice number must contain at least 7 alphanumeric characters.'
], 400);
}
//..Checking item codes for invalid length
$invalidItem = [];
foreach ($data['item_codes'] as $item) {
if (!isset($item['item_code']) || strlen(trim($item['item_code'])) < 6) {
$invalidItem[] = $item['item_code'] ?? '(missing item_code)';
}
}
if (!empty($invalidItem)) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => 'The following item codes have invalid length (less than 6 characters)',
'invalid_item_codes' => $invalidItem
], 400);
}
//..Checking item codes for invalid characters
$invalidItemCodes = [];
foreach ($data['item_codes'] as $item)
{
$itemCode = $item['item_code'] ?? '';
$trimmedCode = trim($itemCode);
if ($trimmedCode == '' || !ctype_alnum($trimmedCode))
{
$invalidItemCodes[] = $item;
}
}
if (!empty($invalidItemCodes)) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => 'The following item_code(s) contain invalid characters (only alphanumeric allowed).',
'invalid_item_codes' => array_map(function($item) {
return $item['item_code'] ?? '(missing item_code)';
}, $invalidItemCodes)
], 400);
}
//..Checking serial numbers for length less than 9 characters
$invalidSerials = [];
foreach ($data['item_codes'] as $item) {
if (isset($item['serial_numbers']) && is_array($item['serial_numbers'])) {
foreach ($item['serial_numbers'] as $serial) {
if (strlen(trim($serial)) < 9)
{
$invalidSerials[] = $serial;
}
}
}
}
if (!empty($invalidSerials)) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => 'The following serial numbers have invalid length (less than 9 characters)',
'invalid_serial_numbers' => $invalidSerials
], 400);
}
//..Checking serial numbers for invalid characters
$invalidSerialNumbers = [];
foreach ($data['item_codes'] as $item) {
if (isset($item['serial_numbers']) && is_array($item['serial_numbers'])) {
foreach ($item['serial_numbers'] as $serial) {
$trimmedSerial = trim($serial);
if ($trimmedSerial == '' || !ctype_alnum($trimmedSerial)) {
$invalidSerialNumbers[] = $serial;
}
}
}
}
if (!empty($invalidSerialNumbers)) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => 'The following serial number(s) contain invalid characters (only alphanumeric allowed).',
'invalid_serial_numbers' => $invalidSerialNumbers
], 400);
}
//Duplicate item code within json payload
$duplicateItemCode = [];
$seenCodes = [];
foreach ($data['item_codes'] as $item)
{
$code = $item['item_code'] ?? null;
if ($code == null) {
continue;
}
if (in_array($code, $seenCodes))
{
if (!in_array($code, array_column($duplicateItemCode, 'item_code'))) {
$duplicateItemCode[] = $item;
}
}
else
{
$seenCodes[] = $code;
}
}
if (!empty($duplicateItemCode)) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Duplicate item_code found in request payload.",
'duplicate_item_codes' => array_map(function($item) {
return $item['item_code'] ?? '(missing item_code)';
}, $duplicateItemCode)
], 400);
}
//Duplicate serial numbers within all item_codes
$duplicateSno = [];
$seenSerials = [];
foreach ($data['item_codes'] as $item)
{
if (isset($item['serial_numbers']) && is_array($item['serial_numbers'])) {
foreach ($item['serial_numbers'] as $serial) {
if (in_array($serial, $seenSerials)) {
if (!in_array($serial, $duplicateSno)) {
$duplicateSno[] = $serial;
}
} else {
$seenSerials[] = $serial;
}
}
}
}
if (!empty($duplicateSno)) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Duplicate serial number found in request payload.",
'duplicate_serial_numbers' => $duplicateSno
], 400);
}
//..Checking invoice number against plant in invoice validation table
$totQuan = InvoiceValidation::where('invoice_number', $invoiceNumber)->count();
if ($totQuan > 0)
{
$scanSQuan = InvoiceValidation::where('invoice_number', $invoiceNumber)->where('scanned_status', 'Scanned')->count();
if ($totQuan == $scanSQuan)
{
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Serial invoice number : '$invoiceNumber' completed the scanning process. Scan the next 'Serial Invoice' to proceed!",
], 400);
}
else
{
$invoiceFirst = InvoiceValidation::with('plant')->where('invoice_number', $invoiceNumber)->first();
$plantCode = $invoiceFirst ? (String)$invoiceFirst->plant->code : null;
if ($data['plant_code'] != $plantCode)
{
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Serial invoice number : '$invoiceNumber' already exists for plant code : '$plantCode'. Pass the valid 'Plant Code' proceed!",
], 400);
}
}
}
//In item codes array serial numbers not exists
$snoNotExist = [];
foreach ($data['item_codes'] as $item)
{
if (!isset($item['item_code']) || !isset($item['serial_numbers']) || !is_array($item['serial_numbers']))
{
//$snoNotExist[] = $item;
$snoNotExist[] = $item['item_code'] ?? '(missing item_code)';
}
}
if(!empty($snoNotExist)){
return response()->json([
'status_code' => 'ERROR',
'status_description' => "item_codes array must have an item_code and an array of serial_numbers below item code doesn't have serial number array.",
'item_codes' => $snoNotExist
], 400);
}
$notFoundItemCodes = [];
foreach ($data['item_codes'] as $item)
{
$itemRecord = Item::where('code', $item['item_code'])->first();
if (!$itemRecord) {
$notFoundItemCodes[] = $item['item_code'];
}
else
{
$itemId = $itemRecord->id;
}
}
if (!empty($notFoundItemCodes)) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "The following item code(s) were not found in items table",
'item_codes' =>$notFoundItemCodes
], 400);
}
//..Checking Item Code aginst Plant in items table
$plant = Plant::find($plantId);
$notFouItePlant = [];
foreach ($data['item_codes'] as $item)
{
$itemRec = Item::where('code', $item['item_code'])
->where('plant_id', $plantId)
->first();
if (!$itemRec) {
$notFouItePlant[] = $item['item_code'];
}
}
if (!empty($notFouItePlant)) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "The following item code(s) were not found in items table for plant '" . ($plant ? $plant->name : 'Unknown'). "'",
'item_codes' => $notFouItePlant
], 400);
}
$notFouItemCodesStiMas = [];
foreach ($data['item_codes'] as $item) {
$itemRecord = Item::where('code', $item['item_code'])->first();
if ($itemRecord) {
$itemId = $itemRecord->id;
$stickerMasterRecord = StickerMaster::where('item_id', $itemId)->first();
if (!$stickerMasterRecord) {
$notFouItemCodesStiMas[] = $item['item_code'];
}
}
else
{
$notFouItemCodesStiMas[] = $item['item_code'];
}
}
if (!empty($notFouItemCodesStiMas)) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => 'The following item code(s) were not found in sticker master table',
'item_codes' => $notFouItemCodesStiMas
], 400);
}
//..Checking Item Code in sticker master table aginst Plant
$notFouIteStickerPlant = [];
foreach ($data['item_codes'] as $item)
{
$stickerMasterRec = StickerMaster::where('item_id', $itemId)
->where('plant_id', $plantId)
->first();
if (!$stickerMasterRec) {
$notFouIteStickerPlant[] = $item['item_code'];
}
}
if (!empty($notFouIteStickerPlant)) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "The following item code(s) were not found in sticker master table for plant'" . ($plant ? $plant->name : 'Unknown'). "'",
'item_codes' => $notFouIteStickerPlant
], 400);
}
$invalidSerialMasType = [];
foreach ($data['item_codes'] as $item) {
$itemRecord = Item::where('code', $item['item_code'])->first();
$itemId = $itemRecord->id;
$stickerMaster = StickerMaster::where('item_id', $itemId)
->where('plant_id', $plantId)
->whereNotNull('material_type')
->where('material_type', '!=', 0)
->first();
if ($stickerMaster) {
$invalidSerialMasType[] = $item['item_code'];
}
}
if (!empty($invalidSerialMasType)) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => 'The following item code(s) not belongs to serial invoice type in sticker master table',
'item_codes' => $invalidSerialMasType
], 400);
}
if ($totQuan > 0)
{
$scanSQuan = InvoiceValidation::where('invoice_number', $invoiceNumber)->where('scanned_status', 'Scanned')->where('plant_id', $plantId)->count();
$allSerialNumbers = [];
foreach ($data['item_codes'] as $item) {
if (isset($item['serial_numbers']) && is_array($item['serial_numbers'])) {
foreach ($item['serial_numbers'] as $serial) {
$allSerialNumbers[] = $serial;
}
}
}
// Check database for existing serial numbers for this plant
$existingSerials = InvoiceValidation::where('plant_id', $plantId)
->where('invoice_number', '!=', $invoiceNumber)
->whereIn('serial_number', $allSerialNumbers)
->pluck('serial_number')
->toArray();
if (!empty($existingSerials)) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => 'serial numbers already exist for this plant in database.',
'duplicate_serial_numbers' => $existingSerials,
], 400);
}
InvoiceValidation::where('invoice_number', $invoiceNumber)
->where(function($query) {
$query->whereNull('motor_scanned_status')->orWhere('motor_scanned_status', '');
})
->where(function($query) {
$query->whereNull('pump_scanned_status')->orWhere('pump_scanned_status', '');
})
->where(function($query) {
$query->whereNull('capacitor_scanned_status')->orWhere('capacitor_scanned_status', '');
})
->where(function($query) {
$query->whereNull('scanned_status_set')->orWhere('scanned_status_set', '');
})
->where(function($query) {
$query->whereNull('scanned_status')->orWhere('scanned_status', '');
})
->forceDelete(); //->delete();
try
{
foreach ($data['item_codes'] as $item)
{
$stickerMasterId = $stickerMasterRecord->id;
if (!isset($item['serial_numbers']) || !is_array($item['serial_numbers'])) {
continue;
}
foreach ($item['serial_numbers'] as $serial)
{
$exists = InvoiceValidation::where('invoice_number', $invoiceNumber)
->where('serial_number', $serial)
->first();
if ($exists)
{
$exists->updated_at = now();
$exists->save();
continue;
}
else
{
InvoiceValidation::create([
'plant_id' => $plantId,
'invoice_number' => $invoiceNumber,
'item_code' => $item['item_code'],
'serial_number' => $serial,
'sticker_master_id' => $stickerMasterId,
'updated_at' => now(),
]);
}
}
}
return response()->json([
'status_code' => 'SUCCESS',
'status_description' => 'Serial Invoice imported successfully!'
], 200);
}
catch (\Exception $e) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => 'Failed to insert one or more serial invoice records: ' . $e->getMessage(),
], 500);
}
}
else
{
$allSerialNumbers = [];
foreach ($data['item_codes'] as $item) {
if (isset($item['serial_numbers']) && is_array($item['serial_numbers'])) {
foreach ($item['serial_numbers'] as $serial)
{
$allSerialNumbers[] = $serial;
}
}
}
// Check database for existing serial numbers for this plant
$existingSerials = InvoiceValidation::where('plant_id', $plantId)
->whereIn('serial_number', $allSerialNumbers)
->pluck('serial_number')
->toArray();
if (!empty($existingSerials)) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => 'serial numbers already exist for this plant in database.',
'duplicate_serial_numbers' => $existingSerials,
], 400);
}
//..
try
{
foreach ($data['item_codes'] as $item)
{
$stickerMasterId = $stickerMasterRecord->id;
foreach ($item['serial_numbers'] as $serial)
{
InvoiceValidation::create([
'plant_id' => $plantId,
'invoice_number' => $invoiceNumber,
'item_code' => $item['item_code'],
'serial_number' => $serial,
'sticker_master_id' => $stickerMasterId,
]);
}
}
return response()->json([
'status_code' => 'SUCCESS',
'status_description' => 'Serial Invoice imported successfully!'
], 200);
}
catch (\Exception $e)
{
return response()->json([
'status_code' => 'ERROR',
'status_description' => 'Failed to insert one or more serial invoice records: ' . $e->getMessage(),
], 500);
}
}
}
catch (\Exception $e)
{
return response()->json([
'status_code' => 'ERROR',
'status_description' => $e->getMessage(),
], 500);
}
}
public function materialInvoice(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);
}
try
{
$data = $request->all();
if (!isset($data['plant_code']) || trim($data['plant_code']) == '')
{
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Plant code can't be empty!"
], 400);
}
else if (Str::length($data['plant_code']) < 4 || !is_numeric($data['plant_code']) || !preg_match('/^[1-9]\d{3,}$/', $data['plant_code']))
{
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Invalid plant code found!"
], 400);
}
$plant = Plant::where('code', $data['plant_code'])->first();
if (!$plant) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => 'Plant not found!'
], 400);
}
$plantId = $plant->id;
$invoiceNumber = $data['invoice_number'] ?? null;
if (!$invoiceNumber || trim($invoiceNumber) == '')
{
return response()->json([
'status_code' => 'ERROR',
'status_description' => 'invoice_number is required!'
], 400);
}
else if (strlen(trim($invoiceNumber)) < 7)
{
return response()->json([
'status_code' => 'ERROR',
'status_description' => 'invoice number must contain at least 7 alphanumeric characters.'
], 400);
}
//..Checking item codes for invalid length
$invalidItem = [];
foreach ($data['item_codes'] as $item) {
if (!isset($item['item_code']) || strlen(trim($item['item_code'])) < 6) {
$invalidItem[] = $item['item_code'] ?? '(missing item_code)';
}
}
if (!empty($invalidItem)) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => 'The following item codes have invalid length (less than 6 characters)',
'invalid_item_codes' => $invalidItem
], 400);
}
//..Checking item codes for invalid characters
$invalidItemCodes = [];
foreach ($data['item_codes'] as $item)
{
$itemCode = $item['item_code'] ?? '';
$trimmedCode = trim($itemCode);
if ($trimmedCode == '' || !ctype_alnum($trimmedCode))
{
$invalidItemCodes[] = $item;
}
}
if (!empty($invalidItemCodes)) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => 'The following item_code(s) contain invalid characters (only alphanumeric allowed).',
'invalid_item_codes' => array_map(function($item) {
return $item['item_code'] ?? '(missing item_code)';
}, $invalidItemCodes)
], 400);
}
//..Checking item codes in items table
$notFoundItemCodes = [];
foreach ($data['item_codes'] as $item)
{
$itemRecord = Item::where('code', $item['item_code'])->first();
if (!$itemRecord) {
$notFoundItemCodes[] = $item['item_code'];
}
}
$itemId = $itemRecord->id;
if (!empty($notFoundItemCodes)) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "The following item code(s) were not found in items table",
'item_codes' =>$notFoundItemCodes
], 400);
}
//..Checking Item Code in sticker master table
$notFouItemCodesStiMas = [];
foreach ($data['item_codes'] as $item)
{
$stickerMasterRecord = StickerMaster::where('item_id', $itemId)->first();
if (!$stickerMasterRecord) {
$notFouItemCodesStiMas[] = $item['item_code'];
}
}
if (!empty($notFouItemCodesStiMas)) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => 'The following item code(s) were not found in sticker master table',
'item_codes' => $notFouItemCodesStiMas
], 400);
}
//..Checking Item Code aginst Plant in items table
$plant = Plant::find($plantId);
$notFouItePlant = [];
foreach ($data['item_codes'] as $item)
{
$itemRec = Item::where('code', $item['item_code'])
->where('plant_id', $plantId)
->first();
if (!$itemRec) {
$notFouItePlant[] = $item['item_code'];
}
}
if (!empty($notFouItePlant)) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "The following item code(s) were not found in items table for plant '" . ($plant ? $plant->name : 'Unknown'). "'",
'item_codes' => $notFouItePlant
], 400);
}
//..Checking Item Code in sticker master table aginst Plant
$notFouIteStickerPlant = [];
foreach ($data['item_codes'] as $item)
{
$stickerMasterRec = StickerMaster::where('item_id', $itemId)
->where('plant_id', $plantId)
->first();
if (!$stickerMasterRec) {
$notFouIteStickerPlant[] = $item['item_code'];
}
}
if (!empty($notFouIteStickerPlant)) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "The following item code(s) were not found in sticker master table for plant'" . ($plant ? $plant->name : 'Unknown'). "'",
'item_codes' => $notFouIteStickerPlant
], 400);
}
$invalidMaterialType = [];
foreach ($data['item_codes'] as $item) {
$itemRecord = Item::where('code', $item['item_code'])->first();
$itemId = $itemRecord->id;
$stickerMaster = StickerMaster::where('item_id', $itemId)
->where('plant_id', $plantId)
->where(function($query) {
$query->whereNull('material_type')
->orWhere('material_type', 0);
})
->first();
if ($stickerMaster) {
$invalidMaterialType[] = $item['item_code'];
}
}
if (!empty($invalidMaterialType)) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => 'The following item code(s) belongs to seial invoice type in sticker master table',
'item_codes' => $invalidMaterialType
], 400);
}
foreach ($data['item_codes'] as $item)
{
$quantity = isset($item['item_quantity']) ? (int)$item['item_quantity'] : null;
InvoiceValidation::create([
'plant_id' => $plantId,
'item_code' => $item['item_code'],
'item_quantity' => $quantity,
'created_at' => now(),
'updated_at' => now(),
]);
}
return response()->json([
'status_code' => 'SUCCESS',
'status_description' => 'Invoice validation records inserted successfully.'
], 200);
}
catch (\Exception $e)
{
return response()->json([
'status_code' => 'ERROR',
'status_description' => $e->getMessage(),
], 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)
{
//
}
// public function handle(Request $request)
// {
// $invoice = InvoiceValidation::withCount([
// 'serialNumbers as scanned_count' => function ($q) {
// $q->where('is_scanned', 1);
// }
// ])->find($request->invoice_id);
// if (!$invoice) {
// return response()->json(['error' => 'Invoice not found'], 404);
// }
// if ($invoice->scanned_count < $invoice->total_serials) {
// Mail::to('alerts@example.com')->send(
// new \App\Mail\IncompleteInvoiceMail(
// $invoice,
// $invoice->scanned_count,
// $invoice->total_serials
// )
// );
// }
// return response()->json(['status' => 'ok']);
// }
}

View File

@@ -0,0 +1,219 @@
<?php
namespace App\Http\Controllers;
use App\Models\Line;
use App\Models\Machine;
use App\Models\Plant;
use App\Models\WorkGroupMaster;
use Illuminate\Http\Request;
use Str;
class MachineController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index()
{
//
}
/**
* Store a newly created resource in storage.
*/
public function store(Request $request)
{
//
}
/**
* Display the all available resource.
*/
public function get_all_data(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);
}
$machines = Machine::with('plant')->with('workGroupMaster')->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 : "",
'work_center' => $machine->work_center ?? "",
];
});
return response()->json([
'machines' => $machinesData
]);
}
/**
* Display the specified resource.
*/
public function get_data(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');
$lineName = $request->header('line-name');
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);
}
else if ($lineName == null || $lineName == '' || Str::length($lineName) <= 0)
{
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Line name can't be empty!"
], 400);
}
$plant = Plant::where('code', $plantCode)->first();
if (!$plant)
{
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Plant Code '{$plantCode}' not found!"
], 400);
}
$plantId = $plant->id;
$line = Line::where('name', $lineName)->first();
if (!$line)
{
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Line Name '{$lineName}' not found!"
], 400);
}
$line = Line::where('name', $lineName)->where('plant_id', $plantId)->first();
if (!$line)
{
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Line Name '{$lineName}' not found for the plant!"
], 400);
}
$lineId = $line->id;//no_of_operation
$lineWorkGroup1Id = $line->work_group1_id;
$lineWorkGroup2Id = $line->work_group2_id;
if ($line->no_of_operation == null || $line->no_of_operation == '' || $line->no_of_operation == 0 || !is_numeric($line->no_of_operation))
{
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Group work center not found for the plant & line!"
], 400);
}
$test = [];
$lineWorkGroupIds = [];
for ($i = 1; $i <= $line->no_of_operation; $i++) {
$curWorkGroupId = $line->{"work_group{$i}_id"};
if (in_array($curWorkGroupId, $lineWorkGroupIds))
{
continue;
}
else
{
$lineWorkGroupIds[] = $curWorkGroupId;
}
$test[] = [
'group_work_center' => WorkGroupMaster::where('id', $curWorkGroupId)->first()->name ?? "",
'operation_number' => WorkGroupMaster::where('id', $curWorkGroupId)->first()->operation_number ?? "",
'work_centers' => Machine::where('plant_id', $plantId)->where('work_group_master_id', $curWorkGroupId)->orderBy('work_center')->pluck('work_center')->toArray() ?? [],
];
}
if($lineWorkGroupIds)
{
return response()->json([
'machines' => $test
]);
}
// $machines = Machine::with('plant')->with('workGroupMaster')->orderBy('plant_id')->get();
// $machinesData = $machines->map(function($machine) use ($lineId, $plantId) {
// $test = [];
// 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();
// $existsInLines = Line::where('plant_id', $plantId)
// ->where('i', '!=', $lineId)
// ->where("work_group{$i}_id", $workGroupRecord->id)
// ->first();
// $test[] = $existsInLines;
// 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;
// }
// return $test[];
// });
// return response()->json([
// 'machines' => $machinesData
// ]);
}
/**
* 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

@@ -0,0 +1,218 @@
<?php
namespace App\Http\Controllers;
use App\Models\DeviceMaster;
use App\Models\MfmMeter;
use App\Models\MfmParameter;
use App\Models\Plant;
use Illuminate\Http\Request;
class MfmParameterController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index()
{
//
}
public function get_mfm_parameterid(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) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Plant Code 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);
}
// $sequences = MfmMeter::where('plant_id', $plant->id)
// ->whereNotNull('sequence')
// ->distinct()
// ->orderBy('sequence', 'asc')
// ->pluck('sequence');
$sequences = MfmMeter::where('plant_id', $plant->id)
->whereNotNull('sequence')
->pluck('sequence')
->unique()
->map(fn($s) => is_numeric($s) ? (int) $s : $s)
->sort()
->values();
if ($sequences->isEmpty())
{
return response()->json([
'status_code' => 'ERROR',
'status_description' => 'No sequences found for the given plant.'
], 404);
}
return response()->json([
'status_code' => 'SUCCESS',
'status_description' => $sequences
], 200);
}
public function get_mfm_parameter(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');
$mfmParameterSeq = $request->header('mfm-meter-sequence');
$deviceName = $request->header('device-name');
if (!$plantCode) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Plant Code value can't be empty"
], 404);
}
else if (!$mfmParameterSeq) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Mfm Parameter sequence value can't be empty"
], 404);
}
else if (!$deviceName) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Device name value can't be empty"
], 404);
}
$plant = Plant::where('code', $plantCode)->first();
$device = DeviceMaster::where('name', $deviceName)->first();
if (!$plant)
{
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Plant Code '{$plantCode}' not found!"
], 404);
}
// Find mfm_meter by sequence and plant_id
$mfmMeter = MfmMeter::where('sequence', trim($mfmParameterSeq))
->where('plant_id', $plant->id)
->where('device_master_id', $device->id)
->first();
if (!$mfmMeter) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "MFM Meter with sequence '{$mfmParameterSeq}' not found for plant code '{$plantCode}'"
], 404);
}
// Now fetch mfm_parameters for this plant and meter
$mfmParameters = MfmParameter::where('plant_id', $plant->id)
->where('mfm_meter_id', $mfmMeter->id)
->where('device_master_id', $device->id)
->get(['register_id', 'byte_to_convert', 'type_to_convert', 'decimal_to_display']);
$transformed = $mfmParameters->map(function ($item) {
$array = $item->toArray();
foreach ($array as $key => $value) {
if (is_null($value)) {
$array[$key] = "";
}
}
return $array;
});
//..if want to send all values in string
// $transformed = $mfmParameters->map(function ($item) {
// $array = $item->toArray();
// foreach ($array as $key => $value) {
// // Always cast to string (empty string if null)
// $array[$key] = is_null($value) ? "" : strval($value);
// }
// return $array;
// });
if ($transformed->isEmpty()) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "No MFM parameters found for the specified plant,meter and device name."
], 404);
}
// Success: return list
return response()->json([
'status_code' => 'SUCCESS',
'status_description' => $transformed
], 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

@@ -0,0 +1,103 @@
<?php
namespace App\Http\Controllers;
use App\Models\ModuleList;
use Illuminate\Http\Request;
class ModuleChartController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index()
{
//
}
public function get_moduleChart(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);
}
$moduleName = $request->header('module-name');
if (empty($moduleName))
{
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Module Name can't be empty!"
], 404);
}
$exists = ModuleList::where('module_name', $moduleName)->exists();
if (!$exists) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Module Name '{$moduleName}' not found in system!"
], 404);
}
// Fetch all unique dashboard names for the given module_name
// $dashboardNames = ModuleList::where('module_name', $moduleName)
// ->distinct()
// ->pluck('dashboard_name');
$dashboardNames = ModuleList::where('module_name', $moduleName)
->orderBy('created_at', 'asc')
->get()
->unique('dashboard_name')
->pluck('dashboard_name')
->values(); // reset array keys
return response()->json([
'status_code' => 'SUCCESS',
'status_description' => $dashboardNames
], 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

@@ -0,0 +1,105 @@
<?php
namespace App\Http\Controllers;
use App\Models\ModuleList;
use Illuminate\Http\Request;
class ModuleController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index()
{
//
}
/**
* Store a newly created resource in storage.
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*/
// public function show(string $id)
// {
// //
// }
public function get_module(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);
}
$moduleName = $request->header('module-name');
if (empty($moduleName))
{
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Module Name can't be empty!"
], 404);
}
$headerValue = $request->header('module-name');
if ($headerValue != 'Module List') {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Invalid value for 'module-name' header!"
], 404);
}
$uniqueModules = ModuleList::select('module_name', 'created_at')
->orderBy('created_at', 'asc')
->get()
->unique('module_name')
->pluck('module_name')
->values();
if ($uniqueModules->isEmpty()) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => 'Module names not found'
], 404);
}
return response()->json([
'status_code' => 'SUCCESS',
'status_description' => $uniqueModules
], 200);
}
/**
* 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

@@ -0,0 +1,106 @@
<?php
namespace App\Http\Controllers;
use App\Models\Line;
use App\Models\ModuleList;
use Illuminate\Http\Request;
class ModuleFGLineController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index()
{
//
}
public function get_moduleFGFilter(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);
}
$lineName = $request->header('line-name');
if (empty($lineName))
{
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Line name can't be empty!"
], 404);
}
$line = Line::where('name', $lineName)->first();
if (!$line) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Line '{$lineName}' not found!"
], 404);
}
if ($line->type !== 'FG Line') {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Line '{$lineName}' is not of type FG Line."
], 400);
}
// Default logic to return filter names
$filterNames = ModuleList::orderBy('created_at', 'asc')
->get()
->unique('filter_name')
->pluck('filter_name')
->filter()
->values();
return response()->json([
'status_code' => 'SUCCESS',
'status_description' => $filterNames
], 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

@@ -0,0 +1,119 @@
<?php
namespace App\Http\Controllers;
use App\Models\ModuleList;
use Illuminate\Http\Request;
class ModuleFilterController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index()
{
//
}
public function get_moduleFilter(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);
}
$lineName = $request->header('line-name');
if (empty($lineName))
{
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Line name can't be empty!"
], 404);
}
// If 'line-name' is 'FG Lines', return actual FG Line names
if (strtolower(trim($lineName)) == 'fg lines') {
$fgLines = \App\Models\Line::where('type', 'FG Line')
->orderBy('created_at', 'asc')
->pluck('name');
if ($fgLines->isEmpty()) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => 'No FG Lines found!'
], 404);
}
return response()->json([
'status_code' => 'SUCCESS',
'status_description' => $fgLines
], 200);
}
// Default logic to return filter names
$filterNames = ModuleList::orderBy('created_at', 'asc')
->get()
->unique('filter_name')
->pluck('filter_name')
->filter()
->values();
return response()->json([
'status_code' => 'SUCCESS',
'status_description' => $filterNames
], 200);
// $filterNames = ModuleList::orderBy('created_at', 'asc')
// ->get()
// ->unique('filter_name')
// ->pluck('filter_name')
// ->filter()
// ->values();
// return response()->json([
// 'status_code' => 'SUCCESS',
// 'status_description' => $filterNames
// ], 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

@@ -0,0 +1,573 @@
<?php
namespace App\Http\Controllers;
use App\Models\Line;
use App\Models\Plant;
use App\Models\ProductionQuantity;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class ModuleFilterDataController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index()
{
//
}
// public function get_moduleFilterData(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);
// }
// $moduleName = $request->header('module-name');
// $chartName = $request->header('chart-name');
// $plantName = $request->header('plant-name');
// $lineName = $request->header('line-name');
// $filterName = $request->header('filter-name');
// $requiredHeaders = [
// 'module-name',
// 'chart-name',
// 'plant-name',
// 'line-name',
// 'filter-name',
// ];
// $missingHeaders = [];
// foreach ($requiredHeaders as $header) {
// if (empty($request->header($header))) {
// $missingHeaders[] = $header;
// }
// }
// if (!empty($missingHeaders)) {
// return response()->json([
// 'status_code' => 'ERROR',
// 'status_description' => 'Missing required headers: ' . implode(', ', $missingHeaders)
// ], 400);
// }
// // Fetch plant ID
// $plant = Plant::where('name', $plantName)->first();
// if (!$plant) {
// return response()->json([
// 'status_code' => 'ERROR',
// 'status_description' => "Plant '{$plantName}' not found!"
// ], 404);
// }
// // Fetch line ID
// $line = Line::where('name', $lineName)->where('plant_id', $plant->id)->first();
// if (!$line) {
// return response()->json([
// 'status_code' => 'ERROR',
// 'status_description' => "Line '{$lineName}' not found for plant '{$plantName}'"
// ], 404);
// }
// $activeFilter = strtolower(trim($request->header('filter-name')));
// if ($activeFilter == 'yesterday') {
// $startDate = now()->subDay()->setTime(8, 0, 0);
// $endDate = now()->setTime(8, 0, 0);
// }
// elseif ($activeFilter == 'this week') {
// $startDate = now()->startOfWeek()->setTime(8, 0, 0);
// $endDate = now()->endOfWeek()->addDay()->setTime(8, 0, 0);
// }
// elseif ($activeFilter == 'this month') {
// $startDate = now()->startOfMonth();
// $endDate = now()->endOfMonth();
// }
// else {
// $startDate = now()->setTime(8, 0, 0);
// $endDate = now()->copy()->addDay()->setTime(8, 0, 0);
// }
// $rowCount = ProductionQuantity::where('plant_id', $plant->id)
// ->where('line_id', $line->id)
// ->whereBetween('created_at', [$startDate, $endDate])
// ->count();
// return response()->json([
// 'status_code' => 'SUCCESS',
// 'status_description' => $rowCount
// ], 200);
// }
// public function get_moduleFilterData(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);
// }
// $requiredHeaders = [
// 'module-name',
// 'chart-name',
// 'plant-name',
// 'line-name',
// 'filter-name',
// ];
// $missingHeaders = [];
// foreach ($requiredHeaders as $header) {
// if (empty($request->header($header))) {
// $missingHeaders[] = $header;
// }
// }
// if (!empty($missingHeaders)) {
// return response()->json([
// 'status_code' => 'ERROR',
// 'status_description' => 'Missing required headers: ' . implode(', ', $missingHeaders)
// ], 404);
// }
// $validFilters = ['Today', 'Yesterday', 'This Week', 'This Month'];
// $filterHeader = $request->header('filter-name');
// if (!in_array($filterHeader, $validFilters)) {
// return response()->json([
// 'status_code' => 'ERROR',
// 'status_description' => "Invalid filter-name value! Accepted values are: " . implode(', ', $validFilters)
// ], 404);
// }
// $plantName = $request->header('plant-name');
// $lineName = $request->header('line-name');
// $filterName = strtolower(trim($request->header('filter-name')));
// $plant = Plant::where('name', $plantName)->first();
// if (!$plant) {
// return response()->json([
// 'status_code' => 'ERROR',
// 'status_description' => "Plant '{$plantName}' not found!"
// ], 404);
// }
// // Set date filter range
// if ($filterName == 'yesterday') {
// $startDate = now()->subDay()->setTime(8, 0, 0);
// $endDate = now()->setTime(8, 0, 0);
// } elseif ($filterName == 'this week') {
// $startDate = now()->startOfWeek()->setTime(8, 0, 0);
// $endDate = now()->endOfWeek()->addDay()->setTime(8, 0, 0);
// } elseif ($filterName == 'this month') {
// $startDate = now()->startOfMonth();
// $endDate = now()->endOfMonth();
// } else {
// $startDate = now()->setTime(8, 0, 0);
// $endDate = now()->copy()->addDay()->setTime(8, 0, 0);
// }
// // Handle All Lines
// if (strtolower(trim($lineName)) == 'all lines') {
// $lines = Line::where('plant_id', $plant->id)->pluck('id', 'name');
// if ($lines->isEmpty()) {
// return response()->json([
// 'status_code' => 'ERROR',
// 'status_description' => "No lines found for plant '{$plantName}'"
// ], 404);
// }
// $lineCounts = [];
// foreach ($lines as $name => $id) {
// $count = ProductionQuantity::where('plant_id', $plant->id)
// ->where('line_id', $id)
// ->whereBetween('created_at', [$startDate, $endDate])
// ->count();
// $lineCounts[$name] = $count;
// }
// return response()->json([
// 'status_code' => 'SUCCESS',
// 'status_description' => $lineCounts
// ], 200);
// }
// // Handle single line
// $line = Line::where('name', $lineName)->where('plant_id', $plant->id)->first();
// if (!$line) {
// return response()->json([
// 'status_code' => 'ERROR',
// 'status_description' => "Line '{$lineName}' not found for plant '{$plantName}'"
// ], 404);
// }
// $rowCount = ProductionQuantity::where('plant_id', $plant->id)
// ->where('line_id', $line->id)
// ->whereBetween('created_at', [$startDate, $endDate])
// ->count();
// $chartName = $request->header('chart-name');
// if ($chartName == 'Production Hourly Count')
// {
// if ($filterHeader == 'Today' || $filterHeader == 'Yesterday') {
// $hourlyCounts = [];
// $hourStart = now()->startOfDay()->addHours(8); // Today 8:00 AM
// if ($filterHeader == 'Yesterday') {
// $hourStart->subDay(); // Yesterday 8:00 AM
// }
// $hourEndFinal = $hourStart->copy()->addDay(); // +1 day = 24 hourly slots
// while ($hourStart < $hourEndFinal) {
// $hourEnd = $hourStart->copy()->addHour();
// $label = $hourStart->format('g:i A') . ' to ' . $hourEnd->format('g:i A');
// $count = ProductionQuantity::where('plant_id', $plant->id)
// ->where('line_id', $line->id)
// ->whereBetween('created_at', [$hourStart, $hourEnd])
// ->count();
// $hourlyCounts[$label] = $count;
// $hourStart = $hourEnd;
// }
// return response()->json([
// 'status_code' => 'SUCCESS',
// 'hourly_data' => $hourlyCounts
// ], 200);
// }
// // THIS WEEK: group by weekdays (Mon to Sun)
// if ($filterHeader == 'This Week') {
// $dowCounts = ProductionQuantity::selectRaw('EXTRACT(DOW FROM created_at) as dow, COUNT(*) as total')
// ->where('plant_id', $plant->id)
// ->where('line_id', $line->id)
// ->whereBetween('created_at', [$startDate, $endDate])
// ->groupBy('dow')
// ->pluck('total', 'dow');
// $labels = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
// $data = array_fill(0, 7, 0);
// foreach ($dowCounts as $dow => $count) {
// $data[$dow] = $count;
// }
// // Reorder from Monday (1) to Sunday (0)
// $orderedData = [
// $data[1] ?? 0,
// $data[2] ?? 0,
// $data[3] ?? 0,
// $data[4] ?? 0,
// $data[5] ?? 0,
// $data[6] ?? 0,
// $data[0] ?? 0
// ];
// return response()->json([
// 'status_code' => 'SUCCESS',
// 'weekly_labels' => $labels,
// 'weekly_counts' => $orderedData
// ], 200);
// }
// //THIS MONTH: group by weeks
// if ($filterHeader == 'This Month') {
// // Count records grouped by week number
// $weekCounts = ProductionQuantity::selectRaw("FLOOR((EXTRACT(DAY FROM created_at) - 1) / 7) + 1 as week_number, COUNT(*) as total")
// ->where('plant_id', $plant->id)
// ->where('line_id', $line->id)
// ->whereBetween('created_at', [$startDate, $endDate])
// ->groupBy('week_number')
// ->pluck('total', 'week_number');
// $weeksCount = ceil($endDate->day / 7); // Total number of weeks in month
// $allWeeks = array_fill(1, $weeksCount, 0);
// $data = array_replace($allWeeks, $weekCounts->toArray());
// // Prepare labels like Week 1 (01 Jul - 07 Jul)
// $labels = [];
// for ($i = 1; $i <= $weeksCount; $i++) {
// $weekStart = $startDate->copy()->addDays(($i - 1) * 7);
// $weekEnd = $startDate->copy()->addDays($i * 7 - 1)->min($endDate);
// $labels[] = "Week $i ({$weekStart->format('d M')} - {$weekEnd->format('d M')})";
// }
// $orderedData = array_values($data);
// return response()->json([
// 'status_code' => 'SUCCESS',
// 'monthly_labels' => $labels,
// 'monthly_counts' => $orderedData
// ], 200);
// }
// }
// if ($chartName == 'Production Line Count')
// {
// return response()->json([
// 'status_code' => 'SUCCESS',
// 'status_description' => $rowCount
// ], 200);
// }
// }
public function get_moduleFilterData(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);
}
$requiredHeaders = [
'module-name', 'chart-name', 'plant-name', 'line-name', 'filter-name'
];
$missingHeaders = [];
foreach ($requiredHeaders as $header) {
if (empty($request->header($header))) {
$missingHeaders[] = $header;
}
}
if (!empty($missingHeaders)) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => 'Missing required headers: ' . implode(', ', $missingHeaders)
], 404);
}
$validFilters = ['Today', 'Yesterday', 'This Week', 'This Month'];
$filterHeader = $request->header('filter-name');
if (!in_array($filterHeader, $validFilters)) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Invalid filter-name value! Accepted values are: " . implode(', ', $validFilters)
], 404);
}
$plantName = $request->header('plant-name');
$lineName = $request->header('line-name');
$filterName = strtolower(trim($request->header('filter-name')));
$chartName = $request->header('chart-name');
$plant = Plant::where('name', $plantName)->first();
if (!$plant) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Plant '{$plantName}' not found!"
], 404);
}
$isAllLines = strtolower(trim($lineName)) == 'all lines';
if ($isAllLines) {
$lines = Line::where('plant_id', $plant->id)->get();
$fgLineIds = $lines->where('type', 'FG Line')->pluck('id')->toArray();
$nonFgLineIds = $lines->where('type', '!=', 'FG Line')->pluck('id')->toArray();
} else {
$line = Line::where('name', $lineName)->where('plant_id', $plant->id)->first();
if (!$line) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Line '{$lineName}' not found for plant '{$plantName}'"
], 404);
}
$lineIds = [$line->id];
$isFgLine = $line->type == 'FG Line';
$baseTable = $isFgLine ? 'quality_validations' : 'production_quantities';
}
if ($filterName == 'yesterday') {
$startDate = now()->subDay()->setTime(8, 0, 0);
$endDate = now()->setTime(8, 0, 0);
$groupBy = 'EXTRACT(HOUR FROM created_at)';
} elseif ($filterName == 'this week') {
$startDate = now()->startOfWeek()->setTime(8, 0, 0);
$endDate = now()->endOfWeek()->addDay()->setTime(8, 0, 0);
$groupBy = 'EXTRACT(DOW FROM created_at)';
} elseif ($filterName == 'this month') {
$startDate = now()->startOfMonth();
$endDate = now()->endOfMonth();
$groupBy = "FLOOR((EXTRACT(DAY FROM created_at) - 1) / 7) + 1";
} else {
$startDate = now()->setTime(8, 0, 0);
$endDate = now()->copy()->addDay()->setTime(8, 0, 0);
$groupBy = 'EXTRACT(HOUR FROM created_at)';
}
if ($chartName == 'Production Line Count' && $isAllLines) {
$lineCounts = [];
foreach ($lines as $line) {
$table = ($line->type == 'FG Line') ? 'quality_validations' : 'production_quantities';
$count = DB::table($table)
->where('plant_id', $plant->id)
->where('line_id', $line->id)
->whereBetween('created_at', [$startDate, $endDate])
->count();
$lineCounts[$line->name] = $count;
}
return response()->json([
'status_code' => 'SUCCESS',
'status_description' => $lineCounts
], 200);
}
if (!$isAllLines)
{
$rowCount = DB::table($baseTable)
->where('plant_id', $plant->id)
->where('line_id', $line->id)
->whereBetween('created_at', [$startDate, $endDate])
->count();
$query = DB::table($baseTable)
->selectRaw("$groupBy AS time_unit, COUNT(*) AS total_quantity")
->where('created_at', '>=', $startDate)
->where('created_at', '<', $endDate)
->where('plant_id', $plant->id)
->where('line_id', $line->id)
->groupByRaw($groupBy)
->orderByRaw($groupBy)
->pluck('total_quantity', 'time_unit')
->toArray();
if ($chartName == 'Production Hourly Count') {
if ($filterName == 'this month') {
$weeksCount = ceil($endDate->day / 7);
$allWeeks = array_fill(1, $weeksCount, 0);
$data = array_replace($allWeeks, $query);
$labels = [];
for ($i = 1; $i <= $weeksCount; $i++) {
$weekStart = $startDate->copy()->addDays(($i - 1) * 7)->format('d M');
$weekEnd = $startDate->copy()->addDays($i * 7 - 1)->min($endDate)->format('d M');
$labels[] = "Week $i ($weekStart - $weekEnd)";
}
$orderedData = array_values($data);
} elseif ($filterName == 'this week') {
$labels = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
$data = array_fill(0, 7, 0);
foreach ($query as $dow => $count) {
$data[$dow] = $count;
}
$orderedData = [
$data[1] ?? 0, $data[2] ?? 0, $data[3] ?? 0,
$data[4] ?? 0, $data[5] ?? 0, $data[6] ?? 0,
$data[0] ?? 0,
];
} else {
$allHours = array_fill(0, 24, 0);
$data = array_replace($allHours, $query);
$shiftedData = [];
foreach ($data as $hour => $count) {
$nextHour = ($hour + 1) % 24;
$shiftedData[$nextHour] = $count;
}
$shiftedKeys = array_merge(range(9, 23), range(0, 8));
$orderedData = array_map(fn($hour) => $shiftedData[$hour] ?? 0, $shiftedKeys);
$labels = array_map(function ($hour) {
$prevHour = ($hour - 1 + 24) % 24;
return date("g:i A", strtotime("$prevHour:00")) . ' to ' . date("g:i A", strtotime("$hour:00"));
}, $shiftedKeys);
}
return response()->json([
'status_code' => 'SUCCESS',
'datasets' => [[
'label' => match ($filterName) {
'this week' => $isFgLine ? 'Daily FG Count This Week' : 'Daily Production This Week',
'this month' => $isFgLine ? 'Weekly FG Count This Month' : 'Weekly Production This Month',
'yesterday' => $isFgLine ? "Yesterday's FG Count" : "Yesterday's Hourly Production",
default => $isFgLine ? "Today's FG Count" : "Today's Hourly Production",
},
'data' => $orderedData
]],
'labels' => $labels,
], 200);
}
if ($chartName == 'Production Line Count') {
return response()->json([
'status_code' => 'SUCCESS',
'status_description' => $rowCount
], 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

@@ -0,0 +1,191 @@
<?php
namespace App\Http\Controllers;
use App\Models\GuardPatrolEntry;
use App\Models\Plant;
use Carbon\Carbon;
use Illuminate\Http\Request;
class ModuleGuardDayCountController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index()
{
//
}
public function get_guardDay_countData(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);
}
$plantName = $request->header('plant-name');
$filterHeader = $request->header('filter-name');
if (empty($plantName) || empty($filterHeader)) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Missing required headers: plant-name, or filter-name"
], 404);
}
$validFilters = ['Today', 'Yesterday', 'This Week', 'This Month'];
if (!in_array($filterHeader, $validFilters)) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Invalid filter-name value! Accepted values are: " . implode(', ', $validFilters)
], 404);
}
// $selectedPlant = $plant->id;
// $activeFilter = strtolower(trim($filterHeader));
$plant = Plant::where('name', $plantName)->first();
if (!$plant) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Plant '{$plantName}' not found!"
], 404);
}
$selectedPlant = $plant->id;
$activeFilter = strtolower(trim($filterHeader));
// Set date range based on filter
switch ($activeFilter) {
case 'yesterday':
$startDate = now()->subDay()->startOfDay();
$endDate = now()->subDay()->endOfDay();
break;
case 'this week':
$startDate = now()->startOfWeek();
$endDate = now()->endOfWeek();
break;
case 'this month':
$startDate = now()->startOfMonth();
$endDate = now()->endOfMonth();
break;
default: // today
$startDate = now()->startOfDay();
$endDate = now()->endOfDay();
break;
}
// Get all unique guard names for this plant
$uniqueGuardNames = GuardPatrolEntry::join('guard_names', 'guard_patrol_entries.guard_name_id', '=', 'guard_names.id')
->where('guard_patrol_entries.plant_id', $selectedPlant)
->select('guard_names.id', 'guard_names.name')
->groupBy('guard_names.id', 'guard_names.name')
->orderBy('guard_names.name')
->pluck('name')
->toArray();
// Get all patrol entries within the date range, grouped by guard name
$guardPatrols = GuardPatrolEntry::join('guard_names', 'guard_patrol_entries.guard_name_id', '=', 'guard_names.id')
->where('guard_patrol_entries.plant_id', $selectedPlant)
->whereBetween('guard_patrol_entries.patrol_time', [$startDate, $endDate])
->select('guard_names.id', 'guard_names.name', 'guard_patrol_entries.patrol_time')
->orderBy('guard_names.name')
->orderBy('guard_patrol_entries.patrol_time')
->get()
->groupBy('name');
$guardTimeSums = [];
foreach ($guardPatrols as $guardName => $patrols) {
$totalSeconds = 0;
$prevTime = null;
foreach ($patrols as $patrol) {
$currentTime = Carbon::parse($patrol->patrol_time);
if ($prevTime) {
$totalSeconds += abs($currentTime->diffInSeconds($prevTime));
}
$prevTime = $currentTime;
}
$guardTimeSums[$guardName] = [
'minutes' => round($totalSeconds / 60),
'hours' => round($totalSeconds / 3600, 1),
];
}
// Prepare chart data
$chartData = [];
foreach ($uniqueGuardNames as $guardName) {
if (in_array($activeFilter, ['today', 'yesterday'])) {
$chartData[] = $guardTimeSums[$guardName]['minutes'] ?? 0;
} else {
$chartData[] = $guardTimeSums[$guardName]['hours'] ?? 0;
}
}
// $chartData = array_map(function ($value) {
// return ($value == 0 || is_null($value)) ? null : $value;
// }, $chartData);
$chartData = array_map(function ($value) {
return ($value == 0 || is_null($value)) ? "" : $value;
}, $chartData);
return response()->json([
'status_code' => 'SUCCESS',
'labels' => array_values($uniqueGuardNames),
'datasets' => [
[
'label' => match ($activeFilter) {
'yesterday' => "Patrols by Guard (Yesterday) Minutes",
'this week' => "Patrols by Guard (This Week) Hours",
'this month' => "Patrols by Guard (This Month) Hours",
default => "Patrols by Guard (Today) Minutes",
},
'data' => $chartData,
],
],
]);
}
/**
* 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

@@ -0,0 +1,173 @@
<?php
namespace App\Http\Controllers;
use App\Models\CheckPointTime;
use App\Models\GuardName;
use App\Models\GuardPatrolEntry;
use App\Models\Plant;
use Carbon\Carbon;
use Illuminate\Http\Request;
class ModuleGuardHourlyCountController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index()
{
//
}
public function get_guardDay_hourlyData(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);
}
$plantName = $request->header('plant-name');
$dateHeader = $request->header('date'); // required: format Y-m-d
$guardIdHeader = $request->header('guard-name'); // required: guard_name_id
$timeHeader = $request->header('time-range'); // required: "08:00 - 10:00"
if (!$plantName || !$dateHeader || !$guardIdHeader || !$timeHeader) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => 'Missing one or more headers: plant-name, date, guard-name, time-range'
], 404);
}
$plant = Plant::where('name', $plantName)->first();
if (!$plant) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Plant '{$plantName}' not found!"
], 404);
}
$selectedPlant = $plant->id;
//$selectedDate = $dateHeader;
$selectedDate = Carbon::createFromFormat('d-m-Y', $dateHeader)->format('Y-m-d');
// $selectedGuardId = $guardIdHeader;
$guard = GuardName::where('name', $guardIdHeader)->first();
if (!$guard) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Guard '{$guardIdHeader}' not found!"
], 404);
}
$selectedGuardId = $guard->id;
[$startTime, $endTime] = explode(' - ', $timeHeader);
// $startFormatted = Carbon::parse("{$selectedDate} {$startTime}");
// $endFormatted = Carbon::parse("{$selectedDate} {$endTime}");
// $startDateTime = $startFormatted->format('H:i:s');
// $endDateTime = $endFormatted->format('H:i:s');
try
{
[$startTime, $endTime] = explode(' - ', $timeHeader);
$startDateTime = Carbon::parse("{$selectedDate} {$startTime}");
$endDateTime = Carbon::parse("{$selectedDate} {$endTime}");
}
catch (\Exception $e) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Invalid time-range format. Use HH:MM:SS - HH:MM:SS"
], 400);
}
$patrols = GuardPatrolEntry::where('plant_id', $selectedPlant)
->where('guard_name_id', $selectedGuardId)
->whereBetween('patrol_time', [$startDateTime, $endDateTime])
->orderBy('patrol_time')
->get();
if ($patrols->count() < 2) {
return response()->json([
'status_code' => 'SUCCESS',
'labels' => [],
'datasets' => []
]);
}
$checkPointTimes = CheckPointTime::where('plant_id', $selectedPlant)
->orderBy('sequence_number')
->get(['sequence_number', 'min_cushioning', 'max_cushioning', 'check_point1_id', 'check_point2_id']);
$expectedSequence = [];
foreach ($checkPointTimes as $row) {
$expectedSequence[] = $row->check_point1_id;
}
if ($checkPointTimes->isNotEmpty()) {
$expectedSequence[] = $checkPointTimes->last()->check_point2_id;
}
$intervals = [];
$labels = [];
$currentSeqIndex = 0;
for ($i = 0; $i < $patrols->count() - 1; $i++) {
$current = Carbon::parse($patrols[$i]->patrol_time);
$next = Carbon::parse($patrols[$i + 1]->patrol_time);
$interval = round($next->floatDiffInRealSeconds($current, true) / 60, 2);
$intervals[] = $interval;
$labels[] = "Seq " . ($i + 1);
}
return response()->json([
'status_code' => 'SUCCESS',
'labels' => $labels,
'datasets' => [
[
'label' => 'Interval (minutes)',
'data' => array_map(fn($val) => $val ?: "", $intervals),
]
]
]);
}
/**
* 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

@@ -0,0 +1,124 @@
<?php
namespace App\Http\Controllers;
use App\Models\GuardPatrolEntry;
use App\Models\Plant;
use Carbon\Carbon;
use Illuminate\Http\Request;
class ModuleGuardNameController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index()
{
//
}
public function get_guard_name_Data(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);
}
$plantName = $request->header('plant-name');
$dateHeader = $request->header('date');
if (!$plantName) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Plant value can't be empty"
], 404);
}
else if (!$dateHeader) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Date value can't be empty"
], 404);
}
$plant = Plant::where('name', $plantName)->first();
if (!$plant) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Plant '{$plantName}' not found!"
], 404);
}
$selectedPlant = $plant->id;
try
{
$selectedDate = Carbon::createFromFormat('d-m-Y', $dateHeader)->format('Y-m-d');
}
catch (\Exception $e) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Invalid date format. Expected format: d-m-Y"
], 400);
}
//$selectedDate = Carbon::createFromFormat('d-m-Y', $dateHeader)->format('Y-m-d');
$guardNames = GuardPatrolEntry::join('guard_names', 'guard_patrol_entries.guard_name_id', '=', 'guard_names.id')
->where('guard_patrol_entries.plant_id', $selectedPlant)
->whereDate('guard_patrol_entries.patrol_time', $selectedDate)
->select('guard_names.name')
->distinct()
->orderBy('guard_names.name')
->pluck('name');
if ($guardNames->isEmpty()) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => 'Guard names not found for the selected plant and date.'
], 404);
}
return response()->json([
'status_code' => 'SUCCESS',
'status_description' => $guardNames,
]);
}
/**
* 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

@@ -0,0 +1,91 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ModuleInvoiceDataController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index()
{
//
}
public function get_invoiceData(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);
}
$moduleName = $request->header('invoice-type-list');
if (empty($moduleName))
{
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Invoice type can't be empty!"
], 404);
}
$headerValue = $request->header('invoice-type-list');
if ($headerValue != 'Invoice Type List') {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Invalid value for 'invoice-type-list' header!"
], 404);
}
$invoiceTypes = ['All Invoice', 'Serial Invoice', 'Individual Invoice', 'Bundle Invoice'];
return response()->json([
'status_code' => 'SUCCESS',
'status_description' => $invoiceTypes
], 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

@@ -0,0 +1,274 @@
<?php
namespace App\Http\Controllers;
use App\Models\InvoiceValidation;
use App\Models\Plant;
use Illuminate\Http\Request;
class ModuleInvoiceQuantityController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index()
{
//
}
// public function get_invoiceQuantityData(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);
// }
// $plantName = $request->header('plant-name');
// $filterHeader = $request->header('filter-name');
// $invoiceHeader = $request->header('invoice-name');
// if (empty($plantName) || empty($invoiceHeader) || empty($filterHeader)) {
// return response()->json([
// 'status_code' => 'ERROR',
// 'status_description' => "Missing required headers: plant-name, invoice-name, or filter-name"
// ], 404);
// }
// $validFilters = ['Today', 'Yesterday', 'This Week', 'This Month'];
// if (!in_array($filterHeader, $validFilters)) {
// return response()->json([
// 'status_code' => 'ERROR',
// 'status_description' => "Invalid filter-name value! Accepted values are: " . implode(', ', $validFilters)
// ], 404);
// }
// $validInvoiceFilters = ['All Invoice', 'Serial Invoice', 'Individual Invoice', 'Bundle Invoice'];
// if (!in_array($invoiceHeader, $validInvoiceFilters)) {
// return response()->json([
// 'status_code' => 'ERROR',
// 'status_description' => "Invalid invoice-name value! Accepted values are: " . implode(', ', $validInvoiceFilters)
// ], 404);
// }
// $plant = Plant::where('name', $plantName)->first();
// if (!$plant) {
// return response()->json([
// 'status_code' => 'ERROR',
// 'status_description' => "Plant '{$plantName}' not found!"
// ], 404);
// }
// $selectedPlant = $plant->id;
// $activeFilter = strtolower(trim($filterHeader));
// $selectedInvoice = strtolower(trim($invoiceHeader));
// // Set time range
// if ($activeFilter == 'yesterday') {
// $startDate = now()->subDay()->setTime(8, 0, 0);
// $endDate = now()->setTime(8, 0, 0);
// } elseif ($activeFilter == 'this week') {
// $startDate = now()->startOfWeek()->setTime(8, 0, 0);
// $endDate = now()->endOfWeek()->addDay()->setTime(8, 0, 0);
// } elseif ($activeFilter == 'this month') {
// $startDate = now()->startOfMonth()->setTime(8, 0, 0);
// $endDate = now()->endOfMonth()->addDay()->setTime(8, 0, 0);
// } else {
// $startDate = now()->setTime(8, 0, 0);
// $endDate = now()->copy()->addDay()->setTime(8, 0, 0);
// }
// $labels = [];
// $datasets = [];
// }
/**
* Store a newly created resource in storage.
*/
public function get_invoiceQuantityData(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);
}
$plantName = $request->header('plant-name');
$filterHeader = $request->header('filter-name');
$invoiceHeader = $request->header('invoice-name');
if (empty($plantName) || empty($invoiceHeader) || empty($filterHeader)) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Missing required headers: plant-name, invoice-name, or filter-name"
], 404);
}
$validFilters = ['Today', 'Yesterday', 'This Week', 'This Month'];
if (!in_array($filterHeader, $validFilters)) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Invalid filter-name value! Accepted values are: " . implode(', ', $validFilters)
], 404);
}
$validInvoiceFilters = ['All Invoice', 'Serial Invoice', 'Individual Invoice', 'Bundle Invoice'];
if (!in_array($invoiceHeader, $validInvoiceFilters)) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Invalid invoice-name value! Accepted values are: " . implode(', ', $validInvoiceFilters)
], 404);
}
$plant = Plant::where('name', $plantName)->first();
if (!$plant) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Plant '{$plantName}' not found!"
], 404);
}
$selectedPlant = $plant->id;
$activeFilter = strtolower(trim($filterHeader));
$selectedInvoice = strtolower(trim($invoiceHeader));
// Set time range
if ($activeFilter == 'yesterday') {
$startDate = now()->subDay()->setTime(8, 0, 0);
$endDate = now()->setTime(8, 0, 0);
} elseif ($activeFilter == 'this week') {
$startDate = now()->startOfWeek()->setTime(8, 0, 0);
$endDate = now()->endOfWeek()->addDay()->setTime(8, 0, 0);
} elseif ($activeFilter == 'this month') {
$startDate = now()->startOfMonth()->setTime(8, 0, 0);
$endDate = now()->endOfMonth()->addDay()->setTime(8, 0, 0);
} else {
$startDate = now()->setTime(8, 0, 0);
$endDate = now()->copy()->addDay()->setTime(8, 0, 0);
}
$types = ['individual_invoice', 'serial_invoice', 'bundle_invoice'];
if ($selectedInvoice != 'all invoice') {
$types = [str_replace(' ', '_', $selectedInvoice)];
}
$labels = ['Total Invoices', 'Scanned Invoices'];
$datasets = [];
$totals = [];
$scanneds = [];
foreach ($types as $type) {
$query = InvoiceValidation::where('plant_id', $selectedPlant)
->whereBetween('created_at', [$startDate, $endDate]);
$completedQuery = InvoiceValidation::where('plant_id', $selectedPlant)
->whereBetween('updated_at', [$startDate, $endDate]);
if ($type == 'individual_invoice') {
$query->where('quantity', 1);
$completedQuery->where('quantity', 1)
->whereNotNull('serial_number')
->where('serial_number', '!=', '');
} elseif ($type == 'serial_invoice') {
$query->whereNull('quantity');
$completedQuery->where('scanned_status', 'Scanned')
->where(function ($q) {
$q->whereNull('quantity')->orWhere('quantity', 0);
});
} elseif ($type == 'bundle_invoice') {
$query->where('quantity', '>', 1);
$completedQuery->where('quantity', '>', 1)
->whereNotNull('serial_number')
->where('serial_number', '!=', '');
}
$totals[] = $query->count();
$scanneds[] = $completedQuery->count();
}
// if (count($types) == 1) {
// $datasets[] = [
// 'label' => 'Invoices',
// 'data' => [$totals[0], $scanneds[0]],
// ];
// }
if (count($types) == 1)
{
$invoiceLabel = ucwords(str_replace('_invoice', '', str_replace('_', ' ', $types[0])));
$datasets[] = [
'label' => $invoiceLabel, // e.g., Serial Invoice
'data' => [$totals[0], $scanneds[0]],
];
}
else
{
$datasets[] = [
'label' => 'Total Invoices',
'data' => $totals,
];
$datasets[] = [
'label' => 'Scanned Invoices',
'data' => $scanneds,
];
$labels = array_map(function ($type) {
return ucwords(str_replace('_invoice', '', str_replace('_', ' ', $type)));
}, $types);
}
foreach ($datasets as &$dataset) {
$dataset['data'] = array_map(function ($value) {
return $value ?? 0;
}, $dataset['data']);
}
return response()->json([
'status_code' => 'SUCCESS',
'labels' => $labels,
'datasets' => $datasets,
], 200);
}
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

@@ -0,0 +1,554 @@
<?php
namespace App\Http\Controllers;
use App\Models\InvoiceValidation;
use App\Models\ModuleList;
use App\Models\Plant;
use Illuminate\Http\Request;
class ModuleInvoiceTypeController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index()
{
//
}
public function get_invoiceFilter(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);
}
$filterName = $request->header('filter-name');
if (empty($filterName))
{
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Filter Name can't be empty!"
], 404);
}
$headerValue = $request->header('filter-name');
if ($headerValue != 'Filter List') {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Invalid value for 'module-name' header!"
], 404);
}
$uniqueModules = ModuleList::select('filter_name', 'created_at')
->orderBy('created_at', 'asc')
->get()
->unique('filter_name')
->pluck('filter_name')
->values();
if ($uniqueModules->isEmpty()) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => 'Filter names not found'
], 404);
}
return response()->json([
'status_code' => 'SUCCESS',
'status_description' => $uniqueModules
], 200);
}
// public function get_invoiceCountData(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);
// }
// $moduleName = $request->header('invoice-name');
// if (empty($moduleName))
// {
// return response()->json([
// 'status_code' => 'ERROR',
// 'status_description' => "Invoice name can't be empty!"
// ], 404);
// }
// $plantName = $request->header('plant-name');
// $selectedInvoice = strtolower(trim($request->header('invoice-name')));
// $activeFilter = strtolower(trim($request->header('filter-name')));
// $plant = Plant::where('name', $plantName)->first();
// if (!$plant) {
// return response()->json([
// 'status_code' => 'ERROR',
// 'status_description' => "Plant '{$plantName}' not found!"
// ], 404);
// }
// $selectedPlant = $plant->id;
// if (empty($selectedInvoice) || empty($selectedPlant) || empty($activeFilter)) {
// return response()->json([
// 'status_code' => 'ERROR',
// 'status_description' => 'Missing required headers: invoice-name, plant-name, or filter-name'
// ], 404);
// }
// $validFilters = ['Today', 'Yesterday', 'This Week', 'This Month'];
// $filterHeader = $request->header('filter-name');
// if (!in_array($filterHeader, $validFilters)) {
// return response()->json([
// 'status_code' => 'ERROR',
// 'status_description' => "Invalid filter-name value! Accepted values are: " . implode(', ', $validFilters)
// ], 404);
// }
// $validInvoiceFilters = ['All Invoice', 'Serial Invoice', 'Individual Invoice', 'Bundle Invoice'];
// $filterInvoice = $request->header('invoice-name');
// if (!in_array($filterInvoice, $validInvoiceFilters)) {
// return response()->json([
// 'status_code' => 'ERROR',
// 'status_description' => "Invalid invoice-name value! Accepted values are: " . implode(', ', $validInvoiceFilters)
// ], 404);
// }
// if ($activeFilter == 'yesterday') {
// $startDate = now()->subDay()->setTime(8, 0, 0);
// $endDate = now()->setTime(8, 0, 0);
// } elseif ($activeFilter == 'this week') {
// $startDate = now()->startOfWeek()->setTime(8, 0, 0);
// $endDate = now()->endOfWeek()->addDay()->setTime(8, 0, 0);
// } elseif ($activeFilter == 'this month') {
// $startDate = now()->startOfMonth()->setTime(8, 0, 0);
// $endDate = now()->endOfMonth()->addDay()->setTime(8, 0, 0);
// } else {
// $startDate = now()->setTime(8, 0, 0);
// $endDate = now()->copy()->addDay()->setTime(8, 0, 0);
// }
// $labels = [];
// $datasets = [];
// if ($activeFilter == 'yesterday' || $activeFilter == 'today')
// {
// // === Imported Invoices ===
// $importedQuery = InvoiceValidation::where('plant_id', $selectedPlant)
// ->whereBetween('created_at', [$startDate, $endDate]);
// if ($selectedInvoice == 'individual invoice') {
// $importedQuery->where('quantity', 1);
// } elseif ($selectedInvoice == 'serial invoice') {
// $importedQuery->whereNull('quantity');
// } elseif ($selectedInvoice == 'bundle invoice') {
// $importedQuery->where('quantity', '>', 1);
// }
// $importedCount = $importedQuery->distinct('invoice_number')->count('invoice_number');
// // === Completed Invoices ===
// $completedQuery = InvoiceValidation::select('invoice_number')
// ->where('plant_id', $selectedPlant)
// ->whereBetween('updated_at', [$startDate, $endDate]);
// if ($selectedInvoice == 'individual invoice') {
// $completedQuery->where('quantity', 1)
// ->groupBy('invoice_number')
// ->havingRaw("COUNT(*) = SUM(CASE WHEN serial_number IS NOT NULL AND serial_number != '' THEN 1 ELSE 0 END)");
// } elseif ($selectedInvoice == 'serial invoice') {
// $completedQuery->whereNull('quantity')
// ->groupBy('invoice_number')
// ->havingRaw("COUNT(*) = SUM(CASE WHEN scanned_status = 'Scanned' THEN 1 ELSE 0 END)");
// } elseif ($selectedInvoice == 'bundle invoice') {
// $completedQuery->where('quantity', '>', 1)
// ->groupBy('invoice_number')
// ->havingRaw("COUNT(*) = SUM(CASE WHEN serial_number IS NOT NULL AND serial_number != '' THEN 1 ELSE 0 END)");
// }
// $completedCount = $completedQuery->count();
// $labels = ['Imported Invoice', 'Completed Invoice'];
// $datasets = [[
// 'label' => 'Invoices',
// 'data' => [$importedCount, $completedCount],
// ]];
// }
// elseif ($activeFilter == 'this week') {
// $labels = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
// $imported = array_fill(0, 7, 0);
// $completed = array_fill(0, 7, 0);
// for ($i = 0; $i < 7; $i++) {
// $dayStart = now()->startOfWeek()->addDays($i)->setTime(8, 0, 0);
// $dayEnd = $dayStart->copy()->addDay()->setTime(8, 0, 0);
// $importedQuery = InvoiceValidation::where('plant_id', $selectedPlant)
// ->whereBetween('created_at', [$dayStart, $dayEnd]);
// $completedQuery = InvoiceValidation::select('invoice_number')
// ->where('plant_id', $selectedPlant)
// ->whereBetween('updated_at', [$dayStart, $dayEnd]);
// if ($selectedInvoice == 'individual invoice') {
// $importedQuery->where('quantity', 1);
// $completedQuery->where('quantity', 1)
// ->groupBy('invoice_number')
// ->havingRaw("COUNT(*) = SUM(CASE WHEN serial_number IS NOT NULL AND serial_number != '' THEN 1 ELSE 0 END)");
// } elseif ($selectedInvoice == 'serial invoice') {
// $importedQuery->whereNull('quantity');
// $completedQuery->whereNull('quantity')
// ->groupBy('invoice_number')
// ->havingRaw("COUNT(*) = SUM(CASE WHEN scanned_status = 'Scanned' THEN 1 ELSE 0 END)");
// } elseif ($selectedInvoice == 'bundle invoice') {
// $importedQuery->where('quantity', '>', 1);
// $completedQuery->where('quantity', '>', 1)
// ->groupBy('invoice_number')
// ->havingRaw("COUNT(*) = SUM(CASE WHEN serial_number IS NOT NULL AND serial_number != '' THEN 1 ELSE 0 END)");
// }
// $imported[$i] = $importedQuery->distinct('invoice_number')->count('invoice_number');
// $completed[$i] = $completedQuery->count();
// }
// $datasets = [
// ['label' => 'Imported Invoices', 'data' => $imported],
// ['label' => 'Completed Invoices', 'data' => $completed],
// ];
// }
// elseif ($activeFilter == 'this month') {
// $startOfMonth = now()->startOfMonth()->setTime(8, 0, 0);
// $endOfMonth = now()->endOfMonth()->addDay()->setTime(8, 0, 0);
// $labels = [];
// $imported = [];
// $completed = [];
// $weekStart = $startOfMonth->copy();
// while ($weekStart < $endOfMonth) {
// $weekEnd = $weekStart->copy()->addDays(7);
// $label = $weekStart->format('M') . ' (' . $weekStart->format('j') . '-' . $weekEnd->subDay()->format('j') . ')';
// $labels[] = $label;
// $importedQuery = InvoiceValidation::where('plant_id', $selectedPlant)
// ->whereBetween('created_at', [$weekStart, $weekEnd]);
// $completedQuery = InvoiceValidation::select('invoice_number')
// ->where('plant_id', $selectedPlant)
// ->whereBetween('updated_at', [$weekStart, $weekEnd]);
// if ($selectedInvoice == 'individual invoice') {
// $importedQuery->where('quantity', 1);
// $completedQuery->where('quantity', 1)
// ->groupBy('invoice_number')
// ->havingRaw("COUNT(*) = SUM(CASE WHEN serial_number IS NOT NULL AND serial_number != '' THEN 1 ELSE 0 END)");
// } elseif ($selectedInvoice == 'serial invoice') {
// $importedQuery->whereNull('quantity');
// $completedQuery->whereNull('quantity')
// ->groupBy('invoice_number')
// ->havingRaw("COUNT(*) = SUM(CASE WHEN scanned_status = 'Scanned' THEN 1 ELSE 0 END)");
// } elseif ($selectedInvoice == 'bundle invoice') {
// $importedQuery->where('quantity', '>', 1);
// $completedQuery->where('quantity', '>', 1)
// ->groupBy('invoice_number')
// ->havingRaw("COUNT(*) = SUM(CASE WHEN serial_number IS NOT NULL AND serial_number != '' THEN 1 ELSE 0 END)");
// }
// $imported[] = $importedQuery->distinct('invoice_number')->count('invoice_number');
// $completed[] = $completedQuery->count();
// $weekStart = $weekEnd;
// }
// $datasets = [
// ['label' => 'Imported Invoices', 'data' => $imported],
// ['label' => 'Completed Invoices', 'data' => $completed],
// ];
// }
// // Clean zero values to null
// foreach ($datasets as &$dataset) {
// $dataset['data'] = array_map(function ($value) {
// return ($value === null) ? 0 : $value;
// }, $dataset['data']);
// }
// return response()->json([
// 'status_code' => 'SUCCESS',
// 'labels' => $labels,
// 'datasets' => $datasets,
// ], 200);
// }
/**
* Store a newly created resource in storage.
*/
public function get_invoiceCountData(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);
}
$plantName = $request->header('plant-name');
$filterHeader = $request->header('filter-name');
$invoiceHeader = $request->header('invoice-name');
if (empty($plantName) || empty($invoiceHeader) || empty($filterHeader)) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Missing required headers: plant-name, invoice-name, or filter-name"
], 404);
}
$validFilters = ['Today', 'Yesterday', 'This Week', 'This Month'];
if (!in_array($filterHeader, $validFilters)) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Invalid filter-name value! Accepted values are: " . implode(', ', $validFilters)
], 404);
}
$validInvoiceFilters = ['All Invoice', 'Serial Invoice', 'Individual Invoice', 'Bundle Invoice'];
if (!in_array($invoiceHeader, $validInvoiceFilters)) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Invalid invoice-name value! Accepted values are: " . implode(', ', $validInvoiceFilters)
], 404);
}
$plant = Plant::where('name', $plantName)->first();
if (!$plant) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Plant '{$plantName}' not found!"
], 404);
}
$selectedPlant = $plant->id;
$activeFilter = strtolower(trim($filterHeader));
$selectedInvoice = strtolower(trim($invoiceHeader));
// Set time range
if ($activeFilter == 'yesterday') {
$startDate = now()->subDay()->setTime(8, 0, 0);
$endDate = now()->setTime(8, 0, 0);
} elseif ($activeFilter == 'this week') {
$startDate = now()->startOfWeek()->setTime(8, 0, 0);
$endDate = now()->endOfWeek()->addDay()->setTime(8, 0, 0);
} elseif ($activeFilter == 'this month') {
$startDate = now()->startOfMonth()->setTime(8, 0, 0);
$endDate = now()->endOfMonth()->addDay()->setTime(8, 0, 0);
} else {
$startDate = now()->setTime(8, 0, 0);
$endDate = now()->copy()->addDay()->setTime(8, 0, 0);
}
$labels = [];
$datasets = [];
// Map types for All Invoice
$invoiceTypes = $selectedInvoice == 'all invoice'
? [
'Individual Invoice' => fn($q) => $q->where('quantity', 1),
'Serial Invoice' => fn($q) => $q->whereNull('quantity'),
'Bundle Invoice' => fn($q) => $q->where('quantity', '>', 1)
]
: [
ucfirst($selectedInvoice) => match ($selectedInvoice) {
'individual invoice' => fn($q) => $q->where('quantity', 1),
'serial invoice' => fn($q) => $q->whereNull('quantity'),
'bundle invoice' => fn($q) => $q->where('quantity', '>', 1),
}
];
foreach ($invoiceTypes as $labelPrefix => $queryModifier) {
if ($activeFilter == 'yesterday' || $activeFilter == 'today') {
$importedQuery = InvoiceValidation::where('plant_id', $selectedPlant)
->whereBetween('created_at', [$startDate, $endDate]);
$queryModifier($importedQuery);
$importedCount = $importedQuery->distinct('invoice_number')->count('invoice_number');
$completedQuery = InvoiceValidation::select('invoice_number')
->where('plant_id', $selectedPlant)
->whereBetween('updated_at', [$startDate, $endDate]);
if ($selectedInvoice == 'serial invoice' || $labelPrefix == 'Serial Invoice') {
$queryModifier($completedQuery)
->groupBy('invoice_number')
->havingRaw("COUNT(*) = SUM(CASE WHEN scanned_status = 'Scanned' THEN 1 ELSE 0 END)");
} else {
$queryModifier($completedQuery)
->groupBy('invoice_number')
->havingRaw("COUNT(*) = SUM(CASE WHEN serial_number IS NOT NULL AND serial_number != '' THEN 1 ELSE 0 END)");
}
$completedCount = $completedQuery->count();
$labels = ['Imported Invoice', 'Completed Invoice'];
$datasets[] = [
'label' => "$labelPrefix",
'data' => [$importedCount, $completedCount],
];
}
elseif ($activeFilter == 'this week') {
$labels = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
$imported = array_fill(0, 7, 0);
$completed = array_fill(0, 7, 0);
for ($i = 0; $i < 7; $i++) {
$dayStart = now()->startOfWeek()->addDays($i)->setTime(8, 0, 0);
$dayEnd = $dayStart->copy()->addDay()->setTime(8, 0, 0);
$importedQuery = InvoiceValidation::where('plant_id', $selectedPlant)
->whereBetween('created_at', [$dayStart, $dayEnd]);
$queryModifier($importedQuery);
$imported[$i] = $importedQuery->distinct('invoice_number')->count('invoice_number');
$completedQuery = InvoiceValidation::select('invoice_number')
->where('plant_id', $selectedPlant)
->whereBetween('updated_at', [$dayStart, $dayEnd]);
if ($selectedInvoice == 'serial invoice' || $labelPrefix == 'Serial Invoice') {
$queryModifier($completedQuery)
->groupBy('invoice_number')
->havingRaw("COUNT(*) = SUM(CASE WHEN scanned_status = 'Scanned' THEN 1 ELSE 0 END)");
} else {
$queryModifier($completedQuery)
->groupBy('invoice_number')
->havingRaw("COUNT(*) = SUM(CASE WHEN serial_number IS NOT NULL AND serial_number != '' THEN 1 ELSE 0 END)");
}
$completed[$i] = $completedQuery->count();
}
$datasets[] = ['label' => "$labelPrefix Imported", 'data' => $imported];
$datasets[] = ['label' => "$labelPrefix Completed", 'data' => $completed];
}
elseif ($activeFilter == 'this month') {
$startOfMonth = now()->startOfMonth()->setTime(8, 0, 0);
$endOfMonth = now()->endOfMonth()->addDay()->setTime(8, 0, 0);
$labels = [];
$imported = [];
$completed = [];
$weekStart = $startOfMonth->copy();
while ($weekStart < $endOfMonth) {
$weekEnd = $weekStart->copy()->addDays(7);
$label = $weekStart->format('M') . ' (' . $weekStart->format('j') . '-' . $weekEnd->subDay()->format('j') . ')';
$labels[] = $label;
$importedQuery = InvoiceValidation::where('plant_id', $selectedPlant)
->whereBetween('created_at', [$weekStart, $weekEnd]);
$queryModifier($importedQuery);
$imported[] = $importedQuery->distinct('invoice_number')->count('invoice_number');
$completedQuery = InvoiceValidation::select('invoice_number')
->where('plant_id', $selectedPlant)
->whereBetween('updated_at', [$weekStart, $weekEnd]);
if ($selectedInvoice == 'serial invoice' || $labelPrefix == 'Serial Invoice') {
$queryModifier($completedQuery)
->groupBy('invoice_number')
->havingRaw("COUNT(*) = SUM(CASE WHEN scanned_status = 'Scanned' THEN 1 ELSE 0 END)");
} else {
$queryModifier($completedQuery)
->groupBy('invoice_number')
->havingRaw("COUNT(*) = SUM(CASE WHEN serial_number IS NOT NULL AND serial_number != '' THEN 1 ELSE 0 END)");
}
$completed[] = $completedQuery->count();
$weekStart = $weekEnd;
}
$datasets[] = ['label' => "$labelPrefix Imported", 'data' => $imported];
$datasets[] = ['label' => "$labelPrefix Completed", 'data' => $completed];
}
}
// Ensure 0 instead of null
foreach ($datasets as &$dataset) {
$dataset['data'] = array_map(fn($val) => $val === null ? 0 : $val, $dataset['data']);
}
return response()->json([
'status_code' => 'SUCCESS',
'labels' => $labels,
'datasets' => $datasets,
]);
}
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

@@ -0,0 +1,94 @@
<?php
namespace App\Http\Controllers;
use App\Models\Plant;
use Illuminate\Http\Request;
class ModulePlantController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index()
{
//
}
public function get_modulePlant(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);
}
$plantName = $request->header('plant-name');
if (empty($plantName))
{
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Plant Name can't be empty!"
], 404);
}
$headerValue = $request->header('plant-name');
if ($headerValue != 'Plant List') {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Invalid value for 'plant-name' header!"
], 404);
}
$plantNames = Plant::orderBy('created_at', 'asc')
->pluck('name')
->values();
return response()->json([
'status_code' => 'SUCCESS',
'status_description' => $plantNames
], 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

@@ -0,0 +1,184 @@
<?php
namespace App\Http\Controllers;
use App\Models\Line;
use App\Models\Plant;
use Illuminate\Http\Request;
class ModulePlantLineController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index()
{
//
}
// public function get_modulePlantLine(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);
// }
// $plantName = $request->header('plant-name');
// if (empty($plantName))
// {
// return response()->json([
// 'status_code' => 'ERROR',
// 'status_description' => "Plant Name can't be empty!"
// ], 404);
// }
// $plant = Plant::where('name', $plantName)->first();
// if (!$plant) {
// return response()->json([
// 'status_code' => 'ERROR',
// 'status_description' => "Plant '{$plantName}' not found!"
// ], 404);
// }
// $lineNames = Line::where('plant_id', $plant->id)
// ->orderBy('created_at', 'asc')
// ->pluck('name');
// if ($lineNames->isEmpty()) {
// return response()->json([
// 'status_code' => 'ERROR',
// 'status_description' => "No lines found for plant '{$plantName}'"
// ], 404);
// }
// // Prepend 'All Lines'
// $lineNames->prepend('All Lines')->values();
// return response()->json([
// 'status_code' => 'SUCCESS',
// 'status_description' => $lineNames,
// ], 200);
// }
public function get_modulePlantLine(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);
}
$plantName = $request->header('plant-name');
$chartName = $request->header('chart-name');
if (empty($plantName)) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Plant name can't be empty!"
], 404);
}
if (empty($chartName)) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Chart name can't be empty!"
], 404);
}
$plant = Plant::where('name', $plantName)->first();
if (!$plant)
{
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Plant '{$plantName}' not found!"
], 404);
}
// Load only lines NOT equal to FG Line
$nonFgLines = Line::where('plant_id', $plant->id)
//->where('type', '!=', 'FG Line')
->orderBy('created_at', 'asc')
->pluck('name')
->toArray();
if (empty($nonFgLines)) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "No non-FG lines found for plant '{$plantName}'"
], 404);
}
$normalizedChartName = strtolower(trim($chartName));
if ($normalizedChartName != 'production order count' && $normalizedChartName != 'production hourly count' && $normalizedChartName != 'production line stop count') {
array_unshift($nonFgLines, 'All Lines');
}
// if (strtolower(trim($chartName)) != 'production hourly count') {
// array_unshift($nonFgLines, 'All Lines');
// }
// Add "All Lines" to beginning and "FG Lines" at the end
// array_unshift($nonFgLines, 'All Lines');
// $nonFgLines[] = 'FG Line';
return response()->json([
'status_code' => 'SUCCESS',
'status_description' => $nonFgLines,
], 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

@@ -0,0 +1,107 @@
<?php
namespace App\Http\Controllers;
use App\Models\Line;
use App\Models\Plant;
use Illuminate\Http\Request;
class ModuleProductionFGLineController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index()
{
//
}
public function get_moduleFGFilterList(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);
}
$plantName = $request->header('plant-name');
$FGName = $request->header('fg-lines');
if (empty($plantName)) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Plant name can't be empty!"
], 404);
}
if (empty($FGName)) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "FG line name can't be empty!"
], 404);
}
$plant = Plant::where('name', $plantName)->first();
if (!$plant) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Plant '{$plantName}' not found!"
], 404);
}
$fgLines = Line::where('plant_id', $plant->id)
->where('type', $FGName)
->pluck('name'); // Only get line names
if ($fgLines->isEmpty()) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "No FG lines found for the selected plant and line!"
], 404);
}
return response()->json([
'status_code' => 'SUCCESS',
'status_description' => $fgLines,
]);
}
/**
* 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

@@ -0,0 +1,171 @@
<?php
namespace App\Http\Controllers;
use App\Models\Line;
use App\Models\Plant;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class ModuleProductionLineStopController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index()
{
//
}
public function get_moduleProductionLineStop(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);
}
$requiredHeaders = ['module-name', 'chart-name', 'plant-name', 'line-name', 'filter-name'];
$missingHeaders = [];
foreach ($requiredHeaders as $header) {
if (empty($request->header($header))) {
$missingHeaders[] = $header;
}
}
if (!empty($missingHeaders)) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => 'Missing required headers: ' . implode(', ', $missingHeaders)
], 404);
}
$plantName = $request->header('plant-name');
$lineName = $request->header('line-name');
$filterName = strtolower(trim($request->header('filter-name')));
$plant = Plant::where('name', $plantName)->first();
if (!$plant) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Plant '{$plantName}' not found!"
], 404);
}
$line = Line::where('name', $lineName)->where('plant_id', $plant->id)->first();
if (!$line) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Line '{$lineName}' not found for plant '{$plantName}'"
], 404);
}
// Set time range
if ($filterName == 'yesterday') {
$startDate = now()->subDay()->setTime(8, 0, 0);
$endDate = now()->setTime(8, 0, 0);
} elseif ($filterName == 'this week') {
$startDate = now()->startOfWeek()->setTime(8, 0, 0);
$endDate = now()->endOfWeek()->addDay()->setTime(8, 0, 0);
} elseif ($filterName == 'this month') {
$startDate = now()->startOfMonth();
$endDate = now()->endOfMonth();
} else {
$startDate = now()->setTime(8, 0, 0);
$endDate = now()->copy()->addDay()->setTime(8, 0, 0);
}
$query = DB::table('production_line_stops')
->join('line_stops as ls', 'production_line_stops.linestop_id', '=', 'ls.id')
->join('lines', 'production_line_stops.line_id', '=', 'lines.id')
->join('plants', 'production_line_stops.plant_id', '=', 'plants.id')
->select(
'ls.code',
'ls.reason',
DB::raw("SUM(production_line_stops.stop_hour) as total_stop_hours"),
DB::raw("SUM(production_line_stops.stop_min) as total_stop_minutes")
)
->where('plants.id', $plant->id)
->where('lines.id', $line->id)
->whereBetween('production_line_stops.created_at', [$startDate, $endDate])
->groupBy('ls.code', 'ls.reason')
->get();
if ($query->isEmpty()) {
return response()->json([
'status_code' => 'SUCCESS',
'labels' => ['No Data'],
'data' => [1],
], 200);
}
$labels = [];
$data = [];
$totalStopMinutes = 0;
foreach ($query as $row) {
$stopHours = $row->total_stop_hours;
$stopMinutes = $row->total_stop_minutes;
$visualTotal = $stopHours + ($stopMinutes / 100);
$labels[] = "{$row->code} - {$row->reason}";
$data[] = $visualTotal;
$totalStopMinutes += ($stopHours * 60) + $stopMinutes;
}
// Calculate available runtime
$remainingMinutes = 1440 - $totalStopMinutes;
$runtimeHours = floor($remainingMinutes / 60);
$runtimeMinutes = $remainingMinutes % 60;
$runtimeVisual = $runtimeHours + ($runtimeMinutes / 100);
$labels[] = 'Available Runtime';
$data[] = $runtimeVisual;
return response()->json([
'status_code' => 'SUCCESS',
'labels' => $labels,
'data' => $data,
], 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

@@ -0,0 +1,402 @@
<?php
namespace App\Http\Controllers;
use App\Models\Line;
use App\Models\Plant;
use App\Models\ProductionQuantity;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class ModuleProductionOrderDataController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index()
{
//
}
// public function get_moduleProductionOrder(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);
// }
// $requiredHeaders = [
// 'module-name',
// 'chart-name',
// 'plant-name',
// 'line-name',
// 'production-order',
// 'filter-name',
// ];
// $missingHeaders = [];
// foreach ($requiredHeaders as $header) {
// if (empty($request->header($header))) {
// $missingHeaders[] = $header;
// }
// }
// if (!empty($missingHeaders)) {
// return response()->json([
// 'status_code' => 'ERROR',
// 'status_description' => 'Missing required headers: ' . implode(', ', $missingHeaders)
// ], 404);
// }
// $validFilters = ['Today', 'Yesterday', 'This Week', 'This Month'];
// $filterHeader = $request->header('filter-name');
// if (!in_array($filterHeader, $validFilters)) {
// return response()->json([
// 'status_code' => 'ERROR',
// 'status_description' => "Invalid filter-name value! Accepted values are: " . implode(', ', $validFilters)
// ], 404);
// }
// $plantName = $request->header('plant-name');
// $lineName = $request->header('line-name');
// $orderValue = $request->header('production-order');
// $filterName = strtolower(trim($request->header('filter-name')));
// $plant = Plant::where('name', $plantName)->first();
// if (!$plant) {
// return response()->json([
// 'status_code' => 'ERROR',
// 'status_description' => "Plant '{$plantName}' not found!"
// ], 404);
// }
// $line = Line::where('name', $lineName)->where('plant_id', $plant->id)->first();
// if (!$line) {
// return response()->json([
// 'status_code' => 'ERROR',
// 'status_description' => 'Line not found!'
// ], 404);
// }
// $lineType = $line->type;
// if ($lineType === 'FG Line')
// {
// $table = 'quality_validations';
// }
// else
// {
// $table = 'production_quantities';
// }
// // Time Range
// if ($filterName == 'yesterday') {
// $startDate = now()->subDay()->setTime(8, 0, 0);
// $endDate = now()->setTime(8, 0, 0);
// $groupBy = "EXTRACT(HOUR FROM $table.created_at)";
// } elseif ($filterName == 'this week') {
// $startDate = now()->startOfWeek()->setTime(8, 0, 0);
// $endDate = now()->endOfWeek()->addDay()->setTime(8, 0, 0);
// $groupBy = "EXTRACT(DOW FROM $table.created_at)";
// } elseif ($filterName == 'this month') {
// $startDate = now()->startOfMonth();
// $endDate = now()->endOfMonth();
// $groupBy = "FLOOR((EXTRACT(DAY FROM $table.created_at) - 1) / 7) + 1";
// } else {
// $startDate = now()->setTime(8, 0, 0);
// $endDate = now()->copy()->addDay()->setTime(8, 0, 0);
// $groupBy = "EXTRACT(HOUR FROM $table.created_at)";
// }
// $query = \DB::table($table)
// ->join('plants', "$table.plant_id", '=', 'plants.id')
// ->join('lines', "$table.line_id", '=', 'lines.id')
// ->selectRaw("$groupBy AS time_unit, count(*) AS total_quantity")
// ->whereBetween("$table.created_at", [$startDate, $endDate])
// ->where('plants.id', $plant->id)
// ->where('lines.id', $line->id)
// ->where("$table.production_order", $orderValue)
// ->groupByRaw($groupBy)
// ->orderByRaw($groupBy)
// ->pluck('total_quantity', 'time_unit')
// ->toArray();
// if ($filterName == 'this month') {
// $weeksCount = ceil($endDate->day / 7);
// $allWeeks = array_fill(1, $weeksCount, 0);
// $data = array_replace($allWeeks, $query);
// $labels = [];
// for ($i = 1; $i <= $weeksCount; $i++) {
// $weekStart = $startDate->copy()->addDays(($i - 1) * 7)->format('d M');
// $weekEnd = $startDate->copy()->addDays($i * 7 - 1)->min($endDate)->format('d M');
// $labels[] = "Week $i ($weekStart - $weekEnd)";
// }
// $orderedData = array_values($data);
// } elseif ($filterName === 'this week') {
// $labels = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
// $data = array_fill(0, 7, 0);
// foreach ($query as $dow => $count) {
// $data[$dow] = $count;
// }
// $orderedData = [
// $data[1] ?? 0, $data[2] ?? 0, $data[3] ?? 0,
// $data[4] ?? 0, $data[5] ?? 0, $data[6] ?? 0,
// $data[0] ?? 0,
// ];
// } else {
// $allHours = array_fill(0, 24, 0);
// $data = array_replace($allHours, $query);
// $shiftedData = [];
// foreach ($data as $hour => $count) {
// $nextHour = ($hour + 1) % 24;
// $shiftedData[$nextHour] = $count;
// }
// $shiftedKeys = array_merge(range(9, 23), range(0, 8));
// $orderedData = array_map(fn($hour) => $shiftedData[$hour] ?? 0, $shiftedKeys);
// $labels = array_map(fn ($hour) => date("g A", strtotime("$hour:00")), $shiftedKeys);
// }
// $orderedData = array_map(function ($value) {
// return ($value == 0 || is_null($value)) ? null : $value;
// }, $orderedData);
// return response()->json([
// 'status_code' => 'SUCCESS',
// 'datasets' => [
// [
// 'label' => match ($filterName) {
// 'this week' => $lineType == 'FG Line' ? "Daily Fg Production Order Count This Week" : "Daily Production Order Count This Week",
// 'this month' => $lineType == 'FG Line' ? "Weekly Fg Production Order Count This Month" : "Weekly Production Order Count This Month",
// 'yesterday' => $lineType == 'FG Line' ? "Yesterday's Hourly Fg Order Count Production" : "Yesterday's Hourly Order Count Production",
// default => $lineType == 'FG Line' ? "Today's Hourly Fg Production Order Count" : "Today's Hourly Production Order Count",
// },
// 'data' => $orderedData,
// 'borderColor' => 'rgba(75, 192, 192, 1)',
// 'backgroundColor' => 'rgba(75, 192, 192, 0.2)',
// 'fill' => false,
// 'tension' => 0.3,
// ]
// ],
// 'labels' => $labels
// ], 200);
// }
public function get_moduleProductionOrder(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);
}
$requiredHeaders = [
'module-name', 'chart-name', 'plant-name',
'line-name', 'production-order', 'filter-name'
];
$missingHeaders = [];
foreach ($requiredHeaders as $header) {
if (empty($request->header($header))) {
$missingHeaders[] = $header;
}
}
if (!empty($missingHeaders)) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => 'Missing required headers: ' . implode(', ', $missingHeaders)
], 404);
}
$filterHeader = $request->header('filter-name');
$validFilters = ['Today', 'Yesterday', 'This Week', 'This Month'];
if (!in_array($filterHeader, $validFilters)) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Invalid filter-name value! Accepted values are: " . implode(', ', $validFilters)
], 404);
}
$plantName = $request->header('plant-name');
$lineName = $request->header('line-name');
$orderVal = $request->header('production-order');
$filter = strtolower($filterHeader);
$plant = Plant::where('name', $plantName)->first();
if (!$plant) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Plant '{$plantName}' not found!"
], 404);
}
$line = Line::where('name', $lineName)->where('plant_id', $plant->id)->first();
if (!$line) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Line '{$lineName}' not found!"
], 404);
}
$lineType = $line->type;
$table = ($lineType == 'FG Line') ? 'quality_validations' : 'production_quantities';
if ($filter == 'today' || $filter == 'yesterday') {
$hourlyCounts = [];
$hourStart = $filter == 'today'
? now()->setTime(8, 0, 0)
: now()->subDay()->setTime(8, 0, 0);
$hourEndFinal = $hourStart->copy()->addDay();
while ($hourStart < $hourEndFinal) {
$hourEnd = $hourStart->copy()->addHour();
$label = $hourStart->format('g:i A') . ' to ' . $hourEnd->format('g:i A');
$count = DB::table($table)
->where('plant_id', $plant->id)
->where('line_id', $line->id)
->where('production_order', $orderVal)
->whereBetween('created_at', [$hourStart, $hourEnd])
->count();
$hourlyCounts[$label] = $count;
$hourStart = $hourEnd;
}
return response()->json([
'status_code' => 'SUCCESS',
'datasets' => [
[
'label' => $filter == 'yesterday'
? "Yesterday's Hourly Production Order Count"
: "Today's Hourly Production Order Count",
'data' => $hourlyCounts
]
]
], 200);
}
// Weekly or Monthly
if ($filter == 'this week') {
$startDate = now()->startOfWeek()->setTime(8, 0, 0);
$endDate = now()->endOfWeek()->addDay()->setTime(8, 0, 0);
$groupBy = "EXTRACT(DOW FROM $table.created_at)";
} else {
$startDate = now()->startOfMonth();
$endDate = now()->endOfMonth();
$groupBy = "FLOOR((EXTRACT(DAY FROM $table.created_at) - 1) / 7) + 1";
}
$query = DB::table($table)
->where('plant_id', $plant->id)
->where('line_id', $line->id)
->where('production_order', $orderVal)
->whereBetween('created_at', [$startDate, $endDate])
->selectRaw("$groupBy as group_key, COUNT(*) as total")
->groupByRaw("group_key")
->pluck('total', 'group_key')
->toArray();
if ($filter == 'this week') {
$labels = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
$data = array_fill(0, 7, 0);
foreach ($query as $dow => $count) {
$data[$dow] = $count;
}
$orderedData = [
$data[1] ?? 0, $data[2] ?? 0, $data[3] ?? 0,
$data[4] ?? 0, $data[5] ?? 0, $data[6] ?? 0,
$data[0] ?? 0,
];
} else {
$weeksCount = ceil($endDate->day / 7);
$allWeeks = array_fill(1, $weeksCount, 0);
$data = array_replace($allWeeks, $query);
$labels = [];
for ($i = 1; $i <= $weeksCount; $i++) {
$weekStart = $startDate->copy()->addDays(($i - 1) * 7)->format('d M');
$weekEnd = $startDate->copy()->addDays($i * 7 - 1)->min($endDate)->format('d M');
$labels[] = "Week $i ($weekStart - $weekEnd)";
}
$orderedData = array_values($data);
}
return response()->json([
'status_code' => 'SUCCESS',
'datasets' => [
[
'label' => match ($filter) {
'this week' => $lineType == 'FG Line'
? "Daily Fg Production Order Count This Week"
: "Daily Production Order Count This Week",
'this month' => $lineType == 'FG Line'
? "Weekly Fg Production Order Count This Month"
: "Weekly Production Order Count This Month",
},
'data' => $orderedData
]
],
'labels' => $labels ?? []
], 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

@@ -0,0 +1,563 @@
<?php
namespace App\Http\Controllers;
use App\Models\Item;
use App\Models\Plant;
use App\Models\WeightValidation;
use Illuminate\Http\Request;
use Str;
class ObdController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index()
{
}
/**
* Store a newly created resource in storage.
*/
public function store(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("ERROR: Unauthorized", 403)
// ->header('Content-Type', 'text/plain');
// }
if ("Bearer " . $expectedToken != $header_auth)
{
return response()->json([
'status_code' => 'ERROR',
'status_description' => 'Invalid authorization token!'
], 403);
}
try
{
$data = $request->all();
// Validate required fields
$missing = [];
if (empty($data['plant_name'])) $missing[] = 'plant_name';
if (empty($data['obd_number'])) $missing[] = 'obd_number';
if (empty($data['line_numbers'])) $missing[] = 'line_numbers';
if (!empty($missing))
{
$message = "Missing required field(s): " . implode(', ', $missing);
// return response($message, 400)->header('Content-Type', 'text/plain');
return response()->json([
'status_code' => 'ERROR',
'status_description' => $message,
], 400);
}
// OBD Number validation
$obdNumber = $data['obd_number'];
if (Str::length($obdNumber) < 8 || !ctype_alnum($obdNumber))
{
// return response("ERROR: OBD Number should contain minimum 8 digits", 400)
// ->header('Content-Type', 'text/plain');
return response()->json([
'status_code' => 'ERROR',
'status_description' => "OBD number should contain minimum 8 digit alpha-numeric values only!"
], 400);
}
// Lookup plant_id by plant_name
$plantId = Plant::where('name', $data['plant_name'])->value('id');
if (!$plantId) {
// return response("ERROR: Plant '{$data['plant_name']}' not found", 404)
// ->header('Content-Type', 'text/plain');
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Plant '{$data['plant_name']}' not found!"
], 404);
}
//Check if OBD number exists for that plant
$obdRecords = WeightValidation::where('plant_id', $plantId)
->where('obd_number', $obdNumber)
->exists();
if (!$obdRecords)
{
// return response( "ERROR: OBD Number '$obdNumber' not found for plant '{$data['plant_name']}'",404)->header('Content-Type', 'text/plain');
return response()->json([
'status_code' => 'ERROR',
'status_description' => "OBD Number '$obdNumber' not found for plant '{$data['plant_name']}'!"
], 404);
}
$missingLines = [];
$alreadyUpdatedLines = [];
foreach ($data['line_numbers'] as $line)
{
if ($line['line_number'] == '' || $line['line_number'] == null)
{
// return response("ERROR: Line Number can't be empty", 400)
// ->header('Content-Type', 'text/plain');
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Line Number can't be empty!"
], 404);
}
$record = WeightValidation::where('plant_id', $plantId)
->where('obd_number', $data['obd_number'])
->where('line_number', $line['line_number'])
->first();
if (!$record)
{
$missingLines[] = $line['line_number'];
continue;
}
$mandatoryFields = ['vehicle_number', 'bundle_number', 'heat_number', 'picked_weight', 'scanned_by'];
$missingFields = [];
foreach ($mandatoryFields as $field)
{
if ($line[$field] == '' || $line[$field] == null)
{
$missingFields[] = ucwords(str_replace('_', ' ', $field));
}
}
if (!empty($missingFields))
{
if (count($missingFields) == 1)
{
$fieldsString = $missingFields[0];
}
else
{
$lastField = array_pop($missingFields);
$fieldsString = implode(', ', $missingFields) . ' and ' . $lastField;
}
$message = $fieldsString . " can't be empty for line_number {$line['line_number']}!";
// return response($message, 400)->header('Content-Type', 'text/plain');
return response()->json([
'status_code' => 'ERROR',
'status_description' => $message
], 400);
}
}
if (!empty($missingLines)) {
$message = "Line(s) " . implode(', ', $missingLines) . " not found for Plant '{$data['plant_name']}' and OBD Number: '{$data['obd_number']}'!";
// return response($message, 404)->header('Content-Type', 'text/plain');
return response()->json([
'status_code' => 'ERROR',
'status_description' => $message
], 404);
}
$seenPairs = [];
$internalDuplicates = [];
$bundleChecks = [];
//Check for duplicates within the request
foreach ($data['line_numbers'] as $line) {
$lineNumber = $line['line_number'];
$bundleNumber = trim((string)$line['bundle_number']);
$pairKey = $lineNumber . '|' . $bundleNumber;
if (isset($seenPairs[$pairKey])) {
$internalDuplicates[] = "Line Number {$lineNumber} with Bundle Number {$bundleNumber}";
} else {
$seenPairs[$pairKey] = true;
$bundleChecks[] = [
'line_number' => $lineNumber,
'bundle_number' => $bundleNumber,
];
}
}
//Check for duplicates in the database
$bundleNumbers = array_column($bundleChecks, 'bundle_number');
$lineNumbers = array_column($bundleChecks, 'line_number');
$existingBundles = WeightValidation::where('plant_id', $plantId)
->where('obd_number', $obdNumber)
->whereIn('line_number', $lineNumbers)
->whereIn('bundle_number', $bundleNumbers)
->get(['line_number', 'bundle_number']);
$grouped = [];
foreach ($existingBundles as $row) {
$line = $row->line_number;
$bundle = $row->bundle_number;
if (!isset($grouped[$line])) {
$grouped[$line] = [];
}
if ($bundle && !in_array($bundle, $grouped[$line])) {
$grouped[$line][] = $bundle;
}
}
$dbDuplicates = [];
foreach ($grouped as $line => $bundles) {
$bundlesStr = implode(', ', $bundles);
$dbDuplicates[] = "Line {$line}, has bundle numbers : {$bundlesStr}";
}
//Return all errors if any duplicates found
$allDuplicates = [];
if (!empty($internalDuplicates))
{
$allDuplicates[] = "Duplicate(s) " . implode(', ', $internalDuplicates);
}
if (!empty($dbDuplicates))
{
$allDuplicates[] = "Already exists in database: " . implode('; ', $dbDuplicates);
}
if (!empty($allDuplicates)) {
// return response(
// "Error:" . implode("\n", $allDuplicates),
// 400
// )->header('Content-Type', 'text/plain');
$retRes = implode(", and ", $allDuplicates);
return response()->json([
'status_code' => 'ERROR',
'status_description' => $retRes
], 400);
}
//..
$updated = 0;
$inserted = 0;
$updatedLines = [];
$insertedLines = [];
$lineTracker = [];
foreach ($data['line_numbers'] as $line)
{
$lineNumber = $line['line_number'];
$existing = WeightValidation::where('plant_id', $plantId)
->where('obd_number', $obdNumber)
->where('line_number', $lineNumber)
->where(function ($query) {
$query->whereNull('bundle_number')
->orWhere('bundle_number', '');
})
->first();
if($existing)
{
$existing->update([
'vehicle_number' => $line['vehicle_number'] ?? null,
'bundle_number' => $line['bundle_number'] ?? null,
'heat_number' => $line['heat_number'] ?? null,
'picked_weight' => $line['picked_weight'] ?? null,
'scanned_by' => $line['scanned_by'] ?? null,
'updated_at' => now(),
]);
$updated++;
$updatedLines[] = $lineNumber;
$lineTracker[$lineNumber] = 1;
}
else
{
$original = WeightValidation::where([
'plant_id' => $plantId,
'obd_number' => $obdNumber,
'line_number' => $lineNumber,
])->orderBy('id')->first();
WeightValidation::create([
'plant_id' => $plantId,
'obd_number' => $obdNumber,
'line_number' => $lineNumber,
'item_id' => $original->item_id ?? null,
'vehicle_number' => $line['vehicle_number'] ?? null,
'bundle_number' => $line['bundle_number'] ?? null,
'picked_weight' => $line['picked_weight'] ?? null,
'scanned_by' => $line['scanned_by'] ?? null,
'batch_number' => $original->batch_number ?? null,
'heat_number' => $line['heat_number'] ?? null,
'obd_weight' => $original->obd_weight ?? null,
'created_at' => now(),
'updated_at' => now(),
]);
$inserted++;
$insertedLines[] = $lineNumber;
$lineTracker[$lineNumber] = isset($lineTracker[$lineNumber]) ? $lineTracker[$lineNumber] + 1 : 1;
}
}
$responseMessage = "OBD Number '{$obdNumber}'";
if ($updated > 0) {
$responseMessage .= " updated successfully. Line Numbers: {" . implode(', ', $updatedLines) . "}";
}
if ($inserted > 0) {
$responseMessage .= "Inserted successfully. Line Numbers: {" . implode(', ', $insertedLines) . "}";
}
// return response($responseMessage, 200)
// ->header('Content-Type', 'text/plain');
return response()->json([
'status_code' => 'SUCCESS',
'status_description' => $responseMessage,
], 200);
}
catch (\Exception $e)
{
// response("ERROR: Server error", 500)->header('Content-Type', 'text/plain');
return response()->json([
'status_code' => 'ERROR',
'status_description' => 'Store OBD data internal server error : '.$e?->getCode()
], 500);
}
}
//Route::get('obd/get-test-datas', [ObdController::class, 'get_test']);
public function get_test(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 (empty($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))
// {
// return response()->json([
// 'status_code' => 'ERROR',
// 'status_description' => "Plant code should contain minimum 4 digits numeric values only!"
// ], 400);
// }
// $plantId = Plant::where('code', $plantCode)->value('id');
// if (!$plantId)
// {
// return response()->json([
// 'status_code' => 'ERROR',
// 'status_description' => "Plant code not found"
// ], 400);
// }
$productionOrder = $request->header('production-order');
if (empty($productionOrder))
{
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Production order can't be empty!"
], 400);
}
else if(Str::length($productionOrder) < 7 || !is_numeric($productionOrder))
{
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Production order should contain minimum 7 digits numeric values only!"
], 400);
}
$prodOrderExist = ($productionOrder == '1234567' || $productionOrder == '7654321');
if (!$prodOrderExist)
{
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Production order not found!"
], 400);
}
try
{
//return response("Successfully GET request Received", 200)->header('Content-Type', 'text/plain');
$itemCode = Item::where('code', '123456')->where('plant_id', 1)->first();
return response()->json([
'item_code' => $itemCode->code,
'item_description' => $itemCode->description
], 200);
}
catch (\Exception $e)
{
//return response("ERROR: GET test data server error", 500)->header('Content-Type', 'text/plain');
return response()->json([
'status_code' => 'ERROR',
'status_description' => 'Get test data internal server error : '.$e?->getCode()
], 500);
}
}
public function get_obd(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("ERROR: Unauthorized", 403)
// ->header('Content-Type', 'text/plain');
// }
if ("Bearer " . $expectedToken != $header_auth)
{
return response()->json([
'status_code' => 'ERROR',
'status_description' => 'Invalid authorization token!'
], 403);
}
$plantName = $request->header('plant-name');
$obdNumber = $request->header('obd-number');
if (empty($plantName))
{
// return response("ERROR: Plant Name can't be empty", 400)
// ->header('Content-Type', 'text/plain');
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Plant Name can't be empty!"
], 400);
}
else if(empty($obdNumber))
{
// return response("ERROR: OBD Number can't be empty", 400)
// ->header('Content-Type', 'text/plain');
return response()->json([
'status_code' => 'ERROR',
'status_description' => "OBD Number can't be empty!"
], 400);
}
else if(Str::length($obdNumber) < 8 || !ctype_alnum($obdNumber))
{
// return response("ERROR: OBD Number should contain minimum 8 digits: '$obdNumber'", 400)
// ->header('Content-Type', 'text/plain');
return response()->json([
'status_code' => 'ERROR',
'status_description' => "OBD number should contain minimum 8 digit alpha-numeric values only!"
], 400);
}
// Fetch the plant id by name
$plantId = Plant::where('name', $plantName)->value('id');
if (!$plantId) {
// return response("ERROR: Plant not found", 400)
// ->header('Content-Type', 'text/plain');
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Plant not found!"
], 400);
}
// $records = WeightValidation::where('plant_id', $plantId)
// ->where('obd_number', $obdNumber)
// ->get();
// Fetch and filter records where vehicle_number is empty or null
$exists = WeightValidation::where('plant_id', $plantId)
->where('obd_number', $obdNumber)
->exists();
if (!$exists)
{
// return response("ERROR: OBD number $obdNumber does not exist for plant '$plantName'", 404)
// ->header('Content-Type', 'text/plain');
return response()->json([
'status_code' => 'ERROR',
'status_description' => "OBD number $obdNumber does not exist for plant '$plantName'!"
], 400);
}
$records = WeightValidation::where('plant_id', $plantId)
->where('obd_number', $obdNumber)
->get()
->filter(function ($record) {
return $record->vehicle_number == '' || $record->vehicle_number == null;
});
if ($records->isEmpty()) {
// return response("SUCCESS: Already scanning process completed for the OBD Number", 200)->header('Content-Type', values: 'text/plain');
return response()->json([
'status_code' => 'SUCCESS',
'status_description' => "Already weight validation completed for the OBD Number!"
], 200);
}
$itemIds = $records->pluck('item_id')->unique();
$itemCodes = Item::whereIn('id', $itemIds)
->select('id', 'code', 'description')
->get()
->keyBy('id');
$ObdResponseStructure = [
'OBD_Number' => [
[
'OBD_Number' => $obdNumber,
'Line_Numbers' => $records->map(function ($item) use ($itemCodes) {
$itemInfo = $itemCodes[$item->item_id] ?? null;
return [
'Line' => $item->line_number ?? "",
'Material_Code' => $itemInfo->code ?? "",
'Material_Description' => $itemInfo->description ?? "",
'Batch_Number' => $item->batch_number ?? "",
// 'Heat_Number' => $item->heat_number ?? "",
'Actual_Weight' => $item->obd_weight ?? "",
];
})->values()->toArray()
]
]
];
return response()->json($ObdResponseStructure);
}
/**
* 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

@@ -0,0 +1,165 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Mpdf\Mpdf;
use Mpdf\QrCode\Output;
use Mpdf\QrCode\QrCode;
class PalletController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index()
{
//
}
public function downloadReprintQrPdf($palletNo)
{
$qrCode = new QrCode($palletNo);
$output = new Output\Png();
$qrBinary = $output->output($qrCode, 100);
$qrBase64 = base64_encode($qrBinary);
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: 0mm; padding-top: 0mm; }
.text-cell { text-align: left; vertical-align: middle; font-size: 20pt; 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>
<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>
<script>
window.onload = function () {
window.print();
setTimeout(function () {
window.close();
}, 500); // Wait 0.5 seconds 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');
}
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; 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>';
// $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 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

@@ -0,0 +1,892 @@
<?php
namespace App\Http\Controllers;
use App\Models\GrMaster;
use App\Models\Item;
use App\Models\Plant;
use App\Models\ProcessOrder;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Storage;
use Str;
class PdfController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index()
{
//
}
public function updateGR(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!',
], 404);
}
$data = $request->all();
if ($data['plant_code'] == null || $data['plant_code'] == '') {
// return response("ERROR: Please provide a valid plant code.", 400)
// ->header('Content-Type', 'text/plain');
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Plant code can't be empty!",
], 404);
} elseif (Str::length($data['plant_code']) < 4 || ! is_numeric($data['plant_code']) || ! preg_match('/^[1-9]\d{3,}$/', $data['plant_code'])) {// !ctype_digit($data['plant_code'])
return response()->json([
'status_code' => 'ERROR',
'status_description' => 'Invalid plant code found!',
], 404);
}
$plant = Plant::where('code', $data['plant_code'])->first();
if (! $plant) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => 'Plant not found!',
], 404);
}
$plantId = $plant->id;
if ($data['gr_number'] == null || $data['gr_number'] == '') {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "GR Number can't be empty!",
], 404);
}
$grExists = GRMaster::where('plant_id', $plantId)
->where('gr_number', $data['gr_number'])
->first();
if (! $grExists) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "GR Number {$data['gr_number']} not found for plant {$data['plant_code']}!",
], 404);
}
$scannedBy = $data['scanned_by'] ?? null;
if ($scannedBy == '' || $scannedBy == null) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Scanned by can't be empty!",
], 404);
}
$user = User::where('name', $data['scanned_by'])
->first();
if (! $user) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "'{$data['scanned_by']}' user not found!",
], 404);
}
$itemCodes = array_column($data['item_codes'], 'item_code');
$duplicateItemCodes = array_unique(array_diff_assoc($itemCodes, array_unique($itemCodes)));
if (count($duplicateItemCodes) > 0) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => 'Duplicate item codes found in request!',
'duplicate_item_codes' => array_values($duplicateItemCodes),
], 404);
}
$allSerials = [];
foreach ($data['item_codes'] as $item) {
if (! isset($item['serial_numbers']) || ! is_array($item['serial_numbers'])) {
continue;
}
foreach ($item['serial_numbers'] as $serial) {
$allSerials[] = $serial;
}
}
$duplicateSerials = array_unique(array_diff_assoc($allSerials, array_unique($allSerials)));
if (count($duplicateSerials) > 0) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => 'Duplicate serial numbers found in request!',
'duplicate_serial_numbers' => array_values($duplicateSerials),
], 404);
}
$invalidLengthItemCodes = [];
foreach ($data['item_codes'] as $item) {
$itemCode = $item['item_code'] ?? null;
// Skip if item code is missing
if (! $itemCode) {
continue;
}
// Check if item code is less than 6 digits or not numeric
if (strlen($itemCode) < 6 || ! ctype_digit($itemCode)) {
$invalidLengthItemCodes[] = $itemCode;
}
}
if (count($invalidLengthItemCodes) > 0) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => 'Some item codes are invalid: must be at least 6 digits!',
'invalid_item_codes' => array_values($invalidLengthItemCodes),
], 404);
}
$invalidItemCodes = [];
$invalidPlantItems = [];
foreach ($data['item_codes'] as $item) {
$itemCode = $item['item_code'] ?? null;
if (! $itemCode) {
$invalidItemCodes[] = '(missing)';
continue;
}
$itemObj = Item::where('code', $itemCode)->first();
if (! $itemObj) {
$invalidItemCodes[] = $itemCode;
continue;
}
$itemPlant = Item::where('plant_id', $plantId)
->where('code', $itemCode)->first();
if (! $itemPlant) {
$invalidPlantItems[] = $itemCode;
}
}
if (count($invalidItemCodes) > 0 || count($invalidPlantItems) > 0) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => 'Some item codes are invalid!',
'not_found_items' => array_values($invalidItemCodes),
'not_in_plant' => array_values($invalidPlantItems),
], 404);
}
$missingSerialsByItem = [];
foreach ($data['item_codes'] as $item) {
$itemCode = $item['item_code'];
$serialNumbers = $item['serial_numbers'];
// Get the item id
$itemObj = Item::where('plant_id', $plantId)
->where('code', $itemCode)
->first();
if (! $itemObj) {
continue;
}
$itemId = $itemObj->id;
$foundSerials = GRMaster::where('plant_id', $plantId)
->where('gr_number', $data['gr_number'])
->where('item_id', $itemId)
->whereIn('serial_number', $serialNumbers)
->pluck('serial_number')
->toArray();
$missingSerials = array_diff($serialNumbers, $foundSerials);
if (count($missingSerials) > 0) {
$missingSerialsByItem[$itemCode] = array_values($missingSerials);
}
}
if (count($missingSerialsByItem) > 0) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => 'Some serial numbers not found in DB for given plant, GR number, and item!',
'missing_serials' => $missingSerialsByItem,
], 404);
}
$alreadyCompleted = [];
foreach ($data['item_codes'] as $item) {
$itemCode = $item['item_code'];
$serialNumbers = $item['serial_numbers'];
$itemId = Item::where('code', $itemCode)->value('id');
foreach ($serialNumbers as $serial) {
$gr = GRMaster::where('plant_id', $plantId)
->where('item_id', $itemId)
->where('gr_number', $data['gr_number'])
->where('serial_number', $serial)
->first();
if (! $gr) {
continue;
}
if ($gr->status == 'Completed') {
$alreadyCompleted[] = $serial;
}
}
}
if (! empty($alreadyCompleted)) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => 'Below serial numbers are already completed',
'serial_numbers' => $alreadyCompleted,
], 404);
}
// {
// $itemCode = $item['item_code'];
// $serialNumbers = $item['serial_numbers'];
// $itemObj = Item::where('code', $itemCode)->first();
// if (!$itemObj) {
// return response()->json([
// 'status_code' => 'ERROR',
// 'status_description' => "Item code: $itemCode not found"
// ], 404);
// }
// $itemPlant = Item::where('plant_id', $plantId)
// ->where('code', $itemCode)->first();
// if (!$itemPlant) {
// return response()->json([
// 'status_code' => 'ERROR',
// 'status_description' => "Item code: $itemCode not found for the plant: $data[plant_code]"
// ], 404);
// }
// $itemId = $itemObj->id;
// // Update all serial numbers for this item
// GRMaster::where('plant_id', $plantId)
// ->where('item_id', $itemId)
// ->where('gr_number', $data['gr_number'])
// ->whereIn('serial_number', $serialNumbers)
// ->update(['created_by' => $scannedBy]);
// }
foreach ($data['item_codes'] as $item) {
$itemCode = $item['item_code'];
$serialNumbers = $item['serial_numbers'];
$itemId = Item::where('code', $itemCode)->value('id');
GRMaster::where('plant_id', $plantId)
->where('item_id', $itemId)
->where('gr_number', $data['gr_number'])
->whereIn('serial_number', $serialNumbers)
->update(['created_by' => $scannedBy, 'status' => 'Completed']);
}
return response()->json([
'status_code' => 'SUCCESS',
'status_description' => 'Serial numbers updated successfully!',
], 200);
}
/**
* 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!',
], 404);
}
$filename = $request->header('process-order');
if (! $filename) {
return response()->json(['error' => 'Missing file-name header'], 404);
}
$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.'"',
]);
}
public function getGRPdf(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!',
], 404);
}
$filename = $request->header('gr-number');
if (! $filename) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => 'Gr Number cannot be empty!',
], 404);
// return response()->json(['error' => 'Missing file-name header'], 404);
}
$filename = basename($filename);
// Ensure the file has .pdf extension
if (! str_ends_with(strtolower($filename), '.pdf')) {
$filename .= '.pdf';
}
$filePath = 'uploads/GRNumber/'.$filename;
if (! Storage::disk('local')->exists($filePath)) {
// return response()->json(['error' => 'File not found'], 404);
return response()->json([
'status_code' => 'ERROR',
'status_description' => 'Pdf File not found for the provided GrNumber!',
], 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.'"',
]);
}
public function getGRSerial(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!',
], 404);
}
$plantCode = $request->header('plant-code');
$grNumber = $request->header('gr-number');
if (! $plantCode) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Plant Code value can't be empty",
], 404);
} elseif (! $grNumber) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => 'GR Number cannot be empty!',
], 404);
}
$plant = Plant::where('code', $plantCode)->first();
$plantId = $plant->id;
if (! $plant) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Plant Code '{$plantCode}' not found!",
], 404);
}
$grExist = GRMaster::where('gr_number', $grNumber)->first();
if (! $grExist) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => 'GR Number not found',
], 404);
}
$grExists = GRMaster::where('plant_id', $plantId)
->where('gr_number', $grNumber)
->first();
if (! $grExists) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => 'GR Number not found for this plant!',
], 404);
}
$grRecords = GrMaster::where('plant_id', $plantId)
->where('gr_number', $grNumber)
->get(['serial_number', 'item_id']);
if (empty($grRecords)) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => 'No serial numbers found for the given GR number!',
], 404);
}
// return response()->json([
// 'serial_numbers' => $serialNumbers
// ], 200);
// $itemId = $grRecords->first()->item_id;
// $itemCode = $itemId ? optional(Item::find($itemId))->code : null;
// $serialNumbers = $grRecords->pluck('serial_number')->toArray();
// return response()->json([
// 'item_code' => $itemCode,
// 'serial_numbers' => $serialNumbers
// ], 200);
$itemIds = $grRecords->pluck('item_id')->unique()->filter();
$items = Item::whereIn('id', $itemIds)->pluck('code', 'id');
$result = $grRecords->groupBy('item_id')->map(function ($group, $itemId) use ($items) {
return [
'item_code' => $items[$itemId] ?? null,
'serial_numbers' => $group->pluck('serial_number')->toArray(),
];
})->values(); // remove keys
return response()->json($result, 200);
}
public function getProcessOrderData(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!',
], 404);
}
$plantCode = $request->header('plant-code');
$processOrder = $request->header('process-order');
if (! $plantCode) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Plant Code value can't be empty",
], 404);
} elseif (! $processOrder) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => 'Process Order cannot be empty!',
], 404);
}
$plant = Plant::where('code', $plantCode)->first();
$plantId = $plant->id;
if (! $plant) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Plant Code '{$plantCode}' not found!",
], 404);
}
$processOrderExist = ProcessOrder::where('process_order', $processOrder)->first();
if (! $processOrderExist) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => 'Process order not found',
], 404);
}
$proOrdAgPlant = ProcessOrder::where('plant_id', $plantId)
->where('process_order', $processOrder)
->first();
if (! $proOrdAgPlant) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => 'Process order not found for this plant!',
], 404);
}
$item = $proOrdAgPlant->item;
$processOrderRecords = ProcessOrder::with('item')
->where('plant_id', $plant->id)
->where('process_order', $processOrder)
->get();
$lastRecord = ProcessOrder::with('item')
->where('plant_id', $plant->id)
->where('process_order', $processOrder)
->orderBy('id', 'desc')
->first();
$totalReceivedQty = $processOrderRecords->sum('received_quantity');
// $lastRecord = $processOrderRecords->first();
$item = $lastRecord->item;
if ($totalReceivedQty == $proOrdAgPlant->order_quantity) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Process order '{$processOrder}' for plant '{$plantCode}' has already reached its order quantity.",
], 404);
}
// if ($totalReceivedQty > $proOrdAgPlant->order_quantity) {
// return response()->json([
// 'status_code' => 'ERROR',
// 'status_description' => "Process order '{$processOrder}' for plant '{$plantCode}' received quantity is more than its order quantity."
// ], 404);
// }
return response()->json([
'item_code' => $item?->code ?? '',
'description' => $item?->description ?? '',
// 'coil_number' => $proOrdAgPlant->coil_number ?? "",
// 'order_quantity' => (string)$proOrdAgPlant->order_quantity ?? "",
'coil_number' => $lastRecord->coil_number ?? '',
'order_quantity' => (string) $lastRecord->order_quantity ?? '',
'received_quantity' => (string) $totalReceivedQty ?? '',
]);
}
public function storeProcessOrderData(Request $request)
{
$expectedUser = env('API_AUTH_USER');
$expectedPw = env('API_AUTH_PW');
$headerAuth = $request->header('Authorization');
$expectedToken = 'Bearer '.$expectedUser.':'.$expectedPw;
if ($headerAuth !== $expectedToken) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => 'Invalid authorization token!',
], 404);
}
$plantCode = $request->header('plant-code');
$processOrder = $request->header('process-order');
$data = $request->all();
Log::info('Process Order POST API >>', ['plant-code' => $plantCode, 'process-order' => $processOrder, 'post-data' => $data]);
if ($plantCode == null || $plantCode == '' || ! $plantCode) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Plant code can't be empty!",
], 404);
} elseif (! is_numeric($plantCode) || Str::length($plantCode) < 4 || ! preg_match('/^[1-9]\d{3,}$/', $plantCode)) { // !ctype_digit($data['plant_code'])
return response()->json([
'status_code' => 'ERROR',
'status_description' => 'Invalid plant code found!',
], 404);
}
if (! $processOrder) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => 'Process-order are required!',
], 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;
$itemCode = $data['item_code'] ?? '';
$coilNo = $data['coil_number'] ?? '';
$orderQty = $data['order_quantity'] ?? 0;
$receivedQty = $data['received_quantity'] ?? 0;
$sfgNo = $data['sfg_number'] ?? '';
$machineId = $data['machine_id'] ?? '';
$createdBy = $data['created_by'] ?? '';
// $validated = $request->validate([
// 'item_code' => 'nullable|integer',
// 'coil_number' => 'nullable|string',
// 'order_quantity' => 'nullable|integer',
// 'received_quantity' => 'nullable|numeric',
// 'sfg_number' => 'nullable|string',
// 'machine_id' => 'nullable|string',
// 'created_by' => 'nullable|string',
// ]);
if ($itemCode == null || $itemCode == '' || ! $itemCode) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Item code can't be empty!",
], 404);
} elseif (Str::length($itemCode) < 6) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => 'Item code should contain minimum 6 digits!',
], 404);
} elseif (! ctype_alnum($itemCode)) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => 'Item code should contain only alpha-numeric values!',
], 404);
}
if ($coilNo == null || $coilNo == '') {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Coil number can't be empty!",
], 404);
} elseif (! is_numeric($coilNo) || Str::length($coilNo) <= 0 || ! preg_match('/^\d{1,}$/', $coilNo)) { // !ctype_digit($data['plant_code'])
return response()->json([
'status_code' => 'ERROR',
'status_description' => 'Invalid coil number found!',
], 404);
}
// if ($sfgNo == null || $sfgNo == '' || ! $sfgNo) {
// return response()->json([
// 'status_code' => 'ERROR',
// 'status_description' => "SFG number can't be empty!",
// ], 404);
// }
// if ($machineId == null || $machineId == '' || ! $machineId) {
// return response()->json([
// 'status_code' => 'ERROR',
// 'status_description' => "Machine ID can't be empty!",
// ], 404);
// }
if ($createdBy == null || $createdBy == '' || ! $createdBy) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "User name can't be empty!",
], 404);
} elseif ($createdBy == 'jothi') {
$createdBy = 'Admin';
}
$user = User::where('name', $createdBy)->first();
$userPlant = User::where('name', $createdBy)->where('plant_id', $plantId)->first();
if (! $user) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "User name '{$createdBy}' not found!",
], 404);
} elseif (! $userPlant && ! $user->hasRole('Super Admin')) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "User name '{$createdBy}' not found for the plant code '{$plantCode}'!",
], 404);
} elseif (! $user->hasRole('Super Admin') && ! $user->hasRole('Process Employee') && ! $user->hasRole('Process Supervisor')) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => 'User does not have rights!',
], 404);
}
$item = Item::where('code', $itemCode)->first();
if (! $item) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Item code '{$itemCode}' not found!",
], 404);
}
$itemPlant = Item::where('code', $itemCode)
->where('plant_id', $plantId)
->first();
if (! $itemPlant) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Item code '{$itemCode}' not found for the plant code '{$plantCode}'!",
], 404);
}
$itemId = $itemPlant->id;
if ($sfgNo != null && $sfgNo != '' && Str::length($sfgNo) > 0 && $sfgNo) {
$existing = ProcessOrder::where('plant_id', $plantId)
->where('sfg_number', $sfgNo)
->first();
if ($existing) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "SFG number '{$sfgNo}' already exist for the plant code '{$plantCode}'!",
], 404);
}
} else {
$sfgNo = null;
}
$existing = ProcessOrder::where('plant_id', $plantId)
->where('process_order', $processOrder)
->where('item_id', '!=', $itemId)
->first();
if ($existing) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Process order '{$processOrder}' already has item_code '{$existing->item->code}' for the plant code '{$plantCode}'!",
], 404);
}
$existing = ProcessOrder::where('plant_id', $plantId)
->where('process_order', $processOrder)
->where('coil_number', $coilNo)
->first();
if ($existing) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Process order '{$processOrder}' with coil number '{$coilNo}' already exist for the plant code '{$plantCode}'!",
], 404);
}
$alreadyReceived = ProcessOrder::where('plant_id', $plantId)
->where('process_order', $processOrder)
->where('item_id', $itemId)
->sum('received_quantity');
if ($orderQty == 0) {
$orderQty = ProcessOrder::where('plant_id', $plantId)
->where('process_order', $processOrder)
->where('item_id', $itemId)
->value('order_quantity') ?? 0;
}
$total = $alreadyReceived + $receivedQty;
if ($total > $orderQty) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Received quantity should not exceed order quantity! Order Qty = {$orderQty}, Already Received Qty = {$alreadyReceived}, Trying to Insert Qty = {$receivedQty}",
], 404);
}
try {
ProcessOrder::Create(
[
'plant_id' => $plantId,
'process_order' => $processOrder,
'item_id' => $itemId,
'coil_number' => $coilNo,
'order_quantity' => $orderQty,
'received_quantity' => $receivedQty,
'sfg_number' => $sfgNo,
'machine_name' => $machineId,
'created_by' => $createdBy,
]
);
return response()->json([
'status_code' => 'SUCCESS',
'status_description' => 'Record Inserted Successfully',
]);
} catch (\Exception $e) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => $e->getMessage(),
], 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

@@ -0,0 +1,74 @@
<?php
namespace App\Http\Controllers;
use App\Models\Plant;
use Illuminate\Http\Request;
class PlantController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index()
{
//
}
/**
* Store a newly created resource in storage.
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*/
public function get_all_data(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);
}
$plants = Plant::with('company')->orderBy('code')->get();
$plantsData = $plants->map(function($plant) {
return [
'company' => $plant->company ? $plant->company->name : "", // Get company name
'plant_code' => (String)$plant->code,
'plant_name' => $plant->name,
'plant_address' => $plant->address,
];
});
return response()->json([
'plants' => $plantsData
]);
}
/**
* 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

@@ -0,0 +1,277 @@
<?php
namespace App\Http\Controllers;
use App\Models\Item;
use App\Models\ProductionQuantity;
use App\Models\StickerMaster;
use Illuminate\Http\Request;
use Mpdf\Mpdf;
use Mpdf\QrCode\Output;
use Mpdf\QrCode\QrCode;
class ProductionStickerReprintController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index()
{
//
}
// public function downloadQrPdf($palletNo)
// {
// $parts = explode('|', $palletNo);
// $itemCode = trim($parts[0]);
// $serial = isset($parts[1]) ? trim($parts[1]) : null;
// // Retrieve the item record by item code
// $item = Item::where('code', $itemCode)->first();
// if (!$item) {
// abort(404, "Item with code {$itemCode} not found.");
// }
// $itemId = $item->id;
// $production = ProductionQuantity::where('item_id', $itemId)
// ->where('serial_number', $serial)
// ->first();
// if (!$production) {
// abort(404, "Production data for item code '{$itemCode}' with serial '{$serial}' not found.");
// }
// $productionOrder = $production->production_order;
// $qrCode = new QrCode($palletNo);
// $output = new Output\Png();
// $qrBinary = $output->output($qrCode, 100);
// $qrBase64 = base64_encode($qrBinary);
// $sticker = StickerMaster::where('item_id', $itemId)->first();
// // Decide number of copies
// $copies = 1;
// if ($sticker) {
// if ($sticker->serial_number_pump == 1) {
// // If pump is selected (regardless of motor), 2 copies
// $copies = 2;
// } elseif ($sticker->serial_number_motor == 1) {
// // Only motor selected, 1 copy
// $copies = 1;
// }
// }
// return '
// <html>
// <head>
// <style>
// body {
// margin: 0;
// padding: 0;
// width: 100mm;
// height: 14mm;
// font-size: 10pt;
// font-family: Arial Narrow, Arial, sans-serif;
// }
// .sticker-table {
// width: 100mm;
// height: 14mm;
// }
// .text-cell {
// margin: 0;
// padding: 0;
// text-align: left;
// font-size: 14pt;
// font-weight: normal;
// line-height: 1.2;
// }
// .text-row {
// font-weight: bold;
// font-size: 9pt;
// }
// .serial {
// text-align: left;
// }
// .po-number {
// text-align: right;
// white-space: nowrap;
// }
// .desc-row {
// font-weight: normal;
// font-size: 8pt;
// }
// .qr-cell {
// width: 14mm;
// text-align: left;
// padding-left: 0mm;
// padding-top: 0mm;
// }
// img.qr {
// width: 20mm;
// height: 20mm;
// }
// </style>
// </head>
// <body>
// <div id="print-container"></div>
// <script>
// const copies = ' . $copies . ';
// const 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">
// <div class="text-row">
// <pre><span class="serial">' . htmlspecialchars($serial) . '</span> <span class="po-number">' . htmlspecialchars($productionOrder) . '</span></pre>
// </div>
// <div class="desc-row">
// ' . htmlspecialchars($item->description) . '
// </div>
// </td>
// </tr>
// </table>
// `;
// const container = document.getElementById("print-container");
// for (let i = 0; i < copies; i++) {
// container.insertAdjacentHTML("beforeend", htmlBlock);
// }
// window.onload = function () {
// window.print();
// setTimeout(function () {
// window.close();
// }, 500);
// };
// </script>
// </body>
// </html>
// ';
// //Get sticker master data
// // $sticker = StickerMaster::where('item_id', $itemId)->first();
// // //Decide number of copies
// // $copies = 1; // default
// // if ($sticker) {
// // if ($sticker->serial_number_motor == 1) {
// // $copies = 1;
// // } elseif (is_null($sticker->serial_number_motor) && $sticker->serial_number_pump == 1) {
// // $copies = 2;
// // }
// // }
// // $mpdf = new Mpdf([
// // 'mode' => 'utf-8',
// // 'format' => [60, 14],
// // 'margin_left' => 0,
// // 'margin_right' => 0,
// // 'margin_top' => 0,
// // 'margin_bottom' => 0,
// // ]);
// // for ($i = 0; $i < $copies; $i++) {
// // $mpdf->WriteHTML($html);
// // if ($i < $copies - 1) {
// // $mpdf->AddPage();
// // }
// // }
// // $mpdf->Output('qr-label.pdf', 'I');
// // exit;
// }
/**
* Store a newly created resource in storage.
*/
public function downloadQrPdf($palletNo)
{
$parts = explode('|', $palletNo);
$itemCode = trim($parts[0]);
$serial = isset($parts[1]) ? trim($parts[1]) : null;
$item = Item::where('code', $itemCode)->first();
$itemId= $item->id;
if (!$item) {
abort(404, "Item with code {$itemCode} not found.");
}
$production = ProductionQuantity::where('item_id', $item->id)
->where('serial_number', $serial)
->first();
if (!$production) {
abort(404, "Production data for item code '{$itemCode}' with serial '{$serial}' not found.");
}
$productionOrder = $production->production_order ?? '';
if ($item->category == 'Submersible Motor')
{
$copies = 1;
}
elseif ($item->category == 'Submersible Pump')
{
$copies = 2;
}
// 5. Generate QR Code (base64)
$qrCode = new QrCode($palletNo);
$output = new Output\Png();
$qrBinary = $output->output($qrCode, 100); // 100 = size
$qrBase64 = base64_encode($qrBinary);
// 6. Return view
return view('print-qr', [
'qrBase64' => $qrBase64,
'serial' => $serial,
'productionOrder' => $productionOrder,
'item' => $item,
'copies'=> $copies,
]);
}
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

@@ -0,0 +1,270 @@
<?php
namespace App\Http\Controllers;
use App\Models\DriverMaster;
use App\Models\VehicleMaster;
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)
{
$request->validate([
'name' => 'required|string',
'identification1' => 'nullable|string',
'identification2' => 'nullable|string',
'identification3' => 'nullable|string',
'contact_number' => 'nullable|string',
'alternate_number' => 'nullable|string',
]);
DriverMaster::create($request->all());
return response()->json(['success' => true]);
}
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);
}
// 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' => '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

@@ -0,0 +1,275 @@
<?php
namespace App\Http\Controllers;
use App\Models\Item;
use App\Models\MotorTestingMaster;
use App\Models\Plant;
use App\Models\StickerMaster;
use Illuminate\Http\Request;
use Str;
class StickerMasterController 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 get_master_type(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');
$itemCode = $request->header('item-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);
}
else if ($itemCode == null || $itemCode == '')
{
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Item Code can't be empty!"
], 400);
}
else if (Str::length($itemCode) < 6 || !ctype_alnum($itemCode))
{
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Invalid item code found!"
], 400);
}
$plant = Plant::where('code', $plantCode)->first();
if (!$plant) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Plant not found!"
], 400);
}
$plantId = $plant->id;
$item = Item::where('code', $itemCode)->first();
if (!$item)
{
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Item Code not found in item table!"
], 404);
}
$item = Item::where('plant_id', $plantId)->where('code', $itemCode)->first();
if (!$item)
{
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Item Code not found in item table for the plant : '$plant->name'!"
], 404);
}
$stickerMaster = StickerMaster::where('plant_id', $plantId)->where('item_id', $item->id)->first();
if (!$stickerMaster)
{
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Item Code not found in sticker master table for the plant : '$plant->name'!"
], 404);
}
$serial_number_motor = $stickerMaster->serial_number_motor ?? null;
$serial_number_pump = $stickerMaster->serial_number_pump ?? null;
if ($serial_number_motor != 1 && $serial_number_pump != 1) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "The Item Code '$itemCode' does not have serial pump or serial motor selected!"
], 400);
}
$serialInfo = [];
if ($serial_number_motor == 1 && $serial_number_pump == 1)
{
$serialInfo[] = 'Serial Pump';
}
else
{
if ($serial_number_motor == 1) {
$serialInfo[] = 'Serial Motor';
}
if ($serial_number_pump == 1) {
$serialInfo[] = 'Serial Pump';
}
}
$output = [
'status_code' => 'SUCCESS',
'status_description' => implode(', ', $serialInfo),
];
return response()->json($output, 200);
}
/**
* Display the specified resource.
*/
public function get_master(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');
$itemCode = $request->header('item-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);
}
else if ($itemCode == null || $itemCode == '')
{
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Item Code can't be empty!"
], 400);
}
else if (Str::length($itemCode) < 6 || !ctype_alnum($itemCode))
{
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Invalid item code found!"
], 400);
}
$plant = Plant::where('code', $plantCode)->first();
if (!$plant) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Plant not found!"
], 400);
}
$plantId = $plant->id;
$item = Item::where('code', $itemCode)->first();
if (!$item)
{
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Item Code not found in item table!"
], 404);
}
$item = Item::where('plant_id', $plantId)->where('code', $itemCode)->first();
if (!$item)
{
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Item Code not found in item table for the plant : '$plant->name'!"
], 404);
}
$description = $item ? $item->description : '';
$uom = $item ? $item->uom : '';
$category = $item ? $item->category : '';
$stickerMaster = StickerMaster::where('plant_id', $plantId)->where('item_id', $item->id)->first();
if (!$stickerMaster)
{
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Item Code not found in sticker master table for the plant : '$plant->name'!"
], 404);
}
$output = [
"item_description" => $description ?? "",
"uom" => $uom ?? "",
"Part_Validation_1" => $stickerMaster?->laser_part_validation1 ?? "",
"Part_Validation_2" => $stickerMaster?->laser_part_validation2 ?? "",
"Part_Validation_3" => $stickerMaster?->laser_part_validation3 ?? "",
"Part_Validation_4" => $stickerMaster?->laser_part_validation4 ?? "",
"Part_Validation_5" => $stickerMaster?->laser_part_validation5 ?? "",
];
return response()->json($output, 200);
}
/**
* 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

@@ -0,0 +1,136 @@
<?php
namespace App\Http\Controllers;
use App\Models\AlertMailRule;
use App\Models\Line;
use App\Models\ProductionQuantity;
use Illuminate\Http\Request;
use Telegram\Bot\Laravel\Facades\Telegram;
use Telegram\Bot\Api;
use Illuminate\Support\Facades\Http;
use Illuminate\Console\Scheduling\Schedule;
use Carbon\Carbon;
use Illuminate\Console\View\Components\Alert;
class TelegramController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index()
{
//
}
public function sendMessage(Request $request)
{
$webhookUrl = env('TEAM_URL');
$start = Carbon::yesterday()->setHour(8)->setMinute(0)->setSecond(0);
$end = Carbon::today()->setHour(7)->setMinute(59)->setSecond(59);
$ruleExists = AlertMailRule::where('module', 'ProductionQuantities')
->where('rule_name', 'ProductionMail')
->where('schedule_type', 'Daily')
->first();
if (!$ruleExists) {
return response()->json([
'status' => 'Skipped',
'message' => 'No matching alert rule found for ProductionQuantities → ProductionMail → Daily.'
]);
}
$plantName = 1;
$lines = Line::where('plant_id', $plantName)->get();
$tableData = [];
foreach ($lines as $line) {
$count = ProductionQuantity::where('line_id', $line->id)
->whereBetween('created_at', [$start, $end])
->count();
$tableData[] = [
'line_name' => $line->name ?? '',
'production_count' => $count ?? ''
];
}
$table = "| Line Name | Total Production Count |\n";
$table .= "|------------|------------------------|\n";
// foreach ($lines as $line) {
// $count = ProductionQuantity::where('line', $line)
// ->whereBetween('created_at', [$start, $end])
// ->count();
// $table .= "| {$line} | {$count} |\n";
// }
// $messageText = "Daily Production Report \n"
// . "From: {$start->format('Y-m-d H:i:s')} To {$end->format('Y-m-d H:i:s')} \n"
// . "Total Production Count: {$rowCount}";
$messageText = "**Daily Production Report - {$plantName}** \n"
. "From: {$start->format('Y-m-d H:i:s')} \n"
. "To: {$end->format('Y-m-d H:i:s')} \n\n"
. $table;
$message = [
"text" => $messageText
];
$response = Http::post($webhookUrl, $message);
// if ($response->successful()) {
// return response()->json(['status' => 'Message sent to Teams!']);
// }
return response()->json([
'status' => $response->successful() ? 'Message sent to Teams!' : 'Failed to send message to Teams',
'plant' => $plantName,
'start_time' => $start->format('Y-m-d H:i:s'),
'end_time' => $end->format('Y-m-d H:i:s'),
'lines' => $tableData,
'teams_message_preview' => $messageText,
]);
//return response()->json(['error' => 'Failed to send message'], 500);
}
/**
* 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

@@ -0,0 +1,534 @@
<?php
namespace App\Http\Controllers;
use App\Models\Item;
use App\Models\Line;
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;
use Mpdf\Mpdf;
use chillerlan\QRCode\QROptions;
use chillerlan\QRCode\Output\QROutputInterface;
use Mpdf\QrCode\Output;
use Mpdf\QrCode\QrCode;
use Str;
class TestingPanelController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index()
{
//
}
/**
* Store a newly created resource in storage.
*/
public function store(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);
}
$data = $request->all();
if ($data['plant_code'] == null || $data['plant_code'] == '')
{
// return response("ERROR: Please provide a valid plant code.", 400)
// ->header('Content-Type', 'text/plain');
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Plant code can't be empty!"
], 400);
}
else if (Str::length($data['plant_code']) < 4 || !is_numeric($data['plant_code']) || !preg_match('/^[1-9]\d{3,}$/', $data['plant_code']))//!ctype_digit($data['plant_code'])
{
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Invalid plant code found!"
], 400);
}
$plant = Plant::where('code', $data['plant_code'])->first();
if (!$plant) {
//return response("Plant not found.", 400)->header('Content-Type', 'text/plain');
return response()->json([
'status_code' => 'ERROR',
'status_description' => 'Plant not found!'
], 400);
}
$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)
{
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)
{
//return response( "Line not found for the specified plant : {$data['plant_code']}",400)->header('Content-Type', 'text/plain');
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Group work center not found for the specified plant : '{$data['plant_code']}'!"
], 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);
}
$machine = Machine::where('work_center', $data['machine_name'])->first();
if (!$machine)
{
return response()->json([
'status_code' => 'ERROR',
'status_description' => 'Work center not found!'
], 400);
}
$machine = Machine::where('work_center', $data['machine_name'])->where('plant_id', $plantId)->first();
if (!$machine)
{
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();
if (!$machine)
{
// return response("Machine not found for the specified line : {$data['line_name']}", 400)->header('Content-Type', 'text/plain');
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Work center not found for the specified Group work center : '{$data['line_name']}'!"
], 400);
}
$machine = Machine::where('work_center', $data['machine_name'])->where('plant_id', $plantId)->where('work_group_master_id', $gWorkCenterId)->first();
if (!$machine) {
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']}'!"
], 400);
}
$lineId = $machine->line_id;
$machineId = $machine->id;
try
{
$insertedSerials = [];
$missedItemCodes = [];
$duplicateItemCodes = [];
$existSnoCount = [];
if (!empty($data['item_codes']) && is_array($data['item_codes']))
{
foreach ($data['item_codes'] as $item)
{
$code = $item['item_code'] ?? null;
// Check if item_code is present
if ($code == '' || $code == null)
{
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Item code can't be empty!"
], 400);
}
// Collect duplicates
if (isset($itemCodeCounts[$code]))
{
$itemCodeCounts[$code]++;
// Only add to duplicates array once
if ($itemCodeCounts[$code] == 2) {
$duplicateItemCodes[] = $code;
}
}
else
{
$itemCodeCounts[$code] = 1;
}
$motorTestingMaster = MotorTestingMaster::whereHas('item', function ($query) use ($item) {
$query->where('code', $item['item_code']);
})->where('plant_id', $plantId)->first();
if (!$motorTestingMaster) {
$missedItemCodes[] = $item['item_code'];
}
if (!empty($item['serial_numbers']) && is_array($item['serial_numbers'])) {
foreach ($item['serial_numbers'] as $serial)
{
$existSnoCount[] = $serial['serial_number'];
}
}
}
// If any duplicates found, return error
if (!empty($duplicateItemCodes)) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => 'Duplicate item codes found in request: ' . implode(', ', $duplicateItemCodes)
], 400);
}
$uniqueInvalidCodes = array_unique($missedItemCodes);
if (!empty($uniqueInvalidCodes)) {
// return response("Item codes : ". implode(', ', $uniqueInvalidCodes)." not found in motor testing master for the specified plant {$plant->name}", 400)
// ->header('Content-Type', 'text/plain');
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Item codes : ". implode(', ', $uniqueInvalidCodes)." not found in master for the specified plant : '{$plant->name}'!"
], 400);
}
$insertedSnoCount = [];
foreach ($data['item_codes'] as $item)
{
$motorTestingMaster = MotorTestingMaster::whereHas('item', callback: function ($query) use ($item) {
$query->where('code', $item['item_code']);
})->where('plant_id', $plantId)->first();
$motorTestingMasterId = $motorTestingMaster->id;
if (!empty($item['serial_numbers']) && is_array($item['serial_numbers']))
{
foreach ($item['serial_numbers'] as $serial)
{
//For update_count calculation
$updateCount = [
'plant_id' => $plantId,
'line_id' => $lineId,
'machine_id' => $machineId,
'motor_testing_master_id' => $motorTestingMasterId,
'serial_number' => $serial['serial_number'] ?? null,
'rework_count' => $serial['rework_count'] ?? 0,
];
// // Find the current max update_count for this composite key //updated_at
// // $maxUpdateCount = \App\Models\TestingPanelReading::where($updateCount)->max('update_count');
// $maxUpdateCount = TestingPanelReading::where($updateCount)->orderByDesc('update_count')->select('update_count')->first();
// // ->select(TestingPanelReading::raw('MAX(CAST(update_count AS INTEGER)) AS max_update_count'))->value('max_update_count');
// // ->value('update_count')
// First, get the maximum length
$maxLength = TestingPanelReading::where($updateCount)->selectRaw('MAX(LENGTH(update_count)) as max_length')->value('max_length');
// Then, get all records with that length
$lastUpdateCount = TestingPanelReading::where($updateCount)->whereRaw('LENGTH(update_count) = ?', [$maxLength])->orderByDesc('update_count')->select('update_count')->first();//->get();
$newUpdateCount = ($lastUpdateCount == null || $lastUpdateCount == '') ? 0 : (int)$lastUpdateCount?->update_count + 1;//$maxUpdateCount?->update_count
$updateCountString = (string)$newUpdateCount;
$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,
'before_fr_pow' => $serial['before_fr_pow'] ?? null,
'before_fr_res_ry' => $serial['before_fr_res_ry'] ?? null,
'before_fr_res_yb' => $serial['before_fr_res_yb'] ?? null,
'before_fr_res_br' => $serial['before_fr_res_br'] ?? null,
'before_fr_ir' => $serial['before_fr_ir'] ?? null,
'before_fr_ir_r' => $serial['before_fr_ir_r'] ?? null,
'before_fr_ir_y' => $serial['before_fr_ir_y'] ?? null,
'before_fr_ir_b' => $serial['before_fr_ir_b'] ?? null,
'before_fr_freq' => $serial['before_fr_freq'] ?? null,
'before_fr_speed' => $serial['before_fr_speed'] ?? null,
'after_fr_vol' => $serial['after_fr_vol'] ?? null,
'after_fr_cur' => $serial['after_fr_cur'] ?? null,
'after_fr_pow' => $serial['after_fr_pow'] ?? null,
'after_fr_ir_hot' => $serial['after_fr_ir_hot'] ?? null,
'after_fr_ir_hot_r' => $serial['after_fr_ir_hot_r'] ?? null,
'after_fr_ir_hot_y' => $serial['after_fr_ir_hot_y'] ?? null,
'after_fr_ir_hot_b' => $serial['after_fr_ir_hot_b'] ?? null,
'after_fr_ir_cool' => $serial['after_fr_ir_cool'] ?? null,
'after_fr_ir_cool_r' => $serial['after_fr_ir_cool_r'] ?? null,
'after_fr_ir_cool_y' => $serial['after_fr_ir_cool_y'] ?? null,
'after_fr_ir_cool_b' => $serial['after_fr_ir_cool_b'] ?? null,
'after_fr_freq' => $serial['after_fr_freq'] ?? null,
'after_fr_speed' => $serial['after_fr_speed'] ?? null,
'after_fr_leak_cur' => $serial['after_fr_leak_cur'] ?? null,
'locked_rt_volt' => $serial['locked_rt_volt'] ?? null,
'locked_rt_cur' => $serial['locked_rt_cur'] ?? null,
'locked_rt_pow' => $serial['locked_rt_pow'] ?? null,
'no_load_pickup_volt' => $serial['no_load_pickup_volt'] ?? null,
'room_temperature' => $serial['room_temperature'] ?? null,
'hv_test' => $serial['hv_test'] ?? null,
'batch_number' => $serial['batch_number'] ?? null,
'batch_count' => $serial['batch_count'] ?? 0,
'result' => $serial['result'] ?? null,
'remark' => $serial['remark'] ?? null,
'rework_count' => $serial['rework_count'] ?? 0,
'output_flag' => $serial['output_flag'] ?? 0,
'tested_by' => $serial['tested_by'] ?? null,
'updated_by' => $serial['updated_by'] ?? null,
'created_at' => $serial['created_at'] ?? null,
'updated_at' => $serial['updated_at'] ?? $serial['created_at'],
'scanned_at' => $serial['scanned_at'] ?? null,
'update_count' => $updateCountString,
];
// Insert the new record
TestingPanelReading::create($row);
$insertedSerials[] = $serial['serial_number'] ?? '[unknown]';
$insertedSnoCount[] = $serial['serial_number'];
}
}
}
}
if (!empty($insertedSerials))
{
if(count($existSnoCount) == count($insertedSnoCount))
{
// $messages[] = "Inserted serial numbers are: " . implode(', ', $insertedSerials);
return response()->json([
'status_code' => 'SUCCESS',
'status_description' => 'Inserted serial numbers are: ' . implode(', ', $insertedSerials)
], 200);
}
else
{
$missingSno = array_diff($existSnoCount,$insertedSnoCount);
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Missed serial numbers are: " . implode(', ', $missingSno)
], 400);
}
}
}
catch (\Exception $e)
{
// return response($e->getMessage(), 500)->header('Content-Type', 'text/plain');
return response()->json([
'status_code' => 'ERROR',
'status_description' => 'Store testing panel readings internal server error : '.$e?->getCode()
], 500);
}
}
/**
* Display the specified resource.
*/
public function get_motor_master(Request $request)
{
$expectedUser = env('API_AUTH_USER');
$expectedPw = env('API_AUTH_PW');
$header_auth = $request->header('Authorization');
$expectedToken = $expectedUser . ':' . $expectedPw;
//$data = $request->all();
if ("Bearer " . $expectedToken != $header_auth)
{
return response()->json([
'status_code' => 'ERROR',
'status_description' => 'Invalid authorization token!'
], 403);
}
$plantCode = $request->header('plant-code');
$itemCode = $request->header('item-code');
// $description = $item ? $item->description : '';
if ($plantCode == null || $plantCode == '')
{
// return response("ERROR: Plant Name can't be empty", 400)
// ->header('Content-Type', 'text/plain');
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);
}
else if($itemCode == null || $itemCode == '')
{
// return response("ERROR: OBD Number can't be empty", 400)
// ->header('Content-Type', 'text/plain');
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Item Code can't be empty!"
], 400);
}
else if(Str::length($itemCode) < 6 || !ctype_alnum($itemCode))
{
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Invalid item code found!"
], 400);
}
$plant = Plant::where('code', $plantCode)->first();
if (!$plant) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Plant not found!"
], 400);
}
$plantId = $plant->id;
$item = Item::where('code', $itemCode)->first();
if (!$item)
{
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Item Code not found in item table!"
], 404);
}
$item = Item::where('plant_id', $plantId)->where('code', $itemCode)->first();
if (!$item)
{
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Item Code not found in item table for the plant : '$plant->name'!"
], 404);
}
// Get description or empty string if not found
$description = $item ? $item->description : '';
$category = $item ? $item->category : '';
$motorTestingMaster = MotorTestingMaster::where('plant_id', $plantId)->where('item_id', $item->id)->first();
if (!$motorTestingMaster)
{
return response()->json([
'status_code' => 'ERROR',
'status_description' => "Item Code not found in motor testing master table for the plant : '$plant->name'!"
], 404);
}
$output = [
"mot_subassembly_code" => $motorTestingMaster->subassembly_code ?? "",
"mot_model_name" => $description,
"mot_non_isi_model" => $motorTestingMaster->isi_model ? "0" :"1",
"mot_phase" => $motorTestingMaster->phase ?? "",
"mot_hp" => $motorTestingMaster->hp ?? "",
"mot_kw" => $motorTestingMaster->kw ?? "",
"mot_volt" => $motorTestingMaster->volt ?? "",
"mot_cur" => $motorTestingMaster->current ?? "",
"mot_rpm" => $motorTestingMaster->rpm ?? "",
"mot_rate_torque_kg" => $motorTestingMaster->torque ?? "",
"mot_freq" => $motorTestingMaster->frequency ?? "",
"mot_conn" => $motorTestingMaster->connection ?? "",
"mot_ins_res_limit" => $motorTestingMaster->ins_res_limit ?? "",
"mot_ins_res_type" => $motorTestingMaster->ins_res_type ?? "",
"mot_category" => $category,
"mot_routine_test_time" => $motorTestingMaster->routine_test_time ?? "",
"mot_res_ry_ll" => $motorTestingMaster->res_ry_ll ?? "",
"mot_res_ry_ul" => $motorTestingMaster->res_ry_ul ?? "",
"mot_res_yb_ll" => $motorTestingMaster->res_yb_ll ?? "",
"mot_res_yb_ul" => $motorTestingMaster->res_yb_ul ?? "",
"mot_res_br_ll" => $motorTestingMaster->res_br_ll ?? "",
"mot_res_br_ul" => $motorTestingMaster->res_br_ul ?? "",
"mot_lock_volt_limit" => $motorTestingMaster->lock_volt_limit ?? "",
"mot_leak_cur_limit" => $motorTestingMaster->leak_cur_limit ?? "",
"mot_lock_cur_ll" => $motorTestingMaster->lock_cur_ll ?? "",
"mot_lock_cur_ul" => $motorTestingMaster->lock_cur_ul ?? "",
"mot_noload_cur_ll" => $motorTestingMaster->noload_cur_ll ?? "",
"mot_noload_cur_ul" => $motorTestingMaster->noload_cur_ul ?? "",
"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 ?? ""
];
return response()->json($output, 200);
}
/**
* 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

@@ -0,0 +1,123 @@
<?php
namespace App\Http\Controllers;
use App\Models\Plant;
use App\Models\User;
// use Carbon\Carbon;
use Hash;
use Illuminate\Http\Request;
class UserController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index()
{
//
}
/**
* Store a newly created resource in storage.
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*/
// show(string $id)
public function get_testing_data(Request $request)
{
$expectedUser = env('API_AUTH_USER');
$expectedPw = env('API_AUTH_PW');
$header_auth = $request->header('Authorization');
$header_user = $request->header('User-Name');
$header_pass = $request->header('User-Pass');
$expectedToken = $expectedUser.':'.$expectedPw;
if ('Bearer '.$expectedToken != $header_auth) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => 'Invalid authorization token!',
], 403);
}
if (! $header_user) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => 'Invalid user name found!',
], 400);
} elseif (! $header_pass) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => 'Invalid password found!',
], 400);
}
$existUser = User::where('name', $header_user)->first();
$existPlant = 'All Plants';
if (! $existUser) {
return response()->json([
'status_code' => 'ERROR',
'status_description' => 'Unknown user name found!',
], 400);
} else {
$codeExist = Plant::where('id', $existUser->plant_id)->first();
if ($codeExist) {
$existPlant = $codeExist->code;
}
}
// Retrieve the user by email
// $user = User::where('email', $email)->first();
if (Hash::check($header_pass, $existUser->password)) {
return response()->json([
'created_at' => $existUser->created_at->format('Y-m-d H:i:s') ?? '',
'updated_at' => $existUser->updated_at->format('Y-m-d H:i:s') ?? '',
'requested_at' => now()->format('Y-m-d H:i:s') ?? '', // Carbon::now(config('app.timezone'))->format('Y-m-d H:i:s') ?? "",
'plant' => (string) $existPlant ?? '',
'email' => $existUser->email ?? '',
'roles' => $existUser->roles()->pluck('name')->toArray(),
], 200);
} else {
return response()->json([
'status_code' => 'ERROR',
'status_description' => 'Password does not match!',
], 400);
}
// $machines = User::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->line->group_work_center ?? "",
// 'work_center' => $machine->work_center ?? "",
// ];
// });
// return response()->json([
// 'machines' => $machinesData
// ]);
}
/**
* Update the specified resource in storage.
*/
public function update(Request $request, string $id)
{
//
}
/**
* Remove the specified resource from storage.
*/
public function destroy(string $id)
{
//
}
}