FIX_download Excel For Top 50 Agentwise Policies Report
This commit is contained in:
parent
c499105297
commit
4fed2b772a
@ -146,10 +146,12 @@ $routes->group('api', ['filter' => 'appSignature'], function ($routes) {
|
||||
$routes->get("dashboard/downloadInsurerPoliciesExcel", "ExcelExportController::downloadInsurerPoliciesExcel");
|
||||
$routes->get("dashboard/downloadProductPoliciesExcel", "ExcelExportController::downloadProductPoliciesExcel");
|
||||
|
||||
//DASHBOARD Season 4 EXPORT EXCEL
|
||||
$routes->get("dashboard/downloadAgentMonthlyPoliciesExcel", "ExcelExportController::downloadAgentMonthlyPoliciesExcel");
|
||||
//DASHBOARD Season 4 EXPORT EXCEL
|
||||
$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/downloadExcelAsZIP", "ExcelExportController::downloadExcelAsZIP");
|
||||
|
||||
//DASHBOARD Season 5 EXPORT EXCEL
|
||||
$routes->get("dashboard/downloadStaffAndProductPoliciesExcel", "ExcelExportController::downloadStaffAndProductPoliciesExcel");
|
||||
@ -204,7 +206,7 @@ $routes->get("processjob", "JobWorker::processJob");
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@ -32,70 +32,65 @@ class ExcelExportController extends ResourceController
|
||||
* @param string $totalValueCol Column letter for the total value (e.g., 'D' or 'F')
|
||||
* @return void
|
||||
*/
|
||||
private function streamExcelFile(
|
||||
array $header,
|
||||
array $data,
|
||||
string $title,
|
||||
string $fileName,
|
||||
string $totalLabelCol,
|
||||
string $totalValueCol
|
||||
): void
|
||||
private function streamExcelFile(array $header, array $data, string $title, string $fileName, bool $showTotal = true): void
|
||||
{
|
||||
// Ensure no output buffering is active before streaming the file
|
||||
while (ob_get_level() > 0) {
|
||||
ob_end_clean();
|
||||
}
|
||||
|
||||
// Create Spreadsheet
|
||||
$spreadsheet = new Spreadsheet();
|
||||
$spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
|
||||
$sheet = $spreadsheet->getActiveSheet();
|
||||
|
||||
// 1. Title (Merged across the header columns)
|
||||
// $lastCol = $sheet->getHighestColumn();
|
||||
$columnCount = count($header);
|
||||
$lastCol = Coordinate::stringFromColumnIndex($columnCount); // <--- MUST be ONLY 'Coordinate::'
|
||||
$sheet->mergeCells("A1:{$lastCol}1"); // Merges A1:E1
|
||||
$lastCol = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::stringFromColumnIndex($columnCount);
|
||||
$rowCount = count($data);
|
||||
|
||||
// $sheet->mergeCells("A1:{$lastCol}1");
|
||||
// 1. Title
|
||||
$sheet->mergeCells("A1:{$lastCol}1");
|
||||
$sheet->setCellValue('A1', $title);
|
||||
$sheet->getStyle('A1')->getFont()->setBold(true);
|
||||
$sheet->getStyle('A1')->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
|
||||
$sheet->getStyle('A1')->getFont()->setBold(true)->setSize(14);
|
||||
$sheet->getStyle('A1')->getAlignment()->setHorizontal('center');
|
||||
|
||||
// 2. Headers (Row 2)
|
||||
// $sheet->fromArray($header, NULL, 'A2')->getFont()->setBold(true);
|
||||
$headerRange = 'A2:' . $lastCol . '2';
|
||||
// 2. Headers
|
||||
$sheet->fromArray($header, NULL, 'A2');
|
||||
$sheet->getStyle($headerRange)->getFont()->setBold(true);
|
||||
$sheet->getStyle("A2:{$lastCol}2")->getFont()->setBold(true);
|
||||
$sheet->getStyle("A2:{$lastCol}2")->getFill()
|
||||
->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
|
||||
->getStartColor()->setARGB('F2F2F2');
|
||||
|
||||
// 3. Data (Starting from Row 3)
|
||||
// Note: The total row MUST be included in the $data array passed to this function.
|
||||
// 3. Data
|
||||
$sheet->fromArray($data, NULL, 'A3');
|
||||
|
||||
// 4. Total Row Styling
|
||||
// Total row number is the count of rows in the $data array (which includes the header, plus 2 for title/headers)
|
||||
$totalRowNumber = count($data) + 2;
|
||||
|
||||
// Apply bold formatting to the label and the sum
|
||||
$sheet->getStyle($totalLabelCol . $totalRowNumber . ':' . $totalValueCol . $totalRowNumber)->getFont()->setBold(true);
|
||||
|
||||
// Align the label to the right
|
||||
$sheet->getStyle($totalLabelCol . $totalRowNumber)->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT);
|
||||
// 4. Dynamic Total Row Styling
|
||||
if ($rowCount > 0 && $showTotal === true) {
|
||||
$totalRowNumber = $rowCount + 2;
|
||||
|
||||
// Auto-size columns for better presentation
|
||||
for ($col = 'A'; $col <= $lastCol; $col++) {
|
||||
// Bold the entire last row
|
||||
$sheet->getStyle("A{$totalRowNumber}:{$lastCol}{$totalRowNumber}")->getFont()->setBold(true);
|
||||
|
||||
// Find the second to last column letter for "Total:" alignment
|
||||
$labelColLetter = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::stringFromColumnIndex($columnCount - 1);
|
||||
|
||||
// Right-align the "Total:" label (usually second to last column)
|
||||
$sheet->getStyle($labelColLetter . $totalRowNumber)->getAlignment()->setHorizontal('right');
|
||||
|
||||
// Format the last column (the sum) as a number
|
||||
$sheet->getStyle($lastCol . $totalRowNumber)->getNumberFormat()->setFormatCode('#,##0.00');
|
||||
}
|
||||
|
||||
// 5. Auto-size
|
||||
for ($i = 1; $i <= $columnCount; $i++) {
|
||||
$col = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::stringFromColumnIndex($i);
|
||||
$sheet->getColumnDimension($col)->setAutoSize(true);
|
||||
}
|
||||
|
||||
// 5. HTTP Headers
|
||||
header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
|
||||
header("Content-Disposition: attachment; filename=\"{$fileName}\"");
|
||||
header("Cache-Control: max-age=0");
|
||||
|
||||
// 6. Output File
|
||||
$writer = new Xlsx($spreadsheet);
|
||||
$writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
|
||||
$writer->save('php://output');
|
||||
|
||||
return;
|
||||
exit();
|
||||
}
|
||||
|
||||
// 1) Broker generate the Excel file
|
||||
@ -134,9 +129,14 @@ class ExcelExportController extends ResourceController
|
||||
}
|
||||
|
||||
// Calculate and append total
|
||||
$grandTotal = array_sum(array_column($data, 13));
|
||||
$data[] = ['','','','','','','','','','','','','Total:', $grandTotal]; // Column C (index 2) is 'Total:', Column D (index 3) is the value
|
||||
|
||||
$lastColIndex = count($header) - 1; // Get index of the last column (Premium)
|
||||
$grandTotal = array_sum(array_column($data, $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
|
||||
$data[] = $totalRow;
|
||||
|
||||
$monthName = ($month === 'current') ? date('M_Y') : date('M_Y', strtotime('-1 month'));
|
||||
$brokerName = $data[0][10] ?? 'Broker';
|
||||
$cleanbrokerName = str_replace(' ', '_', strtolower($brokerName));
|
||||
@ -147,10 +147,10 @@ class ExcelExportController extends ResourceController
|
||||
$header,
|
||||
$data,
|
||||
"Broker Policies Details for {$monthName}",
|
||||
$fileName,
|
||||
'M', // Total Label Column (aligned right)
|
||||
'N' // Total Value Column (bold)
|
||||
$fileName,
|
||||
true // Pass 'true' to show/bold the total row
|
||||
);
|
||||
|
||||
|
||||
return;
|
||||
|
||||
@ -230,8 +230,14 @@ class ExcelExportController extends ResourceController
|
||||
throw new \RuntimeException('No policies found for this vehicle type...', 404);
|
||||
}
|
||||
|
||||
$grandTotal = array_sum(array_column($data, 13));
|
||||
$data[] = ['','','','','','','','','','','','','Total:',$grandTotal]; // Column C is 'Total:', Column D is the value
|
||||
// Calculate and append total
|
||||
$lastColIndex = count($header) - 1; // Get index of the last column (Premium)
|
||||
$grandTotal = array_sum(array_column($data, $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
|
||||
$data[] = $totalRow;
|
||||
|
||||
$monthName = ($month === 'current') ? date('M_Y') : date('M_Y', strtotime('-1 month'));
|
||||
$vehicleType = $data[0][10] ?? 'Vehicle';
|
||||
@ -244,10 +250,8 @@ class ExcelExportController extends ResourceController
|
||||
$data,
|
||||
"Vehicle Type Policies Details for {$monthName}",
|
||||
$fileName,
|
||||
'M', // Total Label Column
|
||||
'N' // Total Value Column
|
||||
true // This will ignore the bold/alignment logic for the last row
|
||||
);
|
||||
|
||||
return;
|
||||
} catch (\Throwable $e) {
|
||||
|
||||
@ -331,8 +335,14 @@ class ExcelExportController extends ResourceController
|
||||
throw new \RuntimeException('No policies found for this insurer for the specified month.', 404);
|
||||
}
|
||||
|
||||
$grandTotal = array_sum(array_column($data, 12));
|
||||
$data[] = ['','','','','','','','','','','','Total:',$grandTotal];
|
||||
// Calculate and append total
|
||||
$lastColIndex = count($header) - 1; // Get index of the last column (Premium)
|
||||
$grandTotal = array_sum(array_column($data, $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
|
||||
$data[] = $totalRow;
|
||||
|
||||
$monthName = ($month === 'current') ? date('M_Y') : date('M_Y', strtotime('-1 month'));
|
||||
$InsurerName = $data[0][7] ?? 'Insurer' ;
|
||||
@ -345,8 +355,7 @@ class ExcelExportController extends ResourceController
|
||||
$data,
|
||||
"Insurer Policies Details for {$monthName}",
|
||||
$fileName,
|
||||
'L', // Total Label Column
|
||||
'M' // Total Value Column
|
||||
true // This will ignore the bold/alignment logic for the last row
|
||||
);
|
||||
|
||||
return; // STOP CI4 rendering anything else
|
||||
@ -418,8 +427,14 @@ class ExcelExportController extends ResourceController
|
||||
throw new \RuntimeException('No low premium agents found...', 404);
|
||||
}
|
||||
|
||||
$grandTotal = array_sum(array_column($data, 13));
|
||||
$data[] = ['','','','','','','','','','','','','Total:', $grandTotal]; // Column E is 'Total:', Column F is the value
|
||||
// Calculate and append total
|
||||
$lastColIndex = count($header) - 1; // Get index of the last column (Premium)
|
||||
$grandTotal = array_sum(array_column($data, $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
|
||||
$data[] = $totalRow;
|
||||
|
||||
// Note: $month variable is undefined, assuming you want current month for filename
|
||||
$monthName = date('M_Y');
|
||||
@ -432,8 +447,7 @@ class ExcelExportController extends ResourceController
|
||||
$data,
|
||||
"Partners Low Premium Policy Details",
|
||||
$fileName,
|
||||
'M', // Total Label Column
|
||||
'N' // Total Value Column
|
||||
true // This will ignore the bold/alignment logic for the last row
|
||||
);
|
||||
|
||||
return;
|
||||
@ -477,7 +491,7 @@ class ExcelExportController extends ResourceController
|
||||
}
|
||||
}
|
||||
|
||||
// 5) AgentMonthly generate the Excel file
|
||||
// 5.1) AgentMonthly generate the Excel file
|
||||
public function downloadAgentMonthlyPoliciesExcel()
|
||||
{
|
||||
try{
|
||||
@ -496,7 +510,7 @@ class ExcelExportController extends ResourceController
|
||||
}
|
||||
|
||||
// Renamed helper function for consistency: getAgentMonthlyPoliciesData
|
||||
$data = $this->getAgentMonthlyPoliciesData($managerId, $agentId); // , $month);
|
||||
$data = $this->getMonthlyPoliciesData($managerId, $agentId); // , $month);
|
||||
$header = [
|
||||
'Received Date', 'Assigned To',
|
||||
'Insurer Name' ,'Insurer Short Name',
|
||||
@ -508,8 +522,14 @@ class ExcelExportController extends ResourceController
|
||||
throw new \RuntimeException('No policies found for this agent for the specified month.', 404);
|
||||
}
|
||||
|
||||
$grandTotal = array_sum(array_column($data, 12));
|
||||
$data[] = ['','','','','','','','','','','','Total:',$grandTotal]; // Column D is 'Total:', Column E is the value
|
||||
// Calculate and append total
|
||||
$lastColIndex = count($header) - 1; // Get index of the last column (Premium)
|
||||
$grandTotal = array_sum(array_column($data, $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
|
||||
$data[] = $totalRow;
|
||||
|
||||
// $monthName = ($month === 'current') ? date('M_Y') : date('M_Y', strtotime('-1 month'));
|
||||
$monthName = date('M Y') ;
|
||||
@ -523,10 +543,100 @@ class ExcelExportController extends ResourceController
|
||||
$data,
|
||||
"Partner Policies Details for {$monthName}",
|
||||
$fileName,
|
||||
'L', // Total Label Column
|
||||
'M' // Total Value Column
|
||||
true // This will ignore the bold/alignment logic for the last row
|
||||
);
|
||||
|
||||
|
||||
return;
|
||||
} 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);
|
||||
}
|
||||
}
|
||||
|
||||
// 5.2) Top 50 Agent the Excel file
|
||||
public function downloadT50AgentPoliciesExcel()
|
||||
{
|
||||
try{
|
||||
$managerId = $this->request->getGet('manager_id');
|
||||
|
||||
if (empty($managerId)) {
|
||||
|
||||
$msg = "Missing: ";
|
||||
$msg .= empty($managerId) ? "manager_id " : "";
|
||||
// $msg .= empty($month) ? "month " : "";
|
||||
$ref = ['debug_msg' => $msg];
|
||||
return $this->response->setJSON(['status' => 'error','code' => 400,'data' => [],'message' => 'Missing required parameters','ref' => $ref])->setStatusCode(200);
|
||||
}
|
||||
|
||||
// Renamed helper function for consistency: getAgentMonthlyPoliciesData
|
||||
$data = $this->getMonthlyPoliciesData($managerId, null);
|
||||
$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)) {
|
||||
throw new \RuntimeException('No policies found for this agent for the specified month.', 404);
|
||||
}
|
||||
|
||||
// Calculate and append total
|
||||
$lastColIndex = count($header) - 1; // Get index of the last column (Premium)
|
||||
$grandTotal = array_sum(array_column($data, $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
|
||||
$data[] = $totalRow;
|
||||
|
||||
$monthName = date('M Y') ;
|
||||
$fileName = 'Top_50_Partner_Policies_Details_' . $monthName . '.xlsx';
|
||||
|
||||
// --- CALL CENTRALIZED FUNCTION ---
|
||||
$this->streamExcelFile(
|
||||
$header,
|
||||
$data,
|
||||
"Top 50 Partner Policies Details - Monthly Report ".$monthName,
|
||||
$fileName,
|
||||
true // This will ignore the bold/alignment logic for the last row
|
||||
);
|
||||
|
||||
return;
|
||||
} catch (\Throwable $e) {
|
||||
|
||||
@ -605,9 +715,8 @@ class ExcelExportController extends ResourceController
|
||||
$header,
|
||||
$data,
|
||||
"Partners Without Policies (Last 10 Days)",
|
||||
$fileName,
|
||||
'C', // Total Label Column (aligned right)
|
||||
'D' // Total Value Column (bold)
|
||||
$fileName,
|
||||
false // This will ignore the bold/alignment logic for the last row
|
||||
);
|
||||
|
||||
return;
|
||||
@ -687,8 +796,14 @@ class ExcelExportController extends ResourceController
|
||||
throw new \RuntimeException('No policies found for the specified month.', 404);
|
||||
}
|
||||
|
||||
$grandTotal = array_sum(array_column($data, 14));
|
||||
$data[] = ['','','','','','','','','','','','','','Total:',$grandTotal]; // Column D is 'Total:', Column E is the value
|
||||
// Calculate and append total
|
||||
$lastColIndex = count($header) - 1; // Get index of the last column (Premium)
|
||||
$grandTotal = array_sum(array_column($data, $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
|
||||
$data[] = $totalRow;
|
||||
|
||||
|
||||
$monthName = ($month === 'current') ? date('M_Y') : date('M_Y', strtotime('-1 month'));
|
||||
@ -703,8 +818,7 @@ class ExcelExportController extends ResourceController
|
||||
$data,
|
||||
"Staff And Product Policies Details for {$monthName}",
|
||||
$fileName,
|
||||
'N', // Total Label Column
|
||||
'O' // Total Value Column
|
||||
true // This will ignore the bold/alignment logic for the last row
|
||||
);
|
||||
|
||||
return; // STOP CI4 rendering anything else
|
||||
@ -749,6 +863,121 @@ class ExcelExportController extends ResourceController
|
||||
}
|
||||
}
|
||||
|
||||
// 8 ZIP inside 3 Excel
|
||||
public function downloadExcelAsZIP($managerId = null)
|
||||
{
|
||||
// Ensure managerId is retrieved correctly if not passed as argument
|
||||
$managerId = $managerId ?? $this->request->getGet('manager_id');
|
||||
|
||||
if (empty($managerId)) {
|
||||
return $this->response->setJSON([
|
||||
'status' => 'error',
|
||||
'code' => 400,
|
||||
'message' => 'Missing required parameter: manager_id'
|
||||
]);
|
||||
}
|
||||
|
||||
// 1. Fetch Data First
|
||||
$monthlyData = $this->getMonthlyPoliciesData($managerId, null);
|
||||
$lowPremiumData = $this->getLowPremiumAgentData($managerId);
|
||||
$inactiveData = $this->getAgentsWithoutPoliciesData($managerId);
|
||||
|
||||
// 2. Add Total Rows where needed (Premium is usually the last index)
|
||||
if (!empty($monthlyData)) {
|
||||
$totalMonthly = array_sum(array_column($monthlyData, 12)); // Index 12 is 'premium_amount'
|
||||
$monthlyData[] = ['', '', '', '', '', '', '', '', '', '', '', 'Total:', $totalMonthly];
|
||||
}
|
||||
|
||||
if (!empty($lowPremiumData)) {
|
||||
$totalLow = array_sum(array_column($lowPremiumData, 13)); // Index 13 is 'premium_amount'
|
||||
$lowPremiumData[] = ['', '', '', '', '', '', '', '', '', '', '', '', 'Total:', $totalLow];
|
||||
}
|
||||
|
||||
// 3. Prepare Report Configuration
|
||||
$reports = [
|
||||
'Monthly_Policies_Details.xlsx' => ['data' => $monthlyData, 'header' => ['Received Date', 'Assigned To', 'Insurer', 'Short Name', 'Insured', 'Reg No', 'Mode', 'Plan', 'Agent', 'Code', 'Policy #', 'Issued Date', 'Premium'], 'title' => "Monthly Report",'showTotal' => true],
|
||||
'Low_Premium_Policies_Details.xlsx' => ['data' => $lowPremiumData, 'header' => ['Received Date', 'Assigned To', 'Insurer', 'Short Name', 'Insured', 'Reg No', 'Mode', 'Plan', 'Agent', 'Code', 'Status', 'Policy #', 'Issued Date', 'Premium'], 'title' => "Low Premium Report",'showTotal' => true],
|
||||
'Partners_Without_Policies_Details.xlsx' => ['data' => $inactiveData, 'header' => ['Partner Name', 'Partner Code', 'Email', 'Mobile'], 'title' => "Inactive Agents",'showTotal' => false]
|
||||
];
|
||||
|
||||
// 4. Initialize Zip
|
||||
$zipFileName = 'Agent_Reports_' . date('Y-m-d_H-i') . '.zip';
|
||||
$zipFilePath = tempnam(sys_get_temp_dir(), 'zip');
|
||||
|
||||
$zip = new \ZipArchive();
|
||||
if ($zip->open($zipFilePath, \ZipArchive::CREATE | \ZipArchive::OVERWRITE) === TRUE) {
|
||||
foreach ($reports as $name => $config) {
|
||||
$excelContent = $this->generateExcelBinary($config['header'], $config['data'], $config['title'],$config['showTotal']);
|
||||
$zip->addFromString($name, $excelContent);
|
||||
}
|
||||
$zip->close();
|
||||
}
|
||||
|
||||
// 5. Direct Download
|
||||
// Instead of creating a file on disk, we can send the ZIP data directly.
|
||||
// This avoids the "deleteFileAfterSend" error entirely.
|
||||
|
||||
$zipData = file_get_contents($zipFilePath); // Read the zip file into a variable
|
||||
unlink($zipFilePath); // Delete the temp file immediately
|
||||
|
||||
return $this->response->download($zipFileName, $zipData);
|
||||
}
|
||||
|
||||
|
||||
private function generateExcelBinary(array $header, array $data, string $title, bool $showTotal = true): string
|
||||
{
|
||||
$spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
|
||||
$sheet = $spreadsheet->getActiveSheet();
|
||||
|
||||
// 1. Calculate dimensions
|
||||
$columnCount = count($header);
|
||||
$lastCol = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::stringFromColumnIndex($columnCount);
|
||||
$rowCount = count($data);
|
||||
|
||||
// 2. Title Styling
|
||||
$sheet->mergeCells("A1:{$lastCol}1");
|
||||
$sheet->setCellValue('A1', $title);
|
||||
$sheet->getStyle('A1')->getFont()->setBold(true)->setSize(14);
|
||||
$sheet->getStyle('A1')->getAlignment()->setHorizontal('center');
|
||||
|
||||
// 3. Headers (Row 2)
|
||||
$sheet->fromArray($header, NULL, 'A2');
|
||||
$sheet->getStyle("A2:{$lastCol}2")->getFont()->setBold(true);
|
||||
$sheet->getStyle("A2:{$lastCol}2")->getFill()
|
||||
->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
|
||||
->getStartColor()->setARGB('F2F2F2'); // Light gray background
|
||||
|
||||
// 4. Data (Starting Row 3)
|
||||
$sheet->fromArray($data, NULL, 'A3');
|
||||
|
||||
// 5. Bold the Total Row (The last row of data)
|
||||
if ($rowCount > 0 && $showTotal === true) {
|
||||
$totalRowNumber = $rowCount + 2; // Row 1 (Title) + Row 2 (Header) + Data Rows
|
||||
$sheet->getStyle("A{$totalRowNumber}:{$lastCol}{$totalRowNumber}")->getFont()->setBold(true);
|
||||
|
||||
// Optional: Add a top border to the total row to make it look professional
|
||||
// $sheet->getStyle("A{$totalRowNumber}:{$lastCol}{$totalRowNumber}")->getBorders()->getTop()->setBorderStyle(\PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN);
|
||||
}
|
||||
|
||||
// 6. Auto-size Columns
|
||||
// Using column index to avoid issues with double-letter columns (e.g., AA, AB)
|
||||
for ($i = 1; $i <= $columnCount; $i++) {
|
||||
$colLetter = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::stringFromColumnIndex($i);
|
||||
$sheet->getColumnDimension($colLetter)->setAutoSize(true);
|
||||
}
|
||||
|
||||
// 7. Capture Binary Output
|
||||
$writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
|
||||
|
||||
// Use Output Buffering to grab the file content as a string
|
||||
ob_start();
|
||||
$writer->save('php://output');
|
||||
$excelBinary = ob_get_clean();
|
||||
|
||||
return $excelBinary;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Executes the detailed policy query and extracts the data for the spreadsheet.
|
||||
* @param string $managerId
|
||||
@ -1040,43 +1269,49 @@ class ExcelExportController extends ResourceController
|
||||
* @param string $month ('current' or 'previous')
|
||||
* @return array
|
||||
*/
|
||||
private function getAgentMonthlyPoliciesData($managerId, $AgentId): array
|
||||
private function getMonthlyPoliciesData($managerId, $AgentId): array
|
||||
{
|
||||
// --- Correction 1: Initialize Database Connection ---
|
||||
|
||||
$data = [];
|
||||
|
||||
try {
|
||||
$builder = $this->db->table('partner_policy pp');
|
||||
// Note: I removed 'broker_id' from SELECT as it's redundant in the Excel sheet details
|
||||
$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,pp.policy_number,DATE_FORMAT(pp.issued_date, "%d-%m-%Y") AS issued_date,pp.premium_amount');
|
||||
|
||||
// 1. Properly aligned Select Statement
|
||||
$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,
|
||||
pp.policy_number,
|
||||
DATE_FORMAT(pp.issued_date, "%d-%m-%Y") AS issued_date,
|
||||
pp.premium_amount
|
||||
');
|
||||
|
||||
// 2. Joins
|
||||
$builder->join('partner_agent pa', 'pp.agent_id = pa.id', 'inner');
|
||||
$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');
|
||||
$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');
|
||||
|
||||
|
||||
// 3. Where Conditions
|
||||
$builder->where('pp.manager_id', $managerId);
|
||||
$builder->where('pa.id', $AgentId);
|
||||
$builder->where('pp.policy_number IS NOT NULL');
|
||||
|
||||
// --- Correction 2: Use Robust Date Range Filtering ---
|
||||
|
||||
if ($AgentId) {
|
||||
$builder->where('pa.id', $AgentId);
|
||||
}
|
||||
|
||||
// Current Month Date Range Filter
|
||||
// if ($month === "current") {
|
||||
// // WHERE issued_date >= start_of_current_month AND issued_date < start_of_next_month
|
||||
$builder->where("pp.issued_date >= DATE_FORMAT(CURRENT_DATE(), '%Y-%m-01')", NULL, FALSE);
|
||||
@ -1087,19 +1322,24 @@ class ExcelExportController extends ResourceController
|
||||
// $builder->where("pp.issued_date >= DATE_FORMAT(DATE_SUB(CURRENT_DATE(), INTERVAL 1 MONTH), '%Y-%m-01')", NULL, FALSE);
|
||||
// $builder->where("pp.issued_date < DATE_FORMAT(CURRENT_DATE(), '%Y-%m-01')", NULL, FALSE);
|
||||
// }
|
||||
|
||||
|
||||
// 4. Order and Limit
|
||||
$builder->orderBy('pp.issued_date', 'DESC');
|
||||
|
||||
if (!$AgentId) {
|
||||
$builder->limit(50);
|
||||
}
|
||||
|
||||
// 5. Fetch and Restructure
|
||||
$results = $builder->get()->getResultArray();
|
||||
|
||||
// Restructure data for PhpSpreadsheet (2D array of values)
|
||||
|
||||
foreach ($results as $row) {
|
||||
// Using array_values ensures we return a indexed 2D array for PhpSpreadsheet
|
||||
$data[] = array_values($row);
|
||||
}
|
||||
|
||||
} catch (DatabaseException $e) {
|
||||
|
||||
} catch (\CodeIgniter\Database\Exceptions\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;
|
||||
}
|
||||
|
||||
|
||||
Loading…
Reference in New Issue
Block a user