diff --git a/app/Config/Routes.php b/app/Config/Routes.php index fd1f09ca..a3a3f7ec 100755 --- a/app/Config/Routes.php +++ b/app/Config/Routes.php @@ -650,6 +650,8 @@ $routes->group("employeeRest", ["filter" => ["authJWT"]], function ($routes) { $routes->post('initiateClaim',"EmployeeRestController::initiateClaim"); $routes->get('get_ticket_type',"EmployeeRestController::get_ticket_type"); $routes->get('get_ticket_data',"EmployeeRestController::get_ticket_data"); + $routes->get('getClaimTypeMaster',"EmployeeRestController::getClaimTypeMaster"); + $routes->post('uploadIRDocs',"EmployeeRestController::uploadIRDocs"); // add retail policy $routes->post("addEmpRetailPolicy", "EmployeeRestController::addEmpRetailPolicy"); @@ -710,7 +712,8 @@ $routes->group("/ticket", ["filter" => "authMVC"], function ($routes) { $routes->post('getUrlDataByTicketId',"TicketController::getUrlDataByTicketId"); $routes->get('remove_url',"TicketController::remove_url"); $routes->get('fetchVehiclePolicy/(:any)','TicketController::fetchVehiclePolicy/$1'); - + $routes->post('saveIRDocsJson',"TicketController::saveIRDocsJson"); + $routes->get('getTpaClaimStatus',"ApiServiceController::getClaimStatus"); }); $routes->group("clientApi",["filter" => "AuthClientApi"], function ($routes){ diff --git a/app/Controllers/ApiServiceController.php b/app/Controllers/ApiServiceController.php index ac6cb0dd..e2d1c5d7 100644 --- a/app/Controllers/ApiServiceController.php +++ b/app/Controllers/ApiServiceController.php @@ -219,6 +219,59 @@ class ApiServiceController extends BaseController } } + // get Claim details + public function getClaimStatus() + { + + $claimId = $this->request->getGet('claim_id'); + + $data = $this->db->table('ticket_master tm') + ->select('tm.id,tm.tpa_id ')->where('tm.id', $claimId)->get()->getRowArray(); // single record + + if($data){ + + $tpaID = $data['tpa_id']; + + if ($tpaID == $this->medi_assist_primary_key) { // MediAssist + $mediAssistController = new MediAssistApiController(); + return $mediAssistController->ClaimDetail($claimId); + }else{ + log_message('error', "This ticket id ( {$claimId} ) TPA has no API service enabled. TPA ID : {$tpaID}"); + $message = "This TPA has no API service enabled"; + return $this->response->setJSON(['status' => false,'message' => $message ]); + } + + } + + + } + + // push Claim Files (IR submission) + public function pushClaimFiles($claimId) + { + + // $claimId = $this->request->getGet('claim_id'); + + $data = $this->db->table('ticket_master tm') + ->select('tm.id,tm.tpa_id ')->where('tm.id', $claimId)->get()->getRowArray(); // single record + + if($data){ + + $tpaID = $data['tpa_id']; + + if ($tpaID == $this->medi_assist_primary_key) { // MediAssist + $mediAssistController = new MediAssistApiController(); + return $mediAssistController->IRSubmission($claimId); + }else{ + log_message('error', "This ticket id ( {$claimId} ) TPA has no API service enabled. TPA ID : {$tpaID}"); + } + + } + + + } + + public function getWellnessUrl() { @@ -314,24 +367,25 @@ class ApiServiceController extends BaseController } } - - - - function getSSORedirectUrl($email = 'user@example.com') + function getSSORedirectUrl($email = 'test@getvisitapp.com') { + log_message('info', "SSO: Starting authentication for email: $email"); + // ---------- CONFIG ---------- - $authUrl = env('VIDAL_WELLNESS_BASE_URL'); // Authentication API URL + $authUrl = env('VIDAL_WELLNESS_BASE_URL'); $subscriptionKey = env('VIDAL_WELLNESS_SUBSCRIPTION_KEY'); $apiVersion = "1"; // Provided Base64 AES key $base64Key = env('VIDAL_WELLNESS_BASE64_KEY'); $key = base64_decode($base64Key); + + log_message('info', "SSO: Config loaded, Auth URL: $authUrl"); // ---------- STEP 1: Build plaintext payload ---------- $plainPayload = json_encode([ "email" => $email, - "corporateId" => env('VIDAL_WELLNESS_CORPORATE_ID'), + // "corporateId" => env('VIDAL_WELLNESS_CORPORATE_ID'), "urlIdentifier" => env('VIDAL_WELLNESS_URL_IDENTIFIER') ]); @@ -340,11 +394,13 @@ class ApiServiceController extends BaseController $encryptedRaw = openssl_encrypt($plainPayload, "AES-256-CBC", $key, OPENSSL_RAW_DATA, $iv); $encryptedPayload = base64_encode($iv) . ":" . base64_encode($encryptedRaw); + + log_message('info', "SSO: Payload encrypted successfully"); // ---------- STEP 3: Call Authentication API ---------- $requestBody = json_encode([ "payload" => $encryptedPayload, - "source" => "portal", + "source" => env('VIDAL_WELLNESS_SUB_PARTNER_ID'), "subPartnerId" => env('VIDAL_WELLNESS_SUB_PARTNER_ID') ]); @@ -362,38 +418,168 @@ class ApiServiceController extends BaseController curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $apiResponse = curl_exec($ch); + $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); + $curlError = curl_error($ch); curl_close($ch); + + log_message('info', "SSO: API response received, HTTP Code: $httpCode"); + + // Check for cURL errors + if ($curlError) { + log_message('error', "SSO: cURL error - $curlError"); + return ["error" => "cURL error: $curlError"]; + } + + // Check HTTP status + if ($httpCode !== 200) { + log_message('error', "SSO: HTTP error - Code: $httpCode, Response: $apiResponse"); + return ["error" => "HTTP error: $httpCode", "response" => $apiResponse]; + } $jsonResponse = json_decode($apiResponse, true); - dd($jsonResponse); - - if (!isset($jsonResponse["data"])) { - return ["error" => "Invalid API response", "response" => $apiResponse]; + // Check JSON decode error + if (json_last_error() !== JSON_ERROR_NONE) { + log_message('error', "SSO: JSON decode error - " . json_last_error_msg()); + return ["error" => "JSON decode error: " . json_last_error_msg(), "response" => $apiResponse]; } + // Check API response status + if (!isset($jsonResponse["status"]) || $jsonResponse["status"] !== "success") { + log_message('error', "SSO: API error - " . json_encode($jsonResponse)); + return ["error" => "API error", "response" => $jsonResponse]; + } + if (!isset($jsonResponse["data"])) { + log_message('error', "SSO: Missing data field in response"); + return ["error" => "Invalid API response - missing data field", "response" => $jsonResponse]; + } + + log_message('info', "SSO: API response validated successfully"); // ---------- STEP 4: Decrypt response ---------- - list($ivBase64, $cipherBase64) = explode(":", $jsonResponse["data"]); + log_message('info', "SSO: Starting response decryption"); + + $dataParts = explode(":", $jsonResponse["data"]); + + if (count($dataParts) !== 2) { + log_message('error', "SSO: Invalid encrypted data format"); + return ["error" => "Invalid encrypted data format", "data" => $jsonResponse["data"]]; + } + + list($ivBase64, $cipherBase64) = $dataParts; $respIv = base64_decode($ivBase64); $respCipher = base64_decode($cipherBase64); + if ($respIv === false || $respCipher === false) { + log_message('error', "SSO: Base64 decode error"); + return ["error" => "Base64 decode error"]; + } + $decryptedJson = openssl_decrypt($respCipher, "AES-256-CBC", $key, OPENSSL_RAW_DATA, $respIv); + if ($decryptedJson === false) { + log_message('error', "SSO: Decryption failed"); + return ["error" => "Decryption failed"]; + } + $decryptedData = json_decode($decryptedJson, true); + if (json_last_error() !== JSON_ERROR_NONE) { + log_message('error', "SSO: Decrypted JSON decode error - " . json_last_error_msg()); + return ["error" => "Decrypted JSON decode error: " . json_last_error_msg()]; + } + if (!isset($decryptedData["redirectUrl"])) { + log_message('error', "SSO: redirectUrl missing in decrypted data"); return ["error" => "redirectUrl missing", "decrypted" => $decryptedData]; } // ---------- FINAL ---------- + log_message('info', "SSO: Authentication successful, redirectUrl obtained"); return $decryptedData["redirectUrl"]; } + // function getSSORedirectUrl($email = 'user@example.com') + // { + // // ---------- CONFIG ---------- + // $authUrl = env('VIDAL_WELLNESS_BASE_URL'); // Authentication API URL + // $subscriptionKey = env('VIDAL_WELLNESS_SUBSCRIPTION_KEY'); + // $apiVersion = "1"; + + // // Provided Base64 AES key + // $base64Key = env('VIDAL_WELLNESS_BASE64_KEY'); + // $key = base64_decode($base64Key); + + // // ---------- STEP 1: Build plaintext payload ---------- + // $plainPayload = json_encode([ + // "email" => $email, + // "corporateId" => env('VIDAL_WELLNESS_CORPORATE_ID'), + // "urlIdentifier" => env('VIDAL_WELLNESS_URL_IDENTIFIER') + // ]); + + // // ---------- STEP 2: Encrypt payload ---------- + // $iv = random_bytes(16); + // $encryptedRaw = openssl_encrypt($plainPayload, "AES-256-CBC", $key, OPENSSL_RAW_DATA, $iv); + + // $encryptedPayload = base64_encode($iv) . ":" . base64_encode($encryptedRaw); + + // // ---------- STEP 3: Call Authentication API ---------- + // $requestBody = json_encode([ + // "payload" => $encryptedPayload, + // "source" => "portal", + // "subPartnerId" => env('VIDAL_WELLNESS_SUB_PARTNER_ID') + // ]); + + // $headers = [ + // "Ocp-Apim-Subscription-Key: $subscriptionKey", + // "apiver: $apiVersion", + // "mode: encrypt", + // "Content-Type: application/json" + // ]; + + // $ch = curl_init($authUrl); + // curl_setopt($ch, CURLOPT_POST, true); + // curl_setopt($ch, CURLOPT_POSTFIELDS, $requestBody); + // curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); + // curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + + // $apiResponse = curl_exec($ch); + // curl_close($ch); + + // $jsonResponse = json_decode($apiResponse, true); + + // dd($jsonResponse); + + // if (!isset($jsonResponse["data"])) { + // return ["error" => "Invalid API response", "response" => $apiResponse]; + // } + + + + // // ---------- STEP 4: Decrypt response ---------- + // list($ivBase64, $cipherBase64) = explode(":", $jsonResponse["data"]); + + // $respIv = base64_decode($ivBase64); + // $respCipher = base64_decode($cipherBase64); + + // $decryptedJson = openssl_decrypt($respCipher, "AES-256-CBC", $key, OPENSSL_RAW_DATA, $respIv); + + // $decryptedData = json_decode($decryptedJson, true); + + // if (!isset($decryptedData["redirectUrl"])) { + // return ["error" => "redirectUrl missing", "decrypted" => $decryptedData]; + // } + + // // ---------- FINAL ---------- + // return $decryptedData["redirectUrl"]; + // } + + + diff --git a/app/Controllers/EmployeeRestController.php b/app/Controllers/EmployeeRestController.php index 859b51d1..05944b51 100755 --- a/app/Controllers/EmployeeRestController.php +++ b/app/Controllers/EmployeeRestController.php @@ -57,6 +57,7 @@ use Illuminate\Http\Request; use App\Controllers\EmployeeServiceController; use App\Models\ClaimFilesModel; +use App\Models\PolicyTransactionModel; use App\Models\TicketMailTemplateModel; use App\Models\TpaApiSeviceModel; use Composer\Pcre\Preg; @@ -2584,6 +2585,8 @@ class EmployeeRestController extends AdminController $data['claims_data'] = $this->ticketMaster->getTicketDataByTicketID($ticket_id); $data['ticket_data'] = $ticketController->getMoreInfo($requestFrom = 'rest', $ticket_id); + $required_docs = $this->ticketMaster->select('required_docs')->where('id', $ticket_id)->first(); + $data['required_docs'] = json_decode($required_docs['required_docs'] ?? '{}', true) ?? []; // $ticketData = $data['ticket_data']; // $ticketHistory = $data['ticket_history']; // print_r($ticketHistory); die; @@ -2840,20 +2843,8 @@ class EmployeeRestController extends AdminController ]; $emp_reatail_policy_data = $this->getEmpRetailPolicy($retailUserData); - - $query = $this->clientModel - ->where('is_active', 1) - ->where('client_type', 2); - - if (!empty($receviedPayload['mobile_no'])) { - $query->where('phone', $receviedPayload['mobile_no']); - } else { - $query->where('email', $receviedPayload['email_id'] ?? null); - } - - $retailClientData = $query->first(); $wellness_data = ['status' => 'failed','message' => 'Coming soon........!']; - return $this->respond(['status' => 'success', 'code' => 200, 'data' => [], 'emp_name' => $retailClientData['client_name'] ?? "", 'pre_policy_count' => 0, 'retail_policy_data' => $emp_reatail_policy_data, 'wellness_data' => $wellness_data], 200); + return $this->respond(['status' => 'success', 'code' => 200, 'data' => [], 'emp_name' => $emp_reatail_policy_data[0]['insurerd_name'] ?? "", 'pre_policy_count' => 0, 'retail_policy_data' => $emp_reatail_policy_data, 'wellness_data' => $wellness_data], 200); } } @@ -3185,7 +3176,9 @@ class EmployeeRestController extends AdminController { try { - $img = $this->addImgModel->where('is_active', 1)->findAll(); + $client_id = $this->request->getGet('client_id'); + + $img = $this->addImgModel->where('is_active', 1)->where('client_id',$client_id)->findAll(); if (count($img) > 0) { $data = []; @@ -3538,8 +3531,14 @@ class EmployeeRestController extends AdminController $received_data = $this->request->getPost(); $this->myLogger->logme('error', 'API claim initiate Recevied Params :' . json_encode($received_data ?? [])); - $get_file_data = $this->request->getFiles('claim_docs'); + $get_file_data = $this->request->getFiles('claim_docs') ?? null; $get_docs_name = $this->request->getPost('claim_doc_names') ?? []; + $policy_transaction_id = $this->request->getPost('policy_transaction_id') ?? null; + + if(!empty($policy_transaction_id)){ + $response = $this->retailClaimInitiate($received_data); + return $this->respond($response, 200); + } if (is_string($get_docs_name)) { $decoded = json_decode($get_docs_name, true); @@ -3694,7 +3693,64 @@ class EmployeeRestController extends AdminController } } - public function handleCliamFiles($data, $ticket_id, $ticket_message_id = null) + public function retailClaimInitiate($data) + { + if(isset($data['policy_transaction_id'])){ + + $policy_transaction_model = new PolicyTransactionModel(); + + $policy = $policy_transaction_model + ->select('policy_transaction.*, clients.client_name, clients.phone as client_mobile, clients.email as client_email') + ->join('clients', 'policy_transaction.client_id = clients.id') + ->where('policy_transaction.is_active',1) + ->where('clients.is_active',1) + ->where('policy_transaction.id', $data['policy_transaction_id']) + ->first(); + + if(!empty($policy)){ + + $claimData = [ + 'ticket_type_id' => $data['policy_type_id'], + 'policy_transaction_id' => $data['policy_transaction_id'], + 'claim_status_id' => 62, + 'policy_no' => $policy['policy_no'], + 'client_policy_id' => $policy['client_policy_id'], + 'insurer_id' => $policy['insurer_id'], + 'client_id' => $policy['client_id'] ?? null, + 'agent_id' => $policy['agent_id'] ?? null, + 'manager_id' => $policy['manager_id'] ?? null, + 'vehicle_id' => $policy['vehicle_id'] ?? null, + 'insured_name' => $policy['client_name'] ?? null, + 'emp_name' => $policy['client_name'] ?? null, + 'emp_mobile' => $policy['client_mobile'] ?? null, + 'emp_mail' => $policy['client_email'] ?? null, + 'emp_personal_mail'=> $policy['client_email'] ?? null, + 'claim_type' => $data['claim_type'], + 'claim_description'=> $data['claim_description'], + 'created_by' => $policy['client_id'] ?? null, + ]; + + $ticket_id = $this->ticketMaster->insert($claimData); + + if($ticket_id){ + $message = 'Claim Initiated Successfully'; + return ['status' => true, 'code' => 200, 'data' => $ticket_id, 'message' => $message]; + }else{ + $message = 'Claim Initiation failed'; + return ['status' => false, 'code' => 404, 'message' => $message]; + } + }else{ + $message = 'Claim Initiation failed. Policy data not found'; + return ['status' => false, 'code' => 404, 'message' => $message]; + } + }else{ + $message = 'Claim Initiation failed'; + return ['status' => false, 'code' => 404, 'message' => $message]; + + } + } + + public function handleCliamFiles($data, $ticket_id, $ticket_message_id = null, $tpa_claim_push = true, $ir_docs = false) { if (!empty($data) && !empty($ticket_id)) { $insert_ids = []; @@ -3712,6 +3768,10 @@ class EmployeeRestController extends AdminController 'mime_type' => getMimeTypeByFileName($value['file_name']), ]; + if($ir_docs == true){ + $data['docs_for_ir'] = 1; + } + $insert_ids[] = $claim_file->insert($data); if (getMimeTypeByFileName($value['file_name']) == "application/pdf") { @@ -3719,16 +3779,19 @@ class EmployeeRestController extends AdminController } } - if ($pdf_exist_in_the_file) { + if ($pdf_exist_in_the_file && $tpa_claim_push == true) { // this call for TPA integration $apiServiceController = new ApiServiceController(); $apiServiceController->pushClaims($ticket_id); log_message('error', "pushClaims function called with Ticket ID: {$ticket_id}, In Employee Rest Controller"); } else { - log_message('error', "Failed to call the pushClaims function in EmployeeRestController for Ticket ID: {$ticket_id}, because the .pdf file does not exist."); + if($tpa_claim_push == false){ + log_message('error', 'Skip the TPA claim push'); + }else{ + log_message('error', "Failed to call the pushClaims function in EmployeeRestController for Ticket ID: {$ticket_id}, because the .pdf file does not exist."); + } } - return $insert_ids; } @@ -3848,6 +3911,8 @@ class EmployeeRestController extends AdminController $emp_id = $this->request->getGet('emp_id'); $ticket_type = $this->request->getGet('ticket_type') ?? null; $ticket_id = $this->request->getGet('ticket_id') ?? null; + $mobile_number = $this->request->getGet('mobile_number') ?? null; + $email_id = $this->request->getGet('email_id') ?? null; $request = \Config\Services::request(); $uri = $request->uri->getPath(); $returnType = ""; @@ -3858,6 +3923,11 @@ class EmployeeRestController extends AdminController return $this->response->setJSON(['status' => false, 'code' => 200, 'message' => 'emp_id is required.'])->setStatusCode(404); } + $retail_ticket_data = []; + if(!empty($mobile_number) || !empty($email_id)){ + $retail_ticket_data = $this->getRetailPolicyClaimData($this->request->getGet()); + } + $TicketMasterModel = new TicketMasterModel(); $ticket_data = $TicketMasterModel->get_ticket_data($emp_id, $returnType, $ticket_type, $ticket_id); @@ -3932,9 +4002,108 @@ class EmployeeRestController extends AdminController } } + $ticket_data = array_merge($ticket_data, $retail_ticket_data); + return $this->response->setJSON(['ticket_data' => $ticket_data])->setStatusCode(200); } + public function getRetailPolicyClaimData($receviedPayload) + { + try { + // Create minimal retail user object + $retailUserData = (object) [ + 'id' => null, + 'mobile' => $receviedPayload['mobile_number'] ?? null, + 'email_id' => $receviedPayload['email_id'] ?? null + ]; + + // Get retail policies of user + $empRetailPolicyData = $this->getEmpRetailPolicy($retailUserData); + + if (empty($empRetailPolicyData)) { + return []; + } + + // Fetch ticket data for each policy + $retail_ticket_data = []; + foreach ($empRetailPolicyData as $policy) { + $tickets = $this->ticketMaster + ->select(" + ticket_master.*, + ( + SELECT th1.old_value + FROM ticket_history th1 + JOIN ticket_claim_status tcs ON th1.old_value = tcs.id + WHERE th1.field_name = 'claim_status_id' + AND th1.ticket_id = ticket_master.id + AND th1.id = ( + SELECT MAX(th2.id) + FROM ticket_history th2 + WHERE th2.ticket_id = th1.ticket_id + AND th2.field_name = 'claim_status_id' + ) + ) AS old_status_id + ") + ->where('is_active', 1) + ->where('client_id', $policy['client_id']) + ->where('policy_transaction_id', $policy['policy_transaction_id']) + ->findAll(); + + if (!empty($tickets)) { + $retail_ticket_data = array_merge($retail_ticket_data, $tickets); + } + } + + if (empty($retail_ticket_data)) { + return []; + } + + // Fetch grouped claim statuses + $client_claim_status = $this->getClaimStatusGrouped(); // Format expected: [status => [ids]] + $claim_type = $this->getClaimTypeMaster('internal'); + + // Convert claim type for quick access + $typeMap = array_column($claim_type, 'claim_type', 'id'); + + // Map status name to each ticket + foreach ($retail_ticket_data as &$ticket) { + $ticket['claim_status'] = null; // Default + + $ticket['claim_type_name'] = $typeMap[$ticket['claim_type']] ?? null; + foreach ($client_claim_status as $status_name => $status_list) { + if (in_array($ticket['claim_status_id'], $status_list)) { + $ticket['claim_status'] = $status_name; + break; + } + + if (in_array($ticket['old_status_id'], $status_list)) { + $ticket['claim_status'] = $status_name; + break; + } + } + } + + return $retail_ticket_data; + + }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, + ]; + + $this->myLogger->logme("error", "EMPLOYEE-REST-CONTROLLER - getRetailPolicyClaimData: Exception: " . json_encode($errorData ?? [])); + + return []; + } + } + public function getClaimStatusGrouped() { // Fetch active claim statuses @@ -3960,7 +4129,6 @@ class EmployeeRestController extends AdminController return $result; } - // not in use did for testing function encrypt_for_sso(): string { @@ -4716,9 +4884,17 @@ class EmployeeRestController extends AdminController $emp_retail_client_data = $this->clientModel ->select(" '{$emp_id}' AS emp_id, + clients.id as client_id, + clients.client_name as insurerd_name, + clients.email as insurerd_mail, + clients.phone as insurerd_mobile, + policy_transaction.id as policy_transaction_id, policy_transaction.insurer_id, policy_transaction.policy_type_id, policy_transaction.policy_no, + policy_transaction.client_policy_id, + policy_transaction.vehicle_id, + vehicle.vehicle_no, DATE_FORMAT(policy_transaction.policy_start_date, '%d-%b-%Y') as policy_start_date, DATE_FORMAT(policy_transaction.policy_end_date, '%d-%b-%Y') as policy_end_date, policy_type.policy_type, @@ -4729,17 +4905,29 @@ class EmployeeRestController extends AdminController ->join('policy_transaction', 'policy_transaction.client_id = clients.id') ->join('insurers', 'policy_transaction.insurer_id = insurers.id') ->join('policy_type', 'policy_transaction.policy_type_id = policy_type.id') + ->join('vehicle', 'policy_transaction.vehicle_id = vehicle.id', 'left') ->where('policy_transaction.is_active', 1) + ->where('policy_transaction.action_type', "inception") ->where('clients.is_active', 1) + ->where('clients.client_type', 2) + ->where('clients.phone IS NOT NULL') ->where('clients.phone', $mobile_number) ->findAll(); }else { $emp_retail_client_data = $this->clientModel ->select(" '{$emp_id}' AS emp_id, + clients.id as client_id, + clients.client_name as insurerd_name, + clients.email as insurerd_mail, + clients.phone as insurerd_mobile, + policy_transaction.id as policy_transaction_id, policy_transaction.insurer_id, policy_transaction.policy_type_id, policy_transaction.policy_no, + policy_transaction.client_policy_id, + policy_transaction.vehicle_id, + vehicle.vehicle_no, DATE_FORMAT(policy_transaction.policy_start_date, '%d-%b-%Y') as policy_start_date, DATE_FORMAT(policy_transaction.policy_end_date, '%d-%b-%Y') as policy_end_date, policy_type.policy_type, @@ -4750,8 +4938,11 @@ class EmployeeRestController extends AdminController ->join('policy_transaction', 'policy_transaction.client_id = clients.id') ->join('insurers', 'policy_transaction.insurer_id = insurers.id') ->join('policy_type', 'policy_transaction.policy_type_id = policy_type.id') + ->join('vehicle', 'policy_transaction.vehicle_id = vehicle.id', 'left') ->where('policy_transaction.is_active', 1) + ->where('policy_transaction.action_type', "inception") ->where('clients.is_active', 1) + ->where('clients.client_type', 2) ->where('clients.email IS NOT NULL') ->where('clients.email', $email_id) ->findAll(); @@ -4889,4 +5080,56 @@ class EmployeeRestController extends AdminController ], 200); } + public function getClaimTypeMaster($return_type = 'api') + { + $data = db_connect()->table('partner_claim_type_master')->select('id,claim_type')->where('is_active',1)->get()->getResultArray(); + + if (!$data) { + return $this->respond(['status' => 'failed', 'code' => 404, 'data' => []], 200); + } + + if($return_type == 'api'){ + return $this->respond(['status' => 'success', 'code' => 200, 'data' => $data]); + }else{ + return $data; + } + } + + public function uploadIRDocs() + { + $ticket_id = $this->request->getPost('ticket_id') ?? null; + $get_file_data = $this->request->getFiles('claim_docs') ?? null; + $get_docs_name = $this->request->getPost('claim_doc_names') ?? []; + $required_docs = $this->request->getPost('required_docs') ?? []; + + if (is_string($get_docs_name)) { + $decoded = json_decode($get_docs_name, true); + $get_docs_name = json_last_error() === JSON_ERROR_NONE ? $decoded : []; + } elseif (!is_array($get_docs_name)) { + $get_docs_name = []; + } + + $file_data = []; + if (isset($get_file_data) && !empty($get_file_data)) { + $file_path = WRITEPATH . 'uploads/claim_files/'; + $file_data = multi_file_Upload($get_file_data, $file_path, $get_docs_name); + } + + $result = $this->handleCliamFiles($file_data, $ticket_id, null, false, true); + + if(!empty($result)){ + // $this->ticketMaster->where('id', $ticket_id)->set(['required_docs', $required_docs])->update(); + db_connect()->query( + "UPDATE ticket_master SET required_docs = ? WHERE id = ?", + [$required_docs, $ticket_id] + ); + $apiServiceController = new ApiServiceController(); + $tpaIrFilePushResponce = $apiServiceController->pushClaimFiles($ticket_id); + return $this->respond(['status' => true, 'code' => 200, 'message' => 'Files uploaded successfully', 'tpaIrFilePushResponce' => $tpaIrFilePushResponce], 200); + }else{ + return $this->respond(['status' => false, 'code' => 400, 'message' => 'Failed to upload the file'], 200); + } + } + + } diff --git a/app/Controllers/MediAssistApiController.php b/app/Controllers/MediAssistApiController.php index 80bdecb7..e0be4976 100644 --- a/app/Controllers/MediAssistApiController.php +++ b/app/Controllers/MediAssistApiController.php @@ -12,15 +12,17 @@ use CodeIgniter\API\ResponseTrait; class MediAssistApiController extends BaseController { - use ResponseTrait; + use ResponseTrait; + protected $db; - public function index() + public function __construct() { - // + $this->db = \Config\Database::connect(); } - public function SubmitClaim ($claimId = null){ + public function SubmitClaim ($claimId = null) + { helper('api'); @@ -35,9 +37,9 @@ class MediAssistApiController extends BaseController ]; //Prepare body data - $db = \Config\Database::connect(); + // Fetch the data from DB - $data = $db->table('ticket_master tm') + $data = $this->db->table('ticket_master tm') ->select(' tm.id, tm.emp_mobile as mobileNo, @@ -141,7 +143,7 @@ class MediAssistApiController extends BaseController log_message('error', 'TPA CLAIM PUSH SUCCESS | claimId: '.$claimId.' | claimReferenceNo: '.$claimRef); - $db->table('ticket_master') + $this->db->table('ticket_master') ->where('id',$claimId) ->update([ 'tpa_claim_push_reference_no' => $claimRef ]); @@ -154,7 +156,8 @@ class MediAssistApiController extends BaseController } - public function EcardRequest ($employeeId = null, $policyNo = null){ + public function EcardRequest ($employeeId = null, $policyNo = null) + { helper('api'); @@ -198,7 +201,6 @@ class MediAssistApiController extends BaseController } - public function GetBenefDetails($requestData) { helper('api'); @@ -326,33 +328,13 @@ class MediAssistApiController extends BaseController } while ($startIndex < $totalCount); // now update DB - $db = \Config\Database::connect(); $updated = 0; - $employee_policy_ids = []; foreach ($employeePolicyData as $policy_data) { - foreach ($allBenef as $row) { - // log_message( - // "error", - // "POLICY MATCH CHECK: " . json_encode([ - // 'policy_data' => [ - // '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, - // ], - // 'row_data' => [ - // 'benefName' => $row['benefName'] ?? null, - // 'priBenefEmpCode' => $row['priBenefEmpCode'] ?? null, - // 'relName' => $row['relName'] ?? null, - // 'benefSex' => $row['benefSex'] ?? null, - // 'benefDOB' => $row['benefDOB'] ?? null, - // 'benefDOB_fmt' => change_date_format($row['benefDOB'],'d/m/Y H:i:s') ?? null, - // ], - // ]) - // ); + $hasMatchForThisPolicy = false; + + foreach ($allBenef as $row) { if ( strtolower(trim($policy_data['name'] ?? '')) == strtolower(trim($row['benefName'] ?? '')) && @@ -361,32 +343,53 @@ class MediAssistApiController extends BaseController ($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']}"); + // log_message('error', "✅ Match found: emp_code={$row['priBenefEmpCode']} policy={$row['polNo']}"); $sql = "UPDATE employee_polices SET tpa_id = ? WHERE id = ?"; - $db->query($sql, [$row['benefMediAssistID'], $policy_data['emp_policy_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 ($db->affectedRows() > 0) { + 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']}"); } - }else{ - log_message('error', "❌ Not matched: 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, + ]; + + log_message( + 'error', + "❌ No match for Nhance = " . json_encode($nhanceSideData) + ); + } + } + + // send e-card if(!empty($employee_policy_ids)){ log_message('error', "sendMailForDownloadingECard JOB PUSHED."); @@ -452,94 +455,271 @@ class MediAssistApiController extends BaseController } } - - // public function GetBenefDetails (){ - - // $postData = $this->request->getJSON(true); - - // helper('api'); - - // $url = ''. getenv('MEDI_ASSIST_API_BASE_URL').'/GetBenefDetails'; - // $method = 'POST'; - - // $headers = [ - // 'Content-Type: application/json', - // 'Username:'. getenv('MEDI_ASSIST_API_USERNAME').'', - // 'Password:'. getenv('MEDI_ASSIST_API_PASSWORD').'', - // ]; - - // $body = [ - // "policyNo" => $$postData['policy_no'], - // "startDate" => "", - // "endDate" => "", - // "isDeActivedata" => false, - // "startIndex" => 0, - // "range" => 100 , - // "employeeId" => "" - // ]; - - // // $body = [ - // // "policyNo" => "97000063250400000031", - // // "startDate" => "", - // // "endDate" => "", - // // "isDeActivedata" => false, - // // "startIndex" => 0, - // // "range" => 100 , - // // "employeeId" => "" - // // ]; - - // $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 ClaimDetail (){ - - + public function ClaimDetail($claimId = null) // 585 this id for test + { helper('api'); - $url = ''. getenv('MEDI_ASSIST_API_BASE_URL').'/ClaimDetail'; + $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').'', + 'Username:' . getenv('MEDI_ASSIST_API_USERNAME'), + 'Password:' . getenv('MEDI_ASSIST_API_PASSWORD'), ]; - $body = [ - "policyNo" => "97000063250400000031", - "startDate" => "", - "endDate" => "", - "employeeCode" => "CITPL120193", - "memberID" => "", - "claimNo" => "", - "claimRefNo" => "" + // 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" => "", + ]; + + } + + // dd($body); + + // $body = [ + // "policyNo" => "97000063250400000031", + // "startDate" => "31/08/2025", + // "endDate" => "01/09/2025", + // "employeeCode" => "CITPL120193", + // "memberID" => "", + // "claimNo" => "", + // "claimRefNo" => "HOSP4078102577_16092025111030" + // ]; + + // 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 API failed for ticket ID: ' . $claimId); + + 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 , 'updated_at' => date('Y-m-d H:i:s')]; + }else{ + $updateArray = ['tpa_claim_status' => $currentStatus , 'tpa_claim_id' => $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('info', "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('info', "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 $this->response->setJSON([ + '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('info', "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('info', "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('info', "IRSubmission API Response => " . json_encode($response)); - if($response['status'] != true){ - return $this->response->setJSON([ - 'status' => false, - 'message' => 'failed.', - 'data' => $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 + ]; } - return $this->response->setJSON($response); + log_message('info', "IRSubmission SUCCESS → ClaimID={$ticket['ClaimID']}"); + return [ + 'status' => true, + 'message' => 'IR Submitted successfully', + 'data' => $response + ]; } @@ -547,6 +727,36 @@ class MediAssistApiController extends BaseController + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + public function HospitalNetwork (){ $postData = $this->request->getJSON(true); @@ -627,44 +837,7 @@ class MediAssistApiController extends BaseController } - public function IRSubmission (){ - $postData = $this->request->getJSON(true); - - helper('api'); - - // $url = ''. getenv('MEDI_ASSIST_API_BASE_URL').'/ClaimAPIServiceUAT/Claim/IRSubmission'; - $url = "https://apiintegration.mediassist.in/ClaimAPIServiceUAT/Claim/IRSubmission"; - $method = 'POST'; - - $headers = [ - 'Content-Type: application/json', - 'Username:' .'NhanceUsr', - 'Password:' .'NhU$p&Cc5wGQbr2', - ]; - - $body = [ - "ClaimID" => "134431104", - "Attachments" => [ - "AttachmentName" => "Test.pdf", - "AttachmentPath" => "https://apiintegration.mediassist.in/IntegrationEcard/DownloadEcard/4078613742/Senthil Kumar P/556/5386" - ] - ]; - - $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() diff --git a/app/Controllers/RestAuthenticationController.php b/app/Controllers/RestAuthenticationController.php index b0f56392..9c9065b9 100755 --- a/app/Controllers/RestAuthenticationController.php +++ b/app/Controllers/RestAuthenticationController.php @@ -2207,6 +2207,7 @@ class RestAuthenticationController extends AdminController ->select('clients.*') ->join('policy_transaction', 'policy_transaction.client_id = clients.id') ->where('policy_transaction.is_active', 1) + ->where('policy_transaction.action_type', "inception") ->where('clients.is_active', 1) ->where('clients.phone', $mobile_number); @@ -2225,6 +2226,7 @@ class RestAuthenticationController extends AdminController ->select('clients.*') ->join('policy_transaction', 'policy_transaction.client_id = clients.id') ->where('policy_transaction.is_active', 1) + ->where('policy_transaction.action_type', "inception") ->where('clients.is_active', 1) ->where('clients.email', $email_id); diff --git a/app/Controllers/TicketController.php b/app/Controllers/TicketController.php index 87620e51..e2ba20fe 100644 --- a/app/Controllers/TicketController.php +++ b/app/Controllers/TicketController.php @@ -2837,6 +2837,32 @@ class TicketController extends BaseController echo $errorMessage; } } + + // -------- END CLAIM DUMP UPLOAD ---------------------------------------------------------------------------------------------- + public function saveIRDocsJson() + { + $ticket_id = $this->request->getPost('ticket_id'); + $required_docs = $this->request->getPost('required_docs'); + + if(empty($ticket_id)){ + return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to save Docs'], 200); + } + + if(empty($required_docs)){ + return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to save Docs'], 200); + } + + db_connect()->query( + "UPDATE ticket_master SET required_docs = ? WHERE id = ?", + [$required_docs, $ticket_id] + ); + + $required_docs = $this->ticketMasterModel->select('required_docs')->where('id', $ticket_id)->first(); + $required_docs = json_decode($required_docs['required_docs'] ?? '{}', true) ?? []; + + return $this->respond(['status' => true, 'code' => 200, 'message' => 'IR docs saved successfully', 'data' => $required_docs], 200); + + } } diff --git a/app/Models/AddImgModel.php b/app/Models/AddImgModel.php index 130da9f6..493d52b8 100755 --- a/app/Models/AddImgModel.php +++ b/app/Models/AddImgModel.php @@ -13,6 +13,7 @@ class AddImgModel extends Model "created_by", "updated_by", "is_active", + "client_id", ]; diff --git a/app/Models/ClaimFilesModel.php b/app/Models/ClaimFilesModel.php index 0e0a987c..8b13acbb 100644 --- a/app/Models/ClaimFilesModel.php +++ b/app/Models/ClaimFilesModel.php @@ -22,6 +22,7 @@ class ClaimFilesModel extends Model 'is_active', 'file_name', 'mime_type', + 'docs_for_ir', ]; // Callbacks diff --git a/app/Models/TicketMasterModel.php b/app/Models/TicketMasterModel.php index a0189088..a44286a9 100644 --- a/app/Models/TicketMasterModel.php +++ b/app/Models/TicketMasterModel.php @@ -89,6 +89,9 @@ class TicketMasterModel extends Model 'hospital_city', 'hospital_pin_code', 'hospital_phone_no', + 'claim_description', + 'required_docs', + 'policy_transaction_id', ]; diff --git a/app/Views/claim_files_upload.php b/app/Views/claim_files_upload.php index 80eccfa0..1c4f0079 100644 --- a/app/Views/claim_files_upload.php +++ b/app/Views/claim_files_upload.php @@ -1,9 +1,68 @@ -