diff --git a/app/Config/Constants.php b/app/Config/Constants.php index eee4bdcd..5cd84385 100755 --- a/app/Config/Constants.php +++ b/app/Config/Constants.php @@ -94,12 +94,12 @@ define('EVENT_PRIORITY_NORMAL', 100); define('EVENT_PRIORITY_HIGH', 10); /** - * @User Role Constant + * @User Teams Constant */ - define('ENROLLMENT_TEAM_ID', '1'); define('CLAIMS_TEAM_ID', '2'); -define('BUSINESS_TEAM_ID', '3'); +// define('BUSINESS_TEAM_ID', '3'); // old don't delete it +define('BUSINESS_TEAM_ID', '4'); // 25th OCT 2025 changed define('FINANCE_TEAM_ID', '4'); define('SALES_TEAM_ID', '5'); define('MANAGEMENT_TEAM_ID', '6'); @@ -107,9 +107,8 @@ define('BUSINESS_SUPPORT_TEAM_ID', '7'); define('POS_TEAM_ID', '8'); /** - * @User Teams Constant + * @User Role Constant */ - define('ADMIN_ROLE_ID', 1); define('MANAGER_ROLE_ID', 2); define('ACCOUNT_MANAGER_ROLE_ID', 3); diff --git a/app/Config/Routes.php b/app/Config/Routes.php index 06f81344..d127bcc7 100755 --- a/app/Config/Routes.php +++ b/app/Config/Routes.php @@ -48,6 +48,7 @@ $routes->get("frontend_content", "AppContentManagementController::frontend_conte $routes->get('/test', 'Home::index'); $routes->get('/check_gemini', 'Home::check_Gemini'); $routes->get('/check_gemini2', 'Home::check_gemini_2'); +$routes->get('/checkPolicyDoc', 'Home::checkPolicyDoc'); $routes->get('/login', 'LoginController::index'); ///auth/google $routes->get('/loginPos', 'LoginController::loginPos'); //login POS team $routes->post('/getVerifyPosMobileNo', 'LoginController::getVerifyPosMobileNo'); //Verify POS team mobile no @@ -212,6 +213,7 @@ $routes->group("/master", ["filter" => "authMVC"], function ($routes) { $routes->post("edit", "MasterController::editInsurerBranch"); $routes->get("editget/(:any)", "MasterController::editInsurerGet/$1"); $routes->get("list/(:any)", "MasterController::insurerBranchList/$1"); + $routes->post("getList", "MasterController::getInsurerBranchList"); $routes->get("remove/(:any)", "MasterController::removeInsurerBranch/$1"); }); }); @@ -395,6 +397,11 @@ $routes->group("/util", ["filter" => "authMVC"], function ($routes) { $routes->get('getMemberDataExcelFileErrors', 'LeadsController::getMemberDataExcelFileErrors'); $routes->post('savePlacementDataAndValidateMemberDataFile', 'LeadsController::savePlacementDataAndValidateMemberDataFile'); $routes->get('checkMemberDataFileValidationStatus', 'LeadsController::checkMemberDataFileValidationStatus'); + $routes->match(['get', 'post', 'delete'], 'nhanceBranchMaster', 'MasterController::nhanceBranchMaster'); + $routes->match(['get', 'post', 'delete'], 'vehicleTypeMaster', 'MasterController::vehicleTypeMaster'); + $routes->match(['get', 'post', 'delete'], 'rtoMaster', 'MasterController::rtoMaster'); + $routes->get('checkDuplicateCdAccount', 'MasterController::checkDuplicateCdAccount'); + $routes->get('proceedExcelFileDataValidation', 'EmployeeController::proceedExcelFileDataValidation'); }); $routes->post("policy_tranction/sendInstallmentRemainderMail","PolicyTransactionController::sendInstallmentRemainderMail"); @@ -420,13 +427,14 @@ $routes->group("policy_tranction", ["filter" => "authMVC"], function ($routes) { $routes->get("remove/(:any)", "PolicyTransactionController::removeCDMaster/$1"); }); - $routes->group("report", ["filter" => "authMVC"], function ($routes) { - $routes->match(['get', 'post'],"list", "PolicyTransactionController::reportBDS"); - $routes->get("report-varience-list", "PolicyTransactionController::reportVarience"); - $routes->get("report-business-list", "PolicyTransactionController::reportBusinessList"); - $routes->get("report-finance-list", "PolicyTransactionController::reportFinanceList"); - $routes->get("report-outstanding-list", "PolicyTransactionController::reportOutstanding"); - }); + $routes->group("report", ["filter" => "authMVC"], function ($routes) { + $routes->match(['get', 'post'],"list", "PolicyTransactionController::reportBDS"); + $routes->match(['get', 'post'],"list_new", "PolicyTransactionController::reportBDSNew"); + $routes->get("report-varience-list", "PolicyTransactionController::reportVarience"); + $routes->get("report-business-list", "PolicyTransactionController::reportBusinessList"); + $routes->get("report-finance-list", "PolicyTransactionController::reportFinanceList"); + $routes->get("report-outstanding-list", "PolicyTransactionController::reportOutstanding"); + }); $routes->group("statement", ["filter" => "authMVC"], function ($routes) { $routes->get("list", "PolicyTransactionController::statementList"); @@ -493,12 +501,16 @@ $routes->cli('cli/sendMailWithAutoQuery','TicketController::sendMailWithAutoQuer //Employee login api's $routes->post("/employeeRest/verifyEmployeeNumber", "RestAuthenticationController::verifyEmployeeWithMobileNumber"); $routes->post("/employeeRest/getVerifiedUserData", "RestAuthenticationController::getVerifiedUserData"); -$routes->post("/employeeRest/verifyMpin", "RestAuthenticationController::verifyMpin"); -$routes->post("/employeeRest/checkMpin", "RestAuthenticationController::checkMpin"); $routes->post("/employeeRest/verifyEmployeeEmailId", "RestAuthenticationController::verifyEmployeeWithEmailId"); $routes->post("/employeeRest/updateEmpOTP", "RestAuthenticationController::updateEmpOTP"); + +$routes->post("employeeRest/saveMpin", "RestAuthenticationController::saveMpin"); +$routes->post("employeeRest/updateMpin", "RestAuthenticationController::updateMpin"); +$routes->post("/employeeRest/verifyMpin", "RestAuthenticationController::verifyMpin"); +$routes->post("/employeeRest/checkMpin", "RestAuthenticationController::checkMpin"); $routes->post("/employeeRest/updateEmpMPIN", "RestAuthenticationController::updateEmpMPIN"); $routes->post("employeeRest/forgotMPIN", "RestAuthenticationController::forgotMPIN"); +$routes->post("employeeRest/updateMobileNumber", "RestAuthenticationController::updateMobileNumber"); // $routes->post("/employeeRest/saveMpin", "RestAuthenticationController::saveMpin"); @@ -522,8 +534,6 @@ $routes->group("/api", ["filter" => "authJWT"], function ($routes) { $routes->post("getId", "RestAuthenticationController::getUserIdFromToken"); }); -$routes->post("employeeRest/saveMpin", "RestAuthenticationController::saveMpin"); -$routes->post("employeeRest/updateMpin", "RestAuthenticationController::updateMpin"); $routes->post("employeeRest/getPostEmployeeDataForAuth", "RestAuthenticationController::getPostEmployeeDataForAuth"); // $routes->post("logHrActivity", "RestAuthenticationController::logHrActivity"); @@ -734,6 +744,9 @@ $routes->group('test', function($routes) { $routes->get('mapping_client_id_and_branch_id','TestingController::mapping_client_id_and_branch_id'); $routes->get('membervalidation', 'TestingController::membervalidation'); $routes->get('generateExcel', 'TestingController::generateExcel'); + $routes->get('logo_renaming','TestingController::logo_renaming'); + // $routes->get('createDefaultMailTempalteInDB','TestingController::createDefaultMailTempalteInCrossDB'); + // $routes->get('createDefaultMailTempalteInSameDB','TestingController::createDefaultMailTempalteInSameDB'); }); $routes->cli('cli/testcli', 'TestingController::testcli'); diff --git a/app/Controllers/BDSReportController.php b/app/Controllers/BDSReportController.php index 355df367..9ba0dca9 100644 --- a/app/Controllers/BDSReportController.php +++ b/app/Controllers/BDSReportController.php @@ -181,7 +181,7 @@ class BDSReportController extends AdminController 'Client' => 'client' ]; - $data['page_name'] = "IRBA Report"; + $data['page_name'] = "IRDA Report"; return $this->loadLayout('irba_report', $data); } else { @@ -202,9 +202,11 @@ class BDSReportController extends AdminController $viewData = []; } + $view_name = "bds_report_Insurer_wise_Data" ; + $html = view('bds_report_Insurer_wise_Data', $viewData); - return $this->respond(['status' => true, 'html' => $html], 200); + return $this->respond(['status' => true, 'html' => $html , 'view_name' => $view_name], 200); } else if ($report_type == 'bap') { $life = $category == 'life' ? 1 : 0; @@ -217,33 +219,40 @@ class BDSReportController extends AdminController $viewData = []; } + $view_name = "bds_report_bap_wise_data"; $html = view('bds_report_bap_wise_data', $viewData); - return $this->respond(['status' => true, 'html' => $html], 200); + return $this->respond(['status' => true, 'html' => $html , 'view_name' => $view_name], 200); } else if ($report_type == 'bapInsurer') { //Condition for BAP Insurer wise date $category = $category == 'life' ? 1 : 0; $viewData['data'] = $this->getBAPInsurerData($category, $fromDate, $toDate); + + $view_name = "irda_bap_insurer_report_list"; $html = view('irda_bap_insurer_report_list', $viewData); - return $this->respond(['status' => true, 'html' => $html], 200); + return $this->respond(['status' => true, 'html' => $html , 'view_name' => $view_name], 200); } else if ($report_type == 'bapClient') { //Condition for BAP Client wise date $category = $category == 'life' ? 1 : 0; $viewData['data'] = $this->getBAPClientData($category, $fromDate, $toDate); + + $view_name = "irda_bap_client_report_list"; $html = view('irda_bap_client_report_list', $viewData); - return $this->respond(['status' => true, 'html' => $html], 200); + return $this->respond(['status' => true, 'html' => $html , 'view_name' => $view_name], 200); } else if ($report_type == 'client') { //Condition for Client wise date $category = $category == 'life' ? 1 : 0; $viewData['data'] = $this->getClientData($category, $fromDate, $toDate); + $view_name = "irda_client_report_list"; + $html = view('irda_client_report_list', $viewData); - return $this->respond(['status' => true, 'html' => $html], 200); + return $this->respond(['status' => true, 'html' => $html , 'view_name' => $view_name], 200); } } } @@ -932,12 +941,19 @@ class BDSReportController extends AdminController $data['client_type'] = [1 => 'Group', 2 => 'Individual']; $data['renewal_data'] = $this->policyTransactionModel->getRenewalReportData($fromDate, $toDate, $client_type, $client_id, $issuer); // print_r($data); die; + $view_name = "bds_renewal_report_list"; $html = view('bds_renewal_report_list', $data); - return $this->respond(['status' => true, 'html' => $html], 200); + return $this->respond(['status' => true, 'html' => $html , 'view_name' => $view_name], 200); } } - public function bdsTATReport() + /** New arugument Introduced Named as "$isInternalCalled" + * Functional Based called means $isInternalCalled is True. + * Output returning as Array + * Route Based called means $isInternalCalled is False. becoz this is External Call + * Output returning as Page + */ + public function bdsTATReport($isInternalCalled = false) { $sql = " SELECT @@ -1010,9 +1026,8 @@ class BDSReportController extends AdminController // dd(db_connect()->getLastQuery(),$result); $data['data'] = $result; // dd($data, get_role_id(), ENROLLMENT_TEAM_ID, user_team()); - // return $this->loadLayout('bds_tat_wise_report', $data); - - return $result; + if ($isInternalCalled) { return $result; } + return $this->loadLayout('bds_tat_wise_report', $data); } public function accountMangerStatusBDSReport() @@ -1141,7 +1156,7 @@ class BDSReportController extends AdminController if ($report_type == 1){ $data['page_title'] = "BDS TAT Report"; - $data['data'] = $this->bdsTATReport(); + $data['data'] = $this->bdsTATReport(true); // Functional Based called means True }else if ($report_type == 2){ $data['page_title'] = "Account Manager Status Report"; diff --git a/app/Controllers/ClientController.php b/app/Controllers/ClientController.php index ee7ae376..908a1ede 100755 --- a/app/Controllers/ClientController.php +++ b/app/Controllers/ClientController.php @@ -518,7 +518,6 @@ class ClientController extends AdminController public function updateEmpAndPolicyStatus() { - $return = $this->clientPolicyModel->updateStatus(); $this->myLogger->logme('error', 'Client Policy Status Update Count: {data}', ['data' => $return['client']]); $this->myLogger->logme('error', 'Employee Policy Status Update Count: {data}', ['data' => $return['emp']]); @@ -869,6 +868,12 @@ class ClientController extends AdminController if ($insert) { $client_data = $this->clientModel->where(['id' => $insert, 'is_active' => 1])->first(); + + $client_id = $insert; + $default_template_creation = $this->createDefaultMailTemplate($client_id , $client_data); + if($default_template_creation == false){ + $this->myLogger->logme('error', 'Default Mail Template Creation Failed for Client ID: {data}', ['data' => $client_id]); + } return $this->respond(['status' => true, 'code' => 200, 'data' => $client_data], 200); } else { return $this->respond(['status' => false, 'code' => 404, 'message' => 'no data found'], 200); @@ -1613,7 +1618,7 @@ class ClientController extends AdminController if ($update) { - $policy_transaction_update = $this->deactivatePolicyTransactionsPolicy($id); + // $policy_transaction_update = $this->deactivatePolicyTransactionsPolicy($id); return $this->respond(['status' => true, 'code' => 200], 200); } else { @@ -4669,7 +4674,7 @@ class ClientController extends AdminController // Additional logic for non-individual clients (client_type != 2) $branch_insert = null; if ($client_type != 2) { - $unit[] = $postData['short_name'] . '-' . $postData['branch_code'] ?? 001; + $unit[] = $postData['short_name'] . '-' . ($postData['branch_code'] ?? 001); $branch_data = [ 'client_id' => $client_insert, 'branch_name' => $postData['branch_name'], @@ -4816,6 +4821,7 @@ class ClientController extends AdminController 'vehicle_no' => $data['vehicle_no'], 'type' => $data['type'], 'rc' => $data['rc'], + 'rto_id' => $data['rto_id'], 'branch_id' => $branch_insert, 'owner' => $client_insert, ]; @@ -4861,6 +4867,7 @@ class ClientController extends AdminController 'vehicle_no' => $data['vehicle_no'], 'type' => $data['type'], 'rc' => $data['rc'], + 'rto_id' => $data['rto_id'], 'branch_id' => $data['branch_id'] ?? null, 'owner' => $data['owner'], ]; @@ -5064,10 +5071,12 @@ class ClientController extends AdminController ->where('policy_no', $policy_no) ->countAllResults(); + $client_policy_data = $this->clientPolicyModel->where('is_active', 1)->where('policy_status', 1)->where('policy_no', trim($policy_no))->first(); + if ($data > 0) { - return $this->respond(['status' => true, 'message' => 'This policy number is already linked to another client', 'data' => $data, 'code' => 409, 'received_data' => $received_data], 200); + return $this->respond(['status' => true, 'message' => 'This policy number is already linked to another client', 'data' => $data, 'code' => 409, 'received_data' => $received_data, 'client_policy_id' => $client_policy_data['id'] ?? null], 200); } else { - return $this->respond(['status' => false, 'message' => 'No Data Found', 'code' => 404, 'received_data' => $received_data], 200); + return $this->respond(['status' => false, 'message' => 'No Data Found', 'code' => 404, 'received_data' => $received_data, 'client_policy_id' => $client_policy_data['id'] ?? null], 200); } } @@ -5636,11 +5645,11 @@ class ClientController extends AdminController public function sendextraparam() { - // $data = db_connect()->table('jobs')->where('id', 1677)->get()->getRowArray(); - // // dd($data); - // $return = $this->updatePolicyTransactionDataWhileClinetPolicyUpdate(json_decode($data['payload'], true)); - // dd($return); - // die; + // $data = db_connect()->table('jobs')->where('id', 1677)->get()->getRowArray(); + // // dd($data); + // $return = $this->updatePolicyTransactionDataWhileClinetPolicyUpdate(json_decode($data['payload'], true)); + // dd($return); + // die; // $employeeController = new EmployeeController(); // $employeeController->truncateFileData('633'); @@ -5658,20 +5667,21 @@ class ClientController extends AdminController // ---------- EMP SERVICE CONTROLLER -------------------------------------------------------------------------------- $empServiceController = new EmployeeServiceController(); - $res = $empServiceController->excelFileFormatValidation(['file_id' => '2055']); + // $res = $empServiceController->excelFileFormatValidation(['file_id' => '1126']); // $res = $empServiceController->excelFileDataValidation(['file_id' => '865']); // $res = $empServiceController->employeesOnboardPreprocess(['file_id' => 726]); // $res = $empServiceController->employeesOnboardProcess(['file_id' => 835]); // $res = $empServiceController->employeesEnrollmentInsert(['file_id' => 836]); - // $res = $empServiceController->employeesSIEnhanceProcess(['file_id' => '978']); + // $res = $empServiceController->employeesSIEnhanceProcess(['file_id' => '1131']); // $res = $empServiceController->employeeDisembark(['file_id' => '1681']); - // $res = $empServiceController->employeesCorrectionProcess(['file_id' => '2033']); - dd($res); + // $res = $empServiceController->employeesCorrectionProcess(['file_id' => '2033']); + // $res = $empServiceController->compareMemberDataAndInceptionData(['file_id' => '1126']); + // dd($res); $EmployeeMultiEventServiceController = new EmployeeMultiEventServiceController(); // $res = $EmployeeMultiEventServiceController->constructMultiEventData(['file_id' => '1069']); - // $res = $EmployeeMultiEventServiceController->excelMultieventFileFormateValidation(['file_id' => '1084']); - // $res = $EmployeeMultiEventServiceController->excelMultieventFileDataValidation(['file_id' => '1069']); + // $res = $EmployeeMultiEventServiceController->excelMultieventFileFormateValidation(['file_id' => '2373']); + // $res = $EmployeeMultiEventServiceController->excelMultieventFileDataValidation(['file_id' => '2373']); // $res = $EmployeeMultiEventServiceController->excelMultieventFileOnBoard(['file_id' => '1069']); // dd($res); @@ -5726,8 +5736,8 @@ class ClientController extends AdminController // $res = $EmpDataServiceController->generateExcelForCorrection($batch_data); // $res = $EmpDataServiceController->importInceptionFileValidation(['file_id' => 1932]); die; // $res = $EmpDataServiceController->importDeletionValidation(['file_id' => 304]); //for live - // $res = $EmpDataServiceController->importSIEnhancementUpdateEndorsementID(['file_id' => 1199]); //for live - // $res = $EmpDataServiceController->importSIEnhancementValidation(['file_id' => 2496]); //for live + // $res = $EmpDataServiceController->importSIEnhancementUpdateEndorsementID(['file_id' => 387]); //for live + // $res = $EmpDataServiceController->importSIEnhancementValidation(['file_id' => 387]); //for live // $res = $EmpDataServiceController->importInceptionUpdateTPAandUHID(['file_id' => 214]); //for live // $res = $EmpDataServiceController->importInceptionUpdateTPAandUHID(['file_id' => 310]); dd($res);//for live // $res = $EmpDataServiceController->getInceptionBasePremium(["13332","13333","13334","13335","13336"]); dd($res);//for live @@ -7305,7 +7315,9 @@ class ClientController extends AdminController $pre_hr_id = $db2->table('client_branch cb') ->select('lc.id') ->join('level_contacts lc','lc.ref_id = cb.id') - ->where('cb.id',$pre_branch_id)->where('cb.is_Active',1)->where('lc.is_Active',1)->get()->getResultArray()[0]['id']??""; + ->where('lc.contact_type', 'client') + ->where('cb.id',$pre_branch_id)->where('cb.is_Active',1) + ->where('lc.is_Active',1)->get()->getResultArray()[0]['id']??""; return $pre_hr_id; } @@ -7725,9 +7737,110 @@ class ClientController extends AdminController return true; } + public function createDefaultMailTemplate($client_id , $client_data){ + + $member_welcome_mail_template = $this->notificationModel->where('client_id',NULL)->where('template_name','member_welcome_mail')->get()->getResultArray()[0]??[]; + + $member_remainder_mail_template = $this->notificationModel->where('client_id',NULL)->where('template_name','member_reminder_mail')->get()->getResultArray()[0]??[]; + + $member_review_and_summary_mail_template = $this->notificationModel->where('client_id',NULL)->where('template_name','member_review_and_summary_mail')->get()->getResultArray()[0]??[]; + + $member_ecard_mail_template = $this->notificationModel->where('client_id',NULL)->where('template_name','member_ecard_mail')->get()->getResultArray()[0]??[]; + + $member_common_mail_template = $this->notificationModel->where('client_id',NULL)->where('template_name','member_common_mail')->get()->getResultArray()[0]??[]; + + $default_member_welcome_mail_template = [ + 'client_id' => $client_id, + 'template_name' => 'member_welcome_mail', + 'subject' => $member_welcome_mail_template['subject']??'', + 'mail_content' => $member_welcome_mail_template['mail_content']??'', + 'mail_content_json'=> $member_welcome_mail_template['mail_content_json']??'', + + 'created_by' => get_session_userid(), + 'created_at' => date('Y-m-d H:i:s'), + 'updated_by' => null, + 'updated_at' => date('Y-m-d H:i:s'), + 'mail_content_copy'=> null + ]; + + $default_member_remainder_mail_template = [ + 'client_id' => $client_id, + 'template_name' => 'member_reminder_mail', + 'subject' => $member_remainder_mail_template['subject']??'', + 'mail_content' => $member_remainder_mail_template['mail_content']??'', + 'mail_content_json'=> $member_remainder_mail_template['mail_content_json']??'', + + 'created_by' => get_session_userid(), + 'created_at' => date('Y-m-d H:i:s'), + 'updated_by' => null, + 'updated_at' => date('Y-m-d H:i:s'), + 'mail_content_copy'=> null + ]; + + $default_member_review_and_summary_mail_template = [ + 'client_id' => $client_id, + 'template_name' => 'member_review_and_summary_mail', + 'subject' => $member_review_and_summary_mail_template['subject']??'', + 'mail_content' => $member_review_and_summary_mail_template['mail_content']??'', + 'mail_content_json'=> $member_review_and_summary_mail_template['mail_content_json']??'', + + 'created_by' => get_session_userid(), + 'created_at' => date('Y-m-d H:i:s'), + 'updated_by' => null, + 'updated_at' => date('Y-m-d H:i:s'), + 'mail_content_copy'=> null + ]; + + $default_member_ecard_mail_template = [ + 'client_id' => $client_id, + 'template_name' => 'member_ecard_mail', + 'subject' => $member_ecard_mail_template['subject']??'', + 'mail_content' => $member_ecard_mail_template['mail_content']??'', + 'mail_content_json'=> $member_ecard_mail_template['mail_content_json']??'', + + 'created_by' => get_session_userid(), + 'created_at' => date('Y-m-d H:i:s'), + 'updated_by' => null, + 'updated_at' => date('Y-m-d H:i:s'), + 'mail_content_copy'=> null + ]; + + $default_member_common_mail_template = [ + 'client_id' => $client_id, + 'template_name' => 'member_common_mail', + 'subject' => $member_common_mail_template['subject']??'', + 'mail_content' => $member_common_mail_template['mail_content']??'', + 'mail_content_json'=> $member_common_mail_template['mail_content_json']??'', + + 'created_by' => get_session_userid(), + 'created_at' => date('Y-m-d H:i:s'), + 'updated_by' => null, + 'updated_at' => date('Y-m-d H:i:s'), + 'mail_content_copy'=> null + ]; + + $this->myLogger->logme('error', 'Default Mail Template Data ' . json_encode([ + $default_member_welcome_mail_template, + $default_member_remainder_mail_template, + $default_member_review_and_summary_mail_template + ], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)); + $default_templates_inserted = $this->notificationModel->insertBatch([ + $default_member_welcome_mail_template, + $default_member_remainder_mail_template, + $default_member_review_and_summary_mail_template, + $default_member_ecard_mail_template, + $default_member_common_mail_template + ]); + + + return $default_templates_inserted ? true : false; + + + } + diff --git a/app/Controllers/DashboardController.php b/app/Controllers/DashboardController.php index 73c2e31a..369f9444 100755 --- a/app/Controllers/DashboardController.php +++ b/app/Controllers/DashboardController.php @@ -225,20 +225,23 @@ class DashboardController extends AdminController $pendingActionsController = new PendingActionsController; $pendingActionsData = $pendingActionsController->getPendingActionsForDashBoard(); - $businessTeamData = $this->policyTransactionModel->getBusinessReportList(); - $financeTeamData = $this->policyTransactionModel->getFinanceReportList(); - $businessTeamStatusData = $this->data_construct_for_bds($businessTeamData); - $financeTeamStatusData = $this->data_construct_for_bds($financeTeamData); + //BDS dashboard data + // $businessTeamData = $this->policyTransactionModel->getBusinessReportList(); + // $financeTeamData = $this->policyTransactionModel->getFinanceReportList(); + // $businessTeamStatusData = $this->data_construct_for_bds($businessTeamData); + // $financeTeamStatusData = $this->data_construct_for_bds($financeTeamData); + $businessTeamData = []; + $financeTeamData = []; + $businessTeamStatusData = []; + $financeTeamStatusData = []; $data['client_branch_emp_list'] = $results; $session = \Config\Services::session(); $session->set('enrollment_data', json_encode($data)); - // echo "
";
$data['pendingActionsData'] = $pendingActionsData;
$data['businessTeamCount'] = count($businessTeamData) ?? 0;
- // dd($businessTeamData);
$data['financeTeamCount'] = count($financeTeamData) ?? 0;
$data['businessTeamStatusData'] = $businessTeamStatusData;
$data['financeTeamStatusData'] = $financeTeamStatusData;
diff --git a/app/Controllers/EmpDataServiceController.php b/app/Controllers/EmpDataServiceController.php
index 1c9fac18..c2021479 100755
--- a/app/Controllers/EmpDataServiceController.php
+++ b/app/Controllers/EmpDataServiceController.php
@@ -121,16 +121,17 @@ class EmpDataServiceController extends BaseController
$insert = $this->batchFileModel->insert($data);
$batch_file_batch_code = $this->batchFileModel->where('id', $insert)->first();
- if ($insert) {
- foreach ($objects as $value) {
- $batch_list_data['batch_code'] = $batch_file_batch_code['batch_code'];
- $batch_list_data['emp_policy_id'] = $value->primaryKey ?? $value->employee_policy_id ?? '';
- $batch_list_data['created_by'] = get_session_userid();
- $this->batchListModel->insert($batch_list_data);
- }
- }
+ // if ($insert) {
+ // foreach ($objects as $value) {
+ // $batch_list_data['batch_code'] = $batch_file_batch_code['batch_code'];
+ // $batch_list_data['emp_policy_id'] = $value->primaryKey ?? $value->employee_policy_id ?? '';
+ // $batch_list_data['created_by'] = get_session_userid();
+ // $this->batchListModel->insert($batch_list_data);
+ // }
+ // }
- return true;
+ return $insert;
+ // return true;
}
@@ -526,8 +527,8 @@ class EmpDataServiceController extends BaseController
// $this->insertBatchList(['batch_code' => $batch_code, 'batch_list_data' => $objects ]);
- $job_details = new Jobs();
- $r = Jobs::addJob(['job_name' => 'insertBatchList', 'payload' => ['batch_code' => $batch_code, 'user_id' => get_session_userid(), 'batch_list_data' => $objects]]);
+ // $job_details = new Jobs();
+ // $r = Jobs::addJob(['job_name' => 'insertBatchList', 'payload' => ['batch_code' => $batch_code, 'user_id' => get_session_userid(), 'batch_list_data' => $objects]]);
// If batch operation is successful
@@ -640,7 +641,13 @@ class EmpDataServiceController extends BaseController
foreach ($ids as $key => $id) {
$group_key = $this->empEndorsementModel->select('group_key')->where('id', $id)->first();
if ($group_key) {
- $this->empEndorsementModel->where('group_key', $group_key)->set('status', 'inprogress')->update();
+
+ $endorsement_update_data['status'] = 'inprogress';
+ if( $export_data['insurer_or_tpa'] == 'tpa'){
+ $endorsement_update_data['is_tpa_export'] = $return ?? generate_random_string(4);
+ }
+
+ $this->empEndorsementModel->where('group_key', $group_key)->set($endorsement_update_data)->update();
}
}
@@ -794,13 +801,21 @@ class EmpDataServiceController extends BaseController
$success = generate_excel($excel_data_info['header'], $excel_data_info['data'], $tempFile);
if ($success) {
+
$return = $this->batchFilesAndBatchListEntry($export_data, $objects);
if ($return) {
foreach ($ids as $key => $id) {
$group_key = $this->empEndorsementModel->select('group_key')->where('id', $id)->first();
if ($group_key) {
- $this->empEndorsementModel->where('group_key', $group_key)->set('status', 'inprogress')->update();
+
+ $endorsement_update_data['status'] = 'inprogress';
+
+ if( $export_data['insurer_or_tpa'] == 'tpa'){
+ $endorsement_update_data['is_tpa_export'] = $return ?? generate_random_string(4);
+ }
+
+ $this->empEndorsementModel->where('group_key', $group_key)->set($endorsement_update_data)->update();
}
}
@@ -914,7 +929,11 @@ class EmpDataServiceController extends BaseController
foreach ($ids as $key => $id) {
$group_key = $this->empEndorsementModel->select('group_key')->where('id', $id)->first();
if ($group_key) {
- $this->empEndorsementModel->where('group_key', $group_key)->set('status', 'inprogress')->update();
+ $endorsement_update_data['status'] = 'inprogress';
+ if( $export_data['insurer_or_tpa'] == 'tpa'){
+ $endorsement_update_data['is_tpa_export'] = $return ?? generate_random_string(4);
+ }
+ $this->empEndorsementModel->where('group_key', $group_key)->set($endorsement_update_data)->update();
}
}
@@ -1002,12 +1021,12 @@ class EmpDataServiceController extends BaseController
return 5;
}
- $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();
+ $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
@@ -1028,7 +1047,7 @@ class EmpDataServiceController extends BaseController
$totals = round($totals, 2);
- if($export_data['insurer_or_tpa'] != 'tpa')// check overal emp premium amt with cd balance only for insurer export, not tpa export
+ if($export_data['insurer_or_tpa'] != 'tpa')// check overal emp premium amt with cd balance only for insurer export, not tpa export
{
if (!empty($cash_balance)) {
if ((int) $cash_balance['balance'] < (int) $totals) {
@@ -1112,6 +1131,7 @@ class EmpDataServiceController extends BaseController
$export_data['batch_code'] = session()->get('batch_code');
$export_data['created_by'] = get_session_userid();
+ $insert = null;
if($value == 'addition'){
if(!empty($additionData) && $additionData != null){
@@ -1125,8 +1145,8 @@ class EmpDataServiceController extends BaseController
$batch_file_batch_code = $this->batchFileModel->where('id', $insert)->first();
// $this->insertBatchList(['batch_code' => $batch_code, 'batch_list_data' => $objects ]);
- $job_details = new Jobs();
- $r = Jobs::addJob(['job_name' => 'insertBatchList', 'payload' => ['batch_code' => $batch_code, 'user_id' => get_session_userid(), 'batch_list_data' => $additionData]]);
+ // $job_details = new Jobs();
+ // $r = Jobs::addJob(['job_name' => 'insertBatchList', 'payload' => ['batch_code' => $batch_code, 'user_id' => get_session_userid(), 'batch_list_data' => $additionData]]);
}
@@ -1143,8 +1163,8 @@ class EmpDataServiceController extends BaseController
$batch_file_batch_code = $this->batchFileModel->where('id', $insert)->first();
// $this->insertBatchList(['batch_code' => $batch_code, 'batch_list_data' => $objects ]);
- $job_details = new Jobs();
- $r = Jobs::addJob(['job_name' => 'insertBatchList', 'payload' => ['batch_code' => $batch_code, 'user_id' => get_session_userid(), 'batch_list_data' => $inceptionData]]);
+ // $job_details = new Jobs();
+ // $r = Jobs::addJob(['job_name' => 'insertBatchList', 'payload' => ['batch_code' => $batch_code, 'user_id' => get_session_userid(), 'batch_list_data' => $inceptionData]]);
}
}else if($value == 'dependent_addition'){
@@ -1160,8 +1180,8 @@ class EmpDataServiceController extends BaseController
$batch_file_batch_code = $this->batchFileModel->where('id', $insert)->first();
// $this->insertBatchList(['batch_code' => $batch_code, 'batch_list_data' => $objects ]);
- $job_details = new Jobs();
- $r = Jobs::addJob(['job_name' => 'insertBatchList', 'payload' => ['batch_code' => $batch_code, 'user_id' => get_session_userid(), 'batch_list_data' => $dependentAdditionData]]);
+ // $job_details = new Jobs();
+ // $r = Jobs::addJob(['job_name' => 'insertBatchList', 'payload' => ['batch_code' => $batch_code, 'user_id' => get_session_userid(), 'batch_list_data' => $dependentAdditionData]]);
}
}else if($value == 'deletion'){
@@ -1176,8 +1196,8 @@ class EmpDataServiceController extends BaseController
$batch_file_batch_code = $this->batchFileModel->where('id', $insert)->first();
// $this->insertBatchList(['batch_code' => $batch_code, 'batch_list_data' => $objects ]);
- $job_details = new Jobs();
- $r = Jobs::addJob(['job_name' => 'insertBatchList', 'payload' => ['batch_code' => $batch_code, 'user_id' => get_session_userid(), 'batch_list_data' => $deletionData]]);
+ // $job_details = new Jobs();
+ // $r = Jobs::addJob(['job_name' => 'insertBatchList', 'payload' => ['batch_code' => $batch_code, 'user_id' => get_session_userid(), 'batch_list_data' => $deletionData]]);
}
}else if($value == 'si_enhancement'){
@@ -1193,8 +1213,8 @@ class EmpDataServiceController extends BaseController
$batch_file_batch_code = $this->batchFileModel->where('id', $insert)->first();
// $this->insertBatchList(['batch_code' => $batch_code, 'batch_list_data' => $objects ]);
- $job_details = new Jobs();
- $r = Jobs::addJob(['job_name' => 'insertBatchList', 'payload' => ['batch_code' => $batch_code, 'user_id' => get_session_userid(), 'batch_list_data' => $enhancementData]]);
+ // $job_details = new Jobs();
+ // $r = Jobs::addJob(['job_name' => 'insertBatchList', 'payload' => ['batch_code' => $batch_code, 'user_id' => get_session_userid(), 'batch_list_data' => $enhancementData]]);
}
}else if($value == 'correction'){
@@ -1210,11 +1230,43 @@ class EmpDataServiceController extends BaseController
$batch_file_batch_code = $this->batchFileModel->where('id', $insert)->first();
// $this->insertBatchList(['batch_code' => $batch_code, 'batch_list_data' => $objects ]);
- $job_details = new Jobs();
- $r = Jobs::addJob(['job_name' => 'insertBatchList', 'payload' => ['batch_code' => $batch_code, 'user_id' => get_session_userid(), 'batch_list_data' => $correctionData]]);
+ // $job_details = new Jobs();
+ // $r = Jobs::addJob(['job_name' => 'insertBatchList', 'payload' => ['batch_code' => $batch_code, 'user_id' => get_session_userid(), 'batch_list_data' => $correctionData]]);
}
}
+ if(in_array($value, ['deletion', 'si_enhancement', 'correction']) && $insert){
+
+ $endorsement_data_for_update = [];
+
+ if($value == 'deletion'){
+ $endorsement_data_for_update = $deletionData;
+ }else if($value == 'si_enhancement') {
+ $endorsement_data_for_update = $enhancementData;
+ }else if($value == 'correction') {
+ $endorsement_data_for_update = $correctionData;
+ }
+
+ foreach ($endorsement_data_for_update as $key => $edata) {
+
+ $id = $edata->id ?? $edata->endorsement_primarykey ?? null;
+
+ if($id){
+ $group_key = $this->empEndorsementModel->select('group_key')->where('id', $id)->first();
+ if ($group_key) {
+
+ $endorsement_update_data['status'] = 'inprogress';
+ if( $export_data['insurer_or_tpa'] == 'tpa'){
+ $endorsement_update_data['is_tpa_export'] = $return ?? generate_random_string(4);
+ }
+
+ $this->empEndorsementModel->where('group_key', $group_key)->set($endorsement_update_data)->update();
+ }
+ }
+ }
+
+ }
+
}
session()->remove('batch_code');
@@ -1457,6 +1509,47 @@ class EmpDataServiceController extends BaseController
//get the employee data for excel file validation
$employee_data = $this->employeePolicyModel->getInceptionEmployeeDataForExportExcel($ref_data, 1);
+ // ----------------- CD BALANCE CHECK ---------------------------------------------------------------------------
+
+ $cash_balance = $this->clientDepositModel
+ ->where('cd_ac_pk', $client_policy_data['cd_ac_pk'])
+ ->where('is_active', 1)
+ ->orderBy('id', 'DESC')
+ ->first();
+
+ if ($cash_balance == null) {
+ $balance = $this->CDMasterModel
+ ->where('client_id', $file['client_id'])
+ ->where('insurer_id', $client_policy_data['insurer_id'])
+ ->where('id', $client_policy_data['cd_ac_pk'])
+ ->first();
+
+ $cash_balance['balance'] = $balance['opening_bal'];
+ }
+
+ // Calculate the total amount from the objects
+ $totals = 0;
+ foreach ($employee_data as $item) {
+ $totals = $totals + $item['total'];
+ }
+
+ $totals = round($totals, 2);
+
+ //check CD amt insufficient only insurer, not tpa
+ if($file['insurer_or_tpa'] == 'insurer')
+ {
+ if (!empty($cash_balance)) {
+ if ((int) $cash_balance['balance'] < (int) $totals) {
+ $this->myLogger->logme('error', 'Inception export failed due to insufficient deposit amount. CASH BALANCE : {balance} and TOTAL AMOUNT : {total}', ['balance' => $cash_balance['balance'], 'total' => $totals]);
+ $this->batchFileModel->where('id', $file_id)->set(['status' => 'failed-7', 'error_data' => 'Insufficient deposit balance. Available CD Balance: ' . $cash_balance['balance'] . ', Excel Total Amount: ' . $totals])->update();
+ return ['status' => 'error', 'message' => 'Insufficient deposit balance. Available CD Balance: ' . $cash_balance['balance'] . ', Required Amount: ' . $totals];
+ }
+ }
+ }
+
+ // ---------------- END CD BALANCE CHECK ----------------------------------------------------------------------------
+
+
if ($employee_data == null || empty($employee_data)) {
if ($insurer_or_tpa == 'tpa') {
@@ -2500,7 +2593,8 @@ class EmpDataServiceController extends BaseController
// 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');
+ // $endorsement_details[] = array('group_key' => $result['group_key'], 'id' => $result['id'], 'endorsement_id' => $value[10], 'status' => 'complete');
+ $endorsement_details[] = array('group_key' => $result['group_key'], 'endorsement_id' => $value[10], 'status' => 'complete');
}
}
@@ -2569,6 +2663,7 @@ class EmpDataServiceController extends BaseController
'event_type' => $file['event_type'],
];
+ $client_policy_data = $this->clientPolicyModel->where('id', $client_policy_id)->first();
$file_name_with_path = WRITEPATH . "/uploads/import_excel/" . $file['file_name'];
@@ -2691,6 +2786,47 @@ class EmpDataServiceController extends BaseController
// dd($endorsement_data, $excel_data);
+ // ----------------- CD BALANCE CHECK ---------------------------------------------------------------------------
+
+ $cash_balance = $this->clientDepositModel
+ ->where('cd_ac_pk', $client_policy_data['cd_ac_pk'])
+ ->where('is_active', 1)
+ ->orderBy('id', 'DESC')
+ ->first();
+
+ if ($cash_balance == null) {
+ $balance = $this->CDMasterModel
+ ->where('client_id', $file['client_id'])
+ ->where('insurer_id', $client_policy_data['insurer_id'])
+ ->where('id', $client_policy_data['cd_ac_pk'])
+ ->first();
+
+ $cash_balance['balance'] = $balance['opening_bal'];
+ }
+
+ // Calculate the total amount from the objects
+ $totals = 0;
+ foreach ($endorsement_data as $item) {
+ $totals = $totals + $item['total'];
+ }
+
+ $totals = round($totals, 2);
+
+ //check CD amt insufficient only insurer, not tpa
+ if($file['insurer_or_tpa'] == 'insurer')
+ {
+ if (!empty($cash_balance)) {
+ if ((int) $cash_balance['balance'] < (int) $totals) {
+ $this->myLogger->logme('error', 'Inception export failed due to insufficient deposit amount. CASH BALANCE : {balance} and TOTAL AMOUNT : {total}', ['balance' => $cash_balance['balance'], 'total' => $totals]);
+ $this->batchFileModel->where('id', $file_id)->set(['status' => 'failed-7', 'error_data' => 'Insufficient deposit balance. Available CD Balance: ' . $cash_balance['balance'] . ', Excel Total Amount: ' . $totals])->update();
+ return ['status' => 'error', 'message' => 'Insufficient deposit balance. Available CD Balance: ' . $cash_balance['balance'] . ', Required Amount: ' . $totals];
+ }
+ }
+ }
+
+ // ---------------- END CD BALANCE CHECK ----------------------------------------------------------------------------
+
+
if ($endorsement_data == null || empty($endorsement_data)) {
@@ -3089,7 +3225,8 @@ class EmpDataServiceController extends BaseController
$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');
+ // $endorsement_details[] = array('id' => $result['id'], 'group_key' => $result['group_key'], 'endorsement_id' => $value[19], 'status' => 'complete');
+ $endorsement_details[] = array('group_key' => $result['group_key'], 'endorsement_id' => $value[19], 'status' => 'complete');
if (strtolower($result['relationship']) == 'self') {
$no_of_insured[] = ['emp_id' => $result['emp_id'], 'emp_code' => $result['emp_code'], 'emp_name' => $result['emp_name'] ];
}else{
@@ -3119,6 +3256,7 @@ class EmpDataServiceController extends BaseController
$empData['rata_premimum'] = $value[16];
$empData['gst'] = $value[17];
$empData['created_by'] = $user_id;
+ $empData['old_basic_cover_si'] = $value[9];
$emp_details[] = $empData;
}
@@ -3139,14 +3277,46 @@ class EmpDataServiceController extends BaseController
// $insertedIds[] = $startId + $i;
// }
+ // $insertedIds = [];
+ // foreach ($emp_details as $emp) {
+
+ // $old_si_value = $emp['old_basic_cover_si'];
+ // $new_si_value = $emp['basic_cover_si'];
+
+ // if($old_si_value < $new_si_value){
+ // $insertedIds['si_adjustment'] = 2;
+ // }else{
+ // $insertedIds['si_adjustment'] = 1;
+ // }
+
+ // unset($emp['old_basic_cover_si']);
+ // $insertedIds['pk'] = $this->employeePolicyModel->insert($emp);
+ // }
+
$insertedIds = [];
foreach ($emp_details as $emp) {
- $insertedIds[] = $this->employeePolicyModel->insert($emp);
- }
- // dd($insertedIds);
+ $old_si_value = $emp['old_basic_cover_si'];
+ $new_si_value = $emp['basic_cover_si'];
- $this->employeePolicyModel->bulkUpdateForEndorsement($endorsement_details);
+ // Determine SI adjustment type
+ $si_adjustment = ($old_si_value < $new_si_value) ? 1 : 2;
+
+ unset($emp['old_basic_cover_si']);
+
+ // Insert and store PK with adjustment info
+ $pk = $this->employeePolicyModel->insert($emp);
+
+ $insertedIds[] = [
+ 'pk' => $pk,
+ 'si_adjustment' => $si_adjustment
+ ];
+ } // dd($insertedIds);
+
+ // update si enhancement endorsement complete
+ $this->empEndorsementModel->updateBatch($endorsement_details, 'group_key');
+
+ // $this->employeePolicyModel->bulkUpdateForEndorsement($endorsement_details); // do not remove this
$this->storeEndorsementNumber($file_id, $endorsement_id, $enrollment_file_id);
}
@@ -3158,7 +3328,6 @@ class EmpDataServiceController extends BaseController
'amount' => $rounded_totals,
]);
-
$this->myLogger->logme('error', 'SI Enhancement Update Endorsement ID -- Employee count : {data}', ['data' => $emp_count]);
$this->myLogger->logme('error', 'SI Enhancement Update Endorsement ID -- Batch File status : {data}', ['data' => $status_val]);
@@ -4195,60 +4364,164 @@ class EmpDataServiceController extends BaseController
}
- public function cashDepositCalculationForSIEnhancement($arrayData)
- {
- // return $arrayData;
+ // public function cashDepositCalculationForSIEnhancement($arrayData)
+ // {
+ // // return $arrayData;
+ // if (!empty($arrayData)) {
+
+ // $client_branch_data = $this->clientBranchModel->where('id', $arrayData['client_branch_id'])->first();
+ // $units = json_decode($client_branch_data['units']);
+
+ // foreach($units as $unit)
+ // {
+
+ // $amount = $this->employeePolicyModel->query("
+ // SELECT SUM(rata_premimum + gst) AS total_sum
+ // FROM employee_polices
+ // JOIN employees ON employees.id = employee_polices.employee_id
+ // WHERE employees.unit = '$unit'
+ // AND employee_polices.id IN (" . implode(',', $arrayData['employeeIds']) . ")
+ // ")->getRow();
+
+ // if($amount){
+
+ // $insurer_id = $this->clientPolicyModel->where('id', $arrayData['client_policy_id'])->first();
+ // $description = 'The following amount of ' . round($amount->total_sum, 2) . ' has been credited for the ' . $arrayData['count'] . ' employees at ' . remove_underscore_capitalize_first_letter($arrayData['event_name']) . ' to ' . remove_underscore_capitalize_first_letter($arrayData['policy_name']) . '.';
+
+ // $data = [
+
+ // 'amount' => $amount->total_sum,
+ // 'sub_type_id' => 4,
+ // 'client_id' => $arrayData['client_id'],
+ // 'client_policy_id' => $arrayData['client_policy_id'],
+ // 'endorsement_no' => $arrayData['endorsement_no'] ?? null,
+ // 'cd_ac_no' => $arrayData['cd_ac_no'] ?? null,
+ // 'insurer_id' => $insurer_id['insurer_id'],
+ // 'unit' => $unit,
+ // 'description' => $description,
+ // 'transaction_type' => 'Debit',
+ // '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']);
+ // }
+ // }
+
+ // $msg = "SI Enhancement Cash Deposite Updated Successfully ";
+ // return [$msg];
+
+ // // print_r($response);
+ // // $query = $this->employeePolicyModel->getLastQuery();
+ // // echo $query . "
";
+
+ // } else {
+ // return 0;
+ // }
+ // }
+
+ public function cashDepositCalculationForSIEnhancement($arrayData)
+ {
if (!empty($arrayData)) {
$client_branch_data = $this->clientBranchModel->where('id', $arrayData['client_branch_id'])->first();
$units = json_decode($client_branch_data['units']);
- foreach($units as $unit)
- {
+ foreach ($units as $unit) {
- $amount = $this->employeePolicyModel->query("
- SELECT SUM(rata_premimum + gst) AS total_sum
- FROM employee_polices
- JOIN employees ON employees.id = employee_polices.employee_id
- WHERE employees.unit = '$unit'
- AND employee_polices.id IN (" . implode(',', $arrayData['employeeIds']) . ")
- ")->getRow();
+ $si_enhance_amt = 0;
+ $si_decrease_amt = 0;
- if($amount){
+ foreach ($arrayData['employeeIds'] as $value) {
- $insurer_id = $this->clientPolicyModel->where('id', $arrayData['client_policy_id'])->first();
- $description = 'The following amount of ' . round($amount->total_sum, 2) . ' has been credited for the ' . $arrayData['count'] . ' employees at ' . remove_underscore_capitalize_first_letter($arrayData['event_name']) . ' to ' . remove_underscore_capitalize_first_letter($arrayData['policy_name']) . '.';
+ // If $value is an array, get its elements; otherwise, assign defaults
+ $pk = is_array($value) ? ($value['pk'] ?? null) : $value;
+ $si_adjustment = is_array($value) ? ($value['si_adjustment'] ?? null) : $value;
+
+ $query = "
+ SELECT SUM(rata_premimum + gst) AS total_sum
+ FROM employee_polices
+ JOIN employees ON employees.id = employee_polices.employee_id
+ WHERE employees.unit = '{$unit}'
+ AND employee_polices.id = '{$pk}'
+ ";
+
+ $amount = $this->employeePolicyModel->query($query)->getRow();
+
+ if ($amount && $amount->total_sum > 0) {
+ if ($si_adjustment == 2) {
+ $si_decrease_amt += $amount->total_sum;
+ } else {
+ $si_enhance_amt += $amount->total_sum;
+ }
+ }
+ }
+
+ // Save Enhancement amount
+ if ($si_enhance_amt > 0) {
+ $policy_data = $this->clientPolicyModel->where('id', $arrayData['client_policy_id'])->first();
+
+ $description = 'An amount of ' . round($si_enhance_amt, 2) .
+ ' has been debited for ' . $arrayData['count'] . ' employees under ' .
+ remove_underscore_capitalize_first_letter($arrayData['event_name']) .
+ ' in ' . remove_underscore_capitalize_first_letter($arrayData['policy_name']) . '.';
$data = [
-
- 'amount' => $amount->total_sum,
+ 'amount' => round($si_enhance_amt, 2),
'sub_type_id' => 4,
'client_id' => $arrayData['client_id'],
'client_policy_id' => $arrayData['client_policy_id'],
'endorsement_no' => $arrayData['endorsement_no'] ?? null,
'cd_ac_no' => $arrayData['cd_ac_no'] ?? null,
- 'insurer_id' => $insurer_id['insurer_id'],
+ 'insurer_id' => $policy_data['insurer_id'],
'unit' => $unit,
'description' => $description,
'transaction_type' => 'Debit',
'updated_by' => $arrayData['user_id'],
'event_name' => $arrayData['event_name'],
'is_active' => 1,
- 'cd_ac_pk' => $insurer_id['cd_ac_pk']
+ 'cd_ac_pk' => $policy_data['cd_ac_pk']
];
- $response = DepositHelper::saveDeposit($data, $arrayData['user_id']);
+ DepositHelper::saveDeposit($data, $arrayData['user_id']);
+ }
+
+ // Save Decrease amount
+ if ($si_decrease_amt > 0) {
+
+ $policy_data = $this->clientPolicyModel->where('id', $arrayData['client_policy_id'])->first();
+
+ $description = 'An amount of ' . round($si_decrease_amt, 2) .
+ ' has been credited for ' . $arrayData['count'] . ' employees due to a decrease in Sum Insured (SI) under ' .
+ remove_underscore_capitalize_first_letter($arrayData['event_name']) .
+ ' in ' . remove_underscore_capitalize_first_letter($arrayData['policy_name']) . '.';
+
+ $data = [
+ 'amount' => round($si_decrease_amt, 2),
+ 'sub_type_id' => 4,
+ 'client_id' => $arrayData['client_id'],
+ 'client_policy_id' => $arrayData['client_policy_id'],
+ 'endorsement_no' => $arrayData['endorsement_no'] ?? null,
+ 'cd_ac_no' => $arrayData['cd_ac_no'] ?? null,
+ 'insurer_id' => $policy_data['insurer_id'],
+ 'unit' => $unit,
+ 'description' => $description,
+ 'transaction_type' => 'Credit',
+ 'updated_by' => $arrayData['user_id'],
+ 'event_name' => $arrayData['event_name'],
+ 'is_active' => 1,
+ 'cd_ac_pk' => $policy_data['cd_ac_pk']
+ ];
+
+ DepositHelper::saveDeposit($data, $arrayData['user_id']);
}
}
- $msg = "SI Enhancement Cash Deposite Updated Successfully ";
+ $msg = "SI Adjustment Cash Deposit Updated Successfully.";
return [$msg];
-
- // print_r($response);
- // $query = $this->employeePolicyModel->getLastQuery();
- // echo $query . "
";
-
} else {
return 0;
}
@@ -4866,6 +5139,7 @@ class EmpDataServiceController extends BaseController
'tpa_id' => $filedata['tpa_id'],
'endorsement_no' => $endorsement_no,
'file_id' => $enrollment_file_id,
+ 'batch_file_id' => $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 a4666518..7d14927a 100755
--- a/app/Controllers/EmployeeController.php
+++ b/app/Controllers/EmployeeController.php
@@ -35,7 +35,8 @@ use App\Controllers\JobWorker;
use App\Controllers\Jobs\SubJob;
use App\Controllers\EmployeeServiceController;
use App\Controllers\EmpDataServiceController;
-
+use App\Models\LeadsModel;
+use App\Models\ThzMasterModel;
use CodeIgniter\API\ResponseTrait;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
@@ -171,7 +172,7 @@ class EmployeeController extends AdminController
return $this->respond(['dataStatus' => false, 'code' => 404, 'message' => 'no data found'], 200);
} else {
- return $this->respond(['dataStatus' => true, 'code' => 200, 'data' => $file['reason']], 200);
+ return $this->respond(['dataStatus' => true, 'code' => 200, 'data' => $file['reason'], 'is_comparison_skipped' => $file['is_comparison_skipped'], 'policy_id' => $file['policy_id']], 200);
}
}
@@ -388,13 +389,11 @@ class EmployeeController extends AdminController
batch_files.client_branch_id,
CASE
- WHEN batch_files.status = 'partially success' OR batch_files.status = 'in-progress-partially' THEN
- batch_files.error_data
- ELSE
- NULL
+ WHEN batch_files.status IN ('partially success', 'in-progress-partially', 'failed-7')
+ THEN batch_files.error_data
+ ELSE NULL
END AS error_data,
-
clients.short_name as client_short_name,
client_branch.branch_name,
client_policy.policy_no,
@@ -669,6 +668,11 @@ class EmployeeController extends AdminController
} else if ($actions == 'import') {
+ if($insurer_or_tpa == "tpa" && in_array($event_type, ['correction', 'deletion', 'si_enhancement'])){
+ session()->setFlashdata('error', "TPA upload is not applicable for this event.");
+ return redirect()->to(base_url('employee/upload'));
+ }
+
$batch_data['file'] = $this->request->getFile('import_file_data');
$file = $this->request->getFile('import_file_data');
@@ -1193,7 +1197,7 @@ class EmployeeController extends AdminController
// --------------- For E-Card Download -----------------------------------------------------------------------------------------------------
- //E-CARD DOWNLOAD FUNCTION USING HTML PRINT
+ //E-CARD DOWNLOAD FUNCTION USING HTML PRINT ( Not in use ) do not delete
public function generateIDCardForEmployeeUsingHtml($rand_string, $people = 0)
{
// dd($rand_string, $people);
@@ -1418,7 +1422,7 @@ class EmployeeController extends AdminController
echo $htmlContent;
}
- //E-CARD DOWNLOAD FUNCTION USING DOM PDF ( CURRENTLY USING THIS )
+ //E-CARD DOWNLOAD FUNCTION USING DOM PDF ( CURRENTLY USING THIS ) Dompdf
public function generateIDCardForEmployee($rand_string, $people = 0, $mode = 0)
{
// dd($rand_string, $people);
@@ -1470,7 +1474,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 = 'common.html';
+ // $tpa_short_name = 'common.html';
+ $tpa_short_name = 'new_ecard.html';
$final_path = $template_data_path . $tpa_short_name;
$this->myLogger->logme('error', 'Checking if template file exists at: ' . $final_path);
@@ -1494,6 +1499,7 @@ class EmployeeController extends AdminController
$value['back_card'] = "Nhance_Ecard_working_1_Back.png";
$placeholders = [
+
'{CLIENT_NAME}' => $value['client_name'],
'{TPA_ID}' => $value['tpa_id'],
'{NAME}' => $value['name'],
@@ -1505,9 +1511,6 @@ class EmployeeController extends AdminController
'{POLICY_START_DATE}' => date('d-M-Y', strtotime($value['policy_start_date'])),
'{POLICY_NO}' => $value['policy_no'],
'{INSURER_NAME}' => strtoupper($value['insurer_name']),
- '{INSURER_LOGO}' => base_url() . 'public/uploads/logo/' . $value['insurer_logo'],
- '{FRONT_CARD}' => base_url() . 'public/uploads/template_bg/' . $value['front_card'],
- '{BACK_CARD}' => base_url() . 'public/uploads/template_bg/' . $value['back_card'],
'{EMP_ID}' => $value['emp_code'],
'{SI_AMT}' => $value['basic_cover_si'],
'{CORPORATE_NAME}' => $value['client_name'],
@@ -1515,18 +1518,38 @@ class EmployeeController extends AdminController
'{TPA_NAME}' => $value['tpa_name'],
'{INSURER_BRANCH}' => $value['insurer_branch_city'],
'{RELATION}' => $value['relationship'],
- '{TPA_LOGO}' => base_url() . 'public/uploads/logo/' . $value['tpa_logo'],
- '{MEDI_USER}' => base_url() . 'public/e_card_imgs/medi_uesr.jpg',
- '{MEDI_INSURER}' => base_url() . 'public/e_card_imgs/Magma.png',
- '{MEDI_BARCODE}' => base_url() . 'public/e_card_imgs/borcode.jpeg',
- '{QR_ANDROID}' => base_url() . 'public/e_card_imgs/android.png',
- '{QR_IOS}' => base_url() . 'public/e_card_imgs/ios.png',
- '{QR_ANDROID_2}' => base_url() . 'public/e_card_imgs/play_store.png',
- '{QR_IOS_2}' => base_url() . 'public/e_card_imgs/appstore.png',
+
+ '{TPA_LOGO}' => getFileIfExists('uploads/logo/' . $value['tpa_logo']),
+ '{MEDI_USER}' => getFileIfExists('e_card_imgs/medi_uesr.jpg'),
+ '{MEDI_INSURER}' => getFileIfExists('e_card_imgs/Magma.png'),
+ '{MEDI_BARCODE}' => getFileIfExists('e_card_imgs/borcode.jpeg'),
+ '{QR_ANDROID}' => getFileIfExists('e_card_imgs/android.png'),
+ '{QR_IOS}' => getFileIfExists('e_card_imgs/ios.png'),
+ '{QR_ANDROID_2}' => getFileIfExists('e_card_imgs/play_store.png'),
+ '{QR_IOS_2}' => getFileIfExists('e_card_imgs/appstore.png'),
+ '{NHANCE_N_LOGO}' => getFileIfExists('assets/images/Nhance_Favi.png'),
+ '{INSURER_LOGO}' => getFileIfExists('uploads/logo/' . $value['insurer_logo']),
+ '{FRONT_CARD}' => getFileIfExists('uploads/template_bg/' . $value['front_card']),
+ '{BACK_CARD}' => getFileIfExists('uploads/template_bg/' . $value['back_card']),
+
+ // '{TPA_LOGO}' => base_url() . 'public/uploads/logo/' . $value['tpa_logo'],
+ // '{MEDI_USER}' => base_url() . 'public/e_card_imgs/medi_uesr.jpg',
+ // '{MEDI_INSURER}' => base_url() . 'public/e_card_imgs/Magma.png',
+ // '{MEDI_BARCODE}' => base_url() . 'public/e_card_imgs/borcode.jpeg',
+ // '{QR_ANDROID}' => base_url() . 'public/e_card_imgs/android.png',
+ // '{QR_IOS}' => base_url() . 'public/e_card_imgs/ios.png',
+ // '{QR_ANDROID_2}' => base_url() . 'public/e_card_imgs/play_store.png',
+ // '{QR_IOS_2}' => base_url() . 'public/e_card_imgs/appstore.png',
+ // '{NHANCE_N_LOGO}' => base_url() . 'public/assets/images/Nhance_Favi.png',
+ // '{INSURER_LOGO}' => base_url() . 'public/uploads/logo/' . $value['insurer_logo'],
+ // '{FRONT_CARD}' => base_url() . 'public/uploads/template_bg/' . $value['front_card'],
+ // '{BACK_CARD}' => base_url() . 'public/uploads/template_bg/' . $value['back_card'],
+
];
$placeholders['{LEVELS}'] = $this->generateAcmAndMForEcard($client_id);
-
+ $placeholders['{NETWORK_HOSPITAL}'] = $this->generateNetworkHospitalsForEcard($value['network_hospitals']);
+
foreach ($placeholders as $placeholder => $replaceValue) {
$htmlContent = str_replace($placeholder, $replaceValue, $htmlContent);
}
@@ -1534,13 +1557,23 @@ class EmployeeController extends AdminController
$html .= $htmlContent;
}
+ // return $html;
// DomPdf
$options = new Options();
$options->set('isRemoteEnabled', true);
$options->set('isHtml5ParserEnabled', true);
$dompdf = new Dompdf($options);
- $dompdf->loadHtml('' . $html); // remove the margin
+ // $dompdf->loadHtml('' . $html); // remove the margin
+ $dompdf->loadHtml('
+
+ ' . $html
+ );
+
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();
@@ -2939,20 +2972,43 @@ class EmployeeController extends AdminController
// Generate the HTML content
$html = '';
-
+
+ $level_index = 1;
foreach ($levels as $level => $contacts) {
$displayLevel = $level == 3 ? 1 : 2; // Switch levels for display
- $html .= '
Level ' . $displayLevel . '
';
+ if($level_index == 1){
+ $html .= 'Level ' . $displayLevel . '
';
+ }else{
+ $html .= '
Level ' . $displayLevel . '
';
+ }
foreach ($contacts as $index => $contact) {
$html .= ($index + 1) . '. ' . $contact['first_name'] . ' / ' . $contact['mobile'] . ' / ' . $contact['email'] . '
';
}
+ $level_index++;
}
- $html .= '
';
+ $html .= '
';
return $html;
}
+ public function generateNetworkHospitalsForEcard($network_hospitals)
+ {
+ $html = "";
+ if (!empty($network_hospitals)) {
+ $html = '
+ Network Hospital:
+
+ ';
+ }
+
+ // For debugging
+ // print_r($html); die;
+
+ return $html;
+ }
+
+
public function getBatchFileData()
{
$file_id = $this->request->getGet('file_id');
@@ -3065,7 +3121,8 @@ class EmployeeController extends AdminController
} else {
$text = "create";
$data['created_by'] = get_session_userid();
- $this->thzMasterModel->insert($data);
+ $thzMasterModel = new ThzMasterModel();
+ $thzMasterModel->insert($data);
$insertID = $this->partnerEndorsementRequestModel->insertID();
$result = true;
}
@@ -3095,5 +3152,58 @@ class EmployeeController extends AdminController
}
}
+ // function for skip the Inception and Member data validation
+ public function proceedExcelFileDataValidation()
+ {
+ $file_id = $this->request->getGet('file_id');
+ $not_skiped = $this->request->getGet('not_skiped') ?? null;
+ $this->myLogger->logme('error', json_encode($this->request->getGet() ?? []));
+
+
+ if(!empty($not_skiped)){
+ $file_model = new FileModel();
+ $file_model->where('id', $file_id)->set(['is_comparison_skipped' => 0])->update();
+ $message = "Inception and Member data comparision continuted by the user id : " . get_session_userid();
+ $this->myLogger->logme('error', $message);
+ return $this->respond(['status' => true, 'code' => 200, 'message' => 'Inception and Member data comparision continued'], 200);
+ }
+
+ if(!empty($file_id)){
+
+ $r = Jobs::addJob(['job_name' => 'excelFileDataValidation','payload' => ['file_id' => $file_id]]);
+ $message = "Inception and Member data comparision skiped successfully by the user id : " . get_session_userid();
+ $this->myLogger->logme('error', $message);
+
+ $file_model = new FileModel();
+ $file_model->where('id', $file_id)->set(['is_comparison_skipped' => 1])->update();
+
+ $policy_id = $this->request->getGet('policy_id') ?? null;
+
+ if ($policy_id) {
+
+ $client_policy_data = $this->clientPolicyModel->where('id', $policy_id)->first();
+
+ if (!empty($client_policy_data) && isset($client_policy_data['is_from_lead'])) {
+ $lead_id = $client_policy_data['is_from_lead'];
+
+ if (!empty($lead_id)) {
+ $lead_model = new LeadsModel();
+ $lead_model->where('id', $lead_id)->set(['policy_with_correction' => 1])->update();
+ } else {
+ $this->myLogger->logme('error', 'Lead ID missing for policy ID: ' . $policy_id);
+ }
+ } else {
+ $this->myLogger->logme('error', 'No client policy data found for policy ID: ' . $policy_id);
+ }
+ } else {
+ $this->myLogger->logme('error', 'Policy ID not provided in GET request.');
+ }
+
+ return $this->respond(['status' => true, 'code' => 200, 'message' => 'Inception and Member data comparision skiped successfully!'], 200);
+ }else{
+ return $this->respond(['status' => false, 'code' => 500, 'message' => 'Failed to skip the comparison!'], 200);
+ }
+ }
+
}
diff --git a/app/Controllers/EmployeeMultiEventServiceController.php b/app/Controllers/EmployeeMultiEventServiceController.php
index e3027d01..782a189b 100644
--- a/app/Controllers/EmployeeMultiEventServiceController.php
+++ b/app/Controllers/EmployeeMultiEventServiceController.php
@@ -26,6 +26,7 @@ use PhpOffice\PhpSpreadsheet\Spreadsheet;
use Kint\Kint;
use App\Helpers\ExcelSanitizeHelper;
+use App\Models\LeadsModel;
class EmployeeMultiEventServiceController extends BaseController
{
@@ -140,7 +141,7 @@ class EmployeeMultiEventServiceController extends BaseController
'is_mandatory' => ['I', 'A', 'DA'],
'data_type' => 'str',
'format' => null,
- 'allowed_values' => ['M', 'F']
+ 'allowed_values' => ['M', 'F', 'Male', 'Female', 'male', 'female']
],
'relationship' => [
'col_idx' => 5,
@@ -524,7 +525,7 @@ class EmployeeMultiEventServiceController extends BaseController
'is_mandatory' => ['I', 'A', 'DA', 'E'],
'data_type' => 'str',
'format' => null,
- 'allowed_values' => ['M', 'F']
+ 'allowed_values' => ['M', 'F', 'Male', 'Female', 'male', 'female']
],
'relationship' => [
'col_idx' => 5,
@@ -889,8 +890,108 @@ class EmployeeMultiEventServiceController extends BaseController
]
];
-
-
+ protected $member_data_excel_columns = [
+ 'sno' => [
+ 'col_idx' => 0,
+ 'col_cell_name' => 'A',
+ 'col_name' => 'Sl no',
+ 'is_mandatory' => false,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+ 'emp_code' => [
+ 'col_idx' => 1,
+ 'col_cell_name' => 'B',
+ 'col_name' => 'Emp Code',
+ 'is_mandatory' => true,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+ 'name' => [
+ 'col_idx' => 2,
+ 'col_cell_name' => 'C',
+ 'col_name' => 'Name',
+ 'is_mandatory' => true,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+ 'relationship' => [
+ 'col_idx' => 3,
+ 'col_cell_name' => 'D',
+ 'col_name' => 'Relationship',
+ 'is_mandatory' => true,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => [
+ 'Self', 'Spouse', 'Son', 'Daughter', 'Father', 'Mother',
+ 'Father-in-law', 'Mother-in-law',
+ 'self', 'spouse', 'son', 'daughter', 'father', 'mother',
+ 'father-in-law', 'mother-in-law'
+ ],
+ 'custom' => 'check_relationship_for_member_data',
+ 'params' => ['row', 'relationship', 'columns_to_check']
+ ],
+ 'gender' => [
+ 'col_idx' => 4,
+ 'col_cell_name' => 'E',
+ 'col_name' => 'Gender',
+ 'is_mandatory' => true,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => ['M', 'F', 'Male', 'Female', 'male', 'female']
+ ],
+ 'dob' => [
+ 'col_idx' => 5,
+ 'col_cell_name' => 'F',
+ 'col_name' => 'DOB',
+ 'is_mandatory' => true,
+ 'data_type' => 'str',
+ 'format' => 'd-M-Y',
+ 'allowed_values' => null,
+ 'age_validation' => true,
+ // 'custom' => 'check_dob_diff',
+ // 'params' => ['row', 'relationship', 'default_age_ratio', 'policy_details']
+ ],
+ 'age' => [
+ 'col_idx' => 6,
+ 'col_cell_name' => 'G',
+ 'col_name' => 'Age',
+ 'is_mandatory' => true,
+ 'data_type' => 'int',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+ 'email' => [
+ 'col_idx' => 7,
+ 'col_cell_name' => 'H',
+ 'col_name' => 'Email',
+ 'is_mandatory' => false,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+ 'mobile' => [
+ 'col_idx' => 8,
+ 'col_cell_name' => 'I',
+ 'col_name' => 'Mobile',
+ 'is_mandatory' => false,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+ 'si' => [
+ 'col_idx' => 9,
+ 'col_cell_name' => 'J',
+ 'col_name' => 'SI',
+ 'is_mandatory' => false,
+ 'data_type' => 'int',
+ 'format' => null,
+ 'allowed_values' => null,
+ ]
+ ];
public function __construct()
{
@@ -914,6 +1015,7 @@ class EmployeeMultiEventServiceController extends BaseController
public function excelMultieventFileFormateValidation($params)
{
+ $this->myLogger->logme('error', 'Excel Multievent File Formate Validation function START: ' . json_encode(['params' => $params]));
helper('excel_util_helper');
$file_id = $params['file_id'];
$file = $this->fileModel->find($file_id);
@@ -991,48 +1093,59 @@ class EmployeeMultiEventServiceController extends BaseController
$params["action"] = "inception";
$params["file_path"] = $file_paths['inception'];
$error[] = $this->excelFileFormatValidation($params);
+ $this->myLogger->logme('error', 'Inception file formate validation result: ' . json_encode(['params' => $params]));
+ if (isset($error['error_data']) && count($error['error_data']) == 0) {
+ $error[] = $this->compareMemberDataAndInceptionData($params);
+ $this->myLogger->logme('error', 'compare Member Data And Inception Data file validation result: ' . json_encode(['params' => $params]));
+ }
}
//addition
if(isset($file_paths['addition']) && $file_paths['addition'] != "" && $file_paths['addition'] != null){
- $params["action"] = "addition";
- $params["file_path"] = $file_paths['addition'];
- $error[] = $this->excelFileFormatValidation($params);
+ $params["action"] = "addition";
+ $params["file_path"] = $file_paths['addition'];
+ $error[] = $this->excelFileFormatValidation($params);
+ $this->myLogger->logme('error', 'Addition file formate validation result: ' . json_encode(['params' => $params]));
}
//dependent_addition
if(isset($file_paths['dependent_addition']) && $file_paths['dependent_addition'] != "" && $file_paths['dependent_addition'] != null){
- $params["action"] = "dependent_addition";
- $params["file_path"] = $file_paths['dependent_addition'];
- $error[] = $this->excelFileFormatValidation($params);
+ $params["action"] = "dependent_addition";
+ $params["file_path"] = $file_paths['dependent_addition'];
+ $error[] = $this->excelFileFormatValidation($params);
+ $this->myLogger->logme('error', 'Dependent Addition file formate validation result: ' . json_encode(['params' => $params]));
}
//deletion
if(isset($file_paths['deletion']) && $file_paths['deletion'] != "" && $file_paths['deletion'] != null){
- $params["action"] = "deletion";
- $params["file_path"] = $file_paths['deletion'];
- $error[] = $this->excelFileFormatValidation($params);
+ $params["action"] = "deletion";
+ $params["file_path"] = $file_paths['deletion'];
+ $error[] = $this->excelFileFormatValidation($params);
+ $this->myLogger->logme('error', 'Deletion file formate validation result: ' . json_encode(['params' => $params]));
}
//correction
if(isset($file_paths['correction']) && $file_paths['correction'] != "" && $file_paths['correction'] != null){
- $params["action"] = "correction";
- $params["file_path"] = $file_paths['correction'];
- $error[] = $this->excelFileFormatValidation($params);
+ $params["action"] = "correction";
+ $params["file_path"] = $file_paths['correction'];
+ $error[] = $this->excelFileFormatValidation($params);
+ $this->myLogger->logme('error', 'Correction file formate validation result: ' . json_encode(['params' => $params]));
}
//si_enhancement
if(isset($file_paths['si_enhancement']) && $file_paths['si_enhancement'] != "" && $file_paths['si_enhancement'] != null){
- $params["action"] = "si_enhancement";
- $params["file_path"] = $file_paths['si_enhancement'];
- $error[] = $this->excelFileFormatValidation($params);
+ $params["action"] = "si_enhancement";
+ $params["file_path"] = $file_paths['si_enhancement'];
+ $error[] = $this->excelFileFormatValidation($params);
+ $this->myLogger->logme('error', 'SI Enhancement file formate validation result: ' . json_encode(['params' => $params]));
}
//missed_inception
if(isset($file_paths['missed_inception']) && $file_paths['missed_inception'] != "" && $file_paths['missed_inception'] != null){
- $params["action"] = "missed_inception";
- $params["file_path"] = $file_paths['missed_inception'];
- $error[] = $this->excelFileFormatValidation($params);
+ $params["action"] = "missed_inception";
+ $params["file_path"] = $file_paths['missed_inception'];
+ $error[] = $this->excelFileFormatValidation($params);
+ $this->myLogger->logme('error', 'Missed Inception file formate validation result: ' . json_encode(['params' => $params]));
}
$error_type = 1;
@@ -1041,6 +1154,7 @@ class EmployeeMultiEventServiceController extends BaseController
if (isset($error['error_data']) && count($error['error_data']) == 0) {
$r = Jobs::addJob(['job_name' => 'excelMultieventFileDataValidation', 'payload' => $params]);
+ $this->myLogger->logme('error', 'excelMultieventFileDataValidation job pushed');
} else {
// $error['error_summary'] = array_count_values($error['error_summary']);
@@ -1056,12 +1170,16 @@ class EmployeeMultiEventServiceController extends BaseController
$this->unlinkFiles($file_paths);
}
+ $this->myLogger->logme('error', 'Excel Multievent File Formate Validation function END');
+
return ($error);
}
public function excelMultieventFileDataValidation($params)
{
+ $this->myLogger->logme('error', 'Excel Multievent File Data Validation function START: ' . json_encode(['params' => $params]));
+
helper('excel_util_helper');
$file_id = $params['file_id'];
$file = $this->fileModel->find($file_id);
@@ -1091,6 +1209,7 @@ class EmployeeMultiEventServiceController extends BaseController
$params["action"] = "inception";
$params["file_path"] = $file_paths['inception'];
$error[] = $this->excelFileDataValidation($params);
+ $this->myLogger->logme('error', 'Inception file Data validation result: ' . json_encode(['params' => $params]));
}
//addition
@@ -1098,6 +1217,7 @@ class EmployeeMultiEventServiceController extends BaseController
$params["action"] = "addition";
$params["file_path"] = $file_paths['addition'];
$error[] = $this->excelFileDataValidation($params);
+ $this->myLogger->logme('error', 'Addition file validation result: ' . json_encode(['params' => $params]));
}
//dependent_addition
@@ -1105,6 +1225,7 @@ class EmployeeMultiEventServiceController extends BaseController
$params["action"] = "dependent_addition";
$params["file_path"] = $file_paths['dependent_addition'];
$error[] = $this->excelFileDataValidation($params);
+ $this->myLogger->logme('error', 'Dependent Addition file Data validation result: ' . json_encode(['params' => $params]));
}
//deletion
@@ -1112,6 +1233,7 @@ class EmployeeMultiEventServiceController extends BaseController
$params["action"] = "deletion";
$params["file_path"] = $file_paths['deletion'];
$error[] = $this->excelFileDataValidation($params);
+ $this->myLogger->logme('error', 'Deletion file Data validation result: ' . json_encode(['params' => $params]));
}
//correction
@@ -1119,6 +1241,7 @@ class EmployeeMultiEventServiceController extends BaseController
$params["action"] = "correction";
$params["file_path"] = $file_paths['correction'];
$error[] = $this->excelFileDataValidation($params);
+ $this->myLogger->logme('error', 'Correction file Data validation result: ' . json_encode(['params' => $params]));
}
//si_enhancement
@@ -1126,6 +1249,7 @@ class EmployeeMultiEventServiceController extends BaseController
$params["action"] = "si_enhancement";
$params["file_path"] = $file_paths['si_enhancement'];
$error[] = $this->excelFileDataValidation($params);
+ $this->myLogger->logme('error', 'SI Enhancement file Data validation result: ' . json_encode(['params' => $params]));
}
//missed_inception
@@ -1133,6 +1257,7 @@ class EmployeeMultiEventServiceController extends BaseController
$params["action"] = "missed_inception";
$params["file_path"] = $file_paths['missed_inception'];
$error[] = $this->excelFileDataValidation($params);
+ $this->myLogger->logme('error', 'Missed Inception file Data validation result: ' . json_encode(['params' => $params]));
}
$error_type = 2;
@@ -1141,6 +1266,7 @@ class EmployeeMultiEventServiceController extends BaseController
if (isset($error['error_data']) && count($error['error_data']) == 0) {
$r = Jobs::addJob(['job_name' => 'excelMultieventFileOnBoard', 'payload' => $params]);
+ $this->myLogger->logme('error', 'excelMultieventFileOnBoard job pushed');
} else {
// $error['error_summary'] = array_count_values($error['error_summary']);
@@ -1153,11 +1279,15 @@ class EmployeeMultiEventServiceController extends BaseController
$this->setPullNotification($this->getFileMetaDataByFileId($file_id, 'failure'));
}
+ $this->myLogger->logme('error', 'Excel Multievent File Data Validation function END');
+
return ($error);
}
public function excelMultieventFileOnBoard($params)
{
+ $this->myLogger->logme('error', 'Excel Multievent File Onboard function START: ' . json_encode(['params' => $params]));
+
helper('excel_util_helper');
$file_id = $params['file_id'];
@@ -1187,6 +1317,7 @@ class EmployeeMultiEventServiceController extends BaseController
$params["action"] = "inception";
$params["file_path"] = $file_paths['inception'];
$error['inception'] = $this->employeesOnboardPreprocess($params);
+ $this->myLogger->logme('error', 'Inception file Onboard Process result: ' . json_encode(['params' => $params]));
}
//addition
@@ -1194,6 +1325,7 @@ class EmployeeMultiEventServiceController extends BaseController
$params["action"] = "addition";
$params["file_path"] = $file_paths['addition'];
$error['addition'] = $this->employeesOnboardPreprocess($params);
+ $this->myLogger->logme('error', 'Addition file Onboard Process result: ' . json_encode(['params' => $params]));
}
//dependent_addition
@@ -1201,6 +1333,7 @@ class EmployeeMultiEventServiceController extends BaseController
$params["action"] = "dependent_addition";
$params["file_path"] = $file_paths['dependent_addition'];
$error['dependent_addition'] = $this->employeesOnboardPreprocess($params);
+ $this->myLogger->logme('error', 'Dependent Addition file Onboard Process result: ' . json_encode(['params' => $params]));
}
//missed_inception
@@ -1208,6 +1341,7 @@ class EmployeeMultiEventServiceController extends BaseController
$params["action"] = "missed_inception";
$params["file_path"] = $file_paths['missed_inception'];
$error['missed_inception'] = $this->employeesOnboardPreprocess($params);
+ $this->myLogger->logme('error', 'Missed Inception file Onboard Process result: ' . json_encode(['params' => $params]));
}
//deletion
@@ -1215,6 +1349,7 @@ class EmployeeMultiEventServiceController extends BaseController
$params["action"] = "deletion";
$params["file_path"] = $file_paths['deletion'];
$error['deletion'] = $this->employeeDisembark($params);
+ $this->myLogger->logme('error', 'Deletion file Onboard Process result: ' . json_encode(['params' => $params]));
}
//correction
@@ -1222,6 +1357,7 @@ class EmployeeMultiEventServiceController extends BaseController
$params["action"] = "correction";
$params["file_path"] = $file_paths['correction'];
$error['correction'] = $this->employeesCorrectionProcess($params);
+ $this->myLogger->logme('error', 'Correction file Onboard Process result: ' . json_encode(['params' => $params]));
}
//si_enhancement
@@ -1229,11 +1365,13 @@ class EmployeeMultiEventServiceController extends BaseController
$params["action"] = "si_enhancement";
$params["file_path"] = $file_paths['si_enhancement'];
$error['si_enhancement'] = $this->employeesSIEnhanceProcess($params);
+ $this->myLogger->logme('error', 'SI Enhancement file Onboard Process result: ' . json_encode(['params' => $params]));
}
$this->fileModel->where('id', $file_id)->set(['status' => 'success', 'reason' => ''])->update();
$this->myLogger->logme("error", $file['action'].': {file_id} uploaded success', ['file_id' => $file_id]);
$this->setPullNotification($this->getFileMetaDataByFileId($file_id, 'success'));
+ $this->myLogger->logme('error', 'Excel Multievent File Onboard function END');
//After insert the success than remove the TEMP JSON files
// $this->unlinkFiles($params['multi_event_file_paths']);
@@ -1357,6 +1495,13 @@ class EmployeeMultiEventServiceController extends BaseController
$enrollment_keys = array_keys($enrollment_columns_to_check);
}
+ // for this condition to avoid 5,00,000 to 500000
+ if($current_column_action == 'SI'){
+ $row[3] = removeNumberFormatting($row[3]);
+ }else if(in_array($current_column_action, ['I','DA', 'MI', 'A'])){
+ $row[6] = removeNumberFormatting($row[6]);
+ }
+
//iterate each row for columns validations
foreach ($row as $col_key => $col) {
$is_mandatory = $columns_to_check[$keys[$col_key]]['is_mandatory'];
@@ -1495,6 +1640,16 @@ class EmployeeMultiEventServiceController extends BaseController
$columns_to_check = $this->inception_excel_columns;
}
+ $current_column_action = null;
+ if($file['action'] == 'inception'){ $current_column_action = 'I'; }
+ else if($file['action'] == 'addition'){ $current_column_action = 'A'; }
+ else if($file['action'] == 'dependent_addition'){ $current_column_action = 'DA'; }
+ else if($file['action'] == 'deletion'){ $current_column_action = 'D'; }
+ else if($file['action'] == 'correction'){ $current_column_action = 'C'; }
+ else if($file['action'] == 'si_enhancement'){ $current_column_action = 'SI'; }
+ else if($file['action'] == 'enrollment'){ $current_column_action = 'I'; }
+ else if($file['action'] == 'missed_inception'){ $current_column_action = 'MI'; }
+
$columns_to_check = $this->syncColIndex($this->multievent_excel_columns, $columns_to_check);
// print_rr($columns_to_check);
@@ -1522,7 +1677,7 @@ class EmployeeMultiEventServiceController extends BaseController
if (in_array($file['action'], ['inception', 'missed_inception', 'addition', 'dependent_addition', 'deletion', 'correction', 'si_enhancement', 'enrollment'])) // the below funcitons are only for I,DA,A
{
- $employee_data_group_by_family = data_group_by_family($excel_data, 'excel', ($file['action'] == 'enrollment' ? 'enrollment' : ''));
+ $employee_data_group_by_family = data_group_by_family($excel_data, 'excel', ($file['action'] == 'enrollment' ? 'enrollment' : ''), $current_column_action);
// dd($employee_data_group_by_family);
$is_self_available_in_policy_terms = false;
if ($policy_details['policy_type_id'] == 3) // GMC parents
@@ -1694,6 +1849,16 @@ class EmployeeMultiEventServiceController extends BaseController
$columns_to_check = $this->inception_excel_columns;
}
+ $current_column_action = null;
+ if($file['action'] == 'inception'){ $current_column_action = 'I'; }
+ else if($file['action'] == 'addition'){ $current_column_action = 'A'; }
+ else if($file['action'] == 'dependent_addition'){ $current_column_action = 'DA'; }
+ else if($file['action'] == 'deletion'){ $current_column_action = 'D'; }
+ else if($file['action'] == 'correction'){ $current_column_action = 'C'; }
+ else if($file['action'] == 'si_enhancement'){ $current_column_action = 'SI'; }
+ else if($file['action'] == 'enrollment'){ $current_column_action = 'I'; }
+ else if($file['action'] == 'missed_inception'){ $current_column_action = 'MI'; }
+
// get policy and rack details
$policy_terms = $this->clientPolicyModel->getPolicyDetails($file['client_id'], $file['policy_id']);
$policy_terms = (array) $policy_terms[0]; // convert obj to array
@@ -1717,7 +1882,7 @@ class EmployeeMultiEventServiceController extends BaseController
//get existing units in the current branch
$existing_units = $this->clientBranchModel->getExisitingUnits(client_id: $file['client_id'], client_branch_id: $file['client_branch_id']);
- $employee_data_group_by_family = data_group_by_family($excel_data);
+ $employee_data_group_by_family = data_group_by_family($excel_data, 'excel', '', $current_column_action);
// dd($employee_data_group_by_family);
foreach ($employee_data_group_by_family as $emp_id => $family) {
@@ -2029,6 +2194,9 @@ class EmployeeMultiEventServiceController extends BaseController
if (check_row_is_empty_or_null($row)) {
break;
}
+
+ $row[3] = removeNumberFormatting($row[3]);
+
// echo '
START- ' . $row[2];
$employee = $this->employeeModel
->where('emp_code', $row[1])
@@ -2038,6 +2206,7 @@ class EmployeeMultiEventServiceController extends BaseController
->where('emp_status', 'active')
->where('is_active', 1)
->first();
+
$employee_policy = $this->employeePolicyModel
->where('employee_id', $employee['id'])
->where('client_policy_id', $file['policy_id'])
@@ -2052,8 +2221,11 @@ class EmployeeMultiEventServiceController extends BaseController
->where('emp_code', $employee['emp_code'])
->where('name', $employee['name'])
->where('field_name', 'basic_cover_si')
+ ->where('is_active', 1)
+ ->where('status !=', 'truncated')
->findAll();
// dd($existing_endorsements);
+
//make entry in endorsement table
if (!count($existing_endorsements)) {
//transform data to send
@@ -2101,6 +2273,8 @@ class EmployeeMultiEventServiceController extends BaseController
$this->empEndorsementModel->save(['pk' => (int)$employee_policy['id'], 'emp_code' => $employee['emp_code'], 'table_name' => 'employee_polices', 'actions' => 'si', 'name' => $employee['name'], 'field_name' => 'basic_cover_si', 'old_value' => $employee_policy['basic_cover_si'], 'new_value' => $row[3], 'created_by' => $file['created_by'], 'remarks' => 'general si enhancement', 'group_key' => $group_key, 'file_id' => $file['id'], 'status' => 'pending']);
$this->empEndorsementModel->save(['pk' => (int)$employee_policy['id'], 'emp_code' => $employee['emp_code'], 'table_name' => 'employee_polices', 'actions' => 'si', 'name' => $employee['name'], 'field_name' => 'premium', 'old_value' => $employee_policy['premium'], 'new_value' => $calculated_data['policy_details']['premium'], 'created_by' => $file['created_by'], 'remarks' => 'general si enhancement', 'group_key' => $group_key, 'file_id' => $file['id'], 'status' => 'pending']);
$this->empEndorsementModel->save(['pk' => (int)$employee_policy['id'], 'emp_code' => $employee['emp_code'], 'table_name' => 'employee_polices', 'actions' => 'si', 'name' => $employee['name'], 'field_name' => 'si_enhancement_date', 'old_value' => null, 'new_value' => change_date_format($row[4], 'd-M-Y', 'Y-m-d'), 'created_by' => $file['created_by'], 'remarks' => 'general si enhancement', 'group_key' => $group_key, 'file_id' => $file['id'], 'status' => 'pending']);
+ }else {
+ $this->myLogger->logme("error", 'Endorsement already exists for this employee ' . json_encode(['file_id' => $file_id, 'emp_code' => $employee['emp_code'], 'emp_name' => $employee['name']]));
}
}
@@ -2125,10 +2299,9 @@ class EmployeeMultiEventServiceController extends BaseController
foreach ($familiy_data as $fkey => $value) {
if (is_array($value)) {
-
+ if (isset($value['gender'])) { $value['gender'] = normalizeGender($value['gender'] );}
if ($file['id'] == null || $value['temp']['source'] == 'excel' || (($file['action'] == 'dependent_addition' && ($value['temp']['premium_type'] == 1 && strtolower($value['relationship']) == 'self') || ($value['temp']['premium_type'] == 2 || $value['temp']['premium_type'] == null)))) //insert data come from excel and from db i.e. ( $file['id'] == null for enrollment data)
{
-
$employee = $this->employeeModel->checkExistingEmp($value, $file['client_branch_id']);
$policy_data = $value['policy_details'];
$temp = $value['temp'];
@@ -2773,9 +2946,13 @@ class EmployeeMultiEventServiceController extends BaseController
// Save JSON file in writable/tmp/
$savedFiles = [];
foreach ($finalData as $key => $data) {
- $filePath = WRITEPATH . 'tmp/' . $key . '_' . time() . '.json';
- file_put_contents($filePath, json_encode($data, JSON_PRETTY_PRINT));
- $savedFiles[$key] = $filePath;
+ if(!empty($data)){
+ $filePath = WRITEPATH . 'tmp/' . $key . '_' . time() . '.json';
+ file_put_contents($filePath, json_encode($data, JSON_PRETTY_PRINT));
+ $savedFiles[$key] = $filePath;
+ }else{
+ $savedFiles[$key] = "";
+ }
}
return $savedFiles;
@@ -2881,6 +3058,135 @@ class EmployeeMultiEventServiceController extends BaseController
return $temp;
}
+ // --------- MEMBER DATA AND INCEPTION DATA COMPARISION ------------------------------------------------------------------------
+
+ public function compareMemberDataAndInceptionData($params)
+ {
+ $file_id = $params['file_id'] ?? null;
+ if (empty($file_id)) {
+ return ['status' => false, 'msg' => 'File ID is missing'];
+ }
+
+ // ✅ Get File Data
+ $file = $this->fileModel->where(['is_active' => 1, 'id' => $file_id])->first();
+ if (empty($file)) {
+ return ['status' => false, 'msg' => 'File not found in DB'];
+ }
+
+ // ✅ Get Client Policy Data
+ $client_policy_data = $this->clientPolicyModel->where(['is_active' => 1, 'id' => $file['policy_id']])->first();
+ if (empty($client_policy_data)) {
+ return ['status' => false, 'msg' => 'Client policy data not found in DB (policy_id: ' . $file['policy_id'] . ')'];
+ }
+
+ // ✅ Get Lead Data
+ $leadModel = new LeadsModel();
+ $lead_data = $leadModel->where(['is_active' => 1, 'id' => $client_policy_data['is_from_lead']])->first();
+ if (empty($lead_data)) {
+ return ['status' => false, 'msg' => 'Lead data not found in DB (lead_id: ' . $client_policy_data['is_from_lead'] . ')'];
+ }
+
+ // ✅ Define File Paths
+ // $inception_file_path = !empty($file['file_name']) ? WRITEPATH . "uploads/excel/" . $file['file_name'] : '';
+ $member_file_path = !empty($lead_data['file_name']) ? WRITEPATH . "uploads/lead_files/" . $lead_data['file_name'] : '';
+
+ // ✅ Check Inception File
+ // if (empty($file['file_name']) || !file_exists($inception_file_path)) {
+ // $message = empty($file['file_name']) ? "Inception file name is missing" : "Inception physical file not found";
+ // $this->myLogger->logme('error', "$message for file id $file_id");
+ // $this->fileModel->update($file_id, [
+ // 'status' => 'failed',
+ // 'reason' => json_encode(['error_summary' => [5], 'error_data' => $message])
+ // ]);
+ // return ['error_summary' => [5], 'error_data' => $message];
+ // }
+
+ // ✅ Check Member File
+ if (empty($lead_data['file_name']) || !file_exists($member_file_path)) {
+ $message = empty($lead_data['file_name']) ? "Member file name is missing" : "Member data physical file not found";
+ $this->myLogger->logme('error', "$message for lead id {$lead_data['id']}");
+ $this->fileModel->update($file_id, [
+ 'status' => 'failed',
+ 'reason' => json_encode(['error_summary' => [5], 'error_data' => $message])
+ ]);
+ return ['error_summary' => [5], 'error_data' => $message];
+ }
+
+
+ // ✅ Read Inception Excel
+ $inception_columns = $this->inception_excel_columns;
+ $inception_data = json_decode(file_get_contents($params['file_path'] ?? []), true);
+ // $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($inception_file_path);
+ // $sheet = $spreadsheet->getActiveSheet();
+ // $highestRow = $sheet->getHighestDataRow();
+ // $allowedColumn = end($inception_columns)['col_cell_name'];
+ // $inception_data = $sheet->rangeToArray("A1:{$allowedColumn}{$highestRow}");
+ // $inception_data = ExcelSanitizeHelper::sanitizeArrayData($inception_data);
+
+ // ✅ Read Member Excel
+ $member_columns = $this->member_data_excel_columns;
+ $spreadsheet2 = \PhpOffice\PhpSpreadsheet\IOFactory::load($member_file_path);
+ $sheet2 = $spreadsheet2->getSheet(0);
+ $highestRow2 = $sheet2->getHighestDataRow();
+ $allowedColumn2 = end($member_columns)['col_cell_name'];
+ $member_data = $sheet2->rangeToArray("A1:{$allowedColumn2}{$highestRow2}");
+ $member_data = ExcelSanitizeHelper::sanitizeArrayData($member_data);
+
+ // dd($inception_data, $member_data);
+
+ // ✅ Compare Inception Data with Member Data
+ $result = ['error_type' => 2, 'error_summary' => [], 'error_data' => []];
+
+ $inception_data_count = count($inception_data);
+ $member_data_count = count($member_data);
+
+ if ($inception_data_count !== $member_data_count) {
+ $result['error_summary'][] = 15;
+ $result['error_message'] = "
+ Inception Data Count:
+ {$inception_data_count}
+ Member Data Count:
+ {$member_data_count}";
+ }
+
+ foreach ($inception_data as $inception_key => $inception_row) {
+
+ // 🔹 If inception row is empty → stop all further processing
+ if (check_row_is_empty_or_null($inception_row)) {
+ break;
+ }
+
+ $match_found = false;
+
+ foreach ($member_data as $member_row) {
+ if (
+ $inception_row[1] == $member_row[1] && // emp_id / emp_code
+ $inception_row[2] == $member_row[2] && // name_of_emp_dep / name
+ $inception_row[5] == $member_row[3] && // relationship
+ normalizeGender($inception_row[4]) == normalizeGender($member_row[4]) && // gender
+ $inception_row[3] == $member_row[5] && // dob
+ $inception_row[13] == $member_row[7] && // email
+ $inception_row[12] == $member_row[8] // phone / mobile
+ ) {
+ $match_found = true;
+ break;
+ }
+ }
+
+ if (!$match_found) {
+ array_push($result['error_summary'], 14);
+ $result['error_data'][$inception_key]['sno']['error'][] = "This inception row was not found in the member data list.";
+ }
+ }
+
+ // ✅ Handle Result
+ if (!empty($result['error_summary'])) {
+ $result['error_summary'] = array_count_values($result['error_summary']);
+ $this->myLogger->logme('error', "File ID $file_id comparison failed");
+ }
+
+ return $result;
+ }
}
diff --git a/app/Controllers/EmployeeRestController.php b/app/Controllers/EmployeeRestController.php
index ff7bfdf7..1d7cdda2 100755
--- a/app/Controllers/EmployeeRestController.php
+++ b/app/Controllers/EmployeeRestController.php
@@ -57,6 +57,8 @@ use Illuminate\Http\Request;
use App\Controllers\EmployeeServiceController;
use App\Models\ClaimFilesModel;
+use App\Models\TicketMailTemplateModel;
+use Composer\Pcre\Preg;
use Kreait\Firebase\Factory;
use Kreait\Firebase\Messaging\CloudMessage;
use Kreait\Firebase\Messaging\Notification;
@@ -94,6 +96,7 @@ class EmployeeRestController extends AdminController
protected $hrAccessControlModel;
protected $insurerModel;
protected $hrFileUploadModel;
+ protected $ticketMailTemplateModel;
public function __construct()
@@ -126,6 +129,7 @@ class EmployeeRestController extends AdminController
$this->hrAccessControlModel = new HRAccessControlModel();
$this->insurerModel = new InsurerModel();
$this->hrFileUploadModel = new HrFileUploadModel();
+ $this->ticketMailTemplateModel = new TicketMailTemplateModel();
}
@@ -2831,7 +2835,7 @@ class EmployeeRestController extends AdminController
->where('client_policy.client_branch_id', $this->request->getGet('client_branch_id') )
->where('client_policy.is_active', 1 )
->where('client_policy.policy_status', $policy_status)
- ->where('client_policy.enrolment_visibility', 1 )
+ ->where('client_policy.enrolment_visibility', 1)
->orderby('client_policy.id' , 'ASC')
->findAll();
@@ -2840,16 +2844,25 @@ class EmployeeRestController extends AdminController
->where('client_id',$this->request->getGet('client_id'))
->where('client_branch_id',$this->request->getGet('client_branch_id'))
->where('is_active', 1 )->findAll();
- $employeeName = $this->employeeModel->where('emp_code',$this->request->getGet('emp_code'))
+
+ $employeeSelfData = $this->employeeModel->where('emp_code',$this->request->getGet('emp_code'))
->where('client_id',$this->request->getGet('client_id'))
->where('client_branch_id',$this->request->getGet('client_branch_id'))
->where('family_floater_key','self')->where('is_active', 1 )
- ->get()->getRow()->name;
+ ->get()->getRow();
+ $employeeName = $employeeSelfData->name ?? "";
+
+
//for get the pre enrollment policy count
$empMobileNo = $this->request->getGet('mobile_no');
$clientId = $this->request->getGet('client_id');
- $prePolicyCount = $this->getPreEmployeePolicyCount($empMobileNo, $clientId);
+
+ if(!empty($employeeSelfData) && isset($employeeSelfData->email_corporate)){
+ $prePolicyCount = $this->getPreEmployeePolicyCount($empMobileNo, $clientId, $employeeSelfData->email_corporate);
+ }else{
+ $prePolicyCount = $this->getPreEmployeePolicyCount($empMobileNo, $clientId);
+ }
$whereArrayForId = [];
foreach ( $employeeData as $key => $value) { array_push($whereArrayForId, $value['id']); }
@@ -2972,7 +2985,11 @@ class EmployeeRestController extends AdminController
function policyTermsFiter($terms , $type)
- {
+ {
+ if(empty($terms)){
+ return [];
+ }
+
$gpa = [
"sumInsured2" => "Sum Insured",
"totalSumInsured" => "Total Sum Assured",
@@ -3471,6 +3488,15 @@ class EmployeeRestController extends AdminController
$received_data = $this->request->getPost();
$this->myLogger->logme('error', 'API claim initiate Recevied Params :' . json_encode($received_data ?? []));
$get_file_data = $this->request->getFiles('claim_docs');
+ $get_docs_name = $this->request->getPost('claim_doc_names') ?? [];
+
+ if (is_string($get_docs_name)) {
+ $decoded = json_decode($get_docs_name, true);
+ $get_docs_name = json_last_error() === JSON_ERROR_NONE ? $decoded : [];
+ } elseif (!is_array($get_docs_name)) {
+ $get_docs_name = [];
+ }
+
// print_r($get_file_data); die;
$employee_id = $received_data['emp_id'];
$client_policy_id = $received_data['client_policy_id'];
@@ -3479,7 +3505,7 @@ class EmployeeRestController extends AdminController
$file_data = [];
if(isset($get_file_data) && !empty($get_file_data)){
$file_path = WRITEPATH . 'uploads/claim_files/';
- $file_data = multi_file_Upload($get_file_data, $file_path);
+ $file_data = multi_file_Upload($get_file_data, $file_path, $get_docs_name);
}
@@ -3629,7 +3655,8 @@ class EmployeeRestController extends AdminController
$data = [
'ticket_id' => $ticket_id,
- 'doc_name' => $value['file_name'],
+ 'doc_name' => $value['doc_name'],
+ 'file_name' => $value['file_name'],
'url' => $value['file_path'],
'file_type' => 2,
'ticket_message_id' => $ticket_message_id,
@@ -4075,18 +4102,19 @@ class EmployeeRestController extends AdminController
// }
// }
- public function getPreEmployeePolicyCount($mobile_no, $clientId = null)
- {
- log_message('error', 'STEP 1: getPreEmployeePolicyCount called with params: ' . json_encode(['mobile_no' => $mobile_no, 'client_id' => $clientId]));
+ public function getPreEmployeePolicyCount($mobile_no, $clientId = null, $email = null)
+ {
+ log_message('error', 'STEP 1: getPreEmployeePolicyCount called with params: ' . json_encode(['mobile_no' => $mobile_no, 'client_id' => $clientId, 'email' => $email]));
- if (empty($mobile_no)) {
- log_message('error', 'STEP 2: Mobile number is empty or null. Returning 0.');
+ if (empty($mobile_no) && empty($email)) {
+ log_message('error', 'STEP 2: Mobile number and Email is empty or null. Returning 0.');
return 0;
}
$client_short_name = null;
if (!empty($clientId)) {
+
log_message('error', 'STEP 3: Fetching client short name for client ID: ' . $clientId);
$client_data = $this->clientModel->where('is_active', 1)->where('id', $clientId)->first();
@@ -4096,14 +4124,25 @@ class EmployeeRestController extends AdminController
} else {
log_message('error', 'STEP 4: No client found for ID: ' . $clientId);
}
+
} else {
log_message('error', 'STEP 3: No clientId provided. Skipping client lookup.');
}
- $post_data = [
- 'mobile_number' => $mobile_no,
- 'client_short_name' => $client_short_name
- ];
+ if(!empty($email)){
+ $post_data = [
+ 'email_id' => $email,
+ 'client_short_name' => $client_short_name
+ ];
+ }else{
+ $post_data = [
+ 'mobile_number' => $mobile_no,
+ 'client_short_name' => $client_short_name
+ ];
+
+ }
+
+
log_message('error', 'STEP 5: Calling third-party API with payload: ' . json_encode($post_data));
@@ -4181,7 +4220,11 @@ class EmployeeRestController extends AdminController
];
// Save into DB
- $this->hrFileUploadModel->insert($data);
+ $result = $this->hrFileUploadModel->insert($data);
+
+ if($result){
+ $this->giveNotificationToClientsAccountManager($data);
+ }
return $this->respondCreated([
'status' => true,
@@ -4195,6 +4238,45 @@ class EmployeeRestController extends AdminController
}
+ private function giveNotificationToClientsAccountManager($data){
+
+ $client_name = $this->clientModel->where('id',$data['client_id'])->findAll()[0]['client_name'] ?? [] ;
+
+ $account_manager_email = $this->clientRMModel->findAccountManagerEmail($data['client_id']);
+
+ $templateName = "hr_endorsement_template";
+
+ $mailTemplate = $this->ticketMailTemplateModel->where('template_name', $templateName)->findAll()[0] ?? [];
+
+ if(empty($mailTemplate)){
+ //empty mail template please update the template in database or create one..!!
+ log_message("error","Empty mail template for inception_addition please update the template in database or create one..!!");
+ return ;
+ }
+
+ $data['file_action'] = ucwords(preg_replace("/_/", " ", $data['file_action']));
+
+ $mailTemplate['mail_content'] = str_replace('%file_action%', $data['file_action'] ?? '', $mailTemplate['mail_content']);
+ $mailTemplate['mail_content'] = str_replace('%client_name%', $client_name ?? '', $mailTemplate['mail_content']);
+ $mailTemplate['mail_content'] = str_replace('%policy_no%', $data['policy_no'] ?? '', $mailTemplate['mail_content']);
+
+ $mailTemplate['subject'] = str_replace('%subject%',$data['file_action']??'',$mailTemplate['subject']);
+ $mailTemplate['subject'] = str_replace('%client_name%',$client_name??'',$mailTemplate['subject']);
+
+ $from_mail = "";
+ $to_mail = $account_manager_email;
+ $subject = $mailTemplate['subject'];
+ $message = $mailTemplate['mail_content'];
+ $cc_string = "";
+ $attachments = "";
+ $reply_to = "";
+ $bcc_string = "";
+
+
+ MailHelper::send_email(['from_mail' => $from_mail, 'mail' => $to_mail, 'cc' => $cc_string, 'subject' => $subject, 'message' => $message, 'attachments' => $attachments, 'reply_to' => $reply_to, 'bcc' => $bcc_string]);
+
+ }
+
public function updateHrFileUploadData()
{
try {
diff --git a/app/Controllers/EmployeeServiceController.php b/app/Controllers/EmployeeServiceController.php
index 07bf7ad5..4b71694c 100755
--- a/app/Controllers/EmployeeServiceController.php
+++ b/app/Controllers/EmployeeServiceController.php
@@ -29,7 +29,7 @@ use PhpOffice\PhpSpreadsheet\Spreadsheet;
use Kint\Kint;
use App\Helpers\ExcelSanitizeHelper;
-
+use App\Models\LeadsModel;
class EmployeeServiceController extends AdminController
{
@@ -144,7 +144,7 @@ class EmployeeServiceController extends AdminController
'is_mandatory' => ['I', 'A', 'DA'],
'data_type' => 'str',
'format' => null,
- 'allowed_values' => ['M', 'F']
+ 'allowed_values' => ['M', 'F', 'Male', 'Female', 'male', 'female', 'MALE', 'FEMALE']
],
'relationship' => [
'col_idx' => 5,
@@ -529,7 +529,8 @@ class EmployeeServiceController extends AdminController
'is_mandatory' => ['I', 'A', 'DA','E'],
'data_type' => 'str',
'format' => null,
- 'allowed_values' => ['M', 'F']
+ 'allowed_values' => ['M', 'F', 'Male', 'Female', 'male', 'female', 'MALE', 'FEMALE']
+
],
'relationship' => [
'col_idx' => 5,
@@ -643,21 +644,121 @@ class EmployeeServiceController extends AdminController
];
protected $enrollment_to_inception_mapping = [
- 0 => 0, // enrollment: sno (Sno) -> inception: sno (S.No)
- 1 => 1, // enrollment: emp_code (Emp_Code) -> inception: emp_id (EMP ID)
- 2 => 2, // enrollment: name (NAME OF EMP/DEP) -> inception: name_of_emp_dep (NAME OF EMP/DEP)
- 3 => 8, // enrollment: doj (DOJ) -> inception: doj (DOJ)
- 4 => 4, // enrollment: gender (Gender) -> inception: gender (Gender)
- 5 => 5, // enrollment: relationship (Relation) -> inception: relationship (RELATIONSHIP)
- 6 => 3, // enrollment: dob (DOB) -> inception: dob (DOB)
- 7 => 13, // enrollment: email (Email) -> inception: email (Email)
- 8 => 12, // enrollment: phone (Mobile) -> inception: phone (Phone)
- 9 => 6, // enrollment: basic_cover_si (SI) -> inception: basic_cover_si (BASIC COVER SI)
- 10 => 10, // enrollment: band_grade (Grade) -> inception: band_grade (Band/Grade)
- 11 => 9 // enrollment: basic_pay (Basic Pay) -> inception: basic_pay (Basic Pay)
- ];
-
-
+ 0 => 0, // enrollment: sno (Sno) -> inception: sno (S.No)
+ 1 => 1, // enrollment: emp_code (Emp_Code) -> inception: emp_id (EMP ID)
+ 2 => 2, // enrollment: name (NAME OF EMP/DEP) -> inception: name_of_emp_dep (NAME OF EMP/DEP)
+ 3 => 8, // enrollment: doj (DOJ) -> inception: doj (DOJ)
+ 4 => 4, // enrollment: gender (Gender) -> inception: gender (Gender)
+ 5 => 5, // enrollment: relationship (Relation) -> inception: relationship (RELATIONSHIP)
+ 6 => 3, // enrollment: dob (DOB) -> inception: dob (DOB)
+ 7 => 13, // enrollment: email (Email) -> inception: email (Email)
+ 8 => 12, // enrollment: phone (Mobile) -> inception: phone (Phone)
+ 9 => 6, // enrollment: basic_cover_si (SI) -> inception: basic_cover_si (BASIC COVER SI)
+ 10 => 10, // enrollment: band_grade (Grade) -> inception: band_grade (Band/Grade)
+ 11 => 9 // enrollment: basic_pay (Basic Pay) -> inception: basic_pay (Basic Pay)
+ ];
+ protected $member_data_excel_columns = [
+ 'sno' => [
+ 'col_idx' => 0,
+ 'col_cell_name' => 'A',
+ 'col_name' => 'Sl no',
+ 'is_mandatory' => false,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+ 'emp_code' => [
+ 'col_idx' => 1,
+ 'col_cell_name' => 'B',
+ 'col_name' => 'Emp Code',
+ 'is_mandatory' => true,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+ 'name' => [
+ 'col_idx' => 2,
+ 'col_cell_name' => 'C',
+ 'col_name' => 'Name',
+ 'is_mandatory' => true,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+ 'relationship' => [
+ 'col_idx' => 3,
+ 'col_cell_name' => 'D',
+ 'col_name' => 'Relationship',
+ 'is_mandatory' => true,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => [
+ 'Self', 'Spouse', 'Son', 'Daughter', 'Father', 'Mother',
+ 'Father-in-law', 'Mother-in-law',
+ 'self', 'spouse', 'son', 'daughter', 'father', 'mother',
+ 'father-in-law', 'mother-in-law'
+ ],
+ 'custom' => 'check_relationship_for_member_data',
+ 'params' => ['row', 'relationship', 'columns_to_check']
+ ],
+ 'gender' => [
+ 'col_idx' => 4,
+ 'col_cell_name' => 'E',
+ 'col_name' => 'Gender',
+ 'is_mandatory' => true,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => ['M', 'F', 'Male', 'Female', 'male', 'female', 'MALE', 'FEMALE']
+ ],
+ 'dob' => [
+ 'col_idx' => 5,
+ 'col_cell_name' => 'F',
+ 'col_name' => 'DOB',
+ 'is_mandatory' => true,
+ 'data_type' => 'str',
+ 'format' => 'd-M-Y',
+ 'allowed_values' => null,
+ 'age_validation' => true,
+ // 'custom' => 'check_dob_diff',
+ // 'params' => ['row', 'relationship', 'default_age_ratio', 'policy_details']
+ ],
+ 'age' => [
+ 'col_idx' => 6,
+ 'col_cell_name' => 'G',
+ 'col_name' => 'Age',
+ 'is_mandatory' => true,
+ 'data_type' => 'int',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+ 'email' => [
+ 'col_idx' => 7,
+ 'col_cell_name' => 'H',
+ 'col_name' => 'Email',
+ 'is_mandatory' => false,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+ 'mobile' => [
+ 'col_idx' => 8,
+ 'col_cell_name' => 'I',
+ 'col_name' => 'Mobile',
+ 'is_mandatory' => false,
+ 'data_type' => 'str',
+ 'format' => null,
+ 'allowed_values' => null
+ ],
+ 'si' => [
+ 'col_idx' => 9,
+ 'col_cell_name' => 'J',
+ 'col_name' => 'SI',
+ 'is_mandatory' => false,
+ 'data_type' => 'int',
+ 'format' => null,
+ 'allowed_values' => null,
+ ]
+ ];
public function __construct()
{
@@ -809,6 +910,13 @@ class EmployeeServiceController extends AdminController
$enrollment_columns_to_check = $this->enrollment_excel_columns;
$enrollment_keys = array_keys($enrollment_columns_to_check);
}
+
+ // for this condition to avoid 5,00,000 to 500000
+ if($current_column_action == 'SI'){
+ $row[3] = removeNumberFormatting($row[3]);
+ }else if(in_array($current_column_action, ['I','DA', 'MI', 'A'])){
+ $row[6] = removeNumberFormatting($row[6]);
+ }
//iterate each row for columns validations
foreach ($row as $col_key => $col)
@@ -923,7 +1031,14 @@ class EmployeeServiceController extends AdminController
}
else //trigger next data validation via job queue server
- {
+ {
+ // check the condition if the policy from the Leads and check the lead id exist in the client policy table
+ if($file['action'] == 'inception' && $policy_details[0]->policy_entry_from == 3 && !empty($policy_details[0]->is_from_lead)){
+ $r = Jobs::addJob(['job_name' => 'compareMemberDataAndInceptionData','payload' => ['file_id' => $file_id]]);
+ $this->myLogger->logme("error",'compareMemberDataAndInceptionData job pushed');
+ return $result;
+ }
+
if($file['action'] == 'enrollment' && $file['uploaded_by'] != 1) // if current action is enrollment and uploaded by HR (0 or NULL) call next validation and return result
{
// dd();
@@ -978,6 +1093,16 @@ class EmployeeServiceController extends AdminController
if($file['action'] == 'enrollment'){ $columns_to_check = $this->enrollment_excel_columns; }
if($file['action'] == 'missed_inception'){ $columns_to_check = $this->inception_excel_columns; }
+ $current_column_action = null;
+ if($file['action'] == 'inception'){ $current_column_action = 'I'; }
+ else if($file['action'] == 'addition'){ $current_column_action = 'A'; }
+ else if($file['action'] == 'dependent_addition'){ $current_column_action = 'DA'; }
+ else if($file['action'] == 'deletion'){ $current_column_action = 'D'; }
+ else if($file['action'] == 'correction'){ $current_column_action = 'C'; }
+ else if($file['action'] == 'si_enhancement'){ $current_column_action = 'SI'; }
+ else if($file['action'] == 'enrollment'){ $current_column_action = 'I'; }
+ else if($file['action'] == 'missed_inception'){ $current_column_action = 'MI'; }
+
// get policy and rack details
$policy_terms = $this->clientPolicyModel->getPolicyDetails($file['client_id'],$file['policy_id']);
$policy_details = (array)$policy_terms[0];
@@ -1008,7 +1133,7 @@ class EmployeeServiceController extends AdminController
if(in_array($file['action'],['inception','missed_inception','addition','dependent_addition','deletion','correction','si_enhancement','enrollment']))// the below funcitons are only for I,DA,A
{
- $employee_data_group_by_family = data_group_by_family($excel_data,'excel',($file['action'] == 'enrollment' ? 'enrollment' : ''));
+ $employee_data_group_by_family = data_group_by_family($excel_data,'excel',($file['action'] == 'enrollment' ? 'enrollment' : ''), $current_column_action);
// dd($employee_data_group_by_family);
$is_self_available_in_policy_terms = false;
if($policy_details['policy_type_id'] == 3) // GMC parents
@@ -1213,6 +1338,16 @@ class EmployeeServiceController extends AdminController
if($file['action'] == 'si_enhancement'){ $columns_to_check = $this->si_enhance_excel_columns; }
if($file['action'] == 'missed_inception'){ $columns_to_check = $this->inception_excel_columns; }
+ $current_column_action = null;
+ if($file['action'] == 'inception'){ $current_column_action = 'I'; }
+ else if($file['action'] == 'addition'){ $current_column_action = 'A'; }
+ else if($file['action'] == 'dependent_addition'){ $current_column_action = 'DA'; }
+ else if($file['action'] == 'deletion'){ $current_column_action = 'D'; }
+ else if($file['action'] == 'correction'){ $current_column_action = 'C'; }
+ else if($file['action'] == 'si_enhancement'){ $current_column_action = 'SI'; }
+ else if($file['action'] == 'enrollment'){ $current_column_action = 'I'; }
+ else if($file['action'] == 'missed_inception'){ $current_column_action = 'MI'; }
+
// get policy and rack details
$policy_terms = $this->clientPolicyModel->getPolicyDetails($file['client_id'],$file['policy_id']);
$policy_terms = (array) $policy_terms[0];// convert obj to array
@@ -1236,7 +1371,7 @@ class EmployeeServiceController extends AdminController
//get existing units in the current branch
$existing_units = $this->clientBranchModel->getExisitingUnits(client_id: $file['client_id'],client_branch_id: $file['client_branch_id']);
- $employee_data_group_by_family = data_group_by_family($excel_data);
+ $employee_data_group_by_family = data_group_by_family($excel_data, 'excel', '', $current_column_action);
// dd($employee_data_group_by_family);
foreach ($employee_data_group_by_family as $emp_id => $family)
{
@@ -1379,9 +1514,9 @@ class EmployeeServiceController extends AdminController
->where('employees.client_id',$file['client_id'])
->where('employees.client_branch_id',$file['client_branch_id'])
->where('employee_polices.client_policy_id',$file['policy_id'])
- ->where('employees.emp_status !=','truncated')
+ ->where('employees.emp_status','active')
->where('employees.is_active', 1)
- ->where('employee_polices.status !=','truncated')
+ ->where('employee_polices.status','active')
->where('employee_polices.is_active', 1)
->first();
@@ -1415,7 +1550,7 @@ class EmployeeServiceController extends AdminController
$employee_policy = $this->employeePolicyModel
->where('employee_id',$employee['id'])
->where('client_policy_id',$file['policy_id'])
- ->where('status !=','truncated')
+ ->where('status','active')
->where('is_active', 1)
->first();
@@ -1542,76 +1677,78 @@ class EmployeeServiceController extends AdminController
return true;
}
-
- //enhance of emp
+ //enhance of emp
public function employeesSIEnhanceProcess($params)
{
- helper('excel_util_helper');
+ helper('excel_util_helper');
//get file name
$file_id = $params['file_id'];
$file = $this->fileModel->find($file_id);
+ // dd($file);
- $file_name_with_path = WRITEPATH."/uploads/excel/".$file['file_name'];
+ $file_name_with_path = WRITEPATH . "/uploads/excel/" . $file['file_name'];
- $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file_name_with_path);
+ $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file_name_with_path);
$sheet = $spreadsheet->getActiveSheet();
-
+
$highestRowAndColumn = $sheet->getHighestRowAndColumn();
$allowedHighestColumn = end($this->si_enhance_excel_columns);
$excel_data = $sheet->rangeToArray('A1:' . $allowedHighestColumn['col_cell_name'] . $highestRowAndColumn['row']);
// $excel_data = $sheet->rangeToArray('A1:' . $highestRowAndColumn['column'] . $highestRowAndColumn['row']);
-
+
unset($excel_data[0]);
// dd($excel_data);
//get policy slab rates
- $slab_details = $this->policiesModel->getPolicySlabRatesForEmpOnboard($file['policy_id'],$file['client_id']);
+ $slab_details = $this->policiesModel->getPolicySlabRatesForEmpOnboard($file['policy_id'], $file['client_id']);
//iterate each row
// dd($slab_details);
- foreach ($excel_data as $col_key => $row)
- {
- if(check_row_is_empty_or_null($row))
- {
- break;
+ foreach ($excel_data as $col_key => $row) {
+ if (check_row_is_empty_or_null($row)) {
+ break;
}
+
+ $row[3] = removeNumberFormatting($row[3]);
+
// echo '
START- ' . $row[2];
$employee = $this->employeeModel
- ->where('emp_code', $row[1])
- ->where('name',$row[2])
- ->where('client_id',$file['client_id'])
- ->where('client_branch_id',$file['client_branch_id'])
- ->where('emp_status', 'active')
- ->where('is_active', 1)
- ->first();
+ ->where('emp_code', $row[1])
+ ->where('name', $row[2])
+ ->where('client_id', $file['client_id'])
+ ->where('client_branch_id', $file['client_branch_id'])
+ ->where('emp_status', 'active')
+ ->where('is_active', 1)
+ ->first();
+
$employee_policy = $this->employeePolicyModel
- ->where('employee_id',$employee['id'])
- ->where('client_policy_id',$file['policy_id'])
+ ->where('employee_id', $employee['id'])
+ ->where('client_policy_id', $file['policy_id'])
->where('status', 'active')
->where('is_active', 1)
->first();
// dd($employee, $employee_policy);
- $existing_endorsements = $this->empEndorsementModel->where('actions','si')
- ->where('table_name','employee_polices')
- ->where('endorsement_id is null')
- ->where('emp_code',$employee['emp_code'])
- ->where('name',$employee['name'])
- ->where('field_name','basic_cover_si')
- ->findAll();
- // dd($existing_endorsements);
- //make entry in endorsement table
- if(!count($existing_endorsements))
- {
+ $existing_endorsements = $this->empEndorsementModel->where('actions', 'si')
+ ->where('table_name', 'employee_polices')
+ ->where('endorsement_id is null')
+ ->where('emp_code', $employee['emp_code'])
+ ->where('name', $employee['name'])
+ ->where('field_name', 'basic_cover_si')
+ ->where('is_active', 1)
+ ->where('status !=', 'truncated')
+ ->findAll();
+ // dd($existing_endorsements);
+
+ //make entry in endorsement table
+ if (!count($existing_endorsements)) {
//transform data to send
//get applicable slab rate for current member relation
$pre_rack_rate_name = '';
$applicable_rack_rate_name = '';
$applicable_rack_rate_master = [];
- foreach ($slab_details['slab_rates'] as $skey => $slab_value)
- {
- if($pre_rack_rate_name != $slab_value['rack_rate_name'])
- {
+ foreach ($slab_details['slab_rates'] as $skey => $slab_value) {
+ if ($pre_rack_rate_name != $slab_value['rack_rate_name']) {
$pre_rack_rate_name = $slab_value['rack_rate_name'];
$rack_rate_json = json_decode($slab_value['additional_relationship'], true);
$relationship_array_key = strtolower(trim($employee['relationship']));
@@ -1624,51 +1761,46 @@ class EmployeeServiceController extends AdminController
$relationship_array_key = 'parents-in-law';
}
- if(array_key_exists($relationship_array_key, $rack_rate_json) && $rack_rate_json[$relationship_array_key] != 0 && $rack_rate_json[$relationship_array_key] != 'NA')
- {
+ if (array_key_exists($relationship_array_key, $rack_rate_json) && $rack_rate_json[$relationship_array_key] != 0 && $rack_rate_json[$relationship_array_key] != 'NA') {
$applicable_rack_rate_name = $slab_value['rack_rate_name'];
$applicable_rack_rate_master = $slab_value['grid_master'];
break;
}
}
}
-
+
//get max age,max count of the familiy
$max_age_and_max_count_of_current_member = $this->employeeModel->getFamiliyCountAndMaxage($employee['emp_code']);
//transform SI excel row data as inception excel OR premium calculateable fomart
- $data = transform_si_excel_row_to_calculatable_format(employee: $employee,employee_policy: $employee_policy,maxage_and_maxcount: $max_age_and_max_count_of_current_member,slab_details: $slab_details,applicable_slab_name: $applicable_rack_rate_name,augmented_si: $row[3],grid_master: $applicable_rack_rate_master);
- $policy_terms = $this->clientPolicyModel->getPolicyDetails($file['client_id'],$file['policy_id']);
+ $data = transform_si_excel_row_to_calculatable_format(employee: $employee, employee_policy: $employee_policy, maxage_and_maxcount: $max_age_and_max_count_of_current_member, slab_details: $slab_details, applicable_slab_name: $applicable_rack_rate_name, augmented_si: $row[3], grid_master: $applicable_rack_rate_master);
+ $policy_terms = $this->clientPolicyModel->getPolicyDetails($file['client_id'], $file['policy_id']);
$policy_terms = (array) $policy_terms[0];
// dd($policy_terms);
//grouping slab details by rack rate name
$temp_slab_rates = group_slab_rates_basedon_name($slab_details);
- $calculated_data = premium_calculation_manager($data,$policy_terms,$temp_slab_rates,$row[3]);
+ $calculated_data = premium_calculation_manager($data, $policy_terms, $temp_slab_rates, $row[3]);
- $group_key = rand(100000, 999999);
- $this->empEndorsementModel->save(['pk' => (int)$employee_policy['id'],'emp_code' => $employee['emp_code'],'table_name' => 'employee_polices','actions' => 'si','name' => $employee['name'],'field_name' => 'basic_cover_si','old_value' => $employee_policy['basic_cover_si'],'new_value' => $row[3],'created_by' => $file['created_by'],'remarks' => 'general si enhancement','group_key' => $group_key,'file_id' => $file['id'],'status' => 'pending']);
- $this->empEndorsementModel->save(['pk' => (int)$employee_policy['id'],'emp_code' => $employee['emp_code'],'table_name' => 'employee_polices','actions' => 'si','name' => $employee['name'],'field_name' => 'premium','old_value' => $employee_policy['premium'],'new_value' => $calculated_data['policy_details']['premium'],'created_by' => $file['created_by'],'remarks' => 'general si enhancement','group_key' => $group_key,'file_id' => $file['id'],'status' => 'pending']);
- $this->empEndorsementModel->save(['pk' => (int)$employee_policy['id'],'emp_code' => $employee['emp_code'],'table_name' => 'employee_polices','actions' => 'si','name' => $employee['name'],'field_name' => 'si_enhancement_date','old_value' => null,'new_value' => change_date_format($row[4],'d-M-Y','Y-m-d'),'created_by' => $file['created_by'],'remarks' => 'general si enhancement','group_key' => $group_key,'file_id' => $file['id'],'status' => 'pending']);
-
-
+ $group_key = rand(100000, 999999);
+ $this->empEndorsementModel->save(['pk' => (int)$employee_policy['id'], 'emp_code' => $employee['emp_code'], 'table_name' => 'employee_polices', 'actions' => 'si', 'name' => $employee['name'], 'field_name' => 'basic_cover_si', 'old_value' => $employee_policy['basic_cover_si'], 'new_value' => $row[3], 'created_by' => $file['created_by'], 'remarks' => 'general si enhancement', 'group_key' => $group_key, 'file_id' => $file['id'], 'status' => 'pending']);
+ $this->empEndorsementModel->save(['pk' => (int)$employee_policy['id'], 'emp_code' => $employee['emp_code'], 'table_name' => 'employee_polices', 'actions' => 'si', 'name' => $employee['name'], 'field_name' => 'premium', 'old_value' => $employee_policy['premium'], 'new_value' => $calculated_data['policy_details']['premium'], 'created_by' => $file['created_by'], 'remarks' => 'general si enhancement', 'group_key' => $group_key, 'file_id' => $file['id'], 'status' => 'pending']);
+ $this->empEndorsementModel->save(['pk' => (int)$employee_policy['id'], 'emp_code' => $employee['emp_code'], 'table_name' => 'employee_polices', 'actions' => 'si', 'name' => $employee['name'], 'field_name' => 'si_enhancement_date', 'old_value' => null, 'new_value' => change_date_format($row[4], 'd-M-Y', 'Y-m-d'), 'created_by' => $file['created_by'], 'remarks' => 'general si enhancement', 'group_key' => $group_key, 'file_id' => $file['id'], 'status' => 'pending']);
+ } else {
+ $this->myLogger->logme("error", 'Endorsement already exists for this employee ' . json_encode(['file_id' => $file_id, 'emp_code' => $employee['emp_code'], 'emp_name' => $employee['name']]));
}
-
-
-
-
}
- $this->fileModel->where('id', $file_id)->set(['status' => 'success','reason' => ''])->update();
- $this->myLogger->logme("error",'{file_id} uploaded success',['file_id' => $file_id]);
+ $this->fileModel->where('id', $file_id)->set(['status' => 'success', 'reason' => ''])->update();
+ $this->myLogger->logme("error", '{file_id} uploaded success', ['file_id' => $file_id]);
+
//set success msg to pull notifications
- $this->setPullNotification($this->getFileMetaDataByFileId($file_id,'success'));
- return true;
+ $this->setPullNotification($this->getFileMetaDataByFileId($file_id, 'success'));
+ return true;
}
-
// insert or update in db for inception addition depent addition
- public function employeesOnboardProcess($params)
+ public function employeesOnboardProcess($params)
{
// dd($params);
@@ -1683,7 +1815,7 @@ class EmployeeServiceController extends AdminController
if(is_array($value))
{
-
+ if (isset($value['gender'])) { $value['gender'] = normalizeGender($value['gender'] );}
if($file['id'] == null || $value['temp']['source'] == 'excel' || (($file['action'] == 'dependent_addition' && ($value['temp']['premium_type'] == 1 && strtolower($value['relationship']) == 'self') || ($value['temp']['premium_type'] == 2 || $value['temp']['premium_type'] == null)))) //insert data come from excel and from db i.e. ( $file['id'] == null for enrollment data)
{
@@ -1723,7 +1855,7 @@ class EmployeeServiceController extends AdminController
$value['updated_by'] = $file['created_by'];
$value['id'] = $employee[0]['id'];
$value['emp_status'] = 'active';
- $value['family_floater_key'] = generate_family_floater_key($value['relationship']);
+ $value['family_floater_key'] = generate_family_floater_key($value['relationship']);
$value['client_branch_id'] = $file['client_branch_id'];
$value['file_id'] = isset($employee[0]['file_id']) && $employee[0]['file_id'] != '' ? $employee[0]['file_id'] : $file['id'] ;
$log_message = 'Update Employee - '.$employee[0]['name'].'('.$employee[0]['emp_code'].') with PK '.$employee[0]['id'];
@@ -1872,127 +2004,125 @@ class EmployeeServiceController extends AdminController
}
-// ---------------------------------------------------------------------------------
+ // ---------------------------------------------------------------------------------
- public function getExcelErrorData($file_id){
+ public function getExcelErrorData($file_id)
+ {
- try {
- $file = $this->fileModel->find($file_id);
- $error_data = json_decode($file['reason']);
- // dd($error_data);
- // return $error_data;
+ try {
+ $file = $this->fileModel->find($file_id);
+ $error_data = json_decode($file['reason']);
+ // dd($error_data);
+ // return $error_data;
- $file_name_with_path = WRITEPATH."/uploads/excel/".$file['file_name'];
+ $file_name_with_path = WRITEPATH."/uploads/excel/".$file['file_name'];
- //check the file exist or not
- if(!file_exists($file_name_with_path))
- {
- $error_message = "File not found";
- $this->myLogger->logme('error',($error_message . ' for file id ' . $file_id));
- return 0;
- }
-
- $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file_name_with_path);
- $sheet = $spreadsheet->getActiveSheet();
-
- $highestRowAndColumn = $sheet->getHighestRowAndColumn();
- $excel_data = $sheet->rangeToArray('A1:' . $highestRowAndColumn['column'] . $highestRowAndColumn['row']);
- $excelErrorData['excel_header'] = $excel_data[0];
- unset($excel_data[0]);
- // echo '';
- // Kint::dump($excel_data);
- if($error_data->error_type == 1){
-
- $finalArray = [];
- foreach ($error_data->error_data as $key => $value) {
-
- foreach ($value as $key2 => $value2) {
- $error_data = $value2->error;
- $data = ['value' => $excel_data[$key][$value2->col_idx], 'error'=>$error_data,];
- $excel_data[$key][$value2->col_idx] = $data;
-
- }
- array_push($finalArray, $excel_data[$key]);
+ //check the file exist or not
+ if(!file_exists($file_name_with_path))
+ {
+ $error_message = "File not found";
+ $this->myLogger->logme('error',($error_message . ' for file id ' . $file_id));
+ return 0;
}
-
- foreach ($finalArray as $fkey => $value){
- foreach ($value as $vkey => $arrayData){
- if(!is_array($arrayData)){
- $data = ['value' => $arrayData];
- $finalArray[$fkey][$vkey] = $data;
+
+ $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file_name_with_path);
+ $sheet = $spreadsheet->getActiveSheet();
+
+ $highestRowAndColumn = $sheet->getHighestRowAndColumn();
+ $excel_data = $sheet->rangeToArray('A1:' . $highestRowAndColumn['column'] . $highestRowAndColumn['row']);
+ $excelErrorData['excel_header'] = $excel_data[0];
+ unset($excel_data[0]);
+ // echo '';
+ // Kint::dump($excel_data);
+ if($error_data->error_type == 1){
+
+ $finalArray = [];
+ foreach ($error_data->error_data as $key => $value) {
+
+ foreach ($value as $key2 => $value2) {
+ $error_data = $value2->error;
+ $data = ['value' => $excel_data[$key][$value2->col_idx], 'error'=>$error_data,];
+ $excel_data[$key][$value2->col_idx] = $data;
+
+ }
+ array_push($finalArray, $excel_data[$key]);
+ }
+
+ foreach ($finalArray as $fkey => $value){
+ foreach ($value as $vkey => $arrayData){
+ if(!is_array($arrayData)){
+ $data = ['value' => $arrayData];
+ $finalArray[$fkey][$vkey] = $data;
+ }
}
}
- }
-
- $excelErrorData['excel_data'] = $finalArray;
- return $excelErrorData;
+
+ $excelErrorData['excel_data'] = $finalArray;
+ return $excelErrorData;
- }else if($error_data->error_type == 2){
+ }else if($error_data->error_type == 2){
- $allErrors = [];
- $typeTowArray = [];
+ $allErrors = [];
+ $typeTowArray = [];
- foreach ($error_data->error_data as $index => $item) {
+ foreach ($error_data->error_data as $index => $item) {
- foreach ($item as $field) {
- if (!isset($allErrors[$index])) {
- $allErrors[$index] = [];
+ foreach ($item as $field) {
+ if (!isset($allErrors[$index])) {
+ $allErrors[$index] = [];
+ }
+ $allErrors[$index] = array_merge($allErrors[$index], $field->error);
}
- $allErrors[$index] = array_merge($allErrors[$index], $field->error);
}
- }
- // dd(array_keys($allErrors));
- foreach ($allErrors as $key => $value){
- // echo $key;
- // print_r($value);
- foreach($excel_data as $excel_data_index => $excel_data_value)
- {
- if($excel_data_value[0] == $key)
+ // dd(array_keys($allErrors));
+ foreach ($allErrors as $key => $value){
+ // echo $key;
+ // print_r($value);
+ foreach($excel_data as $excel_data_index => $excel_data_value)
{
- $data = ['value' => $excel_data[$excel_data_index][1], 'error'=>$value,];
- $excel_data[$excel_data_index][1] = $data;
- array_push($typeTowArray, $excel_data[$excel_data_index]);
- break;
+ if($excel_data_value[0] == $key)
+ {
+ $data = ['value' => $excel_data[$excel_data_index][1], 'error'=>$value,];
+ $excel_data[$excel_data_index][1] = $data;
+ array_push($typeTowArray, $excel_data[$excel_data_index]);
+ break;
+ }
}
- }
-
- }
- // dd($data);
- foreach ($typeTowArray as $fkey => $value){
- foreach ($value as $vkey => $arrayData){
- if(!is_array($arrayData)){
- $data = ['value' => $arrayData];
- $typeTowArray[$fkey][$vkey] = $data;
+
+ }
+ // dd($data);
+ foreach ($typeTowArray as $fkey => $value){
+ foreach ($value as $vkey => $arrayData){
+ if(!is_array($arrayData)){
+ $data = ['value' => $arrayData];
+ $typeTowArray[$fkey][$vkey] = $data;
+ }
}
}
+
+ $excelErrorData['excel_data'] = $typeTowArray;
+ return $excelErrorData;
+
}
- $excelErrorData['excel_data'] = $typeTowArray;
- return $excelErrorData;
+ }catch (\Exception $e) {
+ // Handle any exceptions
+ $errorMessage = $e->getMessage();//die();
+ $this->myLogger->logme('error', $errorMessage);
+ return false; // You can return an error response here
+ }
+ }
- }
+ // ---------------------------------------------------------------------------------
- }catch (\Exception $e) {
- // Handle any exceptions
- $errorMessage = $e->getMessage();//die();
- $this->myLogger->logme('error', $errorMessage);
- return false; // You can return an error response here
- }
+ public function getFileMetaDataByFileId($file_id, $status = 'success')
+ {
-
-
- }
-
-
-// ---------------------------------------------------------------------------------
-
-public function getFileMetaDataByFileId($file_id, $status = 'success'){
-
- $data = $this->fileModel
+ $data = $this->fileModel
->select('files.*, clients.client_name, clients.short_name, policy_type.policy_type as policy_name,client_branch.branch_code')
->join('clients', 'clients.id = files.client_id')
->join('client_policy', 'client_policy.id = files.policy_id')
@@ -2016,11 +2146,9 @@ public function getFileMetaDataByFileId($file_id, $status = 'success'){
return ['msg_txt' => $msg_txt, 'user_id' => $user_id, 'url' => $url, 'status' => $status, 'title' => $msg_title];
}
-
-
- public function setPullNotification($data){
-
-
+
+ public function setPullNotification($data)
+ {
$array = ['message_text' => $data['msg_txt'], 'action_url' => $data['url'], 'msg_status' => $data['status'], 'msg_title' => $data['title']];
$jsonEncodeData = json_encode($array);
@@ -2031,17 +2159,14 @@ public function getFileMetaDataByFileId($file_id, $status = 'success'){
'role_id' => NULL,
'team_id' => NULL,
'message_type' => '1to1',
- ];
+ ];
-
- $this->messageModel->insert($msg_data);
-
-
-}
+ $this->messageModel->insert($msg_data);
+ }
public function employeesEnrollmentInsert($params)
{
- // dd($this->request);
+ // dd($this->request);
helper('excel_util_helper');
//get file name
$file_id = $params['file_id'];
@@ -2059,10 +2184,10 @@ public function getFileMetaDataByFileId($file_id, $status = 'success'){
if(!file_exists($file_name_with_path))
{
//file not found update status and reason
- $message = "Physical file not found";
+ $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();
+ $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);
}
@@ -2077,7 +2202,8 @@ public function getFileMetaDataByFileId($file_id, $status = 'success'){
$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
+
+ //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]);
@@ -2109,11 +2235,11 @@ public function getFileMetaDataByFileId($file_id, $status = 'success'){
{
$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['gender'] = normalizeGender($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];
@@ -2149,10 +2275,10 @@ public function getFileMetaDataByFileId($file_id, $status = 'success'){
$policy_data['date_coverage'] = $row[13] != "" && $row[13] != null ? change_date_format($row[13],'d-M-Y','Y-m-d') : null;
$policy_data['client_policy_id'] = $file['policy_id'];
- $employee = $this->employeeModel->checkExistingEmployee($value,$file['client_branch_id']);
- unset($value['temp']);
+ $employee = $this->employeeModel->checkExistingEmployee($value,$file['client_branch_id']);
+ unset($value['temp']);
//save employee table
- // dd($employee['id']);
+ // dd($employee['id']);
if($employee !== null)
{
$value['updated_by'] = $file['created_by'];
@@ -2170,11 +2296,11 @@ public function getFileMetaDataByFileId($file_id, $status = 'success'){
$value = ExcelSanitizeHelper::sanitizeArrayData($value);
$this->employeeModel->save($value);
- if (isset($value['id']))
- { $emp_id = $value['id']; }
- else { $emp_id = $this->employeeModel->getInsertID();
+ 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; }
@@ -2232,8 +2358,8 @@ public function getFileMetaDataByFileId($file_id, $status = 'success'){
'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);
+ //store email and mail content via helper to send notification
+ $emp_emails[] = sendMailNotification::sendMailNotification('member_welcome_mail', $params);
}
}
}// endof if row is empty check
@@ -2241,7 +2367,7 @@ public function getFileMetaDataByFileId($file_id, $status = 'success'){
// dd($emp_emails);
- // for bulk mail queue job push
+ // for bulk mail queue job push
if (!empty($emp_emails) && count($emp_emails) > 0) {
$emp_emails = array_chunk($emp_emails, 20);
@@ -2259,6 +2385,142 @@ public function getFileMetaDataByFileId($file_id, $status = 'success'){
return true;
- }//end of employeesEnrollmentInsert
+ } //end of employeesEnrollmentInsert
+ // --------- MEMBER DATA AND INCEPTION DATA COMPARISION ------------------------------------------------------------------------
+
+ public function compareMemberDataAndInceptionData($params)
+ {
+ helper('excel_util_helper');
+
+ $file_id = $params['file_id'] ?? null;
+ if (empty($file_id)) {
+ return ['status' => false, 'msg' => 'File ID is missing'];
+ }
+
+ // ✅ Get File Data
+ $file = $this->fileModel->where(['is_active' => 1, 'id' => $file_id])->first();
+ if (empty($file)) {
+ return ['status' => false, 'msg' => 'File not found in DB'];
+ }
+
+ // ✅ Get Client Policy Data
+ $client_policy_data = $this->clientPolicyModel->where(['is_active' => 1, 'id' => $file['policy_id']])->first();
+ if (empty($client_policy_data)) {
+ return ['status' => false, 'msg' => 'Client policy data not found in DB (policy_id: ' . $file['policy_id'] . ')'];
+ }
+
+ // ✅ Get Lead Data
+ $leadModel = new LeadsModel();
+ $lead_data = $leadModel->where(['is_active' => 1, 'id' => $client_policy_data['is_from_lead']])->first();
+ if (empty($lead_data)) {
+ return ['status' => false, 'msg' => 'Lead data not found in DB (lead_id: ' . $client_policy_data['is_from_lead'] . ')'];
+ }
+
+ // ✅ Define File Paths
+ $inception_file_path = !empty($file['file_name']) ? WRITEPATH . "uploads/excel/" . $file['file_name'] : '';
+ $member_file_path = !empty($lead_data['file_name']) ? WRITEPATH . "uploads/lead_files/" . $lead_data['file_name'] : '';
+
+ // ✅ Check Inception File
+ if (empty($file['file_name']) || !file_exists($inception_file_path)) {
+ $message = empty($file['file_name']) ? "Inception file name is missing" : "Inception physical file not found";
+ $this->myLogger->logme('error', "$message for file id $file_id");
+ $this->fileModel->update($file_id, [
+ 'status' => 'failed',
+ 'reason' => json_encode(['error_summary' => [5], 'error_data' => $message])
+ ]);
+ return ['error_summary' => [5], 'error_data' => $message];
+ }
+
+ // ✅ Check Member File
+ if (empty($lead_data['file_name']) || !file_exists($member_file_path)) {
+ $message = empty($lead_data['file_name']) ? "Member file name is missing" : "Member data physical file not found";
+ $this->myLogger->logme('error', "$message for lead id {$lead_data['id']}");
+ $this->fileModel->update($file_id, [
+ 'status' => 'failed',
+ 'reason' => json_encode(['error_summary' => [5], 'error_data' => $message])
+ ]);
+ return ['error_summary' => [5], 'error_data' => $message];
+ }
+
+
+ // ✅ Read Inception Excel
+ $inception_columns = $this->inception_excel_columns;
+ $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($inception_file_path);
+ $sheet = $spreadsheet->getActiveSheet();
+ $highestRow = $sheet->getHighestDataRow();
+ $allowedColumn = end($inception_columns)['col_cell_name'];
+ $inception_data = $sheet->rangeToArray("A1:{$allowedColumn}{$highestRow}");
+ $inception_data = ExcelSanitizeHelper::sanitizeArrayData($inception_data);
+
+ // ✅ Read Member Excel
+ $member_columns = $this->member_data_excel_columns;
+ $spreadsheet2 = \PhpOffice\PhpSpreadsheet\IOFactory::load($member_file_path);
+ $sheet2 = $spreadsheet2->getSheet(0);
+ $highestRow2 = $sheet2->getHighestDataRow();
+ $allowedColumn2 = end($member_columns)['col_cell_name'];
+ $member_data = $sheet2->rangeToArray("A1:{$allowedColumn2}{$highestRow2}");
+ $member_data = ExcelSanitizeHelper::sanitizeArrayData($member_data);
+
+ // dd($inception_data, $member_data);
+
+ // ✅ Compare Inception Data with Member Data
+ $result = ['error_type' => 2, 'error_summary' => [], 'error_data' => []];
+
+ $inception_data_count = count($inception_data);
+ $member_data_count = count($member_data);
+
+ if ($inception_data_count !== $member_data_count) {
+ $result['error_summary'][] = 15;
+ $result['error_message'] = "
+ Inception Data Count:
+ {$inception_data_count}
+ Member Data Count:
+ {$member_data_count}";
+ }
+
+ foreach ($inception_data as $inception_key => $inception_row) {
+
+ // 🔹 If inception row is empty → stop all further processing
+ if (check_row_is_empty_or_null($inception_row)) {
+ break;
+ }
+
+ $match_found = false;
+
+ foreach ($member_data as $member_row) {
+ if (
+ $inception_row[1] == $member_row[1] && // emp_id / emp_code
+ $inception_row[2] == $member_row[2] && // name_of_emp_dep / name
+ $inception_row[5] == $member_row[3] && // relationship
+ normalizeGender($inception_row[4]) == normalizeGender($member_row[4]) && // gender
+ $inception_row[3] == $member_row[5] && // dob
+ $inception_row[13] == $member_row[7] && // email
+ $inception_row[12] == $member_row[8] // phone / mobile
+ ) {
+ $match_found = true;
+ break;
+ }
+ }
+
+ if (!$match_found) {
+ array_push($result['error_summary'], 14);
+ $result['error_data'][$inception_key]['sno']['error'][] = "This inception row was not found in the member data list.";
+ }
+ }
+
+ // ✅ Handle Result
+ if (!empty($result['error_summary'])) {
+ $result['error_summary'] = array_count_values($result['error_summary']);
+ $this->fileModel->update($file_id, [
+ 'status' => 'failed',
+ 'reason' => json_encode($result)
+ ]);
+ $this->myLogger->logme('error', "File ID $file_id comparison failed");
+ } else {
+ Jobs::addJob(['job_name' => 'excelFileDataValidation', 'payload' => ['file_id' => $file_id]]);
+ }
+
+ return $result;
+ }
}
\ No newline at end of file
diff --git a/app/Controllers/Home.php b/app/Controllers/Home.php
index 68eb0402..4af7ddfa 100755
--- a/app/Controllers/Home.php
+++ b/app/Controllers/Home.php
@@ -60,6 +60,8 @@ class Home extends PublicController
//print_rr($data);
}
+
+ //for insurer statement upload
public function check_gemini_2()
{
@@ -203,6 +205,189 @@ class Home extends PublicController
}
+
+ //for insurer policy doc upload
+ public function checkPolicyDoc()
+ {
+
+ try
+ { // $this->convertToPdf();die();
+ // Replace with your actual Gemini API key
+ $apiKey = getenv('GEMINI_API_KEY');
+ // The model to use and the API endpoint
+ $model = "gemini-pro";
+ $model = getenv('GEMINI_MODEL');
+ // $model = "gemini-1.5-pro";
+ // $model = "gemini-1.5-pro";
+ $url = "https://generativelanguage.googleapis.com/v1beta/models/{$model}:generateContent?key={$apiKey}";
+
+ $filePath = 'C:\Users\Venba\AppData\Local\Programs\Python\pyenv\pdfreader\bike-0904023124P114268957.pdf';
+ $filePath = 'C:\Users\Venba\AppData\Local\Programs\Python\pyenv\pdfreader\car-insurance-0904023124P114213011.pdf';
+
+ // Check if the file exists
+ if (!file_exists($filePath)) {
+ die("Error: File not found at {$filePath}");
+ }
+
+ // Get the file's MIME type using the finfo extension
+ $finfo = finfo_open(FILEINFO_MIME_TYPE);
+ $mimeType = finfo_file($finfo, $filePath);
+ finfo_close($finfo);
+ print_r($mimeType);die();
+ // Define supported inline MIME types
+ $supportedInlineMimeTypes = ['application/pdf','text/csv'];
+
+ // Read the file content and encode it to Base64
+ $fileContent = file_get_contents($filePath);
+ $base64Content = base64_encode($fileContent);
+ // The prompt you want to send to the model
+ // $prompt = "give me a json with emp data like name,age,dob,mobile and email. only json not any explanations";
+ $prompt = "Read the following motor policy pdf document and convert into JSON format as sample specified. Give me only JSON,not any explanations.while pick up premium break up give own damage, third party ,personal accident and taxes as mentioned in JSON format.Notes:vehicle_type should be like Two Wheeler,Four Feeler,Good Vehicle,Bus, Tractor,Commercial Vehicle.rto_state_code is first two char of reg_no and rto_city_code 3rd & 4th char of reg_no and it should be two digit numeric code. Any date should be in mysql date format";
+ $prompt .= '"{\"policy\":{\"policy_number\":\"\",\"issue_date\":\"\",\"period\":{\"start\":\"\",\"end\":\"\"},\"insurer\":\"\",\"previous_policy_number\":\"\"},\"insured\":{\"name\":\"\",\"father_name\":\"\",\"address\":[\"\"],\"mobile\":\"\",\"id_proofs\":{\"aadhaar\":\"\",\"pan\":\"\"}},\"vehicle\":{\"reg_no\":\"\",\"rto_state_code\":\"\",\"rto_city_code\":\"\",\"weight\":\"\",\"fuel_type\":\"\",\"date_of_registration\":\"\",\"year_of_manufacture\":\"\",\"engine_no\":\"\",\"chassis_no\":\"\",\"make\":\"\",\"model\":\"\",\"year\":\"\",\"cubic_capacity\":\"\",\"vehicle_type\":\"\"},\"rto\":\"\",\"premium\":{\"tp\":0,\"od\":0,\"pa\":0,\"taxes\":{},\"total\":0,\"in_words\":\"\"},\"endorsements\":[{\"code\":\"\",\"desc\":\"\"}]}"';
+
+ $payloadPart = null;
+
+ // The text part of the prompt
+ $text_part = [
+ "text" => $prompt
+ ];
+ // Conditionally handle the file upload based on MIME type
+ if (in_array($mimeType, $supportedInlineMimeTypes)) {
+ // echo "Detected supported format inline MIME type ({$mimeType})";
+ // Handle PDF as inline data
+ $fileContent = file_get_contents($filePath);
+ $base64Content = base64_encode($fileContent);
+ $payloadPart = [
+ "inlineData" => [
+ "mimeType" => $mimeType,
+ "data" => $base64Content
+ ]
+ ];
+
+ $content_parts = [
+ "parts" => [
+ $text_part,
+ $payloadPart
+ ]
+ ];
+ } else {
+ // Handle Excel/CSV using the Files API
+ // echo "Detected unsupported inline MIME type ({$mimeType}). Uploading via Files API...\n";
+ $fileInfo = $this->uploadFileToGemini($filePath, $apiKey); // Pass apiKey
+
+ // print_r($fileInfo);
+ // The file part, using the URI from the Files API upload
+ $file_part = [
+ "fileData" => [
+ "fileUri" => $fileInfo['uri'],
+ "mimeType" => $fileInfo['mimeType']
+ ]
+ ];
+
+ // The full content array, containing both parts
+ $content_parts = [
+ "parts" => [
+ $text_part,
+ $file_part
+ ]
+ ];
+ }
+
+
+
+
+
+ // The final JSON payload
+ $data = [
+ "contents" => [
+ $content_parts
+ ]
+ ];
+
+ // Encode the data to a JSON string
+ $json_data = json_encode($data);
+
+ // Initialize cURL
+ $ch = curl_init($url);
+
+ // Set cURL options
+ curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); // Set the Content-Type header
+ curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data); // Set the JSON payload
+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return the response as a string
+ curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Optional: to bypass SSL verification if needed (not recommended for production)
+
+ // Execute the cURL request and get the response
+ $response = curl_exec($ch);
+
+ // Check for cURL errors
+ if (curl_errno($ch)) {
+ $curl_error = curl_error($ch);
+ throw new Exception("cURL Error: " . $curl_error);
+ }
+ $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
+
+ // Close the cURL handle
+ curl_close($ch);
+ $ch = null; // Mark handle as closed
+ // Check for non-successful HTTP status codes
+ if ($http_code < 200 || $http_code >= 300) {
+ throw new Exception("API returned non-successful HTTP status code: $http_code. Response: " . substr($response, 0, 200) . '...');
+ }
+
+ // Decode the JSON response
+ $responseData = json_decode($response, true, 512, JSON_THROW_ON_ERROR);
+ $text_path = $responseData['candidates'][0]['content']['parts'][0]['text'] ?? null;
+
+ if ($text_path) {
+ $generatedText = $text_path;
+ log_message('info', "Successfully received generated text.");
+
+ // 9. Attempt to extract and decode the exact JSON from the generated text
+ $json_string = '';
+
+ // Preferred: Regex to find content inside a JSON markdown block: ```json\n(.*?)\n```
+ $extracted_json_match = [];
+ if (preg_match('/```json\s*(.*?)\s*```/s', $generatedText, $extracted_json_match)) {
+ $json_string = trim($extracted_json_match[1]);
+ } else {
+ // Fallback: Find the first '{' and the last '}'
+ $start = strpos($generatedText, '{');
+ $end = strrpos($generatedText, '}');
+ if ($start !== false && $end !== false && $end > $start) {
+ $json_string = substr($generatedText, $start, $end - $start + 1);
+ }
+ }
+
+ if (empty($json_string)) {
+ throw new Exception("Could not extract a valid JSON string from the generated text.");
+ }
+
+ // Decode the extracted JSON string
+ $final_data = json_decode($json_string, true, 512, JSON_THROW_ON_ERROR);
+
+ log_message('info', "Extracted and decoded final JSON data successfully.");
+ echo '';
+ print_r($final_data);
+ // return $final_data;
+
+ } else {
+ // No generated text found, possibly a model safety block or API structure change
+ throw new Exception("Response structure invalid or no generated text candidate found.");
+ }
+
+ } catch (Exception $e) {
+ // Log the error
+ log_message('ERROR', "$request_id: Fatal Error: " . $e->getMessage());
+
+ // Ensure cURL handle is closed if an exception occurred after initialization but before closing
+ if ($ch !== null) {
+ curl_close($ch);
+ }
+ return null; // Return null on failure
+ }
+
+ }
+
// Function to upload a file to the Gemini Files API
diff --git a/app/Controllers/JobWorker.php b/app/Controllers/JobWorker.php
index 50c9820b..1dbf51b5 100755
--- a/app/Controllers/JobWorker.php
+++ b/app/Controllers/JobWorker.php
@@ -171,6 +171,10 @@ class JobWorker extends AdminController
'type' => 'CC', // Handler Category
'handler' => 'App\Controllers\LeadsController',
],
+ 'compareMemberDataAndInceptionData' => [
+ 'type' => 'CC', // Handler Category
+ 'handler' => 'App\Controllers\EmployeeServiceController',
+ ],
];
diff --git a/app/Controllers/LeadsController.php b/app/Controllers/LeadsController.php
index 59608e7e..92fa8a52 100644
--- a/app/Controllers/LeadsController.php
+++ b/app/Controllers/LeadsController.php
@@ -77,7 +77,7 @@ class LeadsController extends BaseController
protected $issuer;
protected $clientType;
protected $leadType;
- protected $leadsStatus;
+ public $leadsStatus;
protected $claim_type_for_gpa;
protected $cause_of_death;
protected $buisnessType;
@@ -344,10 +344,15 @@ class LeadsController extends BaseController
$where = [];
foreach ($search_data as $search_objects => $key) {
if ($key != null && $key != '' && $key != 0 && $search_objects != 'is_dashboard') {
- $where[$search_objects] = $key;
+ if($search_objects == 'status')
+ {
+ $where[('leads.'.$search_objects)] = $key;
+ }else{
+ $where[$search_objects] = $key;
+ }
}
}
-
+ // !dd($where);
$data['lead_data_list'] = $this->leadsModel->getLeadDataForLising($where);
$html = view('leads_list', $data);
@@ -665,7 +670,10 @@ class LeadsController extends BaseController
if ($value['lead_form_type'] == 1) {
//for this push the job to the calculateMembersDemography() function
$job_details = new Jobs();
- $r = Jobs::addJob(['job_name' => 'memberDataListExcelFileFormatValidation', 'payload' => [
+ // $r = Jobs::addJob(['job_name' => 'memberDataListExcelFileFormatValidation', 'payload' => [
+ // 'lead_id' => $insert,
+ // ]]);
+ $r = Jobs::addJob(['job_name' => 'calculateMembersDemography', 'payload' => [
'lead_id' => $insert,
]]);
}
@@ -773,7 +781,7 @@ class LeadsController extends BaseController
$multi_file_data = [];
foreach ($files as $index => $value) {
- $file_name = file_Upload($value, $uploadFilePath);
+ $file_name = file_Upload_for_lead($value, $uploadFilePath);
$multi_file_data[] = [
'file_name' => $file_name,
'docs_name' => $docs_names[$index],
@@ -809,7 +817,10 @@ class LeadsController extends BaseController
if (!empty($lead_form_type) && $lead_form_type == 1 && $key == 0) {
//for this push the job to the calculateMembersDemography() function
$job_details = new Jobs();
- $r = Jobs::addJob(['job_name' => 'memberDataListExcelFileFormatValidation', 'payload' => [
+ // $r = Jobs::addJob(['job_name' => 'memberDataListExcelFileFormatValidation', 'payload' => [
+ // 'lead_id' => $lead_id,
+ // ]]);
+ $r = Jobs::addJob(['job_name' => 'calculateMembersDemography', 'payload' => [
'lead_id' => $lead_id,
]]);
log_message('info', "calculateMembersDemography JOB PUSHED");
@@ -1024,14 +1035,7 @@ class LeadsController extends BaseController
// 3. Optimize lead data query with specific field selection
$lead_data = $this->leadsModel
->select('
- leads.id,
- leads.policy_type_id,
- leads.lead_type,
- leads.source_policy_id,
- leads.policy_end_date,
- leads.lead_form_type,
- leads.created_by,
- leads.client_name,
+ leads.*,
lead_files.status as demography_file_status,
policy_type.question_json,
policy_type.policy_type,
@@ -1090,6 +1094,7 @@ class LeadsController extends BaseController
// 7. Define mail templates as constants or config
$mail_content = $this->getMailTemplate();
+ $placement_mail_content = $this->getMailTemplate('placement');
$subject = $this->getSubjectTemplate($lead_data);
// 8. Pre-calculate sum assured only for GPA
@@ -1098,7 +1103,7 @@ class LeadsController extends BaseController
// 9. Transform mail content once
$data['mail_content'] = $this->transformMailContent($lead_data, $mail_content, $data['page_name']);
$data['subject'] = $this->transformMailContent($lead_data, $subject, $data['page_name']);
- $data['placement_mail_content'] = $this->transformMailContent($lead_data, $mail_content, 'Placement');
+ $data['placement_mail_content'] = $this->transformMailContent($lead_data, $placement_mail_content, 'Placement');
$data['placement_subject'] = $this->transformMailContent($lead_data, $subject, 'Placement');
// 10. Combine related queries
@@ -1151,24 +1156,43 @@ class LeadsController extends BaseController
}
// 13. Extract mail template to separate method for reusability
- private function getMailTemplate()
- {
- return '
- Dear Sir,
- Greetings From Nhance India!
- Please find attached the {{RFQ_OR_QCR}} for {{POLICY_TYPE}} policy pertaining to {{CLIENT_NAME}}.
- Kindly request you to share the competitive quotes at the earliest.
- In case of any query, please feel free to contact us.
- Thank You!
- Best regards,
+ private function getMailTemplate( $template_type = "" )
+ {
+ if($template_type == 'placement'){
+ return '
+ Dear Sir,
+ Greetings From Nhance India!
+ Please find attached the {{RFQ_OR_QCR}} for {{POLICY_TYPE}} policy pertaining to {{CLIENT_NAME}}.
+ Kindly request you to issue the policy at the earliest.
+ In case of any query, please feel free to contact us.
+ Thank You!
+ Best regards,
+
+
+ {{LOGGED_USER_NAME}}
+ Mobile: {{LOGGED_USER_MOBILE}}
+
-
- {{LOGGED_USER_NAME}}
- Mobile: {{LOGGED_USER_MOBILE}}
-
-
-
- ';
+
+ ';
+ }else{
+ return '
+ Dear Sir,
+ Greetings From Nhance India!
+ Please find attached the {{RFQ_OR_QCR}} for {{POLICY_TYPE}} policy pertaining to {{CLIENT_NAME}}.
+ Kindly request you to share the competitive quotes at the earliest.
+ In case of any query, please feel free to contact us.
+ Thank You!
+ Best regards,
+
+
+ {{LOGGED_USER_NAME}}
+ Mobile: {{LOGGED_USER_MOBILE}}
+
+
+
+ ';
+ }
}
// 14. Extract subject template to separate method
@@ -1776,6 +1800,24 @@ class LeadsController extends BaseController
// dd($rfq_data, $lead_id, $type, $propsal_and_insurer);
// print_r($propsal_and_insurer); die;
+ // print_r($is_placement); die;
+
+ $data = json_decode($rfq_data['json'], true);
+ $sheetName = 'Worksheet';
+ if ($type == 2) {
+ $sheetName = 'QCR';
+ // $propsal_and_insurer = "Proposal 1-ICICIPRU-ICICI001";
+ $data = $this->convertJsonForQCR($data, $type);
+ if ($propsal_and_insurer !== null) {
+ list($proposal_key, $insurer_key) = explode('-', $propsal_and_insurer, 2);
+ $data = $this->transformProposelData($data, $proposal_key, $insurer_key);
+ $is_placement = true;
+ $sheetName = 'Placement';
+ }
+ } else if ($type == 1) {
+ $sheetName = 'RFQ';
+ $data = $this->convertJsonForQCR($data, $type);
+ } // dd($data);
if ($rfq_data['lead_type'] == 1) {
@@ -1808,36 +1850,71 @@ class LeadsController extends BaseController
} else {
if (in_array($rfq_data['policy_type_id'], [2, 3, 4, 5])) {
- $lead_data = [
+ if($is_placement == true){
+ $lead_data = [
- 'Insured' => $rfq_data['client_name'],
- 'Policy Type' => $this->leadType[$rfq_data['lead_type']] ?? "",
+ 'Insured' => $rfq_data['client_name'],
+ 'Policy Type' => $this->leadType[$rfq_data['lead_type']] ?? "",
- // 'No of Employees at Inception' => $rfq_data['incept_emp_count'],
- // 'No of Dependents at Inception' => $rfq_data['incept_dept_count'],
- // 'Total Lives at Inception ' => $rfq_data['incept_no_of_lives'],
+ // '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 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'],
+ 'No of Employees at Renewal' => $rfq_data['renewal_emp_count'],
+ 'No of Dependents at Renewal' => $rfq_data['renewal_dept_count'],
+ 'Total Lives at Renewal ' => $rfq_data['renewal_no_of_lives'],
- 'Period of Insurance ' => !empty($rfq_data['policy_start_date']) && !empty($rfq_data['policy_end_date']) ? date('d-m-Y', strtotime($rfq_data['policy_start_date'])) . ' to ' . date('d-m-Y', strtotime($rfq_data['policy_end_date'])) : "To be decided",
- 'Insurer' => $rfq_data['insurer_name'] ?? " - ",
- 'TPA' => $rfq_data['tpa_name'] ?? " - ",
+ 'Period of Insurance ' => !empty($rfq_data['policy_start_date']) && !empty($rfq_data['policy_end_date']) ? date('d-m-Y', strtotime($rfq_data['policy_start_date'])) . ' to ' . date('d-m-Y', strtotime($rfq_data['policy_end_date'])) : "To be decided",
+ 'Insurer' => $rfq_data['insurer_name'] ?? " - ",
+ 'TPA' => $rfq_data['tpa_name'] ?? " - ",
- // 'Policy Run Days' => $rfq_data['policy_run_days'],
- // 'Inception Premium' => formatIndianCurrency($rfq_data['premium_at_inception']),
- // 'Premium as on (' . date('d-m-Y', strtotime($rfq_data['incurred_claims_date'])) . ')' => formatIndianCurrency($rfq_data['premium_date']),
- // 'Earned Premium' => formatIndianCurrency(intval($rfq_data['earned_premium'])),
- // 'Incurred Claims as on (' . date('d-m-Y', strtotime($rfq_data['incurred_claims_date'])) . ')' => formatIndianCurrency($rfq_data['incurred_claims']),
- // 'Annualised Claims' => formatIndianCurrency(intval($rfq_data['annualised_claims'])),
- // 'Incurred Claims Ratio' => $rfq_data['incurred_claims_ratio'] . " %",
- // 'Earned Claims Ratio' => $rfq_data['earned_claims_ratio'] . " %",
- ];
+ // 'Policy Run Days' => $rfq_data['policy_run_days'],
+ // 'Inception Premium' => formatIndianCurrency($rfq_data['premium_at_inception']),
+ // 'Premium as on (' . date('d-m-Y', strtotime($rfq_data['incurred_claims_date'])) . ')' => formatIndianCurrency($rfq_data['premium_date']),
+ // 'Earned Premium' => formatIndianCurrency(intval($rfq_data['earned_premium'])),
+ // 'Incurred Claims as on (' . date('d-m-Y', strtotime($rfq_data['incurred_claims_date'])) . ')' => formatIndianCurrency($rfq_data['incurred_claims']),
+ // 'Annualised Claims' => formatIndianCurrency(intval($rfq_data['annualised_claims'])),
+ // 'Incurred Claims Ratio' => $rfq_data['incurred_claims_ratio'] . " %",
+ // 'Earned Claims Ratio' => $rfq_data['earned_claims_ratio'] . " %",
+ ];
+ }else{
+ $lead_data = [
+ 'Insured' => $rfq_data['client_name'],
+ 'Policy Type' => $this->leadType[$rfq_data['lead_type']] ?? "",
+
+ 'No of Employees at Inception' => $is_placement ? '-' : $rfq_data['incept_emp_count'],
+ 'No of Dependents at Inception' => $is_placement ? '-' : $rfq_data['incept_dept_count'],
+ 'Total Lives at Inception ' => $is_placement ? '-' : $rfq_data['incept_no_of_lives'],
+
+ 'No of Employees at Expiry' => $is_placement ? '-' : $rfq_data['exp_emp_count'],
+ 'No of Dependents at Expiry' => $is_placement ? '-' : $rfq_data['exp_dept_count'],
+ 'Total Lives at Expiry ' => $is_placement ? '-' : $rfq_data['exp_no_of_lives'],
+
+ 'No of Employees at Renewal' => $rfq_data['renewal_emp_count'],
+ 'No of Dependents at Renewal' => $rfq_data['renewal_dept_count'],
+ 'Total Lives at Renewal ' => $rfq_data['renewal_no_of_lives'],
+
+ 'Period of Insurance ' => !empty($rfq_data['policy_start_date']) && !empty($rfq_data['policy_end_date'])
+ ? date('d-m-Y', strtotime($rfq_data['policy_start_date'])) . ' to ' . date('d-m-Y', strtotime($rfq_data['policy_end_date']))
+ : "To be decided",
+
+ 'Insurer' => $rfq_data['insurer_name'] ?? " - ",
+ 'TPA' => $rfq_data['tpa_name'] ?? " - ",
+
+ 'Policy Run Days' => $is_placement ? '-' : $rfq_data['policy_run_days'],
+ 'Inception Premium' => $is_placement ? '-' : formatIndianCurrency($rfq_data['premium_at_inception']),
+ 'Premium as on (' . date('d-m-Y', strtotime($rfq_data['incurred_claims_date'])) . ')' => $is_placement ? '-' : formatIndianCurrency($rfq_data['premium_date']),
+ 'Earned Premium' => $is_placement ? '-' : formatIndianCurrency(intval($rfq_data['earned_premium'])),
+ 'Incurred Claims as on (' . date('d-m-Y', strtotime($rfq_data['incurred_claims_date'])) . ')' => $is_placement ? '-' : formatIndianCurrency($rfq_data['incurred_claims']),
+ 'Annualised Claims' => $is_placement ? '-' : formatIndianCurrency(intval($rfq_data['annualised_claims'])),
+ 'Incurred Claims Ratio' => $is_placement ? '-' : $rfq_data['incurred_claims_ratio'] . " %",
+ 'Earned Claims Ratio' => $is_placement ? '-' : $rfq_data['earned_claims_ratio'] . " %",
+ ];
+ }
} else if (in_array($rfq_data['policy_type_id'], [1, 6, 7])) {
$lead_data = [
@@ -1857,27 +1934,8 @@ class LeadsController extends BaseController
];
}
}
+ // print_r($lead_data); die;
- $data = json_decode($rfq_data['json'], true);
- // dd($data);
-
- $sheetName = 'Worksheet';
- if ($type == 2) {
- $sheetName = 'QCR';
- // $propsal_and_insurer = "Proposal 1-ICICIPRU-ICICI001";
- $data = $this->convertJsonForQCR($data, $type);
- if ($propsal_and_insurer !== null) {
- list($proposal_key, $insurer_key) = explode('-', $propsal_and_insurer, 2);
- $data = $this->transformProposelData($data, $proposal_key, $insurer_key);
- $is_placement = true;
- $sheetName = 'Placement';
- }
- } else if ($type == 1) {
- $sheetName = 'RFQ';
- $data = $this->convertJsonForQCR($data, $type);
- // dd($data);
- }
- // dd($data);
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
@@ -3646,7 +3704,7 @@ class LeadsController extends BaseController
private function prepareClientData($data)
{
return [
- 'client_type' => $data['client_type'] ?? null,
+ 'client_type' => 1,
'entity_type_id' => $data['entity_type_id'] ?? null,
'client_code' => $data['client_code'] ?? null,
'client_name' => $data['client_name'] ?? null,
@@ -3696,6 +3754,8 @@ class LeadsController extends BaseController
'policy_start_date' => $data['policy_start_date'],
'policy_end_date' => $data['policy_end_date'],
'policy_status' => 1,
+ 'policy_entry_from' => 3,
+ 'is_from_lead' => $data['id'],
];
$policy_type_id = $data['policy_type_id'];
@@ -5239,10 +5299,10 @@ class LeadsController extends BaseController
'filePath' => $fullPath
];
} else {
- log_message('warning', 'File name is empty for ID: ' . $id);
+ log_message('error', 'File name is empty for ID: ' . $id);
}
} else {
- log_message('warning', 'File does not exist at path: ' . $fullPath);
+ log_message('error', 'File does not exist at path: ' . $fullPath);
}
} else {
log_message('warning', 'No active lead file found for ID: ' . $id . ' and lead_id: ' . $lead_id);
diff --git a/app/Controllers/MasterController.php b/app/Controllers/MasterController.php
index 013a9324..6191007c 100755
--- a/app/Controllers/MasterController.php
+++ b/app/Controllers/MasterController.php
@@ -33,8 +33,11 @@ use App\Models\ClientDepositModel;
use App\Models\EmployeePolicyModel;
use App\Models\FileModel;
use App\Models\InsurerExcelExportTemplateModel;
+use App\Models\NhanceBranchModel;
use App\Models\SettingsModel;
use App\Models\VehicleModel;
+use App\Models\VehicleTypeModel;
+use App\Models\RTOModel;
use CodeIgniter\CLI\CLI;
@@ -351,6 +354,15 @@ class MasterController extends AdminController
exit();
}
+ public function getInsurerBranchList()
+ {
+ $id = $this->request->getPost('insurer_id');
+
+ $insurer_branch_list = $this->insurerBranchModel->where(['insurer_id' => $id, 'is_active' => 1])->findAll()??[];
+
+ return $this->response->setJSON([ 'data' => $insurer_branch_list ])->setStatusCode(200);
+ }
+
public function editInsurerGeneralInfo()
{
$this->myLogger->logme('error','edit Insurer general info function called');
@@ -1347,6 +1359,16 @@ class MasterController extends AdminController
// === INSERT ===
if (empty($id)) {
+ $cd_acc_count = $this->CDMasterModel->where('is_active', 1)
+ ->where('client_id', $data['client_id'])
+ ->where('insurer_id', $data['insurer_id'])
+ ->where('insurer_branch_id', $data['insurer_branch_id'])
+ ->countAllResults();
+
+ if($cd_acc_count > 0){
+ return $this->respond(['status' => false, 'message' => 'A CD account has already been created for this client, insurer, and insurer branch combination.'], 200);
+ }
+
$this->myLogger->logme("error", 'Performing INSERT operation.');
$insert = $this->CDMasterModel->insert($data);
$this->myLogger->logme("error", 'Insert result: ' . json_encode($insert));
@@ -1571,6 +1593,15 @@ class MasterController extends AdminController
$data['insurer_branch_id'] = $insurer_branch_id;
+ $cd_acc_count = $this->CDMasterModel->where('is_active', 1)
+ ->where('client_id', $data['client_id'])
+ ->where('insurer_id', $data['insurer_id'])
+ ->where('insurer_branch_id', $data['insurer_branch_id'])
+ ->countAllResults();
+
+ if($cd_acc_count > 0){
+ return $this->respond(['status' => false, 'message' => 'A CD account has already been created for this client, insurer, and insurer branch combination.'], 200);
+ }
// array with data for CD Traction table
$cd_tranction_data = [
@@ -1614,11 +1645,30 @@ class MasterController extends AdminController
}
}
+ public function checkDuplicateCdAccount()
+ {
+ $data = $this->request->getGet();
+
+ $cd_acc_count = $this->CDMasterModel
+ ->where('is_active', 1)
+ ->where('client_id', $data['client_id'])
+ ->where('insurer_id', $data['insurer_id'])
+ ->where('insurer_branch_id', $data['insurer_branch_id'])
+ ->countAllResults();
+
+ if($cd_acc_count > 0){
+ return $this->respond(['status' => false, 'message' => 'A CD account has already been created for this client, insurer, and insurer branch combination.'], 200);
+ }else{
+ return $this->respond(['status' => true], 200);
+ }
+ }
+
//Vehicle Master data Function
public function VehicleMasterList()
- { $data['tab_name'] = 'Vehicle Master';
+ {
+ $data['tab_name'] = 'Vehicle Master';
$data['page_name'] = 'Vehicles';
$data['vehicle_type'] = [
'two_wheeler' => 'Two Wheeler',
@@ -2020,4 +2070,255 @@ class MasterController extends AdminController
dd($result);
}
+ //----------------------------------------------------------------------------------------------------------
+
+ public function nhanceBranchMaster()
+ {
+ $nhanceBranchModel = new NhanceBranchModel();
+ $method = $this->request->getMethod();
+ $data['tab_name'] = 'Nhance Branch';
+ $data['page_name'] = 'Nhance Branchs';
+
+ if ($method === 'post') {
+
+ $id = $this->request->getPost('pk') ?? null;
+ $data = $this->request->getPost();
+
+ if (empty($id)) {
+ $update_status = $nhanceBranchModel->insert($data);
+ } else {
+ $update_status = $nhanceBranchModel->where('id', $id)->set($data)->update();
+ }
+
+ if ($update_status) {
+ return $this->respond([
+ 'status' => true,
+ 'code' => 200,
+ 'message' => 'Nhance Branch Master updated successfully',
+ 'data' => $data
+ ], 200);
+ } else {
+ return $this->respond([
+ 'status' => false,
+ 'code' => 400,
+ 'message' => 'Failed to update',
+ 'data' => $data
+ ], 200);
+ }
+
+ } elseif ($method === 'get') {
+
+ $id = $this->request->getGet('pk') ?? null;
+
+ if (!empty($id)) {
+ $data = $nhanceBranchModel->where('is_active', 1)->where('id', $id)->findAll();
+ if (!empty($data)) {
+ return $this->respond(['status' => true, 'code' => 200, 'data' => $data], 200);
+ } else {
+ return $this->respond(['status' => false, 'code' => 400, 'message' => 'No data found'], 200);
+ }
+ }
+
+ $data = $nhanceBranchModel->where('is_active', 1)->orderBy('id', 'DESC')->findAll();
+ return $this->loadLayout('nhance_branch_list', ['data' => $data]);
+
+ } elseif ($method === 'delete') {
+
+ $input = $this->request->getRawInput();
+ $id = $input['pk'] ?? null;
+
+ if (empty($id)) {
+ return $this->respond([
+ 'status' => false,
+ 'code' => 404,
+ 'message' => 'No ID provided for deletion'
+ ], 200);
+ }
+
+ $update_status = $nhanceBranchModel->where('id', $id)->set(['is_active' => 0])->update();
+
+ if ($update_status) {
+ return $this->respond([
+ 'status' => true,
+ 'code' => 200,
+ 'message' => 'Data removed successfully',
+ 'pk' => $id
+ ], 200);
+ } else {
+ return $this->respond([
+ 'status' => false,
+ 'code' => 400,
+ 'message' => 'Failed to remove data',
+ 'pk' => $id
+ ], 200);
+ }
+ }
+ }
+
+
+ public function vehicleTypeMaster()
+ {
+ $vehicleTypeModel = new VehicleTypeModel();
+ $method = $this->request->getMethod();
+ $data['tab_name'] = 'Vehicle Type';
+ $data['page_name'] = 'Vehicle Types';
+ if ($method === 'post') {
+
+ $id = $this->request->getPost('pk') ?? null;
+ $data = $this->request->getPost();
+
+ if (empty($id)) {
+ $update_status = $vehicleTypeModel->insert($data);
+ } else {
+ $update_status = $vehicleTypeModel->where('id', $id)->set($data)->update();
+ }
+
+ if ($update_status) {
+ return $this->respond([
+ 'status' => true,
+ 'code' => 200,
+ 'message' => 'Vehicle Type Master updated successfully',
+ 'data' => $data
+ ], 200);
+ } else {
+ return $this->respond([
+ 'status' => false,
+ 'code' => 400,
+ 'message' => 'Failed to update',
+ 'data' => $data
+ ], 200);
+ }
+
+ } elseif ($method === 'get') {
+
+ $id = $this->request->getGet('pk') ?? null;
+
+ if (!empty($id)) {
+ $data = $vehicleTypeModel->where('is_active', 1)->where('id', $id)->findAll();
+ if (!empty($data)) {
+ return $this->respond(['status' => true, 'code' => 200, 'data' => $data], 200);
+ } else {
+ return $this->respond(['status' => false, 'code' => 400, 'message' => 'No data found'], 200);
+ }
+ }
+
+ $data = $vehicleTypeModel->where('is_active', 1)->orderBy('id', 'DESC')->findAll();
+ return $this->loadLayout('vehicle_type_master_list', ['data' => $data]);
+
+ } elseif ($method === 'delete') {
+
+ $input = $this->request->getRawInput();
+ $id = $input['pk'] ?? null;
+
+ if (empty($id)) {
+ return $this->respond([
+ 'status' => false,
+ 'code' => 404,
+ 'message' => 'No ID provided for deletion'
+ ], 200);
+ }
+
+ $update_status = $vehicleTypeModel->where('id', $id)->set(['is_active' => 0])->update();
+
+ if ($update_status) {
+ return $this->respond([
+ 'status' => true,
+ 'code' => 200,
+ 'message' => 'Data removed successfully',
+ 'pk' => $id
+ ], 200);
+ } else {
+ return $this->respond([
+ 'status' => false,
+ 'code' => 400,
+ 'message' => 'Failed to remove data',
+ 'pk' => $id
+ ], 200);
+ }
+ }
+ }
+
+ public function rtoMaster()
+ {
+ $rtoModel = new RTOModel();
+ $method = $this->request->getMethod();
+ $data['tab_name'] = 'RTO';
+ $data['page_name'] = 'RTO';
+
+ if ($method === 'post') {
+
+ $id = $this->request->getPost('pk') ?? null;
+ $data = $this->request->getPost();
+
+ if (empty($id)) {
+ $update_status = $rtoModel->insert($data);
+ } else {
+ $update_status = $rtoModel->where('id', $id)->set($data)->update();
+ }
+
+ if ($update_status) {
+ return $this->respond([
+ 'status' => true,
+ 'code' => 200,
+ 'message' => 'RTO Master updated successfully',
+ 'data' => $data
+ ], 200);
+ } else {
+ return $this->respond([
+ 'status' => false,
+ 'code' => 400,
+ 'message' => 'Failed to update',
+ 'data' => $data
+ ], 200);
+ }
+
+ } elseif ($method === 'get') {
+
+ $id = $this->request->getGet('pk') ?? null;
+
+ if (!empty($id)) {
+ $data = $rtoModel->where('is_active', 1)->where('id', $id)->findAll();
+ if (!empty($data)) {
+ return $this->respond(['status' => true, 'code' => 200, 'data' => $data], 200);
+ } else {
+ return $this->respond(['status' => false, 'code' => 400, 'message' => 'No data found'], 200);
+ }
+ }
+
+ $data = $rtoModel->where('is_active', 1)->orderBy('id', 'DESC')->findAll();
+ return $this->loadLayout('rto_master_list', ['data' => $data]);
+
+ } elseif ($method === 'delete') {
+
+ $input = $this->request->getRawInput();
+ $id = $input['pk'] ?? null;
+
+ if (empty($id)) {
+ return $this->respond([
+ 'status' => false,
+ 'code' => 404,
+ 'message' => 'No ID provided for deletion'
+ ], 200);
+ }
+
+ $update_status = $rtoModel->where('id', $id)->set(['is_active' => 0])->update();
+
+ if ($update_status) {
+ return $this->respond([
+ 'status' => true,
+ 'code' => 200,
+ 'message' => 'Data removed successfully',
+ 'pk' => $id
+ ], 200);
+ } else {
+ return $this->respond([
+ 'status' => false,
+ 'code' => 400,
+ 'message' => 'Failed to remove data',
+ 'pk' => $id
+ ], 200);
+ }
+ }
+ }
+
}
\ No newline at end of file
diff --git a/app/Controllers/NotificationController.php b/app/Controllers/NotificationController.php
index b497e958..64988466 100755
--- a/app/Controllers/NotificationController.php
+++ b/app/Controllers/NotificationController.php
@@ -3,6 +3,7 @@
// declare(strict_types=1);
namespace App\Controllers;
+use App\Models\CommonEMailModel;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\RequestInterface;
@@ -28,13 +29,16 @@ class NotificationController extends AdminController
protected $notificationModel;
protected $clientModel;
protected $MailAttachmentModel;
+
+ protected $CommonEMailModel;
public function __construct()
{
$this->myLogger = \Config\Services::mylogger();
$this->notificationModel = new NotificationModel();
$this->clientModel = new ClientModel();
- $this->MailAttachmentModel = new MailAttachmentModel();
+ $this->MailAttachmentModel = new MailAttachmentModel();
+ $this->CommonEMailModel = new CommonEMailModel();
}
// This is for Template Name Camel Case to Snake Case for store in DB
@@ -53,33 +57,80 @@ class NotificationController extends AdminController
$form_data['mail_content'] = $this->request->getPost('mailContent');
$form_data['client_id'] = $this->request->getPost('client_id');
$form_data['mail_content_json'] = $this->request->getPost('mailJson');
+ $form_data['email_list'] = $this->request->getPost('email_list');
$notificationModel = new NotificationModel();
$find_notification = $notificationModel->where('client_id',$form_data['client_id'])->where('template_name',$form_data['template_name'])->first();
if ($find_notification) {
- $id = $find_notification['id'];
+ $id = $find_notification['id'] ?? '';
$form_data['updated_by'] = get_session_userid();
$notificationModel->update($id,$form_data);
+ $this->save_common_mail($id , $form_data);
$complete = "Update";
}else{
$form_data['created_by'] = get_session_userid();
- $notificationModel->insert($form_data);
+ $id = $notificationModel->insert($form_data);
+ $this->save_common_mail($id , $form_data);
$complete = "Inserted";
}
return json_encode($complete);
-
+
}
+ private function save_common_mail($id, $form_data)
+ {
+
+ $this->logger->debug("step 1 - inside save common mail");
+
+ if (empty($form_data['email_list'])) {
+ return;
+ }
+
+
+ $this->logger->debug("step 2 - id and form_data are present");
+
+ $emails = array_map('trim', explode(',', $form_data['email_list']));
+
+
+ $this->logger->debug("step 3 common emails were present");
+
+ $common_mail_data = [];
+
+ foreach ($emails as $email) {
+ $common_mail_data[] = ['notification_id' => $id , 'email' => $email , 'is_active' => 1];
+ }
+
+ $this->logger->debug("step 4 common email data \n" . json_encode($common_mail_data));
+
+
+ // Deactivate existing emails
+ $this->CommonEMailModel
+ ->where('notification_id', $id)
+ ->set(['is_active' => 0])
+ ->update();
+
+ $this->logger->debug("step 5 deleted old common email data");
+
+
+
+ // Insert all at once
+ $this->CommonEMailModel->insertBatch($common_mail_data);
+
+ $this->logger->debug("step 6 common mail data insertion done ..!!");
+
+ }
+
// This is for the Enabls in Notification area and Update the Recipient and HR Mail Id in( Enables -> Notification table and Mail id's -> Client table)
public function update_enable()
{
$checkboxNames = [
'member_welcome_mail_btn',
+ 'common_mail_btn',
'member_reminder_mail_btn',
'member_ecard_mail_btn',
'member_review_and_summary_mail_btn',
diff --git a/app/Controllers/PolicyTransactionController.php b/app/Controllers/PolicyTransactionController.php
index db8be45b..6e721f81 100644
--- a/app/Controllers/PolicyTransactionController.php
+++ b/app/Controllers/PolicyTransactionController.php
@@ -1,1441 +1,894 @@
myLogger = \Config\Services::mylogger();
+ use ResponseTrait;
- $this->clientModel = new ClientModel();
- $this->clientBranchModel = new ClientBranchModel();
- $this->policyTypeModel = new PolicyTypeModel();
- $this->clientDepositModel = new ClientDepositModel();
- $this->clientPolicyModel = new ClientPolicyModel();
- $this->insurerBranchModel = new InsurerBranchModel();
- $this->insurerModel = new InsurerModel();
- $this->policyTransactionModel = new PolicyTransactionModel();
- $this->policyTransactionStatusModel = new PolicyTransactionStatusModel();
- $this->kycEntityTypeModel = new KYCEntityTypeModel();
- $this->clientKYCDocsModel = new ClientKYCDocsModel();
- $this->tpaBranchModel = new TPABranchModel();
- $this->tpaModel = new TPAModel();
- $this->PTFileModel = new PTFileModel();
- $this->PTCOShareDetailsModel = new PTCOShareDetailsModel();
- $this->employeeModel = new EmployeeModel();
- $this->userTeamsModel = new UserTeamsModel();
- $this->userModel = new UserModel();
- $this->employeePolicyModel = new EmployeePolicyModel();
- $this->insurerStatements = new InsurerStatements();
- $this->invPaymentDetailsModel = new InvPaymentDetailsModel();
- $this->batchFileModel = new BatchFileModel();
- $this->filesModel = new FileModel();
- $this->coShareStmtDetailsModel = new COShareStmtDetailsModel();
- $this->BdsPlacementModel = new BdsPlacementModel();
- $this->nhanceBranchModel = new NhanceBranchModel();
- $this->invoiceStatus = [
- 'pending' => 'Pending',
- 'generated' => 'Generated',
- 'sent' => 'Sent',
- 'payment_received' => 'Payment
Received',
- ];
- }
+ protected $myLogger;
+ protected $policyTransactionModel;
+ protected $policyTransactionStatusModel;
+ protected $clientModel;
+ protected $clientPolicyModel;
+ protected $clientBranchModel;
+ protected $clientDepositModel;
+ protected $policyTypeModel;
+ protected $insurerBranchModel;
+ protected $insurerModel;
+ protected $kycEntityTypeModel;
+ protected $clientKYCDocsModel;
+ protected $tpaBranchModel;
+ protected $tpaModel;
+ protected $PTFileModel;
+ protected $PTCOShareDetailsModel;
+ protected $employeeModel;
+ protected $userTeamsModel;
+ protected $userModel;
+ protected $employeePolicyModel;
+ protected $insurerStatements;
+ protected $invoiceStatus;
+ protected $invPaymentDetailsModel;
+ protected $batchFileModel;
+ protected $filesModel;
+ protected $coShareStmtDetailsModel;
+ protected $BdsPlacementModel;
+ protected $nhanceBranchModel;
- // Policy Transaction Inception
- public function viewInception()
- {
- $data['tab_name'] = 'Policy';
- $data['page_name'] = 'Policy';
+ public function __construct()
+ {
+ set_session_context('Policy Tranction');
+ $this->myLogger = \Config\Services::mylogger();
- // Static arrays for dropdowns
- $data['issuer'] = [1 => 'JIBS', 2 => 'Nhance'];
- $data['issuer_branch'] = $this->nhanceBranchModel->where('is_active', 1)->findAll();
- $data['client_type'] = [1 => 'Group', 2 => 'Individual'];
- $data['issuing_type'] = [1 => 'Fresh', 2 => 'Renewal', 3 => 'Roll Over'];
- $data['policy_status'] = [
- 'under_process' => 'Under Process',
- 'client_pending' => 'Client Pending',
- 'insurer_pending' => 'Insurer Pending',
- 'co_insurer_pending' => 'Co-Insurer Pending',
- 'tpa_pending' => 'TPA Pending',
- 'validated' => 'Validated',
- 'cancelled' => 'Cancelled',
- 'instalment_pending' => 'Instalment Pending',
- 'completed' => 'Completed',
- 'lost' => 'Lost',
- ];
- $data['invoice_status_array'] = [
- 'yet_to_generate' => 'Pending',
- 'generated' => 'Generated',
- 'send' => 'Sent',
- 'recived' => 'Payment Received',
- ];
- // $data['vehicle_type'] = [
- // 'two_wheeler' => 'Two Wheeler',
- // 'four_wheeler' => 'Four Wheeler',
- // 'truck' => 'Truck',
- // 'bus' => 'Bus',
- // 'van' => 'Van',
- // 'suv' => 'SUV',
- // 'motorcycle' => 'Motorcycle',
- // 'bicycle' => 'Bicycle'
- // ];
- $data['vehicle_type'] = db_connect()->table('vehicle_type')->where('is_active', 1)->get()->getResultArray();
- $data['vehicle_des'] = [
- 'commercial' => 'Commercial',
- 'private' => 'Private',
- ];
- $data['date_type'] = [
- 'policy_issue_date' => 'Policy Issue Date',
- 'policy_start_date' => 'Policy Start Date',
- 'policy_end_date' => 'Policy End Date',
- ];
-
- // Filter data
- $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');
- $status = $this->request->getGet('status');
-
- // Handle null or empty values
- $start_date = empty($start_date) ? 0 : $start_date;
- $end_date = empty($end_date) ? 0 : $end_date;
- $client_id = empty($client_id) ? 0 : $client_id;
- $insurer_id = empty($insurer_id) ? 0 : $insurer_id;
- $policy_type_id = empty($policy_type_id) ? 0 : $policy_type_id;
- $date_type = empty($date_type) ? 0 : $date_type;
- $issuer = empty($issuer) ? 0 : $issuer;
- $status = empty($status) ? 0 : $status; // Corrected from `$issuer`
-
- if ($this->request->is('get')) {
-
- // Fetch inception data list
- $data['inception_data_list'] = $this->policyTransactionModel->getInceptionTranctionListData(
- $start_date,
- $end_date,
- $client_id,
- $insurer_id,
- $policy_type_id,
- $date_type,
- $issuer,
- $status
- );
- } else {
-
- $ids = $this->request->getPost('ids');
- $ids = array_filter(explode(',', $ids));
- $data['inception_data_list'] = $this->policyTransactionModel->getInceptionTranctionListData(
- $start_date = 0,
- $end_date = 0,
- $client_id = 0,
- $insurer_id = 0,
- $policy_type_id = 0,
- $date_type = 0,
- $issuer = 0,
- $status = 0,
- $ids
- );
+ $this->clientModel = new ClientModel();
+ $this->clientBranchModel = new ClientBranchModel();
+ $this->policyTypeModel = new PolicyTypeModel();
+ $this->clientDepositModel = new ClientDepositModel();
+ $this->clientPolicyModel = new ClientPolicyModel();
+ $this->insurerBranchModel = new InsurerBranchModel();
+ $this->insurerModel = new InsurerModel();
+ $this->policyTransactionModel = new PolicyTransactionModel();
+ $this->policyTransactionStatusModel = new PolicyTransactionStatusModel();
+ $this->kycEntityTypeModel = new KYCEntityTypeModel();
+ $this->clientKYCDocsModel = new ClientKYCDocsModel();
+ $this->tpaBranchModel = new TPABranchModel();
+ $this->tpaModel = new TPAModel();
+ $this->PTFileModel = new PTFileModel();
+ $this->PTCOShareDetailsModel = new PTCOShareDetailsModel();
+ $this->employeeModel = new EmployeeModel();
+ $this->userTeamsModel = new UserTeamsModel();
+ $this->userModel = new UserModel();
+ $this->employeePolicyModel = new EmployeePolicyModel();
+ $this->insurerStatements = new InsurerStatements();
+ $this->invPaymentDetailsModel = new InvPaymentDetailsModel();
+ $this->batchFileModel = new BatchFileModel();
+ $this->filesModel = new FileModel();
+ $this->coShareStmtDetailsModel = new COShareStmtDetailsModel();
+ $this->BdsPlacementModel = new BdsPlacementModel();
+ $this->nhanceBranchModel = new NhanceBranchModel();
+ $this->invoiceStatus = [
+ 'pending' => 'Pending',
+ 'generated' => 'Generated',
+ 'sent' => 'Sent',
+ 'payment_received' => 'Payment
Received',
+ ];
}
+ // Policy Transaction Inception
+ public function viewInception()
+ {
+ $bds_edit_pt_id = $this->request->getGet('pt_id') ?? null;
+ $data['tab_name'] = 'Policy';
+ $data['page_name'] = 'Policy';
+
+ // Static arrays for dropdowns
+ $data['issuer'] = [1 => 'JIBS', 2 => 'Nhance'];
+ $data['issuer_branch'] = $this->nhanceBranchModel->where('is_active', 1)->findAll();
+ $data['client_type'] = [1 => 'Group', 2 => 'Individual'];
+ $data['issuing_type'] = [1 => 'Fresh', 2 => 'Renewal', 3 => 'Roll Over'];
+ $data['policy_status'] = [
+ 'under_process' => 'Under Process',
+ 'client_pending' => 'Client Pending',
+ 'insurer_pending' => 'Insurer Pending',
+ 'co_insurer_pending' => 'Co-Insurer Pending',
+ 'tpa_pending' => 'TPA Pending',
+ 'validated' => 'Validated',
+ 'cancelled' => 'Cancelled',
+ 'instalment_pending' => 'Instalment Pending',
+ 'completed' => 'Completed',
+ 'lost' => 'Lost',
+ ];
+ $data['invoice_status_array'] = [
+ 'yet_to_generate' => 'Pending',
+ 'generated' => 'Generated',
+ 'send' => 'Sent',
+ 'recived' => 'Payment Received',
+ ];
+ // $data['vehicle_type'] = [
+ // 'two_wheeler' => 'Two Wheeler',
+ // 'four_wheeler' => 'Four Wheeler',
+ // 'truck' => 'Truck',
+ // 'bus' => 'Bus',
+ // 'van' => 'Van',
+ // 'suv' => 'SUV',
+ // 'motorcycle' => 'Motorcycle',
+ // 'bicycle' => 'Bicycle'
+ // ];
+ $data['vehicle_type'] = db_connect()->table('vehicle_type')->where('is_active', 1)->get()->getResultArray();
+ $data['rto_details'] = db_connect()->table('rto_master')->where('is_active', 1)->get()->getResultArray();
+
+ $data['vehicle_des'] = [
+ 'commercial' => 'Commercial',
+ 'private' => 'Private',
+ ];
+ $data['date_type'] = [
+ 'policy_issue_date' => 'Policy Issue Date',
+ 'policy_start_date' => 'Policy Start Date',
+ 'policy_end_date' => 'Policy End Date',
+ ];
+
+ // Filter data
+ $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');
+ $status = $this->request->getGet('status');
+
+ // Handle null or empty values
+ $start_date = empty($start_date) ? 0 : $start_date;
+ $end_date = empty($end_date) ? 0 : $end_date;
+ $client_id = empty($client_id) ? 0 : $client_id;
+ $insurer_id = empty($insurer_id) ? 0 : $insurer_id;
+ $policy_type_id = empty($policy_type_id) ? 0 : $policy_type_id;
+ $date_type = empty($date_type) ? 0 : $date_type;
+ $issuer = empty($issuer) ? 0 : $issuer;
+ $status = empty($status) ? 0 : $status; // Corrected from `$issuer`
+
+ if(empty($bds_edit_pt_id)){
+ if ($this->request->is('get')) {
+
+ // Fetch inception data list
+ $data['inception_data_list'] = $this->policyTransactionModel->getInceptionTranctionListData(
+ $start_date,
+ $end_date,
+ $client_id,
+ $insurer_id,
+ $policy_type_id,
+ $date_type,
+ $issuer,
+ $status
+ );
+ } else {
+
+ $ids = $this->request->getPost('ids');
+ $ids = array_filter(explode(',', $ids));
+ $data['inception_data_list'] = $this->policyTransactionModel->getInceptionTranctionListData(
+ $start_date = 0,
+ $end_date = 0,
+ $client_id = 0,
+ $insurer_id = 0,
+ $policy_type_id = 0,
+ $date_type = 0,
+ $issuer = 0,
+ $status = 0,
+ $ids
+ );
+ }
+ }else{
+ $data['inception_data_list'] = [];
+ }
- // 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();
- $data['policy_types'] = $this->policyTypeModel->where('is_active', 1)->findAll();
- $data['insurer_branch'] = $this->insurerBranchModel->getInsurerBranchesWithInsurerNames();
- $data['tpa'] = $this->tpaBranchModel->getTpaBranchesWithTpaNames();
- // Fetch PP Teams Data
- $data['ppTeamsData'] = $this->userModel
- ->where('is_active', 1)
- ->findAll();
+ // 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();
+ $data['policy_types'] = $this->policyTypeModel->where('is_active', 1)->findAll();
+ $data['insurer_branch'] = $this->insurerBranchModel->getInsurerBranchesWithInsurerNames();
+ $data['tpa'] = $this->tpaBranchModel->getTpaBranchesWithTpaNames();
- // Fetch Sales Team
- $data['salse_team'] = $this->userModel
- ->select('user_profiles.*')
- ->join('user_teams', 'user_profiles.id = user_teams.user_id')
- ->where('user_teams.team_id', 5)
- ->where('user_teams.is_active', 1)
- ->where('user_profiles.is_active', 1)
- ->findAll();
+ // Fetch PP Teams Data
+ $data['ppTeamsData'] = $this->userModel
+ ->where('is_active', 1)
+ ->findAll();
- // Fetch ACM
- $data['ACM'] = $this->userModel
- ->where('role', 3) // Assuming `role` is in `user_profiles`
- ->where('is_active', 1)
- ->findAll();
- // echo '';
- // print_r($data['ppTeamsData']); die;
+ // Fetch Sales Team
+ $data['salse_team'] = $this->userModel
+ ->select('user_profiles.*')
+ ->join('user_teams', 'user_profiles.id = user_teams.user_id')
+ ->where('user_teams.team_id', 5)
+ ->where('user_teams.is_active', 1)
+ ->where('user_profiles.is_active', 1)
+ ->findAll();
- // dd($data);
+ // Fetch ACM
+ $data['ACM'] = $this->userModel
+ ->where('role', 3) // Assuming `role` is in `user_profiles`
+ ->where('is_active', 1)
+ ->findAll();
+ // echo '';
+ // print_r($data['ppTeamsData']); die;
- // Load view
- $this->loadLayout('policy_transaction_inception_list', $data);
- }
+ // dd($data);
- // policy Transaction Create function start
- public function createInceptionPolicy()
- {
- $post_data = $this->request->getPost() ?? [];
- $this->myLogger->logme('error', 'Policy Trancaction form data : '. json_encode($post_data));
-
- $id = $this->request->getPost('id');
- $data = $this->preparePolicyData();
- $data['cd_ac_pk'] = $this->request->getPost('cd_ac_no');
- $data['issuer'] = 2;
- $this->myLogger->logme('error', 'Policy Trancaction modified form data ( insert data ) : '. json_encode($data));
-
-
- if (!$id) {
- return $this->insertInceptionPolicy($data);
- } else {
- return $this->updateInceptionPolicy($id, $data);
- }
- }
-
- private function preparePolicyData()
- {
- $data = $this->request->getPost();
-
- // print_r($data); die;
- // var_dump($data); die;
-
- if (empty($data['policy_issue_date'])) {
- $data['policy_issue_date'] = null;
+ // Load view
+ $this->loadLayout('policy_transaction_inception_list', $data);
}
- if (empty($data['policy_start_date'])) {
- $data['policy_start_date'] = null;
- }
+ // policy Transaction Create function start
+ public function createInceptionPolicy()
+ {
+ $post_data = $this->request->getPost() ?? [];
+ $this->myLogger->logme('error', 'Policy Trancaction form data : '. json_encode($post_data));
- if (empty($data['policy_end_date'])) {
- $data['policy_end_date'] = null;
- }
-
- if (empty($data['renewal_date'])) {
- $data['renewal_date'] = null;
- }
-
- if (empty($data['rollover_date'])) {
- $data['rollover_date'] = null;
- }
-
- if (empty($data['last_action_date'])) {
- $data['last_action_date'] = null;
- } else {
- $data['last_action_date'] = change_date_format($data['last_action_date']);
- }
+ $id = $this->request->getPost('id');
+ $data = $this->preparePolicyData();
+ $data['cd_ac_pk'] = $this->request->getPost('cd_ac_no');
+ $data['issuer'] = 2;
+ $data['status'] = 'completed';
+ $this->myLogger->logme('error', 'Policy Trancaction modified form data ( insert data ) : '. json_encode($data));
- // Separate Insurer and TPA Branch IDs and IDs
- if (isset($data['insurer_id']) && !empty($data['insurer_id'])) {
- list($data['insurer_branch_id'], $data['insurer_id']) = explode('-', $data['insurer_id']);
- if (isset($data['tpa']) && !empty($data['tpa'])) {
- list($data['tpa_branch_id'], $data['tpa_id']) = explode('-', $data['tpa']);
+ if (!$id) {
+ return $this->insertInceptionPolicy($data);
+ } else {
+ return $this->updateInceptionPolicy($id, $data);
}
}
- $data['tsi'] = generate_tsi_code($data['issue_type']);
- $data['action_type'] = 'inception';
+ private function preparePolicyData()
+ {
+ $data = $this->request->getPost();
- if (!isset($data['co_share'])) {
- $data['co_share'] = 0;
- } elseif ($data['co_share']) {
- $data['co_share'] = 1;
- }
+ // print_r($data); die;
- if (!isset($data['bro_payable_by'])) {
- $data['bro_payable_by'] = 0;
- } elseif ($data['bro_payable_by']) {
- $data['bro_payable_by'] = 1;
- }
+ if (empty($data['policy_issue_date'])) {
+ $data['policy_issue_date'] = null;
+ }
- if (!isset($data['same_as_proposer'])) {
- $data['same_as_proposer'] = 0;
- } elseif ($data['same_as_proposer']) {
- $data['same_as_proposer'] = 1;
- }
+ if (empty($data['policy_start_date'])) {
+ $data['policy_start_date'] = null;
+ }
- if (!isset($data['policy_with_corr'])) {
- $data['policy_with_corr'] = 0;
- } elseif ($data['policy_with_corr']) {
- $data['policy_with_corr'] = 1;
- }
+ if (empty($data['policy_end_date'])) {
+ $data['policy_end_date'] = null;
+ }
- $data['is_cd_reduce_from_bds'] = ($data['policy_type_id'] > 7 && $data['client_type'] == 1) ? 1 : 0;
+ if (empty($data['renewal_date'])) {
+ $data['renewal_date'] = null;
+ }
+ if (empty($data['rollover_date'])) {
+ $data['rollover_date'] = null;
+ }
- if ($data['ct_type'] == "") {
- $data['ct_type'] = 1;
- }
+ if (empty($data['last_action_date'])) {
+ $data['last_action_date'] = null;
+ } else {
+ $data['last_action_date'] = change_date_format($data['last_action_date']);
+ }
- // $month = '01-'.(string)$this->request->getPost('month');
- // $data['month'] = empty($data['month']) ? null : date('Y-m-d', strtotime($month));
-
- // Determine $is_addon value
- $data['is_addon'] = in_array($data['policy_type_id'], [1, 2, 6, 7]) ? 1 : (in_array($data['policy_type_id'], [4, 5]) ? 2 : ($data['policy_type_id'] == 3 && isset($data['base_policy']) ? 3 : 1));
-
- // print_r($data); die;
-
- return $data;
- }
-
- private function insertInceptionPolicy($data)
- {
- // print_r($data); die;
-
- $insert = $this->policyTransactionModel->insert($data);
-
- if ($insert) {
-
- $this->insertTransactionStatus($insert, $data, 1);
- $emp_data = $this->processInsertIndividualMemberInEmpTable($data);
-
- if (isset($data['follow_insurer_id']) && !empty($data['follow_insurer_id'][0])) {
-
- $pt_co_share_details = $this->insertOrUpdateCoShareDetails($data, $insert);
-
- if ($data['ct_type'] == 2) {
- $client_policy_insert_data = $this->prepareClientPolicyInsertData($data);
- $client_policy_id = $this->clientPolicyModel->insert($client_policy_insert_data);
- $this->policyTransactionModel->update($insert, ['client_policy_id' => $client_policy_id]);
- $emp_policy_insert = $this->InsertIndividualEmpPolicyTable($emp_data, $client_policy_id);
- }
-
- if ($data['client_type'] == 1 && $data['status'] == 'completed' && $data['is_cd_reduce_from_bds'] == 1) {
- $this->processCompletedStatus($data, $client_policy_id, $data['insurer_id']);
+ // Separate Insurer and TPA Branch IDs and IDs
+ if (isset($data['insurer_id']) && !empty($data['insurer_id'])) {
+ list($data['insurer_branch_id'], $data['insurer_id']) = explode('-', $data['insurer_id']);
+ if (isset($data['tpa']) && !empty($data['tpa'])) {
+ list($data['tpa_branch_id'], $data['tpa_id']) = explode('-', $data['tpa']);
}
}
- $client_data = $this->clientModel->where('id', $data['client_id'])->first();
- $data['client_kyc'] = $this->clientKYCDocsModel->where('client_id', $data['client_id'])->findAll();
-
- $clientController = new ClientController();
- $data['client_kyc_primary_table'] = $clientController->generateKycPrimaryTable($data['client_id']);
- $data['client_kyc_other_table'] = $clientController->generateKycOthersTable($data['client_id']);
+ $data['tsi'] = generate_tsi_code($data['issue_type']);
+ $data['action_type'] = 'inception';
- $data['entity_type_id'] = $client_data['entity_type_id'];
+ if (!isset($data['co_share'])) {
+ $data['co_share'] = 0;
+ } elseif ($data['co_share']) {
+ $data['co_share'] = 1;
+ }
- return $this->respondSuccess($insert, "Policy transaction created successfully", $data);
+ if (!isset($data['bro_payable_by'])) {
+ $data['bro_payable_by'] = 0;
+ } elseif ($data['bro_payable_by']) {
+ $data['bro_payable_by'] = 1;
+ }
+
+ if (!isset($data['same_as_proposer'])) {
+ $data['same_as_proposer'] = 0;
+ } elseif ($data['same_as_proposer']) {
+ $data['same_as_proposer'] = 1;
+ }
+
+ if (!isset($data['policy_with_corr'])) {
+ $data['policy_with_corr'] = 0;
+ } elseif ($data['policy_with_corr']) {
+ $data['policy_with_corr'] = 1;
+ }
+
+ $data['is_cd_reduce_from_bds'] = ($data['policy_type_id'] > 7 && $data['client_type'] == 1) ? 1 : 0;
+
+
+ if ($data['ct_type'] == "") {
+ $data['ct_type'] = 1;
+ }
+
+ // $month = '01-'.(string)$this->request->getPost('month');
+ // $data['month'] = empty($data['month']) ? null : date('Y-m-d', strtotime($month));
+
+ // Determine $is_addon value
+ $data['is_addon'] = in_array($data['policy_type_id'], [1, 2, 6, 7]) ? 1 : (in_array($data['policy_type_id'], [4, 5]) ? 2 : ($data['policy_type_id'] == 3 && isset($data['base_policy']) ? 3 : 1));
+
+ // print_r($data); die;
+
+ return $data;
}
- return $this->respondError("Failed to create policy transaction");
- }
+ private function insertInceptionPolicy($data)
+ {
+ // print_r($data); die;
- private function updateInceptionPolicy($id, $data)
- {
- // print_r($data); die;
- $old_pt_data = $this->policyTransactionModel->where('is_active', 1)->where("id", $id)->first();
- $old_pt_co_share_data = $this->PTCOShareDetailsModel->where('is_active', 1)->where("id", $id)->first();
- if ($this->policyTransactionModel->update($id, $data)) {
+ $insert = $this->policyTransactionModel->insert($data);
- $this->insertTransactionStatus($id, $data, 1);
- $emp_data = $this->processInsertIndividualMemberInEmpTable($data);
+ if ($insert) {
- if (isset($data['follow_insurer_id']) && !empty($data['follow_insurer_id'][0])) {
+ $this->insertTransactionStatus($insert, $data, 1);
+ $emp_data = $this->processInsertIndividualMemberInEmpTable($data);
- $this->insertOrUpdateCoShareDetails($data, $id);
+ if (isset($data['follow_insurer_id']) && !empty($data['follow_insurer_id'][0])) {
- if ($data['ct_type'] == 1) {
- $this->policyTransactionModel->update($id, ['client_policy_id' => $data['client_policy_id']]);
- }
-
- if (empty($data['client_policy_id']) || $data['client_policy_id'] == 0) {
+ $pt_co_share_details = $this->insertOrUpdateCoShareDetails($data, $insert);
+ $client_policy_id = null;
if ($data['ct_type'] == 2) {
$client_policy_insert_data = $this->prepareClientPolicyInsertData($data);
$client_policy_id = $this->clientPolicyModel->insert($client_policy_insert_data);
- $this->policyTransactionModel->update($id, ['client_policy_id' => $client_policy_id]);
- $this->InsertIndividualEmpPolicyTable($emp_data, $client_policy_id);
+ $this->policyTransactionModel->update($insert, ['client_policy_id' => $client_policy_id]);
+ $emp_policy_insert = $this->InsertIndividualEmpPolicyTable($emp_data, $client_policy_id);
}
- } else {
- if (isset($data['emp_policy_id']) && !empty($data['emp_policy_id'][0])) {
- $this->InsertIndividualEmpPolicyTable($emp_data, $data['client_policy_id']);
+
+ if ($data['client_type'] == 1 && $data['status'] == 'completed' && $data['is_cd_reduce_from_bds'] == 1) {
+ $this->processCompletedStatus($data, $client_policy_id, $data['insurer_id'], $insert);
}
}
- if($old_pt_data['status'] != "completed"){
- if ($data['status'] == 'completed' && $data['ct_type'] == 2) {
- if ($data['client_type'] == 1 && $data['is_cd_reduce_from_bds'] == 1) {
- $this->processCompletedStatus($data, $data['client_policy_id'], $data['insurer_id']);
+ $client_data = $this->clientModel->where('id', $data['client_id'])->first();
+ $data['client_kyc'] = $this->clientKYCDocsModel->where('client_id', $data['client_id'])->findAll();
+
+ $clientController = new ClientController();
+ $data['client_kyc_primary_table'] = $clientController->generateKycPrimaryTable($data['client_id']);
+ $data['client_kyc_other_table'] = $clientController->generateKycOthersTable($data['client_id']);
+ $data['entity_type_id'] = $client_data['entity_type_id'];
+
+ return $this->respondSuccess($insert, "Policy transaction created successfully", $data);
+ }
+
+ return $this->respondError("Failed to create policy transaction");
+ }
+
+ private function updateInceptionPolicy($id, $data)
+ {
+ // print_r($data); die;
+ $old_pt_data = $this->policyTransactionModel->where('is_active', 1)->where("id", $id)->first();
+ $old_pt_co_share_data = $this->PTCOShareDetailsModel->where('is_active', 1)->where("id", $id)->first();
+ if ($this->policyTransactionModel->update($id, $data)) {
+
+ $this->insertTransactionStatus($id, $data, 1);
+ $emp_data = $this->processInsertIndividualMemberInEmpTable($data);
+
+ if (isset($data['follow_insurer_id']) && !empty($data['follow_insurer_id'][0])) {
+
+ $this->insertOrUpdateCoShareDetails($data, $id);
+
+ if ($data['ct_type'] == 1) {
+ $this->policyTransactionModel->update($id, ['client_policy_id' => $data['client_policy_id']]);
+ }
+
+ if (empty($data['client_policy_id']) || $data['client_policy_id'] == 0) {
+
+ if ($data['ct_type'] == 2) {
+ $client_policy_insert_data = $this->prepareClientPolicyInsertData($data);
+ $client_policy_id = $this->clientPolicyModel->insert($client_policy_insert_data);
+ $this->policyTransactionModel->update($id, ['client_policy_id' => $client_policy_id]);
+ $this->InsertIndividualEmpPolicyTable($emp_data, $client_policy_id);
+ }
+ } else {
+ if (isset($data['emp_policy_id']) && !empty($data['emp_policy_id'][0])) {
+ $this->InsertIndividualEmpPolicyTable($emp_data, $data['client_policy_id']);
}
}
+
+ // if($old_pt_data['status'] != "completed"){
+ // if ($data['status'] == 'completed' && $data['ct_type'] == 2) {
+ // if ($data['client_type'] == 1 && $data['is_cd_reduce_from_bds'] == 1) {
+ // $this->processCompletedStatus($data, $data['client_policy_id'], $data['insurer_id'], $id);
+ // }
+ // }
+ // }
+
+ $data['pt_co_share_details'] = $this->PTCOShareDetailsModel->where('pt_id', $id)->where('is_active', 1)->findAll();
}
- $data['pt_co_share_details'] = $this->PTCOShareDetailsModel->where('pt_id', $id)->where('is_active', 1)->findAll();
+ if(isset($data['cd_amt_changed']) && !empty($data['cd_amt_changed'])){
+ $policy_data = $this->policyTransactionModel->where('is_active', 1)->where('id', $id)->first();
+ $this->cdCorrection($policy_data, $data['cd_amt_changed'], $id);
+ }
+
+ $client_data = $this->clientModel->where('id', $data['client_id'])->first();
+ $data['client_kyc'] = $this->clientKYCDocsModel->where('client_id', $data['client_id'])->findAll();
+
+ $clientController = new ClientController();
+ $data['client_kyc_primary_table'] = $clientController->generateKycPrimaryTable($data['client_id']);
+ $data['client_kyc_other_table'] = $clientController->generateKycOthersTable($data['client_id']);
+
+ $data['entity_type_id'] = $client_data['entity_type_id'];
+
+ return $this->respondSuccess($id, "Policy transaction updated successfully", $data);
}
- if(isset($data['cd_amt_changed']) && !empty($data['cd_amt_changed'])){
- $policy_data = $this->policyTransactionModel->where('is_active', 1)->where('id', $id)->first();
- $this->cdCorrection($policy_data, $data['cd_amt_changed']);
- }
-
- $client_data = $this->clientModel->where('id', $data['client_id'])->first();
- $data['client_kyc'] = $this->clientKYCDocsModel->where('client_id', $data['client_id'])->findAll();
-
- $clientController = new ClientController();
- $data['client_kyc_primary_table'] = $clientController->generateKycPrimaryTable($data['client_id']);
- $data['client_kyc_other_table'] = $clientController->generateKycOthersTable($data['client_id']);
-
- $data['entity_type_id'] = $client_data['entity_type_id'];
-
- return $this->respondSuccess($id, "Policy transaction updated successfully", $data);
+ return $this->respondError("Failed to update policy transaction");
}
- return $this->respondError("Failed to update policy transaction");
- }
-
- private function insertOrUpdateCoShareDetails($data, $pt_id)
- {
- // Prepare data for insertion and updating
- $coShareDetails = [];
-
- // print_r($data); die;
- // die;
-
- if (isset($data['co_share_id']) && !empty($data['co_share_id'])) {
- $this->removePtCoShareRecords($data['co_share_id'], $pt_id);
- }
-
- if (isset($data['follow_insurer_id'])) {
-
- foreach ($data['follow_insurer_id'] as $index => $insurer) {
-
- // Separate the insurer and insurer branch
- if (isset($insurer) && !empty($insurer)) {
- list($insurer_branch_id, $insurer_id) = explode('-', $insurer);
- } else {
- $insurer_branch_id = null;
- $insurer_id = null;
- }
-
- if ($data['bro_payable_by'] == 1) {
- $cop_amt = isset($data['co_premium'][$index]) && ($data['co_premium'][$index] != "0.00" && !empty($data['co_premium'][$index])) ? $data['co_premium'][$index] : ($data['base_premium'][$index] ?? 0);
- // print_r($cop_amt);die();
- } else {
- $cop_amt = $data['co_premium'][$index] ?? 0;
- }
-
- // Prepare each co-share detail entry
- $coShareDetails[] = [
- 'pt_id' => $pt_id,
- 'insurer_id' => $insurer_id ?? 0,
- 'insurer_branch_id' => $insurer_branch_id ?? 0,
- 'co_share_type' => $data['co_share_type'][$index] ?? 1,
- 'co_share_per' => $data['co_share_per'][$index] ?? 0,
- 'bp_amt' => $data['base_premium'][$index] ?? 0,
- 'bp_gst_amt' => $data['gst_amount'][$index] ?? 0,
- 'bp_igst' => $data['igst'][$index] ?? 0,
- 'bp_sgst' => $data['sgst'][$index] ?? 0,
- 'bp_cgst' => $data['cgst'][$index] ?? 0,
- 'tp_amt' => $data['tp_premium'][$index] ?? 0,
- 'tep_amt' => $data['ter_premium'][$index] ?? 0,
- 'cotp_amt' => $data['co_tp_premium'][$index] ?? 0,
- 'cotep_amt' => $data['co_ter_premium'][$index] ?? 0,
- 'agreed_amt' => $data['agreed_amount'][$index] ?? 0,
- 'agreed_bp_per' => $data['agreed_bp'][$index] ?? 0,
- 'agreed_tp_per' => $data['agreed_tp'][$index] ?? 0,
- 'agreed_tep_per' => $data['agreed_ter'][$index] ?? 0,
- 'standerd_bp_per' => $data['standard_bp'][$index] ?? 0,
- 'standerd_tp_per' => $data['standard_tp'][$index] ?? 0,
- 'standerd_tep_per' => $data['standard_ter'][$index] ?? 0,
- 'actual_bp_amt' => $data['actual_bp_amt'][$index] ?? 0,
- 'actual_tp_amt' => $data['actual_tp_amt'][$index] ?? 0,
- 'actual_tep_amt' => $data['actual_tep_amt'][$index] ?? 0,
- 'actual_bp_per' => $data['actual_bp_per'][$index] ?? 0,
- 'actual_tp_per' => $data['actual_tp_per'][$index] ?? 0,
- 'actual_tep_per' => $data['actual_tep_per'][$index] ?? 0,
- 'actual_bp_brokerage_amt' => $data['actual_bp_brokerage_amt'][$index] ?? 0,
- 'actual_tp_brokerage_amt' => $data['actual_tp_brokerage_amt'][$index] ?? 0,
- 'actual_tep_brokerage_amt' => $data['actual_tep_brokerage_amt'][$index] ?? 0,
- 'exp_amt' => isset($data['exp_amt'][$index]) && !empty($data['exp_amt'][$index]) ? $data['exp_amt'][$index] : expected_amount_calc($data, $index),
- 'amount' => $data['total'][$index] ?? 0,
- 'stamp_duty' => $data['stamp_duty'][$index] ?? 0,
- 'cop_amt' => $cop_amt,
- 'variance' => $data['variance'][$index] ?? 0,
- 'reward' => $data['reward'][$index] ?? null,
- '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,
- 'non_comm_per_amt' => $data['non_comm_per_amt'][$index] ?? null,
- ];
+ private function insertOrUpdateCoShareDetails($data, $pt_id)
+ {
+ // Prepare data for insertion and updating
+ $coShareDetails = [];
+ if (isset($data['co_share_id']) && !empty($data['co_share_id'])) {
+ $this->removePtCoShareRecords($data['co_share_id'], $pt_id);
}
- // print_r($pt_id);
- // print_r($coShareDetails);
+ if (isset($data['follow_insurer_id'])) {
+
+ foreach ($data['follow_insurer_id'] as $index => $insurer) {
+
+ // Separate the insurer and insurer branch
+ if (isset($insurer) && !empty($insurer)) {
+ list($insurer_branch_id, $insurer_id) = explode('-', $insurer);
+ } else {
+ $insurer_branch_id = null;
+ $insurer_id = null;
+ }
+
+ if ($data['bro_payable_by'] == 1) {
+ $cop_amt = isset($data['co_premium'][$index]) && ($data['co_premium'][$index] != "0.00" && !empty($data['co_premium'][$index])) ? $data['co_premium'][$index] : ($data['base_premium'][$index] ?? 0);
+ // print_r($cop_amt);die();
+ } else {
+ $cop_amt = $data['co_premium'][$index] ?? 0;
+ }
+
+ // Prepare each co-share detail entry
+ $coShareDetails[] = [
+ 'pt_id' => $pt_id,
+ 'insurer_id' => $insurer_id ?? 0,
+ 'insurer_branch_id' => $insurer_branch_id ?? 0,
+ 'co_share_type' => $data['co_share_type'][$index] ?? 1,
+ 'co_share_per' => $data['co_share_per'][$index] ?? 0,
+ 'bp_amt' => $data['base_premium'][$index] ?? 0,
+ 'bp_gst_amt' => $data['gst_amount'][$index] ?? 0,
+ 'bp_igst' => $data['igst'][$index] ?? 0,
+ 'bp_sgst' => $data['sgst'][$index] ?? 0,
+ 'bp_cgst' => $data['cgst'][$index] ?? 0,
+ 'tp_amt' => $data['tp_premium'][$index] ?? 0,
+ 'tep_amt' => $data['ter_premium'][$index] ?? 0,
+ 'cotp_amt' => $data['co_tp_premium'][$index] ?? 0,
+ 'cotep_amt' => $data['co_ter_premium'][$index] ?? 0,
+ 'agreed_amt' => $data['agreed_amount'][$index] ?? 0,
+ 'agreed_bp_per' => $data['agreed_bp'][$index] ?? 0,
+ 'agreed_tp_per' => $data['agreed_tp'][$index] ?? 0,
+ 'agreed_tep_per' => $data['agreed_ter'][$index] ?? 0,
+ 'standerd_bp_per' => $data['standard_bp'][$index] ?? 0,
+ 'standerd_tp_per' => $data['standard_tp'][$index] ?? 0,
+ 'standerd_tep_per' => $data['standard_ter'][$index] ?? 0,
+ 'actual_bp_amt' => $data['actual_bp_amt'][$index] ?? 0,
+ 'actual_tp_amt' => $data['actual_tp_amt'][$index] ?? 0,
+ 'actual_tep_amt' => $data['actual_tep_amt'][$index] ?? 0,
+ 'actual_bp_per' => $data['actual_bp_per'][$index] ?? 0,
+ 'actual_tp_per' => $data['actual_tp_per'][$index] ?? 0,
+ 'actual_tep_per' => $data['actual_tep_per'][$index] ?? 0,
+ 'actual_bp_brokerage_amt' => $data['actual_bp_brokerage_amt'][$index] ?? 0,
+ 'actual_tp_brokerage_amt' => $data['actual_tp_brokerage_amt'][$index] ?? 0,
+ 'actual_tep_brokerage_amt' => $data['actual_tep_brokerage_amt'][$index] ?? 0,
+ 'exp_amt' => isset($data['exp_amt'][$index]) && !empty($data['exp_amt'][$index]) ? $data['exp_amt'][$index] : expected_amount_calc($data, $index),
+ 'amount' => $data['total'][$index] ?? 0,
+ 'stamp_duty' => $data['stamp_duty'][$index] ?? 0,
+ 'cop_amt' => $cop_amt,
+ 'variance' => $data['variance'][$index] ?? 0,
+ 'reward' => $data['reward'][$index] ?? null,
+ '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,
+ 'non_comm_per_amt' => $data['non_comm_per_amt'][$index] ?? null,
+ ];
+ }
+
+ // print_r($pt_id);
+ // print_r($coShareDetails);
+ // die;
+
+ // Separate data into insert and update batches
+ $insertData = array_filter($coShareDetails, function ($detail) {
+ return empty($detail['id']); // Only insert new records
+ });
+
+ $updateData = array_filter($coShareDetails, function ($detail) {
+ return !empty($detail['id']); // Only update existing records
+ });
+
+ // Insert new records
+ if (!empty($insertData)) {
+ $this->PTCOShareDetailsModel->insertBatch($insertData);
+ }
+
+ // Update existing records
+ if (!empty($updateData)) {
+ $this->PTCOShareDetailsModel->updateBatch($updateData, 'id'); // Assuming 'id' is the unique identifier
+ }
+
+ // print_r($this->PTCOShareDetailsModel->getLastQuery()); die;
+ // print_r($coShareDetails);
+ // die;
+
+ return true;
+ }
+
+ // print_r($data);
// die;
-
- // Separate data into insert and update batches
- $insertData = array_filter($coShareDetails, function ($detail) {
- return empty($detail['id']); // Only insert new records
- });
-
- $updateData = array_filter($coShareDetails, function ($detail) {
- return !empty($detail['id']); // Only update existing records
- });
-
- // Insert new records
- if (!empty($insertData)) {
- $this->PTCOShareDetailsModel->insertBatch($insertData);
- }
-
- // Update existing records
- if (!empty($updateData)) {
- $this->PTCOShareDetailsModel->updateBatch($updateData, 'id'); // Assuming 'id' is the unique identifier
- }
-
- // print_r($this->PTCOShareDetailsModel->getLastQuery()); die;
-
- // print_r($coShareDetails);
- // die;
-
- return true;
}
- // print_r($data);
- // die;
- }
-
- private function prepareClientPolicyInsertData($data)
- {
- return [
- 'client_id' => $data['client_id'] ?? null,
- 'insurer_id' => $data['insurer_id'] ?? null,
- 'insurer_branch_id' => $data['insurer_branch_id'] ?? null,
- 'tpa_id' => $data['tpa_id'] ?? null,
- 'tpa_branch_id' => $data['tpa_branch_id'] ?? null,
- 'policy_type_id' => $data['policy_type_id'] ?? null,
- 'policy_start_date' => $data['policy_start_date'] ?? null,
- 'policy_end_date' => $data['policy_end_date'] ?? null,
- 'policy_status' => 1,
- 'is_addon' => $data['is_addon'] ?? null,
- 'base_policy' => $data['base_policy'] ?? 0,
- 'created_by' => get_session_userid(),
- 'policy_no' => $data['policy_no'] ?? null,
- 'client_branch_id' => $data['client_branch_id'] ?? 0,
- 'cd_ac_pk' => $data['cd_ac_no'] ?? null,
- 'gst' => 18,
- ];
- }
-
- private function insertTransactionStatus($policyTranId, $data, $statusType)
- {
- $statusData = [
- 'policy_tran_id' => $policyTranId,
- 'status' => $data['status'],
- 'last_action_date' => $data['last_action_date'],
- 'status_type' => $statusType,
- 'created_by' => get_session_userid(),
- ];
- $this->policyTransactionStatusModel->insert($statusData);
- }
-
- private function processCompletedStatus($data, $client_policy_id, $insurer_id)
- {
- $totalAmount = (int)$data['total'][0] ?? 0;
- $description = 'The following amount of Rs. ' . $totalAmount . '/- has been debited for the ' . $data['emp_count'] . ' employees at Inception (BDS).';
-
- $cdTransactionData = [
- 'amount' => $totalAmount,
- 'sub_type_id' => 4,
- 'client_id' => $data['client_id'],
- 'client_policy_id' => $client_policy_id ?? 0,
- 'endorsement_no' => null,
- 'cd_ac_no' => $data['cd_ac_no'] ?? null,
- 'insurer_id' => $insurer_id,
- 'description' => $description,
- 'transaction_type' => 'Debit',
- 'updated_by' => get_session_userid(),
- 'event_name' => 'inception',
- 'is_active' => 1,
- 'cd_ac_pk' => $data['cd_ac_pk']
- ];
-
- DepositHelper::saveDeposit($cdTransactionData, get_session_userid());
- }
-
- private function cdCorrection($data, $amt)
- {
- $totalAmount = (int)($amt ?? 0);
- $description = 'The following amount of Rs. ' . $totalAmount . '/- has been debited towards the difference arising from the change in the BDS base premium.';
-
- $cdTransactionData = [
- 'amount' => abs($totalAmount),
- 'sub_type_id' => 4,
- 'client_id' => $data['client_id'],
- 'client_policy_id' => $data['client_policy_id'] ?? 0,
- 'endorsement_no' => null,
- 'cd_ac_no' => $data['cd_ac_no'] ?? null,
- 'insurer_id' => $data['insurer_id'],
- 'description' => $description,
- 'transaction_type' => $totalAmount < 0 ? 'Credit' : 'Debit',
- 'updated_by' => get_session_userid(),
- 'event_name' => 'inception',
- 'is_active' => 1,
- 'cd_ac_pk' => $data['cd_ac_pk']
- ];
-
- DepositHelper::saveDeposit($cdTransactionData, get_session_userid());
- }
-
- private function processInsertIndividualMemberInEmpTable($data)
- {
- // print_r($data);
- if (isset($data['family_name']) && !empty($data['family_name'])) {
-
- $emp_data = [];
- $emp_ids = [];
- $random_code = generateRandomCode(); // Generate random code once
-
- foreach ($data['family_name'] as $index => $val) {
-
- // Determine the gender based on the relationship
- $relationship = $data['relationship'][$index] ?? '';
- $gender = 'M'; // Default to Male
-
- // Set gender based on relationship
- if (in_array($relationship, ['Mother', 'Daughter', 'Mother in law', 'Spouse'])) {
- $gender = 'F';
- }
-
- $emp_data[] = [
- 'client_id' => $data['client_id'] ?? 0,
- 'client_branch_id' => $data['client_branch_id'] ?? 0,
- 'name' => $val,
- 'relationship' => $relationship,
- 'gender' => $gender,
- 'emp_status' => 'active',
- 'created_by' => get_session_userid(),
- 'emp_code' => $random_code, // Use the same random code for all
- 'id' => $data['emp_id'][$index] ?? null
- ];
-
- $emp_ids[] = $data['emp_id'][$index] ?? 0;
- }
-
-
- // print_r($emp_data); die;
-
- // Separate data into insert and update batches
- $insertData = array_filter($emp_data, function ($detail) {
- return empty($detail['id']); // Only insert new records
- });
-
- $updateData = array_filter($emp_data, function ($detail) {
- return !empty($detail['id']); // Only update existing records
- });
-
- // Insert new records
- if (!empty($insertData)) {
- $this->employeeModel->insertBatch($insertData);
- }
-
- // Update existing records
- if (!empty($updateData)) {
- $this->employeeModel->updateBatch($updateData, 'id'); // Assuming 'id' is the unique identifier
- }
-
- return $emp_ids;
- }
- }
-
- private function InsertIndividualEmpPolicyTable($emp_ids, $client_policy_id)
- {
- if (!empty($emp_ids)) {
-
- $emp_policy_data = [];
-
- foreach ($emp_ids as $index => $emp_id) {
-
- $emp_policy_data[] = [
- 'employee_id' => $emp_id ?? 0,
- 'client_policy_id' => $client_policy_id ?? 0,
- 'created_by' => get_session_userid(),
- 'status' => 'active',
- ];
- }
-
- // print_r($emp_policy_data); die;
-
- // Insert new records
- if (!empty($emp_policy_data)) {
- $this->employeePolicyModel->insertBatch($emp_policy_data);
- }
-
-
- return true;
- }
- }
-
- private function respondSuccess($id, $message, $data)
- {
- return $this->respond(['status' => true, 'pt_id' => $id, 'message' => $message, 'data' => $data], 200);
- }
-
- private function respondError($message)
- {
- return $this->respond(['status' => false, 'message' => $message], 200);
- }
- // policy Transaction Create function End
-
- // Get the Single Inception Tranction data for edit
- public function getInceptionDataForEdit($id)
- {
- $data = $this->policyTransactionModel
- ->select('
- policy_transaction.*,
- clients.short_name as client_short_name,
- clients.client_type,
- clients.entity_type_id,
- policy_type.policy_type,
- client_policy.tpa_id as master_tpa_id,
- client_policy.tpa_branch_id as master_tpa_branch_id,
- client_policy.policy_type_id as master_policy_type_id,
- client_policy.is_addon,
- client_policy.base_policy,
- (
- select last_action_date
- from policy_transaction_status
- where policy_tran_id = policy_transaction.id
- and status = policy_transaction.status
- order by id desc
- limit 1
-
- ) as last_action_date
- ')
- ->join('clients', 'clients.id = policy_transaction.client_id')
- ->join('client_policy', 'policy_transaction.client_policy_id = client_policy.id', 'left')
- ->join('policy_type', 'client_policy.policy_type_id = policy_type.id', 'left')
- ->where('policy_transaction.id', $id)
- ->where('policy_transaction.is_active', 1)
- ->first();
-
- $data['created_at'] = (isset($data['created_at']) && $data['created_at'] !== null && $data['created_at'] !== '')
- ? date('d/m/Y h:i:s A', strtotime($data['created_at']))
- : null;
-
- $data['updated_at'] = (isset($data['updated_at']) && $data['updated_at'] !== null && $data['updated_at'] !== '')
- ? date('d/m/Y h:i:s A', strtotime($data['updated_at']))
- : null;
-
-
- if (!empty($data['policy_issue_date'])) {
- $data['policy_issue_date'] = change_date_format($data['policy_issue_date'], 'Y-m-d', 'd/m/Y');
+ private function prepareClientPolicyInsertData($data)
+ {
+ return [
+ 'client_id' => $data['client_id'] ?? null,
+ 'insurer_id' => $data['insurer_id'] ?? null,
+ 'insurer_branch_id' => $data['insurer_branch_id'] ?? null,
+ 'tpa_id' => $data['tpa_id'] ?? null,
+ 'tpa_branch_id' => $data['tpa_branch_id'] ?? null,
+ 'policy_type_id' => $data['policy_type_id'] ?? null,
+ 'policy_start_date' => $data['policy_start_date'] ?? null,
+ 'policy_end_date' => $data['policy_end_date'] ?? null,
+ 'policy_status' => 1,
+ 'is_addon' => $data['is_addon'] ?? null,
+ 'base_policy' => $data['base_policy'] ?? 0,
+ 'created_by' => get_session_userid(),
+ 'policy_no' => $data['policy_no'] ?? null,
+ 'client_branch_id' => $data['client_branch_id'] ?? 0,
+ 'cd_ac_pk' => $data['cd_ac_no'] ?? null,
+ 'gst' => 18,
+ 'policy_entry_from' => 2,
+ ];
}
- if (!empty($data['policy_start_date'])) {
- $data['policy_start_date'] = change_date_format($data['policy_start_date'], 'Y-m-d', 'd/m/Y');
+ private function insertTransactionStatus($policyTranId, $data, $statusType)
+ {
+ $statusData = [
+ 'policy_tran_id' => $policyTranId,
+ 'status' => $data['status'],
+ 'last_action_date' => $data['last_action_date'],
+ 'status_type' => $statusType,
+ 'created_by' => get_session_userid(),
+ ];
+ $this->policyTransactionStatusModel->insert($statusData);
}
- if (!empty($data['policy_end_date'])) {
- $data['policy_end_date'] = change_date_format($data['policy_end_date'], 'Y-m-d', 'd/m/Y');
- }
-
- if (!empty($data['renewal_date'])) {
- $data['renewal_date'] = change_date_format($data['renewal_date'], 'Y-m-d', 'd/m/Y');
- }
-
- if (!empty($data['rollover_date'])) {
- $data['rollover_date'] = change_date_format($data['rollover_date'], 'Y-m-d', 'd/m/Y');
- }
-
- if (!empty($data['endorse_eff_date'])) {
- $data['endorse_eff_date'] = change_date_format($data['endorse_eff_date'], 'Y-m-d', 'd/m/Y');
- }
-
- if (!empty($data['last_action_date'])) {
- $data['last_action_date'] = change_date_format($data['last_action_date'], 'Y-m-d', 'd/m/Y');
- }
-
- if (!empty($data['month'])) {
- $data['month'] = change_date_format($data['month'], 'Y-m-d', 'M/Y');
- } else {
- $data['month'] = null;
- }
-
- // print_r($data); die;
-
- $data['renewal_policy'] = $this->clientPolicyModel
- ->select('client_policy.*, policy_type.policy_type')
- ->join('policy_type', 'policy_type.id = client_policy.policy_type_id')
- ->where('client_policy.client_id', $data['client_id'])
- ->where('client_policy.client_branch_id', $data['client_branch_id'])
- ->where('client_policy.is_active', 1)
- ->findAll();
-
- $data['base_policy_data'] = $this->clientPolicyModel
- ->select('client_policy.*, policy_type.policy_type')
- ->join('policy_type', 'policy_type.id = client_policy.policy_type_id')
- ->where('client_policy.client_id', $data['client_id'])
- ->where('client_policy.client_branch_id', $data['client_branch_id'])
- ->whereIn('client_policy.policy_type_id', [2, 3])
- ->where('client_policy.is_active', 1)
- ->findAll();
-
- $pt_bp_amt = $this->PTCOShareDetailsModel
- ->select('bp_amt, amount')
- ->where('pt_id', $id)
- ->where('co_share_type', 1)
- ->where('is_active', 1)
- ->first();
-
- // dd(db_connect()->getLastQuery() ,$pt_bp_amt);
- $data['base_cd_amount'] = $pt_bp_amt['amount'] ?? null;
-
-
- $ptFileQuery = $this->PTFileModel
- ->join('policy_transaction', 'pt_files.pt_id = policy_transaction.id')
- ->where('pt_files.pt_id', $id)
- ->where('pt_files.is_active', 1);
-
- if (!in_array(get_role_id(), [1, 5]) && empty(array_intersect(user_team(), [MANAGEMENT_TEAM_ID, FINANCE_TEAM_ID, BUSINESS_TEAM_ID]))) {
-
- if (get_role_id() == 4 && in_array(POS_TEAM_ID, user_team())) {
- $ptFileQuery->where('pt_files.created_by', get_session_userid());
- }
- }
-
- $data['pt_files'] = $ptFileQuery->findAll();
-
-
-
- $data['pt_co_share_details'] = $this->PTCOShareDetailsModel
- ->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,
-
- (
- SELECT
- SUM(actual_bp_amt)
- FROM
- co_share_stmt_details
- WHERE
- co_share_id = pt_co_share_details.id
- AND is_active = 1
-
- ) AS actual_bp_amount,
-
- (
- SELECT
- SUM(actual_tp_amt)
- FROM
- co_share_stmt_details
- WHERE
- co_share_id = pt_co_share_details.id
- AND is_active = 1
-
- ) AS actual_tp_amount,
-
- (
- SELECT
- SUM(actual_tep_amt)
- FROM
- co_share_stmt_details
- WHERE
- co_share_id = pt_co_share_details.id
- AND is_active = 1
-
- ) AS actual_tep_amount,
-
- (
- SELECT
- SUM(actual_bp_per)
- FROM
- co_share_stmt_details
- WHERE
- co_share_id = pt_co_share_details.id
- AND is_active = 1
-
- ) AS actual_bp_percentage,
-
- (
- SELECT
- SUM(actual_tp_per)
- FROM
- co_share_stmt_details
- WHERE
- co_share_id = pt_co_share_details.id
- AND is_active = 1
-
- ) AS actual_tp_percentage,
-
- (
- SELECT
- SUM(actual_tep_per)
- FROM
- co_share_stmt_details
- WHERE
- co_share_id = pt_co_share_details.id
- AND is_active = 1
-
- ) AS actual_tep_percentage,
-
-
- (
- SELECT
- SUM(actual_bp_brokerage_amt)
- FROM
- co_share_stmt_details
- WHERE
- co_share_id = pt_co_share_details.id
- AND is_active = 1
-
- ) AS actual_bp_brokerage_amount,
-
-
- (
- SELECT
- SUM(actual_tp_brokerage_amt)
- FROM
- co_share_stmt_details
- WHERE
- co_share_id = pt_co_share_details.id
- AND is_active = 1
-
- ) AS actual_tp_brokerage_amount,
-
-
- (
- SELECT
- SUM(actual_tep_brokerage_amt)
- FROM
- co_share_stmt_details
- WHERE
- co_share_id = pt_co_share_details.id
- AND is_active = 1
-
- ) AS actual_tep_brokerage_amount
-
- ")
- ->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')
- ->where('employees.client_id', $data['client_id'])
- ->where('employees.is_active', 1)->findAll();
- // $data['client_kyc'] = $this->clientKYCDocsModel->where('client_id', $data['client_id'])->findAll();
-
- $clientController = new ClientController();
- $data['client_kyc_primary_table'] = $clientController->generateKycPrimaryTable($data['client_id']);
- $data['client_kyc_other_table'] = $clientController->generateKycOthersTable($data['client_id']);
-
- $data['vehicle_docs'] = $this->clientKYCDocsModel
- ->where('client_id', $data['client_id'])
- ->where('vehicle_id', $data['vehicle_id'])
- ->findAll();
-
- // print_r( $data['pt_co_share_details']); die;
- // return $data;
- if ($data) {
- return $this->respond(['status' => true, 'data' => $data], 200);
- } else {
- return $this->respond(['status' => false], 200);
- }
- }
-
- public function removePolicyTransaction($id)
- {
- if ($id) {
-
- $data['is_active'] = 0;
- $policy_transaction_data = $this->policyTransactionModel->where('id', $id)->first();
- if($policy_transaction_data['policy_type_id'] > 7){
- $this->policyTransactionModel->where('id', $id)->set($data)->update();
- $this->PTCOShareDetailsModel->where('pt_id', $id)->set($data)->update();
- $this->clientPolicyModel->where('id', $policy_transaction_data['client_policy_id'])->set($data)->update();
- $this->policyTransactionModel->where('client_policy_id', $policy_transaction_data['client_policy_id'])->set($data)->update();
- }else{
- $this->policyTransactionModel->where('id', $id)->set($data)->update();
- $this->PTCOShareDetailsModel->where('pt_id', $id)->set($data)->update();
- }
- return $this->respond(['status' => true, 'code' => 200, 'message' => 'Policy Transaction removed successfully'], 200);
- } else {
-
- return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to remove policy transaction'], 200);
- }
- }
-
- //function for soft delete for pt_co_share_details records
- public function removePtCoShareRecords($primaryKeys, $pt_id)
- {
- if (empty($primaryKeys)) {
- return false;
- }
-
- // Convert array to a comma-separated string of placeholders for query binding
- $placeholders = implode(',', array_fill(0, count($primaryKeys), '?'));
-
- // Prepare the query with proper binding
- $sql = "UPDATE pt_co_share_details SET is_active = 0 WHERE pt_id = ? AND id NOT IN ($placeholders)";
-
- // Merge pt_id with primary keys for binding
- $params = array_merge([$pt_id], $primaryKeys);
-
- // Execute the query with bound parameters
- return db_connect()->query($sql, $params);
- }
-
-
- //------------------------------------------------------------------------------------------------
-
- // Policy Transaction Endorsement
- public function viewEndorsement()
- {
- // echo '';
- // !dd($this->getEndorsementDataForEdit(17));
-
- $data['tab_name'] = 'Endorsement';
- $data['page_name'] = 'Endorsement';
- $data['issuer'] = [1 => 'JIBS', 2 => 'Nhance'];
- $data['issuer_branch'] = $this->nhanceBranchModel->where('is_active', 1)->findAll();
- $data['client_type'] = [1 => 'Group', 2 => 'Individual'];
-
- $data['policy_status'] = [
- 'under_process' => 'Under Process',
- 'client_pending' => 'Client Pending',
- 'insurer_pending' => 'Insurer Pending',
- 'co_insurer_pending' => 'Co-Insurer Pending',
- 'tpa_pending' => 'TPA Pending',
- 'validated' => 'Validated',
- 'cancelled' => 'Cancelled',
- 'instalment_pending' => 'Instalment Pending',
- 'completed' => 'Completed',
- ];
-
- $data['invoice_status'] = [
- 'yet_to_generate' => 'Pending',
- 'generated' => 'Generated',
- 'send' => 'Sent',
- 'recived' => 'Payment Received',
- ];
-
- $data['action_type'] = [
- 'addition' => 'Addition',
- 'deletion' => 'Deletion',
- 'addition_deletion' => 'Addition & Deletion',
- 'si_enhancement' => 'SI Enhancement',
- 'combo_a_d_si' => 'Combo A, D & SI',
- 'correction' => 'Correction',
- 'baby_addition' => 'Baby Addition',
- 'policy_instalment' => 'Policy Instalment',
- 'addition_inception' => 'Addition-Inception',
- 'bds_correction' => 'BDS Correction',
- 'policy_correction' => 'Policy Correction',
- 'policy_cancellation' => 'Policy Cancellation',
- ];
-
- $data['date_type'] = [
- 'policy_issue_date' => 'Policy Issue Date',
- 'policy_start_date' => 'Policy Start Date',
- 'policy_end_date' => 'Policy End Date',
- ];
-
- //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');
- $status = $this->request->getGet('status');
-
- $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;
- $status = (!isset($issuer) || $status === '' || $status === null) ? 0 : $status;
-
-
- $data['endorsement_data_list'] = $this->policyTransactionModel->getEndorsementTranctionListData($start_date, $end_date, $client_id, $insurer_id, $policy_type_id, $date_type, $issuer, $status);
- $data['client'] = $this->clientModel->where('is_active', 1)->findAll();
- $data['policy_types'] = $this->policyTypeModel->where('is_active', 1)->findAll();
-
- $data['insurer'] = $this->insurerModel->where('is_active', 1)->findAll();
- // $data['tpa'] = $this->tpaModel->where('is_active', 1)->findAll();
- $data['insurer_branch'] = $this->insurerBranchModel->getInsurerBranchesWithInsurerNames();
- $data['tpa'] = $this->tpaBranchModel->getTpaBranchesWithTpaNames();
- list($policyList, $policyListByClient) = $this->getPolicyForEndorsment();
-
- $data['endorsementPolicies'] = $policyList;
- $data['endorsementPolicyListByClient'] = $policyListByClient;
-
- // dd($data);
- // print_r($data['endorsementPolicies']);die();
-
- $this->loadLayout('policy_transaction_endorsement_list', $data);
- }
-
- public function createEndorsementPolicy()
- {
- $id = $this->request->getPost('id');
- $data = $this->preparePolicyTransactionData();
- // print_r($data); die;
-
- if (!$id) {
- return $this->insertEndorsementTransaction($data);
- } else {
- return $this->updateEndorsementTransaction($id, $data);
- }
- }
-
- private function preparePolicyTransactionData()
- {
- $data = $this->request->getPost();
-
- // echo '';
- // print_r($data);
- // die;
-
- if (!isset($data['policy_with_corr'])) {
- $data['policy_with_corr'] = 0;
- } elseif ($data['policy_with_corr']) {
- $data['policy_with_corr'] = 1;
- }
-
- // if (!isset($data['is_cd_reduce_from_bds'])) {
- // $data['is_cd_reduce_from_bds'] = 0;
- // } elseif ($data['is_cd_reduce_from_bds']) {
- // $data['is_cd_reduce_from_bds'] = 1;
- // }
-
- if (empty($data['data_received_date'])) {
- $data['data_received_date'] = null;
- } else {
- $data['data_received_date'] = change_date_format($data['data_received_date'], 'd/m/Y', 'Y-m-d');
- }
-
- if (empty($data['policy_issue_date'])) {
- $data['policy_issue_date'] = null;
- } else {
- $data['policy_issue_date'] = change_date_format($data['policy_issue_date'], 'd/m/Y', 'Y-m-d');
- }
-
- if (empty($data['endorse_eff_date'])) {
- $data['endorse_eff_date'] = null;
- } else {
- $data['endorse_eff_date'] = change_date_format($data['endorse_eff_date'], 'd/m/Y', 'Y-m-d');
- }
-
- if (empty($data['install_due_date'])) {
- $data['install_due_date'] = null;
- } else {
- $data['install_due_date'] = change_date_format($data['install_due_date'], 'd/m/Y', 'Y-m-d');
- }
-
- if (!empty($data['month'])) {
- $month = '01/' . $data['month'];
- $data['month'] = change_date_format($month, 'd/M/Y', 'Y-m-d');
- }
-
- if (empty($data['last_action_date'])) {
- $data['last_action_date'] = null;
- } else {
- $data['last_action_date'] = change_date_format($data['last_action_date']);
- }
-
- // print_r($data); die;
-
- // Separate Insurer and TPA Branch IDs and IDs
- if (isset($data['insurer_id']) && !empty($data['insurer_id'])) {
- list($data['insurer_branch_id'], $data['insurer_id']) = explode('-', $data['insurer_id']);
- if (isset($data['tpa']) && !empty($data['tpa'])) {
- list($data['tpa_branch_id'], $data['tpa_id']) = explode('-', $data['tpa']);
- }
- }
-
- $issue_type = $this->policyTransactionModel
- ->where('action_type', 'inception')
- ->where('client_id', $this->request->getPost('client_id'))
- // ->where('client_policy_id', $this->request->getPost('client_policy_id'))
- ->where('id', $this->request->getPost('client_policy_id'))
- ->where('policy_transaction.is_active', 1)
- ->first();
-
- $data['tsi'] = generate_tsi_code($issue_type['issue_type'] ?? 1);
-
- $client_branch_id = $data['client_branch_id'];
- if ($data['client_branch_id'] == "") {
- $client_branch_id = $issue_type['client_branch_id'];
- }
-
- $data['is_cd_reduce_from_bds'] = (isset($issue_type['policy_type_id']) && $issue_type['policy_type_id'] > 7 && $data['client_type'] == 1) ? 1 : 0;
-
- // if($data['bro_payable_by'] == ""){
- // $data['bro_payable_by'] = $issue_type['bro_payable_by'];
- // }
-
- if (!$data['id']) {
-
- $data += [
- 'issuer' => 2,
- 'issuer_branch' => $data['issuer_branch'] ?? 1,
- 'client_type' => $data['client_type'] ?? $issue_type['client_type'] ?? null,
- 'policy_type_id' => $issue_type['policy_type_id'] ?? null,
- 'issue_type' => $issue_type['issue_type'] ?? null,
- 'source_client_policy_id' => $issue_type['source_client_policy_id'] ?? null,
- 'cd_ac_no' => isset($data['cd_ac_no']) && !empty($data['cd_ac_no']) ? $data['cd_ac_no'] : $issue_type['cd_ac_no'] ?? null,
- 'cd_ac_pk' => isset($data['cd_ac_pk']) && !empty($data['cd_ac_pk']) ? $data['cd_ac_pk'] : $issue_type['cd_ac_pk'] ?? null,
- // 'policy_issue_date' => $issue_type['policy_issue_date'] ?? null,
- 'policy_start_date' => $issue_type['policy_start_date'] ?? null,
- 'policy_end_date' => $issue_type['policy_end_date'] ?? null,
- 'revenue_type' => $issue_type['revenue_type'] ?? null,
- 'co_share' => $issue_type['co_share'] ?? 0,
- 'bro_payable_by' => $data['bro_payable_by'] == "" ? $issue_type['bro_payable_by'] ?? 0 : $data['bro_payable_by'],
- 'installment' => $issue_type['installment'] ?? null,
- 'installment_data' => $issue_type['installment_data'] ?? null,
- 'location' => $issue_type['location'] ?? null,
- 'links' => $issue_type['links'] ?? null,
- 'stage' => $issue_type['stage'] ?? null,
- 'etat' => $issue_type['etat'] ?? null,
- 'etat_band' => $issue_type['etat_band'] ?? null,
- 'edate' => $issue_type['edate'] ?? null,
- 'renewal_date' => $issue_type['renewal_date'] ?? null,
- 'rollover_date' => $issue_type['rollover_date'] ?? null,
- 'policy_holder_name' => $issue_type['policy_holder_name'] ?? null,
- 'same_as_proposer' => $issue_type['same_as_proposer'] ?? 1,
- 'ref' => $issue_type['ref'] ?? null,
- 'spl' => $issue_type['spl'] ?? null,
- 'fund_received' => $issue_type['fund_received'] ?? null,
- 'listed_insurers' => $issue_type['listed_insurers'] ?? null,
- 'ppteam' => $issue_type['ppteam'] ?? null,
- 'sales_generated_by' => $issue_type['sales_generated_by'] ?? null,
- 'serviced_by' => $issue_type['serviced_by'] ?? null
+ private function processCompletedStatus($data, $client_policy_id, $insurer_id, $policyTranId)
+ {
+ $totalAmount = (int)$data['total'][0] ?? 0;
+ $description = 'The following amount of Rs. ' . $totalAmount . '/- has been debited for the ' . $data['emp_count'] . ' employees at Inception (BDS).';
+
+ $cdTransactionData = [
+ 'amount' => $totalAmount,
+ 'sub_type_id' => 4,
+ 'client_id' => $data['client_id'],
+ 'client_policy_id' => $client_policy_id ?? 0,
+ 'endorsement_no' => null,
+ 'cd_ac_no' => $data['cd_ac_no'] ?? null,
+ 'insurer_id' => $insurer_id,
+ 'description' => $description,
+ 'transaction_type' => 'Debit',
+ 'updated_by' => get_session_userid(),
+ 'event_name' => 'inception',
+ 'is_active' => 1,
+ 'cd_ac_pk' => $data['cd_ac_pk'],
+ 'pt_id' => $policyTranId ?? null,
];
- $data['client_branch_id'] = $client_branch_id;
- }
+ $result = DepositHelper::saveDeposit($cdTransactionData, get_session_userid());
- // print_r($issue_type);
- // print_r($data);
- // die;
-
- return $data;
- }
-
- private function insertEndorsementTransaction($data)
- {
- $insert = $this->policyTransactionModel->insert($data);
-
- if ($insert) {
-
- $this->insertTransactionStatus($insert, $data, 1);
- $this->handleCompletedStatus($data, $insert);
- $this->insertOrUpdateCoShareDetails($data, $insert);
-
- return $this->respond(['status' => true, 'message' => 'Endorsement transaction created successfully'], 200);
- }
-
- return $this->respond(['status' => false, 'message' => 'Endorsement transaction creation failed'], 400);
- }
-
- private function updateEndorsementTransaction($id, $data)
- {
- $old_endorse_data = $this->policyTransactionModel->where('id', $id)->where('is_active', 1)->first();
- $update = $this->policyTransactionModel->where('id', $id)->set($data)->update();
-
- if ($update) {
-
- $this->insertTransactionStatus($id, $data, 1);
- if($old_endorse_data['status'] != "completed"){
- $this->handleCompletedStatus($data, $id);
+ if(isset($result) && $result['success'] == true){
+ $update_data['ct_tran_id'] = $result['insert_id'];
+ $this->policyTransactionModel->where('id', $policyTranId)->set($update_data)->update();
}
- $this->insertOrUpdateCoShareDetails($data, $id);
-
-
- return $this->respond(['status' => true, 'message' => 'Endorsement transaction updated successfully'], 200);
}
- return $this->respond(['status' => false, 'message' => 'Endorsement transaction update failed'], 400);
- }
+ private function cdCorrection($data, $amt, $policyTranId)
+ {
+ $totalAmount = (int)($amt ?? 0);
+ $description = 'The following amount of Rs. ' . $totalAmount . '/- has been debited towards the difference arising from the change in the BDS base premium.';
- private function handleCompletedStatus($data, $policy_tran_id)
- {
- if ($data['client_type'] == 1 && $data['status'] == 'completed' && $data['is_cd_reduce_from_bds'] == 1) {
-
- $tolamt = (int) $data['total'][0] ?? 0;
-
- $description = 'The following amount of Rs. ' . round($tolamt, 2) . '/- has been' .
- ($data['action_type'] == 'deletion' ? ' Credit ' : ' Debit ') . 'from the policy transaction (BDS)';
- $cd_tranction_data = [
- 'amount' => $tolamt,
- 'sub_type_id' => $data['action_type'] == 'deletion' ? 3 : 4,
+ $cdTransactionData = [
+ 'amount' => abs($totalAmount),
+ 'sub_type_id' => 4,
'client_id' => $data['client_id'],
- 'client_policy_id' => $data['client_policy_id'],
+ 'client_policy_id' => $data['client_policy_id'] ?? 0,
'endorsement_no' => null,
'cd_ac_no' => $data['cd_ac_no'] ?? null,
'insurer_id' => $data['insurer_id'],
'description' => $description,
- 'transaction_type' => $data['action_type'] == 'deletion' ? 'Credit' : 'Debit',
+ 'transaction_type' => $totalAmount < 0 ? 'Credit' : 'Debit',
'updated_by' => get_session_userid(),
- 'event_name' => $data['action_type'],
+ 'event_name' => 'inception',
'is_active' => 1,
- 'cd_ac_pk' => $data['cd_ac_pk'] ?? null,
+ 'cd_ac_pk' => $data['cd_ac_pk'],
+ 'pt_id' => $policyTranId ?? null,
];
- DepositHelper::saveDeposit($cd_tranction_data, get_session_userid());
- }
- }
-
- public function getEndorsementDataForEdit($id)
- {
- $data = $this->policyTransactionModel
- ->select('
- policy_transaction.*,
- clients.short_name as client_short_name,
- clients.client_type,
- (
- select last_action_date
- from policy_transaction_status
- where policy_tran_id = policy_transaction.id
- and status = policy_transaction.status
- order by id desc
- limit 1
-
- ) as last_action_date
- ')
- ->join('clients', 'clients.id = policy_transaction.client_id')
- ->join('client_policy', 'policy_transaction.client_policy_id = client_policy.id', 'left')
- ->where('policy_transaction.id', $id)
- ->where('policy_transaction.is_active', 1)
- ->orderBy('id', 'asc')
- ->first();
-
-
- if (!empty($data['policy_start_date'])) {
- $data['policy_start_date'] = change_date_format($data['policy_start_date'], 'Y-m-d', 'd/m/Y');
+ DepositHelper::saveDeposit($cdTransactionData, get_session_userid());
}
- if (!empty($data['policy_end_date'])) {
- $data['policy_end_date'] = change_date_format($data['policy_end_date'], 'Y-m-d', 'd/m/Y');
+ private function processInsertIndividualMemberInEmpTable($data)
+ {
+ // print_r($data);
+ if (isset($data['family_name']) && !empty($data['family_name'])) {
+
+ $emp_data = [];
+ $emp_ids = [];
+ $random_code = generateRandomCode(); // Generate random code once
+
+ foreach ($data['family_name'] as $index => $val) {
+
+ // Determine the gender based on the relationship
+ $relationship = $data['relationship'][$index] ?? '';
+ $gender = 'M'; // Default to Male
+
+ // Set gender based on relationship
+ if (in_array($relationship, ['Mother', 'Daughter', 'Mother in law', 'Spouse'])) {
+ $gender = 'F';
+ }
+
+ $emp_data[] = [
+ 'client_id' => $data['client_id'] ?? 0,
+ 'client_branch_id' => $data['client_branch_id'] ?? 0,
+ 'name' => $val,
+ 'relationship' => $relationship,
+ 'gender' => $gender,
+ 'emp_status' => 'active',
+ 'created_by' => get_session_userid(),
+ 'emp_code' => $random_code, // Use the same random code for all
+ 'id' => $data['emp_id'][$index] ?? null
+ ];
+
+ $emp_ids[] = $data['emp_id'][$index] ?? 0;
+ }
+
+
+ // print_r($emp_data); die;
+
+ // Separate data into insert and update batches
+ $insertData = array_filter($emp_data, function ($detail) {
+ return empty($detail['id']); // Only insert new records
+ });
+
+ $updateData = array_filter($emp_data, function ($detail) {
+ return !empty($detail['id']); // Only update existing records
+ });
+
+ // Insert new records
+ if (!empty($insertData)) {
+ $this->employeeModel->insertBatch($insertData);
+ }
+
+ // Update existing records
+ if (!empty($updateData)) {
+ $this->employeeModel->updateBatch($updateData, 'id'); // Assuming 'id' is the unique identifier
+ }
+
+ return $emp_ids;
+ }
}
- if (!empty($data['data_received_date'])) {
- $data['data_received_date'] = change_date_format($data['data_received_date'], 'Y-m-d', 'd/m/Y');
+ private function InsertIndividualEmpPolicyTable($emp_ids, $client_policy_id)
+ {
+ if (!empty($emp_ids)) {
+
+ $emp_policy_data = [];
+
+ foreach ($emp_ids as $index => $emp_id) {
+
+ $emp_policy_data[] = [
+ 'employee_id' => $emp_id ?? 0,
+ 'client_policy_id' => $client_policy_id ?? 0,
+ 'created_by' => get_session_userid(),
+ 'status' => 'active',
+ ];
+ }
+
+ // print_r($emp_policy_data); die;
+
+ // Insert new records
+ if (!empty($emp_policy_data)) {
+ $this->employeePolicyModel->insertBatch($emp_policy_data);
+ }
+
+
+ return true;
+ }
}
- if (!empty($data['policy_issue_date'])) {
- $data['policy_issue_date'] = change_date_format($data['policy_issue_date'], 'Y-m-d', 'd/m/Y');
+ private function respondSuccess($id, $message, $data)
+ {
+ return $this->respond(['status' => true, 'pt_id' => $id, 'message' => $message, 'data' => $data], 200);
}
- if (!empty($data['endorse_eff_date'])) {
- $data['endorse_eff_date'] = change_date_format($data['endorse_eff_date'], 'Y-m-d', 'd/m/Y');
+ private function respondError($message)
+ {
+ return $this->respond(['status' => false, 'message' => $message], 200);
}
+ // policy Transaction Create function End
- if (!empty($data['install_due_date'])) {
- $data['install_due_date'] = change_date_format($data['install_due_date'], 'Y-m-d', 'd/m/Y');
- }
+ // Get the Single Inception Tranction data for edit
+ public function getInceptionDataForEdit($id)
+ {
+ $data = $this->policyTransactionModel
+ ->select('
+ policy_transaction.*,
+ clients.short_name as client_short_name,
+ clients.client_type,
+ clients.entity_type_id,
+ policy_type.policy_type,
+ client_policy.tpa_id as master_tpa_id,
+ client_policy.tpa_branch_id as master_tpa_branch_id,
+ client_policy.policy_type_id as master_policy_type_id,
+ client_policy.is_addon,
+ client_policy.base_policy,
+ (
+ select last_action_date
+ from policy_transaction_status
+ where policy_tran_id = policy_transaction.id
+ and status = policy_transaction.status
+ order by id desc
+ limit 1
- if (!empty($data['last_action_date'])) {
- $data['last_action_date'] = change_date_format($data['last_action_date'], 'Y-m-d', 'd/m/Y');
- }
+ ) as last_action_date
+ ')
+ ->join('clients', 'clients.id = policy_transaction.client_id')
+ ->join('client_policy', 'policy_transaction.client_policy_id = client_policy.id', 'left')
+ ->join('policy_type', 'client_policy.policy_type_id = policy_type.id', 'left')
+ ->where('policy_transaction.id', $id)
+ ->where('policy_transaction.is_active', 1)
+ ->first();
- if (!empty($data['month'])) {
- $data['month'] = change_date_format($data['month'], 'Y-m-d', 'M/Y');
- }
+ $data['created_at'] = (isset($data['created_at']) && $data['created_at'] !== null && $data['created_at'] !== '')
+ ? date('d/m/Y h:i:s A', strtotime($data['created_at']))
+ : null;
- // print_r($data); die;
+ $data['updated_at'] = (isset($data['updated_at']) && $data['updated_at'] !== null && $data['updated_at'] !== '')
+ ? date('d/m/Y h:i:s A', strtotime($data['updated_at']))
+ : null;
- //get PT Co-Share Details
- $data['pt_co_share_details'] = $this->PTCOShareDetailsModel
- ->select("
+ if (!empty($data['policy_issue_date'])) {
+ $data['policy_issue_date'] = change_date_format($data['policy_issue_date'], 'Y-m-d', 'd/m/Y');
+ }
+
+ if (!empty($data['policy_start_date'])) {
+ $data['policy_start_date'] = change_date_format($data['policy_start_date'], 'Y-m-d', 'd/m/Y');
+ }
+
+ if (!empty($data['policy_end_date'])) {
+ $data['policy_end_date'] = change_date_format($data['policy_end_date'], 'Y-m-d', 'd/m/Y');
+ }
+
+ if (!empty($data['renewal_date'])) {
+ $data['renewal_date'] = change_date_format($data['renewal_date'], 'Y-m-d', 'd/m/Y');
+ }
+
+ if (!empty($data['rollover_date'])) {
+ $data['rollover_date'] = change_date_format($data['rollover_date'], 'Y-m-d', 'd/m/Y');
+ }
+
+ if (!empty($data['endorse_eff_date'])) {
+ $data['endorse_eff_date'] = change_date_format($data['endorse_eff_date'], 'Y-m-d', 'd/m/Y');
+ }
+
+ if (!empty($data['last_action_date'])) {
+ $data['last_action_date'] = change_date_format($data['last_action_date'], 'Y-m-d', 'd/m/Y');
+ }
+
+ if (!empty($data['month'])) {
+ $data['month'] = change_date_format($data['month'], 'Y-m-d', 'M/Y');
+ } else {
+ $data['month'] = null;
+ }
+
+ // print_r($data); die;
+
+ $data['renewal_policy'] = $this->clientPolicyModel
+ ->select('client_policy.*, policy_type.policy_type')
+ ->join('policy_type', 'policy_type.id = client_policy.policy_type_id')
+ ->where('client_policy.client_id', $data['client_id'])
+ ->where('client_policy.client_branch_id', $data['client_branch_id'])
+ ->where('client_policy.is_active', 1)
+ ->findAll();
+
+ $data['base_policy_data'] = $this->clientPolicyModel
+ ->select('client_policy.*, policy_type.policy_type')
+ ->join('policy_type', 'policy_type.id = client_policy.policy_type_id')
+ ->where('client_policy.client_id', $data['client_id'])
+ ->where('client_policy.client_branch_id', $data['client_branch_id'])
+ ->whereIn('client_policy.policy_type_id', [2, 3])
+ ->where('client_policy.is_active', 1)
+ ->findAll();
+
+ $pt_bp_amt = $this->PTCOShareDetailsModel
+ ->select('bp_amt, amount')
+ ->where('pt_id', $id)
+ ->where('co_share_type', 1)
+ ->where('is_active', 1)
+ ->first();
+
+ // dd(db_connect()->getLastQuery() ,$pt_bp_amt);
+ $data['base_cd_amount'] = $pt_bp_amt['amount'] ?? null;
+
+
+ $ptFileQuery = $this->PTFileModel
+ ->join('policy_transaction', 'pt_files.pt_id = policy_transaction.id')
+ ->where('pt_files.pt_id', $id)
+ ->where('pt_files.is_active', 1);
+
+ if (!in_array(get_role_id(), [1, 5]) && empty(array_intersect(user_team(), [MANAGEMENT_TEAM_ID, FINANCE_TEAM_ID, BUSINESS_TEAM_ID]))) {
+
+ if (get_role_id() == 4 && in_array(POS_TEAM_ID, user_team())) {
+ $ptFileQuery->where('pt_files.created_by', get_session_userid());
+ }
+ }
+
+ $data['pt_files'] = $ptFileQuery->findAll();
+
+
+
+ $data['pt_co_share_details'] = $this->PTCOShareDetailsModel
+ ->select("
pt_co_share_details.*,
(
@@ -1447,7 +900,7 @@ class PolicyTransactionController extends BaseController
co_share_stmt_details.co_share_id = pt_co_share_details.id
AND co_share_stmt_details.is_active = 1
) AS record_count,
-
+
(
SELECT
SUM(actual_bp_amt)
@@ -1549,1568 +1002,2293 @@ class PolicyTransactionController extends BaseController
AND is_active = 1
) AS actual_tep_brokerage_amount
-
+
")
- ->where('pt_id', $id)
- ->where('is_active', 1)
- ->orderBy('id', 'asc')
- ->findAll();
+ ->where('pt_id', $id)
+ ->where('is_active', 1)
+ ->orderBy('id', 'asc')
+ ->findAll();
- // print_r($data['endorse_eff_date']); die;
+ $data['emp_data'] = $this->employeeModel
+ ->select('employees.*, employee_polices.id as emp_policy_id')
+ ->join('employee_polices', 'employees.id = employee_polices.employee_id', 'left')
+ ->where('employees.client_id', $data['client_id'])
+ ->where('employees.is_active', 1)->findAll();
+ // $data['client_kyc'] = $this->clientKYCDocsModel->where('client_id', $data['client_id'])->findAll();
- if ($data) {
- return $this->respond(['status' => true, 'data' => $data], 200);
- } else {
- return $this->respond(['status' => false], 200);
+ $clientController = new ClientController();
+ $data['client_kyc_primary_table'] = $clientController->generateKycPrimaryTable($data['client_id']);
+ $data['client_kyc_other_table'] = $clientController->generateKycOthersTable($data['client_id']);
+
+ $data['vehicle_docs'] = $this->clientKYCDocsModel
+ ->where('client_id', $data['client_id'])
+ ->where('vehicle_id', $data['vehicle_id'])
+ ->findAll();
+
+ // print_r( $data['pt_co_share_details']); die;
+ // return $data;
+ if ($data) {
+ return $this->respond(['status' => true, 'data' => $data], 200);
+ } else {
+ return $this->respond(['status' => false], 200);
+ }
}
- }
- //------------------------------------------------------------------------------------------------
+ public function removePolicyTransaction($id, $type = 0)
+ {
+ if ($id) {
+ $data['is_active'] = 0;
+ $policy_transaction_data = $this->policyTransactionModel->where('id', $id)->first();
+ if($policy_transaction_data['policy_type_id'] > 7 && $type == 0){
- //file upload function
- public function uploadFile()
- {
- $GoogleDriveController = new GoogleDriveController();
- $files = $this->request->getFiles();
- $doc_name = $this->request->getPost('doc_name[]');
- $pt_id = $this->request->getPost('pt_id');
- $client_policy_id = $this->request->getPost('client_policy_id');
- $data = $this->request->getPost();
+ $this->policyTransactionModel->where('id', $id)->set($data)->update();
+ $this->PTCOShareDetailsModel->where('pt_id', $id)->set($data)->update();
+ $this->clientPolicyModel->where('id', $policy_transaction_data['client_policy_id'])->set($data)->update();
+ $this->policyTransactionModel->where('client_policy_id', $policy_transaction_data['client_policy_id'])->set($data)->update();
- $uploadFilePath = WRITEPATH . 'uploads/client_kyc_documents';
+ $cd_transaction_model = new ClientDepositModel();
+ $cd_transaction_model->where('policy_transaction_id', $id)->set($data)->update();
- $uploadData = [];
+ }else{
+ $this->policyTransactionModel->where('id', $id)->set($data)->update();
+ $this->PTCOShareDetailsModel->where('pt_id', $id)->set($data)->update();
+
+ $cd_transaction_model = new ClientDepositModel();
+ $cd_transaction_model->where('policy_transaction_id', $id)->set($data)->update();
- foreach ($data['doc_name'] as $key => $docName) {
+ }
+ return $this->respond(['status' => true, 'code' => 200, 'message' => 'Policy Transaction removed successfully'], 200);
+ } else {
- // Get the corresponding file for this document name
- $file = $files['file'][$key];
+ return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to remove policy transaction'], 200);
+ }
+ }
- if (!empty($docName) && $file->isValid() && !$file->hasMoved()) {
+ //function for soft delete for pt_co_share_details records
+ public function removePtCoShareRecords($primaryKeys, $pt_id)
+ {
+ if (empty($primaryKeys)) {
+ return false;
+ }
- // Upload the file
- $uploadedFileName = file_Upload($file, $uploadFilePath);
+ // Convert array to a comma-separated string of placeholders for query binding
+ $placeholders = implode(',', array_fill(0, count($primaryKeys), '?'));
- if ($uploadedFileName) {
- // Prepare data for each document upload
- $docData = [
- 'pt_id' => $pt_id,
- 'doc_name' => $docName,
- 'file_name' => $uploadedFileName,
- 'created_by' => get_session_userid(),
+ // Prepare the query with proper binding
+ $sql = "UPDATE pt_co_share_details SET is_active = 0 WHERE pt_id = ? AND id NOT IN ($placeholders)";
+
+ // Merge pt_id with primary keys for binding
+ $params = array_merge([$pt_id], $primaryKeys);
+
+ // Execute the query with bound parameters
+ return db_connect()->query($sql, $params);
+ }
+
+
+ //------------------------------------------------------------------------------------------------
+
+ // Policy Transaction Endorsement
+ public function viewEndorsement()
+ {
+ // echo '';
+ // !dd($this->getEndorsementDataForEdit(17));
+ $bds_edit_pt_id = $this->request->getGet('pt_id') ?? null;
+ $data['tab_name'] = 'Endorsement';
+ $data['page_name'] = 'Endorsement';
+ $data['issuer'] = [1 => 'JIBS', 2 => 'Nhance'];
+ $data['issuer_branch'] = $this->nhanceBranchModel->where('is_active', 1)->findAll();
+ $data['client_type'] = [1 => 'Group', 2 => 'Individual'];
+
+ $data['policy_status'] = [
+ 'under_process' => 'Under Process',
+ 'client_pending' => 'Client Pending',
+ 'insurer_pending' => 'Insurer Pending',
+ 'co_insurer_pending' => 'Co-Insurer Pending',
+ 'tpa_pending' => 'TPA Pending',
+ 'validated' => 'Validated',
+ 'cancelled' => 'Cancelled',
+ 'instalment_pending' => 'Instalment Pending',
+ 'completed' => 'Completed',
+ ];
+
+ $data['invoice_status'] = [
+ 'yet_to_generate' => 'Pending',
+ 'generated' => 'Generated',
+ 'send' => 'Sent',
+ 'recived' => 'Payment Received',
+ ];
+
+ $data['action_type'] = [
+ 'addition' => 'Addition',
+ 'deletion' => 'Deletion',
+ 'addition_deletion' => 'Addition & Deletion',
+ 'si_enhancement' => 'SI Enhancement',
+ 'combo_a_d_si' => 'Combo A, D & SI',
+ 'correction' => 'Correction',
+ 'baby_addition' => 'Baby Addition',
+ 'policy_instalment' => 'Policy Instalment',
+ 'addition_inception' => 'Addition-Inception',
+ 'bds_correction' => 'BDS Correction',
+ 'policy_correction' => 'Policy Correction',
+ 'policy_cancellation' => 'Policy Cancellation',
+ ];
+
+ $data['date_type'] = [
+ 'policy_issue_date' => 'Policy Issue Date',
+ 'policy_start_date' => 'Policy Start Date',
+ 'policy_end_date' => 'Policy End Date',
+ ];
+
+ //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');
+ $status = $this->request->getGet('status');
+
+ $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;
+ $status = (!isset($issuer) || $status === '' || $status === null) ? 0 : $status;
+
+ if($bds_edit_pt_id == null){
+ $data['endorsement_data_list'] = $this->policyTransactionModel->getEndorsementTranctionListData($start_date, $end_date, $client_id, $insurer_id, $policy_type_id, $date_type, $issuer, $status);
+ }else{
+ $data['endorsement_data_list'] = [];
+ }
+ $data['client'] = $this->clientModel->where('is_active', 1)->findAll();
+ $data['policy_types'] = $this->policyTypeModel->where('is_active', 1)->findAll();
+
+ $data['insurer'] = $this->insurerModel->where('is_active', 1)->findAll();
+ // $data['tpa'] = $this->tpaModel->where('is_active', 1)->findAll();
+ $data['insurer_branch'] = $this->insurerBranchModel->getInsurerBranchesWithInsurerNames();
+ $data['tpa'] = $this->tpaBranchModel->getTpaBranchesWithTpaNames();
+ list($policyList, $policyListByClient) = $this->getPolicyForEndorsment();
+
+ $data['endorsementPolicies'] = $policyList;
+ $data['endorsementPolicyListByClient'] = $policyListByClient;
+
+ // dd($data);
+ // print_r($data['endorsementPolicies']);die();
+
+ $this->loadLayout('policy_transaction_endorsement_list', $data);
+ }
+
+ public function createEndorsementPolicy()
+ {
+ $id = $this->request->getPost('id');
+ $data = $this->preparePolicyTransactionData();
+ $data['status'] = 'completed';
+ // print_r($data); die;
+
+ if (!$id) {
+ return $this->insertEndorsementTransaction($data);
+ } else {
+ return $this->updateEndorsementTransaction($id, $data);
+ }
+ }
+
+ private function preparePolicyTransactionData()
+ {
+ $data = $this->request->getPost();
+
+ // echo '';
+ // print_r($data);
+ // die;
+
+ if (!isset($data['policy_with_corr'])) {
+ $data['policy_with_corr'] = 0;
+ } elseif ($data['policy_with_corr']) {
+ $data['policy_with_corr'] = 1;
+ }
+
+ // if (!isset($data['is_cd_reduce_from_bds'])) {
+ // $data['is_cd_reduce_from_bds'] = 0;
+ // } elseif ($data['is_cd_reduce_from_bds']) {
+ // $data['is_cd_reduce_from_bds'] = 1;
+ // }
+
+ if (empty($data['data_received_date'])) {
+ $data['data_received_date'] = null;
+ } else {
+ $data['data_received_date'] = change_date_format($data['data_received_date'], 'd/m/Y', 'Y-m-d');
+ }
+
+ if (empty($data['policy_issue_date'])) {
+ $data['policy_issue_date'] = null;
+ } else {
+ $data['policy_issue_date'] = change_date_format($data['policy_issue_date'], 'd/m/Y', 'Y-m-d');
+ }
+
+ if (empty($data['endorse_eff_date'])) {
+ $data['endorse_eff_date'] = null;
+ } else {
+ $data['endorse_eff_date'] = change_date_format($data['endorse_eff_date'], 'd/m/Y', 'Y-m-d');
+ }
+
+ if (empty($data['install_due_date'])) {
+ $data['install_due_date'] = null;
+ } else {
+ $data['install_due_date'] = change_date_format($data['install_due_date'], 'd/m/Y', 'Y-m-d');
+ }
+
+ if (!empty($data['month'])) {
+ $month = '01/' . $data['month'];
+ $data['month'] = change_date_format($month, 'd/M/Y', 'Y-m-d');
+ }
+
+ if (empty($data['last_action_date'])) {
+ $data['last_action_date'] = null;
+ } else {
+ $data['last_action_date'] = change_date_format($data['last_action_date']);
+ }
+
+ // print_r($data); die;
+
+ // Separate Insurer and TPA Branch IDs and IDs
+ if (isset($data['insurer_id']) && !empty($data['insurer_id'])) {
+ list($data['insurer_branch_id'], $data['insurer_id']) = explode('-', $data['insurer_id']);
+ if (isset($data['tpa']) && !empty($data['tpa'])) {
+ list($data['tpa_branch_id'], $data['tpa_id']) = explode('-', $data['tpa']);
+ }
+ }
+
+ $issue_type = $this->policyTransactionModel
+ ->where('action_type', 'inception')
+ ->where('client_id', $this->request->getPost('client_id'))
+ // ->where('client_policy_id', $this->request->getPost('client_policy_id'))
+ ->where('id', $this->request->getPost('client_policy_id'))
+ ->where('policy_transaction.is_active', 1)
+ ->first();
+
+ $data['tsi'] = generate_tsi_code($issue_type['issue_type'] ?? 1);
+
+ if (!isset($data['client_branch_id']) || $data['client_branch_id'] == "") {
+ $client_branch_id = $issue_type['client_branch_id'];
+ }else{
+ $client_branch_id = $data['client_branch_id'];
+ }
+
+ $data['is_cd_reduce_from_bds'] = (isset($issue_type['policy_type_id']) && $issue_type['policy_type_id'] > 7 && $data['client_type'] == 1) ? 1 : 0;
+
+ // if($data['bro_payable_by'] == ""){
+ // $data['bro_payable_by'] = $issue_type['bro_payable_by'];
+ // }
+
+ if (!$data['id']) {
+
+ $data += [
+ 'issuer' => 2,
+ 'issuer_branch' => $data['issuer_branch'] ?? 1,
+ 'client_type' => $data['client_type'] ?? $issue_type['client_type'] ?? null,
+ 'policy_type_id' => $issue_type['policy_type_id'] ?? null,
+ 'issue_type' => $issue_type['issue_type'] ?? null,
+ 'source_client_policy_id' => $issue_type['source_client_policy_id'] ?? null,
+ 'cd_ac_no' => isset($data['cd_ac_no']) && !empty($data['cd_ac_no']) ? $data['cd_ac_no'] : $issue_type['cd_ac_no'] ?? null,
+ 'cd_ac_pk' => isset($data['cd_ac_pk']) && !empty($data['cd_ac_pk']) ? $data['cd_ac_pk'] : $issue_type['cd_ac_pk'] ?? null,
+ // 'policy_issue_date' => $issue_type['policy_issue_date'] ?? null,
+ 'policy_start_date' => $issue_type['policy_start_date'] ?? null,
+ 'policy_end_date' => $issue_type['policy_end_date'] ?? null,
+ 'revenue_type' => $issue_type['revenue_type'] ?? null,
+ 'co_share' => $issue_type['co_share'] ?? 0,
+ 'bro_payable_by' => $data['bro_payable_by'] == "" ? $issue_type['bro_payable_by'] ?? 0 : $data['bro_payable_by'],
+ 'installment' => $issue_type['installment'] ?? null,
+ 'installment_data' => $issue_type['installment_data'] ?? null,
+ 'location' => $issue_type['location'] ?? null,
+ 'links' => $issue_type['links'] ?? null,
+ 'stage' => $issue_type['stage'] ?? null,
+ 'etat' => $issue_type['etat'] ?? null,
+ 'etat_band' => $issue_type['etat_band'] ?? null,
+ 'edate' => $issue_type['edate'] ?? null,
+ 'renewal_date' => $issue_type['renewal_date'] ?? null,
+ 'rollover_date' => $issue_type['rollover_date'] ?? null,
+ 'policy_holder_name' => $issue_type['policy_holder_name'] ?? null,
+ 'same_as_proposer' => $issue_type['same_as_proposer'] ?? 1,
+ 'ref' => $issue_type['ref'] ?? null,
+ 'spl' => $issue_type['spl'] ?? null,
+ 'fund_received' => $issue_type['fund_received'] ?? null,
+ 'listed_insurers' => $issue_type['listed_insurers'] ?? null,
+ 'ppteam' => $issue_type['ppteam'] ?? null,
+ 'sales_generated_by' => $issue_type['sales_generated_by'] ?? null,
+ 'serviced_by' => $issue_type['serviced_by'] ?? null
+ ];
+
+ $data['client_branch_id'] = $client_branch_id;
+ }
+
+ // print_r($issue_type);
+ // print_r($data);
+ // die;
+
+ return $data;
+ }
+
+ private function insertEndorsementTransaction($data)
+ {
+ $insert = $this->policyTransactionModel->insert($data);
+
+ if ($insert) {
+
+ $this->insertTransactionStatus($insert, $data, 1);
+ $this->handleCompletedStatus($data, $insert);
+ $this->insertOrUpdateCoShareDetails($data, $insert);
+
+ return $this->respond(['status' => true, 'message' => 'Endorsement transaction created successfully'], 200);
+ }
+
+ return $this->respond(['status' => false, 'message' => 'Endorsement transaction creation failed'], 400);
+ }
+
+ private function updateEndorsementTransaction($id, $data)
+ {
+ $old_endorse_data = $this->policyTransactionModel->where('id', $id)->where('is_active', 1)->first();
+ $update = $this->policyTransactionModel->where('id', $id)->set($data)->update();
+
+ if ($update) {
+
+ $this->insertTransactionStatus($id, $data, 1);
+ // if($old_endorse_data['status'] != "completed"){
+ // $this->handleCompletedStatus($data, $id);
+ // }
+ $this->insertOrUpdateCoShareDetails($data, $id);
+
+
+ return $this->respond(['status' => true, 'message' => 'Endorsement transaction updated successfully'], 200);
+ }
+
+ return $this->respond(['status' => false, 'message' => 'Endorsement transaction update failed'], 400);
+ }
+
+ private function handleCompletedStatus($data, $policy_tran_id)
+ {
+ if ($data['client_type'] == 1 && $data['status'] == 'completed' && $data['is_cd_reduce_from_bds'] == 1) {
+
+ $tolamt = (int) $data['total'][0] ?? 0;
+
+ if(!empty($tolamt)){
+ $description = 'The following amount of Rs. ' . round($tolamt, 2) . '/- has been' .
+ ($data['action_type'] == 'deletion' ? ' Credit ' : ' Debit ') . 'from the policy transaction (BDS)';
+
+ $cd_tranction_data = [
+ 'amount' => abs($tolamt),
+ 'sub_type_id' => $data['action_type'] == 'deletion' ? 3 : 4,
+ 'client_id' => $data['client_id'],
+ 'client_policy_id' => $data['client_policy_id'],
+ 'endorsement_no' => null,
+ 'cd_ac_no' => $data['cd_ac_no'] ?? null,
+ 'insurer_id' => $data['insurer_id'],
+ 'description' => $description,
+ 'transaction_type' => $data['action_type'] == 'deletion' ? 'Credit' : 'Debit',
+ 'updated_by' => get_session_userid(),
+ 'event_name' => $data['action_type'],
+ 'is_active' => 1,
+ 'cd_ac_pk' => $data['cd_ac_pk'] ?? null,
+ 'pt_id' => $policy_tran_id ?? null,
];
- // $uploadFilePath = $uploadFilePath . '/' . $uploadedFileName;
+ $result = DepositHelper::saveDeposit($cd_tranction_data, get_session_userid());
- // $GoogleDriveController->uploadFiletoGdrive(client_policy_id: $client_policy_id, doc_type: 'POLICY', file_path: $uploadFilePath, file_name: $uploadedFileName);
-
- // Insert into database
- $insert = $this->PTFileModel->insert($docData);
-
- if ($insert) {
- $uploadData[] = $docData;
+ if(isset($result['success']) && $result['success']){
+ $update_data['ct_tran_id'] = $result['insert_id'];
+ $this->policyTransactionModel->where('id', $policy_tran_id)->set($update_data)->update();
}
}
+
}
}
- // print_r($uploadData); die;
+ public function getEndorsementDataForEdit($id)
+ {
+ $data = $this->policyTransactionModel
+ ->select('
+ policy_transaction.*,
+ clients.short_name as client_short_name,
+ clients.client_type,
+ (
+ select last_action_date
+ from policy_transaction_status
+ where policy_tran_id = policy_transaction.id
+ and status = policy_transaction.status
+ order by id desc
+ limit 1
- // $uploadData = uploadFilesToGoogleDrive($files['file'], $doc_name, $pt_id);
+ ) as last_action_date
+ ')
+ ->join('clients', 'clients.id = policy_transaction.client_id')
+ ->join('client_policy', 'policy_transaction.client_policy_id = client_policy.id', 'left')
+ ->where('policy_transaction.id', $id)
+ ->where('policy_transaction.is_active', 1)
+ ->orderBy('id', 'asc')
+ ->first();
- if (!empty($uploadData)) {
+ $pt_id = null;
- $ptFileQuery = $this->PTFileModel
- ->join('policy_transaction', 'pt_files.pt_id = policy_transaction.id')
- ->where('pt_files.pt_id', $pt_id)
- ->where('pt_files.is_active', 1);
+ if(!empty($data)){
+ $inception_data = $this->policyTransactionModel
+ ->where('policy_no', $data['policy_no'])
+ ->where('client_id', $data['client_id'])
+ ->where('action_type', 'inception')
+ ->first();
+ $pt_id = $inception_data['id'];
+ }
- if (!in_array(get_role_id(), [1, 5]) && empty(array_intersect(user_team(), [MANAGEMENT_TEAM_ID, FINANCE_TEAM_ID, BUSINESS_TEAM_ID]))) {
-
- if (get_role_id() == 4 && in_array(POS_TEAM_ID, user_team())) {
- $ptFileQuery->where('pt_files.created_by', get_session_userid());
- }
+ if (!empty($data['policy_start_date'])) {
+ $data['policy_start_date'] = change_date_format($data['policy_start_date'], 'Y-m-d', 'd/m/Y');
}
- $data['pt_files'] = $ptFileQuery->findAll();
-
- return $this->respond(['status' => true, 'message' => 'File uploaded successfully in G-Drive', 'data' => $data]);
- } else {
- return $this->respond(['status' => false, 'message' => 'Failed to upload file in G-Drive']);
- }
- }
-
- // update Invoice Status
- public function updateInvoiceStatus()
- {
- $ids = $this->request->getPost('ids');
- $ids = json_decode($ids);
-
- // var_dump($ids); die;
-
- $data['invoice_status'] = $this->request->getPost('invoice_status');
- if ($this->request->getPost('invoice_status') == 'generated') {
- $data['invoice_no'] = $this->request->getPost('invoice_no');
- }
-
-
- $update = $this->policyTransactionModel
- ->whereIn('id', $ids)
- ->set($data)
- ->update();
-
-
- if ($update) {
-
- return $this->respond(['status' => true, 'data' => $ids, 'message' => 'Invoice status updated successfully'], 200);
- } else {
- return $this->respond(['status' => true, 'data' => $ids, 'message' => 'Failed to update invoice status'], 200);
- }
- }
-
- public function removeCoShareData($id)
- {
- $this->myLogger->logme('error', 'PT Co Share Detailes Remove function called');
-
- $data = [
- 'updated_by' => get_session_userid(),
- 'is_active' => 0
- ];
-
- $update = $this->PTCOShareDetailsModel->where('id', $id)->set($data)->update();
-
- if ($update) {
- return $this->respond(['status' => true, 'code' => 200, 'message' => 'Data removed successfully'], 200);
- } else {
- return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to remove data'], 200);
- }
- }
-
- public function getPTCOShareCount($client_id, $client_policy_id)
- {
- $totalCount = $this->PTCOShareDetailsModel
- ->select("
- pt_co_share_details.*,
- policy_transaction.bro_payable_by,
- policy_transaction.cd_ac_pk,
- (
- select cd_ac_no
- from cd_master
- where id = policy_transaction.cd_ac_pk
- ) as cd_account_no,
- (
- select balance
- from cash_deposit
- where cd_ac_pk = policy_transaction.cd_ac_pk
- and is_active = 1
- order by id desc
- limit 1
- ) as cd_amount,
- ")
- ->join('policy_transaction', 'policy_transaction.id = pt_co_share_details.pt_id')
- ->where('policy_transaction.client_id', $client_id)
- ->where('policy_transaction.client_policy_id', $client_policy_id)
- ->where('policy_transaction.action_type', 'inception')
- ->where('policy_transaction.is_active', 1)
- ->findAll();
-
- $is_copay_yes = $this->policyTransactionModel
- ->where('client_id', $client_id)
- ->where('client_policy_id', $client_policy_id)
- ->where('action_type', 'inception')
- ->where('is_active', 1)
- ->first();
-
- $cd_ac_no = db_connect()->table('cd_master')->where('id', $is_copay_yes['cd_ac_pk'] ?? null)->get()->getRowArray();
-
- if ($totalCount) {
- return $this->respond(['status' => true, 'code' => 200, 'data' => $totalCount, 'is_copay_yes' => $is_copay_yes, "cd_master_data" => $cd_ac_no], 200);
- } else {
- $insurer_data = $this->clientPolicyModel->where('id', $client_policy_id)->where('is_active', 1)->first();
- return $this->respond(['status' => false, 'code' => 404, 'message' => 'There is no policy inception data.'], 200);
- }
- }
-
- public function checkInvoiceStatus($pt_id)
- {
- $data = $this->policyTransactionModel
- ->join('pt_co_share_details', 'policy_transaction.id = pt_co_share_details.pt_id')
- ->join('insurer_statements', 'pt_co_share_details.statement_id = insurer_statements.id')
- ->where('policy_transaction.id', $pt_id)
- ->where('policy_transaction.is_active', 1)
- ->where('pt_co_share_details.is_active', 1)
- ->where('pt_co_share_details.statement_id IS NOT NULL')
- ->where('insurer_statements.invoice_no IS NOT NULL')
- ->countAllResults();
-
- if ($data) {
- return $this->respond(['status' => true, 'count' => $data, 'code' => 200], 200);
- } else {
- return $this->respond(['status' => false, 'count' => 0, 'message' => 'No Data Found', 'code' => 404], 200);
- }
- }
-
- public function getBasePolicy($client_id, $client_branch_id)
- {
- $data = $this->clientPolicyModel
- ->select('client_policy.*, policy_type.policy_type')
- ->join('policy_type', 'policy_type.id = client_policy.policy_type_id')
- ->where('client_policy.client_id', $client_id)
- ->where('client_policy.client_branch_id', $client_branch_id)
- ->whereIn('client_policy.policy_type_id', [2, 3])
- ->where('client_policy.is_active', 1)
- ->findAll();
-
- if ($data) {
- return $this->respond(['status' => true, 'data' => $data, 'code' => 200], 200);
- } else {
- return $this->respond(['status' => false, 'count' => 0, 'message' => 'No Data Found', 'code' => 404], 200);
- }
- }
-
- //---------------------------------------------------------------------------------------------------
-
- //get BDS Reports data old function
- public function reportBDSOld()
- {
- $data['tab_name'] = 'BDS Report';
- $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',
- ];
-
- $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');
-
- $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;
-
-
- //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);
- // dd($data);
-
- $this->loadLayout('report_bds_filter', $data);
- }
-
- //get BDS Reports data New Function
- public function reportBDS()
- {
-
- $data['tab_name'] = 'BDS Report';
- $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();
- $data['users'] = $this->userModel->where('is_active', 1)->findAll();
- $data['policy_count'] = $this->policyTransactionModel->where('is_active', 1)->countAllResults();
-
-
- //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');
- $user_id = $this->request->getGet('user_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;
- $user_id = (!isset($user_id) || $user_id === '' || $user_id === null) ? 0 : $user_id;
- if ($this->request->is('post')) {
- $isFromDashboard = $this->request->getPost("is_dashboard");
-
- if (isset($isFromDashboard) && !empty($isFromDashboard) && $isFromDashboard == 1) {
- $ids = $this->request->getPost('ids');
-
- $ids = array_filter(explode(',', $ids));
-
- if (!empty($ids)) {
- $idsStr = implode(',', array_map('intval', $ids)); // sanitize IDs to be integers
- $where = "policy_transaction.id IN ($idsStr)";
- } else {
- $where = []; // No valid IDs, return empty result
- }
- }
- // dd($ids);
- }
- //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, $user_id, isset($where) ? $where : '');
- // dd($data);
-
- $this->loadLayout('report_bds_filter', $data);
- }
-
- public function reportVarience()
- {
- $data['tab_name'] = 'Variance Report';
- $data['page_name'] = 'Variance Report';
-
- $data['issuer'] = [1 => 'JIBS', 2 => 'Nhance'];
- $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();
- $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',
- ];
-
- //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');
-
-
- $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;
-
-
- $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);
- // !dd($data['varience_list']);
- $this->loadLayout('variance_report_list', $data);
- }
-
-
- public function reportBusinessList()
- {
- $data['tab_name'] = 'Business Report';
- $data['page_name'] = 'Business Report';
-
- $data['issuer'] = [1 => 'JIBS', 2 => 'Nhance'];
- $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();
- $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',
- ];
-
- //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');
-
- $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;
-
-
- $data['business_list'] = $this->policyTransactionModel->getBusinessReportList($start_date, $end_date, $client_id, $insurer_id, $policy_type_id, $date_type, $issuer);
- $this->loadLayout('business_team_list', $data);
- }
-
-
- public function reportFinanceList()
- {
- $data['tab_name'] = 'Finance Report';
- $data['page_name'] = 'Finance Report';
-
- $data['issuer'] = [1 => 'JIBS', 2 => 'Nhance'];
- $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();
- $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',
- ];
-
- //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');
-
- $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;
-
-
-
- $data['finance_list'] = $this->policyTransactionModel->getFinanceReportList($start_date, $end_date, $client_id, $insurer_id, $policy_type_id, $date_type, $issuer);
- $this->loadLayout('finance_team_list', $data);
- }
-
- public function reportOutstanding()
- {
- $data['tab_name'] = 'Outstanding Report';
- $data['page_name'] = 'Outstanding Report';
-
- $data['issuer'] = [1 => 'JIBS', 2 => 'Nhance'];
- $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();
- $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',
- ];
-
- //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');
- $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]);
-
-
- $insurer_id = (!isset($insurer_id) || $insurer_id === '' || $insurer_id === null) ? 0 : $insurer_id;
- $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, $insurer_id, $insurer_branch_id);
- // dd($this->policyTransactionModel->getLastQuery());
- // dd($data);
- $this->loadLayout('outstanding_report_list', $data);
- }
-
- //---------------------------------------------------------------------------------------------------
-
- //insurer statement list page
- public function statementList()
- {
- // dd($this->validateInsurerStatement(['file_id' => 49])); // for check validateInsurerStatementfunction with hard coded file id always un command
- $data['insurers'] = $this->insurerModel->where('is_active',1)->findAll();
- $today = date('Y-m-d');
- $fromday = $from_date = date('Y-m-d', strtotime('-180 days', strtotime($today)));
- // echo $fromday;die();
- $data['invoice_status_array'] = $this->invoiceStatus;
- $data['insurers'] = $this->insurerBranchModel->getInsurerBranchesWithInsurerNames();
-
- // dd( $data['insurers']);
- $data['insurer_statement_list'] = $this->insurerStatements
- ->select(
- 'insurer_statements.*,
- insurers.name AS insurer_name,
- insurers.short_name,
- user_profiles.first_name,
- insurer_branch.branch_code,
- (SELECT SUM(pt_co_share_details.exp_amt)
- FROM pt_co_share_details
- 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) + 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
- ) AS received_inv_amt'
- )
- ->join('insurers', 'insurer_statements.insurer_id = insurers.id')
- ->join('insurer_branch', 'insurer_statements.branch_id = insurer_branch.id')
- ->join('user_profiles', 'insurer_statements.created_by = user_profiles.id')
- ->where('insurer_statements.is_active', 1)
- // ->where('insurer_statements.file_status','success')
- ->where('date(insurer_statements.created_at) >= ', $from_date)
- ->where('date(insurer_statements.created_at) <= ', $today)
- ->orderBy('insurer_statements.id', 'DESC')
- ->findAll();
-
- // dd( $this->insurerStatements->getLastQuery());
- $data['tab_name'] = 'Statement Upload';
- $data['page_name'] = 'Statement Upload';
-
- $this->loadLayout('insurer_statement_list', $data);
- }
-
- // public function failedStatementList(){
- // $today = date('Y-m-d');
- // $fromday = $from_date = date('Y-m-d', strtotime('-180 days', strtotime($today)));
- // // echo $fromday;die();
- // $data['invoice_status_array'] = $this->invoiceStatus;
- // $data['insurers'] = $this->insurerBranchModel ->getInsurerBranchesWithInsurerNames();
-
- // // dd( $data['insurers']);
- // $data['insurer_statement_list'] = $this->insurerStatements
- // ->select('insurer_statements.*,
- // insurers.name AS insurer_name,
- // insurers.short_name,
- // user_profiles.first_name,
- // insurer_branch.branch_code,
- // (SELECT SUM(pt_co_share_details.exp_amt)
- // FROM pt_co_share_details
- // 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) + 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
- // ) AS received_inv_amt'
- // )
- // ->join('insurers', 'insurer_statements.insurer_id = insurers.id')
- // ->join('insurer_branch', 'insurer_statements.branch_id = insurer_branch.id')
- // ->join('user_profiles', 'insurer_statements.created_by = user_profiles.id')
- // ->where('insurer_statements.is_active', 1)
- // ->where('insurer_statements.file_status','failed')
- // ->where('date(insurer_statements.created_at) >= ', $from_date)
- // ->where('date(insurer_statements.created_at) <= ', $today)
- // ->orderBy('insurer_statements.id', 'DESC')
- // ->findAll();
- // if($data['insurer_statement_list']){
- // return $this->respond(['status' => true, 'code' => 200,'data'=>$data ], 200);
- // }else{
- // return $this->respond(['status'=>false,'message'=>'Data Not Fount'],404);
- // }
-
- // }
-
- public function uploadInsurerStatement()
- {
-
- //validate uploaded file
- $filename = '';
- $validated = $this->validate([
- 'statement' => [
- 'uploaded[statement]',
- 'mime_in[statement,application/vnd.ms-excel,application/vnd,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.oasis.opendocument.spreadsheet]',
- 'max_size[statement,16384]',
- ],
- ]);
- // $this->createStatementFolder();
- if ($validated) {
- $avatar = $this->request->getFile('statement');
- if (!$avatar) {
- $this->myLogger->logme("error", 'Statement File not found');
- return $this->respond(['dataStatus' => false, 'code' => 400, 'message' => 'File not found'], 400);
+ if (!empty($data['policy_end_date'])) {
+ $data['policy_end_date'] = change_date_format($data['policy_end_date'], 'Y-m-d', 'd/m/Y');
}
- $is_moved = $avatar->move(WRITEPATH . 'uploads/statements/');
- if ($is_moved) {
- $filename = $avatar->getName();
- // Handle successful upload, e.g., log success or further processing
- $this->myLogger->logme("error", 'Statement File moved successful');
- } else {
- $this->myLogger->logme("error", 'Statement File move failed');
- return $this->respond(['dataStatus' => false, 'code' => 500, 'message' => 'File move failed'], 500);
+ if (!empty($data['data_received_date'])) {
+ $data['data_received_date'] = change_date_format($data['data_received_date'], 'Y-m-d', 'd/m/Y');
}
- } else {
- $this->myLogger->logme("error", 'Statement Upload failed Invalid file');
- return $this->respond(['dataStatus' => false, 'code' => 404, 'message' => 'Invalid file'], 404);
- }
- //process post variable entry in file table
- $loggedInUserID = get_session_userid();
- // dd($loggedInUserID);
- // $loggedInUserID = 8;
-
- $insurer = $this->request->getPost('insurer');
-
- $insurer_id = explode('-', $insurer)[0];
- $branch_id = explode('-', $insurer)[1];
- // print_r($insurer_id);
- // print_r($branch_id);
- // die();
- $month = $this->request->getPost('statement_month');
- $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, '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
- $validation_result = $this->validateInsurerStatement(['file_id' => $file_id]);
- //update file content to DB
- if ($validation_result['status']) {
- $this->updateInsurerStatement(['file_id' => $file_id]);
- }
-
- if (!isset($file_id) || !$validation_result['status']) {
- return $this->respond(['dataStatus' => false, 'code' => 404, 'message' => 'file not uploaded', 'error_data' => $validation_result['error_data'], 'error_code' => $validation_result['error_code']], 200);
- }
-
- if (isset($file_id) || $validation_result['status']) {
- $this->insurerStatements->where('id', $file_id)->set(['invoice_status' => 'pending'])->update();
- }
-
-
-
- return $this->respond(['dataStatus' => true, 'code' => 200, 'data' => 'file upload success'], 200);
- }
-
- public function createStatementFolder()
- {
- $folderPath = WRITEPATH . 'uploads/statements/';
-
- // Check if the folder doesn't exist
- if (!file_exists($folderPath)) {
- // Create the folder
- if (mkdir($folderPath, 0777, true)) {
- $this->myLogger->logme('error', 'statement upload folder created successfully');
-
- // Set permissions to a+rwx (read, write, execute for all)
- chmod($folderPath, 0777);
- $this->myLogger->logme('error', 'Permissions set to a+rwx.');
- } else {
- // echo "Failed to create folder.";
- $this->myLogger->logme('error', 'Failed to create statement upload folder.');
+ if (!empty($data['policy_issue_date'])) {
+ $data['policy_issue_date'] = change_date_format($data['policy_issue_date'], 'Y-m-d', 'd/m/Y');
}
- } else {
- $this->myLogger->logme('error', 'upload folder exists.');
- }
- }
- public function validateInsurerStatement($params)
- {
- helper('excel_util_helper');
- //get file info
- $file_id = $params['file_id'];
- $file = $this->insurerStatements->find($file_id);
- // dd($file);
- $date = new \DateTime($file['month']);
+ if (!empty($data['endorse_eff_date'])) {
+ $data['endorse_eff_date'] = change_date_format($data['endorse_eff_date'], 'Y-m-d', 'd/m/Y');
+ }
- $month = $date->format('m');
- $year = $date->format('Y');
+ if (!empty($data['install_due_date'])) {
+ $data['install_due_date'] = change_date_format($data['install_due_date'], 'Y-m-d', 'd/m/Y');
+ }
- $error_data = ['error_code' => '', 'error_data' => []];
- $status = 'success';
- $ret_status = true;
- // dd($month.'-'.$year);
- $return = [];
- if (!isset($file)) {
- //file not found in DB
- return array('status' => false, 'msg' => 'statement file not found in DB');
- }
- $file_name_with_path = WRITEPATH . "/uploads/statements/" . $file['file_name'];
+ if (!empty($data['last_action_date'])) {
+ $data['last_action_date'] = change_date_format($data['last_action_date'], 'Y-m-d', 'd/m/Y');
+ }
- //check physical file
- if (!file_exists($file_name_with_path)) {
- //file not found update status and reason
- $message = "Physcial file not found";
- // echo $message;
- $this->myLogger->logme('error', ($message . ' for statement file id ' . $file_id));
- $this->insurerStatements->where('id', $file_id)->set(['file_status' => 'failed', 'reason' => json_encode(['error_code' => 0, 'error_data' => $message])])->update();
- return array('status' => false, 'error_code' => 0); //0 - Physcial file not found
- }
+ if (!empty($data['month'])) {
+ $data['month'] = change_date_format($data['month'], 'Y-m-d', 'M/Y');
+ }
- //get excel data to php array
- $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file_name_with_path);
- $sheet = $spreadsheet->getActiveSheet();
+ // print_r($data); die;
- $highestRowAndColumn = $sheet->getHighestRowAndColumn();
- // dd($highestRowAndColumn);
- $excel_data = $sheet->rangeToArray('A1:' . $highestRowAndColumn['column'] . $highestRowAndColumn['row']);
- unset($excel_data[0]);
- $excel_data = ExcelSanitizeHelper::sanitizeArrayData($excel_data);
- // Kint::dump($excel_data);die();
- //get no of line items and update in DB
- $line_items = 0;
- // get uploaded month transactions data
- $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();
+ //get PT Co-Share Details
+ $data['pt_co_share_details'] = $this->PTCOShareDetailsModel
-
- // 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) {
-
- // $excel_row = ExcelSanitizeHelper::sanitizeArrayData($excel_row);
- $is_source_found = 0;
- // Kint::dump($excel_key,$excel_row[1],$excel_row[2]);
- $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
- $policy_no = preg_replace( '/[\x{200B}\x{200C}\x{200D}\x{FEFF}\x{00A0}\x{200E}\x{200F}\x{202A}-\x{202E}]/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
- $endorsement_no = preg_replace( '/[\x{200B}\x{200C}\x{200D}\x{FEFF}\x{00A0}\x{200E}\x{200F}\x{202A}-\x{202E}]/u', '', $excel_row[2]); //policy_end_date from excel
-
- // Kint::dump($excel_key,$policy_no,$endorsement_no,$policy_start_date,$policy_end_date);//die();
- foreach ($source_data as $source_key => $source_row) {
- $source_endorsement_no = $source_row['endorsement_no'] !== null ? $source_row['endorsement_no'] : null;
- // Kint::dump($source_row, $source_endorsement_no, $policy_no, $endorsement_no);
+ ->select("
+ pt_co_share_details.*,
- // 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 (($policy_no == $source_row['policy_no']) && $endorsement_no == $source_endorsement_no)
- {
- $is_source_found = 1;
- $line_items = $line_items + 1;
- unset($source_data[$source_key]);
- continue 2;
- }
- }
+ (
+ 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,
+
+ (
+ SELECT
+ SUM(actual_bp_amt)
+ FROM
+ co_share_stmt_details
+ WHERE
+ co_share_id = pt_co_share_details.id
+ AND is_active = 1
+
+ ) AS actual_bp_amount,
+
+ (
+ SELECT
+ SUM(actual_tp_amt)
+ FROM
+ co_share_stmt_details
+ WHERE
+ co_share_id = pt_co_share_details.id
+ AND is_active = 1
+
+ ) AS actual_tp_amount,
+
+ (
+ SELECT
+ SUM(actual_tep_amt)
+ FROM
+ co_share_stmt_details
+ WHERE
+ co_share_id = pt_co_share_details.id
+ AND is_active = 1
+
+ ) AS actual_tep_amount,
+
+ (
+ SELECT
+ SUM(actual_bp_per)
+ FROM
+ co_share_stmt_details
+ WHERE
+ co_share_id = pt_co_share_details.id
+ AND is_active = 1
+
+ ) AS actual_bp_percentage,
+
+ (
+ SELECT
+ SUM(actual_tp_per)
+ FROM
+ co_share_stmt_details
+ WHERE
+ co_share_id = pt_co_share_details.id
+ AND is_active = 1
+
+ ) AS actual_tp_percentage,
+
+ (
+ SELECT
+ SUM(actual_tep_per)
+ FROM
+ co_share_stmt_details
+ WHERE
+ co_share_id = pt_co_share_details.id
+ AND is_active = 1
+
+ ) AS actual_tep_percentage,
+
+
+ (
+ SELECT
+ SUM(actual_bp_brokerage_amt)
+ FROM
+ co_share_stmt_details
+ WHERE
+ co_share_id = pt_co_share_details.id
+ AND is_active = 1
+
+ ) AS actual_bp_brokerage_amount,
+
+
+ (
+ SELECT
+ SUM(actual_tp_brokerage_amt)
+ FROM
+ co_share_stmt_details
+ WHERE
+ co_share_id = pt_co_share_details.id
+ AND is_active = 1
+
+ ) AS actual_tp_brokerage_amount,
+
+
+ (
+ SELECT
+ SUM(actual_tep_brokerage_amt)
+ FROM
+ co_share_stmt_details
+ WHERE
+ co_share_id = pt_co_share_details.id
+ AND is_active = 1
+
+ ) AS actual_tep_brokerage_amount
+
+ ")
+ ->where('pt_id', $id)
+ ->where('is_active', 1)
+ ->orderBy('id', 'asc')
+ ->findAll();
- 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
- }
+ // print_r($data['endorse_eff_date']); die;
+
+ $pt_bp_amt = $this->PTCOShareDetailsModel
+ ->select('bp_amt, amount')
+ ->where('pt_id', $id)
+ ->where('co_share_type', 1)
+ ->where('is_active', 1)
+ ->first();
+
+ // dd(db_connect()->getLastQuery() ,$pt_bp_amt);
+ $data['base_cd_amount'] = $pt_bp_amt['amount'] ?? null;
+
+ if ($data) {
+ return $this->respond(['status' => true, 'data' => $data, 'pt_id' => $pt_id], 200);
+ } else {
+ return $this->respond(['status' => false], 200);
}
}
- // dd($error_data);
+ //------------------------------------------------------------------------------------------------
- if ($error_data['error_code']) {
- $status = 'failed';
- $ret_status = false;
- }
- //update in DB
- $this->insurerStatements->where('id', $file_id)->set(['line_items' => $line_items, 'file_status' => $status, 'reason' => json_encode($error_data)])->update();
- return array('status' => $ret_status, 'error_code' => $error_data['error_code'], 'error_data' => $error_data['error_data']);
- }
+ //file upload function
+ public function uploadFile()
+ {
+ $GoogleDriveController = new GoogleDriveController();
+ $files = $this->request->getFiles();
+ $doc_name = $this->request->getPost('doc_name[]');
+ $pt_id = $this->request->getPost('pt_id');
+ $client_policy_id = $this->request->getPost('client_policy_id');
+ $data = $this->request->getPost();
+ $uploadFilePath = WRITEPATH . 'uploads/client_kyc_documents';
- public function updateInsurerStatement($params)
- {
- helper('excel_util_helper');
- //get file info
- $file_id = $params['file_id'];
- $file = $this->insurerStatements->find($file_id);
- // dd($file);
- $date = new \DateTime($file['month']);
+ $uploadData = [];
- $month = $date->format('m');
- $year = $date->format('Y');
+ foreach ($data['doc_name'] as $key => $docName) {
- $error_data = ['error_code' => '', 'error_data' => []];
- $status = 'success';
- $ret_status = true;
- // dd($month.'-'.$year);
- $return = [];
- if (!isset($file)) {
- //file not found in DB
- return array('status' => false, 'msg' => 'statement file not found in DB');
- }
- $file_name_with_path = WRITEPATH . "/uploads/statements/" . $file['file_name'];
+ // Get the corresponding file for this document name
+ $file = $files['file'][$key];
- //check physical file
- if (!file_exists($file_name_with_path)) {
- //file not found update status and reason
- $message = "Physcial file not found";
- // echo $message;
- $this->myLogger->logme('error', ($message . ' for statement file id ' . $file_id));
- $this->insurerStatements->where('id', $file_id)->set(['file_status' => 'failed', 'reason' => json_encode(['error_code' => 0, 'error_data' => $message])])->update();
- return array('status' => false, 'error_code' => 0); //0 - Physcial file not found
- }
+ if (!empty($docName) && $file->isValid() && !$file->hasMoved()) {
- //get excel data to php array
- $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file_name_with_path);
- $sheet = $spreadsheet->getActiveSheet();
+ // Upload the file
+ $uploadedFileName = file_Upload($file, $uploadFilePath);
- $highestRowAndColumn = $sheet->getHighestRowAndColumn();
- // dd($highestRowAndColumn);
- $excel_data = $sheet->rangeToArray('A1:' . $highestRowAndColumn['column'] . $highestRowAndColumn['row']);
- unset($excel_data[0]);
- $excel_data = ExcelSanitizeHelper::sanitizeArrayData($excel_data);
- // dd($excel_data);
- //get no of line items and update in DB
- $line_items = count($excel_data);
- // get uploaded month transactions data
- $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);
- // die;
- // check policy no,insurer and etc in DB for this month
- // if all good return true, otherwise return false with messssage
- $data_to_update = [];
- foreach ($excel_data as $excel_key => $excel_row) {
- $is_row_empty = check_row_is_empty_or_null($excel_row);
- if (!$is_row_empty) {
+ if ($uploadedFileName) {
+ // Prepare data for each document upload
+ $docData = [
+ 'pt_id' => $pt_id,
+ 'doc_name' => $docName,
+ 'file_name' => $uploadedFileName,
+ 'created_by' => get_session_userid(),
+ ];
- $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
- $policy_no = preg_replace('/[\x{200C}\x{200B}]/u', '', $excel_row[1]); //
- $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
+ // $uploadFilePath = $uploadFilePath . '/' . $uploadedFileName;
- foreach ($source_data as $source_key => $source_row) {
- // 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'] : null;
- // 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']) {
- if (($policy_no == $source_row['policy_no']) && $endorsement_no == $source_endorsement_no) {
- $is_source_found = 1;
+ // $GoogleDriveController->uploadFiletoGdrive(client_policy_id: $client_policy_id, doc_type: 'POLICY', file_path: $uploadFilePath, file_name: $uploadedFileName);
- //calculate percentage first
- $total_amt = 0;
+ // Insert into database
+ $insert = $this->PTFileModel->insert($docData);
- $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 != "")) {
- $total_amt += $actual_bp_brokerage;
- //percentage reverse calculation
- if (($actual_bp_per == 0 || $actual_bp_per == 0) && !empty($actual_bp_amt)) {
- $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;
+ if ($insert) {
+ $uploadData[] = $docData;
}
-
- $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 == "") && !empty($actual_tp_amt)) {
- $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 == "") && !empty($actual_tep_amt)) {
- $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;
}
}
}
+
+ // print_r($uploadData); die;
+
+ // $uploadData = uploadFilesToGoogleDrive($files['file'], $doc_name, $pt_id);
+
+ if (!empty($uploadData)) {
+
+ $ptFileQuery = $this->PTFileModel
+ ->join('policy_transaction', 'pt_files.pt_id = policy_transaction.id')
+ ->where('pt_files.pt_id', $pt_id)
+ ->where('pt_files.is_active', 1);
+
+ if (!in_array(get_role_id(), [1, 5]) && empty(array_intersect(user_team(), [MANAGEMENT_TEAM_ID, FINANCE_TEAM_ID, BUSINESS_TEAM_ID]))) {
+
+ if (get_role_id() == 4 && in_array(POS_TEAM_ID, user_team())) {
+ $ptFileQuery->where('pt_files.created_by', get_session_userid());
+ }
+ }
+
+ $data['pt_files'] = $ptFileQuery->findAll();
+
+ return $this->respond(['status' => true, 'message' => 'File uploaded successfully in G-Drive', 'data' => $data]);
+ } else {
+ return $this->respond(['status' => false, 'message' => 'Failed to upload file in G-Drive']);
+ }
}
- // dd($data_to_update);
- $this->coShareStmtDetailsModel->insertBatch($data_to_update, 'id');
- // dd($data_to_update);
- // if($error_data['error_code'])
- // {
- // $status = 'failed';
- // $ret_status = false;
+
+ // update Invoice Status
+ public function updateInvoiceStatus()
+ {
+ $ids = $this->request->getPost('ids');
+ $ids = json_decode($ids);
+
+ // var_dump($ids); die;
+
+ $data['invoice_status'] = $this->request->getPost('invoice_status');
+ if ($this->request->getPost('invoice_status') == 'generated') {
+ $data['invoice_no'] = $this->request->getPost('invoice_no');
+ }
+
+
+ $update = $this->policyTransactionModel
+ ->whereIn('id', $ids)
+ ->set($data)
+ ->update();
+
+
+ if ($update) {
+
+ return $this->respond(['status' => true, 'data' => $ids, 'message' => 'Invoice status updated successfully'], 200);
+ } else {
+ return $this->respond(['status' => true, 'data' => $ids, 'message' => 'Failed to update invoice status'], 200);
+ }
+ }
+
+ public function removeCoShareData($id)
+ {
+ $this->myLogger->logme('error', 'PT Co Share Detailes Remove function called');
+
+ $data = [
+ 'updated_by' => get_session_userid(),
+ 'is_active' => 0
+ ];
+
+ $update = $this->PTCOShareDetailsModel->where('id', $id)->set($data)->update();
+
+ if ($update) {
+ return $this->respond(['status' => true, 'code' => 200, 'message' => 'Data removed successfully'], 200);
+ } else {
+ return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to remove data'], 200);
+ }
+ }
+
+ public function getPTCOShareCount($client_id, $client_policy_id)
+ {
+ $totalCount = $this->PTCOShareDetailsModel
+ ->select("
+ pt_co_share_details.*,
+ policy_transaction.bro_payable_by,
+ policy_transaction.cd_ac_pk,
+ (
+ select cd_ac_no
+ from cd_master
+ where id = policy_transaction.cd_ac_pk
+ ) as cd_account_no,
+ (
+ select balance
+ from cash_deposit
+ where cd_ac_pk = policy_transaction.cd_ac_pk
+ and is_active = 1
+ order by id desc
+ limit 1
+ ) as cd_amount,
+ ")
+ ->join('policy_transaction', 'policy_transaction.id = pt_co_share_details.pt_id')
+ ->where('policy_transaction.client_id', $client_id)
+ // ->where('policy_transaction.client_policy_id', $client_policy_id)
+ ->where('policy_transaction.id', $client_policy_id)
+ ->where('policy_transaction.action_type', 'inception')
+ ->where('policy_transaction.is_active', 1)
+ ->findAll();
+
+ $is_copay_yes = $this->policyTransactionModel
+ ->where('client_id', $client_id)
+ // ->where('client_policy_id', $client_policy_id)
+ ->where('id', $client_policy_id)
+ ->where('action_type', 'inception')
+ ->where('is_active', 1)
+ ->first();
+
+ $cd_ac_no = db_connect()->table('cd_master')->where('id', $is_copay_yes['cd_ac_pk'] ?? null)->get()->getRowArray();
+
+ if ($totalCount) {
+ return $this->respond(['status' => true, 'code' => 200, 'data' => $totalCount, 'is_copay_yes' => $is_copay_yes, "cd_master_data" => $cd_ac_no], 200);
+ } else {
+ $insurer_data = $this->clientPolicyModel->where('id', $client_policy_id)->where('is_active', 1)->first();
+ return $this->respond(['status' => false, 'code' => 404, 'message' => 'There is no policy inception data.'], 200);
+ }
+ }
+
+ public function checkInvoiceStatus($pt_id)
+ {
+ $data = $this->policyTransactionModel
+ ->join('pt_co_share_details', 'policy_transaction.id = pt_co_share_details.pt_id')
+ ->join('insurer_statements', 'pt_co_share_details.statement_id = insurer_statements.id')
+ ->where('policy_transaction.id', $pt_id)
+ ->where('policy_transaction.is_active', 1)
+ ->where('pt_co_share_details.is_active', 1)
+ ->where('pt_co_share_details.statement_id IS NOT NULL')
+ ->where('insurer_statements.invoice_no IS NOT NULL')
+ ->countAllResults();
+
+ if ($data) {
+ return $this->respond(['status' => true, 'count' => $data, 'code' => 200], 200);
+ } else {
+ return $this->respond(['status' => false, 'count' => 0, 'message' => 'No Data Found', 'code' => 404], 200);
+ }
+ }
+
+ public function getBasePolicy($client_id, $client_branch_id)
+ {
+ $data = $this->clientPolicyModel
+ ->select('client_policy.*, policy_type.policy_type')
+ ->join('policy_type', 'policy_type.id = client_policy.policy_type_id')
+ ->where('client_policy.client_id', $client_id)
+ ->where('client_policy.client_branch_id', $client_branch_id)
+ ->whereIn('client_policy.policy_type_id', [2, 3])
+ ->where('client_policy.is_active', 1)
+ ->findAll();
+
+ if ($data) {
+ return $this->respond(['status' => true, 'data' => $data, 'code' => 200], 200);
+ } else {
+ return $this->respond(['status' => false, 'count' => 0, 'message' => 'No Data Found', 'code' => 404], 200);
+ }
+ }
+
+ //---------------------------------------------------------------------------------------------------
+
+ //get BDS Reports data old function
+ public function reportBDSOld()
+ {
+ $data['tab_name'] = 'BDS Report';
+ $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',
+ ];
+
+ $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');
+
+ $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;
+
+
+ //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);
+ // dd($data);
+
+ $this->loadLayout('report_bds_filter', $data);
+ }
+
+ //get BDS Reports data New Function
+ public function reportBDS()
+ {
+
+ $data['tab_name'] = 'BDS Report';
+ $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();
+ $data['users'] = $this->userModel->where('is_active', 1)->findAll();
+ $data['policy_count'] = $this->policyTransactionModel->where('is_active', 1)->countAllResults();
+
+
+ //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');
+ $user_id = $this->request->getGet('user_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;
+ $user_id = (!isset($user_id) || $user_id === '' || $user_id === null) ? 0 : $user_id;
+ if ($this->request->is('post')) {
+ $isFromDashboard = $this->request->getPost("is_dashboard");
+
+ if (isset($isFromDashboard) && !empty($isFromDashboard) && $isFromDashboard == 1) {
+ $ids = $this->request->getPost('ids');
+
+ $ids = array_filter(explode(',', $ids));
+
+ if (!empty($ids)) {
+ $idsStr = implode(',', array_map('intval', $ids)); // sanitize IDs to be integers
+ $where = "policy_transaction.id IN ($idsStr)";
+ } else {
+ $where = []; // No valid IDs, return empty result
+ }
+ }
+ // dd($ids);
+ }
+ //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, $user_id, isset($where) ? $where : '');
+ // dd($data);
+
+ $this->loadLayout('report_bds_filter', $data);
+ }
+
+ public function reportVarience()
+ {
+ $data['tab_name'] = 'Variance Report';
+ $data['page_name'] = 'Variance Report';
+
+ $data['issuer'] = [1 => 'JIBS', 2 => 'Nhance'];
+ $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();
+ $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',
+ ];
+
+ //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');
+
+
+ $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;
+
+
+ $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);
+ // !dd($data['varience_list']);
+ $this->loadLayout('variance_report_list', $data);
+ }
+
+
+ public function reportBusinessList()
+ {
+ $data['tab_name'] = 'Business Report';
+ $data['page_name'] = 'Business Report';
+
+ $data['issuer'] = [1 => 'JIBS', 2 => 'Nhance'];
+ $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();
+ $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',
+ ];
+
+ //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');
+
+ $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;
+
+
+ $data['business_list'] = $this->policyTransactionModel->getBusinessReportList($start_date, $end_date, $client_id, $insurer_id, $policy_type_id, $date_type, $issuer);
+ $this->loadLayout('business_team_list', $data);
+ }
+
+
+ public function reportFinanceList()
+ {
+ $data['tab_name'] = 'Finance Report';
+ $data['page_name'] = 'Finance Report';
+
+ $data['issuer'] = [1 => 'JIBS', 2 => 'Nhance'];
+ $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();
+ $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',
+ ];
+
+ //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');
+
+ $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;
+
+
+
+ $data['finance_list'] = $this->policyTransactionModel->getFinanceReportList($start_date, $end_date, $client_id, $insurer_id, $policy_type_id, $date_type, $issuer);
+ $this->loadLayout('finance_team_list', $data);
+ }
+
+ public function reportOutstanding()
+ {
+ $data['tab_name'] = 'Outstanding Report';
+ $data['page_name'] = 'Outstanding Report';
+
+ $data['issuer'] = [1 => 'JIBS', 2 => 'Nhance'];
+ $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();
+ $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',
+ ];
+
+ //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');
+ $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]);
+
+
+ $insurer_id = (!isset($insurer_id) || $insurer_id === '' || $insurer_id === null) ? 0 : $insurer_id;
+ $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, $insurer_id, $insurer_branch_id);
+ // dd($this->policyTransactionModel->getLastQuery());
+ // dd($data);
+ $this->loadLayout('outstanding_report_list', $data);
+ }
+
+ //---------------------------------------------------------------------------------------------------
+
+ //insurer statement list page
+ public function statementList()
+ {
+ // dd($this->updateInsurerStatement(['file_id' => 133])); // for check validateInsurerStatementfunction with hard coded file id always un command
+ $data['insurers'] = $this->insurerModel->where('is_active',1)->findAll();
+ $today = date('Y-m-d');
+ $fromday = $from_date = date('Y-m-d', strtotime('-180 days', strtotime($today)));
+ // echo $fromday;die();
+ $data['invoice_status_array'] = $this->invoiceStatus;
+ $data['insurers'] = $this->insurerBranchModel->getInsurerBranchesWithInsurerNames();
+
+ // dd( $data['insurers']);
+ $data['insurer_statement_list'] = $this->insurerStatements
+ ->select(
+ 'insurer_statements.*,
+ insurers.name AS insurer_name,
+ insurers.short_name,
+ user_profiles.first_name,
+ insurer_branch.branch_code,
+ (SELECT SUM(pt_co_share_details.exp_amt)
+ FROM pt_co_share_details
+ 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) + 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
+ ) AS received_inv_amt'
+ )
+ ->join('insurers', 'insurer_statements.insurer_id = insurers.id')
+ ->join('insurer_branch', 'insurer_statements.branch_id = insurer_branch.id')
+ ->join('user_profiles', 'insurer_statements.created_by = user_profiles.id')
+ ->where('insurer_statements.is_active', 1)
+ // ->where('insurer_statements.file_status','success')
+ ->where('date(insurer_statements.created_at) >= ', $from_date)
+ ->where('date(insurer_statements.created_at) <= ', $today)
+ ->orderBy('insurer_statements.id', 'DESC')
+ ->findAll();
+
+ // dd( $this->insurerStatements->getLastQuery());
+ $data['tab_name'] = 'Statement Upload';
+ $data['page_name'] = 'Statement Upload';
+
+ $this->loadLayout('insurer_statement_list', $data);
+ }
+
+ // public function failedStatementList(){
+ // $today = date('Y-m-d');
+ // $fromday = $from_date = date('Y-m-d', strtotime('-180 days', strtotime($today)));
+ // // echo $fromday;die();
+ // $data['invoice_status_array'] = $this->invoiceStatus;
+ // $data['insurers'] = $this->insurerBranchModel ->getInsurerBranchesWithInsurerNames();
+
+ // // dd( $data['insurers']);
+ // $data['insurer_statement_list'] = $this->insurerStatements
+ // ->select('insurer_statements.*,
+ // insurers.name AS insurer_name,
+ // insurers.short_name,
+ // user_profiles.first_name,
+ // insurer_branch.branch_code,
+ // (SELECT SUM(pt_co_share_details.exp_amt)
+ // FROM pt_co_share_details
+ // 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) + 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
+ // ) AS received_inv_amt'
+ // )
+ // ->join('insurers', 'insurer_statements.insurer_id = insurers.id')
+ // ->join('insurer_branch', 'insurer_statements.branch_id = insurer_branch.id')
+ // ->join('user_profiles', 'insurer_statements.created_by = user_profiles.id')
+ // ->where('insurer_statements.is_active', 1)
+ // ->where('insurer_statements.file_status','failed')
+ // ->where('date(insurer_statements.created_at) >= ', $from_date)
+ // ->where('date(insurer_statements.created_at) <= ', $today)
+ // ->orderBy('insurer_statements.id', 'DESC')
+ // ->findAll();
+ // if($data['insurer_statement_list']){
+ // return $this->respond(['status' => true, 'code' => 200,'data'=>$data ], 200);
+ // }else{
+ // return $this->respond(['status'=>false,'message'=>'Data Not Fount'],404);
+ // }
+
// }
- //update in DB
- $this->insurerStatements->where('id', $file_id)->set(['file_status' => $status, 'reason' => json_encode($error_data), 'invoice_status' => 'pending'])->update();
- return array('status' => $ret_status, 'error_code' => $error_data['error_code'], 'error_data' => $error_data['error_data']);
- }
- public function getInvoicePaymentDetails()
- {
- $statement_id = $this->request->getUri()->getSegment(4);
+ public function uploadInsurerStatement()
+ {
- $inv_details = $this->insurerStatements->find($statement_id);
- $inv_payment_details = $this->invPaymentDetailsModel
- ->where('statement_id', $statement_id)
- ->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')
+ //validate uploaded file
+ $filename = '';
+ $validated = $this->validate([
+ 'statement' => [
+ 'uploaded[statement]',
+ 'mime_in[statement,application/vnd.ms-excel,application/vnd,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.oasis.opendocument.spreadsheet]',
+ 'max_size[statement,16384]',
+ ],
+ ]);
+ // $this->createStatementFolder();
+ if ($validated) {
+ $avatar = $this->request->getFile('statement');
+ if (!$avatar) {
+ $this->myLogger->logme("error", 'Statement File not found');
+ return $this->respond(['dataStatus' => false, 'code' => 400, 'message' => 'File not found'], 400);
+ }
+
+ $is_moved = $avatar->move(WRITEPATH . 'uploads/statements/');
+ if ($is_moved) {
+ $filename = $avatar->getName();
+ // Handle successful upload, e.g., log success or further processing
+ $this->myLogger->logme("error", 'Statement File moved successful');
+ } else {
+ $this->myLogger->logme("error", 'Statement File move failed');
+ return $this->respond(['dataStatus' => false, 'code' => 500, 'message' => 'File move failed'], 500);
+ }
+ } else {
+ $this->myLogger->logme("error", 'Statement Upload failed Invalid file');
+ return $this->respond(['dataStatus' => false, 'code' => 404, 'message' => 'Invalid file'], 404);
+ }
+
+ //process post variable entry in file table
+ $loggedInUserID = get_session_userid();
+ // dd($loggedInUserID);
+ // $loggedInUserID = 8;
+
+ $insurer = $this->request->getPost('insurer');
+
+ $insurer_id = explode('-', $insurer)[0];
+ $branch_id = explode('-', $insurer)[1];
+ // print_r($insurer_id);
+ // print_r($branch_id);
+ // die();
+ $month = $this->request->getPost('statement_month');
+ $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, '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
+ $validation_result = $this->validateInsurerStatement(['file_id' => $file_id]);
+ //update file content to DB
+ if ($validation_result['status']) {
+ $this->updateInsurerStatement(['file_id' => $file_id]);
+ }
+
+ if (!isset($file_id) || !$validation_result['status']) {
+ return $this->respond(['dataStatus' => false, 'code' => 404, 'message' => 'file not uploaded', 'error_data' => $validation_result['error_data'], 'error_code' => $validation_result['error_code']], 200);
+ }
+
+ if (isset($file_id) || $validation_result['status']) {
+ $this->insurerStatements->where('id', $file_id)->set(['invoice_status' => 'pending'])->update();
+ }
+
+
+
+ return $this->respond(['dataStatus' => true, 'code' => 200, 'data' => 'file upload success'], 200);
+ }
+
+ public function createStatementFolder()
+ {
+ $folderPath = WRITEPATH . 'uploads/statements/';
+
+ // Check if the folder doesn't exist
+ if (!file_exists($folderPath)) {
+ // Create the folder
+ if (mkdir($folderPath, 0777, true)) {
+ $this->myLogger->logme('error', 'statement upload folder created successfully');
+
+ // Set permissions to a+rwx (read, write, execute for all)
+ chmod($folderPath, 0777);
+ $this->myLogger->logme('error', 'Permissions set to a+rwx.');
+ } else {
+ // echo "Failed to create folder.";
+ $this->myLogger->logme('error', 'Failed to create statement upload folder.');
+ }
+ } else {
+ $this->myLogger->logme('error', 'upload folder exists.');
+ }
+ }
+
+ public function validateInsurerStatement($params)
+ {
+ helper('excel_util_helper');
+ //get file info
+ $file_id = $params['file_id'];
+ $file = $this->insurerStatements->find($file_id);
+ // dd($file);
+ $date = new \DateTime($file['month']);
+
+ $month = $date->format('m');
+ $year = $date->format('Y');
+
+ $error_data = ['error_code' => '', 'error_data' => []];
+ $status = 'success';
+ $ret_status = true;
+ // dd($month.'-'.$year);
+ $return = [];
+ if (!isset($file)) {
+ //file not found in DB
+ return array('status' => false, 'msg' => 'statement file not found in DB');
+ }
+ $file_name_with_path = WRITEPATH . "/uploads/statements/" . $file['file_name'];
+
+ //check physical file
+ if (!file_exists($file_name_with_path)) {
+ //file not found update status and reason
+ $message = "Physcial file not found";
+ // echo $message;
+ $this->myLogger->logme('error', ($message . ' for statement file id ' . $file_id));
+ $this->insurerStatements->where('id', $file_id)->set(['file_status' => 'failed', 'reason' => json_encode(['error_code' => 0, 'error_data' => $message])])->update();
+ return array('status' => false, 'error_code' => 0); //0 - Physcial file not found
+ }
+
+ //get excel data to php array
+ $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file_name_with_path);
+ $sheet = $spreadsheet->getActiveSheet();
+
+ $highestRowAndColumn = $sheet->getHighestRowAndColumn();
+ // dd($highestRowAndColumn);
+ $excel_data = $sheet->rangeToArray('A1:' . $highestRowAndColumn['column'] . $highestRowAndColumn['row']);
+ unset($excel_data[0]);
+ $excel_data = ExcelSanitizeHelper::sanitizeArrayData($excel_data);
+ // Kint::dump($excel_data);die();
+ //get no of line items and update in DB
+ $line_items = 0;
+ // get uploaded month transactions data
+ $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) {
+
+ // $excel_row = ExcelSanitizeHelper::sanitizeArrayData($excel_row);
+ $is_source_found = 0;
+ // Kint::dump($excel_key,$excel_row[1],$excel_row[2]);
+ // $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
+ $policy_no = preg_replace( '/[\x{200B}\x{200C}\x{200D}\x{FEFF}\x{00A0}\x{200E}\x{200F}\x{202A}-\x{202E}]/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
+ $endorsement_no = preg_replace( '/[\x{200B}\x{200C}\x{200D}\x{FEFF}\x{00A0}\x{200E}\x{200F}\x{202A}-\x{202E}]/u', '', $excel_row[2]??''); //policy_end_date from excel
+
+ // Kint::dump($excel_key,$policy_no,$endorsement_no,$policy_start_date,$policy_end_date);//die();
+ foreach ($source_data as $source_key => $source_row) {
+ $source_endorsement_no = $source_row['endorsement_no'] !== null ? $source_row['endorsement_no'] : null;
+ // Kint::dump($source_row, $source_endorsement_no, $policy_no, $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 (($policy_no == $source_row['policy_no']) && $endorsement_no == $source_endorsement_no)
+ {
+ $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
+ }
+ }
+ }
+
+ // dd($error_data);
+
+ if ($error_data['error_code']) {
+ $status = 'failed';
+ $ret_status = false;
+ }
+ //update in DB
+ $this->insurerStatements->where('id', $file_id)->set(['line_items' => $line_items, 'file_status' => $status, 'reason' => json_encode($error_data)])->update();
+ return array('status' => $ret_status, 'error_code' => $error_data['error_code'], 'error_data' => $error_data['error_data']);
+ }
+
+
+ public function updateInsurerStatement($params)
+ {
+ helper('excel_util_helper');
+ //get file info
+ $file_id = $params['file_id'];
+ $file = $this->insurerStatements->find($file_id);
+ // dd($file);
+ $date = new \DateTime($file['month']);
+
+ $month = $date->format('m');
+ $year = $date->format('Y');
+
+ $error_data = ['error_code' => '', 'error_data' => []];
+ $status = 'success';
+ $ret_status = true;
+ // dd($month.'-'.$year);
+ $return = [];
+ if (!isset($file)) {
+ //file not found in DB
+ return array('status' => false, 'msg' => 'statement file not found in DB');
+ }
+ $file_name_with_path = WRITEPATH . "/uploads/statements/" . $file['file_name'];
+
+ //check physical file
+ if (!file_exists($file_name_with_path)) {
+ //file not found update status and reason
+ $message = "Physcial file not found";
+ // echo $message;
+ $this->myLogger->logme('error', ($message . ' for statement file id ' . $file_id));
+ $this->insurerStatements->where('id', $file_id)->set(['file_status' => 'failed', 'reason' => json_encode(['error_code' => 0, 'error_data' => $message])])->update();
+ return array('status' => false, 'error_code' => 0); //0 - Physcial file not found
+ }
+
+ //get excel data to php array
+ $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file_name_with_path);
+ $sheet = $spreadsheet->getActiveSheet();
+
+ $highestRowAndColumn = $sheet->getHighestRowAndColumn();
+ // dd($highestRowAndColumn);
+ $excel_data = $sheet->rangeToArray('A1:' . $highestRowAndColumn['column'] . $highestRowAndColumn['row']);
+ unset($excel_data[0]);
+ $excel_data = ExcelSanitizeHelper::sanitizeArrayData($excel_data);
+ // dd($excel_data);
+ //get no of line items and update in DB
+ $line_items = count($excel_data);
+ // get uploaded month transactions data
+ $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);
+ // die;
+ // check policy no,insurer and etc in DB for this month
+ // if all good return true, otherwise return false with messssage
+ $data_to_update = [];
+ foreach ($excel_data as $excel_key => $excel_row) {
+ $is_row_empty = check_row_is_empty_or_null($excel_row);
+ if (!$is_row_empty) {
+
+ $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
+ $policy_no = preg_replace('/[\x{200C}\x{200B}]/u', '', $excel_row[1]); //
+ // $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) {
+ // 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'] : null;
+ // 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']) {
+ if (($policy_no == $source_row['policy_no']) && $endorsement_no == $source_endorsement_no) {
+ $is_source_found = 1;
+
+ //calculate percentage first
+ $total_amt = 0;
+
+ // $actual_bp_per = trim($excel_row[9]); //commented becoz this filed removed tfrom excel file
+ $actual_bp_per = 0; //set default value 0 for maintaining existing code flow
+ $actual_bp_brokerage = trim($excel_row[5]);
+ $actual_bp_amt = trim($excel_row[3]);
+
+ if (($actual_bp_brokerage && $actual_bp_brokerage != 0 && $actual_bp_brokerage != "")) {
+ $total_amt += $actual_bp_brokerage;
+ //percentage reverse calculation
+ if (($actual_bp_per == 0 || $actual_bp_per == 0) && !empty($actual_bp_amt)) {
+ $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]);//commented becoz this filed removed tfrom excel file
+ $actual_tp_per = 0;//set default value 0 for maintaining existing code flow
+ $actual_tp_brokerage = trim($excel_row[6]);
+ $actual_tp_amt = trim($excel_row[4]);
+
+ 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 == "") && !empty($actual_tp_amt)) {
+ $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]);
+
+ $actual_tep_per = 0;
+ $actual_tep_brokerage = 0;
+ $actual_tep_amt = 0;
+
+ 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 == "") && !empty($actual_tep_amt)) {
+ $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[7]), 'statement_id' => $file_id];
+
+ unset($source_data[$source_key]);
+ continue 2;
+ }
+ }
+ }
+ }
+ // dd($data_to_update);
+ $this->coShareStmtDetailsModel->insertBatch($data_to_update, 'id');
+ // dd($data_to_update);
+ // if($error_data['error_code'])
+ // {
+ // $status = 'failed';
+ // $ret_status = false;
+ // }
+ //update in DB
+ $this->insurerStatements->where('id', $file_id)->set(['file_status' => $status, 'reason' => json_encode($error_data), 'invoice_status' => 'pending'])->update();
+ return array('status' => $ret_status, 'error_code' => $error_data['error_code'], 'error_data' => $error_data['error_data']);
+ }
+
+ public function getInvoicePaymentDetails()
+ {
+ $statement_id = $this->request->getUri()->getSegment(4);
+
+ $inv_details = $this->insurerStatements->find($statement_id);
+ $inv_payment_details = $this->invPaymentDetailsModel
->where('statement_id', $statement_id)
- ->groupBy('statement_id')
+ ->where('is_active', 1)
->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'];
+ 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
- ];
- $data['payments'] = $inv_payment_details;
- return $this->respond(['dataStatus' => true, 'code' => 200, 'data' => $data], 200);
- }
-
- public function saveInvoicePaymentDetails()
- {
- $jsonData = $this->request->getJSON();
- $jsonData = (array)$jsonData;
- // echo 'Hi';
- // print_r($jsonData);die();
-
- $invoiceStatus = $jsonData['invoice_status'];
- $hiddenStatementId = $jsonData['hidden_statement_id'];
- $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 = [
- 'invoice_status' => $invoiceStatus,
- '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()
- ];
-
-
-
- $this->insurerStatements->update($hiddenStatementId, $parentData);
-
- // Process child data
- $receivedAmounts = $jsonData['received_amount'];
- $utrNos = $jsonData['utr_no'];
- $tdsTotal = $jsonData['tds'];
- $gstTotal = $jsonData['gst_amount'];
- $paymentDates = $jsonData['payment_date'];
- $pks = $jsonData['pk'];
-
- foreach ($receivedAmounts as $index => $receivedAmount) {
- $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
- $childData = [
- '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
+ // ~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
];
- if ($pk) {
- $childData['updated_by'] = get_session_userid();
- $childData['id'] = (int)$pk;
- } else {
- $childData['created_by'] = get_session_userid();
- }
- // print_r($childData);
- // Insert or update
- $this->invPaymentDetailsModel->save($childData);
- // print_r($this->invPaymentDetailsModel->errors());
-
+ $data['payments'] = $inv_payment_details;
+ return $this->respond(['dataStatus' => true, 'code' => 200, 'data' => $data], 200);
}
- return $this->respond(['dataStatus' => true, 'code' => 200], 200);
- //return $this->response->setJSON(['dataStatus' => 'true']);
- }
-
- public function deletePaymentEntry()
- {
- $payment_id = $this->request->getUri()->getSegment(4);
- //echo $payment_id;
- $this->invPaymentDetailsModel->update($payment_id, ['is_active' => 0]);
- return $this->respond(['dataStatus' => true, 'code' => 200], 200);
- }
-
- public function downloadSampleInsurerStatement()
- {
-
- $filePath = ROOTPATH . 'public/sample_excel/insurer_stament_sample.xlsx';
- // Check if the file exists
- if (file_exists($filePath)) {
-
- // Set the appropriate MIME type
- $mimeType = mime_content_type($filePath);
-
- // Send the file to the client for download
- return $this->response->download($filePath, null, $mimeType);
- } else {
- // File not found, show an error message or redirect
- echo view('errors/html/production');
- }
- }
-
- public function getFileErr()
- {
- $file_id = $this->request->getUri()->getSegment(4);
- $file = $this->insurerStatements->find($file_id);
- return $this->respond(['dataStatus' => true, 'code' => 200, 'data' => $file['reason']], 200);
- }
-
- public function dmsSearch()
- {
- // echo 'scbsc';die();
- if ($this->request->is('post')) {
- // $jsonData = (array)$this->request->getJSON();
- $customer_id = $this->request->getPost('customer_id');
- $policy_id = $this->request->getPost('policy_id');
- $cus_doc_name = $this->request->getPost('cus_doc_name');
- $policy_doc_name = $this->request->getPost('policy_doc_name');
- $pt_files = [];
- $kyc_files = [];
- $batch_files = [];
- $files = [];
+ public function saveInvoicePaymentDetails()
+ {
+ $jsonData = $this->request->getJSON();
+ $jsonData = (array)$jsonData;
+ // echo 'Hi';
// print_r($jsonData);die();
- if ($policy_id != "") {
- //get policy docs from policy transation related tables
- $pt_files = $this->PTFileModel->getPolicyDriveFilesIndex($policy_id, $policy_doc_name);
- $batch_files = $this->batchFileModel->getBatchFilesDataForDocumentSearch($policy_id, $policy_doc_name);
- $files = $this->filesModel->getFilesDataForDocumentSearch($policy_id, $policy_doc_name);
- // dd($files);
- // dd($this->PTFileModel->getLastQuery());
- // ~dd($pt_files);
- }
- if ($customer_id != "") {
- $kyc_files = $this->clientKYCDocsModel->getClientKYCDriveFilesIndex($customer_id, $cus_doc_name);
- // dd($this->clientKYCDocsModel->getLastQuery());
- // !dd($kyc_files);
+
+ $invoiceStatus = $jsonData['invoice_status'];
+ $hiddenStatementId = $jsonData['hidden_statement_id'];
+ $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 = [
+ 'invoice_status' => $invoiceStatus,
+ '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()
+ ];
+
+
+
+ $this->insurerStatements->update($hiddenStatementId, $parentData);
+
+ // Process child data
+ $receivedAmounts = $jsonData['received_amount'];
+ $utrNos = $jsonData['utr_no'];
+ $tdsTotal = $jsonData['tds'];
+ $gstTotal = $jsonData['gst_amount'];
+ $paymentDates = $jsonData['payment_date'];
+ $pks = $jsonData['pk'];
+
+ foreach ($receivedAmounts as $index => $receivedAmount) {
+ $pk = $pks[$index]; // Get the pk for the current record
+ $utrNo = $utrNos[$index];
+ $tds = $tdsTotal[$index];
+ $gst = $gstTotal[$index];
+ $paymentDate = $paymentDates[$index];
+
+ if($utrNo == "" && $tds == "" && $gst == "" && $receivedAmount == "")
+ {
+ continue;
+ }
+ // Prepare data for insert/update
+ $childData = [
+ '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
+ ];
+ if ($pk) {
+ $childData['updated_by'] = get_session_userid();
+ $childData['id'] = (int)$pk;
+ } else {
+ $childData['created_by'] = get_session_userid();
+ }
+ // print_r($childData);
+ // Insert or update
+ $this->invPaymentDetailsModel->save($childData);
+ // print_r($this->invPaymentDetailsModel->errors());
+
}
- $data['files'] = array_merge($pt_files, $kyc_files, $batch_files, $files);
- // dd($data['files']);
- }
- $data['tab_name'] = 'Documents Search';
- $data['page_name'] = 'Documents';
-
- $data['customers'] = $this->clientModel->select('id,client_name,short_name as display_value')->where('is_active', 1)->get()->getResultarray();
- $data['policies'] = $this->clientPolicyModel->select("client_policy.id,client_policy.policy_no,policy_type.policy_type,concat(policy_type.policy_type,' - ',client_policy.policy_no) as display_value")
- ->join('policy_type', 'client_policy.policy_type_id = policy_type.id')
- ->where('client_policy.is_active', 1)->get()->getResultarray();
- // dd($data);
- $this->loadLayout('dms_search', $data);
- }
-
- //---------------------------------------------------------------------------------------------------
-
- public function getCoShareStatementDetails($pt_id)
- {
- if (!$pt_id) {
- return $this->respond([
- 'status' => false,
- 'code' => 400,
- 'message' => 'No data found'
- ], 200);
+ return $this->respond(['dataStatus' => true, 'code' => 200], 200);
+ //return $this->response->setJSON(['dataStatus' => 'true']);
}
- // 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();
+ public function deletePaymentEntry()
+ {
+ $payment_id = $this->request->getUri()->getSegment(4);
+ //echo $payment_id;
+ $this->invPaymentDetailsModel->update($payment_id, ['is_active' => 0]);
+ return $this->respond(['dataStatus' => true, 'code' => 200], 200);
+ }
- // Check if data exists before formatting
- if ($data) {
+ public function downloadSampleInsurerStatement()
+ {
- 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;
+ $filePath = ROOTPATH . 'public/sample_excel/insurer_stament_sample.xlsx';
+ // Check if the file exists
+ if (file_exists($filePath)) {
- // Check if month is not null before formatting
- $row['month'] = $row['month'] ? change_date_format($row['month'], 'Y-m-d', 'M-Y') : null;
+ // Set the appropriate MIME type
+ $mimeType = mime_content_type($filePath);
+
+ // Send the file to the client for download
+ return $this->response->download($filePath, null, $mimeType);
+ } else {
+ // File not found, show an error message or redirect
+ echo view('errors/html/production');
+ }
+ }
+
+ public function getFileErr()
+ {
+ $file_id = $this->request->getUri()->getSegment(4);
+ $file = $this->insurerStatements->find($file_id);
+ return $this->respond(['dataStatus' => true, 'code' => 200, 'data' => $file['reason']], 200);
+ }
+
+ public function dmsSearch()
+ {
+ // echo 'scbsc';die();
+ if ($this->request->is('post')) {
+ // $jsonData = (array)$this->request->getJSON();
+ $customer_id = $this->request->getPost('customer_id');
+ $policy_id = $this->request->getPost('policy_id');
+ $cus_doc_name = $this->request->getPost('cus_doc_name');
+ $policy_doc_name = $this->request->getPost('policy_doc_name');
+ $pt_files = [];
+ $kyc_files = [];
+ $batch_files = [];
+ $files = [];
+ // print_r($jsonData);die();
+ if ($policy_id != "") {
+ //get policy docs from policy transation related tables
+ $pt_files = $this->PTFileModel->getPolicyDriveFilesIndex($policy_id, $policy_doc_name);
+ $batch_files = $this->batchFileModel->getBatchFilesDataForDocumentSearch($policy_id, $policy_doc_name);
+ $files = $this->filesModel->getFilesDataForDocumentSearch($policy_id, $policy_doc_name);
+ // dd($files);
+ // dd($this->PTFileModel->getLastQuery());
+ // ~dd($pt_files);
+ }
+ if ($customer_id != "") {
+ $kyc_files = $this->clientKYCDocsModel->getClientKYCDriveFilesIndex($customer_id, $cus_doc_name);
+ // dd($this->clientKYCDocsModel->getLastQuery());
+ // !dd($kyc_files);
+ }
+
+ $data['files'] = array_merge($pt_files, $kyc_files, $batch_files, $files);
+ // dd($data['files']);
+ }
+ $data['tab_name'] = 'Documents Search';
+ $data['page_name'] = 'Documents';
+
+ $data['customers'] = $this->clientModel->select('id,client_name,short_name as display_value')->where('is_active', 1)->get()->getResultarray();
+ $data['policies'] = $this->clientPolicyModel->select("client_policy.id,client_policy.policy_no,policy_type.policy_type,concat(policy_type.policy_type,' - ',client_policy.policy_no) as display_value")
+ ->join('policy_type', 'client_policy.policy_type_id = policy_type.id')
+ ->where('client_policy.is_active', 1)->get()->getResultarray();
+ // dd($data);
+ $this->loadLayout('dms_search', $data);
+ }
+
+ //---------------------------------------------------------------------------------------------------
+
+ public function getCoShareStatementDetails($pt_id)
+ {
+ if (!$pt_id) {
+ return $this->respond([
+ 'status' => false,
+ 'code' => 400,
+ 'message' => 'No data found'
+ ], 200);
}
- return $this->respond([
- 'status' => true,
- 'code' => 200,
- 'data' => $data
- ], 200);
- } else {
- 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();
- public function getClientPolicyDataBasedOnClientAndInsuer()
- {
+ // Check if data exists before formatting
+ if ($data) {
- $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;
+ 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;
- $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,
- ]);
+ // Check if month is not null before formatting
+ $row['month'] = $row['month'] ? change_date_format($row['month'], 'Y-m-d', 'M-Y') : null;
+ }
- 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);
+ return $this->respond([
+ 'status' => true,
+ 'code' => 200,
+ 'data' => $data
+ ], 200);
+ } else {
+ return $this->respond([
+ 'status' => false,
+ 'code' => 400,
+ 'message' => 'No data found'
+ ], 200);
+ }
}
- $result = $builder->get()->getResultArray();
+ public function getClientPolicyDataBasedOnClientAndInsuer()
+ {
- 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);
- }
- }
+ $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;
- public function checkCDAmountForBasePremium()
- {
- $base_premium = $this->request->getGet('base_premium') ?? 0;
- $cd_ac_no = $this->request->getGet('cd_ac_no') ?? 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,
+ ]);
- // Validate inputs
- if (empty($cd_ac_no)) {
- return $this->respond(['status' => false, 'code' => 400, 'message' => 'CD Account Number is required'], 200);
+ 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);
+ }
}
- // Build query
- $db = db_connect();
- $builder = $db->table("cash_deposit")
- ->where('cd_ac_pk', $cd_ac_no)
- ->where('is_active', 1)
- ->orderBy('id', 'desc')
- ->limit(1);
+ public function checkCDAmountForBasePremium()
+ {
+ $base_premium = $this->request->getGet('base_premium') ?? 0;
+ $cd_ac_no = $this->request->getGet('cd_ac_no') ?? 0;
- $result = $builder->get()->getRowArray();
+ // Validate inputs
+ if (empty($cd_ac_no)) {
+ return $this->respond(['status' => false, 'code' => 400, 'message' => 'CD Account Number is required'], 200);
+ }
- if ($result) {
- // Check if base premium exceeds balance
- $base_premium_greater_than_balance = $base_premium > $result['balance'];
+ // Build query
+ $db = db_connect();
+ $builder = $db->table("cash_deposit")
+ ->where('cd_ac_pk', $cd_ac_no)
+ ->where('is_active', 1)
+ ->orderBy('id', 'desc')
+ ->limit(1);
- return $this->respond([
- 'status' => true,
- 'code' => 200,
- 'data' => $result,
- 'base_premium' => $base_premium,
- 'cd_ac_no' => $cd_ac_no,
- 'base_premium_greater_than_balance' => $base_premium_greater_than_balance,
- ], 200);
+ $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' => $base_premium,
+ 'cd_ac_no' => $cd_ac_no,
+ '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);
}
- 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;
- 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();
- $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);
+ }
- 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);
+ }
- 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);
- }
+ public function sendInstallmentRemainderMail()
+ {
- public function sendInstallmentRemainderMail()
- {
-
- $this->myLogger->logme("error", "Cron Job For Send Installment Remainder Mail Started");
-
- try {
+ $this->myLogger->logme("error", "Cron Job For Send Installment Remainder Mail Started");
try {
- $bdsInstallmentData = $this->BdsPlacementModel->getClientInstallmentDetails();
+ try {
+
+ $bdsInstallmentData = $this->BdsPlacementModel->getClientInstallmentDetails();
+ } catch (Exception $e) {
+
+ $this->myLogger->logme('error', 'Exception: ' . $e->getMessage() . 'Page: ' . $e->getFile() . ' Line: ' . $e->getLine());
+ }
+ $this->myLogger->logme("error", "Data for BDS Installment " . json_encode($bdsInstallmentData));
+ // dd($bdsInstallmentData);
+
+ if (empty($bdsInstallmentData)) {
+
+ $this->myLogger->logme("error", "No Client Installment is Due in the 15th Day");
+
+ return false;
+ }
+
+ foreach ($bdsInstallmentData as $installmentData) {
+
+ $mailData = $this->PrepareBDSMailData($installmentData);
+ $to_mail = $mailData['to_mail'];
+ $message = $mailData['message'];
+ $subject = $mailData['subject'];
+
+ $this->myLogger->logme("error", "Installment Pending for" . $subject);
+
+ $common = ['mail_type' => 'installment_amount_due_remainder_mail'];
+
+ $res = MailHelper::send_email(['mail' => $to_mail, 'subject' => $subject, 'message' => $message, 'common' => $common]);
+
+ $res = json_decode($res);
+ $this->myLogger->logme('error', 'res: ' . json_encode($res));
+
+ if ($res->status == 'success') {
+ return true;
+ } else {
+ return false;
+ }
+ }
} catch (Exception $e) {
$this->myLogger->logme('error', 'Exception: ' . $e->getMessage() . 'Page: ' . $e->getFile() . ' Line: ' . $e->getLine());
}
- $this->myLogger->logme("error", "Data for BDS Installment " . json_encode($bdsInstallmentData));
- // dd($bdsInstallmentData);
+ }
- if (empty($bdsInstallmentData)) {
+ protected function PrepareBDSMailData($data)
+ {
- $this->myLogger->logme("error", "No Client Installment is Due in the 15th Day");
+ try {
- return false;
+ $installment_amount = $data['installment_amount'];
+ $payment_date = date('d-m-Y', strtotime($data['payment_date']));
+ $client = $data['client_name'];
+ $branch = $data['branch_name'];
+ $sales_person_mail = $data['sales_person'];
+ $heads = $data['heads'];
+ $admins = $data['admins'];
+ $buisness_team = $data['buisness_team'];
+ $policy_no = $data['policy_no'];
+ $client_short_name = isset($data['short_name']) && $data['short_name'] != null ? $data['short_name'] : $data['client_name'];
+
+ $subject = "Installment Amount Due For Client - {$client_short_name} - Policy NO({$policy_no}) is Due On - {$payment_date}";
+
+ $message = "Policy Installment for Client - {$client}, Branch - {$branch} is Due on {$payment_date}
+ with amount of {$installment_amount}.
+ Policy No : {$policy_no}";
+
+
+ $to_mail = array_merge(
+ array_column($heads, 'email'),
+ array_column($admins, 'email'),
+ array_column($buisness_team, 'email'),
+ [$sales_person_mail]
+ );
+
+ $to_mail = array_unique($to_mail);
+
+ $this->myLogger->logme("error", "Selected To Address : " . json_encode($to_mail));
+
+ // dd($to_mail);
+ return [
+ 'to_mail' => $to_mail,
+ 'message' => $message,
+ 'subject' => $subject
+ ];
+ } catch (Exception $e) {
+
+ $this->myLogger->logme('error', 'Exception: ' . $e->getMessage() . 'Page: ' . $e->getFile() . ' Line: ' . $e->getLine());
+ }
+ }
+
+ public function getMoreInfo()
+ {
+
+ $pt_id = $this->request->getPost("pt_id");
+ $data_to_send['bds_data'] = $this->BdsPlacementModel->where("is_active", 1)->where("pt_id", $pt_id)->findAll();
+
+ foreach ($data_to_send['bds_data'] as &$data) {
+
+ $data['payment_date'] = (new \DateTime($data['payment_date']))->format('d-m-Y');
}
- foreach ($bdsInstallmentData as $installmentData) {
+ if (!empty($data_to_send)) {
- $mailData = $this->PrepareBDSMailData($installmentData);
- $to_mail = $mailData['to_mail'];
- $message = $mailData['message'];
- $subject = $mailData['subject'];
+ return $this->respond(['status' => true, "data" => $data_to_send], 200);
+ } else {
- $this->myLogger->logme("error", "Installment Pending for" . $subject);
+ return $this->respond(['status' => false, "No Data Found For the Policy Transaction"], 404);
+ }
+ }
- $common = ['mail_type' => 'installment_amount_due_remainder_mail'];
+ public function saveInstallment()
+ {
- $res = MailHelper::send_email(['mail' => $to_mail, 'subject' => $subject, 'message' => $message, 'common' => $common]);
+ $installments = $this->request->getPost('installments');
- $res = json_decode($res);
- $this->myLogger->logme('error', 'res: ' . json_encode($res));
+ if (!$installments || !is_array($installments)) {
+ return $this->respond(['status' => false, 'message' => 'No data received'], 400);
+ }
- if ($res->status == 'success') {
- return true;
- } else {
- return false;
+ $this->myLogger->logme("error", json_encode($installments));
+ // die();
+
+ foreach ($installments as &$row) {
+ // Convert date from d-m-Y to Y-m-d
+ if (!empty($row['payment_date'])) {
+ $date = \DateTime::createFromFormat('d-m-Y', $row['payment_date']);
+ if ($date) {
+ $row['payment_date'] = $date->format('Y-m-d');
+ }
}
+ $this->BdsPlacementModel->save($row);
}
- } catch (Exception $e) {
- $this->myLogger->logme('error', 'Exception: ' . $e->getMessage() . 'Page: ' . $e->getFile() . ' Line: ' . $e->getLine());
- }
- }
-
- protected function PrepareBDSMailData($data)
- {
-
- try {
-
- $installment_amount = $data['installment_amount'];
- $payment_date = date('d-m-Y', strtotime($data['payment_date']));
- $client = $data['client_name'];
- $branch = $data['branch_name'];
- $sales_person_mail = $data['sales_person'];
- $heads = $data['heads'];
- $admins = $data['admins'];
- $buisness_team = $data['buisness_team'];
- $policy_no = $data['policy_no'];
- $client_short_name = isset($data['short_name']) && $data['short_name'] != null ? $data['short_name'] : $data['client_name'];
-
- $subject = "Installment Amount Due For Client - {$client_short_name} - Policy NO({$policy_no}) is Due On - {$payment_date}";
-
- $message = "Policy Installment for Client - {$client}, Branch - {$branch} is Due on {$payment_date}
- with amount of {$installment_amount}.
- Policy No : {$policy_no}";
-
-
- $to_mail = array_merge(
- array_column($heads, 'email'),
- array_column($admins, 'email'),
- array_column($buisness_team, 'email'),
- [$sales_person_mail]
- );
-
- $to_mail = array_unique($to_mail);
-
- $this->myLogger->logme("error", "Selected To Address : " . json_encode($to_mail));
-
- // dd($to_mail);
- return [
- 'to_mail' => $to_mail,
- 'message' => $message,
- 'subject' => $subject
- ];
- } catch (Exception $e) {
-
- $this->myLogger->logme('error', 'Exception: ' . $e->getMessage() . 'Page: ' . $e->getFile() . ' Line: ' . $e->getLine());
- }
- }
-
- public function getMoreInfo()
- {
-
- $pt_id = $this->request->getPost("pt_id");
- $data_to_send['bds_data'] = $this->BdsPlacementModel->where("is_active", 1)->where("pt_id", $pt_id)->findAll();
-
- foreach ($data_to_send['bds_data'] as &$data) {
-
- $data['payment_date'] = (new \DateTime($data['payment_date']))->format('d-m-Y');
+ return $this->respond(['status' => true, 'message' => 'Data saved successfully'], 200);
}
- if (!empty($data_to_send)) {
+ protected function getPolicyForEndorsment()
+ {
- return $this->respond(['status' => true, "data" => $data_to_send], 200);
- } else {
-
- return $this->respond(['status' => false, "No Data Found For the Policy Transaction"], 404);
- }
- }
-
- public function saveInstallment()
- {
-
- $installments = $this->request->getPost('installments');
-
- if (!$installments || !is_array($installments)) {
- return $this->respond(['status' => false, 'message' => 'No data received'], 400);
- }
-
- $this->myLogger->logme("error", json_encode($installments));
- // die();
-
- foreach ($installments as &$row) {
- // Convert date from d-m-Y to Y-m-d
- if (!empty($row['payment_date'])) {
- $date = \DateTime::createFromFormat('d-m-Y', $row['payment_date']);
- if ($date) {
- $row['payment_date'] = $date->format('Y-m-d');
- }
- }
- $this->BdsPlacementModel->save($row);
- }
-
- return $this->respond(['status' => true, 'message' => 'Data saved successfully'], 200);
- }
-
- protected function getPolicyForEndorsment()
- {
-
- $policyList = [];
- $policyListByClient = [];
+ $policyList = [];
+ $policyListByClient = [];
- $clients = $this->clientModel
- ->select("*, DATE_FORMAT(dob, '%d-%m-%Y') as dob")
- ->where('is_active', 1)
+ $clients = $this->clientModel
+ ->select("*, DATE_FORMAT(dob, '%d-%m-%Y') as dob")
+ ->where('is_active', 1)
+ ->findAll();
+
+ $clientIds = array_column($clients, 'id');
+
+ // $policies = $this->clientPolicyModel
+ // ->select("
+ // client_policy.*,
+ // policy_type.policy_type,
+ // policy_type.ebp,
+ // policy_type.etp,
+ // policy_type.iep,
+ // policy_type.itp,
+ // policy_type.bap,
+ // policy_type.allocg,
+ // DATE_FORMAT(client_policy.policy_start_date, '%d/%m/%Y') as policy_start_date,
+ // DATE_FORMAT(client_policy.policy_end_date, '%d/%m/%Y') as policy_end_date
+ // ")
+ // ->join('policy_type', 'policy_type.id = client_policy.policy_type_id')
+ // ->join('policy_transaction pt', 'pt.client_policy_id = client_policy.id and pt.action_type = "inception" and pt.is_active = 1 and pt.client_policy_id is not null')
+ // ->whereIn('client_policy.client_id', $clientIds)
+ // ->where('client_policy.is_active', 1)
+ // ->findAll();
+
+ $policies = $this->policyTransactionModel
+ ->select("
+ policy_transaction.*,
+ policy_type.policy_type,
+ policy_type.ebp,
+ policy_type.etp,
+ policy_type.iep,
+ policy_type.itp,
+ policy_type.bap,
+ policy_type.allocg,
+ DATE_FORMAT(policy_transaction.policy_start_date, '%d/%m/%Y') as policy_start_date,
+ DATE_FORMAT(policy_transaction.policy_end_date, '%d/%m/%Y') as policy_end_date
+ ")
+ ->join('policy_type', 'policy_type.id = policy_transaction.policy_type_id')
+ ->whereIn('policy_transaction.client_id', $clientIds)
+ ->where('policy_transaction.is_active', 1)
+ ->where('policy_transaction.action_type', "inception")
->findAll();
- $clientIds = array_column($clients, 'id');
+ foreach ($policies as $policy) {
+ $policyList[$policy['client_branch_id']][] = $policy;
+ $policyListByClient[$policy['client_id']][] = $policy;
+ if (isset($policyCount[$policy['client_id']])) {
+ $policyCount[$policy['client_id']]++;
+ } else {
+ $policyCount[$policy['client_id']] = 1;
+ }
+ }
- // $policies = $this->clientPolicyModel
- // ->select("
- // client_policy.*,
- // policy_type.policy_type,
- // policy_type.ebp,
- // policy_type.etp,
- // policy_type.iep,
- // policy_type.itp,
- // policy_type.bap,
- // policy_type.allocg,
- // DATE_FORMAT(client_policy.policy_start_date, '%d/%m/%Y') as policy_start_date,
- // DATE_FORMAT(client_policy.policy_end_date, '%d/%m/%Y') as policy_end_date
- // ")
- // ->join('policy_type', 'policy_type.id = client_policy.policy_type_id')
- // ->join('policy_transaction pt', 'pt.client_policy_id = client_policy.id and pt.action_type = "inception" and pt.is_active = 1 and pt.client_policy_id is not null')
- // ->whereIn('client_policy.client_id', $clientIds)
- // ->where('client_policy.is_active', 1)
- // ->findAll();
+ return [$policyList, $policyListByClient];
+ }
- $policies = $this->policyTransactionModel
- ->select("
- policy_transaction.*,
- policy_type.policy_type,
- policy_type.ebp,
- policy_type.etp,
- policy_type.iep,
- policy_type.itp,
- policy_type.bap,
- policy_type.allocg,
- DATE_FORMAT(policy_transaction.policy_start_date, '%d/%m/%Y') as policy_start_date,
- DATE_FORMAT(policy_transaction.policy_end_date, '%d/%m/%Y') as policy_end_date
- ")
- ->join('policy_type', 'policy_type.id = policy_transaction.policy_type_id')
- ->whereIn('policy_transaction.client_id', $clientIds)
- ->where('policy_transaction.is_active', 1)
- ->where('policy_transaction.action_type', "inception")
- ->findAll();
- foreach ($policies as $policy) {
- $policyList[$policy['client_branch_id']][] = $policy;
- $policyListByClient[$policy['client_id']][] = $policy;
- if (isset($policyCount[$policy['client_id']])) {
- $policyCount[$policy['client_id']]++;
- } else {
- $policyCount[$policy['client_id']] = 1;
+ public function reportBDSNew()
+ {
+ // 🧭 Basic Page Info
+ $data['tab_name'] = 'BDS Report';
+ $data['page_name'] = 'BDS Report';
+
+ // 📋 Dropdown Data
+ $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',
+ ];
+
+ // 🏢 Fetch Active Data
+ $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();
+ $data['users'] = $this->userModel->where('is_active', 1)->findAll();
+ $data['policy_count'] = $this->policyTransactionModel->where('is_active', 1)->countAllResults();
+
+ // 🕐 Filters
+ $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');
+ $user_id = $this->request->getGet('user_id');
+
+ // Handle statement month range
+ 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));
+ }
+
+ // Ensure default values
+ $start_date = $start_date ?: 0;
+ $end_date = $end_date ?: 0;
+ $client_id = $client_id ?: 0;
+ $insurer_id = $insurer_id ?: 0;
+ $policy_type_id = $policy_type_id ?: 0;
+ $date_type = $date_type ?: 0;
+ $issuer = $issuer ?: 0;
+ $client_branch_id = $client_branch_id ?: 0;
+ $insurer_branch_id = $insurer_branch_id ?: 0;
+ $client_policy_id = $client_policy_id ?: 0;
+ $user_id = $user_id ?: 0;
+
+ // 🧾 Handle POST requests (Dashboard filters)
+ if ($this->request->is('post')) {
+ $isFromDashboard = $this->request->getPost('is_dashboard');
+
+ if (!empty($isFromDashboard) && $isFromDashboard == 1) {
+ $ids = array_filter(explode(',', $this->request->getPost('ids')));
+
+ if (!empty($ids)) {
+ $idsStr = implode(',', array_map('intval', $ids)); // sanitize IDs
+ $where = "policy_transaction.id IN ($idsStr)";
+ } else {
+ $where = []; // No valid IDs
+ }
}
}
- return [$policyList, $policyListByClient];
+ // 📊 Fetch report data
+ $data['report_list'] = $this->policyTransactionModel->reportBDSNew(
+ $start_date,
+ $end_date,
+ $client_id,
+ $insurer_id,
+ $policy_type_id,
+ $date_type,
+ $issuer,
+ $client_branch_id,
+ $insurer_branch_id,
+ $client_policy_id,
+ $user_id,
+ $where ?? ''
+ );
+
+ $data['list_new'] = true;
+
+ // 🧩 Load View
+ $this->loadLayout('report_bds_filter', $data);
+ }
+
+
+
}
-}
diff --git a/app/Controllers/RestAuthenticationController.php b/app/Controllers/RestAuthenticationController.php
index 24f22283..11b1a8fc 100755
--- a/app/Controllers/RestAuthenticationController.php
+++ b/app/Controllers/RestAuthenticationController.php
@@ -869,6 +869,7 @@ class RestAuthenticationController extends AdminController
return $this->respond(['status' => 'failed','code' => 404,'data' => $result],200);
}
+
} catch (\Throwable $th) {
$this->myLogger->logme("error", "REST-AUTH-CONTROLLER - saveMpin: Exception: " . $th->getMessage() . " --- Line: " . $th->getLine() . " --- Trace: " . $th->getTraceAsString());
log_message('error', ' ');
@@ -1496,4 +1497,460 @@ class RestAuthenticationController extends AdminController
return $this->fail("Invalid Token: " . $e->getMessage(), 401);
}
}
+
+ // -------------- PASSWORD API'S -------------------------------------------------------------------------------------------------------------
+
+ public function savePassword()
+ {
+ log_message('error', ' ');
+ log_message('error', ' ************************************* POST START **************************************** ');
+ log_message('error', ' ');
+ $this->myLogger->logme("error", "REST-AUTH-CONTROLLER - savePassword: Function called");
+ $this->myLogger->logme("error", "REST-AUTH-CONTROLLER - savePassword: Received payload = " . json_encode($this->request->getJSON() ?? []));
+
+ try {
+
+ $payload = $this->request->getJSON();
+ $mobile_number = $payload->mobile_number ?? null;
+ $email_id = $payload->email_id ?? null;
+ $client_id = $payload->client_id ?? null;
+ $plain_password = $payload->password ?? null;
+
+ if (empty($plain_password)) {
+ return $this->respond(['status' => 'failed', 'code' => 400, 'message' => 'Password cannot be empty'], 400);
+ }
+
+ // Build employee query
+ if ($mobile_number) {
+
+ $builder = $this->employeeModel
+ ->select('employees.*')
+ ->join('employee_polices', 'employees.id = employee_polices.employee_id')
+ ->where('employees.mobile', $mobile_number)
+ ->where('employees.relationship', 'Self')
+ ->where('employee_polices.is_active', 1)
+ ->whereIn('employee_polices.status', ['active', 'expired'])
+ ->where('employees.is_active', 1)
+ ->whereIn('employees.emp_status', ['active', 'expired']);
+ if (!empty($client_id)) $builder->where('employees.client_id', $client_id);
+ $employeeData = $builder->orderBy('employees.id', 'desc')->first();
+
+ } else {
+
+ $builder = $this->employeeModel
+ ->select('employees.*')
+ ->join('employee_polices', 'employees.id = employee_polices.employee_id')
+ ->where('employees.email_corporate', $email_id)
+ ->where('employees.relationship', 'Self')
+ ->where('employee_polices.is_active', 1)
+ ->whereIn('employee_polices.status', ['active', 'expired'])
+ ->where('employees.is_active', 1)
+ ->whereIn('employees.emp_status', ['active', 'expired']);
+ if (!empty($client_id)) $builder->where('employees.client_id', $client_id);
+ $employeeData = $builder->orderBy('employees.id', 'desc')->first();
+
+ }
+
+ $lastQuery = $this->employeeModel->db->getLastQuery();
+ $this->myLogger->logme("error", "REST-AUTH-CONTROLLER - savePassword: Last Executed Query: " . $lastQuery);
+ $this->myLogger->logme("error", "REST-AUTH-CONTROLLER - savePassword: employeeData: " . json_encode($employeeData ?? []));
+
+ if ($employeeData) {
+ $id = $employeeData['id'];
+ $hashedPassword = password_hash($plain_password, PASSWORD_DEFAULT);
+
+ $updateData = [
+ 'password' => $hashedPassword,
+ ];
+
+ $updated = $this->employeeModel->where('id', $id)->set($updateData)->update();
+
+ if ($updated) {
+ $this->myLogger->logme("error", "REST-AUTH-CONTROLLER - savePassword: Password saved successfully");
+ $result = ['user_verification' => true, 'message' => "Password saved successfully"];
+ return $this->respond(['status' => 'success', 'code' => 200, 'data' => $result], 200);
+ } else {
+ $this->myLogger->logme("error", "REST-AUTH-CONTROLLER - savePassword: Password save failed");
+ $result = ['user_verification' => true, 'message' => "Password not saved"];
+ return $this->respond(['status' => 'failed', 'code' => 500, 'data' => $result], 200);
+ }
+ } else {
+ $this->myLogger->logme("error", "REST-AUTH-CONTROLLER - savePassword: Employee not found");
+ $result = ['user_verification' => false, 'message' => "User not found"];
+ return $this->respond(['status' => 'failed', 'code' => 404, 'data' => $result], 200);
+ }
+ } catch (\Throwable $th) {
+ $this->myLogger->logme("error", "REST-AUTH-CONTROLLER - savePassword: Exception: " . $th->getMessage() . " --- Line: " . $th->getLine() . " --- Trace: " . $th->getTraceAsString());
+ return $this->respond(['status' => 'failed', 'code' => 500, 'message' => $th->getMessage()], 500);
+ }
+ }
+
+ public function changePassword()
+ {
+ log_message('error', ' ');
+ log_message('error', ' ************************************* CHANGE PASSWORD START **************************************** ');
+ log_message('error', ' ');
+ $this->myLogger->logme("error", "REST-AUTH-CONTROLLER - changePassword: Function called");
+ $this->myLogger->logme("error", "REST-AUTH-CONTROLLER - changePassword: Received payload = " . json_encode($this->request->getJSON() ?? []));
+
+ try {
+ $payload = $this->request->getJSON(true);
+
+ $mobile_number = $payload['mobile_number'] ?? null;
+ $email_id = $payload['email_id'] ?? null;
+ $client_id = $payload['client_id'] ?? null;
+ $otp = $payload['otp'] ?? null;
+ $new_password = $payload['new_password'] ?? null;
+
+ if (empty($otp) || empty($new_password)) {
+ return $this->respond([
+ 'status' => 'failed',
+ 'code' => 400,
+ 'message' => 'OTP and new password are required'
+ ], 400);
+ }
+
+ // Fetch employee details
+ $builder = $this->employeeModel
+ ->select('employees.*')
+ ->join('employee_polices', 'employees.id = employee_polices.employee_id')
+ ->where('employees.relationship', 'Self')
+ ->where('employees.is_active', 1)
+ ->whereIn('employees.emp_status', ['active'])
+ ->where('employee_polices.is_active', 1)
+ ->whereIn('employee_polices.status', ['active']);
+
+ if (!empty($client_id)) $builder->where('employees.client_id', $client_id);
+
+ if ($mobile_number) {
+ $builder->where('employees.mobile', $mobile_number);
+ } elseif ($email_id) {
+ $builder->where('employees.email_corporate', $email_id);
+ } else {
+ return $this->respond([
+ 'status' => 'failed',
+ 'code' => 400,
+ 'message' => 'Mobile number or Email ID is required'
+ ], 400);
+ }
+
+ $employeeData = $builder->orderBy('employees.id', 'desc')->first();
+
+ $this->myLogger->logme("error", "REST-AUTH-CONTROLLER - changePassword: employeeData: " . json_encode($employeeData ?? []));
+
+ if (!$employeeData) {
+ return $this->respond(['status' => 'failed', 'code' => 404, 'message' => 'User not found'], 404);
+ }
+
+ // Check OTP validity (assuming fields: otp, otp_expiry exist)
+ if (empty($employeeData['otp']) || $employeeData['otp'] != $otp) {
+ return $this->respond(['status' => 'failed', 'code' => 401, 'message' => 'Invalid OTP'], 200);
+ }
+
+ if (!empty($employeeData['otp_expiry']) && strtotime($employeeData['otp_expiry']) < time()) {
+ return $this->respond(['status' => 'failed', 'code' => 401, 'message' => 'OTP expired'], 200);
+ }
+
+ // Hash new password
+ $newHashedPassword = password_hash($new_password, PASSWORD_DEFAULT);
+
+ // Update password and clear OTP
+ $updated = $this->employeeModel->update($employeeData['id'], [
+ 'password' => $newHashedPassword,
+ 'otp' => null,
+ ]);
+
+ if ($updated) {
+ $this->myLogger->logme("error", "REST-AUTH-CONTROLLER - changePassword: Password updated successfully");
+ log_message('error', ' ');
+ log_message('error', ' ************************************* CHANGE PASSWORD END **************************************** ');
+ log_message('error', ' ');
+
+ return $this->respond([
+ 'status' => 'success',
+ 'code' => 200,
+ 'message' => 'Password changed successfully'
+ ], 200);
+ } else {
+ return $this->respond([
+ 'status' => 'failed',
+ 'code' => 500,
+ 'message' => 'Failed to update password'
+ ], 500);
+ }
+
+ } catch (\Throwable $th) {
+ $this->myLogger->logme("error", "REST-AUTH-CONTROLLER - changePassword: Exception: " . $th->getMessage());
+ log_message('error', ' ');
+ log_message('error', ' ************************************* CHANGE PASSWORD END **************************************** ');
+ log_message('error', ' ');
+ return $this->respond(['status' => 'failed', 'code' => 500, 'message' => $th->getMessage()], 500);
+ }
+ }
+
+ public function verifyPassword()
+ {
+ log_message('error', ' ');
+ log_message('error', ' ************************************* POST START **************************************** ');
+ log_message('error', ' ');
+ $this->myLogger->logme("error", "REST-AUTH-CONTROLLER - Verify Password: Function called");
+ $this->myLogger->logme("error", "REST-AUTH-CONTROLLER - verifyPassword: Received payload = " . json_encode($this->request->getJSON() ?? []));
+
+ try {
+ $requestData = $this->request->getJSON(true);
+
+ $mobile_number = $requestData['mobile_number'] ?? null;
+ $email_id = $requestData['email_id'] ?? null;
+ $password = $requestData['password'] ?? null;
+ $client_id = $requestData['client_id'] ?? null;
+
+ if (!$password) {
+ return $this->respond(['status' => 'failed', 'code' => 400, 'data' => "", 'message' => 'Password is required'], 400);
+ }
+
+ // 🔹 Fetch employee data
+ if ($mobile_number) {
+ $builder = $this->employeeModel
+ ->select('employees.*')
+ ->join('employee_polices', 'employees.id = employee_polices.employee_id')
+ ->where('employees.mobile', $mobile_number)
+ ->where('employees.relationship', 'Self')
+ ->where('employee_polices.is_active', 1)
+ ->whereIn('employee_polices.status', ['active'])
+ ->where('employees.is_active', 1)
+ ->whereIn('employees.emp_status', ['active']);
+
+ if (!empty($client_id)) {
+ $builder->where('employees.client_id', $client_id);
+ }
+
+ $employeeData = $builder->orderBy('employees.id', 'desc')->first();
+ } elseif ($email_id) {
+ $builder = $this->employeeModel
+ ->select('employees.*')
+ ->join('employee_polices', 'employees.id = employee_polices.employee_id')
+ ->where('employees.email_corporate', $email_id)
+ ->where('employees.relationship', 'Self')
+ ->where('employee_polices.is_active', 1)
+ ->whereIn('employee_polices.status', ['active'])
+ ->where('employees.is_active', 1)
+ ->whereIn('employees.emp_status', ['active']);
+
+ if (!empty($client_id)) {
+ $builder->where('employees.client_id', $client_id);
+ }
+
+ $employeeData = $builder->orderBy('employees.id', 'desc')->first();
+ } else {
+ return $this->respond(['status' => 'failed', 'code' => 400, 'data' => "", 'message' => 'Mobile number or Email ID is required'], 400);
+ }
+
+ $lastQuery = $this->employeeModel->db->getLastQuery();
+ $this->myLogger->logme("error", "REST-AUTH-CONTROLLER - verifyPassword: Last Executed Query: " . $lastQuery);
+ $this->myLogger->logme("error", "REST-AUTH-CONTROLLER - verifyPassword: employeeData: " . json_encode($employeeData ?? []));
+
+ // 🔹 Verify password hash
+ if ($employeeData && isset($employeeData['password']) && password_verify($password, $employeeData['password'])) {
+
+ $this->myLogger->logme("error", "REST-AUTH-CONTROLLER - verifyPassword: Verified employee found");
+
+ // ✅ Log authentication info
+ $auth = HttpRequestHelper::getRequestInfo();
+ if ($auth) {
+ $this->authHistoryModel->insert([
+ 'user_id' => $employeeData['id'],
+ 'user_type' => 'employee',
+ 'ip' => $auth['ip'],
+ 'platform' => $auth['platform'],
+ 'broswer' => $auth['browser'],
+ ]);
+ }
+
+ // ✅ Generate JWT token
+ $employeeData['token_type'] = "post";
+ $token = JWTToken::encode($employeeData);
+
+ log_message('error', ' ');
+ log_message('error', ' ************************************* POST END **************************************** ');
+ log_message('error', ' ');
+
+ return $this->respond(['status' => 'success', 'code' => 200, 'data' => $token], 200);
+ } else {
+ $this->myLogger->logme("error", "REST-AUTH-CONTROLLER - verifyPassword: Invalid password or employee not found");
+ log_message('error', ' ');
+ log_message('error', ' ************************************* POST END **************************************** ');
+ log_message('error', ' ');
+
+ return $this->respond(['status' => 'failed', 'code' => 404, 'data' => "", 'message' => 'Invalid password'], 200);
+ }
+ } catch (\Exception $e) {
+ $this->myLogger->logme("error", "REST-AUTH-CONTROLLER - verifyPassword: Exception: " . $e->getMessage() . " --- Line: " . $e->getLine());
+ log_message('error', ' ');
+ log_message('error', ' ************************************* POST END **************************************** ');
+ log_message('error', ' ');
+ return $this->respond(['status' => 'failed', 'code' => 500, 'data' => "", 'message' => $e->getMessage()], 500);
+ }
+ }
+
+ public function sendChangePasswordOTP()
+ {
+ log_message('error', ' ');
+ log_message('error', ' ************************************* SEND OTP START **************************************** ');
+ log_message('error', ' ');
+
+ $this->myLogger->logme("error", "REST-AUTH-CONTROLLER - sendChangePasswordOTP: Function called");
+ $this->myLogger->logme("error", "REST-AUTH-CONTROLLER - sendChangePasswordOTP: Received payload = " . json_encode($this->request->getJSON() ?? []));
+
+ try {
+ $requestData = $this->request->getJSON(true);
+
+ $email_id = $requestData['email_id'] ?? null;
+ $client_id = $requestData['client_id'] ?? null;
+
+ if (!$email_id) {
+ return $this->respond(['status' => 'failed', 'code' => 400, 'data' => "", 'message' => 'Email ID is required'], 400);
+ }
+
+ // Get employee details
+ $builder = $this->employeeModel
+ ->select('employees.id, employees.mobile, employees.email_corporate, employees.client_id')
+ ->join('employee_polices', 'employees.id = employee_polices.employee_id')
+ ->where('employees.is_active', 1)
+ ->whereIn('employees.emp_status', ['active'])
+ ->where('employee_polices.is_active', 1)
+ ->whereIn('employee_polices.status', ['active'])
+ ->where('employees.relationship', 'Self');
+
+ if (!empty($client_id)) {
+ $builder->where('employees.client_id', $client_id);
+ }
+
+ if ($email_id) {
+ $builder->where('employees.email_corporate', $email_id);
+ }
+
+ $employeeData = $builder->orderBy('employees.id', 'desc')->first();
+
+ $this->myLogger->logme("error", "REST-AUTH-CONTROLLER - sendChangePasswordOTP: Employee Data: " . json_encode($employeeData ?? []));
+
+ if (!$employeeData) {
+ return $this->respond(['status' => 'failed', 'code' => 404, 'data' => "", 'message' => 'Employee not found'], 404);
+ }
+
+ // Generate 6-digit OTP
+ $otp = rand(100000, 999999);
+
+ // Save OTP to DB (assuming 'otp' and 'otp_expiry' columns exist)
+ $this->employeeModel->update($employeeData['id'], [
+ 'otp' => $otp,
+ ]);
+
+ // Send OTP via SMS or Email (you can replace with your actual helper)
+ if ($email_id) {
+ // Example: MailHelper::sendMail($email_id, 'Password Change OTP', "Your OTP is {$otp}");
+ $this->myLogger->logme("error", "REST-AUTH-CONTROLLER - sendChangePasswordOTP: OTP {$otp} sent to email {$email_id}");
+ }
+
+ log_message('error', ' ');
+ log_message('error', ' ************************************* SEND OTP END **************************************** ');
+ log_message('error', ' ');
+
+ return $this->respond(['status' => 'success', 'code' => 200, 'data' => ['otp_sent_to' => $email_id], 'message' => 'OTP sent successfully'], 200);
+ } catch (\Exception $e) {
+ $this->myLogger->logme("error", "REST-AUTH-CONTROLLER - sendChangePasswordOTP: Exception: " . $e->getMessage() . " --- Line: " . $e->getLine());
+ log_message('error', ' ');
+ log_message('error', ' ************************************* SEND OTP END **************************************** ');
+ log_message('error', ' ');
+ return $this->respond(['status' => 'failed', 'code' => 500, 'data' => "", 'message' => $e->getMessage()], 500);
+ }
+ }
+
+ // -------------- EMP MOBILE NUMBER UPDATE API'S -------------------------------------------------------------------------------------------------------------
+
+ public function updateMobileNumber()
+ {
+ log_message('error', ' ');
+ log_message('error', ' ************************************* UPDATE MOBILE START **************************************** ');
+ log_message('error', ' ');
+ $this->myLogger->logme("error", "REST-AUTH-CONTROLLER - updateMobileNumber: Function called");
+ $this->myLogger->logme("error", "REST-AUTH-CONTROLLER - updateMobileNumber: Received payload = " . json_encode($this->request->getJSON() ?? []));
+
+ try {
+
+ $payload = $this->request->getJSON(true);
+
+ $email_id = $payload['email_id'] ?? null;
+ $client_id = $payload['client_id'] ?? null;
+ $new_mobile = $payload['new_mobile_number'] ?? null;
+
+ if (empty($email_id) || empty($new_mobile)) {
+ return $this->respond([
+ 'status' => 'failed',
+ 'code' => 400,
+ 'message' => 'Email ID and new mobile number are required'
+ ], 400);
+ }
+
+ // Fetch employee by email
+ $builder = $this->employeeModel
+ ->select('employees.*')
+ ->join('employee_polices', 'employees.id = employee_polices.employee_id')
+ ->where('employees.email_corporate', $email_id)
+ ->where('employees.relationship', 'Self')
+ ->where('employees.is_active', 1)
+ ->whereIn('employees.emp_status', ['active'])
+ ->where('employee_polices.is_active', 1)
+ ->whereIn('employee_polices.status', ['active']);
+
+ if (!empty($client_id)) {
+ $builder->where('employees.client_id', $client_id);
+ }
+
+ $employeeData = $builder->orderBy('employees.id', 'desc')->first();
+ $this->myLogger->logme("error", "REST-AUTH-CONTROLLER - updateMobileNumber: employeeData: " . json_encode($employeeData ?? []));
+
+ if (!$employeeData) {
+ return $this->respond([
+ 'status' => 'failed',
+ 'code' => 404,
+ 'message' => 'User not found with this Email ID'
+ ], 404);
+ }
+
+ // Update mobile number
+ $updated = $this->employeeModel->update($employeeData['id'], [
+ 'mobile' => $new_mobile,
+ ]);
+
+ if ($updated) {
+ $this->myLogger->logme("error", "REST-AUTH-CONTROLLER - updateMobileNumber: Mobile number updated successfully");
+ log_message('error', ' ');
+ log_message('error', ' ************************************* UPDATE MOBILE END **************************************** ');
+ log_message('error', ' ');
+
+ return $this->respond([
+ 'status' => 'success',
+ 'code' => 200,
+ 'message' => 'Mobile number updated successfully'
+ ], 200);
+ } else {
+ $this->myLogger->logme("error", "REST-AUTH-CONTROLLER - updateMobileNumber: Failed to update mobile number");
+ return $this->respond([
+ 'status' => 'failed',
+ 'code' => 500,
+ 'message' => 'Failed to update mobile number'
+ ], 500);
+ }
+ } catch (\Throwable $th) {
+ $this->myLogger->logme("error", "REST-AUTH-CONTROLLER - updateMobileNumber: Exception: " . $th->getMessage());
+ log_message('error', ' ');
+ log_message('error', ' ************************************* UPDATE MOBILE END **************************************** ');
+ log_message('error', ' ');
+ return $this->respond([
+ 'status' => 'failed',
+ 'code' => 500,
+ 'message' => $th->getMessage()
+ ], 500);
+ }
+ }
}
\ No newline at end of file
diff --git a/app/Controllers/TestingController.php b/app/Controllers/TestingController.php
index e6f377c7..75d4d578 100644
--- a/app/Controllers/TestingController.php
+++ b/app/Controllers/TestingController.php
@@ -362,7 +362,18 @@ class TestingController extends BaseController
$pre_clients_list = $this->getNonDuplicatePreClients();
-
+ $log_post_clients_list = $post_clients_list;
+
+ $log_pre_clients_list = $pre_clients_list;
+
+ log_message('error', 'Post Clients to be processed: ' . count($log_post_clients_list));
+ log_message('error', 'Pre Clients to be processed: ' . count($log_pre_clients_list));
+
+
+
+ $matched_Count = 0;
+ $expected_match_count = min(count($post_clients_list), count($pre_clients_list));
+
if (
!empty($pre_clients_list) &&
@@ -372,12 +383,18 @@ class TestingController extends BaseController
$postDB = \Config\Database::connect();
$preDB = \Config\Database::connect('preDB');
- foreach ($post_clients_list as $post_client) {
+ foreach ($post_clients_list as $index => $post_client) {
- foreach ($pre_clients_list as $pre_client) {
+ foreach ($pre_clients_list as $index => $pre_client) {
if (trim($post_client['short_name']) == trim($pre_client['short_name'])) {
+ unset($log_post_clients_list[$index]);
+ unset($log_pre_clients_list[$index]);
+
+ $matched_Count++;
+
+
$postDB->table('clients')->where('id', $post_client['id'])->update(['pre_client_id' => $pre_client['id']]);
$preDB->table('clients')->where('id', $pre_client['id'])->update(['post_client_id' => $post_client['id']]);
@@ -426,7 +443,28 @@ class TestingController extends BaseController
}
}
}
- }
+
+
+ log_message('error', 'Expected Match Count : ' . $expected_match_count);
+ log_message('error', 'Total Matched Count: ' . $matched_Count);
+ log_message('error', 'Total UnMatched Count: ' . $expected_match_count - $matched_Count);
+
+
+ log_message('error', 'unmatched_reocrds');
+
+ $log_post_clients_list = array_values($log_post_clients_list);
+ $log_pre_clients_list = array_values($log_pre_clients_list);
+
+ if ((count($log_pre_clients_list) < count($log_post_clients_list))) {
+ log_message('error', "unmatched records count from pre- " . count($log_pre_clients_list));
+ log_message('error', print_r($log_pre_clients_list, true));
+ } else {
+ log_message('error', "unmatched records count from post - " . count($log_post_clients_list));
+ log_message('error', print_r($log_post_clients_list, true));
+ }
+ }
+
+ return $this->response->setJSON(['status' => 'success', 'message' => 'Client and Branch mapping completed.'])->setStatusCode(200);
}
@@ -493,7 +531,7 @@ class TestingController extends BaseController
return $results;
}
public function membervalidation($lead_id = 329)
- {
+ {
$lead_controll = new LeadsController();
// $lead_controll->getMemberDataExcelFileErrors();
$res = $lead_controll->memberDataListExcelFileFormatValidation(['lead_id' => $lead_id]);
@@ -501,18 +539,81 @@ class TestingController extends BaseController
}
private $firstNames = [
- 'Rajesh', 'Priya', 'Amit', 'Sneha', 'Vikram', 'Anjali', 'Rahul', 'Deepika',
- 'Sanjay', 'Kavita', 'Arun', 'Pooja', 'Manoj', 'Nisha', 'Suresh', 'Meera',
- 'Karthik', 'Divya', 'Ravi', 'Lakshmi', 'Anand', 'Swathi', 'Vijay', 'Rekha',
- 'Ashok', 'Sangeetha', 'Prakash', 'Uma', 'Ramesh', 'Vani', 'Kumar', 'Radha',
- 'Dinesh', 'Shanti', 'Ganesh', 'Parvati', 'Mohan', 'Sita', 'Arjun', 'Geetha'
+ 'Rajesh',
+ 'Priya',
+ 'Amit',
+ 'Sneha',
+ 'Vikram',
+ 'Anjali',
+ 'Rahul',
+ 'Deepika',
+ 'Sanjay',
+ 'Kavita',
+ 'Arun',
+ 'Pooja',
+ 'Manoj',
+ 'Nisha',
+ 'Suresh',
+ 'Meera',
+ 'Karthik',
+ 'Divya',
+ 'Ravi',
+ 'Lakshmi',
+ 'Anand',
+ 'Swathi',
+ 'Vijay',
+ 'Rekha',
+ 'Ashok',
+ 'Sangeetha',
+ 'Prakash',
+ 'Uma',
+ 'Ramesh',
+ 'Vani',
+ 'Kumar',
+ 'Radha',
+ 'Dinesh',
+ 'Shanti',
+ 'Ganesh',
+ 'Parvati',
+ 'Mohan',
+ 'Sita',
+ 'Arjun',
+ 'Geetha'
];
private $lastNames = [
- 'Kumar', 'Sharma', 'Singh', 'Patel', 'Reddy', 'Nair', 'Iyer', 'Krishnan',
- 'Rao', 'Gupta', 'Verma', 'Agarwal', 'Joshi', 'Mehta', 'Desai', 'Pillai',
- 'Menon', 'Bhat', 'Naidu', 'Varma', 'Malhotra', 'Kapoor', 'Chopra', 'Saxena',
- 'Pandey', 'Mishra', 'Tiwari', 'Dubey', 'Sinha', 'Jain', 'Shah', 'Thakur'
+ 'Kumar',
+ 'Sharma',
+ 'Singh',
+ 'Patel',
+ 'Reddy',
+ 'Nair',
+ 'Iyer',
+ 'Krishnan',
+ 'Rao',
+ 'Gupta',
+ 'Verma',
+ 'Agarwal',
+ 'Joshi',
+ 'Mehta',
+ 'Desai',
+ 'Pillai',
+ 'Menon',
+ 'Bhat',
+ 'Naidu',
+ 'Varma',
+ 'Malhotra',
+ 'Kapoor',
+ 'Chopra',
+ 'Saxena',
+ 'Pandey',
+ 'Mishra',
+ 'Tiwari',
+ 'Dubey',
+ 'Sinha',
+ 'Jain',
+ 'Shah',
+ 'Thakur'
];
private $relationships = ['Self', 'Spouse', 'Son', 'Daughter', 'Father', 'Mother'];
@@ -569,9 +670,9 @@ class TestingController extends BaseController
for ($i = 1; $i <= $totalRecords; $i++) {
$row = $i + 1; // Start from row 2 (row 1 is header)
-
+
$record = $this->generateSampleRecord($i);
-
+
$sheet->setCellValue('A' . $row, $record['sl_no']);
$sheet->setCellValue('B' . $row, $record['emp_code']);
$sheet->setCellValue('C' . $row, $record['name']);
@@ -622,33 +723,33 @@ class TestingController extends BaseController
$firstName = $this->firstNames[array_rand($this->firstNames)];
$lastName = $this->lastNames[array_rand($this->lastNames)];
$name = $firstName . ' ' . $lastName;
-
+
$relationship = $this->relationships[array_rand($this->relationships)];
$gender = $this->genders[array_rand($this->genders)];
-
+
// Generate random age between 18 and 65
$age = rand(18, 65);
-
+
// Calculate DOB based on age
$year = date('Y') - $age;
$month = str_pad(rand(1, 12), 2, '0', STR_PAD_LEFT);
$day = str_pad(rand(1, 28), 2, '0', STR_PAD_LEFT);
$dob = "{$day}-{$month}-{$year}";
-
+
// Generate employee code
$empCode = 'EMP' . str_pad($index, 6, '0', STR_PAD_LEFT);
-
+
// Generate email
$email = strtolower($firstName . '.' . $lastName . $index) . '@' . $this->domains[array_rand($this->domains)];
-
+
// Generate mobile number (Indian format)
$mobile = '+91' . rand(7000000000, 9999999999);
-
+
// Generate insurance amounts
$siOptions = [100000, 200000, 300000, 500000, 1000000];
$si = $siOptions[array_rand($siOptions)];
$si_enhancement = rand(0, 1) ? rand(50000, 200000) : 0;
-
+
$proposed_si_1 = $si + rand(100000, 500000);
$proposed_si_2 = $proposed_si_1 + rand(100000, 500000);
$proposed_si_3 = $proposed_si_2 + rand(100000, 500000);
@@ -673,4 +774,214 @@ class TestingController extends BaseController
];
}
+
+ public function logo_renaming()
+ {
+
+ $directory = ROOTPATH . 'public/uploads/logo/';
+
+ if (!is_dir($directory)) {
+ die("Directory not found: $directory");
+ }
+
+ $files = scandir($directory);
+
+ $client_logo_files = $this->get_client_logo_files();
+
+ $rename_files = "";
+ $failed_rename_files = "";
+
+ foreach ($files as $file) {
+ // Skip system entries
+ if ($file === '.' || $file === '..') {
+ continue;
+ }
+
+
+ $oldPath = $directory . $file;
+
+ if (is_file($oldPath) && in_array(trim($file), $client_logo_files)) {
+
+ // Remove all spaces from filename
+ $newFileName = preg_replace('/\s+|\x{00A0}|\x{200B}|\x{200C}|\x{200D}|\x{FEFF}/u', '', $file);
+
+ $newPath = $directory . $newFileName;
+
+ // Only rename if the name changed
+ if ($oldPath !== $newPath) {
+ if (rename($oldPath, $newPath)) {
+ $rename_files .= "\n Renamed: $file → $newFileName \n";
+ } else {
+ $failed_rename_files .= "\n Failed file: $file \n";
+ }
+ }
+ }
+ }
+
+ $dbUpdated = $this->update_client_logo_files();
+
+ log_message('error', 'Renamed Files: ' . $rename_files);
+ log_message('error', 'Failed Renames: ' . $failed_rename_files);
+ log_message('error', 'Database Update Status: ' . ($dbUpdated ? 'Success' : 'No changes made'));
+
+ return $this->response->setJSON([
+ 'status' => 'success',
+ 'message' => 'Logo renaming completed. kindly check backend logs for details',
+ 'data' => [
+ 'renamed_files' => $rename_files,
+ 'failed_renames' => $failed_rename_files
+ ]
+ ])->setStatusCode(200);
+ }
+
+ public function get_client_logo_files()
+ {
+
+ $db = \Config\Database::connect();
+
+ $sql = "SELECT client_logo FROM clients WHERE client_logo IS NOT NULL AND TRIM(client_logo) <> '' ";
+
+ $query = $db->query($sql);
+
+ $results = $query->getResultArray() ?? [];
+
+ $files = array_map(function ($item) {
+ return trim($item['client_logo']);
+ }, $results);
+
+ return $files;
+ }
+
+ public function update_client_logo_files()
+ {
+
+ $db = \Config\Database::connect();
+
+ $sql = "UPDATE clients
+ SET client_logo = REPLACE(REPLACE(REPLACE(client_logo, CHAR(160), ''), ' ', ''), '\t', '')
+ WHERE client_logo IS NOT NULL
+ AND TRIM(client_logo) <> ''
+ ";
+
+ $query = $db->query($sql);
+
+ return $db->affectedRows() > 0;
+ }
+
+
+ public function createDefaultMailTempalteInCrossDB()
+ {
+ $postDB = \Config\Database::connect(); // target DB
+ $preDB = \Config\Database::connect('preDB'); // source DB
+
+ // Templates to copy
+ $templateNames = [
+ 'member_welcome_mail',
+ 'member_reminder_mail',
+ 'member_review_and_summary_mail'
+ ];
+
+
+
+
+ foreach ($templateNames as $template) {
+
+ $exists = $postDB->table('notifications')
+ ->where('client_id', NULL)
+ ->where('template_name', $template)
+ ->countAllResults();
+
+ if ($exists > 0) {
+ continue; // Skip if already inserted
+ }
+
+ // Fetch template from preDB
+ $templateData = $preDB->table('notifications')
+ ->where('client_id', NULL)
+ ->where('template_name', $template)
+ ->get()
+ ->getRowArray();
+
+ if (!empty($templateData)) {
+
+ // Remove ID to avoid duplicate primary key issues
+ unset($templateData['id']);
+
+ // Set created_by and timestamps if needed
+ $templateData['client_id'] = NULL;
+ $templateData['created_by'] = 1;
+ $templateData['cretaed_at'] = date('Y-m-d H:i:s');
+ $templateData['updated_by'] = NULL;
+ $templateData['updated_at'] = NULL;
+
+ // Insert into postDB
+ $postDB->table('notifications')->insert($templateData);
+ }
+ }
+
+
+ return $this->response->setJSON(['message'=>"Created Default Mail Tempalte In Cross DB "])->setStatusCode(200);
+ }
+
+ public function createDefaultMailTempalteInSameDB()
+ {
+ $postDB = \Config\Database::connect();
+
+ // Templates to copy
+ $templateNames = [
+ 'member_welcome_mail',
+ 'member_reminder_mail',
+ 'member_review_and_summary_mail',
+ 'member_common_mail',
+ 'member_ecard_mail'
+ ];
+
+
+
+
+ foreach ($templateNames as $template) {
+
+ $exists = $postDB->table('notifications')
+ ->where('client_id', NULL)
+ ->where('template_name', $template)
+ ->countAllResults();
+
+ if ($exists > 0 ) {
+ continue; // Skip if already inserted
+ }
+
+ // Fetch template from preDB
+ $templateData = $postDB->table('notifications')
+
+ // this is where we want to replace 0 with the client id we want to replace
+ ->where('client_id', 0)
+
+ // template_name from which you want to create a common template from templateNames array.
+ ->where('template_name', $template)
+ ->get()
+ ->getRowArray();
+
+ if (!empty($templateData)) {
+
+ // Remove ID to avoid duplicate primary key issues
+ unset($templateData['id']);
+
+ // Set created_by and timestamps if needed
+ $templateData['client_id'] = NULL;
+ $templateData['created_by'] = 1;
+ $templateData['cretaed_at'] = date('Y-m-d H:i:s');
+ $templateData['updated_by'] = NULL;
+ $templateData['updated_at'] = NULL;
+
+ // Insert into postDB
+ $postDB->table('notifications')->insert($templateData);
+ }
+ }
+
+
+ return $this->response->setJSON(['message'=>"Created Default Mail Tempalte In Same DB "])->setStatusCode(200);
+ }
+
+
+
}
diff --git a/app/Controllers/TicketController.php b/app/Controllers/TicketController.php
index eb7e894b..f6a924c2 100644
--- a/app/Controllers/TicketController.php
+++ b/app/Controllers/TicketController.php
@@ -1281,8 +1281,12 @@ class TicketController extends BaseController
// $actionType = $this->request->getGet();
$claimFiles = new ClaimFilesModel();
$file_data = $claimFiles->where('id', $claim_file_id)->first();
- $fileName = $file_data['doc_name'];
+ // $fileName = $file_data['doc_name'];
+ $url = $file_data['url'];
+ $parts = explode('/', $url);
+ $fileName = end($parts);
+
$filePath = WRITEPATH . '/uploads/claim_files/' . $fileName;
try {
diff --git a/app/Controllers/UserController.php b/app/Controllers/UserController.php
index b4d391dc..ea0e4fb8 100755
--- a/app/Controllers/UserController.php
+++ b/app/Controllers/UserController.php
@@ -62,7 +62,7 @@ class UserController extends AdminController
// echo '';
// print_r($data); die;
$data['roleData'] = $this->roleModel->select('id, role')->findAll();
- $data['teamData'] = $this->teamModel->select('id, name')->findAll();
+ $data['teamData'] = $this->teamModel->select('id, name')->where('is_active',1)->findAll();
$this->loadLayout('UserList', $data);
}
@@ -156,9 +156,11 @@ class UserController extends AdminController
public function edit()
{
+ // echo ":/ in 159";
if (!$this->request->getPost()) {
return redirect()->to(base_url('/user/list'));
} else {
+ // echo ":/ in 163";
$id = $this->request->getPost('PrimaryKey');
$teams = $this->request->getPost('team');
$userData = $this->request->getPost();
@@ -166,6 +168,7 @@ class UserController extends AdminController
unset($userData['PrimaryKey']);
$existingData = $this->userModel->where('id',$id)->first();;
+ // dd($existingData);die;
// Update data in the 'users' table based on the $id
$userData['updated_by'] = get_session_userid();
@@ -776,32 +779,63 @@ class UserController extends AdminController
}
}
+ // public function downloadIncentivesFile($file_id)
+ // {
+ // try {
+ // $result = $this->partnerManagerIncentiveFileModel->where('id', $file_id)->first();
+
+ // if (!$result || empty($result['incentive_file_name'])) {
+ // throw new \Exception("File Name Not Found");
+ // }
+
+ // $incentive_file_name = $result['incentive_file_name'];
+ // $file_name = basename($incentive_file_name);
+ // $filePath = WRITEPATH . 'uploads/incentives/' . $file_name;
+
+ // if (file_exists($filePath)) {
+ // return $this->response->download($filePath, null);
+ // } else {
+ // throw new \Exception("File Not Found");
+ // }
+
+ // } catch (\Exception $e) {
+
+ // $this->myLogger->logme('error', $e->getMessage());
+
+ // // Show 404 error view
+ // $data['message'] = $e->getMessage();
+ // return view('errors/404', $data);
+ // }
+ // }
+
public function downloadIncentivesFile($file_id)
{
try {
$result = $this->partnerManagerIncentiveFileModel->where('id', $file_id)->first();
if (!$result || empty($result['incentive_file_name'])) {
- throw new \Exception("File Name Not Found");
+ throw new \Exception("File Name Not Found for ID {$file_id}");
}
$incentive_file_name = $result['incentive_file_name'];
$file_name = basename($incentive_file_name);
$filePath = WRITEPATH . 'uploads/incentives/' . $file_name;
- if (file_exists($filePath)) {
- return $this->response->download($filePath, null);
- } else {
- throw new \Exception("File Not Found");
+ if (!file_exists($filePath)) {
+ throw new \Exception("File Not Found: {$file_name}");
}
- } catch (\Exception $e) {
-
+ return $this->response->download($filePath, null);
+ } catch (\Throwable $e) {
+ // Catch all kinds of exceptions
$this->myLogger->logme('error', $e->getMessage());
- // Show 404 error view
- $data['message'] = $e->getMessage();
- return view('errors/404', $data);
+ // Return proper 404 for missing file, else 500 for unexpected error
+ if (str_contains($e->getMessage(), 'Not Found')) {
+ return $this->response->setStatusCode(404)->setBody($e->getMessage());
+ }
+
+ return $this->response->setStatusCode(500)->setBody('Internal Server Error');
}
}
diff --git a/app/Helpers/DepositHelper.php b/app/Helpers/DepositHelper.php
index 9549f8a1..495797f3 100755
--- a/app/Helpers/DepositHelper.php
+++ b/app/Helpers/DepositHelper.php
@@ -66,7 +66,8 @@ class DepositHelper
'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,
- 'record_date' => $data['record_date'] ?? null
+ 'record_date' => $data['record_date'] ?? null,
+ 'policy_transaction_id' => $data['pt_id'] ?? null
];
// Insert data and get the insert ID
diff --git a/app/Helpers/excel_util_helper.php b/app/Helpers/excel_util_helper.php
index e608b013..4329388d 100755
--- a/app/Helpers/excel_util_helper.php
+++ b/app/Helpers/excel_util_helper.php
@@ -109,7 +109,8 @@ if (!function_exists('check_relationship')) {
$family_floaters = isset($policy_terms['family_floaters']);
if ($family_floaters) {
- if (isset($relationship[$col]) && $relationship[$col]['gender'] != $row[4]) {
+ $relation_gender = normalizeGender($row[4]);
+ if (isset($relationship[$col]) && $relationship[$col]['gender'] != $relation_gender) {
$error = "Gender relationship conflict: Expected " . $relationship[$col]['gender'] . ", received $row[4]";
return array('status' => false, 'error' => $error);
}
@@ -369,13 +370,24 @@ if (!function_exists('check_dob_diff')) {
}
if (!function_exists('data_group_by_family')) {
- function data_group_by_family($emp_data, $data_source = 'excel', $action = '')
+ function data_group_by_family($emp_data, $data_source = 'excel', $action = '', $current_column_action = null)
{
$result = [];
// Kint::dump($emp_data);
foreach ($emp_data as $rkey => $row) {
+
+
+
if ($data_source == 'excel') {
if (!check_row_is_empty_or_null($row)) {
+
+ // for this condition to avoid 5,00,000 to 500000
+ if($current_column_action == 'SI'){
+ $row[3] = removeNumberFormatting($row[3]);
+ }else if(in_array($current_column_action, ['I','DA', 'MI', 'A'])){
+ $row[6] = removeNumberFormatting($row[6]);
+ }
+
if ($action == 'enrollment') //if action is enrollment transform current row into inception row, becoz we treat enrollment as inception
{
$row = transform_enrollment_row_to_inception_row($row);
@@ -637,12 +649,19 @@ if (!function_exists('check_dependent_conflict')) {
if (!function_exists('generate_relationship_code')) {
function generate_relationship_code($arr)
{
- $gender = ['M' => 1, 'F' => 2];
+ $gender = [
+ 'M' => 1,
+ 'Male' => 1,
+ 'male' => 1,
+ 'F' => 2,
+ 'Female' => 2,
+ 'female' => 2,
+ ];
$relationship = ['self' => 1, 'spouse' => 2, 'son' => 3, 'daughter' => 4, 'father' => 5, 'mother' => 6, 'father-in-law' => 7, 'mother-in-law' => 8];
$slug = \Config\Services::slug();
$relationship_code = $slug->slugify($arr['relationship']);
$emp_type_code = ($relationship_code == 'self' ? 'EMP_TYP_01' : 'EMP_TYP_03');
- $relationship_code = $gender[trim($arr['gender'])] . $relationship[trim($relationship_code)];
+ $relationship_code = $gender[trim($arr['gender'])] ?? "" . $relationship[trim($relationship_code)] ?? "";
return ['relationship_code' => $relationship_code, 'emp_type_code' => $emp_type_code];
}
}
@@ -1627,21 +1646,53 @@ if (!function_exists('check_dup_mobileno')) {
}
}
+// if (!function_exists('check_dup_email')) {
+// function check_dup_email(array $row, array $existing_mobilenos)
+// {
+// is_valid_or_empty_email($row['13']);
+// if(!empty($row['13'])){
+// foreach ($existing_mobilenos as $k => $value) {
+// if (strtolower($row['5']) == 'self' && $row['13'] == $value['email_corporate']) {
+// return array('status' => false, 'error' => "Duplicate Email");
+// // break;
+// }
+// }
+// }
+// return array('status' => true);
+// }
+// }
+
if (!function_exists('check_dup_email')) {
function check_dup_email(array $row, array $existing_mobilenos)
{
- if(!empty($row['13'])){
- foreach ($existing_mobilenos as $k => $value) {
- if (strtolower($row['5']) == 'self' && $row['13'] == $value['email_corporate']) {
- return array('status' => false, 'error' => "Duplicate Email");
- // break;
+ $errorMessages = [];
+
+ // Validate email
+ $emailCheck = is_valid_or_empty_email($row['13'] ?? "");
+ if (!$emailCheck) {
+ $errorMessages[] = 'Invalid email format';
+ }
+
+ // Check duplicate only if email is not empty
+ if (!empty($row['13'])) {
+ foreach ($existing_mobilenos as $value) {
+ if (strtolower(trim($row['5'])) === 'self' && trim($row['13']) === trim($value['email_corporate'])) {
+ $errorMessages[] = 'Duplicate Email';
+ break;
}
}
}
- return array('status' => true);
+
+ // Prepare final return
+ if (!empty($errorMessages)) {
+ return ['status' => false, 'error' => implode(' & ', $errorMessages)];
+ }
+
+ return ['status' => true, 'error' => ''];
}
}
+
if (!function_exists('generate_family_relationship_array')) {
function generate_family_relationship_array($family_structure_from_policy_terms)
{
@@ -2041,6 +2092,22 @@ if (!function_exists('formatIndianCurrency')) {
}
}
+if (!function_exists('normalizeGender')) {
+ function normalizeGender($gender)
+ {
+ $gender = strtoupper(trim($gender));
+
+ if (in_array($gender, ['M', 'MALE'])) {
+ return 'M';
+ } elseif (in_array($gender, ['F', 'FEMALE'])) {
+ return 'F';
+ }
+
+ // Optional: return null or original if not recognized
+ return null;
+ }
+}
+
// ------------- FUNCTION FOR LEAD MEMBER DATA LIST VALIDATIONS --------------------------------------
if (!function_exists('check_columns_name_exist')) {
@@ -2291,8 +2358,8 @@ if (!function_exists('validateFamily')) {
// Validation 3: Validate spouse gender if spouse exists
if ($spouseMember !== null) {
- $selfGender = strtoupper(trim($selfMember[4])); // Gender field
- $spouseGender = strtoupper(trim($spouseMember[4]));
+ $selfGender = normalizeGender(trim($selfMember[4])); // Gender field
+ $spouseGender = normalizeGender(trim($spouseMember[4]));
$selfName = $selfMember[2]; // Name field
$spouseName = $spouseMember[2];
@@ -2368,3 +2435,24 @@ if (!function_exists('check_age_validation')) {
// ------------- END OF LEAD MEMBER DATA LIST VALIDATIONS --------------------------------------
+if (!function_exists('is_valid_or_empty_email')) {
+ function is_valid_or_empty_email($email)
+ {
+ // If empty or null → return success
+ if (empty($email) && $email != 0) {
+ // return ['status' => true, 'error' => 'Value is empty'];
+ return true;
+ }
+
+ // If valid email → return success
+ if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
+ // return ['status' => true, 'error' => 'Valid email format'];
+ return true;
+ }
+
+ // If invalid email → return failure
+ // return ['status' => false, 'error' => 'Invalid email format'];
+ return false;
+ }
+}
+
diff --git a/app/Helpers/sendMailNotification.php b/app/Helpers/sendMailNotification.php
index f9de6b09..4ac2580e 100755
--- a/app/Helpers/sendMailNotification.php
+++ b/app/Helpers/sendMailNotification.php
@@ -57,6 +57,13 @@ class sendMailNotification
$mail_content = str_replace(["[[app_link]]", "{{app_link}}"], "Review Details", $mail_content);
if ($dataToInsert['relationship'] == 'Self' && $mail != null || $mail != '') {
+
+ $mail_content = preg_replace('/]*>( |\s)*<\/p>/i', '', $mail_content);
+
+ $data['params'] = $params;$data['client_logo'] = $client_logo;
+ $data['mail_content'] = $mail_content;
+ $mail_content = view('mail_template', $data);
+
$wholeData = ['mail' => $mail, 'subject' => $subject,'message'=> $mail_content,'bcc'=> $client_data['common_mails'], 'reply_to' => $client_data['reply_to'], 'attachments' => $attachments, 'common' => $common];
}
@@ -89,6 +96,12 @@ class sendMailNotification
$mail_content = str_replace(["[[member_mobile]]", "{{member_mobile}}"], $employee_mobile_no, $mail_content);
$mail = $emp_data['email_corporate'];
+ $mail_content = preg_replace('/
]*>( |\s)*<\/p>/i', '', $mail_content);
+
+ $data['params'] = $params;$data['client_logo'] = $client_logo;
+ $data['mail_content'] = $mail_content;
+ $mail_content = view('mail_template', $data);
+
$wholeData = ['mail' => $mail, 'subject' => $subject,'message'=> $mail_content, 'bcc'=> $client_data['common_mails'], 'reply_to' => $client_data['reply_to'], 'common' => $common];
return $wholeData;
@@ -139,11 +152,73 @@ class sendMailNotification
$mail_content = str_replace(["[[ecard_download_link]]", "{{ecard_download_link}}"], "Download Insurance Card", $mail_content);
$mail_content = str_replace(["[[client_name]]", "{{client_name}}"], $client_data['client_name'], $mail_content);
+ $mail_content = preg_replace('/
]*>( |\s)*<\/p>/i', '', $mail_content);
+
+ $data['params'] = $params;$data['client_logo'] = $client_logo;
+ $data['mail_content'] = $mail_content;
+ $mail_content = view('mail_template', $data);
+
+
$wholeData = ['mail' => $mail, 'subject' => $subject,'message'=> $mail_content,'bcc'=> $client_data['common_mails'], 'reply_to' => $client_data['reply_to'], 'common' => $common];
return $wholeData;
- } else if($action == 'member_review_and_summary_mail'){
+ } else if($action == 'member_common_mail'){
+
+ $notification = $params['notification'];
+ $get_emp_email_and_other_details = $params['get_emp_email_and_other_details'];
+ $rand_string = $params['rand_string'];
+ $client_data = $params['client_data'];
+ $tpa_id = $params['tpa_id'];
+ $common = $params['common'];
+
+
+ $mail_content = $notification['mail_content'];
+ $mail = $get_emp_email_and_other_details['email_corporate'];
+ $subject = $notification['subject'];
+
+ $cleanedText = mb_convert_encoding($subject, 'UTF-8', 'UTF-8'); // Normalize encoding
+ $cleanedText = preg_replace('/[^\x20-\x7E]/', '', $cleanedText);
+
+ $subject = $cleanedText;
+
+ $link = generate_download_link($rand_string).'/1';
+
+ $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'];
+
+ $post_enrollment_app_link = $_ENV['POST_ENROLLMENT_APP_LINK'];
+
+ $client_logo = base_url() . "public/uploads/logo/" . $client_data['client_logo'];
+ // $client_logo = $nhance_logo;
+
+ $mail_content = str_replace(["[[nhance_logo]]", "{{nhance_logo}}"], "
", $mail_content);
+ $mail_content = str_replace(["[[client_logo]]", "{{client_logo}}"], "
", $mail_content);
+
+ $mail_content = str_replace(["[[member_name]]", "{{member_name}}"], $name, $mail_content);
+ $mail_content = str_replace(["[[member_mobile]]", "{{member_mobile}}"], $employee_mobile_no, $mail_content);
+ $mail_content = str_replace(["[[app_link]]", "{{app_link}}"], "Review Details", $mail_content);
+ $mail_content = str_replace(["[[post_enrollment_app_link]]", "{{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]]", "{{ecard_download_link}}"], "Download Insurance Card", $mail_content);
+ $mail_content = str_replace(["[[client_name]]", "{{client_name}}"], $client_data['client_name'], $mail_content);
+
+ $mail_content = preg_replace('/
]*>( |\s)*<\/p>/i', '', $mail_content);
+
+ $data['params'] = $params;$data['client_logo'] = $client_logo;
+ $data['mail_content'] = $mail_content;
+ $mail_content = view('mail_template', $data);
+
+
+ $wholeData = ['mail' => $mail, 'subject' => $subject,'message'=> $mail_content,'bcc'=> $client_data['common_mails'], 'reply_to' => $client_data['reply_to'], 'common' => $common];
+
+ return $wholeData;
+
+ }else if($action == 'member_review_and_summary_mail'){
$array_list = $params['array_list'];//employeee lst
$client_policy_id = $params['client_policy_id'];
@@ -523,6 +598,13 @@ class sendMailNotification
$mail_content = str_replace(["[[member_mobile]]", "{{member_mobile}}"], $employee_mobile_no, $mail_content);
$mail_content = str_replace(["[[member_summary]]", "{{member_summary}}"], $table_content , $mail_content);
+ $mail_content = preg_replace('/
]*>( |\s)*<\/p>/i', '', $mail_content);
+
+ $data['params'] = $params;$data['client_logo'] = $client_logo;
+ $data['mail_content'] = $mail_content;
+ $mail_content = view('mail_template', $data);
+
+
// print_r($mail_content); die;
// $mail = "aadhavanvalli@gmail.com";
@@ -825,6 +907,13 @@ class sendMailNotification
$full_name = $value['first_name'] .' ' .$value['last_name'];
$mail_content = str_replace(["[[member_name]]", "{{member_name}}"], $full_name , $mail_content);
+ $mail_content = preg_replace('/
]*>( |\s)*<\/p>/i', '', $mail_content);
+
+ $data['params'] = $params;$data['client_logo'] = $client_logo;
+ $data['mail_content'] = $mail_content;
+ $mail_content = view('mail_template', $data);
+
+
$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'}};
}
@@ -1118,6 +1207,11 @@ class sendMailNotification
$mail_content = str_replace(["[[member_summary]]", "{{member_summary}}"], $table_content , $mail_content);
+ $mail_content = preg_replace('/
]*>( |\s)*<\/p>/i', '', $mail_content);
+
+ $data['params'] = $params;$data['client_logo'] = $client_logo;
+ $data['mail_content'] = $mail_content;
+ $mail_content = view('mail_template', $data);
$hr_mails = $client_data['hr_mails'];
$mail_array = explode(',', $hr_mails);
@@ -1182,7 +1276,14 @@ class sendMailNotification
$mail_content = str_replace(["[[app_link]]", "{{app_link}}"], "Review Details", $mail_content);
- if ($mail != null || $mail != '') {
+ if ( isset($mail) && !empty($mail) ) {
+
+ $mail_content = preg_replace('/
]*>( |\s)*<\/p>/i', '', $mail_content);
+
+ $data['params'] = $params;$data['client_logo'] = $client_logo;
+ $data['mail_content'] = $mail_content;
+ $mail_content = view('mail_template', $data);
+
$wholeData = ['mail' => $mail, 'subject' => $subject,'message'=> $mail_content,'bcc'=> $client_data['common_mails'], 'reply_to' => $client_data['reply_to'], 'attachments' => $attachments];
}
@@ -1215,6 +1316,13 @@ class sendMailNotification
if ((isset($notification_data) && $notification_data['enabled'] == 1)) {
if (isset($mail) && !empty($mail)) {
+
+ $mail_content = preg_replace('/
]*>( |\s)*<\/p>/i', '', $mail_content);
+
+ $data['params'] = $params;$data['client_logo'] = $client_logo;
+ $data['mail_content'] = $mail_content;
+ $mail_content = view('mail_template', $data);
+
$wholeData = ['mail' => $mail, 'subject' => $subject,'message'=> $mail_content, 'bcc'=> $client_data['common_mails'], 'reply_to' => $client_data['reply_to']];
}
@@ -1268,6 +1376,67 @@ class sendMailNotification
$mail_content = str_replace(["[[ecard_download_link]]", "{{ecard_download_link}}"], "Download Insurance Card", $mail_content);
$mail_content = str_replace(["[[client_name]]", "{{client_name}}"], $client_data['client_name'], $mail_content);
+ $mail_content = preg_replace('/
]*>( |\s)*<\/p>/i', '', $mail_content);
+
+ $data['params'] = $params;$data['client_logo'] = $client_logo;
+ $data['mail_content'] = $mail_content;
+ $mail_content = view('mail_template', $data);
+
+ $wholeData = ['mail' => $mail, 'subject' => $subject,'message'=> $mail_content,'bcc'=> $client_data['common_mails'],'attachments' => $attachments, 'reply_to' => $client_data['reply_to']];
+
+ return $wholeData;
+
+ }else if($action == 'member_common_mail'){
+
+ $notification = $params['notification_data'];
+ $client_data = $params['client_data'];
+ $mail = $params['test_mail'];
+ $mailAttachmentModel = new MailAttachmentModel();
+ $attachment_data = $mailAttachmentModel
+ ->select('file_path, file_name')
+ ->where('notification_id', $notification['id'])
+ ->where('is_active', 1)
+ ->findAll();
+
+ $attachments = [];
+ foreach ($attachment_data as $data) {
+ $attachments[] = [
+ "filePath" => WRITEPATH . $data['file_path'],
+ "fileName" => $data['file_name']
+ ];
+ }
+
+ $mail_content = $notification['mail_content'];
+ $subject = $notification['subject'];
+
+ $rand_string = 'HX3kUh';
+ $link = generate_download_link($rand_string).'/1';
+
+ $name = 'John Doe';
+ $mobile = 9080706050;
+
+ $nhance_logo = $_ENV['NHANCE_LOGO'];
+ $app_link = $_ENV['App_Url'];
+ $post_enrollment_app_link = $_ENV['POST_ENROLLMENT_APP_LINK'];
+
+ $client_logo = base_url() . "public/uploads/logo/" . $client_data['client_logo'];
+
+ $mail_content = str_replace(["[[nhance_logo]]", "{{nhance_logo}}"], "
", $mail_content);
+ $mail_content = str_replace(["[[client_logo]]", "{{client_logo}}"], "
", $mail_content);
+
+ $mail_content = str_replace(["[[member_name]]", "{{member_name}}"], $name, $mail_content);
+ $mail_content = str_replace(["[[member_mobile]]", "{{member_mobile}}"], $mobile, $mail_content);
+ $mail_content = str_replace(["[[app_link]]", "{{app_link}}"], "Review Details", $mail_content);
+ $mail_content = str_replace(["[[post_enrollment_app_link]]", "{{post_enrollment_app_link}}"], "Review Details", $mail_content);
+ $mail_content = str_replace(["[[ecard_download_link]]", "{{ecard_download_link}}"], "Download Insurance Card", $mail_content);
+ $mail_content = str_replace(["[[client_name]]", "{{client_name}}"], $client_data['client_name'], $mail_content);
+
+ $mail_content = preg_replace('/
]*>( |\s)*<\/p>/i', '', $mail_content);
+
+ $data['params'] = $params;$data['client_logo'] = $client_logo;
+ $data['mail_content'] = $mail_content;
+ $mail_content = view('mail_template', $data);
+
$wholeData = ['mail' => $mail, 'subject' => $subject,'message'=> $mail_content,'bcc'=> $client_data['common_mails'],'attachments' => $attachments, 'reply_to' => $client_data['reply_to']];
return $wholeData;
@@ -1419,6 +1588,11 @@ class sendMailNotification
$mail_content = str_replace(["[[member_mobile]]", "{{member_mobile}}"], $mobile, $mail_content);
$mail_content = str_replace(["[[member_summary]]", "{{member_summary}}"], $table_content , $mail_content);
+ $mail_content = preg_replace('/
]*>( |\s)*<\/p>/i', '', $mail_content);
+
+ $data['params'] = $params;$data['client_logo'] = $client_logo;
+ $data['mail_content'] = $mail_content;
+ $mail_content = view('mail_template', $data);
$wholeData = ['mail' => $mail, 'subject' => $subject,'message'=> $mail_content, 'bcc'=> $client_data['common_mails'], 'reply_to' => $client_data['reply_to']];
@@ -1568,6 +1742,13 @@ class sendMailNotification
$mail_content = str_replace(["[[member_name]]", "{{member_name}}"], $name . ' (' . $emp_code . ')' , $mail_content);
$mail_content = str_replace(["[[member_summary]]", "{{member_summary}}"], $table_content , $mail_content);
+
+ $mail_content = preg_replace('/
]*>( |\s)*<\/p>/i', '', $mail_content);
+
+ $data['params'] = $params;$data['client_logo'] = $client_logo;
+ $data['mail_content'] = $mail_content;
+ $mail_content = view('mail_template', $data);
+
$wholeData = ['mail' => $mail, 'subject' => $subject,'message'=> $mail_content, 'reply_to' => $client_data['reply_to']];
return $wholeData;
@@ -1717,6 +1898,11 @@ class sendMailNotification
$mail_content = str_replace(["[[member_name]]", "{{member_name}}"], $name . ' (' . $emp_code . ')' , $mail_content);
$mail_content = str_replace(["[[member_summary]]", "{{member_summary}}"], $table_content , $mail_content);
+ $mail_content = preg_replace('/
]*>( |\s)*<\/p>/i', '', $mail_content);
+
+ $data['params'] = $params;$data['client_logo'] = $client_logo;
+ $data['mail_content'] = $mail_content;
+ $mail_content = view('mail_template', $data);
$wholeData = ['mail' => $mail, 'subject' => $subject,'message'=> $mail_content, 'reply_to' => $client_data['reply_to']];
diff --git a/app/Helpers/utility_helper.php b/app/Helpers/utility_helper.php
index c03ffcc9..8f976243 100755
--- a/app/Helpers/utility_helper.php
+++ b/app/Helpers/utility_helper.php
@@ -53,6 +53,20 @@ if (!function_exists('change_date_format2')) {
if (!function_exists('file_Upload')) {
function file_Upload($fileToUpload, $filepath)
+ {
+ if ($fileToUpload !== null && $fileToUpload->isValid() && !$fileToUpload->hasMoved()) {
+ $fileToUpload->move($filepath);
+ $fileName = $fileToUpload->getName();
+ $fileName = preg_replace('/[\s\x{00A0}\x{200B}-\x{200D}\x{FEFF}]/u', '', $fileName);
+ return $fileName;
+ } else {
+ return "";
+ }
+ }
+}
+
+if (!function_exists('file_Upload_for_lead')) {
+ function file_Upload_for_lead($fileToUpload, $filepath)
{
if ($fileToUpload !== null && $fileToUpload->isValid() && !$fileToUpload->hasMoved()) {
$fileToUpload->move($filepath);
@@ -98,8 +112,9 @@ if (!function_exists('file_Upload')) {
// }
// }
+// function for only using in the Flutter Claim File Upload
if (!function_exists('multi_file_Upload')) {
- function multi_file_Upload($fileToUpload, $filepath)
+ function multi_file_Upload($fileToUpload, $filepath, $docs_name = [])
{
$uploadedFiles = [];
@@ -109,13 +124,15 @@ if (!function_exists('multi_file_Upload')) {
foreach ($files as $file) {
// If file is itself an array (multiple under same input name)
if (is_array($file)) {
- foreach ($file as $f) {
+ foreach ($file as $index => $f) {
if ($f !== null && $f->isValid() && !$f->hasMoved()) {
- $fileName = $f->getRandomName(); // safer unique name
- $f->move($filepath, $fileName);
+ $fileRandomName = $f->getRandomName(); // safer unique name
+ $fileName = $f->getName();
+ $f->move($filepath, $fileRandomName);
$uploadedFiles[] = [
'file_name' => $fileName,
- 'file_path' => $filepath . $fileName
+ 'doc_name' => $docs_name[$index] ?? $fileName,
+ 'file_path' => $filepath . $fileRandomName
];
}
}
@@ -858,3 +875,29 @@ if (!function_exists('expected_amount_calc')) {
return round($expectedAmount, 2); // Optional: round to 2 decimal places
}
}
+
+if (!function_exists('getFileIfExists')) {
+ function getFileIfExists($path)
+ {
+ return file_exists(FCPATH . $path) ? base_url($path) : '';
+ }
+}
+
+if (!function_exists('removeNumberFormatting')) {
+ function removeNumberFormatting($number)
+ {
+ return (float) str_replace(',', '', trim($number));
+ }
+}
+
+if (!function_exists('formatKey')) {
+ function formatKey($key, $len = 3)
+ {
+ $words = explode('_', $key);
+ $formatted = array_map(function ($word) use ($len) {
+ return strlen($word) < $len ? strtoupper($word) : ucfirst(strtolower($word));
+ }, $words);
+ return implode(' ', $formatted);
+ }
+}
+
diff --git a/app/Models/ClaimFilesModel.php b/app/Models/ClaimFilesModel.php
index 8e22ae01..2d747e3d 100644
--- a/app/Models/ClaimFilesModel.php
+++ b/app/Models/ClaimFilesModel.php
@@ -19,7 +19,8 @@ class ClaimFilesModel extends Model
'updated_by',
'created_at',
'updated_at',
- 'is_active'
+ 'is_active',
+ 'file_name',
];
// Callbacks
diff --git a/app/Models/ClientDepositModel.php b/app/Models/ClientDepositModel.php
index 9d45f38f..8a61b204 100755
--- a/app/Models/ClientDepositModel.php
+++ b/app/Models/ClientDepositModel.php
@@ -28,7 +28,8 @@ class ClientDepositModel extends Model
"event_name",
"unit",
"cd_ac_pk",
- "record_date"
+ "record_date",
+ "policy_transaction_id",
];
diff --git a/app/Models/ClientPolicyModel.php b/app/Models/ClientPolicyModel.php
index 132080de..185f4a20 100755
--- a/app/Models/ClientPolicyModel.php
+++ b/app/Models/ClientPolicyModel.php
@@ -55,6 +55,8 @@ class ClientPolicyModel extends Model
"cd_ac_pk",
"is_lgbtq",
"placement_json",
+ "policy_entry_from",
+ "is_from_lead",
];
// Callbacks
@@ -429,8 +431,8 @@ class ClientPolicyModel extends Model
$emp_count = $this->db->affectedRows();
// Log the result
- log_message('info', "Client policies updated: {$client_count}");
- log_message('info', "Employee policies updated: {$emp_count}");
+ log_message('error', "Client policies updated: {$client_count}");
+ log_message('error', "Employee policies updated: {$emp_count}");
return ['client' => $client_count, 'emp' => $emp_count];
}
diff --git a/app/Models/CommonEMailModel.php b/app/Models/CommonEMailModel.php
new file mode 100644
index 00000000..4b96f7ee
--- /dev/null
+++ b/app/Models/CommonEMailModel.php
@@ -0,0 +1,42 @@
+where('employee_id',$arr['employee_id'])
->where('client_policy_id',$arr['client_policy_id'])
+ ->where('status', 'active')
->where('is_active',1)
->find();
}
@@ -607,9 +608,41 @@ 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 (a.endorsement_id IS NOT NULL OR a.endorsement_id != '')" : "AND (a.endorsement_id IS NULL OR a.endorsement_id = '')";
- $subquery_endorsement_condition = "{$insurer_or_tpa}" === 'tpa' ? "WHERE (endorsement_id IS NOT NULL OR endorsement_id != '')" : "WHERE (endorsement_id IS NULL OR endorsement_id = '')";
+ // $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 = '')";
+ // $subquery_endorsement_condition = "{$insurer_or_tpa}" === 'tpa' ? "WHERE (endorsement_id IS NOT NULL OR endorsement_id != '')" : "WHERE (endorsement_id IS NULL OR endorsement_id = '')";
+ $endorsement_condition = "{$insurer_or_tpa}" === 'tpa' ? "AND (a.endorsement_id IS NULL OR a.is_tpa_export IS NULL)" : "AND (a.endorsement_id IS NULL OR a.endorsement_id = '')";
+ $subquery_endorsement_condition = "{$insurer_or_tpa}" === 'tpa' ? "WHERE (endorsement_id IS NULL OR is_tpa_export IS NULL)" : "WHERE (endorsement_id IS NULL OR endorsement_id = '')";
+
+ /*
+ ROUND(sidata.new_si_premium - sidata.old_si_premium, 2) AS difference_premium,
+ ROUND(
+ (sidata.new_si_premium - sidata.old_si_premium) *
+ (DATEDIFF(employee_polices.policy_end_date, sidata.date_of_coverage) + 1) / 365,
+ 2
+ ) AS pro_rata_premium,
+ ROUND(
+ (
+ (sidata.new_si_premium - sidata.old_si_premium) *
+ (DATEDIFF(employee_polices.policy_end_date, sidata.date_of_coverage) + 1) / 365
+ ) * 0.18,
+ 2
+ ) AS gst,
+ ROUND(
+ (
+ (sidata.new_si_premium - sidata.old_si_premium) *
+ (DATEDIFF(employee_polices.policy_end_date, sidata.date_of_coverage) + 1) / 365
+ ) +
+ ROUND(
+ (
+ (sidata.new_si_premium - sidata.old_si_premium) *
+ (DATEDIFF(employee_polices.policy_end_date, sidata.date_of_coverage) + 1) / 365
+ ) * 0.18,
+ 2
+ ),
+ 2
+ ) AS total
+ */
$query = $this->db->query("
SELECT
@@ -643,33 +676,40 @@ class EmployeePolicyModel extends Model
sidata.old_si_premium,
sidata.date_of_coverage,
DATEDIFF(employee_polices.policy_end_date, sidata.date_of_coverage) + 1 AS no_of_days,
- ROUND(sidata.new_si_premium - sidata.old_si_premium, 2) AS difference_premium,
+
+ ROUND(ABS(sidata.new_si_premium - sidata.old_si_premium), 2) AS difference_premium,
ROUND(
- (sidata.new_si_premium - sidata.old_si_premium) *
- (DATEDIFF(employee_polices.policy_end_date, sidata.date_of_coverage) + 1) / 365,
+ ABS(
+ (sidata.new_si_premium - sidata.old_si_premium) *
+ (DATEDIFF(employee_polices.policy_end_date, sidata.date_of_coverage) + 1) / 365
+ ),
2
) AS pro_rata_premium,
ROUND(
- (
- (sidata.new_si_premium - sidata.old_si_premium) *
- (DATEDIFF(employee_polices.policy_end_date, sidata.date_of_coverage) + 1) / 365
- ) * 0.18,
+ ABS(
+ (
+ (sidata.new_si_premium - sidata.old_si_premium) *
+ (DATEDIFF(employee_polices.policy_end_date, sidata.date_of_coverage) + 1) / 365
+ ) * 0.18
+ ),
2
) AS gst,
ROUND(
- (
- (sidata.new_si_premium - sidata.old_si_premium) *
- (DATEDIFF(employee_polices.policy_end_date, sidata.date_of_coverage) + 1) / 365
- ) +
- ROUND(
- (
- (sidata.new_si_premium - sidata.old_si_premium) *
- (DATEDIFF(employee_polices.policy_end_date, sidata.date_of_coverage) + 1) / 365
- ) * 0.18,
- 2
+ ABS(
+ (
+ (sidata.new_si_premium - sidata.old_si_premium) *
+ (DATEDIFF(employee_polices.policy_end_date, sidata.date_of_coverage) + 1) / 365
+ ) +
+ (
+ (
+ (sidata.new_si_premium - sidata.old_si_premium) *
+ (DATEDIFF(employee_polices.policy_end_date, sidata.date_of_coverage) + 1) / 365
+ ) * 0.18
+ )
),
2
) AS total
+
FROM
emp_endorsement a
LEFT JOIN employees ON employees.emp_code = a.emp_code
@@ -1471,7 +1511,7 @@ class EmployeePolicyModel extends Model
ep.tpa_id,
ep.uhid,
- ep.policy_end_date,
+ cp.policy_end_date,
ep.basic_cover_si,
clients.client_name,
@@ -1492,6 +1532,7 @@ class EmployeePolicyModel extends Model
tpa.tpa_logo AS tpa_logo,
tpa.front_card,
tpa.back_card,
+ tpa.network_hospitals,
tpa.short_name AS tpa_short_name'
)
@@ -1531,12 +1572,19 @@ class EmployeePolicyModel extends Model
e.doj,
e.band,
TIMESTAMPDIFF(YEAR, e.dob, CURDATE()) AS emp_age,
- (SELECT name FROM employees WHERE relationship = "Self" and emp_code = ' . $this->db->escape($emp_code) . ' and client_id = '.$client_id.' LIMIT 1) AS self,
-
+ (
+ SELECT name FROM employees
+ WHERE relationship = "Self"
+ and emp_code = ' . $this->db->escape($emp_code) . '
+ and client_id = '.$client_id.'
+ and is_active = 1
+ and emp_status = "active"
+ LIMIT 1
+ ) AS self,
ep.tpa_id,
ep.uhid,
- ep.policy_end_date,
+ cp.policy_end_date,
ep.basic_cover_si,
clients.client_name,
@@ -1557,6 +1605,7 @@ class EmployeePolicyModel extends Model
tpa.tpa_logo AS tpa_logo,
tpa.front_card,
tpa.back_card,
+ tpa.network_hospitals,
tpa.short_name AS tpa_short_name'
)
diff --git a/app/Models/EndorsementModel.php b/app/Models/EndorsementModel.php
index 60b675cb..30c7a01f 100644
--- a/app/Models/EndorsementModel.php
+++ b/app/Models/EndorsementModel.php
@@ -25,7 +25,8 @@ class EndorsementModel extends Model
'updated_by',
'updated_at',
'file_id',
- 'is_active'
+ 'is_active',
+ 'batch_file_id',
];
}
diff --git a/app/Models/FileModel.php b/app/Models/FileModel.php
index ff4f584e..0f72c18f 100755
--- a/app/Models/FileModel.php
+++ b/app/Models/FileModel.php
@@ -22,6 +22,7 @@ class FileModel extends Model
"uploaded_by",
"updated_by",
"hr_file_id",
+ "is_comparison_skipped",
];
diff --git a/app/Models/InsurerBranchModel.php b/app/Models/InsurerBranchModel.php
index a976e478..2cd28703 100755
--- a/app/Models/InsurerBranchModel.php
+++ b/app/Models/InsurerBranchModel.php
@@ -27,7 +27,7 @@ class InsurerBranchModel extends Model
public function getInsurerBranchesWithInsurerNames()
{
- $query = $this->select('insurer_branch.*, I.short_name as insurer_name')
+ $query = $this->select('insurer_branch.*, I.short_name as insurer_name, I.category')
->join('insurers I', 'insurer_branch.insurer_id = I.id', 'left')
->find();
return $query;
diff --git a/app/Models/LeadsModel.php b/app/Models/LeadsModel.php
index 7cc56602..d3c9ac40 100644
--- a/app/Models/LeadsModel.php
+++ b/app/Models/LeadsModel.php
@@ -106,6 +106,7 @@ class LeadsModel extends Model
'is_insurer_auto_mail',
'quote_received_insurer',
'acm_id',
+ 'policy_with_correction',
];
@@ -204,78 +205,151 @@ class LeadsModel extends Model
return $result;
}
+ // public function getDashData()
+ // {
+ // $statuses = $this->db->table('leads')
+ // ->select('status, policy_with_correction')
+ // ->where("is_active", 1)
+ // ->groupBy('status')
+ // ->get()
+ // ->getResultArray();
+
+ // $policy_with_correction_count = $this->db->table('leads')
+ // ->where('is_active', 1)
+ // ->where('policy_with_correction', 1)
+ // ->countAllResults();
+
+ // $selectParts = [];
+
+ // foreach ($statuses as $status) {
+ // $s = $status['status'];
+ // $alias = strtolower(str_replace(' ', '_', $s));
+
+ // // Count alias
+ // $selectParts[] = "SUM(CASE WHEN status = '{$s}' THEN 1 ELSE 0 END) AS `{$alias}`";
+
+ // // IDs alias
+ // $selectParts[] = "GROUP_CONCAT(CASE WHEN status = '{$s}' THEN leads.id ELSE NULL END) AS `{$alias}_ids`";
+ // }
+
+ // $select = implode(", ", $selectParts);
+
+ // // Start query builder
+ // $builder = $this->db->table('leads');
+
+ // $builder->select($select);
+
+ // // Auditing subquery
+ // $subquery = "(SELECT pk, MAX(created_at) AS last_claim_status_change
+ // FROM auditing_history
+ // WHERE table_name = 'leads' AND field_name = 'status'
+ // GROUP BY pk)";
+
+ // $builder->join("{$subquery} AS th", 'leads.id = th.pk', 'left');
+
+ // // Date filtering for last status change
+ // $dateLimit = 3;
+ // $dateThreshold = date('Y-m-d H:i:s', strtotime("-{$dateLimit} days"));
+
+ // $builder->groupStart()
+ // ->where('th.last_claim_status_change <=', $dateThreshold)
+ // ->orWhere('th.last_claim_status_change IS NULL')
+ // ->groupEnd();
+
+ // // Add only active
+ // $builder->where("leads.is_active", 1);
+
+ // $lead_data = $builder->get()->getResultArray();
+
+ // // dd($this->db->getLastQuery());
+
+ // // Fallback for empty results
+ // if (empty($lead_data)) {
+ // $lead_data[0] = ['total' => 0];
+ // foreach ($statuses as $status) {
+ // $alias = strtolower(str_replace(' ', '_', $status['status']));
+ // $lead_data[0][$alias] = 0;
+ // $lead_data[0]["{$alias}_ids"] = '';
+ // }
+ // }
+
+ // // Calculate total
+ // $total = 0;
+ // foreach ($lead_data[0] as $key => $value) {
+ // // if (!str_ends_with($key, '_ids') && $key != "won") {
+ // // $total += (int) $value;
+ // // }
+
+ // if (!str_ends_with($key, '_ids')) {
+ // $total += (int) $value;
+ // }
+ // }
+
+ // $total = $total + $policy_with_correction_count ?? 0;
+ // $lead_data[0]['total'] = $total;
+ // $lead_data[0]['policy_with_correction'] = $policy_with_correction_count;
+
+
+ // // dd($lead_data[0]);
+ // return $lead_data[0];
+ // }
+
+
public function getDashData()
{
+ // Get all unique statuses
$statuses = $this->db->table('leads')
- ->select('status')
- ->where("is_active", 1)
- ->groupBy('status')
+ ->select('DISTINCT(status)')
+ ->where('is_active', 1)
->get()
->getResultArray();
-
+
+ $policy_with_correction_data = $this->db->table('leads')
+ ->select('COUNT(id) AS count, GROUP_CONCAT(id) AS ids')
+ ->where('is_active', 1)
+ ->where('policy_with_correction', 1)
+ ->get()
+ ->getRowArray();
+
+ if (empty($statuses)) {
+ return ['total' => 0];
+ }
+
+ // Build dynamic select fields for each status
$selectParts = [];
-
- foreach ($statuses as $status) {
- $s = $status['status'];
- $alias = strtolower(str_replace(' ', '_', $s));
-
- // Count alias
- $selectParts[] = "SUM(CASE WHEN status = '{$s}' THEN 1 ELSE 0 END) AS `{$alias}`";
-
- // IDs alias
- $selectParts[] = "GROUP_CONCAT(CASE WHEN status = '{$s}' THEN leads.id ELSE NULL END) AS `{$alias}_ids`";
+ foreach ($statuses as $row) {
+ $status = $row['status'];
+ $alias = strtolower(str_replace(' ', '_', $status));
+
+ $selectParts[] = "SUM(CASE WHEN status = '{$status}' THEN 1 ELSE 0 END) AS `{$alias}`";
+ $selectParts[] = "GROUP_CONCAT(CASE WHEN status = '{$status}' THEN id END) AS `{$alias}_ids`";
}
-
+
$select = implode(", ", $selectParts);
-
- // Start query builder
- $builder = $this->db->table('leads');
-
- $builder->select($select);
-
- // Auditing subquery
- $subquery = "(SELECT pk, MAX(created_at) AS last_claim_status_change
- FROM auditing_history
- WHERE table_name = 'leads' AND field_name = 'status'
- GROUP BY pk)";
-
- $builder->join("{$subquery} AS th", 'leads.id = th.pk', 'left');
-
- // Date filtering for last status change
- $dateLimit = 3;
- $dateThreshold = date('Y-m-d H:i:s', strtotime("-{$dateLimit} days"));
-
- $builder->groupStart()
- ->where('th.last_claim_status_change <=', $dateThreshold)
- ->orWhere('th.last_claim_status_change IS NULL')
- ->groupEnd();
-
- // Add only active
- $builder->where("leads.is_active", 1);
-
- $lead_data = $builder->get()->getResultArray();
-
- // Fallback for empty results
- if (empty($lead_data)) {
- $lead_data[0] = ['total' => 0];
- foreach ($statuses as $status) {
- $alias = strtolower(str_replace(' ', '_', $status['status']));
- $lead_data[0][$alias] = 0;
- $lead_data[0]["{$alias}_ids"] = '';
- }
- }
-
+
+ // Main query
+ $lead_data = $this->db->table('leads')
+ ->select($select)
+ ->where('is_active', 1)
+ ->get()
+ ->getRowArray();
+
// Calculate total
$total = 0;
- foreach ($lead_data[0] as $key => $value) {
- if (!str_ends_with($key, '_ids') && $key != "won") {
- $total += (int) $value;
+ foreach ($lead_data as $key => $val) {
+ if (!str_ends_with($key, '_ids')) {
+ $total += (int) $val;
}
}
- $lead_data[0]['total'] = $total;
-
- // dd($lead_data[0]);
- return $lead_data[0];
+
+ $lead_data['total'] = $total;
+ $lead_data['policy_with_correction'] = $policy_with_correction_data['count'] ?? 0;
+ $lead_data['policy_with_correction_ids'] = $policy_with_correction_data['ids'] ?? null;
+
+ // dd($lead_data);
+ return $lead_data;
}
+
+
}
diff --git a/app/Models/PolicyTransactionModel.php b/app/Models/PolicyTransactionModel.php
index 6ea94e65..c62fa4cc 100644
--- a/app/Models/PolicyTransactionModel.php
+++ b/app/Models/PolicyTransactionModel.php
@@ -1,1095 +1,772 @@
db->table('policy_transaction')
+ ->select("
+ policy_transaction.*,
+ DATE_FORMAT(policy_transaction.policy_issue_date, '%d %b %Y') AS policy_issue_date,
+ DATE_FORMAT(
+ IF(policy_transaction.month IS NULL,
+ policy_transaction.policy_issue_date,
+ policy_transaction.month),
+ '%b %Y') AS policy_issue_month,
+ CASE
+ WHEN clients.client_type = 1 THEN 'Group'
+ WHEN clients.client_type = 2 THEN 'Retail'
+ ELSE '-'
+ END AS client_type,
+ CASE
+ WHEN policy_transaction.revenue_type = 'NA' THEN 'Fresh'
+ ELSE 'Renewal'
+ END AS revenue_type,
+ CASE
+ WHEN policy_transaction.action_type = 'inception' THEN 'Policy'
+ ELSE 'Endorsement'
+ END AS action_type,
+ clients.client_name AS client_name,
+ clients.short_name AS client_short_name,
+ client_branch.branch_name AS client_branch_name,
+ client_branch.address1 AS client_address,
+ policy_type.policy_type,
+ policy_type.bap,
+ insurers.name AS insurer_name,
+ insurers.short_name AS insurer_short_name,
+ insurer_branch.branch_name AS insurer_branch_name,
+ insurer_branch.branch_code AS insurer_branch_code,
+ user_profiles.first_name as user_name,
+ vehicle.vehicle_no,
+ tpa.name as tpa_name,
+ pt_co_share_details.remark as remarks,
+ pt_co_share_details.reward,
+ pt_co_share_details.bp_amt,
+ sales_user.first_name as salse_person_name,
+ service_user.first_name as service_person_name,
- // BDS Report OLD Functin for QUERY
- // public function getBDSReportList($client_id, $policy_id, $branch_id, $issuer)
- 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("
- policy_transaction.*,
- DATE_FORMAT(policy_transaction.policy_issue_date, '%d %b %Y') AS policy_issue_date,
- DATE_FORMAT(
- IF(policy_transaction.month IS NULL,
- policy_transaction.policy_issue_date,
- policy_transaction.month),
- '%b %Y') AS policy_issue_month,
- CASE
- WHEN clients.client_type = 1 THEN 'Group'
- WHEN clients.client_type = 2 THEN 'Retail'
- ELSE '-'
- END AS client_type,
- CASE
- WHEN policy_transaction.revenue_type = 'NA' THEN 'Fresh'
- ELSE 'Renewal'
- END AS revenue_type,
- CASE
- WHEN policy_transaction.action_type = 'inception' THEN 'Policy'
- ELSE 'Endorsement'
- END AS action_type,
- clients.client_name AS client_name,
- clients.short_name AS client_short_name,
- client_branch.branch_name AS client_branch_name,
- client_branch.address1 AS client_address,
- policy_type.policy_type,
- policy_type.bap,
- insurers.name AS insurer_name,
- insurers.short_name AS insurer_short_name,
- insurer_branch.branch_name AS insurer_branch_name,
- insurer_branch.branch_code AS insurer_branch_code,
- user_profiles.first_name as user_name,
- vehicle.vehicle_no,
- tpa.name as tpa_name,
- pt_co_share_details.remark as remarks,
- pt_co_share_details.reward,
- pt_co_share_details.bp_amt,
- sales_user.first_name as salse_person_name,
- service_user.first_name as service_person_name,
+ ROUND((pt_co_share_details.bp_amt + pt_co_share_details.tp_amt + pt_co_share_details.tep_amt), 2) AS premium_wo_gst,
- ROUND((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) * 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((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,
- 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,
- 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_tp_per + pt_co_share_details.agreed_tep_per) AS agreed_tp_or_ter_per,
+ pt_co_share_details.agreed_bp_per,
- pt_co_share_details.agreed_bp_per,
-
- ROUND(
- (pt_co_share_details.bp_amt * pt_co_share_details.agreed_bp_per +
- (pt_co_share_details.tp_amt + pt_co_share_details.tep_amt) *
- (pt_co_share_details.agreed_tp_per + pt_co_share_details.agreed_tep_per)) / 100,
- 2) AS total_irda,
-
- ROUND(
- (ROUND(
+ ROUND(
(pt_co_share_details.bp_amt * pt_co_share_details.agreed_bp_per +
(pt_co_share_details.tp_amt + pt_co_share_details.tep_amt) *
(pt_co_share_details.agreed_tp_per + pt_co_share_details.agreed_tep_per)) / 100,
- 2) * 18 / 100),
- 2) AS gst_on_revenue,
+ 2) AS total_irda,
- ROUND(
- (ROUND(
- (pt_co_share_details.bp_amt * pt_co_share_details.agreed_bp_per +
- (pt_co_share_details.tp_amt + pt_co_share_details.tep_amt) *
- (pt_co_share_details.agreed_tp_per + pt_co_share_details.agreed_tep_per)) / 100,
- 2) +
ROUND(
(ROUND(
(pt_co_share_details.bp_amt * pt_co_share_details.agreed_bp_per +
(pt_co_share_details.tp_amt + pt_co_share_details.tep_amt) *
(pt_co_share_details.agreed_tp_per + pt_co_share_details.agreed_tep_per)) / 100,
2) * 18 / 100),
- 2)),
- 2) AS total_amt_received,
- insurer_statements.invoice_date,
- insurer_statements.invoice_no,
- insurer_statements.invoice_amount,
-
- (
- SELECT
- (SUM(inv_payment_details.inv_amt) + SUM(inv_payment_details.tds)) AS realization_amount
- FROM
- inv_payment_details
- WHERE
- inv_payment_details.statement_id = insurer_statements.id
- AND inv_payment_details.is_active = 1
-
- ) AS realization_amount,
+ 2) AS gst_on_revenue,
ROUND(
- insurer_statements.invoice_amount -
- (
- SELECT
- (SUM(inv_payment_details.inv_amt) + SUM(inv_payment_details.tds))
- FROM
- inv_payment_details
- WHERE
- inv_payment_details.statement_id = insurer_statements.id
- AND inv_payment_details.is_active = 1
- ),
- 2) AS outstanding_amount,
+ (ROUND(
+ (pt_co_share_details.bp_amt * pt_co_share_details.agreed_bp_per +
+ (pt_co_share_details.tp_amt + pt_co_share_details.tep_amt) *
+ (pt_co_share_details.agreed_tp_per + pt_co_share_details.agreed_tep_per)) / 100,
+ 2) +
+ ROUND(
+ (ROUND(
+ (pt_co_share_details.bp_amt * pt_co_share_details.agreed_bp_per +
+ (pt_co_share_details.tp_amt + pt_co_share_details.tep_amt) *
+ (pt_co_share_details.agreed_tp_per + pt_co_share_details.agreed_tep_per)) / 100,
+ 2) * 18 / 100),
+ 2)),
+ 2) AS total_amt_received,
+ insurer_statements.invoice_date,
+ insurer_statements.invoice_no,
+ insurer_statements.invoice_amount,
(
- SELECT
- GROUP_CONCAT(inv_payment_details.utr_no SEPARATOR ', ') AS utr_numbers
- FROM
- inv_payment_details
- WHERE
- inv_payment_details.statement_id = insurer_statements.id
- AND inv_payment_details.is_active = 1
- ) AS utr_numbers,
-
- (
- SELECT
- GROUP_CONCAT(inv_payment_details.received_date SEPARATOR ', ') AS payment_dates
- FROM
- inv_payment_details
- WHERE
- inv_payment_details.statement_id = insurer_statements.id
- AND inv_payment_details.is_active = 1
- ) AS payment_dates
-
- ")
- ->join('pt_co_share_details', 'policy_transaction.id = pt_co_share_details.pt_id', 'left')
- ->join('insurer_statements', 'pt_co_share_details.statement_id = insurer_statements.id', 'left')
- ->join('clients', 'clients.id = policy_transaction.client_id')
- ->join('client_branch', 'policy_transaction.client_branch_id = client_branch.id', 'left')
- ->join('client_policy', 'policy_transaction.client_policy_id = client_policy.id', 'left')
- ->join('user_profiles', 'policy_transaction.created_by = user_profiles.id', 'left')
- ->join('vehicle', 'policy_transaction.vehicle_id = vehicle.id', 'left')
- ->join('policy_type', 'policy_transaction.policy_type_id = policy_type.id', 'left')
- ->join('insurers', 'policy_transaction.insurer_id = insurers.id', 'left')
- ->join('insurer_branch', 'policy_transaction.insurer_branch_id = insurer_branch.id', 'left')
- ->join('tpa', 'policy_transaction.tpa_id = tpa.id', 'left')
- ->join('tpa_branch', 'policy_transaction.tpa_branch_id = tpa_branch.id', 'left')
- ->join('user_profiles AS sales_user', 'policy_transaction.sales_generated_by = sales_user.id', 'left')
- ->join('user_profiles AS service_user', 'policy_transaction.serviced_by = service_user.id', 'left')
- ->where('policy_transaction.is_active', 1);
-
- // Check if the start date and end date are provided
- if ($start_date != 0 && $end_date != 0 && $date_type != 0) {
-
- $startDate = date('Y-m-d 00:00:00', strtotime($start_date));
- $endDate = date('Y-m-d 23:59:59', strtotime($end_date));
-
- $builder->where('policy_transaction.' . $date_type . '>=', $startDate)
- ->where('policy_transaction.' . $date_type . '<=', $endDate);
- } else {
-
- // $fromDate = date('Y-m-d', strtotime('-30 days'));
- // $toDate = date('Y-m-d 23:59:59');
-
- // $builder->where('policy_transaction.created_at >=', $fromDate)
- // ->where('policy_transaction.created_at <=', $toDate);
- }
-
- if ($client_id != 0) {
- $builder->where('policy_transaction.client_id', $client_id);
- }
-
- if ($insurer_id != 0) {
- $builder->where('policy_transaction.insurer_id', $insurer_id);
- }
-
- if ($policy_type_id != 0) {
- $builder->where('client_policy.policy_type_id', $policy_type_id);
- }
-
- if ($issuer != 0) {
- $builder->where('policy_transaction.issuer', $issuer);
- }
-
- if ($client_id == 0 && $insurer_id == 0 && $policy_type_id == 0 && $date_type == 0 && $issuer == 0) {
-
- $fromDate = date('Y-m-d', strtotime('-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');
-
- return $builder->get()->getResultArray();
- }
-
- // BDS Report NEW Functin for QUERY
- // public function getBDSReportList($client_id, $policy_id, $branch_id, $issuer)
-
- // public function getBDSReportList($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0, $client_branch_id = 0, $insurer_branch_id = 0, $client_policy_id = 0)
- // {
-
- // $date_condition = '';
- // if($date_type == 'statement_month' && $start_date != 0 && $end_date != 0) {
- // $date_condition = "
- // AND insurer_statements.month >= '".$start_date ."'
- // AND insurer_statements.month <= '".$end_date ."'
- // ";
- // }
-
- // $builder = $this->db->table('policy_transaction')
- // ->select("
- // policy_transaction.*,
- // DATE_FORMAT(policy_transaction.policy_issue_date, '%d %b %Y') AS policy_issue_date,
- // DATE_FORMAT(
- // IF(policy_transaction.month IS NULL,
- // policy_transaction.policy_issue_date,
- // policy_transaction.month),
- // '%b %Y') AS policy_issue_month,
- // CASE
- // WHEN clients.client_type = 1 THEN 'Group'
- // WHEN clients.client_type = 2 THEN 'Retail'
- // ELSE '-'
- // END AS client_type,
- // CASE
- // WHEN policy_transaction.revenue_type = 'NA' THEN 'Fresh'
- // ELSE 'Renewal'
- // END AS revenue_type,
- // CASE
- // WHEN policy_transaction.action_type = 'inception' THEN 'Policy'
- // ELSE 'Endorsement'
- // END AS action_type,
- // clients.client_name AS client_name,
- // clients.short_name AS client_short_name,
- // client_branch.branch_name AS client_branch_name,
- // client_branch.address1 AS client_address,
- // policy_type.policy_type,
- // policy_type.bap,
- // insurers.name AS insurer_name,
- // insurers.short_name AS insurer_short_name,
- // insurer_branch.branch_name AS insurer_branch_name,
- // insurer_branch.branch_code AS insurer_branch_code,
- // user_profiles.first_name as user_name,
- // vehicle.vehicle_no,
- // tpa.name as tpa_name,
- // pt_co_share_details.remark as remarks,
- // pt_co_share_details.bp_amt,
- // pt_co_share_details.exp_amt,
- // pt_co_share_details.id as pt_id,
- // sales_user.first_name as salse_person_name,
- // service_user.first_name as service_person_name,
-
- // ROUND((pt_co_share_details.bp_amt + pt_co_share_details.tp_amt + pt_co_share_details.tep_amt), 2) AS premium_wo_gst,
-
- // ROUND((ROUND((pt_co_share_details.bp_amt + pt_co_share_details.tp_amt + pt_co_share_details.tep_amt), 2) * 18 / 100), 2) AS gst_amount,
-
- // ROUND((ROUND((pt_co_share_details.bp_amt + pt_co_share_details.tp_amt + pt_co_share_details.tep_amt), 2) + ROUND((ROUND((pt_co_share_details.bp_amt + pt_co_share_details.tp_amt + pt_co_share_details.tep_amt), 2) * 18 / 100), 2)), 2) AS total_premium,
-
- // ROUND((pt_co_share_details.tp_amt + pt_co_share_details.tep_amt), 2) AS tp_or_ter,
-
- // DATEDIFF(policy_transaction.policy_end_date, CURDATE()) AS days,
-
- // (pt_co_share_details.agreed_tp_per + pt_co_share_details.agreed_tep_per) AS agreed_tp_or_ter_per,
-
- // pt_co_share_details.agreed_bp_per,
- // ROUND(
- // (
- // SELECT
- // (
- // SUM(co_share_stmt_details.actual_bp_brokerage_amt) +
- // SUM(co_share_stmt_details.actual_tp_brokerage_amt) +
- // SUM(co_share_stmt_details.actual_tep_brokerage_amt) +
- // SUM(co_share_stmt_details.reward)
-
- // ) AS total_irda_amt
- // FROM
- // co_share_stmt_details
- // JOIN insurer_statements ON co_share_stmt_details.statement_id = insurer_statements.id
- // WHERE
- // co_share_stmt_details.co_share_id = pt_co_share_details.id
- // AND co_share_stmt_details.is_active = 1
- // AND insurer_statements.is_active = 1
- // $date_condition
- // ),
- // 2
- // ) AS total_irda_amt,
- // ROUND(
- // (
- // SELECT
- // (
- // SUM(co_share_stmt_details.reward)
-
- // ) AS reward
- // FROM
- // co_share_stmt_details
- // JOIN insurer_statements ON co_share_stmt_details.statement_id = insurer_statements.id
- // WHERE
- // co_share_stmt_details.co_share_id = pt_co_share_details.id
- // AND co_share_stmt_details.is_active = 1
- // AND insurer_statements.is_active = 1
- // $date_condition
- // ),
- // 2
- // ) AS reward,
-
- // ROUND(
- // (
- // SELECT
- // SUM(
- // COALESCE(co_share_stmt_details.actual_bp_brokerage_amt, 0) +
- // COALESCE(co_share_stmt_details.actual_tp_brokerage_amt, 0) +
- // COALESCE(co_share_stmt_details.actual_tep_brokerage_amt, 0) +
- // COALESCE(co_share_stmt_details.reward, 0)
- // ) AS total_irda_amt
- // FROM
- // co_share_stmt_details
- // JOIN pt_co_share_details AS pt_table ON co_share_stmt_details.co_share_id = pt_table.id
- // JOIN insurer_statements ON co_share_stmt_details.statement_id = insurer_statements.id
- // WHERE
- // co_share_stmt_details.co_share_id = pt_co_share_details.id
- // AND co_share_stmt_details.is_active = 1
- // AND pt_table.is_active = 1
- // AND insurer_statements.is_active = 1
- // AND insurer_statements.invoice_status IS NOT NULL
- // $date_condition
-
- // ),
- // 2
- // ) AS billed_amt,
-
- // ROUND(
- // (
- // (
- // SELECT
- // SUM(
- // COALESCE(co_share_stmt_details.actual_bp_brokerage_amt, 0)
- // + COALESCE(co_share_stmt_details.actual_tp_brokerage_amt, 0)
- // + COALESCE(co_share_stmt_details.actual_tep_brokerage_amt, 0)
- // + COALESCE(co_share_stmt_details.reward, 0)
- // )
- // FROM
- // co_share_stmt_details
- // JOIN insurer_statements ON co_share_stmt_details.statement_id = insurer_statements.id
- // WHERE
- // co_share_stmt_details.co_share_id = pt_co_share_details.id
- // AND co_share_stmt_details.is_active = 1
- // $date_condition
- // )
- // -
- // (
- // SELECT
- // SUM(
- // COALESCE(co_share_stmt_details.actual_bp_brokerage_amt, 0)
- // + COALESCE(co_share_stmt_details.actual_tp_brokerage_amt, 0)
- // + COALESCE(co_share_stmt_details.actual_tep_brokerage_amt, 0)
- // + COALESCE(co_share_stmt_details.reward, 0)
- // )
- // FROM
- // co_share_stmt_details
- // JOIN pt_co_share_details AS pt_table ON co_share_stmt_details.co_share_id = pt_table.id
- // JOIN insurer_statements ON co_share_stmt_details.statement_id = insurer_statements.id
- // WHERE
- // co_share_stmt_details.co_share_id = pt_co_share_details.id
- // AND co_share_stmt_details.is_active = 1
- // AND pt_table.is_active = 1
- // AND insurer_statements.is_active = 1
- // AND insurer_statements.invoice_status IS NULL
- // $date_condition
- // )
- // ),
- // 2
- // ) AS unbilled_amt
-
- // ")
- // ->join('pt_co_share_details', 'policy_transaction.id = pt_co_share_details.pt_id', 'left')
- // // ->join('insurer_statements', 'pt_co_share_details.statement_id = insurer_statements.id', 'left')
- // ->join('clients', 'clients.id = policy_transaction.client_id')
- // ->join('client_branch', 'policy_transaction.client_branch_id = client_branch.id', 'left')
- // ->join('client_policy', 'policy_transaction.client_policy_id = client_policy.id', 'left')
- // ->join('user_profiles', 'policy_transaction.created_by = user_profiles.id', 'left')
- // ->join('vehicle', 'policy_transaction.vehicle_id = vehicle.id', 'left')
- // ->join('policy_type', 'policy_transaction.policy_type_id = policy_type.id', 'left')
- // ->join('insurers', 'pt_co_share_details.insurer_id = insurers.id', 'left')
- // ->join('insurer_branch', 'pt_co_share_details.insurer_branch_id = insurer_branch.id', 'left')
- // ->join('tpa', 'policy_transaction.tpa_id = tpa.id', 'left')
- // ->join('tpa_branch', 'policy_transaction.tpa_branch_id = tpa_branch.id', 'left')
- // ->join('user_profiles AS sales_user', 'policy_transaction.sales_generated_by = sales_user.id', 'left')
- // ->join('user_profiles AS service_user', 'policy_transaction.serviced_by = service_user.id', 'left')
- // ->where('policy_transaction.is_active', 1)
- // ->where('pt_co_share_details.is_active', 1);
-
- // // Check if the start date and end date are provided
- // if ($start_date != 0 && $end_date != 0 && $date_type != 0 && $date_type != 'statement_month') {
-
- // $startDate = date('Y-m-d 00:00:00', strtotime($start_date));
- // $endDate = date('Y-m-d 23:59:59', strtotime($end_date));
-
- // $builder->where('policy_transaction.'.$date_type.'>=', $startDate)
- // ->where('policy_transaction.'.$date_type.'<=', $endDate);
-
- // }
-
- // // if($date_type == 'statement_month' && $start_date != 0 && $end_date != 0){
-
- // // $startDate = date('Y-m-d 00:00:00', strtotime($start_date));
- // // $endDate = date('Y-m-d 23:59:59', strtotime($end_date));
- // // $builder->where('policy_transaction.month >=', $startDate)
- // // ->where('policy_transaction.month <=', $endDate);
- // // }
-
- // // Conditionally join insurer_statements if $date_type == 'statement_month'
- // if ($date_type == 'statement_month' && $start_date != 0 && $end_date != 0) {
- // $startDate = date('Y-m-d', strtotime($start_date));
- // $endDate = date('Y-m-d', strtotime($end_date));
-
- // $builder->join('co_share_stmt_details', 'pt_co_share_details.id = co_share_stmt_details.co_share_id', 'left')
- // ->join('insurer_statements', 'co_share_stmt_details.statement_id = insurer_statements.id','left')
- // ->where('insurer_statements.is_active', 1)
- // ->where('insurer_statements.month >=', $startDate)
- // ->where('insurer_statements.month <=', $endDate)
- // ->groupBy('co_share_stmt_details.co_share_id');
- // }
-
- // if ($client_id != 0) {
- // $builder->where('policy_transaction.client_id', $client_id);
- // }
-
- // if ($insurer_id != 0) {
- // $builder->where('policy_transaction.insurer_id', $insurer_id);
- // }
-
- // if ($client_branch_id != 0) {
- // $builder->where('policy_transaction.client_branch_id', $client_branch_id);
- // }
-
- // if ($insurer_branch_id != 0) {
- // $builder->where('policy_transaction.insurer_branch_id', $insurer_branch_id);
- // }
-
- // if ($client_policy_id != 0) {
- // $builder->where('policy_transaction.client_policy_id', $client_policy_id);
- // }
-
-
-
- // if ($policy_type_id != 0) {
- // $builder->where('client_policy.policy_type_id', $policy_type_id);
- // }
-
- // if ($issuer != 0) {
- // $builder->where('policy_transaction.issuer', $issuer);
- // }
-
- // if($client_id == 0 && $insurer_id == 0 && $policy_type_id == 0 && $date_type == 0 && $issuer == 0){
-
- // $fromDate = date('Y-m-d', strtotime('-30 days'));
- // $toDate = date('Y-m-d 23:59:59');
-
- // $builder->where('policy_transaction.created_at >=', $fromDate)
- // ->where('policy_transaction.created_at <=', $toDate);
-
- // }
-
- // $builder->orderBy('policy_transaction.id', 'desc');
-
- // $result = $builder->get()->getResultArray();
-
- // // dd($this->db->getLastQuery());
-
- // return $result;
- // }
-
- public function getBDSReportList($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0, $client_branch_id = 0, $insurer_branch_id = 0, $client_policy_id = 0, $user_id = 0, $where = [])
- {
-
- $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.cop_amt as bp_amt,
- pt_co_share_details.exp_amt,
- pt_co_share_details.id as pt_id,
- sales_user.first_name as salse_person_name,
- service_user.first_name as service_person_name,
-
- ROUND((pt_co_share_details.cop_amt + pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt), 2) AS premium_wo_gst,
-
- ROUND((ROUND((pt_co_share_details.cop_amt + pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt), 2) * 18 / 100), 2) AS gst_amount,
-
- ROUND((ROUND((pt_co_share_details.cop_amt + pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt), 2) + ROUND((ROUND((pt_co_share_details.cop_amt + pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt), 2) * 18 / 100), 2)), 2) AS total_premium,
-
- ROUND((pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt), 2) AS tp_or_ter,
-
- DATEDIFF(policy_transaction.policy_end_date, CURDATE()) AS days,
-
- (pt_co_share_details.agreed_tp_per + pt_co_share_details.agreed_tep_per) AS agreed_tp_or_ter_per,
-
- pt_co_share_details.agreed_bp_per,
- ROUND(
- (
- SELECT
- (
- SUM(co_share_stmt_details.actual_bp_brokerage_amt) +
- SUM(co_share_stmt_details.actual_tp_brokerage_amt) +
- SUM(co_share_stmt_details.actual_tep_brokerage_amt) +
- SUM(co_share_stmt_details.reward)
-
- ) AS total_irda_amt
- FROM
- co_share_stmt_details
- JOIN insurer_statements ON co_share_stmt_details.statement_id = insurer_statements.id
- WHERE
- co_share_stmt_details.co_share_id = pt_co_share_details.id
- AND co_share_stmt_details.is_active = 1
- AND insurer_statements.is_active = 1
- $date_condition
- ),
- 2
- ) AS total_irda_amt,
- ROUND(
- (
- SELECT
- (
- SUM(co_share_stmt_details.reward)
-
- ) AS reward
- FROM
- co_share_stmt_details
- JOIN insurer_statements ON co_share_stmt_details.statement_id = insurer_statements.id
- WHERE
- co_share_stmt_details.co_share_id = pt_co_share_details.id
- AND co_share_stmt_details.is_active = 1
- AND insurer_statements.is_active = 1
- $date_condition
- ),
- 2
- ) AS reward,
-
- ROUND(
- (
- SELECT
- SUM(
- COALESCE(co_share_stmt_details.actual_bp_brokerage_amt, 0) +
- COALESCE(co_share_stmt_details.actual_tp_brokerage_amt, 0) +
- COALESCE(co_share_stmt_details.actual_tep_brokerage_amt, 0) +
- COALESCE(co_share_stmt_details.reward, 0)
- ) AS total_irda_amt
- FROM
- co_share_stmt_details
- JOIN pt_co_share_details AS pt_table ON co_share_stmt_details.co_share_id = pt_table.id
- JOIN insurer_statements ON co_share_stmt_details.statement_id = insurer_statements.id
- WHERE
- co_share_stmt_details.co_share_id = pt_co_share_details.id
- AND co_share_stmt_details.is_active = 1
- AND pt_table.is_active = 1
- AND insurer_statements.is_active = 1
- AND insurer_statements.invoice_status IS NOT NULL
- $date_condition
-
- ),
- 2
- ) AS billed_amt,
-
- ROUND(
- (
- (
- SELECT
- SUM(
- COALESCE(co_share_stmt_details.actual_bp_brokerage_amt, 0)
- + COALESCE(co_share_stmt_details.actual_tp_brokerage_amt, 0)
- + COALESCE(co_share_stmt_details.actual_tep_brokerage_amt, 0)
- + COALESCE(co_share_stmt_details.reward, 0)
- )
- FROM
- co_share_stmt_details
- JOIN insurer_statements ON co_share_stmt_details.statement_id = insurer_statements.id
- WHERE
- co_share_stmt_details.co_share_id = pt_co_share_details.id
- AND co_share_stmt_details.is_active = 1
- $date_condition
- )
- -
- (
- SELECT
- SUM(
- COALESCE(co_share_stmt_details.actual_bp_brokerage_amt, 0)
- + COALESCE(co_share_stmt_details.actual_tp_brokerage_amt, 0)
- + COALESCE(co_share_stmt_details.actual_tep_brokerage_amt, 0)
- + COALESCE(co_share_stmt_details.reward, 0)
- )
- FROM
- co_share_stmt_details
- JOIN pt_co_share_details AS pt_table ON co_share_stmt_details.co_share_id = pt_table.id
- JOIN insurer_statements ON co_share_stmt_details.statement_id = insurer_statements.id
- WHERE
- co_share_stmt_details.co_share_id = pt_co_share_details.id
- AND co_share_stmt_details.is_active = 1
- AND pt_table.is_active = 1
- AND insurer_statements.is_active = 1
- AND insurer_statements.invoice_status IS NULL
- $date_condition
- )
- ),
- 2
- ) AS unbilled_amt,
- created_user.first_name as user_name,
- CASE
- WHEN pt_co_share_details.co_share_type IN (0, 1)
- THEN policy_transaction.policy_no
- WHEN pt_co_share_details.co_share_type > 1
- THEN CASE
- WHEN pt_co_share_details.follower_policy_no IS NULL
- OR pt_co_share_details.follower_policy_no = ''
- THEN policy_transaction.policy_no
- ELSE pt_co_share_details.follower_policy_no
- END
- ELSE policy_transaction.policy_no
- END AS policy_no
- ")
- ->join('pt_co_share_details', 'policy_transaction.id = pt_co_share_details.pt_id', 'left')
- // ->join('insurer_statements', 'pt_co_share_details.statement_id = insurer_statements.id', 'left')
- ->join('clients', 'clients.id = policy_transaction.client_id')
- ->join('client_branch', 'policy_transaction.client_branch_id = client_branch.id', 'left')
- ->join('client_policy', 'policy_transaction.client_policy_id = client_policy.id', 'left')
- ->join('user_profiles', 'policy_transaction.created_by = user_profiles.id', 'left')
- ->join('vehicle', 'policy_transaction.vehicle_id = vehicle.id', 'left')
- ->join('policy_type', 'policy_transaction.policy_type_id = policy_type.id', 'left')
- ->join('insurers', 'pt_co_share_details.insurer_id = insurers.id', 'left')
- ->join('insurer_branch', 'pt_co_share_details.insurer_branch_id = insurer_branch.id', 'left')
- ->join('tpa', 'policy_transaction.tpa_id = tpa.id', 'left')
- ->join('tpa_branch', 'policy_transaction.tpa_branch_id = tpa_branch.id', 'left')
- ->join('user_profiles AS sales_user', 'policy_transaction.sales_generated_by = sales_user.id', 'left')
- ->join('user_profiles AS service_user', 'policy_transaction.serviced_by = service_user.id', 'left')
- ->join('user_profiles AS created_user', 'policy_transaction.created_by = created_user.id', 'left')
- ->where('policy_transaction.is_active', 1)
- ->where('pt_co_share_details.is_active', 1);
-
- if (
- (!in_array(get_role_id(), [1, 5])) &&
- !(
- in_array(MANAGEMENT_TEAM_ID, user_team()) ||
- in_array(FINANCE_TEAM_ID, user_team()) ||
- in_array(BUSINESS_TEAM_ID, user_team())
- )
- ) {
- if (get_role_id() == 4 && in_array(POS_TEAM_ID, user_team())) {
- $builder->where('policy_transaction.created_by', get_session_userid());
+ SELECT
+ (SUM(inv_payment_details.inv_amt) + SUM(inv_payment_details.tds)) AS realization_amount
+ FROM
+ inv_payment_details
+ WHERE
+ inv_payment_details.statement_id = insurer_statements.id
+ AND inv_payment_details.is_active = 1
+
+ ) AS realization_amount,
+
+ ROUND(
+ insurer_statements.invoice_amount -
+ (
+ SELECT
+ (SUM(inv_payment_details.inv_amt) + SUM(inv_payment_details.tds))
+ FROM
+ inv_payment_details
+ WHERE
+ inv_payment_details.statement_id = insurer_statements.id
+ AND inv_payment_details.is_active = 1
+ ),
+ 2) AS outstanding_amount,
+
+ (
+ SELECT
+ GROUP_CONCAT(inv_payment_details.utr_no SEPARATOR ', ') AS utr_numbers
+ FROM
+ inv_payment_details
+ WHERE
+ inv_payment_details.statement_id = insurer_statements.id
+ AND inv_payment_details.is_active = 1
+ ) AS utr_numbers,
+
+ (
+ SELECT
+ GROUP_CONCAT(inv_payment_details.received_date SEPARATOR ', ') AS payment_dates
+ FROM
+ inv_payment_details
+ WHERE
+ inv_payment_details.statement_id = insurer_statements.id
+ AND inv_payment_details.is_active = 1
+ ) AS payment_dates
+
+ ")
+ ->join('pt_co_share_details', 'policy_transaction.id = pt_co_share_details.pt_id', 'left')
+ ->join('insurer_statements', 'pt_co_share_details.statement_id = insurer_statements.id', 'left')
+ ->join('clients', 'clients.id = policy_transaction.client_id')
+ ->join('client_branch', 'policy_transaction.client_branch_id = client_branch.id', 'left')
+ ->join('client_policy', 'policy_transaction.client_policy_id = client_policy.id', 'left')
+ ->join('user_profiles', 'policy_transaction.created_by = user_profiles.id', 'left')
+ ->join('vehicle', 'policy_transaction.vehicle_id = vehicle.id', 'left')
+ ->join('policy_type', 'policy_transaction.policy_type_id = policy_type.id', 'left')
+ ->join('insurers', 'policy_transaction.insurer_id = insurers.id', 'left')
+ ->join('insurer_branch', 'policy_transaction.insurer_branch_id = insurer_branch.id', 'left')
+ ->join('tpa', 'policy_transaction.tpa_id = tpa.id', 'left')
+ ->join('tpa_branch', 'policy_transaction.tpa_branch_id = tpa_branch.id', 'left')
+ ->join('user_profiles AS sales_user', 'policy_transaction.sales_generated_by = sales_user.id', 'left')
+ ->join('user_profiles AS service_user', 'policy_transaction.serviced_by = service_user.id', 'left')
+ ->where('policy_transaction.is_active', 1);
+
+ // Check if the start date and end date are provided
+ if ($start_date != 0 && $end_date != 0 && $date_type != 0) {
+
+ $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 (!empty($where)) {
- log_message('info', 'Where condition: ' . json_encode($where));
- $builder->where($where);
- }
- // Check if the start date and end date are provided
- if ($start_date != 0 && $end_date != 0 && $date_type != 0 && $date_type != 'statement_month') {
- $startDate = date('Y-m-d 00:00:00', strtotime($start_date));
- $endDate = date('Y-m-d 23:59:59', strtotime($end_date));
+ if ($client_id != 0) {
+ $builder->where('policy_transaction.client_id', $client_id);
+ }
- $builder->where('policy_transaction.' . $date_type . '>=', $startDate)
- ->where('policy_transaction.' . $date_type . '<=', $endDate);
- }
+ if ($insurer_id != 0) {
+ $builder->where('policy_transaction.insurer_id', $insurer_id);
+ }
- // if($date_type == 'statement_month' && $start_date != 0 && $end_date != 0){
+ if ($policy_type_id != 0) {
+ $builder->where('client_policy.policy_type_id', $policy_type_id);
+ }
- // $startDate = date('Y-m-d 00:00:00', strtotime($start_date));
- // $endDate = date('Y-m-d 23:59:59', strtotime($end_date));
- // $builder->where('policy_transaction.month >=', $startDate)
- // ->where('policy_transaction.month <=', $endDate);
- // }
+ if ($issuer != 0) {
+ $builder->where('policy_transaction.issuer', $issuer);
+ }
- // Conditionally join insurer_statements if $date_type == 'statement_month'
- if ($date_type == 'statement_month' && $start_date != 0 && $end_date != 0) {
- $startDate = date('Y-m-d', strtotime($start_date));
- $endDate = date('Y-m-d', strtotime($end_date));
+ if ($client_id == 0 && $insurer_id == 0 && $policy_type_id == 0 && $date_type == 0 && $issuer == 0) {
- $builder->join('co_share_stmt_details', 'pt_co_share_details.id = co_share_stmt_details.co_share_id', 'left')
- ->join('insurer_statements', 'co_share_stmt_details.statement_id = insurer_statements.id', 'left')
- ->where('insurer_statements.is_active', 1)
- ->where('insurer_statements.month >=', $startDate)
- ->where('insurer_statements.month <=', $endDate)
- ->groupBy('co_share_stmt_details.co_share_id');
- }
+ $fromDate = date('Y-m-d', strtotime('-90 days'));
+ $toDate = date('Y-m-d 23:59:59');
- if ($client_id != 0) {
- $builder->where('policy_transaction.client_id', $client_id);
- }
-
- if ($insurer_id != 0) {
- $builder->where('policy_transaction.insurer_id', $insurer_id);
- }
-
- if ($client_branch_id != 0) {
- $builder->where('policy_transaction.client_branch_id', $client_branch_id);
- }
-
- if ($insurer_branch_id != 0) {
- $builder->where('policy_transaction.insurer_branch_id', $insurer_branch_id);
- }
-
- if ($client_policy_id != 0) {
- $builder->where('policy_transaction.client_policy_id', $client_policy_id);
- }
-
- if ($user_id != 0) {
- $builder->where('policy_transaction.created_by', $user_id);
- }
-
-
-
- if ($policy_type_id != 0) {
- $builder->where('client_policy.policy_type_id', $policy_type_id);
- }
-
- if ($issuer != 0) {
- $builder->where('policy_transaction.issuer', $issuer);
- }
-
- if ($client_id == 0 && $insurer_id == 0 && $policy_type_id == 0 && $date_type == 0 && $issuer == 0) {
-
- $fromDate = date('Y-m-d', strtotime('-60 days'));
- $toDate = date('Y-m-d 23:59:59');
-
- if (empty($where)) {
$builder->where('policy_transaction.created_at >=', $fromDate)
->where('policy_transaction.created_at <=', $toDate);
}
+
+ $builder->orderBy('policy_transaction.id', 'desc');
+
+ return $builder->get()->getResultArray();
}
- $builder->orderBy('policy_transaction.id', 'desc');
+ // BDS Report NEW Functin for QUERY
+ // public function getBDSReportList($client_id, $policy_id, $branch_id, $issuer)
- $result = $builder->get()->getResultArray();
+ // 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)
+ // {
- // dd($this->db->getLastQuery());
+ // $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 ."'
+ // ";
+ // }
- return $result;
- }
+ // $builder = $this->db->table('policy_transaction')
+ // ->select("
+ // policy_transaction.*,
+ // DATE_FORMAT(policy_transaction.policy_issue_date, '%d %b %Y') AS policy_issue_date,
+ // DATE_FORMAT(
+ // IF(policy_transaction.month IS NULL,
+ // policy_transaction.policy_issue_date,
+ // policy_transaction.month),
+ // '%b %Y') AS policy_issue_month,
+ // CASE
+ // WHEN clients.client_type = 1 THEN 'Group'
+ // WHEN clients.client_type = 2 THEN 'Retail'
+ // ELSE '-'
+ // END AS client_type,
+ // CASE
+ // WHEN policy_transaction.revenue_type = 'NA' THEN 'Fresh'
+ // ELSE 'Renewal'
+ // END AS revenue_type,
+ // CASE
+ // WHEN policy_transaction.action_type = 'inception' THEN 'Policy'
+ // ELSE 'Endorsement'
+ // END AS action_type,
+ // clients.client_name AS client_name,
+ // clients.short_name AS client_short_name,
+ // client_branch.branch_name AS client_branch_name,
+ // client_branch.address1 AS client_address,
+ // policy_type.policy_type,
+ // policy_type.bap,
+ // insurers.name AS insurer_name,
+ // insurers.short_name AS insurer_short_name,
+ // insurer_branch.branch_name AS insurer_branch_name,
+ // insurer_branch.branch_code AS insurer_branch_code,
+ // user_profiles.first_name as user_name,
+ // vehicle.vehicle_no,
+ // tpa.name as tpa_name,
+ // pt_co_share_details.remark as remarks,
+ // pt_co_share_details.bp_amt,
+ // pt_co_share_details.exp_amt,
+ // pt_co_share_details.id as pt_id,
+ // sales_user.first_name as salse_person_name,
+ // service_user.first_name as service_person_name,
- // public function getInceptionTranctionListData($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0, $status = 0)
- // {
- // // dd($start_date, $end_date, $client_id, $insurer_id, $policy_type_id, $date_type, $issuer, $status);
- // $builder = $this->db->table('policy_transaction')
- // ->select('
- // policy_transaction.*,
- // clients.short_name AS client_short_name,
- // clients.client_code,
- // clients.client_type,
- // clients.client_name,
- // client_branch.branch_name AS client_branch_name,
- // insurers.name AS insurer_name,
- // insurers.short_name AS insurer_short_name,
- // policy_type.policy_type,
- // pt_co_share_details.agreed_amt AS amount,
- // pt_co_share_details.bp_amt AS bp,
- // pt_co_share_details.tp_amt AS tp
- // ')
- // ->join('pt_co_share_details', 'policy_transaction.id = pt_co_share_details.pt_id', 'left')
- // ->join('clients', 'clients.id = policy_transaction.client_id', 'left')
- // ->join('client_branch', 'policy_transaction.client_branch_id = client_branch.id', 'left')
- // ->join('insurers', 'pt_co_share_details.insurer_id = insurers.id', 'left')
- // ->join('client_policy', 'policy_transaction.client_policy_id = client_policy.id', 'left')
- // ->join('policy_type', 'policy_transaction.policy_type_id = policy_type.id', 'left')
- // ->where('policy_transaction.is_active', 1)
- // ->where('policy_transaction.action_type', 'inception');
+ // ROUND((pt_co_share_details.bp_amt + pt_co_share_details.tp_amt + pt_co_share_details.tep_amt), 2) AS premium_wo_gst,
- // if ($start_date != 0 && $end_date != 0 && $date_type != 0) {
+ // 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,
- // $startDate = date('Y-m-d 00:00:00', strtotime($start_date));
- // $endDate = date('Y-m-d 23:59:59', strtotime($end_date));
+ // 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,
- // $builder->where('policy_transaction.'.$date_type.'>=', $startDate)
- // ->where('policy_transaction.'.$date_type.'<=', $endDate);
- // }else{
+ // ROUND((pt_co_share_details.tp_amt + pt_co_share_details.tep_amt), 2) AS tp_or_ter,
- // // $fromDate = date('Y-m-d', strtotime('-30 days'));
- // // $toDate = date('Y-m-d 23:59:59');
+ // DATEDIFF(policy_transaction.policy_end_date, CURDATE()) AS days,
- // // $builder->where('policy_transaction.created_at >=', $fromDate)
- // // ->where('policy_transaction.created_at <=', $toDate);
- // }
+ // (pt_co_share_details.agreed_tp_per + pt_co_share_details.agreed_tep_per) AS agreed_tp_or_ter_per,
- // if ($client_id != 0) {
- // $builder->where('policy_transaction.client_id', $client_id);
- // }
+ // 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)
- // if ($insurer_id != 0) {
- // $builder->where('policy_transaction.insurer_id', $insurer_id);
- // }
+ // ) AS total_irda_amt
+ // FROM
+ // co_share_stmt_details
+ // JOIN insurer_statements ON co_share_stmt_details.statement_id = insurer_statements.id
+ // WHERE
+ // co_share_stmt_details.co_share_id = pt_co_share_details.id
+ // AND co_share_stmt_details.is_active = 1
+ // AND insurer_statements.is_active = 1
+ // $date_condition
+ // ),
+ // 2
+ // ) AS total_irda_amt,
+ // ROUND(
+ // (
+ // SELECT
+ // (
+ // SUM(co_share_stmt_details.reward)
- // if ($policy_type_id != 0) {
- // $builder->where('client_policy.policy_type_id', $policy_type_id);
- // }
+ // ) AS reward
+ // FROM
+ // co_share_stmt_details
+ // JOIN insurer_statements ON co_share_stmt_details.statement_id = insurer_statements.id
+ // WHERE
+ // co_share_stmt_details.co_share_id = pt_co_share_details.id
+ // AND co_share_stmt_details.is_active = 1
+ // AND insurer_statements.is_active = 1
+ // $date_condition
+ // ),
+ // 2
+ // ) AS reward,
- // if ($issuer != 0) {
- // $builder->where('policy_transaction.issuer', $issuer);
- // }
- // if ($status != 0) {
- // $builder->where('policy_transaction.status', $status);
- // }
+ // ROUND(
+ // (
+ // SELECT
+ // SUM(
+ // COALESCE(co_share_stmt_details.actual_bp_brokerage_amt, 0) +
+ // COALESCE(co_share_stmt_details.actual_tp_brokerage_amt, 0) +
+ // COALESCE(co_share_stmt_details.actual_tep_brokerage_amt, 0) +
+ // COALESCE(co_share_stmt_details.reward, 0)
+ // ) AS total_irda_amt
+ // FROM
+ // co_share_stmt_details
+ // JOIN pt_co_share_details AS pt_table ON co_share_stmt_details.co_share_id = pt_table.id
+ // JOIN insurer_statements ON co_share_stmt_details.statement_id = insurer_statements.id
+ // WHERE
+ // co_share_stmt_details.co_share_id = pt_co_share_details.id
+ // AND co_share_stmt_details.is_active = 1
+ // AND pt_table.is_active = 1
+ // AND insurer_statements.is_active = 1
+ // AND insurer_statements.invoice_status IS NOT NULL
+ // $date_condition
- // if($client_id == 0 && $insurer_id == 0 && $policy_type_id == 0 && $date_type == 0 && $issuer == 0){
+ // ),
+ // 2
+ // ) AS billed_amt,
- // $fromDate = date('Y-m-d', strtotime('-30 days'));
- // $toDate = date('Y-m-d 23:59:59');
+ // ROUND(
+ // (
+ // (
+ // SELECT
+ // SUM(
+ // COALESCE(co_share_stmt_details.actual_bp_brokerage_amt, 0)
+ // + COALESCE(co_share_stmt_details.actual_tp_brokerage_amt, 0)
+ // + COALESCE(co_share_stmt_details.actual_tep_brokerage_amt, 0)
+ // + COALESCE(co_share_stmt_details.reward, 0)
+ // )
+ // FROM
+ // co_share_stmt_details
+ // JOIN insurer_statements ON co_share_stmt_details.statement_id = insurer_statements.id
+ // WHERE
+ // co_share_stmt_details.co_share_id = pt_co_share_details.id
+ // AND co_share_stmt_details.is_active = 1
+ // $date_condition
+ // )
+ // -
+ // (
+ // SELECT
+ // SUM(
+ // COALESCE(co_share_stmt_details.actual_bp_brokerage_amt, 0)
+ // + COALESCE(co_share_stmt_details.actual_tp_brokerage_amt, 0)
+ // + COALESCE(co_share_stmt_details.actual_tep_brokerage_amt, 0)
+ // + COALESCE(co_share_stmt_details.reward, 0)
+ // )
+ // FROM
+ // co_share_stmt_details
+ // JOIN pt_co_share_details AS pt_table ON co_share_stmt_details.co_share_id = pt_table.id
+ // JOIN insurer_statements ON co_share_stmt_details.statement_id = insurer_statements.id
+ // WHERE
+ // co_share_stmt_details.co_share_id = pt_co_share_details.id
+ // AND co_share_stmt_details.is_active = 1
+ // AND pt_table.is_active = 1
+ // AND insurer_statements.is_active = 1
+ // AND insurer_statements.invoice_status IS NULL
+ // $date_condition
+ // )
+ // ),
+ // 2
+ // ) AS unbilled_amt
- // $builder->where('policy_transaction.created_at >=', $fromDate)
- // ->where('policy_transaction.created_at <=', $toDate);
+ // ")
+ // ->join('pt_co_share_details', 'policy_transaction.id = pt_co_share_details.pt_id', 'left')
+ // // ->join('insurer_statements', 'pt_co_share_details.statement_id = insurer_statements.id', 'left')
+ // ->join('clients', 'clients.id = policy_transaction.client_id')
+ // ->join('client_branch', 'policy_transaction.client_branch_id = client_branch.id', 'left')
+ // ->join('client_policy', 'policy_transaction.client_policy_id = client_policy.id', 'left')
+ // ->join('user_profiles', 'policy_transaction.created_by = user_profiles.id', 'left')
+ // ->join('vehicle', 'policy_transaction.vehicle_id = vehicle.id', 'left')
+ // ->join('policy_type', 'policy_transaction.policy_type_id = policy_type.id', 'left')
+ // ->join('insurers', 'pt_co_share_details.insurer_id = insurers.id', 'left')
+ // ->join('insurer_branch', 'pt_co_share_details.insurer_branch_id = insurer_branch.id', 'left')
+ // ->join('tpa', 'policy_transaction.tpa_id = tpa.id', 'left')
+ // ->join('tpa_branch', 'policy_transaction.tpa_branch_id = tpa_branch.id', 'left')
+ // ->join('user_profiles AS sales_user', 'policy_transaction.sales_generated_by = sales_user.id', 'left')
+ // ->join('user_profiles AS service_user', 'policy_transaction.serviced_by = service_user.id', 'left')
+ // ->where('policy_transaction.is_active', 1)
+ // ->where('pt_co_share_details.is_active', 1);
- // }
+ // // Check if the start date and end date are provided
+ // if ($start_date != 0 && $end_date != 0 && $date_type != 0 && $date_type != 'statement_month') {
- // $builder->orderBy('policy_transaction.id', 'desc')->limit(10);
+ // $startDate = date('Y-m-d 00:00:00', strtotime($start_date));
+ // $endDate = date('Y-m-d 23:59:59', strtotime($end_date));
- // $result = $builder->get()->getResultArray();
+ // $builder->where('policy_transaction.'.$date_type.'>=', $startDate)
+ // ->where('policy_transaction.'.$date_type.'<=', $endDate);
- // // dd($this->db->getLastQuery());
+ // }
- // return $result;
- // }
+ // // if($date_type == 'statement_month' && $start_date != 0 && $end_date != 0){
- public function getInceptionTranctionListData($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0, $status = 0, $where = null)
- {
- $builder = $this->db->table('policy_transaction')
- ->select("
- policy_transaction.*,
- clients.short_name AS client_short_name,
- clients.client_code,
- clients.client_type,
- clients.client_name,
- client_branch.branch_name AS client_branch_name,
- insurers.name AS insurer_name,
- insurers.short_name AS insurer_short_name,
- policy_type.policy_type,
- pt_co_share_details.agreed_amt AS amount,
- pt_co_share_details.bp_amt AS bp,
- pt_co_share_details.tp_amt AS tp,
- clients.pan,
- DATE_FORMAT(policy_transaction.created_at, '%d %b %Y %h:%i %p') AS created_at,
- user_profiles.first_name as user_name,
- CASE
- WHEN pt_co_share_details.co_share_type IN (0, 1)
- THEN policy_transaction.policy_no
- WHEN pt_co_share_details.co_share_type > 1
- THEN CASE
- WHEN pt_co_share_details.follower_policy_no IS NULL
- OR pt_co_share_details.follower_policy_no = ''
- THEN policy_transaction.policy_no
- ELSE pt_co_share_details.follower_policy_no
- END
- ELSE policy_transaction.policy_no
- END AS policy_no
- ")
- ->join('pt_co_share_details', 'policy_transaction.id = pt_co_share_details.pt_id', 'left')
- ->join('clients', 'clients.id = policy_transaction.client_id', 'left')
- ->join('client_branch', 'policy_transaction.client_branch_id = client_branch.id', 'left')
- ->join('insurers', 'pt_co_share_details.insurer_id = insurers.id', 'left')
- ->join('client_policy', 'policy_transaction.client_policy_id = client_policy.id', 'left')
- ->join('policy_type', 'policy_transaction.policy_type_id = policy_type.id', 'left')
- ->join('user_profiles', 'policy_transaction.created_by = user_profiles.id', 'left')
- ->where('policy_transaction.is_active', 1)
- ->where('policy_transaction.action_type', 'inception');
+ // // $startDate = date('Y-m-d 00:00:00', strtotime($start_date));
+ // // $endDate = date('Y-m-d 23:59:59', strtotime($end_date));
+ // // $builder->where('policy_transaction.month >=', $startDate)
+ // // ->where('policy_transaction.month <=', $endDate);
+ // // }
- if (
- (!in_array(get_role_id(), [1, 5])) &&
- !(
- in_array(MANAGEMENT_TEAM_ID, user_team()) ||
- in_array(FINANCE_TEAM_ID, user_team()) ||
- in_array(BUSINESS_TEAM_ID, user_team())
- )
- ) {
- if (get_role_id() == 4 && in_array(POS_TEAM_ID, user_team())) {
- $builder->where('policy_transaction.created_by', get_session_userid());
+ // // Conditionally join insurer_statements if $date_type == 'statement_month'
+ // if ($date_type == 'statement_month' && $start_date != 0 && $end_date != 0) {
+ // $startDate = date('Y-m-d', strtotime($start_date));
+ // $endDate = date('Y-m-d', strtotime($end_date));
+
+ // $builder->join('co_share_stmt_details', 'pt_co_share_details.id = co_share_stmt_details.co_share_id', 'left')
+ // ->join('insurer_statements', 'co_share_stmt_details.statement_id = insurer_statements.id','left')
+ // ->where('insurer_statements.is_active', 1)
+ // ->where('insurer_statements.month >=', $startDate)
+ // ->where('insurer_statements.month <=', $endDate)
+ // ->groupBy('co_share_stmt_details.co_share_id');
+ // }
+
+ // if ($client_id != 0) {
+ // $builder->where('policy_transaction.client_id', $client_id);
+ // }
+
+ // if ($insurer_id != 0) {
+ // $builder->where('policy_transaction.insurer_id', $insurer_id);
+ // }
+
+ // if ($client_branch_id != 0) {
+ // $builder->where('policy_transaction.client_branch_id', $client_branch_id);
+ // }
+
+ // if ($insurer_branch_id != 0) {
+ // $builder->where('policy_transaction.insurer_branch_id', $insurer_branch_id);
+ // }
+
+ // if ($client_policy_id != 0) {
+ // $builder->where('policy_transaction.client_policy_id', $client_policy_id);
+ // }
+
+
+
+ // if ($policy_type_id != 0) {
+ // $builder->where('client_policy.policy_type_id', $policy_type_id);
+ // }
+
+ // if ($issuer != 0) {
+ // $builder->where('policy_transaction.issuer', $issuer);
+ // }
+
+ // if($client_id == 0 && $insurer_id == 0 && $policy_type_id == 0 && $date_type == 0 && $issuer == 0){
+
+ // $fromDate = date('Y-m-d', strtotime('-30 days'));
+ // $toDate = date('Y-m-d 23:59:59');
+
+ // $builder->where('policy_transaction.created_at >=', $fromDate)
+ // ->where('policy_transaction.created_at <=', $toDate);
+
+ // }
+
+ // $builder->orderBy('policy_transaction.id', 'desc');
+
+ // $result = $builder->get()->getResultArray();
+
+ // // dd($this->db->getLastQuery());
+
+ // return $result;
+ // }
+
+ public function getBDSReportList($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0, $client_branch_id = 0, $insurer_branch_id = 0, $client_policy_id = 0, $user_id = 0, $where = [])
+ {
+
+ $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 . "'
+ ";
}
- }
- // Optimize Date Filtering
- if (!empty($start_date) && !empty($end_date) && !empty($date_type)) {
- $builder->where("policy_transaction.$date_type >=", date('Y-m-d 00:00:00', strtotime($start_date)))
- ->where("policy_transaction.$date_type <=", date('Y-m-d 23:59:59', strtotime($end_date)));
- }
-
- // Apply Filters Only When Necessary
- if (!empty($client_id)) {
- $builder->where('policy_transaction.client_id', $client_id);
- }
- if (!empty($insurer_id)) {
- $builder->where('policy_transaction.insurer_id', $insurer_id);
- }
- if (!empty($policy_type_id)) {
- $builder->where('client_policy.policy_type_id', $policy_type_id);
- }
- if (!empty($issuer)) {
- $builder->where('policy_transaction.issuer', $issuer);
- }
- if (!empty($status)) {
- $builder->where('policy_transaction.status', $status);
- }
-
- // Default to Last 30 Days if No Filters Are Applied
- if (empty($client_id) && empty($insurer_id) && empty($policy_type_id) && empty($date_type) && empty($issuer) && empty($where)) {
- $fromDate = date('Y-m-d', strtotime('-60 days'));
- $toDate = date('Y-m-d 23:59:59');
-
- $builder->where('policy_transaction.created_at >=', $fromDate)
- ->where('policy_transaction.created_at <=', $toDate);
- }
-
- if (!empty($where)) {
- $builder->whereIn('policy_transaction.id', $where);
- }
-
- // Optimize Query Execution
- $builder->orderBy('policy_transaction.id', 'desc');
- $data = $builder->get()->getResultArray();
- return $data;
- }
-
-
- public function getEndorsementTranctionListData($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0, $status = 0)
- {
- // dd($start_date, $end_date, $client_id, $insurer_id, $policy_type_id, $date_type, $issuer, $status);
- $builder = $this->db->table('policy_transaction')
- ->select("
- policy_transaction.*,
- clients.short_name as client_short_name,
- clients.client_code,
- client_branch.branch_name as client_branch_name,
+ $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,
- policy_type.policy_type ,
+ insurer_branch.branch_name AS insurer_branch_name,
+ insurer_branch.branch_code AS insurer_branch_code,
+ user_profiles.first_name as user_name,
+ vehicle.vehicle_no,
+ tpa.name as tpa_name,
+ pt_co_share_details.remark as remarks,
+ pt_co_share_details.cop_amt as bp_amt,
+ pt_co_share_details.exp_amt,
+ pt_co_share_details.id as pt_id,
+ sales_user.first_name as salse_person_name,
+ service_user.first_name as service_person_name,
+
+ ROUND((pt_co_share_details.cop_amt + pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt), 2) AS premium_wo_gst,
+
+ ROUND((ROUND((pt_co_share_details.cop_amt + pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt), 2) * 18 / 100), 2) AS gst_amount,
+
+ ROUND((ROUND((pt_co_share_details.cop_amt + pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt), 2) + ROUND((ROUND((pt_co_share_details.cop_amt + pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt), 2) * 18 / 100), 2)), 2) AS total_premium,
+
+ ROUND((pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt), 2) AS tp_or_ter,
+
+ DATEDIFF(policy_transaction.policy_end_date, CURDATE()) AS days,
+
+ (pt_co_share_details.agreed_tp_per + pt_co_share_details.agreed_tep_per) AS agreed_tp_or_ter_per,
+
+ pt_co_share_details.agreed_bp_per,
+ ROUND(
+ (
+ SELECT
+ (
+ SUM(co_share_stmt_details.actual_bp_brokerage_amt) +
+ SUM(co_share_stmt_details.actual_tp_brokerage_amt) +
+ SUM(co_share_stmt_details.actual_tep_brokerage_amt) +
+ SUM(co_share_stmt_details.reward)
+
+ ) AS total_irda_amt
+ FROM
+ co_share_stmt_details
+ JOIN insurer_statements ON co_share_stmt_details.statement_id = insurer_statements.id
+ WHERE
+ co_share_stmt_details.co_share_id = pt_co_share_details.id
+ AND co_share_stmt_details.is_active = 1
+ AND insurer_statements.is_active = 1
+ $date_condition
+ ),
+ 2
+ ) AS total_irda_amt,
+ ROUND(
+ (
+ SELECT
+ (
+ SUM(co_share_stmt_details.reward)
+
+ ) AS reward
+ FROM
+ co_share_stmt_details
+ JOIN insurer_statements ON co_share_stmt_details.statement_id = insurer_statements.id
+ WHERE
+ co_share_stmt_details.co_share_id = pt_co_share_details.id
+ AND co_share_stmt_details.is_active = 1
+ AND insurer_statements.is_active = 1
+ $date_condition
+ ),
+ 2
+ ) AS reward,
+
+ ROUND(
+ (
+ SELECT
+ SUM(
+ COALESCE(co_share_stmt_details.actual_bp_brokerage_amt, 0) +
+ COALESCE(co_share_stmt_details.actual_tp_brokerage_amt, 0) +
+ COALESCE(co_share_stmt_details.actual_tep_brokerage_amt, 0) +
+ COALESCE(co_share_stmt_details.reward, 0)
+ ) AS total_irda_amt
+ FROM
+ co_share_stmt_details
+ JOIN pt_co_share_details AS pt_table ON co_share_stmt_details.co_share_id = pt_table.id
+ JOIN insurer_statements ON co_share_stmt_details.statement_id = insurer_statements.id
+ WHERE
+ co_share_stmt_details.co_share_id = pt_co_share_details.id
+ AND co_share_stmt_details.is_active = 1
+ AND pt_table.is_active = 1
+ AND insurer_statements.is_active = 1
+ AND insurer_statements.invoice_status IS NOT NULL
+ $date_condition
+
+ ),
+ 2
+ ) AS billed_amt,
+
+ ROUND(
+ (
+ (
+ SELECT
+ SUM(
+ COALESCE(co_share_stmt_details.actual_bp_brokerage_amt, 0)
+ + COALESCE(co_share_stmt_details.actual_tp_brokerage_amt, 0)
+ + COALESCE(co_share_stmt_details.actual_tep_brokerage_amt, 0)
+ + COALESCE(co_share_stmt_details.reward, 0)
+ )
+ FROM
+ co_share_stmt_details
+ JOIN insurer_statements ON co_share_stmt_details.statement_id = insurer_statements.id
+ WHERE
+ co_share_stmt_details.co_share_id = pt_co_share_details.id
+ AND co_share_stmt_details.is_active = 1
+ $date_condition
+ )
+ -
+ (
+ SELECT
+ SUM(
+ COALESCE(co_share_stmt_details.actual_bp_brokerage_amt, 0)
+ + COALESCE(co_share_stmt_details.actual_tp_brokerage_amt, 0)
+ + COALESCE(co_share_stmt_details.actual_tep_brokerage_amt, 0)
+ + COALESCE(co_share_stmt_details.reward, 0)
+ )
+ FROM
+ co_share_stmt_details
+ JOIN pt_co_share_details AS pt_table ON co_share_stmt_details.co_share_id = pt_table.id
+ JOIN insurer_statements ON co_share_stmt_details.statement_id = insurer_statements.id
+ WHERE
+ co_share_stmt_details.co_share_id = pt_co_share_details.id
+ AND co_share_stmt_details.is_active = 1
+ AND pt_table.is_active = 1
+ AND insurer_statements.is_active = 1
+ AND insurer_statements.invoice_status IS NULL
+ $date_condition
+ )
+ ),
+ 2
+ ) AS unbilled_amt,
+ created_user.first_name as user_name,
CASE
WHEN pt_co_share_details.co_share_type IN (0, 1)
THEN policy_transaction.policy_no
@@ -1103,707 +780,1523 @@ class PolicyTransactionModel extends Model
ELSE policy_transaction.policy_no
END AS policy_no
")
- ->join('pt_co_share_details', 'policy_transaction.id = pt_co_share_details.pt_id', 'left')
- ->join('clients', 'policy_transaction.client_id = clients.id', 'left')
- ->join('client_branch', 'policy_transaction.client_branch_id = client_branch.id', 'left')
- ->join('insurers', 'pt_co_share_details.insurer_id = insurers.id', 'left')
- ->join('client_policy', 'policy_transaction.client_policy_id = client_policy.id', 'left')
- ->join('policy_type', 'client_policy.policy_type_id = policy_type.id', 'left')
- ->where('policy_transaction.is_active', 1)
- ->where('policy_transaction.action_type !=', 'inception');
+ ->join('pt_co_share_details', 'policy_transaction.id = pt_co_share_details.pt_id', 'left')
+ // ->join('insurer_statements', 'pt_co_share_details.statement_id = insurer_statements.id', 'left')
+ ->join('clients', 'clients.id = policy_transaction.client_id')
+ ->join('client_branch', 'policy_transaction.client_branch_id = client_branch.id', 'left')
+ ->join('client_policy', 'policy_transaction.client_policy_id = client_policy.id', 'left')
+ ->join('user_profiles', 'policy_transaction.created_by = user_profiles.id', 'left')
+ ->join('vehicle', 'policy_transaction.vehicle_id = vehicle.id', 'left')
+ ->join('policy_type', 'policy_transaction.policy_type_id = policy_type.id', 'left')
+ ->join('insurers', 'pt_co_share_details.insurer_id = insurers.id', 'left')
+ ->join('insurer_branch', 'pt_co_share_details.insurer_branch_id = insurer_branch.id', 'left')
+ ->join('tpa', 'policy_transaction.tpa_id = tpa.id', 'left')
+ ->join('tpa_branch', 'policy_transaction.tpa_branch_id = tpa_branch.id', 'left')
+ ->join('user_profiles AS sales_user', 'policy_transaction.sales_generated_by = sales_user.id', 'left')
+ ->join('user_profiles AS service_user', 'policy_transaction.serviced_by = service_user.id', 'left')
+ ->join('user_profiles AS created_user', 'policy_transaction.created_by = created_user.id', 'left')
+ ->where('policy_transaction.is_active', 1)
+ ->where('pt_co_share_details.is_active', 1);
- if (
- (!in_array(get_role_id(), [1, 5])) &&
- !(
- in_array(MANAGEMENT_TEAM_ID, user_team()) ||
- in_array(FINANCE_TEAM_ID, user_team()) ||
- in_array(BUSINESS_TEAM_ID, user_team())
- )
- ) {
- if (get_role_id() == 4 && in_array(POS_TEAM_ID, user_team())) {
- $builder->where('policy_transaction.created_by', get_session_userid());
+ if (
+ (!in_array(get_role_id(), [1, 5])) &&
+ !(
+ in_array(MANAGEMENT_TEAM_ID, user_team()) ||
+ in_array(FINANCE_TEAM_ID, user_team()) ||
+ in_array(BUSINESS_TEAM_ID, user_team())
+ )
+ ) {
+ if (get_role_id() == 4 && in_array(POS_TEAM_ID, user_team())) {
+ $builder->where('policy_transaction.created_by', get_session_userid());
+ }
}
+ if (!empty($where)) {
+ log_message('info', 'Where condition: ' . json_encode($where));
+ $builder->where($where);
+ }
+ // Check if the start date and end date are provided
+ if ($start_date != 0 && $end_date != 0 && $date_type != 0 && $date_type != 'statement_month') {
+
+ $startDate = date('Y-m-d 00:00:00', strtotime($start_date));
+ $endDate = date('Y-m-d 23:59:59', strtotime($end_date));
+
+ $builder->where('policy_transaction.' . $date_type . '>=', $startDate)
+ ->where('policy_transaction.' . $date_type . '<=', $endDate);
+ }
+
+ // if($date_type == 'statement_month' && $start_date != 0 && $end_date != 0){
+
+ // $startDate = date('Y-m-d 00:00:00', strtotime($start_date));
+ // $endDate = date('Y-m-d 23:59:59', strtotime($end_date));
+ // $builder->where('policy_transaction.month >=', $startDate)
+ // ->where('policy_transaction.month <=', $endDate);
+ // }
+
+ // Conditionally join insurer_statements if $date_type == 'statement_month'
+ if ($date_type == 'statement_month' && $start_date != 0 && $end_date != 0) {
+ $startDate = date('Y-m-d', strtotime($start_date));
+ $endDate = date('Y-m-d', strtotime($end_date));
+
+ $builder->join('co_share_stmt_details', 'pt_co_share_details.id = co_share_stmt_details.co_share_id', 'left')
+ ->join('insurer_statements', 'co_share_stmt_details.statement_id = insurer_statements.id', 'left')
+ ->where('insurer_statements.is_active', 1)
+ ->where('insurer_statements.month >=', $startDate)
+ ->where('insurer_statements.month <=', $endDate)
+ ->groupBy('co_share_stmt_details.co_share_id');
+ }
+
+ if ($client_id != 0) {
+ $builder->where('policy_transaction.client_id', $client_id);
+ }
+
+ if ($insurer_id != 0) {
+ $builder->where('policy_transaction.insurer_id', $insurer_id);
+ }
+
+ if ($client_branch_id != 0) {
+ $builder->where('policy_transaction.client_branch_id', $client_branch_id);
+ }
+
+ if ($insurer_branch_id != 0) {
+ $builder->where('policy_transaction.insurer_branch_id', $insurer_branch_id);
+ }
+
+ if ($client_policy_id != 0) {
+ $builder->where('policy_transaction.client_policy_id', $client_policy_id);
+ }
+
+ if ($user_id != 0) {
+ $builder->where('policy_transaction.created_by', $user_id);
+ }
+
+
+
+ if ($policy_type_id != 0) {
+ $builder->where('client_policy.policy_type_id', $policy_type_id);
+ }
+
+ if ($issuer != 0) {
+ $builder->where('policy_transaction.issuer', $issuer);
+ }
+
+ if ($client_id == 0 && $insurer_id == 0 && $policy_type_id == 0 && $date_type == 0 && $issuer == 0) {
+
+ $fromDate = date('Y-m-d', strtotime('-90 days'));
+ $toDate = date('Y-m-d 23:59:59');
+
+ if (empty($where)) {
+ $builder->where('policy_transaction.created_at >=', $fromDate)
+ ->where('policy_transaction.created_at <=', $toDate);
+ }
+ }
+
+ $builder->orderBy('policy_transaction.id', 'desc');
+
+ $result = $builder->get()->getResultArray();
+
+ // dd($this->db->getLastQuery());
+
+ return $result;
+ }
+
+ // public function getInceptionTranctionListData($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0, $status = 0)
+ // {
+ // // dd($start_date, $end_date, $client_id, $insurer_id, $policy_type_id, $date_type, $issuer, $status);
+ // $builder = $this->db->table('policy_transaction')
+ // ->select('
+ // policy_transaction.*,
+ // clients.short_name AS client_short_name,
+ // clients.client_code,
+ // clients.client_type,
+ // clients.client_name,
+ // client_branch.branch_name AS client_branch_name,
+ // insurers.name AS insurer_name,
+ // insurers.short_name AS insurer_short_name,
+ // policy_type.policy_type,
+ // pt_co_share_details.agreed_amt AS amount,
+ // pt_co_share_details.bp_amt AS bp,
+ // pt_co_share_details.tp_amt AS tp
+ // ')
+ // ->join('pt_co_share_details', 'policy_transaction.id = pt_co_share_details.pt_id', 'left')
+ // ->join('clients', 'clients.id = policy_transaction.client_id', 'left')
+ // ->join('client_branch', 'policy_transaction.client_branch_id = client_branch.id', 'left')
+ // ->join('insurers', 'pt_co_share_details.insurer_id = insurers.id', 'left')
+ // ->join('client_policy', 'policy_transaction.client_policy_id = client_policy.id', 'left')
+ // ->join('policy_type', 'policy_transaction.policy_type_id = policy_type.id', 'left')
+ // ->where('policy_transaction.is_active', 1)
+ // ->where('policy_transaction.action_type', 'inception');
+
+ // if ($start_date != 0 && $end_date != 0 && $date_type != 0) {
+
+ // $startDate = date('Y-m-d 00:00:00', strtotime($start_date));
+ // $endDate = date('Y-m-d 23:59:59', strtotime($end_date));
+
+ // $builder->where('policy_transaction.'.$date_type.'>=', $startDate)
+ // ->where('policy_transaction.'.$date_type.'<=', $endDate);
+ // }else{
+
+ // // $fromDate = date('Y-m-d', strtotime('-30 days'));
+ // // $toDate = date('Y-m-d 23:59:59');
+
+ // // $builder->where('policy_transaction.created_at >=', $fromDate)
+ // // ->where('policy_transaction.created_at <=', $toDate);
+ // }
+
+ // if ($client_id != 0) {
+ // $builder->where('policy_transaction.client_id', $client_id);
+ // }
+
+ // if ($insurer_id != 0) {
+ // $builder->where('policy_transaction.insurer_id', $insurer_id);
+ // }
+
+ // if ($policy_type_id != 0) {
+ // $builder->where('client_policy.policy_type_id', $policy_type_id);
+ // }
+
+ // if ($issuer != 0) {
+ // $builder->where('policy_transaction.issuer', $issuer);
+ // }
+ // if ($status != 0) {
+ // $builder->where('policy_transaction.status', $status);
+ // }
+
+ // if($client_id == 0 && $insurer_id == 0 && $policy_type_id == 0 && $date_type == 0 && $issuer == 0){
+
+ // $fromDate = date('Y-m-d', strtotime('-30 days'));
+ // $toDate = date('Y-m-d 23:59:59');
+
+ // $builder->where('policy_transaction.created_at >=', $fromDate)
+ // ->where('policy_transaction.created_at <=', $toDate);
+
+ // }
+
+ // $builder->orderBy('policy_transaction.id', 'desc')->limit(10);
+
+ // $result = $builder->get()->getResultArray();
+
+ // // dd($this->db->getLastQuery());
+
+ // return $result;
+ // }
+
+ public function getInceptionTranctionListData($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0, $status = 0, $where = null)
+ {
+ $builder = $this->db->table('policy_transaction')
+ ->select("
+ policy_transaction.*,
+ clients.short_name AS client_short_name,
+ clients.client_code,
+ clients.client_type,
+ clients.client_name,
+ client_branch.branch_name AS client_branch_name,
+ insurers.name AS insurer_name,
+ insurers.short_name AS insurer_short_name,
+ policy_type.policy_type,
+ pt_co_share_details.agreed_amt AS amount,
+ pt_co_share_details.bp_amt AS bp,
+ pt_co_share_details.tp_amt AS tp,
+ clients.pan,
+ DATE_FORMAT(policy_transaction.created_at, '%d %b %Y %h:%i %p') AS created_at,
+ user_profiles.first_name as user_name,
+ CASE
+ WHEN pt_co_share_details.co_share_type IN (0, 1)
+ THEN policy_transaction.policy_no
+ WHEN pt_co_share_details.co_share_type > 1
+ THEN CASE
+ WHEN pt_co_share_details.follower_policy_no IS NULL
+ OR pt_co_share_details.follower_policy_no = ''
+ THEN policy_transaction.policy_no
+ ELSE pt_co_share_details.follower_policy_no
+ END
+ ELSE policy_transaction.policy_no
+ END AS policy_no
+ ")
+ ->join('pt_co_share_details', 'policy_transaction.id = pt_co_share_details.pt_id', 'left')
+ ->join('clients', 'clients.id = policy_transaction.client_id', 'left')
+ ->join('client_branch', 'policy_transaction.client_branch_id = client_branch.id', 'left')
+ ->join('insurers', 'pt_co_share_details.insurer_id = insurers.id', 'left')
+ ->join('client_policy', 'policy_transaction.client_policy_id = client_policy.id', 'left')
+ ->join('policy_type', 'policy_transaction.policy_type_id = policy_type.id', 'left')
+ ->join('user_profiles', 'policy_transaction.created_by = user_profiles.id', 'left')
+ ->where('policy_transaction.is_active', 1)
+ ->where('policy_transaction.action_type', 'inception');
+
+ if (
+ (!in_array(get_role_id(), [1, 5])) &&
+ !(
+ in_array(MANAGEMENT_TEAM_ID, user_team()) ||
+ in_array(FINANCE_TEAM_ID, user_team()) ||
+ in_array(BUSINESS_TEAM_ID, user_team())
+ )
+ ) {
+ if (get_role_id() == 4 && in_array(POS_TEAM_ID, user_team())) {
+ $builder->where('policy_transaction.created_by', get_session_userid());
+ }
+ }
+
+ // Optimize Date Filtering
+ if (!empty($start_date) && !empty($end_date) && !empty($date_type)) {
+ $builder->where("policy_transaction.$date_type >=", date('Y-m-d 00:00:00', strtotime($start_date)))
+ ->where("policy_transaction.$date_type <=", date('Y-m-d 23:59:59', strtotime($end_date)));
+ }
+
+ // Apply Filters Only When Necessary
+ if (!empty($client_id)) {
+ $builder->where('policy_transaction.client_id', $client_id);
+ }
+ if (!empty($insurer_id)) {
+ $builder->where('policy_transaction.insurer_id', $insurer_id);
+ }
+ if (!empty($policy_type_id)) {
+ $builder->where('client_policy.policy_type_id', $policy_type_id);
+ }
+ if (!empty($issuer)) {
+ $builder->where('policy_transaction.issuer', $issuer);
+ }
+ if (!empty($status)) {
+ $builder->where('policy_transaction.status', $status);
+ }
+
+ // Default to Last 30 Days if No Filters Are Applied
+ if (empty($client_id) && empty($insurer_id) && empty($policy_type_id) && empty($date_type) && empty($issuer) && empty($where)) {
+ $fromDate = date('Y-m-d', strtotime('-90 days'));
+ $toDate = date('Y-m-d 23:59:59');
+
+ $builder->where('policy_transaction.created_at >=', $fromDate)
+ ->where('policy_transaction.created_at <=', $toDate);
+ }
+
+ if (!empty($where)) {
+ $builder->whereIn('policy_transaction.id', $where);
+ }
+
+ // Optimize Query Execution
+ $builder->orderBy('policy_transaction.id', 'desc');
+ $data = $builder->get()->getResultArray();
+ return $data;
}
- if ($start_date != 0 && $end_date != 0 && $date_type != 0) {
-
- $startDate = date('Y-m-d 00:00:00', strtotime($start_date));
- $endDate = date('Y-m-d 23:59:59', strtotime($end_date));
-
- $builder->where('policy_transaction.' . $date_type . '>=', $startDate)
- ->where('policy_transaction.' . $date_type . '<=', $endDate);
- } else {
-
- // $fromDate = date('Y-m-d', strtotime('-30 days'));
- // $toDate = date('Y-m-d 23:59:59');
-
- // $builder->where('policy_transaction.created_at >=', $fromDate)
- // ->where('policy_transaction.created_at <=', $toDate);
- }
-
- if ($client_id != 0) {
- $builder->where('policy_transaction.client_id', $client_id);
- }
-
- if ($insurer_id != 0) {
- $builder->where('policy_transaction.insurer_id', $insurer_id);
- }
-
- if ($policy_type_id != 0) {
- $builder->where('client_policy.policy_type_id', $policy_type_id);
- }
-
- if ($issuer != 0) {
- $builder->where('policy_transaction.issuer', $issuer);
- }
- if ($status != 0) {
- $builder->where('policy_transaction.status', $status);
- }
-
- if ($client_id == 0 && $insurer_id == 0 && $policy_type_id == 0 && $date_type == 0 && $issuer == 0) {
-
- $fromDate = date('Y-m-d', strtotime('-60 days'));
- $toDate = date('Y-m-d 23:59:59');
-
- $builder->where('policy_transaction.created_at >=', $fromDate)
- ->where('policy_transaction.created_at <=', $toDate);
- }
-
- $builder->orderBy('policy_transaction.id', 'desc');
-
- return $builder->get()->getResultArray();
- }
-
- public function getVarienceReportLIst($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0, $client_branch_id = 0, $insurer_branch_id = 0, $client_policy_id = 0)
- {
- $builder = $this->db->table('policy_transaction')
- ->select("
-
- policy_transaction.id,
- clients.client_name,
- client_branch.branch_name as client_branch_name,
- insurers.name AS insurer_name,
- insurer_branch.branch_name AS insurer_branch_name,
- policy_type.policy_type,
- policy_transaction.policy_no,
- policy_transaction.endorsement_no,
-
- pt_co_share_details.exp_amt,
- pt_co_share_details.variance,
- ROUND ( (pt_co_share_details.cop_amt + pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt),2) as original_premium,
- ROUND(
- (
- SELECT
- (
- SUM(co_share_stmt_details.actual_bp_amt) + SUM(co_share_stmt_details.actual_tp_amt) + SUM(co_share_stmt_details.actual_tep_amt)
- ) AS total_stmt_amt
- FROM
- co_share_stmt_details
- JOIN insurer_statements ON co_share_stmt_details.statement_id = insurer_statements.id and insurer_statements.is_active = 1
- WHERE
- co_share_stmt_details.co_share_id = pt_co_share_details.id
- AND co_share_stmt_details.is_active = 1
- ),
- 2
- ) AS statement_premium,
-
- COALESCE(
- (pt_co_share_details.cop_amt + pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt), 0
- ) -
- COALESCE(
- (
- SELECT
- SUM(co_share_stmt_details.actual_bp_amt) +
- SUM(co_share_stmt_details.actual_tp_amt) +
- SUM(co_share_stmt_details.actual_tep_amt)
- FROM
- co_share_stmt_details
- JOIN
- insurer_statements
- ON
- co_share_stmt_details.statement_id = insurer_statements.id
- AND insurer_statements.is_active = 1
- WHERE
- co_share_stmt_details.co_share_id = pt_co_share_details.id
- AND co_share_stmt_details.is_active = 1
- ), 0
- ) AS premium_variance_amt,
-
-
- ROUND(
- (
- SELECT
- (
- SUM(co_share_stmt_details.actual_bp_brokerage_amt) + SUM(co_share_stmt_details.actual_tp_brokerage_amt) + SUM(co_share_stmt_details.actual_tep_brokerage_amt) + SUM(co_share_stmt_details.reward)
- ) AS total_irda_amt
- FROM
- co_share_stmt_details
- JOIN insurer_statements ON co_share_stmt_details.statement_id = insurer_statements.id and insurer_statements.is_active = 1
- WHERE
- co_share_stmt_details.co_share_id = pt_co_share_details.id
- AND co_share_stmt_details.is_active = 1
- ),
- 2
- ) AS statement_amount,
-
- ROUND(
- pt_co_share_details.exp_amt -
- (
- SELECT
- (
- SUM(co_share_stmt_details.actual_bp_brokerage_amt) +
- SUM(co_share_stmt_details.actual_tp_brokerage_amt) +
- SUM(co_share_stmt_details.actual_tep_brokerage_amt) + SUM(co_share_stmt_details.reward)
- )
- FROM co_share_stmt_details
- JOIN insurer_statements
- ON co_share_stmt_details.statement_id = insurer_statements.id and insurer_statements.is_active = 1
- WHERE
- co_share_stmt_details.co_share_id = pt_co_share_details.id
- AND co_share_stmt_details.is_active = 1
- ),
- 2
- ) AS variance_amt,
- CASE
- WHEN pt_co_share_details.co_share_type IN (0, 1)
- THEN policy_transaction.policy_no
- WHEN pt_co_share_details.co_share_type > 1
- THEN CASE
- WHEN pt_co_share_details.follower_policy_no IS NULL
- OR pt_co_share_details.follower_policy_no = ''
+ public function getEndorsementTranctionListData($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0, $status = 0)
+ {
+ // dd($start_date, $end_date, $client_id, $insurer_id, $policy_type_id, $date_type, $issuer, $status);
+ $builder = $this->db->table('policy_transaction')
+ ->select("
+ policy_transaction.*,
+ clients.short_name as client_short_name,
+ clients.client_code,
+ client_branch.branch_name as client_branch_name,
+ insurers.name AS insurer_name,
+ insurers.short_name AS insurer_short_name,
+ policy_type.policy_type ,
+ CASE
+ WHEN pt_co_share_details.co_share_type IN (0, 1)
THEN policy_transaction.policy_no
- ELSE pt_co_share_details.follower_policy_no
- END
- ELSE policy_transaction.policy_no
- END AS policy_no
- ")
- ->join('pt_co_share_details', 'policy_transaction.id = pt_co_share_details.pt_id', 'left')
- ->join('insurer_statements', 'pt_co_share_details.statement_id = insurer_statements.id', 'left')
- ->join('clients', 'clients.id = policy_transaction.client_id', 'left')
- ->join('client_branch', 'client_branch.id = policy_transaction.client_branch_id', 'left')
- ->join('insurers', 'pt_co_share_details.insurer_id = insurers.id', 'left')
- ->join('insurer_branch', 'pt_co_share_details.insurer_branch_id = insurer_branch.id', 'left')
- ->join('client_policy', 'policy_transaction.client_policy_id = client_policy.id', 'left')
- ->join('policy_type', 'policy_transaction.policy_type_id = policy_type.id', 'left')
- ->where('policy_transaction.is_active', 1)
- ->where('pt_co_share_details.is_active', 1)
- // ->where('insurer_statements.is_active',1);
- // ->having('variance_amt IS NOT NULL')
- // ->having('variance_amt !=',0)
- // ->having('premium_variance_amt IS NOT NULL')
- // ->having('premium_variance_amt !=',0);
+ WHEN pt_co_share_details.co_share_type > 1
+ THEN CASE
+ WHEN pt_co_share_details.follower_policy_no IS NULL
+ OR pt_co_share_details.follower_policy_no = ''
+ THEN policy_transaction.policy_no
+ ELSE pt_co_share_details.follower_policy_no
+ END
+ ELSE policy_transaction.policy_no
+ END AS policy_no
+ ")
+ ->join('pt_co_share_details', 'policy_transaction.id = pt_co_share_details.pt_id', 'left')
+ ->join('clients', 'policy_transaction.client_id = clients.id', 'left')
+ ->join('client_branch', 'policy_transaction.client_branch_id = client_branch.id', 'left')
+ ->join('insurers', 'pt_co_share_details.insurer_id = insurers.id', 'left')
+ ->join('client_policy', 'policy_transaction.client_policy_id = client_policy.id', 'left')
+ ->join('policy_type', 'policy_transaction.policy_type_id = policy_type.id', 'left')
+ ->where('policy_transaction.is_active', 1)
+ ->where('policy_transaction.action_type !=', 'inception');
- // ->group_start()
- ->having('variance_amt IS NOT NULL')
- ->orHaving('variance_amt !=', 0)
- ->having('premium_variance_amt IS NOT NULL')
- ->orHaving('premium_variance_amt !=', 0);
- // ->group_end();
- // ->where('pt_co_share_details.actual_bp_brokerage_amt IS NOT NULL AND pt_co_share_details.actual_bp_brokerage_amt != 0');
- // ->where('pt_co_share_details.variance IS NOT NULL')
- // ->where('pt_co_share_details.variance !=', 0);
+ if (
+ (!in_array(get_role_id(), [1, 5])) &&
+ !(
+ in_array(MANAGEMENT_TEAM_ID, user_team()) ||
+ in_array(FINANCE_TEAM_ID, user_team()) ||
+ in_array(BUSINESS_TEAM_ID, user_team())
+ )
+ ) {
+ if (get_role_id() == 4 && in_array(POS_TEAM_ID, user_team())) {
+ $builder->where('policy_transaction.created_by', get_session_userid());
+ }
+ }
- if ($start_date != 0 && $end_date != 0 && $date_type != 0) {
- $startDate = date('Y-m-d 00:00:00', strtotime($start_date));
- $endDate = date('Y-m-d 23:59:59', strtotime($end_date));
+ if ($start_date != 0 && $end_date != 0 && $date_type != 0) {
- $builder->where('policy_transaction.' . $date_type . '>=', $startDate)
- ->where('policy_transaction.' . $date_type . '<=', $endDate);
- } else {
+ $startDate = date('Y-m-d 00:00:00', strtotime($start_date));
+ $endDate = date('Y-m-d 23:59:59', strtotime($end_date));
- $fromDate = date('Y-m-d', strtotime('-30 days'));
- $toDate = date('Y-m-d 23:59:59');
+ $builder->where('policy_transaction.' . $date_type . '>=', $startDate)
+ ->where('policy_transaction.' . $date_type . '<=', $endDate);
+ } else {
- $builder->where('policy_transaction.created_at >=', $fromDate)
- ->where('policy_transaction.created_at <=', $toDate);
+ // $fromDate = date('Y-m-d', strtotime('-30 days'));
+ // $toDate = date('Y-m-d 23:59:59');
+
+ // $builder->where('policy_transaction.created_at >=', $fromDate)
+ // ->where('policy_transaction.created_at <=', $toDate);
+ }
+
+ if ($client_id != 0) {
+ $builder->where('policy_transaction.client_id', $client_id);
+ }
+
+ if ($insurer_id != 0) {
+ $builder->where('policy_transaction.insurer_id', $insurer_id);
+ }
+
+ if ($policy_type_id != 0) {
+ $builder->where('client_policy.policy_type_id', $policy_type_id);
+ }
+
+ if ($issuer != 0) {
+ $builder->where('policy_transaction.issuer', $issuer);
+ }
+ if ($status != 0) {
+ $builder->where('policy_transaction.status', $status);
+ }
+
+ if ($client_id == 0 && $insurer_id == 0 && $policy_type_id == 0 && $date_type == 0 && $issuer == 0) {
+
+ $fromDate = date('Y-m-d', strtotime('-90 days'));
+ $toDate = date('Y-m-d 23:59:59');
+
+ $builder->where('policy_transaction.created_at >=', $fromDate)
+ ->where('policy_transaction.created_at <=', $toDate);
+ }
+
+ $builder->orderBy('policy_transaction.id', 'desc');
+
+ return $builder->get()->getResultArray();
}
- if ($client_id != 0) {
- $builder->where('policy_transaction.client_id', $client_id);
- }
-
- if ($insurer_id != 0) {
- $builder->where('policy_transaction.insurer_id', $insurer_id);
- }
-
- if ($policy_type_id != 0) {
- $builder->where('client_policy.policy_type_id', $policy_type_id);
- }
-
- if ($issuer != 0) {
- $builder->where('policy_transaction.issuer', $issuer);
- }
-
- if ($client_branch_id != 0) {
- $builder->where('policy_transaction.client_branch_id', $client_branch_id);
- }
-
- if ($insurer_branch_id != 0) {
- $builder->where('policy_transaction.insurer_branch_id', $insurer_branch_id);
- }
-
- if ($client_policy_id != 0) {
- $builder->where('policy_transaction.client_policy_id', $client_policy_id);
- }
-
-
- $builder->orderBy('policy_transaction.id', 'desc');
-
- return $builder->get()->getResultArray();
- }
-
- public function getBusinessReportList($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0, $status = 0)
- {
- $dateThreshold = date('Y-m-d H:i:s', strtotime("- 3 days"));
- $builder = $this->db->table('policy_transaction')
- ->select([
- 'policy_transaction.id AS policy_trns_id',
- 'clients.client_name',
- 'insurers.name AS insurer_name',
- 'policy_type.policy_type',
- 'policy_transaction.endorsement_no',
- "CASE
- WHEN policy_transaction.action_type = 'inception' THEN 'I'
- ELSE 'E'
- END AS action_type",
- 'policy_transaction.action_type as action_type_full',
- 'pt_co_share_details.bp_amt',
- 'pt_co_share_details.tp_amt',
- 'pt_co_share_details.tep_amt',
- 'policy_transaction.status',
- 'CASE
- WHEN pt_co_share_details.co_share_type IN (0, 1)
- THEN policy_transaction.policy_no
- WHEN pt_co_share_details.co_share_type > 1
- THEN CASE
- WHEN pt_co_share_details.follower_policy_no IS NULL
- OR pt_co_share_details.follower_policy_no = ""
- THEN policy_transaction.policy_no
- ELSE pt_co_share_details.follower_policy_no
- END
- ELSE policy_transaction.policy_no
- END AS policy_no'
- ])
- ->join('pt_co_share_details', 'policy_transaction.id = pt_co_share_details.pt_id', 'left')
- ->join('clients', 'clients.id = policy_transaction.client_id', 'left')
- ->join('insurers', 'pt_co_share_details.insurer_id = insurers.id', 'left')
- ->join('client_policy', 'policy_transaction.client_policy_id = client_policy.id', 'left')
- ->join('policy_type', 'policy_transaction.policy_type_id = policy_type.id', 'left')
- ->join(
- '(SELECT policy_tran_id, MAX(created_at) AS last_policy_status_change,is_active
- FROM policy_transaction_status
- WHERE is_active = 1
- GROUP BY policy_tran_id) th',
- 'policy_transaction.id = th.policy_tran_id'
-
- )
- ->where("th.last_policy_status_change <= '{$dateThreshold}'", null, false)
- ->where('policy_transaction.is_active', 1)
- ->where("policy_transaction.status is not null", null, false)
- ->whereNotIn("policy_transaction.status", ['completed'])
- // ->where('policy_transaction.status', 'completed')
- ->where('(pt_co_share_details.bp_amt IS NULL OR pt_co_share_details.bp_amt = 0)', null, false);
-
-
- if ($start_date != 0 && $end_date != 0 && $date_type != 0) {
-
- $startDate = date('Y-m-d 00:00:00', strtotime($start_date));
- $endDate = date('Y-m-d 23:59:59', strtotime($end_date));
-
- $builder->where('policy_transaction.' . $date_type . '>=', $startDate)
- ->where('policy_transaction.' . $date_type . '<=', $endDate);
- } else {
-
- $fromDate = date('Y-m-d', strtotime('-30 days'));
- $toDate = date('Y-m-d 23:59:59');
-
- $builder->where('policy_transaction.created_at >=', $fromDate)
- ->where('policy_transaction.created_at <=', $toDate);
- }
-
- if ($client_id != 0) {
- $builder->where('policy_transaction.client_id', $client_id);
- }
-
- if ($insurer_id != 0) {
- $builder->where('policy_transaction.insurer_id', $insurer_id);
- }
-
- if ($policy_type_id != 0) {
- $builder->where('client_policy.policy_type_id', $policy_type_id);
- }
-
- if ($issuer != 0) {
- $builder->where('policy_transaction.issuer', $issuer);
- }
-
- if ($status != 0) {
- $builder->where('policy_transaction.status', $status);
- }
-
- $builder->orderBy('policy_transaction.id', 'desc');
- // echo $builder->getCompiledSelect();
- // exit;
-
- $returnData = $builder->get()->getResultArray();
-
-
-
- // dd($returnData);
- return $returnData;
- }
-
- public function getFinanceReportList($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0, $status = 0)
- {
- $dateThreshold = date('Y-m-d H:i:s', strtotime("- 3 days"));
-
- $builder = $this->db->table('policy_transaction')
- ->select("
- policy_transaction.id,
- clients.client_name,
- insurers.name AS insurer_name,
- policy_type.policy_type,
- policy_transaction.policy_no,
- policy_transaction.endorsement_no,
- CASE
- WHEN policy_transaction.action_type = 'inception' THEN 'I'
- ELSE 'E'
- END AS action_type,
- policy_transaction.action_type AS action_type_full,
- pt_co_share_details.exp_amt,
- pt_co_share_details.variance,
- policy_transaction.status,
- CASE
- WHEN pt_co_share_details.co_share_type IN (0, 1)
- THEN policy_transaction.policy_no
- WHEN pt_co_share_details.co_share_type > 1
- THEN CASE
- WHEN pt_co_share_details.follower_policy_no IS NULL
- OR pt_co_share_details.follower_policy_no = ''
- THEN policy_transaction.policy_no
- ELSE pt_co_share_details.follower_policy_no
- END
- ELSE policy_transaction.policy_no
- END AS policy_no
- ")
- ->join('pt_co_share_details', 'policy_transaction.id = pt_co_share_details.pt_id', 'left')
- ->join('clients', 'clients.id = policy_transaction.client_id', 'left')
- ->join('insurers', 'pt_co_share_details.insurer_id = insurers.id', 'left')
- ->join('client_policy', 'policy_transaction.client_policy_id = client_policy.id', 'left')
- ->join('policy_type', 'policy_transaction.policy_type_id = policy_type.id', 'left')
- ->join(
- '(SELECT policy_tran_id, MAX(created_at) AS last_policy_status_change,is_active
- FROM policy_transaction_status
- WHERE is_active = 1
- GROUP BY policy_tran_id) th',
- 'policy_transaction.id = th.policy_tran_id'
-
- )
- ->where("th.last_policy_status_change <= '{$dateThreshold}'", null, false)
- ->where('policy_transaction.is_active', 1)
- // ->where('policy_transaction.status', 'completed')
- ->where('COALESCE(pt_co_share_details.agreed_bp_per, 0) + COALESCE(pt_co_share_details.agreed_tp_per, 0) + COALESCE(pt_co_share_details.agreed_tep_per, 0) = 0')
- ->where('COALESCE(pt_co_share_details.actual_bp_amt, 0) + COALESCE(pt_co_share_details.actual_tp_amt, 0) + COALESCE(pt_co_share_details.actual_tep_amt, 0) = 0')
- ->where('COALESCE(pt_co_share_details.actual_bp_brokerage_amt, 0) + COALESCE(pt_co_share_details.actual_tp_brokerage_amt, 0) + COALESCE(pt_co_share_details.actual_tep_brokerage_amt, 0) = 0')
- ->where("policy_transaction.status is not null", null, false)
- ->whereNotIn("policy_transaction.status", ['completed']);
-
- if ($start_date != 0 && $end_date != 0 && $date_type != 0) {
-
- $startDate = date('Y-m-d 00:00:00', strtotime($start_date));
- $endDate = date('Y-m-d 23:59:59', strtotime($end_date));
-
- $builder->where('policy_transaction.' . $date_type . '>=', $startDate)
- ->where('policy_transaction.' . $date_type . '<=', $endDate);
- } else {
-
- $fromDate = date('Y-m-d', strtotime('-30 days'));
- $toDate = date('Y-m-d 23:59:59');
-
- $builder->where('policy_transaction.created_at >=', $fromDate)
- ->where('policy_transaction.created_at <=', $toDate);
- }
-
- if ($client_id != 0) {
- $builder->where('policy_transaction.client_id', $client_id);
- }
-
- if ($insurer_id != 0) {
- $builder->where('policy_transaction.insurer_id', $insurer_id);
- }
-
- if ($policy_type_id != 0) {
- $builder->where('client_policy.policy_type_id', $policy_type_id);
- }
-
- if ($issuer != 0) {
- $builder->where('policy_transaction.issuer', $issuer);
- }
-
- if ($status != 0) {
- $builder->where('policy_transaction.status', $status);
- }
-
- $builder->orderBy('policy_transaction.id', 'desc');
-
- return $builder->get()->getResultArray();
- }
-
- public function getOutstandingReportList_OLD($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0, $status = 0)
- {
- $builder = $this->db->table('policy_transaction')
- ->select("
- policy_transaction.id,
- clients.client_name,
- insurers.name AS insurer_name,
- policy_type.policy_type,
- policy_transaction.endorsement_no,
- CASE
- WHEN policy_transaction.action_type = 'inception' THEN 'I'
- ELSE 'E'
- END AS action_type,
- pt_co_share_details.exp_amt,
- pt_co_share_details.variance,
- insurer_statements.invoice_amount,
- insurer_statements.invoice_status,
-
- ROUND((pt_co_share_details.actual_bp_brokerage_amt + pt_co_share_details.actual_tp_brokerage_amt + pt_co_share_details.actual_tep_brokerage_amt), 2) AS realization_amount2,
+ 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("
- (
- SELECT
- (SUM(inv_payment_details.inv_amt) + SUM(inv_payment_details.tds)) AS realization_amount
- FROM
- inv_payment_details
- WHERE
- inv_payment_details.statement_id = insurer_statements.id
- AND inv_payment_details.is_active = 1
-
- ) AS realization_amount,
-
- ROUND(
- insurer_statements.invoice_amount -
+ policy_transaction.id,
+ clients.client_name,
+ client_branch.branch_name as client_branch_name,
+ insurers.name AS insurer_name,
+ insurer_branch.branch_name AS insurer_branch_name,
+ policy_type.policy_type,
+ policy_transaction.policy_no,
+ policy_transaction.endorsement_no,
+
+ pt_co_share_details.exp_amt,
+ pt_co_share_details.variance,
+ ROUND ( (pt_co_share_details.cop_amt + pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt),2) as original_premium,
+ ROUND(
(
SELECT
- (SUM(inv_payment_details.inv_amt) + SUM(inv_payment_details.tds))
+ (
+ SUM(co_share_stmt_details.actual_bp_amt) + SUM(co_share_stmt_details.actual_tp_amt) + SUM(co_share_stmt_details.actual_tep_amt)
+ ) AS total_stmt_amt
+ FROM
+ co_share_stmt_details
+ JOIN insurer_statements ON co_share_stmt_details.statement_id = insurer_statements.id and insurer_statements.is_active = 1
+ WHERE
+ co_share_stmt_details.co_share_id = pt_co_share_details.id
+ AND co_share_stmt_details.is_active = 1
+ ),
+ 2
+ ) AS statement_premium,
+
+ COALESCE(
+ (pt_co_share_details.cop_amt + pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt), 0
+ ) -
+ COALESCE(
+ (
+ SELECT
+ SUM(co_share_stmt_details.actual_bp_amt) +
+ SUM(co_share_stmt_details.actual_tp_amt) +
+ SUM(co_share_stmt_details.actual_tep_amt)
+ FROM
+ co_share_stmt_details
+ JOIN
+ insurer_statements
+ ON
+ co_share_stmt_details.statement_id = insurer_statements.id
+ AND insurer_statements.is_active = 1
+ WHERE
+ co_share_stmt_details.co_share_id = pt_co_share_details.id
+ AND co_share_stmt_details.is_active = 1
+ ), 0
+ ) AS premium_variance_amt,
+
+
+ ROUND(
+ (
+ SELECT
+ (
+ SUM(co_share_stmt_details.actual_bp_brokerage_amt) + SUM(co_share_stmt_details.actual_tp_brokerage_amt) + SUM(co_share_stmt_details.actual_tep_brokerage_amt) + SUM(co_share_stmt_details.reward)
+ ) AS total_irda_amt
+ FROM
+ co_share_stmt_details
+ JOIN insurer_statements ON co_share_stmt_details.statement_id = insurer_statements.id and insurer_statements.is_active = 1
+ WHERE
+ co_share_stmt_details.co_share_id = pt_co_share_details.id
+ AND co_share_stmt_details.is_active = 1
+ ),
+ 2
+ ) AS statement_amount,
+
+ ROUND(
+ pt_co_share_details.exp_amt -
+ (
+ SELECT
+ (
+ SUM(co_share_stmt_details.actual_bp_brokerage_amt) +
+ SUM(co_share_stmt_details.actual_tp_brokerage_amt) +
+ SUM(co_share_stmt_details.actual_tep_brokerage_amt) + SUM(co_share_stmt_details.reward)
+ )
+ FROM co_share_stmt_details
+ JOIN insurer_statements
+ ON co_share_stmt_details.statement_id = insurer_statements.id and insurer_statements.is_active = 1
+ WHERE
+ co_share_stmt_details.co_share_id = pt_co_share_details.id
+ AND co_share_stmt_details.is_active = 1
+ ),
+ 2
+ ) AS variance_amt,
+ CASE
+ WHEN pt_co_share_details.co_share_type IN (0, 1)
+ THEN policy_transaction.policy_no
+ WHEN pt_co_share_details.co_share_type > 1
+ THEN CASE
+ WHEN pt_co_share_details.follower_policy_no IS NULL
+ OR pt_co_share_details.follower_policy_no = ''
+ THEN policy_transaction.policy_no
+ ELSE pt_co_share_details.follower_policy_no
+ END
+ ELSE policy_transaction.policy_no
+ END AS policy_no
+ ")
+ ->join('pt_co_share_details', 'policy_transaction.id = pt_co_share_details.pt_id', 'left')
+ ->join('insurer_statements', 'pt_co_share_details.statement_id = insurer_statements.id', 'left')
+ ->join('clients', 'clients.id = policy_transaction.client_id', 'left')
+ ->join('client_branch', 'client_branch.id = policy_transaction.client_branch_id', 'left')
+ ->join('insurers', 'pt_co_share_details.insurer_id = insurers.id', 'left')
+ ->join('insurer_branch', 'pt_co_share_details.insurer_branch_id = insurer_branch.id', 'left')
+ ->join('client_policy', 'policy_transaction.client_policy_id = client_policy.id', 'left')
+ ->join('policy_type', 'policy_transaction.policy_type_id = policy_type.id', 'left')
+ ->where('policy_transaction.is_active', 1)
+ ->where('pt_co_share_details.is_active', 1)
+ // ->where('insurer_statements.is_active',1);
+ // ->having('variance_amt IS NOT NULL')
+ // ->having('variance_amt !=',0)
+ // ->having('premium_variance_amt IS NOT NULL')
+ // ->having('premium_variance_amt !=',0);
+
+ // ->group_start()
+ ->having('variance_amt IS NOT NULL')
+ ->orHaving('variance_amt !=', 0)
+ ->having('premium_variance_amt IS NOT NULL')
+ ->orHaving('premium_variance_amt !=', 0);
+ // ->group_end();
+ // ->where('pt_co_share_details.actual_bp_brokerage_amt IS NOT NULL AND pt_co_share_details.actual_bp_brokerage_amt != 0');
+ // ->where('pt_co_share_details.variance IS NOT NULL')
+ // ->where('pt_co_share_details.variance !=', 0);
+
+ if ($start_date != 0 && $end_date != 0 && $date_type != 0) {
+
+ $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('-90 days'));
+ $toDate = date('Y-m-d 23:59:59');
+
+ $builder->where('policy_transaction.created_at >=', $fromDate)
+ ->where('policy_transaction.created_at <=', $toDate);
+ }
+
+ if ($client_id != 0) {
+ $builder->where('policy_transaction.client_id', $client_id);
+ }
+
+ if ($insurer_id != 0) {
+ $builder->where('policy_transaction.insurer_id', $insurer_id);
+ }
+
+ if ($policy_type_id != 0) {
+ $builder->where('client_policy.policy_type_id', $policy_type_id);
+ }
+
+ if ($issuer != 0) {
+ $builder->where('policy_transaction.issuer', $issuer);
+ }
+
+ if ($client_branch_id != 0) {
+ $builder->where('policy_transaction.client_branch_id', $client_branch_id);
+ }
+
+ if ($insurer_branch_id != 0) {
+ $builder->where('policy_transaction.insurer_branch_id', $insurer_branch_id);
+ }
+
+ if ($client_policy_id != 0) {
+ $builder->where('policy_transaction.client_policy_id', $client_policy_id);
+ }
+
+
+ $builder->orderBy('policy_transaction.id', 'desc');
+
+ return $builder->get()->getResultArray();
+ }
+
+ public function getBusinessReportList($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0, $status = 0)
+ {
+ $dateThreshold = date('Y-m-d H:i:s', strtotime("- 3 days"));
+ $builder = $this->db->table('policy_transaction')
+ ->select([
+ 'policy_transaction.id AS policy_trns_id',
+ 'clients.client_name',
+ 'insurers.name AS insurer_name',
+ 'policy_type.policy_type',
+ 'policy_transaction.endorsement_no',
+ "CASE
+ WHEN policy_transaction.action_type = 'inception' THEN 'I'
+ ELSE 'E'
+ END AS action_type",
+ 'policy_transaction.action_type as action_type_full',
+ 'pt_co_share_details.bp_amt',
+ 'pt_co_share_details.tp_amt',
+ 'pt_co_share_details.tep_amt',
+ 'policy_transaction.status',
+ 'CASE
+ WHEN pt_co_share_details.co_share_type IN (0, 1)
+ THEN policy_transaction.policy_no
+ WHEN pt_co_share_details.co_share_type > 1
+ THEN CASE
+ WHEN pt_co_share_details.follower_policy_no IS NULL
+ OR pt_co_share_details.follower_policy_no = ""
+ THEN policy_transaction.policy_no
+ ELSE pt_co_share_details.follower_policy_no
+ END
+ ELSE policy_transaction.policy_no
+ END AS policy_no'
+ ])
+ ->join('pt_co_share_details', 'policy_transaction.id = pt_co_share_details.pt_id', 'left')
+ ->join('clients', 'clients.id = policy_transaction.client_id', 'left')
+ ->join('insurers', 'pt_co_share_details.insurer_id = insurers.id', 'left')
+ ->join('client_policy', 'policy_transaction.client_policy_id = client_policy.id', 'left')
+ ->join('policy_type', 'policy_transaction.policy_type_id = policy_type.id', 'left')
+ ->join(
+ '(SELECT policy_tran_id, MAX(created_at) AS last_policy_status_change,is_active
+ FROM policy_transaction_status
+ WHERE is_active = 1
+ GROUP BY policy_tran_id) th',
+ 'policy_transaction.id = th.policy_tran_id'
+
+ )
+ ->where("th.last_policy_status_change <= '{$dateThreshold}'", null, false)
+ ->where('policy_transaction.is_active', 1)
+ ->where("policy_transaction.status is not null", null, false)
+ ->whereNotIn("policy_transaction.status", ['completed'])
+ // ->where('policy_transaction.status', 'completed')
+ ->where('(pt_co_share_details.bp_amt IS NULL OR pt_co_share_details.bp_amt = 0)', null, false);
+
+
+ if ($start_date != 0 && $end_date != 0 && $date_type != 0) {
+
+ $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('-90 days'));
+ $toDate = date('Y-m-d 23:59:59');
+
+ $builder->where('policy_transaction.created_at >=', $fromDate)
+ ->where('policy_transaction.created_at <=', $toDate);
+ }
+
+ if ($client_id != 0) {
+ $builder->where('policy_transaction.client_id', $client_id);
+ }
+
+ if ($insurer_id != 0) {
+ $builder->where('policy_transaction.insurer_id', $insurer_id);
+ }
+
+ if ($policy_type_id != 0) {
+ $builder->where('client_policy.policy_type_id', $policy_type_id);
+ }
+
+ if ($issuer != 0) {
+ $builder->where('policy_transaction.issuer', $issuer);
+ }
+
+ if ($status != 0) {
+ $builder->where('policy_transaction.status', $status);
+ }
+
+ $builder->orderBy('policy_transaction.id', 'desc');
+ // echo $builder->getCompiledSelect();
+ // exit;
+
+ $returnData = $builder->get()->getResultArray();
+
+
+
+ // dd($returnData);
+ return $returnData;
+ }
+
+ public function getFinanceReportList($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0, $status = 0)
+ {
+ $dateThreshold = date('Y-m-d H:i:s', strtotime("-90 days"));
+
+ $builder = $this->db->table('policy_transaction')
+ ->select("
+ policy_transaction.id,
+ clients.client_name,
+ insurers.name AS insurer_name,
+ policy_type.policy_type,
+ policy_transaction.policy_no,
+ policy_transaction.endorsement_no,
+ CASE
+ WHEN policy_transaction.action_type = 'inception' THEN 'I'
+ ELSE 'E'
+ END AS action_type,
+ policy_transaction.action_type AS action_type_full,
+ pt_co_share_details.exp_amt,
+ pt_co_share_details.variance,
+ policy_transaction.status,
+ CASE
+ WHEN pt_co_share_details.co_share_type IN (0, 1)
+ THEN policy_transaction.policy_no
+ WHEN pt_co_share_details.co_share_type > 1
+ THEN CASE
+ WHEN pt_co_share_details.follower_policy_no IS NULL
+ OR pt_co_share_details.follower_policy_no = ''
+ THEN policy_transaction.policy_no
+ ELSE pt_co_share_details.follower_policy_no
+ END
+ ELSE policy_transaction.policy_no
+ END AS policy_no
+ ")
+ ->join('pt_co_share_details', 'policy_transaction.id = pt_co_share_details.pt_id', 'left')
+ ->join('clients', 'clients.id = policy_transaction.client_id', 'left')
+ ->join('insurers', 'pt_co_share_details.insurer_id = insurers.id', 'left')
+ ->join('client_policy', 'policy_transaction.client_policy_id = client_policy.id', 'left')
+ ->join('policy_type', 'policy_transaction.policy_type_id = policy_type.id', 'left')
+ ->join(
+ '(SELECT policy_tran_id, MAX(created_at) AS last_policy_status_change,is_active
+ FROM policy_transaction_status
+ WHERE is_active = 1
+ GROUP BY policy_tran_id) th',
+ 'policy_transaction.id = th.policy_tran_id'
+
+ )
+ ->where("th.last_policy_status_change <= '{$dateThreshold}'", null, false)
+ ->where('policy_transaction.is_active', 1)
+ // ->where('policy_transaction.status', 'completed')
+ ->where('COALESCE(pt_co_share_details.agreed_bp_per, 0) + COALESCE(pt_co_share_details.agreed_tp_per, 0) + COALESCE(pt_co_share_details.agreed_tep_per, 0) = 0')
+ ->where('COALESCE(pt_co_share_details.actual_bp_amt, 0) + COALESCE(pt_co_share_details.actual_tp_amt, 0) + COALESCE(pt_co_share_details.actual_tep_amt, 0) = 0')
+ ->where('COALESCE(pt_co_share_details.actual_bp_brokerage_amt, 0) + COALESCE(pt_co_share_details.actual_tp_brokerage_amt, 0) + COALESCE(pt_co_share_details.actual_tep_brokerage_amt, 0) = 0')
+ ->where("policy_transaction.status is not null", null, false)
+ ->whereNotIn("policy_transaction.status", ['completed']);
+
+ if ($start_date != 0 && $end_date != 0 && $date_type != 0) {
+
+ $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('-90 days'));
+ $toDate = date('Y-m-d 23:59:59');
+
+ $builder->where('policy_transaction.created_at >=', $fromDate)
+ ->where('policy_transaction.created_at <=', $toDate);
+ }
+
+ if ($client_id != 0) {
+ $builder->where('policy_transaction.client_id', $client_id);
+ }
+
+ if ($insurer_id != 0) {
+ $builder->where('policy_transaction.insurer_id', $insurer_id);
+ }
+
+ if ($policy_type_id != 0) {
+ $builder->where('client_policy.policy_type_id', $policy_type_id);
+ }
+
+ if ($issuer != 0) {
+ $builder->where('policy_transaction.issuer', $issuer);
+ }
+
+ if ($status != 0) {
+ $builder->where('policy_transaction.status', $status);
+ }
+
+ $builder->orderBy('policy_transaction.id', 'desc');
+
+ return $builder->get()->getResultArray();
+ }
+
+ public function getOutstandingReportList_OLD($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0, $status = 0)
+ {
+ $builder = $this->db->table('policy_transaction')
+ ->select("
+ policy_transaction.id,
+ clients.client_name,
+ insurers.name AS insurer_name,
+ policy_type.policy_type,
+ policy_transaction.endorsement_no,
+ CASE
+ WHEN policy_transaction.action_type = 'inception' THEN 'I'
+ ELSE 'E'
+ END AS action_type,
+ pt_co_share_details.exp_amt,
+ pt_co_share_details.variance,
+ insurer_statements.invoice_amount,
+ insurer_statements.invoice_status,
+
+ ROUND((pt_co_share_details.actual_bp_brokerage_amt + pt_co_share_details.actual_tp_brokerage_amt + pt_co_share_details.actual_tep_brokerage_amt), 2) AS realization_amount2,
+
+ (
+ SELECT
+ (SUM(inv_payment_details.inv_amt) + SUM(inv_payment_details.tds)) AS realization_amount
FROM
inv_payment_details
WHERE
inv_payment_details.statement_id = insurer_statements.id
AND inv_payment_details.is_active = 1
- ),
- 2) AS outstanding_amount,
- CASE
- WHEN pt_co_share_details.co_share_type IN (0, 1)
- THEN policy_transaction.policy_no
- WHEN pt_co_share_details.co_share_type > 1
- THEN CASE
- WHEN pt_co_share_details.follower_policy_no IS NULL
- OR pt_co_share_details.follower_policy_no = ''
+
+ ) AS realization_amount,
+
+ ROUND(
+ insurer_statements.invoice_amount -
+ (
+ SELECT
+ (SUM(inv_payment_details.inv_amt) + SUM(inv_payment_details.tds))
+ FROM
+ inv_payment_details
+ WHERE
+ inv_payment_details.statement_id = insurer_statements.id
+ AND inv_payment_details.is_active = 1
+ ),
+ 2) AS outstanding_amount,
+ CASE
+ WHEN pt_co_share_details.co_share_type IN (0, 1)
+ THEN policy_transaction.policy_no
+ WHEN pt_co_share_details.co_share_type > 1
+ THEN CASE
+ WHEN pt_co_share_details.follower_policy_no IS NULL
+ OR pt_co_share_details.follower_policy_no = ''
+ THEN policy_transaction.policy_no
+ ELSE pt_co_share_details.follower_policy_no
+ END
+ ELSE policy_transaction.policy_no
+ END AS policy_no
+ ")
+ ->join('pt_co_share_details', 'policy_transaction.id = pt_co_share_details.pt_id', 'left')
+ ->join('insurer_statements', 'pt_co_share_details.statement_id = insurer_statements.id', 'left')
+ ->join('inv_payment_details', 'insurer_statements.id = inv_payment_details.statement_id', 'left')
+ ->join('clients', 'clients.id = policy_transaction.client_id', 'left')
+ ->join('insurers', 'pt_co_share_details.insurer_id = insurers.id', 'left')
+ ->join('client_policy', 'policy_transaction.client_policy_id = client_policy.id', 'left')
+ ->join('policy_type', 'policy_transaction.policy_type_id = policy_type.id', 'left')
+ ->where('policy_transaction.is_active', 1);
+
+ // Date range filtering
+ if ($start_date != 0 && $end_date != 0 && $date_type != 0) {
+ $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('-90 days'));
+ $toDate = date('Y-m-d 23:59:59');
+
+ $builder->where('policy_transaction.created_at >=', $fromDate)
+ ->where('policy_transaction.created_at <=', $toDate);
+ }
+
+ // Additional filters
+ if ($client_id != 0) {
+ $builder->where('policy_transaction.client_id', $client_id);
+ }
+
+ if ($insurer_id != 0) {
+ $builder->where('policy_transaction.insurer_id', $insurer_id);
+ }
+
+ if ($policy_type_id != 0) {
+ $builder->where('client_policy.policy_type_id', $policy_type_id);
+ }
+
+ if ($issuer != 0) {
+ $builder->where('policy_transaction.issuer', $issuer);
+ }
+
+ if ($status != 0) {
+ $builder->where('policy_transaction.status', $status);
+ }
+
+ // Filter where outstanding_amount is not null
+ $builder->having('outstanding_amount IS NOT NULL');
+
+ $builder->orderBy('policy_transaction.id', 'desc');
+
+ return $builder->get()->getResultArray();
+ }
+
+ public function getOutstandingReportList($start_date = 0, $end_date = 0, $insurer_id = 0, $insurer_branch_id = 0)
+ {
+ $builder = $this->db->table('insurer_statements s')
+ ->select('
+ s.id,
+ s.insurer_id,
+ s.branch_id,
+ ins.short_name,
+ ib.branch_name,
+ s.month,
+ s.line_items,
+ s.stmt_sno,
+ s.invoice_status,
+ s.invoice_date,
+ s.invoice_no,
+ s.invoice_amount,
+ COALESCE(SUM(p.inv_amt) + SUM(p.tds) + SUM(p.gst), 0) AS total_paid,
+ (s.invoice_amount - COALESCE(SUM(p.inv_amt) + SUM(p.tds) + SUM(p.gst), 0)) AS outstanding_amount
+ ')
+ ->join('inv_payment_details p', 's.id = p.statement_id', 'left')
+ ->join('insurers ins', 's.insurer_id = ins.id')
+ ->join('insurer_branch ib', 's.branch_id = ib.id')
+ ->where('s.is_active', 1)
+ ->where('p.is_active', 1)
+ ->groupBy('s.id, s.invoice_no, s.invoice_date, s.invoice_amount')
+ ->having('outstanding_amount >', 0);
+ // ->get();
+
+
+ // Date range filtering
+ if ($start_date != 0 && $end_date != 0) {
+
+ $builder->where('s.month >=', $start_date)
+ ->where('s.month <=', $end_date);
+ }
+
+ if ($insurer_id != 0) {
+ $builder->where('s.insurer_id', $insurer_id);
+ }
+ if ($insurer_branch_id != 0) {
+ $builder->where('s.branch_id', $insurer_branch_id);
+ }
+
+ $builder->orderBy('s.id', 'desc');
+
+ return $builder->get()->getResultArray();
+ }
+
+
+ //function for fetch renewal report data
+ public function getRenewalReportData($start_date = null, $end_date = null, $client_type = null, $client = null, $issuer = null)
+ {
+ $fromDate = date('Y-m-d', strtotime('-90 days'));
+ $toDate = date('Y-m-d 23:59:59');
+
+ if (!empty($start_date) && !empty($end_date)) {
+ $fromDate = change_date_format($start_date);
+ $toDate = change_date_format($end_date);
+ }
+
+ $query = $this->db->table('policy_transaction pt')
+ ->select('
+ pt.*,
+ c.client_name,
+ c.short_name AS client_short_name,
+ c.client_type,
+ policy_type.policy_type,
+ i.name as insurer_name,
+ ib.branch_name as insurer_branch_name,
+ vehicle.vehicle_no,
+ leads.status as lead_status
+ ')
+ ->join('clients c', 'pt.client_id = c.id', 'left')
+ ->join('pt_co_share_details pt_co', 'pt.id = pt_co.pt_id and pt_co.co_share_type = 1', 'left')
+ ->join('insurers i', 'pt_co.insurer_id = i.id', 'left')
+ ->join('insurer_branch ib', 'pt_co.insurer_branch_id = ib.id', 'left')
+ ->join('policy_type', 'pt.policy_type_id = policy_type.id', 'left')
+ ->join('vehicle', 'pt.vehicle_id = vehicle.id and vehicle.is_active = 1', 'left')
+ ->join('leads', 'pt.client_policy_id = leads.source_policy_id and leads.source_policy_id != 0 and leads.is_active = 1', 'left')
+ ->where('pt.policy_end_date >=', $fromDate)
+ ->where('pt.policy_end_date <=', $toDate)
+ ->where('pt.is_active', 1)
+ ->where('pt_co.is_active', 1)
+ ->where('pt.action_type', "inception");
+
+ // Apply filters if parameters are provided
+ if (!empty($client_type)) {
+ $query->where('c.client_type', $client_type);
+ }
+ if (!empty($client)) {
+ $query->where('pt.client_id', $client);
+ }
+ if (!empty($issuer)) { // Corrected condition to check $issuer
+ $query->where('pt.issuer', $issuer);
+ }
+
+ $query->groupBy('pt.id');
+ $query->orderBy('pt.id', 'DESC');
+ // Fetch and return results
+ $results = $query->get()->getResultArray();
+ // print($this->db->getLastQuery()); die;
+ return $results;
+ }
+
+ public function getBDSRenewalData()
+ {
+ // Increase GROUP_CONCAT limit
+ $this->db->query("SET SESSION group_concat_max_len = 1000000;");
+
+ $builder = $this->db->table('policy_transaction pt');
+
+ $builder->select([
+ 'SUM(CASE WHEN pt.policy_end_date < CURDATE() THEN 1 ELSE 0 END) AS Expired',
+ 'SUM(CASE WHEN pt.policy_end_date BETWEEN CURDATE() AND (CURDATE() + INTERVAL 1 MONTH) THEN 1 ELSE 0 END) AS `Renewal Pending`',
+ 'GROUP_CONCAT(CASE WHEN pt.policy_end_date < CURDATE() THEN pt.id ELSE NULL END) AS Expired_ids',
+ 'GROUP_CONCAT(CASE WHEN pt.policy_end_date BETWEEN CURDATE() AND (CURDATE() + INTERVAL 1 MONTH) THEN pt.id ELSE NULL END) AS Renewal_Pending_ids'
+ ]);
+ $builder->where("pt.policy_end_date IS NOT NULL", null, false);
+ $builder->where('pt.is_active', 1);
+
+ // Self join to check if a policy has been renewed
+ $builder->join('policy_transaction renewed', 'renewed.source_client_policy_id = pt.client_policy_id and renewed.client_id = pt.client_id and renewed.client_branch_id = pt.client_branch_id', 'left');
+
+ // Filter for expired or expiring policies
+ $builder->where("(pt.policy_end_date < CURDATE() OR pt.policy_end_date BETWEEN CURDATE() AND (CURDATE() + INTERVAL 1 MONTH))", null, false);
+
+ $builder->where('renewed.id IS NULL', null, false);
+ $query = $builder->get();
+ $result = $query->getResultArray();
+
+ $total = 0;
+ foreach ($result[0] as $key => $value) {
+ if ($key !== 'Expired_ids' && $key !== 'Renewal_Pending_ids') {
+ $total += $value;
+ }
+ }
+
+ // Ensure ID fields are arrays (not null)
+ $result[0]['Expired_ids'] = $result[0]['Expired_ids'] ? $result[0]['Expired_ids'] : [];
+ $result[0]['Renewal Pending_ids'] = $result[0]['Renewal_Pending_ids'] ? $result[0]['Renewal_Pending_ids'] : [];
+
+ // Add total count
+ $result[0]['total'] = $total;
+
+ return $result[0];
+ }
+
+ public function reportBDSNew(
+ $start_date = 0,
+ $end_date = 0,
+ $client_id = 0,
+ $insurer_id = 0,
+ $policy_type_id = 0,
+ $date_type = 0,
+ $issuer = 0,
+ $client_branch_id = 0,
+ $insurer_branch_id = 0,
+ $client_policy_id = 0,
+ $user_id = 0,
+ $where = []
+ ) {
+
+ $date_condition = '';
+
+ // ==============================
+ // DATE FILTER FOR STATEMENT MONTH
+ // ==============================
+ if ($date_type == 'statement_month' && $start_date != 0 && $end_date != 0) {
+ $date_condition = "
+ AND insurer_statements_oq.month >= '{$start_date}'
+ AND insurer_statements_oq.month <= '{$end_date}'
+ ";
+ }
+
+ // ==============================
+ // BASE QUERY
+ // ==============================
+
+
+ // ==============================
+ // Without Statement Upload
+ // ==============================
+
+
+ $builder2 = $this->db->table('policy_transaction')
+ ->select("
+ policy_transaction.id AS id,
+ policy_transaction.endorsement_no AS endorsement_no,
+ policy_transaction.ref AS ref,
+ DATE_FORMAT(policy_transaction.policy_issue_date, '%d %b %Y') AS policy_issue_date,
+
+ DATE_FORMAT( policy_transaction.policy_issue_date, '%b %Y') AS policy_issue_month,
+
+ CASE
+ WHEN 1 = 1 THEN 'no statement uploaded'
+ ELSE 'statement uploaded'
+ END AS statement_uploaded ,
+
+
+ CASE
+ WHEN clients.client_type = 1 THEN 'Group'
+ WHEN clients.client_type = 2 THEN 'Retail'
+ ELSE '-'
+ END AS client_type,
+
+ CASE
+ WHEN policy_transaction.revenue_type = 'NA' THEN 'Fresh'
+ ELSE 'Renewal'
+ END AS revenue_type,
+
+ CASE
+ WHEN policy_transaction.action_type = 'inception' THEN 'Policy'
+ ELSE 'Endorsement'
+ END AS action_type,
+
+ clients.client_name AS client_name,
+ clients.short_name AS client_short_name,
+ client_branch.branch_name AS client_branch_name,
+ client_branch.address1 AS client_address,
+ policy_type.policy_type,
+ policy_type.bap,
+ insurers.name AS insurer_name,
+ insurers.short_name AS insurer_short_name,
+ insurer_branch.branch_name AS insurer_branch_name,
+ insurer_branch.branch_code AS insurer_branch_code,
+ user_profiles.first_name AS user_name,
+ vehicle.vehicle_no,
+ tpa.name AS tpa_name,
+ pt_co_share_details.remark AS remarks,
+ pt_co_share_details.cop_amt AS bp_amt,
+ pt_co_share_details.exp_amt,
+ pt_co_share_details.id AS pt_id,
+ sales_user.first_name AS salse_person_name,
+ service_user.first_name AS service_person_name,
+
+ ROUND(pt_co_share_details.cop_amt + pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt, 2) AS premium_wo_gst,
+ ROUND((ROUND(pt_co_share_details.cop_amt + pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt, 2) * 18 / 100), 2) AS gst_amount,
+ ROUND(
+ ROUND(pt_co_share_details.cop_amt + pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt, 2) +
+ ROUND((ROUND(pt_co_share_details.cop_amt + pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt, 2) * 18 / 100), 2),
+ 2) AS total_premium,
+
+ ROUND(pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt, 2) AS tp_or_ter,
+ DATEDIFF(policy_transaction.policy_end_date, CURDATE()) AS days,
+ (pt_co_share_details.agreed_tp_per + pt_co_share_details.agreed_tep_per) AS agreed_tp_or_ter_per,
+ pt_co_share_details.agreed_bp_per,
+
+ -- ==============================
+ -- SUBQUERY: Total IRDA Amount
+ -- Alias Agreed Amount ...!!
+ -- ==============================
+ ROUND(pt_co_share_details.exp_amt, 2) AS total_irda_amt,
+
+ -- Reward Only
+ ROUND(0, 2) AS reward,
+
+ -- Billed Amount
+ ROUND(0, 2) AS billed_amt,
+
+ created_user.first_name AS user_name,
+
+ CASE
+ WHEN pt_co_share_details.co_share_type IN (0, 1) THEN policy_transaction.policy_no
+ WHEN pt_co_share_details.co_share_type > 1 THEN
+ CASE
+ WHEN pt_co_share_details.follower_policy_no IS NULL OR pt_co_share_details.follower_policy_no = ''
THEN policy_transaction.policy_no
ELSE pt_co_share_details.follower_policy_no
END
- ELSE policy_transaction.policy_no
- END AS policy_no
- ")
- ->join('pt_co_share_details', 'policy_transaction.id = pt_co_share_details.pt_id', 'left')
- ->join('insurer_statements', 'pt_co_share_details.statement_id = insurer_statements.id', 'left')
- ->join('inv_payment_details', 'insurer_statements.id = inv_payment_details.statement_id', 'left')
- ->join('clients', 'clients.id = policy_transaction.client_id', 'left')
- ->join('insurers', 'pt_co_share_details.insurer_id = insurers.id', 'left')
- ->join('client_policy', 'policy_transaction.client_policy_id = client_policy.id', 'left')
- ->join('policy_type', 'policy_transaction.policy_type_id = policy_type.id', 'left')
- ->where('policy_transaction.is_active', 1);
+ ELSE policy_transaction.policy_no
+ END AS policy_no
+ ")
- // Date range filtering
- if ($start_date != 0 && $end_date != 0 && $date_type != 0) {
- $startDate = date('Y-m-d 00:00:00', strtotime($start_date));
- $endDate = date('Y-m-d 23:59:59', strtotime($end_date));
+ // ==============================
+ // JOINS
+ // ==============================
+ ->join('pt_co_share_details', 'policy_transaction.id = pt_co_share_details.pt_id', 'left')
+ ->join('clients', 'clients.id = policy_transaction.client_id')
+ ->join('client_branch', 'policy_transaction.client_branch_id = client_branch.id', 'left')
+ ->join('client_policy', 'policy_transaction.client_policy_id = client_policy.id', 'left')
+ ->join('user_profiles', 'policy_transaction.created_by = user_profiles.id', 'left')
+ ->join('vehicle', 'policy_transaction.vehicle_id = vehicle.id', 'left')
+ ->join('policy_type', 'policy_transaction.policy_type_id = policy_type.id', 'left')
+ ->join('insurers', 'pt_co_share_details.insurer_id = insurers.id', 'left')
+ ->join('insurer_branch', 'pt_co_share_details.insurer_branch_id = insurer_branch.id', 'left')
+ ->join('tpa', 'policy_transaction.tpa_id = tpa.id', 'left')
+ ->join('tpa_branch', 'policy_transaction.tpa_branch_id = tpa_branch.id', 'left')
+ ->join('user_profiles AS sales_user', 'policy_transaction.sales_generated_by = sales_user.id', 'left')
+ ->join('user_profiles AS service_user', 'policy_transaction.serviced_by = service_user.id', 'left')
+ ->join('user_profiles AS created_user', 'policy_transaction.created_by = created_user.id', 'left')
+
+ ->where('policy_transaction.is_active', 1)
+ ->where('pt_co_share_details.is_active', 1)
- $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');
+ // ========================================================
+ // GROUP BY Insurer Statement Months
+ // =======================================================
+ ->groupBy('policy_transaction.policy_no , pt_co_share_details.insurer_id ');
- $builder->where('policy_transaction.created_at >=', $fromDate)
- ->where('policy_transaction.created_at <=', $toDate);
- }
-
- // Additional filters
- if ($client_id != 0) {
- $builder->where('policy_transaction.client_id', $client_id);
- }
-
- if ($insurer_id != 0) {
- $builder->where('policy_transaction.insurer_id', $insurer_id);
- }
-
- if ($policy_type_id != 0) {
- $builder->where('client_policy.policy_type_id', $policy_type_id);
- }
-
- if ($issuer != 0) {
- $builder->where('policy_transaction.issuer', $issuer);
- }
-
- if ($status != 0) {
- $builder->where('policy_transaction.status', $status);
- }
-
- // Filter where outstanding_amount is not null
- $builder->having('outstanding_amount IS NOT NULL');
-
- $builder->orderBy('policy_transaction.id', 'desc');
-
- return $builder->get()->getResultArray();
- }
-
- public function getOutstandingReportList($start_date = 0, $end_date = 0, $insurer_id = 0, $insurer_branch_id = 0)
- {
- $builder = $this->db->table('insurer_statements s')
- ->select('
- s.id,
- s.insurer_id,
- s.branch_id,
- ins.short_name,
- ib.branch_name,
- s.month,
- s.line_items,
- s.stmt_sno,
- s.invoice_status,
- s.invoice_date,
- s.invoice_no,
- s.invoice_amount,
- COALESCE(SUM(p.inv_amt) + SUM(p.tds) + SUM(p.gst), 0) AS total_paid,
- (s.invoice_amount - COALESCE(SUM(p.inv_amt) + SUM(p.tds) + SUM(p.gst), 0)) AS outstanding_amount
- ')
- ->join('inv_payment_details p', 's.id = p.statement_id', 'left')
- ->join('insurers ins', 's.insurer_id = ins.id')
- ->join('insurer_branch ib', 's.branch_id = ib.id')
- ->where('s.is_active', 1)
- ->where('p.is_active', 1)
- ->groupBy('s.id, s.invoice_no, s.invoice_date, s.invoice_amount')
- ->having('outstanding_amount >', 0);
- // ->get();
-
-
- // Date range filtering
- if ($start_date != 0 && $end_date != 0) {
-
- $builder->where('s.month >=', $start_date)
- ->where('s.month <=', $end_date);
- }
-
- if ($insurer_id != 0) {
- $builder->where('s.insurer_id', $insurer_id);
- }
- if ($insurer_branch_id != 0) {
- $builder->where('s.branch_id', $insurer_branch_id);
- }
-
- $builder->orderBy('s.id', 'desc');
-
- return $builder->get()->getResultArray();
- }
-
-
- //function for fetch renewal report data
- public function getRenewalReportData($start_date = null, $end_date = null, $client_type = null, $client = null, $issuer = null)
- {
- $fromDate = date('Y-m-d', strtotime('-60 days'));
- $toDate = date('Y-m-d 23:59:59');
-
- if (!empty($start_date) && !empty($end_date)) {
- $fromDate = change_date_format($start_date);
- $toDate = change_date_format($end_date);
- }
-
- $query = $this->db->table('policy_transaction pt')
- ->select('
- pt.*,
- c.client_name,
- c.short_name AS client_short_name,
- c.client_type,
- policy_type.policy_type,
- i.name as insurer_name,
- ib.branch_name as insurer_branch_name,
- vehicle.vehicle_no,
- leads.status as lead_status
- ')
- ->join('clients c', 'pt.client_id = c.id', 'left')
- ->join('pt_co_share_details pt_co', 'pt.id = pt_co.pt_id and pt_co.co_share_type = 1', 'left')
- ->join('insurers i', 'pt_co.insurer_id = i.id', 'left')
- ->join('insurer_branch ib', 'pt_co.insurer_branch_id = ib.id', 'left')
- ->join('policy_type', 'pt.policy_type_id = policy_type.id', 'left')
- ->join('vehicle', 'pt.vehicle_id = vehicle.id and vehicle.is_active = 1', 'left')
- ->join('leads', 'pt.client_policy_id = leads.source_policy_id and leads.source_policy_id != 0 and leads.is_active = 1', 'left')
- ->where('pt.policy_end_date >=', $fromDate)
- ->where('pt.policy_end_date <=', $toDate)
- ->where('pt.is_active', 1)
- ->where('pt_co.is_active', 1)
- ->where('pt.action_type', "inception");
-
- // Apply filters if parameters are provided
- if (!empty($client_type)) {
- $query->where('c.client_type', $client_type);
- }
- if (!empty($client)) {
- $query->where('pt.client_id', $client);
- }
- if (!empty($issuer)) { // Corrected condition to check $issuer
- $query->where('pt.issuer', $issuer);
- }
-
- $query->groupBy('pt.id');
- $query->orderBy('pt.id', 'DESC');
- // Fetch and return results
- $results = $query->get()->getResultArray();
- // print($this->db->getLastQuery()); die;
- return $results;
- }
-
- public function getBDSRenewalData()
- {
- // Increase GROUP_CONCAT limit
- $this->db->query("SET SESSION group_concat_max_len = 1000000;");
-
- $builder = $this->db->table('policy_transaction pt');
-
- $builder->select([
- 'SUM(CASE WHEN pt.policy_end_date < CURDATE() THEN 1 ELSE 0 END) AS Expired',
- 'SUM(CASE WHEN pt.policy_end_date BETWEEN CURDATE() AND (CURDATE() + INTERVAL 1 MONTH) THEN 1 ELSE 0 END) AS `Renewal Pending`',
- 'GROUP_CONCAT(CASE WHEN pt.policy_end_date < CURDATE() THEN pt.id ELSE NULL END) AS Expired_ids',
- 'GROUP_CONCAT(CASE WHEN pt.policy_end_date BETWEEN CURDATE() AND (CURDATE() + INTERVAL 1 MONTH) THEN pt.id ELSE NULL END) AS Renewal_Pending_ids'
- ]);
- $builder->where("pt.policy_end_date IS NOT NULL", null, false);
- $builder->where('pt.is_active', 1);
-
- // Self join to check if a policy has been renewed
- $builder->join('policy_transaction renewed', 'renewed.source_client_policy_id = pt.client_policy_id and renewed.client_id = pt.client_id and renewed.client_branch_id = pt.client_branch_id', 'left');
-
- // Filter for expired or expiring policies
- $builder->where("(pt.policy_end_date < CURDATE() OR pt.policy_end_date BETWEEN CURDATE() AND (CURDATE() + INTERVAL 1 MONTH))", null, false);
-
- $builder->where('renewed.id IS NULL', null, false);
- $query = $builder->get();
- $result = $query->getResultArray();
-
- $total = 0;
- foreach ($result[0] as $key => $value) {
- if ($key !== 'Expired_ids' && $key !== 'Renewal_Pending_ids') {
- $total += $value;
+ // ==============================
+ // ROLE-BASED FILTERS
+ // ==============================
+ if (
+ (!in_array(get_role_id(), [1, 5])) &&
+ !(
+ in_array(MANAGEMENT_TEAM_ID, user_team()) ||
+ in_array(FINANCE_TEAM_ID, user_team()) ||
+ in_array(BUSINESS_TEAM_ID, user_team())
+ )
+ ) {
+ if (get_role_id() == 4 && in_array(POS_TEAM_ID, user_team())) {
+ $builder2->where('policy_transaction.created_by', get_session_userid());
+ }
}
+
+ // ==============================
+ // ADDITIONAL FILTERS
+ // ==============================
+ if (!empty($where)) {
+ log_message('info', 'Where condition: ' . json_encode($where));
+ $builder2->where($where);
+ }
+
+ if ($start_date != 0 && $end_date != 0 && $date_type != 0 && $date_type != 'statement_month') {
+ $startDate = date('Y-m-d 00:00:00', strtotime($start_date));
+ $endDate = date('Y-m-d 23:59:59', strtotime($end_date));
+
+ $builder2->where("policy_transaction.{$date_type} >=", $startDate)
+ ->where("policy_transaction.{$date_type} <=", $endDate);
+ }
+
+
+ // ==============================
+ // FILTER BY IDs
+ // ==============================
+ if ($client_id != 0) $builder2->where('policy_transaction.client_id', $client_id);
+ if ($insurer_id != 0) $builder2->where('policy_transaction.insurer_id', $insurer_id);
+ if ($client_branch_id != 0) $builder2->where('policy_transaction.client_branch_id', $client_branch_id);
+ if ($insurer_branch_id != 0) $builder2->where('policy_transaction.insurer_branch_id', $insurer_branch_id);
+ if ($client_policy_id != 0) $builder2->where('policy_transaction.client_policy_id', $client_policy_id);
+ if ($user_id != 0) $builder2->where('policy_transaction.created_by', $user_id);
+ if ($policy_type_id != 0) $builder2->where('client_policy.policy_type_id', $policy_type_id);
+ if ($issuer != 0) $builder2->where('policy_transaction.issuer', $issuer);
+
+ // ==============================
+ // DEFAULT 90-DAY FILTER
+ // ==============================
+ if (
+ $client_id == 0 &&
+ $insurer_id == 0 &&
+ $policy_type_id == 0 &&
+ $date_type == 0 &&
+ $issuer == 0
+ ) {
+ $fromDate = date('Y-m-d', strtotime('-90 days'));
+ $toDate = date('Y-m-d 23:59:59');
+
+ if (empty($where)) {
+ $builder2->where('policy_transaction.created_at >=', $fromDate)
+ ->where('policy_transaction.created_at <=', $toDate);
+ }
+ }
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ // ==============================
+ // With Statement Upload
+ // ==============================
+
+ $builder = $this->db->table('policy_transaction')
+ ->select("
+ policy_transaction.id AS id,
+ policy_transaction.endorsement_no AS endorsement_no,
+ policy_transaction.ref AS ref,
+ DATE_FORMAT(policy_transaction.policy_issue_date, '%d %b %Y') AS policy_issue_date,
+ DATE_FORMAT(
+ IF(insurer_statements_oq.month IS NULL,
+ policy_transaction.policy_issue_date,
+ insurer_statements_oq.month
+ ), '%b %Y'
+ ) AS policy_issue_month,
+
+ CASE
+ WHEN insurer_statements_oq.month IS NULL THEN 'no statement uploaded'
+ ELSE 'statement uploaded'
+ END AS statement_uploaded ,
+
+
+ CASE
+ WHEN clients.client_type = 1 THEN 'Group'
+ WHEN clients.client_type = 2 THEN 'Retail'
+ ELSE '-'
+ END AS client_type,
+
+ CASE
+ WHEN policy_transaction.revenue_type = 'NA' THEN 'Fresh'
+ ELSE 'Renewal'
+ END AS revenue_type,
+
+ CASE
+ WHEN policy_transaction.action_type = 'inception' THEN 'Policy'
+ ELSE 'Endorsement'
+ END AS action_type,
+
+ clients.client_name AS client_name,
+ clients.short_name AS client_short_name,
+ client_branch.branch_name AS client_branch_name,
+ client_branch.address1 AS client_address,
+ policy_type.policy_type,
+ policy_type.bap,
+ insurers.name AS insurer_name,
+ insurers.short_name AS insurer_short_name,
+ insurer_branch.branch_name AS insurer_branch_name,
+ insurer_branch.branch_code AS insurer_branch_code,
+ user_profiles.first_name AS user_name,
+ vehicle.vehicle_no,
+ tpa.name AS tpa_name,
+ pt_co_share_details.remark AS remarks,
+ pt_co_share_details.cop_amt AS bp_amt,
+ pt_co_share_details.exp_amt,
+ pt_co_share_details.id AS pt_id,
+ sales_user.first_name AS salse_person_name,
+ service_user.first_name AS service_person_name,
+
+ ROUND(pt_co_share_details.cop_amt + pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt, 2) AS premium_wo_gst,
+ ROUND((ROUND(pt_co_share_details.cop_amt + pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt, 2) * 18 / 100), 2) AS gst_amount,
+ ROUND(
+ ROUND(pt_co_share_details.cop_amt + pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt, 2) +
+ ROUND((ROUND(pt_co_share_details.cop_amt + pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt, 2) * 18 / 100), 2),
+ 2) AS total_premium,
+
+ ROUND(pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt, 2) AS tp_or_ter,
+ DATEDIFF(policy_transaction.policy_end_date, CURDATE()) AS days,
+ (pt_co_share_details.agreed_tp_per + pt_co_share_details.agreed_tep_per) AS agreed_tp_or_ter_per,
+ pt_co_share_details.agreed_bp_per,
+
+ -- ==============================
+ -- SUBQUERY: Total IRDA Amount
+ -- Alias Agreed Amount ...!!
+ -- ==============================
+ ROUND(pt_co_share_details.exp_amt, 2) AS total_irda_amt,
+ -- Reward Only
+ ROUND((
+ SELECT SUM(co_share_stmt_details.reward)
+ FROM co_share_stmt_details
+ JOIN insurer_statements ON co_share_stmt_details.statement_id = insurer_statements.id
+ WHERE co_share_stmt_details.co_share_id = pt_co_share_details.id
+ AND co_share_stmt_details.is_active = 1
+ AND insurer_statements.is_active = 1
+ AND insurer_statements.month = insurer_statements_oq.month
+ {$date_condition}
+ GROUP BY('policy_transaction.policy_no , insurer_statements.month , pt_co_share_details.insurer_id')
+ ), 2) AS reward,
+
+ -- Billed Amount
+ ROUND((
+ SELECT SUM(
+ COALESCE(co_share_stmt_details.actual_bp_brokerage_amt, 0) +
+ COALESCE(co_share_stmt_details.actual_tp_brokerage_amt, 0) +
+ COALESCE(co_share_stmt_details.actual_tep_brokerage_amt, 0) +
+ COALESCE(co_share_stmt_details.reward, 0)
+ )
+ FROM co_share_stmt_details
+ JOIN pt_co_share_details AS pt_table ON co_share_stmt_details.co_share_id = pt_table.id
+ JOIN insurer_statements ON co_share_stmt_details.statement_id = insurer_statements.id
+ WHERE co_share_stmt_details.co_share_id = pt_co_share_details.id
+ AND co_share_stmt_details.is_active = 1
+ AND pt_table.is_active = 1
+ AND insurer_statements.is_active = 1
+ AND insurer_statements.invoice_status IS NOT NULL
+ AND insurer_statements.month = insurer_statements_oq.month
+ {$date_condition}
+ GROUP BY('policy_transaction.policy_no , insurer_statements.month , pt_co_share_details.insurer_id')
+ ), 2) AS billed_amt,
+
+ created_user.first_name AS user_name,
+
+ CASE
+ WHEN pt_co_share_details.co_share_type IN (0, 1) THEN policy_transaction.policy_no
+ WHEN pt_co_share_details.co_share_type > 1 THEN
+ CASE
+ WHEN pt_co_share_details.follower_policy_no IS NULL OR pt_co_share_details.follower_policy_no = ''
+ THEN policy_transaction.policy_no
+ ELSE pt_co_share_details.follower_policy_no
+ END
+ ELSE policy_transaction.policy_no
+ END AS policy_no
+ ")
+
+ // ==============================
+ // JOINS
+ // ==============================
+ ->join('pt_co_share_details', 'policy_transaction.id = pt_co_share_details.pt_id', 'left')
+ ->join('clients', 'clients.id = policy_transaction.client_id')
+ ->join('client_branch', 'policy_transaction.client_branch_id = client_branch.id', 'left')
+ ->join('client_policy', 'policy_transaction.client_policy_id = client_policy.id', 'left')
+ ->join('user_profiles', 'policy_transaction.created_by = user_profiles.id', 'left')
+ ->join('vehicle', 'policy_transaction.vehicle_id = vehicle.id', 'left')
+ ->join('policy_type', 'policy_transaction.policy_type_id = policy_type.id', 'left')
+ ->join('insurers', 'pt_co_share_details.insurer_id = insurers.id', 'left')
+ ->join('insurer_branch', 'pt_co_share_details.insurer_branch_id = insurer_branch.id', 'left')
+ ->join('tpa', 'policy_transaction.tpa_id = tpa.id', 'left')
+ ->join('tpa_branch', 'policy_transaction.tpa_branch_id = tpa_branch.id', 'left')
+ ->join('user_profiles AS sales_user', 'policy_transaction.sales_generated_by = sales_user.id', 'left')
+ ->join('user_profiles AS service_user', 'policy_transaction.serviced_by = service_user.id', 'left')
+ ->join('user_profiles AS created_user', 'policy_transaction.created_by = created_user.id', 'left')
+
+
+ ->join('co_share_stmt_details', 'pt_co_share_details.id = co_share_stmt_details.co_share_id','left')
+ ->join('insurer_statements insurer_statements_oq','insurer_statements_oq.id = co_share_stmt_details.statement_id','left')
+
+ ->where('policy_transaction.is_active', 1)
+ ->where('pt_co_share_details.is_active', 1)
+ ->where('co_share_stmt_details.is_active', 1)
+ ->where('insurer_statements_oq.is_active', 1)
+ ->where('insurer_statements_oq.id IS NOT NULL')
+
+
+ // ========================================================
+ // GROUP BY Insurer Statement Months
+ // =======================================================
+ ->groupBy('policy_transaction.policy_no , pt_co_share_details.insurer_id ,insurer_statements_oq.month');
+
+ // ==============================
+ // ROLE-BASED FILTERS
+ // ==============================
+ if (
+ (!in_array(get_role_id(), [1, 5])) &&
+ !(
+ in_array(MANAGEMENT_TEAM_ID, user_team()) ||
+ in_array(FINANCE_TEAM_ID, user_team()) ||
+ in_array(BUSINESS_TEAM_ID, user_team())
+ )
+ ) {
+ if (get_role_id() == 4 && in_array(POS_TEAM_ID, user_team())) {
+ $builder->where('policy_transaction.created_by', get_session_userid());
+ }
+ }
+
+ // ==============================
+ // ADDITIONAL FILTERS
+ // ==============================
+ if (!empty($where)) {
+ log_message('info', 'Where condition: ' . json_encode($where));
+ $builder->where($where);
+ }
+
+ if ($start_date != 0 && $end_date != 0 && $date_type != 0 && $date_type != 'statement_month') {
+ $startDate = date('Y-m-d 00:00:00', strtotime($start_date));
+ $endDate = date('Y-m-d 23:59:59', strtotime($end_date));
+
+ $builder->where("policy_transaction.{$date_type} >=", $startDate)
+ ->where("policy_transaction.{$date_type} <=", $endDate);
+ }
+
+ // JOIN FOR STATEMENT MONTH FILTER
+ if ($date_type == 'statement_month' && $start_date != 0 && $end_date != 0) {
+ $startDate = date('Y-m-d', strtotime($start_date));
+ $endDate = date('Y-m-d', strtotime($end_date));
+
+ $builder->join('co_share_stmt_details cssdfilter', 'pt_co_share_details.id = cssdfilter.co_share_id', 'left')
+ ->join('insurer_statements', 'cssdfilter.statement_id = insurer_statements.id', 'left')
+ ->where('insurer_statements.is_active', 1)
+ ->where('insurer_statements.month >=', $startDate)
+ ->where('insurer_statements.month <=', $endDate)
+ ->groupBy('cssdfilter.co_share_id');
+ }
+
+ // ==============================
+ // FILTER BY IDs
+ // ==============================
+ if ($client_id != 0) $builder->where('policy_transaction.client_id', $client_id);
+ if ($insurer_id != 0) $builder->where('policy_transaction.insurer_id', $insurer_id);
+ if ($client_branch_id != 0) $builder->where('policy_transaction.client_branch_id', $client_branch_id);
+ if ($insurer_branch_id != 0) $builder->where('policy_transaction.insurer_branch_id', $insurer_branch_id);
+ if ($client_policy_id != 0) $builder->where('policy_transaction.client_policy_id', $client_policy_id);
+ if ($user_id != 0) $builder->where('policy_transaction.created_by', $user_id);
+ if ($policy_type_id != 0) $builder->where('client_policy.policy_type_id', $policy_type_id);
+ if ($issuer != 0) $builder->where('policy_transaction.issuer', $issuer);
+
+ // ==============================
+ // DEFAULT 90-DAY FILTER
+ // ==============================
+ if (
+ $client_id == 0 &&
+ $insurer_id == 0 &&
+ $policy_type_id == 0 &&
+ $date_type == 0 &&
+ $issuer == 0
+ ) {
+ $fromDate = date('Y-m-d', strtotime('-90 days'));
+ $toDate = date('Y-m-d 23:59:59');
+
+ if (empty($where)) {
+ $builder->where('policy_transaction.created_at >=', $fromDate)
+ ->where('policy_transaction.created_at <=', $toDate);
+ }
+ }
+
+
+
+
+
+ $sql1 = $builder2->getCompiledSelect();
+ $sql2 = $builder->getCompiledSelect();
+
+ $finalSql = "($sql1) UNION ALL ($sql2)
+ ORDER BY policy_no DESC, insurer_branch_name ASC, statement_uploaded ASC,
+ STR_TO_DATE(policy_issue_month, '%b %Y') ASC";
+
+
+ $result = $this->db->query($finalSql)->getResultArray();
+
+ return $result;
+
}
- // Ensure ID fields are arrays (not null)
- $result[0]['Expired_ids'] = $result[0]['Expired_ids'] ? $result[0]['Expired_ids'] : [];
- $result[0]['Renewal Pending_ids'] = $result[0]['Renewal_Pending_ids'] ? $result[0]['Renewal_Pending_ids'] : [];
- // Add total count
- $result[0]['total'] = $total;
+
+
- return $result[0];
}
-}
diff --git a/app/Models/RTOModel.php b/app/Models/RTOModel.php
new file mode 100644
index 00000000..6f5abcab
--- /dev/null
+++ b/app/Models/RTOModel.php
@@ -0,0 +1,57 @@
+
-
|
+
+
+
+ |
+
+
+ |
+