diff --git a/.env.sample b/.env.sample
index 49343c62..5c3f1bf8 100755
--- a/.env.sample
+++ b/.env.sample
@@ -129,4 +129,12 @@ HEALTH_INDIA_TOKEN_URL =
HEALTH_INDIA_USERNAME =
HEALTH_INDIA_PASSWORD =
-HEALTH_INDIA_PRIMARY_KEY_CONSTANT =
\ No newline at end of file
+HEALTH_INDIA_PRIMARY_KEY_CONSTANT =
+
+#For sending mail for leads RFQ/QCR
+LEAD_INSURER_FROM_MAIL_ID =
+LEAD_CLIENT_FROM_MAIL_ID =
+
+# BDS Daily Report Emails Configuration
+bds.dailyReportEmails =
+
diff --git a/app/Config/RfqConfig.php b/app/Config/RfqConfig.php
new file mode 100644
index 00000000..ca536901
--- /dev/null
+++ b/app/Config/RfqConfig.php
@@ -0,0 +1,51 @@
+ [
+ 'vitvelz@gmail.com',
+ 'velz1990@gmail.com',
+ 'venkateshraman786@gmail.com',
+ ],
+ 'viewers' => [],
+ ];
+
+ /**
+ * Default protections for RFQ sheets.
+ * Copied from GoogleSheetController::$config.
+ */
+ public array $protections = [
+ [
+ 'range' => 'RFQ Page!B12:C12',
+ 'users' => [
+ 'velz1990@gmail.com',
+ 'vitvelz@gmail.com',
+ 'firebase-adminsdk-mcdfe@nhance-ee8d1.iam.gserviceaccount.com',
+ ],
+ 'groups' => [],
+ ],
+ [
+ 'range' => 'Claims Page!A1',
+ 'users' => [
+ 'velz1990@gmail.com',
+ 'venkateshraman786@gmail.com',
+ 'firebase-adminsdk-mcdfe@nhance-ee8d1.iam.gserviceaccount.com',
+ ],
+ 'groups' => [],
+ ],
+ ];
+}
diff --git a/app/Config/Routes.php b/app/Config/Routes.php
index cf88f2b9..09d117f3 100755
--- a/app/Config/Routes.php
+++ b/app/Config/Routes.php
@@ -446,11 +446,15 @@ $routes->group("/util", ["filter" => "authMVC"], function ($routes) {
$routes->get('generateDemographyDataTable', 'LeadsController::generateDemographyDataTable');
$routes->post('insufficientCdBalanceHrMailSend', 'EmployeeController::insufficientCdBalanceHrMailSend');
$routes->get('getTpaClaimDumpErrorData/(:any)', 'TicketServiceController::getTpaClaimDumpErrorData/$1');
-
+ $routes->get('croneDailyActivityReport', 'DashboardController::croneDailyActivityReport');
});
$routes->post("policy_tranction/sendInstallmentRemainderMail","PolicyTransactionController::sendInstallmentRemainderMail");
$routes->cli("cli/sendInstallmentRemainderMail","PolicyTransactionController::sendInstallmentRemainderMail");
+$routes->cli("cli/cronDailyBDSReport", "PolicyTransactionController::cronDailyBDSReport");
+$routes->cli('cli/croneDailyActivityReport', 'DashboardController::croneDailyActivityReport');
+
+
$routes->group("policy_tranction", ["filter" => "authMVC"], function ($routes) {
@@ -498,6 +502,7 @@ $routes->group("policy_tranction", ["filter" => "authMVC"], function ($routes) {
//$routes->post('failedStatement',"PolicyTransactionController::failedStatementList");
});
+ $routes->get("cronDailyBDSReport", "PolicyTransactionController::cronDailyBDSReport");
});
$routes->group("leads", ["filter" => "authMVC"], function ($routes) {
@@ -505,6 +510,8 @@ $routes->group("leads", ["filter" => "authMVC"], function ($routes) {
$routes->match(['get', 'post'],"list", "LeadsController::viewLeadsList");
$routes->post("create", "LeadsController::createLead");
$routes->get("list/(:any)", "LeadsController::getLeadDataForEdit/$1");
+ $routes->get("createRfqSheet", "LeadsController::createRfqSheet");
+ $routes->get("mailTemplate", "LeadsController::getLeadMailTemplate");
$routes->get("sendMail", "LeadsController::sendMailWithAttachement");
$routes->post("sendMail", "LeadsController::sendMailWithAttachement");
$routes->get("exportQCRandRFQ/(:any)", "LeadsController::exportQCRandRFQ/$1");
@@ -518,6 +525,10 @@ $routes->group("rfq", ["filter" => "authMVC"], function ($routes) {
$routes->post("createQCR", "LeadsController::createQCR");
$routes->get("list/(:any)", "LeadsController::viewRFQ/$1");
$routes->get("nonEB","LeadsController::rfqNonEB");
+ // Non-EB dedicated RFQ/QCR endpoints (do not alter existing ones)
+ $routes->get("nonEB/rfq/(:any)","LeadsController::viewNonEbRFQFromList/$1");
+ $routes->get("nonEB/qcr/(:any)","LeadsController::viewNonEbQCRFromList/$1");
+ $routes->get("placementData/(:num)", "LeadsController::getPlacementData/$1");
});
@@ -547,9 +558,18 @@ $routes->cli("cli/sendCroneRemainderMail", "DashboardController::sendCroneRemain
$routes->cli('cli/update-emp-policy-status', 'ClientController::updateEmpAndPolicyStatus');
$routes->cli('cli/insurerRFQRemainder', 'LeadsController::remainderForQcr');
$routes->cli('cli/sendMailWithAutoQuery','TicketController::sendMailWithAutoQuery');
+
+// Claim Status Update every 2 hours
$routes->cli('cli/MediAssit-ClaimStatusUpdate','MediAssistApiController::ClaimStatusUpdate');
$routes->cli('cli/Vidal-ClaimStatusUpdate','VidalApiController::ClaimStatusUpdate');
+$routes->cli('cli/Fhpl-ClaimStatusUpdate','FhplApiController::ClaimStatusUpdate');
+$routes->cli('cli/HealthIndia-ClaimStatusUpdate','HealthIndiaApiController::ClaimStatusUpdate');
+
+// Sync TPA Claims to Nhance
$routes->cli('cli/MediAssit-syncTpaClaimToNhance','MediAssistApiController::syncTpaClaimToNhance');
+$routes->cli('cli/Fhpl-syncTpaClaimToNhance','FhplApiController::syncFhplClaimsToNhance');
+$routes->cli('cli/HealthIndia-syncTpaClaimToNhance','HealthIndiaApiController::syncHealthIndiaClaimsToNhance');
+
$routes->cli('cli/thzReminderCrone','ThzController::getOpenTicketsOlderThan24HoursAndAssignNextLevel');
@@ -766,6 +786,7 @@ $routes->group("/ticket", ["filter" => "authMVC"], function ($routes) {
$routes->get('fetchVehiclePolicy/(:any)','TicketController::fetchVehiclePolicy/$1');
$routes->post('saveIRDocsJson',"TicketController::saveIRDocsJson");
$routes->get('getTpaClaimStatus',"ApiServiceController::getClaimStatus");
+ $routes->post('manualTpaClaimPush',"ApiServiceController::manualTpaClaimPush");
});
$routes->group("/claim_mis", ["filter" => "authMVC"], function ($routes) {
diff --git a/app/Controllers/ApiServiceController.php b/app/Controllers/ApiServiceController.php
index 28b2aec6..16a650a0 100644
--- a/app/Controllers/ApiServiceController.php
+++ b/app/Controllers/ApiServiceController.php
@@ -476,6 +476,35 @@ class ApiServiceController extends BaseController
}
}
+ /**
+ * Manual TPA Claim Push - accepts claim_id via POST and delegates to pushClaims().
+ * Returns the response from pushClaims() as the API response.
+ */
+ public function manualTpaClaimPush()
+ {
+ $claimId = $this->request->getPost('claim_id');
+
+ if (empty($claimId)) {
+ return $this->response->setJSON([
+ 'status' => false,
+ 'message' => 'claim_id is required'
+ ]);
+ }
+
+ $result = $this->pushClaims($claimId);
+
+ if ($result !== null && is_array($result)) {
+ return $this->response->setJSON([
+ 'status' => $result['status'] ?? false,
+ 'message' => $result['message'] ?? ($result['status'] ? 'Claim pushed successfully' : 'Claim push failed')
+ ]);
+ }
+
+ return $this->response->setJSON([
+ 'status' => false,
+ 'message' => 'Claim push failed or TPA has no API service enabled for this ticket.'
+ ]);
+ }
// public function getWellnessUrl()
diff --git a/app/Controllers/ClientController.php b/app/Controllers/ClientController.php
index 6d2064fa..ee3a8098 100755
--- a/app/Controllers/ClientController.php
+++ b/app/Controllers/ClientController.php
@@ -6975,7 +6975,9 @@ class ClientController extends AdminController
// $response = $ticketServiceController->tpaClaimDumpImporter(["file_id" => 53]); //icici
// $response = $ticketServiceController->tpaClaimDumpImporter(["file_id" => 54]); //mediassist
// $response = $ticketServiceController->tpaClaimDumpImporter(["file_id" => 52]); //reliance
- // $response = $ticketServiceController->tpaClaimDumpImporter(["file_id" => 48]); //vidal
+ // $response = $ticketServiceController->tpaClaimDumpImporter(["file_id" => 48]); //vidal`
+ // $response = $ticketServiceController->tpaClaimDumpImporter(["file_id" => 57]); //mediassist
+
// $response = $ticketServiceController->tpaClaimDumpToTicketMasterImporters(["file_id" => 51]); //abhi
// $response = $ticketServiceController->tpaClaimDumpToTicketMasterImporters(["file_id" => 50]); //fhpl
diff --git a/app/Controllers/DashboardController.php b/app/Controllers/DashboardController.php
index 1dab325b..b4d224fe 100755
--- a/app/Controllers/DashboardController.php
+++ b/app/Controllers/DashboardController.php
@@ -7,6 +7,7 @@ use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;
use App\Helpers\sendMailNotification;
+use App\Helpers\MailHelper;
use CodeIgniter\API\ResponseTrait;
@@ -24,6 +25,11 @@ use App\Controllers\EmpDataServiceController;
use App\Models\TicketMasterModel;
use App\Models\LeadsModel;
use App\Models\TicketClaimStatusModel;
+use App\Models\FileModel;
+use App\Models\BatchFileModel;
+use App\Models\SalesActivityModel;
+use App\Models\SalesActualLeadModel;
+
class DashboardController extends AdminController
@@ -43,6 +49,13 @@ class DashboardController extends AdminController
protected $policyStatus;
protected $colorShades;
protected $claimDashLimit;
+ protected $filesModel;
+ protected $batchFilesModel;
+ protected $leadsModel;
+ protected $ticketMasterModel;
+ protected $ticketClaimStatusModel;
+ protected $salesActivityModel;
+ protected $salesActualModel;
protected $myLogger;
@@ -59,6 +72,13 @@ class DashboardController extends AdminController
$this->ticketModel = new TicketMasterModel();
$this->leadModel = new LeadsModel();
$this->ticketStatusModel = new TicketClaimStatusModel();
+ $this->filesModel = new FileModel();
+ $this->batchFilesModel = new BatchFileModel();
+ $this->leadsModel = new LeadsModel();
+ $this->ticketMasterModel = new TicketMasterModel();
+ $this->ticketClaimStatusModel = new TicketClaimStatusModel();
+ $this->salesActivityModel = new SalesActivityModel();
+ $this->salesActualModel = new SalesActualLeadModel();
$this->myLogger = \Config\Services::mylogger();
@@ -787,4 +807,298 @@ class DashboardController extends AdminController
$data['ticket_type_id'] = $ticketTypeId;
return $this->respond(['status' => "success", "data" => $data], 200);
}
+
+ public function croneDailyActivityReport()
+ {
+
+ // $today = date('Y-m-d');
+ $today = date('Y-m-d', strtotime('-1 day'));
+
+ // Inception & endorsement counts (file uploads)
+ $total_inception_count = $this->filesModel
+ ->where('is_active', 1)
+ ->where('DATE(created_at)', $today)
+ ->where('action', 'inception')
+ ->where('status', 'success')
+ ->countAllResults();
+
+ $total_endorsement_count = $this->filesModel
+ ->where('is_active', 1)
+ ->where('DATE(created_at)', $today)
+ ->where('action !=', 'inception')
+ ->where('status', 'success')
+ ->countAllResults();
+
+ // TPA & Insurer batch file counts
+ $total_tpa_incetion_count = $this->batchFilesModel
+ ->where('is_active', 1)
+ ->where('DATE(created_at)', $today)
+ ->where('event_type', 'inception')
+ ->where('insurer_or_tpa', 'tpa')
+ ->where('status', 'success')
+ ->countAllResults();
+
+ $total_tpa_endorsement_count = $this->batchFilesModel
+ ->where('is_active', 1)
+ ->where('DATE(created_at)', $today)
+ ->where('event_type !=', 'inception')
+ ->where('insurer_or_tpa', 'tpa')
+ ->where('status', 'success')
+ ->countAllResults();
+
+ $total_insurer_incetion_count = $this->batchFilesModel
+ ->where('is_active', 1)
+ ->where('DATE(created_at)', $today)
+ ->where('event_type', 'inception')
+ ->where('insurer_or_tpa', 'insurer')
+ ->where('status', 'success')
+ ->countAllResults();
+
+ $total_insurer_endorsement_count = $this->batchFilesModel
+ ->where('is_active', 1)
+ ->where('DATE(created_at)', $today)
+ ->where('event_type !=', 'inception')
+ ->where('insurer_or_tpa', 'insurer')
+ ->where('status', 'success')
+ ->countAllResults();
+
+ // Claim counts
+ $total_claim_count = $this->ticketMasterModel
+ ->where('is_active', 1)
+ ->where('DATE(created_at)', $today)
+ ->countAllResults();
+
+ $total_gmc_status_wise_claim_count = $this->ticketMasterModel
+ ->select('tcs.claim_status, count(*) as count')
+ ->join('ticket_claim_status tcs', 'tcs.id = ticket_master.claim_status_id', 'left')
+ ->where('ticket_master.is_active', 1)
+ ->where('ticket_master.ticket_type_id', 1)
+ // ->where('DATE(ticket_master.created_at)', $today)
+ ->where('tcs.is_active', 1)
+ ->groupBy('tcs.claim_status')
+ ->findAll();
+
+ $total_gpa_status_wise_claim_count = $this->ticketMasterModel
+ ->select('tcs.claim_status, count(*) as count')
+ ->join('ticket_claim_status tcs', 'tcs.id = ticket_master.claim_status_id', 'left')
+ ->where('ticket_master.is_active', 1)
+ ->where('ticket_master.ticket_type_id', 2)
+ // ->where('DATE(ticket_master.created_at)', $today)
+ ->where('tcs.is_active', 1)
+ ->groupBy('tcs.claim_status')
+ ->findAll();
+
+ $total_edli_status_wise_claim_count = $this->ticketMasterModel
+ ->select('tcs.claim_status, count(*) as count')
+ ->join('ticket_claim_status tcs', 'tcs.id = ticket_master.claim_status_id', 'left')
+ ->where('ticket_master.is_active', 1)
+ ->where('ticket_master.ticket_type_id', 3)
+ // ->where('DATE(ticket_master.created_at)', $today)
+ ->where('tcs.is_active', 1)
+ ->groupBy('tcs.claim_status')
+ ->findAll();
+
+ $total_gtli_status_wise_claim_count = $this->ticketMasterModel
+ ->select('tcs.claim_status, count(*) as count')
+ ->join('ticket_claim_status tcs', 'tcs.id = ticket_master.claim_status_id', 'left')
+ ->where('ticket_master.is_active', 1)
+ ->where('ticket_master.ticket_type_id', 4)
+ // ->where('DATE(ticket_master.created_at)', $today)
+ ->where('tcs.is_active', 1)
+ ->groupBy('tcs.claim_status')
+ ->findAll();
+
+ // Sales / lead counts
+ $total_opportunity_count = $this->leadsModel
+ ->where('is_active', 1)
+ ->where('DATE(created_at)', $today)
+ ->countAllResults();
+
+ $total_rfq_created_count = $this->leadsModel
+ ->where('is_active', 1)
+ ->where('DATE(created_at)', $today)
+ ->where('status', 'rfq_created')
+ ->countAllResults();
+
+ $total_rfq_insurer_send_count = $this->leadsModel
+ ->where('is_active', 1)
+ ->where('DATE(created_at)', $today)
+ ->where('status', 'rfq_sent')
+ ->countAllResults();
+
+ $total_qcr_created_count = $this->leadsModel
+ ->where('is_active', 1)
+ ->where('DATE(created_at)', $today)
+ ->where('status', 'qcr_created')
+ ->countAllResults();
+
+ $total_qcr_client_send_count = $this->leadsModel
+ ->where('is_active', 1)
+ ->where('DATE(created_at)', $today)
+ ->where('status', 'qcr_sent')
+ ->countAllResults();
+
+ $total_placement_count = $this->leadsModel
+ ->where('is_active', 1)
+ ->where('DATE(created_at)', $today)
+ ->where('status', 'won')
+ ->countAllResults();
+
+ $total_activity_count = $this->salesActivityModel
+ ->where('DATE(created_at)', $today)
+ ->countAllResults();
+
+ $total_lead_count = $this->salesActualModel
+ ->where('DATE(created_at)', $today)
+ ->countAllResults();
+
+ $total_bds_count = $this->policyTransactionModel
+ ->select('pt_co_share_details.*')
+ ->join('pt_co_share_details', 'policy_transaction.id = pt_co_share_details.pt_id')
+ ->where('DATE(policy_transaction.created_at)', $today)
+ ->where('pt_co_share_details.is_active', 1)
+ ->where('policy_transaction.is_active', 1)
+ ->countAllResults();
+
+ $total_bds_policy_wise_count = $this->policyTransactionModel
+ ->select('pt_co_share_details.*')
+ ->join('pt_co_share_details', 'policy_transaction.id = pt_co_share_details.pt_id')
+ ->where('DATE(policy_transaction.created_at)', $today)
+ ->where('pt_co_share_details.is_active', 1)
+ ->where('policy_transaction.action_type', 'inception')
+ ->where('policy_transaction.is_active', 1)
+ ->countAllResults();
+
+
+ $total_bds_endorsement_wise_count = $this->policyTransactionModel
+ ->select('pt_co_share_details.*')
+ ->join('pt_co_share_details', 'policy_transaction.id = pt_co_share_details.pt_id')
+ ->where('DATE(policy_transaction.created_at)', $today)
+ ->where('pt_co_share_details.is_active', 1)
+ ->where('policy_transaction.action_type !=', 'inception')
+ ->where('policy_transaction.is_active', 1)
+ ->countAllResults();
+
+ $total_bds_policy_type_wise_count = $this->policyTransactionModel
+ ->select('policy_type.policy_type, count(*) as count')
+ ->join('pt_co_share_details', 'policy_transaction.id = pt_co_share_details.pt_id')
+ ->join('policy_type', 'policy_transaction.policy_type_id = policy_type.id')
+ ->where('DATE(policy_transaction.created_at)', $today)
+ ->where('pt_co_share_details.is_active', 1)
+ ->where('policy_transaction.is_active', 1)
+ ->groupBy('policy_transaction.policy_type_id')
+ ->findAll();
+
+ // Connect Pre DB for Employee Enrollment Count
+
+ $db2 = \Config\Database::connect('preDB');
+
+ $builder = $db2->table('employees');
+ $total_employee_draft_count = $builder->join('employee_polices', 'employees.id = employee_polices.employee_id')
+ ->select('employee_polices.status, count(*) as count')
+ ->where('DATE(employee_polices.created_at)', $today)
+ ->where('employee_polices.is_active', 1)
+ ->where('employees.is_active', 1)
+ ->whereIn('employee_polices.status', ['draft'])
+ ->groupBy('employee_polices.status')
+ ->countAllResults();
+
+
+ $builder1 = $db2->table('employees');
+ $total_employee_enrolled_count = $builder1->join('employee_polices', 'employees.id = employee_polices.employee_id')
+ ->select('employee_polices.status, count(*) as count')
+ ->where('DATE(employee_polices.created_at)', $today)
+ ->where('employee_polices.is_active', 1)
+ ->where('employees.is_active', 1)
+ ->whereIn('employee_polices.status', ['enrolled'])
+ ->groupBy('employee_polices.status')
+ ->countAllResults();
+
+ $builder2 = $db2->table('files');
+ $total_open_for_enrollemnt_policy_count = $builder2
+ ->select('COUNT(*) as count')
+ ->where('enrollment_open_date <=', $today)
+ ->where('enrollment_close_date >=', $today)
+ ->where('is_active', 1)
+ ->where('status', 'success')
+ ->countAllResults();
+
+ $data = [
+ 'total_inception_count' => $total_inception_count,
+ 'total_endorsement_count' => $total_endorsement_count,
+ 'total_tpa_incetion_count' => $total_tpa_incetion_count,
+ 'total_tpa_endorsement_count' => $total_tpa_endorsement_count,
+ 'total_insurer_incetion_count' => $total_insurer_incetion_count,
+ 'total_insurer_endorsement_count' => $total_insurer_endorsement_count,
+ 'total_claim_count' => $total_claim_count,
+ 'total_gmc_status_wise_claim_count' => $total_gmc_status_wise_claim_count,
+ 'total_gpa_status_wise_claim_count' => $total_gpa_status_wise_claim_count,
+ 'total_edli_status_wise_claim_count' => $total_edli_status_wise_claim_count,
+ 'total_gtli_status_wise_claim_count' => $total_gtli_status_wise_claim_count,
+ 'total_opportunity_count' => $total_opportunity_count,
+ 'total_rfq_created_count' => $total_rfq_created_count,
+ 'total_rfq_insurer_send_count' => $total_rfq_insurer_send_count,
+ 'total_qcr_created_count' => $total_qcr_created_count,
+ 'total_qcr_client_send_count' => $total_qcr_client_send_count,
+ 'total_placement_count' => $total_placement_count,
+ 'total_activity_count' => $total_activity_count,
+ 'total_lead_count' => $total_lead_count,
+ 'total_bds_count' => $total_bds_count,
+ 'total_bds_policy_wise_count' => $total_bds_policy_wise_count,
+ 'total_bds_endorsement_wise_count' => $total_bds_endorsement_wise_count,
+ 'total_bds_policy_type_wise_count' => $total_bds_policy_type_wise_count,
+ 'total_employee_draft_count' => $total_employee_draft_count,
+ 'total_employee_enrolled_count' => $total_employee_enrolled_count,
+ 'total_open_for_enrollemnt_policy_count' => $total_open_for_enrollemnt_policy_count,
+ ];
+
+ // dd($data);
+
+ $today = date('d-m-Y', strtotime($today));
+ $data['today'] = $today;
+
+ // Render the HTML email using the dedicated view
+ $message = view('daily_report_email_template', $data);
+ // return $message;
+
+ // Recipients: prefer dedicated env, fallback to BDS report emails if not set
+ $emailList = getenv('activity.dailyReportEmails') ?: getenv('bds.dailyReportEmails') ?: '';
+ $recipientEmails = array_filter(array_map('trim', explode(',', $emailList)));
+
+ if (empty($recipientEmails)) {
+ $this->myLogger->logme('error', 'croneDailyActivityReport: No recipients configured (set activity.dailyReportEmails in .env).');
+ return $this->respond([
+ 'status' => 'success',
+ 'message' => 'Daily activity data prepared but no recipients configured.',
+ 'data' => $data,
+ ], 200);
+ }
+
+ $subject = "Daily Activity Report - {$today}";
+
+ $res = MailHelper::send_email([
+ 'mail' => $recipientEmails,
+ 'subject' => $subject,
+ 'message' => $message,
+ ]);
+
+ $resDecoded = is_string($res) ? json_decode($res, true) : $res;
+
+ if (isset($resDecoded['status']) && $resDecoded['status'] === 'success') {
+ $this->myLogger->logme('error', 'croneDailyActivityReport: Report email sent to ' . count($recipientEmails) . ' recipients');
+ return $this->respond([
+ 'status' => true,
+ 'message' => 'Daily activity report emailed successfully.',
+ 'recipients' => count($recipientEmails),
+ ], 200);
+ }
+
+ $this->myLogger->logme('error', 'croneDailyActivityReport: Email send failed - ' . json_encode($resDecoded));
+ return $this->respond([
+ 'status' => false,
+ 'message' => 'Daily activity data prepared but email send failed.',
+ 'data' => $data,
+ ], 500);
+ }
+
}
diff --git a/app/Controllers/EmployeeRestController.php b/app/Controllers/EmployeeRestController.php
index 3a0bea5b..df5dcfab 100755
--- a/app/Controllers/EmployeeRestController.php
+++ b/app/Controllers/EmployeeRestController.php
@@ -2418,6 +2418,11 @@ class EmployeeRestController extends AdminController
["ticket_type" => "4", "type_name" => "GTLI"],
];
+ $claim_type = $this->ticketController->claimType;
+ unset($claim_type[1][2]);
+ unset($claim_type[1][4]);
+ $data['claim_type'] = $claim_type;
+
return $this->respond(['status' => (count($data) ? 'success' : 'failed'), 'code' => (count($data) ? 200 : 404), 'data' => $data], 200);
}
@@ -2581,61 +2586,90 @@ class EmployeeRestController extends AdminController
$required_docs = $this->ticketMaster->select('required_docs')->where('id', $ticket_id)->first();
$data['required_docs'] = json_decode($required_docs['required_docs'] ?? '{}', true) ?? [];
- // $ticketData = $data['ticket_data'];
- // $ticketHistory = $data['ticket_history'];
- // print_r($ticketHistory); die;
+ // print_rr($data['ticket_history']); die;
+
+ $filteredArray = array_filter($data['ticket_history'], function($item) {
+ return $item['field_name'] == 'claim_status_id';
+ });
+
+ $filteredArray = array_reverse(array_values($filteredArray));
$currentClaimStatus = $this->claimStatusModel->select("claim_status")->where('id', $data['claims_data']['claim_status_id'])->where('is_active', 1)->first();
$ticketClaimStatus = $this->claimStatusModel->select('claim_status, display_name')->where('display_name is not null')->where('ticket_type', $data['claims_data']['ticket_type_id'])->where('is_active', 1)->findAll();
$status_list = array_column($ticketClaimStatus, 'display_name', 'claim_status');
- // print_r($currentClaimStatus); die;
+ // dd($filteredArray, $status_list); die;
- $data['ticket_data'] = array_fill_keys(array_keys($data['ticket_data']), []);
+ $filtered_history = [];
+ $counter = 0;
+
+ foreach ($filteredArray as $key => $value) {
+ foreach ($status_list as $status => $display_name) {
+ if ($value['new_value'] == $status) {
- // Loop through ticket_data
- foreach ($data['ticket_data'] as $status => &$fields) {
- // Search ticket_history for matching old_status_value
- foreach ($data['ticket_history'] as $history) {
+ if($display_name == 'Under Process'){
+ $unique_key = $display_name . str_repeat("\u{200B}", $counter++);
+ }else{
+ $unique_key = $display_name;
+ }
- if ($history['old_status_value'] === $status) {
- // Attach modified_by and created_at
- // $fields['modified_by'] = $history['modified_by'];
- $fields['modified_by'] = "";
- $fields['modified_at'] = date('d-m-Y h:i A', strtotime($history['created_at']));
- // Break after first match (assuming latest entry is enough)
- break;
+ $filtered_history[$unique_key] = [
+ 'modified_by' => "",
+ 'modified_at' => date('d-m-Y h:i A', strtotime($value['created_at'])),
+ ];
}
}
}
+ // dd($filteredArray, $status_list, $filtered_history); die;
- $data['ticket_data'][$currentClaimStatus['claim_status']]['modified_by'] = "";
- $data['ticket_data'][$currentClaimStatus['claim_status']]['modified_at'] = $formatted = date('d-m-Y h:i A', strtotime($data['claims_data']['updated_at']));
- $new_ticket_data = [];
- foreach ($data['ticket_data'] as $oldKey => $value) {
+ // $data['ticket_data'] = array_fill_keys(array_keys($data['ticket_data']), []);
- // Only process if key exists in status_list
- if (! isset($status_list[$oldKey])) {
- continue; // skip and do NOT add to new array
- }
+ // // Loop through ticket_data
+ // foreach ($data['ticket_data'] as $status => &$fields) {
+ // // Search ticket_history for matching old_status_value
+ // foreach ($data['ticket_history'] as $history) {
- // Get new key based on mapping
- $newKey = $status_list[$oldKey];
+ // if ($history['old_status_value'] === $status) {
+ // // Attach modified_by and created_at
+ // // $fields['modified_by'] = $history['modified_by'];
+ // $fields['modified_by'] = "";
+ // $fields['modified_at'] = date('d-m-Y h:i A', strtotime($history['created_at']));
+ // // Break after first match (assuming latest entry is enough)
+ // break;
+ // }
+ // }
+ // }
- // Avoid duplicates
- if (! isset($new_ticket_data[$newKey])) {
- $new_ticket_data[$newKey] = $value;
- }
- }
+ // $data['ticket_data'][$currentClaimStatus['claim_status']]['modified_by'] = "";
+ // $data['ticket_data'][$currentClaimStatus['claim_status']]['modified_at'] = $formatted = date('d-m-Y h:i A', strtotime($data['claims_data']['updated_at']));
- uasort($new_ticket_data, function ($a, $b) {
- $timeA = \DateTime::createFromFormat('d-m-Y h:i A', $a['modified_at']);
- $timeB = \DateTime::createFromFormat('d-m-Y h:i A', $b['modified_at']);
- return $timeA <=> $timeB; // Ascending
- });
+ // $new_ticket_data = [];
- $data['ticket_data'] = $new_ticket_data;
+ // foreach ($data['ticket_data'] as $oldKey => $value) {
+
+ // // Only process if key exists in status_list
+ // if (! isset($status_list[$oldKey])) {
+ // continue; // skip and do NOT add to new array
+ // }
+
+ // // Get new key based on mapping
+ // $newKey = $status_list[$oldKey];
+
+ // // Avoid duplicates
+ // if (! isset($new_ticket_data[$newKey])) {
+ // $new_ticket_data[$newKey] = $value;
+ // }
+ // }
+
+ // uasort($new_ticket_data, function ($a, $b) {
+ // $timeA = \DateTime::createFromFormat('d-m-Y h:i A', $a['modified_at']);
+ // $timeB = \DateTime::createFromFormat('d-m-Y h:i A', $b['modified_at']);
+ // return $timeA <=> $timeB; // Ascending
+ // });
+
+ // $data['ticket_data'] = $new_ticket_data;
+ $data['ticket_data'] = $filtered_history;
$ticketMesssageModel = new TicketMessageModel();
$ticket_message = $ticketMesssageModel
@@ -5451,7 +5485,7 @@ class EmployeeRestController extends AdminController
'dashboard' => $database_id,
],
'exp' => time() + (10 * 60),
- 'params' => (object) [],
+ 'params' => (object) ['client_policy' => $policy_id ], // MUST be object for Metabase
];
$token = JWT::encode($payload, $METABASE_SECRET_KEY, 'HS256');
diff --git a/app/Controllers/FhplApiController.php b/app/Controllers/FhplApiController.php
index 734bb438..8c3e76e1 100644
--- a/app/Controllers/FhplApiController.php
+++ b/app/Controllers/FhplApiController.php
@@ -99,7 +99,7 @@ class FhplApiController extends BaseController
if (count($data) && $data['filePath'] == null) {
log_message('error', "FHPL - Claim Push FAILED | claimId: '.$claimId.' - Claim or File Missing");
- return;
+ return ['status' => false, 'message' => 'Claim Push FAILED | Claim or File Missing'];
}
// Build absolute file path
@@ -108,7 +108,7 @@ class FhplApiController extends BaseController
if (!file_exists($pdfPath)) {
log_message('error', "FHPL - Claim Push FAILED | claimId: '.$claimId.' - PDF not found on server");
- return;
+ return ['status' => false, 'message' => 'Claim Push FAILED | PDF not found on server'];
}
// Convert PDF to Base64
@@ -118,7 +118,7 @@ class FhplApiController extends BaseController
$tokenResponse = json_decode($this->generateAuthToken()->getBody(), true);
if (empty($tokenResponse['data']['access_token'])) {
log_message('error', "FHPL - Claim Push FAILED | claimId: '.$claimId.' - FHPL Token generation failed");
- return;
+ return ['status' => false, 'message' => 'Claim Push FAILED | FHPL Token generation failed'];
}
$token = $tokenResponse['data']['access_token'];
@@ -163,7 +163,7 @@ class FhplApiController extends BaseController
$this->db->table('ticket_master')
->where('id',$claimId)
->update([ 'tpa_push_response' => json_encode($response) ]);
- return;
+ return ['status' => false, 'message' => 'Claim Push FAILED | API call failed'];
}
@@ -185,14 +185,14 @@ class FhplApiController extends BaseController
]);
log_message('error', 'FHPL - Claim Push SUCCESS | claimId: '.$claimId.' | claimNO: '.$fhplClaimNo);
-
+ return ['status' => true, 'message' => 'Claim Push SUCCESS', 'response' => $response];
}else {
log_message('error', 'FHPL - Claim Push API SUCCESS BUT claimsInfo EMPTY | response: '.json_encode($response));
- return;
+ return ['status' => false, 'message' => 'Claim Push API SUCCESS BUT claimsInfo EMPTY'];
}
}
- return;
+ return ['status' => false, 'message' => 'Claim Push API SUCCESS BUT claimsInfo EMPTY'];
// return $this->response->setJSON($response);
}
@@ -288,7 +288,10 @@ class FhplApiController extends BaseController
$tickets = $this->db->table('ticket_master tm')
->select("tm.id,tm.tpa_claim_id,cp.policy_no")
->join('client_policy cp','tm.client_policy_id=cp.id')
- ->where('tm.tpa_claim_id IS NOT NULL')
+ ->where('tm.tpa_claim_push_reference_no IS NOT NULL')
+ ->whereNotIn('tm.claim_status_id', [8, 11, 12, 13, 66, 22, 24, 47, 49, 32, 34, 53, 55, 42, 44, 58, 60])
+ ->where('tm.is_active', 1)
+ ->where('cp.tpa_id', $this->fhplTpaId)
->get()->getResultArray();
$count=0;
@@ -714,7 +717,7 @@ class FhplApiController extends BaseController
// ];
// }
- public function syncFhplClaimsToNhance()
+ public function syncFhplClaimsToNhanceOld()
{
helper('api');
@@ -790,6 +793,201 @@ class FhplApiController extends BaseController
return ['status'=>true,'total'=>count($finalResult)];
}
+ public function syncFhplClaimsToNhance()
+ {
+ helper('api');
+
+ try {
+
+ // Generate FHPL Token
+ $tokenResponse = json_decode($this->generateAuthToken()->getBody(), true);
+
+ if (empty($tokenResponse['data']['access_token'])) {
+ return $this->response->setJSON(['status' => false,'message' => 'FHPL Token generation failed']);
+ }
+
+ $token = $tokenResponse['data']['access_token'];
+
+ $url = getenv('FHPL_BASE_URL')."/api/GetTPA_ClaimsDetails";
+
+ $headers = [
+ "Authorization: Bearer ".$token,
+ "Content-Type: application/json"
+ ];
+
+ $policies = $this->db->table('client_policy')
+ ->where('tpa_id',$this->fhplTpaId)
+ ->get()->getResultArray();
+
+ $finalResult=[];
+ foreach($policies as $policy){
+
+ $body = [
+ "UserName" => getenv('FHPL_USER_NAME'),
+ "Password" => getenv('FHPL_PASSWORD'),
+ "PolicyNumber" => $policy['policy_no'],
+ "Fromdate" => $policy['policy_start_date'],
+ "Todate" => $policy['policy_end_date']
+ ];
+
+ $response = call_third_party_api($url,'POST',$headers,$body);
+
+ if(!empty($response['data'])){
+ log_message('error', 'FHPL - Sync TPA Claims | Exception thrown while calling GetTPA_ClaimsDetails API: ' . json_encode($response));
+ $finalResult = array_merge($finalResult,$response['data']);
+ }
+ }
+
+ $insertedCount = 0;
+
+ // Insert into ticket_master with mandatory columns (reference: MediAssist syncTpaClaimToNhance)
+ foreach($finalResult as $row){
+
+ $status = $row['CLAIM_STATUS'] ?? null;
+
+ $map = [
+ "Under Process"=>5,
+ "Paid"=>11,
+ "Rejected"=>8,
+ "Approved"=>8
+ ];
+
+ $claimStatus = $map[$status] ?? 61;
+
+ // Derive relationship (default to self)
+ $relationship = map_relationship(trim($row['RELATION'] ?? 'self'));
+
+ // Fetch client policy details
+ $clientpolicy = $this->db->table('client_policy cp')
+ ->select("
+ cp.id as client_policy_id,
+ cp.client_id ,
+ cp.insurer_id ,
+ cp.tpa_id ,
+ client_rm.id as acm_id
+ ")
+ ->join('client_rm', 'client_rm.client_id = cp.client_id AND client_rm.level = 3', 'left')
+ ->where('cp.policy_no', $row['POLICY_NO'] ?? null)
+ ->orderBy('client_rm.id','DESC')
+ ->get()
+ ->getRowArray();
+
+ if (!$clientpolicy) {
+ log_message(
+ 'error',
+ 'FHPL - Sync TPA Claims | Client policy not found for policy_no: ' . ($row['POLICY_NO'] ?? 'N/A')
+ );
+ continue;
+ }
+
+ // Fetch employee / insured details
+ $employee = $this->db->table('employees e')
+ ->select("
+ e.id as emp_id,
+ e.emp_code ,
+ e.name as emp_name,
+ e2.id as insured_emp_id,
+ e2.name as insured_emp_name,
+ ep.tpa_id as tpa_no
+ ")
+ ->join(
+ 'employees e2',
+ "e2.emp_code = e.emp_code AND e2.relationship = ".$this->db->escape($relationship),
+ 'left'
+ )
+ ->join( 'employee_polices ep', "ep.employee_id = e2.id ", 'left' )
+ ->where('e.emp_code', $row['EMPLOYEE_NO'] ?? null)
+ ->where('e.client_id', $clientpolicy['client_id'] ?? null)
+ ->where('e.relationship', 'self')
+ ->where('e.is_active', 1)
+ ->where('e2.is_active', 1)
+ ->where('ep.is_active', 1)
+ ->get()
+ ->getRowArray();
+
+ if (!$employee) {
+ log_message(
+ 'error',
+ 'FHPL - Sync TPA Claims | Employee data not found for emp_code: ' . ($row['EMPLOYEE_NO'] ?? 'N/A') .
+ ' | policy_no: ' . ($row['POLICY_NO'] ?? 'N/A') .
+ ' | relationship: ' . $relationship
+ );
+ continue;
+ }
+
+ $claimData = [
+ // Core
+ 'ticket_type_id' => 1,
+ 'claim_status_id' => $claimStatus,
+ 'policy_no' => $row['POLICY_NO'] ?? null,
+ 'claim_number' => $row['CLAIM_ID'] ?? null,
+ 'tpa_claim_id' => $row['CLAIM_ID'] ?? null,
+
+ // local primary ids
+ 'tpa_id' => $clientpolicy['tpa_id'] ?? $this->fhplTpaId,
+ 'insurer_id' => $clientpolicy['insurer_id'] ?? null,
+ 'client_policy_id' => $clientpolicy['client_policy_id'] ?? null,
+ 'client_id' => $clientpolicy['client_id'] ?? null,
+ 'acm_id' => $clientpolicy['acm_id'] ?? null,
+
+ // Employee / Insured
+ 'emp_id' => $employee['emp_id'] ?? null,
+ 'insured_emp_id' => $employee['insured_emp_id'] ?? null,
+ 'tpa_no' => $employee['tpa_no'] ?? null,
+ 'emp_code' => $row['EMPLOYEE_NO'] ?? null,
+ 'emp_name' => $employee['emp_name'] ?? null,
+ 'insured_name' => $row['insured_emp_name'] ?? null,
+ 'relationship' => $relationship,
+
+ // Claim info
+ 'claim_type' => 1,
+ 'mode_of_intimation' => 5,
+ 'claim_amount' => $row['CLAIM_AMOUNT'] ?? null,
+
+ // Dates
+ 'doa' => change_date_format($row['DATE_OF_ADMISSION'] ?? '', null, 'Y-m-d') ?? null,
+ 'dod' => change_date_format($row['DATE_OF_DISCHARGE'] ?? '', null, 'Y-m-d') ?? null,
+
+ // Hospital
+ 'hospital_name' => $row['HOSPITAL_NAME'] ?? null,
+ 'hospital_state' => $row['HOSPITAL_STATE'] ?? null,
+ 'hospital_city' => $row['HOSPITAL_CITY'] ?? null,
+ 'hospital_address' => $row['Hospital Address'] ?? null,
+ 'hospital_pincode' => $row['Hospital Pincode'] ?? null,
+
+ 'registration_date' => $row['CLAIM_REGISTERED_DATE'] ?? null,
+
+ // Others
+ 'tpa_claim_type' => $row['CLAIM_TYPE'] ?? null,
+ 'tpa_ailments' => $row['AILMENT'] ?? null,
+
+ 'created_at' => date('Y-m-d H:i:s'),
+ ];
+
+ $this->db->table('ticket_master')->insert($claimData);
+
+ $insertedCount++;
+ }
+
+ log_message('error', 'FHPL - Sync TPA Claims | Fetched Data | Inserted Data: ' . count($finalResult) . ' | Inserted: ' . $insertedCount);
+ return ['status'=>true,'total'=>count($finalResult), 'inserted'=>$insertedCount];
+
+ } catch (\Throwable $th) {
+ $errorData = [
+ 'message' => $th->getMessage(),
+ 'file' => $th->getFile(),
+ 'line' => $th->getLine(),
+ 'code' => $th->getCode(),
+ 'trace' => $th->getTraceAsString(),
+ 'trace_array' => $th->getTrace(), // full array version (optional)
+ 'function' => $th->getTrace()[0]['function'] ?? null,
+ 'class' => $th->getTrace()[0]['class'] ?? null,
+ ];
+ log_message('error', 'FHPL - Sync TPA Claims | Exception thrown: ' . json_encode($errorData));
+ return ['status'=>false,'message'=>$th->getMessage()];
+ }
+ }
+
public function saveFhplAPIData($array)
{
$file_id = $array['file_id'];
diff --git a/app/Controllers/HealthIndiaApiController.php b/app/Controllers/HealthIndiaApiController.php
index 13bc10c3..66e6d543 100644
--- a/app/Controllers/HealthIndiaApiController.php
+++ b/app/Controllers/HealthIndiaApiController.php
@@ -123,12 +123,12 @@ class HealthIndiaApiController extends BaseController
if (!$data) {
log_message('error', "HEALTH_INDIA - Claim Push FAILED | claimId: {$claimId} - Claim not found");
- return;
+ return ['status' => false, 'message' => 'Claim Push FAILED | Claim not found'];
}
if ($data['filePath'] == null) {
log_message('error', "HEALTH_INDIA - Claim Push FAILED | claimId: {$claimId} - File Missing");
- return;
+ return ['status' => false, 'message' => 'Claim Push FAILED | File Missing'];
}
// Build absolute file path
@@ -137,7 +137,7 @@ class HealthIndiaApiController extends BaseController
if (!file_exists($pdfPath)) {
log_message('error', "HEALTH_INDIA - Claim Push FAILED | claimId: {$claimId} - PDF not found on server at path: {$pdfPath}");
- return;
+ return ['status' => false, 'message' => 'Claim Push FAILED | PDF not found on server'];
}
// Convert PDF to Base64
@@ -217,7 +217,7 @@ class HealthIndiaApiController extends BaseController
$this->db->table('ticket_master')
->where('id', $claimId)
->update(['tpa_push_response' => json_encode($response)]);
- return;
+ return ['status' => false, 'message' => 'Claim Push FAILED | API call failed'];
}
if ($response['status'] === true && !empty($response['data']['result'][0]['ccn'])) {
@@ -234,12 +234,13 @@ class HealthIndiaApiController extends BaseController
]);
log_message('error', 'HEALTH_INDIA - Claim Push SUCCESS | claimId: ' . $claimId . ' | CCN: ' . $ccn . ' | CCN_EXT: ' . $ccnExt);
+ return ['status' => true, 'message' => 'Claim Push SUCCESS', 'response' => $response];
} else {
log_message('error', 'HEALTH_INDIA - Claim Push API SUCCESS BUT CCN EMPTY | claimId: ' . $claimId . ' | response: ' . json_encode($response));
- return;
+ return ['status' => false, 'message' => 'Claim Push API SUCCESS BUT CCN EMPTY'];
}
- return;
+ return ['status' => false, 'message' => 'Claim Push API SUCCESS BUT CCN EMPTY'];
}
public function ClaimDetail($claimId = null)
@@ -355,7 +356,9 @@ class HealthIndiaApiController extends BaseController
$tickets = $this->db->table('ticket_master tm')
->select("tm.id, tm.tpa_claim_id, cp.policy_no")
->join('client_policy cp', 'tm.client_policy_id=cp.id')
- ->where('tm.tpa_claim_id IS NOT NULL')
+ ->where('tm.tpa_claim_push_reference_no IS NOT NULL')
+ ->whereNotIn('tm.claim_status_id', [8, 11, 12, 13, 66, 22, 24, 47, 49, 32, 34, 53, 55, 42, 44, 58, 60])
+ ->where('tm.is_active', 1)
->where('cp.tpa_id', $this->healthIndiaTpaId)
->get()->getResultArray();
@@ -722,7 +725,7 @@ class HealthIndiaApiController extends BaseController
}
}
- public function syncHealthIndiaClaimsToNhance()
+ public function syncHealthIndiaClaimsToNhanceOld()
{
helper('api');
@@ -820,6 +823,217 @@ class HealthIndiaApiController extends BaseController
]);
}
+ public function syncHealthIndiaClaimsToNhance()
+ {
+ helper('api');
+
+ log_message('error', 'HEALTH_INDIA - Sync TPA Claims | Started');
+
+ // Generate Health India Token
+ $tokenResponse = json_decode($this->generateAuthToken()->getBody(), true);
+
+ if (empty($tokenResponse['data']['result'][0]['access_token'])) {
+ log_message('error', 'HEALTH_INDIA - Sync TPA Claims FAILED | Token generation failed');
+ return $this->response->setJSON(['status' => false, 'message' => 'Token generation failed']);
+ }
+
+ $token = $tokenResponse['data']['result'][0]['access_token'];
+
+ $url = getenv('HEALTH_INDIA_BASE_URL') . "/ClaimsMIS/GetClaimsMIS";
+
+ $headers = [
+ "Authorization: Bearer " . $token,
+ "Content-Type: application/json"
+ ];
+
+ $policies = $this->db->table('client_policy')
+ ->where('tpa_id', $this->healthIndiaTpaId)
+ ->get()->getResultArray();
+
+ $finalResult = [];
+
+ foreach ($policies as $policy) {
+ $body = [
+ "policY_NUMBER" => $policy['policy_no']
+ ];
+
+ log_message('error', 'HEALTH_INDIA - Sync TPA Claims | Fetching for policy: ' . $policy['policy_no']);
+
+ $response = call_third_party_api($url, 'POST', $headers, $body);
+
+ if (!empty($response['data']['result'])) {
+ $finalResult = array_merge($finalResult, $response['data']['result']);
+ log_message('error', 'HEALTH_INDIA - Sync TPA Claims | Fetched ' . count($response['data']['result']) . ' claims for policy: ' . $policy['policy_no']);
+ }
+ }
+
+ log_message('error', 'HEALTH_INDIA - Sync TPA Claims | Total claims fetched: ' . count($finalResult));
+
+ $insertedCount = 0;
+
+ foreach ($finalResult as $row) {
+ $status = $row['Claim_Status'] ?? 'Under Process';
+
+ $map = [
+ "Under Process" => 5,
+ "Pending for Bill Entry" => 5,
+ "Paid" => 11,
+ "Rejected" => 8,
+ "Approved" => 8,
+ "Outstanding" => 5,
+ ];
+
+ $claimStatus = $map[$status] ?? 1;
+
+ // Check if claim already exists
+ $existing = $this->db->table('ticket_master')
+ ->where('tpa_claim_id', $row['CLAIM_NUMBER'])
+ ->get()->getRowArray();
+
+ if ($existing) {
+ log_message('error', 'HEALTH_INDIA - Sync TPA Claims | Skipped existing claim: ' . ($row['CLAIM_NUMBER'] ?? 'N/A'));
+ continue;
+ }
+
+ // Derive relationship (default to self)
+ $relationship = 'self';
+ $rawRelation = $row['RELATION_NAME'] ?? null;
+ if (!empty($rawRelation)) {
+ if ($rawRelation === 'Employee') {
+ $relationship = 'self';
+ } elseif (strtoupper($rawRelation) === 'WIFE') {
+ $relationship = 'spouse';
+ } else {
+ $relationship = strtolower($rawRelation);
+ }
+ }
+
+ // Fetch client policy details
+ $clientpolicy = $this->db->table('client_policy cp')
+ ->select("
+ cp.id as client_policy_id,
+ cp.client_id,
+ cp.insurer_id,
+ cp.tpa_id,
+ client_rm.id as acm_id
+ ")
+ ->join('client_rm', 'client_rm.client_id = cp.client_id AND client_rm.level = 3', 'left')
+ ->where('cp.policy_no', $row['Policy_No'] ?? null)
+ ->orderBy('client_rm.id', 'DESC')
+ ->get()
+ ->getRowArray();
+
+ if (!$clientpolicy) {
+ log_message(
+ 'error',
+ 'HEALTH_INDIA - Sync TPA Claims | Client policy not found for policy_no: ' . ($row['Policy_No'] ?? 'N/A')
+ );
+ continue;
+ }
+
+ // Fetch employee / insured details
+ $employee = $this->db->table('employees e')
+ ->select("
+ e.id as emp_id,
+ e.emp_code,
+ e.name as emp_name,
+ e2.id as insured_emp_id,
+ e2.name as insured_emp_name,
+ ep.tpa_id as tpa_no,
+ e.mobile as emp_mobile,
+ e.email_corporate as emp_mail
+ ")
+ ->join(
+ 'employees e2',
+ "e2.emp_code = e.emp_code AND e2.relationship = " . $this->db->escape($relationship),
+ 'left'
+ )
+ ->join('employee_polices ep', "ep.employee_id = e2.id ", 'left')
+ ->where('e.emp_code', $row['Employee_Code'] ?? null)
+ ->where('e.client_id', $clientpolicy['client_id'] ?? null)
+ ->where('e.relationship', 'self')
+ ->where('e.is_active', 1)
+ ->where('e2.is_active', 1)
+ ->where('ep.is_active', 1)
+ ->get()
+ ->getRowArray();
+
+ if (!$employee) {
+ log_message(
+ 'error',
+ 'HEALTH_INDIA - Sync TPA Claims | Employee data not found for emp_code: ' . ($row['Employee_Code'] ?? 'N/A') .
+ ' | policy_no: ' . ($row['Policy_No'] ?? 'N/A') .
+ ' | relationship: ' . $relationship
+ );
+ continue;
+ }
+
+ $claimData = [
+ // Core
+ 'ticket_type_id' => 1,
+ 'claim_status_id' => $claimStatus,
+ 'policy_no' => $row['Policy_No'] ?? null,
+ 'claim_number' => $row['CLAIM_NUMBER'] ?? null,
+ 'tpa_claim_id' => $row['CLAIM_NUMBER'] ?? null,
+
+ // Local primary/foreign keys
+ 'tpa_id' => $clientpolicy['tpa_id'] ?? $this->healthIndiaTpaId,
+ 'insurer_id' => $clientpolicy['insurer_id'] ?? null,
+ 'client_policy_id' => $clientpolicy['client_policy_id'] ?? null,
+ 'client_id' => $clientpolicy['client_id'] ?? null,
+ 'acm_id' => $clientpolicy['acm_id'] ?? null,
+
+ // Employee / Insured
+ 'emp_id' => $employee['emp_id'] ?? null,
+ 'insured_emp_id' => $employee['insured_emp_id'] ?? null,
+ 'tpa_no' => $employee['tpa_no'] ?? null,
+ 'emp_code' => $row['Employee_Code'] ?? null,
+ 'emp_name' => $employee['emp_name'] ?? null,
+ 'insured_name' => $employee['insured_emp_name'] ?? ($row['PATIENT_NAME'] ?? null),
+ 'relationship' => $relationship,
+ 'emp_mobile' => $employee['emp_mobile'] ?? null,
+ 'emp_mail' => $employee['emp_mail'] ?? null,
+
+ // Claim info
+ 'claim_type' => 1,
+ 'mode_of_intimation' => 5,
+ 'claim_amount' => $row['INTIMATED_AMOUNT'] ?? 0,
+
+ // Dates
+ 'doa' => !empty($row['DATEOF_ADMISSION']) ? date('Y-m-d', strtotime($row['DATEOF_ADMISSION'])) : null,
+ 'dod' => !empty($row['DATEOF_DISCHARGE']) ? date('Y-m-d', strtotime($row['DATEOF_DISCHARGE'])) : null,
+
+ // Hospital
+ 'hospital_name' => $row['HOSPITAL_NAME'] ?? null,
+ 'hospital_address' => $row['Hospital_address'] ?? null,
+ 'hospital_pincode' => $row['HOSPITAL_Pincode'] ?? null,
+ 'hospital_state' => $row['HOSPITAL_STATE'] ?? null,
+ 'hospital_city' => $row['HOSPITAL_CITY'] ?? null,
+
+ // TPA extras
+ 'tpa_claim_status' => $status,
+
+ 'created_at' => date('Y-m-d H:i:s'),
+ ];
+
+ $this->db->table('ticket_master')->insert($claimData);
+ $insertedCount++;
+
+ log_message(
+ 'error',
+ 'HEALTH_INDIA - Sync TPA Claims | Inserted claim: ' . ($row['CLAIM_NUMBER'] ?? 'N/A')
+ );
+ }
+
+ log_message('error', 'HEALTH_INDIA - Sync TPA Claims | Completed | Total: ' . count($finalResult) . ' | Inserted: ' . $insertedCount);
+
+ return $this->response->setJSON([
+ 'status' => true,
+ 'total' => count($finalResult),
+ 'inserted' => $insertedCount
+ ]);
+ }
+
public function saveHealthIndiaAPIData($array)
{
$file_id = $array['file_id'];
diff --git a/app/Controllers/LeadsController.php b/app/Controllers/LeadsController.php
index dfd99a43..41739b6a 100644
--- a/app/Controllers/LeadsController.php
+++ b/app/Controllers/LeadsController.php
@@ -1,7 +1,9 @@
myLogger = \Config\Services::mylogger();
- $this->clientModel = new ClientModel();
- $this->userModel = new UserModel();
- $this->clientBranchModel = new ClientBranchModel();
- $this->clientPolicyModel = new ClientPolicyModel();
- $this->levelContactModel = new LevelContactModel();
- $this->leadsModel = new LeadsModel();
- $this->policyTypeModel = new PolicyTypeModel();
- $this->kycEntityTypeModel = new KYCEntityTypeModel();
- $this->policyTransactionStatusModel = new PolicyTransactionStatusModel();
- $this->insurerBranchModel = new InsurerBranchModel();
- $this->tpaBranchModel = new TPABranchModel();
- $this->RFQModel = new RFQModel();
- $this->insurerModel = new InsurerModel();
- $this->occupancyModel = new OccupancyMasterModel();
- $this->leadFilesModel = new LeadFilesModel();
+ $this->clientModel = new ClientModel();
+ $this->userModel = new UserModel();
+ $this->clientBranchModel = new ClientBranchModel();
+ $this->clientPolicyModel = new ClientPolicyModel();
+ $this->levelContactModel = new LevelContactModel();
+ $this->leadsModel = new LeadsModel();
+ $this->policyTypeModel = new PolicyTypeModel();
+ $this->kycEntityTypeModel = new KYCEntityTypeModel();
+ $this->policyTransactionStatusModel = new PolicyTransactionStatusModel();
+ $this->insurerBranchModel = new InsurerBranchModel();
+ $this->tpaBranchModel = new TPABranchModel();
+ $this->RFQModel = new RFQModel();
+ $this->insurerModel = new InsurerModel();
+ $this->occupancyModel = new OccupancyMasterModel();
+ $this->leadFilesModel = new LeadFilesModel();
$this->leadInstallmentPaymentDetails = new LeadInstallmentPaymentDetails();
$this->gmailSentHistoryModel = new GmailSentHistoryModel();
+ $this->leadModel = new SalesActualLeadModel();
+ $this->contactModel = new SalesContactPersonModel();
- $this->issuer = [1 => 'JIBS', 2 => 'Nhance'];
- $this->clientType = [1 => 'Group', 2 => 'Individual'];
- $this->leadType = [1 => 'Fresh', 2 => 'Renewal', 3 => 'Roll Over'];
- $data = $this->kycEntityTypeModel->where('is_active', 1)->findAll();
+
+ $this->issuer = [1 => 'JIBS', 2 => 'Nhance'];
+ $this->clientType = [1 => 'Group', 2 => 'Individual'];
+ $this->leadType = [1 => 'Fresh', 2 => 'Renewal', 3 => 'Roll Over'];
+ $data = $this->kycEntityTypeModel->where('is_active', 1)->findAll();
$this->buisnessType = array_column($data, 'name', 'id');
// $this->buisnessType = [1 => 'Public Sector', 2 => 'Private Sector',3=> 'Trust',4 => 'Proprietorship',5 => 'Partnership',6 => 'Private',7 => 'Individual'];
$this->leadsStatus = [
- 'queued' => 'In-Queued',
- 'rfq_created' => 'RFQ Created',
- 'rfq_sent' => 'RFQ Sent',
- 'qcr_created' => 'QCR Created',
- 'qcr_sent' => 'QCR Sent',
- 'lost' => 'Lost',
- 'co_insurer_pending' => 'Co-Insurer Pending',
- 'won' => 'Won',
- 'completed_with_corrections' => 'Completed with Corrections',
+ 'queued' => 'In-Queued',
+ 'rfq_created' => 'RFQ Created',
+ 'rfq_sent' => 'RFQ Sent',
+ 'qcr_created' => 'QCR Created',
+ 'qcr_sent' => 'QCR Sent',
+ 'lost' => 'Lost',
+ 'co_insurer_pending' => 'Co-Insurer Pending',
+ 'won' => 'Won',
+ 'completed_with_corrections' => 'Completed with Corrections',
'completed_without_corrections' => 'Completed without Corrections',
];
$this->claim_type_for_gpa = [
- 'nil' => 'Nil',
- 'accident_death' => 'Accident Death',
- 'permanent_total_disablement' => 'Permanent Total Disablement',
- 'permanent_partial_disablement' => 'Permanent Partial Disablement',
- 'temporary_total_disablement_benefit' => 'Temporary Total Disablement benefit'
+ 'nil' => 'Nil',
+ 'accident_death' => 'Accident Death',
+ 'permanent_total_disablement' => 'Permanent Total Disablement',
+ 'permanent_partial_disablement' => 'Permanent Partial Disablement',
+ 'temporary_total_disablement_benefit' => 'Temporary Total Disablement benefit',
];
$this->cause_of_death = [
- 'natural_death' => 'Natural Death',
- 'suicide' => 'Suicide',
- 'accident' => 'Accident',
+ 'natural_death' => 'Natural Death',
+ 'suicide' => 'Suicide',
+ 'accident' => 'Accident',
'cardiac_arrest' => 'Cardiac Arrest',
- 'septic_shock' => 'Septic shock',
- 'heart_attack' => 'Heart Attack',
+ 'septic_shock' => 'Septic shock',
+ 'heart_attack' => 'Heart Attack',
];
$this->member_data_excel_columns = [
- 'sno' => [
- 'col_idx' => 0,
- 'col_cell_name' => 'A',
- 'col_name' => 'Sl no',
- 'is_mandatory' => false,
- 'data_type' => 'str',
- 'format' => null,
- 'allowed_values' => null
+ 'sno' => [
+ 'col_idx' => 0,
+ 'col_cell_name' => 'A',
+ 'col_name' => 'Sl no',
+ 'is_mandatory' => false,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null,
],
- 'emp_code' => [
- 'col_idx' => 1,
- 'col_cell_name' => 'B',
- 'col_name' => 'Emp Code',
- 'is_mandatory' => true,
- 'data_type' => 'str',
- 'format' => null,
- 'allowed_values' => null
+ 'emp_code' => [
+ 'col_idx' => 1,
+ 'col_cell_name' => 'B',
+ 'col_name' => 'Emp Code',
+ 'is_mandatory' => true,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null,
],
- 'name' => [
- 'col_idx' => 2,
- 'col_cell_name' => 'C',
- 'col_name' => 'Name',
- 'is_mandatory' => true,
- 'data_type' => 'str',
- 'format' => null,
- 'allowed_values' => null
+ 'name' => [
+ 'col_idx' => 2,
+ 'col_cell_name' => 'C',
+ 'col_name' => 'Name',
+ 'is_mandatory' => true,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null,
],
'relationship' => [
- 'col_idx' => 3,
- 'col_cell_name' => 'D',
- 'col_name' => 'Relationship',
- 'is_mandatory' => true,
- 'data_type' => 'str',
- 'format' => null,
+ 'col_idx' => 3,
+ 'col_cell_name' => 'D',
+ 'col_name' => 'Relationship',
+ 'is_mandatory' => true,
+ 'data_type' => 'str',
+ 'format' => null,
'allowed_values' => [
'Self', 'Spouse', 'Son', 'Daughter', 'Father', 'Mother',
'Father-in-law', 'Mother-in-law',
'self', 'spouse', 'son', 'daughter', 'father', 'mother',
- 'father-in-law', 'mother-in-law'
+ 'father-in-law', 'mother-in-law',
],
- 'custom' => 'check_relationship_for_member_data',
- 'params' => ['row', 'relationship', 'columns_to_check']
+ 'custom' => 'check_relationship_for_member_data',
+ 'params' => ['row', 'relationship', 'columns_to_check'],
],
- 'gender' => [
- 'col_idx' => 4,
- 'col_cell_name' => 'E',
- 'col_name' => 'Gender',
- 'is_mandatory' => true,
- 'data_type' => 'str',
- 'format' => null,
- 'allowed_values' => ['M', 'F']
+ 'gender' => [
+ 'col_idx' => 4,
+ 'col_cell_name' => 'E',
+ 'col_name' => 'Gender',
+ 'is_mandatory' => true,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => ['M', 'F'],
],
- 'dob' => [
- 'col_idx' => 5,
- 'col_cell_name' => 'F',
- 'col_name' => 'DOB',
- 'is_mandatory' => true,
- 'data_type' => 'str',
- 'format' => 'd-M-Y',
+ 'dob' => [
+ 'col_idx' => 5,
+ 'col_cell_name' => 'F',
+ 'col_name' => 'DOB',
+ 'is_mandatory' => true,
+ 'data_type' => 'str',
+ 'format' => 'd-M-Y',
'allowed_values' => null,
'age_validation' => true,
// 'custom' => 'check_dob_diff',
// 'params' => ['row', 'relationship', 'default_age_ratio', 'policy_details']
],
- 'age' => [
- 'col_idx' => 6,
- 'col_cell_name' => 'G',
- 'col_name' => 'Age',
- 'is_mandatory' => true,
- 'data_type' => 'int',
- 'format' => null,
- 'allowed_values' => null
- ],
- 'email' => [
- 'col_idx' => 7,
- 'col_cell_name' => 'H',
- 'col_name' => 'Email',
- 'is_mandatory' => false,
- 'data_type' => 'str',
- 'format' => null,
- 'allowed_values' => null
- ],
- 'mobile' => [
- 'col_idx' => 8,
- 'col_cell_name' => 'I',
- 'col_name' => 'Mobile',
- 'is_mandatory' => false,
- 'data_type' => 'str',
- 'format' => null,
- 'allowed_values' => null
- ],
- 'si' => [
- 'col_idx' => 9,
- 'col_cell_name' => 'J',
- 'col_name' => 'SI',
- 'is_mandatory' => false,
- 'data_type' => 'int',
- 'format' => null,
+ 'age' => [
+ 'col_idx' => 6,
+ 'col_cell_name' => 'G',
+ 'col_name' => 'Age',
+ 'is_mandatory' => true,
+ 'data_type' => 'int',
+ 'format' => null,
'allowed_values' => null,
- ]
+ ],
+ 'email' => [
+ 'col_idx' => 7,
+ 'col_cell_name' => 'H',
+ 'col_name' => 'Email',
+ 'is_mandatory' => false,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null,
+ ],
+ 'mobile' => [
+ 'col_idx' => 8,
+ 'col_cell_name' => 'I',
+ 'col_name' => 'Mobile',
+ 'is_mandatory' => false,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null,
+ ],
+ 'si' => [
+ 'col_idx' => 9,
+ 'col_cell_name' => 'J',
+ 'col_name' => 'SI',
+ 'is_mandatory' => false,
+ 'data_type' => 'int',
+ 'format' => null,
+ 'allowed_values' => null,
+ ],
];
$this->general_relationships = [
- 'self' => [
- 'name' => 'Self',
- 'gender' => 'M',
+ 'self' => [
+ 'name' => 'Self',
+ 'gender' => 'M',
'age_min' => 18,
- 'age_max' => null
+ 'age_max' => null,
],
- 'spouse' => [
- 'name' => 'Spouse',
- 'gender' => 'F',
+ 'spouse' => [
+ 'name' => 'Spouse',
+ 'gender' => 'F',
'age_min' => 18,
- 'age_max' => null
+ 'age_max' => null,
],
- 'son' => [
- 'name' => 'Son',
- 'gender' => 'M',
+ 'son' => [
+ 'name' => 'Son',
+ 'gender' => 'M',
'age_min' => null,
- 'age_max' => 25
+ 'age_max' => 25,
],
- 'daughter' => [
- 'name' => 'Daughter',
- 'gender' => 'F',
+ 'daughter' => [
+ 'name' => 'Daughter',
+ 'gender' => 'F',
'age_min' => null,
- 'age_max' => 25
+ 'age_max' => 25,
],
- 'father' => [
- 'name' => 'Father',
- 'gender' => 'M',
+ 'father' => [
+ 'name' => 'Father',
+ 'gender' => 'M',
'age_min' => 18,
- 'age_max' => null
+ 'age_max' => null,
],
- 'mother' => [
- 'name' => 'Mother',
- 'gender' => 'F',
+ 'mother' => [
+ 'name' => 'Mother',
+ 'gender' => 'F',
'age_min' => 18,
- 'age_max' => null
+ 'age_max' => null,
],
'father-in-law' => [
- 'name' => 'Father in Law',
- 'gender' => 'M',
+ 'name' => 'Father in Law',
+ 'gender' => 'M',
'age_min' => 18,
- 'age_max' => null
+ 'age_max' => null,
],
'mother-in-law' => [
- 'name' => 'Mother in Law',
- 'gender' => 'F',
+ 'name' => 'Mother in Law',
+ 'gender' => 'F',
'age_min' => 18,
- 'age_max' => null
- ]
+ 'age_max' => null,
+ ],
];
-
+
}
public function viewLeadsList()
{
- $data['tab_name'] = 'Opportunities';
+ $data['tab_name'] = 'Opportunities';
$data['page_name'] = 'Opportunities';
// Set basic data
- $data['issuer'] = $this->issuer;
+ $data['issuer'] = $this->issuer;
$data['client_type'] = $this->clientType;
- $data['lead_type'] = $this->leadType;
+ $data['lead_type'] = $this->leadType;
$data['lead_status'] = $this->leadsStatus;
// Fetch policy types and entity data
$data['policy_type'] = $this->policyTypeModel->where('is_active', 1)->findAll();
- $data['entity'] = $this->kycEntityTypeModel->where('is_active', 1)->findAll();
+ $data['entity'] = $this->kycEntityTypeModel->where('is_active', 1)->findAll();
- // dd($lastFiveYears);
+ // Data needed for mail modals on Opportunities list (reuse RFQ behaviour)
+ $data['userList'] = $this->userModel->getUserListForRFQ();
+ $data['exclusiveUserList'] = $this->userModel->getexclusiveUserListForRFQ();
+ // Attachments for mails are lead-specific and will be handled at RFQ level;
+ // keep placeholder here so modal templates render without notices.
+ $data['attachment_html'] = '';
+
+ // dd($lastFiveYears);
if ($this->request->is('get')) {
// Fetch leads data
$data['lead_data_list'] = $this->leadsModel->getLeadDataForLising();
@@ -325,13 +360,13 @@ class LeadsController extends BaseController
$isFromDashboard = $this->request->getPost("is_dashboard");
- if (isset($isFromDashboard) && !empty($isFromDashboard) && $isFromDashboard == 1) {
+ if (isset($isFromDashboard) && ! empty($isFromDashboard) && $isFromDashboard == 1) {
$ids = $this->request->getPost('ids');
$ids = array_filter(explode(',', $ids));
- if (!empty($ids)) {
+ if (! empty($ids)) {
$idsStr = implode(',', array_map('intval', $ids)); // sanitize IDs to be integers
- $where = "leads.id IN ($idsStr)";
+ $where = "leads.id IN ($idsStr)";
} else {
$where = '1 = 0'; // No valid IDs, return empty result
}
@@ -344,11 +379,10 @@ class LeadsController extends BaseController
$where = [];
foreach ($search_data as $search_objects => $key) {
if ($key != null && $key != '' && $key != 0 && $search_objects != 'is_dashboard') {
- if($search_objects == 'status')
- {
- $where[('leads.'.$search_objects)] = $key;
- }else{
- $where[$search_objects] = $key;
+ if ($search_objects == 'status') {
+ $where[('leads.' . $search_objects)] = $key;
+ } else {
+ $where[$search_objects] = $key;
}
}
}
@@ -363,98 +397,98 @@ class LeadsController extends BaseController
public function createLead()
{
- $id = $this->request->getPost('id');
+ $id = $this->request->getPost('id');
$actual_lead_id = $this->request->getPost('actual_lead_id');
- $actual_lead_id = !empty($actual_lead_id) ? $actual_lead_id : null;
- $postData = $this->request->getPost();
- $data = $this->prepareLeadData();
- $rules = [
+ $actual_lead_id = ! empty($actual_lead_id) ? $actual_lead_id : null;
+ $postData = $this->request->getPost();
+ $data = $this->prepareLeadData();
+ $rules = [
- 'lead_type' => [
+ 'lead_type' => [
'rules' => 'integer',
- 'errors' => ['required' => 'Opportunity Type is required']
+ 'errors' => ['required' => 'Opportunity Type is required'],
],
- 'issuer' => [
+ 'issuer' => [
'rules' => 'required',
- 'errors' => ['required' => 'Issuer is required']
+ 'errors' => ['required' => 'Issuer is required'],
],
- 'entity_type_id' => [
+ 'entity_type_id' => [
'rules' => 'required',
- 'errors' => ['required' => 'Entity Type is required']
+ 'errors' => ['required' => 'Entity Type is required'],
],
- 'client_name' => [
+ 'client_name' => [
'rules' => 'required|regex_match[/^[a-zA-Z0-9_ -]+$/]',
'errors' => [
'required' => 'Client Name is required',
- 'regex_match' => 'Client Name only letters, numbers, space, hyphens and underscores are allowed'
- ]
+ 'regex_match' => 'Client Name only letters, numbers, space, hyphens and underscores are allowed',
+ ],
],
- 'client_short_name' => [
+ 'client_short_name' => [
'rules' => 'required|regex_match[/^[a-zA-Z0-9_-]+$/]',
- 'errors' => ['required' => 'Client Short Name is required','regex_match' => 'Client Short Name only letters, numbers, hyphens and underscores are allowed']
+ 'errors' => ['required' => 'Client Short Name is required', 'regex_match' => 'Client Short Name only letters, numbers, hyphens and underscores are allowed'],
],
- 'gst' => [
+ 'gst' => [
'rules' => 'required|regex_match[/^[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z]{1}[1-9A-Z]{1}Z[0-9A-Z]{1}$/]',
'errors' => [
'required' => 'GST Number is required.',
- 'regex_match' => 'Invalid GST format. Example: 22AAAAA0000A1Z5'
- ]
+ 'regex_match' => 'Invalid GST format. Example: 22AAAAA0000A1Z5',
+ ],
],
- 'branch_name' => [
+ 'branch_name' => [
'rules' => 'required|regex_match[/^[a-zA-Z0-9\s_-]+$/]|min_length[3]',
'errors' => [
'required' => 'Branch Name is required.',
'regex_match' => 'Branch Name can only contain letters, numbers, spaces, hyphens and underscores..',
- 'min_length' => 'Branch Name must be at least 3 characters long.'
- ]
+ 'min_length' => 'Branch Name must be at least 3 characters long.',
+ ],
],
- 'branch_code' => [
+ 'branch_code' => [
'rules' => 'required|regex_match[/^[a-zA-Z0-9_-]+$/]',
'errors' => [
'required' => 'Branch Code is required.',
- 'regex_match' => 'Branch Code can only contain letters, numbers, hyphens and underscores..'
- ]
+ 'regex_match' => 'Branch Code can only contain letters, numbers, hyphens and underscores..',
+ ],
],
- 'contact_person_name' => [
+ 'contact_person_name' => [
'rules' => 'required|regex_match[/^[a-zA-Z0-9_ -]+$/]',
'errors' => [
'required' => 'Contact Person Name is required',
- 'regex_match' => 'Contact person name only letters, numbers and spaces, hyphens and underscores..'
- ]
+ 'regex_match' => 'Contact person name only letters, numbers and spaces, hyphens and underscores..',
+ ],
],
'contact_person_mobile' => [
'rules' => 'required',
'rules' => 'required|exact_length[10]|regex_match[/^[0-9]+$/]',
'errors' => [
- 'required' => 'Contact Person Mobile is required' ,
- 'regex_match' => 'Contact Person Mobile Only numbers',
- 'exact_length'=> 'Contact Person Mobile must be exactly 10 digits long.'
- ]
+ 'required' => 'Contact Person Mobile is required',
+ 'regex_match' => 'Contact Person Mobile Only numbers',
+ 'exact_length' => 'Contact Person Mobile must be exactly 10 digits long.',
+ ],
],
- 'contact_person_email' => [
+ 'contact_person_email' => [
'rules' => 'required|regex_match[/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/]',
'errors' => [
'required' => 'Contact Person Email address is required.',
- 'regex_match' => 'Please enter a valid email format (e.g., name@domain.com).'
- ]
+ 'regex_match' => 'Please enter a valid email format (e.g., name@domain.com).',
+ ],
// 'rules' => 'required|valid_email|regex_match[/^[a-zA-Z0-9_-]+$/]',
- // 'regex_match' => 'Contact Person Email Only letters, numbers and characters _ - @ . are allowed'
-
+ // 'regex_match' => 'Contact Person Email Only letters, numbers and characters _ - @ . are allowed'
+
],
- 'salse_person_id' => [
+ 'salse_person_id' => [
'rules' => 'required',
- 'errors' => ['required' => 'Sales Person is required']
+ 'errors' => ['required' => 'Sales Person is required'],
],
- 'status' => [
+ 'status' => [
'rules' => 'required',
- 'errors' => ['required' => 'Status is required']
+ 'errors' => ['required' => 'Status is required'],
],
- 'next_reminder_date' => [
+ 'next_reminder_date' => [
'label' => 'Next Reminder Date',
'rules' => 'permit_empty|valid_date[d/m/Y]',
'errors' => [
- 'valid_date' => 'The {field} must be in the format DD/MM/YYYY.'
- ]
+ 'valid_date' => 'The {field} must be in the format DD/MM/YYYY.',
+ ],
],
];
@@ -465,75 +499,75 @@ class LeadsController extends BaseController
'label' => 'Document Name',
'rules' => 'permit_empty|regex_match[/^[a-zA-Z0-9_\- ]+$/]',
'errors' => [
- 'regex_match' => 'Document Name in {field} can only contain letters, numbers, hyphens, and underscores.'
- ]
+ 'regex_match' => 'Document Name in {field} can only contain letters, numbers, hyphens, and underscores.',
+ ],
];
}
}
// print_r($rules); die;
- if ((int)$this->request->getPost('lead_form_type') === 2) {
+ if ((int) $this->request->getPost('lead_form_type') === 2) {
$rules['client_type'] = [
'rules' => 'required',
- 'errors' => ['required' => 'Client Type is required']
+ 'errors' => ['required' => 'Client Type is required'],
];
$rules['policy_type_id'] = [
'rules' => 'required',
- 'errors' => ['required' => 'Policy Type is required']
+ 'errors' => ['required' => 'Policy Type is required'],
];
$rules['policy_start_date'] = [
'rules' => 'required',
- 'errors' => ['required' => 'Date of Commencement is required']
+ 'errors' => ['required' => 'Date of Commencement is required'],
];
$rules['policy_end_date'] = [
'rules' => 'required',
- 'errors' => ['required' => 'Date of Expiry is required']
+ 'errors' => ['required' => 'Date of Expiry is required'],
];
- if ((int)$this->request->getPost('claim_history') === 1) {
- $rules['first_year.*'] = [
- 'rules' => 'required|regex_match[/^\d{4}-\d{4}$/]',
- 'errors' => ['required' => 'Claim Year is required for all entries.','regex_match' => 'Year must be in format YYYY-YYYY.']
- ];
- $rules['first_policy_type_.*'] = [
- 'rules' => 'required|regex_match[/^[a-zA-Z0-9_-]+$/]',
- 'errors' => ['required' => 'Policy Type is required in Claim History.',
- 'regex_match' => 'Policy Type only letters, numbers, space, hyphens and underscores are allowed'
- ]
- ];
- $rules['first_date_of_loss_.*'] = [
- 'rules' => 'required|regex_match[/^[0-9]{2}-[0-9]{2}-[0-9]{4}$/]',
- 'errors' => ['required' => 'Date of Loss is required.',
- 'regex_match' => 'Date of Loss must be inValid format.']
- ];
- $rules['first_cause_of_loss.*'] = [
- 'rules' => 'required|regex_match[/^[a-zA-Z0-9\s_-]+$/]',
- 'errors' => [
- 'required' => 'Cause of Loss is required.',
- 'regex_match' => 'Cause of Loss only letters, numbers, space, hyphens and underscores are allowed'
- ]
- ];
- $rules['first_claim_amount.*'] = [
- 'rules' => 'required|numeric',
- 'errors' => [
- 'required' => 'Claim Amount is required.',
- 'numeric' => 'Claim Amount must be a number.'
- ]
- ];
- $rules['first_settled_amount.*'] = [
- 'rules' => 'required|numeric',
- 'errors' => ['required' => 'Settled Amount is required.',
- 'numeric' => 'Settled Amount must be a number.']
- ];
- $rules['first_claim_status.*'] = [
- 'rules' => 'required|alpha_space',
- 'errors' => [
- 'required' => 'Claim Status is required.',
- 'alpha_space' => 'Claim Status should only contain letters and spaces.'
- ]
- ];
- }
+ if ((int) $this->request->getPost('claim_history') === 1) {
+ $rules['first_year.*'] = [
+ 'rules' => 'required|regex_match[/^\d{4}-\d{4}$/]',
+ 'errors' => ['required' => 'Claim Year is required for all entries.', 'regex_match' => 'Year must be in format YYYY-YYYY.'],
+ ];
+ $rules['first_policy_type_.*'] = [
+ 'rules' => 'required|regex_match[/^[a-zA-Z0-9_-]+$/]',
+ 'errors' => ['required' => 'Policy Type is required in Claim History.',
+ 'regex_match' => 'Policy Type only letters, numbers, space, hyphens and underscores are allowed',
+ ],
+ ];
+ $rules['first_date_of_loss_.*'] = [
+ 'rules' => 'required|regex_match[/^[0-9]{2}-[0-9]{2}-[0-9]{4}$/]',
+ 'errors' => ['required' => 'Date of Loss is required.',
+ 'regex_match' => 'Date of Loss must be inValid format.'],
+ ];
+ $rules['first_cause_of_loss.*'] = [
+ 'rules' => 'required|regex_match[/^[a-zA-Z0-9\s_-]+$/]',
+ 'errors' => [
+ 'required' => 'Cause of Loss is required.',
+ 'regex_match' => 'Cause of Loss only letters, numbers, space, hyphens and underscores are allowed',
+ ],
+ ];
+ $rules['first_claim_amount.*'] = [
+ 'rules' => 'required|numeric',
+ 'errors' => [
+ 'required' => 'Claim Amount is required.',
+ 'numeric' => 'Claim Amount must be a number.',
+ ],
+ ];
+ $rules['first_settled_amount.*'] = [
+ 'rules' => 'required|numeric',
+ 'errors' => ['required' => 'Settled Amount is required.',
+ 'numeric' => 'Settled Amount must be a number.'],
+ ];
+ $rules['first_claim_status.*'] = [
+ 'rules' => 'required|alpha_space',
+ 'errors' => [
+ 'required' => 'Claim Status is required.',
+ 'alpha_space' => 'Claim Status should only contain letters and spaces.',
+ ],
+ ];
+ }
}
@@ -542,11 +576,11 @@ class LeadsController extends BaseController
// foreach ($allFiles as $inputName => $files) {
// // If it's a single file, wrap it in an array to use the same logic
// $fileArray = is_array($files) ? $files : [$files];
-
+
// foreach ($fileArray as $index => $file) {
// if ($file->isValid() && !$file->hasMoved()) {
// $extension = strtolower($file->getExtension());
-
+
// // Logic: index 0 is Excel only, others are mixed
// if ($index === 0) {
// $allowed = ['xls', 'xlsx'];
@@ -568,7 +602,6 @@ class LeadsController extends BaseController
// }
// }
// }
-
$isValid = $this->validate($rules);
@@ -576,47 +609,44 @@ class LeadsController extends BaseController
$end_dates = $this->request->getPost('policy_end_date');
if ($start_dates && $end_dates) {
-
+
$starts = is_array($start_dates) ? $start_dates : [$start_dates];
- $ends = is_array($end_dates) ? $end_dates : [$end_dates];
+ $ends = is_array($end_dates) ? $end_dates : [$end_dates];
foreach ($starts as $index => $s_date) {
$e_date = $ends[$index] ?? null;
if ($s_date && $e_date) {
-
+
$f_start = change_date_format($s_date, 'd/m/Y', 'Y-m-d');
$f_end = change_date_format($e_date, 'd/m/Y', 'Y-m-d');
if ($f_start && $f_end && ($f_end < $f_start)) {
$isValid = false;
-
+
// Determine the error key name
// If it's an array, we use index (e.g., policy_end_date.0)
$errorKey = is_array($start_dates) ? "policy_end_date.$index" : "policy_end_date";
-
+
$this->validator->setError($errorKey, 'Date of Expiry cannot be before Date of Commencement.');
}
}
}
}
-
- if (!$isValid) {
+ if (! $isValid) {
return $this->response->setStatusCode(400)->setJSON([
- 'status' => false,
+ 'status' => false,
'message' => 'Input validation failed',
- 'code' => 400,
- 'errors' => $this->validator->getErrors()
+ 'code' => 400,
+ 'errors' => $this->validator->getErrors(),
]);
}
-
// print_r($data); die;
-
- if (!$id) {
+ if (! $id) {
return $this->insertNewLead($data);
} else {
return $this->updateOldLead($id, $data);
@@ -625,24 +655,23 @@ class LeadsController extends BaseController
private function prepareLeadData()
{
-
- $request_data = $this->request->getPost();
- $data = sanitizeInputArrayAdvanced($request_data);
-
+
+ $request_data = $this->request->getPost();
+ $data = sanitizeInputArrayAdvanced($request_data);
$data['client_type'] = 1;
- $data['pan'] = "";
+ $data['pan'] = "";
if ($data['lead_type'] != 1) {
- $client_data = $this->clientModel->where('id', $data['client_id'])->where('is_active', 1)->first();
- $data['client_name'] = $client_data['client_name'];
+ $client_data = $this->clientModel->where('id', $data['client_id'])->where('is_active', 1)->first();
+ $data['client_name'] = $client_data['client_name'];
$data['client_short_name'] = $client_data['short_name'];
- $data['entity_type_id'] = $client_data['entity_type_id'];
- $data['client_type'] = $client_data['client_type'];
+ $data['entity_type_id'] = $client_data['entity_type_id'];
+ $data['client_type'] = $client_data['client_type'];
} else {
- if(!empty($data['client_id'])){
+ if (! empty($data['client_id'])) {
$data['is_client_created'] = $data['client_id'];
- }else{
- $data['client_id'] = 0;
+ } else {
+ $data['client_id'] = 0;
$data['client_branch_id'] = 0;
$data['source_policy_id'] = 0;
}
@@ -666,14 +695,14 @@ class LeadsController extends BaseController
private function prepareSingleLeadData($data)
{
// print_r($data); die;
- $index_plus_one = 1;
- $form_file_name = "file_name_" . $index_plus_one;
- $form_docs_name = "docs_name_" . $index_plus_one;
+ $index_plus_one = 1;
+ $form_file_name = "file_name_" . $index_plus_one;
+ $form_docs_name = "docs_name_" . $index_plus_one;
$leads_file_primary_key = $data['leads_file_id'] ?? [];
$multi_file_data = [];
if (isset($data[$form_docs_name])) {
- $files = $this->request->getFileMultiple($form_file_name);
+ $files = $this->request->getFileMultiple($form_file_name);
$multi_file_data = $this->uploadMultiFiles($files, $data[$form_docs_name], $leads_file_primary_key);
}
@@ -682,10 +711,10 @@ class LeadsController extends BaseController
list($insurer_branch_id, $insurer_id) = explode('-', $data['insurer']);
} else {
$insurer_branch_id = 0;
- $insurer_id = 0;
+ $insurer_id = 0;
}
- $data['insurer_id'] = $insurer_id;
+ $data['insurer_id'] = $insurer_id;
$data['insurer_branch_id'] = $insurer_branch_id;
// Separate the insurer and insurer branch, handle missing or invalid data
@@ -693,21 +722,20 @@ class LeadsController extends BaseController
list($tpa_branch_id, $tpa_id) = explode('-', $data['tpa']);
} else {
$tpa_branch_id = 0;
- $tpa_id = 0;
+ $tpa_id = 0;
}
- $data['tpa_id'] = $tpa_id;
+ $data['tpa_id'] = $tpa_id;
$data['tpa_branch_id'] = $tpa_branch_id;
-
- if (!empty($data['policy_start_date'])) {
- $data['policy_start_date'] = change_date_format($data['policy_start_date']);
+ if (! empty($data['policy_start_date'])) {
+ $data['policy_start_date'] = change_date_format($data['policy_start_date']);
} else {
$data['policy_start_date'] = null;
}
- if (!empty($data['policy_end_date'])) {
- $data['policy_end_date'] = change_date_format($data['policy_end_date']);
+ if (! empty($data['policy_end_date'])) {
+ $data['policy_end_date'] = change_date_format($data['policy_end_date']);
} else {
$data['policy_end_date'] = null;
}
@@ -728,26 +756,26 @@ class LeadsController extends BaseController
foreach ($data['policy_type_id'] as $index => $value) {
- $index_plus_one = $index + 1;
- $form_file_name = "file_name_" . $index_plus_one;
- $form_docs_name = "docs_name_" . $index_plus_one;
+ $index_plus_one = $index + 1;
+ $form_file_name = "file_name_" . $index_plus_one;
+ $form_docs_name = "docs_name_" . $index_plus_one;
$leads_file_primary_key = $data['leads_file_id'] ?? [];
- $files = $this->request->getFileMultiple($form_file_name);
- $multi_file_data = $this->uploadMultiFiles($files, $data[$form_docs_name], $leads_file_primary_key);
+ $files = $this->request->getFileMultiple($form_file_name);
+ $multi_file_data = $this->uploadMultiFiles($files, $data[$form_docs_name], $leads_file_primary_key);
// Separate the insurer and insurer branch, handle missing or invalid data
if (isset($data['insurer'][$index]) && strpos($data['insurer'][$index], '-') !== false) {
list($insurer_branch_id, $insurer_id) = explode('-', $data['insurer'][$index]);
} else {
$insurer_branch_id = 0;
- $insurer_id = 0;
+ $insurer_id = 0;
}
// Separate the insurer and insurer branch, handle missing or invalid data
if (isset($data['tpa'][$index]) && strpos($data['tpa'][$index], '-') !== false) {
list($tpa_branch_id, $tpa_id) = explode('-', $data['tpa'][$index]);
} else {
$tpa_branch_id = 0;
- $tpa_id = 0;
+ $tpa_id = 0;
}
// Separate the insurer and insurer branch, handle missing or invalid data
@@ -755,7 +783,7 @@ class LeadsController extends BaseController
list($proposed_insurer_branch_id, $proposed_insurer_id) = explode('-', $data['proposed_insurer'][$index]);
} else {
$proposed_insurer_branch_id = 0;
- $proposed_insurer_id = 0;
+ $proposed_insurer_id = 0;
}
// Separate the TPA and TPA branch, handle missing or invalid data
@@ -763,23 +791,23 @@ class LeadsController extends BaseController
list($proposed_tpa_branch_id, $proposed_tpa_id) = explode('-', $data['proposed_tpa'][$index]);
} else {
$proposed_tpa_branch_id = 0;
- $proposed_tpa_id = 0;
+ $proposed_tpa_id = 0;
}
- if (!empty($data['policy_start_date'][$index])) {
- $policy_start_date = change_date_format($data['policy_start_date'][$index], 'd/m/Y', 'Y-m-d');
+ if (! empty($data['policy_start_date'][$index])) {
+ $policy_start_date = change_date_format($data['policy_start_date'][$index], 'd/m/Y', 'Y-m-d');
} else {
$policy_start_date = null;
}
- if (!empty($data['policy_end_date'][$index])) {
- $policy_end_date = change_date_format($data['policy_end_date'][$index], 'd/m/Y', 'Y-m-d');
+ if (! empty($data['policy_end_date'][$index])) {
+ $policy_end_date = change_date_format($data['policy_end_date'][$index], 'd/m/Y', 'Y-m-d');
} else {
$policy_end_date = null;
}
- if (!empty($data['incurred_claim_date'][$index])) {
- $incurred_claims_date = change_date_format($data['incurred_claim_date'][$index], 'd/m/Y', 'Y-m-d');
+ if (! empty($data['incurred_claim_date'][$index])) {
+ $incurred_claims_date = change_date_format($data['incurred_claim_date'][$index], 'd/m/Y', 'Y-m-d');
} else {
$incurred_claims_date = null;
}
@@ -790,14 +818,14 @@ class LeadsController extends BaseController
// $premium_date = null;
// }
- if (!empty($data['source_policy_start_date']) && $data['lead_type'] == 2) {
- $data['source_policy_start_date'] = change_date_format($data['source_policy_start_date'], 'd/m/Y', 'Y-m-d');
+ if (! empty($data['source_policy_start_date']) && $data['lead_type'] == 2) {
+ $data['source_policy_start_date'] = change_date_format($data['source_policy_start_date'], 'd/m/Y', 'Y-m-d');
} else {
$data['source_policy_start_date'] = null;
}
- if (!empty($data['source_policy_end_date']) && $data['lead_type'] == 2) {
- $data['source_policy_end_date'] = change_date_format($data['source_policy_end_date'], 'd/m/Y', 'Y-m-d');
+ if (! empty($data['source_policy_end_date']) && $data['lead_type'] == 2) {
+ $data['source_policy_end_date'] = change_date_format($data['source_policy_end_date'], 'd/m/Y', 'Y-m-d');
} else {
$data['source_policy_end_date'] = null;
}
@@ -807,7 +835,7 @@ class LeadsController extends BaseController
$reminderDate = trim($data['next_reminder_date'] ?? '');
if ($reminderDate !== '' && $reminderDate != null && $reminderDate != 0) {
- $convertedDate = change_date_format($reminderDate);
+ $convertedDate = change_date_format($reminderDate);
$data['next_reminder_date'] = $convertedDate ?: null;
} else {
$data['next_reminder_date'] = null;
@@ -825,6 +853,7 @@ class LeadsController extends BaseController
$last_3_years_claims = $data['finyear'];
$processedData[] = [
+ 'lost_reason' => $data['lost_reason'] ?? null,
'actual_lead_id' => $data['actual_lead_id'] ?? null,
'lead_type' => $data['lead_type'],
'issuer' => $data['issuer'],
@@ -846,63 +875,62 @@ class LeadsController extends BaseController
'source_policy_id' => $data['source_policy_id'] ?? 0,
'policy_type_id' => $value,
'salse_person_id' => $data['salse_person_id'] ?? 0,
+ 'insurer_id' => $insurer_id ?? 0,
+ 'insurer_branch_id' => $insurer_branch_id ?? 0,
+ 'tpa_id' => $tpa_id ?? 0,
+ 'tpa_branch_id' => $tpa_branch_id ?? 0,
+ 'policy_start_date' => $policy_start_date,
+ 'policy_end_date' => $policy_end_date,
+ 'no_of_lives' => $data['no_of_lives'][$index] ?? null,
+ 'incurred_claims' => $data['incurred_claims'][$index] ?? 0,
+ 'location' => $data['location'][$index] ?? null,
+ 'proposed_insurer_id' => $proposed_insurer_id ?? 0,
+ 'proposed_insurer_branch_id' => $proposed_insurer_branch_id ?? 0,
+ 'proposed_tpa_id' => $proposed_tpa_id ?? 0,
+ 'proposed_tpa_branch_id' => $proposed_tpa_branch_id ?? 0,
- 'insurer_id' => $insurer_id ?? 0,
- 'insurer_branch_id' => $insurer_branch_id ?? 0,
- 'tpa_id' => $tpa_id ?? 0,
- 'tpa_branch_id' => $tpa_branch_id ?? 0,
- 'policy_start_date' => $policy_start_date,
- 'policy_end_date' => $policy_end_date,
- 'no_of_lives' => $data['no_of_lives'][$index] ?? null,
- 'incurred_claims' => $data['incurred_claims'][$index] ?? 0,
- 'location' => $data['location'][$index] ?? null,
- 'proposed_insurer_id' => $proposed_insurer_id ?? 0,
- 'proposed_insurer_branch_id' => $proposed_insurer_branch_id ?? 0,
- 'proposed_tpa_id' => $proposed_tpa_id ?? 0,
- 'proposed_tpa_branch_id' => $proposed_tpa_branch_id ?? 0,
+ 'renewal_emp_count' => $data['renewal_emp_count'][$index] ?? 0,
+ 'renewal_dept_count' => $data['renewal_dept_count'][$index] ?? 0,
+ 'renewal_no_of_lives' => $data['renewal_no_of_lives'][$index] ?? 0,
+ 'incept_emp_count' => $data['incept_emp_count'][$index] ?? 0,
+ 'incept_dept_count' => $data['incept_dept_count'][$index] ?? 0,
+ 'incept_no_of_lives' => $data['incept_no_of_lives'][$index] ?? 0,
+ 'exp_emp_count' => $data['exp_emp_count'][$index] ?? 0,
+ 'exp_dept_count' => $data['exp_dept_count'][$index] ?? 0,
+ 'exp_no_of_lives' => $data['exp_no_of_lives'][$index] ?? 0,
- 'renewal_emp_count' => $data['renewal_emp_count'][$index] ?? 0,
- 'renewal_dept_count' => $data['renewal_dept_count'][$index] ?? 0,
- 'renewal_no_of_lives' => $data['renewal_no_of_lives'][$index] ?? 0,
- 'incept_emp_count' => $data['incept_emp_count'][$index] ?? 0,
- 'incept_dept_count' => $data['incept_dept_count'][$index] ?? 0,
- 'incept_no_of_lives' => $data['incept_no_of_lives'][$index] ?? 0,
- 'exp_emp_count' => $data['exp_emp_count'][$index] ?? 0,
- 'exp_dept_count' => $data['exp_dept_count'][$index] ?? 0,
- 'exp_no_of_lives' => $data['exp_no_of_lives'][$index] ?? 0,
+ 'incurred_claims_date' => $incurred_claims_date,
+ 'paid_claims' => $data['paid_claims'][$index] ?? 0,
+ 'outstanding_claims' => $data['outstanding_claims'][$index] ?? 0,
+ 'policy_run_days' => $data['policy_run_days'][$index] ?? 0,
+ 'premium_at_inception' => $data['premium_at_inception'][$index] ?? 0,
+ 'premium_date' => $data['premium_date'][$index] ?? 0,
+ 'earned_premium' => $data['earned_premium'][$index] ?? 0,
+ 'annualised_claims' => $data['annualised_claims'][$index] ?? 0,
+ 'incurred_claims_ratio' => $data['incurred_claims_ratio'][$index] ?? 0,
+ 'earned_claims_ratio' => $data['earned_claims_ratio'][$index] ?? 0,
+ 'total_si_at_incept' => $data['total_si_at_incept'][$index] ?? 0,
+ 'total_si_at_renewal' => $data['total_si_at_renewal'][$index] ?? 0,
- 'incurred_claims_date' => $incurred_claims_date,
- 'paid_claims' => $data['paid_claims'][$index] ?? 0,
- 'outstanding_claims' => $data['outstanding_claims'][$index] ?? 0,
- 'policy_run_days' => $data['policy_run_days'][$index] ?? 0,
- 'premium_at_inception' => $data['premium_at_inception'][$index] ?? 0,
- 'premium_date' => $data['premium_date'][$index] ?? 0,
- 'earned_premium' => $data['earned_premium'][$index] ?? 0,
- 'annualised_claims' => $data['annualised_claims'][$index] ?? 0,
- 'incurred_claims_ratio' => $data['incurred_claims_ratio'][$index] ?? 0,
- 'earned_claims_ratio' => $data['earned_claims_ratio'][$index] ?? 0,
- 'total_si_at_incept' => $data['total_si_at_incept'][$index] ?? 0,
- 'total_si_at_renewal' => $data['total_si_at_renewal'][$index] ?? 0,
-
- 'total_lives_at_incept' => $data['total_lives_at_incept'][$index] ?? 0,
- 'premium_at_incept' => $data['premium_at_incept'][$index] ?? 0,
- 'fin_years_claims' => $last_3_years_claims,
+ 'total_lives_at_incept' => $data['total_lives_at_incept'][$index] ?? 0,
+ 'premium_at_incept' => $data['premium_at_incept'][$index] ?? 0,
+ 'fin_years_claims' => $last_3_years_claims,
// 'file_name' => $file_name,
- 'multi_file_data' => $multi_file_data ?? null,
+ 'multi_file_data' => $multi_file_data ?? null,
- 'status' => $data['status'] ?? null,
- 'notes' => $data['notes'] ?? null,
+ 'status' => $data['status'] ?? null,
+ 'notes' => $data['notes'] ?? null,
- 'lead_form_type' => $data['lead_form_type'] ?? 1,
- 'custom_fields' => $data['custom_fields'] ?? null,
+ 'lead_form_type' => $data['lead_form_type'] ?? 1,
+ 'custom_fields' => $data['custom_fields'] ?? null,
- 'source_policy_start_date' => $data['source_policy_start_date'] ?? null,
- 'source_policy_end_date' => $data['source_policy_end_date'] ?? null,
- 'claim_history' => $data['claim_history'] ?? 0,
+ 'source_policy_start_date' => $data['source_policy_start_date'] ?? null,
+ 'source_policy_end_date' => $data['source_policy_end_date'] ?? null,
+ 'claim_history' => $data['claim_history'] ?? 0,
- 'next_reminder_date' => $data['next_reminder_date'] ?? null,
- 'is_insurer_auto_mail' => $data['is_insurer_auto_mail'] ?? 0
+ 'next_reminder_date' => $data['next_reminder_date'] ?? null,
+ 'is_insurer_auto_mail' => $data['is_insurer_auto_mail'] ?? 0,
];
}
// print_r($processedData);die();
@@ -924,7 +952,7 @@ class LeadsController extends BaseController
if ($value['lead_form_type'] == 1) {
//for this push the job to the calculateMembersDemography() function
- $job_details = new Jobs();
+ $job_details = new Jobs();
// $r = Jobs::addJob(['job_name' => 'memberDataListExcelFileFormatValidation', 'payload' => [
// 'lead_id' => $insert,
// ]]);
@@ -961,26 +989,25 @@ class LeadsController extends BaseController
->where('leads.is_active', 1)
->first();
- $data['lead_edit_data'] = $this->leadsModel
+ $data['lead_edit_data'] = $this->leadsModel
->where('leads.id', $id)
->where('leads.is_active', 1)
->first();
-
- if (!empty($data['policy_start_date'])) {
- $data['policy_start_date'] = change_date_format($data['policy_start_date'], 'Y-m-d', 'd/m/Y');
+ if (! empty($data['policy_start_date'])) {
+ $data['policy_start_date'] = change_date_format($data['policy_start_date'], 'Y-m-d', 'd/m/Y');
} else {
$data['policy_start_date'] = null;
}
- if (!empty($data['policy_end_date'])) {
- $data['policy_end_date'] = change_date_format($data['policy_end_date'], 'Y-m-d', 'd/m/Y');
+ if (! empty($data['policy_end_date'])) {
+ $data['policy_end_date'] = change_date_format($data['policy_end_date'], 'Y-m-d', 'd/m/Y');
} else {
$data['policy_end_date'] = null;
}
- if (!empty($data['incurred_claims_date'])) {
- $data['incurred_claims_date'] = change_date_format($data['incurred_claims_date'], 'Y-m-d', 'd/m/Y');
+ if (! empty($data['incurred_claims_date'])) {
+ $data['incurred_claims_date'] = change_date_format($data['incurred_claims_date'], 'Y-m-d', 'd/m/Y');
} else {
$data['incurred_claims_date'] = null;
}
@@ -992,17 +1019,17 @@ class LeadsController extends BaseController
// }
$data['multi_file_data'] = $this->leadFilesModel
- ->where('lead_id', $id)
- ->where('type !=', 2)
- ->where('is_active', 1)
- ->first() ?? null;
+ ->where('lead_id', $id)
+ ->where('type !=', 2)
+ ->where('is_active', 1)
+ ->first() ?? null;
$data['lastFiveYears'] = $this->getLastFiveFinancialYears();
- $data['gpaClaimType'] = $this->claim_type_for_gpa;
- $data['causeOfDeath'] = $this->cause_of_death;
+ $data['gpaClaimType'] = $this->claim_type_for_gpa;
+ $data['causeOfDeath'] = $this->cause_of_death;
- if (!empty($data['fin_years_claims'])) {
- $decoded = json_decode($data['fin_years_claims'], true);
+ if (! empty($data['fin_years_claims'])) {
+ $decoded = json_decode($data['fin_years_claims'], true);
$data['lead_edit_data']['fin_years_claims_array'] = isset($decoded['finyear']) ? $decoded['finyear'] : [];
} else {
$data['lead_edit_data']['fin_years_claims_array'] = [];
@@ -1023,24 +1050,24 @@ class LeadsController extends BaseController
{
$statusData = [
'policy_tran_id' => $primaryKey,
- 'status' => $status,
- 'status_type' => $statusType,
- 'created_by' => get_session_userid(),
+ 'status' => $status,
+ 'status_type' => $statusType,
+ 'created_by' => get_session_userid(),
];
$this->policyTransactionStatusModel->insert($statusData);
}
public function uploadMultiFiles($files, $docs_names, $primaryKey)
- {
+ {
$uploadFilePath = WRITEPATH . 'uploads/lead_files/';
$multi_file_data = [];
foreach ($files as $index => $value) {
- $file_name = file_Upload_for_lead($value, $uploadFilePath, UPLOAD_EXT_LEAD_FILES);
+ $file_name = file_Upload_for_lead($value, $uploadFilePath, UPLOAD_EXT_LEAD_FILES);
$multi_file_data[] = [
'file_name' => $file_name,
'docs_name' => $docs_names[$index],
- 'id' => $primaryKey[$index] ?? "",
+ 'id' => $primaryKey[$index] ?? "",
];
}
@@ -1051,27 +1078,27 @@ class LeadsController extends BaseController
{
log_message('info', 'insertMultiFilesData() called with lead_id: ' . $lead_id);
- if (!empty($data)) {
+ if (! empty($data)) {
log_message('info', 'Data is not empty. Total items: ' . count($data));
foreach ($data as $key => $value) {
log_message('info', "Processing item at index {$key}: " . json_encode($value));
- if (!empty($value['id'])) {
+ if (! empty($value['id'])) {
log_message('info', "Record with ID {$value['id']} exists. Preparing to update.");
$lead_file_data = [
- 'lead_id' => $lead_id,
+ 'lead_id' => $lead_id,
'docs_name' => $value['docs_name'],
];
- if (!empty($value['file_name'])) {
+ if (! empty($value['file_name'])) {
$lead_file_data['file_name'] = $value['file_name'];
log_message('info', "file_name found: {$value['file_name']}");
- if (!empty($lead_form_type) && $lead_form_type == 1 && $key == 0) {
+ if (! empty($lead_form_type) && $lead_form_type == 1 && $key == 0) {
//for this push the job to the calculateMembersDemography() function
- $job_details = new Jobs();
+ $job_details = new Jobs();
// $r = Jobs::addJob(['job_name' => 'memberDataListExcelFileFormatValidation', 'payload' => [
// 'lead_id' => $lead_id,
// ]]);
@@ -1087,9 +1114,9 @@ class LeadsController extends BaseController
} else {
log_message('info', "No ID found. Preparing to insert new record.");
- if (!empty($value['file_name'])) {
+ if (! empty($value['file_name'])) {
$lead_file_data = [
- 'lead_id' => $lead_id,
+ 'lead_id' => $lead_id,
'docs_name' => $value['docs_name'],
'file_name' => $value['file_name'],
];
@@ -1101,7 +1128,7 @@ class LeadsController extends BaseController
}
}
- if ($key == 0 && !empty($value['file_name'])) {
+ if ($key == 0 && ! empty($value['file_name'])) {
log_message('info', "Setting first file_name '{$value['file_name']}' to leadsModel for lead_id: {$lead_id}");
$this->leadsModel->where('id', $lead_id)->set('file_name', $value['file_name'])->update();
}
@@ -1117,7 +1144,7 @@ class LeadsController extends BaseController
public function removeMultiFile()
{
$id = $this->request->getGet('lead_file_id');
- if (!empty($id)) {
+ if (! empty($id)) {
$this->leadFilesModel->where('id', $id)->set(['is_active' => 0])->update();
return $this->respond(['status' => true, 'message' => 'File removed successfully'], 200);
} else {
@@ -1155,10 +1182,10 @@ class LeadsController extends BaseController
// $data['lead_id'] = $id;
// $lead_data = $this->leadsModel
// ->select('
- // leads.*,
- // policy_type.question_json,
+ // leads.*,
+ // policy_type.question_json,
// policy_type.policy_type,
- // policy_type.long_name,
+ // policy_type.long_name,
// user_profiles.email as created_person_email
// ')
// ->join('policy_type', 'leads.policy_type_id = policy_type.id')
@@ -1185,7 +1212,6 @@ class LeadsController extends BaseController
// $data['tpa_list'] = $this->tpaBranchModel->getTpaBranchesWithTpaNames();
// $data['account_manager'] = $this->userModel->where('is_active', 1)->where('role', 3)->findAll();
-
// $mail_content = '
//
Dear Sir,
// Greetings From Nhance India!
@@ -1290,10 +1316,10 @@ class LeadsController extends BaseController
// 3. Optimize lead data query with specific field selection
$lead_data = $this->leadsModel
->select('
- leads.*,
+ leads.*,
lead_files.status as demography_file_status,
- policy_type.question_json,
- policy_type.policy_type,
+ policy_type.question_json,
+ policy_type.policy_type,
policy_type.long_name,
user_profiles.email as created_person_email
')
@@ -1304,7 +1330,7 @@ class LeadsController extends BaseController
->where('leads.is_active', 1)
->first();
- if (!$lead_data) {
+ if (! $lead_data) {
// Handle case where lead doesn't exist
throw new \Exception('Opportunity not found');
}
@@ -1328,38 +1354,38 @@ class LeadsController extends BaseController
}
// 5. Cache decoded JSON to avoid multiple decodes
- $question_json_decoded = !empty($lead_data['question_json'])
+ $question_json_decoded = ! empty($lead_data['question_json'])
? json_decode($lead_data['question_json'], true)
: null;
$data['question_json'] = $lead_data['question_json'];
- $data['tab_name'] = $type == 2 ? 'QCR' : 'RFQ';
- $data['page_name'] = $type == 2 ? 'QCR' : 'RFQ';
- $data['lead_data'] = $lead_data;
+ $data['tab_name'] = $type == 2 ? 'QCR' : 'RFQ';
+ $data['page_name'] = $type == 2 ? 'QCR' : 'RFQ';
+ $data['lead_data'] = $lead_data;
// 6. Parallel/batch data fetching for independent queries
- $data['insurer'] = $this->insurerBranchModel->getInsurerBranchesWithInsurerNames();
- $data['userList'] = $this->userModel->getUserListForRFQ();
+ $data['insurer'] = $this->insurerBranchModel->getInsurerBranchesWithInsurerNames();
+ $data['userList'] = $this->userModel->getUserListForRFQ();
$data['exclusiveUserList'] = $this->userModel->getexclusiveUserListForRFQ();
- $data['tpa_list'] = $this->tpaBranchModel->getTpaBranchesWithTpaNames();
- $data['account_manager'] = $this->userModel
+ $data['tpa_list'] = $this->tpaBranchModel->getTpaBranchesWithTpaNames();
+ $data['account_manager'] = $this->userModel
->where('is_active', 1)
->where('role', 3)
->findAll();
// 7. Define mail templates as constants or config
- $mail_content = $this->getMailTemplate();
+ $mail_content = $this->getMailTemplate();
$placement_mail_content = $this->getMailTemplate('placement');
- $subject = $this->getSubjectTemplate($lead_data);
+ $subject = $this->getSubjectTemplate($lead_data);
// 8. Pre-calculate sum assured only for GPA
$data['totalSumAssured'] = ($lead_data['policy_type_id'] == 1) ? $this->handleMemberDataGPATotalSumInsurerFromExcel(['lead_id' => $id]) : [];
// 9. Transform mail content once
- $data['mail_content'] = $this->transformMailContent($lead_data, $mail_content, $data['page_name']);
- $data['subject'] = $this->transformMailContent($lead_data, $subject, $data['page_name']);
+ $data['mail_content'] = $this->transformMailContent($lead_data, $mail_content, $data['page_name']);
+ $data['subject'] = $this->transformMailContent($lead_data, $subject, $data['page_name']);
$data['placement_mail_content'] = $this->transformMailContent($lead_data, $placement_mail_content, 'Placement');
- $data['placement_subject'] = $this->transformMailContent($lead_data, $subject, 'Placement');
+ $data['placement_subject'] = $this->transformMailContent($lead_data, $subject, 'Placement');
// 10. Combine related queries
$data['multi_file_data'] = $this->leadFilesModel
@@ -1374,7 +1400,7 @@ class LeadsController extends BaseController
->findAll();
// 11. Generate views efficiently
- $data['lead_data']['installment_data'] = !empty($installment_data['installments'])
+ $data['lead_data']['installment_data'] = ! empty($installment_data['installments'])
? view('rfq/installment_fields', $installment_data)
: null;
@@ -1398,22 +1424,22 @@ class LeadsController extends BaseController
// Use cached decoded JSON
if ($question_json_decoded) {
- $data['policies'] = $question_json_decoded['policies'] ?? [];
+ $data['policies'] = $question_json_decoded['policies'] ?? [];
$data["child_table_data"] = $question_json_decoded['child_table_data'] ?? [];
}
- $data['product'] = $lead_data['policy_type'];
+ $data['product'] = $lead_data['policy_type'];
$data['buisness_type'] = $this->buisnessType;
- $data['client_type'] = $this->clientType;
+ $data['client_type'] = $this->clientType;
$this->loadLayout('view_rfq_non_eb', $data);
}
}
// 13. Extract mail template to separate method for reusability
- private function getMailTemplate( $template_type = "" )
- {
- if($template_type == 'placement'){
+ private function getMailTemplate($template_type = "")
+ {
+ if ($template_type == 'placement') {
return '
Dear Sir,
Greetings From Nhance India!
@@ -1422,15 +1448,15 @@ class LeadsController extends BaseController
In case of any query, please feel free to contact us.
Thank You!
Best regards,
-
+
{{LOGGED_USER_NAME}}
Mobile: {{LOGGED_USER_MOBILE}}
-
+
';
- }else{
+ } else {
return '
Dear Sir,
Greetings From Nhance India!
@@ -1439,12 +1465,12 @@ class LeadsController extends BaseController
In case of any query, please feel free to contact us.
Thank You!
Best regards,
-
+
{{LOGGED_USER_NAME}}
Mobile: {{LOGGED_USER_MOBILE}}
-
+
';
}
@@ -1463,7 +1489,7 @@ class LeadsController extends BaseController
$data = $this->request->getPost();
- $lead_id = $data['lead_id'];
+ $lead_id = $data['lead_id'];
$json_data = $data['registration_json'];
$existingJson = $this->RFQModel->where('is_active', 1)->where("lead_id", $lead_id)->first()['registration_json'] ?? null;
@@ -1476,10 +1502,9 @@ class LeadsController extends BaseController
->set('is_active', 0)
->update();
- $insertData['lead_id'] = $lead_id;
+ $insertData['lead_id'] = $lead_id;
$insertData['registration_json'] = json_encode($json_data);
-
$this->RFQModel->insert($insertData);
return $this->respond(['status' => true, "message" => "Policy Inforamtion saved"]);
@@ -1491,26 +1516,26 @@ class LeadsController extends BaseController
public function createRFQ()
{
- $data = $this->request->getPost();
+ $data = $this->request->getPost();
$lead_id = $data['lead_id'] ?? null;
- if (!$lead_id) {
+ if (! $lead_id) {
return $this->respond(['status' => false, 'message' => 'Opportunity ID is required'], 400);
}
$rfq_created = $this->RFQModel->where('lead_id', $lead_id)->where('is_active', 1)->countAllResults();
$qcr_created = false;
- $inputJson = json_decode($data['json'], true);
- if (isset($inputJson['premium_data']) && !empty($inputJson['premium_data'])) {
- $sortedJson = $this->reorderProposalsByInsurerTotal($inputJson);
+ $inputJson = json_decode($data['json'], true);
+ if (isset($inputJson['premium_data']) && ! empty($inputJson['premium_data'])) {
+ $sortedJson = $this->reorderProposalsByInsurerTotal($inputJson);
$data['json'] = json_encode($sortedJson);
- $qcr_created = true;
+ $qcr_created = true;
}
$quote_received_insurer = [];
if (($data['submit_type'] ?? "") === 'QCR') {
- $inputJson = json_decode($data['json'], true);
+ $inputJson = json_decode($data['json'], true);
$proposal_data = $inputJson['proposal_data'] ?? array_pop($inputJson);
if (isset($proposal_data['over_all_column_data'])) {
@@ -1519,11 +1544,11 @@ class LeadsController extends BaseController
$this->myLogger->logme("error", "insurer id : " . json_encode($proposel_count));
foreach ($proposel_count as $key => $value) {
- if (!empty($value['insurers'])) {
+ if (! empty($value['insurers'])) {
$qcr_created = true;
foreach ($value['insurers'] as $insurer => $id) {
- if (!empty($id['id'])) {
+ if (! empty($id['id'])) {
$quote_received_insurer[] = $id['id'];
}
}
@@ -1536,13 +1561,13 @@ class LeadsController extends BaseController
$data['type'] = 1;
//update the quote received insurer data to the lead
- if(count($quote_received_insurer) != 0){
+ if (count($quote_received_insurer) != 0) {
$this->leadsModel->update($lead_id, ['quote_received_insurer' => json_encode($quote_received_insurer ?? [])]);
$this->myLogger->logme("error", "quote_received_insurer data updated in the lead: " . json_encode($quote_received_insurer));
}
// Deactivate existing RFQs for this lead and type
- if (!isset($data['rfq_primaryKey']) && empty($data['rfq_primaryKey'])) {
+ if (! isset($data['rfq_primaryKey']) && empty($data['rfq_primaryKey'])) {
$this->RFQModel
->where('lead_id', $lead_id)
->where('type', 1)
@@ -1560,16 +1585,16 @@ class LeadsController extends BaseController
->orderBy('id', 'DESC')
->first();
- if (!empty($latest['registration_json'])) {
+ if (! empty($latest['registration_json'])) {
$data['registration_json'] = $latest['registration_json'];
}
}
// print_r($data); die;
// $data['json'] = "";
- if (isset($data['rfq_primaryKey']) && !empty($data['rfq_primaryKey'])) {
+ if (isset($data['rfq_primaryKey']) && ! empty($data['rfq_primaryKey'])) {
$this->RFQModel->update($data['rfq_primaryKey'], $data);
- $insertId = $data['rfq_primaryKey'];
+ $insertId = $data['rfq_primaryKey'];
$affectedRows = db_connect()->affectedRows();
} else {
// Insert new RFQ
@@ -1592,28 +1617,28 @@ class LeadsController extends BaseController
$message = ($data['submit_type'] ?? '') == 'QCR' ? 'QCR saved successfully' : 'RFQ saved successfully';
return $this->respond([
- 'status' => true,
- 'id' => $insertId,
- 'message' => $message,
- 'data' => $data,
+ 'status' => true,
+ 'id' => $insertId,
+ 'message' => $message,
+ 'data' => $data,
'affectedRows' => $affectedRows ?? null,
], 200);
}
$message = ($data['submit_type'] ?? '') == 'QCR' ? 'Failed to save QCR' : 'Failed to save RFQ';
return $this->respond([
- 'status' => false,
- 'id' => null,
+ 'status' => false,
+ 'id' => null,
'message' => $message,
- 'data' => $data
+ 'data' => $data,
], 200);
}
public function createQCR()
{
- $data = $this->request->getPost();
- $lead_id = $data['lead_id'];
+ $data = $this->request->getPost();
+ $lead_id = $data['lead_id'];
$data['type'] = 2;
$this->RFQModel
@@ -1632,15 +1657,16 @@ class LeadsController extends BaseController
return $this->respond(['status' => false, 'id' => $result, 'message' => "Failed to create QCR", 'data' => $data], 200);
}
-
public function reorderProposalsByInsurerTotal(array $data): array
{
- if (!isset($data['premium_data']['data'])) return $data;
+ if (! isset($data['premium_data']['data'])) {
+ return $data;
+ }
- $original = $data['premium_data']['data'];
- $proposals = [];
- $others = [];
+ $original = $data['premium_data']['data'];
+ $proposals = [];
+ $others = [];
$emptyKeyData = [];
foreach ($original as $key => $value) {
@@ -1677,7 +1703,7 @@ class LeadsController extends BaseController
// Add Quote Asked back at the top
$proposal = array_merge(['Quote Asked' => $quoteAsked], $proposal);
}
-
+
// Sort proposals by their insurer's total
uasort($proposals, function ($a, $b) {
$totalA = 0;
@@ -1702,29 +1728,29 @@ class LeadsController extends BaseController
// Merge back the sorted proposals into the full structure
$data['premium_data']['data'] = array_merge($others, $proposals, $emptyKeyData);
- $data = $this->reorderProposalDataByPremiumOrder($data);
+ $data = $this->reorderProposalDataByPremiumOrder($data);
return $data;
}
private function reorderProposalDataByPremiumOrder(array $data): array
{
- if (!isset($data['premium_data']['data'], $data['proposal_data']['over_all_column_data'])) {
+ if (! isset($data['premium_data']['data'], $data['proposal_data']['over_all_column_data'])) {
return $data;
}
- $porposalData = $data['premium_data']['data'];
- $premiumProposals = array_keys($data['premium_data']['data']);
+ $porposalData = $data['premium_data']['data'];
+ $premiumProposals = array_keys($data['premium_data']['data']);
$filteredProposals = [];
//Reorder the Insurer based on the Premium data insurer
foreach ($porposalData as $key => $value) {
- if(in_array($key, ['Particulars', ""])){
+ if (in_array($key, ['Particulars', ""])) {
continue;
}
// Ensure the premium data is an array and not empty
- if (!is_array($value) || empty($value)) {
+ if (! is_array($value) || empty($value)) {
continue;
}
@@ -1741,7 +1767,7 @@ class LeadsController extends BaseController
// });
// Step 2: Reorder proposal insurers based on premium order
- usort($data['proposal_data']['over_all_column_data'][$key]['insurers'], function($a, $b) use ($premiumOrder) {
+ usort($data['proposal_data']['over_all_column_data'][$key]['insurers'], function ($a, $b) use ($premiumOrder) {
$posA = array_search($a['display_name'] ?? '', $premiumOrder);
$posB = array_search($b['display_name'] ?? '', $premiumOrder);
@@ -1764,21 +1790,21 @@ class LeadsController extends BaseController
// dd($premiumProposals, $filteredProposals);
$data['proposal_data']['over_all_column_data'] = $filteredProposals;
- $data = $this->reorderProposalInHeaderAndData($data);
+ $data = $this->reorderProposalInHeaderAndData($data);
return $data;
}
private function reorderProposalInHeaderAndData(array $data): array
{
- $tableData = $data['table_data'];
+ $tableData = $data['table_data'];
$sortedProposalOrder = $data['proposal_data']['over_all_column_data'];
- $headers = $tableData['headers'] ?? [];
- $dataRows = $tableData['data'] ?? [];
+ $headers = $tableData['headers'] ?? [];
+ $dataRows = $tableData['data'] ?? [];
// Step 1: Separate static and proposal headers
- $staticHeaders = [];
+ $staticHeaders = [];
$proposalHeaders = [];
- $actionHeader = [];
+ $actionHeader = [];
foreach ($headers as $header) {
if (in_array($header['parentHeader'], array_keys($sortedProposalOrder))) {
$proposalHeaders[$header['parentHeader']] = $header;
@@ -1795,10 +1821,10 @@ class LeadsController extends BaseController
foreach ($sortedProposalOrder as $proposalKey => $proposalData) {
// Skip if insurers or subHeaders are missing
if (
- !isset($proposalData['insurers']) ||
- !is_array($proposalData['insurers']) ||
- !isset($proposalHeaders[$proposalKey]['subHeaders']) ||
- !is_array($proposalHeaders[$proposalKey]['subHeaders'])
+ ! isset($proposalData['insurers']) ||
+ ! is_array($proposalData['insurers']) ||
+ ! isset($proposalHeaders[$proposalKey]['subHeaders']) ||
+ ! is_array($proposalHeaders[$proposalKey]['subHeaders'])
) {
continue;
}
@@ -1808,7 +1834,7 @@ class LeadsController extends BaseController
// Add insurers in the sorted order
foreach ($proposalData['insurers'] as $insurer) {
- if(in_array($insurer['display_name'], $proposalHeaders[$proposalKey]['subHeaders'])){
+ if (in_array($insurer['display_name'], $proposalHeaders[$proposalKey]['subHeaders'])) {
$newSubHeaders[] = $insurer['display_name'];
}
}
@@ -1830,7 +1856,7 @@ class LeadsController extends BaseController
// print_rr($reorderedHeaders); die;
$proposel_count = 1;
foreach ($reorderedHeaders as $key => &$value) {
- if(!in_array($value['parentHeader'], ["Existing Renewal", "Existing Rollover"])){
+ if (! in_array($value['parentHeader'], ["Existing Renewal", "Existing Rollover"])) {
$value['parentHeader'] = 'Proposal ' . $proposel_count;
$proposel_count++;
}
@@ -1839,12 +1865,12 @@ class LeadsController extends BaseController
//merge the all headers
$reorderedHeaders = array_merge($staticHeaders, $reorderedHeaders, $actionHeader);
-
+
// Step 3: Reorder each row's `data` by matching parentth
foreach ($dataRows as $dataRowIndex => &$row) {
- $staticData = [];
+ $staticData = [];
$proposalData = [];
- $actionData = [];
+ $actionData = [];
foreach ($row['data'] as $entry) {
if (in_array($entry['parentth'], array_keys($sortedProposalOrder))) {
@@ -1867,18 +1893,18 @@ class LeadsController extends BaseController
}
}
- $dubParTh = "";
+ $dubParTh = "";
$increament = 0;
foreach ($reorderedProposalData as $key => &$value) {
if ($dubParTh == $value['parentth']) {
- if(!in_array($value['parentth'], ["Existing Renewal", "Existing Rollover"])){
+ if (! in_array($value['parentth'], ["Existing Renewal", "Existing Rollover"])) {
$value['parentth'] = 'Proposal ' . ($increament);
}
} else {
$dubParTh = $value['parentth'];
- if(!in_array($value['parentth'], ["Existing Renewal", "Existing Rollover"])){
- $increament = $increament + 1;
+ if (! in_array($value['parentth'], ["Existing Renewal", "Existing Rollover"])) {
+ $increament = $increament + 1;
$value['parentth'] = 'Proposal ' . ($increament);
}
}
@@ -1888,19 +1914,18 @@ class LeadsController extends BaseController
//Reorder the Row Data based on the Insurer
$reorderedProposalData = $this->reorderProposalRowData($reorderedProposalData, $proposalHeaders);
-
// print_rr($reorderedProposalData); die;
$row['data'] = array_merge($staticData, $reorderedProposalData, $actionData);
}
$data['table_data']['headers'] = $reorderedHeaders;
- $data['table_data']['data'] = $dataRows;
+ $data['table_data']['data'] = $dataRows;
- $renumberedArray = $this->renumberProposalKeys($data['proposal_data']['over_all_column_data']);
- $updatedDataSet = $this->renumberProposalKeys($data['premium_data']['data']);
- $data['proposal_data']['over_all_column_data'] = !empty($renumberedArray) ? $renumberedArray : $data['proposal_data']['over_all_column_data'];
- $data['premium_data']['data'] = !empty($updatedDataSet) ? $updatedDataSet : $data['premium_data']['data'];
+ $renumberedArray = $this->renumberProposalKeys($data['proposal_data']['over_all_column_data']);
+ $updatedDataSet = $this->renumberProposalKeys($data['premium_data']['data']);
+ $data['proposal_data']['over_all_column_data'] = ! empty($renumberedArray) ? $renumberedArray : $data['proposal_data']['over_all_column_data'];
+ $data['premium_data']['data'] = ! empty($updatedDataSet) ? $updatedDataSet : $data['premium_data']['data'];
return $data;
}
@@ -1912,7 +1937,7 @@ class LeadsController extends BaseController
// Group rows by parentth
$groupedRows = [];
foreach ($proposalRowData as $row) {
- if (!isset($row['parentth'])) {
+ if (! isset($row['parentth'])) {
continue; // skip invalid rows
}
$groupedRows[$row['parentth']][] = $row;
@@ -1921,15 +1946,15 @@ class LeadsController extends BaseController
// Reorder each group's rows based on header subHeaders
foreach ($proposalHeaderData as $proposalKey => $headerInfo) {
if (
- !isset($groupedRows[$proposalKey]) ||
- !isset($headerInfo['subHeaders']) ||
- !is_array($headerInfo['subHeaders'])
+ ! isset($groupedRows[$proposalKey]) ||
+ ! isset($headerInfo['subHeaders']) ||
+ ! is_array($headerInfo['subHeaders'])
) {
continue;
}
$order = $headerInfo['subHeaders'];
- $rows = $groupedRows[$proposalKey];
+ $rows = $groupedRows[$proposalKey];
// Sort whole rows according to subth position in $order
usort($rows, function ($a, $b) use ($order) {
@@ -1945,12 +1970,12 @@ class LeadsController extends BaseController
private function renumberProposalKeys(array $input): array
{
- $result = [];
+ $result = [];
$counter = 1;
foreach ($input as $key => $value) {
if (strpos($key, 'Proposal') === 0) {
- $newKey = 'Proposal ' . $counter++;
+ $newKey = 'Proposal ' . $counter++;
$result[$newKey] = $value;
} else {
$result[$key] = $value;
@@ -1964,7 +1989,7 @@ class LeadsController extends BaseController
{
$id = $this->request->getGet('id');
// print_r($id); die;
- if (!empty($id)) {
+ if (! empty($id)) {
$this->leadInstallmentPaymentDetails->whereIn('id', $id)->set(['is_active' => 0])->update();
} else {
return $this->respond(['status' => false, 'message' => 'Could not be removed.'], 200);
@@ -1972,9 +1997,9 @@ class LeadsController extends BaseController
if ($this->request->getGet('lead_id')) {
$lead_id = $this->request->getGet('lead_id');
- $data = [
+ $data = [
'no_of_installment' => 0,
- 'is_installment' => 0
+ 'is_installment' => 0,
];
$this->leadsModel->where('id', $lead_id)->set($data)->update();
}
@@ -1984,7 +2009,6 @@ class LeadsController extends BaseController
//-----RFQ and QCR EXPORT------------------------------------------------------------------------------------------------
-
//export main route function
public function exportQCRandRFQ($lead_id, $type, $lead_form_type)
{
@@ -2015,7 +2039,7 @@ class LeadsController extends BaseController
if ($lead_file_path) {
$filePaths = [
['file_path' => $temp_file_path, 'sheets' => []],
- ['file_path' => $lead_file_path, 'sheets' => []]
+ ['file_path' => $lead_file_path, 'sheets' => []],
];
// $outputPath = dirname($temp_file_path) . '/' . 'merged_' . $temp_file_name;
$result = ExcelMergeHelper::mergeExcelFiles($filePaths, $temp_file_path);
@@ -2049,15 +2073,15 @@ class LeadsController extends BaseController
public function constructExcelToSaveTemp($lead_id, $type, $propsal_and_insurer = null)
{
helper('excel_util_helper');
- $rfq_data = $this->RFQModel->getRFQTableDataWithLeadIDAndType($lead_id, $type);
+ $rfq_data = $this->RFQModel->getRFQTableDataWithLeadIDAndType($lead_id, $type);
$is_placement = false;
- $length = 0;
+ $length = 0;
// dd($rfq_data, $lead_id, $type, $propsal_and_insurer);
// print_r($propsal_and_insurer); die;
// print_r($is_placement); die;
- $data = json_decode($rfq_data['json'], true);
+ $data = json_decode($rfq_data['json'], true);
$sheetName = 'Worksheet';
if ($type == 2) {
$sheetName = 'QCR';
@@ -2065,51 +2089,51 @@ class LeadsController extends BaseController
$data = $this->convertJsonForQCR($data, $type);
if ($propsal_and_insurer !== null) {
list($proposal_key, $insurer_key) = explode('-', $propsal_and_insurer, 2);
- $data = $this->transformProposelData($data, $proposal_key, $insurer_key);
- $is_placement = true;
- $sheetName = 'Placement';
+ $data = $this->transformProposelData($data, $proposal_key, $insurer_key);
+ $is_placement = true;
+ $sheetName = 'Placement';
}
} else if ($type == 1) {
$sheetName = 'RFQ';
- $data = $this->convertJsonForQCR($data, $type);
+ $data = $this->convertJsonForQCR($data, $type);
} // dd($data);
if ($rfq_data['lead_type'] == 1) {
if (in_array($rfq_data['policy_type_id'], [2, 3, 4, 5])) {
$lead_data = [
- 'Insured' => $rfq_data['client_name'],
- 'Policy Type' => $this->leadType[$rfq_data['lead_type']] ?? "",
+ 'Insured' => $rfq_data['client_name'],
+ 'Policy Type' => $this->leadType[$rfq_data['lead_type']] ?? "",
- 'No of Employees' => $rfq_data['incept_emp_count'],
- 'No of Dependents' => $rfq_data['incept_dept_count'],
- 'Total Lives' => $rfq_data['incept_no_of_lives'],
+ 'No of Employees' => $rfq_data['incept_emp_count'],
+ 'No of Dependents' => $rfq_data['incept_dept_count'],
+ 'Total Lives' => $rfq_data['incept_no_of_lives'],
- 'Period of Insurance ' => !empty($rfq_data['policy_start_date']) && !empty($rfq_data['policy_end_date']) ? date('d-m-Y', strtotime($rfq_data['policy_start_date'])) . ' to ' . date('d-m-Y', strtotime($rfq_data['policy_end_date'])) : "To be decided",
+ 'Period of Insurance ' => ! empty($rfq_data['policy_start_date']) && ! empty($rfq_data['policy_end_date']) ? date('d-m-Y', strtotime($rfq_data['policy_start_date'])) . ' to ' . date('d-m-Y', strtotime($rfq_data['policy_end_date'])) : "To be decided",
// 'Insurer' => $rfq_data['insurer_name'] ?? " - ",
// 'TPA' => $rfq_data['tpa_name'] ?? " - ",
// 'Policy Run Days' => $rfq_data['policy_run_days'],
];
} else if (in_array($rfq_data['policy_type_id'], [1, 6, 7])) {
$lead_data = [
- 'Insured' => $rfq_data['client_name'],
+ 'Insured' => $rfq_data['client_name'],
'No of Employees at Inception' => $rfq_data['incept_emp_count'],
// 'Total Sum Insured at Inception ' => $rfq_data['total_si_at_incept'],
- 'Policy Period' => !empty($rfq_data['policy_start_date']) && !empty($rfq_data['policy_end_date']) ? date('d-m-Y', strtotime($rfq_data['policy_start_date'])) . ' to ' . date('d-m-Y', strtotime($rfq_data['policy_end_date'])) : "To be decided",
+ 'Policy Period' => ! empty($rfq_data['policy_start_date']) && ! empty($rfq_data['policy_end_date']) ? date('d-m-Y', strtotime($rfq_data['policy_start_date'])) . ' to ' . date('d-m-Y', strtotime($rfq_data['policy_end_date'])) : "To be decided",
// 'Insurer' => $rfq_data['insurer_name'] ?? " - ",
// 'TPA' => $rfq_data['tpa_name'] ?? " - ",
- 'Policy Type' => $this->leadType[$rfq_data['lead_type']] ?? "",
+ 'Policy Type' => $this->leadType[$rfq_data['lead_type']] ?? "",
];
}
-
+
} else {
if (in_array($rfq_data['policy_type_id'], [2, 3, 4, 5])) {
- if($is_placement == true){
+ if ($is_placement == true) {
$lead_data = [
- 'Insured' => $rfq_data['client_name'],
- 'Policy Type' => $this->leadType[$rfq_data['lead_type']] ?? "",
+ 'Insured' => $rfq_data['client_name'],
+ 'Policy Type' => $this->leadType[$rfq_data['lead_type']] ?? "",
// 'No of Employees at Inception' => $rfq_data['incept_emp_count'],
// 'No of Dependents at Inception' => $rfq_data['incept_dept_count'],
@@ -2119,13 +2143,13 @@ class LeadsController extends BaseController
// 'No of Dependents at Expiry' => $rfq_data['exp_dept_count'],
// 'Total Lives at Expiry ' => $rfq_data['exp_no_of_lives'],
- 'No of Employees at Renewal' => $rfq_data['renewal_emp_count'],
+ 'No of Employees at Renewal' => $rfq_data['renewal_emp_count'],
'No of Dependents at Renewal' => $rfq_data['renewal_dept_count'],
- 'Total Lives at Renewal ' => $rfq_data['renewal_no_of_lives'],
+ 'Total Lives at Renewal ' => $rfq_data['renewal_no_of_lives'],
- 'Period of Insurance ' => !empty($rfq_data['policy_start_date']) && !empty($rfq_data['policy_end_date']) ? date('d-m-Y', strtotime($rfq_data['policy_start_date'])) . ' to ' . date('d-m-Y', strtotime($rfq_data['policy_end_date'])) : "To be decided",
- 'Insurer' => $rfq_data['insurer_name'] ?? " - ",
- 'TPA' => $rfq_data['tpa_name'] ?? " - ",
+ 'Period of Insurance ' => ! empty($rfq_data['policy_start_date']) && ! empty($rfq_data['policy_end_date']) ? date('d-m-Y', strtotime($rfq_data['policy_start_date'])) . ' to ' . date('d-m-Y', strtotime($rfq_data['policy_end_date'])) : "To be decided",
+ 'Insurer' => $rfq_data['insurer_name'] ?? " - ",
+ 'TPA' => $rfq_data['tpa_name'] ?? " - ",
// 'Policy Run Days' => $rfq_data['policy_run_days'],
// 'Inception Premium' => formatIndianCurrency($rfq_data['premium_at_inception']),
@@ -2136,52 +2160,52 @@ class LeadsController extends BaseController
// 'Incurred Claims Ratio' => $rfq_data['incurred_claims_ratio'] . " %",
// 'Earned Claims Ratio' => $rfq_data['earned_claims_ratio'] . " %",
];
- }else{
+ } else {
$lead_data = [
- 'Insured' => $rfq_data['client_name'],
- 'Policy Type' => $this->leadType[$rfq_data['lead_type']] ?? "",
+ 'Insured' => $rfq_data['client_name'],
+ 'Policy Type' => $this->leadType[$rfq_data['lead_type']] ?? "",
- 'No of Employees at Inception' => $is_placement ? '-' : $rfq_data['incept_emp_count'],
- 'No of Dependents at Inception' => $is_placement ? '-' : $rfq_data['incept_dept_count'],
- 'Total Lives at Inception ' => $is_placement ? '-' : $rfq_data['incept_no_of_lives'],
+ 'No of Employees at Inception' => $is_placement ? '-' : $rfq_data['incept_emp_count'],
+ 'No of Dependents at Inception' => $is_placement ? '-' : $rfq_data['incept_dept_count'],
+ 'Total Lives at Inception ' => $is_placement ? '-' : $rfq_data['incept_no_of_lives'],
- 'No of Employees at Expiry' => $is_placement ? '-' : $rfq_data['exp_emp_count'],
- 'No of Dependents at Expiry' => $is_placement ? '-' : $rfq_data['exp_dept_count'],
- 'Total Lives at Expiry ' => $is_placement ? '-' : $rfq_data['exp_no_of_lives'],
+ 'No of Employees at Expiry' => $is_placement ? '-' : $rfq_data['exp_emp_count'],
+ 'No of Dependents at Expiry' => $is_placement ? '-' : $rfq_data['exp_dept_count'],
+ 'Total Lives at Expiry ' => $is_placement ? '-' : $rfq_data['exp_no_of_lives'],
- 'No of Employees at Renewal' => $rfq_data['renewal_emp_count'],
- 'No of Dependents at Renewal' => $rfq_data['renewal_dept_count'],
- 'Total Lives at Renewal ' => $rfq_data['renewal_no_of_lives'],
+ 'No of Employees at Renewal' => $rfq_data['renewal_emp_count'],
+ 'No of Dependents at Renewal' => $rfq_data['renewal_dept_count'],
+ 'Total Lives at Renewal ' => $rfq_data['renewal_no_of_lives'],
- 'Period of Insurance ' => !empty($rfq_data['policy_start_date']) && !empty($rfq_data['policy_end_date'])
+ 'Period of Insurance ' => ! empty($rfq_data['policy_start_date']) && ! empty($rfq_data['policy_end_date'])
? date('d-m-Y', strtotime($rfq_data['policy_start_date'])) . ' to ' . date('d-m-Y', strtotime($rfq_data['policy_end_date']))
: "To be decided",
- 'Insurer' => $rfq_data['insurer_name'] ?? " - ",
- 'TPA' => $rfq_data['tpa_name'] ?? " - ",
+ 'Insurer' => $rfq_data['insurer_name'] ?? " - ",
+ 'TPA' => $rfq_data['tpa_name'] ?? " - ",
- 'Policy Run Days' => $is_placement ? '-' : $rfq_data['policy_run_days'],
- 'Inception Premium' => $is_placement ? '-' : formatIndianCurrency($rfq_data['premium_at_inception']),
- 'Premium as on (' . date('d-m-Y', strtotime($rfq_data['incurred_claims_date'])) . ')' => $is_placement ? '-' : formatIndianCurrency($rfq_data['premium_date']),
- 'Earned Premium' => $is_placement ? '-' : formatIndianCurrency(intval($rfq_data['earned_premium'])),
+ 'Policy Run Days' => $is_placement ? '-' : $rfq_data['policy_run_days'],
+ 'Inception Premium' => $is_placement ? '-' : formatIndianCurrency($rfq_data['premium_at_inception']),
+ 'Premium as on (' . date('d-m-Y', strtotime($rfq_data['incurred_claims_date'])) . ')' => $is_placement ? '-' : formatIndianCurrency($rfq_data['premium_date']),
+ 'Earned Premium' => $is_placement ? '-' : formatIndianCurrency(intval($rfq_data['earned_premium'])),
'Incurred Claims as on (' . date('d-m-Y', strtotime($rfq_data['incurred_claims_date'])) . ')' => $is_placement ? '-' : formatIndianCurrency($rfq_data['incurred_claims']),
- 'Annualised Claims' => $is_placement ? '-' : formatIndianCurrency(intval($rfq_data['annualised_claims'])),
- 'Incurred Claims Ratio' => $is_placement ? '-' : $rfq_data['incurred_claims_ratio'] . " %",
- 'Earned Claims Ratio' => $is_placement ? '-' : $rfq_data['earned_claims_ratio'] . " %",
+ 'Annualised Claims' => $is_placement ? '-' : formatIndianCurrency(intval($rfq_data['annualised_claims'])),
+ 'Incurred Claims Ratio' => $is_placement ? '-' : $rfq_data['incurred_claims_ratio'] . " %",
+ 'Earned Claims Ratio' => $is_placement ? '-' : $rfq_data['earned_claims_ratio'] . " %",
];
}
} else if (in_array($rfq_data['policy_type_id'], [1, 6, 7])) {
$lead_data = [
- 'Insured' => $rfq_data['client_name'],
- 'No of Employees at Inception' => $rfq_data['incept_emp_count'],
- 'Total Sum Insured at Inception' => $rfq_data['total_si_at_incept'],
- 'Premium at inception' => $rfq_data['premium_at_incept'],
- 'Policy Period' => !empty($rfq_data['policy_start_date']) && !empty($rfq_data['policy_end_date']) ? date('d-m-Y', strtotime($rfq_data['policy_start_date'])) . ' to ' . date('d-m-Y', strtotime($rfq_data['policy_end_date'])) : "To be decided",
- 'Policy Type' => $this->leadType[$rfq_data['lead_type']] ?? "",
- 'Existing Insurer' => $rfq_data['insurer_name'],
- 'No of Employees at Renewal' => $rfq_data['renewal_emp_count'],
- 'Total Sum Insured at Renewal' => $rfq_data['total_si_at_renewal'],
+ 'Insured' => $rfq_data['client_name'],
+ 'No of Employees at Inception' => $rfq_data['incept_emp_count'],
+ 'Total Sum Insured at Inception' => $rfq_data['total_si_at_incept'],
+ 'Premium at inception' => $rfq_data['premium_at_incept'],
+ 'Policy Period' => ! empty($rfq_data['policy_start_date']) && ! empty($rfq_data['policy_end_date']) ? date('d-m-Y', strtotime($rfq_data['policy_start_date'])) . ' to ' . date('d-m-Y', strtotime($rfq_data['policy_end_date'])) : "To be decided",
+ 'Policy Type' => $this->leadType[$rfq_data['lead_type']] ?? "",
+ 'Existing Insurer' => $rfq_data['insurer_name'],
+ 'No of Employees at Renewal' => $rfq_data['renewal_emp_count'],
+ 'Total Sum Insured at Renewal' => $rfq_data['total_si_at_renewal'],
'Claims Experience for last 3 years' => "Mentioned in Claims sheet",
// 'Insurer' => $rfq_data['insurer_name'] ?? " - ",
// 'TPA' => $rfq_data['tpa_name'] ?? " - ",
@@ -2191,12 +2215,10 @@ class LeadsController extends BaseController
}
// print_r($lead_data); die;
-
$spreadsheet = new Spreadsheet();
- $sheet = $spreadsheet->getActiveSheet();
+ $sheet = $spreadsheet->getActiveSheet();
$sheet->setTitle($sheetName);
-
// Start with lead_data at the top
$rowNumber = 1;
@@ -2204,13 +2226,13 @@ class LeadsController extends BaseController
// $sheet->mergeCells($mergeRange1);
$sheet->setCellValue("A{$rowNumber}", "Nhance India Insurance Broking Pvt Ltd");
$sheet->getStyle("A{$rowNumber}")->applyFromArray([
- 'font' => [
+ 'font' => [
'bold' => true,
- 'size' => 23
+ 'size' => 23,
],
'alignment' => [
'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
- 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
+ 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
],
]);
@@ -2271,22 +2293,22 @@ class LeadsController extends BaseController
$sheet->setCellValue("A{$rowNumber}", "Details of Coverage");
$sheet->getStyle("A{$rowNumber}")->applyFromArray([
- 'font' => [
+ 'font' => [
'bold' => true,
],
- 'fill' => [
- 'fillType' => Fill::FILL_SOLID,
+ 'fill' => [
+ 'fillType' => Fill::FILL_SOLID,
'startColor' => ['rgb' => 'ADD8E6'],
],
'borders' => [
'allBorders' => [
'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
- 'color' => ['argb' => 'FF000000'], // Black color
+ 'color' => ['argb' => 'FF000000'], // Black color
],
],
]);
- if($type == 2){
+ if ($type == 2) {
$subheader_count = array_sum(
array_map(
fn($header) => count(array_filter(
@@ -2296,7 +2318,7 @@ class LeadsController extends BaseController
$data['table_data']['headers']
)
);
- }else{
+ } else {
$subheader_count = array_sum(array_map(fn($header) => count($header['subHeaders']), $data['table_data']['headers']));
}
@@ -2305,7 +2327,7 @@ class LeadsController extends BaseController
}
$headerCount = count($data['table_data']['headers']);
- $lastColumn = Coordinate::stringFromColumnIndex($subheader_count);
+ $lastColumn = Coordinate::stringFromColumnIndex($subheader_count);
// dd( $headerCount, $lastColumn);
// Merge cells from A to the last column
@@ -2315,14 +2337,14 @@ class LeadsController extends BaseController
'borders' => [
'allBorders' => [
'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
- 'color' => ['argb' => 'FF000000'], // Black color
+ 'color' => ['argb' => 'FF000000'], // Black color
],
],
]);
$sheet->mergeCells($mergeRange);
$rowNumber_for_remove_quote_asked = $rowNumber;
- $rowNumber = $rowNumber + 1;
+ $rowNumber = $rowNumber + 1;
if ($type == 2) {
$subHeaderRow = $rowNumber + 1;
@@ -2331,13 +2353,13 @@ class LeadsController extends BaseController
$subHeaderRow = $rowNumber + 1;
}
- $columnLetter = 'A';
+ $columnLetter = 'A';
$header_actual_count = 0;
- $headerIndex = 0;
+ $headerIndex = 0;
foreach ($headers as $header) {
// Kint::dump($header);
- if($is_placement == true){
+ if ($is_placement == true) {
//for placement proposal only
$nxt_ro = $rowNumber + 1;
$sheet->mergeCells("C{$rowNumber}:C{$nxt_ro}");
@@ -2346,13 +2368,13 @@ class LeadsController extends BaseController
if (in_array($header['parentHeader'], ['Item Key', 'Action'])) {
continue;
}
-
- if (!in_array($header['parentHeader'], ['Item Key', 'Action', 'Sno', 'Particulars'])) {
+
+ if (! in_array($header['parentHeader'], ['Item Key', 'Action', 'Sno', 'Particulars'])) {
$header_actual_count++;
- //Quote asked not showed in the QCR excel so some proposel has only one Quote Asked, So that case avoid the proposel name
+ //Quote asked not showed in the QCR excel so some proposel has only one Quote Asked, So that case avoid the proposel name
$subHeaderCount = count($header['subHeaders'] ?? []) ?? 0;
- if($subHeaderCount <= 1 && $type == 2 && $is_placement == false){
+ if ($subHeaderCount <= 1 && $type == 2 && $is_placement == false) {
// print_rr($header);
continue;
}
@@ -2376,33 +2398,33 @@ class LeadsController extends BaseController
}
$startColumn = $columnLetter; // Start of the current header range
- if($type == 2){
- $subHeaderCount = count(array_filter($header['subHeaders'], function($subHeader) {
+ if ($type == 2) {
+ $subHeaderCount = count(array_filter($header['subHeaders'], function ($subHeader) {
return $subHeader !== "Quote Asked";
}));
- }else{
+ } else {
$subHeaderCount = count($header['subHeaders']); // Number of subheaders for this parent header
}
// Set parent header value
- if ($is_placement == true && !in_array($header['parentHeader'], ['Particulars', 'S.No.'])) {
+ if ($is_placement == true && ! in_array($header['parentHeader'], ['Particulars', 'S.No.'])) {
$sheet->setCellValue("{$startColumn}{$rowNumber}", "Terms");
} else {
- if(in_array($header['parentHeader'], ["Existing Renewal", "Existing Rollover"])){
+ if (in_array($header['parentHeader'], ["Existing Renewal", "Existing Rollover"])) {
$sheet->setCellValue("{$startColumn}{$rowNumber}", "Existing Terms");
- }else if(in_array($header['parentHeader'], ["Particulars", "S.No."])){
+ } else if (in_array($header['parentHeader'], ["Particulars", "S.No."])) {
$sheet->setCellValue("{$startColumn}{$rowNumber}", $header['parentHeader']);
- }else{
+ } else {
$headerIndex = $headerIndex + 1;
$sheet->setCellValue("{$startColumn}{$rowNumber}", "Proposal Terms " . $headerIndex);
}
}
-
+
$sheet->getStyle("{$startColumn}{$rowNumber}")->applyFromArray([
- 'font' => ['bold' => true],
+ 'font' => ['bold' => true],
'alignment' => [
'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
- 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
+ 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
],
]);
@@ -2417,7 +2439,7 @@ class LeadsController extends BaseController
// Add subheaders
foreach ($header['subHeaders'] as $subHeader) {
- if($type == 2 && in_array($subHeader, ['Quote Asked'])){
+ if ($type == 2 && in_array($subHeader, ['Quote Asked'])) {
continue;
}
@@ -2433,23 +2455,23 @@ class LeadsController extends BaseController
if ($is_placement == false) {
$sheet->getStyle("{$columnLetter}{$subHeaderRow}")->applyFromArray([
- 'font' => ['bold' => true],
+ 'font' => ['bold' => true],
'alignment' => [
'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
- 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
+ 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
],
]);
}
$columnLetter++; // Move to the next column for subheaders
- // Kint::dump($subHeader);
+ // Kint::dump($subHeader);
$length++;
}
}
-
- if($header_actual_count == 1 && $type == 1){
+
+ if ($header_actual_count == 1 && $type == 1) {
$sheet->getColumnDimension('B')->setWidth(80);
- }else{
+ } else {
$sheet->getColumnDimension('B')->setWidth(35);
}
@@ -2460,13 +2482,13 @@ class LeadsController extends BaseController
'borders' => [
'allBorders' => [
'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
- 'color' => ['argb' => 'FF000000'], // Black color
+ 'color' => ['argb' => 'FF000000'], // Black color
],
],
]);
- // Increase row height for headers and subheaders
- $sheet->getRowDimension($rowNumber)->setRowHeight(25); // Header row height
+ // Increase row height for headers and subheaders
+ $sheet->getRowDimension($rowNumber)->setRowHeight(25); // Header row height
$sheet->getRowDimension($subHeaderRow)->setRowHeight(20); // Subheader row height
if ($is_placement == true) {
@@ -2476,8 +2498,8 @@ class LeadsController extends BaseController
}
// dd($rowNumber);
- $column_data = $data['table_data']['data'];
- $serial_no = 1;
+ $column_data = $data['table_data']['data'];
+ $serial_no = 1;
$maxColumnWidths = [];
// Add table data rows
@@ -2488,7 +2510,7 @@ class LeadsController extends BaseController
continue;
}
- if($type == 2 && in_array($cellData['subth'], ['Quote Asked'])){
+ if ($type == 2 && in_array($cellData['subth'], ['Quote Asked'])) {
continue;
}
@@ -2505,26 +2527,26 @@ class LeadsController extends BaseController
}
$prevColumn2 = $this->getPreviousColumn($columnLetter);
- $dataRange = "A" . ($subHeaderRow + 1) . ":" . "{$prevColumn2}" . ($rowNumber - 1);
+ $dataRange = "A" . ($subHeaderRow + 1) . ":" . "{$prevColumn2}" . ($rowNumber - 1);
$sheet->getStyle($dataRange)->applyFromArray([
'borders' => [
'allBorders' => [
'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
- 'color' => ['argb' => 'FF000000'], // Black color
+ 'color' => ['argb' => 'FF000000'], // Black color
],
],
]);
- //premium data
+ //premium data
if ($type == 2) {
- if($is_placement == true){$columnLetterForPremium = "B";}else{$columnLetterForPremium = "B";}
+ if ($is_placement == true) {$columnLetterForPremium = "B";} else { $columnLetterForPremium = "B";}
$rowNumber += 2;
// Add premium data
// dd($data);
// $labelArray = ["Premium", "GST (%)", "GST Amount (₹)", "Total"];
- $labelArray = ["Premium", "GST Amount (₹)", "Total"];
+ $labelArray = ["Premium", "GST Amount (₹)", "Total"];
$premiumData = $data['premium_data']['data'];
// dd($premiumData);
// $premium = [$labelArray[0]];
@@ -2533,24 +2555,24 @@ class LeadsController extends BaseController
// $total = [$labelArray[2]];
// if($is_placement == true){
- $premium[] = $labelArray[0];
- $gstAmt[] = $labelArray[1];
- $total[] = $labelArray[2];
+ $premium[] = $labelArray[0];
+ $gstAmt[] = $labelArray[1];
+ $total[] = $labelArray[2];
// }
foreach ($premiumData as $proposal => $insurers) {
if ($proposal != 'Particulars') {
foreach ($insurers as $insurer => $values) {
- if($insurer == 'Quote Asked'){
+ if ($insurer == 'Quote Asked') {
// $premium[] = count($insurers ?? []) > 1 ? $labelArray[0] : "";
// $gst[] = "";
// $gstAmt[] = count($insurers ?? []) > 1 ? $labelArray[1] : "";
// $total[] = count($insurers ?? []) > 1 ? $labelArray[2] : "";
- }else{
+ } else {
$premium[] = formatIndianCurrency($values[$labelArray[0]]);
// $gst[] = $values[$labelArray[1]];
$gstAmt[] = formatIndianCurrency($values[$labelArray[1]]);
- $total[] = formatIndianCurrency($values[$labelArray[2]]);
+ $total[] = formatIndianCurrency($values[$labelArray[2]]);
}
}
}
@@ -2563,7 +2585,7 @@ class LeadsController extends BaseController
foreach ($rowData as $key => $value) {
$sheet->setCellValue("{$columnLetter}{$rowNumber}", $value);
if (in_array($value, $labelArray)) {
- $sheet->getStyle("{$columnLetter}{$rowNumber}")->applyFromArray(['font' => ['bold' => true,],]);
+ $sheet->getStyle("{$columnLetter}{$rowNumber}")->applyFromArray(['font' => ['bold' => true]]);
}
$columnLetter++;
}
@@ -2583,7 +2605,7 @@ class LeadsController extends BaseController
'borders' => [
'allBorders' => [
'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
- 'color' => ['argb' => 'FF000000'], // Black color
+ 'color' => ['argb' => 'FF000000'], // Black color
],
],
]);
@@ -2601,7 +2623,7 @@ class LeadsController extends BaseController
}
$company_name = $this->getPreviousColumn($columnLetter_img);
- $mergeRange1 = "A1:{$company_name}1";
+ $mergeRange1 = "A1:{$company_name}1";
$sheet->mergeCells($mergeRange1);
$rowCount = count($lead_data);
@@ -2612,7 +2634,7 @@ class LeadsController extends BaseController
'borders' => [
'allBorders' => [
'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
- 'color' => ['argb' => 'FF000000'], // Black color
+ 'color' => ['argb' => 'FF000000'], // Black color
],
],
]);
@@ -2622,13 +2644,13 @@ class LeadsController extends BaseController
$sheet->getRowDimension(1)->setRowHeight(50); // Adjust as needed
$drawing = new Drawing();
- $path = ROOTPATH . "public/assets/images/Nhance-Logo-Final.png"; // Use FCPATH for server path
+ $path = ROOTPATH . "public/assets/images/Nhance-Logo-Final.png"; // Use FCPATH for server path
$drawing->setPath($path);
$drawing->setCoordinates("{$columnLetter_img}1"); // Set position in column B
- $drawing->setHeight(35); // Adjust image
+ $drawing->setHeight(35); // Adjust image
$offsetX = 35;
$drawing->setOffsetX($offsetX); // Adjust horizontal offset
- $drawing->setOffsetY(10); // Adjust vertical offset
+ $drawing->setOffsetY(10); // Adjust vertical offset
$drawing->setWorksheet($sheet);
//end
@@ -2650,53 +2672,53 @@ class LeadsController extends BaseController
if ($matches) {
$startColumn = $matches[1]; // A
- $startRow = $matches[2]; // 1
- $endColumn = $matches[3]; // G
- $endRow = $matches[4]; // 75
+ $startRow = $matches[2]; // 1
+ $endColumn = $matches[3]; // G
+ $endRow = $matches[4]; // 75
// Convert column letter to index, reduce by 1, and convert back
$endColumnIndex = Coordinate::columnIndexFromString($endColumn) - 1;
- $newEndColumn = Coordinate::stringFromColumnIndex($endColumnIndex);
+ $newEndColumn = Coordinate::stringFromColumnIndex($endColumnIndex);
// Generate the new range (e.g., "A1:F75" instead of "A1:G75")
$newDataRange = "{$startColumn}{$startRow}:{$newEndColumn}{$endRow}";
// $sheet->getStyle($newDataRange)->getBorders()->getAllBorders()->setBorderStyle(Border::BORDER_THIN);
}
- $lastRow = count($lead_data) + 1;
+ $lastRow = count($lead_data) + 1;
$leadRange = "A1:{$columnLetter_img}{$lastRow}";
$sheet->getStyle($leadRange)->applyFromArray([
'borders' => [
'allBorders' => [
'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
- 'color' => ['argb' => 'FF000000'], // Black color
+ 'color' => ['argb' => 'FF000000'], // Black color
],
],
]);
// Set filename
- $string = ($type == 2) ? ($is_placement == true ? 'Placement' : 'QCR') : 'RFQ';
+ $string = ($type == 2) ? ($is_placement == true ? 'Placement' : 'QCR') : 'RFQ';
$current_year = date('Y');
- $next_year = $current_year + 1;
- $policy_year = "$current_year-$next_year";
+ $next_year = $current_year + 1;
+ $policy_year = "$current_year-$next_year";
- if (!empty($rfq_data['policy_end_date'])) {
+ if (! empty($rfq_data['policy_end_date'])) {
- $policy_expiry = strtotime($rfq_data['policy_end_date']);
+ $policy_expiry = strtotime($rfq_data['policy_end_date']);
$formatted_policy = date("d-m-Y", $policy_expiry);
- $filename = "{$rfq_data['client_name']}_{$rfq_data['policy_type']}_{$string}_" . $policy_year . '(Due On ' . $formatted_policy . ')' . '.xlsx';
+ $filename = "{$rfq_data['client_name']}_{$rfq_data['policy_type']}_{$string}_" . $policy_year . '(Due On ' . $formatted_policy . ')' . '.xlsx';
} else {
- $filename = "{$rfq_data['client_name']}_{$rfq_data['policy_type']}_{$string}_" . $policy_year . '_' . '.xlsx';
+ $filename = "{$rfq_data['client_name']}_{$rfq_data['policy_type']}_{$string}_" . $policy_year . '_' . '.xlsx';
}
//claim history new sheet;
- if (!empty($rfq_data['fin_years_claims'])) {
+ if (! empty($rfq_data['fin_years_claims'])) {
$claim_details = json_decode($rfq_data['fin_years_claims'], true) ?? [];
- if (!empty($claim_details['finyear'])) {
+ if (! empty($claim_details['finyear'])) {
// Get headers dynamically
$headers = array_map(function ($key) {
@@ -2709,9 +2731,9 @@ class LeadsController extends BaseController
$sheet = $spreadsheet->getActiveSheet();
// Set headers
- $sheet->fromArray($headers, NULL, 'A1');
+ $sheet->fromArray($headers, null, 'A1');
- // Apply background color and bold style to headers
+ // Apply background color and bold style to headers
$headerCellRange = 'A1:' . chr(64 + count($headers)) . '1'; // e.g., A1:G1
$sheet->getStyle($headerCellRange)->getFont()->setBold(true);
@@ -2725,8 +2747,8 @@ class LeadsController extends BaseController
foreach ($claim_details['finyear'] as $record) {
$col = 'A';
foreach ($record as $array_key => $value) {
- $label = ucwords(str_replace('_', ' ', ($value ?? "")));
- if(in_array($array_key, ['sum_insured', 'claim_amount', 'settled'])){
+ $label = ucwords(str_replace('_', ' ', ($value ?? "")));
+ if (in_array($array_key, ['sum_insured', 'claim_amount', 'settled'])) {
$label = formatIndianCurrency(intval($label));
}
$sheet->setCellValue($col . $row, $label);
@@ -2753,24 +2775,24 @@ class LeadsController extends BaseController
// $sheet->getStyle("A2:{$maxColLetter}{$row}")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
$maxColLetter = chr(64 + count($headers));
- $dataRange = "A1:{$maxColLetter}" . ($row - 1);
+ $dataRange = "A1:{$maxColLetter}" . ($row - 1);
$sheet->getStyle($dataRange)->getAlignment()
->setWrapText(true)
->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER)
->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
- // Optional: Make row height auto (helps when wrap text is on)
- for ($i = 2; $i < $row; $i++) {
- $sheet->getRowDimension($i)->setRowHeight(-1);
- }
+ // Optional: Make row height auto (helps when wrap text is on)
+ for ($i = 2; $i < $row; $i++) {
+ $sheet->getRowDimension($i)->setRowHeight(-1);
+ }
- }
- }
+ }
+ }
// Save to temporary location
$uploadFilePath = WRITEPATH . 'tmp/' . $filename;
- $writer = new Xlsx($spreadsheet);
+ $writer = new Xlsx($spreadsheet);
$writer->save($uploadFilePath);
return [
@@ -2792,21 +2814,21 @@ class LeadsController extends BaseController
public function calculateMembersDemography($params, $returnType = null)
{
- $lead_id = $params['lead_id'];
- $lead_data = $this->leadsModel->find((int)$lead_id);
+ $lead_id = $params['lead_id'];
+ $lead_data = $this->leadsModel->find((int) $lead_id);
$file_name_with_path = WRITEPATH . "/uploads/lead_files/" . $lead_data['file_name'];
- if (!$lead_data) {
+ if (! $lead_data) {
return ['status' => 'failed', 'message' => 'Opportunity data not found'];
}
- try{
+ try {
if ($lead_data['file_name']) {
// $file_name_with_path = WRITEPATH . "/uploads/lead_files/NonPrintableCharacters.xlsx";
//check physical file
- if (!file_exists($file_name_with_path)) {
- //file not found update status and reason
+ if (! file_exists($file_name_with_path)) {
+ //file not found update status and reason
$message = "Lead Physcial file not found";
// echo $message;
$this->myLogger->logme('error', ($message . ' for file ' . $file_name_with_path));
@@ -2816,28 +2838,27 @@ class LeadsController extends BaseController
$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file_name_with_path);
//get members data
- $members_sheet = $spreadsheet->getSheet(0);
+ $members_sheet = $spreadsheet->getSheet(0);
$highestRowAndColumn = $members_sheet->getHighestRowAndColumn();
// dd($highestRowAndColumn);
$uncleaned_members = $members_sheet->rangeToArray('A1:' . $highestRowAndColumn['column'] . $highestRowAndColumn['row']);
- $members = ExcelSanitizeHelper::sanitizeArrayData($uncleaned_members);
+ $members = ExcelSanitizeHelper::sanitizeArrayData($uncleaned_members);
//get age band data
- $age_band_sheet = $spreadsheet->getSheet(1);
+ $age_band_sheet = $spreadsheet->getSheet(1);
$highestRowAndColumn = $age_band_sheet->getHighestRowAndColumn();
- $age_band_data = $age_band_sheet->rangeToArray('A1:' . $highestRowAndColumn['column'] . $highestRowAndColumn['row']);
+ $age_band_data = $age_band_sheet->rangeToArray('A1:' . $highestRowAndColumn['column'] . $highestRowAndColumn['row']);
-
- //check age or dob column
+ //check age or dob column
$members_heading = $members[0];
- $available_col = null;
- $col_index = null;
+ $available_col = null;
+ $col_index = null;
if (in_array('age', array_map('strtolower', $members_heading))) {
$available_col = 'age';
- $col_index = array_search('age', array_map('strtolower', $members_heading));
+ $col_index = array_search('age', array_map('strtolower', $members_heading));
} elseif (in_array('dob', array_map('strtolower', $members_heading))) {
$available_col = 'dob';
- $col_index = array_search('dob', array_map('strtolower', $members_heading));
+ $col_index = array_search('dob', array_map('strtolower', $members_heading));
}
if ($available_col == null) {
@@ -2853,12 +2874,11 @@ class LeadsController extends BaseController
}
//for this to view the demography in the RFQ and QCR page to using internal
- if($returnType == "internal"){
+ if ($returnType == "internal") {
return ['data' => $classifiers];
// print_rr($classifiers); die;
}
-
try {
$result = $this->generateClassifierSpreadsheet($classifiers, WRITEPATH . 'uploads/lead_files/');
if ($result['success']) {
@@ -2868,9 +2888,9 @@ class LeadsController extends BaseController
echo "Filename: " . $result['filename'] . "\n";
$filePaths = [
['file_path' => WRITEPATH . 'uploads/lead_files/' . $lead_data['file_name'], 'sheets' => [0, 1]],
- ['file_path' => WRITEPATH . '/uploads/lead_files/' . $result['filename'], 'sheets' => []],
+ ['file_path' => WRITEPATH . '/uploads/lead_files/' . $result['filename'], 'sheets' => []],
];
- $outputPath = WRITEPATH . 'uploads/lead_files/' . $lead_data['file_name'];
+ $outputPath = WRITEPATH . 'uploads/lead_files/' . $lead_data['file_name'];
$result_merge = ExcelMergeHelper::mergeExcelFiles($filePaths, $outputPath);
if ($result_merge) {
// Call the delete function after the file is successfully created
@@ -2891,8 +2911,8 @@ class LeadsController extends BaseController
$this->myLogger->logme('error', (' no file found ' . $file_name_with_path));
return ['status' => 'failed', 'message' => 'no file found'];
}
-
- }catch(Exception $e){
+
+ } catch (Exception $e) {
$this->myLogger->logme("error", "Exception: " . $e->getMessage() . " --- Line: " . $e->getLine() . " --- Trace: " . $e->getTraceAsString());
return ['status' => 'fail', 'error' => "File not found / Wrong file"];
}
@@ -2902,10 +2922,10 @@ class LeadsController extends BaseController
{
$first_loop = 0;
// $col_index_si = array_search('si enhancement', array_map('strtolower', $members_heading));
- $col_index_si = array_search('si', array_map('strtolower', $members_heading));
+ $col_index_si = array_search('si', array_map('strtolower', $members_heading));
$col_index_relationship = array_search('relationship', array_map('strtolower', $members_heading));
- $relations = [];
- $si_amt = ['general']; // Initialize with 'general' as per first loop condition
+ $relations = [];
+ $si_amt = ['general']; // Initialize with 'general' as per first loop condition
// First pass - collect unique relations and SI amounts
foreach ($members as $member) {
@@ -2917,11 +2937,11 @@ class LeadsController extends BaseController
continue;
}
- if (!in_array($member[$col_index_relationship], $relations) && $member[$col_index_relationship] != null) {
+ if (! in_array($member[$col_index_relationship], $relations) && $member[$col_index_relationship] != null) {
$relations[] = $member[$col_index_relationship];
}
- if (!in_array($member[$col_index_si], $si_amt) && $member[$col_index_si] != null) {
+ if (! in_array($member[$col_index_si], $si_amt) && $member[$col_index_si] != null) {
$si_amt[] = $member[$col_index_si];
}
}
@@ -2960,14 +2980,15 @@ class LeadsController extends BaseController
// Get age
$age = $this->getAge($available_col, $member, $col_index);
-
- $relation = $member[$col_index_relationship];
+ $relation = $member[$col_index_relationship];
$member_si = $member[$col_index_si];
// Find the correct age band (only once per member)
$found_band = false;
foreach ($age_band_data as $age_bands) {
- if ($found_band) break;
+ if ($found_band) {
+ break;
+ }
foreach ($age_bands as $age_band) {
//get Min and Max Age
@@ -3010,21 +3031,21 @@ class LeadsController extends BaseController
public function generateClassifierSpreadsheet($classifiers, $outputDir = 'exports')
{
- if (!file_exists($outputDir)) {
- if (!mkdir($outputDir, 0755, true)) {
+ if (! file_exists($outputDir)) {
+ if (! mkdir($outputDir, 0755, true)) {
throw new Exception("Failed to create directory: $outputDir");
}
}
// Check if directory is writable
- if (!is_writable($outputDir)) {
+ if (! is_writable($outputDir)) {
throw new Exception("Directory is not writable: $outputDir");
}
// Generate unique filename
$timestamp = date('Y-m-d_His');
- $filename = "member_classification_{$timestamp}.xlsx";
- $filepath = $outputDir . DIRECTORY_SEPARATOR . $filename;
+ $filename = "member_classification_{$timestamp}.xlsx";
+ $filepath = $outputDir . DIRECTORY_SEPARATOR . $filename;
// Check if file already exists (shouldn't happen with timestamp, but just in case)
if (file_exists($filepath)) {
@@ -3037,12 +3058,12 @@ class LeadsController extends BaseController
}
$spreadsheet = new Spreadsheet();
- $sheet = $spreadsheet->getActiveSheet();
+ $sheet = $spreadsheet->getActiveSheet();
$sheet->setTitle('Demography_Data');
// Get all age bands
$age_bands = array_keys(reset($classifiers['general']));
- array_pop($age_bands); // Remove 'Grand Total'
+ array_pop($age_bands); // Remove 'Grand Total'
$age_bands[] = 'Grand Total'; // Add it back at the end
$currentRow = 5; // Start from row 5 to match the example
@@ -3054,7 +3075,7 @@ class LeadsController extends BaseController
// Style section header
$sheet->getStyle('B' . $currentRow)->applyFromArray([
- 'font' => ['bold' => true, 'size' => 14],
+ 'font' => ['bold' => true, 'size' => 14],
'alignment' => ['horizontal' => Alignment::HORIZONTAL_CENTER],
]);
@@ -3069,14 +3090,14 @@ class LeadsController extends BaseController
}
// Style headers
- $lastCol = chr(ord('B') + count($age_bands));
+ $lastCol = chr(ord('B') + count($age_bands));
$headerRange = 'B' . $currentRow . ':' . $lastCol . $currentRow;
$sheet->getStyle($headerRange)->applyFromArray([
- 'font' => ['bold' => true],
- 'borders' => [
+ 'font' => ['bold' => true],
+ 'borders' => [
'allBorders' => [
'borderStyle' => Border::BORDER_THIN,
- 'color' => ['rgb' => '000000'],
+ 'color' => ['rgb' => '000000'],
],
],
'alignment' => [
@@ -3100,10 +3121,10 @@ class LeadsController extends BaseController
// Style data row
$dataRange = 'B' . $currentRow . ':' . $lastCol . $currentRow;
$sheet->getStyle($dataRange)->applyFromArray([
- 'borders' => [
+ 'borders' => [
'allBorders' => [
'borderStyle' => Border::BORDER_THIN,
- 'color' => ['rgb' => '000000'],
+ 'color' => ['rgb' => '000000'],
],
],
'alignment' => [
@@ -3126,15 +3147,15 @@ class LeadsController extends BaseController
// Style Grand Total row
$totalRange = 'B' . $currentRow . ':' . $lastCol . $currentRow;
$sheet->getStyle($totalRange)->applyFromArray([
- 'font' => ['bold' => true],
- 'borders' => [
+ 'font' => ['bold' => true],
+ 'borders' => [
'allBorders' => [
'borderStyle' => Border::BORDER_THIN,
- 'color' => ['rgb' => '000000'],
+ 'color' => ['rgb' => '000000'],
],
],
- 'fill' => [
- 'fillType' => Fill::FILL_SOLID,
+ 'fill' => [
+ 'fillType' => Fill::FILL_SOLID,
'startColor' => ['rgb' => 'F2F2F2'],
],
'alignment' => [
@@ -3162,23 +3183,23 @@ class LeadsController extends BaseController
$writer->save($filepath);
// Verify file was created successfully
- if (!file_exists($filepath)) {
+ if (! file_exists($filepath)) {
throw new Exception("Failed to create file: $filepath");
}
// Return the file info after creation
$response = [
- 'success' => true,
+ 'success' => true,
'filepath' => $filepath,
'filename' => $filename,
- 'fullpath' => realpath($filepath)
+ 'fullpath' => realpath($filepath),
];
return $response;
} catch (Exception $e) {
return [
'success' => false,
- 'error' => $e->getMessage()
+ 'error' => $e->getMessage(),
];
}
}
@@ -3191,18 +3212,18 @@ class LeadsController extends BaseController
unlink($filePath); // Delete the file
return [
'success' => true,
- 'message' => "File deleted successfully"
+ 'message' => "File deleted successfully",
];
} else {
return [
'success' => false,
- 'message' => "File does not exist"
+ 'message' => "File does not exist",
];
}
} catch (Exception $e) {
return [
'success' => false,
- 'error' => $e->getMessage()
+ 'error' => $e->getMessage(),
];
}
}
@@ -3216,7 +3237,7 @@ class LeadsController extends BaseController
if ($dob == 'DOB') {
return;
}
- $dobDate = \DateTime::createFromFormat('d-M-Y', $dob);
+ $dobDate = \DateTime::createFromFormat('d-M-Y', $dob);
$currentDate = new \DateTime();
if ($dobDate == false) {
$this->myLogger->logme('error', $dob . 'is not valid');
@@ -3232,18 +3253,17 @@ class LeadsController extends BaseController
$age_band = trim($age_band);
// Parse age range
if (strpos($age_band, '-') === false) {
- $min_age = (int)filter_var($age_band, FILTER_SANITIZE_NUMBER_INT);
+ $min_age = (int) filter_var($age_band, FILTER_SANITIZE_NUMBER_INT);
$max_age = PHP_INT_MAX;
} else {
- $parts = explode("-", $age_band);
- $min_age = (int)$parts[0];
- $max_age = (int)$parts[1];
+ $parts = explode("-", $age_band);
+ $min_age = (int) $parts[0];
+ $max_age = (int) $parts[1];
}
- return array($min_age, $max_age);
+ return [$min_age, $max_age];
}
-
//this funciton for send mail to insurer and client with either RFQ/QCR
public function sendMailWithAttachement()
{
@@ -3254,33 +3274,33 @@ class LeadsController extends BaseController
// print_r($params); die;
- $lead_id = (int)$params['lead_id'];
- $file_type = $params['file_type']; //rfq or qcr
- $recipient_type = $params['recipient_type']; //insurer or client or internal or placement
- $recipient_mail = $params['recipient_mail']; // - only primary key of contacts
- $recipient_mail = json_decode($params['recipient_mail'], true); // - only primary key of contacts
+ $lead_id = (int) $params['lead_id'];
+ $file_type = $params['file_type']; //rfq or qcr
+ $recipient_type = $params['recipient_type']; //insurer or client or internal or placement
+ $recipient_mail = $params['recipient_mail']; // - only primary key of contacts
+ $recipient_mail = json_decode($params['recipient_mail'], true); // - only primary key of contacts
$propsal_and_insurer = isset($params['proposal_insurer']) ? $params['proposal_insurer'] : null;
- $mail_content = $params['mail_content'];
- $mail_subject = $params['subject'];
+ $mail_content = $params['mail_content'];
+ $mail_subject = $params['subject'];
$attachment_file_ids = $params['selected_attachment_files'];
$from_mail = getenv('email.fromEmail');
if (in_array($recipient_type, ['placement', 'insurer', 'internal'])) {
- $from_mail = "im@nhanceindia.in";
+ $from_mail = getenv('LEAD_INSURER_FROM_MAIL_ID');
} else if (in_array($recipient_type, ['client'])) {
- $from_mail = "bs@nhanceindia.in";
+ $from_mail = getenv('LEAD_CLIENT_FROM_MAIL_ID');
}
- $type = "";
+ $type = "";
$insurer_ids = null;
if (in_array($recipient_type, ['placement'])) {
$type = "placement";
} else if (in_array($recipient_type, ['insurer'])) {
- $type = "insurer";
+ $type = "insurer";
$insurer_ids = json_decode($params['insurer_ids'] ?? "", true) ?? [];
- }else if (in_array($recipient_type, ['internal'])) {
+ } else if (in_array($recipient_type, ['internal'])) {
$type = "internal";
- }else if (in_array($recipient_type, ['client'])) {
+ } else if (in_array($recipient_type, ['client'])) {
$type = "client";
}
@@ -3288,32 +3308,32 @@ class LeadsController extends BaseController
if ($recipient_type === 'placement') {
- $lead_data = $this->leadsModel->find((int)$lead_id);
+ $lead_data = $this->leadsModel->find((int) $lead_id);
$data = [];
- if (!empty($params['policy_start_date'])) {
+ if (! empty($params['policy_start_date'])) {
$converted_start = change_date_format($params['policy_start_date']); // converts to Y-m-d
if ($converted_start !== $lead_data['policy_start_date']) {
$data['policy_start_date'] = $converted_start;
}
}
- if (!empty($params['policy_end_date'])) {
+ if (! empty($params['policy_end_date'])) {
$converted_end = change_date_format($params['policy_end_date']); // converts to Y-m-d
if ($converted_end !== $lead_data['policy_end_date']) {
$data['policy_end_date'] = $converted_end;
}
}
- if (!empty($data)) {
+ if (! empty($data)) {
$this->leadsModel->update($lead_id, $data);
}
}
$result_data = [];
// dd($recipient_mail);
- if ($recipient_type == 'insurer' && (!is_array($recipient_mail) || count($recipient_mail) == 0)) {
+ if ($recipient_type == 'insurer' && (! is_array($recipient_mail) || count($recipient_mail) == 0)) {
return $this->respond(['status' => 'failed', 'code' => 400, 'data' => '', 'messgae' => 'Recipient mail not found ! '], 200);
}
// dd();
@@ -3328,16 +3348,15 @@ class LeadsController extends BaseController
// log_message('error', 'Lead Data' . json_encode($lead_data));
// print_r($lead_data ); die;
- $cc_mails = [];
+ $cc_mails = [];
$bcc_mails = [];
//get CC Mails
if ($recipient_type == 'internal' || $recipient_type == 'insurer' || $recipient_type == 'client') {
- $cc_data = isset($params['cc']) ? $params['cc'] : "";
+ $cc_data = isset($params['cc']) ? $params['cc'] : "";
$param_cc_mail = json_decode($cc_data, true);
-
if (isset($param_cc_mail) && is_array($param_cc_mail) && count($param_cc_mail) > 0) {
// Fetch user data where ID is in the param_cc_mail array
$userData = $this->userModel
@@ -3362,13 +3381,20 @@ class LeadsController extends BaseController
// return $this->respond(['status' => 'failed','code' => 400,'data' => '','message' => 'CC mail not found!'], 200);
}
} else if ($recipient_type == 'placement') {
- $cc_mails = isset($params['cc']) ? json_decode($params['cc'], true) : "";
+
+ if(isset($params['cc']) && !empty($params['cc'])) {
+ if(is_array($params['cc'])) {
+ $cc_mails = $params['cc'];
+ } else {
+ $cc_mails = json_decode($params['cc'], true);
+ }
+ }
}
//get BCC Mails
if ($recipient_type == 'insurer' || $recipient_type == 'client') {
- $bcc_data = isset($params['bcc']) ? $params['bcc'] : "";
+ $bcc_data = isset($params['bcc']) ? $params['bcc'] : "";
$param_bcc_mail = json_decode($bcc_data, true);
if (isset($param_bcc_mail) && is_array($param_bcc_mail) && count($param_bcc_mail) > 0) {
@@ -3406,7 +3432,8 @@ class LeadsController extends BaseController
//get file path to attach
if ($lead_data["lead_form_type"] == 2) {
- $file_info = $this->constructNonEbExcelToSaveTemp($lead_id, ($file_type == 'rfq' ? 1 : 2), $propsal_and_insurer);
+ // For Non-EB, download RFQ/QCR file from Google Sheet (if configured)
+ $file_info = $this->downloadFileFromGoogleSheet($lead_data);
} else {
$file_info = $this->constructExcelToSaveTemp($lead_id, ($file_type == 'rfq' ? 1 : 2), $propsal_and_insurer);
}
@@ -3420,10 +3447,10 @@ class LeadsController extends BaseController
if ($lead_file_path) {
$filePaths = [
['file_path' => $temp_file_path, 'sheets' => []],
- ['file_path' => $lead_file_path, 'sheets' => []]
+ ['file_path' => $lead_file_path, 'sheets' => []],
];
- $outputPath = dirname($temp_file_path) . '/' . $temp_file_name;
- $result = ExcelMergeHelper::mergeExcelFiles($filePaths, $outputPath);
+ $outputPath = dirname($temp_file_path) . '/' . $temp_file_name;
+ $result = ExcelMergeHelper::mergeExcelFiles($filePaths, $outputPath);
// print_rr($result);
}
} else {
@@ -3441,21 +3468,24 @@ class LeadsController extends BaseController
$file_name = basename($result);
// Attacments part
- $attachments = [['fileName' => $file_name, 'filePath' => $file_path]];
+ $attachments = [['fileName' => $file_name, 'filePath' => $file_path]];
$other_attachments = $this->handleMultiFileAttachments($attachment_file_ids, $lead_id);
- $attachments = array_merge($attachments, $other_attachments);
+ $attachments = array_merge($attachments, $other_attachments);
// print_r($attachments); die;
//get recipient address
if ($recipient_type == 'insurer' || $recipient_type == 'placement') {
-
+
+ if(!is_array($recipient_mail)) {
+ $recipient_mail = [$recipient_mail];
+ }
$recipient_data = $this->levelContactModel
->where(['contact_type' => 'insurer', 'is_active' => 1])
->whereIn('id', $recipient_mail)
->findAll();
} else if ($recipient_type == 'client') {
- $mailIDS = explode(',', $params['contact_mail']);
+ $mailIDS = explode(',', $params['contact_mail']);
$recipient_data = [];
foreach ($mailIDS as $mail) {
$recipient_data[] = ['name' => $lead_data['contact_person_name'], 'email' => $mail];
@@ -3470,12 +3500,12 @@ class LeadsController extends BaseController
$original_message = '
Request for Quotation (RFQ) Dear {{RECIPIENT_NAME}}, We are reaching out to request a quotation for the following insurance coverage. Please review the details below and provide your quote at your earliest convenience.
RFQ Details Client name {{CLIENT_NAME}} Coverage Type {{POLICY_LONG_NAME}} Policy Start Date {{POLICY_START_DATE}} Policy Duration {{DURATION}}
Please note: Additional terms and details are included in the attachment for your reference.
Please feel free to reach out if you require any further information to prepare the quote. We look forward to receiving your proposal.
Best regards,
Nhance India Pvt Ltd
© Nhance India Pvt Ltd. All rights reserved.
';
//for mail content
- if (!empty($mail_content)) {
+ if (! empty($mail_content)) {
$original_message = $mail_content;
}
//for mail subject
- if (!empty($mail_subject)) {
+ if (! empty($mail_subject)) {
$subject = $mail_subject;
}
@@ -3484,10 +3514,10 @@ class LeadsController extends BaseController
if ($recipient_data) {
foreach ($recipient_data as $position => $recipient) {
- if ($recipient_type == 'insurer'){
+ if ($recipient_type == 'insurer') {
$common['common'] = $insurer_ids[$position] ?? null;
}
-
+
$message = $original_message;
$message = str_replace("{{RECIPIENT_NAME}}", $recipient['name'] != "" ? $recipient['name'] : " ", $message);
$message = str_replace("{{CLIENT_NAME}}", $lead_data['client_name'] != "" ? $lead_data['client_name'] : "", $message);
@@ -3496,7 +3526,7 @@ class LeadsController extends BaseController
$message = str_replace("{{DURATION}}", calculate_days_bw_dates($lead_data['policy_end_date'] ?? "", $lead_data['policy_start_date'] ?? "")->days, $message) ?? '--';
// print_rr($message);calculate_days_bw_dates
- $string = implode(", ", $cc_mails);
+ $string = implode(", ", $cc_mails);
$bcc_string = implode(", ", $bcc_mails);
$res = MailHelper::send_email(['from_mail' => $from_mail, 'mail' => $recipient['email'], 'cc' => $string, 'subject' => $subject, 'message' => $message, 'attachments' => $attachments, 'reply_to' => $reply_to, 'bcc' => $bcc_string, 'common' => $common]);
@@ -3505,10 +3535,10 @@ class LeadsController extends BaseController
}
}
- if($recipient_type == 'placement' && isset($params['acm_email']) && !empty($params['acm_email'])){
+ if ($recipient_type == 'placement' && isset($params['acm_email']) && ! empty($params['acm_email'])) {
$common['mail_type'] = "internal acm";
- $acm_mail_content = '
+ $acm_mail_content = '
Dear Sir,
The placement for the {{POLICY_TYPE}} policy pertaining to {{CLIENT_NAME}} has been successfully won.
Please proceed with the next steps accordingly.
@@ -3518,7 +3548,7 @@ class LeadsController extends BaseController
';
$acm_mail_content = $this->transformMailContent($lead_data, $acm_mail_content, $data['page_name'] = 'QCR');
- $res = MailHelper::send_email(['from_mail' => $from_mail, 'mail' => $params['acm_email'], 'subject' => $subject, 'message' => $acm_mail_content, 'attachments' => $attachments, 'common' => $common]);
+ $res = MailHelper::send_email(['from_mail' => $from_mail, 'mail' => $params['acm_email'], 'subject' => $subject, 'message' => $acm_mail_content, 'attachments' => $attachments, 'common' => $common]);
}
$is_placement = false;
@@ -3526,48 +3556,60 @@ class LeadsController extends BaseController
$is_placement = true;
- list($proposal_key, $insurer_key) = explode('-', $propsal_and_insurer, 2);
+ if(isset($propsal_and_insurer)) {
+
+ if (! empty($propsal_and_insurer[0])) {
+ $parts = explode('-', $propsal_and_insurer[0], 2);
+ $proposal_key = $parts[0] ?? null;
+ $insurer_key = $parts[1] ?? null;
+ } else {
+ $proposal_key = null;
+ $insurer_key = null;
+ }
+
+ }
+
$lead_update_data = [
- 'proposel_name' => $proposal_key,
- 'insurer_name' => $insurer_key,
- 'insurer' => $params['insurer_and_branch'],
+ 'proposel_name' => $proposal_key ?? null ,
+ 'insurer_name' => $insurer_key ?? null,
+ 'insurer' => $params['insurer_and_branch'] ?? null,
];
$data = [
- 'proposel_data' => json_encode($lead_update_data),
- 'status' => 'won',
- 'placement_date' => !empty($params['placement_date']) ? change_date_format($params['placement_date']) : null,
- 'payment_date' => !empty($params['payment_date']) ? change_date_format($params['payment_date']) : null,
- 'utr_no' => $params['utr_no'] ?? null,
- 'is_cd' => $params['is_cd'] ?? null,
- 'premium_amount' => $params['premium_amount'] ?? null,
- 'total_amount' => $params['total_amount'] ?? null,
- 'cd_amount' => $params['cd_amount'] ?? null,
+ 'proposel_data' => json_encode($lead_update_data),
+ 'status' => 'won',
+ 'placement_date' => ! empty($params['placement_date']) ? change_date_format($params['placement_date']) : null,
+ 'payment_date' => ! empty($params['payment_date']) ? change_date_format($params['payment_date']) : null,
+ 'utr_no' => $params['utr_no'] ?? null,
+ 'is_cd' => $params['is_cd'] ?? null,
+ 'premium_amount' => $params['premium_amount'] ?? null,
+ 'total_amount' => $params['total_amount'] ?? null,
+ 'cd_amount' => $params['cd_amount'] ?? null,
'no_of_installment' => $params['no_of_installment'] ?? null,
- 'is_installment' => $params['is_installment'] ?? null,
- 'acm_id' => $params['acm_pk'] ?? null,
+ 'is_installment' => $params['is_installment'] ?? null,
+ 'acm_id' => $params['acm_pk'] ?? null,
'agreed_percentage' => $params['agreed_percentage'] ?? null,
];
- if(isset($params['tpa_id']) && !empty($params['tpa_id'])){
+ if (isset($params['tpa_id']) && ! empty($params['tpa_id'])) {
list($tpaBranchId, $tpaId) = explode('-', $params['tpa_id']);
- $data['tpa_branch_id'] = $tpaBranchId;
- $data['tpa_id'] = $tpaId;
+ $data['tpa_branch_id'] = $tpaBranchId;
+ $data['tpa_id'] = $tpaId;
}
$this->leadsModel->where('id', $lead_id)->set($data)->update();
- if (isset($params['installments']) && !empty($params['installments'])) {
+ if (isset($params['installments']) && ! empty($params['installments'])) {
$installment_data = json_decode($params['installments'], true);
- if (!empty($installment_data)) {
+ if (! empty($installment_data)) {
foreach ($installment_data as $key => $value) {
// print_r($value);die
- $value['payment_date'] = !empty($value['payment_date']) && strtotime($value['payment_date'])
+ $value['payment_date'] = ! empty($value['payment_date']) && strtotime($value['payment_date'])
? date('Y/m/d', strtotime($value['payment_date']))
: null;
- if (isset($value['id']) && !empty($value['id'])) {
+ if (isset($value['id']) && ! empty($value['id'])) {
$this->leadInstallmentPaymentDetails->where('id', $value['id'])->set($value)->update();
} else {
$this->leadInstallmentPaymentDetails->insert($value);
@@ -3595,7 +3637,7 @@ class LeadsController extends BaseController
->update();
}
- //delete attachment file
+ //delete attachment file
unlink($file_path);
return $this->respond(['status' => 'success', 'code' => 200, 'data' => $result_data, 'is_placement' => $is_placement], 200);
}
@@ -3623,7 +3665,7 @@ class LeadsController extends BaseController
$data = $this->levelContactModel->getContactForRFQ($insurerId, $insurerBranchId);
- if (!empty($data)) {
+ if (! empty($data)) {
return $this->respond(['status' => true, 'data' => $data], 200);
} else {
return $this->respond(['status' => false, 'data' => $data, 'message' => 'No contacts were found for the selected insurer.'], 200);
@@ -3641,12 +3683,12 @@ class LeadsController extends BaseController
$defaultHeaders = [
[
'parentHeader' => 'Sno',
- 'subHeaders' => ['-']
+ 'subHeaders' => ['-'],
],
[
'parentHeader' => 'Particulars',
- 'subHeaders' => ['-']
- ]
+ 'subHeaders' => ['-'],
+ ],
];
// Add default headers to the result
@@ -3660,10 +3702,10 @@ class LeadsController extends BaseController
if ($subHeader === $insurer) {
$headerData[] = [
'parentHeader' => $header['parentHeader'],
- 'subHeaders' => [
- // 'Quote Asked', // Default value
- $subHeader // Matched insurer key
- ]
+ 'subHeaders' => [
+ // 'Quote Asked', // Default value
+ $subHeader, // Matched insurer key
+ ],
];
break;
}
@@ -3675,14 +3717,14 @@ class LeadsController extends BaseController
foreach ($data['table_data']['data'] as $entry) {
- $sno = $entry['SNO'];
- $items = $entry['items'];
+ $sno = $entry['SNO'];
+ $items = $entry['items'];
$dataEntry = $entry['data'];
$result = [
- "SNO" => $sno,
+ "SNO" => $sno,
"items" => $items,
- "data" => []
+ "data" => [],
];
foreach ($dataEntry as $item) {
@@ -3690,14 +3732,14 @@ class LeadsController extends BaseController
// Include Sno and Particulars by default
if (in_array($item['parentth'], ['Sno', 'Particulars'])) {
$result['data'][] = [
- "parentth" => $item['parentth'],
- "subth" => $item['subth'],
- "value" => $item['value'],
- "input_value" => $item['input_value']
+ "parentth" => $item['parentth'],
+ "subth" => $item['subth'],
+ "value" => $item['value'],
+ "input_value" => $item['input_value'],
];
}
- // Include Proposal with Quote Asked by default
+ // Include Proposal with Quote Asked by default
/* For proposel do not remove it */
// if ($item['parentth'] === $proposel && $item['subth'] === "Quote Asked") {
// $result['data'][] = [
@@ -3711,10 +3753,10 @@ class LeadsController extends BaseController
// Example of including matching specific proposals and insurers
if ($item['parentth'] === $proposel && $item['subth'] === $insurer) {
$result['data'][] = [
- "parentth" => $item['parentth'],
- "subth" => $item['subth'],
- "value" => $item['value'],
- "input_value" => $item['input_value']
+ "parentth" => $item['parentth'],
+ "subth" => $item['subth'],
+ "value" => $item['value'],
+ "input_value" => $item['input_value'],
];
}
}
@@ -3733,8 +3775,8 @@ class LeadsController extends BaseController
}
$data['table_data']['headers'] = $headerData;
- $data['table_data']['data'] = $columnData;
- $data['premium_data']['data'] = $premiumData;
+ $data['table_data']['data'] = $columnData;
+ $data['premium_data']['data'] = $premiumData;
return $data;
}
@@ -3788,7 +3830,6 @@ class LeadsController extends BaseController
}
}
-
foreach ($first_json['table_data']['data'] as &$item) {
$item['data'] = array_values(array_filter($item['data'], function ($entry) use ($insurer) {
return $entry['subth'] !== $insurer['display_name'];
@@ -3816,8 +3857,8 @@ class LeadsController extends BaseController
}
// Reindex arrays to maintain proper structure
- $first_json['table_data']['headers'] = array_values($first_json['table_data']['headers']);
- $first_json['table_data']['data'] = array_values($first_json['table_data']['data']);
+ $first_json['table_data']['headers'] = array_values($first_json['table_data']['headers']);
+ $first_json['table_data']['data'] = array_values($first_json['table_data']['data']);
$first_json['proposal_data']['over_all_column_data'] = array_map(function ($proposal) {
$proposal['insurers'] = array_values($proposal['insurers']);
return $proposal;
@@ -3848,7 +3889,6 @@ class LeadsController extends BaseController
// Ensure to unset the reference after the loop
unset($row);
-
// Remove insurers from Proposal Data key for RFQ
foreach ($first_json['proposal_data']['over_all_column_data'] as $key => &$proposal) {
if (isset($proposal['insurers'])) {
@@ -3869,13 +3909,12 @@ class LeadsController extends BaseController
//----- Featch Lead data and insert Client -------------------------------------------------------------------------------------------
-
public function featchLeadDataAndInsertClient($lead_id)
{
try {
$data = $this->leadsModel->where('leads.id', $lead_id)->where('leads.is_active', 1)->first();
- if (!$data) {
+ if (! $data) {
$this->myLogger->logme('featchLeadDataAndInsertClient', "Lead not found or inactive", ['lead_id' => $lead_id]);
return $this->respond(['status' => false, 'message' => 'Failed to create Client', 'data' => null], 200);
}
@@ -3885,10 +3924,10 @@ class LeadsController extends BaseController
if ($result) {
$policy_data = $this->clientPolicyModel->where('client_id', $result)->where('is_active', 1)->first();
return $this->respond([
- 'status' => true,
- 'message' => 'New Client created successfully',
- 'client_id' => $result,
- 'data' => $data,
+ 'status' => true,
+ 'message' => 'New Client created successfully',
+ 'client_id' => $result,
+ 'data' => $data,
'client_policy_id' => $policy_data['id'] ?? null,
], 200);
}
@@ -3905,7 +3944,7 @@ class LeadsController extends BaseController
{
try {
$client_data = $this->prepareClientData($data);
- $client_id = $this->clientModel->insert($client_data);
+ $client_id = $this->clientModel->insert($client_data);
if ($client_id) {
$this->createClientBranchAndContactWithLeadData($data, $client_id);
@@ -3923,7 +3962,7 @@ class LeadsController extends BaseController
{
try {
$branch_data = $this->prepareClientBranchData($data, $client_id);
- $branch_id = $this->clientBranchModel->insert($branch_data);
+ $branch_id = $this->clientBranchModel->insert($branch_data);
if ($branch_id) {
$this->leadsModel->where('id', $data['id'])->set('is_client_created', $client_id)->update();
@@ -3943,7 +3982,7 @@ class LeadsController extends BaseController
{
try {
$client_policy_data = $this->prepareClientPolicyData($data, $client_id, $branch_id);
- $client_policy_id = $this->clientPolicyModel->insert($client_policy_data);
+ $client_policy_id = $this->clientPolicyModel->insert($client_policy_data);
if ($client_policy_id) {
$this->leadsModel->where('id', $data['id'])->set('is_client_created', $client_id)->update();
@@ -4034,7 +4073,7 @@ class LeadsController extends BaseController
$placementJson = $this->getPlacementJson($data);
if ($placementJson) {
$client_policy_data['placement_json'] = $placementJson;
- $client_policy_data['policy_terms'] = $this->convertNonEbQCRJsonToPolicyTerms(json_decode($placementJson, true));
+ $client_policy_data['policy_terms'] = $this->convertNonEbQCRJsonToPolicyTerms(json_decode($placementJson, true));
}
}
// print_r($client_policy_data); die;
@@ -4046,13 +4085,13 @@ class LeadsController extends BaseController
{
try {
$proposel_data = json_decode($data['proposel_data'], true);
- $QCRData = $this->RFQModel->where('is_active', 1)->where('lead_id', $data['id'])->first();
+ $QCRData = $this->RFQModel->where('is_active', 1)->where('lead_id', $data['id'])->first();
- if (!$QCRData) {
+ if (! $QCRData) {
throw new \Exception('RFQ Data not found');
}
- $JSON = json_decode($QCRData['json'], true);
+ $JSON = json_decode($QCRData['json'], true);
$converted_json = $this->transformProposelData($JSON, $proposel_data['proposel_name'], $proposel_data['insurer_name']);
// log_message('error', 'Converted JSON: ' . json_encode($converted_json));
@@ -4067,7 +4106,7 @@ class LeadsController extends BaseController
{
$data = $this->leadsModel->where('leads.id', $lead_id)->where('leads.is_active', 1)->first();
- if (!$data) {
+ if (! $data) {
return $this->respond(['status' => false, 'message' => 'Failed to create policy', 'data' => null], 200);
}
@@ -4093,26 +4132,26 @@ class LeadsController extends BaseController
// Initialize age_ratio based on policy type
$age_ratio = $policy_type == 2 ? [
- 'self' => ['min' => '18', 'max' => '60'],
+ 'self' => ['min' => '18', 'max' => '60'],
'spouse' => ['min' => 0, 'max' => 0],
- 'child' => ['min' => 0, 'max' => '25'],
+ 'child' => ['min' => 0, 'max' => '25'],
'elders' => ['min' => 0, 'max' => 0],
] : [
- 'self' => ['min' => '18', 'max' => '60']
+ 'self' => ['min' => '18', 'max' => '60'],
];
foreach ($data['table_data']['data'] as $dataRow) {
$item = $dataRow['items'] ?? '';
foreach ($dataRow['data'] as $cellData) {
- $parentth = $cellData['parentth'] ?? '';
- $subth = $cellData['subth'] ?? '';
+ $parentth = $cellData['parentth'] ?? '';
+ $subth = $cellData['subth'] ?? '';
$input_value = $cellData['input_value'] != "" ? $cellData['input_value'] : ($cellData['value'] ?? '');
- $value = $cellData['value'] ?? '';
+ $value = $cellData['value'] ?? '';
- if( $item == "family_composition" && $subth == $insurer_name && $policy_type == 2){
+ if ($item == "family_composition" && $subth == $insurer_name && $policy_type == 2) {
$age_ratio_array = json_decode($input_value, true)['age_ratio'] ?? null;
- if(!empty($age_ratio_array)){
+ if (! empty($age_ratio_array)) {
$age_ratio = $age_ratio_array;
}
}
@@ -4124,7 +4163,7 @@ class LeadsController extends BaseController
switch (true) {
- // CASE 1: Handle special conditions
+ // CASE 1: Handle special conditions
case str_starts_with($item, 'special_condition') && $parentth === $proposel_name && $subth === $insurer_name:
// log_message("error","INPUT".json_encode($input_value));
$parts = explode('-', $input_value);
@@ -4138,8 +4177,8 @@ class LeadsController extends BaseController
// CASE 2: Handle sum insured
case in_array($item, ['sum_insured', 'sumInsured2']):
- $si_amt = explode(',', $value);
- $terms_array[$item] = $si_amt[0] ?? '';
+ $si_amt = explode(',', $value);
+ $terms_array[$item] = $si_amt[0] ?? '';
$terms_array['multiple_sum_insured'] = array_slice($si_amt, 1);
// Add age_ratio after Sum insured
@@ -4175,7 +4214,7 @@ class LeadsController extends BaseController
public function convertNonEbQCRJsonToPolicyTerms($allTableData)
{
- if (!empty($allTableData)) {
+ if (! empty($allTableData)) {
array_pop($allTableData); // Remove the last item from the array
$terms_array = [];
@@ -4191,8 +4230,8 @@ class LeadsController extends BaseController
foreach ($dataRow['data'] as $cellData) {
$parentth = $cellData['parentth'] ?? '';
- $subth = $cellData['subth'] ?? '';
- $value = $cellData['display_content'] ?? '';
+ $subth = $cellData['subth'] ?? '';
+ $value = $cellData['display_content'] ?? '';
// Skip unwanted keys
if (in_array($parentth, ['SNO', 'Particulars', 'Action']) || $subth === 'Sum Insured' || $subth === 'Fidelity Limit') {
@@ -4205,13 +4244,13 @@ class LeadsController extends BaseController
}
// Set the value directly, overwriting with latest encountered
- if (!empty($item) && !empty($value)) {
+ if (! empty($item) && ! empty($value)) {
$finalItem = $item;
if (strpos($tableGroup['tableId'], 'summary') !== false) {
$policy_type = explode('_', $tableGroup['tableId'])[0] ?? '';
- $finalItem = $policy_type . ' - ' . $item;
+ $finalItem = $policy_type . ' - ' . $item;
}
$terms_array[$finalItem] = $value;
}
@@ -4234,11 +4273,11 @@ class LeadsController extends BaseController
->where('lead_id', $data['id'])
->first();
- if (!$QCRData || empty($QCRData['json'])) {
+ if (! $QCRData || empty($QCRData['json'])) {
return null;
}
- $jsonArray = json_decode($QCRData['json'], true);
+ $jsonArray = json_decode($QCRData['json'], true);
$proposalData = array_pop($jsonArray); // Get last item and remove it from the array
if (empty($jsonArray)) {
@@ -4255,14 +4294,14 @@ class LeadsController extends BaseController
);
}, $jsonArray);
- if (!empty($proposalData)) {
+ if (! empty($proposalData)) {
foreach ($proposalData['proposal_data']['over_all_column_data'] as $key => &$proposal) {
// Keep only the required proposal
if ($key !== $proposel_data['proposel_name']) {
unset($proposalData['proposal_data']['over_all_column_data'][$key]);
} else {
// Within the matched proposal, filter insurers
- if (!empty($proposal['insurers'])) {
+ if (! empty($proposal['insurers'])) {
$proposal['insurers'] = array_values(array_filter($proposal['insurers'], function ($insurer) use ($proposel_data) {
return $insurer['display_name'] === $proposel_data['insurer_name'];
}));
@@ -4272,7 +4311,6 @@ class LeadsController extends BaseController
unset($proposal); // Good practice after foreach by reference
}
-
$placement_json_data[] = $proposalData;
return json_encode($placement_json_data);
@@ -4280,21 +4318,20 @@ class LeadsController extends BaseController
//------------------------------------------------------------------------------------------------
-
public function transformMailContent($lead_data, $mail_content, $page_name)
{
$current_year = date('Y');
- $next_year = $current_year + 1;
- $policy_year = "$current_year-$next_year";
- $page_name = $page_name == "QCR" ? "Quote Comparison Report" : $page_name;
- $log_path = base_url() . '/public/assets/images/Nhance-Logo-Final.png';
+ $next_year = $current_year + 1;
+ $policy_year = "$current_year-$next_year";
+ $page_name = $page_name == "QCR" ? "Quote Comparison Report" : $page_name;
+ $log_path = base_url() . '/public/assets/images/Nhance-Logo-Final.png';
// $log_path ='https://venbait.in/nhance/dev/public/assets/images/Nhance-Logo-Final.png';
// dd($log_path);
$policy_expiry = strtotime($lead_data['policy_end_date']);
$formatted_policy = date("d-m-Y", $policy_expiry);
- $logged_user_id = get_session_userid();
+ $logged_user_id = get_session_userid();
$logged_user_data = $this->userModel->where("id", $logged_user_id)->where("is_active", 1)->first();
@@ -4309,7 +4346,6 @@ class LeadsController extends BaseController
$message = str_replace("{{POLICY_YEAR}}", $policy_year, $message);
$message = str_replace("{{POLICY_END_DATE}}", " (Due On " . $formatted_policy . ")", $message);
-
$message = str_replace("{{LOGGED_USER_NAME}}", ucfirst($logged_user_data['first_name'] ?? "") . " " . ucfirst($logged_user_data['last_name'] ?? ""), $message);
$message = str_replace("{{LOGGED_USER_EMAIL}}", $logged_user_data['email'] ?? "", $message);
$message = str_replace("{{LOGGED_USER_MOBILE}}", $logged_user_data['mobile'] ?? "", $message);
@@ -4321,6 +4357,125 @@ class LeadsController extends BaseController
}
}
+ /**
+ * Return subject and mail content for a lead and a given template type.
+ *
+ * GET params:
+ * - lead_id (int, required)
+ * - template_type (string, one of: rfq, qcr, placement; default: rfq)
+ *
+ * Response:
+ * {
+ * status: 'success'|'error',
+ * code: 200|4xx|5xx,
+ * subject: string,
+ * mail_content: string,
+ * message: string
+ * }
+ */
+ public function getLeadMailTemplate()
+ {
+ try {
+ $leadId = (int) $this->request->getGet('lead_id');
+ $templateType = strtolower((string) $this->request->getGet('template_type'));
+
+ if ($leadId <= 0) {
+ return $this->respond(
+ ['status' => 'error', 'code' => 400, 'message' => 'Invalid lead id'],
+ 400
+ );
+ }
+
+ if (! in_array($templateType, ['rfq', 'qcr', 'placement'], true)) {
+ // Default to RFQ if not provided or invalid
+ $templateType = 'rfq';
+ }
+
+ // Fetch master lead data similar to sendMailWithAttachement / viewRFQ
+ $lead_data = $this->leadsModel
+ ->select('
+ leads.*,
+ policy_type.long_name,
+ policy_type.policy_type,
+ user_profiles.email as created_person_email
+ ')
+ ->join('policy_type', 'leads.policy_type_id = policy_type.id', 'left')
+ ->join('user_profiles', 'leads.created_by = user_profiles.id', 'left')
+ ->where('leads.id', $leadId)
+ ->where('leads.is_active', 1)
+ ->first();
+
+ if (! $lead_data) {
+ $this->myLogger->logme('error', "MAIL TEMPLATE: lead not found | lead_id={$leadId}");
+ return $this->respond(
+ ['status' => 'error', 'code' => 404, 'message' => 'Lead not found'],
+ 404
+ );
+ }
+
+ // Determine page name and mail template type
+ if ($templateType === 'qcr') {
+ $pageName = 'QCR';
+ $mailTemplateId = '';
+ } elseif ($templateType === 'placement') {
+ $pageName = 'Placement';
+ $mailTemplateId = 'placement';
+ } else {
+ // rfq
+ $pageName = 'RFQ';
+ $mailTemplateId = '';
+ }
+
+ $rawMailTemplate = $this->getMailTemplate($mailTemplateId);
+ $rawSubjectTemplate = $this->getSubjectTemplate($lead_data);
+
+ $mail_content = $this->transformMailContent($lead_data, $rawMailTemplate, $pageName);
+ $subject = $this->transformMailContent($lead_data, $rawSubjectTemplate, $pageName);
+
+
+ //attachement files
+ $attachments = $this->leadFilesModel
+ ->where('lead_id', $leadId)
+ ->where('type !=', 2)
+ ->where('is_active', 1)
+ ->findAll();
+
+ $attachment_html = view('rfq/attachment_files', ['multi_file_data' => $attachments]);
+
+ return $this->respond(
+ [
+ 'status' => 'success',
+ 'code' => 200,
+ 'subject' => $subject,
+ 'mail_content' => $mail_content,
+ 'message' => 'Mail template generated successfully',
+ 'attachment_html' => $attachment_html,
+ ],
+ 200
+ );
+ } catch (\Throwable $e) {
+ $errorDetails = [
+ 'message' => $e->getMessage(),
+ 'file' => $e->getFile(),
+ 'line' => $e->getLine(),
+ ];
+
+ $this->myLogger->logme(
+ 'error',
+ 'MAIL TEMPLATE: exception occurred | ' . json_encode($errorDetails)
+ );
+
+ return $this->respond(
+ [
+ 'status' => 'error',
+ 'code' => 500,
+ 'message' => 'Failed to generate mail template',
+ ],
+ 500
+ );
+ }
+ }
+
public function getLastFiveFinancialYears(): array
{
$year = (int) date('Y');
@@ -4333,14 +4488,117 @@ class LeadsController extends BaseController
$financialYears = [];
for ($i = 0; $i < 6; $i++) {
- $startYear = $currentFYStart - $i;
- $endYear = $startYear + 1;
+ $startYear = $currentFYStart - $i;
+ $endYear = $startYear + 1;
$financialYears[] = "{$startYear}-{$endYear}";
}
return $financialYears;
}
+ /**
+ * Fetch basic placement-related lead data for Non-EB placement modal (AJAX).
+ *
+ * Route: GET /rfq/placementData/{lead_id}
+ */
+ public function getPlacementData($id)
+ {
+ try {
+ $leadId = (int) $id;
+
+ if ($leadId <= 0) {
+ return $this->respond(
+ ['status' => 'error', 'code' => 400, 'message' => 'Invalid lead id'],
+ 400
+ );
+ }
+
+ $lead = $this->leadsModel
+ ->where('id', $leadId)
+ ->where('is_active', 1)
+ ->first();
+
+ if (! $lead) {
+ $this->myLogger->logme('error', "PLACEMENT DATA: lead not found | lead_id={$leadId}");
+ return $this->respond(
+ ['status' => 'error', 'code' => 404, 'message' => 'Lead not found'],
+ 404
+ );
+ }
+
+ $data = [
+ 'id' => (int) $lead['id'],
+ 'policy_start_date' => ! empty($lead['policy_start_date']) ? date('d-m-Y', strtotime($lead['policy_start_date'])) : null,
+ 'policy_end_date' => ! empty($lead['policy_end_date']) ? date('d-m-Y', strtotime($lead['policy_end_date'])) : null,
+ 'placement_date' => ! empty($lead['placement_date']) ? date('d-m-Y', strtotime($lead['placement_date'])) : null,
+ 'payment_date' => ! empty($lead['payment_date']) ? date('d-m-Y', strtotime($lead['payment_date'])) : null,
+ 'utr_no' => $lead['utr_no'] ?? null,
+ 'premium_amount' => $lead['premium_amount'] ?? null,
+ 'cd_amount' => $lead['cd_amount'] ?? null,
+ 'total_amount' => $lead['total_amount'] ?? null,
+ 'is_cd' => isset($lead['is_cd']) ? (int) $lead['is_cd'] : 1,
+ 'is_installment' => isset($lead['is_installment']) ? (int) $lead['is_installment'] : 0,
+ 'no_of_installment' => $lead['no_of_installment'] ?? 1,
+ 'status' => $lead['status'] ?? null,
+ ];
+
+ // Fetch insurer level contacts based on lead's insurer/branch
+ $insurerId = $lead['insurer_id'] ?? null;
+ $insurerBranchId = $lead['insurer_branch_id'] ?? null;
+ // echo $insurerId;die();
+ $insurerContacts = [];
+ if (! empty($insurerId)) {
+ // getContactForRFQ($insurerId, $branchId) returns insurer-level contacts
+ $contacts = $this->levelContactModel->getContactForRFQ($insurerId, $insurerBranchId);
+ // print_rr($contacts);die();
+ if (! empty($contacts) && is_array($contacts)) {
+ foreach ($contacts as $contact) {
+ $insurerContacts[] = [
+ 'id' => (int) ($contact['id'] ?? 0),
+ 'display' => trim(
+ ($contact['insurer_name'] ?? '') . ' - ' .
+ ($contact['branch_code'] ?? '') . ' - ' .
+ ($contact['contact_person_name'] ?? '') . ' - ' .
+ ($contact['contact_person_email'] ?? '')
+ ),
+ 'email' => $contact['contact_person_email'] ?? '',
+ ];
+ }
+ }
+ }
+
+ $data['insurer_contacts'] = $insurerContacts;
+
+ return $this->respond(
+ [
+ 'status' => 'success',
+ 'code' => 200,
+ 'data' => $data,
+ ],
+ 200
+ );
+ } catch (\Throwable $e) {
+ $errorDetails = [
+ 'message' => $e->getMessage(),
+ 'file' => $e->getFile(),
+ 'line' => $e->getLine(),
+ ];
+
+ $this->myLogger->logme(
+ 'error',
+ 'PLACEMENT DATA: exception occurred | ' . json_encode($errorDetails)
+ );
+
+ return $this->respond(
+ [
+ 'status' => 'error',
+ 'code' => 500,
+ 'message' => 'Failed to fetch placement data',
+ ],
+ 500
+ );
+ }
+ }
// ------------ RFQ NON EB FUNCTIONS-----------------------------------------------------------------------------------------
@@ -4350,28 +4608,68 @@ class LeadsController extends BaseController
$this->loadLayout('view_rfq_non_eb');
}
+ /**
+ * Dedicated endpoint to view RFQ for Non-EB opportunities from the Opportunities List.
+ * Internally reuses the existing viewRFQ flow without modifying its logic.
+ */
+ public function viewNonEbRFQFromList($id)
+ {
+ echo 'NONEB_RFQ';
+ }
+
+ /**
+ * Dedicated endpoint to view QCR for Non-EB opportunities from the Opportunities List.
+ * Internally reuses the existing viewRFQ flow without modifying its logic.
+ */
+ public function viewNonEbQCRFromList($id)
+ {
+ echo 'NONEB_QCR';
+ }
+
// get lead data for edit both EB and NON-EB
- public function getLeadNonEB($type, $actual_lead_id = null ,$id = null)
+ public function getLeadNonEB($type, $actual_lead_id = null, $id = null)
{
// Convert '0' to null so it doesn't break your existing DB checks
$actual_lead_id = ($actual_lead_id == 0 || $actual_lead_id == '0') ? null : $actual_lead_id;
// Set basic data
$data = [
- 'issuer' => $this->issuer,
- 'client_type' => $this->clientType,
- 'lead_type' => $this->leadType,
- 'lead_status' => $this->leadsStatus,
- 'policy_type' => $this->policyTypeModel->where('is_active', 1)->findAll(),
- 'entity' => $this->kycEntityTypeModel->where('is_active', 1)->findAll(),
- 'insurer' => $this->insurerBranchModel->getInsurerBranchesWithInsurerNames(),
- 'tpa' => $this->tpaBranchModel->getTpaBranchesWithTpaNames(),
- 'lastFiveYears' => $this->getLastFiveFinancialYears(),
- 'gpaClaimType' => $this->claim_type_for_gpa,
- 'causeOfDeath' => $this->cause_of_death,
+ 'issuer' => $this->issuer,
+ 'client_type' => $this->clientType,
+ 'lead_type' => $this->leadType,
+ 'lead_status' => $this->leadsStatus,
+ 'policy_type' => $this->policyTypeModel->where('is_active', 1)->findAll(),
+ 'entity' => $this->kycEntityTypeModel->where('is_active', 1)->findAll(),
+ 'insurer' => $this->insurerBranchModel->getInsurerBranchesWithInsurerNames(),
+ 'tpa' => $this->tpaBranchModel->getTpaBranchesWithTpaNames(),
+ 'lastFiveYears' => $this->getLastFiveFinancialYears(),
+ 'gpaClaimType' => $this->claim_type_for_gpa,
+ 'causeOfDeath' => $this->cause_of_death,
'selected_lead_type' => $type,
'actual_lead_id' => $actual_lead_id,
];
+ if ($actual_lead_id > 0) {
+
+ // 🔹 Client Details (Single Row)
+ $data['actual_lead_client_details'] = $this->leadModel
+ ->select('company_name, email, phone, address, website, gst_number, status, assigned_to')
+ ->where('lead_id', $actual_lead_id)
+ ->first(); // first row only
+
+
+ // 🔹 Contact Person Details (First Row Only)
+ $data['actual_lead_contact_person_details'] = $this->contactModel
+ ->select('contact_id, name, mobile, designation, email, is_primary')
+ ->where('lead_id', $actual_lead_id)
+ ->where('is_primary',1)
+ ->orderBy('is_primary', 'DESC') // optional (primary first)
+ ->first(); // only first row
+ }
+ else {
+ $data['actual_lead_client_details'] = null;
+ $data['actual_lead_contact_person_details'] = null;
+ }
+
// Fetch sales team members who are active in team 5
$data['salse_team'] = $this->userModel
->select('user_profiles.*')
@@ -4381,36 +4679,34 @@ class LeadsController extends BaseController
->where('user_profiles.is_active', 1)
->findAll();
-
-
- if (!empty($id)) {
+ if (! empty($id)) {
$data['lead_edit_data'] = $this->leadsModel->where('id', $id)->first() ?? [];
$data['lead_edit_data']['multi_file_data'] = $this->leadFilesModel
- ->where('lead_id', $id)
- ->where('type !=', 2)
- ->where('is_active', 1)
- ->findAll() ?? null;
+ ->where('lead_id', $id)
+ ->where('type !=', 2)
+ ->where('is_active', 1)
+ ->findAll() ?? null;
$data['lead_edit_data']['lead_file_count'] = count($data['lead_edit_data']['multi_file_data']);
// Decode and merge custom fields if present
- $custom_fields_data = !empty($data['lead_edit_data']['custom_fields'])
+ $custom_fields_data = ! empty($data['lead_edit_data']['custom_fields'])
? json_decode($data['lead_edit_data']['custom_fields'], true)
: [];
- if (!empty($custom_fields_data) && is_array($custom_fields_data)) {
+ if (! empty($custom_fields_data) && is_array($custom_fields_data)) {
$data['lead_edit_data'] = array_merge($data['lead_edit_data'], $custom_fields_data);
}
- if (!empty($data['lead_edit_data'])) {
+ if (! empty($data['lead_edit_data'])) {
foreach (['policy_start_date', 'policy_end_date', 'source_policy_start_date', 'source_policy_end_date', 'incurred_claims_date', 'next_reminder_date'] as $dateField) {
- $data['lead_edit_data'][$dateField] = !empty($data['lead_edit_data'][$dateField])
+ $data['lead_edit_data'][$dateField] = ! empty($data['lead_edit_data'][$dateField])
? change_date_format($data['lead_edit_data'][$dateField], 'Y-m-d', 'd/m/Y')
: null;
}
- $data['lead_edit_data']['fin_years_claims_array'] = !empty($data['lead_edit_data']['fin_years_claims'])
+ $data['lead_edit_data']['fin_years_claims_array'] = ! empty($data['lead_edit_data']['fin_years_claims'])
? json_decode($data['lead_edit_data']['fin_years_claims'], true)['finyear'] ?? []
: [];
@@ -4419,7 +4715,7 @@ class LeadsController extends BaseController
$data
) ?? "";
- $html = view('rfq/multi_files', $data);
+ $html = view('rfq/multi_files', $data);
$data['lead_edit_data']['multi_file_html'] = trim($html) !== '' ? $html : null;
}
@@ -4434,26 +4730,26 @@ class LeadsController extends BaseController
return $this->loadLayout('leads_form_handler', $data);
}
- public function getLeadEmailHistory($id){
- if(!empty($id)){
- $result = $this->gmailSentHistoryModel
- ->where('pk', $id)
- ->where('module',"leads")
- ->orderBy('created_at', 'desc')
- ->findAll();
- if(!empty($result)){
- $result = !empty($result) ? $result : [];
- return $this->response->setJSON((['status' => 'success', 'data' => $result]))->setStatusCode(200);
- }else{
- return $this->response->setJSON((['status' => 'error', 'message' => 'No History found']))->setStatusCode(400);
- }
- }else{
- return $this->response->setJSON((['status' => 'error', 'message' => 'ID not found']))->setStatusCode(404);
+ public function getLeadEmailHistory($id)
+ {
+ if (! empty($id)) {
+ $result = $this->gmailSentHistoryModel
+ ->where('pk', $id)
+ ->where('module', "leads")
+ ->orderBy('created_at', 'desc')
+ ->findAll();
+ if (! empty($result)) {
+ $result = ! empty($result) ? $result : [];
+ return $this->response->setJSON((['status' => 'success', 'data' => $result]))->setStatusCode(200);
+ } else {
+ return $this->response->setJSON((['status' => 'error', 'message' => 'No History found']))->setStatusCode(400);
}
-
+ } else {
+ return $this->response->setJSON((['status' => 'error', 'message' => 'ID not found']))->setStatusCode(404);
+ }
// Select * from gmail_sent_history where pk != "" and module = "leads";
- // echo $id;
+ // echo $id;
}
public function getPolicyTypeFields()
@@ -4463,26 +4759,361 @@ class LeadsController extends BaseController
$html = $this->generateViewPageHtml($policy_type_id) ?? "";
- if (!empty($html)) {
+ if (! empty($html)) {
return $this->respond(['status' => true, 'code' => 200, 'message' => 'Policy Type FIELDS are found', 'data' => $html], 200);
} else {
return $this->respond(['status' => false, 'code' => 400, 'message' => 'Fields not found for this policy type'], 200);
}
}
+ /**
+ * AJAX endpoint to create or fetch RFQ Google Sheet for a lead.
+ *
+ * Flow:
+ * - Get lead_id from query param.
+ * - Fetch lead joined with policy_type (to read both misc columns).
+ * - If leads.misc has non-empty rfq_sheet_id, return that.
+ * - Else, read policy_type.misc.rfq_template_sheet_id and copy that template.
+ * - Apply protections (using RfqConfig if available).
+ * - Store new rfq_sheet_id back into leads.misc.
+ */
+ public function createRfqSheet()
+ {
+ try {
+ $leadId = (int) $this->request->getGet('lead_id');
+
+ if ($leadId <= 0) {
+ return $this->respond(
+ ['status' => 'error', 'code' => 400, 'message' => 'Invalid lead id'],
+ 400
+ );
+ }
+
+ $this->myLogger->logme('error', "RFQ Sheet: starting for lead_id={$leadId}");
+
+ // Fetch lead + policy type (including misc JSON from both)
+ $lead = $this->leadsModel
+ ->select('
+ leads.*,
+ policy_type.policy_type,
+ policy_type.long_name,
+ policy_type.misc as policy_misc
+ ')
+ ->join('policy_type', 'leads.policy_type_id = policy_type.id', 'left')
+ ->where('leads.id', $leadId)
+ ->where('leads.is_active', 1)
+ ->first();
+
+ if (! $lead) {
+ $this->myLogger->logme('error', "RFQ Sheet: lead not found | lead_id={$leadId}");
+ return $this->respond(
+ ['status' => 'error', 'code' => 404, 'message' => 'Lead not found'],
+ 404
+ );
+ }
+
+ // Decode leads.misc
+ $leadMisc = [];
+ if (! empty($lead['misc'])) {
+ $decoded = json_decode($lead['misc'], true);
+ if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
+ $leadMisc = $decoded;
+ } else {
+ $this->myLogger->logme('error', "RFQ Sheet: invalid JSON in leads.misc | lead_id={$leadId}, misc={$lead['misc']}");
+ }
+ }
+
+ // If RFQ sheet already exists, just return it
+ if (! empty($leadMisc['rfq_sheet_id'])) {
+ $sheetId = (string) $leadMisc['rfq_sheet_id'];
+ $sheetLib = new GoogleSheetLib();
+ $sheetUrl = $sheetLib->sheetUrl($sheetId);
+
+ $this->myLogger->logme('error', "RFQ Sheet: existing sheet found | lead_id={$leadId}, sheet_id={$sheetId}");
+
+ return $this->respond(
+ [
+ 'status' => 'success',
+ 'code' => 200,
+ 'sheet_id' => $sheetId,
+ 'sheet_url' => $sheetUrl,
+ 'message' => 'RFQ sheet already exists',
+ ],
+ 200
+ );
+ }
+
+ // Decode policy_type.misc and get template id
+ $policyMisc = [];
+ if (! empty($lead['policy_misc'])) {
+ $decodedPolicy = json_decode($lead['policy_misc'], true);
+ if (json_last_error() === JSON_ERROR_NONE && is_array($decodedPolicy)) {
+ $policyMisc = $decodedPolicy;
+ } else {
+ $this->myLogger->logme('error', "RFQ Sheet: invalid JSON in policy_type.misc | lead_id={$leadId}, policy_misc={$lead['policy_misc']}");
+ }
+ }
+
+ $templateId = $policyMisc['rfq_template_sheet_id'] ?? null;
+ if (empty($templateId)) {
+ $this->myLogger->logme(
+ 'error',
+ "RFQ Sheet: rfq_template_sheet_id missing | lead_id={$leadId}, policy_misc=" . ($lead['policy_misc'] ?? 'NULL')
+ );
+
+ return $this->respond(
+ [
+ 'status' => 'error',
+ 'code' => 400,
+ 'message' => 'RFQ template not found for this policy type',
+ ],
+ 400
+ );
+ }
+
+ // Prepare Google Sheet lib and config
+ $sheetLib = new GoogleSheetLib();
+
+ // Try to use RfqConfig if available for folder/protections
+ $parentFolderId = null;
+ $protections = [];
+
+ try {
+ /** @var \Config\RfqConfig $rfqConfig */
+ $rfqConfig = config('RfqConfig');
+ if ($rfqConfig) {
+ $parentFolderId = $rfqConfig->rfqParentFolderId ?? null;
+ $protections = $rfqConfig->protections ?? [];
+ }
+ } catch (\Throwable $e) {
+ // Config is optional; just log and continue with defaults
+ $this->myLogger->logme('error', 'RFQ Sheet: error loading RfqConfig | ' . $e->getMessage());
+ }
+
+ // Fallback to same parent folder as GoogleSheetController if config not set
+ if (! $parentFolderId) {
+ return $this->respond(
+ [
+ 'status' => 'error',
+ 'code' => 400,
+ 'message' => 'Google config not correct, contact administrator',
+ ],
+ 400);
+ }
+
+ // Filename logic same as exportQCRandRFQ (lines 2660-2673)
+ $string = 'RFQ';
+ $current_year = date('Y');
+ $next_year = $current_year + 1;
+ $policy_year = "{$current_year}-{$next_year}";
+
+ $clientName = trim($lead['client_name'] ?? $lead['client_short_name'] ?? '');
+ $policyType = trim($lead['policy_type'] ?? '');
+
+ if (! empty($lead['policy_end_date'])) {
+ $policy_expiry = strtotime($lead['policy_end_date']);
+ $formatted_policy = date('d-m-Y', $policy_expiry);
+ $sheetName = "{$clientName}_{$policyType}_{$string}_{$policy_year}(Due On {$formatted_policy}).xlsx";
+ } else {
+ $sheetName = "{$clientName}_{$policyType}_{$string}_{$policy_year}_" . '.xlsx';
+ }
+
+ // Copy template in Drive
+ $newSheetId = $sheetLib->copyTemplate($templateId, $sheetName, $parentFolderId);
+ $this->myLogger->logme('error', "RFQ Sheet: template copied | lead_id={$leadId}, template_id={$templateId}, new_sheet_id={$newSheetId}");
+
+ // Apply permissions: get sales users from DB (team_id 5) and add as editors
+ $salesTeam = $this->userModel
+ ->select('user_profiles.email')
+ ->join('user_teams', 'user_profiles.id = user_teams.user_id')
+ ->where('user_teams.team_id', 5)
+ ->where('user_teams.is_active', 1)
+ ->where('user_profiles.is_active', 1)
+ ->findAll();
+ $editorEmails = array_values(array_filter(array_unique(array_column($salesTeam, 'email'))));
+ if (! empty($editorEmails)) {
+ try {
+ $sheetLib->applyPermissions($newSheetId, [
+ 'editors' => $editorEmails,
+ 'viewers' => [],
+ ]);
+ $this->myLogger->logme('error', "RFQ Sheet: permissions applied (sales team) | sheet_id={$newSheetId}, count=" . count($editorEmails));
+ } catch (\Throwable $e) {
+ $this->myLogger->logme(
+ 'error',
+ "RFQ Sheet: failed to apply permissions | sheet_id={$newSheetId}, error=" . $e->getMessage()
+ );
+ }
+ }
+
+ // Apply protections if configured
+ if (! empty($protections)) {
+ try {
+ $sheetLib->applyProtections($newSheetId, $protections);
+ $this->myLogger->logme('error', "RFQ Sheet: protections applied | sheet_id={$newSheetId}");
+ } catch (\Throwable $e) {
+ $this->myLogger->logme(
+ 'error',
+ "RFQ Sheet: failed to apply protections | sheet_id={$newSheetId}, error=" . $e->getMessage()
+ );
+ }
+ }
+
+ // Update leads.misc with new rfq_sheet_id
+ $leadMisc['rfq_sheet_id'] = $newSheetId;
+ $this->leadsModel->update($leadId, [
+ 'misc' => json_encode($leadMisc),
+ 'status' => 'rfq_created',
+ ]);
+
+ $sheetUrl = $sheetLib->sheetUrl($newSheetId);
+
+ $this->myLogger->logme(
+ 'error',
+ "RFQ Sheet: created and stored | lead_id={$leadId}, sheet_id={$newSheetId}"
+ );
+
+ return $this->respond(
+ [
+ 'status' => 'success',
+ 'code' => 200,
+ 'sheet_id' => $newSheetId,
+ 'sheet_url' => $sheetUrl,
+ 'message' => 'RFQ sheet created successfully',
+ ],
+ 200
+ );
+ } catch (\Throwable $e) {
+ $errorDetails = [
+ 'message' => $e->getMessage(),
+ 'file' => $e->getFile(),
+ 'line' => $e->getLine(),
+ ];
+
+ $this->myLogger->logme(
+ 'error',
+ 'RFQ Sheet: exception occurred | ' . json_encode($errorDetails)
+ );
+
+ return $this->respond(
+ [
+ 'status' => 'error',
+ 'code' => 500,
+ 'message' => 'Failed to create RFQ sheet',
+ ],
+ 500
+ );
+ }
+ }
+
+ /**
+ * Download RFQ/QCR Excel file from Google Sheet for Non-EB leads.
+ *
+ * Expects $lead_data to contain misc JSON with rfq_sheet_id or qcr_sheet_id.
+ * Returns an array compatible with constructNonEbExcelToSaveTemp:
+ * [
+ * 'filePath' => string,
+ * 'fileName' => string,
+ * ]
+ */
+ protected function downloadFileFromGoogleSheet(array $lead_data): array
+ {
+ try {
+ $leadId = (int) ($lead_data['id'] ?? 0);
+
+ // Decode misc JSON
+ $misc = [];
+ if (! empty($lead_data['misc'])) {
+ $decoded = json_decode($lead_data['misc'], true);
+ if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
+ $misc = $decoded;
+ } else {
+ $this->myLogger->logme('error', "GSHEET DOWNLOAD: invalid JSON in leads.misc | lead_id={$leadId}, misc={$lead_data['misc']}");
+ }
+ }
+
+ // Prefer RFQ sheet id, fallback to QCR if needed
+ $sheetId = $misc['rfq_sheet_id'] ?? ($misc['qcr_sheet_id'] ?? null);
+
+ if (empty($sheetId)) {
+ $this->myLogger->logme('error', "GSHEET DOWNLOAD: sheet id missing in misc | lead_id={$leadId}");
+ // Fallback: behave like old flow and construct Non-EB Excel locally
+ // $file_info = $this->constructNonEbExcelToSaveTemp($leadId, 1, null);
+ // return [
+ // 'filePath' => $file_info['filePath'],
+ // 'fileName' => $file_info['fileName'],
+ // ];
+ }
+
+ $this->myLogger->logme('error', "GSHEET DOWNLOAD: starting download | lead_id={$leadId}, sheet_id={$sheetId}");
+
+ $sheetLib = new GoogleSheetLib();
+ $binary = $sheetLib->downloadExcel($sheetId);
+
+ if (! $binary) {
+ $this->myLogger->logme('error', "GSHEET DOWNLOAD: empty content from Google | lead_id={$leadId}, sheet_id={$sheetId}");
+ throw new \RuntimeException('Empty content from Google Sheet');
+ }
+
+ $filename = "lead_{$leadId}_" . date('Ymd_His') . '.xlsx';
+ $uploadDir = WRITEPATH . 'tmp/';
+ $uploadFilePath = $uploadDir . $filename;
+
+ if (! is_dir($uploadDir)) {
+ if (! mkdir($uploadDir, 0777, true) && ! is_dir($uploadDir)) {
+ $this->myLogger->logme('error', "GSHEET DOWNLOAD: failed to create tmp dir | path={$uploadDir}");
+ throw new \RuntimeException('Failed to create temporary directory for Excel download');
+ }
+ }
+
+ $bytes = file_put_contents($uploadFilePath, $binary);
+ if ($bytes === false) {
+ $this->myLogger->logme('error', "GSHEET DOWNLOAD: failed to write file | path={$uploadFilePath}");
+ throw new \RuntimeException('Failed to write downloaded Excel file');
+ }
+
+ $this->myLogger->logme('error', "GSHEET DOWNLOAD: saved file | lead_id={$leadId}, path={$uploadFilePath}");
+
+ return [
+ 'filePath' => $uploadFilePath,
+ 'fileName' => $filename,
+ ];
+ } catch (\Throwable $e) {
+ $errorDetails = [
+ 'message' => $e->getMessage(),
+ 'file' => $e->getFile(),
+ 'line' => $e->getLine(),
+ ];
+
+ $this->myLogger->logme(
+ 'error',
+ 'GSHEET DOWNLOAD: exception occurred | ' . json_encode($errorDetails)
+ );
+
+ // Final fallback to existing Non-EB Excel generator to avoid breaking mail flow
+ // $leadId = (int) ($lead_data['id'] ?? 0);
+ // $file_info = $this->constructNonEbExcelToSaveTemp($leadId, 1, null);
+
+ // return [
+ // 'filePath' => $file_info['filePath'],
+ // 'fileName' => $file_info['fileName'],
+ // ];
+ }
+ }
+
public function generateViewPageHtml($policy_type_id, $data = [])
{
$data['insurer'] = $this->insurerBranchModel->getInsurerBranchesWithInsurerNames();
- $data['tpa'] = $this->tpaBranchModel->getTpaBranchesWithTpaNames();
+ $data['tpa'] = $this->tpaBranchModel->getTpaBranchesWithTpaNames();
$viewMap = [
- 1 => 'rfq/gpa',
- 6 => 'rfq/gpa',
- 7 => 'rfq/gpa',
- 2 => 'rfq/gmc',
- 3 => 'rfq/gmc',
- 4 => 'rfq/gmc',
- 5 => 'rfq/gmc',
+ 1 => 'rfq/gpa',
+ 6 => 'rfq/gpa',
+ 7 => 'rfq/gpa',
+ 2 => 'rfq/gmc',
+ 3 => 'rfq/gmc',
+ 4 => 'rfq/gmc',
+ 5 => 'rfq/gmc',
17 => 'rfq/burglary',
22 => 'rfq/car',
23 => 'rfq/cpm',
@@ -4499,7 +5130,7 @@ class LeadsController extends BaseController
45 => 'rfq/marine',
46 => 'rfq/marine',
47 => 'rfq/marine',
- 50 => 'rfq/office'
+ 50 => 'rfq/office',
];
return isset($viewMap[$policy_type_id]) ? view($viewMap[$policy_type_id], $data) : "";
@@ -4509,13 +5140,13 @@ class LeadsController extends BaseController
public function constructNonEbExcelToSaveTemp($lead_id, $type, $propsal_and_insurer = null)
{
- $rfq_data = $this->RFQModel->getRFQTableDataWithLeadIDAndType($lead_id, $type);
+ $rfq_data = $this->RFQModel->getRFQTableDataWithLeadIDAndType($lead_id, $type);
$claim_history = $rfq_data['claim_history'];
// dd($claim_history);
- $lead_data = json_decode($rfq_data['custom_fields'], true) ?? [];
+ $lead_data = json_decode($rfq_data['custom_fields'], true) ?? [];
$lead_data['claim_history'] = $claim_history;
// dd($lead_data);
- if (!is_array($lead_data)) {
+ if (! is_array($lead_data)) {
$lead_data = [];
}
@@ -4532,30 +5163,29 @@ class LeadsController extends BaseController
$lead_data = array_merge(['Insured' => $rfq_data['client_name']], $lead_data);
$policy_registration_data = [];
- if (isset($rfq_data['registration_json']) && !empty($rfq_data['registration_json'])) {
+ if (isset($rfq_data['registration_json']) && ! empty($rfq_data['registration_json'])) {
$policy_registration_data = json_decode($rfq_data['registration_json'], true);
}
-
- $jsonData = json_decode($rfq_data['json'], true);
+ $jsonData = json_decode($rfq_data['json'], true);
$proposalData = end($jsonData);
array_pop($jsonData);
$length = 0;
// dd($jsonData[0]['table_data']['headers']);
- foreach ($jsonData as $key => $data) {
+ foreach ($jsonData as $key => $data) {
if ($type == 2) {
- $data = $this->convertNonEbJsonForQCR($data, $type, $proposalData, $key);
+ $data = $this->convertNonEbJsonForQCR($data, $type, $proposalData, $key);
// Kint::dump($data, 'Second');
if ($propsal_and_insurer !== null) {
list($proposal_key, $insurer_key) = explode('-', $propsal_and_insurer, 2);
- $data = $this->transformNonEbProposelData($data, $proposal_key, $insurer_key, $key);
+ $data = $this->transformNonEbProposelData($data, $proposal_key, $insurer_key, $key);
}
unset($data['proposalData']);
} else if ($type == 1) {
- $data = $this->convertNonEbJsonForQCR($data, $type, $proposalData, $key);
+ $data = $this->convertNonEbJsonForQCR($data, $type, $proposalData, $key);
unset($data['proposalData']);
}
}
@@ -4586,45 +5216,40 @@ class LeadsController extends BaseController
}
$spreadsheet = new Spreadsheet();
- $sheet = $spreadsheet->getActiveSheet();
+ $sheet = $spreadsheet->getActiveSheet();
$sheet->setTitle($sheetName);
-
-
// Start with lead_data at the top
$rowNumber = 1;
- $title = "Nhance India Insurance Broking Pvt Ltd";
+ $title = "Nhance India Insurance Broking Pvt Ltd";
$mergeRange1 = "A{$rowNumber}:{$columnLetterForTitle}{$rowNumber}";
$sheet->mergeCells($mergeRange1);
$sheet->setCellValue("A{$rowNumber}", $title);
$sheet->getStyle("A{$rowNumber}")->applyFromArray([
- 'font' => [
+ 'font' => [
'bold' => true,
- 'size' => 20
+ 'size' => 20,
],
'alignment' => [
'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
- 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
+ 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
],
]);
// Calculate title width
$maxWidthA = mb_strlen($title);
- // dd($columnLetterForImage);
- // Set column width to fit the image properly
+ // dd($columnLetterForImage);
+ // Set column width to fit the image properly
$sheet->getColumnDimension($columnLetterForImage)->setWidth(40); // Adjust as needed
- $sheet->getRowDimension($rowNumber)->setRowHeight(40); // Adjust as needed
-
+ $sheet->getRowDimension($rowNumber)->setRowHeight(40); // Adjust as needed
$drawing = new Drawing();
- $path = ROOTPATH . "public/assets/images/Nhance-Logo-Final.png"; // Use FCPATH for server path
+ $path = ROOTPATH . "public/assets/images/Nhance-Logo-Final.png"; // Use FCPATH for server path
$drawing->setPath($path);
$drawing->setCoordinates("{$columnLetterForImage}{$rowNumber}"); // Set position in column C
- $drawing->setHeight(35); // Adjust image height
-
-
+ $drawing->setHeight(35); // Adjust image height
// Apply center alignment to the cell
$sheet->getStyle("{$columnLetterForImage}{$rowNumber}")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
@@ -4643,15 +5268,15 @@ class LeadsController extends BaseController
// }
// Kint::dump($key);
// Kint::dump($value);
- $formattedKey = ucwords(str_replace('_', ' ', $key));
- $formattedKey = $formattedKey == "Risk Location" ? "Risk Details" : $formattedKey;
- $formattedKey = $formattedKey == "Address" ? "Communication Address" : $formattedKey;
+ $formattedKey = ucwords(str_replace('_', ' ', $key));
+ $formattedKey = $formattedKey == "Risk Location" ? "Risk Details" : $formattedKey;
+ $formattedKey = $formattedKey == "Address" ? "Communication Address" : $formattedKey;
$formattedValue = ucwords(str_replace("_", " ", $value));
if ($key == "claim_history") {
- $formattedValue = $value == "1" ? "Yes" : "No";
- $formattedKey = "Claim Experience";
+ $formattedValue = $value == "1" ? "Yes" : "No";
+ $formattedKey = "Claim Experience";
}
// Kint::dump($formattedValue);
@@ -4666,10 +5291,10 @@ class LeadsController extends BaseController
// Apply styles for alignment and bold text in A:B
$sheet->getStyle($mergeRangeKey)->applyFromArray([
- 'font' => ['bold' => true],
+ 'font' => ['bold' => true],
'alignment' => [
'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
- 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
+ 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
],
]);
@@ -4680,7 +5305,7 @@ class LeadsController extends BaseController
// ]);
// }
- // Track max width needed for columns
+ // Track max width needed for columns
$maxWidthA = max($maxWidthA, mb_strlen($formattedKey)); // Consider title and keys
$maxWidthB = max($maxWidthB, mb_strlen((string) $value));
// if (!empty($policy_registration_data)) {
@@ -4691,7 +5316,6 @@ class LeadsController extends BaseController
$rowNumber++;
}
// die();
-
// Set column width based on max content length (adjusted for padding)
$sheet->getColumnDimension('A')->setWidth($maxWidthA * 1.2);
@@ -4700,9 +5324,9 @@ class LeadsController extends BaseController
// $rowNumber += 1;
//Policy Registration
- if (!empty($policy_registration_data)) {
+ if (! empty($policy_registration_data)) {
foreach ($policy_registration_data as $key => $value) {
- // kint::dump($value);
+ // kint::dump($value);
$startRow = $rowNumber; // Track where the block starts
// Title Row
@@ -4712,13 +5336,13 @@ class LeadsController extends BaseController
// Title Style
$sheet->getStyle($titleMergeRangeKey)->applyFromArray([
- 'font' => ['bold' => true],
+ 'font' => ['bold' => true],
'alignment' => [
'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
- 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
+ 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
],
- 'fill' => [
- 'fillType' => Fill::FILL_SOLID,
+ 'fill' => [
+ 'fillType' => Fill::FILL_SOLID,
'startColor' => ['rgb' => 'ADD8E6'],
],
]);
@@ -4732,10 +5356,10 @@ class LeadsController extends BaseController
$sheet->setCellValue("{$columnLetterForImage}{$rowNumber}", $value['policyType']);
$sheet->getStyle("A{$rowNumber}:C{$rowNumber}")->applyFromArray([
- 'font' => ['bold' => true],
+ 'font' => ['bold' => true],
'alignment' => [
'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
- 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
+ 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
],
]);
@@ -4746,10 +5370,10 @@ class LeadsController extends BaseController
$sheet->setCellValue("{$columnLetterForImage}{$rowNumber}", ucfirst($key) . " Policy");
$sheet->getStyle("A{$rowNumber}:C{$rowNumber}")->applyFromArray([
- 'font' => ['bold' => true],
+ 'font' => ['bold' => true],
'alignment' => [
'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
- 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
+ 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
],
]);
@@ -4757,17 +5381,17 @@ class LeadsController extends BaseController
}
// Type of Business & Nature of Business
- if (isset($value['productSelection']) && !empty($value['productSelection'])) {
+ if (isset($value['productSelection']) && ! empty($value['productSelection'])) {
// Type of Business
$sheet->mergeCells("A{$rowNumber}:{$columnLetterForTitle}{$rowNumber}");
$sheet->setCellValue("A{$rowNumber}", "Type of Business");
$sheet->setCellValue("{$columnLetterForImage}{$rowNumber}", $this->buisnessType[$value['productSelection']['type_of_buisness']] ?? '');
$sheet->getStyle("A{$rowNumber}")->applyFromArray([
- 'font' => ['bold' => true],
+ 'font' => ['bold' => true],
'alignment' => [
'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
- 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
+ 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
],
]);
@@ -4779,33 +5403,33 @@ class LeadsController extends BaseController
$sheet->setCellValue("{$columnLetterForImage}{$rowNumber}", $value['productSelection']['buisness_nature'] ?? '');
$sheet->getStyle("A{$rowNumber}")->applyFromArray([
- 'font' => ['bold' => true],
+ 'font' => ['bold' => true],
'alignment' => [
'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
- 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
+ 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
],
]);
$rowNumber++;
}
- if (isset($value['policyDetails']) && !empty($value['policyDetails'])) {
+ if (isset($value['policyDetails']) && ! empty($value['policyDetails'])) {
// Type of Business
$sheet->mergeCells("A{$rowNumber}:{$columnLetterForTitle}{$rowNumber}");
$sheet->setCellValue("A{$rowNumber}", "Terrorism");
$sheet->setCellValue("{$columnLetterForImage}{$rowNumber}", ucfirst($value['policyDetails']['terrorism'] ?? 'No'));
$sheet->getStyle("A{$rowNumber}")->applyFromArray([
- 'font' => ['bold' => true],
+ 'font' => ['bold' => true],
'alignment' => [
'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
- 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
+ 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
],
]);
$rowNumber++;
}
- if (!empty($value['locations'])) {
+ if (! empty($value['locations'])) {
foreach ($value['locations'] as $index => $location) {
// Merge title cell
@@ -4822,10 +5446,10 @@ class LeadsController extends BaseController
// Style the title cell
$sheet->getStyle("A{$rowNumber}")->applyFromArray([
- 'font' => ['bold' => true],
+ 'font' => ['bold' => true],
'alignment' => [
'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
- 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
+ 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
],
]);
@@ -4833,7 +5457,6 @@ class LeadsController extends BaseController
}
}
-
$endRow = $rowNumber; // Block ends at previous row
// Apply border to the whole block
@@ -4841,7 +5464,7 @@ class LeadsController extends BaseController
'borders' => [
'allBorders' => [
'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
- 'color' => ['argb' => '000000'],
+ 'color' => ['argb' => '000000'],
],
],
]);
@@ -4859,17 +5482,17 @@ class LeadsController extends BaseController
if ($type == 2) {
- $data = $this->convertNonEbJsonForQCR($data, $type, $proposalData, $key);
+ $data = $this->convertNonEbJsonForQCR($data, $type, $proposalData, $key);
// Kint::dump($data, 'Second');
if ($propsal_and_insurer !== null) {
list($proposal_key, $insurer_key) = explode('-', $propsal_and_insurer, 2);
- $data = $this->transformNonEbProposelData($data, $proposal_key, $insurer_key, $key);
+ $data = $this->transformNonEbProposelData($data, $proposal_key, $insurer_key, $key);
}
unset($data['proposalData']);
} else if ($type == 1) {
- $data = $this->convertNonEbJsonForQCR($data, $type, $proposalData, $key);
+ $data = $this->convertNonEbJsonForQCR($data, $type, $proposalData, $key);
unset($data['proposalData']);
}
@@ -4892,7 +5515,6 @@ class LeadsController extends BaseController
$sheet->getColumnDimension($columnLetter)->setWidth(60);
$sheet->getColumnDimension('C')->setWidth(35);
-
if ($header['parentHeader'] == 'Policy') {
// $header['parentHeader'] = 'S.No.';
$sheet->getColumnDimension('A')->setWidth(10);
@@ -4907,20 +5529,19 @@ class LeadsController extends BaseController
$sheet->getColumnDimension('D')->setWidth(35);
}
-
- $startColumn = $columnLetter; // Start of the current header range
+ $startColumn = $columnLetter; // Start of the current header range
$subHeaderCount = count($header['subHeaders']); // Number of subheaders for this parent header
- // Kint::dump($subHeaderCount);
- // Set parent header value
+ // Kint::dump($subHeaderCount);
+ // Set parent header value
$sheet->setCellValue("{$startColumn}{$rowNumber}", $header['parentHeader']);
$sheet->getStyle("{$startColumn}{$rowNumber}")->applyFromArray([
- 'font' => ['bold' => true],
+ 'font' => ['bold' => true],
'alignment' => [
'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
- 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
+ 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
],
- 'fill' => [
- 'fillType' => Fill::FILL_SOLID,
+ 'fill' => [
+ 'fillType' => Fill::FILL_SOLID,
'startColor' => ['rgb' => 'ADD8E6'],
],
]);
@@ -4945,10 +5566,10 @@ class LeadsController extends BaseController
}
$sheet->getStyle("{$columnLetter}{$subHeaderRow}")->applyFromArray([
- 'font' => ['bold' => true],
+ 'font' => ['bold' => true],
'alignment' => [
'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
- 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
+ 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
],
]);
$columnLetter++; // Move to the next column for subheaders
@@ -4959,10 +5580,10 @@ class LeadsController extends BaseController
$sheet->setCellValue("B{$subHeaderRow}", "Sum Insured");
$sheet->mergeCells("B{$subHeaderRow}:C{$subHeaderRow}");
$sheet->getStyle("B{$subHeaderRow}:C{$subHeaderRow}")->applyFromArray([
- 'font' => ['bold' => true],
+ 'font' => ['bold' => true],
'alignment' => [
'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
- 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
+ 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
],
]);
@@ -4973,13 +5594,13 @@ class LeadsController extends BaseController
'borders' => [
'allBorders' => [
'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
- 'color' => ['argb' => 'FF000000'], // Black color
+ 'color' => ['argb' => 'FF000000'], // Black color
],
],
]);
- // Increase row height for headers and subheaders
- $sheet->getRowDimension($rowNumber)->setRowHeight(25); // Header row height
+ // Increase row height for headers and subheaders
+ $sheet->getRowDimension($rowNumber)->setRowHeight(25); // Header row height
$sheet->getRowDimension($subHeaderRow)->setRowHeight(20); // Subheader row height
// $rowNumber = $subHeaderRow + 2;
@@ -4987,15 +5608,15 @@ class LeadsController extends BaseController
$column_data = $data['table_data']['data'];
// dd($column_data);
- $serial_no = 1;
+ $serial_no = 1;
$maxColumnWidths = [];
- $RowSpanEnable = false;
+ $RowSpanEnable = false;
// Add table data rows
foreach ($column_data as $dataRow) {
$columnLetter = 'A';
- $hasPolicy = in_array('Policy', array_column($dataRow['data'], 'parentth'));
+ $hasPolicy = in_array('Policy', array_column($dataRow['data'], 'parentth'));
// Kint::dump($hasPolicy);
foreach ($dataRow['data'] as $cellData) {
@@ -5007,15 +5628,15 @@ class LeadsController extends BaseController
if ($cellData['parentth'] == 'SNO') {
$sheet->setCellValue("{$columnLetter}{$rowNumber}", $serial_no);
} else if ($cellData['parentth'] == 'Policy') {
- $mergeStart = $rowNumber; // Start row for merging
- $mergeEnd = $rowNumber + ($cellData['rowspan'] - 1); // End row for merging
+ $mergeStart = $rowNumber; // Start row for merging
+ $mergeEnd = $rowNumber + ($cellData['rowspan'] - 1); // End row for merging
$sheet->setCellValue("{$columnLetter}{$mergeStart}", $dataRow['SNO']);
$sheet->mergeCells("{$columnLetter}{$mergeStart}:{$columnLetter}{$mergeEnd}");
$sheet->getStyle("{$columnLetter}{$mergeStart}:{$columnLetter}{$mergeEnd}")
->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
} else {
- if (!$hasPolicy && $key == 0) {
+ if (! $hasPolicy && $key == 0) {
$RowSpanEnable = true;
$columnLetter++;
$sheet->setCellValue("{$columnLetter}{$rowNumber}", $cellData['display_content']);
@@ -5024,7 +5645,7 @@ class LeadsController extends BaseController
}
}
- if (!($key === 0 && !$hasPolicy)) {
+ if (! ($key === 0 && ! $hasPolicy)) {
$columnLetter++;
}
}
@@ -5038,12 +5659,12 @@ class LeadsController extends BaseController
// dd($columnLetter);
$prevColumn5 = $this->getPreviousColumn($columnLetter);
- $dataRange = "A" . ($subHeaderRow + 1) . ":" . "{$prevColumn5}" . ($rowNumber - 1);
+ $dataRange = "A" . ($subHeaderRow + 1) . ":" . "{$prevColumn5}" . ($rowNumber - 1);
$sheet->getStyle($dataRange)->applyFromArray([
'borders' => [
'allBorders' => [
'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
- 'color' => ['argb' => 'FF000000'], // Black color
+ 'color' => ['argb' => 'FF000000'], // Black color
],
],
]);
@@ -5071,36 +5692,36 @@ class LeadsController extends BaseController
if ($matches) {
$startColumn = $matches[1]; // A
- $startRow = $matches[2]; // 1
- $endColumn = $matches[3]; // G
- $endRow = $matches[4]; // 75
+ $startRow = $matches[2]; // 1
+ $endColumn = $matches[3]; // G
+ $endRow = $matches[4]; // 75
// Convert column letter to index, reduce by 1, and convert back
$endColumnIndex = Coordinate::columnIndexFromString($endColumn) - 1;
- $newEndColumn = Coordinate::stringFromColumnIndex($endColumnIndex);
+ $newEndColumn = Coordinate::stringFromColumnIndex($endColumnIndex);
// Generate the new range (e.g., "A1:F75" instead of "A1:G75")
$newDataRange = "{$startColumn}{$startRow}:{$newEndColumn}{$endRow}";
// $sheet->getStyle($newDataRange)->getBorders()->getAllBorders()->setBorderStyle(Border::BORDER_THIN);
}
- $lastRow = count($lead_data) + 1;
+ $lastRow = count($lead_data) + 1;
$leadRange = "A1:{$columnLetterForImage}{$lastRow}";
$sheet->getStyle($leadRange)->applyFromArray([
'borders' => [
'allBorders' => [
'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
- 'color' => ['argb' => 'FF000000'], // Black color
+ 'color' => ['argb' => 'FF000000'], // Black color
],
],
]);
}
- $columnWidth = $sheet->getColumnDimension("C")->getWidth(); // e.g., 20
- $cellPixelWidth = $columnWidth * 7; // Approximate conversion (1 unit ≈ 7 pixels)
- $imagePixelWidth = 250; // Approximate width of your image (in pixels)
-
+ $columnWidth = $sheet->getColumnDimension("C")->getWidth(); // e.g., 20
+ $cellPixelWidth = $columnWidth * 7; // Approximate conversion (1 unit ≈ 7 pixels)
+ $imagePixelWidth = 250; // Approximate width of your image (in pixels)
+
$offsetX = max(0, ($cellPixelWidth - $imagePixelWidth) / 2);
$offsetX = $offsetX + 97;
if ($length >= 4) {
@@ -5108,22 +5729,22 @@ class LeadsController extends BaseController
} else if ($length == 3) {
$offsetX = 140;
}
-
- // dd($offsetX, $cellPixelWidth, $imagePixelWidth);
+
+ // dd($offsetX, $cellPixelWidth, $imagePixelWidth);
$drawing->setOffsetX($offsetX); // Dynamically center
- $drawing->setOffsetY(10); // Dynamically center
+ $drawing->setOffsetY(10); // Dynamically center
$drawing->setWorksheet($sheet);
-
- $sheet->getStyle('C1')->getAlignment()
- ->setHorizontal(Alignment::HORIZONTAL_CENTER)
- ->setVertical(Alignment::VERTICAL_CENTER);
- if (!empty($rfq_data['fin_years_claims']) && $claim_history == 1) {
+ $sheet->getStyle('C1')->getAlignment()
+ ->setHorizontal(Alignment::HORIZONTAL_CENTER)
+ ->setVertical(Alignment::VERTICAL_CENTER);
+
+ if (! empty($rfq_data['fin_years_claims']) && $claim_history == 1) {
$claim_details = json_decode($rfq_data['fin_years_claims'], true) ?? [];
- if (!empty($claim_details['finyear'])) {
+ if (! empty($claim_details['finyear'])) {
// Get headers dynamically
$headers = array_map(function ($key) {
@@ -5136,9 +5757,9 @@ class LeadsController extends BaseController
$sheet = $spreadsheet->getActiveSheet();
// Set headers
- $sheet->fromArray($headers, NULL, 'A1');
+ $sheet->fromArray($headers, null, 'A1');
- // Apply background color and bold style to headers
+ // Apply background color and bold style to headers
$headerCellRange = 'A1:' . chr(64 + count($headers)) . '1'; // e.g., A1:G1
$sheet->getStyle($headerCellRange)->getFont()->setBold(true);
@@ -5168,7 +5789,7 @@ class LeadsController extends BaseController
$sheet->getColumnDimension($colLetter)->setAutoSize(true);
}
- // Enable wrap text for all cells
+ // Enable wrap text for all cells
$maxColLetter = chr(64 + count($headers)); // Last column letter
$sheet->getStyle("A2:{$maxColLetter}{$row}")->getAlignment()->setWrapText(true);
@@ -5185,12 +5806,12 @@ class LeadsController extends BaseController
// dd($rowNumber);
// Set filename
- $string = ($type == 2) ? 'QCR' : 'RFQ';
+ $string = ($type == 2) ? 'QCR' : 'RFQ';
$filename = "{$string}_{$rfq_data['client_short_name']}_{$rfq_data['policy_type']}_" . date('YmdHis') . '.xlsx';
// Save to temporary location
$uploadFilePath = WRITEPATH . 'tmp/' . $filename;
- $writer = new Xlsx($spreadsheet);
+ $writer = new Xlsx($spreadsheet);
$writer->save($uploadFilePath);
return [
@@ -5210,7 +5831,7 @@ class LeadsController extends BaseController
// Column-wise Check: Remove headers and relevant data if qcr == 0
foreach ($first_json['proposal_data']['over_all_column_data'] as $proposalKey => $proposalData) {
- if ((isset($proposalData['qcr']) && isset($proposalData['stc'])) && ($proposalData['qcr'] == 0 || $proposalData['qcr'] === false) || ($proposalData['stc'] == 0 || $proposalData['stc'] === false)) {
+ if ((isset($proposalData['qcr']) && isset($proposalData['stc'])) && ($proposalData['qcr'] == 0 || $proposalData['qcr'] === false) || ($proposalData['stc'] == 0 || $proposalData['stc'] === false)) {
// Remove matching parentHeader in headers
foreach ($first_json['table_data']['headers'] as $index => $header) {
@@ -5251,7 +5872,6 @@ class LeadsController extends BaseController
}
}
-
foreach ($first_json['table_data']['data'] as &$item) {
$item['data'] = array_values(array_filter($item['data'], function ($entry) use ($insurer) {
return $entry['subth'] !== $insurer['display_name'];
@@ -5297,7 +5917,7 @@ class LeadsController extends BaseController
$finalRows = [];
- if (!empty($groupedRows)) {
+ if (! empty($groupedRows)) {
// Loop through each row_id group and check for Policy status
foreach ($groupedRows as $rowId => $rows) {
@@ -5317,23 +5937,22 @@ class LeadsController extends BaseController
}
// Step 3: If parent Policy is "Checked", retain the entire group
- if (!$hasPolicy || $isChecked) {
+ if (! $hasPolicy || $isChecked) {
foreach ($rows as $r) {
$finalRows[] = $r;
}
}
}
- if (!empty($finalRows)) {
+ if (! empty($finalRows)) {
// Update the original data
$first_json['table_data']['data'] = array_values($finalRows);
}
}
-
// Reindex arrays to maintain proper structure
- $first_json['table_data']['headers'] = array_values($first_json['table_data']['headers']);
- $first_json['table_data']['data'] = array_values($first_json['table_data']['data']);
+ $first_json['table_data']['headers'] = array_values($first_json['table_data']['headers']);
+ $first_json['table_data']['data'] = array_values($first_json['table_data']['data']);
$first_json['proposal_data']['over_all_column_data'] = array_map(function ($proposal) {
$proposal['insurers'] = array_values($proposal['insurers']);
return $proposal;
@@ -5369,10 +5988,9 @@ class LeadsController extends BaseController
// Ensure to unset the reference after the loop
unset($row);
-
$finalRows = [];
- if (!empty($groupedRows)) {
+ if (! empty($groupedRows)) {
// Loop through each row_id group and check for Policy status
foreach ($groupedRows as $rowId => $rows) {
@@ -5392,14 +6010,14 @@ class LeadsController extends BaseController
}
// Step 3: If parent Policy is "Checked", retain the entire group
- if (!$hasPolicy || $isChecked) {
+ if (! $hasPolicy || $isChecked) {
foreach ($rows as $r) {
$finalRows[] = $r;
}
}
}
- if (!empty($finalRows)) {
+ if (! empty($finalRows)) {
// Update the original data
$first_json['table_data']['data'] = array_values($finalRows);
}
@@ -5431,11 +6049,11 @@ class LeadsController extends BaseController
// Add the first two default headers only once
$headerData[] = [
'parentHeader' => $data['table_data']['headers'][0]['parentHeader'],
- 'subHeaders' => ['-']
+ 'subHeaders' => ['-'],
];
$headerData[] = [
'parentHeader' => $data['table_data']['headers'][1]['parentHeader'],
- 'subHeaders' => ['-']
+ 'subHeaders' => ['-'],
];
$second_table_name = $data['table_data']['headers'][1]['parentHeader'] ?? "";
@@ -5447,7 +6065,7 @@ class LeadsController extends BaseController
if ($subHeader === $insurer) {
$headerData[] = [
'parentHeader' => $header['parentHeader'],
- 'subHeaders' => ['Sum Insured', $subHeader]
+ 'subHeaders' => ['Sum Insured', $subHeader],
];
break 2; // Exit both loops after match is found
}
@@ -5458,17 +6076,17 @@ class LeadsController extends BaseController
// Update the original data's headers
$data['table_data']['headers'] = $headerData;
- if (!empty($actionColumn)) {
+ if (! empty($actionColumn)) {
$data['table_data']['headers'][] = [
'parentHeader' => "Action",
- 'subHeaders' => ['-']
+ 'subHeaders' => ['-'],
];
}
foreach ($data['table_data']['data'] as &$entry) {
- $sno = $entry['SNO'];
- $items = $entry['items'];
+ $sno = $entry['SNO'];
+ $items = $entry['items'];
$row_id = $entry['row_id'];
$filteredData = [];
@@ -5490,7 +6108,7 @@ class LeadsController extends BaseController
$filteredData[] = $item;
}
- if (!empty($actionColumn)) {
+ if (! empty($actionColumn)) {
if ($item['parentth'] === "Action") {
$filteredData[] = $item;
}
@@ -5498,10 +6116,10 @@ class LeadsController extends BaseController
}
// Update the entry with filtered data
- $entry['SNO'] = $sno;
- $entry['items'] = $items;
+ $entry['SNO'] = $sno;
+ $entry['items'] = $items;
$entry['row_id'] = $row_id;
- $entry['data'] = $filteredData;
+ $entry['data'] = $filteredData;
}
unset($entry);
@@ -5522,7 +6140,7 @@ class LeadsController extends BaseController
$attachments = [];
- if (!empty($json_string)) {
+ if (! empty($json_string)) {
log_message('error', 'json_string is not empty');
$fileIds = json_decode($json_string, true);
@@ -5550,12 +6168,12 @@ class LeadsController extends BaseController
if (file_exists($fullPath)) {
log_message('error', 'File exists at path: ' . $fullPath);
- if (!empty($lead_file['file_name'])) {
+ if (! empty($lead_file['file_name'])) {
log_message('error', 'File name is not empty: ' . $lead_file['file_name']);
$attachments[] = [
'fileName' => $lead_file['file_name'],
- 'filePath' => $fullPath
+ 'filePath' => $fullPath,
];
} else {
log_message('error', 'File name is empty for ID: ' . $id);
@@ -5577,20 +6195,20 @@ class LeadsController extends BaseController
public function handleMemberDataGPATotalSumInsurerFromExcel($params)
{
- $lead_id = $params['lead_id'];
- $lead_data = $this->leadsModel->find((int)$lead_id);
+ $lead_id = $params['lead_id'];
+ $lead_data = $this->leadsModel->find((int) $lead_id);
// dd($lead_data);
$file_name_with_path = WRITEPATH . "/uploads/lead_files/" . $lead_data['file_name'];
// dd($file_name_with_path);
- if (!$lead_data) {
+ if (! $lead_data) {
return ['status' => 'failed', 'message' => 'Opportunity data not found'];
}
if ($lead_data['file_name']) {
//check physical file
- if (!file_exists($file_name_with_path)) {
+ if (! file_exists($file_name_with_path)) {
$message = "Lead Physcial file not found";
$this->myLogger->logme('error', ($message . ' for file ' . $file_name_with_path));
@@ -5600,7 +6218,7 @@ class LeadsController extends BaseController
$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file_name_with_path);
//get members data
- $members_sheet = $spreadsheet->getSheet(0);
+ $members_sheet = $spreadsheet->getSheet(0);
$highestRowAndColumn = $members_sheet->getHighestRowAndColumn();
// dd($highestRowAndColumn);
@@ -5610,19 +6228,18 @@ class LeadsController extends BaseController
$members = ExcelSanitizeHelper::sanitizeArrayData($uncleaned_members);
// dd($members);
-
// Check column headings
$members_heading = $members[0];
- $available_col = [];
+ $available_col = [];
$lower_headers = array_map('strtolower', $members_heading);
foreach ($lower_headers as $index => $header) {
if (preg_match('/^(sa\s*-\s*option|proposed\s+sum\s+insured)\s+\d+$/i', $header)) {
$column_name = $members_heading[$index];
- $sum = 0;
+ $sum = 0;
for ($i = 1; $i < count($members); $i++) {
- $cell_raw = $members[$i][$index] ?? '';
+ $cell_raw = $members[$i][$index] ?? '';
$cell_clean = preg_replace('/[^0-9.\-]/', '', $cell_raw); // remove non-numeric chars
if ($cell_clean !== '' && is_numeric($cell_clean)) {
@@ -5634,7 +6251,6 @@ class LeadsController extends BaseController
}
}
-
// dd($available_col);
return $available_col;
}
@@ -5643,7 +6259,7 @@ class LeadsController extends BaseController
}
public function generateDemographyDataTable($param = [])
- {
+ {
if ($this->request !== null) {
$param['lead_id'] = $this->request->getGet('lead_id');
@@ -5684,8 +6300,8 @@ class LeadsController extends BaseController
$html .= "";
$html .= "{$relation} ";
foreach ($allColumns as $col) {
- $value = isset($ages[$col]) ? $ages[$col] : "-";
- $html .= "{$value} ";
+ $value = isset($ages[$col]) ? $ages[$col] : "-";
+ $html .= "{$value} ";
}
$html .= " ";
}
@@ -5695,9 +6311,9 @@ class LeadsController extends BaseController
}
if ($this->request !== null) {
- if(!empty($html)){
+ if (! empty($html)) {
return $this->respond(['status' => true, 'data' => $html], 200);
- }else{
+ } else {
return $this->respond(['status' => false, 'data' => $html], 200);
}
}
@@ -5710,7 +6326,7 @@ class LeadsController extends BaseController
{
$lead_data = $this->leadsModel
->select(
- 'leads.*,
+ 'leads.*,
user_profiles.email as created_person_email,
policy_type.policy_type,
policy_type.long_name
@@ -5732,8 +6348,8 @@ class LeadsController extends BaseController
}
- $from_mail = "im@nhanceindia.in";
- $subject = "Reminder for RFQ";
+ $from_mail = getenv(LEAD_INSURER_FROM_MAIL_ID);
+ $subject = "Reminder for RFQ";
$content_string = '
Dear Sir,
Greetings from Nhance India!
@@ -5761,7 +6377,6 @@ class LeadsController extends BaseController
$mail_content = $this->transformMailContent($lead, $content_string, "RFQ");
$mail_subject = $this->transformMailContent($lead, $subject, "RFQ");
-
$this->myLogger->logme("info", "Processing lead_id={$leadId} for reminder mails");
// get sales person + created_by emails
@@ -5772,7 +6387,7 @@ class LeadsController extends BaseController
->findAll();
$email_list = array_column($sales_person_emails, 'email');
- if (!empty($reply_to)) {
+ if (! empty($reply_to)) {
$email_list[] = $reply_to;
}
$email_list = array_filter(array_unique($email_list));
@@ -5788,7 +6403,7 @@ class LeadsController extends BaseController
->first();
// dd(db_connect()->getLastQuery(), $createdAtRow);
- if (!$createdAtRow) {
+ if (! $createdAtRow) {
$this->myLogger->logme("warning", "No sent history found for lead_id={$leadId}, skipping...");
continue;
}
@@ -5810,14 +6425,14 @@ class LeadsController extends BaseController
// Filter only pending insurers
$quote_received_insurer = json_decode($lead['quote_received_insurer'] ?? "[]", true);
- $reminder_mail_data = [];
+ $reminder_mail_data = [];
if (empty($quote_received_insurer)) {
$reminder_mail_data = $mail_datas;
} else {
foreach ($mail_datas as $mail_value) {
$insurer_id = $mail_value['common'] ?? "";
- if (!in_array($insurer_id, $quote_received_insurer)) {
+ if (! in_array($insurer_id, $quote_received_insurer)) {
$reminder_mail_data[] = $mail_value;
}
}
@@ -5834,7 +6449,7 @@ class LeadsController extends BaseController
$common = ['module' => "leads", 'pk' => $leadId, 'mail_type' => "remainder", 'common' => null];
foreach ($reminder_mail_data as $content) {
- $insurerId = $content['common'] ?? null;
+ $insurerId = $content['common'] ?? null;
$common['common'] = $insurerId;
try {
@@ -5849,20 +6464,19 @@ class LeadsController extends BaseController
'message' => $mail_content ?? "",
'reply_to' => $reply_to,
'bcc' => json_decode($content["bcc"] ?? "", true) ?? "",
- 'common' => $common
+ 'common' => $common,
]);
$this->myLogger->logme("info", "Reminder mail sent to the insurer | lead_id={$leadId}, insurer_id={$insurerId}, response=" . json_encode($res));
$reminder_sended_lead[] = [
'lead_id' => $leadId,
'insurer_id' => $insurerId,
- 'response' => $res
+ 'response' => $res,
];
- } else{
+ } else {
$this->myLogger->logme("info", "Reminder mail disable for this lead_id={$leadId}");
}
-
} catch (\Throwable $e) {
$errorDetails = [
'error_message' => $e->getMessage(),
@@ -5874,22 +6488,21 @@ class LeadsController extends BaseController
$reminder_sended_lead[] = [
'lead_id' => $leadId,
'insurer_id' => $insurerId,
- 'response' => ['status' => false, 'error' => $errorDetails]
+ 'response' => ['status' => false, 'error' => $errorDetails],
];
}
// send reminder to sales person / creator only
$internal_mail_response = MailHelper::send_email([
- 'mail' => $from_mail,
- 'cc' => $email_string,
- 'subject' => $mail_subject ?? "",
- 'message' => $mail_content ?? "",
- 'common' => $common
+ 'mail' => $from_mail,
+ 'cc' => $email_string,
+ 'subject' => $mail_subject ?? "",
+ 'message' => $mail_content ?? "",
+ 'common' => $common,
]);
$this->myLogger->logme("info", "Reminder mail sent to sales persons | lead_id={$leadId}, recipients={$email_string}, response=" . json_encode($internal_mail_response));
-
}
}
@@ -5903,18 +6516,18 @@ class LeadsController extends BaseController
$this->myLogger->logme('error', "uploadMultiFileFromRfq START");
$this->myLogger->logme('error', "Files received: " . json_encode($this->request->getPost() ?? []));
- $lead_id = $this->request->getPost('lead_id');
- $lead_form_type = $this->request->getPost('lead_form_type');
+ $lead_id = $this->request->getPost('lead_id');
+ $lead_form_type = $this->request->getPost('lead_form_type');
$leads_file_primary_key = $this->request->getPost('leads_file_id') ?? [];
- $docs_name = $this->request->getPost('docs_name') ?? [];
- $files = $this->request->getFileMultiple('file_name');
+ $docs_name = $this->request->getPost('docs_name') ?? [];
+ $files = $this->request->getFileMultiple('file_name');
if (empty($files) || empty($docs_name)) {
$this->myLogger->logme('error', "No files or document names provided");
return $this->respond([
- 'status' => false,
- 'code' => 400,
- 'message' => 'No files or document names provided'
+ 'status' => false,
+ 'code' => 400,
+ 'message' => 'No files or document names provided',
], 400);
}
@@ -5923,12 +6536,12 @@ class LeadsController extends BaseController
$this->myLogger->logme('error', "uploadMultiFiles result: " . json_encode($multi_file_data ?? []));
- if (!empty($multi_file_data)) {
+ if (! empty($multi_file_data)) {
$this->insertMultiFilesData($multi_file_data, $lead_id, $lead_form_type);
$this->myLogger->logme('error', "Files inserted successfully into DB");
// update lead file name if change
- if(isset($multi_file_data[0]['file_name']) && !empty($multi_file_data[0]['file_name'])){
+ if (isset($multi_file_data[0]['file_name']) && ! empty($multi_file_data[0]['file_name'])) {
$this->leadsModel->where('id', $lead_id)->set('file_name', $multi_file_data[0]['file_name'])->update();
}
@@ -5936,7 +6549,6 @@ class LeadsController extends BaseController
$this->myLogger->logme('error', "uploadMultiFiles returned empty");
}
-
// Get the updated lead file data
$lead_file_data = $this->leadFilesModel
->where('is_active', 1)
@@ -5946,17 +6558,17 @@ class LeadsController extends BaseController
$this->myLogger->logme('error', "Fetched " . count($lead_file_data) . " lead file records");
- $document_data = $this->renderFileFields($lead_file_data);
- $attch_data['multi_file_data'] = $lead_file_data;
- $attachment_html = view('rfq/attachment_files', $attch_data) ?? "";
+ $document_data = $this->renderFileFields($lead_file_data);
+ $attch_data['multi_file_data'] = $lead_file_data;
+ $attachment_html = view('rfq/attachment_files', $attch_data) ?? "";
$this->myLogger->logme('error', "uploadMultiFileFromRfq END");
return $this->respond([
- 'status' => true,
- 'code' => 200,
- 'message' => "File uploaded Successfully",
- 'document_data' => $document_data,
+ 'status' => true,
+ 'code' => 200,
+ 'message' => "File uploaded Successfully",
+ 'document_data' => $document_data,
'attachment_html' => $attachment_html,
], 200);
@@ -5973,32 +6585,32 @@ class LeadsController extends BaseController
$this->myLogger->logme('error', "Exception in uploadMultiFileFromRfq: " . json_encode($errorDetails));
return $this->respond([
- 'status' => false,
- 'code' => 500,
- 'message' => "File upload failed: " . $e->getMessage(),
- 'errorDetails' => $errorDetails,
+ 'status' => false,
+ 'code' => 500,
+ 'message' => "File upload failed: " . $e->getMessage(),
+ 'errorDetails' => $errorDetails,
], 500);
}
}
public function renderFileFields($multi_file_data = [])
- {
+ {
$uploadFilePath = WRITEPATH . 'uploads/lead_files/';
- $html = '';
+ $html = '';
// If data exists (edit mode)
- if (!empty($multi_file_data)) {
+ if (! empty($multi_file_data)) {
foreach ($multi_file_data as $index => $value) {
- $sample_dwn_link = ' [ Download ]';
- $isFirstField = ($index === 0);
- $placeholder = $isFirstField ? 'First file must be Demography.' : '';
- $first_file_name = $isFirstField ? 'Member List' : '';
+ $sample_dwn_link = ' [ Download ]';
+ $isFirstField = ($index === 0);
+ $placeholder = $isFirstField ? 'First file must be Demography.' : '';
+ $first_file_name = $isFirstField ? 'Member List' : '';
$member_data_link = $isFirstField ? $sample_dwn_link : '';
- $read_only = $isFirstField ? 'readonly' : '';
- $accept = $isFirstField ? '.xls,.xlsx' : '.xls,.xlsx,.pdf,.jpg,.jpeg,.png';
- $displayIndex = $index + 1;
+ $read_only = $isFirstField ? 'readonly' : '';
+ $accept = $isFirstField ? '.xls,.xlsx' : '.xls,.xlsx,.pdf,.jpg,.jpeg,.png';
+ $displayIndex = $index + 1;
$html .= '
@@ -6064,7 +6676,7 @@ class LeadsController extends BaseController
{
$filePath = WRITEPATH . 'uploads/lead_files/' . $fileName;
- if (!file_exists($filePath)) {
+ if (! file_exists($filePath)) {
$data['message'] = 'The Physical File Not Found';
echo view('errors/404', $data);
}
@@ -6088,35 +6700,35 @@ class LeadsController extends BaseController
$this->myLogger->logme('error', 'Start memberDataListExcelFileFormatValidation');
$this->myLogger->logme('error', "Received params: " . json_encode($params));
- $lead_id = $params['lead_id'];
+ $lead_id = $params['lead_id'];
$age_validation_check = $params['age_validation'] ?? null;
- $lead_data = $this->leadsModel->where('id', $lead_id)->first();
+ $lead_data = $this->leadsModel->where('id', $lead_id)->first();
// dd($lead_data);
$return = [];
- if (!isset($lead_data)) {
+ if (! isset($lead_data)) {
$this->myLogger->logme('error', "Lead not found for lead_id: {$lead_id}");
- $this->leadFilesModel->where('lead_id', $lead_id)->where('type', 2)->set(['status' => 'failed', 'error_data' => json_encode(['error_summary' => array_count_values([12]),'error_data' => 'file not found in DB'])])->update();
- return array('status' => false, 'msg' => 'file not found in DB');
+ $this->leadFilesModel->where('lead_id', $lead_id)->where('type', 2)->set(['status' => 'failed', 'error_data' => json_encode(['error_summary' => array_count_values([12]), 'error_data' => 'file not found in DB'])])->update();
+ return ['status' => false, 'msg' => 'file not found in DB'];
}
//get the lead files data
$lead_file_data = $this->leadFilesModel->where('is_active', 1)->where('type', 2)->first();
//check the lead file table has the error data entry if not than create new entry
- if(empty($lead_file_data)){
- $data['type'] = 2;
- $data['file_name'] = $lead_data['file_name'];
- $data['docs_name'] = "Member List";
- $data['lead_id'] = $lead_id;
+ if (empty($lead_file_data)) {
+ $data['type'] = 2;
+ $data['file_name'] = $lead_data['file_name'];
+ $data['docs_name'] = "Member List";
+ $data['lead_id'] = $lead_id;
$lead_file_last_insert_id = $this->leadFilesModel->insert($data);
$this->myLogger->logme('error', "New lead file entry created for store the error data, insert_id : '{$lead_file_last_insert_id}'");
}
$family_composition = [];
- if($age_validation_check && !empty($lead_data['proposel_data'])){
+ if ($age_validation_check && ! empty($lead_data['proposel_data'])) {
$family_composition = $this->getAgeRatioFromRfqJson($lead_id, $lead_data['proposel_data']);
- $this->myLogger->logme('info', 'Family composition :',json_encode($family_composition));
+ $this->myLogger->logme('info', 'Family composition :', json_encode($family_composition));
}
// dd($family_composition);
@@ -6125,34 +6737,34 @@ class LeadsController extends BaseController
$this->myLogger->logme('error', "File path: {$file_name_with_path}");
//check physical file
- if (!file_exists($file_name_with_path)) {
- //file not found update status and reason
+ if (! file_exists($file_name_with_path)) {
+ //file not found update status and reason
$message = "Physcial file not found";
$this->myLogger->logme('error', ($message . ' for lead id ' . $lead_id));
$this->leadFilesModel
->where('lead_id', $lead_id)
->where('type', 2)
- ->set(['status' => 'failed','error_data' => json_encode(['error_summary' => array_count_values([5]),'error_data' => $message])])
+ ->set(['status' => 'failed', 'error_data' => json_encode(['error_summary' => array_count_values([5]), 'error_data' => $message])])
->update();
- return array('error_summary' => [5], 'error_data' => $message);
+ return ['error_summary' => [5], 'error_data' => $message];
}
$this->myLogger->logme('info', 'File exists, starting validation process');
//start validation process
$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file_name_with_path);
- $sheet = $spreadsheet->getActiveSheet();
+ $sheet = $spreadsheet->getActiveSheet();
$highestRowAndColumn = $sheet->getHighestRowAndColumn();
// dd($highestRowAndColumn);
$columns_to_check = $this->member_data_excel_columns;
- $result = ['error_type' => 1, 'error_summary' => [], 'error_data' => []];
- $keys = array_keys($columns_to_check);
+ $result = ['error_type' => 1, 'error_summary' => [], 'error_data' => []];
+ $keys = array_keys($columns_to_check);
$allowedHighestColumn = end($columns_to_check);
- $excel_data = $sheet->rangeToArray('A1:' . $allowedHighestColumn['col_cell_name'] . $highestRowAndColumn['row']);
- $excel_data = ExcelSanitizeHelper::sanitizeArrayData($excel_data);
+ $excel_data = $sheet->rangeToArray('A1:' . $allowedHighestColumn['col_cell_name'] . $highestRowAndColumn['row']);
+ $excel_data = ExcelSanitizeHelper::sanitizeArrayData($excel_data);
$this->myLogger->logme('error', 'Excel data sanitized count : {row_count}', ['row_count' => count($excel_data)]);
// dd($excel_data);
@@ -6171,9 +6783,9 @@ class LeadsController extends BaseController
$this->leadFilesModel
->where('lead_id', $lead_id)
->where('type', 2)
- ->set(['status' => 'failed','error_data' => json_encode(['error_summary' => array_count_values([6]),'error_data' => $message])])
+ ->set(['status' => 'failed', 'error_data' => json_encode(['error_summary' => array_count_values([6]), 'error_data' => $message])])
->update();
- return array('error_summary' => [6], 'error_data' => $message);
+ return ['error_summary' => [6], 'error_data' => $message];
}
$relationship = $this->general_relationships;
@@ -6195,63 +6807,62 @@ class LeadsController extends BaseController
//iterate each row for columns validations
foreach ($row as $col_key => $col) {
- $is_mandatory = $columns_to_check[$keys[$col_key]]['is_mandatory'];
- $format = $columns_to_check[$keys[$col_key]]['format'];
- $allowed_values = $columns_to_check[$keys[$col_key]]['allowed_values'];
+ $is_mandatory = $columns_to_check[$keys[$col_key]]['is_mandatory'];
+ $format = $columns_to_check[$keys[$col_key]]['format'];
+ $allowed_values = $columns_to_check[$keys[$col_key]]['allowed_values'];
$custom_function = isset($columns_to_check[$keys[$col_key]]['custom']) ? $columns_to_check[$keys[$col_key]]['custom'] : null;
- $binding_params = isset($columns_to_check[$keys[$col_key]]['params']) ? $columns_to_check[$keys[$col_key]]['params'] : null;
+ $binding_params = isset($columns_to_check[$keys[$col_key]]['params']) ? $columns_to_check[$keys[$col_key]]['params'] : null;
$column_dispaly_name = $columns_to_check[$keys[$col_key]]['col_name'];
- $column_index = $columns_to_check[$keys[$col_key]]['col_idx'];
- $column_cell = $columns_to_check[$keys[$col_key]]['col_cell_name'];
-
+ $column_index = $columns_to_check[$keys[$col_key]]['col_idx'];
+ $column_cell = $columns_to_check[$keys[$col_key]]['col_cell_name'];
//mandatory check
if (is_bool($is_mandatory) && $is_mandatory === true) {
- if ($col == "" || $col == NULL) {
- array_push($result['error_summary'], 1); //push error code for summary
+ if ($col == "" || $col == null) {
+ array_push($result['error_summary'], 1); //push error code for summary
$result['error_data'][$row_key][$keys[$col_key]]['col_name'] = $column_dispaly_name; //push column name
- $result['error_data'][$row_key][$keys[$col_key]]['col_idx'] = $column_index; //push column index
- $result['error_data'][$row_key][$keys[$col_key]]['error'][] = 'Value is mandatory'; //push exact error desc
+ $result['error_data'][$row_key][$keys[$col_key]]['col_idx'] = $column_index; //push column index
+ $result['error_data'][$row_key][$keys[$col_key]]['error'][] = 'Value is mandatory'; //push exact error desc
}
}
//if is_mandatory is array (action based mandatory check)
if (is_array($is_mandatory)) {
$allowed_actions = $columns_to_check[$keys[$col_key]]['is_mandatory'];
- if ($col == "" || $col == NULL) {
+ if ($col == "" || $col == null) {
array_push($result['error_summary'], 1);
$result['error_data'][$row_key][$keys[$col_key]]['col_name'] = $column_dispaly_name; //push column name
- $result['error_data'][$row_key][$keys[$col_key]]['col_idx'] = $column_index; //push column index
- $result['error_data'][$row_key][$keys[$col_key]]['error'][] = 'Value is mandatory for this action/event';
+ $result['error_data'][$row_key][$keys[$col_key]]['col_idx'] = $column_index; //push column index
+ $result['error_data'][$row_key][$keys[$col_key]]['error'][] = 'Value is mandatory for this action/event';
}
}
//format check
if (isset($format)) {
$format_error = check_excel_date_format($col, $format);
- if (!$format_error['status']) {
+ if (! $format_error['status']) {
array_push($result['error_summary'], 2);
$result['error_data'][$row_key][$keys[$col_key]]['col_name'] = $column_dispaly_name; //push column name
- $result['error_data'][$row_key][$keys[$col_key]]['col_idx'] = $column_index; //push column index
- $result['error_data'][$row_key][$keys[$col_key]]['error'][] = $format_error['error'];
+ $result['error_data'][$row_key][$keys[$col_key]]['col_idx'] = $column_index; //push column index
+ $result['error_data'][$row_key][$keys[$col_key]]['error'][] = $format_error['error'];
}
}
//allowed values check
if (($is_mandatory === true && isset($allowed_values) && is_array($allowed_values)) || (is_array($is_mandatory) && (isset($allowed_values) && is_array($allowed_values)))) {
- if (!in_array((trim($col)), $allowed_values)) {
+ if (! in_array((trim($col)), $allowed_values)) {
array_push($result['error_summary'], 3);
$result['error_data'][$row_key][$keys[$col_key]]['col_name'] = $column_dispaly_name; //push column name
- $result['error_data'][$row_key][$keys[$col_key]]['col_idx'] = $column_index; //push column index
- $result['error_data'][$row_key][$keys[$col_key]]['error'][] = "Value not allowed: Expected " . implode(",", $allowed_values) . " and received $col";
+ $result['error_data'][$row_key][$keys[$col_key]]['col_idx'] = $column_index; //push column index
+ $result['error_data'][$row_key][$keys[$col_key]]['error'][] = "Value not allowed: Expected " . implode(",", $allowed_values) . " and received $col";
}
}
//custom function check
if (isset($custom_function)) {
//convert string params into PHP variables
- // Create an array of variables to pass custom helper funcitons
+ // Create an array of variables to pass custom helper funcitons
$param_values = [];
foreach ($binding_params as $bkey => $bparam) {
$param_values[] = ($$bparam);
@@ -6261,27 +6872,27 @@ class LeadsController extends BaseController
if ($res['status'] === false) {
array_push($result['error_summary'], 4);
$result['error_data'][$row_key][$keys[$col_key]]['col_name'] = $column_dispaly_name; //push column name
- $result['error_data'][$row_key][$keys[$col_key]]['col_idx'] = $column_index; //push column index
- $result['error_data'][$row_key][$keys[$col_key]]['error'][] = $res['error'];
+ $result['error_data'][$row_key][$keys[$col_key]]['col_idx'] = $column_index; //push column index
+ $result['error_data'][$row_key][$keys[$col_key]]['error'][] = $res['error'];
}
}
- }
+ }
//age validation
$age_validation = isset($columns_to_check['dob']['age_validation']) ?? null;
- if (isset($age_validation) && $age_validation && $age_validation_check && !empty($family_composition)) {
+ if (isset($age_validation) && $age_validation && $age_validation_check && ! empty($family_composition)) {
$format_error = check_age_validation($row, $family_composition);
- if (!$format_error['status']) {
+ if (! $format_error['status']) {
array_push($result['error_summary'], 2);
$result['error_data'][$row_key][$keys[$columns_to_check['dob']['col_idx']]]['col_name'] = $columns_to_check['dob']['col_name']; //push column name
- $result['error_data'][$row_key][$keys[$columns_to_check['dob']['col_idx']]]['col_idx'] = $columns_to_check['dob']['col_idx']; //push column index
- $result['error_data'][$row_key][$keys[$columns_to_check['dob']['col_idx']]]['error'][] = $format_error['error'];
+ $result['error_data'][$row_key][$keys[$columns_to_check['dob']['col_idx']]]['col_idx'] = $columns_to_check['dob']['col_idx']; //push column index
+ $result['error_data'][$row_key][$keys[$columns_to_check['dob']['col_idx']]]['error'][] = $format_error['error'];
}
}
$row['row_index'] = $row_key;
- $relation_idx = $columns_to_check['relationship']['col_idx'];
- $emp_code_idx = $columns_to_check['emp_code']['col_idx'];
+ $relation_idx = $columns_to_check['relationship']['col_idx'];
+ $emp_code_idx = $columns_to_check['emp_code']['col_idx'];
if (isset($row[$relation_idx]) && strtolower($row[$relation_idx]) == 'self' && isset($member_family_data[$row[$emp_code_idx]])) {
array_unshift($member_family_data[$row[$emp_code_idx]], $row);
@@ -6295,7 +6906,7 @@ class LeadsController extends BaseController
$check_row_dublicate = check_duplicate_rows_and_contacts($excel_data, $columns_to_check, $result);
// dd($check_row_dublicate);
- if(count($check_row_dublicate)){
+ if (count($check_row_dublicate)) {
$result = $check_row_dublicate;
}
@@ -6305,12 +6916,12 @@ class LeadsController extends BaseController
if (isset($result['error_summary']) && count($result['error_summary'])) {
$result['error_summary'] = array_count_values($result['error_summary']);
- $status = 'failed';
- $failure_reason = ((json_encode($result)));
- $this->leadFilesModel->where('lead_id', $lead_id)->where('type', 2)->set(['status' => $status,'error_data' => $failure_reason])->update();
+ $status = 'failed';
+ $failure_reason = ((json_encode($result)));
+ $this->leadFilesModel->where('lead_id', $lead_id)->where('type', 2)->set(['status' => $status, 'error_data' => $failure_reason])->update();
$this->myLogger->logme("error", '{lead_id} uploaded failed for this lead id', ['lead_id' => $lead_id]);
} else {
- $this->leadFilesModel->where('lead_id', $lead_id)->where('type', 2)->set(['status' => 'success','error_data' => ''])->update();
+ $this->leadFilesModel->where('lead_id', $lead_id)->where('type', 2)->set(['status' => 'success', 'error_data' => ''])->update();
$r = Jobs::addJob(['job_name' => 'calculateMembersDemography', 'payload' => ['lead_id' => $lead_id]]);
}
@@ -6318,22 +6929,22 @@ class LeadsController extends BaseController
}
public function getAgeRatioFromRfqJson($lead_id, $porposel_data)
- {
+ {
$age_ratio = [];
- $rfq_data = $this->RFQModel->where('is_active', 1)->where('lead_id', $lead_id)->orderBy('id', 'desc')->first();
- if(empty($rfq_data) || empty($rfq_data['json'])){
+ $rfq_data = $this->RFQModel->where('is_active', 1)->where('lead_id', $lead_id)->orderBy('id', 'desc')->first();
+ if (empty($rfq_data) || empty($rfq_data['json'])) {
return $age_ratio;
}
- $data = json_decode($rfq_data['json'], true);
+ $data = json_decode($rfq_data['json'], true);
$proposal_and_insurer = json_decode($porposel_data, true);
- $insurer_key = $proposal_and_insurer['insurer_name'] ?? null;
+ $insurer_key = $proposal_and_insurer['insurer_name'] ?? null;
- if(isset($data['table_data']['data'])){
+ if (isset($data['table_data']['data'])) {
foreach ($data['table_data']['data'] as $key => $value) {
- if($value['items'] == 'family_composition'){
+ if ($value['items'] == 'family_composition') {
foreach ($value['data'] as $family_composition) {
- if($family_composition['subth'] == $insurer_key){
+ if ($family_composition['subth'] == $insurer_key) {
$age_ratio = json_decode($family_composition['input_value'] ?? "", true) ?? [];
}
}
@@ -6369,7 +6980,7 @@ class LeadsController extends BaseController
public function getMemberDataListExcelErrorData($lead_id)
{
try {
- $file = $this->leadFilesModel->where('lead_id', $lead_id)->where('type', 2)->where('is_active', 1)->first();
+ $file = $this->leadFilesModel->where('lead_id', $lead_id)->where('type', 2)->where('is_active', 1)->first();
$error_data = json_decode($file['error_data']);
// dd($error_data);
// return $error_data;
@@ -6377,17 +6988,17 @@ class LeadsController extends BaseController
$file_name_with_path = WRITEPATH . "/uploads/lead_files/" . $file['file_name'];
//check the file exist or not
- if (!file_exists($file_name_with_path)) {
+ if (! file_exists($file_name_with_path)) {
$error_message = "File not found";
$this->myLogger->logme('error', ($error_message . ' for file id ' . $lead_id));
return 0;
}
$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file_name_with_path);
- $sheet = $spreadsheet->getActiveSheet();
+ $sheet = $spreadsheet->getActiveSheet();
- $highestRowAndColumn = $sheet->getHighestRowAndColumn();
- $excel_data = $sheet->rangeToArray('A1:' . $highestRowAndColumn['column'] . $highestRowAndColumn['row']);
+ $highestRowAndColumn = $sheet->getHighestRowAndColumn();
+ $excel_data = $sheet->rangeToArray('A1:' . $highestRowAndColumn['column'] . $highestRowAndColumn['row']);
$excelErrorData['excel_header'] = $excel_data[0];
unset($excel_data[0]);
// Kint::dump($excel_data);
@@ -6398,8 +7009,8 @@ class LeadsController extends BaseController
foreach ($error_data->error_data as $key => $value) {
foreach ($value as $key2 => $value2) {
- $error_data = $value2->error;
- $data = ['value' => $excel_data[$key][$value2->col_idx], 'error' => $error_data,];
+ $error_data = $value2->error;
+ $data = ['value' => $excel_data[$key][$value2->col_idx], 'error' => $error_data];
$excel_data[$key][$value2->col_idx] = $data;
}
array_push($finalArray, $excel_data[$key]);
@@ -6407,9 +7018,9 @@ class LeadsController extends BaseController
foreach ($finalArray as $fkey => $value) {
foreach ($value as $vkey => $arrayData) {
- if (!is_array($arrayData)) {
- $data = ['value' => $arrayData];
- $finalArray[$fkey][$vkey] = $data;
+ if (! is_array($arrayData)) {
+ $data = ['value' => $arrayData];
+ $finalArray[$fkey][$vkey] = $data;
}
}
}
@@ -6418,14 +7029,13 @@ class LeadsController extends BaseController
return $excelErrorData;
} else if ($error_data->error_type == 2) {
-
- $allErrors = [];
+ $allErrors = [];
$typeTowArray = [];
foreach ($error_data->error_data as $index => $item) {
foreach ($item as $field) {
- if (!isset($allErrors[$index])) {
+ if (! isset($allErrors[$index])) {
$allErrors[$index] = [];
}
$allErrors[$index] = array_merge($allErrors[$index], $field->error);
@@ -6438,7 +7048,7 @@ class LeadsController extends BaseController
// print_r($value);
foreach ($excel_data as $excel_data_index => $excel_data_value) {
if ($excel_data_value[0] == $key) {
- $data = ['value' => $excel_data[$excel_data_index][1], 'error' => $value,];
+ $data = ['value' => $excel_data[$excel_data_index][1], 'error' => $value];
$excel_data[$excel_data_index][1] = $data;
array_push($typeTowArray, $excel_data[$excel_data_index]);
break;
@@ -6448,9 +7058,9 @@ class LeadsController extends BaseController
// dd($data);
foreach ($typeTowArray as $fkey => $value) {
foreach ($value as $vkey => $arrayData) {
- if (!is_array($arrayData)) {
- $data = ['value' => $arrayData];
- $typeTowArray[$fkey][$vkey] = $data;
+ if (! is_array($arrayData)) {
+ $data = ['value' => $arrayData];
+ $typeTowArray[$fkey][$vkey] = $data;
}
}
}
@@ -6459,7 +7069,7 @@ class LeadsController extends BaseController
return $excelErrorData;
}
} catch (\Exception $e) {
- // Handle any exceptions
+ // Handle any exceptions
$errorMessage = $e->getMessage(); //die();
$this->myLogger->logme('error', $errorMessage);
return false; // You can return an error response here
@@ -6471,10 +7081,10 @@ class LeadsController extends BaseController
// Get file data from the database
$file_data = $this->leadFilesModel->where('lead_id', $lead_id)->where('type', 2)->where('is_active', 1)->first();
- $error = json_decode($file_data['error_data']);
+ $error = json_decode($file_data['error_data']);
// Check if the file exists
- if (!$file_data) {
+ if (! $file_data) {
$error_message = "File not found";
$this->myLogger->logme('error', $error_message . ' for file id ' . $lead_id);
return $error_message;
@@ -6484,7 +7094,7 @@ class LeadsController extends BaseController
$filePath = WRITEPATH . '/uploads/lead_files/' . $fileName;
// Check if the file exists
- if (!file_exists($filePath)) {
+ if (! file_exists($filePath)) {
$error_message = "File not found";
$this->myLogger->logme('error', $error_message . ' for file id ' . $lead_id);
$data['message'] = 'Physical File Not Found';
@@ -6493,7 +7103,7 @@ class LeadsController extends BaseController
// Load the Excel file
$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($filePath);
- $sheet = $spreadsheet->getActiveSheet();
+ $sheet = $spreadsheet->getActiveSheet();
foreach ($error->error_data as $index => $error_data) {
@@ -6507,36 +7117,34 @@ class LeadsController extends BaseController
$originalValue = $sheet->getCell([$colIndex, $rowIndex])->getValue();
- $newValue = implode(', ', $value->error);
- $val = $originalValue . ' ( ' . $newValue . ' )';
- $sheet->setCellValue([$colIndex, $rowIndex], $val);
+ $newValue = implode(', ', $value->error);
+ $val = $originalValue . ' ( ' . $newValue . ' )';
+ $sheet->setCellValue([$colIndex, $rowIndex], $val);
$style = [
'fill' => [
- 'fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID,
- 'startColor' => ['rgb' => 'ffad99'] // Red color
- ]
+ 'fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID,
+ 'startColor' => ['rgb' => 'ffad99'], // Red color
+ ],
];
$sheet->getStyle([$colIndex, $rowIndex])->applyFromArray($style);
}
} else if ($error->error_type == 2) {
-
foreach ($error_data as $key => $value) {
-
$originalValue = $sheet->getCell([1, $rowIndex])->getValue();
- $newValue = implode(', ', $value->error);
- $val = $originalValue . ' ( ' . $newValue . ' )';
- $sheet->setCellValue([$colIndex, $rowIndex], $val);
+ $newValue = implode(', ', $value->error);
+ $val = $originalValue . ' ( ' . $newValue . ' )';
+ $sheet->setCellValue([$colIndex, $rowIndex], $val);
$style = [
'fill' => [
- 'fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID,
- 'startColor' => ['rgb' => 'ffad99'] // Red color
- ]
+ 'fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID,
+ 'startColor' => ['rgb' => 'ffad99'], // Red color
+ ],
];
$sheet->getStyle([$colIndex, $rowIndex])->applyFromArray($style);
}
@@ -6548,7 +7156,7 @@ class LeadsController extends BaseController
// Save the modified Excel file to a new location
$newFilePath = WRITEPATH . '/uploads/lead_files/' . $newFileName;
- $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
+ $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
$writer->save($newFilePath);
// Set headers to force download
@@ -6580,17 +7188,17 @@ class LeadsController extends BaseController
return $this->respond([
'status' => false,
'code' => 400,
- 'message' => 'Opportunity ID is required'
+ 'message' => 'Opportunity ID is required',
], 400);
}
- $lead_id = $params['lead_id'];
+ $lead_id = $params['lead_id'];
$proposal_insurer = $params['proposal_insurer'] ?? '';
// Handle proposal and insurer details
- if (!empty($proposal_insurer) && strpos($proposal_insurer, '-') !== false) {
+ if (! empty($proposal_insurer) && strpos($proposal_insurer, '-') !== false) {
list($proposal_key, $insurer_key) = explode('-', $proposal_insurer, 2);
- $lead_update_data = json_encode([
+ $lead_update_data = json_encode([
'proposel_name' => $proposal_key,
'insurer_name' => $insurer_key,
'insurer' => $params['insurer_and_branch'] ?? null,
@@ -6603,8 +7211,8 @@ class LeadsController extends BaseController
$data = [
'proposel_data' => $lead_update_data,
- 'placement_date' => !empty($params['placement_date']) ? change_date_format($params['placement_date']) : null,
- 'payment_date' => !empty($params['payment_date']) ? change_date_format($params['payment_date']) : null,
+ 'placement_date' => ! empty($params['placement_date']) ? change_date_format($params['placement_date']) : null,
+ 'payment_date' => ! empty($params['payment_date']) ? change_date_format($params['payment_date']) : null,
'utr_no' => $params['utr_no'] ?? null,
'is_cd' => $params['is_cd'] ?? null,
'premium_amount' => $params['premium_amount'] ?? null,
@@ -6619,7 +7227,7 @@ class LeadsController extends BaseController
$lead_data = $this->leadsModel->where('id', $lead_id)->first();
// Compare and update only if changed the start and end date
- if (!empty($params['policy_start_date'])) {
+ if (! empty($params['policy_start_date'])) {
$converted_start = change_date_format($params['policy_start_date']);
if ($converted_start !== $lead_data['policy_start_date']) {
$data['policy_start_date'] = $converted_start;
@@ -6627,7 +7235,7 @@ class LeadsController extends BaseController
}
}
- if (!empty($params['policy_end_date'])) {
+ if (! empty($params['policy_end_date'])) {
$converted_end = change_date_format($params['policy_end_date']);
if ($converted_end !== $lead_data['policy_end_date']) {
$data['policy_end_date'] = $converted_end;
@@ -6636,10 +7244,10 @@ class LeadsController extends BaseController
}
// Handle TPA details
- if (!empty($params['tpa_id']) && strpos($params['tpa_id'], '-') !== false) {
+ if (! empty($params['tpa_id']) && strpos($params['tpa_id'], '-') !== false) {
list($tpaBranchId, $tpaId) = explode('-', $params['tpa_id']);
- $data['tpa_branch_id'] = $tpaBranchId;
- $data['tpa_id'] = $tpaId;
+ $data['tpa_branch_id'] = $tpaBranchId;
+ $data['tpa_id'] = $tpaId;
$this->myLogger->logme('error', "TPA details added: branch=$tpaBranchId, id=$tpaId");
}
@@ -6650,19 +7258,19 @@ class LeadsController extends BaseController
$this->myLogger->logme('error', "Lead updated successfully for ID: $lead_id");
// Save installment details
- if (!empty($params['installments'])) {
+ if (! empty($params['installments'])) {
$installments = json_decode($params['installments'], true);
$this->myLogger->logme('error', "Installments data received: " . json_encode($installments));
- if (is_array($installments) && !empty($installments)) {
+ if (is_array($installments) && ! empty($installments)) {
foreach ($installments as $installment) {
- $installment['payment_date'] = !empty($installment['payment_date']) && strtotime($installment['payment_date'])
+ $installment['payment_date'] = ! empty($installment['payment_date']) && strtotime($installment['payment_date'])
? date('Y-m-d', strtotime($installment['payment_date']))
: null;
$installment['lead_id'] = $lead_id;
- if (!empty($installment['id'])) {
+ if (! empty($installment['id'])) {
$this->leadInstallmentPaymentDetails->update($installment['id'], $installment);
$this->myLogger->logme('error', "Installment updated: " . json_encode($installment));
} else {
@@ -6690,7 +7298,7 @@ class LeadsController extends BaseController
'message' => 'Placement data saved successfully. File being validated',
'lead_id' => $lead_id,
'data' => $data,
- 'params' => $params
+ 'params' => $params,
], 200);
} catch (\Exception $e) {
@@ -6705,7 +7313,7 @@ class LeadsController extends BaseController
'status' => false,
'code' => 500,
'message' => 'Error while validating the member data',
- 'error' => $errorDetails
+ 'error' => $errorDetails,
], 500);
}
}
@@ -6717,7 +7325,7 @@ class LeadsController extends BaseController
return $this->respond([
'status' => false,
'code' => 400,
- 'message' => 'lead_id is required'
+ 'message' => 'lead_id is required',
], 400);
}
@@ -6728,11 +7336,11 @@ class LeadsController extends BaseController
->where('type', 2)
->first();
- if (!$lead_file) {
+ if (! $lead_file) {
return $this->respond([
'status' => false,
'code' => 404,
- 'message' => 'No file found for this lead_id'
+ 'message' => 'No file found for this lead_id',
], 404);
}
@@ -6742,7 +7350,7 @@ class LeadsController extends BaseController
'status' => true,
'code' => 202, // Accepted - still processing
'message' => 'Validation in progress',
- 'data' => ['status' => $lead_file['status']]
+ 'data' => ['status' => $lead_file['status']],
], 200);
}
@@ -6751,12 +7359,10 @@ class LeadsController extends BaseController
'status' => true,
'code' => 200,
'message' => 'Validation completed',
- 'data' => $lead_file
+ 'data' => $lead_file,
], 200);
}
-
// ----------- END OF MEMBER DATA VALIDAATION ------------------------------------------------------------------------------------------------------
-
}
diff --git a/app/Controllers/MediAssistApiController.php b/app/Controllers/MediAssistApiController.php
index a59c2637..05770e6f 100644
--- a/app/Controllers/MediAssistApiController.php
+++ b/app/Controllers/MediAssistApiController.php
@@ -141,7 +141,7 @@ class MediAssistApiController extends BaseController
$this->db->table('ticket_master')
->where('id',$claimId)
->update([ 'tpa_push_response' => json_encode($response) ]);
- return;
+ return ['status' => false, 'message' => 'Claim Push FAILED', 'response' => $response];
}
// return $this->response->setJSON($response);
@@ -156,11 +156,11 @@ class MediAssistApiController extends BaseController
->where('id',$claimId)
->update([ 'tpa_claim_push_reference_no' => $claimRef ]);
- return;
+ return ['status' => true, 'message' => 'Claim Push SUCCESS', 'response' => $response];
} else {
log_message('error','MEDI_ASSIST - Claim Push API Failed | claimReferenceNo EMPTY | claimId: '.$claimId.' | response: '.json_encode($response));
- return;
+ return ['status' => false, 'message' => 'Claim Push API Failed', 'response' => $response];
}
}
diff --git a/app/Controllers/PolicyTransactionController.php b/app/Controllers/PolicyTransactionController.php
index 59c115fe..c762866e 100644
--- a/app/Controllers/PolicyTransactionController.php
+++ b/app/Controllers/PolicyTransactionController.php
@@ -317,8 +317,8 @@ class PolicyTransactionController extends BaseController
'col_cell_name' => 'Q',
'col_name' => 'Base Premium',
'is_mandatory' => false,
- 'data_type' => '',
- 'format' => null,
+ 'data_type' => 'positive_number',
+ 'format' => 'positive_number',
'allowed_values' => null,
'custom' => null,
'params' => null
@@ -329,8 +329,8 @@ class PolicyTransactionController extends BaseController
'col_cell_name' => 'R',
'col_name' => 'Non commission permium Amount',
'is_mandatory' => false,
- 'data_type' => '',
- 'format' => null,
+ 'data_type' => 'positive_number',
+ 'format' => 'positive_number',
'allowed_values' => null,
'custom' => null,
'params' => null
@@ -341,8 +341,8 @@ class PolicyTransactionController extends BaseController
'col_cell_name' => 'S',
'col_name' => 'TP Premium',
'is_mandatory' => false,
- 'data_type' => '',
- 'format' => null,
+ 'data_type' => 'positive_number',
+ 'format' => 'positive_number',
'allowed_values' => null,
'custom' => null,
'params' => null
@@ -353,8 +353,8 @@ class PolicyTransactionController extends BaseController
'col_cell_name' => 'T',
'col_name' => 'IGST',
'is_mandatory' => false,
- 'data_type' => '',
- 'format' => null,
+ 'data_type' => 'positive_number',
+ 'format' => 'positive_number',
'allowed_values' => null,
'custom' => 'check_gst_percentage',
'params' => ['row']
@@ -365,8 +365,8 @@ class PolicyTransactionController extends BaseController
'col_cell_name' => 'U',
'col_name' => 'CGST',
'is_mandatory' => false,
- 'data_type' => '',
- 'format' => null,
+ 'data_type' => 'positive_number',
+ 'format' => 'positive_number',
'allowed_values' => null,
'custom' => 'check_gst_percentage',
'params' => ['row']
@@ -377,8 +377,8 @@ class PolicyTransactionController extends BaseController
'col_cell_name' => 'V',
'col_name' => 'SGST',
'is_mandatory' => false,
- 'data_type' => '',
- 'format' => null,
+ 'data_type' => 'positive_number',
+ 'format' => 'positive_number',
'allowed_values' => null,
'custom' => 'check_gst_percentage',
'params' => ['row']
@@ -390,8 +390,8 @@ class PolicyTransactionController extends BaseController
'col_cell_name' => 'W',
'col_name' => 'Stamp Duty',
'is_mandatory' => false,
- 'data_type' => '',
- 'format' => null,
+ 'data_type' => 'positive_number',
+ 'format' => 'positive_number',
'allowed_values' => null,
'custom' => null,
'params' => null
@@ -414,8 +414,8 @@ class PolicyTransactionController extends BaseController
'col_cell_name' => 'X',
'col_name' => 'Agreed Amount',
'is_mandatory' => false,
- 'data_type' => '',
- 'format' => null,
+ 'data_type' => 'positive_number',
+ 'format' => 'positive_number',
'allowed_values' => null,
'custom' => null,
'params' => null
@@ -426,8 +426,8 @@ class PolicyTransactionController extends BaseController
'col_cell_name' => 'Y',
'col_name' => 'Agreed BP Percentage',
'is_mandatory' => false,
- 'data_type' => '',
- 'format' => null,
+ 'data_type' => 'positive_number',
+ 'format' => 'positive_number',
'allowed_values' => null,
'custom' => null,
'params' => null
@@ -438,8 +438,8 @@ class PolicyTransactionController extends BaseController
'col_cell_name' => 'Z',
'col_name' => 'Agreed TP Percentage',
'is_mandatory' => false,
- 'data_type' => '',
- 'format' => null,
+ 'data_type' => 'positive_number',
+ 'format' => 'positive_number',
'allowed_values' => null,
'custom' => null,
'params' => null
@@ -6098,8 +6098,189 @@ class PolicyTransactionController extends BaseController
return array('status' => false, 'message' => 'file_id is required');
}
- $this->policyTransactionModel->select()->findAll();
+ $data['is_active'] = 0;
+ $this->policyTransactionModel->where('file_id', $file_id)->set($data)->update();
+ $this->PTCOShareDetailsModel->where('file_id', $file_id)->set($data)->update();
+ return $this->respond(['status' => true, 'code' => 200, 'message' => 'BDS bulk upload data truncated successfully'], 200);
+ }
+
+ // ------------------------------------------------------------------------------------------------------------------
+
+ /**
+ * Cron job: Daily BDS Report
+ * Fetches today's BDS entries, generates Excel (matching report_bds.php column order), and emails to recipients from .env.
+ * Recipients: comma-separated emails in bds.reportEmails
+ * File stored temporarily in writable/tmp/ and deleted after sending.
+ */
+ public function cronDailyBDSReport()
+ {
+
+ helper('excel_import_export_helper');
+
+ $filePath = null;
+ try {
+
+ $today = date('Y-m-d', strtotime('-1 day'));
+ $reportList = $this->policyTransactionModel->getBDSReportList($today, $today,0,0,0,'created_at',0,0,0,0,0,[]);
+
+ if (empty($reportList)) {
+ $this->myLogger->logme('error', "cronDailyBDSReport: No BDS records for {$today}");
+ return $this->respond(['status' => 'success', 'message' => 'No BDS records for today. No report sent.'], 200);
+ }
+
+ // Column headers exactly matching report_bds.php order (including display:none columns)
+ $headers = [
+ 'S. No', 'User', 'Month', 'Business Type', 'Client Type', 'Insured Name', 'Transaction Type',
+ 'Policy Type', 'BAP Group', 'Vehicle Number', 'Policy No', 'Endorsement No', 'Insurer Branch',
+ 'Endorsement Effective Date', 'Policy Effective Date', 'Policy Expiry Date', 'Reference', 'Remarks',
+ 'BP Premium', 'TP Premium', 'Premium (without GST)', 'Total Premium', 'Agreed BP %', 'Agreed TP %',
+ 'Rewards', 'Agreed Amount', 'Invoiced Amount', 'Outstanding Amount',
+ 'Salse Person', 'Service Person', 'Salse Person Branch', 'Installment', 'Data Received Date', 'Renewal Date',
+ 'Co-Premium', 'Remuneration Pay By Leader', 'Salse Person Manager', 'Service Person Manager',
+ 'Service Person Branch', 'Rollover Date', 'Policyholder Name', 'Insured (Same as Proposer)',
+ 'Follower Policy No', 'Co-Share %', 'Non Commissional Premium Amount', 'CGST', 'SGST', 'IGST',
+ 'Stamp Duty', 'Standard BP %', 'Standard TP %', 'Actual BP Amount', 'Actual TP Amount',
+ 'Actual BP %', 'Actual TP %', 'Actual BP Remuneration Amount', 'Actual TP Remuneration Amount',
+ 'CD Account No'
+ ];
+
+ $excelData = [];
+ foreach ($reportList as $idx => $row) {
+ $totalIrda = (float)($row['total_irda_amt'] ?? 0);
+ $billedAmt = (float)($row['billed_amt'] ?? 0);
+ $unbilledAmt = $totalIrda - $billedAmt;
+ if ($totalIrda == 0) {
+ $unbilledAmt = abs($unbilledAmt);
+ }
+ $unbilledAmt = ($unbilledAmt == 0 && $billedAmt == 0) ? $totalIrda : $unbilledAmt;
+
+ $hasIrda = ($totalIrda != 0);
+
+ $excelData[] = [
+ $idx + 1,
+ $row['user_name'] ?? 'N/A',
+ $row['policy_issue_month'] ?? 'N/A',
+ $row['revenue_type'] ?? 'N/A',
+ $row['client_type'] ?? 'N/A',
+ $row['client_name'] ?? 'N/A',
+ $row['action_type'] ?? 'N/A',
+ $row['policy_type'] ?? 'N/A',
+ $row['bap'] ?? 'N/A',
+ $row['vehicle_no'] ?? 'N/A',
+ $row['policy_no'] ?? 'N/A',
+ $row['endorsement_no'] ?? 'N/A',
+ $row['insurer_branch_name'] ?? 'N/A',
+ !empty($row['endorse_eff_date']) ? change_date_format($row['endorse_eff_date'], 'Y-m-d', 'd/m/Y') : 'N/A',
+ !empty($row['policy_start_date']) ? change_date_format($row['policy_start_date'], 'Y-m-d', 'd/m/Y') : 'N/A',
+ !empty($row['policy_end_date']) ? change_date_format($row['policy_end_date'], 'Y-m-d', 'd/m/Y') : 'N/A',
+ $row['ref'] ?? 'N/A',
+ $row['remarks'] ?? 'N/A',
+ $hasIrda ? ($row['bp_amt'] ?? '0.00') : '0.00',
+ $hasIrda ? ($row['tp_or_ter'] ?? '0.00') : '0.00',
+ $hasIrda ? ($row['premium_wo_gst'] ?? '0.00') : '0.00',
+ $hasIrda ? ($row['total_premium'] ?? '0.00') : '0.00',
+ $hasIrda ? ($row['agreed_bp_per'] ?? '0.00') . '%' : '0.00%',
+ $hasIrda ? ($row['agreed_tp_or_ter_per'] ?? '0.00') . '%' : '0.00%',
+ $row['reward'] ?? '0.00',
+ $row['total_irda_amt'] ?? '0.00',
+ !empty($row['billed_amt']) ? $row['billed_amt'] : '0.00',
+ number_format((float)$unbilledAmt, 2, '.', ''),
+ $row['salse_person_name'] ?? 'N/A',
+ $row['service_person_name'] ?? 'N/A',
+ $row['nhance_branch'] ?? 'N/A',
+ $row['installment'] ?? 'N/A',
+ !empty($row['data_received_date']) ? change_date_format($row['data_received_date'], 'Y-m-d', 'd/m/Y') : 'N/A',
+ !empty($row['renewal_date']) ? change_date_format($row['renewal_date'], 'Y-m-d', 'd/m/Y') : 'N/A',
+ $row['co_share'] ?? 'No',
+ $row['bro_payable_by'] ?? 'No',
+ $row['salse_manager_name'] ?? 'N/A',
+ $row['service_manager_name'] ?? 'N/A',
+ $row['service_branch'] ?? 'N/A',
+ !empty($row['rollover_date']) ? change_date_format($row['rollover_date'], 'Y-m-d', 'd/m/Y') : 'N/A',
+ $row['policy_holder_name'] ?? 'N/A',
+ $row['same_as_proposer'] ?? 'No',
+ $row['follower_policy_no'] ?? 'N/A',
+ number_format((float)($row['co_share_per'] ?? 0), 2),
+ number_format((float)($row['non_comm_per_amt'] ?? 0), 2),
+ number_format((float)($row['bp_cgst'] ?? 0), 2),
+ number_format((float)($row['bp_sgst'] ?? 0), 2),
+ number_format((float)($row['bp_igst'] ?? 0), 2),
+ number_format((float)($row['stamp_duty'] ?? 0), 2),
+ number_format((float)($row['standerd_bp_per'] ?? 0), 2),
+ number_format((float)($row['standerd_tp_per'] ?? 0), 2),
+ number_format((float)($row['actual_bp_amt'] ?? 0), 2),
+ number_format((float)($row['actual_tp_amt'] ?? 0), 2),
+ number_format((float)($row['actual_bp_per'] ?? 0), 2),
+ number_format((float)($row['actual_tp_per'] ?? 0), 2),
+ number_format((float)($row['actual_tep_brokerage_amt'] ?? 0), 2),
+ number_format((float)($row['actual_tp_brokerage_amt'] ?? 0), 2),
+ $row['cd_ac_no'] ?? 'N/A'
+ ];
+ }
+
+ $today = date('d-m-Y', strtotime($today));
+ $fileName = 'BDS_Daily_Report_' . $today . '.xlsx';
+ $tmpDir = WRITEPATH . 'tmp' . DIRECTORY_SEPARATOR;
+ if (!is_dir($tmpDir)) {
+ mkdir($tmpDir, 0755, true);
+ }
+ $filePath = $tmpDir . $fileName;
+
+ $generated = generate_excel($headers, $excelData, $filePath);
+ if (!$generated) {
+ $this->myLogger->logme('error', 'cronDailyBDSReport: Excel generation failed');
+ return $this->respond(['status' => false, 'message' => 'Excel generation failed'], 500);
+ }
+
+ $emailList = getenv('bds.dailyReportEmails') ?: '';
+ $recipientEmails = array_filter(array_map('trim', explode(',', $emailList)));
+ if (empty($recipientEmails)) {
+ @unlink($filePath);
+ $this->myLogger->logme('error', 'cronDailyBDSReport: No recipients in bds.dailyReportEmails. Report generated but not sent.');
+ return $this->respond([
+ 'status' => 'success',
+ 'message' => 'Report generated. No recipients configured (set bds.dailyReportEmails in .env).',
+ 'file' => $fileName
+ ], 200);
+ }
+
+ $subject = "BDS Report Up to - {$today}";
+ $message = "Please find attached the BDS report up to {$today}.
";
+ $message .= "Total records: " . count($reportList) . "
";
+
+ $attachments = [
+ ['filePath' => $filePath, 'fileName' => $fileName]
+ ];
+
+ $res = MailHelper::send_email([
+ 'mail' => $recipientEmails,
+ 'subject' => $subject,
+ 'message' => $message,
+ 'attachments' => $attachments
+ ]);
+
+ @unlink($filePath);
+
+ $resDecoded = is_string($res) ? json_decode($res, true) : $res;
+ if (isset($resDecoded['status']) && $resDecoded['status'] === 'success') {
+ $this->myLogger->logme('error', "cronDailyBDSReport: Report sent to " . count($recipientEmails) . " recipients");
+ return $this->respond([
+ 'status' => true,
+ 'message' => 'Report generated and emailed successfully.',
+ 'recipients' => count($recipientEmails)
+ ], 200);
+ }
+
+ $this->myLogger->logme('error', 'cronDailyBDSReport: Email send failed - ' . json_encode($resDecoded));
+ return $this->respond(['status' => false, 'message' => 'Report generated but email send failed'], 500);
+ } catch (Exception $e) {
+ if ($filePath && is_file($filePath)) {
+ @unlink($filePath);
+ }
+ $this->myLogger->logme('error', 'cronDailyBDSReport Exception: ' . $e->getMessage());
+ return $this->respond(['status' => false, 'message' => $e->getMessage()], 500);
+ }
}
}
diff --git a/app/Controllers/SalesController.php b/app/Controllers/SalesController.php
index 164444e9..39a0f672 100644
--- a/app/Controllers/SalesController.php
+++ b/app/Controllers/SalesController.php
@@ -53,7 +53,6 @@ class SalesController extends BaseController
->orderBy('lead_id', 'DESC')
->findAll();
-
return $this->loadLayout('sales/activity_view', $data);
}
@@ -66,9 +65,14 @@ class SalesController extends BaseController
return $this->loadLayout('sales/target_view', $data);
}
- /**
- * HELPER: Fetches Sales Managers based on the logged-in user's role and branch
- */
+ /**
+ * HELPER: Fetches Sales Managers based on the logged-in user's role and branch
+ * sales_manager Current branch | Role 4 + Team 5 | Assign To dropdown
+ * sales_manager_ids Current branch | Role 4 + Team 5 | Query filter IDs
+ * sales_manager_with_head Current branch | Role 1,4,5 | Branch reporting dropdown
+ * sales_manager_with_head_ids Current branch | Role 1,4,5 | Branch reporting filter
+ * sales_team All branches | Role 1,4,5 | Admin/global reporting
+ */
private function getSalesStaffData(): array
{
$db = \Config\Database::connect();
@@ -76,54 +80,118 @@ class SalesController extends BaseController
$role = get_role_id();
$team_id = user_team();
+ // ── Get logged-in user's profile ────────────────────────────────
+ $row = $db->table('user_profiles')
+ ->where('is_active', 1)
+ ->where('id', $logged_user_id)
+ ->get()->getRow();
+
+ $nhance_branch_id = $row ? $row->nhance_branch_id : null;
+
+ // ── Base result structure ────────────────────────────────────────
$data = [
- 'users' => [],
- 'sales_manager_ids'=> [],
- 'sales_role' => '',
- 'nhance_branch_id' => null,
- 'assigned_ids' => [],
+ 'sales_role' => '',
+ 'sales_manager' => [],
+ 'sales_manager_ids' => [],
+ 'sales_manager_with_head' => [],
+ 'sales_manager_with_head_ids' => [],
+ 'sales_team' => [],
+ 'nhance_branch_id' => $nhance_branch_id,
];
- $row = $db->table('user_profiles')->select('*')
- ->where('is_active', 1)->where('id', $logged_user_id)
- ->get()->getRow();
+ // ================================================================
+ // QUERY 1: Get all MANAGERS in current branch
+ // Role = 4 AND Team = 5 AND same branch
+ // ================================================================
+ $branch_managers = $db->table('user_profiles up')
+ ->select('up.id, up.first_name, up.role, up.nhance_branch_id')
+ ->join('user_teams ut', 'ut.user_id = up.id')
+ ->where('up.is_active', 1)
+ ->where('ut.is_active', 1)
+ ->where('up.role', 4) // Sales Manager role
+ ->where('ut.team_id', 5) // Sales team
+ ->where('up.nhance_branch_id', $nhance_branch_id) // same branch
+ ->groupBy('up.id')
+ ->get()->getResultArray();
- $nhance_branch_id = $row ? $row->nhance_branch_id : null;
- $data['nhance_branch_id']= $nhance_branch_id;
+ // ================================================================
+ // QUERY 2: Get all HEADS in current branch
+ // Role = 1 or 5 AND same branch
+ // ================================================================
+ $branch_heads = $db->table('user_profiles')
+ ->select('id, first_name, role, nhance_branch_id')
+ ->where('is_active', 1)
+ ->whereIn('role', [1, 5]) // Sales Head roles
+ ->where('nhance_branch_id', $nhance_branch_id) // same branch
+ ->get()->getResultArray();
- // ── Sales Manager (Role 4, Team 5) ──────────────────────────
+ // Add "(Head)" label to heads so dropdown is clear
+ foreach ($branch_heads as &$head) {
+ $head['first_name'] = $head['first_name'] . ' (Head)';
+ }
+ unset($head);
+
+ // ================================================================
+ // QUERY 3: Get ALL MANAGERS across ALL branches
+ // Role = 4 AND Team = 5 (no branch filter)
+ // ================================================================
+ $all_managers = $db->table('user_profiles up')
+ ->select('up.id, up.first_name, up.role, up.nhance_branch_id')
+ ->join('user_teams ut', 'ut.user_id = up.id')
+ ->where('up.is_active', 1)
+ ->where('ut.is_active', 1)
+ ->where('up.role', 4) // Sales Manager role
+ ->where('ut.team_id', 5) // Sales team
+ ->groupBy('up.id')
+ ->get()->getResultArray();
+
+ // ================================================================
+ // QUERY 4: Get ALL HEADS across ALL branches
+ // Role = 1 or 5 (no branch filter)
+ // ================================================================
+ $all_heads = $db->table('user_profiles')
+ ->select('id, first_name, role, nhance_branch_id')
+ ->where('is_active', 1)
+ ->whereIn('role', [1, 5]) // Sales Head roles
+ ->get()->getResultArray();
+
+ // Add "(Head)" label to all heads
+ foreach ($all_heads as &$head) {
+ $head['first_name'] = $head['first_name'] . ' (Head)';
+ }
+ unset($head);
+
+ // ================================================================
+ // BUILD: sales_manager_with_head = branch heads + branch managers
+ // ================================================================
+ $data['sales_manager_with_head'] = array_merge($branch_heads, $branch_managers);
+ $data['sales_manager_with_head_ids'] = array_column($data['sales_manager_with_head'], 'id');
+
+ // ================================================================
+ // BUILD: sales_team = all heads + all managers (every branch)
+ // ================================================================
+ $data['sales_team'] = array_merge($all_heads, $all_managers);
+
+ // ── Sales Manager (Role 4, Team 5) ──────────────────────────────
if ($role == 4 && in_array(5, $team_id)) {
$data['sales_role'] = 'Sales Manager';
+ $data['sales_manager'] = [[ // only himself
+ 'id' => $row->id,
+ 'first_name' => $row->first_name,
+ 'role' => $role,
+ 'nhance_branch_id' => $nhance_branch_id,
+ ]];
$data['sales_manager_ids'] = [$logged_user_id];
- $data['assigned_ids'] = [$logged_user_id];
- $data['users'] = [
- [
- 'id' => $row->id,
- 'first_name' => $row->first_name,
- 'last_name' => $row->last_name ?? '',
- 'nhance_branch_id' => $nhance_branch_id,
- ]
- ];
- // ── Sales Head (Role 1 or 5) ─────────────────────────────────
+ // ── Sales Head (Role 1 or 5) ─────────────────────────────────────
} elseif (in_array($role, [1, 5])) {
- $data['sales_role'] = 'Sales Head';
- $data['users'] = $db->table('user_profiles up')
- ->select('up.id, up.first_name, up.last_name, up.nhance_branch_id')
- ->join('user_teams ut', 'ut.user_id = up.id')
- ->where('up.is_active', 1)
- ->where('ut.is_active', 1)
- ->where('up.role', 4)
- ->where('ut.team_id', 5)
- ->where('up.nhance_branch_id', $nhance_branch_id)
- ->get()
- ->getResultArray();
-
- $ids = array_column($data['users'], 'id');
- $data['sales_manager_ids'] = $ids;
- $data['assigned_ids'] = $ids; // same value, both available
+ $data['sales_role'] = 'Sales Head';
+ $data['sales_manager'] = $branch_managers; // reuse QUERY 1 result
+ $data['sales_manager_ids'] = array_column($branch_managers, 'id');
+ $data['sales_manager_with_head'] = array_merge($branch_heads, $branch_managers); // reuse
+ $data['sales_manager_with_head_ids'] = array_column($data['sales_manager_with_head'], 'id');
}
return $data;
@@ -149,6 +217,9 @@ class SalesController extends BaseController
echo view('layout/footer', $data);
}
+ /**
+ * GET /api/sales/activities/(:num)/complete
+ */
public function completeActivity($id) {
try {
$data = $this->request->getJSON(true);
@@ -236,7 +307,8 @@ class SalesController extends BaseController
'data' => $result['data'],
'total' => $result['total'],
'limit' => $limit,
- 'offset' => $offset
+ 'offset' => $offset,
+ 'counts' => $result['counts'],
]);
} catch (\Exception $e) {
return $this->fail($e->getMessage(), ResponseInterface::HTTP_INTERNAL_SERVER_ERROR);
@@ -398,6 +470,15 @@ class SalesController extends BaseController
$data = $this->request->getJSON(true);
$data['updated_by'] = $this->getUserId();
+ $contact = $this->contactModel->find($id);
+
+ if (isset($data['is_primary']) && $data['is_primary'] == 1) {
+ // Reset all contacts for this lead to 0 primary
+ $this->contactModel->where('lead_id', $contact['lead_id'])
+ ->set(['is_primary' => 0])
+ ->update();
+ }
+
if (!$this->contactModel->update((int)$id, $data)) {
return $this->fail($this->contactModel->errors(), ResponseInterface::HTTP_BAD_REQUEST);
}
@@ -487,7 +568,8 @@ class SalesController extends BaseController
'data' => $result['data'],
'total' => $result['total'],
'limit' => $limit,
- 'offset' => $offset
+ 'offset' => $offset,
+ 'counts' => $result['counts'],
], 200);
} catch (\Exception $e) {
@@ -565,6 +647,11 @@ class SalesController extends BaseController
$data['created_by'] = $this->getUserId();
$data['updated_by'] = $this->getUserId();
+ // FIX: Convert the array to a JSON string so it fits in the VARCHAR column
+ if (isset($data['additional_assigned_ids']) && is_array($data['additional_assigned_ids'])) {
+ $data['additional_assigned_ids'] = json_encode($data['additional_assigned_ids']);
+ }
+
if (!$this->activityModel->insert($data)) {
return $this->fail($this->activityModel->errors(), ResponseInterface::HTTP_BAD_REQUEST);
}
@@ -575,6 +662,11 @@ class SalesController extends BaseController
$activityId = $this->activityModel->getInsertID();
$activity = $this->activityModel->find((int)$activityId);
+ // OPTIONAL: Decode it back to an array for the API response so the frontend gets a clean array
+ if (isset($activity['additional_assigned_ids'])) {
+ $activity['additional_assigned_ids'] = json_decode($activity['additional_assigned_ids'], true);
+ }
+
return $this->respondCreated([
'status' => 'success',
'message' => 'Activity created successfully',
@@ -600,12 +692,22 @@ class SalesController extends BaseController
$data = $this->request->getJSON(true);
$data['updated_by'] = $this->getUserId();
+ // FIX: Convert the array to a JSON string for updating
+ if (isset($data['additional_assigned_ids']) && is_array($data['additional_assigned_ids'])) {
+ $data['additional_assigned_ids'] = json_encode($data['additional_assigned_ids']);
+ }
+
if (!$this->activityModel->update($id, $data)) {
return $this->fail($this->activityModel->errors(), ResponseInterface::HTTP_BAD_REQUEST);
}
$activity = $this->activityModel->find((int)$id);
+ // OPTIONAL: Decode it back to an array for the API response
+ if (isset($activity['additional_assigned_ids'])) {
+ $activity['additional_assigned_ids'] = json_decode($activity['additional_assigned_ids'], true);
+ }
+
return $this->respond([
'status' => 'success',
'message' => 'Activity updated successfully',
@@ -927,252 +1029,896 @@ class SalesController extends BaseController
// ==================== Dashboard ====================
- public function dashboard()
- {
- $payload = $this->request->getGet();
- $base = $this->getSalesStaffData();
- $salesRole = $base['sales_role'];
- $salesManagerIds = $base['sales_manager_ids'];
- $userId = get_session_userid();
- // Get branch id from users array
- $nhanceBranchId = $base['users'][0]['nhance_branch_id'] ?? null;
+// ─────────────────────────────────────────────
+// HELPER: Build FY date range from fy_year string
+// e.g. "2024-2025" → ['2024-04-01 00:00:00', '2025-03-31 23:59:59']
+// ─────────────────────────────────────────────
+private function getFYDateRange(string $financialYear): array
+{
+ // Format: "2025-2026" — split on last hyphen to get start=2025, end=2026
+ $pos = strrpos($financialYear, '-');
+ $startYear = substr($financialYear, 0, $pos); // "2025"
+ $endYear = substr($financialYear, $pos + 1); // "2026"
- if ($salesRole === 'Sales Head') {
- $this->branchLevelDashboard($nhanceBranchId, $salesManagerIds);
- } elseif ($salesRole === 'Sales Manager') {
- $this->salesManagerLevelDashboard($userId, $salesManagerIds,$payload);
- }
- }
+ return [
+ 'start' => $startYear . '-04-01 00:00:00', // 2025-04-01 00:00:00
+ 'end' => $endYear . '-03-31 23:59:59', // 2026-03-31 23:59:59
+ ];
+}
- public function branchLevelDashboard($branchId,$sales_manager_ids)
- {
- // Hardcoded branch ID as requested
- // $branchId = 1;
+// ─────────────────────────────────────────────
+// HELPER: FY quarters (Apr-Jun / Jul-Sep / Oct-Dec / Jan-Mar)
+// ─────────────────────────────────────────────
+private function getFYQuarters(string $financialYear): array
+{
+ $pos = strrpos($financialYear, '-');
+ $sy = (int)substr($financialYear, 0, $pos); // 2025
+ $ey = (int)substr($financialYear, $pos + 1); // 2026
- try {
- $sales_manager_ids = array_values(array_map('intval', $sales_manager_ids));
-
- // Final safe check
- if (empty($sales_manager_ids)) {
- // No valid IDs — skip queries or return empty
- $total_leads = 0;
- $total_activity = 0;
- $total_completed_activity = 0;
- $total_pending_activity = 0;
- $pending_activities = [];
- $recent_activities = [];
- $teamPerformance = [];
-
- $leadsOverview = [];
- } else {
+ return [
+ ['name' => 'Q1', 'label' => "Q1 (Apr–Jun {$sy})", 'start' => "{$sy}-04-01", 'end' => "{$sy}-06-30"],
+ ['name' => 'Q2', 'label' => "Q2 (Jul–Sep {$sy})", 'start' => "{$sy}-07-01", 'end' => "{$sy}-09-30"],
+ ['name' => 'Q3', 'label' => "Q3 (Oct–Dec {$sy})", 'start' => "{$sy}-10-01", 'end' => "{$sy}-12-31"],
+ ['name' => 'Q4', 'label' => "Q4 (Jan–Mar {$ey})", 'start' => "{$ey}-01-01", 'end' => "{$ey}-03-31"],
+ ];
+}
- if (empty($sales_manager_ids) || !is_array($sales_manager_ids)) {
- $sales_manager_ids = array_filter((array) $sales_manager_ids); // removes null, "", 0
- }
-
- // 1. Lead Statistics
- $total_leads = $this->leadModel->whereIn('assigned_to', $sales_manager_ids)->countAllResults(); // Use countAllResults, NOT countAll
- // echo $this->leadModel->getLastQuery();die();
-
- // 2. Total activity
- $total_activity = $this->activityModel->whereIn('assigned_to', $sales_manager_ids)->countAllResults();
+// ─────────────────────────────────────────────
+// dashboard() — entry point
+// ─────────────────────────────────────────────
+public function dashboard()
+{
+ $payload = $this->request->getGet();
+ $base = $this->getSalesStaffData();
+ $salesRole = $base['sales_role'];
+ $salesManagerIds = $base['sales_manager_ids'];
+ $userId = get_session_userid();
- // 3. Completed activity
- $total_completed_activity = $this->activityModel->whereIn('assigned_to', $sales_manager_ids)->where('status', 'completed')->countAllResults();
+ // Get branch id
+ $nhanceBranchId = $base['sales_manager'][0]['nhance_branch_id'] ?? null;
- // 4. Pending activity
- $total_pending_activity = $this->activityModel->whereIn('assigned_to', $sales_manager_ids)->where('status', 'pending')->countAllResults();
-
- $db = \Config\Database::connect();
-
- // 5. Team Performance
- $teamPerformance = $db->table('user_profiles as u')
- ->select('u.first_name, u.last_name, r.role,
- (SELECT COUNT(*) FROM sales_activities WHERE assigned_to = u.id) as total_acts,
- (SELECT COUNT(*) FROM sales_activities WHERE assigned_to = u.id AND status = "completed") as done_acts')
- ->join('roles r', 'r.id = u.role')
- ->where('u.nhance_branch_id', $branchId)
- ->whereIn('u.id', $sales_manager_ids)
- ->where('u.is_active', 1)
- ->get()->getResultArray();
+ $current_fin_year = $payload['fy'] ?? getCurrentFinancialYear();
- // 6. Recent Activities (Joining for Lead Names)
- $recent_activities = $this->activityModel->select('sales_activities.*, sales_actual_leads.company_name')
- ->join('sales_actual_leads', 'sales_actual_leads.lead_id = sales_activities.lead_id')
- ->orderBy('sales_activities.scheduled_date', 'DESC')
- ->limit(6)
- ->findAll();
-
- // 7. Pending Activities (List)
- $pending_activities = $db->table('sales_activities sa')
- ->select('sa.activity_id,sa.lead_id,sa.activity_type,sa.scheduled_date,sa.status,sa.assigned_to,sal.company_name,up.first_name AS assigned_to_name,sa.notes')
- ->join('user_profiles up', 'up.id = sa.assigned_to', 'left')
- ->join('sales_actual_leads sal', 'sal.lead_id = sa.lead_id', 'left') // ✅ ADD THIS
- ->orderBy('sa.scheduled_date', 'DESC')
- ->whereIn('sa.assigned_to', $sales_manager_ids)
- ->where('sa.status', 'pending')
- ->get()->getResultArray();
+ $db = \Config\Database::connect();
- // 8. All Leads Overview
- $leadsOverview = $db->table('sales_actual_leads sal')
- ->select('sal.lead_id,sal.company_name,sal.status,up.first_name AS assigned_to,
- COUNT(DISTINCT sa.activity_id) AS activities,
- COUNT(DISTINCT l.id) AS opportunities
- ')
- ->join('user_profiles up', 'up.id = sal.assigned_to', 'left')
- ->join('sales_activities sa', 'sa.lead_id = sal.lead_id', 'left')
- ->join('leads l', 'l.actual_lead_id = sal.lead_id', 'left')
- ->groupBy('sal.lead_id, sal.company_name, sal.status, up.first_name')
- // ->having('COUNT(DISTINCT sa.activity_id) + COUNT(DISTINCT l.id) >', 0) // ← this line
- ->orderBy('sal.created_at', 'DESC')
- ->whereIn('sal.assigned_to', $sales_manager_ids)
- ->get()
- ->getResultArray();
-
- // 9. Activity BrakDown
- $activityBreakdown = $db->table('sales_activities')
- ->select("activity_type, COUNT(*) AS total, ROUND(COUNT(*) * 100.0 / {$total_activity}, 0) AS percentage", false)
- ->whereIn('assigned_to', $sales_manager_ids)
- ->groupBy('activity_type')
- ->orderBy('total', 'DESC')
- ->get()
- ->getResultArray();
- }
+ // Available FY years for dropdown
+ $fin_years_raw = $db->table('sales_target')
+ ->select('fy_year', false) // false = no backtick escaping
+ ->distinct()
+ ->orderBy('fy_year', 'DESC')
+ ->get()
+ ->getResultArray();
+
+ $fin_years = array_column($fin_years_raw, 'fy_year');
+
+ if (empty($fin_years)) {
+ $fin_years[] = $current_fin_year;
+ }
+
+ // Ensure current FY is available in list
+ if (!in_array($current_fin_year, $fin_years)) {
+ array_unshift($fin_years, $current_fin_year);
+ }
+
+ // Route by role
+ if ($salesRole === 'Sales Head') {
+ $this->branchLevelDashboard($nhanceBranchId, $salesManagerIds, $current_fin_year, $fin_years);
+ } elseif ($salesRole === 'Sales Manager') {
+ $this->salesManagerLevelDashboard($userId, $current_fin_year, $fin_years);
+ }
+}
+
+// ─────────────────────────────────────────────
+// branchLevelDashboard()
+// ─────────────────────────────────────────────
+public function branchLevelDashboard($branchId, $sales_manager_ids, $current_fin_year, $fin_years)
+{
+ try {
+ $sales_manager_ids = array_values(array_filter(array_map('intval', $sales_manager_ids)));
+
+ $db = \Config\Database::connect();
+ $fyRange = $this->getFYDateRange($current_fin_year);
+ $fyStart = $fyRange['start'];
+ $fyEnd = $fyRange['end'];
+
+ if (empty($sales_manager_ids)) {
+ // ── No team members — return empty dashboard ──
$data = [
- 'total_leads' => $total_leads,
- 'total_acts' => $total_activity,
- 'total_completed_acts' => $total_completed_activity,
- 'total_pending_acts'=> $total_pending_activity,
- 'pipeline_value' => '15.0L', // Hardcoded placeholder from PDF [cite: 14]
- 'team' => $teamPerformance,
- 'recent_acts' => $recent_activities,
- 'pending_acts' => $pending_activities,
- 'leads_overview' => $leadsOverview,
- 'activity_breakdown'=> $activityBreakdown,
- 'tab_name' => "Sales Dashboard",
- 'page_name' => "Sales Dashboard"
+ 'total_leads' => 0,
+ 'total_acts' => 0,
+ 'total_completed_acts' => 0,
+ 'total_pending_acts' => 0,
+ 'team' => [],
+ 'pending_acts' => [],
+ 'leads_overview' => [],
+ 'activity_breakdown' => [],
+ 'team_achievement' => [],
+ 'opp_achievement' => [],
+ 'fin_years' => $fin_years,
+ 'current_fin_year' => $current_fin_year,
+ 'tab_name' => 'Sales Dashboard',
+ 'page_name' => 'Sales Dashboard',
];
-
- // dd($data);
-
$this->loadLayout('sales/branch_level_dashboard_view', $data);
-
- // return view('sales/dashboard_view', $data);
-
- } catch (\Exception $e) {
- return $this->failServerError($e->getMessage());
+ return;
}
+
+ // 1. Lead count — FY filtered by created_at
+ $total_leads = $this->leadModel
+ ->whereIn('assigned_to', $sales_manager_ids)
+ ->where('created_at >=', $fyStart)
+ ->where('created_at <=', $fyEnd)
+ ->countAllResults();
+
+ // 2. Total activities — FY filtered by scheduled_date
+ $total_activity = $this->activityModel
+ ->whereIn('assigned_to', $sales_manager_ids)
+ ->where('scheduled_date >=', $fyStart)
+ ->where('scheduled_date <=', $fyEnd)
+ ->countAllResults();
+
+ // 3. Completed activities — FY filtered
+ $total_completed_activity = $this->activityModel
+ ->whereIn('assigned_to', $sales_manager_ids)
+ ->where('status', 'completed')
+ ->where('scheduled_date >=', $fyStart)
+ ->where('scheduled_date <=', $fyEnd)
+ ->countAllResults();
+
+ // 4. Pending activities — FY filtered
+ $total_pending_activity = $this->activityModel
+ ->whereIn('assigned_to', $sales_manager_ids)
+ ->where('status', 'pending')
+ ->where('scheduled_date >=', $fyStart)
+ ->where('scheduled_date <=', $fyEnd)
+ ->countAllResults();
+
+ // 5. Team Performance — subqueries FY filtered by scheduled_date
+ $teamPerformance = $db->table('user_profiles as u')
+ ->select("u.id, u.first_name, u.last_name, r.role,
+ (SELECT COUNT(*) FROM sales_activities
+ WHERE assigned_to = u.id
+ AND scheduled_date >= '{$fyStart}'
+ AND scheduled_date <= '{$fyEnd}') as total_acts,
+ (SELECT COUNT(*) FROM sales_activities
+ WHERE assigned_to = u.id AND status = 'completed'
+ AND scheduled_date >= '{$fyStart}'
+ AND scheduled_date <= '{$fyEnd}') as done_acts", false)
+ ->join('roles r', 'r.id = u.role')
+ ->where('u.nhance_branch_id', $branchId)
+ ->whereIn('u.id', $sales_manager_ids)
+ ->where('u.is_active', 1)
+ ->get()
+ ->getResultArray();
+
+ // 6. Pending Activities list — FY filtered by scheduled_date
+ $pending_activities = $db->table('sales_activities sa')
+ ->select('sa.activity_id, sa.lead_id, sa.activity_type, sa.scheduled_date,
+ sa.status, sa.assigned_to, sal.company_name,
+ up.first_name AS assigned_to_name, sa.notes')
+ ->join('user_profiles up', 'up.id = sa.assigned_to', 'left')
+ ->join('sales_actual_leads sal', 'sal.lead_id = sa.lead_id', 'left')
+ ->whereIn('sa.assigned_to', $sales_manager_ids)
+ ->where('sa.status', 'pending')
+ ->where('sa.scheduled_date >=', $fyStart)
+ ->where('sa.scheduled_date <=', $fyEnd)
+ ->orderBy('sa.scheduled_date', 'DESC')
+ ->get()
+ ->getResultArray();
+
+ // 7. All Leads Overview — FY filtered by sal.created_at
+ // Activities & opportunities also scoped to FY via CASE WHEN
+ $leadsOverview = $db->table('sales_actual_leads sal')
+ ->select("sal.lead_id, sal.company_name, sal.status,
+ up.first_name AS assigned_to,
+ COUNT(DISTINCT CASE WHEN sa.scheduled_date >= '{$fyStart}'
+ AND sa.scheduled_date <= '{$fyEnd}' THEN sa.activity_id END) AS activities,
+ COUNT(DISTINCT CASE WHEN l.updated_at >= '{$fyStart}'
+ AND l.updated_at <= '{$fyEnd}' THEN l.id END) AS opportunities", false)
+ ->join('user_profiles up', 'up.id = sal.assigned_to', 'left')
+ ->join('sales_activities sa', 'sa.lead_id = sal.lead_id', 'left')
+ ->join('leads l', 'l.actual_lead_id = sal.lead_id', 'left')
+ ->whereIn('sal.assigned_to', $sales_manager_ids)
+ ->where('sal.created_at >=', $fyStart)
+ ->where('sal.created_at <=', $fyEnd)
+ ->groupBy('sal.lead_id, sal.company_name, sal.status, up.first_name')
+ ->orderBy('sal.created_at', 'DESC')
+ ->get()
+ ->getResultArray();
+
+ // Protect against division by zero in query #8
+ $total_activity_safe = $total_activity > 0 ? $total_activity : 1;
+
+ // 8. Activity Breakdown — FY filtered by scheduled_date
+ $activityBreakdown = $db->table('sales_activities')
+ ->select("activity_type,
+ COUNT(*) AS total,
+ ROUND(COUNT(*) * 100.0 / {$total_activity_safe}, 0) AS percentage", false)
+ ->whereIn('assigned_to', $sales_manager_ids)
+ ->where('scheduled_date >=', $fyStart)
+ ->where('scheduled_date <=', $fyEnd)
+ ->groupBy('activity_type')
+ ->orderBy('total', 'DESC')
+ ->get()
+ ->getResultArray();
+
+ // 9. Team Achievement (for achievement list + modal)
+ $teamAchievement = $this->buildTeamAchievement(
+ $db, $sales_manager_ids, $branchId, $current_fin_year, $fyStart, $fyEnd
+ );
+
+ // 10. Opportunities Achievement per member
+ $oppAchievement = $this->buildOppAchievement(
+ $db, $sales_manager_ids, $branchId, $current_fin_year, $fyStart, $fyEnd
+ );
+
+ $data = [
+ 'total_leads' => $total_leads,
+ 'total_acts' => $total_activity,
+ 'total_completed_acts' => $total_completed_activity,
+ 'total_pending_acts' => $total_pending_activity,
+ 'team' => $teamPerformance,
+ 'pending_acts' => $pending_activities,
+ 'leads_overview' => $leadsOverview,
+ 'activity_breakdown' => $activityBreakdown,
+ 'team_achievement' => $teamAchievement, // used by JS TEAM constant
+ 'opp_achievement' => $oppAchievement, // used by JS OPP_DATA constant
+ 'fin_years' => $fin_years,
+ 'current_fin_year' => $current_fin_year,
+ 'tab_name' => 'Sales Dashboard',
+ 'page_name' => 'Sales Dashboard',
+ ];
+
+ $this->loadLayout('sales/branch_level_dashboard_view', $data);
+
+ } catch (\Exception $e) {
+ return $this->failServerError($e->getMessage());
+ }
+}
+
+// ─────────────────────────────────────────────
+// buildTeamAchievement()
+// Builds the TEAM array for the achievement list
+// ─────────────────────────────────────────────
+private function buildTeamAchievement($db, array $sales_manager_ids, $branchId, string $fy, string $fyStart, string $fyEnd): array
+{
+ $quarters = $this->getFYQuarters($fy);
+
+ // Gradient palette (cycles)
+ $gradients = [
+ ['grad' => 'linear-gradient(135deg,#10b981,#34d399)', 'color' => '#10b981'],
+ ['grad' => 'linear-gradient(135deg,#06b6d4,#67e8f9)', 'color' => '#06b6d4'],
+ ['grad' => 'linear-gradient(135deg,#4f46e5,#818cf8)', 'color' => '#4f46e5'],
+ ['grad' => 'linear-gradient(135deg,#ec4899,#f9a8d4)', 'color' => '#ec4899'],
+ ['grad' => 'linear-gradient(135deg,#f97316,#fbbf24)', 'color' => '#f97316'],
+ ];
+
+ $members = $db->table('user_profiles as u')
+ ->select('u.id, u.first_name, u.last_name, r.role')
+ ->join('roles r', 'r.id = u.role')
+ ->where('u.nhance_branch_id', $branchId)
+ ->whereIn('u.id', $sales_manager_ids)
+ ->where('u.is_active', 1)
+ ->get()
+ ->getResultArray();
+
+ $result = [];
+
+ foreach ($members as $idx => $m) {
+ $uid = (int)$m['id'];
+
+ // Target from sales_target
+ $targetRow = $db->table('sales_target')
+ ->where('user_id', $uid)
+ ->where('fy_year', $fy)
+ ->get()
+ ->getRowArray();
+ $targetAmt = (float)($targetRow['target_amount'] ?? 0);
+
+ // Achieved (won leads in FY)
+ $achievedAmt = (float)$this->getUserAchievedAmount($fy, $uid);
+
+ // Activities — FY filtered by scheduled_date
+ $totalActs = $db->table('sales_activities')
+ ->where('assigned_to', $uid)
+ ->where('scheduled_date >=', $fyStart)
+ ->where('scheduled_date <=', $fyEnd)
+ ->countAllResults();
+ $doneActs = $db->table('sales_activities')
+ ->where('assigned_to', $uid)
+ ->where('status', 'completed')
+ ->where('scheduled_date >=', $fyStart)
+ ->where('scheduled_date <=', $fyEnd)
+ ->countAllResults();
+
+ // Activity breakdown — FY filtered
+ $actRows = $db->table('sales_activities')
+ ->select('activity_type, COUNT(*) as cnt')
+ ->where('assigned_to', $uid)
+ ->where('scheduled_date >=', $fyStart)
+ ->where('scheduled_date <=', $fyEnd)
+ ->groupBy('activity_type')
+ ->get()->getResultArray();
+ $activities = [];
+ foreach ($actRows as $ar) {
+ $activities[$ar['activity_type']] = (int)$ar['cnt'];
+ }
+
+ // Quarter splits
+ $splits = [];
+ foreach ($quarters as $q) {
+ $qStart = $q['start'] . ' 00:00:00';
+ $qEnd = $q['end'] . ' 23:59:59';
+
+ // Achievement = SUM(exp_amt) for won policies in this quarter
+ $qAchievedRow = $db->query("
+ SELECT COALESCE(SUM(ptcs.exp_amt), 0) AS total
+ FROM policy_transaction pt
+ LEFT JOIN pt_co_share_details ptcs
+ ON ptcs.pt_id = pt.id
+ AND ptcs.is_active = 1
+ WHERE pt.sales_generated_by = ?
+ AND pt.issuer_branch = ?
+ AND pt.created_at >= ?
+ AND pt.created_at <= ?
+ ", [$uid, $branchId, $qStart, $qEnd])->getRowArray();
+ $qAchieved = (float)($qAchievedRow['total'] ?? 0);
+
+ $qTarget = $targetAmt > 0 ? round($targetAmt / 4, 2) : 0;
+
+ $qActs = $db->table('sales_activities')
+ ->where('assigned_to', $uid)
+ ->where('scheduled_date >=', $qStart)
+ ->where('scheduled_date <=', $qEnd)
+ ->countAllResults();
+
+ $qDone = $db->table('sales_activities')
+ ->where('assigned_to', $uid)
+ ->where('status', 'completed')
+ ->where('scheduled_date >=', $qStart)
+ ->where('scheduled_date <=', $qEnd)
+ ->countAllResults();
+
+ $qLeads = $db->table('sales_actual_leads')
+ ->where('assigned_to', $uid)
+ ->where('created_at >=', $qStart)
+ ->where('created_at <=', $qEnd)
+ ->countAllResults();
+
+ $splits[] = [
+ 'name' => $q['label'],
+ 'start' => date('M Y', strtotime($q['start'])),
+ 'end' => date('M Y', strtotime($q['end'])),
+ 'target' => $qTarget,
+ 'achieved' => $qAchieved,
+ 'acts' => $qActs,
+ 'done' => $qDone,
+ 'leads' => $qLeads,
+ ];
+ }
+
+ $palette = $gradients[$idx % count($gradients)];
+
+ $result[] = [
+ 'id' => $uid,
+ 'first_name' => $m['first_name'],
+ 'last_name' => $m['last_name'],
+ 'role' => $m['role'],
+ 'total_acts' => $totalActs,
+ 'done_acts' => $doneActs,
+ 'target_amt' => $targetAmt,
+ 'achieved_amt' => $achievedAmt,
+ 'grad' => $palette['grad'],
+ 'color' => $palette['color'],
+ 'splits' => $splits,
+ 'activities' => $activities,
+ ];
}
- public function salesManagerLevelDashboard($userId,$sales_manager_ids, $payload = [])
- {
- // $userId = get_session_userid();
- // $userId = 1;
- $db = \Config\Database::connect();
+ return $result;
+}
- try {
+// ─────────────────────────────────────────────
+// buildOppAchievement()
+// Opportunities via policy_transaction + pt_co_share_details
+// Returns per-member: totals + flat policy list (no quarterly grouping)
+// ─────────────────────────────────────────────
+private function buildOppAchievement($db, array $sales_manager_ids, $branchId, string $fy, string $fyStart, string $fyEnd): array
+{
+ $result = [];
- // $payload = $this->request->getGet();
- $current_fin_year = $payload['fy'] ?? getCurrentFinancialYear();
+ foreach ($sales_manager_ids as $uid) {
-
- $fin_years = $db->table('sales_target')
- ->select('fy_year')
- ->where('user_id', $userId)
- ->orderBy('fy_year', 'desc')
- ->get()
- ->getResultArray();
+ // ── Target ──
+ $targetRow = $db->table('sales_target')
+ ->where('user_id', $uid)
+ ->where('fy_year', $fy)
+ ->get()
+ ->getRowArray();
+ $targetAmt = (float)($targetRow['target_amount'] ?? 0);
- $fin_years = array_column($fin_years, 'fy_year');
+ // ── All policy rows for this user in FY ──
+ // policy_no, issue_date (from pt), amount (exp_amt from child), created_at
+ // If no matching pt_co_share_details row exists, exp_amt = 0
+ // Policy list for Tab 2: policy_transaction + exp_amt from pt_co_share_details
+ $policyRows = $db->query("
+ SELECT
+ pt.id,
+ pt.policy_no,
+ pt.created_at AS issue_date,
+ COALESCE(ptcs.exp_amt, 0) AS amount,
+ pt.created_at AS created_at
+ FROM policy_transaction pt
+ LEFT JOIN pt_co_share_details ptcs
+ ON ptcs.pt_id = pt.id
+ AND ptcs.is_active = 1
+ WHERE pt.sales_generated_by = ?
+ AND pt.issuer_branch = ?
+ AND pt.created_at >= ?
+ AND pt.created_at <= ?
+ ORDER BY pt.created_at DESC
+ ", [$uid, $branchId, $fyStart, $fyEnd])->getResultArray();
- if(empty($fin_years)){
- $fin_years[] = $current_fin_year;
- }
+ // ── Totals derived from policy_transaction ──
+ $totalPolicies = count($policyRows);
+ $totalExpAmt = array_sum(array_column($policyRows, 'amount'));
- $target = $db->table('sales_target')
- ->where('user_id', $userId)
- ->where('fy_year', $current_fin_year)
- ->get()
- ->getRowArray();
-
- $targetAmount = $target['target_amount'] ?? 0.00;
-
- // get achieved amount from leads table
- $achievedAmount = $this->getUserAchievedAmount($current_fin_year, $userId);
-
- $remainingAmount = $targetAmount - $achievedAmount;
- // $achievementPercent = ($targetAmount > 0) ? round(($achievedAmount / $targetAmount) * 100) : 0;
- $achievementPercent = ($targetAmount > 0) ? min(100, round(($achievedAmount / $targetAmount) * 100)) : 0;
-
- $activitySummary = [
- 'total' => $this->activityModel->where('assigned_to', $userId)->countAllResults(),
- 'pending' => $this->activityModel->where(['assigned_to' => $userId, 'status' => 'pending'])->countAllResults(),
- 'completed' => $this->activityModel->where(['assigned_to' => $userId, 'status' => 'completed'])->countAllResults(),
+ // Clean policy list for JS
+ $policies = array_map(function($row) {
+ return [
+ 'policy_no' => $row['policy_no'],
+ 'issue_date' => $row['issue_date'],
+ 'amount' => (float)$row['amount'],
+ 'created_at' => $row['created_at'],
];
+ }, $policyRows);
- $myLeadsCount = $this->leadModel->where('assigned_to', $userId)->countAllResults();
+ // ── Won Leads for this user in FY (Table 2 in modal) ──
+ // leads.actual_lead_id maps to sales_actual_leads.id
+ // leads.type: 1 = EB, else = Non-EB
+ $wonLeads = $db->query("
+ SELECT
+ sal.lead_id,
+ sal.company_name AS company,
+ CASE WHEN l.lead_type = 1 THEN 'EB' ELSE 'Non-EB' END AS lead_type,
+ l.created_at AS created_at,
+ l.status
+ FROM leads l
+ INNER JOIN sales_actual_leads sal
+ ON sal.lead_id = l.actual_lead_id
+ WHERE l.status = 'won'
+ AND sal.assigned_to = ?
+ AND l.created_at >= ?
+ AND l.created_at <= ?
+ ORDER BY l.created_at DESC
+ ", [$uid, $fyStart, $fyEnd])->getResultArray();
- $upcomingActivities = $this->activityModel->select('sales_activities.*, sales_actual_leads.company_name')
- ->join('sales_actual_leads', 'sales_actual_leads.lead_id = sales_activities.lead_id')
- ->where(['sales_activities.assigned_to' => $userId, 'sales_activities.status' => 'pending'])
- ->orderBy('scheduled_date', 'ASC')
- ->limit(3)
- ->findAll();
-
- $recentLeads = $this->leadModel->where('assigned_to', $userId)
- ->orderBy('created_at', 'DESC')
- ->limit(5)
- ->findAll();
-
- $data = [
- 'target_amt' => $targetAmount,
- 'achieved' => $achievedAmount,
- 'remaining' => $remainingAmount,
- 'percent' => $achievementPercent,
- 'acts' => $activitySummary,
- 'lead_count' => $myLeadsCount,
- 'upcoming' => $upcomingActivities,
- 'recent_leads' => $recentLeads,
- 'fin_years' => $fin_years,
- 'display_fin_years' => format_financial_year($current_fin_year),
- 'user_name' => get_session_userdata()->first_namee ?? '',
- 'tab_name' => "Sales Dashboard",
- 'page_name' => "Sales Dashboard"
- ];
-
- // dd($data);
-
- // return view('sales/my_dashboard_view', $data);
- $this->loadLayout('sales/sales_manager_level_dashboard', $data);
-
- } catch (\Exception $e) {
- return $this->failServerError($e->getMessage());
- }
+ $result[$uid] = [
+ 'total_policies' => $totalPolicies,
+ 'total_exp_amt' => $totalExpAmt,
+ 'target_amt' => $targetAmt,
+ 'policies' => $policies,
+ 'won_leads' => $wonLeads, // for Table 2 in modal Tab 2
+ ];
}
- public function getUserAchievedAmount($financialYear, $userId)
- {
- // Split the string into two years
- $years = explode('-', $financialYear);
- $startYear = $years[0]; // 2025
- $endYear = $years[1]; // 2026
+ return $result;
+}
- // Create the timestamps
- $startFY = $startYear . '-04-01 00:00:00';
- $endFY = $endYear . '-03-31 23:59:59';
+// ─────────────────────────────────────────────
+// getUserAchievedAmount()
+// ─────────────────────────────────────────────
+public function getUserAchievedAmount($financialYear, $userId)
+{
+ // "2025-2026" → strrpos splits correctly into 2025 / 2026
+ $pos = strrpos($financialYear, '-');
+ $startYear = substr($financialYear, 0, $pos); // "2025"
+ $endYear = substr($financialYear, $pos + 1); // "2026"
- $achievedAmountData = $this->leadModel
- ->select('SUM(leads.premium_amount) as achieved_amount')
- ->join('leads', 'sales_actual_leads.lead_id = leads.actual_lead_id')
- ->where('sales_actual_leads.assigned_to', $userId)
- ->where('leads.status', 'won')
- ->where('leads.updated_at >=', $startFY)
- ->where('leads.updated_at <=', $endFY)
+ $startFY = $startYear . '-04-01 00:00:00'; // 2025-04-01
+ $endFY = $endYear . '-03-31 23:59:59'; // 2026-03-31
+
+ // Achievement = SUM(exp_amt) from policy_transaction + pt_co_share_details
+ $db = \Config\Database::connect();
+ $row = $db->query("
+ SELECT COALESCE(SUM(ptcs.exp_amt), 0) AS achieved_amount
+ FROM policy_transaction pt
+ LEFT JOIN pt_co_share_details ptcs
+ ON ptcs.pt_id = pt.id
+ AND ptcs.is_active = 1
+ WHERE pt.sales_generated_by = ?
+ AND pt.created_at >= ?
+ AND pt.created_at <= ?
+ ", [$userId, $startFY, $endFY])->getRowArray();
+
+ return (float)($row['achieved_amount'] ?? 0.00);
+}
+
+// ─────────────────────────────────────────────
+// salesManagerLevelDashboard()
+// ─────────────────────────────────────────────
+public function salesManagerLevelDashboard($userId, $current_fin_year = null, $fin_years = [])
+{
+ $db = \Config\Database::connect();
+
+ try {
+
+ // -------------------------------
+ // Financial Year Handling
+ // -------------------------------
+ if (empty($current_fin_year)) {
+ $current_fin_year = getCurrentFinancialYear();
+ }
+
+ $fyRange = $this->getFYDateRange($current_fin_year);
+ $fyStart = $fyRange['start'];
+ $fyEnd = $fyRange['end'];
+
+ // -------------------------------
+ // Target (FY Based)
+ // -------------------------------
+ $target = $db->table('sales_target')
+ ->where('user_id', $userId)
+ ->where('fy_year', $current_fin_year)
+ ->get()
+ ->getRowArray();
+
+ $targetAmount = (float)($target['target_amount'] ?? 0);
+
+ // -------------------------------
+ // Achieved (FY Based)
+ // -------------------------------
+ $achievedAmount = (float)$this->getUserAchievedAmount($current_fin_year, $userId);
+
+ $remainingAmount = $targetAmount - $achievedAmount;
+ $achievementPercent = ($targetAmount > 0)
+ ? min(100, round(($achievedAmount / $targetAmount) * 100))
+ : 0;
+
+ // -------------------------------
+ // Activity Summary (FY Based using created_at)
+ // -------------------------------
+ $activitySummary = [
+ 'total' => $this->activityModel
+ ->where('assigned_to', $userId)
+ ->where('created_at >=', $fyStart)
+ ->where('created_at <=', $fyEnd)
+ ->countAllResults(),
+
+ 'pending' => $this->activityModel
+ ->where([
+ 'assigned_to' => $userId,
+ 'status' => 'pending'
+ ])
+ ->where('created_at >=', $fyStart)
+ ->where('created_at <=', $fyEnd)
+ ->countAllResults(),
+
+ 'completed' => $this->activityModel
+ ->where([
+ 'assigned_to' => $userId,
+ 'status' => 'completed'
+ ])
+ ->where('created_at >=', $fyStart)
+ ->where('created_at <=', $fyEnd)
+ ->countAllResults(),
+ ];
+
+ // -------------------------------
+ // Leads Count (FY Based)
+ // -------------------------------
+ $myLeadsCount = $this->leadModel
+ ->where('assigned_to', $userId)
+ ->where('created_at >=', $fyStart)
+ ->where('created_at <=', $fyEnd)
+ ->countAllResults();
+
+ // -------------------------------
+ // Upcoming Activities (FY Based)
+ // -------------------------------
+ $upcomingActivities = $this->activityModel
+ ->select('sales_activities.*, sales_actual_leads.company_name')
+ ->join('sales_actual_leads', 'sales_actual_leads.lead_id = sales_activities.lead_id')
+ ->where([
+ 'sales_activities.assigned_to' => $userId,
+ 'sales_activities.status' => 'pending'
+ ])
+ ->where('sales_activities.created_at >=', $fyStart)
+ ->where('sales_activities.created_at <=', $fyEnd)
+ ->orderBy('scheduled_date', 'ASC')
+ ->limit(3)
->findAll();
- return $achievedAmountData[0]['achieved_amount'] ?? 0.00;
+ // -------------------------------
+ // Recent Leads (FY Based)
+ // -------------------------------
+ $recentLeads = $this->leadModel
+ ->where('assigned_to', $userId)
+ ->where('created_at >=', $fyStart)
+ ->where('created_at <=', $fyEnd)
+ ->orderBy('created_at', 'DESC')
+ ->limit(5)
+ ->findAll();
+
+ // -------------------------------
+ // Final Data
+ // -------------------------------
+ $data = [
+ 'target_amt' => $targetAmount,
+ 'achieved' => $achievedAmount,
+ 'remaining' => $remainingAmount,
+ 'percent' => $achievementPercent,
+ 'acts' => $activitySummary,
+ 'lead_count' => $myLeadsCount,
+ 'upcoming' => $upcomingActivities,
+ 'recent_leads' => $recentLeads,
+ 'fin_years' => $fin_years,
+ 'current_fin_year' => $current_fin_year,
+ 'display_fin_years' => format_financial_year($current_fin_year),
+ 'user_name' => get_session_userdata()->first_name ?? '',
+ 'tab_name' => 'Sales Dashboard',
+ 'page_name' => 'Sales Dashboard',
+ ];
+
+ return $this->loadLayout('sales/sales_manager_level_dashboard', $data);
+
+ } catch (\Exception $e) {
+ return $this->failServerError($e->getMessage());
}
+}
+ // public function dashboard()
+ // {
+ // $payload = $this->request->getGet();
+ // $base = $this->getSalesStaffData();
+ // $salesRole = $base['sales_role'];
+ // $salesManagerIds = $base['sales_manager_ids'];
+ // $userId = get_session_userid();
+
+ // // Get branch id from users array
+ // $nhanceBranchId = $base['users'][0]['nhance_branch_id'] ?? null;
+
+ // if ($salesRole === 'Sales Head') {
+ // $this->branchLevelDashboard($nhanceBranchId, $salesManagerIds);
+ // // $this->salesManagerLevelDashboard($userId, $salesManagerIds,$payload);
+ // } elseif ($salesRole === 'Sales Manager') {
+ // $this->salesManagerLevelDashboard($userId, $salesManagerIds,$payload);
+ // }
+ // }
+
+ // public function branchLevelDashboard($branchId,$sales_manager_ids)
+ // {
+ // // Hardcoded branch ID as requested
+ // // $branchId = 1;
+
+ // try {
+ // $sales_manager_ids = array_values(array_map('intval', $sales_manager_ids));
+
+ // // Final safe check
+ // if (empty($sales_manager_ids)) {
+ // // No valid IDs — skip queries or return empty
+ // $total_leads = 0;
+ // $total_activity = 0;
+ // $total_completed_activity = 0;
+ // $total_pending_activity = 0;
+ // $pending_activities = [];
+ // $recent_activities = [];
+ // $teamPerformance = [];
+
+ // $leadsOverview = [];
+ // } else {
+
+ // if (empty($sales_manager_ids) || !is_array($sales_manager_ids)) {
+ // $sales_manager_ids = array_filter((array) $sales_manager_ids); // removes null, "", 0
+ // }
+
+ // // 1. Lead Statistics
+ // $total_leads = $this->leadModel->whereIn('assigned_to', $sales_manager_ids)->countAllResults(); // Use countAllResults, NOT countAll
+ // // echo $this->leadModel->getLastQuery();die();
+
+ // // 2. Total activity
+ // $total_activity = $this->activityModel->whereIn('assigned_to', $sales_manager_ids)->countAllResults();
+
+ // // 3. Completed activity
+ // $total_completed_activity = $this->activityModel->whereIn('assigned_to', $sales_manager_ids)->where('status', 'completed')->countAllResults();
+
+ // // 4. Pending activity
+ // $total_pending_activity = $this->activityModel->whereIn('assigned_to', $sales_manager_ids)->where('status', 'pending')->countAllResults();
+
+ // $db = \Config\Database::connect();
+
+ // // 5. Team Performance
+ // $teamPerformance = $db->table('user_profiles as u')
+ // ->select('u.first_name, u.last_name, r.role,
+ // (SELECT COUNT(*) FROM sales_activities WHERE assigned_to = u.id) as total_acts,
+ // (SELECT COUNT(*) FROM sales_activities WHERE assigned_to = u.id AND status = "completed") as done_acts')
+ // ->join('roles r', 'r.id = u.role')
+ // ->where('u.nhance_branch_id', $branchId)
+ // ->whereIn('u.id', $sales_manager_ids)
+ // ->where('u.is_active', 1)
+ // ->get()->getResultArray();
+
+ // // 6. Recent Activities (Joining for Lead Names)
+ // $recent_activities = $this->activityModel->select('sales_activities.*, sales_actual_leads.company_name')
+ // ->join('sales_actual_leads', 'sales_actual_leads.lead_id = sales_activities.lead_id')
+ // ->orderBy('sales_activities.scheduled_date', 'DESC')
+ // ->limit(6)
+ // ->findAll();
+
+ // // 7. Pending Activities (List)
+ // $pending_activities = $db->table('sales_activities sa')
+ // ->select('sa.activity_id,sa.lead_id,sa.activity_type,sa.scheduled_date,sa.status,sa.assigned_to,sal.company_name,up.first_name AS assigned_to_name,sa.notes')
+ // ->join('user_profiles up', 'up.id = sa.assigned_to', 'left')
+ // ->join('sales_actual_leads sal', 'sal.lead_id = sa.lead_id', 'left') // ✅ ADD THIS
+ // ->orderBy('sa.scheduled_date', 'DESC')
+ // ->whereIn('sa.assigned_to', $sales_manager_ids)
+ // ->where('sa.status', 'pending')
+ // ->get()->getResultArray();
+
+ // // 8. All Leads Overview
+ // $leadsOverview = $db->table('sales_actual_leads sal')
+ // ->select('sal.lead_id,sal.company_name,sal.status,up.first_name AS assigned_to,
+ // COUNT(DISTINCT sa.activity_id) AS activities,
+ // COUNT(DISTINCT l.id) AS opportunities
+ // ')
+ // ->join('user_profiles up', 'up.id = sal.assigned_to', 'left')
+ // ->join('sales_activities sa', 'sa.lead_id = sal.lead_id', 'left')
+ // ->join('leads l', 'l.actual_lead_id = sal.lead_id', 'left')
+ // ->groupBy('sal.lead_id, sal.company_name, sal.status, up.first_name')
+ // // ->having('COUNT(DISTINCT sa.activity_id) + COUNT(DISTINCT l.id) >', 0) // ← this line
+ // ->orderBy('sal.created_at', 'DESC')
+ // ->whereIn('sal.assigned_to', $sales_manager_ids)
+ // ->get()
+ // ->getResultArray();
+
+ // // 9. Activity BrakDown
+ // $activityBreakdown = $db->table('sales_activities')
+ // ->select("activity_type, COUNT(*) AS total, ROUND(COUNT(*) * 100.0 / {$total_activity}, 0) AS percentage", false)
+ // ->whereIn('assigned_to', $sales_manager_ids)
+ // ->groupBy('activity_type')
+ // ->orderBy('total', 'DESC')
+ // ->get()
+ // ->getResultArray();
+ // }
+ // $data = [
+ // 'total_leads' => $total_leads,
+ // 'total_acts' => $total_activity,
+ // 'total_completed_acts' => $total_completed_activity,
+ // 'total_pending_acts'=> $total_pending_activity,
+ // 'pipeline_value' => '15.0L', // Hardcoded placeholder from PDF [cite: 14]
+ // 'display_fin_years' => format_financial_year($current_fin_year),
+ // 'team' => $teamPerformance,
+ // 'recent_acts' => $recent_activities,
+ // 'pending_acts' => $pending_activities,
+ // 'leads_overview' => $leadsOverview,
+ // 'activity_breakdown'=> $activityBreakdown,
+ // 'tab_name' => "Sales Dashboard",
+ // 'page_name' => "Sales Dashboard"
+ // ];
+
+ // // dd($data);
+
+ // $this->loadLayout('sales/branch_level_dashboard_view', $data);
+
+ // // return view('sales/dashboard_view', $data);
+
+ // } catch (\Exception $e) {
+ // return $this->failServerError($e->getMessage());
+ // }
+ // }
+
+ // public function salesManagerLevelDashboard($userId,$sales_manager_ids, $payload = [])
+ // {
+ // // $userId = get_session_userid();
+ // // $userId = 1;
+ // $db = \Config\Database::connect();
+
+ // try {
+
+ // // $payload = $this->request->getGet();
+ // $current_fin_year = $payload['fy'] ?? getCurrentFinancialYear();
+
+
+ // $fin_years = $db->table('sales_target')
+ // ->select('fy_year')
+ // ->where('user_id', $userId)
+ // ->orderBy('fy_year', 'desc')
+ // ->get()
+ // ->getResultArray();
+
+ // $fin_years = array_column($fin_years, 'fy_year');
+
+ // if(empty($fin_years)){
+ // $fin_years[] = $current_fin_year;
+ // }
+
+ // $target = $db->table('sales_target')
+ // ->where('user_id', $userId)
+ // ->where('fy_year', $current_fin_year)
+ // ->get()
+ // ->getRowArray();
+
+ // $targetAmount = $target['target_amount'] ?? 0.00;
+
+ // // get achieved amount from leads table
+ // $achievedAmount = $this->getUserAchievedAmount($current_fin_year, $userId);
+
+ // $remainingAmount = $targetAmount - $achievedAmount;
+ // // $achievementPercent = ($targetAmount > 0) ? round(($achievedAmount / $targetAmount) * 100) : 0;
+ // $achievementPercent = ($targetAmount > 0) ? min(100, round(($achievedAmount / $targetAmount) * 100)) : 0;
+
+ // $activitySummary = [
+ // 'total' => $this->activityModel->where('assigned_to', $userId)->countAllResults(),
+ // 'pending' => $this->activityModel->where(['assigned_to' => $userId, 'status' => 'pending'])->countAllResults(),
+ // 'completed' => $this->activityModel->where(['assigned_to' => $userId, 'status' => 'completed'])->countAllResults(),
+ // ];
+
+ // $myLeadsCount = $this->leadModel->where('assigned_to', $userId)->countAllResults();
+
+ // $upcomingActivities = $this->activityModel->select('sales_activities.*, sales_actual_leads.company_name')
+ // ->join('sales_actual_leads', 'sales_actual_leads.lead_id = sales_activities.lead_id')
+ // ->where(['sales_activities.assigned_to' => $userId, 'sales_activities.status' => 'pending'])
+ // ->orderBy('scheduled_date', 'ASC')
+ // ->limit(3)
+ // ->findAll();
+
+ // $recentLeads = $this->leadModel->where('assigned_to', $userId)
+ // ->orderBy('created_at', 'DESC')
+ // ->limit(5)
+ // ->findAll();
+
+ // $data = [
+ // 'target_amt' => $targetAmount,
+ // 'achieved' => $achievedAmount,
+ // 'remaining' => $remainingAmount,
+ // 'percent' => $achievementPercent,
+ // 'acts' => $activitySummary,
+ // 'lead_count' => $myLeadsCount,
+ // 'upcoming' => $upcomingActivities,
+ // 'recent_leads' => $recentLeads,
+ // 'fin_years' => $fin_years,
+ // 'display_fin_years' => format_financial_year($current_fin_year),
+ // 'user_name' => get_session_userdata()->first_namee ?? '',
+ // 'tab_name' => "Sales Dashboard",
+ // 'page_name' => "Sales Dashboard",
+ // 'splits' => [],
+ // 'activity_breakdown'=> [],
+ // ];
+
+
+
+ // // dd($data);
+
+ // // return view('sales/my_dashboard_view', $data);
+ // $this->loadLayout('sales/sales_manager_level_dashboard', $data);
+
+ // } catch (\Exception $e) {
+ // return $this->failServerError($e->getMessage());
+ // }
+ // }
+
+ // public function getUserAchievedAmount($financialYear, $userId)
+ // {
+ // // Split the string into two years
+ // $years = explode('-', $financialYear);
+ // $startYear = $years[0]; // 2025
+ // $endYear = $years[1]; // 2026
+
+ // // Create the timestamps
+ // $startFY = $startYear . '-04-01 00:00:00';
+ // $endFY = $endYear . '-03-31 23:59:59';
+
+ // $achievedAmountData = $this->leadModel
+ // ->select('SUM(leads.premium_amount) as achieved_amount')
+ // ->join('leads', 'sales_actual_leads.lead_id = leads.actual_lead_id')
+ // ->where('sales_actual_leads.assigned_to', $userId)
+ // ->where('leads.status', 'won')
+ // ->where('leads.updated_at >=', $startFY)
+ // ->where('leads.updated_at <=', $endFY)
+ // ->findAll();
+
+ // return $achievedAmountData[0]['achieved_amount'] ?? 0.00;
+ // }
public function addCalenderEvent($input)
{
diff --git a/app/Controllers/TestingController.php b/app/Controllers/TestingController.php
index daae4293..c83fe172 100644
--- a/app/Controllers/TestingController.php
+++ b/app/Controllers/TestingController.php
@@ -1097,10 +1097,12 @@ class TestingController extends BaseController
'dashboard' => $database_id
],
'exp' => time() + (10 * 60), // 10 minutes
- 'params' => (object)[]
+ 'params' => (object) ['client_policy' => $policy_id ], // MUST be object for Metabase
+
];
$token = JWT::encode($payload, $METABASE_SECRET_KEY, 'HS256');
+ // dd($token);
if ($this->request->getGet('api') == 1) {
return $this->respond([
diff --git a/app/Controllers/TicketController.php b/app/Controllers/TicketController.php
index 01109672..c3d5e86e 100644
--- a/app/Controllers/TicketController.php
+++ b/app/Controllers/TicketController.php
@@ -959,6 +959,8 @@ class TicketController extends BaseController
// Redirect or show a 404 to prevent "Undefined array key" errors
return redirect()->to(base_url('ticket/list'))->with('error', 'Ticket not found');
}
+
+ $ticket_data['is_tpa_api_service_enabled'] = $this->ticketMasterModel->isTpaApiServiceEnabled($ticket_id);
$ticket_data = $this->formatDateForClaim($ticket_data, 'd/m/Y');
@@ -1173,9 +1175,13 @@ class TicketController extends BaseController
'regex_match' => 'Policy Number can only contain letters, numbers, spaces, hyphens(-) underscores(_), and slashes(/).'
]
],
- 'tpa_no' => ['label' => 'TPA ID','rules' => 'permit_empty|regex_match[/^[a-zA-Z0-9]+$/]','errors' => [
- 'regex_match' => 'TPA ID can only contain letters and numbers.'
- ]],
+ 'tpa_no' => [
+ 'label' => 'TPA ID',
+ 'rules' => 'permit_empty|regex_match[/^[a-zA-Z0-9\/]+$/]',
+ 'errors' => [
+ 'regex_match' => 'TPA ID can only contain letters, numbers, and /.'
+ ]
+ ],
'emp_mobile' => ['label' => 'Employee Mobile No','rules' => 'required|numeric|exact_length[10]',
'errors' => [
'required' => 'Mobile number is required',
@@ -1522,9 +1528,13 @@ class TicketController extends BaseController
'regex_match' => 'Policy Number can only contain letters, numbers, spaces, hyphens(-) underscores(_), and slashes(/).'
]
],
- 'tpa_no' => ['label' => 'TPA ID','rules' => 'permit_empty|regex_match[/^[a-zA-Z0-9]+$/]','errors' => [
- 'regex_match' => 'TPA ID can only contain letters and numbers.'
- ]],
+ 'tpa_no' => [
+ 'label' => 'TPA ID',
+ 'rules' => 'permit_empty|regex_match[/^[a-zA-Z0-9\/]+$/]',
+ 'errors' => [
+ 'regex_match' => 'TPA ID can only contain letters, numbers, and /.'
+ ]
+ ],
'emp_mobile' => ['label' => 'Employee Mobile No','rules' => 'required|numeric|exact_length[10]',
'errors' => [
'required' => 'Mobile number is required',
diff --git a/app/Controllers/VidalApiController.php b/app/Controllers/VidalApiController.php
index 3836cb4b..d4674302 100644
--- a/app/Controllers/VidalApiController.php
+++ b/app/Controllers/VidalApiController.php
@@ -164,7 +164,7 @@ class VidalApiController extends BaseController
if (count($data) && $data['filePath'] == null) {
log_message('error', "VIDAL - Claim Push | Submit claim failed - Claim or File Missing");
- return $this->response->setJSON(['status' => false,'message' => 'Claim or File Missing', ]);
+ return ['status' => false, 'message' => 'Claim Push FAILED | Claim or File Missing'];
}
$filePath = $data['filePath'] ?? '';
@@ -271,7 +271,7 @@ class VidalApiController extends BaseController
$this->db->table('ticket_master')
->where('id',$claimId)
->update([ 'tpa_push_response' => json_encode($response) ]);
- return;
+ return ['status' => false, 'message' => 'Claim Push FAILED | API call failed'];
}
// return $this->response->setJSON($response);
@@ -289,16 +289,17 @@ class VidalApiController extends BaseController
->where('id',$claimId)
->update([ 'tpa_claim_push_reference_no' => $claimInwardNO , 'tpa_claim_id' => $claimNO , 'claim_number' => $claimNO ]);
- return;
+ return ['status' => true, 'message' => 'Claim Push SUCCESS'];
} else {
log_message('error', 'VIDAL - Claim Push API SUCCESS BUT claimNO,claimInwardNO EMPTY | claimId: '.$claimId.' | response: '.json_encode($response));
- return;
+ return ['status' => false, 'message' => 'Claim Push API SUCCESS BUT claimNO,claimInwardNO EMPTY'];
}
}else{
log_message('error', 'VIDAL - Claim Push API FAILED | claimId: '.$claimId.' | response: '.json_encode($response));
- return;
+ return ['status' => false, 'message' => 'Claim Push API FAILED'];
}
+
}
function getWellnessSSORedirectUrl($email = 'test@getvisitapp.com')
diff --git a/app/Helpers/excel_util_helper.php b/app/Helpers/excel_util_helper.php
index 5b5d6b7b..9419d6e1 100755
--- a/app/Helpers/excel_util_helper.php
+++ b/app/Helpers/excel_util_helper.php
@@ -3023,6 +3023,9 @@ if (!function_exists('validate_excel_value')) {
case 'vehicle':
return validate_indian_vehicle_number($value);
+ case 'positive_number':
+ return validate_positive_number_value($value);
+
default:
return [
'status' => true,
@@ -3066,6 +3069,24 @@ if (!function_exists('validate_mobile_value')) {
}
}
+if (!function_exists('validate_positive_number_value')) {
+ function validate_positive_number_value($value)
+ {
+ if ($value === "" || $value === null) {
+ return ['status' => true, 'error' => null];
+ }
+
+ if (is_numeric($value) && $value >= 0) {
+ return ['status' => true, 'error' => null];
+ }
+
+ return [
+ 'status' => false,
+ 'error' => "Value must be a positive number"
+ ];
+ }
+}
+
if (!function_exists('validate_email_value')) {
function validate_email_value($value)
{
diff --git a/app/Libraries/GoogleSheetLib.php b/app/Libraries/GoogleSheetLib.php
index a04ab1e9..e5eb8caf 100644
--- a/app/Libraries/GoogleSheetLib.php
+++ b/app/Libraries/GoogleSheetLib.php
@@ -1,10 +1,11 @@
-client = new Google_Client();
@@ -28,7 +28,7 @@ class GoogleSheetLib
// Required scopes
$this->client->addScope([
Google_Service_Drive::DRIVE,
- Google_Service_Sheets::SPREADSHEETS
+ Google_Service_Sheets::SPREADSHEETS,
]);
// Init services
@@ -53,7 +53,7 @@ class GoogleSheetLib
public function write(string $spreadsheetId, array $values, string $range = 'Sheet1')
{
$body = new Google_Service_Sheets_ValueRange([
- 'values' => $values
+ 'values' => $values,
]);
$this->sheets
@@ -81,7 +81,6 @@ class GoogleSheetLib
return $response->getBody()->getContents();
}
-
/* ================= COPY TEMPLATE ================= */
public function copyTemplate(string $templateId, string $name, string $folderId): string
@@ -92,10 +91,10 @@ class GoogleSheetLib
'name' => $name,
'parents' => [$folderId],
- ]),[
- 'supportsAllDrives' => true,
- 'fields' => 'id, name, parents'
- ]
+ ]), [
+ 'supportsAllDrives' => true,
+ 'fields' => 'id, name, parents',
+ ]
);
return $file->id;
@@ -116,7 +115,7 @@ class GoogleSheetLib
private function createPermission(string $fileId, string $email, string $role)
{
- $type = str_starts_with($email, 'group:') ? 'group' : 'user';
+ $type = str_starts_with($email, 'group:') ? 'group' : 'user';
$email = str_replace('group:', '', $email);
$this->drive->permissions->create(
@@ -124,9 +123,9 @@ class GoogleSheetLib
new \Google_Service_Drive_Permission([
'type' => $type,
'role' => $role,
- 'emailAddress' => $email
+ 'emailAddress' => $email,
]),
- ['sendNotificationEmail' => false,'supportsAllDrives' => true]
+ ['sendNotificationEmail' => false, 'supportsAllDrives' => true]
);
}
@@ -135,7 +134,7 @@ class GoogleSheetLib
public function applyProtectionsold(string $spreadsheetId, array $ranges)
{
$spreadsheet = $this->sheets->spreadsheets->get($spreadsheetId);
- $sheetId = $spreadsheet->getSheets()[0]->getProperties()->getSheetId();
+ $sheetId = $spreadsheet->getSheets()[0]->getProperties()->getSheetId();
$requests = [];
@@ -145,96 +144,95 @@ class GoogleSheetLib
$requests[] = [
'addProtectedRange' => [
'protectedRange' => [
- 'range' => [
- 'sheetId' => $sheetId
+ 'range' => [
+ 'sheetId' => $sheetId,
],
- 'warningOnly' => false
- ]
- ]
+ 'warningOnly' => false,
+ ],
+ ],
];
}
$this->sheets->spreadsheets->batchUpdate(
$spreadsheetId,
new Google_Service_Sheets_BatchUpdateSpreadsheetRequest([
- 'requests' => $requests
+ 'requests' => $requests,
])
);
}
-
public function applyProtections(string $spreadsheetId, array $protections)
-{
- // Fetch spreadsheet metadata
- $spreadsheet = $this->sheets->spreadsheets->get(
- $spreadsheetId,
- ['fields' => 'sheets(properties(sheetId,title,gridProperties))']
- );
-
- // Map sheet names
- $sheetMap = [];
- foreach ($spreadsheet->getSheets() as $sheet) {
- $props = $sheet->getProperties();
- $sheetMap[$props->getTitle()] = [
- 'sheetId' => $props->getSheetId(),
- 'rowCount' => $props->getGridProperties()->getRowCount(),
- 'colCount' => $props->getGridProperties()->getColumnCount(),
- ];
- }
-
- $requests = [];
-
- foreach ($protections as $protection) {
-
- $rangeStr = $protection['range'];
-
- if (!str_contains($rangeStr, '!')) {
- throw new \Exception("Invalid range format: {$rangeStr}");
- }
-
- [$sheetName, $a1] = explode('!', $rangeStr, 2);
-
- if (!isset($sheetMap[$sheetName])) {
- throw new \Exception("Sheet not found: {$sheetName}");
- }
-
- $sheetMeta = $sheetMap[$sheetName];
-
- $gridRange = $this->convertA1ToGridRange(
- $a1,
- $sheetMeta['sheetId'],
- $sheetMeta['rowCount'],
- $sheetMeta['colCount']
+ {
+ // Fetch spreadsheet metadata
+ $spreadsheet = $this->sheets->spreadsheets->get(
+ $spreadsheetId,
+ ['fields' => 'sheets(properties(sheetId,title,gridProperties))']
);
- $protectedRange = [
- 'range' => $gridRange,
- 'description' => 'RFQ Protected Area',
- 'warningOnly' => false,
- 'editors' => [
- 'users' => $protection['users'] ?? [],
- 'groups' => $protection['groups'] ?? []
- ]
- ];
+ // Map sheet names
+ $sheetMap = [];
+ foreach ($spreadsheet->getSheets() as $sheet) {
+ $props = $sheet->getProperties();
+ $sheetMap[$props->getTitle()] = [
+ 'sheetId' => $props->getSheetId(),
+ 'rowCount' => $props->getGridProperties()->getRowCount(),
+ 'colCount' => $props->getGridProperties()->getColumnCount(),
+ ];
+ }
- $requests[] = [
- 'addProtectedRange' => [
- 'protectedRange' => $protectedRange
- ]
- ];
+ $requests = [];
+
+ foreach ($protections as $protection) {
+
+ $rangeStr = $protection['range'];
+
+ if (! str_contains($rangeStr, '!')) {
+ throw new \Exception("Invalid range format: {$rangeStr}");
+ }
+
+ [$sheetName, $a1] = explode('!', $rangeStr, 2);
+
+ if (! isset($sheetMap[$sheetName])) {
+ throw new \Exception("Sheet not found: {$sheetName}");
+ }
+
+ $sheetMeta = $sheetMap[$sheetName];
+
+ $gridRange = $this->convertA1ToGridRange(
+ $a1,
+ $sheetMeta['sheetId'],
+ $sheetMeta['rowCount'],
+ $sheetMeta['colCount']
+ );
+
+ $protectedRange = [
+ 'range' => $gridRange,
+ 'description' => 'RFQ Protected Area',
+ 'warningOnly' => false,
+ 'editors' => [
+ 'users' => $protection['users'] ?? [],
+ 'groups' => $protection['groups'] ?? [],
+ ],
+ ];
+
+ $requests[] = [
+ 'addProtectedRange' => [
+ 'protectedRange' => $protectedRange,
+ ],
+ ];
+ }
+
+ if (! empty($requests)) {
+ $batch = new \Google_Service_Sheets_BatchUpdateSpreadsheetRequest([
+ 'requests' => $requests,
+ ]);
+
+ $this->sheets->spreadsheets->batchUpdate($spreadsheetId, $batch);
+ }
+
+ return true;
}
- if (!empty($requests)) {
- $batch = new \Google_Service_Sheets_BatchUpdateSpreadsheetRequest([
- 'requests' => $requests
- ]);
-
- $this->sheets->spreadsheets->batchUpdate($spreadsheetId, $batch);
- }
-
- return true;
-}
-
/* ================= URL ================= */
public function sheetUrl(string $sheetId): string
@@ -242,43 +240,41 @@ class GoogleSheetLib
return "https://docs.google.com/spreadsheets/d/{$sheetId}/edit";
}
+ private function convertA1ToGridRange($a1, $sheetId, $maxRows, $maxCols)
+ {
+ if (preg_match('/^([A-Z]+)(\d+)(?::([A-Z]+)(\d+))?$/i', $a1, $m)) {
- private function convertA1ToGridRange($a1, $sheetId, $maxRows, $maxCols)
-{
- if (preg_match('/^([A-Z]+)(\d+)(?::([A-Z]+)(\d+))?$/i', $a1, $m)) {
+ $startCol = $this->colToIndex($m[1]);
+ $startRow = intval($m[2]) - 1;
- $startCol = $this->colToIndex($m[1]);
- $startRow = intval($m[2]) - 1;
+ if (! empty($m[3])) {
+ $endCol = $this->colToIndex($m[3]) + 1;
+ $endRow = intval($m[4]);
+ } else {
+ $endCol = $startCol + 1;
+ $endRow = $startRow + 1;
+ }
- if (!empty($m[3])) {
- $endCol = $this->colToIndex($m[3]) + 1;
- $endRow = intval($m[4]);
- } else {
- $endCol = $startCol + 1;
- $endRow = $startRow + 1;
+ return [
+ 'sheetId' => $sheetId,
+ 'startRowIndex' => $startRow,
+ 'endRowIndex' => $endRow,
+ 'startColumnIndex' => $startCol,
+ 'endColumnIndex' => $endCol,
+ ];
}
- return [
- 'sheetId' => $sheetId,
- 'startRowIndex' => $startRow,
- 'endRowIndex' => $endRow,
- 'startColumnIndex' => $startCol,
- 'endColumnIndex' => $endCol
- ];
+ throw new \Exception("Unsupported A1 format: {$a1}");
}
- throw new \Exception("Unsupported A1 format: {$a1}");
-}
-
-private function colToIndex($letters)
-{
- $letters = strtoupper($letters);
- $index = 0;
- for ($i = 0; $i < strlen($letters); $i++) {
- $index = $index * 26 + (ord($letters[$i]) - 64);
+ private function colToIndex($letters)
+ {
+ $letters = strtoupper($letters);
+ $index = 0;
+ for ($i = 0; $i < strlen($letters); $i++) {
+ $index = $index * 26 + (ord($letters[$i]) - 64);
+ }
+ return $index - 1;
}
- return $index - 1;
-}
-
}
diff --git a/app/Libraries/MyGoogleDrive.php b/app/Libraries/MyGoogleDrive.php
index 566098eb..2fea0f9e 100644
--- a/app/Libraries/MyGoogleDrive.php
+++ b/app/Libraries/MyGoogleDrive.php
@@ -16,7 +16,7 @@ class MyGoogleDrive
{
$this->myLogger = \Config\Services::mylogger();
$this->client = new Google_Client();
- $this->client->setAuthConfig(ROOTPATH . 'nhance-app-google-drive.json'); // App credentials
+ $this->client->setAuthConfig(ROOTPATH . 'nhance-ee8d1-e3c5269b1ec7.json'); // App credentials
// putenv('GOOGLE_APPLICATION_CREDENTIALS=' . ROOTPATH . 'nhance-app-google-drive.json');
$this->client->useApplicationDefaultCredentials();
diff --git a/app/Libraries/TPAClaimsImportServices/BaseTpaClaimImportService.php b/app/Libraries/TPAClaimsImportServices/BaseTpaClaimImportService.php
index 137caf25..3ccbcadd 100644
--- a/app/Libraries/TPAClaimsImportServices/BaseTpaClaimImportService.php
+++ b/app/Libraries/TPAClaimsImportServices/BaseTpaClaimImportService.php
@@ -9,17 +9,30 @@ use App\Models\TicketMasterModel;
use App\Models\EmployeeModel;
use App\Models\ClaimDumpFileModel;
use App\Models\ClaimsDumpFhplModel;
+use App\Models\ClientPolicyModel;
+
use RuntimeException;
abstract class BaseTpaClaimImportService
{
protected BaseConnection $db;
protected $claimDumpFileModel;
+ protected $clientPolicyModel;
+ protected $policyNumberMapping;
public function __construct()
{
$this->db = db_connect();
$this->claimDumpFileModel = new ClaimDumpFileModel();
+ $this->clientPolicyModel = new ClientPolicyModel();
+ $this->policyNumberMapping = [
+ (int) env('VIDAL_PRIMARY_KEY_CONSTANT') => 'Insurer Policy Number',
+ (int) env('ABHI_PRIMARY_KEY_CONSTANT') => 'Policy Number',
+ (int) env('MEDI_ASSIST_PRIMARY_KEY_CONSTANT') => 'policy_no',
+ (int) env('FHPL_PRIMARY_KEY_CONSTANT') => 'Policy No',
+ (int) env('R_CARE_PRIMARY_KEY_CONSTANT') => 'Policy Number',
+ (int) env('ICICI_PRIMARY_KEY_CONSTANT') => 'POLICY_NO',
+ ];
}
/**
@@ -33,6 +46,8 @@ abstract class BaseTpaClaimImportService
try {
$fileData = $this->claimDumpFileModel->where('id', $fileId)->first();
+ $client_policy_data = $this->clientPolicyModel->where('id', $fileData['client_policy_id'])->first();
+
// Determine sheet name logic...
if (env('FHPL_PRIMARY_KEY_CONSTANT') == $fileData['tpa_id']) {
$rows = $this->readExcelBySheetName($filePath, 'Claims&Preauth');
@@ -47,6 +62,18 @@ abstract class BaseTpaClaimImportService
return ['status' => false, 'message' => 'Excel file contains no data or wrong file upload'];
}
+ if(isset($this->policyNumberMapping[$fileData['tpa_id']]) && !empty($this->policyNumberMapping[$fileData['tpa_id']])){
+ $policy_number_column = $this->policyNumberMapping[$fileData['tpa_id']];
+ }else{
+ $policy_number_column = 'policy_no';
+ }
+
+
+ if($client_policy_data['policy_no'] != ($rows[0][$policy_number_column] ?? '')){
+ $this->db->transRollback();
+ return ['status' => false, 'message' => 'Policy number mismatch in the file and in the system'];
+ }
+
$tpaInsertData = $this->mapTPAData($rows, $fileId);
if (empty($tpaInsertData)) {
diff --git a/app/Models/LeadsModel.php b/app/Models/LeadsModel.php
index 72ac2f59..507786c6 100644
--- a/app/Models/LeadsModel.php
+++ b/app/Models/LeadsModel.php
@@ -1,13 +1,12 @@
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 (!empty($where)) {
+ if (! empty($where)) {
$data->where($where);
}
@@ -185,7 +184,7 @@ class LeadsModel extends Model
public function getLeadForInsertClientList($type = null, $client_id = null)
{
- $query = $this->db->table('leads')
+ $query = $this->db->table('leads')
->select('leads.*, user_profiles.first_name as user_name')
->join('user_profiles', 'leads.created_by = user_profiles.id')
->where('leads.is_active', 1)
@@ -194,8 +193,6 @@ class LeadsModel extends Model
->where("(leads.is_client_created = '' OR leads.is_client_created IS NULL)")
->where("(leads.is_policy_created = '' OR leads.is_policy_created IS NULL)");
-
-
if ($type) {
$query->where('leads.lead_type', $type);
}
@@ -242,8 +239,8 @@ class LeadsModel extends Model
// $builder->select($select);
// // Auditing subquery
- // $subquery = "(SELECT pk, MAX(created_at) AS last_claim_status_change
- // FROM auditing_history
+ // $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)";
@@ -281,7 +278,7 @@ class LeadsModel extends Model
// // if (!str_ends_with($key, '_ids') && $key != "won") {
// // $total += (int) $value;
// // }
-
+
// if (!str_ends_with($key, '_ids')) {
// $total += (int) $value;
// }
@@ -291,12 +288,10 @@ class LeadsModel extends Model
// $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
@@ -321,7 +316,7 @@ class LeadsModel extends Model
$selectParts = [];
foreach ($statuses as $row) {
$status = $row['status'];
- $alias = strtolower(str_replace(' ', '_', $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`";
@@ -339,19 +334,17 @@ class LeadsModel extends Model
// Calculate total
$total = 0;
foreach ($lead_data as $key => $val) {
- if (!str_ends_with($key, '_ids')) {
+ 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['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;
}
-
-
}
diff --git a/app/Models/PolicyTransactionModel.php b/app/Models/PolicyTransactionModel.php
index e9656ad6..20da8dec 100644
--- a/app/Models/PolicyTransactionModel.php
+++ b/app/Models/PolicyTransactionModel.php
@@ -3098,6 +3098,8 @@
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' ";
diff --git a/app/Models/PolicyTypeModel.php b/app/Models/PolicyTypeModel.php
index 90aa1758..4e2dd802 100755
--- a/app/Models/PolicyTypeModel.php
+++ b/app/Models/PolicyTypeModel.php
@@ -1,14 +1,13 @@
select('sales_activities.*, user_profiles.first_name as assigned_to_name')
- ->join('user_profiles', 'user_profiles.id = sales_activities.assigned_to', 'left')
+ // Convert the INT id to a string, then wrap it in JSON quotes to match ["5", "11"]
+ $subQuery = "(SELECT GROUP_CONCAT(up2.first_name SEPARATOR ', ')
+ FROM user_profiles up2
+ WHERE JSON_CONTAINS(sales_activities.additional_assigned_ids, JSON_QUOTE(CAST(up2.id AS CHAR)))
+ ) as additional_assigned_names";
+
+ $builder = $this->select("sales_activities.*, up1.first_name as assigned_to_name, $subQuery")
+ ->join('user_profiles as up1', 'up1.id = sales_activities.assigned_to', 'left')
->where('sales_activities.lead_id', $leadId);
if ($status) {
@@ -78,7 +85,7 @@ class SalesActivityModel extends Model
/**
* Get all sales_activities with filters
*/
- public function getActivitiesWithFilters($filters = [], $limit = 10, $offset = 0)
+ public function getActivitiesWithFiltersOLD($filters = [], $limit = 10, $offset = 0)
{
$this->select('sales_activities.*, sales_actual_leads.company_name, user_profiles.first_name as assigned_to_name')
->join('sales_actual_leads', 'sales_actual_leads.lead_id = sales_activities.lead_id', 'left')
@@ -139,6 +146,90 @@ class SalesActivityModel extends Model
// ];
}
+ public function getActivitiesWithFilters($filters = [], $limit = 10, $offset = 0)
+ {
+ // 1. Initial Selection
+ $builder = $this->select("
+ sales_activities.*,
+ sales_actual_leads.company_name,
+ up1.first_name as assigned_to_name,
+ GROUP_CONCAT(DISTINCT up2.first_name SEPARATOR ', ') as additional_assigned_names
+ ")
+ ->join('sales_actual_leads', 'sales_actual_leads.lead_id = sales_activities.lead_id', 'left')
+ ->join('user_profiles as up1', 'up1.id = sales_activities.assigned_to', 'left');
+
+ // 2. The JSON Join for additional names
+ // Only attempts join if the string looks like a JSON array
+ $builder->join('user_profiles as up2', "
+ sales_activities.additional_assigned_ids IS NOT NULL
+ AND sales_activities.additional_assigned_ids != ''
+ AND sales_activities.additional_assigned_ids != '[]'
+ AND JSON_VALID(sales_activities.additional_assigned_ids)
+ AND JSON_CONTAINS(sales_activities.additional_assigned_ids, JSON_QUOTE(CAST(up2.id AS CHAR)))
+ ", 'left');
+
+ // 3. Apply Filters
+ if (!empty($filters['status'])) {
+ $builder->where('sales_activities.status', $filters['status']);
+ }
+
+ if (!empty($filters['activity_type'])) {
+ $builder->where('sales_activities.activity_type', $filters['activity_type']);
+ }
+
+ if (!empty($filters['assigned_to'])) {
+ $assignedToIds = is_array($filters['assigned_to']) ? $filters['assigned_to'] : explode(',', $filters['assigned_to']);
+ $builder->whereIn('sales_activities.assigned_to', $assignedToIds);
+ }
+
+ if (!empty($filters['search'])) {
+ $builder->groupStart()
+ ->like('sales_actual_leads.company_name', $filters['search'])
+ ->orLike('up1.first_name', $filters['search'])
+ ->groupEnd();
+ }
+
+ // 4. Grouping & Ordering
+ $builder->groupBy('sales_activities.activity_id');
+ $builder->orderBy('sales_activities.created_at', 'DESC');
+
+ // 5. Calculate Counts (using a clean builder to avoid the syntax error)
+ $counts = $this->getActivityStatusCounts($filters);
+
+ // 6. Get Data and Total
+ // Use true for countAllResults to get an accurate count of grouped rows
+ $totalCountQuery = clone $builder;
+ $total = $totalCountQuery->countAllResults(false);
+
+ $data = $builder->findAll($limit, $offset);
+
+ return [
+ 'data' => $data,
+ 'total' => $total,
+ 'counts' => $counts
+ ];
+ }
+
+ /**
+ * Helper function to get counts without breaking the main query syntax
+ */
+ private function getActivityStatusCounts($filters)
+ {
+ $validStatuses = ['pending', 'completed'];
+ $counts = ['all' => 0, 'pending' => 0, 'completed' => 0];
+
+ foreach ($validStatuses as $status) {
+ $query = $this->db->table('sales_activities')->where('status', $status);
+ if (!empty($filters['assigned_to'])) {
+ $ids = is_array($filters['assigned_to']) ? $filters['assigned_to'] : explode(',', $filters['assigned_to']);
+ $query->whereIn('assigned_to', $ids);
+ }
+ $counts[$status] = $query->countAllResults();
+ }
+ $counts['all'] = $counts['pending'] + $counts['completed'];
+ return $counts;
+ }
+
/**
* Complete an activity
*/
diff --git a/app/Models/SalesActualLeadModel.php b/app/Models/SalesActualLeadModel.php
index 22db6a2a..a5ca1026 100644
--- a/app/Models/SalesActualLeadModel.php
+++ b/app/Models/SalesActualLeadModel.php
@@ -123,7 +123,38 @@ class SalesActualLeadModel extends Model
$data = $this->findAll($limit, $offset);
- return ['data' => $data,'total' => $total];
+ $counts = $this->getLeadStatusCounts($filters);
+
+ return ['data' => $data,'total' => $total,'counts' => $counts];
+ }
+
+ /**
+ * Helper function to get counts without breaking the main query syntax
+ */
+ private function getLeadStatusCounts($filters)
+ {
+
+ $validStatuses = ['New', 'Potential', 'Prospects', 'Not a Prospects'];
+ $counts = ['all' => 0, 'New' => 0, 'Potential' => 0, 'Prospects' => 0, 'Not a Prospects' => 0];
+
+ foreach ($validStatuses as $status) {
+ $countQuery = $this->db->table('sales_actual_leads')
+ ->whereIn('status', $validStatuses);
+
+ // Apply assigned_to filter to counts too
+ if (!empty($filters['assigned_to'])) {
+ $assignedToIds = is_array($filters['assigned_to'])
+ ? $filters['assigned_to']
+ : explode(',', $filters['assigned_to']);
+ $countQuery->whereIn('assigned_to', $assignedToIds);
+ }
+
+ $counts[$status] = $countQuery->where('status', $status)->countAllResults();
+ }
+
+ $counts['all'] = array_sum($counts);
+
+ return $counts;
}
/**
diff --git a/app/Models/TicketMasterModel.php b/app/Models/TicketMasterModel.php
index 14101188..13682edb 100644
--- a/app/Models/TicketMasterModel.php
+++ b/app/Models/TicketMasterModel.php
@@ -1218,6 +1218,21 @@ class TicketMasterModel extends Model
}
+ public function isTpaApiServiceEnabled($ticket_id)
+ {
+ $result = $this->db->table('ticket_master tm')
+ ->select('tas.*')
+ ->join('client_policy cp', 'tm.client_policy_id = cp.id')
+ ->join('tpa_api_services tas', 'cp.tpa_id = tas.tpa_id')
+ ->where('tm.id', $ticket_id)
+ ->where('tm.is_active', 1)
+ ->where('cp.is_active', 1)
+ ->where('tas.is_active', 1)
+ ->get()->getRowArray();
+
+ return count($result ?? []) > 0 ? true : false; // true if any API service is enabled, false if no API service is enabled
+ }
+
// -----------------------------------------------------------------------------------------------------
}
diff --git a/app/Views/daily_report_email_template.php b/app/Views/daily_report_email_template.php
new file mode 100644
index 00000000..0ba7c8ff
--- /dev/null
+++ b/app/Views/daily_report_email_template.php
@@ -0,0 +1,347 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
Date: = $today ?>
+
+
+
Inception & Endorsement (File Upload)
+
+
+
Total Inception
+
= $total_inception_count ?>
+
Employee file uploads marked as inception
+
+
+
Total Endorsement
+
= $total_endorsement_count ?>
+
All non‑inception successful uploads
+
+
+
+
+
Employee Enrollment
+
+
+
Draft / Enrolled
+
= $total_employee_draft_count ?? 0 ?> / = $total_employee_enrolled_count ?? 0 ?>
+
Employees in draft / enrolled status for the day
+
+
+
Open for Enrollment Policies
+
= $total_open_for_enrollemnt_policy_count ?? 0 ?>
+
Policies currently open for enrollment
+
+
+
+
+
TPA & Insurer Batch Summary
+
+
+
TPA (Inception / Endorsement)
+
= $total_tpa_incetion_count ?> / = $total_tpa_endorsement_count ?>
+
Successful TPA events
+
+
+
Insurer (Inception / Endorsement)
+
= $total_insurer_incetion_count ?> / = $total_insurer_endorsement_count ?>
+
Successful insurer events
+
+
+
+
+
Sales Funnel & Leads
+
+
+
Opportunities & Won
+
= $total_opportunity_count ?> / = $total_placement_count ?>
+
Total opportunities created vs converted
+
+
+
RFQ (Created / Sent to Insurer)
+
= $total_rfq_created_count ?> / = $total_rfq_insurer_send_count ?>
+
Movement from opportunity to RFQ
+
+
+
QCR (Created / Sent to Client)
+
= $total_qcr_created_count ?> / = $total_qcr_client_send_count ?>
+
Quotes prepared and shared
+
+
+
Total Leads & Activities
+
= $total_lead_count ?> / = $total_activity_count ?>
+
Lead entries and logged touchpoints
+
+
+
+
+
BDS Policy Transactions
+
+
+
Total BDS Transactions
+
= $total_bds_count ?>
+
All policy transactions processed
+
+
+
BDS (Policy / Endorsement)
+
= $total_bds_policy_wise_count ?> / = $total_bds_endorsement_wise_count ?>
+
Split of inceptions vs endorsements
+
+
+
+
+
Claims
+
+
+
Total Claims Registered for the day
+
= $total_claim_count ?>
+
+
+
+
+
+
BDS by Policy Type
+
+
+
+
+ Policy Type
+ Count
+
+
+
+
+
+
+
+ = esc($row['policy_type']) ?>
+
+ = $row['count'] ?>
+
+
+
+
+
+ No BDS activity recorded for today.
+
+
+
+
+
+
+
+
+
Claim Status Breakdown
+
+ The total claims received so far are listed ticket type-wise.
+
+
+ $total_gmc_status_wise_claim_count ?? [],
+ 'GPA Claims' => $total_gpa_status_wise_claim_count ?? [],
+ 'EDLI Claims' => $total_edli_status_wise_claim_count ?? [],
+ 'GTLI Claims' => $total_gtli_status_wise_claim_count ?? [],
+ ];
+ $hasAnyClaimData = false;
+ ?>
+
+ $rows): ?>
+
+
+
= esc($sectionTitle) ?>
+
+
+
+
+ Status
+ Count
+
+
+
+
+
+
+ = esc($row['claim_status']) ?>
+
+ = $row['count'] ?>
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/app/Views/gsheet_editor.php b/app/Views/gsheet_editor.php
index e3c9f316..df694995 100644
--- a/app/Views/gsheet_editor.php
+++ b/app/Views/gsheet_editor.php
@@ -12,7 +12,7 @@
-Google Sheet Editor
+Edit RFQ
💾 Save
⬇ Download
@@ -44,9 +44,9 @@ function createRfq() {
-
+
@@ -146,7 +146,7 @@
-
+
\ No newline at end of file
diff --git a/app/Views/leads_list.php b/app/Views/leads_list.php
index 7ad9f74a..0136b414 100644
--- a/app/Views/leads_list.php
+++ b/app/Views/leads_list.php
@@ -17,8 +17,8 @@ table.dataTable tbody td {
}
.highlight {
- border: 2px solid red;
- background-color: #ffe6e6;
+ border: 2px solid red;
+ background-color: #ffe6e6;
}
.column-header {
@@ -37,6 +37,17 @@ table.dataTable tbody td {
margin-bottom: 10px;
}
+.select2-selection__choice {
+ background-color: #0a8794 !important;
+ color: white !important;
+ font-weight: bold;
+}
+
+.select2-selection__choice__remove {
+ color: white !important;
+ margin-right: 5px;
+}
+
.custom-dropdown-menu {
display: none;
@@ -181,20 +192,20 @@ table.dataTable tbody td {
-
- $row){ ?>
+
+ $row) {?>
-
-
+
-
+
@@ -209,27 +220,56 @@ table.dataTable tbody td {
-
-
+
+
No data available
-
+
-
+
@@ -253,6 +293,9 @@ table.dataTable tbody td {
+
+
+
@@ -261,14 +304,14 @@ table.dataTable tbody td {
×
-
+
-
+
+
+
+
+ No Upcoming Activities for this Financial Year.
+
+
+
My Recent Leads
+
+ placeholder="Search leads..." onkeyup="fetchLeads(false)" style="width: 300px !important;">
+ Add Lead
@@ -166,7 +189,7 @@
@@ -228,7 +251,7 @@
Lead Detail
-
×
+
×
@@ -270,7 +293,7 @@
+
+ Additional Assigner
+
+
+ = $sm['first_name'] ?>
+
+
+