diff --git a/.gitignore b/.gitignore
index e0e9251f..1ab80e5d 100755
--- a/.gitignore
+++ b/.gitignore
@@ -22,8 +22,8 @@ writable/debugbar/*
writable/**/*.db
writable/**/*.sqlite
-writable/e_card_template/*
-!writable/e_card_template/.gitkeep
+# writable/e_card_template/*
+# !writable/e_card_template/.gitkeep
writable/tmp/*
!writable/tmp/.gitkeep
diff --git a/app/Config/Routes.php b/app/Config/Routes.php
index 3aaaaabd..bd45495d 100755
--- a/app/Config/Routes.php
+++ b/app/Config/Routes.php
@@ -61,6 +61,7 @@ $routes->get('download-kyc-docs/(:segment)', 'ClientController::downloadKYCDocum
$routes->get('claim-form-download/(:any)', 'TicketController::downloadClaimForm/$1');
$routes->match (['get','post'],"claims-feedback-form/(:any)/(:any)", "TicketController::viewClaimFeedbackForm/$1/$2");
$routes->match (['get','post'],"claims-feedback-form/(:any)", "TicketController::viewClaimFeedbackForm/$1");
+$routes->get('downloadClaimFile/(:any)', 'TicketController::downloadClaimFile/$1');
@@ -73,6 +74,9 @@ $routes->group("/user", ["filter" => "authMVC"], function ($routes) {
$routes->get("deactive/(:hash)", "UserController::deactive/$1");
$routes->get("rolesandteams", "UserController::getRolesAndTeams");
$routes->get("getUserActivityHistory", "UserController::getUserActivityHistory");
+ $routes->match(['get','post','put'], 'partner', 'UserController::partner');
+ $routes->match(['get','post','put'], 'partnerIncentive', 'UserController::partnerIncentive');
+ $routes->get("download-incentive-file/(:any)", "UserController::downloadIncentivesFile/$1");
});
$routes->group("/dashboard", ["filter" => "authMVC"], function ($routes) {
@@ -181,8 +185,11 @@ $routes->group("/employee", ["filter" => "authMVC"], function ($routes) {
$routes->post("test-rack-rate", "EmployeeController::testRackRate");
$routes->get('test_members_list', 'EmployeeController::test_members_list');
$routes->post('get_emp_history','EmployeeController::getEmpHistory');
+ $routes->get("retail-endorsement-list", "EmployeeController::retailendorsementList");
});
+
+
$routes->group("/master", ["filter" => "authMVC"], function ($routes) {
$routes->group("insurer", ["filter" => "authMVC"], function ($routes) {
@@ -362,14 +369,19 @@ $routes->group("/util", ["filter" => "authMVC"], function ($routes) {
$routes->get('transformMailContent', 'LeadsController::transformMailContent');
$routes->get('getCDAmount', 'ClientController::getCDAmount');
$routes->get('getTheEmpDataForClaim/(:any)', 'ClientController::getTheEmpDataForClaim/$1');
- $routes->get('getTheEmpDataForClaimSearchByMobile/(:any)', 'ClientController::getTheEmpDataForClaimSearchByMobile/$1');
+ // $routes->get('getTheEmpDataForClaimSearchByMobile/(:any)', 'ClientController::getTheEmpDataForClaimSearchByMobile/$1');
+ $routes->get('getTheEmpDataForClaimSearchByMobile', 'ClientController::getTheEmpDataForClaimSearchByMobile');
$routes->get('getLeadNonEB/(:any)', 'LeadsController::getLeadNonEB/$1');
$routes->get('getPolicyTypeFields', 'LeadsController::getPolicyTypeFields');
$routes->get('removeMultiFile', 'LeadsController::removeMultiFile');
$routes->get('removeInstallments', 'LeadsController::removeInstallments');
+ $routes->get('getLeadEmailHistory/(:any)', 'LeadsController::getLeadEmailHistory/$1');
$routes->get('viewHrAccessData', 'ClientController::viewHrAccessData');
$routes->post('saveHrAccessData', 'ClientController::saveHrAccessData');
$routes->get('removeLevelContacts', 'ClientController::removeLevelContacts');
+ $routes->get('getClaimDumpFileErrorData', 'TicketController::getClaimDumpFileErrorData');
+ $routes->get("claim_dump_excel_error/(:any)", "TicketController::getClaimDumpExcelFileErrors/$1");
+ $routes->get("download_claim_dump_file/(:any)", "TicketController::downloadClaimDumpFile/$1");
});
$routes->post("policy_tranction/sendInstallmentRemainderMail","PolicyTransactionController::sendInstallmentRemainderMail");
@@ -447,7 +459,6 @@ $routes->get('cli/sendZeptoMail', 'MasterController::testZeptoSMTP');
$routes->cli('cli/processjob', 'JobWorker::processJob');
$routes->cli('cli/processjobs', 'JobWorker::processJobs');
-$routes->cli('cli/sendMailWithAutoQuery','TicketController::sendMailWithAutoQuery');
$routes->get("processjob", "JobWorker::processJob");
$routes->cli('cli/new_gmail_token', 'MasterController::generateNewGmailAPIToken');
@@ -461,6 +472,10 @@ $routes->cli('cli/new_gdrive_token', 'GoogleDriveController::generateNewGoogleDr
$routes->cli('cli/enrollOpendAndClose', 'DashboardController::updatePolicyEnrollmentStatus');
$routes->cli("cli/sendCroneRemainderMail", "DashboardController::sendCroneRemainderMail");
$routes->cli('cli/update-emp-policy-status', 'ClientController::updateEmpAndPolicyStatus');
+$routes->cli('cli/update-emp-policy-status', 'ClientController::updateEmpAndPolicyStatus');
+$routes->cli('cli/insurerRFQRemainder', 'LeadsController::remainderForQcr');
+$routes->cli('cli/sendMailWithAutoQuery','TicketController::sendMailWithAutoQuery');
+
//Employee login api's
$routes->post("/employeeRest/verifyEmployeeNumber", "RestAuthenticationController::verifyEmployeeWithMobileNumber");
@@ -491,9 +506,6 @@ $routes->get('get_ticket_data',"EmployeeRestController::get_ticket_data");
$routes->group("/api", ["filter" => "authJWT"], function ($routes) {
$routes->post("logined", "RestAuthenticationController::logined");
$routes->post("getId", "RestAuthenticationController::getUserIdFromToken");
- $routes->post('initiateClaim',"EmployeeRestController::initiateClaim");
- $routes->get('get_ticket_type',"EmployeeRestController::get_ticket_type");
- $routes->get('get_ticket_data',"EmployeeRestController::get_ticket_data");
});
$routes->post("employeeRest/saveMpin", "RestAuthenticationController::saveMpin");
@@ -551,7 +563,30 @@ $routes->group("employeeRest", ["filter" => "authJWT"], function ($routes) {
$routes->get("claimView", "EmployeeRestController::claimView");
$routes->get("exportCashDepositData", "EmployeeRestController::exportCashDepositData");
+
+ //thz_master's
+ $routes->post("ticketSave", "ThzController::ticketSave");
+ $routes->get("ticketList", "ThzController::ticketList");
+ $routes->post("ticketConversationSave", "ThzController::ticketConversationSave");
+ $routes->get("ticketConversationList", "ThzController::ticketConversationList");
+ $routes->get("ticketHistoryList", "ThzController::ticketHistoryList");
+ $routes->match(['get','post','put'], 'ticketType', 'ThzController::ticketType');
+
+ $routes->get("hrFileList", "EmployeeRestController::hrFileList");
+ $routes->get("hrFileUploadMasters", "EmployeeRestController::hrFileUploadMasters");
+ $routes->get("hrFileDownload", "EmployeeRestController::hrFileDownload");
+ $routes->post("hrFileUpload", "EmployeeRestController::hrFileUpload");
+ $routes->post("updateHrFileUploadData", "EmployeeRestController::updateHrFileUploadData");
+
+ //claims
+ $routes->post('initiateClaim',"EmployeeRestController::initiateClaim");
+ $routes->get('get_ticket_type',"EmployeeRestController::get_ticket_type");
+ $routes->get('get_ticket_data',"EmployeeRestController::get_ticket_data");
+
+
});
+$routes->get("hrFileDownload", "EmployeeRestController::hrFileDownload");
+$routes->post("hrFileList", "EmployeeRestController::hrFileList");
$routes->get("getEmployeeActiveOrInactivePolicy", "EmployeeRestController::getEmployeeActiveOrInactivePolicy");
$routes->get("sendPushNotification", "EmployeeRestController::sendPushNotification");
$routes->post("sendEmail", "EmployeeRestController::send_email");
@@ -598,6 +633,8 @@ $routes->group("/ticket", ["filter" => "authMVC"], function ($routes) {
$routes->post('upload_url',"TicketController::upload_url");
$routes->post('getUrlDataByTicketId',"TicketController::getUrlDataByTicketId");
$routes->get('remove_url',"TicketController::remove_url");
+ $routes->get('fetchVehiclePolicy/(:any)','TicketController::fetchVehiclePolicy/$1');
+
});
$routes->group("clientApi",["filter" => "AuthClientApi"], function ($routes){
@@ -636,6 +673,21 @@ $routes->post('enrollment','VidalApiController::enrollment');
$routes->post("ticketSave", "ThzController::ticketSave");
-$routes->post("ticketList", "ThzController::ticketList");
+$routes->get("ticketList", "ThzController::ticketList");
$routes->post("ticketConversationSave", "ThzController::ticketConversationSave");
-$routes->post("ticketConversationList", "ThzController::ticketConversationList");
\ No newline at end of file
+$routes->get("ticketConversationList", "ThzController::ticketConversationList");
+$routes->post('ticketAutoFetchDetails',"ThzController::ticketAutoFetchDetails");
+$routes->match(['get','post','put'], 'ticketType', 'ThzController::ticketType');
+$routes->get("ticketHistoryList", "ThzController::ticketHistoryList");
+
+
+//for testing
+$routes->group('test', function($routes) {
+ $routes->post('api/saveForm', 'TestingController::saveForm');
+ $routes->get('insurerRFQRemainder', 'LeadsController::remainderForQcr');
+ $routes->get('generatePDF', 'TestingController::generatePDF');
+ $routes->get('viewPDF', 'TestingController::viewPDF');
+ $routes->get('generate-pdf-view', 'TestingController::generatePDFWithView');
+});
+$routes->cli('cli/testcli', 'TestingController::testcli');
+
diff --git a/app/Controllers/ClientController.php b/app/Controllers/ClientController.php
index d4bfa5d8..2e9e11c9 100755
--- a/app/Controllers/ClientController.php
+++ b/app/Controllers/ClientController.php
@@ -143,7 +143,11 @@ class ClientController extends AdminController
// Perform the query
$builder = $db->table($table);
- $isDuplicate = $builder->where($field, $value)->where('is_active', 1)->countAllResults() > 0;
+ if(is_array($value)){
+ $isDuplicate = $builder->where($value)->where('is_active', 1)->countAllResults() > 0;
+ }else{
+ $isDuplicate = $builder->where($field, $value)->where('is_active', 1)->countAllResults() > 0;
+ }
// Return the result
return $this->response->setJSON(['isDuplicate' => $isDuplicate]);
@@ -180,7 +184,7 @@ class ClientController extends AdminController
public function testMailAttachments($email = 'venkateshraman786@gmail.com')
{
- $message = '
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
';
+ $message = '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
';
// $attachments = [
// ["filePath" => ROOTPATH."public/sample_excel/sample_addition.xls","fileName" => "sample_addition.xls"],
@@ -768,6 +772,8 @@ class ClientController extends AdminController
$editData['client'] = $this->clientModel->where(['id' => $id])->first();
$editData['client_kyc'] = $this->clientKYCDocsModel->where('client_id', $id)->findAll();
+ $editData['client_kyc_primary_table'] = $this->generateKycPrimaryTable($id);
+ $editData['client_kyc_other_table'] = $this->generateKycOthersTable($id);
$editData['client_branch'] = $this->clientBranchModel->where(['client_id' => $id, 'is_active' => 1])->findAll();
$editData['client_relation'] = $this->clientRMModel->where(['client_id' => $id, 'is_active' => 1])->findAll();
$editData['client_branch']['role'] = get_role_id();
@@ -866,6 +872,8 @@ class ClientController extends AdminController
{
$this->myLogger->logme('error', 'create Client kyc function called');
$data = $this->request->getPost();
+ $form_type = $this->request->getPost('form_type') ?? null;
+
// print_r($data); die;
unset($data['file_name']);
$uploadFilePath = WRITEPATH . 'uploads/client_kyc_documents';
@@ -881,8 +889,12 @@ class ClientController extends AdminController
$data['created_by'] = get_session_userid();
$insert = $this->clientKYCDocsModel->insert($data);
if ($insert) {
-
- $kycDocs = $this->clientKYCDocsModel->where('client_id', $this->request->getPost('client_id'))->findAll();
+ // $kycDocs = $this->clientKYCDocsModel->where('client_id', $this->request->getPost('client_id'))->findAll();
+ if($form_type == "others"){
+ $kycDocs = $this->generateKycOthersTable($this->request->getPost('client_id'));
+ }else{
+ $kycDocs = $this->generateKycPrimaryTable($this->request->getPost('client_id'));
+ }
return $this->respond(['status' => true, 'code' => 200, 'data' => $kycDocs, 'file_name' => $File], 200);
} else {
return $this->respond(['status' => false, 'code' => 404, 'message' => 'no data found'], 200);
@@ -895,6 +907,8 @@ class ClientController extends AdminController
$this->myLogger->logme('error', 'edit client kyc function called');
$uploadFilePath = WRITEPATH . 'uploads/client_kyc_documents';
$File = file_Upload($this->request->getFile('file_name'), $uploadFilePath);
+ $form_type = $this->request->getPost('form_type') ?? null;
+
if (!empty($File)) {
$data['file_name'] = $File;
}
@@ -903,8 +917,14 @@ class ClientController extends AdminController
$data['kyc_doc_type_id'] = $this->request->getPost('kyc_doc_id');
$data['updated_by'] = get_session_userid();
$insert = $this->clientKYCDocsModel->insert($data);
+
if ($insert) {
- $kycDocs = $this->clientKYCDocsModel->getKycDocsName($id);
+ // $kycDocs = $this->clientKYCDocsModel->getKycDocsName($id);
+ if($form_type == "others"){
+ $kycDocs = $this->generateKycOthersTable($this->request->getPost('client_id'));
+ }else{
+ $kycDocs = $this->generateKycPrimaryTable($this->request->getPost('client_id'));
+ }
return $this->respond(['status' => true, 'code' => 200, 'data' => $kycDocs], 200);
} else {
return $this->respond(['status' => false, 'code' => 404, 'message' => 'no data found'], 200);
@@ -2144,6 +2164,50 @@ class ClientController extends AdminController
}
}
+ public function generateKycPrimaryTable($client_id){
+
+ $db = db_connect();
+ $builder = $db->table('kyc_docs kd');
+ $builder->select('kd.*, ck.file_name AS upload_doc_name');
+ $builder->join('clients c', 'kd.kyc_type_id = c.entity_type_id');
+ $builder->join(
+ 'client_kyc_documents ck',
+ 'kd.id = ck.kyc_doc_type_id AND ck.client_id = c.id AND ck.is_active = 1',
+ 'left'
+ );
+ $builder->where('c.id', $client_id);
+ $builder->groupBy(['kd.id', 'ck.file_name']);
+
+ $query = $builder->get();
+ $result['data'] = $query->getResultArray();
+ $result['client_id'] = $client_id;
+
+ $table = view('client_kyc_primary_table', $result);
+
+ return $table;
+ // print_r($table); die;
+
+ }
+
+ public function generateKycOthersTable($client_id){
+
+ $result['data'] = $this->clientKYCDocsModel
+ ->where('is_active', 1)
+ ->where('client_id', $client_id)
+ ->groupStart()
+ ->where('kyc_doc_type_id', null)
+ ->orWhere('kyc_doc_type_id', 0)
+ ->groupEnd()
+ ->findAll();
+
+ $result['client_id'] = $client_id;
+ $table = view('client_kyc_other_table', $result);
+
+ return $table;
+ // print_r($table); die;
+
+ }
+
public function getPolicesByInsurerId($id = null)
{
$this->myLogger->logme('error', 'getPolicesByInsurerId function called');
@@ -2419,6 +2483,7 @@ class ClientController extends AdminController
// echo "";
// print_r($this->request->getPost());die;
+ $this->myLogger->logme('error', "post data : " . json_encode($this->request->getPost() ?? []));
$this->myLogger->logme('error', 'Terms CREATE function called');
/*** Client Policy Table Primary Key(ID) ***/
@@ -2620,7 +2685,7 @@ class ClientController extends AdminController
}
$data['enrollment_display_key'] = $this->enrollmentGMCDisplayValueTransform();
-
+ $this->myLogger->logme('error', "contructed post data : " . json_encode($data ?? []));
// print_r($data);die;
$jsonData = json_encode($data);
@@ -2654,194 +2719,269 @@ class ClientController extends AdminController
}
}
+ // public function enrollmentGMCDisplayValueTransform()
+ // {
+ // $data = [];
+
+ // if ($this->request->getPost("waiverofpreexistingdiseases_display")) {
+ // $data['Waiver of Pre-existing Diseases'] = $this->request->getPost("waiverofpreexistingdiseases");
+ // }
+
+ // if ($this->request->getPost("waiverof1234thyearexclusions_display")) {
+ // $data['Waiver of 1, 2, 3 & 4th year Exclusions'] = $this->request->getPost("waiverof1,2,3&4thyearexclusions");
+ // }
+
+ // if ($this->request->getPost("waiverof30dayswaitingperiod_display")) {
+ // $data['Waiver of 30 days waiting period'] = $this->request->getPost("waiverof30dayswaitingperiod");
+ // }
+
+ // if ($this->request->getPost("suminsuredenhancement_display")) {
+ // $data['Sum Insured Enhancement'] = $this->request->getPost("suminsuredenhancement");
+ // }
+
+ // if ($this->request->getPost("waiver_of_90_days_waiting_period_display")) {
+ // $data['Waiver of 90 Days Waiting Period'] = $this->request->getPost("waiver_of_90_days_waiting_period");
+ // }
+
+ // if ($this->request->getPost("waiver_of_other_waiting_periods_display")) {
+ // $data['Waiver of Other Waiting Periods'] = $this->request->getPost("waiver_of_other_waiting_periods");
+ // }
+
+ // if ($this->request->getPost("maternity_benefit_display")) {
+ // $data['Maternity Benefit'] = $this->request->getPost("maternity_benefit");
+ // }
+
+ // if ($this->request->getPost("9monthwaitingperiodwaived_display")) {
+ // $data['9-month waiting Period - waived'] = $this->request->getPost("9monthwaitingperiodwaived");
+ // }
+
+ // if ($this->request->getPost("maternitycoverage_display")) {
+ // $data['Maternity Coverage'] = $this->request->getPost("maternitycoverage");
+ // }
+
+ // if ($this->request->getPost("twindelivery_display")) {
+ // $data['Twin Delivery'] = $this->request->getPost("twindelivery");
+ // }
+
+ // if ($this->request->getPost("well_baby_well_mother_expenses_display")) {
+ // $data['Well baby / Well Mother Expenses'] = $this->request->getPost("well_baby_well_mother_expenses");
+ // }
+
+ // if ($this->request->getPost("preandpostnatal_display")) {
+ // $data['Pre and Post natal'] = $this->request->getPost("preandpostnatal");
+ // }
+
+ // if ($this->request->getPost("infertility_treatment_coverage_display")) {
+ // $data['Infertility Treatment Coverage'] = $this->request->getPost("infertility_treatment_coverage");
+ // }
+
+ // if ($this->request->getPost("babyday1cover_display")) {
+ // $data['Baby Day 1 Cover'] = $this->request->getPost("babyday1cover");
+ // }
+
+ // if ($this->request->getPost("coverfromthedateofjoining_display")) {
+ // $data['Cover from the date of Joining'] = $this->request->getPost("coverfromthedateofjoining");
+ // }
+
+ // if ($this->request->getPost("mid_term_addition_of_new_born_newly_wedded_spouse_display")) {
+ // $data['Mid Term Addition of New Born / Newly Wedded Spouse'] = $this->request->getPost("mid_term_addition_of_new_born_newly_wedded_spouse");
+ // }
+
+ // if ($this->request->getPost("prehospitalizationcover_display")) {
+ // $data['Pre Hospitalization Cover'] = $this->request->getPost("prehospitalizationcover");
+ // }
+
+ // if ($this->request->getPost("posthospitalizationcover_display")) {
+ // $data['Post Hospitalization Cover'] = $this->request->getPost("posthospitalizationcover");
+ // }
+
+ // if ($this->request->getPost("congenitaldiseasesinternal_display")) {
+ // $data['Congenital Diseases - Internal'] = $this->request->getPost("congenitaldiseasesinternal");
+ // }
+
+ // if ($this->request->getPost("congenitaldiseasesexternal_display")) {
+ // $data['Congenital Diseases - External'] = $this->request->getPost("congenitaldiseasesexternal");
+ // }
+
+ // if ($this->request->getPost("copayzonewisecopay_display")) {
+ // $data['Co-Pay/Zone wise Co Pay'] = $this->request->getPost("copayzonewisecopay");
+ // }
+
+ // if ($this->request->getPost("roomrentlimit_display")) {
+ // $data['Room Rent Limit'] = $this->request->getPost("roomrentlimit");
+ // }
+
+ // if ($this->request->getPost("icu_limit_display")) {
+ // $data['ICU Limit'] = $this->request->getPost("icu_limit");
+ // }
+
+ // if ($this->request->getPost("proportionatedeductionclause_display")) {
+ // $data['Proportionate Deduction Clause'] = $this->request->getPost("proportionatedeductionclause");
+ // }
+
+ // if ($this->request->getPost("ailmentcapping_display")) {
+ // $data['Ailment capping'] = $this->request->getPost("ailmentcapping");
+ // }
+
+ // if ($this->request->getPost("ailment_capping_details_display")) {
+ // $data['Ailment capping Details'] = $this->request->getPost("ailment_capping_details");
+ // }
+
+ // if ($this->request->getPost("corporatebuffer_display")) {
+ // $data['Corporate Buffer'] = $this->request->getPost("corporatebuffer");
+ // }
+
+ // if ($this->request->getPost("non_admissible_contingency_corporate_buffer_display")) {
+ // $data['Non-Admissible / Contingency Corporate Buffer'] = $this->request->getPost("non_admissible_contingency_corporate_buffer");
+ // }
+
+ // if ($this->request->getPost("ambulancecharges_display")) {
+ // $data['Ambulance Charges'] = $this->request->getPost("ambulancecharges");
+ // }
+
+ // if ($this->request->getPost("airambulance_display")) {
+ // $data['Air Ambulance'] = $this->request->getPost("airambulance");
+ // }
+
+ // if ($this->request->getPost("reasonableandcustomarycharges_display")) {
+ // $data['Reasonable and Customary Charges'] = $this->request->getPost("reasonableandcustomarycharges");
+ // }
+
+ // if ($this->request->getPost("daycaretreatment_display")) {
+ // $data['Day Care Treatment'] = $this->request->getPost("daycaretreatment");
+ // }
+
+ // if ($this->request->getPost("lasiksurgery_display")) {
+ // $data['Lasik Surgery'] = $this->request->getPost("lasiksurgery");
+ // }
+
+ // if ($this->request->getPost("ayushtreatmentcover_display")) {
+ // $data['AYUSH treatment cover'] = $this->request->getPost("ayudhtreatmentcover");
+ // }
+
+ // if ($this->request->getPost("moderntreatmentsasperirdai_display")) {
+ // $data['Modern treatments as per IRDAI'] = $this->request->getPost("moderntreatmentsasperirdai");
+ // }
+
+ // if ($this->request->getPost("opd_treatment_display")) {
+ // $data['OPD Treatment'] = $this->request->getPost("opd_treatment");
+ // }
+
+ // if ($this->request->getPost("days_of_discharge_display")) {
+ // $data['Claim Intimation Clause'] = $this->request->getPost("days_of_discharge");
+ // }
+
+ // if ($this->request->getPost("days_from_dod_display")) {
+ // $data['Claim Submission'] = $this->request->getPost("days_from_dod");
+ // }
+
+ // if ($this->request->getPost("terrorism_display")) {
+ // $data['Terrorism'] = $this->request->getPost("terrorism");
+ // }
+
+ // if ($this->request->getPost("widower_cover_display")) {
+ // $data['Widower Cover'] = $this->request->getPost("widower_cover");
+ // }
+
+ // if ($this->request->getPost("breavement_cover_display")) {
+ // $data['Breavement Cover'] = $this->request->getPost("breavement_cover");
+ // }
+
+ // if ($this->request->getPost("special_condition_display_value")) {
+
+ // $specialConditionKeyValue = $this->request->getPost("special_condition_display_value") ?? [];
+ // $specialConditionKeyValue = json_decode($specialConditionKeyValue, true);
+
+ // if (is_array($specialConditionKeyValue) && count($specialConditionKeyValue) > 0) {
+ // $mergedArray = array_merge(...array_map(fn($item) => (array) $item, $specialConditionKeyValue));
+ // $data = array_merge($data, $mergedArray);
+ // }
+ // }
+
+ // if(isset($data) && !empty($data)){
+ // return $data;
+ // }else{
+ // $data = [];
+ // return $data;
+ // }
+
+ // }
+
public function enrollmentGMCDisplayValueTransform()
{
$data = [];
- if ($this->request->getPost("waiverofpreexistingdiseases_display")) {
- $data['Waiver of Pre-existing Diseases'] = $this->request->getPost("waiverofpreexistingdiseases");
- }
-
- if ($this->request->getPost("waiverof1234thyearexclusions_display")) {
- $data['Waiver of 1, 2, 3 & 4th year Exclusions'] = $this->request->getPost("waiverof1,2,3&4thyearexclusions");
- }
-
- if ($this->request->getPost("waiverof30dayswaitingperiod_display")) {
- $data['Waiver of 30 days waiting period'] = $this->request->getPost("waiverof30dayswaitingperiod");
- }
+ // Mapping of POST keys to display labels
+ $fields = [
+ 'waiverofpreexistingdiseases' => 'Waiver of Pre-existing Diseases',
+ 'waiverof1,2,3&4thyearexclusions' => 'Waiver of 1, 2, 3 & 4th year Exclusions',
+ 'waiverof30dayswaitingperiod' => 'Waiver of 30 days waiting period',
+ 'suminsuredenhancement' => 'Sum Insured Enhancement',
+ 'waiver_of_90_days_waiting_period' => 'Waiver of 90 Days Waiting Period',
+ 'waiver_of_other_waiting_periods' => 'Waiver of Other Waiting Periods',
+ 'maternity_benefit' => 'Maternity Benefit',
+ '9monthwaitingperiodwaived' => '9-month waiting Period - waived',
+ 'maternitycoverage' => 'Maternity Coverage',
+ 'twindelivery' => 'Twin Delivery',
+ 'well_baby_well_mother_expenses' => 'Well baby / Well Mother Expenses',
+ 'preandpostnatal' => 'Pre and Post natal',
+ 'infertility_treatment_coverage' => 'Infertility Treatment Coverage',
+ 'babyday1cover' => 'Baby Day 1 Cover',
+ 'coverfromthedateofjoining' => 'Cover from the date of Joining',
+ 'mid_term_addition_of_new_born_newly_wedded_spouse' => 'Mid Term Addition of New Born / Newly Wedded Spouse',
+ 'prehospitalizationcover' => 'Pre Hospitalization Cover',
+ 'posthospitalizationcover' => 'Post Hospitalization Cover',
+ 'congenitaldiseasesinternal' => 'Congenital Diseases - Internal',
+ 'congenitaldiseasesexternal' => 'Congenital Diseases - External',
+ 'copayzonewisecopay' => 'Co-Pay/Zone wise Co Pay',
+ 'roomrentlimit' => 'Room Rent Limit',
+ 'icu_limit' => 'ICU Limit',
+ 'proportionatedeductionclause' => 'Proportionate Deduction Clause',
+ 'ailmentcapping' => 'Ailment capping',
+ 'ailment_capping_details' => 'Ailment capping Details',
+ 'corporatebuffer' => 'Corporate Buffer',
+ 'non_admissible_contingency_corporate_buffer' => 'Non-Admissible / Contingency Corporate Buffer',
+ 'ambulancecharges' => 'Ambulance Charges',
+ 'airambulance' => 'Air Ambulance',
+ 'reasonableandcustomarycharges' => 'Reasonable and Customary Charges',
+ 'daycaretreatment' => 'Day Care Treatment',
+ 'lasiksurgery' => 'Lasik Surgery',
+ 'ayudhtreatmentcover' => 'AYUSH treatment cover',
+ 'moderntreatmentsasperirdai' => 'Modern treatments as per IRDAI',
+ 'opd_treatment' => 'OPD Treatment',
+ 'days_of_discharge' => 'Claim Intimation Clause',
+ 'days_from_dod' => 'Claim Submission',
+ 'terrorism' => 'Terrorism',
+ 'widower_cover' => 'Widower Cover',
+ 'breavement_cover' => 'Breavement Cover'
+ ];
- if ($this->request->getPost("suminsuredenhancement_display")) {
- $data['Sum Insured Enhancement'] = $this->request->getPost("suminsuredenhancement");
- }
-
- if ($this->request->getPost("waiver_of_90_days_waiting_period_display")) {
- $data['Waiver of 90 Days Waiting Period'] = $this->request->getPost("waiver_of_90_days_waiting_period");
- }
-
- if ($this->request->getPost("waiver_of_other_waiting_periods_display")) {
- $data['Waiver of Other Waiting Periods'] = $this->request->getPost("waiver_of_other_waiting_periods");
- }
-
- if ($this->request->getPost("maternity_benefit_display")) {
- $data['Maternity Benefit'] = $this->request->getPost("maternity_benefit");
- }
-
- if ($this->request->getPost("9monthwaitingperiodwaived_display")) {
- $data['9-month waiting Period - waived'] = $this->request->getPost("9monthwaitingperiodwaived");
- }
-
- if ($this->request->getPost("maternitycoverage_display")) {
- $data['Maternity Coverage'] = $this->request->getPost("maternitycoverage");
- }
-
- if ($this->request->getPost("twindelivery_display")) {
- $data['Twin Delivery'] = $this->request->getPost("twindelivery");
- }
-
- if ($this->request->getPost("well_baby_well_mother_expenses_display")) {
- $data['Well baby / Well Mother Expenses'] = $this->request->getPost("well_baby_well_mother_expenses");
- }
-
- if ($this->request->getPost("preandpostnatal_display")) {
- $data['Pre and Post natal'] = $this->request->getPost("preandpostnatal");
- }
-
- if ($this->request->getPost("infertility_treatment_coverage_display")) {
- $data['Infertility Treatment Coverage'] = $this->request->getPost("infertility_treatment_coverage");
- }
-
- if ($this->request->getPost("babyday1cover_display")) {
- $data['Baby Day 1 Cover'] = $this->request->getPost("babyday1cover");
- }
-
- if ($this->request->getPost("coverfromthedateofjoining_display")) {
- $data['Cover from the date of Joining'] = $this->request->getPost("coverfromthedateofjoining");
- }
-
- if ($this->request->getPost("mid_term_addition_of_new_born_newly_wedded_spouse_display")) {
- $data['Mid Term Addition of New Born / Newly Wedded Spouse'] = $this->request->getPost("mid_term_addition_of_new_born_newly_wedded_spouse");
- }
-
- if ($this->request->getPost("prehospitalizationcover_display")) {
- $data['Pre Hospitalization Cover'] = $this->request->getPost("prehospitalizationcover");
- }
-
- if ($this->request->getPost("posthospitalizationcover_display")) {
- $data['Post Hospitalization Cover'] = $this->request->getPost("posthospitalizationcover");
- }
-
- if ($this->request->getPost("congenitaldiseasesinternal_display")) {
- $data['Congenital Diseases - Internal'] = $this->request->getPost("congenitaldiseasesinternal");
- }
-
- if ($this->request->getPost("congenitaldiseasesexternal_display")) {
- $data['Congenital Diseases - External'] = $this->request->getPost("congenitaldiseasesexternal");
- }
-
- if ($this->request->getPost("copayzonewisecopay_display")) {
- $data['Co-Pay/Zone wise Co Pay'] = $this->request->getPost("copayzonewisecopay");
- }
-
- if ($this->request->getPost("roomrentlimit_display")) {
- $data['Room Rent Limit'] = $this->request->getPost("roomrentlimit");
- }
-
- if ($this->request->getPost("icu_limit_display")) {
- $data['ICU Limit'] = $this->request->getPost("icu_limit");
- }
-
- if ($this->request->getPost("proportionatedeductionclause_display")) {
- $data['Proportionate Deduction Clause'] = $this->request->getPost("proportionatedeductionclause");
- }
-
- if ($this->request->getPost("ailmentcapping_display")) {
- $data['Ailment capping'] = $this->request->getPost("ailmentcapping");
- }
-
- if ($this->request->getPost("ailment_capping_details_display")) {
- $data['Ailment capping Details'] = $this->request->getPost("ailment_capping_details");
- }
-
- if ($this->request->getPost("corporatebuffer_display")) {
- $data['Corporate Buffer'] = $this->request->getPost("corporatebuffer");
- }
-
- if ($this->request->getPost("non_admissible_contingency_corporate_buffer_display")) {
- $data['Non-Admissible / Contingency Corporate Buffer'] = $this->request->getPost("non_admissible_contingency_corporate_buffer");
- }
-
- if ($this->request->getPost("ambulancecharges_display")) {
- $data['Ambulance Charges'] = $this->request->getPost("ambulancecharges");
- }
-
- if ($this->request->getPost("airambulance_display")) {
- $data['Air Ambulance'] = $this->request->getPost("airambulance");
- }
-
- if ($this->request->getPost("reasonableandcustomarycharges_display")) {
- $data['Reasonable and Customary Charges'] = $this->request->getPost("reasonableandcustomarycharges");
- }
-
- if ($this->request->getPost("daycaretreatment_display")) {
- $data['Day Care Treatment'] = $this->request->getPost("daycaretreatment");
- }
-
- if ($this->request->getPost("lasiksurgery_display")) {
- $data['Lasik Surgery'] = $this->request->getPost("lasiksurgery");
- }
-
- if ($this->request->getPost("ayushtreatmentcover_display")) {
- $data['AYUSH treatment cover'] = $this->request->getPost("ayudhtreatmentcover");
- }
-
- if ($this->request->getPost("moderntreatmentsasperirdai_display")) {
- $data['Modern treatments as per IRDAI'] = $this->request->getPost("moderntreatmentsasperirdai");
- }
-
- if ($this->request->getPost("opd_treatment_display")) {
- $data['OPD Treatment'] = $this->request->getPost("opd_treatment");
- }
-
- if ($this->request->getPost("days_of_discharge_display")) {
- $data['Claim Intimation Clause'] = $this->request->getPost("days_of_discharge");
- }
-
- if ($this->request->getPost("days_from_dod_display")) {
- $data['Claim Submission'] = $this->request->getPost("days_from_dod");
- }
-
- if ($this->request->getPost("terrorism_display")) {
- $data['Terrorism'] = $this->request->getPost("terrorism");
- }
-
- if ($this->request->getPost("widower_cover_display")) {
- $data['Widower Cover'] = $this->request->getPost("widower_cover");
- }
-
- if ($this->request->getPost("breavement_cover_display")) {
- $data['Breavement Cover'] = $this->request->getPost("breavement_cover");
- }
-
- if ($this->request->getPost("special_condition_display_value")) {
-
- $specialConditionKeyValue = $this->request->getPost("special_condition_display_value") ?? [];
- $specialConditionKeyValue = json_decode($specialConditionKeyValue, true);
-
- if (is_array($specialConditionKeyValue) && count($specialConditionKeyValue) > 0) {
- $mergedArray = array_merge(...array_map(fn($item) => (array) $item, $specialConditionKeyValue));
- $data = array_merge($data, $mergedArray);
+ foreach ($fields as $postKey => $label) {
+ $displayKey = $postKey . '_display';
+ $value = $this->request->getPost($postKey);
+ if ($this->request->getPost($displayKey) && $value !== null && $value !== '') {
+ $data[$label] = $value;
}
}
-
- if(isset($data) && !empty($data)){
- return $data;
- }else{
- $data = [];
- return $data;
+
+ // Handle special conditions
+ if ($this->request->getPost("special_condition_display_value")) {
+ $specialConditionKeyValue = json_decode($this->request->getPost("special_condition_display_value"), true);
+ if (is_array($specialConditionKeyValue) && count($specialConditionKeyValue) > 0) {
+ $mergedArray = array_merge(...array_map(fn($item) => (array) $item, $specialConditionKeyValue));
+ // Only add non-empty values
+ foreach ($mergedArray as $k => $v) {
+ if ($v !== null && $v !== '') {
+ $data[$k] = $v;
+ }
+ }
+ }
}
-
+
+ return $data;
}
+
public function getterms()
{
$client_policy_id = $this->request->getVar('client_policy_id');
@@ -3001,92 +3141,145 @@ class ClientController extends AdminController
}
}
+ // public function enrollmentGPADisplayValueTransform()
+ // {
+ // $data = [];
+
+ // if ($this->request->getPost("accidentalDeathBenefit_display")) {
+ // $data['Accidental Death Benefit'] = $this->request->getPost("accidentalDeathBenefit");
+ // }
+ // if ($this->request->getPost("permanentTotalDisablement_display")) {
+ // $data['Permanent Total Disablement'] = $this->request->getPost("permanentTotalDisablement");
+ // }
+ // if ($this->request->getPost("permanentPartialDisablement_display")) {
+ // $data['Permanent Partial Disablement'] = $this->request->getPost("permanentPartialDisablement");
+ // }
+ // if ($this->request->getPost("temporaryTotalDisablementBenefit_display")) {
+ // $data['Temporary Total Disablement Benefit'] = $this->request->getPost("temporaryTotalDisablementBenefit");
+ // }
+ // if ($this->request->getPost("medical_expenses_medical_extension_display")) {
+ // $data['Medical Expenses / Medical Extension (IPD)'] = $this->request->getPost("medical_expenses_medical_extension");
+ // }
+ // if ($this->request->getPost("opd_treatment_cover_display")) {
+ // $data['OPD Treatment Cover'] = $this->request->getPost("opd_treatment_cover");
+ // }
+ // if ($this->request->getPost("ambulanceCharges_display")) {
+ // $data['Ambulance Charges'] = $this->request->getPost("ambulanceCharges");
+ // }
+ // if ($this->request->getPost("repatriation_of_mortal_remains_display")) {
+ // $data['Repatriation of Mortal Remains'] = $this->request->getPost("repatriation_of_mortal_remains");
+ // }
+ // if ($this->request->getPost("childrenEducationWelfareFund_display")) {
+ // $data['Children Education Welfare Fund'] = $this->request->getPost("childrenEducationWelfareFund");
+ // }
+ // if ($this->request->getPost("terrorism_display")) {
+ // $data['Terrorism'] = $this->request->getPost("terrorism");
+ // }
+ // if ($this->request->getPost("worldwideCover_display")) {
+ // $data['Worldwide Cover'] = $this->request->getPost("worldwideCover");
+ // }
+ // if ($this->request->getPost("family_transportation_benefits_display")) {
+ // $data['Family Transportation Benefits'] = $this->request->getPost("family_transportation_benefits");
+ // }
+ // if ($this->request->getPost("fractures_dislocation_burns_display")) {
+ // $data['Fractures / Dislocation / Burns'] = $this->request->getPost("fractures_dislocation_burns");
+ // }
+ // if ($this->request->getPost("coma_display")) {
+ // $data['Coma'] = $this->request->getPost("coma");
+ // }
+ // if ($this->request->getPost("carriageofDeadBody_display")) {
+ // $data['Carriage of Dead Body'] = $this->request->getPost("carriageOfDeadBody");
+ // }
+ // if ($this->request->getPost("compassionateVisitExpenses_display")) {
+ // $data['Compassionate Visit Expenses'] = $this->request->getPost("compassionateVisitExpenses");
+ // }
+ // if ($this->request->getPost("travel_expenses_for_medical_treatment_display")) {
+ // $data['Travel expenses for Medical Treatment'] = $this->request->getPost("travel_expenses_for_medical_treatment");
+ // }
+ // if ($this->request->getPost("daily_cash_allowance_display")) {
+ // $data['Daily cash Allowance'] = $this->request->getPost("daily_cash_allowance");
+ // }
+ // if ($this->request->getPost("artifical_limb_and_prosthesis_display")) {
+ // $data['Artifical Limb and Prosthesis'] = $this->request->getPost("artifical_limb_and_prosthesis");
+ // }
+ // if ($this->request->getPost("animalSnakeInsectBite_display")) {
+ // $data['Animal/Snake/Insect Bite'] = $this->request->getPost("animalSnakeInsectBite");
+ // }
+ // if ($this->request->getPost("air_ambulance_display")) {
+ // $data['Air Ambulance'] = $this->request->getPost("air_ambulance");
+ // }
+
+ // if ($this->request->getPost("gpa_special_condition_display_value")) {
+
+ // $specialConditionKeyValue = $this->request->getPost("gpa_special_condition_display_value") ?? [];
+ // $specialConditionKeyValue = json_decode($specialConditionKeyValue, true);
+
+ // if (is_array($specialConditionKeyValue) && count($specialConditionKeyValue) > 0) {
+ // $mergedArray = array_merge(...array_map(fn($item) => (array) $item, $specialConditionKeyValue));
+ // $data = array_merge($data, $mergedArray);
+ // }
+ // }
+ // // print_r($data); die;
+
+ // if (isset($data) && !empty($data)) {
+ // return $data;
+ // } else {
+ // $data = [];
+ // return $data;
+ // }
+ // }
+
public function enrollmentGPADisplayValueTransform()
- {
+ {
$data = [];
- if ($this->request->getPost("accidentalDeathBenefit_display")) {
- $data['Accidental Death Benefit'] = $this->request->getPost("accidentalDeathBenefit");
- }
- if ($this->request->getPost("permanentTotalDisablement_display")) {
- $data['Permanent Total Disablement'] = $this->request->getPost("permanentTotalDisablement");
- }
- if ($this->request->getPost("permanentPartialDisablement_display")) {
- $data['Permanent Partial Disablement'] = $this->request->getPost("permanentPartialDisablement");
- }
- if ($this->request->getPost("temporaryTotalDisablementBenefit_display")) {
- $data['Temporary Total Disablement Benefit'] = $this->request->getPost("temporaryTotalDisablementBenefit");
- }
- if ($this->request->getPost("medical_expenses_medical_extension_display")) {
- $data['Medical Expenses / Medical Extension (IPD)'] = $this->request->getPost("medical_expenses_medical_extension");
- }
- if ($this->request->getPost("opd_treatment_cover_display")) {
- $data['OPD Treatment Cover'] = $this->request->getPost("opd_treatment_cover");
- }
- if ($this->request->getPost("ambulanceCharges_display")) {
- $data['Ambulance Charges'] = $this->request->getPost("ambulanceCharges");
- }
- if ($this->request->getPost("repatriation_of_mortal_remains_display")) {
- $data['Repatriation of Mortal Remains'] = $this->request->getPost("repatriation_of_mortal_remains");
- }
- if ($this->request->getPost("childrenEducationWelfareFund_display")) {
- $data['Children Education Welfare Fund'] = $this->request->getPost("childrenEducationWelfareFund");
- }
- if ($this->request->getPost("terrorism_display")) {
- $data['Terrorism'] = $this->request->getPost("terrorism");
- }
- if ($this->request->getPost("worldwideCover_display")) {
- $data['Worldwide Cover'] = $this->request->getPost("worldwideCover");
- }
- if ($this->request->getPost("family_transportation_benefits_display")) {
- $data['Family Transportation Benefits'] = $this->request->getPost("family_transportation_benefits");
- }
- if ($this->request->getPost("fractures_dislocation_burns_display")) {
- $data['Fractures / Dislocation / Burns'] = $this->request->getPost("fractures_dislocation_burns");
- }
- if ($this->request->getPost("coma_display")) {
- $data['Coma'] = $this->request->getPost("coma");
- }
- if ($this->request->getPost("carriageofDeadBody_display")) {
- $data['Carriage of Dead Body'] = $this->request->getPost("carriageOfDeadBody");
- }
- if ($this->request->getPost("compassionateVisitExpenses_display")) {
- $data['Compassionate Visit Expenses'] = $this->request->getPost("compassionateVisitExpenses");
- }
- if ($this->request->getPost("travel_expenses_for_medical_treatment_display")) {
- $data['Travel expenses for Medical Treatment'] = $this->request->getPost("travel_expenses_for_medical_treatment");
- }
- if ($this->request->getPost("daily_cash_allowance_display")) {
- $data['Daily cash Allowance'] = $this->request->getPost("daily_cash_allowance");
- }
- if ($this->request->getPost("artifical_limb_and_prosthesis_display")) {
- $data['Artifical Limb and Prosthesis'] = $this->request->getPost("artifical_limb_and_prosthesis");
- }
- if ($this->request->getPost("animalSnakeInsectBite_display")) {
- $data['Animal/Snake/Insect Bite'] = $this->request->getPost("animalSnakeInsectBite");
- }
- if ($this->request->getPost("air_ambulance_display")) {
- $data['Air Ambulance'] = $this->request->getPost("air_ambulance");
- }
+ // Map POST keys to display labels
+ $fields = [
+ 'accidentalDeathBenefit' => 'Accidental Death Benefit',
+ 'permanentTotalDisablement' => 'Permanent Total Disablement',
+ 'permanentPartialDisablement' => 'Permanent Partial Disablement',
+ 'temporaryTotalDisablementBenefit' => 'Temporary Total Disablement Benefit',
+ 'medical_expenses_medical_extension' => 'Medical Expenses / Medical Extension (IPD)',
+ 'opd_treatment_cover' => 'OPD Treatment Cover',
+ 'ambulanceCharges' => 'Ambulance Charges',
+ 'repatriation_of_mortal_remains' => 'Repatriation of Mortal Remains',
+ 'childrenEducationWelfareFund' => 'Children Education Welfare Fund',
+ 'terrorism' => 'Terrorism',
+ 'worldwideCover' => 'Worldwide Cover',
+ 'family_transportation_benefits' => 'Family Transportation Benefits',
+ 'fractures_dislocation_burns' => 'Fractures / Dislocation / Burns',
+ 'coma' => 'Coma',
+ 'carriageOfDeadBody' => 'Carriage of Dead Body',
+ 'compassionateVisitExpenses' => 'Compassionate Visit Expenses',
+ 'travel_expenses_for_medical_treatment' => 'Travel expenses for Medical Treatment',
+ 'daily_cash_allowance' => 'Daily cash Allowance',
+ 'artifical_limb_and_prosthesis' => 'Artifical Limb and Prosthesis',
+ 'animalSnakeInsectBite' => 'Animal/Snake/Insect Bite',
+ 'air_ambulance' => 'Air Ambulance'
+ ];
- if ($this->request->getPost("gpa_special_condition_display_value")) {
-
- $specialConditionKeyValue = $this->request->getPost("gpa_special_condition_display_value") ?? [];
- $specialConditionKeyValue = json_decode($specialConditionKeyValue, true);
-
- if (is_array($specialConditionKeyValue) && count($specialConditionKeyValue) > 0) {
- $mergedArray = array_merge(...array_map(fn($item) => (array) $item, $specialConditionKeyValue));
- $data = array_merge($data, $mergedArray);
+ foreach ($fields as $postKey => $label) {
+ $displayKey = $postKey . '_display';
+ $value = $this->request->getPost($postKey);
+ if ($this->request->getPost($displayKey) && $value !== null && $value !== '') {
+ $data[$label] = $value;
}
}
- // print_r($data); die;
- if (isset($data) && !empty($data)) {
- return $data;
- } else {
- $data = [];
- return $data;
+ // Handle GPA special conditions
+ if ($this->request->getPost("gpa_special_condition_display_value")) {
+ $specialConditionKeyValue = json_decode($this->request->getPost("gpa_special_condition_display_value"), true);
+ if (is_array($specialConditionKeyValue) && count($specialConditionKeyValue) > 0) {
+ $mergedArray = array_merge(...array_map(fn($item) => (array) $item, $specialConditionKeyValue));
+ foreach ($mergedArray as $k => $v) {
+ if ($v !== null && $v !== '') {
+ $data[$k] = $v;
+ }
+ }
+ }
}
+
+ return $data;
}
public function getPolicyGPATerms()
@@ -4051,10 +4244,25 @@ class ClientController extends AdminController
{
// ---------for client-----------------------------------------------------------------------------
+ $role_id = get_role_id();
+ $user_id = get_session_userid();
+
+
+ if ($role_id == 2 || $role_id == 3) {
+
$clients = $this->clientModel
- ->select("*, DATE_FORMAT(dob, '%d-%m-%Y') as dob")
- ->where('is_active', 1)
- ->findAll();
+ ->select("clients.*, DATE_FORMAT(clients.dob, '%d-%m-%Y') as dob")
+ ->join('client_rm', 'client_rm.client_id = clients.id')
+ ->where('client_rm.user_id', $user_id)
+ ->where('clients.is_active', 1)
+ ->findAll();
+ } else {
+
+ $clients = $this->clientModel
+ ->select("*, DATE_FORMAT(dob, '%d-%m-%Y') as dob")
+ ->where('is_active', 1)
+ ->findAll();
+ }
$clientIds = array_column($clients, 'id');
@@ -5037,7 +5245,17 @@ class ClientController extends AdminController
// $employeeController = new EmployeeController();
// $employeeController->truncateFileData('633');
-
+
+ // ---------- TICKET SERVICE CONTROLLER --------------------------------------------------------------------------------
+
+ $ticketServiceController = new TicketServiceController();
+ // $response = $ticketServiceController->claimDumpExcelFileFormatValidation(["file_id" => 34]);
+ // $response = $ticketServiceController->claimDumpExcelFileDataValidation(["file_id" => 34]);
+ // $response = $ticketServiceController->getClaimExcelErrorData(["file_id" => 41]);
+ // $response = $ticketServiceController->claimDumpOnBoardProcess(["file_id" => 17]);
+ // $response = $ticketServiceController->extractExcelData("claims_dump_form_client.xlsx");
+ // dd($response);
+
// ---------- EMP SERVICE CONTROLLER --------------------------------------------------------------------------------
$empServiceController = new EmployeeServiceController();
@@ -5051,21 +5269,33 @@ class ClientController extends AdminController
// $res = $empServiceController->employeesCorrectionProcess(['file_id' => '1681']);
// dd( $res);
+ $EmployeeMultiEventServiceController = new EmployeeMultiEventServiceController();
+ // $res = $EmployeeMultiEventServiceController->constructMultiEventData(['file_id' => '1069']);
+ // $res = $EmployeeMultiEventServiceController->excelMultieventFileFormateValidation(['file_id' => '1084']);
+ // $res = $EmployeeMultiEventServiceController->excelMultieventFileDataValidation(['file_id' => '1069']);
+ // $res = $EmployeeMultiEventServiceController->excelMultieventFileOnBoard(['file_id' => '1069']);
+ // dd($res);
+
+ // $res = $EmployeeMultiEventServiceController->getExcelErrorData(1069, $res);
+ // $res['file_id'] = 1069;
+ // echo view('excel_errors', $res);
+ // dd($res);
+
// ---------- POLICY TRANSACTION CONTROLLER --------------------------------------------------------------------------------
$policyTransactionController = new PolicyTransactionController();
- // $res = $policyTransactionController->validateInsurerStatement(['file_id' => '17']);
+ // $res = $policyTransactionController->validateInsurerStatement(['file_id' => '57']);
// $res = $policyTransactionController->updateInsurerStatement(['file_id' => '22']);
// dd('-----', $res);
// ----------EMP DATA SERVICE CONTROLLER--------------------------------------------------------------------------------
$batch_data = [
- 'client_id' => 20,
- 'client_branch_id' => 72,
- 'client_policy_id' => 127,
+ 'client_id' => 51,
+ 'client_branch_id' => 40,
+ 'client_policy_id' => 63,
'insurer_or_tpa' => "insurer",
- 'event_type' => "deletion",
+ 'event_type' => "correction",
'actions' => "export",
'file_name' => "deletion_enhancement_test_file.xlsx",
];
@@ -5132,25 +5362,30 @@ class ClientController extends AdminController
// $EmpDataServiceController->cashDepositCalculationForDeletion($array);
// $result = $this->employeePolicyModel->getInceptionEmployeeDataForExportExcel($batch_data);
+ // $result = $this->employeePolicyModel->getCorrectionEmployeesDataForExportExcel($batch_data);
// dd(db_connect()->getLastQuery());
// ------------- LEADS CONTROLLER ----------------------------------------------------------
$LeadsController = new LeadsController();
- // $RFQModel = new RFQModel();
+ $RFQModel = new RFQModel();
- // $data = $RFQModel->where('is_active', 1)->where('lead_id', 40)->first();
- // // dd($data);
+ // $data = $RFQModel->where('is_active', 1)->where('lead_id', 323)->orderBy('id', 'desc')->first();
+ // $data = db_connect()->table('leads')->where('is_active', 1)->where('id', 326)->orderBy('id', 'desc')->get()->getResultArray();
+ // dd($data);
// $policy_type = 2;
// $proposel_name = "Proposal 2";
// $insurer_name = "ICICI-P-ICICI002-V1";
// $jsonArray = json_decode($data['json'], true);
- // // dd($jsonArray);
+ // dd($jsonArray);
- // $returndata = $LeadsController->convertQCRJsonToPolicyTerms($jsonArray, $policy_type, $proposel_name, $insurer_name);
- // dd($returndata);
-
- // $LeadsController->handleMemberDataGPATotalSumInsurerFromExcel(['lead_id' => 169]);
+ // $res = $LeadsController->convertQCRJsonToPolicyTerms($jsonArray, $policy_type, $proposel_name, $insurer_name);
+ // $res = $LeadsController->handleMemberDataGPATotalSumInsurerFromExcel(['lead_id' => 169]);
+ // $res = $LeadsController->reorderProposalsByInsurerTotal($jsonArray);
+ // $res = $LeadsController->calculateMembersDemography(['lead_id' => 326]);
+ // $res = $LeadsController->generateDemographyDataTable(['lead_id' => 326]);
+ // echo $res;
+ // dd($res);
// -----------BDS REPORT CONTROLLER---------------------------------------------------------------------------------
@@ -5163,6 +5398,7 @@ class ClientController extends AdminController
// $data['data'] = $BDSReportController->getBAPClientData();
// return $this->loadLayout('irda_bap_client_report_list', $data);
+
// $data['data'] = $BDSReportController->getClientData(1);
// return $this->loadLayout('irda_client_report_list', $data);
@@ -5357,7 +5593,8 @@ class ClientController extends AdminController
employees.mobile AS emp_mobile,
employees.email_corporate AS emp_email,
employees.relationship AS emp_relationship,
- employee_polices.uhid AS policy_no
+ employee_polices.uhid AS policy_no,
+ employee_polices.client_policy_id
")
->join('clients', 'client_policy.client_id = clients.id', 'left')
->join('insurers', 'client_policy.insurer_id = insurers.id', 'left')
@@ -5370,9 +5607,15 @@ class ClientController extends AdminController
->where('employees.is_active', 1)
->where('employees.relationship', "Self")
->where('employee_polices.is_active', 1)
+ ->whereIn('employees.emp_status', ['active'])
+ ->whereIn('employee_polices.status', ['active'])
+ ->where('employees.is_active', 1)
->where('client_policy.id', $param)
+ ->groupBy('employees.emp_code')
->get()
->getResultArray();
+
+ // print_r(db_connect()->getLastQuery()); die;
$dataForClientAndInsurer = $this->clientPolicyModel
->select("
@@ -5414,12 +5657,42 @@ class ClientController extends AdminController
'memberData' => $memberData
], 404);
}
- }
-
- public function getTheEmpDataForClaimSearchByMobile($param, $type = 'mobile', $client_policy_id = null, $client_id = null)
- {
+ }
+
+ // public function getTheEmpDataForClaimSearchByMobile($param, $type = 'mobile', $client_policy_id = null, $client_id = null, $ticket_type_id = null)
+ public function getTheEmpDataForClaimSearchByMobile()
+ {
+
+ $request = $this->request;
+
+ // Get parameters from GET request
+ $param = $request->getGet('param');
+ $type = $request->getGet('type') ?? 'mobile';
+ $client_policy_id = $request->getGet('client_policy_id');
+ $client_id = $request->getGet('client_id');
+ $ticket_type_id = $request->getGet('ticket_type_id');
+
+ // Validate required parameter
+ if (empty($param)) {
+ return $this->response->setJSON([
+ 'status' => false,
+ 'message' => 'Parameter is required'
+ ])->setStatusCode(400);
+ }
+
$field_name = 'employees.' . $type;
+ $policy_type_id = [];
+ if ($ticket_type_id == 1) {
+ $policy_type_id = [2, 3, 4, 5];
+ } else if ($ticket_type_id == 2) {
+ $policy_type_id = [1];
+ } else if ($ticket_type_id == 3) {
+ $policy_type_id = [6];
+ } else if ($ticket_type_id == 4) {
+ $policy_type_id = [7];
+ }
+
// Construct the base query
$query = $this->clientPolicyModel
->select("
@@ -5443,7 +5716,7 @@ class ClientController extends AdminController
->join('insurers', 'client_policy.insurer_id = insurers.id')
->join('tpa', 'client_policy.tpa_id = tpa.id', 'left')
->join('employees', 'clients.id = employees.client_id')
- ->join('employee_polices', 'employees.id = employee_polices.employee_id')
+ ->join('employee_polices', 'employees.id = employee_polices.employee_id AND client_policy.id = employee_polices.client_policy_id')
->where('client_policy.is_active', 1)
->where('insurers.is_active', 1)
->where('tpa.is_active', 1)
@@ -5454,20 +5727,24 @@ class ClientController extends AdminController
->where('employee_polices.status', "active")
->where($field_name, $param);
- if (!empty($client_id)) {
- $query->where('employees.client_id', $client_id);
- }
+ if (!empty($client_id)) {
+ $query->where('employees.client_id', $client_id);
+ }
- if (!empty($client_policy_id)) {
- $query->where('employee_polices.client_policy_id', $client_policy_id);
- }
-
- $query->groupBy('employees.id')
- ->orderBy('employees.id', 'DESC');
-
- $data = $query->get()->getRowArray();
+ if (!empty($client_policy_id)) {
+ $query->where('employee_polices.client_policy_id', $client_policy_id);
+ }
- // print_r(db_connect()->getLastQuery()); die;
+ if ($policy_type_id != null) {
+ $query->whereIn('client_policy.policy_type_id', $policy_type_id);
+ }
+
+ $query->groupBy('employees.id')
+ ->orderBy('employees.id', 'DESC');
+
+ $data = $query->get()->getRowArray();
+
+ // print_r(db_connect()->getLastQuery()); die;
$memberData = [];
$dataForClientAndInsurer = [];
@@ -5478,15 +5755,15 @@ class ClientController extends AdminController
// ->where('user_profiles.role', 3)
// ->get()
// ->getResultArray();
-
- if(!empty($data) && count($data) > 0){
+
+ if (!empty($data) && count($data) > 0) {
$memberData = $this->employeeModel->getEmployeeByEmployeeCode($data['emp_code'], $client_policy_id, $client_id);
$acms_datas = $this->employeeModel->getAcmUsingClientID($data['client_id']);
// if(!empty($acms_datas)){
// $acms = $acms_datas;
// }
- }else{
+ } else {
$acms_datas = "";
}
@@ -6574,268 +6851,6 @@ class ClientController extends AdminController
// ------------------- DEMO CLIENT FUNCTION --------------------------------------------------------------------------------
- // public function wipeDemoClient()
- // {
- // // $this->myLogger->logme('error', "Wipe Demo Client function called");
- // $this->myLogger->logme('error', "Wipe Demo Client function called"); // Red text
-
- // $this->myLogger->logme('error', "Wipe Demo client Payload : " . json_encode($this->request->getPost() ?? []));
- // $client_id = $this->request->getPost('client_id');
-
- // if (empty($client_id)) {
- // return $this->respond(['status' => false, 'message' => 'Client id required'], 404);
- // }
-
- // // 1. Client Model
- // $client_data = $this->clientModel->where('id', $client_id)->where('is_active', 1)->first();
- // $this->myLogger->logme('error', "Client data : " . json_encode($client_data ?? []));
-
- // if (!empty($client_data)) {
- // $is_deleted = $this->clientModel->where('id', $client_id)->delete();
-
- // if ($is_deleted) {
- // $this->myLogger->logme('error', "Client data removed successfully.");
- // } else {
- // $this->myLogger->logme('error', "Client record does not exist.");
- // }
- // } else {
- // return $this->respond(['status' => false, 'message' => 'Client not found'], 404);
- // }
-
- // // 2. Client RM Model
- // $client_rm_data = $this->clientRMModel->where('client_id', $client_id)->first();
- // $this->myLogger->logme('error', "Client Relationship Manager data : " . json_encode($client_rm_data ?? []));
-
- // if (!empty($client_rm_data)) {
- // $is_deleted = $this->clientRMModel->where('client_id', $client_id)->delete();
-
- // if ($is_deleted) {
- // $this->myLogger->logme('error', "Client Relationship Manager data removed successfully.");
- // } else {
- // $this->myLogger->logme('error', "Client Relationship Manager record does not exist. To delete");
- // }
- // } else {
- // $this->myLogger->logme('error', "Client Relationship Manager data not found.");
- // }
-
- // // 3. Client KYC Docs Model
- // $client_kyc_data = $this->clientKYCDocsModel->where('client_id', $client_id)->findAll();
- // $this->myLogger->logme('error', "Client KYC Docs data : " . json_encode($client_kyc_data ?? []));
-
- // if (!empty($client_kyc_data)) {
- // $is_deleted = $this->clientKYCDocsModel->where('client_id', $client_id)->delete();
- // if ($is_deleted) {
- // $this->myLogger->logme('error', "Client KYC Docs data removed successfully.");
- // } else {
- // $this->myLogger->logme('error', "Client KYC Docs record does not exist. To delete");
- // }
- // } else {
- // $this->myLogger->logme('error', "Client KYC Docs data not found.");
- // }
-
- // // 4. Client Branch Model
- // $client_branch_data = $this->clientBranchModel->where('client_id', $client_id)->findAll();
- // $this->myLogger->logme('error', "Client Branch data : " . json_encode($client_branch_data ?? []));
-
- // $branch_ids = array_column($client_branch_data, 'id') ?? [];
- // $this->myLogger->logme('error', "Client Branch id count : " . count($branch_ids ?? []));
-
- // if (!empty($client_branch_data)) {
-
- // $is_deleted = $this->clientBranchModel->where('client_id', $client_id)->delete();
-
- // if ($is_deleted) {
- // $this->myLogger->logme('error', "Client Branch data removed successfully.");
-
- // if(!empty($branch_ids)){
-
- // $level_contact_data = $this->levelContactModel->where('contact_type', 'client')->whereIn('ref_id', $branch_ids)->findAll();
- // $this->myLogger->logme('error', "Level Contact data : " . json_encode($level_contact_data ?? []));
-
- // $is_deleted = $this->levelContactModel->where('contact_type', 'client')->whereIn('ref_id', $branch_ids)->delete();
- // if ($is_deleted) {
- // $this->myLogger->logme('error', "Level Contact data removed successfully.");
- // } else {
- // $this->myLogger->logme('error', "Level Contact record does not exist. To delete");
- // }
-
- // }else{
- // $this->myLogger->logme('error', "Level Contact data not found.");
- // }
-
- // } else {
- // $this->myLogger->logme('error', "Client Branch record does not exist. To delete");
- // }
- // } else {
- // $this->myLogger->logme('error', "Client Branch data not found.");
- // }
-
- // // 5. Client Policy Model
- // $client_policy_data = $this->clientPolicyModel->where('client_id', $client_id)->findAll();
- // $this->myLogger->logme('error', "Client Policy data : " . json_encode($client_policy_data ?? []));
-
- // $policy_ids = array_column($client_policy_data, 'id') ?? [];
- // $this->myLogger->logme('error', "Client Policy id count : " . count($policy_ids ?? []));
-
- // if (!empty($client_policy_data)) {
- // $is_deleted = $this->clientPolicyModel->where('client_id', $client_id)->delete();
- // if ($is_deleted) {
-
- // $this->myLogger->logme('error', "Client Policy data removed successfully.");
-
- // if(!empty($policy_ids)){
-
- // $employee_policy_data = $this->employeePolicyModel->whereIn('client_policy_id', $policy_ids)->findAll();
- // $this->myLogger->logme('error', "Employee Policy data count : " . count($employee_policy_data ?? []));
-
- // $is_deleted = $this->employeePolicyModel->whereIn('client_policy_id', $policy_ids)->delete();
- // if ($is_deleted) {
- // $this->myLogger->logme('error', "Employee policy data removed successfully.");
- // } else {
- // $this->myLogger->logme('error', "Employee policy record does not exist. To delete");
- // }
-
- // }else{
- // $this->myLogger->logme('error', "Employee policy data not found.");
- // }
-
- // } else {
- // $this->myLogger->logme('error', "Client Policy record does not exist. To delete");
- // }
- // } else {
- // $this->myLogger->logme('error', "Client Policy data not found.");
- // }
-
- // // 6. Employee Model
- // $employee_data = $this->employeeModel->where('client_id', $client_id)->findAll();
- // $this->myLogger->logme('error', "Employee data count : " . count($employee_data ?? []));
-
- // if (!empty($employee_data)) {
-
- // $is_deleted = $this->employeeModel->where('client_id', $client_id)->delete();
- // if ($is_deleted) {
- // $this->myLogger->logme('error', "Employee data removed successfully.");
- // } else {
- // $this->myLogger->logme('error', "Employee record does not exist. To delete");
- // }
- // } else {
- // $this->myLogger->logme('error', "Employee data not found.");
- // }
-
- // // 7. Client Deposit Model
- // $client_deposit_data = $this->clientDepositModel->where('client_id', $client_id)->findAll();
- // $this->myLogger->logme('error', "Client Deposit data : " . json_encode($client_deposit_data ?? []));
-
- // if (!empty($client_deposit_data)) {
- // $is_deleted = $this->clientDepositModel->where('client_id', $client_id)->delete();
- // if ($is_deleted) {
- // $this->myLogger->logme('error', "Client Deposit data removed successfully.");
- // } else {
- // $this->myLogger->logme('error', "Client Deposit record does not exist. To delete");
- // }
- // } else {
- // $this->myLogger->logme('error', "Client Deposit data not found.");
- // }
-
- // // 8. Policy Premium 1 Model
- // $policy_premium1_data = $this->policyPremium1Model->where('client_id', $client_id)->findAll();
- // $this->myLogger->logme('error', "Policy Premium 1 data count : " . count($policy_premium1_data ?? []));
-
- // if (!empty($policy_premium1_data)) {
- // $is_deleted = $this->policyPremium1Model->where('client_id', $client_id)->delete();
- // if ($is_deleted) {
- // $this->myLogger->logme('error', "Policy Premium 1 data removed successfully.");
- // } else {
- // $this->myLogger->logme('error', "Policy Premium 1 record does not exist. To delete");
- // }
- // } else {
- // $this->myLogger->logme('error', "Policy Premium 1 data not found.");
- // }
-
- // // 9. Policy Premium 2 Model
- // $policy_premium2_data = $this->policyPremium2Model->where('client_id', $client_id)->findAll();
- // $this->myLogger->logme('error', "Policy Premium 2 data count: " . count($policy_premium2_data ?? []));
-
- // if (!empty($policy_premium2_data)) {
- // $is_deleted = $this->policyPremium2Model->where('client_id', $client_id)->delete();
- // if ($is_deleted) {
- // $this->myLogger->logme('error', "Policy Premium 2 data removed successfully.");
- // } else {
- // $this->myLogger->logme('error', "Policy Premium 2 record does not exist. To delete");
- // }
- // } else {
- // $this->myLogger->logme('error', "Policy Premium 2 data not found.");
- // }
-
- // // 10. Notification Model
- // $notification_data = $this->notificationModel->where('client_id', $client_id)->findAll();
- // $this->myLogger->logme('error', "Notification data : " . json_encode($notification_data ?? []));
-
- // if (!empty($notification_data)) {
- // $is_deleted = $this->notificationModel->where('client_id', $client_id)->delete();
- // if ($is_deleted) {
- // $this->myLogger->logme('error', "Notification data removed successfully.");
- // } else {
- // $this->myLogger->logme('error', "Notification record does not exist. To delete");
- // }
- // } else {
- // $this->myLogger->logme('error', "Notification data not found.");
- // }
-
- // // 11. CD Master Model
- // $cd_master_data = $this->CDMasterModel->where('client_id', $client_id)->findAll();
- // $this->myLogger->logme('error', "CD Master data : " . json_encode($cd_master_data ?? []));
-
- // if (!empty($cd_master_data)) {
- // $is_deleted = $this->CDMasterModel->where('client_id', $client_id)->delete();
- // if ($is_deleted) {
- // $this->myLogger->logme('error', "CD Master data removed successfully.");
- // } else {
- // $this->myLogger->logme('error', "CD Master record does not exist. To delete");
- // }
- // } else {
- // $this->myLogger->logme('error', "CD Master data not found.");
- // }
-
- // // 12. Policy Transaction Model
- // $policy_transaction_data = $this->policyTransactionModel->where('client_id', $client_id)->findAll();
- // $this->myLogger->logme('error', "Policy Transaction data : " . json_encode($policy_transaction_data ?? []));
-
- // $pt_ids = array_column($policy_transaction_data, 'id') ?? [];
- // $this->myLogger->logme('error', "Policy Transaction id count : " . count($pt_ids ?? []));
-
- // if (!empty($policy_transaction_data)) {
- // $is_deleted = $this->policyTransactionModel->where('client_id', $client_id)->delete();
- // if ($is_deleted) {
- // $this->myLogger->logme('error', "Policy Transaction data removed successfully.");
-
- // if(!empty($pt_ids)){
-
- // $pt_co_share_data = $this->PTCOShareDetailsModel->whereIn('pt_id', $pt_ids)->findAll();
- // $this->myLogger->logme('error', "PT CO Share data : " . json_encode($pt_co_share_data ?? []));
-
- // $is_deleted = $this->PTCOShareDetailsModel->whereIn('pt_id', $pt_ids)->delete();
- // if ($is_deleted) {
- // $this->myLogger->logme('error', "PT CO Share data removed successfully.");
- // } else {
- // $this->myLogger->logme('error', "PT CO Share record does not exist. To delete");
- // }
-
- // }else{
- // $this->myLogger->logme('error', "PT CO Share data not found.");
- // }
-
- // } else {
- // $this->myLogger->logme('error', "Policy Transaction record does not exist. To delete");
- // }
- // } else {
- // $this->myLogger->logme('error', "Policy Transaction data not found.");
- // }
-
- // $this->myLogger->logme('error', "Wipe Demo Client function closed");
- // return $this->respond(['status' => true, 'message' => 'Demo client data wiped successfully'], 200);
- // }
-
public function wipeDemoClient()
{
$this->myLogger->logme('error', "========================================");
diff --git a/app/Controllers/EmpDataServiceController.php b/app/Controllers/EmpDataServiceController.php
index 506b39a1..1aec089e 100755
--- a/app/Controllers/EmpDataServiceController.php
+++ b/app/Controllers/EmpDataServiceController.php
@@ -1862,6 +1862,7 @@ class EmpDataServiceController extends BaseController
$status = $file['status'];
$batch_code = $file['batch_code'];
$user_id = $file['created_by'];
+ $policy_issue_date = $file['policy_issue_date'];
$insurer_id = $this->clientPolicyModel->where('id', $client_policy_id)->first();
@@ -2086,6 +2087,8 @@ class EmpDataServiceController extends BaseController
'no_of_dependent' => count($no_of_dependent ?? []) ?? null,
'base_premium' => $base_bremium_and_gst['base_premium'] ?? null,
'gst' => $base_bremium_and_gst['gst'] ?? null,
+ 'policy_issue_date' => $policy_issue_date ?? null,
+ 'created_by' => $file['created_by'] ?? null,
]]);
// $this->cashDepositCalculationForInception($depositeData);
@@ -2417,6 +2420,7 @@ class EmpDataServiceController extends BaseController
$batch_code = $file['batch_code'];
$user_id = $file['created_by'];
$event_type = $file['event_type'];
+ $policy_issue_date = $file['policy_issue_date'];
$status_val = 'success';
@@ -2519,6 +2523,8 @@ class EmpDataServiceController extends BaseController
'endorsement_no' => $endorsement_id[0] ?? null,
'emp_count' => $emp_count ?? null,
'action_type' => $file['event_type'] ?? null,
+ 'policy_issue_date' => $policy_issue_date ?? null,
+ 'created_by' => $file['created_by'] ?? null,
]]);
@@ -2999,6 +3005,7 @@ class EmpDataServiceController extends BaseController
$status = $file['status'];
$batch_code = $file['batch_code'];
$user_id = $file['created_by'];
+ $policy_issue_date = $file['policy_issue_date'];
$insurer_id = $this->clientPolicyModel->where('id', $client_policy_id)->first();
@@ -3179,6 +3186,8 @@ class EmpDataServiceController extends BaseController
'no_of_dependent' => count($no_of_dependent ?? []) ?? null,
'base_premium' => $base_bremium_and_gst['base_premium'] ?? null,
'gst' => $base_bremium_and_gst['gst'] ?? null,
+ 'policy_issue_date' => $policy_issue_date ?? null,
+ 'created_by' => $file['created_by'] ?? null,
]]);
}
@@ -3537,6 +3546,7 @@ class EmpDataServiceController extends BaseController
$status = $file['status'];
$batch_code = $file['batch_code'];
$user_id = $file['created_by'];
+ $policy_issue_date = $file['policy_issue_date'];
$insurer_id = $this->clientPolicyModel->where('id', $client_policy_id)->first();
@@ -3687,6 +3697,8 @@ class EmpDataServiceController extends BaseController
'no_of_dependent' => count($no_of_dependent ?? []) ?? null,
'base_premium' => $base_bremium_and_gst['base_premium'] ?? null,
'gst' => $base_bremium_and_gst['gst'] ?? null,
+ 'policy_issue_date' => $policy_issue_date ?? null,
+ 'created_by' => $file['created_by'] ?? null,
]]);
}
@@ -4981,7 +4993,7 @@ class EmpDataServiceController extends BaseController
'policy_no' => $policy_data['policy_no'] ?? null,
'cd_ac_no' => $policy_data['cd_ac_no'] ?? null,
'cd_ac_pk' => $policy_data['cd_ac_pk'] ?? null,
- 'policy_issue_date' => $policy_data['policy_start_date'] ?? null,
+ 'policy_issue_date' => $params['policy_issue_date'] ?? null,
'policy_start_date' => $policy_data['policy_start_date'] ?? null,
'policy_end_date' => $policy_data['policy_end_date'] ?? null,
'data_received_date' => $policy_data['data_received_date'] ?? null,
@@ -4992,7 +5004,7 @@ class EmpDataServiceController extends BaseController
'co_share' => $policy_data['co_share'] ?? 0,
'pre_payable_by' => $policy_data['pre_payable_by'] ?? 1,
'renewal_date' => $policy_data['policy_end_date'] ?? null,
- 'month' => date('Y-m-01', strtotime($policy_data['policy_start_date'])) ?? null,
+ 'month' => date('Y-m-01', strtotime($params['policy_issue_date'] ?? "")) ?? null,
'ct_type' => 1,
'is_cd_reduce_from_bds' => 0,
'client_type_id' => 0,
@@ -5007,6 +5019,7 @@ class EmpDataServiceController extends BaseController
'source_client_policy_id' => $lead_data['source_policy_id'] ?? null,
'tsi' => generate_tsi_code($lead_data['lead_type'] ?? 1) ?? null,
'installment' => $lead_data['no_of_installment'] ?? null,
+ 'created_by' => $params['created_by'] ?? null,
];
$this->myLogger->logme("error", "Constructed policy transaction data: " . json_encode($policyTransactionData));
diff --git a/app/Controllers/EmployeeController.php b/app/Controllers/EmployeeController.php
index dd80cd05..f3dd3f0b 100755
--- a/app/Controllers/EmployeeController.php
+++ b/app/Controllers/EmployeeController.php
@@ -27,6 +27,7 @@ use App\Models\ClientDepositModel;
use App\Models\PolicyPremium2Model;
use App\Models\AuditHistoryModel;
use App\Models\UserModel;
+use App\Models\PartnerEndorsementRequestModel;
use App\Controllers\Jobs;
@@ -68,6 +69,7 @@ class EmployeeController extends AdminController
protected $PolicyPremium2Model;
protected $auditHistory;
protected $userModel;
+ protected $partnerEndorsementRequestModel;
public function __construct()
{
@@ -90,6 +92,7 @@ class EmployeeController extends AdminController
$this->PolicyPremium2Model = new PolicyPremium2Model();
$this->auditHistory = new AuditHistoryModel();
$this->userModel = new userModel();
+ $this->partnerEndorsementRequestModel = new PartnerEndorsementRequestModel();
}
public function list()
@@ -270,28 +273,35 @@ class EmployeeController extends AdminController
$client_id = $this->request->getPost('client_id');
$policy_id = $this->request->getPost('policy_id');
$branch_id = $this->request->getPost('branch_id');
+ $hr_file_id = $this->request->getPost('hr_file_id') ?? null;
$action = $this->request->getPost('upload-action-type');
$status = 'inprogress';
- $file_id = $this->fileModel->insert(['file_name' => $filename, 'client_id' => $client_id, 'policy_id' => $policy_id, 'created_by' => $loggedInUserID, 'status' => $status, 'action' => $action, 'client_branch_id' => $branch_id,'uploaded_by' => 1]); //here field policy_id have client_policy_id and not policy id from policy master
+ $file_id = $this->fileModel->insert(['file_name' => $filename, 'client_id' => $client_id, 'policy_id' => $policy_id, 'created_by' => $loggedInUserID, 'status' => $status, 'action' => $action, 'client_branch_id' => $branch_id,'uploaded_by' => 1, 'hr_file_id' => $hr_file_id]); //here field policy_id have client_policy_id and not policy id from policy master
$this->myLogger->logme("error", '{file_id} uploaded success', ['file_id' => $file_id]);
- //start validation process
- if($fileSize < 1) // if file size less than 1
- {
- $empServiceController = new EmployeeServiceController();
- $result = $empServiceController->excelFileFormatValidation(['file_id' => $file_id]);
- $this->myLogger->logme("error", '{file_id} is less than 1MB, validating on the fly', ['file_id' => $file_id]);
- //endof validation process
- if (isset($result['error_summary']) && count($result['error_summary'])) {
- return $this->respond(['dataStatus' => false, 'code' => 404, 'message' => 'file rejected with errors'], 200);
- }
- }
- else //if file size greater than 1 add the file as job
- {
- $job_details = new Jobs();
- $r = Jobs::addJob(['job_name' => 'excelFileFormatValidation','payload' => ['file_id' => $file_id]]);
+ if ($action == "all") {
+
+ $r = Jobs::addJob(['job_name' => 'excelMultieventFileFormateValidation', 'payload' => ['file_id' => $file_id]]);
$this->myLogger->logme("error", '{file_id} is greather than 1MB, validating with job queue', ['file_id' => $file_id]);
+
+ } else {
+ //start validation process
+ if ($fileSize < 1) // if file size less than 1
+ {
+ $empServiceController = new EmployeeServiceController();
+ $result = $empServiceController->excelFileFormatValidation(['file_id' => $file_id]);
+ $this->myLogger->logme("error", '{file_id} is less than 1MB, validating on the fly', ['file_id' => $file_id]);
+ //endof validation process
+ if (isset($result['error_summary']) && count($result['error_summary'])) {
+ return $this->respond(['dataStatus' => false, 'code' => 404, 'message' => 'file rejected with errors'], 200);
+ }
+ } else //if file size greater than 1 add the file as job
+ {
+ $job_details = new Jobs();
+ $r = Jobs::addJob(['job_name' => 'excelFileFormatValidation', 'payload' => ['file_id' => $file_id]]);
+ $this->myLogger->logme("error", '{file_id} is greather than 1MB, validating with job queue', ['file_id' => $file_id]);
+ }
}
return $this->respond(['dataStatus' => true, 'code' => 200, 'data' => 'file upload success'], 200);
@@ -302,7 +312,7 @@ class EmployeeController extends AdminController
//for TPA/insurer upload
$data['events'] = ['inception' => 'Inception (Employee + Dependents)', 'missed_inception' => 'Missed Inception (Employee + Dependents)', 'addition' => 'Addition (Employee + Dependents)', 'dependent_addition' => 'Dependent Addition (Only Dependents)', 'deletion' => 'Deletion', 'correction' => 'Correction', 'si_enhancement' => 'SI Enhancement'];
//for inception upload
- $data['actions'] = ['inception' => 'Inception (Employee + Dependents)', 'missed_inception' => 'Missed Inception (Employee + Dependents)', 'addition' => 'Addition (Employee + Dependents)', 'dependent_addition' => 'Dependent Addition (Only Dependents)', 'deletion' => 'Deletion', 'correction' => 'Correction', 'si_enhancement' => 'SI Enhancement'];
+ $data['actions'] = ['all' => 'All', 'inception' => 'Inception (Employee + Dependents)', 'missed_inception' => 'Missed Inception (Employee + Dependents)', 'addition' => 'Addition (Employee + Dependents)', 'dependent_addition' => 'Dependent Addition (Only Dependents)', 'deletion' => 'Deletion', 'correction' => 'Correction', 'si_enhancement' => 'SI Enhancement'];
// $data['actions'] = ['inception' => 'Inception (Employee + Dependents)', 'missed_inception' => 'Missed Inception (Employee + Dependents)', 'addition' => 'Addition (Employee + Dependents)', 'dependent_addition' => 'Dependent Addition (Only Dependents)', 'deletion' => 'Deletion', 'correction' => 'Correction', 'si_enhancement' => 'SI Enhancement','enrollment' => 'Enrolment'];
// $data['import_or_export'] = ['import' => 'Import', 'export' => 'Export'];
@@ -468,6 +478,8 @@ class EmployeeController extends AdminController
$filePath = ROOTPATH . 'public/sample_excel/sample_inception.xls';
}else if ($actionType == 'member_data') {
$filePath = ROOTPATH . 'public/sample_excel/Sample_Member_Data.xlsx';
+ }else if ($actionType == 'all') {
+ $filePath = ROOTPATH . 'public/sample_excel/sample_multievent_file.xlsx';
}
// Check if the file exists
@@ -514,6 +526,7 @@ class EmployeeController extends AdminController
$client_branch_id = $this->request->getPost('client_branch_id');
$insurer_or_tpa = $this->request->getPost('insurer_or_tpa');
$actions = $this->request->getPost('action_type');
+ $policy_issue_date = $this->request->getPost('policy_issue_date');
$client_data = $this->clientPolicyModel->getCliendDataForExcelFileName($client_policy_id);
$file_name = generate_filename($client_data['short_name'], $event_type, $actions, $insurer_or_tpa, $client_data['policy_type'], $client_data['branch_code']);
@@ -529,6 +542,13 @@ class EmployeeController extends AdminController
'actions' => $actions,
'file_name' => $file_name,
];
+
+
+ $batch_data['policy_issue_date'] = (!empty($policy_issue_date) && strtotime($policy_issue_date) !== false)
+ ? change_date_format($policy_issue_date)
+ : null;
+
+
if ($actions == 'export') {
if ($event_type == 'inception' || $event_type == 'addition' || $event_type == 'dependent_addition' || $event_type == 'missed_inception' || ($event_type == 'MultipleEvents' && $insurer_or_tpa == 'tpa')) {
@@ -1163,8 +1183,10 @@ class EmployeeController extends AdminController
return $response;
}
- //E-CARD DOWNLOAD FUNCTION
- public function generateIDCardForEmployee($rand_string, $people = 0)
+ // --------------- For E-Card Download -----------------------------------------------------------------------------------------------------
+
+ //E-CARD DOWNLOAD FUNCTION USING HTML PRINT
+ public function generateIDCardForEmployeeUsingHtml($rand_string, $people = 0)
{
// dd($rand_string, $people);
try {
@@ -1299,6 +1321,258 @@ class EmployeeController extends AdminController
}
+ // Preview E-Card Template function
+ public function previewTemplate($id = null)
+ {
+ $value = [
+ 'tpa_id' => 'TPA12345',
+ 'name' => 'John Doe',
+ 'uhid' => 'UHID67890',
+ 'gender' => 'Male',
+ 'dob' => '1985-05-15',
+ 'self' => 'John Doe',
+ 'policy_end_date' => '2024-12-31',
+ 'policy_start_date' => '2023-01-01',
+ 'policy_no' => 'POL1234567890',
+ 'insurer_name' => 'Example Insurance Company',
+ 'emp_code' => 'EMP001122',
+ 'client_name' => 'Corporate Client Inc.',
+ 'emp_age' => 39,
+ 'tpa_name' => 'Example TPA',
+ 'insurer_branch_city' => 'New York',
+ 'relationship' => 'Self',
+ 'basic_cover_si' => '5,00,000',
+ ];
+
+ $tpa_id = $this->TPAModel->where('id', $id)->first();
+
+ $template_data_path = WRITEPATH . 'e_card_template/';
+ $tpa_short_name = strtolower(str_replace(' ', '_', $tpa_id['short_name'])) . '.html';
+ $final_path = $template_data_path . $tpa_short_name;
+
+ if (!file_exists($final_path)) {
+
+ $data['message'] = 'Record Not Found';
+ return view('errors/404', $data);
+ }
+
+ $tmplt_data = file_get_contents($final_path);
+
+ $placeholders = [
+ '{TPA_ID}' => $value['tpa_id'],
+ '{NAME}' => $value['name'],
+ '{UHID}' => $value['uhid'],
+ '{GENDER}' => $value['gender'],
+ '{DOB}' => date('d-M-Y', strtotime($value['dob'])),
+ '{SELF_NAME}' => $value['self'] ?? $value['name'],
+ '{POLICY_DATE}' => date('d-M-Y', strtotime($value['policy_end_date'])),
+ '{POLICY_START_DATE}' => date('d-M-Y', strtotime($value['policy_start_date'])),
+ '{POLICY_NO}' => $value['policy_no'],
+ '{INSURER_NAME}' => strtoupper($value['insurer_name']),
+ '{EMP_ID}' => $value['emp_code'],
+ '{SI_AMT}' => $value['basic_cover_si'],
+ '{CORPORATE_NAME}' => $value['client_name'],
+ '{AGE}' => $value['emp_age'],
+ '{TPA_NAME}' => $value['tpa_name'],
+ '{INSURER_BRANCH}' => $value['insurer_branch_city'],
+ '{RELATION}' => $value['relationship'],
+ '{FRONT_CARD}' => base_url() . 'public/uploads/template_bg/' . $tpa_id['front_card'],
+ '{BACK_CARD}' => base_url() . 'public/uploads/template_bg/' . $tpa_id['back_card'],
+ '{TPA_LOGO}' => base_url() . 'public/uploads/logo/' . $tpa_id['tpa_logo'],
+ '{INSURER_LOGO}' => base_url() . 'public/assets/images/sample_logo_3.png',
+ '{MEDI_USER}' => base_url() . 'public/e_card_imgs/medi_uesr.jpg',
+ '{MEDI_INSURER}' => base_url() . 'public/e_card_imgs/Magma.png',
+ '{MEDI_BARCODE}' => base_url() . 'public/e_card_imgs/borcode.jpeg',
+ '{QR_ANDROID}' => base_url() . 'public/e_card_imgs/android.png',
+ '{QR_IOS}' => base_url() . 'public/e_card_imgs/ios.png',
+ '{QR_ANDROID_2}' => base_url() . 'public/e_card_imgs/play_store.png',
+ '{QR_IOS_2}' => base_url() . 'public/e_card_imgs/appstore.png',
+
+ ];
+
+ $placeholders['{LEVELS}'] = '
+ Level 1
+ 1. Gowtham / 8754081806 / gowtham@gmail.com
+ 2. Gowtham / 8754081806 / gowtham@gmail.com ';
+
+ // dd($placeholders);
+
+ // Get the values to replace the placeholders
+ $replaceValues = array_values($placeholders);
+
+ // Get the placeholders to search for
+ $searchPlaceholders = array_keys($placeholders);
+
+ // Replace placeholders with values in HTML content
+ $htmlContent = str_replace($searchPlaceholders, $replaceValues, $tmplt_data);
+
+
+ echo $htmlContent;
+ }
+
+ //E-CARD DOWNLOAD FUNCTION USING DOM PDF ( CURRENTLY USING THIS )
+ public function generateIDCardForEmployee($rand_string, $people = 0, $mode = 0)
+ {
+ // dd($rand_string, $people);
+ $this->myLogger->logme('error', 'generateIDCardForEmployee params .' . json_encode(["rand_string" => $rand_string, "people" => $people, "mode" => $mode]));
+ try {
+ $this->myLogger->logme('error', 'generateIDCardForEmployee function started.');
+
+ // Step 1: Attempt to fetch employee code and client policy ID
+ $this->myLogger->logme('error', 'Fetching employee code and client policy ID.');
+
+ $get_emp_code_and_client_policy_id = $this->employeePolicyModel
+ ->select('employee_polices.client_policy_id, employees.emp_code, tpa.short_name,employees.client_id')
+ ->join('client_policy', 'client_policy.id = employee_polices.client_policy_id')
+ ->join('employees', 'employees.id = employee_polices.employee_id')
+ ->join('tpa', 'tpa.id = client_policy.tpa_id')
+ ->where('employees.emp_status', 'active')
+ ->where('employees.is_active', '1')
+ ->where("employee_polices.tpa_id IS NOT NULL AND employee_polices.tpa_id <> ''")
+ ->where('employee_polices.status', 'active')
+ ->where('employee_polices.is_active', '1')
+ ->where('employee_polices.rand_string', $rand_string)
+ ->first();
+
+ // dd($this->employeePolicyModel->getLastQuery());
+
+ // dd($rand_string, $get_emp_code_and_client_policy_id);
+
+ if ($get_emp_code_and_client_policy_id == null || $get_emp_code_and_client_policy_id == "") {
+ $this->myLogger->logme('error', 'Member not found in this rand_string: ' . $rand_string);
+ $data['message'] = 'Record Not Found';
+ return view('errors/404', $data);
+ }
+
+ $this->myLogger->logme('error', 'Member found. Client policy ID: ' . $get_emp_code_and_client_policy_id['client_policy_id']);
+
+ $client_policy_id = $get_emp_code_and_client_policy_id['client_policy_id'];
+ $emp_code = $get_emp_code_and_client_policy_id['emp_code'];
+ $client_id = $get_emp_code_and_client_policy_id['client_id'];
+
+ // Step 2: Fetch ECard data
+ $this->myLogger->logme('error', 'Fetching ECard data using client_policy_id: ' . $client_policy_id . ' and emp_code: ' . $emp_code);
+ $data = $this->employeePolicyModel->getECardDataUsingMd5($client_policy_id, $emp_code,$client_id);
+
+ if ($people == 0) {
+ $this->myLogger->logme('error', 'Fetching single ECard data using rand_string: ' . $rand_string . ' and emp_code: ' . $emp_code);
+ $data = $this->employeePolicyModel->getECardSingleData($rand_string, $emp_code,$client_id);
+ }
+
+ // Step 3: Prepare template path
+ $template_data_path = WRITEPATH . 'e_card_template/';
+ // $tpa_short_name = strtolower(str_replace(' ', '_', $get_emp_code_and_client_policy_id['short_name'])) . '.html';
+ $tpa_short_name = 'common.html';
+ $final_path = $template_data_path . $tpa_short_name;
+
+ $this->myLogger->logme('error', 'Checking if template file exists at: ' . $final_path);
+
+ if (!file_exists($final_path)) {
+ $this->myLogger->logme('error', 'Template file not found: ' . $final_path);
+ $data['message'] = 'Template File Not Found';
+ return view('errors/404', $data);
+ }
+
+ $this->myLogger->logme('error', 'Template file found. Reading template data.');
+ $tmplt_data = file_get_contents($final_path);
+
+ // Step 4: Generate HTML content
+ $this->myLogger->logme('error', 'Generating HTML content from template.');
+ $html = "";
+ foreach ($data as $key => $value) {
+ $htmlContent = $tmplt_data;
+
+ $value['front_card'] = "Nhance_Ecard_working_1_front.png";
+ $value['back_card'] = "Nhance_Ecard_working_1_Back.png";
+
+ $placeholders = [
+ '{CLIENT_NAME}' => $value['client_name'],
+ '{TPA_ID}' => $value['tpa_id'],
+ '{NAME}' => $value['name'],
+ '{UHID}' => $value['uhid'],
+ '{GENDER}' => $value['gender'],
+ '{DOB}' => date('d-M-Y', strtotime($value['dob'])),
+ '{SELF_NAME}' => $value['self'] ?? $value['name'],
+ '{POLICY_DATE}' => date('d-M-Y', strtotime($value['policy_end_date'])),
+ '{POLICY_START_DATE}' => date('d-M-Y', strtotime($value['policy_start_date'])),
+ '{POLICY_NO}' => $value['policy_no'],
+ '{INSURER_NAME}' => strtoupper($value['insurer_name']),
+ '{INSURER_LOGO}' => base_url() . 'public/uploads/logo/' . $value['insurer_logo'],
+ '{FRONT_CARD}' => base_url() . 'public/uploads/template_bg/' . $value['front_card'],
+ '{BACK_CARD}' => base_url() . 'public/uploads/template_bg/' . $value['back_card'],
+ '{EMP_ID}' => $value['emp_code'],
+ '{SI_AMT}' => $value['basic_cover_si'],
+ '{CORPORATE_NAME}' => $value['client_name'],
+ '{AGE}' => $value['emp_age'],
+ '{TPA_NAME}' => $value['tpa_name'],
+ '{INSURER_BRANCH}' => $value['insurer_branch_city'],
+ '{RELATION}' => $value['relationship'],
+ '{TPA_LOGO}' => base_url() . 'public/uploads/logo/' . $value['tpa_logo'],
+ '{MEDI_USER}' => base_url() . 'public/e_card_imgs/medi_uesr.jpg',
+ '{MEDI_INSURER}' => base_url() . 'public/e_card_imgs/Magma.png',
+ '{MEDI_BARCODE}' => base_url() . 'public/e_card_imgs/borcode.jpeg',
+ '{QR_ANDROID}' => base_url() . 'public/e_card_imgs/android.png',
+ '{QR_IOS}' => base_url() . 'public/e_card_imgs/ios.png',
+ '{QR_ANDROID_2}' => base_url() . 'public/e_card_imgs/play_store.png',
+ '{QR_IOS_2}' => base_url() . 'public/e_card_imgs/appstore.png',
+ ];
+
+ $placeholders['{LEVELS}'] = $this->generateAcmAndMForEcard($client_id);
+
+ foreach ($placeholders as $placeholder => $replaceValue) {
+ $htmlContent = str_replace($placeholder, $replaceValue, $htmlContent);
+ }
+
+ $html .= $htmlContent;
+ }
+
+ // DomPdf
+ $options = new Options();
+ $options->set('isRemoteEnabled', true);
+ $options->set('isHtml5ParserEnabled', true);
+
+ $dompdf = new Dompdf($options);
+ $dompdf->loadHtml('' . $html); // remove the margin
+ $dompdf->setPaper('A4', 'portrait');
+ $dompdf->render();
+
+ // Set document title
+ $dompdf->addInfo("Title", "E-Card");
+
+ $filename = 'ecard_' . date('Y-m-d_H-i-s') . '.pdf';
+
+ // if($mode == 1){
+ // $dompdf->stream($filename, ['Attachment' => false]); // Inline view
+ // }else{
+ // $dompdf->stream($filename, ['Attachment' => true]); // Force download
+ // }
+
+ if ($mode == 1) {
+ // Inline view
+ return $this->response
+ ->setHeader('Content-Type', 'application/pdf')
+ ->setHeader('Content-Disposition', 'inline; filename="' . $filename . '"')
+ ->setBody($dompdf->output());
+ } else {
+ // Force download
+ return $this->response
+ ->setHeader('Content-Type', 'application/pdf')
+ ->setHeader('Content-Disposition', 'attachment; filename="' . $filename . '"')
+ ->setBody($dompdf->output());
+ }
+
+ $this->myLogger->logme('error', 'generateIDCardForEmployee function completed successfully.');
+
+ } catch (\Exception $e) {
+ $this->myLogger->logme('error', 'Exception occurred: ' . $e->getMessage());
+ $data['message'] = 'Record Not Found';
+ return view('errors/404', $data);
+ }
+
+ }
+
+ // --------------------------------------------------------------------------------------------------------------------
+
public function viewECard()
{
@@ -1866,95 +2140,6 @@ class EmployeeController extends AdminController
}
}
- // Preview E-Card Template function
- public function previewTemplate($id = null)
- {
- $value = [
- 'tpa_id' => 'TPA12345',
- 'name' => 'John Doe',
- 'uhid' => 'UHID67890',
- 'gender' => 'Male',
- 'dob' => '1985-05-15',
- 'self' => 'John Doe',
- 'policy_end_date' => '2024-12-31',
- 'policy_start_date' => '2023-01-01',
- 'policy_no' => 'POL1234567890',
- 'insurer_name' => 'Example Insurance Company',
- 'emp_code' => 'EMP001122',
- 'client_name' => 'Corporate Client Inc.',
- 'emp_age' => 39,
- 'tpa_name' => 'Example TPA',
- 'insurer_branch_city' => 'New York',
- 'relationship' => 'Self',
- 'basic_cover_si' => '5,00,000',
- ];
-
- $tpa_id = $this->TPAModel->where('id', $id)->first();
-
- $template_data_path = WRITEPATH . 'e_card_template/';
- $tpa_short_name = strtolower(str_replace(' ', '_', $tpa_id['short_name'])) . '.html';
- $final_path = $template_data_path . $tpa_short_name;
-
- if (!file_exists($final_path)) {
-
- $data['message'] = 'Record Not Found';
- return view('errors/404', $data);
- }
-
- $tmplt_data = file_get_contents($final_path);
-
- $placeholders = [
- '{TPA_ID}' => $value['tpa_id'],
- '{NAME}' => $value['name'],
- '{UHID}' => $value['uhid'],
- '{GENDER}' => $value['gender'],
- '{DOB}' => date('d-M-Y', strtotime($value['dob'])),
- '{SELF_NAME}' => $value['self'] ?? $value['name'],
- '{POLICY_DATE}' => date('d-M-Y', strtotime($value['policy_end_date'])),
- '{POLICY_START_DATE}' => date('d-M-Y', strtotime($value['policy_start_date'])),
- '{POLICY_NO}' => $value['policy_no'],
- '{INSURER_NAME}' => strtoupper($value['insurer_name']),
- '{EMP_ID}' => $value['emp_code'],
- '{SI_AMT}' => $value['basic_cover_si'],
- '{CORPORATE_NAME}' => $value['client_name'],
- '{AGE}' => $value['emp_age'],
- '{TPA_NAME}' => $value['tpa_name'],
- '{INSURER_BRANCH}' => $value['insurer_branch_city'],
- '{RELATION}' => $value['relationship'],
- '{FRONT_CARD}' => base_url() . 'public/uploads/template_bg/' . $tpa_id['front_card'],
- '{BACK_CARD}' => base_url() . 'public/uploads/template_bg/' . $tpa_id['back_card'],
- '{TPA_LOGO}' => base_url() . 'public/uploads/logo/' . $tpa_id['tpa_logo'],
- '{INSURER_LOGO}' => base_url() . 'public/assets/images/sample_logo_3.png',
- '{MEDI_USER}' => base_url() . 'public/e_card_imgs/medi_uesr.jpg',
- '{MEDI_INSURER}' => base_url() . 'public/e_card_imgs/Magma.png',
- '{MEDI_BARCODE}' => base_url() . 'public/e_card_imgs/borcode.jpeg',
- '{QR_ANDROID}' => base_url() . 'public/e_card_imgs/android.png',
- '{QR_IOS}' => base_url() . 'public/e_card_imgs/ios.png',
- '{QR_ANDROID_2}' => base_url() . 'public/e_card_imgs/play_store.png',
- '{QR_IOS_2}' => base_url() . 'public/e_card_imgs/appstore.png',
-
- ];
-
- $placeholders['{LEVELS}'] = '
- Level 1
- 1. Gowtham / 8754081806 / gowtham@gmail.com
- 2. Gowtham / 8754081806 / gowtham@gmail.com ';
-
- // dd($placeholders);
-
- // Get the values to replace the placeholders
- $replaceValues = array_values($placeholders);
-
- // Get the placeholders to search for
- $searchPlaceholders = array_keys($placeholders);
-
- // Replace placeholders with values in HTML content
- $htmlContent = str_replace($searchPlaceholders, $replaceValues, $tmplt_data);
-
-
- echo $htmlContent;
- }
-
public function errorListExportImport($file_id)
{
@@ -2825,4 +3010,31 @@ class EmployeeController extends AdminController
}
+ /**
+ * Below function displays the endorsement list page.
+ *
+ * This method retrieves filter data from the request and fetches the endorsement list
+ * based on the provided filters such as client ID, policy ID, and status.
+ */
+
+ public function retailendorsementList()
+ {
+
+ // $data = [];
+ // $data['status'] = ['open' => 'Open', 'inprogress' => 'In-Progress', 'complete' => 'Complete'];
+ // if (count($this->request->getGet())) {
+ // $filterData = $this->request->getGet();
+ // $data['employees'] = $this->partnerEndorsementRequestModel->getRetailEndorsementList(
+ // client_id: $filterData['client_id'],
+ // insurer_id: $filterData['insurer_id'],
+ // status: $filterData['status']
+ // );
+ // $data['getData'] = $filterData;
+ // // echo "";
+ // // print_r($data); die;
+ // }
+ // $this->myLogger->logme('error', 'list called');
+ // $this->loadLayout('retail_endorsement_list', $data);
+ }
+
}
diff --git a/app/Controllers/EmployeeMultiEventServiceController.php b/app/Controllers/EmployeeMultiEventServiceController.php
new file mode 100644
index 00000000..a7519fea
--- /dev/null
+++ b/app/Controllers/EmployeeMultiEventServiceController.php
@@ -0,0 +1,2871 @@
+ [
+ 'name' => 'Self',
+ 'gender' => 'M',
+ 'age_min' => 18,
+ 'age_max' => null
+ ],
+ 'spouse' => [
+ 'name' => 'Spouse',
+ 'gender' => 'F',
+ 'age_min' => 18,
+ 'age_max' => null
+ ],
+ 'son' => [
+ 'name' => 'Son',
+ 'gender' => 'M',
+ 'age_min' => null,
+ 'age_max' => 25
+ ],
+ 'daughter' => [
+ 'name' => 'Daughter',
+ 'gender' => 'F',
+ 'age_min' => null,
+ 'age_max' => 25
+ ],
+ 'father' => [
+ 'name' => 'Father',
+ 'gender' => 'M',
+ 'age_min' => 18,
+ 'age_max' => null
+ ],
+ 'mother' => [
+ 'name' => 'Mother',
+ 'gender' => 'F',
+ 'age_min' => 18,
+ 'age_max' => null
+ ],
+ 'father-in-law' => [
+ 'name' => 'Father in Law',
+ 'gender' => 'M',
+ 'age_min' => 18,
+ 'age_max' => null
+ ],
+ 'mother-in-law' => [
+ 'name' => 'Mother in Law',
+ 'gender' => 'F',
+ 'age_min' => 18,
+ 'age_max' => null
+ ]
+ ];
+
+ protected $inception_excel_columns = [
+ 'sno' => [
+ 'col_idx' => 0,
+ 'col_cell_name' => 'A',
+ 'col_name' => 'S.No',
+ 'is_mandatory' => true,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+ 'emp_id' => [
+ 'col_idx' => 1,
+ 'col_cell_name' => 'B',
+ 'col_name' => 'EMP ID',
+ 'is_mandatory' => true,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+ 'name_of_emp_dep' => [
+ 'col_idx' => 2,
+ 'col_cell_name' => 'C',
+ 'col_name' => 'NAME OF EMP/DEP',
+ 'is_mandatory' => true,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+ 'dob' => [
+ 'col_idx' => 3,
+ 'col_cell_name' => 'D',
+ 'col_name' => 'DOB',
+ 'is_mandatory' => ['I', 'A', 'DA'],
+ 'data_type' => 'str',
+ 'format' => 'd-M-Y',
+ 'allowed_values' => null,
+ 'custom' => 'check_dob_diff',
+ 'params' => ['row', 'relationship', 'default_age_ratio', 'policy_details']
+ ],
+ 'gender' => [
+ 'col_idx' => 4,
+ 'col_cell_name' => 'E',
+ 'col_name' => 'Gender',
+ 'is_mandatory' => ['I', 'A', 'DA'],
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => ['M', 'F']
+ ],
+ 'relationship' => [
+ 'col_idx' => 5,
+ 'col_cell_name' => 'F',
+ 'col_name' => 'RELATIONSHIP',
+ 'is_mandatory' => ['I', 'A', 'DA'],
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => ['Self', 'Spouse', 'Son', 'Daughter', 'Father', 'Mother', 'Father in Law', 'Mother in Law'],
+ 'custom' => 'check_relationship',
+ 'params' => ['row', 'relationship', 'policy_terms']
+ ],
+ 'basic_cover_si' => [
+ 'col_idx' => 6,
+ 'col_cell_name' => 'G',
+ 'col_name' => 'BASIC COVER SI',
+ 'is_mandatory' => null,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null,
+ 'custom' => 'check_si',
+ 'params' => ['row', 'policy_details', 'slab_details']
+ ],
+ 'doc' => [
+ 'col_idx' => 7,
+ 'col_cell_name' => 'H',
+ 'col_name' => 'Date of Coverage',
+ 'is_mandatory' => ['A', 'DA'],
+ 'data_type' => 'str',
+ 'format' => 'd-M-Y',
+ 'allowed_values' => null,
+ 'custom' => 'check_doc',
+ 'params' => ['row', 'policy_details']
+ ],
+ 'doj' => [
+ 'col_idx' => 8,
+ 'col_cell_name' => 'I',
+ 'col_name' => 'DOJ',
+ 'is_mandatory' => false,
+ 'data_type' => 'str',
+ 'format' => 'd-M-Y',
+ 'allowed_values' => null,
+ 'custom' => 'check_doj',
+ 'params' => ['row']
+ ],
+ 'basic_pay' => [
+ 'col_idx' => 9,
+ 'col_cell_name' => 'J',
+ 'col_name' => 'Basic Pay',
+ 'is_mandatory' => false,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null,
+ 'custom' => 'check_basic_pay',
+ 'params' => ['row', 'policy_terms', 'slab_details']
+ ],
+ 'band_grade' => [
+ 'col_idx' => 10,
+ 'col_cell_name' => 'K',
+ 'col_name' => 'Band/Grade',
+ 'is_mandatory' => false,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null,
+ 'custom' => 'check_employee_band',
+ 'params' => ['row', 'policy_terms', 'slab_details']
+ ],
+ 'designation' => [
+ 'col_idx' => 11,
+ 'col_cell_name' => 'L',
+ 'col_name' => 'Designation',
+ 'is_mandatory' => false,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+ 'phone' => [
+ 'col_idx' => 12,
+ 'col_cell_name' => 'M',
+ 'col_name' => 'Phone',
+ 'is_mandatory' => false,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null,
+ 'custom' => 'check_dup_mobileno',
+ 'params' => ['row', 'existing_mobilenos']
+ ],
+ 'email' => [
+ 'col_idx' => 13,
+ 'col_cell_name' => 'N',
+ 'col_name' => 'Email',
+ 'is_mandatory' => false,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null,
+ 'custom' => 'check_dup_email',
+ 'params' => ['row', 'existing_mobilenos']
+ ],
+ 'pre_existing_ailments' => [
+ 'col_idx' => 14,
+ 'col_cell_name' => 'O',
+ 'col_name' => 'PRE EXISTING AILMENTS',
+ 'is_mandatory' => ['I', 'A', 'DA'],
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => ['0', '1']
+ ],
+ 'change_event' => [
+ 'col_idx' => 15,
+ 'col_cell_name' => 'P',
+ 'col_name' => 'Change event',
+ 'is_mandatory' => ['A', 'DA', 'D'],
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+ 'date_of_exit' => [
+ 'col_idx' => 16,
+ 'col_cell_name' => 'Q',
+ 'col_name' => 'Date of exit',
+ 'is_mandatory' => ['D'],
+ 'data_type' => 'str',
+ 'format' => 'd-M-Y',
+ 'allowed_values' => null
+ ],
+ 'reason_for_exit' => [
+ 'col_idx' => 17,
+ 'col_cell_name' => 'R',
+ 'col_name' => 'Reason for exit',
+ 'is_mandatory' => ['D'],
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+ 'unit' => [
+ 'col_idx' => 18,
+ 'col_cell_name' => 'S',
+ 'col_name' => 'Unit',
+ 'is_mandatory' => false,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null,
+ 'custom' => 'check_unit',
+ 'params' => ['row', 'existing_units']
+ ]
+ ];
+
+ protected $deletion_excel_columns = [
+ 'sno' => [
+ 'col_idx' => 0,
+ 'col_cell_name' => 'A',
+ 'col_name' => 'S.No',
+ 'is_mandatory' => true,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+ 'emp_id' => [
+ 'col_idx' => 1,
+ 'col_cell_name' => 'B',
+ 'col_name' => 'EMP ID',
+ 'is_mandatory' => true,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+ 'name_of_emp_dep' => [
+ 'col_idx' => 2,
+ 'col_cell_name' => 'C',
+ 'col_name' => 'NAME OF EMP/DEP',
+ 'is_mandatory' => true,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+ 'change_event' => [
+ 'col_idx' => 3,
+ 'col_cell_name' => 'D',
+ 'col_name' => 'Change event',
+ 'is_mandatory' => ['D'],
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+ 'date_of_exit' => [
+ 'col_idx' => 4,
+ 'col_cell_name' => 'E',
+ 'col_name' => 'Date of exit',
+ 'is_mandatory' => ['D'],
+ 'data_type' => 'str',
+ 'format' => 'd-M-Y',
+ 'allowed_values' => null
+ ],
+ 'reason_for_exit' => [
+ 'col_idx' => 5,
+ 'col_cell_name' => 'F',
+ 'col_name' => 'Reason for exit',
+ 'is_mandatory' => ['D'],
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+ 'claim_status' => [
+ 'col_idx' => 6,
+ 'col_cell_name' => 'G',
+ 'col_name' => 'Claim status',
+ 'is_mandatory' => ['D'],
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => [0, 1]
+ ]
+ ];
+
+ protected $correction_excel_columns = [
+ 'sno' => [
+ 'col_idx' => 0,
+ 'col_cell_name' => 'A',
+ 'col_name' => 'S.No',
+ 'is_mandatory' => true,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+ 'emp_id' => [
+ 'col_idx' => 1,
+ 'col_cell_name' => 'B',
+ 'col_name' => 'EMP ID',
+ 'is_mandatory' => true,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+ 'name_of_emp_dep' => [
+ 'col_idx' => 2,
+ 'col_cell_name' => 'C',
+ 'col_name' => 'NAME OF EMP/DEP',
+ 'is_mandatory' => true,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+ 'field' => [
+ 'col_idx' => 3,
+ 'col_cell_name' => 'D',
+ 'col_name' => 'Field',
+ 'is_mandatory' => true,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => ['name', 'dob', 'relationship', 'email_corporate']
+ ],
+ 'value' => [
+ 'col_idx' => 4,
+ 'col_cell_name' => 'E',
+ 'col_name' => 'Value',
+ 'is_mandatory' => true,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+ 'date_of_correction' => [
+ 'col_idx' => 5,
+ 'col_cell_name' => 'F',
+ 'col_name' => 'Date of Correction',
+ 'is_mandatory' => true,
+ 'data_type' => 'str',
+ 'format' => 'd-M-Y',
+ 'allowed_values' => null
+ ],
+ 'change_event' => [
+ 'col_idx' => 6,
+ 'col_cell_name' => 'G',
+ 'col_name' => 'Change event',
+ 'is_mandatory' => true,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+ 'remarks' => [
+ 'col_idx' => 7,
+ 'col_cell_name' => 'H',
+ 'col_name' => 'Remarks',
+ 'is_mandatory' => false,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null
+ ]
+ ];
+
+ protected $si_enhance_excel_columns = [
+ 'sno' => [
+ 'col_idx' => 0,
+ 'col_cell_name' => 'A',
+ 'col_name' => 'S.No',
+ 'is_mandatory' => true,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+ 'emp_id' => [
+ 'col_idx' => 1,
+ 'col_cell_name' => 'B',
+ 'col_name' => 'EMP ID',
+ 'is_mandatory' => true,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+ 'name_of_emp_dep' => [
+ 'col_idx' => 2,
+ 'col_cell_name' => 'C',
+ 'col_name' => 'NAME OF EMP/DEP',
+ 'is_mandatory' => true,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+ 'augmented_si' => [
+ 'col_idx' => 3,
+ 'col_cell_name' => 'D',
+ 'col_name' => 'Augmented SI',
+ 'is_mandatory' => true,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null,
+ 'custom' => 'check_si',
+ 'params' => ['row', 'policy_details', 'slab_details']
+ ],
+ 'date_of_enhancement' => [
+ 'col_idx' => 4,
+ 'col_cell_name' => 'E',
+ 'col_name' => 'Date of SI Enhancement',
+ 'is_mandatory' => true,
+ 'data_type' => 'str',
+ 'format' => 'd-M-Y',
+ 'allowed_values' => null
+ ]
+ ];
+
+ protected $enrollment_excel_columns = [
+ 'sno' => [
+ 'col_idx' => 0,
+ 'col_cell_name' => 'A',
+ 'col_name' => 'Sno',
+ 'is_mandatory' => true,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+ 'emp_id' => [
+ 'col_idx' => 1,
+ 'col_cell_name' => 'B',
+ 'col_name' => 'Emp code',
+ 'is_mandatory' => true,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+ 'name_of_emp_dep' => [
+ 'col_idx' => 2,
+ 'col_cell_name' => 'C',
+ 'col_name' => 'Name',
+ 'is_mandatory' => true,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+ 'doj' => [
+ 'col_idx' => 3,
+ 'col_cell_name' => 'D',
+ 'col_name' => 'DOJ',
+ 'is_mandatory' => true,
+ 'data_type' => 'str',
+ 'format' => 'd-M-Y',
+ 'allowed_values' => null,
+ 'custom' => null
+ ],
+ 'gender' => [
+ 'col_idx' => 4,
+ 'col_cell_name' => 'E',
+ 'col_name' => 'Gender',
+ 'is_mandatory' => ['I', 'A', 'DA', 'E'],
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => ['M', 'F']
+ ],
+ 'relationship' => [
+ 'col_idx' => 5,
+ 'col_cell_name' => 'F',
+ 'col_name' => 'Relation',
+ 'is_mandatory' => ['I', 'A', 'DA', 'E'],
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null,
+ 'custom' => null
+ ],
+ 'dob' => [
+ 'col_idx' => 6,
+ 'col_cell_name' => 'G',
+ 'col_name' => 'DOB',
+ 'is_mandatory' => ['I', 'A', 'DA'],
+ 'data_type' => 'str',
+ 'format' => 'd-M-Y',
+ 'allowed_values' => null,
+ 'custom' => null,
+ ],
+ 'email' => [
+ 'col_idx' => 7,
+ 'col_cell_name' => 'H',
+ 'col_name' => 'Mail',
+ 'is_mandatory' => false,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+ 'phone' => [
+ 'col_idx' => 8,
+ 'col_cell_name' => 'I',
+ 'col_name' => 'Mobile',
+ 'is_mandatory' => false,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null,
+ 'custom' => null
+ ],
+ 'basic_cover_si' => [
+ 'col_idx' => 9,
+ 'col_cell_name' => 'J',
+ 'col_name' => 'SI',
+ 'is_mandatory' => null,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null,
+ 'custom' => null
+ ],
+ 'band_grade' => [
+ 'col_idx' => 10,
+ 'col_cell_name' => 'K',
+ 'col_name' => 'Grade',
+ 'is_mandatory' => false,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null,
+ 'custom' => null
+ ],
+ 'basic_pay' => [
+ 'col_idx' => 11,
+ 'col_cell_name' => 'L',
+ 'col_name' => 'Basic Pay',
+ 'is_mandatory' => false,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null,
+ 'custom' => null
+ ],
+ 'unit' => [
+ 'col_idx' => 12,
+ 'col_cell_name' => 'M',
+ 'col_name' => 'Unit',
+ 'is_mandatory' => false,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+ 'doc' => [
+ 'col_idx' => 13,
+ 'col_cell_name' => 'N',
+ 'col_name' => 'DOC',
+ 'is_mandatory' => false,
+ 'data_type' => 'str',
+ 'format' => 'd-M-Y',
+ 'allowed_values' => null
+ ]
+ ];
+
+ protected $incetion_to_enrollment_mapping = [
+ 0 => 0, // inception: sno (S.No) -> enrollment: sno (Sno)
+ 1 => 1, // inception: emp_id (EMP ID) -> enrollment: emp_code (Emp_Code)
+ 2 => 2, // inception: name_of_emp_dep (NAME OF EMP/DEP) -> enrollment: name (NAME OF EMP/DEP)
+ 3 => 6, // inception: dob (DOB) -> enrollment: dob (DOB)
+ 4 => 4, // inception: gender (Gender) -> enrollment: gender (Gender)
+ 5 => 5, // inception: relationship (RELATIONSHIP) -> enrollment: relationship (Relation)
+ 6 => 9, // inception: basic_cover_si (BASIC COVER SI) -> enrollment: basic_cover_si (SI)
+ 7 => 13, // inception: doc (Date of Coverage)
+ 8 => 3, // inception: doj (DOJ) -> enrollment: doj (DOJ)
+ 9 => 11, // inception: basic_pay (Basic Pay) -> enrollment: basic_pay (Basic Pay)
+ 10 => 10, // inception: band_grade (Band/Grade) -> enrollment: band_grade (Grade)
+ 11 => null, // inception: designation (Designation) -> No match in enrollment
+ 12 => 8, // inception: phone (Phone) -> enrollment: phone (Mobile)
+ 13 => 7, // inception: email (Email) -> enrollment: email (Email)
+ 14 => null, // inception: pre_existing_ailments (PRE EXISTING AILMENTS) -> No match in enrollment
+ 15 => null, // inception: change_event (Change event) -> No match in enrollment
+ 16 => null, // inception: date_of_exit (Date of exit) -> No match in enrollment
+ 17 => null, // inception: reason_for_exit (Reason for exit) -> No match in enrollment
+ 18 => null // inception: reason_for_exit (Reason for exit) -> No match in enrollment
+ ];
+
+ protected $enrollment_to_inception_mapping = [
+ 0 => 0, // enrollment: sno (Sno) -> inception: sno (S.No)
+ 1 => 1, // enrollment: emp_code (Emp_Code) -> inception: emp_id (EMP ID)
+ 2 => 2, // enrollment: name (NAME OF EMP/DEP) -> inception: name_of_emp_dep (NAME OF EMP/DEP)
+ 3 => 8, // enrollment: doj (DOJ) -> inception: doj (DOJ)
+ 4 => 4, // enrollment: gender (Gender) -> inception: gender (Gender)
+ 5 => 5, // enrollment: relationship (Relation) -> inception: relationship (RELATIONSHIP)
+ 6 => 3, // enrollment: dob (DOB) -> inception: dob (DOB)
+ 7 => 13, // enrollment: email (Email) -> inception: email (Email)
+ 8 => 12, // enrollment: phone (Mobile) -> inception: phone (Phone)
+ 9 => 6, // enrollment: basic_cover_si (SI) -> inception: basic_cover_si (BASIC COVER SI)
+ 10 => 10, // enrollment: band_grade (Grade) -> inception: band_grade (Band/Grade)
+ 11 => 9 // enrollment: basic_pay (Basic Pay) -> inception: basic_pay (Basic Pay)
+ ];
+
+ protected $multievent_excel_columns = [
+ 'sno' => [
+ 'col_idx' => 0,
+ 'col_cell_name' => 'A',
+ 'col_name' => 'S.No',
+ 'is_mandatory' => true,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+ 'emp_id' => [
+ 'col_idx' => 1,
+ 'col_cell_name' => 'B',
+ 'col_name' => 'Emp ID',
+ 'is_mandatory' => true,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+ 'name_of_emp_dep' => [
+ 'col_idx' => 2,
+ 'col_cell_name' => 'C',
+ 'col_name' => 'Name of Emp/Dep',
+ 'is_mandatory' => true,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+ 'dob' => [
+ 'col_idx' => 3,
+ 'col_cell_name' => 'D',
+ 'col_name' => 'DOB',
+ 'is_mandatory' => false,
+ 'data_type' => 'date',
+ 'format' => 'Y-m-d',
+ 'allowed_values' => null
+ ],
+ 'gender' => [
+ 'col_idx' => 4,
+ 'col_cell_name' => 'E',
+ 'col_name' => 'Gender',
+ 'is_mandatory' => false,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => ['Male', 'Female', 'Other']
+ ],
+ 'relationship' => [
+ 'col_idx' => 5,
+ 'col_cell_name' => 'F',
+ 'col_name' => 'Relationship',
+ 'is_mandatory' => false,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+ 'basic_cover_si' => [
+ 'col_idx' => 6,
+ 'col_cell_name' => 'G',
+ 'col_name' => 'Basic cover SI',
+ 'is_mandatory' => false,
+ 'data_type' => 'numeric',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+ 'doc' => [
+ 'col_idx' => 7,
+ 'col_cell_name' => 'H',
+ 'col_name' => 'Date of Coverage',
+ 'is_mandatory' => false,
+ 'data_type' => 'date',
+ 'format' => 'Y-m-d',
+ 'allowed_values' => null
+ ],
+ 'doj' => [
+ 'col_idx' => 8,
+ 'col_cell_name' => 'I',
+ 'col_name' => 'DOJ',
+ 'is_mandatory' => false,
+ 'data_type' => 'date',
+ 'format' => 'Y-m-d',
+ 'allowed_values' => null
+ ],
+ 'basic_pay' => [
+ 'col_idx' => 9,
+ 'col_cell_name' => 'J',
+ 'col_name' => 'Basic Pay',
+ 'is_mandatory' => false,
+ 'data_type' => 'numeric',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+ 'band_grade' => [
+ 'col_idx' => 10,
+ 'col_cell_name' => 'K',
+ 'col_name' => 'Band/Grade',
+ 'is_mandatory' => false,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+ 'designation' => [
+ 'col_idx' => 11,
+ 'col_cell_name' => 'L',
+ 'col_name' => 'Designation',
+ 'is_mandatory' => false,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+ 'phone' => [
+ 'col_idx' => 12,
+ 'col_cell_name' => 'M',
+ 'col_name' => 'Phone',
+ 'is_mandatory' => false,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+ 'email' => [
+ 'col_idx' => 13,
+ 'col_cell_name' => 'N',
+ 'col_name' => 'Email',
+ 'is_mandatory' => false,
+ 'data_type' => 'email',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+ 'pre_existing_ailments' => [
+ 'col_idx' => 14,
+ 'col_cell_name' => 'O',
+ 'col_name' => 'Pre Existing Ailments',
+ 'is_mandatory' => false,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+ 'date_of_exit' => [
+ 'col_idx' => 15,
+ 'col_cell_name' => 'P',
+ 'col_name' => 'Date of Exit',
+ 'is_mandatory' => false,
+ 'data_type' => 'date',
+ 'format' => 'Y-m-d',
+ 'allowed_values' => null
+ ],
+ 'reason_for_exit' => [
+ 'col_idx' => 16,
+ 'col_cell_name' => 'Q',
+ 'col_name' => 'Reason for Exit',
+ 'is_mandatory' => false,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+ 'claim_status' => [
+ 'col_idx' => 17,
+ 'col_cell_name' => 'R',
+ 'col_name' => 'Claim Status',
+ 'is_mandatory' => false,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => ['Approved', 'Rejected', 'Pending']
+ ],
+ 'field' => [
+ 'col_idx' => 18,
+ 'col_cell_name' => 'S',
+ 'col_name' => 'Correction Field',
+ 'is_mandatory' => false,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+ 'value' => [
+ 'col_idx' => 19,
+ 'col_cell_name' => 'T',
+ 'col_name' => 'Correction Value',
+ 'is_mandatory' => false,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+ 'date_of_correction' => [
+ 'col_idx' => 20,
+ 'col_cell_name' => 'U',
+ 'col_name' => 'Date of Correction',
+ 'is_mandatory' => false,
+ 'data_type' => 'date',
+ 'format' => 'Y-m-d',
+ 'allowed_values' => null
+ ],
+ 'remarks' => [
+ 'col_idx' => 21,
+ 'col_cell_name' => 'V',
+ 'col_name' => 'Correction Remarks',
+ 'is_mandatory' => false,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+ 'augmented_si' => [
+ 'col_idx' => 22,
+ 'col_cell_name' => 'W',
+ 'col_name' => 'Augmented SI',
+ 'is_mandatory' => false,
+ 'data_type' => 'numeric',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+ 'date_of_enhancement' => [
+ 'col_idx' => 23,
+ 'col_cell_name' => 'X',
+ 'col_name' => 'Date of SI Enhancement',
+ 'is_mandatory' => false,
+ 'data_type' => 'date',
+ 'format' => 'Y-m-d',
+ 'allowed_values' => null
+ ],
+ 'change_event' => [
+ 'col_idx' => 24,
+ 'col_cell_name' => 'Y',
+ 'col_name' => 'Change Event',
+ 'is_mandatory' => false,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+ 'unit' => [
+ 'col_idx' => 25,
+ 'col_cell_name' => 'Z',
+ 'col_name' => 'Unit',
+ 'is_mandatory' => false,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null
+ ]
+ ];
+
+
+
+
+ public function __construct()
+ {
+ // helper('utility');
+ set_session_context('EmployeeService');
+ $this->myLogger = \Config\Services::mylogger();
+ $this->employeeModel = new EmployeeModel();
+ $this->employeePolicyModel = new EmployeePolicyModel();
+ $this->clientModel = new ClientModel();
+ $this->fileModel = new FileModel();
+ $this->clientPolicyModel = new ClientPolicyModel();
+ $this->policiesModel = new PolicesModel();
+ $this->empEndorsementModel = new EmpEndorsementModel();
+ $this->messageModel = new MessageModel();
+ $this->clientBranchModel = new ClientBranchModel();
+ $this->notificationModel = new NotificationModel();
+ $this->insurerModel = new InsurerModel();
+ }
+
+ // ------------ FUNCTION FOR VADITATIONS HANDLERS -------------------------------------------------------------------------------------
+
+ public function excelMultieventFileFormateValidation($params)
+ {
+ helper('excel_util_helper');
+ $file_id = $params['file_id'];
+ $file = $this->fileModel->find($file_id);
+
+ if (!isset($file)) {
+ //file not found in DB
+ return array('status' => false, 'msg' => 'file not found in DB');
+ }
+ $file_name_with_path = WRITEPATH . "/uploads/excel/" . $file['file_name'];
+
+ //check physical file
+ if (!file_exists($file_name_with_path)) {
+ //file not found update status and reason
+ $message = "Physcial file not found";
+ // echo $message;
+ $this->myLogger->logme('error', ($message . ' for file id ' . $file_id));
+ $this->fileModel->where('id', $file_id)->set(['status' => 'failed', 'reason' => json_encode(['error_summary' => array_count_values([5]), 'error_data' => $message])])->update();
+ return array('error_summary' => [5], 'error_data' => $message);
+ }
+
+ $columns_to_check = $this->multievent_excel_columns;
+ $allowedHighestColumn = end($columns_to_check);
+ // print_rr($this->correction_excel_columns); die;
+
+ $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file_name_with_path);
+ $worksheet = $spreadsheet->getActiveSheet();
+ $highestRow = $worksheet->getHighestDataRow();
+ $highestColumn = $worksheet->getHighestDataColumn();
+
+ $excel_data = $worksheet->rangeToArray('A1:' . $allowedHighestColumn['col_cell_name'] . $highestRow);
+ $excel_header = $excel_data[0];
+
+ //check columns order in excel
+ $column_count_res = check_columns_name($columns_to_check, $excel_header);
+ if (isset($column_count_res) && count($column_count_res)) {
+ //columns count mismatch
+ $message = implode("\n", $column_count_res);
+ // echo $message;
+ $this->myLogger->logme('error', ($message . ' for file id ' . $file_id));
+ $this->fileModel->where('id', $file_id)->set(['status' => 'failed', 'reason' => json_encode(['error_summary' => array_count_values([6]), 'error_data' => $message])])->update();
+ return array('error_summary' => [6], 'error_data' => $message);
+ }
+
+ //check no of columns in excel
+ $total_defined_columns = count($columns_to_check);
+ $excel_columns = ($excel_data[0]);
+ $excel_columns_count = count($excel_columns);
+
+ if ($total_defined_columns != $excel_columns_count) {
+ //columns count mismatch
+ $message = "File columns count mismatch. Expected - $total_defined_columns and received - $excel_columns_count";
+ $this->myLogger->logme('error', ($message . ' for file id ' . $file_id));
+ $this->fileModel->where('id', $file_id)->set(['status' => 'failed', 'reason' => json_encode(['error_summary' => array_count_values([5]), 'error_data' => $message])])->update();
+ return array('error_summary' => [5], 'error_data' => $message);
+ }
+
+ // $file_paths = [
+ // 'inception' => '/opt/lampp/htdocs/claims/nhance/writable/tmp/inception_1756269562.json',
+ // 'missed_inception' => '/opt/lampp/htdocs/claims/nhance/writable/tmp/missed_inception_1756269562.json',
+ // 'addition' => '/opt/lampp/htdocs/claims/nhance/writable/tmp/addition_1756269562.json',
+ // 'dependent_addition' => '/opt/lampp/htdocs/claims/nhance/writable/tmp/dependent_addition_1756269562.json',
+ // 'deletion' => '/opt/lampp/htdocs/claims/nhance/writable/tmp/deletion_1756269562.json',
+ // 'correction' => '/opt/lampp/htdocs/claims/nhance/writable/tmp/correction_1756269562.json',
+ // 'si_enhancement' => '/opt/lampp/htdocs/claims/nhance/writable/tmp/si_enhancement_1756269562.json',
+ // ];
+ //construct and save as a .JSON file to the tmp folder and return the file paths
+ $file_paths = $this->constructMultiEventData($params);
+ $params['multi_event_file_paths'] = $file_paths;
+ // print_rr($file_paths);
+
+ $error = [];
+
+ //inception
+ if(isset($file_paths['inception']) && $file_paths['inception'] != "" && $file_paths['inception'] != null){
+ $params["action"] = "inception";
+ $params["file_path"] = $file_paths['inception'];
+ $error[] = $this->excelFileFormatValidation($params);
+ }
+
+ //addition
+ if(isset($file_paths['addition']) && $file_paths['addition'] != "" && $file_paths['addition'] != null){
+ $params["action"] = "addition";
+ $params["file_path"] = $file_paths['addition'];
+ $error[] = $this->excelFileFormatValidation($params);
+ }
+
+ //dependent_addition
+ if(isset($file_paths['dependent_addition']) && $file_paths['dependent_addition'] != "" && $file_paths['dependent_addition'] != null){
+ $params["action"] = "dependent_addition";
+ $params["file_path"] = $file_paths['dependent_addition'];
+ $error[] = $this->excelFileFormatValidation($params);
+ }
+
+ //deletion
+ if(isset($file_paths['deletion']) && $file_paths['deletion'] != "" && $file_paths['deletion'] != null){
+ $params["action"] = "deletion";
+ $params["file_path"] = $file_paths['deletion'];
+ $error[] = $this->excelFileFormatValidation($params);
+ }
+
+ //correction
+ if(isset($file_paths['correction']) && $file_paths['correction'] != "" && $file_paths['correction'] != null){
+ $params["action"] = "correction";
+ $params["file_path"] = $file_paths['correction'];
+ $error[] = $this->excelFileFormatValidation($params);
+ }
+
+ //si_enhancement
+ if(isset($file_paths['si_enhancement']) && $file_paths['si_enhancement'] != "" && $file_paths['si_enhancement'] != null){
+ $params["action"] = "si_enhancement";
+ $params["file_path"] = $file_paths['si_enhancement'];
+ $error[] = $this->excelFileFormatValidation($params);
+ }
+
+ //missed_inception
+ if(isset($file_paths['missed_inception']) && $file_paths['missed_inception'] != "" && $file_paths['missed_inception'] != null){
+ $params["action"] = "missed_inception";
+ $params["file_path"] = $file_paths['missed_inception'];
+ $error[] = $this->excelFileFormatValidation($params);
+ }
+
+ $error_type = 1;
+ $error = $this->mergeErrors($error, $error_type);
+ // print_rr($error);die;
+
+ if (isset($error['error_data']) && count($error['error_data']) == 0) {
+ $r = Jobs::addJob(['job_name' => 'excelMultieventFileDataValidation', 'payload' => $params]);
+ } else {
+
+ // $error['error_summary'] = array_count_values($error['error_summary']);
+ $status = 'failed';
+ $failure_reason = ((json_encode($error)));
+ $this->fileModel->where('id', $file_id)->set(['status' => $status, 'reason' => $failure_reason])->update();
+ $this->myLogger->logme("error", 'excel Multi event File Formate Validation {file_id} uploaded failed', ['file_id' => $file_id]);
+
+ //set failure msg to pull notifications
+ $this->setPullNotification($this->getFileMetaDataByFileId($file_id, 'failure'));
+
+ // remove the file form the folder after failed the function
+ $this->unlinkFiles($file_paths);
+ }
+
+ return ($error);
+
+ }
+
+ public function excelMultieventFileDataValidation($params)
+ {
+ helper('excel_util_helper');
+ $file_id = $params['file_id'];
+ $file = $this->fileModel->find($file_id);
+
+ if (!isset($file)) {
+ //file not found in DB
+ return array('status' => false, 'msg' => 'file not found in DB');
+ }
+
+ // $file_paths = [
+ // 'inception' => '/opt/lampp/htdocs/claims/nhance/writable/tmp/inception_1756269562.json',
+ // 'missed_inception' => '/opt/lampp/htdocs/claims/nhance/writable/tmp/missed_inception_1756269562.json',
+ // 'addition' => '/opt/lampp/htdocs/claims/nhance/writable/tmp/addition_1756269562.json',
+ // 'dependent_addition' => '/opt/lampp/htdocs/claims/nhance/writable/tmp/dependent_addition_1756269562.json',
+ // 'deletion' => '/opt/lampp/htdocs/claims/nhance/writable/tmp/deletion_1756269562.json',
+ // 'correction' => '/opt/lampp/htdocs/claims/nhance/writable/tmp/correction_1756269562.json',
+ // 'si_enhancement' => '/opt/lampp/htdocs/claims/nhance/writable/tmp/si_enhancement_1756269562.json',
+ // ];
+ // set the file paths
+ $file_paths = $params['multi_event_file_paths'];
+ // print_rr($file_paths);
+
+ $error = [];
+
+ //inception
+ if (isset($file_paths['inception']) && $file_paths['inception'] != "" && $file_paths['inception'] != null) {
+ $params["action"] = "inception";
+ $params["file_path"] = $file_paths['inception'];
+ $error[] = $this->excelFileDataValidation($params);
+ }
+
+ //addition
+ if (isset($file_paths['addition']) && $file_paths['addition'] != "" && $file_paths['addition'] != null) {
+ $params["action"] = "addition";
+ $params["file_path"] = $file_paths['addition'];
+ $error[] = $this->excelFileDataValidation($params);
+ }
+
+ //dependent_addition
+ if (isset($file_paths['dependent_addition']) && $file_paths['dependent_addition'] != "" && $file_paths['dependent_addition'] != null) {
+ $params["action"] = "dependent_addition";
+ $params["file_path"] = $file_paths['dependent_addition'];
+ $error[] = $this->excelFileDataValidation($params);
+ }
+
+ //deletion
+ if (isset($file_paths['deletion']) && $file_paths['deletion'] != "" && $file_paths['deletion'] != null) {
+ $params["action"] = "deletion";
+ $params["file_path"] = $file_paths['deletion'];
+ $error[] = $this->excelFileDataValidation($params);
+ }
+
+ //correction
+ if (isset($file_paths['correction']) && $file_paths['correction'] != "" && $file_paths['correction'] != null) {
+ $params["action"] = "correction";
+ $params["file_path"] = $file_paths['correction'];
+ $error[] = $this->excelFileDataValidation($params);
+ }
+
+ //si_enhancement
+ if (isset($file_paths['si_enhancement']) && $file_paths['si_enhancement'] != "" && $file_paths['si_enhancement'] != null) {
+ $params["action"] = "si_enhancement";
+ $params["file_path"] = $file_paths['si_enhancement'];
+ $error[] = $this->excelFileDataValidation($params);
+ }
+
+ //missed_inception
+ if (isset($file_paths['missed_inception']) && $file_paths['missed_inception'] != "" && $file_paths['missed_inception'] != null) {
+ $params["action"] = "missed_inception";
+ $params["file_path"] = $file_paths['missed_inception'];
+ $error[] = $this->excelFileDataValidation($params);
+ }
+
+ $error_type = 2;
+ $error = $this->mergeErrors($error, $error_type);
+ // print_rr($error);die;
+
+ if (isset($error['error_data']) && count($error['error_data']) == 0) {
+ $r = Jobs::addJob(['job_name' => 'excelMultieventFileOnBoard', 'payload' => $params]);
+ } else {
+
+ // $error['error_summary'] = array_count_values($error['error_summary']);
+ $status = 'failed';
+ $failure_reason = ((json_encode($error)));
+ $this->fileModel->where('id', $file_id)->set(['status' => $status, 'reason' => $failure_reason])->update();
+ $this->myLogger->logme("error", 'excel Multi event File Data Validation {file_id} uploaded failed', ['file_id' => $file_id]);
+
+ //set failure msg to pull notifications
+ $this->setPullNotification($this->getFileMetaDataByFileId($file_id, 'failure'));
+ }
+
+ return ($error);
+ }
+
+ public function excelMultieventFileOnBoard($params)
+ {
+ helper('excel_util_helper');
+
+ $file_id = $params['file_id'];
+ $file = $this->fileModel->find($file_id);
+
+ if (!isset($file)) {
+ //file not found in DB
+ return array('status' => false, 'msg' => 'file not found in DB');
+ }
+
+ // $file_paths = [
+ // 'inception' => '/opt/lampp/htdocs/claims/nhance/writable/tmp/inception_1756269562.json',
+ // 'missed_inception' => '/opt/lampp/htdocs/claims/nhance/writable/tmp/missed_inception_1756269562.json',
+ // 'addition' => '/opt/lampp/htdocs/claims/nhance/writable/tmp/addition_1756269562.json',
+ // 'dependent_addition' => '/opt/lampp/htdocs/claims/nhance/writable/tmp/dependent_addition_1756269562.json',
+ // 'deletion' => '/opt/lampp/htdocs/claims/nhance/writable/tmp/deletion_1756269562.json',
+ // 'correction' => '/opt/lampp/htdocs/claims/nhance/writable/tmp/correction_1756269562.json',
+ // 'si_enhancement' => '/opt/lampp/htdocs/claims/nhance/writable/tmp/si_enhancement_1756269562.json',
+ // ];
+ $file_paths = $params['multi_event_file_paths'];
+ // print_rr($file_paths);
+
+ $error = [];
+
+ //inception
+ if (isset($file_paths['inception']) && $file_paths['inception'] != "" && $file_paths['inception'] != null) {
+ $params["action"] = "inception";
+ $params["file_path"] = $file_paths['inception'];
+ $error['inception'] = $this->employeesOnboardPreprocess($params);
+ }
+
+ //addition
+ if (isset($file_paths['addition']) && $file_paths['addition'] != "" && $file_paths['addition'] != null) {
+ $params["action"] = "addition";
+ $params["file_path"] = $file_paths['addition'];
+ $error['addition'] = $this->employeesOnboardPreprocess($params);
+ }
+
+ //dependent_addition
+ if (isset($file_paths['dependent_addition']) && $file_paths['dependent_addition'] != "" && $file_paths['dependent_addition'] != null) {
+ $params["action"] = "dependent_addition";
+ $params["file_path"] = $file_paths['dependent_addition'];
+ $error['dependent_addition'] = $this->employeesOnboardPreprocess($params);
+ }
+
+ //missed_inception
+ if (isset($file_paths['missed_inception']) && $file_paths['missed_inception'] != "" && $file_paths['missed_inception'] != null) {
+ $params["action"] = "missed_inception";
+ $params["file_path"] = $file_paths['missed_inception'];
+ $error['missed_inception'] = $this->employeesOnboardPreprocess($params);
+ }
+
+ //deletion
+ if (isset($file_paths['deletion']) && $file_paths['deletion'] != "" && $file_paths['deletion'] != null) {
+ $params["action"] = "deletion";
+ $params["file_path"] = $file_paths['deletion'];
+ $error['deletion'] = $this->employeeDisembark($params);
+ }
+
+ //correction
+ if (isset($file_paths['correction']) && $file_paths['correction'] != "" && $file_paths['correction'] != null) {
+ $params["action"] = "correction";
+ $params["file_path"] = $file_paths['correction'];
+ $error['correction'] = $this->employeesCorrectionProcess($params);
+ }
+
+ //si_enhancement
+ if (isset($file_paths['si_enhancement']) && $file_paths['si_enhancement'] != "" && $file_paths['si_enhancement'] != null) {
+ $params["action"] = "si_enhancement";
+ $params["file_path"] = $file_paths['si_enhancement'];
+ $error['si_enhancement'] = $this->employeesSIEnhanceProcess($params);
+ }
+
+ $this->fileModel->where('id', $file_id)->set(['status' => 'success', 'reason' => ''])->update();
+ $this->myLogger->logme("error", $file['action'].': {file_id} uploaded success', ['file_id' => $file_id]);
+ $this->setPullNotification($this->getFileMetaDataByFileId($file_id, 'success'));
+
+ //After insert the success than remove the TEMP JSON files
+ // $this->unlinkFiles($params['multi_event_file_paths']);
+
+ return ($error);
+ }
+
+ // ------------ FUNCTION FOR VADITATIONS -------------------------------------------------------------------------------------
+
+ public function excelFileFormatValidation($params)
+ {
+ helper('excel_util_helper');
+ // dd($params);
+ //get file name
+ $file_id = $params['file_id'];
+ $file = $this->fileModel->find($file_id);
+ $file['action'] = $params['action'];
+ // dd($file);
+
+ $return = [];
+ if (!isset($file)) {
+ //file not found in DB
+ return array('status' => false, 'msg' => 'file not found in DB');
+ }
+
+ $file_name_with_path = WRITEPATH . "/uploads/excel/" . $file['file_name'];
+
+ //check physical file
+ 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 file id ' . $file_id));
+ $this->fileModel->where('id', $file_id)->set(['status' => 'failed', 'reason' => json_encode(['error_summary' => array_count_values([5]), 'error_data' => $message])])->update();
+ return array('error_summary' => [5], 'error_data' => $message);
+ }
+
+ //start validation process
+ $columns_to_check = [];
+ if ($file['action'] == 'inception') {
+ $columns_to_check = $this->inception_excel_columns;
+ }
+ if ($file['action'] == 'addition') {
+ $columns_to_check = $this->inception_excel_columns;
+ }
+ if ($file['action'] == 'dependent_addition') {
+ $columns_to_check = $this->inception_excel_columns;
+ }
+ if ($file['action'] == 'deletion') {
+ $columns_to_check = $this->deletion_excel_columns;
+ }
+ if ($file['action'] == 'correction') {
+ $columns_to_check = $this->correction_excel_columns;
+ }
+ if ($file['action'] == 'si_enhancement') {
+ $columns_to_check = $this->si_enhance_excel_columns;
+ }
+ if ($file['action'] == 'enrollment') {
+ $columns_to_check = $this->enrollment_excel_columns;
+ }
+ if ($file['action'] == 'missed_inception') {
+ $columns_to_check = $this->inception_excel_columns;
+ }
+
+ $columns_to_check = $this->syncColIndex($this->multievent_excel_columns, $columns_to_check);
+ // print_rr($columns_to_check);
+
+ $result = ['error_type' => 1, 'error_summary' => [], 'error_data' => []];
+ $keys = array_keys($columns_to_check);
+
+ $excel_data = json_decode(file_get_contents($params['file_path'] ?? []), true);
+ // dd($excel_data);
+
+ // get policy and rack details
+ $policy_details = $this->clientPolicyModel->getPolicyDetails($file['client_id'], $file['policy_id']);
+ $policy_terms = json_decode($policy_details[0]->policy_terms);
+ $policy_terms = (array) $policy_terms; // convert obj to array
+ $default_age_ratio = isset($policy_terms['age_ratio']) ? json_decode(json_encode($policy_terms['age_ratio']), true) : [];
+
+ //get policy slab rates
+ $slab_details = $this->policiesModel->getPolicySlabRatesForEmpOnboard($file['policy_id'], $file['client_id']);
+ // dd($slab_details);
+
+ //remove header
+ unset($excel_data[0]);
+ $relationship = $this->general_relationships;
+ //get exisiting mobilr nos
+ $existing_mobilenos = $this->employeePolicyModel->getExisitingMobileNos(client_policy_id: $file['policy_id']);
+ //get existing units in the current branch
+ $existing_units = $this->clientBranchModel->getExisitingUnits(client_id: $file['client_id'], client_branch_id: $file['client_branch_id']);
+ // dd($excel_data);
+ foreach ($excel_data as $row_key => $row) {
+ //define row wise action/event in temporary variable
+ $current_column_action = null;
+ if ($file['action'] == 'inception') {
+ $current_column_action = 'I';
+ } else if ($file['action'] == 'addition') {
+ $current_column_action = 'A';
+ } else if ($file['action'] == 'dependent_addition') {
+ $current_column_action = 'DA';
+ } else if ($file['action'] == 'deletion') {
+ $current_column_action = 'D';
+ } else if ($file['action'] == 'correction') {
+ $current_column_action = 'C';
+ } else if ($file['action'] == 'si_enhancement') {
+ $current_column_action = 'SI';
+ } else if ($file['action'] == 'enrollment') {
+ $current_column_action = 'I';
+ } else if ($file['action'] == 'missed_inception') {
+ $current_column_action = 'MI';
+ }
+ //1. avoid empty rows
+ if (check_row_is_empty_or_null($row)) {
+ break;
+ }
+ // Kint::dump($keys);
+ if ($file['action'] == 'enrollment') {
+ $row = transform_enrollment_row_to_inception_row($row);
+ $columns_to_check = $this->inception_excel_columns;
+ $keys = array_keys($columns_to_check);
+ $enrollment_columns_to_check = $this->enrollment_excel_columns;
+ $enrollment_keys = array_keys($enrollment_columns_to_check);
+ }
+
+ //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'];
+ $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;
+
+ $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'];
+ if ($file['action'] == 'enrollment') {
+ if (isset($enrollment_keys[$this->incetion_to_enrollment_mapping[$col_key]]) && $enrollment_keys[$this->incetion_to_enrollment_mapping[$col_key]] != null && $enrollment_keys[$this->incetion_to_enrollment_mapping[$col_key]] != "") {
+ $column_dispaly_name = $enrollment_columns_to_check[$enrollment_keys[$this->incetion_to_enrollment_mapping[$col_key]]]['col_name'];
+ $column_index = $enrollment_columns_to_check[$enrollment_keys[$this->incetion_to_enrollment_mapping[$col_key]]]['col_idx'];
+ $column_cell = $enrollment_columns_to_check[$enrollment_keys[$this->incetion_to_enrollment_mapping[$col_key]]]['col_cell_name'];
+ }
+ }
+
+ $row['current_action'] = $current_column_action;
+
+ //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
+ $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
+ }
+ }
+
+ //if is_mandatory is array (action based mandatory check)
+ if ($current_column_action != null && is_array($is_mandatory) && in_array(strtoupper(trim($current_column_action)), $is_mandatory)) {
+ $allowed_actions = $columns_to_check[$keys[$col_key]]['is_mandatory'];
+ 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';
+ }
+ }
+
+ //format check
+ if (isset($format)) {
+ $format_error = check_excel_date_format($col, $format);
+ 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'];
+ }
+ }
+ // Kint::dump($is_mandatory);
+ //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)))) {
+ // print_r($allowed_values);
+ // dd($col);
+ 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";
+ }
+ }
+
+ //custom function check
+ if (isset($custom_function)) {
+ //convert string params into PHP variables
+ // Create an array of variables to pass custom helper funcitons
+ $param_values = [];
+ foreach ($binding_params as $bkey => $bparam) {
+ $param_values[] = ($$bparam);
+ }
+ // dd(($param_values));//die();
+ $res = call_user_func_array($custom_function, $param_values);
+ // print_r($res['status']);die();
+ 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'];
+ }
+ }
+ } //col foreach
+ // break;
+ } //row foreach
+
+ // dd($result);
+ if (isset($result['error_summary']) && count($result['error_summary'])) {
+ $result['error_summary'] = array_count_values($result['error_summary']);
+ $this->myLogger->logme("error", '{file_id} uploaded failed', ['file_id' => $file_id]);
+ }
+
+ return $result;
+ }
+
+ public function excelFileDataValidation($params)
+ {
+ helper('excel_util_helper');
+
+ //get file name
+ $file_id = $params['file_id'];
+ $file = $this->fileModel->find($file_id);
+ $file['action'] = $params['action'];
+ // Kint::dump($file);
+
+ $return = [];
+ if (!isset($file)) {
+ //file not found in DB
+ return array('status' => false, 'msg' => 'file not found in DB');
+ }
+
+ $columns_to_check = [];
+ if ($file['action'] == 'inception') {
+ $columns_to_check = $this->inception_excel_columns;
+ }
+ if ($file['action'] == 'addition') {
+ $columns_to_check = $this->inception_excel_columns;
+ }
+ if ($file['action'] == 'dependent_addition') {
+ $columns_to_check = $this->inception_excel_columns;
+ }
+ if ($file['action'] == 'deletion') {
+ $columns_to_check = $this->deletion_excel_columns;
+ }
+ if ($file['action'] == 'correction') {
+ $columns_to_check = $this->correction_excel_columns;
+ }
+ if ($file['action'] == 'si_enhancement') {
+ $columns_to_check = $this->si_enhance_excel_columns;
+ }
+ if ($file['action'] == 'enrollment') {
+ $columns_to_check = $this->enrollment_excel_columns;
+ }
+ if ($file['action'] == 'missed_inception') {
+ $columns_to_check = $this->inception_excel_columns;
+ }
+
+ $columns_to_check = $this->syncColIndex($this->multievent_excel_columns, $columns_to_check);
+ // print_rr($columns_to_check);
+
+ // get policy and rack details
+ $policy_terms = $this->clientPolicyModel->getPolicyDetails($file['client_id'], $file['policy_id']);
+ $policy_details = (array)$policy_terms[0];
+ $is_lgbtq = $policy_details['is_lgbtq'];
+
+ $policy_terms = json_decode($policy_terms[0]->policy_terms);
+ $policy_terms = (array) $policy_terms; // convert obj to array
+ // dd($policy_terms);
+
+ $result = ['error_type' => 2, 'error_summary' => [], 'error_data' => []];
+ $keys = array_keys($columns_to_check);
+ $allowedHighestColumn = end($columns_to_check);
+
+ //get excel data
+ $excel_data = json_decode(file_get_contents($params['file_path'] ?? []), true);
+ // Kint::dump($excel_data);
+
+ //remove header
+ unset($excel_data[0]);
+ $relationship = $this->general_relationships;
+
+
+ if (in_array($file['action'], ['inception', 'missed_inception', 'addition', 'dependent_addition', 'deletion', 'correction', 'si_enhancement', 'enrollment'])) // the below funcitons are only for I,DA,A
+ {
+ $employee_data_group_by_family = data_group_by_family($excel_data, 'excel', ($file['action'] == 'enrollment' ? 'enrollment' : ''));
+ // dd($employee_data_group_by_family);
+ $is_self_available_in_policy_terms = false;
+ if ($policy_details['policy_type_id'] == 3) // GMC parents
+ {
+ $temp = $policy_terms['family_floaters'];
+ $temp = is_array($temp) ? $temp : (is_object($temp) ? (array)$temp : []);
+
+ $is_self_available_in_policy_terms = isset($temp['self']) && $temp['self'] == 1 ? true : false;
+ // Kint::dump($temp['self']);
+ // dd($is_self_available_in_policy_terms);
+ }
+ // dd($employee_data_group_by_family);
+ foreach ($employee_data_group_by_family as $emp_id => $family) {
+
+ //if action is DA then get all familiy members,transfrom them into excel array, addd data source as db or excel
+ if ($file['action'] == 'dependent_addition') {
+ $existing_famility_details = $this->employeeModel->getEmpFamilybyEmpCode(emp_code: $emp_id, client_id: $file['client_id'], client_policy_id: $file['policy_id'], emp_status: ['active'], policy_status: ['active'], client_branch_id: [$file['client_branch_id']]);
+ // dd(($existing_famility_details));
+ //transsform familiy details from db columns to exxcel row with column indexs for checking remaining functionalitites
+ $existing_famility_details = transform_db_data_to_excel($existing_famility_details, $file);
+ // dd(array_keys($existing_famility_details[0]));
+ $family = array_merge($family, $existing_famility_details);
+ // kint::dump($family);
+ $family = data_group_by_family($family)[$emp_id]; // reason to call this again bring self to first index of the array
+ }
+ $firstNonTemp = null;
+
+ foreach ($family as $fam) {
+ if (!isset($fam['temp'])) {
+ $firstNonTemp = $fam;
+ break;
+ }
+ }
+ // kint::dump($family);//die();
+
+ //check name dup within a family
+ if ($file['action'] == 'inception' || $file['action'] == 'missed_inception' || $file['action'] == 'addition' || $file['action'] == 'dependent_addition' || $file['action'] == 'enrollment') {
+ $res = name_dup_check_within_family($family, $file['action']); //in both file data & DB data
+ // dd($res);
+ if (count($res)) {
+ foreach ($res as $k => $rowid) {
+ array_push($result['error_summary'], 7); // dup entry in excel file
+ $result['error_data'][$rowid]['name_of_emp_dep']['error'][] = "Twofold Name found within family";
+ }
+ }
+ }
+
+ if ((($file['action'] == 'inception' || $file['action'] == 'missed_inception' || $file['action'] == 'addition' || $file['action'] == 'enrollment') || ($policy_details['policy_type_id'] == 3 && $is_self_available_in_policy_terms)) && ($policy_details['base_policy'] == null || $policy_details['base_policy'] == 0)) // 3 is GMC parents dep addon)
+ {
+ $res = check_self_available_in_family($family, $file['action']);
+ if (!$res['is_self_found']) {
+ array_push($result['error_summary'], 14); // Self not found
+ $result['error_data'][$res['row_id']]['sno']['error'][] = "Self not found in uploaded file";
+ }
+ }
+
+ //check self avaialbe either same policy DB level(i.e.) gMC parents
+ if ($file['action'] == 'dependent_addition' || ($policy_details['policy_type_id'] == 3 && !$is_self_available_in_policy_terms)) // 3 is GMC parents as base policy not as dep addon)
+ {
+ $self_details = $this->employeeModel->getEmpFamilybyEmpCode(emp_code: trim($emp_id), client_id: $file['client_id'], emp_status: ['active', 'draft', 'enrolled'], policy_status: ['active', 'draft', 'enrolled'], client_branch_id: [$file['client_branch_id']], relationship: ['self']);
+ // dd($self_details);
+ if (!count($self_details)) {
+ array_push($result['error_summary'], 14); // Self not found
+ $result['error_data'][$firstNonTemp[0]]['sno']['error'][] = "Self not found in Database";
+ }
+ }
+
+
+ if ($file['action'] == 'dependent_addition' || $file['action'] == 'addition' || $file['action'] == 'inception' || $file['action'] == 'missed_inception' || $file['action'] == 'enrollment') {
+ $res = check_dependent_conflict($family, $policy_terms, $file['action'], $is_lgbtq);
+ // Kint::dump($res);
+ if (!$res['status']) {
+ foreach ($res['error_data'] as $key => $value) {
+ array_push($result['error_summary'], $value['code']);
+ $result['error_data'][$value['row_id']][($value['col_name'])]['error'][] = $value['msg'];
+ }
+ }
+ }
+
+ //check dup with empid and name with db
+ $res = name_and_empid_check_in_db($family, $file);
+ // Kint::dump($res['del']);
+ // echo ' ';
+ // print_r($res);
+ if (count($res['del'])) {
+ foreach ($res['del'] as $k => $rowid) {
+ array_push($result['error_summary'], 10); //record not avail for deletion
+ $result['error_data'][$rowid]['name_of_emp_dep']['error'][] = "Record Not found ";
+ }
+ }
+ if (count($res['i'])) {
+ foreach ($res['i'] as $k => $rowid) {
+ array_push($result['error_summary'], 9); //dup entry
+ $result['error_data'][$rowid]['name_of_emp_dep']['error'][] = "Record already exists";
+ }
+ }
+ } // end of foreach
+ } // end of if current action I,DA,A
+
+ // return $result;
+ 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->fileModel->where('id', $file_id)->set(['status' => $status, 'reason' => $failure_reason])->update();
+ $this->myLogger->logme("error", '{file_id} uploaded failed', ['file_id' => $file_id]);
+
+ //set failure msg to pull notifications
+ $this->setPullNotification($this->getFileMetaDataByFileId($file_id, 'failure'));
+
+ }
+
+ return $result;
+ }
+
+ // ------------ FUNCTION FOR ON-BOARD PROCESS -------------------------------------------------------------------------------------
+
+ // calculate data points and premium
+ public function employeesOnboardPreprocess($params)
+ {
+ helper('excel_util_helper');
+ // dd($params);
+ if (isset($params['file_id'])) //handle data from excel to inception
+ {
+ //get file name
+ $file_id = $params['file_id'];
+ $file = $this->fileModel->find($file_id);
+ $file['action'] = $params['action'];
+ // dd($file);
+ $return = [];
+ if (!isset($file)) {
+ //file not found in DB
+ return array('status' => false, 'msg' => 'file not found in DB');
+ }
+
+ // $file_name_with_path = WRITEPATH . "/uploads/excel/" . $file['file_name'];
+
+ // //check physical file
+ // if (!file_exists($file_name_with_path)) {
+ // //file not found update status and reason
+ // $message = "Physical file not found";
+ // // echo $message;
+ // $this->myLogger->logme('error', ($message . ' for file id ' . $file_id));
+ // $this->fileModel->where('id', $file_id)->set(['status' => 'failed', 'reason' => json_encode(['error_summary' => array_count_values([5]), 'error_data' => $message])])->update();
+ // return array('error_summary' => [5], 'error_data' => $message);
+ // }
+
+ $columns_to_check = [];
+ if ($file['action'] == 'inception') {
+ $columns_to_check = $this->inception_excel_columns;
+ }
+ if ($file['action'] == 'addition') {
+ $columns_to_check = $this->inception_excel_columns;
+ }
+ if ($file['action'] == 'dependent_addition') {
+ $columns_to_check = $this->inception_excel_columns;
+ }
+ if ($file['action'] == 'deletion') {
+ $columns_to_check = $this->deletion_excel_columns;
+ }
+ if ($file['action'] == 'correction') {
+ $columns_to_check = $this->correction_excel_columns;
+ }
+ if ($file['action'] == 'si_enhancement') {
+ $columns_to_check = $this->si_enhance_excel_columns;
+ }
+ if ($file['action'] == 'missed_inception') {
+ $columns_to_check = $this->inception_excel_columns;
+ }
+
+ // get policy and rack details
+ $policy_terms = $this->clientPolicyModel->getPolicyDetails($file['client_id'], $file['policy_id']);
+ $policy_terms = (array) $policy_terms[0]; // convert obj to array
+ // $policy_terms = json_decode($policy_terms[0]->policy_terms);
+
+ // dd($policy_terms);
+
+ //get excel data
+ // $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file_name_with_path);
+ // $sheet = $spreadsheet->getActiveSheet();
+ // $highestRowAndColumn = $sheet->getHighestRowAndColumn();
+ // $allowedHighestColumn = end($columns_to_check);
+ // $excel_data = $sheet->rangeToArray('A1:' . $allowedHighestColumn['col_cell_name'] . $highestRowAndColumn['row']);
+ $excel_data = json_decode(file_get_contents($params['file_path'] ?? []), true);
+ unset($excel_data[0]);
+
+
+ //get policy slab rates
+ $slab_details = $this->policiesModel->getPolicySlabRatesForEmpOnboard($file['policy_id'], $file['client_id']);
+ // dd($slab_details);
+ //get existing units in the current branch
+ $existing_units = $this->clientBranchModel->getExisitingUnits(client_id: $file['client_id'], client_branch_id: $file['client_branch_id']);
+
+ $employee_data_group_by_family = data_group_by_family($excel_data);
+ // dd($employee_data_group_by_family);
+ foreach ($employee_data_group_by_family as $emp_id => $family) {
+
+ //if action is DA then get all familiy members,transfrom them into excel array, addd data source as db or excel
+ if ($file['action'] == 'dependent_addition') {
+ $existing_famility_details = $this->employeeModel->getEmpFamilybyEmpCode(emp_code: $emp_id, client_id: $file['client_id'], client_policy_id: $file['policy_id'], emp_status: ['active'], policy_status: ['active'], client_branch_id: [$file['client_branch_id']]);
+ // dd($existing_famility_details);
+ //transsform familiy details from db columns to exxcel row with column indexs for checking remaining functionalitites
+ $existing_famility_details = transform_db_data_to_excel($existing_famility_details, $file);
+ // Kint::dump($existing_famility_details);
+ $family = array_merge($family, $existing_famility_details);
+ $family = data_group_by_family($family)[$emp_id]; // reason to call this again is bring self to first index of the array
+ // dd($family);
+ }
+
+ // Kint::dump($family);
+ $data = calculate_premium_new(family_data: $family, policy_terms: $policy_terms, slab_details: $slab_details, fileArr: $file, existing_units: $existing_units);
+ // dd($data);
+ $employee_data_group_by_family[$emp_id] = $data;
+ $this->employeesOnboardProcess(['familiy_data' => $data, 'file' => $file]);
+ }
+
+ // $this->fileModel->where('id', $file_id)->set(['status' => 'success', 'reason' => ''])->update();
+ $this->myLogger->logme("error", $file['action'].': {file_id} uploaded success', ['file_id' => $file_id]);
+ // $this->setPullNotification($this->getFileMetaDataByFileId($file_id, 'success'));
+ } else if (isset($params['client_policy_id'])) //handle data from enrollment to inception
+ {
+ $client_policy_id = $params['client_policy_id'];
+ //get client id
+ $client_id = ($this->clientPolicyModel->select('client_id')->find($client_policy_id))['client_id'];
+ // dd($client_id);
+
+ // get policy and rack details
+ $policy_terms = $this->clientPolicyModel->getPolicyDetails($client_id, $client_policy_id);
+ $policy_terms = (array) $policy_terms[0]; // convert obj to array
+
+ //get policy slab rates
+ $slab_details = $this->policiesModel->getPolicySlabRatesForEmpOnboard($client_policy_id, $client_id);
+
+ $existing_famility_details = $this->employeeModel->getEmpFamilybyEmpCode(client_id: $client_id, client_policy_id: $client_policy_id, emp_status: ['enrolled'], policy_status: ['enrolled']);
+
+ // $file = ['id' => null,'client_id' => $client_id,'policy_id' => $client_policy_id,'action' => 'inception'];
+ $file = ['id' => null, 'client_id' => $client_id, 'policy_id' => $client_policy_id, 'action' => 'inception', 'created_by' => get_session_userid(), 'client_branch_id' => $params['client_branch_id']];
+
+ //get existing units in the current branch
+ $existing_units = $this->clientBranchModel->getExisitingUnits(client_id: $file['client_id'], client_branch_id: $file['client_branch_id']);
+ // dd($this->employeeModel->getLastQuery());
+ // Kint::dump($existing_famility_details);die();
+ $employee_data_group_by_family = data_group_by_family($existing_famility_details, $data_source = 'db');
+ // dd($employee_data_group_by_family);
+ foreach ($employee_data_group_by_family as $emp_id => $family) {
+ $transformed_famility_details = transform_db_data_to_excel($family);
+ // $data = calculate_premium_new($transformed_famility_details,$policy_terms,$slab_details,$file);
+ $data = calculate_premium_new(family_data: $transformed_famility_details, policy_terms: $policy_terms, slab_details: $slab_details, fileArr: $file, existing_units: $existing_units);
+ // dd($data);
+ $employee_data_group_by_family[$emp_id] = $data;
+ $this->employeesOnboardProcess(['familiy_data' => $data, 'file' => $file]);
+ }
+
+ // dd($employee_data_group_by_family);
+ }
+
+ // die();
+ return (count($employee_data_group_by_family));
+ }
+
+ //deletion of emp
+ public function employeeDisembark($params)
+ {
+ helper('excel_util_helper');
+
+ //get file name
+ $file_id = $params['file_id'];
+ $file = $this->fileModel->find($file_id);
+ $file['action'] = $params['action'];
+ // dd($file);
+
+ // $file_name_with_path = WRITEPATH . "/uploads/excel/" . $file['file_name'];
+ // $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file_name_with_path);
+ // $sheet = $spreadsheet->getActiveSheet();
+ // $highestRowAndColumn = $sheet->getHighestRowAndColumn();
+ // $allowedHighestColumn = end($this->deletion_excel_columns);
+ // $excel_data = $sheet->rangeToArray('A1:' . $allowedHighestColumn['col_cell_name'] . $highestRowAndColumn['row']);
+ // dd($excel_data);
+
+ $excel_data = json_decode(file_get_contents($params['file_path'] ?? []), true);
+ unset($excel_data[0]);
+ // kint::dump($excel_data);
+
+ $endorsement_data = [];
+ $policy_terms = $this->clientPolicyModel->getPolicyDetails($file['client_id'], $file['policy_id']);
+ $insurer = new InsurerModel();
+ $insurer = ($insurer->find($policy_terms[0]->insurer_id));
+ // kint::dump($insurer);
+
+ //make closure funciton which is going to use only by this method
+ $endorsement = function ($data, $file, $row) use ($insurer) {
+
+ $group_key = rand(100000, 999999);
+ $row[4] = change_date_format($row[4], 'd-M-Y', 'Y-m-d'); // date of exit from excel
+ // Kint::dump($row[4]);
+ // check if insurer configured with add one day for deletion
+ // if($insurer['deletion_add_day'] == true)
+ // {
+ // $row[4] = (new \DateTime($row[4]))->modify('+1 day')->format('Y-m-d');
+ // }
+ // dd($row[4]);
+ //for emp table
+ // $this->empEndorsementModel->save(['pk' => (int)$data['emp_id'],'emp_code' => $data['emp_code'],'table_name' => 'employees','actions' => 'd','name' => $data['name'],'field_name' => 'emp_status','old_value' => $data['emp_status'],'new_value' => 'deactivate','created_by' => $file['created_by'],'remarks' => 'general deletion','group_key' => $group_key,'file_id' => $file['id'],'status' => 'pending']);
+ // dd( $this->empEndorsementModel->getLastQuery());
+ // $this->empEndorsementModel->save(['pk' => (int)$data['emp_id'],'emp_code' => $data['emp_code'],'table_name' => 'employees','actions' => 'd','name' => $data['name'],'field_name' => 'change_event','old_value' => $data['change_event'],'new_value' => 'deletion','created_by' => $file['created_by'],'remarks' => 'general deletion']);
+
+ // for employee policy table
+ $this->empEndorsementModel->save(['pk' => (int)$data['emp_policy_id'], 'emp_code' => $data['emp_code'], 'table_name' => 'employee_polices', 'actions' => 'd', 'name' => $data['name'], 'field_name' => 'date_of_exit', 'old_value' => $data['date_of_exit'], 'new_value' => $row[4], 'created_by' => $file['created_by'], 'remarks' => 'general deletion', 'group_key' => $group_key, 'file_id' => $file['id'], 'status' => 'pending']);
+ $this->empEndorsementModel->save(['pk' => (int)$data['emp_policy_id'], 'emp_code' => $data['emp_code'], 'table_name' => 'employee_polices', 'actions' => 'd', 'name' => $data['name'], 'field_name' => 'reason_for_exit', 'old_value' => $data['reason_for_exit'], 'new_value' => $row[5], 'created_by' => $file['created_by'], 'remarks' => 'general deletion', 'group_key' => $group_key, 'file_id' => $file['id'], 'status' => 'pending']);
+ $this->empEndorsementModel->save(['pk' => (int)$data['emp_policy_id'], 'emp_code' => $data['emp_code'], 'table_name' => 'employee_polices', 'actions' => 'd', 'name' => $data['name'], 'field_name' => 'status', 'old_value' => $data['status'], 'new_value' => 'inactive', 'created_by' => $file['created_by'], 'remarks' => 'general deletion', 'group_key' => $group_key, 'file_id' => $file['id'], 'status' => 'pending']);
+ $this->empEndorsementModel->save(['pk' => (int)$data['emp_policy_id'], 'emp_code' => $data['emp_code'], 'table_name' => 'employee_polices', 'actions' => 'd', 'name' => $data['name'], 'field_name' => 'claim_status', 'old_value' => $data['claim_status'], 'new_value' => $row[6], 'created_by' => $file['created_by'], 'remarks' => 'general deletion', 'group_key' => $group_key, 'file_id' => $file['id'], 'status' => 'pending']);
+ };
+
+ //iterate each row
+ foreach ($excel_data as $col_key => $row) {
+ if (check_row_is_empty_or_null($row)) {
+ break;
+ }
+ // echo ' START- ' . $row[2];
+
+ $employee = $this->employeeModel
+ ->select('employees.*, employee_polices.id as emp_policy_pk')
+ ->join('employee_polices', 'employees.id = employee_polices.employee_id')
+ ->where('employees.emp_code', $row[1])
+ ->where('employees.name', $row[2])
+ ->where('employees.client_id', $file['client_id'])
+ ->where('employees.client_branch_id', $file['client_branch_id'])
+ ->where('employee_polices.client_policy_id', $file['policy_id'])
+ ->where('employees.emp_status !=', 'truncated')
+ ->where('employees.is_active', 1)
+ ->where('employee_polices.status !=', 'truncated')
+ ->where('employee_polices.is_active', 1)
+ ->first();
+
+ // $employee = $this->employeeModel->where('emp_code', $row[1])->where('name',$row[2])->where('client_id',$file['client_id'])->first();
+ // dd($employee);
+ // kint::dump($employee);
+
+ if (is_array($employee) && count($employee)) {
+ // dd($employee);
+ $existing_endorsements = $this->empEndorsementModel->where('actions', 'd')
+ ->where('table_name', 'employee_polices')
+ ->where('endorsement_id is null')
+ ->where('emp_code', $employee['emp_code'])
+ ->where('name', $employee['name'])
+ ->where('pk', $employee['emp_policy_pk'])
+ ->where('field_name', 'status')
+ ->where('status !=', 'truncated')
+ ->where('is_active', 1)
+ ->findAll();
+
+ // dd($existing_endorsements);
+ if (!count($existing_endorsements)) {
+ // dd($employee);
+ if (strtolower($employee['relationship']) != 'self') {
+
+ if (!in_array($employee['id'], $endorsement_data)) //make entry in endorsement firsttime only with checking that PK of emp exisintg in variable $endorsement_data
+ {
+ $employee_policy = $this->employeePolicyModel
+ ->where('employee_id', $employee['id'])
+ ->where('client_policy_id', $file['policy_id'])
+ ->where('status !=', 'truncated')
+ ->where('is_active', 1)
+ ->first();
+
+ $data = ['emp_id' => $employee['id'], 'name' => $employee['name'], 'emp_status' => $employee['emp_status'], 'emp_policy_id' => $employee_policy['id'], 'emp_code' => $employee['emp_code'], 'change_event' => $employee['change_event'], 'date_of_exit' => $employee_policy['date_of_exit'], 'reason_for_exit' => $employee_policy['reason_for_exit'], 'status' => $employee_policy['status'], 'claim_status' => $employee_policy['claim_status']];
+ $endorsement($data, $file, $row);
+ $endorsement_data[] = $employee['id'];
+ }
+ } else {
+
+ $family = $this->employeeModel->getEmpFamilybyEmpCode(emp_code: $row[1], client_id: $file['client_id'], client_policy_id: $file['policy_id'], emp_status: ['active'], policy_status: ['active']);
+ // Kint::dump($family);
+ foreach ($family as $key => $emp) {
+
+ if (!in_array($emp['emp_id'], $endorsement_data)) {
+ $endorsement($emp, $file, $row);
+
+ $endorsement_data[] = $emp['emp_id'];
+ }
+ }
+ }
+ } else {
+ $this->myLogger->logme("error", 'Existing endorsement pending for this employee : emp_code : {emp_code} - emp_name : {name}', ['emp_code' => $row[1], 'name' => $row[2]]);
+ }
+ } else {
+ $this->myLogger->logme("error", '{emp_code} - {name} not found', ['emp_code' => $row[1], 'name' => $row[2]]);
+ }
+
+ // print_r($endorsement_data);
+
+ }
+
+ // $this->fileModel->where('id', $file_id)->set(['status' => 'success', 'reason' => ''])->update();
+ // $this->setPullNotification($this->getFileMetaDataByFileId($file_id, 'success'));
+
+ $this->myLogger->logme("error", $file['action'] . ' : {file_id} uploaded success', ['file_id' => $file_id]);
+ return $endorsement_data;
+ }
+
+ //correction of emp
+ public function employeesCorrectionProcess($params)
+ {
+ helper('excel_util_helper');
+ //get file name
+ $file_id = $params['file_id'];
+ $file = $this->fileModel->find($file_id);
+ $file['action'] = $params['action'];
+
+
+ // $file_name_with_path = WRITEPATH . "/uploads/excel/" . $file['file_name'];
+ // $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file_name_with_path);
+ // $sheet = $spreadsheet->getActiveSheet();
+ // $highestRowAndColumn = $sheet->getHighestRowAndColumn();
+ // $allowedHighestColumn = end($this->correction_excel_columns);
+ // $excel_data = $sheet->rangeToArray('A1:' . $allowedHighestColumn['col_cell_name'] . $highestRowAndColumn['row']);
+
+ $excel_data = json_decode(file_get_contents($params['file_path'] ?? []), true);
+ unset($excel_data[0]);
+ // dd($excel_data);
+
+ //iterate each row
+ foreach ($excel_data as $col_key => $row) {
+ if (check_row_is_empty_or_null($row)) {
+ break;
+ }
+ // echo ' START- ' . $row[2];
+
+ $field_name = $row[3];
+ $field_value = ($field_name == 'dob' ? change_date_format($row[4], 'd-M-Y', 'Y-m-d') : $row[4]);
+
+
+ $employee = $this->employeeModel
+ ->where('emp_code', $row[1])
+ ->where('name', $row[2])
+ ->where('client_id', $file['client_id'])
+ ->where('client_branch_id', $file['client_branch_id'])
+ ->where('emp_status', 'active')
+ ->where('is_active', 1)
+ ->first();
+ $existing_endorsements = $this->empEndorsementModel->where('actions', 'c')
+ ->where('table_name', 'employees')
+ ->where('endorsement_id is null')
+ ->where('emp_code', $employee['emp_code'])
+ ->where('name', $employee['name'])
+ ->where('field_name', $field_name)
+ ->where('is_active', 1)
+ ->where('status !=', 'truncated')
+ ->findAll();
+ // dd($existing_endorsements);
+ //make entry in endorsement table
+ if (!count($existing_endorsements)) {
+ $group_key = rand(100000, 999999);
+ $this->empEndorsementModel->save(['pk' => (int)$employee['id'], 'emp_code' => $employee['emp_code'], 'table_name' => 'employees', 'actions' => 'c', 'name' => $employee['name'], 'field_name' => $field_name, 'old_value' => $employee[$field_name], 'new_value' => $field_value, 'created_by' => $file['created_by'], 'remarks' => $row[7], 'date_of_correction' => change_date_format($row[5], 'd-M-Y', 'Y-m-d'), 'group_key' => $group_key, 'file_id' => $file['id'], 'status' => 'pending']);
+ }
+ }
+
+ // $this->fileModel->where('id', $file_id)->set(['status' => 'success', 'reason' => ''])->update();
+ // $this->setPullNotification($this->getFileMetaDataByFileId($file_id, 'success'));
+ $this->myLogger->logme("error", $file['action'] . ' : {file_id} uploaded success', ['file_id' => $file_id]);
+ return true;
+ }
+
+ //enhance of emp
+ public function employeesSIEnhanceProcess($params)
+ {
+ helper('excel_util_helper');
+ //get file name
+ $file_id = $params['file_id'];
+ $file = $this->fileModel->find($file_id);
+ $file['action'] = $params['action'];
+
+ // $file_name_with_path = WRITEPATH . "/uploads/excel/" . $file['file_name'];
+ // $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file_name_with_path);
+ // $sheet = $spreadsheet->getActiveSheet();
+ // $highestRowAndColumn = $sheet->getHighestRowAndColumn();
+ // $allowedHighestColumn = end($this->si_enhance_excel_columns);
+ // $excel_data = $sheet->rangeToArray('A1:' . $allowedHighestColumn['col_cell_name'] . $highestRowAndColumn['row']);
+ $excel_data = json_decode(file_get_contents($params['file_path'] ?? []), true);
+ unset($excel_data[0]);
+ // dd($excel_data);
+
+ //get policy slab rates
+ $slab_details = $this->policiesModel->getPolicySlabRatesForEmpOnboard($file['policy_id'], $file['client_id']);
+ //iterate each row
+ // dd($slab_details);
+ foreach ($excel_data as $col_key => $row) {
+ if (check_row_is_empty_or_null($row)) {
+ break;
+ }
+ // echo ' START- ' . $row[2];
+ $employee = $this->employeeModel
+ ->where('emp_code', $row[1])
+ ->where('name', $row[2])
+ ->where('client_id', $file['client_id'])
+ ->where('client_branch_id', $file['client_branch_id'])
+ ->where('emp_status', 'active')
+ ->where('is_active', 1)
+ ->first();
+ $employee_policy = $this->employeePolicyModel
+ ->where('employee_id', $employee['id'])
+ ->where('client_policy_id', $file['policy_id'])
+ ->where('status', 'active')
+ ->where('is_active', 1)
+ ->first();
+ // dd($employee, $employee_policy);
+
+ $existing_endorsements = $this->empEndorsementModel->where('actions', 'si')
+ ->where('table_name', 'employee_polices')
+ ->where('endorsement_id is null')
+ ->where('emp_code', $employee['emp_code'])
+ ->where('name', $employee['name'])
+ ->where('field_name', 'basic_cover_si')
+ ->findAll();
+ // dd($existing_endorsements);
+ //make entry in endorsement table
+ if (!count($existing_endorsements)) {
+ //transform data to send
+
+ //get applicable slab rate for current member relation
+ $pre_rack_rate_name = '';
+ $applicable_rack_rate_name = '';
+ $applicable_rack_rate_master = [];
+ foreach ($slab_details['slab_rates'] as $skey => $slab_value) {
+ if ($pre_rack_rate_name != $slab_value['rack_rate_name']) {
+ $pre_rack_rate_name = $slab_value['rack_rate_name'];
+ $rack_rate_json = json_decode($slab_value['additional_relationship'], true);
+ $relationship_array_key = strtolower(trim($employee['relationship']));
+
+ if (in_array($relationship_array_key, ['son', 'daughter'])) {
+ $relationship_array_key = 'childrens';
+ } elseif (in_array($relationship_array_key, ['father', 'mother'])) {
+ $relationship_array_key = 'parents';
+ } elseif (in_array($relationship_array_key, ['father in law', 'mother in law', 'father-in-law', 'mother-in-law'])) {
+ $relationship_array_key = 'parents-in-law';
+ }
+
+ if (array_key_exists($relationship_array_key, $rack_rate_json) && $rack_rate_json[$relationship_array_key] != 0 && $rack_rate_json[$relationship_array_key] != 'NA') {
+ $applicable_rack_rate_name = $slab_value['rack_rate_name'];
+ $applicable_rack_rate_master = $slab_value['grid_master'];
+ break;
+ }
+ }
+ }
+
+ //get max age,max count of the familiy
+ $max_age_and_max_count_of_current_member = $this->employeeModel->getFamiliyCountAndMaxage($employee['emp_code']);
+ //transform SI excel row data as inception excel OR premium calculateable fomart
+
+ $data = transform_si_excel_row_to_calculatable_format(employee: $employee, employee_policy: $employee_policy, maxage_and_maxcount: $max_age_and_max_count_of_current_member, slab_details: $slab_details, applicable_slab_name: $applicable_rack_rate_name, augmented_si: $row[3], grid_master: $applicable_rack_rate_master);
+ $policy_terms = $this->clientPolicyModel->getPolicyDetails($file['client_id'], $file['policy_id']);
+ $policy_terms = (array) $policy_terms[0];
+ // dd($policy_terms);
+ //grouping slab details by rack rate name
+ $temp_slab_rates = group_slab_rates_basedon_name($slab_details);
+
+ $calculated_data = premium_calculation_manager($data, $policy_terms, $temp_slab_rates, $row[3]);
+
+ $group_key = rand(100000, 999999);
+ $this->empEndorsementModel->save(['pk' => (int)$employee_policy['id'], 'emp_code' => $employee['emp_code'], 'table_name' => 'employee_polices', 'actions' => 'si', 'name' => $employee['name'], 'field_name' => 'basic_cover_si', 'old_value' => $employee_policy['basic_cover_si'], 'new_value' => $row[3], 'created_by' => $file['created_by'], 'remarks' => 'general si enhancement', 'group_key' => $group_key, 'file_id' => $file['id'], 'status' => 'pending']);
+ $this->empEndorsementModel->save(['pk' => (int)$employee_policy['id'], 'emp_code' => $employee['emp_code'], 'table_name' => 'employee_polices', 'actions' => 'si', 'name' => $employee['name'], 'field_name' => 'premium', 'old_value' => $employee_policy['premium'], 'new_value' => $calculated_data['policy_details']['premium'], 'created_by' => $file['created_by'], 'remarks' => 'general si enhancement', 'group_key' => $group_key, 'file_id' => $file['id'], 'status' => 'pending']);
+ $this->empEndorsementModel->save(['pk' => (int)$employee_policy['id'], 'emp_code' => $employee['emp_code'], 'table_name' => 'employee_polices', 'actions' => 'si', 'name' => $employee['name'], 'field_name' => 'si_enhancement_date', 'old_value' => null, 'new_value' => change_date_format($row[4], 'd-M-Y', 'Y-m-d'), 'created_by' => $file['created_by'], 'remarks' => 'general si enhancement', 'group_key' => $group_key, 'file_id' => $file['id'], 'status' => 'pending']);
+ }
+ }
+
+ // $this->fileModel->where('id', $file_id)->set(['status' => 'success', 'reason' => ''])->update();
+ // $this->setPullNotification($this->getFileMetaDataByFileId($file_id, 'success'));
+ $this->myLogger->logme("error", $file['action'] . ' : {file_id} uploaded success', ['file_id' => $file_id]);
+
+ return true;
+ }
+
+ // insert or update in db for inception addition depent addition
+ public function employeesOnboardProcess($params)
+ {
+ // dd($params);
+
+ $familiy_data = $params['familiy_data'];
+ $file = $params['file'];
+
+ $policy_details = $this->clientPolicyModel->where('id', $file['policy_id'])->first();
+ // dd($policy_details);
+
+ foreach ($familiy_data as $fkey => $value) {
+ if (is_array($value)) {
+
+
+ if ($file['id'] == null || $value['temp']['source'] == 'excel' || (($file['action'] == 'dependent_addition' && ($value['temp']['premium_type'] == 1 && strtolower($value['relationship']) == 'self') || ($value['temp']['premium_type'] == 2 || $value['temp']['premium_type'] == null)))) //insert data come from excel and from db i.e. ( $file['id'] == null for enrollment data)
+ {
+
+ $employee = $this->employeeModel->checkExistingEmp($value, $file['client_branch_id']);
+ $policy_data = $value['policy_details'];
+ $temp = $value['temp'];
+ unset($value['policy_details']);
+ unset($value['temp']);
+ // Kint::dump($value);
+ // Kint::dump($temp);
+ // Kint::dump($policy_data);
+ // echo '---------------------------------------';
+
+ //start implemet of si enhancement of grid type 10,11
+ if (count($employee) && $file['action'] == 'dependent_addition' && $temp['source'] == 'db' && in_array($temp['grid_id'], [10, 11]) && (($temp['premium_type'] == 1 && (strtolower($value['relationship']) == 'self' || $temp['acting_self'])) || ($temp['premium_type'] == 2 || $temp['premium_type'] == null))) {
+ $log_message = 'Employee record from DB,Checking SI for - ' . $employee[0]['name'] . '(' . $employee[0]['emp_code'] . ')';
+ $this->myLogger->logme('error', $log_message);
+ $res = $this->employeesSIEnhanceProcessWhileOnbboard(employee: $employee[0], policy_data: $policy_data, file: $file); // where employee holds existing emp data and policy_data holds new si enhancement
+
+ break; //skip db employee
+ }
+ //end implemet of si enhancement of grid type
+ //save employee table
+ $value['relationship'] = ucfirst(trim($value['relationship']));
+ if (count($employee)) {
+ $value['updated_by'] = $file['created_by'];
+ $value['id'] = $employee[0]['id'];
+ $value['emp_status'] = 'active';
+ $value['family_floater_key'] = generate_family_floater_key($value['relationship']);
+ $value['client_branch_id'] = $file['client_branch_id'];
+ $value['file_id'] = isset($employee[0]['file_id']) && $employee[0]['file_id'] != '' ? $employee[0]['file_id'] : $file['id'];
+ $log_message = 'Update Employee - ' . $employee[0]['name'] . '(' . $employee[0]['emp_code'] . ') with PK ' . $employee[0]['id'];
+ // $this->myLogger->logme('error',('Update - ' . $employee[0]['id'].' - '. $employee[0]['emp_code'] .' - '.$employee[0]['name']));
+ // echo 'insert emp';
+ } else {
+ $value['emp_status'] = 'active';
+ $value['created_by'] = $file['created_by'];
+ $value['client_branch_id'] = $file['client_branch_id'];
+ $value['family_floater_key'] = generate_family_floater_key($value['relationship']);
+ $value['file_id'] = isset($employee[0]['file_id']) && $employee[0]['file_id'] != '' ? $employee[0]['file_id'] : $file['id'];
+ $log_message = 'Insert Employee- ' . $value['name'] . '(' . $value['emp_code'] . ') with PK ';
+ // $this->myLogger->logme('error',('Insert - ' . $value['emp_code'] .' - '. $value['name']));
+ // echo 'update emp';
+ }
+ $value = ExcelSanitizeHelper::sanitizeArrayData($value);
+ $this->employeeModel->save($value);
+ if (isset($value['id'])) {
+ $emp_id = $value['id'];
+ } else {
+ $emp_id = $this->employeeModel->getInsertID();
+ $log_message .= $emp_id;
+ }
+
+ //commanded for last insert id is coming from buffer
+ // $emp_id = $this->employeeModel->getInsertID();
+ // if($emp_id != 0){ $log_message .= $emp_id; }
+ // else{ $emp_id = $employee[0]['id']; }
+
+ $this->myLogger->logme('error', $log_message);
+
+ //save policy table
+ $employee_policy = $this->employeePolicyModel->checkExistingEmpPolicy(['employee_id' => $emp_id, 'client_policy_id' => $file['policy_id']]);
+ if (count($employee_policy)) {
+ $policy_data['updated_by'] = $file['created_by'];
+ $policy_data['id'] = $employee_policy[0]['id'];
+ $policy_data['status'] = 'active';
+ $policy_data['payable_employee'] = check_pay_by_employee_or_company($policy_details['policy_terms'], $value['relationship']);
+ $policy_data['file_id'] = isset($employee_policy[0]['file_id']) && $employee_policy[0]['file_id'] != '' ? $employee_policy[0]['file_id'] : $file['id'];
+ $log_message = 'Update Employee Policy for ' . $value['name'] . '(' . $value['emp_code'] . ') with PK- ' . $employee_policy[0]['id'] . ' client policy ID ' . $employee_policy[0]['client_policy_id'] . ' with SI ' . $policy_data['basic_cover_si'];
+ // echo 'insert policy';
+ } else {
+ $policy_data['employee_id'] = $emp_id;
+ $policy_data['client_policy_id'] = $file['policy_id'];
+ $policy_data['created_by'] = $file['created_by'];
+ $policy_data['status'] = 'active';
+ $policy_data['payable_employee'] = check_pay_by_employee_or_company($policy_details['policy_terms'], $value['relationship']);
+ $policy_data['file_id'] = $file['id'];
+ $log_message = 'Insert Employee Policy for ' . $value['name'] . '(' . $value['emp_code'] . ') - client policy id -' . $file['policy_id'] . ' - with SI ' . $policy_data['basic_cover_si'];
+ // echo 'update policy';
+ }
+ // log_message('error',json_encode($policy_data));
+ // dd($this->employeePolicyModel->save($policy_data));
+ $res = $this->employeePolicyModel->save($policy_data);
+ // if($res){log_message('error','ths the resul'.$res);}
+ if (isset($policy_data['id'])) {
+ $emp_policy_id = $policy_data['id'];
+ } else {
+ $emp_policy_id = $this->employeePolicyModel->getInsertID();
+ }
+
+ if ($emp_policy_id != 0) //emp policy inserted
+ {
+ $log_message .= ' with PK ' . $emp_policy_id;
+
+ //make endorsement entry if action is addition OR Dependt addition
+ if (($file['action'] == 'missed_inception' || $file['action'] == 'dependent_addition' || $file['action'] == 'addition') && $temp['source'] == 'excel') {
+ $log_message = $file['action'] . ' - endorsement' . $value['emp_code'] . ' - ' . $value['name'] . ' - with policy id' . $emp_policy_id;
+ $this->myLogger->logme('error', $log_message);
+ $actions = ($file['action'] == 'dependent_addition' ? 'da' : ($file['action'] == 'addition' ? 'a' : 'a'));
+ $addition_endorse_data = ['pk' => $emp_policy_id, 'group_key' => rand(100000, 999999), 'emp_code' => $value['emp_code'], 'table_name' => 'employee_polices', 'actions' => $actions, 'name' => $value['name'], 'field_name' => 'basic_cover_si', 'old_value' => NULL, 'new_value' => $policy_data['basic_cover_si'], 'remarks' => 'addition endorsement', 'file_id' => $file['id'], 'created_by' => $file['created_by'], 'status' => 'pending'];
+ $this->employeeEndorsementforAddtionAndDependentAddition($addition_endorse_data);
+ }
+ }
+ // else{ $emp_policy_id = $employee_policy[0]['id']; }
+
+ $this->myLogger->logme('error', $log_message);
+ } // if end
+ } // is array check end
+ else {
+ $this->myLogger->logme('error', '######Incoming value is not an array');
+ }
+ } // for end
+ } //function end
+
+
+ public function employeeEndorsementforAddtionAndDependentAddition($employee)
+ {
+ $this->empEndorsementModel->save($employee);
+ }
+
+ // $employee -> holds existing emp model obj and $policy_data holds new policy changes as array
+ public function employeesSIEnhanceProcessWhileOnbboard(array $employee, array $policy_data, array $file)
+ {
+
+ $employee = $this->employeeModel->where('emp_code', $employee['emp_code'])->where('name', $employee['name'])->where('client_id', $employee['client_id'])->where('client_branch_id', $file['client_branch_id'])->where('is_active', 1)->first();
+ // Kint::dump($this->employeeModel->getLastQuery());
+ // dd($employee);
+ $employee_policy = $this->employeePolicyModel->where('employee_id', $employee['id'])->where('client_policy_id', $file['policy_id'])->first();
+ // dd($employee_policy);
+ // $slab_details = $this->policiesModel->getPolicySlabRatesForEmpOnboard($employee_policy['client_policy_id'],$employee['client_id']);
+ // dd($slab_details);
+ // $temp_slab_details = ($temp['grid_type'] == 'primary' ? $slab_details['slab_rates'] : $slab_details['additional_slab_info']['slab_rates']);
+
+ //check si has changed in normal case OR check premium only changed, still treat as SI enhancement in grid type 10
+ if ($employee_policy['basic_cover_si'] != $policy_data['basic_cover_si'] || ($policy_data['premium'] != null && $policy_data['premium'] != "" && $employee_policy['premium'] != $policy_data['premium'])) {
+ $existing_endorsements = $this->empEndorsementModel->where('actions', 'si')
+ ->where('table_name', 'employee_polices')
+ ->where('endorsement_id is null')
+ ->where('emp_code', $employee['emp_code'])
+ ->where('name', $employee['name'])
+ ->where('field_name', 'basic_cover_si')
+ ->findAll();
+ //make entry in endorsement table
+ if (!count($existing_endorsements)) {
+ $group_key = rand(100000, 999999);
+ $data = array(
+ ['pk' => (int)$employee_policy['id'], 'emp_code' => $employee['emp_code'], 'table_name' => 'employee_polices', 'actions' => 'si', 'name' => $employee['name'], 'field_name' => 'basic_cover_si', 'old_value' => $employee_policy['basic_cover_si'], 'new_value' => $policy_data['basic_cover_si'], 'created_by' => $file['created_by'], 'remarks' => 'general si enhancement via DA', 'group_key' => $group_key, 'file_id' => $file['id']],
+ ['pk' => (int)$employee_policy['id'], 'emp_code' => $employee['emp_code'], 'table_name' => 'employee_polices', 'actions' => 'si', 'name' => $employee['name'], 'field_name' => 'premium', 'old_value' => $employee_policy['premium'], 'new_value' => $policy_data['premium'], 'created_by' => $file['created_by'], 'remarks' => 'general si enhancement via DA', 'group_key' => $group_key, 'file_id' => $file['id']],
+ ['pk' => (int)$employee_policy['id'], 'emp_code' => $employee['emp_code'], 'table_name' => 'employee_polices', 'actions' => 'si', 'name' => $employee['name'], 'field_name' => 'si_enhancement_date', 'old_value' => null, 'new_value' => date('Y-m-d'), 'created_by' => $file['created_by'], 'remarks' => 'general si enhancement via DA', 'group_key' => $group_key, 'file_id' => $file['id']]
+ );
+
+ $this->empEndorsementModel->insertBatch($data);
+ $this->myLogger->logme('error', ($employee['emp_code'] . ' - ' . $employee['name'] . '- ( NEW/OLD SI - ' . $employee_policy['basic_cover_si'] . '/' . $policy_data['basic_cover_si'] . ')' . '( NEW/OLD PREMIUM - ' . $employee_policy['premium'] . '/' . $policy_data['premium'] . ') ' . ' - si enhancement via DA'));
+ $log_message = 'SI enhancement done during dependent_addition - ' . $employee['name'] . '(' . $employee['emp_code'] . ')';
+ $this->myLogger->logme('error', $log_message);
+ return true; //retun true when endorsement inserted
+
+ }
+ return false; //retun false when endorsement not happend
+ }
+ return false; //retun false when endorsement not happend
+
+
+ }
+
+ // --------------- FUNCTION FOR ERROR DISPLAY ------------------------------------------------------------------------------------------
+
+ public function getExcelErrorData($file_id, $res)
+ {
+
+ try {
+ $file = $this->fileModel->find($file_id);
+ // $error_data = json_decode($file['reason'], true);
+ $error_data = $res;
+ // dd($error_data);
+ // return $error_data;
+
+ $file_name_with_path = WRITEPATH . "/uploads/excel/" . $file['file_name'];
+
+ //check the file exist or not
+ if (!file_exists($file_name_with_path)) {
+ $error_message = "File not found";
+ $this->myLogger->logme('error', ($error_message . ' for file id ' . $file_id));
+ return 0;
+ }
+
+ $column_to_check = $this->multievent_excel_columns;
+ $allowedHighestColumn = end($column_to_check);
+
+ $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file_name_with_path);
+ $sheet = $spreadsheet->getActiveSheet();
+
+ $highestRow = $sheet->getHighestDataRow();
+ $excel_data = $sheet->rangeToArray('A1:' . $allowedHighestColumn['col_cell_name'] . $highestRow);
+
+ $excelErrorData['excel_header'] = $excel_data[0];
+ unset($excel_data[0]);
+ // echo '';
+ // Kint::dump($excel_data);
+ if ($error_data['error_type'] == 1) {
+
+ $finalArray = [];
+ 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,];
+ $excel_data[$key][$value2['col_idx']] = $data;
+ }
+ array_push($finalArray, $excel_data[$key]);
+ }
+
+ foreach ($finalArray as $fkey => $value) {
+ foreach ($value as $vkey => $arrayData) {
+ if (!is_array($arrayData)) {
+ $data = ['value' => $arrayData];
+ $finalArray[$fkey][$vkey] = $data;
+ }
+ }
+ }
+
+ $excelErrorData['excel_data'] = $finalArray;
+ return $excelErrorData;
+ } else if ($error_data['error_type'] == 2) {
+
+
+ $allErrors = [];
+ $typeTowArray = [];
+
+ foreach ($error_data['error_data'] as $index => $item) {
+
+ foreach ($item as $field) {
+ if (!isset($allErrors[$index])) {
+ $allErrors[$index] = [];
+ }
+ $allErrors[$index] = array_merge($allErrors[$index], $field['error']);
+ }
+ }
+
+ // dd(array_keys($allErrors));
+ foreach ($allErrors as $key => $value) {
+ // echo $key;
+ // 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,];
+ $excel_data[$excel_data_index][1] = $data;
+ array_push($typeTowArray, $excel_data[$excel_data_index]);
+ break;
+ }
+ }
+ }
+ // dd($data);
+ foreach ($typeTowArray as $fkey => $value) {
+ foreach ($value as $vkey => $arrayData) {
+ if (!is_array($arrayData)) {
+ $data = ['value' => $arrayData];
+ $typeTowArray[$fkey][$vkey] = $data;
+ }
+ }
+ }
+
+ $excelErrorData['excel_data'] = $typeTowArray;
+ return $excelErrorData;
+ }
+ } catch (\Exception $e) {
+ // // Handle any exceptions
+ // $errorMessage = $e->getMessage(); //die();
+ // $this->myLogger->logme('error', $errorMessage);
+ // return false; // You can return an error response here
+
+ $errorDetails = [
+ 'error_message' => $e->getMessage(),
+ 'file' => $e->getFile(),
+ 'line' => $e->getLine(),
+ 'stack_trace' => $e->getTraceAsString(),
+ ];
+ return $errorDetails;
+ }
+ }
+
+ // ---------------------------------------------------------------------------------
+
+ public function getFileMetaDataByFileId($file_id, $status = 'success')
+ {
+
+ $data = $this->fileModel
+ ->select('files.*, clients.client_name, clients.short_name, policy_type.policy_type as policy_name,client_branch.branch_code')
+ ->join('clients', 'clients.id = files.client_id')
+ ->join('client_policy', 'client_policy.id = files.policy_id')
+ ->join('policy_type', 'policy_type.id = client_policy.policy_type_id')
+ ->join('client_branch', 'client_branch.id = files.client_branch_id', 'left')
+ ->where('files.id', $file_id)
+ ->first();
+
+ if ($status == 'success') {
+ $msg_title = 'File Upload Success';
+ } else if ($status == 'failure') {
+ $msg_title = 'File Upload Failure';
+ }
+
+ $msg_txt = $data['client_name'] . ' (' . $data['branch_code'] . ') - ' . $data['policy_name'] . ' - ' . ucfirst($data['action']);
+ $user_id = $data['created_by'];
+ $url = 'employee/upload';
+
+ return ['msg_txt' => $msg_txt, 'user_id' => $user_id, 'url' => $url, 'status' => $status, 'title' => $msg_title];
+ }
+
+ public function setPullNotification($data)
+ {
+
+
+ $array = ['message_text' => $data['msg_txt'], 'action_url' => $data['url'], 'msg_status' => $data['status'], 'msg_title' => $data['title']];
+ $jsonEncodeData = json_encode($array);
+
+ $msg_data = [
+
+ 'message_text' => $jsonEncodeData,
+ 'user_id' => $data['user_id'],
+ 'role_id' => NULL,
+ 'team_id' => NULL,
+ 'message_type' => '1to1',
+ ];
+
+
+ $this->messageModel->insert($msg_data);
+ }
+
+ public function employeesEnrollmentInsert($params)
+ {
+ // dd($this->request);
+ helper('excel_util_helper');
+ //get file name
+ $file_id = $params['file_id'];
+ $file = $this->fileModel->find($file_id);
+ // dd($file);
+ $return = [];
+ if (!isset($file)) {
+ //file not found in DB
+ return array('status' => false, 'msg' => 'file not found in DB');
+ }
+ $file_name_with_path = WRITEPATH . "/uploads/excel/" . $file['file_name'];
+
+ //check physical file
+ if (!file_exists($file_name_with_path)) {
+ //file not found update status and reason
+ $message = "Physical file not found";
+ // echo $message;
+ $this->myLogger->logme('error', ($message . ' for file id ' . $file_id));
+ $this->fileModel->where('id', $file_id)->set(['status' => 'failed', 'reason' => json_encode(['error_summary' => array_count_values([5]), 'error_data' => $message])])->update();
+ return array('error_summary' => [5], 'error_data' => $message);
+ }
+
+ //get excel data
+ $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file_name_with_path);
+ $sheet = $spreadsheet->getActiveSheet();
+
+ $highestRowAndColumn = $sheet->getHighestRowAndColumn();
+ $result = ['error_type' => 2, 'error_summary' => [], 'error_data' => []];
+ $columns_to_check = $this->enrollment_excel_columns;
+ $keys = array_keys($columns_to_check);
+ $allowedHighestColumn = end($columns_to_check);
+ $excel_data = $sheet->rangeToArray('A1:' . $allowedHighestColumn['col_cell_name'] . $highestRowAndColumn['row']);
+ // print_r($keys);die();
+ //get existing units in the current branch
+ $existing_units = $this->clientBranchModel->getExisitingUnits(client_id: $file['client_id'], client_branch_id: $file['client_branch_id']);
+ //remove header
+ unset($excel_data[0]);
+ // dd($excel_data);
+ $emp_emails = [];
+
+ //check is welcome notification enabled
+ $notification = $this->notificationModel->where('client_id', $file['client_id'])->where('template_name', 'member_welcome_mail')->first();
+ // dd($notification);
+ $client_details = $this->clientModel->where('id', $file['client_id'])->first();
+ $policy_details = $this->clientPolicyModel->where('id', $file['policy_id'])->first();
+
+ // dd($policy_details);
+
+ //get policy slab rates
+ // $slab_details = $this->policiesModel->getPolicySlabRatesForEmpOnboard($file['policy_id'],$file['client_id']);
+ // dd($slab_details);
+
+ foreach ($excel_data as $key => $row) {
+ $is_row_empty = check_row_is_empty_or_null($row);
+ if (!$is_row_empty) {
+
+ $value = [];
+ $policy_data = [];
+ $temp_unit = '';
+ if (empty($row[12])) {
+ $temp_unit = $existing_units[0];
+ }
+
+ $value['emp_code'] = $row[1];
+ $value['name'] = $row[2];
+ $value['doj'] = (!empty($row[3]) ? change_date_format($row[3], 'd-M-Y', 'Y-m-d') : null);
+ $value['gender'] = $row[4];
+ $value['relationship'] = ucfirst(trim($row[5]));
+ $value['dob'] = change_date_format($row[6], 'd-M-Y', 'Y-m-d');
+ $value['email_corporate'] = $row[7];
+ $value['mobile'] = $row[8];
+ $value['band'] = $row[10];
+ $value['basic_pay'] = $row[11];
+ $value['unit'] = $temp_unit;
+ $value['family_floater_key'] = null;
+ $value['client_id'] = $file['client_id'];
+ $value['client_branch_id'] = $file['client_branch_id'];
+ $value['file_id'] = $file_id;
+ $value['is_addon_value'] = $policy_details['policy_type_id'] == 3 ? 1 : 0;
+
+ $value['temp']['emp_id'] = null; // dummy value for using exisitng funciton in model
+ if (strtolower(trim($value['relationship'])) === 'mother' || strtolower(trim($value['relationship'])) === 'father') {
+ $relation = 'parent';
+ } else if (strtolower(trim($value['relationship'])) === 'son' || strtolower(trim($value['relationship'])) === 'daughter') {
+ $relation = 'child';
+ } else if ((strtolower(trim($value['relationship'])) === 'father in law' || strtolower(trim($value['relationship'])) === 'mother in law') || (strtolower(trim($value['relationship'])) === 'father-in-law' || strtolower(trim($value['relationship'])) === 'mother-in-law')) {
+ $relation = 'parent_in_law';
+ } else if (strtolower(trim($value['relationship'])) === 'spouse') {
+ $relation = 'spouse';
+ } else if (strtolower(trim($value['relationship'])) === 'self') {
+ $relation = 'self';
+ } else {
+ $relation = '';
+ }
+ $value['family_floater_key'] = $relation;
+
+ // dd($value['family_floater_key']);
+
+ $policy_data['basic_cover_si'] = $row[9];
+ $policy_data['date_coverage'] = $row[13] != "" && $row[13] != null ? change_date_format($row[13], 'd-M-Y', 'Y-m-d') : null;
+ $policy_data['client_policy_id'] = $file['policy_id'];
+
+ $employee = $this->employeeModel->checkExistingEmployee($value, $file['client_branch_id']);
+ unset($value['temp']);
+ //save employee table
+ // dd($employee['id']);
+ if ($employee !== null) {
+ $value['updated_by'] = $file['created_by'];
+ $value['id'] = $employee['id'];
+ $value['emp_status'] = 'draft';
+
+ $log_message = 'Enrollment Update Employee - ' . $employee['name'] . '(' . $employee['emp_code'] . ') with PK ' . $employee['id'];
+ } else {
+ $value['emp_status'] = 'draft';
+ $value['created_by'] = $file['created_by'];
+ $log_message = 'Enrollment Insert Employee- ' . $value['name'] . '(' . $value['emp_code'] . ') with PK ';
+ }
+
+ $value = ExcelSanitizeHelper::sanitizeArrayData($value);
+ $this->employeeModel->save($value);
+ if (isset($value['id'])) {
+ $emp_id = $value['id'];
+ } else {
+ $emp_id = $this->employeeModel->getInsertID();
+ $log_message .= $emp_id;
+ }
+
+ // $emp_id = $this->employeeModel->getInsertID();
+ // if($emp_id != 0){ $log_message .= $emp_id; }
+ // else{ $emp_id = $employee['id']; }
+
+ $this->myLogger->logme('error', $log_message);
+
+ //save policy table
+ $employee_policy = $this->employeePolicyModel->checkExistingEmpPolicy(['employee_id' => $emp_id, 'client_policy_id' => $file['policy_id']]);
+ if (count($employee_policy)) {
+ $policy_data['updated_by'] = $file['created_by'];
+ $policy_data['id'] = $employee_policy[0]['id'];
+ $policy_data['status'] = 'draft';
+ $policy_data['payable_employee'] = check_pay_by_employee_or_company($policy_details['policy_terms'], $value['relationship']);
+ $policy_data['file_id'] = isset($employee_policy[0]['file_id']) && $employee_policy[0]['file_id'] != '' ? $employee_policy[0]['file_id'] : $file_id;
+ $log_message = 'Update Employee Policy for ' . $value['name'] . '(' . $value['emp_code'] . ') with PK- ' . $employee_policy[0]['id'] . ' client policy ID ' . $employee_policy[0]['client_policy_id'] . ' with SI ' . $policy_data['basic_cover_si'];
+ // echo 'insert policy';
+ } else {
+ $policy_data['employee_id'] = $emp_id;
+ $policy_data['client_policy_id'] = $file['policy_id'];
+ $policy_data['created_by'] = $file['created_by'];
+ $policy_data['status'] = 'draft';
+ $policy_data['payable_employee'] = check_pay_by_employee_or_company($policy_details['policy_terms'], $value['relationship']);
+ $policy_data['file_id'] = $file_id;
+ $log_message = 'Insert Employee Policy for ' . $value['name'] . '(' . $value['emp_code'] . ') - client policy id -' . $file['policy_id'] . ' - with SI ' . $policy_data['basic_cover_si'];
+ // echo 'update policy';
+ }
+
+ log_message('error', json_encode($policy_data));
+ // dd($policy_data);
+ $this->employeePolicyModel->save($policy_data);
+ $emp_policy_id = $this->employeePolicyModel->getInsertID();
+ $this->myLogger->logme('error', $log_message);
+
+ $employeeRestController = new EmployeeRestController();
+ $employeeRestController->updatePremiumAmount($file['policy_id'], $value['emp_code'], $file['client_branch_id']);
+
+
+ //save email of self for send mail later
+ if (isset($notification) && $notification['enabled'] == 1 && $notification['mail_content'] != '') {
+ if (strtolower($value['relationship']) == 'self' && $value['email_corporate'] != "") {
+ $params['dataToInsert'] = $value; //holds employee master data
+ $params['notification'] = $notification;
+ $params['client_data'] = $client_details;
+ $params['common'] = [
+ 'client_id' => $file['client_id'],
+ 'client_branch_id' => $file['client_branch_id'],
+ 'client_policy_id' => $file['policy_id'],
+ 'employee_policy_id' => $emp_policy_id ?? null,
+ 'employee_id' => $emp_id,
+ 'mail_type' => 'member_welcome_mail',
+ ];
+ //store email and mail content via helper to send notification
+ $emp_emails[] = sendMailNotification::sendMailNotification('member_welcome_mail', $params);
+ }
+ }
+ } // endof if row is empty check
+ } //end of for loop
+
+ // dd($emp_emails);
+
+ // for bulk mail queue job push
+ if (!empty($emp_emails) && count($emp_emails) > 0) {
+
+ $emp_emails = array_chunk($emp_emails, 20);
+
+ foreach ($emp_emails as $key => $value) {
+ $job_details = new Jobs();
+ $r = Jobs::addJob(['job_name' => 'bulk_mail', 'payload' => $value]);
+ }
+ }
+
+ $this->fileModel->where('id', $file_id)->set(['status' => 'success', 'reason' => ''])->update();
+ $this->myLogger->logme("error", '{file_id} uploaded success', ['file_id' => $file_id]);
+
+ $this->setPullNotification($this->getFileMetaDataByFileId($file_id, 'success'));
+
+
+ return true;
+ } //end of employeesEnrollmentInsert
+
+ // --------------- FUNCTION FOR MULTI EVENT ------------------------------------------------------------------
+
+ public function constructMultiEventData($params)
+ {
+ $file_id = $params['file_id'];
+ $file = $this->fileModel->where('is_active', 1)->where('id', $file_id)->first();
+ $file_name = $file['file_name'];
+
+ $column_to_check = $this->multievent_excel_columns;
+ $allowedHighestColumn = end($column_to_check);
+ $event_coumn_index = $column_to_check['change_event']['col_idx'];
+
+ $addition_column_to_check = $this->inception_excel_columns;
+ $correction_column_to_check = $this->correction_excel_columns;
+ $deletion_column_to_check = $this->deletion_excel_columns;
+ $si_column_to_check = $this->si_enhance_excel_columns;
+
+ $file_name_with_path = WRITEPATH . "uploads/excel/" . $file_name;
+ $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file_name_with_path);
+ $worksheet = $spreadsheet->getActiveSheet();
+
+ $highestRow = $worksheet->getHighestDataRow();
+ $highestColumn = $worksheet->getHighestDataColumn();
+
+ $excel_data = $worksheet->rangeToArray('A1:' . $allowedHighestColumn['col_cell_name'] . $highestRow);
+ $excel_header = $excel_data[0];
+ unset($excel_data[0]);
+ $excel_data = ExcelSanitizeHelper::sanitizeArrayData($excel_data);
+
+
+ // Buckets
+ $inception = [];
+ $missed_inception = [];
+ $addition_endorsement = [];
+ $dependent_addition_endorsement = [];
+ $deletion_endorsement = [];
+ $correction_endorsement = [];
+ $si_enhancement_endorsement = [];
+
+ foreach ($excel_data as $row_idx => $row_value) {
+ $event = strtolower(trim($row_value[$event_coumn_index] ?? ''));
+
+ switch ($event) {
+ case "addition":
+ if (empty($addition_endorsement)) {
+ $addition_endorsement[] = $this->buildHeaderData($addition_column_to_check);
+ }
+ $addition_endorsement[$row_idx] = $this->buildEndorsementData($row_value, $row_idx, $addition_column_to_check, $column_to_check);
+ break;
+
+ case "missed inception":
+ if (empty($missed_inception)) {
+ $missed_inception[] = $this->buildHeaderData($addition_column_to_check);
+ }
+ $missed_inception[$row_idx] = $this->buildEndorsementData($row_value, $row_idx, $addition_column_to_check, $column_to_check);
+ break;
+
+ case "dependent addition":
+ if (empty($dependent_addition_endorsement)) {
+ $dependent_addition_endorsement[] = $this->buildHeaderData($addition_column_to_check);
+ }
+ $dependent_addition_endorsement[$row_idx] = $this->buildEndorsementData($row_value, $row_idx, $addition_column_to_check, $column_to_check);
+ break;
+
+ case "correction":
+ if (empty($correction_endorsement)) {
+ $correction_endorsement[] = $this->buildHeaderData($correction_column_to_check);
+ }
+ $correction_endorsement[$row_idx] = $this->buildEndorsementData($row_value, $row_idx, $correction_column_to_check, $column_to_check);
+ break;
+
+ case "deletion":
+ if (empty($deletion_endorsement)) {
+ $deletion_endorsement[] = $this->buildHeaderData($deletion_column_to_check);
+ }
+ $deletion_endorsement[$row_idx] = $this->buildEndorsementData($row_value, $row_idx, $deletion_column_to_check, $column_to_check);
+ break;
+
+ case "si enhancement":
+ if (empty($si_enhancement_endorsement)) {
+ $si_enhancement_endorsement[] = $this->buildHeaderData($si_column_to_check);
+ }
+ $si_enhancement_endorsement[$row_idx] = $this->buildEndorsementData($row_value, $row_idx, $si_column_to_check, $column_to_check);
+ break;
+
+ default: // inception
+ if (empty($inception) || $inception == "") {
+ $inception[] = $this->buildHeaderData($addition_column_to_check);
+ }
+ $inception[$row_idx] = $this->buildEndorsementData($row_value, $row_idx, $addition_column_to_check, $column_to_check);
+ break;
+ }
+ }
+
+ // Final data collection
+ $finalData = [
+ 'inception' => $inception,
+ 'missed_inception' => $missed_inception,
+ 'addition' => $addition_endorsement,
+ 'dependent_addition' => $dependent_addition_endorsement,
+ 'deletion' => $deletion_endorsement,
+ 'correction' => $correction_endorsement,
+ 'si_enhancement' => $si_enhancement_endorsement,
+ ];
+ // dd($finalData);
+
+ // Save JSON file in writable/tmp/
+ $savedFiles = [];
+ foreach ($finalData as $key => $data) {
+ $filePath = WRITEPATH . 'tmp/' . $key . '_' . time() . '.json';
+ file_put_contents($filePath, json_encode($data, JSON_PRETTY_PRINT));
+ $savedFiles[$key] = $filePath;
+ }
+
+ return $savedFiles;
+
+ }
+
+ public function buildEndorsementData(array $row_value, $row_idx, array $convertable_column, array $multi_event_column): array
+ {
+ $newRow = [];
+ foreach ($convertable_column as $col => $col_val) {
+ $idx = $multi_event_column[$col]['col_idx'];
+ $newRow[] = $row_value[$idx] ?? '';
+ }
+
+ return $newRow;
+ }
+
+ public function buildHeaderData(array $convertable_column): array
+ {
+ $headerRow = [];
+ foreach ($convertable_column as $col) {
+ $headerRow[] = $col['col_name'];
+ }
+
+ return $headerRow;
+ }
+
+ public function unlinkFiles($filePaths)
+ {
+ foreach ($filePaths as $filePath) {
+ if (file_exists($filePath)) {
+ unlink($filePath); // delete file
+ }
+ }
+ }
+
+ public function readTheJsonFileToArray($filePaths)
+ {
+ $allData = [];
+ foreach ($filePaths as $type => $filePath) {
+ if (file_exists($filePath)) {
+ $allData[$type] = json_decode(file_get_contents($filePath), true);
+ }
+ }
+
+ return $allData;
+ }
+
+ public function mergeErrors(array $data, $error_type = 1): array
+ {
+ $merged = [
+ 'error_type' => $error_type,
+ 'error_summary' => [],
+ 'error_data' => []
+ ];
+
+ foreach ($data as $item) {
+ // Merge error_summary (sum values)
+ foreach ($item['error_summary'] as $key => $value) {
+ if (!isset($merged['error_summary'][$key])) {
+ $merged['error_summary'][$key] = 0;
+ }
+ $merged['error_summary'][$key] += $value;
+ }
+
+ // Merge error_data (append rows)
+ foreach ($item['error_data'] as $rowIndex => $rowErrors) {
+ if (!isset($merged['error_data'][$rowIndex])) {
+ $merged['error_data'][$rowIndex] = [];
+ }
+
+ foreach ($rowErrors as $fieldKey => $fieldError) {
+ if (!isset($merged['error_data'][$rowIndex][$fieldKey])) {
+ $merged['error_data'][$rowIndex][$fieldKey] = $fieldError;
+ } else {
+ // merge errors if same field exists
+ $merged['error_data'][$rowIndex][$fieldKey]['error'] = array_merge(
+ $merged['error_data'][$rowIndex][$fieldKey]['error'],
+ $fieldError['error']
+ );
+ // remove duplicates & reindex
+ $merged['error_data'][$rowIndex][$fieldKey]['error'] = array_values(
+ array_unique($merged['error_data'][$rowIndex][$fieldKey]['error'])
+ );
+ }
+ }
+ }
+ }
+
+ return $merged;
+ }
+
+ public function syncColIndex(array $main, array $temp): array
+ {
+ foreach ($temp as $key => &$t) {
+ if (isset($main[$key])) {
+ $t['col_idx'] = $main[$key]['col_idx']; // update col_idx
+ $t['col_cell_name'] = $main[$key]['col_cell_name']; // optional: also sync cell name
+ }
+ }
+ unset($t); // break reference
+
+ return $temp;
+ }
+
+
+
+}
diff --git a/app/Controllers/EmployeeRestController.php b/app/Controllers/EmployeeRestController.php
index d8ec8b0e..1dd19735 100755
--- a/app/Controllers/EmployeeRestController.php
+++ b/app/Controllers/EmployeeRestController.php
@@ -34,6 +34,7 @@ use App\Models\TicketMasterModel;
use App\Models\TicketMessageModel;
use App\Models\HRAccessControlModel;
use App\Models\InsurerModel;
+use App\Models\HrFileUploadModel;
@@ -50,7 +51,7 @@ use CodeIgniter\API\ResponseTrait;
use Illuminate\Http\Request;
use App\Controllers\EmployeeServiceController;
-
+use App\Models\ClaimFilesModel;
use Kreait\Firebase\Factory;
use Kreait\Firebase\Messaging\CloudMessage;
use Kreait\Firebase\Messaging\Notification;
@@ -87,6 +88,7 @@ class EmployeeRestController extends AdminController
protected $ticketController;
protected $hrAccessControlModel;
protected $insurerModel;
+ protected $hrFileUploadModel;
public function __construct()
@@ -118,6 +120,7 @@ class EmployeeRestController extends AdminController
$this->ticketController = new TicketController();
$this->hrAccessControlModel = new HRAccessControlModel();
$this->insurerModel = new InsurerModel();
+ $this->hrFileUploadModel = new HrFileUploadModel();
}
@@ -2619,9 +2622,38 @@ class EmployeeRestController extends AdminController
}
}
-
- return $this->respond(['status' => (count($data) ? 'success' : 'failed'),'code' => (count($data) ? 200 : 404),'data' => $data ], 200);
+ $ticketMesssageModel = new TicketMessageModel();
+ $ticket_message = $ticketMesssageModel
+ ->where('is_active', 1)
+ ->where('sender', "user")
+ ->where('ticket_id', $ticket_id)
+ ->orderBy('id', "desc")
+ ->first();
+
+ $claim_file_urls = [];
+
+ if (isset($ticket_message['id'])) {
+
+ $claimFiles = new ClaimFilesModel();
+ $claim_files_data = $claimFiles
+ ->select('id as claim_file_id, doc_name as claim_file_name')
+ ->where('is_active', 1)
+ ->where('file_type', 2)
+ ->where('ticket_id', $ticket_id)
+ ->where('ticket_message_id', $ticket_message['id'])
+ ->findAll();
+
+ foreach ($claim_files_data as &$value) {
+ $value['url'] = base_url('downloadClaimFile/') . $value['claim_file_id'];
+ $claim_file_urls[] = $value;
+ }
+ unset($value);
+ }
+
+ $data['claim_files'] = $claim_file_urls;
+
+ return $this->respond(['status' => (count($data) ? 'success' : 'failed'),'code' => (count($data) ? 200 : 404),'data' => $data, ], 200);
}
@@ -2817,18 +2849,29 @@ class EmployeeRestController extends AdminController
{
$policyGroup = 'gpa';
$data['ticket_type_id'] = 2;
+ $data['claim_subject'] = "Claim GPA";
+ $data['sum_insured_label'] = "Sum Assured";
+
}else if($ClientPolicyValue['policy_type_id'] == 6)
{
$policyGroup = 'gpa';
$data['ticket_type_id'] = 3;
+ $data['claim_subject'] = "Claim EDLI";
+ $data['sum_insured_label'] = "Sum Assured";
+
}else if($ClientPolicyValue['policy_type_id'] == 7)
{
$policyGroup = 'gpa';
$data['ticket_type_id'] = 4;
+ $data['claim_subject'] = "Claim GTLI";
+ $data['sum_insured_label'] = "Sum Assured";
+
}else
{
$policyGroup = 'gmc';
$data['ticket_type_id'] = 1;
+ $data['claim_subject'] = "Claim GMC";
+ $data['sum_insured_label'] = "Sum Insured";
}
$terms = json_decode($ClientPolicyValue['policy_terms'] , true);
@@ -3403,11 +3446,20 @@ class EmployeeRestController extends AdminController
{
$received_data = $this->request->getPost();
- // print_r($received_data); die;
+ $this->myLogger->logme('error', 'API claim initiate Recevied Params :' . json_encode($received_data ?? []));
+ $get_file_data = $this->request->getFiles('claim_docs');
+ // print_r($get_file_data); die;
$employee_id = $received_data['emp_id'];
$client_policy_id = $received_data['client_policy_id'];
$insured_emp_id = $received_data['insured_emp_id'];
+ $file_data = [];
+ if(isset($get_file_data) && !empty($get_file_data)){
+ $file_path = WRITEPATH . 'uploads/claim_files/';
+ $file_data = multi_file_Upload($get_file_data, $file_path);
+ }
+
+
if (empty($received_data['doa'])) {
$received_data['doa'] = null;
} else{
@@ -3500,11 +3552,14 @@ class EmployeeRestController extends AdminController
'mail_content' => $fetchData['message'] ?? "New Claim",
];
+ $ticket_message_id = null;
if (!empty($messagesData['ticket_id'])) {
$TicketMessageModel = new TicketMessageModel();
- $TicketMessageModel->insert($messagesData);
+ $ticket_message_id = $TicketMessageModel->insert($messagesData);
}
+ $this->handleCliamFiles($file_data, $ticket_id, $ticket_message_id);
+
$mail_sent_status = ($this->ticketController->sendAutoMailTrigger($ticket_id));
if (gettype($mail_sent_status) == 'array') {
$message = 'Claim Iniated Successfully';
@@ -3541,15 +3596,132 @@ class EmployeeRestController extends AdminController
}
}
+ public function handleCliamFiles($data, $ticket_id, $ticket_message_id)
+ {
+ if(!empty($data) && !empty($ticket_id))
+ {
+ $insert_ids = [];
+ $claim_file = new ClaimFilesModel();
+ foreach ($data as $key => $value) {
+
+ $data = [
+ 'ticket_id' => $ticket_id,
+ 'doc_name' => $value['file_name'],
+ 'url' => $value['file_path'],
+ 'file_type' => 2,
+ 'ticket_message_id' => $ticket_message_id,
+ ];
+
+ $insert_ids[] = $claim_file->insert($data);
+ }
+
+ return $insert_ids;
+ }
+
+ return [];
+ }
+
//department
+ // public function get_ticket_type()
+ // {
+ // $ticket_type = $this->ticketController->ticketType;
+ // $ticket_type = array_map(fn($value, $key) => (object) ['id' => $key, 'name' => $value], array_values($ticket_type), array_keys($ticket_type));
+ // // print_r($ticket_type); die;
+ // return $this->response->setJSON(['ticket_type' => $ticket_type])->setStatusCode(200);
+ // }
+
public function get_ticket_type()
{
- $ticket_type = $this->ticketController->ticketType;
- $ticket_type = array_map(fn($value, $key) => (object) ['id' => $key, 'name' => $value], array_values($ticket_type), array_keys($ticket_type));
- // print_r($ticket_type); die;
- return $this->response->setJSON(['ticket_type' => $ticket_type])->setStatusCode(200);
+ try {
+
+ $client_id = $this->request->getGet('client_id');
+ $emp_code = $this->request->getGet('emp_code');
+
+ if (empty($client_id) || empty($emp_code)) {
+
+ $this->myLogger->logme('error', "Missing required parameters: client_id={$client_id}, emp_code={$emp_code}");
+ // return $this->response->setJSON([
+ // 'status' => false,
+ // 'code' => 400,
+ // 'message' => 'client_id and emp_code are required'
+ // ])->setStatusCode(400);
+
+ $ticket_type = $this->ticketController->ticketType;
+ $ticket_type = array_map(fn($value, $key) => (object) ['id' => $key, 'name' => $value], array_values($ticket_type), array_keys($ticket_type));
+ return $this->response->setJSON(['ticket_type' => $ticket_type])->setStatusCode(200);
+ }
+
+ // Get policy type ids
+ $policy_type_ids = $this->employeePolicyModel
+ ->select('client_policy.policy_type_id')
+ ->join('employees', 'employee_polices.employee_id = employees.id')
+ ->join('client_policy', 'employee_polices.client_policy_id = client_policy.id')
+ ->where('employees.is_active', 1)
+ ->whereIn('employees.emp_status', ['active', 'expired'])
+ ->where('employee_polices.is_active', 1)
+ ->whereIn('employee_polices.status', ['active', 'expired'])
+ ->where('employees.client_id', $client_id)
+ ->where('employees.emp_code', $emp_code)
+ ->groupBy('employee_polices.client_policy_id')
+ ->findAll();
+
+ if (!$policy_type_ids) {
+ $this->myLogger->logme('error', "No policy types found for client_id={$client_id}, emp_code={$emp_code}");
+ return $this->response->setJSON([
+ 'status' => false,
+ 'code' => 404,
+ 'message' => 'No policy types found'
+ ])->setStatusCode(404);
+ }
+
+ $this->myLogger->logme('info', "Policy type IDs fetched: " . json_encode($policy_type_ids));
+
+ $ticket_type = $this->ticketController->ticketType;
+ $filtered = [];
+
+ $mapping = [
+ 2 => 1,
+ 3 => 1,
+ 4 => 1,
+ 5 => 1,
+ 1 => 2,
+ 6 => 3,
+ 7 => 4,
+ ];
+
+ foreach ($policy_type_ids as $value) {
+ $ticketTypeId = $value['policy_type_id'] ?? null;
+
+ if (isset($mapping[$ticketTypeId]) && isset($ticket_type[$mapping[$ticketTypeId]])) {
+ $mappedId = $mapping[$ticketTypeId];
+ $mappedName = $ticket_type[$mappedId];
+
+ // Use mappedId as key to avoid duplicates
+ $filtered[$mappedId] = [
+ 'id' => $mappedId,
+ 'name' => $mappedName
+ ];
+
+ $this->myLogger->logme('info', "Ticket type resolved: ID={$ticketTypeId}, Name={$mappedName}");
+ } else {
+ $this->myLogger->logme('warning', "No valid ticket type mapping for policy_type_id={$ticketTypeId}");
+ }
+ }
+
+ $filtered = array_values($filtered);
+ return $this->response->setJSON(['status' => true,'code' => 200, 'ticket_type' => $filtered ])->setStatusCode(200);
+
+ } catch (\Throwable $e) {
+ $this->myLogger->logme('error', "Error in get_ticket_type: " . $e->getMessage() . " Trace: " . $e->getTraceAsString());
+ return $this->response->setJSON([
+ 'status' => false,
+ 'code' => 500,
+ 'message' => 'Internal Server Error'
+ ])->setStatusCode(500);
+ }
}
+
//ticket data
public function get_ticket_data()
{
@@ -3563,6 +3735,10 @@ class EmployeeRestController extends AdminController
$emp_id = $this->request->getGet('emp_id');
$ticket_type = $this->request->getGet('ticket_type') ?? null;
$ticket_id = $this->request->getGet('ticket_id') ?? null;
+ $request = \Config\Services::request();
+ $uri = $request->uri->getPath();
+ $returnType = "";
+ // $returnType = (strpos($uri, 'api') !== false) ? 'api' : 'web';
// dd($emp_id);
if (empty($emp_id)) {
@@ -3570,7 +3746,7 @@ class EmployeeRestController extends AdminController
}
$TicketMasterModel = new TicketMasterModel();
- $ticket_data = $TicketMasterModel->get_ticket_data($emp_id, $ticket_type, $ticket_id);
+ $ticket_data = $TicketMasterModel->get_ticket_data($emp_id, $returnType, $ticket_type, $ticket_id);
if (!empty($ticket_data)) {
@@ -3586,6 +3762,7 @@ class EmployeeRestController extends AdminController
];
foreach ($ticket_data as $key => $value) {
+
foreach ($client_claim_status as $claim_key => $claim_value) {
if (in_array($value['claim_status_id'], $claim_value)) { // Corrected argument order
$ticket_data[$key]['claim_status'] = $claim_key ?? null; // Assign back to the main array
@@ -3600,6 +3777,29 @@ class EmployeeRestController extends AdminController
}
$ticket_data[$key]['claim_type_value'] = $claimType[$claimPrimaryTypey][$value['claim_type']] ?? null;
$ticket_data[$key]['ticket_policy_type'] = $ticketTypeArray[$value['ticket_type_id']] ?? null;
+
+ $claim_file_urls = [];
+
+ if (isset($value['ticket_message_id'])) {
+
+ $claimFiles = new ClaimFilesModel();
+ $claim_files_data = $claimFiles
+ ->select('id as claim_file_id, doc_name as claim_file_name')
+ ->where('is_active', 1)
+ ->where('file_type', 2)
+ ->where('ticket_id', $value['id'])
+ ->where('ticket_message_id', $value['ticket_message_id'])
+ ->findAll();
+
+ foreach ($claim_files_data as &$value) {
+ $value['url'] = base_url('downloadClaimFile/') . $value['claim_file_id'];
+ $claim_file_urls[] = $value;
+ }
+ unset($value);
+ }
+
+ // always set the key (empty if no files found)
+ $ticket_data[$key]['claim_files'] = $claim_file_urls;
}
}
@@ -3650,6 +3850,11 @@ class EmployeeRestController extends AdminController
], 200);
}
+ public function getClaimFiles()
+ {
+ $ticket_id = $this->request->getGet('ticket_id');
+ }
+
// public function getPreEmployeePolicyCount($mobile_no, $clientId = null)
// {
// log_message('error', 'getPreEmployeePolicyCount called with params : ' . json_encode(['mobile_no' => $mobile_no, 'client_id' => $clientId], true));
@@ -3781,4 +3986,272 @@ class EmployeeRestController extends AdminController
return $response->getBody();
}
+
+
+ //--------------------------------------------------------------------------------------------
+ public function hrFileUpload()
+ {
+ try {
+ // Check file
+ $file = $this->request->getFile('file_name');
+ if (!$file) {
+ return $this->response->setJSON([
+ 'status' => false,
+ 'message' => "Invalid file or file not uploaded.",
+ 'data' => "No Data"
+ ]);
+ }
+
+ // Upload folder path
+ $uploadPath = WRITEPATH . 'uploads/hr_files/';
+
+ // If directory not exists, create it
+ if (!is_dir($uploadPath)) {
+ mkdir($uploadPath, 0777, true);
+ }
+
+ // New file name with timestamp
+ $newFileName = time() . '_' . $file->getRandomName();
+
+ // Move file
+ $file->move($uploadPath, $newFileName);
+
+ // Prepare data
+ $data = [
+ 'client_id' => $this->request->getPost('client_id'),
+ 'client_branch_id' => $this->request->getPost('client_branch_id'),
+ 'policy_id' => $this->request->getPost('policy_id'),
+ 'policy_no' => $this->request->getPost('policy_no'),
+ 'file_name' => $newFileName,
+ 'file_action' => $this->request->getPost('file_action'),
+ 'status' => 'Yet to start',
+ 'created_by' => $this->request->getPost('created_by'),
+ 'updated_by' => $this->request->getPost('created_by'),
+ ];
+
+ // Save into DB
+ $this->hrFileUploadModel->insert($data);
+
+ return $this->respondCreated([
+ 'status' => true,
+ 'message' => 'File uploaded successfully',
+ 'data' => $data
+ ]);
+
+ } catch (\Exception $e) {
+ return $this->failServerError($e->getMessage());
+ }
+
+ }
+
+ public function updateHrFileUploadData()
+ {
+ try {
+ $id = $this->request->getPost('id');
+
+ if (!$id) {
+ return $this->failValidationErrors('ID is required for update.');
+ }
+
+ // Prepare data
+ $data = [
+ 'client_id' => $this->request->getPost('client_id'),
+ 'client_branch_id' => $this->request->getPost('client_branch_id'),
+ 'policy_id' => $this->request->getPost('policy_id'),
+ 'policy_no' => $this->request->getPost('policy_no'),
+ 'file_action' => $this->request->getPost('file_action'),
+ 'status' => $this->request->getPost('status'),
+ 'updated_by' => $this->request->getPost('updated_by'),
+ ];
+
+ // Check if record exists
+ $record = $this->hrFileUploadModel->find($id);
+ if (!$record) {
+ return $this->failNotFound("Record with ID {$id} not found.");
+ }
+
+ // Update record
+ $this->hrFileUploadModel->update($id, $data);
+
+ return $this->respond([
+ 'status' => true,
+ 'message' => 'File record updated successfully',
+ 'data' => $data
+ ], 200);
+
+ } catch (\Exception $e) {
+ return $this->failServerError($e->getMessage());
+ }
+ }
+
+
+ public function hrFileDownload($id = null)
+ {
+ try {
+
+ $file_id = $this->request->getGet('id') ?? $id;
+
+ // Find record
+ $record = $this->hrFileUploadModel->where('id',$file_id)->find();
+
+ // print_rr( $record);die;
+
+ if (!$record) {
+ return $this->failNotFound("File record not found");
+ }
+
+ $uploadPath = WRITEPATH . 'uploads/hr_files/';
+ $filePath = $uploadPath . $record[0]['file_name'];
+
+ if (!file_exists($filePath)) {
+ // return $this->failNotFound("File not found on server");
+ $data['message'] = 'The Physical File Not Found';
+ return view('errors/404', $data);
+ }
+
+ // Force file download
+ return $this->response->download($filePath, null)
+ ->setFileName($record[0]['file_name']);
+ } catch (\Exception $e) {
+ return $this->failServerError($e->getMessage());
+ }
+ }
+
+ // public function hrFileList()
+ // {
+ // try {
+ // $request = service('request');
+ // $builder = $this->hrFileUploadModel
+ // ->select('hr_file_upload.* , c.short_name , cb.branch_name , lc.name as first_name ');
+
+ // // Allowed filter keys
+ // $filters = [
+ // 'client_id',
+ // 'client_branch_id',
+ // 'policy_no',
+ // 'file_action',
+ // 'status',
+ // 'created_by'
+ // ];
+
+ // // Apply filters dynamically
+ // foreach ($filters as $key) {
+ // $value = $request->getGetPost($key); // supports both GET and POST
+ // if (!empty($value)) {
+ // $builder->where($key, $value);
+ // }
+ // }
+
+ // // Fetch results
+ // $builder->join('clients c', 'c.id = hr_file_upload.client_id AND c.is_active = 1', 'left');
+ // $builder->join('client_branch cb', 'cb.id = hr_file_upload.client_branch_id AND cb.is_active = 1', 'left');
+ // $builder->join('level_contacts lc', 'lc.id = hr_file_upload.created_by AND lc.contact_type = "client" AND lc.is_active = 1', 'left');
+ // $data = $builder->findAll();
+
+ // return $this->respond([
+ // 'status' => true,
+ // 'message' => 'File list fetched successfully',
+ // 'data' => $data
+ // ]);
+ // } catch (\Exception $e) {
+ // return $this->failServerError($e->getMessage());
+ // }
+ // }
+
+ public function hrFileList()
+ {
+ try {
+ $request = service('request');
+
+ // Start builder from model
+ // $builder = $this->hrFileUploadModel
+ // ->select('hr_file_upload.* , c.short_name , cb.branch_name , lc.name as first_name')
+ // ->join('clients c', 'c.id = hr_file_upload.client_id AND c.is_active = 1', 'left')
+ // ->join('client_branch cb', 'cb.id = hr_file_upload.client_branch_id AND cb.is_active = 1', 'left')
+ // ->join('level_contacts lc', 'lc.id = hr_file_upload.created_by AND lc.contact_type = "client" AND lc.is_active = 1', 'left');
+
+ $builder = $this->hrFileUploadModel
+ ->select('
+ hr_file_upload.id,
+ hr_file_upload.client_id,
+ hr_file_upload.client_branch_id,
+ hr_file_upload.policy_id,
+ hr_file_upload.policy_no,
+ hr_file_upload.file_name,
+ hr_file_upload.file_action,
+ hr_file_upload.created_at,
+ hr_file_upload.created_by,
+ hr_file_upload.updated_at,
+ hr_file_upload.updated_by,
+ c.short_name,
+ cb.branch_name,
+ lc.name as first_name,
+ CASE
+ WHEN f.status IS NULL
+ THEN hr_file_upload.status
+ ELSE CONCAT(UCASE(LEFT(f.status, 1)), LCASE(SUBSTRING(f.status, 2)))
+ END AS status
+ ', false)
+ ->join('clients c', 'c.id = hr_file_upload.client_id AND c.is_active = 1', 'left')
+ ->join('client_branch cb', 'cb.id = hr_file_upload.client_branch_id AND cb.is_active = 1', 'left')
+ ->join('level_contacts lc', 'lc.id = hr_file_upload.created_by AND lc.contact_type = "client" AND lc.is_active = 1', 'left')
+ ->join(
+ '(SELECT f1.*
+ FROM files f1
+ WHERE f1.is_active = 1
+ ORDER BY f1.id DESC
+ LIMIT 1) f',
+ 'f.hr_file_id = hr_file_upload.id',
+ 'left'
+ );
+
+ // Allowed filter keys
+ $filters = [
+ 'client_id',
+ 'client_branch_id',
+ 'policy_id',
+ 'policy_no',
+ 'file_action',
+ 'status',
+ 'created_by'
+ ];
+
+ // Apply filters dynamically
+ foreach ($filters as $key) {
+ $value = $request->getGetPost($key); // supports both GET and POST
+ if (!empty($value)) {
+ $builder->where("hr_file_upload.$key", $value);
+ }
+ }
+
+ // Execute query
+ $data = $builder->get()->getResultArray();
+
+ return $this->respond([
+ 'status' => "success",
+ 'message' => 'File list fetched successfully',
+ 'data' => $data
+ ]);
+ } catch (\Exception $e) {
+ return $this->failServerError($e->getMessage());
+ }
+ }
+
+
+ public function hrFileUploadMasters()
+ {
+ try {
+ //for inception upload
+ $data['actions'] = ['addition' => 'Addition (Employee + Dependents)', 'missed_inception' => 'Missed Inception (Employee + Dependents)', 'dependent_addition' => 'Dependent Addition (Only Dependents)', 'deletion' => 'Deletion', 'correction' => 'Correction', 'si_enhancement' => 'SI Enhancement'];
+
+ return $this->respond([
+ 'status' => true,
+ 'message' => 'File inception upload masters',
+ 'data' => $data
+ ]);
+ } catch (\Exception $e) {
+ return $this->failServerError($e->getMessage());
+ }
+ }
+
}
\ No newline at end of file
diff --git a/app/Controllers/EmployeeServiceController.php b/app/Controllers/EmployeeServiceController.php
index 2cc47520..a80ec116 100755
--- a/app/Controllers/EmployeeServiceController.php
+++ b/app/Controllers/EmployeeServiceController.php
@@ -1702,6 +1702,15 @@ class EmployeeServiceController extends AdminController
$value['relationship'] = ucfirst(trim($value['relationship']));
if(count($employee))
{
+ if (isset($employee[0]['email_corporate']) && $employee[0]['email_corporate'] != '')
+ {
+ unset($value['email_corporate']);
+ }
+
+ if (isset($employee[0]['mobile']) && $employee[0]['mobile'] != '')
+ {
+ unset($value['mobile']);
+ }
$value['updated_by'] = $file['created_by'];
$value['id'] = $employee[0]['id'];
$value['emp_status'] = 'active';
diff --git a/app/Controllers/Home.php b/app/Controllers/Home.php
index 03878326..68eb0402 100755
--- a/app/Controllers/Home.php
+++ b/app/Controllers/Home.php
@@ -309,7 +309,7 @@ public function convertToPdf($inputFile = null)
{
// Customize this based on your needs
$html = '' . htmlspecialchars($worksheet->getTitle()) . ' ';
- $html .= ' ';
+ $html .= '';
foreach ($worksheet->getRowIterator() as $row) {
$html .= '';
diff --git a/app/Controllers/JobWorker.php b/app/Controllers/JobWorker.php
index 4cbf5350..1f322c84 100755
--- a/app/Controllers/JobWorker.php
+++ b/app/Controllers/JobWorker.php
@@ -143,6 +143,30 @@ class JobWorker extends AdminController
'type' => 'CC', // Handler Category
'handler' => 'App\Controllers\ClientController',
],
+ 'claimDumpExcelFileFormatValidation' => [
+ 'type' => 'CC', // Handler Category
+ 'handler' => 'App\Controllers\TicketServiceController',
+ ],
+ 'claimDumpExcelFileDataValidation' => [
+ 'type' => 'CC', // Handler Category
+ 'handler' => 'App\Controllers\TicketServiceController',
+ ],
+ 'claimDumpOnBoardProcess' => [
+ 'type' => 'CC', // Handler Category
+ 'handler' => 'App\Controllers\TicketServiceController',
+ ],
+ 'excelMultieventFileFormateValidation' => [
+ 'type' => 'CC', // Handler Category
+ 'handler' => 'App\Controllers\EmployeeMultiEventServiceController',
+ ],
+ 'excelMultieventFileDataValidation' => [
+ 'type' => 'CC', // Handler Category
+ 'handler' => 'App\Controllers\EmployeeMultiEventServiceController',
+ ],
+ 'excelMultieventFileOnBoard' => [
+ 'type' => 'CC', // Handler Category
+ 'handler' => 'App\Controllers\EmployeeMultiEventServiceController',
+ ],
];
diff --git a/app/Controllers/LeadsController.php b/app/Controllers/LeadsController.php
index fc4a4e86..d5f8ea12 100644
--- a/app/Controllers/LeadsController.php
+++ b/app/Controllers/LeadsController.php
@@ -31,6 +31,7 @@ use App\Models\InsurerModel;
use App\Models\OccupancyMasterModel;
use App\Models\LeadFilesModel;
use App\Models\LeadInstallmentPaymentDetails;
+use App\Models\GmailSentHistoryModel;
use App\Helpers\MailHelper;
use App\Helpers\ExcelMergeHelper;
@@ -70,6 +71,7 @@ class LeadsController extends BaseController
protected $occupancyModel;
protected $leadFilesModel;
protected $leadInstallmentPaymentDetails;
+ protected $gmailSentHistoryModel;
//variables for storing array
protected $issuer;
@@ -102,6 +104,7 @@ class LeadsController extends BaseController
$this->occupancyModel = new OccupancyMasterModel();
$this->leadFilesModel = new LeadFilesModel();
$this->leadInstallmentPaymentDetails = new LeadInstallmentPaymentDetails();
+ $this->gmailSentHistoryModel = new GmailSentHistoryModel();
$this->issuer = [1 => 'JIBS', 2 => 'Nhance'];
$this->clientType = [1 => 'Group', 2 => 'Individual'];
@@ -383,6 +386,20 @@ class LeadsController extends BaseController
$data['source_policy_end_date'] = null;
}
+ //convert the date
+ if (!empty($data['next_reminder_date'])) {
+ $data['next_reminder_date'] = change_date_format($data['next_reminder_date']);
+ } else {
+ $data['next_reminder_date'] = null;
+ }
+
+ //convert 0 and 1
+ if (isset($data['is_insurer_auto_mail'])) {
+ $data['is_insurer_auto_mail'] = 1;
+ } else {
+ $data['is_insurer_auto_mail'] = 0;
+ }
+
// $file_name = file_Upload($files[$index], $uploadFilePath);
$last_3_years_claims = $data['finyear'];
@@ -459,9 +476,12 @@ class LeadsController extends BaseController
'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'] ?? 0,
+ 'is_insurer_auto_mail' => $data['is_insurer_auto_mail'] ?? 0
];
}
// print_r($processedData);die();
@@ -856,21 +876,40 @@ class LeadsController extends BaseController
$qcr_created = true;
}
- if (($data['submit_type'] ?? "") == 'QCR') {
+ $quote_received_insurer = [];
+ if (($data['submit_type'] ?? "") === 'QCR') {
+
$inputJson = json_decode($data['json'], true);
- $proposal_data = array_pop($inputJson);
- if (isset($proposal_data['proposal_data']['over_all_column_data'])) {
- $proposel_count = $proposal_data['proposal_data']['over_all_column_data'];
+ $proposal_data = $inputJson['proposal_data'] ?? array_pop($inputJson);
+
+ if (isset($proposal_data['over_all_column_data'])) {
+ $proposel_count = $proposal_data['over_all_column_data'];
+
+ $this->myLogger->logme("error", "insurer id : " . json_encode($proposel_count));
+
foreach ($proposel_count as $key => $value) {
if (!empty($value['insurers'])) {
$qcr_created = true;
+
+ foreach ($value['insurers'] as $insurer => $id) {
+ if (!empty($id['id'])) {
+ $quote_received_insurer[] = $id['id'];
+ }
+ }
}
}
}
}
+ $this->myLogger->logme("error", "quote_received_insurer : " . json_encode($quote_received_insurer));
$data['type'] = 1;
+ //update the quote received insurer data to the lead
+ 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'])) {
$this->RFQModel
@@ -2552,6 +2591,21 @@ class LeadsController extends BaseController
$from_mail = "bs@nhanceindia.in";
}
+ $type = "";
+ $insurer_ids = null;
+ if (in_array($recipient_type, ['placement'])) {
+ $type = "placement";
+ } else if (in_array($recipient_type, ['insurer'])) {
+ $type = "insurer";
+ $insurer_ids = json_decode($params['insurer_ids'] ?? "", true) ?? [];
+ }else if (in_array($recipient_type, ['internal'])) {
+ $type = "internal";
+ }else if (in_array($recipient_type, ['client'])) {
+ $type = "client";
+ }
+
+ // print_r($insurer_ids); die;
+
if ($recipient_type === 'placement') {
$lead_data = $this->leadsModel->find($lead_id);
@@ -2733,7 +2787,7 @@ class LeadsController extends BaseController
$subject = $file_type == 'rfq' ? 'Request for Quotation from ' . $lead_data['client_name'] . ' for ' . $lead_data['policy_type'] : 'Quotation Comparison Report for ' . $lead_data['policy_type'];
- $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.
';
+ $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)) {
@@ -2746,10 +2800,14 @@ class LeadsController extends BaseController
}
// print_r($subject); die;
-
+ $common = ['module' => "leads", 'pk' => $lead_id, 'mail_type' => $type, 'common' => null];
if ($recipient_data) {
- foreach ($recipient_data as $recipient) {
+ foreach ($recipient_data as $position => $recipient) {
+ 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);
@@ -2761,7 +2819,7 @@ class LeadsController extends BaseController
$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]);
+ $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]);
// !dd($res);
$result_data[] = ['mail' => $recipient['email'], 'status' => $res];
}
@@ -3539,10 +3597,11 @@ 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);
- $message = str_replace("{{LOGO_PATH}}", $log_path, $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);
+ $message = str_replace("{{LOGO_PATH}}", $log_path ?? "", $message);
return $message;
} else {
@@ -3627,7 +3686,7 @@ class LeadsController extends BaseController
}
if (!empty($data['lead_edit_data'])) {
- foreach (['policy_start_date', 'policy_end_date', 'source_policy_start_date', 'source_policy_end_date', 'incurred_claims_date'] as $dateField) {
+ 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])
? change_date_format($data['lead_edit_data'][$dateField], 'Y-m-d', 'd/m/Y')
: null;
@@ -3657,6 +3716,28 @@ 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);
+ }
+
+
+ // Select * from gmail_sent_history where pk != "" and module = "leads";
+ // echo $id;
+ }
+
public function getPolicyTypeFields()
{
@@ -4866,7 +4947,7 @@ class LeadsController extends BaseController
// Start table with clean styling
$html .= "{$category} ";
- $html .= "";
+ $html .= "";
// Table header with light background
$html .= "";
@@ -4893,4 +4974,197 @@ class LeadsController extends BaseController
return $html;
}
+
+ // function for insurer remainder mail cron job
+ public function remainderForQcr()
+ {
+ $lead_data = $this->leadsModel
+ ->select(
+ 'leads.*,
+ user_profiles.email as created_person_email,
+ policy_type.policy_type,
+ policy_type.long_name
+ ')
+ ->join('policy_type', 'leads.policy_type_id = policy_type.id')
+ ->join('user_profiles', 'leads.created_by = user_profiles.id', 'left')
+ ->where('leads.is_active', 1)
+ ->where('user_profiles.is_active', 1)
+ ->whereIn('leads.status', ['rfq_sent', 'qcr_created'])
+ ->where('leads.next_reminder_date', date('Y-m-d'))
+ ->findAll();
+
+ // dd($lead_data);
+
+ if (count($lead_data) == 0) {
+ $this->myLogger->logme("info", "No leads found for reminder mail at " . date('Y-m-d H:i:s'));
+ print_r(["status" => true, "message" => "There is no data to send reminder mail"]);
+ return ["status" => true, "message" => "There is no data to send reminder mail"];
+
+ }
+
+ $from_mail = "im@nhanceindia.in";
+ $subject = "Reminder for RFQ";
+ $content_string = '
+ Dear Sir,
+ Greetings from Nhance India!
+ This is a gentle reminder regarding our earlier mail about the RFQ for the {{POLICY_TYPE}} policy pertaining to {{CLIENT_NAME}} .
+ We kindly request you to share the competitive quotes at the earliest possible convenience.
+ In case of any clarification, please feel free to contact us.
+ Thank you for your prompt attention to this matter.
+ Best regards,
+ Nhance India
+ ';
+
+ $reminder_sended_lead = [];
+
+ foreach ($lead_data as $lead) {
+
+ $leadId = $lead['id'];
+ $reply_to = $lead['created_person_email'] ?? "";
+
+ if (isset($lead['policy_end_date']) && $lead['policy_end_date'] != null) {
+ $subject = "{{CLIENT_NAME}} _ {{POLICY_TYPE}} _ {{RFQ_OR_QCR}} _ {{POLICY_YEAR}} {{POLICY_END_DATE}}";
+ } else {
+ $subject = "{{CLIENT_NAME}} _ {{POLICY_TYPE}} _ {{RFQ_OR_QCR}} _ {{POLICY_YEAR}}";
+ }
+
+ $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
+ $sales_person_emails = $this->userModel
+ ->select('email')
+ ->where('is_active', 1)
+ ->whereIn('id', json_decode($lead['salse_person_id'] ?? "[]", true))
+ ->findAll();
+
+ $email_list = array_column($sales_person_emails, 'email');
+ if (!empty($reply_to)) {
+ $email_list[] = $reply_to;
+ }
+ $email_list = array_filter(array_unique($email_list));
+ $email_string = implode(',', $email_list);
+
+ // Get latest sent mail timestamp
+ $createdAtRow = $this->gmailSentHistoryModel
+ ->select("DATE_FORMAT(created_at, '%Y-%m-%d %H:%i') as created_at", false)
+ ->where('isactive', 1)
+ ->where('mail_type', 'insurer')
+ ->where('pk', $leadId)
+ ->orderBy('id', 'desc')
+ ->first();
+ // dd(db_connect()->getLastQuery(), $createdAtRow);
+
+ if (!$createdAtRow) {
+ $this->myLogger->logme("warning", "No sent history found for lead_id={$leadId}, skipping...");
+ continue;
+ }
+
+ $createdAt = $createdAtRow['created_at'];
+
+ // Fetch mail data for that timestamp
+ $mail_datas = $this->gmailSentHistoryModel
+ ->where('isactive', 1)
+ ->where('mail_type', "insurer")
+ ->where('pk', $leadId)
+ ->where("DATE_FORMAT(created_at, '%Y-%m-%d %H:%i')", $createdAt)
+ ->findAll();
+
+ if (empty($mail_datas)) {
+ $this->myLogger->logme("warning", "No mail data found for lead_id={$leadId} at created_at={$createdAt}");
+ continue;
+ }
+
+ // Filter only pending insurers
+ $quote_received_insurer = json_decode($lead['quote_received_insurer'] ?? "[]", true);
+ $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)) {
+ $reminder_mail_data[] = $mail_value;
+ }
+ }
+ }
+
+ // dd($reminder_mail_data);
+ if (empty($reminder_mail_data)) {
+ $this->myLogger->logme("info", "All insurers already responded for lead_id={$leadId}, no reminder needed");
+ continue;
+ }
+
+ $this->myLogger->logme("info", "Sending " . count($reminder_mail_data) . " reminder mail(s) for lead_id={$leadId}");
+
+ $common = ['module' => "leads", 'pk' => $leadId, 'mail_type' => "remainder", 'common' => null];
+
+ foreach ($reminder_mail_data as $content) {
+ $insurerId = $content['common'] ?? null;
+ $common['common'] = $insurerId;
+
+ try {
+
+ if ($lead['is_insurer_auto_mail'] == 1) {
+ // send reminder to insurer
+ $res = MailHelper::send_email([
+ 'from_mail' => $from_mail,
+ 'mail' => $content['mail'] ?? "",
+ 'cc' => json_decode($content['cc'] ?? "", true) ?? "",
+ 'subject' => $mail_subject ?? "",
+ 'message' => $mail_content ?? "",
+ 'reply_to' => $reply_to,
+ 'bcc' => json_decode($content["bcc"] ?? "", true) ?? "",
+ '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
+ ];
+ } else{
+ $this->myLogger->logme("info", "Reminder mail disable for this lead_id={$leadId}");
+ }
+
+
+ } catch (\Throwable $e) {
+ $errorDetails = [
+ 'error_message' => $e->getMessage(),
+ 'file' => $e->getFile(),
+ 'line' => $e->getLine(),
+ 'stack_trace' => $e->getTraceAsString(),
+ ];
+ $this->myLogger->logme("error", "Exception while sending reminder | lead_id={$leadId}, insurer_id={$insurerId}, error=" . json_encode($errorDetails));
+ $reminder_sended_lead[] = [
+ 'lead_id' => $leadId,
+ 'insurer_id' => $insurerId,
+ '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
+ ]);
+
+ $this->myLogger->logme("info", "Reminder mail sent to sales persons | lead_id={$leadId}, recipients={$email_string}, response=" . json_encode($internal_mail_response));
+
+
+ }
+ }
+
+ return ['status' => true, "data" => $reminder_sended_lead];
+ }
+
+
}
diff --git a/app/Controllers/MasterController.php b/app/Controllers/MasterController.php
index 61c5aedf..60d3b955 100755
--- a/app/Controllers/MasterController.php
+++ b/app/Controllers/MasterController.php
@@ -1798,7 +1798,7 @@ class MasterController extends AdminController
$email_id = CLI::getOption('to') ? CLI::getOption('to') : $email_id;
// print_r($email_id);die();
// $gmailapi = \Config\Services::gmailapi();
- $message = '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
';
+ $message = '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
';
// $attachments = [
// ["filePath" => WRITEPATH."uploads/excel/sample/correction.xls","fileName" => "correction.xls"],
@@ -1821,7 +1821,7 @@ class MasterController extends AdminController
public function testZeptoSMTP()
{
- $message = '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
';
+ $message = '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
';
$attachments = [
["filePath" => ROOTPATH . "public/sample_excel/sample_addition.xls", "fileName" => "sample_addition.xls"],
["filePath" => ROOTPATH . "public/sample_excel/sample_inception.xls", "fileName" => "sample_inception.xls"],
@@ -1894,6 +1894,8 @@ class MasterController extends AdminController
'cache' => WRITEPATH . 'cache',
'sample_import_excel' => ROOTPATH . 'public/sample_import_excel',
'lead_files' => WRITEPATH . 'uploads/lead_files/',
+ 'claim_files' => WRITEPATH . 'uploads/claim_files/',
+ 'claim_dump_excel' => WRITEPATH . 'uploads/claim_dump_excel/',
'claim_sample_forms' => ROOTPATH . 'public/claim_sample_forms/',
];
@@ -1973,7 +1975,7 @@ class MasterController extends AdminController
public function sendMutipleToEmails()
{
- $message = '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
';
+ $message = '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
';
$attachments = [
["filePath" => ROOTPATH . "public/sample_excel/sample_addition.xls", "fileName" => "sample_addition.xls"],
["filePath" => ROOTPATH . "public/sample_excel/sample_inception.xls", "fileName" => "sample_inception.xls"],
diff --git a/app/Controllers/NotificationController.php b/app/Controllers/NotificationController.php
index efdc2571..b497e958 100755
--- a/app/Controllers/NotificationController.php
+++ b/app/Controllers/NotificationController.php
@@ -87,6 +87,8 @@ class NotificationController extends AdminController
'client_hr_summary_mail_btn'
];
$data = [];
+ $emptyTemplate = [];
+ $updatedTemplate = [];
foreach ($checkboxNames as $checkboxName)
{
@@ -111,9 +113,31 @@ class NotificationController extends AdminController
$id = $find['id'];
$changeData['enabled']= $value;
$update = $notificationModel->update($id, $changeData);
+ $updatedTemplate [] = $key;
+ }
+
+ if(!$find && $value == 1){
+ $emptyTemplate [] = $key;
}
}
- return json_encode("true");
+
+ if(count($emptyTemplate) > 0){
+ return $this->response->setJSON([
+ 'status' => false,
+ 'code' => 400,
+ 'message' => 'Notification settings updation Failed.',
+ 'updated_templates' => $updatedTemplate,
+ 'empty_templates' => $emptyTemplate
+ ]);
+ }
+
+ return $this->response->setJSON([
+ 'status' => true,
+ 'code' => 200,
+ 'message' => 'Notification settings updated successfully.',
+ 'updated_templates' => $updatedTemplate,
+ 'empty_templates' => $emptyTemplate
+ ]);
}
// This for Load the Template Data for in View Page
diff --git a/app/Controllers/PolicyTransactionController.php b/app/Controllers/PolicyTransactionController.php
index d6bc5167..2b9afb78 100644
--- a/app/Controllers/PolicyTransactionController.php
+++ b/app/Controllers/PolicyTransactionController.php
@@ -248,12 +248,14 @@ class PolicyTransactionController extends BaseController
// policy Transaction Create function start
public function createInceptionPolicy()
- {
- // print_r($this->request->getPost()); die;
+ {
+ $post_data = $this->request->getPost() ?? [];
+ $this->myLogger->logme('error', 'Policy Trancaction form data : '. json_encode($post_data));
+
$id = $this->request->getPost('id');
$data = $this->preparePolicyData();
$data['cd_ac_pk'] = $this->request->getPost('cd_ac_no');
- // print_r($this->request->getPost()); die;
+ $this->myLogger->logme('error', 'Policy Trancaction modified form data ( insert data ) : '. json_encode($data));
if (!$id) {
@@ -381,7 +383,12 @@ class PolicyTransactionController extends BaseController
}
$client_data = $this->clientModel->where('id', $data['client_id'])->first();
- $data['client_kyc'] = $this->clientKYCDocsModel->where('client_id', $data['client_id'])->findAll();
+ $data['client_kyc'] = $this->clientKYCDocsModel->where('client_id', $data['client_id'])->findAll();
+
+ $clientController = new ClientController();
+ $data['client_kyc_primary_table'] = $clientController->generateKycPrimaryTable($data['client_id']);
+ $data['client_kyc_other_table'] = $clientController->generateKycOthersTable($data['client_id']);
+
$data['entity_type_id'] = $client_data['entity_type_id'];
return $this->respondSuccess($insert, "Policy transaction created successfully", $data);
@@ -431,6 +438,11 @@ class PolicyTransactionController extends BaseController
$client_data = $this->clientModel->where('id', $data['client_id'])->first();
$data['client_kyc'] = $this->clientKYCDocsModel->where('client_id', $data['client_id'])->findAll();
+
+ $clientController = new ClientController();
+ $data['client_kyc_primary_table'] = $clientController->generateKycPrimaryTable($data['client_id']);
+ $data['client_kyc_other_table'] = $clientController->generateKycOthersTable($data['client_id']);
+
$data['entity_type_id'] = $client_data['entity_type_id'];
return $this->respondSuccess($id, "Policy transaction updated successfully", $data);
@@ -975,7 +987,12 @@ class PolicyTransactionController extends BaseController
->join('employee_polices', 'employees.id = employee_polices.employee_id', 'left')
->where('employees.client_id', $data['client_id'])
->where('employees.is_active', 1)->findAll();
- $data['client_kyc'] = $this->clientKYCDocsModel->where('client_id', $data['client_id'])->findAll();
+ // $data['client_kyc'] = $this->clientKYCDocsModel->where('client_id', $data['client_id'])->findAll();
+
+ $clientController = new ClientController();
+ $data['client_kyc_primary_table'] = $clientController->generateKycPrimaryTable($data['client_id']);
+ $data['client_kyc_other_table'] = $clientController->generateKycOthersTable($data['client_id']);
+
$data['vehicle_docs'] = $this->clientKYCDocsModel
->where('client_id', $data['client_id'])
->where('vehicle_id', $data['vehicle_id'])
@@ -995,8 +1012,16 @@ class PolicyTransactionController extends BaseController
if ($id) {
$data['is_active'] = 0;
- $this->policyTransactionModel->where('id', $id)->set($data)->update();
- $this->PTCOShareDetailsModel->where('pt_id', $id)->set($data)->update();
+ $policy_transaction_data = $this->policyTransactionModel->where('id', $id)->first();
+ if($policy_transaction_data['policy_type_id'] > 7){
+ $this->policyTransactionModel->where('id', $id)->set($data)->update();
+ $this->PTCOShareDetailsModel->where('pt_id', $id)->set($data)->update();
+ $this->clientPolicyModel->where('id', $policy_transaction_data['client_policy_id'])->set($data)->update();
+ $this->policyTransactionModel->where('client_policy_id', $policy_transaction_data['client_policy_id'])->set($data)->update();
+ }else{
+ $this->policyTransactionModel->where('id', $id)->set($data)->update();
+ $this->PTCOShareDetailsModel->where('pt_id', $id)->set($data)->update();
+ }
return $this->respond(['status' => true, 'code' => 200, 'message' => 'Policy Transaction removed successfully'], 200);
} else {
diff --git a/app/Controllers/TestingController.php b/app/Controllers/TestingController.php
new file mode 100644
index 00000000..d866cb7f
--- /dev/null
+++ b/app/Controllers/TestingController.php
@@ -0,0 +1,239 @@
+myLogger = \Config\Services::mylogger();
+ }
+
+ public function saveForm()
+ {
+ // Get JSON input
+ $data = $this->request->getPost();
+
+ // For testing: just return the received data
+ return $this->respond([
+ 'status' => 'success',
+ 'message' => 'Form data received successfully!',
+ 'data' => $data
+ ]);
+ }
+
+ public function testcli()
+ {
+ echo "hi";
+ $this->myLogger->logme('error', "test log");
+ echo "hi 2";
+ log_message('error', 'test message for log_message_function');
+ echo "hi 3";
+ }
+
+
+ public function generatePDF()
+ {
+ // Sample data - replace with your actual data source
+ $data = [
+ 'NAME' => 'John Doe',
+ 'GENDER' => 'Male',
+ 'DOB' => '01/01/1990',
+ 'RELATION' => 'Self',
+ 'POLICY_NO' => 'POL123456789',
+ 'TPA_ID' => 'TPA987654321',
+ 'POLICY_START_DATE' => '01/01/2024',
+ 'POLICY_DATE' => '31/12/2024',
+ 'INSURER_NAME' => 'ABC Insurance Co.',
+ 'TPA_NAME' => 'XYZ TPA Ltd.',
+ 'FRONT_CARD' => base_url('assets/images/front-card.jpg'), // Your card images
+ 'BACK_CARD' => base_url('assets/images/back-card.jpg'),
+ 'LEVELS' => 'Level 1: 1800-XXX-XXXX Level 2: support@company.com'
+ ];
+
+ // Load the HTML template
+ $html = $this->loadTemplate($data);
+
+ // Configure DomPDF options
+ $options = new Options();
+ $options->set('isRemoteEnabled', true); // Enable loading of remote images
+ $options->set('isHtml5ParserEnabled', true);
+ $options->set('isPhpEnabled', true);
+ $options->set('debugPng', false);
+ $options->set('debugKeepTemp', false);
+ $options->set('debugCss', false);
+ $options->set('debugLayout', false);
+ $options->set('debugLayoutLines', false);
+ $options->set('debugLayoutBlocks', false);
+ $options->set('debugLayoutInline', false);
+ $options->set('debugLayoutPaddingBox', false);
+
+ // Initialize DomPDF
+ $dompdf = new Dompdf($options);
+
+ // Load HTML content
+ $dompdf->loadHtml($html);
+
+ // Set paper size and orientation
+ $dompdf->setPaper('A4', 'landscape'); // or 'portrait'
+
+ // Render PDF
+ $dompdf->render();
+
+ // Output PDF to browser
+ $filename = 'ecard_' . date('Y-m-d_H-i-s') . '.pdf';
+ $dompdf->stream($filename, ['Attachment' => true]); // Set to false for inline view
+ }
+
+ public function viewPDF()
+ {
+ // Same as generatePDF but with inline view
+ $data = [
+ 'NAME' => 'Korukonda Naga Venkata Ramalinga Satya Swarna Kumari',
+ 'GENDER' => 'Male',
+ 'DOB' => '01/01/1990',
+ 'RELATION' => 'Self',
+ 'POLICY_NO' => '97000034230400000109_EX_Parental',
+ 'TPA_ID' => 'TPA987654321',
+ 'POLICY_START_DATE' => '01/01/2024',
+ 'POLICY_DATE' => '31/12/2024',
+ 'INSURER_NAME' => 'ZURICH KOTAK GTNERAL INSURANCE COIIPANY lNDlA LIMITED',
+ 'TPA_NAME' => 'HealthIndia Insurance TPA Services Pvt. Ltd.',
+ 'FRONT_CARD' => base_url() .('public/uploads/template_bg/Nhance_Ecard_working_1_front_3.png'),
+ 'BACK_CARD' => base_url() . ('public/uploads/template_bg/Nhance_Ecard_working_1_Back_3.png'),
+ 'LEVELS' => 'Level 1: 1800-XXX-XXXX Level 2: support@company.com'
+ ];
+
+ $data2 = [
+ 'NAME' => 'John Doe',
+ 'GENDER' => 'Male',
+ 'DOB' => '01/01/1990',
+ 'RELATION' => 'Self',
+ 'POLICY_NO' => 'POL123456789',
+ 'TPA_ID' => 'TPA987654321',
+ 'POLICY_START_DATE' => '01/01/2024',
+ 'POLICY_DATE' => '31/12/2024',
+ 'INSURER_NAME' => 'ABC Insurance Co.',
+ 'TPA_NAME' => 'XYZ TPA Ltd.',
+ 'FRONT_CARD' => base_url() .('public/uploads/template_bg/Nhance_Ecard_working_1_front_3.png'),
+ 'BACK_CARD' => base_url() . ('public/uploads/template_bg/Nhance_Ecard_working_1_Back_3.png'),
+ 'LEVELS' => 'Level 1: 1800-XXX-XXXX Level 2: support@company.com'
+ ];
+
+ $employeeController = new EmployeeController();
+ // $html = $employeeController->generateIDCardForEmployeeUsingDom('LfpH3R');
+ $html = $this->loadTemplate($data2);
+ // print_r($html); die;
+ $options = new Options();
+ $options->set('isRemoteEnabled', true);
+ $options->set('isHtml5ParserEnabled', true);
+
+ $dompdf = new Dompdf($options);
+ // $dompdf->loadHtml($html);
+ $dompdf->loadHtml('' . $html);
+ $dompdf->setPaper('A4', 'portrait');
+ // $dompdf->setPaper('A4', 'landscape');
+ $dompdf->render();
+
+ $filename = 'ecard_' . date('Y-m-d_H-i-s') . '.pdf';
+ // $dompdf->stream($filename, ['Attachment' => true]); // Inline view
+ $dompdf->stream($filename, ['Attachment' => false]); // Force download
+
+ }
+
+ private function loadTemplate($data)
+ {
+ // Load your HTML template
+ $template = file_get_contents(WRITEPATH . 'e_card_template/common.html');
+
+ // Replace placeholders with actual data
+ foreach ($data as $key => $value) {
+ $template = str_replace('{' . $key . '}', $value, $template);
+ }
+
+ return $template;
+ }
+
+ // not using and not working
+ public function viewPdfUsingMpdf()
+ {
+ $data = [
+ 'NAME' => 'Korukonda Naga Venkata Ramalinga Satya Swarna Kumari',
+ 'GENDER' => 'Male',
+ 'DOB' => '01/01/1990',
+ 'RELATION' => 'Self',
+ 'POLICY_NO' => '97000034230400000109_EX_Parental',
+ 'TPA_ID' => 'TPA987654321',
+ 'POLICY_START_DATE' => '01/01/2024',
+ 'POLICY_DATE' => '31/12/2024',
+ 'INSURER_NAME' => 'ZURICH KOTAK GTNERAL INSURANCE COIIPANY lNDlA LIMITED',
+ 'TPA_NAME' => 'HealthIndia Insurance TPA Services Pvt. Ltd.',
+ 'FRONT_CARD' => base_url('public/uploads/template_bg/Nhance_Ecard_working_1_front_3.png'),
+ 'BACK_CARD' => base_url('public/uploads/template_bg/Nhance_Ecard_working_1_Back_3.png'),
+ 'LEVELS' => 'Level 1: 1800-XXX-XXXX Level 2: support@company.com'
+ ];
+
+ $html = $this->loadTemplate($data);
+
+ // Load mPDF
+ $mpdf = "";
+
+ // $mpdf = new \Mpdf\Mpdf([
+ // 'mode' => 'utf-8',
+ // 'format' => 'A4',
+ // 'margin_left' => 0,
+ // 'margin_right' => 0,
+ // 'margin_top' => 0,
+ // 'margin_bottom' => 0,
+ // 'tempDir' => __DIR__ . '/writable/mpdf'
+ // ]);
+
+ // Optional: Stretch background or images fully
+ // $html = '
+ // ' . $html;
+
+ // $mpdf->WriteHTML($html);
+
+ // // Output inline (no download prompt)
+ // $filename = 'ecard_' . date('Y-m-d_H-i-s') . '.pdf';
+ // $mpdf->Output($filename, 'D');
+ /*
+ 'I' = inline view in browser (no download prompt).
+ 'D' = force download.
+ 'F' = save to file.
+ 'S' = return as string.
+ */
+ }
+
+ public function getEmployeePolicyTypes($client_id, $emp_code, $emp_id)
+ {
+ $employeePolicy = new EmployeePolicyModel();
+
+ $data = $employeePolicy
+ ->select('client_policy.policy_type_id')
+ ->join('employees', 'employee_polices.employee_id = employees.id')
+ ->join('client_policy', 'employee_polices.client_policy_id = client_policy.id')
+ ->where('employees.is_active', 1)
+ ->where('employees.emp_status', ['active', 'expired'])
+ ->where('employee_polices.is_active', 1)
+ ->where('employee_polices.status', ['active', 'expired'])
+ ->where('employees.client_id', $client_id)
+ ->where('employees.emp_code', $emp_code)
+ ->groupBy('employee_polices.client_policy_id')
+ ->findAll();
+
+ }
+}
diff --git a/app/Controllers/ThzController.php b/app/Controllers/ThzController.php
index be2d0f5f..0dea90c1 100644
--- a/app/Controllers/ThzController.php
+++ b/app/Controllers/ThzController.php
@@ -3,25 +3,52 @@
namespace App\Controllers;
use App\Controllers\BaseController;
+use App\Helpers\MailHelper;
use CodeIgniter\HTTP\ResponseInterface;
use App\Models\ThzMasterModel;
use App\Models\ThzMasterNotesModel;
+use App\Models\ThzTypeModel;
+use App\Models\ThzHistoryModel;
use App\ControllerCleaners\ThzControllerCleaner;
+use App\Models\UserModel;
+use App\Models\ClientPolicyModel;
+use App\Models\ClientModel;
+use App\Models\TicketMailTemplateModel;
+use App\Models\ClientRMModel;
+
class ThzController extends BaseController
{
protected $thzMasterModel;
protected $thzMasterNotesModel;
-
+ protected $thzTypeModel;
+ protected $thzHistoryModel;
protected $thzControllerCleaner;
+ protected $userModel;
+ protected $clientPolicyModel;
+ protected $clientModel;
+
+ protected $ticketMailTemplateModel;
+
+ protected $cientRmModel;
+ protected $myLogger;
+
public function __construct()
{
- $this->thzMasterModel = new ThzMasterModel();
- $this->thzMasterNotesModel = new ThzMasterNotesModel();
- $this->thzControllerCleaner = new ThzControllerCleaner();
+ $this->thzMasterModel = new ThzMasterModel();
+ $this->thzMasterNotesModel = new ThzMasterNotesModel();
+ $this->thzTypeModel = new thzTypeModel();
+ $this->thzHistoryModel = new ThzHistoryModel();
+ $this->thzControllerCleaner = new ThzControllerCleaner();
+ $this->userModel = new UserModel();
+ $this->clientPolicyModel = new ClientPolicyModel();
+ $this->clientModel = new ClientModel();
+ $this->cientRmModel = new ClientRMModel();
+ $this->ticketMailTemplateModel = new TicketMailTemplateModel();
+ $this->myLogger = \Config\Services::mylogger();
}
public function index()
@@ -29,141 +56,668 @@ class ThzController extends BaseController
//
}
- public function ticketSave(){
+ public function ticketSave()
+ {
+ try {
+ $data = $this->request->getPost();
+ $references = "";
+ if (!empty($data['thz_id'])) {
- $data = $this->request->getJSON(true);
+ $text = "update";
+ // here insert history Status.
+ $old = $this->thzMasterModel->where('thz_id', $data['thz_id'])->get()->getRowArray();
+ $result = $this->updateTicket($data);
- if (!empty($data['thz_id'])) {
- $data['updated_by'] = get_session_userid();
- $ticket_id = $data['thz_id'];
- $text = "update";
+ if ($old && isset($data['status'])) {
- $result = $this->thzMasterModel->where('thz_id', $ticket_id)->set($data)->update();
+ if ($old['status'] != $data['status']) {
+ $history = [
+ 'thz_id' => $data['thz_id'],
+ 'field_name' => 'status',
+ 'display_name' => 'Status',
+ 'old_value' => $old['status'],
+ 'new_value' => $data['status'],
+ 'is_active' => 1
+ ];
+
+ if (!empty(get_session_userid())) {
+ $history['created_by'] = get_session_userid();
+ }
+
+ $hist_id = $this->thzHistoryModel->insert($history);
+ $references = $old['status'] . " - " . $data['status'] . " - " . $hist_id;
+ } else {
+ $references = $old['status'] . " - " . $data['status'];
+ }
+ } else {
+ $references = "No Details";
+ }
+
+ $updateID = $data['thz_id'];
} else {
- $data['created_by'] = get_session_userid();
- $text = "create";
- $result = $this->thzMasterModel->insert($data);
+ $text = "create";
+ $insertID = $this->insertTicket($data);
+ $result = true;
+ $references = "";
}
- return $this->response->setJSON(([ 'status' => $result ? 'success' : 'error' ,
- 'message' => $result ? "Ticket {$text}d successfully" : "Unable to {$text} ticket. Please try again." ]));
+ $id = isset($insertID) && !empty($insertID) ? $insertID : $updateID;
+ $emailNotificationResult = $this->ticketSaveNotification($data, $insertOrUpdate = $text, $id);
+ return $this->response->setJSON([
+ 'status' => $result ? 'success' : 'error',
+ 'message' => $result ? "Ticket {$text}d successfully " : "Unable to {$text} ticket. Please try again.",
+ 'notification' => $emailNotificationResult ? 'Email Notification Success..!!' : 'Email Notification Failed..!!',
+ 'ref' => $references
+ ])->setStatusCode($result ? 200 : 400);
+ } catch (\Throwable $e) {
+ $code = ($e->getCode() && $e->getCode() >= 100 && $e->getCode() < 600) ? $e->getCode() : 500;
+ $isDbError = $e instanceof \CodeIgniter\Database\Exceptions\DatabaseException
+ || $e instanceof \mysqli_sql_exception
+ || $e instanceof \PDOException;
+ $context = ['title' => get_class($e), 'type' => get_class($e), 'code' => $code, 'message' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()];
+
+ $this->myLogger->logme('error', "Exception: {message} in {file} on line {line}", $context, 0);
+
+ return $this->response->setJSON([
+ 'status' => 'error',
+ 'message' => $isDbError ? 'Data Access Error' : $e->getMessage(),
+ 'ref' => $isDbError ? 'database - ' : 'application - ' . $code . ' - ' . $e->getLine()
+ ])->setStatusCode($code);
+ }
}
-
public function ticketList()
{
- $returnType = strtolower($this->request->getGet('return_type') ?? 'api');
-
- $data = $this->request->getJSON(true);
-
- $tickets = $this->fetchTicketsBasedOnrole($data);
+ try {
+ $returnType = strtolower($this->request->getGet('return_type') ?? 'api');
-
- if ($returnType === 'api') {
- if (empty($tickets)) {
- return $this->response->setJSON([ 'status' => 'error','message' => 'No tickets found',])->setStatusCode(404);
+ $data = $this->request->getGet();
+ if ($returnType === 'web' && in_array(get_role_id(), [2, 3, 4])) {
+ $data['assign_to'] = $data['assign_to'] ?? get_session_userid();
}
- }else{
-
- $data['page_name'] = "Ticket List";
- $data['ticket_data'] = $tickets;
- $data['assigner'] = $this->userModel->where('is_active', 1)->findAll();
- return $this->loadLayout('ticket_list_web', $data);
+
+ $tickets = $this->fetchTicketsBasedOnrole($data);
+
+
+ if ($returnType === 'api') {
+ if (empty($tickets)) {
+ // return $this->response->setJSON([ 'status' => 'error','message' => 'No tickets found'])->setStatusCode(404);
+ throw new \RuntimeException('No tickets found', 400);
+ }
+ } else {
+
+ $data['page_name'] = "Tickets";
+ $data['ticket_data'] = $tickets;
+ $data['assignee'] = $this->userModel->where('is_active', 1)->whereIn('role', ['2', '3', '4'])->findAll(); // enga 5-"head" and 1-"admin" assign pannvaga so dropdown la varakudhathu
+ // 2,3,4 remain person varannum.
+ $data['client_list'] = $this->clientModel->getCreatedByUserName();
+ $data['ticket_type'] = $this->thzTypeModel->where('is_active', 1)->findAll();
+
+ return $this->loadLayout('thz_list', $data);
+ }
+
+
+ return $this->response->setJSON([
+ 'status' => 'success',
+ 'data' => $tickets,
+ ])->setStatusCode(200);
+ } catch (\Throwable $e) {
+ $code = ($e->getCode() && $e->getCode() >= 100 && $e->getCode() < 600) ? $e->getCode() : 500;
+
+ $isDbError = $e instanceof \CodeIgniter\Database\Exceptions\DatabaseException
+ || $e instanceof \mysqli_sql_exception
+ || $e instanceof \PDOException;
+
+ $context = ['title' => get_class($e), 'type' => get_class($e), 'code' => $code, 'message' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()];
+
+ $this->myLogger->logme('error', "Exception: {message} in {file} on line {line}", $context, 0);
+
+ return $this->response->setJSON([
+ 'status' => 'error',
+ 'message' => $isDbError ? 'Data Access Error' : $e->getMessage(),
+ 'ref' => $isDbError ? 'database - ' : 'application - ' . $code . ' - ' . $e->getLine()
+ ])->setStatusCode($code);
}
-
-
-
- return $this->response->setJSON([
- 'status' => 'success',
- 'data' => $tickets,
- ]);
}
+ public function ticketConversationSave()
+ {
- public function ticketConversationSave(){
+ try {
+ $data = $this->request->getPost();
- $data = $this->request->getJSON(true);
+ $data['notes_type'] = $data['notes_type'] ?? 'External';
$result = $this->thzMasterNotesModel->insert($data);
- if(empty($result)){
- return $this->response->setJSON((['status' => 'error', 'message' => 'No tickets found']));
+ if (empty($result)) {
+ // return $this->response->setJSON((['status' => 'error', 'message' => 'No tickets found']))->setStatusCode(404);
+ throw new \RuntimeException('No tickets found', 404);
+ }
+
+ if ($data['notes_type'] == "External") {
+ $emailNotificationResult = $this->ticketConversationSaveNotification($data);
+ } else {
+ $emailNotificationResult = false;
+ }
+
+
+
+ return $this->response->setJSON([
+ 'status' => $result ? 'success' : 'error',
+ 'message' => $result ? "Ticket Notes created successfully" : "Unable to create ticket notes. Please try again.",
+ 'notification' => $emailNotificationResult ? 'Email Notification Success..!!' : 'Email Notification Failed Or No Need..!!'
+ ])->setStatusCode($result ? 200 : 400);
+ } catch (\Throwable $e) {
+ $code = ($e->getCode() && $e->getCode() >= 100 && $e->getCode() < 600) ? $e->getCode() : 500;
+
+ $isDbError = $e instanceof \CodeIgniter\Database\Exceptions\DatabaseException
+ || $e instanceof \mysqli_sql_exception
+ || $e instanceof \PDOException;
+
+ $context = ['title' => get_class($e), 'type' => get_class($e), 'code' => $code, 'message' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()];
+
+ $this->myLogger->logme('error', "Exception: {message} in {file} on line {line}", $context, 0);
+
+ return $this->response->setJSON([
+ 'status' => 'error',
+ 'message' => $isDbError ? 'Data Access Error' : $e->getMessage(),
+ 'ref' => $isDbError ? 'database - ' : 'application - ' . $code . ' - ' . $e->getLine()
+ ])->setStatusCode($code);
}
-
- return $this->response->setJSON((['status' => 'success', 'data' => $result]));
-
-
}
- public function ticketConversationList(){
+ public function ticketAutoFetchDetails()
+ {
+ try {
+ $data = $this->request->getPost();
- $data = $this->request->getJSON(true);
+ $client_id = $data['client_id'] ?? null;
+ $mobile = $data['mobile'] ?? null;
- $thz_id = $data['thz_id'] ?? null;
+ if ($client_id && $mobile) {
+ $details = $this->thzMasterModel->ticketAutoFetchDetails($client_id, $mobile);
- $result = $this->thzMasterNotesModel->ticketConversationList($thz_id);
+ if (empty($details)) {
+ throw new \RuntimeException('No Data found', 400);
+ }
- if(empty($result)){
- return $this->response->setJSON((['status' => 'error', 'message' => 'No tickets found']));
+ $policyIds = array_filter(array_column($details, 'policy_id'));
+ $clientPolicy = !empty($policyIds)
+ ? $this->clientPolicyModel->whereIn('id', $policyIds)->where('is_active', 1)->get()->getResultArray()
+ : [];
+
+ $result['client_details'] = $details;
+ $result['policy_details'] = $clientPolicy ?? [];
+ } else {
+ throw new \RuntimeException('Client and Mobile Not found', 400);
+ }
+
+ return $this->response->setJSON(['status' => 'success', 'data' => $result])->setStatusCode(200);
+ } catch (\Throwable $e) {
+ $code = ($e->getCode() && $e->getCode() >= 100 && $e->getCode() < 600) ? $e->getCode() : 500;
+
+ $isDbError = $e instanceof \CodeIgniter\Database\Exceptions\DatabaseException
+ || $e instanceof \mysqli_sql_exception
+ || $e instanceof \PDOException;
+
+ $context = ['title' => get_class($e), 'type' => get_class($e), 'code' => $code, 'message' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()];
+
+ $this->myLogger->logme('error', "Exception: {message} in {file} on line {line}", $context, 0);
+
+ return $this->response->setJSON([
+ 'status' => 'error',
+ 'message' => $isDbError ? 'Data Access Error' : $e->getMessage(),
+ 'ref' => $isDbError ? 'database - ' : 'application - ' . $code . ' - ' . $e->getLine()
+ ])->setStatusCode($code);
}
-
- return $this->response->setJSON((['status' => 'success', 'data' => $result]));
-
}
+ public function ticketConversationList()
+ {
+ $data = $this->request->getGet();
+ $returnType = strtolower($this->request->getGet('return_type') ?? 'api');
+
+ $thz_id = $data['thz_id'] ?? null;
+
+ $ticketType = $data['notes_type'] ?? 'External';
+
+ if ($thz_id) {
+ $result['master'] = $this->thzMasterModel
+ ->select('thz_master.*, CONCAT(user_profiles.first_name, " ", user_profiles.last_name) as assignee_name')
+ ->join('user_profiles', 'user_profiles.id = thz_master.assign_to', 'left')
+ ->where('thz_master.thz_id', $thz_id)
+ ->findAll();
+
+ if (!empty($result['master'])) {
+ $notes = $this->thzMasterNotesModel->ticketConversationList($thz_id, $returnType);
+ $result['notes'] = !empty($notes) ? $notes : [];
+ } else {
+ // return $this->response->setJSON((['status' => 'error', 'message' => 'No tickets found']))->setStatusCode(400);
+ throw new \RuntimeException('No tickets found', 400);
+ }
+ } else {
+ // return $this->response->setJSON((['status' => 'error', 'message' => 'No tickets found']))->setStatusCode(404);
+ throw new \RuntimeException('No tickets found', 404);
+ }
+
+ if ($returnType === 'api') {
+ try {
+ return $this->response->setJSON((['status' => 'success', 'data' => $result]))->setStatusCode(200);
+ } catch (\Throwable $e) {
+ $code = ($e->getCode() && $e->getCode() >= 100 && $e->getCode() < 600) ? $e->getCode() : 500;
+
+ $isDbError = $e instanceof \CodeIgniter\Database\Exceptions\DatabaseException
+ || $e instanceof \mysqli_sql_exception
+ || $e instanceof \PDOException;
+
+ $context = ['title' => get_class($e), 'type' => get_class($e), 'code' => $code, 'message' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()];
+
+ $this->myLogger->logme('error', "Exception: {message} in {file} on line {line}", $context, 0);
+
+ return $this->response->setJSON([
+ 'status' => 'error',
+ 'message' => $isDbError ? 'Data Access Error' : $e->getMessage(),
+ 'ref' => $isDbError ? 'database - ' : 'application - ' . $code . ' - ' . $e->getLine()
+ ])->setStatusCode($code);
+ }
+ } else {
+
+ $assign_to = $result['master'][0]['assign_to'];
+ $mobile = $result['master'][0]['mobile'];
+
+ $toGetPolicyId = (!empty($result['master'][0]['policy_id']) && strtolower($result['master'][0]['policy_id']) !== 'null')
+ ? $result['master'][0]['policy_id']
+ : '';
+
+ $result['related_tickets'] = $this->thzMasterModel
+ ->select('thz_master.*, CONCAT(user_profiles.first_name, " ", user_profiles.last_name) as assignee_name')
+ ->join('user_profiles', 'user_profiles.id = thz_master.assign_to', 'left')
+ ->where('thz_master.assign_to', $assign_to)
+ ->where('thz_master.mobile', $mobile)
+ ->where('thz_master.thz_id !=', $thz_id)
+ ->where('thz_master.status !=', 'Closed')
+ ->where('thz_master.status !=', 'Resolved')
+ ->findAll();
+
+ $result['assignee'] = $this->userModel->where('is_active', 1)->whereIn('role', ['2', '3', '4'])->findAll(); // enga 5-"head" and 1-"admin" assign pannvaga so dropdown la varakudhathu
+ // 2,3,4 remain person varannum.
+ $result['policy_terms'] = $toGetPolicyId ? $this->getPolicyTerms($toGetPolicyId) : '';
+
+ $result['ticket_type'] = $this->thzTypeModel->where('is_active', 1)->findAll();
+
+ return $this->loadLayout('thz_notes', $result);
+ }
+ }
+
+ public function ticketType()
+ {
+ $method = $this->request->getMethod(); // get, post
+ try {
+ if ($method === 'get') {
+ $types = $this->thzTypeModel->select('id,name,is_active')->where('is_active', 1)->findAll();
+ if (empty($types)) {
+ return $this->response->setJSON(['status' => 'error', 'message' => 'No ticket types found'])->setStatusCode(404);
+ }
+ return $this->response->setJSON(['status' => 'success', 'data' => $types])->setStatusCode(200);
+ }
+
+ if ($method === 'post') {
+
+ $data = $this->request->getPost();
+ if (!empty($data['id'])) {
+ $text = "update";
+ $result = $this->thzTypeModel->update($data['id'], $data);
+ $updateID = $data['id'];
+ } else {
+ $text = "create";
+ $insertID = $this->thzTypeModel->insert($data);
+ $result = true;
+ }
+
+ $id = isset($insertID) && !empty($insertID) ? $insertID : ($updateID ?? null);
+
+ return $this->response->setJSON([
+ 'status' => $id ? 'success' : 'error',
+ 'message' => $id ? "Ticket Type {$text}d successfully" : "Unable to {$text} ticket type. Please try again.",
+ 'id' => $id
+ ])->setStatusCode($id ? 200 : 400);
+ }
+ return $this->response->setJSON(['status' => 'error', 'message' => 'Invalid request method'])->setStatusCode(405);
+ } catch (\Throwable $e) {
+ $code = ($e->getCode() && $e->getCode() >= 100 && $e->getCode() < 600) ? $e->getCode() : 500;
+
+ $isDbError = $e instanceof \CodeIgniter\Database\Exceptions\DatabaseException
+ || $e instanceof \mysqli_sql_exception
+ || $e instanceof \PDOException;
+
+ $context = ['title' => get_class($e), 'type' => get_class($e), 'code' => $code, 'message' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()];
+
+ $this->myLogger->logme('error', "Exception: {message} in {file} on line {line}", $context, 0);
+
+ return $this->response->setJSON([
+ 'status' => 'error',
+ 'message' => $isDbError ? 'Data Access Error' : $e->getMessage(),
+ 'ref' => $isDbError ? 'database - ' : 'application - ' . $code . ' - ' . $e->getLine()
+ ])->setStatusCode($code);
+ }
+ }
+
+ public function ticketHistoryList()
+ {
+ try {
+ $data = $this->request->getGet();
+ $thz_id = $data['thz_id'];
+ // $details = $this->thzHistoryModal->whereIn('thz_id', $thz_id)->where('is_active', 1)->get()->getResultArray();
+ $details = $this->thzHistoryModel->select('thz_history.*, CONCAT(user_profiles.first_name, " ", user_profiles.last_name) as created_name')
+ ->join('user_profiles', 'user_profiles.id = thz_history.created_by', 'left')
+ ->where('thz_history.thz_id', $thz_id)->where('thz_history.is_active', 1)
+ ->orderBy('thz_history.created_at', 'desc')
+ ->get()->getResultArray();
+
+
+
+ if (empty($details)) {
+ // return $this->response->setJSON([ 'status' => 'error','message' => 'No History found'])->setStatusCode(404);
+ throw new \RuntimeException('No History found', 404);
+ }
+
+
+ return $this->response->setJSON(['status' => 'success', 'data' => $details])->setStatusCode(200);
+ } catch (\Throwable $e) {
+ $code = ($e->getCode() && $e->getCode() >= 100 && $e->getCode() < 600) ? $e->getCode() : 500;
+
+ $isDbError = $e instanceof \CodeIgniter\Database\Exceptions\DatabaseException
+ || $e instanceof \mysqli_sql_exception
+ || $e instanceof \PDOException;
+
+ $context = ['title' => get_class($e), 'type' => get_class($e), 'code' => $code, 'message' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()];
+
+ $this->myLogger->logme('error', "Exception: {message} in {file} on line {line}", $context, 0);
+
+ return $this->response->setJSON([
+ 'status' => 'error',
+ 'message' => $isDbError ? 'Data Access Error' : $e->getMessage(),
+ 'ref' => $isDbError ? 'database - ' : 'application - ' . $code . ' - ' . $e->getLine()
+ ])->setStatusCode($code);
+ }
+ }
/************************************************** PRIVATE FUNCTIONS ********************************************************/
- private function checkGeneralUserOrEmployee($data){
-
- if($data['empcode']){
- return $data['empcode'];
- } elseif ($data['mobile']) {
- return $data['mobile'];
- } elseif ($data['email']) {
- return $data['email'];
- } else {
- return null;
- }
-
- }
-
private function fetchTicketsBasedOnrole(array $data): array
{
- $id = $data['thz_id'] ?? null;
+ // $id = $data['thz_id'] ?? null;
$assign_to = $data['assign_to'] ?? null;
$mobile = $data['mobile'] ?? null;
if (!empty($assign_to)) {
// Tickets assigned to a staff
return $this->thzMasterModel
- ->where('assign_to', $assign_to)
- ->findAll();
+ ->select('thz_master.*, CONCAT(user_profiles.first_name, " ", user_profiles.last_name) as assignee_name')
+ ->join('user_profiles', 'user_profiles.id = thz_master.assign_to', 'left')
+ ->where('thz_master.assign_to', $assign_to)
+ ->orderBy('thz_master.created_at', 'desc')
+ ->findAll();
}
- if (!empty($id) && !empty($mobile)) {
+ // if (!empty($id) && !empty($mobile)) {
+ if (!empty($mobile)) {
// Specific ticket by ID and mobile
return $this->thzMasterModel
- ->where('thz_id', $id)
- ->where('mobile', $mobile)
- ->findAll();
+ ->select('thz_master.*, CONCAT(user_profiles.first_name, " ", user_profiles.last_name) as assignee_name')
+ ->join('user_profiles', 'user_profiles.id = thz_master.assign_to', 'left')
+ // ->where('thz_id', $id)
+ ->where('thz_master.mobile', $mobile)
+ ->orderBy('thz_master.created_at', 'desc')
+ ->findAll();
}
// All tickets (e.g., for managers)
- return $this->thzMasterModel->findAll();
+ return $this->thzMasterModel
+ ->select('thz_master.*, CONCAT(user_profiles.first_name, " ", user_profiles.last_name) as assignee_name')
+ ->join('user_profiles', 'user_profiles.id = thz_master.assign_to', 'left')
+ ->orderBy('thz_master.created_at', 'desc')
+ ->findAll();
}
-}
+ private function ticketSaveNotification($data, $insertOrUpdate, $id)
+ {
+ $user_email = $data['email'] ?? null;
+
+ $assignee_id = $data['assign_to'] ?? null;
+
+ $assignee_email = $this->findAssigneeEmail($assignee_id);
+
+ $client_id = $data['client_id'] ?? null;
+
+ $emailToNotified = [
+ 'user_email' => $user_email,
+ 'assignee_email' => $assignee_email
+ ];
+
+ $ticketId = $id;
+
+ $result = $this->ticketSaveEmailNotificationBasedOnRole($emailToNotified, $insertOrUpdate, $ticketId, $data, $client_id);
+
+ return $result;
+ }
+
+ private function ticketConversationSaveNotification($data)
+ {
+
+ $thz_id = $data['thz_id']; // thz is alias of ticket
+
+ $data['subject'] = $this->findSubject($data['thz_id']);
+
+ $assignee_id = $this->findAssigneeId($data['thz_id']);
+
+ $user_email = $this->findUserEmail($data['thz_id']);
+
+ $assignee_email = $this->findAssigneeEmail($assignee_id) ?? '';
+
+ $sender_mail = $data['notes_by'] == "User" ? $user_email : $assignee_email;
+ $receiver_mail = $data['notes_by'] == "User" ? $assignee_email : $user_email;
+
+ $templateName = "ticket_conversation_save_notification";
+
+ $to_email = $receiver_mail;
+
+ $ticketId = $thz_id;
+
+ $message = $data['notes'] ?? '';
+
+ $this->sendEmail($templateName, $data, $to_email, $ticketId, $message);
+
+ return true;
+ }
+
+
+ private function findAssigneeEmail($assignee_id)
+ {
+
+ $row = $this->userModel->where('id', $assignee_id)->get()->getRow();
+ $assigneeEmail = $row ? $row->email : null;
+ return $assigneeEmail ? $assigneeEmail : "";
+ }
+
+ private function findAssigneeId($ticketId)
+ {
+ $row = $this->thzMasterModel->where('thz_id', $ticketId)->get()->getRow();
+ $assigneeId = $row ? $row->assign_to : null;
+ return $assigneeId ? $assigneeId : 0;
+ }
+
+ private function findUserEmail($ticket_id)
+ {
+ $row = $this->thzMasterModel->where('thz_id', $ticket_id)->get()->getRow();
+ $email = $row ? $row->email : null;
+ return $email ? $email : " ";
+ }
+
+ private function findSubject($ticketId)
+ {
+ $row = $this->thzMasterModel->where('thz_id', $ticketId)->get()->getRow();
+ $subject = $row ? $row->subject : null;
+ return $subject ? $subject : " ";
+ }
+
+ private function ticketSaveEmailNotificationBasedOnRole($emailToNotified, $insertOrUpdate, $ticketId, $data, $client_id)
+ {
+
+ $user_email = $emailToNotified['user_email'] ?? null;
+ $assignee_email = $emailToNotified['assignee_email'] ?? null;
+
+
+ if (!empty($assignee_email)) {
+
+ switch ($insertOrUpdate) {
+
+ case 'update':
+
+ $this->sendEmail('ticket_save_update_assignee', $data, $assignee_email, $ticketId);
+
+ break;
+
+ case 'create':
+
+ $this->sendEmail('ticket_save_create_assignee', $data, $assignee_email, $ticketId);
+
+ break;
+
+ default:
+ # code...
+ break;
+ }
+ }
+
+ if (!empty($user_email)) {
+
+ switch ($insertOrUpdate) {
+
+ case 'update':
+
+ $data['assigneeAndStatus'] = empty($assignee_email)
+ ? "Not Yet Assigned"
+ : "Assigned With {$assignee_email}";
+
+ $this->sendEmail('ticket_save_update_user', $data, $user_email, $ticketId);
+
+
+ break;
+
+ case 'create':
+
+ $account_manager_email = $this->cientRmModel->findAccountManagerEmail($client_id);
+
+ $cc = getenv(' G_ticketing_system_cc');
+
+ $template = empty($assignee_email)
+ ? 'ticket_save_create_user_unassigned'
+ : 'ticket_save_create_user_assigned';
+
+ if (!empty($assignee_email)) {
+ $data['assignee_email'] = $assignee_email;
+ }
+
+ $this->sendEmail($template, $data, $user_email, $ticketId);
+
+ // send to account manager and if it is more than one email also no problem we send to all account managers
+ if (!empty($account_manager_email)) {
+ $this->sendEmail($template, $data, $account_manager_email, $ticketId, $cc);
+ }
+
+ break;
+
+ default:
+ # code...
+ break;
+ }
+ }
+
+ return true;
+ }
+
+ private function updateTicket($data)
+ {
+
+ $data['updated_by'] = get_session_userid();
+ $ticket_id = $data['thz_id'];
+ $result = $this->thzMasterModel->where('thz_id', $ticket_id)->set($data)->update();
+
+ return $result;
+ }
+
+ private function insertTicket($data)
+ {
+ $data['created_by'] = get_session_userid();
+ $this->thzMasterModel->insert($data);
+
+ return $this->thzMasterModel->insertID(); // returns the inserted row's ID
+ }
+
+
+ private function sendEmail($templateName, $data, $to_email, $ticketId , $cc = "", $message = "", $bcc = "")
+ {
+
+ $mailTemplate = $this->ticketMailTemplateModel->where('template_name', $templateName)->findAll()[0] ?? [];
+
+ if (empty($mailTemplate)) {
+ return;
+ }
+
+ $mailTemplate['subject'] = str_replace('%subject%', $data['subject'] ?? '', $mailTemplate['subject']);
+
+ $mailTemplate['mail_content'] = str_replace('%subject%', $data['subject'] ?? '', $mailTemplate['mail_content']);
+
+ $mailTemplate['mail_content'] = str_replace('%ticketId%', $ticketId ?? '', $mailTemplate['mail_content']);
+
+ $mailTemplate['mail_content'] = str_replace('%message%', $message ?? '', $mailTemplate['mail_content']);
+
+ $mailTemplate['mail_content'] = str_replace('%assignee_email%', $data['assignee_email'] ?? '', $mailTemplate['mail_content']);
+
+ $mailTemplate['mail_content'] = str_replace('%assigneeAndStatus%', $data['assigneeAndStatus'] ?? '', $mailTemplate['mail_content']);
+
+ $from_mail = "";
+ $to_mail = $to_email;
+ $cc_string = $cc;
+ $subject = $mailTemplate['subject'];
+ $message = $mailTemplate['mail_content'];
+ $attachments = "";
+ $reply_to = "";
+ $bcc_string = $bcc;
+
+ $res = MailHelper::send_email(['from_mail' => $from_mail, 'mail' => $to_mail, 'cc' => $cc_string, 'subject' => $subject, 'message' => $message, 'attachments' => $attachments, 'reply_to' => $reply_to, 'bcc' => $bcc_string]);
+ }
+
+
+ public function getPolicyTerms($client_policy_id)
+ {
+ $policy_data = $this->clientPolicyModel->where('is_active', 1)->where('id', $client_policy_id)->first();
+
+ $policy_terms = [];
+ if (isset($policy_data['policy_terms']) && !empty($policy_data['policy_terms'])) {
+
+ $raw_terms = json_decode($policy_data['policy_terms'] ?? [], true) ?? [];
+
+ $ticketController = new TicketController();
+ $policy_terms = $ticketController->convertTermsToDisplay($raw_terms);
+ }
+
+ $data['policy_terms'] = $policy_terms;
+ return view('view_policy_terms', $data);
+ }
+}
diff --git a/app/Controllers/TicketController.php b/app/Controllers/TicketController.php
index 4c344c28..5d930c71 100644
--- a/app/Controllers/TicketController.php
+++ b/app/Controllers/TicketController.php
@@ -21,6 +21,9 @@ use App\Models\InsurerModel;
use App\Models\EmployeeModel;
use App\Models\TPAModel;
use App\Models\ClaimFilesModel;
+use App\Models\ClaimDumpFileModel;
+use App\Models\VehicleModel;
+use App\Models\PartnerPolicyModel;
use DOMDocument;
use Psr\Log\LoggerInterface;
@@ -60,6 +63,9 @@ class TicketController extends BaseController
protected $insurerModel;
protected $TPAModel;
protected $claimFilesModel;
+ protected $claimDumpFileModel;
+ protected $vehicleModel;
+ protected $partnerPolicyModel;
public function __construct()
{
@@ -69,7 +75,7 @@ class TicketController extends BaseController
$this->ticketMasterModel = new TicketMasterModel();
- $this->ticketType = [1 => "Claim-GMC", 2 => "Claim-GPA", 3 => "EDLI", 4 => "GTLI"];
+ $this->ticketType = [1 => "Claim-GMC", 2 => "Claim-GPA", 3 => "EDLI", 4 => "GTLI", 8 => "Motor"];
$this->priorityType = [
1 => "Low",
2 => "Medium",
@@ -345,6 +351,9 @@ class TicketController extends BaseController
$this->insurerModel = new InsurerModel();
$this->TPAModel = new TPAModel();
$this->claimFilesModel = new ClaimFilesModel();
+ $this->claimDumpFileModel = new ClaimDumpFileModel();
+ $this->vehicleModel = new VehicleModel();
+ $this->partnerPolicyModel = new PartnerPolicyModel();
}
public function ticketList()
@@ -681,6 +690,9 @@ class TicketController extends BaseController
case 4:
$data['ticket_form'] = 'GTLI';
break;
+ case 8:
+ $data['ticket_form'] = 'Motor';
+ break;
}
// Fetch ACM Users
@@ -701,7 +713,10 @@ class TicketController extends BaseController
$claim_status_id = 25;
}else if($ticket_type == 4){
$claim_status_id = 35;
- }else{
+ }else if($ticket_type == 8){
+ $claim_status_id = 62;
+ }
+ else{
$claim_status_id = 1;
}
}
@@ -716,11 +731,79 @@ class TicketController extends BaseController
$data['claim_type'] = $this->claimType[2];
}
+ $data['client_for_motor'] = $this->clientModel->select('id,client_name,phone')->where('client_type', 2)->where('is_active', 1)->findAll();
+
$this->myLogger->logme('error', "Ticket form data fetched successfully for Ticket Type: $ticket_type");
return $data;
}
+ public function fetchVehiclePolicy($id)
+ {
+ $method = $this->request->getMethod();
+
+ try {
+ if (!$id) {
+ throw new \Exception('Invalid ID', 400);
+ }
+
+ if ($method === 'get') {
+ $data['vehicle_list'] = $this->vehicleModel
+ ->where('is_active', 1)
+ ->where('owner', $id)
+ ->findAll();
+
+ // $data['partner_policy_list'] = $this->partnerPolicyModel
+ // ->where('is_active', 1)
+ // ->findAll();
+ $data['partner_policy_list'] = $this->partnerPolicyModel->partnerPolicyList();
+
+ $client = $this->clientModel
+ ->where('is_active', 1)
+ ->where('id', $id)
+ ->first();
+
+ $data['email'] = !empty($client) ? $client['email'] : null;
+ $data['phone'] = !empty($client) ? $client['phone'] : null;
+
+ if (empty($data['vehicle_list']) && empty($data['partner_policy_list'])) {
+ throw new \Exception('No Records found', 404);
+ }
+
+ return $this->response
+ ->setJSON(['status' => 'success', 'data' => $data])
+ ->setStatusCode(200);
+ }
+
+ throw new \Exception('Invalid request method', 405);
+
+ } catch (\Throwable $e) {
+ $code = ($e->getCode() && $e->getCode() >= 100 && $e->getCode() < 600) ? $e->getCode() : 500;
+
+ $isDbError = $e instanceof \CodeIgniter\Database\Exceptions\DatabaseException
+ || $e instanceof \mysqli_sql_exception
+ || $e instanceof \PDOException;
+
+ $context = [
+ 'title' => get_class($e),
+ 'type' => get_class($e),
+ 'code' => $code,
+ 'message' => $e->getMessage(),
+ 'file' => $e->getFile(),
+ 'line' => $e->getLine()
+ ];
+
+ $this->myLogger->logme('error', "Exception: {message} in {file} on line {line}", $context, 0);
+
+ return $this->response->setJSON([
+ 'status' => 'error',
+ 'message' => $isDbError ? 'Data Access Error' : $e->getMessage(),
+ 'ref' => ($isDbError ? 'database - ' : 'application - ') . $code . ' - ' . $e->getLine()
+ ])->setStatusCode($code);
+ }
+ }
+
+
//transform the claim status
public function transFormClaimStatus($claimStatusId, $ticket_type)
{
@@ -789,9 +872,10 @@ class TicketController extends BaseController
}
public function view_ticket($ticket_id)
- {
+ {
// $ticket_data = $this->ticketMasterModel->where('id', $ticket_id)->where('is_active', 1)->first();
$ticket_data = $this->ticketMasterModel->getTicketDataByTicketID($ticket_id);
+
$ticket_data = $this->formatDateForClaim($ticket_data, 'd/m/Y');
if (in_array($ticket_data['claim_status_id'], [15, 25, 35])) {
@@ -850,6 +934,14 @@ class TicketController extends BaseController
// print_rr($data); die;
}
+ // 8TH TYPE is Motor - so do not remove it....
+ if($ticket_data['ticket_type_id'] == 8){
+ $claim_status_id = $ticket_data['claim_status_id'];
+ $ticket_type = $ticket_data['ticket_type_id'];
+ $data['claim_status'] = $this->transFormClaimStatus($claim_status_id, $ticket_type);
+ $data['client_for_motor'] = $this->clientModel->select('id,client_name,phone')->where('client_type', 2)->where('is_active', 1)->findAll();
+ }
+
return $this->loadLayout('ticket_edit_onbording', $data);
}
@@ -1154,13 +1246,23 @@ class TicketController extends BaseController
->orderBy('ticket_messages.created_at', 'DESC')
->findAll();
- foreach ($dataToSend['messages'] as $message) {
+ foreach ($dataToSend['messages'] as &$message) {
$mail_content_converted = $this->convertHtmlToText($message['mail_content']);
$message['mail_content'] = $mail_content_converted;
+
+ $claimFiles = new ClaimFilesModel();
+ $message["files_data"] = $claimFiles->where('is_active', 1)
+ ->where('file_type', 2)->where('ticket_id', $ticket_master_id)
+ ->where('ticket_message_id', $message['id'])
+ ->findAll();
+
}
+ unset($message);
+
$dataToSend['emp_name'] = $this->ticketMasterModel->select('emp_name')
->where('id', $ticket_master_id)->where('is_active', 1)
->first()['emp_name'];
+
// dd($dataToSend);
if ($dataToSend) {
return $dataToSend;
@@ -1170,6 +1272,38 @@ class TicketController extends BaseController
}
}
+ public function downloadClaimFile($claim_file_id = null)
+ {
+ // $actionType = $this->request->getGet();
+ $claimFiles = new ClaimFilesModel();
+ $file_data = $claimFiles->where('id', $claim_file_id)->first();
+ $fileName = $file_data['doc_name'];
+
+ $filePath = WRITEPATH . '/uploads/claim_files/' . $fileName;
+
+ try {
+
+ // Check if the file exists
+ if (file_exists($filePath)) {
+ // Set the appropriate MIME type
+ $mimeType = mime_content_type($filePath);
+
+ // Send the file to the client for download
+ return $this->response->download($filePath, null, $mimeType);
+ } else {
+
+ $data['message'] = 'The Physical File Not Found';
+ echo view('errors/404', $data);
+ }
+ } catch (\Exception $e) {
+ // Handle any exceptions
+ $errorMessage = $e->getMessage();
+ $this->myLogger->logme('error', $errorMessage);
+ // You can return an error response here
+ echo $errorMessage;
+ }
+ }
+
public function convertHtmlToText($html)
{
if(!empty($html)){
@@ -1865,18 +1999,40 @@ class TicketController extends BaseController
public function getPoliciesbyEmpID()
{
$received_data = $this->request->getPost();
+ $ticket_type_id = $this->request->getPost('ticket_type_id') ?? null;
$emp_id = $received_data['emp_id'];
-
+
// Get all client policy IDs for the given employee
- $policies = $this->employeePolicyModel
- ->select('client_policy_id')
- ->where('employee_id', $emp_id)
- ->where('is_active', 1)
- ->where('status', 'active')
- ->findAll();
-
+ if ($ticket_type_id == 1) {
+
+ //get the self data for get the all policy list aginst the emp_code
+ $self_data = $this->employeeModel->where('is_active', 1)->where('id', $emp_id)->first();
+
+ $db = db_connect();
+ $builder = $db->table('employees e');
+ $builder->select('ep.*');
+ $builder->join('employee_polices ep', 'e.id = ep.employee_id');
+ $builder->join('client_policy cp', 'cp.id = ep.client_policy_id AND cp.policy_type_id IN (2,3,4,5)');
+ $builder->where('e.is_active', 1);
+ $builder->where('ep.is_active', 1);
+ $builder->where('e.emp_code', $self_data['emp_code']);
+ $builder->groupBy('client_policy_id');
+
+ $query = $builder->get();
+ $policies = $query->getResultArray();
+ } else {
+
+ $policies = $this->employeePolicyModel
+ ->select('client_policy_id')
+ ->where('employee_id', $emp_id)
+ ->where('is_active', 1)
+ ->where('status', 'active')
+ ->findAll();
+ }
+
+ // Return empty if no policies found
if (empty($policies)) {
- return []; // Return empty if no policies found
+ return [];
}
// Extract client policy IDs into an array
@@ -1899,7 +2055,7 @@ class TicketController extends BaseController
->join('tpa', 'tpa.id = client_policy.tpa_id AND tpa.is_active = 1', 'left')
->where('client_policy.policy_status', 1)
->whereIn('client_policy.id', $policy_ids)
- ->findAll();
+ ->findAll();
// dd($policyNameandID);
if ($policyNameandID){
@@ -2173,7 +2329,8 @@ class TicketController extends BaseController
'url' => $data['url'][$key]??'',
'ticket_id'=> $data['ticket_id_url']??'',
'created_by' => get_session_userid(),
- 'is_active' => 1
+ 'is_active' => 1,
+ 'file_type' => 1
];
$insertArr[] = $insertData;
@@ -2210,6 +2367,7 @@ class TicketController extends BaseController
$urlData = $this->claimFilesModel
->where('ticket_id', $ticket_id)
->where('is_active',1)
+ ->where('file_type',1)
->findAll();
return $this->response->setJSON([
@@ -2383,17 +2541,20 @@ class TicketController extends BaseController
}
// 5. Merge the Sum Insured value if the multiple sum insured exists
- if(isset($data['multiple_sum_insured'])){
- if(isset($data['sumInsured2'])){
- $data['sumInsured2'] = $data['sumInsured2'] . ", " . implode(", ", $data['multiple_sum_insured']);
- }else{
- $data['sum_insured'] = $data['sum_insured'] . ", " . implode(", ", $data['multiple_sum_insured']);
+ if (isset($data['multiple_sum_insured'])) {
+
+ $multipleSumInsured = is_array($data['multiple_sum_insured']) ? $data['multiple_sum_insured'] : [$data['multiple_sum_insured']]; // force into array if string
+
+ if (isset($data['sumInsured2'])) {
+ $data['sumInsured2'] .= ", " . implode(", ", $multipleSumInsured);
+ } else {
+ $data['sum_insured'] .= ", " . implode(", ", $multipleSumInsured);
}
+
unset($data['multiple_sum_insured']);
}
// 6. Add the special condition to key value pair
-
if(!empty($data['special_condition_label'])){
foreach ($data['special_condition_label'] as $key => $value) {
if($value != "" && $value != null) {
@@ -2445,6 +2606,155 @@ class TicketController extends BaseController
}
+ // -------- CLAIM DUMP UPLOAD ----------------------------------------------------------------------------------------------
+
+ public function claimDumpUpload()
+ {
+ $data['page_name'] = "Claim Dupm Upload";
+
+ if($this->request->is('get')){
+
+ $data['claim_dump_file_data'] = $this->claimDumpFileModel
+ ->select('
+ claim_dump_files.id as file_id,
+ claim_dump_files.file_name,
+ claim_dump_files.status,
+ claim_dump_files.created_at,
+ up.first_name as user_name
+ ')
+ ->join('user_profiles as up', 'claim_dump_files.created_by = up.id', 'left')
+ ->where('claim_dump_files.is_active', 1)
+ ->orderBy('claim_dump_files.id', 'desc')
+ ->findAll();
+
+ return $this->loadLayout('claim_dump_file_list', $data);
+
+ }else{
+
+ // print_r($this->request->getFile('claim_dump_list')); die;
+ $filename = '';
+ $fileSize = '';
+
+ //validate uploaded file
+ $validated = $this->validate([
+ 'claim_dump_list' => [
+ 'uploaded[claim_dump_list]',
+ 'mime_in[claim_dump_list,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.oasis.opendocument.spreadsheet]',
+ 'max_size[claim_dump_list,16384]',
+ ],
+ ]);
+
+ if ($validated)
+ {
+ $avatar = $this->request->getFile('claim_dump_list');
+ if (!$avatar) {
+ $this->myLogger->logme("error", 'File not found');
+ return $this->respond(['status' => false, 'code' => 400, 'message' => 'File not found'], 400);
+ }
+
+ $is_moved = $avatar->move(WRITEPATH . 'uploads/claim_dump_excel/');
+
+ if ($is_moved) {
+ $filename = $avatar->getName();
+ $fileSize = $avatar->getSize(); // File size in bytes
+ $fileSize = $fileSize / (1024 * 1024); // Convert to MB
+
+ $this->myLogger->logme("error", 'File move successful');
+
+ } else {
+ $this->myLogger->logme("error", 'File move failed');
+ return $this->respond(['status' => false, 'code' => 500, 'message' => 'File move failed'], 500);
+ }
+
+ } else {
+ $this->myLogger->logme("error", 'Upload failed Invalid file');
+ return $this->respond(['status' => false, 'code' => 404, 'message' => 'Invalid file'], 404);
+ }
+
+
+ $status = 'inprogress';
+ $insert_data = [
+ 'file_name' => $filename,
+ 'status' => $status
+ ];
+
+ $file_id = $this->claimDumpFileModel->insert($insert_data);
+ $this->myLogger->logme("error", 'claim_dumb_file_id : {file_id}, uploaded success', ['file_id' => $file_id]);
+
+ //after file upload success than call the file formate validation in service controller
+ $ticketServiceController = new TicketServiceController();
+ // $response = $ticketServiceController->claimDumpExcelFileFormatValidation(["file_id" => $file_id]);
+ $r = Jobs::addJob(['job_name' => 'claimDumpExcelFileFormatValidation', 'payload' => ['file_id' => $file_id]]);
+
+ return $this->respond(['status' => true, 'code' => 200, 'message' => 'File uploaded successfully. File being validated'], 200);
+
+ }
+ }
+
+ public function getClaimDumpFileErrorData()
+ {
+ $file_id = $this->request->getGet('file_id');
+ $file = $this->claimDumpFileModel->where('id', $file_id)->first();
+ if (!isset($file)) {
+ return $this->respond(['status' => false, 'code' => 404, 'message' => 'No data found'], 200);
+ } else {
+ return $this->respond(['status' => true, 'code' => 200, 'data' => $file['reason']], 200);
+ }
+ }
+
+ public function getClaimDumpExcelFileErrors($file_id)
+ {
+ // $file_id = $this->request->getGet('file_id');
+ $ticketServiceController = new TicketServiceController();
+
+ // Render views and capture output
+ $result = $ticketServiceController->getClaimExcelErrorData($file_id) ?? [];
+ // dd($result);
+
+ if ($result != 0) {
+
+ $result['file_id'] = $file_id;
+ echo view('excel_errors', $result);
+ } else if ($result == 0) {
+
+ $data['message'] = 'File Not Found Physically';
+ return view('errors/404', $data);
+ } else {
+
+ echo view('errors/html/production');
+ }
+ }
+
+ public function downloadClaimDumpFile($file_id)
+ {
+ // $actionType = $this->request->getGet();
+ $file_data = $this->claimDumpFileModel->where('id', $file_id)->first();
+ $fileName = $file_data['file_name'];
+
+ $filePath = WRITEPATH . '/uploads/claim_dump_excel/' . $fileName;
+
+ try {
+
+ // Check if the file exists
+ if (file_exists($filePath)) {
+ // Set the appropriate MIME type
+ $mimeType = mime_content_type($filePath);
+
+ // Send the file to the client for download
+ return $this->response->download($filePath, null, $mimeType);
+ } else {
+
+ $data['message'] = 'The Physical File Not Found';
+ echo view('errors/404', $data);
+ }
+ } catch (\Exception $e) {
+ // Handle any exceptions
+ $errorMessage = $e->getMessage();
+ $this->myLogger->logme('error', $errorMessage);
+ // You can return an error response here
+ echo $errorMessage;
+ }
+ }
}
diff --git a/app/Controllers/TicketServiceController.php b/app/Controllers/TicketServiceController.php
new file mode 100644
index 00000000..d2265378
--- /dev/null
+++ b/app/Controllers/TicketServiceController.php
@@ -0,0 +1,1823 @@
+myLogger = \Config\Services::mylogger();
+ set_session_context('Ticket Service Controller');
+
+ $this->claimDumpFileModel = new ClaimDumpFileModel();
+ $this->clientModel = new ClientModel();
+ $this->insurerModel = new InsurerModel();
+ $this->TPAModel = new TPAModel();
+ $this->ticketClaimStatusModel = new TicketClaimStatusModel();
+ $this->clientPolicyModel = new ClientPolicyModel();
+
+ $this->claim_dump_excel_columns = [
+
+ // Mandatory Fields
+ 'sno' => [
+ 'col_idx' => 0,
+ 'col_cell_name' => 'A',
+ 'col_name' => 'S.No.',
+ 'is_mandatory' => true,
+ 'data_type' => 'int',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+
+ 'policy_type' => [
+ 'col_idx' => 1,
+ 'col_cell_name' => 'B',
+ 'col_name' => 'Policy Type',
+ 'is_mandatory' => true,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => ['GMC', 'GPA', 'EDLI', 'GTLI']
+ ],
+
+ 'status' => [
+ 'col_idx' => 2,
+ 'col_cell_name' => 'C',
+ 'col_name' => 'Status',
+ 'is_mandatory' => true,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+
+ 'client_short_name' => [
+ 'col_idx' => 3,
+ 'col_cell_name' => 'D',
+ 'col_name' => 'Corporate Name',
+ 'is_mandatory' => true,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+
+ 'insurer' => [
+ 'col_idx' => 4,
+ 'col_cell_name' => 'E',
+ 'col_name' => 'Insurer',
+ 'is_mandatory' => true,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+
+ 'tpa' => [
+ 'col_idx' => 5,
+ 'col_cell_name' => 'F',
+ 'col_name' => 'TPA',
+ 'is_mandatory' => true,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+
+ 'policy_no' => [
+ 'col_idx' => 6,
+ 'col_cell_name' => 'G',
+ 'col_name' => 'Policy No',
+ 'is_mandatory' => true,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+
+ 'employee_code' => [
+ 'col_idx' => 7,
+ 'col_cell_name' => 'H',
+ 'col_name' => 'Employee Code',
+ 'is_mandatory' => true,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+
+ 'employee_name' => [
+ 'col_idx' => 8,
+ 'col_cell_name' => 'I',
+ 'col_name' => 'Employee Name',
+ 'is_mandatory' => true,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+
+ 'insured_name' => [
+ 'col_idx' => 9,
+ 'col_cell_name' => 'J',
+ 'col_name' => 'Insured Name',
+ 'is_mandatory' => true,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+
+ 'relationship' => [
+ 'col_idx' => 10,
+ 'col_cell_name' => 'K',
+ 'col_name' => 'Relationship',
+ 'is_mandatory' => true,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => ['Self', 'Spouse', 'Child', 'Parent', 'Other']
+ ],
+
+ 'mode_of_intimation' => [
+ 'col_idx' => 11,
+ 'col_cell_name' => 'L',
+ 'col_name' => 'Mode of Intimation',
+ 'is_mandatory' => true,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => ['Email', 'Phone', 'Portal', 'Physical']
+ ],
+
+ 'acm' => [
+ 'col_idx' => 12,
+ 'col_cell_name' => 'M',
+ 'col_name' => 'ACM',
+ 'is_mandatory' => false,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+
+ 'claim_type' => [
+ 'col_idx' => 13,
+ 'col_cell_name' => 'N',
+ 'col_name' => 'Claim Type',
+ 'is_mandatory' => true,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+
+ 'priority' => [
+ 'col_idx' => 14,
+ 'col_cell_name' => 'O',
+ 'col_name' => 'Priority',
+ 'is_mandatory' => true,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => ['Critical', 'Emergency', 'Urgent', 'High', 'Medium', 'Low']
+ ],
+
+ // Common Fields
+ 'date_of_birth' => [
+ 'col_idx' => 15,
+ 'col_cell_name' => 'P',
+ 'col_name' => 'Date of Birth',
+ 'is_mandatory' => false,
+ 'data_type' => 'date',
+ 'format' => 'd-m-Y',
+ 'allowed_values' => null
+ ],
+
+ 'employee_mobile' => [
+ 'col_idx' => 16,
+ 'col_cell_name' => 'Q',
+ 'col_name' => 'Employee Mobile',
+ 'is_mandatory' => false,
+ 'data_type' => 'str',
+ 'format' => '/^[0-9]{10}$/',
+ 'allowed_values' => null
+ ],
+
+ 'employee_email' => [
+ 'col_idx' => 17,
+ 'col_cell_name' => 'R',
+ 'col_name' => 'Employee Email',
+ 'is_mandatory' => false,
+ 'data_type' => 'str',
+ 'format' => 'email',
+ 'allowed_values' => null
+ ],
+
+ 'employee_personal_email' => [
+ 'col_idx' => 18,
+ 'col_cell_name' => 'S',
+ 'col_name' => 'Employee Personal Email',
+ 'is_mandatory' => false,
+ 'data_type' => 'str',
+ 'format' => 'email',
+ 'allowed_values' => null
+ ],
+
+ // GMC Specific Fields
+ 'hospital_name' => [
+ 'col_idx' => 19,
+ 'col_cell_name' => 'T',
+ 'col_name' => 'Hospital Name',
+ 'is_mandatory' => false,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+
+ 'doa' => [
+ 'col_idx' => 20,
+ 'col_cell_name' => 'U',
+ 'col_name' => 'DOA (Date of Admission)',
+ 'is_mandatory' => false,
+ 'data_type' => 'date',
+ 'format' => 'd-m-Y',
+ 'allowed_values' => null
+ ],
+
+ 'dod' => [
+ 'col_idx' => 21,
+ 'col_cell_name' => 'V',
+ 'col_name' => 'DOD (Date of Discharge)',
+ 'is_mandatory' => false,
+ 'data_type' => 'date',
+ 'format' => 'd-m-Y',
+ 'allowed_values' => null
+ ],
+
+ 'claim_amount' => [
+ 'col_idx' => 22,
+ 'col_cell_name' => 'W',
+ 'col_name' => 'Claim Amount',
+ 'is_mandatory' => false,
+ 'data_type' => 'decimal',
+ 'format' => '2',
+ 'allowed_values' => null
+ ],
+
+ 'pod_no' => [
+ 'col_idx' => 23,
+ 'col_cell_name' => 'X',
+ 'col_name' => 'POD No.',
+ 'is_mandatory' => false,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+
+ 'tpa_id' => [
+ 'col_idx' => 24,
+ 'col_cell_name' => 'Y',
+ 'col_name' => 'TPA ID',
+ 'is_mandatory' => false,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+
+ 'claim_number' => [
+ 'col_idx' => 25,
+ 'col_cell_name' => 'Z',
+ 'col_name' => 'Claim Number',
+ 'is_mandatory' => false,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+
+ // GPA Specific Fields
+ 'sum_insured' => [
+ 'col_idx' => 26,
+ 'col_cell_name' => 'AA',
+ 'col_name' => 'Sum Insured',
+ 'is_mandatory' => false,
+ 'data_type' => 'decimal',
+ 'format' => '2',
+ 'allowed_values' => null
+ ],
+
+ 'date_of_join' => [
+ 'col_idx' => 27,
+ 'col_cell_name' => 'AB',
+ 'col_name' => 'Date of Join',
+ 'is_mandatory' => false,
+ 'data_type' => 'date',
+ 'format' => 'd-m-Y',
+ 'allowed_values' => null
+ ],
+
+ 'date_of_inception' => [
+ 'col_idx' => 28,
+ 'col_cell_name' => 'AC',
+ 'col_name' => 'Date of Inception',
+ 'is_mandatory' => false,
+ 'data_type' => 'date',
+ 'format' => 'd-m-Y',
+ 'allowed_values' => null
+ ],
+
+ 'date_of_accident' => [
+ 'col_idx' => 29,
+ 'col_cell_name' => 'AD',
+ 'col_name' => 'Date of Accident',
+ 'is_mandatory' => false,
+ 'data_type' => 'date',
+ 'format' => 'd-m-Y',
+ 'allowed_values' => null
+ ],
+
+ 'date_of_death' => [
+ 'col_idx' => 30,
+ 'col_cell_name' => 'AE',
+ 'col_name' => 'Date of Death',
+ 'is_mandatory' => false,
+ 'data_type' => 'date',
+ 'format' => 'd-m-Y',
+ 'allowed_values' => null
+ ],
+
+ 'date_of_intimate' => [
+ 'col_idx' => 31,
+ 'col_cell_name' => 'AF',
+ 'col_name' => 'Date of Intimate',
+ 'is_mandatory' => false,
+ 'data_type' => 'date',
+ 'format' => 'd-m-Y',
+ 'allowed_values' => null
+ ],
+
+ // Status Wise Column Mandatory
+ 'raised_date' => [
+ 'col_idx' => 32,
+ 'col_cell_name' => 'AG',
+ 'col_name' => 'Raised Date',
+ 'is_mandatory' => false,
+ 'data_type' => 'date',
+ 'format' => 'd-m-Y',
+ 'allowed_values' => null
+ ],
+
+ 'registration_date' => [
+ 'col_idx' => 33,
+ 'col_cell_name' => 'AH',
+ 'col_name' => 'Registration Date',
+ 'is_mandatory' => false,
+ 'data_type' => 'date',
+ 'format' => 'd-m-Y',
+ 'allowed_values' => null
+ ],
+
+ 'query_received_date' => [
+ 'col_idx' => 34,
+ 'col_cell_name' => 'AI',
+ 'col_name' => 'Query Received Date',
+ 'is_mandatory' => false,
+ 'data_type' => 'date',
+ 'format' => 'd-m-Y',
+ 'allowed_values' => null
+ ],
+
+ 'payment_initiate_date' => [
+ 'col_idx' => 35,
+ 'col_cell_name' => 'AJ',
+ 'col_name' => 'Payment Initiate Date',
+ 'is_mandatory' => false,
+ 'data_type' => 'date',
+ 'format' => 'd-m-Y',
+ 'allowed_values' => null
+ ],
+
+ 'denial_reason' => [
+ 'col_idx' => 36,
+ 'col_cell_name' => 'AK',
+ 'col_name' => 'Denial Reason',
+ 'is_mandatory' => false,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+
+ 'denial_date' => [
+ 'col_idx' => 37,
+ 'col_cell_name' => 'AL',
+ 'col_name' => 'Denial Date',
+ 'is_mandatory' => false,
+ 'data_type' => 'date',
+ 'format' => 'd-m-Y',
+ 'allowed_values' => null
+ ],
+
+ 'approved_date' => [
+ 'col_idx' => 38,
+ 'col_cell_name' => 'AM',
+ 'col_name' => 'Approved Date',
+ 'is_mandatory' => false,
+ 'data_type' => 'date',
+ 'format' => 'd-m-Y',
+ 'allowed_values' => null
+ ],
+
+ 'approved_letter' => [
+ 'col_idx' => 39,
+ 'col_cell_name' => 'AN',
+ 'col_name' => 'Approved Letter',
+ 'is_mandatory' => false,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+
+ 'approved_amount' => [
+ 'col_idx' => 40,
+ 'col_cell_name' => 'AO',
+ 'col_name' => 'Approved Amount',
+ 'is_mandatory' => false,
+ 'data_type' => 'decimal',
+ 'format' => '2',
+ 'allowed_values' => null
+ ],
+
+ 'approved_description' => [
+ 'col_idx' => 41,
+ 'col_cell_name' => 'AP',
+ 'col_name' => 'Approved Description',
+ 'is_mandatory' => false,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+
+ 'utr_details' => [
+ 'col_idx' => 42,
+ 'col_cell_name' => 'AQ',
+ 'col_name' => 'UTR Details',
+ 'is_mandatory' => false,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+
+ 'settle_letter' => [
+ 'col_idx' => 43,
+ 'col_cell_name' => 'AR',
+ 'col_name' => 'Settle Letter',
+ 'is_mandatory' => false,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+
+ 'settled_date' => [
+ 'col_idx' => 44,
+ 'col_cell_name' => 'AS',
+ 'col_name' => 'Settled Date',
+ 'is_mandatory' => false,
+ 'data_type' => 'date',
+ 'format' => 'd-m-Y',
+ 'allowed_values' => null
+ ],
+
+ 'return_remark' => [
+ 'col_idx' => 45,
+ 'col_cell_name' => 'AT',
+ 'col_name' => 'Return Remark',
+ 'is_mandatory' => false,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+
+ 'cancel_remark' => [
+ 'col_idx' => 46,
+ 'col_cell_name' => 'AU',
+ 'col_name' => 'Cancel Remark',
+ 'is_mandatory' => false,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+
+ 'awb_courier' => [
+ 'col_idx' => 47,
+ 'col_cell_name' => 'AV',
+ 'col_name' => 'AWB No. and Courier Name',
+ 'is_mandatory' => false,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+
+ 'non_id_reason' => [
+ 'col_idx' => 48,
+ 'col_cell_name' => 'AW',
+ 'col_name' => 'Non ID Reason',
+ 'is_mandatory' => false,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null
+ ]
+ ];
+
+ $this->tableHeaders = [
+ "S NO",
+ "POLICY #",
+ "Status",
+ "Account manager",
+ "Insurer",
+ "TPA",
+ "Corporate",
+ "Emp ID",
+ "TPA ID",
+ "Claim ID",
+ "Employee Name",
+ "Insured Name",
+ "Relationship",
+ "Emp. Mobile",
+ "Emp mail id",
+ "Claim Collection",
+ "Source Detail",
+ "Claim Type",
+ "Hospital",
+ "DOA",
+ "DOD",
+ "Claim Amount",
+ "Date of Claim Receipt",
+ "Date sent to TPA",
+ "Date of Claim Registration",
+ "Date - Latest Query Raise",
+ "Date - Latest Query Resolution",
+ "Approved Amt",
+ "Date of Approval",
+ "UTR - Settlement",
+ "Date of Settlement",
+ "Reason",
+ "Remarks",
+ "Approval Letter",
+ "Settlement Letter",
+ "Denial Letter",
+ ];
+
+ $this->actualHeaders = [
+
+ "sno" => [
+ 'col_idx' => 0,
+ 'col_cell_name' => 'A',
+ 'col_name' => 'S NO',
+ 'is_mandatory' => true,
+ 'data_type' => 'int',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+ "corporate" => [
+ 'col_idx' => 6,
+ 'col_cell_name' => 'G',
+ 'col_name' => 'Corporate',
+ 'is_mandatory' => true,
+ 'data_type' => 'string',
+ 'format' => null,
+ 'allowed_values' => null,
+ 'custom' => 'check_client',
+ 'params' => ['client_excel_name']
+ ],
+ "policy_no" => [
+ 'col_idx' => 1,
+ 'col_cell_name' => 'B',
+ 'col_name' => 'POLICY #',
+ 'is_mandatory' => true,
+ 'data_type' => 'string',
+ 'format' => null,
+ 'allowed_values' => null,
+ ],
+ "status" => [
+ 'col_idx' => 2,
+ 'col_cell_name' => 'C',
+ 'col_name' => 'Status',
+ 'is_mandatory' => true,
+ 'data_type' => 'string',
+ 'format' => null,
+ 'allowed_values' => null,
+ 'custom' => 'check_status',
+ 'params' => ['excel_status_data']
+ ],
+ "acm" => [
+ 'col_idx' => 3,
+ 'col_cell_name' => 'D',
+ 'col_name' => 'Account manager',
+ 'is_mandatory' => false,
+ 'data_type' => 'string',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+ "insurer" => [
+ 'col_idx' => 4,
+ 'col_cell_name' => 'E',
+ 'col_name' => 'Insurer',
+ 'is_mandatory' => true,
+ 'data_type' => 'string',
+ 'format' => null,
+ 'allowed_values' => null,
+ 'custom' => 'check_insurer',
+ 'params' => ['insurer_excel_name']
+ ],
+ "tpa" => [
+ 'col_idx' => 5,
+ 'col_cell_name' => 'F',
+ 'col_name' => 'TPA',
+ 'is_mandatory' => false,
+ 'data_type' => 'string',
+ 'format' => null,
+ 'allowed_values' => null,
+ 'custom' => 'check_tpa',
+ 'params' => ['tpa_excel_name']
+ ],
+ "emp_id" => [
+ 'col_idx' => 7,
+ 'col_cell_name' => 'H',
+ 'col_name' => 'Emp ID',
+ 'is_mandatory' => true,
+ 'data_type' => 'string',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+ "tpa_id" => [
+ 'col_idx' => 8,
+ 'col_cell_name' => 'I',
+ 'col_name' => 'TPA ID',
+ 'is_mandatory' => false,
+ 'data_type' => 'string',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+ "claim_id" => [
+ 'col_idx' => 9,
+ 'col_cell_name' => 'J',
+ 'col_name' => 'Claim ID',
+ 'is_mandatory' => false,
+ 'data_type' => 'string',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+ "employee_name" => [
+ 'col_idx' => 10,
+ 'col_cell_name' => 'K',
+ 'col_name' => 'Employee Name',
+ 'is_mandatory' => true,
+ 'data_type' => 'string',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+ "insured_name" => [
+ 'col_idx' => 11,
+ 'col_cell_name' => 'L',
+ 'col_name' => 'Insured Name',
+ 'is_mandatory' => true,
+ 'data_type' => 'string',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+ "relationship" => [
+ 'col_idx' => 12,
+ 'col_cell_name' => 'M',
+ 'col_name' => 'Relationship',
+ 'is_mandatory' => true,
+ 'data_type' => 'string',
+ 'format' => null,
+ 'allowed_values' => ['self', 'spouse', 'son', 'daughter', 'father', 'mother', 'father-in-law', 'mother-in-law']
+ ],
+ "emp_mobile" => [
+ 'col_idx' => 13,
+ 'col_cell_name' => 'N',
+ 'col_name' => 'Emp. Mobile',
+ 'is_mandatory' => false,
+ 'data_type' => 'string',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+ "emp_email" => [
+ 'col_idx' => 14,
+ 'col_cell_name' => 'O',
+ 'col_name' => 'Emp mail id',
+ 'is_mandatory' => true,
+ 'data_type' => 'string',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+ "claim_collection" => [
+ 'col_idx' => 15,
+ 'col_cell_name' => 'P',
+ 'col_name' => 'Claim Collection',
+ 'is_mandatory' => true,
+ 'data_type' => 'string',
+ 'format' => null,
+ 'allowed_values' => ["In Person", "Courier", "Online Mode - Email", "Smart Service Desk", "Direct to TPA"]
+ ],
+ "source_detail" => [
+ 'col_idx' => 16,
+ 'col_cell_name' => 'Q',
+ 'col_name' => 'Source Detail',
+ 'is_mandatory' => false,
+ 'data_type' => 'string',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+ "claim_type" => [
+ 'col_idx' => 17,
+ 'col_cell_name' => 'R',
+ 'col_name' => 'Claim Type',
+ 'is_mandatory' => true,
+ 'data_type' => 'string',
+ 'format' => null,
+ 'allowed_values' => ["Claim", "Main Hospitalization", "Pre / Post", "OPD", "ReOpen", "TTD", "PTD", "PPD", "Death"]
+ ],
+ "hospital" => [
+ 'col_idx' => 18,
+ 'col_cell_name' => 'S',
+ 'col_name' => 'Hospital',
+ 'is_mandatory' => false,
+ 'data_type' => 'string',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+ "doa" => [
+ 'col_idx' => 19,
+ 'col_cell_name' => 'T',
+ 'col_name' => 'DOA',
+ 'is_mandatory' => false,
+ 'data_type' => 'date',
+ 'format' => 'd/m/Y',
+ 'allowed_values' => null
+ ],
+ "dod" => [
+ 'col_idx' => 20,
+ 'col_cell_name' => 'U',
+ 'col_name' => 'DOD',
+ 'is_mandatory' => false,
+ 'data_type' => 'date',
+ 'format' => 'd/m/Y',
+ 'allowed_values' => null
+ ],
+ "claim_amount" => [
+ 'col_idx' => 21,
+ 'col_cell_name' => 'V',
+ 'col_name' => 'Claim Amount',
+ 'is_mandatory' => false,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+ "date_claim_receipt" => [
+ 'col_idx' => 22,
+ 'col_cell_name' => 'W',
+ 'col_name' => 'Date of Claim Receipt',
+ 'is_mandatory' => false,
+ 'data_type' => 'date',
+ 'format' => 'd/m/Y',
+ 'allowed_values' => null
+ ],
+ "date_claim_registration" => [
+ 'col_idx' => 24,
+ 'col_cell_name' => 'Y',
+ 'col_name' => 'Date of Claim Registration',
+ 'is_mandatory' => false,
+ 'data_type' => 'date',
+ 'format' => 'd/m/Y',
+ 'allowed_values' => null
+ ],
+ "date_latest_query_raise" => [
+ 'col_idx' => 25,
+ 'col_cell_name' => 'Z',
+ 'col_name' => 'Date - Latest Query Raise',
+ 'is_mandatory' => false,
+ 'data_type' => 'date',
+ 'format' => 'd/m/Y',
+ 'allowed_values' => null
+ ],
+ "date_latest_query_resolution" => [
+ 'col_idx' => 26,
+ 'col_cell_name' => 'AA',
+ 'col_name' => 'Date - Latest Query Resolution',
+ 'is_mandatory' => false,
+ 'data_type' => 'date',
+ 'format' => 'd/m/Y',
+ 'allowed_values' => null
+ ],
+ "approved_amt" => [
+ 'col_idx' => 27,
+ 'col_cell_name' => 'AB',
+ 'col_name' => 'Approved Amt',
+ 'is_mandatory' => false,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+ "date_approval" => [
+ 'col_idx' => 28,
+ 'col_cell_name' => 'AC',
+ 'col_name' => 'Date of Approval',
+ 'is_mandatory' => false,
+ 'data_type' => 'date',
+ 'format' => 'd/m/Y',
+ 'allowed_values' => null
+ ],
+ "utr_settlement" => [
+ 'col_idx' => 29,
+ 'col_cell_name' => 'AD',
+ 'col_name' => 'UTR - Settlement',
+ 'is_mandatory' => false,
+ 'data_type' => 'string',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+ "date_settlement" => [
+ 'col_idx' => 30,
+ 'col_cell_name' => 'AE',
+ 'col_name' => 'Date of Settlement',
+ 'is_mandatory' => false,
+ 'data_type' => 'date',
+ 'format' => 'd/m/Y',
+ 'allowed_values' => null
+ ],
+ "reason" => [
+ 'col_idx' => 31,
+ 'col_cell_name' => 'AF',
+ 'col_name' => 'Reason',
+ 'is_mandatory' => false,
+ 'data_type' => 'text',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+ "remarks" => [
+ 'col_idx' => 32,
+ 'col_cell_name' => 'AG',
+ 'col_name' => 'Remarks',
+ 'is_mandatory' => false,
+ 'data_type' => 'text',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+ "approval_letter" => [
+ 'col_idx' => 33,
+ 'col_cell_name' => 'AH',
+ 'col_name' => 'Approval Letter',
+ 'is_mandatory' => false,
+ 'data_type' => 'string',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+ "settlement_letter" => [
+ 'col_idx' => 34,
+ 'col_cell_name' => 'AI',
+ 'col_name' => 'Settlement Letter',
+ 'is_mandatory' => false,
+ 'data_type' => 'string',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+ "denial_letter" => [
+ 'col_idx' => 35,
+ 'col_cell_name' => 'AJ',
+ 'col_name' => 'Denial Letter',
+ 'is_mandatory' => false,
+ 'data_type' => 'string',
+ 'format' => null,
+ 'allowed_values' => null
+ ]
+ ];
+
+ }
+
+ //create a sample excel for development
+ public function createSampleClaimDumpExcelFileWithHeaderOnly()
+ {
+
+ // create a sample file
+ $headers = [];
+ foreach ($this->claim_dump_excel_columns as $key => $value) {
+ $headers[] = $value['col_name'];
+ }
+ generateExcelWithHeader($headers, 'claim_dump_sample.xlsx');
+ dd($headers);
+ }
+
+ // ---------------------------------------------------------------------------------------------------------
+
+ public function claimDumpExcelFileFormatValidation($params)
+ {
+ $file_id = $params['file_id'];
+ $file = $this->claimDumpFileModel->where("id", $file_id)->first();
+ $this->myLogger->logme('error', "Start the claim dump file format validataion with the file id : " . $file_id);
+ // dd($file);
+
+ $return = [];
+ if (empty($file)) {
+ return array('status' => false, 'message' => 'File not found in Database');
+ }
+
+ $file_name_with_path = WRITEPATH . "/uploads/claim_dump_excel/" . $file['file_name'];
+
+ //check physical file exist
+ if (!file_exists($file_name_with_path)) {
+
+ $message = "Physcial file not found";
+ $this->myLogger->logme('error', ($message . ' for file id : ' . $file_id));
+ $this->claimDumpFileModel->where('id', $file_id)->set(['status' => 'failed', 'reason' => json_encode(['error_summary' => array_count_values([5]), 'error_data' => $message])])->update();
+ return array('error_summary' => [5], 'error_data' => $message);
+ }
+
+ //Read the excel file
+ try {
+ $excel_data_and_headers = $this->extractExcelData($file['file_name']);
+ $excel_data = $excel_data_and_headers['excel_data'];
+ } catch (\Exception $e) {
+ $errorDetails = [
+ 'error_message' => $e->getMessage(),
+ 'file' => $e->getFile(),
+ 'line' => $e->getLine(),
+ 'stack_trace' => $e->getTraceAsString(),
+ ];
+ $message = "Contact system admin";
+ $this->claimDumpFileModel->where('id', $file_id)->set(['status' => 'failed', 'reason' => json_encode(['error_summary' => array_count_values([5]), 'error_data' => $message])])->update();
+ $this->myLogger->logme("error", 'Excel data extraction failed due to : ' . json_encode($errorDetails ?? []));
+ return $errorDetails;
+ }
+ // dd($excel_data_and_headers);
+
+ //Claim dump excel colums
+ $columns_to_check = $excel_data_and_headers['claim_dump_excel_columns'];
+ // dd($columns_to_check);
+
+ //if upload the unwanted file upload handle
+ if(count($columns_to_check) == 0){
+ $message = "Wrong file was uploaded";
+ $this->claimDumpFileModel->where('id', $file_id)->set(['status' => 'failed', 'reason' => json_encode(['error_summary' => array_count_values([5]), 'error_data' => $message])])->update();
+ return array('error_summary' => [5], 'error_data' => $message);
+ }
+
+ //Store the error data by this structure
+ $result = ['error_type' => 1, 'error_summary' => [], 'error_data' => []];
+
+ //excel data is empty than through the error
+ if(count($excel_data ?? []) <= 1){
+ $message = "Uploaded file is empty";
+ $this->claimDumpFileModel->where('id', $file_id)->set(['status' => 'failed', 'reason' => json_encode(['error_summary' => array_count_values([5]), 'error_data' => $message])])->update();
+ return array('error_summary' => [5], 'error_data' => $message);
+ }
+
+ //check no of columns in excel
+ $excel_columns = ($excel_data[0]);
+ // $keys = array_keys($columns_to_check);
+
+ //check columns order in excel
+ $column_count_res = check_columns_name($columns_to_check, $excel_columns);
+ // dd($column_count_res);
+
+ if (isset($column_count_res) && count($column_count_res)) {
+ //columns count mismatch
+ $message = implode("\n", $column_count_res);
+ $this->myLogger->logme('error', ($message . ' for file id ' . $file_id));
+ $this->claimDumpFileModel->where('id', $file_id)->set(['status' => 'failed', 'reason' => json_encode(['error_summary' => array_count_values([6]), 'error_data' => $message])])->update();
+ return array('error_summary' => [6], 'error_data' => $message);
+ }
+
+ $client_data = $this->clientModel->where('is_active', 1)->where('client_type', 1)->findAll();
+ $insurer_data = $this->insurerModel->where('is_active', 1)->findAll();
+ $tpa_data = $this->TPAModel->where('is_active', 1)->findAll();
+ $claim_status_data = $this->ticketClaimStatusModel->select('id, claim_status')->where('is_active', 1)->orderBy('id', 'asc')->groupBy('claim_status')->findAll();
+
+ //remove header
+ unset($excel_data[0]);
+
+ try {
+ foreach ($excel_data as $row_key => $row) {
+
+ //avoid empty rows
+ if (check_row_is_empty_or_null($row)) {
+ break;
+ }
+
+ //iterate each row for columns validations
+ foreach ($row as $col_key => $col) {
+
+ if (!isset($columns_to_check[$col_key])) {
+ continue;
+ }
+
+ $is_mandatory = $columns_to_check[$col_key]['is_mandatory'];
+ $format = $columns_to_check[$col_key]['format'];
+ $allowed_values = $columns_to_check[$col_key]['allowed_values'];
+ $custom_function = isset($columns_to_check[$col_key]['custom']) ? $columns_to_check[$col_key]['custom'] : null;
+ $binding_params = isset($columns_to_check[$col_key]['params']) ? $columns_to_check[$col_key]['params'] : null;
+
+
+ $column_dispaly_name = $columns_to_check[$col_key]['col_name'];
+ $column_index = $columns_to_check[$col_key]['col_idx'];
+ $column_cell = $columns_to_check[$col_key]['col_cell_name'];
+
+
+ if ($column_dispaly_name == "Corporate") {
+ $client_excel_name = ["client_name" => $col, "client_data" => $client_data];
+ }
+
+ if ($column_dispaly_name == "Insurer") {
+ $insurer_excel_name = ["insurer_name" => $col, "insurer_data" => $insurer_data];
+ }
+
+ if ($column_dispaly_name == "TPA") {
+ $tpa_excel_name = ["tpa_name" => $col, "tpa_data" => $tpa_data];
+ }
+
+ if ($column_dispaly_name == "Status") {
+ $excel_status_data = ["value" => $col, "data" => $claim_status_data];
+ }
+
+ //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
+ $result['error_data'][$row_key][$col_key]['col_name'] = $column_dispaly_name; //push column name
+ $result['error_data'][$row_key][$col_key]['col_idx'] = $column_index; //push column index
+ $result['error_data'][$row_key][$col_key]['error'][] = 'Value is mandatory'; //push exact error desc
+ }
+ }
+
+ //format check
+ if (isset($format)) {
+ $format_error = dynamic_check_excel_date_format($col, $format);
+ if (!$format_error['status']) {
+ array_push($result['error_summary'], 2);
+ $result['error_data'][$row_key][$col_key]['col_name'] = $column_dispaly_name; //push column name
+ $result['error_data'][$row_key][$col_key]['col_idx'] = $column_index; //push column index
+ $result['error_data'][$row_key][$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)) {
+ array_push($result['error_summary'], 3);
+ $result['error_data'][$row_key][$col_key]['col_name'] = $column_dispaly_name; //push column name
+ $result['error_data'][$row_key][$col_key]['col_idx'] = $column_index; //push column index
+ $result['error_data'][$row_key][$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
+ $param_values = [];
+ foreach ($binding_params as $bkey => $bparam) {
+ $param_values[] = ($$bparam);
+ }
+
+ $res = call_user_func_array($custom_function, $param_values);
+
+ if ($res['status'] === false) {
+ array_push($result['error_summary'], 4);
+ $result['error_data'][$row_key][$col_key]['col_name'] = $column_dispaly_name; //push column name
+ $result['error_data'][$row_key][$col_key]['col_idx'] = $column_index; //push column index
+ $result['error_data'][$row_key][$col_key]['error'][] = $res['error'];
+ }
+ }
+ }
+ }
+ } catch (\Exception $e) {
+ $errorDetails = [
+ 'error_message' => $e->getMessage(),
+ 'file' => $e->getFile(),
+ 'line' => $e->getLine(),
+ 'stack_trace' => $e->getTraceAsString(),
+ ];
+ $message = "Contact system admin";
+ $this->claimDumpFileModel->where('id', $file_id)->set(['status' => 'failed', 'reason' => json_encode(['error_summary' => array_count_values([5]), 'error_data' => $message])])->update();
+ $this->myLogger->logme("error", 'Claim dump file format validation failed due to : ' . json_encode($errorDetails ?? []));
+ return $errorDetails;
+ }
+
+ 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->claimDumpFileModel->where('id', $file_id)->set(['status' => $status, 'reason' => $failure_reason])->update();
+ $this->myLogger->logme("error", '{file_id} uploaded failed', ['file_id' => $file_id]);
+ } else { //trigger next data validation via job queue server
+ //proceed next data level validation in JOB queue
+ $r = Jobs::addJob(['job_name' => 'claimDumpExcelFileDataValidation', 'payload' => ['file_id' => $file_id]]);
+ // $response = $this->claimDumpExcelFileDataValidation(['file_id' => $file_id]);
+ }
+
+ return $result;
+ }
+
+ public function claimDumpExcelFileDataValidation($params)
+ {
+ //get file name
+ $file_id = $params['file_id'];
+ $file = $this->claimDumpFileModel->find($file_id);
+ $this->myLogger->logme('error', "Start the claim dump File Data Validataion with the file id : " . $file_id);
+ // dd($file);
+
+ if (!isset($file)) {
+ return array('status' => false, 'message' => 'File not found in Database');
+ }
+
+ $file_name_with_path = WRITEPATH . "/uploads/claim_dump_excel/" . $file['file_name'];
+
+ //check physical file
+ if (!file_exists($file_name_with_path)) {
+ $message = "Physical file not found";
+ $this->myLogger->logme('error', ($message . ' for file id ' . $file_id));
+ $this->claimDumpFileModel->where('id', $file_id)->set(['status' => 'failed', 'reason' => json_encode(['error_summary' => array_count_values([5]), 'error_data' => $message])])->update();
+ return array('error_summary' => [5], 'error_data' => $message);
+ }
+
+ //Read the excel file
+ try {
+ $excel_data_and_headers = $this->extractExcelData($file['file_name'], "modified_column");
+ $excel_data = $excel_data_and_headers['excel_data'];
+ } catch (\Exception $e) {
+ $errorDetails = [
+ 'error_message' => $e->getMessage(),
+ 'file' => $e->getFile(),
+ 'line' => $e->getLine(),
+ 'stack_trace' => $e->getTraceAsString(),
+ ];
+ $message = "Contact system admin";
+ $this->claimDumpFileModel->where('id', $file_id)->set(['status' => 'failed', 'reason' => json_encode(['error_summary' => array_count_values([5]), 'error_data' => $message])])->update();
+ $this->myLogger->logme("error", 'Excel data extraction failed due to : ' . json_encode($errorDetails ?? []));
+ return $errorDetails;
+ }
+ // dd($excel_data_and_headers);
+ // print_rr($excel_data);
+
+ //Claim dump excel colums
+ $columns_to_check = $excel_data_and_headers['claim_dump_excel_columns'];
+ // dd($columns_to_check);
+
+ $result = ['error_type' => 1, 'error_summary' => [], 'error_data' => []];
+
+ //remove header
+ unset($excel_data[0]);
+
+ try {
+ foreach ($excel_data as $row_key => $row) {
+
+ //avoid empty rows
+ if (check_row_is_empty_or_null($row)) {
+ break;
+ }
+
+ $client_column_index = $columns_to_check['corporate']['col_idx'];
+ $policy_no_column_index = $columns_to_check['policy_no']['col_idx'];
+ $insurer_column_index = $columns_to_check['insurer']['col_idx'];
+ $tpa_column_index = $columns_to_check['tpa']['col_idx'];
+
+ $emp_id_column_index = $columns_to_check['emp_id']['col_idx'];
+ $emp_name_column_index = $columns_to_check['employee_name']['col_idx'];
+ $insured_name_column_index = $columns_to_check['insured_name']['col_idx'];
+ $claim_no_column_index = $columns_to_check['claim_id']['col_idx'];
+ $tpa_no_column_index = $columns_to_check['tpa_id']['col_idx'];
+ $relation_column_index = $columns_to_check['relationship']['col_idx'];
+ $acm_column_index = $columns_to_check['acm']['col_idx'];
+
+ //excel file Account Manager Details like Name and Mobile Number
+ $excel_acm_data = $row[$acm_column_index] ?? null;
+ // var_dump($excel_acm_data); die;
+
+ $acm_name = null;
+ $acm_mobile = null;
+
+ //seperate the Account Manager Name and Mobile No
+ if (!empty($excel_acm_data)) {
+ $excel_acm_data = str_replace(['–', '—'], '-', $excel_acm_data);
+ $parts = array_map('trim', explode('-', $excel_acm_data, 2));
+ $acm_name = $parts[0] ?? null;
+ $acm_mobile = $parts[1] ?? null;
+
+ // ensure mobile number is digits only
+ if ($acm_mobile !== null) {
+ $acm_mobile = preg_replace('/\D/', '', $acm_mobile);
+ }
+ }
+
+ // dd($acm_name, $acm_mobile);
+
+ $params = [
+ 'client_name' => $row[$client_column_index] ?? null,
+ 'policy_no' => $row[$policy_no_column_index] ?? null,
+ 'insurer_short_name' => $row[$insurer_column_index] ?? null,
+ 'tpa_short_name' => $row[$tpa_column_index] ?? null,
+ 'emp_code' => $row[$emp_id_column_index] ?? null,
+ 'emp_name' => $row[$emp_name_column_index] ?? null,
+ 'insured_name' => $row[$insured_name_column_index] ?? null,
+ 'claim_no' => $row[$claim_no_column_index] ?? null,
+ 'tpa_no' => $row[$tpa_no_column_index] ?? null,
+ 'relationship' => $row[$relation_column_index] ?? null,
+ 'acm_mobile' => $acm_mobile ?? null,
+ 'acm_name' => $acm_name ?? null,
+ ];
+
+ $ticketMasterModal = new TicketMasterModel();
+
+ //check the Claim
+ $claim_data = $ticketMasterModal->getTheClaimDetails($params);
+ // dd($claim_data);
+ if (count($claim_data) != 0) {
+
+ array_push($result['error_summary'], 7);
+ $result['error_data'][$row_key][$policy_no_column_index]['col_name'] = $columns_to_check['policy_no']['col_name']; //push column name
+ $result['error_data'][$row_key][$policy_no_column_index]['col_idx'] = $policy_no_column_index; //push column index
+ $result['error_data'][$row_key][$policy_no_column_index]['error'][] = "This claim already exist in the system";
+
+ } else {
+
+ //check the policy
+ $policy_data = $ticketMasterModal->getPolicyData($params);
+ // dd($policy_data);
+ if (count($policy_data) == 0) {
+
+ array_push($result['error_summary'], 8);
+ $result['error_data'][$row_key][$policy_no_column_index]['col_name'] = $columns_to_check['policy_no']['col_name']; //push column name
+ $result['error_data'][$row_key][$policy_no_column_index]['col_idx'] = $policy_no_column_index; //push column index
+ $result['error_data'][$row_key][$policy_no_column_index]['error'][] = "The combination of Client, Insurer, TPA and Policy No. does not exist in the system";
+
+ } else {
+
+ //check the employee and insured
+ $employee_data = $ticketMasterModal->getEmployeeAndEmployeePolicyDetails($params) ?? [];
+ // dd($employee_data);
+ if (count($employee_data) == 0) {
+ array_push($result['error_summary'], 9);
+ $result['error_data'][$row_key][$emp_name_column_index]['col_name'] = $columns_to_check['employee_name']['col_name']; //push column name
+ $result['error_data'][$row_key][$emp_name_column_index]['col_idx'] = $emp_name_column_index; //push column index
+ $result['error_data'][$row_key][$emp_name_column_index]['error'][] = "This employee not exist in the system";
+ }
+ }
+
+ //check the Account Manager exist
+ $acm_data = $ticketMasterModal->getAcmUserDetails($params) ?? [];
+ // dd($acm_data);
+ if (count($acm_data) == 0) {
+ array_push($result['error_summary'], 10);
+ $result['error_data'][$row_key][$acm_column_index]['col_name'] = $columns_to_check['acm']['col_name']; //push column name
+ $result['error_data'][$row_key][$acm_column_index]['col_idx'] = $acm_column_index; //push column index
+ $result['error_data'][$row_key][$acm_column_index]['error'][] = "This Acount Manager not exist in the system";
+ }
+ }
+
+ }
+ } catch (\Exception $e) {
+ $errorDetails = [
+ 'error_message' => $e->getMessage(),
+ 'file' => $e->getFile(),
+ 'line' => $e->getLine(),
+ 'stack_trace' => $e->getTraceAsString(),
+ ];
+ $message = "Contact system admin";
+ $this->claimDumpFileModel->where('id', $file_id)->set(['status' => 'failed', 'reason' => json_encode(['error_summary' => array_count_values([5]), 'error_data' => $message])])->update();
+ $this->myLogger->logme("error", 'Claim dump file data validation failed due to : ' . json_encode($errorDetails ?? []));
+ return $errorDetails;
+ }
+
+ 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->claimDumpFileModel->where('id', $file_id)->set(['status' => $status, 'reason' => $failure_reason])->update();
+ $this->myLogger->logme("error", '{file_id} uploaded failed', ['file_id' => $file_id]);
+
+ } else {
+ $r = Jobs::addJob(['job_name' => 'claimDumpOnBoardProcess', 'payload' => ['file_id' => $file_id]]);
+ }
+
+ return $result;
+ }
+
+ public function claimDumpOnBoardProcess($params)
+ {
+ //get file name
+ $file_id = $params['file_id'];
+ $file = $this->claimDumpFileModel->find($file_id);
+ $this->myLogger->logme('error', "Start the claim dump OnBoard Process with the file id : " . $file_id);
+ // dd($file);
+
+ if (!isset($file)) {
+ return array('status' => false, 'message' => 'File not found in Database');
+ }
+
+ $file_name_with_path = WRITEPATH . "/uploads/claim_dump_excel/" . $file['file_name'];
+
+ //check physical file
+ if (!file_exists($file_name_with_path)) {
+ $message = "Physical file not found";
+ $this->myLogger->logme('error', ($message . ' for file id ' . $file_id));
+ $this->claimDumpFileModel->where('id', $file_id)->set(['status' => 'failed', 'reason' => json_encode(['error_summary' => array_count_values([5]), 'error_data' => $message])])->update();
+ return array('error_summary' => [5], 'error_data' => $message);
+ }
+
+ //Read the excel file
+ try {
+ $excel_data_and_headers = $this->extractExcelData($file['file_name'], "modified_column");
+ $excel_data = $excel_data_and_headers['excel_data'];
+ unset($excel_data[0]); //remove header
+ } catch (\Exception $e) {
+ $errorDetails = [
+ 'error_message' => $e->getMessage(),
+ 'file' => $e->getFile(),
+ 'line' => $e->getLine(),
+ 'stack_trace' => $e->getTraceAsString(),
+ ];
+ $message = "Contact system admin";
+ $this->claimDumpFileModel->where('id', $file_id)->set(['status' => 'failed', 'reason' => json_encode(['error_summary' => array_count_values([5]), 'error_data' => $message])])->update();
+ $this->myLogger->logme("error", 'Excel data extraction failed due to : ' . json_encode($errorDetails ?? []));
+ return $errorDetails;
+ }
+ // dd($excel_data_and_headers);
+
+ //Claim dump excel colums
+ $columns_to_check = $excel_data_and_headers['claim_dump_excel_columns'];
+
+ //create the instance of the ticket master modal
+ $ticketMasterModal = new TicketMasterModel();
+
+ $inserted_claim_list = [];
+ //loop the excel data to be insert the ticket master modal
+
+ try{
+ foreach ($excel_data as $row_key => $row) {
+
+ //avoid empty rows
+ if (check_row_is_empty_or_null($row)) {
+ break;
+ }
+
+ $client_column_index = $columns_to_check['corporate']['col_idx'];
+ $policy_no_column_index = $columns_to_check['policy_no']['col_idx'];
+ $insurer_column_index = $columns_to_check['insurer']['col_idx'];
+ $tpa_column_index = $columns_to_check['tpa']['col_idx'];
+ $emp_id_column_index = $columns_to_check['emp_id']['col_idx'];
+ $emp_name_column_index = $columns_to_check['employee_name']['col_idx'];
+ $insured_name_column_index = $columns_to_check['insured_name']['col_idx'];
+ $claim_no_column_index = $columns_to_check['claim_id']['col_idx'];
+ $tpa_no_column_index = $columns_to_check['tpa_id']['col_idx'];
+ $relation_column_index = $columns_to_check['relationship']['col_idx'];
+
+ $params = [
+ 'client_name' => $row[$client_column_index] ?? null,
+ 'policy_no' => $row[$policy_no_column_index] ?? null,
+ 'insurer_short_name' => $row[$insurer_column_index] ?? null,
+ 'tpa_short_name' => $row[$tpa_column_index] ?? null,
+ 'emp_code' => $row[$emp_id_column_index] ?? null,
+ 'emp_name' => $row[$emp_name_column_index] ?? null,
+ 'insured_name' => $row[$insured_name_column_index] ?? null,
+ 'claim_no' => $row[$claim_no_column_index] ?? null,
+ 'tpa_no' => $row[$tpa_no_column_index] ?? null,
+ 'relationship' => $row[$relation_column_index] ?? null,
+ ];
+
+ // get the policy data
+ $policy_data = $ticketMasterModal->getEmployeeAndEmployeePolicyDetails($params);
+ // dd($policy_data);
+
+ //construct the claim data to be insert
+ $data = $this->constructClaimData($row, $policy_data, $columns_to_check);
+ // dd($data);
+
+ if(!empty($data)){
+
+ $data['file_id'] = $file_id;
+ //insert the claim data to ticket master table
+ $insert = $ticketMasterModal->insert($data);
+ $inserted_claim_list[] = $insert;
+
+ $str = implode(', ', array_map(fn($k, $v) => "$k=$v", array_keys($params), $params)) ?? "";
+ $this->myLogger->logme("error",'Claim insert success --- :' . $str);
+
+ }else{
+ $str = implode(', ', array_map(fn($k, $v) => "$k=$v", array_keys($params), $params)) ?? "";
+ $this->myLogger->logme("error",'This employee claim dose not insert --- :' . $str);
+ }
+
+
+ }
+ }catch(\Exception $e){
+ $errorDetails = [
+ 'error_message' => $e->getMessage(),
+ 'file' => $e->getFile(),
+ 'line' => $e->getLine(),
+ 'stack_trace' => $e->getTraceAsString(),
+ ];
+ $message = "Contact system admin";
+ $this->claimDumpFileModel->where('id', $file_id)->set(['status' => 'failed', 'reason' => json_encode(['error_summary' => array_count_values([5]), 'error_data' => $message])])->update();
+ $this->myLogger->logme("error", 'Claim dump file Onboard Process failed due to : ' . json_encode( $errorDetails ?? []));
+ return $errorDetails;
+ }
+
+ $this->claimDumpFileModel->where('id', $file_id)->set(['status' => 'success','reason' => ''])->update();
+ $this->myLogger->logme("error",'{file_id} claim dump uploaded success',['file_id' => $file_id]);
+ return $inserted_claim_list;
+ }
+
+ public function extractExcelData($file_name, $returnType = null)
+ {
+ // $file_name = "claims_dump_form_client.xlsx";
+ // Load the Excel file
+ $file_name_with_path = WRITEPATH . "/uploads/claim_dump_excel/" . $file_name;
+ $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file_name_with_path);
+ $worksheet = $spreadsheet->getActiveSheet();
+
+ // Get the highest row and column numbers
+ $highestRow = $worksheet->getHighestDataRow();
+ $highestColumn = $worksheet->getHighestDataColumn();
+ // dd($highestRow, $highestColumn);
+
+ // Get header row (assuming headers are in row 1)
+ // $headerRow = $worksheet->rangeToArray('A1:' . $highestColumn . '1', null, true, false)[0];
+ $excel_data = $worksheet->rangeToArray('A1:' . $highestColumn . $highestRow);
+ // print_rr($excel_data); die;
+
+ $header_with_column_index = $this->getTheColumnIndex($excel_data[0], $this->actualHeaders, $returnType);
+
+ //Sanitize the excel data
+ $excel_data = ExcelSanitizeHelper::sanitizeArrayData($excel_data);
+ // dd($excel_data);
+
+ $data = [
+ 'claim_dump_excel_columns' => $header_with_column_index,
+ 'excel_data' => $excel_data,
+ ];
+
+ // dd($data);
+ return $data;
+ }
+
+ private function getTheColumnIndex($headerRow, $definedColumns, $returnType = null)
+ {
+ $result = [];
+ foreach ($definedColumns as $key => $value) {
+ foreach ($headerRow as $col_index => $col_name) {
+
+ if($returnType == null){
+ if(trim($col_name) == trim($value['col_name'])){
+ $columnLetter = Coordinate::stringFromColumnIndex(($col_index + 1));
+ $result[$col_index] = $value;
+ $result[$col_index]["col_idx"] = $col_index;
+ $result[$col_index]["col_cell_name"] = $columnLetter;
+ }
+ }else{
+ if(trim($col_name) == trim($value['col_name'])){
+ $columnLetter = Coordinate::stringFromColumnIndex(($col_index + 1));
+ $definedColumns[$key]["col_idx"] = $col_index;
+ $definedColumns[$key]["col_cell_name"] = $columnLetter;
+ }
+ }
+ }
+ }
+
+ // dd($result);
+ if($returnType == null){
+ return $result;
+ }
+
+ return $definedColumns;
+
+ }
+
+ private function constructClaimData($excel_data, $db_data, $columns_to_check)
+ {
+ // dd($db_data);
+ $client_column_index = $columns_to_check['corporate']['col_idx'];
+ $policy_no_column_index = $columns_to_check['policy_no']['col_idx'];
+ $insurer_column_index = $columns_to_check['insurer']['col_idx'];
+ $tpa_column_index = $columns_to_check['tpa']['col_idx'];
+
+ $emp_id_column_index = $columns_to_check['emp_id']['col_idx'];
+ $emp_name_column_index = $columns_to_check['employee_name']['col_idx'];
+ $insured_name_column_index = $columns_to_check['insured_name']['col_idx'];
+ $claim_no_column_index = $columns_to_check['claim_id']['col_idx'];
+ $tpa_no_column_index = $columns_to_check['tpa_id']['col_idx'];
+ $relation_column_index = $columns_to_check['relationship']['col_idx'];
+
+ $status_column_index = $columns_to_check['status']['col_idx'];
+ $acm_column_index = $columns_to_check['acm']['col_idx'];
+ $tpa_id_column_index = $columns_to_check['tpa_id']['col_idx'];
+ $claim_id_column_index = $columns_to_check['claim_id']['col_idx'];
+ $emp_mobile_column_index = $columns_to_check['emp_mobile']['col_idx'];
+ $emp_email_column_index = $columns_to_check['emp_email']['col_idx'];
+ $claim_collection_column_index = $columns_to_check['claim_collection']['col_idx'];
+ $source_detail_column_index = $columns_to_check['source_detail']['col_idx'];
+ $claim_type_column_index = $columns_to_check['claim_type']['col_idx'];
+ $hospital_column_index = $columns_to_check['hospital']['col_idx'];
+ $doa_column_index = $columns_to_check['doa']['col_idx'];
+ $dod_column_index = $columns_to_check['dod']['col_idx'];
+ $claim_amount_column_index = $columns_to_check['claim_amount']['col_idx'];
+ $date_claim_receipt_column_index = $columns_to_check['date_claim_receipt']['col_idx'];
+ $date_claim_registration_column_index = $columns_to_check['date_claim_registration']['col_idx'];
+ $date_latest_query_raise_column_index = $columns_to_check['date_latest_query_raise']['col_idx'];
+ $date_latest_query_resolution_index = $columns_to_check['date_latest_query_resolution']['col_idx'];
+ $approved_amt_column_index = $columns_to_check['approved_amt']['col_idx'];
+ $date_approval_column_index = $columns_to_check['date_approval']['col_idx'];
+ $utr_settlement_column_index = $columns_to_check['utr_settlement']['col_idx'];
+ $date_settlement_column_index = $columns_to_check['date_settlement']['col_idx'];
+ $reason_column_index = $columns_to_check['reason']['col_idx'];
+ $remarks_column_index = $columns_to_check['remarks']['col_idx'];
+ $approval_letter_column_index = $columns_to_check['approval_letter']['col_idx'];
+ $settlement_letter_column_index = $columns_to_check['settlement_letter']['col_idx'];
+ $denial_letter_column_index = $columns_to_check['denial_letter']['col_idx'];
+
+ $excel_status_data = $excel_data[$status_column_index] ?? null;
+ $excel_relationship_data = $excel_data[$relation_column_index] ?? null;
+ $excel_acm_data = $excel_data[$acm_column_index] ?? null;
+ $excel_tpa_id_data = $excel_data[$tpa_id_column_index] ?? null;
+ $excel_claim_id_data = $excel_data[$claim_id_column_index] ?? null;
+ $excel_emp_mobile_data = $excel_data[$emp_mobile_column_index] ?? null;
+ $excel_emp_email_data = $excel_data[$emp_email_column_index] ?? null;
+ $excel_claim_collection_data = $excel_data[$claim_collection_column_index] ?? null;
+ $excel_source_detail_data = $excel_data[$source_detail_column_index] ?? null;
+ $excel_claim_type_data = $excel_data[$claim_type_column_index] ?? null;
+ $excel_hospital_data = $excel_data[$hospital_column_index] ?? null;
+ $excel_doa_data = $excel_data[$doa_column_index] ?? null;
+ $excel_dod_data = $excel_data[$dod_column_index] ?? null;
+ $excel_claim_amount_data = $excel_data[$claim_amount_column_index] ?? null;
+ $excel_date_claim_receipt_data = $excel_data[$date_claim_receipt_column_index] ?? null;
+ $excel_date_claim_registration_data = $excel_data[$date_claim_registration_column_index] ?? null;
+ $excel_date_latest_query_raise_data = $excel_data[$date_latest_query_raise_column_index] ?? null;
+ $excel_date_latest_query_resolution_data = $excel_data[$date_latest_query_resolution_index] ?? null;
+ $excel_approved_amt_data = $excel_data[$approved_amt_column_index] ?? null;
+ $excel_date_approval_data = $excel_data[$date_approval_column_index] ?? null;
+ $excel_utr_settlement_data = $excel_data[$utr_settlement_column_index] ?? null;
+ $excel_date_settlement_data = $excel_data[$date_settlement_column_index] ?? null;
+ $excel_reason_data = $excel_data[$reason_column_index] ?? null;
+ $excel_remarks_data = $excel_data[$remarks_column_index] ?? null;
+ $excel_approval_letter_data = $excel_data[$approval_letter_column_index] ?? null;
+ $excel_settlement_letter_data = $excel_data[$settlement_letter_column_index] ?? null;
+ $excel_denial_letter_data = $excel_data[$denial_letter_column_index] ?? null;
+
+
+ //create the instance of the ticket master modal
+ $ticketMasterModal = new TicketMasterModel();
+
+ //excel file Account Manager Details like Name and Mobile Number
+ $excel_acm_data = $excel_data[$acm_column_index] ?? null;
+
+ $acm_name = null;
+ $acm_mobile = null;
+
+ //seperate the Account Manager Name and Mobile No
+ if (!empty($excel_acm_data)) {
+ $parts = array_map('trim', explode('-', $excel_acm_data, 2));
+ $acm_name = $parts[0] ?? null;
+ $acm_mobile = $parts[1] ?? null;
+ }
+
+ $params = [
+ "acm_name" => $acm_name,
+ "acm_mobile" => $acm_mobile,
+ ];
+
+ //get the acountmanager data
+ $acm_data = $ticketMasterModal->getAcmUserDetails($params) ?? [];
+ // dd($acm_data);
+
+ //get the claim status id from the database
+ $claim_status_data = $this->ticketClaimStatusModel
+ ->select('id, claim_status, ticket_type')
+ ->where('is_active', 1)
+ ->where('ticket_type', $db_data['ticket_type_id'])
+ ->where('LOWER(claim_status)', strtolower($excel_status_data))
+ ->first();
+
+ // dd($claim_status_data);
+
+ $claim_status_id = $claim_status_data['id'] ?? null;
+
+ //initialize Ticket controller for the other data
+ $ticketController = new TicketController();
+ $mode_of_intimation = array_flip($ticketController->modeOFIntimate);
+
+ //handle the Claim Type data key
+ $cliam_type_id = 1;
+ if(isset($db_data['ticket_type_id'])){
+ if($db_data['ticket_type_id'] == 2){
+ $claim_type = array_flip($ticketController->claimType[1]);
+ $cliam_type_id = $claim_type[$excel_claim_type_data] ?? 1;
+ }else{
+ $claim_type = array_flip($ticketController->claimType[2]);
+ $cliam_type_id = $claim_type[$excel_claim_type_data] ?? 1;
+ }
+ }
+
+ $db_data['insured_name'] = $excel_data[$insured_name_column_index] ?? null;
+ //get Insured emp name and Insured emp id
+ $insured_data = $ticketMasterModal->getInsuredDetails($db_data);
+ // dd($insured_data);
+
+ //handle remarks based on the status
+ $return_remarks = null;
+ $cancel_remarks = null;
+ $denial_reason = null;
+ if(strtolower($excel_status_data) == strtolower('RETURNED')){
+ $return_remarks = $excel_remarks_data ?? null;
+ }else if(strtolower($excel_status_data) == strtolower('CANCELLED')){
+ $cancel_remarks = $excel_remarks_data ?? null;
+ }else if(strtolower($excel_status_data) == strtolower('REJECTED')){
+ $denial_reason = $excel_reason_data ?? null;
+ }
+
+ $ticketMaster = [
+ 'ticket_type_id' => $db_data['ticket_type_id'] ?? null,
+ 'claim_status_id' => $claim_status_id ?? null,
+ 'acm_id' => $acm_data['id'] ?? null,
+ 'insurer_id' => $db_data['insurer_id'] ?? null,
+ 'tpa_id' => $db_data['tpa_id'] ?? null,
+ 'client_id' => $db_data['client_id'] ?? null,
+ 'emp_id' => $db_data['emp_id'] ?? null,
+ 'client_policy_id' => $db_data['client_policy_id'] ?? null,
+ 'policy_no' => $db_data['policy_no'] ?? null,
+ 'emp_code' => $db_data['emp_code'] ?? null,
+ 'tpa_no' => $excel_tpa_id_data ?? $db_data['tpa_no'] ?? null,
+ 'emp_name' => $db_data['emp_name'] ?? null,
+ 'relationship' => strtolower($excel_relationship_data) ?? null,
+ 'emp_mobile' => $excel_emp_mobile_data ?? $db_data['emp_mobile'] ?? null,
+ 'emp_mail' => $excel_emp_email_data ?? $db_data['emp_mail'] ?? null,
+
+ 'mode_of_intimation' => $mode_of_intimation[$excel_claim_collection_data] ?? null,
+ 'claim_type' => $cliam_type_id ?? null,
+
+ 'insured_emp_id' => $insured_data['emp_id'] ?? null,
+ 'insured_name' => $insured_data['name'] ?? $excel_data[$insured_name_column_index] ?? null,
+
+ 'hospital_name' => $excel_hospital_data ?? null,
+ 'claim_amount' => $excel_claim_amount_data ?? null,
+ 'claim_number' => $excel_claim_id_data ?? null,
+ 'approved_letter' => $excel_approval_letter_data ?? null,
+ 'approved_amount' => $excel_approved_amt_data ?? null,
+ 'utr_details' => $excel_utr_settlement_data ?? null,
+ 'settle_letter' => $excel_settlement_letter_data ?? null,
+ 'return_remark' => $return_remarks,
+ 'cancel_remark' => $cancel_remarks,
+ 'denial_reason' => $denial_reason ?? null,
+
+ 'doa' => normalizeDate($excel_doa_data),
+ 'dod' => normalizeDate($excel_dod_data),
+ 'raised_date' => normalizeDate($excel_date_latest_query_raise_data),
+ 'registration_date' => normalizeDate($excel_date_claim_registration_data),
+ 'query_received_date' => normalizeDate($excel_date_latest_query_resolution_data),
+ 'approved_date' => normalizeDate($excel_date_approval_data),
+ 'settled_date' => normalizeDate($excel_date_settlement_data),
+
+ 'priority' => null,
+ 'emp_personal_mail' => null,
+ 'pod_no' => null,
+ 'dob' => null,
+ 'date_of_join' => null,
+ 'date_of_incep' => null,
+ 'date_of_accident' => null,
+ 'date_of_death' => null,
+ 'date_of_intimat' => null,
+ 'si_amt' => null,
+ 'denial_date' => null,
+ 'awb_no_courier_name' => null,
+ 'non_id_reason' => null,
+ 'pay_initiate_date' => null,
+ 'approved_description' => null
+ ];
+
+ // dd($ticketMaster);
+ return $ticketMaster;
+ }
+
+ public function getClaimExcelErrorData($file_id)
+ {
+ try {
+
+ $file = $this->claimDumpFileModel->where('id', $file_id)->first();
+ $error_data = json_decode($file['reason']);
+ // dd($error_data);
+
+ $file_name_with_path = WRITEPATH . "/uploads/claim_dump_excel/" . $file['file_name'];
+
+ //check the file exist or not
+ if (!file_exists($file_name_with_path)) {
+ $error_message = "File not found";
+ $this->myLogger->logme('error', ($error_message . ' for file id ' . $file_id));
+ return 0;
+ }
+
+ $excel_data_and_headers = $this->extractExcelData($file['file_name']);
+ $excel_data = $excel_data_and_headers['excel_data'];
+ $excelErrorData['excel_header'] = $excel_data[0];
+ unset($excel_data[0]);
+
+ // Kint::dump($excel_data);
+ if ($error_data->error_type == 1) {
+
+ $finalArray = [];
+ 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,];
+ $excel_data[$key][$value2->col_idx] = $data;
+ }
+ array_push($finalArray, $excel_data[$key]);
+ }
+
+ foreach ($finalArray as $fkey => $value) {
+ foreach ($value as $vkey => $arrayData) {
+ if (!is_array($arrayData)) {
+ $data = ['value' => $arrayData];
+ $finalArray[$fkey][$vkey] = $data;
+ }
+ }
+ }
+
+ $excelErrorData['excel_data'] = $finalArray;
+ return $excelErrorData;
+ } else if ($error_data->error_type == 2) {
+
+
+ $allErrors = [];
+ $typeTowArray = [];
+
+ foreach ($error_data->error_data as $index => $item) {
+
+ foreach ($item as $field) {
+ if (!isset($allErrors[$index])) {
+ $allErrors[$index] = [];
+ }
+ $allErrors[$index] = array_merge($allErrors[$index], $field->error);
+ }
+ }
+
+ // dd(array_keys($allErrors));
+ foreach ($allErrors as $key => $value) {
+ // echo $key;
+ // 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,];
+ $excel_data[$excel_data_index][1] = $data;
+ array_push($typeTowArray, $excel_data[$excel_data_index]);
+ break;
+ }
+ }
+ }
+ // dd($data);
+ foreach ($typeTowArray as $fkey => $value) {
+ foreach ($value as $vkey => $arrayData) {
+ if (!is_array($arrayData)) {
+ $data = ['value' => $arrayData];
+ $typeTowArray[$fkey][$vkey] = $data;
+ }
+ }
+ }
+
+ $excelErrorData['excel_data'] = $typeTowArray;
+ return $excelErrorData;
+ }
+ } catch (\Exception $e) {
+ // Handle any exceptions
+ $errorMessage = $e->getMessage(); //die();
+ $this->myLogger->logme('error', $errorMessage);
+ return false; // You can return an error response here
+ }
+ }
+
+ public function truncateClaimDumpFile($file_id)
+ {
+
+ }
+
+}
diff --git a/app/Controllers/UserController.php b/app/Controllers/UserController.php
index 78d3a6c0..255b6507 100755
--- a/app/Controllers/UserController.php
+++ b/app/Controllers/UserController.php
@@ -18,6 +18,8 @@ use App\Models\UserTeamsModel;
use App\Helpers\BookStackUserHelper;
use App\Models\AuthHistoryModel;
use App\Models\UserActivityHistoryModel;
+use App\Models\PartnerStaffModel;
+use App\Models\PartnerManagerIncentiveFileModel;
class UserController extends AdminController
@@ -32,6 +34,8 @@ class UserController extends AdminController
protected $bookStack;
protected $authHistoryModel;
protected $userActivityHistoryModel;
+ protected $partnerStaffModel;
+ protected $partnerManagerIncentiveFileModel;
public function __construct()
{
@@ -45,6 +49,8 @@ class UserController extends AdminController
$this->bookStack = new BookStackUserHelper();
$this->authHistoryModel = new AuthHistoryModel();
$this->userActivityHistoryModel = new UserActivityHistoryModel();
+ $this->partnerStaffModel = new PartnerStaffModel();
+ $this->partnerManagerIncentiveFileModel = new PartnerManagerIncentiveFileModel();
}
public function list()
@@ -563,4 +569,226 @@ class UserController extends AdminController
}
}
+ public function partner()
+ {
+ $method = $this->request->getMethod(); // get, post
+ try{
+ // Listing
+ if ($method === 'get') {
+ $types = $this->partnerStaffModel->findAll();
+ if (empty($types)) {
+ return $this->response->setJSON(['status' => 'error','message' => 'No Staff found'])->setStatusCode(404);
+ }
+ return $this->response->setJSON(['status' => 'success','data' => $types])->setStatusCode(200);
+ }
+
+ // add/update
+ if ($method === 'post') {
+
+ $data = $this->request->getPost();
+ if (!empty($data['id'])) {
+ $text = "update";
+ $result = $this->partnerStaffModel->update($data['id'], $data);
+ $updateID = $data['id'];
+ } else {
+ $text = "create";
+ $data['role_id'] = 1;
+ $data['created_by'] = get_session_userid();
+ $insertID = $this->partnerStaffModel->insert($data);
+ $result = true;
+ }
+
+ $id = isset($insertID) && !empty($insertID) ? $insertID : ($updateID ?? null);
+
+ return $this->response->setJSON([
+ 'status' => $id ? 'success' : 'error',
+ 'message' => $id ? "Staff {$text}d successfully" : "Unable to {$text} staff. Please try again.",
+ 'id' => $id
+ ])->setStatusCode($id ? 200 : 400);
+ }
+
+ // delete
+ if ($method === 'put') {
+ $data = $this->request->getRawInput();
+ $id = $data['id'] ?? null;
+
+ if (!$id) {
+ return $this->response->setJSON(['status' => 'error', 'message' => 'ID is required'])->setStatusCode(400);
+ }
+
+ $staff = $this->partnerStaffModel->find($id);
+ if (!$staff) {
+ return $this->response->setJSON(['status' => 'error','message' => 'Staff not found'])->setStatusCode(404);
+ }
+
+ if ($staff['is_active'] == 1) {
+ $result = $this->partnerStaffModel->update($id, ['is_active' => 0]);
+ $message = "Staff deleted successfully";
+ } else {
+ return $this->response->setJSON(['status' => 'error','message' => 'Staff already deleted'])->setStatusCode(400);
+ }
+
+ return $this->response->setJSON([
+ 'status' => $result ? 'success' : 'error',
+ 'message' => $result ? $message : "Unable to delete staff. Please try again.",
+ 'id' => $id
+ ])->setStatusCode($result ? 200 : 400);
+ }
+ return $this->response->setJSON([ 'status' => 'error', 'message' => 'Invalid request method' ])->setStatusCode(405);
+ }
+ catch (\Throwable $e) {
+ $code = ($e->getCode() && $e->getCode() >= 100 && $e->getCode() < 600) ? $e->getCode() : 500;
+
+ $isDbError = $e instanceof \CodeIgniter\Database\Exceptions\DatabaseException
+ || $e instanceof \mysqli_sql_exception
+ || $e instanceof \PDOException;
+
+ $context = ['title' => get_class($e),'type' => get_class($e),'code' => $code,'message' => $e->getMessage(),'file' => $e->getFile(),'line' => $e->getLine()];
+
+ $this->myLogger->logme('error', "Exception: {message} in {file} on line {line}", $context, 0);
+
+ return $this->response->setJSON([ 'status' => 'error', 'message' => $isDbError ? 'Data Access Error' : $e->getMessage(),
+ 'ref' => $isDbError ? 'database - ' : 'application - ' . $code . ' - ' . $e->getLine()
+ ])->setStatusCode($code);
+ }
+ }
+
+ public function partnerIncentive()
+ {
+ $method = $this->request->getMethod(); // get, post
+ try{
+ // Listing
+ if ($method === 'get') {
+ $manager_id = $this->request->getGet('manager_id');
+ $files = $this->partnerManagerIncentiveFileModel->where('manager_id', $manager_id)->findAll();
+ if (empty($files)) {
+ return $this->response->setJSON(['status' => 'error','message' => 'No Records found'])->setStatusCode(404);
+ }
+ return $this->response->setJSON(['status' => 'success','data' => $files])->setStatusCode(200);
+ }
+
+ // add/update
+ if ($method === 'post') {
+
+ $file = $this->request->getFile('incentive_file_name');
+ $month = $this->request->getPost('incentive_month');
+ $managerId = $this->request->getPost('manager_id');
+ $fileId = $this->request->getPost('id');
+
+ if ($file && $file->isValid() && !$file->hasMoved()) {
+
+ $originalName = $file->getClientName();
+ $extension = $file->getExtension();
+
+ $fileName = pathinfo($originalName, PATHINFO_FILENAME) . '_' . date('Ymd_His') . '.' . $extension;
+
+ $path = WRITEPATH . 'uploads/incentives';
+ $file->move($path, $fileName);
+ $data = [
+ 'manager_id' => $managerId,
+ 'incentive_month' => date('M Y', strtotime($month)),
+ 'incentive_file_name' => $fileName,
+ 'created_by' => get_session_userid()
+ ];
+
+ if ($fileId) {
+ $text = "update";
+ $this->partnerManagerIncentiveFileModel->update($fileId, $data);
+ $updateID = $data['id'];
+ } else {
+ $text = "create";
+ $insertID = $this->partnerManagerIncentiveFileModel->insert($data);
+ $result = true;
+ }
+
+ $id = isset($insertID) && !empty($insertID) ? $insertID : ($updateID ?? null);
+
+ return $this->response->setJSON([
+ 'status' => $id ? 'success' : 'error',
+ 'message' => $id ? "File {$text}d successfully" : "Unable to {$text} file. Please try again.",
+ 'id' => $id
+ ])->setStatusCode($id ? 200 : 400);
+ }
+ return $this->response->setJSON([
+ 'status' => 'error',
+ 'message' => "Unable to Upload file. Please try again.",
+ 'id' => ''
+ ])->setStatusCode(400);
+ }
+
+ // delete
+ if ($method === 'put') {
+ $data = $this->request->getRawInput();
+ $id = $data['id'] ?? null;
+
+ if (!$id) {
+ return $this->response->setJSON(['status' => 'error', 'message' => 'ID is required'])->setStatusCode(400);
+ }
+
+ $files = $this->partnerManagerIncentiveFileModel->find($id);
+ if (!$files) {
+ return $this->response->setJSON(['status' => 'error','message' => 'No Records found'])->setStatusCode(404);
+ }
+
+ if ($files['is_active'] == 1) {
+ $result = $this->partnerManagerIncentiveFileModel->update($id, ['is_active' => 0]);
+ $message = "Files deleted successfully";
+ } else {
+ return $this->response->setJSON(['status' => 'error','message' => 'files already deleted'])->setStatusCode(400);
+ }
+
+ return $this->response->setJSON([
+ 'status' => $result ? 'success' : 'error',
+ 'message' => $result ? $message : "Unable to delete staff. Please try again.",
+ 'id' => $id
+ ])->setStatusCode($result ? 200 : 400);
+ }
+ return $this->response->setJSON([ 'status' => 'error', 'message' => 'Invalid request method' ])->setStatusCode(405);
+ }
+ catch (\Throwable $e) {
+ $code = ($e->getCode() && $e->getCode() >= 100 && $e->getCode() < 600) ? $e->getCode() : 500;
+
+ $isDbError = $e instanceof \CodeIgniter\Database\Exceptions\DatabaseException
+ || $e instanceof \mysqli_sql_exception
+ || $e instanceof \PDOException;
+
+ $context = ['title' => get_class($e),'type' => get_class($e),'code' => $code,'message' => $e->getMessage(),'file' => $e->getFile(),'line' => $e->getLine()];
+
+ $this->myLogger->logme('error', "Exception: {message} in {file} on line {line}", $context, 0);
+
+ return $this->response->setJSON([ 'status' => 'error', 'message' => $isDbError ? 'Data Access Error' : $e->getMessage(),
+ 'ref' => $isDbError ? 'database - ' : 'application - ' . $code . ' - ' . $e->getLine()
+ ])->setStatusCode($code);
+ }
+ }
+
+ public function downloadIncentivesFile($file_id)
+ {
+ try {
+ $result = $this->partnerManagerIncentiveFileModel->where('id', $file_id)->first();
+
+ if (!$result || empty($result['incentive_file_name'])) {
+ throw new \Exception("File Name Not Found");
+ }
+
+ $incentive_file_name = $result['incentive_file_name'];
+ $file_name = basename($incentive_file_name);
+ $filePath = WRITEPATH . 'uploads/incentives/' . $file_name;
+
+ if (file_exists($filePath)) {
+ return $this->response->download($filePath, null);
+ } else {
+ throw new \Exception("File Not Found");
+ }
+
+ } catch (\Exception $e) {
+
+ $this->myLogger->logme('error', $e->getMessage());
+
+ // Show 404 error view
+ $data['message'] = $e->getMessage();
+ return view('errors/404', $data);
+ }
+ }
+
}
\ No newline at end of file
diff --git a/app/Controllers/VidalApiController.php b/app/Controllers/VidalApiController.php
index 259e9841..36dc3f01 100644
--- a/app/Controllers/VidalApiController.php
+++ b/app/Controllers/VidalApiController.php
@@ -123,13 +123,21 @@ class VidalApiController extends BaseController
}
- public function newClaim(){
-
+ public function newClaim()
+ {
$postData = $this->request->getPost();
+ if (empty($postData)) {
+ return $this->response->setJSON([
+ 'status' => false,
+ 'message' => 'Empty Data Given.',
+ 'data' => $postData
+ ]);
+ }
+
helper('api');
- $url = ''. getenv('VIDAL_API_BASE_URL').'/submitClaim';
+ $url = getenv('VIDAL_API_BASE_URL') . '/submitClaim';
$method = 'POST';
$headers = [
@@ -138,27 +146,38 @@ class VidalApiController extends BaseController
];
$body = [
- 'username:' .getenv('VIDAL_API_USERNAME').'',
- 'password:' .getenv('VIDAL_API_PASSWORD').'',
- 'PolicyNo:' .$postData['policyNo'] ?? '',
- 'enrollmentId:' .$postData['enrollmentId'] ?? '',
- 'typeOfClaim:' .$postData['typeOfClaim'] ?? '',
- 'claimSubType:' .$postData['claimSubType'] ?? '',
- 'requestedAmount:' .$postData['requestedAmount'] ?? '',
- 'ailmentType:' .$postData['ailmentType'] ?? '',
- 'admissionDate:' .$postData['admissionDate'] ?? '',
- 'dischargeDate:' .$postData['dischargeDate'] ?? '',
- 'hospitalName:' .$postData['hospitalName'] ?? '',
- 'empanelmentNo:' .$postData['empanelmentNo'] ?? '',
- 'documentType:' .$postData['documentType'] ?? '',
- 'ailmentName:' .$postData['ailmentName'] ?? '',
- 'hospitalAddress:' .$postData['hospitalAddress'] ?? '',
- 'hospitalState:' .$postData['hospitalState'] ?? '',
- 'hospitalCity:' .$postData['hospitalCity'] ?? '',
- 'hospitalPinCode:' .$postData['hospitalPinCode'] ?? '',
- 'hospitalPhoneNo:' .$postData['hospitalPhoneNo'] ?? ''
+ 'username' => getenv('VIDAL_API_USERNAME'),
+ 'password' => getenv('VIDAL_API_PASSWORD'),
+ 'policyNo' => $postData['policyNo'] ?? '',
+ 'enrollmentId' => $postData['enrollmentId'] ?? '',
+ 'typeOfClaim' => $postData['typeOfClaim'] ?? '',
+ 'claimSubType' => $postData['claimSubType'] ?? '',
+ 'requestedAmount' => $postData['requestedAmount'] ?? '',
+ 'ailmentType' => $postData['ailmentType'] ?? '',
+ 'admissionDate' => $postData['admissionDate'] ?? '',
+ 'dischargeDate' => $postData['dischargeDate'] ?? '',
+ 'hospitalName' => $postData['hospitalName'] ?? '',
+ 'empanelmentNo' => $postData['empanelmentNo'] ?? '',
+ 'documentType' => $postData['documentType'] ?? '',
+ 'ailmentName' => $postData['ailmentName'] ?? '',
+ 'hospitalAddress' => $postData['hospitalAddress'] ?? '',
+ 'hospitalState' => $postData['hospitalState'] ?? '',
+ 'hospitalCity' => $postData['hospitalCity'] ?? '',
+ 'hospitalPinCode' => $postData['hospitalPinCode'] ?? '',
+ 'hospitalPhoneNo' => $postData['hospitalPhoneNo'] ?? '',
];
+ // ✅ Handle file upload
+ if ($file = $this->request->getFile('File')) {
+ if ($file->isValid() && !$file->hasMoved()) {
+ $filePath = $file->getTempName();
+ $originalName = $file->getClientName();
+ $mimeType = $file->getMimeType();
+
+ $body['File'] = new \CURLFile($filePath, $mimeType, $originalName);
+ }
+ }
+
$response = call_third_party_api($url, $method, $headers, $body);
if($response['status'] != true){
@@ -170,10 +189,10 @@ class VidalApiController extends BaseController
}
return $this->response->setJSON($response);
-
}
+
public function enrollment(){
$postData = $this->request->getJSON(true);
diff --git a/app/Helpers/ChatbotHelper.php b/app/Helpers/ChatbotHelper.php
index 3ec5eb31..db0e2e3e 100644
--- a/app/Helpers/ChatbotHelper.php
+++ b/app/Helpers/ChatbotHelper.php
@@ -395,18 +395,18 @@ class ChatbotHelper
-
+
-
+
-
+
@@ -414,12 +414,12 @@ class ChatbotHelper
-
+
-
+
@@ -451,7 +451,7 @@ class ChatbotHelper
-
+
@@ -459,7 +459,7 @@ class ChatbotHelper
-
+
@@ -494,7 +494,7 @@ class ChatbotHelper
-
+
@@ -502,7 +502,7 @@ class ChatbotHelper
-
+
@@ -516,7 +516,7 @@ class ChatbotHelper
-
+
diff --git a/app/Helpers/MailHelper.php b/app/Helpers/MailHelper.php
index cce74a9a..89e90262 100755
--- a/app/Helpers/MailHelper.php
+++ b/app/Helpers/MailHelper.php
@@ -322,6 +322,7 @@ class MailHelper
$from_address = isset($params['from_mail']) && !empty($params['from_mail']) ? $params['from_mail'] : getenv('email.fromEmail');
// $from_address = "claims@nhanceindia.in";
+ if(isset($params['common'])){ $params['common']['from_mail'] = $from_address; }
try {
$curl = curl_init();
diff --git a/app/Helpers/api_helper.php b/app/Helpers/api_helper.php
index de9a0b64..95096fdb 100644
--- a/app/Helpers/api_helper.php
+++ b/app/Helpers/api_helper.php
@@ -59,6 +59,7 @@ if (!function_exists('call_third_party_api')) {
}
$decoded = json_decode($response, true);
+
return [
'status' => ($httpCode >= 200 && $httpCode < 300),
'data' => $decoded ?: $response, // fallback to raw response
diff --git a/app/Helpers/claim_dump_helper.php b/app/Helpers/claim_dump_helper.php
new file mode 100644
index 00000000..6f740e8a
--- /dev/null
+++ b/app/Helpers/claim_dump_helper.php
@@ -0,0 +1,179 @@
+ $value) {
+ // Kint::dump($value['client_name'], $client_name);
+ if(trim($value['client_name']) === trim($client_name)){
+ return array('status' => true, 'client_id' => $value['id'], 'error' => '');
+ }
+ }
+ }
+
+ return array('status' => false, 'error' => 'This Client Name does not exist in the system');
+ }
+}
+
+if (!function_exists('check_insurer')) {
+ function check_insurer($params)
+ {
+ $insurer_data = $params['insurer_data'] ?? [];
+ $insurer_name = $params['insurer_name'] ?? "";
+ if (!empty($insurer_data)) {
+ foreach ($insurer_data as $key => $value) {
+ if(trim($value['short_name']) === trim($insurer_name)){
+ return array('status' => true, 'insuer_id' => $value['id'], 'error' => '');
+ }
+ }
+ }
+
+ return array('status' => false, 'error' => 'This Insurer does not exist in the system');
+
+ }
+}
+
+if (!function_exists('check_tpa')) {
+ function check_tpa($params)
+ {
+ $tpa_data = $params['tpa_data'] ?? [];
+ $tpa_name = $params['tpa_name'] ?? "";
+ if (!empty($tpa_data)) {
+ foreach ($tpa_data as $key => $value) {
+ if(trim($value['short_name']) === trim($tpa_name)){
+ return array('status' => true, 'tpa_id' => $value['id'], 'error' => '');
+ }
+ }
+ }
+
+ return array('status' => false, 'error' => 'This TPA does not exist in the system');
+ }
+}
+
+if (!function_exists('check_status')) {
+ function check_status($params)
+ {
+ $data = $params['data'] ?? [];
+ $check_value = $params['value'] ?? "";
+ if (!empty($data)) {
+ foreach ($data as $key => $value) {
+ // Kint::dump(strtolower(trim($value['claim_status'])), strtolower(trim($check_value)));
+ if(strtolower(trim($value['claim_status'])) === strtolower(trim($check_value))){
+ return array('status' => true, 'status_id' => $value['id'], 'error' => '');
+ }
+ }
+ }
+
+ return array('status' => false, 'error' => "This Status ('{$check_value}') does not exist in the system");
+ }
+}
+
+if (!function_exists('check_policy')) {
+ function check_policy($params)
+ {
+ $data = $params['data'] ?? [];
+ $client_id = $params['client_id'] ?? "";
+ $check_value = $params['value'] ?? "";
+ if (!empty($data)) {
+ foreach ($data as $key => $value) {
+ if($value['client_id'] === $client_id && trim($value['policy_no']) === trim($check_value)){
+ return array('status' => true, 'status_id' => $value['id'], 'error' => '');
+ }
+ }
+ }
+
+ return array('status' => false, 'error' => "This Policy Number does not exist in the Client");
+ }
+}
+
+if (!function_exists('check_emp_and_insured')) {
+ function check_emp_and_insured($params)
+ {
+
+ $employee_modal = new EmployeeModel();
+ $tpa_data = $employee_modal
+ ->join('employee_polices', 'employees.id = employee_polices.employee_id')
+ ->where('employees.client', $params['client_id'])
+ ->where('employees.name', $params['emp_name'])
+ ->where('employees.emp_code', $params['emp_code'])
+ ->where('employees.is_active', 1)
+ ->where('employees.emp_status !=', "truncated")
+ ->where('employee_polices.is_active', 1)
+ ->where('employees.status !=', "truncated")
+ ->first();
+
+ if (empty($tpa_data)) {
+ return false;
+ }
+
+ return $tpa_data['id'];
+ }
+}
+
+if (!function_exists('dynamic_check_excel_date_format')) {
+
+ function dynamic_check_excel_date_format($dateString, $format = 'd/m/Y')
+ {
+
+ if ($dateString == "") {
+ return array('status' => true);
+ }
+ $date = DateTime::createFromFormat($format, $dateString);
+
+ if ($date && $date->format($format) == $dateString) {
+ return array('status' => true);
+ } else {
+
+ $res = validate_date_flexible($dateString, $format);
+ if (!$res) {
+ return array('status' => false, 'error' => "wrong date format: Expected {$format}({$res}) and received $dateString");
+ } else {
+ return array('status' => true);
+ }
+ }
+ }
+}
+
+if (!function_exists('validate_date_flexible')) {
+ function validate_date_flexible($date, $format = 'm/d/Y')
+ {
+ // Create a DateTime from the given format
+ $d = DateTime::createFromFormat($format, $date);
+ if (!$d) return false;
+
+ // Compare normalized values (remove leading zeros)
+ $original = preg_replace('/\b0+/', '', $date);
+ $normalized = preg_replace('/\b0+/', '', $d->format($format));
+
+ return $original === $normalized;
+ }
+}
+
+if (!function_exists('normalizeDate')) {
+ function normalizeDate($dateString, $formats = ['d-m-Y', 'd/m/Y', 'm-d-Y', 'm/d/Y', 'Y-m-d'])
+ {
+ if (empty($dateString)) {
+ return null; // keep null if no value
+ }
+
+ foreach ($formats as $format) {
+ $dt = DateTime::createFromFormat($format, trim($dateString));
+ if ($dt && $dt->format($format) === trim($dateString)) {
+ return $dt->format('Y-m-d'); // ✅ return in DB format
+ }
+ }
+
+ return null; // if no valid format found
+ }
+}
+
+?>
\ No newline at end of file
diff --git a/app/Helpers/header.php b/app/Helpers/header.php
index 2ade2b0b..f696e91b 100755
--- a/app/Helpers/header.php
+++ b/app/Helpers/header.php
@@ -73,7 +73,7 @@
body[data-sidebar-size=condensed]:not([data-layout=compact]):not(.auth-fluid-pages) {
- min-height: 0;
+ max-height:100vh !important;
}
.navbar-custom {
@@ -267,7 +267,6 @@
.right-bar {
- width: 300px;
/* Adjust as needed */
overflow: hidden;
}
@@ -616,7 +615,7 @@
-
+
2
App Content Management
diff --git a/app/Helpers/sendMailNotification.php b/app/Helpers/sendMailNotification.php
index bd66c776..f9de6b09 100755
--- a/app/Helpers/sendMailNotification.php
+++ b/app/Helpers/sendMailNotification.php
@@ -305,7 +305,7 @@ class sendMailNotification
}
$table_content .= $policy_name_for_policy_type . '';
- $table_content .= '';
+ $table_content .= '';
// Add text-align: center to the table head
$table_content .= '';
@@ -442,7 +442,7 @@ class sendMailNotification
}
$table_content .= $policy_name_for_policy_type . ' ( Payable By Employee ) ';
- $table_content .= '';
+ $table_content .= '';
// Add text-align: center to the table head
$table_content .= '';
@@ -479,7 +479,7 @@ class sendMailNotification
if (count($Addon_list) > 0) {
$table_content .= '';
- $table_content .= '
';
+ $table_content .= '';
// Center align for table header and body
$table_content .= '';
@@ -655,7 +655,7 @@ class sendMailNotification
}
$table_content .= $policy_name_for_policy_type . '';
- $table_content .= '';
+ $table_content .= '';
// Add text-align: center to the table head
$table_content .= '';
@@ -741,7 +741,7 @@ class sendMailNotification
}
$table_content .= $policy_name_for_policy_type . ' ( Payable By Employee ) ';
- $table_content .= '';
+ $table_content .= '';
// Add text-align: center to the table head
$table_content .= '';
@@ -779,7 +779,7 @@ class sendMailNotification
if (count($Addon_list) > 0) {
$table_content .= '';
- $table_content .= '
';
+ $table_content .= '';
// Center align for table header and body
$table_content .= '';
@@ -956,7 +956,7 @@ class sendMailNotification
}
$table_content .= $policy_name_for_policy_type . '';
- $table_content .= '';
+ $table_content .= '';
// Add text-align: center to the table head
$table_content .= '';
@@ -1042,7 +1042,7 @@ class sendMailNotification
}
$table_content .= $policy_name_for_policy_type . ' ( Payable By Employee ) ';
- $table_content .= '';
+ $table_content .= '';
// Add text-align: center to the table head
$table_content .= '';
@@ -1079,7 +1079,7 @@ class sendMailNotification
if (count($Addon_list) > 0) {
$table_content .= '';
- $table_content .= '
';
+ $table_content .= '';
// Center align for table header and body
$table_content .= '';
@@ -1332,7 +1332,7 @@ class sendMailNotification
// Start table row
$table_content .= $policy_name . '';
- $table_content .= '';
+ $table_content .= '';
$table_content .= '';
$table_content .= '';
$table_content .= 'Name ';
@@ -1384,7 +1384,7 @@ class sendMailNotification
// Generate summary table for addon if applicable
if (count($Addon_list) > 0) {
$table_content .= '';
- $table_content .= '
';
+ $table_content .= '';
$table_content .= '';
$table_content .= '';
@@ -1482,7 +1482,7 @@ class sendMailNotification
// Start table row
$table_content .= $policy_name . '';
- $table_content .= '';
+ $table_content .= '';
$table_content .= '';
$table_content .= '';
$table_content .= 'Name ';
@@ -1534,7 +1534,7 @@ class sendMailNotification
// Generate summary table for addon if applicable
if (count($Addon_list) > 0) {
$table_content .= '';
- $table_content .= '
';
+ $table_content .= '';
$table_content .= '';
$table_content .= '';
@@ -1630,7 +1630,7 @@ class sendMailNotification
// Start table row
$table_content .= $policy_name . '';
- $table_content .= '';
+ $table_content .= '';
$table_content .= '';
$table_content .= '';
$table_content .= 'Name ';
@@ -1683,7 +1683,7 @@ class sendMailNotification
if (count($Addon_list) > 0) {
$table_content .= '';
- $table_content .= '
';
+ $table_content .= '';
$table_content .= '';
$table_content .= '';
diff --git a/app/Helpers/utility_helper.php b/app/Helpers/utility_helper.php
index eae819ea..c03ffcc9 100755
--- a/app/Helpers/utility_helper.php
+++ b/app/Helpers/utility_helper.php
@@ -64,6 +64,79 @@ if (!function_exists('file_Upload')) {
}
}
+// if (!function_exists('multi_file_Upload')) {
+// function multi_file_Upload($fileToUpload, $filepath)
+// {
+// $uploadedFiles = [];
+
+// // Handle multiple files
+// if (is_array($fileToUpload)) {
+// foreach ($fileToUpload as $file) {
+// if ($file !== null && $file->isValid() && !$file->hasMoved()) {
+// $file->move($filepath);
+// $fileName = $file->getName(); // safer unique name
+// $uploadedFiles[] = [
+// 'file_name' => $fileName,
+// 'file_path' => $filepath . $fileName
+// ];
+// }
+// }
+// }
+// // Handle single file
+// else {
+// if ($fileToUpload !== null && $fileToUpload->isValid() && !$fileToUpload->hasMoved()) {
+// $fileToUpload->move($filepath);
+// $fileName = $fileToUpload->getName();
+// $uploadedFiles[] = [
+// 'file_name' => $fileName,
+// 'file_path' => $filepath . $fileName
+// ];
+// }
+// }
+
+// return $uploadedFiles; // always return array of files
+// }
+// }
+
+if (!function_exists('multi_file_Upload')) {
+ function multi_file_Upload($fileToUpload, $filepath)
+ {
+ $uploadedFiles = [];
+
+ // Normalize: always work with an array of UploadedFile objects
+ $files = is_array($fileToUpload) ? $fileToUpload : [$fileToUpload];
+
+ foreach ($files as $file) {
+ // If file is itself an array (multiple under same input name)
+ if (is_array($file)) {
+ foreach ($file as $f) {
+ if ($f !== null && $f->isValid() && !$f->hasMoved()) {
+ $fileName = $f->getRandomName(); // safer unique name
+ $f->move($filepath, $fileName);
+ $uploadedFiles[] = [
+ 'file_name' => $fileName,
+ 'file_path' => $filepath . $fileName
+ ];
+ }
+ }
+ } else {
+ // Single file
+ if ($file !== null && $file->isValid() && !$file->hasMoved()) {
+ $fileName = $file->getRandomName();
+ $file->move($filepath, $fileName);
+ $uploadedFiles[] = [
+ 'file_name' => $fileName,
+ 'file_path' => $filepath . $fileName
+ ];
+ }
+ }
+ }
+
+ return $uploadedFiles; // always return array
+ }
+}
+
+
if (!function_exists('file_unlink')) {
function file_unlink($filepath)
{
diff --git a/app/Models/BatchFileModel.php b/app/Models/BatchFileModel.php
index b8ebc8e9..e791553a 100755
--- a/app/Models/BatchFileModel.php
+++ b/app/Models/BatchFileModel.php
@@ -25,6 +25,7 @@ class BatchFileModel extends Model
"status",
"error_data",
"client_branch_id",
+ "policy_issue_date",
];
// Callbacks
diff --git a/app/Models/ClaimDumpFileModel.php b/app/Models/ClaimDumpFileModel.php
new file mode 100644
index 00000000..224adafc
--- /dev/null
+++ b/app/Models/ClaimDumpFileModel.php
@@ -0,0 +1,56 @@
+where('client_id', $id)
- ->where('user_id', $user_id)
- ->where('level', $level)
- ->countAllResults();
+ ->where('user_id', $user_id)
+ ->where('level', $level)
+ ->countAllResults();
return ($query > 0) ? true : false;
}
- public function getAllClientRM(){
+ public function getAllClientRM()
+ {
return $this->db->table('client_rm')
- ->select('client_rm.client_id, client_rm.level,')
- ->select('user_profiles.first_name as account_manager')
- ->join('user_profiles', 'user_profiles.id = client_rm.user_id')
- ->where('level', 3)
- ->get()
- ->getResult();
-
+ ->select('client_rm.client_id, client_rm.level,')
+ ->select('user_profiles.first_name as account_manager')
+ ->join('user_profiles', 'user_profiles.id = client_rm.user_id')
+ ->where('level', 3)
+ ->get()
+ ->getResult();
}
+ public function findAccountManagerEmail($client_id)
+ {
+ $builder = $this->db->table('client_rm');
+ $builder->select('user_profiles.email');
+ $builder->join('user_profiles', 'user_profiles.id = client_rm.user_id');
+ $builder->where('client_rm.client_id', $client_id);
+ $builder->where('client_rm.level', 3); // Assuming level 3 is for account managers
+ $result = $builder->get()->getResultArray();
+
+ if (count($result) > 0) {
+ // Extract just the email values into a simple string array
+ return array_column($result, 'email');
+ } else {
+ return null; // or []
+ }
+ }
}
diff --git a/app/Models/FileModel.php b/app/Models/FileModel.php
index 5b27a7d4..ff4f584e 100755
--- a/app/Models/FileModel.php
+++ b/app/Models/FileModel.php
@@ -20,7 +20,8 @@ class FileModel extends Model
"policy_id",
"client_branch_id",
"uploaded_by",
- "updated_by"
+ "updated_by",
+ "hr_file_id",
];
diff --git a/app/Models/GmailSentHistoryModel.php b/app/Models/GmailSentHistoryModel.php
index 9a0ae8ea..75abbbe0 100644
--- a/app/Models/GmailSentHistoryModel.php
+++ b/app/Models/GmailSentHistoryModel.php
@@ -7,5 +7,5 @@ use CodeIgniter\Model;
class GmailSentHistoryModel extends Model{
protected $table = 'gmail_sent_history';
protected $primaryKey = 'id';
- protected $allowedFields = ["id", "mail", "bcc", "cc", "message", "attachments", "client_id", "client_branch_id", "client_policy_id", "employee_policy_id", "employee_id", "mail_type", "gmail_api_status", "gmail_api_id", "created_by", "created_at", "updated_by", "updated_at", "isactive","received_message"];
+ protected $allowedFields = ["id", "mail", "bcc", "cc", "message", "attachments", "client_id", "client_branch_id", "client_policy_id", "employee_policy_id", "employee_id", "mail_type", "gmail_api_status", "gmail_api_id", "module", "pk", "from_mail", "created_by", "created_at", "updated_by", "updated_at", "isactive","received_message", "common"];
}
\ No newline at end of file
diff --git a/app/Models/HrFileUploadModel.php b/app/Models/HrFileUploadModel.php
new file mode 100644
index 00000000..c7d9b945
--- /dev/null
+++ b/app/Models/HrFileUploadModel.php
@@ -0,0 +1,35 @@
+select('
level_contacts.id,
insurers.short_name as insurer_name,
+ insurers.id as insurer_id,
insurer_branch.branch_code,
+ insurer_branch.id as insurer_branch_id,
level_contacts.name as contact_person_name,
level_contacts.email as contact_person_email
')
@@ -51,7 +53,7 @@ class LevelContactModel extends Model
$query->where('insurer_branch.insurer_id', $insurer_id);
}
- $result = $query->get()->getResultArray();
+ $result = $query->orderBy('insurers.id')->get()->getResultArray();
return $result;
}
diff --git a/app/Models/PartnerEndorsementRequestModel.php b/app/Models/PartnerEndorsementRequestModel.php
new file mode 100755
index 00000000..083c832d
--- /dev/null
+++ b/app/Models/PartnerEndorsementRequestModel.php
@@ -0,0 +1,89 @@
+db->table('partner_endorsement_request per')
+ ->distinct()
+ ->select('
+ per.id,
+ per.client_id,
+ per.client_policy_id,
+ per.insurer_id,
+ per.insurer_branch_id,
+ per.policy_number,
+ per.endorsement_no,
+ per.endorsement_type,
+ per.endorsement_description,
+ per.created_at,
+ per.updated_by,
+ per.updated_at,
+ per.is_active,
+ per.created_by,
+ per.manager_id,
+ per.agent_id,
+ per.status,
+ i.name as insurer_name,
+ i.short_name as insurer_short_name,
+ c.client_name,
+ c.short_name as client_short_name,
+ ps.name as manager_name,
+ pa.name as agent_name
+ ')
+ ->join('insurers as i', 'i.id = per.insurer_id', 'left')
+ ->join('clients as c', 'c.id = per.client_id AND c.client_type = 2', 'left')
+ ->join('partner_staff as ps', 'ps.id = per.manager_id AND ps.role_id = 1', 'left')
+ ->join('partner_agent as pa', 'pa.id = per.agent_id', 'left');
+
+ if (!empty($status)) {
+ $query->where('per.status', $status);
+ }
+ if (!empty($client_id)) {
+ $query->where('per.client_id', $client_id);
+ }
+ if (!empty($insurers_id)) {
+ $query->where('per.insurer_id', $insurers_id);
+ }
+
+ $query->orderBy('per.id', 'desc');
+
+ return $query->get()->getResultArray();
+ }
+
+}
diff --git a/app/Models/PartnerManagerIncentiveFileModel.php b/app/Models/PartnerManagerIncentiveFileModel.php
new file mode 100755
index 00000000..32e59444
--- /dev/null
+++ b/app/Models/PartnerManagerIncentiveFileModel.php
@@ -0,0 +1,56 @@
+ 'required|integer',
+ // 'incentive_month' => 'required|valid_date',
+ // 'incentive_file_name'=> 'required|string|max_length[150]',
+ // ];
+
+ // protected $validationMessages = [
+ // 'manager_id' => [
+ // 'required' => 'Manager ID is required',
+ // 'integer' => 'Manager ID must be a number',
+ // ],
+ // 'incentive_month' => [
+ // 'required' => 'Incentive Month is required',
+ // 'valid_date' => 'Incentive Month must be a valid date (Y-m-d)',
+ // ],
+ // 'incentive_file_name' => [
+ // 'required' => 'File name is required',
+ // 'max_length' => 'File name cannot exceed 150 characters',
+ // ],
+ // ];
+
+ // protected $skipValidation = false;
+}
diff --git a/app/Models/PartnerPolicyModel.php b/app/Models/PartnerPolicyModel.php
new file mode 100755
index 00000000..71d1550f
--- /dev/null
+++ b/app/Models/PartnerPolicyModel.php
@@ -0,0 +1,72 @@
+db->table('partner_policy as pp')
+ ->select('
+ pp.id,
+ pp.id as partner_policy_id,
+ pp.enquiry_id,
+ pp.insured_name,
+ pp.policy_number,
+ pp.agent_id,
+ pp.manager_id,
+ pp.client_id,
+ pp.client_policy_id,
+ pp.is_active as partner_policy_is_active,
+ pe.insurer_id,
+ pe.is_active as partner_enquiry_is_active,
+ i.name as insurer_name,
+ i.short_name as insurer_short_name,
+ i.is_active as insurer_is_active
+ ')
+ ->join('partner_enquiry as pe', 'pe.id = pp.enquiry_id', 'left')
+ ->join('insurers as i', 'i.id = pe.insurer_id', 'left')
+ ->where('pp.is_active', 1)
+ ->get()
+ ->getResultArray();
+ }
+ // $data['partner_policy_list'] = $this->partnerPolicyModel
+ // ->where('is_active', 1)
+ // ->findAll();
+}
diff --git a/app/Models/PartnerStaffModel.php b/app/Models/PartnerStaffModel.php
new file mode 100755
index 00000000..474f14d1
--- /dev/null
+++ b/app/Models/PartnerStaffModel.php
@@ -0,0 +1,50 @@
+ 'required|min_length[2]|max_length[150]',
+ // 'email' => 'permit_empty|valid_email|max_length[150]',
+ // 'mobile' => 'permit_empty|regex_match[/^[0-9]{10,20}$/]',
+ // ];
+
+ // protected $validationMessages = [
+ // 'name' => [
+ // 'required' => 'Name is required',
+ // 'min_length' => 'Name must have at least 2 characters',
+ // 'max_length' => 'Name cannot exceed 150 characters'
+ // ],
+ // 'email' => [
+ // 'valid_email' => 'Please provide a valid email address',
+ // 'max_length' => 'Email cannot exceed 150 characters'
+ // ],
+ // 'mobile' => [
+ // 'regex_match' => 'Mobile number must be 10–20 digits only'
+ // ]
+ // ];
+
+ // protected $skipValidation = false;
+}
diff --git a/app/Models/ThzHistoryModel.php b/app/Models/ThzHistoryModel.php
new file mode 100644
index 00000000..f7dd22d2
--- /dev/null
+++ b/app/Models/ThzHistoryModel.php
@@ -0,0 +1,45 @@
+db->table('employees e')
+ ->select('e.id, e.email_personal,e.email_corporate, e.client_id, e.client_branch_id as branch_id, e.mobile, e.emp_code, e.name, ep.client_policy_id as policy_id')
+ ->join('employee_polices ep', 'ep.employee_id = e.id AND ep.is_active = 1', 'left')
+ ->whereIn('e.emp_status', ['active', 'draft', 'enrolled'])
+ ->where('e.is_active', 1)
+ ->where('e.mobile', $mobile)
+ ->where('e.client_id', $client_id)
+ ->groupBy('e.client_id')
+ ->get()
+ ->getResultArray();
+
+ return $result;
+
+ }
+
}
diff --git a/app/Models/ThzMasterNotesModel.php b/app/Models/ThzMasterNotesModel.php
index 769b505d..ac970b67 100644
--- a/app/Models/ThzMasterNotesModel.php
+++ b/app/Models/ThzMasterNotesModel.php
@@ -12,7 +12,7 @@ class ThzMasterNotesModel extends Model
protected $returnType = 'array';
protected $useSoftDeletes = false;
protected $protectFields = true;
- protected $allowedFields = ['thz_id','notes','notes_by','created_by','created_at'];
+ protected $allowedFields = ['thz_id','notes','notes_by','created_by','created_at','notes_type'];
protected bool $allowEmptyInserts = false;
@@ -40,7 +40,7 @@ class ThzMasterNotesModel extends Model
protected $beforeDelete = [];
protected $afterDelete = [];
- public function ticketConversationList($thz_id){
+ public function ticketConversationLists($thz_id){
if(empty($thz_id)){
@@ -76,5 +76,42 @@ class ThzMasterNotesModel extends Model
}
+ public function ticketConversationList($thz_id , $returnType)
+ {
+ $ticketTypeFilter = "";
+
+ if ($returnType == 'api') {
+ //user only see his message
+ $ticketTypeFilter = "AND thz_master_notes.notes_type = 'External' ";
+ }
+
+ $integer_ticket_id = (int)$thz_id;
+
+ $notes_sql = "SELECT
+ thz_master_notes.*,
+ CASE
+ WHEN LOWER(thz_master_notes.notes_by) = 'staff'
+ THEN CONCAT(user_profiles.first_name, ' ', user_profiles.last_name)
+ WHEN LOWER(thz_master_notes.notes_by) = 'user'
+ THEN thz_master.name
+ ELSE thz_master_notes.notes_by
+ END AS name
+ FROM thz_master_notes
+ LEFT JOIN user_profiles
+ ON user_profiles.id = thz_master_notes.created_by
+ AND LOWER(thz_master_notes.notes_by) = 'staff'
+ LEFT JOIN thz_master
+ ON thz_master.thz_id = thz_master_notes.thz_id
+ AND LOWER(thz_master_notes.notes_by) = 'user'
+ WHERE thz_master_notes.thz_id = ". $integer_ticket_id ."
+ $ticketTypeFilter
+ ORDER BY thz_master_notes.created_at DESC";
+
+ $result = $this->db->query($notes_sql)->getResultArray();
+
+ return $result;
+ }
+
+
}
diff --git a/app/Models/ThzTypeModel.php b/app/Models/ThzTypeModel.php
new file mode 100644
index 00000000..4903c116
--- /dev/null
+++ b/app/Models/ThzTypeModel.php
@@ -0,0 +1,44 @@
+select('ticket_master.*, tms.mail_subject as subject')
+ $query = $this->select('ticket_master.*, tms.mail_subject as subject, tms.id as ticket_message_id')
->join('ticket_messages tms', 'ticket_master.id = tms.ticket_id', 'left')
- ->where('ticket_master.is_active', 1)
- ->where('tms.sender', "user")
- ->where('ticket_master.emp_id', $emp_id);
+ ->where('ticket_master.is_active', 1);
+ $query->whereIn('sender', ['staff', 'user']);
+ $query->where('ticket_master.emp_id', $emp_id);
if (!empty($ticket_id)) {
$query->where('ticket_master.id', $ticket_id);
@@ -802,8 +807,10 @@ class TicketMasterModel extends Model
$query->where('ticket_master.ticket_type_id', $ticket_type);
}
+ $query->groupBy('ticket_master.id');
$data = $query->findAll();
- // dd($data, db_connect()->getLastQuery());
+ // dd($data, db_connect()->getLastQuery());
+ // print_r($this->db->getLastQuery());die;
return $data;
}
@@ -883,8 +890,6 @@ class TicketMasterModel extends Model
return $finalResults;
}
-
-
public function getNotSettledbutApprovedCount($ticket_type)
{
// Fetch the approved and settled claim_status IDs
@@ -975,7 +980,198 @@ class TicketMasterModel extends Model
return json_encode(['policy_terms' => null]);
}
+ // ---------- CLAIM DUMP UPLOAD-------------------------------------------------------------------------------------------
+
+ public function getPolicyData($params)
+ {
+ $client_name = $params['client_name'] ?? null;
+ $insurer_short_name = $params['insurer_short_name'] ?? null;
+ $tpa_short_name = $params['tpa_short_name'] ?? null;
+ $policy_no = $params['policy_no'] ?? null;
+ $builder = $this->db->table('client_policy');
+ $builder->select('client_policy.*');
+ $builder->join('clients c', 'client_policy.client_id = c.id');
+ $builder->join('insurers i', 'client_policy.insurer_id = i.id');
+ $builder->join('tpa', 'client_policy.tpa_id = tpa.id and tpa.is_active = 1', 'left');
+ $builder->where('c.is_active', 1);
+ $builder->where('client_policy.is_active', 1);
+ $builder->where('i.is_active', 1);
+ $builder->where('c.client_name', trim($client_name));
+ $builder->where('i.short_name', trim($insurer_short_name));
+ if(!empty($tpa_short_name)){
+ $builder->where('tpa.short_name', trim($tpa_short_name));
+ }
+ $builder->where('client_policy.policy_no', trim($policy_no));
+
+ $query = $builder->get();
+ $result = $query->getResultArray();
+ // dd($this->db->getLastQuery());
+ return $result;
+ }
+
+ public function getTheClaimDetails($params)
+ {
+ $client_name = $params['client_name'] ?? null;
+ $policy_no = $params['policy_no'] ?? null;
+ $insurer_short_name = $params['insurer_short_name'] ?? null;
+ $tpa_short_name = $params['tpa_short_name'] ?? null;
+ $emp_code = $params['emp_code'] ?? null;
+ $emp_name = $params['emp_name'] ?? null;
+ $insured_name = $params['insured_name'] ?? null;
+ $claim_no = $params['claim_no'] ?? null;
+ $tpa_no = $params['tpa_no'] ?? null;
+ $relationship = $params['relationship'] ?? null;
+
+ $builder = $this->table('ticket_master');
+ $builder->select('ticket_master.*');
+ $builder->join('clients c', 'ticket_master.client_id = c.id');
+ $builder->join('insurers i', 'ticket_master.insurer_id = i.id');
+ $builder->join('tpa', 'ticket_master.tpa_id = tpa.id', 'left');
+ $builder->where('c.is_active', 1);
+ $builder->where('i.is_active', 1);
+ $builder->where('tpa.is_active', 1);
+ $builder->where('ticket_master.is_active', 1);
+
+ $builder->where('c.client_name', trim($client_name));
+ $builder->where('i.short_name', trim($insurer_short_name));
+ $builder->where('ticket_master.policy_no', trim($policy_no));
+ $builder->where('ticket_master.emp_code', trim($emp_code));
+ $builder->where('ticket_master.emp_name', trim($emp_name));
+ $builder->where('ticket_master.insured_name', trim($insured_name));
+ $builder->where('ticket_master.tpa_no', trim($tpa_no));
+ $builder->where('ticket_master.claim_number', trim($claim_no));
+ $builder->where('ticket_master.relationship', trim($relationship));
+
+ if(!empty($tpa_short_name)){
+ $builder->where('tpa.short_name', trim($tpa_short_name));
+ }
+
+ $query = $builder->get();
+ $result = $query->getResultArray();
+
+ return $result;
+
+ }
+
+ public function getEmployeeAndEmployeePolicyDetails($params)
+ {
+ $client_name = $params['client_name'] ?? null;
+ $emp_code = $params['emp_code'] ?? null;
+ $emp_name = $params['emp_name'] ?? null;
+ $policy_no = $params['policy_no'] ?? null;
+ $relationship = $params['relationship'] ?? null;
+ $insured_name = $params['insured_name'] ?? null;
+
+ // $client_name = "6-Eleven";
+ // $emp_code = "EMP0020K12";
+ // $emp_name = "Lokesh";
+ // $policy_no = "GMC-1999/2000/2021/2022";
+
+
+ $builder = $this->db->table('employees e');
+ $builder->select("
+ e.id as emp_id,
+ e.client_id,
+ e.client_branch_id,
+ e.emp_code,
+ e.name as emp_name,
+ e.mobile as emp_mobile,
+ e.email_corporate as emp_mail,
+ e.email_personal as emp_mail_personal,
+
+ ep.id as emp_policy_id,
+ ep.tpa_id as tpa_no,
+
+ cp.id as client_policy_id,
+ cp.insurer_id,
+ cp.tpa_id,
+ cp.policy_no,
+ CASE
+ WHEN cp.policy_type_id = 2 THEN 1
+ WHEN cp.policy_type_id = 1 THEN 2
+ WHEN cp.policy_type_id = 6 THEN 3
+ WHEN cp.policy_type_id = 7 THEN 4
+ ELSE NULL
+ END AS ticket_type_id
+ ", false);
+ $builder->join('employee_polices ep', 'e.id = ep.employee_id');
+ $builder->join('clients c', 'e.client_id = c.id');
+ $builder->join('client_policy cp', 'ep.client_policy_id = cp.id');
+
+ $builder->where('e.is_active', 1);
+ $builder->where('ep.is_active', 1);
+ $builder->where('c.is_active', 1);
+ $builder->where('cp.is_active', 1);
+ $builder->where('e.emp_code', trim($emp_code));
+ $builder->where('e.name', trim($emp_name));
+ $builder->where('c.client_name', trim($client_name));
+ $builder->where('cp.policy_no', trim($policy_no));
+ $builder->where('LOWER(e.relationship)', strtolower('self'));
+
+ $query = $builder->get();
+ $result = $query->getRowArray();
+
+ return $result;
+ }
+
+ public function getAcmUserDetails($params)
+ {
+ $acm_name = $params['acm_name'] ?? null;
+ $acm_mobile = $params['acm_mobile'] ?? null;
+
+ if ($acm_mobile != null) {
+
+ $builder = $this->db->table('user_profiles');
+ $builder->select("user_profiles.*");
+ $builder->where('user_profiles.is_active', 1);
+ $builder->where('user_profiles.mobile', trim($acm_mobile));
+ $query = $builder->get();
+ $result = $query->getRowArray();
+
+ return $result;
+ }
+
+ return [];
+ }
+
+ public function getInsuredDetails($params)
+ {
+ $client_id = $params['client_id'] ?? null;
+ $emp_code = $params['emp_code'] ?? null;
+ $policy_id = $params['client_policy_id'] ?? null;
+ $insured_name = $params['insured_name'] ?? null;
+
+ $builder = $this->db->table('employees e');
+ $builder->select("
+ e.id as emp_id,
+ e.client_id,
+ e.client_branch_id,
+ e.emp_code,
+ e.name as emp_name,
+ e.mobile as emp_mobile,
+ e.email_corporate as emp_mail,
+ e.email_personal as emp_mail_personal,
+
+ ep.id as emp_policy_id,
+ ep.tpa_id as tpa_no,
+ ");
+ $builder->join('employee_polices ep', 'e.id = ep.employee_id');
+ $builder->where('e.is_active', 1);
+ $builder->where('ep.is_active', 1);
+ $builder->where('e.emp_code', trim($emp_code));
+ $builder->where('e.name', trim($insured_name));
+ $builder->where('e.client_id', trim($client_id));
+ $builder->where('ep.client_policy_id', trim($policy_id));
+
+ $query = $builder->get();
+ $result = $query->getRowArray();
+ // dd($this->db->getLastQuery());
+ return $result;
+
+ }
+
+ // -----------------------------------------------------------------------------------------------------
}
diff --git a/app/Views/DashBoard.php b/app/Views/DashBoard.php
index b0cefc4e..6acad55b 100755
--- a/app/Views/DashBoard.php
+++ b/app/Views/DashBoard.php
@@ -167,36 +167,22 @@
}
}
- .navtab-bg .nav-link {
- margin: 0 5px 10px!important;
- }
-
- .nav-link{
- color:black !important;
- background-color: #D4F5F6 !important;
- font-size: small;
- padding:8px;
- border-radius: 10px !important;
- }
- .nav-link.active-tab {
- color: white !important;
- background-color: #00999E !important;
- font-size: small;
- padding:8px;
- border-radius: 10px !important;
-
- }
- .tab-content-styles{
+ #client_add .tab-content-styles{
background-color:#F4F4F4;
margin-right:20px;
+ margin-top:0px !important;
border-radius:25px!important;
min-height: 70vh !important;
}
+ .active{
+ color : white !important ;
+ }
+
-Dashboard
+Dashboard
@@ -204,20 +190,18 @@
-
-
-
+
@@ -375,3 +359,19 @@ $(document).ready(function(){
});
+
+
diff --git a/app/Views/UserList.php b/app/Views/UserList.php
index b7de1d73..544b544b 100755
--- a/app/Views/UserList.php
+++ b/app/Views/UserList.php
@@ -42,6 +42,17 @@ table.dataTable tbody td {
padding: 20px;
}
+ #mobile::placeholder,
+ #mobile_no::placeholder {
+ font-size: 13px;
+ }
+
+ .custom-select{
+ border-radius: 10px !important ;
+ background-color: #ECECEC !important ;
+ box-shadow: 0px 2px 4px 0px #00000024 !important;
+ }
+
.multiselect-native-select {
position: relative;
}
@@ -223,22 +234,126 @@ table.dataTable tbody td {
.text-danger {
color: #dc3545;
}
+
+ .btn-color{
+ background-color: rgba(52, 174, 178, 1);
+ color: white;
+ border:1px solid rgba(52, 174, 178, 1);
+ }
+
+ .btn-color:hover{
+ background-color: rgba(41, 139, 142, 1);
+ color: white;
+ border:1px solid rgba(41, 139, 142, 1);
+ }
+
+ .dt-buttons.btn-group{
+ display: grid;
+ grid-template-columns: 1fr .4fr .5fr .2fr;
+ }
+
+ #user-table_filter input{ width:100%; }
+
+ button.dt-button,
+ button.dt-button:focus,
+ button.dt-button:active,
+ button.dt-button:hover {
+ background: none !important;
+ border: none !important;
+ box-shadow: none !important;
+ padding: 0 !important;
+ margin: 0 !important;
+ }
+
+
+ /* main button wrapper */
+ .tab-button {
+ width: 201px;
+ height: 37px;
+ border-radius: 10px !important;
+ font-weight: 700;
+ font-size: 14px;
+ line-height: 100%;
+ border: 1px solid #BAF1F3;
+ background: #F5FFFF;
+ cursor: pointer;
+ transition: all 0.2s ease-in-out;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ gap: 6px;
+ }
+
+ /* divider style */
+ .divider-line {
+ color: #DBDBDB;
+ font-weight: 400;
+ }
+
+ /* active state */
+ .highlight-link.active {
+ color: #00999E;
+ }
+
+ /* inactive state */
+ .highlight-link:not(.active) {
+ color: #707070;
+ }
+
+ .no-files-message {
+ width: 900px;
+ height: 300px;
+ background: #ECECEC;
+ opacity: 1;
+
+ display: flex;
+ align-items: center;
+ justify-content: center;
+
+ font-weight: 500; /* Medium */
+ font-size: 18px;
+ line-height: 100%;
+ letter-spacing: 0;
+ color: #333; /* Adjust text color if needed */
+ text-align: center;
+
+ border-radius: 8px; /* optional for smooth edges */
+ margin: 13px; /* center horizontally */
+ }
+
+ #container {
+ max-height: 400px; /* set fixed height */
+ overflow-y: auto; /* enable vertical scroll */
+ overflow-x: hidden; /* prevent horizontal scroll */
+ }
+
+
+ .file-icon-box {
+ /* width: 40px;
+ height: 50px;
+ display: flex;
+ align-items: center;
+ justify-content: center; */
+ border-radius: 10px;
+ background: #F4F6F8;
+ border: 1px solid #ddd; /* matches border-width:1px */
+ padding: 3px;
+ }
+
+
-
+
-
User List
-
-
- ADD
+
Users
-
+
Name
@@ -257,7 +372,7 @@ table.dataTable tbody td {
mobile; ?>
user_role; ?>
-
+
is_active == 1){ echo 'Active'; }else{ echo 'In-Active'; } ?>
@@ -275,6 +390,67 @@ table.dataTable tbody td {
+
+
@@ -286,8 +462,9 @@ table.dataTable tbody td {
-