diff --git a/app/Config/Routes.php b/app/Config/Routes.php index 80aac532..949b564f 100755 --- a/app/Config/Routes.php +++ b/app/Config/Routes.php @@ -438,11 +438,11 @@ $routes->get('getInvoiceAttachment', 'Sales::getInvoiceAttachments'); $routes->get('getInvoiceAttachments', 'Sales::getInvoiceAttachments'); $routes->get('deleteAttachment', 'Sales::deleteAttachment'); $routes->post('saveAttachment', 'Sales::saveAttachment'); -$routes->get('sales_invoice', 'Sales::sales_invoice'); -$routes->post('sales_invoice', 'Sales::sales_invoice'); $routes->post('download_sales_invoice', 'Sales::download_sales_invoice'); $routes->post('updateInvRecQty', 'Sales::updateInvRecQty'); +$routes->match(['GET', 'POST'],'sales_invoice', 'Sales::sales_invoice'); $routes->match(['GET', 'POST'], 'sales_report', 'Sales::sales_report'); +$routes->match(['GET', 'POST'],'credit_notes', 'Sales::credit_notes'); // transporter Routes $routes->match(['GET', 'POST'],'transporterListing', 'Supplier::transporterListing'); diff --git a/app/Controllers/Sales.php b/app/Controllers/Sales.php index a58fb3ee..e81ce7f9 100755 --- a/app/Controllers/Sales.php +++ b/app/Controllers/Sales.php @@ -6,6 +6,7 @@ use App\Controllers\BaseController; use App\Models\Ipinvoice_model; use App\Models\Ipattachment_model; +use App\Models\CreditNoteModel; require_once 'vendor/autoload.php'; use PhpOffice\PhpSpreadsheet\Spreadsheet; @@ -15,6 +16,7 @@ class Sales extends BaseController { protected $ipinvoice_model; protected $ipattachment_model; + protected $CreditNoteModel; protected $session; public function __construct() @@ -22,6 +24,7 @@ class Sales extends BaseController parent::__construct(); $this->ipinvoice_model = new Ipinvoice_model(); $this->ipattachment_model = new Ipattachment_model(); + $this->CreditNoteModel = new CreditNoteModel(); $this->session = session(); $this->isLoggedIn(); } @@ -119,6 +122,33 @@ class Sales extends BaseController } + // credit_notes List + function credit_notes(){ + $fromDate=''; + $toDate=''; + + if ($this->request->getMethod() === 'GET') + { + $toDate = date('Y-m-d'); + $fromDate = date('Y-m-d', strtotime('-90 days', strtotime($toDate))); + } elseif ($this->request->getMethod() === 'POST') { + $fromDate = $this->request->getPost('fromDate'); + $toDate = $this->request->getPost('toDate'); + $fromDate = date('Y-m-d', strtotime($fromDate)); + $toDate = date('Y-m-d', strtotime($toDate)); + } + + $this->global['pageTitle'] = 'Credit Notes'; + $data['credit_notes'] = $this->CreditNoteModel->getAllCreditNotes($fromDate , $toDate); + // dd($data); + $data['fromDate'] = date('d-m-Y', strtotime($fromDate)); + $data['toDate'] = date('d-m-Y', strtotime($toDate)); + + + $this->loadViews("credit_notes", $this->global, $data, NULL); + } + + public function sales_report() { $headline = ''; diff --git a/app/Controllers/StockController.php b/app/Controllers/StockController.php index 354eca66..dbc2587b 100644 --- a/app/Controllers/StockController.php +++ b/app/Controllers/StockController.php @@ -146,25 +146,38 @@ class StockController extends BaseController //incoming Silica Sand Details starts public function loadView_incomingSilicaSandDetails() { + + //one remark is for comments and another remark here is alais status of the sand report , due to client request naming is given wrong , + //hope you bear it..!! + //we did ..!! + + //getting month in post if ($this->request->getMethod() === 'POST') { + //getting remark value which is used to specify the issd entry is accepted/rejected/conditionally accepted.. $remark = $this->request->getPost('remark'); - + $month = $this->request->getPost('month'); + //formatting the date format of Jan-2025 to 2025-01 $date = DateTime::createFromFormat('M-Y', $month); $formattedDate = $date->format('Y-m'); + $month = $formattedDate; + //setting session for any month change $session = session (); $session->set('stock_month',$month); } else { + + //if request is in get method getting remark in query params in new_header.php file(navbar) + $remark = $this->request->getVar('remark'); $session = session(); @@ -172,21 +185,25 @@ class StockController extends BaseController $month = $session->get('stock_month'); if (empty($month)) { - $month = date('Y-m'); // Default to the current month + //if no monthis set in session setting Default to the current month + $month = date('Y-m'); } } $data['month'] = $month; + //set page title $this->global['pageTitle'] = 'Incoming Silica Sand Details'; $materialCodes = []; + //getting all silica sand raw materials material code $silicaSandMaterialCodes = $this->rawmaterialdetails_model->getAllSilicaRawMaterialCode(); $materialCodes [] = $silicaSandMaterialCodes; + //getting all waste Core Sand Material Codes $wasteCoreSandMaterialCodes = $this->rawmaterialdetails_model->getAllWasteCoreSandMaterialCode(); $materialCodes [] = $wasteCoreSandMaterialCodes; @@ -195,6 +212,7 @@ class StockController extends BaseController if (!empty($materialCodes)) { + //remark filter may apply or not $data['igrDetails'] = $this->inwardGateRegister_model->findIgrDetailsForIncomingSilicaSand($materialCodes, $month, $remark); } else { $data['igrDetails'] = []; @@ -202,11 +220,11 @@ class StockController extends BaseController $data['testedBy'] = []; - $DesignationConfigID = 'C010'; + //['lab assistant', 'factory manager', 'lab head'] + $data['testedBy'] = $this->employeedetails_model->incomingSilicaSandTestedBy(); - $data['testedBy'] = $this->employeedetails_model->incomingSilicaSandTestedBy($DesignationConfigID); - - $data['approvedBy'] = $this->employeedetails_model->incomingSilicaSandApprovedBy($DesignationConfigID); + //['factory manager', 'lab head'] + $data['approvedBy'] = $this->employeedetails_model->incomingSilicaSandApprovedBy(); $date = DateTime::createFromFormat('Y-m', $month); @@ -220,6 +238,7 @@ class StockController extends BaseController return $this->loadViews("stock/incomingSilicaSandDetails", $this->global, $data, NULL); } + public function updateIncomingSilicaSandDetails() { @@ -290,6 +309,8 @@ class StockController extends BaseController echo "Data Saved Successfully"; } + + //This is particulary updated by the lab technichians public function updateLabReport() { @@ -353,115 +374,143 @@ class StockController extends BaseController //Drier machine details public function drierMachineDetails() { - - - //drier will be processing different method than other stock in case of session stock month and date format for generating - //dummy data and updating the data . be cautious while updating the code..!! - + // Drier machine details follow a different method of processing stock month and date format than other stock records. + // The stock month and date format must be handled carefully while generating and updating data. + + if ($this->request->getMethod() === 'POST') { - + + // Retrieve the month value from the POST request (expected in "M-Y" format, e.g., "Jan-2025") $currentMonth = $this->request->getPost('month'); - - $date = DateTime::createFromFormat('M-Y', $currentMonth); //in M-Y format - - $formattedDate = $date->format('Y-m'); //in Y-m format - - - $session = session (); - - $session->set('stock_month',$formattedDate); - - - } else { - + + // Convert the month format from "M-Y" (Jan-2025) to "Y-m" (2025-01) for database processing + $date = DateTime::createFromFormat('M-Y', $currentMonth); + $formattedDate = $date->format('Y-m'); + + + $session = session(); + + $session->set('stock_month', $formattedDate); + + } else { + $session = session(); - $currentMonth = $session->get('stock_month'); - + + // If no month is set in the session, default to the current month in "M-Y" format if (empty($currentMonth)) { - $currentMonth = date('M-Y'); // Default to the current month - }else{ - $currentMonth = DateTime::createFromFormat('Y-m', $currentMonth); // in Y-m format - - $currentMonth = $currentMonth->format('M-Y'); // in M-Y format + $currentMonth = date('M-Y'); + } else { + // Convert the stored "Y-m" format (e.g., 2025-01) back to "M-Y" (e.g., Jan-2025) for display + $currentMonth = DateTime::createFromFormat('Y-m', $currentMonth); + $currentMonth = $currentMonth->format('M-Y'); } } - + + // Retrieve the list of dates for the selected month in database-compatible format $monthData = $this->getMonthDatesFromInput($currentMonth); - - $isActiveFilter = 1 ; - $data['startDate'] = $monthData[0]['database']; - $data['endDate'] = $monthData[count($monthData) - 1]['database']; + + + // Set the active filter for suppliers (1 means active suppliers will be fetched) + $isActiveFilter = 1; + + + $data['startDate'] = $monthData[0]['database']; // First day of the selected month + $data['endDate'] = $monthData[count($monthData) - 1]['database']; // Last day of the selected month + + // Generate available time slots for drier machine processing $data['timeDropdown'] = $this->generateTimeOptions(); + + $data['supplierData'] = $this->supplier_model->supplierlisting($isActiveFilter); - + + // Retrieve drier machine details for the selected date range $data['drierDetails'] = $this->drierMachineDetails_model - ->where('date >=', $data['startDate']) - ->where('date <=', $data['endDate']) - ->orderBy('date','asc') - ->findAll(); - - + ->where('date >=', $data['startDate']) + ->where('date <=', $data['endDate']) + ->orderBy('date', 'asc') + ->findAll(); + + $data['datefordropdown'] = $currentMonth; - + + // Set the page title for display $this->global['pageTitle'] = 'Drier Details'; + $this->loadViews("stock/drierMachineDetails", $this->global, $data, NULL); - - } + public function addOrEditdrierMachineDetails() { - + // Retrieve form data from the POST request + $data = $this->request->getPost(); - $data = $this->request->getPost(); - - $drierData[] = $this->mapDrierEntry($data); - + // Map the received data into a structured format using the helper function `mapDrierEntry` + $drierData[] = $this->mapDrierEntry($data); + // Begin a database transaction to ensure atomicity $this->db->transBegin(); + try { + // Arrays to store data for batch insert and batch update operations $inserts = []; $updates = []; + foreach ($drierData as $row) { + // Retrieve the ID of the existing entry (if present) $existingRow = $row['id']; - $data = $row; - + $data = $row; - if (($existingRow)) { + if ($existingRow) { + $existingRow = $this->drierMachineDetails_model->where('id', $row['id'] ?? '')->first(); - + + // Handle gas stock updates for the existing record $this->handleGasStockUpdate($existingRow, $row); + + $updates[] = $data; } else { + // If it's a new record, update gas stock consumption before inserting $this->updateGasStockConsumption($data['date'], $data['total_gas_consumption']); + + $inserts[] = $data; } } + if (!empty($inserts)) { $this->drierMachineDetails_model->insertBatch($inserts); } + if (!empty($updates)) { $this->drierMachineDetails_model->updateBatch($updates, 'id'); } + // Check if the transaction encountered any database errors if ($this->db->transStatus() === false) { throw new \Exception('Transaction failed due to database error.'); } + $this->db->transCommit(); - - return redirect()->to("/drierMachineDetails")->with('success', "Data Saved Successfully"); - - } catch (\Exception $error) { - $this->db->transRollback(); - return redirect()->back()->with('error', ' ' . $error->getMessage()); - } + + + return redirect()->to("/drierMachineDetails")->with('success', "Data Saved Successfully"); + + } catch (\Exception $error) { + // Rollback the transaction in case of an error + $this->db->transRollback(); + + return redirect()->back()->with('error', ' ' . $error->getMessage()); + } } + /** * Maps input row to expected format. */ @@ -491,160 +540,145 @@ class StockController extends BaseController //Coating Machine Details starts public function loadView_coatingMachineDetails() { - if ($this->request->getMethod() === 'POST') { - + // Get the month from the request $month = $this->request->getPost('month'); - + + // Convert month format from "M-Y" to "Y-m" $date = DateTime::createFromFormat('M-Y', $month); - $formattedDate = $date->format('Y-m'); - $month = $formattedDate; - - $session = session (); - - $session->set('stock_month',$month); - - } else { - + + // Store selected month in session + $session = session(); + $session->set('stock_month', $month); + + } else { $session = session(); - $month = $session->get('stock_month'); - + + // Default to the current month if no month is stored in session if (empty($month)) { - $month = date('Y-m'); // Default to the current month + $month = date('Y-m'); } - } - - $data['month'] = $month ; - - $this->global['pageTitle'] = 'Coating Machine Details '; - - + + $data['month'] = $month; + $this->global['pageTitle'] = 'Coating Machine Details'; + + // Define start and end date for the selected month $startDate = "$month-01"; $endDate = date("Y-m-t", strtotime($startDate)); + + // Fetch coating machine details with batch card file details $data['coatingMachineDetails'] = $this->coatingMachineDetails_model - ->select('t_coatingmachinedetails.*, - JSON_ARRAYAGG( - JSON_OBJECT( - "client_given_name", t_batchcard_files.client_file_name, - "filename", t_batchcard_files.filename, - "batchCardId" , t_batchcard_files.id, - "coating_id", t_batchcard_files.coating_id - ) - ) as batchcard_files') - ->join('t_batchcard_files', 't_batchcard_files.coating_id = t_coatingmachinedetails.id', 'left') - ->where('t_coatingmachinedetails.date >=', $startDate) - ->where('t_coatingmachinedetails.date <=', $endDate) - ->groupBy('t_coatingmachinedetails.id') - ->orderBy('t_coatingmachinedetails.date', 'asc') - ->findAll(); - - + ->select('t_coatingmachinedetails.*, + JSON_ARRAYAGG( + JSON_OBJECT( + "client_given_name", t_batchcard_files.client_file_name, + "filename", t_batchcard_files.filename, + "batchCardId" , t_batchcard_files.id, + "coating_id", t_batchcard_files.coating_id + ) + ) as batchcard_files') + ->join('t_batchcard_files', 't_batchcard_files.coating_id = t_coatingmachinedetails.id', 'left') + ->where('t_coatingmachinedetails.date >=', $startDate) + ->where('t_coatingmachinedetails.date <=', $endDate) + ->groupBy('t_coatingmachinedetails.id') + ->orderBy('t_coatingmachinedetails.date', 'asc') + ->findAll(); + + // Convert month format from "Y-m" to "M-Y" for display $date = DateTime::createFromFormat('Y-m', $month); - $formattedDate = $date->format('M-Y'); - $data['month'] = $formattedDate; - + + // Load the view with the required data return $this->loadViews("stock/CoatingMachineDetail", $this->global, $data, NULL); } + public function addNewCoatingMachineDetails() { $message1 = ''; $message2 = ''; $message3 = ''; - + $postData = $this->request->getPost(); - $date = $postData['date']; $shift = $postData['shift']; - + // Check if the same shift already exists on the same date $sameShiftOnDateExists = $this->coatingMachineDetails_model ->where('date', $date) ->where('shift', $shift) ->where('is_active', 1) ->first(); - + if (!empty($sameShiftOnDateExists)) { return redirect()->back()->with('error', 'Already same shift exists on the same date ..!!'); } - + // Start transaction $this->db->transBegin(); - + try { - // Insert into coating machine details table + // Insert data into coating machine details table $insertedId = $this->coatingMachineDetails_model->insert($postData); - + if ($insertedId !== false && $insertedId > 0) { - $message1 = 'Coating Machine details updated successfully'; - + // Update gas stock consumption $dateToBeInserted = $postData['date']; $consumption = $postData['totalGasConsumption']; $updatedResult = $this->updateGasStockConsumption($dateToBeInserted, $consumption); - + if ($updatedResult === false || $updatedResult <= 0) { - // Explicit failure handling for gas stock update throw new \Exception('Failed to update gas stock consumption.'); } + $message2 = 'And updated gas stock consumption.'; $message3 = " Warning..!! Kindly Update the next subsequent month Gas Stock If older month Gas Stock Updated..!!"; } else { throw new \Exception('Failed to insert Coating machine details.'); } - + + // Handle batch card file uploads if ($insertedId !== false && $insertedId > 0) { - $batchCardFiles = $this->request->getFileMultiple('batchCard'); - + if (!empty($batchCardFiles) && !($batchCardFiles[0]->getError() === UPLOAD_ERR_NO_FILE)) { - - foreach ($batchCardFiles as $file) { - if ($file->isValid() && !$file->hasMoved()) { - $clientGivenName = $file->getClientName(); // User-given filename + $clientGivenName = $file->getClientName(); // Original filename $newName = $file->getRandomName(); - + if ($file->move(WRITEPATH . 'uploads/batchcard', $newName)) { - // Only save to DB if file moved successfully + // Insert file details into the database $db = \Config\Database::connect(); $builder = $db->table('t_batchcard_files'); - + $data = [ 'client_file_name' => $clientGivenName, 'filename' => $newName, 'coating_id' => $insertedId ]; - - $result = $builder->insert($data); - + + $builder->insert($data); } } } } - - } - - - + if ($this->db->transStatus() === false) { throw new \Exception('Transaction failed due to database errors.'); } - + $this->db->transCommit(); - - - - // Set flashdata for success message + + // Redirect with success message return redirect()->to("/coatingMachineDetails") ->with('success', $message1 . " " . $message2 . " " . $message3); } catch (\Exception $error) { @@ -652,6 +686,7 @@ class StockController extends BaseController return redirect()->back()->with('error', ' ' . $error->getMessage()); } } + @@ -679,32 +714,36 @@ class StockController extends BaseController $batchCardFiles = $this->request->getFileMultiple('batchCard'); - - // Step 4: Upload new files and insert into DB - foreach ($batchCardFiles as $index => $file) { + if (is_array($batchCardFiles) && !empty($batchCardFiles)) { + // Step 4: Upload new files and insert into DB + foreach ($batchCardFiles as $index => $file) { - if ( !empty($batchCardFiles[$index]) && !($batchCardFiles[$index]->getError() === UPLOAD_ERR_NO_FILE)) { - - $db = \Config\Database::connect(); - $builder = $db->table('t_batchcard_files'); - - if ($file->isValid() && !$file->hasMoved()) { - $clientGivenName = $file->getClientName(); // User-given filename - $newName = $file->getRandomName(); // Randomized unique filename - - // Move the new file to storage - if ($file->move(WRITEPATH . 'uploads/batchcard', $newName)) { - // Insert new file record into the database - $data = [ - 'client_file_name' => $clientGivenName, - 'filename' => $newName, - 'coating_id' => $id - ]; - $builder->insert($data); + if ( !empty($batchCardFiles[$index]) && !($batchCardFiles[$index]->getError() === UPLOAD_ERR_NO_FILE)) { + + $db = \Config\Database::connect(); + $builder = $db->table('t_batchcard_files'); + + if ($file->isValid() && !$file->hasMoved()) { + $clientGivenName = $file->getClientName(); // User-given filename + $newName = $file->getRandomName(); // Randomized unique filename + + // Move the new file to storage + if ($file->move(WRITEPATH . 'uploads/batchcard', $newName)) { + // Insert new file record into the database + $data = [ + 'client_file_name' => $clientGivenName, + 'filename' => $newName, + 'coating_id' => $id + ]; + $builder->insert($data); + } } } } } + + + } if ($updated !== false && $updated > 0) { @@ -1020,14 +1059,13 @@ class StockController extends BaseController private function updateGasStockConsumption($date, $consumption) { - + // Check if an entry exists for the given date $resultExists = $this->gasStockDetails_model ->where('date', $date) ->first(); - + if ($resultExists) { - - + // Ensure the date is in the correct format if ($date instanceof DateTime) { $date = $date->format('Y-m-d'); } elseif (!strtotime($date)) { @@ -1035,39 +1073,40 @@ class StockController extends BaseController } else { $date = date('Y-m-d', strtotime($date)); } - + + // Get the last date of the month for the given date $endDate = date('Y-m-t', strtotime($date)); - - - //what happens if the updation is on the last day of the month? + + // Fetch all stock entries from the given date till the end of the month $resultExists = $this->gasStockDetails_model ->where('date >=', $date) ->where('date <=', $endDate) ->orderBy('date', 'asc') ->findAll(); - + $updatedOpeningStock = 0; $updates = []; - - + + // Update stock values for each day in the month foreach ($resultExists as $index => $result) { - if ($index == 0) { + // Update the first entry with new consumption $result['consumption'] = (float)($result['consumption']) + (float)($consumption); $result['total'] = (float)$result['opening'] + (float)$result['purchaseBharath'] + (float)$result['purchaseIndian']; $result['balanceStock'] = $result['total'] - $result['consumption']; $updatedOpeningStock = (int)$result['balanceStock']; } else { + // Update subsequent entries based on previous balance $result['opening'] = (float)$updatedOpeningStock; $result['total'] = (float)$result['opening'] + (float)$result['purchaseBharath'] + (float)$result['purchaseIndian']; $result['balanceStock'] = (float)$result['total'] - (float)$result['consumption']; $updatedOpeningStock = (int)$result['balanceStock']; } - - + $updates[] = $result; } - + + // Perform batch update if there are changes if (!empty($updates)) { $result = $this->gasStockDetails_model->updateBatch($updates, 'id'); return ($result !== false && $result > 0) ? $result : 0; @@ -1075,69 +1114,67 @@ class StockController extends BaseController return 0; } } else { - - - + // Get the last date of the previous month $previousMonthDate = new DateTime($date); $previousMonthDate = $previousMonthDate->modify('first day of this month') ->modify('-1 day') ->format('Y-m-d'); - - - + + // Check if the previous month's last day entry exists $previousMonthResultExists = $this->gasStockDetails_model ->where('date', $previousMonthDate) ->first(); - - - + $opening = 0; - + + // Set opening stock based on previous month's balance stock if (!empty($previousMonthResultExists) && isset($previousMonthResultExists['balanceStock'])) { $opening = $previousMonthResultExists['balanceStock']; } - - - + + // Generate a list of all dates in the current month $startDate = DateTime::createFromFormat('Y-m-d', $date)->modify('first day of this month')->format('Y-m-d'); $endDate = DateTime::createFromFormat('Y-m-d', $date)->modify('last day of this month')->format('Y-m-d'); - + $datesInMonth = []; $inserts = []; - + $period = new DatePeriod( new DateTime($startDate), new DateInterval('P1D'), (new DateTime($endDate))->modify('+1 day') ); - + foreach ($period as $day) { $datesInMonth[] = $day->format('Y-m-d'); } - - foreach ($datesInMonth as $datesInMonthIndex => $dateInMonth) { - - //update previousMonthResultExists + + // Insert stock records for each day in the month + foreach ($datesInMonth as $dateInMonth) { $balanceStock = $opening; $consumptionForDate = 0; + if ($dateInMonth == $date) { + // Assign the given consumption for the provided date $consumptionForDate = $consumption; $balanceStock = $opening - $consumption; } - + $inserts[] = [ 'date' => $dateInMonth, 'opening' => $opening, - 'purchaseBharath' => Null, - 'purchaseIndian' => Null, - 'total' => Null, + 'purchaseBharath' => null, + 'purchaseIndian' => null, + 'total' => null, 'consumption' => $consumptionForDate, 'balanceStock' => $balanceStock ]; - + + // Update opening for the next day $opening = $balanceStock; } - + + // Perform batch insert if data is available if (!empty($inserts)) { $result = $this->gasStockDetails_model->insertBatch($inserts); return ($result !== false && $result > 0) ? $result : 0; @@ -1146,6 +1183,7 @@ class StockController extends BaseController } } } + @@ -1293,13 +1331,6 @@ class StockController extends BaseController - - - - - - - // Get the previous month's last date diesel stock details for next month updation $previousMonth = DateTime::createFromFormat('Y-m', $month)->modify('-1 month')->format('Y-m'); @@ -1378,46 +1409,7 @@ class StockController extends BaseController // Reset the structure to have indexed arrays without the date keys $data['groupedDieselMachineStockDetails'] = array_values($groupedByDate); - - - - //temp_code_s_2025_02 - - // getting diesel machines for creating table headers - // checking already existing stock if yes then get the diesel machines id from the existing stock - // if not get all the diesel machines from the factory Machine master table - - // if (!empty($data['groupedDieselMachineStockDetails'])) { - - // $result = $groupedByDate[$date]; - - // $distinctMachineId = []; - - // foreach ($result as $index => $eachResult) { - // $distinctMachineId[] = $result[$index]['machine_id']; - // } - - // $dieselMachines = $this->factoryMachine_model - // ->whereIn('id', $distinctMachineId) - // ->orderBy('id', 'asc') - // ->get() - // ->getResultArray(); - - - // } else { - - // $dieselMachines = $this->factoryMachine_model - // ->where('is_active', 1) - // ->where('energy_type', 'Diesel') - // ->orderBy('id', 'asc') - // ->get() - // ->getResultArray(); - - // } - - //temp_code_e_2025_02 - - + @@ -1781,35 +1773,6 @@ class StockController extends BaseController $data['groupedPowerConsumptionStockDetails'] = array_values($groupedByDate); - //temp_code_s_2025_02 - - // getting electric machines for creating table headers - // checking already existing stock if yes then get the electric machines id from the existing stock - // if not get all the electric machines from the factory Machine master table - - // if (!empty($data['groupedPowerConsumptionStockDetails'])) { - - // $result = $groupedByDate[$date]; - - // $distinctMachineId = []; - - // foreach ($result as $index => $eachResult) { - // $distinctMachineId[] = $result[$index]['machine_id']; - // } - - // $electricMachines = $this->factoryMachine_model->getSelectedElectricMachines($distinctMachineId); - - - // } else { - - // $electricMachines = $this->factoryMachine_model->getAllActiveElectricMachines(); - - // } - - //temp_code_e_2025_02 - - - $electricMachinesCount = count($electricMachines); $data['electricMachinesCount'] = $electricMachinesCount; @@ -2241,34 +2204,7 @@ class StockController extends BaseController // Reset the structure to have indexed arrays without the date keys $data['groupedResinStockDetails'] = array_values($groupedByDate); - - //temp_code_s_2025_02 - - // getting resin material for creating table headers - // checking already existing stock if yes then get the material code from the existing stock - // if not get all the material codes currently isActive from the raw material details table - - // if (!empty($data['groupedResinStockDetails'])) { - - // $result = $groupedByDate[$date]; - - // $distinctMaterialCodes = []; - - // foreach ($result as $index => $eachResult) { - // $distinctMaterialCodes[] = $result[$index]['materialCode']; - // } - - // $resinMaterials = $this->rawmaterialdetails_model->getSelectedResinMaterialCode($distinctMaterialCodes); - - // } else { - - // $resinMaterials = $this->rawmaterialdetails_model->getAllResinMaterialCode(); - - // } - - //temp_code_e_2025_02 - - + // getting customer for creating table headers // checking already existing stock if yes then get customer from the existing stock // if not set customer in db , then set '' empty string @@ -2617,32 +2553,7 @@ class StockController extends BaseController // Reset the structure to have indexed arrays without the date keys $data['groupedBagStockDetails'] = array_values($groupedByDate); - - - - //temp_code_s_2025_02 - - // // getting bag material for creating table headers - // // checking already existing stock if yes then get the material code from the existing bag - // // if not get all the material codes from the raw material details table - - // if (!empty($data['groupedBagStockDetails'])) { - // $result = $groupedByDate[$date]; - - // $distinctMaterialCodes = []; - - // foreach ($result as $index => $eachResult) { - // $distinctMaterialCodes[] = $result[$index]['materialCode']; - // } - - // $bagMaterials = $this->rawmaterialdetails_model->getSelectedBagMaterialCode($distinctMaterialCodes); - - // } else { - // $bagMaterials = $this->rawmaterialdetails_model->getAllBagMaterialCode(); - // } - - //temp_code_e_2025_02 - + // getting customer for creating table headers // checking already existing stock if yes then get customer from the existing stock @@ -3272,12 +3183,12 @@ class StockController extends BaseController */ private function handleGasStockUpdate($existingRow, $newRow) { - $existingConsumption = $existingRow['total_gas_consumption']; - $updatedConsumption = $newRow['total_gas_consumption']; + $existingConsumption = $existingRow['total_gas_consumption']; //eg:400 + $updatedConsumption = $newRow['total_gas_consumption']; //eg:500 if ($existingConsumption != $updatedConsumption) { - $changeInConsumption = $updatedConsumption - $existingConsumption; - $this->updateGasStockConsumption($existingRow['date'], $changeInConsumption); + $changeInConsumption = $updatedConsumption - $existingConsumption; // 500-400 = 100 + $this->updateGasStockConsumption($existingRow['date'], $changeInConsumption); // +100 will be the change } } diff --git a/app/Controllers/User.php b/app/Controllers/User.php index 1f962afc..59ab3187 100755 --- a/app/Controllers/User.php +++ b/app/Controllers/User.php @@ -14,6 +14,7 @@ use App\Models\User_model; use App\Models\Ipinvoice_model; use App\Models\Ipattachment_model; use App\Models\Zohobooks_api_model; +use App\Models\CreditNoteModel; require_once 'vendor/autoload.php'; @@ -34,6 +35,7 @@ class User extends BaseController protected $user_model; protected $ipinvoice_model; protected $ipattachment_model; + protected $CreditNoteModel; protected $session; /** @@ -50,6 +52,7 @@ class User extends BaseController $this->user_model = new User_model(); $this->ipinvoice_model = new Ipinvoice_model(); $this->ipattachment_model = new Ipattachment_model(); + $this->CreditNoteModel = new CreditNoteModel(); $this->session = session(); helper('form'); //$this->load->library('form_validation'); $this->isLoggedIn(); @@ -1337,17 +1340,13 @@ class User extends BaseController } } + + function zohobooks_api_fetch_all() { - // print_r($_GET); - // echo isset($_GET['from']) ? $_GET['from'] : 'n'; - // echo isset($_GET['to']) ? $_GET['to'] : 'n'; - // die(); + try { - // if (isset($_POST['sync']) || $_GET['from'] != null && $_GET['to'] != null) - // { - // $ch=curl_init(); - //$this->load->helper('zohobooks_fetch_api_helper'); + helper('zohobook'); $Zohobook_model = model('Zohobook_api_model'); if (isset($_GET['from']) && $_GET['from'] != null && isset($_GET['to']) && $_GET['to'] != null) { @@ -1357,15 +1356,13 @@ class User extends BaseController $date_today = date('Y-m-d'); $date_yesterday = date('Y-m-d', strtotime('-3 day', strtotime($date_today))); } - // echo $date_today.'--'.$date_yesterday;die; + $chk_acc_token_val = $Zohobook_model->get_data('zohobook_accesstoken', 'id', 1); - // print_r($chk_acc_token_val);//die(); + $date = new \DateTime($chk_acc_token_val[0]['created_at']); - //print_r($date); + $date->add(new \DateInterval('PT1H')); - //print_r($date); - //echo '****************'; - //print_r(date('Y-m-d h:i:s')); + $token = 0; if ($date->format('Y-m-d H:i:s') > date('Y-m-d H:i:s')) { $token = $chk_acc_token_val[0]['token']; @@ -1377,17 +1374,23 @@ class User extends BaseController // $token = generateNewToken(); $tokendata['token'] = $token; //$Zohobook_model->update($tokendata , 1,'zohobook_accesstoken'); $result = getheringInvoiceDetails($date_today, $date_yesterday, $token); + $headers_new = $result['headers_new']; $res = json_decode($result['data'], true); $inv_array = $res['invoices']; - // $cteditNotes = getAllCreditNotes($date_today, $date_yesterday, $token); - // dd($cteditNotes); - // dd($inv_array); - // print_r($inv_array); - // echo "rrrr"; - // die(); + $tokenWithCreditNoteScope = generateNewTokenForCreditNoteScope(); + $cteditNotesRes = getAllCreditNotes($date_today, $date_yesterday, $tokenWithCreditNoteScope); + $cteditNotesData = json_decode($cteditNotesRes['data'],true); + + if(count($cteditNotesData['creditnotes'])) + { + $this->saveOrUpdateCreditNote($cteditNotesData['creditnotes']); + } + + + foreach ($inv_array as $inv) { $invoice_id = $inv['invoice_id']; //filter only einvoice status pushed invoices only @@ -1711,6 +1714,27 @@ class User extends BaseController } // END zoho API + public function saveOrUpdateCreditNote($data) + { + + foreach ($data as $key => $value) { + + $existingCreditNote = $this->CreditNoteModel->where('creditnote_id', $value['creditnote_id'])->first(); + + if ($existingCreditNote) { + // Update existing record + $this->CreditNoteModel->update($value['creditnote_id'], $value); + + } else { + // Insert new record + $this->CreditNoteModel->insert($value); + + } + } + + } + + function fetchEmployeeDetails() { $EmpID = $this->request->getPost('EmpID'); diff --git a/app/Helpers/zohobook_helper.php b/app/Helpers/zohobook_helper.php index 4d957e05..c92a8c99 100755 --- a/app/Helpers/zohobook_helper.php +++ b/app/Helpers/zohobook_helper.php @@ -110,69 +110,58 @@ if (! function_exists('test_helper')) { } } + +if (! function_exists('generateNewTokenForCreditNoteScope')) { + function generateNewTokenForCreditNoteScope() + { + // Initialize cURL + $ch = curl_init(); + + // Zoho API credentials + $organization_id = '776847408'; + $client_id = '1000.0WMDLCXAZV5DR60IKE9P49YTYGVL6C'; + $refresh_token = '1000.461f55fee6248d21aafe4c10b05c37dc.9fc8b11993aba1ca95e539740f3d411f'; + $client_secret = '99da3a05cfa13cf91eb6476a3c44cfa3e21b6106a8'; + $redirect_uri = 'https://resicoindustries.com/RIA'; + + + // Construct URL to get the authentication token + $url_getauthtoken = 'https://accounts.zoho.com/oauth/v2/token?refresh_token='.$refresh_token.'&client_id='.$client_id.'&client_secret='.$client_secret.'&redirect_uri='.$redirect_uri.'&grant_type=refresh_token'; + + // Set cURL options + curl_setopt($ch, CURLOPT_URL, $url_getauthtoken); + curl_setopt($ch, CURLOPT_HEADER, 0); + curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + + // Execute cURL request + $res_token = curl_exec($ch); + + // Decode the response + $ress = json_decode($res_token); + + // Return access token + return $ress->access_token; + } +} + if (! function_exists('getAllCreditNotes')) { - // function getAllCreditNotes($date_today, $date_yesterday, $accesstoken) - // { - // // Initialize cURL - // $ch = curl_init(); - - // // Zoho API credentials - // $organization_id = '776847408'; - // // $url_org = "https://books.zoho.com/api/v3/creditnotes?"; - // $url_org = "https://www.zohoapis.com/books/v3/creditnotes?"; - - // // Construct query parameters - // $fields = array( - // "usestate" => "true", - // "organization_id" => $organization_id, - // "date_start" => $date_yesterday, - // "date_end" => $date_today - // ); - // $data_all = http_build_query($fields); - - // // Set headers - // $headers = array( - // 'Authorization: Zoho-oauthtoken '.$accesstoken, - // 'Content-Type: application/json' - // ); - - // // Construct URL - // $data_access = $url_org.$data_all; - - // // Set cURL options - // curl_setopt($ch, CURLOPT_URL, $data_access); - // curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); - - // curl_setopt($ch, CURLOPT_HEADER, 0); - // curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); - // curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); - - // // Execute cURL request - // $result = curl_exec($ch); - - // // Store headers and data - // $data['headers_new'] = $headers; - // $data['data'] = curl_exec($ch); - // // Return data - // return $data; - // } - function getAllCreditNotes($date_today, $date_yesterday, $accesstoken) { // Initialize cURL $ch = curl_init(); - var_dump($accesstoken); + // Zoho API credentials $organization_id = '776847408'; - $url_org = "https://books.zoho.com/api/v3/creditnotes?"; + $url_org = "https://www.zohoapis.com/books/v3/creditnotes?"; // Construct query parameters manually (Zoho might need raw values) - $query_string = "usestate=true&organization_id=$organization_id&date_start=$date_yesterday&date_end=$date_today"; + $query_string = "organization_id=$organization_id&date_start=$date_yesterday&date_end=$date_today"; // Set headers $headers = array( 'Authorization: Zoho-oauthtoken ' . $accesstoken, - 'Content-Type: application/json' + // 'Content-Type: application/json' ); // Set cURL options diff --git a/app/Models/CreditNoteModel.php b/app/Models/CreditNoteModel.php new file mode 100644 index 00000000..5bcd0406 --- /dev/null +++ b/app/Models/CreditNoteModel.php @@ -0,0 +1,89 @@ +where('date >=', $fromDate ) + ->where('date <=', $toDate ) + ->orderBy('date', 'DESC') + ->findAll(); + } + + /** + * Fetch a single credit note by ID + */ + public function getCreditNoteById($id) + { + return $this->where('creditnote_id', $id)->first(); + } + + /** + * Insert a new credit note + */ + public function createCreditNote($data) + { + return $this->insert($data); + } + + /** + * Update an existing credit note + */ + public function updateCreditNote($id, $data) + { + return $this->update($id, $data); + } + + /** + * Delete a credit note by ID + */ + public function deleteCreditNote($id) + { + return $this->delete($id); + } +} diff --git a/app/Models/DrierMachineDetailsModel.php b/app/Models/DrierMachineDetailsModel.php index 9139d5c8..920af9e6 100644 --- a/app/Models/DrierMachineDetailsModel.php +++ b/app/Models/DrierMachineDetailsModel.php @@ -6,7 +6,7 @@ use CodeIgniter\Model; class DrierMachineDetailsModel extends Model { - protected $table = 't_drierMachineDetails'; + protected $table = 't_driermachinedetails'; protected $primaryKey = 'id'; protected $useAutoIncrement = true; protected $returnType = 'array'; diff --git a/app/Models/Employeedetails_model.php b/app/Models/Employeedetails_model.php index a69ac2fa..46dac337 100755 --- a/app/Models/Employeedetails_model.php +++ b/app/Models/Employeedetails_model.php @@ -52,7 +52,7 @@ class Employeedetails_model extends Model return $query->getResult(); } - function incomingSilicaSandTestedBy($ConfigID){ + function incomingSilicaSandTestedBy(){ $builder = $this->db->table('t_employee_details Emp') @@ -67,7 +67,7 @@ class Employeedetails_model extends Model } - function incomingSilicaSandApprovedBy($ConfigID){ + function incomingSilicaSandApprovedBy(){ $builder = $this->db->table('t_employee_details Emp') ->select(' Emp.*') diff --git a/app/Models/FactoryMachineModel.php b/app/Models/FactoryMachineModel.php index 6c363b76..3e77c081 100644 --- a/app/Models/FactoryMachineModel.php +++ b/app/Models/FactoryMachineModel.php @@ -92,7 +92,7 @@ class FactoryMachineModel extends Model $result = $this->db->table('t_factorymachinemaster') ->where('is_active', 1) ->where('energy_type', 'diesel') - ->orderBy('id', 'desc') + ->orderBy('id', 'asc') ->get() ->getResultArray(); diff --git a/app/Models/IncomingSilicaSandDetailsModel.php b/app/Models/IncomingSilicaSandDetailsModel.php index 6061fc5f..6d088985 100644 --- a/app/Models/IncomingSilicaSandDetailsModel.php +++ b/app/Models/IncomingSilicaSandDetailsModel.php @@ -6,7 +6,7 @@ use CodeIgniter\Model; class IncomingSilicaSandDetailsModel extends Model { - protected $table = 't_incomingSilicaSandDetails'; + protected $table = 't_incomingsilicasanddetails'; protected $primaryKey = 'id'; protected $useAutoIncrement = true; protected $returnType = 'array'; diff --git a/app/Models/Inwardgateregister_model.php b/app/Models/Inwardgateregister_model.php index e93e7286..ee8cc2cc 100755 --- a/app/Models/Inwardgateregister_model.php +++ b/app/Models/Inwardgateregister_model.php @@ -1216,7 +1216,7 @@ class Inwardgateregister_model extends Model $builder->groupBy('t_igr_details.IGRNO, t_igr_details.MaterialCode') ->join('t_igr_master igrMast', 'igrMast.IGRNO = t_igr_details.IGRNO') - ->join('t_incomingSilicaSandDetails issd','issd.igrNo_fk = t_igr_details.IGRNO AND issd.materialCode = t_igr_details.MaterialCode','left') + ->join('t_incomingsilicasanddetails issd','issd.igrNo_fk = t_igr_details.IGRNO AND issd.materialCode = t_igr_details.MaterialCode','left') ->join('t_materialmaster materialMaster', 'materialMaster.MaterialCode = t_igr_details.MaterialCode') ->join('t_configdetails cd','cd.key = materialMaster.Category','left') ->join('t_purchaseorder_master poMaster', 'poMaster.PONO = igrMast.PONO', 'left') diff --git a/app/Models/Rawmaterialdetails_model.php b/app/Models/Rawmaterialdetails_model.php index 5c589be8..0cb2b2f8 100755 --- a/app/Models/Rawmaterialdetails_model.php +++ b/app/Models/Rawmaterialdetails_model.php @@ -147,6 +147,10 @@ class Rawmaterialdetails_model extends Model $builder = $this->db->table('t_materialmaster') ->select('MaterialCode') + + /** Caution changing config key is posing risk to entire stock module * */ + // 248 is the config detail key for silica sand + ->where('Category', '248') ->orderBy('CreatedDate', 'desc'); $query = $builder->get(); @@ -159,6 +163,10 @@ class Rawmaterialdetails_model extends Model $builder = $this->db->table('t_materialmaster') ->select('MaterialCode') + + /** Caution changing config key is posing risk to entire stock module * */ + // 328 is the config detail key for silica sand + ->where('Category', '328') ->orderBy('CreatedDate', 'desc'); $query = $builder->get(); diff --git a/app/Models/TrpProductionModel.php b/app/Models/TrpProductionModel.php index 55277d90..de14aba0 100644 --- a/app/Models/TrpProductionModel.php +++ b/app/Models/TrpProductionModel.php @@ -146,7 +146,7 @@ class TrpProductionModel extends Model $builder->join('t_trp_sand_use tsu', 'tsu.date = tpmd.date', 'left'); // Subquery: Coating Machine Gas Consumption - $subquery1 = $this->db->table('t_coatingMachineDetails') + $subquery1 = $this->db->table('t_coatingmachinedetails') ->select('date, SUM(totalGasConsumption) AS totalGasConsumption') ->groupBy('date') ->getCompiledSelect(false); // Convert Query Builder to raw SQL; @@ -154,7 +154,7 @@ class TrpProductionModel extends Model $builder->join("({$subquery1}) tcmd", 'tcmd.date = tpmd.date', 'left'); // Subquery: Drier Machine Gas Consumption - $subquery2 = $this->db->table('t_drierMachineDetails') + $subquery2 = $this->db->table('t_driermachinedetails') ->select('date, SUM(total_gas_consumption) AS totalGasConsumption') ->groupBy('date') ->getCompiledSelect(false); // Convert Query Builder to raw SQL; diff --git a/app/Views/credit_notes.php b/app/Views/credit_notes.php new file mode 100644 index 00000000..d6fab6ce --- /dev/null +++ b/app/Views/credit_notes.php @@ -0,0 +1,355 @@ + + + + + +
+
+ +
+ +
+
+
+
+
+ +
+ +
+
+
+
+
+
+ + +
+ +
+
+ + + + + + + + + + + + +
+ + +
+
+
+ +
+ +
+ + + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
DateCredit NoteInvoiceClient Item PriceItem qtySub TotalGSTTotalStatus
+
+
+
+
+
+
+
+
+ + + + + + + \ No newline at end of file diff --git a/app/Views/includes/new_header.php b/app/Views/includes/new_header.php index 0601e659..10910a6d 100755 --- a/app/Views/includes/new_header.php +++ b/app/Views/includes/new_header.php @@ -654,6 +654,7 @@