Merge branch 'main' of bitbucket.org:jubilian/nhance_partner_be

This commit is contained in:
Gowtham M 2025-12-26 12:11:50 +05:30
commit 69f352cbef
2 changed files with 269 additions and 94 deletions

View File

@ -501,10 +501,34 @@ class DashboardController extends ResourceController
$date = $this->request->getGet('date'); $date = $this->request->getGet('date');
$date = $date ?? date('Y-m-d'); $date = $date ?? date('Y-m-d');
$details['monthlyPolicyCount'] = $this->agentMonthlyPolicyCountandPremiumAmount($date,$manager_id,$raw); $data1 = $this->agentMonthlyPolicyCountandPremiumAmount($date, $manager_id, false);
// $details['monthlyPremiumAmount'] = $this->agentMonthlyPremiumAmount($date,$manager_id,$raw);
if (!empty($data1)) {
$lastIndex1 = count(reset($data1)) - 1;
usort($data1, function($a, $b) use ($lastIndex1) {
$rowA = array_values($a);
$rowB = array_values($b);
return (float)$rowB[$lastIndex1] <=> (float)$rowA[$lastIndex1];
});
}
$details['monthlyPolicyCount'] = $data1;
$details['noPolicyTimeRange'] = $this->agentNoPolicyTimeRange($manager_id,$raw); $details['noPolicyTimeRange'] = $this->agentNoPolicyTimeRange($manager_id,$raw);
$details['below50tPremiumTimeRange'] = $this->agentBelow50tPremiumTimeRange($manager_id,$raw); $data2 = $this->agentBelow50tPremiumTimeRange($manager_id,$raw);
if (!empty($data2)) {
$lastIndex2 = count(reset($data2)) - 1;
usort($data2, function($a, $b) use ($lastIndex2) {
$rowC = array_values($a);
$rowD = array_values($b);
return (float)$rowD[$lastIndex2] <=> (float)$rowC[$lastIndex2];
});
}
$details['below50tPremiumTimeRange'] = $data2;
// $details['monthlyPremiumAmount'] = $this->agentMonthlyPremiumAmount($date,$manager_id,$raw);
$ref['monthlyPolicyCountAndPremiumAmount_total_records'] = is_array($details['monthlyPolicyCount']) ? count($details['monthlyPolicyCount']) : 0; $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['noPolicyTimeRange_total_records'] = is_array($details['noPolicyTimeRange']) ? count($details['noPolicyTimeRange']) : 0;
@ -929,12 +953,12 @@ class DashboardController extends ResourceController
pa.id AS agent_id, pa.id AS agent_id,
pa.name AS agent_name, pa.name AS agent_name,
pa.agent_code, pa.agent_code,
SUM(pp.premium_amount) AS total_premium_amount,
CASE CASE
WHEN pa.is_active = 1 THEN 'Active Agent' WHEN pa.is_active = 1 THEN 'Active Agent'
ELSE 'Inactive Agent' ELSE 'Inactive Agent'
END AS agent_status, END AS agent_status,
MAX(pp.issued_date) AS last_business_date MAX(pp.issued_date) AS last_business_date,
SUM(pp.premium_amount) AS total_premium_amount
"); ");
$builder->join('partner_agent pa', 'pa.id = pp.agent_id', 'inner'); $builder->join('partner_agent pa', 'pa.id = pp.agent_id', 'inner');

View File

@ -113,8 +113,23 @@ class ExcelExportController extends ResourceController
} }
$data = $this->getBrokerPoliciesData($managerId, $brokerId, $month); $data = $this->getBrokerPoliciesData($managerId, $brokerId, $month);
if (empty($data)) {
throw new \RuntimeException('No policies found...', 404);
}
$lastIndex = count(reset($data)) - 1;
// usort($data, function($a, $b) use ($lastIndex) {
// return (float)$a[$lastIndex] <=> (float)$b[$lastIndex];
// });
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 = [ $header = ['S.No',
'Received Date', 'Assigned To', 'Received Date', 'Assigned To',
'Partner Name' , 'Partner Code', 'Partner Name' , 'Partner Code',
'Insurer Name' ,'Insurer Short Name', 'Insurer Name' ,'Insurer Short Name',
@ -124,28 +139,24 @@ class ExcelExportController extends ResourceController
if (empty($data)) {
throw new \RuntimeException('No policies found...', 404);
}
// Calculate and append total // Calculate and append total
$lastColIndex = count($header) - 1; // Get index of the last column (Premium) $lastColIndex = count($header) - 1; // Get index of the last column (Premium)
$grandTotal = array_sum(array_column($data, $lastColIndex)); $grandTotal = array_sum(array_column($finalData, $lastColIndex));
$totalRow = array_fill(0, count($header), ''); // Create empty row of same width $totalRow = array_fill(0, count($header), ''); // Create empty row of same width
$totalRow[$lastColIndex - 1] = 'Total:'; // Put label in 2nd to last $totalRow[$lastColIndex - 1] = 'Total:'; // Put label in 2nd to last
$totalRow[$lastColIndex] = $grandTotal; // Put sum in last $totalRow[$lastColIndex] = $grandTotal; // Put sum in last
$data[] = $totalRow; $finalData[] = $totalRow;
$monthName = ($month === 'current') ? date('M_Y') : date('M_Y', strtotime('-1 month')); $monthName = ($month === 'current') ? date('M_Y') : date('M_Y', strtotime('-1 month'));
$brokerName = $data[0][10] ?? 'Broker'; $brokerName = $finalData[0][11] ?? 'Broker';
$cleanbrokerName = str_replace(' ', '_', strtolower($brokerName)); $cleanbrokerName = str_replace(' ', '_', strtolower($brokerName));
$fileName = $cleanbrokerName . '_Policies_Details_' . $monthName . '.xlsx'; $fileName = $cleanbrokerName . '_Policies_Details_' . $monthName . '.xlsx';
// --- CALL CENTRALIZED FUNCTION --- // --- CALL CENTRALIZED FUNCTION ---
$this->streamExcelFile( $this->streamExcelFile(
$header, $header,
$data, $finalData,
"Broker Policies Details for {$monthName}", "Broker Policies Details for {$monthName}",
$fileName, $fileName,
true // Pass 'true' to show/bold the total row true // Pass 'true' to show/bold the total row
@ -217,8 +228,23 @@ class ExcelExportController extends ResourceController
} }
$data = $this->getProductPoliciesData($managerId, $vehicleType, $month); $data = $this->getProductPoliciesData($managerId, $vehicleType, $month);
if (empty($data)) {
throw new \RuntimeException('No policies found for this vehicle type...', 404);
}
$lastIndex = count(reset($data)) - 1;
// usort($data, function($a, $b) use ($lastIndex) {
// return (float)$a[$lastIndex] <=> (float)$b[$lastIndex];
// });
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 = ['Vehicle Type', 'Issue Date', 'Policy Number', 'Premium Amount']; // $header = ['Vehicle Type', 'Issue Date', 'Policy Number', 'Premium Amount'];
$header = [ $header = ['S.No',
'Received Date', 'Assigned To', 'Received Date', 'Assigned To',
'Partner Name' , 'Partner Code', 'Partner Name' , 'Partner Code',
'Insurer Name' ,'Insurer Short Name', 'Insurer Name' ,'Insurer Short Name',
@ -226,28 +252,26 @@ class ExcelExportController extends ResourceController
'Payment Mode', 'Plan Type', 'Payment Mode', 'Plan Type',
'Vehicle Type', 'Issue Date', 'Policy Number', 'Premium Amount']; 'Vehicle Type', 'Issue Date', 'Policy Number', 'Premium Amount'];
if (empty($data)) {
throw new \RuntimeException('No policies found for this vehicle type...', 404);
}
// Calculate and append total // Calculate and append total
$lastColIndex = count($header) - 1; // Get index of the last column (Premium) $lastColIndex = count($header) - 1; // Get index of the last column (Premium)
$grandTotal = array_sum(array_column($data, $lastColIndex)); $grandTotal = array_sum(array_column($finalData, $lastColIndex));
$totalRow = array_fill(0, count($header), ''); // Create empty row of same width $totalRow = array_fill(0, count($header), ''); // Create empty row of same width
$totalRow[$lastColIndex - 1] = 'Total:'; // Put label in 2nd to last $totalRow[$lastColIndex - 1] = 'Total:'; // Put label in 2nd to last
$totalRow[$lastColIndex] = $grandTotal; // Put sum in last $totalRow[$lastColIndex] = $grandTotal; // Put sum in last
$data[] = $totalRow; $finalData[] = $totalRow;
$monthName = ($month === 'current') ? date('M_Y') : date('M_Y', strtotime('-1 month')); $monthName = ($month === 'current') ? date('M_Y') : date('M_Y', strtotime('-1 month'));
$vehicleType = $data[0][10] ?? 'Vehicle'; $vehicleType = $finalData[0][11] ?? 'Vehicle';
$cleanVehicleType = str_replace(' ', '_', strtolower($vehicleType)); $cleanVehicleType = str_replace(' ', '_', strtolower($vehicleType));
$fileName = $cleanVehicleType . '_Policies_Details_' . $monthName . '.xlsx'; $fileName = $cleanVehicleType . '_Policies_Details_' . $monthName . '.xlsx';
// --- CALL CENTRALIZED FUNCTION --- // --- CALL CENTRALIZED FUNCTION ---
$this->streamExcelFile( $this->streamExcelFile(
$header, $header,
$data, $finalData,
"Vehicle Type Policies Details for {$monthName}", "Vehicle Type Policies Details for {$monthName}",
$fileName, $fileName,
true // This will ignore the bold/alignment logic for the last row true // This will ignore the bold/alignment logic for the last row
@ -322,37 +346,51 @@ class ExcelExportController extends ResourceController
$data = $this->getInsurerPoliciesData($managerId, $insurerId, $month); $data = $this->getInsurerPoliciesData($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);
}
$lastIndex = count(reset($data)) - 1;
// usort($data, function($a, $b) use ($lastIndex) {
// return (float)$a[$lastIndex] <=> (float)$b[$lastIndex];
// });
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);
}
// Define column headers // Define column headers
$header = [ $header = ['S.No',
'Received Date', 'Assigned To', 'Received Date', 'Assigned To',
'Partner Name' , 'Partner Code', 'Partner Name' , 'Partner Code',
'Vehicle Number', 'Vehicle Number',
'Payment Mode', 'Plan Type', 'Payment Mode', 'Plan Type',
'Insurer Name', 'Insurer Short Name','Insured Name', 'Policy Issued Date','Policy Number', 'Premium Amount']; 'Insurer Name', 'Insurer Short Name','Insured Name', 'Policy Issued Date','Policy Number', 'Premium Amount'];
// --- 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);
}
// Calculate and append total // Calculate and append total
$lastColIndex = count($header) - 1; // Get index of the last column (Premium) $lastColIndex = count($header) - 1; // Get index of the last column (Premium)
$grandTotal = array_sum(array_column($data, $lastColIndex)); $grandTotal = array_sum(array_column($finalData, $lastColIndex));
$totalRow = array_fill(0, count($header), ''); // Create empty row of same width $totalRow = array_fill(0, count($header), ''); // Create empty row of same width
$totalRow[$lastColIndex - 1] = 'Total:'; // Put label in 2nd to last $totalRow[$lastColIndex - 1] = 'Total:'; // Put label in 2nd to last
$totalRow[$lastColIndex] = $grandTotal; // Put sum in last $totalRow[$lastColIndex] = $grandTotal; // Put sum in last
$data[] = $totalRow; $finalData[] = $totalRow;
$monthName = ($month === 'current') ? date('M_Y') : date('M_Y', strtotime('-1 month')); $monthName = ($month === 'current') ? date('M_Y') : date('M_Y', strtotime('-1 month'));
$InsurerName = $data[0][7] ?? 'Insurer' ; $InsurerName = $finalData[0][8] ?? 'Insurer' ;
$cleanInsurerName = str_replace(' ', '_', strtolower($InsurerName)); $cleanInsurerName = str_replace(' ', '_', strtolower($InsurerName));
$fileName = $cleanInsurerName . '_Policies_Details_' . $monthName . '.xlsx'; $fileName = $cleanInsurerName . '_Policies_Details_' . $monthName . '.xlsx';
// --- CALL CENTRALIZED FUNCTION --- // --- CALL CENTRALIZED FUNCTION ---
$this->streamExcelFile( $this->streamExcelFile(
$header, $header,
$data, $finalData,
"Insurer Policies Details for {$monthName}", "Insurer Policies Details for {$monthName}",
$fileName, $fileName,
true // This will ignore the bold/alignment logic for the last row true // This will ignore the bold/alignment logic for the last row
@ -416,35 +454,44 @@ class ExcelExportController extends ResourceController
} }
$data = $this->getLowPremiumAgentData($managerId); $data = $this->getLowPremiumAgentData($managerId);
$header = [ if (empty($data)) {
throw new \RuntimeException('No low premium agents found...', 404);
}
$finalData = [];
$serialNo = 1;
foreach ($data as $row) {
$finalData[] = array_merge([$serialNo++], $row);
}
$header = ['S.No',
'Received Date', 'Assigned To', 'Received Date', 'Assigned To',
'Insurer Name' ,'Insurer Short Name', 'Insurer Name' ,'Insurer Short Name',
'Insured Name', 'Vehicle Number', 'Insured Name', 'Vehicle Number',
'Payment Mode', 'Plan Type', 'Payment Mode', 'Plan Type',
'Partner Name', 'Partner Code','Partner Status' ,'Policy Number','Issued Date', 'Premium Amount']; 'Partner Name', 'Partner Code','Partner Status' ,'Policy Number','Issued Date', 'Premium Amount'];
if (empty($data)) {
throw new \RuntimeException('No low premium agents found...', 404);
}
// Calculate and append total // Calculate and append total
$lastColIndex = count($header) - 1; // Get index of the last column (Premium) $lastColIndex = count($header) - 1; // Get index of the last column (Premium)
$grandTotal = array_sum(array_column($data, $lastColIndex)); $grandTotal = array_sum(array_column($finalData, $lastColIndex));
$totalRow = array_fill(0, count($header), ''); // Create empty row of same width $totalRow = array_fill(0, count($header), ''); // Create empty row of same width
$totalRow[$lastColIndex - 1] = 'Total:'; // Put label in 2nd to last $totalRow[$lastColIndex - 1] = 'Total:'; // Put label in 2nd to last
$totalRow[$lastColIndex] = $grandTotal; // Put sum in last $totalRow[$lastColIndex] = $grandTotal; // Put sum in last
$data[] = $totalRow; $finalData[] = $totalRow;
// Note: $month variable is undefined, assuming you want current month for filename // Note: $month variable is undefined, assuming you want current month for filename
$monthName = date('M_Y'); $monthName = date('M_Y');
$PartnerName = $data[0][8] ?? 'Partner'; $PartnerName = $finalData[0][9] ?? 'Partner';
$fileName = 'Partners_Low_Premium_Policy_Details.xlsx'; $fileName = 'Partners_Low_Premium_Policy_Details.xlsx';
// --- CALL CENTRALIZED FUNCTION --- // --- CALL CENTRALIZED FUNCTION ---
$this->streamExcelFile( $this->streamExcelFile(
$header, $header,
$data, $finalData,
"Partners Low Premium Policy Details", "Partners Low Premium Policy Details",
$fileName, $fileName,
true // This will ignore the bold/alignment logic for the last row true // This will ignore the bold/alignment logic for the last row
@ -511,36 +558,60 @@ class ExcelExportController extends ResourceController
// Renamed helper function for consistency: getAgentMonthlyPoliciesData // Renamed helper function for consistency: getAgentMonthlyPoliciesData
$data = $this->getMonthlyPoliciesData($managerId, $agentId); // , $month); $data = $this->getMonthlyPoliciesData($managerId, $agentId); // , $month);
$header = [
'Received Date', 'Assigned To',
'Insurer Name' ,'Insurer Short Name',
'Insured Name', 'Vehicle Number',
'Payment Mode', 'Plan Type',
'Partner Name','Partner Code' , 'Policy Number','Issue Date', 'Premium Amount'];
if (empty($data)) { if (empty($data)) {
throw new \RuntimeException('No policies found for this agent for the specified month.', 404); throw new \RuntimeException('No policies found for this agent for the specified month.', 404);
} }
$lastIndex = count(reset($data)) - 1;
// usort($data, function($a, $b) use ($lastIndex) {
// return (float)$a[$lastIndex] <=> (float)$b[$lastIndex];
// });
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',
'Insurer Name', 'Insurer Short Name',
'Insured Name', 'Vehicle Number',
'Payment Mode', 'Plan Type', 'Issue Date',
'Partner Code', 'Partner Name',
'Policy Number', 'Premium Amount'];
$finalData = [];
$serialNo = 1;
foreach ($data as $row) {
$finalData[] = array_merge([$serialNo++], $row);
}
// Calculate and append total // Calculate and append total
$lastColIndex = count($header) - 1; // Get index of the last column (Premium) $lastColIndex = count($header) - 1; // Get index of the last column (Premium)
$grandTotal = array_sum(array_column($data, $lastColIndex)); $grandTotal = array_sum(array_column($finalData, $lastColIndex));
$totalRow = array_fill(0, count($header), ''); // Create empty row of same width $totalRow = array_fill(0, count($header), ''); // Create empty row of same width
$totalRow[$lastColIndex - 1] = 'Total:'; // Put label in 2nd to last $totalRow[$lastColIndex - 1] = 'Total:'; // Put label in 2nd to last
$totalRow[$lastColIndex] = $grandTotal; // Put sum in last $totalRow[$lastColIndex] = $grandTotal; // Put sum in last
$data[] = $totalRow; $finalData[] = $totalRow;
// $monthName = ($month === 'current') ? date('M_Y') : date('M_Y', strtotime('-1 month')); // $monthName = ($month === 'current') ? date('M_Y') : date('M_Y', strtotime('-1 month'));
$monthName = date('M Y') ; $monthName = date('M Y') ;
$PartnerName = $data[0][8] ?? 'Partner'; $PartnerName = $finalData[0][11] ?? 'Partner';
$cleanPartnerName = str_replace(' ', '_', strtolower($PartnerName)); $cleanPartnerName = str_replace(' ', '_', strtolower($PartnerName));
$fileName = $cleanPartnerName . '_Policies_Details_' . $monthName . '.xlsx'; $fileName = $cleanPartnerName . '_Policies_Details_' . $monthName . '.xlsx';
// --- CALL CENTRALIZED FUNCTION --- // --- CALL CENTRALIZED FUNCTION ---
$this->streamExcelFile( $this->streamExcelFile(
$header, $header,
$data, $finalData,
"Partner Policies Details for {$monthName}", "Partner Policies Details for {$monthName}",
$fileName, $fileName,
true // This will ignore the bold/alignment logic for the last row true // This will ignore the bold/alignment logic for the last row
@ -591,39 +662,47 @@ class ExcelExportController extends ResourceController
// 5.2) Top 50 Agent the Excel file // 5.2) Top 50 Agent the Excel file
public function downloadT50AgentPoliciesExcel() public function downloadT50AgentPoliciesExcel()
{ {
try{ try{
$managerId = $this->request->getGet('manager_id'); $managerId = $this->request->getGet('manager_id');
if (empty($managerId)) { if (empty($managerId)) {
$msg = "Missing: manager_id";
$msg = "Missing: ";
$msg .= empty($managerId) ? "manager_id " : "";
// $msg .= empty($month) ? "month " : "";
$ref = ['debug_msg' => $msg]; $ref = ['debug_msg' => $msg];
return $this->response->setJSON(['status' => 'error','code' => 400,'data' => [],'message' => 'Missing required parameters','ref' => $ref])->setStatusCode(200); return $this->response->setJSON(['status' => 'error', 'code' => 400, 'data' => [], 'message' => 'Missing required parameters', 'ref' => $ref])->setStatusCode(200);
} }
// Renamed helper function for consistency: getAgentMonthlyPoliciesData // Renamed helper function for consistency: getAgentMonthlyPoliciesData
$data = $this->getMonthlyPoliciesData($managerId, null); $data = $this->getMonthlyPolicyCountandPremiumAmount($managerId);
$header = [ $header = ['S.No', 'Partner Code', 'Partner Name', 'Policy Count', 'Premium Amount'];
'Received Date', 'Assigned To',
'Insurer Name' ,'Insurer Short Name',
'Insured Name', 'Vehicle Number',
'Payment Mode', 'Plan Type',
'Partner Name','Partner Code' , 'Policy Number','Issue Date', 'Premium Amount'];
if (empty($data)) { if (empty($data)) {
throw new \RuntimeException('No policies found for this agent for the specified month.', 404); throw new \RuntimeException('No policies found.', 404);
} }
$lastIndex = count(reset($data)) - 1;
// usort($data, function($a, $b) use ($lastIndex) {
// return (float)$a[$lastIndex] <=> (float)$b[$lastIndex];
// });
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);
}
// Calculate and append total // Calculate and append total
$lastColIndex = count($header) - 1; // Get index of the last column (Premium) $lastColIndex = count($header) - 1; // Get index of the last column (Premium)
$grandTotal = array_sum(array_column($data, $lastColIndex)); $grandTotal = array_sum(array_column($finalData, $lastColIndex));
$totalRow = array_fill(0, count($header), ''); // Create empty row of same width $totalRow = array_fill(0, count($header), ''); // Create empty row of same width
$totalRow[$lastColIndex - 1] = 'Total:'; // Put label in 2nd to last $totalRow[$lastColIndex - 1] = 'Total:'; // Put label in 2nd to last
$totalRow[$lastColIndex] = $grandTotal; // Put sum in last $totalRow[$lastColIndex] = $grandTotal; // Put sum in last
$data[] = $totalRow; $finalData[] = $totalRow; // Add the total row to the final set
$monthName = date('M Y') ; $monthName = date('M Y') ;
$fileName = 'Top_50_Partner_Policies_Details_' . $monthName . '.xlsx'; $fileName = 'Top_50_Partner_Policies_Details_' . $monthName . '.xlsx';
@ -631,7 +710,7 @@ class ExcelExportController extends ResourceController
// --- CALL CENTRALIZED FUNCTION --- // --- CALL CENTRALIZED FUNCTION ---
$this->streamExcelFile( $this->streamExcelFile(
$header, $header,
$data, $finalData,
"Top 50 Partner Policies Details - Monthly Report ".$monthName, "Top 50 Partner Policies Details - Monthly Report ".$monthName,
$fileName, $fileName,
true // This will ignore the bold/alignment logic for the last row true // This will ignore the bold/alignment logic for the last row
@ -693,12 +772,30 @@ class ExcelExportController extends ResourceController
} }
$data = $this->getAgentsWithoutPoliciesData($managerId); $data = $this->getAgentsWithoutPoliciesData($managerId);
$header = ['Partner Name', 'Partner Code', 'Email', 'Mobile'];
if (empty($data)) { if (empty($data)) {
throw new \RuntimeException('No Partners without policies found.', 404); throw new \RuntimeException('No Partners without policies found.', 404);
} }
$header = ['S.No','Partner Code','Partner Name', 'Email', 'Mobile'];
$finalData = [];
$serialNo = 1; // Start counter at 1
// 2. Loop through and prepend the serial number
foreach ($rawData as $row) {
// We create a new array for each row
$finalData[] = [
$serialNo++,
$row['agent_code'],
$row['agent_name'],
$row['email'],
$row['mobile']
];
}
// End Date: Today // End Date: Today
$endDate = date('Ymd'); $endDate = date('Ymd');
// Start Date: 9 days ago (10th day is today) // Start Date: 9 days ago (10th day is today)
@ -713,7 +810,7 @@ class ExcelExportController extends ResourceController
// --- CENTRALIZED CALL --- // --- CENTRALIZED CALL ---
$this->streamExcelFile( $this->streamExcelFile(
$header, $header,
$data, $finalData,
"Partners Without Policies (Last 10 Days)", "Partners Without Policies (Last 10 Days)",
$fileName, $fileName,
false // This will ignore the bold/alignment logic for the last row false // This will ignore the bold/alignment logic for the last row
@ -779,11 +876,26 @@ class ExcelExportController extends ResourceController
} }
$data = $this->getStaffAndProductPoliciesExcel($managerId, $executiveId,$vehicleType, $month); $data = $this->getStaffAndProductPoliciesExcel($managerId, $executiveId,$vehicleType, $month);
$executiveName = $data[0][11] ?? 'Sales Executive'; if (empty($data)) {
$vehicleType = $data[0][12] ?? 'Vehicle Type'; throw new \RuntimeException('No policies found for the specified month.', 404);
}
$lastIndex = count(reset($data)) - 1;
// usort($data, function($a, $b) use ($lastIndex) {
// return (float)$a[$lastIndex] <=> (float)$b[$lastIndex];
// });
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);
}
$executiveName = $finalData[0][12] ?? 'Sales Executive';
$vehicleType = $finalData[0][13] ?? 'Vehicle Type';
// Define column headers // Define column headers
$header = [ $header = ['S.No',
'Received Date', 'Assigned To', 'Received Date', 'Assigned To',
'Partner Name' , 'Partner Code', 'Partner Name' , 'Partner Code',
'Insurer Name' ,'Insurer Short Name', 'Insurer Name' ,'Insurer Short Name',
@ -792,18 +904,16 @@ class ExcelExportController extends ResourceController
'Sales Executive Name', 'Vehicle Type', 'Policy Number','Issued Date', 'Premium Amount']; 'Sales Executive Name', 'Vehicle Type', 'Policy Number','Issued Date', 'Premium Amount'];
// --- 1. MODIFIED LOGIC: Throw RuntimeException if no data --- // --- 1. MODIFIED LOGIC: Throw RuntimeException if no data ---
if (empty($data)) {
throw new \RuntimeException('No policies found for the specified month.', 404);
}
// Calculate and append total // Calculate and append total
$lastColIndex = count($header) - 1; // Get index of the last column (Premium) $lastColIndex = count($header) - 1; // Get index of the last column (Premium)
$grandTotal = array_sum(array_column($data, $lastColIndex)); $grandTotal = array_sum(array_column($finalData, $lastColIndex));
$totalRow = array_fill(0, count($header), ''); // Create empty row of same width $totalRow = array_fill(0, count($header), ''); // Create empty row of same width
$totalRow[$lastColIndex - 1] = 'Total:'; // Put label in 2nd to last $totalRow[$lastColIndex - 1] = 'Total:'; // Put label in 2nd to last
$totalRow[$lastColIndex] = $grandTotal; // Put sum in last $totalRow[$lastColIndex] = $grandTotal; // Put sum in last
$data[] = $totalRow; $finalData[] = $totalRow;
$monthName = ($month === 'current') ? date('M_Y') : date('M_Y', strtotime('-1 month')); $monthName = ($month === 'current') ? date('M_Y') : date('M_Y', strtotime('-1 month'));
@ -815,7 +925,7 @@ class ExcelExportController extends ResourceController
// --- CALL CENTRALIZED FUNCTION --- // --- CALL CENTRALIZED FUNCTION ---
$this->streamExcelFile( $this->streamExcelFile(
$header, $header,
$data, $finalData,
"Staff And Product Policies Details for {$monthName}", "Staff And Product Policies Details for {$monthName}",
$fileName, $fileName,
true // This will ignore the bold/alignment logic for the last row true // This will ignore the bold/alignment logic for the last row
@ -1005,7 +1115,8 @@ class ExcelExportController extends ResourceController
pe.reg_no, pe.reg_no,
pm.value as payment_mode_value, pm.value as payment_mode_value,
ipti.insurance_plan_type, ipti.insurance_plan_type,
pb.name AS broker_name, DATE_FORMAT(pp.issued_date, "%d-%m-%Y") AS issued_date,pp.policy_number, pp.premium_amount'); 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');
$builder->join('partner_enquiry pe', 'pe.id = pp.enquiry_id', 'left'); $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_brokers pb', 'pb.id = pe.broker_id', 'left');
$builder->join('partner_quotation Q', 'Q.enquiry_id = pe.id', 'left'); $builder->join('partner_quotation Q', 'Q.enquiry_id = pe.id', 'left');
@ -1073,7 +1184,8 @@ class ExcelExportController extends ResourceController
pe.reg_no, pe.reg_no,
pm.value as payment_mode_value, pm.value as payment_mode_value,
ipti.insurance_plan_type, ipti.insurance_plan_type,
pp.vehicle_type, DATE_FORMAT(pp.issued_date, "%d-%m-%Y") AS issued_date,pp.policy_number, pp.premium_amount'); 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');
$builder->join('partner_enquiry pe', 'pe.id = pp.enquiry_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_quotation Q', 'Q.enquiry_id = pe.id', 'left');
@ -1140,7 +1252,7 @@ class ExcelExportController extends ResourceController
pe.reg_no, pe.reg_no,
pm.value as payment_mode_value, pm.value as payment_mode_value,
ipti.insurance_plan_type, 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,pp.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, pp.premium_amount');
$builder->join('partner_quotation pq', 'pq.id = pp.quotation_id', 'left'); $builder->join('partner_quotation pq', 'pq.id = pp.quotation_id', 'left');
$builder->join('insurers i', 'i.id = pq.insurer_id', 'left'); $builder->join('insurers i', 'i.id = pq.insurer_id', 'left');
@ -1211,7 +1323,7 @@ class ExcelExportController extends ResourceController
pe.reg_no, pe.reg_no,
pm.value as payment_mode_value, pm.value as payment_mode_value,
ipti.insurance_plan_type, ipti.insurance_plan_type,
pse.name as sales_executive_name, pp.vehicle_type AS vechile_type,pp.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,pp.premium_amount');
$builder->join('partner_agent pa', 'pa.id = pp.agent_id', 'left'); $builder->join('partner_agent pa', 'pa.id = pp.agent_id', 'left');
$builder->join('partner_sales_executive pse', 'pse.id = pa.sales_executive_id', 'left'); $builder->join('partner_sales_executive pse', 'pse.id = pa.sales_executive_id', 'left');
@ -1286,10 +1398,10 @@ class ExcelExportController extends ResourceController
pe.reg_no, pe.reg_no,
pm.value AS payment_mode_value, pm.value AS payment_mode_value,
ipti.insurance_plan_type, ipti.insurance_plan_type,
pa.name AS agent_name,
pa.agent_code,
pp.policy_number,
DATE_FORMAT(pp.issued_date, "%d-%m-%Y") AS issued_date, DATE_FORMAT(pp.issued_date, "%d-%m-%Y") AS issued_date,
pa.agent_code AS agent_code,
pa.name AS agent_name,
CONCAT("\t", pp.policy_number) AS policy_number,
pp.premium_amount pp.premium_amount
'); ');
@ -1306,10 +1418,8 @@ class ExcelExportController extends ResourceController
// 3. Where Conditions // 3. Where Conditions
$builder->where('pp.manager_id', $managerId); $builder->where('pp.manager_id', $managerId);
$builder->where('pp.policy_number IS NOT NULL'); $builder->where('pp.policy_number IS NOT NULL');
if ($AgentId) {
$builder->where('pa.id', $AgentId); $builder->where('pa.id', $AgentId);
}
// Current Month Date Range Filter // Current Month Date Range Filter
// if ($month === "current") { // if ($month === "current") {
@ -1326,10 +1436,6 @@ class ExcelExportController extends ResourceController
// 4. Order and Limit // 4. Order and Limit
$builder->orderBy('pp.issued_date', 'DESC'); $builder->orderBy('pp.issued_date', 'DESC');
if (!$AgentId) {
$builder->limit(50);
}
// 5. Fetch and Restructure // 5. Fetch and Restructure
$results = $builder->get()->getResultArray(); $results = $builder->get()->getResultArray();
@ -1347,6 +1453,51 @@ class ExcelExportController extends ResourceController
} }
public function getMonthlyPolicyCountandPremiumAmount($manager_id){
$data = [];
try {
$customDate = date('Y-m-d');
$builder = $this->db->table('partner_policy pp');
$builder->select("
pa.agent_code,
pa.name AS agent_name,
COUNT(pp.policy_number) AS policy_count,
SUM(pp.premium_amount) AS total_premium_amount
");
$builder->join('partner_agent pa', 'pp.agent_id = pa.id', 'inner');
$builder->join('partner_enquiry pe', 'pe.id = pp.enquiry_id', 'left');
$builder->where("MONTH(pp.issued_date) = MONTH('$customDate')", null, false);
$builder->where("YEAR(pp.issued_date) = YEAR('$customDate')", null, false);
$builder->where('pp.manager_id',$manager_id);
$builder->groupBy(['pa.id']);
$builder->orderBy('policy_count', 'DESC');
$builder->limit(50);
$results = $builder->get()->getResultArray();
// 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;
}
/** /**
* Executes the detailed policy query and extracts the data for the spreadsheet. * Executes the detailed policy query and extracts the data for the spreadsheet.
* @param string $managerId * @param string $managerId
@ -1358,7 +1509,7 @@ class ExcelExportController extends ResourceController
try { try {
$builder = $this->db->table('partner_agent pa'); $builder = $this->db->table('partner_agent pa');
$builder->select('pa.name AS agent_name, pa.agent_code, pa.email, pa.mobile'); $builder->select('pa.agent_code,pa.name AS agent_name, pa.email, pa.mobile');
$builder->join( $builder->join(
'partner_policy pp', 'partner_policy pp',
@ -1414,7 +1565,7 @@ class ExcelExportController extends ResourceController
WHEN pa.is_active = 1 THEN 'Active Partner' WHEN pa.is_active = 1 THEN 'Active Partner'
ELSE 'Inactive Partner' ELSE 'Inactive Partner'
END AS agent_status, END AS agent_status,
pp.policy_number, CONCAT('\t', pp.policy_number) AS policy_number,
DATE_FORMAT(pp.issued_date, '%d-%m-%Y') AS issued_date, DATE_FORMAT(pp.issued_date, '%d-%m-%Y') AS issued_date,
pp.premium_amount pp.premium_amount
"); ");