diff --git a/app/Config/Routes.php b/app/Config/Routes.php index f2a1a56..feb9842 100755 --- a/app/Config/Routes.php +++ b/app/Config/Routes.php @@ -151,25 +151,28 @@ $routes->group('api', ['filter' => 'appSignature'], function ($routes) { $routes->get("dashboard/productivityDashboard", "DashboardController::productivityDashboard"); //DASHBOARD Season 1 EXPORT EXCEL (ManagerDashboard - staffLevelPendingSummaryData) - $routes->get("dashboard/downloadStaffPendingSummaryExcel", "ExcelExportController::downloadStaffPendingSummaryExcel"); - $routes->get("dashboard/downloadStaffPendingSummaryExcelByID", "ExcelExportController::downloadStaffPendingSummaryExcelByID"); + $routes->get("dashboard/downloadExcelStaffPendingSummary", "ExcelExportController::downloadExcelStaffPendingSummary"); + $routes->get("dashboard/downloadExcelStaffPendingSummaryByID", "ExcelExportController::downloadExcelStaffPendingSummaryByID"); //DASHBOARD Season 2 EXPORT EXCEL (businessDashboard) - $routes->get("dashboard/downloadBrokerPoliciesExcel", "ExcelExportController::downloadBrokerPoliciesExcel"); - $routes->get("dashboard/downloadInsurerPoliciesExcel", "ExcelExportController::downloadInsurerPoliciesExcel"); - $routes->get("dashboard/downloadProductPoliciesExcel", "ExcelExportController::downloadProductPoliciesExcel"); + $routes->get("dashboard/downloadExcelBroker", "ExcelExportController::downloadBrokerPoliciesExcel"); + $routes->get("dashboard/downloadExcelInsurer", "ExcelExportController::downloadInsurerPoliciesExcel"); + $routes->get("dashboard/downloadExcelProduct", "ExcelExportController::downloadProductPoliciesExcel"); //DASHBOARD Season 3 EXPORT EXCEL (partnerDashboard) - $routes->get("dashboard/downloadT50AgentPoliciesExcel", "ExcelExportController::downloadT50AgentPoliciesExcel"); // whole agent but top 50 - $routes->get("dashboard/downloadAgentMonthlyPoliciesExcel", "ExcelExportController::downloadAgentMonthlyPoliciesExcel"); // particular Agent - $routes->get("dashboard/downloadLowPremiumAgentExcel", "ExcelExportController::downloadLowPremiumAgentExcel"); - $routes->get("dashboard/downloadAgentsWithoutPoliciesExcel", "ExcelExportController::downloadAgentsWithoutPoliciesExcel"); + $routes->get("dashboard/downloadExcelPerformingAgentsTop50", "ExcelExportController::downloadExcelPerformingAgentsTop50"); // PerformingAgents Top50 + $routes->get("dashboard/downloadExcelPerformingAgentsByID", "ExcelExportController::downloadExcelPerformingAgentsByID"); // PerformingAgents ParticularAgent + $routes->get("dashboard/downloadExcelLowPremium", "ExcelExportController::downloadExcelLowPremium"); // NonPerforming Below50K + $routes->get("dashboard/downloadExcelWithoutPolicies", "ExcelExportController::downloadExcelWithoutPolicies"); //NonPerforming NoBuiness //DASHBOARD Season 4 EXPORT EXCEL AS ZIP (partnerDashboard - 3Excel in Zip Folder) $routes->get("dashboard/downloadExcelAsZIP", "ExcelExportController::downloadExcelAsZIP"); //DASHBOARD Season 5 EXPORT EXCEL (productivityDashboard) - $routes->get("dashboard/downloadStaffAndProductPoliciesExcel", "ExcelExportController::downloadStaffAndProductPoliciesExcel"); + $routes->get("dashboard/downloadExcelStaffAndProduct", "ExcelExportController::downloadExcelStaffAndProduct"); + + //REPORT + $routes->get('reports/endorsement-excel', 'ExcelExportController::downloadExcelEndorsement'); @@ -218,18 +221,4 @@ $routes->get("processjob", "JobWorker::processJob"); $routes->get('checkPolicyDoc', 'PolicyController::readFile'); $routes->get('calculateCommission', 'PolicyController::calculateCommission'); $routes->get('testPolicy', 'QuotationController::testPolicy'); - - - - - - - - - - - - - - - + \ No newline at end of file diff --git a/app/Controllers/DashboardController.php b/app/Controllers/DashboardController.php index ab45a73..dbeabd1 100644 --- a/app/Controllers/DashboardController.php +++ b/app/Controllers/DashboardController.php @@ -493,7 +493,7 @@ class DashboardController extends ResourceController // Initialize the details array to ensure the final output is always structured. $message = "Partner Dashboard Data Retrieved Successfully"; - $details = [ 'monthlyPolicyCount' => [],'noPolicyTimeRange' => [],'below50tPremiumTimeRange' => []]; + $details = [ 'agentsPerformanceList' => [],'nonAgentsPerformanceList' => [],'nonAgentsPerformanceListPremium' => []]; // 'agentNoPolicyLast10Days' => [],// 'agentBelow50tPremiumLast10Days' => [], try { @@ -501,7 +501,7 @@ class DashboardController extends ResourceController $date = $this->request->getGet('date'); $date = $date ?? date('Y-m-d'); - $data1 = $this->agentMonthlyPolicyCountandPremiumAmount($date, $manager_id, false); + $data1 = $this->getDataPerformingAgents($date, $manager_id, false); if (!empty($data1)) { @@ -513,9 +513,9 @@ class DashboardController extends ResourceController }); } - $details['monthlyPolicyCount'] = $data1; - $details['noPolicyTimeRange'] = $this->agentNoPolicyTimeRange($manager_id,$raw); - $data2 = $this->getLowPremiumAgentData($manager_id,$raw); + $details['agentsPerformanceList'] = $data1; + $details['nonAgentsPerformanceList'] = $this->getDataNonAgentsPerformanceList($manager_id,$raw); + $data2 = $this->getDataLowPremiumAgent($manager_id,$raw); if (!empty($data2)) { $lastIndex2 = count(reset($data2)) - 1; @@ -525,14 +525,14 @@ class DashboardController extends ResourceController return (float)$rowD[$lastIndex2] <=> (float)$rowC[$lastIndex2]; }); } - $details['below50tPremiumTimeRange'] = $data2; + $details['nonAgentsPerformanceListPremium'] = $data2; - // $details['monthlyPremiumAmount'] = $this->agentMonthlyPremiumAmount($date,$manager_id,$raw); + // $details['agentsPerformanceListPremium'] = $this->agentMonthlyPremiumAmount($date,$manager_id,$raw); - $ref['monthlyPolicyCountAndPremiumAmount_total_records'] = is_array($details['monthlyPolicyCount']) ? count($details['monthlyPolicyCount']) : 0; - $ref['noPolicyTimeRange_total_records'] = is_array($details['noPolicyTimeRange']) ? count($details['noPolicyTimeRange']) : 0; - $ref['below50tPremiumTimeRange_total_records'] = is_array($details['below50tPremiumTimeRange']) ? count($details['below50tPremiumTimeRange']) : 0; + $ref['agentsPerformanceList_monthlyPolicyCountAndPremiumAmount_totalRecords'] = is_array($details['agentsPerformanceList']) ? count($details['agentsPerformanceList']) : 0; + $ref['nonAgentsPerformanceList_noPolicyTimeRange_totalRecords'] = is_array($details['nonAgentsPerformanceList']) ? count($details['nonAgentsPerformanceList']) : 0; + $ref['nonAgentsPerformanceListPremium_below50tPremiumTimeRange_totalRecords'] = is_array($details['nonAgentsPerformanceListPremium']) ? count($details['nonAgentsPerformanceListPremium']) : 0; // 2. Check for overall emptiness (optional, but good practice) @@ -826,7 +826,7 @@ class DashboardController extends ResourceController } //Step 2 - public function agentMonthlyPolicyCountandPremiumAmount($customDate,$manager_id, $raw){ + public function getDataPerformingAgents($customDate,$manager_id, $raw){ $builder = $this->db->table('partner_policy pp'); @@ -890,7 +890,7 @@ class DashboardController extends ResourceController // } //Step 3 no buiness - public function agentNoPolicyTimeRange($managerId, $raw){ + public function getDataNonAgentsPerformanceList($managerId, $raw){ // $builder = $this->db->table('partner_agent pa'); // $builder->select(' @@ -959,8 +959,8 @@ class DashboardController extends ResourceController } //Step 4 - //any changed in this query also change in do the same in ExcelExportController - getLowPremiumAgentData - public function getLowPremiumAgentData($manager_id, $raw){ + //any changed in this query also change in do the same in ExcelExportController - getDataLowPremiumAgent + public function getDataLowPremiumAgent($manager_id, $raw){ $builder = $this->db->table('partner_policy pp'); diff --git a/app/Controllers/EnquiryController.php b/app/Controllers/EnquiryController.php index a770d74..b4ebdd8 100644 --- a/app/Controllers/EnquiryController.php +++ b/app/Controllers/EnquiryController.php @@ -93,6 +93,10 @@ class EnquiryController extends ResourceController $data = $this->enquiryModel->getEnquiry('ALL'); } + // echo (string) $db->getLastQuery(); + // echo $this->db->getLastQuery()->getQuery();die; + + foreach ($data as $key => $row) { if($row['created_on'] !== null) diff --git a/app/Controllers/ExcelExportController.php b/app/Controllers/ExcelExportController.php index f447f1e..4479182 100644 --- a/app/Controllers/ExcelExportController.php +++ b/app/Controllers/ExcelExportController.php @@ -76,6 +76,22 @@ class ExcelExportController extends ResourceController // Format the last column (the sum) as a number $sheet->getStyle($lastCol . $totalRowNumber)->getNumberFormat()->setFormatCode('#,##0.00'); + /** + * ACCOUNTING FORMAT: + * The "_-₹*" part tells Excel to put the ₹ on the left and + * the "*" creates a gap that pushes the numbers to the right. + */ + $accountingFormat = '_-₹* #,##0.00_-;_-₹* -#,##0.00_-;_-₹* "-"??_-;_-@_-'; + + $sheet->getStyle("{$lastCol}3:{$lastCol}{$totalRowNumber}") + ->getNumberFormat() + ->setFormatCode($accountingFormat); + + // 4. Force Right Alignment for the numeric part + $sheet->getStyle("{$lastCol}3:{$lastCol}{$totalRowNumber}") + ->getAlignment() + ->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT); + } @@ -95,7 +111,7 @@ class ExcelExportController extends ResourceController } // 1) Broker generate the Excel file - public function downloadBrokerPoliciesExcel() + public function BrokerWiseExcel() { try{ $managerId = $this->request->getGet('manager_id'); @@ -113,7 +129,7 @@ class ExcelExportController extends ResourceController return $this->response->setJSON(['status' => 'error','code' => 400,'data' => [],'message' => 'Missing required parameters','ref' => $ref])->setStatusCode(200); } - $data = $this->getBrokerPoliciesData($managerId, $brokerId, $month); + $data = $this->getDataBroker($managerId, $brokerId, $month); if (empty($data)) { throw new \RuntimeException('No policies found...', 404); } @@ -126,9 +142,18 @@ class ExcelExportController extends ResourceController }); $finalData = []; $serialNo = 1; + $totalSum = 0; + foreach ($data as $row) { - $finalData[] = array_merge([$serialNo++], $row); + $indexedRow = array_values($row); + $lastIndex = count($indexedRow) - 1; + $totalSum += (float) $indexedRow[$lastIndex]; + unset($indexedRow[$lastIndex]); + $finalData[] = array_merge([$serialNo++], $indexedRow); } + // foreach ($data as $row) { + // $finalData[] = array_merge([$serialNo++], $row); + // } $header = ['S.No', 'Received Date', 'Assigned To', @@ -142,23 +167,30 @@ class ExcelExportController extends ResourceController // Calculate and append total $lastColIndex = count($header) - 1; // Get index of the last column (Premium) - $grandTotal = array_sum(array_column($finalData, $lastColIndex)); + // $grandTotal = array_sum(array_column($finalData, $lastColIndex)); $totalRow = array_fill(0, count($header), ''); // Create empty row of same width $totalRow[$lastColIndex - 1] = 'Total:'; // Put label in 2nd to last - $totalRow[$lastColIndex] = $grandTotal; // Put sum in last + $totalRow[$lastColIndex] = $totalSum; $finalData[] = $totalRow; $monthName = ($month === 'current') ? date('M_Y') : date('M_Y', strtotime('-1 month')); - $brokerName = $finalData[0][11] ?? 'Broker'; - $cleanbrokerName = str_replace(' ', '_', strtolower($brokerName)); - $fileName = $cleanbrokerName . '_Policies_Details_' . $monthName . '.xlsx'; + $brokerName = $finalData[0][11] ?? ''; + + if (empty($brokerName) || $brokerName === 'N/A') { + $fileName = "Broker_Policies_Details_{$monthName}.xlsx"; + } else { + $cleanName = str_replace(' ', '_', strtolower(trim($brokerName))); + $fileName = "{$cleanName}_Policies_Details_{$monthName}.xlsx"; + } + $titleName = str_replace(['_', '.xlsx'], [' ', ''], $fileName); + // --- CALL CENTRALIZED FUNCTION --- $this->streamExcelFile( $header, $finalData, - "Broker Policies Details for {$monthName}", + $titleName, $fileName, true // Pass 'true' to show/bold the total row ); @@ -206,9 +238,8 @@ class ExcelExportController extends ResourceController } } - // 2) Product generate the Excel file - public function downloadProductPoliciesExcel() + public function ProductWiseExcel() { try{ $managerId = $this->request->getGet('manager_id'); @@ -228,7 +259,7 @@ class ExcelExportController extends ResourceController } - $data = $this->getProductPoliciesData($managerId, $vehicleType, $month); + $data = $this->getDataProduct($managerId, $vehicleType, $month); if (empty($data)) { throw new \RuntimeException('No policies found for this vehicle type...', 404); } @@ -241,9 +272,18 @@ class ExcelExportController extends ResourceController }); $finalData = []; $serialNo = 1; + $totalSum = 0; + foreach ($data as $row) { - $finalData[] = array_merge([$serialNo++], $row); + $indexedRow = array_values($row); + $lastIndex = count($indexedRow) - 1; + $totalSum += (float) $indexedRow[$lastIndex]; + unset($indexedRow[$lastIndex]); + $finalData[] = array_merge([$serialNo++], $indexedRow); } + // foreach ($data as $row) { + // $finalData[] = array_merge([$serialNo++], $row); + // } // $header = ['Vehicle Type', 'Issue Date', 'Policy Number', 'Premium Amount']; $header = ['S.No', 'Received Date', 'Assigned To', @@ -257,23 +297,31 @@ class ExcelExportController extends ResourceController // Calculate and append total $lastColIndex = count($header) - 1; // Get index of the last column (Premium) - $grandTotal = array_sum(array_column($finalData, $lastColIndex)); + // $grandTotal = array_sum(array_column($finalData, $lastColIndex)); + $fmt = new \NumberFormatter('en_IN', \NumberFormatter::CURRENCY); + $formattedGrandTotal = $fmt->formatCurrency($totalSum, "INR"); $totalRow = array_fill(0, count($header), ''); // Create empty row of same width $totalRow[$lastColIndex - 1] = 'Total:'; // Put label in 2nd to last - $totalRow[$lastColIndex] = $grandTotal; // Put sum in last + $totalRow[$lastColIndex] = $totalSum; $finalData[] = $totalRow; $monthName = ($month === 'current') ? date('M_Y') : date('M_Y', strtotime('-1 month')); - $vehicleType = $finalData[0][11] ?? 'Vehicle'; - $cleanVehicleType = str_replace(' ', '_', strtolower($vehicleType)); - $fileName = $cleanVehicleType . '_Policies_Details_' . $monthName . '.xlsx'; + $vehicleType = $finalData[0][11] ?? ''; + + if (empty($vehicleType) || $vehicleType === 'N/A') { + $fileName = "Product_Policies_Details_{$monthName}.xlsx"; + } else { + $cleanName = str_replace(' ', '_', strtolower(trim($vehicleType))); + $fileName = "{$cleanName}_Policies_Details_{$monthName}.xlsx"; + } + $titleName = str_replace(['_', '.xlsx'], [' ', ''], $fileName); // --- CALL CENTRALIZED FUNCTION --- $this->streamExcelFile( $header, $finalData, - "Vehicle Type Policies Details for {$monthName}", + $titleName, $fileName, true // This will ignore the bold/alignment logic for the last row ); @@ -318,10 +366,8 @@ class ExcelExportController extends ResourceController } } - - // 3) Insurer generate the Excel file - public function downloadInsurerPoliciesExcel() + public function InsurerWiseExcel() { try{ $managerId = $this->request->getGet('manager_id'); @@ -345,11 +391,11 @@ class ExcelExportController extends ResourceController ])->setStatusCode(200); } - $data = $this->getInsurerPoliciesData($managerId, $insurerId, $month); + $data = $this->getDataInsurer($managerId, $insurerId, $month); // --- 1. MODIFIED LOGIC: Throw RuntimeException if no data --- if (empty($data)) { - throw new \RuntimeException('No policies found for this insurer for the specified month.', 404); + throw new \RuntimeException('No policies Details found for this insurer.', 404); } $lastIndex = count(reset($data)) - 1; // usort($data, function($a, $b) use ($lastIndex) { @@ -360,9 +406,18 @@ class ExcelExportController extends ResourceController }); $finalData = []; $serialNo = 1; + $totalSum = 0; + foreach ($data as $row) { - $finalData[] = array_merge([$serialNo++], $row); + $indexedRow = array_values($row); + $lastIndex = count($indexedRow) - 1; + $totalSum += (float) $indexedRow[$lastIndex]; + unset($indexedRow[$lastIndex]); + $finalData[] = array_merge([$serialNo++], $indexedRow); } + // foreach ($data as $row) { + // $finalData[] = array_merge([$serialNo++], $row); + // } // Define column headers @@ -376,23 +431,31 @@ class ExcelExportController extends ResourceController // Calculate and append total $lastColIndex = count($header) - 1; // Get index of the last column (Premium) - $grandTotal = array_sum(array_column($finalData, $lastColIndex)); + // $grandTotal = array_sum(array_column($finalData, $lastColIndex)); + $fmt = new \NumberFormatter('en_IN', \NumberFormatter::CURRENCY); + $formattedGrandTotal = $fmt->formatCurrency($totalSum, "INR"); $totalRow = array_fill(0, count($header), ''); // Create empty row of same width $totalRow[$lastColIndex - 1] = 'Total:'; // Put label in 2nd to last - $totalRow[$lastColIndex] = $grandTotal; // Put sum in last + $totalRow[$lastColIndex] = $totalSum; $finalData[] = $totalRow; $monthName = ($month === 'current') ? date('M_Y') : date('M_Y', strtotime('-1 month')); - $InsurerName = $finalData[0][8] ?? 'Insurer' ; - $cleanInsurerName = str_replace(' ', '_', strtolower($InsurerName)); - $fileName = $cleanInsurerName . '_Policies_Details_' . $monthName . '.xlsx'; + $InsurerName = $finalData[0][8] ?? "" ; + + if (empty($InsurerName) || $InsurerName === 'N/A') { + $fileName = "Insurer_Policies_Details_{$monthName}.xlsx"; + } else { + $cleanName = str_replace(' ', '_', strtolower(trim($InsurerName))); + $fileName = "{$cleanName}_Policies_Details_{$monthName}.xlsx"; + } + $titleName = str_replace(['_', '.xlsx'], [' ', ''], $fileName); // --- CALL CENTRALIZED FUNCTION --- $this->streamExcelFile( $header, $finalData, - "Insurer Policies Details for {$monthName}", + $titleName, $fileName, true // This will ignore the bold/alignment logic for the last row ); @@ -438,10 +501,9 @@ class ExcelExportController extends ResourceController ], 200); } } - // 4) LowPremium generate the Excel file (Below 5OK) - public function downloadLowPremiumAgentExcel() + public function downloadExcelLowPremium() { try{ $managerId = $this->request->getGet('manager_id'); @@ -454,46 +516,58 @@ class ExcelExportController extends ResourceController return $this->response->setJSON(['status' => 'error','code' => 400,'data' => [],'message' => 'Missing required parameters','ref' => $ref])->setStatusCode(200); } - $data = $this->getLowPremiumAgentData($managerId); + $data = $this->getDataLowPremiumAgent($managerId); if (empty($data)) { throw new \RuntimeException('No low premium agents found...', 404); } $finalData = []; $serialNo = 1; - + $totalSum = 0; + foreach ($data as $row) { - $finalData[] = array_merge([$serialNo++], $row); + // 1. Convert associative row to indexed array + $indexedRow = array_values($row); + + // 2. Add to total sum using the last index (total_premium_amount) + $lastIndex = count($indexedRow) - 1; + $totalSum += (float) $indexedRow[$lastIndex]; + + // 3. Remove columns you don't want in the Excel + unset($indexedRow[$lastIndex]); // Remove total_premium_amount (raw number) + unset($indexedRow[4]); // Remove last_business_date + unset($indexedRow[0]); // Remove agent_id + + // 4. Re-index the array so it's clean (0, 1, 2...) + $cleanedRow = array_values($indexedRow); + + // 5. Merge with Serial Number + $finalData[] = array_merge([$serialNo++], $cleanedRow); } - $header = ['S.No', - 'Received Date', 'Assigned To', - 'Insurer Name' ,'Insurer Short Name', - 'Insured Name', 'Vehicle Number', - 'Payment Mode', 'Plan Type', - 'Partner Name', 'Partner Code','Partner Status' ,'Policy Number','Issued Date', 'Premium Amount']; + $header = ['S.No', 'Partner Code','Partner Name','Partner Status' , 'Premium Amount']; // Calculate and append total $lastColIndex = count($header) - 1; // Get index of the last column (Premium) - $grandTotal = array_sum(array_column($finalData, $lastColIndex)); - + $totalRow = array_fill(0, count($header), ''); // Create empty row of same width $totalRow[$lastColIndex - 1] = 'Total:'; // Put label in 2nd to last - $totalRow[$lastColIndex] = $grandTotal; // Put sum in last + $totalRow[$lastColIndex] = $totalSum; $finalData[] = $totalRow; // Note: $month variable is undefined, assuming you want current month for filename $monthName = date('M_Y'); - $PartnerName = $finalData[0][9] ?? 'Partner'; - $fileName = 'Partners_Low_Premium_Policy_Details.xlsx'; + $PartnerName = $finalData[0][2] ?? ''; + $fileName = 'Non_Performing_Partner_Business_Less_than_50000_Policy_Details.xlsx'; + $titleName = str_replace(['_', '.xlsx'], [' ', ''], $fileName); // --- CALL CENTRALIZED FUNCTION --- $this->streamExcelFile( $header, $finalData, - "Partners Low Premium Policy Details", + $titleName, $fileName, true // This will ignore the bold/alignment logic for the last row ); @@ -540,7 +614,7 @@ class ExcelExportController extends ResourceController } // 5.1) AgentMonthly generate the Excel file - public function downloadAgentMonthlyPoliciesExcel() + public function downloadExcelPerformingAgentsByID() { try{ $managerId = $this->request->getGet('manager_id'); @@ -558,7 +632,7 @@ class ExcelExportController extends ResourceController } // Renamed helper function for consistency: getAgentMonthlyPoliciesData - $data = $this->getMonthlyPoliciesData($managerId, $agentId); // , $month); + $data = $this->getDataPerformingAgentsByID($managerId, $agentId); // , $month); if (empty($data)) { throw new \RuntimeException('No policies found for this agent for the specified month.', 404); @@ -569,14 +643,7 @@ class ExcelExportController extends ResourceController // }); usort($data, function($a, $b) use ($lastIndex) { return (float)$b[$lastIndex] <=> (float)$a[$lastIndex]; - }); - $finalData = []; - $serialNo = 1; - foreach ($data as $row) { - $finalData[] = array_merge([$serialNo++], $row); - } - - + }); $header = ['S.No', 'Received Date', 'Assigned To', @@ -589,31 +656,48 @@ class ExcelExportController extends ResourceController $finalData = []; $serialNo = 1; + $totalSum = 0; foreach ($data as $row) { - $finalData[] = array_merge([$serialNo++], $row); + $indexedRow = array_values($row); + $lastIndex = count($indexedRow) - 1; + $totalSum += (float) $indexedRow[$lastIndex]; + unset($indexedRow[$lastIndex]); + $finalData[] = array_merge([$serialNo++], $indexedRow); } + // foreach ($data as $row) { + // $finalData[] = array_merge([$serialNo++], $row); + // } // Calculate and append total $lastColIndex = count($header) - 1; // Get index of the last column (Premium) - $grandTotal = array_sum(array_column($finalData, $lastColIndex)); + // $grandTotal = array_sum(array_column($finalData, $lastColIndex)); + $fmt = new \NumberFormatter('en_IN', \NumberFormatter::CURRENCY); + $formattedGrandTotal = $fmt->formatCurrency($totalSum, "INR"); $totalRow = array_fill(0, count($header), ''); // Create empty row of same width $totalRow[$lastColIndex - 1] = 'Total:'; // Put label in 2nd to last - $totalRow[$lastColIndex] = $grandTotal; // Put sum in last + $totalRow[$lastColIndex] = $totalSum; $finalData[] = $totalRow; // $monthName = ($month === 'current') ? date('M_Y') : date('M_Y', strtotime('-1 month')); - $monthName = date('M Y') ; - $PartnerName = $finalData[0][11] ?? 'Partner'; - $cleanPartnerName = str_replace(' ', '_', strtolower($PartnerName)); - $fileName = $cleanPartnerName . '_Policies_Details_' . $monthName . '.xlsx'; + + $PartnerName = $finalData[0][11] ?? ''; + + if (empty($PartnerName) || $PartnerName === 'N/A') { + $fileName = 'Performing_Partner_Policy_Details.xlsx'; + } else { + $cleanName = str_replace(' ', '_', strtolower(trim($PartnerName))); + $cleanName = ucwords($cleanName); + $fileName = "Performing_Partner_({$cleanName})_Policy_Details.xlsx"; + } + $titleName = str_replace(['_', '.xlsx'], [' ', ''], $fileName); // --- CALL CENTRALIZED FUNCTION --- $this->streamExcelFile( $header, $finalData, - "Partner Policies Details for {$monthName}", + $titleName, $fileName, true // This will ignore the bold/alignment logic for the last row ); @@ -661,7 +745,7 @@ class ExcelExportController extends ResourceController } // 5.2) Top 50 Agent the Excel file - public function downloadT50AgentPoliciesExcel() + public function downloadExcelPerformingAgentsTop50() { try{ @@ -674,7 +758,7 @@ class ExcelExportController extends ResourceController } // Renamed helper function for consistency: getAgentMonthlyPoliciesData - $data = $this->getMonthlyPolicyCountandPremiumAmount($managerId); + $data = $this->getDataPerformingAgentsTop50($managerId); $header = ['S.No', 'Partner Code', 'Partner Name', 'Policy Count', 'Premium Amount']; if (empty($data)) { @@ -690,29 +774,39 @@ class ExcelExportController extends ResourceController }); $finalData = []; $serialNo = 1; - + $totalSum = 0; + foreach ($data as $row) { - $finalData[] = array_merge([$serialNo++], $row); + $indexedRow = array_values($row); + $lastIndex = count($indexedRow) - 1; + $totalSum += (float) $indexedRow[$lastIndex]; + unset($indexedRow[$lastIndex]); + $finalData[] = array_merge([$serialNo++], $indexedRow); } + // foreach ($data as $row) { + // $finalData[] = array_merge([$serialNo++], $row); + // } // Calculate and append total $lastColIndex = count($header) - 1; // Get index of the last column (Premium) - $grandTotal = array_sum(array_column($finalData, $lastColIndex)); + // $grandTotal = array_sum(array_column($finalData, $lastColIndex)); + $fmt = new \NumberFormatter('en_IN', \NumberFormatter::CURRENCY); + $formattedGrandTotal = $fmt->formatCurrency($totalSum, "INR"); $totalRow = array_fill(0, count($header), ''); // Create empty row of same width $totalRow[$lastColIndex - 1] = 'Total:'; // Put label in 2nd to last - $totalRow[$lastColIndex] = $grandTotal; // Put sum in last - $finalData[] = $totalRow; // Add the total row to the final set + $totalRow[$lastColIndex] = $totalSum; + $finalData[] = $totalRow; - $monthName = date('M Y') ; - $fileName = 'Top_50_Partner_Policies_Details_' . $monthName . '.xlsx'; + $monthName = date('M_Y') ; + $fileName = 'Performing_Partner_Top_50_Policies_Details_Monthly_Report_' . $monthName . '.xlsx'; // --- CALL CENTRALIZED FUNCTION --- $this->streamExcelFile( $header, $finalData, - "Top 50 Partner Policies Details - Monthly Report ".$monthName, + "Performing Partner ( Top 50 ) Policies Details - Monthly Report ".$monthName, $fileName, true // This will ignore the bold/alignment logic for the last row ); @@ -759,7 +853,7 @@ class ExcelExportController extends ResourceController } // 6) Agents who all are Without Policies generate the Excel file (last 10 days no Policies created by the agents) - public function downloadAgentsWithoutPoliciesExcel() + public function downloadExcelWithoutPolicies() { try{ $managerId = $this->request->getGet('manager_id'); @@ -772,7 +866,7 @@ class ExcelExportController extends ResourceController return $this->response->setJSON(['status' => 'error','code' => 400,'data' => [],'message' => 'Missing required parameters','ref' => $ref])->setStatusCode(200); } - $data = $this->getAgentsWithoutPoliciesData($managerId); + $data = $this->getDataAgentsWithoutPolicies($managerId); if (empty($data)) { throw new \RuntimeException('No Partners without policies found.', 404); @@ -799,12 +893,16 @@ class ExcelExportController extends ResourceController // End Date: Today $endDate = date('Ymd'); + $endDateFile = date('d_m_Y'); + $endDateTitle = date('d-m-Y'); // Start Date: 9 days ago (10th day is today) $startDate = date('Ymd', strtotime('-9 days')); + $startDateFile = date('d_m_Y', strtotime('-9 days')); + $startDateTitle = date('d-m-Y', strtotime('-9 days')); // --- Filename Generation --- - $fileName = 'Partners_Without_Policies_' . $startDate . '_to_' . $endDate . '.xlsx'; + $fileName = 'Non_Performing_Partners_No_Business_For_Last_10_Days_' . $startDateFile . '_to_' . $endDateFile . '.xlsx'; // Example output: Agents_Without_Policies_20251206_to_20251215.xlsx @@ -812,7 +910,7 @@ class ExcelExportController extends ResourceController $this->streamExcelFile( $header, $finalData, - "Partners Without Policies (Last 10 Days)", + "Non Performing Partners ( No Business For Last 10 Days " . $startDateTitle . " to " . $endDateTitle." )", $fileName, false // This will ignore the bold/alignment logic for the last row ); @@ -855,7 +953,7 @@ class ExcelExportController extends ResourceController } // 7 Function to generate the Excel file - public function downloadStaffAndProductPoliciesExcel() + public function downloadExcelStaffAndProduct() { try{ $managerId = $this->request->getGet('manager_id'); @@ -876,7 +974,7 @@ class ExcelExportController extends ResourceController } - $data = $this->getStaffAndProductPoliciesExcel($managerId, $executiveId,$vehicleType, $month); + $data = $this->getDataStaffAndProduct($managerId, $executiveId,$vehicleType, $month); if (empty($data)) { throw new \RuntimeException('No policies found for the specified month.', 404); } @@ -889,11 +987,20 @@ class ExcelExportController extends ResourceController }); $finalData = []; $serialNo = 1; + $totalSum = 0; + foreach ($data as $row) { - $finalData[] = array_merge([$serialNo++], $row); + $indexedRow = array_values($row); + $lastIndex = count($indexedRow) - 1; + $totalSum += (float) $indexedRow[$lastIndex]; + unset($indexedRow[$lastIndex]); + $finalData[] = array_merge([$serialNo++], $indexedRow); } - $executiveName = $finalData[0][12] ?? 'Sales Executive'; - $vehicleType = $finalData[0][13] ?? 'Vehicle Type'; + // foreach ($data as $row) { + // $finalData[] = array_merge([$serialNo++], $row); + // } + $executiveName = $finalData[0][11] ?? ''; + $vehicleType = $finalData[0][12] ?? ''; // Define column headers $header = ['S.No', @@ -909,28 +1016,26 @@ class ExcelExportController extends ResourceController // Calculate and append total $lastColIndex = count($header) - 1; // Get index of the last column (Premium) - $grandTotal = array_sum(array_column($finalData, $lastColIndex)); + // $grandTotal = array_sum(array_column($finalData, $lastColIndex)); $totalRow = array_fill(0, count($header), ''); // Create empty row of same width $totalRow[$lastColIndex - 1] = 'Total:'; // Put label in 2nd to last - $totalRow[$lastColIndex] = $grandTotal; // Put sum in last + $totalRow[$lastColIndex] = $totalSum; $finalData[] = $totalRow; $monthName = ($month === 'current') ? date('M_Y') : date('M_Y', strtotime('-1 month')); - - $cleanExecutiveName = str_replace(' ', '_', strtolower($executiveName)); - $cleanVehicleType = str_replace(' ', '_', strtolower($vehicleType)); - $fileName = $cleanExecutiveName . '_' . $cleanVehicleType . '_Policies_Details_' . $monthName . '.xlsx'; - // --- CALL CENTRALIZED FUNCTION --- - $this->streamExcelFile( - $header, - $finalData, - "Staff And Product Policies Details for {$monthName}", - $fileName, - true // This will ignore the bold/alignment logic for the last row - ); + $cleanExec = str_replace(' ', '_', strtolower(trim($executiveName))); + $cleanVeh = str_replace(' ', '_', strtolower(trim($vehicleType))); + + $parts = array_filter([$cleanExec, $cleanVeh]); + $prefix = !empty($parts) ? implode('_', $parts) . '_' : 'Staff_Product_'; + + $fileName = $prefix . "Policies_Details_" . $monthName . ".xlsx"; + $titleName = str_replace(['_', '.xlsx'], [' ', ''], $fileName); + + $this->streamExcelFile($header,$finalData,$titleName,$fileName,true); return; // STOP CI4 rendering anything else @@ -989,9 +1094,9 @@ class ExcelExportController extends ResourceController } // 1. Fetch Data First - $monthlyData = $this->getMonthlyPoliciesData($managerId, null); - $lowPremiumData = $this->getLowPremiumAgentData($managerId); - $inactiveData = $this->getAgentsWithoutPoliciesData($managerId); + $monthlyData = $this->getDataPerformingAgentsByID($managerId, null); + $lowPremiumData = $this->getDataLowPremiumAgent($managerId); + $inactiveData = $this->getDataAgentsWithoutPolicies($managerId); // 2. Add Total Rows where needed (Premium is usually the last index) if (!empty($monthlyData)) { @@ -1089,7 +1194,7 @@ class ExcelExportController extends ResourceController return $excelBinary; } - public function downloadStaffPendingSummaryExcel() + public function downloadExcelStaffPendingSummary() { try{ $managerId = $this->request->getGet('manager_id'); @@ -1102,7 +1207,7 @@ class ExcelExportController extends ResourceController return $this->response->setJSON(['status' => 'error', 'code' => 400, 'data' => [], 'message' => 'Missing required parameters', 'ref' => $ref])->setStatusCode(200); } - $data = $this->getStaffPendingSummaryExcel($managerId); + $data = $this->getDataStaffPendingSummary($managerId); if (empty($data)) { throw new \RuntimeException('No summary found.', 404); @@ -1157,7 +1262,7 @@ class ExcelExportController extends ResourceController $finalData, "Staff Level Pending Summary", $fileName, - true + false ); return; // STOP CI4 rendering anything else @@ -1203,7 +1308,7 @@ class ExcelExportController extends ResourceController } - public function downloadStaffPendingSummaryExcelByID() + public function downloadExcelStaffPendingSummaryByID() { try{ $managerId = $this->request->getGet('manager_id'); @@ -1223,7 +1328,7 @@ class ExcelExportController extends ResourceController } - $data = $this->getStaffPendingSummaryExcelByID($managerId,$staffId,$status); + $data = $this->getDataStaffPendingSummaryByID($managerId,$staffId,$status); if (empty($data)) { throw new \RuntimeException('No summary found.', 404); @@ -1313,6 +1418,115 @@ class ExcelExportController extends ResourceController ], 200); } } + + + public function downloadExcelEndorsement() + { + try{ + $managerId = $this->request->getGet('manager_id'); + + + // --- ADDED VALIDATION (Simplified logic for clarity) --- + if (empty($managerId)) { + $msg = "Missing: manager_id"; + $ref = ['debug_msg' => $msg]; + return $this->response->setJSON(['status' => 'error', 'code' => 400, 'data' => [], 'message' => 'Missing required parameters', 'ref' => $ref])->setStatusCode(200); + } + + $data = $this->getDataEndorsement($managerId); + + + if (empty($data)) { + throw new \RuntimeException('No Endorsement Details found.', 404); + } + + // Define column headers + + + $header = ['S.No', 'Internal/External', + 'Date','Partner', + 'Insurer','Staff', + 'Reg.No','Policy No', + 'Type of Endorsement', + 'Contact Person', + 'Financial/Non-Financial', + 'Pending Days','Remarks', + 'End. Premium' + ]; + + $finalData = []; + $serialNo = 1; + $totalSum = 0; + + foreach ($data as $row) { + $indexedRow = array_values($row); + $lastIndex = count($indexedRow) - 1; + $totalSum += (float) $indexedRow[$lastIndex]; + unset($indexedRow[$lastIndex]); + $finalData[] = array_merge([$serialNo++], $indexedRow); + } + + // Calculate and append total + $lastColIndex = count($header) - 1; // Get index of the last column (Premium) + // $grandTotal = array_sum(array_column($finalData, $lastColIndex)); + + $totalRow = array_fill(0, count($header), ''); // Create empty row of same width + $totalRow[$lastColIndex - 1] = 'Total:'; // Put label in 2nd to last + $totalRow[$lastColIndex] = $totalSum; + $finalData[] = $totalRow; + + $fileName = 'Endorsement_Report_' . date('YmdHis') . '.xlsx'; + + // --- CALL CENTRALIZED FUNCTION --- + $this->streamExcelFile( + $header, + $finalData, + "Endorsement Report", + $fileName, + true + ); + + return; // STOP CI4 rendering anything else + + } catch (\Throwable $e) { + + // ... (Your error handling remains the same) ... + $ref = []; + // Case 1: No Data Found (Soft Success JSON) + if ($e instanceof \RuntimeException && $e->getCode() === 404) { + $ref['message'] = 'No Data Found'; + return $this->respond([ + 'status' => 'success', + 'code' => 200, + 'data' => [], + 'message' => 'No Data Found', + 'ref' => $ref + ], 200); + } + + // Case 2: Database or Other Error (Error JSON) + $isDbError = $e instanceof \CodeIgniter\Database\Exceptions\DatabaseException + || $e instanceof \mysqli_sql_exception + || $e instanceof \PDOException; + + if ($isDbError) { + $ref['debug_info'] = $e->getFile() . " / LN : " . $e->getLine(); + $ref['message'] = 'Database Error Occurred.'; + $message = 'Database Error Occurred.'; + } else { + $ref['message'] = 'An unexpected error occurred: ' . $e->getMessage(); + $message = 'An unexpected error occurred: ' . $e->getMessage(); + } + + return $this->respond([ + 'status' => 'error', + 'code' => 500, + 'data' => [], + 'message'=> $message, + 'ref' => $ref + ], 200); + } + } /** @@ -1322,7 +1536,7 @@ class ExcelExportController extends ResourceController * @param string $month ('current' or 'previous') * @return array */ - private function getBrokerPoliciesData($managerId, $brokerId, $month): array + private function getDataBroker($managerId, $brokerId, $month): array { // --- Correction 1: Initialize Database Connection --- @@ -1343,7 +1557,8 @@ class ExcelExportController extends ResourceController pm.value as payment_mode_value, ipti.insurance_plan_type, pb.name AS broker_name, DATE_FORMAT(pp.issued_date, "%d-%m-%Y") AS issued_date,CONCAT("\t", pp.policy_number) AS policy_number, - pp.premium_amount'); + CONCAT("₹ ", FORMAT(pp.premium_amount, 2, "en_IN")) AS premium_amount, + pp.premium_amount AS raw_premium'); $builder->join('partner_enquiry pe', 'pe.id = pp.enquiry_id', 'left'); $builder->join('partner_brokers pb', 'pb.id = pe.broker_id', 'left'); $builder->join('partner_quotation Q', 'Q.enquiry_id = pe.id', 'left'); @@ -1393,7 +1608,7 @@ class ExcelExportController extends ResourceController * @param string $month ('current' or 'previous') * @return array */ - private function getProductPoliciesData($managerId, $vehicleType, $month): array + private function getDataProduct($managerId, $vehicleType, $month): array { // --- Correction 1: Initialize Database Connection --- @@ -1412,7 +1627,8 @@ class ExcelExportController extends ResourceController pm.value as payment_mode_value, ipti.insurance_plan_type, pp.vehicle_type, DATE_FORMAT(pp.issued_date, "%d-%m-%Y") AS issued_date,CONCAT("\t", pp.policy_number) AS policy_number, - pp.premium_amount'); + CONCAT("₹ ", FORMAT(pp.premium_amount, 2, "en_IN")) AS premium_amount, + pp.premium_amount AS raw_premium'); $builder->join('partner_enquiry pe', 'pe.id = pp.enquiry_id', 'left'); $builder->join('partner_quotation Q', 'Q.enquiry_id = pe.id', 'left'); @@ -1463,7 +1679,7 @@ class ExcelExportController extends ResourceController * @param string $month ('current' or 'previous') * @return array */ - private function getInsurerPoliciesData($managerId, $insurerId, $month): array + private function getDataInsurer($managerId, $insurerId, $month): array { // --- Correction 1: Initialize Database Connection --- @@ -1479,7 +1695,9 @@ class ExcelExportController extends ResourceController pe.reg_no, pm.value as payment_mode_value, ipti.insurance_plan_type, - i.name AS insurer_name,i.short_name,pp.insured_name, DATE_FORMAT(pp.issued_date, "%d-%m-%Y") AS issued_date,CONCAT("\t", pp.policy_number) AS policy_number, pp.premium_amount'); + i.name AS insurer_name,i.short_name,pp.insured_name, DATE_FORMAT(pp.issued_date, "%d-%m-%Y") AS issued_date,CONCAT("\t", pp.policy_number) AS policy_number, + CONCAT("₹ ", FORMAT(pp.premium_amount, 2, "en_IN")) AS premium_amount, + pp.premium_amount AS raw_premium'); $builder->join('partner_quotation pq', 'pq.id = pp.quotation_id', 'left'); $builder->join('insurers i', 'i.id = pq.insurer_id', 'left'); @@ -1532,7 +1750,7 @@ class ExcelExportController extends ResourceController * @param string $month ('current' or 'previous') * @return array */ - private function getStaffAndProductPoliciesExcel($managerId, $executiveId,$vehicleType, $month): array + private function getDataStaffAndProduct($managerId, $executiveId,$vehicleType, $month): array { // --- Correction 1: Initialize Database Connection --- @@ -1550,7 +1768,10 @@ class ExcelExportController extends ResourceController pe.reg_no, pm.value as payment_mode_value, ipti.insurance_plan_type, - pse.name as sales_executive_name, pp.vehicle_type AS vechile_type,CONCAT("\t", pp.policy_number) AS policy_number,DATE_FORMAT(pp.issued_date, "%d-%m-%Y") AS issued_date,pp.premium_amount'); + pse.name as sales_executive_name, pp.vehicle_type AS vechile_type,CONCAT("\t", pp.policy_number) AS policy_number,DATE_FORMAT(pp.issued_date, "%d-%m-%Y") AS issued_date, + CONCAT("₹ ", FORMAT(pp.premium_amount, 2, "en_IN")) AS premium_amount, + pp.premium_amount AS raw_premium'); + $builder->join('partner_agent pa', 'pa.id = pp.agent_id', 'left'); $builder->join('partner_sales_executive pse', 'pse.id = pa.sales_executive_id', 'left'); @@ -1608,7 +1829,7 @@ class ExcelExportController extends ResourceController * @param string $month ('current' or 'previous') * @return array */ - private function getMonthlyPoliciesData($managerId, $AgentId): array + private function getDataPerformingAgentsByID($managerId, $AgentId): array { $data = []; @@ -1629,8 +1850,8 @@ class ExcelExportController extends ResourceController pa.agent_code AS agent_code, pa.name AS agent_name, CONCAT("\t", pp.policy_number) AS policy_number, - pp.premium_amount - '); + CONCAT("₹ ", FORMAT(pp.premium_amount, 2, "en_IN")) AS premium_amount, + pp.premium_amount AS raw_premium'); // 2. Joins $builder->join('partner_agent pa', 'pp.agent_id = pa.id', 'inner'); @@ -1680,7 +1901,7 @@ class ExcelExportController extends ResourceController } - public function getMonthlyPolicyCountandPremiumAmount($manager_id){ + public function getDataPerformingAgentsTop50($manager_id){ $data = []; @@ -1693,8 +1914,8 @@ class ExcelExportController extends ResourceController pa.agent_code, pa.name AS agent_name, COUNT(pp.policy_number) AS policy_count, - SUM(pp.premium_amount) AS total_premium_amount - "); + CONCAT('₹ ', FORMAT(SUM(pp.premium_amount), 2, 'en_IN')) AS premium_amount, + SUM(pp.premium_amount) AS raw_premium"); $builder->join('partner_agent pa', 'pp.agent_id = pa.id', 'inner'); $builder->join('partner_enquiry pe', 'pe.id = pp.enquiry_id', 'left'); @@ -1730,7 +1951,7 @@ class ExcelExportController extends ResourceController * @param string $managerId * @return array */ - private function getAgentsWithoutPoliciesData($managerId): array + private function getDataAgentsWithoutPolicies($managerId): array { $data = []; @@ -1795,151 +2016,195 @@ class ExcelExportController extends ResourceController return $data; } - - /** * Executes the detailed policy query and extracts the data for the spreadsheet. * @param string $managerId * @return array */ - private function getLowPremiumAgentData($managerId): array - { - // --- Correction 1: Initialize Database Connection --- + //any changed in this query also change in do the same in DashboardController - getDataLowPremiumAgent + public function getDataLowPremiumAgent($manager_id){ - $data = []; + $builder = $this->db->table('partner_policy pp'); - try { - $builder = $this->db->table('partner_policy pp'); + $builder->select(" + pa.id AS agent_id, + pa.agent_code, + pa.name AS agent_name, + CASE + WHEN pa.is_active = 1 THEN 'Active Agent' + ELSE 'Inactive Agent' + END AS agent_status, + MAX(pp.issued_date) AS last_business_date, + CONCAT('₹ ', FORMAT(SUM(pp.premium_amount), 2, 'en_IN')) AS display_premium, + SUM(pp.premium_amount) AS total_premium_amount + "); - $builder->select(" - DATE_FORMAT(pe.created_on, '%d-%m-%Y %h:%i %p') AS received_date, - S.name as assigned_to_name, - I.name as insurer_name,I.short_name as insurer_short_name, - pe.name as insured_name, - pe.reg_no, - pm.value as payment_mode_value, - ipti.insurance_plan_type, - pa.name AS agent_name, - pa.agent_code, - CASE - WHEN pa.is_active = 1 THEN 'Active Partner' - ELSE 'Inactive Partner' - END AS agent_status, - CONCAT('\t', pp.policy_number) AS policy_number, - DATE_FORMAT(pp.issued_date, '%d-%m-%Y') AS issued_date, - pp.premium_amount - "); + $builder->join('partner_agent pa', 'pa.id = pp.agent_id', 'inner'); - $builder->join('partner_agent pa', 'pa.id = pp.agent_id', 'inner'); + $builder->where('pp.manager_id', $manager_id); + + $builder->having('total_premium_amount <', 50000); + + // RAW condition must be inside where() with FALSE + // $builder->where(" + // pp.issued_date >= DATE_SUB(CURRENT_TIMESTAMP(), INTERVAL 10 DAY) + // ", null, false); + + // groupBy must be array of separate fields + $builder->groupBy([ + 'pa.id', + 'pa.name', + 'pa.agent_code', + 'pa.is_active' + ]); + + // orderBy must not contain semicolon + must be separated + $builder->orderBy('total_premium_amount', 'DESC'); + $builder->orderBy('last_business_date', 'ASC'); + return $builder->get()->getResultArray(); + } + + // Second Comment + // private function getDataLowPremiumAgent($managerId): array + // { + // $data = []; + + // try { + // // 1. Get the list of Agent IDs who have TOTAL premium < 50,000 + // $agentIdList = $this->db->table('partner_policy') + // ->select('agent_id') + // ->where('manager_id', $managerId) + // ->groupBy('agent_id') + // ->having('SUM(premium_amount) <', 50000) + // ->get() + // ->getResultArray(); + + // // Extract IDs into a simple array: [1, 5, 10...] + // $agentIds = array_column($agentIdList, 'agent_id'); + + // // 2. If no agents found, return empty + // if (empty($agentIds)) { + // return []; + // } + + // // 3. Fetch detailed records for ONLY these agents + // $builder = $this->db->table('partner_policy pp'); + + // $builder->select(" + // DATE_FORMAT(pe.created_on, '%d-%m-%Y %h:%i %p') AS received_date, + // S.name as assigned_to_name, + // I.name as insurer_name, + // I.short_name as insurer_short_name, + // pe.name as insured_name, + // pe.reg_no, + // pm.value as payment_mode_value, + // ipti.insurance_plan_type, + // pa.name AS agent_name, + // pa.agent_code, + // CASE + // WHEN pa.is_active = 1 THEN 'Active Partner' + // ELSE 'Inactive Partner' + // END AS agent_status, + // CONCAT('\t', pp.policy_number) AS policy_number, + // DATE_FORMAT(pp.issued_date, '%d-%m-%Y') AS issued_date, + // /* Indian Rupee Formatting for individual policy premium */ + // CONCAT('₹ ', FORMAT(pp.premium_amount, 2, 'en_IN')) AS premium_amount, + // pp.premium_amount AS raw_premium + // "); + + // $builder->join('partner_agent pa', 'pa.id = pp.agent_id', 'inner'); + // $builder->join('partner_enquiry pe', 'pe.id = pp.enquiry_id', 'left'); + // $builder->join('partner_quotation Q', 'Q.enquiry_id = pe.id', 'left'); + // $builder->join('partner_payment_mode_master pm', 'pm.id = Q.payment_mode_id', 'left'); + // $builder->join('partner_insurance_plan_type_master ipti', 'ipti.id = Q.insurance_plan_type_id', 'left'); + // $builder->join('insurers I', 'I.id = Q.insurer_id', 'left'); + // $builder->join('partner_staff S', 'S.id = pe.assigned_to', 'left'); + + // // WHERE filters + // $builder->where('pp.manager_id', $managerId); + // $builder->whereIn('pp.agent_id', $agentIds); // <--- This filters by the 104 agents found + // $builder->where('pp.premium_amount IS NOT NULL'); + + // $builder->orderBy('pp.issued_date', 'DESC'); + + // $results = $builder->get()->getResultArray(); + + // // Restructure for Excel (array_values removes the string keys) + // foreach ($results as $row) { + // $data[] = array_values($row); + // } + + // } catch (\Exception $e) { + // log_message('error', 'Excel Fetch Error: ' . $e->getMessage()); + // return []; + // } + + // return $data; + // } + + // First Comment + // private function getDataLowPremiumAgent($managerId): array + // { + // // --- Correction 1: Initialize Database Connection --- + + // $data = []; + + // try { + // $builder = $this->db->table('partner_policy pp'); + + // $builder->select(" + // DATE_FORMAT(pe.created_on, '%d-%m-%Y %h:%i %p') AS received_date, + // S.name as assigned_to_name, + // I.name as insurer_name,I.short_name as insurer_short_name, + // pe.name as insured_name, + // pe.reg_no, + // pm.value as payment_mode_value, + // ipti.insurance_plan_type, + // pa.name AS agent_name, + // pa.agent_code, + // CASE + // WHEN pa.is_active = 1 THEN 'Active Partner' + // ELSE 'Inactive Partner' + // END AS agent_status, + // CONCAT('\t', pp.policy_number) AS policy_number, + // DATE_FORMAT(pp.issued_date, '%d-%m-%Y') AS issued_date, + // CONCAT('₹ ', FORMAT(pp.premium_amount, 2, 'en_IN')) AS premium_amount, + // pp.premium_amount AS raw_premium + // "); + + // $builder->join('partner_agent pa', 'pa.id = pp.agent_id', 'inner'); - $builder->join('partner_enquiry pe', 'pe.id = pp.enquiry_id', 'left'); - $builder->join('partner_quotation Q', 'Q.enquiry_id = pe.id', 'left'); - $builder->join('partner_payment_mode_master pm', 'pm.id = Q.payment_mode_id', 'left'); + // $builder->join('partner_enquiry pe', 'pe.id = pp.enquiry_id', 'left'); + // $builder->join('partner_quotation Q', 'Q.enquiry_id = pe.id', 'left'); + // $builder->join('partner_payment_mode_master pm', 'pm.id = Q.payment_mode_id', 'left'); - $builder->join('partner_insurance_plan_type_master ipti', 'ipti.id = Q.insurance_plan_type_id', 'left'); - $builder->join('insurers I', 'I.id = Q.insurer_id', 'left'); - $builder->join('partner_staff S', 'S.id = pe.assigned_to', 'left'); + // $builder->join('partner_insurance_plan_type_master ipti', 'ipti.id = Q.insurance_plan_type_id', 'left'); + // $builder->join('insurers I', 'I.id = Q.insurer_id', 'left'); + // $builder->join('partner_staff S', 'S.id = pe.assigned_to', 'left'); - // WHERE conditions - $builder->where('pp.manager_id', $managerId); - // $builder->where('pa.id', $agentId); - $builder->having('total_premium_amount <', 50000); - $builder->orderBy('pp.issued_date', 'DESC'); + // // WHERE conditions + // $builder->where('pp.manager_id', $managerId); + // // $builder->where('pa.id', $agentId); + // $builder->having('raw_premium <', 50000); + // $builder->orderBy('pp.issued_date', 'DESC'); - $results = $builder->get()->getResultArray(); + // $results = $builder->get()->getResultArray(); - // Restructure data for PhpSpreadsheet (2D array of values) - foreach ($results as $row) { - $data[] = array_values($row); - } + // // Restructure data for PhpSpreadsheet (2D array of values) + // foreach ($results as $row) { + // $data[] = array_values($row); + // } - } catch (DatabaseException $e) { - log_message('error', 'Database Error during Excel fetch: ' . $e->getMessage()); - // Re-throw the exception so it is caught by the main function's catch block - throw $e; - } + // } catch (DatabaseException $e) { + // log_message('error', 'Database Error during Excel fetch: ' . $e->getMessage()); + // // Re-throw the exception so it is caught by the main function's catch block + // throw $e; + // } - return $data; - } + // return $data; + // } - //any changed in this query also change in do the same in DashboardController - getLowPremiumAgentData - private function getLowPremiumAgentData_new($managerId): array - { - // --- Correction 1: Initialize Database Connection --- - - $data = []; - - try { - // 1. First, get the IDs of agents who meet the < 50,000 criteria - $subQuery = $this->db->table('partner_policy') - ->select('agent_id') - ->where('manager_id', $managerId) - ->groupBy('agent_id') - ->having('SUM(premium_amount) <', 50000) - ->get() - ->getResultArray(); - - $agentIds = array_column($subQuery, 'agent_id'); - - // 2. If no agents found, return empty to avoid SQL errors - if (empty($agentIds)) { - return []; - } - - // 3. Now build the detailed Export Query - $builder = $this->db->table('partner_policy pp'); - - $builder->select(" - DATE_FORMAT(pe.created_on, '%d-%m-%Y %h:%i %p') AS received_date, - S.name as assigned_to_name, - I.name as insurer_name, - I.short_name as insurer_short_name, - pe.name as insured_name, - pe.reg_no, - pm.value as payment_mode_value, - ipti.insurance_plan_type, - pa.name AS agent_name, - pa.agent_code, - CASE - WHEN pa.is_active = 1 THEN 'Active Partner' - ELSE 'Inactive Partner' - END AS agent_status, - CONCAT('\t', pp.policy_number) AS policy_number, - DATE_FORMAT(pp.issued_date, '%d-%m-%Y') AS issued_date, - pp.premium_amount - "); - - $builder->join('partner_agent pa', 'pa.id = pp.agent_id', 'inner'); - $builder->join('partner_enquiry pe', 'pe.id = pp.enquiry_id', 'left'); - $builder->join('partner_quotation Q', 'Q.enquiry_id = pe.id', 'left'); - $builder->join('partner_payment_mode_master pm', 'pm.id = Q.payment_mode_id', 'left'); - $builder->join('partner_insurance_plan_type_master ipti', 'ipti.id = Q.insurance_plan_type_id', 'left'); - $builder->join('insurers I', 'I.id = Q.insurer_id', 'left'); - $builder->join('partner_staff S', 'S.id = pe.assigned_to', 'left'); - - // WHERE conditions - $builder->where('pp.manager_id', $managerId); - $builder->whereIn('pp.agent_id', $agentIds); // Filter by the IDs we found above - - $builder->orderBy('pp.issued_date', 'DESC'); - - $results = $builder->get()->getResultArray(); - // return $results; - // Restructure data for PhpSpreadsheet (2D array of values) - foreach ($results as $row) { - $data[] = array_values($row); - } - - } catch (DatabaseException $e) { - log_message('error', 'Database Error during Excel fetch: ' . $e->getMessage()); - // Re-throw the exception so it is caught by the main function's catch block - throw $e; - } - - return $data; - } - - private function getStaffPendingSummaryExcel($managerId): array + private function getDataStaffPendingSummary($managerId): array { $data = []; @@ -1987,11 +2252,11 @@ class ExcelExportController extends ResourceController return $data; } - private function getStaffPendingSummaryExcelByID($managerId, $staffId, $status): array + private function getDataStaffPendingSummaryByID($managerId, $staffId, $status): array { try { $builder = $this->db->table('partner_enquiry pe'); - $builder = $this->db->table('partner_enquiry pe'); + $builder->select(' DATE_FORMAT(pe.created_on, "%d-%m-%Y %h:%i %p") AS received_date, @@ -2069,4 +2334,52 @@ class ExcelExportController extends ResourceController } } + + private function getDataEndorsement($managerId): array + { + try { + + $sql = "SELECT + per.policy_from, + DATE_FORMAT(per.created_at, '%d-%m-%Y %h:%i %p') AS received_date, + I.name AS insurer_name, + pa.name AS agent_name, + ps.name AS staff_name, + pe.reg_no, + CONCAT('\t', pp.policy_number) AS policy_number, + petm.endorsement_type AS endorsement_type, + per.contact_person, + per.financia_or_non_financial, + per.pending_days, + per.endorsement_description AS remarks, + CONCAT('₹ ', FORMAT(per.endorsement_premium, 2, 'en_IN')) AS premium_amount, + per.endorsement_premium AS raw_premium + FROM partner_endorsement_request AS per + LEFT JOIN partner_policy pp ON pp.agent_id = per.agent_id + LEFT JOIN partner_enquiry pe ON pe.agent_id = per.agent_id + LEFT JOIN partner_agent pa ON pa.id = per.agent_id + LEFT JOIN partner_staff ps ON ps.id = pe.assigned_to + LEFT JOIN insurers I ON I.id = pe.insurer_id + LEFT JOIN partner_endorsement_type_master petm ON petm.id = per.endorsement_type + WHERE per.manager_id = :manager_id: + AND per.is_active = 1 + GROUP BY per.id"; + + + $query = $this->db->query($sql, ['manager_id' => $managerId]); + + $results = $query->getResultArray(); + $data = []; + foreach ($results as $row) { + $data[] = array_values($row); + } + + return $data; + + } catch (\Exception $e) { + log_message('error', 'Excel Fetch Error: ' . $e->getMessage()); + throw $e; + } + } + } diff --git a/app/Controllers/SalesExecutive.php b/app/Controllers/SalesExecutive.php index bdec6cb..e21108b 100644 --- a/app/Controllers/SalesExecutive.php +++ b/app/Controllers/SalesExecutive.php @@ -59,11 +59,18 @@ class SalesExecutive extends ResourceController { try{ $data = $this->request->getJSON(true); + + $email = (!empty($data['email'])) ? $data['email'] : null; + $mobile = (!empty($data['mobile'])) ? $data['mobile'] : null; + + if ($email === null && $mobile === null) { + return $this->respond(['status' => 'failed', 'code' => 500, 'data' => 'Email or Mobile is required'], 500); + } $insertData = [ 'name' => $data['name'], - 'email' => $data['email'], - 'mobile' => $data['mobile'], + 'email' => $email, + 'mobile' => $mobile, 'address' => $data['address'], 'manager_id' => $data['manager_id'], 'created_by' => $data['created_by'], @@ -75,7 +82,18 @@ class SalesExecutive extends ResourceController return $this->respond(['status' => 'success', 'code' => 200, 'data' => []], 200); } catch (\Exception $e) { - return $this->respond(['status' => 'failed', 'code' => 500, 'data' => $e->getMessage()], 500); + // return $this->respond(['status' => 'failed', 'code' => 500, 'data' => $e->getMessage()], 500); + $message = $e->getMessage(); + if (strpos($message, '1062') !== false || strpos($message, 'Duplicate entry') !== false) { + if (strpos($message, 'sales_executive_unique_mobile') !== false) { + $message = 'Mobile number already exists'; + } elseif (strpos($message, 'sales_executive_email') !== false) { + $message = 'Email already exists'; + } else { + $message = 'Duplicate record found'; + } + } + return $this->respond(['status' => 'failed', 'code' => 500, 'data' => $message], 500); } } @@ -96,11 +114,17 @@ class SalesExecutive extends ResourceController if (!$salesExecutive) { return $this->respond(['status' => 'failed', 'code' => 200, 'data' => 'Date Not Found'], 200); } + $email = (!empty($data['email'])) ? $data['email'] : null; + $mobile = (!empty($data['mobile'])) ? $data['mobile'] : null; + + if ($email === null && $mobile === null) { + return $this->respond(['status' => 'failed', 'code' => 500, 'data' => 'Either Email or Mobile must be provided'], 500); + } $updateData = [ 'name' => $data['name'] ?? null, - 'email' => $data['email'] ?? null, - 'mobile' => $data['mobile'] ?? null, + 'email' => $email, + 'mobile' => $mobile, 'address' => $data['address'] ?? null, 'updated_by' => $data['updated_by'] ?? null, ]; @@ -110,7 +134,18 @@ class SalesExecutive extends ResourceController return $this->respond(['status' => 'success', 'code' => 200, 'data' => []], 200); } catch (\Exception $e) { - return $this->respond(['status' => 'failed', 'code' => 500, 'data' => $e->getMessage()], 500); + // return $this->respond(['status' => 'failed', 'code' => 500, 'data' => $e->getMessage()], 500); + $message = $e->getMessage(); + if (strpos($message, '1062') !== false || strpos($message, 'Duplicate entry') !== false) { + if (strpos($message, 'sales_executive_unique_mobile') !== false) { + $message = 'Mobile number already exists'; + } elseif (strpos($message, 'sales_executive_email') !== false) { + $message = 'Email already exists'; + } else { + $message = 'Duplicate record found'; + } + } + return $this->respond(['status' => 'failed', 'code' => 500, 'data' => $message], 500); } } diff --git a/app/Controllers/StaffController.php b/app/Controllers/StaffController.php index ba062dd..2f1c325 100644 --- a/app/Controllers/StaffController.php +++ b/app/Controllers/StaffController.php @@ -254,7 +254,7 @@ class StaffController extends ResourceController 'mobile' => $data['mobile'] ?? null, 'role_id' => $data['role_id'], 'manager_id' => $data['manager_id'] ?? null, - 'handler_id' => json_encode($data['handler_id'] ?? []), + 'handler_id' => (isset($data['handler_id']) && !empty($data['handler_id'])) ? json_encode($data['handler_id']) : json_encode([]), 'created_by' => $data['created_by'] ]; @@ -285,18 +285,15 @@ class StaffController extends ResourceController return $this->respond(['status' => 'failed', 'code' => 200, 'data' => 'Date Not Found'], 200); } - $updateData = [ 'name' => $data['name'], 'email' => $data['email'], 'mobile' => $data['mobile'], 'role_id' => $data['role_id'], - 'handler_id' => !empty($data['handler_id']) ? json_encode($data['handler_id']) : [], + 'handler_id' => (isset($data['handler_id']) && !empty($data['handler_id'])) ? json_encode($data['handler_id']) : json_encode([]), 'updated_by' => $data['updated_by'], ]; - - $this->StaffModel->update($id, $updateData); return $this->respond(['status' => 'success', 'code' => 200, 'data' => []], 200); diff --git a/app/Models/EnquiryModel.php b/app/Models/EnquiryModel.php index e969bb0..233124e 100644 --- a/app/Models/EnquiryModel.php +++ b/app/Models/EnquiryModel.php @@ -64,7 +64,7 @@ class EnquiryModel extends Model ->join('partner_agent A', 'A.id = partner_enquiry.agent_id', 'left') ->join('partner_staff S', 'S.id = partner_enquiry.assigned_to', 'left') ->join('partner_quotation Q', 'Q.enquiry_id = partner_enquiry.id AND Q.status = "Accepted" ', 'left') - ->join('insurers I', 'I.id = Q.insurer_id', 'left') + ->join('insurers I', 'I.id = partner_enquiry.insurer_id', 'left') ->join('partner_policy P', 'P.quotation_id = Q.id', 'left') ->join('partner_brokers PB', 'PB.id = partner_enquiry.broker_id', 'left') ->join('partner_payment_mode_master pm', 'pm.id = Q.payment_mode_id', 'left')