diff --git a/.env.sample b/.env.sample index cd4743fb..e834a822 100755 --- a/.env.sample +++ b/.env.sample @@ -111,4 +111,12 @@ FHPL_PRIMARY_KEY_CONSTANT = VIDAL_PRIMARY_KEY_CONSTANT = -MEDI_ASSIST_PRIMARY_KEY_CONSTANT = \ No newline at end of file +MEDI_ASSIST_PRIMARY_KEY_CONSTANT = + + +FHPL_TOKEN_URL = +FHPL_BASE_URL = +FHPL_USER_NAME = +FHPL_PASSWORD = +FHPL_GRANT_TYPE = + diff --git a/app/Config/Routes.php b/app/Config/Routes.php index 772e4239..129e9d4e 100755 --- a/app/Config/Routes.php +++ b/app/Config/Routes.php @@ -773,11 +773,11 @@ $routes->get('fetchUHIDDetails','ICICILombardController::fetchUHIDDetails'); //Third party - testing route $routes->get('FhplGetBenefDetails','FhplApiController::FhplGetBenefDetails'); -$routes->get('EcardRequest','VidalApiController::EcardRequest'); +$routes->get('EcardRequest','FhplApiController::EcardRequest'); $routes->get('HospitalNetwork','MediAssistApiController::HospitalNetwork'); $routes->get('VidalGetBenefDetails','VidalApiController::VidalGetBenefDetails'); $routes->get('ClaimDetail','FhplApiController::ClaimDetail'); -$routes->get('SubmitClaim','FhplApiController::SubmitClaim'); +$routes->get('SubmitClaim','VidalApiController::SubmitClaim'); $routes->get('IntimateClaim','MediAssistApiController::IntimateClaim'); $routes->get('IRSubmission','MediAssistApiController::IRSubmission'); $routes->get('ClaimStatusUpdate','MediAssistApiController::ClaimStatusUpdate'); diff --git a/app/Controllers/ApiServiceController.php b/app/Controllers/ApiServiceController.php index 7c256f40..075a7e01 100644 --- a/app/Controllers/ApiServiceController.php +++ b/app/Controllers/ApiServiceController.php @@ -12,6 +12,7 @@ use App\Controllers\BaseController; use App\Controllers\VidalApiController; use App\Controllers\ICICILombardController; use App\Controllers\MediAssistApiController; +use App\Controllers\FhplApiController; use App\Models\BatchFileModel; use App\Models\FileModel; use App\Helpers\TPADataCompareHelper; @@ -26,6 +27,7 @@ class ApiServiceController extends BaseController protected $medi_assist_primary_key; protected $vidal_primary_key; protected $icici_primary_key; + protected $fhpl_primary_key; public function __construct() { @@ -34,6 +36,7 @@ class ApiServiceController extends BaseController $this->medi_assist_primary_key = getenv('MEDI_ASSIST_PRIMARY_KEY_CONSTANT'); $this->vidal_primary_key = getenv('VIDAL_PRIMARY_KEY_CONSTANT'); $this->icici_primary_key = getenv('ICICI_PRIMARY_KEY_CONSTANT'); + $this->fhpl_primary_key = getenv('FHPL_PRIMARY_KEY_CONSTANT'); } // Push Claims @@ -55,6 +58,10 @@ class ApiServiceController extends BaseController { // Vidal $vidalApiController = new VidalApiController; return $vidalApiController->SubmitClaim($claimId); + }else if ($tpaID == $this->fhpl_primary_key) + { // fhpl + $fhplApiController = new FhplApiController; + return $fhplApiController->SubmitClaim($claimId); }else{ log_message('error', "This ticket id ( {$claimId} ) TPA has no API service enabled. TPA ID : {$tpaID}"); } @@ -130,6 +137,12 @@ class ApiServiceController extends BaseController $vidalApiController = new VidalApiController; $data['eCardDownload'] = $vidalApiController->EcardRequest( $emp_code, $policy_no , $employee_policy[0]['tpa_id'] ); + }else if($employee_policy[0]['tpa_primary_id'] == $this->fhpl_primary_key)// Fhpl + { + + $fhplApiController = new FhplApiController; + $data['eCardDownload'] = $fhplApiController->EcardRequest( $emp_code, $policy_no , $employee_policy[0]['tpa_id'] ); + }else{ if($type == "download"){ @@ -266,6 +279,17 @@ class ApiServiceController extends BaseController return $this->respond(['status' => true, 'code' => 200, 'message' => 'Action Triggered','data' => [] ]); + }else if ($tpa_id == $this->fhpl_primary_key) // Fhpl + { + $file_id = $fileModel->insert($data); + log_message('error', "Files table inserted successfully, File id : {$file_id}"); + // $fhplApiController = new FhplApiController; + // $fhplApiController->FhplGetBenefDetails( [ 'polict_no' => $policy_no, 'file_id' =>$file_id ] ); + $r = Jobs::addJob(['job_name' => 'FhplGetBenefDetails', 'payload' => ['policy_no' => $policy_no, 'file_id' => $file_id, 'client_policy_id' => $policy_id, 'return_type' => 'job']]); + log_message('error', "FhplGetBenefDetails 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' => [] ]); } @@ -287,12 +311,20 @@ class ApiServiceController extends BaseController if ($tpaID == $this->medi_assist_primary_key) { // MediAssist $mediAssistController = new MediAssistApiController(); - return $mediAssistController->ClaimDetail($claimId); + $res = $mediAssistController->ClaimDetail($claimId); + return $this->response->setJSON(['status' => $res['status'],'message' => $res['message'] ]); }else if ($tpaID == $this->vidal_primary_key) { // vidal $vidalApiController = new VidalApiController; - return $vidalApiController->ClaimDetail($claimId); + $res = $vidalApiController->ClaimDetail($claimId); + return $this->response->setJSON(['status' => $res['status'],'message' => $res['message'] ]); + + }else if ($tpaID == $this->fhpl_primary_key) { // Fhpl + + $fhplApiController = new FhplApiController; + $res = $fhplApiController->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}"); diff --git a/app/Controllers/ClientController.php b/app/Controllers/ClientController.php index 56066c73..52b2a67f 100755 --- a/app/Controllers/ClientController.php +++ b/app/Controllers/ClientController.php @@ -1831,6 +1831,7 @@ class ClientController extends AdminController $this->myLogger->logme('error', 'Client branch EDIT function called'); $data = $this->request->getPost(); + $sanitized_post_data = sanitizeInputArrayAdvanced($data); $id = $sanitized_post_data['branch_id_primarykey'] ?? null; $client_id = $sanitized_post_data['client_id'] ?? null; @@ -1838,7 +1839,7 @@ class ClientController extends AdminController $data['pre_branch_id'] = $pre_branch_id; - $units = $sanitized_post_data['units'] ?? null; + $raw_units = $this->request->getPost('units'); $emp_unit_count = 0; $rr_unit_count = 0; @@ -1846,12 +1847,13 @@ class ClientController extends AdminController $total_count = 0; $list_of_branch_units = $this->clientBranchModel->find((int)$id); - $units = json_decode($list_of_branch_units['units']); + $units = !empty($list_of_branch_units['units']) ? json_decode($list_of_branch_units['units'], true) : []; if (!is_array($units) || empty($units)) { $client_data = $this->clientModel->where('id', $sanitized_post_data['client_id'])->first(); $default_unit = trim(($client_data['short_name'] ?? '') . '-' . ($sanitized_post_data['branch_code'] ?? ''), '-'); $sanitized_post_data['units'] = json_encode([$default_unit]); + $units = [$default_unit]; // Update local variable for counting } if (!empty($units)) { @@ -1866,17 +1868,21 @@ class ClientController extends AdminController $uncommonValues = []; + if ($total_count > 0) { - $units = (string) $sanitized_post_data('units'); // Assuming 'units' is an array + + $post_units_raw = $sanitized_post_data['units'] ?? '[]'; - $list_of_branch_units = $this->clientBranchModel->find((int)$id); - $branch_units = json_decode($list_of_branch_units['units'], true); - $units = json_decode($units); - - $uncommonValues = array_diff($branch_units, $units); + $branch_units = json_decode($list_of_branch_units['units'] ?? '[]', true); + + // Ensure we handle both string-json and array types + $incoming_units = is_array($post_units_raw) ? $post_units_raw : json_decode($post_units_raw, true); + + if (is_array($branch_units) && is_array($incoming_units)) { + $uncommonValues = array_diff($branch_units, $incoming_units); + } if (count($uncommonValues) > 0) { - $branchData = $this->clientBranchModel->where('client_id', $client_id)->findAll(); return $this->respond([ @@ -1888,7 +1894,7 @@ class ClientController extends AdminController ], 200); } } - + if (!isset($sanitized_post_data['sez'])) { $sanitized_post_data['sez'] = 0; } elseif ($sanitized_post_data['sez']) { diff --git a/app/Controllers/FhplApiController.php b/app/Controllers/FhplApiController.php index 9497433c..f2ac8b17 100644 --- a/app/Controllers/FhplApiController.php +++ b/app/Controllers/FhplApiController.php @@ -69,7 +69,7 @@ class FhplApiController extends BaseController ]); } - public function SubmitClaim($claimId = 515) + public function SubmitClaim($claimId = null) // 515 { helper('api'); @@ -99,7 +99,7 @@ class FhplApiController extends BaseController if (count($data) && $data['filePath'] == null) { log_message('error', "TPA CLAIM PUSH FAILED FHPL | claimId: '.$claimId.' - Claim or File Missing"); - return $this->response->setJSON(['status' => false,'message' => 'Claim or File Missing', ]); + return; } // Build absolute file path @@ -108,7 +108,7 @@ class FhplApiController extends BaseController if (!file_exists($pdfPath)) { log_message('error', "TPA CLAIM PUSH FAILED FHPL | claimId: '.$claimId.' - PDF not found on server"); - return $this->response->setJSON(['status' => false,'message' => 'PDF not found on server']); + return; } // Convert PDF to Base64 @@ -117,7 +117,8 @@ class FhplApiController extends BaseController // Generate FHPL Token $tokenResponse = json_decode($this->generateAuthToken()->getBody(), true); if (empty($tokenResponse['data']['access_token'])) { - return $this->response->setJSON(['status' => false,'message' => 'FHPL Token generation failed']); + log_message('error', "TPA CLAIM PUSH FAILED FHPL | claimId: '.$claimId.' - FHPL Token generation failed"); + return; } $token = $tokenResponse['data']['access_token']; @@ -125,10 +126,10 @@ class FhplApiController extends BaseController $body = [ "IssueID" => $data['dependentUniqueId'], // this key added after seeing the error in responce have to click with fhpl team "Userid" => getenv('FHPL_USER_NAME'), - "PolicyNo" => "111700-TATAMTORS", // $data['policyNo'], - "UhidNo" => "OIC40830846", //$data['dependentUniqueId'], + "PolicyNo" => $data['policyNo'], // "111700-TATAMTORS", + "UhidNo" => $data['dependentUniqueId'], // "OIC40830846", "ClaimID" => (string) $data['id'], - "DOA" => "2025-10-11",//date('Y-m-d', strtotime($data['admissionDate'])), + "DOA" => date('Y-m-d', strtotime($data['admissionDate'])), //"2025-10-11", "DateofDischarge"=> $data['dischargeDate'] ? date('Y-m-d', strtotime($data['dischargeDate'])) : null, "ClaimedAmount" => (float) $data['requestedAmount'], "DocumentType" => 20, // Fresh Claim @@ -155,7 +156,7 @@ class FhplApiController extends BaseController $response = call_third_party_api($url, 'POST', $headers, $body); - log_message('error', 'FHPL RESPONSE | ' . json_encode($response)); + log_message('error', 'TPA CLAIM PUSH FHPL RESPONSE | ' . json_encode($response)); if($response['status'] != true){ log_message('error', 'TPA CLAIM PUSH FAILED FHPL | claimId: '.$claimId.' | response: '.json_encode($response)); @@ -185,14 +186,17 @@ class FhplApiController extends BaseController log_message('error', 'TPA CLAIM PUSH SUCCESS FHPL | claimId: '.$claimId.' | claimNO: '.$fhplClaimNo); + }else { + log_message('error', 'TPA CLAIM PUSH API SUCCESS BUT claimsInfo EMPTY | response: '.json_encode($response)); + return; } } - - return $this->response->setJSON($response); + return; + // return $this->response->setJSON($response); } - public function ClaimDetail($claimId = 515) + public function ClaimDetail($claimId = null) //515 { helper('api'); @@ -203,13 +207,13 @@ class FhplApiController extends BaseController ->get()->getRowArray(); - if(!$ticket) return $this->response->setJSON(['status'=>false,'message'=>'Invalid claim']); + if(!$ticket) return ['status'=>false,'message'=>'Invalid claim']; // Generate FHPL Token $tokenResponse = json_decode($this->generateAuthToken()->getBody(), true); if (empty($tokenResponse['data']['access_token'])) { - return $this->response->setJSON(['status' => false,'message' => 'FHPL Token generation failed']); + return ['status' => false,'message' => 'FHPL Token generation failed']; } $token = $tokenResponse['data']['access_token']; @@ -219,9 +223,9 @@ class FhplApiController extends BaseController $body = [ "UserName" => getenv('FHPL_USER_NAME'), "Password" => getenv('FHPL_PASSWORD'), - "PolicyNumber" => "GHI-81-25-00087313-000",//$ticket['policy_no'], - "Fromdate" => "2025-04-26",//$ticket['claimNo'], - "Todate" => "2025-04-27",//$ticket['claimNo'], + "PolicyNumber" => $ticket['policy_no'], //"GHI-81-25-00087313-000", + "Fromdate" => $ticket['policy_start_date'],//"2025-04-26", + "Todate" => $ticket['policy_end_date'],//"2025-04-27", ]; $headers = ["Authorization: Bearer ".$token,"Content-Type: application/json"]; @@ -232,12 +236,7 @@ class FhplApiController extends BaseController if (empty($response['data'][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 - ]); + return ['status' => false,'message' => 'API call failed.','data' => $response ]; } @@ -263,18 +262,11 @@ class FhplApiController extends BaseController if( $status != null && isset($map[$status])) { $this->db->table('ticket_master')->where('id',$claimId)->update(['claim_status_id'=>$map[$status],'tpa_claim_status'=>$status]); - // LOG UPDATE log_message('error', "CLAIM STATUS SUCCESS | Updated ticket ID $claimId with claim status: $status"); } - - return $this->response->setJSON([ - 'status' => true, - 'message' => 'Claim status updated.', - 'updated_status' => $status, - 'api_response' => $response - ]); + return ['status' => true,'message' => 'Claim status updated.','updated_status' => $status,'api_response' => $response]; } @@ -298,24 +290,16 @@ class FhplApiController extends BaseController return $this->response->setJSON(['status'=>true,'updated'=>$count]); } - public function EcardRequest($employeeId,$policyNo,$uhid) + public function EcardRequest($employeeId = null,$policyNo = null,$uhid = null) { helper('api'); // Generate FHPL Token $tokenResponse = json_decode($this->generateAuthToken()->getBody(), true); - if (empty($tokenResponse['data']['access_token'])) { - return $this->response->setJSON(['status' => false,'message' => 'FHPL Token generation failed']); + log_message('error', 'Ecard Request FAILED | employeeId: '.$employeeId.' | policyNo: '.$policyNo.' | Message: FHPL Token generation failed'); + return null; } - - // Generate FHPL Token - $tokenResponse = json_decode($this->generateAuthToken()->getBody(), true); - - if (empty($tokenResponse['data']['access_token'])) { - return $this->response->setJSON(['status' => false,'message' => 'FHPL Token generation failed']); - } - $token = $tokenResponse['data']['access_token']; $url = getenv('FHPL_BASE_URL')."/api/GetEcard"; @@ -323,107 +307,402 @@ class FhplApiController extends BaseController $body = [ "UserName" => getenv('FHPL_USER_NAME'), "Password" => getenv('FHPL_PASSWORD'), - "PolicyNumber" => $policyNo, - "EmployeeID" => $employeeId + "PolicyNumber" => $policyNo, //'10/12/2025/16/17', + "EmployeeID" => $employeeId, //'101225', ]; $headers = ["Authorization: Bearer ".$token,"Content-Type: application/json"]; $response = call_third_party_api($url,'POST',$headers,$body); + // dd($response); - if(($response['data']['STATUS'] ?? '')=='SUCCESS'){ - return $response['data']['E_Card']; + if (($response['status'] ?? false) !== true) { + log_message('error', 'Ecard Request FAILED | response: ' . json_encode($response)); + return null; } + if (empty($response['data'][0])) { + log_message('error', 'Ecard Request FAILED | Empty data | response: ' . json_encode($response)); + return null; + } + + $apiData = $response['data'][0]; + + if (($apiData['STATUS'] ?? '') === 'SUCCESS') { + + $ecardUrl = $apiData['E_Card'] ?? ''; + + if (!empty($ecardUrl)) { + log_message( + 'info', + 'Ecard Request PUSH SUCCESS | employeeId: ' . $employeeId . + ' | policyNo: ' . $policyNo . + ' | ecardUrl: ' . $ecardUrl + ); + return $ecardUrl; + } + } + + log_message('error', 'Ecard Request FAILED | response: ' . json_encode($response)); return null; } public function FhplGetBenefDetails($requestData = null) { - helper('api'); - $policyNo = $requestData['policy_no'] ?? "10/12/2025/16/17"; - $client_policy_id = $requestData['client_policy_id'] ?? 0; + $function_calling_type = $requestData['return_type'] ?? 'job'; - // Generate FHPL Token - $tokenResponse = json_decode($this->generateAuthToken()->getBody(), true); - if (empty($tokenResponse['data']['access_token'])) { - return $this->response->setJSON(['status' => false,'message' => 'FHPL Token generation failed']); - } - $token = $tokenResponse['data']['access_token']; + try { + + helper('api'); - $url = getenv('FHPL_BASE_URL')."/api/GetEnrollmentDetailsPolicy"; + $policyNo = $requestData['policy_no'] ?? null; + $client_policy_id = $requestData['client_policy_id'] ?? null; - $headers = [ - "Authorization: Bearer ".$token, - "Content-Type: application/json" - ]; - - $startIndex = 0; - $range = 100; - $allMembers = []; - - do { - $body = [ - "UserName" => getenv('FHPL_USER_NAME'), - "Password" => getenv('FHPL_PASSWORD'), - "PolicyNumber" => $policyNo, - "StartIndex" => $startIndex, - "Range" => $range - ]; - - $response = call_third_party_api($url,'POST',$headers,$body); - - dd($response); - - if(empty($response['data']['Members'])){ - break; - } - - $allMembers = array_merge($allMembers,$response['data']['Members']); - - $startIndex += $range; - - } while($startIndex < ($response['data']['Total'] ?? 0)); - - - dd($allMembers); - - // Now same matching logic you already have - $employeePolicyModel = new EmployeePolicyModel(); - - $employeePolicyData = $employeePolicyModel - ->join('employees','employees.id=employee_polices.employee_id') - ->where('employee_polices.client_policy_id',$client_policy_id) - ->where('employee_polices.tpa_id IS NULL') - ->findAll(); - - $updated = 0; - - foreach($employeePolicyData as $policy){ - foreach($allMembers as $m){ - - if( - strtolower(trim($policy['name']))==strtolower(trim($m['Name'])) && - $policy['emp_code']==$m['MemberID'] && - strtolower($policy['relationship'])==strtolower($m['Relation']) - ){ - $this->db->table('employee_polices') - ->where('id',$policy['emp_policy_id']) - ->update(['tpa_id'=>$m['UHID']]); - - $updated++; + 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']); } } - } - return [ - 'status'=>true, - 'total_fetched'=>count($allMembers), - 'updated'=>$updated - ]; + 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}"); + + // 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', 'TPA ID PULL FAILED | batchFiles is empty for this tpa id pull request'); + if($function_calling_type == "job"){ + return ['status' => false, 'message' => 'batchFiles not found']; + }else{ + return $this->respond(['status' => false, 'message' => 'batchFiles not found']); + } + } + + // Generate FHPL Token + $tokenResponse = json_decode($this->generateAuthToken()->getBody(), true); + if (empty($tokenResponse['data']['access_token'])) { + log_message('error', 'TPA ID PULL | FHPL Token generation failed'); + if($function_calling_type == "job"){ + return ['status' => false, 'message' => 'FHPL Token generation failed']; + }else{ + return $this->respond(['status' => false, 'message' => 'FHPL Token generation failed']); + } + } + $token = $tokenResponse['data']['access_token']; + + $url = getenv('FHPL_BASE_URL') . "/api/GetEnrollmentDetailsPolicy"; + + $headers = [ + "Authorization: Bearer " . $token, + "Content-Type: application/json" + ]; + + $startIndex = 0; + $range = 100; + $allMembers = []; + + while (true) { + + $body = [ + "UserName" => getenv('FHPL_USER_NAME'), + "Password" => getenv('FHPL_PASSWORD'), + "PolicyNumber" => $policyNo, + "StartIndex" => $startIndex, + "Range" => $range + ]; + + log_message('error', "TPA ID PULL | API parems " . json_encode([$url, 'POST', $headers, $body])); + + $response = call_third_party_api($url, 'POST', $headers, $body); + + if (($response['status'] ?? false) !== true) { + log_message('error', 'FHPL API FAILED | response: ' . json_encode($response)); + break; + } + + if ( + !isset($response['data']) || + !is_array($response['data']) || + count($response['data']) === 0 || + !array_is_list($response['data']) // PHP 8+ safe check + ) { + // STOP when data is not a valid list + break; + } + + $allMembers = array_merge($allMembers, $response['data']); + + // Move to next page + $startIndex += $range; + } + + if(empty($allMembers)) + { + + // 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: Empty menber data for this pull request'); + + if($function_calling_type == "job"){ + return ['status' => false, 'message' => 'API call failed', 'data' => 'Empty menber data for this pull request']; + }else{ + return $this->respond(['status' => false, 'message' => 'API call failed', 'data' => 'Empty menber data for this pull request']); + } + + } + + // dd($allMembers); + + //save API data as JSON for analysis + $json = json_encode($allMembers, 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' => 'saveFhplAPIData', 'payload' => [ 'file_id' => $requestData['file_id'],'json_file_path' => $filePath ]]); + + // ================= MATCHING LOGIC ================= + + $employeePolicyModel = new EmployeePolicyModel(); + + $employeePolicyData = $employeePolicyModel + ->join('employees', 'employees.id = employee_polices.employee_id') + ->where('employee_polices.client_policy_id', $client_policy_id) + ->where('employee_polices.tpa_id IS NULL') + ->findAll(); + + $updated = 0; + + foreach ($employeePolicyData as $policy) { + $hasMatchForThisPolicy = false; + foreach ($allMembers as $m) { + + if ( + strtolower(trim($policy['name'])) === strtolower(trim($m['EMPLOYEE_NAME'] ?? '')) && + ($policy['emp_code'] ?? '') == ($m['EMPLOYEE_ID'] ?? '') && + strtolower($policy['relationship']) === strtolower($m['RELATION'] ?? '') + ) { + + $hasMatchForThisPolicy = true; + + + $sql = "UPDATE employee_polices SET tpa_id = ? WHERE id = ?"; + $this->db->query($sql, [$m['TPA_TPADETAIL_ID'], $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', "✅ Updated tpa_id={$m['TPA_TPADETAIL_ID']} for emp_policy_id={$policy['emp_policy_id']} policy={$policyNo}"); + } else { + log_message('error', "⚠️ 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_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."); + } + + $totalCount = count($allMembers); + + 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 FhplGetBenefDetails($requestData = null) + // { + // helper('api'); + + // $policyNo = $requestData['policy_no'] ?? "10/12/2025/16/17"; + // $client_policy_id = $requestData['client_policy_id'] ?? 0; + + // // Generate FHPL Token + // $tokenResponse = json_decode($this->generateAuthToken()->getBody(), true); + // if (empty($tokenResponse['data']['access_token'])) { + // return $this->response->setJSON(['status' => false,'message' => 'FHPL Token generation failed']); + // } + // $token = $tokenResponse['data']['access_token']; + + // $url = getenv('FHPL_BASE_URL')."/api/GetEnrollmentDetailsPolicy"; + + // $headers = [ + // "Authorization: Bearer ".$token, + // "Content-Type: application/json" + // ]; + + // $startIndex = 0; + // $range = 100; + // $allMembers = []; + + // do { + // $body = [ + // "UserName" => getenv('FHPL_USER_NAME'), + // "Password" => getenv('FHPL_PASSWORD'), + // "PolicyNumber" => $policyNo, + // "StartIndex" => $startIndex, + // "Range" => $range + // ]; + + // $response = call_third_party_api($url,'POST',$headers,$body); + + // dd($response); + + // if(empty($response['data']['Members'])){ + // break; + // } + + // $allMembers = array_merge($allMembers,$response['data']['Members']); + + // $startIndex += $range; + + // } while($startIndex < ($response['data']['Total'] ?? 0)); + + + // dd($allMembers); + + // // Now same matching logic you already have + // $employeePolicyModel = new EmployeePolicyModel(); + + // $employeePolicyData = $employeePolicyModel + // ->join('employees','employees.id=employee_polices.employee_id') + // ->where('employee_polices.client_policy_id',$client_policy_id) + // ->where('employee_polices.tpa_id IS NULL') + // ->findAll(); + + // $updated = 0; + + // foreach($employeePolicyData as $policy){ + // foreach($allMembers as $m){ + + // if( + // strtolower(trim($policy['name']))==strtolower(trim($m['Name'])) && + // $policy['emp_code']==$m['MemberID'] && + // strtolower($policy['relationship'])==strtolower($m['Relation']) + // ){ + // $this->db->table('employee_polices') + // ->where('id',$policy['emp_policy_id']) + // ->update(['tpa_id'=>$m['UHID']]); + + // $updated++; + // } + // } + // } + + // return [ + // 'status'=>true, + // 'total_fetched'=>count($allMembers), + // 'updated'=>$updated + // ]; + // } + public function syncFhplClaimsToNhance() { helper('api'); diff --git a/app/Controllers/JobWorker.php b/app/Controllers/JobWorker.php index 160c6fe9..f2020755 100755 --- a/app/Controllers/JobWorker.php +++ b/app/Controllers/JobWorker.php @@ -191,6 +191,10 @@ class JobWorker extends AdminController 'type' => 'CC', // Handler Category 'handler' => 'App\Controllers\VidalApiController', ], + 'FhplGetBenefDetails' => [ + 'type' => 'CC', // Handler Category + 'handler' => 'App\Controllers\FhplApiController', + ], 'bdsDumpExcelFileFormatValidation' => [ 'type' => 'CC', // Handler Category 'handler' => 'App\Controllers\PolicyTransactionController', diff --git a/app/Controllers/MediAssistApiController.php b/app/Controllers/MediAssistApiController.php index 9ce9be18..0452c797 100644 --- a/app/Controllers/MediAssistApiController.php +++ b/app/Controllers/MediAssistApiController.php @@ -518,7 +518,7 @@ class MediAssistApiController extends BaseController ->getRowArray(); if (!$ticket) { - return $this->response->setJSON(['status' => false,'message' => 'Invalid Claim ID' ]); + return ['status' => false,'message' => 'Invalid Claim ID' ]; } // REQUEST BODY @@ -548,8 +548,6 @@ class MediAssistApiController extends BaseController } - - // $body = [ // "policyNo" => "97000063250400000031", // "startDate" => "01/11/2025", @@ -568,11 +566,7 @@ class MediAssistApiController extends BaseController 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 - ]); + return ['status' => false,'message' => 'API call failed.','data' => $response ]; } // Extract claim status @@ -634,12 +628,7 @@ class MediAssistApiController extends BaseController // 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 - ]); + return ['status' => true,'message' => 'Claim status updated.','updated_status' => $currentStatus,'api_response' => $response]; } public function IRSubmission($claimId = null) // 585 this id for test diff --git a/app/Controllers/VidalApiController.php b/app/Controllers/VidalApiController.php index 0c0bc293..f84364a9 100644 --- a/app/Controllers/VidalApiController.php +++ b/app/Controllers/VidalApiController.php @@ -254,8 +254,8 @@ class VidalApiController extends BaseController if($response['data']['status'] == 'SUCCESS') { - $claimNO = $response['data']['data']['claimNO'] ?? null; - $claimInwardNO = $response['data']['data']['claimInwardNO'] ?? null; + $claimNO = $response['data']['data']['claimNo'] ?? null; + $claimInwardNO = $response['data']['data']['claimInwardNo'] ?? null; if(!empty($claimNO) && !empty($claimInwardNO)){ @@ -263,7 +263,7 @@ class VidalApiController extends BaseController $this->db->table('ticket_master') ->where('id',$claimId) - ->update([ 'tpa_claim_push_reference_no' => $claimInwardNO , 'tpa_claim_id' => $claimNO ]); + ->update([ 'tpa_claim_push_reference_no' => $claimInwardNO , 'tpa_claim_id' => $claimNO , 'claim_number' => $claimNO ]); return; @@ -442,7 +442,7 @@ class VidalApiController extends BaseController ->getRowArray(); if (!$ticket) { - return $this->response->setJSON(['status' => false,'message' => 'Invalid Claim ID' ]); + return ['status' => false,'message' => 'Invalid Claim ID' ]; } $body = []; @@ -467,11 +467,7 @@ class VidalApiController extends BaseController if ($response['status'] != true || empty($response['data']['data']['claims'][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 - ]); + return ['status' => false, 'message' => 'API call failed.','data' => $response]; } // Extract claim status @@ -504,12 +500,7 @@ class VidalApiController extends BaseController // 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 - ]); + return ['status' => true,'message' => 'Claim status updated.','updated_status' => $currentStatus,'api_response' => $response]; } public function ClaimStatusUpdate() @@ -804,7 +795,7 @@ class VidalApiController extends BaseController //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 ]]); + $r = Jobs::addJob(['job_name' => 'saveVidalAPIData', 'payload' => [ 'file_id' => $requestData['file_id'],'json_file_path' => $filePath ]]); // now update DB