diff --git a/app/Controllers/StockController.php b/app/Controllers/StockController.php index 47c3f76a..01ac48e5 100644 --- a/app/Controllers/StockController.php +++ b/app/Controllers/StockController.php @@ -28,6 +28,10 @@ use App\Models\MonthWiseMachinesInStockModel; use App\Models\TrpAbstractModel; +helper('stock'); + + + @@ -145,10 +149,11 @@ class StockController extends BaseController } //incoming Silica Sand Details starts + // refactored public function loadView_incomingSilicaSandDetails() { - //one remark is for comments and another remark here is alais status of the sand report , due to client request naming is given wrong , + //here - one remark is for comments and another remark here is alais status of the sand report , due to client request naming is given wrong , //hope you bear it..!! //we did ..!! @@ -170,7 +175,7 @@ class StockController extends BaseController $month = $formattedDate; //setting session for any month change - $session = session (); + $session = session(); $session->set('stock_month',$month); @@ -239,6 +244,8 @@ class StockController extends BaseController } + //insert or update incoming silica sand details + //refactored public function updateIncomingSilicaSandDetails() { @@ -256,45 +263,48 @@ class StockController extends BaseController ->findAll(); $existingIds = array_column($existingRecords, 'id'); + $inserts = []; $updates = []; foreach ($incomingSilicaSandDetailsData as $data) { - $id = !empty($data['id']) ? $data['id'] : null; + + //check for id and assign null if not present + $id = empty($data['id']) ? null : $data['id'] ; $dbData = [ - 'igrNo_fk' => $data['igrNo'], - 'gradeCondition' => $data['gradeCondition'], - '_10' => $data['_10'], - '_20' => $data['_20'], - '_30' => $data['_30'], - '_40' => $data['_40'], - '_50' => $data['_50'], - '_70' => $data['_70'], - '_100' => $data['_100'], - '_140' => $data['_140'], - '_200' => $data['_200'], - '_300' => $data['_300'], - 'pan' => $data['pan'], - 'total' => $data['total'], - 'afsSpec' => $data['afsSpec'], - 'afsActual' => $data['afsActual'], - 'plus20loss' => $data['plus20loss'], - 'plus30Loss' => $data['plus30Loss'], - 'moistureSpec' => $data['moistureSpec'], - 'moistureActual' => $data['moistureActual'], - 'moistureLoss' => $data['moistureLoss'], - 'moistureLossQty' => $data['moistureLossQty'], - 'sieveLossQty' => $data['sieveLossQty'], - 'salableQty' => $data['salableQty'], - 'remark' => $data['remark'], - 'materialCode' => $data['materialCode'], - 'clayOrLossOfIgnition' => $data['clayOrLossOfIgnition'], - 'testedBy' => $data['testedBy'], - 'approvedBy' => $data['approvedBy'], - 'reportComments' => $data['reportComments'], - 'gradeRange' => $data['gradeRange'], - 'reportTime' => $data['reportTime'], + 'igrNo_fk' => $data['igrNo'], + 'gradeCondition' => $data['gradeCondition'], + '_10' => $data['_10'], + '_20' => $data['_20'], + '_30' => $data['_30'], + '_40' => $data['_40'], + '_50' => $data['_50'], + '_70' => $data['_70'], + '_100' => $data['_100'], + '_140' => $data['_140'], + '_200' => $data['_200'], + '_300' => $data['_300'], + 'pan' => $data['pan'], + 'total' => $data['total'], + 'afsSpec' => $data['afsSpec'], + 'afsActual' => $data['afsActual'], + 'plus20loss' => $data['plus20loss'], + 'plus30Loss' => $data['plus30Loss'], + 'moistureSpec' => $data['moistureSpec'], + 'moistureActual' => $data['moistureActual'], + 'moistureLoss' => $data['moistureLoss'], + 'moistureLossQty' => $data['moistureLossQty'], + 'sieveLossQty' => $data['sieveLossQty'], + 'salableQty' => $data['salableQty'], + 'remark' => $data['remark'], + 'materialCode' => $data['materialCode'], + 'clayOrLossOfIgnition' => $data['clayOrLossOfIgnition'], + 'testedBy' => $data['testedBy'], + 'approvedBy' => $data['approvedBy'], + 'reportComments' => $data['reportComments'], + 'gradeRange' => $data['gradeRange'], + 'reportTime' => $data['reportTime'], ]; if ($id && in_array($id, $existingIds)) { @@ -318,6 +328,7 @@ class StockController extends BaseController //This is particulary updated by the lab technichians + //refactored public function updateLabReport() { @@ -326,35 +337,35 @@ class StockController extends BaseController $id = $postData['id']; $dbData = [ - 'igrNo_fk' => $postData['igrNo'], - 'materialCode' => $postData['materialCode'], - '_10' => $postData['_10Mm'], - '_20' => $postData['_20Mm'], - '_30' => $postData['_30Mm'], - '_40' => $postData['_40Mm'], - '_50' => $postData['_50Mm'], - '_70' => $postData['_70Mm'], - '_100' => $postData['_100Mm'], - '_140' => $postData['_140Mm'], - '_200' => $postData['_200Mm'], - '_300' => $postData['_300Mm'], - 'pan' => $postData['pan'], - 'total' => $postData['total'], - 'plus20Loss' => $postData['plus20Loss'], - 'plus30Loss' => $postData['plus30Loss'], - 'moistureSpec' => $postData['moistureSpec'], - 'moistureActual' => $postData['moistureActual'], - 'moistureLoss' => $postData['moistureLoss'], - 'moistureLossQty' => $postData['moistureLossQty'], - 'sieveLossQty' => $postData['sieveLossQty'], - 'salableQty' => $postData['salableQty'], - 'testedBy' => $postData['testedBy'], - 'approvedBy' => $postData['approvedBy'], + 'igrNo_fk' => $postData['igrNo'], + 'materialCode' => $postData['materialCode'], + '_10' => $postData['_10Mm'], + '_20' => $postData['_20Mm'], + '_30' => $postData['_30Mm'], + '_40' => $postData['_40Mm'], + '_50' => $postData['_50Mm'], + '_70' => $postData['_70Mm'], + '_100' => $postData['_100Mm'], + '_140' => $postData['_140Mm'], + '_200' => $postData['_200Mm'], + '_300' => $postData['_300Mm'], + 'pan' => $postData['pan'], + 'total' => $postData['total'], + 'plus20Loss' => $postData['plus20Loss'], + 'plus30Loss' => $postData['plus30Loss'], + 'moistureSpec' => $postData['moistureSpec'], + 'moistureActual' => $postData['moistureActual'], + 'moistureLoss' => $postData['moistureLoss'], + 'moistureLossQty' => $postData['moistureLossQty'], + 'sieveLossQty' => $postData['sieveLossQty'], + 'salableQty' => $postData['salableQty'], + 'testedBy' => $postData['testedBy'], + 'approvedBy' => $postData['approvedBy'], 'clayOrLossOfIgnition' => $postData['clayOrLossOfIgnition'], - 'reportComments' => $postData['reportComments'], - 'gradeRange' => $postData['gradeRange'], - 'reportTime' => $postData['reportTime'], - 'remark' => $postData['remark'] + 'reportComments' => $postData['reportComments'], + 'gradeRange' => $postData['gradeRange'], + 'reportTime' => $postData['reportTime'], + 'remark' => $postData['remark'] ]; @@ -380,8 +391,10 @@ class StockController extends BaseController } //Drier machine details + //refactored public function drierMachineDetails() { + // Drier machine details follow a different method of processing stock month and date format than other stock records. // The stock month and date format must be handled carefully while generating and updating data. @@ -450,13 +463,12 @@ class StockController extends BaseController } - + //add or edit drier machine Details + //refactored public function addOrEditdrierMachineDetails() { - // Retrieve form data from the POST request $data = $this->request->getPost(); - // Map the received data into a structured format using the helper function `mapDrierEntry` $drierData[] = $this->mapDrierEntry($data); // Begin a database transaction to ensure atomicity @@ -466,7 +478,6 @@ class StockController extends BaseController // Arrays to store data for batch insert and batch update operations $inserts = []; $updates = []; - foreach ($drierData as $row) { // Retrieve the ID of the existing entry (if present) @@ -474,20 +485,18 @@ class StockController extends BaseController $data = $row; if ($existingRow) { - + $existingRow = $this->drierMachineDetails_model->where('id', $row['id'] ?? '')->first(); // Handle gas stock updates for the existing record $this->handleGasStockUpdate($existingRow, $row); - - $updates[] = $data; + $updates[] = $data ; } else { // If it's a new record, update gas stock consumption before inserting $this->updateGasStockConsumption($data['date'], $data['total_gas_consumption']); - - - $inserts[] = $data; + + $inserts[] = $data ; } } @@ -520,10 +529,10 @@ class StockController extends BaseController } } - /** * Maps input row to expected format. */ + // refactored private function mapDrierEntry(array $data): array { return [ @@ -545,35 +554,11 @@ class StockController extends BaseController ]; } - - //Coating Machine Details starts + //refactored public function loadView_coatingMachineDetails() { - if ($this->request->getMethod() === 'POST') { - // Get the month from the request - $month = $this->request->getPost('month'); - - // Convert month format from "M-Y" to "Y-m" - $date = DateTime::createFromFormat('d-M-Y', '01-'.$month); - - $formattedDate = $date->format('Y-m'); - - $month = $formattedDate; - - // Store selected month in session - $session = session(); - $session->set('stock_month', $month); - - } else { - $session = session(); - $month = $session->get('stock_month'); - - // Default to the current month if no month is stored in session - if (empty($month)) { - $month = date('Y-m'); - } - } + $month = getStockMonth($this->request); $data['month'] = $month; $this->global['pageTitle'] = 'Coating Machine Details'; @@ -583,28 +568,12 @@ class StockController extends BaseController $endDate = date("Y-m-t", strtotime($startDate)); // Fetch coating machine details with batch card file details - $data['coatingMachineDetails'] = $this->coatingMachineDetails_model - ->select('t_coatingmachinedetails.*, - JSON_ARRAYAGG( - JSON_OBJECT( - "client_given_name", t_batchcard_files.client_file_name, - "filename", t_batchcard_files.filename, - "batchCardId" , t_batchcard_files.id, - "coating_id", t_batchcard_files.coating_id - ) - ) as batchcard_files') - ->join('t_batchcard_files', 't_batchcard_files.coating_id = t_coatingmachinedetails.id', 'left') - ->where('t_coatingmachinedetails.date >=', $startDate) - ->where('t_coatingmachinedetails.date <=', $endDate) - ->groupBy('t_coatingmachinedetails.id') - ->orderBy('t_coatingmachinedetails.date', 'asc') - ->findAll(); + $data['coatingMachineDetails'] = $this->coatingMachineDetails_model->coatingMachineDetails($startDate,$endDate); + // Convert month format from "Y-m" to "M-Y" for display $date = DateTime::createFromFormat('Y-m-d', $month.'-01'); - - $formattedDate = $date->format('M-Y'); $data['month'] = $formattedDate; @@ -614,270 +583,115 @@ class StockController extends BaseController } + //add new coating machine details + // refactored public function addNewCoatingMachineDetails() { - $message1 = ''; - $message2 = ''; - $message3 = ''; - $postData = $this->request->getPost(); $date = $postData['date']; $shift = $postData['shift']; - - // Check if the same shift already exists on the same date - $sameShiftOnDateExists = $this->coatingMachineDetails_model - ->where('date', $date) - ->where('shift', $shift) - ->where('is_active', 1) - ->first(); - - if (!empty($sameShiftOnDateExists)) { + + $multipleShift = $this->coatingMachineDetails_model->isShiftExists($date, $shift); + + if (!empty($multipleShift)) { return redirect()->back()->with('error', 'Already same shift exists on the same date ..!!'); } - - // Start transaction + $this->db->transBegin(); - + try { - // Insert data into coating machine details table $insertedId = $this->coatingMachineDetails_model->insert($postData); - - if ($insertedId !== false && $insertedId > 0) { - $message1 = 'Coating Machine details updated successfully'; - - // Update gas stock consumption - $dateToBeInserted = $postData['date']; - $consumption = $postData['totalGasConsumption']; - $updatedResult = $this->updateGasStockConsumption($dateToBeInserted, $consumption); - - if ($updatedResult === false || $updatedResult <= 0) { - throw new \Exception('Failed to update gas stock consumption.'); - } - - $message2 = 'And updated gas stock consumption.'; - $message3 = " Warning..!! Kindly Update the next subsequent month Gas Stock If older month Gas Stock Updated..!!"; - } else { - throw new \Exception('Failed to insert Coating machine details.'); - } - - // Handle batch card file uploads - if ($insertedId !== false && $insertedId > 0) { - $batchCardFiles = $this->request->getFileMultiple('batchCard'); - - if (!empty($batchCardFiles) && !($batchCardFiles[0]->getError() === UPLOAD_ERR_NO_FILE)) { - foreach ($batchCardFiles as $file) { - if ($file->isValid() && !$file->hasMoved()) { - $clientGivenName = $file->getClientName(); // Original filename - $newName = $file->getRandomName(); - $path = WRITEPATH . 'uploads' . DIRECTORY_SEPARATOR . 'batchcard'; - - if (!is_dir($path)) { - mkdir($path, 0777, true); - } - - if ($file->move($path, $newName)) { - // Insert file details into the database - $db = \Config\Database::connect(); - $builder = $db->table('t_batchcard_files'); - - $data = [ - 'client_file_name' => $clientGivenName, - 'filename' => $newName, - 'coating_id' => $insertedId - ]; - - $builder->insert($data); - } - } - } - } + if (!$insertedId) { + throw new \Exception('Failed to insert Coating Machine Details.'); } - + + $this->updateGasConsumptionOrFail($postData['date'], $postData['totalGasConsumption']); + + $this->handleBatchCardUploads($insertedId); + if ($this->db->transStatus() === false) { throw new \Exception('Transaction failed due to database errors.'); } - + $this->db->transCommit(); - - // Redirect with success message - return redirect()->to("/coatingMachineDetails") - ->with('success', $message1 . " " . $message2 . " " . $message3); + + $successMessage = 'Coating Machine details updated successfully. ' . 'And updated gas stock consumption. '. 'Warning..!! Kindly Update the next subsequent month Gas Stock If older month Gas Stock Updated..!!'; + + return redirect()->to("/coatingMachineDetails")->with('success', $successMessage); + } catch (\Exception $error) { $this->db->transRollback(); - return redirect()->back()->with('error', ' ' . $error->getMessage()); + return redirect()->back()->with('error', $error->getMessage()); } } - - + //update coating machine details + // refactored public function updateCoatingMachineDetails() { - - - $message1 = ''; - $message2 = ''; - $message3 = ''; - $putData = $this->request->getPost(); - - $id = $putData['editCoatingMachineDetailId']; - // Start transaction $this->db->transBegin(); + try { $updated = $this->coatingMachineDetails_model->update($id, $putData); - - - - if ($updated !== false && $updated > 0) { // Assuming $id is the record ID being updated - - $batchCardFiles = $this->request->getFileMultiple('batchCard'); - - if (is_array($batchCardFiles) && !empty($batchCardFiles)) { - // Step 4: Upload new files and insert into DB - foreach ($batchCardFiles as $index => $file) { - - if ( !empty($batchCardFiles[$index]) && !($batchCardFiles[$index]->getError() === UPLOAD_ERR_NO_FILE)) { - - $db = \Config\Database::connect(); - $builder = $db->table('t_batchcard_files'); - - if ($file->isValid() && !$file->hasMoved()) { - $clientGivenName = $file->getClientName(); // User-given filename - $newName = $file->getRandomName(); // Randomized unique filename - - $path = WRITEPATH . 'uploads' . DIRECTORY_SEPARATOR . 'batchcard'; - - if (!is_dir($path)) { - mkdir($path, 0777, true); - } - - if ($file->move($path, $newName)) { - // Insert new file record into the database - $data = [ - 'client_file_name' => $clientGivenName, - 'filename' => $newName, - 'coating_id' => $id - ]; - $builder->insert($data); - } - } - } - } - } - - - - } - - if ($updated !== false && $updated > 0) { - $message1 = "successfully updated Coating machineDetail ."; - //update Gas stock consumption if update is successfull..!! - $dateToBeUpdated = $putData['date']; - - $existingCoatingGasConsumption = $putData['existingTotalGasConsumption']; - $updatedCoatingGasConsumption = $putData['totalGasConsumption']; - - if ($existingCoatingGasConsumption != $updatedCoatingGasConsumption) { - - $changeInConsumption = $updatedCoatingGasConsumption - $existingCoatingGasConsumption; - $updatedResult = $this->updateGasStockConsumption($dateToBeUpdated, $changeInConsumption); - - if ($updatedResult === false || $updatedResult <= 0) { - // Explicit failure handling for gas stock update - throw new \Exception('Failed to update gas stock consumption.'); - } - $message2 = 'And updated gas stock consumption.'; - - $message3 = "Warning..!! Kindly Update the next subsequent month Gas Stock If older month Gas Stock Updated..!!"; - } - // Commit the transaction if all queries succeed - - - if ($this->db->transStatus() === false) { - throw new \Exception('Transaction failed due to database errors.'); - } - $this->db->transCommit(); - - - - - // Set flashdata for success message - return redirect()->to("/coatingMachineDetails") - ->with('success', $message1 . " " . $message2 . " " . $message3); - } else { + if (!$updated) { throw new \Exception('Failed to update Coating machine details.'); } - - - + $this->handleBatchCardUploads($id); + + $messages = ['successfully updated Coating machineDetail.']; + + $this->handleGasConsumptionAdjustment($putData, $messages); + + if ($this->db->transStatus() === false) { + throw new \Exception('Transaction failed due to database errors.'); + } + + $this->db->transCommit(); + + return redirect()->to("/coatingMachineDetails") + ->with('success', implode(" ", $messages)); } catch (\Exception $error) { $this->db->transRollback(); - return redirect()->back()->with('error', ' ' . $error->getMessage()); + return redirect()->back()->with('error', $error->getMessage()); } } + //deleteBatchCardFile + // refactored public function deleteBatchCardFile() { $data = $this->request->getPost(); - - if (!empty($data)) { - - $batchId = $data['id']; - $db = \Config\Database::connect(); - $builder = $db->table('t_batchcard_files'); - - // Step 1: Fetch the filename from DB before deleting - $fileRecord = $builder->select('filename')->where('id', $batchId)->get()->getRow(); - - if ($fileRecord) { - $path = WRITEPATH . 'uploads' . DIRECTORY_SEPARATOR . 'batchcard'; - - if (!is_dir($path)) { - mkdir($path, 0777, true); - } - $filePath = $path . DIRECTORY_SEPARATOR . $fileRecord->filename; - - // Step 2: Delete the file from storage - if (file_exists($filePath)) { - unlink($filePath); - } - - // Step 3: Delete the record from the database - $sql = "DELETE FROM t_batchcard_files WHERE id = ?"; - $deleted = $db->query($sql, [$batchId]); - - if ($deleted) { - return $this->response->setJSON([ - 'status' => '200', - 'message' => "Deleted Batch Card File Successfully..!!" - ]); - } else { - return $this->response->setJSON([ - 'status' => '400', - 'message' => "Failed to Delete..!! Try Again Later" - ]); - } - } else { - return $this->response->setJSON([ - 'status' => '404', - 'message' => "File Not Found..!!" - ]); - } + if (empty($data)) { + return $this->respondWithJson(400, "Invalid Request..!!"); } - return $this->response->setJSON([ - 'status' => '400', - 'message' => "Invalid Request..!!" - ]); + $batchId = $data['id']; + + $fileRecord = $this->getBatchCardFileRecord($batchId); + if (!$fileRecord) { + return $this->respondWithJson(404, "File Not Found..!!"); + } + + $fileDeleted = $this->deleteBatchCardFileFromStorage($fileRecord->filename); + + $recordDeleted = $this->deleteBatchCardFileRecord($batchId); + + if ($recordDeleted) { + return $this->respondWithJson(200, "Deleted Batch Card File Successfully..!!"); + } + + return $this->respondWithJson(400, "Failed to Delete..!! Try Again Later"); } - - + + //downloadBatchCardZip + // refactored public function downloadBatchcardZip() { @@ -908,6 +722,7 @@ class StockController extends BaseController $zip = new \ZipArchive(); + if ($zip->open($zipFilePath, \ZipArchive::CREATE | \ZipArchive::OVERWRITE) === true) { foreach ($batchCardFiles as $file) { @@ -915,11 +730,9 @@ class StockController extends BaseController $originalFilePath = $zipPath . DIRECTORY_SEPARATOR . $file['filename']; // Actual stored file $clientFileName = $file['client_file_name'] ?? $file['filename']; // Use client name if available - + if (file_exists($originalFilePath)) { - $zip->addFile($originalFilePath, $clientFileName); // Rename inside ZIP - } } $zip->close(); @@ -938,937 +751,427 @@ class StockController extends BaseController return redirect()->back()->with('error', 'Failed to create ZIP file.'); } - - // Example function to get batchcard files from DB - private function getBatchCardFiles($coatingId) - { - $batchCardFiles = $this->db->table('t_batchcard_files') - ->where('coating_id', $coatingId) - ->get() - ->getResultArray(); - - return $batchCardFiles; - } - - - - //Gas Stock Details - public function loadView_gasStockDetails() - { - - if ($this->request->getMethod() === 'POST') { - - $month = $this->request->getPost('month'); - - $date = DateTime::createFromFormat('d-M-Y', '01-'.$month); - - $formattedDate = $date->format('Y-m'); - - $month = $formattedDate; - - $session = session (); - - $session->set('stock_month',$month); - - } else { - $session = session(); - - $month = $session->get('stock_month'); - - if (empty($month)) { - $month = date('Y-m'); // Default to the current month - } - } - - $data = []; - - $data['month'] = $month; - - $this->global['pageTitle'] = "Gas Stock Details"; - - - $previousMonth = DateTime::createFromFormat('Y-m-d', $month.'-01')->modify('-1 month')->format('Y-m'); - $previousMonthStartDate = "$previousMonth-01"; - $previousMonthEndDate = date("Y-m-t", strtotime($previousMonthStartDate)); - $data['previousMonthGasStockDetails'] = $this->gasStockDetails_model - ->select('date,balanceStock') - ->where('date =', $previousMonthEndDate) - ->orderBy('date', 'desc') - ->findAll(); - - $startDate = "$month-01"; - $endDate = date("Y-m-t", strtotime($startDate)); - - $data['gasStockDetails'] = $this->gasStockDetails_model - ->select( - 't_gasstockdetails.*, - drier_summary.drierMachineGasconsumption AS drierMachineGasConsumption, - drier_summary.driedSand AS sandDried, - coating_summary.coatingMachineGasconsumption, - coating_summary.coatedSand' - ) - // Subquery with early date filtering - ->join( - '(SELECT date, - SUM(totalGasconsumption) AS coatingMachineGasconsumption, - SUM(totalCoatingSandInKg) AS coatedSand - FROM t_coatingmachinedetails - WHERE is_active = 1 - AND date >= ' . $this->db->escape($startDate) . ' - AND date <= ' . $this->db->escape($endDate) . ' - GROUP BY date - ) AS coating_summary', - 'coating_summary.date = t_gasstockdetails.date', - 'left' - ) - ->join( - '(SELECT date, - SUM(total_gas_consumption) AS drierMachineGasconsumption, - SUM(sand_dried_qty) AS driedSand - FROM t_driermachinedetails - WHERE date >= ' . $this->db->escape($startDate) . ' - AND date <= ' . $this->db->escape($endDate) . ' - GROUP BY date - ) AS drier_summary', - 'drier_summary.date = t_gasstockdetails.date', - 'left' - ) - - ->where('t_gasstockdetails.date >=', $startDate) - ->where('t_gasstockdetails.date <=', $endDate) - ->groupBy('t_gasstockdetails.date') - ->findAll(); - - - - $date = DateTime::createFromFormat('Y-m-d', $month.'-01'); - - $formattedDate = $date->format('M-Y'); - $data['month'] = $formattedDate; - return $this->loadViews("stock/gasStockDetails", $this->global, $data, NULL); - } + //Gas Stock Details + // refactored + public function loadView_gasStockDetails() + { + $month = getStockMonth($this->request); + + $data = []; + $data['month'] = $month; + $this->global['pageTitle'] = "Gas Stock Details"; + + $previousMonthDates = $this->getPreviousMonthDateRange($month); + + $data['previousMonthGasStockDetails'] = $this->gasStockDetails_model + ->select('date, balanceStock') + ->where('date', $previousMonthDates['end']) + ->orderBy('date', 'desc') + ->findAll(); + - public function updateGasStockDetails() - { + $startDate = "$month-01"; + $endDate = date("Y-m-t", strtotime($startDate)); + - $postData = $this->request->getPost(); + $data['gasStockDetails'] = $this->gasStockDetails_model->gasStockDetails($startDate, $endDate); + + // Format month for view display (e.g., Apr-2025) + $formattedDate = DateTime::createFromFormat('Y-m-d', $startDate)->format('M-Y'); + $data['month'] = $formattedDate; + + return $this->loadViews("stock/gasStockDetails", $this->global, $data, NULL); + } + - $updateGasStockDetailsData = json_decode($postData['updateGasStockDetails'], true); + // updateGasStockDetails + // refactored + public function updateGasStockDetails() + { - $updates = []; + $postData = $this->request->getPost(); - $inserts = []; + $updateGasStockDetailsData = json_decode($postData['updateGasStockDetails'], true); - foreach ($updateGasStockDetailsData as $data) { + $updates = []; - $date = $data['date']; + $inserts = []; + foreach ($updateGasStockDetailsData as $data) { - $dbData = [ - 'date' => $data['date'] , - 'opening' => $data['opening'] , - 'purchaseBharath' => $data['purchaseBharath'] , - 'purchaseIndian' => $data['purchaseIndian'] , - 'total' => $data['total'] , - 'consumption' => $data['consumption'] , - 'balanceStock' => $data['balanceStock'] , - 'trp_panel_gas_consumption' => $data['trpPanelGasConsumption'] , - 'trp_physical_gas_consumption' => $data['trpPhysicalGasConsumption'] , - 'trp_sand_production' => $data['trpSandProduction'] , - 'rotary_drier_consumption' => $data['rotaryDrierConsumption'] - ]; + $date = $data['date']; - $resultExists = $this->gasStockDetails_model - ->where('date', $date) - ->first(); + $dbData = [ + 'date' => $data['date'] , + 'opening' => $data['opening'] , + 'purchaseBharath' => $data['purchaseBharath'] , + 'purchaseIndian' => $data['purchaseIndian'] , + 'total' => $data['total'] , + 'consumption' => $data['consumption'] , + 'balanceStock' => $data['balanceStock'] , + 'trp_panel_gas_consumption' => $data['trpPanelGasConsumption'] , + 'trp_physical_gas_consumption' => $data['trpPhysicalGasConsumption'] , + 'trp_sand_production' => $data['trpSandProduction'] , + 'rotary_drier_consumption' => $data['rotaryDrierConsumption'] + ]; - - if (empty($resultExists)) { - $inserts[] = $dbData; - } else { - $dbData['id'] = $resultExists['id']; - $updates[] = $dbData; - } - - } - - - if (!empty($inserts)) { - $this->gasStockDetails_model->insertBatch($inserts); - } - - if (!empty($updates)) { - - $updateResult = $this->gasStockDetails_model->updateBatch($updates, 'id'); - - if ($updateResult === FALSE) { - echo "Error during update"; - } else { - echo "Data Updated Successfully"; - return; - } - } - - echo "Data Saved Successfully Warning..!! Kindly Update the next subsequent month Gas Stock If older month Gas Stock Updated..!!"; - } - - private function updateGasStockConsumption($date, $consumption) - { - // Check if an entry exists for the given date $resultExists = $this->gasStockDetails_model ->where('date', $date) ->first(); - - if ($resultExists) { - // Ensure the date is in the correct format - if ($date instanceof DateTime) { - $date = $date->format('Y-m-d'); - } elseif (!strtotime($date)) { - throw new \Exception("Invalid date format provided."); - } else { - $date = date('Y-m-d', strtotime($date)); - } - - // Get the last date of the month for the given date - $endDate = date('Y-m-t', strtotime($date)); - - // Fetch all stock entries from the given date till the end of the month - $resultExists = $this->gasStockDetails_model - ->where('date >=', $date) - ->where('date <=', $endDate) - ->orderBy('date', 'asc') - ->findAll(); - - $updatedOpeningStock = 0; - $updates = []; - - // Update stock values for each day in the month - foreach ($resultExists as $index => $result) { - if ($index == 0) { - // Update the first entry with new consumption - $result['consumption'] = (float)($result['consumption']) + (float)($consumption); - $result['total'] = (float)$result['opening'] + (float)$result['purchaseBharath'] + (float)$result['purchaseIndian']; - - $result['balanceStock'] = $result['total'] - $result['consumption']; - - $updatedOpeningStock = (int)$result['balanceStock']; - } else { - // Update subsequent entries based on previous balance - - $result['opening'] = (float)$updatedOpeningStock; - - $result['total'] = (float)$result['opening'] + (float)$result['purchaseBharath'] + (float)$result['purchaseIndian']; - - $result['balanceStock'] = (float)$result['total'] - (float)$result['consumption']; - - $updatedOpeningStock = (int)$result['balanceStock']; - } - - $updates[] = $result; - } - - // Perform batch update if there are changes - if (!empty($updates)) { - $result = $this->gasStockDetails_model->updateBatch($updates, 'id'); - return ($result !== false && $result > 0) ? $result : 0; - } else { - return 0; - } - - + if (empty($resultExists)) { + $inserts[] = $dbData; } else { - // Get the last date of the previous month - $previousMonthDate = new DateTime($date); - $previousMonthDate = $previousMonthDate->modify('first day of this month') - ->modify('-1 day') - ->format('Y-m-d'); - - // Check if the previous month's last day entry exists - $previousMonthResultExists = $this->gasStockDetails_model - ->where('date', $previousMonthDate) - ->first(); - - $opening = 0; - - // Set opening stock based on previous month's balance stock - if (!empty($previousMonthResultExists) && isset($previousMonthResultExists['balanceStock'])) { - $opening = $previousMonthResultExists['balanceStock']; - } - - // Generate a list of all dates in the current month - $startDate = DateTime::createFromFormat('Y-m-d', $date)->modify('first day of this month')->format('Y-m-d'); - $endDate = DateTime::createFromFormat('Y-m-d', $date)->modify('last day of this month')->format('Y-m-d'); - - $datesInMonth = []; - $inserts = []; - - $period = new DatePeriod( - new DateTime($startDate), - new DateInterval('P1D'), - (new DateTime($endDate))->modify('+1 day') - ); - - foreach ($period as $day) { - $datesInMonth[] = $day->format('Y-m-d'); - } - - // Insert stock records for each day in the month - foreach ($datesInMonth as $dateInMonth) { - $balanceStock = $opening; - $consumptionForDate = 0; - - if ($dateInMonth == $date) { - // Assign the given consumption for the provided date - $consumptionForDate = $consumption; - $balanceStock = $opening - $consumption; - } - - $inserts[] = [ - 'date' => $dateInMonth, - 'opening' => $opening, - 'purchaseBharath' => null, - 'purchaseIndian' => null, - 'total' => null, - 'consumption' => $consumptionForDate, - 'balanceStock' => $balanceStock - ]; - - // Update opening for the next day - $opening = $balanceStock; - } - - // Perform batch insert if data is available - if (!empty($inserts)) { - $result = $this->gasStockDetails_model->insertBatch($inserts); - return ($result !== false && $result > 0) ? $result : 0; - } else { - return 0; - } + $dbData['id'] = $resultExists['id']; + $updates[] = $dbData; + } + + } + + + if (!empty($inserts)) { + $this->gasStockDetails_model->insertBatch($inserts); + } + + if (!empty($updates)) { + + $updateResult = $this->gasStockDetails_model->updateBatch($updates, 'id'); + + if ($updateResult === FALSE) { + echo "Error during update"; + } else { + echo "Data Updated Successfully"; + return; } } - + echo "Data Saved Successfully Warning..!! Kindly Update the next subsequent month Gas Stock If older month Gas Stock Updated..!!"; + } + //updateGasStockConsumption + // refactored + private function updateGasStockConsumption($date, $consumption) + { + $date = $this->convertToDateWithFlexibleFormats($date,["d-m-Y", "Y-m-d", "m/d/Y", "m-d-Y"],"Y-m-d"); - //diesel stock details + $resultExists = $this->gasStockDetails_model->where('date', $date)->first(); - public function dieselMachineStockDetails(){ + if ($resultExists) { - - if ($this->request->getMethod() === 'POST') { + $endDate = date('Y-m-t', strtotime($date)); - $month = $this->request->getPost('month'); + $records = $this->gasStockDetails_model->where('date >=', $date) + ->where('date <=', $endDate) + ->orderBy('date', 'asc') + ->findAll(); - $date = DateTime::createFromFormat('d-M-Y', '01-'.$month); + $updatedOpeningStock = 0; - $formattedDate = $date->format('Y-m'); - - $month = $formattedDate; - - $session = session (); - - $session->set('stock_month',$month); - - } else { - - $session = session(); - - $month = $session->get('stock_month'); - - if (empty($month)) { - $month = date('Y-m'); // Default to the current month + foreach ($records as $i => &$r) { + if ($i == 0) { + $r['consumption'] += (float)$consumption; + $r['total'] = (float)$r['opening'] + (float)$r['purchaseBharath'] + (float)$r['purchaseIndian']; + $r['balanceStock'] = $r['total'] - $r['consumption']; + $updatedOpeningStock = (int)$r['balanceStock']; + } else { + $r['opening'] = (float)$updatedOpeningStock; + $r['total'] = (float)$r['opening'] + (float)$r['purchaseBharath'] + (float)$r['purchaseIndian']; + $r['balanceStock'] = $r['total'] - $r['consumption']; + $updatedOpeningStock = (int)$r['balanceStock']; } } + //elvis operator + return $this->gasStockDetails_model->updateBatch($records, 'id') ?: 0; + } - $data = []; + $prevDate = (new DateTime($date))->modify('first day of this month')->modify('-1 day')->format('Y-m-d'); + $prev = $this->gasStockDetails_model->where('date', $prevDate)->first(); + $opening = (!empty($prev) && isset($prev['balanceStock'])) ? $prev['balanceStock'] : 0; - $data['month'] = $month; + $start = (new DateTime($date))->modify('first day of this month'); + $end = (new DateTime($date))->modify('last day of this month'); + $period = new DatePeriod($start, new DateInterval('P1D'), $end->modify('+1 day')); - $this->global['pageTitle'] = 'Diesel Machine Stock Details'; + $inserts = []; + foreach ($period as $d) { + $dStr = $d->format('Y-m-d'); + $cons = ($dStr == $date) ? $consumption : 0; + $balance = ($dStr == $date) ? $opening - $consumption : $opening; + $inserts[] = [ + 'date' => $dStr, + 'opening' => $opening, + 'purchaseBharath' => null, + 'purchaseIndian' => null, + 'total' => null, + 'consumption' => $cons, + 'balanceStock' => $balance + ]; + $opening = $balance; + } + //elvis operator + return $this->gasStockDetails_model->insertBatch($inserts) ?: 0; + } - //filter part starts + //diesel stock details + //refactored + public function dieselMachineStockDetails() + { + $month = getStockMonth($this->request); - //start date dynamic from front-end - $startDate = "$month-01"; - //end date of given month - $endDate = date("Y-m-t", strtotime($startDate)); - - - //filter applied currently - $customisedMachineCodes = $this->request->getPost('customisedMachineCodes') ?? []; - - - //already applied filter - $existingCustomMachineCodes = $this->monthWiseMachineInStockModel - ->select('machine_id') - ->where('date',"$month-01") - ->where('machine_category','diesel') - ->findAll(); - - $filterUpdateNeeded = true ; - - if( empty($customisedMachineCodes) && !empty($existingCustomMachineCodes)){ - $customisedMachineCodes = array_column($existingCustomMachineCodes, 'machine_id') ; - $filterUpdateNeeded = false ; - - } - - - //check user applies for filter currently - if(!empty($customisedMachineCodes) && $filterUpdateNeeded){ - - //user applied filter, - - //check already filter existing , if exists remove that , - if(!empty($existingCustomMachineCodes)){ - - //hard delete done..!! - $existingCustomMachineCodes = $this->monthWiseMachineInStockModel - ->where('date',"$month-01") - ->where('machine_category','diesel') - ->delete(); - - } - - - //if no filter already exists or removed current one , just add current filter for that month ....!! - $inserts = []; - - foreach($customisedMachineCodes as $index => $customisedMachineCode){ - - $inserts [] = [ - 'date' => "$month-01", - 'machine_category' => "diesel", - 'machine_id' => $customisedMachineCode - ]; - - } - - if(!empty($inserts)){ - //insert all the latest applied filter - $this->monthWiseMachineInStockModel->insertBatch($inserts); - - //get the currently applied filter - $existingCustomMachineCodes = $this->monthWiseMachineInStockModel - ->select('machine_id') - ->where('date',"$month-01") - ->where('machine_category','diesel') - ->get() - ->getResultArray(); - - } - - } - - - //possible if no filter applied at all...!!! - if(empty($existingCustomMachineCodes)){ - - //no filter applied at all just present previous month material codes - - $previousMonth = date('Y-m-01', strtotime('-1 month', strtotime("$month-01"))); - - $previousMonthCustomMachineCodes = $this->monthWiseMachineInStockModel - ->select('machine_id') - ->where('date',"$previousMonth") - ->where('machine_category','diesel') - ->get() - ->getResultArray(); - - if(!empty($previousMonthCustomMachineCodes)){ - $existingCustomMachineCodes = $this->factoryMachine_model - ->getSelectedDieselMachines(array_column($previousMonthCustomMachineCodes, 'machine_id')); - }else{ - - // inserting all active if no previous month present - $existingCustomMachineCodes = $this ->factoryMachine_model - ->getAllActiveDieselMachines(); - - //add this active products in monthwisemachine stock table - $inserts = []; - - foreach($existingCustomMachineCodes as $index => $customisedMachineCode){ - - $inserts [] = [ - 'date' => "$month-01", - 'machine_category' => "diesel", - 'machine_id' => $customisedMachineCode['id'] - ]; - - } - - if(!empty($inserts)){ - //insert all the latest applied filter - $this->monthWiseMachineInStockModel->insertBatch($inserts); - - } - - } - - - }else{ - //if filter present,get that material codes - $existingCustomMachineCodes = $this->factoryMachine_model - ->getSelectedDieselMachines(array_column($existingCustomMachineCodes, 'machine_id')); - } - - - - //this existingCustomMachineCodes gets its machine 'id' after visiting factory machine master table in above step, - - $machineCodeList = array_column($existingCustomMachineCodes, 'id'); - - $currentDate = new DateTime(); - - if($startDate == $currentDate->format('Y-m-01') && $endDate == $currentDate->format('Y-m-t')){ - - foreach($machineCodeList as $index => $machineCode){ - - //checking filtered present in table , if not create dummy one for whole month - $findMachineCode = $this->factoryVehicleDieselDetails_model - ->where('date >=', $startDate) - ->where('date <=', $endDate) - ->where('machine_id',$machineCode) - ->findAll(); - + $startDate = "$month-01"; + $endDate = date("Y-m-t", strtotime($startDate)); + $currentDate = new DateTime(); + $data = [ + 'month' => $month, + 'activeDieselMachines' => $this->factoryMachine_model->getAllActiveDieselMachines(), + ]; + $this->global['pageTitle'] = 'Diesel Machine Stock Details'; - //check any material code is not present in stock table but applied in filter - if(empty($findMachineCode)){ - //create dummy entry for this - $this->createDummyEntryForDieselMachine($machineCode,$startDate,$endDate); - } - - } - - } - + $customisedMachineCodes = $this->getOrUpdateCustomisedMachineCodes($month); + - $dieselMachines = $existingCustomMachineCodes; + if ($this->isCurrentMonth($startDate, $endDate, $currentDate)) { + $this->ensureDieselDetailsForMonth($customisedMachineCodes, $startDate, $endDate); + } + - $data['activeDieselMachines'] = $this->factoryMachine_model->getAllActiveDieselMachines(); + $dieselMachines = $this->factoryMachine_model->getSelectedDieselMachines($customisedMachineCodes); + $dieselMachinesCount = count($dieselMachines); + + [$prevDetails, $prevTotals] = $this->getPreviousMonthStockDetails($month); + $data['previousMonthDieselMachineStockDetails'] = $prevDetails; + $data['previousMonthTotalDieselMachineStockDetails'] = $prevTotals; + + $data['dieselMachineStockDetails'] = $this->factoryVehicleDieselDetails_model + ->where('date >=', $startDate) + ->where('date <=', $endDate) + ->whereIn('machine_id', $customisedMachineCodes) + ->groupBy(['machine_id', 'date']) + ->orderBy('date', 'asc') + ->orderBy('machine_id', 'asc') + ->findAll(); + - - // Get the previous month's last date diesel stock details for next month updation - - $previousMonth = DateTime::createFromFormat('Y-m-d', $month.'-01')->modify('-1 month')->format('Y-m'); - $previousMonthStartDate = "$previousMonth-01"; - $previousMonthEndDate = date("Y-m-t", strtotime($previousMonthStartDate)); - - $data['previousMonthDieselMachineStockDetails'] = $this->factoryVehicleDieselDetails_model - ->select(['machine_id', 'date', 'closing_reading']) - ->distinct() - ->where('date =', $previousMonthEndDate) - ->groupBy(['machine_id', 'date']) - ->orderBy('date', 'desc') - ->orderBy('machine_id', 'asc') - ->findAll(); - - - $data['previousMonthTotalDieselMachineStockDetails'] = $this->factoryVehicleDieselStockSummary_model - ->select(['id', 'date', 'balance_stock']) - ->distinct() - ->where('date =', $previousMonthEndDate) - ->groupBy(['id', 'date']) - ->orderBy('date', 'desc') - ->findAll(); - - - - // checking in database if the data is available for the month - - $startDate = "$month-01"; - $endDate = date("Y-m-t", strtotime($startDate)); - - $data['dieselMachineStockDetails'] = $this->factoryVehicleDieselDetails_model - ->where('date >=', $startDate) - ->where('date <=', $endDate) - ->whereIn('machine_id',$machineCodeList) - ->groupBy(['machine_id', 'date']) - ->orderBy('date', 'asc') - ->orderBy('machine_id', 'asc') - ->findAll(); - - - $data['totalDiesel'] = $this->factoryVehicleDieselStockSummary_model + $data['totalDiesel'] = $this->factoryVehicleDieselStockSummary_model ->where('date >=', $startDate) ->where('date <=', $endDate) ->orderBy('date', 'asc') ->findAll(); - - // Initialize an empty array to hold the grouped data - $data['groupedDieselMachineStockDetails'] = []; - - // Temporary array to store grouped data by date - $groupedByDate = []; - - // Group by 'date' - foreach ($data['dieselMachineStockDetails'] as $detail) { - $date = $detail['date']; - - // Initialize the outer array for this date if it doesn't exist - if (!isset($groupedByDate[$date])) { - $groupedByDate[$date] = []; - } - - /******************************************************************************************************************* - creating an sub array (inner array) for date wise and append the detail into an array as sub-array - - $groupedByDate[] outer array - - $groupedByDate[$date] - will look like [[material1],[material2],[material3],[material4],[material5]] inner array - - the above process is done for single row (date wise) and the same process is repeated for all the rows - *******************************************************************************************************************/ - - $groupedByDate[$date][] = $detail; - } - - // Sort each date's machines based on the custom order to set table body td - if (!empty($customisedMachineCodes)) { - - foreach ($groupedByDate as $date => &$machines) { - - usort($machines, function ($a, $b) use ($customisedMachineCodes) { - - $indexA = array_search($a['machine_id'], $customisedMachineCodes); - $indexB = array_search($b['machine_id'], $customisedMachineCodes); - - if ($indexA === false && $indexB === false) { - return 0; - } - if ($indexA === false) { - return 1; - } - if ($indexB === false) { - return -1; - } - - return $indexA - $indexB; - }); - } - unset($machines); - } - - // Reset the structure to have indexed arrays without the date keys - $data['groupedDieselMachineStockDetails'] = array_values($groupedByDate); - - - - // Sort each date's machines based on the custom order to set table header th - - if (!empty($customisedMachineCodes)) { - - - - usort($dieselMachines, function ($a, $b) use ($customisedMachineCodes) { - - $indexA = array_search($a['id'], $customisedMachineCodes); - $indexB = array_search($b['id'], $customisedMachineCodes); - - if ($indexA === false && $indexB === false) { - return 0; - } - if ($indexA === false) { - return 1; - } - if ($indexB === false) { - return -1; - } - - return $indexA - $indexB; - }); - - } - - $dieselMachinesCount = count($dieselMachines); - - $data['dieselMachinesCount'] = $dieselMachinesCount; - $data['dieselMachines'] = $dieselMachines; - - $date = DateTime::createFromFormat('Y-m-d', $month.'-01'); - - $formattedDate = $date->format('M-Y'); - - $data['month'] = $formattedDate ; - - // return $this->response->setJSON(['status' =>'success' ,'message' => $data['dieselMachines']]); - - return $this->loadViews("stock/dieselStockDetails", $this->global, $data, NULL); - - - - - } - - public function updateDieselMachineDetails() { - - $postData = $this->request->getPost(); - $updateDmDetailsData = json_decode($postData['updateDieselMachineDetails'], true); - - $updateTotalDmDetailsData = $updateDmDetailsData[0]; - $updateDmDetailsData = $updateDmDetailsData[1]; - - $updatesDmR = []; - $insertsDmR = []; - $updatesTotalDmR = []; - $insertsTotalDmR = []; - - // Fetch existing records in bulk for diesel machine details - $dates = array_column($updateDmDetailsData, 'date'); - $machineIds = array_column($updateDmDetailsData, 'machine_id'); - $existingDmRecords = $this->factoryVehicleDieselDetails_model - ->whereIn('date', $dates) - ->whereIn('machine_id', $machineIds) - ->findAll(); - - $existingDmMap = []; - foreach ($existingDmRecords as $record) { - $existingDmMap [$record['date']] [$record['machine_id']] = $record; - } - - foreach ($updateDmDetailsData as $data) { - $date = $data['date']; - $machineId = $data['machine_id']; - - $dbData = [ - 'date' => $data['date'], - 'machine_id' => $data['machine_id'], - 'opening_reading' => $data['opening_reading'], - 'closing_reading' => $data['closing_reading'], - 'filling_diesel' => $data['filling_diesel'], - 'consumption' => $data['consumption'], - 'running_hours' => $data['running_hours'], - 'mileage' => $data['mileage'] - ]; - - if (isset($existingDmMap[$date][$machineId])) { - $dbData['id'] = $existingDmMap[$date][$machineId]['id']; - $updatesDmR[] = $dbData; - } else { - $insertsDmR[] = $dbData; - } - } - - // Fetch existing records in bulk for diesel stock summary - $dates = array_column($updateTotalDmDetailsData, 'date'); - $existingTotalDmRecords = $this->factoryVehicleDieselStockSummary_model - ->whereIn('date', $dates) - ->findAll(); - - $existingTotalDmMap = []; - foreach ($existingTotalDmRecords as $record) { - $existingTotalDmMap[$record['date']] = $record; - } - - foreach ($updateTotalDmDetailsData as $data) { - $date = $data['date']; - - $dbData = [ - 'date' => $data['date'], - 'opening_stock' => $data['opening_stock'], - 'purchase_diesel' => $data['purchase_diesel'], - 'total_filling_diesel' => $data['total_filling_diesel'], - 'balance_stock' => $data['balance_stock'] - ]; - - if (isset($existingTotalDmMap[$date])) { - $dbData['id'] = $existingTotalDmMap[$date]['id']; - $updatesTotalDmR[] = $dbData; - } else { - $insertsTotalDmR[] = $dbData; - } - } - - // Start the transaction - $this->db->transBegin(); - - try { - if (!empty($insertsDmR)) { - $this->factoryVehicleDieselDetails_model->insertBatch($insertsDmR); - } - - if (!empty($updatesDmR)) { - $this->factoryVehicleDieselDetails_model->updateBatch($updatesDmR, 'id'); - } - - if (!empty($insertsTotalDmR)) { - $this->factoryVehicleDieselStockSummary_model->insertBatch($insertsTotalDmR); - } - - if (!empty($updatesTotalDmR)) { - $this->factoryVehicleDieselStockSummary_model->updateBatch($updatesTotalDmR, 'id'); - } - - // Commit the transaction if all operations are successful - $this->db->transCommit(); - echo "Data Saved Successfully"; - - } catch (\Exception $error) { - // Rollback the transaction in case of any errors - $this->db->transRollback(); - echo "An error occurred: " . $error->getMessage(); - } - } - - - //power stock details - public function powerConsumptionDetails(){ - - - if ($this->request->getMethod() === 'POST') { - - $month = $this->request->getPost('month'); - - $date = DateTime::createFromFormat('d-M-Y', '01-'.$month); //in M-Y format - - $formattedDate = $date->format('Y-m'); //in Y-m format - - $month = $formattedDate; - - $session = session (); - - $session->set('stock_month',$month); - - - } else { - - $session = session(); - - $month = $session->get('stock_month'); - - if (empty($month)) { - $month = date('Y-m'); // Default to the current month - } - } - - $data = []; - - $data['month'] = $month; - - $this->global['pageTitle'] = 'Power Consumption Stock Details'; - - - //filter part starts - - //start date dynamic from front-end - $startDate = "$month-01"; - //end date of given month - $endDate = date("Y-m-t", strtotime($startDate)); + $data['groupedDieselMachineStockDetails'] = $this->groupAndSortStockDetails( + $data['dieselMachineStockDetails'], + $customisedMachineCodes + ); + - //filter applied currently - $customisedMachineCodes = $this->request->getPost('customisedMachineCodes') ?? []; + if (!empty($customisedMachineCodes)) { + $dieselMachines = $this->sortMachinesByCustomOrder($dieselMachines, $customisedMachineCodes); + } + + $data['dieselMachinesCount'] = $dieselMachinesCount; + $data['dieselMachines'] = $dieselMachines; + $data['month'] = DateTime::createFromFormat('Y-m-d', "$month-01")->format('M-Y'); + + return $this->loadViews("stock/dieselStockDetails", $this->global, $data, NULL); + } + - //already applied filter - $existingCustomMachineCodes = $this->monthWiseMachineInStockModel - ->select('machine_id') - ->where('date',"$month-01") - ->where('machine_category','electric') - ->findAll(); + //updateDieselMachineDetails + + public function updateDieselMachineDetails() { + + $postData = $this->request->getPost(); + $updateDmDetailsData = json_decode($postData['updateDieselMachineDetails'], true); + + $updateTotalDmDetailsData = $updateDmDetailsData[0]; + $updateDmDetailsData = $updateDmDetailsData[1]; + + $updatesDmR = []; + $insertsDmR = []; + $updatesTotalDmR = []; + $insertsTotalDmR = []; + + // Fetch existing records in bulk for diesel machine details + $dates = array_column($updateDmDetailsData, 'date'); + $machineIds = array_column($updateDmDetailsData, 'machine_id'); + $existingDmRecords = $this->factoryVehicleDieselDetails_model + ->whereIn('date', $dates) + ->whereIn('machine_id', $machineIds) + ->findAll(); + + $existingDmMap = []; + foreach ($existingDmRecords as $record) { + $existingDmMap [$record['date']] [$record['machine_id']] = $record; + } + + foreach ($updateDmDetailsData as $data) { + $date = $data['date']; + $machineId = $data['machine_id']; + + $dbData = [ + 'date' => $data['date'], + 'machine_id' => $data['machine_id'], + 'opening_reading' => $data['opening_reading'], + 'closing_reading' => $data['closing_reading'], + 'filling_diesel' => $data['filling_diesel'], + 'consumption' => $data['consumption'], + 'running_hours' => $data['running_hours'], + 'mileage' => $data['mileage'] + ]; + + if (isset($existingDmMap[$date][$machineId])) { + $dbData['id'] = $existingDmMap[$date][$machineId]['id']; + $updatesDmR[] = $dbData; + } else { + $insertsDmR[] = $dbData; + } + } + + // Fetch existing records in bulk for diesel stock summary + $dates = array_column($updateTotalDmDetailsData, 'date'); + $existingTotalDmRecords = $this->factoryVehicleDieselStockSummary_model + ->whereIn('date', $dates) + ->findAll(); + + $existingTotalDmMap = []; + foreach ($existingTotalDmRecords as $record) { + $existingTotalDmMap[$record['date']] = $record; + } + + foreach ($updateTotalDmDetailsData as $data) { + $date = $data['date']; + + $dbData = [ + 'date' => $data['date'], + 'opening_stock' => $data['opening_stock'], + 'purchase_diesel' => $data['purchase_diesel'], + 'total_filling_diesel' => $data['total_filling_diesel'], + 'balance_stock' => $data['balance_stock'] + ]; + + if (isset($existingTotalDmMap[$date])) { + $dbData['id'] = $existingTotalDmMap[$date]['id']; + $updatesTotalDmR[] = $dbData; + } else { + $insertsTotalDmR[] = $dbData; + } + } + + // Start the transaction + $this->db->transBegin(); + + try { + if (!empty($insertsDmR)) { + $this->factoryVehicleDieselDetails_model->insertBatch($insertsDmR); + } + + if (!empty($updatesDmR)) { + $this->factoryVehicleDieselDetails_model->updateBatch($updatesDmR, 'id'); + } + + if (!empty($insertsTotalDmR)) { + $this->factoryVehicleDieselStockSummary_model->insertBatch($insertsTotalDmR); + } + + if (!empty($updatesTotalDmR)) { + $this->factoryVehicleDieselStockSummary_model->updateBatch($updatesTotalDmR, 'id'); + } + + // Commit the transaction if all operations are successful + $this->db->transCommit(); + echo "Data Saved Successfully"; + + } catch (\Exception $error) { + // Rollback the transaction in case of any errors + $this->db->transRollback(); + echo "An error occurred: " . $error->getMessage(); + } + } - $filterUpdateNeeded = true ; + + //power stock details + + public function powerConsumptionDetails(){ + + + $month = getStockMonth($this->request); + + + $data = []; + + $data['month'] = $month; + + $this->global['pageTitle'] = 'Power Consumption Stock Details'; - if( empty($customisedMachineCodes) && !empty($existingCustomMachineCodes)){ - $customisedMachineCodes = array_column($existingCustomMachineCodes, 'machine_id') ; - $filterUpdateNeeded = false ; - } - + + //filter part starts + + //start date dynamic from front-end + $startDate = "$month-01"; + //end date of given month + $endDate = date("Y-m-t", strtotime($startDate)); + + + //filter applied currently + $customisedMachineCodes = $this->request->getPost('customisedMachineCodes') ?? []; + + + //already applied filter + $existingCustomMachineCodes = $this->monthWiseMachineInStockModel + ->select('machine_id') + ->where('date',"$month-01") + ->where('machine_category','electric') + ->findAll(); + + $filterUpdateNeeded = true ; + + if( empty($customisedMachineCodes) && !empty($existingCustomMachineCodes)){ + + $customisedMachineCodes = array_column($existingCustomMachineCodes, 'machine_id') ; + $filterUpdateNeeded = false ; + + } + + + //check user applies for filter currently + if(!empty($customisedMachineCodes) && $filterUpdateNeeded){ + + //user applied filter, - //check user applies for filter currently - if(!empty($customisedMachineCodes) && $filterUpdateNeeded){ + //check already filter existing , if exists remove that , + if(!empty($existingCustomMachineCodes)){ - //user applied filter, - - //check already filter existing , if exists remove that , - if(!empty($existingCustomMachineCodes)){ + //hard delete done..!! + $existingCustomMachineCodes = $this->monthWiseMachineInStockModel + ->where('date',"$month-01") + ->where('machine_category','electric') + ->delete(); - //hard delete done..!! - $existingCustomMachineCodes = $this->monthWiseMachineInStockModel - ->where('date',"$month-01") - ->where('machine_category','electric') - ->delete(); - - } - - - //if no filter already exists or removed current one , just add current filter for that month ....!! - $inserts = []; - - foreach($customisedMachineCodes as $index => $customisedMachineCode){ - - $inserts [] = [ - 'date' => "$month-01", - 'machine_category' => "electric", - 'machine_id' => $customisedMachineCode - ]; - - } - - if(!empty($inserts)){ - //insert all the latest applied filter - $this->monthWiseMachineInStockModel->insertBatch($inserts); - - //get the currently applied filter - $existingCustomMachineCodes = $this->monthWiseMachineInStockModel - ->select('machine_id') - ->where('date',"$month-01") - ->where('machine_category','electric') - ->get() - ->getResultArray(); - - } - } - - //possible if no filter applied at all...!!! - if(empty($existingCustomMachineCodes) ){ - //no filter applied at all just present previous month material codes - - $previousMonth = date('Y-m-01', strtotime('-1 month', strtotime("$month-01"))); - - $previousMonthCustomMachineCodes = $this->monthWiseMachineInStockModel - ->select('machine_id') - ->where('date',"$previousMonth") - ->where('machine_category','electric') - ->get() - ->getResultArray(); - - if(!empty($previousMonthCustomMachineCodes)){ - $existingCustomMachineCodes = $this->factoryMachine_model - ->getSelectedDieselMachines(array_column($previousMonthCustomMachineCodes, 'machine_id')); - }else{ - - // inserting all active if no previous month present - $existingCustomMachineCodes = $this->factoryMachine_model - ->getAllActiveElectricMachines(); - - - //if no filter exists , just add current filter for that month ....!! + //if no filter already exists or removed current one , just add current filter for that month ....!! $inserts = []; - foreach($existingCustomMachineCodes as $index => $customisedMachineCode){ + foreach($customisedMachineCodes as $index => $customisedMachineCode){ $inserts [] = [ 'date' => "$month-01", 'machine_category' => "electric", - 'machine_id' => $customisedMachineCode['id'] + 'machine_id' => $customisedMachineCode ]; } @@ -1876,179 +1179,202 @@ class StockController extends BaseController if(!empty($inserts)){ //insert all the latest applied filter $this->monthWiseMachineInStockModel->insertBatch($inserts); + + //get the currently applied filter + $existingCustomMachineCodes = $this->monthWiseMachineInStockModel + ->select('machine_id') + ->where('date',"$month-01") + ->where('machine_category','electric') + ->get() + ->getResultArray(); } - } - - - }else{ - //if filter present,get that material codes - $existingCustomMachineCodes = $this->factoryMachine_model - ->getSelectedElectricMachines(array_column($existingCustomMachineCodes, 'machine_id')); - } - - - - - //this existingCustomMachineCodes gets its machine after visiting factory machine master table - $machineCodeList = array_column($existingCustomMachineCodes, 'id'); - - $currentDate = new DateTime(); - - - if($startDate == $currentDate->format('Y-m-01') && $endDate == $currentDate->format('Y-m-t')){ - - foreach($machineCodeList as $index => $machineCode){ - - //checking filtered material code present in table , if not create dummy one for whole month - $findMachineCode = $this->powerConsumptionDetails_model - ->where('date >=', $startDate) - ->where('date <=', $endDate) - ->where('machine_id',$machineCode) - ->findAll(); - - //check any material code is not present in stock table but applied in filter - if(empty($findMachineCode)){ - //create dummy entry for this - $this->createDummyEntryForElectricMachine($machineCode,$startDate,$endDate); - } - - } - } + } - + + //possible if no filter applied at all...!!! + if(empty($existingCustomMachineCodes) ){ - $electricMachines = $existingCustomMachineCodes; + //no filter applied at all just present previous month material codes - $data['activeElectricMachines'] = $this->factoryMachine_model->getAllActiveElectricMachines(); + $previousMonth = date('Y-m-01', strtotime('-1 month', strtotime("$month-01"))); + + $previousMonthCustomMachineCodes = $this->monthWiseMachineInStockModel + ->select('machine_id') + ->where('date',"$previousMonth") + ->where('machine_category','electric') + ->get() + ->getResultArray(); + if(!empty($previousMonthCustomMachineCodes)){ + $existingCustomMachineCodes = $this->factoryMachine_model + ->getSelectedDieselMachines(array_column($previousMonthCustomMachineCodes, 'machine_id')); + }else{ + // inserting all active if no previous month present + $existingCustomMachineCodes = $this->factoryMachine_model + ->getAllActiveElectricMachines(); + + //if no filter exists , just add current filter for that month ....!! + $inserts = []; + foreach($existingCustomMachineCodes as $index => $customisedMachineCode){ - - - - - - // Get the previous month's last date power consumption stock details for next month updation - - $previousMonth = DateTime::createFromFormat('Y-m-d', $month.'-01')->modify('-1 month')->format('Y-m'); - $previousMonthStartDate = "$previousMonth-01"; - $previousMonthEndDate = date("Y-m-t", strtotime($previousMonthStartDate)); - - $data['previousMonthPowerConsumptionStockDetails'] = $this->powerConsumptionDetails_model - ->select(['machine_id', 'date', 'closing_units']) - ->distinct() - ->where('date =', $previousMonthEndDate) - ->groupBy(['machine_id', 'date']) - ->orderBy('date', 'desc') - ->orderBy('machine_id', 'asc') - ->findAll(); - - $data['previousMonthTotalPowerMachineStockDetails'] = $this->powerConsumptionSummary_model - ->select(['id', 'date', 'final_reading']) - ->distinct() - ->where('date =', $previousMonthEndDate) - ->groupBy(['id', 'date']) - ->orderBy('date', 'desc') - ->findAll(); - - - - // checking in database if the data is available for the month - - - - $data['powerConsumptionStockDetails'] = $this->powerConsumptionDetails_model - ->where('date >=', $startDate) - ->where('date <=', $endDate) - ->whereIn('machine_id',$machineCodeList) - ->groupBy(['machine_id', 'date']) - ->orderBy('date', 'asc') - ->orderBy('machine_id', 'asc') - ->findAll(); - - $data['totalPower'] = $this->powerConsumptionSummary_model - ->where('date >=', $startDate) - ->where('date <=', $endDate) - ->orderBy('date', 'asc') - ->findAll(); - - // Initialize an empty array to hold the grouped data - $data['groupedPowerConsumptionStockDetails'] = []; - - // Temporary array to store grouped data by date - $groupedByDate = []; - - // Group by 'date' - foreach ($data['powerConsumptionStockDetails'] as $detail) { - $date = $detail['date']; - - // Initialize the outer array for this date if it doesn't exist - if (!isset($groupedByDate[$date])) { - $groupedByDate[$date] = []; - } - - /******************************************************************************************************************* - creating an sub array (inner array) for date wise and append the detail into an array as sub-array - - $groupedByDate[] outer array - - $groupedByDate[$date] - will look like [[material1],[material2],[material3],[material4],[material5]] inner array - - the above process is done for single row (date wise) and the same process is repeated for all the rows - *******************************************************************************************************************/ - - $groupedByDate[$date][] = $detail; - } - - - // Sort each date's machines based on the custom order to set table body td - if (!empty($customisedMachineCodes)) { - - foreach ($groupedByDate as $date => &$machines) { - - usort($machines, function ($a, $b) use ($customisedMachineCodes) { - - $indexA = array_search($a['machine_id'], $customisedMachineCodes); - $indexB = array_search($b['machine_id'], $customisedMachineCodes); - - if ($indexA === false && $indexB === false) { - return 0; - } - if ($indexA === false) { - return 1; - } - if ($indexB === false) { - return -1; - } - - return $indexA - $indexB; - }); - } - unset($machines); - } - - // Reset the structure to have indexed arrays without the date keys - $data['groupedPowerConsumptionStockDetails'] = array_values($groupedByDate); - - - // Sort each date's machines based on the custom order to set table header th - - if (!empty($customisedMachineCodes)) { - - - - usort($electricMachines, function ($a, $b) use ($customisedMachineCodes) { - - $indexA = array_search($a['id'], $customisedMachineCodes); - $indexB = array_search($b['id'], $customisedMachineCodes); + $inserts [] = [ + 'date' => "$month-01", + 'machine_category' => "electric", + 'machine_id' => $customisedMachineCode['id'] + ]; + } + + if(!empty($inserts)){ + //insert all the latest applied filter + $this->monthWiseMachineInStockModel->insertBatch($inserts); + + } + } + + + }else{ + //if filter present,get that material codes + $existingCustomMachineCodes = $this->factoryMachine_model + ->getSelectedElectricMachines(array_column($existingCustomMachineCodes, 'machine_id')); + } + + + + + //this existingCustomMachineCodes gets its machine after visiting factory machine master table + $machineCodeList = array_column($existingCustomMachineCodes, 'id'); + + $currentDate = new DateTime(); + + + if($startDate == $currentDate->format('Y-m-01') && $endDate == $currentDate->format('Y-m-t')){ + + foreach($machineCodeList as $index => $machineCode){ + + //checking filtered material code present in table , if not create dummy one for whole month + $findMachineCode = $this->powerConsumptionDetails_model + ->where('date >=', $startDate) + ->where('date <=', $endDate) + ->where('machine_id',$machineCode) + ->findAll(); + + + //check any material code is not present in stock table but applied in filter + if(empty($findMachineCode)){ + //create dummy entry for this + $this->createDummyEntryForElectricMachine($machineCode,$startDate,$endDate); + } + + } + } + + + + $electricMachines = $existingCustomMachineCodes; + + $data['activeElectricMachines'] = $this->factoryMachine_model->getAllActiveElectricMachines(); + + + + + + + + + + + // Get the previous month's last date power consumption stock details for next month updation + + $previousMonth = DateTime::createFromFormat('Y-m-d', $month.'-01')->modify('-1 month')->format('Y-m'); + $previousMonthStartDate = "$previousMonth-01"; + $previousMonthEndDate = date("Y-m-t", strtotime($previousMonthStartDate)); + + $data['previousMonthPowerConsumptionStockDetails'] = $this->powerConsumptionDetails_model + ->select(['machine_id', 'date', 'closing_units']) + ->distinct() + ->where('date =', $previousMonthEndDate) + ->groupBy(['machine_id', 'date']) + ->orderBy('date', 'desc') + ->orderBy('machine_id', 'asc') + ->findAll(); + + $data['previousMonthTotalPowerMachineStockDetails'] = $this->powerConsumptionSummary_model + ->select(['id', 'date', 'final_reading']) + ->distinct() + ->where('date =', $previousMonthEndDate) + ->groupBy(['id', 'date']) + ->orderBy('date', 'desc') + ->findAll(); + + + + // checking in database if the data is available for the month + + + + $data['powerConsumptionStockDetails'] = $this->powerConsumptionDetails_model + ->where('date >=', $startDate) + ->where('date <=', $endDate) + ->whereIn('machine_id',$machineCodeList) + ->groupBy(['machine_id', 'date']) + ->orderBy('date', 'asc') + ->orderBy('machine_id', 'asc') + ->findAll(); + + $data['totalPower'] = $this->powerConsumptionSummary_model + ->where('date >=', $startDate) + ->where('date <=', $endDate) + ->orderBy('date', 'asc') + ->findAll(); + + // Initialize an empty array to hold the grouped data + $data['groupedPowerConsumptionStockDetails'] = []; + + // Temporary array to store grouped data by date + $groupedByDate = []; + + // Group by 'date' + foreach ($data['powerConsumptionStockDetails'] as $detail) { + $date = $detail['date']; + + // Initialize the outer array for this date if it doesn't exist + if (!isset($groupedByDate[$date])) { + $groupedByDate[$date] = []; + } + + /******************************************************************************************************************* + creating an sub array (inner array) for date wise and append the detail into an array as sub-array + + $groupedByDate[] outer array + + $groupedByDate[$date] + will look like [[material1],[material2],[material3],[material4],[material5]] inner array + + the above process is done for single row (date wise) and the same process is repeated for all the rows + *******************************************************************************************************************/ + + $groupedByDate[$date][] = $detail; + } + + + // Sort each date's machines based on the custom order to set table body td + if (!empty($customisedMachineCodes)) { + + foreach ($groupedByDate as $date => &$machines) { + + usort($machines, function ($a, $b) use ($customisedMachineCodes) { + + $indexA = array_search($a['machine_id'], $customisedMachineCodes); + $indexB = array_search($b['machine_id'], $customisedMachineCodes); + if ($indexA === false && $indexB === false) { - return 0; + return 0; } if ($indexA === false) { return 1; @@ -2056,555 +1382,504 @@ class StockController extends BaseController if ($indexB === false) { return -1; } - + return $indexA - $indexB; }); - } - - $electricMachinesCount = count($electricMachines); - - $data['electricMachinesCount'] = $electricMachinesCount; - $data['electricMachines'] = $electricMachines; - - $date = DateTime::createFromFormat('Y-m-d', $month.'-01'); - - $formattedDate = $date->format('M-Y'); - - $data['month'] = $formattedDate; - - // return $this->response->setJSON(['status' =>'success' ,'message' => $data['electricMachines']]); - - return $this->loadViews("stock/powerConsumptionDetails", $this->global, $data, NULL); - + unset($machines); } - public function updatePowerConsumptionDetails(){ + // Reset the structure to have indexed arrays without the date keys + $data['groupedPowerConsumptionStockDetails'] = array_values($groupedByDate); - //pm stands for power machine + + // Sort each date's machines based on the custom order to set table header th + + if (!empty($customisedMachineCodes)) { + + + + usort($electricMachines, function ($a, $b) use ($customisedMachineCodes) { + + $indexA = array_search($a['id'], $customisedMachineCodes); + $indexB = array_search($b['id'], $customisedMachineCodes); - - $postData = $this->request->getPost(); - - $updatePowerConsumptionDetailsData = json_decode($postData['updatePowerConsumptionDetails'], true); - - $updateTotalPmDetailsData = $updatePowerConsumptionDetailsData[0]; - $updatePmDetailsData = $updatePowerConsumptionDetailsData[1]; - - //PmR stands for power machine readings - - $updatesPmR = []; - $insertsPmR = []; - - $updatesTotalPmR = []; - $insertsTotalPmR = []; - - // Fetch existing records in bulk for power machine details - $dates = array_column($updatePmDetailsData, 'date'); - $machineIds = array_column($updatePmDetailsData, 'machine_id'); - $existingPmRecords = $this->powerConsumptionDetails_model - ->whereIn('date', $dates) - ->whereIn('machine_id', $machineIds) - ->findAll(); - - $existingPmMap = []; - foreach ($existingPmRecords as $record) { - $existingPmMap[$record['date']][$record['machine_id']] = $record; - } - - foreach ($updatePmDetailsData as $data) { - $date = $data['date']; - $machineId = $data['machine_id']; - - $dbData = [ - 'date' => $data['date'], - 'machine_id' => $data['machine_id'], - 'opening_units' => $data['opening_units'], - 'closing_units' => $data['closing_units'], - 'total_units' => $data['total_units'], - ]; - - if (isset($existingPmMap[$date][$machineId])) { - $dbData['id'] = $existingPmMap[$date][$machineId]['id']; - $updatesPmR[] = $dbData; - } else { - $insertsPmR[] = $dbData; - } - } - - // Fetch existing records in bulk for power stock summary - $dates = array_column($updateTotalPmDetailsData, 'date'); - $existingTotalPmRecords = $this->powerConsumptionSummary_model - ->whereIn('date', $dates) - ->findAll(); - - $existingTotalPmMap = []; - foreach ($existingTotalPmRecords as $record) { - $existingTotalPmMap[$record['date']] = $record; - } - - foreach ($updateTotalPmDetailsData as $data) { - $date = $data['date']; - - $dbData = [ - 'date' => $data['date'], - 'opening_reading' => $data['opening_reading'], - 'final_reading' => $data['final_reading'], - 'total_reading' => $data['total_reading'], - 'total_units' => $data['total_units'], - 'average_pf' => $data['average_pf'], - 'present_pf' => $data['present_pf'], - 'md' => $data['md'], - 'mf' => $data['mf'] - ]; - - if (isset($existingTotalPmMap[$date])) { - $dbData['id'] = $existingTotalPmMap[$date]['id']; - $updatesTotalPmR[] = $dbData; - } else { - $insertsTotalPmR[] = $dbData; - } - } - - // Start the transaction - $this->db->transBegin(); - - try { - if (!empty($insertsPmR)) { - $this->powerConsumptionDetails_model->insertBatch($insertsPmR); - } - - if (!empty($updatesPmR)) { - $this->powerConsumptionDetails_model->updateBatch($updatesPmR, 'id'); - } - - if (!empty($insertsTotalPmR)) { - $this->powerConsumptionSummary_model->insertBatch($insertsTotalPmR); - } - - if (!empty($updatesTotalPmR)) { - $this->powerConsumptionSummary_model->updateBatch($updatesTotalPmR, 'id'); - } - - // Commit the transaction if all operations are successful - $this->db->transCommit(); - echo "Data Saved Successfully"; - - } catch (\Exception $error) { - // Rollback the transaction in case of any errors - $this->db->transRollback(); - echo "An error occurred: " . $error->getMessage(); - } - - } - - - //Dust And Rough Stock Details - public function loadView_dustAndRoughStockDetails() - { - - if ($this->request->getMethod() === 'POST') { - $month = $this->request->getPost('month'); - - $date = DateTime::createFromFormat('d-M-Y', '01-'.$month); - - $formattedDate = $date->format('Y-m'); - - $month = $formattedDate; - - $session = session (); - - $session->set('stock_month',$month); - - } else { - $session = session(); - - $month = $session->get('stock_month'); - - if (empty($month)) { - $month = date('Y-m'); // Default to the current month + if ($indexA === false && $indexB === false) { + return 0; } + if ($indexA === false) { + return 1; + } + if ($indexB === false) { + return -1; + } + + return $indexA - $indexB; + }); + + } + + $electricMachinesCount = count($electricMachines); + + $data['electricMachinesCount'] = $electricMachinesCount; + $data['electricMachines'] = $electricMachines; + + $date = DateTime::createFromFormat('Y-m-d', $month.'-01'); + + $formattedDate = $date->format('M-Y'); + + $data['month'] = $formattedDate; + + // return $this->response->setJSON(['status' =>'success' ,'message' => $data['electricMachines']]); + + return $this->loadViews("stock/powerConsumptionDetails", $this->global, $data, NULL); + + } + //updatePowerConsumptionDetails + + public function updatePowerConsumptionDetails(){ + + //pm stands for power machine + + + $postData = $this->request->getPost(); + + $updatePowerConsumptionDetailsData = json_decode($postData['updatePowerConsumptionDetails'], true); + + $updateTotalPmDetailsData = $updatePowerConsumptionDetailsData[0]; + $updatePmDetailsData = $updatePowerConsumptionDetailsData[1]; + + //PmR stands for power machine readings + + $updatesPmR = []; + $insertsPmR = []; + + $updatesTotalPmR = []; + $insertsTotalPmR = []; + + // Fetch existing records in bulk for power machine details + $dates = array_column($updatePmDetailsData, 'date'); + $machineIds = array_column($updatePmDetailsData, 'machine_id'); + $existingPmRecords = $this->powerConsumptionDetails_model + ->whereIn('date', $dates) + ->whereIn('machine_id', $machineIds) + ->findAll(); + + $existingPmMap = []; + foreach ($existingPmRecords as $record) { + $existingPmMap[$record['date']][$record['machine_id']] = $record; + } + + foreach ($updatePmDetailsData as $data) { + $date = $data['date']; + $machineId = $data['machine_id']; + + $dbData = [ + 'date' => $data['date'], + 'machine_id' => $data['machine_id'], + 'opening_units' => $data['opening_units'], + 'closing_units' => $data['closing_units'], + 'total_units' => $data['total_units'], + ]; + + if (isset($existingPmMap[$date][$machineId])) { + $dbData['id'] = $existingPmMap[$date][$machineId]['id']; + $updatesPmR[] = $dbData; + } else { + $insertsPmR[] = $dbData; + } + } + + // Fetch existing records in bulk for power stock summary + $dates = array_column($updateTotalPmDetailsData, 'date'); + $existingTotalPmRecords = $this->powerConsumptionSummary_model + ->whereIn('date', $dates) + ->findAll(); + + $existingTotalPmMap = []; + foreach ($existingTotalPmRecords as $record) { + $existingTotalPmMap[$record['date']] = $record; + } + + foreach ($updateTotalPmDetailsData as $data) { + $date = $data['date']; + + $dbData = [ + 'date' => $data['date'], + 'opening_reading' => $data['opening_reading'], + 'final_reading' => $data['final_reading'], + 'total_reading' => $data['total_reading'], + 'total_units' => $data['total_units'], + 'average_pf' => $data['average_pf'], + 'present_pf' => $data['present_pf'], + 'md' => $data['md'], + 'mf' => $data['mf'] + ]; + + if (isset($existingTotalPmMap[$date])) { + $dbData['id'] = $existingTotalPmMap[$date]['id']; + $updatesTotalPmR[] = $dbData; + } else { + $insertsTotalPmR[] = $dbData; + } + } + + // Start the transaction + $this->db->transBegin(); + + try { + if (!empty($insertsPmR)) { + $this->powerConsumptionDetails_model->insertBatch($insertsPmR); + } + + if (!empty($updatesPmR)) { + $this->powerConsumptionDetails_model->updateBatch($updatesPmR, 'id'); + } + + if (!empty($insertsTotalPmR)) { + $this->powerConsumptionSummary_model->insertBatch($insertsTotalPmR); + } + + if (!empty($updatesTotalPmR)) { + $this->powerConsumptionSummary_model->updateBatch($updatesTotalPmR, 'id'); + } + + // Commit the transaction if all operations are successful + $this->db->transCommit(); + echo "Data Saved Successfully"; + + } catch (\Exception $error) { + // Rollback the transaction in case of any errors + $this->db->transRollback(); + echo "An error occurred: " . $error->getMessage(); + } + + } + + //Dust And Rough Stock Details + + public function loadView_dustAndRoughStockDetails() + { + + $month = getStockMonth($this->request); + + + $data = []; + + $data['month'] = $month; + + $this->global['pageTitle'] = 'Dust And Rough Stock Details'; + + $startDate = "$month-01"; + $endDate = date("Y-m-t", strtotime($startDate)); + $data['dustAndRoughStockDetails'] = $this->dustAndRoughStockDetails_model + ->where('date >=', $startDate) + ->where('date <=', $endDate) + ->orderBy('date', 'asc') + ->findAll(); + + $date = DateTime::createFromFormat('Y-m-d', $month.'-01'); + + $formattedDate = $date->format('M-Y'); + + $data['month'] = $formattedDate; + + return $this->loadViews("stock/dustAndRoughStockDetails", $this->global, $data, NULL); + } + + //updateDustAndRoughStockDetails + + public function updateDustAndRoughStockDetails() + { + + $postData = $this->request->getPost(); + + $updateDustAndRoughStockDetailsData = json_decode($postData['updateDustAndRoughStockDetails'], true); + + $updates = []; + + $inserts = []; + + foreach ($updateDustAndRoughStockDetailsData as $data) { + + $data['date'] = DateTime::createFromFormat('d-m-Y', $data['date'])->format('Y-m-d'); + + $date = $data['date']; + + $dbData = [ + 'date' => $data['date'], + 'finalRough' => $data['finalRough'], + 'dust' => $data['dust'], + 'total' => $data['total'] + ]; + + $resultExists = $this->dustAndRoughStockDetails_model + ->where('date', $date) + ->first(); + + + if (empty($resultExists)) { + $inserts[] = $dbData; + } else { + $updates[] = $dbData; } + } - $data = []; + if (!empty($inserts)) { + $this->dustAndRoughStockDetails_model->insertBatch($inserts); + } - $data['month'] = $month; + if (!empty($updates)) { - $this->global['pageTitle'] = 'Dust And Rough Stock Details'; + $updateResult = $this->dustAndRoughStockDetails_model->updateBatch($updates, 'date'); - $startDate = "$month-01"; - $endDate = date("Y-m-t", strtotime($startDate)); - $data['dustAndRoughStockDetails'] = $this->dustAndRoughStockDetails_model - ->where('date >=', $startDate) - ->where('date <=', $endDate) - ->orderBy('date', 'asc') + if ($updateResult === FALSE) { + echo "Error during update"; + } else { + echo "Data Updated Successfully"; + return; + } + } + + echo "Data Saved Successfully"; + } + + + //Resin Stock Details + + public function loadView_resinStockDetails() + { + + $month = getStockMonth($this->request); + + + $data = []; + + $data['month'] = $month; + + $this->global['pageTitle'] = 'Resin Stock Details'; + + $startDate = "$month-01"; + $endDate = date("Y-m-t", strtotime($startDate)); + + + + $customisedMaterialCodes = $this->request->getPost('customisedMaterialCodes') ?? []; + + $existingCustomMaterialCodes = $this->monthWiseMaterialInStockModel + ->select('materialCode') + ->where('date',"$month-01") + ->where('stock_category','resin') ->findAll(); - $date = DateTime::createFromFormat('Y-m-d', $month.'-01'); - - $formattedDate = $date->format('M-Y'); - - $data['month'] = $formattedDate; - - return $this->loadViews("stock/dustAndRoughStockDetails", $this->global, $data, NULL); - } - + $filterUpdateNeeded = true ; - public function updateDustAndRoughStockDetails() - { + if( empty($customisedMaterialCodes) && !empty($existingCustomMaterialCodes)){ + $customisedMaterialCodes = array_column($existingCustomMaterialCodes, 'materialCode') ; + $filterUpdateNeeded = false ; - $postData = $this->request->getPost(); - - $updateDustAndRoughStockDetailsData = json_decode($postData['updateDustAndRoughStockDetails'], true); - - $updates = []; - - $inserts = []; - - foreach ($updateDustAndRoughStockDetailsData as $data) { - - $data['date'] = DateTime::createFromFormat('d-m-Y', $data['date'])->format('Y-m-d'); - - $date = $data['date']; - - $dbData = [ - 'date' => $data['date'], - 'finalRough' => $data['finalRough'], - 'dust' => $data['dust'], - 'total' => $data['total'] - ]; - - $resultExists = $this->dustAndRoughStockDetails_model - ->where('date', $date) - ->first(); - - - if (empty($resultExists)) { - $inserts[] = $dbData; - } else { - $updates[] = $dbData; - } - } - - if (!empty($inserts)) { - $this->dustAndRoughStockDetails_model->insertBatch($inserts); - } - - if (!empty($updates)) { - - $updateResult = $this->dustAndRoughStockDetails_model->updateBatch($updates, 'date'); - - if ($updateResult === FALSE) { - echo "Error during update"; - } else { - echo "Data Updated Successfully"; - return; - } - } - - echo "Data Saved Successfully"; } + + //check user applies for filter currently + if(!empty($customisedMaterialCodes) && $filterUpdateNeeded){ - //Resin Stock Details - public function loadView_resinStockDetails() - { + //user applied new filter, + + //check already filter existing , if exists remove that , + if(!empty($existingCustomMaterialCodes)){ - if ($this->request->getMethod() === 'POST') { + //hard delete done..!! + $existingCustomMaterialCodes = $this->monthWiseMaterialInStockModel + ->where('date',"$month-01") + ->where('stock_category','resin') + ->delete(); - $month = $this->request->getPost('month'); - - $date = DateTime::createFromFormat('d-M-Y', '01-'.$month); - - $formattedDate = $date->format('Y-m'); - - $month = $formattedDate; - - $session = session (); - - $session->set('stock_month',$month); - - } else { - $session = session(); - - $month = $session->get('stock_month'); - - if (empty($month)) { - $month = date('Y-m'); // Default to the current month - } } - $data = []; - $data['month'] = $month; + //if no filter already exists or removed current one , just add current filter for that month ....!! + $inserts = []; - $this->global['pageTitle'] = 'Resin Stock Details'; + foreach($customisedMaterialCodes as $index => $customisedMaterialCode){ - $startDate = "$month-01"; - $endDate = date("Y-m-t", strtotime($startDate)); + $inserts [] = [ + 'date' => "$month-01", + 'stock_category' => "resin", + 'materialCode' => $customisedMaterialCode + ]; + + } + if(!empty($inserts)){ + //insert all the latest applied filter + $this->monthWiseMaterialInStockModel->insertBatch($inserts); - - $customisedMaterialCodes = $this->request->getPost('customisedMaterialCodes') ?? []; - - $existingCustomMaterialCodes = $this->monthWiseMaterialInStockModel + //get the currently applied filter + $existingCustomMaterialCodes = $this->monthWiseMaterialInStockModel ->select('materialCode') ->where('date',"$month-01") ->where('stock_category','resin') - ->findAll(); - - $filterUpdateNeeded = true ; - - if( empty($customisedMaterialCodes) && !empty($existingCustomMaterialCodes)){ - $customisedMaterialCodes = array_column($existingCustomMaterialCodes, 'materialCode') ; - $filterUpdateNeeded = false ; - - } - - - //check user applies for filter currently - if(!empty($customisedMaterialCodes) && $filterUpdateNeeded){ - - //user applied new filter, - - //check already filter existing , if exists remove that , - if(!empty($existingCustomMaterialCodes)){ - - //hard delete done..!! - $existingCustomMaterialCodes = $this->monthWiseMaterialInStockModel - ->where('date',"$month-01") - ->where('stock_category','resin') - ->delete(); - - } - - - //if no filter already exists or removed current one , just add current filter for that month ....!! - $inserts = []; - - foreach($customisedMaterialCodes as $index => $customisedMaterialCode){ - - $inserts [] = [ - 'date' => "$month-01", - 'stock_category' => "resin", - 'materialCode' => $customisedMaterialCode - ]; - - } - - if(!empty($inserts)){ - //insert all the latest applied filter - $this->monthWiseMaterialInStockModel->insertBatch($inserts); - - //get the currently applied filter - $existingCustomMaterialCodes = $this->monthWiseMaterialInStockModel - ->select('materialCode') - ->where('date',"$month-01") - ->where('stock_category','resin') - ->get()->getResultArray(); - - } - - } - - - //possible if no filter applied at all...!!! - if(empty($existingCustomMaterialCodes)){ - - //no filter applied at all just present previous month material codes - - $previousMonth = date('Y-m-01', strtotime('-1 month', strtotime("$month-01"))); - - $previousMonthCustomMachineCodes = $this->monthWiseMaterialInStockModel - ->select('materialCode') - ->where('date',"$previousMonth") - ->where('stock_category','resin') - ->get() - ->getResultArray(); - - if(!empty($previousMonthCustomMachineCodes)){ - $existingCustomMaterialCodes = $this->rawmaterialdetails_model - ->getSelectedResinMaterialCode(array_column($previousMonthCustomMachineCodes, 'materialCode')); - }else{ - - // inserting all active if no previous month present - $existingCustomMaterialCodes = $this->rawmaterialdetails_model->getAllResinMaterialCode(); - - $inserts = []; - - foreach($existingCustomMaterialCodes as $index => $customisedMaterialCode){ - - $inserts [] = [ - 'date' => "$month-01", - 'stock_category' => "resin", - 'materialCode' => $customisedMaterialCode['MaterialCode'] - ]; - - } - - if(!empty($inserts)){ - //insert all the latest applied filter - $this->monthWiseMaterialInStockModel->insertBatch($inserts) ; - - } - } - - - }else{ - //if filter present , Reuse the filter and get that material codes - $existingCustomMaterialCodes = $this->rawmaterialdetails_model - ->getSelectedResinMaterialCode(array_column($existingCustomMaterialCodes, 'materialCode')); - } - - - $materialCodeList = array_column($existingCustomMaterialCodes, 'MaterialCode'); - - $currentDate = new DateTime(); - - if($startDate == $currentDate->format('Y-m-01') && $endDate == $currentDate->format('Y-m-t')){ - - foreach($materialCodeList as $index => $materialCode){ - - - //checking filtered material code present in table , if not create dummy one for whole month if it is current month - $findMachineCode = $this->resinStockDetails_model - ->where('date >=', $startDate) - ->where('date <=', $endDate) - ->where('materialCode',$materialCode) - ->findAll(); - - - //check any material code is not present in stock table but applied in filter - if(empty($findMachineCode)){ - //create dummy entry for this - $this->createDummyEntryForResin($materialCode,$startDate,$endDate); - } + ->get()->getResultArray(); } - } - - - - $resinMaterials = $existingCustomMaterialCodes ; - - $data['activeResinMaterials'] = $this->rawmaterialdetails_model->getAllResinMaterialCode(); - - - - // Get the previous month's last date resin stock details for next month updation - - $previousMonth = DateTime::createFromFormat('Y-m-d', $month.'-01')->modify('-1 month')->format('Y-m'); - $previousMonthStartDate = "$previousMonth-01"; - $previousMonthEndDate = date("Y-m-t", strtotime($previousMonthStartDate)); - $data['previousMonthResinStockDetails'] = $this->resinStockDetails_model - ->select(['materialCode', 'date', 'balanceStock']) - ->distinct() - ->where('date =', $previousMonthEndDate) - ->groupBy(['materialCode', 'date']) - ->orderBy('date', 'desc') - ->orderBy('materialCode', 'asc') - ->findAll(); - - - - // checking in database if the data is available for the month - - - $data['resinStockDetails'] = $this->resinStockDetails_model + } + + + //possible if no filter applied at all...!!! + if(empty($existingCustomMaterialCodes)){ + + //no filter applied at all just present previous month material codes + + $previousMonth = date('Y-m-01', strtotime('-1 month', strtotime("$month-01"))); + + $previousMonthCustomMachineCodes = $this->monthWiseMaterialInStockModel + ->select('materialCode') + ->where('date',"$previousMonth") + ->where('stock_category','resin') + ->get() + ->getResultArray(); + + if(!empty($previousMonthCustomMachineCodes)){ + $existingCustomMaterialCodes = $this->rawmaterialdetails_model + ->getSelectedResinMaterialCode(array_column($previousMonthCustomMachineCodes, 'materialCode')); + }else{ + + // inserting all active if no previous month present + $existingCustomMaterialCodes = $this->rawmaterialdetails_model->getAllResinMaterialCode(); + + $inserts = []; + + foreach($existingCustomMaterialCodes as $index => $customisedMaterialCode){ + + $inserts [] = [ + 'date' => "$month-01", + 'stock_category' => "resin", + 'materialCode' => $customisedMaterialCode['MaterialCode'] + ]; + + } + + if(!empty($inserts)){ + //insert all the latest applied filter + $this->monthWiseMaterialInStockModel->insertBatch($inserts) ; + + } + } + + + }else{ + //if filter present , Reuse the filter and get that material codes + $existingCustomMaterialCodes = $this->rawmaterialdetails_model + ->getSelectedResinMaterialCode(array_column($existingCustomMaterialCodes, 'materialCode')); + } + + + $materialCodeList = array_column($existingCustomMaterialCodes, 'MaterialCode'); + + $currentDate = new DateTime(); + + if($startDate == $currentDate->format('Y-m-01') && $endDate == $currentDate->format('Y-m-t')){ + + foreach($materialCodeList as $index => $materialCode){ + + + //checking filtered material code present in table , if not create dummy one for whole month if it is current month + $findMachineCode = $this->resinStockDetails_model ->where('date >=', $startDate) ->where('date <=', $endDate) - ->whereIn('materialCode',$materialCodeList) - ->groupBy(['materialCode', 'date']) - ->orderBy('date', 'asc') - ->orderBy('materialCode', 'asc') + ->where('materialCode',$materialCode) ->findAll(); + - // Initialize an empty array to hold the grouped data - $data['groupedResinStockDetails'] = []; - - // Temporary array to store grouped data by date - $groupedByDate = []; - - // Group by 'date' - foreach ($data['resinStockDetails'] as $detail) { - $date = $detail['date']; - - // Initialize the outer array for this date if it doesn't exist - if (!isset($groupedByDate[$date])) { - $groupedByDate[$date] = []; + //check any material code is not present in stock table but applied in filter + if(empty($findMachineCode)){ + //create dummy entry for this + $this->createDummyEntryForResin($materialCode,$startDate,$endDate); } - - /******************************************************************************************************************* - creating an sub array (inner array) for date wise and append the detail into an array as sub-array - - $groupedByDate[] outer array - - $groupedByDate[$date] - will look like [[material1],[material2],[material3],[material4],[material5]] inner array - - the above process is done for single row (date wise) and the same process is repeated for all the rows - *******************************************************************************************************************/ - - $groupedByDate[$date][] = $detail; - } - - // Sort each date's materials based on the custom order to set table body td - if (!empty($customisedMaterialCodes)) { - - foreach ($groupedByDate as $date => &$materials) { - - usort($materials, function ($a, $b) use ($customisedMaterialCodes) { - - $indexA = array_search($a['materialCode'], $customisedMaterialCodes); - $indexB = array_search($b['materialCode'], $customisedMaterialCodes); - - if ($indexA === false && $indexB === false) { - return 0; - } - if ($indexA === false) { - return 1; - } - if ($indexB === false) { - return -1; - } - - return $indexA - $indexB; - }); - } - unset($materials); - } - - // Reset the structure to have indexed arrays without the date keys - - //this is for tbody table data td - $data['groupedResinStockDetails'] = array_values($groupedByDate); - - - // getting customer for creating table headers - // checking already existing stock if yes then get customer from the existing stock - // if not set customer in db , then set '' empty string - - foreach ($resinMaterials as $key => $resinMaterial) { - $materialCode = $resinMaterial['MaterialCode']; - $resinMaterials[$key]['customers'] = $this->resinStockDetails_model - ->select('customer') - ->where('date >=', $startDate) - ->where('date <=', $endDate) - ->where('materialCode', $materialCode) - ->first()['customer'] ?? ''; - } - - // Sort each date's materials based on the custom order to set table header th - if (!empty($customisedMaterialCodes)) { - - usort($resinMaterials, function ($a, $b) use ($customisedMaterialCodes) { - - $indexA = array_search($a['MaterialCode'], $customisedMaterialCodes); - $indexB = array_search($b['MaterialCode'], $customisedMaterialCodes); + } + } + + + + $resinMaterials = $existingCustomMaterialCodes ; + + $data['activeResinMaterials'] = $this->rawmaterialdetails_model->getAllResinMaterialCode(); + + + + // Get the previous month's last date resin stock details for next month updation + + $previousMonth = DateTime::createFromFormat('Y-m-d', $month.'-01')->modify('-1 month')->format('Y-m'); + $previousMonthStartDate = "$previousMonth-01"; + $previousMonthEndDate = date("Y-m-t", strtotime($previousMonthStartDate)); + $data['previousMonthResinStockDetails'] = $this->resinStockDetails_model + ->select(['materialCode', 'date', 'balanceStock']) + ->distinct() + ->where('date =', $previousMonthEndDate) + ->groupBy(['materialCode', 'date']) + ->orderBy('date', 'desc') + ->orderBy('materialCode', 'asc') + ->findAll(); + + + + // checking in database if the data is available for the month + + + + $data['resinStockDetails'] = $this->resinStockDetails_model + ->where('date >=', $startDate) + ->where('date <=', $endDate) + ->whereIn('materialCode',$materialCodeList) + ->groupBy(['materialCode', 'date']) + ->orderBy('date', 'asc') + ->orderBy('materialCode', 'asc') + ->findAll(); + + // Initialize an empty array to hold the grouped data + $data['groupedResinStockDetails'] = []; + + // Temporary array to store grouped data by date + $groupedByDate = []; + + // Group by 'date' + foreach ($data['resinStockDetails'] as $detail) { + $date = $detail['date']; + + // Initialize the outer array for this date if it doesn't exist + if (!isset($groupedByDate[$date])) { + $groupedByDate[$date] = []; + } + + /******************************************************************************************************************* + creating an sub array (inner array) for date wise and append the detail into an array as sub-array + + $groupedByDate[] outer array + + $groupedByDate[$date] + will look like [[material1],[material2],[material3],[material4],[material5]] inner array + + the above process is done for single row (date wise) and the same process is repeated for all the rows + *******************************************************************************************************************/ + + $groupedByDate[$date][] = $detail; + } + + // Sort each date's materials based on the custom order to set table body td + if (!empty($customisedMaterialCodes)) { + + foreach ($groupedByDate as $date => &$materials) { + + usort($materials, function ($a, $b) use ($customisedMaterialCodes) { + + $indexA = array_search($a['materialCode'], $customisedMaterialCodes); + $indexB = array_search($b['materialCode'], $customisedMaterialCodes); + if ($indexA === false && $indexB === false) { - return 0; + return 0; } if ($indexA === false) { return 1; @@ -2612,154 +1887,143 @@ class StockController extends BaseController if ($indexB === false) { return -1; } - + return $indexA - $indexB; }); - } - - - $resinMaterialCount = count($resinMaterials); - - $data['resinMaterialCount'] = $resinMaterialCount; - $data['resinMaterials'] = $resinMaterials; - - $date = DateTime::createFromFormat('Y-m-d', $month.'-01'); - - $formattedDate = $date->format('M-Y'); - - $data['month'] = $formattedDate; - - return $this->loadViews("stock/resinStockDetails", $this->global, $data, NULL); + unset($materials); } + // Reset the structure to have indexed arrays without the date keys + //this is for tbody table data td + $data['groupedResinStockDetails'] = array_values($groupedByDate); + + + // getting customer for creating table headers + // checking already existing stock if yes then get customer from the existing stock + // if not set customer in db , then set '' empty string + + foreach ($resinMaterials as $key => $resinMaterial) { + $materialCode = $resinMaterial['MaterialCode']; + $resinMaterials[$key]['customers'] = $this->resinStockDetails_model + ->select('customer') + ->where('date >=', $startDate) + ->where('date <=', $endDate) + ->where('materialCode', $materialCode) + ->first()['customer'] ?? ''; + } + + // Sort each date's materials based on the custom order to set table header th + if (!empty($customisedMaterialCodes)) { + + usort($resinMaterials, function ($a, $b) use ($customisedMaterialCodes) { + + $indexA = array_search($a['MaterialCode'], $customisedMaterialCodes); + $indexB = array_search($b['MaterialCode'], $customisedMaterialCodes); - public function updateResinStockDetails() - { - $postData = $this->request->getPost('updateResinStockDetails'); - $updateResinStockDetailsData = json_decode($postData, true); + if ($indexA === false && $indexB === false) { + return 0; + } + if ($indexA === false) { + return 1; + } + if ($indexB === false) { + return -1; + } - if (empty($updateResinStockDetailsData)) { - echo "No data provided"; + return $indexA - $indexB; + }); + + } + + + $resinMaterialCount = count($resinMaterials); + + $data['resinMaterialCount'] = $resinMaterialCount; + $data['resinMaterials'] = $resinMaterials; + + $date = DateTime::createFromFormat('Y-m-d', $month.'-01'); + + $formattedDate = $date->format('M-Y'); + + $data['month'] = $formattedDate; + + return $this->loadViews("stock/resinStockDetails", $this->global, $data, NULL); + } + + + // updateResinStockDetails + + public function updateResinStockDetails() + { + $postData = $this->request->getPost('updateResinStockDetails'); + $updateResinStockDetailsData = json_decode($postData, true); + + if (empty($updateResinStockDetailsData)) { + echo "No data provided"; + return; + } + + $inserts = []; + $updates = []; + + $dates = array_column($updateResinStockDetailsData, 'date'); + $materialCodes = array_column($updateResinStockDetailsData, 'materialCode'); + + // Fetch existing records in bulk to reduce queries + $existingRecords = $this->resinStockDetails_model + ->whereIn('date', $dates) + ->whereIn('materialCode', $materialCodes) + ->findAll(); + + $existingMap = []; + foreach ($existingRecords as $record) { + $existingMap[$record['date'] . '_' . $record['materialCode']] = $record['id']; + } + + foreach ($updateResinStockDetailsData as $data) { + + $key = $data['date'] . '_' . $data['materialCode']; + + $dbData = [ + 'date' => $data['date'], + 'materialCode' => $data['materialCode'], + 'customer' => $data['customer'], + 'opening' => $data['opening'], + 'receipt' => $data['receipt'], + 'used' => $data['used'], + 'balanceStock' => $data['balanceStock'], + ]; + + if (isset($existingMap[$key])) { + $dbData['id'] = $existingMap[$key]; + $updates[] = $dbData; + } else { + $inserts[] = $dbData; + } + } + + if (!empty($inserts)) { + $this->resinStockDetails_model->insertBatch($inserts); + } + + if (!empty($updates)) { + if ($this->resinStockDetails_model->updateBatch($updates, 'id') === false) { + echo "Error during update"; return; } - - $inserts = []; - $updates = []; - - $dates = array_column($updateResinStockDetailsData, 'date'); - $materialCodes = array_column($updateResinStockDetailsData, 'materialCode'); - - // Fetch existing records in bulk to reduce queries - $existingRecords = $this->resinStockDetails_model - ->whereIn('date', $dates) - ->whereIn('materialCode', $materialCodes) - ->findAll(); - - $existingMap = []; - foreach ($existingRecords as $record) { - $existingMap[$record['date'] . '_' . $record['materialCode']] = $record['id']; - } - - foreach ($updateResinStockDetailsData as $data) { - - $key = $data['date'] . '_' . $data['materialCode']; - - $dbData = [ - 'date' => $data['date'], - 'materialCode' => $data['materialCode'], - 'customer' => $data['customer'], - 'opening' => $data['opening'], - 'receipt' => $data['receipt'], - 'used' => $data['used'], - 'balanceStock' => $data['balanceStock'], - ]; - - if (isset($existingMap[$key])) { - $dbData['id'] = $existingMap[$key]; - $updates[] = $dbData; - } else { - $inserts[] = $dbData; - } - } - - if (!empty($inserts)) { - $this->resinStockDetails_model->insertBatch($inserts); - } - - if (!empty($updates)) { - if ($this->resinStockDetails_model->updateBatch($updates, 'id') === false) { - echo "Error during update"; - return; - } - } - - echo "Data Saved Successfully"; } - - public function createDummyEntryForResin($customisedMaterialCode, $startDate, $endDate) - { - if (!empty($customisedMaterialCode)) { - $inserts = []; - - // Convert start and end date to timestamps - $startTimestamp = strtotime($startDate); - $endTimestamp = strtotime($endDate); - - while ($startTimestamp <= $endTimestamp) { - $inserts[] = [ - 'date' => date('Y-m-d', $startTimestamp), // Convert timestamp to date format - 'materialCode' => $customisedMaterialCode, - 'customer' => ' ', - 'opening' => ' ', - 'receipt' => ' ', - 'used' => ' ', - 'balanceStock' => ' ', - ]; - - $startTimestamp = strtotime('+1 day', $startTimestamp); // Move to the next day - } - - if (!empty($inserts)) { - $this->resinStockDetails_model->insertBatch($inserts); - } - } - } - + echo "Data Saved Successfully"; + } // Bag Stock details starts - + public function loadView_bagStockDetails() { - if ($this->request->getMethod() === 'POST') { - - $month = $this->request->getPost('month'); - - $date = DateTime::createFromFormat('d-M-Y', '01-'.$month); - - $formattedDate = $date->format('Y-m'); - - $month = $formattedDate; - - $session = session (); - - $session->set('stock_month',$month); - - - } else { - - $session = session(); - - $month = $session->get('stock_month'); - - if (empty($month)) { - $month = date('Y-m'); // Default to the current month - } - - } + $month = getStockMonth($this->request); $data = []; @@ -3117,6 +2381,7 @@ class StockController extends BaseController return $this->loadViews("stock/bagStockDetails", $this->global, $data, NULL); } + public function updateBagStockDetails() { @@ -3187,455 +2452,411 @@ class StockController extends BaseController echo "Data Saved Successfully"; } - - - - - public function trpSandUseStockDetails(){ - - if ($this->request->getMethod() === 'POST') { - $month = $this->request->getPost('month'); + public function trpSandUseStockDetails(){ + + + $month = getStockMonth($this->request); - $date = DateTime::createFromFormat('d-M-Y', '01-'.$month); - $formattedDate = $date->format('Y-m'); + $data = []; - $month = $formattedDate; - } else { - $session = session(); + $data['month'] = $month; - $month = $session->get('stock_month'); + $this->global['pageTitle'] = 'Trp Sand Use Stock Details'; + + $startDate = "$month-01"; + $endDate = date("Y-m-t", strtotime($startDate)); + + $data['trpSandUseStockDetails'] = $this->TrpSandUseStock_model + ->where('date >=', $startDate) + ->where('date <=', $endDate) + ->orderBy('date', 'asc') + ->findAll(); + + $date = DateTime::createFromFormat('Y-m-d', $month.'-01'); + + $formattedDate = $date->format('M-Y'); + + $data['month'] = $formattedDate; + + return $this->loadViews("stock/trpSandUseStockDetails", $this->global, $data, NULL); + - if (empty($month)) { - $month = date('Y-m'); // Default to the current month - } } - $data = []; + + public function updateTrpSandUseStockDetails(){ - $data['month'] = $month; + $postData = $this->request->getPost(); - $this->global['pageTitle'] = 'Trp Sand Use Stock Details'; + $updateTrpSandUseStockDetailsData = json_decode($postData['updateTrpSandUseStockDetails'], true); - $startDate = "$month-01"; - $endDate = date("Y-m-t", strtotime($startDate)); - $data['trpSandUseStockDetails'] = $this->TrpSandUseStock_model - ->where('date >=', $startDate) - ->where('date <=', $endDate) - ->orderBy('date', 'asc') - ->findAll(); - - $date = DateTime::createFromFormat('Y-m-d', $month.'-01'); - - $formattedDate = $date->format('M-Y'); - - $data['month'] = $formattedDate; - - return $this->loadViews("stock/trpSandUseStockDetails", $this->global, $data, NULL); - - - } - - public function updateTrpSandUseStockDetails(){ - - $postData = $this->request->getPost(); - - $updateTrpSandUseStockDetailsData = json_decode($postData['updateTrpSandUseStockDetails'], true); - - $updates = []; - - $inserts = []; - - foreach ($updateTrpSandUseStockDetailsData as $data) { - - $data['date'] = DateTime::createFromFormat('d-m-Y', $data['date'])->format('Y-m-d'); - - $date = $data['date']; - - $dbData = [ - 'date' => $data['date'], - 'rough_kgs' => $data['rough_kgs'], - 'fine_kgs' => $data['fine_kgs'], - 'total_kgs' => $data['total_kgs'], - 'customer_name' => $data['customer_name'] - ]; - - $resultExists = $this->TrpSandUseStock_model - ->where('date', $date) - ->first(); - - - if (empty($resultExists)) { - $inserts[] = $dbData; - } else { - $dbData['id'] = $resultExists['id']; - $updates[] = $dbData; - } - } - - if (!empty($inserts)) { - $this->TrpSandUseStock_model->insertBatch($inserts); - } - - if (!empty($updates)) { - - $updateResult = $this->TrpSandUseStock_model->updateBatch($updates, 'id'); - - if ($updateResult === FALSE) { - echo "Error during update"; - } else { - echo "Data Updated Successfully"; - return; - } - } - - echo "Data Saved Successfully"; - } - - public function trpProductionDetails(){ - - //filtering month in post request - - if ($this->request->getMethod() === 'POST') { - $month = $this->request->getPost('month'); - - $date = DateTime::createFromFormat('d-M-Y', '01-'.$month); - - $formattedDate = $date->format('Y-m'); - - $month = $formattedDate; - - $session = session (); - - $session->set('stock_month',$month); - - - } else { - - $session = session(); - - //getting month from session if present - $month = $session->get('stock_month'); - - //else current month - if (empty($month)) { - $month = date('Y-m'); // Default to the current month - } - - } - - $data = []; - - $data['month'] = $month; - - $this->global['pageTitle'] = 'Trp production Details'; - - $startDate = "$month-01"; - $endDate = date("Y-m-t", strtotime($startDate)); - - $trpProductionMaintenanceData = $this->TrpProductionMaintenance_model - ->where('date >=', $startDate) - ->where('date <=', $endDate) - ->find(); - - /* - no data found for given month , create dummy data for that month - because trp production involves join with other tables which are entried by other users so it is better to be empty - and create dummy data for that month .else join wont work - */ - - - - if(empty($trpProductionMaintenanceData)){ + $updates = []; $inserts = []; - $inserts = $this->createDummyDataForTrp($startDate, $endDate); + foreach ($updateTrpSandUseStockDetailsData as $data) { - $freshEntry = true ; + $data['date'] = DateTime::createFromFormat('d-m-Y', $data['date'])->format('Y-m-d'); - $this->updateTrpProductionDetails($inserts ,$freshEntry); + $date = $data['date']; - } + $dbData = [ + 'date' => $data['date'], + 'rough_kgs' => $data['rough_kgs'], + 'fine_kgs' => $data['fine_kgs'], + 'total_kgs' => $data['total_kgs'], + 'customer_name' => $data['customer_name'] + ]; + + $resultExists = $this->TrpSandUseStock_model + ->where('date', $date) + ->first(); - - $result = $this->TrpProduction_model->trpProductionDetails($startDate,$endDate); - - $data['trpProductionDetails'] = $result[0] ; - - $data['crsClientList'] = $result[1] ; - - $data['wcsSupplierList'] = $result[2] ; - - - - - - - - $trpAbstract = $this->trpAbstract_model->where('date', $startDate)->findAll(); - - - - $groupedTrpAbstract = [] ; - - foreach($trpAbstract as $abs){ - if(!isset($groupedTrpAbstract[$abs['particulars']])){ - $groupedTrpAbstract[$abs['particulars']] = $abs ; + if (empty($resultExists)) { + $inserts[] = $dbData; + } else { + $dbData['id'] = $resultExists['id']; + $updates[] = $dbData; } - } + } - $trpAbstract = $groupedTrpAbstract ; + if (!empty($inserts)) { + $this->TrpSandUseStock_model->insertBatch($inserts); + } - $data['trpAbstract'] = $trpAbstract ; + if (!empty($updates)) { - // dd( $data['trpAbstract']['Incoming Raw Sand Details'] ); + $updateResult = $this->TrpSandUseStock_model->updateBatch($updates, 'id'); - // dd((int)$trpAbstract["Incoming Raw Sand Details"]['opening_stock']); + if ($updateResult === FALSE) { + echo "Error during update"; + } else { + echo "Data Updated Successfully"; + return; + } + } - $date = DateTime::createFromFormat('Y-m-d', $month.'-01'); - - $formattedDate = $date->format('M-Y'); - - $data['month'] = $formattedDate; - - - - - - return $this->loadViews("stock/trpProductionStockDetails", $this->global, $data, NULL); - - } - - - public function updateTrpProductionDetails($inserts = null, $freshEntry = false) - { - - //getting values from post request - $postData['updateTrpProductionDetails'] = json_decode($this->request->getPost('updateTrpProductionDetails'),true); - - - - //checking if post data is empty data ? - if (empty($postData['updateTrpProductionDetails'])) { - - //if empty data , we still check for inserts data is available or not - if (empty($inserts)) { - - //if both fails return "no data found" - return $this->response->setJSON(['error' => 'No data found to update']); - - } else { - - //if inserts data is available , then assign to post data - $postData['updateTrpProductionDetails'] = $inserts; - } - } - - $updateTrpProductionDetails = $postData['updateTrpProductionDetails']; - - // Extract all dates from post data - $dates = array_column($updateTrpProductionDetails, 'Date'); - - //format from "d-m-Y" to db "Y-m-d" format - $formattedDates = array_map(fn($date) => $this->convertToDateWithFlexibleFormats($date, ["d-m-Y", "Y-m-d", "m/d/Y", "m-d-Y"], "Y-m-d"), $dates); - - - - // Fetch all existing maintenance , production and waste records for the given formatted dates - - $existingMaintenance = $this->TrpProductionMaintenance_model->whereIn('date', $formattedDates)->findAll(); - - $existingProduction = $this->TrpProduction_model->whereIn('date', $formattedDates)->findAll(); - - $existingWaste = $this->TrpProductionWaste_model->whereIn('date', $formattedDates)->findAll(); - - - //getting list of existing dates of maintenance , production and waste records - - $existingMaintenanceDateList = array_column($existingMaintenance, null, 'date'); - - $existingProductionDateList = array_column($existingProduction, null, 'date'); - - $existingWasteDateList = array_column($existingWaste, null, 'date'); - - - $updateMaintenance = []; - $updateProduction = []; - $updateWaste = []; - - - $insertMaintenance = []; - $insertProduction = []; - $insertWaste = []; - - - foreach ($updateTrpProductionDetails as $data) { - - $date = $this->convertToDateWithFlexibleFormats($data['Date'], ["d-m-Y", "Y-m-d", "m/d/Y", "m-d-Y"], "Y-m-d"); - - // Data arrays - $dbDataTrpMaintenance = [ - 'date' => $date, - 'openingTime' => $data['openingTime'], - 'closingTime' => $data['closingTime'], - 'totalHours' => $data['totalHours'], - 'coldStart' => $data['coldStart'], - 'breakdownHours' => $data['breakdownHours'], - 'burnerFiringHours' => $data['burnerFiringHours'], - 'sandFeedingHours' => $data['sandFeedingHours'], - 'workingPersonEngineers' => $data['workingPersonEngineers'], - 'workingPersonSupervisiors' => $data['workingPersonSupervisiors'], - 'workingPersonOperators' => $data['workingPersonOperators'], - 'rollerDrivers' => $data['rollerDrivers'], - 'natureOfMaintenance' => $data['natureOfMaintenance'], - 'location' => $data['location'], - 'description' => $data['description'] - ]; - - $dbDataTrpProduction = [ - 'date' => $date, - 'gasReceiptBg' => $data['gasReceiptBg'], - 'gasReceiptPg' => $data['gasReceiptPg'], - 'physicalGasConsumption' => $data['physicalGasConsumption'], - 'drierGasConsumption' => $data['drierGasConsumption'], - 'trpPlusDrierGasConsumption' => $data['trpPlusDrierGasConsumption'], - 'trpPhysicalGasPerTon' => $data['trpPhysicalGasPerTon'], - 'panelGasConsumption' => $data['panelGasConsumption'], - 'panelGasPerTon' => $data['panelGasPerTon'], - 'edRunningHours' => $data['edRunningHours'], - 'edProduction' => $data['edProduction'], - 'edUsage' => $data['edUsage'], - 'trpProduction' => $data['trpProduction'], - 'trpProductionPerHour' => $data['trpProductionPerHour'], - 'waterReceipt' => $data['waterReceipt'], - 'waterConsumption' => $data['waterConsumption'], - 'ebReading' => $data['ebReading'], - 'ebReadingPerUnitTon' => $data['ebReadingPerUnitTon'], - ]; - - $dbDataTrpWaste = [ - 'date' => $date, - 'msSeperation' => $data['msSeperation'], - 'edWaste' => $data['edWaste'], - 'coolerBags' => $data['coolerBags'], - 'edPlus20Waste' => $data['edPlus20Waste'], - 'cycloneWaste' => $data['cycloneWaste'], - ]; - - // Check if data already exists - if (isset($existingMaintenanceDateList[$date])) { - - $dbDataTrpMaintenance['id'] = (int) $existingMaintenanceDateList[$date]['id']; - $updateMaintenance[] = $dbDataTrpMaintenance; - - } else { - - $insertMaintenance[] = $dbDataTrpMaintenance; - - } - - if (isset($existingProductionDateList[$date])) { - - $dbDataTrpProduction['id'] = (int) $existingProductionDateList[$date]['id']; - $updateProduction[] = $dbDataTrpProduction; - - } else { - $insertProduction[] = $dbDataTrpProduction; - } - - if (isset($existingWasteDateList[$date])) { - - $dbDataTrpWaste['id'] = (int) $existingWasteDateList[$date]['id']; - $updateWaste[] = $dbDataTrpWaste; - - } else { - $insertWaste[] = $dbDataTrpWaste; - } - } - - // Start transaction - $this->db->transBegin(); - - try { - - // Insert new records in batch - if (!empty($insertMaintenance)) { - $this->TrpProductionMaintenance_model->insertBatch($insertMaintenance); - } - if (!empty($insertProduction)) { - $this->TrpProduction_model->insertBatch($insertProduction); - } - if (!empty($insertWaste)) { - $this->TrpProductionWaste_model->insertBatch($insertWaste); - } - - - // Update existing records in batch - if (!empty($updateMaintenance)) { - $this->TrpProductionMaintenance_model->updateBatch($updateMaintenance, 'id'); - } - if (!empty($updateProduction)) { - $this->TrpProduction_model->updateBatch($updateProduction, 'id'); - } - if (!empty($updateWaste)) { - $this->TrpProductionWaste_model->updateBatch($updateWaste, 'id'); - } - - // Commit transaction if successful - $this->db->transCommit(); - - if (!$freshEntry) { - echo "Data Saved Successfully"; - } - } catch (\Exception $error) { - // Rollback transaction on error - $this->db->transRollback(); - echo "An error occurred: " . $error->getMessage(); - } - } - - public function updateAbstractDetails() { - - $updateAbstractDetails = json_decode($this->request->getPost('updateAbstractDetails'), true); - - if (empty($updateAbstractDetails)) { - echo "No data received"; - return; + echo "Data Saved Successfully"; } - - - $date = trim($updateAbstractDetails[0]['date']); - - $monthPresent = $this->trpAbstract_model->where('date', $date)->findAll(); - - if ( count($monthPresent) > 1 ) { // Update existing records + + public function trpProductionDetails(){ + + //filtering month in post request + + $month = getStockMonth($this->request); + + $data = []; + + $data['month'] = $month; + + $this->global['pageTitle'] = 'Trp production Details'; + + $startDate = "$month-01"; + $endDate = date("Y-m-t", strtotime($startDate)); + + $trpProductionMaintenanceData = $this->TrpProductionMaintenance_model + ->where('date >=', $startDate) + ->where('date <=', $endDate) + ->find(); + + /* + no data found for given month , create dummy data for that month + because trp production involves join with other tables which are entried by other users so it is better to be empty + and create dummy data for that month .else join wont work + */ + + + + if(empty($trpProductionMaintenanceData)){ + + $inserts = []; + + $inserts = $this->createDummyDataForTrp($startDate, $endDate); + + $freshEntry = true ; + + $this->updateTrpProductionDetails($inserts ,$freshEntry); + + } + + + + $result = $this->TrpProduction_model->trpProductionDetails($startDate,$endDate); + + $data['trpProductionDetails'] = $result[0] ; + + $data['crsClientList'] = $result[1] ; + + $data['wcsSupplierList'] = $result[2] ; - foreach ($updateAbstractDetails as $updateAbstractDetail) { - $this->trpAbstract_model - ->where('date', trim($updateAbstractDetail['date'])) - ->where('particulars', trim($updateAbstractDetail['particulars'])) - ->set($updateAbstractDetail) - ->update(); // Correct update usage - } - $result = true; // Indicate success - } else { // Insert new records - $result = $this->trpAbstract_model->insertBatch($updateAbstractDetails); - } - - if ($result) { - echo "Data Saved Successfully"; - } else { - echo "Error in Submitting the abstract"; - } - } - - // -------------------------------------------- in class helpers ---------------------------------------------- + + + + + $trpAbstract = $this->trpAbstract_model->where('date', $startDate)->findAll(); + + + + $groupedTrpAbstract = [] ; + + foreach($trpAbstract as $abs){ + if(!isset($groupedTrpAbstract[$abs['particulars']])){ + $groupedTrpAbstract[$abs['particulars']] = $abs ; + } + } + + $trpAbstract = $groupedTrpAbstract ; + + $data['trpAbstract'] = $trpAbstract ; + + $date = DateTime::createFromFormat('Y-m-d', $month.'-01'); + + $formattedDate = $date->format('M-Y'); + + $data['month'] = $formattedDate; + + + + + + return $this->loadViews("stock/trpProductionStockDetails", $this->global, $data, NULL); + + } + + + public function updateTrpProductionDetails($inserts = null, $freshEntry = false) + { + + //getting values from post request + $postData['updateTrpProductionDetails'] = json_decode($this->request->getPost('updateTrpProductionDetails'),true); + + + + //checking if post data is empty data ? + if (empty($postData['updateTrpProductionDetails'])) { + + //if empty data , we still check for inserts data is available or not + if (empty($inserts)) { + + //if both fails return "no data found" + return $this->response->setJSON(['error' => 'No data found to update']); + + } else { + + //if inserts data is available , then assign to post data + $postData['updateTrpProductionDetails'] = $inserts; + } + } + + $updateTrpProductionDetails = $postData['updateTrpProductionDetails']; + + // Extract all dates from post data + $dates = array_column($updateTrpProductionDetails, 'Date'); + + //format from "d-m-Y" to db "Y-m-d" format + $formattedDates = array_map(fn($date) => $this->convertToDateWithFlexibleFormats($date, ["d-m-Y", "Y-m-d", "m/d/Y", "m-d-Y"], "Y-m-d"), $dates); + + + + // Fetch all existing maintenance , production and waste records for the given formatted dates + + $existingMaintenance = $this->TrpProductionMaintenance_model->whereIn('date', $formattedDates)->findAll(); + + $existingProduction = $this->TrpProduction_model->whereIn('date', $formattedDates)->findAll(); + + $existingWaste = $this->TrpProductionWaste_model->whereIn('date', $formattedDates)->findAll(); + + + //getting list of existing dates of maintenance , production and waste records + + $existingMaintenanceDateList = array_column($existingMaintenance, null, 'date'); + + $existingProductionDateList = array_column($existingProduction, null, 'date'); + + $existingWasteDateList = array_column($existingWaste, null, 'date'); + + + $updateMaintenance = []; + $updateProduction = []; + $updateWaste = []; + + + $insertMaintenance = []; + $insertProduction = []; + $insertWaste = []; + + + foreach ($updateTrpProductionDetails as $data) { + + $date = $this->convertToDateWithFlexibleFormats($data['Date'], ["d-m-Y", "Y-m-d", "m/d/Y", "m-d-Y"], "Y-m-d"); + + // Data arrays + $dbDataTrpMaintenance = [ + 'date' => $date, + 'openingTime' => $data['openingTime'], + 'closingTime' => $data['closingTime'], + 'totalHours' => $data['totalHours'], + 'coldStart' => $data['coldStart'], + 'breakdownHours' => $data['breakdownHours'], + 'burnerFiringHours' => $data['burnerFiringHours'], + 'sandFeedingHours' => $data['sandFeedingHours'], + 'workingPersonEngineers' => $data['workingPersonEngineers'], + 'workingPersonSupervisiors' => $data['workingPersonSupervisiors'], + 'workingPersonOperators' => $data['workingPersonOperators'], + 'rollerDrivers' => $data['rollerDrivers'], + 'natureOfMaintenance' => $data['natureOfMaintenance'], + 'location' => $data['location'], + 'description' => $data['description'] + ]; + + $dbDataTrpProduction = [ + 'date' => $date, + 'gasReceiptBg' => $data['gasReceiptBg'], + 'gasReceiptPg' => $data['gasReceiptPg'], + 'physicalGasConsumption' => $data['physicalGasConsumption'], + 'drierGasConsumption' => $data['drierGasConsumption'], + 'trpPlusDrierGasConsumption' => $data['trpPlusDrierGasConsumption'], + 'trpPhysicalGasPerTon' => $data['trpPhysicalGasPerTon'], + 'panelGasConsumption' => $data['panelGasConsumption'], + 'panelGasPerTon' => $data['panelGasPerTon'], + 'edRunningHours' => $data['edRunningHours'], + 'edProduction' => $data['edProduction'], + 'edUsage' => $data['edUsage'], + 'trpProduction' => $data['trpProduction'], + 'trpProductionPerHour' => $data['trpProductionPerHour'], + 'waterReceipt' => $data['waterReceipt'], + 'waterConsumption' => $data['waterConsumption'], + 'ebReading' => $data['ebReading'], + 'ebReadingPerUnitTon' => $data['ebReadingPerUnitTon'], + ]; + + $dbDataTrpWaste = [ + 'date' => $date, + 'msSeperation' => $data['msSeperation'], + 'edWaste' => $data['edWaste'], + 'coolerBags' => $data['coolerBags'], + 'edPlus20Waste' => $data['edPlus20Waste'], + 'cycloneWaste' => $data['cycloneWaste'], + ]; + + // Check if data already exists + if (isset($existingMaintenanceDateList[$date])) { + + $dbDataTrpMaintenance['id'] = (int) $existingMaintenanceDateList[$date]['id']; + $updateMaintenance[] = $dbDataTrpMaintenance; + + } else { + + $insertMaintenance[] = $dbDataTrpMaintenance; + + } + + if (isset($existingProductionDateList[$date])) { + + $dbDataTrpProduction['id'] = (int) $existingProductionDateList[$date]['id']; + $updateProduction[] = $dbDataTrpProduction; + + } else { + $insertProduction[] = $dbDataTrpProduction; + } + + if (isset($existingWasteDateList[$date])) { + + $dbDataTrpWaste['id'] = (int) $existingWasteDateList[$date]['id']; + $updateWaste[] = $dbDataTrpWaste; + + } else { + $insertWaste[] = $dbDataTrpWaste; + } + } + + // Start transaction + $this->db->transBegin(); + + try { + + // Insert new records in batch + if (!empty($insertMaintenance)) { + $this->TrpProductionMaintenance_model->insertBatch($insertMaintenance); + } + if (!empty($insertProduction)) { + $this->TrpProduction_model->insertBatch($insertProduction); + } + if (!empty($insertWaste)) { + $this->TrpProductionWaste_model->insertBatch($insertWaste); + } + + + // Update existing records in batch + if (!empty($updateMaintenance)) { + $this->TrpProductionMaintenance_model->updateBatch($updateMaintenance, 'id'); + } + if (!empty($updateProduction)) { + $this->TrpProduction_model->updateBatch($updateProduction, 'id'); + } + if (!empty($updateWaste)) { + $this->TrpProductionWaste_model->updateBatch($updateWaste, 'id'); + } + + // Commit transaction if successful + $this->db->transCommit(); + + if (!$freshEntry) { + echo "Data Saved Successfully"; + } + } catch (\Exception $error) { + // Rollback transaction on error + $this->db->transRollback(); + echo "An error occurred: " . $error->getMessage(); + } + } + + + public function updateAbstractDetails() { + + $updateAbstractDetails = json_decode($this->request->getPost('updateAbstractDetails'), true); + + if (empty($updateAbstractDetails)) { + echo "No data received"; + return; + } + + + + $date = trim($updateAbstractDetails[0]['date']); + + $monthPresent = $this->trpAbstract_model->where('date', $date)->findAll(); + + if ( count($monthPresent) > 1 ) { // Update existing records + + + foreach ($updateAbstractDetails as $updateAbstractDetail) { + $this->trpAbstract_model + ->where('date', trim($updateAbstractDetail['date'])) + ->where('particulars', trim($updateAbstractDetail['particulars'])) + ->set($updateAbstractDetail) + ->update(); // Correct update usage + } + $result = true; // Indicate success + } else { // Insert new records + $result = $this->trpAbstract_model->insertBatch($updateAbstractDetails); + } + + if ($result) { + echo "Data Saved Successfully"; + } else { + echo "Error in Submitting the abstract"; + } + } + + + // -------------------------------------------- in-house class helpers ---------------------------------------------- public function getMonthDatesFromInput($monthYear) @@ -3682,12 +2903,6 @@ class StockController extends BaseController return $times; } - - - - /** - * Updates gas stock consumption if the value changes. - */ private function handleGasStockUpdate($existingRow, $newRow) { $existingConsumption = $existingRow['total_gas_consumption']; //eg:400 @@ -3699,7 +2914,6 @@ class StockController extends BaseController } } - function convertToDateWithFlexibleFormats($dateInput, array $inputFormats, string $outputFormat): ?string { @@ -3721,7 +2935,6 @@ class StockController extends BaseController return $dateInput; } - public function createDummyEntryForBag($customisedMaterialCode, $startDate, $endDate) { if (!empty($customisedMaterialCode)) { @@ -3749,6 +2962,34 @@ class StockController extends BaseController $this->bagStockDetails_model->insertBatch($inserts); } } + } + public function createDummyEntryForResin($customisedMaterialCode, $startDate, $endDate) + { + if (!empty($customisedMaterialCode)) { + $inserts = []; + + // Convert start and end date to timestamps + $startTimestamp = strtotime($startDate); + $endTimestamp = strtotime($endDate); + + while ($startTimestamp <= $endTimestamp) { + $inserts[] = [ + 'date' => date('Y-m-d', $startTimestamp), // Convert timestamp to date format + 'materialCode' => $customisedMaterialCode, + 'customer' => ' ', + 'opening' => ' ', + 'receipt' => ' ', + 'used' => ' ', + 'balanceStock' => ' ', + ]; + + $startTimestamp = strtotime('+1 day', $startTimestamp); // Move to the next day + } + + if (!empty($inserts)) { + $this->resinStockDetails_model->insertBatch($inserts); + } + } } public function createDummyEntryForDieselMachine($customisedMachineCode, $startDate, $endDate) @@ -3869,18 +3110,283 @@ class StockController extends BaseController return $inserts; } + private function updateGasConsumptionOrFail($date, $consumption) + { + $result = $this->updateGasStockConsumption($date, $consumption); + if (!$result) { + throw new \Exception('Failed to update gas stock consumption.'); + } + } + + private function handleGasConsumptionAdjustment($data, &$messages) + { + $existingConsumption = $data['existingTotalGasConsumption']; + $newConsumption = $data['totalGasConsumption']; + + if ($existingConsumption == $newConsumption) { + return; + } + + $change = $newConsumption - $existingConsumption; + $result = $this->updateGasStockConsumption($data['date'], $change); + + if (!$result) { + throw new \Exception('Failed to update gas stock consumption.'); + } + + $messages[] = 'And updated gas stock consumption.'; + $messages[] = 'Warning..!! Kindly Update the next subsequent month Gas Stock If older month Gas Stock Updated..!!'; + } + + private function handleBatchCardUploads($coatingId) + { + $files = $this->request->getFileMultiple('batchCard'); + + if (empty($files) || $files[0]->getError() === UPLOAD_ERR_NO_FILE) { + return; + } + + $uploadPath = WRITEPATH . 'uploads' . DIRECTORY_SEPARATOR . 'batchcard'; + if (!is_dir($uploadPath)) { + mkdir($uploadPath, 0777, true); + } + + $db = \Config\Database::connect(); + $builder = $db->table('t_batchcard_files'); + $inserts = []; + + foreach ($files as $file) { + if (!$file->isValid() || $file->hasMoved()) { + continue; + } + + $clientName = $file->getClientName(); + $newName = $file->getRandomName(); + + if ($file->move($uploadPath, $newName)) { + $inserts [] = [ + 'client_file_name' => $clientName, + 'filename' => $newName, + 'coating_id' => $coatingId + ]; + } + + } - + if(!empty($inserts)){ + $builder->insertBatch($inserts); + } + } + + private function getBatchCardFileRecord($id) + { + $db = \Config\Database::connect(); + return $db->table('t_batchcard_files') + ->select('filename') + ->where('id', $id) + ->get() + ->getRow(); + } + private function deleteBatchCardFileFromStorage($filename) + { + $path = WRITEPATH . 'uploads' . DIRECTORY_SEPARATOR . 'batchcard'; + if (!is_dir($path)) { + mkdir($path, 0777, true); + } + + $filePath = $path . DIRECTORY_SEPARATOR . $filename; + if (file_exists($filePath)) { + unlink($filePath); + } + + return 1; + } + + private function deleteBatchCardFileRecord($id) + { + $db = \Config\Database::connect(); + return $db->query("DELETE FROM t_batchcard_files WHERE id = ?", [$id]); + } + + private function respondWithJson($status, $message) + { + return $this->response->setJSON([ + 'status' => (string)$status, + 'message' => $message + ]); + } + + private function getBatchCardFiles($coatingId) + { + $batchCardFiles = $this->db->table('t_batchcard_files') + ->where('coating_id', $coatingId) + ->get() + ->getResultArray(); + + return $batchCardFiles; + } + + private function getPreviousMonthDateRange(string $currentMonth): array + { + $previousMonth = DateTime::createFromFormat('Y-m-d', $currentMonth . '-01') + ->modify('-1 month') + ->format('Y-m'); + + $startDate = "$previousMonth-01"; + $endDate = date("Y-m-t", strtotime($startDate)); + + return [ + 'start' => $startDate, + 'end' => $endDate + ]; + } - - - + private function getOrUpdateCustomisedMachineCodes($month) + { + $filterCodes = $this->request->getPost('customisedMachineCodes') ?? []; + $existingCodes = $this->monthWiseMachineInStockModel + ->select('machine_id') + ->where('date', "$month-01") + ->where('machine_category', 'diesel') + ->findAll(); + + $filterUpdateNeeded = true; + if (empty($filterCodes) && !empty($existingCodes)) { + return array_column($existingCodes, 'machine_id'); + } + + if (!empty($filterCodes) && $filterUpdateNeeded) { + $this->monthWiseMachineInStockModel + ->where('date', "$month-01") + ->where('machine_category', 'diesel') + ->delete(); + + $inserts = array_map(fn($code) => [ + 'date' => "$month-01", + 'machine_category' => "diesel", + 'machine_id' => $code + ], $filterCodes); + + if (!empty($inserts)) { + $this->monthWiseMachineInStockModel->insertBatch($inserts); + } + return $filterCodes; + } + + // If no filter applied at all — fallback to previous month or all active + if (empty($existingCodes)) { + $previousMonth = date('Y-m-01', strtotime('-1 month', strtotime("$month-01"))); + $prevCodes = $this->monthWiseMachineInStockModel + ->select('machine_id') + ->where('date', "$previousMonth") + ->where('machine_category', 'diesel') + ->get() + ->getResultArray(); + + if (!empty($prevCodes)) { + return array_column($prevCodes, 'machine_id'); + } else { + $activeMachines = $this->factoryMachine_model->getAllActiveDieselMachines(); + $inserts = array_map(fn($m) => [ + 'date' => "$month-01", + 'machine_category' => "diesel", + 'machine_id' => $m['id'] + ], $activeMachines); + $this->monthWiseMachineInStockModel->insertBatch($inserts); + return array_column($activeMachines, 'id'); + } + } + + return array_column($existingCodes, 'machine_id'); + } + + private function isCurrentMonth($startDate, $endDate, $currentDate) + { + return $startDate == $currentDate->format('Y-m-01') && $endDate == $currentDate->format('Y-m-t'); + } + + private function ensureDieselDetailsForMonth($machineCodes, $startDate, $endDate) + { + foreach ($machineCodes as $code) { + $exists = $this->factoryVehicleDieselDetails_model + ->where('date >=', $startDate) + ->where('date <=', $endDate) + ->where('machine_id', $code) + ->findAll(); + + if (empty($exists)) { + $this->createDummyEntryForDieselMachine($code, $startDate, $endDate); + } + } + } + + private function getPreviousMonthStockDetails($month) + { + $previousMonth = DateTime::createFromFormat('Y-m-d', "$month-01") + ->modify('-1 month')->format('Y-m'); + $prevStart = "$previousMonth-01"; + $prevEnd = date("Y-m-t", strtotime($prevStart)); + + $details = $this->factoryVehicleDieselDetails_model + ->select(['machine_id', 'date', 'closing_reading']) + ->distinct() + ->where('date =', $prevEnd) + ->groupBy(['machine_id', 'date']) + ->orderBy('date', 'desc') + ->orderBy('machine_id', 'asc') + ->findAll(); + + $totals = $this->factoryVehicleDieselStockSummary_model + ->select(['id', 'date', 'balance_stock']) + ->distinct() + ->where('date =', $prevEnd) + ->groupBy(['id', 'date']) + ->orderBy('date', 'desc') + ->findAll(); + + return [$details, $totals]; + } + + private function groupAndSortStockDetails($details, $customisedOrder) + { + $grouped = []; + foreach ($details as $detail) { + $grouped[$detail['date']][] = $detail; + } + + if (!empty($customisedOrder)) { + foreach ($grouped as &$machines) { + usort($machines, fn($a, $b) => $this->compareByCustomOrder($a, $b, $customisedOrder)); + } + } + + return array_values($grouped); + } + + private function sortMachinesByCustomOrder($machines, $customOrder) + { + usort($machines, fn($a, $b) => $this->compareByCustomOrder($a, $b, $customOrder, 'id')); + return $machines; + } + + private function compareByCustomOrder($a, $b, $order, $key = 'machine_id') + { + $indexA = array_search($a[$key], $order); + $indexB = array_search($b[$key], $order); + + if ($indexA === false && $indexB === false) return 0; + if ($indexA === false) return 1; + if ($indexB === false) return -1; + + return $indexA - $indexB; + } + diff --git a/app/Helpers/stock_helper.php b/app/Helpers/stock_helper.php new file mode 100644 index 00000000..8d06c888 --- /dev/null +++ b/app/Helpers/stock_helper.php @@ -0,0 +1,32 @@ +getMethod() === 'POST') { + $monthInput = $request->getPost('month'); + $date = DateTime::createFromFormat('d-M-Y', '01-' . $monthInput); + $formattedDate = $date ? $date->format('Y-m') : date('Y-m'); + $session->set('stock_month', $formattedDate); + $month = $formattedDate; + } else { + $month = $session->get('stock_month'); + if (empty($month)) { + $month = date('Y-m'); + } + } + + return $month; +} diff --git a/app/Models/CoatingMachineDetailsModel.php b/app/Models/CoatingMachineDetailsModel.php index 544478ba..0ea772ec 100644 --- a/app/Models/CoatingMachineDetailsModel.php +++ b/app/Models/CoatingMachineDetailsModel.php @@ -45,4 +45,47 @@ class CoatingMachineDetailsModel extends Model protected $afterFind = []; protected $beforeDelete = []; protected $afterDelete = []; + + public function coatingMachineDetails($startDate,$endDate){ + $result = $this->db->table('t_coatingmachinedetails') + ->select('t_coatingmachinedetails.*, + JSON_ARRAYAGG( + JSON_OBJECT( + "client_given_name", t_batchcard_files.client_file_name, + "filename", t_batchcard_files.filename, + "batchCardId" , t_batchcard_files.id, + "coating_id", t_batchcard_files.coating_id + ) + ) as batchcard_files') + ->join('t_batchcard_files', 't_batchcard_files.coating_id = t_coatingmachinedetails.id', 'left') + ->where('t_coatingmachinedetails.date >=', $startDate) + ->where('t_coatingmachinedetails.date <=', $endDate) + ->groupBy('t_coatingmachinedetails.id') + ->orderBy('t_coatingmachinedetails.date', 'asc') + ->get() + ->getResultArray(); + return $result; + } + + public function isShiftExists($date, $shift) + { + $result = $this->db->table('t_coatingmachinedetails') + ->where('date', $date) + ->where('shift', $shift) + ->where('is_active', 1) + ->get() + ->getResultArray(); + + return $result; + + } + + + + + + + + + } diff --git a/app/Models/GasStockModel.php b/app/Models/GasStockModel.php index 259807ce..d4cb1c2e 100644 --- a/app/Models/GasStockModel.php +++ b/app/Models/GasStockModel.php @@ -45,4 +45,57 @@ class GasStockModel extends Model protected $afterFind = []; protected $beforeDelete = []; protected $afterDelete = []; + + + public function gasStockDetails($startDate,$endDate){ + + $result = $this->db->table('t_gasstockdetails') + + ->select( + 't_gasstockdetails.*, + drier_summary.drierMachineGasconsumption AS drierMachineGasConsumption, + drier_summary.driedSand AS sandDried, + coating_summary.coatingMachineGasconsumption, + coating_summary.coatedSand' + ) + // Subquery with early date filtering + ->join( + '(SELECT date, + SUM(totalGasconsumption) AS coatingMachineGasconsumption, + SUM(totalCoatingSandInKg) AS coatedSand + FROM t_coatingmachinedetails + WHERE is_active = 1 + AND date >= ' . $this->db->escape($startDate) . ' + AND date <= ' . $this->db->escape($endDate) . ' + GROUP BY date + ) AS coating_summary', + 'coating_summary.date = t_gasstockdetails.date', + 'left' + ) + ->join( + '(SELECT date, + SUM(total_gas_consumption) AS drierMachineGasconsumption, + SUM(sand_dried_qty) AS driedSand + FROM t_driermachinedetails + WHERE date >= ' . $this->db->escape($startDate) . ' + AND date <= ' . $this->db->escape($endDate) . ' + GROUP BY date + ) AS drier_summary', + 'drier_summary.date = t_gasstockdetails.date', + 'left' + ) + + ->where('t_gasstockdetails.date >=', $startDate) + ->where('t_gasstockdetails.date <=', $endDate) + ->groupBy('t_gasstockdetails.date') + ->get() + ->getResultArray(); + + return $result; + + } + + + + } diff --git a/app/Views/stock/bagStockDetails.php b/app/Views/stock/bagStockDetails.php index 7e13766f..1144a2fc 100644 --- a/app/Views/stock/bagStockDetails.php +++ b/app/Views/stock/bagStockDetails.php @@ -614,15 +614,14 @@ foreach ($period as $day) { foreach ($groupedBagStockDetails as $groupedBagStockDetailsIndex => $bagStockDetails) { - $currentDate = date('d-m-Y'); - $dateInMonthDmYFormat = DateTime::createFromFormat('Y-m-d', $bagStockDetails[0]['date'])->format('d-m-Y'); + $currentDate = date('Y-m-d'); ?> -