Merge branch 'dev' of bitbucket.org:jubilian/nhance-enrollment into dev

This commit is contained in:
VENKATESHWARAN 2025-10-11 11:35:55 +05:30
commit 56e918d242
11 changed files with 650 additions and 175 deletions

View File

@ -99,5 +99,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','sms_helper'];
}

View File

@ -71,6 +71,7 @@ $routes->group("/client", ["filter" => "authMVC"], function ($routes) {
$routes->get('remove/(:num)', 'ClientController::removeClient/$1');
$routes->get("list/(:any)", "ClientController::editClientOnboarding/$1");
$routes->post('wipe', 'ClientController::wipeDemoClient');
$routes->get("typeList/(:any)", "ClientController::typeList/$1");
// application/config/routes.php
// Add a route for the view_Deposit method
@ -143,6 +144,7 @@ $routes->group("/client", ["filter" => "authMVC"], function ($routes) {
$routes->group("others", ["filter" => "authMVC"], function ($routes) {
$routes->post("create", "ClientController::createOtherTabContent");
$routes->post('check-duplicate', 'ClientController::validateDuplicateByClientBranch');
});
});

View File

@ -151,6 +151,16 @@ class ClientController extends AdminController
return $this->response->setJSON(['isDuplicate' => $isDuplicate]);
}
public function validateDuplicateByClientBranch()
{
$request = service('request');
$value = $request->getPost('value');
$clientId = $request->getPost('client_id');
$branchId = $request->getPost('branch_id');
$isDuplicate = $this->clientModel->isDuplicateByClientBranch($value, $clientId, $branchId);
return $this->response->setJSON(['isDuplicate' => $isDuplicate]);
}
public function smapletest()
{
$headers = [
@ -337,7 +347,7 @@ class ClientController extends AdminController
{
$this->myLogger->logme('error', 'Client list function called');
$headerData['page_name'] = 'Client List';
$data['clientList'] = $this->clientModel->getCreatedByUserName();
$data['clientList'] = $this->clientModel->getCreatedByUserName(1);
$data['client_rm'] = $this->clientRMModel->getAllClientRM();
$data['lead_data'] = $this->leadsModel->getLeadForInsertClientList();
@ -349,6 +359,26 @@ class ClientController extends AdminController
// $this->loadLayout('client_onboarding', $data);
}
public function typeList($id = null)
{
try {
$data = $this->clientModel->getCreatedByUserName($id); // passing client_type
if (empty($data)) {
return $this->response
->setJSON(['status' => 'error', 'message' => 'No Records found'])
->setStatusCode(404);
}
return $this->response
->setJSON(['status' => 'success', 'data' => $data])
->setStatusCode(200);
} catch (\Throwable $e) {
return $this->response
->setJSON(['status' => 'error', 'message' => $e->getMessage()])
->setStatusCode(500);
}
}
public function updateEmpAndPolicyStatus()
{
@ -877,7 +907,29 @@ class ClientController extends AdminController
}
$data['created_by'] = get_session_userid();
// before updating check if post_branch_id is already existing in the current db
if(isset($data['post_branch_id']) && !empty($data['post_branch_id']))
{
$existing_pre_branch = $this->clientBranchModel
->where('post_branch_id',$data['post_branch_id'])
// ->where('id !=',$pre_branch_id)
->where('is_active',1)
->first();
if($existing_pre_branch)
{
return $this->respond([
'status' => false,
'code' => 409,
'message' => 'The branch is already mapped with another branch. Please check.',
], 409);
}
}
$insert = $this->clientBranchModel->insert($data);
$pre_branch_id = $insert;
if ($insert) {
$level_contact_data = $this->request->getPost('level_contect_data');
@ -885,6 +937,16 @@ class ClientController extends AdminController
$this->saveLevelContacts($level_contact_data, $insert);
}
if($pre_branch_id && isset($data['post_branch_id']) && !empty($data['post_branch_id']))
{
// need to update the client_branch in the pre
$result = $this->updatePostClientBranch($data['post_branch_id'],$pre_branch_id , "create");
log_message('error','Post client_branch update result for post_branch_id '.$data['post_branch_id'].' and pre_branch_id '.$pre_branch_id.' is '.json_encode($result));
}
// if ($insert) {
// for ($i = 0; $i < count($this->request->getPost('name')); $i++) {
// // Prepare data to insert
@ -925,7 +987,11 @@ class ClientController extends AdminController
$this->myLogger->logme('error', 'Client branch EDIT function called');
$id = $this->request->getPost('branch_id_primarykey');
$client_id = $this->request->getPost('client_id');
$post_branch_id = $this->request->getPost('post_branch_id') ?? "";
$data = $this->request->getPost();
$data['post_branch_id'] = $post_branch_id;
$units = $this->request->getPost('units');
$emp_unit_count = 0;
@ -984,7 +1050,44 @@ class ClientController extends AdminController
}
$data['updated_by'] = get_session_userid();
$pre_branch_id = $id;
// before updating check if post_branch_id is already existing in the current db
if(isset($data['post_branch_id']) && !empty($data['post_branch_id']))
{
$existing_pre_branch = $this->clientBranchModel
->where('post_branch_id',$data['post_branch_id'])
->where('id !=',$pre_branch_id)
->where('is_active',1)
->first();
if($existing_pre_branch)
{
return $this->respond([
'status' => false,
'code' => 409,
'message' => 'The branch is already mapped with another branch. Please check.',
], 409);
}
}
$insert = $this->clientBranchModel->update($id, $data);
if($pre_branch_id && isset($data['post_branch_id']) && !empty($data['post_branch_id']))
{
// need to update the client_branch in the post
$result = $this->updatePostClientBranch($data['post_branch_id'],$pre_branch_id , "update");
log_message('error','Post client_branch update result for post_branch_id '.$data['post_branch_id'].' and pre_branch_id '.$pre_branch_id.' is '.json_encode($result));
}
$this->myLogger->logme('error', 'Client branch EDITED by {data}', ['data' => get_session_userid()]);
if ($insert) {
@ -5209,6 +5312,29 @@ class ClientController extends AdminController
}
public function updatePostClientBranch($post_branch_id,$pre_branch_id , $operation){
$postDB = \Config\Database::connect('postDB');
if($operation != 'create'){
$builder = $postDB->table('client_branch');
$builder->where('pre_branch_id', $pre_branch_id);
$builder->update(['pre_branch_id' => null]);
}
$builder = $postDB->table('client_branch');
$builder->where('id', $post_branch_id);
$builder->update(['pre_branch_id' => $pre_branch_id]);
return true;
}

View File

@ -74,18 +74,7 @@ class RestAuthenticationController extends AdminController
return $response->getBody();
}
// public function callThirdPartyGETAPI($queryParams, $endPoint)
// {
// $client = \Config\Services::curlrequest();
// $url = env('POST_ENROLLMENT_BASEURL') . $endPoint;
// $response = $client->get($url, [
// 'query' => $queryParams, // pass as query parameters
// 'http_errors' => false // prevent exception on non-200 status
// ]);
// return $response->getBody();
// }
public function callThirdPartyGETAPI($queryParams, $endPoint, $params = [])
{
@ -114,7 +103,19 @@ class RestAuthenticationController extends AdminController
// employee auth api's start
public function verifyEmployeeWithMobileNumber()
@ -124,7 +125,9 @@ class RestAuthenticationController extends AdminController
$this->myLogger->logme("error", "REST-AUTH-CONTROLLER - Verify Employee With Mobile Number: Function called");
try {
$mobile_number = $this->request->getJSON()->mobile_number;
$data = $this->request->getJSON();
$mobile_number = $data->mobile_number;
$this->myLogger->logme("error", "REST-AUTH-CONTROLLER - verifyEmployeeWithMobileNumber: Received mobile_number = " . $mobile_number);
$empdata = RestAuthHelper::getPreAndPostDataByEmailOrMobile(['mobile_number' => $mobile_number]);
@ -137,42 +140,90 @@ class RestAuthenticationController extends AdminController
return $this->respond(['status' => 'failed','code' => 404,'data' => $result],200);
}
$this->myLogger->logme("error", "REST-AUTH-CONTROLLER - verifyEmployeeWithMobileNumber: employee data both PRE & POST = " . json_encode($empdata));
$employeeData = $this->employeeModel->select('employees.relationship,EP.employee_id')
->join('employee_polices EP', 'EP.employee_id = employees.id', 'inner')
->where('employees.is_active', 1)
->where('employees.relationship', 'self')
->where('employees.emp_status !=', 'truncated')
->where('employees.mobile', $mobile_number)
->where('EP.is_active', 1)
->whereIn('EP.status', ['draft', 'enrolled', 'expired'])
->first();
$employeeData = [];
if (isset($empdata['pre']) && !empty($empdata['pre'])) {
$employeeData = $empdata['pre'];
$this->myLogger->logme("error", "REST-AUTH-CONTROLLER - verifyEmployeeWithMobileNumber: Using PRE data");
} elseif (isset($empdata['post']) && !empty($empdata['post'])) {
$employeeData = $empdata['post'];
$this->myLogger->logme("error", "REST-AUTH-CONTROLLER - verifyEmployeeWithMobileNumber: Using POST data");
}
$otp = random_int(100000, 999999);
$this->myLogger->logme("error", "REST-AUTH-CONTROLLER - verifyEmployeeWithMobileNumber: Final employee data to verify = " . json_encode($employeeData));
if (isset($employeeData['employee_id']))
{
{
$this->myLogger->logme("error", "REST-AUTH-CONTROLLER - verifyEmployeeWithMobileNumber: Employee verified with ID = " . $employeeData['employee_id']);
log_message('error', ' ');
log_message('error', '************************ PRE END ********************************');
$result = ['user_verification' => true ,'message' => "Verified Successfully" ];
return $this->respond(['status' => 'success','code' => 200,'data' => $result],200);
$sql = "
UPDATE employees
INNER JOIN employee_polices ON employee_polices.employee_id = employees.id
SET employees.otp = ?
WHERE employees.id = ?
AND employees.relationship = 'self'
AND employees.is_active = 1
AND employee_polices.is_active = 1
AND employee_polices.status IN ('draft', 'enrolled')
";
$db = db_connect();
$update = $db->query($sql, [$otp, $employeeData['employee_id']]);
$this->myLogger->logme("error", "REST-AUTH-CONTROLLER - verifyEmployeeWithMobileNumber: OTP update query executed. SQL = " . $db->getLastQuery());
if($update)
{
//If post-enrollment data exist update the same otp generated from pre-enrollment.
if (isset($empdata['post']['client_id']) && !empty($empdata['post']['client_id'])) {
$data->otp = $otp;
$data->client_id = $empdata['post']['client_id'];
$data->employee_id = $empdata['post']['employee_id'];
$this->myLogger->logme("error", "REST-AUTH-CONTROLLER - verifyEmployeeWithMobileNumber: Attached otp, client_id and employee_id from POST data to update the otp");
$this->callThirdPartyAPI($data, 'updateEmpOTP');
$this->myLogger->logme("error", "REST-AUTH-CONTROLLER - verifyEmployeeWithMobileNumber: Calling callThirdPartyAPI for updateEmpOTP");
}
//send sms
$SMSResult = sendOtpSms($mobile_number, $otp);
if ($SMSResult['status'] == 'success')
{
$result = ['user_verification' => true ,'message' => "Verified Successfully" ];
return $this->respond(['status' => 'success','code' => 200,'data' => $result],200);
}else{
$result = ['user_verification' => false, 'message' => "SMS sending failed , try again"];
return $this->respond(['status' => 'failed', 'code' => 404, 'data' => $result], 200);
}
}else{
$this->myLogger->logme("error", "REST-AUTH-CONTROLLER - verifyEmployeeWithMobileNumber: OTP update query Failed. SQL = " . $db->getLastQuery());
$result = ['user_verification' => false, 'message' => "Try again. , try again"];
return $this->respond(['status' => 'failed', 'code' => 404, 'data' => $result], 200);
}
} else {
$this->myLogger->logme("error", "REST-AUTH-CONTROLLER - verifyEmployeeWithMobileNumber: Employee ID not found, calling third-party API to POST");
log_message('error', ' ');
log_message('error', '************************ PRE END ********************************');
// Call the third-party API function
return $this->callThirdPartyAPI($this->request->getJSON(),'verifyEmployeeNumber');
$reqData = $this->request->getJSON();
$reqData->otp = $otp;
return $this->callThirdPartyAPI($reqData,'verifyEmployeeNumber');
}
} catch (\Throwable $th) {
@ -208,22 +259,7 @@ class RestAuthenticationController extends AdminController
$this->myLogger->logme("error", "REST-AUTH-CONTROLLER - verifyEmployeeWithEmailId: employee data both PRE & POST = " . json_encode($empdata));
$employeeData = $this->employeeModel->select('
employees.relationship,
EP.employee_id,
employees.client_id,
employees.client_branch_id,
employees.email_corporate
')
->join('employee_polices EP', 'EP.employee_id = employees.id', 'inner')
->where('employees.is_active', 1)
->where('employees.relationship', 'Self')
->where('employees.emp_status !=', 'truncated')
->where('employees.email_corporate', $email)
->where('EP.is_active', 1)
->whereIn('EP.status', ['draft', 'enrolled', 'expired'])
->first();
$employeeData = [];
if (isset($empdata['pre']) && !empty($empdata['pre'])) {
@ -231,15 +267,12 @@ class RestAuthenticationController extends AdminController
$this->myLogger->logme("error", "REST-AUTH-CONTROLLER - verifyEmployeeWithEmailId: Using PRE data");
}
$otp = random_int(100000, 999999);
if (isset($employeeData['employee_id'])) {
if (isset($employeeData['employee_id']))
{
$this->myLogger->logme("error", "REST-AUTH-CONTROLLER - verifyEmployeeWithEmailId: Valid employee found, generating OTP");
$otp = random_int(100000, 999999);
// $update = $this->employeeModel->where('email_corporate', $email)->where('relationship', 'self')
// ->where('is_active', 1)->set(array('otp' => $otp ))
// ->update();
$sql = "
UPDATE employees
@ -253,7 +286,7 @@ class RestAuthenticationController extends AdminController
";
$db = db_connect();
// $update = $db->query($sql, [$otp, $email]);
$update = $db->query($sql, [$otp, $employeeData['employee_id']]);
$this->myLogger->logme("error", "REST-AUTH-CONTROLLER - verifyEmployeeWithEmailId: OTP update query executed. SQL = " . $db->getLastQuery());
@ -261,17 +294,20 @@ class RestAuthenticationController extends AdminController
if($update)
{
$this->myLogger->logme("error", "REST-AUTH-CONTROLLER - verifyEmployeeWithEmailId: OTP updated successfully in PRE DATABASE");
$data->otp = $otp;
//If post-enrollment data exist update the same otp generated from pre-enrollment.
if (isset($empdata['post']['client_id']) && !empty($empdata['post']['client_id'])) {
$data->otp = $otp;
$data->client_id = $empdata['post']['client_id'];
$data->employee_id = $empdata['post']['employee_id'];
$this->myLogger->logme("error", "REST-AUTH-CONTROLLER - verifyEmployeeWithEmailId: Attached otp, client_id and employee_id from POST data to update the otp");
$this->callThirdPartyAPI($data, 'updateEmpOTP');
$this->myLogger->logme("error", "REST-AUTH-CONTROLLER - verifyEmployeeWithEmailId: Calling callThirdPartyAPI for updateEmpOTP");
}
$this->myLogger->logme("error", "REST-AUTH-CONTROLLER - verifyEmployeeWithEmailId: Calling callThirdPartyAPI for updateEmpOTP");
$this->callThirdPartyAPI($data, 'updateEmpOTP');
//send Email
$common = [
'client_id' => $employeeData['client_id'],
'client_branch_id' => $employeeData['client_branch_id'],
@ -309,15 +345,16 @@ class RestAuthenticationController extends AdminController
} else {
$this->myLogger->logme("error", "REST-AUTH-CONTROLLER - verifyEmployeeWithEmailId: Employee not found with email in the PRE DATABASE, falling back to third-party API");
// Call the third-party API function
$apiParams = $this->request->getJSON();
if (!empty($empdata['post']['client_id'])) {
$apiParams->client_id = $empdata['post']['client_id'];
}
// print_r($apiParams); die;
// Call the third-party API function
$apiParams->otp = $otp;
return $this->callThirdPartyAPI($apiParams, 'verifyEmployeeEmailId');
log_message('error', ' ');
log_message('error', '************************ PRE END ********************************');
return $this->callThirdPartyAPI($apiParams, 'verifyEmployeeEmailId');
}
} catch (\Throwable $th) {
log_message('error', ' ');
@ -336,79 +373,42 @@ class RestAuthenticationController extends AdminController
try {
$otp_verification = isset($this->request->getJSON()->otp_verification) ? $this->request->getJSON()->otp_verification : null;
$mobile_number = isset($this->request->getJSON()->mobile_number) ? $this->request->getJSON()->mobile_number : null;
$otp = isset($this->request->getJSON()->otp) ? $this->request->getJSON()->otp : null;
$email_id = isset($this->request->getJSON()->email_id) ? $this->request->getJSON()->email_id : null;
$otp = isset($this->request->getJSON()->otp) ? $this->request->getJSON()->otp : null;
if (isset($this->request->getJSON()->login_by_hr))
{
$this->myLogger->logme("error", "REST-AUTH-CONTROLLER - getVerifiedUserData: login_by_hr detected, fetching employee data directly");
$employeeData = $this->employeeModel->where('id', $this->request->getJSON()->employee_id)->where('relationship', 'self')->where('emp_status !=', 'truncated')->where('is_active', 1)->first();
$this->myLogger->logme("error", "REST-AUTH-CONTROLLER - getVerifiedUserData: employeeData (login_by_hr) = " . json_encode($employeeData));
}else{
$this->myLogger->logme("error", "REST-AUTH-CONTROLLER - getVerifiedUserData: Fetching empdata via RestAuthHelper");
$empdata = RestAuthHelper::getPreAndPostDataByEmailOrMobile(['email_id' => $email_id, 'otp' => $otp, 'mobile_number' => $mobile_number ]);
// print_r($empdata); die;
if(empty($empdata)){
$this->myLogger->logme("error", "REST-AUTH-CONTROLLER - getVerifiedUserData: empdata is empty");
log_message('error', ' ');
log_message('error', '************************ PRE END ********************************');
return $this->respond(['status' => 'failed','code' => 404,'data' => "", 'message' => "Invalid OTP"],200);
}
$this->myLogger->logme("error", "REST-AUTH-CONTROLLER - getVerifiedUserData: empdata = " . json_encode($empdata));
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
->select('employees.*')
->join('employee_polices EP', 'EP.employee_id = employees.id', 'inner')
->where('employees.is_active', 1)
->where('employees.relationship', 'self')
->where('employees.emp_status !=', 'truncated')
->where('employees.mobile', $mobile_number)
->where('EP.is_active', 1)
->whereIn('EP.status', ['draft', 'enrolled'])
->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
->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', ['draft', 'enrolled'])
->where('employees.is_active', 1)
->whereIn('employees.emp_status', ['draft', 'enrolled'])
->where('employees.otp', $otp)
->orderBy('id', 'desc')
->first();
}
$employeeData = [];
if (isset($empdata['pre']) && !empty($empdata['pre'])) {
$employeeData = $empdata['pre'];
$this->myLogger->logme("error", "REST-AUTH-CONTROLLER - getVerifiedUserData: Using PRE data from empdata");
}
$this->myLogger->logme("error", "REST-AUTH-CONTROLLER - getVerifiedUserData: Fetching empdata via RestAuthHelper");
$empdata = RestAuthHelper::getPreAndPostDataByEmailOrMobile(['email_id' => $email_id, 'otp' => $otp, 'mobile_number' => $mobile_number ]);
if(empty($empdata)){
$this->myLogger->logme("error", "REST-AUTH-CONTROLLER - getVerifiedUserData: empdata is empty");
log_message('error', ' ');
log_message('error', '************************ PRE END ********************************');
return $this->respond(['status' => 'Invalid OTP','code' => 404,'data' => "", 'message' => "Invalid OTP"],200);
}
$this->myLogger->logme("error", "REST-AUTH-CONTROLLER - getVerifiedUserData: empdata = " . json_encode($empdata));
$employeeData = [];
if (isset($empdata['pre']) && !empty($empdata['pre'])) {
$employeeData = $empdata['pre'];
$this->myLogger->logme("error", "REST-AUTH-CONTROLLER - getVerifiedUserData: Using PRE data from empdata");
}
$requestData = $this->request->getJSON();
if (isset($empdata['post']['client_id']) && !empty($empdata['post']['client_id'])) {
$requestData->client_id = $empdata['post']['client_id'];
$requestData->employee_id = $empdata['post']['employee_id'];
$this->myLogger->logme("error", "REST-AUTH-CONTROLLER - getVerifiedUserData: Added client_id and employee_id to requestData for to get the POST employee data");
}
// print_r($requestData); die;
if ($employeeData && $otp_verification == true || $employeeData && isset($this->request->getJSON()->login_by_hr) || $employeeData && isset($this->request->getJSON()->otp) )
if ( $employeeData && isset($this->request->getJSON()->otp) )
{
$this->myLogger->logme("error", "REST-AUTH-CONTROLLER - getVerifiedUserData: Verified employee found");
$auth = HttpRequestHelper::getRequestInfo();
@ -462,27 +462,76 @@ class RestAuthenticationController extends AdminController
// employee auth api's end
// HR auth api's start
public function verifyHrWithMobileNumber()
{
try {
$mobile_number = $this->request->getJSON()->mobile_number;
$data = $this->request->getJSON();
$mobile_number = $data->mobile_number;
$HrData = $this->hrModel->where('mobile', $mobile_number)
->where('contact_type', 'client')
->where('is_active', 1)
->first();
if ($HrData) {
$otp = random_int(100000, 999999);
if ($HrData)
{
$result = ['user_verification' => true ,'message' => "Verified Successfully"];
return $this->respond(['status' => 'success','code' => 200,'data' => $result],200);
} else {
// Call the third-party API function
return $this->callThirdPartyAPI($this->request->getJSON(),'verifyHrWithMobileNumber');
$sql = "UPDATE level_contacts SET otp = ? WHERE mobile = ? AND contact_type = 'client' AND is_active = 1";
$db = db_connect();
$update = $db->query($sql, [$otp, $mobile_number]);
if($update)
{
//update otp in post-enrollment
$data->otp = $otp;
$this->callThirdPartyAPI($data, 'updateHROTP');
//send sms
$SMSResult = sendOtpSms($mobile_number, $otp);
if ($SMSResult['status'] == 'success')
{
$result = ['user_verification' => true, 'message' => "Verified Successfully"];
return $this->respond(['status' => 'success', 'code' => 200, 'data' => $result], 200);
} else {
$result = ['user_verification' => false, 'message' => "SMS sending failed , try again"];
return $this->respond(['status' => 'failed', 'code' => 404, 'data' => $result], 200);
}
}else {
$result = ['user_verification' => false, 'message' => "SMS sending failed , try again"];
return $this->respond(['status' => 'failed', 'code' => 404, 'data' => $result], 200);
}
}else {
// Call the third-party API function
$reqData = $this->request->getJSON();
$reqData->otp = $otp;
return $this->callThirdPartyAPI($reqData,'verifyHrWithMobileNumber');
}
} catch (\Throwable $th) {
return $this->respond(['status' => 'failed','code' => 500,'data' => $th],500);
}
@ -501,9 +550,11 @@ class RestAuthenticationController extends AdminController
->where('is_active', 1)
->first();
$otp = random_int(100000, 999999);
if ($HrData) {
$otp = random_int(100000, 999999);
$sql = "
UPDATE level_contacts
@ -546,6 +597,8 @@ class RestAuthenticationController extends AdminController
} else {
// Call the third-party API function
$reqData = $this->request->getJSON();
$reqData->otp = $otp;
return $this->callThirdPartyAPI($this->request->getJSON(),'verifyHrWithEmail');
}
@ -557,21 +610,19 @@ class RestAuthenticationController extends AdminController
public function getVerifiedHrData()
{
try {
// mobile number
$otp_verification = isset($this->request->getJSON()->otp_verification) ? $this->request->getJSON()->otp_verification : 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;
$mobile_number = isset($this->request->getJSON()->mobile_no) ? $this->request->getJSON()->mobile_no : null;
if (isset($mobile_number))
{
$hrData = $this->hrModel->where('mobile', $mobile_number)->where('contact_type', 'client')->first();
$hrData = $this->hrModel->where('mobile', $mobile_number)->where('contact_type', 'client')->where('otp', $otp)->first();
}else{
$hrData = $this->hrModel->where('email', $email)->where('contact_type', 'client')->where('otp', $otp)->first();
}
if ($hrData && $otp_verification == true || $hrData && isset($this->request->getJSON()->otp) )
if ($hrData)
{
$auth = HttpRequestHelper::getRequestInfo();
@ -597,10 +648,10 @@ class RestAuthenticationController extends AdminController
->where('level_contacts.mobile', $mobile_number )
->where('level_contacts.contact_type', 'client')
->findAll();
//set otp value null
$this->hrModel->where('mobile', $mobile_number)->where('otp', $otp)->where('contact_type', 'client')->set(['otp'=>null])->update();
}else if(isset($this->request->getJSON()->otp)){
$this->hrModel->where('email', $email)->where('otp', $otp)->where('contact_type', 'client')->set(['otp'=>null])->update();
}else if(isset($this->request->getJSON()->email)){
$getAllhrData = $this->hrModel->select('level_contacts.id ,level_contacts.mobile , level_contacts.email , clients.id as client_id, clients.client_name, clients.short_name , client_branch.id as client_branch_id,client_branch.branch_name , client_branch.post_branch_id')
->join('client_branch', 'level_contacts.ref_id = client_branch.id', 'left')
@ -608,10 +659,15 @@ class RestAuthenticationController extends AdminController
->where('level_contacts.email', $email )
->where('level_contacts.contact_type', 'client')
->findAll();
//set otp value null
$this->hrModel->where('email', $email)->where('otp', $otp)->where('contact_type', 'client')->set(['otp'=>null])->update();
}
if(count($getAllhrData))
{
$db2 = \Config\Database::connect('postDB');
foreach ($getAllhrData as $key => $value) {
@ -636,28 +692,20 @@ class RestAuthenticationController extends AdminController
}
}
// Call the third-party API function
$apiResponse = $this->callThirdPartyAPI($this->request->getJSON(),'getVerifiedHrData');
return $this->respond(['status' => 'success','code' => 200,'data' => $getAllhrData , 'post_enrollment'=> json_decode($apiResponse, true)],200);
}else {
// Call the third-party API function
$apiResponse = $this->callThirdPartyAPI($this->request->getJSON(),'getVerifiedHrData');
return $this->respond(['status' => 'failed','code' => 404,'data' => "" , 'post_enrollment'=> json_decode($apiResponse, true)],200);
}
$apiResponse = $this->callThirdPartyAPI($this->request->getJSON(),'getVerifiedHrData');
return $this->respond(['status' => 'success','code' => 200,'data' => $getAllhrData , 'post_enrollment'=> json_decode($apiResponse, true)],200);
//call and get allowed module data from post enrollment
// $queryParams = [
// 'hr_id' => $hrData['0']['id'],
// 'request_for' => 'pre_enrollment'
// ];
// $HRAccessRes = $this->callThirdPartyGETAPI($queryParams,'getHRAccessData');
// $HRAccessData = json_decode($HRAccessRes,true);
// if(isset($HRAccessData['data']['allowed_modules'])){ $hrData['0']['allowed_modules'] = json_decode($HRAccessData['data']['allowed_modules'],true)['pre']; }else{ $hrData['0']['allowed_modules'] = []; }
// $hrData['0']['token_type'] = 'pre';
// $result = JWTToken::encode($hrData['0']);
// // Call the third-party API function
// $apiResponse = $this->callThirdPartyAPI($this->request->getJSON(),'getVerifiedHrData');
// return $this->respond(['status' => 'success','code' => 200,'data' => $result , 'post_enrollment'=> json_decode($apiResponse, true)],200);
} else {
// Call the third-party API function

View File

@ -285,6 +285,10 @@ class RestAuthHelper
->where('EP.is_active', 1)
->whereIn('EP.status', ['draft', 'enrolled']);
if (!empty($otp)) {
$builder->where('employees.otp', $otp);
}
if (!empty($old_mpin)) {
$builder->where('employees.mpin', $old_mpin);
}

View File

@ -0,0 +1,44 @@
<?php
use CodeIgniter\Database\BaseConnection;
if (!function_exists('sendOtpSms')) {
function sendOtpSms(string $mobile, string $otp)
{
$apiKey = env('SMS_API_KEY');
$senderId = env('SMS_SENDER_ID');
$templateId = env('SMS_TEMPLATE_ID');
$serviceName = env('SMS_SERVICE_NAME');
$appName = env('SMS_APP_NAME');
// Replace variables {#var#}
$message = "Hi, Your One Time Code for logging into Nhance {$appName} App is {$otp}. Valid for 3 minutes. Please do not share this with anyone. -NHANCE";
log_message('info' , 'SMS - Message '.$message);
// Build the API URL
$url = "https://smsapi.24x7sms.com/api_2.0/SendSMS.aspx?" . http_build_query([
'APIKEY' => $apiKey,
'MobileNo' => $mobile,
'SenderID' => $senderId,
'Message' => $message,
'ServiceName' => $serviceName,
'DLTTemplateID' => $templateId,
]);
// Send request
$response = @file_get_contents($url);
log_message('info' , 'SMS - Response '.$response);
// If response failed
if ($response === FALSE) {
return ['status' => 'failed', 'message' => 'Failed to send SMS.'];
}
return ['status' => 'success', 'message' => 'OTP sent successfully', 'api_response' => $response];
}
}

View File

@ -105,13 +105,21 @@ class ClientModel extends Model
}
public function getCreatedByUserName(){
public function getCreatedByUserName($client_type = null){
return $this->db->table('clients')
// return $this->db->table('clients')
// ->select('clients.*')
// ->where('is_active', 1)
// ->get()
// ->getResult();
$query = $this->db->table('clients')
->select('clients.*')
->where('is_active', 1)
->get()
->getResult();
->where('clients.is_active', 1);
if (!empty($client_type)) {
$query->where('clients.client_type', $client_type);
}
$data = $query->get()->getResult();
return $data;
}
@ -206,5 +214,19 @@ class ClientModel extends Model
return $result;
}
public function isDuplicateByClientBranch($email, $clientId, $branchId)
{
$builder = $this->db->table('level_contacts lc')
->select('lc.id')
->join('client_branch cb', 'lc.ref_id = cb.id', 'left')
->where('lc.email', $email)
->where('lc.contact_type', 'client')
->where('cb.client_id', $clientId)
->where('lc.ref_id', $branchId)
->get();
return $builder->getNumRows() > 0 ? true : false;
}
}

View File

@ -91,13 +91,14 @@ input:checked + .slider:before {
<div class="form-group col-md-6">
<label for="client_name">Client Name<span
class="text-danger">*</span></label>
<input type="text" class="form-control" id="client_name"
<input type="text" class="form-control" id="client_name" data-old-name="<?= isset($client['client_name']) ? $client['client_name'] : '' ?>"
placeholder="Enter Client Name" value="<?= isset($client['client_name']) ? $client['client_name'] : '' ?>" name="client_name" required>
</div>
<div class="form-group col-md-6">
<label for="short_name">Client Short Name<span
class="text-danger">*</span></label>
<input type="text" class="form-control" id="short_name"
data-old-short="<?= isset($client['short_name']) ? $client['short_name'] : '' ?>"
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>

View File

@ -91,10 +91,14 @@
<input type="hidden" class="form-control" value="<?= csrf_hash() ?>" name="<?= csrf_token() ?>" />
<!-- pre_client_id as client_id -->
<input type="hidden" name="client_id" id="client_id_branch"
value="<?= isset($client['id']) ? $client['id'] : '' ?>" />
<!-- post_branch_id -->
<input type="hidden" name="post_branch_id" id="post_branch_id"
value="<?= isset($post_branch_id) ? $post_branch_id : '' ?>" />
<!-- pre_branch_id as branch_id_primarykey -->
<input type="hidden" name="branch_id_primarykey" id="branch_id_primarykey" />
@ -308,7 +312,9 @@ $('#btnBranchAdd').click(function() {
$('#district').val('');
$('#branch_city').val('');
$('#branch_form')[0].reset();
$('#branch_form').parsley().reset();
$('.ac').css('display', 'block');
$('#post_branch_id').val('');
contactCount = 1
var addButton = document.getElementById('add');
@ -379,7 +385,7 @@ $("#branch_form").submit(function(event) {
event.preventDefault();
branch_PrimaryKey = $('#client_id_branch').val();
console.log('branch_PrimaryKey', branch_PrimaryKey)
console.log('branch_PrimaryKey', branch_PrimaryKey);
if (branch_PrimaryKey === '') {
toastr.error('Client is required', 'Error');
@ -398,6 +404,7 @@ $("#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);
@ -488,6 +495,10 @@ $("#branch_form").submit(function(event) {
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
console.log('Something Wrong!', 'warning');
if(xhr.status === 409){
alert('The Current Branch is Already Existing..!!');
}
}, 300);
}
});
@ -640,7 +651,7 @@ 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" onchange="validateInput(this, 'level_contacts', 'email', 'branchBtnSubmit')" 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="validateDuplicateByClientBranch(this, 'branchBtnSubmit')" required>
</div>
<div class="form-group col-md-6">
<label for="${uniqueId}_mobile">Mobile<span class="text-danger">*</span></label>
@ -847,6 +858,71 @@ function checkMobileNumber(input) {
}
let shortNameTimer;
$("#client_name").on("input change keyup", function() {
clearTimeout(shortNameTimer); // cancel previous call
shortNameTimer = setTimeout(() => {
generateShortName(); // only runs after 200ms pause
}, 200); // adjust debounce delay as needed
});
function generateShortName() {
let clientInput = $("#client_name");
let shortInput = $("#short_name");
let oldClientName = clientInput.data("old-name"); // from DB
let oldShortName = shortInput.data("old-short"); // from DB
let newClientName = clientInput.val().trim();
console.log(`LN 866 : NEW - ${newClientName} | OLD - ${oldClientName} | OLD SN - ${oldShortName}`);
if (newClientName.toUpperCase() === (oldClientName || '').toUpperCase()) {
shortInput.val(oldShortName);
return;
}
if (newClientName.length == 0) {
shortInput.val('');
return;
}
if (newClientName.length > 0) {
let shortName = newClientName.substring(0, 10).replace(/\s+/g, '').toUpperCase();
shortInput.val(shortName);
makeUniqueShortName(shortName);
}
}
function makeUniqueShortName(baseName) {
let input = $("#short_name")[0]; // input element
checkDuplicateTableFieldValue("clients", "short_name", baseName, function(isDuplicate) {
if (isDuplicate) {
// Append sequence until unique
let counter = 1;
function tryNext() {
let padded = String(counter).padStart(3, '0'); // 001, 002, 003
let newName = baseName + padded;
checkDuplicateTableFieldValue("clients", "short_name", newName, function(exists) {
if (exists) {
counter++;
tryNext(); // keep checking
} else {
$("#short_name").val(newName);
validateInput(input, "clients", "short_name", "clientBtnSubmit");
}
});
}
tryNext();
} else {
$("#short_name").val(baseName);
validateInput(input, "clients", "short_name", "clientBtnSubmit");
}
});
}
function validateInput(input, table, field, submitBtnId){
let value = $(input).val();
@ -869,6 +945,57 @@ function validateInput(input, table, field, submitBtnId){
}
function validateDuplicateByClientBranch(input, submitButId) {
let value = $(input).val().trim();
let clientId = $('#client_id_branch').val();
let branchId = $('#branch_id_primarykey').val();
console.log(`Ln968 cId: ${clientId} | bId: ${branchId}`);
// Don't forgot be careful
// 1 Local duplication check (User entered)
let isLocalDuplicate = false;
$('input[name="email[]"]').each(function() {
if (this !== input && $(this).val().trim() === value && value !== '') {
isLocalDuplicate = true;
return false; // break loop
}
});
if (isLocalDuplicate) {
console.log(`r u n Local`);
toastr.warning("Email is duplicate!", 'WARNING');
$('#' + submitButId).prop('disabled', true);
return; // dont call server if duplicate in UI
}
// Don't forgot be careful
// 2 Server-side duplicate check (DB)
if (!isLocalDuplicate && value !== '') {
console.log(`r u n Server`);
$.ajax({
url: '<?= base_url("client/others/check-duplicate") ?>',
type: 'POST',
data: {
client_id: clientId,
branch_id: branchId,
value: value
},
dataType: 'json',
success: function(response) {
if (response.isDuplicate) {
toastr.warning("Email already exists!", 'WARNING');
$('#' + submitButId).prop('disabled', true);
} else {
$('#' + submitButId).prop('disabled', false);
}
},
error: function(xhr, status, error) {
console.error('AJAX Error:', error);
}
});
}
}
function getContactsData() {
const contacts = [];

View File

@ -81,7 +81,8 @@
<?php $account_managers .= $client->account_manager . ', '; ?>
<?php endif; ?>
<?php endforeach; ?>
<?php echo rtrim($account_managers, ', '); ?>
<?php $account_managers = rtrim($account_managers, ', ');
echo $account_managers !== '' ? $account_managers : 'N/A'; ?>
</td>
<td>
<div class="btn-group dropdown">
@ -261,9 +262,9 @@
$(document).ready(function(){
$('#lead_id').select2();
})
var table;
$(document).ready(function(){
$('#tickets-table').DataTable({
table = $('#tickets-table').DataTable({
dom: "<'row'<'col-sm-0'f><'col-sm-7 text-right'B>>" +
"<'row'<'col-sm-12'tr>>" +
"<'row'<'col-sm-5'i><'col-sm-7'p>>",
@ -271,6 +272,11 @@
extend: 'csv',
text: 'CSV',
title: 'ClientList',
// title: function() {
// return $('#toggleButtons').is(':checked')
// ? 'GC-Client-List'
// : 'RC-Client-List';
// },
className: 'my_class',
exportOptions: {
columns: ':not(:last-child)'
@ -278,13 +284,91 @@
}],
language: {
search: "_INPUT_",
searchPlaceholder: "Search..."
searchPlaceholder: "Search...",
emptyTable: '<div class="text-center text-muted">No Data found</div>'
},
paging: true ,
// pagingType: 'full_numbers'
});
})
$(".dt-buttons").prepend(`
<span id="statusSwitchWrapper" class="dt-switch-wrapper">
<span class="custom-switch mr-2" style="text-align: left;">
<input type="checkbox" class="custom-control-input" id="toggleButtons" checked>
<label class="custom-control-label" for="toggleButtons" style="vertical-align: sub !important;">Group Client</label>
</span>
</span>
`);
$('#toggleButtons').on('change', function() {
let type = $(this).is(':checked') ? 1 : 2;
// $('div.col-6 h4').text(
// $(this).is(':checked')
// ? "GC Client List"
// : "RC Client List"
// );
let url = '<?= base_url('client/typeList/') ?>' + type;
$.ajax({
url: url,
method: 'GET',
success: function(response) {
if (response.status === "success" && Array.isArray(response.data)) {
renderRows(response.data);
} else {
renderRows([]);
}
},
error: function(xhr, status, error) {
console.error("Error loading:", error);
renderRows([]);
}
});
});
});
function renderRows(data) {
table.clear();
if (Array.isArray(data) && data.length) {
data.forEach((row, index) => {
let clientrm = <?= json_encode($client_rm) ?>;
let account_managers = "";
clientrm.forEach(client => {
if (client.client_id == row.id) {
account_managers += client.account_manager + ", ";
}
});
account_managers = account_managers.replace(/,\s*$/, "");
if (account_managers === "") account_managers = "N/A";
let rowData = [
`<span> ${row.client_name} (${row.short_name})</span>`,
account_managers,
`<div class="btn-group dropdown">
<a href="javascript:void(0);" class="dropdown-toggle arrow-none btn btn-light btn-sm" data-toggle="dropdown" aria-expanded="false">
<i class="mdi mdi-dots-horizontal"></i>
</a>
<div class="dropdown-menu dropdown-menu-right">
<a class="dropdown-item" href="<?= base_url("client/list/") ?>${row.id}">
<i class="mdi mdi-pencil mr-2 text-muted font-18 vertical-middle"></i>Edit
</a>
<?php if(in_array(get_role_id(), [1, 5])) { ?>
<a class="dropdown-item" data-id="${row.id}" onclick="removeClient(this)">
<i class="mdi mdi-delete mr-2 text-muted font-18 vertical-middle"></i>Delete
</a>
<?php } ?>
</div>
</div>`
];
let newRow = table.row.add(rowData);
$(newRow.node()).find('td:eq(0)').addClass('client_info').attr('data-id', row.id);
});
}
table.draw();
}
//DO NOT REMOVE THIS FUNCTION >>> THI FUNCTION FOR CLIENT SOFT DELETE
// function removeClient(element)
// {

View File

@ -126,7 +126,7 @@ body {
<div class="col-md-6">
<div class="form-group col-md-12">
<label for="auto_fetch_client">Client List<span class="text-danger">*</span></label>
<select class="form-control" id="auto_fetch_client" name="auto_fetch_client" required>
<select class="form-control select2" id="auto_fetch_client" name="auto_fetch_client" required>
<option value="">Select Client</option>
<?php if (!empty($auto_fetch_client_list)): ?>
<?php foreach ($auto_fetch_client_list as $client_list): ?>
@ -142,7 +142,7 @@ body {
<div class="col-md-6">
<div class="form-group col-md-12">
<label for="auto_fetch_branch">Branch List<span class="text-danger">*</span></label>
<select class="form-control" id="auto_fetch_branch" name="auto_fetch_branch" required>
<select class="form-control select2" id="auto_fetch_branch" name="auto_fetch_branch" required>
<option value="">Select Branch</option>
</select>
@ -313,10 +313,19 @@ body {
</script>
<script>
$(document).ready(function() {
$('#auto_fetch_client').select2();
$('#auto_fetch_branch').select2();
$('#auto_fetch_client').change(function() {
$('#auto_fetch_branch').html(`<option value="">Select Branch</option>`);
$('.loader').fadeIn();
$('.loader-mask').fadeIn();
$.ajax({
url: "<?php echo base_url('client/branch/auto_fetch_branch'); ?>",
type: "POST",
@ -341,10 +350,18 @@ body {
console.error("Error occurred:", status, error);
},
complete: function() {
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
console.log("auto_fetch_client call is completed..!!");
}
});
});
});
</script>
<script>