From ba328c5fe7627970b495fd694225495670e0f3cf Mon Sep 17 00:00:00 2001 From: vadivelJ96 Date: Mon, 7 Apr 2025 15:48:21 +0530 Subject: [PATCH 01/28] stock changes 07-04-2025 --- app/Controllers/Rawmaterialdetails.php | 8 ++- app/Views/editRawmaterial.php | 6 ++- app/Views/rawmaterialListing.php | 49 +++++++++++++++++++ app/Views/stock/incomingSilicaSandDetails.php | 2 +- 4 files changed, 61 insertions(+), 4 deletions(-) diff --git a/app/Controllers/Rawmaterialdetails.php b/app/Controllers/Rawmaterialdetails.php index 0d3ebff8..990f37ef 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']; //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'); $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/Views/editRawmaterial.php b/app/Views/editRawmaterial.php index e29874fd..e142d4b3 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/rawmaterialListing.php b/app/Views/rawmaterialListing.php index 4ea7e148..565072ef 100755 --- a/app/Views/rawmaterialListing.php +++ b/app/Views/rawmaterialListing.php @@ -76,6 +76,9 @@ $type = "success"; echo show_alert($type, $success); } + + $materialListPage = session()->getFlashdata('materialListPage') ?? $_GET['materialListPage'] ?? 1; + ?>
@@ -207,6 +210,7 @@ ; // Default to 1 if not set + + savedPage = savedPage -1 ; + + + if (!isNaN(savedPage)) { + // Check if the DataTable is initialized + if ($.fn.DataTable.isDataTable('#raw_material_list_table')) { + var dataTable = $('#raw_material_list_table').DataTable(); + + // Get the total number of pages in DataTable + var totalPages = dataTable.page.info().pages; + + // Ensure the page number is within range + if (savedPage >= totalPages) { + savedPage = totalPages > 0 ? totalPages - 1 : 0; + } + + // Set DataTable to the saved page + dataTable.page(savedPage).draw(false); + } + } + // Date range filter function // $.fn.dataTable.ext.search.push( // function (settings, data, dataIndex) { @@ -542,10 +570,31 @@ $(document).ready(function () { }); }); + + - - + @@ -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 From 963b6d888d46a44aaed2867d809f4e697f8c3254 Mon Sep 17 00:00:00 2001 From: VE10-Sanjeev Date: Thu, 10 Apr 2025 13:02:26 +0000 Subject: [PATCH 08/28] export XL --- app/Config/Routes.php | 2 + app/Controllers/Payslip.php | 318 ++++++++++++++++++++++++- app/Helpers/excel_helper.php | 409 ++++++++++++++++++++++++++++++-- app/Models/Monthlypay_model.php | 4 +- app/Views/monthlypayinputs.php | 32 +++ 5 files changed, 733 insertions(+), 32 deletions(-) diff --git a/app/Config/Routes.php b/app/Config/Routes.php index f3ea3138..7070883c 100755 --- a/app/Config/Routes.php +++ b/app/Config/Routes.php @@ -203,6 +203,8 @@ $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('emppaydate/addemppaydate', 'Emppaydate::addemppaydate'); $routes->post('emppaydate/addNewemppay', 'Emppaydate::addNewemppay'); diff --git a/app/Controllers/Payslip.php b/app/Controllers/Payslip.php index 5d09e9e2..26810657 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,315 @@ 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); + + $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) { 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/Models/Monthlypay_model.php b/app/Models/Monthlypay_model.php index d984d3d6..12903b92 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/Views/monthlypayinputs.php b/app/Views/monthlypayinputs.php index 1cb5f9e8..cc6704ee 100755 --- a/app/Views/monthlypayinputs.php +++ b/app/Views/monthlypayinputs.php @@ -201,6 +201,12 @@ + " + title=""> + + + @@ -949,6 +955,32 @@ $(document).ready(function () { }); } + function DataForExportExcel(){ + var my = $('#monthyear').val(); + $('#loader').show(); + $.ajax({ + data:{MY:my}, + type: "POST", + url: "exportMonthlyPayInputs", + success: function(data) { + if(data){ + alert("step1"); + }else{ + alert("false"); + } + }, + error:function(error){ + alert("error"); + console.log("error occured..!!" ,error); + }, + complete:function(){ + $('#loader').hide(); + console.log('ajax call completed..!!'); + } + }); + + } + $("#monthyear").change(function() { From 8a76fbcf52af53e96aeb81987b83702aeb515de6 Mon Sep 17 00:00:00 2001 From: VE10-Sanjeev Date: Sun, 13 Apr 2025 16:22:31 +0000 Subject: [PATCH 09/28] tracker issues fixes --- app/Config/Routes.php | 1 + app/Controllers/Inwardgateregister.php | 3 +- app/Controllers/Monthlypay.php | 20 +++ app/Controllers/Payslip.php | 18 ++- app/Controllers/Requisitionform.php | 17 +-- app/Models/Config_model.php | 1 + app/Models/Employeedetails_model.php | 3 +- app/Models/Inwardgateregister_model.php | 4 +- app/Models/Purchaseorder_model.php | 10 +- app/Models/Rawmaterialdetails_model.php | 2 +- app/Models/Requistion_model.php | 8 +- app/Views/EditservicePurchaseorder.php | 71 ++++++---- app/Views/accountsDashboard.php | 8 +- app/Views/alterpurchaseorder.php | 97 ++++++++++---- app/Views/capitalpurchaseorder.php | 51 ++++++-- app/Views/driverPayslipGeneratePrint.php | 143 ++++++++++++--------- app/Views/editCapitalAmendPO.php | 42 ++++-- app/Views/editCapitalPo.php | 61 ++++++--- app/Views/editImportAmendPO.php | 36 ++++-- app/Views/editRevenueAmendPO.php | 46 +++++-- app/Views/editRevenuepurchaseorder.php | 64 ++++++--- app/Views/editServiceAmendPO.php | 50 ++++--- app/Views/editconfig.php | 27 ++-- app/Views/editimportpo.php | 61 ++++++--- app/Views/editrequisitionform.php | 46 +++++-- app/Views/employeeLeaveApplicationForm.php | 75 ++++++++++- app/Views/importpo.php | 47 +++++-- app/Views/inwardgateregister.php | 49 ++++++- app/Views/purchaseorder.php | 51 ++++++-- app/Views/rawmaterialListing.php | 8 +- app/Views/requisitionform.php | 32 ++++- app/Views/requisitionlisting.php | 2 +- app/Views/servicePurchaseorder.php | 46 +++++-- app/Views/viewinwardgateregister.php | 8 +- 34 files changed, 871 insertions(+), 337 deletions(-) diff --git a/app/Config/Routes.php b/app/Config/Routes.php index a6c7e695..929c4b0b 100755 --- a/app/Config/Routes.php +++ b/app/Config/Routes.php @@ -204,6 +204,7 @@ $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'); diff --git a/app/Controllers/Inwardgateregister.php b/app/Controllers/Inwardgateregister.php index 696df7f7..e42414ab 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);
   }
diff --git a/app/Controllers/Monthlypay.php b/app/Controllers/Monthlypay.php
index 453ffa6c..9ec20dd5 100755
--- a/app/Controllers/Monthlypay.php
+++ b/app/Controllers/Monthlypay.php
@@ -1041,6 +1041,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 26810657..d493ed23 100755
--- a/app/Controllers/Payslip.php
+++ b/app/Controllers/Payslip.php
@@ -587,7 +587,23 @@ class Payslip extends BaseController
 			}
 		}
 		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);
diff --git a/app/Controllers/Requisitionform.php b/app/Controllers/Requisitionform.php
index 287dee63..df083ed1 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);
 	}
 
 	/**
@@ -298,7 +287,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'];
diff --git a/app/Models/Config_model.php b/app/Models/Config_model.php
index cd16446c..34fb88c8 100755
--- a/app/Models/Config_model.php
+++ b/app/Models/Config_model.php
@@ -337,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/Employeedetails_model.php b/app/Models/Employeedetails_model.php
index 9e2348e0..fd8e6aa6 100755
--- a/app/Models/Employeedetails_model.php
+++ b/app/Models/Employeedetails_model.php
@@ -264,7 +264,8 @@ class Employeedetails_model extends Model
             ->join('t_employee_details as emp', 'emp.empid=tbl.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');
+            ->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/Inwardgateregister_model.php b/app/Models/Inwardgateregister_model.php
index a7983aa8..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,
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..8017f97e 100755
--- a/app/Models/Rawmaterialdetails_model.php
+++ b/app/Models/Rawmaterialdetails_model.php
@@ -444,7 +444,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..d2fe8011 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 );
@@ -197,7 +197,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,7 +587,7 @@ 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;
diff --git a/app/Views/EditservicePurchaseorder.php b/app/Views/EditservicePurchaseorder.php
index 401b562d..2ee52d2a 100755
--- a/app/Views/EditservicePurchaseorder.php
+++ b/app/Views/EditservicePurchaseorder.php
@@ -861,7 +861,7 @@ if (!empty($getlogpodtl)) {
 		$('#EditAfterServiceTax').val('');
 		$('#EditAfterKrishiTax').val('');
 		$('#EditAfterSwachhTax').val('');
-		$('#EditTotalOrderValue ').val('');
+		$('#EditTotalOrderValue').val('');
 		$('#EditRate').val('');
 
 		$("#EditItemName").val('');
@@ -1274,6 +1274,7 @@ if (!empty($getlogpodtl)) {
 												Requisition No
 												Item Code
 												Item Description
+												HSN/SAC
 												Line Item Specs
 												Quantity
 												UOM
@@ -1309,6 +1310,7 @@ if (!empty($getlogpodtl)) {
 														MaterialCode ?>
 														MaterialName, 0, 13, "...");
 																								echo $shortName; ?>
+														HSNCODE ?>
 														
 															
 																;
+		var openOrder = ;
 		if(openOrder){
 			$('#Quantity').val(0);
 			$('#Quantity').removeAttr('required');
@@ -2583,7 +2585,7 @@ if (!empty($getlogpodtl)) {
 
 
 	$('#EditotherDescription').hide();
-	$('#otherdescription').hide()
+	$('#otherdescription').hide();
 
 
 
@@ -2597,6 +2599,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,7 +2676,8 @@ if (!empty($getlogpodtl)) {
 						${temp}
 						${Reqnumber}
 						${materialCode}
-						${shorten}`;
+						${shorten}
+						${HSN}`;
 			if (PONOStatus === "PO_DRAFT" || PONOStatus === "PO_CREATED") {
 				rowHtml += `;
+			var openOrder = ;
 		    if(!openOrder){
 				if ($('#Quantity').val() == '') {
 					alert('Please Enter the Quantity value');
@@ -3356,6 +3373,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 +3435,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 +3487,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 +3533,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 +3563,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 +3571,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 +3613,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 +3652,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 +3679,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/accountsDashboard.php b/app/Views/accountsDashboard.php
index 534550c1..efe753ab 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 "";
@@ -427,6 +427,7 @@
 									SNo
 										Item Code
 										Item Description
+										HSN/SAC
 										UOM
 										Ordered Qty
 										Received Qty
@@ -804,6 +805,7 @@
 									'' + i + '' +
 									'' + item.MaterialCode + '' +
 									'' + item.MaterialName + '' +
+									'' + ((item.HSNCODE) ? item.HSNCODE : '') + '' +
 									'' + item.UOM + '' +
 									'' + parseInt(item.Quantity) + '' +
 									'' +
@@ -843,6 +845,7 @@
 										'' + i + '' +
 										'' + item.MaterialCode + '' +
 										'' + item.MaterialName + '' +
+										'' + ((item.HSNCODE) ? item.HSNCODE : '') + '' +
 										'' + item.UOM + '' +
 										'' + parseInt(item.Quantity) + '' +
 										'' +
@@ -878,6 +881,7 @@
 										'' + i + '' +
 										'' + item.MaterialCode + '' +
 										'' + item.MaterialName + '' +
+										'' + ((item.HSNCODE) ? item.HSNCODE : '') + '' +
 										'' + item.UOM + '' +
 										'' + item.Quantity + '' +
 										'' + item.QuantityAsPerInvoice + '' +
diff --git a/app/Views/alterpurchaseorder.php b/app/Views/alterpurchaseorder.php
index 03e67068..ffea7946 100755
--- a/app/Views/alterpurchaseorder.php
+++ b/app/Views/alterpurchaseorder.php
@@ -2222,8 +2222,8 @@ if (!empty($INRSYMBOL)) {
                                 $("#ServiceMaterialCode").append($('').val("0").html("Select Item Code"));
 
                                 $.each(JSON.parse(data), function (index, value) {
-                                    $("#ServiceMaterialCode").append($('').val(value.MaterialCode).html(value.MaterialCode + "-" + value.MaterialName));
-
+                                    var HSNCODE = value.HSNCODE ? value.HSNCODE+" - " : "";
+								    $("#ServiceMaterialCode").append($('').val(value.MaterialCode).html( HSNCODE + value.MaterialName+ " ( "+value.MaterialCode+" ) "));
 
                                 });
                             } else if (input == 'REVENUE') {
@@ -2233,9 +2233,8 @@ if (!empty($INRSYMBOL)) {
                                 $("#MaterialCode").append($('').val("0").html("Select Item Code"));
 
                                 $.each(JSON.parse(data), function (index, value) {
-                                    $("#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+" ) "));
                                 });
                             } else {
 
@@ -2366,7 +2365,8 @@ if (!empty($INRSYMBOL)) {
             //This function is used to add material list after delete           
             $.each(JSON.parse(materialData), function (index, value) {
                 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+" ) "));
                 }
             });
 
@@ -2950,6 +2950,7 @@ if (!empty($INRSYMBOL)) {
                                                 Requisition No
                                                 Item Code
                                                 Item Description
+                                                HSN/SAC
                                                 Line Item Specs
                                                 Quantity
                                                 UOM
@@ -6080,6 +6081,12 @@ if (!empty($INRSYMBOL)) {
 
             // $('#ReqNo').val(Reqnumber).remove();
             // $('#ReqNo option[value='+Reqnumber+']').remove();
+            var selectedRText = $('#MaterialCode option:selected').text();
+            var Rparts = selectedRText.split('-');
+			var RHSN = selectedRText.includes('-') && /^\d+$/.test(Rparts[0].trim()) 
+						? Rparts[0].trim() 
+						: '';
+
             $('#MaterialCode option[value=' + materialCode + ']').remove();
 
 
@@ -6100,6 +6107,7 @@ if (!empty($INRSYMBOL)) {
                     ${Reqnumber}
                     ${materialCode}
                     ${rshorten}
+                    ${RHSN}
                     -
@@ -6748,6 +6756,12 @@ if (!empty($INRSYMBOL)) {
             var AvilBudget = $('#AvalBuget').val();
             var costCode = $('#CostCenterName').val();
             var materialCode = $('#ServiceMaterialCode').val();
+            var SselectedText = $('#ServiceMaterialCode option:selected').text();
+			var Sparts = SselectedText.split('-');
+			var SHSN = SselectedText.includes('-') && /^\d+$/.test(Sparts[0].trim()) 
+						? Sparts[0].trim() 
+						: '';
+
             var materialName = $("#ServiceDescription").val();
             var uom = $("#ServiceUOM").val();
             var addPer = '';
@@ -6804,6 +6818,7 @@ if (!empty($INRSYMBOL)) {
                     ${Reqnumber}
                     ${materialCode}
                     ${sshorten}
+                    ${SHSN}
                     -
@@ -7007,14 +7022,14 @@ if (!empty($INRSYMBOL)) {
             $('#EditEmergPer').val($('#Serviceper' + userid).val());
             $('#EditQuantity').val($('#quantity' + userid).val());
             $('#EditRate').val($('#itemRate' + userid).val());
-            $('#txtEditBasicValue').val(cellval[8].innerHTML);
+            $('#txtEditBasicValue').val(cellval[9].innerHTML);
             $('#EditAfterCgst').val($('#AfterCgst' + userid).val());
             $('#EditAfterSgst').val($('#AfterSgst' + userid).val());
             $('#EditAfterIgst').val($('#AfterIgst' + userid).val());
             $('#EditCgst').val($('#Cgst' + userid).val());
             $('#EditSgst').val($('#Sgst' + userid).val());
             $('#EditIgst').val($('#Igst' + userid).val());
-            $('#EditTotalOrderValue').val(cellval[10].innerHTML);
+            $('#EditTotalOrderValue').val(cellval[11].innerHTML);
             $('#EditOtherAllowances').val($('#OtherAmt' + userid).val());
 
             tinyMCE.get('EdittxtSpcialInstructionSingle').setContent($('#ItemServiceDescription' + userid).val());
@@ -7026,7 +7041,11 @@ if (!empty($INRSYMBOL)) {
 
             $("#EditMaterialCode").empty();
             // $('#EditMaterialCode').val("").select2();
-            $("#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));
 
             if (typeof materialData !== 'undefined' && materialData !== null && materialData !== '') {
                 var parsedMaterialData = JSON.parse(materialData);
@@ -7034,7 +7053,9 @@ if (!empty($INRSYMBOL)) {
                 $.each(parsedMaterialData, function (index, value) {
                     // Assuming userid is defined somewhere in your code
                     if ($('#materialCode' + userid).val() != value.MaterialCode) {
-                        $("#EditMaterialCode").append($('').val(value.MaterialCode).html(value.MaterialCode + "-" + value.MaterialName));
+                        // $("#EditMaterialCode").append($('').val(value.MaterialCode).html(value.MaterialCode + "-" + value.MaterialName));
+                        var HSNCODE = obj.HSNCODE ? obj.HSNCODE+" - " : "";
+						$("#EditMaterialCode").append($('').val(value.MaterialCode).html( HSNCODE + value.MaterialName+ " ( "+value.MaterialCode+" ) "));
                     }
                 });
             } else {
@@ -7127,17 +7148,23 @@ if (!empty($INRSYMBOL)) {
             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;
             cellval[2].innerHTML = editMaterialCode;
             cellval[3].innerHTML = editDescription;
-            cellval[5].innerHTML = editQuantity;
-            cellval[6].innerHTML = editUOM;
-            cellval[7].innerHTML = itemRate;
-            cellval[8].innerHTML = basicval;
-            cellval[9].innerHTML = TotalTaxValue;
-            cellval[10].innerHTML = TotalOrderValue;
+            cellval[4].innerHTML = editHSN;
+            cellval[6].innerHTML = editQuantity;
+            cellval[7].innerHTML = editUOM;
+            cellval[8].innerHTML = itemRate;
+            cellval[9].innerHTML = basicval;
+            cellval[10].innerHTML = TotalTaxValue;
+            cellval[11].innerHTML = TotalOrderValue;
 
 
             $('#materialCode' + userid).val(editMaterialCode);
@@ -7674,7 +7701,7 @@ if (!empty($INRSYMBOL)) {
             $('#EditRevenueQuantity').val($('#quantity' + userid).val());
             $('#EditRevenueRate').val($('#itemRate' + userid).val());
             $('#editrevenueEmergPer').val($('#per' + userid).val());
-            $('#txtEditRevenueBasicValue').val(cellval[8].innerHTML);
+            $('#txtEditRevenueBasicValue').val(cellval[9].innerHTML);
             RequistQuantity = $('#quantity' + userid).val();
             $('#txtEditDiscount').val($('#DisVal' + userid).val());
             $('#txtEditAfterDiscount').val($('#AfterDisVal' + userid).val());
@@ -7708,14 +7735,18 @@ if (!empty($INRSYMBOL)) {
 
 
             $("#EditRevenueMaterialCode").empty();
-
-            $("#EditRevenueMaterialCode").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() + ' ) ';
+            $("#EditRevenueMaterialCode").append($('').val($('#materialCode' + userid).val()).html(P3));
             if (typeof materialData !== 'undefined' && materialData !== null && materialData !== '') {
                 var parsedMaterialData = JSON.parse(materialData);
 
                 $.each(parsedMaterialData, function (index, value) {
                     if ($('#materialCode' + userid).val() != value.MaterialCode) {
-                        $("#EditRevenueMaterialCode").append($('').val(value.MaterialCode).html(value.MaterialCode + "-" + value.MaterialName));
+                        var HSNCODE = value.HSNCODE ? value.HSNCODE+" - " : "";
+						$("#EditRevenueMaterialCode").append($('').val(value.MaterialCode).html( HSNCODE + value.MaterialName+ " ( "+obj.MaterialCode+" ) "));
                     }
                 });
             } else {
@@ -7733,6 +7764,12 @@ if (!empty($INRSYMBOL)) {
 
         var editselectedMaterialCode = '';
         editselectedMaterialCode = $("#EditRevenueMaterialCode").val();
+        var selectedRevenuText = $('#EditRevenueMaterialCode option:selected').text();
+        var editRevenuparts = selectedRevenuText.split('-');
+        var editRevenueHSN = editselectedText.includes('-') && /^\d+$/.test(editRevenuparts[0].trim()) 
+						? editRevenuparts[0].trim() 
+						: '';
+		
 
         $.each(JSON.parse(materialData), function (index, value) {
             if (editselectedMaterialCode == value.MaterialCode) {
@@ -7806,15 +7843,23 @@ if (!empty($INRSYMBOL)) {
             var userid = $("#hiddenRevenueuserid").val();
 
             var tr = document.getElementById(userid);
+
+            var editRselectedText = $('#EditRevenueMaterialCode option:selected').text();
+            var editRparts = editRselectedText.split('-');
+            var editRHSN = editRselectedText.includes('-') && /^\d+$/.test(editRparts[0].trim()) 
+                            ? editRparts[0].trim() 
+                            : '';
+		
             var cellval = tr.cells;
             cellval[2].innerHTML = editMaterialCode;
             cellval[3].innerHTML = editDescription;
-            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);
+            cellval[4].innerHTML = editRHSN;
+            cellval[6].innerHTML = parseFloat(editQuantity).toFixed(2);
+            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);
diff --git a/app/Views/capitalpurchaseorder.php b/app/Views/capitalpurchaseorder.php
index d9eff2ad..d9c3e40a 100755
--- a/app/Views/capitalpurchaseorder.php
+++ b/app/Views/capitalpurchaseorder.php
@@ -804,6 +804,7 @@ if (!empty($INRSYMBOL)) {
                                                 Requisition No
                                                 Item Code
                                                 Item Description
+                                                HSN/SAC
                                                 Line Item Specs
                                                 Quantity
                                                 UOM
@@ -2643,8 +2644,9 @@ if (!empty($INRSYMBOL)) {
 
 
                             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));
                             }
 
                         }
@@ -3443,6 +3445,11 @@ if (!empty($INRSYMBOL)) {
 
 
 
+            var selectedText = $('#MaterialCode option:selected').text();
+            var parts = selectedText.split('-');
+			var HSN = selectedText.includes('-') && /^\d+$/.test(parts[0].trim()) 
+						? parts[0].trim() 
+						: '';
 
 
             $('#MaterialCode option[value=' + materialCode + ']').remove();
@@ -3484,6 +3491,7 @@ if (!empty($INRSYMBOL)) {
                         ${Reqnumber}
                         ${materialCode}
                         ${shorten}
+                        ${HSN}
                         
 						-
@@ -3992,8 +4000,8 @@ if (!empty($INRSYMBOL)) {
 
 
                     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+" ) "));
                     }
 
 
@@ -4298,7 +4306,7 @@ if (!empty($INRSYMBOL)) {
 
             console.log($('#Igst' + userid).val());
 
-            $('#EdittxtTotalOrderValue').val(cellval[10].innerHTML);
+            $('#EdittxtTotalOrderValue').val(cellval[11].innerHTML);
             $('#EditCgst').val($('#Cgst' + userid).val());
             $('#EditAfterCgst').val($('#AfterCgst' + userid).val());
             $('#EditSgst').val($('#Sgst' + userid).val());
@@ -4375,13 +4383,23 @@ if (!empty($INRSYMBOL)) {
             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()));
             $('#EditRateIn').html('Rate(in' + " " + DisplayCurrencySymbol + '/' + EditUOM + ')');
             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 HSNCODE = obj.HSNCODE ? obj.HSNCODE+" - " : "";
+							$("#EditMaterialCode").append($('').val(obj.MaterialCode).html( HSNCODE + obj.MaterialName+ " ( "+obj.MaterialCode+" ) "));
 
                     }
                 });
@@ -4923,6 +4941,12 @@ if (!empty($INRSYMBOL)) {
             $('#ClearingCharges' + userid).val(Clearing);
             $('#Subtotal' + userid).val(Subtotal);
 
+            var editselectedText = $('#EditMaterialCode option:selected').text();
+            var editparts = editselectedText.split('-');
+			var editHSN = editselectedText.includes('-') && /^\d+$/.test(editparts[0].trim()) 
+						? editparts[0].trim() 
+						: '';
+
             if (capitalType == 'International') {
                 TotalTaxValue = 0.00;
                 Total = basicval;
@@ -4930,13 +4954,14 @@ if (!empty($INRSYMBOL)) {
 
             cellval[2].innerHTML = materialCode;
             cellval[3].innerHTML = materialName;
+            cellval[4].innerHTML = editHSN;
 
-            cellval[5].innerHTML = quantity;
-            cellval[6].innerHTML = uom;
-            cellval[7].innerHTML = itemRate;
-            cellval[8].innerHTML = basicval;
-            cellval[9].innerHTML = TotalTaxValue;
-            cellval[10].innerHTML = Total;
+            cellval[6].innerHTML = quantity;
+            cellval[7].innerHTML = uom;
+            cellval[8].innerHTML = itemRate;
+            cellval[9].innerHTML = basicval;
+            cellval[10].innerHTML = TotalTaxValue;
+            cellval[11].innerHTML = Total;
 
 
             $('#EDITCAPITAL').modal('hide');
diff --git a/app/Views/driverPayslipGeneratePrint.php b/app/Views/driverPayslipGeneratePrint.php
index 916654aa..6002e57b 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_loads ?>
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..92e28978 100755 --- a/app/Views/editCapitalAmendPO.php +++ b/app/Views/editCapitalAmendPO.php @@ -888,6 +888,7 @@ if (!empty($POItem) && $CapitalRange == '1') { + @@ -913,6 +914,7 @@ if (!empty($POItem) && $CapitalRange == '1') { + + @@ -976,6 +977,7 @@ $(document).ready(function () { + - `; + + `; if (PONOStatus === "PO_DRAFT" || PONOStatus === "PO_CREATED") { rowHtml += ` + @@ -1304,6 +1305,7 @@ if (!empty($RequistionDetails)) { + + @@ -1341,6 +1342,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)) { + + @@ -297,13 +298,35 @@ $(".searchabledropdown").select2(); - $('#IGRLink').on('click', function() { - filecheck(1); + function debounce(func, timeout = 300) { + let timer; + return (...args) => { + clearTimeout(timer); + timer = setTimeout(() => { func.apply(this, args); }, timeout); + }; + } + + $('#IGRLink, #IGRDraftLink').on('click', function(e) { + e.preventDefault(); + const $btn = $(this); + const strMsg = $btn.is('#IGRLink') + ? 'Generate IGR?' + : 'Save as draft IGR?'; + + if (confirm('Are you sure? ' + strMsg)) { + $btn.prop("disabled", true) + .html(' Processing...'); + filecheck($btn.is('#IGRLink') ? 1 : 0); + } }); - $('#IGRDraftLink').on('click', function() { - filecheck(0); - }); + // $('#IGRLink').on('click', function() { + // filecheck(1); + // }); + + // $('#IGRDraftLink').on('click', function() { + // filecheck(0); + // }); function filecheck(status) { $('#hideIGRStatus').val(status); @@ -320,9 +343,19 @@ // } // } function Save() { - $("#IGRLink, #IGRDraftLink").prop("disabled", true); + + $("#IGRLink, #IGRDraftLink") + .prop("disabled", true) + .html(' Processing...'); if (validate()) { $("#IGRForm").submit(); } - else { $("#IGRLink, #IGRDraftLink").prop("disabled", false); } + else { + // Re-enable buttons and restore original text + $("#IGRLink, #IGRDraftLink") + .prop("disabled", false) + .text(function() { + return $(this).attr('id') === 'IGRLink' ? 'Generate IGR' : 'Save as Draft IGR'; + }); + } } }); @@ -466,6 +499,7 @@ '' + '' + '' + + '' + '' + '' + '' + @@ -898,6 +932,7 @@ '' + '' + '' + + '' + '' + '' + '' + diff --git a/app/Views/purchaseorder.php b/app/Views/purchaseorder.php index 72935ced..8dbe100b 100755 --- a/app/Views/purchaseorder.php +++ b/app/Views/purchaseorder.php @@ -406,8 +406,9 @@ if (!empty($INRSYMBOL)) { 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)); } } @@ -2191,6 +2192,7 @@ if (!empty($INRSYMBOL)) { + @@ -3311,7 +3313,7 @@ if (!empty($INRSYMBOL)) { } else { $('#EditPer').val($('#uom' + userid).val()); } - $('#txtEditBasicValue').val(cellval[8].innerHTML); + $('#txtEditBasicValue').val(cellval[9].innerHTML); RequistQuantity = $('#quantity' + userid).val(); $('#txtEditDiscount').val($('#DisVal' + userid).val()); $('#txtEditAfterDiscount').val($('#AfterDisVal' + userid).val()); @@ -3346,7 +3348,17 @@ 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())); + // $("#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++) { @@ -3373,7 +3385,9 @@ 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+" ) ")); + // $("#EditMaterialCode").append($('').val(obj.MaterialCode).html(obj.MaterialCode + "-" + obj.MaterialName)); } } @@ -3443,6 +3457,12 @@ if (!empty($INRSYMBOL)) { // $('#ReqNo').val(Reqnumber).remove(); // $('#ReqNo option[value='+Reqnumber+']').remove(); + var selectedText = $('#MaterialCode option:selected').text(); + var parts = selectedText.split('-'); + var HSN = selectedText.includes('-') && /^\d+$/.test(parts[0].trim()) + ? parts[0].trim() + : ''; + $('#MaterialCode option[value=' + materialCode + ']').remove(); @@ -3485,6 +3505,7 @@ if (!empty($INRSYMBOL)) { + - - - - + + + + + + + - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -1123,10 +1208,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 +1219,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 +1304,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 +1325,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 +1347,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 +1367,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 +1389,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 +1409,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 +1432,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 +1470,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 +1498,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 +1517,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 +1541,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 +1563,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 +1599,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 6b626dbe..0edcb20d 100644 --- a/app/Views/stock/drierMachineDetails.php +++ b/app/Views/stock/drierMachineDetails.php @@ -535,7 +535,9 @@ $datefordropdown = format_date($datefordropdown, 0, 'M-Y');
* - +
@@ -592,9 +594,11 @@ $datefordropdown = format_date($datefordropdown, 0, 'M-Y');
- + * - +
@@ -699,7 +703,9 @@ $datefordropdown = format_date($datefordropdown, 0, 'M-Y');
* - +
@@ -756,9 +762,11 @@ $datefordropdown = format_date($datefordropdown, 0, 'M-Y');
- + * - +
@@ -807,7 +815,7 @@ $datefordropdown = format_date($datefordropdown, 0, 'M-Y'); - + @@ -895,12 +903,12 @@ $datefordropdown = format_date($datefordropdown, 0, 'M-Y'); @@ -1122,9 +1130,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; } @@ -1188,6 +1196,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); @@ -1203,6 +1222,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); @@ -1219,6 +1249,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); @@ -1233,13 +1274,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) { @@ -1291,6 +1357,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); @@ -1306,6 +1383,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); @@ -1322,6 +1410,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); @@ -1332,6 +1431,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; + } + } + + @@ -1395,17 +1529,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); }); @@ -1417,25 +1548,37 @@ $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'); + }); - }) - - - }) + }); + diff --git a/app/Views/stock/dustAndRoughStockDetails.php b/app/Views/stock/dustAndRoughStockDetails.php index 97456c67..348f287b 100644 --- a/app/Views/stock/dustAndRoughStockDetails.php +++ b/app/Views/stock/dustAndRoughStockDetails.php @@ -332,73 +332,86 @@
- - - - -
- - -
-
- -
- - " - 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 " + data-provide="datepicker" + data-date-format="M-yyyy" + data-date-min-view-mode="1" readonly + style="max-width: 175px;"> + +
+ + + +
+ + + + + + + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+ +
- - - + + + @@ -597,7 +610,8 @@ if ($dateInMonthDmYFormat === $currentDate) { echo 'style="background: #cef0ad;"'; } - ?>> + ?> + > + + + + + + + + + + + @@ -667,8 +693,6 @@ } - - function checkDateRange(fromDate, toDate, tableDate) { // Convert the dates to a comparable format (YYYY-MM-DD) let from = convertToDate(fromDate); @@ -703,9 +727,8 @@ var updateDustAndRoughStockDetails = 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: { updateDustAndRoughStockDetails @@ -715,10 +738,8 @@ success: function(data) { if (data) { - $('#loader').hide(); console.log(data); - alert(data); - window.location.reload(); + showMessage(data); } }, @@ -730,7 +751,7 @@ console.error("Response Text:", xhr.responseText); }, complete: function() { - $('#loader').hide(); + console.log("Ajax Request Completed for dust and Rough Stock Details"); } }); @@ -774,12 +795,26 @@ function finalRoughStockChange(tdElement) { try { + + let basicCheck =checkIsNumber(tdElement.innerText.trim()); + + if(basicCheck == 0){ + alert("Kindly Enter Numbers only..!!"); + return ; + } + let dataId = tdElement.getAttribute('data-id') let finalRoughStock = validateInput(tdElement.innerText); let dustStock = validateInput(document.querySelector(`td.dust[data-id="${dataId}"]`).innerText); let total = (Number(finalRoughStock) + Number(dustStock)); document.querySelector(`td.total[data-id="${dataId}"]`).innerText = total; + let table = document.getElementById('dustAndRoughStockDetailsTableId'); + + let column = 'finalRough' ; + + calculateTotal(table,dataId,column); + } catch (error) { console.error("There is an error updating stock ..!!" + error); } @@ -787,12 +822,25 @@ function dustStockChange(tdElement) { try { + + let basicCheck =checkIsNumber(tdElement.innerText.trim()); + + if(basicCheck == 0){ + alert("Kindly Enter Numbers only..!!"); + return ; + } + let dataId = tdElement.getAttribute('data-id') let finalRoughStock = validateInput(document.querySelector(`td.finalRough[data-id="${dataId}"]`).innerText); let dustStock = validateInput(tdElement.innerText); let total = (Number(finalRoughStock) + Number(dustStock)); document.querySelector(`td.total[data-id="${dataId}"]`).innerText = total; + let table = document.getElementById('dustAndRoughStockDetailsTableId'); + let column = 'dust'; + + calculateTotal(table,dataId,column); + } catch (error) { @@ -801,8 +849,6 @@ } } - - function validateInput(input) { @@ -818,12 +864,21 @@ // 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; + } + } + @@ -847,45 +902,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'); + }); - }) - - - }) + }); + + + + + + \ No newline at end of file diff --git a/app/Views/stock/gasStockDetails.php b/app/Views/stock/gasStockDetails.php index 69e45d85..133d63c9 100644 --- a/app/Views/stock/gasStockDetails.php +++ b/app/Views/stock/gasStockDetails.php @@ -312,6 +312,20 @@
+
+
+
@@ -656,20 +670,34 @@ -
- - - - - - - - - - - - - + + + + + + + + + + + + + + @@ -768,8 +796,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 ?> ').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 +3348,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 +3436,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 +4069,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..f8ad6ac1 100755 --- a/app/Views/editCapitalPo.php +++ b/app/Views/editCapitalPo.php @@ -943,6 +943,7 @@ $(document).ready(function () { Requisition No Item Code Item DescriptionHSN/SAC Line Item Specs Quantity UOMMaterialCode ?> MaterialName, 0, 13, "..."); echo $shortName; ?>HSNCODE ?> ').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 +4804,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,7 +4952,8 @@ $(document).ready(function () { ${temp} ${Reqnumber} ${materialCode}${shorten}${shorten}${HSN}').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 +5845,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 +5897,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 +5964,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()); @@ -6715,19 +6737,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/editImportAmendPO.php b/app/Views/editImportAmendPO.php index 1500d30e..4e38583b 100755 --- a/app/Views/editImportAmendPO.php +++ b/app/Views/editImportAmendPO.php @@ -1279,6 +1279,7 @@ if (!empty($RequistionDetails)) { SNo Requisition No Item DescriptionHSN/SAC Line Item Specs Quantity UOMReqNo ?> MaterialName, 0, 13, "..."); echo $shortName; ?>HSNCODE ?> ').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+" ) ")); } } @@ -2678,10 +2680,19 @@ if (!empty($RequistionDetails)) { - $('#EditTotalOrderValue').val(cellval[6].innerHTML); + $('#EditTotalOrderValue').val(cellval[7].innerHTML); $("#EditMaterialCode").empty(); var Material = ; - $("#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) { @@ -2724,6 +2735,13 @@ if (!empty($RequistionDetails)) { var CostCode = $("#EditCostCenter").val(); var AvilBudget = $('#EditAvlBudAmt').val(); var editMaterialCode = $("#EditMaterialCode").val(); + + var editselectedText = $('#EditMaterialCode option:selected').text(); + var editparts = editselectedText.split('-'); + var editHSN = editselectedText.includes('-') && /^\d+$/.test(editparts[0].trim()) + ? editparts[0].trim() + : ''; + var edititemname = $("#EditItemName").val(); var editUOM = $('#EditUOM').val(); var editQuantity = $('#EditQuantity').val(); @@ -2799,11 +2817,11 @@ if (!empty($RequistionDetails)) { var tr = document.getElementById(userid); var cellval = tr.cells; - - cellval[4].innerHTML = editQuantity; - cellval[5].innerHTML = editUOM; - cellval[6].innerHTML = itemRate; - cellval[7].innerHTML = BasicValue; + cellval[4].innerHTML = editHSN; + cellval[5].innerHTML = editQuantity; + cellval[6].innerHTML = editUOM; + cellval[7].innerHTML = itemRate; + cellval[8].innerHTML = BasicValue; $('#materialCode' + userid).val(editMaterialCode); $('#materialName' + userid).val(edititemname); diff --git a/app/Views/editRevenueAmendPO.php b/app/Views/editRevenueAmendPO.php index 5fd2ce98..91c73689 100755 --- a/app/Views/editRevenueAmendPO.php +++ b/app/Views/editRevenueAmendPO.php @@ -1316,6 +1316,7 @@ if (!empty($INRSYMBOL)) { SNo Requisition No Item DescriptionHSN/SAC Line Item Specs Quantity UOMReqNo ?> MaterialName, 0, 13, "..."); echo $shortName; ?>HSNCODE ?> '; 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 +2366,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 +2375,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 +2403,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 +2428,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 +2441,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 +2500,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 +2883,7 @@ if (!empty($INRSYMBOL)) { + + 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/inwardgateregister.php b/app/Views/inwardgateregister.php index ba94d820..9ca75e3d 100755 --- a/app/Views/inwardgateregister.php +++ b/app/Views/inwardgateregister.php @@ -160,6 +160,7 @@ # Item Code Item DescriptionHSN/SAC Rate UOM Ordered Quantity' + 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 + 'Requisition No Item Code Item DescriptionHSN/SAC Line Item Specs Quantity UOM${Reqnumber} ${materialCode} ${shorten}${HSN} - @@ -3602,17 +3623,23 @@ if (!empty($INRSYMBOL)) { 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; cellval[2].innerHTML = editMaterialCode; cellval[3].innerHTML = editDescription; - cellval[5].innerHTML = editQuantity; - cellval[6].innerHTML = editUOM; - cellval[7].innerHTML = itemRate; - cellval[8].innerHTML = basicval; - cellval[9].innerHTML = TotalTaxValue; - cellval[10].innerHTML = TotalOrderValue; + cellval[4].innerHTML = editHSN; + cellval[6].innerHTML = editQuantity; + cellval[7].innerHTML = editUOM; + cellval[8].innerHTML = itemRate; + cellval[9].innerHTML = basicval; + cellval[10].innerHTML = TotalTaxValue; + cellval[11].innerHTML = TotalOrderValue; $('#materialCode' + userid).val(editMaterialCode); diff --git a/app/Views/rawmaterialListing.php b/app/Views/rawmaterialListing.php index 565072ef..ae25f7b5 100755 --- a/app/Views/rawmaterialListing.php +++ b/app/Views/rawmaterialListing.php @@ -315,7 +315,7 @@ $(document).ready(function () { let result = JSON.parse(response); if (result.length > 0) { let tableHtml = ` - +
@@ -337,12 +337,12 @@ $(document).ready(function () { tableHtml += ` - + - - + + @@ -205,6 +206,7 @@ if (!empty($Emp)) { + + - + + @@ -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)) { + - + - + @@ -1253,6 +1254,7 @@ '' + '' + '' + + '' + '' + '' + '' + @@ -1307,6 +1309,7 @@ '' + '' + '' + + '' + '' + ''; if (userRole == 5) { // 5 - lab staff @@ -1367,6 +1370,7 @@ '' + '' + '' + + '' + '' + '' ; if (userRole == 5) { // 5 - lab staff From 75110ae438f7bf14bc579ed956fcc5a8102c8fa5 Mon Sep 17 00:00:00 2001 From: VE10-Sanjeev Date: Tue, 15 Apr 2025 06:02:32 +0000 Subject: [PATCH 10/28] Raised trackers issues --- app/Config/Routes.php | 1 + app/Controllers/Requisitionform.php | 84 +++++++++++-------------- app/Models/Rawmaterialdetails_model.php | 9 +-- app/Models/Requistion_model.php | 18 ++++-- app/Views/editrequisitionform.php | 62 ++++++++++++++++-- app/Views/inwardgateregister.php | 4 +- app/Views/requisitionform.php | 78 ++++++++++++++++------- 7 files changed, 171 insertions(+), 85 deletions(-) diff --git a/app/Config/Routes.php b/app/Config/Routes.php index 929c4b0b..110b49d4 100755 --- a/app/Config/Routes.php +++ b/app/Config/Routes.php @@ -251,6 +251,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'); diff --git a/app/Controllers/Requisitionform.php b/app/Controllers/Requisitionform.php index df083ed1..39f1d4e3 100755 --- a/app/Controllers/Requisitionform.php +++ b/app/Controllers/Requisitionform.php @@ -204,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() { @@ -277,8 +234,9 @@ class Requisitionform extends BaseController { $ReqType = $this->request->getPost('id'); + $CatType = $this->request->getPost('cid'); - $MaterialCode = $this->requistion_model->GetMaterialCode($ReqType); + $MaterialCode = $this->requistion_model->GetMaterialCode($ReqType,$CatType); $MaterialName = ""; $UOM = ""; $HTML = ""; @@ -310,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 */ @@ -390,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]); @@ -459,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 as Created!\nRequistion Number Is: ". $ReqNumber; return $this->response->setJSON([$display_message]); } @@ -592,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/Models/Rawmaterialdetails_model.php b/app/Models/Rawmaterialdetails_model.php index 8017f97e..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') diff --git a/app/Models/Requistion_model.php b/app/Models/Requistion_model.php index d2fe8011..897c3df8 100755 --- a/app/Models/Requistion_model.php +++ b/app/Models/Requistion_model.php @@ -172,14 +172,13 @@ class Requistion_model extends Model * This function is used to get the Material details for the Request type * @return array $result : This is result of the query */ - function GetMaterialCode($ReqType,$NotArray='') + function GetMaterialCode($ReqType,$CatType,$NotArray='') { $builder = $this->db->table('t_materialmaster') ->select('MaterialCode, MaterialName,UOM,material_rate,HSNCODE') - - ->where('IsActive',1); + ->where('IsActive',1) + ->where('Category',$CatType); //->where('MaterialType',$ReqType ); - $query = $builder->get(); if($NotArray == '') { @@ -594,6 +593,17 @@ class Requistion_model extends Model 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/Views/editrequisitionform.php b/app/Views/editrequisitionform.php index 68f64d22..8fe49172 100755 --- a/app/Views/editrequisitionform.php +++ b/app/Views/editrequisitionform.php @@ -322,6 +322,17 @@ td { aria-hidden="true">× @@ -620,7 +620,7 @@ - - + - - + white-space: normal !important; width: 100px !important; width:70%; + text-align:left;">${item.MaterialName} + + `; diff --git a/app/Views/gasCylinderReturned.php b/app/Views/gasCylinderReturned.php index d5c542c6..a4bca007 100644 --- a/app/Views/gasCylinderReturned.php +++ b/app/Views/gasCylinderReturned.php @@ -152,7 +152,7 @@ @@ -543,12 +543,12 @@ - + - - - - + + + + @@ -570,10 +570,10 @@ - - - - + + + + diff --git a/app/Views/includes/new_header.php b/app/Views/includes/new_header.php index fe6b57ba..e67192ba 100755 --- a/app/Views/includes/new_header.php +++ b/app/Views/includes/new_header.php @@ -759,7 +759,7 @@ diff --git a/app/Views/rawmaterialListing.php b/app/Views/rawmaterialListing.php index 565072ef..4931dcf9 100755 --- a/app/Views/rawmaterialListing.php +++ b/app/Views/rawmaterialListing.php @@ -232,7 +232,7 @@
Date
${CreatedDate}${CreatedDate} ${item.SupplierName} + ${item.PONO} ${item.POType}${item.POType} ${TotalOrderValue} diff --git a/app/Views/requisitionform.php b/app/Views/requisitionform.php index 50e95219..b14c6f0c 100755 --- a/app/Views/requisitionform.php +++ b/app/Views/requisitionform.php @@ -155,6 +155,7 @@ if (!empty($Emp)) { Material Code Material Name Material CategoryHSN/SAC Uom Quantity Action ${materialCode} ${materialName} ${categoryName}${HSN} ${uom} ${quantity} @@ -760,11 +769,14 @@ if (!empty($Emp)) { var userid = $triggerElement.data('userid'); var $tr = $('#' + userid); var $cells = $tr.find('td'); + var HSN = $cells.eq(4).text()?$cells.eq(4).text()+'-':''; + var MaterialType = HSN+$cells.eq(2).text()+' ( '+$cells.eq(1).text()+ ' ) '; $('#EditMaterialCode').val($cells.eq(1).text()); + $('#EditMaterialType').val(MaterialType); $('#EditDescription').val($cells.eq(2).text()); $('#EditCategory').val($cells.eq(3).text()); - $('#EditUOM').val($cells.eq(4).text()); - $('#EditQuantity').val($cells.eq(5).text()); + $('#EditUOM').val($cells.eq(5).text()); + $('#EditQuantity').val($cells.eq(6).text()); $('#Edituserid').val(userid); }); }); @@ -783,6 +795,13 @@ if (!empty($Emp)) { var editMaterialCode = $("#EditMaterialCode").val(); var editDescription = $("#EditDescription").val(); var editCategory = $("#EditCategory").val(); + + var editMaterialType = $('#EditMaterialType').val(); + var editparts = editMaterialType.split('-'); + var editHSN = editselectedText.includes('-') && /^\d+$/.test(editparts[0].trim()) + ? editparts[0].trim() + : ''; + var editUOM = $('#EditUOM').val(); var editQuantity = $('#EditQuantity').val(); @@ -791,8 +810,9 @@ if (!empty($Emp)) { cells.eq(1).text(editMaterialCode); cells.eq(2).text(editDescription); cells.eq(3).text(editCategory); - cells.eq(4).text(editUOM); - cells.eq(5).text(editQuantity); + cells.eq(4).text(editHSN); + cells.eq(5).text(editUOM); + cells.eq(6).text(editQuantity); $('#MaterialCode' + edituserid).val(editMaterialCode); $('#Description' + edituserid).val(editDescription); diff --git a/app/Views/requisitionlisting.php b/app/Views/requisitionlisting.php index 8cc36bac..aa7686a2 100755 --- a/app/Views/requisitionlisting.php +++ b/app/Views/requisitionlisting.php @@ -170,7 +170,7 @@ if (!empty($Status)) { newLineItem ?>StatusName); ?>StatusName); ?> ').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+" ) ")); } } @@ -686,6 +686,13 @@ if (!empty($INRSYMBOL)) { var CostCode = $("#EditCostCenter").val(); var AvilBudget = $('#EditAvlBudAmt').val(); var editMaterialCode = $("#EditMaterialCode").val(); + var selectedText = $('#EditMaterialCode option:selected').text(); + var editselectedText = $('#EditMaterialCode option:selected').text(); + var editparts = editselectedText.split('-'); + var editHSN = editselectedText.includes('-') && /^\d+$/.test(editparts[0].trim()) + ? editparts[0].trim() + : ''; + var editDescription = $("#EditItemName").val(); var editUOM = $('#EditUOM').val(); var editPer = ''; @@ -725,12 +732,13 @@ if (!empty($INRSYMBOL)) { 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); @@ -1069,6 +1077,7 @@ if (!empty($INRSYMBOL)) { Requisition No Item Code Item DescriptionHSN/SAC Line Item Specs Quantity UOM${Reqnumber} ${materialCode} ${shorten}${HSN} - diff --git a/app/Views/viewinwardgateregister.php b/app/Views/viewinwardgateregister.php index f1e04c44..34f49cb0 100755 --- a/app/Views/viewinwardgateregister.php +++ b/app/Views/viewinwardgateregister.php @@ -248,7 +248,7 @@ $time = $createddate->format('h:i A'); ?>
@@ -267,7 +267,7 @@ SupplierName ?> DeliveryChellanOrInvoiceNo ?>DeliveryChellanDate; if(!$invdate || $invdate == 'null' || $invdate === '0000-00-00 00:00:00'){ echo ""; @@ -497,6 +497,7 @@ SNo Item Code Item DescriptionHSN/SAC UOM Ordered Qty Received Qty' + i + '' + item.MaterialCode + '' + item.MaterialName + '' + ((item.HSNCODE) ? item.HSNCODE : '') + '' + item.UOM + '' + parseInt(item.Quantity) + '' + i + '' + item.MaterialCode + '' + item.MaterialName + '' + ((item.HSNCODE) ? item.HSNCODE : '') + '' + item.UOM + '' + parseInt(item.Quantity) + '' + i + '' + item.MaterialCode + '' + item.MaterialName + '' + ((item.HSNCODE) ?item.HSNCODE : '') + '' + item.UOM + '' + item.Quantity + ' - + + payroll_id)) { echo "contenteditable='true';"; } ?> payroll_id)) { ?> title="Payslip Calculated" style="text-align:right;color:blue;" @@ -640,7 +640,7 @@ - + \ No newline at end of file diff --git a/app/Views/editconfig.php b/app/Views/editconfig.php index 8b789f2b..66e35bfb 100755 --- a/app/Views/editconfig.php +++ b/app/Views/editconfig.php @@ -35,7 +35,7 @@ if (!empty($master)) {

Edit Config Details

- Back
@@ -68,7 +68,7 @@ if (!empty($master)) {
'form-horizontal', 'id' => 'editConfig'); - echo form_open(base_url() . 'configurationctrl/updateconfig', $attributes); ?> + echo form_open(base_url() . "configurationctrl/updateconfig?page=$page", $attributes); ?>
@@ -241,7 +241,9 @@ if (!empty($master)) { @@ -607,13 +609,17 @@ if (!empty($master)) { data-materialCode="${item.MaterialCode}" data-materialType="${item.MaterialType}" data-uom="${item.UOM}" - style="cursor: pointer; color: #4d3a6d;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;"> + style="cursor: pointer; color: #4d3a6d;overflow: hidden;text-overflow: ellipsis;white-space: nowrap; width:10%; + text-align:center;"> ${item.MaterialCode}
${item.MaterialName}${item.MaterialType}${item.IsActive == 1 ?"Active":"InActive"}${item.MaterialType}${item.IsActive == 1 ?"Active":"InActive"}
${item.IGRNO} ${item.fullCylinderDate} ${item.cylinderNo}${item.grossWeight}${item.grossWeight} ${item.emptyCylinderDate}${item.tareWeight}${item.netWeight}${item.actualWeight}${item.shortage}${item.tareWeight}${item.netWeight}${item.actualWeight}${item.shortage} ${item.invoiceNo} ${item.DeliveryChellanDate} ${item.DriverName} Weight${totalNetWeight}${totalActualWeight}${totalShortage} Weight${totalNetWeight}${totalActualWeight}${totalShortage}
-

( Note :The entries count includes archived data... )

+ diff --git a/app/Views/sales_dashboard.php b/app/Views/sales_dashboard.php index b23e12fe..150e8ad7 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: 40000000 // Maximum value for y-axis } }, plugins: { diff --git a/app/Views/stock/CoatingMachineDetail.php b/app/Views/stock/CoatingMachineDetail.php index e7e2bb68..e81d289c 100644 --- a/app/Views/stock/CoatingMachineDetail.php +++ b/app/Views/stock/CoatingMachineDetail.php @@ -1296,7 +1296,7 @@ @@ -1459,7 +1458,6 @@ let machineRunningInHrs = calculateMachineRunInHrs(machineOnDate, machineOnTimeHr, machineOffTimeHr); if (!machineRunningInHrs) { - $('#machineOffTimeHrId').val(''); return } @@ -1467,12 +1465,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 +1503,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 +1522,6 @@ }) - }) - - - - - @@ -1712,48 +1770,59 @@ + @@ -1141,60 +1239,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 f0d294ae..c48483f5 100644 --- a/app/Views/stock/dieselStockDetails.php +++ b/app/Views/stock/dieselStockDetails.php @@ -319,6 +319,19 @@ foreach ($period as $day) {
+
+
@@ -368,7 +381,7 @@ foreach ($period as $day) { + id="dieselMachineStockDetailsExport"> 0, 'running_hours' => 0, 'mileage' => 0, + 'machineId' => $machineId, ]; } @@ -782,21 +796,39 @@ foreach ($period as $day) {
+ Total +
Gas Per Ton Qty Per Hrs (Metric Ton) Moisture Loss Qty (Metric Ton)Dust Qty (Metric Ton)Dust Qty (Kgs) Customer Name - + - +
Total
">
Total 000
+ Total +
@@ -826,9 +897,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 +908,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 +967,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 +987,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 +1008,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 +1028,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 +1052,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 +1072,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 +1097,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 +1135,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; + } + } + + + + + + + \ No newline at end of file diff --git a/app/Views/stock/incomingSilicaSandDetails.php b/app/Views/stock/incomingSilicaSandDetails.php index 7ea940ab..ed986cc7 100644 --- a/app/Views/stock/incomingSilicaSandDetails.php +++ b/app/Views/stock/incomingSilicaSandDetails.php @@ -720,7 +720,7 @@ " - 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 " + data-provide="datepicker" + data-date-format="M-yyyy" + data-date-min-view-mode="1" readonly + style="max-width: 175px;"> - - - - - - - - - - - - - - +
+
+ + + + + + + + + + + + + + + + + + + + +
+ +
+
-
-
- -
+ - - + @@ -1701,21 +1701,21 @@ if (!empty($getlogpodtl)) { @@ -2262,7 +2262,7 @@ if (!empty($getlogpodtl)) { 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 ea3bdd4a..afde5728 100644 --- a/app/Views/accountsDashboard.php +++ b/app/Views/accountsDashboard.php @@ -436,7 +436,7 @@ Tax (%) Taxable Amt Total Amt - Remarks + Remarks * @@ -812,8 +812,8 @@ '' + ((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) + ''; ' ' + ' ' + '' + @@ -852,8 +852,8 @@ '' + ((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) + ''; ' ' + ' ' + '' + @@ -887,8 +887,8 @@ '' + 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/assetListing.php b/app/Views/assetListing.php index 58770a69..fe17cfe4 100755 --- a/app/Views/assetListing.php +++ b/app/Views/assetListing.php @@ -54,7 +54,7 @@ - Add New + Add New Asset @@ -171,6 +171,7 @@ diff --git a/app/Views/attendance.php b/app/Views/attendance.php index f476585e..d26ae34d 100755 --- a/app/Views/attendance.php +++ b/app/Views/attendance.php @@ -268,7 +268,7 @@ $currentday = date('d'); - + 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 7837df3c..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 () { diff --git a/app/Views/editCapitalAmendPO.php b/app/Views/editCapitalAmendPO.php index 92e28978..a353d3cf 100755 --- a/app/Views/editCapitalAmendPO.php +++ b/app/Views/editCapitalAmendPO.php @@ -1759,9 +1759,9 @@ if (!empty($POItem) && $CapitalRange == '1') {
@@ -2446,8 +2446,8 @@ if (!empty($POItem) && $CapitalRange == '1') { diff --git a/app/Views/editCapitalPo.php b/app/Views/editCapitalPo.php index df550de9..cb24438d 100755 --- a/app/Views/editCapitalPo.php +++ b/app/Views/editCapitalPo.php @@ -926,7 +926,7 @@ $(document).ready(function () { @@ -1271,7 +1271,7 @@ $(document).ready(function () { data-userid="" data-toggle="modal" href="#EDITCAPITAL">    + data-userid="" id="Del"> @@ -1610,7 +1610,7 @@ $(document).ready(function () {      - + @@ -1660,17 +1660,17 @@ $(document).ready(function () { @@ -3098,7 +3098,7 @@ $(document).ready(function () { 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 4e38583b..8259b06e 100755 --- a/app/Views/editImportAmendPO.php +++ b/app/Views/editImportAmendPO.php @@ -1258,7 +1258,7 @@ if (!empty($RequistionDetails)) { @@ -1610,7 +1610,7 @@ if (!empty($RequistionDetails)) { Previous Upload -      - +
@@ -1665,9 +1665,9 @@ if (!empty($RequistionDetails)) { diff --git a/app/Views/editOld.php b/app/Views/editOld.php index d005134a..a9252156 100755 --- a/app/Views/editOld.php +++ b/app/Views/editOld.php @@ -92,8 +92,8 @@ if (!empty($EmpList)) {
- - + +
@@ -133,7 +133,7 @@ if (!empty($EmpList)) { -
+
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 e142d4b3..48b5e391 100755 --- a/app/Views/editRawmaterial.php +++ b/app/Views/editRawmaterial.php @@ -364,7 +364,7 @@ if ($total <= $reorder) { - +
diff --git a/app/Views/editRevenueAmendPO.php b/app/Views/editRevenueAmendPO.php index 91c73689..d230eafd 100755 --- a/app/Views/editRevenueAmendPO.php +++ b/app/Views/editRevenueAmendPO.php @@ -1681,7 +1681,7 @@ if (!empty($INRSYMBOL)) { Previous Upload -      - +
@@ -1735,9 +1735,9 @@ if (!empty($INRSYMBOL)) {
@@ -2165,7 +2165,7 @@ if (!empty($INRSYMBOL)) {
diff --git a/app/Views/editRevenuepurchaseorder.php b/app/Views/editRevenuepurchaseorder.php index 8888791f..aedc3008 100755 --- a/app/Views/editRevenuepurchaseorder.php +++ b/app/Views/editRevenuepurchaseorder.php @@ -2359,7 +2359,7 @@ if (!empty($getlogpodtl)) { + class="btn btn-success auditor-restricted-btn" id="abcd">Select Line Item @@ -2575,7 +2575,7 @@ if (!empty($getlogpodtl)) { data-userid="" data-toggle="modal" href="#EDITREVENUE"> - @@ -2947,7 +2947,7 @@ if (!empty($getlogpodtl)) { Previous Upload -      - + @@ -3002,21 +3002,21 @@ if (!empty($getlogpodtl)) {
-   Reset -   Save as Draft -   Submit -   Approve +   Reset +   Save as Draft +   Submit +   Approve -   Reset -   Submit -   Approve +   Reset +   Submit +   Approve   OK -   Submit +   Submit -   Reset -   Submit -   Approve +   Reset +   Submit +   Approve   OK @@ -3381,7 +3381,7 @@ if (!empty($getlogpodtl)) { @@ -3749,7 +3749,7 @@ if (!empty($getlogpodtl)) { @@ -4579,7 +4579,7 @@ if (!empty($getlogpodtl)) { - + diff --git a/app/Views/editServiceAmendPO.php b/app/Views/editServiceAmendPO.php index 2c7c4e5e..b3f41f9a 100755 --- a/app/Views/editServiceAmendPO.php +++ b/app/Views/editServiceAmendPO.php @@ -1404,7 +1404,7 @@ foreach ($PaymentTerms as $TER) { Previous Upload -      - +
@@ -1451,9 +1451,9 @@ foreach ($PaymentTerms as $TER) { @@ -1783,7 +1783,7 @@ foreach ($PaymentTerms as $TER) { diff --git a/app/Views/editSupplier.php b/app/Views/editSupplier.php index 1b8366f8..5e90c047 100755 --- a/app/Views/editSupplier.php +++ b/app/Views/editSupplier.php @@ -498,7 +498,7 @@ if (!empty($supplier)) { - + diff --git a/app/Views/editconfig.php b/app/Views/editconfig.php index 27bf6f70..1013c078 100755 --- a/app/Views/editconfig.php +++ b/app/Views/editconfig.php @@ -99,7 +99,7 @@ if (!empty($master)) { @@ -211,6 +211,7 @@ if (!empty($master)) {       configlisting?page=" class="btn btn-secondary" > Cancel - + @@ -361,7 +362,7 @@ if (!empty($master)) { data-dismiss="modal">Cancel diff --git a/app/Views/editimportpo.php b/app/Views/editimportpo.php index 4f881dbe..a2e23b74 100755 --- a/app/Views/editimportpo.php +++ b/app/Views/editimportpo.php @@ -836,7 +836,7 @@ if (!empty($getlogpodtl)) { @@ -1037,7 +1037,7 @@ if (!empty($getlogpodtl)) { if ($PONOStatus == PO_DRAFT || $PONOStatus == PO_CREATED || $PONOStatus == REQITEM_Emergency_PO_CREATED || $PONOStatus == PO_APPROVED) { ?>     - + @@ -1336,7 +1336,7 @@ if (!empty($getlogpodtl)) { Previous Upload -      - +
@@ -1389,17 +1389,17 @@ if (!empty($getlogpodtl)) { diff --git a/app/Views/editrequisitionform.php b/app/Views/editrequisitionform.php index 627eb3f9..64dcc3d3 100755 --- a/app/Views/editrequisitionform.php +++ b/app/Views/editrequisitionform.php @@ -208,7 +208,7 @@ td { @@ -251,7 +251,7 @@ td { StatusName; ?> -     +     CategoryName; ?> @@ -296,14 +296,14 @@ td {
-    -    -    -    +    +    +    +    -    -    -    +    +    +   
@@ -487,7 +487,7 @@ td { + class="btn btn-info waves-effect waves-light auditor-restricted-btn EditClick">Edit diff --git a/app/Views/employeeLeaveApplicationForm.php b/app/Views/employeeLeaveApplicationForm.php index 65974ac5..b7bcc8d6 100755 --- a/app/Views/employeeLeaveApplicationForm.php +++ b/app/Views/employeeLeaveApplicationForm.php @@ -82,7 +82,7 @@ From Date To Date Number Of Days - Status + Status Action @@ -105,7 +105,7 @@ - + -
+
@@ -241,6 +242,7 @@
+
@@ -256,8 +258,10 @@
@@ -349,10 +353,10 @@ alert('Please Enter the Reason'); return; } - if ($('#status_val').val() === '') { - alert('Please Select Status'); - return; - } + // if ($('#status_val').val() === '') { + // alert('Please Select Status'); + // return; + // } // validateDateRange(function(isValid) { // if (!isValid) { // alert("The selected date range overlaps with an existing approved leave."); @@ -366,7 +370,7 @@ end_date:$('#end_date').val(), no_of_days:$('#no_of_days').val(), reason:$('#reason').val(), - status:$('#status_val').val(), + status:$('#status_val').val() ? $('#status_val').val() : 'Draft', }; $('#loader').show(); diff --git a/app/Views/employeeListing.php b/app/Views/employeeListing.php index 9dcc2b9c..bdf32fc3 100755 --- a/app/Views/employeeListing.php +++ b/app/Views/employeeListing.php @@ -101,7 +101,7 @@ 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 @@ + + - From 505f66696b93e2c3a9753c86574c0b9ba1998654 Mon Sep 17 00:00:00 2001 From: VE10-Sanjeev Date: Sat, 19 Apr 2025 13:32:35 +0000 Subject: [PATCH 24/28] tracker issues --- app/Config/Routes.php | 1 + app/Controllers/User.php | 40 +++++++----- app/Models/User_model.php | 16 +++++ app/Views/addUser.php | 93 +++++++++++++++------------- app/Views/editOld.php | 28 +++++++++ app/Views/monthlypayinputs.php | 17 ++++- app/Views/userListing.php | 7 +-- app/Views/viewinwardgateregister.php | 7 ++- 8 files changed, 144 insertions(+), 65 deletions(-) diff --git a/app/Config/Routes.php b/app/Config/Routes.php index c92e8115..2ec88ef2 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->get('isEmailExists', 'User::isEmailExists'); // Supplier Routes $routes->match(["GET","POST"],'supplierlisting', 'Supplier::index'); // list supplier 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/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/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/monthlypayinputs.php b/app/Views/monthlypayinputs.php index 4d2e8eef..73838c06 100755 --- a/app/Views/monthlypayinputs.php +++ b/app/Views/monthlypayinputs.php @@ -589,7 +589,6 @@ - @@ -819,6 +818,22 @@ $(document).ready(function () { let ws = XLSX.utils.table_to_sheet(table); // Convert modified table to sheet let wb = XLSX.utils.book_new(); // Create a new workbook + var range = XLSX.utils.decode_range(ws['!ref']); + + // Auto-size columns + let colWidths = []; + for (let R = range.s.r; R <= range.e.r; ++R) { + for (let C = range.s.c; C <= range.e.c; ++C) { + let cell_ref = XLSX.utils.encode_cell({ c: C, r: R }); + let cell = ws[cell_ref]; + if (cell) { + let val = cell.v ? cell.v.toString() : ''; + colWidths[C] = Math.max(colWidths[C] || 10, val.length); + } + } + } + + ws['!cols'] = colWidths.map(w => ({ wch: w + 2 })); XLSX.utils.book_append_sheet(wb, ws, 'Sheet1'); // Append sheet to workbook XLSX.writeFile(wb, filename || 'export.xlsx'); // Save the file } diff --git a/app/Views/userListing.php b/app/Views/userListing.php index 40309e9d..4dcfb81f 100755 --- a/app/Views/userListing.php +++ b/app/Views/userListing.php @@ -160,15 +160,14 @@ - +    - diff --git a/app/Views/viewinwardgateregister.php b/app/Views/viewinwardgateregister.php index edea47f4..2387b09e 100755 --- a/app/Views/viewinwardgateregister.php +++ b/app/Views/viewinwardgateregister.php @@ -1724,15 +1724,16 @@ // let fieldName = str.replace(/([a-z])([A-Z])/g, '$1 $2'); let sentence = " "; if (parseInt(record.is_add) === 1) { - // sentence += record.IGR_No + " was Created by "+record.FullName+ " on "+record.indian_date+" at "+record.indian_time; + sentence += record.IGR_No + " was Created by "+record.FullName+ " on "+record.indian_date+" at "+record.indian_time+"

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