diff --git a/app/Config/Routes.php b/app/Config/Routes.php index 107ed188..949b564f 100755 --- a/app/Config/Routes.php +++ b/app/Config/Routes.php @@ -43,9 +43,9 @@ $routes->get('user/deleteUser', 'User::deleteUser'); $routes->get('user/reActivateUser', 'User::reActivateUser'); // Supplier Routes -$routes->get('supplierlisting', 'Supplier::index'); // list supplier +$routes->match(["GET","POST"],'supplierlisting', 'Supplier::index'); // list supplier $routes->add('addsupplier', 'Supplier::addsupplier');//load add supplier page -$routes->get('viewsupplier', 'Supplier::viewsupplier');// load edit supplier page +$routes->get('viewsupplier', 'Supplier::viewsupplier'); $routes->post('editsupplier', 'Supplier::updatesupplierdetails'); //save supplier details $routes->post('addNewsupplier', 'Supplier::savesupplierdetails'); // update supplier details $routes->post('supplierExist', 'Supplier::checksupplier'); @@ -68,7 +68,7 @@ $routes->post('deleteMaterial', 'Rawmaterialdetails::deleteMaterial'); $routes->post('reActivateMaterial', 'Rawmaterialdetails::reActivateMaterial'); // Cost Center Routes -$routes->get('costListing', 'CostCenter::index'); +$routes->match(['GET','POST'],'costListing', 'CostCenter::index'); $routes->post('fetchCostCenterDetails', 'CostCenter::fetchCostCenterDetails');// for Ajax both add and edit.... $routes->get('reActivateCostCenter', 'CostCenter::reActivateCostCenter'); $routes->get('deleteCostCenter', 'CostCenter::deleteCostCenter'); @@ -98,7 +98,7 @@ $routes->post('getDriver', 'Driver::getDriver'); $routes->match(['GET', 'POST', 'PUT', 'DELETE'], 'driverPrintPdf', 'Driver::driverPrintPdf'); // Asset Detail Routes -$routes->get('assetListing', 'Assetdetails::assetListing'); +$routes->match(['GET','POST'],'assetListing', 'Assetdetails::assetListing'); $routes->get('addasset', 'Assetdetails::addasset'); $routes->post('assetdetails/getpodetails', 'Assetdetails::getpodetails'); $routes->post('assetdetails/getline', 'Assetdetails::getline'); @@ -153,7 +153,7 @@ $routes->get('configurationctrl/deleteConfig', 'Configurationctrl::deleteConfig' $routes->get('configurationctrl/reActivateConfig', 'Configurationctrl::reActivateConfig'); // Department Master Routes -$routes->get('departmentListing', 'Department::index'); +$routes->match(["GET","POST"],'departmentListing', 'Department::index'); $routes->get('adddepartment', 'Department::adddepartment'); $routes->post('savedepartment', 'Department::savedepartment'); $routes->get('editOlddepartment', 'Department::viewdepartment'); @@ -297,10 +297,10 @@ $routes->match(['GET', 'POST', 'PUT', 'DELETE'], 'storerequisitionlisting', 'Sto $routes->match(['GET', 'POST', 'PUT', 'DELETE'], 'EditStoreRequisition', 'Storerequisitioncontroller::EditStoreRequistion'); // Application IGR Routes -$routes->get('AddIGR', 'Inwardgateregister::addIGR'); // ADD IGR page - working -$routes->get('ViewIGR', 'Inwardgateregister::viewIGR'); // View IGR PAGE - Working +$routes->get( 'AddIGR', 'Inwardgateregister::addIGR'); // ADD IGR page - working +$routes->get( 'ViewIGR', 'Inwardgateregister::viewIGR'); // View IGR PAGE - Working $routes->post('ViewIGR', 'Inwardgateregister::viewIGR');//for filter purpose -$routes->get('accountsDashboard', 'Inwardgateregister::accountsDashboard'); // View IGR PAGE - Working +$routes->get( 'accountsDashboard', 'Inwardgateregister::accountsDashboard'); // View IGR PAGE - Working $routes->post('ViewIGRDetails', 'Inwardgateregister::viewIGRDetails'); $routes->post('GetIGRLineItemDetails', 'Inwardgateregister::getIGRLineItemDetails'); $routes->post('SaveIGR', 'Inwardgateregister::SaveIGR');// Save IGR PAGE - Working @@ -311,10 +311,13 @@ $routes->post('getCostCenterData', 'Inwardgateregister::getCostCenterData'); $routes->post('ViewIGRfile', 'Inwardgateregister::ViewIGRfile'); $routes->post('getAdditionalIGRFile', 'Inwardgateregister::getAdditionalIGRFile'); $routes->post('deleteAdditionalIGRFile', 'Inwardgateregister::deleteAdditionalIGRFile'); -$routes->get('download-files/(:segment)', 'Inwardgateregister::downloadFilesAsZip/$1'); +$routes->get( 'download-files/(:segment)', 'Inwardgateregister::downloadFilesAsZip/$1'); $routes->post('inwardgateregister/edituploadfile', 'Inwardgateregister::edituploadfile'); $routes->post('getIGRRemarks', 'Inwardgateregister::getIGRRemarks'); $routes->post('saveIGRRemarks', 'Inwardgateregister::saveIGRRemarks'); +$routes->post('updateGasShortage','Inwardgateregister::updateGasShortage'); +$routes->post('gasShortageList','Inwardgateregister::gasShortageList'); +$routes->post('getGasShortageDetail',"Inwardgateregister::getGasShortageDetail"); // Non IGR / Expense @@ -442,7 +445,7 @@ $routes->match(['GET', 'POST'], 'sales_report', 'Sales::sales_report'); $routes->match(['GET', 'POST'],'credit_notes', 'Sales::credit_notes'); // transporter Routes -$routes->get('transporterListing', 'Supplier::transporterListing'); +$routes->match(['GET', 'POST'],'transporterListing', 'Supplier::transporterListing'); $routes->post('fetchTransporterDetails', 'Supplier::fetchTransporterDetails');// for Ajax both add and edit.... $routes->get('deleteTransporter', 'Supplier::deleteTransporter'); $routes->get('reActivateTransporter', 'Supplier::reActivateTransporter'); @@ -452,6 +455,7 @@ $routes->post('checkTransporter', 'Supplier::checkTransporter'); $routes->post('createFactoryMachineMasterDetails', 'FactoryMachineController::createFactoryMachineMasterDetails'); $routes->get('readFactoryMachineMasterDetails', 'FactoryMachineController::readFactoryMachineMasterDetails'); +$routes->post('readFactoryMachineMasterDetails', 'FactoryMachineController::readFactoryMachineMasterDetails'); $routes->get('readFactoryMachineMasterDetailsById', 'FactoryMachineController::readFactoryMachineMasterDetailsById'); $routes->post('updateFactoryMachineMasterDetails', 'FactoryMachineController::updateFactoryMachineMasterDetails'); $routes->get('deleteFactoryMachineMasterDetails', 'FactoryMachineController::deleteFactoryMachineMasterDetails'); @@ -517,5 +521,7 @@ $routes->post('updateTrpSandUseStockDetails', 'StockController::updateTrpSandUse //trp production stock details $routes->match(['GET', 'POST'], 'trpProductionDetails', 'StockController::trpProductionDetails'); $routes->post('updateTrpProductionDetails', 'StockController::updateTrpProductionDetails'); +//trp abstract +$routes->post('updateAbstractDetails','StockController::updateAbstractDetails'); diff --git a/app/Controllers/Assetdetails.php b/app/Controllers/Assetdetails.php index 8d512fcb..ec4fe370 100755 --- a/app/Controllers/Assetdetails.php +++ b/app/Controllers/Assetdetails.php @@ -50,9 +50,22 @@ class Assetdetails extends BaseController */ function assetListing() { + $isActiveFilter = 1 ; // default showing active data + $showArchive = 0 ; // + + if ($this->request->getMethod() === 'POST') { + + $showArchive = $this->request->getPost('showArchive'); + //reversing condition that when user wants deleted data to be shown then we are making active filter 0 + if($showArchive){ + $isActiveFilter = 0; + } + } + + $data['showArchive'] = $showArchive; - $data['userRecords'] = $this->assetdetails_model->assetListing(); + $data['userRecords'] = $this->assetdetails_model->assetListing($isActiveFilter); $this->global['pageTitle'] = 'Asset List'; //print_r($data);die(); diff --git a/app/Controllers/CostCenter.php b/app/Controllers/CostCenter.php index 478b0bfa..fd796a8b 100755 --- a/app/Controllers/CostCenter.php +++ b/app/Controllers/CostCenter.php @@ -45,7 +45,21 @@ class CostCenter extends BaseController */ public function index() { - $data['userRecords'] = $this->costcenter_model->CostListing(); + + $isActiveFilter = 1 ; // default showing active data + $showArchive = 0 ; // + + if ($this->request->getMethod() === 'POST') { + + $showArchive = $this->request->getPost('showArchive'); + //reversing condition that when user wants deleted data to be shown we are making active filter + if($showArchive){ + $isActiveFilter = 0; + } + } + + $data['showArchive'] = $showArchive; + $data['userRecords'] = $this->costcenter_model->CostListing($isActiveFilter); $this->global['pageTitle'] = 'Cost List'; $this->loadViews("costListing", $this->global, $data, NULL); diff --git a/app/Controllers/Department.php b/app/Controllers/Department.php index 79d4d956..fa607f43 100755 --- a/app/Controllers/Department.php +++ b/app/Controllers/Department.php @@ -48,20 +48,25 @@ class Department extends BaseController public function index() { - // if($this->isAdmin() == TRUE) - // { - // $this->loadThis(); - // } - // else - // { + + $isActiveFilter = 1 ; // default showing active data + $showArchive = 0 ; // + + if ($this->request->getMethod() === 'POST') { + + $showArchive = $this->request->getPost('showArchive'); + //reversing condition that when user wants deleted data to be shown then we are making active filter 0 + if($showArchive){ + $isActiveFilter = 0; + } + } + + $data['showArchive'] = $showArchive; + + $this->department_model = new department_model(); - //$searchText = $this->request->getPost('searchText'); - //$data['searchText'] = $searchText; - //$count = $this->department_model->departmentListing($searchText); - //$returns = $this->paginationCompress ( "departmentListing/", $count, 20 ); - - $data['userRecords'] = $this->department_model->departmentListing(); //$searchText, $returns["page"], $returns["segment"]); + $data['userRecords'] = $this->department_model->departmentListing($isActiveFilter); //$searchText, $returns["page"], $returns["segment"]); $this->global['pageTitle'] = 'Department Listing'; diff --git a/app/Controllers/Emergencypurchaseorder.php b/app/Controllers/Emergencypurchaseorder.php index d4a143a2..62ba5781 100755 --- a/app/Controllers/Emergencypurchaseorder.php +++ b/app/Controllers/Emergencypurchaseorder.php @@ -125,7 +125,7 @@ class Emergencypurchaseorder extends BaseController // print_r($this->request->getPost());die; $txtRowCount = $this->request->getPost('txtRowCount'); $POdt = $this->request->getPost('PODate'); - $PODate = get_date_time_format($POdt); + $PODate = get_date_time_dynamical_format('d-m-Y','Y-m-d',"$POdt"); $SupplierID = $this->request->getPost('drpSupplier'); $DeliveryAddr = $this->request->getPost('DeliveryAddr'); $CostCenterName = $this->request->getPost('CostCenterName'); @@ -369,7 +369,7 @@ class Emergencypurchaseorder extends BaseController $POdt = $this->request->getPost('PODate'); - $PODate = get_date_time_format($POdt); + $PODate = get_date_time_dynamical_format('d-m-Y','Y-m-d',"$POdt"); $SupplierID = $this->request->getPost('drpSupplier'); $DeliveryAddr = $this->request->getPost('DeliveryAddr'); $dt = $this->request->getPost('Deliverydt'); diff --git a/app/Controllers/Expense.php b/app/Controllers/Expense.php index 4483e649..4d4a61d6 100755 --- a/app/Controllers/Expense.php +++ b/app/Controllers/Expense.php @@ -25,6 +25,8 @@ class Expense extends BaseController public function index() { + + $isActiveFilter = 1 ; if ($this->request->getMethod() === 'GET') { @@ -38,7 +40,7 @@ class Expense extends BaseController } $data['expense_list'] = $this->expense_model->getAllExpense($fromDate,$toDate); - $data['supplier_list'] = json_encode($this->supplier_model->supplierlisting()); + $data['supplier_list'] = json_encode($this->supplier_model->supplierlisting($isActiveFilter)); $this->global['pageTitle'] = 'Non IGR / Expense List'; $data['fromDate'] = date('d-m-Y', strtotime($fromDate)); $data['toDate'] = date('d-m-Y', strtotime($toDate)); diff --git a/app/Controllers/FactoryMachineController.php b/app/Controllers/FactoryMachineController.php index 002f78dd..aac84358 100644 --- a/app/Controllers/FactoryMachineController.php +++ b/app/Controllers/FactoryMachineController.php @@ -80,9 +80,25 @@ class FactoryMachineController extends BaseController public function readFactoryMachineMasterDetails(){ + + $isActiveFilter = 1 ; // default showing active data + $showArchive = 0 ; // + + if ($this->request->getMethod() === 'POST') { + + $showArchive = $this->request->getPost('showArchive'); + //reversing condition that when user wants deleted data to be shown then we are making active filter 0 + if($showArchive){ + $isActiveFilter = 0; + } + } + + $data['showArchive'] = $showArchive; + $this->global['pageTitle'] = 'Factory Machine Master Details'; $data['masterData'] = $this->factoryMachineMaster_model + ->where('is_active',$isActiveFilter) ->orderBy('created_at','DESC') ->findAll(); diff --git a/app/Controllers/Inwardgateregister.php b/app/Controllers/Inwardgateregister.php index 1df68778..b709be63 100755 --- a/app/Controllers/Inwardgateregister.php +++ b/app/Controllers/Inwardgateregister.php @@ -8,6 +8,7 @@ use CodeIgniter\Validation\Exceptions\ValidationException; use App\Models\Inwardgateregister_model; use App\Models\IGRRemarks_model; +use App\Models\GasShortageModel; use App\Helpers\Notification; use DateTime; @@ -25,6 +26,7 @@ class Inwardgateregister extends BaseController { protected $inwardgateregister_model; protected $IGRRemarks_model; + protected $gasShortage_model; protected $session; protected $logger; @@ -37,6 +39,7 @@ class Inwardgateregister extends BaseController parent::__construct(); $this->inwardgateregister_model = new Inwardgateregister_model(); $this->IGRRemarks_model = new IGRRemarks_model(); + $this->gasShortage_model = new GasShortageModel(); $this->session = session(); helper('form'); //$this->load->library('form_validation'); @@ -688,6 +691,7 @@ function viewIGRDetails() $IGRNO = $this->request->getPost('id'); $data['details'] = $this->inwardgateregister_model->viewigr($IGRNO); + $TaxInPercentage = 0; for ($i = 0; $i < count($data['details']); $i++) { $details = $data['details'][$i]; @@ -1474,4 +1478,62 @@ function updateIGRWeight(){ } } + + + public function gasShortageList(){ + + $postData = $this->request->getPost(); + + $allShortages = $this->gasShortage_model->where('invoiceNo',$postData['invoiceNo'])->findAll(); + + return $this->response->setJSON(['status' => 'success', 'data' => $allShortages]); + + + } + + + public function getGasShortageDetail(){ + + $postData = $this->request->getPost(); + + $shortage = $this->gasShortage_model->where('id',$postData['id'])->find(); + + return $this->response->setJSON(['status' => 'success', 'data' => $shortage]); + + } + + + + public function updateGasShortage() + { + $postData = $this->request->getPost(); + + // Validate required data + if (!$postData) { + return $this->response->setJSON(['status' => 'error', 'message' => 'Invalid request. No data received.']); + } + + // Validate required fields for adding + if ( !isset($postData['invoiceNo']) ) { + return $this->response->setJSON(['status' => 'error', 'message' => 'Missing required fields: invoice No.']); + } + + // Handle update (edit) + if (isset($postData["id"])) { + return $this->gasShortage_model->update($postData["id"], $postData) + ? $this->response->setJSON(['status' => 'success', 'message' => 'Gas shortage details updated successfully.']) + : $this->response->setJSON(['status' => 'error', 'message' => 'Failed to update gas shortage details.']); + } + + // Insert new shortage (add) + return ($insertId = $this->gasShortage_model->insert($postData)) + ? $this->response->setJSON(['status' => 'success', 'message' => 'Gas shortage details added successfully.', 'data' => ['id' => $insertId]]) + : $this->response->setJSON(['status' => 'error', 'message' => 'Failed to save gas shortage details.']); + + } + + + + + } \ No newline at end of file diff --git a/app/Controllers/Payslip.php b/app/Controllers/Payslip.php index f790bb11..2adae210 100755 --- a/app/Controllers/Payslip.php +++ b/app/Controllers/Payslip.php @@ -801,10 +801,10 @@ class Payslip extends BaseController $loan = $Balance_Amount; } - $empSalaryAdd = $final_salary_amount+$shed+$diesel; + $empSalaryAdd = $final_salary_amount; $empSalarySub = $loan; - $salaryInCurrentday = $empSalaryAdd - $empSalarySub; - $load_driver_data[$i]->driver_final_payment = $salaryInCurrentday; + // $salaryInCurrentday = $empSalaryAdd - $empSalarySub; + // $load_driver_data[$i]->driver_final_payment = $salaryInCurrentday; $load_driver_data[$i]->payroll_id = $monthly_pay_array[$driver_id]->payroll_id; $load_driver_data[$i]->Festival_Bonus = $monthly_pay_array[$driver_id]->Festival_Bonus; @@ -871,8 +871,8 @@ class Payslip extends BaseController $empSalaryAdd = $final_salary_amount; $empSalarySub = $loan; - $salaryInCurrentday = $empSalaryAdd - $empSalarySub; - $load_driver_data[$i]->driver_final_payment = $salaryInCurrentday+$shed+$diesel; + // $salaryInCurrentday = $empSalaryAdd - $empSalarySub; + // $load_driver_data[$i]->driver_final_payment = $salaryInCurrentday+$shed+$diesel; $load_driver_data[$i]->total_cal_days = $get_last_date_of_the_month; } @@ -1168,6 +1168,7 @@ class Payslip extends BaseController $EmpID = $j['Emp ID']; $is_driver = $this->driver_model->getDriverName($EmpID,1); $DaysWorked = $j['Days Worked']; + $NoTrips = isset($j['Number Of Trips']) ? $j['Number Of Trips'] : 0.00 ; $TotalCalDays = isset($j['Total Days']) ? $j['Total Days'] : 0.00 ; $ActualSalary = isset($j['Basic Salary']) ? $j['Basic Salary'] : 0.00 ; $WorkedSalary = isset($j['Worked Salary']) ? $j['Worked Salary'] : 0.00 ; @@ -1228,12 +1229,14 @@ class Payslip extends BaseController $drivermonthlypaydata = array( 'month_year'=>$month, 'driver_id'=>$EmpID, - 'no_of_loads'=>(strpos($TotalCalDays, "(trip)") !== false) ? explode(" ", $TotalCalDays)[0] : 0, + 'TotalCalDays' => $TotalCalDays, + 'no_of_loads'=>(strpos($NoTrips, "(trip)") !== false) ? explode(" ", $NoTrips)[0] : 0, 'monthly_food_amount'=>$Food, 'total_diesel_amount'=>$Diesel, 'total_shed_amount'=>$Shed, 'monthly_salary_amount'=>($Basic+$Food), 'final_payment'=>$Estimate, + 'BASIC'=>$Basic, 'HRA'=>$HRA, 'ESI'=>$ESI, 'PF'=>$PF, @@ -1419,8 +1422,10 @@ class Payslip extends BaseController $currentDayBasic = isset($Data['PayDetails'][0]->monthly_salary_amount) ? $Data['PayDetails'][0]->monthly_salary_amount : 0; $PF_Rate = $Data['PayDetails'][0]->PF_Rate; $ESI_Rate = $Data['PayDetails'][0]->ESI_Rate; - $Data['esi_amount'] = ($Data['PayDetails'][0]->esi_applicable == 1) ? $currentDayBasic * $ESI_Rate / 100 : 0; - $Data['pf_amount'] = ($Data['PayDetails'][0]->pf_applicable == 1) ? $currentDayBasic * $PF_Rate / 100 : 0; + // $Data['esi_amount'] = ($Data['PayDetails'][0]->esi_applicable == 1) ? $currentDayBasic * $ESI_Rate / 100 : 0; + // $Data['pf_amount'] = ($Data['PayDetails'][0]->pf_applicable == 1) ? $currentDayBasic * $PF_Rate / 100 : 0; + $Data['esi_amount'] = ($Data['PayDetails'][0]->esi_applicable == 1) ? $Data['PayDetails'][0]->ESI : 0; + $Data['pf_amount'] = ($Data['PayDetails'][0]->pf_applicable == 1) ? $Data['PayDetails'][0]->PF : 0; $html = view("driverPayslipGeneratePrint", $Data); }else{ //echo "EmpID" . $EmpID; diff --git a/app/Controllers/Purchaseorder.php b/app/Controllers/Purchaseorder.php index ee194634..dc0be372 100755 --- a/app/Controllers/Purchaseorder.php +++ b/app/Controllers/Purchaseorder.php @@ -3068,7 +3068,6 @@ class Purchaseorder extends BaseController $this->purchaseorder_model->insertlogpo($logpo); } } - // print_r($this->request->getPost());die; for ($i = 1; $i <= $RowCount; $i++) { $MaterialCode = $this->request->getPost('materialCode' . $i); diff --git a/app/Controllers/Rawmaterialdetails.php b/app/Controllers/Rawmaterialdetails.php index 679b5cec..ef947deb 100755 --- a/app/Controllers/Rawmaterialdetails.php +++ b/app/Controllers/Rawmaterialdetails.php @@ -66,9 +66,22 @@ class Rawmaterialdetails extends BaseController function rawmaterialListing() { - $this->rawmaterialdetails_model = new rawmaterialdetails_model();; + $isActiveFilter = 1 ; // default showing active data + $showArchive = 0 ; // - $data['userRecords'] = $this->rawmaterialdetails_model->rawmaterialListing(); + if ($this->request->getMethod() === 'POST') { + + $showArchive = $this->request->getPost('showArchive'); + //reversing condition that when user wants deleted data to be shown we are making active filter + if($showArchive){ + $isActiveFilter = 0; + } + } + + $this->rawmaterialdetails_model = new rawmaterialdetails_model(); + + $data['userRecords'] = $this->rawmaterialdetails_model->rawmaterialListing($isActiveFilter); + $data['showArchive'] = $showArchive ; $data['materialCategoryList']= $this->materialCategories_model->where('is_active',1)->findAll(); $this->global['pageTitle'] = 'RawMaterial Listing'; diff --git a/app/Controllers/StockController.php b/app/Controllers/StockController.php index c3b26a66..77651838 100644 --- a/app/Controllers/StockController.php +++ b/app/Controllers/StockController.php @@ -17,14 +17,16 @@ use App\Models\BagStockDetailsModel; use App\Models\DustAndRoughModel; use App\Models\ResinStockModel; use App\Models\GasStockModel; -use App\Models\TrpAbstract; -use App\Models\TrpAbstractParticulars; use App\Models\TrpSandUseStockModel; use App\Models\TrpProductionModel; use App\Models\TrpProductionMaintenanceModel; use App\Models\TrpProductionWasteModel; use App\Models\Employeedetails_model; use App\Models\PowerConsumptionSummaryModel; +use App\Models\MonthWiseMaterialInStockModel; +use App\Models\MonthWiseMachinesInStockModel; +use App\Models\TrpAbstractModel; + @@ -68,9 +70,11 @@ class StockController extends BaseController protected $employeedetails_model; - protected $trpAbstractParticularsModel ; + protected $monthWiseMaterialInStockModel ; - protected $trpAbstractModel ; + protected $monthWiseMachineInStockModel ; + + protected $trpAbstract_model ; /** @@ -120,10 +124,12 @@ class StockController extends BaseController $this->employeedetails_model = new Employeedetails_model(); $this->powerConsumptionSummary_model = new PowerConsumptionSummaryModel(); + + $this->monthWiseMaterialInStockModel = new MonthWiseMaterialInStockModel(); - $this->trpAbstractParticularsModel = new TrpAbstractParticulars(); + $this->monthWiseMachineInStockModel = new MonthWiseMachinesInStockModel(); - $this->trpAbstractModel = new TrpAbstract(); + $this->trpAbstract_model = new TrpAbstractModel(); $this->session = session(); @@ -137,583 +143,2293 @@ class StockController extends BaseController // } - //Coating Machine Details starts - public function loadView_coatingMachineDetails() - { + //incoming Silica Sand Details starts + public function loadView_incomingSilicaSandDetails() + { - if ($this->request->getMethod() === 'POST') { - - $month = $this->request->getPost('month'); + //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 ..!! - $date = DateTime::createFromFormat('M-Y', $month); + + //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'); - $formattedDate = $date->format('Y-m'); + + $month = $formattedDate; + + //setting session for any month change + $session = session (); + + $session->set('stock_month',$month); + + + } else { - $month = $formattedDate; - - $session = session (); + //if request is in get method getting remark in query params in new_header.php file(navbar) - $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 + $remark = $this->request->getVar('remark'); + + $session = session(); + + $month = $session->get('stock_month'); + + if (empty($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; + + $materialCodes = call_user_func_array('array_merge', $materialCodes); + + + if (!empty($materialCodes)) { + //remark filter may apply or not + $data['igrDetails'] = $this->inwardGateRegister_model->findIgrDetailsForIncomingSilicaSand($materialCodes, $month, $remark); + } else { + $data['igrDetails'] = []; + } + + $data['testedBy'] = []; + + //['lab assistant', 'factory manager', 'lab head'] + $data['testedBy'] = $this->employeedetails_model->incomingSilicaSandTestedBy(); + + //['factory manager', 'lab head'] + $data['approvedBy'] = $this->employeedetails_model->incomingSilicaSandApprovedBy(); + + + $date = DateTime::createFromFormat('Y-m', $month); + + $formattedDate = $date->format('M-Y'); + + $data['month'] = $formattedDate; + + $data['remark'] = $remark; + + return $this->loadViews("stock/incomingSilicaSandDetails", $this->global, $data, NULL); + } + + public function updateIncomingSilicaSandDetails() + { + + $postData = $this->request->getPost(); + + $incomingSilicaSandDetailsData = json_decode($postData['incomingSilicaSandDetailsData'], true); + + $inserts = []; + $updates = []; + + foreach ($incomingSilicaSandDetailsData as $data) { + + $id = $data['id']; + + $dbData = [ + 'igrNo_fk' => $data['IGR No'], + 'materialCode' => $data['MaterialCode'], + 'grade' => $data['Grade'], + 'gradeCondition' => $data['Grade Condition'], + '_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['AFS Spec'], + 'afsActual' => $data['AFS Actual'], + 'plus20loss' => $data['Plus 20 loss%'], + 'plus30Loss' => $data['Plus 30 Loss %'], + 'moistureSpec' => $data['Moisture % Spec'], + 'moistureActual' => $data['Moisture Actual'], + 'moistureLoss' => $data['Moisture Loss'], + 'moistureLossQty' => $data['Moisture loss Qty'], + 'sieveLossQty' => $data['Sieve Loss Qty'], + 'salableQty' => $data['Salable Qty'], + 'remark' => $data['Remark'] + + ]; + + + + $resultExists = $this->incomingSilicaSandDetails_model + ->where('id', $id) + ->first(); + + if (!empty($resultExists)) { + $dbData['id'] = $resultExists['id']; + $updates[] = $dbData; + } else { + $inserts[] = $dbData; + } + } + + if (!empty($updates)) { + $updated = $this->incomingSilicaSandDetails_model->updateBatch($updates, 'id'); + } + + if (!empty($inserts)) { + $inserted = $this->incomingSilicaSandDetails_model->insertBatch($inserts); + } + + echo "Data Saved Successfully"; + } + + + //This is particulary updated by the lab technichians + public function updateLabReport() + { + + $postData = $this->request->getPost(); + + $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'], + 'clayOrLossOfIgnition' => $postData['clayOrLossOfIgnition'], + 'reportComments' => $postData['reportComments'], + 'gradeRange' => $postData['gradeRange'], + 'reportTime' => $postData['reportTime'] + + ]; + + + + $resultExists = $this->incomingSilicaSandDetails_model + ->where('id', $id) + ->first(); + if ($resultExists) { + $updated = $this->incomingSilicaSandDetails_model + ->update($id, $dbData); + } else { + $updated = $this->incomingSilicaSandDetails_model + ->insert($dbData); + } + + + if ($updated) { + return $this->response->setJSON(['status' => 'success', 'message' => 'Data Updated Successfully']); + } else { + return $this->response->setJSON(['status' => 'error', 'message' => 'Failed to update data']); + } } - $data['month'] = $month ; + //Drier machine details + 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. + + + 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'); + + // 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'); + - $this->global['pageTitle'] = 'Coating Machine Details '; + $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'); + } 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); + + + // 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(); + + + $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(); + + // 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; + + 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) { + // Rollback the transaction in case of an error + $this->db->transRollback(); + + return redirect()->back()->with('error', ' ' . $error->getMessage()); + } + } + + + /** + * Maps input row to expected format. + */ + private function mapDrierEntry(array $data): array + { + return [ + 'id' => $data['id'] ?? null, + 'date' => $this->convertToDateWithFlexibleFormats($data['date'], ["d-m-Y", "Y-m-d", "m/d/Y", "m-d-Y"], "Y-m-d"), + 'drier_on_time' => $data['drier_on_time'], + 'drier_off_time' => $data['drier_off_time'], + 'drier_running_hours' => $data['drier_running_hours'], + 'supplier_name' => $data['supplier_name'], + 'input_sand_moisture' => $data['input_sand_moisture'], + 'total_gas_consumption' => $data['total_gas_consumption'], + 'gas_per_ton' => $data['gas_per_ton'], + 'input_sand_qty' => $data['input_sand_qty'], + 'moisture_loss_qty' => $data['moisture_loss_qty'], + 'sand_dried_qty' => $data['sand_dried_qty'], + 'qty_per_hours' => $data['qty_per_hours'], + 'dust_qty' => $data['dust_qty'], + 'customer_name' => $data['customer_name'] + ]; + } - $startDate = "$month-01"; - $endDate = date("Y-m-t", strtotime($startDate)); - $data['coatingMachineDetails'] = $this->coatingMachineDetails_model - ->select('t_coatingMachineDetails.*, - JSON_ARRAYAGG( - JSON_OBJECT( + + //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; + + // 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'); + } + } + + $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(); - - - $date = DateTime::createFromFormat('Y-m', $month); - - $formattedDate = $date->format('M-Y'); - - $data['month'] = $formattedDate; - - 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 - $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.'); - } - - if ($insertedId !== false && $insertedId > 0) { - - $batchCardFiles = $this->request->getFileMultiple('batchCard'); - - if (!empty($batchCardFiles) && !($batchCardFiles[0]->getError() === UPLOAD_ERR_NO_FILE)) { + ) + ) 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(); - foreach ($batchCardFiles as $file) { + // 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; - if ($file->isValid() && !$file->hasMoved()) { - $clientGivenName = $file->getClientName(); // User-given filename - $newName = $file->getRandomName(); - - if ($file->move(WRITEPATH . 'uploads/batchcard', $newName)) { - // Only save to DB if file moved successfully - $db = \Config\Database::connect(); - $builder = $db->table('t_batchcard_files'); - - $data = [ - 'client_file_name' => $clientGivenName, - 'filename' => $newName, - 'coating_id' => $insertedId - ]; - - $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 - return redirect()->to("/coatingMachineDetails") - ->with('success', $message1 . " " . $message2 . " " . $message3); - } catch (\Exception $error) { - $this->db->transRollback(); - return redirect()->back()->with('error', ' ' . $error->getMessage()); + // Load the view with the required data + return $this->loadViews("stock/CoatingMachineDetail", $this->global, $data, NULL); } - } + - - - 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'); - - - // 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); - } - } - } - } + 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 ..!!'); } - - 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); - + + // 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) { - // 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..!!"; + $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.'); } - // Commit the transaction if all queries succeed - - + + // 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(); + + if ($file->move(WRITEPATH . 'uploads/batchcard', $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 ($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); - } else { - throw new \Exception('Failed to update Coating machine details.'); + } catch (\Exception $error) { + $this->db->transRollback(); + return redirect()->back()->with('error', ' ' . $error->getMessage()); } - - - - - - } catch (\Exception $error) { - $this->db->transRollback(); - return redirect()->back()->with('error', ' ' . $error->getMessage()); } - } + + + + + 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); - public function deleteBatchCardFile() - { - $data = $this->request->getPost(); - - if (!empty($data)) { - $batchId = $data['id']; - $db = \Config\Database::connect(); - $builder = $db->table('t_batchcard_files'); + + 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'); - // Step 1: Fetch the filename from DB before deleting - $fileRecord = $builder->select('filename')->where('id', $batchId)->get()->getRow(); - - if ($fileRecord) { - $filePath = WRITEPATH . 'uploads/batchcard/' . $fileRecord->filename; - - // Step 2: Delete the file from storage - if (file_exists($filePath)) { - unlink($filePath); + 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); + } + } + } + } + } + + + } - - // 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..!!" - ]); + + 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 { + throw new \Exception('Failed to update Coating machine details.'); + } + + + + + + } catch (\Exception $error) { + $this->db->transRollback(); + return redirect()->back()->with('error', ' ' . $error->getMessage()); + } + } + + 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) { + $filePath = WRITEPATH . 'uploads/batchcard/' . $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' => '400', - 'message' => "Failed to Delete..!! Try Again Later" + 'status' => '404', + 'message' => "File Not Found..!!" ]); } - } else { - return $this->response->setJSON([ - 'status' => '404', - 'message' => "File Not Found..!!" - ]); } + + return $this->response->setJSON([ + 'status' => '400', + 'message' => "Invalid Request..!!" + ]); } - - return $this->response->setJSON([ - 'status' => '400', - 'message' => "Invalid Request..!!" - ]); - } - public function downloadBatchcardZip() - { - $coatingId = $this->request->getGet('coating_id'); - $date = $this->request->getGet('date'); - $batchCardFiles = $this->getBatchCardFiles($coatingId); // Fetch files from DB - - if (empty($batchCardFiles)) { - return redirect()->back()->with('error', 'No batchcard files found.'); + public function downloadBatchcardZip() + { + $coatingId = $this->request->getGet('coating_id'); + $date = $this->request->getGet('date'); + $batchCardFiles = $this->getBatchCardFiles($coatingId); // Fetch files from DB + + if (empty($batchCardFiles)) { + return redirect()->back()->with('error', 'No batchcard files found.'); + } + + $zipFileName = 'batchcard_files_' . $date . '.zip'; + $zipFilePath = WRITEPATH . 'uploads/batchcard' . $zipFileName; // CI4 WRITEPATH safe directory + + $zip = new \ZipArchive(); + if ($zip->open($zipFilePath, \ZipArchive::CREATE | \ZipArchive::OVERWRITE) === true) { + foreach ($batchCardFiles as $file) { + $originalFilePath = WRITEPATH . 'uploads/batchcard/' . $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(); + + $response = $this->response->download($zipFilePath, null)->setFileName($zipFileName); + + // Delete ZIP after response is sent + register_shutdown_function(function () use ($zipFilePath) { + if (file_exists($zipFilePath)) { + unlink($zipFilePath); + } + }); + + return $response; + } + + 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; + } + - $zipFileName = 'batchcard_files_' . $date . '.zip'; - $zipFilePath = WRITEPATH . 'uploads/batchcard' . $zipFileName; // CI4 WRITEPATH safe directory - - $zip = new \ZipArchive(); - if ($zip->open($zipFilePath, \ZipArchive::CREATE | \ZipArchive::OVERWRITE) === true) { - foreach ($batchCardFiles as $file) { - $originalFilePath = WRITEPATH . 'uploads/batchcard/' . $file['filename']; // Actual stored file - $clientFileName = $file['client_file_name'] ?? $file['filename']; // Use client name if available + + //Gas Stock Details + public function loadView_gasStockDetails() + { + + if ($this->request->getMethod() === 'POST') { + + $month = $this->request->getPost('month'); + + $date = DateTime::createFromFormat('M-Y', $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', $month)->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) / 1000 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(); + + + + $data['month'] = DateTime::createFromFormat('Y-m', $month)->format('M-Y'); + + return $this->loadViews("stock/gasStockDetails", $this->global, $data, NULL); + } + + public function updateGasStockDetails() + { + + $postData = $this->request->getPost(); + + $updateGasStockDetailsData = json_decode($postData['updateGasStockDetails'], true); + + $updates = []; + + $inserts = []; + + foreach ($updateGasStockDetailsData as $data) { + + $date = $data['date']; + + + $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'] + ]; + + $resultExists = $this->gasStockDetails_model + ->where('date', $date) + ->first(); + + + 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; + } + } 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; + } + } + } + + + + + + //diesel stock details - if (file_exists($originalFilePath)) { - $zip->addFile($originalFilePath, $clientFileName); // Rename inside ZIP + public function dieselMachineStockDetails(){ + + + if ($this->request->getMethod() === 'POST') { + + $month = $this->request->getPost('month'); + + $date = DateTime::createFromFormat('M-Y', $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'] = 'Diesel Machine 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)); + + + //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(); + + + //check user applies for filter currently + if(!empty($customisedMachineCodes)){ + + //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 + ]; + + + //checking filtered material code present in table , if not create dummy one for whole month + $findMachineCode = $this->factoryVehicleDieselDetails_model + ->where('date >=', $startDate) + ->where('date <=', $endDate) + ->where('machine_id',$customisedMachineCode) + ->findAll(); + + //check any material code is not present in stock table but applied in filter + if(empty($findMachineCode)){ + + //create dummy entry for this + $this->createDummyEntryForDieselMachine($customisedMachineCode,$startDate,$endDate); + } + + } + + 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 all active material codes + $existingCustomMachineCodes = $this->factoryMachine_model + ->getAllActiveDieselMachines(); + }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'); + + $dieselMachines = $existingCustomMachineCodes; + + $data['activeDieselMachines'] = $this->factoryMachine_model->getAllActiveDieselMachines(); + + + + + + + + + + + + // Get the previous month's last date diesel stock details for next month updation + + $previousMonth = DateTime::createFromFormat('Y-m', $month)->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 + ->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; + } + + // Reset the structure to have indexed arrays without the date keys + $data['groupedDieselMachineStockDetails'] = array_values($groupedByDate); + + + + //temp_code_s_2025_02 + + // getting diesel machines for creating table headers + // checking already existing stock if yes then get the diesel machines id from the existing stock + // if not get all the diesel machines from the factory Machine master table + + // if (!empty($data['groupedDieselMachineStockDetails'])) { + + // $result = $groupedByDate[$date]; + + // $distinctMachineId = []; + + // foreach ($result as $index => $eachResult) { + // $distinctMachineId[] = $result[$index]['machine_id']; + // } + + // $dieselMachines = $this->factoryMachine_model + // ->whereIn('id', $distinctMachineId) + // ->orderBy('id', 'asc') + // ->get() + // ->getResultArray(); + + + // } else { + + // $dieselMachines = $this->factoryMachine_model + // ->where('is_active', 1) + // ->where('energy_type', 'Diesel') + // ->orderBy('id', 'asc') + // ->get() + // ->getResultArray(); + + // } + + //temp_code_e_2025_02 + + + + + + $dieselMachinesCount = count($dieselMachines); + + $data['dieselMachinesCount'] = $dieselMachinesCount; + $data['dieselMachines'] = $dieselMachines; + + $date = DateTime::createFromFormat('Y-m', $month); + + $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(); } } - $zip->close(); - - $response = $this->response->download($zipFilePath, null)->setFileName($zipFileName); - // Delete ZIP after response is sent - register_shutdown_function(function () use ($zipFilePath) { - if (file_exists($zipFilePath)) { - unlink($zipFilePath); + + //power stock details + public function powerConsumptionDetails(){ + + + if ($this->request->getMethod() === 'POST') { + + $month = $this->request->getPost('month'); + + $date = DateTime::createFromFormat('M-Y', $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 + } } - }); - - return $response; - } - - 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; - } - - - //incoming Silica Sand Details starts - public function loadView_incomingSilicaSandDetails() - { + $data = []; - if ($this->request->getMethod() === 'POST') { + $data['month'] = $month; - $remark = $this->request->getPost('remark'); - - $month = $this->request->getPost('month'); - - $date = DateTime::createFromFormat('M-Y', $month); - - $formattedDate = $date->format('Y-m'); - - $month = $formattedDate; - - $session = session (); - - $session->set('stock_month',$month); + $this->global['pageTitle'] = 'Power Consumption Stock Details'; - } else { - $remark = $this->request->getVar('remark'); + - $session = session(); + //filter part starts - $month = $session->get('stock_month'); + //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(); + + + //check user applies for filter currently + if(!empty($customisedMachineCodes)){ + + //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(); + + } + + + //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 + ]; + + + //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',$customisedMachineCode) + ->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($customisedMachineCode,$startDate,$endDate); + } + + } + + 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 all active material codes + $existingCustomMachineCodes = $this->factoryMachine_model + ->getAllActiveElectricMachines(); + }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'); + + $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', $month)->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; + } + + // Reset the structure to have indexed arrays without the date keys + $data['groupedPowerConsumptionStockDetails'] = array_values($groupedByDate); + + + //temp_code_s_2025_02 + + // getting electric machines for creating table headers + // checking already existing stock if yes then get the electric machines id from the existing stock + // if not get all the electric machines from the factory Machine master table + + // if (!empty($data['groupedPowerConsumptionStockDetails'])) { + + // $result = $groupedByDate[$date]; + + // $distinctMachineId = []; + + // foreach ($result as $index => $eachResult) { + // $distinctMachineId[] = $result[$index]['machine_id']; + // } + + // $electricMachines = $this->factoryMachine_model->getSelectedElectricMachines($distinctMachineId); + + + // } else { + + // $electricMachines = $this->factoryMachine_model->getAllActiveElectricMachines(); + + // } + + //temp_code_e_2025_02 + + + + $electricMachinesCount = count($electricMachines); + + $data['electricMachinesCount'] = $electricMachinesCount; + $data['electricMachines'] = $electricMachines; + + $date = DateTime::createFromFormat('Y-m', $month); + + $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); - if (empty($month)) { - $month = date('Y-m'); // Default to the current month } - } + public function updatePowerConsumptionDetails(){ - $data['month'] = $month; + //pm stands for power machine + + + $postData = $this->request->getPost(); - $this->global['pageTitle'] = 'Incoming Silica Sand Details'; + $updatePowerConsumptionDetailsData = json_decode($postData['updatePowerConsumptionDetails'], true); - $materialCodes = []; + $updateTotalPmDetailsData = $updatePowerConsumptionDetailsData[0]; + $updatePmDetailsData = $updatePowerConsumptionDetailsData[1]; + + //PmR stands for power machine readings - $silicaSandMaterialCodes = $this->rawmaterialdetails_model->getAllSilicaRawMaterialCode(); + $updatesPmR = []; + $insertsPmR = []; - $materialCodes [] = $silicaSandMaterialCodes; + $updatesTotalPmR = []; + $insertsTotalPmR = []; - $wasteCoreSandMaterialCodes = $this->rawmaterialdetails_model->getAllWasteCoreSandMaterialCode(); + // 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(); + } - $materialCodes [] = $wasteCoreSandMaterialCodes; - - $materialCodes = call_user_func_array('array_merge', $materialCodes); - - - if (!empty($materialCodes)) { - $data['igrDetails'] = $this->inwardGateRegister_model->findIgrDetailsForIncomingSilicaSand($materialCodes, $month, $remark); - } else { - $data['igrDetails'] = []; - } - - $data['testedBy'] = []; - - $DesignationConfigID = 'C010'; - - $data['testedBy'] = $this->employeedetails_model->incomingSilicaSandTestedBy($DesignationConfigID); - - $data['approvedBy'] = $this->employeedetails_model->incomingSilicaSandApprovedBy($DesignationConfigID); - - - $date = DateTime::createFromFormat('Y-m', $month); - - $formattedDate = $date->format('M-Y'); - - $data['month'] = $formattedDate; - - $data['remark'] = $remark; - - return $this->loadViews("stock/incomingSilicaSandDetails", $this->global, $data, NULL); - } - - public function updateIncomingSilicaSandDetails() - { - - $postData = $this->request->getPost(); - - $incomingSilicaSandDetailsData = json_decode($postData['incomingSilicaSandDetailsData'], true); - - $inserts = []; - $updates = []; - - foreach ($incomingSilicaSandDetailsData as $data) { - - $id = $data['id']; - - $dbData = [ - 'igrNo_fk' => $data['IGR No'], - 'materialCode' => $data['MaterialCode'], - 'grade' => $data['Grade'], - 'gradeCondition' => $data['Grade Condition'], - '_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['AFS Spec'], - 'afsActual' => $data['AFS Actual'], - 'plus20loss' => $data['Plus 20 loss%'], - 'plus30Loss' => $data['Plus 30 Loss %'], - 'moistureSpec' => $data['Moisture % Spec'], - 'moistureActual' => $data['Moisture Actual'], - 'moistureLoss' => $data['Moisture Loss'], - 'moistureLossQty' => $data['Moisture loss Qty'], - 'sieveLossQty' => $data['Sieve Loss Qty'], - 'salableQty' => $data['Salable Qty'], - 'remark' => $data['Remark'] - - ]; - - - - $resultExists = $this->incomingSilicaSandDetails_model - ->where('id', $id) - ->first(); - - if (!empty($resultExists)) { - $dbData['id'] = $resultExists['id']; - $updates[] = $dbData; - } else { - $inserts[] = $dbData; } - } - - if (!empty($updates)) { - $updated = $this->incomingSilicaSandDetails_model->updateBatch($updates, 'id'); - } - - if (!empty($inserts)) { - $inserted = $this->incomingSilicaSandDetails_model->insertBatch($inserts); - } - - echo "Data Saved Successfully"; - } - - public function updateLabReport() - { - - $postData = $this->request->getPost(); - - $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'], - 'clayOrLossOfIgnition' => $postData['clayOrLossOfIgnition'], - 'reportComments' => $postData['reportComments'], - 'gradeRange' => $postData['gradeRange'], - 'reportTime' => $postData['reportTime'] - - ]; - - - - $resultExists = $this->incomingSilicaSandDetails_model - ->where('id', $id) - ->first(); - if ($resultExists) { - $updated = $this->incomingSilicaSandDetails_model - ->update($id, $dbData); - } else { - $updated = $this->incomingSilicaSandDetails_model - ->insert($dbData); - } - if ($updated) { - return $this->response->setJSON(['status' => 'success', 'message' => 'Data Updated Successfully']); - } else { - return $this->response->setJSON(['status' => 'error', 'message' => 'Failed to update data']); - } - } + //Dust And Rough Stock Details + public function loadView_dustAndRoughStockDetails() + { + + if ($this->request->getMethod() === 'POST') { + $month = $this->request->getPost('month'); + + $date = DateTime::createFromFormat('M-Y', $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'] = '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', $month); + + $formattedDate = $date->format('M-Y'); + + $data['month'] = $formattedDate; + + return $this->loadViews("stock/dustAndRoughStockDetails", $this->global, $data, NULL); + } + + + 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(); - // Bag Stock details starts + 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"; + } + + + //Resin Stock Details + public function loadView_resinStockDetails() + { + + if ($this->request->getMethod() === 'POST') { + + $month = $this->request->getPost('month'); + + $date = DateTime::createFromFormat('M-Y', $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'] = '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(); + + + //check user applies for filter currently + if(!empty($customisedMaterialCodes)){ + + //user applied 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 + ]; + + //checking filtered material code present in table , if not create dummy one for whole month + $findMaterialCode = $this->resinStockDetails_model + ->where('date >=', $startDate) + ->where('date <=', $endDate) + ->where('materialCode',$customisedMaterialCode) + ->findAll(); + + //check any material code is not present in stock table but applied in filter + if(empty($findMaterialCode)){ + //create dummy entry for that + $this->createDummyEntryForResin($customisedMaterialCode,$startDate,$endDate); + } + + } + + 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 all active material codes + $existingCustomMaterialCodes = $this->rawmaterialdetails_model->getAllResinMaterialCode(); + }else{ + //if filter present,get that material codes + $existingCustomMaterialCodes = $this->rawmaterialdetails_model + ->getSelectedResinMaterialCode(array_column($existingCustomMaterialCodes, 'materialCode')); + } + + + $materialCodeList = array_column($existingCustomMaterialCodes, 'MaterialCode'); + + $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', $month)->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; + } + + // Reset the structure to have indexed arrays without the date keys + $data['groupedResinStockDetails'] = array_values($groupedByDate); + + + //temp_code_s_2025_02 + + // getting resin material for creating table headers + // checking already existing stock if yes then get the material code from the existing stock + // if not get all the material codes currently isActive from the raw material details table + + // if (!empty($data['groupedResinStockDetails'])) { + + // $result = $groupedByDate[$date]; + + // $distinctMaterialCodes = []; + + // foreach ($result as $index => $eachResult) { + // $distinctMaterialCodes[] = $result[$index]['materialCode']; + // } + + // $resinMaterials = $this->rawmaterialdetails_model->getSelectedResinMaterialCode($distinctMaterialCodes); + + // } else { + + // $resinMaterials = $this->rawmaterialdetails_model->getAllResinMaterialCode(); + + // } + + //temp_code_e_2025_02 + + + // 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'] ?? ''; + } + + $resinMaterialCount = count($resinMaterials); + + $data['resinMaterialCount'] = $resinMaterialCount; + $data['resinMaterials'] = $resinMaterials; + + $date = DateTime::createFromFormat('Y-m', $month); + + $formattedDate = $date->format('M-Y'); + + $data['month'] = $formattedDate; + + return $this->loadViews("stock/resinStockDetails", $this->global, $data, NULL); + } + + + + public function updateResinStockDetails() + { + + + $postData = $this->request->getPost(); + + $updateResinStockDetailsData = json_decode($postData['updateResinStockDetails'], true); + + $updates = []; + + $inserts = []; + + foreach ($updateResinStockDetailsData as $data) { + + $date = $data['date']; + $materialCode = $data['materialCode']; + + + $dbData = [ + 'date' => $data['date'], + 'materialCode' => $data['materialCode'], + 'customer' => $data['customer'], + 'opening' => $data['opening'], + 'receipt' => $data['receipt'], + 'used' => $data['used'], + 'balanceStock' => $data['balanceStock'], + ]; + + $resultExists = $this->resinStockDetails_model + ->where('date', $date) + ->where('materialCode', $materialCode) + ->first(); + + + if (empty($resultExists)) { + $inserts[] = $dbData; + } else { + $dbData['id'] = $resultExists['id']; + $updates[] = $dbData; + } + } + + + if (!empty($inserts)) { + $this->resinStockDetails_model->insertBatch($inserts); + } + + if (!empty($updates)) { + + $updateResult = $this->resinStockDetails_model->updateBatch($updates, 'id'); + + if ($updateResult === FALSE) { + echo "Error during update"; + } else { + echo "Data Updated Successfully"; + 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); + } + } + } + + + // Bag Stock details starts //custom filterMaterialCode given by user @@ -750,11 +2466,6 @@ class StockController extends BaseController // Action - - - - - public function loadView_bagStockDetails() { @@ -791,6 +2502,98 @@ class StockController extends BaseController $this->global['pageTitle'] = 'Bag 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','packing_material') + ->findAll(); + + + //check user applies for filter currently + if(!empty($customisedMaterialCodes)){ + + //user applied 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','packing_material') + ->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' => "packing_material", + 'materialCode' => $customisedMaterialCode + ]; + + //checking filtered material code present in table , if not create dummy one for whole month + $findMaterialCode = $this->bagStockDetails_model + ->where('date >=', $startDate) + ->where('date <=', $endDate) + ->where('materialCode',$customisedMaterialCode) + ->findAll(); + + //check any material code is not present in stock table but applied in filter + if(empty($findMaterialCode)){ + //create dummy entry for that + $this->createDummyEntryForBag($customisedMaterialCode,$startDate,$endDate); + } + + } + + 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','packing_material') + ->get()->getResultArray(); + + } + + } + + + //possible if no filter applied at all...!!! + if(empty($existingCustomMaterialCodes)){ + //no filter applied at all just present all active material codes + $existingCustomMaterialCodes = $this->rawmaterialdetails_model + ->getAllBagMaterialCode(); + }else{ + //if filter present,get that material codes + $existingCustomMaterialCodes = $this->rawmaterialdetails_model + ->getSelectedBagMaterialCode(array_column($existingCustomMaterialCodes, 'materialCode')); + } + + + $materialCodeList = array_column($existingCustomMaterialCodes, 'MaterialCode'); + + $bagMaterials = $existingCustomMaterialCodes ; + + $data['activeBagMaterials'] = $this->rawmaterialdetails_model->getAllBagMaterialCode(); + + // Get the previous month's last date bag stock details for next month updation $previousMonth = DateTime::createFromFormat('Y-m', $month)->modify('-1 month')->format('Y-m'); @@ -807,13 +2610,12 @@ class StockController extends BaseController - // checking in database if the data is available for the month + // checking in database if the data is available for the month - $startDate = "$month-01"; - $endDate = date("Y-m-t", strtotime($startDate)); $data['bagStockDetails'] = $this->bagStockDetails_model ->where('date >=', $startDate) ->where('date <=', $endDate) + ->whereIn('materialCode',$materialCodeList) ->groupBy(['materialCode', 'date']) ->orderBy('date', 'asc') ->orderBy('materialCode', 'asc') @@ -838,12 +2640,12 @@ class StockController extends BaseController /******************************************************************************************************************* creating an sub array (inner array) for date wise and append the detail into an array as sub-array - $groupedByDate[] outer array + $groupedByDate[] outer array - $groupedByDate[$date] - will look like [[bag1],[bag2],[bag3],[bag4],[bag5]] inner array + $groupedByDate[$date] + will look like [[bag1],[bag2],[bag3],[bag4],[bag5]] inner array - the above process is done for single row (date wise) and the same process is repeated for all the rows + the above process is done for single row (date wise) and the same process is repeated for all the rows *******************************************************************************************************************/ @@ -856,25 +2658,28 @@ class StockController extends BaseController + //temp_code_s_2025_02 - // getting bag material for creating table headers - // checking already existing stock if yes then get the material code from the existing bag - // if not get all the material codes from the raw material details table + // // getting bag material for creating table headers + // // checking already existing stock if yes then get the material code from the existing bag + // // if not get all the material codes from the raw material details table - if (!empty($data['groupedBagStockDetails'])) { - $result = $groupedByDate[$date]; + // if (!empty($data['groupedBagStockDetails'])) { + // $result = $groupedByDate[$date]; - $distinctMaterialCodes = []; + // $distinctMaterialCodes = []; - foreach ($result as $index => $eachResult) { - $distinctMaterialCodes[] = $result[$index]['materialCode']; - } + // foreach ($result as $index => $eachResult) { + // $distinctMaterialCodes[] = $result[$index]['materialCode']; + // } - $bagMaterials = $this->rawmaterialdetails_model->getSelectedBagMaterialCode($distinctMaterialCodes); - - } else { - $bagMaterials = $this->rawmaterialdetails_model->getAllBagMaterialCode(); - } + // $bagMaterials = $this->rawmaterialdetails_model->getSelectedBagMaterialCode($distinctMaterialCodes); + + // } else { + // $bagMaterials = $this->rawmaterialdetails_model->getAllBagMaterialCode(); + // } + + //temp_code_e_2025_02 // getting customer for creating table headers @@ -964,609 +2769,8 @@ class StockController extends BaseController } - //Dust And Rough Stock Details - public function loadView_dustAndRoughStockDetails() - { - if ($this->request->getMethod() === 'POST') { - $month = $this->request->getPost('month'); - $date = DateTime::createFromFormat('M-Y', $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'] = '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', $month); - - $formattedDate = $date->format('M-Y'); - - $data['month'] = $formattedDate; - - return $this->loadViews("stock/dustAndRoughStockDetails", $this->global, $data, NULL); - } - - 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; - } - } - - 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"; - } - - - //Resin Stock Details - public function loadView_resinStockDetails() - { - - if ($this->request->getMethod() === 'POST') { - - $month = $this->request->getPost('month'); - - $date = DateTime::createFromFormat('M-Y', $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'] = 'Resin Stock Details'; - - - // Get the previous month's last date resin stock details for next month updation - - $previousMonth = DateTime::createFromFormat('Y-m', $month)->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 - - $startDate = "$month-01"; - $endDate = date("Y-m-t", strtotime($startDate)); - $data['resinStockDetails'] = $this->resinStockDetails_model - ->where('date >=', $startDate) - ->where('date <=', $endDate) - ->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; - } - - // Reset the structure to have indexed arrays without the date keys - $data['groupedResinStockDetails'] = array_values($groupedByDate); - - - - // getting resin material for creating table headers - // checking already existing stock if yes then get the material code from the existing stock - // if not get all the material codes from the raw material details table - - if (!empty($data['groupedResinStockDetails'])) { - - $result = $groupedByDate[$date]; - - $distinctMaterialCodes = []; - - foreach ($result as $index => $eachResult) { - $distinctMaterialCodes[] = $result[$index]['materialCode']; - } - - $resinMaterials = $this->rawmaterialdetails_model->getSelectedResinMaterialCode($distinctMaterialCodes); - - } else { - - $resinMaterials = $this->rawmaterialdetails_model->getAllResinMaterialCode(); - - } - - - // 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'] ?? ''; - } - - $resinMaterialCount = count($resinMaterials); - - $data['resinMaterialCount'] = $resinMaterialCount; - $data['resinMaterials'] = $resinMaterials; - - $date = DateTime::createFromFormat('Y-m', $month); - - $formattedDate = $date->format('M-Y'); - - $data['month'] = $formattedDate; - - return $this->loadViews("stock/resinStockDetails", $this->global, $data, NULL); - } - - public function updateResinStockDetails() - { - - - $postData = $this->request->getPost(); - - $updateResinStockDetailsData = json_decode($postData['updateResinStockDetails'], true); - - $updates = []; - - $inserts = []; - - foreach ($updateResinStockDetailsData as $data) { - - $date = $data['date']; - $materialCode = $data['materialCode']; - - - $dbData = [ - 'date' => $data['date'], - 'materialCode' => $data['materialCode'], - 'customer' => $data['customer'], - 'opening' => $data['opening'], - 'receipt' => $data['receipt'], - 'used' => $data['used'], - 'balanceStock' => $data['balanceStock'], - ]; - - $resultExists = $this->resinStockDetails_model - ->where('date', $date) - ->where('materialCode', $materialCode) - ->first(); - - - if (empty($resultExists)) { - $inserts[] = $dbData; - } else { - $dbData['id'] = $resultExists['id']; - $updates[] = $dbData; - } - } - - - if (!empty($inserts)) { - $this->resinStockDetails_model->insertBatch($inserts); - } - - if (!empty($updates)) { - - $updateResult = $this->resinStockDetails_model->updateBatch($updates, 'id'); - - if ($updateResult === FALSE) { - echo "Error during update"; - } else { - echo "Data Updated Successfully"; - return; - } - } - - echo "Data Saved Successfully"; - } - - - //Gas Stock Details - public function loadView_gasStockDetails() - { - - if ($this->request->getMethod() === 'POST') { - - $month = $this->request->getPost('month'); - - $date = DateTime::createFromFormat('M-Y', $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', $month)->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) / 1000 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(); - - - - $data['month'] = DateTime::createFromFormat('Y-m', $month)->format('M-Y'); - - return $this->loadViews("stock/gasStockDetails", $this->global, $data, NULL); - } - - public function updateGasStockDetails() - { - - $postData = $this->request->getPost(); - - $updateGasStockDetailsData = json_decode($postData['updateGasStockDetails'], true); - - $updates = []; - - $inserts = []; - - foreach ($updateGasStockDetailsData as $data) { - - $date = $data['date']; - - - $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'] - ]; - - $resultExists = $this->gasStockDetails_model - ->where('date', $date) - ->first(); - - - 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) - { - - $resultExists = $this->gasStockDetails_model - ->where('date', $date) - ->first(); - - if ($resultExists) { - - - 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)); - } - - $endDate = date('Y-m-t', strtotime($date)); - - - //what happens if the updation is on the last day of the month? - $resultExists = $this->gasStockDetails_model - ->where('date >=', $date) - ->where('date <=', $endDate) - ->orderBy('date', 'asc') - ->findAll(); - - $updatedOpeningStock = 0; - $updates = []; - - - foreach ($resultExists as $index => $result) { - - if ($index == 0) { - $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 { - $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; - } - - if (!empty($updates)) { - $result = $this->gasStockDetails_model->updateBatch($updates, 'id'); - return ($result !== false && $result > 0) ? $result : 0; - } else { - return 0; - } - } else { - - - - $previousMonthDate = new DateTime($date); - $previousMonthDate = $previousMonthDate->modify('first day of this month') - ->modify('-1 day') - ->format('Y-m-d'); - - - - $previousMonthResultExists = $this->gasStockDetails_model - ->where('date', $previousMonthDate) - ->first(); - - - - $opening = 0; - - if (!empty($previousMonthResultExists) && isset($previousMonthResultExists['balanceStock'])) { - $opening = $previousMonthResultExists['balanceStock']; - } - - - - $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 - $balanceStock = $opening; - $consumptionForDate = 0; - if ($dateInMonth == $date) { - $consumptionForDate = $consumption; - $balanceStock = $opening - $consumption; - } - - $inserts[] = [ - 'date' => $dateInMonth, - 'opening' => $opening, - 'purchaseBharath' => Null, - 'purchaseIndian' => Null, - 'total' => Null, - 'consumption' => $consumptionForDate, - 'balanceStock' => $balanceStock - ]; - - $opening = $balanceStock; - } - - if (!empty($inserts)) { - $result = $this->gasStockDetails_model->insertBatch($inserts); - return ($result !== false && $result > 0) ? $result : 0; - } else { - return 0; - } - } - } public function trpSandUseStockDetails(){ @@ -1737,8 +2941,32 @@ class StockController extends BaseController $data['wcsSupplierList'] = $result[2] ; + + + + + $trpAbstract = $this->trpAbstract_model->where('date', $startDate)->findAll(); + + // dd( $trpAbstract ); + + $groupedTrpAbstract = [] ; + + foreach($trpAbstract as $abs){ + if(!isset($groupedTrpAbstract[$abs['particulars']])){ + $groupedTrpAbstract[$abs['particulars']] = $abs ; + } + } + + $trpAbstract = $groupedTrpAbstract ; + + $data['trpAbstract'] = $trpAbstract ; + + // dd( $data['trpAbstract']['Incoming Raw Sand Details'] ); + + // dd((int)$trpAbstract["Incoming Raw Sand Details"]['opening_stock']); + $date = DateTime::createFromFormat('Y-m', $month); $formattedDate = $date->format('M-Y'); @@ -1931,24 +3159,6 @@ class StockController extends BaseController foreach ($datesInMonth as $datesInMonthIndex => $dateInMonth) { - if($datesInMonthIndex == 0){ - - $trpAbstractParticulars =$this->trpAbstractParticularsModel->findAll(); - - foreach($trpAbstractParticulars as $index => $trpAbstractParticular){ - - $trpAbstract[] = [ - 'date' => $dateInMonth , - 'abs_opening_stock' => 0 , - 'abs_physical_stock'=> 0 , - 'abs_remarks' => " " , - 'abs_particular_id' => $trpAbstractParticular['id'], - ]; - } - - - } - $inserts[] = [ 'Date' => $dateInMonth, @@ -1994,6 +3204,46 @@ class StockController extends BaseController } + 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"; + } + } + + + + + @@ -2005,7 +3255,7 @@ class StockController extends BaseController - // --------------------------------------------gwm---------------------------------------------- + // -------------------------------------------- in class helpers---------------------------------------------- public function getMonthDatesFromInput($monthYear) @@ -2053,153 +3303,19 @@ class StockController extends BaseController } - 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..!! - - if ($this->request->getMethod() === 'POST') { - - $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 { - - $session = session(); - - $currentMonth = $session->get('stock_month'); - - 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 - } - } - - $monthData = $this->getMonthDatesFromInput($currentMonth); - - $data['startDate'] = $monthData[0]['database']; - $data['endDate'] = $monthData[count($monthData) - 1]['database']; - $data['timeDropdown'] = $this->generateTimeOptions(); - $data['supplierData'] = $this->supplier_model->supplierlisting(); - - $data['drierDetails'] = $this->drierMachineDetails_model - ->where('date >=', $data['startDate']) - ->where('date <=', $data['endDate']) - ->orderBy('date','asc') - ->findAll(); - - - $data['datefordropdown'] = $currentMonth; - - $this->global['pageTitle'] = 'Drier Details'; - $this->loadViews("stock/drierMachineDetails", $this->global, $data, NULL); - - - } - - public function addOrEditdrierMachineDetails() - { - - - $data = $this->request->getPost(); - - $drierData[] = $this->mapDrierEntry($data); - - - $this->db->transBegin(); - try { - $inserts = []; - $updates = []; - - foreach ($drierData as $row) { - $existingRow = $row['id']; - $data = $row; - - - if (($existingRow)) { - // dd("inside update"); - $existingRow = $this->drierMachineDetails_model->where('id', $row['id'] ?? '')->first(); - - $this->handleGasStockUpdate($existingRow, $row); - $updates[] = $data; - } else { - // dd("inside insert"); - $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'); - } - - 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()); - } - } - - /** - * Maps input row to expected format. - */ - private function mapDrierEntry(array $data): array - { - return [ - 'id' => $data['id'] ?? null, - 'date' => $this->convertToDateWithFlexibleFormats($data['date'], ["d-m-Y", "Y-m-d", "m/d/Y", "m-d-Y"], "Y-m-d"), - 'drier_on_time' => $data['drier_on_time'], - 'drier_off_time' => $data['drier_off_time'], - 'drier_running_hours' => $data['drier_running_hours'], - 'supplier_name' => $data['supplier_name'], - 'input_sand_moisture' => $data['input_sand_moisture'], - 'total_gas_consumption' => $data['total_gas_consumption'], - 'gas_per_ton' => $data['gas_per_ton'], - 'input_sand_qty' => $data['input_sand_qty'], - 'moisture_loss_qty' => $data['moisture_loss_qty'], - 'sand_dried_qty' => $data['sand_dried_qty'], - 'qty_per_hours' => $data['qty_per_hours'], - 'dust_qty' => $data['dust_qty'], - 'customer_name' => $data['customer_name'] - ]; - } /** * Updates gas stock consumption if the value changes. */ 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 } } @@ -2225,572 +3341,93 @@ class StockController extends BaseController return $dateInput; } - public function powerConsumptionDetails(){ - - if ($this->request->getMethod() === 'POST') { - - $month = $this->request->getPost('month'); - - $date = DateTime::createFromFormat('M-Y', $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 + public function createDummyEntryForBag($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->bagStockDetails_model->insertBatch($inserts); } } - - $data = []; - - $data['month'] = $month; - - $this->global['pageTitle'] = 'Power Consumption Stock Details'; - - - // Get the previous month's last date power consumption stock details for next month updation - - $previousMonth = DateTime::createFromFormat('Y-m', $month)->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 - - $startDate = "$month-01"; - $endDate = date("Y-m-t", strtotime($startDate)); - - $data['powerConsumptionStockDetails'] = $this->powerConsumptionDetails_model - ->where('date >=', $startDate) - ->where('date <=', $endDate) - ->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; - } - - // Reset the structure to have indexed arrays without the date keys - $data['groupedPowerConsumptionStockDetails'] = array_values($groupedByDate); - - - // getting electric machines for creating table headers - // checking already existing stock if yes then get the electric machines id from the existing stock - // if not get all the electric machines from the factory Machine master table - - if (!empty($data['groupedPowerConsumptionStockDetails'])) { - - $result = $groupedByDate[$date]; - - $distinctMachineId = []; - - foreach ($result as $index => $eachResult) { - $distinctMachineId[] = $result[$index]['machine_id']; - } - - $electricMachines = $this->factoryMachine_model - ->whereIn('id', $distinctMachineId) - ->orderBy('id', 'asc') - ->get() - ->getResultArray(); - - - } else { - - $electricMachines = $this->factoryMachine_model - ->where('is_active', 1) - ->where('energy_type', 'Electric') - ->orderBy('id', 'asc') - ->get() - ->getResultArray(); - - } - - - - $electricMachinesCount = count($electricMachines); - - $data['electricMachinesCount'] = $electricMachinesCount; - $data['electricMachines'] = $electricMachines; - - $date = DateTime::createFromFormat('Y-m', $month); - - $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); - } - 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(); - } - + public function createDummyEntryForDieselMachine($customisedMachineCode, $startDate, $endDate) + { + if (!empty($customisedMachineCode)) { + $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 + 'machine_id' => $customisedMachineCode, + 'opening_units' => ' ', + 'closing_units' => ' ', + 'total_units' => ' ', + ]; + + $startTimestamp = strtotime('+1 day', $startTimestamp); // Move to the next day + } + + if (!empty($inserts)) { + $this->factoryVehicleDieselDetails_model->insertBatch($inserts); + } + } } - - - public function dieselMachineStockDetails(){ - - - if ($this->request->getMethod() === 'POST') { - - $month = $this->request->getPost('month'); - - $date = DateTime::createFromFormat('M-Y', $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'] = 'Diesel Machine Stock Details'; - - - // Get the previous month's last date diesel stock details for next month updation - - $previousMonth = DateTime::createFromFormat('Y-m', $month)->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) - ->groupBy(['machine_id', 'date']) - ->orderBy('date', 'asc') - ->orderBy('machine_id', 'asc') - ->findAll(); - - - $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; - } - - // Reset the structure to have indexed arrays without the date keys - $data['groupedDieselMachineStockDetails'] = array_values($groupedByDate); - - - - // getting diesel machines for creating table headers - // checking already existing stock if yes then get the diesel machines id from the existing stock - // if not get all the diesel machines from the factory Machine master table - - if (!empty($data['groupedDieselMachineStockDetails'])) { - - $result = $groupedByDate[$date]; - - $distinctMachineId = []; - - foreach ($result as $index => $eachResult) { - $distinctMachineId[] = $result[$index]['machine_id']; - } - - $dieselMachines = $this->factoryMachine_model - ->whereIn('id', $distinctMachineId) - ->orderBy('id', 'asc') - ->get() - ->getResultArray(); - - - } else { - - $dieselMachines = $this->factoryMachine_model - ->where('is_active', 1) - ->where('energy_type', 'Diesel') - ->orderBy('id', 'asc') - ->get() - ->getResultArray(); - - } - - - - - - - $dieselMachinesCount = count($dieselMachines); - - $data['dieselMachinesCount'] = $dieselMachinesCount; - $data['dieselMachines'] = $dieselMachines; - - $date = DateTime::createFromFormat('Y-m', $month); - - $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); + public function createDummyEntryForElectricMachine($customisedMachineCode, $startDate, $endDate) + { + if (!empty($customisedMachineCode)) { + $inserts = []; - $updateTotalDmDetailsData = $updateDmDetailsData[0]; - $updateDmDetailsData = $updateDmDetailsData[1]; + // Convert start and end date to timestamps + $startTimestamp = strtotime($startDate); + $endTimestamp = strtotime($endDate); - $updatesDmR = []; - $insertsDmR = []; - $updatesTotalDmR = []; - $insertsTotalDmR = []; + while ($startTimestamp <= $endTimestamp) { + $inserts[] = [ + 'date' => date('Y-m-d', $startTimestamp), // Convert timestamp to date format + 'machine_id' => $customisedMachineCode, + 'opening_units' => ' ', + 'closing_units' => ' ', + 'total_units' => ' ', + ]; - // 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); + $startTimestamp = strtotime('+1 day', $startTimestamp); // Move to the next day } - if (!empty($updatesDmR)) { - $this->factoryVehicleDieselDetails_model->updateBatch($updatesDmR, 'id'); + if (!empty($inserts)) { + $this->powerConsumptionDetails_model->insertBatch($inserts); } - - 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(); } } + + + + diff --git a/app/Controllers/Supplier.php b/app/Controllers/Supplier.php index 3cc7562b..2aacb665 100755 --- a/app/Controllers/Supplier.php +++ b/app/Controllers/Supplier.php @@ -47,7 +47,22 @@ class Supplier extends BaseController */ public function index() { - $data['userRecords'] = $this->supplier_model->supplierlisting(); + + $isActiveFilter = 1 ; // default showing active transporters data + $showArchive = 0 ; // + + if ($this->request->getMethod() === 'POST') { + + $showArchive = $this->request->getPost('showArchive'); + //reversing condition that when user wants deleted data to be shown we are making active filter + if($showArchive){ + $isActiveFilter = 0; + } + } + + + $data['userRecords'] = $this->supplier_model->supplierlisting($isActiveFilter); + $data['showArchive'] = $showArchive ; $this->global['pageTitle'] = 'Supplier Listing'; $this->loadViews("supplierListing", $this->global, $data, NULL); } @@ -473,7 +488,20 @@ class Supplier extends BaseController */ public function transporterListing() { - $data['userRecords'] = $this->supplier_model->transporterListing(); + $isActiveFilter = 1 ; // default showing active transporters data + $showArchive = 0 ; // + + if ($this->request->getMethod() === 'POST') { + + $showArchive = $this->request->getPost('showArchive'); + //reversing condition that when user wants deleted data to be shown we are making active filter + if($showArchive){ + $isActiveFilter = 0; + } + } + + $data['userRecords'] = $this->supplier_model->transporterListing($isActiveFilter); + $data['showArchive'] = $showArchive ; $this->global['pageTitle'] = 'Transporter List'; $this->loadViews("transporterListing", $this->global, $data, NULL); } diff --git a/app/Controllers/User.php b/app/Controllers/User.php index 49acf7b1..59ab3187 100755 --- a/app/Controllers/User.php +++ b/app/Controllers/User.php @@ -894,14 +894,26 @@ class User extends BaseController */ function userListing() { - // if($this->isAdmin() == TRUE) - // { - // $this->loadThis(); - // } - // else - // { + + $isDeleted = 0 ; // default showing active data + $showArchive = 0 ; // + + if ($this->request->getMethod() === 'POST') { + + $showArchive = $this->request->getPost('showArchive'); + //reversing condition that when user wants deleted data to be shown then we are making active filter 0 + if($showArchive){ + $isDeleted = 1; + } + } + + $data['showArchive'] = $showArchive; + + // dd($data); + + + $data['userRecords'] = $this->user_model->userListing($isDeleted); - $data['userRecords'] = $this->user_model->userListing(); $this->global['pageTitle'] = 'User Listing'; // dd($data); diff --git a/app/Models/Assetdetails_model.php b/app/Models/Assetdetails_model.php index db2b81cf..e1340547 100755 --- a/app/Models/Assetdetails_model.php +++ b/app/Models/Assetdetails_model.php @@ -14,12 +14,13 @@ class Assetdetails_model extends Model * @param number $segment : This is pagination limit * @return array $result : This is result */ - function assetListing() + function assetListing($isActiveFilter) { $builder = $this->db->table('t_asset_details asd') ->select('asd.*,dep.DepartmentName,sup.SupplierName') ->join('t_departmentdetails dep', ' dep.DEPCode = asd.DEPCode', 'left') ->join('t_supplierdetailsn sup', 'sup.SupplierID = asd.SupplierCode', 'left') + ->where('asd.IsActive',$isActiveFilter) ->orderBy('asd.CreatedDt', 'desc'); $query = $builder->get(); diff --git a/app/Models/CoatingMachineDetailsModel.php b/app/Models/CoatingMachineDetailsModel.php index 46819fe7..544478ba 100644 --- a/app/Models/CoatingMachineDetailsModel.php +++ b/app/Models/CoatingMachineDetailsModel.php @@ -6,7 +6,7 @@ use CodeIgniter\Model; class CoatingMachineDetailsModel extends Model { - protected $table = 't_coatingMachineDetails'; + protected $table = 't_coatingmachinedetails'; protected $primaryKey = 'id'; protected $useAutoIncrement = true; protected $returnType = 'array'; diff --git a/app/Models/Costcenter_model.php b/app/Models/Costcenter_model.php index ad1290a1..4e57be36 100755 --- a/app/Models/Costcenter_model.php +++ b/app/Models/Costcenter_model.php @@ -13,12 +13,13 @@ class Costcenter_model extends Model * @param number $segment : This is pagination limit * @return array $result : This is result */ - function CostListing() + function CostListing($isActiveFilter) { $builder = $this->db->table('t_costcenter_master as Cost') ->select('Cost.id as id, Cost.CostCenterCode as code,Cost.CostCenterName as CostCenterName , Cost.ApprovedBy as ApprovedBy,Emp.FirstName as FirstName,Emp.Designation as Designation ,Cost.CreatedDate,Cost.IsActive,Cost.DeletedBy,Cost.DeletedBy') ->join('t_employee_details as Emp', 'Emp.EmpID=Cost.ApprovedBy') + ->where('Cost.IsActive',$isActiveFilter) ->orderBy('Cost.CreatedDate', 'desc'); $query =$builder->get(); diff --git a/app/Models/Department_model.php b/app/Models/Department_model.php index 7e943aa2..9ab32dfe 100755 --- a/app/Models/Department_model.php +++ b/app/Models/Department_model.php @@ -49,11 +49,13 @@ class Department_model extends Model * @param number $segment : This is pagination limit * @return array $result : This is result */ - function departmentListing() + function departmentListing($isActiveFilter) { $builder = $this->db->table('t_departmentdetails as BaseT') ->select('BaseT.CreatedDt,BaseT.DepartmentName, BaseT.DEPCode, BaseT.HeadDept, BaseT.IsActive , - BaseT.HeadDept') + BaseT.HeadDept,HeadDept.DepartmentName as headDepartmentName') + ->join('t_departmentdetails as HeadDept', 'BaseT.HeadDept = HeadDept.DEPCode' ,'left') + ->where('BaseT.IsActive',$isActiveFilter) ->orderBy("BaseT.DEPCode", "desc"); $query = $builder->get(); $result = $query->getResult(); diff --git a/app/Models/DrierMachineDetailsModel.php b/app/Models/DrierMachineDetailsModel.php index 9139d5c8..920af9e6 100644 --- a/app/Models/DrierMachineDetailsModel.php +++ b/app/Models/DrierMachineDetailsModel.php @@ -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'; diff --git a/app/Models/Driver_model.php b/app/Models/Driver_model.php index d0b5e716..97fecf21 100755 --- a/app/Models/Driver_model.php +++ b/app/Models/Driver_model.php @@ -285,7 +285,7 @@ class Driver_model extends Model $builder = $this->db->table('t_driver_payroll Pay')->select('Pay.*') ->select('Emp.EmpID,CONCAT_WS(" ", Emp.FirstName, Emp.LastName) as driver_name,Emp.DateofBirth as Dob,Emp.PANNo as Pan,Emp.BankBranchName as BankName,Emp.BankAccountNo as BankAccountNumber,Emp.IFSCCode as IFSCCode,Emp.DateofJoining as DOJ,Emp.AadharNo,Emp.Designation as Designation,Dep.DepartmentName as DeptName,Emp.esi_applicable,Emp.pf_applicable') ->select('t_emp_pay_data.PF_Rate,t_emp_pay_data.ESI_Rate') - ->select('month.Festival_Bonus,month.HRA,month.Loan_Recovered,month.total_diesel_amount,month.total_shed_amount') + ->select('month.Festival_Bonus,month.BASIC,month.HRA,month.Loan_Recovered,month.total_diesel_amount,month.total_shed_amount') // ->select('month.monthly_salary_amount,month.monthly_food_amount,month.Festival_Bonus,month.final_payment,month.HRA,month.ESI,month.PF,month.Loan_Recovered,month.total_diesel_amount,month.total_shed_amount') ->join('t_employee_details Emp', 'Pay.driver_id = Emp.EmpID') ->join('t_departmentdetails Dep', 'Emp.Departmentcode = Dep.DEPCode') diff --git a/app/Models/Employeedetails_model.php b/app/Models/Employeedetails_model.php index a69ac2fa..46dac337 100755 --- a/app/Models/Employeedetails_model.php +++ b/app/Models/Employeedetails_model.php @@ -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.*') diff --git a/app/Models/FactoryMachineModel.php b/app/Models/FactoryMachineModel.php index 12fd7af4..6c363b76 100644 --- a/app/Models/FactoryMachineModel.php +++ b/app/Models/FactoryMachineModel.php @@ -7,7 +7,7 @@ use CodeIgniter\Model; class FactoryMachineModel extends Model { // The table associated with this model - protected $table = 't_factoryMachineMaster'; + protected $table = 't_factorymachinemaster'; // Primary key of the table protected $primaryKey = 'id'; @@ -41,7 +41,7 @@ class FactoryMachineModel extends Model public function checkMachineName($machineId,$machineName){ - $builder = $this->db->table('t_factoryMachineMaster'); + $builder = $this->db->table('t_factorymachinemaster'); if(!empty($machineId)){ $builder = $builder->where('id !=' , $machineId); @@ -62,6 +62,57 @@ class FactoryMachineModel extends Model } + public function getAllActiveElectricMachines(){ + + $result = $this->db->table('t_factorymachinemaster') + ->where('is_active', 1) + ->where('energy_type', 'electric') + ->orderBy('id', 'asc') + ->get() + ->getResultArray(); + + return $result ; + + } + + public function getSelectedElectricMachines($distinctMachineId){ + + $result = $this->db->table('t_factorymachinemaster') + ->whereIn('id', $distinctMachineId) + ->orderBy('id', 'asc') + ->get() + ->getResultArray(); + + return $result; + + } + + public function getAllActiveDieselMachines(){ + + $result = $this->db->table('t_factorymachinemaster') + ->where('is_active', 1) + ->where('energy_type', 'diesel') + ->orderBy('id', 'desc') + ->get() + ->getResultArray(); + + return $result ; + + } + + public function getSelectedDieselMachines($distinctMachineId){ + + $result = $this->db->table('t_factorymachinemaster') + ->whereIn('id', $distinctMachineId) + ->orderBy('id', 'asc') + ->get() + ->getResultArray(); + + return $result; + + } + + } diff --git a/app/Models/FactoryVehicleDieselDetailsModel.php b/app/Models/FactoryVehicleDieselDetailsModel.php index 7a441358..cac41203 100644 --- a/app/Models/FactoryVehicleDieselDetailsModel.php +++ b/app/Models/FactoryVehicleDieselDetailsModel.php @@ -6,7 +6,7 @@ use CodeIgniter\Model; class FactoryVehicleDieselDetailsModel extends Model { - protected $table = 't_factoryVehicleDieselDetails'; + protected $table = 't_factoryvehicledieseldetails'; protected $primaryKey = 'id'; protected $allowedFields = [ diff --git a/app/Models/FactoryVehicleDieselStockSummaryModel.php b/app/Models/FactoryVehicleDieselStockSummaryModel.php index 98462a36..0e37e548 100644 --- a/app/Models/FactoryVehicleDieselStockSummaryModel.php +++ b/app/Models/FactoryVehicleDieselStockSummaryModel.php @@ -6,7 +6,7 @@ use CodeIgniter\Model; class FactoryVehicleDieselStockSummaryModel extends Model { - protected $table = 't_factoryVehicleDieselStockSummary'; + protected $table = 't_factoryvehicledieselstocksummary'; protected $primaryKey = 'id'; protected $allowedFields = [ diff --git a/app/Models/GasShortageModel.php b/app/Models/GasShortageModel.php new file mode 100644 index 00000000..4b8f5be9 --- /dev/null +++ b/app/Models/GasShortageModel.php @@ -0,0 +1,49 @@ +db->table('t_igr_master igr') ->distinct() - ->select("igr.IGRNO,igr.*,igrd.*,MM.MaterialName,MM.UOM,sup.Address,sup.SupplierName,POM.ServiceDescription,POL.Quantity,POL.Rate,POM.POType,POM.IsOpenOrder, - POM.CapitalRange,POM.CapitalRange,st.CGST as service_cgst,st.SGST as service_sgst,st.IGST as service_igst,it.IGST as import_igst,rt.CGST as revenue_cgst,rt.SGST as revenue_sgst,rt.IGST as revenue_igst") + ->select(" + igr.IGRNO,igr.*,igrd.*, + MM.MaterialName,MM.UOM, + sup.Address,sup.SupplierName, + POL.Rate, + POM.ServiceDescription,POL.Quantity,POM.POType,POM.IsOpenOrder, + POM.CapitalRange,POM.CapitalRange, + st.CGST as service_cgst,st.SGST as service_sgst,st.IGST as service_igst, + it.IGST as import_igst, + rt.CGST as revenue_cgst,rt.SGST as revenue_sgst,rt.IGST as revenue_igst, + cd.ConfigValue As MaterialCategory") + ->join('t_igr_details igrd', 'igrd.IGRNO = igr.IGRNO') ->join('t_purchaseorder_master POM', 'igr.PONO = POM.PONO') ->join('t_purchaseorder_lineitem POL', 'igr.PONO = POL.PONO and POL.MaterialCode=igrd.MaterialCode ') @@ -564,6 +574,7 @@ class Inwardgateregister_model extends Model ->join('t_service_tax st', 'st.LineItemNo = POL.LineItemNo' , 'left') ->join('t_revenue_tax rt', 'rt.LineItemNo = POL.LineItemNo' , 'left') ->join('t_import_tax it', 'it.LineItemNo = POL.LineItemNo' , 'left') + ->join('t_configdetails cd','cd.key = MM.Category','left') ->where('igr.IGRNO', $IGRNO); $query = $builder->get(); @@ -1191,7 +1202,7 @@ class Inwardgateregister_model extends Model igrMast.MaterialRcvdDate as materialRecievedDate, igrMast.VehicleNo, supplierDetails.SupplierName, - materialMaster.Category as sandType , + cd.ConfigValue as sandType , t_igr_details.QuantityAsPerInvoice as Qty, issd.*') ->whereIn('t_igr_details.MaterialCode', $materialCodes) @@ -1205,8 +1216,9 @@ 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') ->join('t_supplierdetailsn supplierDetails', 'supplierDetails.SupplierID = poMaster.SupplierID', 'left') ->orderBy('t_igr_details.CreatedDate', 'asc '); diff --git a/app/Models/TrpAbstractParticulars.php b/app/Models/MonthWiseMachinesInStockModel.php similarity index 86% rename from app/Models/TrpAbstractParticulars.php rename to app/Models/MonthWiseMachinesInStockModel.php index 4cef5bd9..ff901a90 100644 --- a/app/Models/TrpAbstractParticulars.php +++ b/app/Models/MonthWiseMachinesInStockModel.php @@ -4,15 +4,15 @@ namespace App\Models; use CodeIgniter\Model; -class TrpAbstractParticulars extends Model +class MonthWiseMachinesInStockModel extends Model { - protected $table = 't_trp_abstract_particulars'; + protected $table = 't_monthwisemachinesinstock'; protected $primaryKey = 'id'; protected $useAutoIncrement = true; protected $returnType = 'array'; protected $useSoftDeletes = false; protected $protectFields = true; - protected $allowedFields = ['particular']; + protected $allowedFields = ['date','machine_id','machine_category']; protected bool $allowEmptyInserts = false; protected bool $updateOnlyChanged = true; diff --git a/app/Models/TrpAbstract.php b/app/Models/MonthWiseMaterialInStockModel.php similarity index 85% rename from app/Models/TrpAbstract.php rename to app/Models/MonthWiseMaterialInStockModel.php index 3df62676..e4626b70 100644 --- a/app/Models/TrpAbstract.php +++ b/app/Models/MonthWiseMaterialInStockModel.php @@ -4,15 +4,15 @@ namespace App\Models; use CodeIgniter\Model; -class TrpAbstract extends Model +class MonthWiseMaterialInStockModel extends Model { - protected $table = 't_trp_abstract'; + protected $table = 't_monthwisematerialinstock'; protected $primaryKey = 'id'; protected $useAutoIncrement = true; protected $returnType = 'array'; protected $useSoftDeletes = false; protected $protectFields = true; - protected $allowedFields = ['abs_opening_stock','abs_physical_stock','abs_remarks','abs_particular_id']; + protected $allowedFields = ['date','materialCode','stock_category']; protected bool $allowEmptyInserts = false; protected bool $updateOnlyChanged = true; diff --git a/app/Models/Payroll_model.php b/app/Models/Payroll_model.php index 3b71a779..48b7e907 100755 --- a/app/Models/Payroll_model.php +++ b/app/Models/Payroll_model.php @@ -172,11 +172,27 @@ class Payroll_model extends Model function getPayOn() { + // For Employee - old $builder = $this->db->table('t_monthly_pay_inputs') ->select('DISTINCT(Month_Year)') ->orderBy("Month_Year", "desc"); $query = $builder->get(); - return $query->getResult(); + $result1 = $query->getResult(); + + // For Driver - new + $builder = $this->db->table('t_driver_monthly_pay_inputs') + ->select('DISTINCT(month_year) as Month_Year') + ->orderBy("month_year", "desc"); + $query = $builder->get(); + $result2 = $query->getResult(); + + $result = array_merge($result1, $result2); + // removed duplicates - refer gpt - gpt solved + $unique = array_map("unserialize", array_unique(array_map("serialize", $result))); + return $unique; + + + } function getBankInfo($bank = "") diff --git a/app/Models/PowerConsumptionDetails.php b/app/Models/PowerConsumptionDetails.php index 67a88fcc..5902ddfa 100644 --- a/app/Models/PowerConsumptionDetails.php +++ b/app/Models/PowerConsumptionDetails.php @@ -6,7 +6,7 @@ use CodeIgniter\Model; class PowerConsumptionDetails extends Model { - protected $table = 't_powerConsumptionDetails'; + protected $table = 't_powerconsumptiondetails'; protected $primaryKey = 'id'; protected $allowedFields = [ diff --git a/app/Models/Rawmaterialdetails_model.php b/app/Models/Rawmaterialdetails_model.php index cbd3a5fa..0cb2b2f8 100755 --- a/app/Models/Rawmaterialdetails_model.php +++ b/app/Models/Rawmaterialdetails_model.php @@ -14,7 +14,7 @@ class Rawmaterialdetails_model extends Model * @param number $segment : This is pagination limit * @return array $result : This is result */ - function rawmaterialListing() + function rawmaterialListing($isActiveFilter) { $builder = $this->db->table('t_materialmaster') @@ -22,6 +22,7 @@ class Rawmaterialdetails_model extends Model ->join('tbl_users as user', 'user.UserId = t_materialmaster.createdby', 'left') ->join('t_employee_details as emp', 'emp.EmpID = user.EmpID', 'left') ->join('t_configdetails as cd', 'cd.Key = t_materialmaster.Category', 'left') + ->where('t_materialmaster.IsActive',$isActiveFilter) ->orderBy('CreatedDate','desc'); $query = $builder->get(); $result = $query->getResult(); @@ -146,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(); @@ -158,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(); diff --git a/app/Models/Requistion_model.php b/app/Models/Requistion_model.php index 47a68809..28af2c0d 100755 --- a/app/Models/Requistion_model.php +++ b/app/Models/Requistion_model.php @@ -387,9 +387,7 @@ class Requistion_model extends Model $this->db->transComplete(); // Complete transaction try { - $result = ($result) ? $result : false; - if ($result && $affected_rows > 0) { - + if ($affected_rows > 0) { $subQuery = 'SELECT ReqNo FROM t_requestion_master ORDER BY CreatedDate DESC LIMIT 1'; $query = $this->db->query($subQuery); diff --git a/app/Models/Supplier_model.php b/app/Models/Supplier_model.php index 16cba09a..69613bb2 100755 --- a/app/Models/Supplier_model.php +++ b/app/Models/Supplier_model.php @@ -14,7 +14,7 @@ class Supplier_model extends Model * @param number $segment : This is pagination limit * @return array $result : This is result */ - function supplierlisting() + function supplierlisting($isActiveFilter) { $builder = $this->db->table('t_supplierdetailsn as BaseT') @@ -22,6 +22,7 @@ class Supplier_model extends Model ->join('t_paymentterms as pmt', 'pmt.PaymentID = BaseT.PaymentID', 'left') ->join('tbl_users as user', 'user.UserId = BaseT.createdby', 'left') ->join('t_employee_details as emp', 'emp.EmpID = user.EmpID', 'left') + ->where('BaseT.IsActive',$isActiveFilter) ->orderBy('BaseT.CreatedOn', 'desc'); $query = $builder->get(); @@ -224,17 +225,19 @@ class Supplier_model extends Model } /*SUPPLIER */ /** for transporter listing */ - function transporterListing() + function transporterListing($isActiveFilter) { + $builder = $this->db->table('t_transporter as t') ->select('t.id,t.name,t_employee_details.FirstName as FirstName,t.created_on,t.isactive') ->join('tbl_users', 'tbl_users.userId = t.created_by') ->join('t_employee_details', 't_employee_details.EmpID=tbl_users.EmpID') - ->orderBy('t.created_on', 'desc'); + ->where('t.isactive',$isActiveFilter); + $builder->orderBy('t.created_on', 'desc'); $query =$builder->get(); $result = $query->getResult(); - // echo $this->db->getLastQuery()->getQuery();die; + // echo $this->db->getLastQuery()->getQuery();die; return $result; } diff --git a/app/Models/TrpAbstractModel.php b/app/Models/TrpAbstractModel.php new file mode 100644 index 00000000..487749ac --- /dev/null +++ b/app/Models/TrpAbstractModel.php @@ -0,0 +1,73 @@ +db->table('t_trp_abstract') + ->where('date',$startDate) + ->where('date',$endDate) + ->get() + ->getResultArray(); + + return $currentMonthTrpAbstract; + + } + + + + + + + + + + + + +} + diff --git a/app/Models/TrpProductionModel.php b/app/Models/TrpProductionModel.php index 0b498b98..55277d90 100644 --- a/app/Models/TrpProductionModel.php +++ b/app/Models/TrpProductionModel.php @@ -60,12 +60,14 @@ class TrpProductionModel extends Model // Subquery definition $subquery = $this->db->table('t_materialmaster') ->select('materialCode') - ->where('Category' ,'waste core') //328 - is for waste core in config master + ->where('Category' ,'328') ->get() ->getResultArray(); $materialCodes = array_column($subquery, 'materialCode'); // Extracts 'materialCode' values + + // dd($this->db->getLastQuery()); // Convert the array of material codes to a comma-separated string diff --git a/app/Models/User_model.php b/app/Models/User_model.php index 2abe7eb9..ebafde7c 100755 --- a/app/Models/User_model.php +++ b/app/Models/User_model.php @@ -15,14 +15,16 @@ class User_model extends Model * @param number $segment : This is pagination limit * @return array $result : This is result */ - function userListing() + function userListing($isDeleted) { $builder = $this->db->table('t_employee_details EMP') - ->select('user.isDeleted,user.createdDtm,EMP.EmpID,EMP.FirstName,EMP.LastName,EMP.Designation,user.email as EmailId,EMP.ContactNumber, + ->select('user.isDeleted,user.createdDtm,EMP.EmpID,EMP.FirstName, + EMP.LastName,EMP.Designation,user.email as EmailId,EMP.ContactNumber, DEPT.DEPCode,DEPT.DepartmentName,role.role,user.userId') - ->join('t_departmentdetails DEPT', 'EMP.Departmentcode = DEPT.DEPCode') - ->join('tbl_users user', 'user.EmpID = EMP.EmpID') - ->join('tbl_roles role', 'user.roleId = role.roleId') + ->join('t_departmentdetails DEPT', 'EMP.Departmentcode = DEPT.DEPCode','left') + ->join('tbl_users user', 'user.EmpID = EMP.EmpID','left') + ->join('tbl_roles role', 'user.roleId = role.roleId','left') + ->where('user.isDeleted',$isDeleted) ->orderBy('user.createdDtm', 'desc'); $query = $builder->get(); diff --git a/app/Views/EditservicePurchaseorder.php b/app/Views/EditservicePurchaseorder.php index f9bd28b4..ae89c7d9 100755 --- a/app/Views/EditservicePurchaseorder.php +++ b/app/Views/EditservicePurchaseorder.php @@ -1,60 +1,61 @@ + }); + }); + "NO", "value" => "0"), @@ -148,6 +151,7 @@ if (!empty($MaxPODate)) { $MaxPoDate = $date->PODate; } } + if (!empty($POMaster)) { foreach ($POMaster as $Req) { @@ -279,8 +283,6 @@ if (!empty($getlogpodtl)) { }); - - + + + // Hide the edit container and show the tag + $editContainer.hide(); + $link.show(); + }); + }); +
- +
-
- - +
+ + + +
- - 'form-label-left ImportPO ', 'name' => 'ImportPO', 'id' => 'ImportPO', 'enctype' => 'multipart/form-data'); - echo form_open(base_url() . '/purchaseorder/addPO/', $attributes); ?> - - -
@@ -550,7 +548,6 @@ if (!empty($getlogpodtl)) {
-
@@ -615,7 +612,6 @@ if (!empty($getlogpodtl)) {
-
Check Today's Foreign Exchange value (Click here) @@ -809,6 +805,7 @@ if (!empty($getlogpodtl)) {
+
@@ -825,264 +822,261 @@ if (!empty($getlogpodtl)) {




- - - - - - - - - - - - - - - - - - - - Rate; +
+
+
SNoRequisition NoItem CodeItem DescriptionLine Item SpecsQuantityUOMRateBasic AmountAction
+ + + + + + + + + + + + + + + + - ?> - - - - - - - - - - - - - - + + " id="" value="ReqNo; ?>" /> - + foreach ($POItem as $record) { + $index = $index + 1; + //echo $record->Rate; - - " /> + ?> + + + + + + + + + + + - - - - - - - - - - - + + - - + + " /> + + + + + + + + + + + + + - - + + - + - - - + - - + - - + + + - - + + - + + + - - - - + + - + + - + - + - - + - + - + - + - + + - + - - + - + - + - + + - + - - + - " id="" value="AfterCustomEdCess; ?>" /> + - if ($PONOStatus == PO_DRAFT || $PONOStatus == PO_CREATED || $PONOStatus == REQITEM_Emergency_PO_CREATED || $PONOStatus == PO_APPROVED) { ?> - - - AfterLandingCharge + $TotalLanding; - $TotalLanding = $TotalLanding + ($record->AfterLandingCharge); - $tothighseas = $tothighseas + $record->AfterHighSeasSalesCharge; - $totcustom = $totcustom + $record->AfterCustomDuty; - $totexciseduty = $totexciseduty + $record->AfterExciseDuty; - $totexcisedutyED = $totexcisedutyED + $record->AfterExciseDutyEdCess; - $totexciseSH = $totexciseSH + $record->AfterExciseDutySHCess; - $totcustomED = $totcustomED + $record->AfterCustomEdCess; + if ($PONOStatus == PO_DRAFT || $PONOStatus == PO_CREATED || $PONOStatus == REQITEM_Emergency_PO_CREATED || $PONOStatus == PO_APPROVED) { ?> + + + AfterCustomSHCess; - $totaddtnlexcise = $totaddtnlexcise + $record->AfterAddlExciseDuty; - $totgrossduty = $totgrossduty + $record->Grossdutypayable; - // $totavlmodvat = $totavlmodvat +$record->AvailableModvat; - //$totgrossduty=$totgrossduty+$record->Grossdutypayable; - $totavlmodvat = $totavlmodvat + $record->AvailableModvat; - $totgrossexpense = $totgrossexpense + $record->Grossexpensesduetocustomduty; - $ExchangeRate = $record->ExchangeRate; - //echo $totorder; - $totorder = $totorder + $record->TotalOrderValue; - //echo $totorder; + //echo $record->AfterLandingCharge + $TotalLanding; + $TotalLanding = $TotalLanding + ($record->AfterLandingCharge); + $tothighseas = $tothighseas + $record->AfterHighSeasSalesCharge; + $totcustom = $totcustom + $record->AfterCustomDuty; + $totexciseduty = $totexciseduty + $record->AfterExciseDuty; + $totexcisedutyED = $totexcisedutyED + $record->AfterExciseDutyEdCess; + $totexciseSH = $totexciseSH + $record->AfterExciseDutySHCess; + $totcustomED = $totcustomED + $record->AfterCustomEdCess; - $totfreight = $totfreight + $record->AfterFreightValue; + $totcustomSH = $totcustomSH + $record->AfterCustomSHCess; + $totaddtnlexcise = $totaddtnlexcise + $record->AfterAddlExciseDuty; + $totgrossduty = $totgrossduty + $record->Grossdutypayable; + // $totavlmodvat = $totavlmodvat +$record->AvailableModvat; + //$totgrossduty=$totgrossduty+$record->Grossdutypayable; + $totavlmodvat = $totavlmodvat + $record->AvailableModvat; + $totgrossexpense = $totgrossexpense + $record->Grossexpensesduetocustomduty; + $ExchangeRate = $record->ExchangeRate; + //echo $totorder; + $totorder = $totorder + $record->TotalOrderValue; - $totassesable = $totassesable + $record->AssessableValue; - $totSubtotal = $totSubtotal + $record->SubTotal; - $totigst = $totigst + $record->AfterIGST; + //echo $totorder; - //echo $totcustomED; - // $totorder=$record->TotalOrderValue; - // //$ServiceDescription=$record->ServiceDescription; - // echo $totorder; - //alert($totorder); + $totfreight = $totfreight + $record->AfterFreightValue; + $totassesable = $totassesable + $record->AssessableValue; + $totSubtotal = $totSubtotal + $record->SubTotal; + $totigst = $totigst + $record->AfterIGST; - } + //echo $totcustomED; + // $totorder=$record->TotalOrderValue; + // //$ServiceDescription=$record->ServiceDescription; + // echo $totorder; + //alert($totorder); - ?> - + } + ?> + - + -
SNoRequisition NoItem CodeItem DescriptionLine Item SpecsQuantityUOMRateBasic AmountAction
ReqNo ?>MaterialCode ?>MaterialName, 0, 13, "..."); - echo $shortName; ?> - - - LineitemAuditorNotes) ? $record->LineitemAuditorNotes : "-"; ?> - - - LineitemAuditorNotes) ? $record->LineitemAuditorNotes : "-"; } ?> - Quantity ?>UOM ?>Rate ?>BasicValue ?>
ReqNo ?>MaterialCode ?>MaterialName, 0, 13, "..."); + echo $shortName; ?> + + + LineitemAuditorNotes) ? $record->LineitemAuditorNotes : "-"; ?> + + + LineitemAuditorNotes) ? $record->LineitemAuditorNotes : "-"; + } ?> + Quantity ?>UOM ?>Rate ?>BasicValue ?>     - -    
    + +    
-
+ $totassesable = number_format($totassesable, 2, '.', ''); + $totSubtotal = number_format($totSubtotal, 2, '.', ''); + $totigst = number_format($totigst, 2, '.', ''); + } + ?> -

- + + +
+
+ +

@@ -1192,8 +1186,8 @@ if (!empty($getlogpodtl)) { > - - + +
@@ -1265,44 +1259,41 @@ if (!empty($getlogpodtl)) {
- - +
-
- - 'txtSpcialInstruction', 'value' => set_value('txtSpcialInstruction', strip_tags($ServiceDescription)), 'id' => 'txtSpcialInstruction', 'class' => 'form-control', 'rows' => '10', 'cols' => '40'); - echo form_textarea($data); - ?> -
+
+ + 'txtSpcialInstruction', 'value' => set_value('txtSpcialInstruction', strip_tags($ServiceDescription)), 'id' => 'txtSpcialInstruction', 'class' => 'form-control', 'rows' => '10', 'cols' => '40'); + echo form_textarea($data); + ?>
-
- +
- -
- - - -
- + +
+ + + +
+
@@ -1311,71 +1302,71 @@ if (!empty($getlogpodtl)) {
-
- - - - - - - - +
- + + + + + + + -   Cancel - -   Save as Draft - -   Submit -   Approve - - + - - - OK - - - -   Submit -   Approve - OK - +   Cancel + +   Save as Draft +   Submit +   Approve + + -
+ + OK + + + +   Submit +   Approve + OK + + + + +
-
- -
-
- 'AWAITING APPROVE', - 'AWAITING RELEASE' => 'AWAITING APPROVE', - 'RELEASER ONHOLD' => 'APPROVER ONHOLD', - 'PO RELEASED' => 'PO APPROVED', - ]; +
- if (isset($StatusName) && !empty($StatusName)) { - if (isset($statusMappings[$StatusName])) { - echo $statusMappings[$StatusName]; - } else { - echo $StatusName; - } +
+
+ 'AWAITING APPROVE', + 'AWAITING RELEASE' => 'AWAITING APPROVE', + 'RELEASER ONHOLD' => 'APPROVER ONHOLD', + 'PO RELEASED' => 'PO APPROVED', + ]; + + if (isset($StatusName) && !empty($StatusName)) { + if (isset($statusMappings[$StatusName])) { + echo $statusMappings[$StatusName]; } else { - echo "Status not provided"; + echo $StatusName; } - ?> - + } else { + echo "Status not provided"; + } + ?> +
@@ -1384,19 +1375,19 @@ if (!empty($getlogpodtl)) { -
-
-
-
-
- - + + + + + + +