generateAuthToken('esbgpauhid'); if (!$tokenResponse || empty($tokenResponse['data']['access_token'])) { log_message('error', 'ICICI - Token generation failed for UHID fetch: ' . json_encode($tokenResponse, JSON_PRETTY_PRINT)); return [ 'new_status' => 'FAILED', 'updatedCount' => 0, 'response' => $tokenResponse, 'error' => 'Token generation failed.', ]; } $token = $tokenResponse['data']['access_token']; log_message('error', 'ICICI - Token generated for UHID fetch.'); $url = env('ICICI_BASE_URL') . '/fetchuhid'; $headers = [ 'Authorization: Bearer ' . $token, 'Content-Type: application/json', ]; $correlationId = !empty($batch['icici_correlation_id']) ? $batch['icici_correlation_id'] : sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x', mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0x0fff) | 0x4000, mt_rand(0, 0x3fff) | 0x8000, mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff) ); log_message('error', 'ICICI - Using CorrelationId: ' . $correlationId); $imid = $overrideImid ?: ($batch['icici_batch_id'] ?? null); log_message('error', 'ICICI - Using IMID: ' . var_export($imid, true) . ' (overrideImid: ' . var_export($overrideImid, true) . ')'); if (empty($imid) || empty($batch['icici_endorsement_policy_no'])) { log_message('error', 'ICICI - IMID or endorsement PolicyNumber missing for UHID fetch. IMID: ' . var_export($imid, true) . ', endorsementPolicyNo: ' . var_export($batch['icici_endorsement_policy_no'] ?? null, true)); return [ 'new_status' => 'FAILED', 'updatedCount' => 0, 'response' => null, 'error' => 'IMID or endorsement PolicyNumber missing for UHID fetch.', ]; } $body = [ 'PolicyNumber' => $batch['icici_endorsement_policy_no'], 'IMID' => $imid, 'CorrelationId' => $correlationId, ]; log_message('error', 'ICICI - Calling fetchuhid API. URL: ' . $url . ' Request: ' . json_encode($body, JSON_PRETTY_PRINT)); $response = call_third_party_api($url, 'POST', $headers, $body, true); log_message('error', 'ICICI - fetchuhid API response: ' . json_encode($response, JSON_PRETTY_PRINT)); $apiData = $response['data'] ?? []; $newFlag = 'FAILED'; $updatedCount = 0; $emp_policy_pks = []; $client_policy_data = db_connect()->table('client_policy') ->select('cp.policy_no as policyNumber, cdm.cd_ac_no as CDBGAccountNumber, policy_type.policy_type') ->join('cd_master cdm', 'client_policy.cd_ac_pk = cdm.id') ->join('policy_type', 'policy_type.id = client_policy.policy_type_id') ->where('client_policy.id', $batch['client_policy_id']) ->get() ->getRowArray(); $file_data = db_connect()->table('batch_files') ->where('batch_files.id', $file_id) ->get() ->getRowArray(); if (!empty($response['status']) && $response['status'] === true && (($apiData['statusMessage'] ?? null) === 'SUCCESS')) { $newFlag = 'COMPLETED'; log_message('error', 'ICICI - fetchuhid API returned SUCCESS. Processing memberDetails.'); // Update UHID in employee_polices table based on memberDetails $memberDetails = $apiData['memberDetails'] ?? []; if (!empty($memberDetails) && is_array($memberDetails)) { $db = \Config\Database::connect(); $clientPolicyId = (int) ($batch['client_policy_id'] ?? 0); log_message('error', 'ICICI - MemberDetails count: ' . count($memberDetails) . ', client_policy_id: ' . $clientPolicyId); foreach ($memberDetails as $member) { $employeeMemberId = $member['employeeMemberId'] ?? null; $uhid = $member['uhid'] ?? null; log_message('error', 'ICICI - Processing member: ' . json_encode($member, JSON_PRETTY_PRINT)); if (empty($employeeMemberId) || empty($uhid)) { log_message('error', 'ICICI - Skipping member due to missing employeeMemberId or uhid. employeeMemberId: ' . var_export($employeeMemberId, true) . ', uhid: ' . var_export($uhid, true)); continue; } // Find employee by emp_code = employeeMemberId $employee = $db->table('employees') ->select('id') ->where('emp_code', $employeeMemberId) ->where('client_id', $batch['client_id']) ->where('is_active', 1) ->get() ->getRowArray(); if (empty($employee)) { log_message('error', 'ICICI - No employee found for emp_code: ' . $employeeMemberId); continue; } // Update TPA ID for that employee and policy if($file_data['action'] == 'deletion'){ $emp_policy_pks[] = $this->updateDeletionData($employee['id'], $clientPolicyId, $uhid, $member['endorsementNumber'] ?? null); }else if(in_array($file_data['action'], ['correction', 'si_enhancement'])){ $emp_policy_pks[] = $this->updateModificationData($employee, $member['endorsementNumber'] ?? null, $member, $file_data); }else{ $this->updateAdditionData($employee['id'], $clientPolicyId, $uhid); } log_message('error', 'ICICI - Updated employee_polices for employee_id: ' . $employee['id'] . ', client_policy_id: ' . $clientPolicyId . ', set tpa_id: ' . $uhid); $updatedCount++; } } else { log_message('error', 'ICICI - No memberDetails present or not an array in API response.'); } if($file_id){ $json = json_encode($memberDetails, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); $filePath = WRITEPATH . 'tmp/'.time().'_'.$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' => $file_id, 'json_file_path' => $filePath ]]); } if(!empty($emp_policy_pks)){ if($file_data['action'] == 'deletion'){ $r = Jobs::addJob(['job_name' => 'cashDepositCalculationForDeletion', 'payload' => [ 'employeeIds' => $emp_policy_pks, 'client_id' => $file_data['client_id'] ?? null, 'client_policy_id' => $file_data['client_policy_id'] ?? null, 'client_branch_id' => $file_data['client_branch_id'] ?? null, 'cd_ac_no' => $client_policy_data['CDBGAccountNumber'] ?? null, 'endorsement_no' => null, 'count' => count($emp_policy_pks), 'event_name' => $file_data['event_type'], 'policy_name' => $client_policy_data['policy_type'], 'user_id' => $file_data['created_by'] ?? null, 'file_id' => $file_id, ]]); } if($file_data['action'] == 'si_enhancement'){ $job_details = new Jobs(); $r = Jobs::addJob(['job_name' => 'cashDepositCalculationForSIEnhancement','payload' => [ 'employeeIds' => $emp_policy_pks, 'client_id' => $file_data['client_id'] ?? null, 'client_policy_id' => $file_data['client_policy_id'] ?? null, 'client_branch_id' => $file_data['client_branch_id'] ?? null, 'cd_ac_no' => $client_policy_data['CDBGAccountNumber'] ?? null, 'endorsement_no' => $file_data['endorsementNumber'] ?? null, 'count' => count($emp_policy_pks), 'event_name' => $file_data['event_type'], 'policy_name' => $client_policy_data['policy_type'], 'user_id' => $file_data['created_by'] ?? null, 'file_id' => $file_id, ]]); } } } else { log_message('error', 'ICICI - fetchuhid API did not return SUCCESS. status: ' . var_export($response['status'] ?? null, true) . ', statusMessage: ' . var_export($apiData['statusMessage'] ?? null, true) . ', message: ' . var_export($apiData['message'] ?? null, true)); } $batchModel = new BatchFileModel(); $batchModel->update($batch['id'], [ 'icici_uhid_status_flag' => $newFlag, ]); log_message('error', 'ICICI - Updated batch_files id ' . ($batch['id'] ?? 'unknown') . ' with icici_uhid_status_flag: ' . $newFlag . '. total UHIDs updated: ' . $updatedCount); return [ 'new_status' => $newFlag, 'updatedCount' => $updatedCount, 'response' => $response, 'request' => $body, ]; } public function generateAuthToken($scope = 'esbhealth') { helper('api'); $url = env('ICICI_TOKEN_URL'); $method = 'POST'; $headers = [ 'Content-Type: application/x-www-form-urlencoded' ]; $body = [ 'grant_type' => env('ICICI_GRANT_TYPE'), 'username' => env('ICICI_USER_NAME'), 'password' => env('ICICI_PASSWORD'), 'scope' => $scope ?: env('ICICI_API_SCOPE'), 'client_id' => env('ICICI_CLIENT_ID'), 'client_secret' => env('ICICI_CLIENT_SECRET') ]; $response = call_third_party_api($url, $method, $headers, $body); log_message('error', 'ICICI - generateAuthToken API URL: ' . json_encode(["url" => $url, "method" => $method, "headers" => $headers, "body" => $body], JSON_PRETTY_PRINT)); log_message('error', 'ICICI - generateAuthToken API response: ' . json_encode($response, JSON_PRETTY_PRINT)); if($response['status'] != true){ return [ 'status' => false, 'message' => 'Token generation failed.', 'data' => $response ]; } // Debug removed: return token response to caller. return $response; } public function ICICIPushEmployeeDetails($requested_data = null) { $function_calling_type = $requested_data['return_type'] ?? 'api'; try { // 1. Centralize Input $client_id = $requested_data['client_id'] ?? $this->request->getGet('client_id') ?? null; $client_branch_id = $requested_data['client_branch_id'] ?? $this->request->getGet('client_branch_id') ?? null; $policy_id = $requested_data['client_policy_id'] ?? $this->request->getGet('client_policy_id') ?? null; $file_id = $requested_data['file_id'] ?? $this->request->getGet('file_id') ?? null; $flagStatus = $requested_data['flag_status'] ?? $this->request->getGet('flag_status') ?? null; $action = $requested_data['event'] ?? $this->request->getGet('event') ?? null; $event = "ADD"; $fileModel = new BatchFileModel(); $updateBatchFileStatus = function (string $status) use ($file_id, $fileModel) { if (empty($file_id)) { log_message('error', 'ICICI - ICICIPushEmployeeDetails | file_id missing, skipped batch_files.status update.'); return; } $fileModel->where('id', $file_id)->set('status', $status)->update(); log_message('error', "ICICI - ICICIPushEmployeeDetails | batch_files.status updated for file_id {$file_id} => {$status}"); }; //fetch token $tokenResponse = $this->generateAuthToken('esbgpabatchcreation'); if (!$tokenResponse || empty($tokenResponse['data']['access_token'])) { $return_respond_data = [ 'status' => false, 'message' => 'Token generation failed.', 'data' => $tokenResponse ]; log_message('error', 'ICICI - ICICIPushEmployeeDetails Failed: ' . json_encode($return_respond_data, JSON_PRETTY_PRINT)); $updateBatchFileStatus('failed-8'); if ($function_calling_type == "job") { return $return_respond_data; } else { return $this->response->setJSON($return_respond_data); } } $token = $tokenResponse['data']['access_token']; $url = env('ICICI_BASE_URL') . '/batchcreation'; $headers = [ 'Authorization: Bearer ' . $token, 'Content-Type: application/json', ]; if(in_array($action, ['inception', 'addition', 'missed_inception', 'dependent_addition'])){ // Prepare body data from employee policies $db = \Config\Database::connect(); $data = $db->table('employee_polices ep') ->select(' cp.policy_no as policyNumber, cdm.cd_ac_no as CDBGAccountNumber, e.id,e.emp_code as MemberEmpId, e.doj as DOJ, e.name as InsuredName, e.dob as DOB, e.relationship as Relationship, e.gender as Gender, ep.date_coverage as DOC, ep.basic_cover_si as SumInsured, e.email_corporate as EmailId ') ->join('employees e', 'e.id = ep.employee_id') ->join('client_policy cp', 'ep.client_policy_id = cp.id') ->join('cd_master cdm', 'cp.cd_ac_pk = cdm.id') ->where('ep.client_policy_id', $policy_id) ->where('ep.status', 'active') ->where('ep.is_active', 1) ->where('ep.tpa_id', null) ->get() ->getResultArray(); }else if(in_array($action, ['deletion', 'correction', 'si_enhancement'])) { $EmployeePolicyModel = new EmployeePolicyModel(); if($action == 'deletion'){ $deletion_data = $EmployeePolicyModel->getDeletionEmployeeDataForExportExcel($requested_data, 1); $data = $this->formatPolicyDataForDeletion($deletion_data, $policy_id); }else if($action == 'correction'){ $correction_data = $EmployeePolicyModel->getCorrectionEmployeesDataForExportExcel($requested_data, 1); $data = $this->formatPolicyDataForCorrection($correction_data, $policy_id); }else if($action == 'si_enhancement'){ $si_enhancement_data = $EmployeePolicyModel->getSIEnhancementEmployeesDataForExportExcel($requested_data, 1); $data = $this->formatPolicyDataForSIEnhancement($si_enhancement_data, $policy_id); } } // dd($data); if (empty($data)) { $return_respond_data = [ 'status' => false, 'message' => 'No active employee policies found for given policy.', 'data' => [], ]; log_message('error', 'ICICI - ICICIPushEmployeeDetails Failed: ' . json_encode($return_respond_data, JSON_PRETTY_PRINT)); $updateBatchFileStatus('failed-8'); if ($function_calling_type == "job") { return $return_respond_data; } else { return $this->response->setJSON($return_respond_data); } } $body = $this->formatPolicyData($data, $flagStatus); if (empty($body['CDBGAccountNumber'])) { $return_respond_data = [ 'status' => false, 'message' => 'CDBGAccountNumber is empty for selected policy. Please configure policy CD account number.', 'data' => $body, ]; log_message('error', 'ICICI - ICICIPushEmployeeDetails Failed: ' . json_encode($return_respond_data, JSON_PRETTY_PRINT)); $updateBatchFileStatus('failed-8'); if ($function_calling_type == "job") { return $return_respond_data; } else { return $this->response->setJSON($return_respond_data); } } if (empty($body['MemberDetails'])) { $return_respond_data = [ 'status' => false, 'message' => 'No valid member records available for ICICI enrollment payload.', 'data' => $body, ]; log_message('error', 'ICICI - ICICIPushEmployeeDetails Failed: ' . json_encode($return_respond_data, JSON_PRETTY_PRINT)); $updateBatchFileStatus('failed-8'); if ($function_calling_type == "job") { return $return_respond_data; } else { return $this->response->setJSON($return_respond_data); } } $response = call_third_party_api($url, 'POST', $headers, $body, true); // true = raw body mode log_message('error', 'ICICI - ICICIPushEmployeeDetails call_third_party_api Response: ' . json_encode($response, JSON_PRETTY_PRINT)); // Save batch information only on successful API call if (!empty($response['status']) && $response['status'] === true) { $apiData = $response['data'] ?? []; $updateData = [ 'icici_correlation_id' => $body['CorrelationId'] ?? null, 'icici_batch_id' => $apiData['batchId'] ?? null, 'icici_status_flag' => 'PENDING', 'icici_status_message' => $apiData['message'] ?? null, 'icici_endorsement_policy_no' => $apiData['endorsement_policy_no'] ?? null, 'icici_uhid_status_flag' => 'PENDING', ]; $batchModel = new BatchFileModel(); $batchModel->where('id', $file_id)->set($updateData)->update(); log_message('error', "ICICI - ICICIPushEmployeeDetails success and update batch files table with file id : $file_id : " . json_encode($updateData, JSON_PRETTY_PRINT)); } if ($function_calling_type == "job") { $updateBatchFileStatus(!empty($response['status']) && $response['status'] === true ? 'success' : 'failed-8'); return $response; } else { $updateBatchFileStatus(!empty($response['status']) && $response['status'] === true ? 'success' : 'failed-8'); return $this->response->setJSON($response); } } catch (\Throwable $th) { $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', 'ICICI - Exception thrown while calling ICICIPushEmployeeDetails API: ' . json_encode($errorData, JSON_PRETTY_PRINT)); if (!empty($requested_data['file_id'])) { $catchFileModel = new BatchFileModel(); $catchFileModel->where('id', $requested_data['file_id'])->set('status', 'failed-8')->update(); log_message('error', "ICICI - ICICIPushEmployeeDetails | batch_files.status updated in catch for file_id {$requested_data['file_id']} => failed-8"); } $updateBatchFileStatus('failed-8'); if ($function_calling_type == "job") { return ['status' => false, 'message' => 'API call failed', 'data' => $errorData]; } else { return $this->response->setJSON(['status' => false, 'message' => 'API call failed', 'data' => []]); } } } public function getEnrollmentBatchStatus($param) { helper('api'); try { $clientPolicyId = $param['client_policy_id']; $fileId = $param['file_id']; $fileModel = new BatchFileModel(); $updateBatchFileStatus = function (string $status) use ($fileId, $fileModel) { if (empty($fileId)) { log_message('error', 'ICICI - getEnrollmentBatchStatus | file_id missing, skipped batch_files.status update.'); return; } $fileModel->where('id', $fileId)->set('status', $status)->update(); log_message('error', "ICICI - getEnrollmentBatchStatus | batch_files.status updated for file_id {$fileId} => {$status}"); }; log_message('error', "ICICI - getEnrollmentBatchStatus started for client_policy_id: {$clientPolicyId}, file_id: {$fileId}"); //fetch token $tokenResponse = $this->generateAuthToken('esbgpabatchstatus'); if (!$tokenResponse || empty($tokenResponse['data']['access_token'])) { log_message('error', 'ICICI - Token generation failed for batch status: ' . json_encode($tokenResponse, JSON_PRETTY_PRINT)); $updateBatchFileStatus('failed-8'); return [ 'status' => false, 'message' => 'Token generation failed.', 'data' => $tokenResponse ]; } $token = $tokenResponse['data']['access_token']; log_message('error', 'ICICI - Token generated for batch status.'); $url = env('ICICI_BASE_URL') . '/batchstatus'; $headers = [ 'Authorization: Bearer ' . $token, 'Content-Type: application/json' ]; $db = \Config\Database::connect(); // Fetch all pending / in-process batches for ICICI $query = $db->table('batch_files bf') ->select('bf.id, bf.client_policy_id, bf.icici_batch_id, bf.icici_correlation_id, cp.policy_no') ->join('client_policy cp', 'cp.id = bf.client_policy_id') ->where('bf.is_active', 1) ->whereIn('bf.icici_status_flag', ['PENDING', 'IN_PROCESS']) ->where('bf.icici_batch_id IS NOT NULL'); if (!empty($clientPolicyId)) { $query->where('bf.client_policy_id', (int) $clientPolicyId); } $batches = $query->get()->getResultArray(); log_message('error', 'ICICI - Fetched pending batches count: ' . count($batches)); if (empty($batches)) { log_message('error', 'ICICI - No pending ICICI GPA batches found.'); $updateBatchFileStatus('success'); return [ 'status' => true, 'message' => 'No pending ICICI GPA batches found.', 'data' => [], ]; } $batchModel = new BatchFileModel(); $results = []; foreach ($batches as $batch) { $body = [ 'PolicyNumber' => $batch['policy_no'], 'BatchId' => $batch['icici_batch_id'], 'CorrelationId' => $batch['icici_correlation_id'], ]; log_message('error', 'ICICI - Calling batchstatus API for batch_file_id: ' . $batch['id'] . ', payload: ' . json_encode($body, JSON_PRETTY_PRINT)); $response = call_third_party_api($url, 'POST', $headers, $body, true); log_message('error', 'ICICI - batchstatus API response for batch_file_id: ' . $batch['id'] . ': ' . json_encode($response, JSON_PRETTY_PRINT)); $apiData = $response['data'] ?? []; $message = $apiData['message'] ?? null; $statusMessage = $apiData['statusMessage'] ?? null; $newStatusFlag = 'FAILED'; if (!empty($response['status']) && $response['status'] === true && $statusMessage === 'SUCCESS') { if ($message === 'Process Completed') { $newStatusFlag = 'COMPLETED'; } elseif ($message === 'In Process') { $newStatusFlag = 'IN_PROCESS'; } else { $newStatusFlag = 'PENDING'; } } $updateData = [ 'icici_status_flag' => $newStatusFlag, 'icici_status_message' => $message, 'icici_endorsement_policy_no' => $apiData['endorsementPolicyNo'] ?? null, ]; // If process completed successfully, UHID step becomes pending if ($newStatusFlag === 'COMPLETED') { $updateData['icici_uhid_status_flag'] = 'PENDING'; } $batchModel->update($batch['id'], $updateData); log_message('error', 'ICICI - Updated batch_files for id ' . $batch['id'] . ' with: ' . json_encode($updateData, JSON_PRETTY_PRINT)); // After COMPLETED, trigger UHID fetch internally (no extra imid param). // $uhidResult = null; // if ($newStatusFlag === 'COMPLETED') { // // Ensure we pass endorsement policy number to the internal UHID fetch helper. // $batch['icici_endorsement_policy_no'] = $updateData['icici_endorsement_policy_no'] ?? null; // log_message('error', 'ICICI - Triggering UHID fetch for batch_file_id: ' . $batch['id']); // $uhidResult = $this->fetchUhidAndUpdateEmployeePolicies($batch); // log_message('error', 'ICICI - UHID fetch result for batch_file_id ' . $batch['id'] . ': ' . json_encode($uhidResult, JSON_PRETTY_PRINT)); // } $results[] = [ 'batch_file_id' => $batch['id'], 'request' => $body, 'response' => $response, 'new_status' => $newStatusFlag, // 'uhid_fetch' => $uhidResult, ]; } // Push a job to fetch UHID details asynchronously if needed (keeps backward compatibility) $r = Jobs::addJob(['job_name' => 'fetchUHIDDetails', 'payload' => ['client_policy_id' => $clientPolicyId, 'file_id' => $fileId, 'return_type' => 'job']]); log_message('error', "ICICI - getEnrollmentBatchStatus job pushed for client_policy_id: {$clientPolicyId}, file_id: {$fileId}, job_result: " . json_encode($r, JSON_PRETTY_PRINT)); $updateBatchFileStatus('success'); return [ 'status' => true, 'message' => 'Batch status updated.', 'data' => $results, ]; } catch (\Throwable $th) { $errorData = [ 'message' => $th->getMessage(), 'file' => $th->getFile(), 'line' => $th->getLine(), 'code' => $th->getCode(), 'trace' => $th->getTraceAsString(), 'trace_array' => $th->getTrace(), ]; if (!empty($param['file_id'])) { $catchFileModel = new BatchFileModel(); $catchFileModel->where('id', $param['file_id'])->set('status', 'failed-8')->update(); log_message('error', "ICICI - getEnrollmentBatchStatus | batch_files.status updated in catch for file_id {$param['file_id']} => failed-8"); } log_message('error', 'ICICI - Exception in getEnrollmentBatchStatus: ' . json_encode($errorData, JSON_PRETTY_PRINT)); $updateBatchFileStatus('failed-8'); return [ 'status' => false, 'message' => 'Batch status updated failed.', 'data' => $errorData, ]; } } public function fetchUHIDDetails($param) { helper('api'); try { log_message('error', 'ICICI - fetchUHIDDetails started with params: ' . json_encode($param, JSON_PRETTY_PRINT)); $policy_id = $param['client_policy_id']; $fileId = $param['file_id']; $imid = $param['imid'] ?? null; // optional; if omitted we derive from icici_batch_id $fileModel = new BatchFileModel(); $updateBatchFileStatus = function (string $status) use ($fileId, $fileModel) { if (empty($fileId)) { log_message('error', 'ICICI - fetchUHIDDetails | file_id missing, skipped batch_files.status update.'); return; } $fileModel->where('id', $fileId)->set('status', $status)->update(); log_message('error', "ICICI - fetchUHIDDetails | batch_files.status updated for file_id {$fileId} => {$status}"); }; if (empty($policy_id)) { log_message('error', 'ICICI - fetchUHIDDetails failed: client_policy_id is required. Params: ' . json_encode($param, JSON_PRETTY_PRINT)); $updateBatchFileStatus('failed-8'); return [ 'status' => false, 'message' => 'client_policy_id is required.', 'data' => [], ]; } $batchModel = new BatchFileModel(); $batch = $batchModel ->where('client_policy_id', $policy_id) ->where('is_active', 1) ->where('icici_status_flag', 'COMPLETED') ->whereIn('icici_uhid_status_flag', ['PENDING', 'FAILED']) ->orderBy('id', 'DESC') ->first(); if (empty($batch)) { log_message('error', "ICICI - No completed ICICI GPA batch found for UHID fetch. client_policy_id: {$policy_id}"); $updateBatchFileStatus('failed-8'); return [ 'status' => false, 'message' => 'No completed ICICI GPA batch found for UHID fetch.', 'data' => [], ]; } log_message('error', 'ICICI - fetchUHIDDetails found batch: ' . json_encode($batch, JSON_PRETTY_PRINT)); log_message('error', 'ICICI - Triggering fetchUhidAndUpdateEmployeePolicies for batch_id: ' . $batch['id'] . ', imid: ' . var_export($imid, true)); $uhidResult = $this->fetchUhidAndUpdateEmployeePolicies($batch, $imid, $fileId); log_message('error', 'ICICI - fetchUhidAndUpdateEmployeePolicies result for batch_id ' . $batch['id'] . ': ' . json_encode($uhidResult, JSON_PRETTY_PRINT)); $updateBatchFileStatus('success'); return [ 'status' => true, 'message' => 'UHID details fetched.', 'data' => [ 'batch_file_id' => $batch['id'], 'request' => $uhidResult['request'] ?? [], 'response' => $uhidResult['response'] ?? [], 'new_status' => $uhidResult['new_status'] ?? 'FAILED', 'uhid_updated_count' => $uhidResult['updatedCount'] ?? 0, ], ]; } catch (\Throwable $th) { $errorData = [ 'message' => $th->getMessage(), 'file' => $th->getFile(), 'line' => $th->getLine(), 'code' => $th->getCode(), 'trace' => $th->getTraceAsString(), 'trace_array' => $th->getTrace(), ]; if (!empty($param['file_id'])) { $catchFileModel = new BatchFileModel(); $catchFileModel->where('id', $param['file_id'])->set('status', 'failed-8')->update(); log_message('error', "ICICI - fetchUHIDDetails | batch_files.status updated in catch for file_id {$param['file_id']} => failed-8"); } log_message('error', 'ICICI - Exception in fetchUHIDDetails: ' . json_encode($errorData, JSON_PRETTY_PRINT)); return [ 'status' => false, 'message' => 'UHID details fetched failed.', 'data' => $errorData, ]; } } public function formatPolicyData($data, $flagStatus = "A") { // Helper to format date as DD-MMM-YYYY (e.g. 7-JUL-1993) $formatDate = function ($date) { if (empty($date)) { return null; } $timestamp = strtotime($date); if ($timestamp === false) { return null; } return strtoupper(date('j-M-Y', $timestamp)); }; // Generate UUID v4 for CorrelationId $generateUUID = function () { return sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x', mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0x0fff) | 0x4000, mt_rand(0, 0x3fff) | 0x8000, mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff) ); }; $mapGender = function ($gender) { $normalized = strtoupper(trim((string) $gender)); if ($normalized === 'M' || $normalized === 'MALE') { return 'MALE'; } if ($normalized === 'F' || $normalized === 'FEMALE') { return 'FEMALE'; } return $normalized; }; // Map MemberDetails in ICICI expected request format $memberDetails = []; foreach ($data as $row) { if (empty($row['MemberEmpId']) || empty($row['InsuredName']) || empty($row['DOB']) || empty($row['DOC'])) { continue; } $memberDetails[] = [ "EmployeeMemberId" => preg_replace('/[^A-Za-z0-9]/', '', (string) $row['MemberEmpId']), "DOJ" => $formatDate($row['DOJ']), "InsuredName" => $row['InsuredName'], "DOB" => $formatDate($row['DOB']), "Relationship" => strtoupper((string) $row['Relationship']), "Gender" => $mapGender($row['Gender'] ?? ''), "DOC" => $formatDate($row['DOC']), "DOL" => isset($row['DOL']) ? $formatDate($row['DOL']) : null, "SumInsured" => $row['SumInsured'], "EmailId" => $row['EmailId'], "FlagStatus" => $flagStatus ]; } // Final body return [ "PolicyNumber" => $data[0]['policyNumber'] ?? null, "CDBGAccountNumber" => $data[0]['CDBGAccountNumber'] ?? null, "CorrelationId" => $generateUUID(), "MemberDetails" => $memberDetails ]; } private function formatPolicyDataForDeletion($data, $policy_id) { $client_policy_data = db_connect()->table('client_policy') ->select('cp.policy_no as policyNumber, cdm.cd_ac_no as CDBGAccountNumber') ->join('cd_master cdm', 'client_policy.cd_ac_pk = cdm.id') ->where('client_policy.id', $policy_id) ->get() ->getRowArray(); $formattedData = []; foreach ($data as $key => $value) { $formattedData[] = [ 'policyNumber' => $client_policy_data['policyNumber'] ?? null, 'CDBGAccountNumber' => $client_policy_data['CDBGAccountNumber'] ?? null, 'MemberEmpId' => $value['emp_code'] ?? null, 'DOJ' => change_date_format($value['emp_doj']) ?? null, 'InsuredName' => $value['emp_name'] ?? null, 'DOB' => change_date_format($value['emp_dob']) ?? null, 'Relationship' => $value['emp_relationship'] ?? null, 'Gender' => $value['emp_gender'] ?? null, 'DOC' => $value['date_coverage'] ?? null, 'DOL' => $value['dateofexit'] ?? null, 'SumInsured' => $value['basic_cover_si'] ?? null, 'EmailId' => $value['emp_email_c'] ?? null, ]; } return $formattedData; } private function formatPolicyDataForCorrection($data, $policy_id) { $client_policy_data = db_connect()->table('client_policy') ->select('cp.policy_no as policyNumber, cdm.cd_ac_no as CDBGAccountNumber') ->join('cd_master cdm', 'client_policy.cd_ac_pk = cdm.id') ->where('client_policy.id', $policy_id) ->get() ->getRowArray(); $formattedData = []; foreach ($data as $key => $value) { $formattedData[] = [ 'policyNumber' => $client_policy_data['policyNumber'] ?? null, 'CDBGAccountNumber' => $client_policy_data['CDBGAccountNumber'] ?? null, 'MemberEmpId' => $value['emp_code'] ?? null, 'DOJ' => change_date_format($value['emp_doj']) ?? null, 'InsuredName' => $value['field_name'] == 'name' ? $value['new_value'] : $value['emp_name'] ?? null, 'DOB' => change_date_format($value['field_name'] == 'dob' ? $value['new_value'] : $value['emp_dob'] ?? null) ?? null, 'Relationship' => $value['emp_relationship'] ?? null, 'Gender' => $value['emp_gender'] ?? null, 'DOC' => $value['date_coverage'] ?? null, 'SumInsured' => $value['basic_cover_si'] ?? null, 'EmailId' => $value['field_name'] == 'email_corporate' ? $value['new_value'] : $value['emp_email_c'] ?? null, ]; } return $formattedData; } private function formatPolicyDataForSIEnhancement($data, $policy_id) { $client_policy_data = db_connect()->table('client_policy') ->select('cp.policy_no as policyNumber, cdm.cd_ac_no as CDBGAccountNumber') ->join('cd_master cdm', 'client_policy.cd_ac_pk = cdm.id') ->where('client_policy.id', $policy_id) ->get() ->getRowArray(); $formattedData = []; foreach ($data as $key => $value) { $formattedData[] = [ 'policyNumber' => $client_policy_data['policyNumber'] ?? null, 'CDBGAccountNumber' => $client_policy_data['CDBGAccountNumber'] ?? null, 'MemberEmpId' => $value['emp_code'] ?? null, 'DOJ' => $value['emp_doj'] ?? null, 'InsuredName' => $value['emp_name'] ?? null, 'DOB' => $value['emp_dob'] ?? null, 'Relationship' => $value['emp_relationship'] ?? null, 'Gender' => $value['emp_gender'] ?? null, 'DOC' => $value['date_of_coverage'] ?? null, 'SumInsured' => $value['new_basic_cover_si'] ?? null, 'EmailId' => $value['emp_email_c'] ?? null, ]; } return $formattedData; } private function updateAdditionData($employee_id, $clientPolicyId, $uhid) { $db = \Config\Database::connect(); $db->table('employee_polices') ->where('employee_id', $employee_id) ->where('client_policy_id', $clientPolicyId) ->set('tpa_id', $uhid) ->update(); return true; } private function updateDeletionData($employee_id, $clientPolicyId, $uhid, $endorsement_no) { $db = \Config\Database::connect(); if(empty($endorsement_no)){ return null; } // Get policy row (single) $policy_data = $db->table('employee_polices') ->where('employee_id', $employee_id) ->where('client_policy_id', $clientPolicyId) ->where('tpa_id', $uhid) ->get() ->getRowArray(); // Get endorsement data $endorsment_data = $db->table('emp_endorsement') ->where('table_name', 'employee_polices') ->where('pk', $policy_data['id'] ?? 0) ->where('status !=', 'truncated') ->where('endorsement_no IS NULL', null, false) ->where('is_active', 1) ->where('actions', 'd') ->get() ->getResultArray(); if (empty($endorsment_data)) { return null; } $result = []; $group_keys = []; foreach ($endorsment_data as $row) { if (!empty($row['group_key'])) { $group_keys[] = $row['group_key']; } if (isset($row['field_name']) && isset($row['new_value'])) { $result[$row['field_name']] = $row['new_value']; } } // Remove duplicate group keys $group_keys = array_unique($group_keys); // Update endorsement table if (!empty($group_keys)) { $db->table('emp_endorsement') ->whereIn('group_key', $group_keys) ->set('endorsement_no', $endorsement_no) ->update(); } // Update employee_polices table if (!empty($result)) { $db->table('employee_polices') ->where('employee_id', $employee_id) ->where('client_policy_id', $clientPolicyId) ->where('tpa_id', $uhid) ->set($result) ->update(); } return $policy_data['id'] ?? null; } private function updateModificationData($employee, $endorsement_no, $member, $file_data) { $db = \Config\Database::connect(); if (empty($employee)) { return null; } if (empty($members)) { return null; } if (empty($endorsement_no)) { return null; } // update only CORRECTION data if ($file_data['action'] == 'correction') { $endorsment_data = $db->table('emp_endorsement') ->where('table_name', 'employees') ->where('pk', $employee['id'] ?? 0) ->where('emp_code', $employee['emp_code'] ?? '') ->where('status !=', 'truncated') ->where('endorsement_no IS NULL', null, false) ->where('is_active', 1) ->where('actions', 'c') ->get() ->getResultArray(); $result = []; $group_keys = []; foreach ($endorsment_data as $row) { if (!empty($row['group_key'])) { $group_keys[] = $row['group_key']; } if (isset($row['field_name']) && isset($row['new_value'])) { $result[$row['field_name']] = $row['new_value']; } } // Remove duplicate group keys $group_keys = array_unique($group_keys); // Update endorsement table if (!empty($group_keys)) { $db->table('emp_endorsement') ->whereIn('group_key', $group_keys) ->set('endorsement_no', $endorsement_no) ->update(); } // Update endorsement table if (!empty($result)) { $db->table('employees') ->where('id', $employee['id'] ?? 0) ->set($result) ->update(); } } // update only SI ENHANCEMENT data if ($file_data['action'] == 'si_enhancement') { // Get policy row (single) $policy_data = $db->table('employee_polices') ->where('employee_id', $employee['id'] ?? 0) ->where('client_policy_id', $file_data['client_policy_id'] ?? 0) ->where('tpa_id', $member['uhid'] ?? '') ->get() ->getRowArray(); // Get endorsement data $endorsment_data = $db->table('emp_endorsement') ->where('table_name', 'employee_polices') ->where('pk', $policy_data['id'] ?? 0) ->where('status !=', 'truncated') ->where('endorsement_no IS NULL', null, false) ->where('is_active', 1) ->where('actions', 'si') ->get() ->getResultArray(); if (empty($endorsment_data)) { return null; } $result = []; $group_keys = []; $old_result = []; foreach ($endorsment_data as $row) { if (!empty($row['group_key'])) { $group_keys[] = $row['group_key']; } if (isset($row['field_name']) && isset($row['new_value'])) { $result[$row['field_name']] = $row['new_value']; $old_result[$row['field_name']] = $row['old_value']; } } $si_adjustment = ($old_result['basic_cover_si'] < $result['basic_cover_si']) ? 1 : 2; $insertedIds = [ 'pk' => $endorsment_data['pk'], 'si_adjustment' => $si_adjustment ]; // Remove duplicate group keys $group_keys = array_unique($group_keys); // Update endorsement table if (!empty($group_keys)) { $db->table('emp_endorsement') ->whereIn('group_key', $group_keys) ->set('endorsement_no', $endorsement_no) ->update(); } // Update employee_polices table if (!empty($result)) { $db->table('employee_polices') ->where('employee_id', $employee['id'] ?? 0) ->where('client_policy_id', $file_data['client_policy_id'] ?? 0) ->where('tpa_id', $member['uhid'] ?? '') ->set($result) ->update(); } return $insertedIds ?? null; } } public function saveICICILombardAPIData($array) { $file_id = $array['file_id']; $json = file_get_contents($array['json_file_path']); $records = json_decode($json, true); // log_message('error','MEDI_ASSIST - 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['employeeMemberId'] ?? ''), 'name' => trim($row['insuredName'] ?? ''), 'dob' => !empty($row['DOB']) ? date('Y-m-d', strtotime(str_replace('/', '-', $row['DOB']))) : null, 'relation' => trim($row['Relationship'] ?? null), 'gender' => strtoupper($row['Gender'] ?? null), 'self' => strtolower($row['Relationship'] ?? '') === 'self' ? 1 : 0, 'si' => $row['SumInsured'] ?? null, 'doj' => isset($row['DOC']) ? date('Y-m-d', strtotime(str_replace('/', '-', $row['DOC']))) : null, 'tpa_id' => trim($row['uhid'] ?? null), 'age' => null, 'is_active' => 1, 'created_by' => $file_info[0]['created_by'] ?? null, 'endorsement_no' => trim($row['endorsementNumber'] ?? null), 'action_flag_status' => trim($row['flagStatus'] ?? null), ]; } // log_message('error','MEDI_ASSIST - 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 } // ------------------------------------------------------------------------------------------------------------- // For testing purpose only - to trigger batch creation API with sample data without going through the entire flow of file upload and processing. This can be removed later. // ------------------------------------------------------------------------------------------------------------- public function createEnrollmentBatch() { $client_id = $this->request->getGet('client_id'); $client_branch_id = $this->request->getGet('client_branch_id'); $policy_id = $this->request->getGet('policy_id'); $event = $this->request->getGet('event'); //fetch token $tokenResponse = $this->generateAuthToken(); if (!$tokenResponse || empty($tokenResponse['data']['access_token'])) { return $this->response->setJSON([ 'status' => false, 'message' => 'Token generation failed.', 'data' => $tokenResponse ]); } $token = $tokenResponse['data']['access_token']; $url = env('ICICI_BASE_URL').'/batchcreation'; $headers = [ 'Authorization: Bearer ' . $token, 'Content-Type: application/json', ]; //Prepare body data // $db = \Config\Database::connect(); // $data = $db->table('employee_polices ep') // ->select('cp.policy_no as policyNumber, cp.cd_ac_no as CDBGAccountNumber, // e.id,e.emp_code as MemberEmpId, e.doj as DOJ, e.name as InsuredName, e.dob as DOB, e.relationship as Relationship, // e.gender as Gender, ep.date_coverage as DOC,ep.basic_cover_si as SumInsured, e.email_corporate as EmailId // ') // ->join('employees e', 'e.id = ep.employee_id') // ->join('client_policy cp', 'ep.client_policy_id = cp.id') // ->where('ep.client_policy_id', $policy_id) // ->where('ep.status', 'active') // ->where('ep.is_active', 1) // // ->where('ep.uhid', null) // ->get() // ->getResultArray(); // $body = $this->formatPolicyData($data); // dd($body); // $body = [ // "PolicyNumber" => "4016/PPN/A/O/53167743/00/000", // "CDBGAccountNumber" => "CD-MUM-0026", // "CorrelationId" => "550e8400-e29b-41d4-a716-446655440016", // "MemberDetails" => [ // [ // "MemberEmpId" => "EMPID3625562", // "DOJ" => "21-MAR-2019", // "InsuredName" => "Jeeva", // "DOB" => "7-JUL-1993", // "Relationship" => "SELF", // "Gender" => "MALE", // "DOC" => '28-Oct-2025', // "SumInsured" => "500000", // "EmailId" => "Jeeva@GMAIL.COM", // "FlagStatus" => "A" // ], // [ // "MemberEmpId" => "EMPID3625562", // "DOJ" => "21-MAR-2019", // "InsuredName" => "Muthu", // "DOB" => "8-AUG-1970", // "Relationship" => "MOTHER", // "Gender" => "FEMALE", // "DOC" => '28-Oct-2025', // "EmailId" => "Muthu@GMAIL.COM", // "FlagStatus" => "A" // ], // ] // ]; $body = [ "PolicyNumber" => "4016/PPN/A/O/53185987/00/000", "CDBGAccountNumber" => "CD-MUM-0026", "CorrelationId" => "550e8400-e29b-41d4-a716-446655440026", "MemberDetails" => [ [ "MemberEmpId" => "EMPID3625567", "DOJ" => "21-MAR-2019", "InsuredName" => "sanjeev", "DOB" => "7-JUL-1993", "Relationship" => "SELF", "Gender" => "MALE", "DOC" => '10-Mar-2026', "SumInsured" => "500000", "EmailId" => "sanjeev@GMAIL.COM", "FlagStatus" => "A" ], [ "MemberEmpId" => "EMPID3625567", "DOJ" => "21-MAR-2019", "InsuredName" => "bhavya", "DOB" => "8-AUG-1970", "Relationship" => "MOTHER", "Gender" => "FEMALE", "DOC" => '10-Mar-2026', "EmailId" => "bhavya@GMAIL.COM", "FlagStatus" => "A" ], ] ]; $response = call_third_party_api($url, 'POST', $headers, $body, true); // true = raw body mode // print_rr(json_encode($response));die(); return $this->response->setJSON(['API'=>$url,'headers'=>$headers,'body'=>$body,'response'=>$response]); } public function getEnrollmentBatchStatusOld() { helper('api'); //fetch token $tokenResponse = $this->generateAuthToken(); if (!$tokenResponse || empty($tokenResponse['data']['access_token'])) { return $this->response->setJSON([ 'status' => false, 'message' => 'Token generation failed.', 'data' => $tokenResponse ]); } $token = $tokenResponse['data']['access_token']; $url = env('ICICI_BASE_URL').'/batchstatus'; $headers = [ 'Authorization: Bearer ' . $token, 'Content-Type: application/json' ]; // dd($headers); $body = [ "PolicyNumber" => "4016/PPN/A/O/53185987/00/000", "BatchId" => "3746145", "CorrelationId" => "550e8400-e29b-41d4-a716-446655440026" ]; $response = call_third_party_api($url, 'POST', $headers, $body, true); return $this->response->setJSON(['API'=>$url,'headers'=>$headers,'body'=>$body,'response'=>$response]); } public function fetchUHIDDetailsOld() { helper('api'); //fetch token $tokenResponse = $this->generateAuthToken('esbgpauhid'); // dd($tokenResponse); if (!$tokenResponse || empty($tokenResponse['data']['access_token'])) { return $this->response->setJSON([ 'status' => false, 'message' => 'Token generation failed.', 'data' => $tokenResponse ]); } $token = $tokenResponse['data']['access_token']; // print_rr($token); $url = env('ICICI_BASE_URL').'/fetchuhid'; $headers = [ 'Authorization: Bearer ' . $token, 'Content-Type: application/json' ]; $body = [ "PolicyNumber" => "4016/PPN/A/O/53185987/00/001", "IMID" => "201580517901", "CorrelationId" => "550e8400-e29b-41d4-a716-446655440022" ]; $response = call_third_party_api($url, 'POST', $headers, $body, true); // dd($response); return $this->response->setJSON(['API'=>$url,'headers'=>$headers,'body'=>$body,'response'=>$response]); } // data": { // "policyNumber": "4016/PPN/A/O/53185987/00/000", // "batchId": "3746144", // "message": "Data Dumped Successfully", // "status": true, // "statusMessage": "SUCCESS", // "correlationId": "550e8400-e29b-41d4-a716-446655440025" // }, // "data": { // "policyNumber": "4016/PPN/A/O/53185987/00/000", // "batchId": "3746145", // "message": "Data Dumped Successfully", // "status": true, // "statusMessage": "SUCCESS", // "correlationId": "550e8400-e29b-41d4-a716-446655440026" // }, // $body = [ // "PolicyNumber" => "4016/A/O/53077718/00/000", // "CDBGAccountNumber" => "CD-MUM-0026", // "CorrelationId" => "550e8400-e29b-41d4-a716-446655440001", // "MemberDetails" => [ // [ // "MemberEmpId" => "EMPID3625557", // "DOJ" => "21-MAR-2019", // "InsuredName" => "Kumar", // "DOB" => "7-JUL-1983", // "Relationship" => "SELF", // "Gender" => "MALE", // "DOC" => "08-JUL-2025", // "SumInsured" => "400000", // "EmailId" => "KUMAR@GMAIL.COM", // "FlagStatus" => "A" // ], // [ // "MemberEmpId" => "EMPID3625557", // "DOJ" => "21-MAR-2019", // "InsuredName" => "Saranya", // "DOB" => "8-AUG-1970", // "Relationship" => "MOTHER", // "Gender" => "FEMALE", // "DOC" => "08-JUL-2025", // "SumInsured" => "400000", // "EmailId" => "Saranya@GMAIL.COM", // "FlagStatus" => "A" // ], // ] // ]; }