Merge remote-tracking branch 'origin/dev' into dev

This commit is contained in:
velz 2026-03-31 12:04:55 +05:30
commit d3e4304dcc
27 changed files with 2214 additions and 218 deletions

View File

@ -132,6 +132,18 @@ HEALTH_INDIA_PASSWORD =
HEALTH_INDIA_PRIMARY_KEY_CONSTANT =
# Volo / TrueCover (EWA) — ewatpa.com APIs
VOLO_PRIMARY_KEY_CONSTANT =
VOLO_API_ADMIN_BASE_URL = https://uatapiadmin.ewatpa.com
VOLO_API_CONSUMER_BASE_URL = https://uatapiconsumer.ewatpa.com
VOLO_API_EMAIL =
VOLO_API_PASSWORD =
VOLO_LOGGED_IN_PORTAL = POLICY_CONFIGURATION_PORTAL
# Optional: if get-entity-from-policy cannot be used
VOLO_DEFAULT_ENTITY_ID =
# Required for claim intimation — hospital id from Volo network master
VOLO_DEFAULT_HOSPITAL_ID =
#For sending mail for leads RFQ/QCR
LEAD_INSURER_FROM_MAIL_ID =
LEAD_CLIENT_FROM_MAIL_ID =

Binary file not shown.

View File

@ -24,6 +24,7 @@ class Acl
'#^/downloadFileTableFile#' => ['public' => true],
'#^/swagger#' => ['roles' => [ADMIN_ROLE_ID]],
'#^/getEmployeeActiveOrInactivePolicy#' => ['roles' => [ADMIN_ROLE_ID, HEAD_ROLE_ID]],
'#^/test/chartbrewDashboardDemo#' => ['roles' => [ADMIN_ROLE_ID, HEAD_ROLE_ID]],
'#^/bulkEcardDownloadAsZip#' => ['roles' => [ADMIN_ROLE_ID, HEAD_ROLE_ID]],
'#^/sheet#' => ['roles' => [ADMIN_ROLE_ID, HEAD_ROLE_ID]],
'#^/sendextraparam#' => ['roles' => [ADMIN_ROLE_ID, HEAD_ROLE_ID]],
@ -40,6 +41,7 @@ class Acl
'#^/sales/dashboard#' => ['roles' => [ADMIN_ROLE_ID, HEAD_ROLE_ID, STAFF_ROLE_ID]],
'#^/sales#' => ['roles' => [ADMIN_ROLE_ID, HEAD_ROLE_ID, STAFF_ROLE_ID]],
'#^/expense#' => ['roles' => [ADMIN_ROLE_ID, HEAD_ROLE_ID, STAFF_ROLE_ID]],
'#^/sendDataToTPA#' => ['roles' => [ADMIN_ROLE_ID, HEAD_ROLE_ID, ACCOUNT_MANAGER_ROLE_ID, MANAGER_ROLE_ID]],

View File

@ -577,6 +577,7 @@ $routes->cli('cli/MediAssit-ClaimStatusUpdate','MediAssistApiController::ClaimSt
$routes->cli('cli/Vidal-ClaimStatusUpdate','VidalApiController::ClaimStatusUpdate');
$routes->cli('cli/Fhpl-ClaimStatusUpdate','FhplApiController::ClaimStatusUpdate');
$routes->cli('cli/HealthIndia-ClaimStatusUpdate','HealthIndiaApiController::ClaimStatusUpdate');
$routes->cli('cli/Volo-ClaimStatusUpdate','VoloApiController::ClaimStatusUpdate');
// Sync TPA Claims to Nhance
$routes->cli('cli/MediAssit-syncTpaClaimToNhance','MediAssistApiController::syncTpaClaimToNhance');
@ -883,6 +884,7 @@ $routes->get('HealthIndiaGetBenefDetails','HealthIndiaApiController::HealthIndia
// API service (Don't delete)
$routes->post("ecardRequest", "ApiServiceController::ecardRequest");
$routes->post("getTPAID", "ApiServiceController::getTPAID");
$routes->post("sendDataToTPA", "ApiServiceController::sendDataToTPA");
$routes->get('fileDownload','MediAssistApiController::fileDownload');
@ -923,6 +925,7 @@ $routes->group('test', function($routes) {
$routes->get('logo_renaming','TestingController::logo_renaming');
$routes->get('testingquerys','TestingController::testingquerys');
$routes->get('thzReminderCrone','ThzController::getOpenTicketsOlderThan24HoursAndAssignNextLevel');
$routes->get('chartbrewDashboardDemo','TestingController::chartbrewDashboardDemo');
// $routes->get('createDefaultMailTempalteInDB','TestingController::createDefaultMailTempalteInCrossDB');
// $routes->get('createDefaultMailTempalteInSameDB','TestingController::createDefaultMailTempalteInSameDB');
});

View File

@ -13,6 +13,7 @@ use App\Controllers\VidalApiController;
use App\Controllers\ICICILombardController;
use App\Controllers\MediAssistApiController;
use App\Controllers\FhplApiController;
use App\Controllers\VoloApiController;
use App\Models\BatchFileModel;
use App\Models\FileModel;
use App\Helpers\TPADataCompareHelper;
@ -29,6 +30,7 @@ class ApiServiceController extends BaseController
protected $icici_primary_key;
protected $fhpl_primary_key;
protected $health_india_primary_key;
protected $volo_primary_key;
public function __construct()
{
@ -39,6 +41,7 @@ class ApiServiceController extends BaseController
$this->icici_primary_key = getenv('ICICI_PRIMARY_KEY_CONSTANT');
$this->fhpl_primary_key = getenv('FHPL_PRIMARY_KEY_CONSTANT');
$this->health_india_primary_key = getenv('HEALTH_INDIA_PRIMARY_KEY_CONSTANT');
$this->volo_primary_key = getenv('VOLO_PRIMARY_KEY_CONSTANT');
}
// Push Claims
@ -68,6 +71,10 @@ class ApiServiceController extends BaseController
{ // health india
$healthIndiaApiController = new HealthIndiaApiController;
return $healthIndiaApiController->SubmitClaim($claimId);
}else if ($tpaID == $this->volo_primary_key)
{ // Volo / TrueCover (EWA)
$voloApiController = new VoloApiController();
return $voloApiController->SubmitClaim($claimId);
}else{
log_message('error', "This ticket id ( {$claimId} ) TPA has no API service enabled. TPA ID : {$tpaID}");
}
@ -164,6 +171,12 @@ class ApiServiceController extends BaseController
$healthIndiaApiController = new HealthIndiaApiController;
$data['eCardDownload'] = $healthIndiaApiController->EcardRequest( $emp_code, $policy_no , $employee_policy[0]['tpa_id'] );
}else if($employee_policy[0]['tpa_primary_id'] == $this->volo_primary_key)// Volo / TrueCover
{
$voloApiController = new VoloApiController();
$data['eCardDownload'] = $voloApiController->EcardRequest( $emp_code, $policy_no , $employee_policy[0]['tpa_id'] );
}else{
if($type == "download"){
@ -232,7 +245,13 @@ class ApiServiceController extends BaseController
$policy_id = $this->request->getPost('client_policy_id') ?? null;
$fileModel = new BatchFileModel();
$filesData = $fileModel->where('is_active', 1)->where('event_type', 'api')->where('status', 'inprogress')->countAllResults();
$filesData = $fileModel
->join('client_policy', 'client_policy.id = batch_files.client_policy_id')
->where('client_policy.tpa_id', $tpa_id)
->where('batch_files.is_active', 1)
->where('batch_files.event_type', 'api')
->where('batch_files.status', 'inprogress')
->countAllResults();
if($filesData > 0){
log_message('error', "TPA GetBenefDetails job is already in process.");
@ -322,6 +341,15 @@ class ApiServiceController extends BaseController
return $this->respond(['status' => true, 'code' => 200, 'message' => 'Action Triggered','data' => [] ]);
}else if ($tpa_id == $this->volo_primary_key) // Volo / TrueCover
{
$file_id = $fileModel->insert($data);
log_message('error', "Files table inserted successfully, File id : {$file_id}");
$r = Jobs::addJob(['job_name' => 'VoloGetBenefDetails', 'payload' => ['policy_no' => $policy_no, 'file_id' => $file_id, 'client_policy_id' => $policy_id, 'return_type' => 'job']]);
log_message('error', "VoloGetBenefDetails job pushed successfully.");
return $this->respond(['status' => true, 'code' => 200, 'message' => 'Action Triggered','data' => [] ]);
}else{
return $this->respond(['status' => false, 'code' => 200,'message' => 'TPA not found ','data' => [] ]);
}
@ -364,6 +392,12 @@ class ApiServiceController extends BaseController
$res = $healthIndiaApiController->ClaimDetail($claimId);
return $this->response->setJSON(['status' => $res['status'],'message' => $res['message'] ]);
}else if ($tpaID == $this->volo_primary_key) { // Volo / TrueCover
$voloApiController = new VoloApiController();
$res = $voloApiController->ClaimDetail($claimId);
return $this->response->setJSON(['status' => $res['status'],'message' => $res['message'] ]);
}else{
log_message('error', "This ticket id ( {$claimId} ) TPA has no API service enabled. TPA ID : {$tpaID}");
$message = "This TPA has no API service enabled";

View File

@ -2706,9 +2706,9 @@ class ClientController extends AdminController
'rules' => 'required',
'errors' => ['required' => 'Please select an Insurer.']
],
'tpa' => [
'cd_ac_no' => [
'rules' => 'required',
'errors' => ['required' => 'Please select a TPA.']
'errors' => ['required' => 'Please select an CD account number.']
],
'policy_no' => [
'rules' => ['required', 'regex_match[/^[a-zA-Z0-9\s_\-\/\\\]+$/]'],
@ -2740,8 +2740,10 @@ class ClientController extends AdminController
'errors' => ['required' => 'End date is required.']
],
'wellness_plan_id' => [
'rules' => 'permit_empty|alpha_numeric',
'errors' => ['alpha_numeric' => 'Wellness Plan ID can only contain letters and numbers.']
'rules' => 'permit_empty|regex_match[/^[a-zA-Z0-9\/_-]+$/]',
'errors' => [
'regex_match' => 'Wellness Plan ID can only contain letters, numbers, hyphens (-), underscores (_), and forward slashes (/).'
]
],
'wellness_vendor_id' => [
'rules' => 'permit_empty'
@ -2754,6 +2756,13 @@ class ClientController extends AdminController
'is_lgbtq' => ['rules' => 'permit_empty']
];
if($request_post_data['policy_type_id'] == 2){
$rules['tpa'] = [
'rules' => 'required',
'errors' => ['required' => 'Please select a TPA.']
];
}
// 2. Run the initial validation
$isValid = $this->validate($rules);
@ -2876,7 +2885,11 @@ class ClientController extends AdminController
/** here ci4 rules not implemented, because UI screen Fields are hide/show implemented thats why */
public function editClientPolicy()
{
{
$data = $this->request->getPost();
$sanitized_post_data = sanitizeInputArrayAdvanced($data);
$rules = [
'client_branch_id' => [
'rules' => 'required',
@ -2893,9 +2906,9 @@ class ClientController extends AdminController
'rules' => 'required',
'errors' => ['required' => 'Please select an Insurer.']
],
'tpa' => [
'cd_ac_no' => [
'rules' => 'required',
'errors' => ['required' => 'Please select a TPA.']
'errors' => ['required' => 'Please select an CD account number.']
],
'policy_no' => [
'rules' => ['required', 'regex_match[/^[a-zA-Z0-9\s_\-\/\\\]+$/]'],
@ -2927,8 +2940,10 @@ class ClientController extends AdminController
'errors' => ['required' => 'End date is required.']
],
'wellness_plan_id' => [
'rules' => 'permit_empty|alpha_numeric',
'errors' => ['alpha_numeric' => 'Wellness Plan ID can only contain letters and numbers.']
'rules' => 'permit_empty|regex_match[/^[a-zA-Z0-9\/_-]+$/]',
'errors' => [
'regex_match' => 'Wellness Plan ID can only contain letters, numbers, hyphens (-), underscores (_), and forward slashes (/).'
]
],
'wellness_vendor_id' => [
'rules' => 'permit_empty'
@ -2941,6 +2956,13 @@ class ClientController extends AdminController
'is_lgbtq' => ['rules' => 'permit_empty']
];
if($data['policy_type_id'] == 2){
$rules['tpa'] = [
'rules' => 'required',
'errors' => ['required' => 'Please select a TPA.']
];
}
// 2. Run the initial validation
$isValid = $this->validate($rules);
@ -2968,8 +2990,7 @@ class ClientController extends AdminController
}
$this->myLogger->logme('error', 'Client policy function called');
$data = $this->request->getPost();
$sanitized_post_data = sanitizeInputArrayAdvanced($data);
$id = $sanitized_post_data['PrimaryKey'] ?? null;
$client_id = $sanitized_post_data['client_id'] ?? null;
@ -6465,12 +6486,13 @@ class ClientController extends AdminController
$client_type = $this->request->getGet('client_type') ?? null;
// Check in Policy Transaction (BDS)
$bds_count = $this->policyTransactionModel
$bds_data = $this->policyTransactionModel
->where('is_active', 1)
->where('action_type', 'inception')
->where('TRIM(policy_no)', $policy_no)
->where('policy_no IS NOT NULL AND policy_no <> ""')
->countAllResults();
->orderBy('id', 'desc')
->first() ?? [];
// Check in Enrollment (client_policy)
$client_policy_data = $this->clientPolicyModel
@ -6480,14 +6502,15 @@ class ClientController extends AdminController
->first();
// Decide message + count
if ($bds_count > 0) {
if (count($bds_data) > 0) {
return $this->respond([
'status' => true,
'message' => "This policy number is already linked to another policy in the BDS",
'code' => 409,
'data' => $bds_count,
'data' => $bds_data['id'],
'received_data' => $received_data,
'pt_id' => $bds_data['id'],
'client_policy_id' => $client_policy_data['id'] ?? null
], 200);
@ -6506,8 +6529,9 @@ class ClientController extends AdminController
return $this->respond([
'status' => false,
'message' => 'No Data Found',
'message' => 'Policy number not found in BDS or Enrollment, so proceed to add a new policy.',
'code' => 404,
'is_dublicate' => false,
'received_data' => $received_data,
'client_policy_id' => null
], 200);

View File

@ -59,6 +59,8 @@ class FhplApiController extends BaseController
curl_close($ch);
// dd($response);
return [
'status' => $httpCode === 200,
'http_code' => $httpCode,
@ -112,7 +114,7 @@ class FhplApiController extends BaseController
$fileContent = base64_encode(file_get_contents($pdfPath));
// Generate FHPL Token
$tokenResponse = json_decode($this->generateAuthToken()->getBody(), true);
$tokenResponse = $this->generateAuthToken();
if (empty($tokenResponse['data']['access_token'])) {
log_message('error', "FHPL - Claim Push FAILED | claimId: '.$claimId.' - FHPL Token generation failed");
return ['status' => false, 'message' => 'Claim Push FAILED | FHPL Token generation failed'];
@ -207,7 +209,7 @@ class FhplApiController extends BaseController
if(!$ticket) return ['status'=>false,'message'=>'Invalid claim'];
// Generate FHPL Token
$tokenResponse = json_decode($this->generateAuthToken()->getBody(), true);
$tokenResponse = $this->generateAuthToken();
if (empty($tokenResponse['data']['access_token'])) {
return ['status' => false,'message' => 'FHPL Token generation failed'];
@ -306,7 +308,7 @@ class FhplApiController extends BaseController
helper('api');
// Generate FHPL Token
$tokenResponse = json_decode($this->generateAuthToken()->getBody(), true);
$tokenResponse = $this->generateAuthToken();
if (empty($tokenResponse['data']['access_token'])) {
log_message('error', 'FHPL - Ecard Request FAILED | employeeId: '.$employeeId.' | policyNo: '.$policyNo.' | Message: FHPL Token generation failed');
return null;
@ -409,7 +411,7 @@ class FhplApiController extends BaseController
}
// Generate FHPL Token
$tokenResponse = json_decode($this->generateAuthToken()->getBody(), true);
$tokenResponse = $this->generateAuthToken();
if (empty($tokenResponse['data']['access_token'])) {
log_message('error', 'FHPL - TPA ID Pull | FHPL Token generation failed');
if($function_calling_type == "job"){
@ -719,7 +721,7 @@ class FhplApiController extends BaseController
helper('api');
// Generate FHPL Token
$tokenResponse = json_decode($this->generateAuthToken()->getBody(), true);
$tokenResponse = $this->generateAuthToken();
if (empty($tokenResponse['data']['access_token'])) {
return ['status' => false,'message' => 'FHPL Token generation failed'];
@ -797,7 +799,7 @@ class FhplApiController extends BaseController
try {
// Generate FHPL Token
$tokenResponse = json_decode($this->generateAuthToken()->getBody(), true);
$tokenResponse = $this->generateAuthToken();
if (empty($tokenResponse['data']['access_token'])) {
return ['status' => false,'message' => 'FHPL Token generation failed'];
@ -829,9 +831,23 @@ class FhplApiController extends BaseController
$response = call_third_party_api($url,'POST',$headers,$body);
if(!empty($response['data'])){
log_message('error', 'FHPL - Sync TPA Claims | Exception thrown while calling GetTPA_ClaimsDetails API: ' . json_encode($response));
$finalResult = array_merge($finalResult,$response['data']);
if (!empty($response['data'])) {
log_message('error', 'FHPL - Sync TPA Claims API Response: ' . json_encode($response));
// Convert to array if it's JSON string
if (is_string($response['data'])) {
$decodedData = json_decode($response['data'], true);
} else {
$decodedData = $response['data'];
}
// Merge only if it's array
if (is_array($decodedData)) {
$finalResult = array_merge($finalResult, $decodedData);
} else {
log_message('error', 'FHPL - Data is not an array: ' . print_r($response['data'], true));
}
}
}

View File

@ -141,7 +141,7 @@ class HealthIndiaApiController extends BaseController
$fileContent = base64_encode(file_get_contents($pdfPath));
// Generate Health India Token
$tokenResponse = json_decode($this->generateAuthToken()->getBody(), true);
$tokenResponse = $this->generateAuthToken();
if (empty($tokenResponse['data']['result'][0]['access_token'])) {
log_message('error', "HEALTH_INDIA - Claim Push FAILED | claimId: {$claimId} - Token generation failed");
return;
@ -258,7 +258,7 @@ class HealthIndiaApiController extends BaseController
}
// Generate Health India Token
$tokenResponse = json_decode($this->generateAuthToken()->getBody(), true);
$tokenResponse = $this->generateAuthToken();
if (empty($tokenResponse['data']['result'][0]['access_token'])) {
log_message('error', 'HEALTH_INDIA - Claim Status FAILED | claimId: ' . $claimId . ' - Token generation failed');
@ -378,7 +378,7 @@ class HealthIndiaApiController extends BaseController
log_message('error', "HEALTH_INDIA - Ecard Request | Started | employeeId: {$employeeId} | policyNo: {$policyNo} | memberId: {$memberId}");
// Generate Health India Token
$tokenResponse = json_decode($this->generateAuthToken()->getBody(), true);
$tokenResponse = $this->generateAuthToken();
if (empty($tokenResponse['data']['result'][0]['access_token'])) {
log_message('error', "HEALTH_INDIA - Ecard Request | employeeId: {$employeeId} | policyNo: {$policyNo} | Message: Token generation failed");
return null;
@ -483,7 +483,7 @@ class HealthIndiaApiController extends BaseController
}
// Generate Health India Token
$tokenResponse = json_decode($this->generateAuthToken()->getBody(), true);
$tokenResponse = $this->generateAuthToken();
if (empty($tokenResponse['data']['result'][0]['access_token'])) {
log_message('error', 'HEALTH_INDIA - TPA ID Pull | Token generation failed');
if ($function_calling_type == "job") {
@ -729,7 +729,7 @@ class HealthIndiaApiController extends BaseController
log_message('error', 'HEALTH_INDIA - Sync TPA Claims | Started');
// Generate Health India Token
$tokenResponse = json_decode($this->generateAuthToken()->getBody(), true);
$tokenResponse = $this->generateAuthToken();
if (empty($tokenResponse['data']['result'][0]['access_token'])) {
log_message('error', 'HEALTH_INDIA - Sync TPA Claims FAILED | Token generation failed');
@ -827,7 +827,7 @@ class HealthIndiaApiController extends BaseController
log_message('error', 'HEALTH_INDIA - Sync TPA Claims | Started');
// Generate Health India Token
$tokenResponse = json_decode($this->generateAuthToken()->getBody(), true);
$tokenResponse = $this->generateAuthToken();
if (empty($tokenResponse['data']['result'][0]['access_token'])) {
log_message('error', 'HEALTH_INDIA - Sync TPA Claims FAILED | Token generation failed');

View File

@ -5,10 +5,129 @@ namespace App\Controllers;
use CodeIgniter\Controller;
use Kint;
use Ramsey\Uuid\Uuid;
use App\Models\BatchFileModel;
class ICICILombardController extends AdminController
{
/**
* Fetch UHID details for a completed batch and update `employee_polices.uhid`.
*
* @param array $batch Row from batch_files joined with client_policy (must include: id, client_policy_id, icici_batch_id, icici_correlation_id, icici_endorsement_policy_no)
* @param string|null $overrideImid If provided, uses this value instead of icici_batch_id.
* @return array {new_status, updatedCount, response}
*/
private function fetchUhidAndUpdateEmployeePolicies(array $batch, ?string $overrideImid = null): array
{
helper('api');
$tokenResponse = $this->generateAuthToken('esbgpauhid');
if (!$tokenResponse || empty($tokenResponse['data']['access_token'])) {
return [
'new_status' => 'FAILED',
'updatedCount' => 0,
'response' => $tokenResponse,
'error' => 'Token generation failed.',
];
}
$token = $tokenResponse['data']['access_token'];
$url = env('ICICI_BASE_URL') . '/fetchuhid';
$headers = [
'Authorization: Bearer ' . $token,
'Content-Type: application/json',
];
$correlationId = !empty($batch['icici_correlation_id'])
? $batch['icici_correlation_id']
: 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),
);
$imid = $overrideImid ?: ($batch['icici_batch_id'] ?? null);
if (empty($imid) || empty($batch['icici_endorsement_policy_no'])) {
return [
'new_status' => 'FAILED',
'updatedCount' => 0,
'response' => null,
'error' => 'IMID or endorsement PolicyNumber missing for UHID fetch.',
];
}
$body = [
'PolicyNumber' => $batch['icici_endorsement_policy_no'],
'IMID' => $imid,
'CorrelationId' => $correlationId,
];
$response = call_third_party_api($url, 'POST', $headers, $body, true);
$apiData = $response['data'] ?? [];
$newFlag = 'FAILED';
$updatedCount = 0;
if (!empty($response['status']) && $response['status'] === true && (($apiData['statusMessage'] ?? null) === 'SUCCESS')) {
$newFlag = 'COMPLETED';
// Update UHID in employee_polices table based on memberDetails
$memberDetails = $apiData['memberDetails'] ?? [];
if (!empty($memberDetails) && is_array($memberDetails)) {
$db = \Config\Database::connect();
$clientPolicyId = (int) ($batch['client_policy_id'] ?? 0);
foreach ($memberDetails as $member) {
$employeeMemberId = $member['employeeMemberId'] ?? null;
$uhid = $member['uhid'] ?? null;
if (empty($employeeMemberId) || empty($uhid)) {
continue;
}
// Find employee by emp_code = employeeMemberId
$employee = $db->table('employees')
->select('id')
->where('emp_code', $employeeMemberId)
->get()
->getRowArray();
if (empty($employee)) {
continue;
}
// Update UHID for that employee and policy
$db->table('employee_polices')
->where('employee_id', $employee['id'])
->where('client_policy_id', $clientPolicyId)
->set('uhid', $uhid)
->update();
$updatedCount++;
}
}
}
$batchModel = new BatchFileModel();
$batchModel->update($batch['id'], [
'icici_uhid_status_flag' => $newFlag,
]);
return [
'new_status' => $newFlag,
'updatedCount' => $updatedCount,
'response' => $response,
'request' => $body,
];
}
public function generateAuthToken($scope = 'esbhealth')
{
helper('api');
@ -21,7 +140,7 @@ class ICICILombardController extends AdminController
'grant_type' => env('ICICI_GRANT_TYPE'),
'username' => env('ICICI_USER_NAME'),
'password' => env('ICICI_PASSWORD'),
'scope' => env('ICICI_API_SCOPE'),
'scope' => $scope ?: env('ICICI_API_SCOPE'),
'client_id' => env('ICICI_CLIENT_ID'),
'client_secret' => env('ICICI_CLIENT_SECRET')
];
@ -37,6 +156,7 @@ class ICICILombardController extends AdminController
]);
}
// Debug removed: return token response to caller.
return $response;
}
@ -44,11 +164,12 @@ class ICICILombardController extends AdminController
{
$client_id = $this->request->getGet('client_id');
$client_branch_id = $this->request->getGet('client_branch_id');
$policy_id = $this->request->getGet('policy_id');
// Prefer `client_policy_id` key (also accept legacy `policy_id`)
$policy_id = $this->request->getGet('client_policy_id') ?? $this->request->getGet('policy_id');
$event = $this->request->getGet('event');
//fetch token
$tokenResponse = $this->generateAuthToken();
$tokenResponse = $this->generateAuthToken('esbgpabatchcreation');
if (!$tokenResponse || empty($tokenResponse['data']['access_token'])) {
return $this->response->setJSON([
'status' => false,
@ -66,91 +187,71 @@ class ICICILombardController extends AdminController
];
//Prepare body data
// $db = \Config\Database::connect();
// $data = $db->table('employee_polices ep')
// ->select('cp.policy_no as policyNumber, cp.cd_ac_no as CDBGAccountNumber,
// e.id,e.emp_code as MemberEmpId, e.doj as DOJ, e.name as InsuredName, e.dob as DOB, e.relationship as Relationship,
// e.gender as Gender, ep.date_coverage as DOC,ep.basic_cover_si as SumInsured, e.email_corporate as EmailId
// ')
// ->join('employees e', 'e.id = ep.employee_id')
// ->join('client_policy cp', 'ep.client_policy_id = cp.id')
// ->where('ep.client_policy_id', $policy_id)
// ->where('ep.status', 'active')
// ->where('ep.is_active', 1)
// // ->where('ep.uhid', null)
// ->get()
// ->getResultArray();
// $body = $this->formatPolicyData($data);
// dd($body);
// Prepare body data from employee policies
$db = \Config\Database::connect();
$data = $db->table('employee_polices ep')
->select('cp.policy_no as policyNumber, cp.cd_ac_no as CDBGAccountNumber,
e.id,e.emp_code as MemberEmpId, e.doj as DOJ, e.name as InsuredName, e.dob as DOB, e.relationship as Relationship,
e.gender as Gender, ep.date_coverage as DOC,ep.basic_cover_si as SumInsured, e.email_corporate as EmailId
')
->join('employees e', 'e.id = ep.employee_id')
->join('client_policy cp', 'ep.client_policy_id = cp.id')
->where('ep.client_policy_id', $policy_id)
->where('ep.status', 'active')
->where('ep.is_active', 1)
// ->where('ep.uhid', null)
->get()
->getResultArray();
// dd($data);
if (empty($data)) {
return $this->response->setJSON([
'status' => false,
'message' => 'No active employee policies found for given policy.',
'data' => [],
]);
}
$body = $this->formatPolicyData($data);
if (empty($body['CDBGAccountNumber'])) {
return $this->response->setJSON([
'status' => false,
'message' => 'CDBGAccountNumber is empty for selected policy. Please configure policy CDBG account number.',
'data' => $body,
]);
}
// $body = [
// "PolicyNumber" => "4016/PPN/A/O/53167743/00/000",
// "CDBGAccountNumber" => "CD-MUM-0026",
// "CorrelationId" => "550e8400-e29b-41d4-a716-446655440016",
// "MemberDetails" => [
// [
// "MemberEmpId" => "EMPID3625562",
// "DOJ" => "21-MAR-2019",
// "InsuredName" => "Jeeva",
// "DOB" => "7-JUL-1993",
// "Relationship" => "SELF",
// "Gender" => "MALE",
// "DOC" => '28-Oct-2025',
// "SumInsured" => "500000",
// "EmailId" => "Jeeva@GMAIL.COM",
// "FlagStatus" => "A"
// ],
// [
// "MemberEmpId" => "EMPID3625562",
// "DOJ" => "21-MAR-2019",
// "InsuredName" => "Muthu",
// "DOB" => "8-AUG-1970",
// "Relationship" => "MOTHER",
// "Gender" => "FEMALE",
// "DOC" => '28-Oct-2025',
// "EmailId" => "Muthu@GMAIL.COM",
// "FlagStatus" => "A"
// ],
// ]
// ];
$body = [
"PolicyNumber" => "4016/PPN/A/O/53185987/00/000",
"CDBGAccountNumber" => "CD-MUM-0026",
"CorrelationId" => "550e8400-e29b-41d4-a716-446655440023",
"MemberDetails" => [
[
"MemberEmpId" => "EMPID3625566",
"DOJ" => "21-MAR-2019",
"InsuredName" => "sanjeev",
"DOB" => "7-JUL-1993",
"Relationship" => "SELF",
"Gender" => "MALE",
"DOC" => '25-Jan-2026',
"SumInsured" => "500000",
"EmailId" => "sanjeev@GMAIL.COM",
"FlagStatus" => "A"
],
[
"MemberEmpId" => "EMPID3625566",
"DOJ" => "21-MAR-2019",
"InsuredName" => "bhavya",
"DOB" => "8-AUG-1970",
"Relationship" => "MOTHER",
"Gender" => "FEMALE",
"DOC" => '25-Jan-2026',
"EmailId" => "bhavya@GMAIL.COM",
"FlagStatus" => "A"
],
]
];
if (empty($body['MemberDetails'])) {
return $this->response->setJSON([
'status' => false,
'message' => 'No valid member records available for ICICI enrollment payload.',
'data' => $body,
]);
}
$response = call_third_party_api($url, 'POST', $headers, $body, true); // true = raw body mode
// print_rr(json_encode($response));die();
// Save batch information only on successful API call
if (!empty($response['status']) && $response['status'] === true) {
$apiData = $response['data'] ?? [];
$batchModel = new BatchFileModel();
$batchModel->insert([
'client_id' => $client_id,
'client_policy_id' => $policy_id,
'client_branch_id' => $client_branch_id,
'event_type' => $event,
'insurer_or_tpa' => 'ICICI_LOMBARD',
'actions' => 'ICICI_GPA_ENROLLMENT',
'is_active' => 1,
'icici_correlation_id' => $body['CorrelationId'] ?? null,
'icici_batch_id' => $apiData['batchId'] ?? null,
'icici_status_flag' => 'PENDING',
'icici_status_message' => $apiData['message'] ?? null,
'icici_endorsement_policy_no' => null,
'icici_uhid_status_flag' => 'PENDING',
]);
}
return $this->response->setJSON($response);
}
@ -158,8 +259,11 @@ class ICICILombardController extends AdminController
{
helper('api');
// User request: use `client_policy_id` key (also accept legacy `policy_id`)
$clientPolicyId = $this->request->getGet('client_policy_id') ?? $this->request->getGet('policy_id');
//fetch token
$tokenResponse = $this->generateAuthToken();
$tokenResponse = $this->generateAuthToken('esbgpabatchstatus');
if (!$tokenResponse || empty($tokenResponse['data']['access_token'])) {
return $this->response->setJSON([
'status' => false,
@ -176,61 +280,156 @@ class ICICILombardController extends AdminController
'Content-Type: application/json'
];
// dd($headers);
$db = \Config\Database::connect();
$body = [
"PolicyNumber" => "4016/PPN/A/O/53185987/00/000",
"BatchId" => "3728144",
"CorrelationId" => "550e8400-e29b-41d4-a716-446655440022"
];
// Fetch all pending / in-process batches for ICICI
$query = $db->table('batch_files bf')
->select('bf.id, bf.client_policy_id, bf.icici_batch_id, bf.icici_correlation_id, cp.policy_no')
->join('client_policy cp', 'cp.id = bf.client_policy_id')
->where('bf.is_active', 1)
->whereIn('bf.icici_status_flag', ['PENDING', 'IN_PROCESS'])
->where('bf.icici_batch_id IS NOT NULL');
$response = call_third_party_api($url, 'POST', $headers, $body, true);
if (!empty($clientPolicyId)) {
$query->where('bf.client_policy_id', (int) $clientPolicyId);
}
return $this->response->setJSON($response);
$batches = $query->get()->getResultArray();
if (empty($batches)) {
return $this->response->setJSON([
'status' => true,
'message' => 'No pending ICICI GPA batches found.',
'data' => [],
]);
}
$batchModel = new BatchFileModel();
$results = [];
foreach ($batches as $batch) {
$body = [
'PolicyNumber' => $batch['policy_no'],
'BatchId' => $batch['icici_batch_id'],
'CorrelationId' => $batch['icici_correlation_id'],
];
$response = call_third_party_api($url, 'POST', $headers, $body, true);
$apiData = $response['data'] ?? [];
$message = $apiData['message'] ?? null;
$statusMessage = $apiData['statusMessage'] ?? null;
$newStatusFlag = 'FAILED';
if (!empty($response['status']) && $response['status'] === true && $statusMessage === 'SUCCESS') {
if ($message === 'Process Completed') {
$newStatusFlag = 'COMPLETED';
} elseif ($message === 'In Process') {
$newStatusFlag = 'IN_PROCESS';
} else {
$newStatusFlag = 'PENDING';
}
}
$updateData = [
'icici_status_flag' => $newStatusFlag,
'icici_status_message' => $message,
'icici_endorsement_policy_no'=> $apiData['endorsementPolicyNo'] ?? null,
];
// If process completed successfully, UHID step becomes pending
if ($newStatusFlag === 'COMPLETED') {
$updateData['icici_uhid_status_flag'] = 'PENDING';
}
$batchModel->update($batch['id'], $updateData);
// After COMPLETED, trigger UHID fetch internally (no extra imid param).
$uhidResult = null;
if ($newStatusFlag === 'COMPLETED') {
// Ensure we pass endorsement policy number to the internal UHID fetch helper.
$batch['icici_endorsement_policy_no'] = $updateData['icici_endorsement_policy_no'] ?? null;
$uhidResult = $this->fetchUhidAndUpdateEmployeePolicies($batch);
}
$results[] = [
'batch_file_id' => $batch['id'],
'request' => $body,
'response' => $response,
'new_status' => $newStatusFlag,
'uhid_fetch' => $uhidResult,
];
}
return $this->response->setJSON([
'status' => true,
'message' => 'Batch status updated.',
'data' => $results,
]);
}
public function fetchUHIDDetails()
{
helper('api');
//fetch token
$tokenResponse = $this->generateAuthToken('esbgpauhid');
// dd($tokenResponse);
if (!$tokenResponse || empty($tokenResponse['data']['access_token'])) {
// Accept `client_policy_id` key (also accept legacy `policy_id`)
$policy_id = $this->request->getGet('client_policy_id') ?? $this->request->getGet('policy_id');
$imid = $this->request->getGet('imid'); // optional; if omitted we derive from icici_batch_id
if (empty($policy_id)) {
return $this->response->setJSON([
'status' => false,
'message' => 'Token generation failed.',
'data' => $tokenResponse
'status' => false,
'message' => 'client_policy_id is required.',
'data' => [],
]);
}
$token = $tokenResponse['data']['access_token'];
// print_rr($token);
$batchModel = new BatchFileModel();
$batch = $batchModel
->where('client_policy_id', $policy_id)
->where('is_active', 1)
->where('icici_status_flag', 'COMPLETED')
->whereIn('icici_uhid_status_flag', ['PENDING', 'FAILED'])
->orderBy('id', 'DESC')
->first();
$url = env('ICICI_BASE_URL').'/fetchuhid';
$headers = [
'Authorization: Bearer ' . $token,
'Content-Type: application/json'
];
if (empty($batch)) {
return $this->response->setJSON([
'status' => false,
'message' => 'No completed ICICI GPA batch found for UHID fetch.',
'data' => [],
]);
}
$body = [
"PolicyNumber" => "4016/PPN/A/O/53185987/00/001",
"IMID" => "201580517901",
"CorrelationId" => "550e8400-e29b-41d4-a716-446655440022"
];
$uhidResult = $this->fetchUhidAndUpdateEmployeePolicies($batch, $imid);
$response = call_third_party_api($url, 'POST', $headers, $body, true);
// dd($response);
return $this->response->setJSON($response);
return $this->response->setJSON([
'status' => true,
'message' => 'UHID details fetched.',
'data' => [
'batch_file_id' => $batch['id'],
'request' => $uhidResult['request'] ?? [],
'response' => $uhidResult['response'] ?? [],
'new_status' => $uhidResult['new_status'] ?? 'FAILED',
'uhid_updated_count' => $uhidResult['updatedCount'] ?? 0,
],
]);
}
public function formatPolicyData($data)
{
// Helper to format date
// Helper to format date as DD-MMM-YYYY (e.g. 7-JUL-1993)
$formatDate = function ($date) {
return strtoupper(date('j-M-Y', strtotime($date))); // Example: 7-JUL-1983
if (empty($date)) {
return null;
}
$timestamp = strtotime($date);
if ($timestamp === false) {
return null;
}
return strtoupper(date('j-M-Y', $timestamp));
};
// Generate UUID v4 for CorrelationId
@ -248,26 +447,42 @@ class ICICILombardController extends AdminController
);
};
// Map MemberDetails
$memberDetails = array_map(function ($row) use ($formatDate) {
return [
"MemberEmpId" => $row['MemberEmpId'],
"DOJ" => $formatDate($row['DOJ']),
"InsuredName" => $row['InsuredName'],
"DOB" => $formatDate($row['DOB']),
"Relationship" => strtoupper($row['Relationship']),
"Gender" => strtoupper($row['Gender']),
"DOC" => $formatDate($row['DOC']),
"SumInsured" => $row['SumInsured'],
"EmailId" => $row['EmailId'],
"FlagStatus" => "A" // fixed value
$mapGender = function ($gender) {
$normalized = strtoupper(trim((string) $gender));
if ($normalized === 'M' || $normalized === 'MALE') {
return 'MALE';
}
if ($normalized === 'F' || $normalized === 'FEMALE') {
return 'FEMALE';
}
return $normalized;
};
// Map MemberDetails in ICICI expected request format
$memberDetails = [];
foreach ($data as $row) {
if (empty($row['MemberEmpId']) || empty($row['InsuredName']) || empty($row['DOB']) || empty($row['DOC'])) {
continue;
}
$memberDetails[] = [
"EmployeeMemberId" => preg_replace('/[^A-Za-z0-9]/', '', (string) $row['MemberEmpId']),
"DOJ" => $formatDate($row['DOJ']),
"InsuredName" => $row['InsuredName'],
"DOB" => $formatDate($row['DOB']),
"Relationship" => strtoupper((string) $row['Relationship']),
"Gender" => $mapGender($row['Gender'] ?? ''),
"DOC" => $formatDate($row['DOC']),
"SumInsured" => $row['SumInsured'],
"EmailId" => $row['EmailId'],
"FlagStatus" => "A"
];
}, $data);
}
// Final body
return [
"PolicyNumber" => $data[0]['policyNumber'] ?? null,
"CDBGAccountNumber" => $data[0]['CDBGAccountNumber'] ?? null , // "CD-MUM-0026",
"CDBGAccountNumber" => $data[0]['CDBGAccountNumber'] ?? env('ICICI_CDBG_ACCOUNT_NUMBER'),
"CorrelationId" => $generateUUID(),
"MemberDetails" => $memberDetails
];

View File

@ -211,6 +211,14 @@ class JobWorker extends AdminController
'type' => 'CC', // Handler Category
'handler' => 'App\Controllers\HealthIndiaApiController',
],
'VoloGetBenefDetails' => [
'type' => 'CC', // Handler Category
'handler' => 'App\Controllers\VoloApiController',
],
'saveVoloAPIData' => [
'type' => 'CC', // Handler Category
'handler' => 'App\Controllers\VoloApiController',
],
'bdsDumpExcelFileFormatValidation' => [
'type' => 'CC', // Handler Category
'handler' => 'App\Controllers\PolicyTransactionController',
@ -242,6 +250,10 @@ class JobWorker extends AdminController
'visitOffBoard' => [
'type' => 'CC', // Handler Category
'handler' => 'App\Controllers\EmployeeController',
],
'ICICIPushEmployeeDetails' => [
'type' => 'CC', // Handler Category
'handler' => 'App\Controllers\ICICILombardController',
]
];

View File

@ -836,8 +836,8 @@ class LeadsController extends BaseController
'client_short_name' => $data['client_short_name'],
'entity_type_id' => $data['entity_type_id'],
'client_code' => $data['client_code'],
'pan' => $data['pan'],
'gst' => $data['gst'],
'pan' => $data['pan'] ?? null,
'gst' => $data['gst'] ?? null,
'branch_name' => $data['branch_name'],
'branch_code' => $data['branch_code'],
'contact_person_name' => $data['contact_person_name'],

View File

@ -1383,29 +1383,28 @@ class MediAssistApiController extends BaseController
$plainJson = json_encode($payload, JSON_UNESCAPED_SLASHES);
// Derive a 32byte key (AES256) and 16byte IV from the provided strings
// $key = substr(hash('sha256', $keyString, true), 0, 32);
// $iv = substr(hash('md5', $ivString, true), 0, 16);
// Encrypt with AES256CBC + PKCS7 padding (OpenSSL default)
$cipherTextRaw = openssl_encrypt($plainJson, $cipher_algorithm, $keyString, OPENSSL_RAW_DATA, $ivString);
// ✅ EXACT same as C#
$key = substr(str_pad($keyString, 32, '0'), 0, 32);
$iv = substr(str_pad($ivString, 16, '0'), 0, 16);
// Encrypt
$cipherTextRaw = openssl_encrypt($plainJson, $cipher_algorithm, $key, OPENSSL_RAW_DATA, $iv);
if ($cipherTextRaw === false) {
log_message('error', 'MEDI_ASSIST - Wellness SSO URL generation | Encryption failed while generating Medi Assist wellness token.');
return [
'status' => 'failed',
'message' => 'Encryption failed while generating Medi Assist wellness token.',
];
throw new \Exception('Encryption failed.');
}
// ✅ Step 1: Base64 encode
$base64Cipher = base64_encode($cipherTextRaw);
// Base64 encode and URLencode for use as EncryptedSSO
$encryptedSSO = urlencode(base64_encode($cipherTextRaw));
// $encryptedSSO = rtrim(strtr(base64_encode($cipherTextRaw), '+/', '-_'), '=');
// ✅ Step 2: PREFIX IV (CRITICAL — matches C#)
$encryptedSSO = $iv . $base64Cipher;
// Build the final login URL
$loginUrl = str_replace(['{0}', '{1}'], [$planId, $encryptedSSO], $loginUrlTemplate);
// ⚠️ URL encode (VERY IMPORTANT for this format)
$finalSSO = urlencode($encryptedSSO);
// Build URL
$loginUrl = str_replace(['{0}', '{1}'], [$planId, $finalSSO], $loginUrlTemplate);
log_message('error', 'MEDI_ASSIST - Wellness SSO URL generation | Medi Assist wellness SSO URL generated successfully.');

View File

@ -549,6 +549,8 @@ class PolicyTransactionController extends BaseController
public function viewInception()
{
$bds_edit_pt_id = $this->request->getGet('pt_id') ?? null;
$view = $this->request->getGet('view') ?? null;
$data['tab_name'] = 'Policies';
$data['page_name'] = 'Policies';
@ -618,7 +620,7 @@ class PolicyTransactionController extends BaseController
$issuer = empty($issuer) ? 0 : $issuer;
$status = empty($status) ? 0 : $status; // Corrected from `$issuer`
if(empty($bds_edit_pt_id)){
if(empty($bds_edit_pt_id) && empty($view)){
if ($this->request->is('get')) {
// Fetch inception data list

View File

@ -1322,7 +1322,7 @@ class TestingController extends BaseController
* If env values are not present, sensible dummy defaults are used so that
* the function can still be exercised.
*/
public function testMediAssistWellness()
public function testMediAssistWellnessOld()
{
// Configuration prefer environment variables, fall back to demo values
@ -1374,4 +1374,239 @@ class TestingController extends BaseController
],
], 200);
}
public function chartbrewDashboardDemo()
{
// 1. Configuration - Use a Chartbrew-specific Secret Key from .env
$chartbrew_base_url = "https://analytics.nhanceindia.in/report/my-first-dashboard-oHbWNWH0";
$chartbrew_secret = getenv('METABASE_SECRET_KEY'); // Ensure this is set in your .env
// 2. Get dynamic parameters (matching your screenshot's naming convention)
$policy_id = $this->request->getGet('client_policy_id') ?? 4687;
// 3. Define the Payload
// Note: 'sub' (Subject) should usually be the user ID or a unique identifier
// depending on Chartbrew's specific JWT requirements.
$payload = [
"sub" => [
"type" => "Project",
"id" => 4, // Integer type usually preferred
"sharePolicyId" => 4
],
"iat" => time(),
"exp" => time() + (10 * 60), // 10 minute expiration
];
// 4. Encode the JWT
// Make sure you have 'use Firebase\JWT\JWT;' at the top of your controller
$token = JWT::encode($payload, $chartbrew_secret, 'HS256');
// 5. Construct the URL
// We use http_build_query to ensure special characters are handled correctly
$params = [
'token' => $token,
'theme' => 'light',
'client_policy_id' => $policy_id
];
$url = $chartbrew_base_url . '?' . http_build_query($params);
// 6. Optional API response
if ($this->request->getGet('api') == 1) {
return $this->response->setJSON([
'status' => 'success',
'data' => [
'chartbrewUrl' => $url,
'policy_id' => $policy_id
]
]);
}
// 7. Return the View
return view('chartbrew_dashboard_view', [
'iframe_url' => $url,
'policy_id' => $policy_id
]);
}
public function testMediAssistWellness2()
{
// Config
$keyString = env('MEDIASSIST_WELLNESS_KEY');
$ivString = env('MEDIASSIST_WELLNESS_IV');
$loginUrlTemplate = env('MEDIASSIST_WELLNESS_LOGIN_URL');
$partnerCorpId = '15963';
$cipher_algorithm = 'AES-256-CBC';
// Payload (MATCH EXACT CASE from doc)
$payload = [
'Id' => '15022',
'expiryTime' => (string)(time() + 600), // string format safer
'CPartnerId' => $partnerCorpId,
];
$plainJson = json_encode($payload, JSON_UNESCAPED_SLASHES);
// ✅ IMPORTANT: Ensure correct key + IV length (ASCII based)
$key = substr(str_pad($keyString, 32, '0'), 0, 32); // 32 bytes
$iv = substr(str_pad($ivString, 16, '0'), 0, 16); // 16 bytes
// Encrypt
$cipherTextRaw = openssl_encrypt(
$plainJson,
$cipher_algorithm,
$key,
OPENSSL_RAW_DATA,
$iv
);
if ($cipherTextRaw === false) {
return $this->respond([
'status' => false,
'message' => 'Encryption failed.',
], 500);
}
// ✅ Use ONLY Base64 (NO urlencode unless explicitly required)
$encryptedSSO = base64_encode($cipherTextRaw);
// Build URL
$loginUrl = str_replace(
['{0}', '{1}'],
[$partnerCorpId, $encryptedSSO],
$loginUrlTemplate
);
return $this->respond([
'status' => true,
'data' => [
'loginUrl' => $loginUrl,
'encryptedSSO' => $encryptedSSO,
'plainPayload' => $payload,
'decryptMediAssistWellness' => $this->decryptMediAssistWellness($encryptedSSO),
],
], 200);
}
public function testMediAssistWellness()
{
try {
// Config
$keyString = env('MEDIASSIST_WELLNESS_KEY');
$ivString = env('MEDIASSIST_WELLNESS_IV');
$loginUrlTemplate = env('MEDIASSIST_WELLNESS_LOGIN_URL');
$partnerCorpId = '15963';
$cipher_algorithm = 'AES-256-CBC';
// Payload
$payload = [
'Id' => '15022',
'expiryTime' => (string)(time() + 600),
'CPartnerId' => $partnerCorpId,
];
$plainJson = json_encode($payload, JSON_UNESCAPED_SLASHES);
// ✅ EXACT same as C#
$key = substr(str_pad($keyString, 32, '0'), 0, 32);
$iv = substr(str_pad($ivString, 16, '0'), 0, 16);
// Encrypt
$cipherTextRaw = openssl_encrypt($plainJson,$cipher_algorithm,$key,OPENSSL_RAW_DATA,$iv);
if ($cipherTextRaw === false) {
throw new \Exception('Encryption failed.');
}
// ✅ Step 1: Base64 encode
$base64Cipher = base64_encode($cipherTextRaw);
// ✅ Step 2: PREFIX IV (CRITICAL — matches C#)
$encryptedSSO = $iv . $base64Cipher;
// ⚠️ URL encode (VERY IMPORTANT for this format)
$finalSSO = urlencode($encryptedSSO);
// Build URL
$loginUrl = str_replace(
['{0}', '{1}'],
[$partnerCorpId, $finalSSO],
$loginUrlTemplate
);
return $this->respond([
'status' => true,
'data' => [
'loginUrl' => $loginUrl,
'encryptedSSO' => $encryptedSSO,
'base64Only' => $base64Cipher,
'ivUsed' => $iv,
'plainPayload' => $payload,
],
], 200);
} catch (\Throwable $e) {
log_message('error', 'MediAssist SSO Error: ' . $e->getMessage());
return $this->respond([
'status' => false,
'message' => $e->getMessage(),
], 500);
}
}
public function decryptMediAssistWellness($encryptedSSO)
{
// Config
$keyString = env('MEDIASSIST_WELLNESS_KEY');
$ivString = env('MEDIASSIST_WELLNESS_IV');
$cipher_algorithm = 'AES-256-CBC';
// Ensure same key + IV format used in encryption
$key = substr(str_pad($keyString, 32, '0'), 0, 32); // 32 bytes
$iv = substr(str_pad($ivString, 16, '0'), 0, 16); // 16 bytes
// Decode Base64
$cipherTextRaw = base64_decode($encryptedSSO, true);
if ($cipherTextRaw === false) {
return [
'status' => false,
'message' => 'Invalid Base64 string.',
];
}
// Decrypt
$decrypted = openssl_decrypt(
$cipherTextRaw,
$cipher_algorithm,
$key,
OPENSSL_RAW_DATA,
$iv
);
if ($decrypted === false) {
return [
'status' => false,
'message' => 'Decryption failed.',
];
}
// Convert JSON to array
$data = json_decode($decrypted, true);
return [
'status' => true,
'data' => [
'decryptedRaw' => $decrypted,
'decoded' => $data
],
];
}
}

View File

@ -450,9 +450,10 @@ class TicketController extends BaseController
}
else{
$data['ticket_data'] = $this->ticketSearch();
// print_r($data['ticket_data']);die;
$html = view('ticket_list', $data);
return $this->respond(['status' => true, 'html' => $html], 200);
return $this->respond([
'status' => true,
'rows' => $data['ticket_data'] ?? [],
], 200);
}
}
@ -574,7 +575,9 @@ class TicketController extends BaseController
->join("({$subquery->getCompiledSelect()}) tat_category", 'tm.id = tat_category.ticket_id', 'left')
->where('tm.is_active', 1)
->whereNotIn('claim_status_id', [11, 12, 13, 22, 24, 32, 34, 42, 44, 47, 53, 58, 65])
->orderBy('tm.id', 'DESC');
->orderBy('tm.id', 'DESC')
->limit(100);
$data = $query->get()->getResultArray();

View File

@ -478,7 +478,7 @@ class VidalApiController extends BaseController
$body = [
'empNO' => "",
'tpaCardID' => "",
'claimID' => $ticket['claimID'],
'claimID' => $ticket['claimID'], //"GUR-0326-CL-0001471"
'emailID' => "",
'mobileNO' => "",
];
@ -487,6 +487,8 @@ class VidalApiController extends BaseController
$response = call_third_party_api($url, $method, $headers, $body);
// dd($url, $method, $headers, $body, $response);
if ($response['status'] != true || empty($response['data']['data']['claims'][0])) {
log_message('error', 'VIDAL - Claim Status FAILED | for ticket ID: ' . $claimId.' | response: '.json_encode($response));
@ -504,6 +506,7 @@ class VidalApiController extends BaseController
$tpa_claim_no = $claimData['claimNumber'] ?? '';
$currentStatus = $claimData['status'] ?? '';
$tpa_claim_type = $claimData['claimType'] ?? '';
$tpa_shortfall_no = $claimData['shortfallNo'] ?? '';
$doa = !empty($claimData['doa'] ?? null) ? date('Y-m-d', strtotime(str_replace('/', '-', $claimData['doa']))) : null;
@ -530,6 +533,9 @@ class VidalApiController extends BaseController
if (!empty($tpa_claim_type)) {
$updateArray['tpa_claim_type'] = $tpa_claim_type;
}
if (!empty($tpa_shortfall_no)) {
$updateArray['tpa_shortfall_no'] = $tpa_shortfall_no;
}
if($ticket['doa'] == $doa || $ticket['claim_number'] == $tpa_claim_no){
// UPDATE ticket_master
@ -1065,8 +1071,142 @@ class VidalApiController extends BaseController
return $result;
}
public function IRSubmission($claimId = null)
{
log_message('error', "VIDAL - IR Submission | INIT for ticket_id={$claimId}");
// 1. FETCH TICKET DETAILS
$ticket = $this->db->table('ticket_master tm')
->select("
tm.id,
tm.tpa_no as memberId,
tm.tpa_claim_push_reference_no as claimInwardNO,
tm.tpa_claim_id as claimNO,
tm.tpa_shortfall_no as shortfallNO,
cp.policy_no as policyNo,
cp.policy_start_date as startDate,
cp.policy_end_date as endDate,
e.emp_code as employeeCode
")
->join('employees e', 'e.id = tm.emp_id', 'left')
->join('client_policy cp', 'tm.client_policy_id = cp.id', 'left')
->where('tm.id', $claimId)
->get()
->getRowArray();
if (!$ticket || empty($ticket['claimNO'])) {
log_message('error', "VIDAL - IR Submission FAILED → ClaimID NOT FOUND for ticket_id={$claimId}");
return [
'status' => false,
'message' => "ClaimID not found for ticket {$claimId}"
];
}
// 2. FETCH IR ATTACHMENTS
$fileData = $this->db->table('claim_files f')
->where('f.ticket_id', $claimId)
->where('f.docs_for_ir', 1)
->get()
->getResultArray();
if (empty($fileData)) {
log_message('error', "VIDAL - IR Submission FAILED → No IR attachments found for ticket_id={$claimId}");
return [
'status' => false,
'message' => 'IR attachments not found for the claim'
];
}
// 3. UPLOAD FILES TO VIDAL
$fileIdList = [];
foreach ($fileData as $file) {
if (empty($file['filePath'])) {
continue;
}
$filename = basename($file['filePath']);
$fullPath = WRITEPATH . 'uploads/claim_files/' . $filename;
$upload = $this->uploadFileToVidal($fullPath, $filename);
if (empty($upload['status']) || $upload['status'] !== true) {
log_message('error', "VIDAL - IR Submission FAILED → File upload failed");
return [
'status' => false,
'message' => 'File upload failed',
'data' => $upload
];
}
$fileIdList[] = $upload['fileId']; // deeplink URL
}
if (empty($fileIdList)) {
return [
'status' => false,
'message' => 'No valid files uploaded'
];
}
// 4. PREPARE REQUEST BODY
$body = [
"shortFallNo" => $ticket['shortfallNO'],
];
// If single file → fileId
if (count($fileIdList) === 1) {
$body["fileId"] = $fileIdList[0];
} else {
$body["fileIdList"] = $fileIdList;
}
log_message('error', "VIDAL - IR Submission Request Body => " . json_encode($body));
// 5. API CALL
helper('api');
$url = env('VIDAL_API_BASE_URL_IRSUBMISSION');
$method = 'POST';
$headers = [
'Content-Type: application/json',
'Ocp-Apim-Subscription-Key: ' . getenv('VIDAL_SUBSCRIPTION_KEY'),
];
$response = call_third_party_api($url, $method, $headers, json_encode($body));
log_message('error', "VIDAL - IR Submission API Response => " . json_encode($response));
// 6. HANDLE RESPONSE
if (empty($response['status']) || $response['status'] !== true) {
log_message(
'error',
"VIDAL - IR Submission FAILED for ClaimNO={$ticket['claimNO']} → Response=" . json_encode($response)
);
return [
'status' => false,
'message' => 'IR Submission failed',
'data' => $response
];
}
log_message('error', "VIDAL - IR Submission SUCCESS → ClaimNO={$ticket['claimNO']}");
return [
'status' => true,
'message' => 'IR Submitted successfully',
'data' => $response
];
}
}

View File

@ -0,0 +1,924 @@
<?php
namespace App\Controllers;
use App\Controllers\BaseController;
use App\Controllers\Jobs;
use App\Models\BatchFileModel;
use App\Models\EmployeePolicyModel;
use App\Models\TpaApiDataModel;
use CodeIgniter\API\ResponseTrait;
/**
* TrueCover / EWA TPA APIs (ewatpa.com) Volo integration layer.
*
* @see Postman collection (login, enrollment, hospitals, documents, claim flows).
*/
class VoloApiController extends BaseController
{
use ResponseTrait;
protected $db;
protected $voloTpaId;
/** @var string|null Cached access token for the current request cycle */
private ?string $cachedAccessToken = null;
public function __construct()
{
$this->db = \Config\Database::connect();
$this->voloTpaId = getenv('VOLO_PRIMARY_KEY_CONSTANT');
}
protected function adminBaseUrl(): string
{
return rtrim((string) getenv('VOLO_API_ADMIN_BASE_URL'), '/');
}
protected function consumerBaseUrl(): string
{
return rtrim((string) getenv('VOLO_API_CONSUMER_BASE_URL'), '/');
}
/**
* Obtain API access token (login).
*
* @return string|null Full accessToken value as returned by API (includes "Token " prefix when applicable)
*/
public function getAccessToken(): ?string
{
if ($this->cachedAccessToken !== null) {
return $this->cachedAccessToken;
}
helper('api');
$url = $this->adminBaseUrl() . '/external/login';
$body = [
'emailId' => getenv('VOLO_API_EMAIL'),
'password' => getenv('VOLO_API_PASSWORD'),
'loggedInPortal' => getenv('VOLO_LOGGED_IN_PORTAL') ?: 'POLICY_CONFIGURATION_PORTAL',
];
$headers = ['Content-Type: application/json'];
$response = call_third_party_api($url, 'POST', $headers, $body);
if (empty($response['status'])) {
log_message('error', 'VOLO - Login failed | ' . json_encode($response));
return null;
}
$data = $response['data'] ?? null;
if (!is_array($data)) {
log_message('error', 'VOLO - Login invalid response shape | ' . json_encode($response));
return null;
}
$token = $data['accessToken'] ?? null;
if ($token === null || $token === '' || $token === 'Token null') {
log_message('error', 'VOLO - Login rejected or empty token | ' . json_encode($data));
return null;
}
$this->cachedAccessToken = $token;
return $this->cachedAccessToken;
}
/**
* @return array{0: bool, 1: array<int, string>}
*/
protected function authorizedJsonHeaders(): array
{
$token = $this->getAccessToken();
if ($token === null) {
return [false, []];
}
return [true, [
'Content-Type: application/json',
'Authorization: ' . $token,
]];
}
/**
* GET /trueclaim/tpa/get-Enrollment-dump
*/
public function getEnrollmentDumpByEndorsement(string $insurerPolicyNumber, string $endorsmentNo)
{
helper('api');
[$ok, $headers] = $this->authorizedJsonHeaders();
if (!$ok) {
return ['status' => false, 'message' => 'VOLO token failed'];
}
$query = http_build_query([
'insurerPolicyNumber' => $insurerPolicyNumber,
'endorsmentNo' => $endorsmentNo,
]);
$url = $this->adminBaseUrl() . '/trueclaim/tpa/get-Enrollment-dump?' . $query;
return call_third_party_api($url, 'GET', $headers, []);
}
/**
* GET /trueclaim/tpa/getHospitalByInsurerName
*/
public function getHospitalByInsurerName(string $insurerName)
{
helper('api');
[$ok, $headers] = $this->authorizedJsonHeaders();
if (!$ok) {
return ['status' => false, 'message' => 'VOLO token failed'];
}
$query = http_build_query(['insurerName' => $insurerName]);
$url = $this->adminBaseUrl() . '/trueclaim/tpa/getHospitalByInsurerName?' . $query;
return call_third_party_api($url, 'GET', $headers, []);
}
/**
* POST /trueclaim/tpa/doc
*
* @param array<string, mixed> $body
*/
public function uploadDocument(array $body)
{
helper('api');
[$ok, $headers] = $this->authorizedJsonHeaders();
if (!$ok) {
return ['status' => false, 'message' => 'VOLO token failed'];
}
$url = $this->adminBaseUrl() . '/trueclaim/tpa/doc';
return call_third_party_api($url, 'POST', $headers, $body);
}
/**
* GET /trueclaim/tpa/get-Enroll-dump
*/
public function getEnrollmentDump(string $insurerPolicyNumber)
{
helper('api');
[$ok, $headers] = $this->authorizedJsonHeaders();
if (!$ok) {
return ['status' => false, 'message' => 'VOLO token failed'];
}
$query = http_build_query(['insurerPolicyNumber' => $insurerPolicyNumber]);
$url = $this->adminBaseUrl() . '/trueclaim/tpa/get-Enroll-dump?' . $query;
return call_third_party_api($url, 'GET', $headers, []);
}
/**
* POST consumer /truecover/external-service/claim-status
*/
public function fetchExternalClaimStatus(string $tpaClaimNo)
{
helper('api');
[$ok, $headers] = $this->authorizedJsonHeaders();
if (!$ok) {
return ['status' => false, 'message' => 'VOLO token failed'];
}
$url = $this->consumerBaseUrl() . '/truecover/external-service/claim-status';
$body = ['tpaClaimNo' => $tpaClaimNo];
return call_third_party_api($url, 'POST', $headers, $body);
}
/**
* POST /trueclaim/tpa/getTpaData
*
* @return array<string, mixed>
*/
public function getTpaData(string $startDate, string $endDate, string $entityId)
{
helper('api');
[$ok, $headers] = $this->authorizedJsonHeaders();
if (!$ok) {
return ['status' => false, 'message' => 'VOLO token failed'];
}
$url = $this->adminBaseUrl() . '/trueclaim/tpa/getTpaData';
$body = [
'startDate' => $startDate,
'endDate' => $endDate,
'entityId' => $entityId,
];
return call_third_party_api($url, 'POST', $headers, $body);
}
/**
* GET /trueclaim/create-new-all-member-id-card-pdf
* Returns raw API response; body may contain base64 PDF payload.
*/
public function getEcardPdfRequest(string $employeeId, string $entityId)
{
helper('api');
[$ok, $headers] = $this->authorizedJsonHeaders();
if (!$ok) {
return ['status' => false, 'message' => 'VOLO token failed'];
}
$query = http_build_query([
'employeeId' => $employeeId,
'entityId' => $entityId,
]);
$url = $this->adminBaseUrl() . '/trueclaim/create-new-all-member-id-card-pdf?' . $query;
return call_third_party_api($url, 'GET', $headers, []);
}
/**
* GET /trueclaim/get-entity-from-policy
*/
public function getEntityFromPolicy(string $policyNumber)
{
helper('api');
[$ok, $headers] = $this->authorizedJsonHeaders();
if (!$ok) {
return ['status' => false, 'message' => 'VOLO token failed'];
}
$query = http_build_query(['policyNumber' => $policyNumber]);
$url = $this->adminBaseUrl() . '/trueclaim/get-entity-from-policy?' . $query;
return call_third_party_api($url, 'GET', $headers, []);
}
/**
* POST /trueclaim/policy-bazaar/intimate-claim
*
* @param array<string, mixed> $payload
*/
public function intimateClaim(array $payload)
{
helper('api');
[$ok, $headers] = $this->authorizedJsonHeaders();
if (!$ok) {
return ['status' => false, 'message' => 'VOLO token failed'];
}
$url = $this->adminBaseUrl() . '/trueclaim/policy-bazaar/intimate-claim';
return call_third_party_api($url, 'POST', $headers, $payload);
}
/**
* POST /trueclaim/tpa/getClaimData?claimId=
*/
public function getClaimData(string $claimId)
{
helper('api');
[$ok, $headers] = $this->authorizedJsonHeaders();
if (!$ok) {
return ['status' => false, 'message' => 'VOLO token failed'];
}
$query = http_build_query(['claimId' => $claimId]);
$url = $this->adminBaseUrl() . '/trueclaim/tpa/getClaimData?' . $query;
return call_third_party_api($url, 'POST', $headers, new \stdClass());
}
/**
* Pull enrollment from Volo (get-Enroll-dump), match members, update employee_polices.tpa_id (memberId).
* Same flow as MediAssistApiController::MediAssistGetBenefDetails.
*
* @param array<string, mixed> $requestData
* @return array<string, mixed>|\CodeIgniter\HTTP\Response
*/
public function VoloGetBenefDetails($requestData)
{
$function_calling_type = $requestData['return_type'] ?? 'job';
try {
helper(['api', 'utility']);
$policyNo = $requestData['policy_no'] ?? null;
$client_policy_id = $requestData['client_policy_id'] ?? null;
if (empty($policyNo)) {
log_message('error', 'VOLO - TPA ID Pull | policy_no missing in request');
if ($function_calling_type === 'job') {
return ['status' => false, 'message' => 'policy_no required'];
}
return $this->respond(['status' => false, 'message' => 'policy_no required']);
}
if (empty($client_policy_id)) {
log_message('error', 'VOLO - TPA ID Pull | client_policy_id missing in request');
if ($function_calling_type === 'job') {
return ['status' => false, 'message' => 'client_policy_id required'];
}
return $this->respond(['status' => false, 'message' => 'client_policy_id required']);
}
log_message('error', "VOLO - TPA ID Pull | called for policy_no: {$policyNo} , client_policy_id: {$client_policy_id}");
$employeePolicyModel = new EmployeePolicyModel();
$employeePolicyData = $employeePolicyModel
->select('
employees.*,
employee_polices.id as emp_policy_id,
employee_polices.client_policy_id,
')
->join('employees', 'employees.id = employee_polices.employee_id')
->where('employee_polices.is_active', 1)
->where('employee_polices.status', 'active')
->where('employees.is_active', 1)
->where('employees.emp_status', 'active')
->where('employee_polices.tpa_id IS NULL')
->where('employee_polices.client_policy_id', $client_policy_id)
->findAll();
if (empty($employeePolicyData)) {
log_message('error', 'VOLO - TPA ID Pull FAILED | employeePolicyData is empty (tpa_id IS NULL from nhance) for this TPA ID Pull request');
if ($function_calling_type === 'job') {
return ['status' => false, 'message' => 'employeePolicyData not found'];
}
return $this->respond(['status' => false, 'message' => 'employeePolicyData not found']);
}
$response = $this->getEnrollmentDump((string) $policyNo);
if (empty($response['status'])) {
if (isset($requestData['file_id']) && !empty($requestData['file_id'])) {
$file_model = new BatchFileModel();
$file_model->where('id', $requestData['file_id'])->set('status', 'failed-8')->update();
log_message('error', "VOLO - Files table status updated for the file id : {$requestData['file_id']}");
}
log_message('error', 'VOLO - TPA ID Pull API FAILED | ' . json_encode($response));
if ($function_calling_type === 'job') {
return ['status' => false, 'message' => 'API call failed', 'data' => $response];
}
return $this->respond(['status' => false, 'message' => 'API call failed', 'data' => $response]);
}
$apiPayload = $response['data'] ?? null;
if (!is_array($apiPayload)) {
log_message('error', 'VOLO - TPA ID Pull FAILED | invalid response shape | ' . json_encode($response));
if (isset($requestData['file_id']) && !empty($requestData['file_id'])) {
(new BatchFileModel())->where('id', $requestData['file_id'])->set('status', 'failed-8')->update();
}
if ($function_calling_type === 'job') {
return ['status' => false, 'message' => 'Invalid API response'];
}
return $this->respond(['status' => false, 'message' => 'Invalid API response']);
}
$allRows = $this->extractVoloEnrollmentRows($apiPayload);
if ($allRows === []) {
log_message('error', 'VOLO - TPA ID Pull FAILED | enrollment body empty | ' . json_encode($apiPayload));
if (isset($requestData['file_id']) && !empty($requestData['file_id'])) {
(new BatchFileModel())->where('id', $requestData['file_id'])->set('status', 'failed-8')->update();
}
if ($function_calling_type === 'job') {
return ['status' => false, 'message' => 'enrollment body empty'];
}
return $this->respond(['status' => false, 'message' => 'enrollment body empty']);
}
$totalCount = count($allRows);
log_message('error', "VOLO - TPA ID Pull | fetched {$totalCount} enrollment row(s)");
$json = json_encode($allRows, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
$filePath = WRITEPATH . 'tmp/' . time() . '_' . ($requestData['file_id'] ?? '0') . '_volo.json';
file_put_contents($filePath, $json);
if (!empty($requestData['file_id'])) {
Jobs::addJob([
'job_name' => 'saveVoloAPIData',
'payload' => [
'file_id' => $requestData['file_id'],
'json_file_path' => $filePath,
],
]);
}
$batch_file_success = 'success';
$updated = 0;
$employee_policy_ids = [];
foreach ($employeePolicyData as $policy_data) {
$hasMatchForThisPolicy = false;
foreach ($allRows as $row) {
if (!is_array($row)) {
continue;
}
$voloEmpCode = trim((string) ($row['memberEmployeeNo'] ?? $row['memberAltEmployeeNo'] ?? $row['empId'] ?? ''));
$voloMemberId = trim((string) ($row['memberId'] ?? ''));
if ($voloMemberId === '') {
continue;
}
if (
strtolower(trim((string) ($policy_data['name'] ?? ''))) === strtolower(trim((string) ($row['memberName'] ?? '')))
&& (string) ($policy_data['emp_code'] ?? '') === $voloEmpCode
&& $this->voloRelationsMatch((string) ($policy_data['relationship'] ?? ''), (string) ($row['relation'] ?? ''))
&& $this->voloGendersMatch((string) ($policy_data['gender'] ?? ''), (string) ($row['gender'] ?? ''))
&& $this->voloDobsMatch((string) ($policy_data['dob'] ?? ''), $row['DOB'] ?? $row['dob'] ?? null)
) {
$hasMatchForThisPolicy = true;
$sql = 'UPDATE employee_polices SET tpa_id = ? WHERE id = ?';
$this->db->query($sql, [$voloMemberId, $policy_data['emp_policy_id']]);
if (strtolower(trim((string) ($policy_data['relationship'] ?? ''))) === 'self') {
$employee_policy_ids[] = $policy_data['emp_policy_id'];
}
if ($this->db->affectedRows() > 0) {
$updated++;
log_message('error', "VOLO - Updated tpa_id={$voloMemberId} for emp_code={$voloEmpCode} policy={$policyNo}");
} else {
log_message('error', "VOLO - No update (already set or not matched) for emp_code={$voloEmpCode} policy={$policyNo}");
}
}
}
if (!$hasMatchForThisPolicy) {
$nhanceSideData = [
'name' => $policy_data['name'] ?? null,
'emp_code' => $policy_data['emp_code'] ?? null,
'relationship' => $policy_data['relationship'] ?? null,
'gender' => $policy_data['gender'] ?? null,
'dob' => $policy_data['dob'] ?? null,
];
$batch_file_success = 'partially success';
log_message('error', 'VOLO - No match for Nhance = ' . json_encode($nhanceSideData));
}
}
if ($employee_policy_ids !== []) {
log_message('error', 'VOLO - sendMailForDownloadingECard JOB PUSHED.');
Jobs::addJob(['job_name' => 'sendMailForDownloadingECard', 'payload' => ['ids' => $employee_policy_ids, 'client_policy_id' => $client_policy_id]]);
}
if (isset($requestData['file_id']) && !empty($requestData['file_id'])) {
$file_model = new BatchFileModel();
$file_model->where('id', $requestData['file_id'])->set('status', $batch_file_success)->update();
log_message('error', "VOLO - Files table status updated for the file id : {$requestData['file_id']}");
}
log_message('error', "VOLO - TPA ID Pull SUCCESS | Total fetched={$totalCount}, updated={$updated}");
if ($function_calling_type === 'job') {
return [
'status' => true,
'message' => 'Updated successfully',
'total_fetched' => $totalCount,
'total_updated' => $updated,
];
}
return $this->respond([
'status' => true,
'message' => 'Updated successfully',
'total_fetched' => $totalCount,
'total_updated' => $updated,
]);
} catch (\Throwable $th) {
if (isset($requestData['file_id']) && !empty($requestData['file_id'])) {
$file_model = new BatchFileModel();
$file_model->where('id', $requestData['file_id'])->set('status', 'failed-8')->update();
log_message('error', "VOLO - Files table status updated for the file id : {$requestData['file_id']}");
}
$errorData = [
'message' => $th->getMessage(),
'file' => $th->getFile(),
'line' => $th->getLine(),
];
log_message('error', 'VOLO - Exception in VoloGetBenefDetails: ' . json_encode($errorData));
if ($function_calling_type === 'job') {
return ['status' => false, 'message' => 'API call failed', 'data' => $errorData];
}
return $this->respond(['status' => false, 'message' => 'API call failed', 'data' => $errorData]);
}
}
/**
* Persist raw Volo enrollment rows into tpa_api_data (same pattern as saveMediAssitAPIData).
*
* @param array<string, mixed> $array
*/
public function saveVoloAPIData($array)
{
$file_id = $array['file_id'];
$json = file_get_contents($array['json_file_path']);
$records = json_decode($json, true);
if (!is_array($records)) {
return;
}
$file_model = new BatchFileModel();
$file_info = $file_model->where('id', $file_id)->find();
$tpaApiDataModel = new TpaApiDataModel();
$tpaApiDataModel->set('is_active', 0)->where('file_id', $file_id)->update();
$mappedRows = [];
foreach ($records as $row) {
if (!is_array($row)) {
continue;
}
$dobRaw = $row['DOB'] ?? $row['dob'] ?? null;
$dobYmd = null;
if ($dobRaw !== null && $dobRaw !== '') {
$dobYmd = $this->normalizeVoloDobToYmd($dobRaw);
}
$rel = trim((string) ($row['relation'] ?? ''));
$mappedRows[] = [
'file_id' => $file_id,
'emp_code' => trim((string) ($row['memberEmployeeNo'] ?? $row['empId'] ?? '')),
'name' => trim((string) ($row['memberName'] ?? '')),
'dob' => $dobYmd,
'relation' => $rel,
'gender' => $this->voloGenderToMediStyle((string) ($row['gender'] ?? '')),
'self' => in_array(strtoupper($rel), ['EMPLOYEE', 'SELF'], true) ? 1 : 0,
'tpa_id' => trim((string) ($row['memberId'] ?? '')),
'age' => isset($row['age']) && is_numeric($row['age']) ? (int) $row['age'] : null,
'is_active' => 1,
'created_by' => $file_info[0]['created_by'] ?? null,
];
}
if ($mappedRows !== []) {
$tpaApiDataModel->insertBatchWithChunkLog($mappedRows, 500, 'FILE_ID_' . $file_id);
}
}
/**
* @param array<string, mixed> $apiData Decoded JSON root from Volo get-Enroll-dump
* @return list<array<string, mixed>>
*/
protected function extractVoloEnrollmentRows(array $apiData): array
{
$body = $apiData['body'] ?? null;
if (is_array($body)) {
$out = [];
foreach ($body as $item) {
if (is_array($item)) {
$out[] = $item;
}
}
return $out;
}
return [];
}
protected function voloRelationsMatch(string $nhanceRel, string $voloRel): bool
{
$n = strtolower(trim(str_replace('-', ' ', $nhanceRel)));
$v = strtoupper(trim(str_replace('-', ' ', $voloRel)));
if ($n === 'self' && in_array($v, ['EMPLOYEE', 'PRIMARY', 'INSURED'], true)) {
return true;
}
return strtolower($v) === $n || $n === strtolower($v);
}
protected function voloGendersMatch(string $nh, string $volo): bool
{
return $this->genderNorm($nh) === $this->genderNorm($volo);
}
protected function genderNorm(string $g): string
{
$g = strtolower(trim($g));
if ($g === '' || $g === 'm' || strpos($g, 'male') === 0) {
return 'm';
}
if ($g === 'f' || strpos($g, 'female') === 0) {
return 'f';
}
return $g;
}
protected function voloDobsMatch(string $nhanceDob, mixed $voloDob): bool
{
$v = $this->normalizeVoloDobToYmd($voloDob);
if ($v === null || $v === '') {
return false;
}
$tsN = strtotime($nhanceDob);
if ($tsN === false) {
return false;
}
$n = date('Y-m-d', $tsN);
return $n === $v;
}
protected function normalizeVoloDobToYmd(mixed $dob): ?string
{
if ($dob === null || $dob === '') {
return null;
}
if (is_numeric($dob) && (float) $dob > 1_000_000_000_000) {
return date('Y-m-d', (int) (((float) $dob) / 1000));
}
$ts = strtotime(str_replace('/', '-', (string) $dob));
return $ts ? date('Y-m-d', $ts) : null;
}
protected function voloGenderToMediStyle(string $g): string
{
return $this->genderNorm($g) === 'f' ? 'F' : 'M';
}
/**
* Resolve entity id for a policy number (uses get-entity-from-policy).
*/
protected function resolveEntityId(string $policyNo): ?string
{
$fallback = getenv('VOLO_DEFAULT_ENTITY_ID');
if (!empty($fallback)) {
return (string) $fallback;
}
$res = $this->getEntityFromPolicy($policyNo);
if (empty($res['status']) || !is_array($res['data'])) {
return null;
}
$body = $res['data']['body'] ?? null;
if ($body === null || $body === '') {
return null;
}
return (string) $body;
}
//-----------------------------------------------------------------------------------------------------------------------------
/**
* Push claim via intimate-claim (policy-bazaar) API.
*/
public function SubmitClaim($claimId = null)
{
helper('api');
$data = $this->db->table('ticket_master tm')
->select('
tm.id,
tm.doa as admissionDate,
tm.dod as dischargeDate,
tm.claim_amount as requestedAmount,
tm.tpa_no as memberId,
cp.policy_no as policyNo,
cf.url as filePath
')
->join('client_policy cp', 'tm.client_policy_id = cp.id', 'left')
->join('claim_files cf', "cf.ticket_id = tm.id AND cf.file_type = 2 AND cf.mime_type = 'application/pdf'", 'left')
->where('tm.id', $claimId)
->get()
->getRowArray();
if (!$data) {
log_message('error', 'VOLO - Claim Push FAILED | claimId: ' . $claimId . ' | claim not found');
return ['status' => false, 'message' => 'Claim Push FAILED | Claim not found'];
}
if (empty($data['filePath'])) {
log_message('error', 'VOLO - Claim Push FAILED | claimId: ' . $claimId . ' | file missing');
return ['status' => false, 'message' => 'Claim Push FAILED | File Missing'];
}
$filename = basename($data['filePath']);
$pdfPath = WRITEPATH . 'uploads/claim_files/' . $filename;
if (!is_readable($pdfPath)) {
log_message('error', 'VOLO - Claim Push FAILED | claimId: ' . $claimId . ' | PDF not readable');
return ['status' => false, 'message' => 'Claim Push FAILED | PDF not found on server'];
}
$publicUrl = base_url('fileDownload?file_path=') . $pdfPath;
$entityId = $this->resolveEntityId($data['policyNo'] ?? '');
if ($entityId === null) {
log_message('error', 'VOLO - Claim Push FAILED | claimId: ' . $claimId . ' | entity id not resolved');
return ['status' => false, 'message' => 'Claim Push FAILED | entity id not resolved'];
}
$hospitalId = getenv('VOLO_DEFAULT_HOSPITAL_ID');
if ($hospitalId === false || $hospitalId === '') {
log_message('error', 'VOLO - Claim Push FAILED | claimId: ' . $claimId . ' | VOLO_DEFAULT_HOSPITAL_ID not set');
return ['status' => false, 'message' => 'Claim Push FAILED | hospital id not configured'];
}
$doa = !empty($data['admissionDate']) ? date('Y-m-d', strtotime($data['admissionDate'])) : '';
$dod = !empty($data['dischargeDate']) ? date('Y-m-d', strtotime($data['dischargeDate'])) : $doa;
$payload = [
'hospitalId' => (string) $hospitalId,
'memberId' => (string) ($data['memberId'] ?? ''),
'dateOfAdmission' => $doa,
'dateOfDischarge' => $dod,
'potentialClaimAmount' => (float) ($data['requestedAmount'] ?? 0),
'claimDocuments' => [
[
'documentName' => $filename,
'documentType' => 'medical_report',
'extension' => 'pdf',
'url' => $publicUrl,
],
],
'entityId' => (string) $entityId,
'insurerPolicyNumber' => (string) ($data['policyNo'] ?? ''),
];
log_message('error', 'VOLO - Claim Push | claimId: ' . $claimId . ' | payload: ' . json_encode($payload));
$response = $this->intimateClaim($payload);
if (empty($response['status'])) {
log_message('error', 'VOLO - Claim Push FAILED | claimId: ' . $claimId . ' | ' . json_encode($response));
$this->db->table('ticket_master')
->where('id', $claimId)
->update(['tpa_push_response' => json_encode($response)]);
return ['status' => false, 'message' => 'Claim Push FAILED', 'response' => $response];
}
$apiData = $response['data'] ?? null;
$ref = null;
if (is_array($apiData)) {
$ref = $apiData['message'] ?? null;
}
if (!empty($ref)) {
$this->db->table('ticket_master')
->where('id', $claimId)
->update([
'tpa_claim_push_reference_no' => $ref,
'tpa_claim_id' => $ref,
'updated_at' => date('Y-m-d H:i:s'),
]);
log_message('error', 'VOLO - Claim Push SUCCESS | claimId: ' . $claimId . ' | ref: ' . $ref);
return ['status' => true, 'message' => 'Claim Push SUCCESS', 'response' => $response];
}
log_message('error', 'VOLO - Claim Push empty reference | claimId: ' . $claimId . ' | ' . json_encode($response));
return ['status' => false, 'message' => 'Claim Push API response missing reference', 'response' => $response];
}
/**
* Refresh claim status from consumer claim-status service.
*/
public function ClaimDetail($claimId = null)
{
helper('api');
$ticket = $this->db->table('ticket_master tm')
->select('tm.id, tm.tpa_claim_push_reference_no, tm.tpa_claim_id')
->where('tm.id', $claimId)
->get()
->getRowArray();
if (!$ticket) {
return ['status' => false, 'message' => 'Invalid claim'];
}
$tpaClaimNo = $ticket['tpa_claim_push_reference_no'] ?? $ticket['tpa_claim_id'] ?? null;
if (empty($tpaClaimNo)) {
log_message('error', 'VOLO - Claim status | missing TPA claim ref | ticket: ' . $claimId);
return ['status' => false, 'message' => 'TPA claim reference missing'];
}
$response = $this->fetchExternalClaimStatus((string) $tpaClaimNo);
if (empty($response['status']) || !is_array($response['data'])) {
log_message('error', 'VOLO - Claim status FAILED | ticket: ' . $claimId . ' | ' . json_encode($response));
return ['status' => false, 'message' => 'API call failed', 'data' => $response];
}
$payload = $response['data'];
$body = $payload['body'] ?? $payload;
$currentStatus = '';
if (is_array($body)) {
$currentStatus = (string) ($body['status'] ?? $body['claim_status'] ?? '');
}
if ($currentStatus === '') {
log_message('error', 'VOLO - Claim status empty | ticket: ' . $claimId . ' | ' . json_encode($response));
return ['status' => false, 'message' => 'Status not found in response', 'data' => $response];
}
$validStatuses = [
'READY_TO_PAY' => 11,
'PAID' => 11,
'SETTLED' => 11,
'REJECTED' => 8,
'DENIED' => 8,
'QUERY' => 4,
'PRE_AUTH_QUERY_RESPONDED' => 4,
'PRE_AUTH_QUERY' => 4,
'MEMBER_UNENDORSED' => 5,
'In-Progress' => 5,
'UNDER_PROCESS' => 5,
'UNDER PROCESS' => 5,
];
$normalized = strtoupper(str_replace(' ', '_', trim($currentStatus)));
$claimStatusId = $validStatuses[$currentStatus] ?? ($validStatuses[$normalized] ?? 5);
$updateArray = [
'tpa_claim_status' => $currentStatus,
'updated_at' => date('Y-m-d H:i:s'),
'claim_status_id' => $claimStatusId,
];
$this->db->table('ticket_master')->where('id', $claimId)->update($updateArray);
log_message('error', 'VOLO - Claim status SUCCESS | ticket: ' . $claimId . ' | status: ' . $currentStatus);
return [
'status' => true,
'message' => 'Claim status updated.',
'updated_status' => $currentStatus,
'api_response' => $response,
];
}
public function ClaimStatusUpdate()
{
helper('api');
$tickets = $this->db->table('ticket_master tm')
->select('tm.id')
->join('client_policy cp', 'tm.client_policy_id = cp.id', 'left')
->where('tm.tpa_claim_push_reference_no IS NOT NULL')
->whereNotIn('tm.claim_status_id', [8, 11, 12, 13, 66, 22, 24, 47, 49, 32, 34, 53, 55, 42, 44, 58, 60])
->where('tm.is_active', 1)
->where('cp.tpa_id', $this->voloTpaId)
->get()
->getResultArray();
$count = 0;
foreach ($tickets as $t) {
$this->ClaimDetail($t['id']);
$count++;
}
return $this->response->setJSON(['status' => true, 'updated' => $count]);
}
/**
* E-card PDF returns a data URL the app can open, or null on failure.
*
* @param string|null $voloEmployeeId Volo/TPA employee or member id stored in employee_polices.tpa_id
*/
public function EcardRequest($emp_code = null, $policy_no = null, $voloEmployeeId = null)
{
if (empty($voloEmployeeId)) {
log_message('error', 'VOLO - Ecard | missing Volo employee/member id | emp_code: ' . ($emp_code ?? ''));
return null;
}
$entityId = $this->resolveEntityId((string) $policy_no);
if ($entityId === null) {
log_message('error', 'VOLO - Ecard | entity id not resolved | policy: ' . ($policy_no ?? ''));
return null;
}
$res = $this->getEcardPdfRequest((string) $voloEmployeeId, $entityId);
if (empty($res['status']) || !is_array($res['data'])) {
log_message('error', 'VOLO - Ecard FAILED | ' . json_encode($res));
return null;
}
$body = $res['data']['body'] ?? null;
if (!is_string($body) || $body === '') {
log_message('error', 'VOLO - Ecard FAILED | empty body | ' . json_encode($res));
return null;
}
return 'data:application/pdf;base64,' . $body;
}
}

View File

@ -18,14 +18,21 @@ class BatchFileModel extends Model
'event_type',
'actions',
'count',
"created_by",
"updated_by",
"is_active",
"amount",
"status",
"error_data",
"client_branch_id",
"policy_issue_date",
'created_by',
'updated_by',
'is_active',
'amount',
'status',
'error_data',
'client_branch_id',
'policy_issue_date',
// ICICI Lombard GPA batch fields
'icici_correlation_id',
'icici_batch_id',
'icici_status_flag',
'icici_status_message',
'icici_endorsement_policy_no',
'icici_uhid_status_flag',
];
// Callbacks

View File

@ -1177,6 +1177,7 @@ class EmployeePolicyModel extends Model
employee_polices.claim_status,
employee_polices.age_band,
employee_polices.tpa_id,
employee_polices.date_coverage,
batch_data.emp_policy_id AS emp_policy_id,

View File

@ -1112,7 +1112,7 @@
// Default to Last 30 Days if No Filters Are Applied
if (empty($client_id) && empty($insurer_id) && empty($policy_type_id) && empty($date_type) && empty($issuer) && empty($where)) {
$fromDate = date('Y-m-d', strtotime('-90 days'));
$fromDate = date('Y-m-d', strtotime('-30 days'));
$toDate = date('Y-m-d 23:59:59');
$builder->where('policy_transaction.created_at >=', $fromDate)

View File

@ -0,0 +1,10 @@
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<iframe src="<?= $iframe_url ?>" allowTransparency="true" width="1200" height="600" frameborder="0" style="background-color: #ffffff"></iframe>
</body>
</html>

View File

@ -2047,7 +2047,7 @@ input:checked + .slider_blue::before {
}
//append the CD Account number for the dropdown
function appendCDACNO(data, select = null) {
function appendCDACNOOld(data, select = null) {
//console.log('appendCDACNO', data);
//console.log('appendCDACNO', select);
@ -2084,6 +2084,30 @@ input:checked + .slider_blue::before {
$('#cd_ac_no').val(select).trigger('change');
}
}
function appendCDACNO(data, select = null) {
const $dropdown = $('#cd_ac_no');
// 1. Build everything as a single string/fragment instead of multiple appends
let optionsHtml = '<option value="">Select CD Account Number</option>';
if (!data || data.length === 0) {
optionsHtml += '<option value="add_cd">+ Add New CD</option>';
} else {
// 2. Faster Loop and String Concatenation
$.each(data, function(index, item) {
optionsHtml += `<option value="${item.id}">${item.cd_ac_no}</option>`;
});
}
// 3. Single DOM update (Idhu dhaan performance-ah boost pannum)
$dropdown.html(optionsHtml);
// 4. Handle Selection
if (select) {
$dropdown.val(select).trigger('change');
}
}
// append Base Policy to the dropdown for edit only
function appendBasePolicyList(data, select = null)

View File

@ -2086,7 +2086,10 @@ body[data-sidebar-size="condensed"] .footer {
<?php if (in_array(get_role_id(), [1, 5]) || (in_array(MANAGEMENT_TEAM_ID, user_team()) || in_array(FINANCE_TEAM_ID, user_team()) || in_array(BUSINESS_TEAM_ID, user_team()) || in_array(POS_TEAM_ID, user_team()))) { ?>
<li>
<a href="<?= base_url('/policy_tranction/inception/list') ?>">Policy</a>
<a href="<?= base_url('/policy_tranction/inception/list?view=1') ?>">Policy Add</a>
</li>
<li>
<a href="<?= base_url('/policy_tranction/inception/list') ?>">Policy List</a>
</li>
<!-- <li>
<a href="<?= base_url('/policy_tranction/inception/list2') ?>">Policy 2</a>

View File

@ -395,6 +395,27 @@ table.dataTable tbody td {
</div>
</div>
</div>
<div class="modal fade" id="policyNoAddModal" tabindex="-1" role="dialog" aria-labelledby="policyNoAddModalLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="policyNoAddModalLabel">Add policy</h5>
<button type="button" id="close_btn" class="close" data-dismiss="modal" aria-hidden="true">x</button>
</div>
<div class="modal-body">
<label for="modal_policy_no">Policy number</label>
<input type="text" class="form-control" id="modal_policy_no" name="modal_policy_no" autocomplete="off" placeholder="Enter policy number">
<small class="text-danger d-block mt-1" id="policy_no_add_modal_feedback"></small>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" onclick="hidePolicyNoAddModal()">Cancel</button>
<button type="button" class="btn btn-outline-primary" onclick="runInceptionAddFlowFromList()">Proceed to Add</button>
<button type="button" class="btn btn-primary" id="policyNoModalCheck">Check</button>
</div>
</div>
</div>
</div>
<script>
/* Modified by Gemini Code Assist */
function openPolicyFilterNav() {
@ -547,6 +568,7 @@ $(document).ready(function(){
getClientAndBranchAndPolicy()
addHTMLInput();
addHTMLInputForVehicleFileUpload()
getAddPage();
<?php if (session()->has('create_failed')) : ?>
toastr.error('<?= session()->getFlashdata('create_failed') ?>', 'Failed');
@ -577,9 +599,87 @@ $(document).ready(function(){
$('#ppteam').select2();
})
function openPolicyNoAddModal() {
var myModal = new bootstrap.Modal(document.getElementById('policyNoAddModal'));
myModal.show();
}
function runInceptionAddFlowFromList() {
hide_list_show_add();
addInsurerColumn();
addHTMLInput(null, 'policy_docs_div');
$('#policy_docs').show();
$('.close').click();
}
function validatePolicyNoForAdd() {
var pn = ($('#modal_policy_no').val() || '').trim();
$('#policy_no_add_modal_feedback').text('');
if (!pn) {
$('#policy_no_add_modal_feedback').text('Please enter a policy number.');
return;
}
$('.loader').fadeIn();
$('.loader-mask').fadeIn();
$.ajax({
url: '<?= base_url('/util/get_client_policy_data_using_policy_no') ?>',
type: 'GET',
data: { policy_no: pn },
dataType: 'json',
success: function (res) {
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
var msg = (res && res.message) ? String(res.message) : 'Unable to validate policy number.';
if ("pt_id" in res) {
console.log("PT ID exists:", res.pt_id);
getPolicyTransactionDataForEdit(res.pt_id);
$('.close').click();
} else if("is_dublicate" in res){
runInceptionAddFlowFromList();
toastr.success(msg,'SUCCESS');
} else {
toastr.warning(msg,'WARNING');
}
},
error: function () {
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
}
});
}
function getAddPage(){
const params = new URLSearchParams(window.location.search);
const view = params.get('view') ?? 0;
if(view == 1){
runInceptionAddFlowFromList();
}
}
// Datatable document ready
$(document).ready(function() {
$('#policyNoModalCheck').on('click', function () {
validatePolicyNoForAdd();
});
$('#policyNoModalProceedAdd').on('click', function () {
proceedToAddFromPolicyNoModal();
});
$(document).on('keydown', '#modal_policy_no', function (e) {
if (e.key === 'Enter') {
e.preventDefault();
validatePolicyNoForAdd();
}
});
var ticketsTable = $('#tickets-table');
if (ticketsTable.length) {
@ -605,10 +705,7 @@ $(document).ready(function() {
text: '<i class="mdi mdi-plus" ></i><span class=" btn-custom"> Add </span>',
className: 'btn app-btn-primary mr-2',
action: function (e, dt, node, config) {
hide_list_show_add();
addInsurerColumn();
addHTMLInput(null, 'policy_docs_div');
$('#policy_docs').show()
openPolicyNoAddModal();
}
},
{

View File

@ -268,18 +268,173 @@ table.dataTable tbody td {
<!-------------------------------------------------------------------------------------------------->
<script>
$(document).ready(function() {
window.ticketTableInstance = window.ticketTableInstance || null;
window.ticketTableIsDeleteEnabled = <?= in_array(get_role_id(), [1,2,5]) ? 'true' : 'false'; ?>;
window.ticketTypeMap = <?= json_encode($ticket_type ?? []); ?>;
window.priorityTypeMap = <?= json_encode($priorityType ?? []); ?>;
window.modeOfIntimateMap = <?= json_encode($modeOFIntimate ?? []); ?>;
window.claimTypeMap = <?= json_encode($claimType ?? []); ?>;
function escapeHtml(value) {
if (value === null || value === undefined) return '';
return String(value)
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#039;');
}
function asText(value) {
if (value === null || value === undefined || value === '') return 'N/A';
return escapeHtml(value);
}
function getClaimTypeLabel(row) {
var typeId = Number(row.ticket_type_id || 0);
var claimKey = row.claim_type || '';
if (!window.claimTypeMap[typeId]) return '';
return window.claimTypeMap[typeId][claimKey] || '';
}
function getStatusDisplay(row) {
var status = row.status || '';
var claimStatusId = Number(row.claim_status_id || 0);
var approved = Number(row.is_head_approved);
var statusesWithIcon = [8, 23, 33, 43];
if (statusesWithIcon.indexOf(claimStatusId) !== -1) {
if (approved === 0) return escapeHtml(status) + '&nbsp;<i class="fa fa-exclamation-triangle" style="color:#cece00;" aria-hidden="true"></i>';
if (approved === 1) return escapeHtml(status) + '&nbsp;<i class="mdi mdi-check-circle" style="color:green;" aria-hidden="true"></i>';
if (approved === 2) return escapeHtml(status) + '&nbsp;<i class="mdi mdi-close-circle-outline" style="color:red;" aria-hidden="true"></i>';
}
return escapeHtml(status);
}
function getStatusTooltip(row) {
var status = row.status || '';
if (Number(row.claim_status_id) === 8) {
if (Number(row.is_head_approved) === 0) return 'Waiting for approvel';
if (Number(row.is_head_approved) === 1) return 'Rejection approved';
if (Number(row.is_head_approved) === 2) return 'Rejection not approved';
}
return status;
}
function getActionCell(row) {
if (!window.ticketTableIsDeleteEnabled) return '';
var id = escapeHtml(row.id || '');
return '' +
'<td>' +
' <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 delete" data-id="' + id + '" onclick="removeClaim(this, \'' + id + '\')">' +
' <i class="mdi mdi-delete mr-2 text-muted font-18 vertical-middle"></i>Delete' +
' </a>' +
' </div>' +
' </div>' +
'</td>';
}
function buildTicketRowHtml(row) {
var statusUpdated = row.ticket_updated_date ? '<span class="text-custom-grey"><br>Updated at ' + escapeHtml(row.ticket_updated_date) + '</span>' : '';
var claimCreated = row.ticket_created_date ? '<span class="text-custom-grey"><br>Created at ' + escapeHtml(row.ticket_created_date) + '</span>' : '';
var policyType = (window.ticketTypeMap[row.ticket_type_id] || '').replace('Claim-', '');
var modeOfIntimation = window.modeOfIntimateMap[row.mode_of_intimation] || '';
var priority = window.priorityTypeMap[row.priority || 0] || '';
return '' +
'<tr data-id="' + escapeHtml(row.id) + '" style="cursor: pointer;">' +
'<td data-toggle="tooltip" data-placement="top" title="' + escapeHtml(getStatusTooltip(row)) + '">' +
'<span class="status-tooltip">' + getStatusDisplay(row) + '</span>' +
statusUpdated +
'</td>' +
'<td>' + asText(policyType) + '</td>' +
'<td>' + asText(row.claim_no) + claimCreated + '</td>' +
'<td>' + asText(row.tpa_no) + '</td>' +
'<td>' + asText(row.emp_code) + '</td>' +
'<td>' + asText(row.emp_name) + '</td>' +
'<td>' + asText(row.insured_name) + '</td>' +
'<td>' + asText(row.short_name) + '</td>' +
'<td style="display: none;">' + escapeHtml(row.acm_name || '') + '</td>' +
'<td style="display: none;">' + escapeHtml(row.insurer_name || '') + '</td>' +
'<td style="display: none;">' + escapeHtml(row.tpa_name || '') + '</td>' +
'<td style="display: none;">' + escapeHtml(row.policy_no || '') + '</td>' +
'<td style="display: none;">' + escapeHtml(priority) + '</td>' +
'<td style="display: none;">' + escapeHtml(row.relationship || '') + '</td>' +
'<td style="display: none;">' + escapeHtml(row.emp_mobile || '') + '</td>' +
'<td style="display: none;">' + escapeHtml(row.emp_mail || '') + '</td>' +
'<td style="display: none;">' + escapeHtml(row.emp_personal_mail || '') + '</td>' +
'<td style="display: none;">' + escapeHtml(modeOfIntimation) + '</td>' +
'<td style="display: none;">' + escapeHtml(getClaimTypeLabel(row)) + '</td>' +
'<td style="display: none;">' + escapeHtml(row.hospital_name || '') + '</td>' +
'<td style="display: none;">' + escapeHtml(row.doa || '') + '</td>' +
'<td style="display: none;">' + escapeHtml(row.dod || '') + '</td>' +
'<td style="display: none;">' + escapeHtml(row.claim_amount || '') + '</td>' +
'<td style="display: none;">' + escapeHtml(row.pod_no || '') + '</td>' +
'<td style="display: none;">' + escapeHtml(row.date_of_join || '') + '</td>' +
'<td style="display: none;">' + escapeHtml(row.date_of_incep || '') + '</td>' +
'<td style="display: none;">' + escapeHtml(row.dob || '') + '</td>' +
'<td style="display: none;">' + escapeHtml(row.date_of_accident || '') + '</td>' +
'<td style="display: none;">' + escapeHtml(row.date_of_death || '') + '</td>' +
'<td style="display: none;">' + escapeHtml(row.date_of_intimat || '') + '</td>' +
'<td style="display: none;">' + escapeHtml(row.si_amt || '') + '</td>' +
'<td style="display: none;">' + escapeHtml(row.raised_date || '') + '</td>' +
'<td style="display: none;">' + escapeHtml(row.registration_date || '') + '</td>' +
'<td style="display: none;">' + escapeHtml(row.query_received_date || '') + '</td>' +
'<td style="display: none;">' + escapeHtml(row.denial_date || '') + '</td>' +
'<td style="display: none;">' + escapeHtml(row.approved_date || '') + '</td>' +
'<td style="display: none;">' + escapeHtml(row.settled_date || '') + '</td>' +
'<td style="display: none;">' + escapeHtml(row.denial_reason || '') + '</td>' +
'<td style="display: none;">' + escapeHtml(row.approved_letter || '') + '</td>' +
'<td style="display: none;">' + escapeHtml(row.approved_amount || '') + '</td>' +
'<td style="display: none;">' + escapeHtml(row.utr_details || '') + '</td>' +
'<td style="display: none;">' + escapeHtml(row.settle_letter || '') + '</td>' +
'<td style="display: none;">' + escapeHtml(row.return_remark || '') + '</td>' +
'<td style="display: none;">' + escapeHtml(row.cancel_remark || '') + '</td>' +
'<td style="display: none;">' + escapeHtml(row.awb_no_courier_name || '') + '</td>' +
'<td style="display: none;">' + escapeHtml(row.non_id_reason || '') + '</td>' +
'<td style="display: none;">' + escapeHtml(row.pay_initiate_date || '') + '</td>' +
'<td style="display: none;">' + escapeHtml(row.approved_description || '') + '</td>' +
'<td>' + escapeHtml(row.tat || '') + '</td>' +
getActionCell(row) +
'</tr>';
}
function applyTicketRows(rows) {
var table = $('#scroll-horizontal-datatable');
var tbody = table.find('tbody');
var html = '';
(rows || []).forEach(function (row) {
html += buildTicketRowHtml(row);
});
if (window.ticketTableInstance) {
window.ticketTableInstance.clear();
tbody.html(html);
window.ticketTableInstance.rows.add(tbody.find('tr')).draw();
} else {
tbody.html(html);
}
$('[data-toggle="tooltip"]').tooltip();
}
window.updateTicketTableRows = applyTicketRows;
$(document).ready(function() {
$('[data-toggle="tooltip"]').tooltip();
});
// Datatable document ready
$(document).ready(function() {
var ticketsTable = $('#scroll-horizontal-datatable');
if (ticketsTable.length) {
ticketsTable.DataTable({
if (ticketsTable.length && !window.ticketTableInstance) {
window.ticketTableInstance = ticketsTable.DataTable({
scrollX: true,
// dom: "<'row'<'col-sm-6'f><'col-sm-6 text-right'B>>" + // Filter left, buttons right
// "<'row'<'col-sm-12'tr>>" +
@ -364,8 +519,8 @@ $(document).ready(function() {
pageLength: 10, // Set default number of rows per page (optional)
ordering: false,
});
} else {
console.error("Table atet found.");
} else if (!ticketsTable.length) {
console.error("Table not found.");
}
});

View File

@ -287,8 +287,9 @@
console.log('Filter Responce', response);
if (response.status == true) {
$('#ticket_list_div').empty();
$('#ticket_list_div').html(response.html);
if (typeof window.updateTicketTableRows === 'function') {
window.updateTicketTableRows(response.rows || []);
}
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
@ -331,8 +332,9 @@
console.log('Filter Responce', response);
if (response.status == true) {
$('#ticket_list_div').empty();
$('#ticket_list_div').html(response.html);
if (typeof window.updateTicketTableRows === 'function') {
window.updateTicketTableRows(response.rows || []);
}
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');

View File

@ -0,0 +1,76 @@
<?php
namespace Tests\unit;
use App\Controllers\ICICILombardController;
use CodeIgniter\Test\CIUnitTestCase;
class ICICILombardControllerTest extends CIUnitTestCase
{
public function testFormatPolicyDataBuildsExpectedBatchPayload(): void
{
$controller = new ICICILombardController();
// Sample rows matching createEnrollmentBatch query output shape.
$input = [
[
'policyNumber' => '4016/PPN/A/O/53185987/00/000',
'CDBGAccountNumber' => 'CD-MUM-0026',
'MemberEmpId' => 'EMPID3625567',
'DOJ' => '2019-03-21',
'InsuredName' => 'sanjeev',
'DOB' => '1993-07-07',
'Relationship' => 'SELF',
'Gender' => 'male',
'DOC' => '25-Jan-2026',
'SumInsured' => '500000',
'EmailId' => 'sanjeev@GMAIL.COM',
],
[
'policyNumber' => '4016/PPN/A/O/53185987/00/000',
'CDBGAccountNumber' => 'CD-MUM-0026',
'MemberEmpId' => 'EMPID3625567',
'DOJ' => '2019-03-21',
'InsuredName' => 'bhavya',
'DOB' => '1970-08-08',
'Relationship' => 'MOTHER',
'Gender' => 'female',
'DOC' => '25-Jan-2026',
'SumInsured' => null,
'EmailId' => 'bhavya@GMAIL.COM',
],
];
$result = $controller->formatPolicyData($input);
$this->assertIsArray($result);
$this->assertSame('4016/PPN/A/O/53185987/00/000', $result['PolicyNumber']);
$this->assertSame('CD-MUM-0026', $result['CDBGAccountNumber']);
$this->assertMatchesRegularExpression(
'/^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/i',
$result['CorrelationId']
);
$this->assertCount(2, $result['MemberDetails']);
$first = $result['MemberDetails'][0];
$this->assertSame('EMPID3625567', $first['EmployeeMemberId']);
$this->assertSame('21-MAR-2019', $first['DOJ']);
$this->assertSame('sanjeev', $first['InsuredName']);
$this->assertSame('7-JUL-1993', $first['DOB']);
$this->assertSame('SELF', $first['Relationship']);
$this->assertSame('MALE', $first['Gender']);
$this->assertSame('25-JAN-2026', $first['DOC']);
$this->assertSame('500000', $first['SumInsured']);
$this->assertSame('sanjeev@GMAIL.COM', $first['EmailId']);
$this->assertSame('A', $first['FlagStatus']);
$second = $result['MemberDetails'][1];
$this->assertSame('bhavya', $second['InsuredName']);
$this->assertSame('8-AUG-1970', $second['DOB']);
$this->assertSame('MOTHER', $second['Relationship']);
$this->assertSame('FEMALE', $second['Gender']);
$this->assertSame('25-JAN-2026', $second['DOC']);
$this->assertNull($second['SumInsured']);
}
}