1189 lines
55 KiB
PHP
1189 lines
55 KiB
PHP
<?php
|
|
|
|
namespace App\Controllers;
|
|
|
|
use CodeIgniter\RESTful\ResourceController;
|
|
|
|
use PhpOffice\PhpSpreadsheet\Spreadsheet;
|
|
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
|
|
use PhpOffice\PhpSpreadsheet\Style\Border;
|
|
use PhpOffice\PhpSpreadsheet\Cell\Coordinate; // <--- THIS MUST BE HERE
|
|
use PhpOffice\PhpSpreadsheet\Style\Alignment;
|
|
|
|
class ExcelExportController extends ResourceController
|
|
{
|
|
protected $db;
|
|
|
|
public function __construct()
|
|
{
|
|
$this->db = \Config\Database::connect();
|
|
}
|
|
|
|
|
|
/**
|
|
* Centralized function to create the spreadsheet, apply styling,
|
|
* set headers, and stream the file output.
|
|
*
|
|
* @param array $header Column headers (1D array)
|
|
* @param array $data Policy data including the total row (2D array)
|
|
* @param string $title Spreadsheet title
|
|
* @param string $fileName Output file name
|
|
* @param string $totalLabelCol Column letter for the 'TOTAL:' label (e.g., 'C' or 'E')
|
|
* @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
|
|
{
|
|
// Ensure no output buffering is active before streaming the file
|
|
while (ob_get_level() > 0) {
|
|
ob_end_clean();
|
|
}
|
|
|
|
// Create Spreadsheet
|
|
$spreadsheet = new 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
|
|
|
|
// $sheet->mergeCells("A1:{$lastCol}1");
|
|
$sheet->setCellValue('A1', $title);
|
|
$sheet->getStyle('A1')->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
|
|
|
|
// 2. Headers (Row 2)
|
|
$sheet->fromArray($header, NULL, 'A2');
|
|
|
|
// 3. Data (Starting from Row 3)
|
|
// Note: The total row MUST be included in the $data array passed to this function.
|
|
$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);
|
|
|
|
// Auto-size columns for better presentation
|
|
for ($col = 'A'; $col <= $lastCol; $col++) {
|
|
$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->save('php://output');
|
|
|
|
return;
|
|
}
|
|
|
|
// 1) Broker generate the Excel file
|
|
public function downloadBrokerPoliciesExcel()
|
|
{
|
|
try{
|
|
$managerId = $this->request->getGet('manager_id');
|
|
$brokerId = $this->request->getGet('broker_id');
|
|
$month = $this->request->getGet('month');
|
|
|
|
if (empty($managerId) || empty($brokerId) || empty($month)) {
|
|
|
|
$msg = "Missing: ";
|
|
$msg .= empty($managerId) ? "manager_id " : "";
|
|
$msg .= empty($brokerId) ? "broker_id " : "";
|
|
$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);
|
|
|
|
$header = ['Received Date',
|
|
'Assigned To_name',
|
|
'Partner Name' , 'Partner Code',
|
|
'Insurer Name' ,'Insurer Short Name',
|
|
'Insured Name',
|
|
'Vehicle Number',
|
|
'Payment Mode',
|
|
'Plan Type','Broker Name', 'Issue Date', 'Policy Number', 'Premium Amount'];
|
|
|
|
|
|
|
|
if (empty($data)) {
|
|
throw new \RuntimeException('No policies found...', 404);
|
|
}
|
|
|
|
// 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
|
|
|
|
$monthName = ($month === 'current') ? date('M_Y') : date('M_Y', strtotime('-1 month'));
|
|
$brokerName = $data[0][10] ?? 'Broker';
|
|
$cleanbrokerName = str_replace(' ', '_', strtolower($brokerName));
|
|
$fileName = $cleanbrokerName . '_Policies_Details_' . $monthName . '.xlsx';
|
|
|
|
// --- CALL CENTRALIZED FUNCTION ---
|
|
$this->streamExcelFile(
|
|
$header,
|
|
$data,
|
|
"Broker Policies Details for {$monthName}",
|
|
$fileName,
|
|
'M', // Total Label Column (aligned right)
|
|
'N' // 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['debug_msg'] = '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['debug_msg'] = 'Database Error Occurred: ' . $e->getMessage();
|
|
$message = 'Database Error Occurred.';
|
|
} else {
|
|
$ref['debug_msg'] = 'An unexpected error occurred: ' . $e->getMessage();
|
|
$message = 'Something went wrong. Please try again later.';
|
|
}
|
|
|
|
return $this->respond([
|
|
'status' => 'error',
|
|
'code' => 500,
|
|
'data' => [],
|
|
'message'=> $message,
|
|
'ref' => $ref
|
|
], 200);
|
|
}
|
|
}
|
|
|
|
|
|
// 2) Product generate the Excel file
|
|
public function downloadProductPoliciesExcel()
|
|
{
|
|
try{
|
|
$managerId = $this->request->getGet('manager_id');
|
|
$vehicleType = $this->request->getGet('vehicle_type');
|
|
$month = $this->request->getGet('month');
|
|
|
|
if (empty($managerId) || empty($vehicleType) || empty($month)) {
|
|
|
|
|
|
$msg = "Missing: ";
|
|
$msg .= empty($managerId) ? "manager_id " : "";
|
|
$msg .= empty($brokerId) ? "broker_id " : "";
|
|
$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->getProductPoliciesData($managerId, $vehicleType, $month);
|
|
// $header = ['Vehicle Type', 'Issue Date', 'Policy Number', 'Premium Amount'];
|
|
$header = ['Received Date',
|
|
'Assigned To_name',
|
|
'Partner Name' , 'Partner Code',
|
|
'Insurer Name' ,'Insurer Short Name',
|
|
'Insured Name',
|
|
'Vehicle Number',
|
|
'Payment Mode',
|
|
'Plan Type','Vehicle Type', 'Issue Date', 'Policy Number', 'Premium Amount'];
|
|
|
|
if (empty($data)) {
|
|
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
|
|
|
|
$monthName = ($month === 'current') ? date('M_Y') : date('M_Y', strtotime('-1 month'));
|
|
$vehicleType = $data[0][0] ?? 'Vehicle';
|
|
$cleanVehicleType = str_replace(' ', '_', strtolower($vehicleType));
|
|
$fileName = $cleanVehicleType . '_Policies_Details_' . $monthName . '.xlsx';
|
|
|
|
// --- CALL CENTRALIZED FUNCTION ---
|
|
$this->streamExcelFile(
|
|
$header,
|
|
$data,
|
|
"Vehicle Type Policies Details for {$monthName}",
|
|
$fileName,
|
|
'M', // Total Label Column
|
|
'N' // Total Value Column
|
|
);
|
|
|
|
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['debug_msg'] = '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['debug_msg'] = 'Database Error Occurred: ' . $e->getMessage();
|
|
$message = 'Database Error Occurred.';
|
|
} else {
|
|
$ref['debug_msg'] = 'An unexpected error occurred: ' . $e->getMessage();
|
|
$message = 'Something went wrong. Please try again later.';
|
|
}
|
|
|
|
return $this->respond([
|
|
'status' => 'error',
|
|
'code' => 500,
|
|
'data' => [],
|
|
'message'=> $message,
|
|
'ref' => $ref
|
|
], 200);
|
|
}
|
|
}
|
|
|
|
|
|
|
|
// 3) Insurer generate the Excel file
|
|
public function downloadInsurerPoliciesExcel()
|
|
{
|
|
try{
|
|
$managerId = $this->request->getGet('manager_id');
|
|
$insurerId = $this->request->getGet('insurer_id');
|
|
$month = $this->request->getGet('month');
|
|
|
|
// --- ADDED VALIDATION (Simplified logic for clarity) ---
|
|
if (empty($managerId) || empty($insurerId) || empty($month)) {
|
|
$msg = "Missing: ";
|
|
$msg .= empty($managerId) ? "manager_id " : "";
|
|
$msg .= empty($insurerId) ? "insurer_id " : "";
|
|
$msg .= empty($month) ? "month " : "";
|
|
$ref = ['debug_msg' => $msg];
|
|
// 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',
|
|
'ref' => $ref
|
|
])->setStatusCode(200);
|
|
}
|
|
|
|
$data = $this->getInsurerPoliciesData($managerId, $insurerId, $month);
|
|
|
|
// Define column headers
|
|
$header = ['Received Date',
|
|
'Assigned To',
|
|
'Partner Name' , 'Partner Code',
|
|
'Vehicle Number',
|
|
'Payment Mode',
|
|
'Plan Type','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);
|
|
}
|
|
|
|
$grandTotal = array_sum(array_column($data, 12));
|
|
$data[] = ['','','','','','','','','','','','Total:',$grandTotal];
|
|
|
|
$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';
|
|
|
|
// --- CALL CENTRALIZED FUNCTION ---
|
|
$this->streamExcelFile(
|
|
$header,
|
|
$data,
|
|
"Insurer Policies Details for {$monthName}",
|
|
$fileName,
|
|
'L', // Total Label Column
|
|
'M' // Total Value Column
|
|
);
|
|
|
|
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['debug_msg'] = '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['debug_msg'] = 'Database Error Occurred: ' . $e->getMessage();
|
|
$message = 'Database Error Occurred.';
|
|
} else {
|
|
$ref['debug_msg'] = 'An unexpected error occurred: ' . $e->getMessage();
|
|
$message = 'Something went wrong. Please try again later.';
|
|
}
|
|
|
|
return $this->respond([
|
|
'status' => 'error',
|
|
'code' => 500,
|
|
'data' => [],
|
|
'message'=> $message,
|
|
'ref' => $ref
|
|
], 200);
|
|
}
|
|
}
|
|
|
|
|
|
// 4) LowPremium generate the Excel file (Below 5OK)
|
|
public function downloadLowPremiumAgentExcel()
|
|
{
|
|
try{
|
|
$managerId = $this->request->getGet('manager_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->getLowPremiumAgentData($managerId);
|
|
$header = ['Partner Name', 'Partner Code','Partner Status' ,'Policy Number','Issued Date', 'Premium Amount'];
|
|
|
|
if (empty($data)) {
|
|
throw new \RuntimeException('No low premium agents found...', 404);
|
|
}
|
|
|
|
$grandTotal = array_sum(array_column($data, 5));
|
|
$data[] = ['','','','','Total:', $grandTotal]; // Column E is 'Total:', Column F is the value
|
|
|
|
// Note: $month variable is undefined, assuming you want current month for filename
|
|
$monthName = date('Ym');
|
|
$PartnerName = $data[0][0] ?? 'Partner';
|
|
$fileName = $PartnerName . '_Low_Premium_Details_' . $monthName . '.xlsx';
|
|
|
|
// --- CALL CENTRALIZED FUNCTION ---
|
|
$this->streamExcelFile(
|
|
$header,
|
|
$data,
|
|
"Partners Low Premium Policy Details",
|
|
$fileName,
|
|
'E', // Total Label Column
|
|
'F' // Total Value Column
|
|
);
|
|
|
|
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['debug_msg'] = '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['debug_msg'] = 'Database Error Occurred: ' . $e->getMessage();
|
|
$message = 'Database Error Occurred.';
|
|
} else {
|
|
$ref['debug_msg'] = 'An unexpected error occurred: ' . $e->getMessage();
|
|
$message = 'Something went wrong. Please try again later.';
|
|
}
|
|
|
|
return $this->respond([
|
|
'status' => 'error',
|
|
'code' => 500,
|
|
'data' => [],
|
|
'message'=> $message,
|
|
'ref' => $ref
|
|
], 200);
|
|
}
|
|
}
|
|
|
|
// 5) AgentMonthly generate the Excel file
|
|
public function downloadAgentMonthlyPoliciesExcel()
|
|
{
|
|
try{
|
|
$managerId = $this->request->getGet('manager_id');
|
|
$agentId = $this->request->getGet('agent_id');
|
|
// $month = $this->request->getGet('month');
|
|
|
|
if (empty($managerId) || empty($agentId)) {
|
|
|
|
$msg = "Missing: ";
|
|
$msg .= empty($managerId) ? "manager_id " : "";
|
|
$msg .= empty($agentId) ? "agent_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->getAgentMonthlyPoliciesData($managerId, $agentId); // , $month);
|
|
$header = ['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);
|
|
}
|
|
|
|
$grandTotal = array_sum(array_column($data, 4));
|
|
$data[] = ['','','','Total:',$grandTotal]; // Column D is 'Total:', Column E is the value
|
|
|
|
// $monthName = ($month === 'current') ? date('M_Y') : date('M_Y', strtotime('-1 month'));
|
|
$monthName = date('M_Y') ;
|
|
$PartnerName = $data[0][0] ?? 'Partner';
|
|
$cleanPartnerName = str_replace(' ', '_', strtolower($PartnerName));
|
|
$fileName = $cleanPartnerName . '_Policies_Details_' . $monthName . '.xlsx';
|
|
|
|
// --- CALL CENTRALIZED FUNCTION ---
|
|
$this->streamExcelFile(
|
|
$header,
|
|
$data,
|
|
"Partner Policies Details for {$monthName}",
|
|
$fileName,
|
|
'D', // Total Label Column
|
|
'E' // Total Value Column
|
|
);
|
|
|
|
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);
|
|
}
|
|
}
|
|
|
|
// 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');
|
|
|
|
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($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->getStaffAndProductPoliciesExcel($managerId, $executiveId,$vehicleType, $month);
|
|
$executiveName = $data[0][11] ?? 'Sales Executive';
|
|
$vehicleType = $data[0][12] ?? 'Vehicle Type';
|
|
// Define column headers
|
|
|
|
$header = ['Received Date',
|
|
'Assigned To_name',
|
|
'Partner Name' , 'Partner Code',
|
|
'Insurer Name' ,'Insurer Short Name',
|
|
'Insured Name',
|
|
'Vehicle Number',
|
|
'Payment Mode',
|
|
'Plan Type',
|
|
'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 the specified month.', 404);
|
|
}
|
|
|
|
$grandTotal = array_sum(array_column($data, 14));
|
|
$data[] = ['','','','','','','','','','','','','','Total:',$grandTotal]; // Column D is 'Total:', Column E is the value
|
|
|
|
|
|
$monthName = ($month === 'current') ? date('M_Y') : date('M_Y', strtotime('-1 month'));
|
|
|
|
$cleanExecutiveName = str_replace(' ', '_', strtolower($executiveName));
|
|
$cleanVehicleType = str_replace(' ', '_', strtolower($vehicleType));
|
|
$fileName = $cleanExecutiveName . '_' . $cleanVehicleType . '_Policies_Details_' . $monthName . '.xlsx';
|
|
|
|
// --- CALL CENTRALIZED FUNCTION ---
|
|
$this->streamExcelFile(
|
|
$header,
|
|
$data,
|
|
"Staff And Product Policies Details for {$monthName}",
|
|
$fileName,
|
|
'N', // Total Label Column
|
|
'O' // Total Value Column
|
|
);
|
|
|
|
return; // STOP CI4 rendering anything else
|
|
|
|
} catch (\Throwable $e) {
|
|
|
|
// ... (Your error handling remains the same) ...
|
|
$ref = [];
|
|
// Case 1: No Data Found (Soft Success JSON)
|
|
if ($e instanceof \RuntimeException && $e->getCode() === 404) {
|
|
$ref['message'] = 'No Data Found';
|
|
return $this->respond([
|
|
'status' => 'success',
|
|
'code' => 200,
|
|
'data' => [],
|
|
'message' => 'No Data Found',
|
|
'ref' => $ref
|
|
], 200);
|
|
}
|
|
|
|
// Case 2: Database or Other Error (Error JSON)
|
|
$isDbError = $e instanceof \CodeIgniter\Database\Exceptions\DatabaseException
|
|
|| $e instanceof \mysqli_sql_exception
|
|
|| $e instanceof \PDOException;
|
|
|
|
if ($isDbError) {
|
|
$ref['debug_info'] = $e->getFile() . " / LN : " . $e->getLine();
|
|
$ref['message'] = 'Database Error Occurred.';
|
|
$message = 'Database Error Occurred.';
|
|
} else {
|
|
$ref['message'] = 'An unexpected error occurred: ' . $e->getMessage();
|
|
$message = 'An unexpected error occurred: ' . $e->getMessage();
|
|
}
|
|
|
|
return $this->respond([
|
|
'status' => 'error',
|
|
'code' => 500,
|
|
'data' => [],
|
|
'message'=> $message,
|
|
'ref' => $ref
|
|
], 200);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Executes the detailed policy query and extracts the data for the spreadsheet.
|
|
* @param string $managerId
|
|
* @param int $brokerId
|
|
* @param string $month ('current' or 'previous')
|
|
* @return array
|
|
*/
|
|
private function getBrokerPoliciesData($managerId, $brokerId, $month): 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,
|
|
A.name as agent_name, A.agent_code,
|
|
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,
|
|
pb.name AS broker_name, DATE_FORMAT(pp.issued_date, "%d-%m-%Y") AS issued_date,pp.policy_number, pp.premium_amount');
|
|
$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_agent A', 'A.id = pe.agent_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');
|
|
|
|
// --- Correction 2: Use Robust Date Range Filtering ---
|
|
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);
|
|
$builder->where("pp.issued_date < DATE_FORMAT(DATE_ADD(CURRENT_DATE(), INTERVAL 1 MONTH), '%Y-%m-01')", NULL, FALSE);
|
|
}
|
|
else if ($month === "previous") {
|
|
// WHERE issued_date >= start_of_previous_month AND issued_date < start_of_current_month
|
|
$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);
|
|
}
|
|
|
|
// Broker and Manager Filter
|
|
$builder->where('pp.manager_id', $managerId);
|
|
$builder->where('pb.id', $brokerId);
|
|
$builder->orderBy('pp.issued_date', 'DESC');
|
|
|
|
$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.
|
|
* @param string $managerId
|
|
* @param string $vehicleType
|
|
* @param string $month ('current' or 'previous')
|
|
* @return array
|
|
*/
|
|
private function getProductPoliciesData($managerId, $vehicleType, $month): 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,
|
|
A.name as agent_name, A.agent_code,
|
|
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,
|
|
pp.vehicle_type, DATE_FORMAT(pp.issued_date, "%d-%m-%Y") AS issued_date,pp.policy_number, pp.premium_amount');
|
|
|
|
$builder->join('partner_enquiry pe', 'pe.id = pp.enquiry_id', 'left');
|
|
$builder->join('partner_quotation Q', 'Q.enquiry_id = pe.id', 'left');
|
|
$builder->join('partner_payment_mode_master pm', 'pm.id = Q.payment_mode_id', 'left');
|
|
$builder->join('partner_agent A', 'A.id = pe.agent_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');
|
|
|
|
|
|
// --- Correction 2: Use Robust Date Range Filtering ---
|
|
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);
|
|
$builder->where("pp.issued_date < DATE_FORMAT(DATE_ADD(CURRENT_DATE(), INTERVAL 1 MONTH), '%Y-%m-01')", NULL, FALSE);
|
|
}
|
|
else if ($month === "previous") {
|
|
// WHERE issued_date >= start_of_previous_month AND issued_date < start_of_current_month
|
|
$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);
|
|
}
|
|
|
|
// Broker and Manager Filter
|
|
$builder->where('pp.manager_id', $managerId);
|
|
$builder->where('pp.vehicle_type', $vehicleType);
|
|
|
|
|
|
$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.
|
|
* @param string $managerId
|
|
* @param int $insurerId
|
|
* @param string $month ('current' or 'previous')
|
|
* @return array
|
|
*/
|
|
private function getInsurerPoliciesData($managerId, $insurerId, $month): 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,
|
|
A.name as agent_name, A.agent_code,
|
|
pe.reg_no,
|
|
pm.value as payment_mode_value,
|
|
ipti.insurance_plan_type,
|
|
i.name AS insurer_name,i.short_name,pp.insured_name, DATE_FORMAT(pp.issued_date, "%d-%m-%Y") AS issued_date,pp.policy_number, pp.premium_amount');
|
|
|
|
$builder->join('partner_quotation pq', 'pq.id = pp.quotation_id', 'left');
|
|
$builder->join('insurers i', 'i.id = pq.insurer_id', 'left');
|
|
|
|
$builder->join('partner_enquiry pe', 'pe.id = pp.enquiry_id', 'left');
|
|
$builder->join('partner_payment_mode_master pm', 'pm.id = pq.payment_mode_id', 'left');
|
|
$builder->join('partner_agent A', 'A.id = pe.agent_id', 'left');
|
|
$builder->join('partner_insurance_plan_type_master ipti', 'ipti.id = pq.insurance_plan_type_id', 'left');
|
|
$builder->join('partner_staff S', 'S.id = pe.assigned_to', 'left');
|
|
|
|
// --- Correction 2: Use Robust Date Range Filtering ---
|
|
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);
|
|
$builder->where("pp.issued_date < DATE_FORMAT(DATE_ADD(CURRENT_DATE(), INTERVAL 1 MONTH), '%Y-%m-01')", NULL, FALSE);
|
|
}
|
|
else if ($month === "previous") {
|
|
// WHERE issued_date >= start_of_previous_month AND issued_date < start_of_current_month
|
|
$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);
|
|
}
|
|
|
|
// Broker and Manager Filter
|
|
$builder->where('pp.manager_id', $managerId);
|
|
$builder->where('i.id', $insurerId);
|
|
$builder->where('i.is_active',1);
|
|
$builder->orderBy('pp.issued_date', 'DESC');
|
|
|
|
$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.
|
|
* @param string $managerId
|
|
* @param int $executiveId
|
|
* @param string $vehicleType
|
|
* @param string $month ('current' or 'previous')
|
|
* @return array
|
|
*/
|
|
private function getStaffAndProductPoliciesExcel($managerId, $executiveId,$vehicleType, $month): array
|
|
{
|
|
// --- Correction 1: Initialize Database Connection ---
|
|
|
|
$data = [];
|
|
|
|
try {
|
|
$builder = $this->db->table('partner_policy pp');
|
|
|
|
$builder->select('
|
|
DATE_FORMAT(pe.created_on, "%d-%m-%Y %h:%i %p") AS received_date,
|
|
S.name as assigned_to_name,
|
|
pa.name as agent_name, pa.agent_code,
|
|
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,
|
|
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');
|
|
$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_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');
|
|
|
|
|
|
// --- Correction 2: Use Robust Date Range Filtering ---
|
|
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);
|
|
$builder->where("pp.issued_date < DATE_FORMAT(DATE_ADD(CURRENT_DATE(), INTERVAL 1 MONTH), '%Y-%m-01')", NULL, FALSE);
|
|
}
|
|
else if ($month === "previous") {
|
|
// WHERE issued_date >= start_of_previous_month AND issued_date < start_of_current_month
|
|
$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);
|
|
}
|
|
|
|
// Broker and Manager Filter
|
|
$builder->where('pp.manager_id', $managerId);
|
|
$builder->where('pa.sales_executive_id', $executiveId);
|
|
$builder->where('pa.sales_executive_id IS NOT NULL');
|
|
$builder->where('pse.is_active', 1);
|
|
$builder->where('pp.vehicle_type', $vehicleType);
|
|
$builder->orderBy('pp.issued_date', 'DESC');
|
|
$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.
|
|
* @param string $managerId
|
|
* @param int $AgentId
|
|
* @param string $month ('current' or 'previous')
|
|
* @return array
|
|
*/
|
|
private function getAgentMonthlyPoliciesData($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');
|
|
|
|
$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');
|
|
|
|
|
|
$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 ($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);
|
|
$builder->where("pp.issued_date < DATE_FORMAT(DATE_ADD(CURRENT_DATE(), INTERVAL 1 MONTH), '%Y-%m-01')", NULL, FALSE);
|
|
// }
|
|
// else if ($month === "previous") {
|
|
// // WHERE issued_date >= start_of_previous_month AND issued_date < start_of_current_month
|
|
// $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);
|
|
// }
|
|
|
|
$builder->orderBy('pp.issued_date', 'DESC');
|
|
|
|
$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.
|
|
* @param string $managerId
|
|
* @return array
|
|
*/
|
|
private function getAgentsWithoutPoliciesData($managerId): array
|
|
{
|
|
$data = [];
|
|
|
|
try {
|
|
$builder = $this->db->table('partner_agent pa');
|
|
$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)',
|
|
'left'
|
|
);
|
|
$builder->where('pa.manager_id', $managerId);
|
|
$builder->where('pp.id IS NULL', null, false);
|
|
|
|
$builder->orderBy('pa.name', 'ASC');
|
|
|
|
$results = $builder->get()->getResultArray();
|
|
|
|
foreach ($results as $row) {
|
|
$data[] = array_values($row);
|
|
}
|
|
|
|
} catch (\CodeIgniter\Database\Exceptions\DatabaseException $e) {
|
|
log_message('error', 'Database Error during Excel fetch: ' . $e->getMessage());
|
|
throw $e;
|
|
}
|
|
|
|
return $data;
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
* Executes the detailed policy query and extracts the data for the spreadsheet.
|
|
* @param string $managerId
|
|
* @return array
|
|
*/
|
|
private function getLowPremiumAgentData($managerId): array
|
|
{
|
|
// --- Correction 1: Initialize Database Connection ---
|
|
|
|
$data = [];
|
|
|
|
try {
|
|
$builder = $this->db->table('partner_policy pp');
|
|
|
|
$builder->select("
|
|
pa.name AS agent_name,
|
|
pa.agent_code,
|
|
CASE
|
|
WHEN pa.is_active = 1 THEN 'Active Partner'
|
|
ELSE 'Inactive Partner'
|
|
END AS agent_status,
|
|
pp.policy_number,
|
|
DATE_FORMAT(pp.issued_date, '%d-%m-%Y') AS issued_date,
|
|
pp.premium_amount
|
|
");
|
|
|
|
$builder->join('partner_agent pa', 'pa.id = pp.agent_id', 'inner');
|
|
// WHERE conditions
|
|
$builder->where('pp.manager_id', $managerId);
|
|
// $builder->where('pa.id', $agentId);
|
|
$builder->where('pp.premium_amount <', 50000);
|
|
$builder->orderBy('pp.issued_date', 'DESC');
|
|
|
|
$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;
|
|
}
|
|
|
|
}
|