Files
pds/app/Http/Controllers/ObdController.php
2025-05-24 20:33:51 +05:30

572 lines
22 KiB
PHP

<?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');
}
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 = "ERROR: Missing required field(s): " . implode(', ', $missing);
return response($message, 400)->header('Content-Type', 'text/plain');
}
// 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');
}
// 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');
}
//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');
}
$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');
}
$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', '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 = "ERROR: " . $fieldsString . " can't be empty for line_number " . $line['line_number'];
return response($message, 400)->header('Content-Type', 'text/plain');
}
// Check if ANY of the fields are NOT empty in DB
$fields = ['vehicle_number', 'bundle_number', 'picked_weight', 'scanned_by'];
$alreadyUpdatedLines = [];
foreach ($data['line_numbers'] as $line) {
// Fetch the record for this line
$record = WeightValidation::where('plant_id', $plantId)
->where('obd_number', $data['obd_number'])
->where('line_number', $line['line_number'])
->first();
//If No Record Found
if (!$record)
{
continue; // Skip to next line
}
$hasAnyValue = false;
foreach ($fields as $field)
{
if (!empty($record->$field))
{
$hasAnyValue = true;
break;
}
}
if ($hasAnyValue)
{
$alreadyUpdatedLines[] = $line['line_number'];
}
}
if (!empty($alreadyUpdatedLines))
{
return response( "Already line number(s): " . implode(', ', $alreadyUpdatedLines) . " is updated for obd_number '" . $data['obd_number'] . "'", 400)->header('Content-Type', 'text/plain');
}
}
// If any lines are missing, report
if (!empty($missingLines)) {
$message = "ERROR: 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');
}
$updated = 0;
$updatedLines = [];
foreach ($data['line_numbers'] as $line)
{
$count = WeightValidation::where([
'plant_id' => $plantId,
'obd_number' => $data['obd_number'],
'line_number'=> $line['line_number'],
])
->update([
'vehicle_number' => $line['vehicle_number'] ?? null,
'bundle_number' => $line['bundle_number'] ?? null,
'picked_weight' => $line['picked_weight'] ?? null,
'scanned_by' => $line['scanned_by'] ?? null,
'updated_at' => now(),
]);
//$updated += $count;
if ($count > 0) {
$updated += $count;
$updatedLines[] = $line['line_number'];
}
}
$message = "SUCCESS: OBD Number '" . $data['obd_number'] . "' updated successfully and line number(s): " . implode(', ', $updatedLines);
return response($message, 200)->header('Content-Type', 'text/plain');
// $message = "SUCCESS: OBD Number '" . $data['obd_number'] . "' updated successfully";
// return response($message, 200)->header('Content-Type', 'text/plain');
}
catch (\Exception $e)
{
return response("ERROR: Server error", 500)->header('Content-Type', 'text/plain');
}
}
//Route::post('obd/store-test-data', [ObdController::class, 'test'])
public function 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("ERROR: Unauthorized", 403)
// ->header('Content-Type', 'text/plain');
// }
try
{
return response("Successfully Received", 200)->header('Content-Type', 'text/plain');
// $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 = "ERROR: Missing required field(s): " . implode(', ', $missing);
// return response($message, 400)->header('Content-Type', 'text/plain');
// }
// // 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');
// }
// // 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');
// }
// //Check if OBD number exists for that plant
// $obdRecords = WeightValidation::where('plant_id', $plantId)
// ->where('obd_number', $obdNumber)
// ->select('id', 'line_number') // Only fetch required columns
// ->get();
// if ($obdRecords->isEmpty()) {
// return response(
// "ERROR: OBD Number '$obdNumber' not found for plant '{$data['plant_name']}'",
// 404
// )->header('Content-Type', 'text/plain');
// }
// $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');
// }
// $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', '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 = "ERROR: " . $fieldsString . " can't be empty for line_number " . $line['line_number'];
// return response($message, 400)->header('Content-Type', 'text/plain');
// }
// // Check if ANY of the fields are NOT empty in DB
// $fields = ['vehicle_number', 'bundle_number', 'picked_weight', 'scanned_by'];
// $alreadyUpdatedLines = [];
// foreach ($data['line_numbers'] as $line) {
// // Fetch the record for this line
// $record = WeightValidation::where('plant_id', $plantId)
// ->where('obd_number', $data['obd_number'])
// ->where('line_number', $line['line_number'])
// ->first();
// //If No Record Found
// if (!$record)
// {
// continue; // Skip to next line
// }
// $hasAnyValue = false;
// foreach ($fields as $field)
// {
// if (!empty($record->$field))
// {
// $hasAnyValue = true;
// break;
// }
// }
// if ($hasAnyValue)
// {
// $alreadyUpdatedLines[] = $line['line_number'];
// }
// }
// // Only after checking all lines, return if any already updated
// if (!empty($alreadyUpdatedLines)) {
// return response(
// "Already line number(s) updated for obd number '{$data['obd_number']}' is :" . implode(', ', $alreadyUpdatedLines),
// 400
// )->header('Content-Type', 'text/plain');
// }
// }
// // If any lines are missing, report
// if (!empty($missingLines)) {
// $message = "ERROR: 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');
// }
// // If we reach here, all lines are valid and need updating
// $updated = 0;
// foreach ($data['line_numbers'] as $line)
// {
// $count = WeightValidation::where([
// 'plant_id' => $plantId,
// 'obd_number' => $data['obd_number'],
// 'line_number'=> $line['line_number'],
// ])
// ->update([
// 'vehicle_number' => $line['vehicle_number'] ?? null,
// 'bundle_number' => $line['bundle_number'] ?? null,
// 'picked_weight' => $line['picked_weight'] ?? null,
// 'scanned_by' => $line['scanned_by'] ?? null,
// 'updated_at' => now(),
// ]);
// $updated += $count;
// }
// $message = "SUCCESS: OBD Number '" . $data['obd_number'] . "' updated successfully";
// return response($message, 200)->header('Content-Type', 'text/plain');
}
catch (\Exception $e)
{
return response("ERROR: Server error", 500)->header('Content-Type', 'text/plain');
}
}
/**
* Display the specified resource.
*/
// public function get(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');
// }
// $plantName = $request->header('Plant_Name');
// $obdNumber = $request->header('obd_number');
// if (empty($plantName) || empty($obdNumber)) {
// return response("ERROR: Missing required headers (Plant_Name, OBD_Number)", 400)
// ->header('Content-Type', 'text/plain');
// }
// // Fetch the plant record by name
// $plant = Plant::where('name', $plantName)->value('id');
// if (!$plant)
// {
// return response("ERROR: Plant not found", 400)
// ->header('Content-Type', 'text/plain');
// }
// $plantId = $plant->id;
// $records = WeightValidation::where('plant_id', $plantId)
// ->where('obd_number', $obdNumber)
// ->get();
// if ($records->isEmpty()) {
// return response("ERROR: No records found", 404)->header('Content-Type', 'text/plain');
// }
// $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 ?? "",
// // 'Quantity' => $item->picked_weight ?? "",
// 'Batch_Number' => $item->batch_number ?? "",
// 'Heat_Number' => $item->heat_number ?? "",
// ];
// })->toArray()
// ]
// ]
// ];
// return response()->json($ObdResponseStructure);
// }
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');
}
$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');
}
else if(empty($obdNumber))
{
return response("ERROR: OBD Number can't be empty", 400)
->header('Content-Type', 'text/plain');
}
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');
}
// 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');
}
// $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');
}
$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', 'text/plain');
}
$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)
{
//
}
}