diff --git a/app/Controllers/TicketServiceController.php b/app/Controllers/TicketServiceController.php index 3b1469e7..602f0708 100644 --- a/app/Controllers/TicketServiceController.php +++ b/app/Controllers/TicketServiceController.php @@ -1862,10 +1862,10 @@ class TicketServiceController extends BaseController } public function tpaClaimDumpImporter($params) - { - try { + { + $file_id = $params['file_id'] ?? null; // Move outside try to ensure catch can see it - $file_id = $params['file_id'] ?? null; + try { $file_path = WRITEPATH . 'uploads' . DIRECTORY_SEPARATOR . 'claim_dump_excel' . DIRECTORY_SEPARATOR; if (!$file_id) { @@ -1873,13 +1873,11 @@ class TicketServiceController extends BaseController } $fileData = $this->claimDumpFileModel->find((int)$file_id); - if (!$fileData) { return ['status' => false, 'message' => 'Invalid file ID. No file data found']; } $file_full_path = $file_path . $fileData['file_name']; - if (!is_file($file_full_path)) { return ['status' => false, 'message' => 'Claim dump file not found']; } @@ -1888,106 +1886,96 @@ class TicketServiceController extends BaseController $result = $handler->runTpaClaimDumpInsert($file_full_path, $file_id); if (!empty($result['status']) && $result['status'] === true) { - // mark file as processing and queue next job Jobs::addJob(['job_name' => 'tpaClaimDumpToTicketMasterImporters', 'payload' => ['file_id' => $file_id]]); } else { - $errorMessage = $result['message'] ?? 'Unknown import error'; - $reason = [ - 'error_summary' => [5 => 1], - 'error_data' => $errorMessage - ]; - $reasonJson = json_encode($reason, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); - // mark the file as failed using the model - $updated = $this->claimDumpFileModel->update($file_id, [ - 'status' => 'failed', - 'reason' => $reasonJson, - 'updated_by' => $fileData['created_by'] ?? null - ]); - if ($updated === false) { - $this->myLogger->logme('error', 'Claim dump file update to failed status failed for file_id: ' . $file_id); - } else { - $this->myLogger->logme('error', 'Claim dump file marked failed for file_id: ' . $file_id); - } + // FORCE FAIL LOGIC + $this->markAsFailed($file_id, $result['message'] ?? 'System error contact admin', $fileData['created_by'] ?? null); } return $result; - } catch (\Throwable $th) { + $this->myLogger->logme("error", 'TPA_CLAIM_IMPORTER_JOB : ' . $th->getMessage()); - $this->myLogger->logme( - "error", - 'TPA_CLAIM_IMPORTER_JOB : ' . - $th->getMessage() . ' | Line: ' . $th->getLine() - ); - - // attempt to mark file as failed if file_id available if (!empty($file_id)) { - $reason = json_encode(['error_summary' => [5 => 1], 'error_data' => 'TPA import crashed: ' . $th->getMessage()], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); - $this->claimDumpFileModel->update($file_id, ['status' => 'failed', 'reason' => $reason]); + $this->markAsFailed($file_id, 'System error contact admin'); } return [ 'status' => false, 'message' => 'TPA Claim dump import failed', - 'error_data' => [ - 'message' => $th->getMessage(), - 'file' => $th->getFile(), - 'line' => $th->getLine(), - 'trace' => $th->getTraceAsString() - ] + 'error_data' => $th->getMessage() ]; } } + private function markAsFailed($file_id, $message, $user_id = null) + { + $reason = json_encode([ + 'error_summary' => [5 => 1], + 'error_data' => $message + ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); + + $data = [ + 'status' => 'failed', + 'reason' => $reason, + 'updated_by' => $user_id + ]; + + // Using the direct update(id, data) method is often more reliable inside try/catch + return $this->claimDumpFileModel->update($file_id, $data); + } + public function tpaClaimDumpToTicketMasterImporters($params) { - try { + $file_id = $params['file_id'] ?? null; + $fileData = null; + + try { + if (!$file_id) { + return ['status' => false, 'message' => 'File ID is missing']; + } - $file_id = $params['file_id'] ?? null; $fileData = $this->claimDumpFileModel->where('id', $file_id)->first(); if (!$fileData) { - return ['status' => false, 'message' => 'Invalid file ID No file data found to import']; + return ['status' => false, 'message' => 'Invalid file ID. No file data found to import']; } $handler = TpaClaimsImportFactory::make($fileData['tpa_id'] ?? 0); $result = $handler->runTicketMasterInsert($params); if (!empty($result['status']) && $result['status'] === true) { - $updated = $this->claimDumpFileModel->where('id', $file_id)->set(['status' => 'success', 'reason' => null])->update(); + // Success: Update the status to success + $this->claimDumpFileModel->update($file_id, [ + 'status' => 'success', + 'reason' => null + ]); } else { - - $errorMessage = $result['message'] ?? 'Unknown import error C'; - $reason = [ - 'error_summary' => [5 => 1], // 🔒 always fixed - 'error_data' => $errorMessage - ]; - - $reason = json_encode($reason); - $updated = $this->claimDumpFileModel->where('id', $file_id)->set(['status' => 'failed', 'reason' => $reason])->update(); + // Logic failure: The runTicketMasterInsert returned status false + $this->markAsFailed( + $file_id, + $result['message'] ?? 'System error contact admin', + $fileData['created_by'] ?? null + ); } return $result; - } catch (\Throwable $th) { + // Log the full error + $this->myLogger->logme("error", 'TICKET_MASTER_CLAIM_IMPORTER_JOB :' . $th->getMessage() . ' at line ' . $th->getLine()); - $this->myLogger->logme("error", 'TICKET_MASTER_CLAIM_IMPORTER_JOB :' .($th->getMessage() . ' --- ' . $th->getLine() . '----' . $th->getTraceAsString())); - - $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, - ]; + // CRITICAL: Even if the code crashes, try to mark the file as failed + if ($file_id) { + $this->markAsFailed($file_id, 'Fatal Crash: ' . $th->getMessage(), $fileData['created_by'] ?? null); + } return [ 'status' => false, 'message' => $th->getMessage(), - 'error_data' => json_encode($errorData, JSON_PRETTY_PRINT) + 'error_data' => [ + 'line' => $th->getLine(), + 'file' => $th->getFile() + ] ]; } } diff --git a/app/Libraries/TPAClaimsImportServices/BaseTpaClaimImportService.php b/app/Libraries/TPAClaimsImportServices/BaseTpaClaimImportService.php index d428072f..d2b715cc 100644 --- a/app/Libraries/TPAClaimsImportServices/BaseTpaClaimImportService.php +++ b/app/Libraries/TPAClaimsImportServices/BaseTpaClaimImportService.php @@ -27,55 +27,49 @@ abstract class BaseTpaClaimImportService */ public function runTpaClaimDumpInsert(string $filePath, int $fileId): array { - $this->db->transStart(); + // 1. Start Transaction + $this->db->transBegin(); - $fileData = $this->claimDumpFileModel->where('id', $fileId)->first(); + try { + $fileData = $this->claimDumpFileModel->where('id', $fileId)->first(); - if (env('FHPL_PRIMARY_KEY_CONSTANT') == $fileData['tpa_id']) { - $rows = $this->readExcelBySheetName($filePath, 'Claims&Preauth'); - } else if (env('R_CARE_PRIMARY_KEY_CONSTANT') == $fileData['tpa_id']) { - $rows = $this->readExcelBySheetName($filePath, 'CL'); - // $AL = $this->readExcelBySheetName($filePath, 'AL'); - // $rows = array_merge($CL, $AL); - } else { - $rows = $this->readExcel($filePath); + // Determine sheet name logic... + if (env('FHPL_PRIMARY_KEY_CONSTANT') == $fileData['tpa_id']) { + $rows = $this->readExcelBySheetName($filePath, 'Claims&Preauth'); + } else if (env('R_CARE_PRIMARY_KEY_CONSTANT') == $fileData['tpa_id']) { + $rows = $this->readExcelBySheetName($filePath, 'CL'); + } else { + $rows = $this->readExcel($filePath); + } + + if (empty($rows)) { + $this->db->transRollback(); // ROLLBACK BEFORE RETURN + return ['status' => false, 'message' => 'Excel file contains no data or wrong file upload']; + } + + $tpaInsertData = $this->mapTPAData($rows, $fileId); + + if (empty($tpaInsertData)) { + $this->db->transRollback(); // ROLLBACK BEFORE RETURN + return ['status' => false, 'message' => 'These records already exist in the system.']; + } + + $return_res = $this->bulkInsertTPATable($tpaInsertData); + + if ($return_res !== true) { + $this->db->transRollback(); // ROLLBACK BEFORE RETURN + return ['status' => false, 'message' => 'TPA Import bulk insert failed']; + } + + // 2. Commit if everything is fine + $this->db->transCommit(); + return ['status' => true, 'message' => 'File uploaded successfully', 'record_count' => count($tpaInsertData)]; + + } catch (\Throwable $e) { + // 3. Rollback on any crash/exception + $this->db->transRollback(); + return ['status' => false, 'message' => 'System error : ' . $e->getMessage()]; } - // dd($rows); - - if (empty($rows)) { - return ['status' => false, 'message' => 'Excel file contains no data or wrong file upload']; - } - - $tpaInsertData = $this->mapTPAData($rows, $fileId); - // dd($tpaInsertData); - - if (empty($tpaInsertData)) { - return ['status' => false, 'message' => 'These records already exist in the system. Please check the file']; - } - - $return_res = $this->bulkInsertTPATable($tpaInsertData); - - if ($return_res !== true) { - return ['status' => false, 'message' => 'TPA Import bulk insert failed']; - } - - $this->db->transComplete(); - - if ($this->db->transStatus() === false) { - - $error = $this->db->error(); - $error_data = [ - 'message' => $error['message'] ?: 'Unknown DB error', - 'code' => $error['code'] ?? null, - 'last_query' => (string) $this->db->getLastQuery() - ]; - - // dd($error_data); - unset($error_data['last_query']); - return ['status' => false, 'message' => 'TPA Import transaction failed', 'error_data' => $error_data]; - } - - return ['status' => true, 'message' => 'File uploaded successfully', 'record_count' => count($tpaInsertData ?? [])]; } /** @@ -83,45 +77,65 @@ abstract class BaseTpaClaimImportService */ public function runTicketMasterInsert(array $params): array { - $this->db->transStart(); + // 1. Start manual transaction + $this->db->transBegin(); - $file_id = $params['file_id']; + try { + $file_id = $params['file_id']; + $ticketMasterData = $this->mapClaimMasterData($file_id); - $ticketMasterData = $this->mapClaimMasterData($file_id); - // dd($ticketMasterData); - - if (!$ticketMasterData['status']) { - return $ticketMasterData; - } - - $message = ''; - $return_res = false; - if(!empty($ticketMasterData['mapped_array'])){ - $return_res = $this->importClaimMaster($ticketMasterData['mapped_array']); - $message .= 'Ticket Master Claim bulk insert success. '; - } - - if(!empty($ticketMasterData['rejected_reason_array'])){ - $return_res = $this->updateTicketMasterRejectedReasonInTPATable($ticketMasterData['rejected_reason_array']); - if(empty($ticketMasterData['mapped_array'])){ - $message .= 'Those employees not in our system. '; - }else{ - $message .= 'Ticket Master Claim rejected reason updated successfully. '; + // Check if mapping failed + if (!$ticketMasterData['status']) { + $this->db->transRollback(); // ALWAYS rollback before early return + return $ticketMasterData; } + + $message = ''; + $hasExecutedTask = false; + + // Process Mapped Data + if (!empty($ticketMasterData['mapped_array'])) { + $insert_res = $this->importClaimMaster($ticketMasterData['mapped_array']); + if (!$insert_res) { + $this->db->transRollback(); + return ['status' => false, 'message' => 'Ticket Master Claim bulk insert failed']; + } + $message .= 'Ticket Master Claim bulk insert success. '; + $hasExecutedTask = true; + } + + // Process Rejected Reasons + if (!empty($ticketMasterData['rejected_reason_array'])) { + $update_res = $this->updateTicketMasterRejectedReasonInTPATable($ticketMasterData['rejected_reason_array']); + if (!$update_res) { + $this->db->transRollback(); + return ['status' => false, 'message' => 'Updating rejected reasons failed']; + } + + $message .= empty($ticketMasterData['mapped_array']) + ? 'Those employees not in our system. ' + : 'Ticket Master Claim rejected reason updated successfully. '; + $hasExecutedTask = true; + } + + // If nothing was processed but no error occurred + if (!$hasExecutedTask) { + $this->db->transRollback(); + return ['status' => false, 'message' => 'No data found to process.']; + } + + // 2. Commit the transaction + $this->db->transCommit(); + return ['status' => true, 'message' => trim($message)]; + + } catch (\Throwable $th) { + // 3. Rollback on crash + $this->db->transRollback(); + return [ + 'status' => false, + 'message' => 'System error during Ticket Master Insert: ' . $th->getMessage() + ]; } - - if(!$return_res){ - return ['status' => false, 'message' => 'Ticket Master Claim bulk insert failed']; - } - - $this->db->transComplete(); - - if ($this->db->transStatus() === false) { - return ['status' => false, 'message' => 'Ticket Master Claim bulk insert failed']; - } - - return ['status' => true, 'message' => $message]; - } /**