nhance/app/Controllers/MediAssistApiController.php

1421 lines
56 KiB
PHP
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace App\Controllers;
use App\Controllers\BaseController;
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 MediAssistApiController extends BaseController
{
use ResponseTrait;
protected $db;
protected $mediAssistTpaId;
public function __construct()
{
$this->db = \Config\Database::connect();
$this->mediAssistTpaId = getenv('MEDI_ASSIST_PRIMARY_KEY_CONSTANT');
}
public function SubmitClaim ($claimId = null)
{
helper('api');
// $url = ''. getenv('MEDI_ASSIST_API_BASE_URL').'/SubmitClaim';
$url = getenv('MEDI_ASSIST_API_BASE_URL_CLAIMSUBMIT');
$method = 'POST';
$headers = [
'Content-Type: application/json',
'Username:'. getenv('MEDI_ASSIST_API_USERNAME').'',
'Password:'. getenv('MEDI_ASSIST_API_PASSWORD').'',
];
//Prepare body data
// Fetch the data from DB
$data = $this->db->table('ticket_master tm')
->select('
tm.id,
tm.emp_mobile as mobileNo,
tm.emp_mail as emailId,
tm.doa as claimDateOfAdmission,
tm.dod as claimDateOfDischarge,
tm.hospital_name as hospName,
tm.claim_amount as claimAmount,
cp.policy_no as policyNo,
e.id as empId,
tm.tpa_no as memberId,
tn.note as disease,
tn.note as reasonForHospitalization,
cf.url as fileName,
cf.url as filePath
')
->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 = 2 and cf.mime_type = 'application/pdf'", 'left')
->where('tm.id', $claimId)
->get()
->getRowArray(); // single record
// Map DB result to request body
if ($data) {
$filePath = $data['filePath'] ?? '';
$filename = basename($filePath);
$fileDir = WRITEPATH . 'uploads/claim_files/'.$filename;
if ($fileDir) {
$downloadUrl = base_url('fileDownload?file_path=').$fileDir;
} else {
$downloadUrl = '';
}
$body = [
"policyNo" => $data['policyNo'] ?? "",
"memberId" => $data['memberId'] ?? "",
"mobileNo" => $data['mobileNo'] ?? "",
"emailId" => $data['emailId'] ?? "",
"claimDateOfAdmission" => $data['claimDateOfAdmission'] ?? "",
"claimDateOfDischarge" => $data['claimDateOfDischarge'] ?? "",
"hospName" => $data['hospName'] ?? "",
"hospAddress" => $data['hospName'] ?? "", // If hospAddress not available, reuse hospName
"reasonForHospitalization" => $data['reasonForHospitalization'] ?? "",
"disease" => $data['disease'] ?? "",
"claimAmount" => (float)($data['claimAmount'] ?? 0),
"claimType" => "HOSPITALIZATION", // static value
"claimSubmissionAttachments" => [
"fileName" => $data['fileName'] ?? "",
"filePath" => $downloadUrl ?? ""
]
];
} else {
$body = [];
}
// dd($body);
// $body = [
// "policyNo" => "570000/48/2025/286",
// "memberId" => 4078919887,
// "mobileNo" => "95000XXXXX",
// "emailId" => "test@Medi.com",
// "claimDateOfAdmission" => "2023-12-14",
// "claimDateOfDischarge" => "2023-12-16",
// "hospName" => "TestHosp",
// "hospAddress" => "Testhosp",
// "reasonForHospitalization" => "test",
// "disease" => "testkediney",
// "claimAmount" => 10,
// "claimType" => "HOSPITALIZATION",
// "claimSubmissionAttachments" => [
// "fileName" => "Test.pdf",
// "filePath" => "https://apiintegration.mediassist.in/IntegrationEcard/DownloadEcard/4078613742/Senthil Kumar P/556/5386"
// ]
// ];
log_message('error', 'TPA CLAIM PUSH | claimId: '.$claimId.' | payload: '.json_encode($body));
$response = call_third_party_api($url, $method, $headers, $body);
if($response['status'] != true){
log_message('error', 'TPA 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;
}
// return $this->response->setJSON($response);
$claimRef = $response['data']['claimReferenceNo'] ?? null;
if(!empty($claimRef)){
log_message('error', 'TPA CLAIM PUSH SUCCESS | claimId: '.$claimId.' | claimReferenceNo: '.$claimRef);
$this->db->table('ticket_master')
->where('id',$claimId)
->update([ 'tpa_claim_push_reference_no' => $claimRef ]);
return;
} else {
log_message('error', 'TPA CLAIM PUSH API SUCCESS BUT claimReferenceNo EMPTY | claimId: '.$claimId.' | response: '.json_encode($response));
return;
}
}
public function EcardRequest ($employeeId = null, $policyNo = null)
{
helper('api');
// $url = ''. getenv('MEDI_ASSIST_API_BASE_URL').'/EcardUrl';
$url = getenv('MEDI_ASSIST_API_BASE_URL_ECARDREQUEST');
$method = 'POST';
$headers = [
'Content-Type: application/json',
'Username:'. getenv('MEDI_ASSIST_API_USERNAME').'',
'Password:'. getenv('MEDI_ASSIST_API_PASSWORD').'',
];
$body = [
"employeeId" => $employeeId,
"policyNo" => $policyNo
];
// $body = [
// "employeeId" => "CITPL120006",
// "policyNo" => "97000063250400000031"
// ];
$response = call_third_party_api($url, $method, $headers, $body);
if($response['status'] != true){
log_message('error', 'Ecard Request FAILED | employeeId: '.$employeeId.' | policyNo: '.$policyNo.' | response: '.json_encode($response));
return null;
}
$ecardUrl = $response['data']['ecardUrl'] ?? null;
if(!empty($ecardUrl)){
log_message('error', 'Ecard Request PUSH SUCCESS | employeeId: '.$employeeId.' | policyNo: '.$policyNo.' | ecardUrl: '.$ecardUrl);
return $ecardUrl;
} else {
log_message('error', 'Ecard Request SUCCESS BUT ecardUrl EMPTY | employeeId: '.$employeeId.' | policyNo: '.$policyNo.' | response: '.json_encode($response));
return null;
}
}
public function MediAssistGetBenefDetails($requestData)
{
// helper('api');
// helper('TPADataCompareHelper');
// $report = EmployeeCompareHelper::compareDbVsMediassist(
// $dbRows,
// $mediassistAPIdata
// );
// print_rr($report);
// die();
// print_r($requestData);die();
//START OF THE PROGRAM
$function_calling_type = $requestData['return_type'] ?? 'job';
try {
// $url = getenv('MEDI_ASSIST_API_BASE_URL') . '/GetBenefDetails';
$url = getenv('MEDI_ASSIST_API_BASE_URL_FETCHTPA');
$method = 'POST';
$headers = [
'Content-Type: application/json',
'Username:' . getenv('MEDI_ASSIST_API_USERNAME'),
'Password:' . getenv('MEDI_ASSIST_API_PASSWORD'),
];
$policyNo = $requestData['policy_no'] ?? null;
$client_policy_id = $requestData['client_policy_id'] ?? null;
if (empty($policyNo)) {
log_message('error', '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', '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', "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', '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'];
}else{
return $this->respond(['status' => false, 'message' => 'employeePolicyData not found']);
}
}
$allBenef = [];
$startIndex = 0;
$range = 100;
$totalCount = 0;
do {
$body = [
"policyNo" => $policyNo,
"startDate" => "",
"endDate" => "",
"isDeActivedata" => false,
"startIndex" => $startIndex,
"range" => $range,
"employeeId" => ""
];
log_message('error', "TPA ID PULL | API Request (startIndex={$startIndex}): " . json_encode($body));
log_message('error', "TPA ID PULL | API parems " . json_encode([$url, $method, $headers, $body]));
$response = call_third_party_api($url, $method, $headers, $body);
if ($response['status'] != true) {
// 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.");
}
log_message('error', 'TPA ID PULL API FAILED | API failed: ' . json_encode($response));
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]);
}
}
$data = $response['data'] ?? [];
if (!isset($data['benefDetails'])) {
log_message('error', "TPA ID PULL FAILED |: 'benefDetails' missing in API response: " . json_encode($data));
break;
}
$count = $data['count'] ?? 0;
$totalCount = $count;
$fetchedCount = count($data['benefDetails']);
log_message('error', "Fetched {$fetchedCount} records (startIndex={$startIndex}) of total {$count}");
$allBenef = array_merge($allBenef, $data['benefDetails']);
$startIndex += $range;
} while ($startIndex < $totalCount);
//save API data as JSON for analysis
$json = json_encode($allBenef, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
// $filename = time() . '.json';
$filePath = WRITEPATH . 'tmp/'.time().'_'.$requestData['file_id'].'.json';
file_put_contents($filePath, $json);
//call a job for dump JSON data to DB
$job_details = new Jobs();
$r = Jobs::addJob(['job_name' => 'saveMediAssitAPIData', 'payload' => [
'file_id' => $requestData['file_id'],
'json_file_path' => $filePath ]]);
// now update DB
$batch_file_success = 'success';
$updated = 0;
$employee_policy_ids = [];
foreach ($employeePolicyData as $policy_data) {
$hasMatchForThisPolicy = false;
foreach ($allBenef as $row) {
if (
strtolower(trim($policy_data['name'] ?? '')) == strtolower(trim($row['benefName'] ?? '')) &&
($policy_data['emp_code'] ?? '') == ($row['priBenefEmpCode'] ?? '') &&
strtolower(trim($policy_data['relationship'] ?? '')) == strtolower(trim(str_replace('-', ' ', $row['relName'] ?? ''))) &&
($policy_data['gender'] ?? '') == ($row['benefSex'] ?? '') &&
($policy_data['dob'] ?? '') == (change_date_format($row['benefDOB'], 'd/m/Y H:i:s') ?? '')
) {
$hasMatchForThisPolicy = true;
// log_message('error', "✅ Match found: emp_code={$row['priBenefEmpCode']} policy={$row['polNo']}");
$sql = "UPDATE employee_polices
SET tpa_id = ?
WHERE id = ?";
$this->db->query($sql, [$row['benefMediAssistID'], $policy_data['emp_policy_id']]);
// for e-card send
if(strtolower(trim($policy_data['relationship'])) == 'self'){
$employee_policy_ids[] = $policy_data['emp_policy_id'];
}
if ($this->db->affectedRows() > 0) {
$updated++;
log_message('error', "✅ Updated tpa_id={$row['benefMediAssistID']} for emp_code={$row['priBenefEmpCode']} policy={$row['polNo']}");
} else {
log_message('error', "⚠️ No update (already set or not matched) for emp_code={$row['priBenefEmpCode']} policy={$row['polNo']}");
}
}
}
// Handle NO MATCH for this policy
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',
"❌ No match for Nhance = " . json_encode($nhanceSideData)
);
}
}
// send e-card
if(!empty($employee_policy_ids)){
log_message('error', "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']}");
} else {
log_message('error', "Failed to update file table status.");
}
log_message('error', "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(), // full array version (optional)
'function' => $th->getTrace()[0]['function'] ?? null,
'class' => $th->getTrace()[0]['class'] ?? null,
];
log_message('error', 'Exception thrown while calling GetBenefDetails 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 ClaimDetail($claimId = null) // 585 this id for test
{
helper('api');
$url = getenv('MEDI_ASSIST_API_BASE_URL_CLAIMSTATUS');
$method = 'POST';
$headers = [
'Content-Type: application/json',
'Username:' . getenv('MEDI_ASSIST_API_USERNAME'),
'Password:' . getenv('MEDI_ASSIST_API_PASSWORD'),
];
// Fetch ticket master details
$ticket = $this->db->table('ticket_master tm')
->select("
tm.id,
tm.tpa_no as memberId,
tm.tpa_claim_push_reference_no as claimRefNo,
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) {
return $this->response->setJSON(['status' => false,'message' => 'Invalid Claim ID' ]);
}
// REQUEST BODY
if($ticket['claimRefNo'] != null)
{
$body = [
"policyNo" => $ticket['policyNo'] ?? "",
"startDate" => "",
"endDate" => "",
"employeeCode" => $ticket['employeeCode'] ?? "",
"memberID" => "",
"claimNo" => "",
"claimRefNo" => $ticket['claimRefNo'] ?? "",
];
}else{
$body = [
"policyNo" => $ticket['policyNo'] ?? "",
"startDate" => "",
"endDate" => "",
"employeeCode" => $ticket['employeeCode'] ?? "",
"memberID" => "",
"claimNo" => "",
"claimRefNo" => "",
];
}
// $body = [
// "policyNo" => "97000063250400000031",
// "startDate" => "01/11/2025",
// "endDate" => "05/11/2025",
// "employeeCode" => "",
// "memberID" => "",
// "claimNo" => "",
// "claimRefNo" => ""
// ];
// CALL API
$response = call_third_party_api($url, $method, $headers, $body);
if ($response['status'] != true || empty($response['data']['claimsData'][0])) {
log_message('error', 'CLAIM STATUS FAILED | for ticket ID: ' . $claimId.' | response: '.json_encode($response));
return $this->response->setJSON([
'status' => false,
'message' => 'API call failed.',
'data' => $response
]);
}
// Extract claim status
$claimData = $response['data']['claimsData'][0];
$currentStatus = $claimData['claim_Current_Status'] ?? '';
$tpa_claim_no = $claimData['tpA_CLAIM_NO'] ?? '';
// VALID STATUS LIST
$validStatuses = [
"Claim Received" => 1,
"In Progress" => 5,
"Processed" => 11,
"Claim Paid" => 11,
"Denied" => 13,
"Cancelled" => 13,
"Information Awaited" => 4,
"Confirmation Awaited" => 4,
"Information Awaited Reminder" => 4,
"Information Awaited Final Reminder" => 4,
"Insurer Concurrence Awaited" => 6,
"Closed" => 12,
"Physical Documents Awaited" => 9,
"Processed - Payment Initiated" => 10,
"Processed - Transaction Failed" => 10,
"Processed - Account Details Updated" => 10,
"Processed - Debit Note Raised With Insurer for Payment"=> 10,
"Processed - Payment Initiated by Insurer" => 10,
"Payment - Refunded to Insurer" => 14,
"Processed - Processing Payment" => 10,
"Processed - Physical Documents Awaited" => 9,
// Extra Mappings (based on your DB list)
"NON ID" => 1,
"ID NOT GENERATED" => 2,
"CDA" => 3,
"REJECTED" => 8,
"APPROVED" => 9,
"PAYMENT INITIATED" => 10,
"SETTLED" => 11,
"RETURNED" => 14,
"UNDER PROCESS - TPA" => 61,
"DENIAL REVIEW AWAITED" => 66,
];
// Maping tpa claim status with local claim Status
if (isset($validStatuses[$currentStatus]))
{
$updateArray = ['claim_status_id' => $validStatuses[$currentStatus] , 'tpa_claim_status' => $currentStatus , 'tpa_claim_id' => $tpa_claim_no, 'claim_number' => $tpa_claim_no, 'updated_at' => date('Y-m-d H:i:s')];
}else{
$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')];
}
// UPDATE ticket_master
$this->db->table('ticket_master')->where('id', $claimId)->update($updateArray);
// LOG UPDATE
log_message('error', "CLAIM STATUS SUCCESS | Updated ticket ID $claimId with claim status: $currentStatus");
return $this->response->setJSON([
'status' => true,
'message' => 'Claim status updated.',
'updated_status' => $currentStatus,
'api_response' => $response
]);
}
public function IRSubmission($claimId = null) // 585 this id for test
{
log_message('error', "IRSubmission 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 claimRefNo,
tm.tpa_claim_id as ClaimID,
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['ClaimID'])) {
log_message('error', "IRSubmission 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();
$Attachments = [];
if (count($fileData)) {
foreach ($fileData as $file) {
if (!empty($file['url'])) {
$filename = basename($file['url']);
$fileDir = WRITEPATH . 'uploads/claim_files/' . $filename;
if (file_exists($fileDir)) {
$downloadUrl = base_url('fileDownload?file_path=') . $fileDir;
} else {
$downloadUrl = "";
log_message('error', "File NOT FOUND on server → {$fileDir}");
}
log_message('error', "IRSubmission Attachment Ready: {$filename} | URL={$downloadUrl}");
$Attachments[] = [
"AttachmentName" => $filename,
"AttachmentPath" => $downloadUrl
];
} else {
log_message('error', "IRSubmission Missing File URL → file_id={$file['id']}");
}
}
}
// 3. API REQUEST BODY
$body = [
"ClaimID" => $ticket['ClaimID'],
"Attachments" => $Attachments
];
log_message('error', "IRSubmission Request Body => " . json_encode($body));
// 4. SEND API CALL
helper('api');
// 'https://apiintegration.mediassist.in/ClaimAPIServiceUAT/Claim/IRSubmission' // dev url
$url = env('MEDI_ASSIST_API_BASE_URL_IRSUBMISSION');
$method = 'POST';
$headers = [
'Content-Type: application/json',
'Username:' . getenv('MEDI_ASSIST_API_USERNAME'),
'Password:' . getenv('MEDI_ASSIST_API_PASSWORD'),
];
$response = call_third_party_api($url, $method, $headers, $body);
log_message('error', "IRSubmission API Response => " . json_encode($response));
// 5. HANDLE RESPONSE
if (!$response['status']) {
log_message(
'error',
"IRSubmission FAILED for ClaimID={$ticket['ClaimID']} → Response=" . json_encode($response)
);
return [
'status' => false,
'message' => 'IR Submission failed',
'data' => $response
];
}
log_message('error', "IRSubmission SUCCESS → ClaimID={$ticket['ClaimID']}");
return [
'status' => true,
'message' => 'IR Submitted successfully',
'data' => $response
];
}
public function saveMediAssitAPIData($array)
{
$file_id = $array['file_id'];
$json = file_get_contents($array['json_file_path']);
$records = json_decode($json, true);
// log_message('error','saveMediAssitAPIData' . json_encode($array));//die();
$file_model = new BatchFileModel();
$file_info = $file_model->where('id', $file_id)->find();
// dd($file_info);
$tpaApiDataModel = new TpaApiDataModel();
// echo $file_id;die();
//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['priBenefEmpCode'] ?? ''),
'name' => trim($row['benefName'] ?? ''),
'dob' => !empty($row['benefDOB'])
? date('Y-m-d', strtotime(str_replace('/', '-', $row['benefDOB'])))
: null,
'relation' => trim($row['relName'] ?? null),
'gender' => strtoupper($row['benefSex'] ?? null),
'self' => strtolower($row['relName'] ?? '') === 'self' ? 1 : 0,
'tpa_id' => trim($row['benefMediAssistID'] ?? null),
'age' => is_numeric($row['benefAge'] ?? null)
? (int) $row['benefAge']
: null,
'is_active' => 1,
'created_by' => $file_info[0]['created_by'] ?? null,
];
}
// log_message('error','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
}
public function ClaimStatusUpdate()
{
helper('api');
$url = getenv('MEDI_ASSIST_API_BASE_URL_CLAIMSTATUS');
$method = 'POST';
$headers = [
'Content-Type: application/json',
'Username:' . getenv('MEDI_ASSIST_API_USERNAME'),
'Password:' . getenv('MEDI_ASSIST_API_PASSWORD'),
];
// Fetch ticket master details
$TicketData = $this->db->table('ticket_master tm')
->select("
tm.id,
tm.tpa_no as memberId,
tm.tpa_claim_push_reference_no as claimRefNo,
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.tpa_claim_push_reference_no IS NOT NULL')
->where('tm.is_active', 1)
->whereNotIn('tm.claim_status_id', [8, 11, 12, 13, 66, 22, 24, 47, 49, 32, 34, 53, 55, 42, 44, 58, 60])
->where('tm.tpa_id', $this->mediAssistTpaId)
->get()
->getResultArray();
// dd($TicketData);
if (!$TicketData) {
log_message('error', "Claims not found to update status");
return $this->response->setJSON(['status' => false,'message' => 'Claims not found' ]);
}
$error_data = [];
$status_updated_count = 0;
foreach ($TicketData as $key => $ticket)
{
$claimId = $ticket['id'];
// REQUEST BODY
if($ticket['claimRefNo'] != null)
{
$body = [
"policyNo" => $ticket['policyNo'] ?? "",
"startDate" => "",
"endDate" => "",
"employeeCode" => $ticket['employeeCode'] ?? "",
"memberID" => "",
"claimNo" => "",
"claimRefNo" => $ticket['claimRefNo'] ?? "",
];
}else{
$body = [
"policyNo" => $ticket['policyNo'] ?? "",
"startDate" => "",
"endDate" => "",
"employeeCode" => $ticket['employeeCode'] ?? "",
"memberID" => "",
"claimNo" => "",
"claimRefNo" => "",
];
}
// CALL API
$response = call_third_party_api($url, $method, $headers, $body);
if ($response['status'] != true || empty($response['data']['claimsData'][0])) {
log_message('error', 'CLAIM STATUS FAILED | for ticket ID: ' . $claimId.' | response: '.json_encode($response));
$error_data[$claimId][['status' => false,'message' => 'API call failed.','data' => $response]];
}
// Extract claim status
$claimData = $response['data']['claimsData'][0];
$currentStatus = $claimData['claim_Current_Status'] ?? '';
$tpa_claim_no = $claimData['tpA_CLAIM_NO'] ?? '';
// VALID STATUS LIST
$validStatuses = [
"Claim Received" => 1,
"In Progress" => 5,
"Processed" => 11,
"Claim Paid" => 11,
"Denied" => 13,
"Cancelled" => 13,
"Information Awaited" => 4,
"Confirmation Awaited" => 4,
"Information Awaited Reminder" => 4,
"Information Awaited Final Reminder" => 4,
"Insurer Concurrence Awaited" => 6,
"Closed" => 12,
"Physical Documents Awaited" => 9,
"Processed - Payment Initiated" => 10,
"Processed - Transaction Failed" => 10,
"Processed - Account Details Updated" => 10,
"Processed - Debit Note Raised With Insurer for Payment"=> 10,
"Processed - Payment Initiated by Insurer" => 10,
"Payment - Refunded to Insurer" => 14,
"Processed - Processing Payment" => 10,
"Processed - Physical Documents Awaited" => 9,
// Extra Mappings (based on your DB list)
"NON ID" => 1,
"ID NOT GENERATED" => 2,
"CDA" => 3,
"REJECTED" => 8,
"APPROVED" => 9,
"PAYMENT INITIATED" => 10,
"SETTLED" => 11,
"RETURNED" => 14,
"UNDER PROCESS - TPA" => 61,
"DENIAL REVIEW AWAITED" => 66,
];
// Maping tpa claim status with local claim Status
if (isset($validStatuses[$currentStatus]))
{
$updateArray = ['claim_status_id' => $validStatuses[$currentStatus] , 'tpa_claim_status' => $currentStatus , 'tpa_claim_id' => $tpa_claim_no , 'claim_number' => $tpa_claim_no , 'updated_at' => date('Y-m-d H:i:s')];
}else{
$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')];
}
// UPDATE ticket_master
$this->db->table('ticket_master')->where('id', $claimId)->update($updateArray);
$status_updated_count ++;
// LOG UPDATE
log_message('error', "CLAIM STATUS SUCCESS | Updated ticket ID $claimId with claim status: $currentStatus");
}
return $this->response->setJSON([
'status' => true,
'message' => 'Claim status updated.',
'updated_status' => $currentStatus,
'api_response' => $response,
'count' => $status_updated_count,
'error_data' => $error_data,
]);
}
public function syncTpaClaimToNhance()
{
helper(['api', 'date']);
$url = getenv('MEDI_ASSIST_API_BASE_URL_CLAIMSTATUS');
$method = 'POST';
$headers = [
'Content-Type: application/json',
'Username:' . getenv('MEDI_ASSIST_API_USERNAME'),
'Password:' . getenv('MEDI_ASSIST_API_PASSWORD'),
];
// REQUEST DATES
$reqStartDate = $this->request->getGet('start_date');
$reqEndDate = $this->request->getGet('end_date');
// If start_date OR end_date is missing → last 7 days
if (empty($reqStartDate) || empty($reqEndDate)) {
$endDateObj = new \DateTime(); // today
$startDateObj = (clone $endDateObj)->modify('-6 days');
} else {
$startDateObj = new \DateTime($reqStartDate);
$endDateObj = new \DateTime($reqEndDate);
}
// Final usable variables
$reqStartDate = $startDateObj->format('Y-m-d');
$reqEndDate = $endDateObj->format('Y-m-d');
// Final usable variables
$reqStartDate = new \DateTime($reqStartDate);
$reqEndDate = new \DateTime($reqEndDate);
// FETCH POLICY DATA
$policies = $this->db->table('client_policy cp')
->select("
cp.policy_no AS policyNo,
cp.policy_start_date AS policyStartDate,
cp.policy_end_date AS policyEndDate
")
->where('cp.is_active', 1)
->where('cp.policy_type_id', 2)
->where('cp.policy_status', 1)
// ->where('cp.policy_no', '97000063250400000031')
->where('cp.tpa_id', $this->mediAssistTpaId)
->get()
->getResultArray();
if (empty($policies)) {
log_message('error', 'No policies found for claim sync');
return $this->response->setJSON([
'status' => false,
'message' => 'Policies not found'
]);
}
$finalResult = [];
$errorData = [];
// LOOP POLICIES
foreach ($policies as $policy) {
$policyStart = new \DateTime($policy['policyStartDate']);
$policyEnd = new \DateTime($policy['policyEndDate']);
// ADJUST DATE RANGE (inside policy period)
$startDate = max($reqStartDate, $policyStart);
$endDate = min($reqEndDate, $policyEnd);
if ($startDate > $endDate) {
continue; // No valid range for this policy
}
// SPLIT INTO 7-DAY CHUNKS
$chunkStart = clone $startDate;
while ($chunkStart <= $endDate) {
$chunkEnd = clone $chunkStart;
$chunkEnd->modify('+6 days');
if ($chunkEnd > $endDate) {
$chunkEnd = clone $endDate;
}
// PREPARE BODY
$body = [
"policyNo" => $policy['policyNo'],
"startDate" => $chunkStart->format('d/m/Y'),
"endDate" => $chunkEnd->format('d/m/Y'),
"employeeCode" => "",
"memberID" => "",
"claimNo" => "",
"claimRefNo" => "",
];
// CALL TPA API
$response = call_third_party_api($url, $method, $headers, $body);
if (empty($response['status']) || empty($response['data']['claimsData'])) {
log_message('error','CLAIM STATUS FAILED | ' .'policyNo: ' . $policy['policyNo'] .' | ' . $chunkStart->format('Y-m-d') .' to ' . $chunkEnd->format('Y-m-d') .' | response: ' . json_encode($response) );
$errorData[] = [
'policy_no' => $policy['policyNo'],
'start' => $chunkStart->format('Y-m-d'),
'end' => $chunkEnd->format('Y-m-d'),
];
} else {
$finalResult = array_merge($finalResult,$response['data']['claimsData']);
}
// Move to next chunk
$chunkStart->modify('+7 days');
}
}
// 5⃣ FINAL RESPONSE
foreach ($finalResult as $key => $value) {
$relationship = strtolower(trim($value['relation'] ?? ''));
if ($relationship === 'employee') {
$relationship = 'self';
}
$ticket = $this->db->table('ticket_master tm')->select("tm.id")
->where('tm.policy_no', $value['policY_NUMBER'])
->where('tm.emp_code', $value['employeE_NO'])
->where('tm.claim_amount', $value['estimateD_CLAIM_AMOUNT'])
->where('tm.doa', $this->mediDate($value['datE_OF_ADMISSION'] ?? null))
// ->where('tm.claim_number', $value['tpA_CLAIM_NO'])
->get()
->getRowArray();
if(!$ticket)
{
// VALID STATUS LIST
$validStatuses = [
"Claim Received" => 1,
"In Progress" => 5,
"Processed" => 11,
"Claim Paid" => 11,
"Denied" => 13,
"Cancelled" => 13,
"Information Awaited" => 4,
"Confirmation Awaited" => 4,
"Information Awaited Reminder" => 4,
"Information Awaited Final Reminder" => 4,
"Insurer Concurrence Awaited" => 6,
"Closed" => 12,
"Physical Documents Awaited" => 9,
"Processed - Payment Initiated" => 10,
"Processed - Transaction Failed" => 10,
"Processed - Account Details Updated" => 10,
"Processed - Debit Note Raised With Insurer for Payment"=> 10,
"Processed - Payment Initiated by Insurer" => 10,
"Payment - Refunded to Insurer" => 14,
"Processed - Processing Payment" => 10,
"Processed - Physical Documents Awaited" => 9,
"Pre-Auth Processed" => 8,
// Extra Mappings (based on your DB list)
"NON ID" => 1,
"ID NOT GENERATED" => 2,
"CDA" => 3,
"REJECTED" => 8,
"APPROVED" => 9,
"PAYMENT INITIATED" => 10,
"SETTLED" => 11,
"RETURNED" => 14,
"UNDER PROCESS - TPA" => 61,
"DENIAL REVIEW AWAITED" => 66,
];
$currentStatus = trim($value['claim_Current_Status'] ?? '');
$claimStatusId = $validStatuses[$currentStatus] ?? null;
if (!$claimStatusId) {
log_message('error', 'Unknown claim status: '.$currentStatus);
continue;
}
$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', $value['policY_NUMBER'])
->orderBy('client_rm.id','DESC')
->get()
->getRowArray();
$employee = $this->db->table('employees e')
->select("
e.id as emp_id,
e.emp_code ,
e2.id as insured_emp_id,
ep.tpa_id as tpa_no,
")
->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', $value['employeE_NO'])
->where('e.relationship', 'self')
->get()
->getRowArray();
$claimData = [
// Core
'ticket_type_id' => 1,
'claim_status_id' => $claimStatusId,
'policy_no' => $value['policY_NUMBER'] ?? null,
'claim_number' => $value['tpA_CLAIM_NO'] ?? null,
'tpa_claim_id' => $value['tpA_CLAIM_NO'] ?? null,
// local promary id
'tpa_id' => $clientpolicy['tpa_id'] ?? null,
'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' => $value['employeE_NO'] ?? null,
'emp_name' => $value['employeE_NAME'] ?? null,
'insured_name' => $value['beneficiarY_NAME'] ?? null,
'relationship' => $relationship,
'emp_mobile' => $value['mobile'] ?? null,
'emp_mail' => $value['email'] ?? null,
// Claim info
'claim_type' => 1,
'mode_of_intimation' => 5,
'claim_amount' => $value['estimateD_CLAIM_AMOUNT']
?? $value['finaL_BILL_AMOUNT']
?? null,
'approved_amount' => $value['claiM_APPROVED_AMOUNT'] ?? null,
// Dates
'dob' => $this->mediDate($value['datE_OF_BIRTH'] ?? null),
'doa' => $this->mediDate($value['datE_OF_ADMISSION'] ?? null),
'dod' => $this->mediDate($value['datE_OF_DISCHARGE'] ?? null),
'raised_date' => $this->mediDate($value['claiM_REGISTERED_DATE'] ?? null),
'approved_date' => $this->mediDate($value['approved_Date'] ?? null),
'settled_date' => $this->mediDate($value['paiD_DATE'] ?? null),
// Hospital
'hospital_name' => $value['hospitaL_NAME'] ?? null,
'hospital_address' => $value['hospitaL_ADDRESS'] ?? null,
'hospital_state' => $value['hospitaL_STATE'] ?? null,
'hospital_city' => $value['hospitaL_CITY'] ?? null,
'hospital_pin_code'=> $value['hosP_PINCODE'] ?? null,
// Payment
'utr_details' => $value['banK_CHEQUE_NO'] ?? null,
'settle_letter' => $value['settlement_LetterLink'] ?? null,
];
$this->db->table('ticket_master')->insert($claimData);
log_message(
'error',
'New claim created | Policy: '.$claimData['policy_no'].' | Claim: '.$claimData['claim_number']
);
}
}
return $this->response->setJSON([
'status' => true,
'message' => 'TPA claim status sync completed',
'total_records' => count($finalResult),
'result' => $finalResult,
'errors' => $errorData
]);
}
public function mediDate($date)
{
if (empty($date)) return null;
$dt = \DateTime::createFromFormat('d/m/Y H:i:s', $date);
return $dt ? $dt->format('Y-m-d') : null;
}
public function HospitalNetwork (){
$postData = $this->request->getJSON(true);
helper('api');
$url = ''. getenv('MEDI_ASSIST_API_BASE_URL').'/NetworkHospital';
$method = 'POST';
$headers = [
'Content-Type: application/json',
'Username:'. getenv('MEDI_ASSIST_API_USERNAME').'',
'Password:'. getenv('MEDI_ASSIST_API_PASSWORD').'',
];
$body = [
"startIndex" => 0,
"endIndex" => 10,
"policyNumber" => "97000063250400000031"
];
$response = call_third_party_api($url, $method, $headers, $body);
if($response['status'] != true){
return $this->response->setJSON([
'status' => false,
'message' => 'failed.',
'data' => $response
]);
}
return $this->response->setJSON($response);
}
public function IntimateClaim (){
$postData = $this->request->getJSON(true);
helper('api');
// $url = ''. getenv('MEDI_ASSIST_API_BASE_URL').'/ClaimAPIServiceUAT/Claim/IntimateClaim';
$url = "https://apiintegration.mediassist.in/ClaimAPIServiceUAT/Claim/IntimateClaim";
$method = 'POST';
$headers = [
'Content-Type: application/json',
'Username:' .'NhanceUsr',
'Password:' .'NhU$p&Cc5wGQbr2',
];
$p = 'NhU$p&Cc5wGQbr2';
$body = [
"Username" => "NhanceUsr",
"Password" => $p,
"policyNo" => "570000/48/2025/286",
"memberId" => 4078919887,
"DateOfAdmisssion" => date('Y-m-d', strtotime('2023-12-14')),
"HospitalName" => "test",
"AilmentDescription" => "Kidney",
"ContactNo" => "78745XXXXX"
];
$response = call_third_party_api($url, $method, $headers, $body);
if($response['status'] != true){
return $this->response->setJSON([
'status' => false,
'message' => 'failed.',
'data' => $response
]);
}
return $this->response->setJSON($response);
}
public function fileDownload()
{
$filePath = $this->request->getGet('file_path');
$filename = basename($filePath);
// Return file as download
return $this->response->download($filePath, null)->setFileName($filename);
}
}