diff --git a/app/Config/Autoload.php b/app/Config/Autoload.php index c80f6c1c..a1a4356c 100755 --- a/app/Config/Autoload.php +++ b/app/Config/Autoload.php @@ -47,7 +47,8 @@ class Autoload extends AutoloadConfig public $psr4 = [ APP_NAMESPACE => APPPATH, // For custom app namespace 'Config' => APPPATH . 'Config', - 'Helpers' => APPPATH . 'Helpers' + 'Helpers' => APPPATH . 'Helpers', + 'App\\Libraries' => APPPATH . 'Libraries', ]; /** @@ -99,5 +100,5 @@ class Autoload extends AutoloadConfig * @var string[] * @phpstan-var list */ - public $helpers = ['uuid','session','utility', 'form', 'url', 'oauth', 'fileupload', 'excel_import_export', 'file', 'drive','ExcelSanitizeHelper']; + public $helpers = ['uuid','session','utility', 'form', 'url', 'oauth', 'fileupload', 'excel_import_export', 'file', 'drive','ExcelSanitizeHelper', 'api_helper']; } diff --git a/app/Config/Database.php b/app/Config/Database.php index 1a43584f..b0c2a6e3 100755 --- a/app/Config/Database.php +++ b/app/Config/Database.php @@ -74,6 +74,21 @@ class Database extends Config 'busyTimeout' => 1000, ]; + public $preDB = [ + 'DSN' => '', + 'hostname' => 'localhost', + 'username' => 'root', + 'password' => 'root', + 'database' => 'other_db', + 'DBDriver' => 'MySQLi', + 'DBPrefix' => '', + 'pConnect' => false, + 'DBDebug' => (ENVIRONMENT !== 'production'), + 'charset' => 'utf8', + 'DBCollat' => 'utf8_general_ci', + ]; + + public function __construct() { parent::__construct(); diff --git a/app/Config/Routes.php b/app/Config/Routes.php index 80a25075..a6cef1ed 100755 --- a/app/Config/Routes.php +++ b/app/Config/Routes.php @@ -358,6 +358,8 @@ $routes->group("/util", ["filter" => "authMVC"], function ($routes) { $routes->get('getPolicyTypeFields', 'LeadsController::getPolicyTypeFields'); $routes->get('removeMultiFile', 'LeadsController::removeMultiFile'); $routes->get('removeInstallments', 'LeadsController::removeInstallments'); + $routes->get('viewHrAccessData', 'ClientController::viewHrAccessData'); + $routes->post('saveHrAccessData', 'ClientController::saveHrAccessData'); }); $routes->post("policy_tranction/sendInstallmentRemainderMail","PolicyTransactionController::sendInstallmentRemainderMail"); @@ -458,6 +460,7 @@ $routes->post("/employeeRest/checkMpin", "RestAuthenticationController::checkMpi $routes->post("/employeeRest/verifyEmployeeEmailId", "RestAuthenticationController::verifyEmployeeWithEmailId"); $routes->post("/employeeRest/updateEmpOTP", "RestAuthenticationController::updateEmpOTP"); $routes->post("/employeeRest/updateEmpMPIN", "RestAuthenticationController::updateEmpMPIN"); +$routes->post("employeeRest/forgotMPIN", "RestAuthenticationController::forgotMPIN"); // $routes->post("/employeeRest/saveMpin", "RestAuthenticationController::saveMpin"); @@ -466,6 +469,7 @@ $routes->post("/employeeRest/verifyHrWithMobileNumber", "RestAuthenticationContr $routes->post("/employeeRest/verifyHrWithEmail", "RestAuthenticationController::verifyHrWithEmail"); $routes->post("/employeeRest/getVerifiedHrData", "RestAuthenticationController::getVerifiedHrData"); $routes->post("/employeeRest/updateHROTP", "RestAuthenticationController::updateHROTP"); +$routes->get("/employeeRest/getHRAccessData", "RestAuthenticationController::getHRAccessData"); // Test initiate Claim $routes->post('initiateClaim',"EmployeeRestController::initiateClaim"); @@ -484,11 +488,9 @@ $routes->group("/api", ["filter" => "authJWT"], function ($routes) { $routes->post("employeeRest/saveMpin", "RestAuthenticationController::saveMpin"); $routes->post("employeeRest/updateMpin", "RestAuthenticationController::updateMpin"); +$routes->post("employeeRest/getPostEmployeeDataForAuth", "RestAuthenticationController::getPostEmployeeDataForAuth"); - -$routes->get("getEmployeePolicy", "EmployeeRestController::getEmployeePolicy"); -$routes->get("getAddOnPolicy", "EmployeeRestController::getAddOnPolicy"); $routes->group("employeeRest", ["filter" => "authJWT"], function ($routes) { $routes->post("getVerifiedUserData", "RestAuthenticationController::getVerifiedUserData"); @@ -517,13 +519,6 @@ $routes->group("employeeRest", ["filter" => "authJWT"], function ($routes) { $routes->get("exportDataByClientPolicyId", "EmployeeRestController::exportDataByClientPolicyId"); - $routes->get("getPolicyLevelEmployeeSummaryData", "EmployeeRestController::getPolicyLevelEmployeeSummaryData"); - $routes->get("cdSummaryData", "EmployeeRestController::cdSummaryData"); - $routes->get("cdTransactionData", "EmployeeRestController::cdTransactionData"); - $routes->match( ['get', 'post'], 'claimsSearch','EmployeeRestController::claimsSearch'); - $routes->get("claimView", "EmployeeRestController::claimView"); - $routes->get("exportCashDepositData", "EmployeeRestController::exportCashDepositData"); - $routes->get("removeEmpAndEmpPolicyData", "EmployeeRestController::removeEmpAndEmpPolicyData"); $routes->post("calculatePremium", "EmployeeRestController::calculatePremium"); @@ -535,10 +530,22 @@ $routes->group("employeeRest", ["filter" => "authJWT"], function ($routes) { $routes->get("getWellnessURL", "EmployeeRestController::getWellnessURL"); //$routes->post('postDataForTicket',"EmployeeRestController::postDataForTicket"); + + //hr api's + $routes->get("getPolicyLevelEmployeeSummaryData", "EmployeeRestController::getPolicyLevelEmployeeSummaryData"); + $routes->get("cdSummaryData", "EmployeeRestController::cdSummaryData"); + $routes->get("cdTransactionData", "EmployeeRestController::cdTransactionData"); + $routes->match( ['get', 'post'], 'claimsSearch','EmployeeRestController::claimsSearch'); + $routes->get("claimView", "EmployeeRestController::claimView"); + $routes->get("exportCashDepositData", "EmployeeRestController::exportCashDepositData"); + }); $routes->get("getEmployeeActiveOrInactivePolicy", "EmployeeRestController::getEmployeeActiveOrInactivePolicy"); $routes->get("sendPushNotification", "EmployeeRestController::sendPushNotification"); $routes->post("sendEmail", "EmployeeRestController::send_email"); +$routes->get("getPolicyLevelEmployeeSummaryData", "EmployeeRestController::getPolicyLevelEmployeeSummaryData"); +$routes->get("cdTransactionData", "EmployeeRestController::cdTransactionData"); +$routes->match( ['get', 'post'], 'claimsSearch','EmployeeRestController::claimsSearch'); $routes->get("getBackToEnrolledDetails", "EmployeeRestController::getBackToEnrolledDetails"); @@ -590,3 +597,14 @@ $routes->post("dispatchWebhookData/(:any)/(:any)",'ClientWebHooksController::pus $routes->post("retrieveWebhookDataEmp","ClientWebHooksController::pullData_emp"); $routes->post("retrieveWebhookDataClaim","ClientWebHooksController::pullData_claim"); + + + +//Third party Api Call + +$routes->get('generateAuthToken','ICICILombardController::generateAuthToken'); +$routes->get('createEnrollmentBatch','ICICILombardController::createEnrollmentBatch'); +$routes->get('getEnrollmentBatchStatus','ICICILombardController::getEnrollmentBatchStatus'); +$routes->get('fetchUHIDDetails','ICICILombardController::fetchUHIDDetails'); + +$routes->get('testTracelog','TestBusinessController::a'); \ No newline at end of file diff --git a/app/Controllers/ClientController.php b/app/Controllers/ClientController.php index be5f2664..a1eb3002 100755 --- a/app/Controllers/ClientController.php +++ b/app/Controllers/ClientController.php @@ -41,6 +41,7 @@ use App\Models\PolicyTransactionStatusModel; use App\Models\VehicleModel; use App\Models\LeadsModel; use App\Models\ClientApiModel; +use App\Models\HRAccessControlModel; use App\Controllers\EmpDataServiceController; use App\Controllers\GoogleDriveController; @@ -88,6 +89,7 @@ class ClientController extends AdminController protected $leadsModel; protected $clientApi; protected $PTCOShareDetailsModel; + protected $HRAccessControlModel; public function __construct() @@ -125,6 +127,7 @@ class ClientController extends AdminController $this->leadsModel = new LeadsModel(); $this->clientApi = new ClientApiModel(); $this->PTCOShareDetailsModel = new PTCOShareDetailsModel(); + $this->HRAccessControlModel = new HRAccessControlModel(); } //-------------------------------------------------------------------------------------------------------- @@ -618,12 +621,14 @@ class ClientController extends AdminController } // In your controller - public function deposit($id = null , $requestFrom = null ) + public function deposit($id = null , $requestFrom = null , $policyId = null) { + $headerData['page_name'] = 'Client Deposit'; - + $data['clientName'] = $this->clientModel->where('id', $id)->find(); - $data['clientData'] = $this->clientPolicyModel->getinsurerswithclientid($id); + $data['clientData'] = $this->clientPolicyModel->getinsurerswithclientid($id,$policyId); + $data['depositsummary'] = $this->clientPolicyModel->getDepositlistsummary($id); // Fetch associated insurer names and balances @@ -672,7 +677,7 @@ class ClientController extends AdminController } $data['insurerName'] = $this->insurerModel->getInsurerName($insurerId, $clientId); - $data['depositdata'] = $this->clientPolicyModel->getdepositData($clientId, $insurerId, $cd_ac_pk); + $data['depositdata'] = $this->clientPolicyModel->getdepositData($clientId, $insurerId, $cd_ac_pk, $subTypeOptions); $data['clientData'] = $this->clientPolicyModel->getClientById($clientId); $data['deposiamount'] = $this->clientPolicyModel->getDepositSummary($clientId, $insurerId, $cd_ac_pk); $data['cd_ac_pk'] = $cd_ac_pk; @@ -1029,19 +1034,9 @@ class ClientController extends AdminController $insert = $this->clientBranchModel->insert($data); if ($insert) { - for ($i = 0; $i < count($this->request->getPost('name')); $i++) { - // Prepare data to insert - $data = [ - 'contact_type' => 'client', - 'ref_id' => $insert, - 'created_by' => get_session_userid(), - 'name' => $this->request->getPost('name')[$i], - 'email' => $this->request->getPost('email')[$i], - 'mobile' => $this->request->getPost('mobile')[$i], - 'designation' => $this->request->getPost('designation')[$i] - ]; - $contacts = $this->levelContactModel->insert($data); - } + $level_contact_data = $this->request->getPost('level_contect_data'); + $level_contact_data = !empty($level_contact_data) ? json_decode($level_contact_data, true) : null; + $this->saveLevelContacts($level_contact_data, $insert); } if ($insert) { @@ -1133,19 +1128,9 @@ class ClientController extends AdminController if ($insert) { - $this->levelContactModel->where('ref_id', $id)->where('contact_type', 'client')->delete(); - for ($i = 0; $i < count($this->request->getPost('name')); $i++) { - $data = [ - 'contact_type' => 'client', - 'ref_id' => $id, - 'updated_by' => get_session_userid(), - 'name' => $this->request->getPost('name')[$i], - 'email' => $this->request->getPost('email')[$i], - 'mobile' => $this->request->getPost('mobile')[$i], - 'designation' => $this->request->getPost('designation')[$i] - ]; - $contacts = $this->levelContactModel->insert($data); - } + $level_contact_data = $this->request->getPost('level_contect_data'); + $level_contact_data = !empty($level_contact_data) ? json_decode($level_contact_data, true) : null; + $this->saveLevelContacts($level_contact_data, $id); } if ($insert) { @@ -1159,7 +1144,8 @@ class ClientController extends AdminController 'list_of_branch_units' => $list_of_branch_units, 'total_count' => $total_count, 'uncommonValues' => $uncommonValues, - 'message' => 'Client branch updated successfully' + 'message' => 'Client branch updated successfully', + 'response_data' => $this->request->getPost() ], 200); } else { @@ -1167,6 +1153,24 @@ class ClientController extends AdminController } } + public function saveLevelContacts($level_contact_data, $branch_id) + { + if (!empty($level_contact_data) && is_array($level_contact_data)) { + foreach ($level_contact_data as $value) { + if (!empty($value['id'])) { + $id = $value['id']; + unset($value['id']); + $this->levelContactModel->update($id, $value); + } else { + unset($value['id']); + $value['contact_type'] = "client"; + $value['ref_id'] = $branch_id ?? null; + $this->levelContactModel->insert($value); + } + } + } + } + public function createClientPolicy() @@ -4223,24 +4227,64 @@ class ClientController extends AdminController } public function get_client_policy_data_using_policy_no() - { + { + $received_data = $this->request->getGet(); $policy_no = $this->request->getGet('policy_no'); + $client_id = $this->request->getGet('client_id'); + $client_branch_id = $this->request->getGet('client_branch_id'); + $policy_type_id = $this->request->getGet('policy_type_id'); + $client_type = $this->request->getGet('client_type'); + $data = $this->clientPolicyModel ->select(" client_policy.*, + policy_type.policy_type, clients.client_type, + clients.client_name, 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('clients', 'client_policy.client_id = clients.id') + ->join('policy_type', 'client_policy.policy_type_id = policy_type.id') ->where('client_policy.policy_no', $policy_no) ->where('client_policy.is_active', 1) + ->where('client_policy.policy_status', 1) ->first(); if ($data) { - return $this->respond(['status' => true, 'data' => $data, 'code' => 200], 200); + + if ($client_type == 1) { + if ($data['client_id'] == $client_id && $data['client_branch_id'] == $client_branch_id) { + + if ($data['policy_type_id'] == $policy_type_id) { + return $this->respond(['status' => true, 'data' => $data, 'code' => 200, 'received_data' => $received_data], 200); + } else { + $policy_type = $this->policyTypeModel->where('id', $policy_type_id)->first(); + $message = 'This policy number is mapped to the selected client with policy type: ' . (!empty($data['policy_type']) ? $data['policy_type'] : 'N/A') . '. You selected: ' . (!empty($policy_type['policy_type']) ? $policy_type['policy_type'] : 'N/A') . '. Please check.'; + return $this->respond(['status' => true, 'data' => $data, 'code' => 409, "message" => $message, 'received_data' => $received_data], 200); + } + } else { + $message = 'This policy number is already linked to another client' . (!empty($data['client_name']) ? '. Client name : ' . $data['client_name'] : '') . '. Please check'; + return $this->respond(['status' => true, 'code' => 409, "message" => $message, 'received_data' => $received_data, 'db_data' => $data], 200); + } + } else { + if ($data['client_id'] == $client_id) { + + if ($data['policy_type_id'] == $policy_type_id) { + return $this->respond(['status' => true, 'data' => $data, 'code' => 200, 'received_data' => $received_data], 200); + } else { + $policy_type = $this->policyTypeModel->where('id', $policy_type_id)->first(); + $message = 'This policy number is mapped to the selected client with policy type: ' . (!empty($data['policy_type']) ? $data['policy_type'] : 'N/A') . '. You selected: ' . (!empty($policy_type['policy_type']) ? $policy_type['policy_type'] : 'N/A') . '. Please check.'; + return $this->respond(['status' => true, 'data' => $data, 'code' => 409, "message" => $message, 'received_data' => $received_data], 200); + } + } else { + $message = 'This policy number is already linked to another client' . (!empty($data['client_name']) ? '. Client name : ' . $data['client_name'] : '') . '. Please check'; + return $this->respond(['status' => true, 'code' => 409, "message" => $message, 'received_data' => $received_data, 'db_data' => $data], 200); + } + } + } else { - return $this->respond(['status' => false, 'message' => 'No Data Found', 'code' => 404], 200); + return $this->respond(['status' => false, 'message' => 'No Data Found', 'code' => 404, 'received_data' => $received_data], 200); } } @@ -4827,7 +4871,7 @@ class ClientController extends AdminController // ---------- EMP SERVICE CONTROLLER -------------------------------------------------------------------------------- $employeeRestController = new EmployeeServiceController(); - // $employeeRestController->excelFileDataValidation(['file_id' => 823]); + // $employeeRestController->excelFileDataValidation(['file_id' => 1629]); die; // $employeeRestController->employeesOnboardPreprocess(['file_id' => 726]); // $employeeRestController->employeesOnboardProcess(['file_id' => 835]); // $employeeRestController->employeesEnrollmentInsert(['file_id' => 836]); @@ -4846,18 +4890,20 @@ class ClientController extends AdminController // ----------EMP DATA SERVICE CONTROLLER-------------------------------------------------------------------------------- + $batch_data = [ + 'client_id' => 97, + 'client_policy_id' => 6174, + 'client_branch_id' => 73, + 'insurer_or_tpa' => "insurer", + 'event_type' => "deletion", + 'actions' => "export", + 'file_name' => "deletion_enhancement_test_file.xlsx", + ]; + // $batch_data = [ // 'client_id' => 29, - // 'client_policy_id' => 17, - // 'client_branch_id' => 15, - // 'insurer_or_tpa' => "insurer", - // 'event_type' => "deletion", - // ]; - - // $batch_data = [ - // 'client_id' => 89, - // 'client_policy_id' => 328, - // 'client_branch_id' => 88, + // 'client_policy_id' => 77, + // 'client_branch_id' => 45, // 'insurer_or_tpa' => "insurer", // // 'insurer_or_tpa' => "tpa", // 'event_type' => "si_enhancement", @@ -4878,11 +4924,12 @@ class ClientController extends AdminController // $EmpDataServiceController->sendMailForDownloadingECard($ids); $EmpDataServiceController = new EmpDataServiceController(); + // $return = $EmpDataServiceController->generateExcelForDeletion($batch_data); dd($return); die; // $EmpDataServiceController->generateExcelForSIEnhancement($batch_data); die; // $EmpDataServiceController->importInceptionFileValidation(['file_id' => 1932]); die; // $EmpDataServiceController->importDeletionValidation(['file_id' => 304]); //for live // $EmpDataServiceController->importSIEnhancementUpdateEndorsementID(['file_id' => 1199]); //for live - // $EmpDataServiceController->importSIEnhancementValidation(['file_id' => 1205]); //for live + // $result = $EmpDataServiceController->importSIEnhancementValidation(['file_id' => 2496]); //for live // $EmpDataServiceController->importInceptionUpdateTPAandUHID(['file_id' => 214]); //for live // $result = $this->employeePolicyModel->getDeletionEmployeeDataForExportExcel($batch_data); @@ -5060,6 +5107,24 @@ class ClientController extends AdminController // $return_value = check_cd_entry_exist($baseWhere); // dd($return_value); + + + + // $param = 9715454901; + // $type = 'emp_code'; + // $client_policy_id = 64; + // $client_id = 3927; + + // $result = $this->getTheEmpDataForClaimSearchByMobile($param, $type, $client_policy_id, $client_id); + // $result = $this->employeePolicyModel->getEmployeePolicy(); + // $result = $this->getHrAccessData($client_id); + // $html = view('hr_access_controll', $result); + // dd($html); + + // $employeeRestController = new EmployeeRestController(); + // $result = $employeeRestController->getPreEmployeePolicyCount($param, $client_id); + // dd($result); + } // ------------------------------------------------------------------------------------------------------- @@ -5154,7 +5219,8 @@ class ClientController extends AdminController ->where('employees.relationship', "Self") ->where('employee_polices.is_active', 1) ->where('client_policy.id', $param) - ->findAll(); + ->get() + ->getResultArray(); $dataForClientAndInsurer = $this->clientPolicyModel ->select(" @@ -5263,7 +5329,7 @@ class ClientController extends AdminController if(!empty($data) && count($data) > 0){ - $memberData = $this->employeeModel->getEmployeeByEmployeeCode($data['emp_code'], $data['policy_id'], $client_id); + $memberData = $this->employeeModel->getEmployeeByEmployeeCode($data['emp_code'], $client_policy_id, $client_id); $acms_datas = $this->employeeModel->getAcmUsingClientID($data['client_id']); // if(!empty($acms_datas)){ // $acms = $acms_datas; @@ -5768,7 +5834,8 @@ class ClientController extends AdminController return $id; } - private function reorderProposalsByInsurerTotal(array $data): array { + private function reorderProposalsByInsurerTotal(array $data): array + { Kint::dump($data); if (!isset($data['premium_data']['data'])) return $data; @@ -5831,7 +5898,8 @@ class ClientController extends AdminController return $data; } - private function reorderProposalDataByPremiumOrder(array $data): array { + private function reorderProposalDataByPremiumOrder(array $data): array + { if (!isset($data['premium_data']['data'], $data['proposal_data']['over_all_column_data'])) { return $data; } @@ -5853,7 +5921,8 @@ class ClientController extends AdminController return $data; } - private function reorderProposalInHeaderAndData(array $data): array { + private function reorderProposalInHeaderAndData(array $data): array + { // Kint::dump($data); $tableData = $data['table_data']; @@ -5953,7 +6022,8 @@ class ClientController extends AdminController return $data; } - private function renumberProposalKeys(array $input): array { + private function renumberProposalKeys(array $input): array + { $result = []; $counter = 1; @@ -5968,7 +6038,9 @@ class ClientController extends AdminController return $result; } - public function saveApiData(){ + + public function saveApiData() + { $receivedData = $this->request->getPost(); @@ -5988,7 +6060,8 @@ class ClientController extends AdminController } - public function sendToken(){ + public function sendToken() + { $client_id = $this->request->getGet('client_id'); @@ -6001,6 +6074,345 @@ class ClientController extends AdminController } } + // --------------------------------------------------------------------------------------------------- + + public function viewHrAccessData() + { + $client_id = $this->request->getGet('client_id'); + $data = $this->getHrAccessData($client_id); + // $data = []; + + $html = view('hr_access_controll', $data); + return $this->respond([ + 'status' => true, + 'code' => 200, + 'data' => $html + ], 200); + } + + public function getHrAccessData($client_id) + { + $hrAccessData = []; + + $post_client_data = $this->clientModel->where('id', $client_id)->where('is_active', 1)->first(); + + $hrAccessData['post_hr_data'] = $this->clientBranchModel + ->select('lc.id as post_hr_id, lc.name as hr_name, lc.mobile as hr_mobile, lc.email as hr_mail') + ->join('level_contacts lc', 'client_branch.id = lc.ref_id') + ->where('client_branch.is_active', 1) + ->where('lc.is_active', 1) + ->where('lc.contact_type', 'client') + ->where('client_branch.client_id', $client_id) + ->findAll(); + + $hrAccessData['post_policy_data'] = $this->clientPolicyModel + ->select('client_policy.id as client_policy_id, client_policy.policy_no as policy_no, policy_type.policy_type, client_policy.policy_status') + ->join('policy_type', 'client_policy.policy_type_id = policy_type.id') + ->where('client_policy.is_active', 1) + ->where('client_policy.client_id', $client_id) + // ->orderBy('client_policy_id', 'desc') + ->orderBy('client_policy.policy_status', 'desc') + ->findAll(); + + $hrAccessData['post_cd_data'] = $this->CDMasterModel + ->select('cd_master.id as cd_master_pk, cd_master.cd_ac_no as cd_account_no, insurers.name as insurer_name, insurers.short_name as insurer_short_name') + ->join('insurers', 'cd_master.insurer_id = insurers.id') + ->where('cd_master.is_active', 1) + ->where('cd_master.client_id', $client_id) + ->findAll(); + + $hrAccessData['hr_access_table_data'] = $this->HRAccessControlModel + ->where('is_active', 1) + ->where('post_client_id', $client_id) + ->findAll(); + + try { + log_message('error', 'Attempting to connect to preDB...'); + $db2 = \Config\Database::connect('preDB'); + log_message('error', 'Connection to preDB successful.'); + } catch (\Throwable $e) { + log_message('error', 'DB connection to preDB failed: ' . $e->getMessage()); + + $hrAccessData['pre_hr_data'] = []; + $hrAccessData['pre_policy_data'] = []; + $combinedHrAccessData = $this->constructHrAccessData($hrAccessData, $client_id); + return $combinedHrAccessData; + } + + $pre_client_data = $db2->table('clients')->where('is_active', 1)->where('short_name', $post_client_data['short_name'])->get()->getRowArray(); + + $hrAccessData['pre_hr_data'] = $db2->table('client_branch') + ->select('lc.id as pre_hr_id, lc.name as hr_name, lc.mobile as hr_mobile, lc.email as hr_mail') + ->join('level_contacts lc', 'client_branch.id = lc.ref_id') + ->where('client_branch.is_active', 1) + ->where('lc.is_active', 1) + ->where('lc.contact_type', 'client') + ->where('client_branch.client_id', $pre_client_data['id']) + ->get() + ->getResultArray(); + + $hrAccessData['pre_policy_data'] = $db2->table('client_policy') + ->select('client_policy.id as client_policy_id, client_policy.policy_no as policy_no, policy_type.policy_type, client_policy.policy_status') + ->join('policy_type', 'client_policy.policy_type_id = policy_type.id') + ->where('client_policy.is_active', 1) + ->where('client_policy.client_id', $pre_client_data['id']) + // ->orderBy('client_policy_id', 'desc') + ->orderBy('client_policy.policy_status', 'desc') + ->get() + ->getResultArray(); + + // dd($hrAccessData); + + $combinedHrAccessData = $this->constructHrAccessData($hrAccessData, $client_id); + return $combinedHrAccessData; + } + + public function constructHrAccessData($data, $client_id) + { + // dd($data); + $preHrs = $data['pre_hr_data']; + $postHrs = $data['post_hr_data']; + $hrAccessTableData = $data['hr_access_table_data']; + $merged = []; + + // Merge based on mobile and email + foreach ($postHrs as $post) { + $found = false; + foreach ($preHrs as $index => $pre) { + if ($post['hr_mobile'] === $pre['hr_mobile'] && $post['hr_mail'] === $pre['hr_mail']) { + $merged[] = [ + 'pre_hr_id' => $pre['pre_hr_id'], + 'post_hr_id' => $post['post_hr_id'], + 'hr_name' => $post['hr_name'], + 'hr_mobile' => $post['hr_mobile'], + 'hr_mail' => $post['hr_mail'] + ]; + unset($preHrs[$index]); // remove matched pre_hr + $found = true; + break; + } + } + + if (!$found) { + $merged[] = [ + 'pre_hr_id' => null, + 'post_hr_id' => $post['post_hr_id'], + 'hr_name' => $post['hr_name'], + 'hr_mobile' => $post['hr_mobile'], + 'hr_mail' => $post['hr_mail'] + ]; + } + } + + // Remaining preHrs (not matched) + foreach ($preHrs as $pre) { + $merged[] = [ + 'pre_hr_id' => $pre['pre_hr_id'], + 'post_hr_id' => null, + 'hr_name' => $pre['hr_name'], + 'hr_mobile' => $pre['hr_mobile'], + 'hr_mail' => $pre['hr_mail'] + ]; + } + + // dd($merged); + + $result = []; + + if (empty($hrAccessTableData)) { + + // No access data — fill result with hr data and other fields as null + foreach ($merged as $hr) { + $result[] = [ + 'hr_access_table_pk' => null, + 'post_client_id' => $client_id ?? null, + 'pre_hr_id' => $hr['pre_hr_id'] ?? null, + 'post_hr_id' => $hr['post_hr_id'] ?? null, + 'allowed_pre_modules' => [], + 'allowed_post_modules' => [], + 'allowed_pre_policies' => [], + 'allowed_active_policies' => [], + 'allowed_cd' => [], + 'hr_name' => $hr['hr_name'] ?? null, + 'hr_mobile' => $hr['hr_mobile'] ?? null, + 'hr_mail' => $hr['hr_mail'] ?? null, + ]; + } + + } else { + // First create a map of HR data by post_hr_id for quick lookup + $hrMap = []; + foreach ($merged as $hr) { + $hrMap[$hr['post_hr_id']] = $hr; + } + + // Process access data first + foreach ($hrAccessTableData as $access) { + $post_hr_id = $access['post_hr_id']; + + // Check if this HR exists in our merged data + if (isset($hrMap[$post_hr_id])) { + $hr = $hrMap[$post_hr_id]; + $temp_arr_key = $hr['hr_mobile'] . $hr['hr_mail']; + + // Parse allowed modules + $allowed_modules = json_decode($access['allowed_modules'], true) ?? null; + $allowed_pre_modules = $allowed_modules['pre'] ?? []; + $allowed_post_modules = $allowed_modules['post'] ?? []; + + $result[$temp_arr_key] = [ + 'hr_access_table_pk' => $access['id'] ?? null, + 'post_client_id' => $access['post_client_id'] ?? null, + 'pre_hr_id' => $hr['pre_hr_id'] ?? null, + 'post_hr_id' => $hr['post_hr_id'] ?? null, + 'allowed_pre_modules' => $allowed_pre_modules, + 'allowed_post_modules' => $allowed_post_modules, + 'allowed_pre_policies' => json_decode($access['allowed_pre_policies'], true) ?? [], + 'allowed_active_policies' => json_decode($access['allowed_active_policies'], true) ?? [], + 'allowed_cd' => json_decode($access['allowed_cd'], true) ?? [], + 'hr_name' => $hr['hr_name'], + 'hr_mobile' => $hr['hr_mobile'], + 'hr_mail' => $hr['hr_mail'] + ]; + + // Remove from map so we know it's been processed + unset($hrMap[$post_hr_id]); + } + } + + // Now process any remaining HRs that didn't have access records + foreach ($hrMap as $hr) { + $temp_arr_key = $hr['hr_mobile'] . $hr['hr_mail']; + + $result[$temp_arr_key] = [ + 'hr_access_table_pk' => null, + 'post_client_id' => $client_id ?? null, + 'pre_hr_id' => $hr['pre_hr_id'] ?? null, + 'post_hr_id' => $hr['post_hr_id'] ?? null, + 'allowed_pre_modules' => [], + 'allowed_post_modules' => [], + 'allowed_pre_policies' => [], + 'allowed_active_policies' => [], + 'allowed_cd' => [], + 'hr_name' => $hr['hr_name'] ?? null, + 'hr_mobile' => $hr['hr_mobile'] ?? null, + 'hr_mail' => $hr['hr_mail'] ?? null, + ]; + } + } + + + $resultData['hr_access_data'] = array_values($result); + $resultData['pre_policy_data'] = $data['pre_policy_data']; + $resultData['post_policy_data'] = $data['post_policy_data']; + $resultData['post_cd_data'] = $data['post_cd_data']; + // echo '**********************************************'; + // print_rr($resultData);die(); + + return $resultData; + } + + public function saveHrAccessData() + { + try { + // Step 1: Fetch and decode the JSON data + $client_id = $this->request->getPost('client_id'); + $jsonData = $this->request->getPost('json'); + $data = json_decode($jsonData, true); + + if (!$data || !is_array($data)) { + log_message('error', 'Invalid or empty JSON in saveHrAccessData: ' . $jsonData); + return $this->respond([ + 'status' => false, + 'code' => 400, + 'message' => 'Invalid JSON data provided.', + ], 400); + } + + $success = []; + $errors = []; + $skippedCount = 0; + + // Step 2: Loop and insert/update + foreach ($data as $index => $value) { + try { + // Decode allowed_modules and validate + $allowed_modules = json_decode($value['allowed_modules'], true); + if (empty($allowed_modules)) { + $skippedCount++; + continue; // Skip this record + } + + // Format allowed_modules: { pre: [1], post: [2,3,4] } + $pre = in_array(1, $allowed_modules) ? [1] : []; + $post = array_values(array_filter($allowed_modules, fn($v) => $v !== 1)); + $value['allowed_modules'] = json_encode(['pre' => $pre, 'post' => $post]); + + // INSERT or UPDATE + if (empty($value['pk']) || (int)$value['pk'] === 0) { + unset($value['pk']); // Prevent insert error + $insertedId = $this->HRAccessControlModel->insert($value); + if ($insertedId === false) { + throw new \Exception('Insert failed: ' . json_encode($this->HRAccessControlModel->errors())); + } + $success[] = "Inserted row at index {$index} with ID {$insertedId}."; + } else { + $update = $this->HRAccessControlModel->update($value['pk'], $value); + if ($update === false) { + throw new \Exception('Update failed for ID ' . $value['pk'] . ': ' . json_encode($this->HRAccessControlModel->errors())); + } + $success[] = "Updated row with ID {$value['pk']}."; + } + } catch (\Exception $e) { + log_message('error', 'HRAccess Save Error at index ' . $index . ': ' . $e->getMessage()); + $errors[] = "Error at index {$index}: " . $e->getMessage(); + } + } + + // Step 3: If all rows were skipped (no allowed_modules) + if (count($data) === $skippedCount) { + return $this->respond([ + 'status' => false, + 'code' => 422, + 'message' => 'Please select at least one module for any user.', + ], 422); + } + + // Step 4: Final response + if (empty($errors)) { + + $data = $this->getHrAccessData($client_id); + $html = view('hr_access_controll', $data); + + return $this->respond([ + 'status' => true, + 'code' => 200, + 'message' => 'All records processed successfully.', + 'details' => $success, + 'data' => $html, + ], 200); + + } else { + return $this->respond([ + 'status' => false, + 'code' => 207, + 'message' => 'Some records failed to save.', + 'success' => $success, + 'errors' => $errors + ], 207); + } + } catch (\Exception $e) { + log_message('critical', 'Fatal error in saveHrAccessData: ' . $e->getMessage()); + return $this->respond([ + 'status' => false, + 'code' => 500, + 'message' => 'Unexpected server error.', + 'error' => $e->getMessage() + ], 500); + } + } + + } diff --git a/app/Controllers/EmpDataServiceController.php b/app/Controllers/EmpDataServiceController.php index 3dbf91d5..9d3eeecf 100755 --- a/app/Controllers/EmpDataServiceController.php +++ b/app/Controllers/EmpDataServiceController.php @@ -1918,7 +1918,7 @@ class EmpDataServiceController extends BaseController $result_for_employees_policy = $this->employeePolicyModel ->select('employee_polices.*') ->join('employees', 'employees.id = employee_polices.employee_id') - ->join('emp_endorsement', 'emp_endorsement.employee_id = employees.id') // assuming this is the correct join + ->join('emp_endorsement', 'emp_endorsement.pk = employees.id') // assuming this is the correct join ->where('employees.emp_code', $emp_code) ->where('employees.name', $name) ->where('employees.client_id', $client_id) diff --git a/app/Controllers/EmployeeController.php b/app/Controllers/EmployeeController.php index 6541e011..512122c6 100755 --- a/app/Controllers/EmployeeController.php +++ b/app/Controllers/EmployeeController.php @@ -344,9 +344,11 @@ class EmployeeController extends AdminController $query->where('cr.user_id', $user_id); } // ->where('files.created_by', get_session_userid()) - $data['fileList'] = $query->groupBy("c.id")->orderBy('files.created_at', 'desc') - ->limit(1500) + $data['fileList'] = $query->groupBy("files.id")->orderBy('files.created_at', 'desc') + // $data['fileList'] = $query + ->limit(2000) ->find(); + // dd($this->fileModel->getLastQuery()); // dd($data['fileList']); $query2 = $this->batchFileModel->select(" @@ -395,7 +397,7 @@ class EmployeeController extends AdminController $query2->where('cr.user_id', $user_id); } // ->where('files.created_by', get_session_userid()) - $data['batch_list'] = $query2->groupBy("clients.id")->orderBy('batch_files.id', 'desc') + $data['batch_list'] = $query2->groupBy("batch_files.id")->orderBy('batch_files.id', 'desc') ->limit(1500) ->find(); @@ -1388,7 +1390,7 @@ class EmployeeController extends AdminController } //STEP:3 - Update files table status - $this->fileModel->where('id', $file_id)->set(['status' => 'truncated'])->update(); + $this->fileModel->where('id', $file_id)->set(['status' => 'truncated','updated_by' => $loggedInUserID])->update(); $this->myLogger->logme('error', '---- files table updated ----'); //FINAL STEP - Update reverse entry in cash_deposite table @@ -1477,7 +1479,7 @@ class EmployeeController extends AdminController // dd($affectedRows); $affectedRows = $affectedRows * 2; - $this->fileModel->where('id', $file_id)->set(['status' => 'truncated'])->update(); + $this->fileModel->where('id', $file_id)->set(['status' => 'truncated','updated_by' => $loggedInUserID])->update(); } @@ -1544,7 +1546,7 @@ class EmployeeController extends AdminController // STEP 3: //update files table status to "truncated" - $this->fileModel->where('id', $file_id)->set(['status' => 'truncated'])->update(); + $this->fileModel->where('id', $file_id)->set(['status' => 'truncated','updated_by' => $loggedInUserID])->update(); $this->myLogger->logme('error', 'files table updated'); diff --git a/app/Controllers/EmployeeRestController.php b/app/Controllers/EmployeeRestController.php index db9a0ea2..8a77865c 100755 --- a/app/Controllers/EmployeeRestController.php +++ b/app/Controllers/EmployeeRestController.php @@ -32,6 +32,8 @@ use App\Models\AuditHistoryModel; use App\Models\TicketClaimStatusModel; use App\Models\TicketMasterModel; use App\Models\TicketMessageModel; +use App\Models\HRAccessControlModel; +use App\Models\InsurerModel; @@ -83,6 +85,8 @@ class EmployeeRestController extends AdminController protected $ticketMessage; protected $ticketController; + protected $hrAccessControlModel; + protected $insurerModel; public function __construct() @@ -112,6 +116,8 @@ class EmployeeRestController extends AdminController $this->ticketMessage = new TicketMessageModel(); $this->ticketController = new TicketController(); + $this->hrAccessControlModel = new HRAccessControlModel(); + $this->insurerModel = new InsurerModel(); } @@ -2276,23 +2282,60 @@ class EmployeeRestController extends AdminController } + + public function getHRAccessData( $hr_id = null , $request_for = 'post_enrollment') + { + $hr_id = $this->request->getGet('hr_id') ?? $hr_id; + $request_for = $this->request->getGet('request_for') ?? $request_for; + + if($request_for == 'pre_enrollment'){ $idField = 'pre_hr_id'; }else{ $idField = 'post_hr_id'; } + + $data = $this->hrAccessControlModel->where($idField , $hr_id)->where('is_active' , 1)->first(); + + if($request_for == 'post_enrollment'){ return $data ?? []; } + + return $this->respond(['status' => (($data) ? 'success' : 'failed'),'code' => (($data) ? 200 : 404),'data' => $data ], 200); + } + public function getPolicyLevelEmployeeSummaryData() { + $hr_id = $this->request->getGet('hr_id'); + $HRAccessData = $this->getHRAccessData($hr_id,'post_enrollment'); + + if(isset($HRAccessData['allowed_active_policies'])) + { + $policyId = json_decode($HRAccessData['allowed_active_policies'],true); + }else{ + $policyId = []; + } + + if(count($policyId) == 0){ + return $this->respond(['status' => 'failed','code' => (count($policyId) ? 200 : 404),'data' => [] ], 200); + } + + - $ClientPolicyData = $this->clientPolicyModel->select('client_policy.id as client_policy_id , client_policy.client_id as client_id, client_policy.policy_type_id as policy_type_id, client_policy.is_addon as is_addon , client_policy.open_for_enrollment as OpenForEnrollment , client_policy.inception_type as inception_type ') + $ClientPolicyData = $this->clientPolicyModel->select('client_policy.id as client_policy_id , client_policy.client_id as client_id, client_policy.policy_type_id as policy_type_id, client_policy.is_addon as is_addon , client_policy.open_for_enrollment as OpenForEnrollment , client_policy.inception_type as inception_type, client_policy.policy_no as policy_no, client_policy.insurer_id as insurer_id, DATE_FORMAT(client_policy.policy_end_date, "%d-%m-%Y") AS policy_expiry_date ') ->where('client_policy.client_id', $this->request->getGet('client_id') ) ->where('client_policy.client_branch_id', $this->request->getGet('client_branch_id') ) ->where('client_policy.is_active', 1 ) ->where('client_policy.policy_status', $this->request->getGet('policy_status')) + ->whereIn('client_policy.id', $policyId) ->findAll(); + + $result = []; // dd( $ClientPolicyData); foreach ($ClientPolicyData as $key => $value) { $policyTypeData = $this->policyTypeModel->where('id',$value['policy_type_id'])->get()->getRow(); + $insurerData = $this->insurerModel->where('id',$value['insurer_id'])->get()->getRow(); + $value['type'] = $policyTypeData->policy_type; $value['policy_name'] = $policyTypeData->long_name; + $value['insurer_name'] = $insurerData->name; + $value['insurer_short_name'] = $insurerData->short_name; $employeeDetails = $this->employeePolicyModel->getEmployeePolicy( client_id:$value['client_id'],policy_id: $value['client_policy_id'],status:0,branch_id:$this->request->getGet('client_branch_id')); // dd($employeeDetails); $activeCount = 0; @@ -2331,13 +2374,28 @@ class EmployeeRestController extends AdminController public function cdSummaryData() { + $hr_id = $this->request->getGet('hr_id'); + $HRAccessData = $this->getHRAccessData($hr_id,'post_enrollment'); + + if(isset($HRAccessData['allowed_active_policies'])) + { + $policyId = json_decode($HRAccessData['allowed_active_policies'],true); + }else{ + $policyId = []; + } + + if(count($policyId) == 0){ + return $this->respond(['status' => 'failed','code' => (count($policyId) ? 200 : 404),'data' => [] ], 200); + } + $clientId = $this->request->getGet('client_id'); $clientController = new ClientController; - $result = $clientController->deposit($clientId , $requestFrom = 'rest'); + $result = $clientController->deposit($clientId , $requestFrom = 'rest' , $policyId); $data = []; + foreach ($result['clientData'] as $key => $value) { $temp['client_id'] = $value->client_id; @@ -2494,12 +2552,16 @@ class EmployeeRestController extends AdminController 'tm.awb_no_courier_name', 'tm.non_id_reason', 'tm.pay_initiate_date', - 'tm.approved_description' + 'tm.approved_description', + 'pt.policy_type as policy_type', + 'cp.policy_no as client_policy_no', ]); $builder->join('insurers i', 'i.id = tm.insurer_id AND i.is_active = 1', 'left'); $builder->join('clients c', 'c.id = tm.client_id AND c.is_active = 1', 'left'); $builder->join('ticket_claim_status tcs', 'tcs.id = tm.claim_status_id AND tcs.is_active = 1', 'left'); + $builder->join('client_policy cp', 'tm.client_policy_id = cp.id', 'left'); + $builder->join('policy_type pt', 'cp.policy_type_id = pt.id', 'left'); $builder->where('tm.is_active', 1); @@ -2533,15 +2595,31 @@ class EmployeeRestController extends AdminController $data['claims_data'] = $this->ticketMaster->getTicketDataByTicketID($ticket_id); $data['ticket_data'] = $ticketController->getMoreInfo($requestFrom = 'rest', $ticket_id); + + // $data = $response['data']; // Assuming your full array is stored in $response + // $ticketData = $data['ticket_data']; + // $ticketHistory = $data['ticket_history']; + + // Loop through ticket_data + foreach ($data['ticket_data'] as $status => &$fields) { + // Search ticket_history for matching old_status_value + foreach ($data['ticket_history'] as $history) { + if ($history['old_status_value'] === $status) { + // Attach modified_by and created_at + $fields['modified_by'] = $history['modified_by']; + $fields['modified_at'] = date('d-m-Y h:i A', strtotime($history['created_at'])); + // Break after first match (assuming latest entry is enough) + break; + } + } + } + return $this->respond(['status' => (count($data) ? 'success' : 'failed'),'code' => (count($data) ? 200 : 404),'data' => $data ], 200); } - - - public function exportCashDepositData() { @@ -2712,6 +2790,12 @@ class EmployeeRestController extends AdminController ->where('client_branch_id',$this->request->getGet('client_branch_id')) ->where('family_floater_key','self')->where('is_active', 1 ) ->get()->getRow()->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); + $whereArrayForId = []; foreach ( $employeeData as $key => $value) { array_push($whereArrayForId, $value['id']); } @@ -2759,6 +2843,7 @@ class EmployeeRestController extends AdminController $data['heading'] = $ClientPolicyValue['policy_long_name']; $data['claims_grace_date'] = $this->convertDateFormatDisplay($ClientPolicyValue['claims_grace_date']); $data['policy_status'] = $policy_status_key; + $data['pre_policy_count'] = $prePolicyCount; // $data['policy_terms'] = $terms; // if($ClientPolicyValue['policy_type_id'] == 1){ $data['heading'] = 'Group Personal Accident Coverage'; }else @@ -2811,7 +2896,7 @@ class EmployeeRestController extends AdminController } - return $this->respond(['status' => 'success','code' => 200,'data' => $result , 'emp_name' => $employeeName ], 200); + return $this->respond(['status' => 'success','code' => 200,'data' => $result , 'emp_name' => $employeeName, 'pre_policy_count' => $prePolicyCount ], 200); }else{ return $this->respond(['status' => 'failed','code' => 404,'data' => [] ], 200); @@ -3535,5 +3620,160 @@ class EmployeeRestController extends AdminController } } + public function getEmployeePolicyCount() + { + $db2 = \Config\Database::connect('preDB'); + + $mobile_no = $this->request->getGet('mobile_no'); + + $builder = $db2->table('employees') + ->join('employee_polices', 'employees.id = employee_polices.employee_id') + ->where('employees.is_active', 1) + ->whereIn('employees.emp_status', ['draft', 'enrolled']) + ->where('employee_polices.is_active', 1) + ->whereIn('employee_polices.status', ['draft', 'enrolled']) + ->where('employees.mobile', $mobile_no) + ->groupBy('employee_polices.client_policy_id'); + + $query = $builder->get(); + $count = $query->getNumRows(); // count grouped rows manually + + return $this->respond([ + 'status' => 'success', + 'code' => 200, + 'policy_count' => $count + ], 200); + } + + // public function getPreEmployeePolicyCount($mobile_no, $clientId = null) + // { + // log_message('error', 'getPreEmployeePolicyCount called with params : ' . json_encode(['mobile_no' => $mobile_no, 'client_id' => $clientId], true)); + + // if (empty($mobile_no)) { + // log_message('error', 'Mobile number is empty or null.'); + // return 0; + // } + + // $client_short_name = []; + // if(!empty($clientId)){ + // $client_data = $this->clientModel->where('is_active', 1)->where('id', $clientId)->first(); + // $client_short_name = $client_data['short_name'] ?? null; + // } + + // $post_data = [ + // 'mobile_number' => $mobile_no, + // 'client_data' => $client_short_name + // ]; + + // $response = $this->callThirdPartyAPI($post_data, 'getPreEmployeePolicyCount'); + // print_r( $response); die; + + // return $response['data'] ?? 0 ; + + + // try { + // log_message('error', 'Attempting to connect to preDB...'); + // $db2 = \Config\Database::connect('preDB'); + // log_message('error', 'Connection to preDB successful.'); + // } catch (\Throwable $e) { + // log_message('error', 'DB connection to preDB failed: ' . $e->getMessage()); + // return 0; + // } + + // try { + // log_message('error', 'Building query to count employee policies...'); + // $builder = $db2->table('employees') + // ->join('employee_polices', 'employees.id = employee_polices.employee_id') + // ->join('client_policy cp', 'employee_polices.client_policy_id = cp.id') + // ->where('employees.is_active', 1) + // ->whereIn('employees.emp_status', ['draft', 'enrolled']) + // ->where('employee_polices.is_active', 1) + // ->whereIn('employee_polices.status', ['draft', 'enrolled']) + // ->where('cp.enrolment_visibility', 1) + // ->where('cp.open_for_enrollment', 1) + // ->whereIn('cp.policy_type_id', [1,2,6,7]) + // ->where('employees.mobile', $mobile_no) + // ->orderBy('employees.created_at', 'desc') + // ->groupBy('employee_polices.client_policy_id'); + + // if(!empty($clientId)){ + // $builder->where('employees.client_id', $clientId); + // } + + // log_message('error', 'Executing policy count query...'); + // $query = $builder->get(); + // $count = $query->getNumRows(); + // // dd($db2->getLastQuery()); + + // log_message('error', 'Policy count result: ' . $count); + // return $count; + + // } catch (\Throwable $e) { + // log_message('error', 'Query failed in getPreEmployeePolicyCount: ' . $e->getMessage()); + // return 0; + // } + // } + + 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])); + + if (empty($mobile_no)) { + log_message('error', 'STEP 2: Mobile number 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(); + + if ($client_data) { + $client_short_name = $client_data['short_name'] ?? null; + log_message('error', 'STEP 4: Found client short name: ' . $client_short_name); + } 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 + ]; + + log_message('error', 'STEP 5: Calling third-party API with payload: ' . json_encode($post_data)); + + try { + $response = $this->callThirdPartyAPI($post_data, 'getPreEmployeePolicyCount'); + log_message('error', 'STEP 6: API raw response: ' . $response); + + $response = json_decode($response, true); + + if (json_last_error() !== JSON_ERROR_NONE) { + log_message('error', 'STEP 7: JSON decoding failed: ' . json_last_error_msg()); + return 0; + } + + $count = $response['data'] ?? 0; + log_message('error', 'STEP 8: Final count extracted: ' . $count); + + return $count; + } catch (\Throwable $e) { + log_message('error', 'STEP 6: API call failed: ' . $e->getMessage()); + return 0; + } + } + + private function callThirdPartyAPI($postData , $endPoint) + { + $client = \Config\Services::curlrequest(); + $url = env('PRE_ENROLLMENT_BASEURL').$endPoint; + $response = $client->post( $url, ['json' => $postData, 'http_errors' => false ] ); + // return json_decode($response->getBody(), true); + return $response->getBody(); + } } \ No newline at end of file diff --git a/app/Controllers/ICICILombardController.php b/app/Controllers/ICICILombardController.php new file mode 100644 index 00000000..e1c09e30 --- /dev/null +++ b/app/Controllers/ICICILombardController.php @@ -0,0 +1,186 @@ + 'password', + 'username' => 'Nhanceins', + 'password' => 'SSWW7bFNaLxxQyw', + 'scope' => $scope, + 'client_id' => 'Nhanceins', + 'client_secret' => 'P4W0G6TAYMa0MV8bbVSx4pTAqbCcUIg48kCWa6PJykAhGWzPmpPr0iLuNWtz5wqN' + ]; + print_rr(json_encode($body));//die; + $response = call_third_party_api($url, $method, $headers, $body); + + print_rr(json_encode($response));//die; + if($response['status'] != true){ + return $this->response->setJSON([ + 'status' => false, + 'message' => 'Token generation failed.', + 'data' => $response + ]); + } + + return $response; + } + + public function createEnrollmentBatch() + { + helper('api'); + + //fetch token + $tokenResponse = $this->generateAuthToken(); + if (!$tokenResponse || empty($tokenResponse['data']['access_token'])) { + return $this->response->setJSON([ + 'status' => false, + 'message' => 'Token generation failed.', + 'data' => $tokenResponse + ]); + } + $token = $tokenResponse['data']['access_token']; + // dd($token); + + $url = 'https://ilesbapigee.insurancearticlez.com/health/ilservices/health/v1/enrollment/batchcreation'; + $headers = [ + 'Authorization: Bearer ' . $token, + 'Content-Type: application/json', + //'Scope: esbgpabatchcreation' + ]; + + $body = [ + "PolicyNumber" => "4016/A/51974976/00/000", + "CDBGAccountNumber" => "CD-MUM-3344", + "CorrelationId" => "86383c78-4c67-4e4d-9aa0-8f926fb0d55f", + "MemberDetails" => [ + [ + "EmployeeMemberId" => "EMPID3625556", + "DOJ" => "21-MAR-2019", + "InsuredName" => "ABC28144", + "DOB" => "7-JUL-1983", + "Relationship" => "SELF", + "Gender" => "MALE", + "DOC" => "20-JAN-2020", + "SumInsured" => "600000", + "EmailId" => "ABC@GMAIL.COM", + "FlagStatus" => "A" + ], + [ + "EmployeeMemberId" => "EMPID3625556", + "DOJ" => "21-MAR-2019", + "InsuredName" => "ABC28146", + "DOB" => "8-AUG-1970", + "Relationship" => "MOTHER", + "Gender" => "FEMALE", + "DOC" => "20-JAN-2020", + "SumInsured" => "600000", + "EmailId" => "ABC@GMAIL.COM", + "FlagStatus" => "A" + ], + [ + "EmployeeMemberId" => "EMPID0502220011", + "UHID" => "IL00688842553", + "InsuredName" => "ABC28142", + "DOB" => "8-SEP-1970", + "Gender" => "MALE", + "SumInsured" => "600000", + "EmailId" => "ABC@GMAIL.COM", + "FlagStatus" => "M" + ], + [ + "UHID" => "IL00688842552", + "DOL" => "20-JAN-2020", + "FlagStatus" => "D" + ] + ] + ]; + // Kint::dump($body); + print_rr(json_encode($body)); + // dd(); + $response = call_third_party_api($url, 'POST', $headers, ($body),true); // true = raw body mode + print_rr(json_encode($response));die(); + return $this->response->setJSON($response); + } + + public function getEnrollmentBatchStatus() + { + helper('api'); + + //fetch token + $tokenResponse = $this->generateAuthToken('esbgpabatchstatus'); + if (!$tokenResponse || empty($tokenResponse['data']['access_token'])) { + return $this->response->setJSON([ + 'status' => false, + 'message' => 'Token generation failed.', + 'data' => $tokenResponse + ]); + } + $token = $tokenResponse['data']['access_token']; + + + $url = 'https://ilesbapigee.insurancearticlez.com/health/ilservices/health/v1/enrollment/batchstatus'; + $headers = [ + 'Authorization: Bearer ' . $token, + 'Content-Type: application/json' + ]; + + $body = [ + "PolicyNumber" => "4016/A/51974976/00/000", + "BatchId" => "2345617878", + "CorrelationId" => "86383c78-4c67-4e4d-9aa0-8f926fb0d55f" + ]; + + $response = call_third_party_api($url, 'POST', $headers, json_encode($body), true); + + return $this->response->setJSON($response); + } + + public function fetchUHIDDetails() + { + helper('api'); + + //fetch token + $tokenResponse = $this->generateAuthToken('esbgpauhid'); + if (!$tokenResponse || empty($tokenResponse['data']['access_token'])) { + return $this->response->setJSON([ + 'status' => false, + 'message' => 'Token generation failed.', + 'data' => $tokenResponse + ]); + } + $token = $tokenResponse['data']['access_token']; + + $url = 'https://ilesbapigee.insurancearticlez.com/health/ilservices/health/v1/enrollment/fetchuhid'; + $headers = [ + 'Authorization: Bearer ' . $token, + 'Content-Type: application/json' + ]; + + $body = [ + "PolicyNumber" => "4016/A/51974976/00/000", + "IMID" => "2345617878", + "CorrelationId" => "86383c78-4c67-4e4d-9aa0-8f926fb0d55f" + ]; + + $response = call_third_party_api($url, 'POST', $headers, json_encode($body), true); + + return $this->response->setJSON($response); + } + + + +} diff --git a/app/Controllers/LeadsController.php b/app/Controllers/LeadsController.php index ee908837..56f7f1d0 100644 --- a/app/Controllers/LeadsController.php +++ b/app/Controllers/LeadsController.php @@ -1280,8 +1280,8 @@ class LeadsController extends BaseController 'No of Employees at Inception' => $rfq_data['incept_emp_count'], 'Total Sum Insured at Inception ' => $rfq_data['total_si_at_incept'], 'Policy Period' => !empty($rfq_data['policy_start_date']) && !empty($rfq_data['policy_end_date']) ? date('d-m-Y', strtotime($rfq_data['policy_start_date'])) . ' to ' . date('d-m-Y', strtotime($rfq_data['policy_end_date'])) : "To be decided", - 'Insurer' => $rfq_data['insurer_name'] ?? " - ", - 'TPA' => $rfq_data['tpa_name'] ?? " - ", + // 'Insurer' => $rfq_data['insurer_name'] ?? " - ", + // 'TPA' => $rfq_data['tpa_name'] ?? " - ", 'Policy Type' => $this->leadType[$rfq_data['lead_type']] ?? "", ]; } @@ -1310,9 +1310,9 @@ class LeadsController extends BaseController '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' => $rfq_data['earned_premium'], + '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($rfq_data['annualised_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'] . " %", ]; @@ -1322,11 +1322,11 @@ class LeadsController extends BaseController 'No of Employees at Renewal' => $rfq_data['renewal_emp_count'], 'Total Sum Insured at Renewal ' => $rfq_data['total_si_at_renewal'], 'Policy Period' => !empty($rfq_data['policy_start_date']) && !empty($rfq_data['policy_end_date']) ? date('d-m-Y', strtotime($rfq_data['policy_start_date'])) . ' to ' . date('d-m-Y', strtotime($rfq_data['policy_end_date'])) : "To be decided", - 'Insurer' => $rfq_data['insurer_name'] ?? " - ", - 'TPA' => $rfq_data['tpa_name'] ?? " - ", + // 'Insurer' => $rfq_data['insurer_name'] ?? " - ", + // 'TPA' => $rfq_data['tpa_name'] ?? " - ", 'Policy Type' => $this->leadType[$rfq_data['lead_type']] ?? "", 'Existing Insurer' => $rfq_data['insurer_name'], - 'TPA ' => $rfq_data['tpa_name'], + // 'TPA ' => $rfq_data['tpa_name'], ]; } } @@ -1360,7 +1360,7 @@ class LeadsController extends BaseController $rowNumber = 1; $mergeRange1 = "A{$rowNumber}:B{$rowNumber}"; - $sheet->mergeCells($mergeRange1); + // $sheet->mergeCells($mergeRange1); $sheet->setCellValue("A{$rowNumber}", "Nhance India Insurance Broking Pvt Ltd"); $sheet->getStyle("A{$rowNumber}")->applyFromArray([ 'font' => [ @@ -1374,9 +1374,8 @@ class LeadsController extends BaseController ]); // Apply center alignment to the cell - $sheet->getStyle("C{$rowNumber}")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER); - $sheet->getStyle("C{$rowNumber}")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER); - + // $sheet->getStyle("C{$rowNumber}")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER); + // $sheet->getStyle("C{$rowNumber}")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER); $rowNumber = $rowNumber + 1; @@ -1388,22 +1387,22 @@ class LeadsController extends BaseController // Merge A:B for key and C:D for value $mergeRangeKey = "A{$rowNumber}:B{$rowNumber}"; - $mergeRangeValue = "C{$rowNumber}"; + // $mergeRangeValue = "C{$rowNumber}"; $sheet->mergeCells($mergeRangeKey); - $sheet->mergeCells($mergeRangeValue); + // $sheet->mergeCells($mergeRangeValue); // Set values in merged cells $sheet->setCellValue("A{$rowNumber}", $key); $sheet->setCellValue("C{$rowNumber}", $value); - // Apply styles for alignment and bold text in A:B - $sheet->getStyle($mergeRangeKey)->applyFromArray([ - 'font' => ['bold' => true], - 'alignment' => [ - 'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER, - 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER, - ], - ]); + // // Apply styles for alignment and bold text in A:B + // $sheet->getStyle($mergeRangeKey)->applyFromArray([ + // 'font' => ['bold' => true], + // 'alignment' => [ + // 'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER, + // 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER, + // ], + // ]); // Apply bold style to B column if the key is "Insured" if ($key == "Insured") { @@ -1419,7 +1418,7 @@ class LeadsController extends BaseController $rowNumber++; } - // // Set column width based on max content length (adjusted for padding) + // Set column width based on max content length (adjusted for padding) $sheet->getColumnDimension('A')->setWidth($maxWidthA * 1.2); // $sheet->getColumnDimension('B')->setWidth($maxWidthA * 1.5); $sheet->getColumnDimension('C')->setWidth(35); @@ -1470,13 +1469,14 @@ class LeadsController extends BaseController $sheet->mergeCells($mergeRange); $rowNumber_for_remove_quote_asked = $rowNumber; $rowNumber = $rowNumber + 1; + if ($type == 2) { $subHeaderRow = $rowNumber + 1; } else { $subHeaderRow = $rowNumber_for_remove_quote_asked; } - $columnLetter = 'A'; + $columnLetter = 'A'; $header_actual_count = 0; foreach ($headers as $header) { // Kint::dump($header); @@ -1561,8 +1561,6 @@ class LeadsController extends BaseController $sheet->getColumnDimension('B')->setWidth(35); } - // die(); - // Apply border to the header range $prevColumn1 = $this->getPreviousColumn($columnLetter); $headerRange = "A{$rowNumber}:" . "{$prevColumn1}" . "{$subHeaderRow}"; @@ -1584,6 +1582,7 @@ class LeadsController extends BaseController } else { $rowNumber = $subHeaderRow + 2; } + // dd($rowNumber); $column_data = $data['table_data']['data']; $serial_no = 1; @@ -1627,36 +1626,37 @@ class LeadsController extends BaseController // Add premium data // dd($data); - $labelArray = ["Premium", "GST (%)", "GST Amount (₹)", "Total"]; + // $labelArray = ["Premium", "GST (%)", "GST Amount (₹)", "Total"]; + $labelArray = ["Premium", "GST Amount (₹)", "Total"]; $premiumData = $data['premium_data']['data']; - $premium = [$labelArray[0]]; - $gst = [$labelArray[1]]; - $gstAmt = [$labelArray[2]]; - $total = [$labelArray[3]]; + // $premium = [$labelArray[0]]; + // $gst = [$labelArray[1]]; + // $gstAmt = [$labelArray[1]]; + // $total = [$labelArray[2]]; foreach ($premiumData as $proposal => $insurers) { if ($proposal != 'Particulars') { foreach ($insurers as $insurer => $values) { if($insurer == 'Quote Asked'){ - $premium[] = ""; - $gst[] = ""; - $gstAmt[] = ""; - $total[] = ""; + $premium[] = $labelArray[0]; + // $gst[] = ""; + $gstAmt[] = $labelArray[1]; + $total[] = $labelArray[2]; }else{ $premium[] = formatIndianCurrency($values[$labelArray[0]]); - $gst[] = $values[$labelArray[1]]; - $gstAmt[] = formatIndianCurrency($values[$labelArray[2]]); - $total[] = formatIndianCurrency($values[$labelArray[3]]); + // $gst[] = $values[$labelArray[1]]; + $gstAmt[] = formatIndianCurrency($values[$labelArray[1]]); + $total[] = formatIndianCurrency($values[$labelArray[2]]); } } } } - foreach ([$premium, $gst, $gstAmt, $total] as $index => $rowData) { - $columnLetter = 'B'; + foreach ([$premium, $gstAmt, $total] as $index => $rowData) { + $columnLetter = 'C'; foreach ($rowData as $key => $value) { $sheet->setCellValue("{$columnLetter}{$rowNumber}", $value); - if ($key === 0) { + if (in_array($value, $labelArray)) { $sheet->getStyle("{$columnLetter}{$rowNumber}")->applyFromArray(['font' => ['bold' => true,],]); } $columnLetter++; @@ -1669,7 +1669,8 @@ class LeadsController extends BaseController } else { $prevColumn3 = $this->getPreviousColumn($columnLetter, 2); } - $premiumRange = "B" . ($rowNumber - 4) . ":" . "{$prevColumn3}" . ($rowNumber - 1); + + $premiumRange = "C" . ($rowNumber - 3) . ":" . "{$prevColumn3}" . ($rowNumber - 1); // dd($premiumRange); $sheet->getStyle($premiumRange)->applyFromArray([ @@ -1682,9 +1683,7 @@ class LeadsController extends BaseController ]); } - //set imgage and align the row and column - // Kint::dump($columnLetter); if ($type == 2) { if ($is_placement == true) { $columnLetter_img = $this->getPreviousColumn($columnLetter); @@ -1694,7 +1693,6 @@ class LeadsController extends BaseController } else { $columnLetter_img = $this->getPreviousColumn($columnLetter); } - // dd($columnLetter_img); $company_name = $this->getPreviousColumn($columnLetter_img); $mergeRange1 = "A1:{$company_name}1"; @@ -1722,39 +1720,19 @@ class LeadsController extends BaseController $drawing->setPath($path); $drawing->setCoordinates("{$columnLetter_img}1"); // Set position in column B $drawing->setHeight(35); // Adjust image - $columnWidth = $sheet->getColumnDimension("C")->getWidth(); // e.g., 20 - $cellPixelWidth = $columnWidth * 7; // Approximate conversion (1 unit ≈ 7 pixels) - $imagePixelWidth = 250; // Approximate width of your image (in pixels) - - $offsetX = max(0, ($cellPixelWidth - $imagePixelWidth) / 2); - $offsetX = $offsetX + 97; - // dd($length); - if ($length >= 4) { - $offsetX = 65; - } else if ($length == 3) { - $offsetX = 65; - } - - // Center align the image in the cell + $offsetX = 35; $drawing->setOffsetX($offsetX); // Adjust horizontal offset $drawing->setOffsetY(10); // Adjust vertical offset $drawing->setWorksheet($sheet); - //end - // Auto-size columns // foreach ($sheet->getColumnIterator() as $column) { // $sheet->getColumnDimension($column->getColumnIndex())->setAutoSize(true); // } $dataRange = $sheet->calculateWorksheetDimension(); - - $sheet->getStyle($dataRange)->getAlignment() - ->setHorizontal(Alignment::HORIZONTAL_CENTER) - ->setVertical(Alignment::VERTICAL_CENTER) - ->setWrapText(true); - + $sheet->getStyle($dataRange)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER)->setVertical(Alignment::VERTICAL_CENTER)->setWrapText(true); $sheet->getStyle('A1')->applyFromArray([ 'alignment' => [ 'wrapText' => false, // Disables text wrapping for A1 @@ -1791,8 +1769,6 @@ class LeadsController extends BaseController ], ]); - - // Set filename $string = ($type == 2) ? ($is_placement == true ? 'Placement' : 'QCR') : 'RFQ'; $current_year = date('Y'); @@ -1809,7 +1785,6 @@ class LeadsController extends BaseController $filename = "{$rfq_data['client_name']}_{$rfq_data['policy_type']}_{$string}_" . $policy_year . '_' . '.xlsx'; } - // Save to temporary location $uploadFilePath = WRITEPATH . 'tmp/' . $filename; $writer = new Xlsx($spreadsheet); @@ -4026,7 +4001,7 @@ class LeadsController extends BaseController $offsetX = max(0, ($cellPixelWidth - $imagePixelWidth) / 2); $offsetX = $offsetX + 97; if ($length >= 4) { - $offsetX = 50; + $offsetX = 35; } else if ($length == 3) { $offsetX = 140; } diff --git a/app/Controllers/PolicyTransactionController.php b/app/Controllers/PolicyTransactionController.php index 6622d0fa..9a275f79 100644 --- a/app/Controllers/PolicyTransactionController.php +++ b/app/Controllers/PolicyTransactionController.php @@ -2037,8 +2037,8 @@ class PolicyTransactionController extends BaseController //insurer statement list page public function statementList() { - // dd($this->validateInsurerStatement(['file_id' => 30])); - // $data['insurers'] = $this->insurerModel->where('is_active',1)->findAll(); + // 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(); @@ -2261,13 +2261,13 @@ class PolicyTransactionController extends BaseController // dd($highestRowAndColumn); $excel_data = $sheet->rangeToArray('A1:' . $highestRowAndColumn['column'] . $highestRowAndColumn['row']); unset($excel_data[0]); - // Kint::dump($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(); + // Kint::dump($source_data);die(); // check policy no,insurer and etc in DB for this month @@ -2277,17 +2277,24 @@ class PolicyTransactionController extends BaseController 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{200C}\x{200B}]/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 - // Kint::dump($policy_no); + $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_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']) { + 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]); diff --git a/app/Controllers/RestAuthenticationController.php b/app/Controllers/RestAuthenticationController.php index a31dabe7..4aa0d89d 100755 --- a/app/Controllers/RestAuthenticationController.php +++ b/app/Controllers/RestAuthenticationController.php @@ -21,6 +21,8 @@ use CodeIgniter\API\ResponseTrait; use App\Models\EmployeeModel; use App\Models\AuthHistoryModel; use App\Models\LevelContactModel; +use App\Models\HRAccessControlModel; +use App\Models\ClientModel; use Firebase\JWT\JWT; // require_once('../vendor/autoload.php'); @@ -35,6 +37,8 @@ class RestAuthenticationController extends AdminController protected $employeeModel; protected $authHistoryModel; protected $hrModel; + protected $hrAccessControlModel; + protected $clientModel; public function __construct() @@ -45,6 +49,8 @@ class RestAuthenticationController extends AdminController $this->employeeModel = new EmployeeModel(); $this->authHistoryModel = new AuthHistoryModel(); $this->hrModel = new LevelContactModel(); + $this->hrAccessControlModel = new HRAccessControlModel(); + $this->clientModel = new ClientModel(); } @@ -100,6 +106,7 @@ class RestAuthenticationController extends AdminController } } catch (\Throwable $th) { + $this->myLogger->logme("error", ($th->getMessage().' --- '.$th->getLine())); return $this->respond(['status' => 'failed','code' => 500,'data' => $th],500); } } @@ -107,10 +114,13 @@ class RestAuthenticationController extends AdminController public function verifyEmployeeWithEmailId() { try { + + log_message('error', json_encode($this->request->getJSON())); $email = $this->request->getJSON()->email; + $client_id = $this->request->getJSON()->client_id ?? null; - $employeeData = $this->employeeModel->select(' + $builder = $this->employeeModel->select(' employees.relationship, EP.employee_id, employees.client_id, @@ -121,19 +131,38 @@ class RestAuthenticationController extends AdminController ->join('employee_polices EP', 'EP.employee_id = employees.id', 'inner') ->where('employees.is_active', 1) ->where('employees.relationship', 'Self') - ->where('employees.emp_status !=', 'truncated') + ->whereIn('employees.emp_status', ['active', 'expired']) ->where('employees.email_corporate', $email) ->where('EP.is_active', 1) - ->whereIn('EP.status', ['active', 'expired']) - ->first(); + ->whereIn('EP.status', ['active', 'expired']); + + if (!empty($client_id)) { + $builder->where('employees.client_id', $client_id); + } + + $builder->orderBy('employees.id', 'desc'); + $employeeData = $builder->first(); if (isset($employeeData['employee_id'])) { $otp = random_int(100000, 999999); - $update = $this->employeeModel->where('email_corporate', $email)->where('relationship', 'Self') - ->where('is_active', 1)->set(array('otp' => $otp)) - ->update(); + // $update = $this->employeeModel->where('email_corporate', $email)->where('relationship', 'Self') + // ->where('is_active', 1)->set(array('otp' => $otp)) + // ->update(); + + $builder = $this->employeeModel + ->where('email_corporate', $email) + ->where('relationship', 'Self') + ->where('is_active', 1) + ->where('id', $employeeData['employee_id']); + + if (!empty($client_id)) { + $builder->where('client_id', $client_id); + } + + $update = $builder->set(['otp' => $otp])->update(); + if ($update) { $common = [ @@ -161,11 +190,14 @@ class RestAuthenticationController extends AdminController $result = ['user_verification' => false, 'message' => "Verification failed , try again"]; return $this->respond(['status' => 'failed', 'code' => 404, 'data' => $result], 200); } + } else { $result = ['user_verification' => false, 'message' => "User not found"]; return $this->respond(['status' => 'failed', 'code' => 404, 'data' => $result], 200); } + } catch (\Throwable $th) { + $this->myLogger->logme("error", ($th->getMessage().' --- '.$th->getLine())); return $this->respond(['status' => 'failed', 'code' => 500, 'data' => $th], 500); } } @@ -175,53 +207,137 @@ class RestAuthenticationController extends AdminController $email = $this->request->getJSON()->email; $otp = $this->request->getJSON()->otp; - - $this->employeeModel->where('email_corporate', $email)->where('relationship', 'Self') - ->where('is_active', 1)->set(array('otp' => $otp)) - ->update(); + $client_id = $this->request->getJSON()->client_id ?? null; + $employee_id = $this->request->getJSON()->employee_id ?? null; + + // $builder = $this->employeeModel + // ->where('email_corporate', $email) + // ->where('relationship', 'Self') + // ->where('is_active', 1); + + $builder = $this->employeeModel + ->join('employee_polices EP', 'EP.employee_id = employees.id', 'inner') + ->where('employees.email_corporate', $email) + ->where('employees.relationship', 'Self') + ->where('employees.is_active', 1) + ->whereIn('employees.emp_status', ['active', 'expired']) + ->where('EP.is_active', 1) + ->whereIn('EP.status', ['active', 'expired']); + + + if (!empty($client_id)) { + $builder->where('client_id', $client_id); + } + + if (!empty($employee_id)) { + $builder->where('id', $employee_id); + } + + $builder->set(['otp' => $otp])->update(); return true; } + // public function updateEmpMPIN() + // { + // $requestData = $this->request->getJSON(); + // print_r($requestData); die; + // $mobile_number = $requestData->mobile_number ?? null; + // $email_id = $requestData->email_id ?? null; + // $new_mpin = $requestData->new_mpin ?? $requestData->mpin ?? null; + // $old_mpin = $requestData->old_mpin ?? null; + // $is_mpin_skipped = $requestData->is_mpin_skipped ?? null; + // $is_biometric_enabled = $requestData->is_biometric_enabled ?? null; + + // if (!$new_mpin) { + // return $this->response->setJSON(['status' => false, 'message' => 'MPIN is required.']); + // } + + // $query = $this->employeeModel->where('relationship', 'self'); + + // if ($mobile_number) { + // $query->where('mobile', $mobile_number); + // } elseif ($email_id) { + // $query->where('email_corporate', $email_id); + // } else { + // return $this->response->setJSON(['status' => false, 'message' => 'Mobile number or Email ID is required.']); + // } + + // if (!empty($old_mpin)) { + // $query->where('mpin', $old_mpin); + // } + + // // Fetch employee data + // $employeeData = $query->first(); + + // if (!$employeeData) { + // return $this->response->setJSON(['status' => false, 'message' => 'Employee not found or invalid MPIN.']); + // } + + // if(!empty($is_mpin_skipped) && !empty($is_biometric_enabled)){ + // $mpin_data_to_updata = [ + // 'mpin' => $new_mpin, + // 'is_mpin_skipped' => $is_mpin_skipped, + // 'is_biometric_enabled' => $is_biometric_enabled + // ]; + // }else{ + // $mpin_data_to_updata = ['mpin' => $new_mpin]; + // } + + // // Update MPIN + // $updated = $this->employeeModel->update($employeeData['id'], $mpin_data_to_updata); + + // return true; + // } + public function updateEmpMPIN() { - $requestData = $this->request->getJSON(); - $mobile_number = $requestData->mobile_number ?? null; - $email_id = $requestData->email_id ?? null; - $new_mpin = $requestData->new_mpin ?? $requestData->mpin ?? null; - $old_mpin = $requestData->old_mpin ?? null; - - if (!$new_mpin) { - return $this->response->setJSON(['status' => false, 'message' => 'MPIN is required.']); + try { + log_message('info', 'MPIN update request received.'); + + $requestData = $this->request->getJSON(); + log_message('debug', 'Request data: ' . json_encode($requestData)); + + $client_id = $requestData->client_id ?? null; + $employee_id = $requestData->employee_id ?? null; + $mpin = $requestData->mpin ?? null; + + if (!$mpin) { + log_message('error', 'MPIN is missing.'); + return $this->response->setJSON(['status' => false, 'message' => 'MPIN is required.']); + } + + if (!$employee_id) { + log_message('error', 'employee_id is missing.'); + return $this->response->setJSON(['status' => false, 'message' => 'employee_id is required.']); + } + + $updated = $this->employeeModel->where('id', $employee_id)->set(['mpin' => $mpin])->update(); + + if ($updated) { + log_message('info', "MPIN updated successfully for employee ID: {$employee_id}"); + return $this->response->setJSON([ + 'status' => true, + 'message' => 'MPIN updated successfully.' + ]); + } else { + log_message('error', "Failed to update MPIN for employee ID: {$employee_id}"); + return $this->response->setJSON([ + 'status' => false, + 'message' => 'Failed to update MPIN.' + ]); + } + } catch (\Exception $e) { + log_message('critical', 'Exception in updateEmpMPIN: ' . $e->getMessage()); + return $this->response->setJSON([ + 'status' => false, + 'message' => 'Unexpected error occurred.', + 'error' => $e->getMessage() + ]); } - - $query = $this->employeeModel->where('relationship', 'self'); - - if ($mobile_number) { - $query->where('mobile', $mobile_number); - } elseif ($email_id) { - $query->where('email_corporate', $email_id); - } else { - return $this->response->setJSON(['status' => false, 'message' => 'Mobile number or Email ID is required.']); - } - - if (!empty($old_mpin)) { - $query->where('mpin', $old_mpin); - } - - // Fetch employee data - $employeeData = $query->first(); - - if (!$employeeData) { - return $this->response->setJSON(['status' => false, 'message' => 'Employee not found or invalid MPIN.']); - } - - // Update MPIN - $updated = $this->employeeModel->update($employeeData['id'], ['mpin' => $new_mpin]); - - return true; } + @@ -234,6 +350,7 @@ class RestAuthenticationController extends AdminController $otp = isset($this->request->getJSON()->otp) ? $this->request->getJSON()->otp : null; $email_id = isset($this->request->getJSON()->email_id) ? $this->request->getJSON()->email_id : null; + $client_id = $this->request->getJSON()->client_id ?? null; if (isset($this->request->getJSON()->login_by_hr)) { @@ -241,9 +358,41 @@ class RestAuthenticationController extends AdminController }else{ if (isset($mobile_number)) { - $employeeData = $this->employeeModel->where('mobile', $mobile_number)->where('relationship', 'self')->where('emp_status !=', 'truncated')->where('is_active', 1)->first(); + // $employeeData = $this->employeeModel->where('mobile', $mobile_number)->where('relationship', 'self')->where('emp_status !=', 'truncated')->where('is_active', 1)->first(); + $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 { - $employeeData = $this->employeeModel->where('email_corporate', $email_id)->where('otp', $otp)->where('relationship', 'self')->where('emp_status !=', 'truncated')->where('is_active', 1)->first(); + // $employeeData = $this->employeeModel->where('email_corporate', $email_id)->where('otp', $otp)->where('relationship', 'self')->where('emp_status !=', 'truncated')->where('is_active', 1)->first(); + $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']) + ->where('otp', $otp); + + if (!empty($client_id)) { + $builder->where('employees.client_id', $client_id); + } + + $employeeData = $builder->orderBy('employees.id', 'desc')->first(); } } @@ -265,7 +414,7 @@ class RestAuthenticationController extends AdminController $result = JWTToken::encode($employeeData); if(isset($this->request->getJSON()->otp)){ - $this->employeeModel->where('email_corporate', $email_id)->where('otp', $otp)->where('relationship', 'self')->set(['otp'=>null])->update(); + $this->employeeModel->where('id', $employeeData['id'])->where('otp', $otp)->where('relationship', 'self')->set(['otp'=>null])->update(); } return $this->respond(['status' => 'success','code' => 200,'data' => $result],200); @@ -392,7 +541,7 @@ class RestAuthenticationController extends AdminController try { // mobile number $otp_verification = isset($this->request->getJSON()->otp_verification) ? $this->request->getJSON()->otp_verification : null; - $mobile_number = isset($this->request->getJSON()->mobile_number) ? $this->request->getJSON()->mobile_number : null; + $mobile_number = isset($this->request->getJSON()->mobile_no) ? $this->request->getJSON()->mobile_no : null; // email id $otp = isset($this->request->getJSON()->otp) ? $this->request->getJSON()->otp : null; $email = isset($this->request->getJSON()->email) ? $this->request->getJSON()->email : null; @@ -422,7 +571,7 @@ class RestAuthenticationController extends AdminController } - if(isset($this->request->getJSON()->mobile_number)){ + if(isset($this->request->getJSON()->mobile_no)){ $hrData = $this->hrModel ->select('level_contacts.* , client_branch.client_id as client_id') ->join('client_branch', 'level_contacts.ref_id = client_branch.id', 'left') @@ -441,6 +590,11 @@ class RestAuthenticationController extends AdminController ->find(); } + $HRAccessData = $this->getHRAccessData( $hrData['0']['id'] , 'post_enrollment'); + + if(isset($HRAccessData['allowed_modules'])){ $hrData['0']['allowed_modules'] = json_decode($HRAccessData['allowed_modules'],true)['post']; }else{ $hrData['0']['allowed_modules'] = []; } + + $hrData['0']['token_type'] = 'post'; $result = JWTToken::encode($hrData['0']); @@ -457,6 +611,21 @@ class RestAuthenticationController extends AdminController } + public function getHRAccessData( $hr_id = null , $request_for = 'post_enrollment') + { + $hr_id = $this->request->getGet('hr_id') ?? $hr_id; + $request_for = $this->request->getGet('request_for') ?? $request_for; + + if($request_for == 'pre_enrollment'){ $idField = 'pre_hr_id'; }else{ $idField = 'post_hr_id'; } + + $data = $this->hrAccessControlModel->where($idField , $hr_id)->where('is_active' , 1)->first(); + + if($request_for == 'post_enrollment'){ return $data ?? []; } + + return $this->respond(['status' => (($data) ? 'success' : 'failed'),'code' => (($data) ? 200 : 404),'data' => $data ], 200); + } + + public function getUserIdFromToken() { @@ -481,21 +650,60 @@ class RestAuthenticationController extends AdminController $mobile_number = isset($this->request->getJSON()->mobile_number) ? $this->request->getJSON()->mobile_number : null; $email_id = isset($this->request->getJSON()->email_id) ? $this->request->getJSON()->email_id : null; + $client_id = $this->request->getJSON()->client_id ?? null; if (isset($mobile_number)) { - $employeeData = $this->employeeModel->where('mobile', $mobile_number)->where('relationship', 'self')->first(); + // $employeeData = $this->employeeModel->where('mobile', $mobile_number)->where('relationship', 'self')->first(); + $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 { - $employeeData = $this->employeeModel->where('email_corporate', $email_id)->where('relationship', 'self')->first(); + // $employeeData = $this->employeeModel->where('email_corporate', $email_id)->where('relationship', 'self')->first(); + $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(); } $mpin = $this->request->getJSON()->mpin; + $is_mpin_skipped = $this->request->getJSON()->is_mpin_skipped; + $is_biometric_enabled = $this->request->getJSON()->is_biometric_enabled; + $mpin_data_to_updata = [ + 'mpin' => $mpin, + 'is_mpin_skipped' => $is_mpin_skipped, + 'is_biometric_enabled' => $is_biometric_enabled + ]; if ($employeeData) { $id= $employeeData["id"]; - $updateMpin = $this->employeeModel->where('id', $id)->set('mpin', $mpin)->update(); + $updateMpin = $this->employeeModel->where('id', $id)->set( $mpin_data_to_updata)->update(); if($updateMpin){ $result = ['user_verification' => true , 'message' => "Mpin Updated"]; return $this->respond(['status' => 'success','code' => 200,'data' => $result],200); @@ -511,6 +719,7 @@ class RestAuthenticationController extends AdminController } } catch (\Throwable $th) { + $this->myLogger->logme("error", ($th->getMessage().' --- '.$th->getLine())); return $this->respond(['status' => 'failed','code' => 500,'data' => $th],500); } } @@ -523,15 +732,54 @@ class RestAuthenticationController extends AdminController $email_id = isset($this->request->getJSON()->email_id) ? $this->request->getJSON()->email_id : null; $old_mpin = $this->request->getJSON()->old_mpin; $mpin = $this->request->getJSON()->new_mpin; + $client_id = $this->request->getJSON()->client_id ?? null; - if (isset($mobile_number)) - { - $employeeData = $this->employeeModel->where('mobile', $mobile_number)->where('mpin', $old_mpin)->where('relationship', 'self')->first(); - }else{ - $employeeData = $this->employeeModel->where('email_corporate', $email_id)->where('mpin', $old_mpin)->where('relationship', 'self')->first(); + // if (isset($mobile_number)) + // { + // $employeeData = $this->employeeModel->where('mobile', $mobile_number)->where('mpin', $old_mpin)->where('relationship', 'self')->first(); + // }else{ + // $employeeData = $this->employeeModel->where('email_corporate', $email_id)->where('mpin', $old_mpin)->where('relationship', 'self')->first(); + // } + + if (isset($mobile_number)) { + // $employeeData = $this->employeeModel->where('mobile', $mobile_number)->where('mpin', $old_mpin)->where('relationship', 'self')->first(); + $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']) + ->where('employees.mpin', $old_mpin); + + if (!empty($client_id)) { + $builder->where('employees.client_id', $client_id); + } + + $employeeData = $builder->orderBy('employees.id', 'desc')->first(); + + } else { + // $employeeData = $this->employeeModel->where('email_corporate', $email_id)->where('mpin', $old_mpin)->where('relationship', 'self')->first(); + $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']) + ->where('employees.mpin', $old_mpin); + + if (!empty($client_id)) { + $builder->where('employees.client_id', $client_id); + } + + $employeeData = $builder->orderBy('employees.id', 'desc')->first(); } - if ($employeeData) { $id= $employeeData["id"]; @@ -551,49 +799,164 @@ class RestAuthenticationController extends AdminController } } catch (\Throwable $th) { + $this->myLogger->logme("error", ($th->getMessage().' --- '.$th->getLine())); return $this->respond(['status' => 'failed','code' => 500,'data' => $th],500); } } + // public function verifyMpin() + // { + // try { + + // $mobile_number = isset($this->request->getJSON()->mobile_number) ? $this->request->getJSON()->mobile_number : null; + // $email_id = isset($this->request->getJSON()->email_id) ? $this->request->getJSON()->email_id : null; + // $mpin = $this->request->getJSON()->mpin; + // if (isset($mobile_number)) + // { + // // $employeeData = $this->employeeModel->where('mobile', $mobile_number)->where('relationship', 'self')->first(); + // $employeeData = $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']) + // ->get(); + // }else{ + // // $employeeData = $this->employeeModel->where('email_corporate', $email_id)->where('relationship', 'self')->first(); + // $employeeData = $this->employeeModel + // ->select('employees.*') + // ->join('employee_polices', 'employees.id = employee_polices.employee_id') + // ->where('employees.email_corporate', $email_id) + // ->where('employee_polices.is_active', 1) + // ->whereIn('employee_polices.status', ['active']) + // ->where('employees.is_active', 1) + // ->whereIn('employees.emp_status', ['active']) + // ->where("employees.relationship", "Self") // RAW SQL condition + // ->first(); + + // } + // if ($employeeData && $mpin == $employeeData["mpin"]) { + + // $auth = HttpRequestHelper::getRequestInfo(); + // if ($auth) { + // $data = [ + // 'user_id' => $employeeData['id'], + // 'user_type' => 'employee', + // 'ip' => $auth['ip'], + // 'platform' => $auth['platform'], + // 'broswer' => $auth['browser'], + // ]; + + // $authdata= $this->authHistoryModel->insert($data); + + // } + + // $result = JWTToken::encode($employeeData); + // // $result = $employeeData; + // return $this->respond(['status' => 'success','code' => 200,'data' => $result],200); + // } else { + // return $this->respond(['status' => 'failed','code' => 404,'data' => "Invalid OTP"],200); + // } + // } catch (\Exception $e) { + // return $this->respond(['status' => 'failed','code' => 500,'data' => $e->getMessage()],500); + // } + // } + public function verifyMpin() { try { + $requestData = $this->request->getJSON(true); - $mobile_number = isset($this->request->getJSON()->mobile_number) ? $this->request->getJSON()->mobile_number : null; - $email_id = isset($this->request->getJSON()->email_id) ? $this->request->getJSON()->email_id : null; - $mpin = $this->request->getJSON()->mpin; - if (isset($mobile_number)) - { - $employeeData = $this->employeeModel->where('mobile', $mobile_number)->where('relationship', 'self')->first(); - }else{ - $employeeData = $this->employeeModel->where('email_corporate', $email_id)->where('relationship', 'self')->first(); + $mobile_number = $requestData['mobile_number'] ?? null; + $email_id = $requestData['email_id'] ?? null; + $mpin = $requestData['mpin'] ?? null; + $client_id = $requestData['client_id'] ?? null; + // print_r($mpin); + + if (!$mpin) { + return $this->respond(['status' => 'failed', 'code' => 400, 'data' => 'MPIN is required'], 400); } - if ($employeeData && $mpin == $employeeData["mpin"]) { - $auth = HttpRequestHelper::getRequestInfo(); - if ($auth) { - $data = [ - 'user_id' => $employeeData['id'], - 'user_type' => 'employee', - 'ip' => $auth['ip'], - 'platform' => $auth['platform'], - 'broswer' => $auth['browser'], - ]; + if ($mobile_number) { - $authdata= $this->authHistoryModel->insert($data); - + $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(); - $result = JWTToken::encode($employeeData); - // $result = $employeeData; - return $this->respond(['status' => 'success','code' => 200,'data' => $result],200); + } 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' => 404,'data' => "Invalid OTP"],200); + return $this->respond(['status' => 'failed', 'code' => 400, 'data' => 'Mobile number or Email ID is required'], 400); + } + + // print_r($employeeData); die; + + if ($employeeData && isset($employeeData['mpin']) && $mpin === $employeeData['mpin']) { + + $auth = HttpRequestHelper::getRequestInfo(); + if ($auth) { + $this->authHistoryModel->insert([ + 'user_id' => $employeeData['id'], + 'user_type' => 'employee', + 'ip' => $auth['ip'], + 'platform' => $auth['platform'], + 'broswer' => $auth['browser'], // Note: typo in 'broswer' retained if it's your actual DB field + ]); + } + + $token = JWTToken::encode($employeeData); + + return $this->respond([ + 'status' => 'success', + 'code' => 200, + 'data' => $token + ], 200); + } else { + return $this->respond([ + 'status' => 'failed', + 'code' => 404, + 'data' => 'Invalid MPIN' + ], 200); } } catch (\Exception $e) { - return $this->respond(['status' => 'failed','code' => 500,'data' => $e->getMessage()],500); + $this->myLogger->logme("error", ($e->getMessage().' --- '.$e->getLine())); + return $this->respond([ + 'status' => 'failed', + 'code' => 500, + 'data' => $e->getMessage() + ], 500); } } @@ -603,28 +966,169 @@ class RestAuthenticationController extends AdminController $mobile_number = isset($this->request->getJSON()->mobile_number) ? $this->request->getJSON()->mobile_number : null; $email_id = isset($this->request->getJSON()->email_id) ? $this->request->getJSON()->email_id : null; // $mpin = $this->request->getJSON()->mpin; + $client_id = $this->request->getJSON()->client_id ?? null; + if (isset($mobile_number)) { - $employeeData = $this->employeeModel->where('mobile', $mobile_number)->where('relationship', 'self')->first(); - }else{ - $employeeData = $this->employeeModel->where('email_corporate', $email_id)->where('relationship', 'self')->first(); - } - + // $employeeData = $this->employeeModel->where('mobile', $mobile_number)->where('relationship', 'self')->first(); + $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{ + // $employeeData = $this->employeeModel->where('email_corporate', $email_id)->where('relationship', 'self')->first(); + $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(); + } if ($employeeData && $employeeData["mpin"] != null) { - return $this->respond(['status' => 'success','code' => 200,'data' => "Mpin - exist" , 'Mpin' =>$employeeData["mpin"]],200); + return $this->respond(['status' => 'success','code' => 200,'data' => "Mpin - exist" , 'Mpin' =>$employeeData["mpin"], 'is_mpin_skipped' => $employeeData['is_mpin_skipped'], 'is_biometric_enabled' => $employeeData['is_biometric_enabled']],200); } else { return $this->respond(['status' => 'failed','code' => 404,'data' => "Mpin - not found", 'Mpin' =>null],200); } } catch (\Exception $e) { + $this->myLogger->logme("error", ($e->getMessage().' --- '.$e->getLine())); return $this->respond(['status' => 'failed','code' => 500,'data' => $e->getMessage()],500); } } + public function forgotMPIN() + { + try { + log_message('info', 'forgotMPIN() called.'); + + $json = $this->request->getJSON(); + $mobile_number = $json->mobile_number ?? null; + $email_id = $json->email_id ?? null; + $client_id = $json->client_id ?? null; + + log_message('info', 'Received input - Mobile: ' . var_export($mobile_number, true) . ', Email: ' . var_export($email_id, true)); + + // Step 1: Check input + if (!$mobile_number && !$email_id) { + log_message('error', 'Mobile number and email ID are both missing.'); + return $this->respond([ + 'status' => 'failed', + 'code' => 400, + 'message' => 'Mobile number or email ID is required.' + ], 400); + } + + // Step 2: Fetch employee data + if ($mobile_number) { + + log_message('info', 'Looking up employee by mobile number: ' . $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) + ->where('employee_polices.status', ['active']) + ->where('employees.is_active', 1) + ->where('employees.emp_status', ['active']); + + if (!empty($client_id)) { + $builder->where('employees.client_id', $client_id); + } + + $employeeData = $builder->orderBy('employees.id', 'desc')->first(); + + } else { + + log_message('info', 'Looking up employee by email: ' . $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) + ->where('employee_polices.status', ['active']) + ->where('employees.is_active', 1) + ->where('employees.emp_status', ['active']); + + if (!empty($client_id)) { + $builder->where('employees.client_id', $client_id); + } + + $employeeData = $builder->orderBy('employees.id', 'desc')->first(); + } + + log_message('info', '$employeeData : ' . json_encode($employeeData)); + + // Step 3: Found employee + if (!empty($employeeData)) { + log_message('info', 'Employee found: ID = ' . $employeeData['id']); + + $updateData = [ + 'mpin' => null, + 'is_mpin_skipped' => null, + 'is_biometric_enabled' => null + ]; + + log_message('info', 'Updating employee MPIN fields to null for ID: ' . $employeeData['id']); + + $updated = $this->employeeModel + ->where('id', $employeeData['id']) + ->set($updateData) + ->update(); + + if ($updated) { + log_message('info', 'MPIN reset successful for employee ID: ' . $employeeData['id']); + return $this->respond([ + 'status' => 'success', + 'code' => 200, + 'message' => 'MPIN reset successfully.' + ], 200); + } else { + log_message('error', 'Failed to update MPIN fields for employee ID: ' . $employeeData['id']); + return $this->respond([ + 'status' => 'failed', + 'code' => 500, + 'message' => 'Could not reset MPIN values.', + ], 500); + } + } else { + // Step 4: Not found in local DB — call external fallback + log_message('warning', 'Employee not found locally. Falling back to third-party API.'); + return $this->respond(['status' => 'failed','code' => 404,'data' => "Employee not found"],200); } + } catch (\Throwable $e) { + $this->myLogger->logme("error", ($e->getMessage().' --- '.$e->getLine())); + return $this->respond([ + 'status' => 'failed', + 'code' => 500, + 'message' => 'Server error: ' . $e->getMessage() + ], 500); + } + } + // TokenController.php public function bookstackLoginToken() @@ -651,6 +1155,81 @@ class RestAuthenticationController extends AdminController return redirect()->to($url); } + public function getPostEmployeeDataForAuth() + { + $params = $this->request->getJSON(true); + // print_r( $params); die; + + $mobile_number = $params['mobile_number'] ?? null; + $email_id = $params['email_id'] ?? null; + $otp = $params['otp'] ?? null; + $old_mpin = $params['old_mpin'] ?? null; + + if (empty($mobile_number) && empty($email_id)) { + return $this->respond([ + 'status' => 'failed', + 'message' => 'Mobile number or Email ID is required.', + 'data' => [], + ], 400); + } + + if (!empty($mobile_number)) { + + $builder = $this->employeeModel + ->select('employees.id as employee_id, employees.*') + ->join('employee_polices EP', 'EP.employee_id = employees.id', 'inner') + ->where('employees.is_active', 1) + ->where("TRIM(employees.relationship) = 'self'", null, false) + ->whereIn('employees.emp_status', ['active', 'expired']) + ->where('employees.mobile', $mobile_number) + ->where('EP.is_active', 1) + ->whereIn('EP.status', ['active', 'expired']); + + if (!empty($old_mpin)) { + $builder->where('employees.mpin', $old_mpin); + } + + $employeeData = $builder->orderBy('employees.id', 'desc')->first(); + + } else { + $builder = $this->employeeModel + ->select('employees.id as employee_id, employees.*') + ->join('employee_polices EP', 'EP.employee_id = employees.id', 'inner') + ->where('employees.is_active', 1) + ->where("TRIM(employees.relationship) = 'self'", null, false) + ->whereIn('employees.emp_status', ['active', 'expired']) + ->where('employees.email_corporate', $email_id) + ->where('EP.is_active', 1) + ->whereIn('EP.status', ['active', 'expired']); + + if (!empty($otp)) { + $builder->where('employees.otp', $otp); + } + + if (!empty($old_mpin)) { + $builder->where('employees.mpin', $old_mpin); + } + + $employeeData = $builder->orderBy('employees.id', 'desc')->first(); + } + + if ($employeeData) { + + $client_data = $this->clientModel->where('is_active', 1)->where('id', $employeeData['client_id'])->first(); + $employeeData['client_short_name'] = $client_data['short_name']; + + return $this->respond([ + 'status' => 'success', + 'data' => $employeeData, + ], 200); + } + + return $this->respond([ + 'status' => 'failed', + 'message' => 'No employee found.', + 'data' => [], + ], 404); + } diff --git a/app/Controllers/TestBusinessController.php b/app/Controllers/TestBusinessController.php new file mode 100644 index 00000000..7f317fb2 --- /dev/null +++ b/app/Controllers/TestBusinessController.php @@ -0,0 +1,30 @@ +callWithTrace('b',50,10); + $r = $this->b(50,10); + + return json_encode(['a' => $r]); + // return view('welcome_message'); + } + + public function b($x, $y) + { + // print_rr(debug_backtrace(0)); + return $x + $y; + } +} + + diff --git a/app/Controllers/TicketController.php b/app/Controllers/TicketController.php index 1807f9b9..139b63e1 100644 --- a/app/Controllers/TicketController.php +++ b/app/Controllers/TicketController.php @@ -152,6 +152,88 @@ class TicketController extends BaseController 53 => ['cancel_remark'], 58 => ['cancel_remark'], ]; + + $this->extraFieldsDisplayForFrontend = [ + 1 => [ 'non_id_reason' => 'Non ID Reason' ], + 10 => [ 'pay_initiate_date' => 'Payment Initiated Date' ], + 3 => [ 'raised_date' => 'Raised Date' ], + 4 => [ 'raised_date' => 'Raised Date' ], + 5 => [ + 'claim_number' => 'Claim Number', + 'registration_date' => 'Registration Date' + ], + 7 => [ 'query_received_date' => 'Query Received Date' ], + 8 => [ + 'denial_reason' => 'Denial Reason', + 'denial_date' => 'Denial Date' + ], + 9 => [ + 'approved_amount' => 'Approved Amount', + 'approved_date' => 'Approved Date', + 'approved_letter' => 'Approved Letter', + 'approved_description' => 'Approved Description' + ], + 11 => [ + 'utr_details' => 'UTR Details', + 'settled_date' => 'Settled Date', + 'settle_letter' => 'Settle Letter' + ], + 40 => [ + 'approved_amount' => 'Approved Amount', + 'approved_date' => 'Approved Date', + 'approved_letter' => 'Approved Letter', + 'approved_description' => 'Approved Description' + ], + 44 => [ + 'utr_details' => 'UTR Details', + 'settled_date' => 'Settled Date', + 'settle_letter' => 'Settle Letter' + ], + 30 => [ + 'approved_amount' => 'Approved Amount', + 'approved_date' => 'Approved Date', + 'approved_letter' => 'Approved Letter', + 'approved_description' => 'Approved Description' + ], + 34 => [ + 'utr_details' => 'UTR Details', + 'settled_date' => 'Settled Date', + 'settle_letter' => 'Settle Letter' + ], + 20 => [ + 'approved_amount' => 'Approved Amount', + 'approved_date' => 'Approved Date', + 'approved_letter' => 'Approved Letter', + 'approved_description' => 'Approved Description' + ], + 24 => [ + 'utr_details' => 'UTR Details', + 'settled_date' => 'Settled Date', + 'settle_letter' => 'Settle Letter' + ], + 14 => [ + 'return_remark' => 'Return Remark', + 'awb_no_courier_name' => 'AWB No Courier Name' + ], + 48 => [ + 'return_remark' => 'Return Remark', + 'awb_no_courier_name' => 'AWB No Courier Name' + ], + 59 => [ + 'return_remark' => 'Return Remark', + 'awb_no_courier_name' => 'AWB No Courier Name' + ], + 54 => [ + 'return_remark' => 'Return Remark', + 'awb_no_courier_name' => 'AWB No Courier Name' + ], + 13 => [ 'cancel_remark' => 'Cancel Remark' ], + 47 => [ 'cancel_remark' => 'Cancel Remark' ], + 53 => [ 'cancel_remark' => 'Cancel Remark' ], + 58 => [ 'cancel_remark' => 'Cancel Remark' ] +]; + + $this->nonIDReason = [ "Newborn Baby" => "Newborn Baby", "Newly Wedded Spouse" => "Newly Wedded Spouse", @@ -1854,7 +1936,7 @@ class TicketController extends BaseController $this->loadLayout("ticket_feedback_list",$data); } - public function getMoreInfo($requestFrom = null , $ticket_id) { + public function getMoreInfo($requestFrom = null , $ticket_id = null) { if($requestFrom == null){ $ticket_id = $this->request->getPost('ticket_id'); @@ -1863,6 +1945,7 @@ class TicketController extends BaseController $this->myLogger->logme("error", "Ticket ID : " . $ticket_id); $fields = $this->extraFields; + $displayFields = $this->extraFieldsDisplayForFrontend; $data_to_send = []; // Get ticket data @@ -1878,16 +1961,18 @@ class TicketController extends BaseController ->groupBy("th.old_value, tcs.claim_status") ->get() ->getResultArray(); - + // dd($ticket_previous_status); // Loop through previous status and gather the required data foreach ($ticket_previous_status as $status) { - $this->myLogger->logme("error", "Status : " . json_encode($status)); + // $this->myLogger->logme("error", "Status : " . json_encode($status)); if (isset($fields[$status['old_value']])) { $field = $fields[$status['old_value']]; - + // print_r($field); // Ensure claim_status is a scalar value (string or int) $claim_status = (string)$status['claim_status']; // Cast to string to avoid issues + // echo $claim_status; + // dd($displayFields[$status['old_value']]); // Initialize claim_status if it doesn't exist in the array if (!isset($data_to_send[$claim_status])) { @@ -1897,31 +1982,34 @@ class TicketController extends BaseController // Handle case where $field is an array if (is_array($field)) { foreach ($field as $f) { + // dd($displayFields[$status['old_value']]); // Check if the field exists in the ticket data - $data_to_send[$claim_status][$f] = isset($ticket_data[$f]) ? $ticket_data[$f] : null; - + $data_to_send[$claim_status][$f] = ['display_name' => $displayFields[$status['old_value']][$f] ,'display_value' => isset($ticket_data[$f]) ? $ticket_data[$f] : null]; + // dd($data_to_send); // Check if the field contains a date and format it - if ($this->isDate($data_to_send[$claim_status][$f])) { - $data_to_send[$claim_status][$f] = date('d-m-Y', strtotime($data_to_send[$claim_status][$f])); + if ($this->isDate($data_to_send[$claim_status][$f]['display_value'])) { + $data_to_send[$claim_status][$f] = ['display_name' => $displayFields[$status['old_value']][$f] ,'display_value' => date('d-m-Y', strtotime($data_to_send[$claim_status][$f]['display_value']))]; + // $data_to_send[$claim_status][$f] = date('d-m-Y', strtotime($data_to_send[$claim_status][$f])); } - $this->myLogger->logme("error", "Data for field {$f}: " . json_encode($data_to_send[$claim_status][$f])); + // $this->myLogger->logme("error", "Data for field {$f}: " . json_encode($data_to_send[$claim_status][$f])); } } else { // If field is not an array, handle it as a single field - $data_to_send[$claim_status][$field] = isset($ticket_data[$field]) ? $ticket_data[$field] : null; + // Check if the field exists in the ticket data + $data_to_send[$claim_status][$f] = ['display_name' => $displayFields[$status['old_value']][$f] ,'display_value' => isset($ticket_data[$f]) ? $ticket_data[$f] : null]; // Check if the field contains a date and format it if ($this->isDate($data_to_send[$claim_status][$field])) { - $data_to_send[$claim_status][$field] = date('d-m-Y', strtotime($data_to_send[$claim_status][$field])); + $data_to_send[$claim_status][$f] = ['display_name' => $displayFields[$status['old_value']][$f] ,'display_value' => date('d-m-Y', strtotime($data_to_send[$claim_status][$f]['display_value']))]; } - $this->myLogger->logme("error", "Data for field {$field}: " . json_encode($data_to_send[$claim_status][$field])); + // $this->myLogger->logme("error", "Data for field {$field}: " . json_encode($data_to_send[$claim_status][$field])); } } } - $this->myLogger->logme('error', "Total data: " . json_encode($data_to_send)); + // $this->myLogger->logme('error', "Total data: " . json_encode($data_to_send)); if($requestFrom == 'rest'){ return $data_to_send; diff --git a/app/Controllers/TraceableController.php b/app/Controllers/TraceableController.php new file mode 100644 index 00000000..e1562c93 --- /dev/null +++ b/app/Controllers/TraceableController.php @@ -0,0 +1,127 @@ +logFile = $logFile; + } + + public function wrap($instance) + { + $handler = $this; + $class = new ReflectionClass($instance); + + foreach ($class->getMethods(ReflectionMethod::IS_PUBLIC) as $method) { + if ($method->isConstructor() || $method->isStatic()) continue; + + $methodName = $method->getName(); + $instance->$methodName = function(...$args) use ($handler, $instance, $methodName) { + return $handler->logCall($instance, $methodName, $args); + }; + } + + return $instance; + } + + public function logCall($instance, $method, $args) + { + $isRootCall = (self::$callDepth === 0); + if ($isRootCall) { + self::$currentUuid = $this->generateUuid(); + } + self::$callDepth++; + + $reflection = new ReflectionMethod($instance, $method); + + // Log IN + $this->writeLog([ + 'timestamp' => date('Y-m-d H:i:s'), + 'uuid' => self::$currentUuid, + 'direction' => 'IN', + 'function' => get_class($instance) . '::' . $method, + 'line' => $reflection->getStartLine(), + 'params' => $this->getParameterValues($reflection, $args) + ]); + + try { + $result = $reflection->invokeArgs($instance, $args); + + // Log OUT + $this->writeLog([ + 'timestamp' => date('Y-m-d H:i:s'), + 'uuid' => self::$currentUuid, + 'direction' => 'OUT', + 'function' => get_class($instance) . '::' . $method, + 'line' => $reflection->getEndLine(), + 'result' => $result + ]); + + return $result; + } finally { + self::$callDepth--; + if ($isRootCall) { + self::$currentUuid = null; + } + } + } + + private function getParameterValues($reflection, $args) + { + $params = []; + foreach ($reflection->getParameters() as $i => $param) { + $params[$param->name] = $args[$i] ?? ($param->isDefaultValueAvailable() + ? $param->getDefaultValue() + : null); + } + return $params; + } + + private function writeLog($data) + { + file_put_contents($this->logFile, json_encode($data) . PHP_EOL, FILE_APPEND); + } + + private function generateUuid() + { + return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x', + mt_rand(0, 0xffff), mt_rand(0, 0xffff), + mt_rand(0, 0xffff), + mt_rand(0, 0x0fff) | 0x4000, + mt_rand(0, 0x3fff) | 0x8000, + mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff) + ); + } +} + +class TestBusinessController +{ + public function a($a = 10) + { + $r = $this->b(50, $a); + return json_encode(['a' => $r]); + } + + public function b($x, $y) + { + $r = $this->c($x + $y); + return $r; + } + + public function c($x) + { + return $x * 2; + } +} + +// Usage: +$logger = new DeepLogger(); +$controller = new TestBusinessController(); +$loggedController = $logger->wrap($controller); + +// This will now log all calls (a, b, and c) +echo $loggedController->a(10); \ No newline at end of file diff --git a/app/Helpers/api_helper.php b/app/Helpers/api_helper.php new file mode 100644 index 00000000..de9a0b64 --- /dev/null +++ b/app/Helpers/api_helper.php @@ -0,0 +1,68 @@ +'; + // print_r($headers); + // print_r($body); + // die; + + // Setup curl options + $options = [ + CURLOPT_URL => $url, + CURLOPT_RETURNTRANSFER => true, + CURLOPT_CUSTOMREQUEST => $method, + CURLOPT_HTTPHEADER => $headers, + ]; + + // Only include body for applicable methods + if (!empty($body) && in_array($method, ['POST', 'PUT', 'PATCH', 'DELETE'])) { + if (stripos($contentType, 'application/json') !== false) { + $options[CURLOPT_POSTFIELDS] = json_encode($body); + } elseif (stripos($contentType, 'application/x-www-form-urlencoded') !== false) { + $options[CURLOPT_POSTFIELDS] = http_build_query($body); + } elseif (stripos($contentType, 'multipart/form-data') !== false) { + $options[CURLOPT_POSTFIELDS] = $body; // For file uploads or multipart fields + } else { + // Default fallback + $options[CURLOPT_POSTFIELDS] = $body; + } + } + + curl_setopt_array($ch, $options); + + $response = curl_exec($ch); + $error = curl_error($ch); + $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); + + curl_close($ch); + + if ($error) { + return [ + 'status' => false, + 'message' => 'Curl error: ' . $error + ]; + } + + $decoded = json_decode($response, true); + return [ + 'status' => ($httpCode >= 200 && $httpCode < 300), + 'data' => $decoded ?: $response, // fallback to raw response + 'code' => $httpCode + ]; + } +} diff --git a/app/Helpers/excel_util_helper.php b/app/Helpers/excel_util_helper.php index 141fe725..00dc0a9d 100755 --- a/app/Helpers/excel_util_helper.php +++ b/app/Helpers/excel_util_helper.php @@ -252,12 +252,12 @@ if (!function_exists('check_si')) { if (!$is_si_found && $slab_value['si'] == $received_si) //match si amount { - // echo 'found'; + echo 'found - ' . $slab_value['si']. ' - ' . $received_si; $is_si_found = true; } // check age slab - if (in_array(strtoupper($row['current_action']), ['I', 'A', 'DA', 'MI']) && (($slab_value['premium_type'] == 1 && strtolower($row['5']) == 'self') || ($slab_value['premium_type'] == 2))) { + if (in_array(strtoupper($row['current_action']), ['I', 'A', 'DA', 'MI']) && (($slab_value['premium_type'] == 1 && strtolower($row['5']) == 'self') || ($slab_value['premium_type'] == 2) || ($slab_value['premium_type'] == 3))) { if ($row[3] != '' && $row[3] != null) // dob { $dob = convert_string_to_date($row[3]); @@ -298,7 +298,7 @@ if (!function_exists('check_si')) { $return_array['status'] = false; $return_array['error'] = "Sum insured value mandantory"; } - + // !Kint::dump($return_array); return $return_array; } } @@ -475,7 +475,7 @@ if (!function_exists('name_and_empid_check_in_db')) { ->where("ep.is_active", 1) ->where("ep.status", 'active') // ->where("ep.client_id",$client_id) - ->where('name', trim($row[2]))->where('emp_code', trim($row[1])) + ->where('TRIM(name)', trim($row[2]))->where('TRIM(emp_code)', trim($row[1])) ->findAll(); // kint::dump($employeeModel->getLastQuery()->getQuery()); diff --git a/app/Libraries/CustomTraceLogger.php b/app/Libraries/CustomTraceLogger.php new file mode 100644 index 00000000..7ca66b28 --- /dev/null +++ b/app/Libraries/CustomTraceLogger.php @@ -0,0 +1,42 @@ +logFile = $logDir . 'trace-' . date('Y-m-d') . '.log'; + } + + public function log($direction, $functionName, $lineNo, $params = []) + { + try { + $uuid = get_session_uuid(); + + $logEntry = [ + 'timestamp' => date('c'), + 'uuid' => $uuid, + 'direction' => $direction, // IN or OUT + 'function' => $functionName, + 'line' => $lineNo, + 'params' => $params, + ]; + + file_put_contents( + $this->logFile, + json_encode($logEntry) . PHP_EOL, + FILE_APPEND | LOCK_EX + ); + } catch (Throwable $e) { + // Don’t break anything if logging fails + } + } +} diff --git a/app/Models/ClientPolicyModel.php b/app/Models/ClientPolicyModel.php index 59f05958..f571659e 100755 --- a/app/Models/ClientPolicyModel.php +++ b/app/Models/ClientPolicyModel.php @@ -168,25 +168,48 @@ class ClientPolicyModel extends Model } - public function getinsurerswithclientid($id) + public function getinsurerswithclientid($id, $policyId = null) { + // dd($policyId); - return $this->db->table('client_policy') - ->select('client_policy.*, cd_master.cd_ac_no as cd_master_account_no') - ->select('insurers.name as insurer_name, insurers.short_name as insurer_short') - ->select('clients.client_name as client_name') - ->join('clients', 'clients.id=client_policy.client_id') - ->join('insurers', 'insurers.id = client_policy.insurer_id') - ->join('cd_master', 'cd_master.insurer_id = insurers.id AND cd_master.client_id = client_policy.client_id') - ->where('client_policy.client_id', $id) - ->where('cd_master.id = client_policy.cd_ac_pk') - ->where('cd_master.is_active', 1) - ->groupBy('client_policy.client_id', $id) // Group by insurer_id - ->groupBy('client_policy.insurer_id') - ->groupBy('client_policy.cd_ac_pk') - ->get() - ->getResult(); + $builder = $this->db->table('client_policy') + ->select('client_policy.*, cd_master.cd_ac_no as cd_master_account_no') + ->select('insurers.name as insurer_name, insurers.short_name as insurer_short') + ->select('clients.client_name as client_name') + ->join('clients', 'clients.id = client_policy.client_id') + ->join('insurers', 'insurers.id = client_policy.insurer_id') + ->join('cd_master', 'cd_master.insurer_id = insurers.id AND cd_master.client_id = client_policy.client_id') + ->where('client_policy.client_id', $id) + ->where('cd_master.id = client_policy.cd_ac_pk') + ->where('cd_master.is_active', 1) + ->groupBy('client_policy.client_id') + ->groupBy('client_policy.insurer_id') + ->groupBy('client_policy.cd_ac_pk'); + if ($policyId != null) { + $builder->whereIn('client_policy.id', $policyId); + } + + return $builder->get()->getResult(); + + + + // return $this->db->table('client_policy') + // ->select('client_policy.*, cd_master.cd_ac_no as cd_master_account_no') + // ->select('insurers.name as insurer_name, insurers.short_name as insurer_short') + // ->select('clients.client_name as client_name') + // ->join('clients', 'clients.id=client_policy.client_id') + // ->join('insurers', 'insurers.id = client_policy.insurer_id') + // ->join('cd_master', 'cd_master.insurer_id = insurers.id AND cd_master.client_id = client_policy.client_id') + // ->where('client_policy.client_id', $id) + // ->where('cd_master.id = client_policy.cd_ac_pk') + // ->where('cd_master.is_active', 1) + // ->groupBy('client_policy.client_id', $id) // Group by insurer_id + // ->groupBy('client_policy.insurer_id') + // ->groupBy('client_policy.cd_ac_pk') + // ->get() + // ->getResult(); + // return $this->db->table('client_policy') // ->select('insurers.name as insurer_name, insurers.short_name as insurer_short') // ->select('clients.client_name as client_name') @@ -226,8 +249,19 @@ class ClientPolicyModel extends Model } - public function getDepositData($clientId, $insurerId, $cd_ac_pk = null) - { + public function getDepositData($clientId, $insurerId, $cd_ac_pk = null, $subTypeOptions = null) + { + + if($subTypeOptions != null){ + $caseSql = "CASE cash_deposit.sub_type"; + foreach ($subTypeOptions as $key => $label) { + $caseSql .= " WHEN {$key} THEN " . $this->db->escape($label); + } + $caseSql .= " ELSE 'Unknown' END AS sub_type_text"; + }else{ + $caseSql = ""; + } + // Fetch the deposit data based on client and insurer IDs $query = $this->db->table('cash_deposit') ->select('cash_deposit.*') @@ -237,6 +271,7 @@ class ClientPolicyModel extends Model // ->select('policies.name as policy_name') ->select('policy_type.policy_type') ->select('user_profiles.first_name as username') + ->select($caseSql) ->join('user_profiles', 'user_profiles.id = cash_deposit.created_by', 'left') ->join('insurers', 'insurers.id = cash_deposit.insurer_id', 'left') ->join('clients', 'clients.id = cash_deposit.client_id', 'left') @@ -246,7 +281,8 @@ class ClientPolicyModel extends Model ->join('policy_type', 'policy_type.id = client_policy.policy_type_id', 'left') ->where('cash_deposit.client_id', $clientId) ->where('cash_deposit.insurer_id', $insurerId) - ->where('cash_deposit.is_active', 1); + ->where('cash_deposit.is_active', 1) + ->where('cd_master.is_active', 1); // ->where('cash_deposit.cd_ac_pk = cd_master.id') if(!empty($cd_ac_pk)){ $query->where('cash_deposit.cd_ac_pk', $cd_ac_pk); @@ -319,15 +355,32 @@ class ClientPolicyModel extends Model public function getDepositlistsummary($id) { - return $this->db->table('cash_deposit') - ->select('insurer_id, cd_ac_pk') - ->select('SUM(CASE WHEN transaction_type = "Credit" THEN amount ELSE -amount END) AS balance') - ->where('client_id', $id) - ->where('is_active', 1) - ->groupBy('insurer_id') - // ->groupBy('cd_ac_pk') - ->get() - ->getResult(); + // return $this->db->table('cash_deposit') + // ->select('insurer_id, cd_ac_pk, balance') + // // ->select('SUM(CASE WHEN transaction_type = "Credit" THEN amount ELSE -amount END) AS balance') + // ->where('client_id', $id) + // ->where('is_active', 1) + // ->orderBy('id', 'desc') + // ->groupBy('insurer_id') + // // ->groupBy('cd_ac_pk') + // ->get() + // ->getResult(); + + $sql = " + SELECT cd.insurer_id, cd.cd_ac_pk, cd.balance + FROM cash_deposit cd + INNER JOIN ( + SELECT insurer_id, MAX(id) AS max_id + FROM cash_deposit + WHERE client_id = ? + AND is_active = 1 + GROUP BY insurer_id + ) latest ON cd.insurer_id = latest.insurer_id AND cd.id = latest.max_id + ORDER BY cd.id DESC + "; + + return $this->db->query($sql, [$id])->getResult(); + } diff --git a/app/Models/EmployeeModel.php b/app/Models/EmployeeModel.php index 6f4af68b..1bc55f06 100755 --- a/app/Models/EmployeeModel.php +++ b/app/Models/EmployeeModel.php @@ -42,7 +42,9 @@ class EmployeeModel extends Model "token_time_out", "emp_type", "unit", - "mpin" + "mpin", + "is_mpin_skipped", + "is_biometric_enabled", ]; // Callbacks @@ -269,6 +271,8 @@ class EmployeeModel extends Model ->join('employee_polices', 'employees.id = employee_polices.employee_id', 'left') ->where('employees.is_active', 1) ->where('employee_polices.is_active', 1) + ->where('employees.emp_status', "active") + ->where('employee_polices.status', "active") ->where('employees.emp_code', $emp_code); if(!empty($client_id)){ diff --git a/app/Models/EmployeePolicyModel.php b/app/Models/EmployeePolicyModel.php index f6ff81ed..ec4b9222 100755 --- a/app/Models/EmployeePolicyModel.php +++ b/app/Models/EmployeePolicyModel.php @@ -224,7 +224,28 @@ class EmployeePolicyModel extends Model public function getEmployeePolicy($client_id = 0, $policy_id = 0, $status = [], $branch_id = 0, $emp_code = "", $emp_name = "") { // dd($status); - + $ecard_download_link = " + CASE + WHEN + LOWER(emp.relationship) = 'self' AND + employee_polices.tpa_id IS NOT NULL AND employee_polices.tpa_id != '' AND + employee_polices.uhid IS NOT NULL AND employee_polices.uhid != '' + THEN + CASE + WHEN + (employee_polices.tpa_id IS NOT NULL AND employee_polices.tpa_id != '') + AND + (employee_polices.uhid IS NOT NULL AND employee_polices.uhid != '') + THEN + CONCAT('" . base_url('download-e-card/') . "', employee_polices.rand_string, '/1') + ELSE + null + END + ELSE + NULL + END AS ecard_download_link + "; + $result = $this->select([ 'employee_polices.*', 'policy_type.policy_type as policy_name', @@ -257,6 +278,7 @@ class EmployeePolicyModel extends Model 'client_branch.branch_code as client_branch_code', 'cp.policy_no', 'cp.policy_type_id', + $ecard_download_link ]) ->join('employees emp', 'employee_polices.employee_id = emp.id') ->join('client_policy cp', 'employee_polices.client_policy_id = cp.id') //cp - client policy @@ -603,6 +625,7 @@ class EmployeePolicyModel extends Model $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 = '')"; $query = $this->db->query(" @@ -676,6 +699,7 @@ class EmployeePolicyModel extends Model CAST(MAX(CASE WHEN field_name = 'premium' THEN old_value END) AS DECIMAL(10,2)) AS old_si_premium, MAX(CASE WHEN field_name = 'si_enhancement_date' THEN new_value END) AS date_of_coverage FROM emp_endorsement + $subquery_endorsement_condition GROUP BY emp_code ) AS sidata ON a.emp_code = sidata.emp_code WHERE employee_polices.client_policy_id = '{$client_policy_id}' diff --git a/app/Models/FileModel.php b/app/Models/FileModel.php index c6f04f63..5b27a7d4 100755 --- a/app/Models/FileModel.php +++ b/app/Models/FileModel.php @@ -19,7 +19,8 @@ class FileModel extends Model "client_id", "policy_id", "client_branch_id", - "uploaded_by" + "uploaded_by", + "updated_by" ]; diff --git a/app/Models/HRAccessControlModel.php b/app/Models/HRAccessControlModel.php new file mode 100644 index 00000000..a9a4e2c7 --- /dev/null +++ b/app/Models/HRAccessControlModel.php @@ -0,0 +1,60 @@ +where('client_policy.insurer_id', $insurerId) ->where('client_policy.client_id', $client_id) ->where('cd_master.id = client_policy.cd_ac_pk') + ->where('cd_master.is_active', 1) ->get(); if ($query->resultID->num_rows > 0) { diff --git a/app/Models/UserModel.php b/app/Models/UserModel.php index ed5a8ace..8a5eff7d 100755 --- a/app/Models/UserModel.php +++ b/app/Models/UserModel.php @@ -112,6 +112,7 @@ class UserModel extends Model ->join('user_teams', 'user_profiles.id = user_teams.user_id') ->where('user_profiles.id', $user_id) ->where('user_teams.is_active', 1) + ->where("user_profiles.is_active", 1) ->get() ->getResultArray(); diff --git a/app/Traits/Traceable.php b/app/Traits/Traceable.php new file mode 100644 index 00000000..b2fa930d --- /dev/null +++ b/app/Traits/Traceable.php @@ -0,0 +1,23 @@ +getMethod($method); + $line = $function->getStartLine(); + + $logger->log('IN', get_class($this) . "::$method", $line, $params); + + $result = $function->invokeArgs($this, $params); + + $logger->log('OUT', get_class($this) . "::$method", $line, $result); + + return $result; + } +} diff --git a/app/Views/cd_master_list.php b/app/Views/cd_master_list.php index 92bde594..67ac08a0 100755 --- a/app/Views/cd_master_list.php +++ b/app/Views/cd_master_list.php @@ -394,8 +394,8 @@ document.addEventListener("DOMContentLoaded", function () { }); }); - $('#cd_ac_no').change(function(){ - + $('#cd_ac_no').keyup(function(){ + console.log('key chnage detected'); var cd_ac_no = $(this).val(); console.log(cd_ac_no +'-'+cd_ac_no.length); cd_ac_no = cd_ac_no.trim(); @@ -411,8 +411,11 @@ document.addEventListener("DOMContentLoaded", function () { console.log(res) if(res.status == true){ toastr.warning(res.message, 'warning'); - $('#cd_ac_no').val(''); + // $('#cd_ac_no').val(''); + $('#btnSubmit').prop('disabled',true); + return; } + $('#btnSubmit').prop('disabled',false); }, error: function (xhr, status, error) { console.error(xhr.responseText); diff --git a/app/Views/client_basic_info.php b/app/Views/client_basic_info.php index 220164b8..32420ed2 100755 --- a/app/Views/client_basic_info.php +++ b/app/Views/client_basic_info.php @@ -98,7 +98,7 @@ input:checked + .slider:before { + placeholder="Enter Short Name" value="" name="short_name" onkeyup="validateInput(this, 'clients', 'short_name', 'clientBtnSubmit')" required> @@ -137,7 +137,7 @@ input:checked + .slider:before {
+ id="clientBtnSubmit">Submit
diff --git a/app/Views/client_branch.php b/app/Views/client_branch.php index 40e04f54..708a66df 100755 --- a/app/Views/client_branch.php +++ b/app/Views/client_branch.php @@ -163,6 +163,9 @@
+ + +
+ name="email[]" id="email" data-parsley-trigger="change" data-parsley-type="email" onkeyup="validateInput(this, 'level_contacts', 'email', 'branchBtnSubmit')" required>
+ id="branchBtnSubmit">Submit
@@ -347,6 +350,9 @@ $("#branch_form").submit(function(event) { var selectedValues = $("#selected").val(); console.log(selectedValues, selectedValues); + let level_contect_data = getContactsData(); + console.log('level_contect_data', level_contect_data); + event.preventDefault(); branch_PrimaryKey = $('#client_id_branch').val(); @@ -370,11 +376,14 @@ $("#branch_form").submit(function(event) { var formData = new FormData($('#branch_form')[0]); const jsonString = JSON.stringify(selectedValues); + const level_contect_data_json_string = JSON.stringify(level_contect_data); console.log('jsonString', jsonString); + console.log('level_contect_data_json_string', level_contect_data_json_string); // Append the JSON string to the FormData object formData.append('units', jsonString); + formData.append('level_contect_data', level_contect_data_json_string); $.ajax({ data: formData, @@ -495,6 +504,8 @@ $('body').on('click', '.btnBranchEdit', function() { dataType: 'json', success: function(res) { + console.log('branch response', res); + setTimeout(function() { $('.loader').fadeOut(); $('.loader-mask').delay(350).fadeOut('slow'); @@ -525,10 +536,25 @@ $('body').on('click', '.btnBranchEdit', function() { appendOption(res.data.units) - $('#name').val(res.contact[0].name); - $('#email').val(res.contact[0].email); - $('#mobile').val(res.contact[0].mobile); - $('#designation').val(res.contact[0].designation); + // $('#branch_table_pk').val(res.contact[0].id); + // $('#name').val(res.contact[0].name); + // $('#email').val(res.contact[0].email); + // $('#mobile').val(res.contact[0].mobile); + // $('#designation').val(res.contact[0].designation); + + if (res.contact && res.contact.length > 0 && res.contact[0]) { + $('#branch_table_pk').val(res.contact[0].id || ''); + $('#name').val(res.contact[0].name || ''); + $('#email').val(res.contact[0].email || ''); + $('#mobile').val(res.contact[0].mobile || ''); + $('#designation').val(res.contact[0].designation || ''); + } else { + $('#branch_table_pk').val(''); + $('#name').val(''); + $('#email').val(''); + $('#mobile').val(''); + $('#designation').val(''); + } res.contact.shift(); // console.log(res.contact.length) @@ -579,6 +605,7 @@ function appendContactHtml(contact = false, reset = false) {
+
@@ -591,11 +618,11 @@ function appendContactHtml(contact = false, reset = false) {
- +
- +
@@ -767,6 +794,51 @@ function checkMobileNumber(input) { }); } + +function validateInput(input, table, field, submitButId){ + + let value = $(input).val(); + let label = $(input).closest('.form-group').find('label').text().replace('*', '').trim(); + + let message = "Value is duplicate!"; + if(label){ + message = label + " already exists!"; + } + + checkDuplicateTableFieldValue(table, field, value, function(isDuplicate) { + if (isDuplicate) { + toastr.warning(message, 'WARNING'); + // $(input).val('') + $('#' + submitButId).prop('disabled', true); + } else{ + $('#' + submitButId).prop('disabled', false); + } + }); + +} + +function getContactsData() { + const contacts = []; + + const ids = $('input[name="branch_table_pk[]"]'); + const names = $('input[name="name[]"]'); + const mobiles = $('input[name="mobile[]"]'); + const emails = $('input[name="email[]"]'); + const designations = $('input[name="designation[]"]'); + + for (let i = 0; i < ids.length; i++) { + contacts.push({ + id: $(ids[i]).val() || null, + name: $(names[i]).val(), + mobile: $(mobiles[i]).val(), + email: $(emails[i]).val(), + designation: $(designations[i]).val() + }); + } + + return contacts; +} + - - - - - + + diff --git a/app/Views/hr_access_controll.php b/app/Views/hr_access_controll.php new file mode 100644 index 00000000..3052daca --- /dev/null +++ b/app/Views/hr_access_controll.php @@ -0,0 +1,178 @@ +
+
+
+ + +
+ + $value) { + $key = $key + 1 ?> + + +
+ + + + + + +
+ +
+ +
+
+
+
+
+
+
+
+ > + Pre enrollment +
+ +
+ + +
+ + +
+ + +
+ + +
+ + +
+ + +
+ + $policies) { + $statusText = $policies['policy_status'] == 1 ? 'Active' : 'In-Active'; + $statusClass = $policies['policy_status'] == 1 ? 'active' : 'inactive'; + ?> +
+ > + +
+ +
+ +
+
+ +
+
+
+ > + Active policies +
+
+ + + +
+ + +
+ + +
+ + +
+ + +
+ + +
+ + $policies) { + $statusText = $policies['policy_status'] == 1 ? 'Active' : 'In-Active'; + $statusClass = $policies['policy_status'] == 1 ? 'active' : 'inactive'; + ?> +
+ > + +
+ + + +
+
+
+ +
+
+
+ > + CD statement +
+ +
+ + +
+ + +
+ + $cd) { ?> +
+ > + +
+ +
+
+
+ +
+
+
+ > + Claims +
+
+
+
+
+
+
+ + + + +
+ +
+
+ + +
There is no HR data
+ +
+
+
\ No newline at end of file diff --git a/app/Views/layout/footer.php b/app/Views/layout/footer.php index c63f59f6..c150e074 100755 --- a/app/Views/layout/footer.php +++ b/app/Views/layout/footer.php @@ -302,9 +302,9 @@ }); - fetchMessages(); + // fetchMessages(); - setInterval(fetchMessages, 60000); // Fetch messages every sixty seconds + // setInterval(fetchMessages, 60000); // Fetch messages every sixty seconds }); $(document).ready(function() { @@ -823,6 +823,7 @@ \ No newline at end of file diff --git a/app/Views/view_rfq.php b/app/Views/view_rfq.php index 4d3ee31e..845d7229 100644 --- a/app/Views/view_rfq.php +++ b/app/Views/view_rfq.php @@ -230,7 +230,7 @@       Export Excel - +