From bbe05d62b148c05b56eb3bfb6f35d2dcae4424a4 Mon Sep 17 00:00:00 2001 From: dhanabalan Date: Fri, 26 Sep 2025 11:40:00 +0530 Subject: [PATCH] Enhance readFiles method to validate CSV row structure and return error response for insufficient columns --- app/Http/Controllers/SapFileController.php | 42 ++++++++++++---------- 1 file changed, 24 insertions(+), 18 deletions(-) diff --git a/app/Http/Controllers/SapFileController.php b/app/Http/Controllers/SapFileController.php index 7da07a2..b6113b4 100644 --- a/app/Http/Controllers/SapFileController.php +++ b/app/Http/Controllers/SapFileController.php @@ -177,31 +177,37 @@ class SapFileController extends Controller // 'status' => 'SUCCESS', // 'rows_imported' => count($rows), // ]); - // Remove header row - $headerLine = array_shift($lines); + // Prepare arrays $serialNumbers = []; $remainingRows = []; - foreach ($lines as $line) { - $values = str_getcsv($line); - - // Serial number is 6th column (index 5) - $serialNumbers[] = $values[5] ?? null; - - // Remove the serial number column and keep remaining - $remainingRow = $values; - unset($remainingRow[5]); - $remainingRow = array_values($remainingRow); // reindex array - $remainingRows[] = $remainingRow; - } + foreach ($lines as $line) { + $values = str_getcsv($line); + // Debug: make sure CSV split is correct + if (count($values) < 6) { return response()->json([ - 'status' => 'SUCCESS', - 'serial_numbers' => $serialNumbers, - 'remaining_rows' => $remainingRows, - ]); + 'status' => 'ERROR', + 'message' => 'CSV row has fewer than 6 columns', + 'line' => $line + ], 400); + } + + $serialNumbers[] = $values[5] ?? null; + + $remainingRow = $values; + unset($remainingRow[5]); + $remainingRow = array_values($remainingRow); // reindex + $remainingRows[] = $remainingRow; +} + +return response()->json([ + 'status' => 'SUCCESS', + 'serial_numbers' => $serialNumbers, + 'remaining_rows_sample' => array_slice($remainingRows, 0, 5), // just first 5 for debug +]); }