MERGE_TEST_MERGE_NEWHR&MPIN_ISSUE

This commit is contained in:
Ubuntu 2025-07-11 17:40:11 +05:30
commit fb7bbea3ce
40 changed files with 3435 additions and 491 deletions

View File

@ -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<string>
*/
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'];
}

View File

@ -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();

View File

@ -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');

View File

@ -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);
}
}
}

View File

@ -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)

View File

@ -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');

View File

@ -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();
}
}

View File

@ -0,0 +1,186 @@
<?php
namespace App\Controllers;
use CodeIgniter\Controller;
use Kint;
class ICICILombardController extends AdminController
{
public function generateAuthToken($scope = 'esbhealth')
{
helper('api');
// dd($scope);
$url = 'https://ilesbapigee.insurancearticlez.com/generate-jwt-token';
$method = 'POST';
$headers = [
'Content-Type: application/x-www-form-urlencoded'
];
$body = [
'grant_type' => '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);
}
}

View File

@ -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;
}

View File

@ -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]);

View File

@ -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);
}

View File

@ -0,0 +1,30 @@
<?php
namespace App\Controllers;
// use CodeIgniter\Controller;
// use App\Traits\Traceable;
use App\Controllers\TraceableController;
class TestBusinessController extends AdminController
{
// use Traceable;
public function a()
{
print_rr(debug_backtrace(0));
// dd('sdjk');
// $r = $this->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;
}
}

View File

@ -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;

View File

@ -0,0 +1,127 @@
<?php
class DeepLogger
{
private $logFile;
private static $currentUuid;
private static $callDepth = 0;
public function __construct($logFile = 'function_calls.log')
{
$this->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);

View File

@ -0,0 +1,68 @@
<?php
if (!function_exists('call_third_party_api')) {
function call_third_party_api($url, $method = 'GET', $headers = [], $body = [])
{
$ch = curl_init();
// Normalize method
$method = strtoupper($method);
// Detect content type from headers
$contentType = 'application/json'; // default
foreach ($headers as $h) {
if (stripos($h, 'Content-Type:') !== false) {
$contentType = trim(substr($h, strlen('Content-Type:')));
}
}
// echo '<pre>';
// 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
];
}
}

View File

@ -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());

View File

@ -0,0 +1,42 @@
<?php
namespace App\Libraries;
use Throwable;
class CustomTraceLogger
{
protected $logFile;
public function __construct()
{
$logDir = WRITEPATH . 'trace_logs/';
if (!is_dir($logDir)) {
mkdir($logDir, 0777, true);
}
$this->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) {
// Dont break anything if logging fails
}
}
}

View File

@ -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();
}

View File

@ -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)){

View File

@ -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}'

View File

@ -19,7 +19,8 @@ class FileModel extends Model
"client_id",
"policy_id",
"client_branch_id",
"uploaded_by"
"uploaded_by",
"updated_by"
];

View File

@ -0,0 +1,60 @@
<?php
namespace App\Models;
use CodeIgniter\Model;
class HRAccessControlModel extends Model
{
protected $table = 'hr_access_control';
protected $primaryKey = 'id';
protected $allowedFields = [
'id',
'pre_hr_id',
'post_hr_id',
'post_client_id',
'allowed_modules',
'allowed_pre_policies',
'allowed_active_policies',
'allowed_cd',
'created_at',
'created_by',
'updated_at',
'updated_by',
'is_active'
];
// Callbacks
protected $allowCallbacks = true;
protected $beforeInsert = ["checkAndADDCreatedByValue"];
protected $afterInsert = [];
protected $beforeUpdate = ["checkAndUpdateUpdatedByValue"];
protected $afterUpdate = [];
protected $beforeFind = [];
protected $afterFind = [];
protected $beforeDelete = [];
protected $afterDelete = [];
protected function checkAndADDCreatedByValue(array $data)
{
// Check if 'updated_by' value is null or empty
if (empty($data['data']['created_by'])) {
// Set 'updated_by' value to the current session user ID
$data['data']['created_by'] = get_session_userid();
}
return $data;
}
protected function checkAndUpdateUpdatedByValue(array $data)
{
// Check if 'updated_by' value is null or empty
if (empty($data['data']['updated_by'])) {
// Set 'updated_by' value to the current session user ID
$data['data']['updated_by'] = get_session_userid();
}
return $data;
}
}

View File

@ -47,6 +47,7 @@ class InsurerModel extends Model
->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) {

View File

@ -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();

23
app/Traits/Traceable.php Normal file
View File

@ -0,0 +1,23 @@
<?php
namespace App\Traits;
use App\Libraries\CustomTraceLogger;
trait Traceable
{
public function __call($method, $params)
{
$logger = new CustomTraceLogger();
$reflector = new \ReflectionClass($this);
$function = $reflector->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;
}
}

View File

@ -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);

View File

@ -98,7 +98,7 @@ input:checked + .slider:before {
<label for="short_name">Client Short Name<span
class="text-danger">*</span></label>
<input type="text" class="form-control" id="short_name"
placeholder="Enter Short Name" value="<?= isset($client['short_name']) ? $client['short_name'] : '' ?>" name="short_name" required>
placeholder="Enter Short Name" value="<?= isset($client['short_name']) ? $client['short_name'] : '' ?>" name="short_name" onkeyup="validateInput(this, 'clients', 'short_name', 'clientBtnSubmit')" required>
</div>
</div>
@ -137,7 +137,7 @@ input:checked + .slider:before {
<div class="form-group text-right m-b-0">
<button type="submit" class="btn btn-primary waves-effect waves-light mr-1"
id="btnSubmit">Submit</button>
id="clientBtnSubmit">Submit</button>
<button type="button" class="btn btn-secondary waves-effect btnBack"
id="btnBack">Cancel</button>
</div>

View File

@ -163,6 +163,9 @@
</div>
<div class="form-row">
<input type="hidden" name="branch_table_pk[]" id="branch_table_pk" >
<div class="form-group col-md-6">
<label for="first_name">Name<span class="text-danger">*</span></label>
<input value="" type="text" class="form-control" placeholder="Enter Contact Name"
@ -178,12 +181,12 @@
<div class="form-group col-md-6">
<label for="last_name">Email<span class="text-danger">*</span></label>
<input value="" type="text" class="form-control" placeholder="Enter Contact Email"
name="email[]" id="email" data-parsley-trigger="change" data-parsley-type="email" required>
name="email[]" id="email" data-parsley-trigger="change" data-parsley-type="email" onkeyup="validateInput(this, 'level_contacts', 'email', 'branchBtnSubmit')" required>
</div>
<div class="form-group col-md-6">
<label for="mobile">Mobile<span class="text-danger">*</span></label>
<input value="" type="text" class="form-control" placeholder="Enter Contact Mobile"
name="mobile[]" id="mobile" onchange="checkMobileNumber(this)"
name="mobile[]" id="mobile" onkeyup="validateInput(this, 'level_contacts', 'mobile', 'branchBtnSubmit')"
onkeypress="return onlyNumbers(event)" maxlength="10" minlength="10"
data-parsley-type-message="Please enter a valid 10-digit mobile number."
data-parsley-required-message="Please enter a valid 10-digit mobile number."
@ -202,7 +205,7 @@
</div>
<div class="form-group text-right m-b-0">
<button type="submit" class="btn btn-primary waves-effect waves-light mr-1"
id="btnSubmit">Submit</button>
id="branchBtnSubmit">Submit</button>
<button type="button" class="btn btn-secondary waves-effect btnBack"
id="btnBack">Cancel</button>
</div>
@ -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) {
</div>
</div>
<div class="form-row">
<input type="hidden" name="branch_table_pk[]" id="${uniqueId}_branch_table_pk" value="${contact !== undefined && contact !== false ? contact.id : ''}">
<div class="form-group col-md-6">
<label for="${uniqueId}_first_name">Name<span class="text-danger">*</span></label>
<input value="${contact !== undefined && contact !== false ? contact.name : ''}" type="text" class="form-control" placeholder="Enter Contact Name" name="name[]" id="${uniqueId}_name" required>
@ -591,11 +618,11 @@ function appendContactHtml(contact = false, reset = false) {
<div class="form-row">
<div class="form-group col-md-6">
<label for="${uniqueId}_last_name">Email<span class="text-danger">*</span></label>
<input value="${contact !== undefined && contact !== false ? contact.email : ''}" type="text" class="form-control" placeholder="Enter Contact Email" name="email[]" id="${uniqueId}_email" data-parsley-trigger="change" data-parsley-type="email" required>
<input value="${contact !== undefined && contact !== false ? contact.email : ''}" type="text" class="form-control" placeholder="Enter Contact Email" name="email[]" id="${uniqueId}_email" data-parsley-trigger="change" data-parsley-type="email" onkeyup="validateInput(this, 'level_contacts', 'email', 'branchBtnSubmit')" required>
</div>
<div class="form-group col-md-6">
<label for="${uniqueId}_mobile">Mobile<span class="text-danger">*</span></label>
<input value="${contact !== undefined && contact !== false ? contact.mobile : ''}" type="text" class="form-control" placeholder="Enter Contact Mobile" name="mobile[]" id="${uniqueId}_mobile" onchange="checkMobileNumber(this)" onkeypress = "return onlyNumbers(event)" maxlength="10" min="10" data-parsley-type-message="Please enter a valid 10-digit mobile number." data-parsley-required-message="Please enter a valid 10-digit mobile number." required>
<input value="${contact !== undefined && contact !== false ? contact.mobile : ''}" type="text" class="form-control" placeholder="Enter Contact Mobile" name="mobile[]" id="${uniqueId}_mobile" onkeyup="validateInput(this, 'level_contacts', 'mobile', 'branchBtnSubmit')" onkeypress = "return onlyNumbers(event)" maxlength="10" min="10" data-parsley-type-message="Please enter a valid 10-digit mobile number." data-parsley-required-message="Please enter a valid 10-digit mobile number." required>
</div>
</div>
<div class="form-group" style="display: flex;">
@ -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;
}
</script>
<script>

View File

@ -34,6 +34,226 @@ body {
</style>
<style>
body {
background-color: #f8f9fa;
font-size: 14px;
}
.container-fluid {
padding: 12px;
}
.user-card {
background: white;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(77, 77, 77, 0.3);
margin-bottom: 12px;
overflow: hidden;
transition: all 0.3s ease;
}
.user-card:hover {
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}
.card-header {
background: #d6d6d6;
color: white;
padding: 12px 18px;
cursor: pointer;
display: flex;
justify-content: space-between;
align-items: center;
transition: background 0.3s ease;
}
.card-header:hover {
background: #b4bec5;
}
.user-info h5 {
margin-bottom: 2px;
font-size: 1.1em;
color: #121212;
}
.user-email {
font-size: 0.85em;
opacity: 0.9;
margin: 0;
color:rgb(56, 55, 55);
}
.accordion-icon {
font-size: 1.2em;
transition: transform 0.3s ease;
color: #121212;
}
.accordion-icon.active {
transform: rotate(180deg);
}
.card-content {
max-height: 0;
overflow: hidden;
transition: max-height 0.4s ease;
background: white;
}
.card-content.active {
max-height: 500px;
overflow-y: auto;
}
.content-inner {
padding: 18px;
}
.section {
background: #d6dce1;
border-radius: 6px;
padding: 12px;
border: 1px solid #e9ecef;
margin-bottom: 12px;
transition: all 0.3s ease;
}
.section:hover {
border-color: #667eea;
box-shadow: 0 2px 8px rgba(102, 126, 234, 0.1);
}
.section-title {
font-weight: 600;
margin-bottom: 8px;
color: #121212;
font-size: 0.95em;
display: flex;
align-items: center;
}
.main-checkbox {
margin-right: 8px;
transform: scale(1.1);
cursor: pointer;
}
.checkbox-group {
margin-left: 24px;
transition: all 0.3s ease;
max-height: 225px;
overflow-y: auto;
padding-right: 8px;
overflow-x: hidden;
}
.checkbox-group::-webkit-scrollbar {
width: 4px;
}
.checkbox-group::-webkit-scrollbar-track {
background: #f1f1f1;
border-radius: 2px;
}
.checkbox-group::-webkit-scrollbar-thumb {
background: #667eea;
border-radius: 2px;
}
.checkbox-group::-webkit-scrollbar-thumb:hover {
background: #5a6fd8;
}
.checkbox-item {
display: flex;
align-items: center;
padding: 4px 8px;
border-radius: 4px;
transition: background 0.2s ease;
/* margin-bottom: 3px; */
margin-bottom: -7px;
}
.checkbox-item:hover {
background: rgba(102, 126, 234, 0.1);
}
.checkbox-item input[type="checkbox"] {
transform: scale(1.05);
cursor: pointer;
margin-right: 6px;
}
.checkbox-item label {
cursor: pointer;
user-select: none;
margin: 0;
font-size: 0.9em;
}
.hidden {
opacity: 0;
max-height: 0 !important;
overflow: hidden;
margin: 0;
padding: 0;
}
.policy-number {
font-family: monospace;
font-size: 0.8em;
color: #6c757d;
}
.submit-container {
background: white;
padding: 18px;
border-radius: 8px;
/* box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); */
margin-top: 20px;
text-align: right;
}
/* .btn-submit {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
border: none;
padding: 10px 30px;
font-weight: 600;
border-radius: 25px;
transition: all 0.3s ease;
}
.btn-submit:hover {
background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
transform: translateY(-2px);
box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
} */
.output-container {
background: #f8f9fa;
border: 1px solid #dee2e6;
border-radius: 8px;
padding: 15px;
margin-top: 20px;
display: none;
}
.output-table {
font-family: monospace;
font-size: 0.85em;
white-space: pre-wrap;
background: white;
padding: 10px;
border-radius: 4px;
border: 1px solid #dee2e6;
}
</style>
<div class="row" id="client_add">
<div class="col-12">
@ -88,6 +308,12 @@ body {
<span class="d-none d-sm-inline-block">Policies</span>
</a>
</li>
<li class="nav-item">
<a href="#hr-access-tab" data-toggle="tab" aria-expanded="false" class="nav-link px-3 py-2" id="hr_access_tab" onclick="appendHrAccessControllHtml(this)">
<span class="mr-1"><i class="mdi mdi-book-open-page-variant"></i></span>
<span class="d-none d-sm-inline-block">HR Access Controll</span>
</a>
</li>
<!-- <li class="nav-item">
<a href="#api-tab" data-toggle="tab" aria-expanded="false" class="nav-link px-3 py-2" id="api_tab">
<span class="mdi mdi-api"></span>
@ -102,6 +328,18 @@ body {
</li> -->
</ul>
<div class="tab-content">
<div class="tab-pane fade" id="hr-access-tab">
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-body" id="hr_access_append_area">
</div>
</div>
</div> <!-- end col -->
</div>
</div>
<?php include("client_api.php"); ?>
<?php // include('client_others_tab.php'); ?>
<?php include('notification.php'); ?>
@ -117,39 +355,10 @@ body {
</div>
<script>
// $(document).ready(function(){
// var tabid = localStorage.getItem('tabId');
// console.log(tabid)
// $('#'+tabid).click();
// localStorage.removeItem('tabId')
// })
let hrAccessControlHtmlAppended = false;
// $('#general_tab').click( function (){
// localStorage.setItem('tabId', 'general_tab')
// })
// $('#KYC-DOC-tab').click( function (){
// localStorage.setItem('tabId', 'kyc_tab')
// })
// $('#RM_tab').click( function (){
// localStorage.setItem('tabId', 'RM_tab')
// })
// $('#branch_tab').click( function (){
// localStorage.setItem('tabId', 'branch_tab')
// })
// $('#policy_tab').click( function (){
// localStorage.setItem('tabId', 'policy_tab')
// })
</script>
<script>
function client_kyc_docs() {
var check_client_id = $('#general_PrimaryKey');
@ -236,13 +445,11 @@ body {
client_relationship_manager();
});
document.getElementById("policy_tab").addEventListener("click", function(event) {
event.preventDefault();
client_policies();
});
document.getElementById("branch_tab").addEventListener("click", function(event) {
event.preventDefault();
client_branch_contact();
@ -253,6 +460,372 @@ body {
client_notification();
});
function appendHrAccessControllHtml(input){
console.log(input.id);
let client_id = $('#general_PrimaryKey').val();
console.log('client_id ', client_id);
let url = '<?= base_url('util/viewHrAccessData') ?>';
let requestData = {client_id : client_id};
if(hrAccessControlHtmlAppended == false){
sendAjaxRequestForGlobal(url, 'GET', requestData, function(response) {
console.log('Data fetched successfully:', response);
if (response.status === true) {
$('#hr_access_append_area').empty();
$('#hr_access_append_area').append(response.data)
hrAccessControlHtmlAppended = true;
} else {
console.log(response.message, 'WARNING');
hrAccessControlHtmlAppended = false;
}
}, function(xhr, status, error) {
console.error('Error fetching data:', error);
console.error(xhr.responseText);
hrAccessControlHtmlAppended = false;
});
}else{
console.log('Already HTML appended');
}
}
</script>
<script>
function toggleAccordion(header) {
const card = header.parentElement;
const content = card.querySelector('.card-content');
const icon = header.querySelector('.accordion-icon i');
// Close all other accordions
document.querySelectorAll('.user-card').forEach(otherCard => {
if (otherCard !== card) {
const otherContent = otherCard.querySelector('.card-content');
const otherIcon = otherCard.querySelector('.accordion-icon i');
otherContent.classList.remove('active');
otherIcon.classList.remove('fa-chevron-up');
otherIcon.classList.add('fa-chevron-down');
}
});
// Toggle current accordion
content.classList.toggle('active');
if (content.classList.contains('active')) {
icon.classList.remove('fa-chevron-down');
icon.classList.add('fa-chevron-up');
} else {
icon.classList.remove('fa-chevron-up');
icon.classList.add('fa-chevron-down');
}
}
function toggleSection(checkbox, sectionId) {
const section = document.getElementById(sectionId);
const checkboxes = section.querySelectorAll('input[type="checkbox"]');
if (checkbox.checked) {
section.classList.remove('hidden');
checkboxes.forEach(cb => {
cb.disabled = false;
});
} else {
section.classList.add('hidden');
checkboxes.forEach(cb => {
cb.checked = false;
cb.disabled = true;
});
}
}
function getCheckedValues(name) {
const checkboxes = document.querySelectorAll(`input[name="${name}"]:checked`);
return Array.from(checkboxes).map(cb => parseInt(cb.value));
}
// function submitForm(event) {
// event.preventDefault();
// const formData = new FormData(document.getElementById('insuranceForm'));
// const users = [];
// // Process User 1
// const user1 = {
// pk: formData.get('user1_pk'),
// pre_hr_id: formData.get('user1_pre_hr_id'),
// post_hr_id: formData.get('user1_post_hr_id'),
// allowed_modules: getCheckedValues('user1_modules'),
// allowed_pre_policies: getCheckedValues('user1_pre_policies'),
// allowed_active_policies: getCheckedValues('user1_active_policies'),
// allowed_cd: getCheckedValues('user1_cd'),
// allowed_claims: getCheckedValues('user1_claims')
// };
// // Process User 2
// const user2 = {
// pk: formData.get('user2_pk'),
// pre_hr_id: formData.get('user2_pre_hr_id'),
// post_hr_id: formData.get('user2_post_hr_id'),
// allowed_modules: getCheckedValues('user2_modules'),
// allowed_pre_policies: getCheckedValues('user2_pre_policies'),
// allowed_active_policies: getCheckedValues('user2_active_policies'),
// allowed_cd: getCheckedValues('user2_cd'),
// allowed_claims: getCheckedValues('user2_claims')
// };
// users.push(user1, user2);
// // Generate JSON format
// const jsonOutput = users.map(user => {
// const modules = user.allowed_modules.length > 0 ? `[${user.allowed_modules.join(',')}]` : '[]';
// const prePolicies = user.allowed_pre_policies.length > 0 ? `[${user.allowed_pre_policies.join(',')}]` : '[]';
// const activePolicies = user.allowed_active_policies.length > 0 ? `[${user.allowed_active_policies.join(',')}]` : '[]';
// const cdPolicies = user.allowed_cd.length > 0 ? `[${user.allowed_cd.join(',')}]` : '[]';
// const claims = user.allowed_claims.length > 0 ? `[${user.allowed_claims.join(',')}]` : '[]';
// return {
// pk: parseInt(user.pk) || 0,
// pre_hr_id: user.pre_hr_id || "",
// post_hr_id: user.post_hr_id || "",
// allowed_modules: modules,
// allowed_pre_policies: prePolicies,
// allowed_active_policies: activePolicies,
// allowed_cd: cdPolicies,
// allowed_claims: claims
// };
// });
// const output = JSON.stringify(jsonOutput, null, 1);
// // Display the output (you can modify this part based on your needs)
// console.log(output);
// // Optional: Display in a textarea or pre element
// const outputElement = document.getElementById('output');
// if (outputElement) {
// outputElement.textContent = output;
// }
// // Optional: Copy to clipboard
// if (navigator.clipboard) {
// navigator.clipboard.writeText(output).then(() => {
// console.log('Output copied to clipboard');
// }).catch(err => {
// console.error('Failed to copy to clipboard:', err);
// });
// }
// }
function submitForm(event) {
event.preventDefault();
let client_id = $('#general_PrimaryKey').val();
const formData = new FormData(document.getElementById('insuranceForm'));
const users = [];
// Loop through each .user-card
document.querySelectorAll('.user-card').forEach(card => {
const userId = card.getAttribute('data-user-id'); // e.g., "user1", "user2"
const user = {
pk: formData.get(`${userId}_pk`),
pre_hr_id: formData.get(`${userId}_pre_hr_id`),
post_hr_id: formData.get(`${userId}_post_hr_id`),
post_client_id: formData.get(`${userId}_post_client_id`),
allowed_modules: getCheckedValues(`${userId}_modules`),
allowed_pre_policies: getCheckedValues(`${userId}_pre_policies`),
allowed_active_policies: getCheckedValues(`${userId}_active_policies`),
allowed_cd: getCheckedValues(`${userId}_cd`),
allowed_claims: getCheckedValues(`${userId}_claims`)
};
users.push(user);
});
console.log("users array", users);
const jsonOutput = users.map(user => {
return {
pk: parseInt(user.pk) || 0,
pre_hr_id: user.pre_hr_id || "",
post_hr_id: user.post_hr_id || "",
post_client_id: user.post_client_id || "",
allowed_modules: user.allowed_modules.length ? `[${user.allowed_modules.join(',')}]` : '[]',
allowed_pre_policies: user.allowed_pre_policies.length ? `[${user.allowed_pre_policies.join(',')}]` : '[]',
allowed_active_policies: user.allowed_active_policies.length ? `[${user.allowed_active_policies.join(',')}]` : '[]',
allowed_cd: user.allowed_cd.length ? `[${user.allowed_cd.join(',')}]` : '[]',
allowed_claims: user.allowed_claims.length ? `[${user.allowed_claims.join(',')}]` : '[]'
};
});
const output = JSON.stringify(jsonOutput, null, 1);
// Display the output
const outputElement = document.getElementById('outputTable');
if (outputElement) {
outputElement.textContent = output;
}
// Copy to clipboard
if (navigator.clipboard) {
navigator.clipboard.writeText(output).then(() => {
console.log('Output copied to clipboard');
}).catch(err => {
console.error('Failed to copy to clipboard:', err);
});
}
console.log(output);
let url = '<?= base_url('util/saveHrAccessData') ?>';
let requestData = {json : output, client_id : client_id};
sendAjaxRequestForGlobal(url, 'POST', requestData, function(response) {
console.log('Data fetched successfully:', response);
if (response.status === true) {
$('#hr_access_append_area').empty();
$('#hr_access_append_area').append(response.data)
toastr.success(response.message, 'SUCCESS');
} else {
console.error(response.message, 'WARNING');
}
}, function(xhr, status, error) {
console.error('Error fetching data:', error);
console.error(xhr.responseText);
});
}
// Helper function to get checked checkbox values (if not already defined)
function getCheckedValues(namePrefix) {
const checkboxes = document.querySelectorAll(`input[name^="${namePrefix}"]:checked`);
return Array.from(checkboxes).map(cb => cb.value);
}
// $(document).on('change', '.select-all', function () {
// let type = $(this).data('type');
// let user = $(this).data('user');
// let group = $(this).data('group');
// let selector = '.policy-checkbox[data-user="' + user + '"][data-group="' + group + '"]';
// if (type === 'active') {
// selector += '.active';
// } else if (type === 'inactive') {
// selector += '.inactive';
// }
// $(selector).prop('checked', this.checked);
// });
$(document).on('change', '.select-all', function () {
let $this = $(this);
let type = $this.data('type');
let user = $this.data('user');
let group = $this.data('group');
console.log('--- SELECT-ALL CHANGED ---');
console.log('Type:', type); // all / active / inactive
console.log('User:', user); // user index
console.log('Group:', group); // pre / post
// Step 1: Uncheck other "select-all" checkboxes in the same user/group
$('.select-all[data-user="' + user + '"][data-group="' + group + '"]').not(this).prop('checked', false);
console.log('Unchecked other master checkboxes in same group');
// Step 2: Build full selector
let baseSelector = '.policy-checkbox[data-user="' + user + '"][data-group="' + group + '"]';
let targetSelector = baseSelector;
if (type === 'active') {
targetSelector += '.active';
console.log('Targeting ACTIVE checkboxes only');
} else if (type === 'inactive') {
targetSelector += '.inactive';
console.log('Targeting INACTIVE checkboxes only');
} else {
console.log('Targeting ALL checkboxes');
}
// Step 3: Uncheck all policy checkboxes in that group
$(baseSelector).prop('checked', false);
console.log('Unchecked all checkboxes for user', user, 'group', group);
// Step 4: If this master is checked, apply checking to relevant ones
if ($this.is(':checked')) {
$(targetSelector).prop('checked', true);
console.log('Checked selector:', targetSelector);
} else {
console.log('Master checkbox was unchecked — no checkboxes set');
}
console.log('--- END ---');
});
// $(document).on('change', '.post-select-all', function () {
// let $this = $(this);
// let type = $this.data('type');
// let user = $this.data('user');
// let group = $this.data('group');
// console.log('--- POST SELECT-ALL CHANGED ---');
// console.log('Type:', type); // all / active / inactive
// console.log('User:', user); // user index
// console.log('Group:', group); // pre / post
// // Step 1: Uncheck other "select-all" checkboxes in the same user/group
// $('.post-select-all[data-user="' + user + '"][data-group="' + group + '"]').not(this).prop('checked', false);
// console.log('Unchecked other master checkboxes in same group');
// // Step 2: Build selector for post policy checkboxes
// // Note: Post policy checkboxes use name="userX_active_policies" not class="policy-checkbox"
// let baseSelector = 'input[name="user' + user + '_active_policies"][data-user="' + user + '"][data-group="' + group + '"]';
// let targetSelector = baseSelector;
// if (type === 'active-post') {
// // Target checkboxes that have 'active' in their class or are associated with active policies
// targetSelector = baseSelector + ':not(.inactive)';
// console.log('Targeting ACTIVE checkboxes only');
// } else if (type === 'inactive-post') {
// // Target checkboxes that have 'inactive' in their class
// targetSelector = baseSelector + '.inactive';
// console.log('Targeting INACTIVE checkboxes only');
// } else {
// console.log('Targeting ALL checkboxes');
// }
// // Step 3: Uncheck all policy checkboxes in that group first
// $(baseSelector).prop('checked', false);
// console.log('Unchecked all checkboxes for user', user, 'group', group);
// // Step 4: If this master is checked, apply checking to relevant ones
// if ($this.is(':checked')) {
// if (type === 'active') {
// // Check all checkboxes that don't have 'inactive' class
// $(baseSelector).each(function() {
// if (!$(this).hasClass('inactive')) {
// $(this).prop('checked', true);
// }
// });
// } else if (type === 'inactive') {
// // Check all checkboxes that have 'inactive' class
// $(baseSelector + '.inactive').prop('checked', true);
// } else {
// // Check all checkboxes
// $(baseSelector).prop('checked', true);
// }
// console.log('Applied checking based on type:', type);
// } else {
// console.log('Master checkbox was unchecked — no checkboxes set');
// }
// console.log('--- END ---');
// });
</script>

View File

@ -0,0 +1,178 @@
<div class="container-fluid">
<div class="row">
<div class="col-12">
<?php if(isset($hr_access_data) && !empty($hr_access_data)) { ?>
<form id="insuranceForm" onsubmit="submitForm(event)">
<?php foreach ($hr_access_data as $key => $value) {
$key = $key + 1 ?>
<!-- User 1 Card -->
<div class="user-card" data-user-id="<?= 'user' . $key ?>">
<!-- Hidden form elements for User 1 -->
<input type="hidden" name="<?= 'user' . $key ?>_pk" value="<?= $value['hr_access_table_pk'] ?>">
<input type="hidden" name="<?= 'user' . $key ?>_pre_hr_id" value="<?= $value['pre_hr_id'] ?>">
<input type="hidden" name="<?= 'user' . $key ?>_post_hr_id" value="<?= $value['post_hr_id'] ?>">
<input type="hidden" name="<?= 'user' . $key ?>_post_client_id" value="<?= $value['post_client_id'] ?>">
<div class="card-header" onclick="toggleAccordion(this)">
<div class="user-info">
<h5 class="mb-0"><?= $value['hr_name'] ?></h5>
<p class="user-email"><?= $value['hr_mail'] ?></p>
</div>
<div class="accordion-icon">
<i class="fas fa-chevron-down"></i>
</div>
</div>
<div class="card-content">
<div class="content-inner">
<div class="row">
<div class="col-md-6 col-lg-3">
<div class="section">
<div class="section-title">
<input type="checkbox" class="main-checkbox"
onchange="toggleSection(this, '<?= 'user' . $key ?>-pre')" name="<?= 'user' . $key ?>_modules"
value="1" <?php if (in_array(1, $value['allowed_pre_modules'] ?? [])) {
echo 'checked';
} ?>>
<i class="fas fa-user-plus mr-2"></i>Pre enrollment
</div>
<div class="<?= in_array(1, $value['allowed_pre_modules']) ? 'checkbox-group' : 'checkbox-group hidden' ?>" id="<?= 'user' . $key ?>-pre">
<!-- Select All -->
<div class="checkbox-item">
<input type="checkbox" class="select-all" data-type="all" data-user="<?= $key ?>" data-group="pre">
<label>Select all</label>
</div>
<!-- Select All Active -->
<div class="checkbox-item">
<input type="checkbox" class="select-all" data-type="active" data-user="<?= $key ?>" data-group="pre">
<label>Select all Active policies</label>
</div>
<!-- Select All Inactive -->
<div class="checkbox-item">
<input type="checkbox" class="select-all" data-type="inactive" data-user="<?= $key ?>" data-group="pre">
<label>Select all In-Active policies</label>
</div>
<?php foreach ($pre_policy_data as $key1 => $policies) {
$statusText = $policies['policy_status'] == 1 ? 'Active' : 'In-Active';
$statusClass = $policies['policy_status'] == 1 ? 'active' : 'inactive';
?>
<div class="checkbox-item">
<input type="checkbox" class="policy-checkbox <?= $statusClass ?>" name="<?= 'user' . $key ?>_pre_policies" data-user="<?= $key ?>" data-group="pre" value="<?= $policies['client_policy_id'] ?>"
<?= in_array($policies['client_policy_id'], $value['allowed_pre_policies']) ? 'checked' : '' ?>>
<label style="<?php if($policies['policy_status'] == 0){echo 'color:#ff5757';} ?>"><?= $policies['policy_type'] . ' - ' . $policies['policy_no'] ?></label>
</div>
<?php } ?>
</div>
</div>
</div>
<div class="col-md-6 col-lg-3">
<div class="section">
<div class="section-title">
<input type="checkbox" class="main-checkbox"
onchange="toggleSection(this, '<?= 'user' . $key ?>-active')" name="<?= 'user' . $key ?>_modules"
value="2" <?php if (in_array(2, $value['allowed_post_modules'])) {
echo 'checked';
} ?>>
<i class="fas fa-check-circle mr-2"></i>Active policies
</div>
<div class="<?php if (in_array(2, $value['allowed_post_modules'])) {echo 'checkbox-group';} else {echo 'checkbox-group hidden';} ?>" id="<?= 'user' . $key ?>-active">
<!-- Select All -->
<div class="checkbox-item">
<input type="checkbox" class="select-all" data-type="all" data-user="<?= $key ?>" data-group="post">
<label>Select all</label>
</div>
<!-- Select All Active -->
<div class="checkbox-item">
<input type="checkbox" class="select-all" data-type="active" data-user="<?= $key ?>" data-group="post">
<label>Select all Active policies</label>
</div>
<!-- Select All Inactive -->
<div class="checkbox-item">
<input type="checkbox" class="select-all" data-type="inactive" data-user="<?= $key ?>" data-group="post">
<label>Select all In-Active policies</label>
</div>
<?php foreach ($post_policy_data as $key2 => $policies) {
$statusText = $policies['policy_status'] == 1 ? 'Active' : 'In-Active';
$statusClass = $policies['policy_status'] == 1 ? 'active' : 'inactive';
?>
<div class="checkbox-item">
<input type="checkbox" class="policy-checkbox <?= $statusClass ?>" id="<?= 'user' . $key ?>-gmc2" name="<?= 'user' . $key ?>_active_policies" data-user="<?= $key ?>" data-group="post"
value="<?= $policies['client_policy_id'] ?>" <?php if (in_array($policies['client_policy_id'], $value['allowed_active_policies'])) {echo 'checked';} ?>>
<label for="<?= 'user' . $key ?>-gmc2" style="<?php if($policies['policy_status'] == 0){echo 'color:#ff5757';} ?>"><?= $policies['policy_type'] . ' - ' . $policies['policy_no'] ?></label>
</div>
<?php } ?>
</div>
</div>
</div>
<div class="col-md-6 col-lg-3">
<div class="section">
<div class="section-title">
<input type="checkbox" class="main-checkbox"
onchange="toggleSection(this, '<?= 'user' . $key ?>-cd')" name="<?= 'user' . $key ?>_modules" value="3" <?php if (in_array(3, $value['allowed_post_modules'])) { echo 'checked';} ?>>
<i class="fas fa-file-alt mr-2"></i>CD statement
</div>
<div class="<?php if (in_array(3, $value['allowed_post_modules'])) {echo 'checkbox-group';} else {echo 'checkbox-group hidden';} ?>" id="<?= 'user' . $key ?>-cd">
<!-- Select All -->
<div class="checkbox-item">
<input type="checkbox" class="select-all" data-type="all" data-user="<?= $key ?>" data-group="cd">
<label>Select all</label>
</div>
<?php foreach ($post_cd_data as $key3 => $cd) { ?>
<div class="checkbox-item">
<input type="checkbox" class="policy-checkbox" data-user="<?= $key ?>" data-group="cd" id="<?= 'user' . $key ?>-icici1" name="<?= 'user' . $key ?>_cd" value="<?= $cd['cd_master_pk'] ?>" <?php if (in_array($cd['cd_master_pk'], $value['allowed_cd'])) { echo 'checked';} ?>>
<label for="<?= 'user' . $key ?>-icici1"><?= $cd['insurer_short_name'] ?> - <span class="policy-number"><?= $cd['cd_account_no'] ?></span></label>
</div>
<?php } ?>
</div>
</div>
</div>
<div class="col-md-6 col-lg-3">
<div class="section">
<div class="section-title">
<input type="checkbox" class="main-checkbox" name="<?= 'user' . $key ?>_modules" value="4" <?php if (in_array(4, $value['allowed_post_modules'])) {echo 'checked';} ?>>
<i class="fas fa-clipboard-list mr-2"></i>Claims
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<?php } ?>
<!-- Submit Section -->
<div class="submit-container">
<button type="submit" class="btn btn-primary btn-submit">
Submit Form
</button>
</div>
</form>
<?php } else { ?>
<div class="submit-container"><b>There is no HR data</b></div>
<?php } ?>
</div>
</div>
</div>

View File

@ -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 @@
<script>
function formatDate(dateString)
{
// Parse the input date string
@ -863,6 +864,7 @@
return currentTime;
}
</script>
<script>

View File

@ -98,6 +98,14 @@
min-height: 0;
}
body[data-sidebar-size=condensed] .navbar-custom {
left: 155px !important;
}
body[data-sidebar-size=condensed] .logo-box {
width: 155px !important;
}
.navbar-custom {
top: -10px !important;
height: 61px !important;
@ -542,7 +550,7 @@
<a href="<?= base_url('/dashboard/view') ?>" class="logo logo-light text-center">
<span class="logo-sm">
<img src="<?= base_url() . "public"; ?>/assets/images/Nhance_Favi_white_2.png" alt="" width="30" height="30">
<img src="<?= base_url() . "public"; ?>/assets/images/nhance_white_logo.svg" alt="" width="130" height="30">
</span>
<!-- <span class="logo-lg">
<img src="<?= base_url() . "public"; ?>./assets/images/logo-light.png" alt="" height="20">

View File

@ -1423,7 +1423,9 @@
console.log('Policy Run Days (Final):', policy_run_days);
let annualised_claims = policy_run_days > 0 ? (incurred_claims / policy_run_days) * 365 : 0;
let annualised_claims_roundoff = Math.round(annualised_claims);
// let annualised_claims_roundoff = annualised_claims.toFixed(2);
let annualised_claims_roundoff = Math.trunc(annualised_claims);
console.log('Annualised Claims:', annualised_claims);
console.log('Annualised Claims (Rounded):', annualised_claims_roundoff);
$('#annualised_claims').val(annualised_claims_roundoff);
@ -1431,22 +1433,24 @@
let premium_as_on_date = Number($('#premium_date').val()) || 0;
console.log('Premium as on Date:', premium_as_on_date);
let incurred_claim_ratio = (annualised_claims > 0 && premium_as_on_date > 0)
? (annualised_claims / premium_as_on_date)
let incurred_claim_ratio = (incurred_claims > 0 && premium_as_on_date > 0)
? (incurred_claims / premium_as_on_date) * 100
: 0;
let incurred_claim_ratio_roundoff = isFinite(incurred_claim_ratio) ? Math.round(incurred_claim_ratio) : 0;
let incurred_claim_ratio_roundoff = isFinite(incurred_claim_ratio) ? incurred_claim_ratio.toFixed(2) : 0;
console.log('Incurred Claim Ratio:', incurred_claim_ratio);
console.log('Incurred Claim Ratio (Rounded):', incurred_claim_ratio_roundoff);
$('#incurred_claims_ratio').val(incurred_claim_ratio_roundoff);
let earned_premium = premium_as_on_date > 0 ? (premium_as_on_date / 365) * 364 : 0;
let earned_premium_roundoff = Math.round(earned_premium);
let earned_premium = premium_as_on_date > 0 ? (premium_as_on_date / 365) * policy_run_days : 0;
// let earned_premium_roundoff = earned_premium.toFixed(2);
let earned_premium_roundoff = Math.trunc(earned_premium);
console.log('Earned Premium:', earned_premium);
console.log('Earned Premium (Rounded):', earned_premium_roundoff);
$('#earned_premium').val(earned_premium_roundoff);
let earnedClaimsRatio = earned_premium > 0 ? annualised_claims / earned_premium : 0;
let earnedClaimsRatioRounded = Math.round(earnedClaimsRatio);
let earnedClaimsRatio = premium_as_on_date > 0 ? (annualised_claims / premium_as_on_date) * 100 : 0;
let earnedClaimsRatioRounded = earnedClaimsRatio.toFixed(2);
console.log('Earned Claims Ratio:', earnedClaimsRatio);
console.log('Earned Claims Ratio (Rounded):', earnedClaimsRatioRounded);
$('#earned_claims_ratio').val(earnedClaimsRatioRounded);

View File

@ -166,8 +166,8 @@
let form_type = $(this).data('id') || 0;
console.log('onsubmit event', this)
console.log('onsubmit event get data value',form_type)
console.log('onsubmit event', this);
console.log('onsubmit event get data value',form_type);
console.log('client_type', $('#client_type').val());
event.preventDefault();
@ -180,8 +180,6 @@
$('#gst').removeAttr('required');
}
isClientFormSubmitting = true;
var isValid = $('#client_form').parsley().validate();
if (!isValid) {
@ -199,6 +197,7 @@
return;
}
isClientFormSubmitting = true;
form_action = '<?= base_url("util/createClientWithMinimalData"); ?>';
@ -289,6 +288,7 @@
error: function (xhr, status, error) {
console.error(xhr.responseText);
console.error(status, error);
isClientFormSubmitting = false;
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
}

View File

@ -92,7 +92,6 @@
<div class="tab-pane fade active show" id="primary_rack_rate_tab">
<form role="form" class="parsley-examples" method="post" id="GridForm_"
enctype="multipart/form-data">
<input type="hidden" value="<?= csrf_hash() ?>" name="<?= csrf_token() ?>" />
<input type="hidden" name="client_id" id="Client_id"
value="<?= isset($client['id']) ? $client['id'] : '' ?>" />
<input type="hidden" name="client_policy_id" id="client_policy_id" />
@ -144,7 +143,7 @@
</div>
<div class="form-group text-right m-b-0" id="hide_smbt_btn">
<button class="btn btn-primary waves-effect waves-light mr-1" id="btnGridSubmit_2">Submit</button>
<button type="submit" class="btn btn-primary" id="btnGridSubmit_2">Submit</button>
<a class="btn btn-secondary waves-effect waves-light mr-1" id="btnGridrename" onclick="renameRackRateTab(this, null)">Rename</a>
</div>
</form>
@ -191,10 +190,9 @@ $(document).on('click', '.close', function() {
var rarc_rate_json_array = [];
$(document).on('submit', 'form[id^="GridForm_"]', function(event) {
console.log('submitted function called')
event.preventDefault(); // Prevent the default form submission
console.log('submitted function called')
var form = $(this);
console.log('form', form)
@ -393,6 +391,8 @@ $('body').on('click', '.btnPolicyModel', function()
$("#hidden_unit").val(branch_units[0]);
console.log('unit', branch_units[0]);
$("#gpa_unit1").val(branch_units[0]);
$("#gpa_unit2").val(branch_units[0]);
$("#gpa_unit3").val(branch_units[0]);
}
var data_for_the_rack_rate = JSON.parse(res.premiumData) ?? [];
var groupedData = groupByRackRateName(data_for_the_rack_rate) ?? [];
@ -747,7 +747,7 @@ function addGridHTML(event = false, data = false, ui_type = false, si_or_bp = fa
var id_var = 'grid_';
var default_unit = $('#hidden_unit').val();
var default_unit = $('#hidden_unit').val() ?? "";
var dataIdValue = ''
@ -787,7 +787,7 @@ function addGridHTML(event = false, data = false, ui_type = false, si_or_bp = fa
<div class="form-row" style="width:101%;padding: 10px;" id="removeChild_${Count}">
<div class="form-group col-md-3 unitDiv">
<label for="mobile">Units<span class="text-danger">*</span></label>
<input value="${data !== false && data !== undefined && data !== '' ? (data.si_or_bp == '3' ? data.unit : '') : ''}" type="text" class="form-control" placeholder="Enter Unit" name="gpa_unit_3[]" id="gpa_unit3" required>
<input value="${data !== false && data !== undefined && data !== '' ? (data.si_or_bp == '3' ? data.unit : default_unit) : default_unit}" type="text" class="form-control" placeholder="Enter Unit" name="gpa_unit_3[]" id="gpa_unit3" required>
</div>
<div class="form-group col-md-1" id="">
<label for="mobile">Grade<span class="text-danger">*</span></label>
@ -828,12 +828,12 @@ function addGridHTML(event = false, data = false, ui_type = false, si_or_bp = fa
</div>
<div class="form-group col-md-3" id="">
<label for="mobile">Sum Insured<span class="text-danger">*</span></label>
<input value="${data !== false && data !== undefined && data !== '' ? (data.si_or_bp == '1' ? data.si : '') : ''}" type="text" class="form-control" placeholder="Enter Sum Insured" name="gpa_sum_si[]" id="gpa_sum_si" onkeypress = "return onlyNumbers(event)" onchange="formatNumber(this)" required>
<input value="${data !== false && data !== undefined && data !== '' ? (data.si_or_bp == '1' ? data.si : '') : ''}" type="text" class="form-control" placeholder="Enter Sum Insured" name="gpa_sum_si[]" id="gpa_sum_si" onkeypress = "return onlyNumbers(event)" onchange="formatNumber(this)">
<div id='gpa_sum_si_number_word' class="text-danger-2" ></div>
</div>
<div class="form-group col-md-3">
<label for="mobile">Premium<span class="text-danger">*</span></label>
<input value="${data !== false && data !== undefined && data !== '' ? (data.si_or_bp == '1' ? data.premium : '') : ''}" type="text" class="form-control" placeholder="Enter Premium" name="gpa_sum_premium[]" id="gpa_sum_premium" onkeypress = "return onlyNumbers(event)" onchange="formatNumber(this)" required>
<input value="${data !== false && data !== undefined && data !== '' ? (data.si_or_bp == '1' ? data.premium : '') : ''}" type="text" class="form-control" placeholder="Enter Premium" name="gpa_sum_premium[]" id="gpa_sum_premium" onkeypress = "return onlyNumbers(event)" onchange="formatNumber(this)">
<div id='gpa_sum_premium_number_word' class="text-danger-2" ></div>
</div>
@ -864,7 +864,7 @@ function addGridHTML(event = false, data = false, ui_type = false, si_or_bp = fa
<div class="form-row" style="padding: 10px;">
<div class="form-group col-md-3 unitDiv">
<label for="mobile">Units<span class="text-danger">*</span></label>
<input value="${data !== false && data !== undefined && data !== '' ? (data.si_or_bp == '2' ? data.unit : '') : ''}" type="text" class="form-control" placeholder="Enter Unit" name="gpa_unit[]" id="gpa_unit2" required>
<input value="${data !== false && data !== undefined && data !== '' ? (data.si_or_bp == '2' ? data.unit : default_unit) : default_unit}" type="text" class="form-control" placeholder="Enter Unit" name="gpa_unit[]" id="gpa_unit2" required>
</div>
<div class="form-col col-md-2">
<label for="mobile">Basic Pay<span class="text-danger">*</span></label>
@ -1391,6 +1391,8 @@ function appendGridtHtml(ui_type = false, secondary = false, data = false)
console.log('appendGridtHtml function ui_type', ui_type);
console.log('appendGridtHtml function secondary', secondary);
console.log('appendGridtHtml function typeof secondary', typeof secondary);
var default_unit = $('#hidden_unit').val();
// alert(default_unit);
// console.log('appendGridtHtml function data.unit', data.unit);
// console.log('appendGridtHtml function data.unit type',typeof data.unit);
@ -1420,16 +1422,16 @@ function appendGridtHtml(ui_type = false, secondary = false, data = false)
html = `<div class="form-row gpa_sum_insure_remove" style="width:101%" id="removeChild_${Count}">
<div class="form-group col-md-3 unitDiv">
<label for="mobile">Units<span class="text-danger">*</span></label>
<input value="${data !== false && data !== undefined && data !== default_unit ? data.unit : default_unit}"}" type="text" class="form-control" placeholder="Enter Unit" name="gpa_unit_1[]" id="gpa_unit1" required>
<input value="${data !== false && data !== undefined && data !== default_unit ? data.unit : default_unit}" type="text" class="form-control" placeholder="Enter Unit" name="gpa_unit_1[]" id="gpa_unit1" required>
</div>
<div class="form-group col-md-3" id="">
<label for="mobile">Sum Insured<span class="text-danger">*</span></label>
<input value="${data !== false && data !== undefined && data !== '' ? data.si : ''}" type="text" class="form-control" placeholder="Enter Sum Insured" name="gpa_sum_si[]" id="gpa_sum_si" onkeypress = "return onlyNumbers(event)" onchange="formatNumber(this)" required>
<input value="${data !== false && data !== undefined && data !== '' ? data.si : ''}" type="text" class="form-control" placeholder="Enter Sum Insured" name="gpa_sum_si[]" id="gpa_sum_si" onkeypress = "return onlyNumbers(event)" onchange="formatNumber(this)">
<div id='gpa_si_number_word' class="text-danger-2" ></div>
</div>
<div class="form-group col-md-3">
<label for="mobile">Premium<span class="text-danger">*</span></label>
<input value="${data !== false && data !== undefined && data !== '' ? data.premium : ''}" type="text" class="form-control" placeholder="Enter Premium" name="gpa_sum_premium[]" id="gpa_sum_premium" onkeypress = "return onlyNumbers(event)" onchange="formatNumber(this)" required>
<input value="${data !== false && data !== undefined && data !== '' ? data.premium : ''}" type="text" class="form-control" placeholder="Enter Premium" name="gpa_sum_premium[]" id="gpa_sum_premium" onkeypress = "return onlyNumbers(event)" onchange="formatNumber(this)" >
<div id='gpa_premium_number_word' class="text-danger-2" ></div>
</div>
@ -1446,7 +1448,7 @@ function appendGridtHtml(ui_type = false, secondary = false, data = false)
html = `<div class="form-row gpa_band_remove" style="width:101%" id="removeChild_${Count}">
<div class="form-group col-md-3 unitDiv">
<label for="mobile">Units<span class="text-danger">*</span></label>
<input value="${data !== false && data !== undefined && data !== '' ? data.unit : ''}"}" type="text" class="form-control" placeholder="Enter Unit" name="gpa_unit_3[]" id="gpa_unit3" required>
<input value="${data !== false && data !== undefined && data !== default_unit ? data.unit : default_unit}" type="text" class="form-control" placeholder="Enter Unit" name="gpa_unit_3[]" id="gpa_unit3" required>
</div>
<div class="form-group col-md-1" id="">
@ -1480,7 +1482,7 @@ function appendGridtHtml(ui_type = false, secondary = false, data = false)
<div class="form-row gpa_basic_pay_remove" style="width:101%" id="removeChild_${Count}">
<div class="form-group col-md-3 unitDiv">
<label for="mobile">Units<span class="text-danger">*</span></label>
<input value="${data !== false && data !== undefined && data !== '' ? data.unit : ''}"}" type="text" class="form-control" placeholder="Enter Unit" name="gpa_unit[]" id="gpa_unit2" required>
<input value="${data !== false && data !== undefined && data !== default_unit ? data.unit : default_unit}" type="text" class="form-control" placeholder="Enter Unit" name="gpa_unit[]" id="gpa_unit2" required>
</div>
<div class="form-col col-md-2">
@ -3354,7 +3356,6 @@ function appendNewTab(tabNameData = null, data = null)
newTabPane.innerHTML = `
<form role="form" class="parsley-examples" method="post" id="GridForm_${tabId}"
enctype="multipart/form-data">
<input type="hidden" value="<?= csrf_hash() ?>" name="<?= csrf_token() ?>" />
<input type="hidden" name="client_id" id="Client_id"value="<?= isset($client['id']) ? $client['id'] : '' ?>" />
<input type="hidden" name="client_policy_id" id="client_policy_id_${tabId}" value="`+client_policy_for_additional_rack_rate+`"/>
<input type="hidden" name="rack_rate_name" id="rack_rate_name_${tabId}" value="${tabName}">
@ -3405,7 +3406,7 @@ function appendNewTab(tabNameData = null, data = null)
</div>
<div class="form-group text-right m-b-0" id="hide_smbt_btn_${tabId}">
<button type="submit" class="btn btn-primary waves-effect waves-light mr-1" id="btnGridSubmit_2_${tabId}">Submit</button>
<button type="submit" class="btn btn-primary" id="btnGridSubmit_2_${tabId}">Submit</button>
<a class="btn btn-danger waves-effect waves-light mr-1" id="btnGridremove_2_${tabId}" onclick="removeTab(this, '${tabId}', '${tabName}')">Delete</a>
<a class="btn btn-secondary waves-effect waves-light mr-1" id="btnGridrename_${tabId}" onclick="renameRackRateTab(this, '${tabId}', '${tabName}')">Rename</a>
</div>

View File

@ -1163,6 +1163,7 @@
var team_id = [];
let isClientFormSubmitting = false;
let isVehicleFormSubmitting = false;
var insurer_count_array = [];
$(document).ready(function(){
@ -1172,19 +1173,85 @@ $(document).ready(function(){
// keyboard: false
// })
$('#upload_enrollment_model').on('hide.bs.modal', function (e) {
if (!isClientFormSubmitting) {
// Ask for confirmation
if (confirm("Are you sure you want to close? Unsaved changes will be lost.")) {
// If confirmed, reset the form
$('#client_form')[0].reset();
} else {
// If not confirmed, prevent the modal from closing
e.preventDefault();
}
document.getElementById('vehicle_form').addEventListener('reset', function(event) {
console.log('vehicle_form reset called', event.type);
if(isVehicleFormSubmitting == false){
event.preventDefault();
}
});
document.getElementById('client_form').addEventListener('reset', function(event) {
console.log('client_form reset called', event.type);
if(isClientFormSubmitting == false){
event.preventDefault();
}
});
$('#upload_enrollment_model').on('hide.bs.modal', function (e) {
console.log('Attempting to hide #upload_enrollment_model modal');
let policy_type_id = $('#policy_type_id').val();
console.log('policy_type_id:', policy_type_id);
let shouldClose = false;
if(isClientFormSubmitting == false){
shouldClose = confirm("Are you sure you want to close? Unsaved changes will be lost.");
// const shouldClose = true; // Always true, can be changed to confirm() if needed
console.log('User confirmation result:', shouldClose);
if (shouldClose) {
console.log('User confirmed closing. Resetting #client_form.');
$('#client_form')[0].reset();
console.log('#client_form reset successfully.');
if (policy_type_id == 8) {
$('#client_form').removeAttr('data-id');
console.log('data-id attribute removed from #client_form.');
console.log('Opening #vehicle_modal.');
const vehicleModal = new bootstrap.Modal(document.getElementById('vehicle_modal'));
vehicleModal.show();
console.log('Setting form data for #vehicle_form from localStorage.');
setFormDataFromLocalStorage("#vehicle_form", "vehicleFormData");
}else {
console.log('policy_type_id is not 8 — proceeding with default modal behavior.');
}
} else {
console.log('User cancelled closing. Preventing modal from hiding.');
e.preventDefault(); // stops modal from closing
}
}
});
$('#vehicle_modal').on('hide.bs.modal', function (e) {
console.log('Attempting to hide #vehicle_modal modal');
if(isVehicleFormSubmitting == false){
const shouldClose = confirm("Are you sure you want to close? Unsaved changes will be lost.");
console.log('User confirmation result:', shouldClose);
if (!shouldClose) {
console.log('User cancelled closing. Preventing modal from hiding.');
e.preventDefault();
}
}
});
$('#aadhar').attr('data-parsley-required', 'false');
$('#aadhar').removeAttr('required');
@ -1300,8 +1367,11 @@ $(document).ready(function(){
if(owner_id == 'add_client'){
$(this).val("");
if($('#client_type').val()){
isVehicleFormSubmitting = true;
$('#vehicle_close_btn').click();
if ($('#client_type').val() == 2) {
@ -1346,6 +1416,8 @@ $(document).ready(function(){
var myModal = new bootstrap.Modal(document.getElementById('upload_enrollment_model'));
myModal.show();
isVehicleFormSubmitting = false;
}else{
toastr.warning('Please select the Owner type', 'WARNING');
@ -3389,6 +3461,8 @@ $("#vehicle_form").submit(function(event) {
return ;
}
isVehicleFormSubmitting = true;
form_action = '<?= base_url("util/createVehicleWithMinimalData"); ?>';
$('.loader').fadeIn();
@ -3438,10 +3512,12 @@ $("#vehicle_form").submit(function(event) {
$('#vehicle_form')[0].reset();
$('.close').click();
isVehicleFormSubmitting = false;
},
error: function (xhr, status, error) {
console.error(xhr.responseText);
console.error(status, error);
isVehicleFormSubmitting = false;
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
}
@ -3838,6 +3914,18 @@ $('#policy_no').change(function(){
var policy_no = $(this).val();
policy_no = policy_no.trim();
let client_id = $('#client_id').val()?.trim();
let client_type = $('#client_type').val()?.trim();
let client_branch_id = $('#client_branch_id').val()?.trim();
let policy_type_id = $('#policy_type_id').val()?.trim();
if (!client_id || !client_branch_id || !policy_type_id) {
if(client_type == 1){
toastr.warning('Please select the policy type, client and branch', "WARNING");
$('#policy_no').val('');
return;
}
}
$pt_id = $('#policy_tranction_policy_number').val();
console.log('$pt_id', $pt_id);
@ -3846,13 +3934,19 @@ $('#policy_no').change(function(){
$.ajax({
url: '<?php echo base_url('util/get_client_policy_data_using_policy_no/');?>',
type: "GET",
data : { policy_no : policy_no },
data : { policy_no : policy_no, client_id : client_id, client_branch_id : client_branch_id, policy_type_id : policy_type_id, client_type : client_type},
dataType: 'json',
success: function (res) {
console.log('get_client_policy_data_using_policy_no response', res)
if(res.status == true){
if(res.status == true && res.code == 409){
toastr.warning(res.message,'WARNING');
$('#policy_no').val("");
return;
}
if(res.status == true){
$('#ct_type').val(1);
$('#client_policy_id').val(res.data.id);
$('#policy_start_date').val(res.data.policy_start_date);

View File

@ -212,8 +212,8 @@ $(document).ready(function() {
customizeData: function (data) {
for (var i = 0; i < data.body.length; i++) {
for (var j = 0; j < data.body[i].length; j++) {
// Check if the column is the 9th index (10th column)
if (j === 9) {
// Check if the column is the 9th index (10th column) and 10th index (11th column)
if (j === 9 || j === 10) {
data.body[i][j] = '\u200C' + data.body[i][j];
}
}

View File

@ -78,12 +78,12 @@
<i class="fa fa-info-circle text-primary"></i>
<div class="info-tooltip">
<strong>Formulas:</strong><br>
1. Incurred Claims = Paid Claims + Outstanding Claims<br>
2. Policy Run Days = Incurred Claim Date - Policy Start Date + 1<br>
3. Earned Premium = (Premium as on Date / 365) × 364<br>
4. Annualised Claims = (Incurred Claims / Policy Run Days) × 365<br>
5. Incurred Claim Ratio = Annualised Claims / Premium as on Date<br>
6. Earned Claims Ratio = Annualised Claims / Earned Premium
1. Incurred Claims = Paid Claims + Outstanding Claims<br>
2. Policy Run Days = Incurred Claim Date - Policy Start Date + 1<br>
3. Earned Premium = (Premium as on Date / 365) × Policy Run Days<br>
4. Annualised Claims = (Incurred Claims / Policy Run Days) × 365<br>
5. Incurred Claim Ratio = Incurred Claims / Premium as on Date<br>
6. Earned Claims Ratio = Annualised Claims / Premium as on Date
</div>
</span>
</div>

View File

@ -43,18 +43,16 @@
<?php
if (!isset($view_ticket_page)) {
if ($selected_ticket_type == 1) {
include('ticket_form_gmc.php');
} else {
include('ticket_form_gpa.php');
if (!isset($view_ticket_page)) {
if ($selected_ticket_type == 1) {
include('ticket_form_gmc.php');
} else {
include('ticket_form_gpa.php');
}
}
}
?>
<div class="modal fade" id="empDetailsModal" tabindex="-1" role="dialog" aria-labelledby="empDetailsModalLabel"
aria-hidden="true" aria-modal="true" data-backdrop="static">
<div class="modal fade" id="empDetailsModal" role="dialog" aria-labelledby="empDetailsModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
@ -312,44 +310,73 @@ if (!isset($view_ticket_page)) {
}
//append the clients data to the modal
function appendClients(data) {
$('#emp_client_data_list').empty();
// function appendClients(data) {
// $('#emp_client_data_list').empty();
$('#emp_client_data_list').append($('<option>', {
value: '0',
text: 'Select Client'
}));
// $('#emp_client_data_list').append($('<option>', {
// value: '0',
// text: 'Select Client'
// }));
// $.each(data, function(index, item) {
// var option = $('<option>', {
// value: item.id,
// text: item.client_name,
// 'data-name': item.client_name,
// });
// $('#emp_client_data_list').append(option).select2();
// });
// }
function appendClients(data) {
let $select = $('#emp_client_data_list');
$select.empty();
let options = '<option value="0">Select Client</option>';
$.each(data, function(index, item) {
var option = $('<option>', {
value: item.id,
text: item.client_name,
'data-name': item.client_name,
});
$('#emp_client_data_list').append(option).select2();
options += `<option value="${item.id}" data-name="${item.client_name}">${item.client_name}</option>`;
});
$select.html(options);
$select.select2(); // ✅ Only call once after building all options
}
//append the clients data for mobile search to the modal
function appendClientsForMobileSearch(data) {
$('#mobile_emp_client_data_list').empty();
$('#mobile_emp_client_data_list').append($('<option>', {
value: '0',
text: 'Select Client'
}));
//append the clients data for mobile search to the modal
// function appendClientsForMobileSearch(data) {
// $('#mobile_emp_client_data_list').empty();
// $('#mobile_emp_client_data_list').append($('<option>', {
// value: '0',
// text: 'Select Client'
// }));
// $.each(data, function(index, item) {
// var option = $('<option>', {
// value: item.id,
// text: item.short_name,
// });
// $('#mobile_emp_client_data_list').append(option).select2();
// });
// }
function appendClientsForMobileSearch(data) {
let $select = $('#mobile_emp_client_data_list');
$select.empty();
let options = '<option value="0">Select Client</option>';
$.each(data, function(index, item) {
var option = $('<option>', {
value: item.id,
text: item.short_name,
});
$('#mobile_emp_client_data_list').append(option).select2();
options += `<option value="${item.id}">${item.short_name}</option>`;
});
$select.html(options);
$select.select2(); // ✅ Only once
}
//append the clients branch data to the modal
@ -388,10 +415,10 @@ if (!isset($view_ticket_page)) {
$.each(data, function(index, item) {
if (ticket_type == 1) {
console.log("inside if 1");
// console.log("inside if 1");
if (item.policy_type_id == 2 || item.policy_type_id == 3 || item.policy_type_id == 4 || item
.policy_type_id == 5) {
console.log("inside if 2");
// console.log("inside if 2");
var option = $('<option>', {
value: item.id,
text: item.policy_type + '-' + item.policy_no,
@ -401,9 +428,9 @@ if (!isset($view_ticket_page)) {
}
} else if (ticket_type == 2) {
console.log("inside if 3");
// console.log("inside if 3");
if (item.policy_type_id == 1) {
console.log("inside if 4");
// console.log("inside if 4");
var option = $('<option>', {
value: item.id,
text: item.policy_type + '-' + item.policy_no,
@ -435,7 +462,7 @@ if (!isset($view_ticket_page)) {
}
} else {
console.log("inside else condition");
// console.log("inside else condition");
}
});
@ -498,6 +525,8 @@ if (!isset($view_ticket_page)) {
function getEmpData(input) {
console.log('STEP 1', new Date().toLocaleString());
console.log(input)
let param = $(input).val();
let url = '<?= base_url('util/getTheEmpDataForClaim/') ?>' + param;
@ -513,6 +542,7 @@ if (!isset($view_ticket_page)) {
// Send AJAX request
sendAjaxRequestForGlobal(url, 'GET', requestData, function(response) {
console.log('STEP 2', new Date().toLocaleString());
console.log('Data fetched successfully:', response);
if (response.status) {
@ -625,26 +655,48 @@ if (!isset($view_ticket_page)) {
}
// function appendEmployee(data, attrId) {
// console.log('STEP 3', new Date().toLocaleString());
// console.log('data', data)
// $('#' + attrId).empty();
// $('#' + attrId).append($('<option>', {
// value: '0',
// text: 'Select Employee'
// }));
// $.each(data, function(index, item) {
// // console.log(item)
// var option = $('<option>', {
// value: item.emp_code,
// text: item.emp_name + ' - ' + item.emp_code,
// });
// $('#' + attrId).append(option).select2();
// });
// console.log('STEP 4', new Date().toLocaleString());
// }
function appendEmployee(data, attrId) {
console.log('STEP 3', new Date().toLocaleString());
console.log('data', data);
console.log('data', data)
let $select = $('#' + attrId);
$select.empty();
$('#' + attrId).empty();
$('#' + attrId).append($('<option>', {
value: '0',
text: 'Select Employee'
}));
let options = '<option value="0">Select Employee</option>';
$.each(data, function(index, item) {
console.log(item)
var option = $('<option>', {
value: item.emp_code,
text: item.emp_name + ' - ' + item.emp_code,
});
$('#' + attrId).append(option).select2();
options += `<option value="${item.emp_code}">${item.emp_name} - ${item.emp_code}</option>`;
});
$select.html(options); // ⬅ Append all at once
$select.select2(); // ⬅ Initialize once after options are set
console.log('STEP 4', new Date().toLocaleString());
}
function appendMember(data, attrId) {
@ -808,40 +860,40 @@ if (!isset($view_ticket_page)) {
function setMemberData(input) {
var selectedOption = $(input).find(':selected');
var selectedOption = $(input).find(':selected');
// Retrieve the data-* attributes
var empId = selectedOption.data('empid');
var empName = selectedOption.data('empname');
var policyNo = selectedOption.data('policyno');
var tpaNo = selectedOption.data('tpano');
var relationship = selectedOption.data('relationship');
// Retrieve the data-* attributes
var empId = selectedOption.data('empid');
var empName = selectedOption.data('empname');
var policyNo = selectedOption.data('policyno');
var tpaNo = selectedOption.data('tpano');
var relationship = selectedOption.data('relationship');
$('#tpa_no').val(tpaNo);
$('#insured_emp_id').val(empId);
$('#insured_name').val(empName);
// $('#policy_no').val(policyNo);
$('#tpa_no').val(tpaNo);
$('#insured_emp_id').val(empId);
$('#insured_name').val(empName);
// $('#policy_no').val(policyNo);
$('#relationship option').each(function() {
if ($(this).text() === relationship) {
$(this).prop('selected', true);
}
});
$('#relationship option').each(function() {
if ($(this).text() === relationship) {
$(this).prop('selected', true);
}
});
if (tpaNo == "") {
if (tpaNo == "") {
$('#claim_status_id').val(1)
$('#non_id_reason').attr('required', true);
var $label = $("#non_id_reason_lable_id");
$label.text('*');
$('#claim_status_id').val(1)
$('#non_id_reason').attr('required', true);
var $label = $("#non_id_reason_lable_id");
$label.text('*');
} else {
$('#claim_status_id').val(2)
$('#non_id_reason').attr('required', false);
var $label = $("#non_id_reason_lable_id");
$label.text("");
} else {
$('#claim_status_id').val(2)
$('#non_id_reason').attr('required', false);
var $label = $("#non_id_reason_lable_id");
$label.text("");
}
}
}
// $('#employee_data_points').on('change', function() {
@ -870,25 +922,25 @@ if (!isset($view_ticket_page)) {
function toResetTheModelFields() {
$('#emp_mobile_number_for_claim').val('');
$('#employee_data_points').val();
$('#employee_by_number').val('');
$('#member_by_number').val('0').select2();
$('#emp_client_data_list').val('0').select2();
$('#emp_client_branch_data_list').val('0').select2();
$('#emp_client_policy_data_list').val('0').select2();
$('#search_by_client_employee').val('0').select2();
$('#search_by_client_member').val('0').select2();
}
$('#emp_mobile_number_for_claim').val('');
$('#employee_data_points').val();
$('#employee_by_number').val('');
$('#member_by_number').val('0').select2();
$('#emp_client_data_list').val('0').select2();
$('#emp_client_branch_data_list').val('0').select2();
$('#emp_client_policy_data_list').val('0').select2();
$('#search_by_client_employee').val('0').select2();
$('#search_by_client_member').val('0').select2();
}
$('#tpa_no').on('input', function() {
let tpaNo = $(this).val().trim();
console.log('tpaNo:', tpaNo);
$('#tpa_no').on('input', function() {
let tpaNo = $(this).val().trim();
console.log('tpaNo:', tpaNo);
let isEmpty = tpaNo === "";
$('#claim_status_id').val(isEmpty ? 1 : 2);
$('#non_id_reason').prop('required', isEmpty);
$('#non_id_reason_lable_id').text(isEmpty ? '*' : '');
});
let isEmpty = tpaNo === "";
$('#claim_status_id').val(isEmpty ? 1 : 2);
$('#non_id_reason').prop('required', isEmpty);
$('#non_id_reason_lable_id').text(isEmpty ? '*' : '');
});
</script>

View File

@ -230,7 +230,7 @@
<?php } ?>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<a id="submitExcel" onclick="checkTheTableDataChanged(2)" class="btn btn-primary" id>Export Excel</a>
<button id="submitInternalMail" class="btn btn-primary" onclick="checkTheTableDataChanged(4)">Send Internal Mail</button>
<?php if (get_role_id() == 1 || in_array($user_team,[6,7])) { ?>
<?php if (in_array(get_role_id(), [1,5]) || in_array(BUSINESS_SUPPORT_TEAM_ID, user_team()) || in_array(MANAGEMENT_TEAM_ID, user_team())) { ?>
<button id="submitMail" class="btn btn-primary"
onclick="checkTheTableDataChanged(3)">Send Insurer Mail</button>
<?php } ?>