nhance/app/Controllers/ICICILombardController.php

546 lines
20 KiB
PHP

<?php
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');
$url = env('ICICI_TOKEN_URL');
$method = 'POST';
$headers = [
'Content-Type: application/x-www-form-urlencoded'
];
$body = [
'grant_type' => env('ICICI_GRANT_TYPE'),
'username' => env('ICICI_USER_NAME'),
'password' => env('ICICI_PASSWORD'),
'scope' => $scope ?: env('ICICI_API_SCOPE'),
'client_id' => env('ICICI_CLIENT_ID'),
'client_secret' => env('ICICI_CLIENT_SECRET')
];
$response = call_third_party_api($url, $method, $headers, $body);
if($response['status'] != true){
return $this->response->setJSON([
'status' => false,
'message' => 'Token generation failed.',
'data' => $response
]);
}
// Debug removed: return token response to caller.
return $response;
}
public function createEnrollmentBatch()
{
$client_id = $this->request->getGet('client_id');
$client_branch_id = $this->request->getGet('client_branch_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('esbgpabatchcreation');
if (!$tokenResponse || empty($tokenResponse['data']['access_token'])) {
return $this->response->setJSON([
'status' => false,
'message' => 'Token generation failed.',
'data' => $tokenResponse
]);
}
$token = $tokenResponse['data']['access_token'];
$url = env('ICICI_BASE_URL').'/batchcreation';
$headers = [
'Authorization: Bearer ' . $token,
'Content-Type: application/json',
];
// 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,
]);
}
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
// 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);
}
public function getEnrollmentBatchStatus()
{
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('esbgpabatchstatus');
if (!$tokenResponse || empty($tokenResponse['data']['access_token'])) {
return $this->response->setJSON([
'status' => false,
'message' => 'Token generation failed.',
'data' => $tokenResponse
]);
}
$token = $tokenResponse['data']['access_token'];
$url = env('ICICI_BASE_URL').'/batchstatus';
$headers = [
'Authorization: Bearer ' . $token,
'Content-Type: application/json'
];
$db = \Config\Database::connect();
// 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');
if (!empty($clientPolicyId)) {
$query->where('bf.client_policy_id', (int) $clientPolicyId);
}
$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');
// 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' => 'client_policy_id is required.',
'data' => [],
]);
}
$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();
if (empty($batch)) {
return $this->response->setJSON([
'status' => false,
'message' => 'No completed ICICI GPA batch found for UHID fetch.',
'data' => [],
]);
}
$uhidResult = $this->fetchUhidAndUpdateEmployeePolicies($batch, $imid);
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 as DD-MMM-YYYY (e.g. 7-JUL-1993)
$formatDate = function ($date) {
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
$generateUUID = function () {
return sprintf(
'%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
mt_rand(0, 0xffff),
mt_rand(0, 0xffff),
mt_rand(0, 0xffff),
mt_rand(0, 0x0fff) | 0x4000,
mt_rand(0, 0x3fff) | 0x8000,
mt_rand(0, 0xffff),
mt_rand(0, 0xffff),
mt_rand(0, 0xffff)
);
};
$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"
];
}
// Final body
return [
"PolicyNumber" => $data[0]['policyNumber'] ?? null,
"CDBGAccountNumber" => $data[0]['CDBGAccountNumber'] ?? env('ICICI_CDBG_ACCOUNT_NUMBER'),
"CorrelationId" => $generateUUID(),
"MemberDetails" => $memberDetails
];
}
// $body = [
// "PolicyNumber" => "4016/A/O/53077718/00/000",
// "CDBGAccountNumber" => "CD-MUM-0026",
// "CorrelationId" => "550e8400-e29b-41d4-a716-446655440001",
// "MemberDetails" => [
// [
// "MemberEmpId" => "EMPID3625557",
// "DOJ" => "21-MAR-2019",
// "InsuredName" => "Kumar",
// "DOB" => "7-JUL-1983",
// "Relationship" => "SELF",
// "Gender" => "MALE",
// "DOC" => "08-JUL-2025",
// "SumInsured" => "400000",
// "EmailId" => "KUMAR@GMAIL.COM",
// "FlagStatus" => "A"
// ],
// [
// "MemberEmpId" => "EMPID3625557",
// "DOJ" => "21-MAR-2019",
// "InsuredName" => "Saranya",
// "DOB" => "8-AUG-1970",
// "Relationship" => "MOTHER",
// "Gender" => "FEMALE",
// "DOC" => "08-JUL-2025",
// "SumInsured" => "400000",
// "EmailId" => "Saranya@GMAIL.COM",
// "FlagStatus" => "A"
// ],
// ]
// ];
}