nhance_partner_be/app/Controllers/DashboardController.php

1072 lines
45 KiB
PHP

<?php
namespace App\Controllers;
use CodeIgniter\RESTful\ResourceController;
class DashboardController extends ResourceController
{
protected $db;
public function __construct()
{
$this->db = \Config\Database::connect();
}
public function managerDashboard()
{
$manager_id = $this->request->getGet('manager_id');
$today = date('Y-m-d');
$month = date('m');
$year = date('Y');
// --- Policies Issued ---
$policiesToday = $this->db->table('partner_policy')
->where('created_on >=', $today.' 00:00:00')
->where('created_on <=', $today.' 23:59:59')
->where('manager_id',$manager_id)
->countAllResults();
$policiesMonth = $this->db->table('partner_policy')
->where('MONTH(created_on)', $month)
->where('YEAR(created_on)', $year)
->where('manager_id',$manager_id)
->countAllResults();
$policiesYear = $this->db->table('partner_policy')
->where('YEAR(created_on)', $year)
->where('manager_id',$manager_id)
->countAllResults();
// --- Premium Value ---
$premiumToday = (float) ($this->db->table('partner_policy')
->selectSum('premium_amount', 'total')
->where('created_on >=', $today.' 00:00:00')
->where('created_on <=', $today.' 23:59:59')
->where('manager_id',$manager_id)
->get()->getRow()->total ?? 0);
$premiumMonth = (float) ($this->db->table('partner_policy')
->selectSum('premium_amount', 'total')
->where('MONTH(created_on)', $month)
->where('YEAR(created_on)', $year)
->where('manager_id',$manager_id)
->get()->getRow()->total ?? 0);
$premiumYear = (float) ($this->db->table('partner_policy')
->selectSum('premium_amount', 'total')
->where('YEAR(created_on)', $year)
->where('manager_id',$manager_id)
->get()->getRow()->total ?? 0);
// --- Earnings (same as premium for now) ---
$earningsToday = $premiumToday;
$earningsMonth = $premiumMonth;
$earningsYear = $premiumYear;
$last30 = date('Y-m-d H:i:s', strtotime('-30 days'));
// --- Performance Agents (last 30 days) ---
$performanceAgents = $this->db->table('partner_agent pa')
->select('pa.id AS agent_id, pa.name AS agent_name, COUNT(pp.id) AS total_policy_issued, COALESCE(SUM(pp.premium_amount),0) AS total_premium_value, IF(COUNT(pp.id)>0,"Active","Inactive") AS status')
->join('partner_policy pp', 'pp.agent_id = pa.id', 'inner')
->where('pp.created_on >=', $last30)
->where('pa.manager_id',$manager_id)
->get()
->getResultArray();
if(count($performanceAgents) == 1 && $performanceAgents[0]['agent_name'] == null){
$performanceAgents = [];
}
// --- Un assigned enquiry ---
$unassignedEnquiry = $this->db->table('partner_enquiry pe')
->select('pe.* , pe.name as insured_name , pa.name as agent_name')
->join('partner_agent pa', 'pa.id = pe.agent_id', 'left')
->where('pe.assigned_to', 0)
->where('pe.manager_id', $manager_id)
->get()
->getResultArray();
// // --- Staff level Quotations Pending ---
// $quotationsPending = $this->db->table('partner_staff ps')
// ->select('ps.name as staff_name, COUNT(pe.id) as total_quotation_pending')
// ->join('partner_enquiry pe', "pe.assigned_to = ps.id AND pe.status = 'Awaiting Proposal'", 'left')
// ->where('ps.role_id', 2)
// ->where('ps.manager_id',$manager_id)
// ->groupBy('ps.id, ps.name')
// ->get()->getResultArray();
// // --- Staff level Quotations Approva Pending ---
// $quotationsApprovalPending = $this->db->table('partner_staff ps')
// ->select('ps.name as staff_name, COUNT(pe.id) as total_approval_pending')
// ->join('partner_enquiry pe', "pe.assigned_to = ps.id AND pe.status = 'Proposal Created'", 'left')
// ->where('ps.role_id', 2)
// ->where('ps.manager_id',$manager_id)
// ->groupBy('ps.id, ps.name')
// ->get()->getResultArray();
// // --- Staff level Policies Pending ---
// $policiesPending = $this->db->table('partner_staff ps')
// ->select('ps.name as staff_name, COUNT(pe.id) as total_policis_pending, SUM(pq.premium_amount) as total_premium_value')
// ->join('partner_enquiry pe', "pe.assigned_to = ps.id AND pe.status = 'Proposal Accepted'", 'left')
// ->join('partner_quotation pq', "pq.enquiry_id = pe.id AND pq.status = 'Accepted'", 'left')
// ->where('ps.role_id', 2)
// ->where('ps.manager_id',$manager_id)
// ->groupBy('ps.id, ps.name')
// ->get()->getResultArray();
$staffLevelPendingSummary = $this->db->table('partner_enquiry pe')
->select("
ps.name AS staff_name,
ps.id AS staff_id,
ps.handler_id,
COUNT(pe.id) AS total_assigned,
SUM(CASE WHEN pe.enquiry_status != 'Completed' THEN 1 ELSE 0 END) AS total_pending,
SUM(CASE WHEN DATE(pe.created_on) = CURDATE() THEN 1 ELSE 0 END) AS today_assigned,
SUM(CASE WHEN pe.enquiry_status = 'Assigned' AND DATE(pe.created_on) = CURDATE() THEN 1 ELSE 0 END) AS today_pending,
SUM(CASE WHEN pe.enquiry_status = 'In progress' AND DATE(pe.created_on) = CURDATE() THEN 1 ELSE 0 END) AS today_in_progress,
SUM(CASE WHEN pe.enquiry_status = 'Completed' AND DATE(pe.created_on) = CURDATE() THEN 1 ELSE 0 END) AS today_completed,
")
->join('partner_staff ps', 'ps.id = pe.assigned_to', 'left')
->where('pe.manager_id', $manager_id)
->where('pe.is_active', 1)
->where('pe.assigned_to IS NOT NULL')
->where('pe.assigned_to !=', 0)
->groupBy('pe.assigned_to')
->orderBy('ps.name', 'ASC')
->get()
->getResultArray();
foreach ($staffLevelPendingSummary as &$row) {
$handlerIds = json_decode($row['handler_id'] ?? '[]', true);
if (!empty($handlerIds)) {
$handlers = $this->db->table('partner_staff')
->select('name')
->whereIn('id', $handlerIds)
->get()
->getResultArray();
$row['handlers'] = array_column($handlers, 'name');
} else {
$row['handlers'] = [];
}
}
$result = [
'policies_issued' => [
'today' => $policiesToday,
'month' => $policiesMonth,
'year' => $policiesYear,
],
'premium_value' => [
'today' => $premiumToday,
'month' => $premiumMonth,
'year' => $premiumYear,
],
'earnings' => [
'today' => $earningsToday,
'month' => $earningsMonth,
'year' => $earningsYear,
],
'agents_performance' => $performanceAgents,
'unassigned_enquiry' => $unassignedEnquiry,
// 'quotations_pending' => $quotationsPending,
// 'quotations_approval_pending' => $quotationsApprovalPending,
// 'policies_pending' => $policiesPending,
'staff_level_pending_summary' => $staffLevelPendingSummary
];
return $this->respond(['status' => 'success', 'code' => 200, 'data' => $result], 200);
}
public function handlerDashboard()
{
$handler_id = $this->request->getGet('handler_id');
$manager_id = $this->request->getGet('manager_id');
if (empty($handler_id)) {
return $this->response->setJSON([
'status' => false,
'message' => 'Handler ID is required.'
]);
}
$staffLevelPendingSummary = $this->db->table('partner_enquiry pe')
->select("
ps.name AS staff_name,
ps.id AS staff_id,
COUNT(pe.id) AS total_assigned,
SUM(CASE WHEN pe.enquiry_status != 'Completed' THEN 1 ELSE 0 END) AS total_pending,
SUM(CASE WHEN DATE(pe.created_on) = CURDATE() THEN 1 ELSE 0 END) AS today_assigned,
SUM(CASE WHEN pe.enquiry_status = 'Assigned' AND DATE(pe.created_on) = CURDATE() THEN 1 ELSE 0 END) AS today_pending,
SUM(CASE WHEN pe.enquiry_status = 'In progress' AND DATE(pe.created_on) = CURDATE() THEN 1 ELSE 0 END) AS today_in_progress,
SUM(CASE WHEN pe.enquiry_status = 'Completed' AND DATE(pe.created_on) = CURDATE() THEN 1 ELSE 0 END) AS today_completed,
")
->join('partner_staff ps', 'ps.id = pe.assigned_to', 'left')
->groupStart()
->where("JSON_CONTAINS(ps.handler_id, '\"$handler_id\"')")
->orWhere('ps.id', $handler_id)
->groupEnd()
// ->where('ps.handler_id', $handler_id)
->where('pe.is_active', 1)
->where('pe.assigned_to IS NOT NULL')
->where('pe.assigned_to !=', 0)
->groupBy('pe.assigned_to')
->orderBy('ps.name', 'ASC')
->get()
->getResultArray();
$last30 = date('Y-m-d H:i:s', strtotime('-30 days'));
// --- Performance Agents (last 30 days) ---
$performanceAgents = $this->db->table('partner_agent pa')
->select('pa.id AS agent_id, pa.name AS agent_name, COUNT(pp.id) AS total_policy_issued, COALESCE(SUM(pp.premium_amount),0) AS total_premium_value, IF(COUNT(pp.id)>0,"Active","Inactive") AS status')
->join('partner_policy pp', 'pp.agent_id = pa.id', 'inner')
->where('pp.created_on >=', $last30)
->where('pa.manager_id',$manager_id)
->get()
->getResultArray();
if(count($performanceAgents) == 1 && $performanceAgents[0]['agent_name'] == null)
{
$performanceAgents = [];
}
// --- Un assigned enquiry ---
$unassignedEnquiry = $this->db->table('partner_enquiry pe')
->select('pe.* , pe.name as insured_name , pa.name as agent_name')
->join('partner_agent pa', 'pa.id = pe.agent_id', 'left')
->where('pe.assigned_to', 0)
->where('pe.manager_id', $manager_id)
->get()
->getResultArray();
$result = [
'staff_level_pending_summary' => $staffLevelPendingSummary,
'agents_performance' => $performanceAgents,
'unassigned_enquiry' => $unassignedEnquiry,
];
return $this->respond(['status' => 'success', 'code' => 200, 'data' => $result], 200);
}
public function staffDashboard()
{
$staff_id = $this->request->getGet('staff_id');
// --- Proposal pending for staff (last 30 days) ---
$quotationsPending = $this->db->table('partner_enquiry pe')
->select('pe.* ')
->where('pe.assigned_to',$staff_id)
->whereIn('pe.status',["Awaiting Proposal","Proposal Rejected"])
->orderBy('pe.created_on', 'DESC')
->get()
->getResultArray();
// --- Proposal Approval pending for staff (last 30 days) ---
$quotationsApprovalPending = $this->db->table('partner_enquiry pe')
->select('pe.* ')
->where('pe.assigned_to',$staff_id)
->whereIn('pe.status',["Proposal Created"])
->orderBy('pe.created_on', 'DESC')
->get()
->getResultArray();
// --- Policy pending for staff (last 30 days) ---
$policiesPending = $this->db->table('partner_enquiry pe')
->select('pe.* , I.name as insurer_name, I.short_name as insurer_short_name')
->join('partner_quotation Q', 'Q.enquiry_id = pe.id AND Q.status = "Accepted"', 'left')
->join('insurers I', 'I.id = Q.insurer_id', 'left')
->where('pe.assigned_to',$staff_id)
->whereIn('pe.status',["Proposal Accepted"])
->orderBy('pe.created_on', 'DESC')
->get()
->getResultArray();
$result = [
'quotations_pending' => $quotationsPending,
'quotations_approval_pending' => $quotationsApprovalPending,
'quotations_rejected' => $quotationsApprovalPending,
'policies_pending' => $policiesPending,
];
return $this->respond(['status' => 'success', 'code' => 200, 'data' => $result], 200);
}
public function agentDashboard()
{
$agent_id = $this->request->getGet('agent_id');
$today = date('Y-m-d');
$month = date('m');
$year = date('Y');
// --- Policies Issued ---
$policiesToday = $this->db->table('partner_policy')
->where('created_on >=', $today.' 00:00:00')
->where('created_on <=', $today.' 23:59:59')
->where('agent_id',$agent_id)
->countAllResults();
$policiesMonth = $this->db->table('partner_policy')
->where('MONTH(created_on)', $month)
->where('YEAR(created_on)', $year)
->where('agent_id',$agent_id)
->countAllResults();
$policiesYear = $this->db->table('partner_policy')
->where('YEAR(created_on)', $year)
->where('agent_id',$agent_id)
->countAllResults();
// --- Premium Value ---
$premiumToday = (float) ($this->db->table('partner_policy')
->selectSum('premium_amount', 'total')
->where('created_on >=', $today.' 00:00:00')
->where('created_on <=', $today.' 23:59:59')
->where('agent_id',$agent_id)
->get()->getRow()->total ?? 0);
$premiumMonth = (float) ($this->db->table('partner_policy')
->selectSum('premium_amount', 'total')
->where('MONTH(created_on)', $month)
->where('YEAR(created_on)', $year)
->where('agent_id',$agent_id)
->get()->getRow()->total ?? 0);
$premiumYear = (float) ($this->db->table('partner_policy')
->selectSum('premium_amount', 'total')
->where('YEAR(created_on)', $year)
->where('agent_id',$agent_id)
->get()->getRow()->total ?? 0);
// --- Earnings (same as premium for now) ---
$earningsToday = $premiumToday;
$earningsMonth = $premiumMonth;
$earningsYear = $premiumYear;
$last30 = date('Y-m-d H:i:s', strtotime('-30 days'));
// --- Proposal pending for agent (last 30 days) ---
$quotationsPending = $this->db->table('partner_enquiry pe')
->select('pe.* ')
->where('pe.created_on >=', $last30)
->where('pe.agent_id',$agent_id)
->whereIn('pe.status',["Awaiting Proposal","Proposal Rejected"])
->orderBy('pe.created_on', 'DESC')
->get()
->getResultArray();
// --- Proposal approval pending for agent (last 30 days) ---
$quotationsApprovalPending = $this->db->table('partner_enquiry pe')
->select('pe.* ')
->where('pe.created_on >=', $last30)
->where('pe.agent_id',$agent_id)
->whereIn('pe.status',["Awaiting Created"])
->orderBy('pe.created_on', 'DESC')
->get()
->getResultArray();
// --- Policy pending for agent (last 30 days) ---
$policiesPending = $this->db->table('partner_enquiry pe')
->select('pe.* , I.name as insurer_name , I.short_name as insurer_short_name')
->join('partner_quotation Q', 'Q.enquiry_id = pe.id AND Q.status = "Accepted"', 'left')
->join('insurers I', 'I.id = Q.insurer_id', 'left')
->where('pe.created_on >=', $last30)
->where('pe.agent_id',$agent_id)
->where('pe.status','Proposal Accepted')
->orderBy('pe.created_on', 'DESC')
->get()
->getResultArray();
$result = [
'policies_issued' => [
'today' => $policiesToday,
'month' => $policiesMonth,
'year' => $policiesYear,
],
'premium_value' => [
'today' => $premiumToday,
'month' => $premiumMonth,
'year' => $premiumYear,
],
'earnings' => [
'today' => $earningsToday,
'month' => $earningsMonth,
'year' => $earningsYear,
],
'quotations_pending' => $quotationsPending,
'quotations_approval_pending' => $quotationsApprovalPending,
'policies_pending' => $policiesPending,
];
return $this->respond(['status' => 'success', 'code' => 200, 'data' => $result], 200);
}
//business dashboard = month-wise insurer,broker and product (PolicyCount , Premium)
public function businessDashboard()
{
$manager_id = $this->request->getGet('manager_id');
// Initialize the details array to ensure the final output is always structured.
$details = [ 'brokerWise' => [], 'productWise' => [], 'insurerWise' => []];
$code = 200;
$message = "Business Dashboard Data Retrieved Successfully";
try {
// 1. Fetch all data concurrently (or sequentially, as shown)
$details['brokerWise'] = $this->brokerWise($manager_id);
$details['productWise'] = $this->productWise($manager_id);
$details['insurerWise'] = $this->insurerWise($manager_id);
// 2. Check for overall emptiness (optional, but good practice)
$is_empty = array_reduce($details, function ($carry, $item) {
return $carry && empty($item);
}, true);
if ($is_empty) {
// Throw a 404 if ALL data sections are empty
throw new \RuntimeException('No Data Found', 404);
}
// 3. Return a successful, combined JSON response
return $this->response->setJSON([
'status' => 'success',
'data' => $details, // Contains the nested arrays: brokerWise, productWise, insurerWise
'code' => 200,
'message' => $message,
'ref' => 'NIL'
])->setStatusCode(200);
} catch (\Throwable $e) {
// --- Centralized Error Handling Logic ---
$code = ($e->getCode() && $e->getCode() >= 100 && $e->getCode() < 600)
? $e->getCode() : 500;
$isDbError = $e instanceof \CodeIgniter\Database\Exceptions\DatabaseException
|| $e instanceof \mysqli_sql_exception
|| $e instanceof \PDOException;
if ($isDbError) {
// Log the full error, but return minimal info for security
$ref = $e->getFile() . " / LN : " . $e->getLine();
} else {
// This catches the \RuntimeException for "No Data found" (code 404)
$ref = "Application exception occurred";
}
// Return an error JSON response
return $this->response->setJSON([
'status' => 'error',
'data' => [], // Return empty data on error
'code' => $e->getCode(),
'message' => $e->getMessage(),
'ref' => $ref,
])->setStatusCode($code);
}
}
//partner dashboard = month-wise PolicyCount , month-wise Premium, No Agent For Last 10 Days and below 50thouands Premium agentwise
public function partnerDashboard()
{
$manager_id = $this->request->getGet('manager_id');
// Initialize the details array to ensure the final output is always structured.
$code = 200;
$message = "Partner Dashboard Data Retrieved Successfully";
$details = [ 'monthlyPolicyCount' => [],'monthlyPremiumAmount' => [],'noPolicyTimeRange' => [],'below50tPremiumTimeRange' => []];
// 'agentNoPolicyLast10Days' => [],// 'agentBelow50tPremiumLast10Days' => [],
try {
// 1. Fetch all data concurrently (or sequentially, as shown)
$date = $this->request->getGet('date');
$date = $date ?? date('Y-m-d');
$limit = $limit ?? 50;
$value = $value ?? 10;
$unit = $unit ?? 'DAY';
$details['monthlyPolicyCount'] = $this->agentMonthlyPolicyCount($date,$limit,$manager_id);
$details['monthlyPremiumAmount'] = $this->agentMonthlyPremiumAmount($date,$limit,$manager_id);
$details['noPolicyTimeRange'] = $this->agentNoPolicyTimeRange($value,$unit,$manager_id);
$details['below50tPremiumTimeRange'] = $this->agentBelow50tPremiumTimeRange($value,$unit,$manager_id);
// 2. Check for overall emptiness (optional, but good practice)
$is_empty = array_reduce($details, function ($carry, $item) {
return $carry && empty($item);
}, true);
if ($is_empty) {
throw new \RuntimeException('No Data Found', 404);
}
// 3. Return a successful, combined JSON response
return $this->response->setJSON([
'status' => 'success',
'data' => $details, // Contains the nested arrays: brokerWise, productWise, insurerWise
'code' => 200,
'message' => $message,
'ref' => 'NIL'
])->setStatusCode(200);
} catch (\Throwable $e) {
// --- Centralized Error Handling Logic ---
$code = ($e->getCode() && $e->getCode() >= 100 && $e->getCode() < 600)
? $e->getCode() : 500;
$isDbError = $e instanceof \CodeIgniter\Database\Exceptions\DatabaseException
|| $e instanceof \mysqli_sql_exception
|| $e instanceof \PDOException;
if ($isDbError) {
// Log the full error, but return minimal info for security
$ref = $e->getFile() . " / LN : " . $e->getLine();
} else {
// This catches the \RuntimeException for "No Data found" (code 404)
$ref = "Application exception occurred";
}
// Return an error JSON response
return $this->response->setJSON([
'status' => 'error',
'data' => [], // Return empty data on error
'code' => $e->getCode(),
'message' => $e->getMessage(),
'ref' => $ref,
])->setStatusCode($code);
}
}
public function productivityDashboard(){
$manager_id = $this->request->getGet('manager_id');
// Initialize the details array to ensure the final output is always structured.
$details = [ 'StaffWise' => [], 'ProductWise' => []];
$code = 200;
$message = "Productivity Dashboard Data Retrieved Successfully";
try {
// 1. Fetch all data concurrently (or sequentially, as shown)
$details['StaffWise'] = $this->staffWiseProductList($manager_id);
// $details['ProductWise'] = $this->productivityProductWise($manager_id);
// 2. Check for overall emptiness (optional, but good practice)
$is_empty = array_reduce($details, function ($carry, $item) {
return $carry && empty($item);
}, true);
if ($is_empty) {
// Throw a 404 if ALL data sections are empty
throw new \RuntimeException('No Data Found', 404);
}
// 3. Return a successful, combined JSON response
return $this->response->setJSON([
'status' => 'success',
'data' => $details, // Contains the nested arrays: brokerWise, productWise, insurerWise
'code' => 200,
'message' => $message,
'ref' => 'NIL'
])->setStatusCode(200);
} catch (\Throwable $e) {
// --- Centralized Error Handling Logic ---
$code = ($e->getCode() && $e->getCode() >= 100 && $e->getCode() < 600)
? $e->getCode() : 500;
$isDbError = $e instanceof \CodeIgniter\Database\Exceptions\DatabaseException
|| $e instanceof \mysqli_sql_exception
|| $e instanceof \PDOException;
if ($isDbError) {
// Log the full error, but return minimal info for security
$ref = $e->getFile() . " / LN : " . $e->getLine();
} else {
// This catches the \RuntimeException for "No Data found" (code 404)
$ref = "Application exception occurred";
}
// Return an error JSON response
return $this->response->setJSON([
'status' => 'error',
'data' => [], // Return empty data on error
'code' => $e->getCode(),
'message' => $e->getMessage(),
'ref' => $ref,
])->setStatusCode($code);
}
}
//Step 1.1
public function insurerWise($manager_id){
$builder = $this->db->table('partner_policy pp');
$builder->select("
DATE_FORMAT(CURRENT_DATE(), '%b') AS curr_month,
YEAR(CURRENT_DATE()) AS year_of_curr_month,
DATE_FORMAT(DATE_SUB(CURRENT_DATE(), INTERVAL 1 MONTH), '%b') AS pre_month,
YEAR(DATE_SUB(CURRENT_DATE(), INTERVAL 1 MONTH)) AS year_of_last_month,
i.name,
i.short_name,
i.id AS insurer_id,
pq.insurer_id AS PQ_insurer_id,
pq.insurer_id,
pp.insured_name,
COUNT(
CASE
WHEN MONTH(pp.issued_date) = MONTH(CURRENT_DATE())
AND YEAR(pp.issued_date) = YEAR(CURRENT_DATE())
THEN pp.client_policy_id
ELSE NULL
END
) AS total_policies_current_month,
SUM(
CASE
WHEN MONTH(pp.issued_date) = MONTH(CURRENT_DATE())
AND YEAR(pp.issued_date) = YEAR(CURRENT_DATE())
THEN pp.premium_amount
ELSE 0
END
) AS total_premium_current_month,
COUNT(
CASE
WHEN pp.issued_date >= DATE_FORMAT(DATE_SUB(CURRENT_DATE(), INTERVAL 1 MONTH), '%Y-%m-01')
AND pp.issued_date < DATE_FORMAT(CURRENT_DATE(), '%Y-%m-01')
THEN pp.client_policy_id
ELSE NULL
END
) AS total_policies_pre_month,
SUM(
CASE
WHEN pp.issued_date >= DATE_FORMAT(DATE_SUB(CURRENT_DATE(), INTERVAL 1 MONTH), '%Y-%m-01')
AND pp.issued_date < DATE_FORMAT(CURRENT_DATE(), '%Y-%m-01')
THEN pp.premium_amount
ELSE 0
END
) AS total_premium_pre_month
");
$builder->join('partner_quotation pq', 'pq.id = pp.quotation_id', 'left');
$builder->join('insurers i', 'i.id = pq.insurer_id', 'left');
$builder->where("
pp.issued_date >= DATE_FORMAT(DATE_SUB(CURRENT_DATE(), INTERVAL 1 MONTH), '%Y-%m-01')
AND pp.issued_date < DATE_FORMAT(DATE_ADD(CURRENT_DATE(), INTERVAL 1 MONTH), '%Y-%m-01')
", null, false);
$builder->where('pp.manager_id',$manager_id);
$builder->where('i.is_active',1);
$builder->where("pq.insurer_id != 0");
$builder->groupBy('pq.insurer_id');
$builder->orderBy('pq.insurer_id');
$query = $builder->get();
$result = $query->getResultArray();
return $result;
}
//Step 1.2
public function brokerWise($manager_id){
$builder = $this->db->table('partner_policy pp');
$builder->select("
DATE_FORMAT(CURRENT_DATE(), '%b') AS curr_month,
YEAR(CURRENT_DATE()) AS year_of_curr_month,
DATE_FORMAT(DATE_SUB(CURRENT_DATE(), INTERVAL 1 MONTH), '%b') AS pre_month,
YEAR(DATE_SUB(CURRENT_DATE(), INTERVAL 1 MONTH)) AS year_of_last_month,
pb.name AS broker_name,
pb.id AS broker_id,
pe.broker_id AS PE_broker_id,
COUNT(
CASE
WHEN MONTH(pp.issued_date) = MONTH(CURRENT_DATE())
AND YEAR(pp.issued_date) = YEAR(CURRENT_DATE())
THEN pp.client_policy_id
ELSE NULL
END
) AS total_policies_current_month,
SUM(
CASE
WHEN MONTH(pp.issued_date) = MONTH(CURRENT_DATE())
AND YEAR(pp.issued_date) = YEAR(CURRENT_DATE())
THEN pp.premium_amount
ELSE 0
END
) AS total_premium_current_month,
COUNT(
CASE
WHEN pp.issued_date >= DATE_FORMAT(DATE_SUB(CURRENT_DATE(), INTERVAL 1 MONTH), '%Y-%m-01')
AND pp.issued_date < DATE_FORMAT(CURRENT_DATE(), '%Y-%m-01')
THEN pp.client_policy_id
ELSE NULL
END
) AS total_policies_pre_month,
SUM(
CASE
WHEN pp.issued_date >= DATE_FORMAT(DATE_SUB(CURRENT_DATE(), INTERVAL 1 MONTH), '%Y-%m-01')
AND pp.issued_date < DATE_FORMAT(CURRENT_DATE(), '%Y-%m-01')
THEN pp.premium_amount
ELSE 0
END
) AS total_premium_pre_month
");
$builder->join('partner_enquiry pe', 'pe.id = pp.enquiry_id', 'left');
$builder->join('partner_brokers pb', 'pb.id = pe.broker_id', 'left');
$builder->where("
pp.issued_date >= DATE_FORMAT(DATE_SUB(CURRENT_DATE(), INTERVAL 1 MONTH), '%Y-%m-01')
AND pp.issued_date < DATE_FORMAT(DATE_ADD(CURRENT_DATE(), INTERVAL 1 MONTH), '%Y-%m-01')
", null, false);
$builder->where('pp.manager_id',$manager_id);
$builder->groupBy('pb.id');
$builder->orderBy('pb.id');
$query = $builder->get();
$result = $query->getResultArray();
return $result;
}
//Step 1.3
public function productWise($manager_id){
$builder = $this->db->table('partner_policy pp');
$builder->select("
DATE_FORMAT(CURRENT_DATE(), '%b') AS curr_month,
YEAR(CURRENT_DATE()) AS year_of_curr_month,
DATE_FORMAT(DATE_SUB(CURRENT_DATE(), INTERVAL 1 MONTH), '%b') AS pre_month,
YEAR(DATE_SUB(CURRENT_DATE(), INTERVAL 1 MONTH)) AS year_of_last_month,
pp.vehicle_type,
COUNT(
CASE
WHEN MONTH(pp.issued_date) = MONTH(CURRENT_DATE())
AND YEAR(pp.issued_date) = YEAR(CURRENT_DATE())
THEN pp.client_policy_id
ELSE NULL
END
) AS total_policies_current_month,
SUM(
CASE
WHEN MONTH(pp.issued_date) = MONTH(CURRENT_DATE())
AND YEAR(pp.issued_date) = YEAR(CURRENT_DATE())
THEN pp.premium_amount
ELSE 0
END
) AS total_premium_current_month,
COUNT(
CASE
WHEN pp.issued_date >= DATE_FORMAT(DATE_SUB(CURRENT_DATE(), INTERVAL 1 MONTH), '%Y-%m-01')
AND pp.issued_date < DATE_FORMAT(CURRENT_DATE(), '%Y-%m-01')
THEN pp.client_policy_id
ELSE NULL
END
) AS total_policies_pre_month,
SUM(
CASE
WHEN pp.issued_date >= DATE_FORMAT(DATE_SUB(CURRENT_DATE(), INTERVAL 1 MONTH), '%Y-%m-01')
AND pp.issued_date < DATE_FORMAT(CURRENT_DATE(), '%Y-%m-01')
THEN pp.premium_amount
ELSE 0
END
) AS total_premium_pre_month
");
$builder->where("
pp.issued_date >= DATE_FORMAT(DATE_SUB(CURRENT_DATE(), INTERVAL 1 MONTH), '%Y-%m-01')
AND pp.issued_date < DATE_FORMAT(DATE_ADD(CURRENT_DATE(), INTERVAL 1 MONTH), '%Y-%m-01')
", null, false);
$builder->where('pp.manager_id',$manager_id);
$builder->groupBy('pp.vehicle_type');
$query = $builder->get();
$result = $query->getResultArray();
return $result;
}
//Step 2.1
public function agentMonthlyPolicyCount($customDate,$limit,$manager_id){
// 2.1
// $customDate = $custom_date; // '2025-11-05' or CURRENT_DATE()
// $limit = 50;
$builder = $this->db->table('partner_policy pp');
$builder->select("
pp.agent_id AS PP_agent_id,
pa.id AS agent_id,
pa.name AS agent_name,
pa.agent_code,
COUNT(pp.id) AS policy_count
");
$builder->join('partner_agent pa', 'pp.agent_id = pa.id', 'inner');
$builder->join('partner_enquiry pe', 'pe.id = pp.enquiry_id', 'left');
$builder->where("MONTH(pp.issued_date) = MONTH('$customDate')", null, false);
$builder->where("YEAR(pp.issued_date) = YEAR('$customDate')", null, false);
$builder->where('pp.manager_id',$manager_id);
$builder->groupBy(['pa.id']);
$builder->orderBy('policy_count', 'DESC');
$builder->limit($limit);
$result = $builder->get()->getResultArray();
return $result;
}
//Step 2.2
public function agentMonthlyPremiumAmount($customDate,$limit,$manager_id){
// 2.2
// $customDate = $custom_date; // Example '2025-11-05'
// $limit = 50;
$builder = $this->db->table('partner_policy pp');
$builder->select("
pp.agent_id AS PP_agent_id,
pa.id AS agent_id,
pa.name AS agent_name,
pa.agent_code,
SUM(pp.premium_amount) AS total_premium_amount
");
$builder->join('partner_agent pa', 'pp.agent_id = pa.id', 'inner');
$builder->join('partner_enquiry pe', 'pe.id = pp.enquiry_id', 'left');
$builder->where("MONTH(pp.issued_date) = MONTH('$customDate')", null, false);
$builder->where("YEAR(pp.issued_date) = YEAR('$customDate')", null, false);
$builder->where('pp.manager_id',$manager_id);
// $builder->groupBy(['pa.id']);
$builder->orderBy('total_premium_amount', 'DESC');
$builder->limit($limit);
$result = $builder->get()->getResultArray();
return $result;
}
//Step 3
public function agentNoPolicyTimeRange($value,$unit,$manager_id){
// $value = 10; // dynamic number (10, 50, 1, 2, 3, etc.)
// $unit = 'DAY'; // DAY, MONTH, YEAR (dynamic)
$interval = "DATE_SUB(CURRENT_TIMESTAMP(), INTERVAL $value $unit)";
$builder = $this->db->table('partner_agent pa');
$builder->select('
pa.id AS agent_id,
pa.name AS agent_name,
pa.email,
pa.mobile,
pa.agent_code,
pa.is_active
');
$builder->join(
'partner_policy pp',
"pa.id = pp.agent_id AND pp.issued_date >= $interval",
'left',
false // IMPORTANT → allows raw SQL
);
$builder->where('pa.manager_id',$manager_id);
$builder->where('pp.id', null);
$builder->orderBy('pa.name');
$result = $builder->get()->getResultArray();
return $result;
}
//Step 4
public function agentBelow50tPremiumTimeRange($value,$unit,$manager_id){
// 4th
// $value = 10; // Dynamic (10, 50, 1, 2, 3...)
// $unit = 'DAY'; // DAY, MONTH, YEAR
$interval = "DATE_SUB(CURRENT_TIMESTAMP(), INTERVAL $value $unit)";
$builder = $this->db->table('partner_policy pp');
$builder->select("
pa.id AS agent_id,
pa.name AS agent_name,
pa.agent_code AS agent_code,
pp.agent_id AS PP_agent_id,
SUM(pp.premium_amount) AS total_premium_amount,
CASE
WHEN pa.is_active = 1 THEN 'Active Agent'
ELSE 'Inactive Agent'
END AS agent_status,
DATE_FORMAT(pp.issued_date, '%d-%m-%Y') AS created_date_ui_formatted,
pp.issued_date AS created_date_sql_formatted
");
$builder->join('partner_agent pa', 'pa.id = pp.agent_id', 'left');
$builder->where('pp.manager_id', $manager_id);
$builder->where('pp.premium_amount <', 50000);
$builder->where("pp.issued_date >= $interval", null, false); // raw SQL
$builder->groupBy('pa.id');
$builder->orderBy('total_premium_amount', 'DESC');
$builder->orderBy('created_date_sql_formatted', 'DESC');
return $builder->get()->getResultArray();
}
// Step 5
public function staffWiseProductList($manager_id)
{
$builder = $this->db->table('partner_policy pp');
$builder->select("
DATE_FORMAT(CURRENT_DATE(), '%b') AS curr_month,
YEAR(CURRENT_DATE()) AS year_of_curr_month,
DATE_FORMAT(DATE_SUB(CURRENT_DATE(), INTERVAL 1 MONTH), '%b') AS pre_month,
YEAR(DATE_SUB(CURRENT_DATE(), INTERVAL 1 MONTH)) AS year_of_last_month,
pa.sales_executive_id,
pse.name as sales_executive_name,
pp.manager_id,
pp.vehicle_type AS vechile_type,
COUNT(
CASE
WHEN MONTH(pp.issued_date) = MONTH(CURRENT_DATE())
AND YEAR(pp.issued_date) = YEAR(CURRENT_DATE())
THEN pp.client_policy_id
END
) AS total_policies_current_month,
SUM(
CASE
WHEN MONTH(pp.issued_date) = MONTH(CURRENT_DATE())
AND YEAR(pp.issued_date) = YEAR(CURRENT_DATE())
THEN pp.premium_amount ELSE 0
END
) AS total_premium_current_month,
COUNT(
CASE
WHEN pp.issued_date >= DATE_FORMAT(DATE_SUB(CURRENT_DATE(), INTERVAL 1 MONTH), '%Y-%m-01')
AND pp.issued_date < DATE_FORMAT(CURRENT_DATE(), '%Y-%m-01')
THEN pp.client_policy_id
END
) AS total_policies_pre_month,
SUM(
CASE
WHEN pp.issued_date >= DATE_FORMAT(DATE_SUB(CURRENT_DATE(), INTERVAL 1 MONTH), '%Y-%m-01')
AND pp.issued_date < DATE_FORMAT(CURRENT_DATE(), '%Y-%m-01')
THEN pp.premium_amount ELSE 0
END
) AS total_premium_pre_month
");
$builder->join('partner_agent pa', 'pa.id = pp.agent_id', 'left');
$builder->join('partner_sales_executive pse', 'pse.id = pa.sales_executive_id', 'left');
// Date filters
$builder->where("
pp.issued_date >= DATE_FORMAT(DATE_SUB(CURRENT_DATE(), INTERVAL 1 MONTH), '%Y-%m-01')
AND pp.issued_date < DATE_FORMAT(DATE_ADD(CURRENT_DATE(), INTERVAL 1 MONTH), '%Y-%m-01')
", null, false);
$builder->where('pp.manager_id', $manager_id);
$builder->where('pa.sales_executive_id IS NOT NULL', null, false);
$builder->where('pse.is_active', 1);
// Group by sales exec + vehicle type
$builder->groupBy("pa.sales_executive_id, pp.vehicle_type");
$builder->orderBy("pa.sales_executive_id");
$rows = $builder->get()->getResultArray();
// Final compilation
$final = [];
foreach ($rows as $row) {
$se_id = $row['sales_executive_id'];
if (!isset($final[$se_id])) {
$final[$se_id] = [
"curr_month" => $row["curr_month"],
"year_of_curr_month" => $row["year_of_curr_month"],
"pre_month" => $row["pre_month"],
"year_of_last_month" => $row["year_of_last_month"],
"sales_executive_id" => $row["sales_executive_id"],
"sales_executive_name" => $row["sales_executive_name"],
"manager_id" => $row["manager_id"],
"products_list" => [],
"total_products" => 0
];
}
// Add each product entry
$final[$se_id]["products_list"][] = [
"vechile_type" => $row["vechile_type"],
"total_policies_current_month" => $row["total_policies_current_month"],
"total_premium_current_month" => $row["total_premium_current_month"],
"total_policies_pre_month" => $row["total_policies_pre_month"],
"total_premium_pre_month" => $row["total_premium_pre_month"]
];
}
// Add total_products count
// foreach ($final as $key => $value) {
// $final[$key]["total_products"] = count($value["products_list"]);
// }
return array_values($final);
}
}