db->table('policy_transaction') ->select(" policy_transaction.*, DATE_FORMAT(policy_transaction.policy_issue_date, '%d %b %Y') AS policy_issue_date, DATE_FORMAT( IF(policy_transaction.month IS NULL, policy_transaction.policy_issue_date, policy_transaction.month), '%b %Y') AS policy_issue_month, CASE WHEN clients.client_type = 1 THEN 'Group' WHEN clients.client_type = 2 THEN 'Retail' ELSE '-' END AS client_type, CASE WHEN policy_transaction.revenue_type = 'NA' THEN 'Fresh' ELSE 'Renewal' END AS revenue_type, CASE WHEN policy_transaction.action_type = 'inception' THEN 'Policy' ELSE 'Endorsement' END AS action_type, clients.client_name AS client_name, clients.short_name AS client_short_name, client_branch.branch_name AS client_branch_name, client_branch.address1 AS client_address, policy_type.policy_type, policy_type.bap, insurers.name AS insurer_name, insurers.short_name AS insurer_short_name, insurer_branch.branch_name AS insurer_branch_name, insurer_branch.branch_code AS insurer_branch_code, user_profiles.first_name as user_name, vehicle.vehicle_no, tpa.name as tpa_name, pt_co_share_details.remark as remarks, pt_co_share_details.reward, pt_co_share_details.bp_amt, sales_user.first_name as salse_person_name, service_user.first_name as service_person_name, ROUND((pt_co_share_details.bp_amt + pt_co_share_details.tp_amt + pt_co_share_details.tep_amt), 2) AS premium_wo_gst, ROUND((ROUND((pt_co_share_details.bp_amt + pt_co_share_details.tp_amt + pt_co_share_details.tep_amt), 2) * 18 / 100), 2) AS gst_amount, ROUND((ROUND((pt_co_share_details.bp_amt + pt_co_share_details.tp_amt + pt_co_share_details.tep_amt), 2) + ROUND((ROUND((pt_co_share_details.bp_amt + pt_co_share_details.tp_amt + pt_co_share_details.tep_amt), 2) * 18 / 100), 2)), 2) AS total_premium, ROUND((pt_co_share_details.tp_amt + pt_co_share_details.tep_amt), 2) AS tp_or_ter, DATEDIFF(policy_transaction.policy_end_date, CURDATE()) AS days, (pt_co_share_details.agreed_tp_per + pt_co_share_details.agreed_tep_per) AS agreed_tp_or_ter_per, pt_co_share_details.agreed_bp_per, ROUND( (pt_co_share_details.bp_amt * pt_co_share_details.agreed_bp_per + (pt_co_share_details.tp_amt + pt_co_share_details.tep_amt) * (pt_co_share_details.agreed_tp_per + pt_co_share_details.agreed_tep_per)) / 100, 2) AS total_irda, ROUND( (ROUND( (pt_co_share_details.bp_amt * pt_co_share_details.agreed_bp_per + (pt_co_share_details.tp_amt + pt_co_share_details.tep_amt) * (pt_co_share_details.agreed_tp_per + pt_co_share_details.agreed_tep_per)) / 100, 2) * 18 / 100), 2) AS gst_on_revenue, ROUND( (ROUND( (pt_co_share_details.bp_amt * pt_co_share_details.agreed_bp_per + (pt_co_share_details.tp_amt + pt_co_share_details.tep_amt) * (pt_co_share_details.agreed_tp_per + pt_co_share_details.agreed_tep_per)) / 100, 2) + ROUND( (ROUND( (pt_co_share_details.bp_amt * pt_co_share_details.agreed_bp_per + (pt_co_share_details.tp_amt + pt_co_share_details.tep_amt) * (pt_co_share_details.agreed_tp_per + pt_co_share_details.agreed_tep_per)) / 100, 2) * 18 / 100), 2)), 2) AS total_amt_received, insurer_statements.invoice_date, insurer_statements.invoice_no, insurer_statements.invoice_amount, ( SELECT (SUM(inv_payment_details.inv_amt) + SUM(inv_payment_details.tds)) AS realization_amount FROM inv_payment_details WHERE inv_payment_details.statement_id = insurer_statements.id AND inv_payment_details.is_active = 1 ) AS realization_amount, ROUND( insurer_statements.invoice_amount - ( SELECT (SUM(inv_payment_details.inv_amt) + SUM(inv_payment_details.tds)) FROM inv_payment_details WHERE inv_payment_details.statement_id = insurer_statements.id AND inv_payment_details.is_active = 1 ), 2) AS outstanding_amount, ( SELECT GROUP_CONCAT(inv_payment_details.utr_no SEPARATOR ', ') AS utr_numbers FROM inv_payment_details WHERE inv_payment_details.statement_id = insurer_statements.id AND inv_payment_details.is_active = 1 ) AS utr_numbers, ( SELECT GROUP_CONCAT(inv_payment_details.received_date SEPARATOR ', ') AS payment_dates FROM inv_payment_details WHERE inv_payment_details.statement_id = insurer_statements.id AND inv_payment_details.is_active = 1 ) AS payment_dates ") ->join('pt_co_share_details', 'policy_transaction.id = pt_co_share_details.pt_id', 'left') ->join('insurer_statements', 'pt_co_share_details.statement_id = insurer_statements.id', 'left') ->join('clients', 'clients.id = policy_transaction.client_id') ->join('client_branch', 'policy_transaction.client_branch_id = client_branch.id', 'left') ->join('client_policy', 'policy_transaction.client_policy_id = client_policy.id', 'left') ->join('user_profiles', 'policy_transaction.created_by = user_profiles.id', 'left') ->join('vehicle', 'policy_transaction.vehicle_id = vehicle.id', 'left') ->join('policy_type', 'policy_transaction.policy_type_id = policy_type.id', 'left') ->join('insurers', 'policy_transaction.insurer_id = insurers.id', 'left') ->join('insurer_branch', 'policy_transaction.insurer_branch_id = insurer_branch.id', 'left') ->join('tpa', 'policy_transaction.tpa_id = tpa.id', 'left') ->join('tpa_branch', 'policy_transaction.tpa_branch_id = tpa_branch.id', 'left') ->join('user_profiles AS sales_user', 'policy_transaction.sales_generated_by = sales_user.id', 'left') ->join('user_profiles AS service_user', 'policy_transaction.serviced_by = service_user.id', 'left') ->where('policy_transaction.is_active', 1); // Check if the start date and end date are provided if ($start_date != 0 && $end_date != 0 && $date_type != 0) { $this->validateDateType($date_type); $startDate = date('Y-m-d 00:00:00', strtotime($start_date)); $endDate = date('Y-m-d 23:59:59', strtotime($end_date)); $builder->where('policy_transaction.' . $date_type . ' >=', $startDate) ->where('policy_transaction.' . $date_type . ' <=', $endDate); } else { // $fromDate = date('Y-m-d', strtotime('-30 days')); // $toDate = date('Y-m-d 23:59:59'); // $builder->where('policy_transaction.created_at >=', $fromDate) // ->where('policy_transaction.created_at <=', $toDate); } if ($client_id != 0) { $builder->where('policy_transaction.client_id', $client_id); } if ($insurer_id != 0) { $builder->where('policy_transaction.insurer_id', $insurer_id); } if ($policy_type_id != 0) { $builder->where('client_policy.policy_type_id', $policy_type_id); } if ($issuer != 0) { $builder->where('policy_transaction.issuer', $issuer); } if ($client_id == 0 && $insurer_id == 0 && $policy_type_id == 0 && $date_type == 0 && $issuer == 0) { $fromDate = date('Y-m-d', strtotime('-90 days')); $toDate = date('Y-m-d 23:59:59'); $builder->where('policy_transaction.created_at >=', $fromDate) ->where('policy_transaction.created_at <=', $toDate); } $builder->orderBy('policy_transaction.id', 'desc'); return $builder->get()->getResultArray(); } // BDS Report NEW Functin for QUERY // public function getBDSReportList($client_id, $policy_id, $branch_id, $issuer) // public function getBDSReportList($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0, $client_branch_id = 0, $insurer_branch_id = 0, $client_policy_id = 0) // { // $date_condition = ''; // if($date_type == 'statement_month' && $start_date != 0 && $end_date != 0) { // $date_condition = " // AND insurer_statements.month >= '".$start_date ."' // AND insurer_statements.month <= '".$end_date ."' // "; // } // $builder = $this->db->table('policy_transaction') // ->select(" // policy_transaction.*, // DATE_FORMAT(policy_transaction.policy_issue_date, '%d %b %Y') AS policy_issue_date, // DATE_FORMAT( // IF(policy_transaction.month IS NULL, // policy_transaction.policy_issue_date, // policy_transaction.month), // '%b %Y') AS policy_issue_month, // CASE // WHEN clients.client_type = 1 THEN 'Group' // WHEN clients.client_type = 2 THEN 'Retail' // ELSE '-' // END AS client_type, // CASE // WHEN policy_transaction.revenue_type = 'NA' THEN 'Fresh' // ELSE 'Renewal' // END AS revenue_type, // CASE // WHEN policy_transaction.action_type = 'inception' THEN 'Policy' // ELSE 'Endorsement' // END AS action_type, // clients.client_name AS client_name, // clients.short_name AS client_short_name, // client_branch.branch_name AS client_branch_name, // client_branch.address1 AS client_address, // policy_type.policy_type, // policy_type.bap, // insurers.name AS insurer_name, // insurers.short_name AS insurer_short_name, // insurer_branch.branch_name AS insurer_branch_name, // insurer_branch.branch_code AS insurer_branch_code, // user_profiles.first_name as user_name, // vehicle.vehicle_no, // tpa.name as tpa_name, // pt_co_share_details.remark as remarks, // pt_co_share_details.bp_amt, // pt_co_share_details.exp_amt, // pt_co_share_details.id as pt_id, // sales_user.first_name as salse_person_name, // service_user.first_name as service_person_name, // ROUND((pt_co_share_details.bp_amt + pt_co_share_details.tp_amt + pt_co_share_details.tep_amt), 2) AS premium_wo_gst, // ROUND((ROUND((pt_co_share_details.bp_amt + pt_co_share_details.tp_amt + pt_co_share_details.tep_amt), 2) * 18 / 100), 2) AS gst_amount, // ROUND((ROUND((pt_co_share_details.bp_amt + pt_co_share_details.tp_amt + pt_co_share_details.tep_amt), 2) + ROUND((ROUND((pt_co_share_details.bp_amt + pt_co_share_details.tp_amt + pt_co_share_details.tep_amt), 2) * 18 / 100), 2)), 2) AS total_premium, // ROUND((pt_co_share_details.tp_amt + pt_co_share_details.tep_amt), 2) AS tp_or_ter, // DATEDIFF(policy_transaction.policy_end_date, CURDATE()) AS days, // (pt_co_share_details.agreed_tp_per + pt_co_share_details.agreed_tep_per) AS agreed_tp_or_ter_per, // pt_co_share_details.agreed_bp_per, // ROUND( // ( // SELECT // ( // SUM(co_share_stmt_details.actual_bp_brokerage_amt) + // SUM(co_share_stmt_details.actual_tp_brokerage_amt) + // SUM(co_share_stmt_details.actual_tep_brokerage_amt) + // SUM(co_share_stmt_details.reward) // ) AS total_irda_amt // FROM // co_share_stmt_details // JOIN insurer_statements ON co_share_stmt_details.statement_id = insurer_statements.id // WHERE // co_share_stmt_details.co_share_id = pt_co_share_details.id // AND co_share_stmt_details.is_active = 1 // AND insurer_statements.is_active = 1 // $date_condition // ), // 2 // ) AS total_irda_amt, // ROUND( // ( // SELECT // ( // SUM(co_share_stmt_details.reward) // ) AS reward // FROM // co_share_stmt_details // JOIN insurer_statements ON co_share_stmt_details.statement_id = insurer_statements.id // WHERE // co_share_stmt_details.co_share_id = pt_co_share_details.id // AND co_share_stmt_details.is_active = 1 // AND insurer_statements.is_active = 1 // $date_condition // ), // 2 // ) AS reward, // ROUND( // ( // SELECT // SUM( // COALESCE(co_share_stmt_details.actual_bp_brokerage_amt, 0) + // COALESCE(co_share_stmt_details.actual_tp_brokerage_amt, 0) + // COALESCE(co_share_stmt_details.actual_tep_brokerage_amt, 0) + // COALESCE(co_share_stmt_details.reward, 0) // ) AS total_irda_amt // FROM // co_share_stmt_details // JOIN pt_co_share_details AS pt_table ON co_share_stmt_details.co_share_id = pt_table.id // JOIN insurer_statements ON co_share_stmt_details.statement_id = insurer_statements.id // WHERE // co_share_stmt_details.co_share_id = pt_co_share_details.id // AND co_share_stmt_details.is_active = 1 // AND pt_table.is_active = 1 // AND insurer_statements.is_active = 1 // AND insurer_statements.invoice_status IS NOT NULL // $date_condition // ), // 2 // ) AS billed_amt, // ROUND( // ( // ( // SELECT // SUM( // COALESCE(co_share_stmt_details.actual_bp_brokerage_amt, 0) // + COALESCE(co_share_stmt_details.actual_tp_brokerage_amt, 0) // + COALESCE(co_share_stmt_details.actual_tep_brokerage_amt, 0) // + COALESCE(co_share_stmt_details.reward, 0) // ) // FROM // co_share_stmt_details // JOIN insurer_statements ON co_share_stmt_details.statement_id = insurer_statements.id // WHERE // co_share_stmt_details.co_share_id = pt_co_share_details.id // AND co_share_stmt_details.is_active = 1 // $date_condition // ) // - // ( // SELECT // SUM( // COALESCE(co_share_stmt_details.actual_bp_brokerage_amt, 0) // + COALESCE(co_share_stmt_details.actual_tp_brokerage_amt, 0) // + COALESCE(co_share_stmt_details.actual_tep_brokerage_amt, 0) // + COALESCE(co_share_stmt_details.reward, 0) // ) // FROM // co_share_stmt_details // JOIN pt_co_share_details AS pt_table ON co_share_stmt_details.co_share_id = pt_table.id // JOIN insurer_statements ON co_share_stmt_details.statement_id = insurer_statements.id // WHERE // co_share_stmt_details.co_share_id = pt_co_share_details.id // AND co_share_stmt_details.is_active = 1 // AND pt_table.is_active = 1 // AND insurer_statements.is_active = 1 // AND insurer_statements.invoice_status IS NULL // $date_condition // ) // ), // 2 // ) AS unbilled_amt // ") // ->join('pt_co_share_details', 'policy_transaction.id = pt_co_share_details.pt_id', 'left') // // ->join('insurer_statements', 'pt_co_share_details.statement_id = insurer_statements.id', 'left') // ->join('clients', 'clients.id = policy_transaction.client_id') // ->join('client_branch', 'policy_transaction.client_branch_id = client_branch.id', 'left') // ->join('client_policy', 'policy_transaction.client_policy_id = client_policy.id', 'left') // ->join('user_profiles', 'policy_transaction.created_by = user_profiles.id', 'left') // ->join('vehicle', 'policy_transaction.vehicle_id = vehicle.id', 'left') // ->join('policy_type', 'policy_transaction.policy_type_id = policy_type.id', 'left') // ->join('insurers', 'pt_co_share_details.insurer_id = insurers.id', 'left') // ->join('insurer_branch', 'pt_co_share_details.insurer_branch_id = insurer_branch.id', 'left') // ->join('tpa', 'policy_transaction.tpa_id = tpa.id', 'left') // ->join('tpa_branch', 'policy_transaction.tpa_branch_id = tpa_branch.id', 'left') // ->join('user_profiles AS sales_user', 'policy_transaction.sales_generated_by = sales_user.id', 'left') // ->join('user_profiles AS service_user', 'policy_transaction.serviced_by = service_user.id', 'left') // ->where('policy_transaction.is_active', 1) // ->where('pt_co_share_details.is_active', 1); // // Check if the start date and end date are provided // if ($start_date != 0 && $end_date != 0 && $date_type != 0 && $date_type != 'statement_month') { // $startDate = date('Y-m-d 00:00:00', strtotime($start_date)); // $endDate = date('Y-m-d 23:59:59', strtotime($end_date)); // $builder->where('policy_transaction.'.$date_type.'>=', $startDate) // ->where('policy_transaction.'.$date_type.'<=', $endDate); // } // // if($date_type == 'statement_month' && $start_date != 0 && $end_date != 0){ // // $startDate = date('Y-m-d 00:00:00', strtotime($start_date)); // // $endDate = date('Y-m-d 23:59:59', strtotime($end_date)); // // $builder->where('policy_transaction.month >=', $startDate) // // ->where('policy_transaction.month <=', $endDate); // // } // // Conditionally join insurer_statements if $date_type == 'statement_month' // if ($date_type == 'statement_month' && $start_date != 0 && $end_date != 0) { // $startDate = date('Y-m-d', strtotime($start_date)); // $endDate = date('Y-m-d', strtotime($end_date)); // $builder->join('co_share_stmt_details', 'pt_co_share_details.id = co_share_stmt_details.co_share_id', 'left') // ->join('insurer_statements', 'co_share_stmt_details.statement_id = insurer_statements.id','left') // ->where('insurer_statements.is_active', 1) // ->where('insurer_statements.month >=', $startDate) // ->where('insurer_statements.month <=', $endDate) // ->groupBy('co_share_stmt_details.co_share_id'); // } // if ($client_id != 0) { // $builder->where('policy_transaction.client_id', $client_id); // } // if ($insurer_id != 0) { // $builder->where('policy_transaction.insurer_id', $insurer_id); // } // if ($client_branch_id != 0) { // $builder->where('policy_transaction.client_branch_id', $client_branch_id); // } // if ($insurer_branch_id != 0) { // $builder->where('policy_transaction.insurer_branch_id', $insurer_branch_id); // } // if ($client_policy_id != 0) { // $builder->where('policy_transaction.client_policy_id', $client_policy_id); // } // if ($policy_type_id != 0) { // $builder->where('client_policy.policy_type_id', $policy_type_id); // } // if ($issuer != 0) { // $builder->where('policy_transaction.issuer', $issuer); // } // if($client_id == 0 && $insurer_id == 0 && $policy_type_id == 0 && $date_type == 0 && $issuer == 0){ // $fromDate = date('Y-m-d', strtotime('-30 days')); // $toDate = date('Y-m-d 23:59:59'); // $builder->where('policy_transaction.created_at >=', $fromDate) // ->where('policy_transaction.created_at <=', $toDate); // } // $builder->orderBy('policy_transaction.id', 'desc'); // $result = $builder->get()->getResultArray(); // // dd($this->db->getLastQuery()); // return $result; // } public function getBDSReportList1($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0, $client_branch_id = 0, $insurer_branch_id = 0, $client_policy_id = 0, $user_id = 0, $where = []) { $date_condition = ''; if ($date_type == 'statement_month' && $start_date != 0 && $end_date != 0) { $date_condition = " AND insurer_statements.month >= '" . $start_date . "' AND insurer_statements.month <= '" . $end_date . "' "; } $builder = $this->db->table('policy_transaction') ->select(" policy_transaction.*, DATE_FORMAT(policy_transaction.policy_issue_date, '%d %b %Y') AS policy_issue_date, DATE_FORMAT( IF(pt_co_share_details.pt_policy_issue_date IS NULL, policy_transaction.policy_issue_date, pt_co_share_details.pt_policy_issue_date), '%b %Y') AS policy_issue_month, CASE WHEN clients.client_type = 1 THEN 'Group' WHEN clients.client_type = 2 THEN 'Retail' ELSE '-' END AS client_type, CASE WHEN policy_transaction.revenue_type = 'NA' THEN 'Fresh' ELSE 'Renewal' END AS revenue_type, CASE WHEN policy_transaction.action_type = 'inception' THEN 'Policy' ELSE 'Endorsement' END AS action_type, clients.client_name AS client_name, clients.short_name AS client_short_name, client_branch.branch_name AS client_branch_name, client_branch.address1 AS client_address, policy_type.policy_type, policy_type.bap, insurers.name AS insurer_name, insurers.short_name AS insurer_short_name, insurer_branch.branch_name AS insurer_branch_name, insurer_branch.branch_code AS insurer_branch_code, user_profiles.first_name as user_name, vehicle.vehicle_no, tpa.name as tpa_name, pt_co_share_details.remark as remarks, pt_co_share_details.cop_amt as bp_amt, pt_co_share_details.exp_amt, pt_co_share_details.id as pt_id, sales_user.first_name as salse_person_name, service_user.first_name as service_person_name, ROUND((pt_co_share_details.cop_amt + pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt), 2) AS premium_wo_gst, ROUND((ROUND((pt_co_share_details.cop_amt + pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt), 2) * 18 / 100), 2) AS gst_amount_velmurugan, ROUND((ROUND((pt_co_share_details.cop_amt + pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt), 2) + ROUND((ROUND((pt_co_share_details.cop_amt + pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt), 2) * 18 / 100), 2)), 2) AS total_premium_velmurugan, ROUND(COALESCE(tep_gst_amt, 0) + COALESCE(bp_gst_amt, 0) + COALESCE(tp_gst_amt, 0),2) AS gst_amount, ROUND(ROUND(pt_co_share_details.cop_amt + pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt, 2) + ROUND(COALESCE(tep_gst_amt, 0) + COALESCE(bp_gst_amt, 0) + COALESCE(tp_amt, 0),2), 2) AS total_premium, ROUND((pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt), 2) AS tp_or_ter, DATEDIFF(policy_transaction.policy_end_date, CURDATE()) AS days, (pt_co_share_details.agreed_tp_per + pt_co_share_details.agreed_tep_per) AS agreed_tp_or_ter_per, pt_co_share_details.agreed_bp_per, ROUND( ( SELECT ( SUM(co_share_stmt_details.actual_bp_brokerage_amt) + SUM(co_share_stmt_details.actual_tp_brokerage_amt) + SUM(co_share_stmt_details.actual_tep_brokerage_amt) + SUM(co_share_stmt_details.reward) ) AS total_irda_amt FROM co_share_stmt_details JOIN insurer_statements ON co_share_stmt_details.statement_id = insurer_statements.id WHERE co_share_stmt_details.co_share_id = pt_co_share_details.id AND co_share_stmt_details.is_active = 1 AND insurer_statements.is_active = 1 $date_condition ), 2 ) AS total_irda_amt, ROUND( ( SELECT ( SUM(co_share_stmt_details.reward) ) AS reward FROM co_share_stmt_details JOIN insurer_statements ON co_share_stmt_details.statement_id = insurer_statements.id WHERE co_share_stmt_details.co_share_id = pt_co_share_details.id AND co_share_stmt_details.is_active = 1 AND insurer_statements.is_active = 1 $date_condition ), 2 ) AS reward, ROUND( ( SELECT SUM( COALESCE(co_share_stmt_details.actual_bp_brokerage_amt, 0) + COALESCE(co_share_stmt_details.actual_tp_brokerage_amt, 0) + COALESCE(co_share_stmt_details.actual_tep_brokerage_amt, 0) + COALESCE(co_share_stmt_details.reward, 0) ) AS total_irda_amt FROM co_share_stmt_details JOIN pt_co_share_details AS pt_table ON co_share_stmt_details.co_share_id = pt_table.id JOIN insurer_statements ON co_share_stmt_details.statement_id = insurer_statements.id WHERE co_share_stmt_details.co_share_id = pt_co_share_details.id AND co_share_stmt_details.is_active = 1 AND pt_table.is_active = 1 AND insurer_statements.is_active = 1 AND insurer_statements.invoice_status IS NOT NULL $date_condition ), 2 ) AS billed_amt, ROUND( ( ( SELECT SUM( COALESCE(co_share_stmt_details.actual_bp_brokerage_amt, 0) + COALESCE(co_share_stmt_details.actual_tp_brokerage_amt, 0) + COALESCE(co_share_stmt_details.actual_tep_brokerage_amt, 0) + COALESCE(co_share_stmt_details.reward, 0) ) FROM co_share_stmt_details JOIN insurer_statements ON co_share_stmt_details.statement_id = insurer_statements.id WHERE co_share_stmt_details.co_share_id = pt_co_share_details.id AND co_share_stmt_details.is_active = 1 $date_condition ) - ( SELECT SUM( COALESCE(co_share_stmt_details.actual_bp_brokerage_amt, 0) + COALESCE(co_share_stmt_details.actual_tp_brokerage_amt, 0) + COALESCE(co_share_stmt_details.actual_tep_brokerage_amt, 0) + COALESCE(co_share_stmt_details.reward, 0) ) FROM co_share_stmt_details JOIN pt_co_share_details AS pt_table ON co_share_stmt_details.co_share_id = pt_table.id JOIN insurer_statements ON co_share_stmt_details.statement_id = insurer_statements.id WHERE co_share_stmt_details.co_share_id = pt_co_share_details.id AND co_share_stmt_details.is_active = 1 AND pt_table.is_active = 1 AND insurer_statements.is_active = 1 AND insurer_statements.invoice_status IS NULL $date_condition ) ), 2 ) AS unbilled_amt, created_user.first_name as user_name, CASE WHEN pt_co_share_details.co_share_type IN (0, 1) THEN policy_transaction.policy_no WHEN pt_co_share_details.co_share_type > 1 THEN CASE WHEN pt_co_share_details.follower_policy_no IS NULL OR pt_co_share_details.follower_policy_no = '' THEN policy_transaction.policy_no ELSE pt_co_share_details.follower_policy_no END ELSE policy_transaction.policy_no END AS policy_no ") ->join('pt_co_share_details', 'policy_transaction.id = pt_co_share_details.pt_id', 'left') // ->join('insurer_statements', 'pt_co_share_details.statement_id = insurer_statements.id', 'left') ->join('clients', 'clients.id = policy_transaction.client_id') ->join('client_branch', 'policy_transaction.client_branch_id = client_branch.id', 'left') ->join('client_policy', 'policy_transaction.client_policy_id = client_policy.id', 'left') ->join('user_profiles', 'policy_transaction.created_by = user_profiles.id', 'left') ->join('vehicle', 'policy_transaction.vehicle_id = vehicle.id', 'left') ->join('policy_type', 'policy_transaction.policy_type_id = policy_type.id', 'left') ->join('insurers', 'pt_co_share_details.insurer_id = insurers.id', 'left') ->join('insurer_branch', 'pt_co_share_details.insurer_branch_id = insurer_branch.id', 'left') ->join('tpa', 'policy_transaction.tpa_id = tpa.id', 'left') ->join('tpa_branch', 'policy_transaction.tpa_branch_id = tpa_branch.id', 'left') ->join('user_profiles AS sales_user', 'policy_transaction.sales_generated_by = sales_user.id', 'left') ->join('user_profiles AS service_user', 'policy_transaction.serviced_by = service_user.id', 'left') ->join('user_profiles AS created_user', 'policy_transaction.created_by = created_user.id', 'left') ->where('policy_transaction.is_active', 1) ->where('pt_co_share_details.is_active', 1); if ( (!in_array(get_role_id(), [1, 5])) && !( in_array(MANAGEMENT_TEAM_ID, user_team()) || in_array(FINANCE_TEAM_ID, user_team()) || in_array(BUSINESS_TEAM_ID, user_team()) ) ) { if (get_role_id() == 4 && in_array(POS_TEAM_ID, user_team())) { $builder->where('policy_transaction.created_by', get_session_userid()); } } if (!empty($where)) { log_message('info', 'Where condition: ' . json_encode($where)); $builder->where($where); } // Check if the start date and end date are provided if ($start_date != 0 && $end_date != 0 && $date_type != 0 && $date_type != 'statement_month') { $this->validateDateType($date_type); $startDate = date('Y-m-d 00:00:00', strtotime($start_date)); $endDate = date('Y-m-d 23:59:59', strtotime($end_date)); if($date_type == "policy_issue_date"){ $builder->where("pt_co_share_details.pt_policy_issue_date >=", $startDate) ->where("pt_co_share_details.pt_policy_issue_date <=", $endDate); }else{ $builder->where('policy_transaction.' . $date_type . ' >=', $startDate) ->where('policy_transaction.' . $date_type . ' <=', $endDate); } } // if($date_type == 'statement_month' && $start_date != 0 && $end_date != 0){ // $startDate = date('Y-m-d 00:00:00', strtotime($start_date)); // $endDate = date('Y-m-d 23:59:59', strtotime($end_date)); // $builder->where('policy_transaction.month >=', $startDate) // ->where('policy_transaction.month <=', $endDate); // } // Conditionally join insurer_statements if $date_type == 'statement_month' if ($date_type == 'statement_month' && $start_date != 0 && $end_date != 0) { $startDate = date('Y-m-d', strtotime($start_date)); $endDate = date('Y-m-d', strtotime($end_date)); $builder->join('co_share_stmt_details', 'pt_co_share_details.id = co_share_stmt_details.co_share_id', 'left') ->join('insurer_statements', 'co_share_stmt_details.statement_id = insurer_statements.id', 'left') ->where('insurer_statements.is_active', 1) ->where('insurer_statements.month >=', $startDate) ->where('insurer_statements.month <=', $endDate) ->groupBy('co_share_stmt_details.co_share_id'); } if ($client_id != 0) { $builder->where('policy_transaction.client_id', $client_id); } if ($insurer_id != 0) { $builder->where('policy_transaction.insurer_id', $insurer_id); } if ($client_branch_id != 0) { $builder->where('policy_transaction.client_branch_id', $client_branch_id); } if ($insurer_branch_id != 0) { $builder->where('policy_transaction.insurer_branch_id', $insurer_branch_id); } if ($client_policy_id != 0) { $builder->where('policy_transaction.client_policy_id', $client_policy_id); } if ($user_id != 0) { $builder->where('policy_transaction.created_by', $user_id); } if ($policy_type_id != 0) { $builder->where('client_policy.policy_type_id', $policy_type_id); } if ($issuer != 0) { $builder->where('policy_transaction.issuer', $issuer); } if ($client_id == 0 && $insurer_id == 0 && $policy_type_id == 0 && $date_type == 0 && $issuer == 0) { $fromDate = date('Y-m-d', strtotime('-90 days')); $toDate = date('Y-m-d 23:59:59'); if (empty($where)) { $builder->where('policy_transaction.created_at >=', $fromDate) ->where('policy_transaction.created_at <=', $toDate); } } $builder->orderBy('policy_transaction.id', 'desc'); $result = $builder->get()->getResultArray(); // dd($this->db->getLastQuery()); return $result; } // public function getInceptionTranctionListData($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0, $status = 0) // { // // dd($start_date, $end_date, $client_id, $insurer_id, $policy_type_id, $date_type, $issuer, $status); // $builder = $this->db->table('policy_transaction') // ->select(' // policy_transaction.*, // clients.short_name AS client_short_name, // clients.client_code, // clients.client_type, // clients.client_name, // client_branch.branch_name AS client_branch_name, // insurers.name AS insurer_name, // insurers.short_name AS insurer_short_name, // policy_type.policy_type, // pt_co_share_details.agreed_amt AS amount, // pt_co_share_details.bp_amt AS bp, // pt_co_share_details.tp_amt AS tp // ') // ->join('pt_co_share_details', 'policy_transaction.id = pt_co_share_details.pt_id', 'left') // ->join('clients', 'clients.id = policy_transaction.client_id', 'left') // ->join('client_branch', 'policy_transaction.client_branch_id = client_branch.id', 'left') // ->join('insurers', 'pt_co_share_details.insurer_id = insurers.id', 'left') // ->join('client_policy', 'policy_transaction.client_policy_id = client_policy.id', 'left') // ->join('policy_type', 'policy_transaction.policy_type_id = policy_type.id', 'left') // ->where('policy_transaction.is_active', 1) // ->where('policy_transaction.action_type', 'inception'); // if ($start_date != 0 && $end_date != 0 && $date_type != 0) { // $startDate = date('Y-m-d 00:00:00', strtotime($start_date)); // $endDate = date('Y-m-d 23:59:59', strtotime($end_date)); // $builder->where('policy_transaction.'.$date_type.'>=', $startDate) // ->where('policy_transaction.'.$date_type.'<=', $endDate); // }else{ // // $fromDate = date('Y-m-d', strtotime('-30 days')); // // $toDate = date('Y-m-d 23:59:59'); // // $builder->where('policy_transaction.created_at >=', $fromDate) // // ->where('policy_transaction.created_at <=', $toDate); // } // if ($client_id != 0) { // $builder->where('policy_transaction.client_id', $client_id); // } // if ($insurer_id != 0) { // $builder->where('policy_transaction.insurer_id', $insurer_id); // } // if ($policy_type_id != 0) { // $builder->where('client_policy.policy_type_id', $policy_type_id); // } // if ($issuer != 0) { // $builder->where('policy_transaction.issuer', $issuer); // } // if ($status != 0) { // $builder->where('policy_transaction.status', $status); // } // if($client_id == 0 && $insurer_id == 0 && $policy_type_id == 0 && $date_type == 0 && $issuer == 0){ // $fromDate = date('Y-m-d', strtotime('-30 days')); // $toDate = date('Y-m-d 23:59:59'); // $builder->where('policy_transaction.created_at >=', $fromDate) // ->where('policy_transaction.created_at <=', $toDate); // } // $builder->orderBy('policy_transaction.id', 'desc')->limit(10); // $result = $builder->get()->getResultArray(); // // dd($this->db->getLastQuery()); // return $result; // } public function getInceptionTranctionListData($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0, $status = 0, $where = null) { $builder = $this->db->table('policy_transaction') ->select(" policy_transaction.*, clients.short_name AS client_short_name, clients.client_code, clients.client_type, clients.client_name, client_branch.branch_name AS client_branch_name, insurers.name AS insurer_name, insurers.short_name AS insurer_short_name, policy_type.policy_type, pt_co_share_details.agreed_amt AS amount, pt_co_share_details.bp_amt AS bp, pt_co_share_details.tp_amt AS tp, clients.pan, DATE_FORMAT(policy_transaction.created_at, '%d %b %Y %h:%i %p') AS created_at, user_profiles.first_name as user_name, CASE WHEN pt_co_share_details.co_share_type IN (0, 1) THEN policy_transaction.policy_no WHEN pt_co_share_details.co_share_type > 1 THEN CASE WHEN pt_co_share_details.follower_policy_no IS NULL OR pt_co_share_details.follower_policy_no = '' THEN policy_transaction.policy_no ELSE pt_co_share_details.follower_policy_no END ELSE policy_transaction.policy_no END AS policy_no ") ->join('pt_co_share_details', 'policy_transaction.id = pt_co_share_details.pt_id', 'left') ->join('clients', 'clients.id = policy_transaction.client_id', 'left') ->join('client_branch', 'policy_transaction.client_branch_id = client_branch.id', 'left') ->join('insurers', 'pt_co_share_details.insurer_id = insurers.id', 'left') ->join('client_policy', 'policy_transaction.client_policy_id = client_policy.id', 'left') ->join('policy_type', 'policy_transaction.policy_type_id = policy_type.id', 'left') ->join('user_profiles', 'policy_transaction.created_by = user_profiles.id', 'left') ->where('policy_transaction.is_active', 1) ->where('policy_transaction.action_type', 'inception'); // if ( // (!in_array(get_role_id(), [1, 5])) && // !( // in_array(MANAGEMENT_TEAM_ID, user_team()) || // in_array(FINANCE_TEAM_ID, user_team()) || // in_array(BUSINESS_TEAM_ID, user_team()) // ) // ) { // if (get_role_id() == 4 && in_array(POS_TEAM_ID, user_team())) { // $builder->where('policy_transaction.created_by', get_session_userid()); // } // } if ((!in_array(get_role_id(), [1, 5]))) { if (in_array(POS_TEAM_ID, user_team())) { $builder->where('policy_transaction.created_by', get_session_userid()); } } // Optimize Date Filtering if (!empty($start_date) && !empty($end_date) && !empty($date_type)) { $this->validateDateType($date_type); $startDate = change_date_format($start_date, 'd/m/Y', 'Y-m-d 00:00:00'); $endDate = change_date_format($end_date, 'd/m/Y', 'Y-m-d 23:59:59'); if($date_type == "policy_issue_date"){ $builder->where("pt_co_share_details.pt_policy_issue_date >=", $startDate) ->where("pt_co_share_details.pt_policy_issue_date <=", $endDate); }else{ $builder->where("policy_transaction.$date_type >=", $startDate) ->where("policy_transaction.$date_type <=", $startDate); } } // Apply Filters Only When Necessary if (!empty($client_id)) { $builder->where('policy_transaction.client_id', $client_id); } if (!empty($insurer_id)) { $builder->where('policy_transaction.insurer_id', $insurer_id); } if (!empty($policy_type_id)) { $builder->where('client_policy.policy_type_id', $policy_type_id); } if (!empty($issuer)) { $builder->where('policy_transaction.issuer', $issuer); } if (!empty($status)) { $builder->where('policy_transaction.status', $status); } // Default to Last 30 Days if No Filters Are Applied if (empty($client_id) && empty($insurer_id) && empty($policy_type_id) && empty($date_type) && empty($issuer) && empty($where)) { $fromDate = date('Y-m-d', strtotime('-30 days')); $toDate = date('Y-m-d 23:59:59'); $builder->where('policy_transaction.created_at >=', $fromDate) ->where('policy_transaction.created_at <=', $toDate); } if (!empty($where)) { $builder->whereIn('policy_transaction.id', $where); } // Optimize Query Execution $builder->orderBy('policy_transaction.id', 'desc'); $data = $builder->get()->getResultArray(); // dd($this->db->getLastQuery()); return $data; } public function getCachedInceptionTranctionListData(array $filters): array { $cacheKey = 'inception_list_v1_' . md5(json_encode($filters)); $cache = \Config\Services::cache(); $cached = $cache->get($cacheKey); if (is_array($cached) && isset($cached['rows'], $cached['expires_at'])) { return $cached; } $ttl = 300; $rows = $this->getInceptionTranctionListData( $filters['start_date'] ?? 0, $filters['end_date'] ?? 0, $filters['client_id'] ?? 0, $filters['insurer_id'] ?? 0, $filters['policy_type_id'] ?? 0, $filters['date_type'] ?? 0, $filters['issuer'] ?? 0, $filters['status'] ?? 0, $filters['ids'] ?? null ); $payload = [ 'rows' => $rows, 'expires_at' => time() + $ttl, ]; $cache->save($cacheKey, $payload, $ttl); return $payload; } public function filterInceptionTranctionRowsBySearch(array $rows, string $searchValue): array { $needle = mb_strtolower(trim($searchValue)); if ($needle === '') { return $rows; } $issuerMap = [1 => 'jibs', 2 => 'nhance']; $issueTypeMap = [1 => 'fresh', 2 => 'renewal', 3 => 'roll over']; $clientTypeMap = [1 => 'group', 2 => 'individual']; $statusMap = [ 'under_process' => 'under process', 'client_pending' => 'client pending', 'insurer_pending' => 'insurer pending', 'co_insurer_pending' => 'co-insurer pending', 'tpa_pending' => 'tpa pending', 'validated' => 'validated', 'cancelled' => 'cancelled', 'instalment_pending' => 'instalment pending', 'completed' => 'completed', 'lost' => 'lost', ]; $fields = [ 'client_name', 'client_short_name', 'client_branch_name', 'insurer_short_name', 'policy_type', 'policy_no', 'user_name', 'status', 'pan', ]; return array_values(array_filter($rows, static function (array $row) use ($needle, $fields, $issuerMap, $issueTypeMap, $clientTypeMap, $statusMap) { foreach ($fields as $field) { $value = $row[$field] ?? ''; if ($value !== '' && mb_strpos(mb_strtolower((string) $value), $needle) !== false) { return true; } } // Search by rendered labels shown in list columns. $issuerText = $issuerMap[(int) ($row['issuer'] ?? 0)] ?? ''; if ($issuerText !== '' && mb_strpos($issuerText, $needle) !== false) { return true; } $issueTypeText = $issueTypeMap[(int) ($row['issue_type'] ?? 0)] ?? ''; if ($issueTypeText !== '' && mb_strpos($issueTypeText, $needle) !== false) { return true; } $clientTypeText = $clientTypeMap[(int) ($row['client_type'] ?? 0)] ?? ''; if ($clientTypeText !== '' && mb_strpos($clientTypeText, $needle) !== false) { return true; } $statusCode = (string) ($row['status'] ?? ''); $statusText = $statusMap[$statusCode] ?? ''; if ($statusText !== '' && mb_strpos($statusText, $needle) !== false) { return true; } return false; })); } public function getInceptionTranctionListDataTable(int $draw, int $start, int $length, string $searchValue, array $filters): array { $cached = $this->getCachedInceptionTranctionListData($filters); $allRows = $cached['rows'] ?? []; $recordsTotal = count($allRows); if ($searchValue !== '') { $allRows = $this->filterInceptionTranctionRowsBySearch($allRows, $searchValue); } $recordsFiltered = count($allRows); if ($length < 0) { $length = $recordsFiltered; } $pageRows = $length > 0 ? array_slice(array_values($allRows), $start, $length) : array_values($allRows); return [ 'draw' => $draw, 'recordsTotal' => $recordsTotal, 'recordsFiltered' => $recordsFiltered, 'data' => $pageRows, 'cache_expires_in_ms' => max(0, (($cached['expires_at'] ?? time()) - time()) * 1000), ]; } public function getEndorsementTranctionListData($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0, $status = 0) { // dd($start_date, $end_date, $client_id, $insurer_id, $policy_type_id, $date_type, $issuer, $status); $builder = $this->db->table('policy_transaction') ->select(" policy_transaction.*, clients.short_name as client_short_name, clients.client_code, client_branch.branch_name as client_branch_name, insurers.name AS insurer_name, insurers.short_name AS insurer_short_name, policy_type.policy_type , CASE WHEN pt_co_share_details.co_share_type IN (0, 1) THEN policy_transaction.policy_no WHEN pt_co_share_details.co_share_type > 1 THEN CASE WHEN pt_co_share_details.follower_policy_no IS NULL OR pt_co_share_details.follower_policy_no = '' THEN policy_transaction.policy_no ELSE pt_co_share_details.follower_policy_no END ELSE policy_transaction.policy_no END AS policy_no ") ->join('pt_co_share_details', 'policy_transaction.id = pt_co_share_details.pt_id', 'left') ->join('clients', 'policy_transaction.client_id = clients.id', 'left') ->join('client_branch', 'policy_transaction.client_branch_id = client_branch.id', 'left') ->join('insurers', 'pt_co_share_details.insurer_id = insurers.id', 'left') ->join('client_policy', 'policy_transaction.client_policy_id = client_policy.id', 'left') ->join('policy_type', 'policy_transaction.policy_type_id = policy_type.id', 'left') ->where('policy_transaction.is_active', 1) ->where('policy_transaction.action_type !=', 'inception'); // if ( // (!in_array(get_role_id(), [1, 5])) && // !( // in_array(MANAGEMENT_TEAM_ID, user_team()) || // in_array(FINANCE_TEAM_ID, user_team()) || // in_array(BUSINESS_TEAM_ID, user_team()) // ) // ) { // if (get_role_id() == 4 && in_array(POS_TEAM_ID, user_team())) { // $builder->where('policy_transaction.created_by', get_session_userid()); // } // } if ((!in_array(get_role_id(), [1, 5]))) { if (in_array(POS_TEAM_ID, user_team())) { $builder->where('policy_transaction.created_by', get_session_userid()); } } if ($start_date != 0 && $end_date != 0 && $date_type != 0) { $this->validateDateType($date_type); $startDate = change_date_format($start_date, 'd/m/Y', 'Y-m-d 00:00:00'); $endDate = change_date_format($end_date, 'd/m/Y', 'Y-m-d 23:59:59'); if($date_type == "policy_issue_date"){ $builder->where("pt_co_share_details.pt_policy_issue_date >=", $startDate) ->where("pt_co_share_details.pt_policy_issue_date <=", $endDate); }else{ $builder->where('policy_transaction.' . $date_type . ' >=', $startDate) ->where('policy_transaction.' . $date_type . ' <=', $endDate); } } else { // $fromDate = date('Y-m-d', strtotime('-30 days')); // $toDate = date('Y-m-d 23:59:59'); // $builder->where('policy_transaction.created_at >=', $fromDate) // ->where('policy_transaction.created_at <=', $toDate); } if ($client_id != 0) { $builder->where('policy_transaction.client_id', $client_id); } if ($insurer_id != 0) { $builder->where('policy_transaction.insurer_id', $insurer_id); } if ($policy_type_id != 0) { $builder->where('client_policy.policy_type_id', $policy_type_id); } if ($issuer != 0) { $builder->where('policy_transaction.issuer', $issuer); } if ($status != 0) { $builder->where('policy_transaction.status', $status); } if ($client_id == 0 && $insurer_id == 0 && $policy_type_id == 0 && $date_type == 0 && $issuer == 0) { $fromDate = date('Y-m-d', strtotime('-90 days')); $toDate = date('Y-m-d 23:59:59'); $builder->where('policy_transaction.created_at >=', $fromDate) ->where('policy_transaction.created_at <=', $toDate); } $builder->orderBy('policy_transaction.id', 'desc'); // dd($this->db->getLastQuery()); return $builder->get()->getResultArray(); } public function getCachedEndorsementTranctionListData(array $filters): array { $cacheKey = 'endorsement_list_v1_' . md5(json_encode($filters)); $cache = \Config\Services::cache(); $cached = $cache->get($cacheKey); if (is_array($cached) && isset($cached['rows'], $cached['expires_at'])) { return $cached; } $ttl = 300; $rows = $this->getEndorsementTranctionListData( $filters['start_date'] ?? 0, $filters['end_date'] ?? 0, $filters['client_id'] ?? 0, $filters['insurer_id'] ?? 0, $filters['policy_type_id'] ?? 0, $filters['date_type'] ?? 0, $filters['issuer'] ?? 0, $filters['status'] ?? 0 ); $payload = [ 'rows' => $rows, 'expires_at' => time() + $ttl, ]; $cache->save($cacheKey, $payload, $ttl); return $payload; } public function filterEndorsementTranctionRowsBySearch(array $rows, string $searchValue): array { $needle = mb_strtolower(trim($searchValue)); if ($needle === '') { return $rows; } $issuerMap = [1 => 'jibs', 2 => 'nhance']; $statusMap = [ 'under_process' => 'under process', 'client_pending' => 'client pending', 'insurer_pending' => 'insurer pending', 'co_insurer_pending' => 'co-insurer pending', 'tpa_pending' => 'tpa pending', 'validated' => 'validated', 'cancelled' => 'cancelled', 'instalment_pending' => 'instalment pending', 'completed' => 'completed', ]; $actionTypeMap = [ 'addition' => 'addition', 'deletion' => 'deletion', 'addition_deletion' => 'addition & deletion', 'si_enhancement' => 'si enhancement', 'combo_a_d_si' => 'combo a, d & si', 'correction' => 'correction', 'baby_addition' => 'baby addition', 'policy_instalment' => 'policy instalment', 'addition_inception' => 'addition-inception', 'bds_correction' => 'bds correction', 'policy_correction' => 'policy correction', 'policy_cancellation' => 'policy cancellation', ]; $fields = [ 'client_short_name', 'client_branch_name', 'insurer_short_name', 'policy_type', 'endorsement_no', 'policy_no', ]; return array_values(array_filter($rows, static function (array $row) use ($needle, $fields, $issuerMap, $statusMap, $actionTypeMap) { foreach ($fields as $field) { $value = $row[$field] ?? ''; if ($value !== '' && mb_strpos(mb_strtolower((string) $value), $needle) !== false) { return true; } } $issuerText = $issuerMap[(int) ($row['issuer'] ?? 0)] ?? ''; if ($issuerText !== '' && mb_strpos($issuerText, $needle) !== false) { return true; } $statusText = $statusMap[(string) ($row['status'] ?? '')] ?? ''; if ($statusText !== '' && mb_strpos($statusText, $needle) !== false) { return true; } $actionTypeText = $actionTypeMap[(string) ($row['action_type'] ?? '')] ?? ''; if ($actionTypeText !== '' && mb_strpos($actionTypeText, $needle) !== false) { return true; } return false; })); } public function getEndorsementTranctionListDataTable(int $draw, int $start, int $length, string $searchValue, array $filters): array { $cached = $this->getCachedEndorsementTranctionListData($filters); $allRows = $cached['rows'] ?? []; $recordsTotal = count($allRows); if ($searchValue !== '') { $allRows = $this->filterEndorsementTranctionRowsBySearch($allRows, $searchValue); } $recordsFiltered = count($allRows); if ($length < 0) { $length = $recordsFiltered; } $pageRows = $length > 0 ? array_slice(array_values($allRows), $start, $length) : array_values($allRows); return [ 'draw' => $draw, 'recordsTotal' => $recordsTotal, 'recordsFiltered' => $recordsFiltered, 'data' => $pageRows, 'cache_expires_in_ms' => max(0, (($cached['expires_at'] ?? time()) - time()) * 1000), ]; } public function getVarienceReportLIst($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0, $client_branch_id = 0, $insurer_branch_id = 0, $client_policy_id = 0) { $builder = $this->db->table('policy_transaction') ->select(" policy_transaction.id, clients.client_name, client_branch.branch_name as client_branch_name, insurers.name AS insurer_name, insurer_branch.branch_name AS insurer_branch_name, policy_type.policy_type, policy_transaction.policy_no, policy_transaction.endorsement_no, pt_co_share_details.exp_amt, pt_co_share_details.variance, ROUND ( (pt_co_share_details.cop_amt + pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt),2) as original_premium, ROUND( ( SELECT ( SUM(co_share_stmt_details.actual_bp_amt) + SUM(co_share_stmt_details.actual_tp_amt) + SUM(co_share_stmt_details.actual_tep_amt) ) AS total_stmt_amt FROM co_share_stmt_details JOIN insurer_statements ON co_share_stmt_details.statement_id = insurer_statements.id and insurer_statements.is_active = 1 WHERE co_share_stmt_details.co_share_id = pt_co_share_details.id AND co_share_stmt_details.is_active = 1 ), 2 ) AS statement_premium, COALESCE( (pt_co_share_details.cop_amt + pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt), 0 ) - COALESCE( ( SELECT SUM(co_share_stmt_details.actual_bp_amt) + SUM(co_share_stmt_details.actual_tp_amt) + SUM(co_share_stmt_details.actual_tep_amt) FROM co_share_stmt_details JOIN insurer_statements ON co_share_stmt_details.statement_id = insurer_statements.id AND insurer_statements.is_active = 1 WHERE co_share_stmt_details.co_share_id = pt_co_share_details.id AND co_share_stmt_details.is_active = 1 ), 0 ) AS premium_variance_amt, ROUND( ( SELECT ( SUM(co_share_stmt_details.actual_bp_brokerage_amt) + SUM(co_share_stmt_details.actual_tp_brokerage_amt) + SUM(co_share_stmt_details.actual_tep_brokerage_amt) + SUM(co_share_stmt_details.reward) ) AS total_irda_amt FROM co_share_stmt_details JOIN insurer_statements ON co_share_stmt_details.statement_id = insurer_statements.id and insurer_statements.is_active = 1 WHERE co_share_stmt_details.co_share_id = pt_co_share_details.id AND co_share_stmt_details.is_active = 1 ), 2 ) AS statement_amount, ROUND( pt_co_share_details.exp_amt - ( SELECT ( SUM(co_share_stmt_details.actual_bp_brokerage_amt) + SUM(co_share_stmt_details.actual_tp_brokerage_amt) + SUM(co_share_stmt_details.actual_tep_brokerage_amt) + SUM(co_share_stmt_details.reward) ) FROM co_share_stmt_details JOIN insurer_statements ON co_share_stmt_details.statement_id = insurer_statements.id and insurer_statements.is_active = 1 WHERE co_share_stmt_details.co_share_id = pt_co_share_details.id AND co_share_stmt_details.is_active = 1 ), 2 ) AS variance_amt, CASE WHEN pt_co_share_details.co_share_type IN (0, 1) THEN policy_transaction.policy_no WHEN pt_co_share_details.co_share_type > 1 THEN CASE WHEN pt_co_share_details.follower_policy_no IS NULL OR pt_co_share_details.follower_policy_no = '' THEN policy_transaction.policy_no ELSE pt_co_share_details.follower_policy_no END ELSE policy_transaction.policy_no END AS policy_no ") ->join('pt_co_share_details', 'policy_transaction.id = pt_co_share_details.pt_id', 'left') ->join('insurer_statements', 'pt_co_share_details.statement_id = insurer_statements.id', 'left') ->join('clients', 'clients.id = policy_transaction.client_id', 'left') ->join('client_branch', 'client_branch.id = policy_transaction.client_branch_id', 'left') ->join('insurers', 'pt_co_share_details.insurer_id = insurers.id', 'left') ->join('insurer_branch', 'pt_co_share_details.insurer_branch_id = insurer_branch.id', 'left') ->join('client_policy', 'policy_transaction.client_policy_id = client_policy.id', 'left') ->join('policy_type', 'policy_transaction.policy_type_id = policy_type.id', 'left') ->where('policy_transaction.is_active', 1) ->where('pt_co_share_details.is_active', 1) // ->where('insurer_statements.is_active',1); // ->having('variance_amt IS NOT NULL') // ->having('variance_amt !=',0) // ->having('premium_variance_amt IS NOT NULL') // ->having('premium_variance_amt !=',0); // ->group_start() ->having('variance_amt IS NOT NULL') ->orHaving('variance_amt !=', 0) ->having('premium_variance_amt IS NOT NULL') ->orHaving('premium_variance_amt !=', 0); // ->group_end(); // ->where('pt_co_share_details.actual_bp_brokerage_amt IS NOT NULL AND pt_co_share_details.actual_bp_brokerage_amt != 0'); // ->where('pt_co_share_details.variance IS NOT NULL') // ->where('pt_co_share_details.variance !=', 0); if ($start_date != 0 && $end_date != 0 && $date_type != 0) { $this->validateDateType($date_type); $startDate = date('Y-m-d 00:00:00', strtotime($start_date)); $endDate = date('Y-m-d 23:59:59', strtotime($end_date)); if($date_type == "policy_issue_date"){ $builder->where("pt_co_share_details.pt_policy_issue_date >=", $startDate) ->where("pt_co_share_details.pt_policy_issue_date <=", $endDate); }else{ $builder->where('policy_transaction.' . $date_type . ' >=', $startDate) ->where('policy_transaction.' . $date_type . ' <=', $endDate); } } else { $fromDate = date('Y-m-d', strtotime('-90 days')); $toDate = date('Y-m-d 23:59:59'); $builder->where('policy_transaction.created_at >=', $fromDate) ->where('policy_transaction.created_at <=', $toDate); } if ($client_id != 0) { $builder->where('policy_transaction.client_id', $client_id); } if ($insurer_id != 0) { $builder->where('policy_transaction.insurer_id', $insurer_id); } if ($policy_type_id != 0) { $builder->where('client_policy.policy_type_id', $policy_type_id); } if ($issuer != 0) { $builder->where('policy_transaction.issuer', $issuer); } if ($client_branch_id != 0) { $builder->where('policy_transaction.client_branch_id', $client_branch_id); } if ($insurer_branch_id != 0) { $builder->where('policy_transaction.insurer_branch_id', $insurer_branch_id); } if ($client_policy_id != 0) { $builder->where('policy_transaction.client_policy_id', $client_policy_id); } $builder->orderBy('policy_transaction.id', 'desc'); $return_data = $builder->get()->getResultArray(); // dd(db_connect()->getLastQuery()); return $return_data; } public function getBusinessReportList($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0, $status = 0) { $dateThreshold = date('Y-m-d H:i:s', strtotime("- 3 days")); $builder = $this->db->table('policy_transaction') ->select([ 'policy_transaction.id AS policy_trns_id', 'clients.client_name', 'insurers.name AS insurer_name', 'policy_type.policy_type', 'policy_transaction.endorsement_no', "CASE WHEN policy_transaction.action_type = 'inception' THEN 'I' ELSE 'E' END AS action_type", 'policy_transaction.action_type as action_type_full', 'pt_co_share_details.bp_amt', 'pt_co_share_details.tp_amt', 'pt_co_share_details.tep_amt', 'policy_transaction.status', 'CASE WHEN pt_co_share_details.co_share_type IN (0, 1) THEN policy_transaction.policy_no WHEN pt_co_share_details.co_share_type > 1 THEN CASE WHEN pt_co_share_details.follower_policy_no IS NULL OR pt_co_share_details.follower_policy_no = "" THEN policy_transaction.policy_no ELSE pt_co_share_details.follower_policy_no END ELSE policy_transaction.policy_no END AS policy_no' ]) ->join('pt_co_share_details', 'policy_transaction.id = pt_co_share_details.pt_id', 'left') ->join('clients', 'clients.id = policy_transaction.client_id', 'left') ->join('insurers', 'pt_co_share_details.insurer_id = insurers.id', 'left') ->join('client_policy', 'policy_transaction.client_policy_id = client_policy.id', 'left') ->join('policy_type', 'policy_transaction.policy_type_id = policy_type.id', 'left') ->join( '(SELECT policy_tran_id, MAX(created_at) AS last_policy_status_change,is_active FROM policy_transaction_status WHERE is_active = 1 GROUP BY policy_tran_id) th', 'policy_transaction.id = th.policy_tran_id' ) ->where("th.last_policy_status_change <= '{$dateThreshold}'", null, false) ->where('policy_transaction.is_active', 1) ->where("policy_transaction.status is not null", null, false) ->whereNotIn("policy_transaction.status", ['completed']) // ->where('policy_transaction.status', 'completed') ->where('(pt_co_share_details.bp_amt IS NULL OR pt_co_share_details.bp_amt = 0)', null, false); if ($start_date != 0 && $end_date != 0 && $date_type != 0) { $this->validateDateType($date_type); $startDate = date('Y-m-d 00:00:00', strtotime($start_date)); $endDate = date('Y-m-d 23:59:59', strtotime($end_date)); if($date_type == "policy_issue_date"){ $builder->where("pt_co_share_details.pt_policy_issue_date >=", $startDate) ->where("pt_co_share_details.pt_policy_issue_date <=", $endDate); }else{ $builder->where('policy_transaction.' . $date_type . ' >=', $startDate) ->where('policy_transaction.' . $date_type . ' <=', $endDate); } } else { $fromDate = date('Y-m-d', strtotime('-90 days')); $toDate = date('Y-m-d 23:59:59'); $builder->where('policy_transaction.created_at >=', $fromDate) ->where('policy_transaction.created_at <=', $toDate); } if ($client_id != 0) { $builder->where('policy_transaction.client_id', $client_id); } if ($insurer_id != 0) { $builder->where('policy_transaction.insurer_id', $insurer_id); } if ($policy_type_id != 0) { $builder->where('client_policy.policy_type_id', $policy_type_id); } if ($issuer != 0) { $builder->where('policy_transaction.issuer', $issuer); } if ($status != 0) { $builder->where('policy_transaction.status', $status); } $builder->orderBy('policy_transaction.id', 'desc'); // echo $builder->getCompiledSelect(); // exit; $returnData = $builder->get()->getResultArray(); // dd($returnData); return $returnData; } public function getFinanceReportList($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0, $status = 0) { $dateThreshold = date('Y-m-d H:i:s', strtotime("-90 days")); $builder = $this->db->table('policy_transaction') ->select(" policy_transaction.id, clients.client_name, insurers.name AS insurer_name, policy_type.policy_type, policy_transaction.policy_no, policy_transaction.endorsement_no, CASE WHEN policy_transaction.action_type = 'inception' THEN 'I' ELSE 'E' END AS action_type, policy_transaction.action_type AS action_type_full, pt_co_share_details.exp_amt, pt_co_share_details.variance, policy_transaction.status, CASE WHEN pt_co_share_details.co_share_type IN (0, 1) THEN policy_transaction.policy_no WHEN pt_co_share_details.co_share_type > 1 THEN CASE WHEN pt_co_share_details.follower_policy_no IS NULL OR pt_co_share_details.follower_policy_no = '' THEN policy_transaction.policy_no ELSE pt_co_share_details.follower_policy_no END ELSE policy_transaction.policy_no END AS policy_no ") ->join('pt_co_share_details', 'policy_transaction.id = pt_co_share_details.pt_id', 'left') ->join('clients', 'clients.id = policy_transaction.client_id', 'left') ->join('insurers', 'pt_co_share_details.insurer_id = insurers.id', 'left') ->join('client_policy', 'policy_transaction.client_policy_id = client_policy.id', 'left') ->join('policy_type', 'policy_transaction.policy_type_id = policy_type.id', 'left') ->join( '(SELECT policy_tran_id, MAX(created_at) AS last_policy_status_change,is_active FROM policy_transaction_status WHERE is_active = 1 GROUP BY policy_tran_id) th', 'policy_transaction.id = th.policy_tran_id' ) ->where("th.last_policy_status_change <= '{$dateThreshold}'", null, false) ->where('policy_transaction.is_active', 1) // ->where('policy_transaction.status', 'completed') ->where('COALESCE(pt_co_share_details.agreed_bp_per, 0) + COALESCE(pt_co_share_details.agreed_tp_per, 0) + COALESCE(pt_co_share_details.agreed_tep_per, 0) = 0') ->where('COALESCE(pt_co_share_details.actual_bp_amt, 0) + COALESCE(pt_co_share_details.actual_tp_amt, 0) + COALESCE(pt_co_share_details.actual_tep_amt, 0) = 0') ->where('COALESCE(pt_co_share_details.actual_bp_brokerage_amt, 0) + COALESCE(pt_co_share_details.actual_tp_brokerage_amt, 0) + COALESCE(pt_co_share_details.actual_tep_brokerage_amt, 0) = 0') ->where("policy_transaction.status is not null", null, false) ->whereNotIn("policy_transaction.status", ['completed']); if ($start_date != 0 && $end_date != 0 && $date_type != 0) { $this->validateDateType($date_type); $startDate = date('Y-m-d 00:00:00', strtotime($start_date)); $endDate = date('Y-m-d 23:59:59', strtotime($end_date)); if($date_type == "policy_issue_date"){ $builder->where("pt_co_share_details.pt_policy_issue_date >=", $startDate) ->where("pt_co_share_details.pt_policy_issue_date <=", $endDate); }else{ $builder->where('policy_transaction.' . $date_type . ' >=', $startDate) ->where('policy_transaction.' . $date_type . ' <=', $endDate); } } else { $fromDate = date('Y-m-d', strtotime('-90 days')); $toDate = date('Y-m-d 23:59:59'); $builder->where('policy_transaction.created_at >=', $fromDate) ->where('policy_transaction.created_at <=', $toDate); } if ($client_id != 0) { $builder->where('policy_transaction.client_id', $client_id); } if ($insurer_id != 0) { $builder->where('policy_transaction.insurer_id', $insurer_id); } if ($policy_type_id != 0) { $builder->where('client_policy.policy_type_id', $policy_type_id); } if ($issuer != 0) { $builder->where('policy_transaction.issuer', $issuer); } if ($status != 0) { $builder->where('policy_transaction.status', $status); } $builder->orderBy('policy_transaction.id', 'desc'); return $builder->get()->getResultArray(); } public function getOutstandingReportList_OLD($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0, $status = 0) { $builder = $this->db->table('policy_transaction') ->select(" policy_transaction.id, clients.client_name, insurers.name AS insurer_name, policy_type.policy_type, policy_transaction.endorsement_no, CASE WHEN policy_transaction.action_type = 'inception' THEN 'I' ELSE 'E' END AS action_type, pt_co_share_details.exp_amt, pt_co_share_details.variance, insurer_statements.invoice_amount, insurer_statements.invoice_status, ROUND((pt_co_share_details.actual_bp_brokerage_amt + pt_co_share_details.actual_tp_brokerage_amt + pt_co_share_details.actual_tep_brokerage_amt), 2) AS realization_amount2, ( SELECT (SUM(inv_payment_details.inv_amt) + SUM(inv_payment_details.tds)) AS realization_amount FROM inv_payment_details WHERE inv_payment_details.statement_id = insurer_statements.id AND inv_payment_details.is_active = 1 ) AS realization_amount, ROUND( insurer_statements.invoice_amount - ( SELECT (SUM(inv_payment_details.inv_amt) + SUM(inv_payment_details.tds)) FROM inv_payment_details WHERE inv_payment_details.statement_id = insurer_statements.id AND inv_payment_details.is_active = 1 ), 2) AS outstanding_amount, CASE WHEN pt_co_share_details.co_share_type IN (0, 1) THEN policy_transaction.policy_no WHEN pt_co_share_details.co_share_type > 1 THEN CASE WHEN pt_co_share_details.follower_policy_no IS NULL OR pt_co_share_details.follower_policy_no = '' THEN policy_transaction.policy_no ELSE pt_co_share_details.follower_policy_no END ELSE policy_transaction.policy_no END AS policy_no ") ->join('pt_co_share_details', 'policy_transaction.id = pt_co_share_details.pt_id', 'left') ->join('insurer_statements', 'pt_co_share_details.statement_id = insurer_statements.id', 'left') ->join('inv_payment_details', 'insurer_statements.id = inv_payment_details.statement_id', 'left') ->join('clients', 'clients.id = policy_transaction.client_id', 'left') ->join('insurers', 'pt_co_share_details.insurer_id = insurers.id', 'left') ->join('client_policy', 'policy_transaction.client_policy_id = client_policy.id', 'left') ->join('policy_type', 'policy_transaction.policy_type_id = policy_type.id', 'left') ->where('policy_transaction.is_active', 1); // Date range filtering if ($start_date != 0 && $end_date != 0 && $date_type != 0) { $this->validateDateType($date_type); $startDate = date('Y-m-d 00:00:00', strtotime($start_date)); $endDate = date('Y-m-d 23:59:59', strtotime($end_date)); if($date_type == "policy_issue_date"){ $builder->where("pt_co_share_details.pt_policy_issue_date >=", $startDate) ->where("pt_co_share_details.pt_policy_issue_date <=", $endDate); }else{ $builder->where('policy_transaction.' . $date_type . ' >=', $startDate) ->where('policy_transaction.' . $date_type . ' <=', $endDate); } } else { $fromDate = date('Y-m-d', strtotime('-90 days')); $toDate = date('Y-m-d 23:59:59'); $builder->where('policy_transaction.created_at >=', $fromDate) ->where('policy_transaction.created_at <=', $toDate); } // Additional filters if ($client_id != 0) { $builder->where('policy_transaction.client_id', $client_id); } if ($insurer_id != 0) { $builder->where('policy_transaction.insurer_id', $insurer_id); } if ($policy_type_id != 0) { $builder->where('client_policy.policy_type_id', $policy_type_id); } if ($issuer != 0) { $builder->where('policy_transaction.issuer', $issuer); } if ($status != 0) { $builder->where('policy_transaction.status', $status); } // Filter where outstanding_amount is not null $builder->having('outstanding_amount IS NOT NULL'); $builder->orderBy('policy_transaction.id', 'desc'); return $builder->get()->getResultArray(); } public function getOutstandingReportList($start_date = 0, $end_date = 0, $insurer_id = 0, $insurer_branch_id = 0) { $builder = $this->db->table('insurer_statements s') ->select(' s.id, s.insurer_id, s.branch_id, ins.short_name, ib.branch_name, s.month, s.line_items, s.stmt_sno, s.invoice_status, s.invoice_date, s.invoice_no, s.invoice_amount, COALESCE(SUM(p.inv_amt) + SUM(p.tds) + SUM(p.gst), 0) AS total_paid, (s.invoice_amount - COALESCE(SUM(p.inv_amt) + SUM(p.tds) + SUM(p.gst), 0)) AS outstanding_amount ') ->join('inv_payment_details p', 's.id = p.statement_id', 'left') ->join('insurers ins', 's.insurer_id = ins.id') ->join('insurer_branch ib', 's.branch_id = ib.id') ->where('s.is_active', 1) ->where('p.is_active', 1) ->groupBy('s.id, s.invoice_no, s.invoice_date, s.invoice_amount') ->having('outstanding_amount >', 0); // ->get(); // Date range filtering if ($start_date != 0 && $end_date != 0) { $builder->where('s.month >=', $start_date) ->where('s.month <=', $end_date); } if ($insurer_id != 0) { $builder->where('s.insurer_id', $insurer_id); } if ($insurer_branch_id != 0) { $builder->where('s.branch_id', $insurer_branch_id); } $builder->orderBy('s.id', 'desc'); return $builder->get()->getResultArray(); } //function for fetch renewal report data public function getRenewalReportData($start_date = null, $end_date = null, $client_type = null, $client = null, $issuer_branch = null) { $fromDate = date('Y-m-d', strtotime('-90 days')); $toDate = date('Y-m-d 23:59:59'); if (!empty($start_date) && !empty($end_date)) { $fromDate = change_date_format($start_date); $toDate = change_date_format($end_date); } $query = $this->db->table('policy_transaction pt') ->select(' pt.*, c.client_name, c.short_name AS client_short_name, c.client_type, policy_type.policy_type, i.name as insurer_name, ib.branch_name as insurer_branch_name, vehicle.vehicle_no, leads.status as lead_status ') ->join('clients c', 'pt.client_id = c.id', 'left') ->join('pt_co_share_details pt_co', 'pt.id = pt_co.pt_id and pt_co.co_share_type = 1', 'left') ->join('insurers i', 'pt_co.insurer_id = i.id', 'left') ->join('insurer_branch ib', 'pt_co.insurer_branch_id = ib.id', 'left') ->join('policy_type', 'pt.policy_type_id = policy_type.id', 'left') ->join('vehicle', 'pt.vehicle_id = vehicle.id and vehicle.is_active = 1', 'left') ->join('leads', 'pt.client_policy_id = leads.source_policy_id and leads.source_policy_id != 0 and leads.is_active = 1', 'left') ->where('pt.renewal_date >=', $fromDate) ->where('pt.renewal_date <=', $toDate) ->where('pt.is_active', 1) ->where('pt_co.is_active', 1) ->where('pt.action_type', "inception") ->where("NOT EXISTS (SELECT 1 FROM policy_transaction p2 WHERE p2.source_client_policy_id = pt.client_policy_id AND p2.is_active = 1)"); // Apply filters if parameters are provided if (!empty($client_type)) { $query->where('c.client_type', $client_type); } if (!empty($client)) { $query->where('pt.client_id', $client); } if (!empty($issuer_branch)) { // Corrected condition to check $issuer $query->where('pt.issuer_branch', $issuer_branch); } $query->groupBy('pt.id'); $query->orderBy('pt.id', 'DESC'); // Fetch and return results $results = $query->get()->getResultArray(); // print($this->db->getLastQuery()); die; return $results; } public function getRenewalReportDataOld($start_date = null, $end_date = null, $client_type = null, $client = null, $issuer = null) { $fromDate = date('Y-m-d', strtotime('-90 days')); $toDate = date('Y-m-d 23:59:59'); if (!empty($start_date) && !empty($end_date)) { $fromDate = change_date_format($start_date); $toDate = change_date_format($end_date); } $query = $this->db->table('policy_transaction pt') ->select(' pt.*, c.client_name, c.short_name AS client_short_name, c.client_type, policy_type.policy_type, i.name as insurer_name, ib.branch_name as insurer_branch_name, vehicle.vehicle_no, leads.status as lead_status ') ->join('clients c', 'pt.client_id = c.id', 'left') ->join('pt_co_share_details pt_co', 'pt.id = pt_co.pt_id and pt_co.co_share_type = 1', 'left') ->join('insurers i', 'pt_co.insurer_id = i.id', 'left') ->join('insurer_branch ib', 'pt_co.insurer_branch_id = ib.id', 'left') ->join('policy_type', 'pt.policy_type_id = policy_type.id', 'left') ->join('vehicle', 'pt.vehicle_id = vehicle.id and vehicle.is_active = 1', 'left') ->join('leads', 'pt.client_policy_id = leads.source_policy_id and leads.source_policy_id != 0 and leads.is_active = 1', 'left') ->where('pt.policy_end_date >=', $fromDate) ->where('pt.policy_end_date <=', $toDate) ->where('pt.is_active', 1) ->where('pt_co.is_active', 1) ->where('pt.action_type', "inception"); // Apply filters if parameters are provided if (!empty($client_type)) { $query->where('c.client_type', $client_type); } if (!empty($client)) { $query->where('pt.client_id', $client); } if (!empty($issuer)) { // Corrected condition to check $issuer $query->where('pt.issuer', $issuer); } $query->groupBy('pt.id'); $query->orderBy('pt.id', 'DESC'); // Fetch and return results $results = $query->get()->getResultArray(); // print($this->db->getLastQuery()); die; return $results; } public function getBDSRenewalData() { // Increase GROUP_CONCAT limit $this->db->query("SET SESSION group_concat_max_len = 1000000;"); $builder = $this->db->table('policy_transaction pt'); $builder->select([ 'SUM(CASE WHEN pt.policy_end_date < CURDATE() THEN 1 ELSE 0 END) AS Expired', 'SUM(CASE WHEN pt.policy_end_date BETWEEN CURDATE() AND (CURDATE() + INTERVAL 1 MONTH) THEN 1 ELSE 0 END) AS `Renewal Pending`', 'GROUP_CONCAT(CASE WHEN pt.policy_end_date < CURDATE() THEN pt.id ELSE NULL END) AS Expired_ids', 'GROUP_CONCAT(CASE WHEN pt.policy_end_date BETWEEN CURDATE() AND (CURDATE() + INTERVAL 1 MONTH) THEN pt.id ELSE NULL END) AS Renewal_Pending_ids' ]); $builder->where("pt.policy_end_date IS NOT NULL", null, false); $builder->where('pt.is_active', 1); // Self join to check if a policy has been renewed $builder->join('policy_transaction renewed', 'renewed.source_client_policy_id = pt.client_policy_id and renewed.client_id = pt.client_id and renewed.client_branch_id = pt.client_branch_id', 'left'); // Filter for expired or expiring policies $builder->where("(pt.policy_end_date < CURDATE() OR pt.policy_end_date BETWEEN CURDATE() AND (CURDATE() + INTERVAL 1 MONTH))", null, false); $builder->where('renewed.id IS NULL', null, false); $query = $builder->get(); $result = $query->getResultArray(); $total = 0; foreach ($result[0] as $key => $value) { if ($key !== 'Expired_ids' && $key !== 'Renewal_Pending_ids') { $total += $value; } } // Ensure ID fields are arrays (not null) $result[0]['Expired_ids'] = $result[0]['Expired_ids'] ? $result[0]['Expired_ids'] : []; $result[0]['Renewal Pending_ids'] = $result[0]['Renewal_Pending_ids'] ? $result[0]['Renewal_Pending_ids'] : []; // Add total count $result[0]['total'] = $total; return $result[0]; } public function reportBDSNew( $start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0, $client_branch_id = 0, $insurer_branch_id = 0, $client_policy_id = 0, $user_id = 0, $where = [] ) { $date_condition = ''; // ============================== // DATE FILTER FOR STATEMENT MONTH // ============================== if ($date_type == 'statement_month' && $start_date != 0 && $end_date != 0) { $date_condition = " AND insurer_statements_oq.month >= '{$start_date}' AND insurer_statements_oq.month <= '{$end_date}' "; } // ============================== // BASE QUERY // ============================== // ============================== // Without Statement Upload // ============================== $builder2 = $this->db->table('policy_transaction') ->select(" policy_transaction.id AS id, policy_transaction.endorsement_no AS endorsement_no, policy_transaction.ref AS ref, DATE_FORMAT(policy_transaction.policy_issue_date, '%d %b %Y') AS policy_issue_date, DATE_FORMAT( policy_transaction.policy_issue_date, '%b %Y') AS policy_issue_month, CASE WHEN 1 = 1 THEN 'no statement uploaded' ELSE 'statement uploaded' END AS statement_uploaded , CASE WHEN clients.client_type = 1 THEN 'Group' WHEN clients.client_type = 2 THEN 'Retail' ELSE '-' END AS client_type, CASE WHEN policy_transaction.revenue_type = 'NA' THEN 'Fresh' ELSE 'Renewal' END AS revenue_type, CASE WHEN policy_transaction.action_type = 'inception' THEN 'Policy' ELSE 'Endorsement' END AS action_type, clients.client_name AS client_name, clients.short_name AS client_short_name, client_branch.branch_name AS client_branch_name, client_branch.address1 AS client_address, policy_type.policy_type, policy_type.bap, insurers.name AS insurer_name, insurers.short_name AS insurer_short_name, insurer_branch.branch_name AS insurer_branch_name, insurer_branch.branch_code AS insurer_branch_code, user_profiles.first_name AS user_name, vehicle.vehicle_no, tpa.name AS tpa_name, pt_co_share_details.remark AS remarks, pt_co_share_details.cop_amt AS bp_amt, pt_co_share_details.exp_amt, pt_co_share_details.id AS pt_id, sales_user.first_name AS salse_person_name, service_user.first_name AS service_person_name, ROUND(pt_co_share_details.cop_amt + pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt, 2) AS premium_wo_gst, ROUND((ROUND(pt_co_share_details.cop_amt + pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt, 2) * 18 / 100), 2) AS gst_amount, ROUND( ROUND(pt_co_share_details.cop_amt + pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt, 2) + ROUND((ROUND(pt_co_share_details.cop_amt + pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt, 2) * 18 / 100), 2), 2) AS total_premium, ROUND(pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt, 2) AS tp_or_ter, DATEDIFF(policy_transaction.policy_end_date, CURDATE()) AS days, (pt_co_share_details.agreed_tp_per + pt_co_share_details.agreed_tep_per) AS agreed_tp_or_ter_per, pt_co_share_details.agreed_bp_per, -- ============================== -- SUBQUERY: Total IRDA Amount -- Alias Agreed Amount ...!! -- ============================== ROUND(pt_co_share_details.exp_amt, 2) AS total_irda_amt, -- Reward Only ROUND(0, 2) AS reward, -- Billed Amount ROUND(0, 2) AS billed_amt, created_user.first_name AS user_name, CASE WHEN pt_co_share_details.co_share_type IN (0, 1) THEN policy_transaction.policy_no WHEN pt_co_share_details.co_share_type > 1 THEN CASE WHEN pt_co_share_details.follower_policy_no IS NULL OR pt_co_share_details.follower_policy_no = '' THEN policy_transaction.policy_no ELSE pt_co_share_details.follower_policy_no END ELSE policy_transaction.policy_no END AS policy_no ") // ============================== // JOINS // ============================== ->join('pt_co_share_details', 'policy_transaction.id = pt_co_share_details.pt_id', 'left') ->join('clients', 'clients.id = policy_transaction.client_id') ->join('client_branch', 'policy_transaction.client_branch_id = client_branch.id', 'left') ->join('client_policy', 'policy_transaction.client_policy_id = client_policy.id', 'left') ->join('user_profiles', 'policy_transaction.created_by = user_profiles.id', 'left') ->join('vehicle', 'policy_transaction.vehicle_id = vehicle.id', 'left') ->join('policy_type', 'policy_transaction.policy_type_id = policy_type.id', 'left') ->join('insurers', 'pt_co_share_details.insurer_id = insurers.id', 'left') ->join('insurer_branch', 'pt_co_share_details.insurer_branch_id = insurer_branch.id', 'left') ->join('tpa', 'policy_transaction.tpa_id = tpa.id', 'left') ->join('tpa_branch', 'policy_transaction.tpa_branch_id = tpa_branch.id', 'left') ->join('user_profiles AS sales_user', 'policy_transaction.sales_generated_by = sales_user.id', 'left') ->join('user_profiles AS service_user', 'policy_transaction.serviced_by = service_user.id', 'left') ->join('user_profiles AS created_user', 'policy_transaction.created_by = created_user.id', 'left') ->where('policy_transaction.is_active', 1) ->where('pt_co_share_details.is_active', 1) // ======================================================== // GROUP BY Insurer Statement Months // ======================================================= // ->groupBy('policy_transaction.policy_no , pt_co_share_details.insurer_id ') ; // ============================== // ROLE-BASED FILTERS // ============================== if ( (!in_array(get_role_id(), [1, 5])) && !( in_array(MANAGEMENT_TEAM_ID, user_team()) || in_array(FINANCE_TEAM_ID, user_team()) || in_array(BUSINESS_TEAM_ID, user_team()) ) ) { if (get_role_id() == 4 && in_array(POS_TEAM_ID, user_team())) { $builder2->where('policy_transaction.created_by', get_session_userid()); } } // ============================== // ADDITIONAL FILTERS // ============================== if (!empty($where)) { log_message('info', 'Where condition: ' . json_encode($where)); $builder2->where($where); } if ($start_date != 0 && $end_date != 0 && $date_type != 0 && $date_type != 'statement_month') { $startDate = date('Y-m-d 00:00:00', strtotime($start_date)); $endDate = date('Y-m-d 23:59:59', strtotime($end_date)); $builder2->where("policy_transaction.{$date_type} >=", $startDate) ->where("policy_transaction.{$date_type} <=", $endDate); } // ============================== // FILTER BY IDs // ============================== if ($client_id != 0) $builder2->where('policy_transaction.client_id', $client_id); if ($insurer_id != 0) $builder2->where('policy_transaction.insurer_id', $insurer_id); if ($client_branch_id != 0) $builder2->where('policy_transaction.client_branch_id', $client_branch_id); if ($insurer_branch_id != 0) $builder2->where('policy_transaction.insurer_branch_id', $insurer_branch_id); if ($client_policy_id != 0) $builder2->where('policy_transaction.client_policy_id', $client_policy_id); if ($user_id != 0) $builder2->where('policy_transaction.created_by', $user_id); if ($policy_type_id != 0) $builder2->where('client_policy.policy_type_id', $policy_type_id); if ($issuer != 0) $builder2->where('policy_transaction.issuer', $issuer); // ============================== // DEFAULT 90-DAY FILTER // ============================== if ( $client_id == 0 && $insurer_id == 0 && $policy_type_id == 0 && $date_type == 0 && $issuer == 0 ) { $fromDate = date('Y-m-d', strtotime('-90 days')); $toDate = date('Y-m-d 23:59:59'); if (empty($where)) { $builder2->where('policy_transaction.created_at >=', $fromDate) ->where('policy_transaction.created_at <=', $toDate); } } // ============================== // With Statement Upload // ============================== $builder = $this->db->table('policy_transaction') ->select(" policy_transaction.id AS id, policy_transaction.endorsement_no AS endorsement_no, policy_transaction.ref AS ref, DATE_FORMAT(policy_transaction.policy_issue_date, '%d %b %Y') AS policy_issue_date, DATE_FORMAT( IF(insurer_statements_oq.month IS NULL, policy_transaction.policy_issue_date, insurer_statements_oq.month ), '%b %Y' ) AS policy_issue_month, CASE WHEN insurer_statements_oq.month IS NULL THEN 'no statement uploaded' ELSE 'statement uploaded' END AS statement_uploaded , CASE WHEN clients.client_type = 1 THEN 'Group' WHEN clients.client_type = 2 THEN 'Retail' ELSE '-' END AS client_type, CASE WHEN policy_transaction.revenue_type = 'NA' THEN 'Fresh' ELSE 'Renewal' END AS revenue_type, CASE WHEN policy_transaction.action_type = 'inception' THEN 'Policy' ELSE 'Endorsement' END AS action_type, clients.client_name AS client_name, clients.short_name AS client_short_name, client_branch.branch_name AS client_branch_name, client_branch.address1 AS client_address, policy_type.policy_type, policy_type.bap, insurers.name AS insurer_name, insurers.short_name AS insurer_short_name, insurer_branch.branch_name AS insurer_branch_name, insurer_branch.branch_code AS insurer_branch_code, user_profiles.first_name AS user_name, vehicle.vehicle_no, tpa.name AS tpa_name, pt_co_share_details.remark AS remarks, pt_co_share_details.cop_amt AS bp_amt, pt_co_share_details.exp_amt, pt_co_share_details.id AS pt_id, sales_user.first_name AS salse_person_name, service_user.first_name AS service_person_name, ROUND(pt_co_share_details.cop_amt + pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt, 2) AS premium_wo_gst, ROUND((ROUND(pt_co_share_details.cop_amt + pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt, 2) * 18 / 100), 2) AS gst_amount, ROUND( ROUND(pt_co_share_details.cop_amt + pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt, 2) + ROUND((ROUND(pt_co_share_details.cop_amt + pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt, 2) * 18 / 100), 2), 2) AS total_premium, ROUND(pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt, 2) AS tp_or_ter, DATEDIFF(policy_transaction.policy_end_date, CURDATE()) AS days, (pt_co_share_details.agreed_tp_per + pt_co_share_details.agreed_tep_per) AS agreed_tp_or_ter_per, pt_co_share_details.agreed_bp_per, -- ============================== -- SUBQUERY: Total IRDA Amount -- Alias Agreed Amount ...!! -- ============================== ROUND(pt_co_share_details.exp_amt, 2) AS total_irda_amt, -- Reward Only ROUND(( SELECT SUM(co_share_stmt_details.reward) FROM co_share_stmt_details JOIN insurer_statements ON co_share_stmt_details.statement_id = insurer_statements.id WHERE co_share_stmt_details.co_share_id = pt_co_share_details.id AND co_share_stmt_details.is_active = 1 AND insurer_statements.is_active = 1 AND insurer_statements.month = insurer_statements_oq.month {$date_condition} GROUP BY('policy_transaction.policy_no , insurer_statements.month , pt_co_share_details.insurer_id') ), 2) AS reward, -- Billed Amount ROUND(( SELECT SUM( COALESCE(co_share_stmt_details.actual_bp_brokerage_amt, 0) + COALESCE(co_share_stmt_details.actual_tp_brokerage_amt, 0) + COALESCE(co_share_stmt_details.actual_tep_brokerage_amt, 0) + COALESCE(co_share_stmt_details.reward, 0) ) FROM co_share_stmt_details JOIN pt_co_share_details AS pt_table ON co_share_stmt_details.co_share_id = pt_table.id JOIN insurer_statements ON co_share_stmt_details.statement_id = insurer_statements.id WHERE co_share_stmt_details.co_share_id = pt_co_share_details.id AND co_share_stmt_details.is_active = 1 AND pt_table.is_active = 1 AND insurer_statements.is_active = 1 AND insurer_statements.invoice_status IS NOT NULL AND insurer_statements.month = insurer_statements_oq.month {$date_condition} GROUP BY('policy_transaction.policy_no , insurer_statements.month , pt_co_share_details.insurer_id') ), 2) AS billed_amt, created_user.first_name AS user_name, CASE WHEN pt_co_share_details.co_share_type IN (0, 1) THEN policy_transaction.policy_no WHEN pt_co_share_details.co_share_type > 1 THEN CASE WHEN pt_co_share_details.follower_policy_no IS NULL OR pt_co_share_details.follower_policy_no = '' THEN policy_transaction.policy_no ELSE pt_co_share_details.follower_policy_no END ELSE policy_transaction.policy_no END AS policy_no ") // ============================== // JOINS // ============================== ->join('pt_co_share_details', 'policy_transaction.id = pt_co_share_details.pt_id', 'left') ->join('clients', 'clients.id = policy_transaction.client_id') ->join('client_branch', 'policy_transaction.client_branch_id = client_branch.id', 'left') ->join('client_policy', 'policy_transaction.client_policy_id = client_policy.id', 'left') ->join('user_profiles', 'policy_transaction.created_by = user_profiles.id', 'left') ->join('vehicle', 'policy_transaction.vehicle_id = vehicle.id', 'left') ->join('policy_type', 'policy_transaction.policy_type_id = policy_type.id', 'left') ->join('insurers', 'pt_co_share_details.insurer_id = insurers.id', 'left') ->join('insurer_branch', 'pt_co_share_details.insurer_branch_id = insurer_branch.id', 'left') ->join('tpa', 'policy_transaction.tpa_id = tpa.id', 'left') ->join('tpa_branch', 'policy_transaction.tpa_branch_id = tpa_branch.id', 'left') ->join('user_profiles AS sales_user', 'policy_transaction.sales_generated_by = sales_user.id', 'left') ->join('user_profiles AS service_user', 'policy_transaction.serviced_by = service_user.id', 'left') ->join('user_profiles AS created_user', 'policy_transaction.created_by = created_user.id', 'left') ->join('co_share_stmt_details', 'pt_co_share_details.id = co_share_stmt_details.co_share_id', 'left') ->join('insurer_statements insurer_statements_oq', 'insurer_statements_oq.id = co_share_stmt_details.statement_id', 'left') ->where('policy_transaction.is_active', 1) ->where('pt_co_share_details.is_active', 1) ->where('co_share_stmt_details.is_active', 1) ->where('insurer_statements_oq.is_active', 1) ->where('insurer_statements_oq.id IS NOT NULL') // ======================================================== // GROUP BY Insurer Statement Months // ======================================================= // ->groupBy('policy_transaction.policy_no , pt_co_share_details.insurer_id ,insurer_statements_oq.month') ; // ============================== // ROLE-BASED FILTERS // ============================== if ( (!in_array(get_role_id(), [1, 5])) && !( in_array(MANAGEMENT_TEAM_ID, user_team()) || in_array(FINANCE_TEAM_ID, user_team()) || in_array(BUSINESS_TEAM_ID, user_team()) ) ) { if (get_role_id() == 4 && in_array(POS_TEAM_ID, user_team())) { $builder->where('policy_transaction.created_by', get_session_userid()); } } // ============================== // ADDITIONAL FILTERS // ============================== if (!empty($where)) { log_message('info', 'Where condition: ' . json_encode($where)); $builder->where($where); } if ($start_date != 0 && $end_date != 0 && $date_type != 0 && $date_type != 'statement_month') { $this->validateDateType($date_type); $startDate = date('Y-m-d 00:00:00', strtotime($start_date)); $endDate = date('Y-m-d 23:59:59', strtotime($end_date)); $builder->where("policy_transaction.{$date_type} >=", $startDate) ->where("policy_transaction.{$date_type} <=", $endDate); } // JOIN FOR STATEMENT MONTH FILTER if ($date_type == 'statement_month' && $start_date != 0 && $end_date != 0) { $startDate = date('Y-m-d', strtotime($start_date)); $endDate = date('Y-m-d', strtotime($end_date)); $builder->join('co_share_stmt_details cssdfilter', 'pt_co_share_details.id = cssdfilter.co_share_id', 'left') ->join('insurer_statements', 'cssdfilter.statement_id = insurer_statements.id', 'left') ->where('insurer_statements.is_active', 1) ->where('insurer_statements.month >=', $startDate) ->where('insurer_statements.month <=', $endDate) ->groupBy('cssdfilter.co_share_id'); } // ============================== // FILTER BY IDs // ============================== if ($client_id != 0) $builder->where('policy_transaction.client_id', $client_id); if ($insurer_id != 0) $builder->where('policy_transaction.insurer_id', $insurer_id); if ($client_branch_id != 0) $builder->where('policy_transaction.client_branch_id', $client_branch_id); if ($insurer_branch_id != 0) $builder->where('policy_transaction.insurer_branch_id', $insurer_branch_id); if ($client_policy_id != 0) $builder->where('policy_transaction.client_policy_id', $client_policy_id); if ($user_id != 0) $builder->where('policy_transaction.created_by', $user_id); if ($policy_type_id != 0) $builder->where('client_policy.policy_type_id', $policy_type_id); if ($issuer != 0) $builder->where('policy_transaction.issuer', $issuer); // ============================== // DEFAULT 90-DAY FILTER // ============================== if ( $client_id == 0 && $insurer_id == 0 && $policy_type_id == 0 && $date_type == 0 && $issuer == 0 ) { $fromDate = date('Y-m-d', strtotime('-90 days')); $toDate = date('Y-m-d 23:59:59'); if (empty($where)) { $builder->where('policy_transaction.created_at >=', $fromDate) ->where('policy_transaction.created_at <=', $toDate); } } $sql1 = $builder2->getCompiledSelect(); $sql2 = $builder->getCompiledSelect(); $finalSql = "(:sql1:) UNION ALL (:sql2:) ORDER BY policy_no DESC, insurer_branch_name ASC, statement_uploaded ASC, STR_TO_DATE(policy_issue_month, '%b %Y') ASC"; $binds = ['sql1'=>$sql1,'sql2'=>$sql1]; $result = $this->db->query($finalSql,$binds)->getResultArray(); // dd($this->db->getLastQuery()); return $result; } //not in use function due to complexity of query and union, so writing raw query with bindings to avoid sql injection public function getBDSReportListSingleUnion($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0, $client_branch_id = 0, $insurer_branch_id = 0, $client_policy_id = 0, $user_id = 0, $where = []) { $statement_month_condition = ''; if ($date_type == 'statement_month' && $start_date != 0 && $end_date != 0) { $statement_month_condition = " WHERE statement_month >= '" . $start_date . "' AND statement_month <= '" . $end_date . "' "; } $default_date_filter = ''; if ($client_id == 0 && $insurer_id == 0 && $policy_type_id == 0 && $date_type == 0 && $issuer == 0) { $fromDate = date('Y-m-d', strtotime('-90 days')); $toDate = date('Y-m-d 23:59:59'); if (empty($where)) { $default_date_filter = " AND pt.created_at >= '" . $fromDate . "' AND pt.created_at <= '" . $toDate . "' "; } } $conditions = ""; // start safely // 1. Role-based restrictions if ( (!in_array(get_role_id(), [1, 5])) && !( in_array(MANAGEMENT_TEAM_ID, user_team()) || in_array(FINANCE_TEAM_ID, user_team()) || in_array(BUSINESS_TEAM_ID, user_team()) ) ) { if (get_role_id() == 4 && in_array(POS_TEAM_ID, user_team())) { $conditions .= " AND pt.created_by = " . get_session_userid(); } } // 2. Dynamic $where array if (!empty($where)) { foreach ($where as $column => $value) { $value = addslashes($value); $conditions .= " AND `$column` = '$value' "; } } // 3. Date condition (except statement_month) if ($start_date != 0 && $end_date != 0 && $date_type != 0 && $date_type != 'statement_month') { $this->validateDateType($date_type); $startDate = date('Y-m-d 00:00:00', strtotime($start_date)); $endDate = date('Y-m-d 23:59:59', strtotime($end_date)); if ($date_type === "policy_issue_date") { $conditions .= " AND pcsd.pt_policy_issue_date >= '$startDate' "; $conditions .= " AND pcsd.pt_policy_issue_date <= '$endDate' "; } else { $conditions .= " AND pt.$date_type >= '$startDate' "; $conditions .= " AND pt.$date_type <= '$endDate' "; } } // 4. Common filters if ($client_id != 0) { $conditions .= " AND pt.client_id = $client_id "; } if ($insurer_id != 0) { $conditions .= " AND pt.insurer_id = $insurer_id "; } if ($client_branch_id != 0) { $conditions .= " AND pt.client_branch_id = $client_branch_id "; } if ($insurer_branch_id != 0) { $conditions .= " AND pt.insurer_branch_id = $insurer_branch_id "; } if ($client_policy_id != 0) { $conditions .= " AND pt.client_policy_id = $client_policy_id "; } if ($user_id != 0) { $conditions .= " AND pt.created_by = $user_id "; } if ($policy_type_id != 0) { $conditions .= " AND pt.policy_type_id = $policy_type_id "; } if ($issuer != 0) { $conditions .= " AND pt.issuer = $issuer "; } $sql = " SELECT * FROM ( SELECT pt.id AS id, pt.endorsement_no, pt.ref, pt.data_received_date, pt.endorse_eff_date, pt.policy_start_date, pt.policy_end_date, pt.renewal_date, pt.installment, nhance_branch.branch_name as nhance_branch, DATE_FORMAT(pt.policy_issue_date, '%d %b %Y') AS policy_issue_date, DATE_FORMAT(pcsd.pt_policy_issue_date, '%b %Y') AS policy_issue_month, pt.month as statement_month, 'no statement uploaded' AS statement_uploaded, CASE WHEN c.client_type = 1 THEN 'Group' WHEN c.client_type = 2 THEN 'Retail' ELSE '-' END AS client_type, CASE WHEN pt.revenue_type = 'NA' THEN 'Fresh' ELSE 'Renewal' END AS revenue_type, CASE WHEN pt.action_type = 'inception' THEN 'Policy' ELSE 'Endorsement' END AS action_type, pt.action_type as action_type_string, c.client_name, c.id as client_id, c.short_name AS client_short_name, cb.branch_name AS client_branch_name, cb.id AS client_branch_id, cb.address1 AS client_address, ptype.policy_type, ptype.bap, ins.id AS insurer_id, ins.name AS insurer_name, ins.short_name AS insurer_short_name, ib.branch_name AS insurer_branch_name, ib.id AS insurer_branch_id, ib.branch_code AS insurer_branch_code, created_user.first_name AS user_name, v.vehicle_no, tpa.name AS tpa_name, pcsd.remark AS remarks, pcsd.cop_amt AS bp_amt, pcsd.exp_amt, pcsd.id AS pt_id, su.first_name AS salse_person_name, se.first_name AS service_person_name, ROUND(pcsd.cop_amt + pcsd.cotp_amt + pcsd.cotep_amt, 2) AS premium_wo_gst, ROUND((pcsd.cop_amt + pcsd.cotp_amt + pcsd.cotep_amt) * 0.18, 2) AS gst_amount, ROUND((pcsd.cop_amt + pcsd.cotp_amt + pcsd.cotep_amt) * 1.18, 2) AS total_premium, ROUND(pcsd.cotp_amt + pcsd.cotep_amt, 2) AS tp_or_ter, DATEDIFF(pt.policy_end_date, CURDATE()) AS days, (pcsd.agreed_tp_per + pcsd.agreed_tep_per) AS agreed_tp_or_ter_per, ROUND(pcsd.exp_amt, 2) AS total_irda_amt, 0.00 AS reward, 0.00 AS billed_amt, CASE WHEN pcsd.co_share_type IN (0,1) THEN pt.policy_no WHEN pcsd.co_share_type > 1 THEN IFNULL(NULLIF(pcsd.follower_policy_no,''), pt.policy_no) ELSE pt.policy_no END AS policy_no, CASE WHEN pt.co_share = 1 THEN 'Yes' ELSE 'No' END AS co_share, CASE WHEN pt.bro_payable_by = 1 THEN 'Yes' ELSE 'No' END AS bro_payable_by, pcsd.non_comm_per_amt, pcsd.bp_igst, pcsd.bp_sgst, pcsd.bp_cgst, pcsd.agreed_bp_per, ROUND(pcsd.agreed_tp_per + pcsd.agreed_tep_per,2) AS agreed_tp_per, pcsd.standerd_bp_per, ROUND(pcsd.standerd_tp_per + pcsd.standerd_tep_per,2) AS standerd_tp_per, 0 AS actual_bp_amt, ROUND(0, 2) AS actual_tp_amt, 0 AS actual_bp_per, ROUND(0, 2) AS actual_tp_per, 0 AS actual_tep_brokerage_amt, ROUND(0, 2) AS actual_tp_brokerage_amt, service_branch.branch_name as service_branch, salse_manager.first_name as salse_manager_name, service_manager.first_name as service_manager_name, cd_master.cd_ac_no, pt.rollover_date, pt.policy_holder_name, CASE WHEN pt.same_as_proposer = 1 THEN 'Yes' ELSE 'No' END AS same_as_proposer, pcsd.follower_policy_no, pcsd.co_share_per, pcsd.stamp_duty FROM policy_transaction pt LEFT JOIN pt_co_share_details pcsd ON pt.id = pcsd.pt_id JOIN clients c ON c.id = pt.client_id LEFT JOIN client_branch cb ON pt.client_branch_id = cb.id LEFT JOIN client_policy cp ON pt.client_policy_id = cp.id LEFT JOIN user_profiles up ON pt.created_by = up.id LEFT JOIN vehicle v ON pt.vehicle_id = v.id LEFT JOIN policy_type ptype ON pt.policy_type_id = ptype.id LEFT JOIN insurers ins ON pcsd.insurer_id = ins.id LEFT JOIN insurer_branch ib ON pcsd.insurer_branch_id = ib.id LEFT JOIN tpa ON pt.tpa_id = tpa.id LEFT JOIN tpa_branch tb ON pt.tpa_branch_id = tb.id LEFT JOIN user_profiles su ON pt.sales_generated_by = su.id LEFT JOIN user_profiles se ON pt.serviced_by = se.id LEFT JOIN user_profiles created_user ON pt.created_by = created_user.id LEFT JOIN nhance_branch ON pt.issuer_branch = nhance_branch.id LEFT JOIN nhance_branch service_branch ON pt.service_person_branch_id = service_branch.id LEFT JOIN user_profiles salse_manager ON pt.salse_person_manager_id = salse_manager.id LEFT JOIN user_profiles service_manager ON pt.service_person_manager_id = service_manager.id LEFT JOIN cd_master ON pt.cd_ac_pk = cd_master.id WHERE pt.is_active = 1 AND pcsd.is_active = 1 $default_date_filter $conditions GROUP BY pt.policy_no, pt.endorsement_no, pcsd.insurer_id UNION ALL SELECT pt.id AS id, pt.endorsement_no, pt.ref, pt.data_received_date, pt.endorse_eff_date, pt.policy_start_date, pt.policy_end_date, pt.renewal_date, pt.installment, nhance_branch.branch_name as nhance_branch, DATE_FORMAT(pt.policy_issue_date, '%d %b %Y') AS policy_issue_date, DATE_FORMAT(IF(insq.month IS NULL, pcsd.pt_policy_issue_date, insq.month),'%b %Y') AS policy_issue_month, insq.month as statement_month, 'statement uploaded' AS statement_uploaded, CASE WHEN c.client_type = 1 THEN 'Group' WHEN c.client_type = 2 THEN 'Retail' ELSE '-' END AS client_type, CASE WHEN pt.revenue_type = 'NA' THEN 'Fresh' ELSE 'Renewal' END AS revenue_type, CASE WHEN IFNULL(cssd.actual_tep_brokerage_amt, 0) = 0 AND IFNULL(cssd.actual_tp_brokerage_amt, 0) = 0 AND IFNULL(cssd.actual_bp_brokerage_amt, 0) = 0 AND IFNULL(cssd.reward, 0) != 0 THEN 'Rewards' WHEN pt.action_type = 'inception' THEN 'Policy' ELSE 'Endorsement' END AS action_type, pt.action_type as action_type_string, c.client_name, c.id as client_id, c.short_name AS client_short_name, cb.branch_name AS client_branch_name, cb.id AS client_branch_id, cb.address1 AS client_address, ptype.policy_type, ptype.bap, ins.id AS insurer_id, ins.name AS insurer_name, ins.short_name AS insurer_short_name, ib.branch_name AS insurer_branch_name, ib.id AS insurer_branch_id, ib.branch_code AS insurer_branch_code, created_user.first_name as user_name, v.vehicle_no, tpa.name AS tpa_name, pcsd.remark AS remarks, pcsd.cop_amt AS bp_amt, pcsd.exp_amt, pcsd.id AS pt_id, su.first_name AS salse_person_name, se.first_name AS service_person_name, ROUND(pcsd.cop_amt + pcsd.cotp_amt + pcsd.cotep_amt,2) AS premium_wo_gst, ROUND((pcsd.cop_amt + pcsd.cotp_amt + pcsd.cotep_amt) * 0.18,2) AS gst_amount, ROUND((pcsd.cop_amt + pcsd.cotp_amt + pcsd.cotep_amt) * 1.18,2) AS total_premium, ROUND(pcsd.cotp_amt + pcsd.cotep_amt,2) AS tp_or_ter, DATEDIFF(pt.policy_end_date, CURDATE()) AS days, (pcsd.agreed_tp_per + pcsd.agreed_tep_per) AS agreed_tp_or_ter_per, CASE WHEN insq.month = pt.month THEN pcsd.exp_amt ELSE 0 END AS total_irda_amt_2, COALESCE(( SELECT SUM(cs.reward) FROM co_share_stmt_details cs JOIN insurer_statements i ON cs.statement_id = i.id WHERE cs.co_share_id = pcsd.id AND i.month = insq.month AND i.is_active = 1 AND cs.is_active = 1 GROUP BY pt.policy_no, i.month, pcsd.insurer_id ),0) AS reward, COALESCE(( SELECT SUM( COALESCE(cs.actual_bp_brokerage_amt,0) + COALESCE(cs.actual_tp_brokerage_amt,0) + COALESCE(cs.actual_tep_brokerage_amt,0) + COALESCE(cs.reward,0) ) FROM co_share_stmt_details cs JOIN insurer_statements i ON cs.statement_id = i.id WHERE cs.co_share_id = pcsd.id AND i.invoice_status IS NOT NULL AND i.month = insq.month AND i.is_active = 1 AND cs.is_active = 1 GROUP BY pt.policy_no, i.month, pcsd.insurer_id ),0) AS billed_amt, CASE WHEN pcsd.co_share_type IN (0,1) THEN pt.policy_no WHEN pcsd.co_share_type > 1 THEN IFNULL(NULLIF(pcsd.follower_policy_no,''), pt.policy_no) ELSE pt.policy_no END AS policy_no, CASE WHEN pt.co_share = 1 THEN 'Yes' ELSE 'No' END AS co_share, CASE WHEN pt.bro_payable_by = 1 THEN 'Yes' ELSE 'No' END AS bro_payable_by, pcsd.non_comm_per_amt, pcsd.bp_igst, pcsd.bp_sgst, pcsd.bp_cgst, pcsd.agreed_bp_per, ROUND(pcsd.agreed_tp_per + pcsd.agreed_tep_per,2) AS agreed_tp_per, pcsd.standerd_bp_per, ROUND(pcsd.standerd_tp_per + pcsd.standerd_tep_per,2) AS standerd_tp_per, cssd.actual_bp_amt, ROUND(cssd.actual_tp_amt + cssd.actual_tep_amt,2) AS actual_tp_amt, cssd.actual_bp_per, ROUND(cssd.actual_tp_per + cssd.actual_tep_per,2) AS actual_tp_per, cssd.actual_tep_brokerage_amt, ROUND(cssd.actual_tp_brokerage_amt + cssd.actual_bp_brokerage_amt,2) AS actual_tp_brokerage_amt, service_branch.branch_name as service_branch, salse_manager.first_name as salse_manager_name, service_manager.first_name as service_manager_name, cd_master.cd_ac_no, pt.rollover_date, pt.policy_holder_name, CASE WHEN pt.same_as_proposer = 1 THEN 'Yes' ELSE 'No' END AS same_as_proposer, pcsd.follower_policy_no, pcsd.co_share_per, pcsd.stamp_duty FROM policy_transaction pt LEFT JOIN pt_co_share_details pcsd ON pt.id = pcsd.pt_id LEFT JOIN co_share_stmt_details cssd ON pcsd.id = cssd.co_share_id LEFT JOIN insurer_statements insq ON cssd.statement_id = insq.id JOIN clients c ON c.id = pt.client_id LEFT JOIN client_branch cb ON pt.client_branch_id = cb.id LEFT JOIN client_policy cp ON pt.client_policy_id = cp.id LEFT JOIN user_profiles up ON pt.created_by = up.id LEFT JOIN vehicle v ON pt.vehicle_id = v.id LEFT JOIN policy_type ptype ON pt.policy_type_id = ptype.id LEFT JOIN insurers ins ON pcsd.insurer_id = ins.id LEFT JOIN insurer_branch ib ON pcsd.insurer_branch_id = ib.id LEFT JOIN tpa ON pt.tpa_id = tpa.id LEFT JOIN tpa_branch tb ON pt.tpa_branch_id = tb.id LEFT JOIN user_profiles su ON pt.sales_generated_by = su.id LEFT JOIN user_profiles se ON pt.serviced_by = se.id LEFT JOIN user_profiles created_user ON pt.created_by = created_user.id LEFT JOIN nhance_branch ON pt.issuer_branch = nhance_branch.id LEFT JOIN nhance_branch service_branch ON pt.service_person_branch_id = service_branch.id LEFT JOIN user_profiles salse_manager ON pt.salse_person_manager_id = salse_manager.id LEFT JOIN user_profiles service_manager ON pt.service_person_manager_id = service_manager.id LEFT JOIN cd_master ON pt.cd_ac_pk = cd_master.id WHERE pt.is_active = 1 AND pcsd.is_active = 1 AND cssd.is_active = 1 AND insq.is_active = 1 $default_date_filter $conditions GROUP BY pt.policy_no, pt.endorsement_no, pcsd.insurer_id, insq.month ) AS final_result $statement_month_condition -- GROUP BY statement_month, insurer_name, policy_no -- WHERE id = 6063 ORDER BY id DESC, policy_no ASC, insurer_branch_name ASC, statement_uploaded ASC, statement_month ASC, STR_TO_DATE(policy_issue_month, '%b %Y') ASC "; $query = $this->db->query($sql); $result = $query->getResultArray(); // dd($result); // dd($this->db->getLastQuery()); $keys = []; $filtered = []; foreach ($result as $row) { $endorsement_number = "-"; if(!empty($row['endorsement_no'])){ $endorsement_number = $row['endorsement_no']; } $key = $row['statement_month'].'|'.$row['insurer_name'].'|'.$row['policy_no'] . '|' . $endorsement_number; // If uploaded record exists, always keep it and override previous if ($row['statement_uploaded'] === 'statement uploaded') { $filtered[$key] = $row; // overwrite no-statement row if it exists $keys[$key] = true; } // Keep "no statement uploaded" only if uploaded one not added yet elseif (!isset($keys[$key])) { $filtered[$key] = $row; } } $result = array_values($filtered); // dd($result); // $runningBilled = []; // $totalIrdaMap = []; // $final = []; // foreach ($result as $row) { // $ptId = $row['pt_id']; // // Store total_irda_amt only once (first non-zero value) // if (!isset($totalIrdaMap[$ptId]) && $row['total_irda_amt'] > 0) { // $totalIrdaMap[$ptId] = $row['total_irda_amt']; // } // // Initialize running sum // if (!isset($runningBilled[$ptId])) { // $runningBilled[$ptId] = 0; // } // // Add billed amount to running total // $runningBilled[$ptId] += (float)$row['billed_amt']; // // Calculate unbilled amount // $row['unbilled_amount'] = ($totalIrdaMap[$ptId] ?? 0) - $runningBilled[$ptId]; // $final[] = $row; // } $totalBilled = []; $totalIrdaMap = []; foreach ($result as $row) { $key = $row['pt_id'].'-'.$row['insurer_id']; // Sum billed amount $totalBilled[$key] = ($totalBilled[$key] ?? 0) + (float) ($row['billed_amt'] ?? 0); // Store total_irda_amt once if (!isset($totalIrdaMap[$key]) && ($row['total_irda_amt'] ?? 0) > 0) { $totalIrdaMap[$key] = (float) $row['total_irda_amt']; } } $ptSeen = []; $final = []; foreach ($result as $row) { $ptId = $row['pt_id'].'-'.$row['insurer_id']; if (!isset($ptSeen[$ptId])) { // First entry → set unbilled amount $row['unbilled_amount'] = ($totalIrdaMap[$ptId] ?? 0) - ($totalBilled[$ptId] ?? 0); $ptSeen[$ptId] = true; } else { // Other entries → zero $row['unbilled_amount'] = 0; } $final[] = $row; } $result = $final; // print_rr($result); die; return $result; } public function getBDSReportList($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0, $client_branch_id = 0, $insurer_branch_id = 0, $client_policy_id = 0, $user_id = 0, $where = []) { $client_id = (int)$client_id; $insurer_id = (int)$insurer_id; $policy_type_id = (int)$policy_type_id; $client_branch_id = (int)$client_branch_id; $insurer_branch_id = (int)$insurer_branch_id; $client_policy_id = (int)$client_policy_id; $user_id = (int)$user_id; $issuer = (int)$issuer; $whereAdded = false; $statement_month_condition = ''; if ($date_type == 'statement_month' && $start_date != 0 && $end_date != 0) { $statement_month_condition = " WHERE statement_month >= '" . $start_date . "' AND statement_month <= '" . $end_date . "' "; $whereAdded = true; } $default_date_filter = ''; if ($client_id == 0 && $insurer_id == 0 && $policy_type_id == 0 && $date_type == 0 && $issuer == 0) { $fromDate = date('Y-m-d', strtotime('-90 days')); $toDate = date('Y-m-d 23:59:59'); if (empty($where)) { $default_date_filter = " AND pt.created_at >= '" . $fromDate . "' AND pt.created_at <= '" . $toDate . "' "; } } $conditions = ""; // start safely // 1. Role-based restrictions // if ( // (!in_array(get_role_id(), [1, 5])) && // !( // in_array(MANAGEMENT_TEAM_ID, user_team()) || // in_array(FINANCE_TEAM_ID, user_team()) || // in_array(BUSINESS_TEAM_ID, user_team()) // ) // ) { // if (get_role_id() == 4 && in_array(POS_TEAM_ID, user_team())) { // $conditions .= " AND pt.created_by = " . get_session_userid(); // } // } if ((!in_array(get_role_id(), [1, 5]))) { if (in_array(POS_TEAM_ID, user_team())) { $conditions .= " AND pt.created_by = " . get_session_userid(); } } // 2. Dynamic $where (string SQL fragment or column => value map) if (!empty($where)) { if (is_string($where)) { $conditions .= ' AND ' . $where . ' '; } else { foreach ($where as $column => $value) { $value = addslashes($value); $conditions .= " AND `$column` = '$value' "; } } } // 3. Date condition (except statement_month) if ($start_date != 0 && $end_date != 0 && $date_type != 0 && $date_type != 'statement_month') { $this->validateDateType($date_type); $startDate = date('Y-m-d 00:00:00', strtotime($start_date)); $endDate = date('Y-m-d 23:59:59', strtotime($end_date)); if ($date_type === "policy_issue_date") { $conditions .= " AND pcsd.pt_policy_issue_date >= '$startDate' "; $conditions .= " AND pcsd.pt_policy_issue_date <= '$endDate' "; } else if ($date_type === "created_at") { $conditions .= " AND pt.created_at <= '$endDate' "; } else { $conditions .= " AND pt.$date_type >= '$startDate' "; $conditions .= " AND pt.$date_type <= '$endDate' "; } } // 4. Common filters if ($client_id != 0) { $conditions .= " AND pt.client_id = $client_id "; } if ($insurer_id != 0) { $conditions .= " AND pcsd.insurer_id = $insurer_id "; } if ($client_branch_id != 0) { $conditions .= " AND pt.client_branch_id = $client_branch_id "; } if ($insurer_branch_id != 0) { $conditions .= " AND pcsd.insurer_branch_id = $insurer_branch_id "; } if ($client_policy_id != 0) { $conditions .= " AND pt.client_policy_id = $client_policy_id "; } if ($user_id != 0) { $conditions .= " AND pt.created_by = $user_id "; } if ($policy_type_id != 0) { $conditions .= " AND pt.policy_type_id = $policy_type_id "; } if ($issuer != 0) { $conditions .= " AND pt.issuer = $issuer "; } $main_conditions = ''; function addCondition(&$main_conditions, &$whereAdded, $condition) { if (!$whereAdded) { $main_conditions .= " WHERE $condition "; $whereAdded = true; } else { $main_conditions .= " AND $condition "; } } // 4. Common filters if ($client_id != 0) { addCondition($main_conditions, $whereAdded, "client_id = $client_id"); } if ($insurer_id != 0) { addCondition($main_conditions, $whereAdded, "insurer_id = $insurer_id"); } if ($client_branch_id != 0) { addCondition($main_conditions, $whereAdded, "client_branch_id = $client_branch_id"); } if ($insurer_branch_id != 0) { addCondition($main_conditions, $whereAdded, "insurer_branch_id = $insurer_branch_id"); } $sql = " SELECT * FROM ( SELECT pt.id AS id, pt.endorsement_no, pt.ref, pt.data_received_date, pt.endorse_eff_date, pt.policy_start_date, pt.policy_end_date, pt.renewal_date, pt.installment, nhance_branch.branch_name as nhance_branch, DATE_FORMAT(pcsd.pt_policy_issue_date, '%d %b %Y') AS policy_issue_date, DATE_FORMAT(pcsd.pt_policy_issue_date, '%b %Y') AS policy_issue_month, DATE_FORMAT(pcsd.pt_policy_issue_date, '%b %Y') AS statement_year_month, pcsd.pt_policy_issue_date as statement_month, 'no statement uploaded' AS statement_uploaded, CASE WHEN c.client_type = 1 THEN 'Group' WHEN c.client_type = 2 THEN 'Retail' ELSE '-' END AS client_type, CASE WHEN pt.revenue_type = 'NA' THEN 'Fresh' ELSE 'Renewal' END AS revenue_type, CASE WHEN pt.action_type = 'inception' THEN 'Policy' ELSE 'Endorsement' END AS action_type, pt.action_type as action_type_string, c.client_name, c.id as client_id, c.short_name AS client_short_name, cb.branch_name AS client_branch_name, cb.id AS client_branch_id, cb.address1 AS client_address, ptype.policy_type, ptype.bap, ins.id AS insurer_id, ins.name AS insurer_name, ins.short_name AS insurer_short_name, ib.branch_name AS insurer_branch_name, ib.id AS insurer_branch_id, ib.branch_code AS insurer_branch_code, created_user.first_name AS user_name, v.vehicle_no, tpa.name AS tpa_name, pcsd.remark AS remarks, pcsd.cop_amt AS bp_amt, pcsd.exp_amt, pcsd.id AS pt_id, su.first_name AS salse_person_name, se.first_name AS service_person_name, ROUND(pcsd.cop_amt + pcsd.cotp_amt + pcsd.cotep_amt, 2) AS premium_wo_gst, ROUND((pcsd.cop_amt + pcsd.cotp_amt + pcsd.cotep_amt) * 0.18, 2) AS gst_amount, ROUND((pcsd.cop_amt + pcsd.cotp_amt + pcsd.cotep_amt) * 1.18, 2) AS total_premium, ROUND(pcsd.cotp_amt + pcsd.cotep_amt, 2) AS tp_or_ter, DATEDIFF(pt.policy_end_date, CURDATE()) AS days, (pcsd.agreed_tp_per + pcsd.agreed_tep_per) AS agreed_tp_or_ter_per, ROUND(pcsd.exp_amt, 2) AS total_irda_amt, 0.00 AS reward, 0.00 AS billed_amt, CASE WHEN pcsd.co_share_type IN (0,1) THEN pt.policy_no WHEN pcsd.co_share_type > 1 THEN IFNULL(NULLIF(pcsd.follower_policy_no,''), pt.policy_no) ELSE pt.policy_no END AS policy_no, CASE WHEN pt.co_share = 1 THEN 'Yes' ELSE 'No' END AS co_share, CASE WHEN pt.bro_payable_by = 1 THEN 'Yes' ELSE 'No' END AS bro_payable_by, pcsd.non_comm_per_amt, pcsd.bp_igst, pcsd.bp_sgst, pcsd.bp_cgst, pcsd.agreed_bp_per, ROUND(pcsd.agreed_tp_per + pcsd.agreed_tep_per,2) AS agreed_tp_per, pcsd.standerd_bp_per, ROUND(pcsd.standerd_tp_per + pcsd.standerd_tep_per,2) AS standerd_tp_per, 0 AS actual_bp_amt, ROUND(0, 2) AS actual_tp_amt, 0 AS actual_bp_per, ROUND(0, 2) AS actual_tp_per, 0 AS actual_tep_brokerage_amt, ROUND(0, 2) AS actual_tp_brokerage_amt, service_branch.branch_name as service_branch, salse_manager.first_name as salse_manager_name, service_manager.first_name as service_manager_name, cd_master.cd_ac_no, pt.rollover_date, pt.policy_holder_name, CASE WHEN pt.same_as_proposer = 1 THEN 'Yes' ELSE 'No' END AS same_as_proposer, pcsd.follower_policy_no, pcsd.co_share_per, pcsd.stamp_duty, 'first' as query FROM policy_transaction pt LEFT JOIN pt_co_share_details pcsd ON pt.id = pcsd.pt_id JOIN clients c ON c.id = pt.client_id LEFT JOIN client_branch cb ON pt.client_branch_id = cb.id LEFT JOIN client_policy cp ON pt.client_policy_id = cp.id LEFT JOIN user_profiles up ON pt.created_by = up.id LEFT JOIN vehicle v ON pt.vehicle_id = v.id LEFT JOIN policy_type ptype ON pt.policy_type_id = ptype.id LEFT JOIN insurers ins ON pcsd.insurer_id = ins.id LEFT JOIN insurer_branch ib ON pcsd.insurer_branch_id = ib.id LEFT JOIN tpa ON pt.tpa_id = tpa.id LEFT JOIN tpa_branch tb ON pt.tpa_branch_id = tb.id LEFT JOIN user_profiles su ON pt.sales_generated_by = su.id LEFT JOIN user_profiles se ON pt.serviced_by = se.id LEFT JOIN user_profiles created_user ON pt.created_by = created_user.id LEFT JOIN nhance_branch ON pt.issuer_branch = nhance_branch.id LEFT JOIN nhance_branch service_branch ON pt.service_person_branch_id = service_branch.id LEFT JOIN user_profiles salse_manager ON pt.salse_person_manager_id = salse_manager.id LEFT JOIN user_profiles service_manager ON pt.service_person_manager_id = service_manager.id LEFT JOIN cd_master ON pt.cd_ac_pk = cd_master.id WHERE pt.is_active = 1 AND pcsd.is_active = 1 $default_date_filter $conditions GROUP BY pt.policy_no, pt.endorsement_no, pcsd.insurer_id UNION ALL SELECT pt.id AS id, pt.endorsement_no, pt.ref, pt.data_received_date, pt.endorse_eff_date, pt.policy_start_date, pt.policy_end_date, pt.renewal_date, pt.installment, nhance_branch.branch_name as nhance_branch, DATE_FORMAT(pcsd.pt_policy_issue_date, '%d %b %Y') AS policy_issue_date, DATE_FORMAT(IF(insq.month IS NULL, pcsd.pt_policy_issue_date, insq.month),'%b %Y') AS policy_issue_month, DATE_FORMAT(insq.month, '%b %Y') AS statement_year_month, insq.month as statement_month, 'statement uploaded' AS statement_uploaded, CASE WHEN c.client_type = 1 THEN 'Group' WHEN c.client_type = 2 THEN 'Retail' ELSE '-' END AS client_type, CASE WHEN pt.revenue_type = 'NA' THEN 'Fresh' ELSE 'Renewal' END AS revenue_type, CASE WHEN pt.action_type = 'inception' THEN 'Policy' ELSE 'Endorsement' END AS action_type, pt.action_type as action_type_string, c.client_name, c.id as client_id, c.short_name AS client_short_name, cb.branch_name AS client_branch_name, cb.id AS client_branch_id, cb.address1 AS client_address, ptype.policy_type, ptype.bap, ins.id AS insurer_id, ins.name AS insurer_name, ins.short_name AS insurer_short_name, ib.branch_name AS insurer_branch_name, ib.id AS insurer_branch_id, ib.branch_code AS insurer_branch_code, created_user.first_name as user_name, v.vehicle_no, tpa.name AS tpa_name, pcsd.remark AS remarks, pcsd.cop_amt AS bp_amt, pcsd.exp_amt, pcsd.id AS pt_id, su.first_name AS salse_person_name, se.first_name AS service_person_name, ROUND(pcsd.cop_amt + pcsd.cotp_amt + pcsd.cotep_amt,2) AS premium_wo_gst, ROUND((pcsd.cop_amt + pcsd.cotp_amt + pcsd.cotep_amt) * 0.18,2) AS gst_amount, ROUND((pcsd.cop_amt + pcsd.cotp_amt + pcsd.cotep_amt) * 1.18,2) AS total_premium, ROUND(pcsd.cotp_amt + pcsd.cotep_amt,2) AS tp_or_ter, DATEDIFF(pt.policy_end_date, CURDATE()) AS days, (pcsd.agreed_tp_per + pcsd.agreed_tep_per) AS agreed_tp_or_ter_per, CASE WHEN DATE_FORMAT(insq.month, '%Y-%m') = DATE_FORMAT(pcsd.pt_policy_issue_date, '%Y-%m') THEN pcsd.exp_amt ELSE 0 END AS total_irda_amt_2, 0 AS reward, COALESCE(( SELECT SUM( COALESCE(cs.actual_bp_brokerage_amt,0) + COALESCE(cs.actual_tp_brokerage_amt,0) + COALESCE(cs.actual_tep_brokerage_amt,0) ) FROM co_share_stmt_details cs JOIN insurer_statements i ON cs.statement_id = i.id WHERE cs.co_share_id = pcsd.id AND i.invoice_status IS NOT NULL AND i.month = insq.month AND i.is_active = 1 AND cs.is_active = 1 GROUP BY pt.policy_no, i.month, pcsd.insurer_id ),0) AS billed_amt, CASE WHEN pcsd.co_share_type IN (0,1) THEN pt.policy_no WHEN pcsd.co_share_type > 1 THEN IFNULL(NULLIF(pcsd.follower_policy_no,''), pt.policy_no) ELSE pt.policy_no END AS policy_no, CASE WHEN pt.co_share = 1 THEN 'Yes' ELSE 'No' END AS co_share, CASE WHEN pt.bro_payable_by = 1 THEN 'Yes' ELSE 'No' END AS bro_payable_by, pcsd.non_comm_per_amt, pcsd.bp_igst, pcsd.bp_sgst, pcsd.bp_cgst, pcsd.agreed_bp_per, ROUND(pcsd.agreed_tp_per + pcsd.agreed_tep_per,2) AS agreed_tp_per, pcsd.standerd_bp_per, ROUND(pcsd.standerd_tp_per + pcsd.standerd_tep_per,2) AS standerd_tp_per, cssd.actual_bp_amt, ROUND(cssd.actual_tp_amt + cssd.actual_tep_amt,2) AS actual_tp_amt, cssd.actual_bp_per, ROUND(cssd.actual_tp_per + cssd.actual_tep_per,2) AS actual_tp_per, cssd.actual_tep_brokerage_amt, ROUND(cssd.actual_tp_brokerage_amt + cssd.actual_bp_brokerage_amt,2) AS actual_tp_brokerage_amt, service_branch.branch_name as service_branch, salse_manager.first_name as salse_manager_name, service_manager.first_name as service_manager_name, cd_master.cd_ac_no, pt.rollover_date, pt.policy_holder_name, CASE WHEN pt.same_as_proposer = 1 THEN 'Yes' ELSE 'No' END AS same_as_proposer, pcsd.follower_policy_no, pcsd.co_share_per, pcsd.stamp_duty, 'second' as query FROM policy_transaction pt LEFT JOIN pt_co_share_details pcsd ON pt.id = pcsd.pt_id LEFT JOIN co_share_stmt_details cssd ON pcsd.id = cssd.co_share_id LEFT JOIN insurer_statements insq ON cssd.statement_id = insq.id JOIN clients c ON c.id = pt.client_id LEFT JOIN client_branch cb ON pt.client_branch_id = cb.id LEFT JOIN client_policy cp ON pt.client_policy_id = cp.id LEFT JOIN user_profiles up ON pt.created_by = up.id LEFT JOIN vehicle v ON pt.vehicle_id = v.id LEFT JOIN policy_type ptype ON pt.policy_type_id = ptype.id LEFT JOIN insurers ins ON pcsd.insurer_id = ins.id LEFT JOIN insurer_branch ib ON pcsd.insurer_branch_id = ib.id LEFT JOIN tpa ON pt.tpa_id = tpa.id LEFT JOIN tpa_branch tb ON pt.tpa_branch_id = tb.id LEFT JOIN user_profiles su ON pt.sales_generated_by = su.id LEFT JOIN user_profiles se ON pt.serviced_by = se.id LEFT JOIN user_profiles created_user ON pt.created_by = created_user.id LEFT JOIN nhance_branch ON pt.issuer_branch = nhance_branch.id LEFT JOIN nhance_branch service_branch ON pt.service_person_branch_id = service_branch.id LEFT JOIN user_profiles salse_manager ON pt.salse_person_manager_id = salse_manager.id LEFT JOIN user_profiles service_manager ON pt.service_person_manager_id = service_manager.id LEFT JOIN cd_master ON pt.cd_ac_pk = cd_master.id WHERE pt.is_active = 1 AND pcsd.is_active = 1 AND cssd.is_active = 1 AND insq.is_active = 1 $default_date_filter $conditions GROUP BY pt.policy_no, pt.endorsement_no, pcsd.insurer_id, insq.month UNION ALL SELECT pt.id AS id, pt.endorsement_no, pt.ref, pt.data_received_date, pt.endorse_eff_date, pt.policy_start_date, pt.policy_end_date, pt.renewal_date, pt.installment, nhance_branch.branch_name as nhance_branch, DATE_FORMAT(pcsd.pt_policy_issue_date, '%d %b %Y') AS policy_issue_date, DATE_FORMAT(IF(insq.month IS NULL, pcsd.pt_policy_issue_date, insq.month),'%b %Y') AS policy_issue_month, DATE_FORMAT(insq.month, '%b %Y') AS statement_year_month, insq.month as statement_month, 'statement uploaded' AS statement_uploaded, CASE WHEN c.client_type = 1 THEN 'Group' WHEN c.client_type = 2 THEN 'Retail' ELSE '-' END AS client_type, CASE WHEN pt.revenue_type = 'NA' THEN 'Fresh' ELSE 'Renewal' END AS revenue_type, CASE WHEN IFNULL(cssd.reward,0) <> 0 THEN 'Rewards' ELSE 'Rewards' END AS action_type, pt.action_type as action_type_string, c.client_name, c.id as client_id, c.short_name AS client_short_name, cb.branch_name AS client_branch_name, cb.id AS client_branch_id, cb.address1 AS client_address, ptype.policy_type, ptype.bap, ins.id AS insurer_id, ins.name AS insurer_name, ins.short_name AS insurer_short_name, ib.branch_name AS insurer_branch_name, ib.id AS insurer_branch_id, ib.branch_code AS insurer_branch_code, created_user.first_name as user_name, v.vehicle_no, tpa.name AS tpa_name, pcsd.remark AS remarks, pcsd.cop_amt AS bp_amt, pcsd.exp_amt, pcsd.id AS pt_id, su.first_name AS salse_person_name, se.first_name AS service_person_name, ROUND(pcsd.cop_amt + pcsd.cotp_amt + pcsd.cotep_amt,2) AS premium_wo_gst, ROUND((pcsd.cop_amt + pcsd.cotp_amt + pcsd.cotep_amt) * 0.18,2) AS gst_amount, ROUND((pcsd.cop_amt + pcsd.cotp_amt + pcsd.cotep_amt) * 1.18,2) AS total_premium, ROUND(pcsd.cotp_amt + pcsd.cotep_amt,2) AS tp_or_ter, DATEDIFF(pt.policy_end_date, CURDATE()) AS days, (pcsd.agreed_tp_per + pcsd.agreed_tep_per) AS agreed_tp_or_ter_per, 0 AS total_irda_amt_2, COALESCE(( SELECT SUM(cs.reward) FROM co_share_stmt_details cs JOIN insurer_statements i ON cs.statement_id = i.id WHERE cs.co_share_id = pcsd.id AND i.month = insq.month AND i.is_active = 1 AND cs.is_active = 1 GROUP BY pt.policy_no, i.month, pcsd.insurer_id ),0) AS reward, 0 AS billed_amt, CASE WHEN pcsd.co_share_type IN (0,1) THEN pt.policy_no WHEN pcsd.co_share_type > 1 THEN IFNULL(NULLIF(pcsd.follower_policy_no,''), pt.policy_no) ELSE pt.policy_no END AS policy_no, CASE WHEN pt.co_share = 1 THEN 'Yes' ELSE 'No' END AS co_share, CASE WHEN pt.bro_payable_by = 1 THEN 'Yes' ELSE 'No' END AS bro_payable_by, pcsd.non_comm_per_amt, pcsd.bp_igst, pcsd.bp_sgst, pcsd.bp_cgst, pcsd.agreed_bp_per, ROUND(pcsd.agreed_tp_per + pcsd.agreed_tep_per,2) AS agreed_tp_per, pcsd.standerd_bp_per, ROUND(pcsd.standerd_tp_per + pcsd.standerd_tep_per,2) AS standerd_tp_per, cssd.actual_bp_amt, ROUND(cssd.actual_tp_amt + cssd.actual_tep_amt,2) AS actual_tp_amt, cssd.actual_bp_per, ROUND(cssd.actual_tp_per + cssd.actual_tep_per,2) AS actual_tp_per, cssd.actual_tep_brokerage_amt, ROUND(cssd.actual_tp_brokerage_amt + cssd.actual_bp_brokerage_amt,2) AS actual_tp_brokerage_amt, service_branch.branch_name as service_branch, salse_manager.first_name as salse_manager_name, service_manager.first_name as service_manager_name, cd_master.cd_ac_no, pt.rollover_date, pt.policy_holder_name, CASE WHEN pt.same_as_proposer = 1 THEN 'Yes' ELSE 'No' END AS same_as_proposer, pcsd.follower_policy_no, pcsd.co_share_per, pcsd.stamp_duty, 'third' as query FROM policy_transaction pt LEFT JOIN pt_co_share_details pcsd ON pt.id = pcsd.pt_id LEFT JOIN co_share_stmt_details cssd ON pcsd.id = cssd.co_share_id LEFT JOIN insurer_statements insq ON cssd.statement_id = insq.id JOIN clients c ON c.id = pt.client_id LEFT JOIN client_branch cb ON pt.client_branch_id = cb.id LEFT JOIN client_policy cp ON pt.client_policy_id = cp.id LEFT JOIN user_profiles up ON pt.created_by = up.id LEFT JOIN vehicle v ON pt.vehicle_id = v.id LEFT JOIN policy_type ptype ON pt.policy_type_id = ptype.id LEFT JOIN insurers ins ON pcsd.insurer_id = ins.id LEFT JOIN insurer_branch ib ON pcsd.insurer_branch_id = ib.id LEFT JOIN tpa ON pt.tpa_id = tpa.id LEFT JOIN tpa_branch tb ON pt.tpa_branch_id = tb.id LEFT JOIN user_profiles su ON pt.sales_generated_by = su.id LEFT JOIN user_profiles se ON pt.serviced_by = se.id LEFT JOIN user_profiles created_user ON pt.created_by = created_user.id LEFT JOIN nhance_branch ON pt.issuer_branch = nhance_branch.id LEFT JOIN nhance_branch service_branch ON pt.service_person_branch_id = service_branch.id LEFT JOIN user_profiles salse_manager ON pt.salse_person_manager_id = salse_manager.id LEFT JOIN user_profiles service_manager ON pt.service_person_manager_id = service_manager.id LEFT JOIN cd_master ON pt.cd_ac_pk = cd_master.id WHERE pt.is_active = 1 AND pcsd.is_active = 1 AND cssd.is_active = 1 AND insq.is_active = 1 $default_date_filter $conditions ) AS final_result $statement_month_condition $main_conditions -- GROUP BY statement_month, insurer_name, policy_no -- WHERE id = 6143 ORDER BY id DESC, policy_no ASC, insurer_branch_name ASC, statement_uploaded ASC, statement_month ASC, STR_TO_DATE(policy_issue_month, '%b %Y') ASC "; $query = $this->db->query($sql); $result = $query->getResultArray(); return $this->processBDSReportResults($result); } /** * Post-process raw BDS report rows (dedup, rewards, unbilled amounts). */ public function processBDSReportResults(array $result): array { $keys = []; $filtered = []; foreach ($result as $row) { $endorsement_number = !empty($row['endorsement_no']) ? $row['endorsement_no'] : '-'; $reward = (float) ($row['reward'] ?? 0); $billed_amt = (float) ($row['billed_amt'] ?? 0); if ($reward == 0.00 && $billed_amt == 0.00 && $row['statement_uploaded'] === 'statement uploaded') { continue; } if ($reward > 0 && ($row['billed_amt'] ?? 0) == 0.00) { $row['total_irda_amt'] = '0.00'; $row['billed_amt'] = $reward; $rewardFlag = 'R'; } else { $rewardFlag = 'N'; } $key = implode('|', [ $row['statement_year_month'], $row['insurer_name'], $row['policy_no'], $endorsement_number, $rewardFlag, ]); if ($row['statement_uploaded'] === 'statement uploaded') { $filtered[$key] = $row; $keys[$key] = true; } elseif (!isset($keys[$key])) { $filtered[$key] = $row; } } $result = array_values($filtered); $totalBilled = []; $totalIrdaMap = []; foreach ($result as $row) { $key = $row['pt_id'] . '-' . $row['insurer_id']; $totalBilled[$key] = ($totalBilled[$key] ?? 0) + (float) ($row['billed_amt'] ?? 0); if (!isset($totalIrdaMap[$key])) { $totalIrdaMap[$key] = (float) $row['total_irda_amt']; } if (($row['reward'] ?? 0) > 0) { $totalIrdaMap[$key] = ($totalIrdaMap[$key] ?? 0) + (float) $row['reward']; } } $ptSeen = []; $final = []; foreach ($result as $row) { $ptId = $row['pt_id'] . '-' . $row['insurer_id']; if (!isset($ptSeen[$ptId])) { $totalIrdaVal = $totalIrdaMap[$ptId] ?? 0; $totalBilledVal = $totalBilled[$ptId] ?? 0; $addMinus = false; if ($totalIrdaVal < 0) { $totalIrdaVal = abs($totalIrdaVal); $totalBilledVal = abs($totalBilledVal); $addMinus = true; } $row['unbilled_amount'] = round((float) ($totalIrdaVal - $totalBilledVal), 2); if ($addMinus) { $row['unbilled_amount'] = ($row['unbilled_amount'] * -1); } $ptSeen[$ptId] = true; } else { $row['unbilled_amount'] = '0.00'; } $final[] = $row; } return $final; } /** * Cached processed BDS report list for a given filter set. */ public function getCachedBDSReportList(array $filters): array { $cacheKey = 'bds_report_v1_' . md5(json_encode($filters)); $cache = \Config\Services::cache(); $cached = $cache->get($cacheKey); if (is_array($cached)) { return $cached; } $processed = $this->getBDSReportList( $filters['start_date'] ?? 0, $filters['end_date'] ?? 0, $filters['client_id'] ?? 0, $filters['insurer_id'] ?? 0, $filters['policy_type_id'] ?? 0, $filters['date_type'] ?? 0, $filters['issuer'] ?? 0, $filters['client_branch_id'] ?? 0, $filters['insurer_branch_id'] ?? 0, $filters['client_policy_id'] ?? 0, $filters['user_id'] ?? 0, $filters['where'] ?? [] ); $cache->save($cacheKey, $processed, 300); return $processed; } /** * Server-side DataTables payload for BDS report. */ public function getBDSReportListDataTable(int $draw, int $start, int $length, string $searchValue, array $filters): array { $allRows = $this->getCachedBDSReportList($filters); $recordsTotal = count($allRows); if ($searchValue !== '') { $allRows = $this->filterBDSReportRowsBySearch($allRows, $searchValue); } $recordsFiltered = count($allRows); if ($length < 0) { $length = $recordsFiltered; } $pageRows = $length > 0 ? array_slice(array_values($allRows), $start, $length) : array_values($allRows); return [ 'draw' => $draw, 'recordsTotal' => $recordsTotal, 'recordsFiltered' => $recordsFiltered, 'data' => $pageRows, 'totals' => $this->calculateBDSReportTotals($allRows), ]; } /** * Global search across BDS report row fields. */ public function filterBDSReportRowsBySearch(array $rows, string $searchValue): array { $needle = mb_strtolower(trim($searchValue)); if ($needle === '') { return $rows; } // Match DataTables "common search" behavior against primary visible columns. $searchFields = [ 'user_name', 'policy_issue_month', 'client_name', 'action_type', 'policy_type', 'policy_no', 'endorsement_no', 'insurer_branch_name', ]; return array_values(array_filter($rows, static function (array $row) use ($needle, $searchFields) { foreach ($searchFields as $field) { $value = $row[$field] ?? ''; if ($value !== '' && mb_strpos(mb_strtolower((string) $value), $needle) !== false) { return true; } } $numericFields = [ 'bp_amt', 'tp_or_ter', 'premium_wo_gst', 'total_premium', 'agreed_bp_per', 'agreed_tp_or_ter_per', 'reward', 'total_irda_amt', 'billed_amt', 'unbilled_amount', ]; foreach ($numericFields as $field) { $value = $row[$field] ?? ''; if ($value !== '' && $value !== null && mb_strpos((string) $value, $needle) !== false) { return true; } } return false; })); } /** * Summary totals for BDS report badges (matches client-side footerCallback logic). */ public function calculateBDSReportTotals(array $rows): array { $totalPremium = 0.0; $totalRewards = 0.0; $totalIrda = 0.0; $totalBilled = 0.0; $totalUnbilled = 0.0; foreach ($rows as $row) { $hasIrda = ((float) ($row['total_irda_amt'] ?? 0)) != 0.0; $totalPremium += $hasIrda ? (float) ($row['premium_wo_gst'] ?? 0) : 0.0; $totalRewards += (float) ($row['reward'] ?? 0); $totalIrda += (float) ($row['total_irda_amt'] ?? 0); $totalBilled += (float) ($row['billed_amt'] ?? 0); $totalUnbilled += (float) ($row['unbilled_amount'] ?? 0); } $totalIrdaAmt = $totalBilled - $totalRewards; $totalRevenue = $totalIrdaAmt + $totalRewards; return [ 'total_premium' => number_format($totalPremium, 2, '.', ''), 'total_rewards' => number_format($totalRewards, 2, '.', ''), 'total_irda' => number_format($totalIrdaAmt, 2, '.', ''), 'total_revenue' => number_format($totalRevenue, 2, '.', ''), 'total_billed' => number_format($totalBilled, 2, '.', ''), 'total_unbilled' => number_format($totalUnbilled, 2, '.', ''), 'policy_count' => count($rows), ]; } }