diff --git a/app/Config/Autoload.php b/app/Config/Autoload.php index be6c1869..832c52b0 100755 --- a/app/Config/Autoload.php +++ b/app/Config/Autoload.php @@ -90,5 +90,5 @@ class Autoload extends AutoloadConfig * * @var list */ - public $helpers = ['cias','datetime','image','alert','excel']; + public $helpers = ['cias','datetime','image','alert']; } diff --git a/app/Config/Routes.php b/app/Config/Routes.php index f3ea3138..752cfac5 100755 --- a/app/Config/Routes.php +++ b/app/Config/Routes.php @@ -41,6 +41,7 @@ $routes->match(['GET', 'POST', 'PUT', 'DELETE'], 'editUser', 'User::editUser'); $routes->post('user/Deleteuserdepartment', 'User::Deleteuserdepartment'); $routes->get('user/deleteUser', 'User::deleteUser'); $routes->get('user/reActivateUser', 'User::reActivateUser'); +$routes->match(['GET', 'POST', 'PUT', 'DELETE'],'isEmailExists', 'User::isEmailExists'); // Supplier Routes $routes->match(["GET","POST"],'supplierlisting', 'Supplier::index'); // list supplier @@ -203,6 +204,9 @@ $routes->get('deleteLeaveApplicationForm', 'Monthlypay::deleteLeaveApplicationFo $routes->post('validateDateRange', 'Monthlypay::validateDateRange'); $routes->match(['GET', 'POST'], 'leaveApplicationPDF/(:any)', 'Monthlypay::leaveApplicationPDF/$1'); $routes->match(['GET', 'POST'], 'overTimeDetails', 'Monthlypay::overTimeDetails'); +$routes->get('exportMonthlyPayInputs/(:any)', 'Payslip::exportMonthlyPayInputs/$1'); +$routes->get('leaveStatus/(:any)/(:any)', 'Monthlypay::leaveStatus/$1/$2'); + $routes->get('emppaydate/addemppaydate', 'Emppaydate::addemppaydate'); $routes->post('emppaydate/addNewemppay', 'Emppaydate::addNewemppay'); @@ -248,6 +252,7 @@ $routes->post('EditRequisition', 'Requisitionform::EditRequisition'); $routes->post('addNewRequisition', 'Requisitionform::addNewRequisition'); $routes->post('getMaterialCode', 'Requisitionform::getMaterialCode'); $routes->post('getMaterialDetails', 'Requisitionform::getMaterialDetails'); +$routes->post('getCategoryDetails', 'Requisitionform::getCategoryDetails'); $routes->post('DeleteRequistionForm', 'Requisitionform::DeleteRequistionForm'); // recheck it used or not. $routes->post('requisitionform/ApproveRequest', 'Requisitionform::ApproveRequest'); $routes->post('requisitionform/DeleteReqNo', 'Requisitionform::DeleteReqNo'); @@ -322,7 +327,7 @@ $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', 'Inwardgateregister::downloadFilesAsZip'); $routes->post('inwardgateregister/edituploadfile', 'Inwardgateregister::edituploadfile'); $routes->post('getIGRRemarks', 'Inwardgateregister::getIGRRemarks'); $routes->post('saveIGRRemarks', 'Inwardgateregister::saveIGRRemarks'); @@ -330,6 +335,7 @@ $routes->post('updateGasShortage','Inwardgateregister::updateGasShortage'); $routes->get('gasCylinderEntered','Inwardgateregister::gasCylinderEntered'); $routes->get('gasCylinderPending','Inwardgateregister::gasCylinderPending'); $routes->get('gasCylinderReturned','Inwardgateregister::gasCylinderReturned'); +$routes->post('gasCylindersByIgr','Inwardgateregister::gasCylindersByIgr'); $routes->post('getGasShortageDetail',"Inwardgateregister::getGasShortageDetail"); diff --git a/app/Controllers/Configurationctrl.php b/app/Controllers/Configurationctrl.php index 33b81260..1b94d7ee 100755 --- a/app/Controllers/Configurationctrl.php +++ b/app/Controllers/Configurationctrl.php @@ -87,6 +87,7 @@ class Configurationctrl extends BaseController $isActiveFilter = 1 ; // default flag for active data $showArchive = 0 ; // default flag for inactive data + $page = 1; // default page number if ($this->request->getMethod() === 'POST') { @@ -100,6 +101,7 @@ class Configurationctrl extends BaseController if ($this->request->getMethod() === 'GET') { $ConfigID = $this->request->getVar('ConfigID'); + $page = $this->request->getVar('page'); } $data['showArchive'] = $showArchive; @@ -107,7 +109,10 @@ class Configurationctrl extends BaseController $data['master'] = $this->configmodel->GetConfigCenterMaster($ConfigID); $data['child'] = $this->configmodel->GetConfigCenterDetails($ConfigID,$isActiveFilter); + $data['ConfigID'] = $ConfigID; + + $data['page'] = $page; $this->global['pageTitle'] = 'Edit Config'; $this->loadViews("editconfig", $this->global, $data, NULL); @@ -121,6 +126,7 @@ class Configurationctrl extends BaseController $ConfigName = $this->request->getPost('ConfigName'); $Comments = $this->request->getPost('Remarks'); $Rowcount = $this->request->getPost('txtRowCount'); + $page = $this->request->getGet('page')??1; $config = array('Config_ID' => $ConfigId, 'ConfigName' => $ConfigName, 'Comments' => $Comments); $result = $this->configmodel->updateconfig($config, $ConfigId); @@ -142,7 +148,7 @@ class Configurationctrl extends BaseController $this->session->setFlashdata('success', 'Configuration Updated successfully!'); - return redirect()->route('configlisting'); + return redirect()->to('/configlisting?page=' . $page); } @@ -252,8 +258,10 @@ class Configurationctrl extends BaseController $configId = $data['ConfigID']; $configValue = $data['ConfigValue']; $key = $data['key']??''; + $userId = $data['userId']; - $result = $this->configmodel->saveConfigValue($key,$configId, $configValue); + + $result = $this->configmodel->saveConfigValue($key,$configId, $configValue,$userId); if($result){ return $this->response->setJSON(['status'=>true]); diff --git a/app/Controllers/Driver.php b/app/Controllers/Driver.php index 625175e4..e6ef6307 100755 --- a/app/Controllers/Driver.php +++ b/app/Controllers/Driver.php @@ -561,7 +561,6 @@ class Driver extends BaseController $html = view("driverPayslipGeneratePrint", $Data); } - $mpdf = new Mpdf([ 'mode' => 'utf-8', 'format' => 'A4-P', diff --git a/app/Controllers/Employeedetails.php b/app/Controllers/Employeedetails.php index 8847a3f7..c447fdab 100755 --- a/app/Controllers/Employeedetails.php +++ b/app/Controllers/Employeedetails.php @@ -926,108 +926,145 @@ class Employeedetails extends BaseController function exportemployee() { $exportData = $this->employeedetails_model->export_excel(); - + $companyName = $this->companydetailsmodel->companylisting(); + $companyName = isset($companyName[0]->CompanyName) ? $companyName[0]->CompanyName : "Resico India Pvt Ltd"; $file_name = 'Employee_Details' . ' ' . '.xls'; //save our workbook as this file name + $spreadsheet = new Spreadsheet(); $sheet = $spreadsheet->getActiveSheet(); - $sheet->mergeCells('L3:S3'); - $sheet->getStyle('L3')->getAlignment()->setHorizontal('center'); - $sheet->setTitle('Employee details'); + $sheet->mergeCells('A1:AN1'); + $sheet->getStyle('A1')->getAlignment()->setHorizontal('center'); + $sheet->setTitle('Employee Details');// Sheet 1 replaced $headers = [ - 'L3' => 'RESICO Employee Details', - 'A5' => 'EmpID', - 'B5' => 'FirstName-LastName', - 'C5' => 'FatherName', - 'D5' => 'Gender', - 'E5' => 'Date of Birth', - 'F5' => 'ContactNumber', - 'G5' => 'EmailId', - 'H5' => 'BloodGroup', - 'I5' => 'MartialStatus', - 'J5' => 'DateofJoining', - 'K5' => 'PreviousYearsOfExp', - 'L5' => 'Designation', - 'M5' => 'DepartmentName', - 'N5' => 'PresentAddress', - 'O5' => 'PermanentAddress', - 'P5' => 'EmergencyContactName', - 'Q5' => 'EmergencyContactNumber', - 'R5' => 'Edu_Qualification', - 'S5' => 'Additional_Qualification', - 'T5' => 'Reference_Name', - 'U5' => 'Reference_ContactNumber', - 'V5' => 'BankStatemant', - 'W5' => 'AadharNo', - 'X5' => 'PANNo', - 'Y5' => 'PassportNo', - 'Z5' => 'Passport_Valid_till', - 'AA5' => 'Voter ID', - 'AB5' => 'Driving License', - 'AC5' => 'Driving License Expiry Date', - 'AD5' => 'Official Email ID', - 'AE5' => 'IsActive', - 'AF5' => 'PFNO', - 'AG5' => 'ESI', - 'AH5' => 'Nominee Details', - // 'AI5'=>'PF_Balance', - // 'AJ5'=>'PF_Bal_On', - 'AI5' => 'Remarks', - 'AJ5' => 'CreatedBy', - 'AK5' => 'UpdatedBY' + 'A1' => $companyName.' - Employee Details', + 'A2' => 'EmpID',// personal + 'B2' => 'Name', + 'C2' => 'Father / Husband Name', + 'D2' => 'Gender', + 'E2' => 'Date of Birth', + 'F2' => 'ContactNumber', + 'G2' => 'MartialStatus', + 'H2' => 'Date of Joining', + 'I2' => 'Previous Years of Experience', + 'J2' => 'Designation', + 'K2' => 'DepartmentName', + 'L2' => 'PresentAddress', + 'M2' => 'PermanentAddress', + 'N2' => 'Qualification', + 'O2' => 'Work_Location', + 'P2' => 'Management Team', + 'Q2' => 'Driver', + + 'R2' => 'Bank Name', // bank & Work related + 'S2' => 'Account Number', + 'T2' => 'IFSC', + 'U2' => 'Bank Address', + 'V2' => 'Total Salary', + 'W2' => 'Basic Pay', + 'X2' => 'HRA Rate(%)', + 'Y2' => 'HRA Amount', + 'Z2' => 'UAN', + 'AA2' => 'PF Applicable', + 'AB2' => 'PF Rate(%)', + 'AC2' => 'ESI Applicable', + 'AD2' => 'ESI Rate(%)', + 'AE2' => 'ESI Number', + 'AF2' => 'TDS Applicable', + 'AG2' => 'TDS Rate(%)', + + 'AH2' => 'Aadhar Number', //IDentity + 'AI2' => 'PAN Number', + 'AJ2' => 'Passport Number', + + 'AK2' => 'Active / Inactive',// Others + 'AL2' => 'Reason', + 'AM2' => 'Created By', + 'AN2' => 'Updated By' + ]; foreach ($headers as $cell => $value) { $sheet->setCellValue($cell, $value); - $sheet->getStyle($cell)->getFont()->setSize($cell == 'L3' ? 14 : 12); + $sheet->getStyle($cell)->getFont()->setSize($cell == 'A1' ? 14 : 12); $sheet->getStyle($cell)->getFont()->setBold(true); } + $sheet->getStyle("A2:AN2")->applyFromArray([ + 'font' => [ + 'bold' => true, + 'size' => 12, + ], + 'alignment' => [ + 'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER, + 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER, + ] + ]); + + // $sheet->getRowDimension(5)->setRowHeight(25); + + + foreach (range('A', 'Z') as $col) { + $sheet->getColumnDimension($col)->setAutoSize(true); + } + foreach (range('A', 'N') as $col) { + $sheet->getColumnDimension('A' . $col)->setAutoSize(true); + } + + + if ($exportData) { - $i = 6; + $i = 3; $s = 1; foreach ($exportData as $data) { + ; + // $dob = get_date_time_dynamical_format("Y-m-d H:i:s","d-m-Y","$data['DateofBirth']"); $rowData = [ - 'A' . $i, - $data['EmpID'], - 'B' . $i => $data['FirstName'] . '-' . $data['LastName'], + 'A' . $i => $data['EmpID'], + 'B' . $i => $data['Name'], 'C' . $i => $data['FatherName'], 'D' . $i => $data['Gender'], - 'E' . $i => $data['DateofBirth'], + 'E' . $i => get_date_time_dynamical_format("Y-m-d H:i:s","d-m-Y",$data['DateofBirth']), 'F' . $i => $data['ContactNumber'], - 'G' . $i => $data['EmailId'], - 'H' . $i => $data['BloodGroup'], - 'I' . $i => $data['MartialStatus'], - 'J' . $i => $data['DateofJoining'], - 'K' . $i => $data['PreviousYearsOfExp'], - 'L' . $i => $data['Designation'], - 'M' . $i => $data['DepartmentName'], - 'N' . $i => $data['PresentAddress'], - 'O' . $i => $data['PermanentAddress'], - 'P' . $i => $data['EmergencyContactName'], - 'Q' . $i => $data['EmergencyContactNumber'], - 'R' . $i => $data['Edu_Qualification'], - 'S' . $i => $data['Additional_Qualification'], - 'T' . $i => $data['Reference_Name'], - 'U' . $i => $data['Reference_ContactNumber'], - 'V' . $i => $data['BankAccountNo'] . '-' . $data['IFSCCode'] . '-' . $data['BankBranchName'] . $data['BankAddress'], - 'W' . $i => $data['AadharNo'], - 'X' . $i => $data['PANNo'], - 'Y' . $i => $data['PassportNo'], - 'Z' . $i => $data['Passport_Valid_till'], - 'AA' . $i => $data['VoterID'], - 'AB' . $i => $data['DriverLicense'], - 'AC' . $i => $data['LicenseValidtill'], - 'AD' . $i => $data['personalEmailId'], - 'AE' . $i => $data['IsActive'], - 'AF' . $i => $data['PFNO'], - 'AG' . $i => $data['ESI'], - 'AH' . $i => $data['NomineeDetails'], - // 'AI'. $i=>$data['PF_Balance'], - // 'AJ'. $i=>$data['PF_Bal_On'], - 'AI' . $i => $data['Remarks'], - 'AJ' . $i => $data['CreatedByName'], - 'AK' . $i => $data['UpdatedByName'], + 'G' . $i => $data['MartialStatus'], + 'H' . $i => get_date_time_dynamical_format("Y-m-d H:i:s","d-m-Y",$data['DateofJoining']), + 'I' . $i => $data['PreviousYearsOfExp'] ? $data['PreviousYearsOfExp'] : 0, + 'J' . $i => $data['Designation'], + 'K' . $i => $data['DepartmentName'], + 'L' . $i => $data['PresentAddress'], + 'M' . $i => $data['PermanentAddress'], + 'N' . $i => $data['Edu_Qualification'], + 'O' . $i => $data['work_location'], + 'P' . $i => $data['is_management_team'] ? $data['is_management_team'] : '-', + 'Q' . $i => $data['is_driver'] ? $data['is_driver'] : '-', + + 'R' . $i => $data['BankBranchName'],//bank related + 'S' . $i => $data['BankAccountNo'], + 'T' . $i => $data['IFSCCode'], + 'U' . $i => $data['BankAddress'], + 'V' . $i => $data['TotalSalary'], //'Total Salary', + 'W' . $i => $data['Basic_Pay'], //'Basic Pay', + 'X' . $i => $data['HRA_Rate'], //'HRA Rate(%)', + 'Y' . $i => $data['HRA_Amount'], //'HRA Amount', + 'Z' . $i => $data['UANO'], //'UAN', + 'AA' . $i => $data['pf_applicable'] ? $data['pf_applicable'] : 0, //'PF Applicable', + 'AB' . $i => $data['PF_Rate'], //'PF Rate(%)', + // 'AC' . $i => $data['PFNO'], + 'AC' . $i => $data['esi_applicable'] ? $data['esi_applicable'] : 0 , //'ESI Applicable', + 'AD' . $i => $data['ESI_Rate'], //'ESI Rate(%)', + 'AE' . $i => $data['ESI'], //'ESI Number', + 'AF' . $i => $data['tds_applicable'] ? $data['tds_applicable'] : 0, //'TDS Applicable', + 'AG' . $i => $data['TDS_Rate'], //'TDS Rate(%)', + + + 'AH' . $i => $data['AadharNo'] ? $data['AadharNo'] : '-', //IDentity + 'AI' . $i => $data['PANNo'] ? $data['PANNo'] : '-', + 'AJ' . $i => $data['PassportNo'] ? $data['PassportNo'] : '-', + + 'AK' . $i => $data['IsActive'] == 1 ? 'Active' : "In-active",//others + 'AL' . $i => $data['reason'] ? $data['reason'] : '-', + 'AM' . $i => $data['CreatedByName'], + 'AN' . $i => $data['UpdatedByName'], ]; foreach ($rowData as $cell => $value) { diff --git a/app/Controllers/Emppaydate.php b/app/Controllers/Emppaydate.php index 067cb80c..6439057c 100755 --- a/app/Controllers/Emppaydate.php +++ b/app/Controllers/Emppaydate.php @@ -150,8 +150,28 @@ class Emppaydate extends BaseController function downloadEmpLoanData($paydataid = "") { - $data['emppay'] = $this->emppaydate_model->getUserInfo($paydataid); - + $emppay = $this->emppaydate_model->getUserInfo($paydataid); + + $monthYear = get_date_time_dynamical_format('Y-m-d','m-Y',get_current_date()); + // $monthYear = "02-2025"; + foreach ($emppay as $index => $value) { + if($value->is_driver) { + $info = $this->emppaydate_model->driverPayInfo($value->PAYEMPID, $monthYear); + + foreach ($info as $i => $v) { + + $hra = $v->HRA; // => 885.60 + $esi = $v->ESI; // => 0.00 + $pf = $v->PF; // => 0.00 + $basic = $v->BASIC; + $TotalSalary = ($basic + $hra + $v->Festival_Bonus) - ($value->Monthly_Due+$esi + $pf); + $emppay[$index]->TotalSalary = $TotalSalary; + $emppay[$index]->Basic_Pay = $basic; + } + } + } + $data['emppay'] = $emppay; + $data['loan_histoty'] = $this->emppaydate_model->getUserLoanHistoryInfo($data['emppay'][0]->Loan_ID); diff --git a/app/Controllers/Inwardgateregister.php b/app/Controllers/Inwardgateregister.php index 7d50bf69..80cd15e5 100755 --- a/app/Controllers/Inwardgateregister.php +++ b/app/Controllers/Inwardgateregister.php @@ -299,8 +299,9 @@ class Inwardgateregister extends BaseController $PO = $this->request->getPost('id'); $CreatedBy = $this->session->get('userId'); - $this->inwardgateregister_model->UpdatePOMaster($PO, $CreatedBy,IGR_CREATED); + // $this->inwardgateregister_model->UpdatePOMaster($PO, $CreatedBy,IGR_CREATED); $data = $this->inwardgateregister_model->viewpurchaseorder($PO); + // echo "
"; print_r($data);die;
 
     echo json_encode($data);
   }
@@ -1080,24 +1081,29 @@ function updateIGRWeight(){
   $this->saveIGRLineitemHistory($igr_lineitem, $IGRNO,$IGRItemNo);
 
   $requestWeightFileName =null ;
-  if($WeightFile){
-    if (!empty($requestWeightFileName)) {
-      if ($WeightFile && $WeightFile->isValid() && !$WeightFile->hasMoved()) {
-        if (!empty($this->inwardgateregister_model->isFileExistsInIGRdetails($requestWeightFileName))) {
-          log_message('error', 'File already exists in the database'.$requestWeightFileName);
-        }
-        else{
-          $WeightFile->move($path, $requestWeightFileName);   
-          $igr_lineitem['WeightFile'] = $requestWeightFileName;
-        }
-      }
+  $msg = null;
+  if ($WeightFile && $WeightFile->isValid() && !$WeightFile->hasMoved()) {
+    
+    $requestWeightFileName = $WeightFile->getName(); // Generate a unique name
+
+    // Optional: Check for duplicates in DB if needed
+    if (!empty($this->inwardgateregister_model->isFileExistsInIGRdetails($requestWeightFileName))) {
+        log_message('error', 'File already exists in the database: ' . $requestWeightFileName);
+        $msg = "'File already exists in the database: ' . $requestWeightFileName";
+    } else {
+        $WeightFile->move($path, $requestWeightFileName);   
+        $igr_lineitem['WeightFile'] = $requestWeightFileName;
+        $msg = "";
     }
+  }else{
+    log_message('error', 'File invlisd: ' . $requestWeightFileName);
+    $msg = "";
   }
-  
+
   $update = $this->inwardgateregister_model->updateIGRLineItem($igr_lineitem, $IGRItemNo);
     
   if ($update) {
-    echo "Details update successfully!";
+    echo "Details updated successfully!\n".$msg;
   }
 }
   function AddOgr()
@@ -1327,75 +1333,82 @@ function updateIGRWeight(){
     }
   }
   
-  public function downloadFilesAsZip($igrno)
-  {
-      // Get all file details for the given IGR number
-      $fileDetails = $this->inwardgateregister_model->getAllIgrFileDetails($igrno); 
   
-      // Define the root path for files
-      $rootPath = ROOTPATH . 'public/uploads/Igrfiles/';
-      
-      // Check if the directory exists, create if it doesn't
-      if (!is_dir($rootPath)) {
-          if (!mkdir($rootPath, 0755, true)) {
-              echo '';
-              return;
-          }
-      }
-  
-      // Ensure the directory is writable
-      if (!is_writable($rootPath)) {
-          echo '';
-          return;
-      }
-  
-      // Create a new ZIP archive
-      $zip = new ZipArchive();
-      $zipFileName = $igrno . '.zip';
-      $zipFilePath = $rootPath . $zipFileName;
-  
-      // Attempt to open the ZIP file
-      if ($zip->open($zipFilePath, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== TRUE) {
-          echo '';
-          return redirect()->to('/ViewIGR');
-      }
-  
-      $filesAdded = false;
-  
-      // Add each file to the ZIP archive
-      foreach ($fileDetails as $file) {
-          $filePath = $rootPath . $file->file;
-  
-          // Ensure file exists and is not a directory
-          if (file_exists($filePath) && is_file($filePath)) {
-              // Sanitize filename for ZIP
-              $sanitizedFilename = preg_replace('/[^a-zA-Z0-9_\-\.]/', '_', $file->file);
-              if (!$zip->addFile($filePath, $sanitizedFilename)) {
-                  echo '';
-                  $zip->close();
-                  return redirect()->to('/ViewIGR');
-              }
-              $filesAdded = true;
-          } else {
-              echo '';
-              continue;
-          }
-      }
-  
-      // Close ZIP archive if files were added
-      if ($filesAdded) {
-          $zip->close(); // Close ZIP only if files were added
-          return $this->response->download($zipFilePath, null)->setFileName($zipFileName);
-      } else {
-          // Close and remove any empty ZIP file created
-          $zip->close();
-          if (file_exists($zipFilePath)) {
-              unlink($zipFilePath);
-          }
-          echo '';
-          return redirect()->to('/ViewIGR');
-      }
-  }
+
+  public function downloadFilesAsZip()
+{
+    // Get the IGR number from query string
+    $igrno = $this->request->getGet('IGRNO'); 
+
+    // Get file details based on IGR number
+    $fileDetails = $this->inwardgateregister_model->getAllIgrFileDetails($igrno); 
+
+    // Define root path for original files
+    $fileRootPath = ROOTPATH . 'public/uploads/Igrfiles/';
+
+    // Define separate directory for ZIP output
+    $zipDir = ROOTPATH . 'writable/zips/';
+    if (!is_dir($zipDir)) {
+        if (!mkdir($zipDir, 0777, true)) {
+            echo '';
+            return;
+        }
+    }
+
+    // Make sure ZIP directory is writable
+    if (!is_writable($zipDir)) {
+        echo '';
+        return;
+    }
+
+    // OPTIONAL: Set PHP's temp directory if the system one is failing
+    $customTemp = ROOTPATH . 'writable/tempzip/';
+    if (!is_dir($customTemp)) {
+        mkdir($customTemp, 0777, true);
+    }
+    ini_set('sys_temp_dir', $customTemp);
+
+    // Create ZIP archive
+    $zip = new ZipArchive();
+    $zipFileName = preg_replace('/[^a-zA-Z0-9_\-]/', '_', $igrno) . '.zip'; // sanitize filename
+    $zipFilePath = $zipDir . $zipFileName;
+
+    if ($zip->open($zipFilePath, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== TRUE) {
+        echo '';
+        return redirect()->to('/ViewIGR');
+    }
+
+    $filesAdded = false;
+
+    // Add each file to ZIP
+    foreach ($fileDetails as $file) {
+        $filePath = $fileRootPath . $file->file;
+
+        if (file_exists($filePath) && is_file($filePath)) {
+            $sanitizedFilename = preg_replace('/[^a-zA-Z0-9_\-\.]/', '_', $file->file);
+            if (!$zip->addFile($filePath, $sanitizedFilename)) {
+                echo '';
+                $zip->close();
+                return redirect()->to('/ViewIGR');
+            }
+            $filesAdded = true;
+        } else {
+            echo '';
+        }
+    }
+
+    if ($filesAdded) {
+        $zip->close();
+        return $this->response->download($zipFilePath, null)->setFileName($zipFileName);
+    } else {
+        $zip->close();
+        if (file_exists($zipFilePath)) {
+            unlink($zipFilePath);
+        }
+        echo '';
+        return redirect()->to('/ViewIGR');
+    }
+}
 
 
 
@@ -1696,6 +1709,26 @@ function updateIGRWeight(){
           ]);
       }
   }
+
+  public function gasCylindersByIgr(){
+
+    $IGRNO = $this->request->getPost('IGRNO');
+
+    $gasMaterialCodes = $this->rawMaterialDetails_model->getAllGasMaterialCode();
+
+    $gasMaterialCodes = array_column($gasMaterialCodes,'MaterialCode');
+    
+    $cylinderDetails = $this->inwardgateregister_model->gasCylindersByIgr($IGRNO , $gasMaterialCodes);
+
+    $response = [
+        'status' => 'success',
+        'message' => 'Gas cylinders retrieved successfully.',
+        'data' => $cylinderDetails
+    ];
+
+    return $this->response->setJSON($response);
+
+  }
   
   /*
   *********************************************************  sec_gas_shortage_ends  **************************************************************
diff --git a/app/Controllers/Monthlypay.php b/app/Controllers/Monthlypay.php
index 453ffa6c..469b535f 100755
--- a/app/Controllers/Monthlypay.php
+++ b/app/Controllers/Monthlypay.php
@@ -970,7 +970,7 @@ class Monthlypay extends BaseController
         $this->global['pageTitle'] = 'Employee Leave Application Form';        
         $data['leave_info'] = $this->monthlypay_model->getheringleaveApplicationForm();
         $data['employee_info'] = $this->monthlypay_model->getheringemployeeinformation();
-        $data['status_info'] = ["Draft","Approved"];
+        $data['status_info'] = ["Draft","Approved","Cancel"];
         $this->loadviews('employeeLeaveApplicationForm', $this->global, $data, NULL);
     }
 
@@ -991,18 +991,19 @@ class Monthlypay extends BaseController
                 
                 $leave_details['created_by'] = $userId;
                 $affectedRows = $this->monthlypay_model->saveleaveApplicationForm($leave_details,$id);
-                 if ($affectedRows > 0) {
+                //  if ($affectedRows > 0) {
                     $data = ['status' => true, 'message' => 'Leave Applicationform details created successfully.'];
-                 }
+                //  }
             } else {
                 $leave_details['leave_application_id'] = $id;
                 $leave_details['updated_by'] = $userId;
                 $affectedRows = $this->monthlypay_model->saveleaveApplicationForm($leave_details,$id);
-                if ($affectedRows > 0) {
-                    $data = ['status' => true, 'message' => 'Leave Applicationform details updated successfully.'];
-                }else{
-                    $data = ['status' => true, 'message' => 'There is no changes in Leave Applicationform details.'];
-                } 
+                // if ($affectedRows > 0) {
+                //     $data = ['status' => true, 'message' => 'Leave Applicationform details updated successfully.'];
+                // }else{
+                //     $data = ['status' => true, 'message' => 'There is no changes in Leave Applicationform details.'];
+                // } 
+                $data = ['status' => true, 'message' => 'Leave Applicationform details updated successfully.'];
                 
             }
     
@@ -1041,6 +1042,26 @@ class Monthlypay extends BaseController
 
     }
 
+    public function leaveStatus($leave_application_id, $status)
+    {
+        if (!empty($leave_application_id)) {
+            $data = [
+                'status' => $status,
+                'updated_by' => session()->get('userId')
+            ];
+
+            $affectedRows = $this->monthlypay_model->saveleaveApplicationForm($data, $leave_application_id);
+            $message = ($affectedRows > 0) 
+                ? "Leave Application updated successfully." 
+                : "No changes were made.";
+
+            return $this->response->setJSON(['status' => true, 'message' => $message]);
+        } else {
+            return $this->response->setJSON(['status' => false, 'message' => 'Invalid leave application ID.']);
+        }
+    }
+
+
     public function leaveApplicationPDF($leave_application_id){
         
       
diff --git a/app/Controllers/Payslip.php b/app/Controllers/Payslip.php
index 887ee555..0e8ed2db 100755
--- a/app/Controllers/Payslip.php
+++ b/app/Controllers/Payslip.php
@@ -287,14 +287,7 @@ class Payslip extends BaseController
 			$empSalarySub = $esiAmount + $pfAmount + $loan;
 			
 			$salaryInCurrentday =  $empSalaryAdd -  $empSalarySub;
-			// echo $esiAmount .'
'; - // echo $pfAmount .'
'; - // echo $loan .'
'; - // echo $empSalarySub .'
'; - // echo $empSalaryAdd .'
'; - // echo $salaryInCurrentday .'
'; - // die; - + $employeeSalary[] = round($salaryInCurrentday); $esi[] = number_format($esiAmount,2, '.', ''); $pf[] = number_format($pfAmount,2, '.', ''); @@ -309,6 +302,331 @@ class Payslip extends BaseController $this->loadViews("monthlypayinputs", $this->global, $data, NULL); } + public function exportMonthlyPayInputs1($value) + { + $headlines = [ + 'company_name' => 'Resico Solutions', + 'file_name' => 'Resico_Salary_'.$value.'.xls', + 'type' => 1, + 'header1' => ['Emp ID', 'Name', 'Department', 'Salary'], // example headers + 'header2' => [], + 'footer' => false, + ]; + + $xldata = [ + ['E001', 'Arun', 'HR', 25000], + ['E002', 'Meena', 'Finance', 28000], + ]; + + helper('excel'); + generate_excel($headlines, $xldata); + } + + + public function exportMonthlyPayInputs($value){ + + helper('excel'); + $monthyear = get_date_time_dynamical_format('n-Y','m-Y',"$value"); + $employee = [];$i=0; $j=0; + $company_info = $this->payroll_model->getCompanyInformation(); + $employee_monthinputs_info = $this->monthlypay_model->getEmpPayDetailsforMonthInputs($monthyear); + $driver_monthinputs_info = $this->driverMonthlyPayInputs($monthyear); + // $headlines_main = ['S. No','Emp ID','Employees Name','Date of Joining','Destingnation','Total Days' ,'Days Worked','Leave','Basic Salary','Per day Salary','Worked Salary','Per Hours Salary','Earned Salary', '70% BASIC','30% HRA','Gross Salary','Esi 0.75%','Pf 12%','Esi + Pf (Ee`s)' ,'Over Time','Feb-25 Advance','TDS 92B','Refuned PF Nov24','Net Salary','Gross Salary','Over Time','Gross Net Salary','Esi (0)','Pf (0)','Sep-24 Advance','TDS 92B','Refuned PF Nov24','Net Salary','Diff']; + $headlines_main = ['S. No','Emp ID','Employees Name','Date of Joining','Destingnation','Total','Days','Leave','Basic','Per day','Worked','Per Hours','Earned','70%','30%','Gross','Esi','Pf','Esi + Pf','Over Time','Feb-25 Advance','TDS 92B','Refuned PF Nov24','Net Salary','Gross','Over Time','Gross Net','Esi','Pf','Sep-24 Advance','TDS 92B','Refuned PF Nov24','Net Salary','Diff']; + + $headlines_sub = ['', '', '', '', '', 'Days','Worked','', 'Salary','Salary','Salary','Salary','Salary', 'BASIC','HRA','Salary','0.75%','12%','Ee`s','','','','','','Salary','','Salary',' 0','0','','','','','']; + + $dum = []; + foreach ($employee_monthinputs_info as $key => $rec) { + // echo $rec->EmpID; + // print_r($dum);die; + $dum[$rec->EmpID] = $rec; + } + $employee_monthinputs_info = array_values($dum); + + + foreach ($employee_monthinputs_info as $value) { + + $employee[$i]['SNO'] = $i+1; + $employee[$i]['ID'] = $value->EmpID; + $employee[$i]['Name'] = $value->FirstName; + $employee[$i]['DOJ'] = get_date_time_dynamical_format('Y-m-d H:i:s','d-m-Y',"$value->DateofJoining"); + $employee[$i]['Designation'] = $value->Designation ; + $NoofDays = $value->NoofDays; // Month day 30,31,28 + $employee[$i]['NoofDays'] = round($NoofDays); + $Days_worked = $value->Days_worked; // Work day + $employee[$i]['Days_worked'] = round($Days_worked); + $employee[$i]['Leave'] = round($value->NoofDays - ($Days_worked)); // Absent Days LOP + $Basic_Pay = $value->Basic_Pay; + // $employee[$i]['Basic_Pay'] = $Basic_Pay; + $TotalSalary = $value->TotalSalary; + $employee[$i]['TotalSalary'] = number_format($TotalSalary, 2, '.', ''); + $PerDaySalary = $value->TotalSalary / $NoofDays; + $employee[$i]['PerDaySalary'] = number_format($PerDaySalary, 2, '.', ''); + + $WorkedSalary = $PerDaySalary * ($Days_worked); + $employee[$i]['WorkedSalary'] = number_format($WorkedSalary, 2, '.', ''); + $PerHrSalary = $PerDaySalary / 8; + $employee[$i]['PerHrSalary'] = number_format($PerHrSalary, 2, '.', ''); + $employee[$i]['EarnedSalary'] = number_format($WorkedSalary, 2, '.', ''); + + $BasicWorked = $WorkedSalary * 70 / 100; + $employee[$i]['BasicWorked'] = number_format($BasicWorked, 2, '.', ''); + $HraWorked = $WorkedSalary * 30 / 100; + $employee[$i]['HraWorked'] = number_format($HraWorked, 2, '.', ''); + $employee[$i]['GrossSalary'] = number_format($BasicWorked + $HraWorked, 2, '.', ''); + if ($value->is_management_team == 1) + { + $OT_Hrs_Worked = 0; //OT hours + $value->OT_Hrs_Worked = 0; + } else { + $OT_Hrs_Worked = $value->OT_Hrs_Worked; //OT hours + } + $totSalayOT = ($OT_Hrs_Worked != 0) ? $OT_Hrs_Worked * $PerHrSalary : 0; + + $HRA_Amount = $value->HRA_Amount; + $Paid_leave = $value->Paid_leave; // leave day + $Monthly_Due = $value->Monthly_Due; // AUTO LOAN DUE + $Loan_Recovered = $value->Loan_Recovered; //MANUAL LOAN DUE + $due_start_date = $value->DueDate; + + if (strlen((string)$monthyear) == 6) { + $monthyear = '0' . $monthyear; + } + $pmonth = substr($monthyear, 0, 2); + $pyear = substr($monthyear, -4); + + $pmonth = substr($monthyear, 0, 2); + $pyear = substr($monthyear, -4); + $pday = cal_days_in_month(CAL_GREGORIAN, $pmonth, $pyear); + $payfulldate = $pyear . '-' . $pmonth . '-' . $pday; + $totalDaysWorked = $Days_worked + $Paid_leave; + $Loan_amount = $value->Loan_Amount; + $Paid_Amount = $value->Paid_Amount; + $Balance_Amount = $Loan_amount - $Paid_Amount; + $loan = 0; + if ($Loan_Recovered == 'NA') { + $loan = 0.00; + } else if ($Loan_Recovered == 0.00) { + if (strtotime($due_start_date) <= strtotime($payfulldate)) { + $loan = $Monthly_Due; + } + } else if ($Loan_Recovered >= 0.00) { + if (strtotime($due_start_date) <= strtotime($payfulldate)) { + $loan = $Loan_Recovered; + } + } + + if ($Monthly_Due > $Balance_Amount) { + $loan = $Balance_Amount; + } + + $PF_Rate = $value->PF_Rate; + $ESI_Rate = $value->ESI_Rate; + + $dayHra = $HRA_Amount / $NoofDays; + $dayBasic = $Basic_Pay / $NoofDays; + + //current day basic and hra salary + if ($value->is_management_team == 1) + { + $currentDayBasic = $dayBasic * $NoofDays; + $currentDayHra = $dayHra * $NoofDays; + } else { + $currentDayBasic = $dayBasic * $totalDaysWorked; + $currentDayHra = $dayHra * $totalDaysWorked; + } + + if ($value->esi_applicable == 1) { $esiAmount = ($currentDayBasic + $currentDayHra) * $ESI_Rate / 100; } else { $esiAmount = 0; } + if ($value->pf_applicable == 1) { $pfAmount = $currentDayBasic * $PF_Rate / 100; } else { $pfAmount = 0; } + + /** pf amount per day**/ + + //echo $totalothour;die; + $empSalaryAdd = $currentDayBasic + $currentDayHra + $totSalayOT; + + $empSalarySub = $esiAmount + $pfAmount + $loan; + + $salaryInCurrentday = $empSalaryAdd - $empSalarySub; + + $employee[$i]['ESI'] = number_format($esiAmount, 2, '.', ''); + $employee[$i]['PF'] = number_format($pfAmount, 2, '.', ''); + $employee[$i]['ESI_PF'] = number_format($esiAmount + $pfAmount, 2, '.', ''); + $employee[$i]['OT'] = number_format($totSalayOT, 2, '.', ''); + + $employee[$i]['Feb_25_Advance'] = "-"; + $employee[$i]['TDS_92B'] ="-"; + $employee[$i]['Refuned_PF_Nov24'] ="-"; + $employee[$i]['NetSalary'] = round($salaryInCurrentday); + + $employee[$i]['GrossSalary2'] = "-"; + $employee[$i]['OT2'] = "-"; + $employee[$i]['GrossNetSalary'] = "-"; + $employee[$i]['ESI2'] ="-"; + $employee[$i]['PF2'] ="-"; + $employee[$i]['Sep_24_Advance'] = "-"; + $employee[$i]['TDS_92B'] = "-"; + $employee[$i]['Refuned_PF_Nov24'] = "-"; + $employee[$i]['Net_Salary'] = "-"; + $employee[$i]['Diff'] = "-"; + $employee[$i]['work_location'] = $value->work_location; + $employee[$i]['tds_applicable'] = $value->tds_applicable; + $employee[$i]['pf_applicable'] = $value->pf_applicable; + $employee[$i]['esi_applicable'] = $value->esi_applicable; + $i++; + + } + $j = $i; + foreach($driver_monthinputs_info as $record ){ + $hra_worked = $record->hra_worked; + $basic_worked = $record->basic_worked; + $sum_of_amount = ($record->driver_salary+$record->driver_shed+$record->driver_diesel); + + $employee[$j]['SNO'] = $j+1; + $employee[$j]['ID'] = $record->EmpID; + $employee[$j]['Name'] = $record->FirstName; + $employee[$j]['DOJ'] = get_date_time_dynamical_format('Y-m-d H:i:s','d-m-Y',"$record->DateofJoining"); + $employee[$j]['Designation'] = $record->Designation; + $employee[$j]['NoofDays'] = round($record->total_cal_days); + $employee[$j]['Days_worked'] = round($record->unique_days); + $employee[$j]['Leave'] = round($record->total_cal_days - $record->unique_days); + // number_format(0.00, 2, '.', ''); // paid leave + // number_format(0.00, 2, '.', ''); //ot hours + $employee[$j]['TotalSalary'] = number_format($sum_of_amount, 2, '.', ''); + $worked_amt = $sum_of_amount / $record->total_cal_days ; + $employee[$j]['PerDaySalary'] = number_format($worked_amt, 2, '.', ''); + $employee[$j]['WorkedSalary'] = number_format($worked_amt, 2, '.', ''); + $hr_amt = $worked_amt/8; + $employee[$j]['PerHrSalary'] = number_format($hr_amt, 2, '.', ''); + $employee[$j]['EarnedSalary'] = number_format($sum_of_amount, 2, '.', ''); + $employee[$j]['BasicWorked'] = number_format($basic_worked, 2, '.', ''); + $employee[$j]['HraWorked'] = number_format($hra_worked, 2, '.', ''); + $employee[$j]['GrossSalary'] = number_format($basic_worked + $hra_worked, 2, '.', ''); + + $employee[$j]['ESI'] = number_format($record->esi_amount, 2, '.', ''); + $employee[$j]['PF'] = number_format($record->pf_amount, 2, '.', ''); + $employee[$j]['ESI_PF'] = number_format($record->esi_amount + $record->pf_amount, 2, '.', ''); + $employee[$j]['OT'] = number_format(0, 2, '.', ''); + $estTotal = ($basic_worked + $hra_worked + $record->Festival_Bonus)-($record->Monthly_Due+$record->esi_amount+$record->pf_amount); + + $employee[$j]['Feb_25_Advance'] = "-"; + $employee[$j]['TDS_92B'] ="-"; + $employee[$j]['Refuned_PF_Nov24'] ="-"; + $employee[$j]['NetSalary'] = round($estTotal); + + $employee[$j]['GrossSalary2'] = "-"; + $employee[$j]['OT2'] = "-"; + $employee[$j]['GrossNetSalary'] = "-"; + $employee[$j]['ESI2'] ="-"; + $employee[$j]['PF2'] ="-"; + $employee[$j]['Sep_24_Advance'] = "-"; + $employee[$j]['TDS_92B'] = "-"; + $employee[$j]['Refuned_PF_Nov24'] = "-"; + $employee[$j]['Net_Salary'] = "-"; + $employee[$j]['Diff'] = "-"; + $employee[$j]['work_location'] = $record->work_location; + $employee[$j]['tds_applicable'] = $record->tds_applicable; + $employee[$j]['pf_applicable'] = $record->pf_applicable; + $employee[$j]['esi_applicable'] = $record->esi_applicable; + $j++; + } + $finalFooter[] = $employee; + // do not try chatgpt please. + $location_info = []; + foreach ($employee as $key => $value) + { + if (isset($value['work_location']) && $value['work_location'] == "Thiruvenkadu") { + array_push($location_info,$value); + unset($employee[$key]); + } + } + + $tds_info = []; + foreach ($employee as $key => $value) + { + if (isset($value['tds_applicable']) && (int)$value['tds_applicable'] == 1) { + array_push($tds_info,$value); + unset($employee[$key]); + } + } + + $esi_or_pf_info = []; + foreach ($employee as $key => $value) + { + if (isset($value['pf_applicable']) && (int)$value['pf_applicable'] == 1 || isset($value['esi_applicable']) && (int)$value['esi_applicable'] == 1) { + array_push($esi_or_pf_info,$value); + unset($employee[$key]); + } + } + + $keysToRemove = ['work_location','tds_applicable','pf_applicable','esi_applicable']; + foreach ($tds_info as &$t_item) { + foreach ($keysToRemove as $key) { + unset($t_item[$key]); + } + } + unset($t_item); + + foreach ($esi_or_pf_info as &$e_item) { + foreach ($keysToRemove as $key) { + unset($e_item[$key]); + } + } + unset($e_item); + + foreach ($location_info as &$l_item) { + foreach ($keysToRemove as $key) { + unset($l_item[$key]); + } + } + unset($l_item); + + foreach ($employee as &$o_item) { + foreach ($keysToRemove as $key) { + unset($o_item[$key]); + } + } + unset($o_item); + + foreach ($finalFooter as &$topLevelArray) { + if (is_array($topLevelArray)) { + foreach ($topLevelArray as &$employeeArray) { // Changed from $finalFooter to $employeeArray + if (is_array($employeeArray)) { // Check $employeeArray instead of $x + foreach ($keysToRemove as $key) { + if (array_key_exists($key, $employeeArray)) { + unset($employeeArray[$key]); + } + } + } + } + unset($employeeArray); // Break the reference + } + } + unset($topLevelArray); // Break the reference + + $xl[] = array_values($tds_info); + $xl[] = array_values($esi_or_pf_info); + $xl[] = array_values($location_info); + $xl[] = array_values($employee); + + // dd($xl); + + $headlines['company_name'] = isset($company_info[0]->CompanyName) ? $company_info[0]->CompanyName : "Resico India Pvt Ltd"; + $headlines['header1'] = $headlines_main; + $headlines['header2'] = $headlines_sub; + $headlines['type'] = 2; + $headlines['header2'] = $headlines_sub; + $headlines['merge_end_column'] = 7; + $headlines['file_name'] = 'ResicoSalary'.$pmonth.'-'.$pyear.'.xls'; + $headlines['final_Footer'] = $finalFooter; + + generate_excel($headlines,$xl); + + + // dd($employee); + + } + public function driverMonthlyPayInputs($current) { @@ -576,7 +894,7 @@ class Payslip extends BaseController $Estimate_first = explode(".", $Estimate); - if (!is_numeric($Estimate) || (strlen((string)$Estimate)) > 8 || (strlen((string)$Estimate_first[0])) > 6) { + if (!is_numeric($Estimate) || (strlen((string)$Estimate)) > 10 || (strlen((string)$Estimate_first[0])) > 8) { // echo $Estimate_first[0]; // echo $EmpID . "-Estimate Invalid Data!"; $ErrorFlag++; @@ -602,7 +920,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 ; + // $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 ; @@ -659,12 +977,11 @@ class Payslip extends BaseController $Food = isset($load_driver_data[0]->monthly_food_amount) ? (int)$load_driver_data[0]->monthly_food_amount : 0; $Shed = isset($load_driver_data[0]->shed_amount) ? (int)$load_driver_data[0]->shed_amount : 0; $Diesel = isset($load_driver_data[0]->diesel_amount) ? (int)$load_driver_data[0]->diesel_amount : 0; - + $drivermonthlypaydata = array( 'month_year'=>$month, 'driver_id'=>$EmpID, '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, @@ -681,7 +998,6 @@ class Payslip extends BaseController ); - // print_r($drivermonthlypaydata);die; $result = $this->driver_model->saveMonthlyData($drivermonthlypaydata); } @@ -845,7 +1161,6 @@ class Payslip extends BaseController // print_r($is_driver);die; if($is_driver == "1"){ $Data['PayDetails'] = $this->driver_model->GetPayslipdata($Payon, $EmpID); - // print_r($Data['PayDetails']);die; $name = $Data['PayDetails'][0]->driver_name; $filename = 'PayslipFor-' . $EmpID . ' ' . $name . ' ' . $m . ' ' . $y; @@ -878,7 +1193,7 @@ class Payslip extends BaseController } } - +// echo $html;die; $mpdf = new Mpdf([ 'mode' => 'utf-8', @@ -899,7 +1214,7 @@ class Payslip extends BaseController $mpdf->WriteHTML($html); $mpdf->SetTitle('Resico:Payslip'); - $mpdf->Output("Payslip-" . $filename . ".pdf", 'D'); + $mpdf->Output($filename . ".pdf", 'D'); } diff --git a/app/Controllers/Rawmaterialdetails.php b/app/Controllers/Rawmaterialdetails.php index 0d3ebff8..e79e5a68 100755 --- a/app/Controllers/Rawmaterialdetails.php +++ b/app/Controllers/Rawmaterialdetails.php @@ -289,6 +289,7 @@ class Rawmaterialdetails extends BaseController $data['assetcode'] = $this->rawmaterialdetails_model->getAssetcode(); $data['avg_price'] = $this->rawmaterialdetails_model->getMaterialAvg($RawMaterialID); $data['materialRateHistory'] = $this->rawmaterialdetails_model->getMaterialRateHistory($RawMaterialID); + $data['materialListPage'] = $_GET['page']??1; //print_r($data['avg_price']);die(); $this->global['pageTitle'] = 'Edit Material Master'; @@ -317,6 +318,7 @@ class Rawmaterialdetails extends BaseController $stock = $this->request->getPost('openstock'); $reorder = $this->request->getPost('reorder'); $stockdate = $this->request->getPost('Date'); + $materialListPage = $this->request->getPost('materialListPage') ?? 1; $stockdate = (empty($stockdate)) ? NULL : get_date_time_dynamical_format('d-m-Y','Y-m-d',"$stockdate"); $chked = $this->request->getPost('isactive'); @@ -329,11 +331,15 @@ class Rawmaterialdetails extends BaseController $result = $this->rawmaterialdetails_model->editRawmaterial($RawMaterial, $MaterialCode); - if ($result == true) { + if ($result == true) { $this->session->setFlashdata('success', 'RawMaterial Updated successfully!'); + $this->session->setFlashdata('materialListPage', "$materialListPage"); + } else { echo ""; $this->session->setFlashdata('error', 'RawMaterial Record Not updated!'); + $this->session->setFlashdata('materialListPage', "$materialListPage"); + } return redirect()->route('rawmaterialListing'); diff --git a/app/Controllers/Requisitionform.php b/app/Controllers/Requisitionform.php index 287dee63..e6cd0c8d 100755 --- a/app/Controllers/Requisitionform.php +++ b/app/Controllers/Requisitionform.php @@ -130,18 +130,7 @@ class Requisitionform extends BaseController // echo 'ReqType'.$ReqPOType; $data['ReqPOType'] = $ReqPOType == '' ? $ReqType : $ReqPOType; $data['LineItem'] = $this->requistion_model->getEditRequistItemList($ReqNo); - $data['description'] = ''; - foreach ($data['LineItem'] as $key => $line) { - $description = isset($line->MaterialDescription) ? $line->MaterialDescription : null; - - $data['LineItem'][$key]->CategoryName = $line->MaterialCode - ? $this->requistion_model->getCategoryName($line->MaterialCode) - : ""; - } - - - $data['CostCenter'] = $this->requistion_model->getCostCenterUserID($userID); // $data['MaterialCode'] = $this->requistion_model->EditMaterialCode($ReqNo, $ReqType); // Old Based on Type.. $data['MaterialCode'] = $this->requistion_model->EditMaterialCode($ReqNo); @@ -163,7 +152,7 @@ class Requisitionform extends BaseController } $this->requistion_model->DeleteRequistionLineItem($ReqNo, $MaterialCode); - return $this->response->setJSON("Successfully Deleted the Line item" . $ReqNo); + return $this->response->setJSON("Successfully Deleted the Line item " . $ReqNo); } /** @@ -215,49 +204,6 @@ class Requisitionform extends BaseController $this->loadViews("requisitionlistapproval", $this->global, $data, NULL); } - /** - * This function used to load the Employee details based on the EmpID selection - */ - function GetSelectedEmpDetails() - { - $ReqType = $_GET['ReqType']; - $EmpID = $this->request->getPost('id'); - $empDetails = $this->requistion_model->GetEmployeeDetails($EmpID); - $DeptCode = $empDetails[0]['DEPCode']; - $CostList = $this->requistion_model->GetCostCenterByDept($DeptCode); - $HTML = ""; - $BudAmount = ""; - if (count($CostList) > 0) { - for ($j = 0; $j < count($CostList); $j++) { - $Code = $CostList[$j]['CostCenterCode']; - $Name = $CostList[$j]['CostCenterName']; - $HTML .= ""; - } - } - if (count($CostList) == 1) { - - $FYStart = ''; - $FYEnd = ''; - $FiscalYear = $this->costcenter_model->getFiscalYear(); - if (!empty($FiscalYear)) { - foreach ($FiscalYear as $Fy) { - $FYStart = $Fy->StartYear; - $FYEnd = $Fy->EndYear; - } - } - - $FYdt = $FYStart . " - " . $FYEnd; - - - $result = $this->purchaseorder_model->GetAvailableBudgetAmount($CostCode, $FYdt, $ReqType); - //print_r($result); - $AvilBudAmt = '0'; - if (count($result) > 0) { - $BudAmount = $result[0]['BudgetAmount'] - $result[0]['Totalvalue']; - } - } - die(json_encode(array('emp' => $empDetails, 'Cost' => $HTML, 'AvlAmount' => $BudAmount))); - } function getAvailableBudAmount() { @@ -288,6 +234,7 @@ class Requisitionform extends BaseController { $ReqType = $this->request->getPost('id'); + $CatType = $this->request->getPost('cid'); $MaterialCode = $this->requistion_model->GetMaterialCode($ReqType); $MaterialName = ""; @@ -298,7 +245,9 @@ class Requisitionform extends BaseController for ($j = 0; $j < count($MaterialCode); $j++) { $Code = $MaterialCode[$j]['MaterialCode']; $Name = $MaterialCode[$j]['MaterialName']; - $HTML .= ""; + $HSN = $MaterialCode[$j]['HSNCODE'] ? $MaterialCode[$j]['HSNCODE']." - " : ""; + // $HTML .= ""; + $HTML .= ""; } $MaterialName = $MaterialCode[0]['MaterialName']; $UOM = $MaterialCode[0]['UOM']; @@ -319,6 +268,28 @@ class Requisitionform extends BaseController return $this->response->setJSON(['MatDetail' => $MaterialDetails]); } + + function getCategoryDetails() + { + + $CategoryDetails = $this->requistion_model->getmaterialCategory(); + $HTML = ""; + + if (count($CategoryDetails) > 0) { + for ($j = 0; $j < count($CategoryDetails); $j++) { + $Code = $CategoryDetails[$j]['Key']; + $Name = $CategoryDetails[$j]['ConfigValue']; + + $HTML .= ""; + + } + + } + + $response = ['Category' => $HTML]; + return $this->response->setJSON($response); + } + /** * To Insert the Requistion Details to Database */ @@ -399,9 +370,13 @@ class Requisitionform extends BaseController } if ($Status == REQ_DRAFT) { - $display_message = 'Successfully Saved the Requistion details.Requistion No is ' . $ReqNumber; - } else { - $display_message = 'Successfully Created the Requistion details.Requistion No is ' . $ReqNumber; + $display_message = "Successfully Saved the Requisition details in Draft!\nRequistion Number Is: ". $ReqNumber; + // $display_message = "Requistion Saved as Draft!\nRequistion Number Is: ". $ReqNumber; + } else if($Status == REQ_APPROVED) { + $display_message = "Successfully Updated the Requistion details as Approved!\nRequistion Number Is: ". $ReqNumber; + // $display_message = "Requistion Created Successfully!\nRequistion Number Is: ". $ReqNumber; + }else{ + $display_message = "Successfully Created the Requistion details!\nRequistion Number Is: ". $ReqNumber; } return $this->response->setJSON([$display_message]); @@ -468,7 +443,8 @@ class Requisitionform extends BaseController } } } - $display_message = 'Successfully Updated the Requistion details.Requistion No is ' . $ReqNumber; + + $display_message = "Successfully Updated the Requistion details!\nRequistion Number Is: ". $ReqNumber; return $this->response->setJSON([$display_message]); } @@ -601,7 +577,8 @@ class Requisitionform extends BaseController $Request = array('Status' => $Status, 'Comments' => $Remarks, 'ApprovedOn' => $ApprovedDate, 'Approvedby' => $ApprovedBy); $this->requistion_model->UpdateRequistion($Request, $ReqNo); - return $this->response->setJSON(['message' => "Successfully Updated the Requisition No: " . $ReqNo]); + + return $this->response->setJSON(['message' => "Requistion Updated Successfully!\nRequistion Number Is: ".$ReqNo]); } } diff --git a/app/Controllers/StockController.php b/app/Controllers/StockController.php index 8d423624..01ac48e5 100644 --- a/app/Controllers/StockController.php +++ b/app/Controllers/StockController.php @@ -28,6 +28,10 @@ use App\Models\MonthWiseMachinesInStockModel; use App\Models\TrpAbstractModel; +helper('stock'); + + + @@ -145,10 +149,11 @@ class StockController extends BaseController } //incoming Silica Sand Details starts + // refactored public function loadView_incomingSilicaSandDetails() { - //one remark is for comments and another remark here is alais status of the sand report , due to client request naming is given wrong , + //here - one remark is for comments and another remark here is alais status of the sand report , due to client request naming is given wrong , //hope you bear it..!! //we did ..!! @@ -170,7 +175,7 @@ class StockController extends BaseController $month = $formattedDate; //setting session for any month change - $session = session (); + $session = session(); $session->set('stock_month',$month); @@ -239,6 +244,8 @@ class StockController extends BaseController } + //insert or update incoming silica sand details + //refactored public function updateIncomingSilicaSandDetails() { @@ -256,45 +263,48 @@ class StockController extends BaseController ->findAll(); $existingIds = array_column($existingRecords, 'id'); + $inserts = []; $updates = []; foreach ($incomingSilicaSandDetailsData as $data) { - $id = !empty($data['id']) ? $data['id'] : null; + + //check for id and assign null if not present + $id = empty($data['id']) ? null : $data['id'] ; $dbData = [ - 'igrNo_fk' => $data['igrNo'], - 'gradeCondition' => $data['gradeCondition'], - '_10' => $data['_10'], - '_20' => $data['_20'], - '_30' => $data['_30'], - '_40' => $data['_40'], - '_50' => $data['_50'], - '_70' => $data['_70'], - '_100' => $data['_100'], - '_140' => $data['_140'], - '_200' => $data['_200'], - '_300' => $data['_300'], - 'pan' => $data['pan'], - 'total' => $data['total'], - 'afsSpec' => $data['afsSpec'], - 'afsActual' => $data['afsActual'], - 'plus20loss' => $data['plus20loss'], - 'plus30Loss' => $data['plus30Loss'], - 'moistureSpec' => $data['moistureSpec'], - 'moistureActual' => $data['moistureActual'], - 'moistureLoss' => $data['moistureLoss'], - 'moistureLossQty' => $data['moistureLossQty'], - 'sieveLossQty' => $data['sieveLossQty'], - 'salableQty' => $data['salableQty'], - 'remark' => $data['remark'], - 'materialCode' => $data['materialCode'], - 'clayOrLossOfIgnition' => $data['clayOrLossOfIgnition'], - 'testedBy' => $data['testedBy'], - 'approvedBy' => $data['approvedBy'], - 'reportComments' => $data['reportComments'], - 'gradeRange' => $data['gradeRange'], - 'reportTime' => $data['reportTime'], + 'igrNo_fk' => $data['igrNo'], + 'gradeCondition' => $data['gradeCondition'], + '_10' => $data['_10'], + '_20' => $data['_20'], + '_30' => $data['_30'], + '_40' => $data['_40'], + '_50' => $data['_50'], + '_70' => $data['_70'], + '_100' => $data['_100'], + '_140' => $data['_140'], + '_200' => $data['_200'], + '_300' => $data['_300'], + 'pan' => $data['pan'], + 'total' => $data['total'], + 'afsSpec' => $data['afsSpec'], + 'afsActual' => $data['afsActual'], + 'plus20loss' => $data['plus20loss'], + 'plus30Loss' => $data['plus30Loss'], + 'moistureSpec' => $data['moistureSpec'], + 'moistureActual' => $data['moistureActual'], + 'moistureLoss' => $data['moistureLoss'], + 'moistureLossQty' => $data['moistureLossQty'], + 'sieveLossQty' => $data['sieveLossQty'], + 'salableQty' => $data['salableQty'], + 'remark' => $data['remark'], + 'materialCode' => $data['materialCode'], + 'clayOrLossOfIgnition' => $data['clayOrLossOfIgnition'], + 'testedBy' => $data['testedBy'], + 'approvedBy' => $data['approvedBy'], + 'reportComments' => $data['reportComments'], + 'gradeRange' => $data['gradeRange'], + 'reportTime' => $data['reportTime'], ]; if ($id && in_array($id, $existingIds)) { @@ -318,6 +328,7 @@ class StockController extends BaseController //This is particulary updated by the lab technichians + //refactored public function updateLabReport() { @@ -326,35 +337,35 @@ class StockController extends BaseController $id = $postData['id']; $dbData = [ - 'igrNo_fk' => $postData['igrNo'], - 'materialCode' => $postData['materialCode'], - '_10' => $postData['_10Mm'], - '_20' => $postData['_20Mm'], - '_30' => $postData['_30Mm'], - '_40' => $postData['_40Mm'], - '_50' => $postData['_50Mm'], - '_70' => $postData['_70Mm'], - '_100' => $postData['_100Mm'], - '_140' => $postData['_140Mm'], - '_200' => $postData['_200Mm'], - '_300' => $postData['_300Mm'], - 'pan' => $postData['pan'], - 'total' => $postData['total'], - 'plus20Loss' => $postData['plus20Loss'], - 'plus30Loss' => $postData['plus30Loss'], - 'moistureSpec' => $postData['moistureSpec'], - 'moistureActual' => $postData['moistureActual'], - 'moistureLoss' => $postData['moistureLoss'], - 'moistureLossQty' => $postData['moistureLossQty'], - 'sieveLossQty' => $postData['sieveLossQty'], - 'salableQty' => $postData['salableQty'], - 'testedBy' => $postData['testedBy'], - 'approvedBy' => $postData['approvedBy'], + 'igrNo_fk' => $postData['igrNo'], + 'materialCode' => $postData['materialCode'], + '_10' => $postData['_10Mm'], + '_20' => $postData['_20Mm'], + '_30' => $postData['_30Mm'], + '_40' => $postData['_40Mm'], + '_50' => $postData['_50Mm'], + '_70' => $postData['_70Mm'], + '_100' => $postData['_100Mm'], + '_140' => $postData['_140Mm'], + '_200' => $postData['_200Mm'], + '_300' => $postData['_300Mm'], + 'pan' => $postData['pan'], + 'total' => $postData['total'], + 'plus20Loss' => $postData['plus20Loss'], + 'plus30Loss' => $postData['plus30Loss'], + 'moistureSpec' => $postData['moistureSpec'], + 'moistureActual' => $postData['moistureActual'], + 'moistureLoss' => $postData['moistureLoss'], + 'moistureLossQty' => $postData['moistureLossQty'], + 'sieveLossQty' => $postData['sieveLossQty'], + 'salableQty' => $postData['salableQty'], + 'testedBy' => $postData['testedBy'], + 'approvedBy' => $postData['approvedBy'], 'clayOrLossOfIgnition' => $postData['clayOrLossOfIgnition'], - 'reportComments' => $postData['reportComments'], - 'gradeRange' => $postData['gradeRange'], - 'reportTime' => $postData['reportTime'], - 'remark' => $postData['remark'] + 'reportComments' => $postData['reportComments'], + 'gradeRange' => $postData['gradeRange'], + 'reportTime' => $postData['reportTime'], + 'remark' => $postData['remark'] ]; @@ -380,8 +391,10 @@ class StockController extends BaseController } //Drier machine details + //refactored public function drierMachineDetails() { + // Drier machine details follow a different method of processing stock month and date format than other stock records. // The stock month and date format must be handled carefully while generating and updating data. @@ -447,15 +460,15 @@ class StockController extends BaseController $this->global['pageTitle'] = 'Drier Details'; $this->loadViews("stock/drierMachineDetails", $this->global, $data, NULL); + } - + //add or edit drier machine Details + //refactored public function addOrEditdrierMachineDetails() { - // Retrieve form data from the POST request $data = $this->request->getPost(); - // Map the received data into a structured format using the helper function `mapDrierEntry` $drierData[] = $this->mapDrierEntry($data); // Begin a database transaction to ensure atomicity @@ -465,7 +478,6 @@ class StockController extends BaseController // Arrays to store data for batch insert and batch update operations $inserts = []; $updates = []; - foreach ($drierData as $row) { // Retrieve the ID of the existing entry (if present) @@ -473,20 +485,18 @@ class StockController extends BaseController $data = $row; if ($existingRow) { - + $existingRow = $this->drierMachineDetails_model->where('id', $row['id'] ?? '')->first(); // Handle gas stock updates for the existing record $this->handleGasStockUpdate($existingRow, $row); - - $updates[] = $data; + $updates[] = $data ; } else { // If it's a new record, update gas stock consumption before inserting $this->updateGasStockConsumption($data['date'], $data['total_gas_consumption']); - - - $inserts[] = $data; + + $inserts[] = $data ; } } @@ -519,10 +529,10 @@ class StockController extends BaseController } } - /** * Maps input row to expected format. */ + // refactored private function mapDrierEntry(array $data): array { return [ @@ -544,35 +554,11 @@ class StockController extends BaseController ]; } - - //Coating Machine Details starts + //refactored public function loadView_coatingMachineDetails() { - if ($this->request->getMethod() === 'POST') { - // Get the month from the request - $month = $this->request->getPost('month'); - - // Convert month format from "M-Y" to "Y-m" - $date = DateTime::createFromFormat('d-M-Y', '01-'.$month); - - $formattedDate = $date->format('Y-m'); - - $month = $formattedDate; - - // Store selected month in session - $session = session(); - $session->set('stock_month', $month); - - } else { - $session = session(); - $month = $session->get('stock_month'); - - // Default to the current month if no month is stored in session - if (empty($month)) { - $month = date('Y-m'); - } - } + $month = getStockMonth($this->request); $data['month'] = $month; $this->global['pageTitle'] = 'Coating Machine Details'; @@ -582,26 +568,12 @@ class StockController extends BaseController $endDate = date("Y-m-t", strtotime($startDate)); // Fetch coating machine details with batch card file details - $data['coatingMachineDetails'] = $this->coatingMachineDetails_model - ->select('t_coatingmachinedetails.*, - JSON_ARRAYAGG( - JSON_OBJECT( - "client_given_name", t_batchcard_files.client_file_name, - "filename", t_batchcard_files.filename, - "batchCardId" , t_batchcard_files.id, - "coating_id", t_batchcard_files.coating_id - ) - ) as batchcard_files') - ->join('t_batchcard_files', 't_batchcard_files.coating_id = t_coatingmachinedetails.id', 'left') - ->where('t_coatingmachinedetails.date >=', $startDate) - ->where('t_coatingmachinedetails.date <=', $endDate) - ->groupBy('t_coatingmachinedetails.id') - ->orderBy('t_coatingmachinedetails.date', 'asc') - ->findAll(); + $data['coatingMachineDetails'] = $this->coatingMachineDetails_model->coatingMachineDetails($startDate,$endDate); + // Convert month format from "Y-m" to "M-Y" for display $date = DateTime::createFromFormat('Y-m-d', $month.'-01'); - + $formattedDate = $date->format('M-Y'); $data['month'] = $formattedDate; @@ -611,270 +583,115 @@ class StockController extends BaseController } + //add new coating machine details + // refactored public function addNewCoatingMachineDetails() { - $message1 = ''; - $message2 = ''; - $message3 = ''; - $postData = $this->request->getPost(); $date = $postData['date']; $shift = $postData['shift']; - - // Check if the same shift already exists on the same date - $sameShiftOnDateExists = $this->coatingMachineDetails_model - ->where('date', $date) - ->where('shift', $shift) - ->where('is_active', 1) - ->first(); - - if (!empty($sameShiftOnDateExists)) { + + $multipleShift = $this->coatingMachineDetails_model->isShiftExists($date, $shift); + + if (!empty($multipleShift)) { return redirect()->back()->with('error', 'Already same shift exists on the same date ..!!'); } - - // Start transaction + $this->db->transBegin(); - + try { - // Insert data into coating machine details table $insertedId = $this->coatingMachineDetails_model->insert($postData); - - if ($insertedId !== false && $insertedId > 0) { - $message1 = 'Coating Machine details updated successfully'; - - // Update gas stock consumption - $dateToBeInserted = $postData['date']; - $consumption = $postData['totalGasConsumption']; - $updatedResult = $this->updateGasStockConsumption($dateToBeInserted, $consumption); - - if ($updatedResult === false || $updatedResult <= 0) { - throw new \Exception('Failed to update gas stock consumption.'); - } - - $message2 = 'And updated gas stock consumption.'; - $message3 = " Warning..!! Kindly Update the next subsequent month Gas Stock If older month Gas Stock Updated..!!"; - } else { - throw new \Exception('Failed to insert Coating machine details.'); - } - - // Handle batch card file uploads - if ($insertedId !== false && $insertedId > 0) { - $batchCardFiles = $this->request->getFileMultiple('batchCard'); - - if (!empty($batchCardFiles) && !($batchCardFiles[0]->getError() === UPLOAD_ERR_NO_FILE)) { - foreach ($batchCardFiles as $file) { - if ($file->isValid() && !$file->hasMoved()) { - $clientGivenName = $file->getClientName(); // Original filename - $newName = $file->getRandomName(); - $path = WRITEPATH . 'uploads' . DIRECTORY_SEPARATOR . 'batchcard'; - - if (!is_dir($path)) { - mkdir($path, 0777, true); - } - - if ($file->move($path, $newName)) { - // Insert file details into the database - $db = \Config\Database::connect(); - $builder = $db->table('t_batchcard_files'); - - $data = [ - 'client_file_name' => $clientGivenName, - 'filename' => $newName, - 'coating_id' => $insertedId - ]; - - $builder->insert($data); - } - } - } - } + if (!$insertedId) { + throw new \Exception('Failed to insert Coating Machine Details.'); } - + + $this->updateGasConsumptionOrFail($postData['date'], $postData['totalGasConsumption']); + + $this->handleBatchCardUploads($insertedId); + if ($this->db->transStatus() === false) { throw new \Exception('Transaction failed due to database errors.'); } - + $this->db->transCommit(); - - // Redirect with success message - return redirect()->to("/coatingMachineDetails") - ->with('success', $message1 . " " . $message2 . " " . $message3); + + $successMessage = 'Coating Machine details updated successfully. ' . 'And updated gas stock consumption. '. 'Warning..!! Kindly Update the next subsequent month Gas Stock If older month Gas Stock Updated..!!'; + + return redirect()->to("/coatingMachineDetails")->with('success', $successMessage); + } catch (\Exception $error) { $this->db->transRollback(); - return redirect()->back()->with('error', ' ' . $error->getMessage()); + return redirect()->back()->with('error', $error->getMessage()); } } - - + //update coating machine details + // refactored public function updateCoatingMachineDetails() { - - - $message1 = ''; - $message2 = ''; - $message3 = ''; - $putData = $this->request->getPost(); - - $id = $putData['editCoatingMachineDetailId']; - // Start transaction $this->db->transBegin(); + try { $updated = $this->coatingMachineDetails_model->update($id, $putData); - - - - if ($updated !== false && $updated > 0) { // Assuming $id is the record ID being updated - - $batchCardFiles = $this->request->getFileMultiple('batchCard'); - - if (is_array($batchCardFiles) && !empty($batchCardFiles)) { - // Step 4: Upload new files and insert into DB - foreach ($batchCardFiles as $index => $file) { - - if ( !empty($batchCardFiles[$index]) && !($batchCardFiles[$index]->getError() === UPLOAD_ERR_NO_FILE)) { - - $db = \Config\Database::connect(); - $builder = $db->table('t_batchcard_files'); - - if ($file->isValid() && !$file->hasMoved()) { - $clientGivenName = $file->getClientName(); // User-given filename - $newName = $file->getRandomName(); // Randomized unique filename - - $path = WRITEPATH . 'uploads' . DIRECTORY_SEPARATOR . 'batchcard'; - - if (!is_dir($path)) { - mkdir($path, 0777, true); - } - - if ($file->move($path, $newName)) { - // Insert new file record into the database - $data = [ - 'client_file_name' => $clientGivenName, - 'filename' => $newName, - 'coating_id' => $id - ]; - $builder->insert($data); - } - } - } - } - } - - - - } - - if ($updated !== false && $updated > 0) { - $message1 = "successfully updated Coating machineDetail ."; - //update Gas stock consumption if update is successfull..!! - $dateToBeUpdated = $putData['date']; - - $existingCoatingGasConsumption = $putData['existingTotalGasConsumption']; - $updatedCoatingGasConsumption = $putData['totalGasConsumption']; - - if ($existingCoatingGasConsumption != $updatedCoatingGasConsumption) { - - $changeInConsumption = $updatedCoatingGasConsumption - $existingCoatingGasConsumption; - $updatedResult = $this->updateGasStockConsumption($dateToBeUpdated, $changeInConsumption); - - if ($updatedResult === false || $updatedResult <= 0) { - // Explicit failure handling for gas stock update - throw new \Exception('Failed to update gas stock consumption.'); - } - $message2 = 'And updated gas stock consumption.'; - - $message3 = "Warning..!! Kindly Update the next subsequent month Gas Stock If older month Gas Stock Updated..!!"; - } - // Commit the transaction if all queries succeed - - - if ($this->db->transStatus() === false) { - throw new \Exception('Transaction failed due to database errors.'); - } - $this->db->transCommit(); - - - - - // Set flashdata for success message - return redirect()->to("/coatingMachineDetails") - ->with('success', $message1 . " " . $message2 . " " . $message3); - } else { + if (!$updated) { throw new \Exception('Failed to update Coating machine details.'); } - - - + $this->handleBatchCardUploads($id); + + $messages = ['successfully updated Coating machineDetail.']; + + $this->handleGasConsumptionAdjustment($putData, $messages); + + if ($this->db->transStatus() === false) { + throw new \Exception('Transaction failed due to database errors.'); + } + + $this->db->transCommit(); + + return redirect()->to("/coatingMachineDetails") + ->with('success', implode(" ", $messages)); } catch (\Exception $error) { $this->db->transRollback(); - return redirect()->back()->with('error', ' ' . $error->getMessage()); + return redirect()->back()->with('error', $error->getMessage()); } } + //deleteBatchCardFile + // refactored public function deleteBatchCardFile() { $data = $this->request->getPost(); - - if (!empty($data)) { - - $batchId = $data['id']; - $db = \Config\Database::connect(); - $builder = $db->table('t_batchcard_files'); - - // Step 1: Fetch the filename from DB before deleting - $fileRecord = $builder->select('filename')->where('id', $batchId)->get()->getRow(); - - if ($fileRecord) { - $path = WRITEPATH . 'uploads' . DIRECTORY_SEPARATOR . 'batchcard'; - - if (!is_dir($path)) { - mkdir($path, 0777, true); - } - $filePath = $path . DIRECTORY_SEPARATOR . $fileRecord->filename; - - // Step 2: Delete the file from storage - if (file_exists($filePath)) { - unlink($filePath); - } - - // Step 3: Delete the record from the database - $sql = "DELETE FROM t_batchcard_files WHERE id = ?"; - $deleted = $db->query($sql, [$batchId]); - - if ($deleted) { - return $this->response->setJSON([ - 'status' => '200', - 'message' => "Deleted Batch Card File Successfully..!!" - ]); - } else { - return $this->response->setJSON([ - 'status' => '400', - 'message' => "Failed to Delete..!! Try Again Later" - ]); - } - } else { - return $this->response->setJSON([ - 'status' => '404', - 'message' => "File Not Found..!!" - ]); - } + if (empty($data)) { + return $this->respondWithJson(400, "Invalid Request..!!"); } - return $this->response->setJSON([ - 'status' => '400', - 'message' => "Invalid Request..!!" - ]); + $batchId = $data['id']; + + $fileRecord = $this->getBatchCardFileRecord($batchId); + if (!$fileRecord) { + return $this->respondWithJson(404, "File Not Found..!!"); + } + + $fileDeleted = $this->deleteBatchCardFileFromStorage($fileRecord->filename); + + $recordDeleted = $this->deleteBatchCardFileRecord($batchId); + + if ($recordDeleted) { + return $this->respondWithJson(200, "Deleted Batch Card File Successfully..!!"); + } + + return $this->respondWithJson(400, "Failed to Delete..!! Try Again Later"); } - - + + //downloadBatchCardZip + // refactored public function downloadBatchcardZip() { @@ -905,6 +722,7 @@ class StockController extends BaseController $zip = new \ZipArchive(); + if ($zip->open($zipFilePath, \ZipArchive::CREATE | \ZipArchive::OVERWRITE) === true) { foreach ($batchCardFiles as $file) { @@ -912,11 +730,9 @@ class StockController extends BaseController $originalFilePath = $zipPath . DIRECTORY_SEPARATOR . $file['filename']; // Actual stored file $clientFileName = $file['client_file_name'] ?? $file['filename']; // Use client name if available - + if (file_exists($originalFilePath)) { - $zip->addFile($originalFilePath, $clientFileName); // Rename inside ZIP - } } $zip->close(); @@ -935,594 +751,630 @@ class StockController extends BaseController return redirect()->back()->with('error', 'Failed to create ZIP file.'); } - - // Example function to get batchcard files from DB - private function getBatchCardFiles($coatingId) - { - $batchCardFiles = $this->db->table('t_batchcard_files') - ->where('coating_id', $coatingId) - ->get() - ->getResultArray(); - - return $batchCardFiles; - } - - - - //Gas Stock Details - public function loadView_gasStockDetails() - { - - if ($this->request->getMethod() === 'POST') { - - $month = $this->request->getPost('month'); - - $date = DateTime::createFromFormat('d-M-Y', '01-'.$month); - - $formattedDate = $date->format('Y-m'); - - $month = $formattedDate; - - $session = session (); - - $session->set('stock_month',$month); - - } else { - $session = session(); - - $month = $session->get('stock_month'); - - if (empty($month)) { - $month = date('Y-m'); // Default to the current month - } - } - - $data = []; - - $data['month'] = $month; - - $this->global['pageTitle'] = "Gas Stock Details"; - - - $previousMonth = DateTime::createFromFormat('Y-m-d', $month.'-01')->modify('-1 month')->format('Y-m'); - $previousMonthStartDate = "$previousMonth-01"; - $previousMonthEndDate = date("Y-m-t", strtotime($previousMonthStartDate)); - $data['previousMonthGasStockDetails'] = $this->gasStockDetails_model - ->select('date,balanceStock') - ->where('date =', $previousMonthEndDate) - ->orderBy('date', 'desc') - ->findAll(); - - $startDate = "$month-01"; - $endDate = date("Y-m-t", strtotime($startDate)); - - $data['gasStockDetails'] = $this->gasStockDetails_model - ->select( - 't_gasstockdetails.*, - drier_summary.drierMachineGasconsumption AS drierMachineGasConsumption, - drier_summary.driedSand AS sandDried, - coating_summary.coatingMachineGasconsumption, - coating_summary.coatedSand' - ) - // Subquery with early date filtering - ->join( - '(SELECT date, - SUM(totalGasconsumption) AS coatingMachineGasconsumption, - SUM(totalCoatingSandInKg) / 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(); - - - - $date = DateTime::createFromFormat('Y-m-d', $month.'-01'); - - $formattedDate = $date->format('M-Y'); - $data['month'] = $formattedDate; - return $this->loadViews("stock/gasStockDetails", $this->global, $data, NULL); - } + //Gas Stock Details + // refactored + public function loadView_gasStockDetails() + { + $month = getStockMonth($this->request); + + $data = []; + $data['month'] = $month; + $this->global['pageTitle'] = "Gas Stock Details"; + + $previousMonthDates = $this->getPreviousMonthDateRange($month); + + $data['previousMonthGasStockDetails'] = $this->gasStockDetails_model + ->select('date, balanceStock') + ->where('date', $previousMonthDates['end']) + ->orderBy('date', 'desc') + ->findAll(); + - public function updateGasStockDetails() - { + $startDate = "$month-01"; + $endDate = date("Y-m-t", strtotime($startDate)); + - $postData = $this->request->getPost(); + $data['gasStockDetails'] = $this->gasStockDetails_model->gasStockDetails($startDate, $endDate); + + // Format month for view display (e.g., Apr-2025) + $formattedDate = DateTime::createFromFormat('Y-m-d', $startDate)->format('M-Y'); + $data['month'] = $formattedDate; + + return $this->loadViews("stock/gasStockDetails", $this->global, $data, NULL); + } + - $updateGasStockDetailsData = json_decode($postData['updateGasStockDetails'], true); + // updateGasStockDetails + // refactored + public function updateGasStockDetails() + { - $updates = []; + $postData = $this->request->getPost(); - $inserts = []; + $updateGasStockDetailsData = json_decode($postData['updateGasStockDetails'], true); - foreach ($updateGasStockDetailsData as $data) { + $updates = []; - $date = $data['date']; + $inserts = []; + foreach ($updateGasStockDetailsData as $data) { - $dbData = [ - 'date' => $data['date'] , - 'opening' => $data['opening'] , - 'purchaseBharath' => $data['purchaseBharath'] , - 'purchaseIndian' => $data['purchaseIndian'] , - 'total' => $data['total'] , - 'consumption' => $data['consumption'] , - 'balanceStock' => $data['balanceStock'] , - 'trp_panel_gas_consumption' => $data['trpPanelGasConsumption'] , - 'trp_physical_gas_consumption' => $data['trpPhysicalGasConsumption'] , - 'trp_sand_production' => $data['trpSandProduction'] , - 'rotary_drier_consumption' => $data['rotaryDrierConsumption'] - ]; + $date = $data['date']; - $resultExists = $this->gasStockDetails_model - ->where('date', $date) - ->first(); + $dbData = [ + 'date' => $data['date'] , + 'opening' => $data['opening'] , + 'purchaseBharath' => $data['purchaseBharath'] , + 'purchaseIndian' => $data['purchaseIndian'] , + 'total' => $data['total'] , + 'consumption' => $data['consumption'] , + 'balanceStock' => $data['balanceStock'] , + 'trp_panel_gas_consumption' => $data['trpPanelGasConsumption'] , + 'trp_physical_gas_consumption' => $data['trpPhysicalGasConsumption'] , + 'trp_sand_production' => $data['trpSandProduction'] , + 'rotary_drier_consumption' => $data['rotaryDrierConsumption'] + ]; - - if (empty($resultExists)) { - $inserts[] = $dbData; - } else { - $dbData['id'] = $resultExists['id']; - $updates[] = $dbData; - } - - } - - - if (!empty($inserts)) { - $this->gasStockDetails_model->insertBatch($inserts); - } - - if (!empty($updates)) { - - $updateResult = $this->gasStockDetails_model->updateBatch($updates, 'id'); - - if ($updateResult === FALSE) { - echo "Error during update"; - } else { - echo "Data Updated Successfully"; - return; - } - } - - echo "Data Saved Successfully Warning..!! Kindly Update the next subsequent month Gas Stock If older month Gas Stock Updated..!!"; - } - - private function updateGasStockConsumption($date, $consumption) - { - // Check if an entry exists for the given date $resultExists = $this->gasStockDetails_model ->where('date', $date) ->first(); - - if ($resultExists) { - // Ensure the date is in the correct format - if ($date instanceof DateTime) { - $date = $date->format('Y-m-d'); - } elseif (!strtotime($date)) { - throw new \Exception("Invalid date format provided."); - } else { - $date = date('Y-m-d', strtotime($date)); - } - - // Get the last date of the month for the given date - $endDate = date('Y-m-t', strtotime($date)); - - // Fetch all stock entries from the given date till the end of the month - $resultExists = $this->gasStockDetails_model - ->where('date >=', $date) - ->where('date <=', $endDate) - ->orderBy('date', 'asc') - ->findAll(); - - $updatedOpeningStock = 0; - $updates = []; - - // Update stock values for each day in the month - foreach ($resultExists as $index => $result) { - if ($index == 0) { - // Update the first entry with new consumption - $result['consumption'] = (float)($result['consumption']) + (float)($consumption); - $result['total'] = (float)$result['opening'] + (float)$result['purchaseBharath'] + (float)$result['purchaseIndian']; - - $result['balanceStock'] = $result['total'] - $result['consumption']; - - $updatedOpeningStock = (int)$result['balanceStock']; - } else { - // Update subsequent entries based on previous balance - - $result['opening'] = (float)$updatedOpeningStock; - - $result['total'] = (float)$result['opening'] + (float)$result['purchaseBharath'] + (float)$result['purchaseIndian']; - - $result['balanceStock'] = (float)$result['total'] - (float)$result['consumption']; - - $updatedOpeningStock = (int)$result['balanceStock']; - } - - $updates[] = $result; - } - - // Perform batch update if there are changes - if (!empty($updates)) { - $result = $this->gasStockDetails_model->updateBatch($updates, 'id'); - return ($result !== false && $result > 0) ? $result : 0; - } else { - return 0; - } - - + if (empty($resultExists)) { + $inserts[] = $dbData; } else { - // Get the last date of the previous month - $previousMonthDate = new DateTime($date); - $previousMonthDate = $previousMonthDate->modify('first day of this month') - ->modify('-1 day') - ->format('Y-m-d'); - - // Check if the previous month's last day entry exists - $previousMonthResultExists = $this->gasStockDetails_model - ->where('date', $previousMonthDate) - ->first(); - - $opening = 0; - - // Set opening stock based on previous month's balance stock - if (!empty($previousMonthResultExists) && isset($previousMonthResultExists['balanceStock'])) { - $opening = $previousMonthResultExists['balanceStock']; - } - - // Generate a list of all dates in the current month - $startDate = DateTime::createFromFormat('Y-m-d', $date)->modify('first day of this month')->format('Y-m-d'); - $endDate = DateTime::createFromFormat('Y-m-d', $date)->modify('last day of this month')->format('Y-m-d'); - - $datesInMonth = []; - $inserts = []; - - $period = new DatePeriod( - new DateTime($startDate), - new DateInterval('P1D'), - (new DateTime($endDate))->modify('+1 day') - ); - - foreach ($period as $day) { - $datesInMonth[] = $day->format('Y-m-d'); - } - - // Insert stock records for each day in the month - foreach ($datesInMonth as $dateInMonth) { - $balanceStock = $opening; - $consumptionForDate = 0; - - if ($dateInMonth == $date) { - // Assign the given consumption for the provided date - $consumptionForDate = $consumption; - $balanceStock = $opening - $consumption; - } - - $inserts[] = [ - 'date' => $dateInMonth, - 'opening' => $opening, - 'purchaseBharath' => null, - 'purchaseIndian' => null, - 'total' => null, - 'consumption' => $consumptionForDate, - 'balanceStock' => $balanceStock - ]; - - // Update opening for the next day - $opening = $balanceStock; - } - - // Perform batch insert if data is available - if (!empty($inserts)) { - $result = $this->gasStockDetails_model->insertBatch($inserts); - return ($result !== false && $result > 0) ? $result : 0; - } else { - return 0; - } + $dbData['id'] = $resultExists['id']; + $updates[] = $dbData; + } + + } + + + if (!empty($inserts)) { + $this->gasStockDetails_model->insertBatch($inserts); + } + + if (!empty($updates)) { + + $updateResult = $this->gasStockDetails_model->updateBatch($updates, 'id'); + + if ($updateResult === FALSE) { + echo "Error during update"; + } else { + echo "Data Updated Successfully"; + return; } } - + echo "Data Saved Successfully Warning..!! Kindly Update the next subsequent month Gas Stock If older month Gas Stock Updated..!!"; + } + //updateGasStockConsumption + // refactored + private function updateGasStockConsumption($date, $consumption) + { + $date = $this->convertToDateWithFlexibleFormats($date,["d-m-Y", "Y-m-d", "m/d/Y", "m-d-Y"],"Y-m-d"); - //diesel stock details + $resultExists = $this->gasStockDetails_model->where('date', $date)->first(); - public function dieselMachineStockDetails(){ + if ($resultExists) { - - if ($this->request->getMethod() === 'POST') { + $endDate = date('Y-m-t', strtotime($date)); - $month = $this->request->getPost('month'); + $records = $this->gasStockDetails_model->where('date >=', $date) + ->where('date <=', $endDate) + ->orderBy('date', 'asc') + ->findAll(); - $date = DateTime::createFromFormat('d-M-Y', '01-'.$month); + $updatedOpeningStock = 0; - $formattedDate = $date->format('Y-m'); - - $month = $formattedDate; - - $session = session (); - - $session->set('stock_month',$month); - - } else { - - $session = session(); - - $month = $session->get('stock_month'); - - if (empty($month)) { - $month = date('Y-m'); // Default to the current month + foreach ($records as $i => &$r) { + if ($i == 0) { + $r['consumption'] += (float)$consumption; + $r['total'] = (float)$r['opening'] + (float)$r['purchaseBharath'] + (float)$r['purchaseIndian']; + $r['balanceStock'] = $r['total'] - $r['consumption']; + $updatedOpeningStock = (int)$r['balanceStock']; + } else { + $r['opening'] = (float)$updatedOpeningStock; + $r['total'] = (float)$r['opening'] + (float)$r['purchaseBharath'] + (float)$r['purchaseIndian']; + $r['balanceStock'] = $r['total'] - $r['consumption']; + $updatedOpeningStock = (int)$r['balanceStock']; } } + //elvis operator + return $this->gasStockDetails_model->updateBatch($records, 'id') ?: 0; + } - $data = []; + $prevDate = (new DateTime($date))->modify('first day of this month')->modify('-1 day')->format('Y-m-d'); + $prev = $this->gasStockDetails_model->where('date', $prevDate)->first(); + $opening = (!empty($prev) && isset($prev['balanceStock'])) ? $prev['balanceStock'] : 0; - $data['month'] = $month; + $start = (new DateTime($date))->modify('first day of this month'); + $end = (new DateTime($date))->modify('last day of this month'); + $period = new DatePeriod($start, new DateInterval('P1D'), $end->modify('+1 day')); - $this->global['pageTitle'] = 'Diesel Machine Stock Details'; + $inserts = []; + foreach ($period as $d) { + $dStr = $d->format('Y-m-d'); + $cons = ($dStr == $date) ? $consumption : 0; + $balance = ($dStr == $date) ? $opening - $consumption : $opening; + + $inserts[] = [ + 'date' => $dStr, + 'opening' => $opening, + 'purchaseBharath' => null, + 'purchaseIndian' => null, + 'total' => null, + 'consumption' => $cons, + 'balanceStock' => $balance + ]; + $opening = $balance; + } + //elvis operator + return $this->gasStockDetails_model->insertBatch($inserts) ?: 0; + } + + //diesel stock details + //refactored + public function dieselMachineStockDetails() + { + $month = getStockMonth($this->request); + + $startDate = "$month-01"; + $endDate = date("Y-m-t", strtotime($startDate)); + $currentDate = new DateTime(); + $data = [ + 'month' => $month, + 'activeDieselMachines' => $this->factoryMachine_model->getAllActiveDieselMachines(), + ]; + $this->global['pageTitle'] = 'Diesel Machine Stock Details'; + + + $customisedMachineCodes = $this->getOrUpdateCustomisedMachineCodes($month); + + + if ($this->isCurrentMonth($startDate, $endDate, $currentDate)) { + $this->ensureDieselDetailsForMonth($customisedMachineCodes, $startDate, $endDate); + } + + + $dieselMachines = $this->factoryMachine_model->getSelectedDieselMachines($customisedMachineCodes); + $dieselMachinesCount = count($dieselMachines); + + + [$prevDetails, $prevTotals] = $this->getPreviousMonthStockDetails($month); + $data['previousMonthDieselMachineStockDetails'] = $prevDetails; + $data['previousMonthTotalDieselMachineStockDetails'] = $prevTotals; + + + $data['dieselMachineStockDetails'] = $this->factoryVehicleDieselDetails_model + ->where('date >=', $startDate) + ->where('date <=', $endDate) + ->whereIn('machine_id', $customisedMachineCodes) + ->groupBy(['machine_id', 'date']) + ->orderBy('date', 'asc') + ->orderBy('machine_id', 'asc') + ->findAll(); + + + $data['totalDiesel'] = $this->factoryVehicleDieselStockSummary_model + ->where('date >=', $startDate) + ->where('date <=', $endDate) + ->orderBy('date', 'asc') + ->findAll(); + + + $data['groupedDieselMachineStockDetails'] = $this->groupAndSortStockDetails( + $data['dieselMachineStockDetails'], + $customisedMachineCodes + ); + - //filter part starts - - //start date dynamic from front-end - $startDate = "$month-01"; - //end date of given month - $endDate = date("Y-m-t", strtotime($startDate)); + if (!empty($customisedMachineCodes)) { + $dieselMachines = $this->sortMachinesByCustomOrder($dieselMachines, $customisedMachineCodes); + } + + $data['dieselMachinesCount'] = $dieselMachinesCount; + $data['dieselMachines'] = $dieselMachines; + $data['month'] = DateTime::createFromFormat('Y-m-d', "$month-01")->format('M-Y'); + + return $this->loadViews("stock/dieselStockDetails", $this->global, $data, NULL); + } + - //filter applied currently - $customisedMachineCodes = $this->request->getPost('customisedMachineCodes') ?? []; + //updateDieselMachineDetails + + public function updateDieselMachineDetails() { + + $postData = $this->request->getPost(); + $updateDmDetailsData = json_decode($postData['updateDieselMachineDetails'], true); + + $updateTotalDmDetailsData = $updateDmDetailsData[0]; + $updateDmDetailsData = $updateDmDetailsData[1]; + + $updatesDmR = []; + $insertsDmR = []; + $updatesTotalDmR = []; + $insertsTotalDmR = []; + + // Fetch existing records in bulk for diesel machine details + $dates = array_column($updateDmDetailsData, 'date'); + $machineIds = array_column($updateDmDetailsData, 'machine_id'); + $existingDmRecords = $this->factoryVehicleDieselDetails_model + ->whereIn('date', $dates) + ->whereIn('machine_id', $machineIds) + ->findAll(); + + $existingDmMap = []; + foreach ($existingDmRecords as $record) { + $existingDmMap [$record['date']] [$record['machine_id']] = $record; + } + + foreach ($updateDmDetailsData as $data) { + $date = $data['date']; + $machineId = $data['machine_id']; + + $dbData = [ + 'date' => $data['date'], + 'machine_id' => $data['machine_id'], + 'opening_reading' => $data['opening_reading'], + 'closing_reading' => $data['closing_reading'], + 'filling_diesel' => $data['filling_diesel'], + 'consumption' => $data['consumption'], + 'running_hours' => $data['running_hours'], + 'mileage' => $data['mileage'] + ]; + + if (isset($existingDmMap[$date][$machineId])) { + $dbData['id'] = $existingDmMap[$date][$machineId]['id']; + $updatesDmR[] = $dbData; + } else { + $insertsDmR[] = $dbData; + } + } + + // Fetch existing records in bulk for diesel stock summary + $dates = array_column($updateTotalDmDetailsData, 'date'); + $existingTotalDmRecords = $this->factoryVehicleDieselStockSummary_model + ->whereIn('date', $dates) + ->findAll(); + + $existingTotalDmMap = []; + foreach ($existingTotalDmRecords as $record) { + $existingTotalDmMap[$record['date']] = $record; + } + + foreach ($updateTotalDmDetailsData as $data) { + $date = $data['date']; + + $dbData = [ + 'date' => $data['date'], + 'opening_stock' => $data['opening_stock'], + 'purchase_diesel' => $data['purchase_diesel'], + 'total_filling_diesel' => $data['total_filling_diesel'], + 'balance_stock' => $data['balance_stock'] + ]; + + if (isset($existingTotalDmMap[$date])) { + $dbData['id'] = $existingTotalDmMap[$date]['id']; + $updatesTotalDmR[] = $dbData; + } else { + $insertsTotalDmR[] = $dbData; + } + } + + // Start the transaction + $this->db->transBegin(); + + try { + if (!empty($insertsDmR)) { + $this->factoryVehicleDieselDetails_model->insertBatch($insertsDmR); + } + + if (!empty($updatesDmR)) { + $this->factoryVehicleDieselDetails_model->updateBatch($updatesDmR, 'id'); + } + + if (!empty($insertsTotalDmR)) { + $this->factoryVehicleDieselStockSummary_model->insertBatch($insertsTotalDmR); + } + + if (!empty($updatesTotalDmR)) { + $this->factoryVehicleDieselStockSummary_model->updateBatch($updatesTotalDmR, 'id'); + } + + // Commit the transaction if all operations are successful + $this->db->transCommit(); + echo "Data Saved Successfully"; + + } catch (\Exception $error) { + // Rollback the transaction in case of any errors + $this->db->transRollback(); + echo "An error occurred: " . $error->getMessage(); + } + } + + + //power stock details + + public function powerConsumptionDetails(){ + + + $month = getStockMonth($this->request); - //already applied filter - $existingCustomMachineCodes = $this->monthWiseMachineInStockModel + $data = []; + + $data['month'] = $month; + + $this->global['pageTitle'] = 'Power Consumption Stock Details'; + + + + + //filter part starts + + //start date dynamic from front-end + $startDate = "$month-01"; + //end date of given month + $endDate = date("Y-m-t", strtotime($startDate)); + + + //filter applied currently + $customisedMachineCodes = $this->request->getPost('customisedMachineCodes') ?? []; + + + //already applied filter + $existingCustomMachineCodes = $this->monthWiseMachineInStockModel + ->select('machine_id') + ->where('date',"$month-01") + ->where('machine_category','electric') + ->findAll(); + + $filterUpdateNeeded = true ; + + if( empty($customisedMachineCodes) && !empty($existingCustomMachineCodes)){ + + $customisedMachineCodes = array_column($existingCustomMachineCodes, 'machine_id') ; + $filterUpdateNeeded = false ; + + } + + + //check user applies for filter currently + if(!empty($customisedMachineCodes) && $filterUpdateNeeded){ + + //user applied filter, + + //check 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 + ]; + + } + + 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') - ->findAll(); - - $filterUpdateNeeded = true ; - - if( empty($customisedMachineCodes) && !empty($existingCustomMachineCodes)){ - $customisedMachineCodes = array_column($existingCustomMachineCodes, 'materialCode') ; - $filterUpdateNeeded = false ; - - } - - - //check user applies for filter currently - if(!empty($customisedMachineCodes) && $filterUpdateNeeded){ - - //user applied filter, - - //check already filter existing , if exists remove that , - if(!empty($existingCustomMachineCodes)){ - - //hard delete done..!! - $existingCustomMachineCodes = $this->monthWiseMachineInStockModel - ->where('date',"$month-01") - ->where('machine_category','diesel') - ->delete(); - - } - - - //if no filter already exists or removed current one , just add current filter for that month ....!! - $inserts = []; - - foreach($customisedMachineCodes as $index => $customisedMachineCode){ - - $inserts [] = [ - 'date' => "$month-01", - 'machine_category' => "diesel", - 'machine_id' => $customisedMachineCode - ]; + ->where('machine_category','electric') + ->get() + ->getResultArray(); + } + + } - //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(); + + //possible if no filter applied at all...!!! + if(empty($existingCustomMachineCodes) ){ - //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); - } - - } + //no filter applied at all just present previous month material codes - if(!empty($inserts)){ - //insert all the latest applied filter - $this->monthWiseMachineInStockModel->insertBatch($inserts); + $previousMonth = date('Y-m-01', strtotime('-1 month', strtotime("$month-01"))); + + $previousMonthCustomMachineCodes = $this->monthWiseMachineInStockModel + ->select('machine_id') + ->where('date',"$previousMonth") + ->where('machine_category','electric') + ->get() + ->getResultArray(); - //get the currently applied filter - $existingCustomMachineCodes = $this->monthWiseMachineInStockModel - ->select('machine_id') - ->where('date',"$month-01") - ->where('machine_category','diesel') - ->get() - ->getResultArray(); - - } + if(!empty($previousMonthCustomMachineCodes)){ + $existingCustomMachineCodes = $this->factoryMachine_model + ->getSelectedDieselMachines(array_column($previousMonthCustomMachineCodes, 'machine_id')); + }else{ + + // inserting all active if no previous month present + $existingCustomMachineCodes = $this->factoryMachine_model + ->getAllActiveElectricMachines(); + + + //if no filter exists , just add current filter for that month ....!! + $inserts = []; + + foreach($existingCustomMachineCodes as $index => $customisedMachineCode){ + + $inserts [] = [ + 'date' => "$month-01", + 'machine_category' => "electric", + 'machine_id' => $customisedMachineCode['id'] + ]; } - - //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')); + if(!empty($inserts)){ + //insert all the latest applied filter + $this->monthWiseMachineInStockModel->insertBatch($inserts); + } + } - - //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(); + }else{ + //if filter present,get that material codes + $existingCustomMachineCodes = $this->factoryMachine_model + ->getSelectedElectricMachines(array_column($existingCustomMachineCodes, 'machine_id')); + } - // Get the previous month's last date diesel stock details for next month updation + //this existingCustomMachineCodes gets its machine after visiting factory machine master table + $machineCodeList = array_column($existingCustomMachineCodes, 'id'); - $previousMonth = DateTime::createFromFormat('Y-m-d', $month.'-01')->modify('-1 month')->format('Y-m'); - $previousMonthStartDate = "$previousMonth-01"; - $previousMonthEndDate = date("Y-m-t", strtotime($previousMonthStartDate)); - - $data['previousMonthDieselMachineStockDetails'] = $this->factoryVehicleDieselDetails_model - ->select(['machine_id', 'date', 'closing_reading']) - ->distinct() - ->where('date =', $previousMonthEndDate) - ->groupBy(['machine_id', 'date']) - ->orderBy('date', 'desc') - ->orderBy('machine_id', 'asc') - ->findAll(); + $currentDate = new DateTime(); - $data['previousMonthTotalDieselMachineStockDetails'] = $this->factoryVehicleDieselStockSummary_model - ->select(['id', 'date', 'balance_stock']) - ->distinct() - ->where('date =', $previousMonthEndDate) - ->groupBy(['id', 'date']) - ->orderBy('date', 'desc') - ->findAll(); + if($startDate == $currentDate->format('Y-m-01') && $endDate == $currentDate->format('Y-m-t')){ + + foreach($machineCodeList as $index => $machineCode){ - - - // 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 + //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) - ->whereIn('machine_id',$machineCodeList) - ->groupBy(['machine_id', 'date']) - ->orderBy('date', 'asc') - ->orderBy('machine_id', 'asc') + ->where('machine_id',$machineCode) ->findAll(); + + + //check any material code is not present in stock table but applied in filter + if(empty($findMachineCode)){ + //create dummy entry for this + $this->createDummyEntryForElectricMachine($machineCode,$startDate,$endDate); + } + + } + } + + + + $electricMachines = $existingCustomMachineCodes; + + $data['activeElectricMachines'] = $this->factoryMachine_model->getAllActiveElectricMachines(); - $data['totalDiesel'] = $this->factoryVehicleDieselStockSummary_model + + + + + + + + + // Get the previous month's last date power consumption stock details for next month updation + + $previousMonth = DateTime::createFromFormat('Y-m-d', $month.'-01')->modify('-1 month')->format('Y-m'); + $previousMonthStartDate = "$previousMonth-01"; + $previousMonthEndDate = date("Y-m-t", strtotime($previousMonthStartDate)); + + $data['previousMonthPowerConsumptionStockDetails'] = $this->powerConsumptionDetails_model + ->select(['machine_id', 'date', 'closing_units']) + ->distinct() + ->where('date =', $previousMonthEndDate) + ->groupBy(['machine_id', 'date']) + ->orderBy('date', 'desc') + ->orderBy('machine_id', 'asc') + ->findAll(); + + $data['previousMonthTotalPowerMachineStockDetails'] = $this->powerConsumptionSummary_model + ->select(['id', 'date', 'final_reading']) + ->distinct() + ->where('date =', $previousMonthEndDate) + ->groupBy(['id', 'date']) + ->orderBy('date', 'desc') + ->findAll(); + + + + // checking in database if the data is available for the month + + + + $data['powerConsumptionStockDetails'] = $this->powerConsumptionDetails_model + ->where('date >=', $startDate) + ->where('date <=', $endDate) + ->whereIn('machine_id',$machineCodeList) + ->groupBy(['machine_id', 'date']) + ->orderBy('date', 'asc') + ->orderBy('machine_id', 'asc') + ->findAll(); + + $data['totalPower'] = $this->powerConsumptionSummary_model ->where('date >=', $startDate) ->where('date <=', $endDate) ->orderBy('date', 'asc') ->findAll(); - // Initialize an empty array to hold the grouped data - $data['groupedDieselMachineStockDetails'] = []; + // Initialize an empty array to hold the grouped data + $data['groupedPowerConsumptionStockDetails'] = []; - // Temporary array to store grouped data by date - $groupedByDate = []; + // Temporary array to store grouped data by date + $groupedByDate = []; - // Group by 'date' - foreach ($data['dieselMachineStockDetails'] as $detail) { - $date = $detail['date']; + // 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; + // Initialize the outer array for this date if it doesn't exist + if (!isset($groupedByDate[$date])) { + $groupedByDate[$date] = []; } - // Sort each date's machines based on the custom order to set table body td - if (!empty($customisedMachineCodes)) { + /******************************************************************************************************************* + creating an sub array (inner array) for date wise and append the detail into an array as sub-array - foreach ($groupedByDate as $date => &$machines) { - - usort($machines, function ($a, $b) use ($customisedMachineCodes) { - - $indexA = array_search($a['machine_id'], $customisedMachineCodes); - $indexB = array_search($b['machine_id'], $customisedMachineCodes); - - if ($indexA === false && $indexB === false) { - return 0; - } - if ($indexA === false) { - return 1; - } - if ($indexB === false) { - return -1; - } - - return $indexA - $indexB; - }); - } - unset($machines); - } + $groupedByDate[] outer array - // Reset the structure to have indexed arrays without the date keys - $data['groupedDieselMachineStockDetails'] = array_values($groupedByDate); - + $groupedByDate[$date] + will look like [[material1],[material2],[material3],[material4],[material5]] inner array + + the above process is done for single row (date wise) and the same process is repeated for all the rows + *******************************************************************************************************************/ + + $groupedByDate[$date][] = $detail; + } - // Sort each date's machines based on the custom order to set table header th + // Sort each date's machines based on the custom order to set table body td + if (!empty($customisedMachineCodes)) { - if (!empty($customisedMachineCodes)) { - - - - usort($dieselMachines, function ($a, $b) use ($customisedMachineCodes) { - - $indexA = array_search($a['id'], $customisedMachineCodes); - $indexB = array_search($b['id'], $customisedMachineCodes); + foreach ($groupedByDate as $date => &$machines) { + usort($machines, function ($a, $b) use ($customisedMachineCodes) { + + $indexA = array_search($a['machine_id'], $customisedMachineCodes); + $indexB = array_search($b['machine_id'], $customisedMachineCodes); + if ($indexA === false && $indexB === false) { - return 0; + return 0; } if ($indexA === false) { return 1; @@ -1530,925 +1382,504 @@ class StockController extends BaseController if ($indexB === false) { return -1; } - + return $indexA - $indexB; }); - } + unset($machines); + } - $dieselMachinesCount = count($dieselMachines); + // Reset the structure to have indexed arrays without the date keys + $data['groupedPowerConsumptionStockDetails'] = array_values($groupedByDate); - $data['dieselMachinesCount'] = $dieselMachinesCount; - $data['dieselMachines'] = $dieselMachines; - $date = DateTime::createFromFormat('Y-m-d', $month.'-01'); + // Sort each date's machines based on the custom order to set table header th - $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); + if (!empty($customisedMachineCodes)) { + usort($electricMachines, function ($a, $b) use ($customisedMachineCodes) { + + $indexA = array_search($a['id'], $customisedMachineCodes); + $indexB = array_search($b['id'], $customisedMachineCodes); + + if ($indexA === false && $indexB === false) { + return 0; + } + if ($indexA === false) { + return 1; + } + if ($indexB === false) { + return -1; + } + + return $indexA - $indexB; + }); } - 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(); - } - } + $electricMachinesCount = count($electricMachines); + $data['electricMachinesCount'] = $electricMachinesCount; + $data['electricMachines'] = $electricMachines; - //power stock details - public function powerConsumptionDetails(){ + $date = DateTime::createFromFormat('Y-m-d', $month.'-01'); - - if ($this->request->getMethod() === 'POST') { + $formattedDate = $date->format('M-Y'); - $month = $this->request->getPost('month'); + $data['month'] = $formattedDate; - $date = DateTime::createFromFormat('d-M-Y', '01-'.$month); //in M-Y format - - $formattedDate = $date->format('Y-m'); //in Y-m format - - $month = $formattedDate; - - $session = session (); - - $session->set('stock_month',$month); - - - } else { - - $session = session(); - - $month = $session->get('stock_month'); - - if (empty($month)) { - $month = date('Y-m'); // Default to the current month - } - } - - $data = []; - - $data['month'] = $month; - - $this->global['pageTitle'] = 'Power Consumption Stock Details'; + // return $this->response->setJSON(['status' =>'success' ,'message' => $data['electricMachines']]); + return $this->loadViews("stock/powerConsumptionDetails", $this->global, $data, NULL); + } + //updatePowerConsumptionDetails + public function updatePowerConsumptionDetails(){ - //filter part starts - - //start date dynamic from front-end - $startDate = "$month-01"; - //end date of given month - $endDate = date("Y-m-t", strtotime($startDate)); - - - //filter applied currently - $customisedMachineCodes = $this->request->getPost('customisedMachineCodes') ?? []; - - - //already applied filter - $existingCustomMachineCodes = $this->monthWiseMachineInStockModel - ->select('machine_id') - ->where('date',"$month-01") - ->where('machine_category','electric') - ->findAll(); - - $filterUpdateNeeded = true ; - - if( empty($customisedMachineCodes) && !empty($existingCustomMachineCodes)){ - $customisedMachineCodes = array_column($existingCustomMachineCodes, 'materialCode') ; - $filterUpdateNeeded = false ; - - } - - - //check user applies for filter currently - if(!empty($customisedMachineCodes) && $filterUpdateNeeded){ - - //user applied filter, - - //check already filter existing , if exists remove that , - if(!empty($existingCustomMachineCodes)){ - - //hard delete done..!! - $existingCustomMachineCodes = $this->monthWiseMachineInStockModel - ->where('date',"$month-01") - ->where('machine_category','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-d', $month.'-01')->modify('-1 month')->format('Y-m'); - $previousMonthStartDate = "$previousMonth-01"; - $previousMonthEndDate = date("Y-m-t", strtotime($previousMonthStartDate)); - - $data['previousMonthPowerConsumptionStockDetails'] = $this->powerConsumptionDetails_model - ->select(['machine_id', 'date', 'closing_units']) - ->distinct() - ->where('date =', $previousMonthEndDate) - ->groupBy(['machine_id', 'date']) - ->orderBy('date', 'desc') - ->orderBy('machine_id', 'asc') - ->findAll(); - - $data['previousMonthTotalPowerMachineStockDetails'] = $this->powerConsumptionSummary_model - ->select(['id', 'date', 'final_reading']) - ->distinct() - ->where('date =', $previousMonthEndDate) - ->groupBy(['id', 'date']) - ->orderBy('date', 'desc') - ->findAll(); - - - - // checking in database if the data is available for the month - - - - $data['powerConsumptionStockDetails'] = $this->powerConsumptionDetails_model - ->where('date >=', $startDate) - ->where('date <=', $endDate) - ->whereIn('machine_id',$machineCodeList) - ->groupBy(['machine_id', 'date']) - ->orderBy('date', 'asc') - ->orderBy('machine_id', 'asc') - ->findAll(); - - $data['totalPower'] = $this->powerConsumptionSummary_model - ->where('date >=', $startDate) - ->where('date <=', $endDate) - ->orderBy('date', 'asc') - ->findAll(); - - // Initialize an empty array to hold the grouped data - $data['groupedPowerConsumptionStockDetails'] = []; - - // Temporary array to store grouped data by date - $groupedByDate = []; - - // Group by 'date' - foreach ($data['powerConsumptionStockDetails'] as $detail) { - $date = $detail['date']; - - // Initialize the outer array for this date if it doesn't exist - if (!isset($groupedByDate[$date])) { - $groupedByDate[$date] = []; - } - - /******************************************************************************************************************* - creating an sub array (inner array) for date wise and append the detail into an array as sub-array - - $groupedByDate[] outer array - - $groupedByDate[$date] - will look like [[material1],[material2],[material3],[material4],[material5]] inner array - - the above process is done for single row (date wise) and the same process is repeated for all the rows - *******************************************************************************************************************/ - - $groupedByDate[$date][] = $detail; - } - - - // Sort each date's machines based on the custom order to set table body td - if (!empty($customisedMachineCodes)) { - - foreach ($groupedByDate as $date => &$machines) { - - usort($machines, function ($a, $b) use ($customisedMachineCodes) { - - $indexA = array_search($a['machine_id'], $customisedMachineCodes); - $indexB = array_search($b['machine_id'], $customisedMachineCodes); - - if ($indexA === false && $indexB === false) { - return 0; - } - if ($indexA === false) { - return 1; - } - if ($indexB === false) { - return -1; - } - - return $indexA - $indexB; - }); - } - unset($machines); - } - - // Reset the structure to have indexed arrays without the date keys - $data['groupedPowerConsumptionStockDetails'] = array_values($groupedByDate); - - - // Sort each date's machines based on the custom order to set table header th - - if (!empty($customisedMachineCodes)) { - - - - usort($electricMachines, function ($a, $b) use ($customisedMachineCodes) { - - $indexA = array_search($a['id'], $customisedMachineCodes); - $indexB = array_search($b['id'], $customisedMachineCodes); - - if ($indexA === false && $indexB === false) { - return 0; - } - if ($indexA === false) { - return 1; - } - if ($indexB === false) { - return -1; - } - - return $indexA - $indexB; - }); - - } - - $electricMachinesCount = count($electricMachines); - - $data['electricMachinesCount'] = $electricMachinesCount; - $data['electricMachines'] = $electricMachines; - - $date = DateTime::createFromFormat('Y-m-d', $month.'-01'); - - $formattedDate = $date->format('M-Y'); - - $data['month'] = $formattedDate; - - // return $this->response->setJSON(['status' =>'success' ,'message' => $data['electricMachines']]); - - return $this->loadViews("stock/powerConsumptionDetails", $this->global, $data, NULL); - - } - - public function updatePowerConsumptionDetails(){ - - //pm stands for power machine - - - $postData = $this->request->getPost(); - - $updatePowerConsumptionDetailsData = json_decode($postData['updatePowerConsumptionDetails'], true); - - $updateTotalPmDetailsData = $updatePowerConsumptionDetailsData[0]; - $updatePmDetailsData = $updatePowerConsumptionDetailsData[1]; - - //PmR stands for power machine readings - - $updatesPmR = []; - $insertsPmR = []; - - $updatesTotalPmR = []; - $insertsTotalPmR = []; - - // Fetch existing records in bulk for power machine details - $dates = array_column($updatePmDetailsData, 'date'); - $machineIds = array_column($updatePmDetailsData, 'machine_id'); - $existingPmRecords = $this->powerConsumptionDetails_model - ->whereIn('date', $dates) - ->whereIn('machine_id', $machineIds) - ->findAll(); - - $existingPmMap = []; - foreach ($existingPmRecords as $record) { - $existingPmMap[$record['date']][$record['machine_id']] = $record; - } - - foreach ($updatePmDetailsData as $data) { - $date = $data['date']; - $machineId = $data['machine_id']; - - $dbData = [ - 'date' => $data['date'], - 'machine_id' => $data['machine_id'], - 'opening_units' => $data['opening_units'], - 'closing_units' => $data['closing_units'], - 'total_units' => $data['total_units'], - ]; - - if (isset($existingPmMap[$date][$machineId])) { - $dbData['id'] = $existingPmMap[$date][$machineId]['id']; - $updatesPmR[] = $dbData; - } else { - $insertsPmR[] = $dbData; - } - } - - // Fetch existing records in bulk for power stock summary - $dates = array_column($updateTotalPmDetailsData, 'date'); - $existingTotalPmRecords = $this->powerConsumptionSummary_model - ->whereIn('date', $dates) - ->findAll(); - - $existingTotalPmMap = []; - foreach ($existingTotalPmRecords as $record) { - $existingTotalPmMap[$record['date']] = $record; - } - - foreach ($updateTotalPmDetailsData as $data) { - $date = $data['date']; - - $dbData = [ - 'date' => $data['date'], - 'opening_reading' => $data['opening_reading'], - 'final_reading' => $data['final_reading'], - 'total_reading' => $data['total_reading'], - 'total_units' => $data['total_units'], - 'average_pf' => $data['average_pf'], - 'present_pf' => $data['present_pf'], - 'md' => $data['md'], - 'mf' => $data['mf'] - ]; - - if (isset($existingTotalPmMap[$date])) { - $dbData['id'] = $existingTotalPmMap[$date]['id']; - $updatesTotalPmR[] = $dbData; - } else { - $insertsTotalPmR[] = $dbData; - } - } - - // Start the transaction - $this->db->transBegin(); - - try { - if (!empty($insertsPmR)) { - $this->powerConsumptionDetails_model->insertBatch($insertsPmR); - } - - if (!empty($updatesPmR)) { - $this->powerConsumptionDetails_model->updateBatch($updatesPmR, 'id'); - } - - if (!empty($insertsTotalPmR)) { - $this->powerConsumptionSummary_model->insertBatch($insertsTotalPmR); - } - - if (!empty($updatesTotalPmR)) { - $this->powerConsumptionSummary_model->updateBatch($updatesTotalPmR, 'id'); - } - - // Commit the transaction if all operations are successful - $this->db->transCommit(); - echo "Data Saved Successfully"; - - } catch (\Exception $error) { - // Rollback the transaction in case of any errors - $this->db->transRollback(); - echo "An error occurred: " . $error->getMessage(); - } - - } - - - //Dust And Rough Stock Details - public function loadView_dustAndRoughStockDetails() - { - - if ($this->request->getMethod() === 'POST') { - $month = $this->request->getPost('month'); - - $date = DateTime::createFromFormat('d-M-Y', '01-'.$month); - - $formattedDate = $date->format('Y-m'); - - $month = $formattedDate; - - $session = session (); - - $session->set('stock_month',$month); - - } else { - $session = session(); - - $month = $session->get('stock_month'); - - if (empty($month)) { - $month = date('Y-m'); // Default to the current month - } - } - - $data = []; - - $data['month'] = $month; - - $this->global['pageTitle'] = 'Dust And Rough Stock Details'; - - $startDate = "$month-01"; - $endDate = date("Y-m-t", strtotime($startDate)); - $data['dustAndRoughStockDetails'] = $this->dustAndRoughStockDetails_model - ->where('date >=', $startDate) - ->where('date <=', $endDate) - ->orderBy('date', 'asc') - ->findAll(); - - $date = DateTime::createFromFormat('Y-m-d', $month.'-01'); - - $formattedDate = $date->format('M-Y'); - - $data['month'] = $formattedDate; - - return $this->loadViews("stock/dustAndRoughStockDetails", $this->global, $data, NULL); - } - + //pm stands for power machine - public function updateDustAndRoughStockDetails() - { + + $postData = $this->request->getPost(); - $postData = $this->request->getPost(); + $updatePowerConsumptionDetailsData = json_decode($postData['updatePowerConsumptionDetails'], true); - $updateDustAndRoughStockDetailsData = json_decode($postData['updateDustAndRoughStockDetails'], true); + $updateTotalPmDetailsData = $updatePowerConsumptionDetailsData[0]; + $updatePmDetailsData = $updatePowerConsumptionDetailsData[1]; + + //PmR stands for power machine readings - $updates = []; + $updatesPmR = []; + $insertsPmR = []; - $inserts = []; + $updatesTotalPmR = []; + $insertsTotalPmR = []; - 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; + // 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; } - } - - 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; + + 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(); } - } - echo "Data Saved Successfully"; + } + + //Dust And Rough Stock Details + + public function loadView_dustAndRoughStockDetails() + { + + $month = getStockMonth($this->request); + + + $data = []; + + $data['month'] = $month; + + $this->global['pageTitle'] = 'Dust And Rough Stock Details'; + + $startDate = "$month-01"; + $endDate = date("Y-m-t", strtotime($startDate)); + $data['dustAndRoughStockDetails'] = $this->dustAndRoughStockDetails_model + ->where('date >=', $startDate) + ->where('date <=', $endDate) + ->orderBy('date', 'asc') + ->findAll(); + + $date = DateTime::createFromFormat('Y-m-d', $month.'-01'); + + $formattedDate = $date->format('M-Y'); + + $data['month'] = $formattedDate; + + return $this->loadViews("stock/dustAndRoughStockDetails", $this->global, $data, NULL); + } + + //updateDustAndRoughStockDetails + + public function updateDustAndRoughStockDetails() + { + + $postData = $this->request->getPost(); + + $updateDustAndRoughStockDetailsData = json_decode($postData['updateDustAndRoughStockDetails'], true); + + $updates = []; + + $inserts = []; + + foreach ($updateDustAndRoughStockDetailsData as $data) { + + $data['date'] = DateTime::createFromFormat('d-m-Y', $data['date'])->format('Y-m-d'); + + $date = $data['date']; + + $dbData = [ + 'date' => $data['date'], + 'finalRough' => $data['finalRough'], + 'dust' => $data['dust'], + 'total' => $data['total'] + ]; + + $resultExists = $this->dustAndRoughStockDetails_model + ->where('date', $date) + ->first(); + + + if (empty($resultExists)) { + $inserts[] = $dbData; + } else { + $updates[] = $dbData; + } } + if (!empty($inserts)) { + $this->dustAndRoughStockDetails_model->insertBatch($inserts); + } - //Resin Stock Details - public function loadView_resinStockDetails() - { + if (!empty($updates)) { - if ($this->request->getMethod() === 'POST') { - - $month = $this->request->getPost('month'); - - $date = DateTime::createFromFormat('d-M-Y', '01-'.$month); - - $formattedDate = $date->format('Y-m'); - - $month = $formattedDate; - - $session = session (); - - $session->set('stock_month',$month); + $updateResult = $this->dustAndRoughStockDetails_model->updateBatch($updates, 'date'); + if ($updateResult === FALSE) { + echo "Error during update"; } else { - $session = session(); + echo "Data Updated Successfully"; + return; + } + } - $month = $session->get('stock_month'); + echo "Data Saved Successfully"; + } + + + //Resin Stock Details + + public function loadView_resinStockDetails() + { + + $month = getStockMonth($this->request); + + + $data = []; + + $data['month'] = $month; + + $this->global['pageTitle'] = 'Resin Stock Details'; + + $startDate = "$month-01"; + $endDate = date("Y-m-t", strtotime($startDate)); + + + + $customisedMaterialCodes = $this->request->getPost('customisedMaterialCodes') ?? []; + + $existingCustomMaterialCodes = $this->monthWiseMaterialInStockModel + ->select('materialCode') + ->where('date',"$month-01") + ->where('stock_category','resin') + ->findAll(); + + $filterUpdateNeeded = true ; + + if( empty($customisedMaterialCodes) && !empty($existingCustomMaterialCodes)){ + $customisedMaterialCodes = array_column($existingCustomMaterialCodes, 'materialCode') ; + $filterUpdateNeeded = false ; + + } + + + //check user applies for filter currently + if(!empty($customisedMaterialCodes) && $filterUpdateNeeded){ + + //user applied new filter, + + //check already filter existing , if exists remove that , + if(!empty($existingCustomMaterialCodes)){ + + //hard delete done..!! + $existingCustomMaterialCodes = $this->monthWiseMaterialInStockModel + ->where('date',"$month-01") + ->where('stock_category','resin') + ->delete(); - if (empty($month)) { - $month = date('Y-m'); // Default to the current month - } } - $data = []; - $data['month'] = $month; + //if no filter already exists or removed current one , just add current filter for that month ....!! + $inserts = []; - $this->global['pageTitle'] = 'Resin Stock Details'; + foreach($customisedMaterialCodes as $index => $customisedMaterialCode){ - $startDate = "$month-01"; - $endDate = date("Y-m-t", strtotime($startDate)); + $inserts [] = [ + 'date' => "$month-01", + 'stock_category' => "resin", + 'materialCode' => $customisedMaterialCode + ]; + + } + if(!empty($inserts)){ + //insert all the latest applied filter + $this->monthWiseMaterialInStockModel->insertBatch($inserts); - - $customisedMaterialCodes = $this->request->getPost('customisedMaterialCodes') ?? []; - - $existingCustomMaterialCodes = $this->monthWiseMaterialInStockModel + //get the currently applied filter + $existingCustomMaterialCodes = $this->monthWiseMaterialInStockModel ->select('materialCode') ->where('date',"$month-01") ->where('stock_category','resin') - ->findAll(); - - $filterUpdateNeeded = true ; + ->get()->getResultArray(); + + } - if( empty($customisedMaterialCodes) && !empty($existingCustomMaterialCodes)){ - $customisedMaterialCodes = array_column($existingCustomMaterialCodes, 'materialCode') ; - $filterUpdateNeeded = false ; + } - } + + //possible if no filter applied at all...!!! + if(empty($existingCustomMaterialCodes)){ + + //no filter applied at all just present previous month material codes + + $previousMonth = date('Y-m-01', strtotime('-1 month', strtotime("$month-01"))); + $previousMonthCustomMachineCodes = $this->monthWiseMaterialInStockModel + ->select('materialCode') + ->where('date',"$previousMonth") + ->where('stock_category','resin') + ->get() + ->getResultArray(); - //check user applies for filter currently - if(!empty($customisedMaterialCodes) && $filterUpdateNeeded){ + if(!empty($previousMonthCustomMachineCodes)){ + $existingCustomMaterialCodes = $this->rawmaterialdetails_model + ->getSelectedResinMaterialCode(array_column($previousMonthCustomMachineCodes, 'materialCode')); + }else{ - //user applied new filter, - - //check already filter existing , if exists remove that , - if(!empty($existingCustomMaterialCodes)){ + // inserting all active if no previous month present + $existingCustomMaterialCodes = $this->rawmaterialdetails_model->getAllResinMaterialCode(); - //hard delete done..!! - $existingCustomMaterialCodes = $this->monthWiseMaterialInStockModel - ->where('date',"$month-01") - ->where('stock_category','resin') - ->delete(); + $inserts = []; + foreach($existingCustomMaterialCodes as $index => $customisedMaterialCode){ + + $inserts [] = [ + 'date' => "$month-01", + 'stock_category' => "resin", + 'materialCode' => $customisedMaterialCode['MaterialCode'] + ]; + } - - //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(); - - } - + if(!empty($inserts)){ + //insert all the latest applied filter + $this->monthWiseMaterialInStockModel->insertBatch($inserts) ; + + } } + + }else{ + //if filter present , Reuse the filter and get that material codes + $existingCustomMaterialCodes = $this->rawmaterialdetails_model + ->getSelectedResinMaterialCode(array_column($existingCustomMaterialCodes, 'materialCode')); + } + + + $materialCodeList = array_column($existingCustomMaterialCodes, 'MaterialCode'); + + $currentDate = new DateTime(); + + if($startDate == $currentDate->format('Y-m-01') && $endDate == $currentDate->format('Y-m-t')){ - //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 , Reuse the filter and get that material codes - $existingCustomMaterialCodes = $this->rawmaterialdetails_model - ->getSelectedResinMaterialCode(array_column($existingCustomMaterialCodes, 'materialCode')); - } + foreach($materialCodeList as $index => $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-d', $month.'-01')->modify('-1 month')->format('Y-m'); - $previousMonthStartDate = "$previousMonth-01"; - $previousMonthEndDate = date("Y-m-t", strtotime($previousMonthStartDate)); - $data['previousMonthResinStockDetails'] = $this->resinStockDetails_model - ->select(['materialCode', 'date', 'balanceStock']) - ->distinct() - ->where('date =', $previousMonthEndDate) - ->groupBy(['materialCode', 'date']) - ->orderBy('date', 'desc') - ->orderBy('materialCode', 'asc') - ->findAll(); - - - - // checking in database if the data is available for the month - - - - $data['resinStockDetails'] = $this->resinStockDetails_model + //checking filtered material code present in table , if not create dummy one for whole month if it is current month + $findMachineCode = $this->resinStockDetails_model ->where('date >=', $startDate) ->where('date <=', $endDate) - ->whereIn('materialCode',$materialCodeList) - ->groupBy(['materialCode', 'date']) - ->orderBy('date', 'asc') - ->orderBy('materialCode', 'asc') + ->where('materialCode',$materialCode) ->findAll(); + - // Initialize an empty array to hold the grouped data - $data['groupedResinStockDetails'] = []; - - // Temporary array to store grouped data by date - $groupedByDate = []; - - // Group by 'date' - foreach ($data['resinStockDetails'] as $detail) { - $date = $detail['date']; - - // Initialize the outer array for this date if it doesn't exist - if (!isset($groupedByDate[$date])) { - $groupedByDate[$date] = []; + //check any material code is not present in stock table but applied in filter + if(empty($findMachineCode)){ + //create dummy entry for this + $this->createDummyEntryForResin($materialCode,$startDate,$endDate); } - - /******************************************************************************************************************* - creating an sub array (inner array) for date wise and append the detail into an array as sub-array - - $groupedByDate[] outer array - - $groupedByDate[$date] - will look like [[material1],[material2],[material3],[material4],[material5]] inner array - - the above process is done for single row (date wise) and the same process is repeated for all the rows - *******************************************************************************************************************/ - - $groupedByDate[$date][] = $detail; - } - - // Sort each date's materials based on the custom order to set table body td - if (!empty($customisedMaterialCodes)) { - - foreach ($groupedByDate as $date => &$materials) { - - usort($materials, function ($a, $b) use ($customisedMaterialCodes) { - - $indexA = array_search($a['materialCode'], $customisedMaterialCodes); - $indexB = array_search($b['materialCode'], $customisedMaterialCodes); - - if ($indexA === false && $indexB === false) { - return 0; - } - if ($indexA === false) { - return 1; - } - if ($indexB === false) { - return -1; - } - - return $indexA - $indexB; - }); - } - unset($materials); - } - - // Reset the structure to have indexed arrays without the date keys - - //this is for tbody table data td - $data['groupedResinStockDetails'] = array_values($groupedByDate); - - - // getting customer for creating table headers - // checking already existing stock if yes then get customer from the existing stock - // if not set customer in db , then set '' empty string - - foreach ($resinMaterials as $key => $resinMaterial) { - $materialCode = $resinMaterial['MaterialCode']; - $resinMaterials[$key]['customers'] = $this->resinStockDetails_model - ->select('customer') - ->where('date >=', $startDate) - ->where('date <=', $endDate) - ->where('materialCode', $materialCode) - ->first()['customer'] ?? ''; - } - - // Sort each date's materials based on the custom order to set table header th - if (!empty($customisedMaterialCodes)) { - - usort($resinMaterials, function ($a, $b) use ($customisedMaterialCodes) { - - $indexA = array_search($a['MaterialCode'], $customisedMaterialCodes); - $indexB = array_search($b['MaterialCode'], $customisedMaterialCodes); + } + } + + + + $resinMaterials = $existingCustomMaterialCodes ; + + $data['activeResinMaterials'] = $this->rawmaterialdetails_model->getAllResinMaterialCode(); + + + + // Get the previous month's last date resin stock details for next month updation + + $previousMonth = DateTime::createFromFormat('Y-m-d', $month.'-01')->modify('-1 month')->format('Y-m'); + $previousMonthStartDate = "$previousMonth-01"; + $previousMonthEndDate = date("Y-m-t", strtotime($previousMonthStartDate)); + $data['previousMonthResinStockDetails'] = $this->resinStockDetails_model + ->select(['materialCode', 'date', 'balanceStock']) + ->distinct() + ->where('date =', $previousMonthEndDate) + ->groupBy(['materialCode', 'date']) + ->orderBy('date', 'desc') + ->orderBy('materialCode', 'asc') + ->findAll(); + + + + // checking in database if the data is available for the month + + + + $data['resinStockDetails'] = $this->resinStockDetails_model + ->where('date >=', $startDate) + ->where('date <=', $endDate) + ->whereIn('materialCode',$materialCodeList) + ->groupBy(['materialCode', 'date']) + ->orderBy('date', 'asc') + ->orderBy('materialCode', 'asc') + ->findAll(); + + // Initialize an empty array to hold the grouped data + $data['groupedResinStockDetails'] = []; + + // Temporary array to store grouped data by date + $groupedByDate = []; + + // Group by 'date' + foreach ($data['resinStockDetails'] as $detail) { + $date = $detail['date']; + + // Initialize the outer array for this date if it doesn't exist + if (!isset($groupedByDate[$date])) { + $groupedByDate[$date] = []; + } + + /******************************************************************************************************************* + creating an sub array (inner array) for date wise and append the detail into an array as sub-array + + $groupedByDate[] outer array + + $groupedByDate[$date] + will look like [[material1],[material2],[material3],[material4],[material5]] inner array + + the above process is done for single row (date wise) and the same process is repeated for all the rows + *******************************************************************************************************************/ + + $groupedByDate[$date][] = $detail; + } + + // Sort each date's materials based on the custom order to set table body td + if (!empty($customisedMaterialCodes)) { + + foreach ($groupedByDate as $date => &$materials) { + + usort($materials, function ($a, $b) use ($customisedMaterialCodes) { + + $indexA = array_search($a['materialCode'], $customisedMaterialCodes); + $indexB = array_search($b['materialCode'], $customisedMaterialCodes); + if ($indexA === false && $indexB === false) { - return 0; + return 0; } if ($indexA === false) { return 1; @@ -2456,153 +1887,143 @@ class StockController extends BaseController if ($indexB === false) { return -1; } - + return $indexA - $indexB; }); - } - - - $resinMaterialCount = count($resinMaterials); - - $data['resinMaterialCount'] = $resinMaterialCount; - $data['resinMaterials'] = $resinMaterials; - - $date = DateTime::createFromFormat('Y-m-d', $month.'-01'); - - $formattedDate = $date->format('M-Y'); - - $data['month'] = $formattedDate; - - return $this->loadViews("stock/resinStockDetails", $this->global, $data, NULL); + unset($materials); } + // Reset the structure to have indexed arrays without the date keys + //this is for tbody table data td + $data['groupedResinStockDetails'] = array_values($groupedByDate); + + + // getting customer for creating table headers + // checking already existing stock if yes then get customer from the existing stock + // if not set customer in db , then set '' empty string + + foreach ($resinMaterials as $key => $resinMaterial) { + $materialCode = $resinMaterial['MaterialCode']; + $resinMaterials[$key]['customers'] = $this->resinStockDetails_model + ->select('customer') + ->where('date >=', $startDate) + ->where('date <=', $endDate) + ->where('materialCode', $materialCode) + ->first()['customer'] ?? ''; + } + + // Sort each date's materials based on the custom order to set table header th + if (!empty($customisedMaterialCodes)) { + + usort($resinMaterials, function ($a, $b) use ($customisedMaterialCodes) { + + $indexA = array_search($a['MaterialCode'], $customisedMaterialCodes); + $indexB = array_search($b['MaterialCode'], $customisedMaterialCodes); - public function updateResinStockDetails() - { - $postData = $this->request->getPost('updateResinStockDetails'); - $updateResinStockDetailsData = json_decode($postData, true); + if ($indexA === false && $indexB === false) { + return 0; + } + if ($indexA === false) { + return 1; + } + if ($indexB === false) { + return -1; + } - if (empty($updateResinStockDetailsData)) { - echo "No data provided"; + return $indexA - $indexB; + }); + + } + + + $resinMaterialCount = count($resinMaterials); + + $data['resinMaterialCount'] = $resinMaterialCount; + $data['resinMaterials'] = $resinMaterials; + + $date = DateTime::createFromFormat('Y-m-d', $month.'-01'); + + $formattedDate = $date->format('M-Y'); + + $data['month'] = $formattedDate; + + return $this->loadViews("stock/resinStockDetails", $this->global, $data, NULL); + } + + + // updateResinStockDetails + + public function updateResinStockDetails() + { + $postData = $this->request->getPost('updateResinStockDetails'); + $updateResinStockDetailsData = json_decode($postData, true); + + if (empty($updateResinStockDetailsData)) { + echo "No data provided"; + return; + } + + $inserts = []; + $updates = []; + + $dates = array_column($updateResinStockDetailsData, 'date'); + $materialCodes = array_column($updateResinStockDetailsData, 'materialCode'); + + // Fetch existing records in bulk to reduce queries + $existingRecords = $this->resinStockDetails_model + ->whereIn('date', $dates) + ->whereIn('materialCode', $materialCodes) + ->findAll(); + + $existingMap = []; + foreach ($existingRecords as $record) { + $existingMap[$record['date'] . '_' . $record['materialCode']] = $record['id']; + } + + foreach ($updateResinStockDetailsData as $data) { + + $key = $data['date'] . '_' . $data['materialCode']; + + $dbData = [ + 'date' => $data['date'], + 'materialCode' => $data['materialCode'], + 'customer' => $data['customer'], + 'opening' => $data['opening'], + 'receipt' => $data['receipt'], + 'used' => $data['used'], + 'balanceStock' => $data['balanceStock'], + ]; + + if (isset($existingMap[$key])) { + $dbData['id'] = $existingMap[$key]; + $updates[] = $dbData; + } else { + $inserts[] = $dbData; + } + } + + if (!empty($inserts)) { + $this->resinStockDetails_model->insertBatch($inserts); + } + + if (!empty($updates)) { + if ($this->resinStockDetails_model->updateBatch($updates, 'id') === false) { + echo "Error during update"; return; } - - $inserts = []; - $updates = []; - - $dates = array_column($updateResinStockDetailsData, 'date'); - $materialCodes = array_column($updateResinStockDetailsData, 'materialCode'); - - // Fetch existing records in bulk to reduce queries - $existingRecords = $this->resinStockDetails_model - ->whereIn('date', $dates) - ->whereIn('materialCode', $materialCodes) - ->findAll(); - - $existingMap = []; - foreach ($existingRecords as $record) { - $existingMap[$record['date'] . '_' . $record['materialCode']] = $record['id']; - } - - foreach ($updateResinStockDetailsData as $data) { - - $key = $data['date'] . '_' . $data['materialCode']; - - $dbData = [ - 'date' => $data['date'], - 'materialCode' => $data['materialCode'], - 'customer' => $data['customer'], - 'opening' => $data['opening'], - 'receipt' => $data['receipt'], - 'used' => $data['used'], - 'balanceStock' => $data['balanceStock'], - ]; - - if (isset($existingMap[$key])) { - $dbData['id'] = $existingMap[$key]; - $updates[] = $dbData; - } else { - $inserts[] = $dbData; - } - } - - if (!empty($inserts)) { - $this->resinStockDetails_model->insertBatch($inserts); - } - - if (!empty($updates)) { - if ($this->resinStockDetails_model->updateBatch($updates, 'id') === false) { - echo "Error during update"; - return; - } - } - - echo "Data Saved Successfully"; } - - public function createDummyEntryForResin($customisedMaterialCode, $startDate, $endDate) - { - if (!empty($customisedMaterialCode)) { - $inserts = []; - - // Convert start and end date to timestamps - $startTimestamp = strtotime($startDate); - $endTimestamp = strtotime($endDate); - - while ($startTimestamp <= $endTimestamp) { - $inserts[] = [ - 'date' => date('Y-m-d', $startTimestamp), // Convert timestamp to date format - 'materialCode' => $customisedMaterialCode, - 'customer' => ' ', - 'opening' => ' ', - 'receipt' => ' ', - 'used' => ' ', - 'balanceStock' => ' ', - ]; - - $startTimestamp = strtotime('+1 day', $startTimestamp); // Move to the next day - } - - if (!empty($inserts)) { - $this->resinStockDetails_model->insertBatch($inserts); - } - } - } - + echo "Data Saved Successfully"; + } // Bag Stock details starts - + public function loadView_bagStockDetails() { - if ($this->request->getMethod() === 'POST') { - $month = $this->request->getPost('month'); - - $date = DateTime::createFromFormat('d-M-Y', '01-'.$month); - - $formattedDate = $date->format('Y-m'); - - $month = $formattedDate; - - $session = session (); - - $session->set('stock_month',$month); - - - } else { - - $session = session(); - - $month = $session->get('stock_month'); - - if (empty($month)) { - $month = date('Y-m'); // Default to the current month - } - - } + $month = getStockMonth($this->request); $data = []; @@ -2663,19 +2084,6 @@ class StockController extends BaseController '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); - } } @@ -2697,18 +2105,85 @@ class StockController extends BaseController //possible if no filter applied at all...!!! if(empty($existingCustomMaterialCodes)){ - //no filter applied at all just present all active material codes + + //no filter applied at all just present previous month material codes + + $previousMonth = date('Y-m-01', strtotime('-1 month', strtotime("$month-01"))); + + $previousMonthCustomMachineCodes = $this->monthWiseMaterialInStockModel + ->select('materialCode') + ->where('date',"$previousMonth") + ->where('stock_category','packing_material') + ->get() + ->getResultArray(); + + if(!empty($previousMonthCustomMachineCodes)){ + $existingCustomMaterialCodes = $this->rawmaterialdetails_model + ->getSelectedResinMaterialCode(array_column($previousMonthCustomMachineCodes, 'materialCode')); + }else{ + + // inserting all active if no previous month present $existingCustomMaterialCodes = $this->rawmaterialdetails_model ->getAllBagMaterialCode(); + + //if no filter already exists or removed current one , just add current filter for that month ....!! + $inserts = []; + + foreach($existingCustomMaterialCodes as $index => $customisedMaterialCode){ + + $inserts [] = [ + 'date' => "$month-01", + 'stock_category' => "packing_material", + 'materialCode' => $customisedMaterialCode['MaterialCode'] + ]; + + } + + if(!empty($inserts)){ + //insert all the latest applied filter + $this->monthWiseMaterialInStockModel->insertBatch($inserts) ; + } + + } + + }else{ - //if filter present,get that material codes + //if filter present,get that material codes $existingCustomMaterialCodes = $this->rawmaterialdetails_model ->getSelectedBagMaterialCode(array_column($existingCustomMaterialCodes, 'materialCode')); - } + + + } $materialCodeList = array_column($existingCustomMaterialCodes, 'MaterialCode'); + $currentDate = new DateTime(); + + if($startDate == $currentDate->format('Y-m-01') && $endDate == $currentDate->format('Y-m-t')){ + + foreach($materialCodeList as $index => $materialCode){ + + + //checking filtered material code present in table , if not create dummy one for whole month for current month only + $findMachineCode = $this->bagStockDetails_model + ->where('date >=', $startDate) + ->where('date <=', $endDate) + ->where('materialCode',$materialCode) + ->findAll(); + + + //check any material code is not present in stock table but applied in filter + if(empty($findMachineCode)){ + //create dummy entry for this + $this->createDummyEntryForBag($materialCode,$startDate,$endDate); + } + + } + } + + + $bagMaterials = $existingCustomMaterialCodes ; $data['activeBagMaterials'] = $this->rawmaterialdetails_model->getAllBagMaterialCode(); @@ -2811,17 +2286,60 @@ class StockController extends BaseController // getting customer for creating table headers // checking already existing stock if yes then get customer from the existing stock // if not set customer as '' empty string - + + // Collect all material codes to query in one go + $materialCodes = array_column($bagMaterials, 'MaterialCode'); + + // Get current month customers in bulk + $currentCustomers = $this->bagStockDetails_model + ->select('materialCode, customer') + ->where('date >=', $startDate) + ->where('date <=', $endDate) + ->whereIn('materialCode', $materialCodes) + ->findAll(); + + // Map them as materialCode => customer + $currentCustomerMap = []; + foreach ($currentCustomers as $row) { + $currentCustomerMap[$row['materialCode']] = $row['customer']; + } + + // Get previous month customers in bulk + $previousStartDate = date('Y-m-01', strtotime('-1 month', strtotime($startDate))); + $previousEndDate = date('Y-m-t', strtotime('-1 month', strtotime($startDate))); + + $previousCustomers = $this->bagStockDetails_model + ->select('materialCode, customer') + ->where('date >=', $previousStartDate) + ->where('date <=', $previousEndDate) + ->whereIn('materialCode', $materialCodes) + ->findAll(); + + // Map them as materialCode => customer + $previousCustomerMap = []; + foreach ($previousCustomers as $row) { + $previousCustomerMap[$row['materialCode']] = $row['customer']; + } + + // Now merge this data efficiently foreach ($bagMaterials as $key => $bagMaterial) { $materialCode = $bagMaterial['MaterialCode']; - $bagMaterials[$key]['customers'] = $this->bagStockDetails_model - ->select('customer') - ->where('date >=', $startDate) - ->where('date <=', $endDate) - ->where('materialCode', $materialCode) - ->first()['customer'] ?? ''; + + // First, check in current month + $customer = $currentCustomerMap[$materialCode] ?? ''; + + // If not found or empty/blank, check in previous month + if (trim($customer) === '') { + $customer = $previousCustomerMap[$materialCode] ?? ''; + } + + // Set final customer value + $bagMaterials[$key]['customers'] = $customer; + } + + // Sort each date's materials based on the custom order to set table header th if (!empty($customisedMaterialCodes)) { @@ -2846,6 +2364,8 @@ class StockController extends BaseController } + // dd($bagMaterials); + $bagMaterialcount = count($bagMaterials); @@ -2861,6 +2381,7 @@ class StockController extends BaseController return $this->loadViews("stock/bagStockDetails", $this->global, $data, NULL); } + public function updateBagStockDetails() { @@ -2931,477 +2452,411 @@ class StockController extends BaseController echo "Data Saved Successfully"; } - - - - - public function trpSandUseStockDetails(){ - - if ($this->request->getMethod() === 'POST') { - $month = $this->request->getPost('month'); + public function trpSandUseStockDetails(){ + + + $month = getStockMonth($this->request); - $date = DateTime::createFromFormat('d-M-Y', '01-'.$month); - $formattedDate = $date->format('Y-m'); + $data = []; - $month = $formattedDate; - } else { - $session = session(); + $data['month'] = $month; - $month = $session->get('stock_month'); + $this->global['pageTitle'] = 'Trp Sand Use Stock Details'; + + $startDate = "$month-01"; + $endDate = date("Y-m-t", strtotime($startDate)); + + $data['trpSandUseStockDetails'] = $this->TrpSandUseStock_model + ->where('date >=', $startDate) + ->where('date <=', $endDate) + ->orderBy('date', 'asc') + ->findAll(); + + $date = DateTime::createFromFormat('Y-m-d', $month.'-01'); + + $formattedDate = $date->format('M-Y'); + + $data['month'] = $formattedDate; + + return $this->loadViews("stock/trpSandUseStockDetails", $this->global, $data, NULL); + - if (empty($month)) { - $month = date('Y-m'); // Default to the current month - } } - $data = []; + + public function updateTrpSandUseStockDetails(){ - $data['month'] = $month; + $postData = $this->request->getPost(); - $this->global['pageTitle'] = 'Trp Sand Use Stock Details'; + $updateTrpSandUseStockDetailsData = json_decode($postData['updateTrpSandUseStockDetails'], true); - $startDate = "$month-01"; - $endDate = date("Y-m-t", strtotime($startDate)); - $data['trpSandUseStockDetails'] = $this->TrpSandUseStock_model - ->where('date >=', $startDate) - ->where('date <=', $endDate) - ->orderBy('date', 'asc') - ->findAll(); - - $date = DateTime::createFromFormat('Y-m-d', $month.'-01'); - - $formattedDate = $date->format('M-Y'); - - $data['month'] = $formattedDate; - - return $this->loadViews("stock/trpSandUseStockDetails", $this->global, $data, NULL); - - - } - - public function updateTrpSandUseStockDetails(){ - - $postData = $this->request->getPost(); - - $updateTrpSandUseStockDetailsData = json_decode($postData['updateTrpSandUseStockDetails'], true); - - $updates = []; - - $inserts = []; - - foreach ($updateTrpSandUseStockDetailsData as $data) { - - $data['date'] = DateTime::createFromFormat('d-m-Y', $data['date'])->format('Y-m-d'); - - $date = $data['date']; - - $dbData = [ - 'date' => $data['date'], - 'rough_kgs' => $data['rough_kgs'], - 'fine_kgs' => $data['fine_kgs'], - 'total_kgs' => $data['total_kgs'], - 'customer_name' => $data['customer_name'] - ]; - - $resultExists = $this->TrpSandUseStock_model - ->where('date', $date) - ->first(); - - - if (empty($resultExists)) { - $inserts[] = $dbData; - } else { - $dbData['id'] = $resultExists['id']; - $updates[] = $dbData; - } - } - - if (!empty($inserts)) { - $this->TrpSandUseStock_model->insertBatch($inserts); - } - - if (!empty($updates)) { - - $updateResult = $this->TrpSandUseStock_model->updateBatch($updates, 'id'); - - if ($updateResult === FALSE) { - echo "Error during update"; - } else { - echo "Data Updated Successfully"; - return; - } - } - - echo "Data Saved Successfully"; - } - - - - public function trpProductionDetails(){ - - //filtering month in post request - - if ($this->request->getMethod() === 'POST') { - $month = $this->request->getPost('month'); - - $date = DateTime::createFromFormat('d-M-Y', '01-'.$month); - - $formattedDate = $date->format('Y-m'); - - $month = $formattedDate; - - $session = session (); - - $session->set('stock_month',$month); - - - } else { - - $session = session(); - - //getting month from session if present - $month = $session->get('stock_month'); - - //else current month - if (empty($month)) { - $month = date('Y-m'); // Default to the current month - } - - } - - $data = []; - - $data['month'] = $month; - - $this->global['pageTitle'] = 'Trp production Details'; - - $startDate = "$month-01"; - $endDate = date("Y-m-t", strtotime($startDate)); - - $trpProductionMaintenanceData = $this->TrpProductionMaintenance_model - ->where('date >=', $startDate) - ->where('date <=', $endDate) - ->find(); - - /* - no data found for given month , create dummy data for that month - because trp production involves join with other tables which are entried by other users so it is better to be empty - and create dummy data for that month .else join wont work - */ - - - - if(empty($trpProductionMaintenanceData)){ + $updates = []; $inserts = []; - $inserts = $this->createDummyDataForTrp($startDate, $endDate); + foreach ($updateTrpSandUseStockDetailsData as $data) { - $freshEntry = true ; + $data['date'] = DateTime::createFromFormat('d-m-Y', $data['date'])->format('Y-m-d'); - $this->updateTrpProductionDetails($inserts ,$freshEntry); + $date = $data['date']; - } + $dbData = [ + 'date' => $data['date'], + 'rough_kgs' => $data['rough_kgs'], + 'fine_kgs' => $data['fine_kgs'], + 'total_kgs' => $data['total_kgs'], + 'customer_name' => $data['customer_name'] + ]; + + $resultExists = $this->TrpSandUseStock_model + ->where('date', $date) + ->first(); - - $result = $this->TrpProduction_model->trpProductionDetails($startDate,$endDate); - - $data['trpProductionDetails'] = $result[0] ; - - $data['crsClientList'] = $result[1] ; - - $data['wcsSupplierList'] = $result[2] ; - - - - - - - - $trpAbstract = $this->trpAbstract_model->where('date', $startDate)->findAll(); - - - - $groupedTrpAbstract = [] ; - - foreach($trpAbstract as $abs){ - if(!isset($groupedTrpAbstract[$abs['particulars']])){ - $groupedTrpAbstract[$abs['particulars']] = $abs ; + if (empty($resultExists)) { + $inserts[] = $dbData; + } else { + $dbData['id'] = $resultExists['id']; + $updates[] = $dbData; } - } + } - $trpAbstract = $groupedTrpAbstract ; + if (!empty($inserts)) { + $this->TrpSandUseStock_model->insertBatch($inserts); + } - $data['trpAbstract'] = $trpAbstract ; + if (!empty($updates)) { - // dd( $data['trpAbstract']['Incoming Raw Sand Details'] ); + $updateResult = $this->TrpSandUseStock_model->updateBatch($updates, 'id'); - // dd((int)$trpAbstract["Incoming Raw Sand Details"]['opening_stock']); + if ($updateResult === FALSE) { + echo "Error during update"; + } else { + echo "Data Updated Successfully"; + return; + } + } - $date = DateTime::createFromFormat('Y-m-d', $month.'-01'); - - $formattedDate = $date->format('M-Y'); - - $data['month'] = $formattedDate; - - - - - - return $this->loadViews("stock/trpProductionStockDetails", $this->global, $data, NULL); - - } - - - - - - - public function updateTrpProductionDetails($inserts = null, $freshEntry = false) - { - - //getting values from post request - $postData['updateTrpProductionDetails'] = json_decode($this->request->getPost('updateTrpProductionDetails'),true); - - - - //checking if post data is empty data ? - if (empty($postData['updateTrpProductionDetails'])) { - - //if empty data , we still check for inserts data is available or not - if (empty($inserts)) { - - //if both fails return "no data found" - return $this->response->setJSON(['error' => 'No data found to update']); - - } else { - - //if inserts data is available , then assign to post data - $postData['updateTrpProductionDetails'] = $inserts; - } - } - - $updateTrpProductionDetails = $postData['updateTrpProductionDetails']; - - // Extract all dates from post data - $dates = array_column($updateTrpProductionDetails, 'Date'); - - //format from "d-m-Y" to db "Y-m-d" format - $formattedDates = array_map(fn($date) => $this->convertToDateWithFlexibleFormats($date, ["d-m-Y", "Y-m-d", "m/d/Y", "m-d-Y"], "Y-m-d"), $dates); - - - - // Fetch all existing maintenance , production and waste records for the given formatted dates - - $existingMaintenance = $this->TrpProductionMaintenance_model->whereIn('date', $formattedDates)->findAll(); - - $existingProduction = $this->TrpProduction_model->whereIn('date', $formattedDates)->findAll(); - - $existingWaste = $this->TrpProductionWaste_model->whereIn('date', $formattedDates)->findAll(); - - - //getting list of existing dates of maintenance , production and waste records - - $existingMaintenanceDateList = array_column($existingMaintenance, null, 'date'); - - $existingProductionDateList = array_column($existingProduction, null, 'date'); - - $existingWasteDateList = array_column($existingWaste, null, 'date'); - - - $updateMaintenance = []; - $updateProduction = []; - $updateWaste = []; - - - $insertMaintenance = []; - $insertProduction = []; - $insertWaste = []; - - - foreach ($updateTrpProductionDetails as $data) { - - $date = $this->convertToDateWithFlexibleFormats($data['Date'], ["d-m-Y", "Y-m-d", "m/d/Y", "m-d-Y"], "Y-m-d"); - - // Data arrays - $dbDataTrpMaintenance = [ - 'date' => $date, - 'openingTime' => $data['openingTime'], - 'closingTime' => $data['closingTime'], - 'totalHours' => $data['totalHours'], - 'coldStart' => $data['coldStart'], - 'breakdownHours' => $data['breakdownHours'], - 'burnerFiringHours' => $data['burnerFiringHours'], - 'sandFeedingHours' => $data['sandFeedingHours'], - 'workingPersonEngineers' => $data['workingPersonEngineers'], - 'workingPersonSupervisiors' => $data['workingPersonSupervisiors'], - 'workingPersonOperators' => $data['workingPersonOperators'], - 'rollerDrivers' => $data['rollerDrivers'], - 'natureOfMaintenance' => $data['natureOfMaintenance'], - 'location' => $data['location'], - 'description' => $data['description'] - ]; - - $dbDataTrpProduction = [ - 'date' => $date, - 'gasReceiptBg' => $data['gasReceiptBg'], - 'gasReceiptPg' => $data['gasReceiptPg'], - 'physicalGasConsumption' => $data['physicalGasConsumption'], - 'trpPlusDrierGasConsumption' => $data['trpPlusDrierGasConsumption'], - 'trpPhysicalGasPerTon' => $data['trpPhysicalGasPerTon'], - 'panelGasConsumption' => $data['panelGasConsumption'], - 'panelGasPerTon' => $data['panelGasPerTon'], - 'edRunningHours' => $data['edRunningHours'], - 'edProduction' => $data['edProduction'], - 'edUsage' => $data['edUsage'], - 'trpProduction' => $data['trpProduction'], - 'trpProductionPerHour' => $data['trpProductionPerHour'], - 'waterReceipt' => $data['waterReceipt'], - 'waterConsumption' => $data['waterConsumption'], - 'ebReading' => $data['ebReading'], - 'ebReadingPerUnitTon' => $data['ebReadingPerUnitTon'], - ]; - - $dbDataTrpWaste = [ - 'date' => $date, - 'msSeperation' => $data['msSeperation'], - 'edWaste' => $data['edWaste'], - 'coolerBags' => $data['coolerBags'], - 'edPlus20Waste' => $data['edPlus20Waste'], - 'cycloneWaste' => $data['cycloneWaste'], - ]; - - // Check if data already exists - if (isset($existingMaintenanceDateList[$date])) { - - $dbDataTrpMaintenance['id'] = (int) $existingMaintenanceDateList[$date]['id']; - $updateMaintenance[] = $dbDataTrpMaintenance; - - } else { - - $insertMaintenance[] = $dbDataTrpMaintenance; - - } - - if (isset($existingProductionDateList[$date])) { - - $dbDataTrpProduction['id'] = (int) $existingProductionDateList[$date]['id']; - $updateProduction[] = $dbDataTrpProduction; - - } else { - $insertProduction[] = $dbDataTrpProduction; - } - - if (isset($existingWasteDateList[$date])) { - - $dbDataTrpWaste['id'] = (int) $existingWasteDateList[$date]['id']; - $updateWaste[] = $dbDataTrpWaste; - - } else { - $insertWaste[] = $dbDataTrpWaste; - } - } - - // Start transaction - $this->db->transBegin(); - - try { - - // Insert new records in batch - if (!empty($insertMaintenance)) { - $this->TrpProductionMaintenance_model->insertBatch($insertMaintenance); - } - if (!empty($insertProduction)) { - $this->TrpProduction_model->insertBatch($insertProduction); - } - if (!empty($insertWaste)) { - $this->TrpProductionWaste_model->insertBatch($insertWaste); - } - - - // Update existing records in batch - if (!empty($updateMaintenance)) { - $this->TrpProductionMaintenance_model->updateBatch($updateMaintenance, 'id'); - } - if (!empty($updateProduction)) { - $this->TrpProduction_model->updateBatch($updateProduction, 'id'); - } - if (!empty($updateWaste)) { - $this->TrpProductionWaste_model->updateBatch($updateWaste, 'id'); - } - - // Commit transaction if successful - $this->db->transCommit(); - - if (!$freshEntry) { - echo "Data Saved Successfully"; - } - } catch (\Exception $error) { - // Rollback transaction on error - $this->db->transRollback(); - echo "An error occurred: " . $error->getMessage(); - } - } - - - - - public function updateAbstractDetails() { - - $updateAbstractDetails = json_decode($this->request->getPost('updateAbstractDetails'), true); - - if (empty($updateAbstractDetails)) { - echo "No data received"; - return; + echo "Data Saved Successfully"; } - - - $date = trim($updateAbstractDetails[0]['date']); - - $monthPresent = $this->trpAbstract_model->where('date', $date)->findAll(); - - if ( count($monthPresent) > 1 ) { // Update existing records + + public function trpProductionDetails(){ + + //filtering month in post request + + $month = getStockMonth($this->request); + + $data = []; + + $data['month'] = $month; + + $this->global['pageTitle'] = 'Trp production Details'; + + $startDate = "$month-01"; + $endDate = date("Y-m-t", strtotime($startDate)); + + $trpProductionMaintenanceData = $this->TrpProductionMaintenance_model + ->where('date >=', $startDate) + ->where('date <=', $endDate) + ->find(); + + /* + no data found for given month , create dummy data for that month + because trp production involves join with other tables which are entried by other users so it is better to be empty + and create dummy data for that month .else join wont work + */ + + + + if(empty($trpProductionMaintenanceData)){ + + $inserts = []; + + $inserts = $this->createDummyDataForTrp($startDate, $endDate); + + $freshEntry = true ; + + $this->updateTrpProductionDetails($inserts ,$freshEntry); + + } + + + + $result = $this->TrpProduction_model->trpProductionDetails($startDate,$endDate); + + $data['trpProductionDetails'] = $result[0] ; + + $data['crsClientList'] = $result[1] ; + + $data['wcsSupplierList'] = $result[2] ; - foreach ($updateAbstractDetails as $updateAbstractDetail) { - $this->trpAbstract_model - ->where('date', trim($updateAbstractDetail['date'])) - ->where('particulars', trim($updateAbstractDetail['particulars'])) - ->set($updateAbstractDetail) - ->update(); // Correct update usage + + + + + + $trpAbstract = $this->trpAbstract_model->where('date', $startDate)->findAll(); + + + + $groupedTrpAbstract = [] ; + + foreach($trpAbstract as $abs){ + if(!isset($groupedTrpAbstract[$abs['particulars']])){ + $groupedTrpAbstract[$abs['particulars']] = $abs ; + } + } + + $trpAbstract = $groupedTrpAbstract ; + + $data['trpAbstract'] = $trpAbstract ; + + $date = DateTime::createFromFormat('Y-m-d', $month.'-01'); + + $formattedDate = $date->format('M-Y'); + + $data['month'] = $formattedDate; + + + + + + return $this->loadViews("stock/trpProductionStockDetails", $this->global, $data, NULL); + + } + + + public function updateTrpProductionDetails($inserts = null, $freshEntry = false) + { + + //getting values from post request + $postData['updateTrpProductionDetails'] = json_decode($this->request->getPost('updateTrpProductionDetails'),true); + + + + //checking if post data is empty data ? + if (empty($postData['updateTrpProductionDetails'])) { + + //if empty data , we still check for inserts data is available or not + if (empty($inserts)) { + + //if both fails return "no data found" + return $this->response->setJSON(['error' => 'No data found to update']); + + } else { + + //if inserts data is available , then assign to post data + $postData['updateTrpProductionDetails'] = $inserts; + } + } + + $updateTrpProductionDetails = $postData['updateTrpProductionDetails']; + + // Extract all dates from post data + $dates = array_column($updateTrpProductionDetails, 'Date'); + + //format from "d-m-Y" to db "Y-m-d" format + $formattedDates = array_map(fn($date) => $this->convertToDateWithFlexibleFormats($date, ["d-m-Y", "Y-m-d", "m/d/Y", "m-d-Y"], "Y-m-d"), $dates); + + + + // Fetch all existing maintenance , production and waste records for the given formatted dates + + $existingMaintenance = $this->TrpProductionMaintenance_model->whereIn('date', $formattedDates)->findAll(); + + $existingProduction = $this->TrpProduction_model->whereIn('date', $formattedDates)->findAll(); + + $existingWaste = $this->TrpProductionWaste_model->whereIn('date', $formattedDates)->findAll(); + + + //getting list of existing dates of maintenance , production and waste records + + $existingMaintenanceDateList = array_column($existingMaintenance, null, 'date'); + + $existingProductionDateList = array_column($existingProduction, null, 'date'); + + $existingWasteDateList = array_column($existingWaste, null, 'date'); + + + $updateMaintenance = []; + $updateProduction = []; + $updateWaste = []; + + + $insertMaintenance = []; + $insertProduction = []; + $insertWaste = []; + + + foreach ($updateTrpProductionDetails as $data) { + + $date = $this->convertToDateWithFlexibleFormats($data['Date'], ["d-m-Y", "Y-m-d", "m/d/Y", "m-d-Y"], "Y-m-d"); + + // Data arrays + $dbDataTrpMaintenance = [ + 'date' => $date, + 'openingTime' => $data['openingTime'], + 'closingTime' => $data['closingTime'], + 'totalHours' => $data['totalHours'], + 'coldStart' => $data['coldStart'], + 'breakdownHours' => $data['breakdownHours'], + 'burnerFiringHours' => $data['burnerFiringHours'], + 'sandFeedingHours' => $data['sandFeedingHours'], + 'workingPersonEngineers' => $data['workingPersonEngineers'], + 'workingPersonSupervisiors' => $data['workingPersonSupervisiors'], + 'workingPersonOperators' => $data['workingPersonOperators'], + 'rollerDrivers' => $data['rollerDrivers'], + 'natureOfMaintenance' => $data['natureOfMaintenance'], + 'location' => $data['location'], + 'description' => $data['description'] + ]; + + $dbDataTrpProduction = [ + 'date' => $date, + 'gasReceiptBg' => $data['gasReceiptBg'], + 'gasReceiptPg' => $data['gasReceiptPg'], + 'physicalGasConsumption' => $data['physicalGasConsumption'], + 'drierGasConsumption' => $data['drierGasConsumption'], + 'trpPlusDrierGasConsumption' => $data['trpPlusDrierGasConsumption'], + 'trpPhysicalGasPerTon' => $data['trpPhysicalGasPerTon'], + 'panelGasConsumption' => $data['panelGasConsumption'], + 'panelGasPerTon' => $data['panelGasPerTon'], + 'edRunningHours' => $data['edRunningHours'], + 'edProduction' => $data['edProduction'], + 'edUsage' => $data['edUsage'], + 'trpProduction' => $data['trpProduction'], + 'trpProductionPerHour' => $data['trpProductionPerHour'], + 'waterReceipt' => $data['waterReceipt'], + 'waterConsumption' => $data['waterConsumption'], + 'ebReading' => $data['ebReading'], + 'ebReadingPerUnitTon' => $data['ebReadingPerUnitTon'], + ]; + + $dbDataTrpWaste = [ + 'date' => $date, + 'msSeperation' => $data['msSeperation'], + 'edWaste' => $data['edWaste'], + 'coolerBags' => $data['coolerBags'], + 'edPlus20Waste' => $data['edPlus20Waste'], + 'cycloneWaste' => $data['cycloneWaste'], + ]; + + // Check if data already exists + if (isset($existingMaintenanceDateList[$date])) { + + $dbDataTrpMaintenance['id'] = (int) $existingMaintenanceDateList[$date]['id']; + $updateMaintenance[] = $dbDataTrpMaintenance; + + } else { + + $insertMaintenance[] = $dbDataTrpMaintenance; + + } + + if (isset($existingProductionDateList[$date])) { + + $dbDataTrpProduction['id'] = (int) $existingProductionDateList[$date]['id']; + $updateProduction[] = $dbDataTrpProduction; + + } else { + $insertProduction[] = $dbDataTrpProduction; + } + + if (isset($existingWasteDateList[$date])) { + + $dbDataTrpWaste['id'] = (int) $existingWasteDateList[$date]['id']; + $updateWaste[] = $dbDataTrpWaste; + + } else { + $insertWaste[] = $dbDataTrpWaste; + } + } + + // Start transaction + $this->db->transBegin(); + + try { + + // Insert new records in batch + if (!empty($insertMaintenance)) { + $this->TrpProductionMaintenance_model->insertBatch($insertMaintenance); + } + if (!empty($insertProduction)) { + $this->TrpProduction_model->insertBatch($insertProduction); + } + if (!empty($insertWaste)) { + $this->TrpProductionWaste_model->insertBatch($insertWaste); + } + + + // Update existing records in batch + if (!empty($updateMaintenance)) { + $this->TrpProductionMaintenance_model->updateBatch($updateMaintenance, 'id'); + } + if (!empty($updateProduction)) { + $this->TrpProduction_model->updateBatch($updateProduction, 'id'); + } + if (!empty($updateWaste)) { + $this->TrpProductionWaste_model->updateBatch($updateWaste, 'id'); + } + + // Commit transaction if successful + $this->db->transCommit(); + + if (!$freshEntry) { + echo "Data Saved Successfully"; + } + } catch (\Exception $error) { + // Rollback transaction on error + $this->db->transRollback(); + echo "An error occurred: " . $error->getMessage(); } - $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"; + + + public function updateAbstractDetails() { + + $updateAbstractDetails = json_decode($this->request->getPost('updateAbstractDetails'), true); + + if (empty($updateAbstractDetails)) { + echo "No data received"; + return; + } + + + + $date = trim($updateAbstractDetails[0]['date']); + + $monthPresent = $this->trpAbstract_model->where('date', $date)->findAll(); + + if ( count($monthPresent) > 1 ) { // Update existing records + + + foreach ($updateAbstractDetails as $updateAbstractDetail) { + $this->trpAbstract_model + ->where('date', trim($updateAbstractDetail['date'])) + ->where('particulars', trim($updateAbstractDetail['particulars'])) + ->set($updateAbstractDetail) + ->update(); // Correct update usage + } + $result = true; // Indicate success + } else { // Insert new records + $result = $this->trpAbstract_model->insertBatch($updateAbstractDetails); + } + + if ($result) { + echo "Data Saved Successfully"; + } else { + echo "Error in Submitting the abstract"; + } } - } - + - - - - - - - - - - - - - - - // -------------------------------------------- in class helpers ---------------------------------------------- + // -------------------------------------------- in-house class helpers ---------------------------------------------- public function getMonthDatesFromInput($monthYear) @@ -3440,7 +2895,7 @@ class StockController extends BaseController while ($start <= $end) { $timeValue = date('H:i', $start); // 24-hour format for value - $timeLabel = date('h:i a', $start); // 12-hour format with AM/PM for display + $timeLabel = date('h:i A', $start); // 12-hour format with AM/PM for display $times[$timeValue] = $timeLabel; // Store time in associative array $start = strtotime('+15 minutes', $start); // Increment by 15 minutes } @@ -3448,12 +2903,6 @@ class StockController extends BaseController return $times; } - - - - /** - * Updates gas stock consumption if the value changes. - */ private function handleGasStockUpdate($existingRow, $newRow) { $existingConsumption = $existingRow['total_gas_consumption']; //eg:400 @@ -3465,7 +2914,6 @@ class StockController extends BaseController } } - function convertToDateWithFlexibleFormats($dateInput, array $inputFormats, string $outputFormat): ?string { @@ -3487,7 +2935,6 @@ class StockController extends BaseController return $dateInput; } - public function createDummyEntryForBag($customisedMaterialCode, $startDate, $endDate) { if (!empty($customisedMaterialCode)) { @@ -3515,6 +2962,34 @@ class StockController extends BaseController $this->bagStockDetails_model->insertBatch($inserts); } } + } + public function createDummyEntryForResin($customisedMaterialCode, $startDate, $endDate) + { + if (!empty($customisedMaterialCode)) { + $inserts = []; + + // Convert start and end date to timestamps + $startTimestamp = strtotime($startDate); + $endTimestamp = strtotime($endDate); + + while ($startTimestamp <= $endTimestamp) { + $inserts[] = [ + 'date' => date('Y-m-d', $startTimestamp), // Convert timestamp to date format + 'materialCode' => $customisedMaterialCode, + 'customer' => ' ', + 'opening' => ' ', + 'receipt' => ' ', + 'used' => ' ', + 'balanceStock' => ' ', + ]; + + $startTimestamp = strtotime('+1 day', $startTimestamp); // Move to the next day + } + + if (!empty($inserts)) { + $this->resinStockDetails_model->insertBatch($inserts); + } + } } public function createDummyEntryForDieselMachine($customisedMachineCode, $startDate, $endDate) @@ -3610,6 +3085,7 @@ class StockController extends BaseController 'gasReceiptBg' => " ", 'gasReceiptPg' => " ", 'physicalGasConsumption' => " ", + 'drierGasConsumption' => " ", 'trpPlusDrierGasConsumption' => " ", 'trpPhysicalGasPerTon' => " ", 'panelGasConsumption' => " ", @@ -3634,19 +3110,283 @@ class StockController extends BaseController return $inserts; } + private function updateGasConsumptionOrFail($date, $consumption) + { + $result = $this->updateGasStockConsumption($date, $consumption); + if (!$result) { + throw new \Exception('Failed to update gas stock consumption.'); + } + } + + private function handleGasConsumptionAdjustment($data, &$messages) + { + $existingConsumption = $data['existingTotalGasConsumption']; + $newConsumption = $data['totalGasConsumption']; + + if ($existingConsumption == $newConsumption) { + return; + } + + $change = $newConsumption - $existingConsumption; + $result = $this->updateGasStockConsumption($data['date'], $change); + + if (!$result) { + throw new \Exception('Failed to update gas stock consumption.'); + } + + $messages[] = 'And updated gas stock consumption.'; + $messages[] = 'Warning..!! Kindly Update the next subsequent month Gas Stock If older month Gas Stock Updated..!!'; + } + + private function handleBatchCardUploads($coatingId) + { + $files = $this->request->getFileMultiple('batchCard'); + + if (empty($files) || $files[0]->getError() === UPLOAD_ERR_NO_FILE) { + return; + } + + $uploadPath = WRITEPATH . 'uploads' . DIRECTORY_SEPARATOR . 'batchcard'; + if (!is_dir($uploadPath)) { + mkdir($uploadPath, 0777, true); + } + + $db = \Config\Database::connect(); + $builder = $db->table('t_batchcard_files'); + $inserts = []; + + foreach ($files as $file) { + if (!$file->isValid() || $file->hasMoved()) { + continue; + } + + $clientName = $file->getClientName(); + $newName = $file->getRandomName(); + + if ($file->move($uploadPath, $newName)) { + $inserts [] = [ + 'client_file_name' => $clientName, + 'filename' => $newName, + 'coating_id' => $coatingId + ]; + } + + } - + if(!empty($inserts)){ + $builder->insertBatch($inserts); + } + } + private function getBatchCardFileRecord($id) + { + $db = \Config\Database::connect(); + return $db->table('t_batchcard_files') + ->select('filename') + ->where('id', $id) + ->get() + ->getRow(); + } + private function deleteBatchCardFileFromStorage($filename) + { + $path = WRITEPATH . 'uploads' . DIRECTORY_SEPARATOR . 'batchcard'; + if (!is_dir($path)) { + mkdir($path, 0777, true); + } + + $filePath = $path . DIRECTORY_SEPARATOR . $filename; + if (file_exists($filePath)) { + unlink($filePath); + } + + return 1; + } + + private function deleteBatchCardFileRecord($id) + { + $db = \Config\Database::connect(); + return $db->query("DELETE FROM t_batchcard_files WHERE id = ?", [$id]); + } + + private function respondWithJson($status, $message) + { + return $this->response->setJSON([ + 'status' => (string)$status, + 'message' => $message + ]); + } + + private function getBatchCardFiles($coatingId) + { + $batchCardFiles = $this->db->table('t_batchcard_files') + ->where('coating_id', $coatingId) + ->get() + ->getResultArray(); + + return $batchCardFiles; + } + + private function getPreviousMonthDateRange(string $currentMonth): array + { + $previousMonth = DateTime::createFromFormat('Y-m-d', $currentMonth . '-01') + ->modify('-1 month') + ->format('Y-m'); + + $startDate = "$previousMonth-01"; + $endDate = date("Y-m-t", strtotime($startDate)); + + return [ + 'start' => $startDate, + 'end' => $endDate + ]; + } - - - + private function getOrUpdateCustomisedMachineCodes($month) + { + $filterCodes = $this->request->getPost('customisedMachineCodes') ?? []; + $existingCodes = $this->monthWiseMachineInStockModel + ->select('machine_id') + ->where('date', "$month-01") + ->where('machine_category', 'diesel') + ->findAll(); + + $filterUpdateNeeded = true; + if (empty($filterCodes) && !empty($existingCodes)) { + return array_column($existingCodes, 'machine_id'); + } + + if (!empty($filterCodes) && $filterUpdateNeeded) { + $this->monthWiseMachineInStockModel + ->where('date', "$month-01") + ->where('machine_category', 'diesel') + ->delete(); + + $inserts = array_map(fn($code) => [ + 'date' => "$month-01", + 'machine_category' => "diesel", + 'machine_id' => $code + ], $filterCodes); + + if (!empty($inserts)) { + $this->monthWiseMachineInStockModel->insertBatch($inserts); + } + return $filterCodes; + } + + // If no filter applied at all — fallback to previous month or all active + if (empty($existingCodes)) { + $previousMonth = date('Y-m-01', strtotime('-1 month', strtotime("$month-01"))); + $prevCodes = $this->monthWiseMachineInStockModel + ->select('machine_id') + ->where('date', "$previousMonth") + ->where('machine_category', 'diesel') + ->get() + ->getResultArray(); + + if (!empty($prevCodes)) { + return array_column($prevCodes, 'machine_id'); + } else { + $activeMachines = $this->factoryMachine_model->getAllActiveDieselMachines(); + $inserts = array_map(fn($m) => [ + 'date' => "$month-01", + 'machine_category' => "diesel", + 'machine_id' => $m['id'] + ], $activeMachines); + $this->monthWiseMachineInStockModel->insertBatch($inserts); + return array_column($activeMachines, 'id'); + } + } + + return array_column($existingCodes, 'machine_id'); + } + + private function isCurrentMonth($startDate, $endDate, $currentDate) + { + return $startDate == $currentDate->format('Y-m-01') && $endDate == $currentDate->format('Y-m-t'); + } + + private function ensureDieselDetailsForMonth($machineCodes, $startDate, $endDate) + { + foreach ($machineCodes as $code) { + $exists = $this->factoryVehicleDieselDetails_model + ->where('date >=', $startDate) + ->where('date <=', $endDate) + ->where('machine_id', $code) + ->findAll(); + + if (empty($exists)) { + $this->createDummyEntryForDieselMachine($code, $startDate, $endDate); + } + } + } + + private function getPreviousMonthStockDetails($month) + { + $previousMonth = DateTime::createFromFormat('Y-m-d', "$month-01") + ->modify('-1 month')->format('Y-m'); + $prevStart = "$previousMonth-01"; + $prevEnd = date("Y-m-t", strtotime($prevStart)); + + $details = $this->factoryVehicleDieselDetails_model + ->select(['machine_id', 'date', 'closing_reading']) + ->distinct() + ->where('date =', $prevEnd) + ->groupBy(['machine_id', 'date']) + ->orderBy('date', 'desc') + ->orderBy('machine_id', 'asc') + ->findAll(); + + $totals = $this->factoryVehicleDieselStockSummary_model + ->select(['id', 'date', 'balance_stock']) + ->distinct() + ->where('date =', $prevEnd) + ->groupBy(['id', 'date']) + ->orderBy('date', 'desc') + ->findAll(); + + return [$details, $totals]; + } + + private function groupAndSortStockDetails($details, $customisedOrder) + { + $grouped = []; + foreach ($details as $detail) { + $grouped[$detail['date']][] = $detail; + } + + if (!empty($customisedOrder)) { + foreach ($grouped as &$machines) { + usort($machines, fn($a, $b) => $this->compareByCustomOrder($a, $b, $customisedOrder)); + } + } + + return array_values($grouped); + } + + private function sortMachinesByCustomOrder($machines, $customOrder) + { + usort($machines, fn($a, $b) => $this->compareByCustomOrder($a, $b, $customOrder, 'id')); + return $machines; + } + + private function compareByCustomOrder($a, $b, $order, $key = 'machine_id') + { + $indexA = array_search($a[$key], $order); + $indexB = array_search($b[$key], $order); + + if ($indexA === false && $indexB === false) return 0; + if ($indexA === false) return 1; + if ($indexB === false) return -1; + + return $indexA - $indexB; + } + diff --git a/app/Controllers/User.php b/app/Controllers/User.php index 66466711..2f55a36d 100755 --- a/app/Controllers/User.php +++ b/app/Controllers/User.php @@ -1020,15 +1020,11 @@ class User extends BaseController // Validation passed $EmpID = $this->request->getPost('EmpList'); - $roleId = !empty($this->request->getPost('role')) ? $this->request->getPost('role') : '2' ; + $roleId = $this->request->getPost('role'); $password = (string)$this->request->getPost('password'); $Createddt = date('Y-m-d H:i:s'); $email = $this->request->getPost('MailID'); - $SelectedDepartment = (string)$this->request->getPost('txtSelectedDepartment'); - $comma_separated = explode(':', $SelectedDepartment); - if (count($comma_separated) == 1 && in_array('DEP27', $comma_separated)) { - $roleId = '6'; - } + $userInfo = [ 'email' => $email, 'EmpID' => $EmpID, @@ -1040,16 +1036,7 @@ class User extends BaseController $result = $this->user_model->addNewUser($userInfo); - if ($SelectedDepartment != '') { - foreach ($comma_separated as $DeptCode) { - $userdept = [ - 'EmpID' => $EmpID, - 'Departmentcode' => $DeptCode - ]; - $access = $this->user_model->addAccess($userdept); - } - } - + if ($result > 0) { // return redirect()->to('userListing')->with('success', 'New user created successfully!'); $this->session->setFlashdata('success', 'New user created successfully!'); @@ -1072,6 +1059,27 @@ class User extends BaseController }; } + function isEmailExists(){ + + + $MailID = $this->request->getPost('MailID'); + $empID = $this->request->getPost('EmpID'); + + + if (!$MailID) { + return $this->response->setJSON(['success' => false, 'message' => 'Mail ID not provided']); + } + + $isEmailExists = $this->user_model->isEmailExists($MailID,$empID); + + if ($isEmailExists) { + return $this->response->setJSON(['success' => true, 'message' => 'Email Already Exsiting']); + } else { + return $this->response->setJSON(['success' => false, 'message' => '']); + } + + } + function Deleteuserdepartment() { diff --git a/app/Helpers/excel_helper.php b/app/Helpers/excel_helper.php index c4ab8e73..3ae8c548 100755 --- a/app/Helpers/excel_helper.php +++ b/app/Helpers/excel_helper.php @@ -3,47 +3,412 @@ use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Writer\Xlsx; use PhpOffice\PhpSpreadsheet\IOFactory; use PhpOffice\PhpSpreadsheet\Reader\Exception as SpreadsheetReaderException; +use PhpOffice\PhpSpreadsheet\Cell\Coordinate; +use PhpOffice\PhpSpreadsheet\Style\Alignment; +use PhpOffice\PhpSpreadsheet\Style\Color; +use PhpOffice\PhpSpreadsheet\Style\Font; +use PhpOffice\PhpSpreadsheet\Style\Fill; +use PhpOffice\PhpSpreadsheet\Style\Border; +use PhpOffice\PhpSpreadsheet\Style\Borders; + if (!function_exists('generate_excel')) { - - /* - This function generates an Excel file using the given headers and data and saves it with the specified filename. - It utilizes the PhpSpreadsheet library to create and manipulate Excel files. - - Parameters: - - $headers: An array containing the column headers for the Excel sheet. - - $data: An array containing the data to be inserted into the Excel sheet. - - $filename: The name of the file to be saved. - - $totals (optional): A flag indicating whether to include total calculations in the Excel sheet. - */ - - - function generate_excel($headers, $data, $filename) + + function generate_excel($headlines, $xldata) { + + $headersMain = $headlines['header1']; + $headersSub = $headlines['header2']; + $company = $headlines['company_name']; + $filename = $headlines['file_name']; + $type = $headlines['type']; + $footer = false; + $mergeEndCol = $headlines['merge_end_column']; + // $type = 1 means $data is single + // $type = 2 means $data is multiple array + + // Create new Spreadsheet object $spreadsheet = new Spreadsheet(); + $sheet = $spreadsheet->getActiveSheet(); + + // Set worksheet title + $sheet->setTitle('Sheet 1'); - // Set worksheet title - $spreadsheet->getActiveSheet()->setTitle('Sheet 1'); + + // A1 Start here... should be compnay name .... + $sheet->setCellValue('A1', $company); - // Set headers into the spreadsheet - $spreadsheet->getActiveSheet()->fromArray([$headers], null, 'A1'); + // Get last column letter based on headers count + // $lastColumnLetter = getExcelColumnName(count($headers) - 1); + $colCount = count($headersMain); + + // Calculate end column by character math (works up to 'ZZ') + $lastColumnLetter = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::stringFromColumnIndex($colCount); - // Set data into the spreadsheet - $spreadsheet->getActiveSheet()->fromArray($data, null, 'A2'); + $sheet->mergeCells("A1:{$lastColumnLetter}1"); + // Style A1 + $sheet->getStyle("A1")->getFill() + ->setFillType(Fill::FILL_SOLID) + ->getStartColor()->setRGB('ADD8E6'); // Light blue + $sheet->getStyle("A1")->getAlignment() + ->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER) + ->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER); + + $sheet->getStyle("A1")->getFont()->setBold(true)->setSize(14); + + $sheet->getStyle("A1")->getFont() + ->getColor() + ->setRGB(Color::COLOR_WHITE); + + // /. A1 ends here + $currentRow = 2; // Start at row 2 + if($type == 1){ + $startCell = 'A' . $currentRow; + $lastcolrow = callHeader($sheet, $headersMain, $startCell,$headersSub); + $lastcolrow2 = callSkipRow($lastcolrow); + $lastcolrow3 = callData($sheet,$headersMain,$xldata,$lastcolrow2,$mergeEndCol); + $lastcolrow4 = callSkipRow($lastcolrow3); + if($footer){ + $lastcolrow5 = callFooter($sheet, $headersMain, $xldata, $lastcolrow4,'','',$mergeEndCol); + } + + + }else if($type == 2){ + // $final_Footer=[]; + // foreach($xldata as $i => $xl){ + // echo $i; + // echo "
";
+                //     print_r($xl[$i]);
+                //     echo "
"; + // // echo count($xl[$i])."**"; + // // $forFinalFooter + // } + // foreach ($xldata as $i => $xl) { + // $forFinalFooter[] = $xl[$i]; + // } + $final_Footer = isset($headlines['final_Footer']) && !empty($headlines['final_Footer']) ? $headlines['final_Footer'] : []; + + foreach ($xldata as $index => $data) { + if (!empty($data)) { + $startCell = 'A' . $currentRow; + + $lastcolrow = callHeader($sheet, $headersMain, $startCell,$headersSub); + $lastcolrow2 = callSkipRow($lastcolrow); + $lastcolrow3 = callData($sheet, $headersMain, $data, $lastcolrow2); + $lastcolrow4 = callSkipRow($lastcolrow3); + $lastcolrow5 = callFooter($sheet, $headersMain, $data, $lastcolrow4,'Total Amount Rs','228B22',$mergeEndCol); + $lastcolrow6 = callSkipRow($lastcolrow5); + + // Update currentRow for next iteration + $currentRow = (int) filter_var($lastcolrow6, FILTER_SANITIZE_NUMBER_INT); + } else { + $startCell = 'A' . $currentRow; + $lastcolrow = callHeader($sheet, $headersMain, $startCell,$headersSub); + $lastcolrow2 = callSkipRow($lastcolrow); + + $currentRow = (int) filter_var($lastcolrow2, FILTER_SANITIZE_NUMBER_INT); + } + } + + if(!empty($final_Footer)){ + $startCell = 'A' . $currentRow; + callFooter($sheet, $headersMain, $final_Footer[0], $startCell,'Final Net Salary Amount Rs','DC143C',$mergeEndCol); + // echo "cr".$currentRow;die; + } + + // $final_Footer + + } // Create Excel writer $writer = new Xlsx($spreadsheet); + $columnCount = count($headersMain); + for ($col = 1; $col <= $columnCount; $col++) { + $columnLetter = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::stringFromColumnIndex($col); + $sheet->getColumnDimension($columnLetter)->setAutoSize(true); + } + + $highestColumn = $sheet->getHighestColumn(); // e.g., 'E' + $highestRow = $sheet->getHighestRow(); // e.g., 10 + + // Build the full range (e.g., 'A1:E10') + $range = 'A1:' . $highestColumn . $highestRow; + + // Apply border to that range + $sheet->getStyle($range)->applyFromArray([ + 'borders' => [ + 'allBorders' => [ + 'borderStyle' => Border::BORDER_THIN, + 'color' => ['argb' => 'FF000000'], + ], + ], + ]); try { + // Save Excel file to the specified path - $writer->save($filename); - return true; // Return true if file was successfully saved + ob_clean(); + header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); + header("Content-Disposition: attachment; filename=\"$filename\""); + header('Cache-Control: max-age=0'); + + $writer->save('php://output'); // stream to browser + exit; // Return true if file was successfully saved + } catch (\Exception $e) { // Log or handle the exception return false; // Return false if there was an error saving the file } } } + + +function callHeader($sheet, $headersMain, $startCell, $headersSub = []) { + $rowNumber = (int) filter_var($startCell, FILTER_SANITIZE_NUMBER_INT); + + $startCol = 'A'; + $colCount = count($headersMain); + + // Calculate end column by character math (works up to 'ZZ') + $endCol = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::stringFromColumnIndex($colCount); + + // Check if sub-header has any non-empty value + $hasSubHeader = !empty(array_filter($headersSub, function ($val) { + return trim($val) !== ''; + })); + + // 1. Write Main Header + $sheet->fromArray([$headersMain], null, $startCell); + $mainHeaderRange = "{$startCol}{$rowNumber}:{$endCol}{$rowNumber}"; + + // Style Main Header + $sheet->getStyle($mainHeaderRange)->applyFromArray([ + 'font' => [ + 'bold' => true, + 'color' => ['rgb' => 'FF0000'], + 'size' => 12, + ], + 'alignment' => [ + 'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER, + 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER, + ] + ]); + + if ($hasSubHeader) { + // 2. Write Sub Header + $subHeaderRow = $rowNumber + 1; + $sheet->fromArray([$headersSub], null, "A{$subHeaderRow}"); + + $subHeaderRange = "{$startCol}{$subHeaderRow}:{$endCol}{$subHeaderRow}"; + + + $sheet->getStyle($subHeaderRange)->applyFromArray([ + 'font' => [ + 'bold' => true, + 'color' => ['rgb' => 'FF0000'], + 'size' => 12, + ], + 'alignment' => [ + 'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER, + 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER, + ] + ]); + + return 'A' . ($subHeaderRow + 1); + } else { + return 'A' . ($rowNumber + 1); + } +} + + + +function callData($sheet, $headers, $data, $startCell) { + + $startRow = (int) filter_var($startCell, FILTER_SANITIZE_NUMBER_INT); + $startCol = 'A'; + $sheet->fromArray($data, null, $startCell); + + $dataRowCount = count($data); + $lastDataRow = $startRow + $dataRowCount; + + // $dataColCount = count($headers); + // $lastDataColumn = getExcelColumnName($dataColCount - 1); + // $dataRange = "{$startCol}{$startRow}:{$lastDataColumn}{$lastDataRow}"; + // Set font color to black + // $sheet->getStyle($dataRange)->getFont()->getColor()->setRGB('000000'); + + return 'A' . ($lastDataRow + 1); // return next row +} + +function callSkipRow($startCell){ + $row = (int) filter_var($startCell, FILTER_SANITIZE_NUMBER_INT); + return 'A' . ($row + 1); // just skip a line +} + +// function callFooter($sheet, $headers, $data, $startCell,$mergeEndindex) { + +// $row = (int) filter_var($startCell, FILTER_SANITIZE_NUMBER_INT); + +// $startCol = preg_replace('/[0-9]/', '', $startCell); + +// // Determine numeric columns dynamically +// // $numericIndexes = []; +// // foreach ($data as $index => $val) { +// // foreach ($data as $rowData) { +// // if (isset($rowData[$index]) && is_numeric($rowData[$index])) { +// // $numericIndexes[] = $index; +// // break; +// // } +// // } +// // } +// if (!empty($data)) { +// // Look at the first row +// $firstRow = $data[0]; + +// foreach ($firstRow as $key => $value) { +// foreach ($data as $row) { +// if (isset($row[$key]) && is_numeric($row[$key])) { +// $numericIndexes[] = $key; // use the key (could be column name) +// break; +// } +// } +// } +// } + +// // Get first numeric column index for placing totals +// if (empty($numericIndexes)) return 'A' . ($row + 1); // Nothing to total + +// sort($numericIndexes); +// $firstNumericIndex = $numericIndexes[0]; +// $colCount = count($headers); + +// // Calculate end column by character math (works up to 'ZZ') +// if($mergeEndindex == ''){ +// $mergeEndCol = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::stringFromColumnIndex($colCount - 1); + +// }else{ +// $mergeEndCol = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::stringFromColumnIndex((int)$mergeEndindex); +// } + + + +// // echo gettype($row);die; + +// // Merge from A to column before first numeric column (for "TOTAL" label) +// $sheet->mergeCells("A{$row}:{$mergeEndCol}{$row}"); +// $sheet->setCellValue("A{$row}", 'TOTAL'); + +// // Style for TOTAL label +// $sheet->getStyle("A{$row}:{$mergeEndCol}{$row}")->applyFromArray([ +// 'font' => [ +// 'bold' => true, +// 'size' => 14, +// 'color' => ['rgb' => '228B22'] +// ], +// 'alignment' => [ +// 'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER, +// 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER +// ] +// ]); + +// // Total each numeric column and write to corresponding cell +// foreach ($numericIndexes as $index) { +// $total = 0; +// foreach ($data as $rowData) { +// $value = $rowData[$index] ?? 0; +// if (is_numeric($value)) { +// $total += $value; +// } +// } +// $colLetter = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::stringFromColumnIndex((int)$index); +// $sheet->setCellValue("{$colLetter}{$row}", $total); +// } + +// return 'A' . ($row + 1); // Return next available row +// } +function callFooter($sheet, $headers, $data, $startCell,$label,$code,$mergeEndIndex = null) { + $row = (int) filter_var($startCell, FILTER_SANITIZE_NUMBER_INT); + $startCol = preg_replace('/[0-9]/', '', $startCell); + + $numericKeys = []; + $columnKeys = array_keys($data[0] ?? []); + $columnKeyToIndex = array_flip($columnKeys); // key => index + + // Detect numeric columns + foreach ($columnKeys as $key) { + foreach ($data as $rowData) { + if (isset($rowData[$key]) && is_numeric($rowData[$key])) { + $numericKeys[] = $key; + break; + } + } + } + + // If no numeric columns, skip total row + if (empty($numericKeys)) { + return $startCol . ($row + 1); + } + + // Determine where to end the merge for the TOTAL label + if ($mergeEndIndex === null || $mergeEndIndex === '') { + $firstNumericKey = $numericKeys[0]; + $firstNumericIndex = $columnKeyToIndex[$firstNumericKey]; + $mergeEndIndex = $firstNumericIndex > 0 ? $firstNumericIndex - 1 : 0; + } + + // Write totals for each numeric column + foreach ($numericKeys as $colKey) { + $total = 0; + foreach ($data as $rowData) { + $val = $rowData[$colKey] ?? 0; + if (is_numeric($val)) { + $total += $val; + } + } + + $colIndex = $columnKeyToIndex[$colKey]; + $colLetter = Coordinate::stringFromColumnIndex($colIndex + 1); + $sheet->setCellValue("{$colLetter}{$row}", $total); + $sheet->getStyle("{$colLetter}{$row}")->getNumberFormat()->setFormatCode('#,##0.00'); + $sheet->getStyle("{$colLetter}{$row}")->applyFromArray([ + 'font' => [ + 'bold' => true, + 'size' => 12 + ], + 'alignment' => [ + 'horizontal' => Alignment::HORIZONTAL_CENTER, + 'vertical' => Alignment::VERTICAL_CENTER + ] + ]); + + + } + + + $mergeEndCol = Coordinate::stringFromColumnIndex((int)$mergeEndIndex + 1); + $mergeRange = "{$startCol}{$row}:{$mergeEndCol}{$row}"; + + // Merge cells and write $label name = "TOTAL" + $sheet->mergeCells($mergeRange); + $sheet->setCellValue("{$startCol}{$row}", $label); + + // Style "TOTAL" label + $sheet->getStyle($mergeRange)->applyFromArray([ + 'font' => [ + 'bold' => true, + 'size' => 14, + 'color' => ['rgb' => $code] + ], + 'alignment' => [ + 'horizontal' => Alignment::HORIZONTAL_CENTER, + 'vertical' => Alignment::VERTICAL_CENTER + ] + ]); + + // Return next row cell reference + return $startCol . ($row + 1); +} + diff --git a/app/Helpers/stock_helper.php b/app/Helpers/stock_helper.php new file mode 100644 index 00000000..8d06c888 --- /dev/null +++ b/app/Helpers/stock_helper.php @@ -0,0 +1,32 @@ +getMethod() === 'POST') { + $monthInput = $request->getPost('month'); + $date = DateTime::createFromFormat('d-M-Y', '01-' . $monthInput); + $formattedDate = $date ? $date->format('Y-m') : date('Y-m'); + $session->set('stock_month', $formattedDate); + $month = $formattedDate; + } else { + $month = $session->get('stock_month'); + if (empty($month)) { + $month = date('Y-m'); + } + } + + return $month; +} diff --git a/app/Models/CoatingMachineDetailsModel.php b/app/Models/CoatingMachineDetailsModel.php index 544478ba..0ea772ec 100644 --- a/app/Models/CoatingMachineDetailsModel.php +++ b/app/Models/CoatingMachineDetailsModel.php @@ -45,4 +45,47 @@ class CoatingMachineDetailsModel extends Model protected $afterFind = []; protected $beforeDelete = []; protected $afterDelete = []; + + public function coatingMachineDetails($startDate,$endDate){ + $result = $this->db->table('t_coatingmachinedetails') + ->select('t_coatingmachinedetails.*, + JSON_ARRAYAGG( + JSON_OBJECT( + "client_given_name", t_batchcard_files.client_file_name, + "filename", t_batchcard_files.filename, + "batchCardId" , t_batchcard_files.id, + "coating_id", t_batchcard_files.coating_id + ) + ) as batchcard_files') + ->join('t_batchcard_files', 't_batchcard_files.coating_id = t_coatingmachinedetails.id', 'left') + ->where('t_coatingmachinedetails.date >=', $startDate) + ->where('t_coatingmachinedetails.date <=', $endDate) + ->groupBy('t_coatingmachinedetails.id') + ->orderBy('t_coatingmachinedetails.date', 'asc') + ->get() + ->getResultArray(); + return $result; + } + + public function isShiftExists($date, $shift) + { + $result = $this->db->table('t_coatingmachinedetails') + ->where('date', $date) + ->where('shift', $shift) + ->where('is_active', 1) + ->get() + ->getResultArray(); + + return $result; + + } + + + + + + + + + } diff --git a/app/Models/Config_model.php b/app/Models/Config_model.php index 32e0d7a4..34fb88c8 100755 --- a/app/Models/Config_model.php +++ b/app/Models/Config_model.php @@ -96,10 +96,25 @@ class Config_model extends Model { //echo $ConfigID ;die(); $builder = $this->db->table('t_configmaster COM') - ->select('*') - ->join('t_configdetails con', 'con.Config_ID = COM.Config_ID', 'left') - ->where('COM.Config_ID', $ConfigID) - ->where('con.isActive', $isActiveFilter); + ->select('COM.*, + con.*, + creator_emp.FirstName AS created_by, + updater_emp.FirstName AS updated_by + ') + ->join('t_configdetails con', 'con.Config_ID = COM.Config_ID', 'left') + + // Join for Created By + ->join('tbl_users creator', 'creator.userId = con.created_by', 'left') + ->join('t_employee_details creator_emp', 'creator_emp.EmpID = creator.EmpID', 'left') + // Join for Updated By + ->join('tbl_users updater', 'updater.userId = con.updated_by', 'left') + ->join('t_employee_details updater_emp', 'updater_emp.EmpID = updater.EmpID', 'left') + + ->where('COM.Config_ID', $ConfigID) + ->where('con.isActive', $isActiveFilter) + ->orderBy('con.Key', 'desc'); + + $query = $builder->get(); return $query->getResult(); @@ -288,7 +303,7 @@ return $result; } - public function saveConfigValue($key,$configId, $configValue){ + public function saveConfigValue($key,$configId, $configValue,$userId){ @@ -297,7 +312,8 @@ return $result; ->where('Config_ID', $configId) ->where('key',$key) ->update([ - 'ConfigValue'=> $configValue + 'ConfigValue'=> $configValue, + 'updated_by' => $userId ]); $res = $this->db->affectedRows(); return $res; @@ -308,6 +324,7 @@ return $result; [ 'ConfigValue'=>$configValue, 'Config_ID'=>$configId, + 'created_by'=> $userId, 'isActive'=> 1]); $res = $this->db->affectedRows(); return $res; @@ -320,6 +337,7 @@ return $result; $result = $this->db->table('t_configdetails') ->where('Config_ID','C023') + ->where('isActive',1) ->get() ->getResultArray(); diff --git a/app/Models/Driver_model.php b/app/Models/Driver_model.php index 5fee3b33..3a446d87 100755 --- a/app/Models/Driver_model.php +++ b/app/Models/Driver_model.php @@ -131,12 +131,14 @@ class Driver_model extends Model } function driverAttendanceForMonthlyPayInputs($from,$to){ - // list($year,$month,$date) = explode('-', get_current_date()); + list($year,$month,$date) = explode('-', $from); + $t_driver_monthly_pay_inputs_month_year = "$month-$year"; // $new_date_format = "$year-$month-01"; $builder = $this->db->table('t_driver_attendance') ->select('t_driver_attendance.driver_id,driver_details.FirstName as driver_name,driver_details.is_driver,COUNT(DISTINCT t_driver_attendance.date) AS unique_days, - DATE_FORMAT(date, "%M-%Y") AS month_year,COUNT(t_driver_attendance.load_type) AS no_of_loads,driver_details.*,t_emp_pay_data.PF_Rate,t_emp_pay_data.ESI_Rate') + DATE_FORMAT(date, "%M-%Y") AS month_year,driver_details.*,t_emp_pay_data.PF_Rate,t_emp_pay_data.ESI_Rate, + COUNT(t_driver_attendance.load_type) AS no_of_loads') ->select('SUM(t_driver_attendance.salary_amount) as monthly_salary_amount, SUM(t_driver_attendance.food_amount) as monthly_food_amount, diesel_amount,shed_amount,CONCAT_WS(" ", driver_details.FirstName, driver_details.LastName) AS FullName') @@ -145,18 +147,21 @@ class Driver_model extends Model ->join('t_emp_pay_data','t_emp_pay_data.EmpID=driver_details.EmpID','Left') ->join('t_loan_master','t_loan_master.EmpID = driver_details.EmpID and t_loan_master.Remaining_Due != 0','Left') ->join('t_loan_history','t_loan_history.Loan_ID = t_loan_master.Loan_ID','Left') - ->join('t_driver_monthly_pay_inputs','t_driver_monthly_pay_inputs.driver_id = driver_details.EmpID','Left') + ->join('t_driver_monthly_pay_inputs', + 't_driver_monthly_pay_inputs.driver_id = driver_details.EmpID AND + t_driver_monthly_pay_inputs.month_year = "'.$t_driver_monthly_pay_inputs_month_year.'"', + 'left' + ) ->where('t_driver_attendance.date BETWEEN "'.$from.'" AND "'.$to.'"') // ->where("t_loan_master.Due_Start_Date", $new_date_format) ->groupBy('DATE_FORMAT(t_driver_attendance.date, "%M-%Y"),t_driver_attendance.driver_id'); $query = $builder->get(); // $last_query = $this->db->getLastQuery(); - // echo $last_query;die; + // echo $last_query; return $query->getResult(); } - function driverMonthlyPayInputs($monthYear){ $builder = $this->db->table('t_driver_monthly_pay_inputs'); @@ -221,7 +226,8 @@ class Driver_model extends Model ->where('DATE_FORMAT(`t_driver_attendance`.`date`, "%Y-%m")',$monthyear) ->where('t_driver_attendance.driver_id',$input_driver_id); $query = $builder->get()->getRow(); - // $last_query = $this->db->getLastQuery(); + // $last_query = $this->db->getLastQuery(); + // echo $last_query;die; return $query; } function getPayOn() @@ -317,13 +323,14 @@ 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('t_emp_pay_data.PF_Rate,t_emp_pay_data.ESI_Rate,COUNT(t_driver_attendance.load_type) AS no_of_load') ->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') ->join('t_emp_pay_data','t_emp_pay_data.EmpID=Emp.EmpID','Left') - ->join('t_driver_monthly_pay_inputs month', 'month.driver_id = Emp.EmpID'); + ->join('t_driver_monthly_pay_inputs month', 'month.driver_id = Emp.EmpID') + ->join('t_driver_attendance','t_driver_attendance.driver_id = Emp.EmpID'); if ($PayOn != '') { $builder->where('Pay.PayOn', $PayOn); } diff --git a/app/Models/Employeedetails_model.php b/app/Models/Employeedetails_model.php index 2ad3d0e7..fd8e6aa6 100755 --- a/app/Models/Employeedetails_model.php +++ b/app/Models/Employeedetails_model.php @@ -256,13 +256,18 @@ class Employeedetails_model extends Model function export_excel() { - $builder = $this->db->table('t_employee_details as det') - ->select(' det.*,Dep.DepartmentName as DepartmentName,det.firstname,emp1.firstname as UpdatedByName,emp1.firstname as CreatedByName') - ->join('t_departmentdetails Dep', 'det.Departmentcode = Dep.DEPCode', 'left') - ->join('tbl_users as tbl', ' det.createdby = tbl.userid', 'left') + $builder = $this->db->table('t_employee_details as ed') + ->select('CONCAT_WS(" ", ed.FirstName, ed.LastName) as Name, ed.*,Dep.DepartmentName as DepartmentName,CONCAT_WS(" ", emp1.FirstName, emp1.LastName) as UpdatedByName,CONCAT_WS(" ", emp.FirstName, emp.LastName) as CreatedByName') + ->select('t_emp_pay_data.Pay_Data_ID,t_emp_pay_data.EmpID,t_emp_pay_data.Basic_Pay,t_emp_pay_data.HRA_Rate,t_emp_pay_data.Allowances,t_emp_pay_data.Food_Allowances,t_emp_pay_data.Incentives,t_emp_pay_data.PF_Rate,t_emp_pay_data.ESI_Rate,t_emp_pay_data.HRA_Amount,t_emp_pay_data.TotalSalary') + ->join('t_departmentdetails Dep', 'ed.Departmentcode = Dep.DEPCode', 'left') + ->join('tbl_users as tbl', ' ed.createdby = tbl.userid', 'left') ->join('t_employee_details as emp', 'emp.empid=tbl.empid', 'left') - ->join('tbl_users as tbl1', ' det.UpdatedBy = tbl1.userid', 'left') - ->join('t_employee_details as emp1', 'emp1.empid=tbl1.empid', 'left'); + ->join('tbl_users as tbl1', ' ed.UpdatedBy = tbl1.userid', 'left') + ->join('t_employee_details as emp1', 'emp1.empid=tbl1.empid', 'left') + ->join('t_emp_pay_data', 'ed.EmpID=t_emp_pay_data.EmpID', 'left') + ->groupBy('ed.EmpID'); + return $builder->get()->getResultArray(); + } } diff --git a/app/Models/Emppaydate_model.php b/app/Models/Emppaydate_model.php index 3a185c4d..b31e7bec 100755 --- a/app/Models/Emppaydate_model.php +++ b/app/Models/Emppaydate_model.php @@ -68,7 +68,7 @@ class Emppaydate_model extends Model } function getUserInfo($paydataid) { - $sql = 'select t_emp_pay_data.Pay_Data_ID,t_emp_pay_data.EmpID as PAYEMPID,t_emp_pay_data.Basic_Pay,t_emp_pay_data.HRA_Rate,t_emp_pay_data.Allowances,t_emp_pay_data.Food_Allowances,t_emp_pay_data.Incentives,t_emp_pay_data.PF_Rate,t_emp_pay_data.ESI_Rate,t_emp_pay_data.HRA_Amount,t_emp_pay_data.TotalSalary,t_employee_details.FirstName,t_employee_details.LastName,t_loan_master.*from t_emp_pay_data + $sql = 'select t_emp_pay_data.Pay_Data_ID,t_emp_pay_data.EmpID as PAYEMPID,t_emp_pay_data.Basic_Pay,t_emp_pay_data.HRA_Rate,t_emp_pay_data.Allowances,t_emp_pay_data.Food_Allowances,t_emp_pay_data.Incentives,t_emp_pay_data.PF_Rate,t_emp_pay_data.ESI_Rate,t_emp_pay_data.HRA_Amount,t_emp_pay_data.TotalSalary,t_employee_details.FirstName,t_employee_details.LastName,t_employee_details.is_driver,t_loan_master.*from t_emp_pay_data join t_employee_details on t_emp_pay_data.EmpID=t_employee_details.EmpID left join t_loan_master on t_emp_pay_data.EmpID=t_loan_master.EmpID and t_loan_master.is_Active = 1 where t_emp_pay_data.Pay_Data_ID = ?;'; @@ -76,6 +76,23 @@ class Emppaydate_model extends Model return $query->getResult(); } + + function driverPayInfo($EmpID,$monthYear){ + + $builder = $this->db->table('t_driver_monthly_pay_inputs'); + $builder->select('t_driver_monthly_pay_inputs.*, t_driver_payroll.id as payroll_id'); + $builder->join('t_driver_payroll', 't_driver_payroll.driver_id = t_driver_monthly_pay_inputs.driver_id', 'left'); + $builder->where('t_driver_monthly_pay_inputs.driver_id', $EmpID); + $builder->where('t_driver_monthly_pay_inputs.month_year', $monthYear); + $builder->groupBy('t_driver_monthly_pay_inputs.driver_id, t_driver_monthly_pay_inputs.month_year'); + + $query = $builder->get(); + $result = $query->getResult(); + + return $result; + + } + function getUserLoanHistoryInfo($loan_id) { $sql = 'select * from t_loan_history where Loan_ID = ?;'; diff --git a/app/Models/GasStockModel.php b/app/Models/GasStockModel.php index 259807ce..d4cb1c2e 100644 --- a/app/Models/GasStockModel.php +++ b/app/Models/GasStockModel.php @@ -45,4 +45,57 @@ class GasStockModel extends Model protected $afterFind = []; protected $beforeDelete = []; protected $afterDelete = []; + + + public function gasStockDetails($startDate,$endDate){ + + $result = $this->db->table('t_gasstockdetails') + + ->select( + 't_gasstockdetails.*, + drier_summary.drierMachineGasconsumption AS drierMachineGasConsumption, + drier_summary.driedSand AS sandDried, + coating_summary.coatingMachineGasconsumption, + coating_summary.coatedSand' + ) + // Subquery with early date filtering + ->join( + '(SELECT date, + SUM(totalGasconsumption) AS coatingMachineGasconsumption, + SUM(totalCoatingSandInKg) AS coatedSand + FROM t_coatingmachinedetails + WHERE is_active = 1 + AND date >= ' . $this->db->escape($startDate) . ' + AND date <= ' . $this->db->escape($endDate) . ' + GROUP BY date + ) AS coating_summary', + 'coating_summary.date = t_gasstockdetails.date', + 'left' + ) + ->join( + '(SELECT date, + SUM(total_gas_consumption) AS drierMachineGasconsumption, + SUM(sand_dried_qty) AS driedSand + FROM t_driermachinedetails + WHERE date >= ' . $this->db->escape($startDate) . ' + AND date <= ' . $this->db->escape($endDate) . ' + GROUP BY date + ) AS drier_summary', + 'drier_summary.date = t_gasstockdetails.date', + 'left' + ) + + ->where('t_gasstockdetails.date >=', $startDate) + ->where('t_gasstockdetails.date <=', $endDate) + ->groupBy('t_gasstockdetails.date') + ->get() + ->getResultArray(); + + return $result; + + } + + + + } diff --git a/app/Models/Inwardgateregister_model.php b/app/Models/Inwardgateregister_model.php index c162bb3a..db7dbb13 100755 --- a/app/Models/Inwardgateregister_model.php +++ b/app/Models/Inwardgateregister_model.php @@ -195,7 +195,7 @@ class Inwardgateregister_model extends Model function viewpurchaseorder($PO) { - $subQuery = 'SELECT distinct POM.PONO, POL.MaterialCode, POL.Quantity, POL.ReceivedQuantity, (POL.Quantity - POL.ReceivedQuantity) as PendingQty, QuantityRejected, POL.PONO, MM.MaterialName, MM.UOM,POL.Rate + $subQuery = 'SELECT distinct POM.PONO, POL.MaterialCode, POL.Quantity, POL.ReceivedQuantity, (POL.Quantity - POL.ReceivedQuantity) as PendingQty, QuantityRejected, POL.PONO, MM.MaterialName, MM.UOM,MM.HSNCODE,POL.Rate FROM t_purchaseorder_master POM LEFT JOIN t_purchaseorder_lineitem POL ON POL.PONO = POM.PONO LEFT JOIN t_igr_master IGM ON IGM.PONO = POL.PONO @@ -568,7 +568,7 @@ class Inwardgateregister_model extends Model ->distinct() ->select(" igr.IGRNO,igr.*,igrd.*, - MM.MaterialName,MM.UOM, + MM.MaterialName,MM.UOM,MM.HSNCODE, sup.Address,sup.SupplierName, POL.Rate, POM.ServiceDescription,POL.Quantity,POM.POType,POM.IsOpenOrder, @@ -1515,4 +1515,41 @@ class Inwardgateregister_model extends Model return $result; } + + public function gasCylindersByIgr($IGRNO, $gasMaterialCodes) { + + $builder = $this->db->table('t_igr_master as t_igrm') + ->select(" + t_igrm.IGRNO, + tgsd.fullCylinderDate, + tgsd.cylinderNo, + tgsd.grossWeight, + tgsd.emptyCylinderDate, + tgsd.tareWeight, + tgsd.netWeight, + tgsd.actualWeight, + tgsd.shortage, + tgsd.invoiceNo, + t_igrm.DeliveryChellanDate, + t_igrm.DriverName, + t_igrm.VehicleNo + + ") + + ->join('t_igr_details tigrd', 'tigrd.IGRNO = t_igrm.IGRNO') + ->join('t_purchaseorder_master tpom', 'tpom.PONO = t_igrm.PONO', 'left') + ->join('t_supplierdetailsn tsd', 'tsd.SupplierID = tpom.SupplierID') + ->join('t_gasshortagedetails tgsd', 'tgsd.IGRNO = t_igrm.IGRNO', 'left') + + ->whereIn('tigrd.MaterialCode', $gasMaterialCodes) + ->where("DATE(tigrd.CreatedDate) >= '2025-04-01'") + ->where('tgsd.gas_cylinder_status', 'gas_returned') + ->where('t_igrm.IGRNO', $IGRNO); // Direct where clause on IGRNO in master table + + $result = $builder->get()->getResultArray(); + + return $result; + } + + } diff --git a/app/Models/Monthlypay_model.php b/app/Models/Monthlypay_model.php index 929a7d1f..3a6548ab 100755 --- a/app/Models/Monthlypay_model.php +++ b/app/Models/Monthlypay_model.php @@ -103,7 +103,7 @@ class Monthlypay_model extends Model //echo $lastdate; //left join t_payroll on t_employee_details.EmpID = t_payroll.EmpID and month(t_payroll.PayOn) = month(?) and year(t_payroll.PayOn) = year(?) - $sql = "select t_emp_pay_data.EmpID,t_emp_pay_data.*,t_employee_details.FirstName,t_employee_details.DateofJoining,t_employee_details.Designation,t_employee_details.esi_applicable,t_employee_details.pf_applicable,t_employee_details.is_management_team,t_attendance.Days_Worked as Days_worked,t_attendance.Absent as LOP_Days,t_attendance.Paid_Leave as Paid_leave,t_attendance.Total_OTHrs as OT_Hrs_Worked,t_attendance.NoofDays,t_attendance.sunday_count,t_loan_master.Loan_ID,t_loan_master.Monthly_Due,t_loan_master.Due_Start_Date as DueDate,t_loan_master.Loan_Amount,t_loan_master.Paid_Amount,t_payroll.Id,t_monthly_pay_inputs.Loan_Recovered,t_monthly_pay_inputs.Estimate,t_monthly_pay_inputs.Festival_Bonus,t_monthly_pay_inputs.Other_Deductions,t_monthly_pay_inputs.is_payslip_generated,t_loan_history .Balance_Amount,t_employee_details.is_driver + $sql = "select t_emp_pay_data.EmpID,t_emp_pay_data.*,t_employee_details.work_location,t_employee_details.tds_applicable,t_employee_details.FirstName,t_employee_details.DateofJoining,t_employee_details.Designation,t_employee_details.esi_applicable,t_employee_details.pf_applicable,t_employee_details.is_management_team,t_attendance.Days_Worked as Days_worked,t_attendance.Absent as LOP_Days,t_attendance.Paid_Leave as Paid_leave,t_attendance.Total_OTHrs as OT_Hrs_Worked,t_attendance.NoofDays,t_attendance.sunday_count,t_loan_master.Loan_ID,t_loan_master.Monthly_Due,t_loan_master.Due_Start_Date as DueDate,t_loan_master.Loan_Amount,t_loan_master.Paid_Amount,t_payroll.Id,t_monthly_pay_inputs.Loan_Recovered,t_monthly_pay_inputs.Estimate,t_monthly_pay_inputs.Festival_Bonus,t_monthly_pay_inputs.Other_Deductions,t_monthly_pay_inputs.is_payslip_generated,t_loan_history .Balance_Amount,t_employee_details.is_driver from t_emp_pay_data left join t_employee_details on t_employee_details.EmpID = t_emp_pay_data.EmpID left join t_payroll on t_employee_details.EmpID = t_payroll.EmpID and t_payroll.PayOn = ? @@ -119,7 +119,7 @@ class Monthlypay_model extends Model $query = $this->db->query($sql, array($month, $month, $lastdate, $current, $current)); // Get the last executed query // $last_query = $this->db->getLastQuery(); - // echo $last_query; + // echo $last_query;die; return $query->getResult(); } diff --git a/app/Models/Purchaseorder_model.php b/app/Models/Purchaseorder_model.php index 8ce9adcd..82deffbd 100755 --- a/app/Models/Purchaseorder_model.php +++ b/app/Models/Purchaseorder_model.php @@ -1096,7 +1096,7 @@ mstr.CourierNo,pom.Status,pom.POType') //,bill.BillNo,bill.FilePath, { $subQuery = 'SELECT distinct LineItem.LineitemAuditorNotes,LineItem.LineItemNo,LineItem.ReqNo,LineItem.Per,Mat.MaterialCode,Mat.MaterialName,Mat.UOM,LineItem.Quantity,ReceivedQuantity,Rate,LineItem.Status,(LineItem.Quantity *Rate) as BasicValue ,(After_CGST + After_SGST + After_IGST) as Taxamount,Dept.DepartmentName - ,TotalValue,CGST,After_CGST,SGST,After_SGST,IGST,After_IGST,otherallowance,LineItem.CostCenterCode,LineItem.ServiceFrequency,LineItem.ServiceMaterialDescription,Req.Schedule_Type,Req.NumberOfService,Req.Service_Period,ReqDet.MaterialDescription + ,TotalValue,CGST,After_CGST,SGST,After_SGST,IGST,After_IGST,otherallowance,LineItem.CostCenterCode,LineItem.ServiceFrequency,LineItem.ServiceMaterialDescription,Req.Schedule_Type,Req.NumberOfService,Req.Service_Period,ReqDet.MaterialDescription,Mat.HSNCODE FROM t_purchaseorder_lineitem LineItem left join t_materialmaster Mat on Mat.MaterialCode = LineItem.MaterialCode left join t_service_tax Tax on Tax.LineItemNo = LineItem.LineItemNo @@ -1142,7 +1142,7 @@ mstr.CourierNo,pom.Status,pom.POType') //,bill.BillNo,bill.FilePath, { $subQuery = 'SELECT distinct LineItem.LineitemAuditorNotes,LineItem.LineItemNo,Req.ReqNo,Mat.MaterialCode,Mat.MaterialName,Mat.UOM,Quantity,Per,ServiceMaterialDescription,ReceivedQuantity,Rate,Req.Status,(Quantity *Rate) as BasicValue , (( AfterSGST + AfterCGST + - AfterIGST )) as Taxamount ,TotalValue,Tax.*,Req.CostCenterCode,Dept.DepartmentName,LineItem.LineitemAuditorNotes + AfterIGST )) as Taxamount ,TotalValue,Tax.*,Req.CostCenterCode,Dept.DepartmentName,LineItem.LineitemAuditorNotes,Mat.HSNCODE FROM t_purchaseorder_lineitem LineItem join t_materialmaster Mat on Mat.MaterialCode = LineItem.MaterialCode left join t_revenue_tax Tax on Tax.LineItemNo = LineItem.LineItemNo @@ -1337,7 +1337,7 @@ mstr.CourierNo,pom.Status,pom.POType') //,bill.BillNo,bill.FilePath, ExciseDutySHCess, AfterCustomEdCess, ROUND((Quantity * Rate), 2) AS TotalOrderValue, ROUND((POMast.ExchangeRate * BasicPriceInMTon), 2) AS BasicINRValue, TotalValue, CurrencyType, ReceivedQuantity, Tax.*, LineItem.ServiceMaterialDescription, Req.CostCenterCode, - Dept.DepartmentName + Dept.DepartmentName,Mat.HSNCODE FROM t_purchaseorder_lineitem LineItem LEFT JOIN t_purchaseorder_master POMast ON POMast.PONO = LineItem.PONO @@ -1743,7 +1743,7 @@ mstr.CourierNo,pom.Status,pom.POType') //,bill.BillNo,bill.FilePath, $subQuery = 'SELECT distinct LineItem.LineItemNo,LineItem.Per,LineItem.ServiceMaterialDescription,Req.ReqNo,Mat.MaterialCode,Mat.MaterialName,LineItem.ServiceMaterialDescription,LineItem.ServiceFrequency, Mat.UOM,Quantity,ReceivedQuantity,Rate,Req.Status,Tax.*, ROUND((RMCIncludingCustomersPerKG*Quantity),2)as Taxamount,LandingCharge,HighSeasSalesCharge,CustomDuty,ExciseDuty,ExciseDutyEdCess,CustomEdCess,POMast.ExchangeRate,POMast.ExchangeRateCalculatedon,POMast.TotalOrderValue as BasicValue,POMast.CapitalRange,AfterLandingCharge,AfterHighSeasSalesCharge,AfterCustomDuty,AfterExciseDuty,AfterExciseDutyEdCess,AddlExciseDuty,AfterAddlExciseDuty,Grossdutypayable,AvailableModvat,Grossexpensesduetocustomduty,purchaseratePerKG,CustomDutyExpensesPerKG,RMCIncludingCustomersPerKG,QuantityKG,BasicPriceInMTon,ProductPrice,CustomSHCess,AfterCustomSHCess,AfterExciseDutySHCess,ExciseDutySHCess,AfterCustomEdCess,ROUND((POMast.ExchangeRate*BasicPriceInMTon*Quantity),2) as BasicINRValue,Tax.TotalValue as ImportTotalValue,Tax.FreightType,Tax.NoOfTrip,Tax.FreightValue,Tax.AfterFreightValue,POMast.CurrencyType, - LineItem.LineitemAuditorNotes, + LineItem.LineitemAuditorNotes,Mat.HSNCODE, Req.CostCenterCode,Dept.DepartmentName FROM t_purchaseorder_lineitem LineItem join t_purchaseorder_master POMast on POMast.PONO = LineItem.PONO join t_materialmaster Mat on Mat.MaterialCode = LineItem.MaterialCode @@ -1802,7 +1802,7 @@ mstr.CourierNo,pom.Status,pom.POType') //,bill.BillNo,bill.FilePath, Mat.UOM,Quantity,ReceivedQuantity,Rate,Req.Status,ROUND((ServiceTax.After_CGST + ServiceTax.After_SGST + ServiceTax.After_IGST),2) as ServiceTaxamount ,ServiceTax.TotalValue,ServiceTax.CGST,ServiceTax.After_CGST,ServiceTax.SGST,ServiceTax.After_SGST,ServiceTax.IGST,ServiceTax.After_IGST,ServiceTax.otherallowance,ServiceTax.discount,ServiceTax.discountval,ServiceTax.Afterdiscountval, POMast.ExchangeRate,POMast.ExchangeRateCalculatedon,POMast.TotalOrderValue as BasicValue,POMast.CapitalRange,ROUND((POMast.TotalOrderValue),2) as BasicINRValue,POMast.CurrencyType,FreightType as Ftype,NoOfTrip as NoTrip,FreightValue as Fvalue,AfterFreightValue as Afvalue, - LineItem.LineitemAuditorNotes, + LineItem.LineitemAuditorNotes,Mat.HSNCODE, Req.CostCenterCode,Dept.DepartmentName FROM t_purchaseorder_lineitem LineItem join t_purchaseorder_master POMast on POMast.PONO = LineItem.PONO join t_materialmaster Mat on Mat.MaterialCode = LineItem.MaterialCode diff --git a/app/Models/Rawmaterialdetails_model.php b/app/Models/Rawmaterialdetails_model.php index 51e60c69..469884c6 100755 --- a/app/Models/Rawmaterialdetails_model.php +++ b/app/Models/Rawmaterialdetails_model.php @@ -74,16 +74,16 @@ class Rawmaterialdetails_model extends Model } //This function used to get the material category using configdetails table - function getmaterialCategory($MaterialCategory = '') + function getmaterialCategory() { $Config_ID = 'C023'; $builder = $this->db->table('t_configdetails') ->select('Key,Config_ID,ConfigValue') ->where('isActive', 1) ->where('Config_id', $Config_ID); - if ($MaterialCategory != '') { - $builder->where('ConfigValue !=', $MaterialCategory); - } + // if ($MaterialCategory != '') { + // $builder->where('ConfigValue !=', $MaterialCategory); + // } $query = $builder->get(); return $query->getResult(); @@ -143,6 +143,7 @@ class Rawmaterialdetails_model extends Model return $query->getResult(); } + function getAllSilicaRawMaterialCode(){ $builder = $this->db->table('t_materialmaster') @@ -444,7 +445,7 @@ where (CurrentStock+OpeningStock)db->table('t_materialmaster MM') - ->select('MM.MaterialCode,MM.MaterialName,MM.MaterialType,MM.Category,MM.IsActive,MM.UOM') + ->select('MM.MaterialCode,MM.MaterialName,MM.MaterialType,MM.Category,MM.IsActive,MM.UOM,MM.HSNCODE') ->where('MM.Category' , $configKey); $query = $builder->get(); diff --git a/app/Models/Requistion_model.php b/app/Models/Requistion_model.php index e4cfd50b..7bd246fb 100755 --- a/app/Models/Requistion_model.php +++ b/app/Models/Requistion_model.php @@ -155,7 +155,7 @@ class Requistion_model extends Model // This function also called in store req. also $reqType not removed..... function EditMaterialCode($ReqNo, $ReqType = NULL){ - $subQuery = 'SELECT Mat.MaterialCode, Mat.MaterialName, Mat.UOM FROM t_materialmaster Mat + $subQuery = 'SELECT Mat.MaterialCode, Mat.MaterialName, Mat.UOM,Mat.HSNCODE FROM t_materialmaster Mat WHERE Mat.MaterialCode NOT IN ( SELECT Req.MaterialCode FROM t_requestion_details Req JOIN t_requestion_master mast ON Req.ReqNo = mast.ReqNo @@ -175,7 +175,7 @@ class Requistion_model extends Model function GetMaterialCode($ReqType,$NotArray='') { $builder = $this->db->table('t_materialmaster') - ->select('MaterialCode, MaterialName,UOM,material_rate') + ->select('MaterialCode, MaterialName,UOM,material_rate,HSNCODE') ->where('IsActive',1); //->where('MaterialType',$ReqType ); @@ -190,6 +190,7 @@ class Requistion_model extends Model return $query->getResult(); } } + /** * This function is used to get the Raw Material information * @return array $result : This is result of the query @@ -197,7 +198,7 @@ class Requistion_model extends Model function getRawMaterialList($MaterialCode) { $builder = $this->db->table('t_materialmaster MM') - ->select('MM.MaterialName,MM.UOM,MM.Category,CD.ConfigValue as CategoryName') + ->select('MM.MaterialName,MM.UOM,MM.Category,CD.ConfigValue as CategoryName,MM.HSNCODE') ->join('t_configdetails CD', 'CD.Key = MM.Category', 'left') ->where('MM.MaterialCode',$MaterialCode ); $query = $builder->get(); @@ -587,13 +588,24 @@ class Requistion_model extends Model function getCategoryName($materialCode){ $subQuery ='SELECT MM.MaterialCode,MM.MaterialName,MM.MaterialType,MM.Category,MM.IsActive,CD.ConfigValue from t_materialmaster as MM - left join t_configdetails as CD on CD.Key = MM.Category + left join t_configdetails as CD on CD.Key = MM.Category where MM.MaterialCode = '.$materialCode; $categoryName = $this->db->query($subQuery)->getRow()->ConfigValue; return $categoryName; } + function getmaterialCategory() + { + $Config_ID = 'C023'; + $builder = $this->db->table('t_configdetails') + ->select('Key,Config_ID,ConfigValue') + ->where('isActive', 1) + ->where('Config_id', $Config_ID); + $query = $builder->get(); + return $query->getResultArray(); + } + } \ No newline at end of file diff --git a/app/Models/TrpProductionModel.php b/app/Models/TrpProductionModel.php index 8b8366ae..b7fb0551 100644 --- a/app/Models/TrpProductionModel.php +++ b/app/Models/TrpProductionModel.php @@ -13,7 +13,8 @@ class TrpProductionModel extends Model protected $returnType = 'array'; protected $useSoftDeletes = false; protected $protectFields = true; - protected $allowedFields = ['id','date', 'gasReceiptBg', 'gasReceiptPg', 'physicalGasConsumption', 'trpPlusDrierGasConsumption', + protected $allowedFields = ['id','date', 'gasReceiptBg', 'gasReceiptPg', 'physicalGasConsumption', + 'drierGasConsumption','trpPlusDrierGasConsumption', 'trpPhysicalGasPerTon', 'panelGasConsumption','panelGasPerTon','edRunningHours','edProduction','edUsage', 'trpProduction', 'trpProductionPerHour', 'waterReceipt', 'waterConsumption' ,'ebReading', 'ebReadingPerUnitTon']; @@ -88,8 +89,8 @@ class TrpProductionModel extends Model tpd.physicalGasConsumption, - IFNULL(tdmd.totalGasConsumption, 0) AS drierGasConsumption, IFNULL(tcmd.totalGasConsumption, 0) AS coatingGasConsumption, + tpd.drierGasConsumption As drierGasConsumption, tpd.trpPlusDrierGasConsumption, tpd.trpPhysicalGasPerTon, tpd.panelGasConsumption, @@ -143,13 +144,15 @@ class TrpProductionModel extends Model $builder->join("({$subquery1}) tcmd", 'tcmd.date = tpmd.date', 'left'); - // Subquery: Drier Machine Gas Consumption - $subquery2 = $this->db->table('t_driermachinedetails') - ->select('date, SUM(total_gas_consumption) AS totalGasConsumption') - ->groupBy('date') - ->getCompiledSelect(false); // Convert Query Builder to raw SQL; + //client requirement change from auto entry to manual entry from drier gas consumption - $builder->join("({$subquery2}) tdmd", 'tdmd.date = tpmd.date', 'left'); + // Subquery: Drier Machine Gas Consumption + // $subquery2 = $this->db->table('t_driermachinedetails') + // ->select('date, SUM(total_gas_consumption) AS totalGasConsumption') + // ->groupBy('date') + // ->getCompiledSelect(false); // Convert Query Builder to raw SQL; + + // $builder->join("({$subquery2}) tdmd", 'tdmd.date = tpmd.date', 'left'); diff --git a/app/Models/User_model.php b/app/Models/User_model.php index ebafde7c..b0656cdf 100755 --- a/app/Models/User_model.php +++ b/app/Models/User_model.php @@ -340,4 +340,20 @@ GROUP BY financial_year "; return $query->getResult(); } + + + public function isEmailExists($email, $excludeEmpID = null) + { + $builder = $this->db->table('tbl_users'); + $builder->select('email'); + $builder->where('email', $email); + + if (!empty($excludeEmpID)) { + $builder->where('EmpID !=', $excludeEmpID); + } + + $query = $builder->get(); + return $query->getNumRows() > 0; + } + } \ No newline at end of file diff --git a/app/Views/EditservicePurchaseorder.php b/app/Views/EditservicePurchaseorder.php index 401b562d..3b080fbe 100755 --- a/app/Views/EditservicePurchaseorder.php +++ b/app/Views/EditservicePurchaseorder.php @@ -276,7 +276,12 @@ if (!empty($getlogpodtl)) { menubar: false, statusbar: false, - toolbar: false + toolbar: false, + setup: function(ed) { + ed.on('init', function(evt) { + ed.setContent(``); + }); + } }); tinymce.init({ selector: "textarea#txtSpcialInstruction", // Add model SpcialInstruction @@ -861,7 +866,7 @@ if (!empty($getlogpodtl)) { $('#EditAfterServiceTax').val(''); $('#EditAfterKrishiTax').val(''); $('#EditAfterSwachhTax').val(''); - $('#EditTotalOrderValue ').val(''); + $('#EditTotalOrderValue').val(''); $('#EditRate').val(''); $("#EditItemName").val(''); @@ -1256,7 +1261,7 @@ if (!empty($getlogpodtl)) { > IS THIS OPEN ORDER FORMAT - + @@ -1274,6 +1279,7 @@ if (!empty($getlogpodtl)) { Requisition No Item Code Item Description + HSN/SAC Line Item Specs Quantity UOM @@ -1309,6 +1315,7 @@ if (!empty($getlogpodtl)) { MaterialCode ?> MaterialName, 0, 13, "..."); echo $shortName; ?> + HSNCODE ?> - +     @@ -1494,7 +1501,7 @@ if (!empty($getlogpodtl)) { 'ScopeofWork', 'value' => set_value('ScopeofWork', $ServiceDescription), 'id' => 'ScopeofWork', 'class' => 'form-control', 'rows' => '10', 'cols' => '40'); echo form_textarea($data); ?> @@ -1657,7 +1664,7 @@ if (!empty($getlogpodtl)) {      - + @@ -1699,21 +1706,21 @@ if (!empty($getlogpodtl)) { @@ -2260,7 +2267,7 @@ if (!empty($getlogpodtl)) { @@ -2547,7 +2554,7 @@ if (!empty($getlogpodtl)) { $('input[type="file"], input[type="radio"], input[type="checkbox"]').attr('disabled', true); $("#PaymentTerms,#drpSupplier,#insuranceStatus,#PoTypeOptions,#workstatus").prop("disabled", true); } - var openOrder = ; + var openOrder = ; if(openOrder){ $('#Quantity').val(0); $('#Quantity').removeAttr('required'); @@ -2583,7 +2590,7 @@ if (!empty($getlogpodtl)) { $('#EditotherDescription').hide(); - $('#otherdescription').hide() + $('#otherdescription').hide(); @@ -2597,6 +2604,14 @@ if (!empty($getlogpodtl)) { var AvilBudget = $('#AvlBudAmt').val(); var costCode = $('#CostCenter').val(); var materialCode = $('#MaterialCode').val(); + var selectedText = $('#MaterialCode option:selected').text(); + var parts = selectedText.split('-'); + var HSN = selectedText.includes('-') && /^\d+$/.test(parts[0].trim()) + ? parts[0].trim() + : ''; + + + var materialName = $("#ItemName").val(); var uom = $("#UOM").val(); var addPer = ''; @@ -2666,8 +2681,9 @@ if (!empty($getlogpodtl)) { ${temp} ${Reqnumber} ${materialCode} - ${shorten}`; - if (PONOStatus === "PO_DRAFT" || PONOStatus === "PO_CREATED") { + ${shorten} + ${HSN}`; + if (PONOStatus === "" || PONOStatus === "") { rowHtml += `- @@ -2781,8 +2797,13 @@ if (!empty($getlogpodtl)) { var FrequencyValue = $("#EditFrequencyNo").val(); var ServiceDescription = $('#EdittxtSpcialInstruction').val(); var OtherAmt = $('#EditOtherAllowances').val(); - var TotalOrderValue = $("#EditTotalOrderValue ").val(); + var TotalOrderValue = $("#EditTotalOrderValue").val(); + var editselectedText = $('#EditMaterialCode option:selected').text(); + var editparts = editselectedText.split('-'); + var editHSN = editselectedText.includes('-') && /^\d+$/.test(editparts[0].trim()) + ? editparts[0].trim() + : ''; var basicval = $("#txtEditBasicValue").val(); @@ -2795,12 +2816,13 @@ if (!empty($getlogpodtl)) { cellval[2].innerHTML = editMaterialCode; cellval[3].innerHTML = editDescription; - cellval[5].innerHTML = editQuantity; - cellval[6].innerHTML = editUOM; - cellval[7].innerHTML = parseFloat(itemRate).toFixed(2); - cellval[8].innerHTML = parseFloat(basicval).toFixed(2); - cellval[9].innerHTML = parseFloat(TotalTaxValue).toFixed(2); - cellval[10].innerHTML = parseFloat(TotalOrderValue).toFixed(2); + cellval[4].innerHTML = editHSN; + cellval[6].innerHTML = editQuantity; + cellval[7].innerHTML = editUOM; + cellval[8].innerHTML = parseFloat(itemRate).toFixed(2); + cellval[9].innerHTML = parseFloat(basicval).toFixed(2); + cellval[10].innerHTML = parseFloat(TotalTaxValue).toFixed(2); + cellval[11].innerHTML = parseFloat(TotalOrderValue).toFixed(2); $('#materialCode' + userid).val(editMaterialCode); @@ -3118,7 +3140,7 @@ if (!empty($getlogpodtl)) { $('#txtSpcialInstruction').focus(); return false; } else { - var openOrder = ; + var openOrder = ; if(!openOrder){ if ($('#Quantity').val() == '') { alert('Please Enter the Quantity value'); @@ -3356,6 +3378,7 @@ if (!empty($getlogpodtl)) { //If others is the payment terms to display mandatory field $(document).ready(function() { + $('#otherdescription').hide(); $("#PaymentTerms").change(function() { var otherPayment = ''; if ($('#PaymentTerms').val().trim() == 'PT08') { @@ -3417,8 +3440,8 @@ if (!empty($getlogpodtl)) { if (obj.materialCode == materialCode) { $("#MaterialCode").val(''); } else { - $("#MaterialCode").append($('').val(obj.MaterialCode).html(obj.MaterialCode + "-" + obj.MaterialName)); - + var HSNCODE = obj.HSNCODE ? obj.HSNCODE+" - " : ""; + $("#MaterialCode").append($('').val(obj.MaterialCode).html( HSNCODE + obj.MaterialName+ " ( "+obj.MaterialCode+" ) ")); } @@ -3469,8 +3492,9 @@ if (!empty($getlogpodtl)) { if (isAdded == "0") { - - $("#MaterialCode").append($('').val(obj.MaterialCode).html(obj.MaterialCode + "-" + obj.MaterialName)); + var HSNCODE = obj.HSNCODE ? obj.HSNCODE+" - " : ""; + $("#MaterialCode").append($('').val(obj.MaterialCode).html( HSNCODE + obj.MaterialName+ " ( "+obj.MaterialCode+" ) ")); + // $("#MaterialCode").append($('').val(obj.MaterialCode).html(obj.MaterialCode + "-" + obj.MaterialName)); } } @@ -3514,7 +3538,7 @@ if (!empty($getlogpodtl)) { RateValue = $('#itemRate' + userid).val(); RateValue = parseFloat(RateValue).toFixed(2) $('#EditRate').val(RateValue); - $('#txtEditBasicValue').val(cellval[8].innerHTML); + $('#txtEditBasicValue').val(cellval[9].innerHTML); $('#EditCgst').val($('#Cgst' + userid).val()); $('#EditSgst').val($('#Sgst' + userid).val()); $('#EditIgst').val($('#Igst' + userid).val()); @@ -3544,7 +3568,7 @@ if (!empty($getlogpodtl)) { $("#EditFrequencyNo").val($('#FrequencyValue' + userid).val()); } - $('#EditTotalOrderValue').val(cellval[10].innerHTML); + $('#EditTotalOrderValue').val(cellval[11].innerHTML); $('#EditOtherAllowances').val($('#OtherAmt' + userid).val()); tinyMCE.get('EdittxtSpcialInstruction').setContent($('#ItemDescription' + userid).val()); RequistQuantity = $('#quantity' + userid).val(); @@ -3552,9 +3576,14 @@ if (!empty($getlogpodtl)) { $("#EditMaterialCode").empty(); + var P0 = cellval[4].innerHTML; + var P1 = (P0) ? P0 + " - " : ""; + var P2 = P1 + $('#materialName' + userid).val() ; + var P3 = P2 + " ( " + $('#materialCode' + userid).val() + ' ) '; + $("#EditMaterialCode").append($('') .val($('#materialCode' + userid).val()) - .html($('#materialCode' + userid).val() + "-" + $('#materialName' + userid).val()) + .html(P3) .prop('selected', true) ); // Make the select element read-only (disable it) @@ -3589,8 +3618,9 @@ if (!empty($getlogpodtl)) { if (isAdded == "0") { - - $("#EditMaterialCode").append($('').val(obj.MaterialCode).html(obj.MaterialCode + "-" + obj.MaterialName)); + // $("#EditMaterialCode").append($('').val(obj.MaterialCode).html(obj.MaterialCode + "-" + obj.MaterialName)); + var HSNCODE = obj.HSNCODE ? obj.HSNCODE+" - " : ""; + $("#EditMaterialCode").append($('').val(obj.MaterialCode).html( HSNCODE + obj.MaterialName+ " ( "+obj.MaterialCode+" ) ")); } } @@ -3627,7 +3657,7 @@ if (!empty($getlogpodtl)) { RateValue = $('#itemRate' + userid).val(); RateValue = parseFloat(RateValue).toFixed(2) $('#ViewRate').val(RateValue); - $('#txtViewBasicValue').val(cellval[8].innerHTML); + $('#txtViewBasicValue').val(cellval[9].innerHTML); $('#ViewCgst').val($('#Cgst' + userid).val()); $('#ViewSgst').val($('#Sgst' + userid).val()); $('#ViewIgst').val($('#Igst' + userid).val()); @@ -3654,7 +3684,7 @@ if (!empty($getlogpodtl)) { $("#ViewFrequencyNo").val($('#FrequencyValue' + userid).val()); } - $('#ViewTotalOrderValue').val(cellval[10].innerHTML); + $('#ViewTotalOrderValue').val(cellval[11].innerHTML); $('#ViewOtherAllowances').val($('#OtherAmt' + userid).val()); tinyMCE.get('ViewtxtSpcialInstruction').setContent($('#ItemDescription' + userid).val()); diff --git a/app/Views/POlist.php b/app/Views/POlist.php index 7f5f87b3..c6be2a09 100755 --- a/app/Views/POlist.php +++ b/app/Views/POlist.php @@ -193,13 +193,13 @@ ?> - get('roleText') == 'System Administrator'){ ?> -     - + diff --git a/app/Views/accountsDashboard.php b/app/Views/accountsDashboard.php index 534550c1..afde5728 100644 --- a/app/Views/accountsDashboard.php +++ b/app/Views/accountsDashboard.php @@ -209,7 +209,7 @@ if(!empty($draft)){ ?> - + IGRNO ?> @@ -218,7 +218,7 @@ SupplierName ?> DeliveryChellanOrInvoiceNo ?> - DeliveryChellanDate; if(!$invdate || $invdate == 'null' || $invdate === '0000-00-00 00:00:00'){ echo ""; @@ -262,7 +262,7 @@ isIgrFilePresent)){ ?> - +   @@ -427,6 +427,7 @@ SNo Item Code Item Description + HSN/SAC UOM Ordered Qty Received Qty @@ -435,7 +436,7 @@ Tax (%) Taxable Amt Total Amt - Remarks + Remarks * @@ -804,14 +805,15 @@ '' + i + '' + '' + item.MaterialCode + '' + '' + item.MaterialName + '' + + '' + ((item.HSNCODE) ? item.HSNCODE : '') + '' + '' + item.UOM + '' + '' + parseInt(item.Quantity) + '' + '' + '' + ((isOpenOrder) ? 0 : parseInt(item.Quantity - item.QuantityAsPerInvoice)) + '' + '' + Number(item.Rate).toFixed(2) + '' + '' + tax_percentage + '' + - '' + amount + '' + - '' + grand_total_amount + '' + + '' + Number(amount).toFixed(2) + '' + + '' + Number(grand_total_amount).toFixed(2) + ''; ' ' + ' ' + '' + @@ -843,14 +845,15 @@ '' + i + '' + '' + item.MaterialCode + '' + '' + item.MaterialName + '' + + '' + ((item.HSNCODE) ? item.HSNCODE : '') + '' + '' + item.UOM + '' + '' + parseInt(item.Quantity) + '' + '' + '' + ((isOpenOrder) ? 0 : parseInt(item.Quantity - item.QuantityAsPerInvoice)) + '' + '' + Number(item.Rate).toFixed(2) + '' + '' + tax_percentage + '' + - '' + amount + '' + - '' + grand_total_amount + '' + + '' + Number(amount).toFixed(2) + '' + + '' + Number(grand_total_amount).toFixed(2) + ''; ' ' + ' ' + '' + @@ -878,13 +881,14 @@ '' + i + '' + '' + item.MaterialCode + '' + '' + item.MaterialName + '' + + '' + ((item.HSNCODE) ? item.HSNCODE : '') + '' + '' + item.UOM + '' + '' + item.Quantity + '' + '' + item.QuantityAsPerInvoice + '' + '' + Number(item.Rate).toFixed(2) + '' + '' + tax_percentage + '' + - '' + amount + '' + - '' + grand_total_amount + '' + + '' + Number(amount).toFixed(2) + '' + + '' + Number(grand_total_amount).toFixed(2) + ''; '' + item.Remarks + '' + ' ' + '' + diff --git a/app/Views/addUser.php b/app/Views/addUser.php index d23d6733..e2c3a463 100755 --- a/app/Views/addUser.php +++ b/app/Views/addUser.php @@ -18,8 +18,8 @@
-
-
+ +
@@ -63,7 +63,7 @@
- +
-
+
@@ -181,58 +181,67 @@ $("#ContactNo").val(''); } }); + + $('#MailID').change(function() { + var mailID = $(this).val(); + var empID = ''// $('#EmpList').val(); + if (mailID) { + $('#loader').show(); + $.ajax({ + url: "isEmailExists", + type: 'POST', + data: { EmpID:empID,MailID:mailID }, + success: function(data) { + if (data.success) { + $('#loader').hide(); + alert(data.message); + $("#MailID").val(''); + } else { + $('#loader').hide(); + } + }, + error: function() { + $('#loader').hide(); + alert('An Error Occur in this email address'); + $("#MailID").val(''); + } + }); + }else{ + alert("Invalid email address"); + } + }); }); - $('#addPop').click(function() { - if ($('#distriList option:selected').val() != null) { - if ($('#distriList option:selected').val() == 0) {} else { - var tempSelect = $('#distriList option:selected').val(); - var tempText = $('#distriList option:selected').text(); - var o = new Option(tempText, tempSelect); - var hidval = tempSelect; - var Selectedval = '' - if (orgVal != '') { - Selectedval = orgVal + ':' + hidval; - } else { - Selectedval = hidval - } - $(o).html(tempText); - $("#selectDistriList").append(o); - $('#distriList option:selected').remove(); - $("#distriList").attr('selectedIndex', '-1').find("option:selected").removeAttr("selected"); - $("#selectDistriList").attr('selectedIndex', '-1').find("option:selected").removeAttr("selected"); - tempSelect = ''; - tempText = ''; - Selectedval = ''; - } - } else { - alert("Before add please select any position."); - } - }); - + \ No newline at end of file diff --git a/app/Views/costListing.php b/app/Views/costListing.php index 66baab6f..ad3e3e6d 100755 --- a/app/Views/costListing.php +++ b/app/Views/costListing.php @@ -53,7 +53,7 @@
- Add Cost + Add Cost Details
@@ -137,7 +137,7 @@    -     @@ -187,7 +187,7 @@ diff --git a/app/Views/departmentListing.php b/app/Views/departmentListing.php index 2b36b420..f3f63c6f 100755 --- a/app/Views/departmentListing.php +++ b/app/Views/departmentListing.php @@ -60,7 +60,7 @@ - Add New department + Add New department @@ -159,6 +159,7 @@ diff --git a/app/Views/driverAttendance.php b/app/Views/driverAttendance.php index 4be0a29a..88a55301 100755 --- a/app/Views/driverAttendance.php +++ b/app/Views/driverAttendance.php @@ -76,7 +76,7 @@ $datefordropdown = format_date($datefordropdown, 0, 'M-Y'); - @@ -130,7 +130,7 @@ $datefordropdown = format_date($datefordropdown, 0, 'M-Y');     - +     @@ -165,7 +165,7 @@ $datefordropdown = format_date($datefordropdown, 0, 'M-Y'); Diesel - > + > @@ -179,7 +179,7 @@ $datefordropdown = format_date($datefordropdown, 0, 'M-Y'); Shed Amount - > + > @@ -234,32 +234,19 @@ $datefordropdown = format_date($datefordropdown, 0, 'M-Y'); + modify('first day of this month')->format('Y-m-d');?> modify('last day of this month')->format('Y-m-d');?> modify('today')->format('Y-m-d');?>
-
- - -
-
- - - -
-
- - - -
@@ -271,11 +258,20 @@ $datefordropdown = format_date($datefordropdown, 0, 'M-Y'); -->
+ + +
+
+ + + +
+
-
+
@@ -323,7 +319,7 @@ $datefordropdown = format_date($datefordropdown, 0, 'M-Y');
@@ -385,16 +381,17 @@ $datefordropdown = format_date($datefordropdown, 0, 'M-Y'); $("#attendanceModal").on("shown.bs.modal", function (e) { - + var dname = ""; var id = $(e.relatedTarget).data('id'); - let fields = ['invoice_number', 'vehicle_number', 'load_type', 'salary_amount', 'food_amount','customer','quantity','total_amount']; + let fields = ['invoice_number', 'vehicle_number', 'load_type', 'salary_amount', 'food_amount','customer','quantity','total_amount','category_type']; fields.forEach(function(field) { $("#" + field).val(""); + }); if (id == 0) { - $('#attendanceTitle').html("Add Driver Trip"); + $('#attendanceTitle').html("Add "+dname+" Trip Details"); $("#driver_attendance_id").val(0); } else { $("#driver_attendance_id").val(id); @@ -408,6 +405,9 @@ $datefordropdown = format_date($datefordropdown, 0, 'M-Y'); if(field == 'driver_id'){ $("#driver_id").val(arr && arr['driver_id']); } + if(field == 'category_type'){ + $("#category_type").val(arr && arr['type']); + } var salary = arr['salary_amount'] ? parseFloat(arr['salary_amount']) : 0; var food = arr['food_amount'] ? parseFloat(arr['food_amount']) : 0; @@ -421,7 +421,7 @@ $datefordropdown = format_date($datefordropdown, 0, 'M-Y'); $('#total_amount').val(ttl.toFixed(2)); }); - $('#attendanceTitle').html("Edit Driver Trip"); + $('#attendanceTitle').html("Edit "+dname+" Trip Details"); } }); $('#tempClick').click(function () { @@ -553,7 +553,6 @@ $datefordropdown = format_date($datefordropdown, 0, 'M-Y'); var diesel = parseFloat($('input[data-column="diesel_amount"]').val()) || 0; var shed = parseFloat($('input[data-column="shed_amount"]').val()) || 0; var row = parseInt($('#rowTotalAmount').text()) || 0; - console.log(row); var total = row + diesel + shed; $('#totalAmount').text(total); // Display the total with 2 decimal places @@ -570,15 +569,16 @@ $datefordropdown = format_date($datefordropdown, 0, 'M-Y'); let param_month_year = urlParams.get("month_year"); let param_date = urlParams.get("date"); - - if(param_date == ""){ - let monthMap = {"Jan": "01", "Feb": "02", "Mar": "03", "Apr": "04","May": "05", "Jun": "06", "Jul": "07", "Aug": "08","Sep": "09", "Oct": "10", "Nov": "11", "Dec": "12"}; - let [month, year] = param_month_year.split('-'); - input_date = `01-${monthMap[month]}-${year}`; - }else{ - input_date = param_date; - } + if (!param_date || param_date.trim() === "") { + + let new_my = param_month_year ? param_month_year : ""; + let monthMap = {"Jan": "01", "Feb": "02", "Mar": "03", "Apr": "04", "May": "05", "Jun": "06", "Jul": "07", "Aug": "08", "Sep": "09", "Oct": "10", "Nov": "11", "Dec": "12"}; + let [month, year] = new_my.split('-'); + input_date = `01-${monthMap[month]}-${year}`; + + } else { input_date = param_date; } + // Send data to the server using AJAX $.ajax({ diff --git a/app/Views/driverPayslipGeneratePrint.php b/app/Views/driverPayslipGeneratePrint.php index 916654aa..f6500eee 100755 --- a/app/Views/driverPayslipGeneratePrint.php +++ b/app/Views/driverPayslipGeneratePrint.php @@ -19,65 +19,88 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +
Name driver_name; ?>Employee ID EmpID ?>
Designation Designation ?>Department DeptName ?>
Date Of Joining DOJ)) ?>No Of Loads no_of_loads ?>
Bank Name BankName ?>PAN Number Pan;?>
Bank Acc No BankAccountNumber ?> Aadhar NumberAadharNo);?>
Bank IFSC IFSCCode ?>Loan Balance BalanceAdvance ?>
Diesel diesel_amount; ?>
Shed Duty Amount shed_amount; ?>
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Name:driver_name; ?>Employee ID:EmpID ?>
Designation:Designation ?>Department:DeptName ?>
Date Of Joining:DOJ)) ?>No Of Loads:no_of_load ?>
Bank Name:BankName ?>PAN Number:Pan; ?>
Bank Acc No:BankAccountNumber ?>Aadhar Number:AadharNo); ?>
Bank IFSC:IFSCCode ?>Loan Balance:BalanceAdvance ?>
Diesel Amount:diesel_amount; ?>
Shed Duty Amount:shed_amount; ?>
@@ -85,7 +108,7 @@ - + diff --git a/app/Views/editCapitalAmendPO.php b/app/Views/editCapitalAmendPO.php index fb7a822a..d1c39dc7 100755 --- a/app/Views/editCapitalAmendPO.php +++ b/app/Views/editCapitalAmendPO.php @@ -337,7 +337,12 @@ if (!empty($POItem) && $CapitalRange == '1') { selector: "textarea#txtSpcialInstruction", menubar: false, statusbar: false, - toolbar: false + toolbar: false, + setup: function(ed) { + ed.on('init', function(evt) { + ed.setContent(``); + }); + } // plugins: "link image" }); tinymce.init({ @@ -888,6 +893,7 @@ if (!empty($POItem) && $CapitalRange == '1') { + @@ -913,6 +919,7 @@ if (!empty($POItem) && $CapitalRange == '1') { + + @@ -976,6 +982,7 @@ $(document).ready(function () { + - `; - if (PONOStatus === "PO_DRAFT" || PONOStatus === "PO_CREATED") { + + `; + if (PONOStatus === "" || PONOStatus === "") { rowHtml += ` + @@ -1341,6 +1347,7 @@ if (!empty($INRSYMBOL)) { + + @@ -2355,8 +2367,9 @@ if (isset($AvlimportBudAmt) && !empty($AvlimportBudAmt)) { if (isAdded == "0") { - - $("#MaterialCode").append($('').val(obj.MaterialCode).html(obj.MaterialCode + "-" + obj.MaterialName)); + var HSNCODE = obj.HSNCODE ? obj.HSNCODE+" - " : ""; + $("#MaterialCode").append($('').val(obj.MaterialCode).html( HSNCODE + obj.MaterialName+ " ( "+obj.MaterialCode+" ) ")); + } } @@ -3439,6 +3452,14 @@ if (isset($AvlimportBudAmt) && !empty($AvlimportBudAmt)) { var AvilBudget = $('#AvlBudAmt').val(); var costCode = $('#CostCenter').val(); var materialCode = $('#MaterialCode').val(); + var selectedText = $('#MaterialCode option:selected').text(); + var parts = selectedText.split('-'); + var HSN = selectedText.includes('-') && /^\d+$/.test(parts[0].trim()) + ? parts[0].trim() + : ''; + + + var materialName = $("#ItemName").val(); var uom = $("#UOM").val(); var quantity = $("#Quantity").val(); @@ -3533,6 +3554,7 @@ if (isset($AvlimportBudAmt) && !empty($AvlimportBudAmt)) { + ' + '' + '' + + '' + '' + '' + '' + @@ -611,6 +645,11 @@ var RecQty = parseFloat($('#txtReceivedQuantity' + Rowid).val() == '' ? '0.00' : $('#txtReceivedQuantity' + Rowid).val()); var OrderedQty = parseFloat($("#Quantity_1" + Rowid).text()); var r = $("#Remark" + Rowid).val(); + if (r == '') { + alert("Please Enter the Remark") + $("#Remark" + Rowid).focus(); + return false; + } var isOpenOrder = parseInt($("#hiddenIsOpenOrder").val(), 2); var formatted_IsOpenOrder = (isOpenOrder === 0 || isNaN(isOpenOrder)) ? 0 : 1; if (formatted_IsOpenOrder == 0) { @@ -863,7 +902,7 @@ isOpenOrder = parseInt(obj.IsOpenOrder ? obj.IsOpenOrder : "0", 2); var formatted_IsOpenOrder = (isOpenOrder === 0 || isNaN(isOpenOrder)) ? "" : "Open"; $('.help-block').text(formatted_IsOpenOrder); - var button_text_for_IGRDraftLink = (isOpenOrder === 0 || isNaN(isOpenOrder)) ? "Save as Draft IGR" : "Save as Open IGR"; + var button_text_for_IGRDraftLink = (isOpenOrder === 0 || isNaN(isOpenOrder)) ? "Save as Draft IGR" : "Save as Draft IGR"; $('#IGRDraftLink').text(button_text_for_IGRDraftLink); //$("#Add").val(obj.Address); $("#del").val(obj.DeliveryDate); @@ -898,6 +937,7 @@ '' + '' + '' + + '' + '' + '' + '' + diff --git a/app/Views/monthlypayinputs.php b/app/Views/monthlypayinputs.php index 1cb5f9e8..73838c06 100755 --- a/app/Views/monthlypayinputs.php +++ b/app/Views/monthlypayinputs.php @@ -198,15 +198,23 @@
- + + " + title=""> + + + - + - + - +
@@ -496,7 +504,7 @@ + value="is_driver ?>"> @@ -559,8 +567,8 @@ - @@ -581,7 +589,6 @@ @@ -612,7 +619,7 @@ - - + - + diff --git a/app/Views/sales_dashboard.php b/app/Views/sales_dashboard.php index b23e12fe..ce62ea2b 100755 --- a/app/Views/sales_dashboard.php +++ b/app/Views/sales_dashboard.php @@ -252,7 +252,7 @@ } }, min: 0, // Minimum value for y-axis - max: 30000000 // Maximum value for y-axis + max: 50000000 // Maximum value for y-axis } }, plugins: { diff --git a/app/Views/sales_invoice.php b/app/Views/sales_invoice.php index f6fc61ac..c83a09a3 100755 --- a/app/Views/sales_invoice.php +++ b/app/Views/sales_invoice.php @@ -177,7 +177,7 @@ @@ -341,7 +341,7 @@ - + @@ -1824,7 +1833,7 @@ if (!empty($INRSYMBOL)) { $('#EditQuantity').val($('#quantity' + userid).val()); RequistQuantity = $('#quantity' + userid).val(); $('#EditRate').val($('#itemRate' + userid).val()); - $('#txtEditBasicValue').val(cellval[7].innerHTML); + $('#txtEditBasicValue').val(cellval[9].innerHTML); $('#EditCgst').val($('#Cgst' + userid).val()); $('#EditAfterCgst').val($('#AfterCgst' + userid).val()); $('#EditSgst').val($('#Sgst' + userid).val()); @@ -1842,7 +1851,7 @@ if (!empty($INRSYMBOL)) { $("#EditFrequencyNo").val($('#FrequencyValue' + userid).val()); } - $('#EditTotalOrderValue').val(cellval[9].innerHTML); + $('#EditTotalOrderValue').val(cellval[11].innerHTML); $('#EditOtherAllowances').val($('#OtherAmt' + userid).val()); $('#EditOtheritemDescription').val($('#OtherServiceDescription' + userid).val()); @@ -1863,7 +1872,12 @@ if (!empty($INRSYMBOL)) { $("#EditMaterialCode").empty(); var Material = ; // For Binding Material list center for the selected Requistion Number - $("#EditMaterialCode").append($('').val($('#materialCode' + userid).val()).html($('#materialCode' + userid).val() + "-" + $('#materialName' + userid).val())); + var P0 = cellval[4].innerHTML; + var P1 = (P0) ? P0 + " - " : ""; + var P2 = P1 + $('#materialName' + userid).val() ; + var P3 = P2 + " ( " + $('#materialCode' + userid).val() + ' ) '; + + $("#EditMaterialCode").append($('').val($('#materialCode' + userid).val()).html(P3)); var isAdded = "0"; for (i = 0; i < Material.length; i++) { $.each(Material[i], function(idx, obj) { @@ -1891,8 +1905,8 @@ if (!empty($INRSYMBOL)) { if (isAdded == "0") { - - $("#EditMaterialCode").append($('').val(obj.MaterialCode).html(obj.MaterialCode + "-" + obj.MaterialName)); + var HSNCODE = obj.HSNCODE ? obj.HSNCODE+" - " : ""; + $("#EditMaterialCode").append($('').val(obj.MaterialCode).html( HSNCODE + obj.MaterialName+ " ( "+obj.MaterialCode+" ) ")); } } @@ -1919,6 +1933,11 @@ if (!empty($INRSYMBOL)) { var AvilBudget = $('#AvlBudAmt').val(); var costCode = $('#CostCenter').val(); var materialCode = $('#MaterialCode').val(); + var selectedText = $('#MaterialCode option:selected').text(); + var parts = selectedText.split('-'); + var HSN = selectedText.includes('-') && /^\d+$/.test(parts[0].trim()) + ? parts[0].trim() + : ''; var materialName = $("#ItemName").val(); var uom = $("#UOM").val(); @@ -1991,6 +2010,7 @@ if (!empty($INRSYMBOL)) { + - + - + - + - + - + - - - - - + + + + + @@ -1296,7 +1298,7 @@ @@ -1364,10 +1365,10 @@

( Previously Uploaded File ${element.client_given_name} )

- + `; - $('#editBatchCardRowId').append(string) + $('#editBatchCardRowId').append(string); }); @@ -1459,7 +1460,6 @@ let machineRunningInHrs = calculateMachineRunInHrs(machineOnDate, machineOnTimeHr, machineOffTimeHr); if (!machineRunningInHrs) { - $('#machineOffTimeHrId').val(''); return } @@ -1467,12 +1467,31 @@ $('#totalCoatingSandId').trigger('change'); $('#totalGasConsumptionId').trigger('change'); - - }) + $('#totalCoatingId , #shiftId , #gradeId').change(function(){ + + let basicCheck =checkIsNumber($(this).val().trim()); + + + if (basicCheck == 0) { + alert("Kindly Enter Numbers only..!!"); + return; + } + + + }) + $('#totalCoatingSandId').change(function() { + let basicCheck =checkIsNumber($(this).val().trim()); + + + if (basicCheck == 0) { + alert("Kindly Enter Numbers only..!!"); + return; + } + let totalCoatingSandValue = $(this).val(); let machineRunningInHrsValue = $('#machineRunningInHrsId').val(); @@ -1486,6 +1505,15 @@ $('#totalGasConsumptionId').change(function() { + + let basicCheck =checkIsNumber($(this).val().trim()); + + + if (basicCheck == 0) { + alert("Kindly Enter Numbers only..!!"); + return; + } + let totalGasConsumptionValue = $(this).val(); let machineRunningInHrsValue = $('#machineRunningInHrsId').val(); if (totalGasConsumptionValue && machineRunningInHrsValue) { @@ -1496,14 +1524,6 @@ }) - }) - - - - - @@ -1651,15 +1711,15 @@ $('#changeMonthForm').submit(); }); - $(document).ready(function(){ - $('#month').datepicker({ + $('#month').datepicker({ format: 'M-yyyy', viewMode: 'months', minViewMode: 'months', autoclose: true, - orientation: 'bottom' - }) - }) + orientation: 'bottom', + startDate: new Date(2025, 0), // Jan is month 0 + endDate: new Date() // current date as max + }); @@ -1712,48 +1772,59 @@ + @@ -1141,60 +1245,70 @@ foreach ($period as $day) { + + + + + + + + + \ No newline at end of file diff --git a/app/Views/stock/dieselStockDetails.php b/app/Views/stock/dieselStockDetails.php index 5adc25eb..868f18aa 100644 --- a/app/Views/stock/dieselStockDetails.php +++ b/app/Views/stock/dieselStockDetails.php @@ -260,6 +260,13 @@ .card { margin-bottom: 5px; } + + .hidden-row { + display: none; + } + + + @@ -319,6 +326,19 @@ foreach ($period as $day) {
+
+
@@ -368,17 +388,17 @@ foreach ($period as $day) { + id="dieselMachineStockDetailsExport"> - @@ -581,17 +601,17 @@ foreach ($period as $day) { foreach ($groupedDieselMachineStockDetails as $rowIndex => $dieselStockDetails) { + $currentDate = date('Y-m-d'); + ?> -
" format('d-m-Y'); - if ($dateInMonthDmYFormat === $currentDate) { - echo 'style="background: #cef0ad;"'; - } - ?>> + if ($dieselStockDetails[0]['date'] === $currentDate) { + echo 'style="background: #cef0ad;"'; + } + ?> + > 0, 'running_hours' => 0, 'mileage' => 0, + 'machineId' => $machineId, ]; } @@ -782,21 +803,39 @@ foreach ($period as $day) { - - - - + + + + + + + - - - - - - + + + + + + + + + + + - + - $dateInMonth) { ?> - $dateInMonth) { + + $currentDate = date('Y-m-d'); + + ?> + + " format('d-m-Y'); - if ($dateInMonthDmYFormat === $currentDate) { + if ($dateInMonth === $currentDate) { echo 'style="background: #cef0ad;"'; } ?>> @@ -1017,6 +1058,59 @@ foreach ($period as $day) { + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -1123,10 +1217,9 @@ foreach ($period as $day) { var updateDieselMachineDetails = tableToJson(); - alert('Updation may take a while, And we appreciate your patience..!!'); + showMessage('Updation may take a while, And we appreciate your patience..!!'); - $('#loader').show(); - $.ajax({ + $.ajax({ data: { updateDieselMachineDetails }, @@ -1135,16 +1228,13 @@ foreach ($period as $day) { success: function(data) { if (data) { - $('#loader').hide(); - console.log(data); - alert(data); - window.location.reload(); + showMessage(data); } }, error: function(xhr, status, error) { - alert("An error occurred while processing the request. Please try again."); + showMessage("An error occurred while processing the request. Please try again."); console.error("Error Code:", xhr.status); console.error("Error Message:", error); console.error("Response Text:", xhr.responseText); @@ -1223,6 +1313,15 @@ foreach ($period as $day) { function openingReadingChange(tdElement) { try { + + let basicCheck =checkIsNumber(tdElement.innerText.trim()); + + if(basicCheck == 0){ + + alert("Kindly Enter Numbers only..!!"); + return ; + } + let dataId = tdElement.getAttribute('data-id'); let [date, machine_id] = tdElement.getAttribute('data-id').split(' '); let openingReading = validateInput(tdElement.innerText); @@ -1235,7 +1334,16 @@ foreach ($period as $day) { document.querySelector(`td.mileage[data-id="${dataId}"]`).innerText = parseFloat(mileage).toFixed(2); - updateStockValue(date, machine_id, closingReading) + updateStockValue(date, machine_id, closingReading); + + + let table = document.getElementById('dieselStockDetailsTableId'); + let column1 = 'runningHours'; + let column2 = 'mileage'; + + calculateTotal(table,dataId,column1) + + calculateTotal(table,dataId,column2) } catch (error) { @@ -1248,6 +1356,15 @@ foreach ($period as $day) { function closingReadingChange(tdElement) { try { + + let basicCheck =checkIsNumber(tdElement.innerText.trim()); + + if(basicCheck == 0){ + + alert("Kindly Enter Numbers only..!!"); + return ; + } + let dataId = tdElement.getAttribute('data-id'); let [date, machine_id] = tdElement.getAttribute('data-id').split(' '); let closingReading = validateInput(tdElement.innerText); @@ -1259,8 +1376,16 @@ foreach ($period as $day) { document.querySelector(`td.runningHours[data-id="${dataId}"]`).innerText = parseFloat(runningHours).toFixed(2); document.querySelector(`td.mileage[data-id="${dataId}"]`).innerText = parseFloat(mileage).toFixed(2); - updateStockValue(date, machine_id, closingReading) + updateStockValue(date, machine_id, closingReading); + let table = document.getElementById('dieselStockDetailsTableId'); + + let column1 = 'runningHours'; + let column2 = 'mileage'; + + calculateTotal(table,dataId,column1) + + calculateTotal(table,dataId,column2) } catch (error) { @@ -1273,6 +1398,15 @@ foreach ($period as $day) { function consumptionChange(tdElement) { try { + + let basicCheck =checkIsNumber(tdElement.innerText.trim()); + + if(basicCheck == 0){ + + alert("Kindly Enter Numbers only..!!"); + return ; + } + let dataId = tdElement.getAttribute('data-id'); let [date, machine_id] = tdElement.getAttribute('data-id').split(' '); let closingReading = validateInput(document.querySelector(`td.closingReading[data-id="${dataId}"]`).innerText); @@ -1284,7 +1418,16 @@ foreach ($period as $day) { document.querySelector(`td.runningHours[data-id="${dataId}"]`).innerText = parseFloat(runningHours).toFixed(2); document.querySelector(`td.mileage[data-id="${dataId}"]`).innerText = parseFloat(mileage).toFixed(2); - updateStockValue(date, machine_id, closingReading) + updateStockValue(date, machine_id, closingReading); + + let table = document.getElementById('dieselStockDetailsTableId'); + + let column1 = 'consumption'; + let column2 = 'mileage'; + + calculateTotal(table,dataId,column1) + + calculateTotal(table,dataId,column2) } catch (error) { @@ -1298,6 +1441,15 @@ foreach ($period as $day) { try { + let basicCheck =checkIsNumber(tdElement.innerText.trim()); + + if(basicCheck == 0){ + + alert("Kindly Enter Numbers only..!!"); + return ; + } + + let dataId = tdElement.getAttribute('data-id'); let [date, machine_id] = tdElement.getAttribute('data-id').split(" "); @@ -1327,6 +1479,17 @@ foreach ($period as $day) { updateTotalStockValue(date, balanceTD); + let table = document.getElementById('dieselStockDetailsTableId'); + let column1 = 'fillingDiesel'; + let column2 = 'fillingTD'; + let column3 = 'purchaseTD'; + + calculateTotal(table,dataId,column1); + + calculateTotal(table,date,column2); + + calculateTotal(table,date,column3); + } catch (error) { @@ -1344,6 +1507,14 @@ foreach ($period as $day) { try { + let basicCheck =checkIsNumber(tdElement.innerText.trim()); + + if(basicCheck == 0){ + + alert("Kindly Enter Numbers only..!!"); + return ; + } + let dataId = tdElement.getAttribute('data-id'); let openingTD = validateInput(tdElement.innerText); @@ -1355,7 +1526,17 @@ foreach ($period as $day) { document.querySelector(`td.balanceTD[data-id="${dataId}"]`).innerText = parseFloat(balanceTD).toFixed(2); - updateTotalStockValue(dataId, balanceTD) + updateTotalStockValue(dataId, balanceTD); + + let table = document.getElementById('dieselStockDetailsTableId'); + + let column1 = 'fillingTD'; + + let column2 = 'purchaseTD'; + + calculateTotal(table,dataId,column1); + + calculateTotal(table,dataId,column2); } catch (error) { @@ -1369,6 +1550,16 @@ foreach ($period as $day) { function purchaseTDStockChange(tdElement) { try { + + + let basicCheck =checkIsNumber(tdElement.innerText.trim()); + + if(basicCheck == 0){ + + alert("Kindly Enter Numbers only..!!"); + return ; + } + let dataId = tdElement.getAttribute('data-id'); let purchaseTD = validateInput(tdElement.innerText); let openingTD = validateInput(document.querySelector(`td.openingTD[data-id="${dataId}"]`).innerText); @@ -1381,6 +1572,18 @@ foreach ($period as $day) { updateTotalStockValue(dataId, balanceTD); + + let table = document.getElementById('dieselStockDetailsTableId'); + + let column1 = 'fillingTD'; + + let column2 = 'purchaseTD'; + + calculateTotal(table,dataId,column1); + + calculateTotal(table,dataId,column2); + + } catch (error) { @@ -1405,12 +1608,23 @@ foreach ($period as $day) { // Validate against the regex const isValid = /^-?\d*\.?\d*$/.test(input); if (!isValid) { - alert('Invalid input! Please enter a valid number.'); + return 0; } return input; } + + function checkIsNumber(input) { + + const isValid = /^-?\d*\.?\d*$/.test(input); + + if (!isValid) { + return 0; + } + } + + + + + + + + + \ No newline at end of file diff --git a/app/Views/stock/drierMachineDetails.php b/app/Views/stock/drierMachineDetails.php index 79ac5c1f..e990901d 100644 --- a/app/Views/stock/drierMachineDetails.php +++ b/app/Views/stock/drierMachineDetails.php @@ -327,9 +327,7 @@ $datefordropdown = format_date($datefordropdown, 0, 'M-Y'); " class="form-control " - data-provide="datepicker" - data-date-format="M-yyyy" - data-date-min-view-mode="1" readonly> + readonly> @@ -359,12 +357,12 @@ $datefordropdown = format_date($datefordropdown, 0, 'M-Y'); -
+ *
- + * @@ -512,6 +511,7 @@ $datefordropdown = format_date($datefordropdown, 0, 'M-Y');
+ *
@@ -531,7 +532,10 @@ $datefordropdown = format_date($datefordropdown, 0, 'M-Y');
- + * +
@@ -539,6 +543,7 @@ $datefordropdown = format_date($datefordropdown, 0, 'M-Y');
+ *
@@ -552,13 +557,14 @@ $datefordropdown = format_date($datefordropdown, 0, 'M-Y');
+ *
- +
@@ -566,7 +572,7 @@ $datefordropdown = format_date($datefordropdown, 0, 'M-Y');
- +
@@ -586,14 +592,18 @@ $datefordropdown = format_date($datefordropdown, 0, 'M-Y');
- - + + * +
+ *
@@ -627,13 +637,14 @@ $datefordropdown = format_date($datefordropdown, 0, 'M-Y');
+ *
- - @@ -644,8 +655,8 @@ $datefordropdown = format_date($datefordropdown, 0, 'M-Y');
- - @@ -668,7 +679,8 @@ $datefordropdown = format_date($datefordropdown, 0, 'M-Y');
- $value) { ?> @@ -679,15 +691,19 @@ $datefordropdown = format_date($datefordropdown, 0, 'M-Y');
- + + * + type="text" class="form-control" id="editEntryInputSandQtyId" name="input_sand_qty" value="" required>
- + * +
@@ -695,8 +711,9 @@ $datefordropdown = format_date($datefordropdown, 0, 'M-Y');
+ * + type="text" class="form-control" id="editEntrySandDriedQtyId" name="sand_dried_qty" value="" required>
@@ -708,21 +725,22 @@ $datefordropdown = format_date($datefordropdown, 0, 'M-Y');
+ * + type="text" class="form-control" id="editEntryTotalGasConsumptionId" name="total_gas_consumption" value="" required>
- - Gas / Ton +
- +
@@ -731,7 +749,7 @@ $datefordropdown = format_date($datefordropdown, 0, 'M-Y');
-
@@ -742,19 +760,23 @@ $datefordropdown = format_date($datefordropdown, 0, 'M-Y');
- - + + * +
- + * +
- + @@ -791,7 +813,7 @@ $datefordropdown = format_date($datefordropdown, 0, 'M-Y');
- + @@ -879,12 +901,12 @@ $datefordropdown = format_date($datefordropdown, 0, 'M-Y'); @@ -944,8 +966,9 @@ $datefordropdown = format_date($datefordropdown, 0, 'M-Y'); $summary['input_sand_qty'] += $a['input_sand_qty'] == "-" ? 0 : (float) $a['input_sand_qty']; $summary['moisture_loss_qty'] += $a['moisture_loss_qty'] == "-" ? 0 : (float) $a['moisture_loss_qty']; $summary['sand_dried_qty'] += $a['sand_dried_qty'] == "-" ? 0 : (float) $a['sand_dried_qty']; - $summary['gas_per_ton'] = round(($summary['total_gas_consumption'] / $summary['sand_dried_qty'])); - $summary['qty_per_hrs'] = round( ($summary['sand_dried_qty'] / $summary['drier_running_hours']) ); + $summary['gas_per_ton'] = number_format(($summary['total_gas_consumption'] / $summary['sand_dried_qty']), 2); + $summary['qty_per_hrs'] = number_format(($summary['sand_dried_qty'] / $summary['drier_running_hours']), 2); + $summary['dust_qty'] += $a['dust_qty'] == "-" ? 0 : (float) $a['dust_qty']; } ?> @@ -1106,9 +1129,9 @@ $datefordropdown = format_date($datefordropdown, 0, 'M-Y'); hours = parseInt(hours, 10); // Adjust hours based on AM/PM - if (modifier === "pm" && hours < 12) { + if (modifier === "PM" && hours < 12) { hours += 12; - } else if (modifier === "am" && hours === 12) { + } else if (modifier === "AM" && hours === 12) { hours = 0; } @@ -1172,6 +1195,17 @@ $datefordropdown = format_date($datefordropdown, 0, 'M-Y'); let totalGasConsumption = $('#additionalEntryTotalGasConsumptionId').val(); let sandDriedQty = $('#additionalEntrySandDriedQtyId').val(); + + let basicCheck = checkIsNumber(totalGasConsumption); + let basicCheck2 = checkIsNumber(sandDriedQty); + + if (basicCheck == 0) { + alert("Kindly Enter Numbers only..!!"); + } + if (basicCheck2 == 0) { + alert("Kindly Enter Numbers only..!!"); + } + if (totalGasConsumption != '' && sandDriedQty != '') { let gasPerTon = (parseFloat(totalGasConsumption) / parseFloat(sandDriedQty)).toFixed(2); @@ -1187,6 +1221,17 @@ $datefordropdown = format_date($datefordropdown, 0, 'M-Y'); let inputSandQty = $('#additionalEntryInputSandQtyId').val(); let sandDriedQty = $('#additionalEntrySandDriedQtyId').val(); + let basicCheck = checkIsNumber(inputSandQty); + let basicCheck2 = checkIsNumber(sandDriedQty); + + if (basicCheck == 0) { + alert("Kindly Enter Numbers only..!!"); + } + if (basicCheck2 == 0) { + alert("Kindly Enter Numbers only..!!"); + + } + if (inputSandQty != '' && sandDriedQty != '') { let moistureLossQty = parseFloat(inputSandQty) - parseFloat(sandDriedQty); @@ -1203,6 +1248,17 @@ $datefordropdown = format_date($datefordropdown, 0, 'M-Y'); let drierRunninhHrs = $('#additionalEntryRunningHrsId').val(); let sandDriedQty = $('#additionalEntrySandDriedQtyId').val(); + let basicCheck = checkIsNumber(drierRunninhHrs); + let basicCheck2 = checkIsNumber(sandDriedQty); + + if (basicCheck == 0) { + alert("Kindly Enter Numbers only..!!"); + } + if (basicCheck2 == 0) { + alert("Kindly Enter Numbers only..!!"); + + } + if (drierRunninhHrs != '' && sandDriedQty != '') { let qtyPerHrs = parseFloat(sandDriedQty) / parseFloat(drierRunninhHrs); @@ -1217,13 +1273,38 @@ $datefordropdown = format_date($datefordropdown, 0, 'M-Y'); } + function additionalEntryInputSandMoisture(value) { + + let sandMoisture = $('#additionalEntryInputSandMoistureId').val(); + + let basicCheck = checkIsNumber(sandMoisture); + + if (basicCheck == 0) { + alert("Kindly Enter Numbers only..!!"); + } + +} + + function additionalEntryDustQty(value) { + + let dustQty = $('#additionalEntryDustQtyId').val(); + + let basicCheck = checkIsNumber(dustQty); + + if (basicCheck == 0) { + alert("Kindly Enter Numbers only..!!"); + } + + } + + // this for edit entry in ten ton f=drier function editEntryCalculateMachineRunningHrs() { - let dreierMachineOnTime = $('#editEntryDrierOnTimeId').val(); + let dreierMachineOnTime = $('#editEntryDrierOnTimeId').val(); let dreierMachineOffTime = $('#editEntryDrierOffTimeId').val(); if (dreierMachineOnTime == dreierMachineOffTime) { @@ -1275,6 +1356,17 @@ $datefordropdown = format_date($datefordropdown, 0, 'M-Y'); let totalGasConsumption = $('#editEntryTotalGasConsumptionId').val(); let sandDriedQty = $('#editEntrySandDriedQtyId').val(); + + let basicCheck = checkIsNumber(totalGasConsumption); + let basicCheck2 = checkIsNumber(sandDriedQty); + + if (basicCheck == 0) { + alert("Kindly Enter Numbers only..!!"); + } + if (basicCheck2 == 0) { + alert("Kindly Enter Numbers only..!!"); + } + if (totalGasConsumption != '' && sandDriedQty != '') { let gasPerTon = (parseFloat(totalGasConsumption) / parseFloat(sandDriedQty)).toFixed(2); @@ -1290,6 +1382,17 @@ $datefordropdown = format_date($datefordropdown, 0, 'M-Y'); let inputSandQty = $('#editEntryInputSandQtyId').val(); let sandDriedQty = $('#editEntrySandDriedQtyId').val(); + let basicCheck = checkIsNumber(inputSandQty); + let basicCheck2 = checkIsNumber(sandDriedQty); + + if (basicCheck == 0) { + alert("Kindly Enter Numbers only..!!"); + } + + if (basicCheck2 == 0) { + alert("Kindly Enter Numbers only..!!"); + } + if (inputSandQty != '' && sandDriedQty != '') { let moistureLossQty = parseFloat(inputSandQty) - parseFloat(sandDriedQty); @@ -1306,6 +1409,17 @@ $datefordropdown = format_date($datefordropdown, 0, 'M-Y'); let drierRunninhHrs = $('#editEntryRunningHrsId').val(); let sandDriedQty = $('#editEntrySandDriedQtyId').val(); + let basicCheck = checkIsNumber(drierRunninhHrs); + let basicCheck2 = checkIsNumber(sandDriedQty); + + if (basicCheck == 0) { + alert("Kindly Enter Numbers only..!!"); + } + + if (basicCheck2 == 0) { + alert("Kindly Enter Numbers only..!!"); + } + if (drierRunninhHrs != '' && sandDriedQty != '') { let qtyPerHrs = parseFloat(sandDriedQty) / parseFloat(drierRunninhHrs); @@ -1316,6 +1430,41 @@ $datefordropdown = format_date($datefordropdown, 0, 'M-Y'); } } + + function editEntryInputSandMoisture(value) { + + let sandMoisture = $('#editEntryInputSandMoistureId').val(); + + let basicCheck = checkIsNumber(sandMoisture); + + if (basicCheck == 0) { + alert("Kindly Enter Numbers only..!!"); + } + + } + + function editEntryDustQty(value) { + + let dustQty = $('#editEntryDustQtyId').val(); + + let basicCheck = checkIsNumber(dustQty); + + if (basicCheck == 0) { + alert("Kindly Enter Numbers only..!!"); + } + + } + + function checkIsNumber(input) { + + const isValid = /^-?\d*\.?\d*$/.test(input); + + if (!isValid) { + return 0; + } + } + + @@ -1379,17 +1528,14 @@ $datefordropdown = format_date($datefordropdown, 0, 'M-Y'); let rows = []; // Extract table data row-by-row - $(table).find('tr').each(function(rowIndex) { + $(table).find('tr').each(function() { let rowData = []; - $(this).find('th, td').each(function(colIndex) { + $(this).find('th, td').each(function() { // Skip hidden columns if ($(this).css('display') === 'none') return; let cellText = $(this).text().trim(); - - - rowData.push(cellText); }); @@ -1401,35 +1547,59 @@ $datefordropdown = format_date($datefordropdown, 0, 'M-Y'); // Create a worksheet from array (no DOM needed!) let ws = XLSX.utils.aoa_to_sheet(rows); + + // Calculate max column count from the collected rows + let colCount = 0; + rows.forEach(row => { + if (row.length > colCount) colCount = row.length; + }); + + // Set custom column widths (10 for each column) + const wscols = []; + for (let i = 0; i < colCount; i++) { + wscols.push({ wch: 10 }); + } + ws['!cols'] = wscols; + + // Create workbook and export let wb = XLSX.utils.book_new(); XLSX.utils.book_append_sheet(wb, ws, 'Sheet1'); XLSX.writeFile(wb, filename || 'export.xlsx'); } - let tableId = 'drierTable'; document.getElementById('drierMachineDetailsExport').addEventListener('click', function() { - exportTableToExcel(tableId, 'drierMachineDetails_.xlsx'); + }); - }) - - - }) + }); + @@ -847,45 +905,52 @@ } }); + // Format date in first column and left-align $(cloneTable).find('tbody tr').each(function() { - let firstTd = $(this).find('td').eq(0); // Get the first column (Date) - - // Convert Date Format (Assuming it's in YYYY-MM-DD format) - let originalDate = firstTd.text().trim(); // Get the text value - let parts = originalDate.split('-'); // Split into [YYYY, MM, DD] + let firstTd = $(this).find('td').eq(0); + let originalDate = firstTd.text().trim(); + let parts = originalDate.split('-'); if (parts.length === 3) { - let formattedDate = `${parts[2]}-${parts[1]}-${parts[0]}`; // Rearrange to DD-MM-YYYY - firstTd.text(formattedDate); // Update the cell value + let formattedDate = `${parts[2]}-${parts[1]}-${parts[0]}`; + firstTd.text(formattedDate); } - - // Apply left alignment to the date column firstTd.css("text-align", "left"); - - }); + // Convert modified table to worksheet + let ws = XLSX.utils.table_to_sheet(cloneTable); - let ws = XLSX.utils.table_to_sheet(cloneTable); // Convert modified table to sheet - let wb = XLSX.utils.book_new(); // Create a new workbook - XLSX.utils.book_append_sheet(wb, ws, 'Sheet1'); // Append sheet to workbook - XLSX.writeFile(wb, filename || 'export.xlsx'); // Save the file + // Dynamically get maximum column count + let colCount = 0; + $(cloneTable).find('tr').each(function() { + let count = $(this).find('th, td').length; + if (count > colCount) colCount = count; + }); + + // Set column widths to 10 units for each + const wscols = []; + for (let i = 0; i < colCount; i++) { + wscols.push({ wch: 10 }); + } + ws['!cols'] = wscols; + + // Create workbook and save + let wb = XLSX.utils.book_new(); + XLSX.utils.book_append_sheet(wb, ws, 'Sheet1'); + XLSX.writeFile(wb, filename || 'export.xlsx'); } - - let tableId = 'dustAndRoughStockDetailsTableId'; document.getElementById('dustAndRoughStockExport').addEventListener('click', function() { - exportTableToExcel(tableId, 'dustAndRoughStockDetails.xlsx'); + }); - }) - - - }) + }); + @@ -1024,4 +1094,54 @@ }, 200); }); }); + + + + + + \ No newline at end of file diff --git a/app/Views/stock/gasStockDetails.php b/app/Views/stock/gasStockDetails.php index b4110044..337a91b8 100644 --- a/app/Views/stock/gasStockDetails.php +++ b/app/Views/stock/gasStockDetails.php @@ -280,6 +280,12 @@ .card { margin-bottom: 5px; } + + .hidden-row { + display: none; + } + +
@@ -312,6 +318,20 @@
+
+
+ @@ -323,9 +343,7 @@ " class="form-control " - data-provide="datepicker" - data-date-format="M-yyyy" - data-date-min-view-mode="1" readonly> + readonly>
@@ -355,12 +373,12 @@ - @@ -472,9 +490,9 @@
- + - + @@ -486,21 +504,22 @@ + $gasStockDetail) { - - $date = Datetime::createFromFormat('Y-m-d', $gasStockDetail['date'])->format('d-m-Y') + $currentDate = date('Y-m-d'); + $date = Datetime::createFromFormat('Y-m-d', $gasStockDetail['date'])->format('d-m-Y'); ?> + - " > + if ($gasStockDetail['date'] === $currentDate) { + echo 'style="background: #cef0ad;"'; + } + ?> + > @@ -656,20 +675,34 @@ - - - - - - - - - - - - - - + + + + + + + + + + + + + + @@ -698,18 +731,18 @@ } foreach ($datesInMonth as $datesInMonthIndex => $dateInMonth) { - + $currentDate = date('d-m-Y'); $dateInMonthDmYFormat = Datetime::createFromFormat('Y-m-d', $dateInMonth)->format('d-m-Y'); ?> - " > @@ -768,8 +801,51 @@ oninput="gasConsumptionChange(this)" contenteditable="true"> - + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EarningsAmount DeductionsAmount
 BASIC BASIC BASIC; ?>   PF  SNo Requisition No Item DescriptionHSN/SAC Line Item Specs Quantity UOMReqNo ?> MaterialName, 0, 13, "..."); echo $shortName; ?>HSNCODE ?>
- 'txtSpcialInstruction', 'value' => set_value('txtSpcialInstruction', strip_tags($scopeofwork)), 'id' => 'txtSpcialInstruction', 'class' => 'form-control', 'rows' => '10', 'cols' => '40'); - echo form_textarea($data); - ?> + +
@@ -1757,9 +1765,9 @@ if (!empty($POItem) && $CapitalRange == '1') {
@@ -2444,8 +2452,8 @@ if (!empty($POItem) && $CapitalRange == '1') { @@ -2681,8 +2689,9 @@ if (!empty($POItem) && $CapitalRange == '1') { if (isAdded == "0") { - - $("#MaterialCode").append($('').val(obj.MaterialCode).html(obj.MaterialCode + "-" + obj.MaterialName)); + var HSNCODE = obj.HSNCODE ? obj.HSNCODE+" - " : ""; + $("#MaterialCode").append($('').val(obj.MaterialCode).html( HSNCODE + obj.MaterialName+ " ( "+obj.MaterialCode+" ) ")); + // $("#MaterialCode").append($('').val(obj.MaterialCode).html(obj.MaterialCode + "-" + obj.MaterialName)); } } @@ -3345,7 +3354,7 @@ Calculate Landing charge $('#EditOtherAllowances').val($('#otherallowance' + userid).val()); //$('#Editservicetotalordervaue').val($('#totalservicevalue'+userid).val()); - $('#Editservicetotalordervaue').val(cellval[9].innerHTML); + $('#Editservicetotalordervaue').val(cellval[10].innerHTML); @@ -3433,12 +3442,22 @@ Calculate Landing charge $("#EditMaterialCode").empty(); - $("#EditMaterialCode").append($('').val($('#materialCode' + userid).val()).html($('#materialCode' + userid).val() + "-" + $('#materialName' + userid).val())); + var P0 = cellval[3].innerHTML; + var P1 = (P0) ? P0 + " - " : ""; + var P2 = P1 + $('#materialName' + userid).val() ; + var P3 = P2 + " ( " + $('#materialCode' + userid).val() + ' ) '; + + $("#EditMaterialCode").append($('') + .val($('#materialCode' + userid).val()) + .html(P3) + .prop('selected', true) + ); for (i = 0; i < Material.length; i++) { $.each(Material[i], function (idx, obj) { if (obj.MaterialCode != $('#materialCode' + userid).val()) { - $("#EditMaterialCode").append($('').val(obj.MaterialCode).html(obj.MaterialCode + "-" + obj.MaterialName)); + var HSN = (obj.HSNCODE) ? obj.HSNCODE+" - " : ""; + $("#EditMaterialCode").append($('').val(obj.MaterialCode).html(HSN + obj.MaterialName + " ( "+obj.MaterialCode+" ) ")); } }); @@ -4056,19 +4075,26 @@ Calculate Landing charge $('#DisVal' + userid).val(DisVal); $('#AfterDisVal' + userid).val(AfterDisVal); var shorten = materialName.length > 13 ? materialName.slice(0, 13) + "..." : materialName; + var editselectedText = $('#EditMaterialCode option:selected').text(); + var editparts = editselectedText.split('-'); + var editHSN = editselectedText.includes('-') && /^\d+$/.test(editparts[0].trim()) + ? editparts[0].trim() + : ''; + cellval[2].innerHTML = shorten; //alert(materialName); - cellval[4].innerHTML = parseFloat(quantity).toFixed(2); + cellval[4].innerHTML = editHSN; + cellval[5].innerHTML = parseFloat(quantity).toFixed(2); //alert(quantity); - cellval[5].innerHTML = uom; + cellval[6].innerHTML = uom; //alert(uom); - cellval[6].innerHTML = parseFloat(itemRate).toFixed(2); + cellval[7].innerHTML = parseFloat(itemRate).toFixed(2); //alert(itemRate); - cellval[7].innerHTML = parseFloat(basicval).toFixed(2); + cellval[8].innerHTML = parseFloat(basicval).toFixed(2); //alert(basicval); - cellval[8].innerHTML = parseFloat(TotalTaxValue).toFixed(2); + cellval[9].innerHTML = parseFloat(TotalTaxValue).toFixed(2); //alert(TotalTaxValue); - cellval[9].innerHTML = parseFloat(totalservicevalue).toFixed(2); + cellval[10].innerHTML = parseFloat(totalservicevalue).toFixed(2); //alert(basicval); diff --git a/app/Views/editCapitalPo.php b/app/Views/editCapitalPo.php index ba8ab4c0..671dbeac 100755 --- a/app/Views/editCapitalPo.php +++ b/app/Views/editCapitalPo.php @@ -343,7 +343,12 @@ if (!empty($getlogpodtl)) { selector: "textarea#txtSpcialInstruction", menubar: false, statusbar: false, - toolbar: false + toolbar: false, + setup: function(ed) { + ed.on('init', function(evt) { + ed.setContent(``); + }); + } }); tinymce.init({ selector: "textarea#ItemDescription", @@ -926,7 +931,7 @@ $(document).ready(function () { @@ -943,6 +948,7 @@ $(document).ready(function () {
Requisition No Item Code Item DescriptionHSN/SAC Line Item Specs Quantity UOMMaterialCode ?> MaterialName, 0, 13, "..."); echo $shortName; ?>HSNCODE ?>     + data-userid="" id="Del"> @@ -1587,10 +1594,11 @@ $(document).ready(function () {
- 'txtSpcialInstruction', 'value' => set_value('txtSpcialInstruction', strip_tags($ServiceDescription)), 'id' => 'txtSpcialInstruction', 'class' => 'form-control', 'rows' => '10', 'cols' => '40'); - echo form_textarea($data); - ?> + +
@@ -1608,7 +1616,7 @@ $(document).ready(function () {      - + @@ -1658,17 +1666,17 @@ $(document).ready(function () { @@ -3096,7 +3104,7 @@ $(document).ready(function () { @@ -4061,8 +4069,8 @@ $(document).ready(function () { if (isAdded == "0") { - - $("#MaterialCode").append($('').val(obj.MaterialCode).html(obj.MaterialCode + "-" + obj.MaterialName)); + var HSNCODE = obj.HSNCODE ? obj.HSNCODE+" - " : ""; + $("#MaterialCode").append($('').val(obj.MaterialCode).html( HSNCODE + obj.MaterialName+ " ( "+obj.MaterialCode+" ) ")); } } @@ -4802,6 +4810,14 @@ $(document).ready(function () { var costCode = $('#CostCenter').val(); var materialCode = $('#MaterialCode').val(); + var selectedText = $('#MaterialCode option:selected').text(); + var parts = selectedText.split('-'); + var HSN = selectedText.includes('-') && /^\d+$/.test(parts[0].trim()) + ? parts[0].trim() + : ''; + + + var materialName = $("#CapitalItemName").val(); var uom = $("#CPUOM").val(); var addPer = ''; @@ -4942,8 +4958,9 @@ $(document).ready(function () {
${temp} ${Reqnumber} ${materialCode}${shorten}${shorten}${HSN}- @@ -5466,9 +5483,8 @@ $(document).ready(function () { if (value.MaterialCode == materialCode) { - - - $("#MaterialCode").append($('').val(value.MaterialCode).html(value.MaterialCode + "-" + value.MaterialName)); + var HSNCODE = value.HSNCODE ? value.HSNCODE+"-" : ""; + $("#MaterialCode").append($('').val(value.MaterialCode).html( HSNCODE + value.MaterialName+ " ( "+value.MaterialCode+" ) ")); } @@ -5835,7 +5851,7 @@ $(document).ready(function () { $('#EditCustomDutyExpenses').val($('#CustomDutyExpenses' + userid).val()); //$('#txtEditInsurance').val($('#RMCIncludingCustomers'+userid).val()); - $('#EdittxtTotalOrderValue').val(cellval[10].innerHTML); + $('#EdittxtTotalOrderValue').val(cellval[11].innerHTML); @@ -5887,13 +5903,25 @@ $(document).ready(function () { var Material = ; $("#EditMaterialCode").empty(); + var P0 = cellval[4].innerHTML; + var P1 = (P0) ? P0 + " - " : ""; + var P2 = P1 + $('#materialName' + userid).val() ; + var P3 = P2 + " ( " + $('#materialCode' + userid).val() + ' ) '; - $("#EditMaterialCode").append($('').val($('#materialCode' + userid).val()).html($('#materialCode' + userid).val() + "-" + $('#materialName' + userid).val())); + $("#EditMaterialCode").append($('') + .val($('#materialCode' + userid).val()) + .html(P3) + .prop('selected', true) + ); + + // $("#EditMaterialCode").append($('').val($('#materialCode' + userid).val()).html($('#materialCode' + userid).val() + "-" + $('#materialName' + userid).val())); for (i = 0; i < Material.length; i++) { $.each(Material[i], function(idx, obj) { if (obj.MaterialCode != $('#materialCode' + userid).val()) { - $("#EditMaterialCode").append($('').val(obj.MaterialCode).html(obj.MaterialCode + "-" + obj.MaterialName)); + // $("#EditMaterialCode").append($('').val(obj.MaterialCode).html(obj.MaterialCode + "-" + obj.MaterialName)); + var HSN = (obj.HSNCODE) ? obj.HSNCODE+" - " : ""; + $("#EditMaterialCode").append($('').val(obj.MaterialCode).html(HSN + obj.MaterialName + " ( "+obj.MaterialCode+" ) ")); } }); @@ -5942,7 +5970,7 @@ $(document).ready(function () { $('#ViewAfterSgst').val($('#AfterSgst' + userid).val()); $('#ViewAfterIgst').val($('#AfterIgst' + userid).val()); $('#ViewOtherAllowances').val($('#OtherAmt' + userid).val()); - $('#ViewTotalAmountlocal').val(cellval[10].innerHTML); + $('#ViewTotalAmountlocal').val(cellval[11].innerHTML); $('#drpFreightviewloc').val($("#Ftype" + userid).val()); @@ -6555,12 +6583,12 @@ $(document).ready(function () { var itemRate = parseFloat(convertRate).toFixed(2); var basicval = $("#EditCPTotalAmount").val(); var Cgst = $("#EditCgst").val(); - var AfterCgst = $("#EditAfterCgst").val(); + var AfterCgst = $("#EditAfterCgst").val() == '' ? 0 : $("#EditAfterCgst").val(); var Sgst = $("#EditSgst").val(); - var AfterSgst = $("#EditAfterSgst").val(); + var AfterSgst = $("#EditAfterSgst").val() == '' ? 0 : $("#EditAfterSgst").val(); var Igst = $("#EditIgst").val(); //Dom Caps - var AfterIgst = $("#EditAfterIgst").val(); //Dom Caps - var OtherAmt = parseFloat($("#EditOtherAllowances").val() == '' ? "0.00" : $('#EditOtherAllowances').val()).toFixed(2); + var AfterIgst = $("#EditAfterIgst").val() == '' ? 0 :$("#EditAfterIgst").val(); //Dom Caps + var OtherAmt = parseFloat($("#EditOtherAllowances").val() == '' ? 0 : $('#EditOtherAllowances').val()).toFixed(2); var TotalTaxValue = EditcalculateTaxValue(); @@ -6601,7 +6629,7 @@ $(document).ready(function () { var NoOfTrip = $("#EditNOOfTrips").val(); var DisType = $("#EditDiscountType").val(); var DisVal = $("#txtEditDiscount").val(); - var AfterDisVal = $("#txtEditAfterDiscount").val(); + var AfterDisVal = $("#txtEditAfterDiscount").val() == '' ? 0 : $("#txtEditAfterDiscount").val(); @@ -6618,13 +6646,10 @@ $(document).ready(function () { var FreightTypeloc = $('#drpFreighteditloc').val(); var FreightRateloc = $('#txtFreightlocedit').val(); - var FreightRateAmountloc = $('#txtAfterFreightlocedit').val(); + var FreightRateAmountloc = $('#txtAfterFreightlocedit').val() == '' ? 0 : $('#txtAfterFreightlocedit').val(); var Nooftriploc = $('#NOOfTripslocedit').val(); - - - var Total = (parseFloat(basicval) + parseFloat(AfterCgst) + parseFloat(AfterSgst) + parseFloat(AfterIgst) + parseFloat(OtherAmt) - parseFloat(AfterDisVal) + parseFloat(FreightRateAmountloc)).toFixed(2); if (capital == 0) { @@ -6715,19 +6740,24 @@ $(document).ready(function () { $('#DutyImpact' + userid).val(DutyImpact); $('#NetValue' + userid).val(Nett); $('#ClearingCharge' + userid).val(ClearingCharges); + var editselectedText = $('#EditMaterialCode option:selected').text(); + var editparts = editselectedText.split('-'); + var editHSN = editselectedText.includes('-') && /^\d+$/.test(editparts[0].trim()) + ? editparts[0].trim() + : ''; var shorten = materialName.length > 13 ? materialName.slice(0, 13) + "..." : materialName; cellval[2].innerHTML = materialCode; cellval[3].innerHTML = shorten; - - cellval[5].innerHTML = quantity; - cellval[6].innerHTML = uom; - cellval[7].innerHTML = parseFloat(itemRate).toFixed(2); - cellval[8].innerHTML = parseFloat(basicval).toFixed(2); - cellval[9].innerHTML = parseFloat(TotalTaxValue).toFixed(2); // what should i display here ?? if international means - cellval[10].innerHTML = parseFloat(Total).toFixed(2); + cellval[4].innerHTML = editHSN; + cellval[6].innerHTML = quantity; + cellval[7].innerHTML = uom; + cellval[8].innerHTML = parseFloat(itemRate).toFixed(2); + cellval[9].innerHTML = parseFloat(basicval).toFixed(2); + cellval[10].innerHTML = parseFloat(TotalTaxValue).toFixed(2); // what should i display here ?? if international means + cellval[11].innerHTML = parseFloat(Total).toFixed(2); diff --git a/app/Views/editEmployeenew.php b/app/Views/editEmployeenew.php index bac2778f..843f654d 100755 --- a/app/Views/editEmployeenew.php +++ b/app/Views/editEmployeenew.php @@ -1307,7 +1307,7 @@ if (!empty($EmpDetails)) { diff --git a/app/Views/editImportAmendPO.php b/app/Views/editImportAmendPO.php index 1500d30e..ef18e6f4 100755 --- a/app/Views/editImportAmendPO.php +++ b/app/Views/editImportAmendPO.php @@ -302,11 +302,23 @@ if (!empty($RequistionDetails)) { > \ No newline at end of file diff --git a/app/Views/editOldasset.php b/app/Views/editOldasset.php index 35c903af..76d7c852 100755 --- a/app/Views/editOldasset.php +++ b/app/Views/editOldasset.php @@ -272,7 +272,7 @@ if (!empty($assetList)) {
Cancel - +
diff --git a/app/Views/editRawmaterial.php b/app/Views/editRawmaterial.php index e29874fd..48b5e391 100755 --- a/app/Views/editRawmaterial.php +++ b/app/Views/editRawmaterial.php @@ -113,7 +113,7 @@ if ($total <= $reorder) {

Edit Material - Details

-
@@ -361,10 +361,12 @@ if ($total <= $reorder) {
diff --git a/app/Views/editRevenueAmendPO.php b/app/Views/editRevenueAmendPO.php index 5fd2ce98..313819a3 100755 --- a/app/Views/editRevenueAmendPO.php +++ b/app/Views/editRevenueAmendPO.php @@ -234,6 +234,11 @@ if (!empty($INRSYMBOL)) { menubar: false, statusbar: false, toolbar: false, + setup: function(ed) { + ed.on('init', function(evt) { + ed.setContent(``); + }); + } //plugins: "link image" }); tinymce.init({ @@ -1316,6 +1321,7 @@ if (!empty($INRSYMBOL)) {
SNo Requisition No Item DescriptionHSN/SAC Line Item Specs Quantity UOMReqNo ?> MaterialName, 0, 13, "..."); echo $shortName; ?>HSNCODE ?>
- 'txtSpcialInstruction', 'id' => 'txtSpcialInstruction', 'value' => set_value('txtSpcialInstruction', strip_tags($ServiceDescription)), 'rows' => '8', 'class' => 'form-control'); - echo form_textarea($data); - ?> + +
@@ -1679,7 +1686,7 @@ if (!empty($INRSYMBOL)) { Previous Upload -
     - + @@ -1733,9 +1740,9 @@ if (!empty($INRSYMBOL)) { @@ -2163,7 +2170,7 @@ if (!empty($INRSYMBOL)) { @@ -2344,16 +2351,16 @@ if (!empty($INRSYMBOL)) { $(document).ready(function () { var tempUserId = 0; var index = '1'; - var userid = ''; + var userid = ''; $("#EDITREVENUE").on("shown.bs.modal", function (e) { var AvlBudAmt = ''; AvlBudAmt = ''; userid = $(e.relatedTarget).data('userid'); + $('#isEdit').val(1); $('#isEdit').val(1); - if (tempUserId == 0) { var tr = document.getElementById(userid); var cellval = tr.cells; var id = $('#Reqnumber' + userid).val(); @@ -2364,6 +2371,7 @@ if (!empty($INRSYMBOL)) { $('#EditAvlBudAmt').val(AvlBudAmt); $('#EditMaterialCode').val($('#materialCode' + userid).val()); + $('#EditItemName').val($('#materialName' + userid).val()); $('#EditUOM').val($('#uom' + userid).val()); $('#EditQuantity').val($('#quantity' + userid).val()); @@ -2372,7 +2380,7 @@ if (!empty($INRSYMBOL)) { var EdititemRate = parseFloat($('#itemRate' + userid).val()).toFixed(2); $('#EditRate').val(EdititemRate); - $('#txtEditBasicValue').val(parseFloat(cellval[7].innerHTML).toFixed(2)); + $('#txtEditBasicValue').val(parseFloat(cellval[8].innerHTML).toFixed(2)); RequistQuantity = $('#quantity' + userid).val(); $('#txtEditDiscount').val($('#DisVal' + userid).val()); $('#txtEditAfterDiscount').val($('#AfterDisVal' + userid).val()); @@ -2400,7 +2408,16 @@ if (!empty($INRSYMBOL)) { $("#EditMaterialCode").empty(); var Material = ; // For Binding Material list center for the selected Requistion Number - $("#EditMaterialCode").append($('').val($('#materialCode' + userid).val()).html($('#materialCode' + userid).val() + "-" + $('#materialName' + userid).val())); + var P0 = cellval[3].innerHTML; + var P1 = (P0) ? P0 + " - " : ""; + var P2 = P1 + $('#materialName' + userid).val() ; + var P3 = P2 + " ( " + $('#materialCode' + userid).val() + ' ) '; + + $("#EditMaterialCode").append($('') + .val($('#materialCode' + userid).val()) + .html(P3) + .prop('selected', true) + ); var isAdded = "0"; for (i = 0; i < Material.length; i++) { $.each(Material[i], function (idx, obj) { @@ -2416,7 +2433,8 @@ if (!empty($INRSYMBOL)) { } }); if (isAdded == "0") { - $("#EditMaterialCode").append($('').val(obj.MaterialCode).html(obj.MaterialCode + "-" + obj.MaterialName)); + var HSNCODE = obj.HSNCODE ? obj.HSNCODE+" - " : ""; + $("#EditMaterialCode").append($('').val(obj.MaterialCode).html( HSNCODE + obj.MaterialName+ " ( "+obj.MaterialCode+" ) ")); } } }); @@ -2428,7 +2446,7 @@ if (!empty($INRSYMBOL)) { $("input:radio[name='optExcise'][value='" + $('#ExciseOption' + userid).val() + "']").prop('checked', 'checked'); $("input:radio[name='optVat'][value='" + $('#VatOption' + userid).val() + "']").prop('checked', 'checked'); $("input:radio[name='optCST'][value='" + $('#CSTOption' + userid).val() + "']").prop('checked', 'checked'); - } + if (userid) { tempUserId = userid; @@ -2487,18 +2505,23 @@ if (!empty($INRSYMBOL)) { var TotalOrderValue = $("#txtEditTotalOrderValue").val(); var Service_Description = $("#Edit_Service_Description").val(); var TotalTaxValue = calculateEditTaxValue(); + var editselectedText = $('#EditMaterialCode option:selected').text(); + var editparts = editselectedText.split('-'); + var editHSN = editselectedText.includes('-') && /^\d+$/.test(editparts[0].trim()) + ? editparts[0].trim() + : ''; var tr = document.getElementById(userid); var cellval = tr.cells; var shorten = editDescription.length > 13 ? editDescription.slice(0, 13) + "..." : editDescription; cellval[2].innerHTML = shorten; - - cellval[4].innerHTML = parseFloat(editQuantity).toFixed(2); - cellval[5].innerHTML = editUOM; - cellval[6].innerHTML = parseFloat(itemRate).toFixed(2); - cellval[7].innerHTML = parseFloat(basicval).toFixed(2); - cellval[8].innerHTML = parseFloat(TotalTaxValue).toFixed(2); - cellval[9].innerHTML = parseFloat(TotalOrderValue).toFixed(2); + cellval[3].innerHTML = editHSN; + cellval[5].innerHTML = parseFloat(editQuantity).toFixed(2); + cellval[6].innerHTML = editUOM; + cellval[7].innerHTML = parseFloat(itemRate).toFixed(2); + cellval[8].innerHTML = parseFloat(basicval).toFixed(2); + cellval[9].innerHTML = parseFloat(TotalTaxValue).toFixed(2); + cellval[10].innerHTML = parseFloat(TotalOrderValue).toFixed(2); $('#materialCode' + userid).val(editMaterialCode); $('#materialName' + userid).val(editDescription); @@ -2865,7 +2888,7 @@ if (!empty($INRSYMBOL)) { + + diff --git a/app/Views/employeeListing.php b/app/Views/employeeListing.php index 4f567c38..bdf32fc3 100755 --- a/app/Views/employeeListing.php +++ b/app/Views/employeeListing.php @@ -90,7 +90,7 @@
-
+
- Add New Employee +
@@ -222,9 +225,7 @@ var table = $('#datatable').DataTable({ dom: 'Blfrtip', - buttons: [ - 'excel', 'pdf' - ], + buttons: [ 'pdf' ], pageLength: 10, lengthMenu: [ [10, 20, 30, 50, -1], [10, 20, 30, 50, "All"] ], // Rows per page options responsive: false, diff --git a/app/Views/gasCylinderReturned.php b/app/Views/gasCylinderReturned.php index 9ea0eb9d..a4bca007 100644 --- a/app/Views/gasCylinderReturned.php +++ b/app/Views/gasCylinderReturned.php @@ -3,17 +3,15 @@ @@ -148,14 +148,14 @@
-
- -
+
+ +
@@ -171,30 +171,30 @@
-
- - - + - - + + - - - - - -
-
-
+ + + + + + + + +
+ +
@@ -203,76 +203,92 @@ - - + + - + - + - - + + + - + + - -

No Gas Cylinder Returned in the Given Dates..!!

- + +

No Gas Cylinder Returned in the Given Dates..!!

+ - $gasCylinder): - $gasCylinder['MaterialRcvdDate'] = date('d-m-Y',strtotime($gasCylinder['MaterialRcvdDate'])); - $gasCylinder['DeliveryChellanDate'] = date('d-m-Y',strtotime($gasCylinder['DeliveryChellanDate'])); - $gasCylinder['emptyCylinderDate'] = date('d-m-Y',strtotime($gasCylinder['emptyCylinderDate'])); - ?> + $gasCylinder): + $gasCylinder['MaterialRcvdDate'] = date('d-m-Y', strtotime($gasCylinder['MaterialRcvdDate'])); + $gasCylinder['DeliveryChellanDate'] = date('d-m-Y', strtotime($gasCylinder['DeliveryChellanDate'])); + $gasCylinder['emptyCylinderDate'] = date('d-m-Y', strtotime($gasCylinder['emptyCylinderDate'])); + ?> - - - - - - - - - - - - - - - - - + - + + + + + + - - - - + + + + + + + + + - - - - - + + + + + + + + + + + + +
Full Cylinder DateFull Cylinder Date IGR NoSupplierSupplier Bill/Invoice No Cylinder Name Gross Weight Empty Cylinder DateTare WeightNet WeightTare WeightNet Weight Actual Weight ShortageCylinder Count Cylinder Pending Bill Date Driver Name Vehicle NoDownload
+ +
+
+ +
+
@@ -304,31 +320,41 @@ console.log("Received date string:", dateString); // Split the date string into date and time components - var dateTimeParts = dateString.split(' '); - var dateParts = dateTimeParts[0].split('-'); - var timeParts = dateTimeParts[1].split(':'); + var dateTimeParts = dateString?.split(' '); + var dateParts = dateTimeParts[0]?.split('-'); + var timeParts = dateTimeParts[1]?.split(':'); // Extract individual components var year = parseInt(dateParts[0], 10); var month = parseInt(dateParts[1], 10) - 1; // Months are zero-based in JavaScript var day = parseInt(dateParts[2], 10); - var hours = parseInt(timeParts[0], 10); - var minutes = parseInt(timeParts[1], 10); - var seconds = parseInt(timeParts[2], 10); + var hours = 0; + var minutes = 0; + var seconds = 0; + + + if(timeParts){ + // Extract time components + hours = parseInt(timeParts[0], 10); + minutes = parseInt(timeParts[1], 10); + seconds = parseInt(timeParts[2], 10); + } + // Create a new Date object var date = new Date(year, month, day, hours, minutes, seconds); // Extract date components - var day = date.getDate().toString().padStart(2, '0'); - var month = (date.getMonth() + 1).toString().padStart(2, '0'); // Months are zero-based - var year = date.getFullYear(); + day = date.getDate().toString().padStart(2, '0'); + month = (date.getMonth() + 1).toString().padStart(2, '0'); // Months are zero-based + year = date.getFullYear(); // Extract time components - var hours = date.getHours().toString().padStart(2, '0'); - var minutes = date.getMinutes().toString().padStart(2, '0'); - var seconds = date.getSeconds().toString().padStart(2, '0'); + hours = date.getHours().toString().padStart(2, '0'); + minutes = date.getMinutes().toString().padStart(2, '0'); + seconds = date.getSeconds().toString().padStart(2, '0'); + var formattedDate = ''; // Format the date and time in DD-MM-YYYY HH:MM:SS format if (flag == 1) { @@ -355,9 +381,8 @@ + let fromDateObj = new Date(fromDate.split('-').reverse().join('-')); + let toDateObj = new Date(toDate.split('-').reverse().join('-')); + if (fromDateObj > toDateObj) { + alert('Incorrect Date Applied For Filter..!!'); + $('#toDate').attr('min', fromDate); + $('#toDate').val(''); - - - - - - - - - - - - - - - + if (cylinderPendingCount > 0) { + alert("Please clear the " + cylinderPendingCount + " pending cylinders before downloading the Excel file."); + return false; + } + $("#loader").show(); + $.ajax({ + type: "POST", + url: "gasCylindersByIgr", + data: { + IGRNO: igrNo + }, + success: function(response) { + $("#loader").hide(); + if (response.status === "success") { + console.log(response.data); // Debugging - Check if data is correct + + let tableHTML = ` + + + + + + + + + + + + + + + + + + + + + `; + + let totalShortage = 0; + let totalNetWeight = 0; + let totalActualWeight = 0; + + response.data.forEach(item => { + + totalShortage += Number(item.shortage); + + totalNetWeight += Number(item.netWeight); + + totalActualWeight += Number(item.actualWeight); + + item.fullCylinderDate = formatDateTime(item.fullCylinderDate, 1); + item.emptyCylinderDate = formatDateTime(item.emptyCylinderDate, 1); + item.DeliveryChellanDate = formatDateTime(item.DeliveryChellanDate, 1); + + tableHTML += ` + + + + + + + + + + + + + + + + + + `; + }); + + tableHTML += ` + + + + + + + + + + + + + + + + + + + + + +
IGRNOFull Cylinder DateCylinder NoGross WeightEmpty Cylinder Return DateTare WeightNet WeightActual WeightShortageBill NoBill DateDriver NameVehicle No
${item.IGRNO}${item.fullCylinderDate}${item.cylinderNo}${item.grossWeight}${item.emptyCylinderDate}${item.tareWeight}${item.netWeight}${item.actualWeight}${item.shortage}${item.invoiceNo}${item.DeliveryChellanDate}${item.DriverName}${item.VehicleNo}
 
Weight${totalNetWeight}${totalActualWeight}${totalShortage}
+ `; + + $("#excelTableDiv").html(tableHTML); + + let table = document.getElementById('excelTable'); + + let filename = "GasCylinderReturned_" + igrNo + ".xlsx"; + + let rows = []; + + // Extract table data row-by-row + $(table).find('tr').each(function(rowIndex) { + let rowData = []; + + $(this).find('th, td').each(function(colIndex) { + // Skip hidden columns + if ($(this).css('display') === 'none') return; + let cellText = $(this).text().trim(); + rowData.push(cellText); + }); + + // Add the cleaned row only if it has data + if (rowData.length > 0) { + rows.push(rowData); + } + }); + + // Create a worksheet from array (no DOM needed!) + let ws = XLSX.utils.aoa_to_sheet(rows); + + // Define column widths (in character units) + const columnWidth = 15; // Set your desired width here + const wscols = []; + for (let i = 0; i < Object.keys(response.data[0]).length; i++) { + wscols.push({ + wch: columnWidth + }); + } + ws['!cols'] = wscols; + + let wb = XLSX.utils.book_new(); + XLSX.utils.book_append_sheet(wb, ws, 'Sheet1'); + XLSX.writeFile(wb, filename || 'export.xlsx'); + } + }, + + error: function(xhr, status, error) { + console.log(xhr.responseText); + alert("Something went wrong! Please try again."); + }, + complete: function() { + console.log("AJAX request completed."); + $("#loader").hide(); // Hide loader + } + }); + } + \ No newline at end of file diff --git a/app/Views/importpo.php b/app/Views/importpo.php index 56790240..4d034d64 100755 --- a/app/Views/importpo.php +++ b/app/Views/importpo.php @@ -322,10 +322,19 @@ if (isset($AvlimportBudAmt) && !empty($AvlimportBudAmt)) { $('#editTripsValue').hide(); } $('#EditPer').val($('#Per' + userid).val()); - $('#EditTotalOrderValue').val(cellval[9].innerHTML); + $('#EditTotalOrderValue').val(cellval[10].innerHTML); $("#EditMaterialCode").empty(); var Material = ; - $("#EditMaterialCode").append($('').val($('#materialCode' + userid).val()).html($('#materialCode' + userid).val() + "-" + $('#materialName' + userid).val())); + var P0 = cellval[4].innerHTML; + var P1 = (P0) ? P0 + " - " : ""; + var P2 = P1 + $('#materialName' + userid).val() ; + var P3 = P2 + " ( " + $('#materialCode' + userid).val() + ' ) '; + + $("#EditMaterialCode").append($('') + .val($('#materialCode' + userid).val()) + .html(P3) + .prop('selected', true) + ); var isAdded = "0"; for (i = 0; i < Material.length; i++) { $.each(Material[i], function(idx, obj) { @@ -341,7 +350,9 @@ if (isset($AvlimportBudAmt) && !empty($AvlimportBudAmt)) { } }); if (isAdded == "0") { - $("#EditMaterialCode").append($('').val(obj.MaterialCode).html(obj.MaterialCode + "-" + obj.MaterialName)); + var HSNCODE = obj.HSNCODE ? obj.HSNCODE+" - " : ""; + $("#EditMaterialCode").append($('').val(obj.MaterialCode).html( HSNCODE + obj.MaterialName+ " ( "+obj.MaterialCode+" ) ")); + // $("#EditMaterialCode").append($('').val(obj.MaterialCode).html(obj.MaterialCode + "-" + obj.MaterialName)); } } }); @@ -842,6 +853,7 @@ if (isset($AvlimportBudAmt) && !empty($AvlimportBudAmt)) {
Requisition No Item Code Item DescriptionHSN/SAC Line Item Specs Quantity UOM${Reqnumber} ${materialCode} ${shorten}${HSN} - @@ -3873,13 +3895,20 @@ if (isset($AvlimportBudAmt) && !empty($AvlimportBudAmt)) { if (FreightTypename != "PER TRIP") { Nooftrip = ''; } + + var editselectedText = $('#EditMaterialCode option:selected').text(); + var editparts = editselectedText.split('-'); + var editHSN = editselectedText.includes('-') && /^\d+$/.test(editparts[0].trim()) + ? editparts[0].trim() + : ''; var tr = document.getElementById(userid); var cellval = tr.cells; - cellval[5].innerHTML = editQuantity; - cellval[6].innerHTML = editUOM; - cellval[7].innerHTML = itemRate; - cellval[8].innerHTML = BasicValue; + cellval[4].innerHTML = editHSN; + cellval[6].innerHTML = editQuantity; + cellval[7].innerHTML = editUOM; + cellval[8].innerHTML = itemRate; + cellval[9].innerHTML = BasicValue; $('#materialCode' + userid).val(editMaterialCode); $('#materialName' + userid).val(edititemname); diff --git a/app/Views/includes/new_footer.php b/app/Views/includes/new_footer.php index 0d2c6d92..25454a4a 100755 --- a/app/Views/includes/new_footer.php +++ b/app/Views/includes/new_footer.php @@ -155,6 +155,39 @@ + + @@ -380,10 +413,10 @@ $('#MaterialRcvdDate').focus(); return false; } else if (Noval == 0) { - alert('Invoice Quantity is Empty.Please Enter the value'); + alert('Invoice Quantity is Missing. Kindly Enter the Value'); return false; } else if (isExceed == 1 && formatted_IsOpenOrder == 0) { - alert("Invoice Quantity is exceeding the Ordered Quantity.Please Contact Purchase Team for further Process ") + alert("Invoice Quantity is exceeding the Ordered Quantity. Please Contact Purchase Team for further Process ") return false; } else { return true; @@ -466,6 +499,7 @@ '' + j + '' + item.MaterialCode + '' + item.MaterialName + '' + ((item.HSNCODE) ? item.HSNCODE : '') + '' + Number(item.Rate).toFixed(2) + '' + item.UOM + '' + item.Quantity + '' + j + '' + item.MaterialCode + '' + item.MaterialName + '' + ((item.HSNCODE) ? item.HSNCODE : '') + '' + Number(item.Rate).toFixed(2) + '' + item.UOM + '' + item.Quantity + ' - + + - payroll_id)) { echo "contenteditable='true';"; } ?> payroll_id)) { ?> title="Payslip Calculated" style="text-align:right;color:blue;" @@ -632,7 +639,7 @@ - + - \ No newline at end of file diff --git a/app/Views/requisitionlisting.php b/app/Views/requisitionlisting.php index 8cc36bac..d0b5beec 100755 --- a/app/Views/requisitionlisting.php +++ b/app/Views/requisitionlisting.php @@ -111,10 +111,10 @@ if (!empty($Status)) { - Raise New Requisition + Raise New Requisition 0) { ?> -

The Requisition No is in Draft +

The Requisition No is in Draft status. Please act on the requisition.Then only you can raise New Requisition.

@@ -170,13 +170,13 @@ if (!empty($Status)) {
newLineItem ?>StatusName); ?>StatusName); ?>     -     Requisition No Item Code Item DescriptionHSN/SAC Line Item Specs Quantity UOM${Reqnumber} ${materialCode} ${shorten}${HSN} - diff --git a/app/Views/stock/CoatingMachineDetail.php b/app/Views/stock/CoatingMachineDetail.php index 60aff806..1d1a29a4 100644 --- a/app/Views/stock/CoatingMachineDetail.php +++ b/app/Views/stock/CoatingMachineDetail.php @@ -335,7 +335,11 @@ - getFlashdata('error')): ?> + getFlashdata('error')): ?>
getFlashdata('error'); ?>
@@ -361,9 +365,7 @@ " class="form-control " - data-provide="datepicker" - data-date-format="M-yyyy" - data-date-min-view-mode="1" readonly> + readonly> @@ -393,12 +395,12 @@ - @@ -840,7 +842,7 @@
-
+

@@ -857,7 +859,7 @@
@@ -999,15 +1001,15 @@
@@ -1077,11 +1079,11 @@ - - (A) (A) (A) (A)
+ Total +
Gas Per Ton Qty Per Hrs (Metric Ton) Moisture Loss Qty (Metric Ton)Dust Qty (Metric Ton)Dust Qty (Kgs) Customer Name - + - + Consumption Sand Dried Qty Sand Dried Qty(MT) ConsumptionSand Coated Qty Sand Coated Qty(Kg) Panel Consumption Physical Consumption Ton
+ Total +
@@ -826,9 +902,8 @@ var updateGasStockDetails = tableToJson(); - alert('Updation may take a while, And we appreciate your patience..!!'); + showMessage('Updation may take a while, And we appreciate your patience..!!'); - $('#loader').show(); $.ajax({ data: { updateGasStockDetails @@ -838,22 +913,19 @@ success: function(data) { if (data) { - $('#loader').hide(); - console.log(data); - alert(data); - window.location.reload(); + showMessage(data); } }, error: function(xhr, status, error) { - alert("An error occurred while processing the request. Please try again."); + showMessage("An error occurred while processing the request. Please try again."); console.error("Error Code:", xhr.status); console.error("Error Message:", error); console.error("Response Text:", xhr.responseText); }, complete: function() { - $('#loader').hide(); + console.log("Request completed."); } }); @@ -900,6 +972,14 @@ function openingStockChange(tdElement) { try { + + let basicCheck =checkIsNumber(tdElement.innerText.trim()); + + if(basicCheck == 0){ + alert("Kindly Enter Numbers only..!!"); + return ; + } + let dataId = tdElement.getAttribute('data-id'); let date = dataId; let openingStock = validateInput(tdElement.innerText); @@ -912,7 +992,16 @@ document.querySelector(`td.total[data-id="${dataId}"]`).innerText = totalGas; document.querySelector(`td.balanceStock[data-id="${dataId}"]`).innerText = currentBalanceStock; - updateStockValue(date, currentBalanceStock) + updateStockValue(date, currentBalanceStock); + + let table = document.getElementById('gasStockDetailsTableId'); + let column2 = "openingStock"; + let column3 = "total"; + let column4 = "balanceStock"; + + calculateTotal(table,dataId,column2); + calculateTotal(table,dataId,column3); + calculateTotal(table,dataId,column4); } catch (error) { @@ -924,6 +1013,14 @@ function purchaseBharathStockChange(tdElement) { try { + + let basicCheck =checkIsNumber(tdElement.innerText.trim()); + + if(basicCheck == 0){ + alert("Kindly Enter Numbers only..!!"); + return ; + } + let dataId = tdElement.getAttribute('data-id'); let date = dataId; let openingStock = validateInput(document.querySelector(`td.openingStock[data-id="${dataId}"]`).innerText); @@ -936,7 +1033,18 @@ document.querySelector(`td.total[data-id="${dataId}"]`).innerText = totalGas; document.querySelector(`td.balanceStock[data-id="${dataId}"]`).innerText = currentBalanceStock; - updateStockValue(date, currentBalanceStock) + updateStockValue(date, currentBalanceStock); + + let table = document.getElementById('gasStockDetailsTableId'); + let column1 = 'purchaseBharath'; + let column2 = "openingStock"; + let column3 = "total"; + let column4 = "balanceStock"; + + calculateTotal(table,dataId,column1); + calculateTotal(table,dataId,column2); + calculateTotal(table,dataId,column3); + calculateTotal(table,dataId,column4); } catch (error) { @@ -949,6 +1057,14 @@ function purchaseIndianStockChange(tdElement) { try { + + let basicCheck =checkIsNumber(tdElement.innerText.trim()); + + if(basicCheck == 0){ + alert("Kindly Enter Numbers only..!!"); + return ; + } + let dataId = tdElement.getAttribute('data-id'); let date = dataId; let openingStock = validateInput(document.querySelector(`td.openingStock[data-id="${dataId}"]`).innerText); @@ -961,7 +1077,19 @@ document.querySelector(`td.total[data-id="${dataId}"]`).innerText = totalGas; document.querySelector(`td.balanceStock[data-id="${dataId}"]`).innerText = currentBalanceStock; - updateStockValue(date, currentBalanceStock) + updateStockValue(date, currentBalanceStock); + + let table = document.getElementById('gasStockDetailsTableId') ; + let column1 = 'purchaseIndian' ; + let column2 = "openingStock" ; + let column3 = "total" ; + let column4 = "balanceStock" ; + + calculateTotal(table,dataId,column1); + calculateTotal(table,dataId,column2); + calculateTotal(table,dataId,column3); + calculateTotal(table,dataId,column4); + } catch (error) { @@ -974,18 +1102,29 @@ function gasConsumptionChange(tdElement) { try { + + let basicCheck =checkIsNumber(tdElement.innerText.trim()); + + if(basicCheck == 0){ + alert("Kindly Enter Numbers only..!!"); + return ; + } + let dataId = tdElement.getAttribute('data-id'); let date = dataId; //total gas consumption - let tenTonGasConsumption = validateInput(document.querySelector(`td.tenTonGasConsumption[data-id="${dataId}"]`).innerText); - let coatingGasConsumption = validateInput(document.querySelector(`td.coatingGasConsumption[data-id="${dataId}"]`).innerText); - let trpPanelGasConsumption = validateInput(document.querySelector(`td.trpPanelGasConsumption[data-id="${dataId}"]`).innerText); - let trpPhysicalGasConsumption = validateInput(document.querySelector(`td.trpPhysicalGasConsumption[data-id="${dataId}"]`).innerText); - let rotaryGasConsumption = validateInput(document.querySelector(`td.rotaryGasConsumption[data-id="${dataId}"]`).innerText); - - let toatalGasConsumption = Number(tenTonGasConsumption) + Number(coatingGasConsumption) + Number(trpPhysicalGasConsumption) + - Number(trpPanelGasConsumption) + Number(rotaryGasConsumption); + let tenTonGasConsumption = validateInput(document.querySelector(`td.tenTonGasConsumption[data-id="${dataId}"]`).innerText); + let coatingGasConsumption = validateInput(document.querySelector(`td.coatingGasConsumption[data-id="${dataId}"]`).innerText); + let trpPanelGasConsumption = validateInput(document.querySelector(`td.trpPanelGasConsumption[data-id="${dataId}"]`).innerText); + let trpPhysicalGasConsumption = validateInput(document.querySelector(`td.trpPhysicalGasConsumption[data-id="${dataId}"]`).innerText); + let rotaryGasConsumption = validateInput(document.querySelector(`td.rotaryGasConsumption[data-id="${dataId}"]`).innerText); + + let toatalGasConsumption = Number(tenTonGasConsumption) + Number(coatingGasConsumption) + + Number(trpPhysicalGasConsumption) + // + Number(trpPanelGasConsumption) + //panel gas is not used in consumption calculation but needed its value in sheet..!! + + Number(rotaryGasConsumption); //total gas purchase and opening addition @@ -1001,13 +1140,38 @@ document.querySelector(`td.consumption[data-id="${dataId}"]`).innerText = toatalGasConsumption; document.querySelector(`td.balanceStock[data-id="${dataId}"]`).innerText = currentBalanceStock; - updateStockValue(date, currentBalanceStock) + updateStockValue(date, currentBalanceStock); + + let table = document.getElementById('gasStockDetailsTableId'); + let column1 = tdElement.className.split(' ')[1]; + let column2 = "openingStock"; + let column3 = "total"; + let column4 = "balanceStock"; + let column5 = "consumption"; + + calculateTotal(table,dataId,column5); + calculateTotal(table,dataId,column1); + calculateTotal(table,dataId,column2); + calculateTotal(table,dataId,column3); + calculateTotal(table,dataId,column4); + + } catch (error) { console.error("There is an error updating stock ..!!" + error); } } + + function checkIsNumber(input) { + + const isValid = /^-?\d*\.?\d*$/.test(input); + + if (!isValid) { + return 0; + } + } + + @@ -1337,4 +1518,99 @@ + + + + + + \ No newline at end of file diff --git a/app/Views/stock/incomingSilicaSandDetails.php b/app/Views/stock/incomingSilicaSandDetails.php index e2afc565..b2b64690 100644 --- a/app/Views/stock/incomingSilicaSandDetails.php +++ b/app/Views/stock/incomingSilicaSandDetails.php @@ -325,9 +325,6 @@ " class="form-control " - data-provide="datepicker" - data-date-format="M-yyyy" - data-date-min-view-mode="1" readonly> @@ -353,12 +350,12 @@ - @@ -720,7 +717,7 @@ " + class="form-control mt-2" style="z-index:30;" readonly> @@ -374,17 +394,17 @@ foreach ($period as $day) { + id="powerConsumptionExport"> - @@ -590,19 +610,17 @@ foreach ($period as $day) { foreach ($groupedPowerConsumptionStockDetails as $groupedIndex => $powerStockDetails) { + $currentDate = date('Y-m-d'); - - ?> - + " format('d-m-Y'); - if ($dateInMonthDmYFormat === $currentDate) { - echo 'style="background: #cef0ad;"'; - } - ?>> + if ($powerStockDetails[0]['date'] === $currentDate) { + echo 'style="background: #cef0ad;"'; + } + ?> + > "-", 'closing_units' => 0, 'total_units' => 0, + 'machine_id' => $machineId, ]; } @@ -797,22 +816,48 @@ foreach ($period as $day) { Total - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + - - - + + + - + - $dateInMonth) { ?> - format('d-m-Y'); - if ($dateInMonthDmYFormat === $currentDate) { - echo 'style="background: #cef0ad;"'; - } - ?>> - - format('d-m-Y'); + $dateInMonth) { + $currentDate = date('Y-m-d'); + ?> - - - + " + + > + + format('d-m-Y'); + + ?> + + + + - + - oninput="openingTPStockChange(this)" - contenteditable="true" + oninput="openingTPStockChange(this)" + contenteditable="true" - > - > + + ?> - + - + oninput="finalTPStockChange(this)" + contenteditable="true"> - + ?> - + - + - + - - + + - + - + - $powerMachine) { - ?> - + $powerMachine) { + ?> + - - - + + + - - - + + + - + oninput="openingUnitsChange(this)" + contenteditable="true" + + + data-id=" "> + + + $previousMonthPowerConsumptionStockDetail) { + if ($previousMonthPowerConsumptionStockDetail['machine_id'] == $powerMachine['id']) { + echo $previousMonthPowerConsumptionStockDetail['closing_units']; + break; + } + } + ?> + + + + + + $previousMonthPowerConsumptionStockDetail) { + if ($previousMonthPowerConsumptionStockDetail['machine_id'] == $powerMachine['id']) { + echo $previousMonthPowerConsumptionStockDetail['closing_units']; + break; + } + } + ?> + + + + - - oninput="openingUnitsChange(this)" - contenteditable="true" + - data-id=" "> - - - $previousMonthPowerConsumptionStockDetail) { - if ($previousMonthPowerConsumptionStockDetail['machine_id'] == $powerMachine['id']) { - echo $previousMonthPowerConsumptionStockDetail['closing_units']; - break; - } - } - ?> - - - - - - $previousMonthPowerConsumptionStockDetail) { - if ($previousMonthPowerConsumptionStockDetail['machine_id'] == $powerMachine['id']) { - echo $previousMonthPowerConsumptionStockDetail['closing_units']; - break; - } - } - ?> - - - - - - - + + + + + + Total + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -1077,9 +1187,8 @@ foreach ($period as $day) { var updatePowerConsumptionDetails = tableToJson(); - alert('Updation may take a while, And we appreciate your patience..!!'); + showMessage('Updation may take a while, And we appreciate your patience..!!'); - $('#loader').show(); $.ajax({ data: { updatePowerConsumptionDetails @@ -1089,21 +1198,19 @@ foreach ($period as $day) { success: function(data) { if (data) { - $('#loader').hide(); - alert(data); - window.location.reload(); + showMessage(data); } }, error: function(xhr, status, error) { - alert("An error occurred while processing the request. Please try again."); + showMessage("An error occurred while processing the request. Please try again."); console.error("Error Code:", xhr.status); console.error("Error Message:", error); console.error("Response Text:", xhr.responseText); }, complete: function() { - $('#loader').hide(); + console.log("Request completed."); } }); @@ -1176,6 +1283,14 @@ foreach ($period as $day) { function openingUnitsChange(tdElement) { try { + + let basicCheck =checkIsNumber(tdElement.innerText.trim()); + + if(basicCheck == 0){ + alert("Kindly Enter Numbers only..!!"); + return ; + } + let dataId = tdElement.getAttribute('data-id'); let [date, machine_id] = tdElement.getAttribute('data-id').split(' '); let openingUnits = validateInput(tdElement.innerText); @@ -1186,7 +1301,13 @@ foreach ($period as $day) { document.querySelector(`td.totalUnits[data-id="${dataId}"]`).innerText = parseFloat(totalUnits).toFixed(2); - updateStockValue(date, machine_id, closingUnits) + updateStockValue(date, machine_id, closingUnits); + + let table = document.getElementById('powerStockDetailsTableId'); + + let column1 = 'totalUnits'; + + calculateTotal(table,dataId,column1); } catch (error) { @@ -1199,6 +1320,14 @@ foreach ($period as $day) { function closingUnitsChange(tdElement) { try { + + let basicCheck =checkIsNumber(tdElement.innerText.trim()); + + if(basicCheck == 0){ + alert("Kindly Enter Numbers only..!!"); + return ; + } + let dataId = tdElement.getAttribute('data-id'); let [date, machine_id] = tdElement.getAttribute('data-id').split(' '); let openingUnits = validateInput(document.querySelector(`td.openingUnits[data-id="${dataId}"]`).innerText); @@ -1209,7 +1338,13 @@ foreach ($period as $day) { document.querySelector(`td.totalUnits[data-id="${dataId}"]`).innerText = parseFloat(totalUnits).toFixed(2); - updateStockValue(date, machine_id, closingUnits) + updateStockValue(date, machine_id, closingUnits); + + let table = document.getElementById('powerStockDetailsTableId'); + + let column1 = 'totalUnits'; + + calculateTotal(table,dataId,column1); } catch (error) { @@ -1224,6 +1359,13 @@ foreach ($period as $day) { try { + let basicCheck =checkIsNumber(tdElement.innerText.trim()); + + if(basicCheck == 0){ + alert("Kindly Enter Numbers only..!!"); + return ; + } + let dataId = tdElement.getAttribute('data-id'); let openingTP = validateInput(tdElement.innerText); @@ -1239,6 +1381,15 @@ foreach ($period as $day) { updateTotalStockValue(dataId, finalTP); + let table = document.getElementById('powerStockDetailsTableId'); + + let column2 = 'totalReadingTP'; + + let column3 = 'totalUnitsTP'; + + calculateTotal(table,dataId,column2); + + calculateTotal(table,dataId,column3); } catch (error) { @@ -1252,6 +1403,13 @@ foreach ($period as $day) { try { + let basicCheck =checkIsNumber(tdElement.innerText.trim()); + + if(basicCheck == 0){ + alert("Kindly Enter Numbers only..!!"); + return ; + } + let dataId = tdElement.getAttribute('data-id'); let openingTP = validateInput(document.querySelector(`td.openingTP[data-id="${dataId}"]`).innerText); @@ -1265,8 +1423,19 @@ foreach ($period as $day) { document.querySelector(`td.totalUnitsTP[data-id="${dataId}"]`).innerText = parseFloat(totalUnitsTP).toFixed(2); - updateTotalStockValue(dataId, finalTP) + updateTotalStockValue(dataId, finalTP); + let table = document.getElementById('powerStockDetailsTableId'); + + let column2 = 'totalReadingTP'; + + let column3 = 'totalUnitsTP'; + + calculateTotal(table,dataId,column2); + + calculateTotal(table,dataId,column3); + + } catch (error) { @@ -1280,12 +1449,30 @@ foreach ($period as $day) { try { + let basicCheck =checkIsNumber(tdElement.innerText.trim()); + + if(basicCheck == 0){ + alert("Kindly Enter Numbers only..!!"); + return ; + } + let dataId = tdElement.getAttribute('data-id'); let mdTP = validateInput(tdElement.innerText); document.querySelector(`td.mfTP[data-id="${dataId}"]`).innerText = parseFloat(mdTP * 60).toFixed(2); + // let table = document.getElementById('powerStockDetailsTableId'); + + // let column1 = 'mdTP'; + + // let cloumn2 = 'mfTP'; + + + // calculateTotal(table,dataId,column1); + + // calculateTotal(table,dataId,column2); + } catch (error) { console.error("There is an error updating stock ..!!" + error); @@ -1315,6 +1502,16 @@ foreach ($period as $day) { return input; } + + function checkIsNumber(input) { + + const isValid = /^-?\d*\.?\d*$/.test(input); + + if (!isValid) { + return 0; + } + } + + @@ -1692,4 +1899,117 @@ foreach ($period as $day) { }, 200); }); }); + + + + + + + \ No newline at end of file diff --git a/app/Views/stock/resinStockDetails.php b/app/Views/stock/resinStockDetails.php index bd304af1..8056653e 100644 --- a/app/Views/stock/resinStockDetails.php +++ b/app/Views/stock/resinStockDetails.php @@ -265,6 +265,13 @@ .card { margin-bottom: 5px; } + + + .hidden-row { + display: none; + } + + @@ -325,6 +332,20 @@ foreach ($period as $day) {
+
+
+ @@ -374,17 +395,17 @@ foreach ($period as $day) { + id="resinStockExport"> - @@ -576,21 +597,27 @@ foreach ($period as $day) { $resinStockDetails) { - ?> - + " + + style=" "> - $currentDate = date('d-m-Y'); - $dateInMonthDmYFormat = DateTime::createFromFormat('Y-m-d', $resinStockDetails[0]['date'])->format('d-m-Y'); - if ($dateInMonthDmYFormat === $currentDate) { - echo 'style="background: #cef0ad;"'; - } - ?>> + + $resinStock) { ?> @@ -660,6 +687,7 @@ foreach ($period as $day) { 'receipt' => 0, 'used' => 0, 'balanceStock' => 0, + 'materialCode' => $resinStock['materialCode'], ]; } @@ -686,10 +714,14 @@ foreach ($period as $day) { - - - - + + + + @@ -699,96 +731,127 @@ foreach ($period as $day) { - + - $dateInMonth) { ?> - $dateInMonth) { + + $currentDate = date('Y-m-d'); + ?> - format('d-m-Y'); - if ($dateInMonthDmYFormat === $currentDate) { - echo 'style="background: #cef0ad ;"'; - } - ?>> - $resinMaterial) { ?> - - - - format('d-m-Y'); - ?> - - - - - - - - - - - - - - - - - - - - oninput="openingStockChange(this)" - contenteditable="true" - - > + " $previousMonthResinStockDetail) { - if ($previousMonthResinStockDetail['materialCode'] == $resinMaterial['MaterialCode']) { - echo $previousMonthResinStockDetail['balanceStock']; - break; + + + + if ($dateInMonth === $currentDate) { + echo 'style="background: #cef0ad ;"'; } - } ?> - - - - - - - - - + > $previousMonthResinStockDetail) { - if ($previousMonthResinStockDetail['materialCode'] == $resinMaterial['MaterialCode']) { - echo $previousMonthResinStockDetail['balanceStock']; - break; - } - } - ?> + // dd($resinMaterials); + foreach ($resinMaterials as $resinMaterialIndex => $resinMaterial) { ?> + - + + format('d-m-Y'); + ?> + + + + + + + + + + + + + + + + + + + + oninput="openingStockChange(this)" + contenteditable="true" + + > + + $previousMonthResinStockDetail) { + if ($previousMonthResinStockDetail['materialCode'] == $resinMaterial['MaterialCode']) { + echo $previousMonthResinStockDetail['balanceStock']; + break; + } + } + ?> + + + + + + + + + + $previousMonthResinStockDetail) { + if ($previousMonthResinStockDetail['materialCode'] == $resinMaterial['MaterialCode']) { + echo $previousMonthResinStockDetail['balanceStock']; + break; + } + } + ?> + + + + - - - + + + + + + Total + + + + + + + + + + + + + + + + @@ -901,9 +964,8 @@ foreach ($period as $day) { var updateResinStockDetails = tableToJson(); - alert('Updation may take a while, And we appreciate your patience..!!'); + showMessage('Updation may take a while, And we appreciate your patience..!!'); - $('#loader').show(); $.ajax({ data: { updateResinStockDetails @@ -913,10 +975,9 @@ foreach ($period as $day) { success: function(data) { if (data) { - $('#loader').hide(); + console.log(data); - alert(data); - window.location.reload(); + showMessage(data); } }, @@ -928,7 +989,7 @@ foreach ($period as $day) { console.error("Response Text:", xhr.responseText); }, complete: function() { - $('#loader').hide(); + console.log("Ajax request is completed..!!") } }); @@ -976,6 +1037,14 @@ foreach ($period as $day) { function openingStockChange(tdElement) { try { + + let basicCheck =checkIsNumber(tdElement.innerText.trim()); + + if(basicCheck == 0){ + alert("Kindly Enter Numbers only..!!"); + return ; + } + let dataId = tdElement.getAttribute('data-id'); let [date, materialCode] = tdElement.getAttribute('data-id').split(' '); let openingStock = validateInput(tdElement.innerText); @@ -984,7 +1053,16 @@ foreach ($period as $day) { let currentBalanceStock = validateInput((Number(openingStock) + Number(receiptStock)) - Number(usedStock)); document.querySelector(`td.balanceStock[data-id="${dataId}"]`).innerText = currentBalanceStock; - updateStockValue(date, materialCode, currentBalanceStock) + updateStockValue(date, materialCode, currentBalanceStock); + + let table = document.getElementById('resinStockDetailsTableId'); + + let column1 = 'receiptStock'; + let column2 = 'usedStock'; + + calculateTotal(table, dataId, column1); + calculateTotal(table, dataId, column2); + } catch (error) { @@ -996,6 +1074,12 @@ foreach ($period as $day) { function receiptStockChange(tdElement) { try { + let basicCheck =checkIsNumber(tdElement.innerText.trim()); + + if(basicCheck == 0){ + alert("Kindly Enter Numbers only..!!"); + return ; + } let dataId = tdElement.getAttribute('data-id'); let [date, materialCode] = tdElement.getAttribute('data-id').split(' '); let openingStock = validateInput(document.querySelector(`td.openingStock[data-id="${dataId}"]`).innerText); @@ -1004,7 +1088,17 @@ foreach ($period as $day) { let currentBalanceStock = (Number(openingStock) + Number(receiptStock)) - Number(usedStock); document.querySelector(`td.balanceStock[data-id="${dataId}"]`).innerText = currentBalanceStock; - updateStockValue(date, materialCode, currentBalanceStock) + updateStockValue(date, materialCode, currentBalanceStock); + + let table = document.getElementById('resinStockDetailsTableId'); + + + + let column1 = 'receiptStock'; + let column2 = 'usedStock'; + + calculateTotal(table, dataId, column1); + calculateTotal(table, dataId, column2); } catch (error) { @@ -1019,6 +1113,14 @@ foreach ($period as $day) { function usedStockChange(tdElement) { try { + + let basicCheck =checkIsNumber(tdElement.innerText.trim()); + + if(basicCheck == 0){ + alert("Kindly Enter Numbers only..!!"); + return ; + } + let dataId = tdElement.getAttribute('data-id'); let [date, materialCode] = tdElement.getAttribute('data-id').split(' '); let openingStock = validateInput(document.querySelector(`td.openingStock[data-id="${dataId}"]`).innerText); @@ -1027,7 +1129,16 @@ foreach ($period as $day) { let currentBalanceStock = (Number(openingStock) + Number(receiptStock)) - Number(usedStock); document.querySelector(`td.balanceStock[data-id="${dataId}"]`).innerText = currentBalanceStock; - updateStockValue(date, materialCode, currentBalanceStock) + updateStockValue(date, materialCode, currentBalanceStock); + + let table = document.getElementById('resinStockDetailsTableId'); + + + let column1 = 'receiptStock'; + let column2 = 'usedStock'; + + calculateTotal(table, dataId, column1); + calculateTotal(table, dataId, column2); } catch (error) { @@ -1053,12 +1164,22 @@ foreach ($period as $day) { // Validate against the regex const isValid = /^-?\d*\.?\d*$/.test(input); if (!isValid) { - alert('Invalid input! Please enter a valid number.'); + return 0; } return input; } + + function checkIsNumber(input) { + + const isValid = /^-?\d*\.?\d*$/.test(input); + + if (!isValid) { + return 0; + } + } + + + + + + \ No newline at end of file diff --git a/app/Views/stock/trpProductionStockDetails.php b/app/Views/stock/trpProductionStockDetails.php index 2e3892e3..18e1c5c2 100644 --- a/app/Views/stock/trpProductionStockDetails.php +++ b/app/Views/stock/trpProductionStockDetails.php @@ -210,7 +210,7 @@ background-color: #50bbd9; /* Green background */ color: #ffffff; - border: 2px solid ; + border: 2px solid; white-space: normal; /* Allows text to wrap */ word-wrap: break-word; @@ -306,10 +306,16 @@ margin-bottom: 5px; } - #trpProductionStockDetailsTableId { /* Replace with your table's actual ID or selector */ - border-collapse: collapse; + #trpProductionStockDetailsTableId { + /* Replace with your table's actual ID or selector */ + border-collapse: collapse; } + .hidden-row { + display: none; + } + + @@ -395,6 +401,20 @@ $timeOtions[] = "12:00 AM";
+
+
+ @@ -436,12 +456,12 @@ $timeOtions[] = "12:00 AM"; - @@ -690,22 +710,20 @@ $timeOtions[] = "12:00 AM"; $totalWcsReceived = 0; $totalCrsReceived = 0; - // dd(array_keys($trpProductionDetails[0])); - // dd($trpProductionDetails); ?> $trpProductionDetail) { + $currentDate = date('Y-m-d'); + $dateInMonthDmYFormat = DateTime::createFromFormat('Y-m-d', $trpProductionDetail['date'])->format('d-m-Y'); + ?> - ?> - - " format('d-m-Y'); - if ($dateInMonthDmYFormat === $currentDate) { + + if ($trpProductionDetail['date'] === $currentDate) { echo 'style="background: #cef0ad;"'; } ?>> @@ -800,7 +818,8 @@ $timeOtions[] = "12:00 AM"; + contenteditable="true" + oninput="trpStockChange(this)"> @@ -808,7 +827,8 @@ $timeOtions[] = "12:00 AM"; + contenteditable="true" + oninput="trpStockChange(this)"> @@ -828,7 +848,9 @@ $timeOtions[] = "12:00 AM"; + data-id=" drierGasConsumption" + oninput="trpStockChange(this)" + contenteditable="true"> @@ -836,7 +858,7 @@ $timeOtions[] = "12:00 AM"; - + @@ -889,7 +911,8 @@ $timeOtions[] = "12:00 AM"; + contenteditable="true" + oninput="trpStockChange(this)"> @@ -899,7 +922,8 @@ $timeOtions[] = "12:00 AM"; + contenteditable="true" + oninput="trpStockChange(this)"> @@ -907,7 +931,8 @@ $timeOtions[] = "12:00 AM"; + contenteditable="true" + oninput="trpStockChange(this)"> @@ -955,7 +980,8 @@ $timeOtions[] = "12:00 AM"; + contenteditable="true" + oninput="trpStockChange(this)"> @@ -963,7 +989,8 @@ $timeOtions[] = "12:00 AM"; + contenteditable="true" + oninput="trpStockChange(this)"> @@ -1027,6 +1054,7 @@ $timeOtions[] = "12:00 AM"; @@ -1035,6 +1063,7 @@ $timeOtions[] = "12:00 AM"; @@ -1045,7 +1074,8 @@ $timeOtions[] = "12:00 AM"; + contenteditable="true" + oninput="trpStockChange(this)"> @@ -1053,7 +1083,8 @@ $timeOtions[] = "12:00 AM"; + contenteditable="true" + oninput="trpStockChange(this)"> @@ -1061,7 +1092,8 @@ $timeOtions[] = "12:00 AM"; + contenteditable="true" + oninput="trpStockChange(this)"> @@ -1069,7 +1101,8 @@ $timeOtions[] = "12:00 AM"; + contenteditable="true" + oninput="trpStockChange(this)"> @@ -1077,7 +1110,8 @@ $timeOtions[] = "12:00 AM"; + contenteditable="true" + oninput="trpStockChange(this)"> @@ -1120,6 +1154,7 @@ $timeOtions[] = "12:00 AM"; 'waterReceipt' => 0, 'waterConsumption' => 0, 'ebReading' => 0, + 'noOfEbReadingDays' => 0, 'ebReadingPerUnitTon' => 0, 'workingPersonEngineers' => 0, 'workingPersonSupervisiors' => 0, @@ -1182,6 +1217,8 @@ $timeOtions[] = "12:00 AM"; $summary['waterConsumption'] += is_numeric($trpProductionDetail['waterConsumption']) ? $trpProductionDetail['waterConsumption'] : 0; $summary['ebReading'] += is_numeric($trpProductionDetail['ebReading']) ? $trpProductionDetail['ebReading'] : 0; $summary['ebReadingPerUnitTon'] += is_numeric($trpProductionDetail['ebReadingPerUnitTon']) ? $trpProductionDetail['ebReadingPerUnitTon'] : 0; + $summary['noOfEbReadingDays'] += is_numeric($trpProductionDetail['ebReading']) + && $trpProductionDetail['ebReading'] != 0 ? 1 : 0 ; $summary['workingPersonEngineers'] += is_numeric($trpProductionDetail['workingPersonEngineers']) ? $trpProductionDetail['workingPersonEngineers'] : 0; $summary['workingPersonSupervisiors'] += is_numeric($trpProductionDetail['workingPersonSupervisiors']) ? $trpProductionDetail['workingPersonSupervisiors'] : 0; $summary['workingPersonOperators'] += is_numeric($trpProductionDetail['workingPersonOperators']) ? $trpProductionDetail['workingPersonOperators'] : 0; @@ -1206,55 +1243,64 @@ $timeOtions[] = "12:00 AM"; - + - + - + - + - + - + - + - + - + @@ -1262,7 +1308,8 @@ $timeOtions[] = "12:00 AM"; - + @@ -1270,39 +1317,45 @@ $timeOtions[] = "12:00 AM"; - + - + - + - + - + - + @@ -1310,7 +1363,8 @@ $timeOtions[] = "12:00 AM"; - + @@ -1318,46 +1372,51 @@ $timeOtions[] = "12:00 AM"; - + - - - + - + - + - + - + - + @@ -1365,51 +1424,58 @@ $timeOtions[] = "12:00 AM"; - + - + - + - - + + - - + - + - + - - + + @@ -1433,31 +1499,36 @@ $timeOtions[] = "12:00 AM"; - + - + - + - + - + @@ -1484,6 +1555,8 @@ $timeOtions[] = "12:00 AM";
+ +
@@ -1502,16 +1575,16 @@ $timeOtions[] = "12:00 AM";
- - + + - - + +
@@ -1549,97 +1622,99 @@ $timeOtions[] = "12:00 AM"; if (!empty($trpAbstract)) { + // $trpAbstract["Incoming Raw Sand Details"]['date'], 'absParticulars' => "Incoming Raw Sand Details", + 'absRunningHrs' => "", 'absPerHour' => "", 'absOpeningStock' => (int)$trpAbstract["Incoming Raw Sand Details"]['opening_stock'], 'absReceipt' => $totalWcsReceived, 'absTotal' => (int)$trpAbstract["Incoming Raw Sand Details"]['opening_stock'] + $totalWcsReceived, - 'absConsumption' => $summary['edProduction'], - 'absClosingStock' => ((int)$trpAbstract["Incoming Raw Sand Details"]['opening_stock'] + $totalWcsReceived) - $summary['edProduction'], - 'absPhysicalStock' => (int)$trpAbstract["Incoming Raw Sand Details"]['physical_stock'], - 'absRemarks' => $trpAbstract["Incoming Raw Sand Details"]['remarks'], + 'absConsumption' => $summary['edProduction']== 0 ? " " : $summary['edProduction'], + 'absClosingStock' => ((int)$trpAbstract["Incoming Raw Sand Details"]['opening_stock'] + $totalWcsReceived) - $summary['edProduction'] == 0 ? " " : ((int)$trpAbstract["Incoming Raw Sand Details"]['opening_stock'] + $totalWcsReceived) - $summary['edProduction'], + 'absPhysicalStock' => (int)$trpAbstract["Incoming Raw Sand Details"]['physical_stock']== 0 ? " " : (int)$trpAbstract["Incoming Raw Sand Details"]['physical_stock'], + 'absRemarks' => $trpAbstract["Incoming Raw Sand Details"]['remarks'] == 0 ? " " : $trpAbstract["Incoming Raw Sand Details"]['remarks'], ], [ 'absDate' => $trpAbstract["ED Details"]['date'], 'absParticulars' => "ED Details", - 'absRunningHrs' => $summary['edRunningHours'], - 'absPerHour' => number_format($summary['edProduction'] / ($summary['edRunningHours'] == 0 ? 1 : $summary['edRunningHours']), 2), - 'absOpeningStock' => (int)$trpAbstract["ED Details"]['opening_stock'], - 'absReceipt' => $summary['edProduction'], - 'absTotal' => (int)$trpAbstract["ED Details"]['opening_stock'] + $summary['edProduction'], - 'absConsumption' => $summary['edUsage'] + ($summary['coolerBags'] * 1250) + ($summary['cycloneWaste'] * 1250) + ($summary['edWaste'] * 1250), - 'absClosingStock' => (int)$trpAbstract["ED Details"]['opening_stock'] + $summary['edProduction'] - ($summary['edUsage'] + ($summary['coolerBags'] * 1250) + ($summary['cycloneWaste'] * 1250) + ($summary['edWaste'] * 1250)), - 'absPhysicalStock' => (int)$trpAbstract["ED Details"]['physical_stock'], + 'absRunningHrs' => $summary['edRunningHours'] == 0 ? " " : $summary['edRunningHours'], + 'absPerHour' => number_format($summary['edProduction'] / ($summary['edRunningHours'] == 0 ? 1 : $summary['edRunningHours']), 2) == 0 ? " " : number_format($summary['edProduction'] / ($summary['edRunningHours'] == 0 ? 1 : $summary['edRunningHours']), 2), + 'absOpeningStock' => (int)$trpAbstract["ED Details"]['opening_stock'] == 0 ? " " : (int)$trpAbstract["ED Details"]['opening_stock'], + 'absReceipt' => $summary['edProduction'] == 0 ? " " : $summary['edProduction'], + 'absTotal' => (int)$trpAbstract["ED Details"]['opening_stock'] + $summary['edProduction'] == 0 ? " " : (int)$trpAbstract["ED Details"]['opening_stock'] + $summary['edProduction'], + 'absConsumption' => $summary['edUsage'] + ($summary['coolerBags'] * 1250) + ($summary['cycloneWaste'] * 1250) + ($summary['edWaste'] * 1250) == 0 ? " " : $summary['edUsage'] + ($summary['coolerBags'] * 1250) + ($summary['cycloneWaste'] * 1250) + ($summary['edWaste'] * 1250), + 'absClosingStock' => (int)$trpAbstract["ED Details"]['opening_stock'] + $summary['edProduction'] - ($summary['edUsage'] + ($summary['coolerBags'] * 1250) + ($summary['cycloneWaste'] * 1250) + ($summary['edWaste'] * 1250)) == 0 ? " " : (int)$trpAbstract["ED Details"]['opening_stock'] + $summary['edProduction'] - ($summary['edUsage'] + ($summary['coolerBags'] * 1250) + ($summary['cycloneWaste'] * 1250) + ($summary['edWaste'] * 1250)), + 'absPhysicalStock' => (int)$trpAbstract["ED Details"]['physical_stock'] == 0 ? " " : (int)$trpAbstract["ED Details"]['physical_stock'], 'absRemarks' => $trpAbstract["ED Details"]['remarks'], ], [ 'absDate' => $trpAbstract["TRP Total Sand"]['date'], 'absParticulars' => "TRP Total Sand", - 'absRunningHrs' => $summary['sandFeedingHours'], - 'absPerHour' => $summary['trpProductionPerHour'], - 'absOpeningStock' => (int)$trpAbstract["TRP Total Sand"]['opening_stock'], - 'absReceipt' => $summary['trpProduction'], - 'absTotal' => (int)$trpAbstract["TRP Total Sand"]['opening_stock'] + $summary['trpProduction'], - 'absConsumption' => $totalCrsReceived, - 'absClosingStock' => (int)$trpAbstract["TRP Total Sand"]['opening_stock'] + $summary['trpProduction'] - $totalCrsReceived, - 'absPhysicalStock' => (int)$trpAbstract["TRP Total Sand"]['physical_stock'], + 'absRunningHrs' => $summary['sandFeedingHours'] == 0 ? " " : $summary['sandFeedingHours'], + 'absPerHour' => $summary['trpProductionPerHour'] == 0 ? " " : $summary['trpProductionPerHour'], + 'absOpeningStock' => (int)$trpAbstract["TRP Total Sand"]['opening_stock'] == 0 ? " " : (int)$trpAbstract["TRP Total Sand"]['opening_stock'], + 'absReceipt' => $summary['trpProduction'] == 0 ? " " : $summary['trpProduction'], + 'absTotal' => (int)$trpAbstract["TRP Total Sand"]['opening_stock'] + $summary['trpProduction'] == 0 ? " " : (int)$trpAbstract["TRP Total Sand"]['opening_stock'] + $summary['trpProduction'], + 'absConsumption' => $totalCrsReceived == 0 ? " " : $totalCrsReceived, + 'absClosingStock' => (int)$trpAbstract["TRP Total Sand"]['opening_stock'] + $summary['trpProduction'] - $totalCrsReceived == 0 ? " " : (int)$trpAbstract["TRP Total Sand"]['opening_stock'] + $summary['trpProduction'] - $totalCrsReceived, + 'absPhysicalStock' => (int)$trpAbstract["TRP Total Sand"]['physical_stock'] == 0 ? " " : (int)$trpAbstract["TRP Total Sand"]['physical_stock'], 'absRemarks' => $trpAbstract["TRP Total Sand"]['remarks'], ], - [ + [ 'absDate' => $trpAbstract["Trp Physical Gas Consumption"]['date'], 'absParticulars' => "Trp Physical Gas Consumption", 'absRunningHrs' => "", - 'absPerHour' => number_format(($summary['trpPlusDrierGasConsumption']) / (($summary['trpProduction'] == 0 ? 1000 : $summary['trpProduction']) / 1000), 2, '.', ''), - 'absOpeningStock' => (int)$trpAbstract["Trp Physical Gas Consumption"]['opening_stock'], - 'absReceipt' => $summary['gasReceiptBg'] + $summary['gasReceiptPg'], - 'absTotal' => (int)$trpAbstract["Trp Physical Gas Consumption"]['opening_stock'] + $summary['gasReceiptBg'] + $summary['gasReceiptPg'], - 'absConsumption' => $summary['physicalGasConsumption'], - 'absClosingStock' => (int)$trpAbstract["Trp Physical Gas Consumption"]['opening_stock'] + $summary['gasReceiptBg'] + $summary['gasReceiptPg'] - $summary['physicalGasConsumption'], - 'absPhysicalStock' => (int)$trpAbstract["Trp Physical Gas Consumption"]['physical_stock'], - 'absRemarks' => $trpAbstract["Trp Physical Gas Consumption"]['remarks'], + 'absPerHour' => number_format(($summary['trpPlusDrierGasConsumption']) / (($summary['trpProduction'] == 0 ? 1000 : $summary['trpProduction']) / 1000), 2, '.', '') == 0 ? " " : number_format(($summary['trpPlusDrierGasConsumption']) / (($summary['trpProduction'] == 0 ? 1000 : $summary['trpProduction']) / 1000), 2, '.', ''), + 'absOpeningStock' => (int)$trpAbstract["Trp Physical Gas Consumption"]['opening_stock'] == 0 ? " " : (int)$trpAbstract["Trp Physical Gas Consumption"]['opening_stock'], + 'absReceipt' => $summary['gasReceiptBg'] + $summary['gasReceiptPg'] == 0 ? " " : $summary['gasReceiptBg'] + $summary['gasReceiptPg'], + 'absTotal' => (int)$trpAbstract["Trp Physical Gas Consumption"]['opening_stock'] + $summary['gasReceiptBg'] + $summary['gasReceiptPg'] == 0 ? " " : (int)$trpAbstract["Trp Physical Gas Consumption"]['opening_stock'] + $summary['gasReceiptBg'] + $summary['gasReceiptPg'], + 'absConsumption' => $summary['physicalGasConsumption'] == 0 ? " " : $summary['physicalGasConsumption'], + 'absClosingStock' => (int)$trpAbstract["Trp Physical Gas Consumption"]['opening_stock'] + $summary['gasReceiptBg'] + $summary['gasReceiptPg'] - $summary['physicalGasConsumption'] == 0 ? " " : (int)$trpAbstract["Trp Physical Gas Consumption"]['opening_stock'] + $summary['gasReceiptBg'] + $summary['gasReceiptPg'] - $summary['physicalGasConsumption'], + 'absPhysicalStock' => (int)$trpAbstract["Trp Physical Gas Consumption"]['physical_stock'] == 0 ? " " : (int)$trpAbstract["Trp Physical Gas Consumption"]['physical_stock'], + 'absRemarks' => $trpAbstract["Trp Physical Gas Consumption"]['remarks'] , ], - [ + [ 'absDate' => $trpAbstract["Trp Panel Gas Consumption"]['date'], 'absParticulars' => "Trp Panel Gas Consumption", 'absRunningHrs' => "", - 'absPerHour' => number_format(($summary['panelGasConsumption']) / (($summary['trpProduction'] == 0 ? 1000 : $summary['trpProduction']) / 1000), 2), - 'absOpeningStock' => (int)$trpAbstract["Trp Panel Gas Consumption"]['opening_stock'], - 'absReceipt' => $summary['gasReceiptBg'] + $summary['gasReceiptPg'], - 'absTotal' => (int)$trpAbstract["Trp Panel Gas Consumption"]['opening_stock'] + $summary['gasReceiptBg'] + $summary['gasReceiptPg'], - 'absConsumption' => $summary['panelGasConsumption'], - 'absClosingStock' => (int)$trpAbstract["Trp Panel Gas Consumption"]['opening_stock'] + $summary['gasReceiptBg'] + $summary['gasReceiptPg'] - $summary['panelGasConsumption'], + 'absPerHour' => number_format(($summary['panelGasConsumption']) / (($summary['trpProduction'] == 0 ? 1000 : $summary['trpProduction']) / 1000), 2) == 0 ? " " : number_format(($summary['panelGasConsumption']) / (($summary['trpProduction'] == 0 ? 1000 : $summary['trpProduction']) / 1000), 2), + 'absOpeningStock' => (int)$trpAbstract["Trp Panel Gas Consumption"]['opening_stock'] == 0 ? " " : (int)$trpAbstract["Trp Panel Gas Consumption"]['opening_stock'], + 'absReceipt' => $summary['gasReceiptBg'] + $summary['gasReceiptPg'] == 0 ? " " : $summary['gasReceiptBg'] + $summary['gasReceiptPg'], + 'absTotal' => (int)$trpAbstract["Trp Panel Gas Consumption"]['opening_stock'] + $summary['gasReceiptBg'] + $summary['gasReceiptPg'] == 0 ? " " : (int)$trpAbstract["Trp Panel Gas Consumption"]['opening_stock'] + $summary['gasReceiptBg'] + $summary['gasReceiptPg'], + 'absConsumption' => $summary['panelGasConsumption'] == 0 ? " " : $summary['panelGasConsumption'], + 'absClosingStock' => (int)$trpAbstract["Trp Panel Gas Consumption"]['opening_stock'] + $summary['gasReceiptBg'] + $summary['gasReceiptPg'] - $summary['panelGasConsumption'] == 0 ? " " : (int)$trpAbstract["Trp Panel Gas Consumption"]['opening_stock'] + $summary['gasReceiptBg'] + $summary['gasReceiptPg'] - $summary['panelGasConsumption'], 'absPhysicalStock' => (int)$trpAbstract["Trp Panel Gas Consumption"]['physical_stock'], 'absRemarks' => $trpAbstract["Trp Panel Gas Consumption"]['remarks'], ], - [ + [ 'absDate' => $trpAbstract["Water Consumption"]['date'], 'absParticulars' => "Water Consumption", 'absRunningHrs' => "", 'absPerHour' => "", - 'absOpeningStock' => (int)$trpAbstract["Water Consumption"]['opening_stock'], - 'absReceipt' => $summary['waterReceipt'], - 'absTotal' => (int)$trpAbstract["Water Consumption"]['opening_stock'] + $summary['waterReceipt'], - 'absConsumption' => $summary['waterConsumption'], - 'absClosingStock' => (int)$trpAbstract["Water Consumption"]['opening_stock'] + $summary['waterReceipt'] - $summary['waterConsumption'], - 'absPhysicalStock' => (int)$trpAbstract["Water Consumption"]['physical_stock'], - 'absRemarks' => $trpAbstract["Water Consumption"]['remarks'], + 'absOpeningStock' => (int)$trpAbstract["Water Consumption"]['opening_stock'] == 0 ? " " : (int)$trpAbstract["Water Consumption"]['opening_stock'], + 'absReceipt' => $summary['waterReceipt'] == 0 ? " " : $summary['waterReceipt'], + 'absTotal' => (int)$trpAbstract["Water Consumption"]['opening_stock'] + $summary['waterReceipt'] == 0 ? " " : (int)$trpAbstract["Water Consumption"]['opening_stock'] + $summary['waterReceipt'], + 'absConsumption' => $summary['waterConsumption'] == 0 ? " " : $summary['waterConsumption'], + 'absClosingStock' => (int)$trpAbstract["Water Consumption"]['opening_stock'] + $summary['waterReceipt'] - $summary['waterConsumption'] == 0 ? " " : (int)$trpAbstract["Water Consumption"]['opening_stock'] + $summary['waterReceipt'] - $summary['waterConsumption'], + 'absPhysicalStock' => (int)$trpAbstract["Water Consumption"]['physical_stock'] == 0 ? " " : (int)$trpAbstract["Water Consumption"]['physical_stock'], + 'absRemarks' => $trpAbstract["Water Consumption"]['remarks'] , ], - [ + [ 'absDate' => $trpAbstract["Power Consumption"]['date'], 'absParticulars' => "Power Consumption", - 'absRunningHrs' => $summary['ebReadingPerUnitTon'], + 'absRunningHrs' => $summary['ebReadingPerUnitTon'] / ($summary['noOfEbReadingDays'] == 0 ? 1 : $summary['noOfEbReadingDays'] ) == 0 ? " " : number_format($summary['ebReadingPerUnitTon'] / ($summary['noOfEbReadingDays'] == 0 ? 1 : $summary['noOfEbReadingDays'] ),2), 'absPerHour' => "", - 'absOpeningStock' => (int)$trpAbstract["Power Consumption"]['opening_stock'], + 'absOpeningStock' => (int)$trpAbstract["Power Consumption"]['opening_stock'] == 0 ? " " : (int)$trpAbstract["Power Consumption"]['opening_stock'], 'absReceipt' => '', 'absTotal' => '', - 'absConsumption' => $summary['ebReading'], + 'absConsumption' => $summary['ebReading'] == 0 ? " " : $summary['ebReading'], 'absClosingStock' => '', - 'absPhysicalStock' => (int)$trpAbstract["Power Consumption"]['physical_stock'], + 'absPhysicalStock' => (int)$trpAbstract["Power Consumption"]['physical_stock'] == 0 ? " " : (int)$trpAbstract["Power Consumption"]['physical_stock'], 'absRemarks' => $trpAbstract["Power Consumption"]['remarks'], ] ]; @@ -1657,38 +1732,48 @@ $timeOtions[] = "12:00 AM"; - + - + - + + contenteditable="true" + data-id=""> - + - + - + - + + contenteditable="true" + data-id=""> + contenteditable="true" + data-id=""> @@ -1703,14 +1788,13 @@ $timeOtions[] = "12:00 AM"; $abstractForCurrentMonth = [ [ - 'absParticulars' => "Incoming Raw Sand Details", 'absRunningHrs' => "", 'absPerHour' => "", 'absOpeningStock' => '', 'absReceipt' => $totalWcsReceived == 0 ? " " : $totalWcsReceived, 'absTotal' => $totalWcsReceived == 0 ? " " : $totalWcsReceived, - 'absConsumption' => $summary['edProduction'] == 0 ? " " : $summary['edProduction'] , + 'absConsumption' => $summary['edProduction'] == 0 ? " " : $summary['edProduction'], 'absClosingStock' => ($totalWcsReceived) - $summary['edProduction'] == 0 ? " " : $totalWcsReceived - $summary['edProduction'], 'absPhysicalStock' => '', 'absRemarks' => '', @@ -1762,28 +1846,28 @@ $timeOtions[] = "12:00 AM"; 'absOpeningStock' => '', 'absReceipt' => $summary['gasReceiptBg'] + $summary['gasReceiptPg'] == 0 ? " " : $summary['gasReceiptBg'] + $summary['gasReceiptPg'], 'absTotal' => $summary['gasReceiptBg'] + $summary['gasReceiptPg'] == 0 ? " " : $summary['gasReceiptBg'] + $summary['gasReceiptPg'], - 'absConsumption' => $summary['panelGasConsumption'] == 0 ? " " : $summary['panelGasConsumption'] , + 'absConsumption' => $summary['panelGasConsumption'] == 0 ? " " : $summary['panelGasConsumption'], 'absClosingStock' => ($summary['gasReceiptBg'] + $summary['gasReceiptPg']) - $summary['panelGasConsumption'] == 0 ? " " : ($summary['gasReceiptBg'] + $summary['gasReceiptPg']) - $summary['panelGasConsumption'], 'absPhysicalStock' => '', 'absRemarks' => '', ], [ - 'absParticulars' => "Water Consumption", - 'absRunningHrs' => "", - 'absPerHour' => "", - 'absOpeningStock' => '', - 'absReceipt' => $summary['waterReceipt'] == 0 ? " " : $summary['waterReceipt'], - 'absTotal' => $summary['waterReceipt'] == 0 ? " " : $summary['waterReceipt'], - 'absConsumption' => $summary['waterReceipt'] - $summary['waterConsumption'] == 0 ? " " : $summary['waterReceipt'] - $summary['waterConsumption'], + 'absParticulars' => "Water Consumption", + 'absRunningHrs' => "", + 'absPerHour' => "", + 'absOpeningStock' => '', + 'absReceipt' => $summary['waterReceipt'] == 0 ? " " : $summary['waterReceipt'], + 'absTotal' => $summary['waterReceipt'] == 0 ? " " : $summary['waterReceipt'], + 'absConsumption' => $summary['waterReceipt'] - $summary['waterConsumption'] == 0 ? " " : $summary['waterReceipt'] - $summary['waterConsumption'], 'absClosingStock' => '', - 'absPhysicalStock' => '', - 'absRemarks' => '', + 'absPhysicalStock' => '', + 'absRemarks' => '', ], [ 'absParticulars' => "Power Consumption", - 'absRunningHrs' => $summary['ebReadingPerUnitTon'] == 0 ? " " : $summary['ebReadingPerUnitTon'], + 'absRunningHrs' => $summary['ebReadingPerUnitTon'] / ($summary['noOfEbReadingDays'] == 0 ? 1 : $summary['noOfEbReadingDays'] ) == 0 ? " " : number_format($summary['ebReadingPerUnitTon'] / ($summary['noOfEbReadingDays'] == 0 ? 1 : $summary['noOfEbReadingDays'] ) , 2), 'absPerHour' => "", 'absOpeningStock' => '', 'absReceipt' => '', @@ -1808,38 +1892,48 @@ $timeOtions[] = "12:00 AM"; - + - + - + + contenteditable="true" + data-id=""> - + - + - + - + + contenteditable="true" + data-id=""> + contenteditable="true" + data-id=""> @@ -1862,6 +1956,8 @@ $timeOtions[] = "12:00 AM";
+ +
@@ -1986,41 +2082,42 @@ $timeOtions[] = "12:00 AM"; const rowData = { Date: rowCells.eq(0).text().trim(), - openingTime: openingTime, - closingTime: closingTime, - totalHours: $(this).find(`td[data-id='${dateInYmD} totalHours']`).text().trim(), - coldStart: $(this).find(`td[data-id='${dateInYmD} coldStart']`).text().trim(), - breakdownHours: $(this).find(`td[data-id='${dateInYmD} breakdownHours']`).text().trim(), - burnerFiringHours: $(this).find(`td[data-id='${dateInYmD} burnerFiringHours']`).text().trim(), - sandFeedingHours: $(this).find(`td[data-id='${dateInYmD} sandFeedingHours']`).text().trim(), - gasReceiptBg: $(this).find(`td[data-id='${dateInYmD} gasReceiptBg']`).text().trim(), - gasReceiptPg: $(this).find(`td[data-id='${dateInYmD} gasReceiptPg']`).text().trim(), - physicalGasConsumption: $(this).find(`td[data-id='${dateInYmD} physicalGasConsumption']`).text().trim(), - trpPlusDrierGasConsumption: $(this).find(`td[data-id='${dateInYmD} trpPlusDrierGasConsumption']`).text().trim(), - trpPhysicalGasPerTon: $(this).find(`td[data-id='${dateInYmD} trpPhysicalGasPerTon']`).text().trim(), - panelGasConsumption: $(this).find(`td[data-id='${dateInYmD} panelGasConsumption']`).text().trim(), - panelGasPerTon: $(this).find(`td[data-id='${dateInYmD} panelGasPerTon']`).text().trim(), - edRunningHours: $(this).find(`td[data-id='${dateInYmD} edRunningHours']`).text().trim(), - edProduction: $(this).find(`td[data-id='${dateInYmD} edProduction']`).text().trim(), - edUsage: $(this).find(`td[data-id='${dateInYmD} edUsage']`).text().trim(), - waterConsumption: $(this).find(`td[data-id='${dateInYmD} waterConsumption']`).text().trim(), - trpProduction: $(this).find(`td[data-id='${dateInYmD} trpProduction']`).text().trim(), - trpProductionPerHour: $(this).find(`td[data-id='${dateInYmD} trpProductionPerHour']`).text().trim(), - waterReceipt: $(this).find(`td[data-id='${dateInYmD} waterReceipt']`).text().trim(), - ebReading: $(this).find(`td[data-id='${dateInYmD} ebReading']`).text().trim(), - ebReadingPerUnitTon: $(this).find(`td[data-id='${dateInYmD} ebReadingPerUnitTon']`).text().trim(), - workingPersonEngineers: $(this).find(`td[data-id='${dateInYmD} workingPersonEngineers']`).text().trim(), - workingPersonSupervisiors: $(this).find(`td[data-id='${dateInYmD} workingPersonSupervisiors']`).text().trim(), - workingPersonOperators: $(this).find(`td[data-id='${dateInYmD} workingPersonOperators']`).text().trim(), - rollerDrivers: $(this).find(`td[data-id='${dateInYmD} rollerDrivers']`).text().trim(), - natureOfMaintenance: $(this).find(`td[data-id='${dateInYmD} natureOfMaintenance']`).text().trim(), - location: $(this).find(`td[data-id='${dateInYmD} location']`).text().trim(), - description: $(this).find(`td[data-id='${dateInYmD} description']`).text().trim(), - msSeperation: $(this).find(`td[data-id='${dateInYmD} msSeperation']`).text().trim(), - edWaste: $(this).find(`td[data-id='${dateInYmD} edWaste']`).text().trim(), - coolerBags: $(this).find(`td[data-id='${dateInYmD} coolerBags']`).text().trim(), - edPlus20Waste: $(this).find(`td[data-id='${dateInYmD} edPlus20Waste']`).text().trim(), - cycloneWaste: $(this).find(`td[data-id='${dateInYmD} cycloneWaste']`).text().trim(), + openingTime: openingTime, + closingTime: closingTime, + totalHours: $(this).find(`td[data-id='${dateInYmD} totalHours']`).text().trim(), + coldStart: $(this).find(`td[data-id='${dateInYmD} coldStart']`).text().trim(), + breakdownHours: $(this).find(`td[data-id='${dateInYmD} breakdownHours']`).text().trim(), + burnerFiringHours: $(this).find(`td[data-id='${dateInYmD} burnerFiringHours']`).text().trim(), + sandFeedingHours: $(this).find(`td[data-id='${dateInYmD} sandFeedingHours']`).text().trim(), + gasReceiptBg: $(this).find(`td[data-id='${dateInYmD} gasReceiptBg']`).text().trim(), + gasReceiptPg: $(this).find(`td[data-id='${dateInYmD} gasReceiptPg']`).text().trim(), + physicalGasConsumption: $(this).find(`td[data-id='${dateInYmD} physicalGasConsumption']`).text().trim(), + drierGasConsumption: $(this).find(`td[data-id='${dateInYmD} drierGasConsumption']`).text().trim(), + trpPlusDrierGasConsumption: $(this).find(`td[data-id='${dateInYmD} trpPlusDrierGasConsumption']`).text().trim(), + trpPhysicalGasPerTon: $(this).find(`td[data-id='${dateInYmD} trpPhysicalGasPerTon']`).text().trim(), + panelGasConsumption: $(this).find(`td[data-id='${dateInYmD} panelGasConsumption']`).text().trim(), + panelGasPerTon: $(this).find(`td[data-id='${dateInYmD} panelGasPerTon']`).text().trim(), + edRunningHours: $(this).find(`td[data-id='${dateInYmD} edRunningHours']`).text().trim(), + edProduction: $(this).find(`td[data-id='${dateInYmD} edProduction']`).text().trim(), + edUsage: $(this).find(`td[data-id='${dateInYmD} edUsage']`).text().trim(), + waterConsumption: $(this).find(`td[data-id='${dateInYmD} waterConsumption']`).text().trim(), + trpProduction: $(this).find(`td[data-id='${dateInYmD} trpProduction']`).text().trim(), + trpProductionPerHour: $(this).find(`td[data-id='${dateInYmD} trpProductionPerHour']`).text().trim(), + waterReceipt: $(this).find(`td[data-id='${dateInYmD} waterReceipt']`).text().trim(), + ebReading: $(this).find(`td[data-id='${dateInYmD} ebReading']`).text().trim(), + ebReadingPerUnitTon: $(this).find(`td[data-id='${dateInYmD} ebReadingPerUnitTon']`).text().trim(), + workingPersonEngineers: $(this).find(`td[data-id='${dateInYmD} workingPersonEngineers']`).text().trim(), + workingPersonSupervisiors: $(this).find(`td[data-id='${dateInYmD} workingPersonSupervisiors']`).text().trim(), + workingPersonOperators: $(this).find(`td[data-id='${dateInYmD} workingPersonOperators']`).text().trim(), + rollerDrivers: $(this).find(`td[data-id='${dateInYmD} rollerDrivers']`).text().trim(), + natureOfMaintenance: $(this).find(`td[data-id='${dateInYmD} natureOfMaintenance']`).text().trim(), + location: $(this).find(`td[data-id='${dateInYmD} location']`).text().trim(), + description: $(this).find(`td[data-id='${dateInYmD} description']`).text().trim(), + msSeperation: $(this).find(`td[data-id='${dateInYmD} msSeperation']`).text().trim(), + edWaste: $(this).find(`td[data-id='${dateInYmD} edWaste']`).text().trim(), + coolerBags: $(this).find(`td[data-id='${dateInYmD} coolerBags']`).text().trim(), + edPlus20Waste: $(this).find(`td[data-id='${dateInYmD} edPlus20Waste']`).text().trim(), + cycloneWaste: $(this).find(`td[data-id='${dateInYmD} cycloneWaste']`).text().trim(), }; @@ -2102,12 +2199,20 @@ $timeOtions[] = "12:00 AM"; - function trpStockChange(tdElement) { + function trpStockChange(tdElement,timeValue="") { try { + let basicCheck =checkIsNumber(tdElement.innerText.trim()); + + if(basicCheck == 0 && timeValue == ""){ + console.log(tdElement.innerText.trim()); + alert("Kindly Enter Numbers only..!!"); + return ; + } + let tr = $(tdElement).closest('tr'); @@ -2197,7 +2302,23 @@ $timeOtions[] = "12:00 AM"; document.querySelector(`td.ebReadingPerUnitTon[data-id="${date} ebReadingPerUnitTon"]`).innerText = isFinite(ebReadingPerUnitTon) ? (ebReadingPerUnitTon).toFixed(2) : " "; + // currently onchange total calculation for trp is in hold + // let classArray = Array.from(tdElement.classList); + + + // let table = document.getElementById('trpProductionStockDetailsTableId'); + // let column1 = `${classArray[2]}`; + // let column2 = 'totalHours'; + // let column3 = 'burnerFiringHours'; + // let column4 = 'sandFeedingHours'; + + // calculateTotal(table, column1); + // calculateTotal(table, column2); + // calculateTotal(table, column3); + // calculateTotal(table, column4); + + // calculateAbstractTotal(); @@ -2207,6 +2328,18 @@ $timeOtions[] = "12:00 AM"; } } + + function checkIsNumber(input) { + + const isValid = /^-?\d*\.?\d*$/.test(input); + + if (!isValid) { + return 0; + } + } + + + @@ -2262,7 +2395,7 @@ $timeOtions[] = "12:00 AM"; document.querySelector(`td.totalHours[data-id="${date} totalHours"]`).innerText = totalHours; - trpStockChange(this); + trpStockChange(this,"timeValue"); @@ -2311,7 +2444,6 @@ $timeOtions[] = "12:00 AM"; // Validate against the regex const isValid = /^-?\d*\.?\d*$/.test(input); if (!isValid) { - alert('Invalid input! Please enter a valid number.'); return 0; } @@ -2330,8 +2462,8 @@ $timeOtions[] = "12:00 AM"; // Convert to numbers for calculations let openingStock = validateInput(openingStockTd) || 0; - let receipt = validateInput(receiptTd) || 0; - let consumption = validateInput(consumptionTd) || 0; + let receipt = validateInput(receiptTd) || 0; + let consumption = validateInput(consumptionTd) || 0; // Calculate values let totalStock = parseFloat(openingStock) + parseFloat(receipt); @@ -2515,7 +2647,21 @@ $timeOtions[] = "12:00 AM"; }); - let ws = XLSX.utils.table_to_sheet(cloneTable); // Convert modified table to sheet + let ws = XLSX.utils.table_to_sheet(cloneTable); + + // Set column width to 10 for all columns + let colCount = 0; + $(cloneTable).find('tr').each(function() { + let count = $(this).find('th, td').length; + if (count > colCount) colCount = count; + }); + + let wscols = []; + for (let i = 0; i < colCount; i++) { + wscols.push({ wch: 10 }); // Set width of 10 for all columns + } + ws['!cols'] = wscols; + let wb = XLSX.utils.book_new(); // Create a new workbook XLSX.utils.book_append_sheet(wb, ws, 'Sheet1'); // Append sheet to workbook XLSX.writeFile(wb, filename || 'export.xlsx'); // Save the file @@ -2543,8 +2689,10 @@ $timeOtions[] = "12:00 AM"; viewMode: 'months', minViewMode: 'months', autoclose: true, - orientation: 'bottom' - }) + orientation: 'bottom', + startDate: new Date(2025, 0), // Jan is month 0 + endDate: new Date() // current date as max + }); @@ -2569,12 +2717,12 @@ $timeOtions[] = "12:00 AM"; }).catch(err => console.log("Error enabling fullscreen:", err)); } else { document.exitFullscreen().then(() => { - div.style.width = "100%"; + div.style.width = "100%"; div.style.height = "auto"; // Reset .table-responsive height when exiting fullscreen - // If .table-responsive exists, set its height to 90vh - if (tableResponsive) { + // If .table-responsive exists, set its height to 90vh + if (tableResponsive) { tableResponsive.style.maxHeight = "450px"; tableResponsive.style.overflowY = "auto"; // Allow scrolling if needed } @@ -2674,4 +2822,259 @@ $timeOtions[] = "12:00 AM"; let parts = dateString.split('-'); return new Date(parts[2], parts[1] - 1, parts[0]); // Year, Month (0-based), Day } + + + + + + \ No newline at end of file diff --git a/app/Views/stock/trpSandUseStockDetails.php b/app/Views/stock/trpSandUseStockDetails.php index 2bee9dbf..3767b999 100644 --- a/app/Views/stock/trpSandUseStockDetails.php +++ b/app/Views/stock/trpSandUseStockDetails.php @@ -283,6 +283,11 @@ .card { margin-bottom: 5px; } + + .hidden-row { + display: none; + } + @@ -319,76 +324,90 @@
- - - -
- - -
+
+
-
- - " - class="form-control " - data-provide="datepicker" - data-date-format="M-yyyy" - data-date-min-view-mode="1" readonly - style="max-width: 175px;"> +
+
+ +
+ -
+
- + " + class="form-control " + readonly + style="max-width: 175px;"> - - - - - - - - - - - - - - +
+
+ + + + + + + + + + + + + + + + + + + + +
+ +
+
-
-
- -
+
- - +
- +