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

@ -146,25 +146,38 @@ class StockController extends BaseController
//incoming Silica Sand Details starts
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') {
//getting remark value which is used to specify the issd entry is accepted/rejected/conditionally accepted..
$remark = $this->request->getPost('remark');
$month = $this->request->getPost('month');
//formatting the date format of Jan-2025 to 2025-01
$date = DateTime::createFromFormat('M-Y', $month);
$formattedDate = $date->format('Y-m');
$month = $formattedDate;
//setting session for any month change
$session = session ();
$session->set('stock_month',$month);
} else {
//if request is in get method getting remark in query params in new_header.php file(navbar)
$remark = $this->request->getVar('remark');
$session = session();
@ -172,21 +185,25 @@ class StockController extends BaseController
$month = $session->get('stock_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;
//set page title
$this->global['pageTitle'] = 'Incoming Silica Sand Details';
$materialCodes = [];
//getting all silica sand raw materials material code
$silicaSandMaterialCodes = $this->rawmaterialdetails_model->getAllSilicaRawMaterialCode();
$materialCodes [] = $silicaSandMaterialCodes;
//getting all waste Core Sand Material Codes
$wasteCoreSandMaterialCodes = $this->rawmaterialdetails_model->getAllWasteCoreSandMaterialCode();
$materialCodes [] = $wasteCoreSandMaterialCodes;
@ -195,6 +212,7 @@ class StockController extends BaseController
if (!empty($materialCodes)) {
//remark filter may apply or not
$data['igrDetails'] = $this->inwardGateRegister_model->findIgrDetailsForIncomingSilicaSand($materialCodes, $month, $remark);
} else {
$data['igrDetails'] = [];
@ -202,11 +220,11 @@ class StockController extends BaseController
$data['testedBy'] = [];
$DesignationConfigID = 'C010';
//['lab assistant', 'factory manager', 'lab head']
$data['testedBy'] = $this->employeedetails_model->incomingSilicaSandTestedBy();
$data['testedBy'] = $this->employeedetails_model->incomingSilicaSandTestedBy($DesignationConfigID);
$data['approvedBy'] = $this->employeedetails_model->incomingSilicaSandApprovedBy($DesignationConfigID);
//['factory manager', 'lab head']
$data['approvedBy'] = $this->employeedetails_model->incomingSilicaSandApprovedBy();
$date = DateTime::createFromFormat('Y-m', $month);
@ -220,6 +238,7 @@ class StockController extends BaseController
return $this->loadViews("stock/incomingSilicaSandDetails", $this->global, $data, NULL);
}
public function updateIncomingSilicaSandDetails()
{
@ -290,6 +309,8 @@ class StockController extends BaseController
echo "Data Saved Successfully";
}
//This is particulary updated by the lab technichians
public function updateLabReport()
{
@ -353,115 +374,143 @@ class StockController extends BaseController
//Drier machine details
public function drierMachineDetails()
{
//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..!!
// 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.
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');
$date = DateTime::createFromFormat('M-Y', $currentMonth); //in M-Y format
$formattedDate = $date->format('Y-m'); //in Y-m format
$session = session ();
$session->set('stock_month',$formattedDate);
} else {
// 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');
$session = session();
$session->set('stock_month', $formattedDate);
} else {
$session = session();
$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)) {
$currentMonth = date('M-Y'); // Default to the current month
}else{
$currentMonth = DateTime::createFromFormat('Y-m', $currentMonth); // in Y-m format
$currentMonth = $currentMonth->format('M-Y'); // in M-Y format
$currentMonth = date('M-Y');
} else {
// 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');
}
}
// Retrieve the list of dates for the selected month in database-compatible format
$monthData = $this->getMonthDatesFromInput($currentMonth);
$isActiveFilter = 1 ;
$data['startDate'] = $monthData[0]['database'];
$data['endDate'] = $monthData[count($monthData) - 1]['database'];
// Set the active filter for suppliers (1 means active suppliers will be fetched)
$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['supplierData'] = $this->supplier_model->supplierlisting($isActiveFilter);
// Retrieve drier machine details for the selected date range
$data['drierDetails'] = $this->drierMachineDetails_model
->where('date >=', $data['startDate'])
->where('date <=', $data['endDate'])
->orderBy('date','asc')
->findAll();
->where('date >=', $data['startDate'])
->where('date <=', $data['endDate'])
->orderBy('date', 'asc')
->findAll();
$data['datefordropdown'] = $currentMonth;
// Set the page title for display
$this->global['pageTitle'] = 'Drier Details';
$this->loadViews("stock/drierMachineDetails", $this->global, $data, NULL);
}
public function addOrEditdrierMachineDetails()
{
// Retrieve form data from the POST request
$data = $this->request->getPost();
$data = $this->request->getPost();
$drierData[] = $this->mapDrierEntry($data);
// Map the received data into a structured format using the helper function `mapDrierEntry`
$drierData[] = $this->mapDrierEntry($data);
// Begin a database transaction to ensure atomicity
$this->db->transBegin();
try {
// 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)
$existingRow = $row['id'];
$data = $row;
$data = $row;
if (($existingRow)) {
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;
} else {
// If it's a new record, update gas stock consumption before inserting
$this->updateGasStockConsumption($data['date'], $data['total_gas_consumption']);
$inserts[] = $data;
}
}
if (!empty($inserts)) {
$this->drierMachineDetails_model->insertBatch($inserts);
}
if (!empty($updates)) {
$this->drierMachineDetails_model->updateBatch($updates, 'id');
}
// Check if the transaction encountered any database errors
if ($this->db->transStatus() === false) {
throw new \Exception('Transaction failed due to database error.');
}
$this->db->transCommit();
return redirect()->to("/drierMachineDetails")->with('success', "Data Saved Successfully");
} catch (\Exception $error) {
$this->db->transRollback();
return redirect()->back()->with('error', ' ' . $error->getMessage());
}
return redirect()->to("/drierMachineDetails")->with('success', "Data Saved Successfully");
} 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.
*/
@ -491,160 +540,145 @@ class StockController extends BaseController
//Coating Machine Details starts
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('M-Y', $month);
$formattedDate = $date->format('Y-m');
$month = $formattedDate;
$session = session ();
$session->set('stock_month',$month);
} else {
// 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'); // Default to the current month
$month = date('Y-m');
}
}
$data['month'] = $month ;
$this->global['pageTitle'] = 'Coating Machine Details ';
$data['month'] = $month;
$this->global['pageTitle'] = 'Coating Machine Details';
// Define start and end date for the selected month
$startDate = "$month-01";
$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();
->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();
// Convert month format from "Y-m" to "M-Y" for display
$date = DateTime::createFromFormat('Y-m', $month);
$formattedDate = $date->format('M-Y');
$data['month'] = $formattedDate;
// Load the view with the required data
return $this->loadViews("stock/CoatingMachineDetail", $this->global, $data, NULL);
}
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)) {
return redirect()->back()->with('error', 'Already same shift exists on the same date ..!!');
}
// Start transaction
$this->db->transBegin();
try {
// Insert into coating machine details table
// 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) {
// 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..!!";
} 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(); // User-given filename
$clientGivenName = $file->getClientName(); // Original filename
$newName = $file->getRandomName();
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();
$builder = $db->table('t_batchcard_files');
$data = [
'client_file_name' => $clientGivenName,
'filename' => $newName,
'coating_id' => $insertedId
];
$result = $builder->insert($data);
$builder->insert($data);
}
}
}
}
}
if ($this->db->transStatus() === false) {
throw new \Exception('Transaction failed due to database errors.');
}
$this->db->transCommit();
// Set flashdata for success message
// Redirect with success message
return redirect()->to("/coatingMachineDetails")
->with('success', $message1 . " " . $message2 . " " . $message3);
} catch (\Exception $error) {
@ -652,6 +686,7 @@ class StockController extends BaseController
return redirect()->back()->with('error', ' ' . $error->getMessage());
}
}
@ -679,32 +714,36 @@ class StockController extends BaseController
$batchCardFiles = $this->request->getFileMultiple('batchCard');
// Step 4: Upload new files and insert into DB
foreach ($batchCardFiles as $index => $file) {
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
// Move the new file to storage
if ($file->move(WRITEPATH . 'uploads/batchcard', $newName)) {
// Insert new file record into the database
$data = [
'client_file_name' => $clientGivenName,
'filename' => $newName,
'coating_id' => $id
];
$builder->insert($data);
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
// Move the new file to storage
if ($file->move(WRITEPATH . 'uploads/batchcard', $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) {
@ -1020,14 +1059,13 @@ class StockController extends BaseController
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)) {
@ -1035,39 +1073,40 @@ class StockController extends BaseController
} 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));
//what happens if the updation is on the last day of the month?
// 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;
@ -1075,69 +1114,67 @@ class StockController extends BaseController
return 0;
}
} 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');
}
foreach ($datesInMonth as $datesInMonthIndex => $dateInMonth) {
//update previousMonthResultExists
// 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,
'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;
@ -1146,6 +1183,7 @@ class StockController extends BaseController
}
}
}
@ -3272,12 +3310,12 @@ class StockController extends BaseController
*/
private function handleGasStockUpdate($existingRow, $newRow)
{
$existingConsumption = $existingRow['total_gas_consumption'];
$updatedConsumption = $newRow['total_gas_consumption'];
$existingConsumption = $existingRow['total_gas_consumption']; //eg:400
$updatedConsumption = $newRow['total_gas_consumption']; //eg:500
if ($existingConsumption != $updatedConsumption) {
$changeInConsumption = $updatedConsumption - $existingConsumption;
$this->updateGasStockConsumption($existingRow['date'], $changeInConsumption);
$changeInConsumption = $updatedConsumption - $existingConsumption; // 500-400 = 100
$this->updateGasStockConsumption($existingRow['date'], $changeInConsumption); // +100 will be the change
}
}

View File

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

View File

@ -52,7 +52,7 @@ class Employeedetails_model extends Model
return $query->getResult();
}
function incomingSilicaSandTestedBy($ConfigID){
function incomingSilicaSandTestedBy(){
$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')
->select(' Emp.*')

View File

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

View File

@ -1216,7 +1216,7 @@ class Inwardgateregister_model extends Model
$builder->groupBy('t_igr_details.IGRNO, t_igr_details.MaterialCode')
->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_configdetails cd','cd.key = materialMaster.Category','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')
->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')
->orderBy('CreatedDate', 'desc');
$query = $builder->get();
@ -159,6 +163,10 @@ class Rawmaterialdetails_model extends Model
$builder = $this->db->table('t_materialmaster')
->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')
->orderBy('CreatedDate', 'desc');
$query = $builder->get();

View File

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