FIX_export Last 2 api
This commit is contained in:
parent
adbedba07e
commit
dc2a945a06
@ -118,15 +118,16 @@ class ExcelExportController extends ResourceController
|
||||
$grandTotal = array_sum(array_column($data, 3));
|
||||
$data[] = ['','','Total:', $grandTotal]; // Column C (index 2) is 'Total:', Column D (index 3) is the value
|
||||
|
||||
$monthName = ($month === 'current') ? date('Ym') : date('Ym', strtotime('-1 month'));
|
||||
$monthName = ($month === 'current') ? date('M_Y') : date('M_Y', strtotime('-1 month'));
|
||||
$brokerName = $data[0][0] ?? 'Broker';
|
||||
$fileName = $brokerName . '_Policies_Details_' . $monthName . '.xlsx';
|
||||
$cleanbrokerName = str_replace(' ', '_', strtolower($brokerName));
|
||||
$fileName = $cleanbrokerName . '_Policies_Details_' . $monthName . '.xlsx';
|
||||
|
||||
// --- CALL CENTRALIZED FUNCTION ---
|
||||
$this->streamExcelFile(
|
||||
$header,
|
||||
$data,
|
||||
"Broker Policies Details for {$month}",
|
||||
"Broker Policies Details for {$monthName}",
|
||||
$fileName,
|
||||
'C', // Total Label Column (aligned right)
|
||||
'D' // Total Value Column (bold)
|
||||
@ -206,15 +207,16 @@ class ExcelExportController extends ResourceController
|
||||
$grandTotal = array_sum(array_column($data, 3));
|
||||
$data[] = ['','','Total:',$grandTotal]; // Column C is 'Total:', Column D is the value
|
||||
|
||||
$monthName = ($month === 'current') ? date('Ym') : date('Ym', strtotime('-1 month'));
|
||||
$monthName = ($month === 'current') ? date('M_Y') : date('M_Y', strtotime('-1 month'));
|
||||
$vehicleType = $data[0][0] ?? 'Vehicle';
|
||||
$fileName = $vehicleType . '_Policies_Details_' . $monthName . '.xlsx';
|
||||
$cleanVehicleType = str_replace(' ', '_', strtolower($vehicleType));
|
||||
$fileName = $cleanVehicleType . '_Policies_Details_' . $monthName . '.xlsx';
|
||||
|
||||
// --- CALL CENTRALIZED FUNCTION ---
|
||||
$this->streamExcelFile(
|
||||
$header,
|
||||
$data,
|
||||
"Vehicle Type Policies Details for {$month}",
|
||||
"Vehicle Type Policies Details for {$monthName}",
|
||||
$fileName,
|
||||
'C', // Total Label Column
|
||||
'D' // Total Value Column
|
||||
@ -298,60 +300,23 @@ class ExcelExportController extends ResourceController
|
||||
throw new \RuntimeException('No policies found for this insurer for the specified month.', 404);
|
||||
}
|
||||
|
||||
$grandTotal = 0;
|
||||
foreach ($data as $row) { $grandTotal += (float)$row[5]; }
|
||||
|
||||
// Create and append the "Total" row
|
||||
$totalRow = ['','','','','Total:',$grandTotal];
|
||||
$data[] = $totalRow;
|
||||
$grandTotal = array_sum(array_column($data, 5));
|
||||
$data[] = ['','','','','Total:',$grandTotal];
|
||||
|
||||
// Determine file name and date string
|
||||
$monthName = ($month === 'current') ? date('Ym') : date('Ym', strtotime('-1 month'));
|
||||
$InsurerName = $data[0][0];
|
||||
$monthName = ($month === 'current') ? date('M_Y') : date('M_Y', strtotime('-1 month'));
|
||||
$InsurerName = $data[0][0] ?? 'Insurer' ;
|
||||
$cleanInsurerName = str_replace(' ', '_', strtolower($InsurerName));
|
||||
$fileName = $cleanInsurerName . '_Policies_Details_' . $monthName . '.xlsx';
|
||||
|
||||
// 2. Prepare PhpSpreadsheet (assuming $spreadsheet, $writer, etc. are created here)
|
||||
while (ob_get_level() > 0) {
|
||||
ob_end_clean();
|
||||
}
|
||||
|
||||
// Create Spreadsheet
|
||||
$spreadsheet = new Spreadsheet();
|
||||
$sheet = $spreadsheet->getActiveSheet();
|
||||
|
||||
// Title
|
||||
$sheet->mergeCells('A1:G1');
|
||||
$sheet->setCellValue('A1', "Insurer Policies Details for $month");
|
||||
$sheet->getStyle('A1')->getAlignment()->setHorizontal('center');
|
||||
|
||||
// Headers
|
||||
$sheet->fromArray($header, NULL, 'A2');
|
||||
|
||||
// Data
|
||||
$sheet->fromArray($data, NULL, 'A3');
|
||||
|
||||
// 1. Define the target row number (Must be the first step!)
|
||||
$totalRowNumber = count($data) + 2;
|
||||
|
||||
// 2. Set the 'TOTAL:' label in Column F
|
||||
$sheet->setCellValue('E' . $totalRowNumber, 'TOTAL:');
|
||||
|
||||
// 3. Apply bold formatting to the label and the sum (Columns C and D)
|
||||
$sheet->getStyle('E' . $totalRowNumber . ':F' . $totalRowNumber)->getFont()->setBold(true);
|
||||
|
||||
// 4. Align the label to the right for a clean look next to the sum
|
||||
$sheet->getStyle('E' . $totalRowNumber)->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT);
|
||||
|
||||
// File Name
|
||||
$fileName = $InsurerName . '_Policies_Details_' . $monthName . '.xlsx';
|
||||
|
||||
// HTTP Headers
|
||||
header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
|
||||
header("Content-Disposition: attachment; filename=\"{$fileName}\"");
|
||||
header("Cache-Control: max-age=0");
|
||||
|
||||
// Output File
|
||||
$writer = new Xlsx($spreadsheet);
|
||||
$writer->save('php://output');
|
||||
// --- CALL CENTRALIZED FUNCTION ---
|
||||
$this->streamExcelFile(
|
||||
$header,
|
||||
$data,
|
||||
"Insurer Policies Details for {$monthName}",
|
||||
$fileName,
|
||||
'E', // Total Label Column
|
||||
'F' // Total Value Column
|
||||
);
|
||||
|
||||
return; // STOP CI4 rendering anything else
|
||||
|
||||
@ -399,7 +364,6 @@ class ExcelExportController extends ResourceController
|
||||
// 4) LowPremium generate the Excel file (Below 5OK)
|
||||
public function downloadLowPremiumAgentExcel()
|
||||
{
|
||||
echo "***";
|
||||
try{
|
||||
$managerId = $this->request->getGet('manager_id');
|
||||
|
||||
@ -506,15 +470,16 @@ class ExcelExportController extends ResourceController
|
||||
$grandTotal = array_sum(array_column($data, 4));
|
||||
$data[] = ['','','','Total:',$grandTotal]; // Column D is 'Total:', Column E is the value
|
||||
|
||||
$monthName = ($month === 'current') ? date('Ym') : date('Ym', strtotime('-1 month'));
|
||||
$monthName = ($month === 'current') ? date('M_Y') : date('M_Y', strtotime('-1 month'));
|
||||
$PartnerName = $data[0][0] ?? 'Partner';
|
||||
$fileName = $PartnerName . '_Policies_Details_' . $monthName . '.xlsx';
|
||||
$cleanPartnerName = str_replace(' ', '_', strtolower($PartnerName));
|
||||
$fileName = $cleanPartnerName . '_Policies_Details_' . $monthName . '.xlsx';
|
||||
|
||||
// --- CALL CENTRALIZED FUNCTION ---
|
||||
$this->streamExcelFile(
|
||||
$header,
|
||||
$data,
|
||||
"Partner Policies Details for {$month}",
|
||||
"Partner Policies Details for {$monthName}",
|
||||
$fileName,
|
||||
'D', // Total Label Column
|
||||
'E' // Total Value Column
|
||||
@ -561,78 +526,137 @@ class ExcelExportController extends ResourceController
|
||||
}
|
||||
}
|
||||
|
||||
// Function to generate the Excel file
|
||||
public function downloadStaffWiseProductPoliciesExcel()
|
||||
// 6) Agents who all are Without Policies generate the Excel file (last 10 days no Policies created by the agents)
|
||||
public function downloadAgentsWithoutPoliciesExcel()
|
||||
{
|
||||
try{
|
||||
$managerId = $this->request->getGet('manager_id');
|
||||
$brokerId = $this->request->getGet('broker_id');
|
||||
|
||||
if (empty($managerId)) {
|
||||
$msg = "Missing: ";
|
||||
$msg .= empty($managerId) ? "manager_id " : "";
|
||||
$ref = ['debug_msg' => $msg];
|
||||
// $ref = ['debug_msg' => 'Missing required parameters: manager_id, broker_id, and month must be provided.'];
|
||||
return $this->response->setJSON(['status' => 'error','code' => 400,'data' => [],'message' => 'Missing required parameters','ref' => $ref])->setStatusCode(200);
|
||||
}
|
||||
|
||||
$data = $this->getAgentsWithoutPoliciesData($managerId);
|
||||
$header = ['Partner Name', 'Partner Code', 'Email', 'Mobile'];
|
||||
|
||||
if (empty($data)) {
|
||||
throw new \RuntimeException('No Partners without policies found.', 404);
|
||||
}
|
||||
|
||||
// End Date: Today
|
||||
$endDate = date('Ymd');
|
||||
// Start Date: 9 days ago (10th day is today)
|
||||
$startDate = date('Ymd', strtotime('-9 days'));
|
||||
|
||||
// --- Filename Generation ---
|
||||
|
||||
$fileName = 'Partners_Without_Policies_' . $startDate . '_to_' . $endDate . '.xlsx';
|
||||
|
||||
// Example output: Agents_Without_Policies_20251206_to_20251215.xlsx
|
||||
|
||||
// --- CENTRALIZED CALL ---
|
||||
$this->streamExcelFile(
|
||||
$header,
|
||||
$data,
|
||||
"Partners Without Policies (Last 10 Days)",
|
||||
$fileName,
|
||||
'C', // Total Label Column (aligned right)
|
||||
'D' // Total Value Column (bold)
|
||||
);
|
||||
|
||||
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' => [],
|
||||
'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.';
|
||||
} else {
|
||||
$ref['message'] = 'An unexpected error occurred: ' . $e->getMessage();
|
||||
}
|
||||
|
||||
return $this->respond([
|
||||
'status' => 'error',
|
||||
'code' => $e->getCode() ?: 500,
|
||||
'data' => [],
|
||||
'ref' => $ref
|
||||
], 200);
|
||||
}
|
||||
}
|
||||
|
||||
// 7 Function to generate the Excel file
|
||||
public function downloadStaffAndProductPoliciesExcel()
|
||||
{
|
||||
try{
|
||||
$managerId = $this->request->getGet('manager_id');
|
||||
$executiveId = $this->request->getGet('sales_executive_id');
|
||||
$vehicleType = $this->request->getGet('vehicle_type');
|
||||
$month = $this->request->getGet('month');
|
||||
|
||||
// --- ADDED VALIDATION (Simplified logic for clarity) ---
|
||||
if (empty($managerId) || empty($brokerId) || empty($month)) {
|
||||
$ref = ['message' => 'Missing required parameters: manager_id, broker_id, and month must be provided.'];
|
||||
// Status code remains 200, but JSON code is 400 as per your preference
|
||||
return $this->response->setJSON([
|
||||
'status' => 'error',
|
||||
'code' => 400,
|
||||
'data' => [],
|
||||
'message' => 'Missing required parameters: manager_id, broker_id, and month must be provided.',
|
||||
'ref' => $ref
|
||||
])->setStatusCode(200);
|
||||
if (empty($managerId) || empty($executiveId) || empty($vehicleType) || empty($month)) {
|
||||
$msg = "Missing: ";
|
||||
$msg .= empty($managerId) ? "manager_id " : "";
|
||||
$msg .= empty($executiveId) ? "sales_executive_id " : "";
|
||||
$msg .= empty($vehicleType) ? "vehicle_type " : "";
|
||||
$msg .= empty($month) ? "month " : "";
|
||||
$ref = ['debug_msg' => $msg];
|
||||
// $ref = ['debug_msg' => 'Missing required parameters: manager_id, broker_id, and month must be provided.'];
|
||||
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->getStaffAndProductPoliciesExcel($managerId, $executiveId,$vehicleType, $month);
|
||||
$executiveName = $data[0][0] ?? 'Sales Executive';
|
||||
$vehicleType = $data[0][1] ?? 'Vehicle Type';
|
||||
// Define column headers
|
||||
$header = ['Broker Name', 'Issue Date', 'Policy Number', 'Premium Amount'];
|
||||
$header = ['Sales Executive Name', 'Vehicle Type', 'Policy Number','Issued Date', 'Premium Amount'];
|
||||
|
||||
// --- 1. MODIFIED LOGIC: Throw RuntimeException if no data ---
|
||||
if (empty($data)) {
|
||||
throw new \RuntimeException('No policies found for this broker for the specified month.', 404);
|
||||
throw new \RuntimeException('No policies found for the specified month.', 404);
|
||||
}
|
||||
|
||||
$grandTotal = 0;
|
||||
foreach ($data as $row) { $grandTotal += (float)$row[3]; }
|
||||
|
||||
// Create and append the "Total" row
|
||||
$totalRow = ['','','Total:',$grandTotal];
|
||||
$data[] = $totalRow;
|
||||
$grandTotal = array_sum(array_column($data, 4));
|
||||
$data[] = ['','','','Total:',$grandTotal]; // Column D is 'Total:', Column E is the value
|
||||
|
||||
// Determine file name and date string
|
||||
$monthName = ($month === 'current') ? date('Ym') : date('Ym', strtotime('-1 month'));
|
||||
$brokerName = $data[0][0];
|
||||
|
||||
$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';
|
||||
|
||||
// 2. Prepare PhpSpreadsheet (assuming $spreadsheet, $writer, etc. are created here)
|
||||
while (ob_get_level() > 0) {
|
||||
ob_end_clean();
|
||||
}
|
||||
|
||||
// Create Spreadsheet
|
||||
$spreadsheet = new Spreadsheet();
|
||||
$sheet = $spreadsheet->getActiveSheet();
|
||||
|
||||
// Title
|
||||
$sheet->mergeCells('A1:D1');
|
||||
$sheet->setCellValue('A1', "Broker Policies Details for $month");
|
||||
$sheet->getStyle('A1')->getAlignment()->setHorizontal('center');
|
||||
|
||||
// Headers
|
||||
$sheet->fromArray($header, NULL, 'A2');
|
||||
|
||||
// Data
|
||||
$sheet->fromArray($data, NULL, 'A3');
|
||||
|
||||
// File Name
|
||||
$fileName = $brokerName . '_Policies_Details_' . $monthName . '.xlsx';
|
||||
|
||||
// HTTP Headers
|
||||
header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
|
||||
header("Content-Disposition: attachment; filename=\"{$fileName}\"");
|
||||
header("Cache-Control: max-age=0");
|
||||
|
||||
// Output File
|
||||
$writer = new Xlsx($spreadsheet);
|
||||
$writer->save('php://output');
|
||||
// --- CALL CENTRALIZED FUNCTION ---
|
||||
$this->streamExcelFile(
|
||||
$header,
|
||||
$data,
|
||||
"Staff And Product Policies Details for {$monthName}",
|
||||
$fileName,
|
||||
'D', // Total Label Column
|
||||
'E' // Total Value Column
|
||||
);
|
||||
|
||||
return; // STOP CI4 rendering anything else
|
||||
|
||||
@ -675,401 +699,6 @@ class ExcelExportController extends ResourceController
|
||||
], 200);
|
||||
}
|
||||
}
|
||||
|
||||
public function downloadAgentsWithoutPoliciesExcel()
|
||||
{
|
||||
try{
|
||||
$managerId = $this->request->getGet('manager_id');
|
||||
|
||||
if (empty($managerId)) {
|
||||
// ... (Missing parameter error handling) ...
|
||||
}
|
||||
|
||||
$data = $this->getAgentsWithoutPoliciesData($managerId);
|
||||
$header = ['Partner Name', 'Partner Code', 'Email', 'Mobile'];
|
||||
|
||||
if (empty($data)) {
|
||||
throw new \RuntimeException('No agents without policies found.', 404);
|
||||
}
|
||||
|
||||
$monthName = date('Ym'); // Assuming current month is used for the file name
|
||||
$fileName = 'Agents_Without_Policies_Details_' . $monthName . '.xlsx';
|
||||
|
||||
// --- CALL CENTRALIZED FUNCTION (NO TOTAL PARAMETERS) ---
|
||||
$this->streamExcelFile(
|
||||
$header,
|
||||
$data,
|
||||
"Agents Without Policies",
|
||||
$fileName
|
||||
// Note: Omitting 'C', 'D' will prevent total row styling
|
||||
);
|
||||
|
||||
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' => [],
|
||||
'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.';
|
||||
} else {
|
||||
$ref['message'] = 'An unexpected error occurred: ' . $e->getMessage();
|
||||
}
|
||||
|
||||
return $this->respond([
|
||||
'status' => 'error',
|
||||
'code' => $e->getCode() ?: 500,
|
||||
'data' => [],
|
||||
'ref' => $ref
|
||||
], 200);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
// Function to generate the Excel file
|
||||
public function downloadAgentMonthlyPoliciesExcel_2()
|
||||
{
|
||||
try{
|
||||
$managerId = $this->request->getGet('manager_id');
|
||||
$brokerId = $this->request->getGet('broker_id');
|
||||
$month = $this->request->getGet('month');
|
||||
|
||||
// --- ADDED VALIDATION (Simplified logic for clarity) ---
|
||||
|
||||
|
||||
|
||||
$data = $this->getAgentMonthlyPoliciesExcel($managerId, $brokerId, $month);
|
||||
// Define column headers
|
||||
$header = ['Partner Name','Partner Code' ,'Issue Date', 'Policy Number', 'Premium Amount'];
|
||||
|
||||
|
||||
// --- 1. MODIFIED LOGIC: Throw RuntimeException if no data ---
|
||||
if (empty($data)) {
|
||||
throw new \RuntimeException('No policies found for this broker for the specified month.', 404);
|
||||
}
|
||||
|
||||
$grandTotal = 0;
|
||||
foreach ($data as $row) { $grandTotal += (float)$row[3]; }
|
||||
|
||||
// Create and append the "Total" row
|
||||
$totalRow = ['','','Total:',$grandTotal];
|
||||
$data[] = $totalRow;
|
||||
|
||||
// Determine file name and date string
|
||||
$monthName = ($month === 'current') ? date('Ym') : date('Ym', strtotime('-1 month'));
|
||||
$PartnerName = $data[0][0];
|
||||
|
||||
// 2. Prepare PhpSpreadsheet (assuming $spreadsheet, $writer, etc. are created here)
|
||||
while (ob_get_level() > 0) {
|
||||
ob_end_clean();
|
||||
}
|
||||
|
||||
// Create Spreadsheet
|
||||
$spreadsheet = new Spreadsheet();
|
||||
$sheet = $spreadsheet->getActiveSheet();
|
||||
|
||||
// Title
|
||||
$sheet->mergeCells('A1:F1');
|
||||
$sheet->setCellValue('A1', "Partner Policies Details for $month");
|
||||
$sheet->getStyle('A1')->getAlignment()->setHorizontal('center');
|
||||
|
||||
// Headers
|
||||
$sheet->fromArray($header, NULL, 'A2');
|
||||
|
||||
// Data
|
||||
$sheet->fromArray($data, NULL, 'A3');
|
||||
|
||||
// File Name
|
||||
$fileName = $PartnerName . '_Policies_Details_' . $monthName . '.xlsx';
|
||||
|
||||
// HTTP Headers
|
||||
header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
|
||||
header("Content-Disposition: attachment; filename=\"{$fileName}\"");
|
||||
header("Cache-Control: max-age=0");
|
||||
|
||||
// Output File
|
||||
$writer = new Xlsx($spreadsheet);
|
||||
$writer->save('php://output');
|
||||
|
||||
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' => [],
|
||||
'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.';
|
||||
} else {
|
||||
$ref['message'] = 'An unexpected error occurred: ' . $e->getMessage();
|
||||
}
|
||||
|
||||
return $this->respond([
|
||||
'status' => 'error',
|
||||
'code' => $e->getCode() ?: 500,
|
||||
'data' => [],
|
||||
'ref' => $ref
|
||||
], 200);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
// Function to generate the Excel file
|
||||
public function downloadAgentNoPolicyTimeRange_2()
|
||||
{
|
||||
try{
|
||||
$managerId = $this->request->getGet('manager_id');
|
||||
$brokerId = $this->request->getGet('broker_id');
|
||||
$month = $this->request->getGet('month');
|
||||
|
||||
// --- ADDED VALIDATION (Simplified logic for clarity) ---
|
||||
if (empty($managerId) || empty($brokerId) || empty($month)) {
|
||||
$ref = ['message' => 'Missing required parameters: manager_id, broker_id, and month must be provided.'];
|
||||
// Status code remains 200, but JSON code is 400 as per your preference
|
||||
return $this->response->setJSON([
|
||||
'status' => 'error',
|
||||
'code' => 400,
|
||||
'data' => [],
|
||||
'ref' => $ref
|
||||
])->setStatusCode(200);
|
||||
}
|
||||
|
||||
$data = $this->getBrokerPoliciesData($managerId, $brokerId, $month);
|
||||
// Define column headers
|
||||
$header = ['Broker Name', 'Issue Date', 'Policy Number', 'Premium Amount'];
|
||||
|
||||
// --- 1. MODIFIED LOGIC: Throw RuntimeException if no data ---
|
||||
if (empty($data)) {
|
||||
throw new \RuntimeException('No policies found for this broker for the specified month.', 404);
|
||||
}
|
||||
|
||||
$grandTotal = 0;
|
||||
foreach ($data as $row) { $grandTotal += (float)$row[3]; }
|
||||
|
||||
// Create and append the "Total" row
|
||||
$totalRow = ['','','Total:',$grandTotal];
|
||||
$data[] = $totalRow;
|
||||
|
||||
// Determine file name and date string
|
||||
$monthName = ($month === 'current') ? date('Ym') : date('Ym', strtotime('-1 month'));
|
||||
$brokerName = $data[0][0];
|
||||
|
||||
// 2. Prepare PhpSpreadsheet (assuming $spreadsheet, $writer, etc. are created here)
|
||||
while (ob_get_level() > 0) {
|
||||
ob_end_clean();
|
||||
}
|
||||
|
||||
// Create Spreadsheet
|
||||
$spreadsheet = new Spreadsheet();
|
||||
$sheet = $spreadsheet->getActiveSheet();
|
||||
|
||||
// Title
|
||||
$sheet->mergeCells('A1:D1');
|
||||
$sheet->setCellValue('A1', "Broker Policies Details for $month");
|
||||
$sheet->getStyle('A1')->getAlignment()->setHorizontal('center');
|
||||
|
||||
// Headers
|
||||
$sheet->fromArray($header, NULL, 'A2');
|
||||
|
||||
// Data
|
||||
$sheet->fromArray($data, NULL, 'A3');
|
||||
|
||||
// File Name
|
||||
$fileName = $brokerName . '_Policies_Details_' . $monthName . '.xlsx';
|
||||
|
||||
// HTTP Headers
|
||||
header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
|
||||
header("Content-Disposition: attachment; filename=\"{$fileName}\"");
|
||||
header("Cache-Control: max-age=0");
|
||||
|
||||
// Output File
|
||||
$writer = new Xlsx($spreadsheet);
|
||||
$writer->save('php://output');
|
||||
|
||||
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' => [],
|
||||
'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.';
|
||||
} else {
|
||||
$ref['message'] = 'An unexpected error occurred: ' . $e->getMessage();
|
||||
}
|
||||
|
||||
return $this->respond([
|
||||
'status' => 'error',
|
||||
'code' => $e->getCode() ?: 500,
|
||||
'data' => [],
|
||||
'ref' => $ref
|
||||
], 200);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
// Function to generate the Excel file
|
||||
public function downloadBrokerPoliciesExcel_agentBelow50tPremiumTimeRange_2()
|
||||
{
|
||||
try{
|
||||
$managerId = $this->request->getGet('manager_id');
|
||||
$brokerId = $this->request->getGet('broker_id');
|
||||
$month = $this->request->getGet('month');
|
||||
|
||||
// --- ADDED VALIDATION (Simplified logic for clarity) ---
|
||||
if (empty($managerId) || empty($brokerId) || empty($month)) {
|
||||
$ref = ['message' => 'Missing required parameters: manager_id, broker_id, and month must be provided.'];
|
||||
// Status code remains 200, but JSON code is 400 as per your preference
|
||||
return $this->response->setJSON([
|
||||
'status' => 'error',
|
||||
'code' => 400,
|
||||
'data' => [],
|
||||
'ref' => $ref
|
||||
])->setStatusCode(200);
|
||||
}
|
||||
|
||||
$data = $this->getBrokerPoliciesData($managerId, $brokerId, $month);
|
||||
// Define column headers
|
||||
$header = ['Broker Name', 'Issue Date', 'Policy Number', 'Premium Amount'];
|
||||
|
||||
$grandTotal = 0;
|
||||
foreach ($data as $row) { $grandTotal += (float)$row[3]; }
|
||||
|
||||
// Create and append the "Total" row
|
||||
$totalRow = ['','','Total:',$grandTotal];
|
||||
$data[] = $totalRow;
|
||||
|
||||
// --- 1. MODIFIED LOGIC: Throw RuntimeException if no data ---
|
||||
if (empty($data)) {
|
||||
throw new \RuntimeException('No policies found for this broker for the specified month.', 404);
|
||||
}
|
||||
|
||||
// Determine file name and date string
|
||||
$monthName = ($month === 'current') ? date('Ym') : date('Ym', strtotime('-1 month'));
|
||||
$brokerName = $data[0][0];
|
||||
|
||||
// 2. Prepare PhpSpreadsheet (assuming $spreadsheet, $writer, etc. are created here)
|
||||
while (ob_get_level() > 0) {
|
||||
ob_end_clean();
|
||||
}
|
||||
|
||||
// Create Spreadsheet
|
||||
$spreadsheet = new Spreadsheet();
|
||||
$sheet = $spreadsheet->getActiveSheet();
|
||||
|
||||
// Title
|
||||
$sheet->mergeCells('A1:D1');
|
||||
$sheet->setCellValue('A1', "Broker Policies Details for $month");
|
||||
$sheet->getStyle('A1')->getAlignment()->setHorizontal('center');
|
||||
|
||||
// Headers
|
||||
$sheet->fromArray($header, NULL, 'A2');
|
||||
|
||||
// Data
|
||||
$sheet->fromArray($data, NULL, 'A3');
|
||||
|
||||
// File Name
|
||||
$fileName = $brokerName . '_Policies_Details_' . $monthName . '.xlsx';
|
||||
|
||||
// HTTP Headers
|
||||
header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
|
||||
header("Content-Disposition: attachment; filename=\"{$fileName}\"");
|
||||
header("Cache-Control: max-age=0");
|
||||
|
||||
// Output File
|
||||
$writer = new Xlsx($spreadsheet);
|
||||
$writer->save('php://output');
|
||||
|
||||
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' => [],
|
||||
'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.';
|
||||
} else {
|
||||
$ref['message'] = 'An unexpected error occurred: ' . $e->getMessage();
|
||||
}
|
||||
|
||||
return $this->respond([
|
||||
'status' => 'error',
|
||||
'code' => $e->getCode() ?: 500,
|
||||
'data' => [],
|
||||
'ref' => $ref
|
||||
], 200);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Executes the detailed policy query and extracts the data for the spreadsheet.
|
||||
@ -1124,8 +753,6 @@ class ExcelExportController extends ResourceController
|
||||
return $data;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Executes the detailed policy query and extracts the data for the spreadsheet.
|
||||
* @param string $managerId
|
||||
@ -1177,7 +804,6 @@ class ExcelExportController extends ResourceController
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Executes the detailed policy query and extracts the data for the spreadsheet.
|
||||
@ -1234,13 +860,12 @@ class ExcelExportController extends ResourceController
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Executes the detailed policy query and extracts the data for the spreadsheet.
|
||||
* @param string $managerId
|
||||
* @param int $brokerId
|
||||
* @param int $executiveId
|
||||
* @param string $vehicleType
|
||||
* @param string $month ('current' or 'previous')
|
||||
* @return array
|
||||
*/
|
||||
@ -1359,39 +984,31 @@ class ExcelExportController extends ResourceController
|
||||
*/
|
||||
private function getAgentsWithoutPoliciesData($managerId): array
|
||||
{
|
||||
|
||||
// --- Correction 1: Initialize Database Connection ---
|
||||
|
||||
$data = [];
|
||||
|
||||
try {
|
||||
$builder = $this->db->table('partner_agent pa');
|
||||
// Note: I removed 'broker_id' from SELECT as it's redundant in the Excel sheet details
|
||||
$builder->select("pa.name AS agent_name,pa.agent_code,pa.email,pa.mobile");
|
||||
$builder->select('pa.name AS agent_name, pa.agent_code, pa.email, pa.mobile');
|
||||
|
||||
$builder->join(
|
||||
'partner_policy pp',
|
||||
"pa.id = pp.agent_id AND pp.issued_date >= DATE_SUB(CURRENT_TIMESTAMP(), INTERVAL 10 DAY)",
|
||||
'pa.id = pp.agent_id AND pp.issued_date >= DATE_SUB(CURRENT_TIMESTAMP(), INTERVAL 10 DAY)',
|
||||
'left'
|
||||
);
|
||||
|
||||
// Broker and Manager Filter
|
||||
$builder->where('pp.manager_id', $managerId);
|
||||
$builder->where('pp.id', null); // No policy in last 10 days
|
||||
$builder->where('pa.manager_id', $managerId);
|
||||
$builder->where('pp.id IS NULL', null, false);
|
||||
|
||||
$builder->orderBy('pa.name', 'ASC');
|
||||
// echo $builder->getCompiledSelect(); die;
|
||||
|
||||
$results = $builder->get()->getResultArray();
|
||||
|
||||
|
||||
// Restructure data for PhpSpreadsheet (2D array of values)
|
||||
|
||||
foreach ($results as $row) {
|
||||
$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;
|
||||
throw $e;
|
||||
}
|
||||
|
||||
return $data;
|
||||
|
||||
Loading…
Reference in New Issue
Block a user