diff --git a/app/Config/Autoload.php b/app/Config/Autoload.php index 6cdb37c7..c80f6c1c 100755 --- a/app/Config/Autoload.php +++ b/app/Config/Autoload.php @@ -99,5 +99,5 @@ class Autoload extends AutoloadConfig * @var string[] * @phpstan-var list */ - public $helpers = ['uuid','session','utility', 'form', 'url', 'oauth', 'fileupload', 'excel_import_export', 'file', 'drive']; + public $helpers = ['uuid','session','utility', 'form', 'url', 'oauth', 'fileupload', 'excel_import_export', 'file', 'drive','ExcelSanitizeHelper']; } diff --git a/app/Config/Routes.php b/app/Config/Routes.php index a6472417..83992845 100755 --- a/app/Config/Routes.php +++ b/app/Config/Routes.php @@ -22,6 +22,12 @@ $routes->get("view", "EmployeeController::viewECard/$1"); $routes->get("smapletest", "ClientController::smapletest"); $routes->get("testMailAttachments", "ClientController::testMailAttachments"); $routes->get("updatePolicyTermsKey", "ClientController::updatePolicyTermsKey"); +$routes->get("updateRemainderDate", "ClientController::updateRemainderDate"); +$routes->get("sendCroneRemainderMail", "DashboardController::sendCroneRemainderMail"); +$routes->get("sendextraparam", "ClientController::sendextraparam"); +// $routes->post("iAgreeForAddOn", "EmployeeRestController::iAgreeForAddOn"); +// $routes->get("sendCroneRemainderMail", "DashboardController::sendCroneRemainderMail"); +// $routes->post("employeeUpload", "EmployeeRestController::employeeUpload"); $routes->post("add_advertise_image", "AppContentManagementController::add_advertise_image"); $routes->get("add_image_index", "AppContentManagementController::add_image_index"); @@ -130,6 +136,11 @@ $routes->group("/client", ["filter" => "authMVC"], function ($routes) { $routes->get("list/(:any)", "ClientController::listVehicleFiles/$1"); $routes->get("delete/(:any)", "ClientController::deleteVehicleFiles/$1"); }); + + + $routes->group("others", ["filter" => "authMVC"], function ($routes) { + $routes->post("create", "ClientController::createOtherTabContent"); + }); }); $routes->group("/employee", ["filter" => "authMVC"], function ($routes) { @@ -144,6 +155,7 @@ $routes->group("/employee", ["filter" => "authMVC"], function ($routes) { $routes->get("truncate/(:any)", "EmployeeController::truncateFileData/$1"); $routes->get("test-rack-rate", "EmployeeController::testRackRate"); $routes->post("test-rack-rate", "EmployeeController::testRackRate"); + $routes->get('test_members_list', 'EmployeeController::test_members_list'); }); $routes->group("/master", ["filter" => "authMVC"], function ($routes) { @@ -316,6 +328,13 @@ $routes->group("/util", ["filter" => "authMVC"], function ($routes) { $routes->get('view_log/(:any)', 'EmployeeController::viewLog/$1'); $routes->get('download_log/(:any)', 'EmployeeController::downloadLog/$1'); $routes->post('checkDuplicateTableFieldValue', 'ClientController::checkDuplicateTableFieldValue'); + $routes->get('getCoShareStatementDetails/(:any)', 'PolicyTransactionController::getCoShareStatementDetails/$1'); + $routes->get('getClientPolicyDataBasedOnClientAndInsuer', 'PolicyTransactionController::getClientPolicyDataBasedOnClientAndInsuer'); + $routes->get('checkCDAmountForBasePremium', 'PolicyTransactionController::checkCDAmountForBasePremium'); + $routes->post('map_employees', 'EmployeeController::mapEmployees'); + $routes->post('get_data_for_mapping', 'EmployeeController::getDataForMapping'); + $routes->post('unmap_employees/(:num)', 'EmployeeController::unmapEmployees/$1'); + $routes->get('transformMailContent', 'LeadsController::transformMailContent'); }); $routes->group("policy_tranction", ["filter" => "authMVC"], function ($routes) { @@ -351,6 +370,8 @@ $routes->group("policy_tranction", ["filter" => "authMVC"], function ($routes) { $routes->get("deletePaymentEntry/(:any)", "PolicyTransactionController::deletePaymentEntry/$1"); $routes->get("downloadSampleInsurerStatement", "PolicyTransactionController::downloadSampleInsurerStatement"); $routes->get("getFileErr/(:any)", "PolicyTransactionController::getFileErr/$1"); + $routes->get("getInsurerStatementMonth", "PolicyTransactionController::getInsurerStatementMonth"); + $routes->get("deleteStatement/(:any)", "PolicyTransactionController::deleteStatement/$1"); }); }); @@ -361,9 +382,11 @@ $routes->group("leads", ["filter" => "authMVC"], function ($routes) { $routes->post("create", "LeadsController::createLead"); $routes->get("list/(:any)", "LeadsController::getLeadDataForEdit/$1"); $routes->get("sendMail", "LeadsController::sendMailWithAttachement"); + $routes->post("sendMail", "LeadsController::sendMailWithAttachement"); $routes->get("exportQCRandRFQ/(:any)", "LeadsController::exportQCRandRFQ/$1"); $routes->get("featchLeadDataAndInsertClient/(:any)", "LeadsController::featchLeadDataAndInsertClient/$1"); $routes->get("featchClientPolicyFromLead/(:any)", "LeadsController::featchClientPolicyFromLead/$1"); + }); $routes->group("rfq", ["filter" => "authMVC"], function ($routes) { @@ -377,6 +400,7 @@ $routes->get("driveListFiles", "GoogleDriveController::listFiles"); $routes->post('dmsSearch', 'PolicyTransactionController::dmsSearch', ['filter' => 'authMVC']); $routes->get('dmsSearch', 'PolicyTransactionController::dmsSearch', ['filter' => 'authMVC']); $routes->get('downloadGdriveFile', 'GoogleDriveController::downloadGdriveFile', ['filter' => 'authMVC']); +$routes->get('cli/sendZeptoMail', 'MasterController::testZeptoSMTP'); $routes->cli('cli/processjob', 'JobWorker::processJob'); $routes->cli('cli/processjobs', 'JobWorker::processJobs'); @@ -384,6 +408,7 @@ $routes->cli('cli/processjobs', 'JobWorker::processJobs'); $routes->get("processjob", "JobWorker::processJob"); $routes->cli('cli/new_gmail_token', 'MasterController::generateNewGmailAPIToken'); $routes->cli('cli/send_mail_cli', 'MasterController::testGmailAPIViaCLI'); +$routes->cli('cli/sendZeptoMail', 'MasterController::testZeptoSMTP'); $routes->cli('cli/check_bounce_mail_cli', 'MasterController::testCheckBounceMails'); $routes->cli('cli/app_check_list', 'MasterController::appCheckList'); $routes->cli('cli/new_gdrive_token', 'GoogleDriveController::generateNewGoogleDriveAccessToken'); @@ -393,6 +418,7 @@ $routes->post("/employeeRest/verifyEmployeeNumber", "RestAuthenticationControlle $routes->post("/employeeRest/getVerifiedUserData", "RestAuthenticationController::getVerifiedUserData"); $routes->post("/employeeRest/verifyMpin", "RestAuthenticationController::verifyMpin"); $routes->post("/employeeRest/checkMpin", "RestAuthenticationController::checkMpin"); +$routes->post("/employeeRest/verifyEmployeeEmailId", "RestAuthenticationController::verifyEmployeeWithEmailId"); //HR login api's $routes->post("/employeeRest/verifyHrWithMobileNumber", "RestAuthenticationController::verifyHrWithMobileNumber"); @@ -402,7 +428,7 @@ $routes->group("/api", ["filter" => "authJWT"], function ($routes) { $routes->post("logined", "RestAuthenticationController::logined"); $routes->post("getId", "RestAuthenticationController::getUserIdFromToken"); }); - +// $routes->get("getEmployeePolicy", "EmployeeRestController::getEmployeePolicy"); $routes->group("employeeRest", ["filter" => "authJWT"], function ($routes) { $routes->post("getVerifiedUserData", "RestAuthenticationController::getVerifiedUserData"); @@ -443,10 +469,11 @@ $routes->group("employeeRest", ["filter" => "authJWT"], function ($routes) { $routes->get("getFEContent", "EmployeeRestController::getFEContent"); $routes->get("getAdvertisementImage", "EmployeeRestController::getAdvertisementImage"); }); - +$routes->get("getEmployeeActiveOrInactivePolicy", "EmployeeRestController::getEmployeeActiveOrInactivePolicy"); $routes->get("sendPushNotification", "EmployeeRestController::sendPushNotification"); $routes->post("sendEmail", "EmployeeRestController::send_email"); +$routes->get("getBackToEnrolledDetails", "EmployeeRestController::getBackToEnrolledDetails"); // Ticketing System diff --git a/app/Controllers/ChatBotController.php b/app/Controllers/ChatBotController.php index afc79b5e..d2ecad96 100755 --- a/app/Controllers/ChatBotController.php +++ b/app/Controllers/ChatBotController.php @@ -73,7 +73,7 @@ class ChatBotController extends AdminController public function getChatResponse() { - // try { + try { $emp_code = $this->request->getVar('emp_code'); $client_id = $this->request->getVar('client_id'); $client_branch_id = $this->request->getVar('client_branch_id'); @@ -236,9 +236,9 @@ class ChatBotController extends AdminController return $this->respond(['status' => 'failed','code' => 404,'data' => 'No Data'],404); } - // } catch (\Throwable $th) { - // return $this->respond(['status' => 'failed','code' => 500,'data' => $th],500); - // } + } catch (\Throwable $th) { + return $this->respond(['status' => 'failed','code' => 500,'data' => $th],500); + } } diff --git a/app/Controllers/ClientController.php b/app/Controllers/ClientController.php index 06f29c30..9e964863 100755 --- a/app/Controllers/ClientController.php +++ b/app/Controllers/ClientController.php @@ -118,6 +118,8 @@ class ClientController extends AdminController $this->leadsModel = new LeadsModel(); } + //-------------------------------------------------------------------------------------------------------- + public function checkDuplicateTableFieldValue() { $table = $this->request->getPost('table'); @@ -181,7 +183,7 @@ class ClientController extends AdminController print_rr($attachments); } - public function testingForReviewMail($client_id = 77, $emp_code = 'MGL-004', $mail_active = 0) //this function for only tsesting some logics not use for business logic + public function testingForReviewMail($client_id = 77, $emp_code = 'EMP001-K1', $mail_active = 0) //this function for only tsesting some logics not use for business logic { $client_policy_ids = $this->employeeModel @@ -209,6 +211,13 @@ class ClientController extends AdminController if (!is_null($client_policy_id) && is_array($client_policy_id)) { + + $empData = $this->employeeModel->where('emp_code', $emp_code )->where('client_id', $client_id ) ->where('is_active', 1 )->findAll(); + + $filteredEmpData = array_filter($empData, fn($item) => $item['relationship'] === 'Self'); + + // dd($filteredEmpData); + $array_list = []; foreach ($client_policy_id as $key => $value) { @@ -230,6 +239,14 @@ class ClientController extends AdminController $params ['emp_code'] = $emp_code; $params ['client_id'] = $client_id; $params ['notification'] = $notification; + $params['common'] = [ + 'client_id' => $filteredEmpData[0]['client_id'], + 'client_branch_id' => $filteredEmpData[0]['client_branch_id'], + 'client_policy_id' => null, + 'employee_policy_id' => null, + 'employee_id' => $filteredEmpData[0]['id'], + 'mail_type' => 'member_review_and_summary_mail', + ]; // dd($params); @@ -243,6 +260,7 @@ class ClientController extends AdminController if (isset($wholeData[0])) { + $params['common']['mail_type'] = 'account_maneger_summary_mail'; $account_manager_wholeData =sendMailNotification::sendMailNotification('account_maneger_summary_mail', $params); // print_r($account_manager_wholeData); die; @@ -261,6 +279,7 @@ class ClientController extends AdminController $this->myLogger->logme("error", 'Account Manager Mail Configuration not Enable for this client'); } + $params['common']['mail_type'] = 'client_hr_summary_mail'; $client_hr_wholeData =sendMailNotification::sendMailNotification('client_hr_summary_mail', $params); // print_r($client_hr_wholeData); die; @@ -298,6 +317,8 @@ class ClientController extends AdminController // return $this->respond(['status' => 'success','code' => 200,'data' => [] ], 200); } + //-------------------------------------------------------------------------------------------------------- + public function index() { $this->myLogger->logme('error', 'Client list function called'); @@ -463,7 +484,7 @@ class ClientController extends AdminController // Fetch associated insurer names and balances $balances = $this->clientPolicyModel->getBalances($id); $data['balances'] = $balances; - + // dd($data); echo view('layout/header', $headerData); echo view('client_deposit_list', $data); echo view('layout/footer'); @@ -500,7 +521,7 @@ class ClientController extends AdminController $data['clientData'] = $this->clientPolicyModel->getClientById($clientId); $data['deposiamount'] = $this->clientPolicyModel->getDepositSummary($clientId, $insurerId); - // dd($data['depositdata']); + // dd($data['insurerName']); // print_r($data['depositdata'] );die; // Load the view for the new list page; @@ -584,7 +605,7 @@ class ClientController extends AdminController $editData['client_policy'] = $clientPoliceData; $editData['client_policy']['role'] = get_role_id(); $editData['notification'] = $this->notificationModel->select('template_name,enabled')->where('client_id', $id)->findAll(); - $editData['placeHolders'] = ['member_name', 'nhance_logo', 'tpa_id', 'ecard_download_link', 'client_logo', 'policy_no', 'member_summary', 'app_link', 'post_enrollment_app_link', 'client_name']; + $editData['placeHolders'] = ['member_name', 'member_mobile', 'nhance_logo', 'tpa_id', 'ecard_download_link', 'client_logo', 'policy_no', 'member_summary', 'app_link', 'post_enrollment_app_link', 'client_name']; // dd($editData); echo view('layout/header', $headerData); @@ -1030,9 +1051,12 @@ class ClientController extends AdminController $data['policy_status'] = 1; $data['inception_type'] = $this->request->getPost('inception_type') ? 2 : 1; $data['client_branch_id'] = $this->request->getPost('client_branch_id'); - $data['cd_ac_no'] = $this->request->getPost('cd_ac_no'); + $data['cd_ac_pk'] = $this->request->getPost('cd_ac_no'); $data['gst'] = $this->request->getPost('gst'); $data['disclaimer'] = $this->request->getPost('disclaimer'); + $data['is_member_modify_allowed'] = $this->request->getPost('is_member_modify_allowed') ? 1 : 0; + $data['enrolment_visibility'] = $this->request->getPost('enrolment_visibility') ? 1 : 0; + if ($policy_type_id == 1 || $policy_type_id == 2 || $policy_type_id == 6 || $policy_type_id == 7) { @@ -1059,14 +1083,15 @@ class ClientController extends AdminController if ($data['inception_type'] == 2) { $data['open_date'] = change_date_format($this->request->getPost('open_date'), 'd-m-Y', 'Y-m-d'); $data['close_date'] = change_date_format($this->request->getPost('close_date'), 'd-m-Y', 'Y-m-d'); - $data['reminder_date'] = change_date_format($this->request->getPost('reminder_date'), 'd-m-Y', 'Y-m-d'); + // $data['reminder_date'] = change_date_format($this->request->getPost('reminder_date'), 'd-m-Y', 'Y-m-d'); + $data['reminder_date'] = $this->request->getPost('reminder_date'); } else { $data['open_date'] = null; $data['closedate'] = null; $data['reminder_date'] = null; } - $data['created_by'] = get_session_userid(); + $data['created_by'] = get_session_userid(); $policy_tranction_data = [ @@ -1077,7 +1102,7 @@ class ClientController extends AdminController 'insurer_branch_id' => $insurerBranchId, 'issue_type' => 1, 'policy_no' => $this->request->getPost('policy_no'), - 'cd_ac_no' => $this->request->getPost('cd_ac_no'), + 'cd_ac_pk' => $this->request->getPost('cd_ac_no'), 'policy_issue_date' => date('Y-m-d'), 'policy_start_date' => change_date_format($this->request->getPost('policy_start_date'), 'd-m-Y', 'Y-m-d'), 'policy_end_date' => change_date_format($this->request->getPost('policy_end_date'), 'd-m-Y', 'Y-m-d'), @@ -1087,7 +1112,6 @@ class ClientController extends AdminController ]; - $insert = $this->clientPolicyModel->insert($data); if ($insert) { @@ -1114,6 +1138,7 @@ class ClientController extends AdminController public function editClientPolicy() { + // print_r('test'); die; $this->myLogger->logme('error', 'Client policy function called'); @@ -1157,16 +1182,17 @@ class ClientController extends AdminController $data['inception_type'] = $this->request->getPost('inception_type') ? 2 : 1; $data['enrolment_visibility'] = $this->request->getPost('enrolment_visibility') ? 1 : 0; $data['client_branch_id'] = $this->request->getPost('client_branch_id'); - $data['cd_ac_no'] = $this->request->getPost('cd_ac_no'); + $data['cd_ac_pk'] = $this->request->getPost('cd_ac_no'); $data['gst'] = $this->request->getPost('gst'); $data['disclaimer'] = $this->request->getPost('disclaimer'); $data['policy_start_date'] = change_date_format($this->request->getPost('policy_start_date'), 'd-m-Y', 'Y-m-d'); $data['policy_end_date'] = change_date_format($this->request->getPost('policy_end_date'), 'd-m-Y', 'Y-m-d'); - + $data['is_member_modify_allowed'] = $this->request->getPost('is_member_modify_allowed') ? 1 : 0; if ($data['inception_type'] == 2) { $data['open_date'] = change_date_format($this->request->getPost('open_date'), 'd-m-Y', 'Y-m-d'); $data['close_date'] = change_date_format($this->request->getPost('close_date'), 'd-m-Y', 'Y-m-d'); - $data['reminder_date'] = change_date_format($this->request->getPost('reminder_date'), 'd-m-Y', 'Y-m-d'); + // $data['reminder_date'] = change_date_format($this->request->getPost('reminder_date'), 'd-m-Y', 'Y-m-d'); + $data['reminder_date'] = $this->request->getPost('reminder_date'); } else { $data['open_date'] = null; $data['close_date'] = null; @@ -2056,6 +2082,11 @@ class ClientController extends AdminController $data['age_ratio']['elders']['min'] = $this->request->getPost("other_member_min_age") ? $this->request->getPost("other_member_min_age") : 0; $data['age_ratio']['elders']['max'] = $this->request->getPost("other_member_max_age") ? $this->request->getPost("other_member_max_age") : 0; + $data['is_payable_employee']['self'] = $this->request->getPost("is_payable_employee_for_self") ? 1 : 0; + $data['is_payable_employee']['spouse'] = $this->request->getPost("is_payable_employee_for_spouse") ? 1 : 0; + $data['is_payable_employee']['childern'] = $this->request->getPost("is_payable_employee_for_child") ? 1 : 0; + $data['is_payable_employee']['elders'] = $this->request->getPost("is_payable_employee_for_elders") ? 1 : 0; + // if (!in_array("self", $data['family_floaters'])) { @@ -2146,6 +2177,7 @@ class ClientController extends AdminController $data['preandpostnatal'] = ""; $data['babyday1cover'] = ""; } + $data['9monthwaitingperiodwaived'] = str_replace(',', '', $this->request->getPost("9monthwaitingperiodwaived")); $data['coverfromthedateofjoining'] = str_replace(',', '', $this->request->getPost("coverfromthedateofjoining")); $data['waiverof1,2,3&4thyearexclusions'] = $this->request->getPost("waiverof1,2,3&4thyearexclusions"); @@ -2286,6 +2318,8 @@ class ClientController extends AdminController $data['totalSumInsured'] = str_replace(',', '', $this->request->getPost("totalSumInsured")); $data['age_ratio']['self']['min'] = $this->request->getPost("self_min_age"); $data['age_ratio']['self']['max'] = $this->request->getPost("self_max_age"); + $data['is_payable_employee']['self'] = 0; + $data['accidentalDeathBenefit'] = str_replace(',', '', $this->request->getPost("accidentalDeathBenefit")); $data['permanentTotalDisablement'] = str_replace(',', '', $this->request->getPost("permanentTotalDisablement")); $data['permanentPartialDisablement'] = $this->request->getPost("permanentPartialDisablement"); @@ -2419,11 +2453,11 @@ class ClientController extends AdminController $termsData = json_decode($termsData['policy_terms']); - if (isset($termsData->sum_insured) && empty($termsData->sum_insured)) { + if (isset($termsData->sum_insured) && $termsData->sum_insured == "" && $termsData->sum_insured == null) { return $this->respond(['status' => false, 'code' => 200, 'message' => 'The Policy terms Sum Insured field is empty', 'data' => $record], 200); } - if (isset($termsData->SumInsured) && empty($termsData->sum_insured)) { + if (isset($termsData->sumInsured2) && $termsData->sumInsured2 == "" && $termsData->sumInsured2 == null) { return $this->respond(['status' => false, 'code' => 200, 'message' => 'The Policy terms Sum Insured field is empty'], 200); } @@ -2515,12 +2549,14 @@ class ClientController extends AdminController } } + //for this function policy binding dropdown list use ( client policy ) public function getClientBranch($client_id) { $branchs = $this->clientBranchModel ->select('*') ->where('client_id', $client_id) + ->where('is_active', 1) ->findAll(); return $this->respond(['status' => true, 'code' => 200, 'data' => $branchs], 200); @@ -2869,6 +2905,13 @@ class ClientController extends AdminController $client_policy_id = $this->request->getPost("client_policy_id"); $policy_terms = $this->request->getPost("policy_terms"); + if (!empty($policy_terms)) { + $policy_terms = json_decode($policy_terms, true); + $policy_terms['is_payable_employee']['self'] = 0; + $policy_terms = json_encode($policy_terms); + } + + $record = $this->clientPolicyModel->where('id', $client_policy_id)->first(); if ($record) { @@ -2936,15 +2979,15 @@ class ClientController extends AdminController $multi_si = []; - if (isset($JSON->sum_insured) && !empty($JSON->sum_insured)) { + if (isset($JSON->sum_insured) && $JSON->sum_insured != "" && $JSON->sum_insured != null) { $multi_si[] = $JSON->sum_insured; - } elseif (isset($JSON->sumInsured2) && !empty($JSON->sumInsured2)) { + } elseif (isset($JSON->sumInsured2) && $JSON->sumInsured2 != "" && $JSON->sumInsured2 != null) { $multi_si[] = $JSON->sumInsured2; } if (isset($JSON->multiple_sum_insured) && is_array($JSON->multiple_sum_insured)) { foreach ($JSON->multiple_sum_insured as $msi) { - if (!empty($msi)) { + if ($msi != "" && $msi != null) { $multi_si[] = $msi; } } @@ -3256,11 +3299,10 @@ class ClientController extends AdminController public function getClientAndBranchAndPolicy() { + // ---------for client----------------------------------------------------------------------------- + $clients = $this->clientModel->where('is_active', 1)->findAll(); - $vehicles = $this->vehicleModel - ->select('vehicle.*, clients.client_type') - ->join('clients', 'clients.id=vehicle.owner') - ->where('vehicle.is_active', 1)->findAll(); + $clientIds = array_column($clients, 'id'); // Fetch branches in a single query @@ -3269,6 +3311,29 @@ class ClientController extends AdminController ->where('is_active', 1) ->findAll(); + // -----------for vehicle --------------------------------------------------------------------------- + + $vehicles = $this->vehicleModel + ->select('vehicle.*, clients.client_type') + ->join('clients', 'clients.id=vehicle.owner') + ->where('vehicle.is_active', 1)->findAll(); + + // -----------for Insurer --------------------------------------------------------------------------- + + //fetch all insurer data + $insurers = $this->insurerModel->where('is_active', 1)->findAll(); + + //map the insurer primary key to column + $insurersIds = array_column($insurers, 'id'); + + // Fetch insurer branches in a single query + $insurerBranches = $this->insurerBranchModel + ->whereIn('insurer_id', $insurersIds) + ->where('is_active', 1) + ->findAll(); + + // -----------for Policy --------------------------------------------------------------------------- + // Fetch policies in a single query $policies = $this->clientPolicyModel ->select(" @@ -3287,16 +3352,26 @@ class ClientController extends AdminController ->where('client_policy.is_active', 1) ->findAll(); + // -------------------------------------------------------------------------------------- + $branchList = []; $policyList = []; $policyListByClient = []; $unitList = []; + $insurerBranchList = []; + //for client branch mapping to the client foreach ($branches as $branch) { $branchList[$branch['client_id']][] = $branch; $unitList[$branch['id']][] = json_decode($branch['units']); } + //for insurer branch mapping to the insurer + foreach ($insurerBranches as $branch) { + $insurerBranchList[$branch['insurer_id']][] = $branch; + } + + //for client policy mapping to the branch and client foreach ($policies as $policy) { $policyList[$policy['client_branch_id']][] = $policy; $policyListByClient[$policy['client_id']][] = $policy; @@ -3307,6 +3382,7 @@ class ClientController extends AdminController } } + //get policy count foreach ($clients as &$client) { $client['client_policy_count'] = $policyCount[$client['id']] ?? 0; } @@ -3319,6 +3395,8 @@ class ClientController extends AdminController 'branch_data' => $branchList, 'policy_data' => $policyList, 'policyListByClient' => $policyListByClient, + 'insurer_data' => $insurers, + 'insurer_branch_data' => $insurerBranchList, 'unit_data' => $unitList, ], 200); } else { @@ -3579,15 +3657,22 @@ class ClientController extends AdminController dd($result); } + // --------------------------------------------------------------------------------------------------------- + public function updatePolicyTermsKey() { + $client_id = $this->request->getGet('client_id'); - $data = $this->clientPolicyModel - ->where("policy_terms IS NOT NULL AND policy_terms <> ''") - ->where('policy_type_id', 2) - ->where('is_active', 1) - ->findAll(); - + $query = $this->clientPolicyModel + ->where("policy_terms IS NOT NULL AND policy_terms <> ''") + ->where('is_active', 1); + + if (!empty($client_id)) { + $query->where('client_id', $client_id); + } + + $data = $query->findAll(); + for ($i = 0; $i < count($data); $i++) { if (isset($data[$i]['policy_terms']) && !empty($data[$i]['policy_terms'])) { @@ -3596,82 +3681,269 @@ class ClientController extends AdminController continue; } - // Set default value of copayzonewisecopay to "empty" - $ans = isset($policyTerms['copayzonewisecopay']) ? $policyTerms['copayzonewisecopay'] : 'empty'; + $is_addon = $data[$i]['is_addon']; + $payable_arr = []; + if (in_array($data[$i]['policy_type_id'], [2,3]) && $is_addon == 1) { + + $payable_arr = [ "self" => 0, "spouse" => 0, "childern" => 0, "elders" => 0, ]; + + } else if ($data[$i]['policy_type_id'] == 3 && $is_addon == 3) { + + $payable_arr = ["self" => 1,"spouse" => 1,"childern" => 1,"elders" => 1,]; + + } else if (in_array($data[$i]['policy_type_id'], [4, 5])) { + + $payable_arr = ["self" => 1,"spouse" => 1,"childern" => 1,"elders" => 1,]; + } // Initialize an empty array for the ordered policy terms $orderedPolicyTerms = []; - // Add copayzonewisecopay and copayzonewisecopaydata if they exist_ - if (isset($policyTerms['copayzonewisecopay'])) { - - $orderedPolicyTerms['copayzonewisecopay'] = $policyTerms['copayzonewisecopay']; - $orderedPolicyTerms['co_pay_details'] = isset($policyTerms['co_pay_details']) ? $policyTerms['co_pay_details'] : ''; - } + if(in_array($data[$i]['policy_type_id'], [2,3,4,5])){ + // Set default value of copayzonewisecopay to "empty" + $ans = isset($policyTerms['copayzonewisecopay']) ? $policyTerms['copayzonewisecopay'] : 'empty'; - // Add ailmentcapping and ailmentcappingdata if they exist_ - if (isset($policyTerms['ailmentcapping'])) { - $orderedPolicyTerms['ailmentcapping'] = $policyTerms['ailmentcapping']; - $orderedPolicyTerms['ailment_capping_details'] = isset($policyTerms['ailment_capping_details']) ? $policyTerms['ailment_capping_details'] : ''; - } - - - // Now add the rest of the policy terms that are not copayzonewisecopay, copayzonewisecopaydata, ailmentcapping, or ailmentcapping_data_ - foreach ($policyTerms as $key => $value) { - if (!in_array($key, ['copayzonewisecopay', 'co_pay_details', 'ailmentcapping', 'ailment_capping_details'])) { - $orderedPolicyTerms[$key] = $value; + // add is_payable_employee for the GMC Policy + if (isset($policyTerms['age_ratio'])) { + if(!isset($policyTerms['is_payable_employee'])){ + $aliment_index = array_search('age_ratio', array_keys($policyTerms)); + $orderedPolicyTerms[] = [ + "key" => "is_payable_employee", + "value" => $payable_arr, + "position" => $aliment_index + 1, + ]; + } } + + // Add copayzonewisecopay and copayzonewisecopaydata if they exist_ + if (isset($policyTerms['copayzonewisecopay'])) { + + if(!isset($policyTerms['co_pay_details'])){ + + $co_pay_details_value = ""; + if (strtolower($ans) == "nil" || $ans == 0) { + $policyTerms['copayzonewisecopay'] = 0; + $co_pay_details_value = ""; + } elseif ($ans != 'empty' && $ans !== 'Nil' && $ans !== null && $ans != '' && $ans != 0) { + $policyTerms['copayzonewisecopay'] = 1; + $co_pay_details_value = $ans; + } + + $co_pay_index = array_search('copayzonewisecopay', array_keys($policyTerms)); + $orderedPolicyTerms[] = [ + "key" => "co_pay_details", + "value" => $co_pay_details_value, + "position" => $co_pay_index + 2, + ]; + + unset($policyTerms['optionalparentalcopay']); + + } + } + + // Add ailmentcapping and ailmentcappingdata if they exist + if (isset($policyTerms['ailmentcapping'])) { + if(!isset($policyTerms['ailment_capping_details'])){ + $aliment_index = array_search('ailmentcapping', array_keys($policyTerms)); + $orderedPolicyTerms[] = [ + "key" => "ailment_capping_details", + "value" => "", + "position" => $aliment_index + 3, + ]; + } + } + + }else { + + // add is_payable_employee for the GMC Policy + if (isset($policyTerms['age_ratio'])) { + if(!isset($policyTerms['is_payable_employee'])){ + $aliment_index = array_search('age_ratio', array_keys($policyTerms)); + $orderedPolicyTerms[] = [ + "key" => "is_payable_employee", + "value" => [ + "self" => 0, + ], + "position" => $aliment_index + 1, + ]; + } + }else{ + + if(!isset($policyTerms['is_payable_employee'])){ + $orderedPolicyTerms[] = [ + "key" => "is_payable_employee", + "value" => [ + "self" => 0, + ], + "position" => 2, + ]; + } + } + } + + foreach ($orderedPolicyTerms as $term) { + $position = $term['position']; + $key = $term['key']; + $value = $term['value']; // Insert the key-value pair at the specified index + $policyTerms = array_merge( + array_slice($policyTerms, 0, $position, true), + [$key => $value], + array_slice($policyTerms, $position, null, true) + ); + } + // Re-encode the ordered policy terms - $updatedPolicyTerms = json_encode($orderedPolicyTerms); + $updatedPolicyTerms = json_encode($policyTerms); - - // Update the policyterms in the database_ + // dd($orderedPolicyTerms, $updatedPolicyTerms); $this->clientPolicyModel->update($data[$i]['id'], ['policy_terms' => $updatedPolicyTerms]); + } + } + + public function updateRemainderDate() + { + // Connect to the database and fetch the data + $data = db_connect()->table('client_policy') + ->where("reminder_date IS NOT NULL AND reminder_date <> ''") + ->where('is_active', 1) + ->get() + ->getResultArray(); + + $days = []; + foreach ($data as $value) { + + $reminderDate = strtotime($value['reminder_date']); + if ($reminderDate) { + $date_of_date = date('d', $reminderDate); + $days[] = $date_of_date; + $days[] = $value['reminder_date']; + db_connect()->table('client_policy')->where('id', $value['id'])->set('reminder_date', $date_of_date)->update(); + } + } + + dd($days); + } + + public function sendextraparam() + { + $batch_data = [ + 'client_id' => 17, + 'client_policy_id' => 30, + 'client_branch_id' => 18, + 'event_type' => "inception", + ]; + + // $batch_data['insurer_or_tpa'] = 'insurer'; + $batch_data['insurer_or_tpa'] = 'tpa'; + + + // dd($this->request); + // $employeeRestController = new EmployeeServiceController(); + // $employeeRestController->employeesOnboardPreprocess(['file_id' => 721]); + + // $r = Jobs::addJob(['job_name' => 'employeesEnrollmentInsert','payload' => ['file_id' => 721]]); - // Handle different conditions for copayzonewisecopay - if (strtolower($ans) == "nil" || $ans == 0) { - // If copayzonewisecopay is "nil" or 0, reset it to 0 and add copayzonewisecopaydata as empty_ - if (isset($orderedPolicyTerms['copayzonewisecopay'])) { - $orderedPolicyTerms['copayzonewisecopay'] = 0; - $orderedPolicyTerms['co_pay_details'] = ""; + // $dashBoardController = new DashboardController(); + // $client_policy_data = $this->clientPolicyModel->getPolicyDetailsForRemainder($client_id=159, $client_branch_id=126); + // $dashBoardController->sendRemainderMail($client_policy_data); + + // $EmpDataServiceController = new EmpDataServiceController(); + // $emp_data = $this->employeePolicyModel->getEmployeePolicyForEcard(12); + // $ids = array_column($emp_data, 'id'); + // $EmpDataServiceController->sendMailForDownloadingECard($ids); + + // $EmpDataServiceController = new EmpDataServiceController(); + // $EmpDataServiceController->importDeletionValidation(['file_id' => 304]); //for live + + // $result = $this->employeePolicyModel->getDeletionEmployeeDataForExportExcel($batch_data); + // print_rr($result); die; + + // $empServiceController = new EmployeeServiceController(); + // $res = $empServiceController->employeesOnboardPreprocess(['file_id' => '741']); + + // $PolicyTransactionController = new PolicyTransactionController(); + // $res = $PolicyTransactionController->validateInsurerStatement(['file_id' => '36']); + + // $empServiceController = new EmployeeServiceController(); + // $res = $empServiceController->excelFileDataValidation(['file_id' => '319']); + // dd($res); + + // $EmpDataServiceController = new EmpDataServiceController(); + // $EmpDataServiceController->importInceptionFileValidation(['file_id' => 160]); + + $EmpDataServiceController = new EmpDataServiceController(); + // $EmpDataServiceController->importInceptionUpdateTPAandUHID(['file_id' => 162]); + // $EmpDataServiceController->importInceptionFileValidation(['file_id' => 162]); + // $EmpDataServiceController->importDeletionValidation(['file_id' => 171]); + // $EmpDataServiceController->importDeletionUpdateEndorsementID(['file_id' => 171]); + // $EmpDataServiceController->importCorrectionUpdateEndorsementID(['file_id' => 188]); + $array = [ + "employeeIds" => ["12800", "12798", "12797", "12799"], + "client_id" => "159", + "client_policy_id" => "336", + "client_branch_id" => "126", + "cd_ac_no" => "Apple_123", + "endorsement_no" => "ENDORSEMENT_ID", + "count" => 4, + "event_name" => "deletion", + "policy_name" => "GMC", + "user_id" => "1" + ]; + + // $EmpDataServiceController->cashDepositCalculationForDeletion($array); + + // $employeeRestController = new EmployeeServiceController(); + // $employeeRestController->employeesOnboardPreprocess(['file_id' => 757]); + + // $result = $this->employeePolicyModel->getInceptionEmployeeDataForExportExcel($batch_data); + // dd(db_connect()->getLastQuery()); + + } + + // ------------------------------------------------------------------------------------------------------- + + + public function createOtherTabContent() + { + $this->myLogger->logme('error', 'Client Others function called'); + $data = $this->request->getPost(); + $data['created_by'] = get_session_userid(); + $client_id = $data['client_id']; + unset($data['client_id']); + + $insert = $this->clientModel->where('id', $client_id)->set($data)->update(); + + if ($insert) { + return $this->respond(['status' => true, 'code' => 200, 'message' => 'Client others data updated', 'data' => $data], 200); + } else { + return $this->respond(['status' => false, 'code' => 404, 'message' => 'No data to update'], 200); + } + } + + + // ------------------------------------------------------------------------------------------------------- + + public function enrollmentAddonSIAmountDropdown($client_policy_id) + { + if(!empty($client_policy_id)){ + $client_policy_details = $this->clientPolicyModel->where('id', $client_policy_id)->where('policy_status', 1)->where('is_active', 1)->first(); + + if(!empty($client_policy_details) && $client_policy_details['policy_type_id'] == 3 && $client_policy_details['is_addon'] == 3){ + + $base_policy_id = $client_policy_details['base_policy'] ?? 0; + + if(!empty($base_policy_id)){ + + + } - - // Rebuild the array after modification - foreach ($policyTerms as $key => $value) { - if (!in_array($key, ['copayzonewisecopay', 'co_pay_details'])) { - $orderedPolicyTerms[$key] = $value; - } - } - - - $updatedPolicyTerms = json_encode($orderedPolicyTerms); - $this->clientPolicyModel->update($data[$i]['id'], ['policy_terms' => $updatedPolicyTerms]); - continue; - } elseif ($ans != 'empty' && $ans !== 'Nil' && $ans !== null && $ans != '' && $ans != 0) { - // If copayzonewisecopay has a valid value, update it - if (isset($orderedPolicyTerms['copayzonewisecopay'])) { - $orderedPolicyTerms['copayzonewisecopay'] = 1; - $orderedPolicyTerms['co_pay_details'] = $ans; - } - - - // Rebuild the array after modification - foreach ($policyTerms as $key => $value) { - if (!in_array($key, ['copayzonewisecopay', 'co_pay_details'])) { - $orderedPolicyTerms[$key] = $value; - } - } - - - $updatedPolicyTerms = json_encode($orderedPolicyTerms); - $this->clientPolicyModel->update($data[$i]['id'], ['policy_terms' => $updatedPolicyTerms]); } } } diff --git a/app/Controllers/DashboardController.php b/app/Controllers/DashboardController.php index dfa0841a..4df9136a 100755 --- a/app/Controllers/DashboardController.php +++ b/app/Controllers/DashboardController.php @@ -362,173 +362,247 @@ class DashboardController extends AdminController // dd($client_policy_data, $send_mail_for_manual_or_crone); $reminder_whole_mail = []; - + foreach ($client_policy_data as $client_policy) { - if(empty($send_mail_for_manual_or_crone)){ + // Fetch client data + $client_data = $this->clientModel->find($client_policy['client_id']); - // echo '1'; + // Fetch notification settings + $notification_data = $this->notificationModel + ->where('client_id', $client_policy['client_id']) + ->where('template_name', 'member_reminder_mail') + ->first(); - // Fetch client data - $client_data = $this->clientModel->find($client_policy['client_id']); - - // Fetch notification settings - $notification_data = $this->notificationModel - ->where('client_id', $client_policy['client_id']) - ->where('template_name', 'member_reminder_mail') - ->first(); + if ($notification_data && $notification_data['enabled'] == 1 && !empty($notification_data['mail_content'])) { - // $this->myLogger->logme('error', 'Notification data fetched: ' . json_encode($notification_data)); - - // Check if notification should be sent - if ($notification_data && $notification_data['enabled'] == 1 && !empty($notification_data['mail_content'])) { + //manaual + if (empty($send_mail_for_manual_or_crone)) { + + // Check if notification should be sent $this->myLogger->logme('error', 'Notification should be sent for client policy ID: ' . $client_policy['id']); - - // Fetch all employees related to the client policy - $employees = $this->employeePolicyModel - ->select('employees.*') - ->join('employees', 'employee_polices.employee_id = employees.id', 'left') - ->where('employee_polices.client_policy_id', $client_policy['id']) - ->where('employees.emp_status', 'draft') - ->where('employees.is_active', 1) - ->where('employee_polices.status', 'draft') - ->where('employee_polices.is_active', 1) - ->where('employees.relationship', 'Self') - ->findAll(); - + + $employees = []; + if (in_array($client_policy['policy_type_id'], [2, 4]) || ($client_policy['policy_type_id'] == 3 && $client_policy['is_addon'] == 1)) { + + // Fetch all employees related to the client policy + $employees = $this->employeePolicyModel + ->select('employees.*, employee_polices.id as emp_policy_id') + ->join('employees', 'employee_polices.employee_id = employees.id', 'left') + ->where('employee_polices.client_policy_id', $client_policy['id']) + ->where('employees.is_active', 1) + ->where('employee_polices.is_active', 1) + ->where('employees.emp_status', 'draft') + ->where('employee_polices.status', 'draft') + ->where('employees.relationship', 'Self') + ->where("employees.email_corporate IS NOT NULL AND employees.email_corporate != ''") + ->findAll(); + + // dd($employees, 'first'); + + } else if (($client_policy['policy_type_id'] == 3 && $client_policy['is_addon'] == 3) || $client_policy['policy_type_id'] == 5) { + + $empDependentData = $this->employeePolicyModel + ->select('employees.*, employee_polices.id as emp_policy_id') + ->join('employees', 'employee_polices.employee_id = employees.id', 'left') + ->where('employee_polices.client_policy_id', $client_policy['id']) + ->where('employees.is_active', 1) + ->where('employee_polices.is_active', 1) + ->where('employees.emp_status', 'draft') + ->where('employee_polices.status', 'draft') + ->where('employees.relationship !=', 'Self') + ->findAll(); + + $empCodes = array_column($empDependentData, 'emp_code'); + + // dd($empDependentData, $empCodes,'second'); + + if (!empty($empCodes)) { + + $empSelfData = $this->employeePolicyModel + ->select('employees.*, employee_polices.id as emp_policy_id') + ->join('employees', 'employee_polices.employee_id = employees.id', 'left') + ->whereIn('employees.emp_code', $empCodes) + ->where('employees.is_active', 1) + ->where('employee_polices.is_active', 1) + ->where('employees.relationship', 'Self') + ->where("employees.email_corporate IS NOT NULL AND employees.email_corporate != ''") + ->findAll(); + + $employees = array_merge($employees, $empSelfData); + } + } + + // dd($employees); + // Process each employee - foreach ($employees as $employee) { - - if ($employee['emp_status'] == 'draft' && $employee['relationship'] == 'Self') { + if (!empty($employees) && count($employees) > 0) { + + foreach ($employees as $employee) { + $this->myLogger->logme('error', 'Employee status and relationship check passed for employee ID: ' . $employee['id']); - + // Mail params $params['emp_data'] = $employee; $params['client_data'] = $client_data; $params['notification_data'] = $notification_data; - + $params['common'] = [ + 'client_id' => $client_policy['client_id'], + 'client_branch_id' => $client_policy['client_branch_id'], + 'client_policy_id' => $client_policy['id'], + 'employee_policy_id' => $employee['emp_policy_id'], + 'employee_id' => $employee['id'], + 'mail_type' => 'member_reminder_mail', + ]; + // Send the mail notification $mail_result = sendMailNotification::sendMailNotification('member_reminder_mail', $params); + // dd($mail_result); // $this->myLogger->logme('error', 'Mail sent result: ' . json_encode($mail_result)); $reminder_whole_mail[] = $mail_result; } } - } else { - $this->myLogger->logme('error', 'Notification not sent for client policy ID: ' . $client_policy['id']); + + } else { // crone + + if (!empty($client_policy['reminder_date'])) { + + $currentDate = date('d'); + $remainder_dates = explode(",", $client_policy['reminder_date']); + + foreach ($remainder_dates as $date) { + + if ($currentDate == $date) { + + $this->myLogger->logme('error', 'Notification should be sent for client policy ID: ' . $client_policy['id']); + + // Fetch all employees related to the client policy + $employees = []; + if (in_array($client_policy['policy_type_id'], [2, 4]) || ($client_policy['policy_type_id'] == 3 && $client_policy['is_addon'] == 1)) { + + $employees = $this->employeePolicyModel + ->select('employees.*, employee_polices.id as emp_policy_id') + ->join('employees', 'employee_polices.employee_id = employees.id', 'left') + ->where('employee_polices.client_policy_id', $client_policy['id']) + ->where('employees.is_active', 1) + ->where('employee_polices.is_active', 1) + ->where('employees.emp_status', 'draft') + ->where('employee_polices.status', 'draft') + ->where('employees.relationship', 'Self') + ->where("employees.email_corporate IS NOT NULL AND employees.email_corporate != ''") + ->findAll(); + + // dd($employees, 'first'); + + } else if (($client_policy['policy_type_id'] == 3 && $client_policy['is_addon'] == 3) || $client_policy['policy_type_id'] == 5) { + + $empDependentData = $this->employeePolicyModel + ->select('employees.*, employee_polices.id as emp_policy_id') + ->join('employees', 'employee_polices.employee_id = employees.id', 'left') + ->where('employee_polices.client_policy_id', $client_policy['id']) + ->where('employees.is_active', 1) + ->where('employee_polices.is_active', 1) + ->where('employees.emp_status', 'draft') + ->where('employee_polices.status', 'draft') + ->where('employees.relationship !=', 'Self') + ->findAll(); + + $empCodes = array_column($empDependentData, 'emp_code'); + + // dd($empDependentData, $empCodes,'second'); + + if (!empty($empCodes)) { + + $empSelfData = $this->employeePolicyModel + ->select('employees.*, employee_polices.id as emp_policy_id') + ->join('employees', 'employee_polices.employee_id = employees.id', 'left') + ->whereIn('employees.emp_code', $empCodes) + ->where('employees.is_active', 1) + ->where('employee_polices.is_active', 1) + ->where('employees.relationship', 'Self') + ->where("employees.email_corporate IS NOT NULL AND employees.email_corporate != ''") + ->findAll(); + + $employees = array_merge($employees, $empSelfData); + } + } + + // dd($employees); + + // Process each employee + foreach ($employees as $employee) { + + $this->myLogger->logme('error', 'Employee status and relationship check passed for employee ID: ' . $employee['id']); + + // Mail params + $params['emp_data'] = $employee; + $params['client_data'] = $client_data; + $params['notification_data'] = $notification_data; + $params['common'] = [ + 'client_id' => $client_policy['client_id'], + 'client_branch_id' => $client_policy['client_branch_id'], + 'client_policy_id' => $client_policy['id'], + 'employee_policy_id' => $employee['emp_policy_id'], + 'employee_id' => $employee['id'], + 'mail_type' => 'member_reminder_mail', + ]; + + // Send the mail notification + $mail_result = sendMailNotification::sendMailNotification('member_reminder_mail', $params); + // $this->myLogger->logme('error', 'Mail sent result: ' . json_encode($mail_result)); + $reminder_whole_mail[] = $mail_result; + } + + } + } + + } else { + $this->myLogger->logme('error', "SEND REMAINDER CRONE --- Remainder date is empty()"); + } } } else { - // echo '2'; - - $currentDate = date('d-m-Y'); - - if($currentDate == date('d-m-Y', strtotime($client_policy['reminder_date']))){ - - // echo '3'; - - $client_data = $this->clientModel->find($client_policy['client_id']); - - // Fetch notification settings - $notification_data = $this->notificationModel - ->where('client_id', $client_policy['client_id']) - ->where('template_name', 'member_reminder_mail') - ->first(); - - // Check if notification should be sent - if ($notification_data && $notification_data['enabled'] == 1 && !empty($notification_data['mail_content'])) { - - // echo '4'; - - $this->myLogger->logme('error', 'Notification should be sent for client policy ID: ' . $client_policy['id']); - - // Fetch all employees related to the client policy - $employees = $this->employeePolicyModel - ->select('employees.*') - ->join('employees', 'employee_polices.employee_id = employees.id', 'left') - ->where('employee_polices.client_policy_id', $client_policy['id']) - ->where('employees.emp_status', 'draft') - ->where('employees.is_active', 1) - ->where('employee_polices.status', 'draft') - ->where('employee_polices.is_active', 1) - ->where('employees.relationship', 'Self') - ->findAll(); - - // Process each employee - foreach ($employees as $employee) { - - if ($employee['emp_status'] == 'draft' && $employee['relationship'] == 'Self') { - $this->myLogger->logme('error', 'Employee status and relationship check passed for employee ID: ' . $employee['id']); - - // Mail params - $params['emp_data'] = $employee; - $params['client_data'] = $client_data; - $params['notification_data'] = $notification_data; - - // Send the mail notification - $mail_result = sendMailNotification::sendMailNotification('member_reminder_mail', $params); - // $this->myLogger->logme('error', 'Mail sent result: ' . json_encode($mail_result)); - $reminder_whole_mail[] = $mail_result; - } - } - } else { - // echo '5'; - $this->myLogger->logme('error', 'Notification not sent for client policy ID: ' . $client_policy['id']); - } - } + $this->myLogger->logme('error', 'Notification setup not found or not enabled'); + $this->myLogger->logme('error', 'Notification was not sent for this Client ID: ' . $client_policy['client_id']); } } // dd($reminder_whole_mail); + // print_rr($reminder_whole_mail); die; - // $this->myLogger->logme('error', 'Whole email, count: ' . $reminder_whole_mail); - // Process and queue bulk emails - $temp_whole_data = []; - $count = 0; - - foreach ($reminder_whole_mail as $whole_index => $values) { - foreach ($values as $index => $value) { - $temp_whole_data[] = $value; - $count++; - $this->myLogger->logme('error', 'Queueing email, count: ' . $count); - - if ($count == 20 || ($whole_index == count($reminder_whole_mail) - 1 && $index == count($values) - 1)) { - if (!empty($temp_whole_data)) { - Jobs::addJob(['job_name' => 'bulk_mail', 'payload' => $temp_whole_data]); - $this->myLogger->logme('error', 'Added bulk mail job: ' . json_encode($temp_whole_data)); - $temp_whole_data = []; - $count = 0; - } - } + if (!empty($reminder_whole_mail) && count($reminder_whole_mail) > 0) { + + $reminder_whole_mail = array_chunk($reminder_whole_mail, 20); + foreach ($reminder_whole_mail as $key => $value) { + // $job_details = new Jobs(); + $r = Jobs::addJob(['job_name' => 'bulk_mail', 'payload' => $value]); } } - - if (count($temp_whole_data) > 0) { - Jobs::addJob(['job_name' => 'bulk_mail', 'payload' => $temp_whole_data]); - $this->myLogger->logme('error', 'Added final bulk mail job: ' . json_encode($temp_whole_data)); + + if (count($reminder_whole_mail) > 0) { return true; - } - - if(count($reminder_whole_mail) > 0){ - return true; - }else{ + } else { return false; } - } - public function sendManualReminder($client_id, $client_branch_id) + public function sendManualReminder($client_id, $client_branch_id, $client_policy_id = null) { + $this->myLogger->logme('error','Log Works'); + $this->myLogger->logme('error', "sendManualRemainder called with client_id: {$client_id}, client_branch_id: {$client_branch_id}"); - $client_policy_data = $this->clientPolicyModel->getPolicyDetailsForRemainder($client_id, $client_branch_id); + $client_policy_data = $this->clientPolicyModel->getPolicyDetailsForRemainder($client_id, $client_branch_id, $client_policy_id); // print_r($client_policy_data); die; // print_r($this->clientPolicyModel->getLastQuery()); die; // $this->myLogger->logme('error', "Policy details fetched: " . json_encode($client_policy_data)); if ($client_policy_data) { $result = $this->sendRemainderMail($client_policy_data); + log_message('error',json_encode($result)); + $this->myLogger->logme('error',$result); $this->myLogger->logme('error', "Manual Remainder Mail sending result: " . ($result ? 'success' : 'failure')); if ($result) { @@ -545,7 +619,7 @@ class DashboardController extends AdminController } } - public function sendManualEcard($client_id, $client_branch_id, $policy_id) + public function sendManualEcard($client_id, $client_branch_id, $policy_id) { $this->myLogger->logme('error', "sendManualEcard called with client_id: {$client_id}, client_branch_id: {$client_branch_id}, policy id : {$policy_id}"); @@ -555,6 +629,7 @@ class DashboardController extends AdminController { return $this->respond(['status' => false, 'code' => 400, 'message' => 'No template found','message2' => 'Failed' ], 200); } + $emp_data = $this->employeePolicyModel->getEmployeePolicyForEcard($policy_id); if(count($emp_data) == 0) @@ -574,7 +649,8 @@ class DashboardController extends AdminController } - public function data_construct_for_bds($data){ + public function data_construct_for_bds($data) + { $groupedData = [ 'under_process' => [], diff --git a/app/Controllers/EmpDataServiceController.php b/app/Controllers/EmpDataServiceController.php index 9ae9e2d1..fa3d4378 100755 --- a/app/Controllers/EmpDataServiceController.php +++ b/app/Controllers/EmpDataServiceController.php @@ -157,7 +157,14 @@ class EmpDataServiceController extends BaseController return 5; } - $cash_balance = $this->clientDepositModel->where('cd_ac_no', $policy_details['cd_ac_no'])->orderBy('id', 'DESC')->first(); + $cash_balance = $this->clientDepositModel + ->where('cd_ac_pk', $policy_details['cd_ac_pk']) + // ->where('cd_ac_no', $policy_details['cd_ac_no']) + ->where('is_active', 1) + ->orderBy('id', 'DESC') + ->first(); + + // dd(db_connect()->getLastQuery(), $cash_balance); if ($cash_balance == null) { $balance = $this->CDMasterModel @@ -169,13 +176,13 @@ class EmpDataServiceController extends BaseController $cash_balance['balance'] = $balance['opening_bal']; } - // Calculate the total amount from the objects - $totals = 0; - foreach ($objects as $item) { - $totals = $totals + $item->total; - } - - $totals = round($totals, 2); + // Calculate the total amount from the objects + $totals = 0; + foreach ($objects as $item) { + $totals = $totals + $item->total; + } + + $totals = round($totals, 2); if($export_data['insurer_or_tpa'] == 'insurer') //check CD amt related issue for only insurer, not tpa { @@ -205,9 +212,6 @@ class EmpDataServiceController extends BaseController // Log the export file name $this->myLogger->logme('error', 'Inception export file name : {data}', ['data' => $export_data['file_name']]); - // remove existing batch file anf batch list data every time export - $this->removeOldExportInfoFromBatchFile($export_data); - // default excel header information $excel_header_columns = [ [ @@ -258,7 +262,7 @@ class EmpDataServiceController extends BaseController [ 'column_index' => 7, 'column_name' => 'DATE OF COVERAGE', - 'db_column_name' => 'date_coverage' + 'db_column_name' => 'date_of_coverage' ], [ 'column_index' => 8, @@ -292,7 +296,7 @@ class EmpDataServiceController extends BaseController ], [ 'column_index' => 14, - 'column_name' => 'UHID', + 'column_name' => 'RISK ID', 'db_column_name' => 'uhid' ], // [ @@ -368,7 +372,7 @@ class EmpDataServiceController extends BaseController [ 'column_index' => 7, 'column_name' => 'DATE OF COVERAGE', - 'db_column_name' => 'date_coverage' + 'db_column_name' => 'date_of_coverage' ], [ 'column_index' => 8, @@ -402,7 +406,7 @@ class EmpDataServiceController extends BaseController ], [ 'column_index' => 14, - 'column_name' => 'UHID', + 'column_name' => 'RISK ID', 'db_column_name' => 'uhid' ], // [ @@ -426,16 +430,48 @@ class EmpDataServiceController extends BaseController 'db_column_name' => 'total' ] ]; + + //for addition and dependent addition adding a ENDORSEMENT NO column + if(in_array($export_data['event_type'], ['addition', 'dependent_addition'])){ + $excel_header_columns[] = [ + 'column_index' => 18, + 'column_name' => 'ENDORSEMENT NO', + 'db_column_name' => '' + ]; + } + }else{ + // get excel export format structure array - $template_json = $this->clientPolicyModel - ->select('insurer_excel_export_template.jsoncolumns') - ->join('insurer_excel_export_template', 'insurer_excel_export_template.insurer_id = client_policy.insurer_id and insurer_excel_export_template.policy_type_id = client_policy.policy_type_id') - ->where('client_policy.id', $export_data['client_policy_id']) - ->where('insurer_excel_export_template.event_name', $export_data['event_type']) - ->where('insurer_excel_export_template.is_active', 1) //Live issue changes 17-10-2024 - ->where('insurer_excel_export_template.type_name', $export_data['actions']) - ->first(); + // $template_json = $this->clientPolicyModel + // ->select('insurer_excel_export_template.jsoncolumns') + // ->join('insurer_excel_export_template', 'insurer_excel_export_template.insurer_id = client_policy.insurer_id and insurer_excel_export_template.policy_type_id = client_policy.policy_type_id') + // ->where('client_policy.id', $export_data['client_policy_id']) + // ->where('insurer_excel_export_template.event_name', $export_data['event_type']) + // ->where('insurer_excel_export_template.is_active', 1) //Live issue changes 17-10-2024 + // ->where('insurer_excel_export_template.type_name', $export_data['actions']) + // ->first(); + + $sql = " + SELECT `insurer_excel_export_template`.`jsoncolumns` + FROM `client_policy` + JOIN `insurer_excel_export_template` + ON `insurer_excel_export_template`.`insurer_id` = `client_policy`.`insurer_id` + AND `insurer_excel_export_template`.`policy_type_id` = + CASE + WHEN `client_policy`.`policy_type_id` IN (2, 3, 4, 5) THEN 2 + ELSE `client_policy`.`policy_type_id` + END + WHERE `client_policy`.`id` = '".$export_data['client_policy_id']."' + AND `insurer_excel_export_template`.`event_name` = '".$export_data['event_type']."' + AND `insurer_excel_export_template`.`is_active` = 1 + AND `insurer_excel_export_template`.`type_name` = '".$export_data['actions']."' + LIMIT 1"; + + $query = db_connect()->query($sql); + $template_json = $query->getRowArray(); + + // dd(db_connect()->getLastQuery()); if(!empty($template_json) && $template_json != null){ $excel_header_columns = json_decode($template_json['jsoncolumns'], true); @@ -444,6 +480,10 @@ class EmpDataServiceController extends BaseController } } + // remove existing batch file anf batch list data every time export + $this->removeOldExportInfoFromBatchFile($export_data); + + //convert the excel data based on the insurer $excel_data_info = generate_insurer_based_excel($excel_header_columns, $objects); // Generate Excel file @@ -507,6 +547,7 @@ class EmpDataServiceController extends BaseController $ids = []; $objects = $this->employeePolicyModel->getCorrectionEmployeesDataForExportExcel($export_data); + // dd(db_connect()->getLastQuery(),$objects); foreach ($objects as $obj) { $ids[] = $obj->id; @@ -519,33 +560,13 @@ class EmpDataServiceController extends BaseController if ($count == 0) { $this->myLogger->logme('error', 'No Record found. Endorsement ID Alread Updated. Correction export data count : {data}', ['data' => $count]); - // return false; + return false; } - $this->removeOldExportInfoFromBatchFile($export_data); - $this->myLogger->logme('error', 'Correction export file name : {data}', ['data' => $export_data['file_name']]); - - - // get excel export format structure array - $template_json = $this->clientPolicyModel - ->select('insurer_excel_export_template.jsoncolumns') - ->join('insurer_excel_export_template', 'insurer_excel_export_template.insurer_id = client_policy.insurer_id and insurer_excel_export_template.policy_type_id = client_policy.policy_type_id') - ->where('client_policy.id', $export_data['client_policy_id']) - ->where('insurer_excel_export_template.event_name', $export_data['event_type']) - ->where('insurer_excel_export_template.is_active', 1) //Live issue changes 17-10-2024 - ->where('insurer_excel_export_template.type_name', $export_data['actions']) - ->first(); - - if(!empty($template_json) && $template_json != null){ - $excel_header_columns = json_decode($template_json['jsoncolumns'], true); - }else{ - return 6; - } - - + if( $export_data['insurer_or_tpa'] == 'tpa'){ $excel_header_columns = [ @@ -553,7 +574,7 @@ class EmpDataServiceController extends BaseController ['column_index' => 1, 'column_name' => 'RISK ID', 'db_column_name' => 'uhid'], ['column_index' => 1, 'column_name' => 'NAME OF EMP/DEP', 'db_column_name' => 'emp_name'], ['column_index' => 3, 'column_name' => 'EMP/DEP TYPE', 'db_column_name' => 'emp_type'], - ['column_index' => 4, 'column_name' => 'RELATION', 'db_column_name' => 'relationship_code'], + ['column_index' => 4, 'column_name' => 'RELATION', 'db_column_name' => 'emp_relationship'], ['column_index' => 5, 'column_name' => 'DOB', 'db_column_name' => 'emp_dob'], ['column_index' => 6, 'column_name' => 'GENDER', 'db_column_name' => 'emp_gender'], ['column_index' => 7, 'column_name' => 'Wrong Data', 'db_column_name' => 'old_value'], @@ -561,6 +582,23 @@ class EmpDataServiceController extends BaseController ['column_index' => 9, 'column_name' => 'Remarks', 'db_column_name' => 'remarks'], ['column_index' => 10, 'column_name' => 'Endorsement_Id', 'db_column_name' => null] ]; + }else{ + + // get excel export format structure array + $template_json = $this->clientPolicyModel + ->select('insurer_excel_export_template.jsoncolumns') + ->join('insurer_excel_export_template', 'insurer_excel_export_template.insurer_id = client_policy.insurer_id and insurer_excel_export_template.policy_type_id = client_policy.policy_type_id') + ->where('client_policy.id', $export_data['client_policy_id']) + ->where('insurer_excel_export_template.event_name', $export_data['event_type']) + ->where('insurer_excel_export_template.is_active', 1) //Live issue changes 17-10-2024 + ->where('insurer_excel_export_template.type_name', $export_data['actions']) + ->first(); + + if(!empty($template_json) && $template_json != null){ + $excel_header_columns = json_decode($template_json['jsoncolumns'], true); + }else{ + return 6; + } } @@ -616,7 +654,12 @@ class EmpDataServiceController extends BaseController return 1; } - $cash_balance = $this->clientDepositModel->where('cd_ac_no', $policy_details['cd_ac_no'])->orderBy('id', 'DESC')->first(); + $cash_balance = $this->clientDepositModel + ->where('cd_ac_pk', $policy_details['cd_ac_pk']) + // ->where('cd_ac_no', $policy_details['cd_ac_no']) + ->where('is_active', 1) + ->orderBy('id', 'DESC') + ->first(); if ($cash_balance == null) { @@ -751,10 +794,14 @@ class EmpDataServiceController extends BaseController public function generateExcelForDeletion($export_data) - { + { + // dd($export_data); + $ids = []; $objects = $this->employeePolicyModel->getDeletionEmployeeDataForExportExcel($export_data); + // dd(db_connect()->getLastQuery()); + // dd($objects); $totals = 0; foreach ($objects as $obj) { @@ -779,22 +826,6 @@ class EmpDataServiceController extends BaseController $this->removeOldExportInfoFromBatchFile($export_data); $this->myLogger->logme('error', 'Deletion export file name : {data}', ['data' => $export_data['file_name']]); - // get excel export format structure array - $template_json = $this->clientPolicyModel - ->select('insurer_excel_export_template.jsoncolumns') - ->join('insurer_excel_export_template', 'insurer_excel_export_template.insurer_id = client_policy.insurer_id and insurer_excel_export_template.policy_type_id = client_policy.policy_type_id') - ->where('client_policy.id', $export_data['client_policy_id']) - ->where('insurer_excel_export_template.event_name', $export_data['event_type']) - ->where('insurer_excel_export_template.is_active', 1) //Live issue changes 17-10-2024 - ->where('insurer_excel_export_template.type_name', $export_data['actions']) - ->first(); - - if(!empty($template_json) && $template_json != null){ - $excel_header_columns = json_decode($template_json['jsoncolumns'], true); - }else{ - return 6; - } - if( $export_data['insurer_or_tpa'] == 'tpa'){ $excel_header_columns = [ @@ -803,19 +834,37 @@ class EmpDataServiceController extends BaseController ['column_index' => 2, 'column_name' => 'EMP NAME', 'db_column_name' => 'emp_name'], ['column_index' => 3, 'column_name' => 'DOB', 'db_column_name' => 'emp_dob'], ['column_index' => 4, 'column_name' => 'GENDER', 'db_column_name' => 'emp_gender'], - ['column_index' => 5, 'column_name' => 'RELATIONSHIP', 'db_column_name' => 'emp_relationship_code'], + ['column_index' => 5, 'column_name' => 'RELATIONSHIP', 'db_column_name' => 'emp_relationship'], ['column_index' => 6, 'column_name' => 'SUM INSURED', 'db_column_name' => 'basic_cover_si'], - ['column_index' => 7, 'column_name' => 'Date of Leaving', 'db_column_name' => 'date_of_leaving'], + ['column_index' => 7, 'column_name' => 'Date of Leaving', 'db_column_name' => 'dateofexit'], ['column_index' => 8, 'column_name' => 'Policy End Date', 'db_column_name' => 'policy_end_date'], ['column_index' => 9, 'column_name' => 'No Of Days', 'db_column_name' => 'no_of_days'], ['column_index' => 10, 'column_name' => 'Premium', 'db_column_name' => 'premium'], ['column_index' => 11, 'column_name' => 'Pro Rata Premium', 'db_column_name' => 'pro_rata_premium'], ['column_index' => 12, 'column_name' => 'GST', 'db_column_name' => 'gst'], ['column_index' => 13, 'column_name' => 'Total', 'db_column_name' => 'total'], - ['column_index' => 14, 'column_name' => 'Claim Status', 'db_column_name' => null], + ['column_index' => 14, 'column_name' => 'Claim Status', 'db_column_name' => 'claim_status'], ['column_index' => 15, 'column_name' => 'ENDORSEMENT_ID', 'db_column_name' => null] ]; + }else{ + + // get excel export format structure array + $template_json = $this->clientPolicyModel + ->select('insurer_excel_export_template.jsoncolumns') + ->join('insurer_excel_export_template', 'insurer_excel_export_template.insurer_id = client_policy.insurer_id and insurer_excel_export_template.policy_type_id = client_policy.policy_type_id') + ->where('client_policy.id', $export_data['client_policy_id']) + ->where('insurer_excel_export_template.event_name', $export_data['event_type']) + ->where('insurer_excel_export_template.is_active', 1) //Live issue changes 17-10-2024 + ->where('insurer_excel_export_template.type_name', $export_data['actions']) + ->first(); + + if(!empty($template_json) && $template_json != null){ + $excel_header_columns = json_decode($template_json['jsoncolumns'], true); + }else{ + return 6; + } + } $excel_data_info = generate_insurer_based_excel($excel_header_columns, $objects); @@ -915,7 +964,12 @@ class EmpDataServiceController extends BaseController return 5; } - $cash_balance = $this->clientDepositModel->where('cd_ac_no', $policy_details['cd_ac_no'])->orderBy('id', 'DESC')->first(); + $cash_balance = $this->clientDepositModel + ->where('cd_ac_pk', $policy_details['cd_ac_pk']) + // ->where('cd_ac_no', $policy_details['cd_ac_no']) + ->where('is_active', 1) + ->orderBy('id', 'DESC') + ->first(); if ($cash_balance == null) { $balance = $this->CDMasterModel @@ -1252,6 +1306,7 @@ class EmpDataServiceController extends BaseController $this->myLogger->logme('info', 'Inception File Validation -- Function called'); $file_id = $params['file_id']; + // dd($file_id); $this->myLogger->logme('error', 'Inception File Validation -- Batch File Table Primary ID : {data}', ['data' => $file_id]); @@ -1284,30 +1339,36 @@ class EmpDataServiceController extends BaseController // array_pop($excel_data); $inceptionHeader = [ - 'S.No', - 'NAME OF EMP/DEP', - 'EMP ID', - // 'EMP/DEP TYPE', - // 'RELATIONSHIP CODE', - 'DOB', - 'GENDER', - 'PRE EXISTING AILMENTS', - 'BASIC COVER SI', - 'DATE OF COVERAGE', - 'AGE', - 'RELATIONSHIP', - 'REMARKS', - 'POLICY END DATE', - 'NO OF DAYS', - 'TPA ID', - 'UHID', - // 'PREMIUM', - 'PRO RATA PREMIUM', - 'GST', - 'TOTAL AMOUNT' - ]; + 'S.No', + 'NAME OF EMP/DEP', + 'EMP ID', + // 'EMP/DEP TYPE', + // 'RELATIONSHIP CODE', + 'DOB', + 'GENDER', + 'PRE EXISTING AILMENTS', + 'BASIC COVER SI', + 'DATE OF COVERAGE', + 'AGE', + 'RELATIONSHIP', + 'REMARKS', + 'POLICY END DATE', + 'NO OF DAYS', + 'TPA ID', + 'RISK ID', + // 'PREMIUM', + 'PRO RATA PREMIUM', + 'GST', + 'TOTAL AMOUNT', + ]; + if(in_array($file['event_type'], ['addition', 'dependent_addition'])){ + $inceptionHeader[] = 'ENDORSEMENT NO'; + } + + // dd($inceptionHeader); foreach ($inceptionHeader as $key => $value) { + if($excel_header[$key] != $value){ $data = [ 'status' => 'failed-5', @@ -1323,49 +1384,11 @@ class EmpDataServiceController extends BaseController } } - $emp_count = count($excel_data); + //get the employee data for excel file validation $employee_data = $this->employeePolicyModel->getInceptionEmployeeDataForExportExcel($ref_data, 1); - // ->select(' - - // employee_polices.id as emp_policy_id, - // employees.name AS emp_name, - // employees.emp_code AS emp_code, - // "Has Define" as emp_type, - // employees.relationship_code AS emp_relationship_code, - // employees.dob AS emp_dob, - // employees.gender AS emp_gender, - // employee_polices.pre_existing_alignments, - // employee_polices.basic_cover_si, - // employee_polices.date_coverage, - // TIMESTAMPDIFF(YEAR, employees.dob, CURDATE()) AS emp_age, - // employees.relationship AS emp_relationship, - // employees.change_event AS change_event, - // employee_polices.policy_end_date, - // employee_polices.days, - // employee_polices.tpa_id, - // employee_polices.uhid, - // employee_polices.premium, - // employee_polices.rata_premimum, - // employee_polices.gst, - // (employee_polices.rata_premimum + employee_polices.gst) AS total - // ') - - // ->join('employees', 'employees.id = employee_polices.employee_id') - // ->where('employee_polices.client_policy_id', $client_policy_id) - // ->where('employees.client_id', $client_id) - // ->where('employees.client_branch_id', $client_branch_id) - // ->where("employee_polices.{$id} IS NULL OR employee_polices.{$id} = ''") - // ->where('employee_polices.is_active', 1) - // ->where('employee_polices.status', 'active') - // ->where('employees.is_active', 1) - // ->where('employees.emp_status', 'active') - // ->findAll(); - - - if ($employee_data == null || empty($employee_data)) { if ($insurer_or_tpa == 'tpa') { @@ -1398,7 +1421,6 @@ class EmpDataServiceController extends BaseController } $this->myLogger->logme('error', 'Inception File Validation -- UHID or TPAID already updated or the uploadedfile is not correct'); - } $excel_data_count = count($excel_data); @@ -1419,7 +1441,6 @@ class EmpDataServiceController extends BaseController $this->myLogger->logme('error', 'Inception File Validation -- excel file count partially : {data}', ['data' => $partially_updated_data]); } - if ($emp_data_count < $excel_data_count) { $data = [ @@ -1439,6 +1460,8 @@ class EmpDataServiceController extends BaseController $errors = []; // Initialize an array to store errors $missing_id = []; $batch_list_id = []; + $tpa_id_all = []; //this array to store all TPA ID + $tpa_id_duplicate = []; //store duplicate TPA ID foreach ($employee_data as $key => $emp_value) { @@ -1448,18 +1471,53 @@ class EmpDataServiceController extends BaseController break; } + //--- TPA ID Duplicate check start --- + + $current_tpa_id = $excel_data[$key][13]; + + if (isset($tpa_id_all[$current_tpa_id])) { + + // Add the current row to errors + $errors[$key][] = [ + 'row' => $key, + 'column' => 13, + 'db_data' => "Duplicate TPA ID Found", + 'excel_data' => $current_tpa_id + ]; + + // Add all existing rows with the same TPA ID to errors + foreach ($tpa_id_all[$current_tpa_id] as $existing_row) { + $errors[$existing_row][] = [ + 'row' => $existing_row, + 'column' => 13, + 'db_data' => "Duplicate TPA ID Found", + 'excel_data' => $current_tpa_id + ]; + } + + } else { + $tpa_id_all[$current_tpa_id][] = $key; + } + + //--- TPA ID Duplicate check end --- + if ($insurer_or_tpa == 'tpa') { + if ($excel_data[$key][13] === null) { $missing_id[$key][] = [ 'row' => $key, - 'column' => 15, + 'column' => 13, + 'db_data' => "TPA ID is Must", + 'excel_data' => $excel_data[$key][13] ]; } } else if ($insurer_or_tpa == 'insurer') { if ($excel_data[$key][14] === null) { $missing_id[$key][] = [ 'row' => $key, - 'column' => 16, + 'column' => 14, + 'db_data' => "UHID or Risk ID is Must", + 'excel_data' => $excel_data[$key][14] ]; } } @@ -1565,6 +1623,7 @@ class EmpDataServiceController extends BaseController } if ($emp_value['gst'] != $excel_data[$key][16]) { + $errors[$key][] = [ 'row' => $key, 'column' => 16, @@ -1599,14 +1658,15 @@ class EmpDataServiceController extends BaseController $batch_list_id[] = $emp_value['primaryKey']; } - + // dd($errors); + $error_count = count($errors); $json_errors = json_encode($errors); $missing_id_count = count($missing_id); $json_missing_id = json_encode($missing_id); - // dd($error_count, $missing_id_count, $json_errors, $json_missing_id); + // dd($error_count, $missing_id_count, $json_errors, $json_missing_id, $employee_data, $excel_data); if ($missing_id_count > 0) { @@ -1691,6 +1751,7 @@ class EmpDataServiceController extends BaseController $file_id = $params['file_id']; $file = $this->batchFileModel->find($file_id); + // dd($file); if (!$file) { @@ -1723,22 +1784,20 @@ class EmpDataServiceController extends BaseController ->first(); $get_policy_type = $this->clientPolicyModel - ->select('policy_type.policy_type, policies.policy_type_id as policy_type_id') - ->join('policies', 'policies.id = client_policy.policy_id') - ->join('policy_type', 'policy_type.id = policies.policy_type_id') + ->select('client_policy.*, policy_type.policy_type') + ->join('policy_type', 'policy_type.id = client_policy.policy_type_id', 'left') ->where('client_policy.id', $client_policy_id) ->first(); + // dd($get_policy_type); $status_val = 'success'; if ($status == 'in-progress-partially') { - $status_val = 'partially success'; } $this->myLogger->logme('error', 'Inception Update TPA and UHID -- file name : {data}', ['data' => $file['file_name']]); - $file_name_with_path = WRITEPATH . "/uploads/import_excel/" . $file['file_name']; $excel_data = $this->readExcelFileToArray($file_name_with_path); unset($excel_data[0]); // Remove header row @@ -1749,10 +1808,15 @@ class EmpDataServiceController extends BaseController $emp_details = []; $tpa_id = []; $uhid = []; + $emp_endorsement_table_data = []; + $enrollment_file_id = null; + $endorsement_id = null; $emp_count = count($excel_data); $db = \Config\Database::connect(); + // print_rr($excel_data); die; + foreach ($excel_data as $key => $value) { $name = $value[1]; @@ -1792,11 +1856,54 @@ class EmpDataServiceController extends BaseController $emp_details[] = array('id' => $result['id'], 'tpa_id' => $value[13], 'uhid' => $value[14]); } + //for addition and dependent_addition endorsement , endorsement_id update functionality + if(in_array($file['event_type'], ['addition', 'dependent_addition']) && isset($value[18])){ + + $action = 'a'; + if($file['event_type'] == "dependent_addition"){ + $action = 'da'; + } + + $endorsement_id = $value[18]; + + $result_for_endorsement = $this->empEndorsementModel + ->select('emp_endorsement.*, employees.id as emp_id, employee_polices.id as emp_policy_id') + ->join('employee_polices', 'employee_polices.id = emp_endorsement.pk') + ->join('employees', 'employees.emp_code = emp_endorsement.emp_code') + ->where('employees.emp_code', $emp_code) + ->where('employees.name', $name) + ->where('employees.client_id', $client_id) + ->where('employees.client_branch_id', $client_branch_id) + ->where('emp_endorsement.actions', $action) + ->where('employee_polices.client_policy_id', $client_policy_id) + ->where('employee_polices.is_active', 1) + ->where('employee_polices.status', 'active') + ->where('employees.is_active', 1) + ->where('employees.emp_status', 'active') + ->where('(emp_endorsement.endorsement_id IS NULL OR emp_endorsement.endorsement_id = "")') + ->groupBy('emp_endorsement.group_key') + ->first(); + + if (!empty($result_for_endorsement) && count($result_for_endorsement)) { + $enrollment_file_id = $result_for_endorsement['file_id']; //files table primary key + $emp_endorsement_table_data[] = array('id' => $result_for_endorsement['id'], 'group_key' => $result_for_endorsement['group_key'], 'endorsement_id' => $value[18], 'status' => 'complete'); + } + } + } + } + // dd($emp_endorsement_table_data, $enrollment_file_id); + + //update the employee policy data (TPAID or UHID) $return = $this->employeePolicyModel->bulkUpdate($emp_details); + if(in_array($file['event_type'], ['addition', 'dependent_addition']) && !empty($emp_endorsement_table_data)){ + $this->employeePolicyModel->updateEmpEndorsementAddition($emp_endorsement_table_data); + $this->storeEndorsementNumber($file_id, $endorsement_id, $enrollment_file_id); + } + // Update batch file status and amount $this->batchFileModel->update($file_id, [ 'count' => $emp_count, @@ -1832,7 +1939,7 @@ class EmpDataServiceController extends BaseController 'client_id' => $client_id, 'client_policy_id' => $client_policy_id, 'cd_ac_no' => $CD_Account_Number['cd_ac_no'] ?? null, - 'endorsement_no' => null, + 'endorsement_no' => $endorsement_id, 'client_branch_id' => $client_branch_id, 'count' => $emp_count, 'event_name' => $file['event_type'], @@ -1874,7 +1981,6 @@ class EmpDataServiceController extends BaseController //Endorsement Correction public function importCorrectionValidation($params) { - $this->myLogger->logme('error', 'Correction File Validation -- Function called'); $file_id = $params['file_id']; @@ -1886,6 +1992,14 @@ class EmpDataServiceController extends BaseController $batch_code = $file['batch_code']; $user_id = $file['created_by']; + $ref_data = [ + 'client_id' => $client_id, + 'client_policy_id' => $client_policy_id, + 'client_branch_id' => $client_branch_id, + 'insurer_or_tpa' => $file['insurer_or_tpa'], + 'event_type' => $file['event_type'], + ]; + $file_name_with_path = WRITEPATH . "/uploads/import_excel/" . $file['file_name']; if (!file_exists($file_name_with_path)) { @@ -1903,7 +2017,6 @@ class EmpDataServiceController extends BaseController $headers = ['Emp Code','RISK ID','NAME OF EMP/DEP','EMP/DEP TYPE','RELATION','DOB','GENDER','Wrong Data','Correct Data','Remarks','Endorsement_Id']; - foreach ($headers as $key => $value) { if($excel_header[$key] != $value){ $data = [ @@ -1920,44 +2033,10 @@ class EmpDataServiceController extends BaseController } } - - - $endorsement_data = $this->empEndorsementModel - ->select(" - emp_endorsement.id, - emp_endorsement.pk, - emp_endorsement.emp_code, - emp_endorsement.endorsement_id, - emp_endorsement.old_value, - emp_endorsement.new_value, - emp_endorsement.field_name, - emp_endorsement.remarks, - emp_endorsement.actions, - employees.id AS primaryKey, - employees.name AS emp_name, - employees.dob AS emp_dob, - employees.gender AS emp_gender, - employees.client_id AS emp_client_id, - 'Has Define' AS emp_type, - employee_polices.uhid, - employees.relationship_code - ") - ->join("employees", "employees.id = emp_endorsement.pk", "left") - ->join("employee_polices", "employees.id = employee_polices.employee_id", "left") - ->where("employees.client_id", $client_id) - ->where("employee_polices.client_policy_id", $client_policy_id) - ->where("employees.client_branch_id", $client_branch_id) - ->where("employees.is_active", 1) - ->where("employees.emp_status", "active") - ->where("emp_endorsement.actions", "c") - ->where("(emp_endorsement.endorsement_id IS NULL OR emp_endorsement.endorsement_id = '')") - ->findAll(); - - + $endorsement_data = $this->employeePolicyModel->getCorrectionEmployeesDataForExportExcel($ref_data, 1); // dd($endorsement_data, $excel_data); - if ($endorsement_data == null || empty($endorsement_data)) { $data = [ @@ -1992,8 +2071,6 @@ class EmpDataServiceController extends BaseController $this->myLogger->logme('error', 'correctionFileValidation excel file count partially : {data}', ['data' => $partially_updated_data]); } - - if ($endorsement_data_count < $excel_data_count) { $data = [ @@ -2009,7 +2086,6 @@ class EmpDataServiceController extends BaseController return 'The Excel record count exceeds the DB record count. excel file count : ' . $excel_data_count . 'db count : ' . $endorsement_data_count; } - $errors = []; // Initialize an array to store errors $missing_id = []; $batch_list_id = []; @@ -2099,17 +2175,14 @@ class EmpDataServiceController extends BaseController $batch_list_id[] = $endorsement_value['primaryKey']; } - $error_count = count($errors); $json_errors = json_encode($errors); - $missing_id_count = count($missing_id); $json_missing_id = json_encode($missing_id); // dd($error_count, $missing_id_count, $json_errors, $json_missing_id, $batch_list_id); - if ($missing_id_count > 0) { $data = [ @@ -2128,7 +2201,6 @@ class EmpDataServiceController extends BaseController } - if ($error_count > 0) { $data = [ @@ -2174,7 +2246,8 @@ class EmpDataServiceController extends BaseController } - public function importCorrectionUpdateEndorsementID($params){ + public function importCorrectionUpdateEndorsementID($params) + { $this->myLogger->logme('error', 'importCorrectionUpdateEndorsementID called'); @@ -2221,11 +2294,11 @@ class EmpDataServiceController extends BaseController $emp_details = []; $endorsement_id = []; $endorsement_details = []; + $enrollment_file_id = null; $emp_count = count($excel_data); $db = \Config\Database::connect(); - foreach ($excel_data as $key => $value) { $emp_code = $value[0]; @@ -2233,27 +2306,44 @@ class EmpDataServiceController extends BaseController $endorsement_id[] = $value[10]; $uhid = $value[1]; + $isDate = \DateTime::createFromFormat('d-M-Y', $old_value) && \DateTime::createFromFormat('d-M-Y', $old_value)->format('d-M-Y') === $old_value; + + if($isDate){ + $old_value = change_date_format($old_value); + } + + // dd($old_value, $isDate); $result = $this->empEndorsementModel - ->select('emp_endorsement.*, employees.id as emp_id') - ->join('employees', 'employees.id = emp_endorsement.pk') - ->join('employee_polices', 'employee_polices.employee_id = employees.id') - ->where('employees.emp_code', $emp_code) - ->where('employees.client_id', $client_id) - ->where('employees.client_branch_id', $client_branch_id) - ->where('employee_polices.client_policy_id', $client_policy_id) - ->where('employee_polices.uhid', $uhid) - ->where('emp_endorsement.old_value', $old_value) - - ->where('employee_polices.is_active', 1) - ->where('employee_polices.status', 'active') - ->where('employees.is_active', 1) - ->where('employees.emp_status', 'active') - ->first(); + ->select('emp_endorsement.*, employees.id as emp_id') + ->join('employees', 'employees.id = emp_endorsement.pk') + ->join('employee_polices', 'employee_polices.employee_id = employees.id') + ->where('employees.emp_code', $emp_code) + ->where('employees.client_id', $client_id) + ->where('employees.client_branch_id', $client_branch_id) + ->where('employee_polices.client_policy_id', $client_policy_id) + ->where('employee_polices.uhid', $uhid) + ->where('emp_endorsement.old_value', $old_value) + + ->where('employee_polices.is_active', 1) + ->where('employee_polices.status', 'active') + ->where('employees.is_active', 1) + ->where('employees.emp_status', 'active') + ->where("emp_endorsement.is_active", 1) + ->where("emp_endorsement.status !=", "truncated") + ->first(); + + // print_r($result); die; if (isset($result['id']) && $result['id'] !== null) { - // return $result; + $enrollment_file_id = $result['file_id']; + + if($result['field_name'] == 'dob'){ + $value[8] = change_date_format($value[8]); + } + // dd($value[8]); + $emp_details[] = array('id' => $result['emp_id'], $result['field_name'] => $value[8]); $endorsement_details[] = array('group_key' => $result['group_key'], 'id' => $result['id'], 'endorsement_id' => $value[10], 'status' => 'complete'); } @@ -2264,7 +2354,7 @@ class EmpDataServiceController extends BaseController $this->empEndorsementModel->updateBatch($endorsement_details, 'group_key'); $this->employeePolicyModel->bulkUpdateForCorrection($emp_details); - $this->storeEndorsementNumber($file_id, $endorsement_id[0]); + $this->storeEndorsementNumber($file_id, $endorsement_id[0], $enrollment_file_id); // Update batch file status and amount @@ -2294,7 +2384,6 @@ class EmpDataServiceController extends BaseController } - //Endorsement SIEnhancement public function importSIEnhancementValidation($params) { @@ -2778,6 +2867,7 @@ class EmpDataServiceController extends BaseController $employeeIds = []; $emp_details = []; $endorsement_id = ''; + $enrollment_file_id = ''; $endorsement_details = []; $totals = 0; @@ -2809,6 +2899,8 @@ class EmpDataServiceController extends BaseController ->first(); if (isset($result['id']) && $result['id'] !== null) { + + $enrollment_file_id = $result['file_id']; $emp_policy_ids[] = array('id' => $result['emp_policy_id'], 'is_active' => 0); $employeeIds[] = $result['emp_policy_id']; $endorsement_details[] = array('id' => $result['id'], 'group_key' => $result['group_key'], 'endorsement_id' => $value[19], 'status' => 'complete'); @@ -2868,7 +2960,7 @@ class EmpDataServiceController extends BaseController // } $this->employeePolicyModel->bulkUpdateForEndorsement($endorsement_details); - $this->storeEndorsementNumber($file_id, $endorsement_id); + $this->storeEndorsementNumber($file_id, $endorsement_id, $enrollment_file_id); // Update batch file status and amount @@ -2932,6 +3024,14 @@ class EmpDataServiceController extends BaseController $batch_code = $file['batch_code']; $user_id = $file['created_by']; + $ref_data = [ + 'client_id' => $client_id, + 'client_policy_id' => $client_policy_id, + 'client_branch_id' => $client_branch_id, + 'insurer_or_tpa' => $file['insurer_or_tpa'], + 'event_type' => $file['event_type'], + ]; + $file_name_with_path = WRITEPATH . "/uploads/import_excel/" . $file['file_name']; @@ -2945,7 +3045,7 @@ class EmpDataServiceController extends BaseController // array_pop($excel_data); $headers = ['S.No','EMP ID','EMP NAME','DOB','GENDER','RELATIONSHIP','SUM INSURED','Date of Leaving','Policy End Date','No Of Days','Premium','Pro Rata Premium','GST','Total','Claim Status','ENDORSEMENT_ID']; - + // dd($headers, $excel_header); foreach ($headers as $key => $value) { if($excel_header[$key] != $value){ @@ -2963,72 +3063,8 @@ class EmpDataServiceController extends BaseController } } - $db = \Config\Database::connect(); - - $sql = " - SELECT DISTINCT - a.id as endorsement_primarykey, - a.group_key, - employee_polices.id as primaryKey, - employees.name AS emp_name, - employees.emp_code AS emp_code, - employees.dob AS emp_dob, - employees.gender AS emp_gender, - employees.relationship AS emp_relationship, - 'Has Define' as emp_type, - - employee_polices.basic_cover_si, - employee_polices.uhid as risk_id, - employee_polices.policy_end_date, - employee_polices.rata_premimum as premium, - - - deletiondata.empstatus, - deletiondata.changeevent, - deletiondata.dateofexit, - deletiondata.reasonforexit, - deletiondata.status, - - DATEDIFF(employee_polices.policy_end_date, deletiondata.dateofexit) AS no_of_days, - ROUND((employee_polices.rata_premimum * DATEDIFF(employee_polices.policy_end_date, deletiondata.dateofexit)) / 365, 2) AS pro_rata_premium, - ROUND(((employee_polices.rata_premimum * DATEDIFF(employee_polices.policy_end_date, deletiondata.dateofexit)) / 365) * 0.18, 2) AS gst, - ROUND(((employee_polices.rata_premimum * DATEDIFF(employee_polices.policy_end_date, deletiondata.dateofexit)) / 365) + (((employee_polices.rata_premimum * DATEDIFF(employee_polices.policy_end_date, deletiondata.dateofexit)) / 365) * 0.18), 2) AS total - FROM - emp_endorsement a - LEFT JOIN - employees ON a.emp_code = employees.emp_code and a.pk = employees.id - LEFT JOIN - employee_polices ON employees.id = employee_polices.employee_id - - LEFT JOIN( - - select aa.emp_code, aa.new_value as 'empstatus', bb.new_value as 'changeevent', cc.new_value as 'dateofexit', dd.new_value as 'reasonforexit', ee.new_value as 'status' from - - ( SELECT a1.emp_code, a1.field_name, a1.new_value from emp_endorsement as a1 where a1.field_name = 'emp_status') aa - left join - ( SELECT b1.emp_code, b1.field_name, b1.new_value from emp_endorsement as b1 where b1.field_name = 'change_event') bb on aa.emp_code = bb.emp_code - left join - ( SELECT c1.emp_code, c1.field_name, c1.new_value from emp_endorsement as c1 where c1.field_name = 'date_of_exit') cc on aa.emp_code = cc.emp_code - left join - ( SELECT d1.emp_code, d1.field_name, d1.new_value from emp_endorsement as d1 where d1.field_name = 'reason_for_exit') dd on aa.emp_code = dd.emp_code - left JOIN - ( SELECT e1.emp_code, e1.field_name, e1.new_value from emp_endorsement as e1 where e1.field_name = 'status') ee on aa.emp_code = ee.emp_code - - ) as deletiondata on a.emp_code = deletiondata.emp_code - - WHERE employee_polices.client_policy_id = '$client_policy_id' - AND employees.client_branch_id = '$client_branch_id' - AND a.actions = 'd' - AND employee_polices.is_active = 1 - AND employee_polices.status = 'active' - AND employees.is_active = 1 - AND employees.emp_status = 'active' - AND (a.endorsement_id IS NULL OR a.endorsement_id = '') - group by group_key - "; - - $query = $db->query($sql); - $endorsement_data = $query->getResultArray(); + $objects = $this->employeePolicyModel->getDeletionEmployeeDataForExportExcel($ref_data, 1); + $endorsement_data = $objects; // dd($endorsement_data); @@ -3341,6 +3377,7 @@ class EmpDataServiceController extends BaseController $employee_policy_table_data = []; $employee_policy_table_primaryKey = []; $endorsement_id = ''; + $enrollment_file_id = null; //files table primary key $totals = 0; @@ -3361,13 +3398,16 @@ class EmpDataServiceController extends BaseController 'emp_name' => $emp_name, 'emp_code' => $emp_code ]; + $result = $this->employeePolicyModel->fetchEmpEndorsementData($fetch_data); + // dd($result, db_connect()->getLastQuery()); if (isset($result['emp_endorsement_primarykey']) && $result['emp_endorsement_primarykey'] !== null) { + $enrollment_file_id = $result['file_id']; //files table primary key $employee_policy_table_primaryKey[] = $result['emp_policy_primarykey']; //for cash deposite - $employee_policy_table_data[] = array('id' => $result['emp_policy_primarykey'], 'date_of_exit' => $result['date_of_exit'], 'reason_for_exit' => $result['reason_for_exit'], 'status' => $result['status']); - $employees_table_data[] = array('id' => $result['employees_id'], 'emp_status' => $result['status']); + $employee_policy_table_data[] = array('id' => $result['emp_policy_primarykey'], 'date_of_exit' => change_date_format($result['date_of_exit']), 'reason_for_exit' => $result['reason_for_exit'], 'claim_status' => $result['claim_status'], 'status' => $result['status']); + // $employees_table_data[] = array('id' => $result['employees_id'], 'emp_status' => $result['status']); $emp_endorsement_table_data[] = array('id' => $result['emp_endorsement_primarykey'], 'group_key' => $result['group_key'], 'endorsement_id' => $value[15], 'status' => 'complete'); } @@ -3379,11 +3419,10 @@ class EmpDataServiceController extends BaseController // dd($employees_table_data, $emp_endorsement_table_data, $employee_policy_table_data, $employee_policy_table_primaryKey, $totals, $emp_count); - // Check if $employees_table_data is null or empty - if (empty($employees_table_data)) { - return ['status' => 'error', 'message' => 'Employees table data is empty or null.']; - } + // if (empty($employees_table_data)) { + // return ['status' => 'error', 'message' => 'Employees table data is empty or null.']; + // } // Check if $employee_policy_table_data is null or empty if (empty($employee_policy_table_data)) { @@ -3395,10 +3434,10 @@ class EmpDataServiceController extends BaseController return ['status' => 'error', 'message' => 'Employee endorsement table data is empty or null.']; } - $this->employeeModel->updateBatch($employees_table_data, 'id'); + // $this->employeeModel->updateBatch($employees_table_data, 'id'); $this->employeePolicyModel->updateBatch($employee_policy_table_data, 'id'); $this->employeePolicyModel->bulkUpdateForEndorsement($emp_endorsement_table_data); - $this->storeEndorsementNumber($file_id, $endorsement_id); + $this->storeEndorsementNumber($file_id, $endorsement_id, $enrollment_file_id); // Update batch file status and amount $this->batchFileModel->update($file_id, [ @@ -3407,12 +3446,12 @@ class EmpDataServiceController extends BaseController 'amount' => $rounded_totals, ]); - $this->myLogger->logme('error', 'Deletion Update Endorsement ID -- Employee count : {data}', ['data' => $emp_count]); $this->myLogger->logme('error', 'Deletion Update Endorsement ID -- Batch File status : {data}', ['data' => $status_val]); //call the cash deposite function if ($file['insurer_or_tpa'] == 'insurer') { + $policy_name = $this->getPolicyNameUsingClientPolicyId($client_policy_id); $job_details = new Jobs(); $r = Jobs::addJob(['job_name' => 'cashDepositCalculationForDeletion', 'payload' => [ @@ -3842,7 +3881,7 @@ class EmpDataServiceController extends BaseController //end not in use /** - * The below functions are Calculates and records cash deposits for employee policies at inception. + * The below functions are Calculates and records cash deposits for employee policies at Deletion. * * @param array $arrayData An array containing necessary data including : * - employee IDs, @@ -3868,7 +3907,8 @@ class EmpDataServiceController extends BaseController foreach($units as $unit) { - + $client_policy_id = $arrayData['client_policy_id']; + $cd_ac_pk = $this->clientPolicyModel->select('cd_ac_pk')->where('id',$client_policy_id)->first(); $amount = $this->employeePolicyModel->query(" SELECT SUM(rata_premimum + gst) AS total_sum FROM employee_polices @@ -3896,6 +3936,7 @@ class EmpDataServiceController extends BaseController 'updated_by' => $arrayData['user_id'], 'event_name' => $arrayData['event_name'], 'is_active' => 1, + 'cd_ac_pk' => $cd_ac_pk['cd_ac_pk'] ]; $response = DepositHelper::saveDeposit($data, $arrayData['user_id']); @@ -3952,6 +3993,7 @@ class EmpDataServiceController extends BaseController 'updated_by' => $arrayData['user_id'], 'event_name' => $arrayData['event_name'], 'is_active' => 1, + 'cd_ac_pk' => $insurer_id['cd_ac_pk'] ]; $response = DepositHelper::saveDeposit($data, $arrayData['user_id']); @@ -3987,7 +4029,7 @@ class EmpDataServiceController extends BaseController // dd($client_branch_data, $units); $get_insurer_id_from_client_policy = db_connect()->table('client_policy') - ->select('insurer_id') + ->select('insurer_id,cd_ac_pk') ->where('id', $arrayData['client_policy_id']) ->get() ->getRowArray(); @@ -4040,6 +4082,7 @@ class EmpDataServiceController extends BaseController WHERE employee_polices.id IN (" . implode(',', $arrayData['employeeIds']) . ") AND emp_endorsement.pk IN (" . implode(',', $arrayData['employeeIds']) . ") + AND employee_polices.claim_status = 0 AND emp_endorsement.field_name = 'date_of_exit' ")->getRow(); @@ -4064,6 +4107,7 @@ class EmpDataServiceController extends BaseController 'updated_by' => $arrayData['user_id'], 'event_name' => $arrayData['event_name'], 'is_active' => 1, + 'cd_ac_pk' => $insurer_id['cd_ac_pk'] ]; $response = DepositHelper::saveDeposit($data, $arrayData['user_id']); @@ -4206,7 +4250,7 @@ class EmpDataServiceController extends BaseController $result[] = array( "field_name" => 'Exit on', - "data" => change_date_format($obj->date_of_leaving, 'Y-m-d', 'd-M-Y'), + "data" => change_date_format($obj->dateofexit, 'Y-m-d', 'd-M-Y'), ); $result[] = array( @@ -4319,7 +4363,15 @@ class EmpDataServiceController extends BaseController $temp_id = $ids[0]; $get_client_info = $this->employeePolicyModel - ->select('employee_polices.client_policy_id, employees.emp_code, employees.email_corporate, employees.client_id, employees.name, employee_polices.rand_string, employee_polices.tpa_id') + ->select(' + employee_polices.client_policy_id, + employees.emp_code, + employees.email_corporate, + employees.client_id, + employees.name, + employee_polices.rand_string, + employee_polices.tpa_id' + ) ->join('employees', 'employees.id = employee_polices.employee_id') ->where('employees.emp_status', 'active') ->where('employees.is_active', '1') @@ -4350,11 +4402,32 @@ class EmpDataServiceController extends BaseController $count = 0; $processedCount = 0; $wholeData = []; + // $wholeMailData = []; foreach ($ids as $id) { + $emp_details = $this->employeePolicyModel - ->select('employee_polices.client_policy_id, employees.relationship, employees.emp_code, employees.email_corporate, employees.client_id, employees.name, employee_polices.rand_string, employee_polices.tpa_id') + ->select(' + employees.id as emp_id, + employees.client_id, + employees.client_branch_id, + employees.relationship, + employees.emp_code, + employees.email_corporate, + employees.name, + employees.mobile, + employees.basic_cover_si, + + cp.policy_type_id, + cp.is_addon, + + employee_polices.id as emp_policy_id, + employee_polices.client_policy_id, + employee_polices.rand_string, + employee_polices.tpa_id + ') ->join('employees', 'employees.id = employee_polices.employee_id') + ->join('client_policy cp', 'employee_polices.client_policy_id = cp.id') ->where('employees.emp_status', 'active') ->where('employees.is_active', '1') ->where('employee_polices.status', 'active') @@ -4365,7 +4438,8 @@ class EmpDataServiceController extends BaseController if ($emp_details) { $this->myLogger->logme('error', 'sendMailForDownloadingECard - Processing employee_policy_id: {id}', ['id' => $id]); - if (!empty($emp_details['email_corporate']) && $emp_details['relationship'] === 'Self') { + if (!empty($emp_details['email_corporate'])) { + $params = [ 'rand_string' => $emp_details['rand_string'], 'tpa_id' => $emp_details['tpa_id'], @@ -4373,9 +4447,21 @@ class EmpDataServiceController extends BaseController 'client_data' => $client_data, 'get_emp_email_and_other_details' => $emp_details, ]; + + $params['common'] = [ + 'client_id' => $emp_details['client_id'], + 'client_branch_id' => $emp_details['client_branch_id'], + 'client_policy_id' => $emp_details['client_policy_id'], + 'employee_policy_id' => $emp_details['emp_policy_id'], + 'employee_id' => $emp_details['emp_id'], + 'mail_type' => 'member_ecard_mail', + ]; + $wholeData[] = sendMailNotification::sendMailNotification('member_ecard_mail', $params); + // $wholeMailData[] = sendMailNotification::sendMailNotification('member_ecard_mail', $params); $count++; } + $processedCount++; // Send batch emails or handle single email @@ -4396,6 +4482,8 @@ class EmpDataServiceController extends BaseController } } } + + // dd($wholeMailData); $this->myLogger->logme('error', 'sendMailForDownloadingECard - Email processing completed'); return true; @@ -4406,7 +4494,6 @@ class EmpDataServiceController extends BaseController } } - public function readExcelFileToArray($path) { $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($path); @@ -4501,7 +4588,7 @@ class EmpDataServiceController extends BaseController $this->messageModel->insert($msg_data); } - public function storeEndorsementNumber($file_id, $endorsement_no) + public function storeEndorsementNumber($file_id, $endorsement_no, $enrollment_file_id) { // Log the function entry with input parameters $this->myLogger->logme('error', "storeEndorsementNumber --- Starting function with file_id: $file_id and endorsement_no: $endorsement_no"); @@ -4537,6 +4624,7 @@ class EmpDataServiceController extends BaseController 'insurer_id' => $filedata['insurer_id'], 'tpa_id' => $filedata['tpa_id'], 'endorsement_no' => $endorsement_no, + 'file_id' => $enrollment_file_id, 'endorsement_type' => $filedata['event_type'], 'created_by' => $filedata['created_by'], ]); diff --git a/app/Controllers/EmployeeController.php b/app/Controllers/EmployeeController.php index c308d65f..56dbc4eb 100755 --- a/app/Controllers/EmployeeController.php +++ b/app/Controllers/EmployeeController.php @@ -24,6 +24,7 @@ use App\Models\TPAModel; use App\Models\InsurerExcelExportTemplateModel; use App\Models\InsurerModel; use App\Models\ClientDepositModel; +use App\Models\PolicyPremium2Model; use App\Controllers\Jobs; @@ -40,7 +41,7 @@ use PhpOffice\PhpSpreadsheet\Writer\Xlsx; use Dompdf\Dompdf; use Dompdf\Options; - +use Kint; class EmployeeController extends AdminController { @@ -62,6 +63,7 @@ class EmployeeController extends AdminController protected $excelExportTemplateModel; protected $insurerModel; protected $cashDepositModel; + protected $PolicyPremium2Model; public function __construct() { @@ -81,6 +83,7 @@ class EmployeeController extends AdminController $this->policiesModel = new PolicesModel(); $this->insurerModel = new InsurerModel(); $this->cashDepositModel = new ClientDepositModel(); + $this->PolicyPremium2Model = new PolicyPremium2Model(); } public function list() @@ -108,7 +111,7 @@ class EmployeeController extends AdminController emp_name : $filterData['emp_name'] ?? null, status : $filterData['status'] ?? [], ); - + // log_message('error',json_encode($data['employees'])); // Set getData in $data array with the processed $filterData $data['getData'] = $filterData; } @@ -207,7 +210,9 @@ class EmployeeController extends AdminController // $this->fileModel->where('id', '12')->set(['status' => 'failed','reason' => $failure_reason])->update(); // dd($failure_reason); // } - + // $this->truncateFileData(747, 5) ; + // print_rr($this->cloneWorksheet()); + // die(); if ($this->request->getMethod() == 'post') { //validate uploaded file @@ -308,14 +313,8 @@ class EmployeeController extends AdminController 'c.short_name', 'cb.branch_name', 'cp.id as client_policy_id', - '(SELECT COUNT(*) - FROM employees e - JOIN employee_polices ep ON e.id = ep.employee_id - WHERE e.file_id = files.id AND ep.client_policy_id = files.policy_id) as employee_count', - '(SELECT SUM(ep.rata_premimum) + SUM(ep.gst) - FROM employees e - JOIN employee_polices ep ON e.id = ep.employee_id - WHERE e.file_id = files.id AND ep.client_policy_id = files.policy_id) as total', + '"0" as employee_count', + '"0" as total', 'policy_type.policy_type' , 'cp.policy_no' , ]) @@ -330,20 +329,46 @@ class EmployeeController extends AdminController ->find(); // dd($data['fileList']); - $data['batch_list'] = $this->batchFileModel->select( - 'batch_files.*, + $data['batch_list'] = $this->batchFileModel->select(" + + batch_files.id, + batch_files.client_id, + batch_files.client_policy_id, + batch_files.batch_code, + batch_files.file_name, + batch_files.insurer_or_tpa, + batch_files.event_type, + batch_files.actions, + batch_files.count, + batch_files.created_by, + batch_files.created_at, + batch_files.updated_by, + batch_files.updated_at, + batch_files.is_active, + batch_files.amount, + batch_files.status, + batch_files.client_branch_id, + + CASE + WHEN batch_files.status = 'partially success' THEN + batch_files.error_data + ELSE + error_data = null + END AS error_data, + clients.short_name as client_short_name, client_branch.branch_name, client_policy.policy_no, policy_type.policy_type - ') - ->join('client_policy', 'client_policy.id = batch_files.client_policy_id') - ->join('client_branch', 'client_branch.id = batch_files.client_branch_id') - ->join('policy_type', 'policy_type.id = client_policy.policy_type_id') - ->join('clients', 'clients.id = client_policy.client_id') - ->orderBy('batch_files.id', 'desc') - ->limit(100) - ->find(); + + ") + ->join('client_policy', 'client_policy.id = batch_files.client_policy_id') + ->join('client_branch', 'client_branch.id = batch_files.client_branch_id') + ->join('policy_type', 'policy_type.id = client_policy.policy_type_id') + ->join('clients', 'clients.id = client_policy.client_id') + ->orderBy('batch_files.id', 'desc') + ->limit(100) + ->find(); // dd($data['fileList']);die(); @@ -626,6 +651,7 @@ class EmployeeController extends AdminController session()->setFlashdata('error', $return); return redirect()->to(base_url('employee/upload')); } + } else if ($event_type == 'si_enhancement') { @@ -711,16 +737,25 @@ class EmployeeController extends AdminController public function enrollmentClientList() { $data = []; - $client_list = $this->clientModel->findAll(); - $branch_list = $this->clientBranchModel->findAll(); + $client_list = $this->clientModel->where('clients.is_active', 1)->findAll(); + $branch_list = $this->clientBranchModel->where('client_branch.is_active', 1)->findAll(); + $policy_list = $this->clientPolicyModel + ->select('client_policy.*, policy_type.policy_type') + ->join('policy_type', 'client_policy.policy_type_id = policy_type.id') + ->where('client_policy.is_active', 1) + ->findAll(); + $data['client_list'] = $client_list; $data['branch_list'] = $branch_list; + $data['policy_list'] = $policy_list; // Get session data if available $data['selected_client_id'] = session()->get('client_id'); $data['selected_branch_id'] = session()->get('branch_id'); $data['selected_type'] = session()->get('type'); + // dd($data); + $this->myLogger->logme('error', 'list called'); return $this->loadLayout('enrollment_list', $data); @@ -734,11 +769,16 @@ class EmployeeController extends AdminController employees.emp_status, auth_history.user_type') ->join('employees', $client_id .'= employees.client_id AND ' . $branch_id . '= employees.client_branch_id', 'left') ->join('auth_history', 'employees.id = auth_history.user_id AND "employee" = auth_history.user_type', 'left') + ->where('employees.is_active', 1) + ->where('employees.emp_status !=', 'truncated') + ->groupBy('employees.id') ->findAll(); $groupedData = []; $employeeId = ''; + foreach ($results as $row) { + if($employeeId != $row['employee_id']){ $employeeId = $row['employee_id']; }else{ @@ -751,7 +791,8 @@ class EmployeeController extends AdminController $employeeUserType = $row['user_type']; - if ($employeeId !== null && $employeeRelationship == 'Self') { + // if ($employeeId !== null && $employeeRelationship == 'Self') { + if ($employeeId !== null) { // Append employee info to the branch's employees list $groupedData[] = [ 'employee_id' => $employeeId, @@ -1066,6 +1107,7 @@ class EmployeeController extends AdminController return $response; } + //E-CARD DOWNLOAD FUNCTION public function generateIDCardForEmployee($rand_string, $people = 0) { // dd($rand_string, $people); @@ -1115,7 +1157,8 @@ class EmployeeController extends AdminController // 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 = 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); @@ -1134,6 +1177,9 @@ class EmployeeController extends AdminController $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'], @@ -1166,6 +1212,8 @@ class EmployeeController extends AdminController '{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); @@ -1205,28 +1253,35 @@ class EmployeeController extends AdminController } - //truncateFileDataIn DB (de activate rows) + //truncateFileDataIn DB (de activate rows) NEW FUNCTION public function truncateFileData($file_id, $role_id = null) - { + { + $this->myLogger->logme('error', '---- truncateFileData Function called ----'); $file_id = $this->request->uri->getSegment(3); - // $file_id = 112; + // $file_id = 747; + + $this->myLogger->logme('error', 'File id for truncate : -- FILE ID : {data} --', ['data' => $file_id]); + + //get the files data $file = $this->fileModel->find($file_id); + $client_id = $file['client_id']; $client_policy_id = $file['policy_id']; $loggedInUserID = get_session_userid(); + //get the client policy data $policy_data = $this->clientPolicyModel->where('id', $client_policy_id)->first(); + + //get the cd transaction data based on the insurer and client $cd_tranction = $this->cashDepositModel - ->where('client_id', $client_id) - ->where('insurer_id', $policy_data['insurer_id']) - ->where('event_name',$file['action']) - ->where('client_policy_id', $client_policy_id) + ->where('client_id', $client_id) //client + ->where('insurer_id', $policy_data['insurer_id']) //insurer + ->where('event_name',$file['action']) //event + ->where('client_policy_id', $client_policy_id)//policy ->orderBy('id', 'desc') ->first(); - // $file['action'] = 'si_enhancement'; - // $result = []; - // !dd($file); + // print_r($file); die; if ($file['action'] == 'inception' || $file['action'] == 'dependent_addition' || $file['action'] == 'addition' || $file['action'] == 'enrollment' || $file['action'] == 'missed_inception') { @@ -1236,46 +1291,140 @@ class EmployeeController extends AdminController $result = $this->employeeModel->getEmpListByFileId(file_id: $file_id, emp_status: ['active'], policy_status: ['active']); } - // ~dd($result); + // print_r($result); die; if (count($result) && $role_id == null) { + if(get_role_id() == 1 || get_role_id() == 5){ return $this->respond(['role' => get_role_id(), 'dataStatus' => false, 'code' => 404, 'message' => 'File data already processed. Do you want to truncate data from uploaded file?'], 200); }else{ return $this->respond(['role' => get_role_id(), 'dataStatus' => false, 'code' => 404, 'message' => 'File data already processed'], 200); } + } else { - //update emp and emp plocies - $db = db_connect(); - $query = "UPDATE employees JOIN employee_polices ON employees.id = employee_polices.employee_id and employees.file_id = $file_id SET employees.emp_status = 'truncated', employee_polices.status = 'truncated', employees.is_active = 0,employee_polices.is_active = 0 WHERE employees.file_id = $file_id"; - $db->query($query); - $affectedRows = $db->affectedRows(); - // print_r($db->getLastQuery()); die; - // $affectedRows = 10; + $this->myLogger->logme('error', '---- TRUNCATED STARTED WITH ADMIN OR HEAD PERMISSION ----'); + $this->myLogger->logme('error', '---- Event Type : -- {data} ----', ['data' => $file['action']]); - //update file status - $this->fileModel->where('id', $file_id)->set(['status' => 'truncated'])->update(); + if($file['action'] != 'enrollment') + { + $employee_policy_data_with_file_id = $this->employeePolicyModel->where('file_id', $file_id)->findAll(); - if($cd_tranction){ + if(!empty($employee_policy_data_with_file_id) && count($employee_policy_data_with_file_id) > 0){ - $cd_data = [ - 'amount' => $cd_tranction['amount'], - 'sub_type_id' => 8, - 'endorsement_no' => null, - 'insurer_id' =>$policy_data['insurer_id'], - 'description' => 'The policy Truncated by Admin or Head', - 'transaction_type' => 'Credit', - 'updated_by' => 1, - 'client_id' => $client_id, - 'client_policy_id' => $client_policy_id, - 'cd_ac_no' => $policy_data['cd_ac_no'] ?? null, - 'event_name' => $file['action'], - ]; + // GET THE CD TRANSACTION AMOUNT + $cd_amount_total = $this->employeePolicyModel->calculateCdTranctionAmount($file_id); + $cd_amount = $cd_amount_total['total'] ?? 0; + $this->myLogger->logme('error', '---- CD Amount : {data} ----', ['data' => $cd_amount]); + + //STEP: 1 - Update employee policy table + $db = db_connect(); + $query = " + UPDATE employee_polices + SET employee_polices.status = 'truncated', employee_polices.is_active = 0 + WHERE employee_polices.file_id = $file_id + "; + $db->query($query); + $affectedRows = $db->affectedRows(); + $this->myLogger->logme('error', '---- employee_polices table update query : {data} ----', ['data' => $query]); + $this->myLogger->logme('error', '---- employee_polices table updated - Affected Rows : {data} ----', ['data' => $affectedRows]); + // print_r($db->getLastQuery()); die; + + //STEP:2 - Update emp_endorsement Table + if(in_array($file['action'], ['addition', 'dependent_addition'])){ + $this->empEndorsementModel->where('file_id', $file_id)->set(['status' => 'truncated','is_active' => 0])->update(); + $this->myLogger->logme('error', '---- emp_endorsement table updated ----'); + } + + //STEP:3 - Update files table status + $this->fileModel->where('id', $file_id)->set(['status' => 'truncated'])->update(); + $this->myLogger->logme('error', '---- files table updated ----'); + + //FINAL STEP - Update reverse entry in cash_deposite table + if(!empty($cd_amount)){ + + $cd_data = [ + 'amount' => $cd_amount, + 'sub_type_id' => 8, + 'endorsement_no' => null, + 'insurer_id' =>$policy_data['insurer_id'], + 'description' => 'The policy Truncated by Admin or Head', + 'transaction_type' => 'Credit', + 'updated_by' => 1, + 'client_id' => $client_id, + 'client_policy_id' => $client_policy_id, + 'cd_ac_no' => $policy_data['cd_ac_no'] ?? null, + 'cd_ac_pk' => $policy_data['cd_ac_pk'] ?? null, + 'event_name' => $file['action'], + ]; + + $response = DepositHelper::saveDeposit($cd_data, $loggedInUserID); + $this->myLogger->logme('error', 'cash_deposite table updated -- cd transaction'); + } + + }else{ + + $this->myLogger->logme('error', '---- There is no data to truncate ----'); + return $this->respond(['role' => get_role_id(), 'dataStatus' => false, 'code' => 404, 'message' => 'There is no data to truncate'], 200); + } + + } + else + { + // echo 'came here...1'; + //check all dependents added by self and other dependent policies + $emp_codes = $this->employeeModel->select('emp_code') + ->where('file_id', $file_id) + ->findAll(); + $emp_codes = array_column($emp_codes,'emp_code'); + // Kint::dump($emp_codes);//die; + + $dependent_policies = $this->clientPolicyModel->select('id') + ->where('base_policy', $client_policy_id) + ->findAll(); + // $dependent_policies = [ [10],[25],[35] ]; + // Kint::dump($dependent_policies); + // Kint::dump(array_column($dependent_policies,'id')); + if(count($dependent_policies)) + { + $dependent_policies = array_column($dependent_policies,'id'); + // Kint::dump($dependent_policies); + $second_level_dependent_policies = $this->clientPolicyModel->select('id') + ->whereIn('base_policy', $dependent_policies) + ->findAll(); + // dd($second_level_dependent_policies); + if(count($second_level_dependent_policies)) + { + $second_level_dependent_policies = array_column($second_level_dependent_policies,'id'); + } + + $dependent_policies = array_merge($dependent_policies,$second_level_dependent_policies); + } + $dependent_policies = array_merge($dependent_policies,[$client_policy_id]); + // Kint::dump($dependent_policies); + + //update emp and emp plocies + $db = db_connect(); + $emp_codes = '(' . implode(',', array_map(fn($code) => "'$code'", $emp_codes)) . ')'; + $dependent_policies = '(' . implode(',', $dependent_policies) . ')'; + $query = " + UPDATE employee_polices + JOIN employees ON employees.id = employee_polices.employee_id and employees.emp_code in $emp_codes + SET employee_polices.status = 'truncated', employee_polices.is_active = 0 + WHERE employee_polices.client_policy_id in $dependent_policies + "; + // print_r($query); die; + $db->query($query); + $affectedRows = $db->affectedRows(); + + // dd($affectedRows); + $affectedRows = $affectedRows * 2; + $this->fileModel->where('id', $file_id)->set(['status' => 'truncated'])->update(); - $response = DepositHelper::saveDeposit($cd_data, $loggedInUserID); } - return $this->respond(['dataStatus' => true, 'code' => 200, 'data' => round($affectedRows / 2)], 200); + $this->myLogger->logme('error', 'SUCCESSFULLY TRUNCATED'); + + return $this->respond(['dataStatus' => true, 'code' => 200, 'data' => round($affectedRows / 2)], 200); } } else if ($file['action'] == 'si_enhancement' || $file['action'] == 'correction' || $file['action'] == 'deletion') { @@ -1291,23 +1440,57 @@ class EmployeeController extends AdminController // print_r($this->empEndorsementModel->getLastQuery()); // echo $res[0]->count;die(); + if ($res[0]->count == 0 || $role_id == 5 || $role_id == 1) { - //update truncated status to db + + $this->myLogger->logme('error', 'TRUNCATED STARTED WITH ADMIN OR HEAD PERMISSION'); + $this->myLogger->logme('error', 'Event Type : -- {data} --', ['data' => $file['action']]); + + $transaction_type = 'Credit'; + $cd_amount = $cd_tranction['amount']; + + if($file['action'] == 'deletion'){ + $transaction_type = 'Debit'; + //get cd amount for the particular file id to reverse entry to the cash deposite for only deletion + $cd_amount_total = $this->employeePolicyModel->getDeletionDataForTruncated($file['id']); + $totalSum = array_sum(array_column($cd_amount_total, 'total')); + $cd_amount = $totalSum; + + $this->myLogger->logme('error', 'Deletion CD Amount : {data}', ['data' => $cd_amount]); + } + + $this->myLogger->logme('error', 'Endorsemnt CD Amount : {data}', ['data' => $cd_amount]); + + + //STEP 1: + //update truncated status to the Emp_endorsement table $this->empEndorsementModel->where('file_id', $file_id) - ->set(['status' => 'truncated']) + ->set(['status' => 'truncated','is_active' => 0]) ->update(); - //update file status + + $this->myLogger->logme('error', 'emp_endorsement table updated'); + + //STEP 2: + if($file['action'] == 'deletion') { + //update the employee policy table reverse the data + $this->employeePolicyModel->updateEmployeePolicyTruncateReverse($file_id); + $this->myLogger->logme('error', 'employee_polices table updated for deletion'); + } + + if($file['action'] == 'correction'){ + + } + + // STEP 3: + //update files table status to "truncated" $this->fileModel->where('id', $file_id)->set(['status' => 'truncated'])->update(); + $this->myLogger->logme('error', 'files table updated'); + if($cd_tranction && $file['action'] != 'correction'){ - $transaction_type = 'Credit'; - if($file['action'] == 'deletion'){ - $transaction_type = 'Debit'; - } - $cd_data = [ - 'amount' => $cd_tranction['amount'], + 'amount' => $cd_amount, 'sub_type_id' => 8, 'endorsement_no' => null, 'insurer_id' =>$policy_data['insurer_id'], @@ -1317,13 +1500,291 @@ class EmployeeController extends AdminController 'client_id' => $client_id, 'client_policy_id' => $client_policy_id, 'cd_ac_no' => $policy_data['cd_ac_no'] ?? null, + 'cd_ac_pk' => $policy_data['cd_ac_pk'] ?? null, 'event_name' => $file['action'], ]; $response = DepositHelper::saveDeposit($cd_data, $loggedInUserID); + $this->myLogger->logme('error', 'cash_deposite table updated -- cd transaction'); + } + $this->myLogger->logme('error', 'SUCCESSFULLY TRUNCATED'); + return $this->respond(['dataStatus' => true, 'code' => 200, 'data' => 'success'], 200); + + } else { + if(get_role_id() == 1 || get_role_id() == 5){ + return $this->respond(['role' => get_role_id(), 'dataStatus' => false, 'code' => 404, 'message' => 'File data already processed. Do you want to truncate data from uploaded file?'], 200); + }else{ + return $this->respond(['dataStatus' => false, 'code' => 404, 'message' => 'File data already processed'], 200); + } + } + } + } + + //truncateFileData OLD FUNCTION + public function truncateFileDataOld($file_id, $role_id = null) + { + $file_id = $this->request->uri->getSegment(3); + // $file_id = 747; + $file = $this->fileModel->find($file_id); + $client_id = $file['client_id']; + $client_policy_id = $file['policy_id']; + $loggedInUserID = get_session_userid(); + + $policy_data = $this->clientPolicyModel->where('id', $client_policy_id)->first(); + + $cd_tranction = $this->cashDepositModel + ->where('client_id', $client_id) //client + ->where('insurer_id', $policy_data['insurer_id']) //insurer + ->where('event_name',$file['action']) //event + ->where('client_policy_id', $client_policy_id)//policy + ->orderBy('id', 'desc') + ->first(); + + + // $file['action'] = 'si_enhancement'; + // $result = []; + // dd($file); + if ($file['action'] == 'inception' || $file['action'] == 'dependent_addition' || $file['action'] == 'addition' || $file['action'] == 'enrollment' || $file['action'] == 'missed_inception') { + + + if($file['action'] == 'enrollment'){ + $result = $this->employeeModel->getEmpListByFileId(file_id: $file_id, emp_status: ['draft','enrolled'], policy_status: ['draft','enrolled']); + }else{ + $result = $this->employeeModel->getEmpListByFileId(file_id: $file_id, emp_status: ['active'], policy_status: ['active']); + } + + $result = []; + // ~dd($result); + if (count($result) && $role_id == null) { + if(get_role_id() == 1 || get_role_id() == 5){ + return $this->respond(['role' => get_role_id(), 'dataStatus' => false, 'code' => 404, 'message' => 'File data already processed. Do you want to truncate data from uploaded file?'], 200); + }else{ + return $this->respond(['role' => get_role_id(), 'dataStatus' => false, 'code' => 404, 'message' => 'File data already processed'], 200); + } + } else { + + $this->myLogger->logme('error', 'TRUNCATED STARTED WITH ADMIN OR HEAD PERMISSION'); + $this->myLogger->logme('error', 'Event Type : -- {data} --', ['data' => $file['action']]); + + + // GET THE CD AMOUND + //get cd amount for the particular file id to reverse entry to the cash deposite + $cd_amount = $cd_tranction['amount']; + if(in_array($file['action'], ['addition', 'dependent_addition'])){ + $cd_amount_total = $this->employeePolicyModel->getAdditionDataForTruncated($file_id, $file['action']); + // dd($cd_amount_total); + $cd_amount = $cd_amount_total['total']; + + $this->myLogger->logme('error', 'Addition or Dependent Addition CD Amount : {data}', ['data' => $cd_amount]); + } + + $this->myLogger->logme('error', 'CD Amount : {data}', ['data' => $cd_amount]); + + + if($file['action'] != 'enrollment') + { + //STEP: 1 - Update employee policy table + //update emp and emp plocies + $db = db_connect(); + $query = " + UPDATE employee_polices + JOIN employees ON employees.id = employee_polices.employee_id + SET employee_polices.status = 'truncated', employee_polices.is_active = 0 + WHERE employees.file_id = $file_id + "; + + $db->query($query); + $affectedRows = $db->affectedRows(); + $this->myLogger->logme('error', 'employee_polices table update query : {data}', ['data' => $query]); + $this->myLogger->logme('error', 'employee_polices table updated - Affected Rows : {data}', ['data' => $affectedRows]); + // print_r($db->getLastQuery()); die; + // $affectedRows = 10; + + //STEP:2 - Update emp_endorsement Table + //update truncated status and is_active 0 to the Emp_endorsement table + if(in_array($file['action'], ['addition', 'dependent_addition'])){ + $this->empEndorsementModel->where('file_id', $file_id) + ->set(['status' => 'truncated','is_active' => 0]) + ->update(); + + $this->myLogger->logme('error', 'emp_endorsement table updated'); + } + + //STEP:3 - Update files table + //update file status + $this->fileModel->where('id', $file_id)->set(['status' => 'truncated'])->update(); + $this->myLogger->logme('error', 'files table updated'); + } + else + { + // echo 'came here...1'; + //check all dependents added by self and other dependent policies + $emp_codes = $this->employeeModel->select('emp_code') + ->where('file_id', $file_id) + ->findAll(); + $emp_codes = array_column($emp_codes,'emp_code'); + // Kint::dump($emp_codes);//die; + + $dependent_policies = $this->clientPolicyModel->select('id') + ->where('base_policy', $client_policy_id) + ->findAll(); + // $dependent_policies = [ [10],[25],[35] ]; + // Kint::dump($dependent_policies); + // Kint::dump(array_column($dependent_policies,'id')); + if(count($dependent_policies)) + { + $dependent_policies = array_column($dependent_policies,'id'); + // Kint::dump($dependent_policies); + $second_level_dependent_policies = $this->clientPolicyModel->select('id') + ->whereIn('base_policy', $dependent_policies) + ->findAll(); + // dd($second_level_dependent_policies); + if(count($second_level_dependent_policies)) + { + $second_level_dependent_policies = array_column($second_level_dependent_policies,'id'); + } + + $dependent_policies = array_merge($dependent_policies,$second_level_dependent_policies); + } + $dependent_policies = array_merge($dependent_policies,[$client_policy_id]); + // Kint::dump($dependent_policies); + + //update emp and emp plocies + $db = db_connect(); + $emp_codes = '(' . implode(',', array_map(fn($code) => "'$code'", $emp_codes)) . ')'; + $dependent_policies = '(' . implode(',', $dependent_policies) . ')'; + $query = " + UPDATE employee_polices + JOIN employees ON employees.id = employee_polices.employee_id and employees.emp_code in $emp_codes + SET employee_polices.status = 'truncated', employee_polices.is_active = 0 + WHERE employee_polices.client_policy_id in $dependent_policies + "; + $db->query($query); + $affectedRows = $db->affectedRows(); + + // dd($affectedRows); + $affectedRows = $affectedRows * 2; + $this->fileModel->where('id', $file_id)->set(['status' => 'truncated'])->update(); + + } + + //FINAL STEP - Update reverse entry in cash_deposite table + if($cd_tranction){ + + $cd_data = [ + 'amount' => $cd_amount, + 'sub_type_id' => 8, + 'endorsement_no' => null, + 'insurer_id' =>$policy_data['insurer_id'], + 'description' => 'The policy Truncated by Admin or Head', + 'transaction_type' => 'Credit', + 'updated_by' => 1, + 'client_id' => $client_id, + 'client_policy_id' => $client_policy_id, + 'cd_ac_no' => $policy_data['cd_ac_no'] ?? null, + 'cd_ac_pk' => $policy_data['cd_ac_pk'] ?? null, + 'event_name' => $file['action'], + ]; + + $response = DepositHelper::saveDeposit($cd_data, $loggedInUserID); + $this->myLogger->logme('error', 'cash_deposite table updated -- cd transaction'); + + } + + $this->myLogger->logme('error', 'SUCCESSFULLY TRUNCATED'); + + return $this->respond(['dataStatus' => true, 'code' => 200, 'data' => round($affectedRows / 2)], 200); + } + + } else if ($file['action'] == 'si_enhancement' || $file['action'] == 'correction' || $file['action'] == 'deletion') { + + $res = $this->empEndorsementModel->select(['count(id) as count']) + ->where('emp_endorsement.file_id', $file_id) + ->groupStart() + ->where('emp_endorsement.endorsement_id is not null') + ->orwhereIn('emp_endorsement.status', ['complete']) + ->groupEnd() + ->get() + ->getResult(); + + // print_r($this->empEndorsementModel->getLastQuery()); + // echo $res[0]->count;die(); + + if ($res[0]->count == 0 || $role_id == 5 || $role_id == 1) { + + $this->myLogger->logme('error', 'TRUNCATED STARTED WITH ADMIN OR HEAD PERMISSION'); + $this->myLogger->logme('error', 'Event Type : -- {data} --', ['data' => $file['action']]); + + $transaction_type = 'Credit'; + $cd_amount = $cd_tranction['amount']; + + if($file['action'] == 'deletion'){ + $transaction_type = 'Debit'; + //get cd amount for the particular file id to reverse entry to the cash deposite for only deletion + $cd_amount_total = $this->employeePolicyModel->getDeletionDataForTruncated($file['id']); + $totalSum = array_sum(array_column($cd_amount_total, 'total')); + $cd_amount = $totalSum; + + $this->myLogger->logme('error', 'Deletion CD Amount : {data}', ['data' => $cd_amount]); + } + + $this->myLogger->logme('error', 'Endorsemnt CD Amount : {data}', ['data' => $cd_amount]); + + + //STEP 1: + //update truncated status to the Emp_endorsement table + $this->empEndorsementModel->where('file_id', $file_id) + ->set(['status' => 'truncated','is_active' => 0]) + ->update(); + + $this->myLogger->logme('error', 'emp_endorsement table updated'); + + //STEP 2: + if($file['action'] == 'deletion') { + //update the employee policy table reverse the data + $this->employeePolicyModel->updateEmployeePolicyTruncateReverse($file_id); + $this->myLogger->logme('error', 'employee_polices table updated for deletion'); + } + + if($file['action'] == 'correction'){ + + } + + // STEP 3: + //update files table status to "truncated" + $this->fileModel->where('id', $file_id)->set(['status' => 'truncated'])->update(); + $this->myLogger->logme('error', 'files table updated'); + + + if($cd_tranction && $file['action'] != 'correction'){ + + $cd_data = [ + 'amount' => $cd_amount, + 'sub_type_id' => 8, + 'endorsement_no' => null, + 'insurer_id' =>$policy_data['insurer_id'], + 'description' => 'The policy Truncated by Admin or Head', + 'transaction_type' => $transaction_type, + 'updated_by' => 1, + 'client_id' => $client_id, + 'client_policy_id' => $client_policy_id, + 'cd_ac_no' => $policy_data['cd_ac_no'] ?? null, + 'cd_ac_pk' => $policy_data['cd_ac_pk'] ?? null, + 'event_name' => $file['action'], + ]; + + $response = DepositHelper::saveDeposit($cd_data, $loggedInUserID); + $this->myLogger->logme('error', 'cash_deposite table updated -- cd transaction'); + + } + + $this->myLogger->logme('error', 'SUCCESSFULLY TRUNCATED'); + + return $this->respond(['dataStatus' => true, 'code' => 200, 'data' => 'success'], 200); + } else { if(get_role_id() == 1 || get_role_id() == 5){ return $this->respond(['role' => get_role_id(), 'dataStatus' => false, 'code' => 404, 'message' => 'File data already processed. Do you want to truncate data from uploaded file?'], 200); @@ -1403,6 +1864,13 @@ class EmployeeController extends AdminController ]; + $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); @@ -1627,14 +2095,18 @@ class EmployeeController extends AdminController $existing_units = $this->clientBranchModel->getExisitingUnits(client_id: $client_id,client_branch_id: $branch_id); //get familiy details in inception file format array from post method $data = calculate_premium_new(family_data: $family_details,policy_terms:$policy_details,slab_details:$slab_details,fileArr: $file,existing_units: $existing_units); - + // print_rr($data);die(); foreach($data as $key => $member ) { // ~dd($member); - if(is_array($member)) + if(is_array($member) && isset($member['policy_details']['date_coverage']) && isset($member['policy_details']['policy_end_date']) ) { $data[$key]['policy_details']['no_of_days'] = $member['policy_details']['date_coverage'] ? (calculate_days_bw_dates($member['policy_details']['date_coverage'],$member['policy_details']['policy_end_date'])->days + 1) : ''; } + else + { + $data[$key]['policy_details']['no_of_days'] = '0'; + } } return $this->respond(['dataStatus' => true, 'code' => 200, 'data' => ['new' => $data,'old' => $existing_famility_details], 200]); @@ -1747,22 +2219,29 @@ class EmployeeController extends AdminController public function update_emp_data() { $data = $this->request->getPost(); - - $data['dob'] = date('Y-m-d', strtotime($data['dob'])); - + // print_rr($data);die(); + // $data['dob'] = date('Y-m-d', strtotime($data['dob'])); + if(isset( $data['dob'])){ + $data['dob'] = change_date_format($data['dob'], 'd/m/Y', 'Y-m-d'); + } + // print_rr($data); die; + // Fetch current employee data $employee_data = $this->employeeModel->where('id', $data['employee_primary_id'])->first(); if ($employee_data['relationship'] == 'Self') { - if ($employee_data['gender'] != $data['gender']) { + if(isset($data['gender'])){ - $spouse_gender = ($data['gender'] == 'M') ? 'F' : 'M'; - $this->employeeModel - ->where('emp_code', $employee_data['emp_code']) - ->where('relationship', 'Spouse') - ->set(['gender' => $spouse_gender]) - ->update(); + if ($employee_data['gender'] != $data['gender']) { + + $spouse_gender = ($data['gender'] == 'M') ? 'F' : 'M'; + $this->employeeModel + ->where('emp_code', $employee_data['emp_code']) + ->where('relationship', 'Spouse') + ->set(['gender' => $spouse_gender]) + ->update(); + } } } @@ -1792,9 +2271,9 @@ class EmployeeController extends AdminController public function checkDeletionGetDataFunction() { // $batch_data = [ - // 'client_id' => 77, - // 'client_policy_id' => 203, - // 'client_branch_id' => 53, + // 'client_id' => 159, + // 'client_policy_id' => 336, + // 'client_branch_id' => 126, // ]; // $batch_data['insurer_or_tpa'] = 'insurer'; @@ -1958,5 +2437,274 @@ class EmployeeController extends AdminController return redirect()->back()->with('error', 'Log file not found.'); } + public function exportToExceltpadata() + { + // Create a new Spreadsheet + $spreadsheet = new Spreadsheet(); + $sheet = $spreadsheet->getActiveSheet(); + + // Header row + $headers = [ + 'TPA_NAME', 'SHORT_NAME', 'TPA_BRANCH_NAME', 'TPA_BRANCH_CODE', + 'TPA_CONTACT_PERSON_NAME', 'TPA_CONTACT_PERSON_EMAIL', 'TPA_CONTACT_PERSON_MOBILE', + 'TPA_CONTACT_PERSON_DESIGNATION', 'IS_DELETED' + ]; + $sheet->fromArray($headers, NULL, 'A1'); + + // Data rows + $data = [ + ["ICICI Lombard Health Care", "IL Health care", "Chennai", "997133", "Heena", "dharanisri@jubiliant.in", "9043955294", "General Manager", "YES"], + ["ICICI Lombard Health Care", "IL Health care", "Chennai", "997133", "Mahammad shireen", "mahammad.shireen@icicilombard.com", "8655420732", "Claims head", "NO"], + ["Medi Assist Insurance TPA Private Limited", "Medi Assist", "Chennai", "YA0000000348", "Ragavi", "dharanisri@jubiliant.in", "9043955294", "Senior Manager", "YES"], + ["Medi Assist Insurance TPA Private Limited", "Medi Assist", "Chennai", "YA0000000348", "Vijayalakshmi", "vijayalakshmi.c@mediassist.in", "7795542162", "Senior Executive | Account Management", "NO"], + ["Vidal Health Insurance TPA", "Vidal", "Chennai", "YA0000000349", "vijalakshmi", "vijayalakshmi.c@mediassist.in", "7795542162", "Senior Executive", "NO"], + ["Vidal Health Insurance TPA", "Vidal", "Chennai", "YA0000000349", "M.Pushparaj", "pushparaj.moorthy@vidalhealth.com", "8939634456", "Executive", "NO"], + ["Digit in-House", "Digit in-House", "Go Digit General Insurance Ltd", "1", "sathish", "sathish.n@vidalhealth.com", "7823913800", "Senior Executive", "NO"], + ["Digit in-House", "Digit in-House", "Go Digit General Insurance Ltd", "1", "Mr. Pavan", "TK.Pavankumar@godigit.com", "8754490492", "Strategic Partnerships", "NO"], + ["Aditya Birla Health Insurance Co. Limited", "ABHI", "Chennai", "O1", "sathish", "sathish.n@vidalhealth.com", "7823913800", "Senior Executive", "NO"], + ["Aditya Birla Health Insurance Co. Limited", "ABHI", "Chennai", "O1", "Jhonson Kj", "jhonson.kj@adityabirlacapital.com", "9900729513", "Executive", "NO"], + ["Aditya Birla Health Insurance Co. Limited", "ABHI", "Chennai", "01", "Jhonson Kj", "jhonson.kj@adityabirlacapital.com", "9900729513", "Executive", "NO"], + ["R Care Health", "R Care", "Chennai", "01", "Jeevanadam", "Jeevanandam.Kumaran@relianceada.com", "8825982053", "Executive", "NO"], + ["IFFCO-TOKIO GENERAL INSURANCE CO. LTD", "ITGI", "Chennai", "01", "Anjali", "Anjali.K@ext.iffcotokio.co.in", "6374270165", "Senior Executive", "NO"], + ["Star Health and Allied Insurance", "STAR", "Chennai", "110000", "Mr. Vijay Baskar", "vijayabhaskar.m@starhealth.in", "9840905286", "Area Manager", "NO"], + ]; + $sheet->fromArray($data, NULL, 'A2'); + + // Save the file + $filename = 'TPA_Data.xlsx'; + $writer = new Xlsx($spreadsheet); + + // Set headers for download + header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); + header('Content-Disposition: attachment; filename="' . $filename . '"'); + header('Cache-Control: max-age=0'); + + $writer->save('php://output'); + exit; + } + + //------------------------------------------------------------------------------------------------------ + + + public function test_members_list(){ + // $model = new EmployeeModel(); + // $list = [ + // ['relationship' => 'spouse','emp_code' => 'TEST002', 'name' => 'Lakshmi','email_personal' => 'lakshmi@gmail.com','mobile'=>'6382156701','gender'=>'female','dob'=>'1996-05-19','doj'=>'2022-02-01','basic_pay'=>'100000','emp_status'=>'enrolled'], + // ['relationship' => 'Daughter','emp_code' => 'TEST002', 'name' => 'Jayalakshmi','email_personal' => 'jayalakshmi@gmail.com','mobile'=>'6382156701','gender'=>'female','dob'=>'2018-05-19','doj'=>'2022-02-01','basic_pay'=>'100000','emp_status'=>'enrolled'], + // ['relationship' => 'Son','emp_code' => 'TEST002', 'name' => 'Jayam Ravi','email_personal' => 'jayamravi@gmail.com','mobile'=>'6382156701','gender'=>'male','dob'=>'1994-05-19','doj'=>'2019-02-01','basic_pay'=>'100000','emp_status'=>'enrolled'], + // // ['relationship' => 'self','emp_code' => 'TEST003', 'name' => 'Ravi Shankar','email_personal' => 'srinivassaravanan2002@gmail.com','email_corporate'=>'srinivas.saravanan@venbainfotech.com','mobile'=>'6382156701','gender'=>'male','dob'=>'1994-05-19','doj'=>'2022-02-01','basic_pay'=>'100000','emp_status'=>'enrolled'] + // ['relationship' => 'spouse','emp_code' => 'TEST001', 'name' => 'Lakshmi','email_personal' => 'lakshmi@gmail.com','mobile'=>'6382156701','gender'=>'female','dob'=>'1996-05-19','doj'=>'2022-02-01','basic_pay'=>'100000','emp_status'=>'enrolled'], + + // ]; + // foreach($list as $listitem){ + + + // $model->insert($listitem); + // } + // die(); + $employee_data = $this->employeeModel->getTestEmployeeData(); + $data['employees'] = $employee_data; + $data['clients'] = $this->clientModel->findAll(); + // dd($data); + return $this->loadLayout('test_members_list',$data); + } + + public function mapEmployees(){ + $client_id = $this->request->getPost('client_id'); + $branch_id = $this->request->getPost('branch_id'); + $policy_id = $this->request->getPost('client_policy_id'); + $selected_employees = (array)$this->request->getPost('selected'); + $si_amt = $this->request->getPost('si_amt'); + $policy_start_date_unformatted = $this->request->getPost('policy_start_date'); + + $policy_start_date = change_date_format($policy_start_date_unformatted, 'd/M/Y', 'Y-m-d'); + + $data1 = [ + 'client_id' => $client_id, + 'client_branch_id' => $branch_id, + ]; + $data2 = [ + 'client_policy_id' => $policy_id, + 'status' => 'draft', + 'date_coverage' => $policy_start_date, + 'basic_cover_si' => $si_amt, + + ]; + + for($i = 0; $i < count($selected_employees); $i++){ + $data2['employee_id'] = $selected_employees[$i]; + $result1 = $this->employeeModel->set($data1)->where('id',$selected_employees[$i])->update(); + $result2 = $this->employeePolicyModel->insert($data2); + } + if ($result1 && $result2) { + return $this->respond(['status' => true, 'code' => 200, 'message' => 'Employees mapped successfully'], 200); + } else { + return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to map employees.'], 404); + } + } + + public function getDataForMapping(){ + $policy_id = $this->request->getPost('policy_id');log_message('error',$policy_id); + $data['policy_start_date'] = $this->clientPolicyModel->select('policy_start_date')->where('id',$policy_id)->first()['policy_start_date']; + $data['si_amt'] = $this->PolicyPremium2Model->select('si')->where('client_policy_id', $policy_id)->groupBy('si')->findAll(); + log_message('error',json_encode($data).'policy id '.$policy_id); + return $this->respond(['status' => true, 'code' => 200, 'data' => $data], 200); + } + + public function unmapEmployees($actionType){ + $selected_employees = (array)$this->request->getPost('selected'); + if($actionType == 0){ + for($i = 0;$iemployeeModel->set(['client_id' => null, 'client_branch_id' => null])->where('id',$selected_employees[$i])->update();log_message('error',$result1); + $result2 = $this->employeePolicyModel->where('employee_id',$selected_employees[$i])->delete();log_message('error',$result2); + } + } + else if ($actionType == 1){ + for($i = 0;$iemployeeModel->set(['client_id' => null, 'client_branch_id' => null])->where('id',$selected_employees[$i])->update();log_message('error','result 1 is '.$result1); + $result2 = $this->employeePolicyModel->where('employee_id',$selected_employees[$i])->delete();log_message('error', 'result 2 is '.$result2); + $emp_code = $this->employeeModel->select('emp_code')->where('id',$selected_employees[$i])->first()['emp_code'];log_message('error','emp_code is '.$emp_code); + $result3 = $this->employeeModel->where('emp_code',$emp_code)->whereNotIn('relationship',['self'])->delete();log_message('error','result 3 is '.$result3); + } + } + else{ + return $this->respond(['status' => false, 'code' => 404, 'message' => 'Invalid action type.'], 404); + } + if($actionType == 1){ + if($result1 && $result2 && $result3){ + return $this->respond(['status' => true, 'code' => 200, 'message' => 'Employees unmapped successfully and Dependencies are Deleted'], 200); + } + else{ + return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to unmap employees.'], 404); + } + }else{ + if($result1 && $result2 ){ + return $this->respond(['status' => true, 'code' => 200, 'message' => 'Employees unmapped successfully'], 200); + } + else{ + return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to unmap employees.'], 404); + } + } + + } + + public function cloneWorksheet() + { + // Define file paths + $inputFilePath = 'C:\Users\Venba\Downloads/merge1.xlsx'; // Path to the existing file + $outputFilePath = WRITEPATH . '/tmp/cloned_file.xlsx'; // Path to save the new file + + try { + // Load the existing spreadsheet + $spreadsheet = IOFactory::load($inputFilePath); + + // Get the first worksheet (or specify the index of the sheet to clone) + $originalWorksheet = $spreadsheet->getSheet(0); + + // Clone the worksheet + $clonedWorksheet = clone $originalWorksheet; + + // Generate a unique name for the cloned worksheet + $baseName = "Cloned Sheet"; + $sheetIndex = 1; + $uniqueName = $baseName; + + // Check for duplicate names and generate a unique one + while ($spreadsheet->sheetNameExists($uniqueName)) { + $uniqueName = $baseName . " " . $sheetIndex; + $sheetIndex++; + } + + // Set the unique name for the cloned worksheet + $clonedWorksheet->setTitle($uniqueName); + + // Add the cloned worksheet to the spreadsheet + $spreadsheet->addSheet($clonedWorksheet); + + // Modify the cloned sheet (optional) + $clonedWorksheet->setCellValue('A1', 'Hello, Cloned Sheet!'); + + // Save the modified spreadsheet to a new file + $writer = new Xlsx($spreadsheet); + $writer->save($outputFilePath); + + return $this->response->setJSON([ + 'status' => 'success', + 'message' => 'Spreadsheet with cloned sheet created successfully!', + 'file_path' => $outputFilePath, + ]); + } catch (\Exception $e) { + // Handle exceptions + return $this->response->setJSON([ + 'status' => 'error', + 'message' => $e->getMessage(), + ]); + } + } + + //------------------------------------------------------------------------------------------------------ + + + public function generateAcmAndMForEcard($client_id) + { + $db = db_connect(); + $builder = $db->table('client_rm'); + $builder->select('user_profiles.first_name, user_profiles.mobile, user_profiles.email, client_rm.level'); + $builder->join('user_profiles', 'client_rm.user_id = user_profiles.id'); + $builder->where('client_rm.client_id', $client_id); + $builder->whereIn('client_rm.level', [2, 3]); + $builder->where('client_rm.is_active', 1); + $builder->orderBy('client_rm.level', 'desc'); + $query = $builder->get(); + $result = $query->getResultArray(); + + $levels = [ + 3 => [], + 2 => [] + ]; + + foreach ($result as $value) { + $levels[$value['level']][] = $value; + } + + // Generate the HTML content + $html = ''; + + foreach ($levels as $level => $contacts) { + $displayLevel = $level == 3 ? 1 : 2; // Switch levels for display + $html .= '
Level ' . $displayLevel . '
'; + foreach ($contacts as $index => $contact) { + $html .= ($index + 1) . '. ' . $contact['first_name'] . ' / ' . $contact['mobile'] . ' / ' . $contact['email'] . '
'; + } + } + + $html .= '


'; + + return $html; + } + + public function getBatchFileData() + { + $file_id = $this->request->getGet('file_id'); + + if(!empty($file_id)){ + + + $batch_file_data = $this->batchFileModel + ->where('id', $file_id) + ->where('is_active', 1) + ->first(); + + if(!empty($batch_file_data)){ + return $this->respond(['status' => true, 'code' => 200, 'batch_file_data' => $batch_file_data], 200); + }else{ + return $this->respond(['status' => false, 'code' => 200, 'message' => 'No data found.'], 200); + } + + }else{ + return $this->respond(['status' => false, 'code' => 404, 'message' => 'No data to found. File ID Not found'], 200); + } + } } diff --git a/app/Controllers/EmployeeRestController.php b/app/Controllers/EmployeeRestController.php index 0684f727..ec4f7478 100755 --- a/app/Controllers/EmployeeRestController.php +++ b/app/Controllers/EmployeeRestController.php @@ -28,6 +28,7 @@ use App\Models\UserModel; use App\Models\FEContentModel; use App\Models\AddImgModel; use App\Models\ClientBranchModel; +use App\Models\AuditHistoryModel; use App\Controllers\Jobs ; @@ -71,6 +72,7 @@ class EmployeeRestController extends AdminController protected $feContentModel; protected $addImgModel; protected $clientBranchModel; + protected $auditHistoryModel; public function __construct() @@ -94,6 +96,7 @@ class EmployeeRestController extends AdminController $this->feContentModel = new FEContentModel(); $this->addImgModel = new AddImgModel(); $this->clientBranchModel = new ClientBranchModel(); + $this->auditHistoryModel = new AuditHistoryModel(); } @@ -221,7 +224,9 @@ class EmployeeRestController extends AdminController try { $data = $this->request->getJSON(); - + $openForEnrollment = $this->findThePolicyIsOpenForEnrollment($data[0]->client_policy_id); + if($openForEnrollment == false){ return $this->respond(['status' => 'failed','code' => 404,'data' => 'Enrollment closed'], 404); } + if ($data) { $Count = 0; @@ -245,13 +250,11 @@ class EmployeeRestController extends AdminController $item->dob = $this->convertDateFormatYMD($item->dob); $item->emp_status = 'draft'; - $employee = $this->employeeModel->insert($item); if ($employee) { $Count++; } - } } @@ -260,21 +263,15 @@ class EmployeeRestController extends AdminController if(isset($data[0]->id)) { - - $this->createEmployeePolicyData($data[0]->id , $data[0]->emp_code , $data[0]->client_id , $data[0]->client_policy_id , $data[0]->basic_cover_si); - - }else{ - - $this->createEmployeePolicyData($employee , $data[0]->emp_code , $data[0]->client_id , $data[0]->client_policy_id , $data[0]->basic_cover_si); - + $this->createEmployeePolicyData($data[0]->id , $data[0]->emp_code , $data[0]->client_id , $data[0]->client_policy_id , $data[0]->basic_cover_si); + }else + { + $payable_employee = $this->getEmployeePayableValue($data[0]->client_policy_id,$data[0]->relationship); + $this->createEmployeePolicyData($employee , $data[0]->emp_code , $data[0]->client_id , $data[0]->client_policy_id , $data[0]->basic_cover_si , $payable_employee); } - - - $this->updatePremiumAmount($data[0]->client_policy_id , $data[0]->emp_code , $data[0]->client_branch_id); - $result = []; return $this->respond(['status' => 'success','code' => 200,'data' => $result], 200); } else { @@ -288,7 +285,37 @@ class EmployeeRestController extends AdminController } - public function createEmployeePolicyData($employee_id,$emp_code,$client_id,$client_policy_id,$basic_cover_si = null) + public function getEmployeePayableValue($client_policy_id,$relationship) + { + $terms = $this->clientPolicyModel->where('id',$client_policy_id)->get()->getRow()->policy_terms; + + if(isset(json_decode($terms)->is_payable_employee)) + { + $is_payable_obj = json_decode($terms)->is_payable_employee; + + if ($relationship === 'Mother' || $relationship === 'Father' || $relationship === 'Father in Law' || $relationship === 'Mother in Law') + { + return $is_payable_obj->elders; + } + else if($relationship === 'Son' || $relationship === 'Daughter') + { + return $is_payable_obj->childern; + } + else if($relationship === 'Spouse') + { + return $is_payable_obj->spouse; + } + + }else{ + return 0; + } + + + + + } + + public function createEmployeePolicyData($employee_id,$emp_code,$client_id,$client_policy_id,$basic_cover_si = null,$payable_employee = 0) { if($basic_cover_si == null) @@ -314,6 +341,7 @@ class EmployeeRestController extends AdminController $data['employee_id']= $employee_id; $data['client_policy_id']= $client_policy_id; $data['basic_cover_si']= $basic_cover_si; + $data['payable_employee']= $payable_employee; $data['status']= 'draft'; $data['date_coverage'] = $this->getEmployeeCoverageDate($emp_code, $client_policy_id); @@ -346,7 +374,7 @@ class EmployeeRestController extends AdminController ->where('client_policy_id',$value['policy_details']['client_policy_id'] ) ->where('employee_id' , $value['temp']['emp_id'] ) ->where('is_active', 1 ) - ->set(array('premium'=> $value['policy_details']['premium'] , 'rata_premimum'=> $value['policy_details']['rata_premimum'] , 'gst'=> $value['policy_details']['gst'] )) + ->set(array('basic_cover_si' => $value['policy_details']['basic_cover_si'],'premium'=> $value['policy_details']['premium'] , 'rata_premimum'=> $value['policy_details']['rata_premimum'] , 'gst'=> $value['policy_details']['gst'] )) ->update(); } @@ -481,6 +509,10 @@ class EmployeeRestController extends AdminController try { $requestData = $this->request->getJSON(); + + $openForEnrollment = $this->findThePolicyIsOpenForEnrollment($requestData[0]->client_policy_id); + if($openForEnrollment == false){ return $this->respond(['status' => 'failed','code' => 404,'data' => 'Enrollment closed'], 404); } + foreach ($requestData as $key => $value) { @@ -687,14 +719,17 @@ class EmployeeRestController extends AdminController $notification = $this->notificationModel->where('client_id',$client_id)->where('template_name','member_welcome_mail')->first(); - $jwt = $this->request->getHeader('Authorization'); + $jwt = $this->request->getHeaderLine('Authorization'); $jwtParts = explode(' ', $jwt); $token = $jwtParts[2]; $decodedPayload = json_decode(base64_decode(explode('.', $token)[1]), true); + // get the employee id from token $employee_id = $decodedPayload['id']; + + $client_policy = $this->clientPolicyModel->where('id', $policy_id)->where('client_id', $client_id)->where('client_branch_id', $client_branch_id)->first(); if ($client_policy) { $policy = $this->policesModel->where('id', $client_policy['policy_id'])->first(); @@ -710,6 +745,7 @@ class EmployeeRestController extends AdminController //make an entry in DB $file_id = $this->fileModel->insert(['file_name' => $filename, 'client_id' => $client_id, 'policy_id' => $policy_id, 'created_by' => $employee_id, 'status' => 'inprogress', 'action' => 'enrollment', 'client_branch_id' => $client_branch_id]); //here field policy_id have client_policy_id and not policy id from policy master + $this->myLogger->logme("error", '{file_id} - client uploaded success', ['file_id' => $file_id]); $empServiceController = new EmployeeServiceController(); @@ -841,7 +877,7 @@ class EmployeeRestController extends AdminController 'basic_pay'=> $extra['11'][$index], 'unit'=> isset($extra['12'][$index]) ? $extra['12'][$index] : null, 'client_branch_id' => $client_branch_id, - 'date_coverage' => $extra['13'][$index] + 'date_coverage' => $extra['13'][$index] != "" && $extra['13'][$index] != null ? change_date_format($extra['13'][$index],'d-M-Y','Y-m-d') : null ]; $basic_cover_si_value = null; @@ -875,7 +911,10 @@ class EmployeeRestController extends AdminController $basic_cover_si[]= $basic_cover_si_value; } } + $count = 0; + $wholeData=[];// Initialize an empty array to store employee email. + for ($a=0; $a employeePolicyModel->checkExistingEmpPolicy(['employee_id' => $emp_id,'client_policy_id' => $policy_id]); + $emp_policy_data =[ 'employee_id'=>$emp_id, 'client_policy_id'=>$policy_id, 'status'=> 'draft', 'date_coverage' => $date_coverage, - 'basic_cover_si'=>isset($basic_cover_si[$a]) ? $basic_cover_si[$a] : null + 'payable_employee' => check_pay_by_employee_or_company($client_policy['policy_terms'], $dataToInsert[$a]['relationship']), + 'basic_cover_si'=>isset($basic_cover_si[$a]) ? $basic_cover_si[$a] : null, + 'file_id' => isset($employee_policy['file_id']) && $employee_policy['file_id'] != '' ? $employee_policy['file_id'] : $file_id, ]; - $employee_policy = $this->employeePolicyModel->checkExistingEmpPolicy(['employee_id' => $emp_id,'client_policy_id' => $policy_id]); + // print_r($employee_policy); die; if ($employee_policy) { foreach ($employee_policy as $existing_policy) { $emp_policy_data['id']= $existing_policy['id']; $emp_policy_data['updated_at'] = $formatted_date_time; $this->employeePolicyModel->save($emp_policy_data); } + $emp_policy_id = $employee_policy[0]['id']; } else { - $emp_policy = $this->employeePolicyModel->insert($emp_policy_data); + $emp_policy_id = $this->employeePolicyModel->insert($emp_policy_data); } if (isset($notification) && $notification['enabled'] == 1 && !empty($notification['mail_content'])) { //trigger - $wholeData=[]; + // $wholeData=[]; if ($dataToInsert[$a]['relationship'] == 'Self' && isset($dataToInsert[$a]['email_corporate']) && !empty($dataToInsert[$a]['email_corporate'])) { $params['dataToInsert'] = $dataToInsert[$a]; $params['notification'] = $notification; $params['client_data'] = $client_data; + $params['common'] = [ + 'client_id' => $client_id, + 'client_branch_id' => $client_branch_id, + 'client_policy_id' => $policy_id, + 'employee_policy_id' => $emp_policy_id ?? null, + 'employee_id' => $emp_id, + 'mail_type' => 'member_welcome_mail', + ]; $wholeData[] = sendMailNotification::sendMailNotification('member_welcome_mail', $params); $count++; } - if($count == 20 || $a == count($dataToInsert)-1){ - if (count($wholeData) > 0) { - $job_details = new Jobs(); - $r = Jobs::addJob(['job_name' => 'bulk_mail','payload' => $wholeData]); - $wholeData = []; - $count = 0; - } - } + + // if($count == 20 || $a == count($dataToInsert)-1){ + // if (count($wholeData) > 0) { + // $job_details = new Jobs(); + // $r = Jobs::addJob(['job_name' => 'bulk_mail','payload' => $wholeData]); + // $wholeData = []; + // $count = 0; + // } + // } // if ($dataToInsert[$a]['email_corporate'] != null || $dataToInsert[$a]['email_corporate'] != '' && $dataToInsert[$a]['relationship'] == 'Self') { } } + + // print_r($wholeData); die; + + // for bulk mail queue job push + if (!empty($wholeData) && count($wholeData) > 0) { + + $wholeData = array_chunk($wholeData, 20); + + foreach ($wholeData 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' => '','error_data' => ''])->update(); return $this->respond(['status' => 'success', 'code' => 200, 'message' => "Success" ], 200); }else{ @@ -1011,7 +1078,8 @@ class EmployeeRestController extends AdminController $id = $this->request->getGet('id'); $emp_code = $this->request->getGet('emp_code'); $client_id = $this->request->getGet('client_id'); - $client_branch_id = $this->request->getGet('client_branch_id'); + $client_branch_id = $this->request->getGet('client_branch_id'); + $login_by_hr = $this->request->getGet('login_by_hr'); // This is an array containing keys to be removed from the terms and conditions array $keysToRemove = ["removable_keys"]; @@ -1045,16 +1113,21 @@ class EmployeeRestController extends AdminController $array->GridMaster = $getSlabAndGridData['grid_master']; if($array->tpa_id != null){ - $array->eCardDownload = base_url('download-e-card/') . $array->rand_string; + $array->eCardDownload = base_url('download-e-card/') . $array->rand_string.'/1'; }else{ $array->eCardDownload = null; } // Construct value for policy type GPA - if($getSlabAndGridData['grid_master']['policy_type'] == "GPA" && $this->request->getGet('policy') == 'GPA'){ + // $getSlabAndGridData['grid_master']['policy_type'] == "GPA" + if($array->policy_type_id == 1 && $this->request->getGet('policy') == 'GPA') + { - // Filter employee data where the family_floater_key is 'self' + $si_value = 0; + + // Filter employee data where the family_floater_key is 'self' $selfData = array_filter($empData, fn($arr) => trim(strtolower($arr['family_floater_key'])) === 'self'); $employee_policy = $this->employeePolicyModel->where('employee_id',$selfData[0]['id'])->where('client_policy_id',$array->ClientPolicyId)->where('is_active', 1 )->get()->getRow(); + $si_value = isset($employee_policy->basic_cover_si) ? $employee_policy->basic_cover_si : 0; $self['is_value_exist'] = true; $self['data']['family_floater_key'] = 'self'; @@ -1068,14 +1141,15 @@ class EmployeeRestController extends AdminController $array->mapped_family_floaters = $self; $array->type = 'GPA'; + $array->si_value = $si_value; $res = []; array_push($res,$array); - $EDLIPolicy = $this->getAdditionalGPAPolicy($employeeData,6,$emp_code,$client_id,$client_branch_id); + $EDLIPolicy = $this->getAdditionalGPAPolicy($employeeData,6,$emp_code,$client_id,$client_branch_id,$login_by_hr); if($EDLIPolicy){ array_push($res,$EDLIPolicy); } - $GTLIPolicy = $this->getAdditionalGPAPolicy($employeeData,7,$emp_code,$client_id,$client_branch_id); + $GTLIPolicy = $this->getAdditionalGPAPolicy($employeeData,7,$emp_code,$client_id,$client_branch_id,$login_by_hr); if($GTLIPolicy){ array_push($res,$GTLIPolicy); } return $this->respond(['status' => 'success','code' => 200,'data' => $res ], 200); @@ -1087,7 +1161,9 @@ class EmployeeRestController extends AdminController } // Construct value for policy type GMC - }else if($getSlabAndGridData['grid_master']['policy_type'] == "GMC" && $this->request->getGet('policy') == 'GMC' ){ + // $getSlabAndGridData['grid_master']['policy_type'] == "GMC" + }else if($array->policy_type_id == 2 && $this->request->getGet('policy') == 'GMC' ) + { @@ -1097,7 +1173,7 @@ class EmployeeRestController extends AdminController // Generate Notes string based on familyFloates terms $array->notes = $this->FloterNotesConvertion($familyFloates); - if($getSlabAndGridData['slab_rates'][0]['premium_type'] == 1) + if($getSlabAndGridData['slab_rates'][0]['premium_type'] == 1 || $getSlabAndGridData['slab_rates'][0]['premium_type'] == 3) { $array->floter_text_heading = 'Floater Sum Insured'; $array->floter_text_description = 'This is a floater sum insured. A floater is a type of sum insured that provides coverage to more than one member ot a family at the same time. Simply put, its a single insurance cover for the entire family.'; @@ -1114,6 +1190,9 @@ class EmployeeRestController extends AdminController $floters = $this->FloterConvertion($familyFloates); $data = []; + $dependent_and_si_value = 0; + $dependent_and_si_premium_value = 0; + $dependent_and_si_gst_value = 0; foreach ($floters as $familyFloatesValue) { $dependent = preg_replace('/\d/', '', $familyFloatesValue); @@ -1121,6 +1200,9 @@ class EmployeeRestController extends AdminController foreach ($empData as $key => $value) { if ($value['family_floater_key'] === $dependent) { $employee_policy = $this->employeePolicyModel->where('employee_id',$value['id'])->where('client_policy_id',$array->ClientPolicyId)->where('is_active', 1 )->get()->getRow(); + if(isset($employee_policy->basic_cover_si)){ $dependent_and_si_value = ($dependent_and_si_value == 0) ? $employee_policy->basic_cover_si : $dependent_and_si_value; } + if(isset($employee_policy->rata_premimum)){ $dependent_and_si_premium_value = $dependent_and_si_premium_value + $employee_policy->rata_premimum;} + if(isset($employee_policy->gst)){ $dependent_and_si_gst_value = $dependent_and_si_gst_value + $employee_policy->gst;} $temp['is_value_exist'] = true; $temp['data']['family_floater_key'] = $familyFloatesValue; @@ -1176,7 +1258,6 @@ class EmployeeRestController extends AdminController } - // Add family floter buttons placement data for FE validation if(count($floters)){ foreach ($floters as $familyFloatesValue) { @@ -1197,6 +1278,9 @@ class EmployeeRestController extends AdminController $array->mapped_family_floaters = $data; $array->type = "GMC"; + $array->family_floaters_of_dependent_and_si_value = $dependent_and_si_value > 0 ? $dependent_and_si_value : 0; + $array->family_floaters_of_dependent_and_si_premium_value = $dependent_and_si_premium_value > 0 ? round($dependent_and_si_premium_value) : 0; + $array->family_floaters_of_dependent_and_gst_value = $dependent_and_si_gst_value > 0 ? round($dependent_and_si_gst_value) : 0; $checkGmcParentsPolicyExist = $this->clientPolicyModel->select('client_policy.id as ClientPolicyId , client_policy.client_id as ClientId, client_policy.policy_type_id as policy_type_id, policy_type.long_name as Policy_Name , client_policy.is_addon as is_addon , client_policy.open_for_enrollment as OpenForEnrollment , client_policy.inception_type as inception_type , client_policy.policy_terms as Policy_Terms') ->join('policy_type', 'client_policy.policy_type_id = policy_type.id', 'left') @@ -1272,7 +1356,7 @@ class EmployeeRestController extends AdminController { if($tpaArray[0]->tpa_id != null) - $array->eCardDownload = base_url('download-e-card/') . $tpaArray[0]->rand_string; + $array->eCardDownload = base_url('download-e-card/') . $tpaArray[0]->rand_string.'/1'; else $array->eCardDownload = null; @@ -1289,7 +1373,7 @@ class EmployeeRestController extends AdminController // Generate Notes string based on familyFloates terms $array->notes = $this->FloterNotesConvertion($familyFloates); - if($getSlabAndGridData['slab_rates'][0]['premium_type'] == 1) + if($getSlabAndGridData['slab_rates'][0]['premium_type'] == 1 || $getSlabAndGridData['slab_rates'][0]['premium_type'] == 3) { $array->floter_text_heading = 'Floater Sum Insured'; $array->floter_text_description = 'This is a floater sum insured. A floater is a type of sum insured that provides coverage to more than one member ot a family at the same time. Simply put, its a single insurance cover for the entire family.'; @@ -1309,15 +1393,20 @@ class EmployeeRestController extends AdminController $floters = $this->FloterConvertion($familyFloates); $data = []; + $dependent_and_si_value = 0; + $dependent_and_si_premium_value = 0; + $dependent_and_si_gst_value = 0; foreach ($floters as $familyFloatesValue) { $dependent = preg_replace('/\d/', '', $familyFloatesValue); - if(count($empData)){ foreach ($empData as $key => $value) { if ($value['family_floater_key'] === $dependent) { $employee_policy = $this->employeePolicyModel->where('employee_id',$value['id'])->where('client_policy_id',$array->ClientPolicyId)->where('is_active', 1 )->get()->getRow(); - // dd( $employee_policy); + if(isset($employee_policy->basic_cover_si)){ $dependent_and_si_value = ($dependent_and_si_value == 0) ? $employee_policy->basic_cover_si : $dependent_and_si_value; } + if(isset($employee_policy->rata_premimum)){ $dependent_and_si_premium_value = $dependent_and_si_premium_value + $employee_policy->rata_premimum;} + if(isset($employee_policy->gst)){ $dependent_and_si_gst_value = $dependent_and_si_gst_value + $employee_policy->gst;} + $temp['is_value_exist'] = true; $temp['data']['family_floater_key'] = $familyFloatesValue; $temp['data']['employee_id'] = $value['id']; @@ -1386,6 +1475,9 @@ class EmployeeRestController extends AdminController $array->mapped_family_floaters = $data; $array->type = "GMC - Parents"; + $array->family_floaters_of_dependent_and_si_value = $dependent_and_si_value > 0 ? $dependent_and_si_value : 0; + $array->family_floaters_of_dependent_and_si_premium_value = $dependent_and_si_premium_value > 0 ? round($dependent_and_si_premium_value) : 0; + $array->family_floaters_of_dependent_and_gst_value = $dependent_and_si_gst_value > 0 ? round($dependent_and_si_gst_value) : 0; return $array; @@ -1394,7 +1486,7 @@ class EmployeeRestController extends AdminController } - public function getAdditionalGPAPolicy($empData,$policy_type,$emp_code,$client_id,$client_branch_id) + public function getAdditionalGPAPolicy($empData,$policy_type,$emp_code,$client_id,$client_branch_id,$login_by_hr) { $checkPolicyExist = $this->clientPolicyModel->select('client_policy.id as ClientPolicyId , client_policy.client_id as ClientId, client_policy.policy_type_id as policy_type_id, client_policy.is_addon as is_addon , client_policy.open_for_enrollment as OpenForEnrollment , client_policy.inception_type as inception_type , client_policy.policy_terms as Policy_Terms , client_policy.enrolment_visibility') ->where('client_policy.policy_type_id', $policy_type ) @@ -1411,18 +1503,23 @@ class EmployeeRestController extends AdminController $decodedArray = json_decode($array->Policy_Terms); $array->Policy_Terms = $decodedArray; - + $si_value = 0; // Filter employee data where the family_floater_key is 'self' $selfData = array_filter($empData, fn($arr) => trim(strtolower($arr['family_floater_key'])) === 'self'); $employee_policy = $this->employeePolicyModel->where('employee_id',$selfData[0]['id'])->where('client_policy_id',$array->ClientPolicyId)->where('is_active', 1 )->get()->getRow(); + $si_value = isset($employee_policy->basic_cover_si) ? $employee_policy->basic_cover_si : 0; $policyTypeData = $this->policyTypeModel->where('id',$policy_type)->get()->getRow(); + $array->type = $policyTypeData->policy_type; $array->Policy_Name = $policyTypeData->long_name; + $array->si_value = $si_value; + + if($employee_policy){ if($employee_policy->tpa_id != null){ - $array->eCardDownload = base_url('download-e-card/') . $employee_policy->rand_string; + $array->eCardDownload = base_url('download-e-card/') . $employee_policy->rand_string.'/1'; }else{ $array->eCardDownload = null; } $self['is_value_exist'] = true; @@ -1436,10 +1533,20 @@ class EmployeeRestController extends AdminController $self['data']['basic_cover_si'] = isset($employee_policy->basic_cover_si) ? $employee_policy->basic_cover_si : 0; $array->mapped_family_floaters = $self; - if($array->enrolment_visibility == 1) + + if (isset($login_by_hr) && $login_by_hr == true) + { return $array; - else - return false; + }else{ + + if($array->enrolment_visibility == 1) + return $array; + else + return false; + + } + + }else{ return false; @@ -1461,6 +1568,9 @@ class EmployeeRestController extends AdminController foreach ($array as $key => $value) { if ($value > 0 && $key != 'elders_count') { if ($value != 0 && $key === 'childrens') { + + if($value > 2){ $value = 2; } + for ($i = 1; $i <= $value; $i++) { $result[] = "child" . $i; } @@ -1500,7 +1610,7 @@ class EmployeeRestController extends AdminController $string = ucwords($string); $result .= ' + '.$string; }else if($value != 0 && $key ==='self') { - $result = 'Allowed memebrs Self '; + $result = 'Allowed members Self '; }else if($value != 0 && $key ==='childrens') { if($value > 1){ $result .= ' + '.$value.' Children'; }else{ $result .= ' + '.$value.' Child'; } }else if($value != 0 && $key ==='elders_count') { @@ -1519,7 +1629,7 @@ class EmployeeRestController extends AdminController if($first_two_chars == " +"){ $modified_string = substr($result, 3); - return "Allowed memebrs ".$modified_string; + return "Allowed members ".$modified_string; }else{ return $result; } @@ -1617,6 +1727,7 @@ class EmployeeRestController extends AdminController $responce['OpenForEnrollment'] = $array['open_for_enrollment']; $responce['policy_terms'] = $decodedArray; $responce['policy_type_id'] = $array['policy_type_id']; + //$responce['is_member_modify_allowed'] = $array['is_member_modify_allowed']; $responce['disclaimer'] = $array['disclaimer']; $tpaArray = $this->employeeModel->select('employees.name as name , employee_polices.tpa_id as tpa_id , employee_polices.rand_string as rand_string') @@ -1631,7 +1742,7 @@ class EmployeeRestController extends AdminController if(count($tpaArray)) { if($tpaArray[0]->tpa_id != null) - $responce['eCardDownload'] = base_url('download-e-card/') . $tpaArray[0]->rand_string; + $responce['eCardDownload'] = base_url('download-e-card/') . $tpaArray[0]->rand_string.'/1'; else $responce['eCardDownload'] = null; @@ -1640,7 +1751,7 @@ class EmployeeRestController extends AdminController } if(count($getSlabAndGridData['slab_rates'])){ - if($getSlabAndGridData['slab_rates'][0]['premium_type'] == 1) + if($getSlabAndGridData['slab_rates'][0]['premium_type'] == 1 || $getSlabAndGridData['slab_rates'][0]['premium_type'] == 3) { $responce['floter_text_heading'] = 'Floater Sum Insured'; }else{ @@ -1651,6 +1762,10 @@ class EmployeeRestController extends AdminController if($array['is_addon'] == 3 && $array['policy_type_id'] == 3)//dependent add on policy { + + if($this->request->getGet('client_id') == 8) // This changes only for client "sterling" + { + $selfGMC = $this->employeeModel->select('employees.name , employee_polices.basic_cover_si') ->join('employee_polices', 'employees.id = employee_polices.employee_id') ->join('client_policy', 'client_policy.id = employee_polices.client_policy_id AND client_policy.policy_type_id = 2') @@ -1669,6 +1784,9 @@ class EmployeeRestController extends AdminController // To reindex the array to have a proper 0 index $responce['SlabRates'] = array_values($filteredSlabRates); + } + + // Map family floaters that already exist in the employee table $familyFloates = $policy_terms->family_floaters; // remove parent and parent-in-law from familyFloaters @@ -1689,7 +1807,7 @@ class EmployeeRestController extends AdminController foreach ($addOnEmployeeData as $key => $value) { if ($value['family_floater_key'] === $dependent) { $employee_policy = $this->employeePolicyModel->where('employee_id',$value['id'])->where('client_policy_id',$array['id'])->where('is_active', 1 )->get()->getRow(); - if(isset($employee_policy->basic_cover_si)){ $dependent_and_si_value = $employee_policy->basic_cover_si; } + if(isset($employee_policy->basic_cover_si)){ $dependent_and_si_value = ($dependent_and_si_value == 0) ? $employee_policy->basic_cover_si : $dependent_and_si_value; } if(isset($employee_policy->rata_premimum)){ $dependent_and_si_premium_value = $dependent_and_si_premium_value + $employee_policy->rata_premimum;} if(isset($employee_policy->gst)){ $dependent_and_si_gst_value = $dependent_and_si_gst_value + $employee_policy->gst;} @@ -1768,8 +1886,8 @@ class EmployeeRestController extends AdminController $responce['family_floaters_of_dependent_and_si_array'] = $data; $responce['family_floaters_of_dependent_and_si_value'] = $dependent_and_si_value > 0 ? $dependent_and_si_value : 0; - $responce['family_floaters_of_dependent_and_si_premium_value'] = $dependent_and_si_premium_value > 0 ? $dependent_and_si_premium_value : 0; - $responce['family_floaters_of_dependent_and_gst_value'] = $dependent_and_si_gst_value > 0 ? $dependent_and_si_gst_value : 0; + $responce['family_floaters_of_dependent_and_si_premium_value'] = $dependent_and_si_premium_value > 0 ? round($dependent_and_si_premium_value) : 0; + $responce['family_floaters_of_dependent_and_gst_value'] = $dependent_and_si_gst_value > 0 ? round($dependent_and_si_gst_value) : 0; @@ -1788,8 +1906,12 @@ class EmployeeRestController extends AdminController $whereArray = []; foreach ( $decodedArray->family_floaters as $key => $value) { if($value != 0){ - if($key == 'parents'){ $text = 'parent'; }else if($key == 'childrens'){ $text = 'child'; }else if($key == 'parents-in-law'){$text = 'parent_in_law';}else{ $text = $key; } - array_push($whereArray,$text); + if($key == 'parents'){ $text = ["parent"]; } + else if($key == 'childrens'){ $text = ["child"]; } + else if($key == 'parents-in-law'){ $text = ["parent_in_law"];} + else if($key ==='either-parents-pil') { $text = ["parent", "parent_in_law"];} + else{ $text = [$key]; } + $whereArray = array_merge($whereArray, $text); } } @@ -1806,7 +1928,7 @@ class EmployeeRestController extends AdminController foreach ($BasePolicyEmployeeData as $key => $value) { $employee_policy = $this->employeePolicyModel->where('employee_id',$value['id'])->where('client_policy_id',$array['id'])->where('is_active', 1 )->get()->getRow(); - if(isset($employee_policy->basic_cover_si)){ $only_si_value = $employee_policy->basic_cover_si; } + if(isset($employee_policy->basic_cover_si)){ $only_si_value = ($only_si_value == 0) ? $employee_policy->basic_cover_si : $only_si_value; } if(isset($employee_policy->rata_premimum)){ $only_si_premium_value = $only_si_premium_value + $employee_policy->rata_premimum;} if(isset($employee_policy->gst)){ $only_si_gst_value = $only_si_gst_value + $employee_policy->gst;} $temp3['is_value_exist'] = true; @@ -1823,7 +1945,7 @@ class EmployeeRestController extends AdminController $responce['family_floaters_of_only_si_array'] = $only_si_array; $responce['family_floaters_of_only_si_value'] = $only_si_value; - $responce['family_floaters_of_only_si_premium_value'] = $only_si_premium_value; + $responce['family_floaters_of_only_si_premium_value'] = round($only_si_premium_value); $responce['family_floaters_of_only_si_gst_value'] = $only_si_gst_value; @@ -1838,8 +1960,12 @@ class EmployeeRestController extends AdminController $whereArray = []; foreach ( $decodedArray->family_floaters as $key => $value) { if($value != 0){ - if($key == 'parents'){ $text = 'parent'; }else if($key == 'childrens'){ $text = 'child'; }else if($key == 'parents-in-law'){$text = 'parent_in_law';}else{ $text = $key; } - array_push($whereArray,$text); + if($key == 'parents'){ $text = ["parent"]; } + else if($key == 'childrens'){ $text = ["child"]; } + else if($key == 'parents-in-law'){ $text = ["parent_in_law"];} + else if($key ==='either-parents-pil') { $text = ["parent", "parent_in_law"];} + else{ $text = [$key]; } + $whereArray = array_merge($whereArray, $text); } } @@ -1855,7 +1981,7 @@ class EmployeeRestController extends AdminController foreach ($BasePolicyEmployeeData as $key => $value) { $employee_policy = $this->employeePolicyModel->where('employee_id',$value['id'])->where('client_policy_id',$array['id'])->where('is_active', 1 )->get()->getRow(); - if(isset($employee_policy->basic_cover_si)){ $only_si_value = $employee_policy->basic_cover_si; } + if(isset($employee_policy->basic_cover_si)){ $only_si_value = ($only_si_value == 0) ? $employee_policy->basic_cover_si : $only_si_value; } if(isset($employee_policy->rata_premimum)){ $only_si_premium_value = $only_si_premium_value + $employee_policy->rata_premimum;} if(isset($employee_policy->gst)){ $only_si_gst_value = $only_si_gst_value + $employee_policy->gst;} $temp3['is_value_exist'] = true; @@ -1872,8 +1998,8 @@ class EmployeeRestController extends AdminController $responce['family_floaters_of_only_si_array'] = $only_si_array; $responce['family_floaters_of_only_si_value'] = $only_si_value; - $responce['family_floaters_of_only_si_premium_value'] = $only_si_premium_value; - $responce['family_floaters_of_only_si_gst_value'] = $only_si_gst_value; + $responce['family_floaters_of_only_si_premium_value'] = round($only_si_premium_value); + $responce['family_floaters_of_only_si_gst_value'] = round($only_si_gst_value); if($this->request->getGet('policy') == 'GMC-SI-PARENT-TOPUP'){ @@ -1900,20 +2026,18 @@ class EmployeeRestController extends AdminController { $postData = json_decode($this->request->getBody(), true); + $this->myLogger->logme("error", $this->request->getBody()); $client_policy_id = $postData['client_policy_id']; sort($client_policy_id); $emp_code = $postData['emp_code']; $client_id = $postData['client_id']; - $this->employeeModel->where('emp_code', $emp_code ) - ->where('client_id', $client_id ) - ->where('is_active', 1 ) - ->set(array('emp_status'=>'enrolled')) - ->update(); - $empData = $this->employeeModel->where('emp_code', $emp_code )->where('client_id', $client_id ) ->where('is_active', 1 )->findAll(); - + $employeeIds = array_column($empData, 'id'); + //for mail common parameter + $filteredEmpData = array_filter($empData, fn($item) => $item['relationship'] === 'Self'); + if (!is_null($client_policy_id) && is_array($client_policy_id)) { $array_list = []; @@ -1922,33 +2046,70 @@ class EmployeeRestController extends AdminController $policy = $this->clientPolicyModel->where('id',$value)->where('open_for_enrollment',1)->find(); if($policy) { - foreach ($empData as $empDataKey => $empDataValue) + $this->myLogger->logme("error", 'client policy id = '.$value.' is open for enrollment'); + + $empPolicyData = $this->employeePolicyModel->where('client_policy_id', $value ) + ->where('is_active', 1 ) + ->whereIn('employee_id',$employeeIds) + ->findAll(); + if(count($empPolicyData)) { + + $empIdsFromPolicyData = array_column($empPolicyData, 'employee_id'); + //update emp polict table $this->employeePolicyModel->where('client_policy_id', $value ) ->where('is_active', 1 ) - ->where('employee_id', $empDataValue['id'] ) + ->whereIn('employee_id', $empIdsFromPolicyData ) + ->groupStart() + ->where('status', 'draft') + ->orWhere('status', 'enrolled') + ->groupEnd() ->set(array('status'=>'enrolled')) ->update(); + //update Employee table + $this->employeeModel->where('emp_code', $emp_code) + ->whereIn('id', $empIdsFromPolicyData) + ->where('client_id', $client_id) + ->where('is_active', 1) + ->groupStart() + ->where('emp_status', 'draft') + ->orWhere('emp_status', 'enrolled') + ->groupEnd() + ->set(['emp_status' => 'enrolled']) + ->update(); + } - + $find = $this->employeeModel->getEmpFamilybyEmpCode(client_policy_id: $value,emp_code: $emp_code,client_id: $client_id,emp_status:['draft','enrolled'],policy_status:['draft','enrolled']); if(count($find) > 0){ $array_list[] = $find; } - } + }else { $this->myLogger->logme("error", 'client policy id = '.$value.' is not open for enrollment');} } + + + $notification = $this->notificationModel->where('client_id' ,$client_id)->where('template_name', 'member_review_and_summary_mail')->first(); - if (isset($notification) && $notification['enabled'] == 1) { + if (isset($notification) && $notification['enabled'] == 1 && count($array_list)) { $params ['array_list'] = $array_list; $params ['client_policy_id'] = $client_policy_id; $params ['emp_code'] = $emp_code; $params ['client_id'] = $client_id; $params ['notification'] = $notification; + $params['common'] = [ + 'client_id' => $filteredEmpData[0]['client_id'], + 'client_branch_id' => $filteredEmpData[0]['client_branch_id'], + 'client_policy_id' => null, + 'employee_policy_id' => null, + 'employee_id' => $filteredEmpData[0]['id'], + 'mail_type' => 'member_review_and_summary_mail', + ]; + // print_r($params);die; $wholeData =sendMailNotification::sendMailNotification('member_review_and_summary_mail', $params); $mail_send_return = MailHelper::send_email($wholeData[0]); @@ -1956,6 +2117,7 @@ class EmployeeRestController extends AdminController if (isset($wholeData[0])) { + $params['common']['mail_type'] = 'account_maneger_summary_mail'; $account_manager_wholeData =sendMailNotification::sendMailNotification('account_maneger_summary_mail', $params); if($account_manager_wholeData != null && $account_manager_wholeData != '' && count($account_manager_wholeData)) @@ -1968,6 +2130,7 @@ class EmployeeRestController extends AdminController $this->myLogger->logme("error", 'Account Manager Mail Configuration not Enable for this client'); } + $params['common']['mail_type'] = 'client_hr_summary_mail'; $client_hr_wholeData =sendMailNotification::sendMailNotification('client_hr_summary_mail', $params); if($client_hr_wholeData != null && $client_hr_wholeData != '' &&count($client_hr_wholeData)) @@ -1994,11 +2157,21 @@ class EmployeeRestController extends AdminController // retun array public function calculatePremium($clientPolicyId = null , $empCode = null, $default_si = null , $client_branch_id = null)//family level { + // dd($clientPolicyId, $empCode, $default_si, $client_branch_id); helper('excel_util_helper'); - $client_policy_id = $this->request->getVar('client_policy_id') ?? $clientPolicyId; - $emp_code = $this->request->getVar('emp_code') ?? $empCode; - $default_si = $this->request->getVar('si') ?? $default_si;// si amt which choosed in add on policy - $client_branch_id = $this->request->getVar('client_branch_id') ?? $client_branch_id; + + if($this->request){ // + $client_policy_id = $this->request->getVar('client_policy_id') ?? $clientPolicyId; + $emp_code = $this->request->getVar('emp_code') ?? $empCode; + $default_si = $this->request->getVar('si') ?? $default_si;// si amt which choosed in add on policy + $client_branch_id = $this->request->getVar('client_branch_id') ?? $client_branch_id; + }else{ + //Cli and enrollment + $client_policy_id = $clientPolicyId; + $emp_code = $empCode; + $default_si = $default_si;// si amt which choosed in add on policy + $client_branch_id =$client_branch_id; + } // dd($client_policy_id); @@ -2203,7 +2376,8 @@ class EmployeeRestController extends AdminController { try { - $clientPolicy = $this->clientPolicyModel->where('id',$this->request->getGet('client_policy_id'))->findAll(); + $clientPolicy = $this->clientPolicyModel->where('id',$this->request->getGet('client_policy_id')) + ->where('open_for_enrollment',1)->findAll(); if(count($clientPolicy)) { @@ -2211,8 +2385,19 @@ class EmployeeRestController extends AdminController if($clientPolicy[0]['is_addon'] == 2)//Topup { - $empData = $this->employeeModel->where('emp_code',$this->request->getGet('emp_code')) - ->where('is_addon_value', 0 )->findAll(); + + if($clientPolicy[0]['policy_type_id'] == 4)//GMC-Topup + { + $empData = $this->employeeModel->where('emp_code',$this->request->getGet('emp_code')) + ->where('is_addon_value', 0 ) + ->findAll(); + }else if($clientPolicy[0]['policy_type_id'] == 5)//GMC-Parent-Topup + { + $empData = $this->employeeModel->where('emp_code',$this->request->getGet('emp_code')) + ->where('is_addon_value', 1 ) + ->findAll(); + } + if(count($empData)) { foreach ($empData as $key => $value) { @@ -2268,7 +2453,7 @@ class EmployeeRestController extends AdminController function getEmployeeActiveOrInactivePolicy() { if($this->request->getGet('type') == 'Active'){ $policy_status = 1; }else{ $policy_status = 0; } - $ClientPolicyData = $this->clientPolicyModel->select('client_policy.* , policy_type.policy_type as policy_type,insurers.name as insurer_name,tpa.name as tpa_name') + $ClientPolicyData = $this->clientPolicyModel->select('client_policy.* , policy_type.policy_type as policy_type,insurers.name as insurer_name,tpa.name as tpa_name,tpa.network_hospitals as network_hospitals_url') ->join('insurers', 'client_policy.insurer_id = insurers.id', 'left') ->join('tpa', 'client_policy.tpa_id = tpa.id', 'left') ->join('policy_type', 'client_policy.policy_type_id = policy_type.id', 'left') @@ -2318,6 +2503,7 @@ class EmployeeRestController extends AdminController $data['policy_no'] = $ClientPolicyValue['policy_no']; $data['insurer_name'] = $ClientPolicyValue['insurer_name']; $data['tpa_name'] = $ClientPolicyValue['tpa_name']; + $data['network_hospitals_url'] = $ClientPolicyValue['network_hospitals_url']; $data['policy_start_date'] = $this->convertDateFormatDisplay($ClientPolicyValue['policy_start_date']); $data['policy_end_date'] = $this->convertDateFormatDisplay($ClientPolicyValue['policy_end_date']); // $data['policy_terms'] = $terms; @@ -2347,22 +2533,22 @@ class EmployeeRestController extends AdminController $si_gst_value = 0; foreach ($employee_policy as $key => $value) { - if(isset($value['basic_cover_si'])){ $si_value = $value['basic_cover_si']; } + if(isset($value['basic_cover_si'])){ $si_value = ($si_value == 0) ? $value['basic_cover_si'] : $si_value; } if(isset($value['premium'])){ $si_premium_value = $si_premium_value + $value['premium'];} if(isset($value['gst'])){ $si_gst_value = $si_gst_value + $value['gst'];} } if($employee_policy[0]['tpa_id'] != null) - $data['eCardDownload'] = base_url('download-e-card/') . $employee_policy[0]['rand_string']; + $data['eCardDownload'] = base_url('download-e-card/') . $employee_policy[0]['rand_string'].'/1'; else $data['eCardDownload'] = null; $data['si_value'] = $si_value; - $data['si_premium_value'] = ($ClientPolicyValue['policy_type_id'] == 1 || $ClientPolicyValue['policy_type_id'] == 2) ? 0 : $si_premium_value; - $data['si_gst_value'] = ($ClientPolicyValue['policy_type_id'] == 1 || $ClientPolicyValue['policy_type_id'] == 2) ? 0 : $si_gst_value; + $data['si_premium_value'] = ($ClientPolicyValue['policy_type_id'] == 1 || $ClientPolicyValue['policy_type_id'] == 2) ? 0 : round($si_premium_value); + $data['si_gst_value'] = ($ClientPolicyValue['policy_type_id'] == 1 || $ClientPolicyValue['policy_type_id'] == 2) ? 0 : round($si_gst_value); $data['EmployeePolicy'] = $employee_policy; array_push($result, $data); @@ -2381,6 +2567,8 @@ class EmployeeRestController extends AdminController function policyTermsFiter($terms , $type) { + + $gpa = [ "sumInsured2" => "Sum Insured", @@ -2410,18 +2598,25 @@ class EmployeeRestController extends AdminController ]; $gmc = [ - "sum_insured" => "Sum Insured", + "waiverofpreexistingdiseases" => "Waiver of Pre-existing Diseases", - "maternitycoverage" => "Maternity Coverage", - "babyday1cover" => "Baby Day 1 Cover", - "9monthwaitingperiodwaived" => "9-month waiting Period �waived", - "coverfromthedateofjoining" => "Cover from the date of Joining", "waiverof1,2,3&4thyearexclusions" => "Waiver of 1, 2, 3 & 4th year Exclusions", "waiverof30dayswaitingperiod" => "Waiver of 30 days waiting period", + "9monthwaitingperiodwaived" => "9-month waiting Period waived", + "twindelivery" => "Twin Delivery", + "maternitycoverage" => "Maternity Coverage", + "preandpostnatal" => "Pre and Post natal", "prehospitalizationcover" => "Pre Hospitalization Cover", - "copayzonewisecopay" => "Co-Pay/Zone wise Co Pay", + "posthospitalizationcover" => "Post Hospitalization Cover ", + "congenitaldiseasesinternal" => "Congenital Diseases - Internal ", + "congenitaldiseasesexternal" => "Congenital Diseases - External ", "roomrentlimit" => "Room Rent Limit", + "proportionatedeductionclause" => "Proportionate Deduction Clause", + "ayudhtreatmentcover" => "AYUSH treatment covered", + "lasiksurgery" => "Lasik Surgery", + "cataract" => "Cataract", "ailmentcapping" => "Ailment capping", + "moderntreatmentsasperirdai" => "Modern Treatment " ]; @@ -2430,15 +2625,51 @@ class EmployeeRestController extends AdminController if($type == 'gpa'){ foreach ($gpa as $key => $value) { if(isset($terms->$key)) - $finalarray[$value] = $terms->$key; + { + if($terms->$key == 1) + { + $termsValue = 'Yes'; + }else if($terms->$key == 0) + { + $termsValue = 'No'; + }else + { + $termsValue = $terms->$key; + } + $finalarray[$value] = $termsValue; + } + } + if(isset(($terms->gpa_special_condition_label)) && is_array($terms->gpa_special_condition_label) && is_array($terms->gpa_special_condition_input)){ + for ($i=0; $i < count($terms->gpa_special_condition_label); $i++) { + $finalarray[$terms->gpa_special_condition_label[$i]] = $terms->gpa_special_condition_input[$i]; + } } }else{ foreach ($gmc as $key => $value) { if(isset($terms->$key)) - $finalarray[$value] = $terms->$key; + { + if($terms->$key == 1) + { + $termsValue = 'Yes'; + }else if($terms->$key == 0) + { + $termsValue = 'No'; + }else + { + $termsValue = $terms->$key; + } + $finalarray[$value] = $termsValue; + } + } + if(isset(($terms->special_condition_label)) && is_array($terms->special_condition_label) && is_array($terms->special_condition_input)){ + for ($i=0; $i < count($terms->special_condition_label); $i++) { + $finalarray[$terms->special_condition_label[$i]] = $terms->special_condition_input[$i]; + } } } - + + + return $finalarray; @@ -2502,18 +2733,25 @@ class EmployeeRestController extends AdminController public function storeFireBase() { - // try { - $json = $this->request->getJSON(); - $firebase_token = $json->firebase_token; - $mobile = $json->mobile; + try { + + $firebase_token = isset($this->request->getJSON()->firebase_token) ? $this->request->getJSON()->firebase_token : null; + $mobile = isset($this->request->getJSON()->mobile) ? $this->request->getJSON()->mobile : null; + $email_id = isset($this->request->getJSON()->email_id) ? $this->request->getJSON()->email_id : null; // Ensure the mobile number is provided if (empty($mobile)) { return $this->respond(['status' => 'failed', 'code' => 400, 'message' => 'Mobile number is required'], 400); } - // Fetch employee by mobile number - $employee = $this->employeeModel->where('mobile', $mobile)->first(); + // Fetch employee + if (isset($mobile)) + { + $employee = $this->employeeModel->where('mobile', $mobile)->where('relationship', 'self')->where('is_active', 1)->first(); + } else { + $employee = $this->employeeModel->where('email_corporate', $email_id)->where('relationship', 'self')->where('is_active', 1)->first(); + } + if ($employee) { // Check if firebase_token is provided @@ -2548,38 +2786,271 @@ class EmployeeRestController extends AdminController } else { return $this->respond(['status' => 'failed', 'code' => 404, 'message' => 'Employee not found'], 404); } - // } catch (\Throwable $th) { - // log_message('error', 'An error occurred: ' . $th->getMessage()); - // return $this->respond(['status' => 'failed', 'code' => 500, 'message' => 'An error occurred', 'error' => $th->getMessage()], 500); - // } + } catch (\Throwable $th) { + log_message('error', 'An error occurred: ' . $th->getMessage()); + return $this->respond(['status' => 'failed', 'code' => 500, 'message' => 'An error occurred', 'error' => $th->getMessage()], 500); + } } - public function sendPushNotification() + // public function sendPushNotification() + // { + // $deviceToken = 'cMVKESh8QzqIl8nh_yqbcl:APA91bHKm87Sh1goVJNKZtctV4etgLMQboI0eyDVn3MH1yf9cO-2RtQRlFnKLdataOxosoxm7a4JvATKjfI1_Bids46mGw5m8zesp90mR4odCbD_cJtGmBeMYt4hssSY0YtAht1emK_H'; + // $title = 'Nhance'; + // $body = 'All your policy enrolled successfully ..!'; + + // // Initialize Firebase with the service account + // $firebase = (new Factory) + // ->withServiceAccount(APPPATH . 'Config/google-services.json') + // ->createMessaging(); + + // $notification = Notification::create($title, $body); + // $message = CloudMessage::withTarget('token', $deviceToken) + // ->withNotification($notification); + + // try { + // $firebase->send($message); + // return $this->response->setJSON(['status' => 'success']); + // } catch (MessagingException $e) { + // //return $this->response->setJSON(['status' => 'error', 'message' => $e->getMessage()]); + // log_message('error', $e->getMessage()); + // } + // } + + + public function getBackToEnrolledDetails() { - $deviceToken = 'cMVKESh8QzqIl8nh_yqbcl:APA91bHKm87Sh1goVJNKZtctV4etgLMQboI0eyDVn3MH1yf9cO-2RtQRlFnKLdataOxosoxm7a4JvATKjfI1_Bids46mGw5m8zesp90mR4odCbD_cJtGmBeMYt4hssSY0YtAht1emK_H'; - $title = 'Nhance'; - $body = 'All your policy enrolled successfully ..!'; - - // Initialize Firebase with the service account - $firebase = (new Factory) - ->withServiceAccount(APPPATH . 'Config/google-services.json') - ->createMessaging(); - - $notification = Notification::create($title, $body); - $message = CloudMessage::withTarget('token', $deviceToken) - ->withNotification($notification); - - try { - $firebase->send($message); - return $this->response->setJSON(['status' => 'success']); - } catch (MessagingException $e) { - //return $this->response->setJSON(['status' => 'error', 'message' => $e->getMessage()]); - log_message('error', $e->getMessage()); + // Get query parameters + $empCode = $this->request->getGet('emp_code'); + $clientId = $this->request->getGet('client_id'); + $clientBranchId = $this->request->getGet('client_branch_id'); + + + if (!$empCode || !$clientId || !$clientBranchId) { return $this->fail("emp_code, client_id, and client_branch_id are required parameters."); } + + //Fetch active employee details + $employees = $this->employeeModel->select('id,emp_code,name,relationship,dob,emp_status,is_addon_value,created_at,updated_at') + ->where([ + 'emp_code' => $empCode, + 'client_id' => $clientId, + 'client_branch_id' => $clientBranchId, + 'is_active' => 1 + ]) + ->findAll(); + + //Find status of self + $selfEmployee = array_filter($employees, function($employee) { return $employee['relationship'] === 'Self'; }); + $data['self_status'] = !empty($selfEmployee) ? array_values($selfEmployee)[0]['emp_status'] : null; + $data['self_enrolled_time'] = !empty($selfEmployee) ? array_values($selfEmployee)[0]['updated_at'] : null; + $data['self_employee_id'] = !empty($selfEmployee) ? array_values($selfEmployee)[0]['id'] : null; + + + //Fetch employee policy details + $employeeIds = array_column($employees, 'id'); + $policies = $this->employeePolicyModel->whereIn('employee_id', $employeeIds)->where('is_active',1)->findAll(); + + + //Find the stage of enrolment process + $employeeStatuses = array_column($employees, 'emp_status'); + $employeePolicyStatuses = array_column($policies, 'status'); + $uniqueStatuses = array_unique(array_merge($employeeStatuses, $employeePolicyStatuses)); + + if(count($uniqueStatuses) > 1){ $enrolmentStagekey = 1; }else{ if($uniqueStatuses[0] == 'draft'){ $enrolmentStagekey = 0; }else{ $enrolmentStagekey = 2; } } + + $enrolmentStage = ['Draft Only','Intermittent Enrollment','Successful Enrollment']; + $data['enrolment_stage'] = $enrolmentStage[$enrolmentStagekey]; + + + + $data['revert_employee_data'] = []; + $data['revert_employee_policy_data'] = []; + if($enrolmentStagekey == 1) + { + //Find active employee history + $empIdsWithoutSelf = $employeeIds; + $key = array_search($data['self_employee_id'], $empIdsWithoutSelf); + unset($empIdsWithoutSelf[$key]); + foreach ($empIdsWithoutSelf as $key => $pk) + { + $retrivedData = $this->retriveOldData($data['self_enrolled_time'],'employees',$pk); + if($retrivedData != false) + array_push($data['revert_employee_data'] , $retrivedData); + } + + //Find inactive employee history + $inActiveEmployees = $this->employeeModel->select('id,emp_code,name,relationship,dob,emp_status,is_addon_value,created_at,updated_at') + ->where([ + 'emp_code' => $empCode, + 'client_id' => $clientId, + 'client_branch_id' => $clientBranchId, + 'is_active' => 0 + ]) + ->findAll(); + $inActiveEmployeeIds = array_column($inActiveEmployees, 'id'); + foreach ($inActiveEmployeeIds as $key => $pk) + { + $retrivedData = $this->retriveOldData($data['self_enrolled_time'],'employees',$pk); + if($retrivedData != false) + array_push($data['revert_employee_data'] , $retrivedData); + } + + + //Merged active and inactive employees , employee_polict history + $mergedEmpIds = array_merge($employeeIds,$inActiveEmployeeIds); + $empPolicyData = $this->employeePolicyModel->whereIn('employee_id', $mergedEmpIds)->findAll(); + $employeePolicyIds = array_column($empPolicyData, 'id'); + foreach ($employeePolicyIds as $key => $pk) + { + $retrivedData = $this->retriveOldData($data['self_enrolled_time'],'employee_polices',$pk); + if($retrivedData != false) + array_push($data['revert_employee_policy_data'] , $retrivedData); + } } + + + if($this->request->getGet('revert_data') == 1) + { + //update data back to employee + if(count($data['revert_employee_data'])){ + foreach ($data['revert_employee_data'] as $key => $val) + { + $this->employeeModel->where('id',$val['id'] )->set($val['data'])->update(); + } + } + //update data back to employee policy + if(count($data['revert_employee_policy_data'])){ + foreach ($data['revert_employee_policy_data'] as $key => $val) + { + $this->employeePolicyModel->where('id',$val['id'] )->set($val['data'])->update(); + } + } + //update enrolled status for self + if(count($data['revert_employee_data']) || count($data['revert_employee_policy_data'])){ + $this->employeeModel->where('id',$data['self_employee_id'] )->set(array('emp_status'=>'enrolled'))->update(); + $data['retrieve_status'] = 'Data revert successfully'; + }else{ + $data['retrieve_status'] = 'There is no data to revert'; + } + + } + + + + + + // Fetch all policies related to these employees who currently active + $current_employee_data = $this->employeeModel->select('id,emp_code,name,relationship,dob,emp_status,is_addon_value,created_at,updated_at') + ->where([ + 'emp_code' => $empCode, + 'client_id' => $clientId, + 'client_branch_id' => $clientBranchId, + 'is_active' => 1 + ]) + ->findAll(); + $Ids = array_column($current_employee_data, 'id'); + $policies = $this->employeePolicyModel->whereIn('employee_id', $Ids)->where('is_active',1)->findAll(); + // Group policies by policy_id + $groupedPolicies = []; + foreach ($policies as $policy) { + $policyId = $policy['client_policy_id']; + + if (!isset($groupedPolicies[$policyId])) { + $groupedPolicies[$policyId] = [ + 'policy_id' => $policy['id'], + 'client_policy_id' => $policy['client_policy_id'], + 'uhid' => $policy['uhid'], + 'status' => $policy['status'], + 'basic_cover_si' => $policy['basic_cover_si'], + 'date_coverage' => $policy['date_coverage'], + 'policy_end_date' => $policy['policy_end_date'], + 'members' => [] + ]; + } + + // Add member details to the current policy + foreach ($current_employee_data as $employee) { + if ($employee['id'] === $policy['employee_id']) { + $groupedPolicies[$policyId]['members'][] = [ + 'id' => $employee['id'], + 'emp_code' => $employee['emp_code'], + 'name' => $employee['name'], + 'relationship' => $employee['relationship'], + 'dob' => $employee['dob'], + 'emp_status' => $employee['emp_status'], + 'is_addon_value' => $employee['is_addon_value'] + ]; + } + } + } + + // Re-index the grouped policies + $data['currentPolicies'] = array_values($groupedPolicies); + + return $this->respond(['data' => $data]); + } + + public function retriveOldData($self_enrolled_time,$table,$pk) + { + + $historyData = $this->auditHistoryModel->where('pk', $pk)->where('table_name',$table)->findAll(); + + $beforeEnrolled = []; + $afterEnrolled = []; + // Split the array + foreach ($historyData as $val) { + if ($val['created_at'] <= $self_enrolled_time) { $beforeEnrolled[] = $val; } else { $afterEnrolled[] = $val; } + } + + if(count($beforeEnrolled) && count($afterEnrolled)){ //After enrolment edited some of the data + + $temp['table'] = $table; + $temp['id'] = $pk; + // Extract earliest `old_value` for each `field_name` + $originalValues = []; + foreach ($afterEnrolled as $entry) { + $field = $entry['field_name']; + // If the field is not already in originalValues , update it + if (!isset($originalValues[$field])) { + $originalValues[$field] = $entry['old_value']; + } + } + $temp['data'] = $originalValues; + return $temp; + + }else if(!count($beforeEnrolled) && !count($afterEnrolled)){ //After enrolment created new data + + $temp['table'] = $table; + $temp['id'] = $pk; + $temp['data'] = ['is_active'=> 0 ]; + return $temp; + + }else if(!count($beforeEnrolled) && count($afterEnrolled)){ //After enrolment created new data and edited some of the data + + $temp['table'] = $table; + $temp['id'] = $pk; + $temp['data'] = ['is_active'=> 0 ]; + return $temp; + + }else if(count($beforeEnrolled) && !count($afterEnrolled)){ //After enrolment nothing changes from the data + + return false; + } + } + + + public function findThePolicyIsOpenForEnrollment($plicy_id) + { + + $policy = $this->clientPolicyModel->where('id',$plicy_id)->where('open_for_enrollment',1)->find(); + + if($policy) + return true; + else + return false; + } diff --git a/app/Controllers/EmployeeServiceController.php b/app/Controllers/EmployeeServiceController.php index 6756e470..7eafb908 100755 --- a/app/Controllers/EmployeeServiceController.php +++ b/app/Controllers/EmployeeServiceController.php @@ -132,7 +132,7 @@ class EmployeeServiceController extends AdminController 'format' => 'd-M-Y', 'allowed_values' => null, 'custom' => 'check_dob_diff', - 'params' => ['row', 'relationship', 'default_age_ratio'] + 'params' => ['row', 'relationship', 'default_age_ratio','policy_details'] ], 'gender' => [ 'col_idx' => 4, @@ -236,7 +236,9 @@ class EmployeeServiceController extends AdminController 'is_mandatory' => false, 'data_type' => 'str', 'format' => null, - 'allowed_values' => null + 'allowed_values' => null, + 'custom' => 'check_dup_email', + 'params' => ['row', 'existing_mobilenos'] ], 'pre_existing_ailments' => [ 'col_idx' => 14, @@ -342,6 +344,15 @@ class EmployeeServiceController extends AdminController '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] ] ]; @@ -765,10 +776,9 @@ class EmployeeServiceController extends AdminController $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($existing_units); + // dd($excel_data); foreach ($excel_data as $row_key => $row) { //define row wise action/event in temporary variable @@ -1036,7 +1046,7 @@ class EmployeeServiceController extends AdminController } } - 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) + 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']) @@ -1049,7 +1059,7 @@ class EmployeeServiceController extends AdminController //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'],policy_status:['active'],client_branch_id:[ $file['client_branch_id'] ],relationship:['self']); + $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)) { @@ -1232,7 +1242,6 @@ class EmployeeServiceController extends AdminController // Kint::dump($family);die(); $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]); } @@ -1326,7 +1335,7 @@ class EmployeeServiceController extends AdminController // } // 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']); + // $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']); @@ -1334,6 +1343,7 @@ class EmployeeServiceController extends AdminController $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) @@ -1368,7 +1378,7 @@ class EmployeeServiceController extends AdminController 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'])->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']]; + $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']; } @@ -1459,6 +1469,8 @@ class EmployeeServiceController extends AdminController ->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 @@ -1580,9 +1592,15 @@ class EmployeeServiceController extends AdminController // 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)) @@ -1603,7 +1621,7 @@ class EmployeeServiceController extends AdminController // echo '---------------------------------------'; //start implemet of si enhancement of grid type 10,11 - if(count($employee) && $file['action'] == 'dependent_addition' && $temp['source'] == 'db' && in_array($value['temp']['grid_id'],[10,11]) && ( ($value['temp']['premium_type'] == 1 && (strtolower($value['relationship']) == 'self' || $temp['acting_self'])) || ($value['temp']['premium_type'] == 2 || $value['temp']['premium_type'] == null))) + 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); @@ -1612,7 +1630,6 @@ class EmployeeServiceController extends AdminController break;//skip db employee } //end implemet of si enhancement of grid type - //save employee table $value['relationship'] = ucfirst(trim($value['relationship'])); if(count($employee)) @@ -1621,6 +1638,7 @@ class EmployeeServiceController extends AdminController $value['id'] = $employee[0]['id']; $value['emp_status'] = 'active'; $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'; @@ -1631,11 +1649,11 @@ class EmployeeServiceController extends AdminController $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'; } - $this->employeeModel->save($value); if (isset($value['id'])) { $emp_id = $value['id']; @@ -1658,7 +1676,8 @@ class EmployeeServiceController extends AdminController $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'; } @@ -1668,11 +1687,15 @@ class EmployeeServiceController extends AdminController $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'; } - - $this->employeePolicyModel->save($policy_data); + // 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']; @@ -1691,7 +1714,7 @@ class EmployeeServiceController extends AdminController $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']]; + $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); } @@ -1879,7 +1902,7 @@ class EmployeeServiceController extends AdminController // --------------------------------------------------------------------------------- - public function getFileMetaDataByFileId($file_id, $status = 'success'){ +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') @@ -1928,191 +1951,221 @@ class EmployeeServiceController extends AdminController } - -public function employeesEnrollmentInsert($params) -{ - - 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(); - - foreach ($excel_data as $key => $row) - { - // dd($key.'-'.count($excel_data)); - $value = []; - $policy_data = []; - $temp_unit = ''; - if(empty($row[12])) + 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)) { - $temp_unit = $existing_units[0]; + //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); } - - $value['emp_code'] = $row[1]; - $value['name'] = $row[2]; - $value['doj'] = (!empty($row[3]) ? convert_string_to_date($row[3],'Y-m-d'): null); - $value['gender'] = $row[4]; - $value['relationship'] = ucfirst(trim($row[5])); - $value['dob'] = convert_string_to_date($row[6],'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['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'){ - $relation = 'parent_in_law'; - }else if(strtolower(trim($value['relationship'])) === 'spouse'){ - $relation = 'spouse'; - }else{ - $relation = 'self'; - } - $value['family_floater_key'] = $relation; + //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 = []; - $policy_data['basic_cover_si'] = $row[9]; - $policy_data['date_coverage'] = $row[13]; - $policy_data['client_policy_id'] = $file['policy_id']; + //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(); - $employee = $this->employeeModel->checkExistingEmployee($value,$file['client_branch_id']); - unset($value['temp']); - //save employee table - // dd($employee['id']); - if($employee !== null) + // 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])) { - $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 '; + $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; - $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'; - - $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'; - $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'; - } - - $this->employeePolicyModel->save($policy_data); - $emp_policy_id = $this->employeePolicyModel->getInsertID(); - $this->myLogger->logme('error',$log_message); - - //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; - - //store email and mail content via helper to send notification - $emp_emails[] = sendMailNotification::sendMailNotification('member_welcome_mail', $params); - // Kint::dump($emp_emails); - // Kint::dump($key.'-'.count($excel_data)); - // if mail count is 20 send bulk mail and reset emp_emails variable - if (count($emp_emails) == 20 || $key == count($excel_data) ) { - $job_details = new Jobs(); - $r = Jobs::addJob(['job_name' => 'bulk_mail','payload' => $emp_emails]); - // echo 'Mail triggered'; - $emp_emails = []; + $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'){ + $relation = 'parent_in_law'; + }else if(strtolower(trim($value['relationship'])) === 'spouse'){ + $relation = 'spouse'; + }else{ + $relation = 'self'; } - - } - } - } //end of for loop + $value['family_floater_key'] = $relation; - $this->fileModel->where('id', $file_id)->set(['status' => 'success','reason' => ''])->update(); - $this->myLogger->logme("error",'{file_id} uploaded success',['file_id' => $file_id]); + $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']; - $this->setPullNotification($this->getFileMetaDataByFileId($file_id,'success')); + $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 '; + } + + $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; -} + return true; + }//end of employeesEnrollmentInsert -} +} \ No newline at end of file diff --git a/app/Controllers/JobWorker.php b/app/Controllers/JobWorker.php index a0d5f694..fcaf2096 100755 --- a/app/Controllers/JobWorker.php +++ b/app/Controllers/JobWorker.php @@ -126,6 +126,10 @@ class JobWorker extends AdminController 'employeesEnrollmentInsert' => [ 'type' => 'CC', // Handler Category 'handler' => 'App\Controllers\EmployeeServiceController', + ], + 'calculateMembersDemography' => [ + 'type' => 'CC', // Handler Category + 'handler' => 'App\Controllers\LeadsController', ] ]; diff --git a/app/Controllers/LeadsController.php b/app/Controllers/LeadsController.php index 7c5eef43..6140f45e 100644 --- a/app/Controllers/LeadsController.php +++ b/app/Controllers/LeadsController.php @@ -4,10 +4,14 @@ namespace App\Controllers; use CodeIgniter\API\ResponseTrait; + +use Exception; + use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Style\Border; use PhpOffice\PhpSpreadsheet\Style\Alignment; use PhpOffice\PhpSpreadsheet\Writer\Xlsx; +use PhpOffice\PhpSpreadsheet\Style\Fill; use App\Models\UserModel; use App\Models\ClientModel; @@ -24,13 +28,19 @@ use App\Models\RFQModel; use App\Models\InsurerModel; use App\Helpers\MailHelper; +use App\Helpers\ExcelMergeHelper; +use App\Helpers\ExcelSanitizeHelper; +use Google\Service\CloudSearch\PushItem; use Kint; +use App\Controllers\Jobs; +use App\Controllers\JobWorker; + class LeadsController extends BaseController -{ +{ use ResponseTrait; - + //log message protected $myLogger; @@ -89,13 +99,20 @@ class LeadsController extends BaseController } public function viewLeadsList() - { + { + + // $d = $this->constructExcelToSaveTemp(24, 1, $propsal_and_insurer = null); + // $job_details = new Jobs(); + // $r = Jobs::addJob(['job_name' => 'calculateMembersDemography', 'payload' => ['lead_id' => 24]]); + // $d = $this->calculateMembersDemography(['lead_id' => 24]); + //$this->mergeQuoteExcelFileWithMembersListExcelFile(24, 1, $propsal_and_insurer = null); + // dd($d); $data['page_name'] = 'Leads'; // Set basic data - $data['issuer'] = $this->issuer; - $data['client_type'] = $this->clientType; - $data['lead_type'] = $this->leadType; + $data['issuer'] = $this->issuer; + $data['client_type'] = $this->clientType; + $data['lead_type'] = $this->leadType; $data['lead_status'] = $this->leadsStatus; // Fetch policy types and entity data @@ -118,8 +135,8 @@ class LeadsController extends BaseController // dd($data); // Fetch leads data - $data['lead_data_list'] = $this->leadsModel->getLeadDataForLising(); - + $data ['lead_data_list'] = $this->leadsModel->getLeadDataForLising(); + // Load layout and pass data $this->loadLayout('leads_list', $data); } @@ -131,51 +148,56 @@ class LeadsController extends BaseController $data = $this->prepareLeadData(); // print_r($this->request->getPost()); die; - + if (!$id) { return $this->insertNewLead($data); } else { return $this->updateOldLead($id, $data); } } - + private function prepareLeadData() { $data = $this->request->getPost(); - - if($data['lead_type'] == 2){ + + if ($data['lead_type'] == 2) { $client_data = $this->clientModel->where('id', $data['client_id'])->where('is_active', 1)->first(); $data['client_name'] = $client_data['client_name']; $data['client_short_name'] = $client_data['short_name']; $data['entity_type_id'] = $client_data['entity_type_id']; $data['client_type'] = $client_data['client_type']; - }else{ + } else { $data['client_id'] = 0; $data['client_branch_id'] = 0; $data['source_policy_id'] = 0; } $data['client_code'] = generate_client_code(); - if($data['client_code'] == 2){ + if ($data['client_code'] == 2) { $data['client_code'] = generate_client_code('IC'); } - + $data = $this->prepareMultipleLeadData($data); // print_r($data); die; return $data; } private function prepareMultipleLeadData($data) - { + { // print_r($data); die; $processedData = []; - foreach($data['policy_type_id'] as $index => $value){ + $uploadFilePath = WRITEPATH . 'uploads/lead_files/'; + // Get all uploaded files for 'file_name[]' + $files = $this->request->getFileMultiple('file_name'); + + // print_r($files); die; + + foreach($data['policy_type_id'] as $index => $value){ // Separate the insurer and insurer branch, handle missing or invalid data if (isset($data['insurer'][$index]) && strpos($data['insurer'][$index], '-') !== false) { list($insurer_branch_id, $insurer_id) = explode('-', $data['insurer'][$index]); - } else { $insurer_branch_id = 0; $insurer_id = 0; } @@ -186,7 +208,6 @@ class LeadsController extends BaseController $tpa_branch_id = 0; $tpa_id = 0; } - // Separate the insurer and insurer branch, handle missing or invalid data if (isset($data['proposed_insurer'][$index]) && strpos($data['proposed_insurer'][$index], '-') !== false) { @@ -204,18 +225,37 @@ class LeadsController extends BaseController $proposed_tpa_id = 0; } - if(!empty($data['policy_start_date'][$index])){ + if (!empty($data['policy_start_date'][$index])) { $policy_start_date = change_date_format($data['policy_start_date'][$index], 'd/m/Y', 'Y-m-d'); - }else{ + } else { $policy_start_date = null; } - - if(!empty($data['policy_end_date'][$index])){ + + if (!empty($data['policy_end_date'][$index])) { $policy_end_date = change_date_format($data['policy_end_date'][$index], 'd/m/Y', 'Y-m-d'); - }else{ + } else { $policy_end_date = null; } - + + if(!empty($data['incurred_claim_date'][$index])){ + $incurred_claims_date = change_date_format($data['incurred_claim_date'][$index], 'd/m/Y', 'Y-m-d'); + }else{ + $incurred_claims_date = null; + } + + if(!empty($data['premium_date'][$index])){ + $premium_date = change_date_format($data['premium_date'][$index], 'd/m/Y', 'Y-m-d'); + }else{ + $premium_date = null; + } + + $file_name = file_Upload($files[$index], $uploadFilePath); + + $last_3_years_claims = null; + if($value != 2){ + $last_3_years_claims = $data['finyear']; + } + $processedData[] = [ 'lead_type' => $data['lead_type'], 'issuer' => $data['issuer'], @@ -244,13 +284,39 @@ class LeadsController extends BaseController 'policy_start_date' => $policy_start_date, 'policy_end_date' => $policy_end_date, 'no_of_lives' => $data['no_of_lives'][$index] ?? null, - 'claims' => $data['claims'][$index] ?? null, + 'incurred_claims' => $data['incurred_claims'][$index] ?? 0, 'location' => $data['location'][$index] ?? null, 'proposed_insurer_id' => $proposed_insurer_id ?? 0, 'proposed_insurer_branch_id' => $proposed_insurer_branch_id ?? 0, 'proposed_tpa_id' => $proposed_tpa_id ?? 0, 'proposed_tpa_branch_id' => $proposed_tpa_branch_id ?? 0, + 'renewal_emp_count' => $data['renewal_emp_count'][$index] ?? 0, + 'renewal_dept_count' => $data['renewal_dept_count'][$index] ?? 0, + 'renewal_no_of_lives' => $data['renewal_no_of_lives'][$index] ?? 0, + 'incept_emp_count' => $data['incept_emp_count'][$index] ?? 0, + 'incept_dept_count' => $data['incept_dept_count'][$index] ?? 0, + 'incept_no_of_lives' => $data['incept_no_of_lives'][$index] ?? 0, + 'exp_emp_count' => $data['exp_emp_count'][$index] ?? 0, + 'exp_dept_count' => $data['exp_dept_count'][$index] ?? 0, + 'exp_no_of_lives' => $data['exp_no_of_lives'][$index] ?? 0, + + 'incurred_claims_date' => $incurred_claims_date, + 'paid_claims' => $data['paid_claims'][$index] ?? 0, + 'outstanding_claims' => $data['outstanding_claims'][$index] ?? 0, + 'policy_run_days' => $data['policy_run_days'][$index] ?? 0, + 'premium_at_inception' => $data['premium_at_inception'][$index] ?? 0, + 'premium_date' => $premium_date, + 'earned_premium' => $data['earned_premium'][$index] ?? 0, + 'annualised_claims' => $data['annualised_claims'][$index] ?? 0, + 'incurred_claims_ratio' => $data['incurred_claims_ratio'][$index] ?? 0, + 'earned_claims_ratio' => $data['earned_claims_ratio'][$index] ?? 0, + 'total_si_at_incept' => $data['total_si_at_incept'][$index] ?? 0, + 'total_si_at_renewal' => $data['total_si_at_renewal'][$index] ?? 0, + 'fin_years_claims' => $last_3_years_claims, + + 'file_name' => $file_name, + 'status' => $data['status'] ?? null, 'notes' => $data['notes'] ?? null, ]; @@ -258,59 +324,76 @@ class LeadsController extends BaseController return $processedData; } - + private function insertNewLead($data) - { + { $insertCount = []; - foreach($data as $value){ + foreach ($data as $value) { $insert = $this->leadsModel->insert($value); $insertCount[] = $insert; $this->insertLeadStatus($insert, $value['status'], 3); + + //for this push the job to the calculateMembersDemography() function + $job_details = new Jobs(); + $r = Jobs::addJob(['job_name' => 'calculateMembersDemography', 'payload' => [ + 'lead_id' => $insert, + ]]); } if (count($insertCount) > 0) { - return $this->respond(['status' => true, 'lead_id' => $insert, 'message' => 'New Lead created successfully', 'data' =>$data], 200); + return $this->respond(['status' => true, 'lead_id' => $insert, 'message' => 'New Lead created successfully', 'data' => $data], 200); } - return $this->respond(['status' => false, 'lead_id' => $insert, 'message' => "Failed to create Lead", 'data' =>$data], 200); + return $this->respond(['status' => false, 'lead_id' => $insert, 'message' => "Failed to create Lead", 'data' => $data], 200); } - + private function updateOldLead($id, $data) - { + { if ($this->leadsModel->where('id', $id)->set($data[0])->update()) { $this->insertLeadStatus($id, $data[0]['status'], 3); - return $this->respond(['status' => true, 'lead_id' => $id, 'message' => "Lead updated successfully", 'data' =>$data], 200); + return $this->respond(['status' => true, 'lead_id' => $id, 'message' => "Lead updated successfully", 'data' => $data], 200); } - return $this->respond(['status' => false, 'lead_id' => $id, 'message' => "Failed to update Lead", 'data' =>$data], 200); + return $this->respond(['status' => false, 'lead_id' => $id, 'message' => "Failed to update Lead", 'data' => $data], 200); } // Get the Single Lead data for edit public function getLeadDataForEdit($id) - { + { $data = $this->leadsModel - ->where('leads.id', $id) - ->where('leads.is_active', 1) - ->first(); + ->where('leads.id', $id) + ->where('leads.is_active', 1) + ->first(); - if(!empty($data['policy_start_date'])){ + if (!empty($data['policy_start_date'])) { $data['policy_start_date'] = change_date_format($data['policy_start_date'], 'Y-m-d', 'd/m/Y'); - }else{ + } else { $data['policy_start_date'] = null; } - if(!empty($data['policy_end_date'])){ + if (!empty($data['policy_end_date'])) { $data['policy_end_date'] = change_date_format($data['policy_end_date'], 'Y-m-d', 'd/m/Y'); - }else{ + } else { $data['policy_end_date'] = null; } - - if($data){ - return $this->respond(['status' => true, 'data' => $data], 200); - }else{ - return $this->respond(['status' => false], 200); + + if (!empty($data['incurred_claims_date'])) { + $data['incurred_claims_date'] = change_date_format($data['incurred_claims_date'], 'Y-m-d', 'd/m/Y'); + } else { + $data['incurred_claims_date'] = null; } + if (!empty($data['premium_date'])) { + $data['premium_date'] = change_date_format($data['premium_date'], 'Y-m-d', 'd/m/Y'); + } else { + $data['premium_date'] = null; + } + + if ($data) { + return $this->respond(['status' => true, 'data' => $data], 200); + } else { + return $this->respond(['status' => false], 200); + } } private function insertLeadStatus($primaryKey, $status, $statusType) @@ -328,31 +411,32 @@ class LeadsController extends BaseController //--------RFQ----------------------------------------------------------------------------------------------- - public function viewRFQ($id, $type = 1){ + public function viewRFQ($id, $type = 1) + { $data['rfq_data'] = $this->RFQModel ->where('lead_id', $id) - ->where('type', $type) + // ->where('type', $type) ->where('is_active', 1) ->first(); $data['rfq_count'] = $this->RFQModel ->where('lead_id', $id) - ->where('type', 1) + // ->where('type', 1) ->where('is_active', 1) ->countAllResults(); $data['qcr_count'] = $this->RFQModel - ->where('lead_id', $id) - ->where('type', 2) - ->where('is_active', 1) - ->countAllResults(); + ->where('lead_id', $id) + ->where('type', 2) + ->where('is_active', 1) + ->countAllResults(); // dd(count($data['rfq_data'])); $data['lead_id'] = $id; $lead_data = $this->leadsModel - ->select('leads.*, policy_type.question_json') + ->select('leads.*, policy_type.question_json, policy_type.policy_type') ->join('policy_type', 'leads.policy_type_id = policy_type.id') ->where('leads.id', $id) ->where('leads.is_active', 1) @@ -360,22 +444,26 @@ class LeadsController extends BaseController // dd($lead_data); - if($lead_data['lead_type'] == 2){ + if ($lead_data['lead_type'] == 2) { $client_policy_data = $this->clientPolicyModel->where('is_active', 1)->where('id', $lead_data['source_policy_id'])->first(); $data['policy_terms'] = $client_policy_data['policy_terms']; } $data['question_json'] = $lead_data['question_json']; - $data['page_name'] = isset($data['rfq_data']['type']) && $data['rfq_data']['type'] == 2 ? 'QCR' : 'RFQ'; + $data['page_name'] = $type == 2 ? 'QCR' : 'RFQ'; $data['insurer'] = $this->insurerBranchModel->getInsurerBranchesWithInsurerNames(); $data['userList'] = $this->userModel->getUserListForRFQ(); $data['lead_data'] = $lead_data; + $data['mail_content'] = $this->transformMailContent($id); + // dd($data); $this->loadLayout('view_rfq.php', $data); } public function createRFQ(){ + + // print_r($this->request->getPost('json')); die(); $data = $this->request->getPost(); $lead_id = $data['lead_id']; @@ -390,14 +478,17 @@ class LeadsController extends BaseController $result = $this->RFQModel->insert($data); if ($result) { - return $this->respond(['status' => true, 'id' => $result, 'message' => 'RFQ created successfully', 'data' =>$data], 200); + + $message = "RFQ submitted successfully"; + if($data['submit_type'] == 'QCR'){ $message = "QCR submitted successfully"; } + return $this->respond(['status' => true, 'id' => $result, 'message' => $message, 'data' => $data], 200); } - return $this->respond(['status' => false, 'id' => $result, 'message' => "Failed to create RFQ", 'data' =>$data], 200); - + return $this->respond(['status' => false, 'id' => $result, 'message' => "Failed to create RFQ", 'data' => $data], 200); } - public function createQCR(){ + public function createQCR() + { $data = $this->request->getPost(); $lead_id = $data['lead_id']; @@ -413,10 +504,10 @@ class LeadsController extends BaseController $result = $this->RFQModel->insert($data); if ($result) { - return $this->respond(['status' => true, 'id' => $result, 'message' => 'QCR created successfully', 'data' =>$data], 200); + return $this->respond(['status' => true, 'id' => $result, 'message' => 'QCR created successfully', 'data' => $data], 200); } - return $this->respond(['status' => false, 'id' => $result, 'message' => "Failed to create QCR", 'data' =>$data], 200); + return $this->respond(['status' => false, 'id' => $result, 'message' => "Failed to create QCR", 'data' => $data], 200); } @@ -424,16 +515,40 @@ class LeadsController extends BaseController //export main route function - public function exportQCRandRFQ($lead_id, $type, $export_type){ - $this-> exportExcelForQCRandRFQ($lead_id, $type); + public function exportQCRandRFQ($lead_id, $type, $export_type) + { + $this->exportExcelForQCRandRFQ($lead_id, $type); } //FOR EXCEL public function exportExcelForQCRandRFQ($lead_id, $type) { $filepath = $this->constructExcelToSaveTemp($lead_id, $type); + $lead_data = $this->RFQModel->getRFQTableDataWithLeadIDAndType($lead_id, $type); + // dd($filepath); + + //Excel merging part + if ($lead_data['file_name'] != null && $lead_data['file_name'] != '') { + + $temp_file_path = $filepath['filePath']; + $temp_file_name = $filepath['fileName']; + $lead_file_path = WRITEPATH . 'uploads/lead_files/' . $lead_data['file_name']; + + // dd($lead_data, $temp_file_path, $temp_file_name, $lead_file_path); + + if ($lead_file_path) { + $filePaths = [ + ['file_path' => $temp_file_path, 'sheets' => []], + ['file_path' => $lead_file_path, 'sheets' => []] + ]; + // $outputPath = dirname($temp_file_path) . '/' . 'merged_' . $temp_file_name; + $result = ExcelMergeHelper::mergeExcelFiles($filePaths, $temp_file_path); + // print_rr($result); + } + } + $filepath = $filepath['filePath']; - + if (file_exists($filepath)) { // Set headers to force download header('Content-Description: File Transfer'); @@ -441,45 +556,112 @@ class LeadsController extends BaseController header('Content-Disposition: attachment; filename="' . basename($filepath) . '"'); header('Content-Length: ' . filesize($filepath)); header('Pragma: public'); - + // Output the file content readfile($filepath); - + // Delete the file after download unlink($filepath); - + exit; } else { echo "File does not exist."; } } - + //Construct excel file and save the file to the folder and return file path public function constructExcelToSaveTemp($lead_id, $type, $propsal_and_insurer = null) - { + { $rfq_data = $this->RFQModel->getRFQTableDataWithLeadIDAndType($lead_id, $type); - // dd($rfq_data, $lead_id, $type); + // dd($rfq_data, $lead_id, $type, $propsal_and_insurer); + // print_r($propsal_and_insurer); die; + + if($rfq_data['lead_type'] == 1){ + + if($rfq_data['policy_type_id'] == 2){ + $lead_data = [ + + 'Insured' => $rfq_data['client_name'], + 'Policy Status' => $rfq_data['status'], + + 'No of Employees' => $rfq_data['incept_emp_count'], + 'No of Dependents' => $rfq_data['incept_dept_count'], + 'Total Lives' => $rfq_data['incept_no_of_lives'], + + 'Period of Insurance ' => date('d/m/Y', strtotime($rfq_data['policy_start_date'])).' to '. date('d/m/Y', strtotime($rfq_data['policy_end_date'])), + 'Policy Run Days' => $rfq_data['policy_run_days'], + ]; + }else if($rfq_data['policy_type_id'] == 1){ + $lead_data = [ + 'Insured' => $rfq_data['client_name'], + 'No of Employees at Inception' => $rfq_data['incept_emp_count'], + 'Total Sum Insured at Inception ' => $rfq_data['total_si_at_incept'], + 'Policy Period' => date('d/m/Y', strtotime($rfq_data['policy_start_date'])).' to '. date('d/m/Y', strtotime($rfq_data['policy_end_date'])), + 'Policy Status' => $rfq_data['status'], + 'Existing Insurer' => $rfq_data['insurer_name'], + 'TPA ' => $rfq_data['tpa_name'], + ]; + } + + }else{ + if($rfq_data['policy_type_id'] == 2){ + $lead_data = [ + + 'Insured' => $rfq_data['client_name'], + 'Policy Status' => $rfq_data['status'], + + 'No of Employees at Inception' => $rfq_data['incept_emp_count'], + 'No of Dependents at Inception' => $rfq_data['incept_dept_count'], + 'Total Lives at Inception ' => $rfq_data['incept_no_of_lives'], + + 'No of Employees at Expiry' => $rfq_data['exp_emp_count'], + 'No of Dependents at Expiry' => $rfq_data['exp_dept_count'], + 'Total Lives at Expiry ' => $rfq_data['exp_no_of_lives'], + + 'No of Employees at Renewal' => $rfq_data['renewal_emp_count'], + 'No of Dependents at Renewal' => $rfq_data['renewal_dept_count'], + 'Total Lives at Renewal ' => $rfq_data['renewal_no_of_lives'], + + 'Period of Insurance ' => date('d/m/Y', strtotime($rfq_data['policy_start_date'])).' to '. date('d/m/Y', strtotime($rfq_data['policy_end_date'])), + 'Policy Run Days' => $rfq_data['policy_run_days'], + 'Inception Premium' => $rfq_data['premium_at_inception'], + 'Premium as on (Date - DD MM YYYY should be entered based on the claims dump report)' => $rfq_data['premium_date'], + 'Earned Premium' => $rfq_data['earned_premium'], + 'Incurred Claims as on (Date - DD MM YYYY should be entered based on the claims dump report)' => $rfq_data['incurred_claims_date'], + 'Annualised Claims' => $rfq_data['annualised_claims'], + 'Incurred Claims Ratio' => $rfq_data['incurred_claims_ratio'], + 'Earned Claims Ratio' => $rfq_data['earned_claims_ratio'], + ]; + }else if($rfq_data['policy_type_id'] == 1){ + $lead_data = [ + 'Insured' => $rfq_data['client_name'], + 'No of Employees at Renewal' => $rfq_data['renewal_emp_count'], + 'Total Sum Insured at Renewal ' => $rfq_data['total_si_at_renewal'], + 'Policy Period' => date('d/m/Y', strtotime($rfq_data['policy_start_date'])).' to '. date('d/m/Y', strtotime($rfq_data['policy_end_date'])), + 'Policy Status' => $rfq_data['status'], + 'Existing Insurer' => $rfq_data['insurer_name'], + 'TPA ' => $rfq_data['tpa_name'], + ]; + } + } - $lead_data = [ - 'Insured' => $rfq_data['client_name'], - 'Insurer' => $rfq_data['insurer_name'] . ' - ' . $rfq_data['insurer_branch_name'], - 'TPA' => $rfq_data['tpa_name'] . ' - ' . $rfq_data['tpa_branch_name'], - ]; - $data = json_decode($rfq_data['json'], true); if($type == 2){ - $data = $this->convertJsonForQCR($data, 'stc'); + $data = $this->convertJsonForQCR($data, $type); if($propsal_and_insurer !== null){ list($proposal_key, $insurer_key) = explode('-', $propsal_and_insurer, 2); $data = $this->transformProposelData($data, $proposal_key, $insurer_key); } + }else if($type == 1){ + $data = $this->convertJsonForQCR($data, $type); + // dd($data); } - + $spreadsheet = new Spreadsheet(); $sheet = $spreadsheet->getActiveSheet(); - + // Start with lead_data at the top $rowNumber = 1; foreach ($lead_data as $key => $value) { @@ -499,26 +681,26 @@ class LeadsController extends BaseController ], ]); - + $rowNumber += 2; // Add headers and subheaders $headers = $data['table_data']['headers']; $subHeaderRow = $rowNumber + 1; $columnLetter = 'A'; - + foreach ($headers as $header) { if (in_array($header['parentHeader'], ['Item Key', 'Action'])) { continue; } - + if ($header['parentHeader'] === 'Sno') { $header['parentHeader'] = 'S.No.'; } - + $startColumn = $columnLetter; // Start of the current header range $subHeaderCount = count($header['subHeaders']); // Number of subheaders for this parent header - + // Set parent header value $sheet->setCellValue("{$startColumn}{$rowNumber}", $header['parentHeader']); $sheet->getStyle("{$startColumn}{$rowNumber}")->applyFromArray([ @@ -528,7 +710,7 @@ class LeadsController extends BaseController 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER, ], ]); - + // Merge header cells if it spans multiple subheaders if ($subHeaderCount > 1) { $endColumn = chr(ord($startColumn) + $subHeaderCount - 1); // Calculate the end column @@ -536,7 +718,7 @@ class LeadsController extends BaseController } else { $endColumn = $startColumn; // No merge needed if only one subheader } - + // Add subheaders foreach ($header['subHeaders'] as $subHeader) { $sheet->setCellValue("{$columnLetter}{$subHeaderRow}", $subHeader); @@ -550,7 +732,7 @@ class LeadsController extends BaseController $columnLetter++; // Move to the next column for subheaders } } - + // Apply border to the header range $headerRange = "A{$rowNumber}:" . chr(ord($columnLetter) - 1) . "{$subHeaderRow}"; $sheet->getStyle($headerRange)->applyFromArray([ @@ -565,7 +747,7 @@ class LeadsController extends BaseController // Increase row height for headers and subheaders $sheet->getRowDimension($rowNumber)->setRowHeight(30); // Header row height $sheet->getRowDimension($subHeaderRow)->setRowHeight(25); // Subheader row height - + $rowNumber = $subHeaderRow + 2; $column_data = $data['table_data']['data']; $serial_no = 1; @@ -599,27 +781,32 @@ class LeadsController extends BaseController ], ], ]); - - if($type == 2){ + + if ($type == 2) { $rowNumber += 2; - + // Add premium data + $labelArray = ["Premium", "GST (%)", "GST Amount (₹)", "Total"]; $premiumData = $data['premium_data']['data']; - $premium = ['Premium']; - $gst = ['GST']; - $total = ['Total']; - + $premium = [$labelArray[0]]; + $gst = [$labelArray[1]]; + $gstAmt = [$labelArray[2]]; + $total = [$labelArray[3]]; + foreach ($premiumData as $proposal => $insurers) { - foreach ($insurers as $insurer => $values) { - $premium[] = $values['Premium']; - $gst[] = $values['GST']; - $total[] = $values['Total']; + if($proposal != 'Particulars'){ + foreach ($insurers as $insurer => $values) { + $premium[] = $values[$labelArray[0]]; + $gst[] = $values[$labelArray[1]]; + $gstAmt[] = $values[$labelArray[2]]; + $total[] = $values[$labelArray[3]]; + } } } - - foreach ([$premium, $gst, $total] as $index => $rowData) { + + foreach ([$premium, $gst, $gstAmt, $total] as $index => $rowData) { $columnLetter = 'B'; foreach ($rowData as $key => $value) { $sheet->setCellValue("{$columnLetter}{$rowNumber}", $value); @@ -640,43 +827,496 @@ class LeadsController extends BaseController ], ], ]); - } - + // Auto-size columns foreach ($sheet->getColumnIterator() as $column) { $sheet->getColumnDimension($column->getColumnIndex())->setAutoSize(true); } - + // Set filename $string = ($type == 2) ? 'QCR' : 'RFQ'; $filename = "{$string}_{$rfq_data['client_short_name']}_{$rfq_data['policy_type']}_" . date('YmdHis') . '.xlsx'; - + // Save to temporary location $uploadFilePath = WRITEPATH . 'tmp/' . $filename; $writer = new Xlsx($spreadsheet); $writer->save($uploadFilePath); - + return [ 'filePath' => $uploadFilePath, 'fileName' => $filename, ]; } + + //Merge RFQ/QCR file with lead members file + public function mergeQuoteExcelFileWithMembersListExcelFile($lead_id, $type, $source_file_path) + { + $rfq_data = $this->RFQModel->getRFQTableDataWithLeadIDAndType($lead_id, $type); + + if ($source_file_path && $rfq_data['file_name']) { + } + + return true; + } + + public function calculateMembersDemography($params) + { + $lead_id = $params['lead_id']; + $lead_data = $this->leadsModel->find($lead_id); + $file_name_with_path = WRITEPATH . "/uploads/lead_files/" . $lead_data['file_name']; + + if (!$lead_data) { + return ['status' => 'failed', 'message' => 'Lead data not found']; + } + if ($lead_data['file_name']) { + // $file_name_with_path = WRITEPATH . "/uploads/lead_files/NonPrintableCharacters.xlsx"; + + //check physical file + if (!file_exists($file_name_with_path)) { + //file not found update status and reason + $message = "Lead Physcial file not found"; + // echo $message; + $this->myLogger->logme('error', ($message . ' for file ' . $file_name_with_path)); + return ['status' => 'failed', 'message' => 'no physical file']; + } + + $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file_name_with_path); + + //get members data + $members_sheet = $spreadsheet->getSheet(0); + $highestRowAndColumn = $members_sheet->getHighestRowAndColumn(); + // dd($highestRowAndColumn); + $uncleaned_members = $members_sheet->rangeToArray('A1:' . $highestRowAndColumn['column'] . $highestRowAndColumn['row']); + $members = ExcelSanitizeHelper::sanitizeArrayData($uncleaned_members); + //get age band data + $age_band_sheet = $spreadsheet->getSheet(1); + $highestRowAndColumn = $age_band_sheet->getHighestRowAndColumn(); + $age_band_data = $age_band_sheet->rangeToArray('A1:' . $highestRowAndColumn['column'] . $highestRowAndColumn['row']); + + + //check age or dob column + $members_heading = $members[0]; + $available_col = null; + $col_index = null; + + if (in_array('age', array_map('strtolower', $members_heading))) { + $available_col = 'age'; + $col_index = array_search('age', array_map('strtolower', $members_heading)); + } elseif (in_array('dob', array_map('strtolower', $members_heading))) { + $available_col = 'dob'; + $col_index = array_search('dob', array_map('strtolower', $members_heading)); + } + + if ($available_col == null) { + $message = 'No DOB or Age column '; + $this->myLogger->logme('error', ($message . $file_name_with_path)); + return ['status' => 'failed', 'message' => $message]; + } + try { + $classifiers = $this->getDemographyData($members, $age_band_data, $members_heading, $available_col, $col_index); + } catch (Exception $e) { + return ['status' => 'fail', 'message' => $e->getMessage()]; + } + + try { + $result = $this->generateClassifierSpreadsheet($classifiers, WRITEPATH . 'uploads/lead_files/'); + if ($result['success']) { + $this->myLogger->logme('error', "Spreadsheet generated successfully!"); + + echo "Location: " . $result['fullpath'] . "\n"; + echo "Filename: " . $result['filename'] . "\n"; + $filePaths = [ + ['file_path' => WRITEPATH . 'uploads/lead_files/' . $lead_data['file_name'], 'sheets' => [0, 1]], + ['file_path' => WRITEPATH.'/uploads/lead_files/' . $result['filename'], 'sheets' => []], + ]; + $outputPath = WRITEPATH . 'uploads/lead_files/Member_Data.xlsx'; + $result_merge = ExcelMergeHelper::mergeExcelFiles($filePaths, $outputPath); + if ($result_merge) { + // Call the delete function after the file is successfully created + $deleteResponse = $this->deleteGeneratedFile($result['fullpath']); + + // Add delete message to response + $response['deleteMessage'] = $deleteResponse['message']; + return ['status' => 'success', 'message' => 'Member_Data Merged Suceesfully']; + } + } else { + echo "Error generating spreadsheet: " . $result['error']; + } + } catch (Exception $e) { + echo "Error: " . $e->getMessage(); + return ['status' => 'fail', 'message' => $e->getMessage()]; + } + } else { + $this->myLogger->logme('error', (' no file found ' . $file_name_with_path)); + return ['status' => 'failed', 'message' => 'no file found']; + } + } + + public function getDemographyData($members, $age_band_data, $members_heading, $available_col, $col_index) + { + $first_loop = 0; + $col_index_si = array_search('si enhancement', array_map('strtolower', $members_heading)); + $col_index_relationship = array_search('relationship', array_map('strtolower', $members_heading)); + $relations = []; + $si_amt = ['general']; // Initialize with 'general' as per first loop condition + + // First pass - collect unique relations and SI amounts + foreach ($members as $member) { + if ($first_loop == 0) { + $first_loop++; + continue; + } + if ($member == null) { + continue; + } + + if (!in_array($member[$col_index_relationship], $relations) && $member[$col_index_relationship] != null) { + $relations[] = $member[$col_index_relationship]; + } + + if (!in_array($member[$col_index_si], $si_amt) && $member[$col_index_si] != null) { + $si_amt[] = $member[$col_index_si]; + } + } + // Initialize classifier array + $classifiers = []; + foreach ($si_amt as $si) { + $classifiers[$si] = []; + // Initialize relation counts including Grand Total row + foreach ($relations as $relation) { + $classifiers[$si][$relation] = []; + foreach ($age_band_data as $age_bands) { + foreach ($age_bands as $age_interval) { + $classifiers[$si][$relation][$age_interval] = 0; + } + } + // Add Grand Total column for each relation echo('test passed 3.5'); + + $classifiers[$si][$relation]['Grand Total'] = 0; + } + // Initialize Grand Total row + $classifiers[$si]['Grand Total'] = []; + foreach ($age_band_data as $age_bands) { + foreach ($age_bands as $age_interval) { + $classifiers[$si]['Grand Total'][$age_interval] = 0; + } + } + // Add grand total of grand totals + $classifiers[$si]['Grand Total']['Grand Total'] = 0; + } + // Process members and count them + foreach ($members as $member) { + if ($first_loop == 0) { + $first_loop++; + continue; + } + // Get age + $age = $this->getAge($available_col, $member, $col_index); + + + $relation = $member[$col_index_relationship]; + $member_si = $member[$col_index_si]; + + // Find the correct age band (only once per member) + $found_band = false; + foreach ($age_band_data as $age_bands) { + if ($found_band) break; + + foreach ($age_bands as $age_band) { + //get Min and Max Age + list($min_age, $max_age) = $this->getAgeRange($age_band); + + // If age fits in this band + if ($age >= $min_age && $age <= $max_age) { + // Update counts for general category + if (isset($classifiers['general'][$relation][$age_band])) { + // Increment count for specific relation and age band + $classifiers['general'][$relation][$age_band]++; + // Update row total (Grand Total column) + $classifiers['general'][$relation]['Grand Total']++; + // Update column total (Grand Total row) + $classifiers['general']['Grand Total'][$age_band]++; + // Update grand total of grand totals + $classifiers['general']['Grand Total']['Grand Total']++; + } + + // Update counts for specific SI category + if (isset($classifiers[$member_si][$relation][$age_band])) { + // Increment count for specific relation and age band + $classifiers[$member_si][$relation][$age_band]++; + // Update row total (Grand Total column) + $classifiers[$member_si][$relation]['Grand Total']++; + // Update column total (Grand Total row) + $classifiers[$member_si]['Grand Total'][$age_band]++; + // Update grand total of grand totals + $classifiers[$member_si]['Grand Total']['Grand Total']++; + } + + $found_band = true; + break; + } + } + } + } + return $classifiers; + } + + public function generateClassifierSpreadsheet($classifiers, $outputDir = 'exports') + { + if (!file_exists($outputDir)) { + if (!mkdir($outputDir, 0755, true)) { + throw new Exception("Failed to create directory: $outputDir"); + } + } + // Check if directory is writable + if (!is_writable($outputDir)) { + throw new Exception("Directory is not writable: $outputDir"); + } + + // Generate unique filename + $timestamp = date('Y-m-d_His'); + $filename = "member_classification_{$timestamp}.xlsx"; + $filepath = $outputDir . DIRECTORY_SEPARATOR . $filename; + + // Check if file already exists (shouldn't happen with timestamp, but just in case) + if (file_exists($filepath)) { + $counter = 1; + while (file_exists($outputDir . DIRECTORY_SEPARATOR . "member_classification_{$timestamp}_{$counter}.xlsx")) { + $counter++; + } + $filename = "member_classification_{$timestamp}_{$counter}.xlsx"; + $filepath = $outputDir . DIRECTORY_SEPARATOR . $filename; + } + + $spreadsheet = new Spreadsheet(); + $sheet = $spreadsheet->getActiveSheet(); + $sheet->setTitle('Demography_Data'); + + // Get all age bands + $age_bands = array_keys(reset($classifiers['general'])); + array_pop($age_bands); // Remove 'Grand Total' + $age_bands[] = 'Grand Total'; // Add it back at the end + + $currentRow = 5; // Start from row 5 to match the example + + // Function to write section data + $writeSectionData = function ($data, $sheet, &$currentRow, $si_type) use ($age_bands) { + // Add section header for the SI type + $sheet->setCellValue('B' . $currentRow, strtoupper($si_type)); + + // Style section header + $sheet->getStyle('B' . $currentRow)->applyFromArray([ + 'font' => ['bold' => true, 'size' => 14], + 'alignment' => ['horizontal' => Alignment::HORIZONTAL_CENTER], + ]); + + $currentRow++; // Move to the next row after the section header + + // Set headers for the data table + $sheet->setCellValue('B' . $currentRow, 'Relationship'); + $col = 'C'; + foreach ($age_bands as $band) { + $sheet->setCellValue($col . $currentRow, $band); + $col++; + } + + // Style headers + $lastCol = chr(ord('B') + count($age_bands)); + $headerRange = 'B' . $currentRow . ':' . $lastCol . $currentRow; + $sheet->getStyle($headerRange)->applyFromArray([ + 'font' => ['bold' => true], + 'borders' => [ + 'allBorders' => [ + 'borderStyle' => Border::BORDER_THIN, + 'color' => ['rgb' => '000000'], + ], + ], + 'alignment' => [ + 'horizontal' => Alignment::HORIZONTAL_CENTER, + ], + ]); + + $currentRow++; + + // Write data rows + foreach ($data as $relation => $values) { + if ($relation !== 'Grand Total') { + $sheet->setCellValue('B' . $currentRow, $relation); + $col = 'C'; + foreach ($age_bands as $band) { + $value = $values[$band] ?: ''; // Convert 0 to empty string + $sheet->setCellValue($col . $currentRow, $value); + $col++; + } + + // Style data row + $dataRange = 'B' . $currentRow . ':' . $lastCol . $currentRow; + $sheet->getStyle($dataRange)->applyFromArray([ + 'borders' => [ + 'allBorders' => [ + 'borderStyle' => Border::BORDER_THIN, + 'color' => ['rgb' => '000000'], + ], + ], + 'alignment' => [ + 'horizontal' => Alignment::HORIZONTAL_CENTER, + ], + ]); + + $currentRow++; + } + } + + // Add Grand Total row + $sheet->setCellValue('B' . $currentRow, 'Grand Total'); + $col = 'C'; + foreach ($age_bands as $band) { + $sheet->setCellValue($col . $currentRow, $data['Grand Total'][$band]); + $col++; + } + + // Style Grand Total row + $totalRange = 'B' . $currentRow . ':' . $lastCol . $currentRow; + $sheet->getStyle($totalRange)->applyFromArray([ + 'font' => ['bold' => true], + 'borders' => [ + 'allBorders' => [ + 'borderStyle' => Border::BORDER_THIN, + 'color' => ['rgb' => '000000'], + ], + ], + 'fill' => [ + 'fillType' => Fill::FILL_SOLID, + 'startColor' => ['rgb' => 'F2F2F2'], + ], + 'alignment' => [ + 'horizontal' => Alignment::HORIZONTAL_CENTER, + ], + ]); + + $currentRow += 3; // Add gap after each section + }; + + // Write each SI section with gaps + foreach ($classifiers as $si_type => $data) { + $writeSectionData($data, $sheet, $currentRow, $si_type); + } + + // Auto-size columns + foreach (range('B', chr(ord('B') + count($age_bands))) as $col) { + $sheet->getColumnDimension($col)->setAutoSize(true); + } + + // Create Excel file + try { + // Create Excel file + $writer = new Xlsx($spreadsheet); + $writer->save($filepath); + + // Verify file was created successfully + if (!file_exists($filepath)) { + throw new Exception("Failed to create file: $filepath"); + } + + // Return the file info after creation + $response = [ + 'success' => true, + 'filepath' => $filepath, + 'filename' => $filename, + 'fullpath' => realpath($filepath) + ]; + + return $response; + + } catch (Exception $e) { + return [ + 'success' => false, + 'error' => $e->getMessage() + ]; + } + } + + // Function to delete generated file + public function deleteGeneratedFile($filePath) + { + try { + if (file_exists($filePath)) { + unlink($filePath); // Delete the file + return [ + 'success' => true, + 'message' => "File deleted successfully" + ]; + } else { + return [ + 'success' => false, + 'message' => "File does not exist" + ]; + } + } catch (Exception $e) { + return [ + 'success' => false, + 'error' => $e->getMessage() + ]; + } + } + + public function getAge($available_col, $member, $col_index) + { + if ($available_col == 'age') { + $age = $member[$col_index]; + } else { + $dob = $member[$col_index]; + if ($dob == 'DOB') { + return; + } + $dobDate = \DateTime::createFromFormat('d-M-Y', $dob); + $currentDate = new \DateTime(); + if ($dobDate == false) { + $this->myLogger->logme('error', $dob . 'is not valid'); + return; + } + $age = $currentDate->diff($dobDate)->y; + } + return $age; + } + + public function getAgeRange($age_band) + { + $age_band = trim($age_band); + // Parse age range + if (strpos($age_band, '-') === false) { + $min_age = (int)filter_var($age_band, FILTER_SANITIZE_NUMBER_INT); + $max_age = PHP_INT_MAX; + } else { + $parts = explode("-", $age_band); + $min_age = (int)$parts[0]; + $max_age = (int)$parts[1]; + } + + return array($min_age, $max_age); + } + + //this funciton for send mail to insurer and client with either RFQ/QCR public function sendMailWithAttachement() { helper('excel_util_helper'); helper('MailHelper'); + helper('ExcelMergeHelper'); + $params = $this->request->getPost(); - $params = $this->request->getGet(); // print_r($params); die; + $lead_id = $params['lead_id']; $file_type = $params['file_type']; //rfq or qcr $recipient_type = $params['recipient_type']; //insurer or client or internal or placement $recipient_mail = $params['recipient_mail']; // - only primary key of contacts $recipient_mail = json_decode($params['recipient_mail'], true); // - only primary key of contacts $propsal_and_insurer = isset($params['proposal_insurer']) ? $params['proposal_insurer'] : null; + $mail_content = $params['mail_content']; + $mail_subject = $params['subject']; $result_data = []; // dd($recipient_mail); @@ -687,18 +1327,22 @@ class LeadsController extends BaseController //gather lead info $lead_data = $this->leadsModel ->select('leads.*,policy_type.long_name,policy_type.policy_type,user_profiles.email as created_person_email') - ->join('policy_type', 'leads.policy_type_id = policy_type.id') - ->join('user_profiles', 'leads.created_by = user_profiles.id') + ->join('policy_type', 'leads.policy_type_id = policy_type.id', 'left') + ->join('user_profiles', 'leads.created_by = user_profiles.id', 'left') ->where('leads.id', $lead_id) ->first(); + // print_r($lead_data ); die; + $cc_mails = []; - + $bcc_mails = []; + //get CC Mails - if($recipient_type == 'internal' || $recipient_type == 'placement'){ + if ($recipient_type == 'internal' || $recipient_type == 'placement' || $recipient_type == 'insurer' || $recipient_type == 'client') { $cc_data = isset($params['cc']) ? $params['cc'] : ""; $param_cc_mail = json_decode($cc_data, true); + if (isset($param_cc_mail) && is_array($param_cc_mail) && count($param_cc_mail) > 0) { // Fetch user data where ID is in the param_cc_mail array $userData = $this->userModel @@ -712,18 +1356,49 @@ class LeadsController extends BaseController $cc_mails = array_column($userData, 'email'); // print_r(json_encode($cc_mails)); die; - + // If no emails were found, return an error response - if (empty($cc_mails)) { - return $this->respond(['status' => 'failed','code' => 400,'data' => '','message' => 'No valid CC mail addresses found!'], 200); - } + // if (empty($cc_mails)) { + // return $this->respond(['status' => 'failed','code' => 400,'data' => '','message' => 'No valid CC mail addresses found!'], 200); + // } } else { // Handle case where param_cc_mail is not valid - return $this->respond(['status' => 'failed','code' => 400,'data' => '','message' => 'CC mail not found!'], 200); + // return $this->respond(['status' => 'failed','code' => 400,'data' => '','message' => 'CC mail not found!'], 200); } } + + //get BCC Mails + if ($recipient_type == 'insurer' || $recipient_type == 'client') { + + $bcc_data = isset($params['bcc']) ? $params['bcc'] : ""; + $param_bcc_mail = json_decode($bcc_data, true); + if (isset($param_bcc_mail) && is_array($param_bcc_mail) && count($param_bcc_mail) > 0) { + // Fetch user data where ID is in the param_cc_mail array + $userData = $this->userModel + ->where('is_active', 1) + ->whereIn('id', $param_bcc_mail) + ->findAll(); + + // print_r($userData); die; + + // Extract emails from the fetched user data + $bcc_mails = array_column($userData, 'email'); + + // print_r(json_encode($cc_mails)); die; + + // If no emails were found, return an error response + // if (empty($cc_mails)) { + // return $this->respond(['status' => 'failed','code' => 400,'data' => '','message' => 'No valid CC mail addresses found!'], 200); + // } + + } else { + // Handle case where param_cc_mail is not valid + // return $this->respond(['status' => 'failed','code' => 400,'data' => '','message' => 'CC mail not found!'], 200); + } + } + if ($recipient_type == 'client' && ($lead_data['contact_person_email'] == '' || $lead_data['contact_person_email'] == null)) { return $this->respond(['status' => 'failed', 'code' => 400, 'data' => '', 'messgae' => 'Recipient mail not found ! '], 200); } @@ -733,12 +1408,28 @@ class LeadsController extends BaseController //get file path to attach $file_info = $this->constructExcelToSaveTemp($lead_id, ($file_type == 'rfq' ? 1 : 2), $propsal_and_insurer); + if ($lead_data['file_name'] != null && $lead_data['file_name'] != '') { + $temp_file_path = $file_info['filePath']; + $temp_file_name = $file_info['fileName']; + $lead_file_path = WRITEPATH . 'uploads/lead_files/' . $lead_data['file_name']; + if ($lead_file_path) { + $filePaths = [ + ['file_path' => $temp_file_path, 'sheets' => []], + ['file_path' => $lead_file_path, 'sheets' => []] + ]; + $outputPath = dirname($temp_file_path) . '/' . 'merged_' . $temp_file_name; + $result = ExcelMergeHelper::mergeExcelFiles($filePaths, $outputPath); + // print_rr($result); + } + } + // print_rr($lead_data); + // print_rr($file_info); // $file_path = WRITEPATH."uploads/excel/sample/correction.xls"; // $file_name = $file_type.'.xlsx'; // !dd($file_info); - - $file_path = $file_info['filePath']; - $file_name = $file_info['fileName']; + + $file_path = $result; + $file_name = basename($result); $attachments = [['fileName' => $file_name, 'filePath' => $file_path]]; //get recipient address @@ -753,9 +1444,9 @@ class LeadsController extends BaseController // print_r($recipient_data); die; - } else if($recipient_type == 'client') { + } else if ($recipient_type == 'client') { $recipient_data = [['name' => $lead_data['contact_person_name'], 'email' => $lead_data['contact_person_email']]]; - }else{ + } else { $recipient_data = [['name' => "Team", 'email' => $params['to']]]; } // print_r($recipient_data); die; @@ -763,7 +1454,19 @@ 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.

'; - if($recipient_data){ + //for mail content + if(!empty($mail_content)){ + $original_message = $mail_content; + } + + //for mail subject + if(!empty($mail_subject)){ + $subject = $mail_subject; + } + + // print_r($subject); die; + + if ($recipient_data) { foreach ($recipient_data as $recipient) { $message = $original_message; @@ -775,13 +1478,13 @@ class LeadsController extends BaseController // print_rr($message);calculate_days_bw_dates - $res = MailHelper::send_email(['mail' => $recipient['email'], 'cc'=> $cc_mails, 'subject' => $subject, 'message' => $message, 'attachments' => $attachments, 'reply_to' => $reply_to]); + $res = MailHelper::send_email(['mail' => $recipient['email'], 'cc' => $cc_mails, 'subject' => $subject, 'message' => $message, 'attachments' => $attachments, 'reply_to' => $reply_to, 'bcc' => $bcc_mails]); // !dd($res); $result_data[] = ['mail' => $recipient['email'], 'status' => $res]; } } - if($recipient_type == 'placement'){ + if ($recipient_type == 'placement') { list($proposal_key, $insurer_key) = explode('-', $propsal_and_insurer, 2); @@ -789,11 +1492,16 @@ class LeadsController extends BaseController 'proposel_name' => $proposal_key, 'insurer_name' => $insurer_key, 'insurer' => $params['insurer_and_branch'], - ] ; + ]; $data = [ 'proposel_data' => json_encode($lead_update_data), - 'status' => 'won' + 'status' => 'won', + 'placement_date' => change_date_format($params['placement_date'], 'd/m/Y', 'Y-m-d'), + 'utr_no' => $params['utr_no'], + 'premium_amount' => $params['premium_amount'], + 'total_amount' => $params['total_amount'], + 'cd_amount' => $params['cd_amount'], ]; $this->leadsModel->where('id', $lead_id)->set($data)->update(); @@ -809,12 +1517,11 @@ class LeadsController extends BaseController $data = $this->levelContactModel->getContactForRFQ(); - if($data){ + if ($data) { return $this->respond(['status' => true, 'data' => $data], 200); - }else{ + } else { return $this->respond(['status' => false], 200); } - } public function getInsurerBranchContacts($insurer_and_branch_id) @@ -822,12 +1529,12 @@ class LeadsController extends BaseController if (strpos($insurer_and_branch_id, '-') === false) { return $this->respond(['status' => false, 'message' => 'Invalid ID format'], 400); } - + // Split the insurer_and_branch_id list($insurerBranchId, $insurerId) = explode('-', $insurer_and_branch_id); - + $data = $this->levelContactModel->getContactForRFQ($insurerId, $insurerBranchId); - + if (!empty($data)) { return $this->respond(['status' => true, 'data' => $data], 200); } else { @@ -835,12 +1542,12 @@ class LeadsController extends BaseController } } - function transformProposelData($data, $proposel, $insurer){ + public function transformProposelData($data, $proposel, $insurer){ // print_r($data['premium_data']['data']); die; $headerData = []; - + // Default headers: S. No and Particulars $defaultHeaders = [ [ @@ -852,10 +1559,10 @@ class LeadsController extends BaseController 'subHeaders' => ['-'] ] ]; - + // Add default headers to the result $headerData = array_merge($headerData, $defaultHeaders); - + foreach ($data['table_data']['headers'] as $header) { // Check if the parentHeader matches the target proposal if ($header['parentHeader'] === $proposel) { @@ -882,13 +1589,13 @@ class LeadsController extends BaseController $sno = $entry['SNO']; $items = $entry['items']; $dataEntry = $entry['data']; - + $result = [ "SNO" => $sno, "items" => $items, "data" => [] ]; - + foreach ($dataEntry as $item) { // Include Sno and Particulars by default @@ -900,7 +1607,7 @@ class LeadsController extends BaseController "input_value" => $item['input_value'] ]; } - + // Include Proposal with Quote Asked by default if ($item['parentth'] === $proposel && $item['subth'] === "Quote Asked") { $result['data'][] = [ @@ -910,7 +1617,7 @@ class LeadsController extends BaseController "input_value" => $item['input_value'] ]; } - + // Example of including matching specific proposals and insurers if ($item['parentth'] === $proposel && $item['subth'] === $insurer) { $result['data'][] = [ @@ -921,13 +1628,13 @@ class LeadsController extends BaseController ]; } } - + // Add to the final result $columnData[] = $result; } - + $premiumData = []; - + foreach ($data['premium_data']['data'] as $key => $value) { if ($key === $proposel) { $premiumData[$key]['Quote Asked'] = $value['Quote Asked']; @@ -940,112 +1647,157 @@ class LeadsController extends BaseController $data['premium_data']['data'] = $premiumData; return $data; - } - function convertJsonForQCR($json, $type) + public function convertJsonForQCR($json, $type) { if ($json) { + // Deep copy of JSON $first_json = json_decode(json_encode($json), true); + // dd($first_json); - // Column-wise Check: Remove headers and relevant data if qcr == 0 - foreach ($json['proposal_data']['over_all_column_data'] as $proposalKey => $proposalData) { - if ($proposalData['stc'] == 0 || $proposalData['stc'] === false) { - // Remove matching parentHeader in headers - foreach ($first_json['table_data']['headers'] as $index => $header) { - if ($header['parentHeader'] === $proposalKey) { - unset($first_json['table_data']['headers'][$index]); - } - } - - // Remove data entries with matching parentth - foreach ($first_json['table_data']['data'] as &$item) { - $item['data'] = array_values(array_filter($item['data'], function ($entry) use ($proposalKey) { - return $entry['parentth'] !== $proposalKey; - })); - } - - // Remove proposalKey from over_all_column_data - unset($first_json['proposal_data']['over_all_column_data'][$proposalKey]); - - if($type == 'stc'){ - // Remove proposalKey from premium_data - unset($first_json['premium_data']['data'][$proposalKey]); - } - } - - // Insurer Check: Remove subHeaders and relevant data for insurers with qcr == 0 - foreach ($proposalData['insurers'] as $insurerIndex => $insurer) { - if ($insurer['stc'] === 0 || $insurer['stc'] === false) { - foreach ($first_json['table_data']['headers'] as &$header) { - if (isset($header['subHeaders'])) { - $header['subHeaders'] = array_values(array_filter($header['subHeaders'], function ($sub) use ($insurer) { - return $sub !== $insurer['display_name']; - })); + if($type == 2){ + + // Column-wise Check: Remove headers and relevant data if qcr == 0 + foreach ($json['proposal_data']['over_all_column_data'] as $proposalKey => $proposalData) { + + if (($proposalData['qcr'] == 0 || $proposalData['qcr'] === false) || ($proposalData['stc'] == 0 || $proposalData['stc'] === false)) { + + // Remove matching parentHeader in headers + foreach ($first_json['table_data']['headers'] as $index => $header) { + if ($header['parentHeader'] === $proposalKey) { + unset($first_json['table_data']['headers'][$index]); } } - + // Remove data entries with matching parentth foreach ($first_json['table_data']['data'] as &$item) { - $item['data'] = array_values(array_filter($item['data'], function ($entry) use ($insurer) { - return $entry['subth'] !== $insurer['display_name']; + $item['data'] = array_values(array_filter($item['data'], function ($entry) use ($proposalKey) { + return $entry['parentth'] !== $proposalKey; })); } - - // Remove insurer from proposal's insurers array - unset($first_json['proposal_data']['over_all_column_data'][$proposalKey]['insurers'][$insurerIndex]); - if($type == 'stc'){ - unset($first_json['premium_data']['data'][$proposalKey][$insurer['display_name']]); + // Remove proposalKey from over_all_column_data + unset($first_json['proposal_data']['over_all_column_data'][$proposalKey]); + + if($type == 2){ + // Remove proposalKey from premium_data + unset($first_json['premium_data']['data'][$proposalKey]); + } + } + + // Insurer Check: Remove subHeaders and relevant data for insurers with qcr == 0 + foreach ($proposalData['insurers'] as $insurerIndex => $insurer) { + if (($insurer['qcr'] === 0 || $insurer['qcr'] === false) || ($insurer['stc'] === 0 || $insurer['stc'] === false) ) { + foreach ($first_json['table_data']['headers'] as &$header) { + if (isset($header['subHeaders'])) { + $header['subHeaders'] = array_values(array_filter($header['subHeaders'], function ($sub) use ($insurer) { + return $sub !== $insurer['display_name']; + })); + } + } + + + foreach ($first_json['table_data']['data'] as &$item) { + $item['data'] = array_values(array_filter($item['data'], function ($entry) use ($insurer) { + return $entry['subth'] !== $insurer['display_name']; + })); + } + + // Remove insurer from proposal's insurers array + unset($first_json['proposal_data']['over_all_column_data'][$proposalKey]['insurers'][$insurerIndex]); + + if($type == 2){ + unset($first_json['premium_data']['data'][$proposalKey][$insurer['display_name']]); + } } } } - } - - // Row-wise Check: Remove rows if qcr == 0 for actions - foreach ($first_json['table_data']['data'] as $rowKey => $rowData) { - foreach ($rowData['data'] as $data) { - if ($data['parentth'] === "Action" && isset($data['input_value']['stc']) && $data['input_value']['stc'] == 0) { - unset($first_json['table_data']['data'][$rowKey]); - break; + + // Row-wise Check: Remove rows if qcr == 0 for actions + foreach ($first_json['table_data']['data'] as $rowKey => $rowData) { + foreach ($rowData['data'] as $data) { + if ($data['parentth'] === "Action" && (isset($data['input_value']['qcr']) && $data['input_value']['qcr'] == 0) || (isset($data['input_value']['stc']) && $data['input_value']['stc'] == 0)) { + unset($first_json['table_data']['data'][$rowKey]); + break; + } } } + + // Reindex arrays to maintain proper structure + $first_json['table_data']['headers'] = array_values($first_json['table_data']['headers']); + $first_json['table_data']['data'] = array_values($first_json['table_data']['data']); + $first_json['proposal_data']['over_all_column_data'] = array_map(function ($proposal) { + $proposal['insurers'] = array_values($proposal['insurers']); + return $proposal; + }, $first_json['proposal_data']['over_all_column_data']); + + }else{ + + //remove insurer as Subheaders for RFQ + foreach ($first_json['table_data']['headers'] as &$header) { + $header['subHeaders'] = array_filter($header['subHeaders'], function ($subHeader) { + return in_array($subHeader, ['Quote Asked', '-']); + }); + } + + //Remove insurer Row wise data for RFQ + foreach ($first_json['table_data']['data'] as &$row) { + + // Filter the inner data array + $row['data'] = array_filter( + $row['data'], + function ($item) { + return in_array($item['subth'], ['Quote Asked', '-']); + } + ); + + $row['data'] = array_values($row['data']); + } + + // Ensure to unset the reference after the loop + unset($row); + + + // Remove insurers from Proposal Data key for RFQ + foreach ($first_json['proposal_data']['over_all_column_data'] as $key => &$proposal) { + if (isset($proposal['insurers'])) { + // Set the insurers array to empty + $proposal['insurers'] = []; + } + } + + // Ensure to reset the reference + unset($proposal); + } - - // Reindex arrays to maintain proper structure - $first_json['table_data']['headers'] = array_values($first_json['table_data']['headers']); - $first_json['table_data']['data'] = array_values($first_json['table_data']['data']); - $first_json['proposal_data']['over_all_column_data'] = array_map(function ($proposal) { - $proposal['insurers'] = array_values($proposal['insurers']); - return $proposal; - }, $first_json['proposal_data']['over_all_column_data']); - + return $first_json; } - + return null; } - + //----- Featch Lead data and insert Client ------------------------------------------------------------------------------------------- public function featchLeadDataAndInsertClient($lead_id) { $data = $this->leadsModel->where('leads.id', $lead_id)->where('leads.is_active', 1)->first(); - + if (!$data) { return $this->respond(['status' => false, 'message' => 'Failed to create Client', 'data' => null], 200); } - + $result = $this->createClientWithLeadData($data); - + if ($result) { $policy_data = $this->clientPolicyModel->where('client_id', $result)->where('is_active', 1)->first(); return $this->respond(['status' => true, 'message' => 'New Client created successfully', 'client_id' => $result, 'data' => $data, 'client_policy_id' => $policy_data['id']], 200); } - + return $this->respond(['status' => false, 'message' => 'Failed to create client', 'data' => $data], 200); } @@ -1061,7 +1813,7 @@ class LeadsController extends BaseController return $client_id; } - + private function prepareClientData($data) { return [ @@ -1073,27 +1825,27 @@ class LeadsController extends BaseController 'pan' => $data['pan'], ]; } - + public function createClientBranchAndContactWithLeadData($data, $client_id) { $branch_data = $this->prepareClientBranchData($data, $client_id); $branch_id = $this->clientBranchModel->insert($branch_data); - + if ($branch_id) { $this->leadsModel->where('id', $data['id'])->set('is_client_created', $client_id)->update(); $contact_data = $this->prepareContactData($data, $branch_id); $this->levelContactModel->insert($contact_data); - + $this->createClientPolicyWithLeadData($data, $client_id, $branch_id); } - + return $branch_id; } - + private function prepareClientBranchData($data, $client_id) { $default_unit = trim(($data['client_short_name'] ?? '') . '-' . ($data['branch_code'] ?? ''), '-'); - + return [ 'client_id' => $client_id, 'branch_name' => $data['branch_name'], @@ -1102,7 +1854,7 @@ class LeadsController extends BaseController 'units' => json_encode([$default_unit]), ]; } - + private function prepareContactData($data, $branch_id) { return [ @@ -1113,22 +1865,22 @@ class LeadsController extends BaseController 'ref_id' => $branch_id, ]; } - + public function createClientPolicyWithLeadData($data, $client_id, $branch_id) { $client_policy_data = $this->prepareClientPolicyData($data, $client_id, $branch_id); $client_policy_id = $this->clientPolicyModel->insert($client_policy_data); - if($client_policy_id){ + if ($client_policy_id) { $this->leadsModel->where('id', $data['id'])->set('is_client_created', $client_id)->update(); } return $client_policy_id; } - + private function prepareClientPolicyData($data, $client_id, $branch_id) - { + { $proposel_data = json_decode($data['proposel_data'], true); // print_r($proposel_data); die; list($insurer_branch_id, $insurer_id) = explode('-', $proposel_data['insurer'], 2); @@ -1147,7 +1899,7 @@ class LeadsController extends BaseController ]; $terms = $this->preparePolicyTermsFromRFQ($data); - + $policy_type_id = $data['policy_type_id']; if (in_array($policy_type_id, [1, 2, 6, 7])) { $client_policy_data['is_addon'] = 1; // Base Policy @@ -1157,61 +1909,114 @@ class LeadsController extends BaseController // if ($base_policy) { // $data['is_addon'] = 3; // Dependent Addon // } else { - $data['is_addon'] = 1; + $data['is_addon'] = 1; // } } $client_policy_data['policy_terms'] = $this->preparePolicyTermsFromRFQ($data); // print_r($client_policy_data); die; - + return $client_policy_data; } - + private function preparePolicyTermsFromRFQ($data) - { + { $proposel_data = json_decode($data['proposel_data'], true); $QCRData = $this->RFQModel->where('is_active', 1)->where('type', 2)->where('lead_id', $data['id'])->first(); - + $JSON = json_decode($QCRData['json'], true); - $converted_json = $this->transformProposelData($JSON, $proposel_data['proposel_name'], $proposel_data['insurer_name']); - + $converted_json = $this->transformProposelData($JSON, $proposel_data['proposel_name'], $proposel_data['insurer_name']); + return $this->convertQCRJsonToPolicyTerms($converted_json, $data['policy_type_id'], $proposel_data['proposel_name'], $proposel_data['insurer_name']); } private function convertQCRJsonToPolicyTerms($data, $policy_type, $proposel_name, $insurer_name) { $GMC_Keys = [ - "sum_insured", "family_floater", "family_floaters", "age_ratio", "waiverofpreexistingdiseases", - "maternitycoverage", "twindelivery", "preandpostnatal", "babyday1cover", "9monthwaitingperiodwaived", - "coverfromthedateofjoining", "waiverof1,2,3&4thyearexclusions", "waiverof30dayswaitingperiod", - "prehospitalizationcover", "congenitaldiseasesinternal", "copayzonewisecopay", - "bioabsorbablestenttoriclensmultifocallens", "roomrentlimit", "proportionatedeductionclause", - "ailmentcapping", "ambulancecharges", "airambulance", "familytransportationbenefit", - "reasonableandcustomarycharges", "ayudhtreatmentcover", "congenitaldiseasesexternal", - "optionalparentalcopay", "posthospitalizationcover", "corporatebuffer", "sublimitofcorporatebuffer", - "ayushTreatmentCoverData", "armdcovered", "suminsuredenhancement", "automaticsuminsuredreinstatement", - "additionalsicknessbenefit", "lasiksurgery", "midterminclusion", "capd", "organdonorexpenses", - "moderntreatmentsasperirdai", "Wellness", "days_of_discharge", "days_from_dod", - "special_condition_label", "special_condition_input", "multiple_sum_insured", - "cataract", "cataractData" + "sum_insured", + "family_floater", + "family_floaters", + "age_ratio", + "waiverofpreexistingdiseases", + "maternitycoverage", + "twindelivery", + "preandpostnatal", + "babyday1cover", + "9monthwaitingperiodwaived", + "coverfromthedateofjoining", + "waiverof1,2,3&4thyearexclusions", + "waiverof30dayswaitingperiod", + "prehospitalizationcover", + "congenitaldiseasesinternal", + "copayzonewisecopay", + "bioabsorbablestenttoriclensmultifocallens", + "roomrentlimit", + "proportionatedeductionclause", + "ailmentcapping", + "ambulancecharges", + "airambulance", + "familytransportationbenefit", + "reasonableandcustomarycharges", + "ayudhtreatmentcover", + "congenitaldiseasesexternal", + "optionalparentalcopay", + "posthospitalizationcover", + "corporatebuffer", + "sublimitofcorporatebuffer", + "ayushTreatmentCoverData", + "armdcovered", + "suminsuredenhancement", + "automaticsuminsuredreinstatement", + "additionalsicknessbenefit", + "lasiksurgery", + "midterminclusion", + "capd", + "organdonorexpenses", + "moderntreatmentsasperirdai", + "Wellness", + "days_of_discharge", + "days_from_dod", + "special_condition_label", + "special_condition_input", + "multiple_sum_insured", + "cataract", + "cataractData" ]; - + $GPA_Keys = [ - "sumInsured2", "totalSumInsured", "age_ratio", "accidentalDeathBenefit", "permanentTotalDisablement", - "permanentPartialDisablement", "temporaryTotalDisablementBenefit", "accidentalHospitalizationExpenses", - "childrenEducationWelfareFund", "compassionateVisitExpenses", "compassionateVisitExpensesData", - "brokenBoneExpenses", "brokenBoneExpensesData", "ambulanceCharges", "ambulanceChargesData", - "burnExpenses", "burnExpensesData", "carriageOfDeadBody", "carriageOfDeadBodyData", - "animalSnakeInsectBite", "terrorism", "worldwideCover", "gpa_special_condition_label", - "gpa_special_condition_input", "multiple_sum_insured" + "sumInsured2", + "totalSumInsured", + "age_ratio", + "accidentalDeathBenefit", + "permanentTotalDisablement", + "permanentPartialDisablement", + "temporaryTotalDisablementBenefit", + "accidentalHospitalizationExpenses", + "childrenEducationWelfareFund", + "compassionateVisitExpenses", + "compassionateVisitExpensesData", + "brokenBoneExpenses", + "brokenBoneExpensesData", + "ambulanceCharges", + "ambulanceChargesData", + "burnExpenses", + "burnExpensesData", + "carriageOfDeadBody", + "carriageOfDeadBodyData", + "animalSnakeInsectBite", + "terrorism", + "worldwideCover", + "gpa_special_condition_label", + "gpa_special_condition_input", + "multiple_sum_insured" ]; - + // Select keys based on policy type $termsKey = $policy_type == 1 ? $GPA_Keys : $GMC_Keys; - + // Initialize terms_array with default empty values $terms_array = array_fill_keys($termsKey, ""); $specialKeys = ['special_condition_label', 'special_condition_input', 'gpa_special_condition_label', 'gpa_special_condition_input', 'multiple_sum_insured']; @@ -1226,37 +2031,39 @@ class LeadsController extends BaseController "child" => ["min" => 0, "max" => "25"], "elders" => ["min" => 0, "max" => 0], ] : ["self" => ["min" => "18", "max" => "60"]]; - + foreach ($data['table_data']['data'] as $dataRow) { $item = $dataRow['items'] ?? ''; - + foreach ($dataRow['data'] as $cellData) { $parentth = $cellData['parentth'] ?? ''; $subth = $cellData['subth'] ?? ''; $input_value = $cellData['input_value'] ?? ''; $value = $cellData['value'] ?? ''; - + // Skip unwanted keys - if (in_array($parentth, ['Sno', 'Item Key', 'Particulars', 'Action']) || - in_array($subth, ['Quote Asked'])) { + if ( + in_array($parentth, ['Sno', 'Item Key', 'Particulars', 'Action']) || + in_array($subth, ['Quote Asked']) + ) { continue; } - + // Handle special conditions if (str_starts_with($item, "special_condition") && $parentth === $proposel_name && $subth === $insurer_name) { - + $parts = explode("-", $input_value); $question = $parts[0] ?? ''; $answer = $parts[1] ?? ''; $labelKey = $policy_type == 1 ? 'gpa_special_condition_label' : 'special_condition_label'; $inputKey = $policy_type == 1 ? 'gpa_special_condition_input' : 'special_condition_input'; - + $terms_array[$labelKey][] = $question; $terms_array[$inputKey][] = $answer; continue; } - + // Handle sum insured if (in_array($item, ['sum_insured', 'sumInsured2'])) { $si_amt = explode(",", $value); @@ -1264,42 +2071,94 @@ class LeadsController extends BaseController $terms_array['multiple_sum_insured'] = array_slice($si_amt, 1); continue; } - + // Handle family floaters if ($item === 'family_composition') { $terms_array['family_floaters'] = isJsonString($input_value) ? json_decode($input_value, true) : $input_value; continue; } - + // Decode JSON if valid $terms_array[$item] = isJsonString($input_value) ? (json_decode($input_value, true)['key'] ?? '') : $input_value; } } - + return json_encode($terms_array); } - + public function featchClientPolicyFromLead($client_id, $branch_id, $lead_id) { $data = $this->leadsModel->where('leads.id', $lead_id)->where('leads.is_active', 1)->first(); - + if (!$data) { return $this->respond(['status' => false, 'message' => 'Failed to create policy', 'data' => null], 200); } - + $result = $this->createClientPolicyWithLeadData($data, $client_id, $branch_id); // print_r($result); die; - + if ($result) { $policy_data = $this->clientPolicyModel->where('id', $result)->where('is_active', 1)->first(); return $this->respond(['status' => true, 'message' => 'New Policy created successfully', 'client_policy_id' => $result, 'data' => $data, 'client_id' => $policy_data['client_id']], 200); } - + return $this->respond(['status' => false, 'message' => 'Failed to create policy', 'data' => $data], 200); - } -} \ No newline at end of file + //------------------------------------------------------------------------------------------------ + + + public function transformMailContent($lead_id) + { + helper('excel_util_helper'); + // $params = $this->request->getGet(); + + // print_r($params); die; + // $lead_id = $params['lead_id']; + // $file_type = $params['file_type']; //rfq or qcr + // $recipient_type = $params['recipient_type']; //insurer or client or internal or placement + // $recipient_mail = $params['recipient_mail']; // - only primary key of contacts + // $propsal_and_insurer = isset($params['proposal_insurer']) ? $params['proposal_insurer'] : null; + + // if ($recipient_type == 'insurer' && empty($recipient_mail)) { + // return $this->respond(['status' => 'failed', 'code' => 400, 'data' => '', 'messgae' => 'Recipient mail not found ! '], 200); + // } + + //gather lead info + $lead_data = $this->leadsModel + ->select('leads.*,policy_type.long_name,policy_type.policy_type,user_profiles.email as created_person_email') + ->join('policy_type', 'leads.policy_type_id = policy_type.id', 'left') + ->join('user_profiles', 'leads.created_by = user_profiles.id', 'left') + ->where('leads.id', $lead_id) + ->first(); + + // dd($lead_data); + + if($lead_data){ + + $recipient_data = ['name' => "Team"]; + $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.

'; + + $message = $original_message; + $message = str_replace("{{RECIPIENT_NAME}}", $recipient_data['name'], $message); + $message = str_replace("{{CLIENT_NAME}}", $lead_data['client_name'], $message); + $message = str_replace("{{POLICY_LONG_NAME}}", $lead_data['long_name'], $message); + $message = str_replace("{{POLICY_START_DATE}}", change_date_format($lead_data['policy_start_date'], 'Y-m-d', 'd-m-Y'), $message); + $message = str_replace("{{DURATION}}", calculate_days_bw_dates($lead_data['policy_end_date'] ?? "", $lead_data['policy_start_date'] ?? "")->days, $message) ?? '--'; + + // return $this->respond(['status' => true, 'code' => 200, 'data' => $message], 200); + return $message; + + }else{ + + // return $this->respond(['status' => false, 'code' => 404, 'message' => "This lead has not data"], 200); + return ''; + } + + + + } +} diff --git a/app/Controllers/LoginController.php b/app/Controllers/LoginController.php index 10c42716..b3ca2187 100755 --- a/app/Controllers/LoginController.php +++ b/app/Controllers/LoginController.php @@ -19,17 +19,16 @@ class LoginController extends BaseController // set_session_data($session_data); // $isLoggedIn = check_session(); $isLoggedIn = check_session(); - - if ($isLoggedIn) { + $hasCookie = check_cookie(); + if ($isLoggedIn || $hasCookie) { return redirect()->to(base_url('/dashboard/view')); } return view('login'); } - + public function receiveGoogleOAuthResponse() { - $UserModel = new UserModel(); //echo 'DONE';die(); if ($this->request->getGet('code')) { @@ -52,7 +51,10 @@ class LoginController extends BaseController 'userProfile' => $value->picture, 'user_team' => $user_team, ]; - + $path = getenv('cookie.Path'); + $domain = getenv('cookie.Domain'); + $https = getenv('ccokie.secure'); + setcookie('session_data', json_encode($session_data), time() + 12 * 60 * 60, $path, $domain, $https, true); set_session_data($session_data); log_message('error', 'Set The UserId : `'. $user->id .'` in Session'); @@ -82,12 +84,14 @@ class LoginController extends BaseController public function initiateGoogleOAuth() { - return googleOAuthLogin(false); + return googleOAuthLogin(false); } public function logout() { + $path = getenv('cookie.Path'); session()->destroy(); + setcookie('session_data', '', time() - 3600, $path); return redirect()->to(base_url('login')); } diff --git a/app/Controllers/MasterController.php b/app/Controllers/MasterController.php index 1599bac2..4b5c9032 100755 --- a/app/Controllers/MasterController.php +++ b/app/Controllers/MasterController.php @@ -30,6 +30,8 @@ use App\Models\StateModel; use App\Models\PolicyTypeModel; use App\Models\CDMasterModel; use App\Models\ClientDepositModel; +use App\Models\EmployeePolicyModel; +use App\Models\FileModel; use App\Models\InsurerExcelExportTemplateModel; use App\Models\SettingsModel; use App\Models\VehicleModel; @@ -1222,7 +1224,7 @@ class MasterController extends AdminController $data = $this->request->getPost(); $date = (string) $this->request->getPost('opening_date'); $data['opening_date'] = date('Y-m-d', strtotime($date)); - + // print_rr($data);die(); // Prepare the array with data $cd_tranction_data = [ 'amount' => $data['opening_bal'], @@ -1245,7 +1247,7 @@ class MasterController extends AdminController $insert = $this->CDMasterModel->insert($data); if ($insert) { - + $cd_tranction_data['cd_ac_pk'] = $this->CDMasterModel->insertID(); $response = DepositHelper::saveDeposit($cd_tranction_data, $loggedInUserID); session()->setFlashdata('success', "Cash Deposite Master Added Successfully"); @@ -1311,12 +1313,31 @@ class MasterController extends AdminController ->where('id', $id) ->where('is_active', 1) ->first(); + + $db = db_connect(); + $builder = $db->table('cd_master'); + $builder->select('cd_master.cd_ac_no, cd_master.id, COUNT(cash_deposit.cd_ac_no) AS cd_ac_no_count_cd_tranction'); + $builder->join('cash_deposit', 'cash_deposit.cd_ac_pk = cd_master.id'); + $builder->where('cash_deposit.is_active', 1); + $builder->where('cd_master.is_active', 1); + $builder->where('cd_master.id', $id); + $builder->groupBy('cd_master.id'); - // convert the date formate 2000-01-01 to 01-01-2000 + $query = $builder->get(); + $result = $query->getResultArray(); + + // print_r($result); die; + + $count = 0; + if(isset($result[0])){ + $count = $result[0]['cd_ac_no_count_cd_tranction']; + } + + // convert the date formate 2000-01-01 to 01-01-2000 $cd_data['opening_date'] = date('d-m-Y', strtotime($cd_data['opening_date'])); if ($cd_data) { - return $this->respond(['status' => true, 'code' => 200, 'data' => $cd_data], 200); + return $this->respond(['status' => true, 'code' => 200, 'data' => $cd_data, 'cd_transaction_count' => $count], 200); } else { return $this->respond(['status' => false, 'code' => 404], 200); } @@ -1500,25 +1521,34 @@ class MasterController extends AdminController } - public function duplicateTemplate($template_id, $event_name) + // Duplicate the insuer same policy type other events template + public function duplicateTemplate($template_id, $event_name, $insurer_id) { + // Fetch the template data based on the provided ID and ensure it is active $insurer_template_data = $this->insurerTemplateModel->where('id', $template_id) - ->where('is_active', 1) - ->first(); + ->where('is_active', 1) + ->first(); + + // Check if the event name matches the existing template's event name + $insurer_template_data_check_duplicate = $this->insurerTemplateModel + ->where('insurer_id', $insurer_id) + ->where('event_name', $event_name) + ->where('policy_type_id', $insurer_template_data['policy_type_id']) + ->where('is_active', 1) + ->findAll(); + + //if the template already exist than return the message + if (!empty($insurer_template_data_check_duplicate) && count($insurer_template_data_check_duplicate) > 0) { + return $this->respond([ + 'status' => false, + 'message' => 'Template with the same event already exists.', + 'data' => $insurer_template_data_check_duplicate + ]); + } - if ($insurer_template_data) { - - // Check if the event name matches the existing template's event name - if ($insurer_template_data['event_name'] == $event_name) { - return $this->respond([ - 'status' => false, - 'message' => 'Template with the same event already exists.', - 'data' => $insurer_template_data - ]); - } - + // Prepare data for insertion as a duplicate $data_to_insert = [ "insurer_id" => $insurer_template_data['insurer_id'], @@ -1529,28 +1559,28 @@ class MasterController extends AdminController "created_by" => get_session_user(), "is_active" => 1, ]; - + // Insert the duplicate template data $insert_result = $this->insurerTemplateModel->insert($data_to_insert); - + if ($insert_result) { return $this->respond([ - 'status' => true, - 'message' => 'Template duplicated successfully.', + 'status' => true, + 'message' => 'Template duplicated successfully.', 'data' => $insurer_template_data ]); } else { return $this->respond([ - 'status' => false, - 'message' => 'Failed to duplicate template.', + 'status' => false, + 'message' => 'Failed to duplicate template.', 'data' => $insurer_template_data ]); } } else { // No matching active template found return $this->respond([ - 'status' => false, - 'message' => 'No active template data found.', + 'status' => false, + 'message' => 'No active template data found.', 'data' => null ]); } @@ -1574,7 +1604,7 @@ class MasterController extends AdminController $to = $this->request->getPost('to'); $subject = $this->request->getPost('subject'); $mail_content = $this->request->getPost('content'); - + $common = ['mail_type'=>'test_mail_ui']; /*****CHOOSE ANY ONE AT A TIME, COMMENT ANOTHER ONE******/ /*****CALLING DIRECLT USING LIB******/ @@ -1591,7 +1621,7 @@ class MasterController extends AdminController /*****CALLING DIRECLT USING LIB******/ /*****CALLING VIA MAIL HELPER******/ - $res = MailHelper::send_email(['mail' => $to, 'subject' => $subject, 'message' => $mail_content]); + $res = MailHelper::send_email(['mail' => $to, 'subject' => $subject,'common'=>$common ,'message' => $mail_content]); return $this->respond(['status' => 'success','code' => 200,'data' => $res],200); /*****CALLING VIA MAIL HELPER******/ @@ -1623,14 +1653,42 @@ class MasterController extends AdminController ["filePath" => ROOTPATH."public/sample_excel/sample_inception.xls","fileName" => "sample_inception.xls"], ["filePath" => ROOTPATH."public/assets/images/login_bg.jpg","fileName" => "login_bg.jpg"] ]; - - + $common = ['mail_type'=>'test_mail_cli']; $email_id = CLI::getOption('to') ? CLI::getOption('to') : $email_id; - $res = MailHelper::send_email(['mail' => $email_id, 'subject' => 'Mail Via CLI', 'message' => $message,'attachments' => $attachments]); + $res = MailHelper::send_email(['mail' => $email_id, 'subject' => 'Mail Via CLI', 'message' => $message,'attachments' => $attachments,'common'=>$common]); + echo "Inside the master controller"; print_r($res); } - + + public function testZeptoSMTP() { + $message = ''; + $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"], + ["filePath" => ROOTPATH."public/assets/images/login_bg.jpg","fileName" => "login_bg.jpg"] + ]; + $email_id = 'srinivas.saravanan@venbainfotech.com'; + $common = ['mail_type'=>'test_mail_cli']; + // Send email and get response + $result = MailHelper::send_email(['mail' => $email_id, 'subject' => 'Mail Via CLI', 'message' => $message,'attachments' => $attachments,'common'=>$common]); + + + log_message('error',json_encode($result)); + // Format the response for display/debugging + $response = [ + 'success' => $result['success'] ?? false, + 'smtp_data' => [ + 'last_reply' => $result['smtp_data']['last_reply'] ?? '', + 'error_info' => $result['smtp_data']['error_info'] ?? '' + ], + 'message_id' => $result['message_id'] ?? '', + 'timestamp' => $result['timestamp'] ?? '' + ]; + + // Return JSON response + return $this->response->setJSON($result); + } public function testCheckBounceMails() { $gmailapi = \Config\Services::gmailapi(); @@ -1672,6 +1730,7 @@ class MasterController extends AdminController 'template_bg' => ROOTPATH . 'public/uploads/template_bg/', 'attachments' => WRITEPATH . 'uploads/attachments/', 'sample_import_excel' => ROOTPATH . 'public/sample_import_excel', + 'lead_files' => WRITEPATH . 'uploads/lead_files/', ]; foreach ($folders as $folderName => $folderPath) { diff --git a/app/Controllers/PolicyTransactionController.php b/app/Controllers/PolicyTransactionController.php index 452aa207..6784c0fd 100644 --- a/app/Controllers/PolicyTransactionController.php +++ b/app/Controllers/PolicyTransactionController.php @@ -31,6 +31,7 @@ use App\Models\InsurerStatements; use App\Models\InvPaymentDetailsModel; use App\Models\BatchFileModel; use App\Models\FileModel; +use App\Models\COShareStmtDetailsModel; use Kint; class PolicyTransactionController extends BaseController @@ -62,6 +63,7 @@ class PolicyTransactionController extends BaseController protected $invPaymentDetailsModel; protected $batchFileModel; protected $filesModel; + protected $coShareStmtDetailsModel; public function __construct() { @@ -91,11 +93,12 @@ class PolicyTransactionController extends BaseController $this->invPaymentDetailsModel = new InvPaymentDetailsModel(); $this->batchFileModel = new BatchFileModel(); $this->filesModel = new FileModel(); + $this->coShareStmtDetailsModel = new COShareStmtDetailsModel(); $this->invoiceStatus = [ 'pending' => 'Pending', 'generated' => 'Generated', 'sent' => 'Sent', - 'payment_received' => 'Payment Received', + 'payment_received' => 'Payment
Received', ]; } @@ -179,6 +182,7 @@ class PolicyTransactionController extends BaseController // Fetch additional data $data['client'] = $this->clientModel->where('is_active', 1)->findAll(); + $data['client_branch'] = $this->clientBranchModel->where('is_active', 1)->findAll(); $data['policy_type'] = $this->policyTypeModel->where('is_active', 1)->findAll(); $data['insurer'] = $this->insurerModel->where('is_active', 1)->findAll(); $data['entity'] = $this->kycEntityTypeModel->where('is_active', 1)->findAll(); @@ -221,6 +225,7 @@ class PolicyTransactionController extends BaseController // print_r($this->request->getPost()); die; $id = $this->request->getPost('id'); $data = $this->preparePolicyData(); + $data['cd_ac_pk'] = $this->request->getPost('cd_ac_no'); // print_r($this->request->getPost()); die; @@ -430,7 +435,7 @@ class PolicyTransactionController extends BaseController if(isset($data['follow_insurer_id'])){ foreach ($data['follow_insurer_id'] as $index => $insurer) { - + // Separate the insurer and insurer branch list($insurer_branch_id, $insurer_id) = explode('-', $insurer); @@ -473,6 +478,7 @@ class PolicyTransactionController extends BaseController 'created_by' => get_session_userid() ?? null, 'updated_by' => get_session_userid() ?? null, 'id' => $data['co_share_id'][$index] ?? null, // Assuming this is the ID to identify existing records + 'follower_policy_no' => $data['follower_policy_no'][$index] ?? null, // Assuming this is the ID to identify existing records ]; } @@ -529,7 +535,7 @@ class PolicyTransactionController extends BaseController 'created_by' => get_session_userid(), 'policy_no' => $data['policy_no'] ?? null, 'client_branch_id' => $data['client_branch_id'] ?? 0, - 'cd_ac_no' => $data['cd_ac_no'] ?? null, + 'cd_ac_pk' => $data['cd_ac_no'] ?? null, 'gst' => 18, ]; } @@ -786,10 +792,24 @@ class PolicyTransactionController extends BaseController ->findAll(); $data['pt_co_share_details'] = $this->PTCOShareDetailsModel - ->where('pt_id', $id) - ->where('is_active', 1) - ->orderBy('id', 'asc') - ->findAll(); + ->select(" + pt_co_share_details.*, + + ( + SELECT + COUNT(*) + FROM + co_share_stmt_details + WHERE + co_share_stmt_details.co_share_id = pt_co_share_details.id + AND co_share_stmt_details.is_active = 1 + ) AS record_count + ") + ->where('pt_id', $id) + ->where('is_active', 1) + ->orderBy('id', 'asc') + ->findAll(); + $data['emp_data'] = $this->employeeModel ->select('employees.*, employee_polices.id as emp_policy_id') ->join('employee_polices', 'employees.id = employee_polices.employee_id', 'left') @@ -1329,8 +1349,8 @@ class PolicyTransactionController extends BaseController //--------------------------------------------------------------------------------------------------- - //get BDS Reports data - public function reportBDS() + //get BDS Reports data old function + public function reportBDSOld() { $data['page_name'] = 'BDS Report'; @@ -1390,6 +1410,81 @@ class PolicyTransactionController extends BaseController $this->loadLayout('report_bds_filter', $data); } + //get BDS Reports data New Function + public function reportBDS() + { + + $data['page_name'] = 'BDS Report'; + + $data['issuer'] = [1 => 'JIBS', 2 => 'Nhance']; + $data['client_type'] = [1 => 'Group', 2 => 'Individual']; + $data['issuing_type'] = [1 => 'Fresh', 2 => 'Renewal', 3 => 'Roll Over']; + $data['policy_status'] = [ + 'pending' => 'Pending', + 'exported_to_insurer' => 'Exported to Insurer', + 'imported_from_insurer' => 'Imported from Insurer', + 'exported_to_tpa' => 'Exported to TPA', + 'imported_from_tpa' => 'Imported from TPA', + 'completed' => 'Completed' + ]; + $data['invoice_status_array'] = [ + 'yet_to_generate' => 'Yet to Generate', + 'generated' => 'Generated', + 'send' => 'Send', + 'recived' => 'Recived', + ]; + $data['date_type'] = [ + 'policy_issue_date' => 'Policy Issue Date', + 'policy_start_date' => 'Policy Start Date', + 'policy_end_date' => 'Policy End Date', + 'data_received_date' => 'Data Received Date', + 'closure_date' => 'Closure Date', + 'statement_month' => 'Statement Month', + ]; + + $data['insurer'] = $this->insurerModel->where('is_active', 1)->findAll(); + $data['policy_types'] = $this->policyTypeModel->where('is_active', 1)->findAll(); + $data['clients'] = $this->clientModel->where('is_active', 1)->findAll(); + + //filter datas + $start_date = $this->request->getGet('start_date'); + $end_date = $this->request->getGet('end_date'); + $client_id = $this->request->getGet('client_id'); + $insurer_id = $this->request->getGet('insurer_id'); + $policy_type_id = $this->request->getGet('policy_type_id'); + $date_type = $this->request->getGet('date_type'); + $issuer = $this->request->getGet('issuer'); + $client_branch_id = $this->request->getGet('client_branch_id'); + $insurer_branch_id = $this->request->getGet('insurer_branch_id'); + $client_policy_id = $this->request->getGet('client_policy_id'); + + if($date_type == 'statement_month'){ + $start_date = (string)date('Y-m-01', strtotime($start_date)); + $end_date = (string)date('Y-m-31', strtotime($end_date)); + } + + // dd($start_date, $end_date, $date_type); + + $start_date = (!isset($start_date) || $start_date === '' || $start_date === null) ? 0 : $start_date; + $end_date = (!isset($end_date) || $end_date === '' || $end_date === null) ? 0 : $end_date; + + $client_id = (!isset($client_id) || $client_id === '' || $client_id === null) ? 0 : $client_id; + $insurer_id = (!isset($insurer_id) || $insurer_id === '' || $insurer_id === null) ? 0 : $insurer_id; + $policy_type_id = (!isset($policy_type_id) || $policy_type_id === '' || $policy_type_id === null) ? 0 : $policy_type_id; + $date_type = (!isset($date_type) || $date_type === '' || $date_type === null) ? 0 : $date_type; + $issuer = (!isset($issuer) || $issuer === '' || $issuer === null) ? 0 : $issuer; + $client_branch_id = (!isset($client_branch_id) || $client_branch_id === '' || $client_branch_id === null) ? 0 : $client_branch_id; + $insurer_branch_id = (!isset($insurer_branch_id) || $insurer_branch_id === '' || $insurer_branch_id === null) ? 0 : $insurer_branch_id; + $client_policy_id = (!isset($client_policy_id) || $client_policy_id === '' || $client_policy_id === null) ? 0 : $client_policy_id; + + + //Actual data for the list + $data['report_list'] = $this->policyTransactionModel->getBDSReportList($start_date, $end_date, $client_id, $insurer_id, $policy_type_id, $date_type, $issuer, $client_branch_id, $insurer_branch_id, $client_policy_id); + // dd($data['report_list']); + + $this->loadLayout('report_bds_filter', $data); + } + public function reportVarience() { $data['page_name'] = 'Variance Report'; @@ -1414,6 +1509,10 @@ class PolicyTransactionController extends BaseController $policy_type_id = $this->request->getGet('policy_type_id'); $date_type = $this->request->getGet('date_type'); $issuer = $this->request->getGet('issuer'); + $client_branch_id = $this->request->getGet('client_branch_id'); + $insurer_branch_id = $this->request->getGet('insurer_branch_id'); + $client_policy_id = $this->request->getGet('client_policy_id'); + $start_date = (!isset($start_date) || $start_date === '' || $start_date === null) ? 0 : $start_date; $end_date = (!isset($end_date) || $end_date === '' || $end_date === null) ? 0 : $end_date; @@ -1424,7 +1523,12 @@ class PolicyTransactionController extends BaseController $date_type = (!isset($date_type) || $date_type === '' || $date_type === null) ? 0 : $date_type; $issuer = (!isset($issuer) || $issuer === '' || $issuer === null) ? 0 : $issuer; - $data['varience_list'] = $this->policyTransactionModel->getVarienceReportLIst($start_date, $end_date, $client_id, $insurer_id, $policy_type_id, $date_type, $issuer); + $client_branch_id = (!isset($client_branch_id) || $client_branch_id === '' || $client_branch_id === null) ? 0 : $client_branch_id; + $insurer_branch_id = (!isset($insurer_branch_id) || $insurer_branch_id === '' || $insurer_branch_id === null) ? 0 : $insurer_branch_id; + $client_policy_id = (!isset($client_policy_id) || $client_policy_id === '' || $client_policy_id === null) ? 0 : $client_policy_id; + + + $data['varience_list'] = $this->policyTransactionModel->getVarienceReportLIst($start_date, $end_date, $client_id, $insurer_id, $policy_type_id, $date_type, $issuer, $client_branch_id, $insurer_branch_id, $client_policy_id); $this->loadLayout('variance_report_list', $data); } @@ -1531,20 +1635,17 @@ class PolicyTransactionController extends BaseController $end_date = $this->request->getGet('end_date'); $client_id = $this->request->getGet('client_id'); $insurer_id = $this->request->getGet('insurer_id'); - $policy_type_id = $this->request->getGet('policy_type_id'); - $date_type = $this->request->getGet('date_type'); - $issuer = $this->request->getGet('issuer'); + $insurer_branch_id = $this->request->getGet('insurer_branch_id'); + + $start_date = (!isset($start_date) || $start_date === '' || $start_date === null) ? 0 : change_date_format($start_date,'d-m-Y','Y-m-01'); + $end_date = (!isset($end_date) || $end_date === '' || $end_date === null) ? 0 : change_date_format($end_date,'d-m-Y','Y-m-31'); + // dd([$start_date,$end_date]); - $start_date = (!isset($start_date) || $start_date === '' || $start_date === null) ? 0 : $start_date; - $end_date = (!isset($end_date) || $end_date === '' || $end_date === null) ? 0 : $end_date; - $client_id = (!isset($client_id) || $client_id === '' || $client_id === null) ? 0 : $client_id; $insurer_id = (!isset($insurer_id) || $insurer_id === '' || $insurer_id === null) ? 0 : $insurer_id; - $policy_type_id = (!isset($policy_type_id) || $policy_type_id === '' || $policy_type_id === null) ? 0 : $policy_type_id; - $date_type = (!isset($date_type) || $date_type === '' || $date_type === null) ? 0 : $date_type; - $issuer = (!isset($issuer) || $issuer === '' || $issuer === null) ? 0 : $issuer; + $insurer_branch_id = (!isset($insurer_branch_id) || $insurer_branch_id === '' || $insurer_branch_id === null) ? 0 : $insurer_branch_id; - $data['outstanting_list'] = $this->policyTransactionModel->getOutstandingReportLIst($start_date, $end_date, $client_id, $insurer_id, $policy_type_id, $date_type, $issuer); + $data['outstanting_list'] = $this->policyTransactionModel->getOutstandingReportLIst($start_date, $end_date,$insurer_id, $insurer_branch_id); // dd($this->policyTransactionModel->getLastQuery()); // dd($data); $this->loadLayout('outstanding_report_list', $data); @@ -1576,7 +1677,7 @@ class PolicyTransactionController extends BaseController WHERE pt_co_share_details.is_active = 1 AND pt_co_share_details.statement_id = insurer_statements.id ) AS exp_inv_amt, - (SELECT SUM(inv_payment_details.inv_amt) + SUM(inv_payment_details.tds) + (SELECT SUM(inv_payment_details.inv_amt) + SUM(inv_payment_details.tds) + SUM(inv_payment_details.gst) FROM inv_payment_details WHERE inv_payment_details.is_active = 1 AND inv_payment_details.statement_id = insurer_statements.id @@ -1649,9 +1750,10 @@ class PolicyTransactionController extends BaseController $month = $month.'-01'; // print_r($month);die; $month = change_date_format($month,'Y-M-d','Y-m-d'); + $stmt_sno = $this->request->getPost('statement_no'); // print_r($month);die; - $file_id = $this->insurerStatements->insert(['insurer_id' => $insurer_id, 'branch_id' => $branch_id, 'file_name' => $filename,'month' => $month, 'created_by' => $loggedInUserID]); //here field policy_id have client_policy_id and not policy id from policy master + $file_id = $this->insurerStatements->insert(['insurer_id' => $insurer_id, 'branch_id' => $branch_id, 'file_name' => $filename,'month' => $month, 'created_by' => $loggedInUserID,'stmt_sno' => $stmt_sno]); //here field policy_id have client_policy_id and not policy id from policy master $this->myLogger->logme("error", '{file_id} statement uploaded success', ['file_id' => $file_id]); //validate file @@ -1739,47 +1841,52 @@ class PolicyTransactionController extends BaseController unset($excel_data[0]); // Kint::dump($excel_data); //get no of line items and update in DB - $line_items = count($excel_data); + $line_items = 0; // get uploaded month transactions data - $source_data = $this->PTCOShareDetailsModel->getNonReconcileredPolicyTransactions(month:$month,year:$year,insurer_id:$file['insurer_id'],insurer_branch_id:$file['branch_id']); + $source_data = $this->PTCOShareDetailsModel->getNonReconcileredPolicyTransactions(insurer_id:$file['insurer_id'],insurer_branch_id:$file['branch_id']); // var_dump($source_data);die(); // Kint::dump($source_data);//die(); + // check policy no,insurer and etc in DB for this month // if all good return true, otherwise return false with messssage foreach ($excel_data as $excel_key => $excel_row) { $is_row_empty = check_row_is_empty_or_null($excel_row); - if($is_row_empty) + if(!$is_row_empty) { - continue; - } + $is_source_found = 0; + $policy_start_date = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[4]);//policy_start_date from excel + $policy_end_date = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[5]);//policy_end_date from excel + $policy_no = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[1]);//policy_end_date from excel + $client_name = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[3]);//clientname from excel + $endorsement_no = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[2]);//policy_end_date from excel - $is_source_found = 0; - $policy_start_date = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[4]);//policy_start_date from excel - $policy_end_date = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[5]);//policy_end_date from excel - $policy_no = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[1]);//policy_end_date from excel - $client_name = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[3]);//clientname from excel - $endorsement_no = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[2]);//policy_end_date from excel - - foreach ($source_data as $source_key => $source_row) - { - if( ($policy_no == $source_row['policy_no']) && $endorsement_no == $source_row['endorsement_no'] && change_date_format($policy_start_date,'d/m/Y','Y-m-d') == $source_row['policy_start_date'] && change_date_format($policy_end_date,'d/m/Y','Y-m-d') == $source_row['policy_end_date'] && $client_name == $source_row['client_name']) + foreach ($source_data as $source_key => $source_row) { - $is_source_found = 1; - unset($source_data[$source_key]); - continue 2; + $source_endorsement_no = $source_row['endorsement_no'] !== null ? $source_row['endorsement_no'] : ""; + if( ($policy_no == $source_row['policy_no']) && $endorsement_no == $source_endorsement_no && change_date_format($policy_start_date,'d-m-Y','Y-m-d') == $source_row['policy_start_date'] && change_date_format($policy_end_date,'d-m-Y','Y-m-d') == $source_row['policy_end_date'] && $client_name == $source_row['client_name']) + { + $is_source_found = 1; + $line_items = $line_items + 1; + unset($source_data[$source_key]); + continue 2; + } + } + + if($is_source_found == 0) + { + // echo $excel_key.'-'.$excel_row[1] . '- not found
'; + $error_data['error_code'] = 1;//match not found + // $error_data['error_data'] = ($error_data['error_data'] ?? []); + $error_data['error_data'] = array_merge($error_data['error_data'],[$excel_row[0]]);//match not found } - } - if($is_source_found == 0) - { - // echo $excel_key.'-'.$excel_row[1] . '- not found
'; - $error_data['error_code'] = 1;//match not found - // $error_data['error_data'] = ($error_data['error_data'] ?? []); - $error_data['error_data'] = array_merge($error_data['error_data'],[$excel_row[0]]);//match not found } } + + // dd($error_data); + if($error_data['error_code']) { $status = 'failed'; @@ -1793,6 +1900,7 @@ class PolicyTransactionController extends BaseController public function updateInsurerStatement($params) { + helper('excel_util_helper'); //get file info $file_id = $params['file_id']; $file = $this->insurerStatements->find($file_id); @@ -1837,7 +1945,7 @@ class PolicyTransactionController extends BaseController //get no of line items and update in DB $line_items = count($excel_data); // get uploaded month transactions data - $source_data = $this->PTCOShareDetailsModel->getNonReconcileredPolicyTransactions(month:$month,year:$year,insurer_id:$file['insurer_id'],insurer_branch_id:$file['branch_id']); + $source_data = $this->PTCOShareDetailsModel->getNonReconcileredPolicyTransactions(insurer_id:$file['insurer_id'],insurer_branch_id:$file['branch_id']); // Kint::dump($source_data);die; // Kint::dump($excel_data); @@ -1846,92 +1954,100 @@ class PolicyTransactionController extends BaseController $data_to_update = []; foreach ($excel_data as $excel_key => $excel_row) { - $is_source_found = 0; - $policy_start_date = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[4]);//policy_start_date from excel - $policy_end_date = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[5]);//policy_end_date from excel - $policy_no = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[1]);//policy_end_date from excel - $client_name = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[3]);//clientname from excel - $endorsement_no = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[2]);//policy_end_date from excel - - foreach ($source_data as $source_key => $source_row) + $is_row_empty = check_row_is_empty_or_null($excel_row); + if(!$is_row_empty) { - // Kint::dump(change_date_format($excel_row[3],'d/m/Y','Y-m-d')); - if( ($policy_no == $source_row['policy_no']) && $endorsement_no == $source_row['endorsement_no'] && change_date_format($policy_start_date,'d/m/Y','Y-m-d') == $source_row['policy_start_date'] && change_date_format($policy_end_date,'d/m/Y','Y-m-d') == $source_row['policy_end_date'] && $client_name == $source_row['client_name']) + + $is_source_found = 0; + $policy_start_date = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[4]);//policy_start_date from excel + $policy_end_date = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[5]);//policy_end_date from excel + $policy_no = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[1]);//policy_end_date from excel + $client_name = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[3]);//clientname from excel + $endorsement_no = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[2]);//policy_end_date from excel + + foreach ($source_data as $source_key => $source_row) { - $is_source_found = 1; - - //calculate percentage first - $total_amt = 0; - - $actual_bp_per = trim($excel_row[9]); - $actual_bp_brokerage = trim($excel_row[12]); - $actual_bp_amt = trim($excel_row[6]); - - if(($actual_bp_brokerage && $actual_bp_brokerage != 0 && $actual_bp_brokerage != "")) + // Kint::dump(change_date_format($excel_row[3],'d-m-Y','Y-m-d')); + $source_endorsement_no = $source_row['endorsement_no'] !== null ? $source_row['endorsement_no'] : ""; + if( ($policy_no == $source_row['policy_no']) && $endorsement_no == $source_endorsement_no && change_date_format($policy_start_date,'d-m-Y','Y-m-d') == $source_row['policy_start_date'] && change_date_format($policy_end_date,'d-m-Y','Y-m-d') == $source_row['policy_end_date'] && $client_name == $source_row['client_name']) { - $total_amt += $actual_bp_brokerage; - //percentage reverse calculation - if($actual_bp_per == 0 || $actual_bp_per == "") + $is_source_found = 1; + + //calculate percentage first + $total_amt = 0; + + $actual_bp_per = trim($excel_row[9]); + $actual_bp_brokerage = trim($excel_row[12]); + $actual_bp_amt = trim($excel_row[6]); + + if(($actual_bp_brokerage && $actual_bp_brokerage != 0 && $actual_bp_brokerage != "")) { - $actual_bp_per = round(($actual_bp_brokerage / $actual_bp_amt) * 100,2); + $total_amt += $actual_bp_brokerage; + //percentage reverse calculation + if($actual_bp_per == 0 || $actual_bp_per == "") + { + $actual_bp_per = round(($actual_bp_brokerage / $actual_bp_amt) * 100,2); + } + } - - } - else - { - $actual_bp_brokerage = $actual_bp_amt * ($actual_bp_per / 100); - $total_amt += $actual_bp_brokerage; - } - - $actual_tp_per = trim($excel_row[10]); - $actual_tp_brokerage = trim($excel_row[13]); - $actual_tp_amt = trim($excel_row[7]); - - if($actual_tp_brokerage && $actual_tp_brokerage != 0 && $actual_tp_brokerage != "") - { - $total_amt += $actual_tp_brokerage; - //percentage reverse calculation - if($actual_tp_per == 0 || $actual_tp_per == "") + else { - $actual_tp_per = ($actual_tp_brokerage / $actual_tp_amt) * 100; + $actual_bp_brokerage = $actual_bp_amt * ($actual_bp_per / 100); + $total_amt += $actual_bp_brokerage; } - } - else - { - $actual_tp_brokerage = $actual_tp_amt * ($actual_tp_per / 100); - $total_amt += $actual_tp_brokerage; - } - $actual_tep_per = trim($excel_row[11]); - $actual_tep_brokerage = trim($excel_row[14]); - $actual_tep_amt = trim($excel_row[8]); + $actual_tp_per = trim($excel_row[10]); + $actual_tp_brokerage = trim($excel_row[13]); + $actual_tp_amt = trim($excel_row[7]); - if($actual_tep_brokerage && $actual_tep_brokerage != 0 && $actual_tep_brokerage != "") - { - $total_amt += $actual_tep_brokerage; - //percentage reverse calculation - if($actual_tep_per == 0 || $actual_tep_per == "") + if($actual_tp_brokerage && $actual_tp_brokerage != 0 && $actual_tp_brokerage != "") { - $actual_tep_per = ($actual_tep_brokerage / $actual_tep_amt) * 100; + $total_amt += $actual_tp_brokerage; + //percentage reverse calculation + if($actual_tp_per == 0 || $actual_tp_per == "") + { + $actual_tp_per = ($actual_tp_brokerage / $actual_tp_amt) * 100; + } } + else + { + $actual_tp_brokerage = $actual_tp_amt * ($actual_tp_per / 100); + $total_amt += $actual_tp_brokerage; + } + + $actual_tep_per = trim($excel_row[11]); + $actual_tep_brokerage = trim($excel_row[14]); + $actual_tep_amt = trim($excel_row[8]); + + if($actual_tep_brokerage && $actual_tep_brokerage != 0 && $actual_tep_brokerage != "") + { + $total_amt += $actual_tep_brokerage; + //percentage reverse calculation + if($actual_tep_per == 0 || $actual_tep_per == "") + { + $actual_tep_per = ($actual_tep_brokerage / $actual_tep_amt) * 100; + } + } + else + { + $actual_tep_brokerage = $actual_tep_amt * ($actual_tep_per / 100); + $total_amt += $actual_tep_brokerage; + } + + //find variance + $variance_amt = $source_row['exp_amt'] - $total_amt; + + $data_to_update[] = ['co_share_id' => $source_row['id'],'actual_bp_amt' => $actual_bp_amt,'actual_tp_amt' => $actual_tp_amt,'actual_tep_amt' => $actual_tep_amt,'actual_bp_per' => $actual_bp_per,'actual_tp_per' => $actual_tp_per,'actual_tep_per' => $actual_tep_per,'variance' => $variance_amt,'actual_tep_brokerage_amt' => $actual_tep_brokerage,'actual_tp_brokerage_amt' => $actual_tp_brokerage,'actual_bp_brokerage_amt' => $actual_bp_brokerage,'reward' => trim($excel_row[15]),'statement_id' => $file_id]; + + unset($source_data[$source_key]); + continue 2; } - else - { - $actual_tep_brokerage = $actual_tep_amt * ($actual_tep_per / 100); - $total_amt += $actual_tep_brokerage; - } - - //find variance - $variance_amt = $source_row['exp_amt'] - $total_amt; - - $data_to_update[] = ['id' => $source_row['id'],'actual_bp_amt' => $actual_bp_amt,'actual_tp_amt' => $actual_tp_amt,'actual_tep_amt' => $actual_tep_amt,'actual_bp_per' => $actual_bp_per,'actual_tp_per' => $actual_tp_per,'actual_tep_per' => $actual_tep_per,'variance' => $variance_amt,'actual_tep_brokerage_amt' => $actual_tep_brokerage,'actual_tp_brokerage_amt' => $actual_tp_brokerage,'actual_bp_brokerage_amt' => $actual_bp_brokerage,'reward' => trim($excel_row[15]),'statement_id' => $file_id]; - - unset($source_data[$source_key]); - continue 2; } + } } - $this->PTCOShareDetailsModel->updateBatch($data_to_update, 'id'); + // dd($data_to_update); + $this->coShareStmtDetailsModel->insertBatch($data_to_update, 'id'); // dd($data_to_update); // if($error_data['error_code']) // { @@ -1953,8 +2069,24 @@ class PolicyTransactionController extends BaseController ->where('is_active',1) ->get() ->getResultArray(); + if(!$inv_details['invoice_value']) + { + $stmt_level_value = $this->coShareStmtDetailsModel->select('sum(actual_tep_brokerage_amt) + sum(actual_tp_brokerage_amt) + sum(actual_bp_brokerage_amt) + sum(reward) as invoice_value') + ->where('statement_id',$statement_id) + ->groupBy('statement_id') + ->get() + ->getResultArray(); + // print_r($stmt_level_value); + if($stmt_level_value && count($stmt_level_value) && isset($stmt_level_value[0])) + { + $inv_details['invoice_value'] = $stmt_level_value[0]['invoice_value']; + } + } // ~dd($inv_details); $data = [ 'invoice_status' => $inv_details['invoice_status'], + 'gst_per' => isset($inv_details['gst_per']) ? $inv_details['gst_per'] : 18 , + 'invoice_value' => $inv_details['invoice_value'], + 'gst_value' => $inv_details['gst_value'], 'invoice_no' => $inv_details['invoice_no'], 'invoice_amount' => $inv_details['invoice_amount'], 'invoice_date' => isset($inv_details['invoice_date']) ? change_date_format($inv_details['invoice_date'],'Y-m-d','d/m/Y') : null ]; @@ -1976,6 +2108,9 @@ class PolicyTransactionController extends BaseController $invoiceNo = $jsonData['invoice_no']; $invoiceDate = change_date_format($jsonData['invoice_date'],'d/m/Y','Y-m-d'); $invoice_amount = $jsonData['invoice_amount']; + $invoice_value = $jsonData['invoice_value']; + $gst_per = $jsonData['invoice_gst_per']; + $gst_value = $jsonData['invoice_gst']; //Update statement table $parentData = [ @@ -1983,6 +2118,9 @@ class PolicyTransactionController extends BaseController 'invoice_no' => $invoiceNo, 'invoice_date' => $invoiceDate, 'invoice_amount' => $invoice_amount, + 'gst_per' => $gst_per, + 'gst_value' => $gst_value, + 'invoice_value' => $invoice_value, 'updated_by' => get_session_userid() ]; @@ -1994,6 +2132,7 @@ class PolicyTransactionController extends BaseController $receivedAmounts = $jsonData['received_amount']; $utrNos = $jsonData['utr_no']; $tdsTotal = $jsonData['tds']; + $gstTotal = $jsonData['gst_amount']; $paymentDates = $jsonData['payment_date']; $pks = $jsonData['pk']; @@ -2001,6 +2140,7 @@ class PolicyTransactionController extends BaseController $pk = $pks[$index]; // Get the pk for the current record $utrNo = $utrNos[$index]; $tds = $tdsTotal[$index]; + $gst = $gstTotal[$index]; $paymentDate = $paymentDates[$index]; // Prepare data for insert/update @@ -2008,6 +2148,7 @@ class PolicyTransactionController extends BaseController 'inv_amt' => $receivedAmount, 'utr_no' => $utrNo, 'tds' => $tds, + 'gst' => $gst, 'received_date' => change_date_format($paymentDate,'d/m/Y','Y-m-d'), 'statement_id' => $hiddenStatementId ]; @@ -2107,5 +2248,182 @@ class PolicyTransactionController extends BaseController } + + //--------------------------------------------------------------------------------------------------- + + public function getCoShareStatementDetails($pt_id) + { + if (!$pt_id) { + return $this->respond([ + 'status' => false, + 'code' => 400, + 'message' => 'No data found' + ], 200); + } + + // Fetch data from the database + $data = db_connect()->table("co_share_stmt_details") + ->select(" + co_share_stmt_details.*, + insurer_statements.month, + insurer_statements.invoice_status, + insurer_statements.invoice_date, + insurer_statements.invoice_no, + insurer_statements.invoice_amount, + insurer_statements.stmt_sno, + (co_share_stmt_details.actual_bp_amt + co_share_stmt_details.actual_tp_amt + co_share_stmt_details.actual_tep_amt) AS sum_of_actual_amt + ") + ->join('insurer_statements', 'co_share_stmt_details.statement_id = insurer_statements.id') + ->where([ + 'co_share_stmt_details.is_active' => 1, + 'insurer_statements.is_active' => 1, + 'co_share_stmt_details.co_share_id' => $pt_id + ]) + ->get() + ->getResultArray(); + + // Check if data exists before formatting + if ($data) { + + foreach ($data as &$row) { + // Check if invoice_date is not null before formatting + $row['invoice_date'] = $row['invoice_date'] ? change_date_format($row['invoice_date'], 'Y-m-d', 'd/m/Y') : null; + + // Check if month is not null before formatting + $row['month'] = $row['month'] ? change_date_format($row['month'], 'Y-m-d', 'M-Y') : null; + } + + return $this->respond([ + 'status' => true, + 'code' => 200, + 'data' => $data + ], 200); + } else { + return $this->respond([ + 'status' => false, + 'code' => 400, + 'message' => 'No data found' + ], 200); + } + } + + public function getClientPolicyDataBasedOnClientAndInsuer() + { + + $client_id = $this->request->getGet('client_id') ?? 0; + $client_branch_id = $this->request->getGet('client_branch_id') ?? 0; + $insurer_id = $this->request->getGet('insurer_id') ?? 0; + $insurer_branch_id = $this->request->getGet('insurer_branch_id') ?? 0; + $policy_type_id = $this->request->getGet('policy_type_id') ?? 0; + + $builder = db_connect()->table("client_policy") + ->select(" + client_policy.*, + policy_type.policy_type, + ") + ->join('policy_type', 'client_policy.policy_type_id = policy_type.id') + ->where([ + 'client_policy.is_active' => 1, + ]); + + if (!empty($client_id)) { + $builder->where('client_policy.client_id', $client_id); + } + if (!empty($client_branch_id)) { + $builder->where('client_policy.client_branch_id', $client_branch_id); + } + if (!empty($insurer_id)) { + $builder->where('client_policy.insurer_id', $insurer_id); + } + if (!empty($insurer_branch_id)) { + $builder->where('client_policy.insurer_branch_id', $insurer_branch_id); + } + if (!empty($policy_type_id)) { + $builder->where('client_policy.policy_type_id', $policy_type_id); + } + + $result = $builder->get()->getResultArray(); + + if ($result) { + return $this->respond(['status' => true,'code' => 200,'data' => $result, 'getData' => $this->request->getGet()], 200); + } else { + return $this->respond(['status' => false,'code' => 400,'message' => 'No data found'], 200); + } + } + + public function checkCDAmountForBasePremium() + { + $base_premium = $this->request->getGet('base_premium') ?? 0; + $cd_ac_no = $this->request->getGet('cd_ac_no') ?? 0; + + // Validate inputs + if (empty($cd_ac_no)) { + return $this->respond(['status' => false, 'code' => 400, 'message' => 'CD Account Number is required'], 200); + } + + // Build query + $db = db_connect(); + $builder = $db->table("cash_deposit") + ->where('cd_ac_no', $cd_ac_no) + ->where('is_active', 1) + ->orderBy('id', 'desc') + ->limit(1); + + $result = $builder->get()->getRowArray(); + + if ($result) { + // Check if base premium exceeds balance + $base_premium_greater_than_balance = $base_premium > $result['balance']; + + return $this->respond([ + 'status' => true, + 'code' => 200, + 'data' => $result, + 'base_premium_greater_than_balance' => $base_premium_greater_than_balance, + ], 200); + } + + return $this->respond(['status' => false, 'code' => 400, 'message' => 'No data found for this CD'], 200); + } + + public function getInsurerStatementMonth() + { + $insurer_id = $this->request->getGet('insurer_id'); + $month = $this->request->getGet('month'); + // echo $month; + $insurer_branch_id = explode('-',$insurer_id)[1]; + $insurer_id = explode('-',$insurer_id)[0]; + $month = $month.'-01'; + $month = change_date_format($month,'Y-M-d','Y-m-d'); + // echo $month; + + $res_data = $this->insurerStatements + ->where('insurer_id',$insurer_id) + ->where('branch_id',$insurer_branch_id) + ->where('month', $month) + ->where('is_active', 1) + ->where('file_status', 'success') + ->findAll(); + + return $this->respond(['dataStatus' => true, 'code' => 200,'data' => $res_data], 200); + + + } + + public function deleteStatement($id) + { + // echo $id;die(); + $this->coShareStmtDetailsModel->where('statement_id',$id) + ->set(['is_active' => 0]) + ->update(); + $this->invPaymentDetailsModel->where('statement_id',$id) + ->set(['is_active' => 0]) + ->update(); + $this->insurerStatements->where('id',$id) + ->set(['is_active' => 0]) + ->update(); + return $this->respond(['dataStatus' => true, 'code' => 200], 200); + } + } \ No newline at end of file diff --git a/app/Controllers/RestAuthenticationController.php b/app/Controllers/RestAuthenticationController.php index bed2e473..56c65ff8 100755 --- a/app/Controllers/RestAuthenticationController.php +++ b/app/Controllers/RestAuthenticationController.php @@ -4,7 +4,7 @@ namespace App\Controllers; - +use App\Helpers\MailHelper; use App\Controllers\LoginController; use App\Helpers\DepositHelper; use App\Helpers\JWTToken; @@ -73,7 +73,9 @@ class RestAuthenticationController extends AdminController $employeeData = $this->employeeModel->where('mobile', $mobile_number) ->where('relationship', 'self') - ->where('is_active', 1)->first(); + ->where('emp_status !=', 'truncated') + ->where('is_active', 1) + ->first(); if ($employeeData) { @@ -88,24 +90,93 @@ class RestAuthenticationController extends AdminController return $this->respond(['status' => 'failed','code' => 500,'data' => $th],500); } } + + public function verifyEmployeeWithEmailId() + { + try { + $email = $this->request->getJSON()->email; + + + $employeeData = $this->employeeModel->where('email_corporate', $email)->where('relationship', 'self') + ->where('emp_status !=', 'truncated')->where('is_active', 1) + ->first(); + + if ($employeeData) { + + $otp = random_int(100000, 999999); + + $update = $this->employeeModel->where('email_corporate', $email)->where('relationship', 'self') + ->where('is_active', 1)->set(array('otp' => $otp )) + ->update(); + if($update) + { + + $common = [ + 'client_id' => $employeeData['client_id'], + 'client_branch_id' => $employeeData['client_branch_id'], + 'client_policy_id' => null, + 'employee_policy_id' => null, + 'employee_id' => $employeeData['id'], + 'mail_type' => 'otp_mail', + ]; + $subject = 'Nhance user verification - OTP'; + $mail_content = $otp.' is your verification code for Nhance.'; + $res = MailHelper::send_email(['mail' => $employeeData['email_corporate'], 'subject' => $subject ,'common'=>$common ,'message' => $mail_content]); + $this->myLogger->logme("info", $res); + + if(json_decode($res)->status == 'success') + { + $result = ['user_verification' => true ,'message' => "Verified Successfully"]; + return $this->respond(['status' => 'success','code' => 200,'data' => $result],200); + + }else{ + $result = ['user_verification' => false , 'message' => "Mail sending failed , try again"]; + return $this->respond(['status' => 'failed','code' => 404,'data' => $result],200); + } + + }else{ + + $result = ['user_verification' => false , 'message' => "Verification failed , try again"]; + return $this->respond(['status' => 'failed','code' => 404,'data' => $result],200); + + } + + + } else { + $result = ['user_verification' => false , 'message' => "User not found"]; + return $this->respond(['status' => 'failed','code' => 404,'data' => $result],200); + + } + } catch (\Throwable $th) { + return $this->respond(['status' => 'failed','code' => 500,'data' => $th],500); + } + } public function getVerifiedUserData() { try { - $mobile_number = $this->request->getJSON()->mobile_number; - $otp_verification = $this->request->getJSON()->otp_verification; + + $otp_verification = isset($this->request->getJSON()->otp_verification) ? $this->request->getJSON()->otp_verification : null; + $mobile_number = isset($this->request->getJSON()->mobile_number) ? $this->request->getJSON()->mobile_number : null; + + $otp = isset($this->request->getJSON()->otp) ? $this->request->getJSON()->otp : null; + $email_id = isset($this->request->getJSON()->email_id) ? $this->request->getJSON()->email_id : null; if (isset($this->request->getJSON()->login_by_hr)) { - $employeeData = $this->employeeModel->where('id', $this->request->getJSON()->employee_id)->where('relationship', 'self')->first(); + $employeeData = $this->employeeModel->where('id', $this->request->getJSON()->employee_id)->where('relationship', 'self')->where('emp_status !=', 'truncated')->where('is_active', 1)->first(); }else{ - $employeeData = $this->employeeModel->where('mobile', $mobile_number)->where('relationship', 'self')->first(); + if (isset($mobile_number)) + { + $employeeData = $this->employeeModel->where('mobile', $mobile_number)->where('relationship', 'self')->where('emp_status !=', 'truncated')->where('is_active', 1)->first(); + } else { + $employeeData = $this->employeeModel->where('email_corporate', $email_id)->where('otp', $otp)->where('relationship', 'self')->where('emp_status !=', 'truncated')->where('is_active', 1)->first(); + } } - - if ($employeeData && $otp_verification == true || $employeeData && isset($this->request->getJSON()->login_by_hr)) { + if ($employeeData && $otp_verification == true || $employeeData && isset($this->request->getJSON()->login_by_hr) || $employeeData && isset($this->request->getJSON()->otp) ) { $auth = HttpRequestHelper::getRequestInfo(); if ($auth) { $data = [ @@ -120,6 +191,11 @@ class RestAuthenticationController extends AdminController $result = JWTToken::encode($employeeData); + + if(isset($this->request->getJSON()->otp)){ + $this->employeeModel->where('email_corporate', $email_id)->where('otp', $otp)->where('relationship', 'self')->set(['otp'=>null])->update(); + } + return $this->respond(['status' => 'success','code' => 200,'data' => $result],200); } else { @@ -137,7 +213,8 @@ class RestAuthenticationController extends AdminController $HrData = $this->hrModel->where('mobile', $mobile_number) ->where('contact_type', 'client') - ->where('is_active', 1)->first(); + ->where('is_active', 1) + ->first(); if ($HrData) { @@ -214,11 +291,20 @@ class RestAuthenticationController extends AdminController public function saveMpin() { try { - $mobile_number = $this->request->getJSON()->mobile_number; + + $mobile_number = isset($this->request->getJSON()->mobile_number) ? $this->request->getJSON()->mobile_number : null; + $email_id = isset($this->request->getJSON()->email_id) ? $this->request->getJSON()->email_id : null; + + if (isset($mobile_number)) { + $employeeData = $this->employeeModel->where('mobile', $mobile_number)->where('relationship', 'self')->first(); + } else { + $employeeData = $this->employeeModel->where('email_corporate', $email_id)->where('relationship', 'self')->first(); + } + $mpin = $this->request->getJSON()->mpin; - $employeeData = $this->employeeModel->where('mobile', $mobile_number)->where('relationship', 'self')->first(); + if ($employeeData) { $id= $employeeData["id"]; @@ -245,12 +331,20 @@ class RestAuthenticationController extends AdminController public function updateMpin() { try { - $mobile_number = $this->request->getJSON()->mobile_number; + + $mobile_number = isset($this->request->getJSON()->mobile_number) ? $this->request->getJSON()->mobile_number : null; + $email_id = isset($this->request->getJSON()->email_id) ? $this->request->getJSON()->email_id : null; $old_mpin = $this->request->getJSON()->old_mpin; $mpin = $this->request->getJSON()->new_mpin; - - $employeeData = $this->employeeModel->where('mobile', $mobile_number)->where('mpin', $old_mpin)->where('relationship', 'self')->first(); + if (isset($mobile_number)) + { + $employeeData = $this->employeeModel->where('mobile', $mobile_number)->where('mpin', $old_mpin)->where('relationship', 'self')->first(); + }else{ + $employeeData = $this->employeeModel->where('email_corporate', $email_id)->where('mpin', $old_mpin)->where('relationship', 'self')->first(); + } + + if ($employeeData) { $id= $employeeData["id"]; @@ -277,10 +371,17 @@ class RestAuthenticationController extends AdminController public function verifyMpin() { try { - $mobile_number = $this->request->getJSON()->mobile_number; + + $mobile_number = isset($this->request->getJSON()->mobile_number) ? $this->request->getJSON()->mobile_number : null; + $email_id = isset($this->request->getJSON()->email_id) ? $this->request->getJSON()->email_id : null; $mpin = $this->request->getJSON()->mpin; - $employeeData = $this->employeeModel->where('mobile', $mobile_number)->where('relationship', 'self')->first(); + if (isset($mobile_number)) + { + $employeeData = $this->employeeModel->where('mobile', $mobile_number)->where('relationship', 'self')->first(); + }else{ + $employeeData = $this->employeeModel->where('email_corporate', $email_id)->where('relationship', 'self')->first(); + } if ($employeeData && $mpin == $employeeData["mpin"]) { $auth = HttpRequestHelper::getRequestInfo(); @@ -312,10 +413,19 @@ class RestAuthenticationController extends AdminController public function checkMpin() { try { - $mobile_number = $this->request->getJSON()->mobile_number; + $mobile_number = isset($this->request->getJSON()->mobile_number) ? $this->request->getJSON()->mobile_number : null; + $email_id = isset($this->request->getJSON()->email_id) ? $this->request->getJSON()->email_id : null; + $mpin = $this->request->getJSON()->mpin; + + if (isset($mobile_number)) + { + $employeeData = $this->employeeModel->where('mobile', $mobile_number)->where('relationship', 'self')->first(); + }else{ + $employeeData = $this->employeeModel->where('email_corporate', $email_id)->where('relationship', 'self')->first(); + } - $employeeData = $this->employeeModel->where('mobile', $mobile_number)->where('relationship', 'self')->first(); + if ($employeeData && $employeeData["mpin"] != null) { diff --git a/app/Controllers/UserController.php b/app/Controllers/UserController.php index 8d68fc1a..b9f5c34e 100755 --- a/app/Controllers/UserController.php +++ b/app/Controllers/UserController.php @@ -40,7 +40,7 @@ class UserController extends AdminController $data['UserList'] = $this->userModel->getUserList(); // echo '
';
         // print_r($data); die;
-        $data['roleData'] = $this->roleModel->select('id, role')->findAll();
+        $data['roleData'] = $this->roleModel->select('id, role')->findAll();        
         $data['teamData'] = $this->teamModel->select('id, name')->findAll();
         $this->loadLayout('UserList', $data);
     }
@@ -71,39 +71,43 @@ class UserController extends AdminController
                     $this->userTeamsModel->insert($teamData);
                 }
 
+                $db = \Config\Database::connect();
+                $tableName = 'hdz_staff';
+                
+                // Set default values
+                $admin = 0;
+                $acm = 0;
+                $acm_id = null;
+                
                 if ($userData['role'] == 3) {
-
-                    $db = \Config\Database::connect();
-                    $tableName = 'hdz_staff';
                     $admin = 0;
                     $acm = 1;
                     $acm_id = $insert;
-
-                    $password = '12345678'; //Default password
-                    $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
-
-                    foreach ($temp_team as $key => $value) {
-
-                        $team = $this->teamModel->where('id', $value)->first();
-
-                        if ($team['name'] == 'Claims') {
-                            $hdz_staff = [
-                                'emp_code' => $userData['emp_code'],
-                                'fullname' => $userData['first_name'],
-                                'username' => strtolower($userData['first_name']),
-                                'email' => $userData['email'],
-                                'admin' => $admin,
-                                'acm' => $acm,
-                                'acm_id' => $acm_id,
-                                'registration' => time(),
-                                'password' => $hashedPassword,
-                                'active' => 1,
-                            ];
-
-                            $db->table($tableName)->insert($hdz_staff);
-                        }
-                    }
+                } else if (in_array($userData['role'], [1, 5])) {
+                    $admin = 1;
+                    $acm = 0;
+                    $acm_id = null;
                 }
+                
+                $password = '12345678'; // Default password
+                $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
+                
+                $hdz_staff = [
+                    'emp_code' => $userData['emp_code'],
+                    'fullname' => $userData['first_name'],
+                    'username' => strtolower($userData['first_name']),
+                    'email' => $userData['email'],
+                    'admin' => $admin,
+                    'acm' => $acm,
+                    'acm_id' => $acm_id,
+                    'registration' => time(),
+                    'password' => $hashedPassword,
+                    'active' => 1,
+                    'department' => 'a:7:{i:0;s:1:"1";i:1;s:1:"2";i:2;s:1:"5";i:3;s:1:"3";i:4;s:1:"9";i:5;s:1:"4";i:6;s:2:"10";}',
+                ];
+                
+                $db->table($tableName)->insert($hdz_staff);
+                
             }
         }
         $this->myLogger->logme('error', 'User create Successfully created by id {data}', ['data' =>  get_session_userid()]);
@@ -149,33 +153,55 @@ class UserController extends AdminController
                     }
                 }
 
+                $db = \Config\Database::connect();
+                $tableName = 'hdz_staff';
+                
+                $hdz_staff = [
+                    'emp_code' => $userData['emp_code'],
+                    'fullname' => $userData['first_name'],
+                    'username' => strtolower($userData['first_name']),
+                    'email' => $userData['email'],
+                    'registration' => time(),
+                    'active' => 1,
+                    'department' => 'a:7:{i:0;s:1:"1";i:1;s:1:"2";i:2;s:1:"5";i:3;s:1:"3";i:4;s:1:"9";i:5;s:1:"4";i:6;s:2:"10";}',
+                ];
+                
                 if ($userData['role'] == 3) {
-
-                    $db = \Config\Database::connect();
-                    $tableName = 'hdz_staff';
-                    $admin = 1;
-
-                    foreach ($userData['team'] as $key => $value) {
-                        if ($value == 2) {
-
-                            $hdz_staff = [
-                                'emp_code' => $userData['emp_code'],
-                                'fullname' => $userData['first_name'],
-                                'username' => strtolower($userData['first_name']),
-                                'email' => $userData['email'],
-                                'admin' => $admin,
-                                'registration' => time(),
-                                'active' => 1,
-                            ];
-
-                            $db->table($tableName)->where('emp_code', $userData['emp_code'])
-                                ->where('email', $userData['email'])
-                                ->set($hdz_staff)
-                                ->update();
-                        }
-                    }
-
+                    $hdz_staff['admin'] = 0;
+                    $hdz_staff['acm'] = 1;
+                    $hdz_staff['acm_id'] = $id;
+                } elseif (in_array($userData['role'], [1, 5])) {
+                    $hdz_staff['admin'] = 1;
+                    $hdz_staff['acm'] = 0;
+                    $hdz_staff['acm_id'] = null;
+                } else {
+                    
+                    return redirect()->to(base_url('/user/list'));
                 }
+                
+                // Check if staff data exists
+                $staffData = $db->table($tableName)
+                    // ->where('emp_code', $userData['emp_code'])
+                    ->where('email', $userData['email'])
+                    ->get()->getResult();
+                
+                if (!empty($staffData)) {
+
+                    // Update existing record
+                    $db->table($tableName)
+                        // ->where('emp_code', $userData['emp_code'])
+                        ->where('email', $userData['email'])
+                        ->set($hdz_staff)->update();
+
+                } else {
+
+                    $password = '12345678'; // Default password
+                    $hdz_staff['password'] = password_hash($password, PASSWORD_DEFAULT);
+                
+                    // Insert new record
+                    $db->table($tableName)->insert($hdz_staff);
+                }
+                
             }
 
             return redirect()->to(base_url('/user/list'));
diff --git a/app/Filters/AuthMVC.php b/app/Filters/AuthMVC.php
index aa406108..1e0be969 100755
--- a/app/Filters/AuthMVC.php
+++ b/app/Filters/AuthMVC.php
@@ -9,7 +9,7 @@ class AuthMVC implements FilterInterface
 {
     public function before(RequestInterface $request, $arguments = null)
     {
-        if (!check_session()) {
+        if (!check_session() && !check_cookie()) {
             
           return redirect()->to(base_url('/login'));
         }
diff --git a/app/Helpers/DepositHelper.php b/app/Helpers/DepositHelper.php
index aa5950f0..0ee54530 100755
--- a/app/Helpers/DepositHelper.php
+++ b/app/Helpers/DepositHelper.php
@@ -62,6 +62,7 @@ class DepositHelper
             'created_by' => $loggedInUserID,
             'updated_by' => $data['updated_by'],
             'balance' => $newBalance, // Include the new balance in the data array
+            'cd_ac_pk'=> isset($data['cd_ac_pk'])?$data['cd_ac_pk']:null,
         ];
 
         // Insert data and get the insert ID
diff --git a/app/Helpers/ExcelMergeHelper.php b/app/Helpers/ExcelMergeHelper.php
new file mode 100644
index 00000000..36306692
--- /dev/null
+++ b/app/Helpers/ExcelMergeHelper.php
@@ -0,0 +1,150 @@
+getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine());
+            log_message('debug', 'Retrying with reversed file order');
+            
+            // Reverse the file order and try again
+            $reversedFiles = array_reverse($filePaths);
+            
+            try {
+                return self::processFiles($reversedFiles, $outputPath);
+            } catch (Exception $e2) {
+                log_message('error', 'Both attempts failed. Last error: ' . $e2->getMessage() . ' in ' . $e2->getFile() . ' on line ' . $e2->getLine());
+                return null;
+            }
+        }
+    }
+
+    /**
+     * Process files to merge spreadsheets
+     *
+     * @param array $filePaths
+     * @param string $outputPath
+     * @return string
+     * @throws Exception
+     */
+    private static function processFiles(array $filePaths, string $outputPath): string
+    {
+        log_message('debug', 'Starting Excel merge process');
+        log_message('debug', 'Files to process: ' . json_encode($filePaths));
+        
+        if (empty($filePaths)) {
+            throw new Exception("No files provided to merge");
+        }
+
+        // Initialize an empty merged spreadsheet
+        $mergedSpreadsheet = new Spreadsheet();
+        $mergedSpreadsheet->removeSheetByIndex(0); // Remove the default empty sheet
+        
+        // Process the base file
+        $firstFile = array_shift($filePaths);
+        self::processSingleFile($firstFile, $mergedSpreadsheet);
+
+        // Process remaining files
+        foreach ($filePaths as $index => $fileInfo) {
+            self::processSingleFile($fileInfo, $mergedSpreadsheet, $index);
+        }
+
+        // Save the merged file
+        log_message('debug', "Saving merged file to: {$outputPath}");
+        $writer = IOFactory::createWriter($mergedSpreadsheet, 'Xlsx');
+        $writer->setPreCalculateFormulas(false);
+        $writer->save($outputPath);
+        
+        // Clean up
+        $mergedSpreadsheet->disconnectWorksheets();
+        unset($mergedSpreadsheet);
+        gc_collect_cycles();
+        
+        log_message('debug', 'Excel merge process completed successfully');
+        return $outputPath;
+    }
+
+    /**
+     * Process a single file to merge its sheets into the merged spreadsheet
+     *
+     * @param array $fileInfo
+     * @param Spreadsheet $mergedSpreadsheet
+     * @param int|null $index
+     * @throws Exception
+     */
+    private static function processSingleFile(array $fileInfo, Spreadsheet $mergedSpreadsheet, int $index = null)
+    {
+        if (!isset($fileInfo['file_path']) || !file_exists($fileInfo['file_path'])) {
+            $path = $fileInfo['file_path'] ?? 'undefined';
+            log_message('error', "File " . ($index ?? 'base') . ": Invalid or missing file path: {$path}");
+            return;
+        }
+
+        log_message('debug', "Processing file " . ($index ?? 'base') . ": " . $fileInfo['file_path']);
+        
+        try {
+            // Load the source spreadsheet
+            $sourceSpreadsheet = IOFactory::load($fileInfo['file_path']);
+            
+            // Get all worksheets
+            $worksheets = $sourceSpreadsheet->getAllSheets();
+            $totalSheets = count($worksheets);
+            log_message('debug', "Total sheets in file: " . $totalSheets);
+
+            $sheetsToMerge = $fileInfo['sheets'] ?? [];
+
+            // Process each worksheet
+            foreach ($worksheets as $sheetIndex => $worksheet) {
+                if (empty($sheetsToMerge) || in_array($sheetIndex, $sheetsToMerge)) {
+                    try {
+                        $sheetName = $worksheet->getTitle();
+                        log_message('debug', "Processing sheet: {$sheetName}");
+
+                        // Generate unique sheet name before cloning
+                        $newName = $sheetName;
+                        $counter = 1;
+                        
+                        while (in_array($newName, $mergedSpreadsheet->getSheetNames())) {
+                            $newName = $sheetName . "_" . $counter++;
+                            log_message('debug', "Sheet name already exists. Trying new name: {$newName}");
+                        }
+
+                        // Clone the worksheet and set the new name
+                        $clonedSheet = clone $worksheet;
+                        $clonedSheet->setTitle($newName);
+
+                        // Add as external sheet
+                        $mergedSpreadsheet->addExternalSheet($clonedSheet);
+
+                        log_message('debug', "Successfully added sheet: {$newName}");
+                    } catch (Exception $e) {
+                        log_message('error', "Error processing sheet {$sheetName} as new name {$newName}: " . $e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine());
+                    }
+                }
+            }
+            
+            // Clean up source spreadsheet
+            $sourceSpreadsheet->disconnectWorksheets();
+            unset($sourceSpreadsheet);
+            gc_collect_cycles();
+            
+        } catch (Exception $e) {
+            log_message('error', "Error processing file {$fileInfo['file_path']}: " . $e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine());
+        }
+    }
+}
\ No newline at end of file
diff --git a/app/Helpers/ExcelSanitizeHelper.php b/app/Helpers/ExcelSanitizeHelper.php
new file mode 100644
index 00000000..b4950b34
--- /dev/null
+++ b/app/Helpers/ExcelSanitizeHelper.php
@@ -0,0 +1,51 @@
+ $value) {
+                if (is_array($value)) {
+                    $cleanData[$key] = self::sanitizeArrayData($value); // Recursive call for nested arrays
+                } elseif (is_string($value)) {
+                    // Remove non-printable characters and trim whitespace from strings
+                    $cleanData[$key] = trim(str_replace(self::$nonPrintableChars, '', $value));
+                } else {
+                    $cleanData[$key] = $value; // Keep non-string/non-array data as is
+                }
+            }
+            
+            return $cleanData;
+        } catch (\Exception $e) {
+            // Log the error and the problematic data for debugging
+            log_message('error', 'Error sanitizing array data: ' . $e->getMessage());
+            log_message('error', 'Problematic data: ' . json_encode($data));
+            return $data; // Return the original data in case of error
+        }
+    }
+}
diff --git a/app/Helpers/GmailResponseHandler.php b/app/Helpers/GmailResponseHandler.php
new file mode 100644
index 00000000..4a45f65c
--- /dev/null
+++ b/app/Helpers/GmailResponseHandler.php
@@ -0,0 +1,125 @@
+myLogger = \Config\Services::mylogger();
+
+    }
+    
+    
+    public function receive_and_distribute_param_to_functions($params)
+    {
+        try{
+
+            $this->store_gmail_response_data($params);
+            $this->gmail_response_logger($params);
+            $this->client_id_flag_setter($params);
+
+        }
+        catch(Exception $e)
+        {
+
+            $error = $e->getMessage();
+            echo "An Error Occured" . $error;
+            log_message('error',$error);
+                
+        }    
+    }
+    
+
+    public function store_gmail_response_data($params){
+        // foreach ($params as $key => $value){
+        //     $prepare_data = [
+        //         $key => $value
+        //     ];
+        // }
+        // $data = [
+        //     'email' => isset($params['params']['mail']) ? $params['params']['mail'] : null,
+        //     'bcc' => isset($params['params']['bcc']) ? json_encode($params['params']['bcc']) : null,
+        //     'cc' => isset($params['params']['cc']) ? json_encode($params['params']['cc']) : null,
+        //     'message' => isset($params['params']['message']) ? $params['params']['message'] : null,
+        //     'attachments' => isset($params['params']['attachments']) ? json_encode($params['params']['attachments']) : null,
+        //     'client_id' => isset($params['params']['common']['client_id']) ? $params['params']['common']['client_id'] : null,
+        //     'client_branch_id' => isset($params['params']['common']['client_branch_id']) ? $params['params']['common']['client_branch_id'] : null,
+        //     'client_policy_id' => isset($params['params']['common']['client_policy_id']) ? $params['params']['common']['client_policy_id'] : null,
+        //     'employee_policy_id' => isset($params['params']['common']['employee_policy_id']) ? $params['params']['common']['employee_policy_id'] : null,
+        //     'employee_id' => isset($params['params']['common']['employee_id']) ? $params['params']['common']['employee_id'] : null,
+        //     'mail_type' => isset($params['params']['common']['mail_type']) ? $params['params']['common']['mail_type'] : null,
+        //     'gmail_api_status' => isset($params['gmail_api']['status']) ? $params['gmail_api']['status'] : null,
+        //     'gmail_api_id' => isset($params['gmail_api']['data']['id']) ? $params['gmail_api']['data']['id'] : null
+        // ];
+       // Initialize data array
+        $data = [];
+        // print_r($params['params']['common']);die();
+        if (isset($params['params']['common'])) {
+            foreach ($params['params']['common'] as $key => $value) {
+                $data[$key] = isset($value) ? $value : null;
+            }
+            unset($params['params']['common']);
+        }
+        if (isset($params['params'])){
+            foreach($params['params'] as $key => $value){
+                $arr = ['bcc','cc','attachments'];
+                if(in_array($key,$arr)){
+                    $data[$key] = isset($value)?json_encode($value):null;
+                }else{
+                    $data[$key] = isset($value)?$value:null;
+                }
+            }
+        }
+        if(isset($params['zepto_api']['data']) && $params['zepto_api']['message'] == 'OK' ){
+            $data['gmail_api_status'] = isset($params['zepto_api']['data']) ? $params['zepto_api']['data'][0]['code'] : null;
+            $data['gmail_api_id'] = isset($params['zepto_api']['request_id']) ? $params['zepto_api']['request_id'] : null;
+            $data['received_message'] = isset($params['zepto_api']['data'][0]['message']) ? json_encode($params['zepto_api']['data'][0]['message']) : null;
+
+        }
+        elseif(isset($params['zepto_api']['error'])){
+            $data['gmail_api_status'] = isset($params['zepto_api']['error']['code'])?$params['zepto_api']['error']['code']:null;
+            $data['received_message'] = json_encode($params['zepto_api']);
+            $data['gmail_api_id'] = isset($params['zepto_api']['error']['request_id']) ? $params['zepto_api']['error']['request_id'] : null;
+        }
+         
+        $gmailModel = new GmailSentHistoryModel();
+        $save_status = $gmailModel->insert($data); 
+    }
+
+    public function gmail_response_logger($params)
+    {
+        if(isset($params['zepto_api']['error'])){
+            $this->myLogger->logme('error',json_encode($params));
+        }
+    }
+
+    public function client_id_flag_setter($params)
+    {
+        try{
+            if (isset($params['params']['common']['mail_type'])){
+                if($params['params']['common']['mail_type'] == 'member_ecard_mail'){
+                    $employeePolicyModel = new EmployeePolicyModel();
+                    $update_status = $employeePolicyModel->where('id',$params['params']['common']['employee_policy_id'])->set('ecard_sent_status',1)->update();
+                    if($update_status){
+                        $this->myLogger->logme('error',"ecard_sent_status updated for ".$params['params']['common']['employee_policy_id']);
+                    }else{
+                        $this->myLogger->logme('error','ecard_sent_status failed to update');
+                    }
+                }
+                
+            }
+        }
+    catch(Exception $e){
+        $error = $e->getMessage();
+        $this->myLogger->logme('error','An Error Occured - '.$error);
+    }
+}
+
+}
\ No newline at end of file
diff --git a/app/Helpers/JWTToken.php b/app/Helpers/JWTToken.php
index 196bdaca..41d76b5c 100755
--- a/app/Helpers/JWTToken.php
+++ b/app/Helpers/JWTToken.php
@@ -11,7 +11,7 @@ use Firebase\JWT\SignatureInvalidException;
 // use Psr\Http\Message\RequestInterface;
 use CodeIgniter\HTTP\RequestInterface;
 use ReflectionClass;
-
+use Exception;
 use App\Models\EmployeeModel;
 use App\Models\LevelContactModel;
 
diff --git a/app/Helpers/MailHelper.php b/app/Helpers/MailHelper.php
index 0bc21c46..91e955b0 100755
--- a/app/Helpers/MailHelper.php
+++ b/app/Helpers/MailHelper.php
@@ -1,164 +1,422 @@
 setMailType('html');
+//             $email->setFrom('bbone@venbait.in', 'Nhance');
+
+//             $email->setTo($emaill);
+
+//             if (!empty($bcc)) {
+//                 // Convert the comma-separated string into an array
+//                 $bccList = explode(',', $bcc);
+//                 // Trim whitespace from each email ID
+//                 $bccList = array_map('trim', $bccList);
+//                 // Set BCC recipients
+//                 $email->setBCC($bccList);
+//             }
+
+//             $email->setSubject($subject);
+
+//             $email->setMessage($message);
+
+//             if ($email->send()) {
+
+//                 return json_encode(['status' => 'success','code' => 200, 'message'=>'Email Sent Successfully...','data' => $emaill,],200);
+//             } else {
+//                 $myLogger->logme('error', "mail sent failed -  $emaill");
+//                 return json_encode(['status' => 'failed','code' => 404,'message'=>'Email Sent Failed...','data' => $emaill  ],404);
+//             }
+            
+//         } catch (Exception $e) {
+//             $msg = $e->getMessage();
+//             $myLogger->logme('error', "mail sent failed -  $msg");
+//             return json_encode(['status' => 'failed','code' => 500,'data' => $emaill],500);
+//         }  
+//     }
+
+//     public static function bulk_mail_smtp(array $mails = [])
+//     {
+//         // print_r();die;
+//         $model = new JobModel();
+//         $start = microtime(true);
+//         $runtime= 0;
+//        try {
+//         foreach ( $mails as $index=>$mail) {
+//                 $runtime = microtime(true) - $start;
+//                 $send_mail = self::send_email($mail);   
+//         }
+        
+//         return json_encode(['status' => 'success','code' => 200, 'message'=>'Email Sent Successfully...'],200);
+
+//        } catch (\Throwable $th) {
+//         return json_encode(['status' => 'failed','code' => 500],500);
+//        }
+//     }
+
+//     //using GmailAPI
+//      public static function send_email($params) 
+//     {    
+
+//         // print_r($params);die;
+//         $myLogger = \Config\Services::mylogger();
+//         $gmailapi = \Config\Services::gmailapi();
+
+//         $emaill = $params['mail'];
+//         $subject = $params['subject'];
+//         $message = $params['message'];
+//         $attachments = isset($params['attachments']) && count($params['attachments']) ? $params['attachments'] : [];
+//         $common = isset($params['common'])?$params['common']:'';
+//         //check BCC mail
+//         if (isset($params['bcc'])) {
+//             $bcc = $params['bcc'];
+//             if(!is_array($bcc)){
+//                 $bcc = explode(',', $bcc);
+//             }
+//         }else{
+//             $bcc = [];
+//         }
+
+//         //check CC mail
+//         if (isset($params['cc'])) {
+//             $cc = $params['cc'];
+//             if(!is_array($cc)){
+//                 $cc = explode(',', $cc);
+//             }
+//         }else{
+//             $cc = [];
+//         }
+
+//         //check REPLY TO mail
+//         $reply_to = "";
+//         if(isset($params['reply_to']) && !empty($params['reply_to'])){
+//             $reply_to = $params['reply_to'];
+//         }
+//         $MailDataHelper = new GmailResponseHandler();
+
+//         $res['params'] = $params;
+//         try {
+          
+//               $res['gmail_api'] = $gmailapi->sendMessage($emaill, $subject, $message, 'no-reply@nhanceindia.in', $reply_to, $cc, $bcc,$attachments);
+//                if($res['gmail_api']['status'])
+//                {
+//                   $response = $res;
+//                   $MailDataHelper->receive_and_distribute_param_to_functions($response);
+//                   return json_encode(['status' => 'success','code' => 200, 'message'=>('Email Sent Successfully...'.$emaill),'data' => $res,],200);
+//                }
+//                else
+//                {
+//                     $myLogger->logme('error', "mail sent failed -  $emaill");
+//                     $response = $res;
+//                     $MailDataHelper->receive_and_distribute_param_to_functions($response);
+//                     return json_encode(['status' => 'failed','code' => 404,'message'=>( 'Email Sent Failed...' . $emaill ),'data' => $res  ],404);
+//                }
+ 
+//         } catch (Exception $e) {
+//             $msg['error'] = $e->getMessage();
+//             $msg['params'] = $params;
+//             $myLogger->logme('error', "mail sent failed -  $msg");
+//             $response = $msg;
+//             $MailDataHelper->receive_and_distribute_param_to_functions($response);
+//             return json_encode(['status' => 'failed','code' => 500,'data' => $msg],500);
+//         }
+        
+
+//     }
+
+
+//     public static function bulk_mail(array $mails = [])
+//     {
+//         // print_r($mails);die;
+//         $model = new JobModel();
+//         $start = microtime(true);
+//         $runtime= 0;
+//        try {
+//         foreach ( $mails as $index=>$mail) {
+//                 $runtime = microtime(true) - $start;
+//                 $send_mail = self::send_email($mail);
+//         }
+        
+//         return json_encode(['status' => 'success','code' => 200, 'message'=>'Email Sent Successfully...'],200);
+
+//        } catch (\Throwable $th) {
+//         $error = $th->getMessage();
+//         log_message('error',$error);
+//         return json_encode(['status' => 'failed','code' => 500,'error'=>$error],500);
+//        }
+//     }
+
+// }
+
+
 namespace App\Helpers;
 use Psr\Log\LoggerInterface;
-
 use App\Controllers\BaseController;
-
-use PHPMailer\PHPMailer\PHPMailer;
-use PHPMailer\PHPMailer\SMTP;
-use PHPMailer\PHPMailer\Exception;
-
 use App\Models\JobModel;
 
-
 class MailHelper
 {
     public static function send_email_smtp($params) 
     {    
-
-        // print_r($params);die;
         $myLogger = \Config\Services::mylogger();
         $emaill = $params['mail'];
         $subject = $params['subject'];
         $message = $params['message'];
         if (isset($params['bcc'])) {
             $bcc = $params['bcc'];
-        }else{
-            $bcc= '';
+        } else {
+            $bcc = '';
         }
+        $from_address = getenv('email.fromEmail');
+
+
         try {
-            
-            $email = \Config\Services::email();
-            $email->setMailType('html');
-            $email->setFrom('bbone@venbait.in', 'Nhance');
-
-            $email->setTo($emaill);
+            $curl = curl_init();
+            $postData = [
+                'from' => [
+                    'address' => $from_address
+                ],
+                'to' => [
+                    [
+                        'email_address' => [
+                            'address' => $emaill
+                        ]
+                    ]
+                ],
+                'subject' => $subject,
+                'htmlbody' => $message
+            ];
 
+            // Add BCC if present
             if (!empty($bcc)) {
-                // Convert the comma-separated string into an array
                 $bccList = explode(',', $bcc);
-                // Trim whitespace from each email ID
                 $bccList = array_map('trim', $bccList);
-                // Set BCC recipients
-                $email->setBCC($bccList);
+                $postData['bcc'] = array_map(function($email) {
+                    return [
+                        'email_address' => [
+                            'address' => $email
+                        ]
+                    ];
+                }, $bccList);
             }
 
-            $email->setSubject($subject);
+            curl_setopt_array($curl, [
+                CURLOPT_URL => "https://api.zeptomail.in/v1.1/email",
+                CURLOPT_RETURNTRANSFER => true,
+                CURLOPT_ENCODING => "",
+                CURLOPT_MAXREDIRS => 10,
+                CURLOPT_TIMEOUT => 30,
+                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
+                CURLOPT_CUSTOMREQUEST => "POST",
+                CURLOPT_POSTFIELDS => json_encode($postData),
+                CURLOPT_HTTPHEADER => [
+                    "accept: application/json",
+                    "authorization: Zoho-enczapikey " . getenv('ZEPTO_API_KEY'),
+                    "cache-control: no-cache",
+                    "content-type: application/json",
+                ],
+            ]);
 
-            $email->setMessage($message);
+            $response = curl_exec($curl);
+            $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
+            $err = curl_error($curl);
 
-            if ($email->send()) {
+            curl_close($curl);
+            if ($err) {
+                $myLogger->logme('error', "mail sent failed -  $emaill");
+                return json_encode(['status' => 'failed', 'code' => 404, 'message' => 'Email Sent Failed...', 'data' => $emaill], 404);
+            }
 
-                return json_encode(['status' => 'success','code' => 200, 'message'=>'Email Sent Successfully...','data' => $emaill,],200);
+            $apiResponse = json_decode($response, true);
+            
+            if ($httpCode === 200) {
+                return json_encode(['status' => 'success', 'code' => 200, 'message' => 'Email Sent Successfully...', 'data' => $emaill], 200);
             } else {
                 $myLogger->logme('error', "mail sent failed -  $emaill");
-                return json_encode(['status' => 'failed','code' => 404,'message'=>'Email Sent Failed...','data' => $emaill  ],404);
+                return json_encode(['status' => 'failed', 'code' => 404, 'message' => 'Email Sent Failed...', 'data' => $emaill], 404);
             }
-            
-        } catch (Exception $e) {
+
+        } catch (\Exception $e) {
             $msg = $e->getMessage();
             $myLogger->logme('error', "mail sent failed -  $msg");
-            return json_encode(['status' => 'failed','code' => 500,'data' => $emaill],500);
-        }  
+            return json_encode(['status' => 'failed', 'code' => 500, 'data' => $emaill], 500);
+        }
     }
 
     public static function bulk_mail_smtp(array $mails = [])
     {
-        // print_r();die;
         $model = new JobModel();
         $start = microtime(true);
-        $runtime= 0;
-       try {
-        foreach ( $mails as $index=>$mail) {
+        $runtime = 0;
+        try {
+            foreach ($mails as $index => $mail) {
                 $runtime = microtime(true) - $start;
                 $send_mail = self::send_email($mail);   
-        }
-        
-        return json_encode(['status' => 'success','code' => 200, 'message'=>'Email Sent Successfully...'],200);
+            }
+            
+            return json_encode(['status' => 'success', 'code' => 200, 'message' => 'Email Sent Successfully...'], 200);
 
-       } catch (\Throwable $th) {
-        return json_encode(['status' => 'failed','code' => 500],500);
-       }
+        } catch (\Throwable $th) {
+            return json_encode(['status' => 'failed', 'code' => 500], 500);
+        }
     }
 
-    //using GmailAPI
-     public static function send_email($params) 
+    public static function send_email($params) 
     {    
-
-        // print_r($params);die;
         $myLogger = \Config\Services::mylogger();
-        $gmailapi = \Config\Services::gmailapi();
-
+        
         $emaill = $params['mail'];
         $subject = $params['subject'];
         $message = $params['message'];
-        $attachments = isset($params['attachments']) && count($params['attachments']) ? $params['attachments'] : [];
-        
-        //check BCC mail
-        if (isset($params['bcc'])) {
-            $bcc = $params['bcc'];
-            $bcc = explode(',', $bcc);
-        }else{
-            $bcc = [];
-        }
-
-        //check CC mail
-        if (isset($params['cc'])) {
-            $cc = $params['cc'];
-            if(!is_array($cc)){
-                $cc = explode(',', $cc);
-            }
-        }else{
-            $cc = [];
-        }
-
-        //check REPLY TO mail
-        $reply_to = "";
-        if(isset($params['reply_to']) && !empty($params['reply_to'])){
-            $reply_to = $params['reply_to'];
-        }
+        $attachments = isset($params['attachments']) ? $params['attachments'] : [];
+        $common = isset($params['common']) ? $params['common'] : '';
 
+        $from_address = getenv('email.fromEmail');
         try {
-          
-              $res = $gmailapi->sendMessage($emaill, $subject, $message, 'no-reply@nhanceindia.in', $reply_to, $cc, $bcc,$attachments);
+            $curl = curl_init();
+            
+            $postData = [
+                'from' => [
+                    'address' => $from_address
+                ],
+                'to' => [
+                    [
+                        'email_address' => [
+                            'address' => $emaill
+                        ]
+                    ]
+                ],
+                'subject' => $subject,
+                'htmlbody' => $message
+            ];
 
-               if($res['status'])
-               {
-                  return json_encode(['status' => 'success','code' => 200, 'message'=>('Email Sent Successfully...'.$emaill),'data' => $res,],200);
-               }
-               else
-               {
-                    $myLogger->logme('error', "mail sent failed -  $emaill");
-                    return json_encode(['status' => 'failed','code' => 404,'message'=>( 'Email Sent Failed...' . $emaill ),'data' => $res  ],404);
-               }
- 
-        } catch (Exception $e) {
-            $msg = $e->getMessage();
-            $myLogger->logme('error', "mail sent failed -  $msg");
-            return json_encode(['status' => 'failed','code' => 500,'data' => $msg],500);
-        }  
+            // Handle attachments
+            if (!empty($attachments)) {
+                $postData['attachments'] = [];
+                foreach ($attachments as $attachment) {
+                    if (isset($attachment['filePath']) && file_exists($attachment['filePath'])) {
+                        // Determine MIME type dynamically
+                        $fileMimeType = mime_content_type($attachment['filePath']);
+            
+                        $postData['attachments'][] = [
+                            'content' => base64_encode(file_get_contents($attachment['filePath'])),
+                            'name' => $attachment['fileName'],
+                            'mime_type' => $fileMimeType, // Add mime_type field
+                        ];
+                    }
+                }
+            }
+            
+
+            curl_setopt_array($curl, [
+                CURLOPT_URL => "https://api.zeptomail.in/v1.1/email",
+                CURLOPT_RETURNTRANSFER => true,
+                CURLOPT_ENCODING => "",
+                CURLOPT_MAXREDIRS => 10,
+                CURLOPT_TIMEOUT => 30,
+                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
+                CURLOPT_CUSTOMREQUEST => "POST",
+                CURLOPT_POSTFIELDS => json_encode($postData),
+                CURLOPT_HTTPHEADER => [
+                    "accept: application/json",
+                    "authorization: Zoho-enczapikey " . getenv('ZEPTO_API_KEY'),
+                    "cache-control: no-cache",
+                    "content-type: application/json",
+                ],
+            ]);
+
+            $mail_result = curl_exec($curl);
+            $err = curl_error($curl);
+            curl_close($curl);
+            // log_message('error','inside mail helper');
+            // log_message('error', $response.' error->'.$err);die();
+            $res['params'] = $params;
+            $MailDataHelper = new GmailResponseHandler();
+            $apiResponse = json_decode($mail_result, true);
+            $res['zepto_api'] = $apiResponse;
+            if (isset($apiResponse['error'])) {
+                $response = $res;
+                $MailDataHelper->receive_and_distribute_param_to_functions($response);
+                return json_encode([
+                    'status' => 'failed',
+                    'code' => 404,
+                    'message' => 'Email Sent Failed...' . $emaill,
+                    'data' => $res
+                ], 404);
+            }
+
+            // $apiResponse = json_decode($response, true);
+
+            // Check if request_id exists in response (indicates success)
+            if (isset($apiResponse['data'])) {
+                $response = $res;
+                $MailDataHelper->receive_and_distribute_param_to_functions($response);
+                return json_encode([
+                    'status' => 'success',
+                    'code' => 200,
+                    'message' => 'Email Sent Successfully...' . $emaill,
+                    'data' => $res
+                ], 200);
+            } 
+
+        } catch (\Exception $e) {
+            $msg['error'] = $e->getMessage();
+            $msg['params'] = $params;
+            $response = $res;
+            $MailDataHelper->receive_and_distribute_param_to_functions($response);
+            return json_encode([
+                'status' => 'failed',
+                'code' => 500,
+                'data' => $msg
+            ], 500);
+        }
     }
 
-
     public static function bulk_mail(array $mails = [])
     {
-        // print_r();die;
         $model = new JobModel();
         $start = microtime(true);
-        $runtime= 0;
-       try {
-        foreach ( $mails as $index=>$mail) {
+        $runtime = 0;
+        try {
+            foreach ($mails as $index => $mail) {
                 $runtime = microtime(true) - $start;
                 $send_mail = self::send_email($mail);
+            }
+            
+            return json_encode(['status' => 'success', 'code' => 200, 'message' => 'Email Sent Successfully...'], 200);
+
+        } catch (\Throwable $th) {
+            $error = $th->getMessage();
+            log_message('error', $error);
+            return json_encode(['status' => 'failed', 'code' => 500, 'error' => $error], 500);
         }
-        
-        return json_encode(['status' => 'success','code' => 200, 'message'=>'Email Sent Successfully...'],200);
-
-       } catch (\Throwable $th) {
-        return json_encode(['status' => 'failed','code' => 500],500);
-       }
     }
-
 }
 ?>
\ No newline at end of file
diff --git a/app/Helpers/excel_import_export_helper.php b/app/Helpers/excel_import_export_helper.php
index 3355253e..ad484ffe 100755
--- a/app/Helpers/excel_import_export_helper.php
+++ b/app/Helpers/excel_import_export_helper.php
@@ -128,7 +128,7 @@ if (! function_exists('transform_objects_to_array_for_inception')) {
                 $obj->emp_gender,                    // Employee Gender
                 $obj->pre_existing_alignments,       // Pre-existing Alignments
                 $obj->basic_cover_si,                // Basic Cover SI
-                $obj->date_coverage,                 // Date Coverage
+                $obj->date_of_coverage,                 // Date Coverage
                 $obj->emp_age,                       // Employee Age
                 $obj->emp_relationship,              // Employee Relationship
                 $obj->change_event,                  // Change Event
@@ -260,7 +260,6 @@ if (! function_exists('transform_objects_to_array_for_deletion')) {
                 $obj->total,                        
                 $claim_status,
                 $endorsement_id
-
             ];
 
             // Append the row data to the main data array
@@ -487,7 +486,7 @@ if (!function_exists('format_Excel_BasedOn_Client'))
                             $rowData[] = $obj->basic_cover_si; // Employee BASIC COVER SI
                             break;
                         case 'dateofcoverage':
-                            $rowData[] = $obj->date_coverage; //  DATE OF COVERAGE
+                            $rowData[] = $obj->date_of_coverage; //  DATE OF COVERAGE
                             break;
                         case 'age':
                             $rowData[] = $obj->emp_age; // Employee AGE
diff --git a/app/Helpers/excel_util_helper.php b/app/Helpers/excel_util_helper.php
index a371ed98..436ae854 100755
--- a/app/Helpers/excel_util_helper.php
+++ b/app/Helpers/excel_util_helper.php
@@ -345,8 +345,7 @@ if(!function_exists('check_basic_pay'))
 
 if (!function_exists('check_dob_diff')) 
 {
-    function check_dob_diff($row,$relationships,$default_age_ratio) {
-        // echo 'called';
+    function check_dob_diff($row,$relationships,$default_age_ratio,$policy_details) {
         if($row['current_action'] != null &&  in_array(strtoupper($row['current_action']), ['I','A','DA','MI']))// check rule only of action column data available
         {
                 if($row[3] != null && $row[5] != null)
@@ -358,13 +357,11 @@ if (!function_exists('check_dob_diff'))
                     }
                     // return array('status' => true);
                     $dob = $dateString;
-                    // echo $row[3].' - '.$dob;echo '
'; - $currentDateTime = new DateTime();//die(); - // print_r($currentDateTime); + //$currentDateTime = new DateTime();//previously dob calculated from current date time + $temp_date = ($row[7] != null && $row[7] != "") ? convert_string_to_date($row[7]) : $policy_details[0]->policy_start_date; //pick date of coverage from row if not then use policy start date as from to calculate DOB + $currentDateTime = new DateTime($temp_date);//later DOB calculated from date of coverage or policy_start_date // die(); $passedDateTime = new DateTime($dob); - // print_r($passedDateTime); - $interval = $currentDateTime->diff($passedDateTime); //remap default age ratio data into relationship array if(count($default_age_ratio)) @@ -375,7 +372,6 @@ if (!function_exists('check_dob_diff')) $relationship = $slug->slugify($row[5]); $age_min = isset($relationships[$relationship]['age_min']) ? $relationships[$relationship]['age_min'] : NULL; $age_max = isset($relationships[$relationship]['age_max']) ? $relationships[$relationship]['age_max'] : NULL; - // echo $relationship.','.$age_min.'-'.$age_max; if($age_min !== null && $age_min > $interval->y) { return array('status' => false,'error' => "Age conflict : minimum $age_min yrs allowed, received $interval->y"); @@ -965,7 +961,6 @@ if (!function_exists('calculate_premium_new')) if(empty($member[18])){ $member[18] = $existing_units[0]; } //transform as db row column $transformed_familiy_member_data = transform_excel_data_to_db($member,$fileArr); - // kint::dump($transformed_familiy_member_data); //generate relationship code if($transformed_familiy_member_data['temp']['action'] != 'D' && $transformed_familiy_member_data['temp']['action'] != 'C' && $transformed_familiy_member_data['temp']['action'] != 'SI') { @@ -979,7 +974,7 @@ if (!function_exists('calculate_premium_new')) 'isEmployeeSourceEnrollment' => $fileArr['id'] == null, 'isEmployeeSourceExcelFile' => $transformed_familiy_member_data['temp']['source'] == 'excel', 'isCurrentActionDependentAddition' => $fileArr['action'] == 'dependent_addition', - // 'isPrimaryGridPremiumTypeSingle' => $transformed_familiy_member_data['temp']['premium_type'] == 1, + 'isPrimaryGridPremiumTypeSingle' => isset($transformed_familiy_member_data['temp']['premium_type']) ? $transformed_familiy_member_data['temp']['premium_type'] == 1 : 0, 'isCurrentRelationshipSelf' => (strtolower($transformed_familiy_member_data['relationship']) == 'self' || (isset($transformed_familiy_member_data['temp']['acting_self']) && $transformed_familiy_member_data['temp']['acting_self'] === true)), 'isBasicCoverCalculatedToCurrentEmployee' => ($transformed_familiy_member_data['policy_details']['basic_cover_si'] != null && $transformed_familiy_member_data['policy_details']['basic_cover_si'] != 0) ]; @@ -1049,7 +1044,7 @@ if (!function_exists('transform_excel_data_to_db')) $result['designation'] = $memArr[11]; $result['mobile'] = $memArr[12]; $result['email_corporate'] = $memArr[13]; - $result['file_id'] = $actionArr['id']; + $result['file_id'] = isset($memArr['temp']['source']) && $memArr['temp']['source'] == 'db' && isset($memArr['temp']['file_id']) ? $memArr['temp']['file_id'] : $actionArr['id']; $result['client_id'] = $actionArr['client_id']; $result['change_event'] = $memArr[15]; $result['unit'] = $memArr[18]; @@ -1078,8 +1073,6 @@ if (!function_exists('premium_calculation_manager')) { function premium_calculation_manager($emp_data,$policy_terms,$slab_details,$default_si = null) { - // Kint::dump($emp_data);die(); - $myLogger = \Config\Services::mylogger(); // grid type // 1 = premium => si @@ -1091,25 +1084,25 @@ if (!function_exists('premium_calculation_manager')) //check emp records if($emp_data['file_id'] == null && $emp_data['temp']['emp_status'] == 'draft' && $emp_data['temp']['policy_status'] == 'draft') { - $original_emp_records = get_emp_records_from_audit_history($emp_data['temp']['emp_id']); - if(is_array($original_emp_records)) - { - // Kint::dump($original_emp_records); - $emp_data = replace_original_data(original_data:$original_emp_records,current_data:$emp_data); - // Kint::dump($value); - } + // $original_emp_records = get_emp_records_from_audit_history($emp_data['temp']['emp_id']); + // if(is_array($original_emp_records)) + // { + // // Kint::dump($original_emp_records); + // // $emp_data = replace_original_data(original_data:$original_emp_records,current_data:$emp_data); + // // Kint::dump($value); + // } } //check emp policy records if($emp_data['file_id'] == null && $emp_data['temp']['emp_status'] == 'draft' && $emp_data['temp']['policy_status'] == 'draft') { - $original_emp_policy_records = get_emp_policy_records_from_audit_history($emp_data['temp']['emp_policy_id']); - if(is_array($original_emp_policy_records)) - { - // Kint::dump($original_emp_records); - $emp_data['policy_details'] = replace_original_data(original_data:$original_emp_policy_records,current_data:$emp_data['policy_details']); - // Kint::dump($policy_data); - } + // $original_emp_policy_records = get_emp_policy_records_from_audit_history($emp_data['temp']['emp_policy_id']); + // if(is_array($original_emp_policy_records)) + // { + // // Kint::dump($original_emp_records); + // $emp_data['policy_details'] = replace_original_data(original_data:$original_emp_policy_records,current_data:$emp_data['policy_details']); + // // Kint::dump($policy_data); + // } }//end of fetching data from audit history table @@ -1167,7 +1160,7 @@ if (!function_exists('premium_calculation_manager')) { if($temp_slab_rates[0]['si_or_bp'] == 2) { - $temp_si = $emp_data['basic_pay'] * $temp_slab_rates[0]['si_or_bp']; + $temp_si = $emp_data['basic_pay'] * $temp_slab_rates[0]['basic_multiplier']; $temp_premium = ($temp_si * $temp_slab_rates[0]['multiplier']) / 1000; $emp_data['policy_details']['basic_cover_si'] = $temp_si; @@ -1209,7 +1202,7 @@ if (!function_exists('premium_calculation_manager')) $employee_received_si = $default_si == null ? $emp_data['policy_details']['basic_cover_si'] : $default_si; foreach ($temp_slab_rates as $skey => $slab_value) { - if($slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'] && (($slab_value['premium_type'] == 1 && ( strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['acting_self'] ) ) || ($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null) )) + if($slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'] && (($slab_value['premium_type'] == 1 && ( strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['acting_self'] ) ) || ($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null || $slab_value['premium_type'] == 3 ) )) { $emp_data['policy_details']['basic_cover_si'] = $slab_value['si']; $emp_data['policy_details']['date_coverage'] = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']); @@ -1229,10 +1222,13 @@ if (!function_exists('premium_calculation_manager')) //GMC - Employees Age band $employee_received_si = $default_si == null ? $emp_data['policy_details']['basic_cover_si'] : $default_si; // dd($employee_received_si); + $temp_date = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']); + $age = calculate_days_bw_dates(from_date: $emp_data['dob'],to_date: $temp_date)->y; + foreach ($temp_slab_rates as $skey => $slab_value) { - $age = calculate_days_bw_dates(from_date: $emp_data['dob'])->y; - if($slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'] && ($slab_value['age_from'] <= $age && $slab_value['age_to'] >= $age) && (($slab_value['premium_type'] == 1 && ( strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['acting_self'] ) ) || ($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null) )) + + if($slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'] && ($slab_value['age_from'] <= $age && $slab_value['age_to'] >= $age) && (($slab_value['premium_type'] == 1 && ( strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['acting_self'] ) ) || ($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null || $slab_value['premium_type'] == 3) )) { // dd($slab_value); $emp_data['policy_details']['basic_cover_si'] = $slab_value['si']; @@ -1250,10 +1246,13 @@ if (!function_exists('premium_calculation_manager')) case "5": //GMC - Employees Age + SI $employee_received_si = $default_si == null ? $emp_data['policy_details']['basic_cover_si'] : $default_si; + $temp_date = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']); + $age = calculate_days_bw_dates(from_date: $emp_data['dob'],to_date: $temp_date)->y; + foreach ($temp_slab_rates as $skey => $slab_value) { - $age = calculate_days_bw_dates(from_date: $emp_data['dob'])->y; - if($slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'] && ($slab_value['age_from'] <= $age && $slab_value['age_to'] >= $age) && (($slab_value['premium_type'] == 1 && ( strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['acting_self'] ) ) || ($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null) )) + + if($slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'] && ($slab_value['age_from'] <= $age && $slab_value['age_to'] >= $age) && (($slab_value['premium_type'] == 1 && ( strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['acting_self'] ) ) || ($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null || $slab_value['premium_type'] == 3 ) )) { $emp_data['policy_details']['basic_cover_si'] = $slab_value['si']; $emp_data['policy_details']['date_coverage'] = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']); @@ -1270,10 +1269,12 @@ if (!function_exists('premium_calculation_manager')) case "6": //GMC - Employees + Dependent Age band $employee_received_si = $default_si == null ? $emp_data['policy_details']['basic_cover_si'] : $default_si; + $temp_date = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']); + $age = calculate_days_bw_dates(from_date: $emp_data['dob'],to_date: $temp_date)->y; foreach ($temp_slab_rates as $skey => $slab_value) { - $age = calculate_days_bw_dates(from_date: $emp_data['dob'])->y; - if($slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'] && ($slab_value['age_from'] <= $age && $slab_value['age_to'] >= $age) && (($slab_value['premium_type'] == 1 && ( strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['acting_self'] ) ) || ($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null) )) + + if($slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'] && ($slab_value['age_from'] <= $age && $slab_value['age_to'] >= $age) && (($slab_value['premium_type'] == 1 && ( strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['acting_self'] ) ) || ($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null || $slab_value['premium_type'] == 3) )) { // echo $emp_data['name']; $emp_data['policy_details']['basic_cover_si'] = $slab_value['si']; @@ -1292,10 +1293,12 @@ if (!function_exists('premium_calculation_manager')) case "7": //GMC - Employees + Dependent Age + SI $employee_received_si = $default_si == null ? $emp_data['policy_details']['basic_cover_si'] : $default_si; + $temp_date = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']); + $age = calculate_days_bw_dates(from_date: $emp_data['dob'],to_date: $temp_date)->y; foreach ($temp_slab_rates as $skey => $slab_value) { - $age = calculate_days_bw_dates(from_date: $emp_data['dob'])->y; - if($slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'] && ($slab_value['age_from'] <= $age && $slab_value['age_to'] >= $age) && (($slab_value['premium_type'] == 1 && ( strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['acting_self'] ) ) || ($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null) )) + + if($slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'] && ($slab_value['age_from'] <= $age && $slab_value['age_to'] >= $age) && (($slab_value['premium_type'] == 1 && ( strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['acting_self'] ) ) || ($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null || $slab_value['premium_type'] == 3) )) { $emp_data['policy_details']['basic_cover_si'] = $slab_value['si']; $emp_data['policy_details']['date_coverage'] = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']); @@ -1317,7 +1320,7 @@ if (!function_exists('premium_calculation_manager')) foreach ($temp_slab_rates as $skey => $slab_value) { - if($slab_value['grade'] == $employee_received_band && $slab_value['unit'] == $emp_data['unit'] && $slab_value['si'] == $employee_received_si && (($slab_value['premium_type'] == 1 && ( strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['acting_self'] ) ) || ($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null) )) + if($slab_value['grade'] == $employee_received_band && $slab_value['unit'] == $emp_data['unit'] && $slab_value['si'] == $employee_received_si && (($slab_value['premium_type'] == 1 && ( strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['acting_self'] ) ) || ($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null || $slab_value['premium_type'] == 3) )) { // $emp_data['policy_details']['basic_cover_si'] = $slab_value['si']; $emp_data['policy_details']['basic_cover_si'] = $slab_value['si']; @@ -1339,7 +1342,7 @@ if (!function_exists('premium_calculation_manager')) foreach ($temp_slab_rates as $skey => $slab_value) { - if($slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'] && (($slab_value['premium_type'] == 1 && ( strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['acting_self'] )) || ($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null) )) + if($slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'] && (($slab_value['premium_type'] == 1 && ( strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['acting_self'] )) || ($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null || $slab_value['premium_type'] == 3) )) { $emp_data['policy_details']['basic_cover_si'] = $slab_value['si']; $emp_data['policy_details']['date_coverage'] = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']); @@ -1366,7 +1369,7 @@ if (!function_exists('premium_calculation_manager')) if( $slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'] && ($slab_value['age_from'] <= $max_age && $slab_value['age_to'] >= $max_age) && (($slab_value['premium_type'] == 1 && - ( strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['acting_self'] )) || ($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null) ) ) + ( strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['acting_self'] )) || ($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null || $slab_value['premium_type'] == 3) ) ) { $emp_data['policy_details']['basic_cover_si'] = $employee_received_si; $emp_data['policy_details']['date_coverage'] = isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']; @@ -1391,7 +1394,7 @@ if (!function_exists('premium_calculation_manager')) { if($slab_value['si'] == $employee_received_si && $slab_value['grade'] == $employee_received_band && $slab_value['unit'] == $emp_data['unit'] && (($slab_value['premium_type'] == 1 && - ( strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['acting_self'] )) || ($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null) )) + ( strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['acting_self'] )) || ($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null || $slab_value['premium_type'] == 3) )) { //calculate premium based on count // echo $emp_data['name']; @@ -1420,7 +1423,7 @@ if (!function_exists('premium_calculation_manager')) $emp_data['policy_details']['basic_cover_si'] = null; foreach ($temp_slab_rates as $skey => $slab_value) { - if( $slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'] && ((($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null) && $slab_value['relationship'] == $employee_relationship) || ($slab_value['premium_type'] == 1 && ( strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['acting_self'] ) )) ) + if( $slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'] && ((($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null || $slab_value['premium_type'] == 3) && $slab_value['relationship'] == $employee_relationship) || ($slab_value['premium_type'] == 1 && ( strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['acting_self'] ) )) ) { $emp_data['policy_details']['basic_cover_si'] = $employee_received_si; @@ -1442,10 +1445,11 @@ if (!function_exists('premium_calculation_manager')) $employee_relationship = $slug->slugify($emp_data['relationship']); $employee_relationship = ($employee_relationship == 'daughter' || $employee_relationship == 'son' ? $employee_relationship = 'child' : $employee_relationship); $emp_data['policy_details']['basic_cover_si'] = null; - $age = calculate_days_bw_dates(from_date: $emp_data['dob'])->y; + $temp_date = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']); + $age = calculate_days_bw_dates(from_date: $emp_data['dob'],to_date: $temp_date)->y; foreach ($temp_slab_rates as $skey => $slab_value) { - if( $slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'] && ($slab_value['age_from'] <= $age && $slab_value['age_to'] >= $age) && ((($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null) && $slab_value['relationship'] == $employee_relationship) || ($slab_value['premium_type'] == 1 && ( strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['acting_self'] ) )) ) + if( $slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'] && ($slab_value['age_from'] <= $age && $slab_value['age_to'] >= $age) && ((($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null || $slab_value['premium_type'] == 3) && $slab_value['relationship'] == $employee_relationship) || ($slab_value['premium_type'] == 1 && ( strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['acting_self'] ) )) ) { $emp_data['policy_details']['basic_cover_si'] = $employee_received_si; @@ -1466,9 +1470,17 @@ if (!function_exists('premium_calculation_manager')) default: $myLogger->logme('error',($emp_data['emp_code'].'-'.$emp_data['name'].' - grid type not found')); } + + //this if condition for premium calculated & premium type 3 (familiy floater but premium calculated every individual implemented later) then remove si amount only for dependents (not self) + if($is_match_found && strtolower($emp_data['relationship']) != 'self' && $temp_slab_rates[0]['premium_type'] == 3) + { + //set dependent si to 0 + $emp_data['policy_details']['basic_cover_si'] = 0; + } if(!$is_match_found) { - $age = calculate_days_bw_dates(from_date: $emp_data['dob'])->y; + $temp_date = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']); + $age = calculate_days_bw_dates(from_date: $emp_data['dob'],to_date: $temp_date)->y; $log_message = '[ client_policy_id : ' .$emp_data['policy_details']['client_policy_id'].' - '. $emp_data['emp_code'].' - '.$emp_data['name'] .' - '. $emp_data['policy_details']['basic_cover_si'] . ', Age : '. $age.' ]'; if($temp_slab_rates[0]['premium_type'] == 1) { @@ -1480,6 +1492,7 @@ if (!function_exists('premium_calculation_manager')) $emp_data['policy_details']['rata_premimum'] = 0; $emp_data['policy_details']['gst'] = 0; $emp_data['policy_details']['days'] = 0; + $emp_data['policy_details']['policy_end_date'] = $policy_terms['policy_end_date']; } else { $log_message .= '- skipping, slab rate not found'; } $myLogger->logme('error',$log_message); @@ -1553,6 +1566,7 @@ if (!function_exists('transform_db_data_to_excel')) $row['temp']['emp_status'] = $value['emp_status']; $row['temp']['policy_status'] = $value['status']; $row['temp']['rata_premimum'] = $value['rata_premimum']; + $row['temp']['file_id'] = $value['file_id']; array_push($return_data, ($row)); } @@ -1719,6 +1733,21 @@ if(!function_exists('check_dup_mobileno')) } } +if(!function_exists('check_dup_email')) +{ + function check_dup_email(array $row,array $existing_mobilenos) + { + foreach($existing_mobilenos as $k => $value) + { + if ($row['13'] == $value['email_corporate']) { + return array('status' => false,'error' => "Duplicate Email"); + // break; + } + } + return array('status' => true); + } +} + if(!function_exists('generate_family_relationship_array')) { function generate_family_relationship_array($family_structure_from_policy_terms) { diff --git a/app/Helpers/sendMailNotification.php b/app/Helpers/sendMailNotification.php index fbc374a8..2615b1fc 100755 --- a/app/Helpers/sendMailNotification.php +++ b/app/Helpers/sendMailNotification.php @@ -17,11 +17,13 @@ class sendMailNotification public static function sendMailNotification($action, $params) { $wholeData =[]; + if ($action == 'member_welcome_mail') { $dataToInsert = $params['dataToInsert']; $notification = $params['notification']; $client_data = $params['client_data']; + $common = $params['common']; $mailAttachmentModel = new MailAttachmentModel(); $attachment_data = $mailAttachmentModel @@ -42,6 +44,7 @@ class sendMailNotification $subject = $notification['subject']; $app_link = $_ENV['App_Url']; $employee_name =$dataToInsert['name']; + $employee_mobile_no =$dataToInsert['mobile']; $mail_content = $notification['mail_content']; $nhance_logo = $_ENV['NHANCE_LOGO']; $client_logo = base_url() . "public/uploads/logo/" . $client_data['client_logo']; @@ -49,11 +52,12 @@ class sendMailNotification $mail_content = str_replace("[[client_logo]]", "Client Logo", $mail_content); $mail_content = str_replace("[[nhance_logo]]", "Nhance Logo", $mail_content); $mail_content = str_replace("[[member_name]]", $employee_name, $mail_content); + $mail_content = str_replace("[[member_mobile]]", $employee_mobile_no, $mail_content); $mail_content = str_replace("[[client_name]]", $client_data['client_name'], $mail_content); $mail_content = str_replace("[[app_link]]", "Review Details", $mail_content); if ($dataToInsert['relationship'] == 'Self' && $mail != null || $mail != '') { - $wholeData = ['mail' => $mail, 'subject' => $subject,'message'=> $mail_content,'bcc'=> $client_data['common_mails'], 'reply_to' => $client_data['reply_to'], 'attachments' => $attachments]; + $wholeData = ['mail' => $mail, 'subject' => $subject,'message'=> $mail_content,'bcc'=> $client_data['common_mails'], 'reply_to' => $client_data['reply_to'], 'attachments' => $attachments, 'common' => $common]; } return $wholeData; @@ -64,6 +68,7 @@ class sendMailNotification $emp_data = $params['emp_data']; $notification_data = $params['notification_data']; $client_data = $params['client_data']; + $common = $params['common']; $subject = $notification_data['subject']; $app_link = $_ENV['App_Url']; @@ -76,68 +81,18 @@ class sendMailNotification $mail_content = str_replace("[[nhance_logo]]", "Nhance Logo", $mail_content); $mail_content = str_replace("[[client_logo]]", "Client Logo", $mail_content); $mail_content = str_replace("[[app_link]]", "Review Details", $mail_content); - if ($emp_data && (isset($notification_data) && $notification_data['enabled'] == 1)) { - if(isset($emp_data['relationship'])){ - if ($emp_data['relationship'] == 'Self') { - if(count($emp_data) > 0){ - $mail =''; - if ($emp_data['relationship'] == 'Self') { - $employee_name =$emp_data['name']; - $mail_content = str_replace("[[member_name]]", $employee_name, $mail_content); - $mail = $emp_data['email_corporate']; - } - } - }else{ - $mail =''; - } - - }else{ - $employee_name =$emp_data['name']; - $mail_content = str_replace("[[member_name]]", $employee_name, $mail_content); - $mail = $emp_data['email_corporate']; - } - - if (isset($mail) && !empty($mail)) { - $wholeData[] = ['mail' => $mail, 'subject' => $subject,'message'=> $mail_content, 'bcc'=> $client_data['common_mails'], 'reply_to' => $client_data['reply_to']]; - } + - }else{ - - foreach ($emp_data as $key => $value) { - if ($value['relationship'] != 'Self') { - $emp_data = $EmployeeModel->where('client_id', $client_data['id'])->where('emp_code', $value['emp_code'])->where('is_active',1)->findAll(); - if(count($emp_data) > 1){ - $mail =''; - foreach ($emp_data as $key => $values) { - if ($value['relationship'] == 'Self') { - $employee_name =$values['name']; - $mail_content = str_replace("[[member_name]]", $employee_name, $mail_content); - $mail = $values['email_corporate']; - } - } - }else{ - $mail =''; - } - }else{ - $employee_name =$value['name']; - $mail_content = str_replace("[[member_name]]", $employee_name, $mail_content); - $mail = $value['email_corporate']; - } - if (isset($mail) && !empty($mail)) { - $wholeData[] = ['mail' => $mail, 'subject' => $subject,'message'=> $mail_content, 'bcc'=> $client_data['common_mails'], 'reply_to' => $client_data['reply_to']]; - } - } - } + $employee_name =$emp_data['name']; + $employee_mobile_no =$emp_data['mobile']; + $mail_content = str_replace("[[member_name]]", $employee_name, $mail_content); + $mail_content = str_replace("[[member_mobile]]", $employee_mobile_no, $mail_content); + $mail = $emp_data['email_corporate']; - if (count($wholeData) < 1) { - $wholeData = []; - } + $wholeData = ['mail' => $mail, 'subject' => $subject,'message'=> $mail_content, 'bcc'=> $client_data['common_mails'], 'reply_to' => $client_data['reply_to'], 'common' => $common]; return $wholeData; - // }else{ - // return "false"; - // } } else if($action == 'member_ecard_mail'){ @@ -146,6 +101,7 @@ class sendMailNotification $rand_string = $params['rand_string']; $client_data = $params['client_data']; $tpa_id = $params['tpa_id']; + $common = $params['common']; $mail_content = $notification['mail_content']; @@ -161,6 +117,7 @@ class sendMailNotification $app_link = $_ENV['App_Url']; $name = $get_emp_email_and_other_details['name']; + $employee_mobile_no = $get_emp_email_and_other_details['mobile']; $mail_content = $notification['mail_content']; $nhance_logo = $_ENV['NHANCE_LOGO']; @@ -175,12 +132,13 @@ class sendMailNotification $mail_content = str_replace("[[client_logo]]", "Client Logo", $mail_content); $mail_content = str_replace("[[member_name]]", $name, $mail_content); + $mail_content = str_replace("[[member_mobile]]", $employee_mobile_no, $mail_content); $mail_content = str_replace("[[app_link]]", "Review Details", $mail_content); $mail_content = str_replace("[[post_enrollment_app_link]]", "Review Details", $mail_content); // $mail_content = str_replace("[[tpa_id]]", $tpa_id, $mail_content); $mail_content = str_replace("[[ecard_download_link]]", "Download Insurance Card", $mail_content); $mail_content = str_replace("[[client_name]]", $client_data['client_name'], $mail_content); - $wholeData = ['mail' => $mail, 'subject' => $subject,'message'=> $mail_content,'bcc'=> $client_data['common_mails'], 'reply_to' => $client_data['reply_to']]; + $wholeData = ['mail' => $mail, 'subject' => $subject,'message'=> $mail_content,'bcc'=> $client_data['common_mails'], 'reply_to' => $client_data['reply_to'], 'common' => $common]; return $wholeData; @@ -190,6 +148,7 @@ class sendMailNotification $client_policy_id = $params['client_policy_id']; $emp_code = $params['emp_code']; $client_id = $params['client_id']; + $common = $params['common']; $clientModel = new ClientModel(); $notificationModel = new NotificationModel(); @@ -226,20 +185,25 @@ class sendMailNotification $gst = 0; $Addon_list = []; $name = ''; + $employee_mobile_no = ''; $emp_code = ''; // echo '
';
                 // print_r($array_list); die;
 
-                foreach ($array_list as $item) {
-                    
+               
 
+                foreach ($array_list as $item) {
+
+                    $payable_employee_array = [];
+                    
                     if (count($item) != 0) {
 
                         $table_content .= '

Policy Type :'; $temp_data = ''; $policy_name = ''; $is_addon = ''; + $rowspan = count($item) ?? 2; foreach ($item as $inner_item) { @@ -252,30 +216,55 @@ class sendMailNotification } //end of getting policy premium data + // dd($policy_premium_data); + + if($inner_item['payable_employee'] == 1 && $client_policy_data['policy_type_id'] == 2){ + $payable_employee_array['emp_data'][] = $inner_item; + } + + // dd($policy_premium_data); + $policy_name = $inner_item['policy_name']; if ($inner_item['relationship'] == 'Self') { $emp_code = '(' . $inner_item['emp_code'] . ')'; $mail = $inner_item['email_corporate']; $name = $inner_item['name']; + $employee_mobile_no = $inner_item['mobile']; } $si = ''; $premium = ''; $gst_forself = ''; - if(checkFamilyFloaters($policy_premium_data, $client_policy_data, $inner_item)){ - $si = '₹ ' .format_indian_number($inner_item['basic_cover_si']); - $premium = '₹ ' .format_indian_number(round($inner_item['premium'])); + // if(checkFamilyFloaters($policy_premium_data, $client_policy_data, $inner_item)){ + + if($policy_premium_data['premium_type'] == 2){ + $si = '₹ ' .format_indian_number($inner_item['basic_cover_si']); + }else{ + if ($inner_item['relationship'] == 'Self') { + $payable_employee_array['si_amount'] = $inner_item['basic_cover_si']; + $payable_employee_array['self_premium'] = $inner_item['rata_premimum']; + $payable_employee_array['self_gst'] = $inner_item['gst']; + } + empty($inner_item['basic_cover_si']) ? $si = 0 : $si = '₹ ' .format_indian_number($inner_item['basic_cover_si']); + } + + $premium = '₹ ' .format_indian_number(round($inner_item['rata_premimum'])); $gst_forself = '₹ ' .format_indian_number(round($inner_item['gst'])); - } + // } $temp_data .= ''; $temp_data .= '' . $inner_item['name'] . ($inner_item['relationship'] == 'Self' ? ' (' . $inner_item['emp_code'] . ')' : '') . ''; $temp_data .= '' . $inner_item['relationship'] . ''; $temp_data .= '' . \DateTime::createFromFormat('Y-m-d', $inner_item['dob'])->format('d-m-Y') . ''; - $temp_data .= '' . $si . ''; - + + if($policy_premium_data['premium_type'] == 2){ + $temp_data .= '' . $si . ''; + }else{ + $temp_data .= (($si != 0 && count($item) != 1) ? ('' . $si . '') : ($si == 0 ? "" : '' . $si . '') ); + } + // Only Display SI Topup and Dependent Addon if ($inner_item['is_addon'] == 2 || $inner_item['is_addon'] == 3) { $temp_data .= '' . $premium . ''; @@ -334,6 +323,140 @@ class sendMailNotification $addtional_premium = 0; $gst = 0; } + + // dd($payable_employee_array); + // dd(count($payable_employee_array['emp_data'])); + + if(isset($payable_employee_array['emp_data']) && count($payable_employee_array['emp_data']) > 0){ + + $table_content .= '

Policy Type :'; + $temp_data = ''; + $is_addon = ''; + $rowspan = count($payable_employee_array['emp_data']) ?? 2; + + $self_si_amount = $payable_employee_array['si_amount'] ?? 0; + $self_premium = $payable_employee_array['self_premium'] ?? 0; + $self_gst = $payable_employee_array['self_gst'] ?? 0; + + + // dd($payable_employee_array['si_amount'], $self_si_amount); + + foreach ($payable_employee_array['emp_data'] as $inner_item) { + + //getting policy premium data + $client_policy_data = $clientPolicyModel->where('id', $inner_item['client_policy_id'])->first(); + if($client_policy_data['policy_type_id'] == 1 || $client_policy_data['policy_type_id'] == 6 || $client_policy_data['policy_type_id'] == 7 ){ + $policy_premium_data = $PolicyPremium1Model->where('client_policy_id', $inner_item['client_policy_id'])->where('is_active', '1')->first(); + }else{ + $policy_premium_data = $PolicyPremium2Model->where('client_policy_id', $inner_item['client_policy_id'])->where('is_active', '1')->first(); + } + //end of getting policy premium data + + // dd($policy_premium_data); + + $si = ''; + $premium = ''; + $gst_forself = ''; + + if($policy_premium_data['premium_type'] == 2){ + $si = '₹ ' .format_indian_number($inner_item['basic_cover_si']); + }else{ + empty($self_si_amount) ? $si = 0 : $si = '₹ ' .format_indian_number($self_si_amount); + } + + if($policy_premium_data['premium_type'] == 1){ + + empty($self_premium) ? $premium = 0 : $premium = '₹ ' .format_indian_number($self_premium); + empty($self_gst) ? $gst_forself = 0 : $gst_forself = '₹ ' .format_indian_number($self_gst); + + }else{ + + $premium = '₹ ' .format_indian_number(round($inner_item['rata_premimum'])); + $gst_forself = '₹ ' .format_indian_number(round($inner_item['gst'])); + + } + + $temp_data .= ''; + $temp_data .= '' . $inner_item['name'] . ($inner_item['relationship'] == 'Self' ? ' (' . $inner_item['emp_code'] . ')' : '') . ''; + $temp_data .= '' . $inner_item['relationship'] . ''; + $temp_data .= '' . \DateTime::createFromFormat('Y-m-d', $inner_item['dob'])->format('d-m-Y') . ''; + + // dd($si); + + if($policy_premium_data['premium_type'] == 2){ + + $temp_data .= '' . $si . ''; + $temp_data .= '' . $premium . ''; + $temp_data .= '' . $gst_forself . ''; + + }else{ + + if($policy_premium_data['premium_type'] == 1){ + + $temp_data .= (($si != 0 && count($item) != 1) ? ('' . $si . '') : ($si == 0 ? "" : '' . $si . '') ); + $temp_data .= (($premium != 0 && count($item) != 1) ? ('' . $premium . '') : ($premium == 0 ? "" : '' . $premium . '') ); + $temp_data .= (($gst_forself != 0 && count($item) != 1) ? ('' . $gst_forself . '') : ($gst_forself == 0 ? "" : '' . $gst_forself . '') ); + + }else{ + + $temp_data .= (($si != 0 && count($item) != 1) ? ('' . $si . '') : ($si == 0 ? "" : '' . $si . '') ); + $temp_data .= '' . $premium . ''; + $temp_data .= '' . $gst_forself . ''; + } + + $self_si_amount = 0; + $self_premium = 0; + $self_gst = 0; + } + + + $temp_data .= ''; + + $is_addon = $inner_item['is_addon']; + + $addtional_premium = $inner_item['rata_premimum'] + $addtional_premium; + $gst = $inner_item['gst'] + $gst; + } + + $policy_name_for_policy_type = $inner_item['policy_name']; + if($client_policy_data['policy_type_id'] == 3 && $client_policy_data['is_addon'] == 3){ + $policy_name_for_policy_type = 'Add-On Group Medical Coverage for Parents'; + } + + $table_content .= $policy_name_for_policy_type . ' ( Payable By Employee )

'; + $table_content .= ''; + + // Add text-align: center to the table head + $table_content .= ''; + $table_content .= ''; + $table_content .= ''; + $table_content .= ''; + $table_content .= ''; + $table_content .= ''; + $table_content .= ''; + $table_content .= ''; + + $table_content .= ''; + $table_content .= ''; + + // Add text-align: center to the table body + $table_content .= '' . $temp_data . ''; + $table_content .= '
NameRelationDate Of BirthSum InsuredPremiumGST
'; + + + $addon_list_array = [ + 'policy_name' => $policy_name_for_policy_type . '( Payable By Employee )', + 'addtional_premium' => round($addtional_premium), + 'gst' => round($gst) + ]; + $Addon_list[] = $addon_list_array; + + + $temp_data = ''; + $addtional_premium = 0; + $gst = 0; + + } } if (count($Addon_list) > 0) { @@ -375,16 +498,18 @@ class sendMailNotification // $table_content .= '
' . $sum_total_words . '
'; } + // dd($payable_employee_array, $Addon_list); // print_r($table_content); die; $mail_content = str_replace("[[member_name]]", $name . ' (' . $emp_code . ')' , $mail_content); + $mail_content = str_replace("[[member_mobile]]", $employee_mobile_no, $mail_content); $mail_content = str_replace("[[member_summary]]", $table_content , $mail_content); // print_r($mail_content); die; // $mail = "aadhavanvalli@gmail.com"; // if (isset($mail) && !empty($mail)) { - $wholeData[] = ['mail' => $mail, 'subject' => $subject,'message'=> $mail_content, 'bcc'=> $client_data['common_mails'], 'reply_to' => $client_data['reply_to']]; + $wholeData[] = ['mail' => $mail, 'subject' => $subject,'message'=> $mail_content, 'bcc'=> $client_data['common_mails'], 'reply_to' => $client_data['reply_to'], 'common' => $common]; // } return $wholeData; @@ -395,6 +520,7 @@ class sendMailNotification $client_id = $params['client_id']; $client_policy_id = $params['client_policy_id']; + $common = $params['common']; $clientModel = new ClientModel(); $notificationModel = new NotificationModel(); @@ -442,6 +568,9 @@ class sendMailNotification $Addon_list = []; foreach ($array_list as $item) { + + $payable_employee_array = []; + if (count($item) != 0) { $table_content .= '

Policy Type :'; $temp_data = ''; @@ -459,6 +588,10 @@ class sendMailNotification } //end of getting policy premium data + if($inner_item['payable_employee'] == 1 && $client_policy_data['policy_type_id'] == 2){ + $payable_employee_array[] = $inner_item; + } + $policy_name = $inner_item['policy_name']; if ($inner_item['relationship'] == 'Self') { @@ -470,11 +603,11 @@ class sendMailNotification $si = ''; $premium = ''; $gst_forself = ''; - if(checkFamilyFloaters($policy_premium_data, $client_policy_data, $inner_item)){ + // if(checkFamilyFloaters($policy_premium_data, $client_policy_data, $inner_item)){ $si = '₹ ' .format_indian_number($inner_item['basic_cover_si']); $premium = '₹ ' .format_indian_number(round($inner_item['premium'])); $gst_forself = '₹ ' .format_indian_number(round($inner_item['gst'])); - } + // } $temp_data .= ''; $temp_data .= '' . $inner_item['name'] . $emp_code . ''; @@ -540,6 +673,90 @@ class sendMailNotification $addtional_premium = 0; $gst = 0; } + + if(count($payable_employee_array) > 0){ + + $table_content .= '

Policy Type :'; + $temp_data = ''; + $is_addon = ''; + + foreach ($payable_employee_array as $inner_item) { + + + //getting policy premium data + $client_policy_data = $clientPolicyModel->where('id', $inner_item['client_policy_id'])->first(); + if($client_policy_data['policy_type_id'] == 1 || $client_policy_data['policy_type_id'] == 6 || $client_policy_data['policy_type_id'] == 7 ){ + $policy_premium_data = $PolicyPremium1Model->where('client_policy_id', $inner_item['client_policy_id'])->where('is_active', '1')->first(); + }else{ + $policy_premium_data = $PolicyPremium2Model->where('client_policy_id', $inner_item['client_policy_id'])->where('is_active', '1')->first(); + } + //end of getting policy premium data + + + $si = ''; + $premium = ''; + $gst_forself = ''; + + $si = '₹ ' .format_indian_number($inner_item['basic_cover_si']); + $premium = '₹ ' .format_indian_number(round($inner_item['rata_premimum'])); + $gst_forself = '₹ ' .format_indian_number(round($inner_item['gst'])); + + $temp_data .= ''; + $temp_data .= '' . $inner_item['name'] . ($inner_item['relationship'] == 'Self' ? ' (' . $inner_item['emp_code'] . ')' : '') . ''; + $temp_data .= '' . $inner_item['relationship'] . ''; + $temp_data .= '' . \DateTime::createFromFormat('Y-m-d', $inner_item['dob'])->format('d-m-Y') . ''; + $temp_data .= '' . $si . ''; + $temp_data .= '' . $premium . ''; + $temp_data .= '' . $gst_forself . ''; + + $temp_data .= ''; + + $is_addon = $inner_item['is_addon']; + + $addtional_premium = $inner_item['rata_premimum'] + $addtional_premium; + $gst = $inner_item['gst'] + $gst; + } + + $policy_name_for_policy_type = $inner_item['policy_name']; + if($client_policy_data['policy_type_id'] == 3 && $client_policy_data['is_addon'] == 3){ + $policy_name_for_policy_type = 'Add-On Group Medical Coverage for Parents'; + } + + $table_content .= $policy_name_for_policy_type . ' ( Payable By Employee )

'; + $table_content .= ''; + + // Add text-align: center to the table head + $table_content .= ''; + $table_content .= ''; + $table_content .= ''; + $table_content .= ''; + $table_content .= ''; + $table_content .= ''; + $table_content .= ''; + $table_content .= ''; + + $table_content .= ''; + $table_content .= ''; + + // Add text-align: center to the table body + $table_content .= '' . $temp_data . ''; + $table_content .= '
NameRelationDate Of BirthSum InsuredPremiumGST
'; + + + $addon_list_array = [ + 'policy_name' => $policy_name_for_policy_type . '( Payable By Employee )', + 'addtional_premium' => round($addtional_premium), + 'gst' => round($gst) + ]; + $Addon_list[] = $addon_list_array; + + + $temp_data = ''; + $addtional_premium = 0; + $gst = 0; + + } + } if (count($Addon_list) > 0) { @@ -590,7 +807,7 @@ class sendMailNotification $full_name = $value['first_name'] .' ' .$value['last_name']; $mail_content = str_replace("[[member_name]]", $full_name , $mail_content); - $wholeData[] = ['mail' => $value['email'], 'subject' => $subject,'message'=> $mail_content, 'reply_to' => $client_data['reply_to']]; + $wholeData[] = ['mail' => $value['email'], 'subject' => $subject,'message'=> $mail_content, 'reply_to' => $client_data['reply_to'], 'common' => $common]; // $wholeData[] = ['mail' => $value['email'], 'subject' => $subject,'message'=> $mail_content, 'bcc'=> $client_data['common_mails']]; } return $wholeData; @@ -600,6 +817,7 @@ class sendMailNotification $client_id = $params['client_id']; $client_policy_id = $params['client_policy_id']; + $common = $params['common']; $clientModel = new ClientModel(); $clientPolicyModel = new ClientPolicyModel(); @@ -646,8 +864,11 @@ class sendMailNotification $gst = 0; $array_list = $params['array_list']; $Addon_list = []; - + foreach ($array_list as $item) { + + $payable_employee_array = []; + if (count($item) != 0) { $table_content .= '

Policy Type :'; $temp_data = ''; @@ -665,6 +886,10 @@ class sendMailNotification } //end of getting policy premium data + if($inner_item['payable_employee'] == 1 && $client_policy_data['policy_type_id'] == 2){ + $payable_employee_array[] = $inner_item; + } + $policy_name = $inner_item['policy_name']; if ($inner_item['relationship'] == 'Self') { @@ -679,11 +904,11 @@ class sendMailNotification // dd($policy_premium_data, $client_policy_data, $inner_item); - if(checkFamilyFloaters($policy_premium_data, $client_policy_data, $inner_item)){ + // if(checkFamilyFloaters($policy_premium_data, $client_policy_data, $inner_item)){ $si = '₹ ' .format_indian_number($inner_item['basic_cover_si']); $premium = '₹ ' .format_indian_number(round($inner_item['premium'])); $gst_forself = '₹ ' .format_indian_number(round($inner_item['gst'])); - } + // } $temp_data .= ''; $temp_data .= '' . $inner_item['name'] . $emp_code . ''; @@ -749,6 +974,89 @@ class sendMailNotification $addtional_premium = 0; $gst = 0; } + + if(count($payable_employee_array) > 0){ + + $table_content .= '

Policy Type :'; + $temp_data = ''; + $is_addon = ''; + + foreach ($payable_employee_array as $inner_item) { + + + //getting policy premium data + $client_policy_data = $clientPolicyModel->where('id', $inner_item['client_policy_id'])->first(); + if($client_policy_data['policy_type_id'] == 1 || $client_policy_data['policy_type_id'] == 6 || $client_policy_data['policy_type_id'] == 7 ){ + $policy_premium_data = $PolicyPremium1Model->where('client_policy_id', $inner_item['client_policy_id'])->where('is_active', '1')->first(); + }else{ + $policy_premium_data = $PolicyPremium2Model->where('client_policy_id', $inner_item['client_policy_id'])->where('is_active', '1')->first(); + } + //end of getting policy premium data + + + $si = ''; + $premium = ''; + $gst_forself = ''; + + $si = '₹ ' .format_indian_number($inner_item['basic_cover_si']); + $premium = '₹ ' .format_indian_number(round($inner_item['rata_premimum'])); + $gst_forself = '₹ ' .format_indian_number(round($inner_item['gst'])); + + $temp_data .= ''; + $temp_data .= '' . $inner_item['name'] . ($inner_item['relationship'] == 'Self' ? ' (' . $inner_item['emp_code'] . ')' : '') . ''; + $temp_data .= '' . $inner_item['relationship'] . ''; + $temp_data .= '' . \DateTime::createFromFormat('Y-m-d', $inner_item['dob'])->format('d-m-Y') . ''; + $temp_data .= '' . $si . ''; + $temp_data .= '' . $premium . ''; + $temp_data .= '' . $gst_forself . ''; + + $temp_data .= ''; + + $is_addon = $inner_item['is_addon']; + + $addtional_premium = $inner_item['rata_premimum'] + $addtional_premium; + $gst = $inner_item['gst'] + $gst; + } + + $policy_name_for_policy_type = $inner_item['policy_name']; + if($client_policy_data['policy_type_id'] == 3 && $client_policy_data['is_addon'] == 3){ + $policy_name_for_policy_type = 'Add-On Group Medical Coverage for Parents'; + } + + $table_content .= $policy_name_for_policy_type . ' ( Payable By Employee )

'; + $table_content .= ''; + + // Add text-align: center to the table head + $table_content .= ''; + $table_content .= ''; + $table_content .= ''; + $table_content .= ''; + $table_content .= ''; + $table_content .= ''; + $table_content .= ''; + $table_content .= ''; + + $table_content .= ''; + $table_content .= ''; + + // Add text-align: center to the table body + $table_content .= '' . $temp_data . ''; + $table_content .= '
NameRelationDate Of BirthSum InsuredPremiumGST
'; + + + $addon_list_array = [ + 'policy_name' => $policy_name_for_policy_type . '( Payable By Employee )', + 'addtional_premium' => round($addtional_premium), + 'gst' => round($gst) + ]; + $Addon_list[] = $addon_list_array; + + + $temp_data = ''; + $addtional_premium = 0; + $gst = 0; + + } } if (count($Addon_list) > 0) { @@ -798,7 +1106,7 @@ class sendMailNotification $mail_array = array_map('trim', $mail_array); $wholeData = []; foreach ($mail_array as $key => $value) { - $wholeData[] = ['mail' => $value, 'subject' => $subject,'message'=> $mail_content, 'reply_to' => $client_data['reply_to']]; + $wholeData[] = ['mail' => $value, 'subject' => $subject,'message'=> $mail_content, 'reply_to' => $client_data['reply_to'], 'common' => $common]; // $wholeData[] = ['mail' => $value, 'subject' => $subject,'message'=> $mail_content, 'bcc'=> $client_data['common_mails']]; } @@ -841,6 +1149,7 @@ class sendMailNotification // print_r($attachments); die; $employee_name = 'John Doe'; + $mobile = 9080706050; $app_link = $_ENV['App_Url']; $nhance_logo = $_ENV['NHANCE_LOGO']; @@ -850,6 +1159,7 @@ class sendMailNotification $mail_content = str_replace("[[client_logo]]", "Client Logo", $mail_content); $mail_content = str_replace("[[nhance_logo]]", "Nhance Logo", $mail_content); $mail_content = str_replace("[[member_name]]", $employee_name, $mail_content); + $mail_content = str_replace("[[member_mobile]]", $mobile, $mail_content); $mail_content = str_replace("[[client_name]]", $client_data['client_name'], $mail_content); $mail_content = str_replace("[[app_link]]", "Review Details", $mail_content); @@ -873,6 +1183,7 @@ class sendMailNotification $app_link = $_ENV['App_Url']; $employee_name = 'John Doe'; + $mobile = 9080706050; $client_logo = base_url() . "public/uploads/logo/" . $client_data['client_logo']; @@ -880,6 +1191,7 @@ class sendMailNotification $mail_content = str_replace("[[nhance_logo]]", "Nhance Logo", $mail_content); $mail_content = str_replace("[[client_logo]]", "Client Logo", $mail_content); $mail_content = str_replace("[[app_link]]", "Review Details", $mail_content); + $mail_content = str_replace("[[member_mobile]]", $mobile, $mail_content); if ((isset($notification_data) && $notification_data['enabled'] == 1)) { @@ -905,6 +1217,7 @@ class sendMailNotification $link = generate_download_link($rand_string); $name = 'John Doe'; + $mobile = 9080706050; $nhance_logo = $_ENV['NHANCE_LOGO']; $app_link = $_ENV['App_Url']; @@ -916,6 +1229,7 @@ class sendMailNotification $mail_content = str_replace("[[client_logo]]", "Client Logo", $mail_content); $mail_content = str_replace("[[member_name]]", $name, $mail_content); + $mail_content = str_replace("[[member_mobile]]", $mobile, $mail_content); $mail_content = str_replace("[[app_link]]", "Review Details", $mail_content); $mail_content = str_replace("[[post_enrollment_app_link]]", "Review Details", $mail_content); $mail_content = str_replace("[[ecard_download_link]]", "Download Insurance Card", $mail_content); @@ -937,7 +1251,8 @@ class sendMailNotification 'premium' => 12000, 'gst' => 2160, 'rata_premimum' => 12000, - 'is_addon' => 2 + 'is_addon' => 2, + 'mobile' => 9080706050 ]; @@ -967,6 +1282,7 @@ class sendMailNotification $gst = 0; $Addon_list = []; $name = $array_list['name']; + $mobile = $array_list['mobile']; $emp_code = ''; if (!empty($array_list)) { @@ -987,9 +1303,9 @@ class sendMailNotification $table_content .= ''; $table_content .= ''; $table_content .= 'Name'; - $table_content .= 'Relation'; - $table_content .= 'Date Of Birth'; - $table_content .= 'Sum Insured'; + $table_content .= 'Relation'; + $table_content .= 'Date Of Birth'; + $table_content .= 'Sum Insured'; // Only Display SI Topup and Dependent Addon if ($array_list['is_addon'] == 2 || $array_list['is_addon'] == 3) { @@ -1003,14 +1319,14 @@ class sendMailNotification // Table body with details $table_content .= ''; $table_content .= ''; - $table_content .= '' . $array_list['name'] . $emp_code . ''; - $table_content .= '' . $array_list['relationship'] . ''; - $table_content .= '' . \DateTime::createFromFormat('Y-m-d', $array_list['dob'])->format('d-m-Y') . ''; - $table_content .= '₹' . format_indian_number($array_list['basic_cover_si']) . ''; + $table_content .= '' . nl2br(wordwrap($array_list['name'] . $emp_code, 11, "\n", true)) . ''; + $table_content .= '' . $array_list['relationship'] . ''; + $table_content .= '' . \DateTime::createFromFormat('Y-m-d', $array_list['dob'])->format('d-m-Y') . ''; + $table_content .= '₹' . format_indian_number($array_list['basic_cover_si']) . ''; if ($array_list['is_addon'] == 2 || $array_list['is_addon'] == 3) { - $table_content .= '₹' . format_indian_number(round($array_list['premium'])) . ''; - $table_content .= '₹' . format_indian_number(round($array_list['gst'])) . ''; + $table_content .= '₹' . format_indian_number(round($array_list['premium'])) . ''; + $table_content .= '₹' . format_indian_number(round($array_list['gst'])) . ''; } $table_content .= ''; @@ -1039,10 +1355,10 @@ class sendMailNotification $table_content .= ''; $table_content .= ''; - $table_content .= 'Policy Name'; - $table_content .= 'Additional Premium'; - $table_content .= 'GST'; - $table_content .= 'Total'; + $table_content .= 'Policy Name'; + $table_content .= 'Additional Premium'; + $table_content .= 'GST'; + $table_content .= 'Total'; $table_content .= ''; $table_content .= ''; @@ -1050,16 +1366,16 @@ class sendMailNotification $total_addon = $Addon_list[0]['gst'] + $Addon_list[0]['addtional_premium']; $table_content .= ''; - $table_content .= '' . $Addon_list[0]['policy_name'] . ''; - $table_content .= '₹' . format_indian_number($Addon_list[0]['addtional_premium']) . ''; - $table_content .= '₹' . format_indian_number($Addon_list[0]['gst']) . ''; - $table_content .= '₹' . format_indian_number($total_addon) . ''; + $table_content .= '' . $Addon_list[0]['policy_name'] . ''; + $table_content .= '₹' . format_indian_number($Addon_list[0]['addtional_premium']) . ''; + $table_content .= '₹' . format_indian_number($Addon_list[0]['gst']) . ''; + $table_content .= '₹' . format_indian_number($total_addon) . ''; $table_content .= ''; $sum_total_words = numberToWords($total_addon); $table_content .= ''; $table_content .= 'Total'; - $table_content .= '₹' . format_indian_number($total_addon) . ''; + $table_content .= '₹' . format_indian_number($total_addon) . ''; $table_content .= ''; $table_content .= ''; $table_content .= '

'; @@ -1067,6 +1383,7 @@ class sendMailNotification } $mail_content = str_replace("[[member_name]]", $name . ' (' . $emp_code . ')' , $mail_content); + $mail_content = str_replace("[[member_mobile]]", $mobile, $mail_content); $mail_content = str_replace("[[member_summary]]", $table_content , $mail_content); @@ -1136,14 +1453,14 @@ class sendMailNotification $table_content .= ''; $table_content .= ''; $table_content .= 'Name'; - $table_content .= 'Relation'; - $table_content .= 'Date Of Birth'; - $table_content .= 'Sum Insured'; + $table_content .= 'Relation'; + $table_content .= 'Date Of Birth'; + $table_content .= 'Sum Insured'; // Only Display SI Topup and Dependent Addon if ($array_list['is_addon'] == 2 || $array_list['is_addon'] == 3) { - $table_content .= 'Premium'; - $table_content .= 'GST'; + $table_content .= 'Premium'; + $table_content .= 'GST'; } $table_content .= ''; @@ -1152,14 +1469,14 @@ class sendMailNotification // Table body with details $table_content .= ''; $table_content .= ''; - $table_content .= '' . $array_list['name'] . $emp_code . ''; - $table_content .= '' . $array_list['relationship'] . ''; - $table_content .= '' . \DateTime::createFromFormat('Y-m-d', $array_list['dob'])->format('d-m-Y') . ''; - $table_content .= '₹' . format_indian_number($array_list['basic_cover_si']) . ''; + $table_content .= '' . nl2br(wordwrap($array_list['name'] . $emp_code, 11, "\n", true)) . ''; + $table_content .= '' . $array_list['relationship'] . ''; + $table_content .= '' . \DateTime::createFromFormat('Y-m-d', $array_list['dob'])->format('d-m-Y') . ''; + $table_content .= '₹' . format_indian_number($array_list['basic_cover_si']) . ''; if ($array_list['is_addon'] == 2 || $array_list['is_addon'] == 3) { - $table_content .= '₹' . format_indian_number(round($array_list['premium'])) . ''; - $table_content .= '₹' . format_indian_number(round($array_list['gst'])) . ''; + $table_content .= '₹' . format_indian_number(round($array_list['premium'])) . ''; + $table_content .= '₹' . format_indian_number(round($array_list['gst'])) . ''; } $table_content .= ''; @@ -1188,10 +1505,10 @@ class sendMailNotification $table_content .= ''; $table_content .= ''; - $table_content .= 'Policy Name'; - $table_content .= 'Additional Premium'; - $table_content .= 'GST'; - $table_content .= 'Total'; + $table_content .= 'Policy Name'; + $table_content .= 'Additional Premium'; + $table_content .= 'GST'; + $table_content .= 'Total'; $table_content .= ''; $table_content .= ''; @@ -1199,17 +1516,17 @@ class sendMailNotification $total_addon = $Addon_list[0]['gst'] + $Addon_list[0]['addtional_premium']; $table_content .= ''; - $table_content .= '' . $Addon_list[0]['policy_name'] . ''; - $table_content .= '₹' . format_indian_number($Addon_list[0]['addtional_premium']) . ''; - $table_content .= '₹' . format_indian_number($Addon_list[0]['gst']) . ''; - $table_content .= '₹' . format_indian_number($total_addon) . ''; + $table_content .= '' . $Addon_list[0]['policy_name'] . ''; + $table_content .= '₹' . format_indian_number($Addon_list[0]['addtional_premium']) . ''; + $table_content .= '₹' . format_indian_number($Addon_list[0]['gst']) . ''; + $table_content .= '₹' . format_indian_number($total_addon) . ''; $table_content .= ''; $sum_total_words = numberToWords($total_addon); $table_content .= ''; $table_content .= 'Total'; - $table_content .= '₹' . format_indian_number($total_addon) . ''; - $table_content .= ''; + $table_content .= '₹' . format_indian_number($total_addon) . ''; + $table_content .= ''; $table_content .= ''; $table_content .= '

'; } @@ -1228,7 +1545,7 @@ class sendMailNotification $array_list = [ 'policy_name' => 'Health Insurance Plan', 'emp_code' => 'E12345', - 'name' => 'John Doe', + 'name' => 'Ramakrishnaparamahamsar', 'relationship' => 'Self', 'dob' => '1985-05-15', 'basic_cover_si' => 500000, @@ -1284,14 +1601,14 @@ class sendMailNotification $table_content .= ''; $table_content .= ''; $table_content .= 'Name'; - $table_content .= 'Relation'; - $table_content .= 'Date Of Birth'; - $table_content .= 'Sum Insured'; + $table_content .= 'Relation'; + $table_content .= 'Date Of Birth'; + $table_content .= 'Sum Insured'; // Only Display SI Topup and Dependent Addon if ($array_list['is_addon'] == 2 || $array_list['is_addon'] == 3) { - $table_content .= 'Premium'; - $table_content .= 'GST'; + $table_content .= 'Premium'; + $table_content .= 'GST'; } $table_content .= ''; @@ -1300,14 +1617,14 @@ class sendMailNotification // Table body with details $table_content .= ''; $table_content .= ''; - $table_content .= '' . $array_list['name'] . $emp_code . ''; - $table_content .= '' . $array_list['relationship'] . ''; - $table_content .= '' . \DateTime::createFromFormat('Y-m-d', $array_list['dob'])->format('d-m-Y') . ''; - $table_content .= '₹' . format_indian_number($array_list['basic_cover_si']) . ''; + $table_content .= '' . nl2br(wordwrap($array_list['name'] . $emp_code, 11, "\n", true)) . ''; + $table_content .= '' . $array_list['relationship'] . ''; + $table_content .= '' . \DateTime::createFromFormat('Y-m-d', $array_list['dob'])->format('d-m-Y') . ''; + $table_content .= '₹' . format_indian_number($array_list['basic_cover_si']) . ''; if ($array_list['is_addon'] == 2 || $array_list['is_addon'] == 3) { - $table_content .= '₹' . format_indian_number(round($array_list['premium'])) . ''; - $table_content .= '₹' . format_indian_number(round($array_list['gst'])) . ''; + $table_content .= '₹' . format_indian_number(round($array_list['premium'])) . ''; + $table_content .= '₹' . format_indian_number(round($array_list['gst'])) . ''; } $table_content .= ''; @@ -1337,10 +1654,10 @@ class sendMailNotification $table_content .= ''; $table_content .= ''; - $table_content .= 'Policy Name'; - $table_content .= 'Additional Premium'; - $table_content .= 'GST'; - $table_content .= 'Total'; + $table_content .= 'Policy Name'; + $table_content .= 'Additional Premium'; + $table_content .= 'GST'; + $table_content .= 'Total'; $table_content .= ''; $table_content .= ''; @@ -1348,16 +1665,16 @@ class sendMailNotification $total_addon = $Addon_list[0]['gst'] + $Addon_list[0]['addtional_premium']; $table_content .= ''; - $table_content .= '' . $Addon_list[0]['policy_name'] . ''; - $table_content .= '₹' . format_indian_number($Addon_list[0]['addtional_premium']) . ''; - $table_content .= '₹' . format_indian_number($Addon_list[0]['gst']) . ''; - $table_content .= '₹' . format_indian_number($total_addon) . ''; + $table_content .= '' . $Addon_list[0]['policy_name'] . ''; + $table_content .= '₹' . format_indian_number($Addon_list[0]['addtional_premium']) . ''; + $table_content .= '₹' . format_indian_number($Addon_list[0]['gst']) . ''; + $table_content .= '₹' . format_indian_number($total_addon) . ''; $table_content .= ''; $sum_total_words = numberToWords($total_addon); $table_content .= ''; - $table_content .= 'Total'; - $table_content .= '₹' . format_indian_number($total_addon) . ''; + $table_content .= 'Total'; + $table_content .= '₹' . format_indian_number($total_addon) . ''; $table_content .= ''; $table_content .= ''; $table_content .= '

'; diff --git a/app/Helpers/session_helper.php b/app/Helpers/session_helper.php index 4a13df4d..f5c6e513 100755 --- a/app/Helpers/session_helper.php +++ b/app/Helpers/session_helper.php @@ -1,5 +1,39 @@ getUserByEmail($value['userData']->email); + if($user){ + if($user->is_active !== '0'){ + $user_team = $UserModel->getUserTeamsByUserID($user->id); + // dd($user_team); + + $session_data = [ + 'isLoggedIn' => True , + 'userid' => $user->id, + 'userData' => $user, + 'userProfile' => $value['userProfile'], + 'user_team' => $user_team, + ]; + set_session_data($session_data); + // $this->getUserDeviceInfo($user->id, 'NhanceUser'); + // return redirect()->to(base_url('/dashboard/view')); + return true; + + } + // $session_data = (array)json_decode($_COOKIE['session_data']); + // set_session_data($session_data); + } + }else{ + return false; + } +} if (!function_exists('check_session')) { function check_session() @@ -150,7 +184,7 @@ if (!function_exists('user_team')) { } - +} diff --git a/app/Helpers/utility_helper.php b/app/Helpers/utility_helper.php index fe345717..79523f60 100755 --- a/app/Helpers/utility_helper.php +++ b/app/Helpers/utility_helper.php @@ -24,9 +24,9 @@ if (!function_exists('generate_uuid')) { } } -if (!function_exists('change_date_format')) { +if (!function_exists('change_date_format2')) { - function change_date_format($data, $source_format, $output_format) + function change_date_format2($data, $source_format, $output_format) { $data = trim($data); // echo $data, $source_format, $output_format;return true; @@ -404,67 +404,68 @@ if(!function_exists('checkFamilyFloaters')){ } } +if (!function_exists('numberToWords')) { + function numberToWords($number) + { + $words = array( + '0' => 'Zero', + '1' => 'One', + '2' => 'Two', + '3' => 'Three', + '4' => 'Four', + '5' => 'Five', + '6' => 'Six', + '7' => 'Seven', + '8' => 'Eight', + '9' => 'Nine', + '10' => 'Ten', + '11' => 'Eleven', + '12' => 'Twelve', + '13' => 'Thirteen', + '14' => 'Fourteen', + '15' => 'Fifteen', + '16' => 'Sixteen', + '17' => 'Seventeen', + '18' => 'Eighteen', + '19' => 'Nineteen', + '20' => 'Twenty', + '30' => 'Thirty', + '40' => 'Forty', + '50' => 'Fifty', + '60' => 'Sixty', + '70' => 'Seventy', + '80' => 'Eighty', + '90' => 'Ninety' + ); -function numberToWords($number) -{ - $words = array( - '0' => 'Zero', - '1' => 'One', - '2' => 'Two', - '3' => 'Three', - '4' => 'Four', - '5' => 'Five', - '6' => 'Six', - '7' => 'Seven', - '8' => 'Eight', - '9' => 'Nine', - '10' => 'Ten', - '11' => 'Eleven', - '12' => 'Twelve', - '13' => 'Thirteen', - '14' => 'Fourteen', - '15' => 'Fifteen', - '16' => 'Sixteen', - '17' => 'Seventeen', - '18' => 'Eighteen', - '19' => 'Nineteen', - '20' => 'Twenty', - '30' => 'Thirty', - '40' => 'Forty', - '50' => 'Fifty', - '60' => 'Sixty', - '70' => 'Seventy', - '80' => 'Eighty', - '90' => 'Ninety' - ); - - if ($number < 21) { - return $words[$number]; - } - - if ($number < 100) { - $tens = (int)($number / 10) * 10; - $units = $number % 10; - return $words[$tens] . ($units ? ' ' . $words[$units] : ''); - } - - if ($number < 1000) { - $hundreds = (int)($number / 100); - $remainder = $number % 100; - return $words[$hundreds] . ' Hundred' . ($remainder ? ' and ' . numberToWords($remainder) : ''); - } - - $levels = array('', ' Thousand', ' Million', ' Billion', ' Trillion', ' Quadrillion', ' Quintillion'); - - for ($i = 0, $unit = 1; $i < count($levels); $i++, $unit *= 1000) { - if ($number < $unit * 1000) { - $current = (int)($number / $unit); - $remainder = $number % $unit; - return numberToWords($current) . $levels[$i] . ($remainder ? ' ' . numberToWords($remainder) : ''); + if ($number < 21) { + return $words[$number]; } - } - return $number; // Fallback for numbers beyond the supported range + if ($number < 100) { + $tens = (int)($number / 10) * 10; + $units = $number % 10; + return $words[$tens] . ($units ? ' ' . $words[$units] : ''); + } + + if ($number < 1000) { + $hundreds = (int)($number / 100); + $remainder = $number % 100; + return $words[$hundreds] . ' Hundred' . ($remainder ? ' and ' . numberToWords($remainder) : ''); + } + + $levels = array('', ' Thousand', ' Million', ' Billion', ' Trillion', ' Quadrillion', ' Quintillion'); + + for ($i = 0, $unit = 1; $i < count($levels); $i++, $unit *= 1000) { + if ($number < $unit * 1000) { + $current = (int)($number / $unit); + $remainder = $number % $unit; + return numberToWords($current) . $levels[$i] . ($remainder ? ' ' . numberToWords($remainder) : ''); + } + } + + return $number; // Fallback for numbers beyond the supported range + } } if (!function_exists('print_rr')) { @@ -493,6 +494,7 @@ if (!function_exists('get_server_details')) { ]; } } + if (!function_exists('isJsonString')) { function isJsonString($input) @@ -501,3 +503,161 @@ if (!function_exists('isJsonString')) { return (json_last_error() === JSON_ERROR_NONE); // Check if the last JSON error is "no error" } } + +if (!function_exists('isValidDate')) { + function isValidDate($date, $format) { + $parsed_date = DateTime::createFromFormat($format, $date); + return $parsed_date && $parsed_date->format($format) === $date; + } +} + +if (!function_exists('change_date_format')) { + + function change_date_format($date_str, $source_format = null, $output_format = 'Y-m-d') { + + $date_str = trim($date_str); + // Allowed date formats + $allowed_formats = [ + // Day Month Year (clear unambiguous formats) + 'd M Y', // 01 Dec 2024 + 'd-M-Y', // 01-Dec-2024 + 'd/M/Y', // 01/Dec/2024 + 'd.M.Y', // 01.Dec.2024 + 'd,M,Y', // 01,Dec,2024 + + // Month Day Year (clear unambiguous formats) + 'M d Y', // Dec 01 2024 + 'M-d-Y', // Dec-01-2024 + 'M/d/Y', // Dec/01/2024 + 'M.d.Y', // Dec.01.2024 + 'M,d,Y', // Dec,01,2024 + + // Year Month Day (clear unambiguous formats) + 'Y M d', // 2024 Dec 01 + 'Y-M-d', // 2024-Dec-01 + 'Y/M/d', // 2024/Dec/01 + 'Y.M.d', // 2024.Dec.01 + 'Y,M,d', // 2024,Dec,01 + + // Year Numeric Month Numeric Day + 'Y-m-d', // 2024-12-01 + 'Y/m/d', // 2024/12/01 + 'Y.m.d', // 2024.12.01 + 'Y,m,d', // 2024,12,01 + ]; + + try { + // Case 1: Source and Output formats are provided + if ($source_format !== null && $output_format !== null) { + $date = DateTime::createFromFormat($source_format, $date_str); + if (!$date) { + throw new Exception("Invalid date string for source format: $source_format"); + } + return $date->format($output_format); + } + + // Case 2: Source format is provided, Output format is null + if ($source_format !== null && $output_format === null) { + $date = DateTime::createFromFormat($source_format, $date_str); + if (!$date) { + throw new Exception("Invalid date string for source format: $source_format"); + } + return $date->format('Y-m-d'); // MySQL default format + } + + // Case 3: Source format is null, auto-detect format + if ($source_format === null) { + foreach ($allowed_formats as $format) { + if (isValidDate($date_str, $format)) { + $date = DateTime::createFromFormat($format, $date_str); + return $date->format($output_format); // Default is MySQL format + } + } + // If no format matches, throw an exception + $allowed_placeholders = implode(', ', $allowed_formats); + throw new Exception("Invalid date string format. Allowed formats: $allowed_placeholders"); + } + } catch (Exception $e) { + return "Error: " . $e->getMessage(); + } + + return null; + } +} + +// if (!function_exists('check_pay_by_employee_or_company')) +// { + +// function check_pay_by_employee_or_company($is_payable_employee = null, $relationship = null) { + +// $relationship = strtolower(str_replace(" ", "_", $relationship)); + +// $result = 0; + +// if($relationship == 'self'){ + +// $result = $is_payable_employee['self'] == 1 ? 1 : 0; + +// }else if($relationship == 'spouse'){ + +// $result = $is_payable_employee['spouse'] == 1 ? 1 : 0; + +// }else if(in_array($relationship, ['son', 'daughter'])){ + +// $result = $is_payable_employee['childern'] == 1 ? 1 : 0; + +// }else if(in_array($relationship, ['father', 'mother', 'father_in_law', 'mother_in_law'])){ + +// $result = $is_payable_employee['elders'] == 1 ? 1 : 0; + +// } + +// return $result; +// } +// } + +if (!function_exists('check_pay_by_employee_or_company')) { + + function check_pay_by_employee_or_company($policy_terms = null, $relationship = null) + { + + // dd($policy_terms, $relationship); + + if (!$policy_terms || !($policy_terms = json_decode($policy_terms, true))) { + return 0; + } + + // dd($policy_terms, $relationship); + + if (!isset($policy_terms['is_payable_employee'])) { + return 0; + } + + $is_payable_employee = $policy_terms['is_payable_employee']; + + $relationship = strtolower(str_replace(" ", "_", $relationship)); + + // dd($is_payable_employee, $relationship); + + $relationshipMap = [ + 'self' => 'self', + 'spouse' => 'spouse', + 'son' => 'childern', + 'daughter' => 'childern', + 'father' => 'elders', + 'mother' => 'elders', + 'father_in_law' => 'elders', + 'mother_in_law' => 'elders' + ]; + + if (array_key_exists($relationship, $relationshipMap)) { + $key = $relationshipMap[$relationship]; + + return isset($is_payable_employee[$key]) && $is_payable_employee[$key] == 1 ? 1 : 0; + } + + return 0; + } + +} + diff --git a/app/Libraries/MyLogger.php b/app/Libraries/MyLogger.php index efa401d5..71ebafe1 100755 --- a/app/Libraries/MyLogger.php +++ b/app/Libraries/MyLogger.php @@ -21,7 +21,7 @@ class MyLogger extends Logger $message = '{context} - {uuid} -' . $message; // /echo $message;//die(); - $context = array_merge($context,['uuid' => get_session_uuid()]); + $context = array_merge($context,['uuid' => (null !== get_session_uuid()) ? get_session_uuid() : 'CLI']); // print_r($context);die(); // echo isset($context['context']) ? $context['context'] : $this->context;die(); $context['context'] = isset($context['context']) ? $context['context'] : get_session_context(); diff --git a/app/Models/AuditHistoryModel.php b/app/Models/AuditHistoryModel.php new file mode 100644 index 00000000..797515f9 --- /dev/null +++ b/app/Models/AuditHistoryModel.php @@ -0,0 +1,22 @@ + \ No newline at end of file diff --git a/app/Models/CDMasterModel.php b/app/Models/CDMasterModel.php index 8c7581a3..663ea3bc 100755 --- a/app/Models/CDMasterModel.php +++ b/app/Models/CDMasterModel.php @@ -65,28 +65,37 @@ class CDMasterModel extends Model { $query = $this->db->table('cd_master') + ->select('cd_master.*, clients.client_name, clients.short_name, insurers.name AS insurer_name, user_profiles.first_name AS user_name, IFNULL(cd_ac_counts.cd_ac_no_count, 0) AS cd_ac_no_count, IFNULL(cd_ac_counts_for_cdt.cd_ac_no_count_cd_tranction, 0) AS cd_ac_no_count_cd_tranction') ->join('clients', 'clients.id = cd_master.client_id') ->join('insurers', 'insurers.id = cd_master.insurer_id') ->join('user_profiles', 'user_profiles.id = cd_master.created_by') ->join( - '(SELECT cd_master.cd_ac_no, COUNT(client_policy.cd_ac_no) AS cd_ac_no_count - FROM cd_master - JOIN client_policy ON client_policy.cd_ac_no = cd_master.cd_ac_no - WHERE client_policy.is_active = 1 - AND cd_master.is_active = 1 - GROUP BY cd_master.cd_ac_no) AS cd_ac_counts', - 'cd_ac_counts.cd_ac_no = cd_master.cd_ac_no', + '(SELECT cd_master.cd_ac_no, cd_master.id, COUNT(client_policy.cd_ac_no) AS cd_ac_no_count + + FROM cd_master + JOIN client_policy ON client_policy.cd_ac_pk = cd_master.id + WHERE client_policy.is_active = 1 + AND cd_master.is_active = 1 + GROUP BY cd_master.id + + ) AS cd_ac_counts', + + 'cd_ac_counts.id = cd_master.id', 'left' ) ->join( - '(SELECT cd_master.cd_ac_no, COUNT(cash_deposit.cd_ac_no) AS cd_ac_no_count_cd_tranction - FROM cd_master - JOIN cash_deposit ON cash_deposit.cd_ac_no = cd_master.cd_ac_no - WHERE cash_deposit.is_active = 1 - AND cd_master.is_active = 1 - GROUP BY cd_master.cd_ac_no) AS cd_ac_counts_for_cdt', - 'cd_ac_counts_for_cdt.cd_ac_no = cd_master.cd_ac_no', + '(SELECT cd_master.cd_ac_no, cd_master.id, COUNT(cash_deposit.cd_ac_no) AS cd_ac_no_count_cd_tranction + + FROM cd_master + JOIN cash_deposit ON cash_deposit.cd_ac_pk = cd_master.id + WHERE cash_deposit.is_active = 1 + AND cd_master.is_active = 1 + GROUP BY cd_master.id + + ) AS cd_ac_counts_for_cdt', + + 'cd_ac_counts_for_cdt.id = cd_master.id', 'left' ) ->where('cd_master.is_active', 1) diff --git a/app/Models/COShareStmtDetailsModel.php b/app/Models/COShareStmtDetailsModel.php new file mode 100644 index 00000000..df007cf9 --- /dev/null +++ b/app/Models/COShareStmtDetailsModel.php @@ -0,0 +1,38 @@ +db->table('client_policy') @@ -135,13 +170,14 @@ class ClientPolicyModel extends Model public function getinsurerswithclientid($id){ return $this->db->table('client_policy') - ->select('client_policy.*, cd_master.cd_ac_no') + ->select('client_policy.*, cd_master.cd_ac_no as cd_master_account_no') ->select('insurers.name as insurer_name, insurers.short_name as insurer_short') ->select('clients.client_name as client_name') ->join('clients','clients.id=client_policy.client_id') ->join('insurers', 'insurers.id = client_policy.insurer_id') ->join('cd_master', 'cd_master.insurer_id = insurers.id AND cd_master.client_id = client_policy.client_id') ->where('client_policy.client_id', $id) + ->where('cd_master.id = client_policy.cd_ac_pk') ->groupBy('client_policy.insurer_id') ->groupBy('client_policy.client_id', $id) // Group by insurer_id ->get() @@ -191,6 +227,7 @@ class ClientPolicyModel extends Model ->select('cash_deposit.*') ->select('insurers.name as insurer_name, insurers.short_name as insurer_short') ->select('clients.client_name as clientname, clients.short_name as clientshort, client_policy.policy_no') + ->select('cd_master.cd_ac_no as cd_master_account_no') // ->select('policies.name as policy_name') ->select('policy_type.policy_type') ->select('user_profiles.first_name as username') @@ -198,11 +235,13 @@ class ClientPolicyModel extends Model ->join('insurers', 'insurers.id = cash_deposit.insurer_id', 'left') ->join('clients', 'clients.id = cash_deposit.client_id', 'left') ->join('client_policy', 'client_policy.id = cash_deposit.client_policy_id', 'left') + ->join('cd_master', 'cd_master.id = cash_deposit.cd_ac_pk', 'left') // ->join('policies', 'policies.id = client_policy.policy_id', 'left') ->join('policy_type', 'policy_type.id = client_policy.policy_type_id', 'left') ->where('cash_deposit.client_id', $clientId) ->where('cash_deposit.insurer_id', $insurerId) ->where('cash_deposit.is_active', 1) + // ->where('cash_deposit.cd_ac_pk = cd_master.id') ->orderBy('cash_deposit.id', 'DESC') ->get() ->getResult(); @@ -389,21 +428,26 @@ public function getCliendDataForExcelFileName($client_policy_id){ } //for this using in CRONE JOB -public function getPolicyDetailsForRemainder($client_id = null, $branch_id = null) +public function getPolicyDetailsForRemainder($client_id = null, $branch_id = null, $policy_id = null) { $builder = $this->table('client_policy') - ->where('client_policy.is_addon', 1) - ->where('client_policy.open_for_enrollment', 1) - ->where('client_policy.inception_type', 2) ->where('client_policy.is_active', 1) ->where('client_policy.policy_status', 1) - ->whereIn('client_policy.policy_type_id', [2, 3]); - + // ->where('client_policy.is_addon', 1) + // ->where('client_policy.inception_type', 2) + ->where('client_policy.open_for_enrollment', 1); + if ($client_id && $branch_id) { $builder->where('client_policy.client_id', $client_id) ->where('client_policy.client_branch_id', $branch_id); } + if(empty($policy_id)){ + $builder->whereIn('client_policy.policy_type_id', [2, 3, 4, 5]); + }else{ + $builder->where('client_policy.id', $policy_id); + } + return $builder->get()->getResultArray(); } diff --git a/app/Models/EmployeeModel.php b/app/Models/EmployeeModel.php index b84b96a9..73caca1e 100755 --- a/app/Models/EmployeeModel.php +++ b/app/Models/EmployeeModel.php @@ -106,7 +106,7 @@ class EmployeeModel extends Model public function getEmpFamilybyEmpCode(string $client_policy_id = null,string $emp_code = null,string $client_id = null,array $emp_status = [],array $policy_status = [],array $relationship = [],array $client_branch_id = []) { - $result = $this->select(['employees.id as emp_id', 'employees.client_id','employees.client_branch_id', 'employees.relationship', 'employees.relationship_code', 'employees.change_event', 'employees.emp_code', 'employees.name', 'employees.email_personal', 'employees.email_corporate', 'employees.mobile', 'employees.gender', 'employees.dob', 'employees.doj', 'employees.basic_pay', 'employees.band', 'employees.designation', 'employees.emp_status','employees.unit','employee_polices.id as emp_policy_id', 'employee_polices.employee_id', 'employee_polices.client_policy_id', 'employee_polices.tpa_id', 'employee_polices.uhid', 'employee_polices.batch_code', 'employee_polices.status', 'employee_polices.pre_existing_alignments', 'employee_polices.basic_cover_si', 'employee_polices.date_coverage', 'employee_polices.policy_end_date', 'employee_polices.days', 'employee_polices.premium', 'employee_polices.rata_premimum', 'employee_polices.gst', 'employee_polices.date_of_exit', 'employee_polices.reason_for_exit','policy_type.long_name as policy_name','client_policy.is_addon']) + $result = $this->select(['employees.id as emp_id', 'employees.client_id','employees.client_branch_id', 'employees.relationship', 'employees.relationship_code', 'employees.change_event', 'employees.emp_code', 'employees.name', 'employees.email_personal', 'employees.email_corporate', 'employees.mobile', 'employees.gender', 'employees.dob', 'employees.doj', 'employees.basic_pay', 'employees.band', 'employees.designation', 'employees.emp_status','employees.unit','employees.file_id','employee_polices.id as emp_policy_id', 'employee_polices.employee_id', 'employee_polices.client_policy_id', 'employee_polices.tpa_id', 'employee_polices.uhid', 'employee_polices.batch_code', 'employee_polices.status', 'employee_polices.pre_existing_alignments', 'employee_polices.basic_cover_si', 'employee_polices.date_coverage', 'employee_polices.policy_end_date', 'employee_polices.days', 'employee_polices.premium', 'employee_polices.rata_premimum', 'employee_polices.gst', 'employee_polices.date_of_exit', 'employee_polices.reason_for_exit','policy_type.long_name as policy_name','client_policy.is_addon', 'employee_polices.payable_employee']) ->join('employee_polices', 'employee_polices.employee_id = employees.id') ->join('client_policy', 'client_policy.id = employee_polices.client_policy_id') ->join('policy_type', 'policy_type.id = client_policy.policy_type_id','left') @@ -149,10 +149,12 @@ class EmployeeModel extends Model { return $this->db->table('employee_polices') - ->select(' policy_type.long_name as Policy_Name , client_policy.policy_terms as Policy_Terms, client_policy.client_id as ClientId, client_policy.policy_id as PolicyId,client_policy.id as ClientPolicyId, client_policy.open_for_enrollment as OpenForEnrollment , employee_polices.tpa_id as tpa_id , employee_polices.rand_string as rand_string') // Select all columns from both tables + ->select(' policy_type.long_name as Policy_Name , client_policy.policy_terms as Policy_Terms, client_policy.client_id as ClientId, client_policy.policy_id as PolicyId,client_policy.id as ClientPolicyId, client_policy.open_for_enrollment as OpenForEnrollment,client_policy.disclaimer,client_policy.policy_type_id , employee_polices.tpa_id as tpa_id , employee_polices.rand_string as rand_string') // Select all columns from both tables ->join('client_policy', 'client_policy.id = employee_polices.client_policy_id') ->join('policy_type', 'policy_type.id = client_policy.policy_type_id') ->where('client_policy.policy_status', 1) + ->where('employee_polices.status !=', 'truncated') + ->where('employee_polices.is_active', 1) ->where('employee_polices.employee_id', $id) ->get() ->getResult(); @@ -210,4 +212,32 @@ class EmployeeModel extends Model return $results; } + public function getTestEmployeeData(){ + $query = " + SELECT + e.*, + ( + SELECT + COUNT(ep.client_policy_id) + FROM + employee_polices ep + WHERE + ep.employee_id = e.id + ) AS policy_count + FROM + employees e + WHERE + e.emp_code LIKE 'TEST%' + ORDER BY + e.emp_code, + CASE + WHEN e.relationship = 'self' THEN 1 + WHEN e.relationship = 'spouse' THEN 2 + ELSE 3 + END; + "; + $results = $this->db->query($query)->getResultArray(); + return $results; + } + } diff --git a/app/Models/EmployeePolicyModel.php b/app/Models/EmployeePolicyModel.php index abbba1e4..c7dce21a 100755 --- a/app/Models/EmployeePolicyModel.php +++ b/app/Models/EmployeePolicyModel.php @@ -32,6 +32,10 @@ class EmployeePolicyModel extends Model "updated_at", "rand_string", "is_active", + "claim_status", + 'ecard_sent_status', + 'payable_employee', + 'file_id' ]; // Callbacks @@ -111,6 +115,7 @@ class EmployeePolicyModel extends Model 'client_branch.branch_name as client_branch_name', 'client_branch.branch_code as client_branch_code', 'cp.policy_no', + 'cp.policy_type_id', ]) ->join('employees emp', 'employee_polices.employee_id = emp.id') ->join('client_policy cp', 'employee_polices.client_policy_id = cp.id') //cp - client policy @@ -124,7 +129,6 @@ class EmployeePolicyModel extends Model ->join('client_branch', 'emp.client_branch_id = client_branch.id') //cm - client master ->orderBy('emp.emp_code', 'ASC') ->orderBy('employee_polices.employee_id', 'ASC'); - // Conditionally add where clauses if ($client_id != 0 && !empty($client_id)) { $result->where('emp.client_id', $client_id); @@ -177,7 +181,11 @@ class EmployeePolicyModel extends Model $result->where('employee_polices.is_active', 1) ->where('emp.is_active', 1); - return $result->findAll(); + $res = $result->findAll(); + + // dd($this->db->getLastQuery()); + + return $res; } public function getEmployeePolicyForEcard($policy_id = 0) @@ -185,7 +193,7 @@ class EmployeePolicyModel extends Model $result = $this->select([ 'employee_polices.id' ]) - ->join('employees emp', 'employee_polices.employee_id = emp.id AND emp.relationship = "Self" '); + ->join('employees emp', 'employee_polices.employee_id = emp.id'); if ($policy_id !=0 && !empty($policy_id)) { $result->where('employee_polices.client_policy_id', $policy_id); } @@ -193,7 +201,10 @@ class EmployeePolicyModel extends Model $result->where('employee_polices.is_active', 1) ->where('employee_polices.status', 'active') ->where('employee_polices.tpa_id is not null') - ->where('emp.relationship','Self'); + ->where('employee_polices.ecard_sent_status',0) + // ->where('emp.relationship','Self'); + ->where('emp.email_corporate !=','') + ->where('emp.email_corporate is not null'); return $result->findAll(); // $result->findAll(); @@ -214,6 +225,7 @@ class EmployeePolicyModel extends Model public function getInceptionEmployeeDataForExportExcel($ref_data, $return_type = 0) { + $client_id = $ref_data['client_id']; $client_policy_id = $ref_data['client_policy_id']; $client_branch_id = $ref_data['client_branch_id']; $insurer_or_tpa = $ref_data['insurer_or_tpa']; @@ -247,7 +259,6 @@ class EmployeePolicyModel extends Model SELECT employees.name AS emp_name, employees.emp_code AS emp_code, - employees.dob AS emp_dob, employees.gender AS emp_gender, employees.relationship AS emp_relationship, employees.relationship_code AS emp_relationship_code, @@ -255,7 +266,6 @@ class EmployeePolicyModel extends Model employees.change_event AS change_event, - employees.doj AS emp_doj, employees.mobile AS emp_mobile, employees.email_corporate AS emp_email_c, employees.email_personal AS emp_email_p, @@ -272,8 +282,6 @@ class EmployeePolicyModel extends Model employee_polices.uhid, employee_polices.pre_existing_alignments, employee_polices.basic_cover_si, - employee_polices.date_coverage, - employee_polices.policy_end_date, employee_polices.days as no_of_days, employee_polices.premium, employee_polices.rata_premimum as pro_rata_premium, @@ -283,6 +291,12 @@ class EmployeePolicyModel extends Model batch_data.bl AS batch_list_batch_code, batch_data.bf AS batch_files_batch_code, + DATE_FORMAT(employees.dob, '%d-%b-%Y') AS emp_dob, + DATE_FORMAT(employees.doj, '%d-%b-%Y') AS emp_doj, + DATE_FORMAT(employee_polices.policy_end_date, '%d-%b-%Y') AS policy_end_date, + DATE_FORMAT(employee_polices.date_coverage, '%d-%b-%Y') AS date_of_coverage, + + CASE WHEN client_branch.sez = 0 THEN 'NON-SEZ' WHEN client_branch.sez = 1 THEN 'SEZ' @@ -301,6 +315,9 @@ class EmployeePolicyModel extends Model WHERE batch_files.event_type = '{$event}' AND batch_files.actions = 'export' AND batch_files.insurer_or_tpa = '{$insurer_or_tpa}' + AND batch_files.client_policy_id = '{$client_policy_id}' + AND batch_files.client_policy_id = '{$client_id}' + ) as batch_data ON employee_polices.id = batch_data.emp_policy_id WHERE employee_polices.client_policy_id = '{$client_policy_id}' AND (employee_polices.{$id} IS NULL OR employee_polices.{$id} = '') @@ -319,11 +336,14 @@ class EmployeePolicyModel extends Model }else{ $results = $query->getResult(); } + + // dd($this->db->getLastQuery()); + return $results; } - public function getCorrectionEmployeesDataForExportExcel($ref_data) + public function getCorrectionEmployeesDataForExportExcel($ref_data, $return_type = 0) { $client_id = $ref_data['client_id']; @@ -331,22 +351,19 @@ class EmployeePolicyModel extends Model $client_branch_id = $ref_data['client_branch_id']; $insurer_or_tpa = $ref_data['insurer_or_tpa']; - $endorsement_condition = "{$insurer_or_tpa}" === 'tpa' ? "AND (emp_endorsement.endorsement_id IS NOT NULL OR emp_endorsement.endorsement_id != '')" : "AND (emp_endorsement.endorsement_id IS NULL OR emp_endorsement.endorsement_id = '')"; + $endorsement_condition = "{$insurer_or_tpa}" === 'tpa' ? "AND (emp_endorsement.endorsement_id IS NULL OR emp_endorsement.endorsement_id = '')" : "AND (emp_endorsement.endorsement_id IS NULL OR emp_endorsement.endorsement_id = '')"; $sql = " SELECT DISTINCT emp_endorsement.id, emp_endorsement.pk, emp_endorsement.emp_code, - emp_endorsement.endorsement_id, - emp_endorsement.old_value, - emp_endorsement.new_value, + emp_endorsement.endorsement_id, emp_endorsement.field_name, emp_endorsement.remarks, emp_endorsement.actions, employees.id AS primaryKey, employees.name AS emp_name, - employees.dob AS emp_dob, employees.gender AS emp_gender, employees.client_id AS emp_client_id, employees.emp_type as emp_type, @@ -356,7 +373,23 @@ class EmployeePolicyModel extends Model employees.relationship as emp_relationship, 'C' as event_type_data, - employees.doj AS emp_doj, + CASE + WHEN emp_endorsement.field_name = 'dob' THEN + DATE_FORMAT(emp_endorsement.old_value, '%d-%b-%Y') + ELSE + emp_endorsement.old_value + END AS old_value, + + CASE + WHEN emp_endorsement.field_name = 'dob' THEN + DATE_FORMAT(emp_endorsement.new_value, '%d-%b-%Y') + ELSE + emp_endorsement.new_value + END AS new_value, + + DATE_FORMAT(employees.dob, '%d-%b-%Y') AS emp_dob, + DATE_FORMAT(employees.doj, '%d-%b-%Y') AS emp_doj, + employees.mobile AS emp_mobile, employees.email_corporate AS emp_email_c, employees.email_personal AS emp_email_p, @@ -396,19 +429,21 @@ class EmployeePolicyModel extends Model AND employee_polices.status = 'active' AND employees.is_active = 1 AND employees.emp_status = 'active' - AND (employee_polices.tpa_id IS NOT NULL AND employee_polices.tpa_id != '') - AND (employee_polices.uhid IS NOT NULL AND employee_polices.uhid != '') $endorsement_condition"; // Execute the raw query $query = $this->db->query($sql); // Get the result set - $result = $query->getResult(); + if($return_type == 1){ + $results = $query->getResultArray(); + }else{ + $results = $query->getResult(); + } // dd($this->db->getLastQuery(), $result); - return $result; + return $results; } @@ -553,8 +588,177 @@ class EmployeePolicyModel extends Model } + // DO NOT DELETE this DELETION QUERY FUNCTION - public function getDeletionEmployeeDataForExportExcel($ref_data) + // public function getDeletionEmployeeDataForExportExcel($ref_data, $return_type = 0) + // { + + // $client_id = $ref_data['client_id']; + // $client_policy_id = $ref_data['client_policy_id']; + // $client_branch_id = $ref_data['client_branch_id']; + // $insurer_or_tpa = $ref_data['insurer_or_tpa']; + + // $get_insurer_id_from_client_policy = $this->db->table('client_policy') + // ->select('insurer_id') + // ->where('id', $client_policy_id) + // ->get() + // ->getRowArray(); + + // $add_one_day = 0; + + // if (!empty($get_insurer_id_from_client_policy)) { + + // $get_the_insurer_add_one_for_delete = $this->db->table('insurers') + // ->select('deletion_add_day') + // ->where('id', $get_insurer_id_from_client_policy['insurer_id']) + // ->get() + // ->getRowArray(); + + // if (!empty($get_the_insurer_add_one_for_delete) && $get_the_insurer_add_one_for_delete['deletion_add_day'] == 1) { + // $add_one_day = 1; + // } + // } + + // $status_condition = "{$insurer_or_tpa}" === 'tpa' + // ? "employee_polices.status = 'inactive' AND employees.emp_status = 'inactive'" + // : "employee_polices.status = 'active' AND employees.emp_status = 'active'"; + + // $endorsement_condition = "{$insurer_or_tpa}" === 'tpa' ? "AND (a.endorsement_id IS NOT NULL OR a.endorsement_id != '')" : "AND (a.endorsement_id IS NULL OR a.endorsement_id = '')"; + + // $query = $this->db->query(" + // SELECT DISTINCT + // a.id as endorsement_primarykey, + // a.group_key, + // employee_polices.id as primaryKey, + // employees.name AS emp_name, + // employees.emp_code AS emp_code, + // employees.dob AS emp_dob, + // employees.gender AS emp_gender, + // employees.relationship AS emp_relationship, + // employees.relationship_code AS emp_relationship_code, + // employees.emp_type as emp_type, + // 'D' as event_type_data, + // TIMESTAMPDIFF(YEAR, employees.dob, CURDATE()) AS emp_age, + + // employees.doj AS emp_doj, + // employees.mobile AS emp_mobile, + // employees.email_corporate AS emp_email_c, + // employees.email_personal AS emp_email_p, + // employees.band AS emp_grade, + // employees.designation AS emp_designation, + // employees.basic_pay AS emp_basic_pay, + + // employee_polices.basic_cover_si, + // employee_polices.uhid as uhid, + // employee_polices.policy_end_date, + // employee_polices.rata_premimum as premium, + // employee_polices.claim_status, + + // batch_data.emp_policy_id AS emp_policy_id, + // batch_data.bl AS batch_list_batch_code, + // batch_data.bf AS batch_files_batch_code, + + // deletiondata.empstatus, + // deletiondata.changeevent, + // deletiondata.dateofexit, + // deletiondata.reasonforexit, + // deletiondata.status, + + // DATEDIFF(employee_polices.policy_end_date, deletiondata.dateofexit) + '$add_one_day' AS no_of_days, + + + // CASE + // WHEN employee_polices.claim_status = 0 THEN + // ROUND((employee_polices.rata_premimum * (DATEDIFF(employee_polices.policy_end_date, deletiondata.dateofexit) + $add_one_day)) / 365, 2) + // ELSE + // 0 + // END AS pro_rata_premium, + + // CASE + // WHEN employee_polices.claim_status = 0 THEN + // ROUND(((employee_polices.rata_premimum * (DATEDIFF(employee_polices.policy_end_date, deletiondata.dateofexit) + $add_one_day)) / 365) * 0.18, 2) + // ELSE + // 0 + // END AS gst, + + // CASE + // WHEN employee_polices.claim_status = 0 THEN + // ROUND(((employee_polices.rata_premimum * (DATEDIFF(employee_polices.policy_end_date, deletiondata.dateofexit) + $add_one_day)) / 365) + + // (((employee_polices.rata_premimum * (DATEDIFF(employee_polices.policy_end_date, deletiondata.dateofexit) + $add_one_day)) / 365) * 0.18), 2) + // ELSE + // 0 + // END AS total, + + // CASE + // WHEN employee_polices.claim_status = 0 THEN + // 'No claim' + // ELSE + // 'Claim' + // END AS claim_status + + // FROM + // emp_endorsement a + // LEFT JOIN + // employees ON a.emp_code = employees.emp_code + // LEFT JOIN + // employee_polices ON employees.id = employee_polices.employee_id + + // LEFT JOIN( + + // select aa.emp_code, aa.new_value as 'empstatus', bb.new_value as 'changeevent', cc.new_value as 'dateofexit', dd.new_value as 'reasonforexit', ee.new_value as 'status' from + + // ( SELECT a1.emp_code, a1.field_name, a1.new_value from emp_endorsement as a1 where a1.field_name = 'emp_status' and a1.status != 'truncated') aa + // left join + // ( SELECT b1.emp_code, b1.field_name, b1.new_value from emp_endorsement as b1 where b1.field_name = 'change_event' and b1.status != 'truncated') bb on aa.emp_code = bb.emp_code + // left join + // ( SELECT c1.emp_code, c1.field_name, c1.new_value from emp_endorsement as c1 where c1.field_name = 'date_of_exit' and c1.status != 'truncated') cc on aa.emp_code = cc.emp_code + // left join + // ( SELECT d1.emp_code, d1.field_name, d1.new_value from emp_endorsement as d1 where d1.field_name = 'reason_for_exit' and d1.status != 'truncated') dd on aa.emp_code = dd.emp_code + // left JOIN + // ( SELECT e1.emp_code, e1.field_name, e1.new_value from emp_endorsement as e1 where e1.field_name = 'status' and e1.status != 'truncated') ee on aa.emp_code = ee.emp_code + + // ) as deletiondata on a.emp_code = deletiondata.emp_code and a.status != 'truncated' + + // LEFT JOIN + // ( + // SELECT + // batch_list.emp_policy_id, + // batch_list.batch_code AS bl, + // batch_files.batch_code AS bf + // FROM + // batch_files + // LEFT JOIN + // batch_list ON batch_files.batch_code = batch_list.batch_code + // WHERE + // batch_files.event_type = 'deletion' + // AND batch_files.actions = 'export' + // AND batch_files.insurer_or_tpa = '{$insurer_or_tpa}' + // ) AS batch_data ON employee_polices.id = batch_data.emp_policy_id + + // WHERE employee_polices.client_policy_id = {$client_policy_id} + // AND employees.client_branch_id = {$client_branch_id} + // $endorsement_condition + // AND a.actions = 'd' + // AND a.status != 'truncated' + // AND employee_polices.is_active = 1 + // AND employees.is_active = 1 + // AND $status_condition + // group by group_key + // "); + + // if($return_type == 1){ + // $result = $query->getResultArray(); + // }else{ + // $result = $query->getResult(); + // } + + // // dd($this->db->getLastQuery(), $result); + + // return $result; + + // } + + public function getDeletionEmployeeDataForExportExcel($ref_data, $return_type = 0) { $client_id = $ref_data['client_id']; @@ -584,10 +788,10 @@ class EmployeePolicyModel extends Model } $status_condition = "{$insurer_or_tpa}" === 'tpa' - ? "employee_polices.status = 'inactive' AND employees.emp_status = 'inactive'" + ? "employee_polices.status = 'active' AND employees.emp_status = 'active'" : "employee_polices.status = 'active' AND employees.emp_status = 'active'"; - $endorsement_condition = "{$insurer_or_tpa}" === 'tpa' ? "AND (a.endorsement_id IS NOT NULL OR a.endorsement_id != '')" : "AND (a.endorsement_id IS NULL OR a.endorsement_id = '')"; + $endorsement_condition = "{$insurer_or_tpa}" === 'tpa' ? "AND (a.endorsement_id IS NULL OR a.endorsement_id = '')" : "AND (a.endorsement_id IS NULL OR a.endorsement_id = '')"; $query = $this->db->query(" SELECT DISTINCT @@ -596,7 +800,6 @@ class EmployeePolicyModel extends Model employee_polices.id as primaryKey, employees.name AS emp_name, employees.emp_code AS emp_code, - employees.dob AS emp_dob, employees.gender AS emp_gender, employees.relationship AS emp_relationship, employees.relationship_code AS emp_relationship_code, @@ -604,7 +807,6 @@ class EmployeePolicyModel extends Model 'D' as event_type_data, TIMESTAMPDIFF(YEAR, employees.dob, CURDATE()) AS emp_age, - employees.doj AS emp_doj, employees.mobile AS emp_mobile, employees.email_corporate AS emp_email_c, employees.email_personal AS emp_email_p, @@ -614,9 +816,8 @@ class EmployeePolicyModel extends Model employee_polices.basic_cover_si, employee_polices.uhid as uhid, - employee_polices.policy_end_date, - employee_polices.premium, - employee_polices.rata_premimum as pro_rata_premium, + employee_polices.rata_premimum as premium, + employee_polices.claim_status, batch_data.emp_policy_id AS emp_policy_id, batch_data.bl AS batch_list_batch_code, @@ -624,39 +825,77 @@ class EmployeePolicyModel extends Model deletiondata.empstatus, deletiondata.changeevent, - deletiondata.dateofexit, deletiondata.reasonforexit, deletiondata.status, + deletiondata.claimstatus, + + DATE_FORMAT(employees.dob, '%d-%b-%Y') AS emp_dob, + DATE_FORMAT(employees.doj, '%d-%b-%Y') AS emp_doj, + DATE_FORMAT(employee_polices.policy_end_date, '%d-%b-%Y') AS policy_end_date, + DATE_FORMAT(deletiondata.dateofexit, '%d-%b-%Y') AS dateofexit, + DATEDIFF(employee_polices.policy_end_date, deletiondata.dateofexit) + '$add_one_day' AS no_of_days, - ROUND((employee_polices.rata_premimum * (DATEDIFF(employee_polices.policy_end_date, deletiondata.dateofexit) + $add_one_day)) / 365, 2) AS pro_rata_premium, - ROUND(((employee_polices.rata_premimum * (DATEDIFF(employee_polices.policy_end_date, deletiondata.dateofexit) + $add_one_day)) / 365) * 0.18, 2) AS gst, - ROUND(((employee_polices.rata_premimum * (DATEDIFF(employee_polices.policy_end_date, deletiondata.dateofexit) + $add_one_day)) / 365) + (((employee_polices.rata_premimum * (DATEDIFF(employee_polices.policy_end_date, deletiondata.dateofexit) + $add_one_day)) / 365) * 0.18), 2) AS total + + CASE + WHEN deletiondata.claimstatus = 0 OR deletiondata.claimstatus IS NULL THEN + ROUND((employee_polices.rata_premimum * (DATEDIFF(employee_polices.policy_end_date, deletiondata.dateofexit) + $add_one_day)) / 365, 2) + ELSE + 0 + END AS pro_rata_premium, + + CASE + WHEN deletiondata.claimstatus = 0 OR deletiondata.claimstatus IS NULL THEN + ROUND(((employee_polices.rata_premimum * (DATEDIFF(employee_polices.policy_end_date, deletiondata.dateofexit) + $add_one_day)) / 365) * 0.18, 2) + ELSE + 0 + END AS gst, + + CASE + WHEN deletiondata.claimstatus = 0 OR deletiondata.claimstatus IS NULL THEN + ROUND(((employee_polices.rata_premimum * (DATEDIFF(employee_polices.policy_end_date, deletiondata.dateofexit) + $add_one_day)) / 365) + + (((employee_polices.rata_premimum * (DATEDIFF(employee_polices.policy_end_date, deletiondata.dateofexit) + $add_one_day)) / 365) * 0.18), 2) + ELSE + 0 + END AS total, + + CASE + WHEN deletiondata.claimstatus = 0 OR deletiondata.claimstatus IS NULL THEN + + 'No claim' + ELSE + 'Claim' + END AS claim_status + FROM emp_endorsement a LEFT JOIN - employees ON a.emp_code = employees.emp_code and a.pk = employees.id + employee_polices ON a.pk = employee_polices.id LEFT JOIN - employee_polices ON employees.id = employee_polices.employee_id - - LEFT JOIN( - - select aa.emp_code, aa.new_value as 'empstatus', bb.new_value as 'changeevent', cc.new_value as 'dateofexit', dd.new_value as 'reasonforexit', ee.new_value as 'status' from - - ( SELECT a1.emp_code, a1.field_name, a1.new_value from emp_endorsement as a1 where a1.field_name = 'emp_status' and a1.status != 'truncated') aa - left join - ( SELECT b1.emp_code, b1.field_name, b1.new_value from emp_endorsement as b1 where b1.field_name = 'change_event' and b1.status != 'truncated') bb on aa.emp_code = bb.emp_code - left join - ( SELECT c1.emp_code, c1.field_name, c1.new_value from emp_endorsement as c1 where c1.field_name = 'date_of_exit' and c1.status != 'truncated') cc on aa.emp_code = cc.emp_code - left join - ( SELECT d1.emp_code, d1.field_name, d1.new_value from emp_endorsement as d1 where d1.field_name = 'reason_for_exit' and d1.status != 'truncated') dd on aa.emp_code = dd.emp_code - left JOIN - ( SELECT e1.emp_code, e1.field_name, e1.new_value from emp_endorsement as e1 where e1.field_name = 'status' and e1.status != 'truncated') ee on aa.emp_code = ee.emp_code - - ) as deletiondata on a.emp_code = deletiondata.emp_code and a.status != 'truncated' + employees ON employee_polices.employee_id = employees.id + + LEFT JOIN ( + SELECT + emp_code, + group_key, + MAX(CASE WHEN field_name = 'emp_status' THEN new_value END) AS empstatus, + MAX(CASE WHEN field_name = 'change_event' THEN new_value END) AS changeevent, + MAX(CASE WHEN field_name = 'date_of_exit' THEN new_value END) AS dateofexit, + MAX(CASE WHEN field_name = 'reason_for_exit' THEN new_value END) AS reasonforexit, + MAX(CASE WHEN field_name = 'status' THEN new_value END) AS status, + MAX(CASE WHEN field_name = 'claim_status' THEN new_value END) AS claimstatus + FROM + emp_endorsement + WHERE + status != 'truncated' + GROUP BY + group_key + + ) AS deletiondata + ON a.emp_code = deletiondata.emp_code AND a.status != 'truncated' LEFT JOIN - ( + ( SELECT batch_list.emp_policy_id, batch_list.batch_code AS bl, @@ -669,7 +908,7 @@ class EmployeePolicyModel extends Model batch_files.event_type = 'deletion' AND batch_files.actions = 'export' AND batch_files.insurer_or_tpa = '{$insurer_or_tpa}' - ) AS batch_data ON employee_polices.id = batch_data.emp_policy_id + ) AS batch_data ON employee_polices.id = batch_data.emp_policy_id WHERE employee_polices.client_policy_id = {$client_policy_id} AND employees.client_branch_id = {$client_branch_id} @@ -682,9 +921,15 @@ class EmployeePolicyModel extends Model group by group_key "); - $result = $query->getResult(); + if($return_type == 1){ + $result = $query->getResultArray(); + }else{ + $result = $query->getResult(); + } // dd($this->db->getLastQuery(), $result); + // dd($result); + return $result; } @@ -706,6 +951,7 @@ class EmployeePolicyModel extends Model ee.id as emp_endorsement_primarykey, ep.id as emp_policy_primarykey, e.id as employees_primarykey, + ee.file_id, ee.group_key, ( SELECT employees.id @@ -733,7 +979,12 @@ class EmployeePolicyModel extends Model CASE WHEN ee.field_name = 'status' THEN ee.new_value END - ) AS status + ) AS status, + MAX( + CASE + WHEN ee.field_name = 'claim_status' THEN ee.new_value + END + ) AS claim_status FROM emp_endorsement AS ee JOIN employee_polices AS ep ON ep.id = ee.pk @@ -743,7 +994,7 @@ class EmployeePolicyModel extends Model AND ep.client_policy_id = '$client_policy_id' AND e.client_branch_id = '$client_branch_id' AND ee.name = '$emp_name' - AND ee.field_name IN ('date_of_exit', 'reason_for_exit', 'status') + AND ee.field_name IN ('date_of_exit', 'reason_for_exit', 'status', 'claim_status') AND ep.is_active = 1 AND ep.status = 'active' AND e.is_active = 1 @@ -801,7 +1052,6 @@ class EmployeePolicyModel extends Model e.remarks, e.endorsement_id, ep.client_policy_id, - policies.name as policy_name, insurers.short_name as insurer_short_name, client_policy.policy_no, policy_type.policy_type @@ -811,9 +1061,9 @@ class EmployeePolicyModel extends Model $query1->join('employees', 'employees.id = ep.employee_id'); $query1->join('client_policy', 'client_policy.id = ep.client_policy_id'); $query1->join('client_branch', 'client_branch.id = employees.client_branch_id'); - $query1->join('policies', 'policies.id = client_policy.policy_id'); - $query1->join('policy_type', 'policy_type.id = policies.policy_type_id'); - $query1->join('insurers', 'insurers.id = policies.insurer_id'); + // $query1->join('policies', 'policies.id = client_policy.policy_id'); + $query1->join('policy_type', 'policy_type.id = client_policy.policy_type_id'); + $query1->join('insurers', 'insurers.id = client_policy.insurer_id'); $query1->whereIn('e.actions', ['c']); $query1->where('ep.client_policy_id', $policy_id); $query1->where('employees.client_id', $client_id); @@ -838,7 +1088,6 @@ class EmployeePolicyModel extends Model e.endorsement_id, e.remarks, ep.client_policy_id, - policies.name as policy_name, insurers.short_name as insurer_short_name, client_policy.policy_no, policy_type.policy_type @@ -847,10 +1096,10 @@ class EmployeePolicyModel extends Model $query2->join('employees', 'employees.id = ep.employee_id'); $query2->join('client_policy', 'client_policy.id = ep.client_policy_id'); $query2->join('client_branch', 'client_branch.id = employees.client_branch_id'); - $query2->join('policies', 'policies.id = client_policy.policy_id'); - $query2->join('policy_type', 'policy_type.id = policies.policy_type_id'); - $query2->join('insurers', 'insurers.id = policies.insurer_id'); - $query2->whereIn('e.actions', ['si', 'd']); + // $query2->join('policies', 'policies.id = client_policy.policy_id'); + $query2->join('policy_type', 'policy_type.id = client_policy.policy_type_id'); + $query2->join('insurers', 'insurers.id = client_policy.insurer_id'); + $query2->whereIn('e.actions', ['si', 'd', 'a']); $query2->where('ep.client_policy_id', $policy_id); $query2->where('employees.client_id', $client_id); $query2->where('employees.client_branch_id', $branch_id); @@ -864,6 +1113,8 @@ class EmployeePolicyModel extends Model $results2 = $query2->get()->getResultArray(); $results = array_merge($results1, $results2); + + // dd($this->db->getLastQuery()); return $results; @@ -1144,13 +1395,13 @@ class EmployeePolicyModel extends Model return "WHEN group_key = $id THEN $endorsement_id"; }, $escapedIds, $escapedEndorsementIds); - $caseStatus = array_map(function ($id, $status) { - return "WHEN status = $id THEN $status"; - }, $escapedIds, $escapedStatuses); + // $caseStatus = array_map(function ($id, $status) { + // return "WHEN status = $id THEN $status"; + // }, $escapedIds, $escapedStatuses); // Convert cases to a string $caseEndorsementIdString = implode(' ', $caseEndorsementId); - $caseStatusString = implode(' ', $caseStatus); + // $caseStatusString = implode(' ', $caseStatus); // Convert ids to a string $idsString = implode(', ', $escapedIds); @@ -1160,10 +1411,12 @@ class EmployeePolicyModel extends Model UPDATE emp_endorsement SET endorsement_id = CASE {$caseEndorsementIdString} END, - status = CASE {$caseStatusString} END + status = 'complete' WHERE group_key IN ({$idsString}) "; + + // dd($sql); // Begin a transaction $this->db->transBegin(); @@ -1180,6 +1433,7 @@ class EmployeePolicyModel extends Model // Otherwise, commit $this->db->transCommit(); } + // $this->storeEndorsementNumber($file_id, $endorsement_id, $enrollment_file_id); return $this->db->getLastQuery(); } catch (\Exception $e) { @@ -1251,5 +1505,234 @@ class EmployeePolicyModel extends Model } + //for truncate get deletion data + public function getDeletionDataForTruncated($file_id) + { + // Fetch the necessary details in a single query using JOINs + $result = $this->db->table('files f') + ->select('i.deletion_add_day') + ->join('client_policy cp', 'cp.id = f.policy_id', 'left') + ->join('insurers i', 'i.id = cp.insurer_id', 'left') + ->where('f.id', $file_id) + ->get() + ->getRowArray(); + + // Determine if one day should be added for deletion + $add_one_day = (!empty($result) && $result['deletion_add_day'] == 1) ? 1 : 0; + + + $query = $this->db->query(" + + SELECT DISTINCT + + a.id as endorsement_primarykey, + a.group_key, + employee_polices.id as primaryKey, + employees.name AS emp_name, + employees.emp_code AS emp_code, + employees.dob AS emp_dob, + employees.gender AS emp_gender, + employees.relationship AS emp_relationship, + employees.relationship_code AS emp_relationship_code, + employees.emp_type as emp_type, + 'D' as event_type_data, + TIMESTAMPDIFF(YEAR, employees.dob, CURDATE()) AS emp_age, + + employees.doj AS emp_doj, + employees.mobile AS emp_mobile, + employees.email_corporate AS emp_email_c, + employees.email_personal AS emp_email_p, + employees.band AS emp_grade, + employees.designation AS emp_designation, + employees.basic_pay AS emp_basic_pay, + + employee_polices.basic_cover_si, + employee_polices.uhid as uhid, + employee_polices.policy_end_date, + employee_polices.rata_premimum as premium, + employee_polices.claim_status, + + deletiondata.empstatus, + deletiondata.changeevent, + deletiondata.dateofexit, + deletiondata.reasonforexit, + deletiondata.status, + deletiondata.claimstatus, + + DATEDIFF(employee_polices.policy_end_date, deletiondata.dateofexit) + '$add_one_day' AS no_of_days, + + CASE + WHEN deletiondata.claimstatus = 0 OR deletiondata.claimstatus IS NULL THEN + ROUND((employee_polices.rata_premimum * (DATEDIFF(employee_polices.policy_end_date, deletiondata.dateofexit) + $add_one_day)) / 365, 2) + ELSE + 0 + END AS pro_rata_premium, + + CASE + WHEN deletiondata.claimstatus = 0 OR deletiondata.claimstatus IS NULL THEN + ROUND(((employee_polices.rata_premimum * (DATEDIFF(employee_polices.policy_end_date, deletiondata.dateofexit) + $add_one_day)) / 365) * 0.18, 2) + ELSE + 0 + END AS gst, + + CASE + WHEN deletiondata.claimstatus = 0 OR deletiondata.claimstatus IS NULL THEN + ROUND(((employee_polices.rata_premimum * (DATEDIFF(employee_polices.policy_end_date, deletiondata.dateofexit) + $add_one_day)) / 365) + + (((employee_polices.rata_premimum * (DATEDIFF(employee_polices.policy_end_date, deletiondata.dateofexit) + $add_one_day)) / 365) * 0.18), 2) + ELSE + 0 + END AS total, + + CASE + WHEN deletiondata.claimstatus = 0 OR deletiondata.claimstatus IS NULL THEN + 'No claim' + ELSE + 'Claim' + END AS claim_status + + FROM + emp_endorsement a + LEFT JOIN + employee_polices ON a.pk = employee_polices.id + LEFT JOIN + employees ON employee_polices.employee_id = employees.id + + LEFT JOIN ( + SELECT + emp_code, + group_key, + MAX(CASE WHEN field_name = 'emp_status' THEN new_value END) AS empstatus, + MAX(CASE WHEN field_name = 'change_event' THEN new_value END) AS changeevent, + MAX(CASE WHEN field_name = 'date_of_exit' THEN new_value END) AS dateofexit, + MAX(CASE WHEN field_name = 'reason_for_exit' THEN new_value END) AS reasonforexit, + MAX(CASE WHEN field_name = 'status' THEN new_value END) AS status, + MAX(CASE WHEN field_name = 'claim_status' THEN new_value END) AS claimstatus + FROM + emp_endorsement + WHERE + status != 'truncated' + GROUP BY + group_key + + ) AS deletiondata + + ON a.emp_code = deletiondata.emp_code AND a.status != 'truncated' + + WHERE a.file_id = {$file_id} + AND a.actions = 'd' + AND a.status != 'truncated' + AND employee_polices.is_active = 1 + AND employees.is_active = 1 + group by group_key + "); + + + $result = $query->getResultArray(); + // dd($this->db->getLastQuery(), $result); + // dd($result); + + return $result; + + } + + //for truncate get addition data + public function getAdditionDataForTruncated($file_id, $event_type) + { + $action = "a"; + if($event_type == "dependent_addition"){ + $action = "da"; + } + + $query = $this->db->query(" + + SELECT + ROUND(SUM(ep.rata_premimum + ep.gst), 2) AS total + FROM + emp_endorsement ee + JOIN + employee_polices ep ON ee.pk = ep.id + WHERE + ee.file_id = $file_id + AND ee.actions = '$action' + AND ep.status != 'truncated' + AND ee.status != 'truncated' + AND ee.is_active = 1 + AND ep.is_active = 1; + "); + + + $result = $query->getResultArray(); + // dd($this->db->getLastQuery(), $result); + // dd($result); + + return $result[0]; + + } + + // reverse the employee policy table data for the truncated the deletion file + public function updateEmployeePolicyTruncateReverse($file_id) + { + $this->db->query(" + UPDATE employee_polices + SET + is_active = 1, + status = 'active', + date_of_exit = NULL, + reason_for_exit = NULL, + claim_status = 0, + WHERE + id IN ( + SELECT pk + FROM emp_endorsement + WHERE file_id = $file_id + GROUP BY group_key + ) + AND status = 'inactive' + "); + + } + + //update employee policy table status truncated and is_active 0 for truncated to the addition file + public function updateEmpEndorsementAddition($array) + { + $caseStatus = "CASE "; + $caseEndorsementId = "CASE "; + $ids = []; + foreach ($array as $item) { + $caseStatus .= "WHEN id = {$item['id']} THEN '{$item['status']}' "; + $caseEndorsementId .= "WHEN id = {$item['id']} THEN '{$item['endorsement_id']}' "; + $ids[] = $item['id']; + } + $caseStatus .= "END"; + $caseEndorsementId .= "END"; + $ids = implode(',', $ids); + $query = "UPDATE emp_endorsement SET status = $caseStatus, endorsement_id = $caseEndorsementId WHERE id IN ($ids);"; // Execute the query + $this->db->query($query); + } + + //calculate the CD Transaction sum of the amount for the inception, addition, dependent addition, missed inception + public function calculateCdTranctionAmount($file_id) + { + $query = $this->db->query(" + + SELECT + ROUND(SUM(ep.rata_premimum + ep.gst), 2) AS total + FROM + employee_polices ep + WHERE + ep.file_id = $file_id + AND ep.uhid IS NOT NULL' + AND ep.status != 'truncated' + AND ep.status != 'truncated' + AND ep.is_active = 1; + "); + + + $result = $query->getResultArray(); + // dd($this->db->getLastQuery(), $result); + // dd($result); + + return $result[0]; + } } \ No newline at end of file diff --git a/app/Models/GmailSentHistoryModel.php b/app/Models/GmailSentHistoryModel.php new file mode 100644 index 00000000..9a0ae8ea --- /dev/null +++ b/app/Models/GmailSentHistoryModel.php @@ -0,0 +1,11 @@ +db->table('client_policy') - ->select('insurers.id, insurers.name, cd_master.cd_ac_no') + ->select('insurers.id, insurers.name, cd_master.cd_ac_no as cd_master_account_no') ->join('insurers', 'insurers.id = client_policy.insurer_id') ->join('cd_master', 'cd_master.insurer_id = insurers.id AND cd_master.client_id = client_policy.client_id') ->where('client_policy.insurer_id', $insurerId) ->where('client_policy.client_id', $client_id) + ->where('cd_master.id = client_policy.cd_ac_pk') ->get(); if ($query->resultID->num_rows > 0) { @@ -60,7 +61,7 @@ class InsurerModel extends Model { $insurer_data = $this->db->table('insurer_excel_export_template') ->select('insurer_excel_export_template.*, insurers.name as insurer_name, insurers.is_multi_event') - ->select('CASE WHEN insurers.is_multi_event = 1 THEN "All" ELSE insurer_excel_export_template.event_name END as event_name', false) + // ->select('CASE WHEN insurers.is_multi_event = 1 THEN "All" ELSE insurer_excel_export_template.event_name END as event_name', false) ->select('insurer_excel_export_template.type_name, insurer_excel_export_template.jsoncolumns, policy_type.policy_type') ->join('insurers', 'insurers.id = insurer_excel_export_template.insurer_id') ->join('policy_type', 'policy_type.id = insurer_excel_export_template.policy_type_id') diff --git a/app/Models/InsurerStatements.php b/app/Models/InsurerStatements.php index 0e2dc2ec..257624cd 100644 --- a/app/Models/InsurerStatements.php +++ b/app/Models/InsurerStatements.php @@ -23,7 +23,11 @@ class InsurerStatements extends Model "invoice_no", "invoice_amount", "invoice_date", - "updated_by" + "updated_by", + "stmt_sno", + "gst_per", + "gst_value", + "invoice_value" ]; diff --git a/app/Models/InvPaymentDetailsModel.php b/app/Models/InvPaymentDetailsModel.php index 262f76d6..7f7a7522 100644 --- a/app/Models/InvPaymentDetailsModel.php +++ b/app/Models/InvPaymentDetailsModel.php @@ -16,6 +16,7 @@ class InvPaymentDetailsModel extends Model 'inv_amt', 'utr_no', 'tds', + 'gst', 'received_date', 'created_by', 'is_active', diff --git a/app/Models/LeadsModel.php b/app/Models/LeadsModel.php index cae506f2..5867a5d0 100644 --- a/app/Models/LeadsModel.php +++ b/app/Models/LeadsModel.php @@ -37,7 +37,7 @@ class LeadsModel extends Model 'policy_start_date', 'policy_end_date', 'no_of_lives', - 'claims', + 'incurred_claims', 'location', 'proposed_insurer_id', 'proposed_insurer_branch_id', @@ -52,6 +52,38 @@ class LeadsModel extends Model 'updated_by', 'is_active', 'is_client_created', + + 'renewal_emp_count', + 'renewal_dept_count', + 'renewal_no_of_lives', + 'incept_emp_count', + 'incept_dept_count', + 'incept_no_of_lives', + 'exp_emp_count', + 'exp_dept_count', + 'exp_no_of_lives', + 'file_name', + + 'incurred_claims_date', + 'paid_claims', + 'outstanding_claims', + 'policy_run_days', + 'premium_at_inception', + 'premium_date', + 'earned_premium', + 'annualised_claims', + 'incurred_claims_ratio', + 'earned_claims_ratio', + + 'placement_date', + 'utr_no', + 'premium_amount', + 'total_amount', + 'cd_amount', + + 'total_si_at_incept', + 'total_si_at_renewal', + 'fin_years_claims', ]; diff --git a/app/Models/PTCOShareDetailsModel.php b/app/Models/PTCOShareDetailsModel.php index 385645ed..bb2eb359 100644 --- a/app/Models/PTCOShareDetailsModel.php +++ b/app/Models/PTCOShareDetailsModel.php @@ -63,11 +63,15 @@ class PTCOShareDetailsModel extends Model 'amount', 'stamp_duty', 'cop_amt', - 'statement_id' + 'statement_id', + 'follower_policy_no', ]; - public function getNonReconcileredPolicyTransactions(string $month,string $year,string $insurer_id,string $insurer_branch_id) + public function getNonReconcileredPolicyTransactions(string $insurer_id,string $insurer_branch_id) { + $currentDate = date('Y-m-d'); + $sixMonthsAgo = date('Y-m-01', strtotime('-6 months')); + return $this->db->table('pt_co_share_details pt_co') ->select(' pt_co.id, @@ -93,12 +97,15 @@ class PTCOShareDetailsModel extends Model ->join('policy_transaction pt', 'pt_co.pt_id = pt.id') ->join('clients c', 'pt.client_id = c.id') ->where('pt_co.is_active', 1) - ->where('MONTH(pt.month)', $month) - ->where('YEAR(pt.month)', $year) + ->where('pt.is_active', 1) + // ->where('MONTH(pt.month)', $month) + // ->where('YEAR(pt.month)', $year) ->where('pt_co.insurer_id', $insurer_id) ->where('pt_co.insurer_branch_id', $insurer_branch_id) - ->where('pt_co.statement_id is null') + // ->where('pt_co.statement_id is null') ->where('pt.status','completed') + ->where('DATE(pt.created_at) >=', $sixMonthsAgo) + ->where('DATE(pt.created_at) <=', $currentDate) // ->where('pt_co.exp_amt', 0.00) // ->orWhere('pt_co.exp_amt is null') ->get() diff --git a/app/Models/PolicyTransactionModel.php b/app/Models/PolicyTransactionModel.php index ba54a5ce..0364fd17 100644 --- a/app/Models/PolicyTransactionModel.php +++ b/app/Models/PolicyTransactionModel.php @@ -76,6 +76,7 @@ class PolicyTransactionModel extends Model 'ct_tran_id', 'remarks', 'month', + 'cd_ac_pk' ]; @@ -113,8 +114,9 @@ class PolicyTransactionModel extends Model return $data; } + // BDS Report OLD Functin for QUERY // public function getBDSReportList($client_id, $policy_id, $branch_id, $issuer) - public function getBDSReportList($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0) + public function getBDSReportListOld($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0) { $builder = $this->db->table('policy_transaction') ->select(" @@ -311,6 +313,257 @@ class PolicyTransactionModel extends Model return $builder->get()->getResultArray(); } + + // BDS Report NEW Functin for QUERY + // public function getBDSReportList($client_id, $policy_id, $branch_id, $issuer) + public function getBDSReportList($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0, $client_branch_id = 0, $insurer_branch_id = 0, $client_policy_id = 0) + { + + $date_condition = ''; + if($date_type == 'statement_month' && $start_date != 0 && $end_date != 0) { + $date_condition = " + AND insurer_statements.month >= '".$start_date ."' + AND insurer_statements.month <= '".$end_date ."' + "; + } + + $builder = $this->db->table('policy_transaction') + ->select(" + policy_transaction.*, + DATE_FORMAT(policy_transaction.policy_issue_date, '%d %b %Y') AS policy_issue_date, + DATE_FORMAT( + IF(policy_transaction.month IS NULL, + policy_transaction.policy_issue_date, + policy_transaction.month), + '%b %Y') AS policy_issue_month, + CASE + WHEN clients.client_type = 1 THEN 'Group' + WHEN clients.client_type = 2 THEN 'Retail' + ELSE '-' + END AS client_type, + CASE + WHEN policy_transaction.revenue_type = 'NA' THEN 'Fresh' + ELSE 'Renewal' + END AS revenue_type, + CASE + WHEN policy_transaction.action_type = 'inception' THEN 'Policy' + ELSE 'Endorsement' + END AS action_type, + clients.client_name AS client_name, + clients.short_name AS client_short_name, + client_branch.branch_name AS client_branch_name, + client_branch.address1 AS client_address, + policy_type.policy_type, + policy_type.bap, + insurers.name AS insurer_name, + insurers.short_name AS insurer_short_name, + insurer_branch.branch_name AS insurer_branch_name, + insurer_branch.branch_code AS insurer_branch_code, + user_profiles.first_name as user_name, + vehicle.vehicle_no, + tpa.name as tpa_name, + pt_co_share_details.remark as remarks, + pt_co_share_details.reward, + pt_co_share_details.bp_amt, + pt_co_share_details.exp_amt, + pt_co_share_details.id as pt_id, + sales_user.first_name as salse_person_name, + service_user.first_name as service_person_name, + + ROUND((pt_co_share_details.bp_amt + pt_co_share_details.tp_amt + pt_co_share_details.tep_amt), 2) AS premium_wo_gst, + + ROUND((ROUND((pt_co_share_details.bp_amt + pt_co_share_details.tp_amt + pt_co_share_details.tep_amt), 2) * 18 / 100), 2) AS gst_amount, + + ROUND((ROUND((pt_co_share_details.bp_amt + pt_co_share_details.tp_amt + pt_co_share_details.tep_amt), 2) + ROUND((ROUND((pt_co_share_details.bp_amt + pt_co_share_details.tp_amt + pt_co_share_details.tep_amt), 2) * 18 / 100), 2)), 2) AS total_premium, + + ROUND((pt_co_share_details.tp_amt + pt_co_share_details.tep_amt), 2) AS tp_or_ter, + + DATEDIFF(policy_transaction.policy_end_date, CURDATE()) AS days, + + (pt_co_share_details.agreed_tp_per + pt_co_share_details.agreed_tep_per) AS agreed_tp_or_ter_per, + + pt_co_share_details.agreed_bp_per, + + ROUND( + ( + SELECT + ( + SUM(co_share_stmt_details.actual_bp_brokerage_amt) + + SUM(co_share_stmt_details.actual_tp_brokerage_amt) + + SUM(co_share_stmt_details.actual_tep_brokerage_amt) + + SUM(co_share_stmt_details.reward) + + ) AS total_irda_amt + FROM + co_share_stmt_details + JOIN insurer_statements ON co_share_stmt_details.statement_id = insurer_statements.id + WHERE + co_share_stmt_details.co_share_id = pt_co_share_details.id + AND co_share_stmt_details.is_active = 1 + AND insurer_statements.is_active = 1 + $date_condition + ), + 2 + ) AS total_irda_amt, + + ROUND( + ( + SELECT + SUM( + COALESCE(co_share_stmt_details.actual_bp_brokerage_amt, 0) + + COALESCE(co_share_stmt_details.actual_tp_brokerage_amt, 0) + + COALESCE(co_share_stmt_details.actual_tep_brokerage_amt, 0) + + COALESCE(co_share_stmt_details.reward, 0) + ) AS total_irda_amt + FROM + co_share_stmt_details + JOIN pt_co_share_details AS pt_table ON co_share_stmt_details.co_share_id = pt_table.id + JOIN insurer_statements ON co_share_stmt_details.statement_id = insurer_statements.id + WHERE + co_share_stmt_details.co_share_id = pt_co_share_details.id + AND co_share_stmt_details.is_active = 1 + AND pt_table.is_active = 1 + AND insurer_statements.is_active = 1 + AND insurer_statements.invoice_no IS NOT NULL + $date_condition + + ), + 2 + ) AS billed_amt, + + ROUND( + ( + ( + SELECT + SUM( + COALESCE(co_share_stmt_details.actual_bp_brokerage_amt, 0) + + COALESCE(co_share_stmt_details.actual_tp_brokerage_amt, 0) + + COALESCE(co_share_stmt_details.actual_tep_brokerage_amt, 0) + + COALESCE(co_share_stmt_details.reward, 0) + ) + FROM + co_share_stmt_details + JOIN insurer_statements ON co_share_stmt_details.statement_id = insurer_statements.id + WHERE + co_share_stmt_details.co_share_id = pt_co_share_details.id + AND co_share_stmt_details.is_active = 1 + $date_condition + ) + - + ( + SELECT + SUM( + COALESCE(co_share_stmt_details.actual_bp_brokerage_amt, 0) + + COALESCE(co_share_stmt_details.actual_tp_brokerage_amt, 0) + + COALESCE(co_share_stmt_details.actual_tep_brokerage_amt, 0) + + COALESCE(co_share_stmt_details.reward, 0) + ) + FROM + co_share_stmt_details + JOIN pt_co_share_details AS pt_table ON co_share_stmt_details.co_share_id = pt_table.id + JOIN insurer_statements ON co_share_stmt_details.statement_id = insurer_statements.id + WHERE + co_share_stmt_details.co_share_id = pt_co_share_details.id + AND co_share_stmt_details.is_active = 1 + AND pt_table.is_active = 1 + AND insurer_statements.is_active = 1 + AND insurer_statements.invoice_no IS NULL + $date_condition + ) + ), + 2 + ) AS unbilled_amt + + ") + ->join('pt_co_share_details', 'policy_transaction.id = pt_co_share_details.pt_id', 'left') + ->join('insurer_statements', 'pt_co_share_details.statement_id = insurer_statements.id', 'left') + ->join('clients', 'clients.id = policy_transaction.client_id') + ->join('client_branch', 'policy_transaction.client_branch_id = client_branch.id', 'left') + ->join('client_policy', 'policy_transaction.client_policy_id = client_policy.id', 'left') + ->join('user_profiles', 'policy_transaction.created_by = user_profiles.id', 'left') + ->join('vehicle', 'policy_transaction.vehicle_id = vehicle.id', 'left') + ->join('policy_type', 'policy_transaction.policy_type_id = policy_type.id', 'left') + ->join('insurers', 'policy_transaction.insurer_id = insurers.id', 'left') + ->join('insurer_branch', 'policy_transaction.insurer_branch_id = insurer_branch.id', 'left') + ->join('tpa', 'policy_transaction.tpa_id = tpa.id', 'left') + ->join('tpa_branch', 'policy_transaction.tpa_branch_id = tpa_branch.id', 'left') + ->join('user_profiles AS sales_user', 'policy_transaction.sales_generated_by = sales_user.id', 'left') + ->join('user_profiles AS service_user', 'policy_transaction.serviced_by = service_user.id', 'left') + ->where('policy_transaction.is_active', 1) + ->where('pt_co_share_details.is_active', 1); + + // Check if the start date and end date are provided + if ($start_date != 0 && $end_date != 0 && $date_type != 0 && $date_type != 'statement_month') { + + $startDate = date('Y-m-d 00:00:00', strtotime($start_date)); + $endDate = date('Y-m-d 23:59:59', strtotime($end_date)); + + $builder->where('policy_transaction.'.$date_type.'>=', $startDate) + ->where('policy_transaction.'.$date_type.'<=', $endDate); + + }else{ + + // $fromDate = date('Y-m-d', strtotime('-30 days')); + // $toDate = date('Y-m-d 23:59:59'); + + // $builder->where('policy_transaction.created_at >=', $fromDate) + // ->where('policy_transaction.created_at <=', $toDate); + } + + if($date_type == 'statement_month' && $start_date != 0 && $end_date != 0){ + + $builder->where('policy_transaction.month >=', $startDate) + ->where('policy_transaction.month <=', $endDate); + } + + if ($client_id != 0) { + $builder->where('policy_transaction.client_id', $client_id); + } + + if ($insurer_id != 0) { + $builder->where('policy_transaction.insurer_id', $insurer_id); + } + + if ($client_branch_id != 0) { + $builder->where('policy_transaction.client_branch_id', $client_branch_id); + } + + if ($insurer_branch_id != 0) { + $builder->where('policy_transaction.insurer_branch_id', $insurer_branch_id); + } + + if ($client_policy_id != 0) { + $builder->where('policy_transaction.client_policy_id', $client_policy_id); + } + + + + if ($policy_type_id != 0) { + $builder->where('client_policy.policy_type_id', $policy_type_id); + } + + if ($issuer != 0) { + $builder->where('policy_transaction.issuer', $issuer); + } + + if($client_id == 0 && $insurer_id == 0 && $policy_type_id == 0 && $date_type == 0 && $issuer == 0){ + + $fromDate = date('Y-m-d', strtotime('-30 days')); + $toDate = date('Y-m-d 23:59:59'); + + $builder->where('policy_transaction.created_at >=', $fromDate) + ->where('policy_transaction.created_at <=', $toDate); + + } + + $builder->orderBy('policy_transaction.id', 'desc'); + + $result = $builder->get()->getResultArray(); + + // dd($this->db->getLastQuery()); + + return $result; + } public function getInceptionTranctionListData($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0, $status = 0) { @@ -466,50 +719,74 @@ class PolicyTransactionModel extends Model return $builder->get()->getResultArray(); } - public function getVarienceReportLIst($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0, $status = 0) + public function getVarienceReportLIst($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0, $client_branch_id = 0, $insurer_branch_id = 0, $client_policy_id = 0) { $builder = $this->db->table('policy_transaction') ->select(" + policy_transaction.id, clients.client_name, + client_branch.branch_name as client_branch_name, insurers.name AS insurer_name, + insurer_branch.branch_name AS insurer_branch_name, policy_type.policy_type, policy_transaction.policy_no, policy_transaction.endorsement_no, - CASE - WHEN policy_transaction.action_type = 'inception' THEN 'I' - ELSE 'E' - END AS action_type, + pt_co_share_details.exp_amt, pt_co_share_details.variance, - insurer_statements.invoice_amount, - insurer_statements.invoice_status, - - ROUND((pt_co_share_details.actual_bp_brokerage_amt + pt_co_share_details.actual_tp_brokerage_amt + pt_co_share_details.actual_tep_brokerage_amt), 2) AS realization_amount2, + ROUND( ( SELECT - (SUM(inv_payment_details.inv_amt) + SUM(inv_payment_details.tds)) AS realization_amount + ( + SUM(co_share_stmt_details.actual_bp_brokerage_amt) + SUM(co_share_stmt_details.actual_tp_brokerage_amt) + SUM(co_share_stmt_details.actual_tep_brokerage_amt) + ) AS total_irda_amt FROM - inv_payment_details + co_share_stmt_details + JOIN insurer_statements ON co_share_stmt_details.statement_id = insurer_statements.id WHERE - inv_payment_details.statement_id = insurer_statements.id - AND inv_payment_details.is_active = 1 - - ) AS realization_amount, + co_share_stmt_details.co_share_id = pt_co_share_details.id + AND co_share_stmt_details.is_active = 1 + ), + 2 + ) AS statement_amount, + + ROUND( + pt_co_share_details.exp_amt - + ( + SELECT + ( + SUM(co_share_stmt_details.actual_bp_brokerage_amt) + + SUM(co_share_stmt_details.actual_tp_brokerage_amt) + + SUM(co_share_stmt_details.actual_tep_brokerage_amt) + ) + FROM co_share_stmt_details + JOIN insurer_statements + ON co_share_stmt_details.statement_id = insurer_statements.id + WHERE + co_share_stmt_details.co_share_id = pt_co_share_details.id + AND co_share_stmt_details.is_active = 1 + ), + 2 + ) AS variance_amt + ") ->join('pt_co_share_details', 'policy_transaction.id = pt_co_share_details.pt_id', 'left') ->join('insurer_statements', 'pt_co_share_details.statement_id = insurer_statements.id', 'left') - ->join('inv_payment_details', 'insurer_statements.id = inv_payment_details.statement_id', 'left') ->join('clients', 'clients.id = policy_transaction.client_id', 'left') + ->join('client_branch', 'client_branch.id = policy_transaction.client_branch_id', 'left') ->join('insurers', 'pt_co_share_details.insurer_id = insurers.id', 'left') + ->join('insurer_branch', 'pt_co_share_details.insurer_branch_id = insurer_branch.id', 'left') ->join('client_policy', 'policy_transaction.client_policy_id = client_policy.id', 'left') ->join('policy_type', 'policy_transaction.policy_type_id = policy_type.id', 'left') ->where('policy_transaction.is_active', 1) - ->where('pt_co_share_details.actual_bp_brokerage_amt IS NOT NULL AND pt_co_share_details.actual_bp_brokerage_amt != 0') - ->where('pt_co_share_details.variance IS NOT NULL') - ->where('pt_co_share_details.variance !=', 0); + ->where('pt_co_share_details.is_active', 1) + ->having('variance_amt IS NOT NULL'); + // ->where('pt_co_share_details.actual_bp_brokerage_amt IS NOT NULL AND pt_co_share_details.actual_bp_brokerage_amt != 0'); + // ->where('pt_co_share_details.variance IS NOT NULL') + // ->where('pt_co_share_details.variance !=', 0); if ($start_date != 0 && $end_date != 0 && $date_type != 0) { @@ -543,9 +820,18 @@ class PolicyTransactionModel extends Model $builder->where('policy_transaction.issuer', $issuer); } - if ($status != 0) { - $builder->where('policy_transaction.status', $status); + if ($client_branch_id != 0) { + $builder->where('policy_transaction.client_branch_id', $client_branch_id); } + + if ($insurer_branch_id != 0) { + $builder->where('policy_transaction.insurer_branch_id', $insurer_branch_id); + } + + if ($client_policy_id != 0) { + $builder->where('policy_transaction.client_policy_id', $client_policy_id); + } + $builder->orderBy('policy_transaction.id', 'desc'); @@ -694,7 +980,7 @@ class PolicyTransactionModel extends Model return $builder->get()->getResultArray(); } - public function getOutstandingReportList($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0, $status = 0) + public function getOutstandingReportList_OLD($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0, $status = 0) { $builder = $this->db->table('policy_transaction') ->select(" @@ -791,5 +1077,53 @@ class PolicyTransactionModel extends Model return $builder->get()->getResultArray(); } + + public function getOutstandingReportList($start_date = 0, $end_date = 0, $insurer_id = 0,$insurer_branch_id = 0) + { + $builder = $this->db->table('insurer_statements s') + ->select(' + s.id, + s.insurer_id, + s.branch_id, + ins.short_name, + ib.branch_name, + s.month, + s.line_items, + s.stmt_sno, + s.invoice_status, + s.invoice_date, + s.invoice_no, + s.invoice_amount, + COALESCE(SUM(p.inv_amt) + SUM(p.tds) + SUM(p.gst), 0) AS total_paid, + (s.invoice_amount - COALESCE(SUM(p.inv_amt) + SUM(p.tds) + SUM(p.gst), 0)) AS outstanding_amount + ') + ->join('inv_payment_details p', 's.id = p.statement_id', 'left') + ->join('insurers ins', 's.insurer_id = ins.id') + ->join('insurer_branch ib', 's.branch_id = ib.id') + ->where('s.is_active', 1) + ->where('p.is_active', 1) + ->groupBy('s.id, s.invoice_no, s.invoice_date, s.invoice_amount') + ->having('outstanding_amount >', 0); + // ->get(); + + + // Date range filtering + if ($start_date != 0 && $end_date != 0) { + + $builder->where('s.month >=', $start_date) + ->where('s.month <=', $end_date); + } + + if ($insurer_id != 0) { + $builder->where('s.insurer_id', $insurer_id); + } + if ($insurer_branch_id != 0) { + $builder->where('s.branch_id', $insurer_branch_id); + } + + $builder->orderBy('s.id', 'desc'); + + return $builder->get()->getResultArray(); + } } diff --git a/app/Models/RFQModel.php b/app/Models/RFQModel.php index d616e517..2b1560e0 100644 --- a/app/Models/RFQModel.php +++ b/app/Models/RFQModel.php @@ -60,14 +60,13 @@ class RFQModel extends Model public function getRFQTableDataWithLeadIDAndType($lead_id, $type){ return $this->select(' - leads.client_name, - leads.client_short_name, + leads.*, insurers.name as insurer_name, insurer_branch.branch_name as insurer_branch_name, tpa.name as tpa_name, tpa_branch.branch_name as tpa_branch_name, policy_type.policy_type, - rfq.json + rfq.json, ') ->join('leads', 'rfq.lead_id = leads.id') ->join('policy_type', 'leads.policy_type_id = policy_type.id') @@ -76,7 +75,7 @@ class RFQModel extends Model ->join('tpa', 'leads.tpa_id = tpa.id', 'left') ->join('tpa_branch', 'leads.tpa_branch_id = tpa_branch.id', 'left') ->where('rfq.lead_id', $lead_id) - ->where('rfq.type', $type) + // ->where('rfq.type', $type) ->where('rfq.is_active', 1) ->first(); diff --git a/app/Views/UserList.php b/app/Views/UserList.php index 37ce4dd5..be654b8d 100755 --- a/app/Views/UserList.php +++ b/app/Views/UserList.php @@ -182,7 +182,9 @@ $(document).ready(function () { $('#tickets-table').DataTable({ - dom: "<'row'<'col-sm-0'f><'col-sm-9 text-right'B>>" , + dom: "<'row'<'col-sm-0'f><'col-sm-9 text-right'B>>" + // Keep your original alignment for the search and buttons + "<'row'<'col-sm-12'tr>>" + // Table rows + "<'row'<'col-sm-6'i><'col-sm-6'p>>", buttons: [ { extend: 'csv', diff --git a/app/Views/batch_list.php b/app/Views/batch_list.php index b5747912..4d85d018 100755 --- a/app/Views/batch_list.php +++ b/app/Views/batch_list.php @@ -41,6 +41,7 @@ (₹)Amount User/Time Status + Action @@ -69,77 +70,89 @@ by + - +   - +   - + failed -   - + failed -   - - + + failed -   - - + + failed + + failed -   - - + - -   - + + + + + + + - - \ No newline at end of file + } + + // Format numbers when the DOM content is loaded + document.addEventListener("DOMContentLoaded", function() { + setTimeout(() => { + + formatNumbersByClass('indian-number'); + + }, 500); + }); + + function getBatchFileData(input){ + + let client_id = $(input).data('client_id') + let client_policy_id = $(input).data('client_policy_id') + let client_branch_id = $(input).data('client_branch_id') + let insurer_or_tpa = $(input).data('insurer_or_tpa') + let event_type = $(input).data('event_type') + let actions = $(input).data('actions') + + console.log('client_id', client_id); + console.log('client_policy_id', client_policy_id); + console.log('client_branch_id', client_branch_id); + console.log('insurer_or_tpa', insurer_or_tpa); + console.log('event_type', event_type); + console.log('actions', actions); + + $('#batch_file_client_id').val(client_id); + $('#batch_file_policy_id').val(client_policy_id); + $('#batch_file_branch_id').val(client_branch_id); + $('#batch_file_insurer_or_tpa').val(insurer_or_tpa); + $('#batch_file_action_type').val(actions); + $('#batch_file_event_type').val(event_type); + + + var myModal = new bootstrap.Modal(document.getElementById('batch_file_upload_modal')); + myModal.show(); + + + // $('.loader').fadeIn(); + // $('.loader-mask').fadeIn(); + + // console.log('file_id', file_id); + // let url = ''; + + // // Data to send in the AJAX request + // let requestData = { + // file_id: file_id, + // }; + + // // Send AJAX request + // sendAjaxRequestForGlobal(url, 'GET', requestData, function(response) { + + // console.log('Data fetched successfully:', response); + // console.log('Data fetched successfully:', response.batch_file_data); + // console.log('response.batch_file_data.client_branch_id:', response.batch_file_data.client_branch_id); + + // if (response.status == true) { + + // } else { + + // toastr.warning(response.message || 'Unable to fetch data', 'WARNING'); + // } + + // $('.loader').fadeOut(); + // $('.loader-mask').delay(350).fadeOut('slow'); + + // }, function(xhr, status, error) { + // console.error('Error fetching data:', error); + // console.error(xhr.responseText); + // toastr.error('An error occurred while checking the SI amount.', 'ERROR'); + + // $('.loader').fadeOut(); + // $('.loader-mask').delay(350).fadeOut('slow'); + // // addRow(); + // }); + } + + + \ No newline at end of file diff --git a/app/Views/business_team_list.php b/app/Views/business_team_list.php index 33c99426..81977a54 100644 --- a/app/Views/business_team_list.php +++ b/app/Views/business_team_list.php @@ -16,6 +16,32 @@ table.dataTable tbody td { .dataTables_filter { position: absolute; } +.custom-dropdown-menu { + display: none; + position: absolute; + background-color: #ffffff !important; + border: 1px solid rgba(0, 0, 0, 0.15); + border-radius: 0.25rem; + padding: 0.5rem 0; + min-width: 10rem; + z-index: 9999; + box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); +} + +.custom-dropdown-menu .dropdown-item { + display: block !important; + width: 100% !important; + padding: 0.5rem 1rem !important; + color: #212529 !important; + text-decoration: none !important; + background-color: transparent !important; +} + +.custom-dropdown-menu .dropdown-item:hover { + background-color: #f8f9fa !important; + color: #16181b !important; + cursor: pointer !important; +}
@@ -209,6 +235,97 @@ table.dataTable tbody td {
+ + + \ No newline at end of file diff --git a/app/Views/client_deposit_list.php b/app/Views/client_deposit_list.php index 3df642a9..d19d0ec6 100755 --- a/app/Views/client_deposit_list.php +++ b/app/Views/client_deposit_list.php @@ -33,7 +33,7 @@ insurer_name;?> - cd_ac_no;?> + cd_master_account_no;?> ₹
@@ -114,6 +141,123 @@ table.dataTable thead th {
+ \ No newline at end of file diff --git a/app/Views/client_policy.php b/app/Views/client_policy.php index a0bb84b5..cf219b6c 100755 --- a/app/Views/client_policy.php +++ b/app/Views/client_policy.php @@ -37,12 +37,14 @@
+ +
@@ -56,7 +58,7 @@
- + @@ -77,7 +79,7 @@
@@ -244,7 +257,6 @@ } }) - var policy_PrimaryKey = $('#client_id_policy').val(); var policy_client = $('#policy_PrimaryKey').val(); @@ -301,11 +313,11 @@ allowInput: false }); - var reminderDatePicker = flatpickr("#reminder_date", { - dateFormat: "d-m-Y", - defaultDate: today, - allowInput: false - }); + // var reminderDatePicker = flatpickr("#reminder_date", { + // dateFormat: "d-m-Y", + // defaultDate: today, + // allowInput: false + // }); $('#add_form').hide(); @@ -521,7 +533,7 @@ var formData = new FormData($('#policy_form')[0]); var policy_form_action = $('#policy_form_action').val(); - + console.log(formData+'form data'); $.ajax({ data: formData, url: policy_form_action, @@ -690,8 +702,8 @@ $.get(url_for_cd, function(response){ - //console.log(response) - //console.log(response.data) + // console.log(response) + // console.log(response.data) if(response.status == false && response.insurer_id != 'undefined'){ toastr.warning('The CD Account Number not found.', 'Warning'); @@ -784,13 +796,14 @@ $('#open_date').val(rearrangeDateFormat(res.data.open_date)); $('#end_date').val(rearrangeDateFormat(res.data.policy_end_date)); $('#close_date').val(rearrangeDateFormat(res.data.close_date)); - $('#reminder_date').val(rearrangeDateFormat(res.data.reminder_date)); + $('#reminder_date').val(res.data.reminder_date); $('#disclaimer').val(res.data.disclaimer); $('#gst_no').val(gst); $('#policy_status').val(checkDateStatus(res.data.policy_end_date)); $('#policy_status_field').show(); + //Open for enrollment yes or no if (res.data.inception_type == 2) { $('#inception_type').prop('checked', true); $('#open_date').parent().show(); @@ -805,13 +818,20 @@ $('.dateofdata').attr('required', false); } - + //Policy Visibility in Web App if (res.data.enrolment_visibility == 1) { $('#policy_visibility').prop('checked', true); } else { $('#policy_visibility').prop('checked', false); } + // Member Modify Data Enable or Disable + // if (res.data.is_member_modify_allowed == 1) { + // $('#is_member_modify_allowed').prop('checked', true); + // } else { + // $('#is_member_modify_allowed').prop('checked', false); + // } + // if (res.data.is_addon != '1' && res.data.is_addon != '0') { // $('#base_policy_id').show(); @@ -874,14 +894,14 @@ if (res.data.is_addon == 2 || res.data.is_addon == 3) { $("#insurer").next(".select2-container").css({ - 'pointer-events': 'none', + 'pointer-events': 'auto', }); $('#select2-insurer-container').css({ 'background-color': '#ebebe0', }); $("#tpa").next(".select2-container").css({ - 'pointer-events': 'none', + 'pointer-events': 'auto', }); $('#select2-tpa-container').css({ 'background-color': '#ebebe0', @@ -1178,7 +1198,9 @@ } else if (input) { // console.log( 'input type step 2', typeof input); // Handle the case where input is a string - number = parseFloat(input.replace(/,/g, ''), 10); + // number = parseFloat(input.replace(/,/g, ''), 10); + number = parseFloat(String(input).replace(/,/g, ''), 10); + } else { // Handle the case where input is undefined or null number = NaN; // or handle as needed @@ -1334,7 +1356,7 @@ if ($(this).val() == 4 || $(this).val() == 5) { $("#insurer").next(".select2-container").css({ - 'pointer-events': 'none', + 'pointer-events': 'auto', }); $('#select2-insurer-container').css({ @@ -1342,7 +1364,7 @@ }); $("#tpa").next(".select2-container").css({ - 'pointer-events': 'none', + 'pointer-events': 'auto', }); $('#select2-tpa-container').css({ @@ -1627,7 +1649,7 @@ $.each(data, function(index, item) { const option = $('