changes in stock module 06-03-2025

This commit is contained in:
vadivelJ96 2025-03-06 16:00:48 +05:30
parent 866f497e6c
commit c496887066
7 changed files with 257 additions and 212 deletions

View File

@ -147,24 +147,37 @@ class StockController extends BaseController
public function loadView_incomingSilicaSandDetails() 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 ,
//hope you bear it..!!
//we did ..!!
//getting month in post
if ($this->request->getMethod() === 'POST') { if ($this->request->getMethod() === 'POST') {
//getting remark value which is used to specify the issd entry is accepted/rejected/conditionally accepted..
$remark = $this->request->getPost('remark'); $remark = $this->request->getPost('remark');
$month = $this->request->getPost('month'); $month = $this->request->getPost('month');
//formatting the date format of Jan-2025 to 2025-01
$date = DateTime::createFromFormat('M-Y', $month); $date = DateTime::createFromFormat('M-Y', $month);
$formattedDate = $date->format('Y-m'); $formattedDate = $date->format('Y-m');
$month = $formattedDate; $month = $formattedDate;
//setting session for any month change
$session = session (); $session = session ();
$session->set('stock_month',$month); $session->set('stock_month',$month);
} else { } else {
//if request is in get method getting remark in query params in new_header.php file(navbar)
$remark = $this->request->getVar('remark'); $remark = $this->request->getVar('remark');
$session = session(); $session = session();
@ -172,21 +185,25 @@ class StockController extends BaseController
$month = $session->get('stock_month'); $month = $session->get('stock_month');
if (empty($month)) { if (empty($month)) {
$month = date('Y-m'); // Default to the current month //if no monthis set in session setting Default to the current month
$month = date('Y-m');
} }
} }
$data['month'] = $month; $data['month'] = $month;
//set page title
$this->global['pageTitle'] = 'Incoming Silica Sand Details'; $this->global['pageTitle'] = 'Incoming Silica Sand Details';
$materialCodes = []; $materialCodes = [];
//getting all silica sand raw materials material code
$silicaSandMaterialCodes = $this->rawmaterialdetails_model->getAllSilicaRawMaterialCode(); $silicaSandMaterialCodes = $this->rawmaterialdetails_model->getAllSilicaRawMaterialCode();
$materialCodes [] = $silicaSandMaterialCodes; $materialCodes [] = $silicaSandMaterialCodes;
//getting all waste Core Sand Material Codes
$wasteCoreSandMaterialCodes = $this->rawmaterialdetails_model->getAllWasteCoreSandMaterialCode(); $wasteCoreSandMaterialCodes = $this->rawmaterialdetails_model->getAllWasteCoreSandMaterialCode();
$materialCodes [] = $wasteCoreSandMaterialCodes; $materialCodes [] = $wasteCoreSandMaterialCodes;
@ -195,6 +212,7 @@ class StockController extends BaseController
if (!empty($materialCodes)) { if (!empty($materialCodes)) {
//remark filter may apply or not
$data['igrDetails'] = $this->inwardGateRegister_model->findIgrDetailsForIncomingSilicaSand($materialCodes, $month, $remark); $data['igrDetails'] = $this->inwardGateRegister_model->findIgrDetailsForIncomingSilicaSand($materialCodes, $month, $remark);
} else { } else {
$data['igrDetails'] = []; $data['igrDetails'] = [];
@ -202,11 +220,11 @@ class StockController extends BaseController
$data['testedBy'] = []; $data['testedBy'] = [];
$DesignationConfigID = 'C010'; //['lab assistant', 'factory manager', 'lab head']
$data['testedBy'] = $this->employeedetails_model->incomingSilicaSandTestedBy();
$data['testedBy'] = $this->employeedetails_model->incomingSilicaSandTestedBy($DesignationConfigID); //['factory manager', 'lab head']
$data['approvedBy'] = $this->employeedetails_model->incomingSilicaSandApprovedBy();
$data['approvedBy'] = $this->employeedetails_model->incomingSilicaSandApprovedBy($DesignationConfigID);
$date = DateTime::createFromFormat('Y-m', $month); $date = DateTime::createFromFormat('Y-m', $month);
@ -220,6 +238,7 @@ class StockController extends BaseController
return $this->loadViews("stock/incomingSilicaSandDetails", $this->global, $data, NULL); return $this->loadViews("stock/incomingSilicaSandDetails", $this->global, $data, NULL);
} }
public function updateIncomingSilicaSandDetails() public function updateIncomingSilicaSandDetails()
{ {
@ -290,6 +309,8 @@ class StockController extends BaseController
echo "Data Saved Successfully"; echo "Data Saved Successfully";
} }
//This is particulary updated by the lab technichians
public function updateLabReport() public function updateLabReport()
{ {
@ -353,115 +374,143 @@ class StockController extends BaseController
//Drier machine details //Drier machine details
public function drierMachineDetails() 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.
//drier will be processing different method than other stock in case of session stock month and date format for generating
//dummy data and updating the data . be cautious while updating the code..!!
if ($this->request->getMethod() === 'POST') { if ($this->request->getMethod() === 'POST') {
// Retrieve the month value from the POST request (expected in "M-Y" format, e.g., "Jan-2025")
$currentMonth = $this->request->getPost('month'); $currentMonth = $this->request->getPost('month');
$date = DateTime::createFromFormat('M-Y', $currentMonth); //in M-Y format // Convert the month format from "M-Y" (Jan-2025) to "Y-m" (2025-01) for database processing
$date = DateTime::createFromFormat('M-Y', $currentMonth);
$formattedDate = $date->format('Y-m'); //in Y-m format $formattedDate = $date->format('Y-m');
$session = session (); $session = session();
$session->set('stock_month',$formattedDate);
$session->set('stock_month', $formattedDate);
} else { } else {
$session = session(); $session = session();
$currentMonth = $session->get('stock_month'); $currentMonth = $session->get('stock_month');
// If no month is set in the session, default to the current month in "M-Y" format
if (empty($currentMonth)) { if (empty($currentMonth)) {
$currentMonth = date('M-Y'); // Default to the current month $currentMonth = date('M-Y');
}else{ } else {
$currentMonth = DateTime::createFromFormat('Y-m', $currentMonth); // in Y-m format // Convert the stored "Y-m" format (e.g., 2025-01) back to "M-Y" (e.g., Jan-2025) for display
$currentMonth = DateTime::createFromFormat('Y-m', $currentMonth);
$currentMonth = $currentMonth->format('M-Y'); // in M-Y format $currentMonth = $currentMonth->format('M-Y');
} }
} }
// Retrieve the list of dates for the selected month in database-compatible format
$monthData = $this->getMonthDatesFromInput($currentMonth); $monthData = $this->getMonthDatesFromInput($currentMonth);
$isActiveFilter = 1 ;
$data['startDate'] = $monthData[0]['database']; // Set the active filter for suppliers (1 means active suppliers will be fetched)
$data['endDate'] = $monthData[count($monthData) - 1]['database']; $isActiveFilter = 1;
$data['startDate'] = $monthData[0]['database']; // First day of the selected month
$data['endDate'] = $monthData[count($monthData) - 1]['database']; // Last day of the selected month
// Generate available time slots for drier machine processing
$data['timeDropdown'] = $this->generateTimeOptions(); $data['timeDropdown'] = $this->generateTimeOptions();
$data['supplierData'] = $this->supplier_model->supplierlisting($isActiveFilter); $data['supplierData'] = $this->supplier_model->supplierlisting($isActiveFilter);
// Retrieve drier machine details for the selected date range
$data['drierDetails'] = $this->drierMachineDetails_model $data['drierDetails'] = $this->drierMachineDetails_model
->where('date >=', $data['startDate']) ->where('date >=', $data['startDate'])
->where('date <=', $data['endDate']) ->where('date <=', $data['endDate'])
->orderBy('date','asc') ->orderBy('date', 'asc')
->findAll(); ->findAll();
$data['datefordropdown'] = $currentMonth; $data['datefordropdown'] = $currentMonth;
// Set the page title for display
$this->global['pageTitle'] = 'Drier Details'; $this->global['pageTitle'] = 'Drier Details';
$this->loadViews("stock/drierMachineDetails", $this->global, $data, NULL); $this->loadViews("stock/drierMachineDetails", $this->global, $data, NULL);
} }
public function addOrEditdrierMachineDetails() 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);
$data = $this->request->getPost(); // Begin a database transaction to ensure atomicity
$drierData[] = $this->mapDrierEntry($data);
$this->db->transBegin(); $this->db->transBegin();
try { try {
// Arrays to store data for batch insert and batch update operations
$inserts = []; $inserts = [];
$updates = []; $updates = [];
foreach ($drierData as $row) { foreach ($drierData as $row) {
// Retrieve the ID of the existing entry (if present)
$existingRow = $row['id']; $existingRow = $row['id'];
$data = $row; $data = $row;
if ($existingRow) {
if (($existingRow)) {
$existingRow = $this->drierMachineDetails_model->where('id', $row['id'] ?? '')->first(); $existingRow = $this->drierMachineDetails_model->where('id', $row['id'] ?? '')->first();
// Handle gas stock updates for the existing record
$this->handleGasStockUpdate($existingRow, $row); $this->handleGasStockUpdate($existingRow, $row);
$updates[] = $data; $updates[] = $data;
} else { } else {
// If it's a new record, update gas stock consumption before inserting
$this->updateGasStockConsumption($data['date'], $data['total_gas_consumption']); $this->updateGasStockConsumption($data['date'], $data['total_gas_consumption']);
$inserts[] = $data; $inserts[] = $data;
} }
} }
if (!empty($inserts)) { if (!empty($inserts)) {
$this->drierMachineDetails_model->insertBatch($inserts); $this->drierMachineDetails_model->insertBatch($inserts);
} }
if (!empty($updates)) { if (!empty($updates)) {
$this->drierMachineDetails_model->updateBatch($updates, 'id'); $this->drierMachineDetails_model->updateBatch($updates, 'id');
} }
// Check if the transaction encountered any database errors
if ($this->db->transStatus() === false) { if ($this->db->transStatus() === false) {
throw new \Exception('Transaction failed due to database error.'); throw new \Exception('Transaction failed due to database error.');
} }
$this->db->transCommit(); $this->db->transCommit();
return redirect()->to("/drierMachineDetails")->with('success', "Data Saved Successfully");
} catch (\Exception $error) { return redirect()->to("/drierMachineDetails")->with('success', "Data Saved Successfully");
$this->db->transRollback();
return redirect()->back()->with('error', ' ' . $error->getMessage()); } catch (\Exception $error) {
} // Rollback the transaction in case of an error
$this->db->transRollback();
return redirect()->back()->with('error', ' ' . $error->getMessage());
}
} }
/** /**
* Maps input row to expected format. * Maps input row to expected format.
*/ */
@ -491,67 +540,64 @@ class StockController extends BaseController
//Coating Machine Details starts //Coating Machine Details starts
public function loadView_coatingMachineDetails() public function loadView_coatingMachineDetails()
{ {
if ($this->request->getMethod() === 'POST') { if ($this->request->getMethod() === 'POST') {
// Get the month from the request
$month = $this->request->getPost('month'); $month = $this->request->getPost('month');
// Convert month format from "M-Y" to "Y-m"
$date = DateTime::createFromFormat('M-Y', $month); $date = DateTime::createFromFormat('M-Y', $month);
$formattedDate = $date->format('Y-m'); $formattedDate = $date->format('Y-m');
$month = $formattedDate; $month = $formattedDate;
$session = session (); // Store selected month in session
$session = session();
$session->set('stock_month',$month); $session->set('stock_month', $month);
} else { } else {
$session = session(); $session = session();
$month = $session->get('stock_month'); $month = $session->get('stock_month');
// Default to the current month if no month is stored in session
if (empty($month)) { if (empty($month)) {
$month = date('Y-m'); // Default to the current month $month = date('Y-m');
} }
} }
$data['month'] = $month ; $data['month'] = $month;
$this->global['pageTitle'] = 'Coating Machine Details';
$this->global['pageTitle'] = 'Coating Machine Details ';
// Define start and end date for the selected month
$startDate = "$month-01"; $startDate = "$month-01";
$endDate = date("Y-m-t", strtotime($startDate)); $endDate = date("Y-m-t", strtotime($startDate));
// Fetch coating machine details with batch card file details
$data['coatingMachineDetails'] = $this->coatingMachineDetails_model $data['coatingMachineDetails'] = $this->coatingMachineDetails_model
->select('t_coatingmachinedetails.*, ->select('t_coatingmachinedetails.*,
JSON_ARRAYAGG( JSON_ARRAYAGG(
JSON_OBJECT( JSON_OBJECT(
"client_given_name", t_batchcard_files.client_file_name, "client_given_name", t_batchcard_files.client_file_name,
"filename", t_batchcard_files.filename, "filename", t_batchcard_files.filename,
"batchCardId" , t_batchcard_files.id, "batchCardId" , t_batchcard_files.id,
"coating_id", t_batchcard_files.coating_id "coating_id", t_batchcard_files.coating_id
) )
) as batchcard_files') ) as batchcard_files')
->join('t_batchcard_files', 't_batchcard_files.coating_id = t_coatingmachinedetails.id', 'left') ->join('t_batchcard_files', 't_batchcard_files.coating_id = t_coatingmachinedetails.id', 'left')
->where('t_coatingmachinedetails.date >=', $startDate) ->where('t_coatingmachinedetails.date >=', $startDate)
->where('t_coatingmachinedetails.date <=', $endDate) ->where('t_coatingmachinedetails.date <=', $endDate)
->groupBy('t_coatingmachinedetails.id') ->groupBy('t_coatingmachinedetails.id')
->orderBy('t_coatingmachinedetails.date', 'asc') ->orderBy('t_coatingmachinedetails.date', 'asc')
->findAll(); ->findAll();
// Convert month format from "Y-m" to "M-Y" for display
$date = DateTime::createFromFormat('Y-m', $month); $date = DateTime::createFromFormat('Y-m', $month);
$formattedDate = $date->format('M-Y'); $formattedDate = $date->format('M-Y');
$data['month'] = $formattedDate; $data['month'] = $formattedDate;
// Load the view with the required data
return $this->loadViews("stock/CoatingMachineDetail", $this->global, $data, NULL); return $this->loadViews("stock/CoatingMachineDetail", $this->global, $data, NULL);
} }
public function addNewCoatingMachineDetails() public function addNewCoatingMachineDetails()
{ {
$message1 = ''; $message1 = '';
@ -559,7 +605,6 @@ class StockController extends BaseController
$message3 = ''; $message3 = '';
$postData = $this->request->getPost(); $postData = $this->request->getPost();
$date = $postData['date']; $date = $postData['date'];
$shift = $postData['shift']; $shift = $postData['shift'];
@ -578,11 +623,10 @@ class StockController extends BaseController
$this->db->transBegin(); $this->db->transBegin();
try { try {
// Insert into coating machine details table // Insert data into coating machine details table
$insertedId = $this->coatingMachineDetails_model->insert($postData); $insertedId = $this->coatingMachineDetails_model->insert($postData);
if ($insertedId !== false && $insertedId > 0) { if ($insertedId !== false && $insertedId > 0) {
$message1 = 'Coating Machine details updated successfully'; $message1 = 'Coating Machine details updated successfully';
// Update gas stock consumption // Update gas stock consumption
@ -591,30 +635,27 @@ class StockController extends BaseController
$updatedResult = $this->updateGasStockConsumption($dateToBeInserted, $consumption); $updatedResult = $this->updateGasStockConsumption($dateToBeInserted, $consumption);
if ($updatedResult === false || $updatedResult <= 0) { if ($updatedResult === false || $updatedResult <= 0) {
// Explicit failure handling for gas stock update
throw new \Exception('Failed to update gas stock consumption.'); throw new \Exception('Failed to update gas stock consumption.');
} }
$message2 = 'And updated 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..!!"; $message3 = " Warning..!! Kindly Update the next subsequent month Gas Stock If older month Gas Stock Updated..!!";
} else { } else {
throw new \Exception('Failed to insert Coating machine details.'); throw new \Exception('Failed to insert Coating machine details.');
} }
// Handle batch card file uploads
if ($insertedId !== false && $insertedId > 0) { if ($insertedId !== false && $insertedId > 0) {
$batchCardFiles = $this->request->getFileMultiple('batchCard'); $batchCardFiles = $this->request->getFileMultiple('batchCard');
if (!empty($batchCardFiles) && !($batchCardFiles[0]->getError() === UPLOAD_ERR_NO_FILE)) { if (!empty($batchCardFiles) && !($batchCardFiles[0]->getError() === UPLOAD_ERR_NO_FILE)) {
foreach ($batchCardFiles as $file) { foreach ($batchCardFiles as $file) {
if ($file->isValid() && !$file->hasMoved()) { if ($file->isValid() && !$file->hasMoved()) {
$clientGivenName = $file->getClientName(); // User-given filename $clientGivenName = $file->getClientName(); // Original filename
$newName = $file->getRandomName(); $newName = $file->getRandomName();
if ($file->move(WRITEPATH . 'uploads/batchcard', $newName)) { if ($file->move(WRITEPATH . 'uploads/batchcard', $newName)) {
// Only save to DB if file moved successfully // Insert file details into the database
$db = \Config\Database::connect(); $db = \Config\Database::connect();
$builder = $db->table('t_batchcard_files'); $builder = $db->table('t_batchcard_files');
@ -624,27 +665,20 @@ class StockController extends BaseController
'coating_id' => $insertedId 'coating_id' => $insertedId
]; ];
$result = $builder->insert($data); $builder->insert($data);
} }
} }
} }
} }
} }
if ($this->db->transStatus() === false) { if ($this->db->transStatus() === false) {
throw new \Exception('Transaction failed due to database errors.'); throw new \Exception('Transaction failed due to database errors.');
} }
$this->db->transCommit(); $this->db->transCommit();
// Redirect with success message
// Set flashdata for success message
return redirect()->to("/coatingMachineDetails") return redirect()->to("/coatingMachineDetails")
->with('success', $message1 . " " . $message2 . " " . $message3); ->with('success', $message1 . " " . $message2 . " " . $message3);
} catch (\Exception $error) { } catch (\Exception $error) {
@ -655,6 +689,7 @@ class StockController extends BaseController
public function updateCoatingMachineDetails() public function updateCoatingMachineDetails()
{ {
@ -679,32 +714,36 @@ class StockController extends BaseController
$batchCardFiles = $this->request->getFileMultiple('batchCard'); $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) {
// Step 4: Upload new files and insert into DB if ( !empty($batchCardFiles[$index]) && !($batchCardFiles[$index]->getError() === UPLOAD_ERR_NO_FILE)) {
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');
$db = \Config\Database::connect(); if ($file->isValid() && !$file->hasMoved()) {
$builder = $db->table('t_batchcard_files'); $clientGivenName = $file->getClientName(); // User-given filename
$newName = $file->getRandomName(); // Randomized unique filename
if ($file->isValid() && !$file->hasMoved()) { // Move the new file to storage
$clientGivenName = $file->getClientName(); // User-given filename if ($file->move(WRITEPATH . 'uploads/batchcard', $newName)) {
$newName = $file->getRandomName(); // Randomized unique filename // Insert new file record into the database
$data = [
// Move the new file to storage 'client_file_name' => $clientGivenName,
if ($file->move(WRITEPATH . 'uploads/batchcard', $newName)) { 'filename' => $newName,
// Insert new file record into the database 'coating_id' => $id
$data = [ ];
'client_file_name' => $clientGivenName, $builder->insert($data);
'filename' => $newName, }
'coating_id' => $id
];
$builder->insert($data);
} }
} }
} }
} }
} }
if ($updated !== false && $updated > 0) { if ($updated !== false && $updated > 0) {
@ -1020,14 +1059,13 @@ class StockController extends BaseController
private function updateGasStockConsumption($date, $consumption) private function updateGasStockConsumption($date, $consumption)
{ {
// Check if an entry exists for the given date
$resultExists = $this->gasStockDetails_model $resultExists = $this->gasStockDetails_model
->where('date', $date) ->where('date', $date)
->first(); ->first();
if ($resultExists) { if ($resultExists) {
// Ensure the date is in the correct format
if ($date instanceof DateTime) { if ($date instanceof DateTime) {
$date = $date->format('Y-m-d'); $date = $date->format('Y-m-d');
} elseif (!strtotime($date)) { } elseif (!strtotime($date)) {
@ -1036,10 +1074,10 @@ class StockController extends BaseController
$date = date('Y-m-d', strtotime($date)); $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)); $endDate = date('Y-m-t', strtotime($date));
// Fetch all stock entries from the given date till the end of the month
//what happens if the updation is on the last day of the month?
$resultExists = $this->gasStockDetails_model $resultExists = $this->gasStockDetails_model
->where('date >=', $date) ->where('date >=', $date)
->where('date <=', $endDate) ->where('date <=', $endDate)
@ -1049,25 +1087,26 @@ class StockController extends BaseController
$updatedOpeningStock = 0; $updatedOpeningStock = 0;
$updates = []; $updates = [];
// Update stock values for each day in the month
foreach ($resultExists as $index => $result) { foreach ($resultExists as $index => $result) {
if ($index == 0) { if ($index == 0) {
// Update the first entry with new consumption
$result['consumption'] = (float)($result['consumption']) + (float)($consumption); $result['consumption'] = (float)($result['consumption']) + (float)($consumption);
$result['total'] = (float)$result['opening'] + (float)$result['purchaseBharath'] + (float)$result['purchaseIndian']; $result['total'] = (float)$result['opening'] + (float)$result['purchaseBharath'] + (float)$result['purchaseIndian'];
$result['balanceStock'] = $result['total'] - $result['consumption']; $result['balanceStock'] = $result['total'] - $result['consumption'];
$updatedOpeningStock = (int)$result['balanceStock']; $updatedOpeningStock = (int)$result['balanceStock'];
} else { } else {
// Update subsequent entries based on previous balance
$result['opening'] = (float)$updatedOpeningStock; $result['opening'] = (float)$updatedOpeningStock;
$result['total'] = (float)$result['opening'] + (float)$result['purchaseBharath'] + (float)$result['purchaseIndian']; $result['total'] = (float)$result['opening'] + (float)$result['purchaseBharath'] + (float)$result['purchaseIndian'];
$result['balanceStock'] = (float)$result['total'] - (float)$result['consumption']; $result['balanceStock'] = (float)$result['total'] - (float)$result['consumption'];
$updatedOpeningStock = (int)$result['balanceStock']; $updatedOpeningStock = (int)$result['balanceStock'];
} }
$updates[] = $result; $updates[] = $result;
} }
// Perform batch update if there are changes
if (!empty($updates)) { if (!empty($updates)) {
$result = $this->gasStockDetails_model->updateBatch($updates, 'id'); $result = $this->gasStockDetails_model->updateBatch($updates, 'id');
return ($result !== false && $result > 0) ? $result : 0; return ($result !== false && $result > 0) ? $result : 0;
@ -1075,30 +1114,25 @@ class StockController extends BaseController
return 0; return 0;
} }
} else { } else {
// Get the last date of the previous month
$previousMonthDate = new DateTime($date); $previousMonthDate = new DateTime($date);
$previousMonthDate = $previousMonthDate->modify('first day of this month') $previousMonthDate = $previousMonthDate->modify('first day of this month')
->modify('-1 day') ->modify('-1 day')
->format('Y-m-d'); ->format('Y-m-d');
// Check if the previous month's last day entry exists
$previousMonthResultExists = $this->gasStockDetails_model $previousMonthResultExists = $this->gasStockDetails_model
->where('date', $previousMonthDate) ->where('date', $previousMonthDate)
->first(); ->first();
$opening = 0; $opening = 0;
// Set opening stock based on previous month's balance stock
if (!empty($previousMonthResultExists) && isset($previousMonthResultExists['balanceStock'])) { if (!empty($previousMonthResultExists) && isset($previousMonthResultExists['balanceStock'])) {
$opening = $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'); $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'); $endDate = DateTime::createFromFormat('Y-m-d', $date)->modify('last day of this month')->format('Y-m-d');
@ -1115,12 +1149,13 @@ class StockController extends BaseController
$datesInMonth[] = $day->format('Y-m-d'); $datesInMonth[] = $day->format('Y-m-d');
} }
foreach ($datesInMonth as $datesInMonthIndex => $dateInMonth) { // Insert stock records for each day in the month
foreach ($datesInMonth as $dateInMonth) {
//update previousMonthResultExists
$balanceStock = $opening; $balanceStock = $opening;
$consumptionForDate = 0; $consumptionForDate = 0;
if ($dateInMonth == $date) { if ($dateInMonth == $date) {
// Assign the given consumption for the provided date
$consumptionForDate = $consumption; $consumptionForDate = $consumption;
$balanceStock = $opening - $consumption; $balanceStock = $opening - $consumption;
} }
@ -1128,16 +1163,18 @@ class StockController extends BaseController
$inserts[] = [ $inserts[] = [
'date' => $dateInMonth, 'date' => $dateInMonth,
'opening' => $opening, 'opening' => $opening,
'purchaseBharath' => Null, 'purchaseBharath' => null,
'purchaseIndian' => Null, 'purchaseIndian' => null,
'total' => Null, 'total' => null,
'consumption' => $consumptionForDate, 'consumption' => $consumptionForDate,
'balanceStock' => $balanceStock 'balanceStock' => $balanceStock
]; ];
// Update opening for the next day
$opening = $balanceStock; $opening = $balanceStock;
} }
// Perform batch insert if data is available
if (!empty($inserts)) { if (!empty($inserts)) {
$result = $this->gasStockDetails_model->insertBatch($inserts); $result = $this->gasStockDetails_model->insertBatch($inserts);
return ($result !== false && $result > 0) ? $result : 0; return ($result !== false && $result > 0) ? $result : 0;
@ -1150,6 +1187,7 @@ class StockController extends BaseController
//diesel stock details //diesel stock details
public function dieselMachineStockDetails(){ public function dieselMachineStockDetails(){
@ -3272,12 +3310,12 @@ class StockController extends BaseController
*/ */
private function handleGasStockUpdate($existingRow, $newRow) private function handleGasStockUpdate($existingRow, $newRow)
{ {
$existingConsumption = $existingRow['total_gas_consumption']; $existingConsumption = $existingRow['total_gas_consumption']; //eg:400
$updatedConsumption = $newRow['total_gas_consumption']; $updatedConsumption = $newRow['total_gas_consumption']; //eg:500
if ($existingConsumption != $updatedConsumption) { if ($existingConsumption != $updatedConsumption) {
$changeInConsumption = $updatedConsumption - $existingConsumption; $changeInConsumption = $updatedConsumption - $existingConsumption; // 500-400 = 100
$this->updateGasStockConsumption($existingRow['date'], $changeInConsumption); $this->updateGasStockConsumption($existingRow['date'], $changeInConsumption); // +100 will be the change
} }
} }

View File

@ -6,7 +6,7 @@ use CodeIgniter\Model;
class DrierMachineDetailsModel extends Model class DrierMachineDetailsModel extends Model
{ {
protected $table = 't_drierMachineDetails'; protected $table = 't_driermachinedetails';
protected $primaryKey = 'id'; protected $primaryKey = 'id';
protected $useAutoIncrement = true; protected $useAutoIncrement = true;
protected $returnType = 'array'; protected $returnType = 'array';

View File

@ -52,7 +52,7 @@ class Employeedetails_model extends Model
return $query->getResult(); return $query->getResult();
} }
function incomingSilicaSandTestedBy($ConfigID){ function incomingSilicaSandTestedBy(){
$builder = $this->db->table('t_employee_details Emp') $builder = $this->db->table('t_employee_details Emp')
@ -67,7 +67,7 @@ class Employeedetails_model extends Model
} }
function incomingSilicaSandApprovedBy($ConfigID){ function incomingSilicaSandApprovedBy(){
$builder = $this->db->table('t_employee_details Emp') $builder = $this->db->table('t_employee_details Emp')
->select(' Emp.*') ->select(' Emp.*')

View File

@ -6,7 +6,7 @@ use CodeIgniter\Model;
class IncomingSilicaSandDetailsModel extends Model class IncomingSilicaSandDetailsModel extends Model
{ {
protected $table = 't_incomingSilicaSandDetails'; protected $table = 't_incomingsilicasanddetails';
protected $primaryKey = 'id'; protected $primaryKey = 'id';
protected $useAutoIncrement = true; protected $useAutoIncrement = true;
protected $returnType = 'array'; protected $returnType = 'array';

View File

@ -1216,7 +1216,7 @@ class Inwardgateregister_model extends Model
$builder->groupBy('t_igr_details.IGRNO, t_igr_details.MaterialCode') $builder->groupBy('t_igr_details.IGRNO, t_igr_details.MaterialCode')
->join('t_igr_master igrMast', 'igrMast.IGRNO = t_igr_details.IGRNO') ->join('t_igr_master igrMast', 'igrMast.IGRNO = t_igr_details.IGRNO')
->join('t_incomingSilicaSandDetails issd','issd.igrNo_fk = t_igr_details.IGRNO AND issd.materialCode = t_igr_details.MaterialCode','left') ->join('t_incomingsilicasanddetails issd','issd.igrNo_fk = t_igr_details.IGRNO AND issd.materialCode = t_igr_details.MaterialCode','left')
->join('t_materialmaster materialMaster', 'materialMaster.MaterialCode = t_igr_details.MaterialCode') ->join('t_materialmaster materialMaster', 'materialMaster.MaterialCode = t_igr_details.MaterialCode')
->join('t_configdetails cd','cd.key = materialMaster.Category','left') ->join('t_configdetails cd','cd.key = materialMaster.Category','left')
->join('t_purchaseorder_master poMaster', 'poMaster.PONO = igrMast.PONO', 'left') ->join('t_purchaseorder_master poMaster', 'poMaster.PONO = igrMast.PONO', 'left')

View File

@ -147,6 +147,10 @@ class Rawmaterialdetails_model extends Model
$builder = $this->db->table('t_materialmaster') $builder = $this->db->table('t_materialmaster')
->select('MaterialCode') ->select('MaterialCode')
/** Caution changing config key is posing risk to entire stock module * */
// 248 is the config detail key for silica sand
->where('Category', '248') ->where('Category', '248')
->orderBy('CreatedDate', 'desc'); ->orderBy('CreatedDate', 'desc');
$query = $builder->get(); $query = $builder->get();
@ -159,6 +163,10 @@ class Rawmaterialdetails_model extends Model
$builder = $this->db->table('t_materialmaster') $builder = $this->db->table('t_materialmaster')
->select('MaterialCode') ->select('MaterialCode')
/** Caution changing config key is posing risk to entire stock module * */
// 328 is the config detail key for silica sand
->where('Category', '328') ->where('Category', '328')
->orderBy('CreatedDate', 'desc'); ->orderBy('CreatedDate', 'desc');
$query = $builder->get(); $query = $builder->get();

View File

@ -25,7 +25,6 @@
"kint-php/kint": "^5.0.4", "kint-php/kint": "^5.0.4",
"mikey179/vfsstream": "^1.6", "mikey179/vfsstream": "^1.6",
"nexusphp/cs-config": "^3.6", "nexusphp/cs-config": "^3.6",
"phpunit/phpunit": "^10.5.16",
"predis/predis": "^1.1 || ^2.0" "predis/predis": "^1.1 || ^2.0"
}, },
"suggest": { "suggest": {