nhance/app/Models/LeadsModel.php

362 lines
11 KiB
PHP

<?php
namespace App\Models;
use CodeIgniter\Model;
class LeadsModel extends Model
{
protected $table = 'leads';
protected $primaryKey = 'id';
protected $allowedFields = [
'id',
'actual_lead_id',
'lead_type',
'issuer',
'client_type',
'client_name',
'client_short_name',
'entity_type_id',
'client_code',
'cost_center',
'pan',
'gst',
'branch_name',
'branch_code',
'contact_person_name',
'contact_person_mobile',
'contact_person_email',
'client_id',
'client_branch_id',
'source_policy_id',
'policy_type_id',
'salse_person_id',
'insurer_id',
'insurer_branch_id',
'tpa_id',
'tpa_branch_id',
'policy_start_date',
'policy_end_date',
'no_of_lives',
'incurred_claims',
'location',
'proposed_insurer_id',
'proposed_insurer_branch_id',
'proposed_tpa_id',
'proposed_tpa_branch_id',
'proposel_data',
'status',
'notes',
'lost_reason',
'created_at',
'created_by',
'updated_at',
'updated_by',
'is_active',
'is_client_created',
'renewal_emp_count',
'renewal_dept_count',
'renewal_no_of_lives',
'incept_emp_count',
'incept_dept_count',
'incept_no_of_lives',
'exp_emp_count',
'exp_dept_count',
'exp_no_of_lives',
'file_name',
'incurred_claims_date',
'paid_claims',
'outstanding_claims',
'policy_run_days',
'premium_at_inception',
'premium_date',
'earned_premium',
'annualised_claims',
'incurred_claims_ratio',
'earned_claims_ratio',
'placement_date',
'utr_no',
'premium_amount',
'total_amount',
'cd_amount',
'total_si_at_incept',
'total_si_at_renewal',
'fin_years_claims',
'lead_form_type',
'custom_fields',
'source_policy_start_date',
'source_policy_end_date',
'payment_date',
'is_cd',
'is_installment',
'no_of_installment',
'is_policy_created',
'claim_history',
'total_lives_at_incept',
'premium_at_incept',
'next_reminder_date',
'is_insurer_auto_mail',
'quote_received_insurer',
'acm_id',
'policy_with_correction',
'agreed_percentage', 'misc',
'rfq_qcr_viewers',
];
// Callbacks
protected $allowCallbacks = true;
protected $beforeInsert = ["checkAndADDCreatedByValue"];
protected $afterInsert = [];
protected $beforeUpdate = ["checkAndUpdateUpdatedByValue"];
protected $afterUpdate = [];
protected $beforeFind = [];
protected $afterFind = [];
protected $beforeDelete = [];
protected $afterDelete = [];
protected function checkAndADDCreatedByValue(array $data)
{
// Check if 'updated_by' value is null or empty
if (empty($data['data']['created_by'])) {
// Set 'updated_by' value to the current session user ID
$data['data']['created_by'] = get_session_userid();
}
return $data;
}
protected function checkAndUpdateUpdatedByValue(array $data)
{
// Check if 'updated_by' value is null or empty
if (empty($data['data']['updated_by'])) {
// Set 'updated_by' value to the current session user ID
$data['data']['updated_by'] = get_session_userid();
}
return $data;
}
public function getLeadDataForLising($where = null)
{
$data = $this->select('
leads.*,
lead_files.status as demography_file_status,
kyc_entity_type.name as entity_type,
policy_type.policy_type,
user_profiles.first_name as salse_person_name,
(
SELECT COUNT(*) AS qcr_count
FROM rfq
WHERE type = 2
AND is_active = 1 and lead_id = leads.id
) AS qcr_count,
(
SELECT COUNT(*) AS rfq_count
FROM rfq
WHERE type = 1
AND is_active = 1 and lead_id = leads.id
) AS rfq_count
')
->join('kyc_entity_type', 'leads.entity_type_id = kyc_entity_type.id', 'left')
->join('user_profiles', 'leads.salse_person_id = user_profiles.id', 'left')
->join('policy_type', 'leads.policy_type_id = policy_type.id', 'left')
->join('lead_files', 'leads.id = lead_files.lead_id AND lead_files.type = 2 AND lead_files.is_active = 1', 'left')
->where('leads.is_active', 1);
if (get_role_id() == STAFF_ROLE_ID) {
$data->where('leads.created_by', get_session_userid());
}
if (! empty($where)) {
$data->where($where);
}
return $data->orderBy('leads.id', 'desc')->findAll();
}
public function getLeadForInsertClientList($type = null, $client_id = null)
{
$query = $this->db->table('leads')
->select('leads.*, user_profiles.first_name as user_name, policy_type.allocg')
->join('user_profiles', 'leads.created_by = user_profiles.id')
->join('policy_type', 'leads.policy_type_id = policy_type.id', 'left')
->where('leads.is_active', 1)
->where('leads.status', 'won')
->groupStart()
->where("(leads.is_client_created = '' OR leads.is_client_created IS NULL)")
->orWhere("(leads.is_policy_created = '' OR leads.is_policy_created IS NULL)")
->groupEnd()
->groupStart()
->where("policy_type.allocg != 'EB'")
->orWhere("(policy_type.allocg = 'EB' AND leads.proposel_data IS NOT NULL AND leads.proposel_data <> '')")
->groupEnd();
if ($type) {
$query->where('leads.lead_type', $type);
}
if ($client_id) {
$query->where('leads.client_id', $client_id);
}
$result = $query->get()->getResultArray();
return $result;
}
// public function getDashData()
// {
// $statuses = $this->db->table('leads')
// ->select('status, policy_with_correction')
// ->where("is_active", 1)
// ->groupBy('status')
// ->get()
// ->getResultArray();
// $policy_with_correction_count = $this->db->table('leads')
// ->where('is_active', 1)
// ->where('policy_with_correction', 1)
// ->countAllResults();
// $selectParts = [];
// foreach ($statuses as $status) {
// $s = $status['status'];
// $alias = strtolower(str_replace(' ', '_', $s));
// // Count alias
// $selectParts[] = "SUM(CASE WHEN status = '{$s}' THEN 1 ELSE 0 END) AS `{$alias}`";
// // IDs alias
// $selectParts[] = "GROUP_CONCAT(CASE WHEN status = '{$s}' THEN leads.id ELSE NULL END) AS `{$alias}_ids`";
// }
// $select = implode(", ", $selectParts);
// // Start query builder
// $builder = $this->db->table('leads');
// $builder->select($select);
// // Auditing subquery
// $subquery = "(SELECT pk, MAX(created_at) AS last_claim_status_change
// FROM auditing_history
// WHERE table_name = 'leads' AND field_name = 'status'
// GROUP BY pk)";
// $builder->join("{$subquery} AS th", 'leads.id = th.pk', 'left');
// // Date filtering for last status change
// $dateLimit = 3;
// $dateThreshold = date('Y-m-d H:i:s', strtotime("-{$dateLimit} days"));
// $builder->groupStart()
// ->where('th.last_claim_status_change <=', $dateThreshold)
// ->orWhere('th.last_claim_status_change IS NULL')
// ->groupEnd();
// // Add only active
// $builder->where("leads.is_active", 1);
// $lead_data = $builder->get()->getResultArray();
// // dd($this->db->getLastQuery());
// // Fallback for empty results
// if (empty($lead_data)) {
// $lead_data[0] = ['total' => 0];
// foreach ($statuses as $status) {
// $alias = strtolower(str_replace(' ', '_', $status['status']));
// $lead_data[0][$alias] = 0;
// $lead_data[0]["{$alias}_ids"] = '';
// }
// }
// // Calculate total
// $total = 0;
// foreach ($lead_data[0] as $key => $value) {
// // if (!str_ends_with($key, '_ids') && $key != "won") {
// // $total += (int) $value;
// // }
// if (!str_ends_with($key, '_ids')) {
// $total += (int) $value;
// }
// }
// $total = $total + $policy_with_correction_count ?? 0;
// $lead_data[0]['total'] = $total;
// $lead_data[0]['policy_with_correction'] = $policy_with_correction_count;
// // dd($lead_data[0]);
// return $lead_data[0];
// }
public function getDashData()
{
// Get all unique statuses
$statuses = $this->db->table('leads')
->select('DISTINCT(status)')
->where('is_active', 1)
->get()
->getResultArray();
$policy_with_correction_data = $this->db->table('leads')
->select('COUNT(id) AS count, GROUP_CONCAT(id) AS ids')
->where('is_active', 1)
->where('policy_with_correction', 1)
->get()
->getRowArray();
if (empty($statuses)) {
return ['total' => 0];
}
// Build dynamic select fields for each status
$selectParts = [];
foreach ($statuses as $row) {
$status = $row['status'];
$alias = strtolower(str_replace(' ', '_', $status));
$selectParts[] = "SUM(CASE WHEN status = '{$status}' THEN 1 ELSE 0 END) AS `{$alias}`";
$selectParts[] = "GROUP_CONCAT(CASE WHEN status = '{$status}' THEN id END) AS `{$alias}_ids`";
}
$select = implode(", ", $selectParts);
// Main query
$lead_data = $this->db->table('leads')
->select($select)
->where('is_active', 1)
->get()
->getRowArray();
// Calculate total
$total = 0;
foreach ($lead_data as $key => $val) {
if (! str_ends_with($key, '_ids')) {
$total += (int) $val;
}
}
$lead_data['total'] = $total;
$lead_data['policy_with_correction'] = $policy_with_correction_data['count'] ?? 0;
$lead_data['policy_with_correction_ids'] = $policy_with_correction_data['ids'] ?? null;
// dd($lead_data);
return $lead_data;
}
}