nhance/app/Controllers/HealthIndiaApiController.php
2026-07-15 15:49:13 +05:30

1110 lines
47 KiB
PHP

<?php
namespace App\Controllers;
use App\Controllers\BaseController;
use App\Controllers\TicketController;
use App\Models\BatchFileModel;
use App\Models\EmployeePolicyModel;
use App\Models\TpaApiDataModel;
use App\Models\ClientPolicyModel;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\API\ResponseTrait;
use App\Controllers\Jobs;
class HealthIndiaApiController extends BaseController
{
use ResponseTrait;
protected $db;
protected $healthIndiaTpaId;
protected $claim_type_array;
protected $ticketController;
public function __construct()
{
$this->db = \Config\Database::connect();
$this->healthIndiaTpaId = getenv('HEALTH_INDIA_PRIMARY_KEY_CONSTANT');
$this->ticketController = new TicketController();
$this->claim_type_array = $this->ticketController->claimType;
}
public function generateAuthToken()
{
$url = getenv('HEALTH_INDIA_TOKEN_URL'); // https://software.healthindiatpa.com/HIITPABROKERAPI/JWT/GenerateJWTAuth
// Basic Authentication credentials
$username = getenv('HEALTH_INDIA_USERNAME'); // /MU4gwfBYC71M1QnczasegH0vPM5IMbESO4iy4wbUrQ=
$password = getenv('HEALTH_INDIA_PASSWORD'); // KoVi+w2WGA+ET6fHN3kdBamHNsDKbA+kUtuF++4jWcg=
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_USERPWD => $username . ':' . $password,
CURLOPT_POSTFIELDS => '{}',
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'Accept: application/json',
],
CURLOPT_TIMEOUT => 30,
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (curl_errno($ch)) {
log_message('error', 'HEALTH_INDIA TOKEN GENERATION FAILED | Error: ' . curl_error($ch));
curl_close($ch);
return ['status' => false, 'error' => curl_error($ch)];
}
curl_close($ch);
$responseData = json_decode($response, true);
if ($httpCode === 200 && isset($responseData['status']) && $responseData['status'] === true) {
log_message('error', 'HEALTH_INDIA TOKEN GENERATION SUCCESS | Token: ' . ($responseData['result'][0]['access_token'] ?? 'N/A'));
} else {
log_message('error', 'HEALTH_INDIA TOKEN GENERATION FAILED | Response: ' . $response);
}
return [
'status' => $httpCode === 200,
'http_code' => $httpCode,
'data' => $responseData,
];
}
public function SubmitClaim($claimId = null)
{
helper(['api', 'tpa_claim_push_log', 'utility']);
tpa_claim_push_log($claimId, 'HEALTH_INDIA - Claim Push | Started for claimId: ' . $claimId);
$data = $this->db->table('ticket_master tm')
->select('
tm.id,
tm.emp_mobile as mobileNo,
tm.emp_mail as emailId,
tm.doa as admissionDate,
tm.dod as dischargeDate,
tm.hospital_pin_code as hospitalCode,
tm.hospital_name as hospitalName,
tm.hospital_address as hospitalAddress,
tm.hospital_phone_no as hospitalNumber,
tm.claim_amount as claimedAmount,
tm.tpa_no as memberId,
tm.claim_description as ailmentDescription,
cp.policy_no as policyNumber,
e.emp_code as employeeCode,
tn.note as disease,
cf.id as fileId,
cf.url as filePath,
tm.claim_type as claimType,
tm.claim_type as benefitType
')
->join('employees e', 'e.id = tm.emp_id', 'left')
->join('client_policy cp', 'tm.client_policy_id = cp.id', 'left')
->join('ticket_notes tn', 'tn.ticket_id = tm.id', 'left')
->join('claim_files cf', "cf.ticket_id = tm.id AND cf.file_type = 4 AND cf.is_active = 1 AND cf.mime_type = 'application/pdf'", 'left')
->where('tm.id', $claimId)
->get()
->getRowArray();
// dd($data);
if (!$data) {
tpa_claim_push_log($claimId, "HEALTH_INDIA - Claim Push FAILED | claimId: {$claimId} - Claim not found");
return ['status' => false, 'message' => 'Claim Push FAILED | Claim not found'];
}
if ($data['filePath'] == null) {
tpa_claim_push_log($claimId, "HEALTH_INDIA - Claim Push FAILED | claimId: {$claimId} - File Missing");
return ['status' => false, 'message' => 'Claim Push FAILED | File Missing'];
}
$file_id = $data['fileId'] ?? null;
$filename = basename($data['filePath']);
$resolved = storage_resolve_claim_file_path(WRITEPATH . 'uploads/claim_files', $filename);
if (!($resolved['success'] ?? false) || empty($resolved['path'])) {
tpa_claim_push_log($claimId, "HEALTH_INDIA - Claim Push FAILED | claimId: {$claimId} - PDF not found in local/S3 for file: {$filename}");
return ['status' => false, 'message' => 'Claim Push FAILED | PDF not found on server'];
}
$rawContent = @file_get_contents($resolved['path']);
storage_cleanup_temp_claim_file($resolved);
if ($rawContent === false) {
tpa_claim_push_log($claimId, "HEALTH_INDIA - Claim Push FAILED | claimId: {$claimId} - Unable to read file for base64: {$filename}");
return ['status' => false, 'message' => 'Claim Push FAILED | PDF not readable'];
}
$fileContent = base64_encode($rawContent);
// Generate Health India Token
$tokenResponse = $this->generateAuthToken();
if (empty($tokenResponse['data']['result'][0]['access_token'])) {
tpa_claim_push_log($claimId, "HEALTH_INDIA - Claim Push FAILED | claimId: {$claimId} - Token generation failed");
return;
}
$token = $tokenResponse['data']['result'][0]['access_token'];
// Map claim type: Reimbursement or Cashless
// Map claim_type to benefit type (IPD / OPD)
$claimTypeValue = $this->claim_type_array[1][$data['claim_type'] ?? null] ?? null;
$benefitTypeMap = [
'Main Hospitalization' => 'IPD',
'Pre / Post' => 'IPD',
'ReOpen' => 'IPD',
'OPD' => 'OPD',
];
$mappedBenefitType = $benefitTypeMap[$claimTypeValue] ?? 'IPD';
// Build Health India Claim Submission Request (API Section 5)
$body = [
"policY_NUMBER" => $data['policyNumber'],
"employeE_CODE" => $data['employeeCode'],
"membeR_ID" => $data['memberId'],
"claiM_TYPE" => 'Reimbursement',
"benefiT_TYPE" => $mappedBenefitType,
"claimeD_AMOUNT" => (string) $data['claimedAmount'],
"datE_OF_ADMISSION" => date('Y-m-d', strtotime($data['admissionDate'])),
"ailmenT_DESCRIPTION" => $data['ailmentDescription'] ?? 'NA',
"hospitaL_CODE" => $data['hospitalCode'] ?? '',
"hospitaL_NAME" => $data['hospitalName'] ?? '',
"hospitaL_ADDRESS" => $data['hospitalAddress'] ?? '',
"hospitaL_NUMBER" => $data['hospitalNumber'] ?? '',
"pdF_BYTES" => [$fileContent]
];
// $body = [
// 'policY_NUMBER' => '141600_POLICY_AWAITED',
// 'employeE_CODE' => 'DECP000',
// 'membeR_ID' => '10662420SE',
// 'claiM_TYPE' => 'Reimbursement',
// 'benefiT_TYPE' => 'IPD',
// 'claimeD_AMOUNT' => '102',
// 'datE_OF_ADMISSION' => '2026-01-19',
// 'ailmenT_DESCRIPTION' => 'Fever',
// 'hospitaL_CODE' => '100900',
// 'hospitaL_NAME' => 'Test',
// 'hospitaL_ADDRESS' => 'YEst',
// 'hospitaL_NUMBER' => '2233445566',
// "pdF_BYTES" => [$fileContent]
// ];
$url = getenv('HEALTH_INDIA_BASE_URL') . "/Intimation/GetClaimIntimation";
$headers = [
"Authorization: Bearer " . $token,
"Content-Type: application/json"
];
tpa_claim_push_log($claimId, 'HEALTH_INDIA - Claim Push | claimId: ' . $claimId . ' | URL: ' . $url);
$response = call_third_party_api($url, 'POST', $headers, $body);
// dd($response);
if ($response['status'] != true) {
tpa_claim_push_log($claimId, 'HEALTH_INDIA - Claim Push FAILED | claimId: ' . $claimId . ' | response: ' . 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 | API call failed'];
}
if ($response['status'] === true && !empty($response['data']['result'][0]['ccn'])) {
$ccn = $response['data']['result'][0]['ccn'];
$ccnExt = $response['data']['result'][0]['ccN_EXT'] ?? '0';
$this->db->table('ticket_master')
->where('id', $claimId)
->update([
// 'claim_number' => $ccn,
// 'tpa_claim_id' => $ccn,
'tpa_claim_push_reference_no' => $ccn . '-' . $ccnExt,
'updated_at' => date('Y-m-d H:i:s')
]);
// Update claim files table that file is sent to tpa for this claim
if(!empty($file_id)){
$this->db->table('claim_files')
->where('id', $file_id)
->update([ 'is_file_sent_to_tpa' => 1 ]);
tpa_claim_push_log($claimId, 'HEALTH_INDIA - Claim Push | Updating claim_files table for file_id: '.$file_id);
}else{
tpa_claim_push_log($claimId, 'HEALTH_INDIA - Claim Push | No file_id found to update claim_files table.');
}
tpa_claim_push_log($claimId, 'HEALTH_INDIA - Claim Push SUCCESS | claimId: ' . $claimId . ' | CCN: ' . $ccn . ' | CCN_EXT: ' . $ccnExt);
return ['status' => true, 'message' => 'Claim Push SUCCESS', 'response' => $response];
} else {
tpa_claim_push_log($claimId, 'HEALTH_INDIA - Claim Push API SUCCESS BUT CCN EMPTY | claimId: ' . $claimId . ' | response: ' . json_encode($response));
return ['status' => false, 'message' => 'Claim Push API SUCCESS BUT CCN EMPTY'];
}
return ['status' => false, 'message' => 'Claim Push API SUCCESS BUT CCN EMPTY'];
}
public function ClaimDetail($claimId = null)
{
helper('api');
log_message('error', 'HEALTH_INDIA - Claim Status | Started for claimId: ' . $claimId);
$ticket = $this->db->table('ticket_master tm')
->select("tm.id, tm.tpa_claim_push_reference_no, cp.policy_no, cp.policy_start_date, cp.policy_end_date, tm.emp_code")
->join('client_policy cp', 'tm.client_policy_id=cp.id')
->where('tm.id', $claimId)
->get()->getRowArray();
if (!$ticket) {
log_message('error', 'HEALTH_INDIA - Claim Status FAILED | claimId: ' . $claimId . ' - Invalid claim');
return ['status' => false, 'message' => 'Invalid claim'];
}
// Generate Health India Token
$tokenResponse = $this->generateAuthToken();
if (empty($tokenResponse['data']['result'][0]['access_token'])) {
log_message('error', 'HEALTH_INDIA - Claim Status FAILED | claimId: ' . $claimId . ' - Token generation failed');
return ['status' => false, 'message' => 'Token generation failed'];
}
$token = $tokenResponse['data']['result'][0]['access_token'];
$url = getenv('HEALTH_INDIA_BASE_URL') . "/Claims/GetClaims";
// Using claim number wise approach (Section 7.3 - option 3)
$reference = $ticket['tpa_claim_push_reference_no'];
$parts = explode('-', $reference);
$ccn = $parts[0] ?? null;
$ccnExt = $parts[1] ?? null;
$body = [
"policY_NUMBER" => $ticket['policy_no'],
"CCN" => $ccn,
"CCN_EXT" => $ccnExt
];
$headers = [
"Authorization: Bearer " . $token,
"Content-Type: application/json"
];
log_message('error', 'HEALTH_INDIA - Claim Status | claimId: ' . $claimId . ' | Request: ' . json_encode($body));
$response = call_third_party_api($url, 'POST', $headers, $body);
// dd($response);
if (empty($response['data']['result'][0])) {
log_message('error', 'HEALTH_INDIA - Claim Status FAILED | claimId: ' . $claimId . ' | Empty response data');
return ['status' => false, 'message' => 'API call failed.', 'data' => $response];
}
// Extract claim status
$claimData = $response['data']['result'][0];
$tpa_claim_no = $claimData['tpA_CLAIM_NO'] ?? '';
$currentStatus = $claimData['claiM_STATUS'] ?? '';
$tpa_claim_type = $claimData['typE_OF_CLAIM'] ?? '';
$tpa_ailments = $claimData['ailment'] ?? '';
$validStatuses = [
"In-Progress" => 5,
"Under Process" => 5,
"Query" => 4,
"Paid" => 11,
"Rejected" => 8,
"Approved" => 8,
"Required Information" => 4,
"Intimated and File NOT received" => 4,
];
$updateArray = [
'tpa_claim_status' => $currentStatus,
'tpa_claim_id' => $tpa_claim_no,
'claim_number' => $tpa_claim_no,
'updated_at' => date('Y-m-d H:i:s'),
];
if (isset($validStatuses[$currentStatus])) {
$updateArray['claim_status_id'] = $validStatuses[$currentStatus];
}
if (!empty($tpa_claim_type)) {
$updateArray['tpa_claim_type'] = $tpa_claim_type;
}
if (!empty($tpa_ailments)) {
$updateArray['tpa_ailments'] = $tpa_ailments;
}
$this->db->table('ticket_master')->where('id',$claimId)->update($updateArray);
log_message('error', "HEALTH_INDIA - Claim Status SUCCESS | Updated ticket ID $claimId with claim status: $currentStatus");
return [
'status' => true,
'message' => 'Claim status updated.',
'updated_status' => $currentStatus,
'api_response' => $response
];
}
public function ClaimStatusUpdate()
{
helper('api');
log_message('error', 'HEALTH_INDIA - Claim Status UPDATE BULK | Started');
$tickets = $this->db->table('ticket_master tm')
->select("tm.id, tm.tpa_claim_id, cp.policy_no")
->join('client_policy cp', 'tm.client_policy_id=cp.id')
->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->healthIndiaTpaId)
->get()->getResultArray();
$count = 0;
foreach ($tickets as $t) {
$this->ClaimDetail($t['id']);
$count++;
}
log_message('error', 'HEALTH_INDIA - Claim Status UPDATE BULK | Completed | Updated: ' . $count);
return $this->response->setJSON(['status' => true, 'updated' => $count]);
}
public function EcardRequest($employeeId = null, $policyNo = null, $memberId = null)
{
helper('api');
log_message('error', "HEALTH_INDIA - Ecard Request | Started | employeeId: {$employeeId} | policyNo: {$policyNo} | memberId: {$memberId}");
// Generate Health India Token
$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;
}
$token = $tokenResponse['data']['result'][0]['access_token'];
// API Section 3.3 - Individual member e-card
$url = getenv('HEALTH_INDIA_BASE_URL') . "/Member/GetMemberEcard";
$body = [
"policY_NUMBER" => $policyNo ,//'141600_POLICY_AWAITED',
"employeE_CODE" => $employeeId,//'DECP000',
"membeR_ID" => $memberId//'19662410E',
];
$headers = [
"Authorization: Bearer " . $token,
"Content-Type: application/json"
];
log_message('error', 'HEALTH_INDIA - Ecard Request | Request: ' . json_encode($body));
$response = call_third_party_api($url, 'POST', $headers, $body);
log_message('error', 'HEALTH_INDIA - Ecard Request | Response: ' . json_encode($response));
if (($response['status'] ?? false) !== true) {
log_message('error', 'HEALTH_INDIA - Ecard Request | response: ' . json_encode($response));
return null;
}
if (empty($response['data']['result'][0])) {
log_message('error', 'HEALTH_INDIA - Ecard Request | Empty data | response: ' . json_encode($response));
return null;
}
$apiData = $response['data']['result'][0];
if (($apiData['message'] ?? '') === 'SUCCESS') {
$ecardUrl = $apiData['membeR_ECARD'] ?? '';
if (!empty($ecardUrl)) {
log_message('error', "HEALTH_INDIA - Ecard Request | employeeId: {$employeeId} | policyNo: {$policyNo} | memberId: {$memberId} | ecardUrl: {$ecardUrl}");
return $ecardUrl;
}
}
log_message('error', 'HEALTH_INDIA - Ecard Request | response: ' . json_encode($response));
return null;
}
public function HealthIndiaGetBenefDetails($requestData = null)
{
$function_calling_type = $requestData['return_type'] ?? 'job';
try {
helper('api');
$policyNo = $requestData['policy_no'] ?? null; //'141600_POLICY_AWAITED';
$client_policy_id = $requestData['client_policy_id'] ?? null; // 6473;
if (empty($policyNo)) {
log_message('error', 'HEALTH_INDIA - TPA ID Pull | policy_no missing in request');
if ($function_calling_type == "job") {
return ['status' => false, 'message' => 'policy_no required'];
} else {
return $this->respond(['status' => false, 'message' => 'policy_no required']);
}
}
if (empty($client_policy_id)) {
log_message('error', 'HEALTH_INDIA - TPA ID Pull | client_policy_id missing in request');
if ($function_calling_type == "job") {
return ['status' => false, 'message' => 'client_policy_id required'];
} else {
return $this->respond(['status' => false, 'message' => 'client_policy_id required']);
}
}
log_message('error', "HEALTH_INDIA - TPA ID Pull | called for policy_no: {$policyNo}, client_policy_id: {$client_policy_id}");
// Fetch file download dates
$batchFiles = $this->db->table('batch_files f')
->select("f.created_at")
->where('f.client_policy_id', $client_policy_id)
->where('f.insurer_or_tpa', 'tpa')
->where('f.actions', 'export')
->get()
->getResultArray();
if (empty($batchFiles)) {
log_message('error', 'HEALTH_INDIA - TPA ID Pull FAILED | batchFiles is empty for this tpa id pull request');
$file_model = new BatchFileModel();
$bfData = [
'error_data' => json_encode(['error_data' => 'No trace found for TPA member download (export).']),
'status' => 'failed-7',
];
$file_model->where('id', $requestData['file_id'])->set($bfData)->update();
if ($function_calling_type == "job") {
return ['status' => false, 'message' => 'batchFiles not found'];
} else {
return $this->respond(['status' => false, 'message' => 'batchFiles not found']);
}
}
// Generate Health India Token
$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") {
return ['status' => false, 'message' => 'Token generation failed'];
} else {
return $this->respond(['status' => false, 'message' => 'Token generation failed']);
}
}
$token = $tokenResponse['data']['result'][0]['access_token'];
// API Section 2.3 - Bulk Enrolment data Fetch
$url = getenv('HEALTH_INDIA_BASE_URL') . "/Enrollment/GetEnrollmentData";
$headers = [
"Authorization: Bearer " . $token,
"Content-Type: application/json"
];
$body = [
"policY_NUMBER" => $policyNo
];
log_message('error', "HEALTH_INDIA - TPA ID Pull | API params: " . json_encode(['url' => $url, 'method' => 'POST', 'body' => $body]));
$response = call_third_party_api($url, 'POST', $headers, $body);
// dd($response);
log_message('error', "HEALTH_INDIA - TPA ID Pull | API Response Received ");
if (($response['status'] ?? false) !== true) {
log_message('error', 'HEALTH_INDIA - TPA ID Pull API FAILED | response: ' . json_encode($response));
// update file table status after the tpa id failed to update
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', "Files table status updated for the file id: {$requestData['file_id']}");
} else {
log_message('error', "Failed to update file table status.");
}
if ($function_calling_type == "job") {
return ['status' => false, 'message' => 'API call failed', 'data' => $response];
} else {
return $this->respond(['status' => false, 'message' => 'API call failed', 'data' => $response]);
}
}
if (
!isset($response['data']['result']) ||
!is_array($response['data']['result']) ||
count($response['data']['result']) === 0
) {
log_message('error', 'HEALTH_INDIA - TPA ID Pull API FAILED | Empty member data for this pull request');
// update file table status after the tpa id failed to update
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', "Files table status updated for the file id: {$requestData['file_id']}");
} else {
log_message('error', "Failed to update file table status.");
}
if ($function_calling_type == "job") {
return ['status' => false, 'message' => 'API call failed', 'data' => 'Empty member data for this pull request'];
} else {
return $this->respond(['status' => false, 'message' => 'API call failed', 'data' => 'Empty member data for this pull request']);
}
}
$allMembers = $response['data']['result'];
// Save API data as JSON for analysis
$json = json_encode($allMembers, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
$filePath = WRITEPATH . 'tmp/' . time() . '_' . $requestData['file_id'] . '.json';
file_put_contents($filePath, $json);
log_message('error', "HEALTH_INDIA - TPA ID Pull | Saved JSON to: {$filePath}");
// Call a job for dump JSON data to DB
$job_details = new Jobs();
$r = Jobs::addJob([
'job_name' => 'saveHealthIndiaAPIData',
'payload' => [
'file_id' => $requestData['file_id'],
'json_file_path' => $filePath
]
]);
log_message('error', "HEALTH_INDIA - TPA ID Pull | Job added for saving API data");
// ================= MATCHING LOGIC =================
$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();
// echo (string) $employeePolicyModel->db->getLastQuery();
// dd($employeePolicyData);
$updated = 0;
$batch_file_success = 'success';
$employee_policy_ids = [];
foreach ($employeePolicyData as $policy) {
$hasMatchForThisPolicy = false;
foreach ($allMembers as $m) {
// Match based on: employee name, employee code, and relation
if($m['relation'] == 'Employee') { $relation = 'self'; }
else if($m['relation'] == 'WIFE') { $relation = 'spouse'; }
else { $relation = $m['relation']; }
if (
strtolower(trim($policy['name'])) === strtolower(trim($m['insured_Name'] ?? '')) &&
($policy['emp_code'] ?? '') == ($m['employeeCode'] ?? '') &&
strtolower($policy['relationship']) === strtolower($relation ?? '')
) {
$hasMatchForThisPolicy = true;
$sql = "UPDATE employee_polices SET tpa_id = ? WHERE id = ?";
$this->db->query($sql, [$m['memberId'], $policy['emp_policy_id']]);
// For e-card send
if (strtolower(trim($policy['relationship'])) == 'self') {
$employee_policy_ids[] = $policy['emp_policy_id'];
}
if ($this->db->affectedRows() > 0) {
$updated++;
log_message('error', "HEALTH_INDIA - TPA ID Pull | Updated tpa_id={$m['memberId']} for emp_policy_id={$policy['emp_policy_id']} policy={$policyNo}");
} else {
log_message('error', "HEALTH_INDIA - TPA ID Pull | No update (already set or not matched) for emp_policy_id={$policy['emp_policy_id']} policy={$policyNo}");
}
}
}
// Handle NO MATCH for this policy
if (!$hasMatchForThisPolicy) {
$nhanceSideData = [
'name' => $policy['name'] ?? null,
'emp_code' => $policy['emp_code'] ?? null,
'relationship' => $policy['relationship'] ?? null,
'gender' => $policy['gender'] ?? null,
'dob' => $policy['dob'] ?? null,
];
$batch_file_success = 'partially success';
log_message('error', "HEALTH_INDIA - TPA ID Pull | No match for Nhance = " . json_encode($nhanceSideData));
}
}
// Send e-card
if (!empty($employee_policy_ids)) {
log_message('error', "HEALTH_INDIA - TPA ID Pull | sendMailForDownloadingECard JOB PUSHED.");
Jobs::addJob([
'job_name' => 'sendMailForDownloadingECard',
'payload' => [
'ids' => $employee_policy_ids,
'client_policy_id' => $client_policy_id
]
]);
}
// Update file table status after the tpa id successfully updated
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', "Files table status updated for the file id: {$requestData['file_id']} with status: {$batch_file_success}");
} else {
log_message('error', "Failed to update file table status.");
}
$totalCount = count($allMembers);
log_message('error', "HEALTH_INDIA - TPA ID Pull SUCCESS | completed. Total fetched={$totalCount}, updated={$updated}");
if ($function_calling_type == "job") {
return [
'status' => true,
'message' => 'Updated successfully',
'total_fetched' => $totalCount,
'total_updated' => $updated
];
} else {
return $this->respond([
'status' => true,
'message' => 'Updated successfully',
'total_fetched' => $totalCount,
'total_updated' => $updated
]);
}
} catch (\Throwable $th) {
// Update file table status after the tpa id failed to update
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', "Files table status updated for the file id: {$requestData['file_id']}");
} else {
log_message('error', "Failed to update file table status.");
}
$errorData = [
'message' => $th->getMessage(),
'file' => $th->getFile(),
'line' => $th->getLine(),
'code' => $th->getCode(),
'trace' => $th->getTraceAsString(),
'trace_array' => $th->getTrace(),
'function' => $th->getTrace()[0]['function'] ?? null,
'class' => $th->getTrace()[0]['class'] ?? null,
];
log_message('error', 'Exception thrown while calling HealthIndiaGetBenefDetails API: ' . json_encode($errorData));
if ($function_calling_type == "job") {
return ['status' => false, 'message' => 'API call failed', 'data' => $errorData];
} else {
return $this->respond(['status' => false, 'message' => 'API call failed', 'data' => $errorData]);
}
}
}
public function syncHealthIndiaClaimsToNhanceOld()
{
helper('api');
log_message('error', 'HEALTH_INDIA - Sync TPA Claims | Started');
// Generate Health India Token
$tokenResponse = $this->generateAuthToken();
if (empty($tokenResponse['data']['result'][0]['access_token'])) {
log_message('error', 'HEALTH_INDIA - Sync TPA Claims FAILED | Token generation failed');
return $this->response->setJSON(['status' => false, 'message' => 'Token generation failed']);
}
$token = $tokenResponse['data']['result'][0]['access_token'];
$url = getenv('HEALTH_INDIA_BASE_URL') . "/ClaimsMIS/GetClaimsMIS";
$headers = [
"Authorization: Bearer " . $token,
"Content-Type: application/json"
];
$policies = $this->db->table('client_policy')
->where('tpa_id', $this->healthIndiaTpaId)
->get()->getResultArray();
$finalResult = [];
foreach ($policies as $policy) {
$body = [
"policY_NUMBER" => $policy['policy_no']
];
log_message('error', 'HEALTH_INDIA - Sync TPA Claims | Fetching for policy: ' . $policy['policy_no']);
$response = call_third_party_api($url, 'POST', $headers, $body);
if (!empty($response['data']['result'])) {
$finalResult = array_merge($finalResult, $response['data']['result']);
log_message('error', 'HEALTH_INDIA - Sync TPA Claims | Fetched ' . count($response['data']['result']) . ' claims for policy: ' . $policy['policy_no']);
}
}
log_message('error', 'HEALTH_INDIA - Sync TPA Claims | Total claims fetched: ' . count($finalResult));
// Insert / update ticket_master
$insertedCount = 0;
foreach ($finalResult as $row) {
$status = $row['Claim_Status'] ?? 'Under Process';
$map = [
"Under Process" => 5,
"Pending for Bill Entry" => 5,
"Paid" => 11,
"Rejected" => 8,
"Approved" => 8,
"Outstanding" => 5,
];
$claimStatus = $map[$status] ?? 1;
// Check if claim already exists
$existing = $this->db->table('ticket_master')
->where('tpa_claim_id', $row['CLAIM_NUMBER'])
->get()->getRowArray();
if (!$existing) {
$this->db->table('ticket_master')->insert([
'policy_no' => $row['Policy_No'] ?? '',
'claim_number' => $row['CLAIM_NUMBER'] ?? '',
'tpa_claim_id' => $row['CLAIM_NUMBER'] ?? '',
'emp_code' => $row['Employee_Code'] ?? '',
'insured_name' => $row['PATIENT_NAME'] ?? '',
'claim_amount' => $row['INTIMATED_AMOUNT'] ?? 0,
'hospital_name' => $row['HOSPITAL_NAME'] ?? '',
'doa' => !empty($row['DATEOF_ADMISSION']) ? date('Y-m-d', strtotime($row['DATEOF_ADMISSION'])) : null,
'dod' => !empty($row['DATEOF_DISCHARGE']) ? date('Y-m-d', strtotime($row['DATEOF_DISCHARGE'])) : null,
'claim_status_id' => $claimStatus,
'tpa_id' => $this->healthIndiaTpaId,
'claim_created_by'=> 'TPA',
'created_at' => date('Y-m-d H:i:s')
]);
$insertedCount++;
log_message('error', 'HEALTH_INDIA - Sync TPA Claims | Inserted claim: ' . ($row['CLAIM_NUMBER'] ?? 'N/A'));
} else {
log_message('error', 'HEALTH_INDIA - Sync TPA Claims | Skipped existing claim: ' . ($row['CLAIM_NUMBER'] ?? 'N/A'));
}
}
log_message('error', 'HEALTH_INDIA - Sync TPA Claims | Completed | Total: ' . count($finalResult) . ' | Inserted: ' . $insertedCount);
return $this->response->setJSON([
'status' => true,
'total' => count($finalResult),
'inserted' => $insertedCount
]);
}
public function syncHealthIndiaClaimsToNhance()
{
helper('api');
log_message('error', 'HEALTH_INDIA - Sync TPA Claims | Started');
// Generate Health India Token
$tokenResponse = $this->generateAuthToken();
if (empty($tokenResponse['data']['result'][0]['access_token'])) {
log_message('error', 'HEALTH_INDIA - Sync TPA Claims FAILED | Token generation failed');
return $this->response->setJSON(['status' => false, 'message' => 'Token generation failed']);
}
$token = $tokenResponse['data']['result'][0]['access_token'];
$url = getenv('HEALTH_INDIA_BASE_URL') . "/ClaimsMIS/GetClaimsMIS";
$headers = [
"Authorization: Bearer " . $token,
"Content-Type: application/json"
];
$policies = $this->db->table('client_policy')
->where('tpa_id', $this->healthIndiaTpaId)
->get()->getResultArray();
$finalResult = [];
foreach ($policies as $policy) {
$body = [
"policY_NUMBER" => $policy['policy_no']
];
log_message('error', 'HEALTH_INDIA - Sync TPA Claims | Fetching for policy: ' . $policy['policy_no']);
$response = call_third_party_api($url, 'POST', $headers, $body);
if (!empty($response['data']['result'])) {
$finalResult = array_merge($finalResult, $response['data']['result']);
log_message('error', 'HEALTH_INDIA - Sync TPA Claims | Fetched ' . count($response['data']['result']) . ' claims for policy: ' . $policy['policy_no']);
}
}
log_message('error', 'HEALTH_INDIA - Sync TPA Claims | Total claims fetched: ' . count($finalResult));
$insertedCount = 0;
foreach ($finalResult as $row) {
$status = $row['Claim_Status'] ?? 'Under Process';
$map = [
"Under Process" => 5,
"Pending for Bill Entry" => 5,
"Paid" => 11,
"Rejected" => 8,
"Approved" => 8,
"Outstanding" => 5,
];
$claimStatus = $map[$status] ?? 1;
// Check if claim already exists
$existing = $this->db->table('ticket_master')
->where('tpa_claim_id', $row['CLAIM_NUMBER'])
->get()->getRowArray();
if ($existing) {
log_message('error', 'HEALTH_INDIA - Sync TPA Claims | Skipped existing claim: ' . ($row['CLAIM_NUMBER'] ?? 'N/A'));
continue;
}
// Derive relationship (default to self)
$relationship = 'self';
$rawRelation = $row['RELATION_NAME'] ?? null;
if (!empty($rawRelation)) {
if ($rawRelation === 'Employee') {
$relationship = 'self';
} elseif (strtoupper($rawRelation) === 'WIFE') {
$relationship = 'spouse';
} else {
$relationship = strtolower($rawRelation);
}
}
// Fetch client policy details
$clientpolicy = $this->db->table('client_policy cp')
->select("
cp.id as client_policy_id,
cp.client_id,
cp.insurer_id,
cp.tpa_id,
client_rm.id as acm_id
")
->join('client_rm', 'client_rm.client_id = cp.client_id AND client_rm.level = 3', 'left')
->where('cp.policy_no', $row['Policy_No'] ?? null)
->orderBy('client_rm.id', 'DESC')
->get()
->getRowArray();
if (!$clientpolicy) {
log_message(
'error',
'HEALTH_INDIA - Sync TPA Claims | Client policy not found for policy_no: ' . ($row['Policy_No'] ?? 'N/A')
);
continue;
}
// Fetch employee / insured details
$employee = $this->db->table('employees e')
->select("
e.id as emp_id,
e.emp_code,
e.name as emp_name,
e2.id as insured_emp_id,
e2.name as insured_emp_name,
ep.tpa_id as tpa_no,
e.mobile as emp_mobile,
e.email_corporate as emp_mail
")
->join(
'employees e2',
"e2.emp_code = e.emp_code AND e2.relationship = " . $this->db->escape($relationship),
'left'
)
->join('employee_polices ep', "ep.employee_id = e2.id ", 'left')
->where('e.emp_code', $row['Employee_Code'] ?? null)
->where('e.client_id', $clientpolicy['client_id'] ?? null)
->where('e.relationship', 'self')
->where('e.is_active', 1)
->where('e2.is_active', 1)
->where('ep.is_active', 1)
->get()
->getRowArray();
if (!$employee) {
log_message(
'error',
'HEALTH_INDIA - Sync TPA Claims | Employee data not found for emp_code: ' . ($row['Employee_Code'] ?? 'N/A') .
' | policy_no: ' . ($row['Policy_No'] ?? 'N/A') .
' | relationship: ' . $relationship
);
continue;
}
$claimData = [
// Core
'ticket_type_id' => 1,
'claim_status_id' => $claimStatus,
'policy_no' => $row['Policy_No'] ?? null,
'claim_number' => $row['CLAIM_NUMBER'] ?? null,
'tpa_claim_id' => $row['CLAIM_NUMBER'] ?? null,
// Local primary/foreign keys
'tpa_id' => $clientpolicy['tpa_id'] ?? $this->healthIndiaTpaId,
'insurer_id' => $clientpolicy['insurer_id'] ?? null,
'client_policy_id' => $clientpolicy['client_policy_id'] ?? null,
'client_id' => $clientpolicy['client_id'] ?? null,
'acm_id' => $clientpolicy['acm_id'] ?? null,
// Employee / Insured
'emp_id' => $employee['emp_id'] ?? null,
'insured_emp_id' => $employee['insured_emp_id'] ?? null,
'tpa_no' => $employee['tpa_no'] ?? null,
'emp_code' => $row['Employee_Code'] ?? null,
'emp_name' => $employee['emp_name'] ?? null,
'insured_name' => $employee['insured_emp_name'] ?? ($row['PATIENT_NAME'] ?? null),
'relationship' => $relationship,
'emp_mobile' => $employee['emp_mobile'] ?? null,
'emp_mail' => $employee['emp_mail'] ?? null,
// Claim info
'claim_type' => 1,
'mode_of_intimation' => 5,
'claim_amount' => $row['INTIMATED_AMOUNT'] ?? 0,
// Dates
'doa' => !empty($row['DATEOF_ADMISSION']) ? date('Y-m-d', strtotime($row['DATEOF_ADMISSION'])) : null,
'dod' => !empty($row['DATEOF_DISCHARGE']) ? date('Y-m-d', strtotime($row['DATEOF_DISCHARGE'])) : null,
// Hospital
'hospital_name' => $row['HOSPITAL_NAME'] ?? null,
'hospital_address' => $row['Hospital_address'] ?? null,
'hospital_pincode' => $row['HOSPITAL_Pincode'] ?? null,
'hospital_state' => $row['HOSPITAL_STATE'] ?? null,
'hospital_city' => $row['HOSPITAL_CITY'] ?? null,
// TPA extras
'tpa_claim_status' => $status,
'claim_created_by' => 'TPA',
'created_at' => date('Y-m-d H:i:s'),
'tpa_claim_push_reference_no' => $row['ccn'].'-'.$row['ccN_EXT'] ?? null,
];
$this->db->table('ticket_master')->insert($claimData);
$insertedCount++;
log_message(
'error',
'HEALTH_INDIA - Sync TPA Claims | Inserted claim: ' . ($row['CLAIM_NUMBER'] ?? 'N/A')
);
}
log_message('error', 'HEALTH_INDIA - Sync TPA Claims | Completed | Total: ' . count($finalResult) . ' | Inserted: ' . $insertedCount);
return $this->response->setJSON([
'status' => true,
'total' => count($finalResult),
'inserted' => $insertedCount
]);
}
public function saveHealthIndiaAPIData($array)
{
$file_id = $array['file_id'];
$json = file_get_contents($array['json_file_path']);
$records = json_decode($json, true);
// log_message('error','HEALTH_INDIA - saveHealthIndiaAPIData' . json_encode($array));//die();
$file_model = new BatchFileModel();
$file_info = $file_model->where('id', $file_id)->find();
$tpaApiDataModel = new TpaApiDataModel();
//deactivate old data
$tpaApiDataModel->set('is_active', 0)->where('file_id', $file_id)->update();
//covert tpa data to our model data
$mappedRows = [];
foreach ($records as $row) {
$mappedRows[] = [
'file_id' => $file_id, // ← pass from controller
'emp_code' => trim($row['employeeCode'] ?? ''),
'name' => trim($row['insured_Name'] ?? ''),
'dob' => !empty($row['dateOfBirth'] ?? null) ? date('Y-m-d', strtotime(str_replace('/', '-', $row['dateOfBirth']))) : null,
'relation' => map_relationship(trim($row['relation'] ?? null)),
'gender' => strtoupper($row['gender'] ?? null),
'self' => map_relationship(trim($row['relation'] ?? null)) === 'self' ? 1 : 0,
'tpa_id' => trim($row['memberId'] ?? null),
'age' => is_numeric($row['age'] ?? null) ? (int) $row['age'] : null,
'is_active' => 1,
'created_by' => $file_info[0]['created_by'] ?? null,
'action_flag_status' => $row['insuredStatus'] == 'Active' ? 'A' : 'D',
'doj' => change_date_format($row['doj'],),
'si' => $row['baseSumInsured'],
'endorsement_no' => $row['endorsementNumber']
];
}
// log_message('error','HEALTH_INDIA - COUNT' . count($mappedRows));
// print_rr($mappedRows);//die();
$result = $tpaApiDataModel->insertBatchWithChunkLog($mappedRows,500,('FILE_ID_'.$file_id));
// unlink($file_array['json_file_path']); // delete temp json file
}
}