From 7cea4444d5e9be2163e3bc1a32c8bf087dbb499c Mon Sep 17 00:00:00 2001 From: "sanjeev.p" Date: Fri, 23 Jan 2026 11:28:18 +0530 Subject: [PATCH 1/9] FIX_ 1) sanitizepost for all 2) MIME File Upload images and pdf 3)CI Rules --- .../AppContentManagementController.php | 128 +- app/Controllers/BDSReportController.php | 23 +- app/Controllers/ClientController.php | 1134 ++++++++---- app/Controllers/EmployeeController.php | 114 +- app/Controllers/LeadsController.php | 92 +- app/Controllers/MasterController.php | 1588 +++++++++++++++-- app/Controllers/PayoutController.php | 12 +- .../PolicyTransactionController.php | 34 +- app/Controllers/ThzController.php | 118 +- app/Controllers/TicketController.php | 362 +++- app/Controllers/UserController.php | 319 +++- app/Views/UserList.php | 33 +- app/Views/add_image_list.php | 12 +- app/Views/bds_dump_file_list.php | 8 + app/Views/cd_master_add_modal.php | 10 + app/Views/claim_mis_file_list.php | 8 + app/Views/client_basic_info.php | 15 +- app/Views/client_branch.php | 2 +- app/Views/client_kyc.php | 3 +- app/Views/client_kyc_2.php | 1 + app/Views/client_kyc_other_table.php | 2 +- app/Views/client_kyc_primary_table.php | 2 +- app/Views/client_kyc_single_table.php | 1 + app/Views/client_policy.php | 11 +- app/Views/employee_data_list.php | 12 +- app/Views/faq_list.php | 12 + app/Views/frontend_content_list.php | 13 +- app/Views/insurer_basic_info.php | 10 + app/Views/insurer_export_templete.php | 41 +- app/Views/kyc_docs.php | 20 + app/Views/leads_form.php | 12 +- app/Views/leads_form_handler.php | 2 +- app/Views/leads_non_eb.php | 10 + app/Views/nhance_branch_list.php | 10 + .../policy_transaction_inception_list.php | 4 +- .../policy_transaction_inception_list_2.php | 4 +- app/Views/pos_list.php | 16 +- app/Views/retail_endorsement_list.php | 10 + app/Views/rfq/multi_files.php | 2 +- app/Views/rto_master_list.php | 10 + app/Views/test_members_list.php | 15 +- app/Views/thz_list.php | 12 +- app/Views/thz_notes.php | 26 +- app/Views/ticket_mail_template.php | 11 +- app/Views/tpa_basic_info.php | 11 + app/Views/tpa_branch.php | 10 + app/Views/vehicle_details.php | 13 +- app/Views/vehicle_master_list.php | 10 + app/Views/vehicle_type_list.php | 2 +- app/Views/vehicle_type_master_list.php | 10 + app/Views/view_rfq.php | 2 +- 51 files changed, 3662 insertions(+), 680 deletions(-) diff --git a/app/Controllers/AppContentManagementController.php b/app/Controllers/AppContentManagementController.php index 54f8cbb0..ac62129d 100755 --- a/app/Controllers/AppContentManagementController.php +++ b/app/Controllers/AppContentManagementController.php @@ -59,8 +59,48 @@ class AppContentManagementController extends AdminController // add and edit public function add_advertise_image() { try { + + $data = $this->request->getPost(); + $sanitized_post_data = sanitizeInputArrayAdvanced($data); + $id = (int) $sanitized_post_data['add_image_id']; + + $rules = [ + 'client_id' => [ + 'rules' => 'required|integer', + 'errors' => [ + 'required' => 'Client is required', + 'integer' => 'Invalid client selected' + ] + ], + ]; + $rules['advertise_image'] = [ + 'rules' => ($id === 0 ? 'uploaded[advertise_image]|' : '') // required only for ADD + . 'is_image[advertise_image]' + . '|mime_in[advertise_image,image/jpg,image/jpeg,image/png]' + . '|max_size[advertise_image,200]' + . '|min_dims[advertise_image,1640,664]' + . '|max_dims[advertise_image,1640,664]', + 'errors' => [ + 'uploaded' => 'Image is required', + 'is_image' => 'File must be an image', + 'mime_in' => 'Only JPG, JPEG, PNG allowed', + 'max_size' => 'Image size must not exceed 200 KB', + 'min_dims' => 'Image dimensions must be exactly 1640x664 pixels', + 'max_dims' => 'Image dimensions must be exactly 1640x664 pixels', + ] + ]; + if (!$this->validate($rules)) { + return $this->response->setStatusCode(400)->setJSON([ + 'status' => false, + 'message' => 'Input validation failed', + 'code' => 400, + 'errors' => $this->validator->getErrors() + ]); + } + + $file = $this->request->getFile('advertise_image'); - $client_id = $this->request->getPost('client_id'); + $client_id = $sanitized_post_data['client_id']; //1) original file name for vaildations $fileName = $file->getClientName(); //original file name for vaildations $existing = $this->addImgModel->where('name', $fileName)->where('client_id', $fileName)->where('is_active', 1)->first(); @@ -80,13 +120,13 @@ class AppContentManagementController extends AdminController $file->move($uploadPath, $fileName); - $id = $this->request->getPost('add_image_id'); - $data = ['name' => $fileName,'client_id'=>$client_id]; + $id = $sanitized_post_data['add_image_id']; + $details = ['name' => $fileName,'client_id'=>$client_id]; if ($id == 0) { - $this->addImgModel->insert($data); + $this->addImgModel->insert($details); } else { - $this->addImgModel->update($id, $data); + $this->addImgModel->update($id, $details); } return $this->respond(['status' => true, 'message' => 'Image saved successfully.']); @@ -143,8 +183,56 @@ class AppContentManagementController extends AdminController if ($this->request->getMethod() === 'post') { - $id = $this->request->getPost('fe_id'); - $data = $this->request->getPost(); + $rules = [ + 'type' => [ + 'rules' => 'required|max_length[255]', + 'errors' => [ + 'required' => 'Type is required', + 'max_length' => 'Type cannot exceed 255 characters' + ] + ], + 'content_section' => [ + 'rules' => 'required|max_length[255]', + 'errors' => [ + 'required' => 'Content Section is required', + 'max_length' => 'Content Section cannot exceed 255 characters' + ] + ], + 'heading' => [ + 'rules' => 'required|max_length[255]', + 'errors' => [ + 'required' => 'Heading is required', + 'max_length' => 'Heading cannot exceed 255 characters' + ] + ], + 'content' => [ + 'rules' => 'required|max_length[5000]', + 'errors' => [ + 'required' => 'Content is required', + 'max_length' => 'Content cannot exceed 5000 characters' + ] + ], + 'notes' => [ + 'rules' => 'required|max_length[1500]', + 'errors' => [ + 'required' => 'Notes are required', + 'max_length' => 'Notes cannot exceed 1500 characters' + ] + ] + ]; + + if (!$this->validate($rules)) { + return $this->response->setStatusCode(400)->setJSON([ + 'status' => false, + 'message' => 'Input validation failed', + 'code' => 400, + 'errors' => $this->validator->getErrors() + ]); + } + $request_post_data = $this->request->getPost(); + $data = sanitizeInputArrayAdvanced($data); + $id = $data['fe_id']; + unset($data['fe_id']); @@ -231,8 +319,30 @@ class AppContentManagementController extends AdminController try { // --- 1. POST: CREATE OR UPDATE --- if ($method === 'post') { - $id = $this->request->getPost('faq_id'); - $data = array_filter($this->request->getPost(), fn($v) => $v !== '' && $v !== null); + $rules = [ + 'category' => [ + 'rules' => 'required', + 'errors' => [ + 'required' => 'Category is required' + ] + ], + 'question' => [ + 'rules' => 'required', + 'errors' => [ + 'required' => 'Question is required' + ] + ], + 'answer' => [ + 'rules' => 'required', + 'errors' => [ + 'required' => 'Answer is required' + ] + ] + ]; + $request_post_data = $this->request->getPost(); + $sanitized_post_data = sanitizeInputArrayAdvanced($request_post_data); + $data = array_filter($sanitized_post_data, fn($v) => $v !== '' && $v !== null); + $id = $data['faq_id']; if (empty($id)) { $status = $this->faqModel->insert($data); diff --git a/app/Controllers/BDSReportController.php b/app/Controllers/BDSReportController.php index 84702df7..c871254b 100644 --- a/app/Controllers/BDSReportController.php +++ b/app/Controllers/BDSReportController.php @@ -191,10 +191,13 @@ class BDSReportController extends AdminController return $this->loadLayout('irba_report', $data); } else { - $fromDate = $this->request->getPost('fromDate'); - $toDate = $this->request->getPost('toDate'); - $category = $this->request->getPost('category'); - $report_type = $this->request->getPost('report_type'); + $request_post_data = $this->request->getPost(); + $sanitized_post_data = sanitizeInputArrayAdvanced($request_post_data); + + $fromDate = $sanitized_post_data['fromDate']; + $toDate = $sanitized_post_data['toDate']; + $category = $sanitized_post_data['category']; + $report_type = $sanitized_post_data['report_type']; // log_message('error',json_encode($_POST));die(); if ($report_type == 'insurer') { $life = $category == 'life' ? 1 : 0; @@ -937,11 +940,13 @@ class BDSReportController extends AdminController return $this->loadLayout('renewal_search', $data); } else { - $fromDate = $this->request->getPost('fromDate'); - $toDate = $this->request->getPost('toDate'); - $client_id = $this->request->getPost('client_id'); - $client_type = $this->request->getPost('client_type'); - $issuer_branch = $this->request->getPost('issuer_branch'); + $request_post_data = $this->request->getPost(); + $sanitized_post_data = sanitizeInputArrayAdvanced($request_post_data); + $fromDate = $sanitized_post_data['fromDate']; + $toDate = $sanitized_post_data['toDate']; + $client_id = $sanitized_post_data['client_id']; + $client_type = $sanitized_post_data['client_type']; + $issuer_branch = $sanitized_post_data['issuer_branch']; $data['issuer_branch'] = $this->nhanceBranchModel->where('is_active', 1)->findAll(); $data['client_type'] = [1 => 'Group', 2 => 'Individual']; diff --git a/app/Controllers/ClientController.php b/app/Controllers/ClientController.php index 4bbf2189..5ec28f01 100755 --- a/app/Controllers/ClientController.php +++ b/app/Controllers/ClientController.php @@ -936,40 +936,104 @@ class ClientController extends AdminController public function createClientGeneralInfo() { - $this->myLogger->logme('error', 'Client general info function called'); + + $rules = [ + 'entity_type_id' => [ + 'rules' => 'required', + 'errors' => [ + 'required' => 'Entity Type is required', + ] + ], + 'client_name' => [ + 'rules' => 'required|alpha_space', + 'errors' => [ + 'required' => 'Client Name is required', + 'alpha_space' => 'Client Name can only contain alphabets and spaces.', + ] + ], + 'short_name' => [ + 'rules' => 'required|alpha', + 'errors' => [ + 'required' => 'Client Short Name is required', + 'alpha' => 'Client Short Name can only contain alphabets.', + ] + ], + 'pan' => [ + 'rules' => 'required|regex_match[/^[A-Z]{5}[0-9]{4}[A-Z]$/]', + 'errors' => [ + 'required' => 'PAN Number is required.', + 'regex_match' => 'Invalid PAN format. Example: ABCDE1234F' + ] + ], + 'hr_file_processed_by' => [ + 'rules' => 'required', + 'errors' => [ + 'required' => 'HR File Processed By is required.', + ] + ], + 'client_logo' => [ + 'rules' => [ + 'is_image[client_logo]', + 'max_size[client_logo,200]', // 200 KB + 'ext_in[client_logo,jpg,jpeg,png]', + 'max_dims[client_logo,100,100]', + ], + 'errors' => [ + 'is_image' => 'The uploaded file must be an image', + 'max_size' => 'File size should not exceed 200 KB', + 'ext_in' => 'Allowed file types: jpg, jpeg, png', + 'max_dims' => 'Image dimensions must be 100 x 100 pixels', + ] + ], + + ]; + + if (!$this->validate($rules)) { + return $this->response->setStatusCode(400)->setJSON([ + 'status' => false, + 'message' => 'Input validation failed', + 'code' => 400, + 'errors' => $this->validator->getErrors() + ]); + } + + + $uploadFilePath = ROOTPATH . 'public/uploads/logo/'; $file_name = file_Upload($this->request->getFile('client_logo'), $uploadFilePath); $data = $this->request->getPost(); - $data['created_by'] = get_session_userid(); - $data['client_logo'] = $file_name; - $data['client_code'] = generate_client_code(); + $sanitized_post_data = sanitizeInputArrayAdvanced($data); + $sanitized_post_data['created_by'] = get_session_userid(); + $sanitized_post_data['client_logo'] = $file_name; + $sanitized_post_data['client_code'] = generate_client_code(); - if (!isset($data['is_download_btn'])) { - $data['is_download_btn'] = 0; - } elseif ($data['is_download_btn']) { - $data['is_download_btn'] = 1; + if (!isset($sanitized_post_data['is_download_btn'])) { + $sanitized_post_data['is_download_btn'] = 0; + } elseif ($sanitized_post_data['is_download_btn']) { + $sanitized_post_data['is_download_btn'] = 1; } - if (empty($data['parent_client_id'])) { - $data['parent_client_id'] = null; + if (empty($sanitized_post_data['parent_client_id'])) { + $sanitized_post_data['parent_client_id'] = null; } - $insert = $this->clientModel->insert($data); + $insertID = $this->clientModel->insert($sanitized_post_data); - if ($insert) { - $client_data = $this->clientModel->where(['id' => $insert, 'is_active' => 1])->first(); - - $client_id = $insert; - $default_template_creation = $this->createDefaultMailTemplate($client_id , $client_data); - if($default_template_creation == false){ - $this->myLogger->logme('error', 'Default Mail Template Creation Failed for Client ID: {data}', ['data' => $client_id]); + if ($insertID) { + + $client_info = $this->clientModel->where(['id' => $insertID, 'is_active' => 1])->first(); + + // Template Creation + if (!$this->createDefaultMailTemplate($insertID, $client_info)) { + $this->myLogger->logme('error', 'Default Mail Template Creation Failed for Client ID: ' . $insertID); } - return $this->respond(['status' => true, 'code' => 200, 'data' => $client_data], 200); - } else { - return $this->respond(['status' => false, 'code' => 404, 'message' => 'no data found'], 200); + + return $this->respond(['status' => true, 'code' => 200, 'data' => $client_info], 200); } + + return $this->respond(['status' => false, 'code' => 500, 'message' => 'Failed to create client'], 500); } public function editClientGeneralInfo() @@ -1009,7 +1073,7 @@ class ClientController extends AdminController - public function createClientKYCInfo() + public function createClientKYCInf() { $this->myLogger->logme('error', 'create Client kyc function called'); $data = $this->request->getPost(); @@ -1042,33 +1106,113 @@ class ClientController extends AdminController } } + /** Create Client KYC Documents V1 */ + public function createClientKYCInfo() + { + $this->myLogger->logme('error', 'Create Client KYC function called'); + + $rules = [ + 'file_name' => [ + 'rules' => 'uploaded[file_name]|max_size[file_name,5120]|ext_in[file_name,pdf,jpg,jpeg,png]', + 'errors' => [ + 'uploaded' => 'KYC document file is required', + 'max_size' => 'File size should not exceed 5MB', + 'ext_in' => 'Allowed file types: pdf, jpg, jpeg, png', + ] + ], + ]; + + if (!$this->validate($rules)) { + return $this->response->setStatusCode(400)->setJSON([ + 'status' => false, + 'message' => 'Input validation failed', + 'code' => 400, + 'errors' => $this->validator->getErrors() + ]); + } + + $data = $this->request->getPost(); + $sanitized_data = sanitizeInputArrayAdvanced($data); + $form_type = $sanitized_data['form_type'] ?? null; + + unset($data['file_name']); + + $file = $this->request->getFile('file_name'); + + $fileName = file_Upload($file, $uploadFilePath); + + if (!empty($fileName)) { + $sanitized_data['file_name'] = $fileName; + } + + $sanitized_data['created_by'] = get_session_userid(); + + $insertID = $this->clientKYCDocsModel->insert($sanitized_data); + if ($insertID) { + if ($form_type === 'others') { + $kycDocs = $this->generateKycOthersTable($sanitized_data['client_id']); + } else { + $kycDocs = $this->generateKycPrimaryTable($sanitized_data['client_id']); + } + return $this->respond(['status' => true, 'code' => 200, 'data' => $kycDocs, 'file_name' => $File], 200); + } else { + return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to upload KYC document'], 200); + } + } + + /** Edit Client KYC Documents V1 */ public function editClientKYCInfo() { + $this->myLogger->logme('error', 'Edit Client KYC function called'); + + $rules = [ + 'file_name' => [ + 'rules' => 'uploaded[file_name]|max_size[file_name,5120]|ext_in[file_name,pdf,jpg,jpeg,png]', + 'errors' => [ + 'uploaded' => 'KYC document file is required', + 'max_size' => 'File size should not exceed 5MB', + 'ext_in' => 'Allowed file types: pdf, jpg, jpeg, png', + ] + ], + ]; - $this->myLogger->logme('error', 'edit client kyc function called'); - $uploadFilePath = WRITEPATH . 'uploads/client_kyc_documents'; - $File = file_Upload($this->request->getFile('file_name'), $uploadFilePath); - $form_type = $this->request->getPost('form_type') ?? null; - - if (!empty($File)) { - $data['file_name'] = $File; + if (!$this->validate($rules)) { + return $this->response->setStatusCode(400)->setJSON([ + 'status' => false, + 'message' => 'Input validation failed', + 'code' => 400, + 'errors' => $this->validator->getErrors() + ]); } - $id = $this->request->getPost('PrimaryKey'); - $data['client_id'] = $id; - $data['kyc_doc_type_id'] = $this->request->getPost('kyc_doc_id'); - $data['updated_by'] = get_session_userid(); - $insert = $this->clientKYCDocsModel->insert($data); - if ($insert) { - // $kycDocs = $this->clientKYCDocsModel->getKycDocsName($id); - if ($form_type == "others") { - $kycDocs = $this->generateKycOthersTable($this->request->getPost('client_id')); + $data = $this->request->getPost(); + $sanitized_data = sanitizeInputArrayAdvanced($data); + $form_type = $sanitized_data['form_type'] ?? null; + + unset($sanitized_data['file_name']); + + $file = $this->request->getFile('file_name'); + + $fileName = file_Upload($file, $uploadFilePath); + + if (!empty($fileName)) { + $sanitized_data['file_name'] = $fileName; + } + $id = $sanitized_data['PrimaryKey']; + $sanitized_data['client_id'] = $id; + $sanitized_data['kyc_doc_type_id'] = $this->request->getPost('kyc_doc_id'); + $sanitized_data['updated_by'] = get_session_userid(); + + $insertID = $this->clientKYCDocsModel->insert($sanitized_data); + if ($insertID) { + if ($form_type === 'others') { + $kycDocs = $this->generateKycOthersTable($sanitized_data['client_id']); } else { - $kycDocs = $this->generateKycPrimaryTable($this->request->getPost('client_id')); + $kycDocs = $this->generateKycPrimaryTable($sanitized_data['client_id']); } - return $this->respond(['status' => true, 'code' => 200, 'data' => $kycDocs], 200); + return $this->respond(['status' => true, 'code' => 200, 'data' => $kycDocs, 'file_name' => $File], 200); } else { - return $this->respond(['status' => false, 'code' => 404, 'message' => 'no data found'], 200); + return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to upload KYC document'], 200); } } @@ -1095,12 +1239,33 @@ class ClientController extends AdminController } - + /** Client KYC Documents V2 */ public function createClientKYCInfo_2() { - $this->myLogger->logme('error', 'create Client kyc function called'); - $data = $this->request->getPost(); + $this->myLogger->logme('error', 'Create Client KYC V2 function called'); + + $rules = [ + 'file_name' => [ + 'rules' => 'uploaded[file_name]|max_size[file_name,5120]|ext_in[file_name,pdf,jpg,jpeg,png]', + 'errors' => [ + 'uploaded' => 'KYC document file is required', + 'max_size' => 'File size should not exceed 5MB', + 'ext_in' => 'Allowed file types: pdf, jpg, jpeg, png', + ] + ], + ]; + + if (!$this->validate($rules)) { + return $this->response->setStatusCode(400)->setJSON([ + 'status' => false, + 'message' => 'Input validation failed', + 'code' => 400, + 'errors' => $this->validator->getErrors() + ]); + } + + $data = $this->request->getPost(); $uploadedFile = $this->request->getFile('file_name'); if ($uploadedFile && $uploadedFile->isValid() && !$uploadedFile->hasMoved()) { @@ -1108,21 +1273,30 @@ class ClientController extends AdminController } else { $this->myLogger->logme('error', 'File failed validation or was not uploaded.'); } + unset($data['file_name']); + $sanitized_data = sanitizeInputArrayAdvanced($data); + $form_type = $sanitized_data['form_type'] ?? null; + + $file = $this->request->getFile('file_name'); + $fileName = file_Upload($file, $uploadFilePath); + + if (!empty($fileName)) { + $sanitized_data['file_name'] = $fileName; + } + + $sanitized_data['created_by'] = get_session_userid(); $uploadFilePath = WRITEPATH . 'uploads/client_kyc_documents'; $File = file_Upload($uploadedFile, $uploadFilePath); $this->myLogger->logme('info', 'Result of file_Upload: ' . $File); unset($data['file_name']); - if (!empty($File)) { $data['file_name'] = $File; } + $insertID = $this->clientKYCDocsModel->insert($sanitized_data); - $data['created_by'] = get_session_userid(); - $insert = $this->clientKYCDocsModel->insert($data); - - if ($insert) { - $html = $this->generateKycSingleTable($data['client_id']); - $dropdown = $this->fetch_dropdown($data['client_id']); + if ($insertID) { + $html = $this->generateKycSingleTable($sanitized_data['client_id']); + $dropdown = $this->fetch_dropdown($sanitized_data['client_id']); return $this->respond(['status' => true, 'code' => 200, 'file_name' => $File, 'html' => $html,'dropdown'=>$dropdown], 200); } else { $this->myLogger->logme('error', 'Database insert failed.'); @@ -1130,12 +1304,46 @@ class ClientController extends AdminController } } + /** Edit Client KYC Documents V2 */ public function editClientKYCInfo_2() { - $kyc_id = $this->request->getPost('id'); - $client_id = $this->request->getPost('client_id'); - $old_file_name = $this->request->getPost('old_file_name'); + $this->myLogger->logme('error', 'Edit Client KYC V2 function called'); + + $rules = [ + 'file_name' => [ + 'rules' => 'uploaded[file_name]|max_size[file_name,5120]|ext_in[file_name,pdf,jpg,jpeg,png]', + 'errors' => [ + 'uploaded' => 'KYC document file is required', + 'max_size' => 'File size should not exceed 5MB', + 'ext_in' => 'Allowed file types: pdf, jpg, jpeg, png', + ] + ], + ]; + + if (!$this->validate($rules)) { + return $this->response->setStatusCode(400)->setJSON([ + 'status' => false, + 'message' => 'Input validation failed', + 'code' => 400, + 'errors' => $this->validator->getErrors() + ]); + } + + + $data = $this->request->getPost(); + unset($data['file_name']); + $sanitized_data = sanitizeInputArrayAdvanced($data); + $form_type = $sanitized_data['form_type'] ?? null; + $kyc_id = $sanitized_data['id'] ?? null; + $client_id = $sanitized_data['client_id'] ?? null; + $old_file_name = $sanitized_data['old_file_name'] ?? null; + + if (empty($kyc_id)) { + return $this->respond(['status' => false, 'message' => 'Missing KYC ID'], 400); + } + + $updateData = []; $uploadedFile = $this->request->getFile('file_name'); $new_file_name = null; $uploadFilePath = WRITEPATH . 'uploads/client_kyc_documents'; @@ -1143,12 +1351,11 @@ class ClientController extends AdminController if ($uploadedFile && $uploadedFile->isValid() && !$uploadedFile->hasMoved()) { - - $new_file_name = file_Upload($uploadedFile, $uploadFilePath); - - if (!empty($new_file_name)) { - - $updateData['file_name'] = $new_file_name; + $new_file_name = file_Upload($uploadedFile, $uploadFilePath); + if (!$new_file_name) { + return $this->respond(['status' => false, 'code' => 500, 'message' => 'New file upload failed on server.'], 200); + } + $updateData['file_name'] = $new_file_name; // Delete the old file from the storage if it exists // if (!empty($old_file_name)) { @@ -1158,56 +1365,64 @@ class ClientController extends AdminController // // Optionally delete from G-Drive here if applicable // } // } - } else { - // New file upload failed - return $this->respond(['status' => false, 'code' => 500, 'message' => 'New file upload failed on server.'], 200); - } + } - // 2. Perform the database update - if (!empty($updateData)) { - - $updateData['updated_by'] = get_session_userid(); - $update = $this->clientKYCDocsModel->update($kyc_id, $updateData); - $html = $this->generateKycSingleTable($client_id); - $dropdown = $this->fetch_dropdown($client_id); - - if ($update) { - return $this->respond(['status' => true, 'code' => 200, 'message' => 'Document updated successfully.','html' => $html,'dropdown' => $dropdown], 200); - } - } else { - + if (empty($updateData)) { return $this->respond(['status' => true, 'code' => 200, 'message' => 'No changes detected. Document remains the same.'], 200); } - + $updateData['updated_by'] = get_session_userid(); + + $update = $this->clientKYCDocsModel->update($kyc_id, $updateData); + + if ($update) { + return $this->respond([ + 'status' => true, + 'message' => 'Document updated successfully', + 'html' => $this->generateKycSingleTable($client_id), + 'dropdown' => $this->fetch_dropdown($client_id) + ], 200); + } + return $this->respond(['status' => false, 'code' => 404, 'message' => 'Database update failed or record not found.'], 200); } - - public function deleteClientKycDocs_2() + /** Delete Client KYC Documents V2 */ + public function deleteClientKycDocs_2() { - - $kyc_id = $this->request->getPost('id'); - $client_id = $this->request->getPost('client_id'); - // echo "KID".$kyc_id; - // echo "CID".$client_id; + $this->myLogger->logme('error', 'Delete Client KYC V2 function called'); + $data = $this->request->getPost(); + $sanitized_data = sanitizeInputArrayAdvanced($data); + $kyc_id = $sanitized_data['id'] ?? null; + $client_id = $sanitized_data['client_id'] ?? null; + $is_active = $sanitized_data['is_active'] ?? null; if (empty($kyc_id)) { return $this->respond(['status' => false, 'code' => 400, 'message' => 'Missing document ID.'], 200); } - $updateData['updated_by'] = get_session_userid(); - $updateData['is_active'] = $this->request->getPost('is_active'); + + + $updateData = [ + 'is_active' => (int) $is_active, + 'updated_by' => get_session_userid() + ]; + $delete = $this->clientKYCDocsModel->update($kyc_id, $updateData); - // $delete = 1; + if ($delete) { - $html = $this->generateKycSingleTable($client_id); - $dropdown = $this->fetch_dropdown($client_id); - return $this->respond(['status' => true, 'code' => 200, 'id' => $kyc_id, 'message' => 'Document successfully deactivated.','html' => $html,'dropdown' => $dropdown], 200); - } else { - return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to update record (ID not found or DB error).'], 200); + return $this->respond([ + 'status' => true, + 'code' => 200, + 'id' => $kyc_id, + 'message' => 'Document successfully deactivated.', + 'html' => $this->generateKycSingleTable($client_id), + 'dropdown' => $this->fetch_dropdown($client_id) + ], 200); } + + return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to update record (ID not found or DB error).'], 200); } public function fetch_dropdown($client_id) @@ -1365,31 +1580,123 @@ class ClientController extends AdminController { $this->myLogger->logme('error', 'Client branch CREATE function called'); - $data = $this->request->getPost(); - if (!isset($data['sez'])) { - $data['sez'] = 0; - } elseif ($data['sez']) { - $data['sez'] = 1; + $rules = [ + 'branch_name' => [ + 'rules' => 'required', + 'errors' => [ + 'required' => 'Branch Name is required', + ] + ], + 'branch_code' => [ + 'rules' => 'required', + 'errors' => [ + 'required' => 'Branch Code is required', + ] + ], + 'address1' => [ + 'rules' => 'required', + 'errors' => [ + 'required' => 'Address Line 1 is required', + ] + ], + 'state' => [ + 'rules' => 'required', + 'errors' => [ + 'required' => 'State is required', + ] + ], + 'district' => [ + 'rules' => 'required', + 'errors' => [ + 'required' => 'District is required.', + ] + ], + 'city' => [ + 'rules' => 'required', + 'errors' => [ + 'required' => 'City is required.', + ] + ], + 'pincode' => [ + 'rules' => 'required', + 'errors' => [ + 'required' => 'Pincode is required.', + ] + ], + 'gst' => [ + 'rules' => 'required|regex_match[/^\d{2}[A-Z]{5}\d{4}[A-Z]{1}[A-Z\d]{1}Z[A-Z\d]{1}$/]', + 'errors' => [ + 'required' => 'GST number is required', + 'regex_match' => 'Invalid GST Number. Example: 12ABCDE1234F5Z6' + ] + ], + 'name.*' => [ + 'rules' => 'required|alpha_space', + 'errors' => [ + 'required' => 'Contact name is required', + 'alpha_space' => 'Contact name may contain only letters and spaces' + ] + ], + 'designation.*' => [ + 'rules' => 'required|alpha_space', + 'errors' => [ + 'required' => 'Designation is required', + 'alpha_space' => 'Designation may contain only letters and spaces' + ] + ], + 'email.*' => [ + 'rules' => 'required|valid_email', + 'errors' => [ + 'required' => 'Email is required', + 'valid_email' => 'Please enter a valid email address' + ] + ], + 'mobile.*' => [ + 'rules' => 'required|numeric|exact_length[10]', + 'errors' => [ + 'required' => 'Mobile number is required', + 'numeric' => 'Mobile number must contain digits only', + 'exact_length' => 'Mobile number must be exactly 10 digits' + ] + ], + ]; + + if (!$this->validate($rules)) { + return $this->response->setStatusCode(400)->setJSON([ + 'status' => false, + 'message' => 'Input validation failed', + 'code' => 400, + 'errors' => $this->validator->getErrors() + ]); } - $units = json_decode($data['units'], true) ?? []; + $data = $this->request->getPost(); + $sanitized_post_data = sanitizeInputArrayAdvanced($data); + + if (!isset($sanitized_post_data['sez'])) { + $sanitized_post_data['sez'] = 0; + } elseif ($sanitized_post_data['sez']) { + $sanitized_post_data['sez'] = 1; + } + + $units = json_decode($sanitized_post_data['units'], true) ?? []; if (!is_array($units) || empty($units)) { - $client_data = $this->clientModel->where('id', $data['client_id'])->first(); - $default_unit = trim(($client_data['short_name'] ?? '') . '-' . ($data['branch_code'] ?? ''), '-'); - $data['units'] = json_encode([$default_unit]); + $client_data = $this->clientModel->where('id', $sanitized_post_data['client_id'])->first(); + $default_unit = trim(($client_data['short_name'] ?? '') . '-' . ($sanitized_post_data['branch_code'] ?? ''), '-'); + $sanitized_post_data['units'] = json_encode([$default_unit]); } - $data['created_by'] = get_session_userid(); + $sanitized_post_data['created_by'] = get_session_userid(); // before updating check if pre_branch_id is already existing in the current db - if(isset($data['pre_branch_id']) && !empty($data['pre_branch_id'])) + if(isset($sanitized_post_data['pre_branch_id']) && !empty($sanitized_post_data['pre_branch_id'])) { $existing_pre_branch = $this->clientBranchModel - ->where('pre_branch_id',$data['pre_branch_id']) + ->where('pre_branch_id',$sanitized_post_data['pre_branch_id']) //->where('id !=',$post_branch_id) ->first(); @@ -1405,26 +1712,39 @@ class ClientController extends AdminController - $insert = $this->clientBranchModel->insert($data); + $insert = $this->clientBranchModel->insert($sanitized_post_data); $post_branch_id = $insert; if ($insert) { - $level_contact_data = $this->request->getPost('level_contect_data'); - $level_contact_data = !empty($level_contact_data) ? json_decode($level_contact_data, true) : null; - $this->saveLevelContacts($level_contact_data, $insert); + + $level_contact_data_raw = $this->request->getPost('level_contect_data'); + $level_contact_data = []; + + if (!empty($level_contact_data_raw)) { + $level_contact_data_decoded = json_decode($level_contact_data_raw, true); + + if (json_last_error() === JSON_ERROR_NONE && is_array($level_contact_data_decoded)) { + $level_contact_data = sanitizeInputArrayAdvanced($level_contact_data_decoded); + } + } + + if (!empty($level_contact_data)) { + $this->saveLevelContacts($level_contact_data, $insert); + } + } - if($post_branch_id && isset($data['pre_branch_id']) && !empty($data['pre_branch_id'])) + if($post_branch_id && isset($sanitized_post_data['pre_branch_id']) && !empty($sanitized_post_data['pre_branch_id'])) { // need to update the client_branch in the pre - $result = $this->updatePreClientBranch($data['pre_branch_id'],$post_branch_id , "create"); + $result = $this->updatePreClientBranch($sanitized_post_data['pre_branch_id'],$post_branch_id , "create"); - log_message('error','Pre client_branch update result for pre_branch_id '.$data['pre_branch_id'].' and post_branch_id '.$post_branch_id.' is '.json_encode($result)); + log_message('error','Pre client_branch update result for pre_branch_id '.$sanitized_post_data['pre_branch_id'].' and post_branch_id '.$post_branch_id.' is '.json_encode($result)); } if ($insert) { - $branchData = $this->clientBranchModel->where('client_id', $this->request->getPost('client_id'))->findAll(); + $branchData = $this->clientBranchModel->where('client_id', $sanitized_post_data('client_id'))->findAll(); $branchData['role'] = get_role_id(); return $this->respond([ 'status' => true, @@ -1445,14 +1765,15 @@ class ClientController extends AdminController { $this->myLogger->logme('error', 'Client branch EDIT function called'); - $id = $this->request->getPost('branch_id_primarykey'); - $client_id = $this->request->getPost('client_id'); - $pre_branch_id = $this->request->getPost('pre_branch_id') ?? ''; + $data = $this->request->getPost(); + $sanitized_post_data = sanitizeInputArrayAdvanced($data); + $id = $sanitized_post_data['branch_id_primarykey']; + $client_id = $sanitized_post_data['client_id']; + $pre_branch_id = $sanitized_post_data['pre_branch_id'] ?? ''; - $data = $this->request->getPost(); $data['pre_branch_id'] = $pre_branch_id; - $units = $this->request->getPost('units'); + $units = $sanitized_post_data['units']; $emp_unit_count = 0; $rr_unit_count = 0; @@ -1463,9 +1784,9 @@ class ClientController extends AdminController $units = json_decode($list_of_branch_units['units']); if (!is_array($units) || empty($units)) { - $client_data = $this->clientModel->where('id', $data['client_id'])->first(); - $default_unit = trim(($client_data['short_name'] ?? '') . '-' . ($data['branch_code'] ?? ''), '-'); - $data['units'] = json_encode([$default_unit]); + $client_data = $this->clientModel->where('id', $sanitized_post_data['client_id'])->first(); + $default_unit = trim(($client_data['short_name'] ?? '') . '-' . ($sanitized_post_data['branch_code'] ?? ''), '-'); + $sanitized_post_data['units'] = json_encode([$default_unit]); } if (!empty($units)) { @@ -1481,7 +1802,7 @@ class ClientController extends AdminController $uncommonValues = []; if ($total_count > 0) { - $units = (string) $this->request->getPost('units'); // Assuming 'units' is an array + $units = (string) $sanitized_post_data('units'); // Assuming 'units' is an array $list_of_branch_units = $this->clientBranchModel->find((int)$id); $branch_units = json_decode($list_of_branch_units['units'], true); @@ -1503,22 +1824,22 @@ class ClientController extends AdminController } } - if (!isset($data['sez'])) { - $data['sez'] = 0; - } elseif ($data['sez']) { - $data['sez'] = 1; + if (!isset($sanitized_post_data['sez'])) { + $sanitized_post_data['sez'] = 0; + } elseif ($sanitized_post_data['sez']) { + $sanitized_post_data['sez'] = 1; } - $data['updated_by'] = get_session_userid(); + $sanitized_post_data['updated_by'] = get_session_userid(); $post_branch_id = $id; // before updating check if pre_branch_id is already existing in the current db - if(isset($data['pre_branch_id']) && !empty($data['pre_branch_id'])) + if(isset($sanitized_post_data['pre_branch_id']) && !empty($sanitized_post_data['pre_branch_id'])) { $existing_pre_branch = $this->clientBranchModel - ->where('pre_branch_id',$data['pre_branch_id']) + ->where('pre_branch_id',$sanitized_post_data['pre_branch_id']) ->where('id !=',$post_branch_id) ->first(); @@ -1532,16 +1853,16 @@ class ClientController extends AdminController } } - $insert = $this->clientBranchModel->update($id, $data); + $insert = $this->clientBranchModel->update($id, $sanitized_post_data); - if($post_branch_id && isset($data['pre_branch_id']) && !empty($data['pre_branch_id'])) + if($post_branch_id && isset($sanitized_post_data['pre_branch_id']) && !empty($sanitized_post_data['pre_branch_id'])) { // need to update the client_branch in the pre - $result = $this->updatePreClientBranch($data['pre_branch_id'],$post_branch_id , "update"); + $result = $this->updatePreClientBranch($sanitized_post_data['pre_branch_id'],$post_branch_id , "update"); - log_message('error','Pre client_branch update result for pre_branch_id '.$data['pre_branch_id'].' and post_branch_id '.$post_branch_id.' is '.json_encode($result)); + log_message('error','Pre client_branch update result for pre_branch_id '.$sanitized_post_data['pre_branch_id'].' and post_branch_id '.$post_branch_id.' is '.json_encode($result)); } @@ -1549,10 +1870,22 @@ class ClientController extends AdminController if ($insert) { + + $level_contact_data_raw = $this->request->getPost('level_contect_data'); + $level_contact_data = []; + + if (!empty($level_contact_data_raw)) { + $level_contact_data_decoded = json_decode($level_contact_data_raw, true); + + if (json_last_error() === JSON_ERROR_NONE && is_array($level_contact_data_decoded)) { + $level_contact_data = sanitizeInputArrayAdvanced($level_contact_data_decoded); + } + } + + if (!empty($level_contact_data)) { + $this->saveLevelContacts($level_contact_data, $insert); + } - $level_contact_data = $this->request->getPost('level_contect_data'); - $level_contact_data = !empty($level_contact_data) ? json_decode($level_contact_data, true) : null; - $this->saveLevelContacts($level_contact_data, $id); } if ($insert) { @@ -1567,7 +1900,7 @@ class ClientController extends AdminController 'total_count' => $total_count, 'uncommonValues' => $uncommonValues, 'message' => 'Client branch updated successfully', - 'response_data' => $this->request->getPost() + 'response_data' => $sanitized_post_data ], 200); } else { @@ -1627,8 +1960,7 @@ class ClientController extends AdminController } - - + /** here ci4 rules not implemented, because UI screen Fields are hide/show implemented thats why */ public function createClientPolicy() { @@ -1637,20 +1969,23 @@ class ClientController extends AdminController $this->myLogger->logme('error', 'Client policy CREATE function called'); - $policy_type_id = $this->request->getPost('policy_type_id'); - $client_branch_id = $this->request->getPost('client_branch_id'); - $client_id = $this->request->getPost('client_id'); - $base_policy = $this->request->getPost('base_policy'); + $data = $this->request->getPost(); + $sanitized_post_data = sanitizeInputArrayAdvanced($data); + + $policy_type_id = $sanitized_post_data['policy_type_id']; + $client_branch_id = $sanitized_post_data['client_branch_id']; + $client_id = $sanitized_post_data['client_id']; + $base_policy = $sanitized_post_data['base_policy']; - $insurerValue = (string) $this->request->getPost('insurer'); + $insurerValue = (string) $sanitized_post_data['insurer']; list($insurerBranchId, $insurerId) = explode('-', $insurerValue); $data['insurer_branch_id'] = $insurerBranchId; $data['insurer_id'] = $insurerId; - $tpaValue = (string) $this->request->getPost('tpa'); + $tpaValue = (string) $sanitized_post_data['tpa']; if ($tpaValue === null || $tpaValue === '') { $tpaBranchId = null; @@ -1660,98 +1995,101 @@ class ClientController extends AdminController } - $data['client_id'] = $client_id; - $data['tpa_branch_id'] = $tpaBranchId; - $data['tpa_id'] = $tpaId; - $data['policy_type_id'] = $this->request->getPost('policy_type_id'); + $insert_data['client_id'] = $client_id; + $insert_data['tpa_branch_id'] = $tpaBranchId; + $insert_data['tpa_id'] = $tpaId; + $insert_data['policy_type_id'] = $sanitized_post_data['policy_type_id']; - $data['no_of_lives'] = $this->request->getPost('no_of_lives'); - $data['policy_status'] = $this->request->getPost('policy_status'); - $data['no_of_employees'] = $this->request->getPost('no_of_employees'); - $data['earned_premium_date'] = change_date_format($this->request->getPost('earned_premium_date'), 'd-m-Y', 'Y-m-d') ?? null; - $data['claims_incurred_date'] = change_date_format($this->request->getPost('claims_incurred_date'), 'd-m-Y', 'Y-m-d') ?? null; - $data['incurred_claims_ratio'] = $this->request->getPost('incurred_claims_ratio'); - $data['no_lives_at_inception'] = $this->request->getPost('no_lives_at_inception'); - $data['premium_paid_at_inception'] = $this->request->getPost('premium_paid_at_inception'); - $data['claims_experience_for_last_3_years'] = $this->request->getPost('claims_experience_for_last_3_years'); - $data['earned_premium_amount'] = $this->request->getPost('earned_premium_amount'); - $data['claims_incurred_amount'] = $this->request->getPost('claims_incurred_amount'); - $data['base_policy'] = ($this->request->getPost('base_policy') === '' || $this->request->getPost('base_policy') == 0) ? null : $this->request->getPost('base_policy'); - $data['policy_status'] = 1; - $data['inception_type'] = $this->request->getPost('inception_type') ? 2 : 1; - $data['client_branch_id'] = $this->request->getPost('client_branch_id'); - $data['cd_ac_pk'] = $this->request->getPost('cd_ac_no'); - $data['gst'] = $this->request->getPost('gst'); - $data['disclaimer'] = $this->request->getPost('disclaimer'); - $data['is_member_modify_allowed'] = $this->request->getPost('is_member_modify_allowed') ? 1 : 0; - $data['enrolment_visibility'] = $this->request->getPost('enrolment_visibility') ? 1 : 0; - $data['is_lgbtq'] = $this->request->getPost('is_lgbtq') ? 1 : 0; - $data['wellness_plan_id'] = $this->request->getPost('wellness_plan_id'); - $data['wellness_vendor_id'] = $this->request->getPost('wellness_vendor_id'); - $data['wellness_vendor_id'] = !empty($data['wellness_vendor_id']) ? $data['wellness_vendor_id'] : null; + $insert_data['no_of_lives'] = $sanitized_post_data['no_of_lives']; + $insert_data['policy_status'] = $sanitized_post_data['policy_status']; + $insert_data['no_of_employees'] = $sanitized_post_data['no_of_employees']; + $insert_data['earned_premium_date'] = change_date_format($sanitized_post_data['earned_premium_date'], 'd-m-Y', 'Y-m-d') ?? null; + $insert_data['claims_incurred_date'] = change_date_format($sanitized_post_data['claims_incurred_date'], 'd-m-Y', 'Y-m-d') ?? null; + $insert_data['incurred_claims_ratio'] = $sanitized_post_data['incurred_claims_ratio']; + $insert_data['no_lives_at_inception'] = $sanitized_post_data['no_lives_at_inception']; + $insert_data['premium_paid_at_inception'] = $sanitized_post_data['premium_paid_at_inception']; + $insert_data['claims_experience_for_last_3_years'] = $sanitized_post_data['claims_experience_for_last_3_years']; + $insert_data['earned_premium_amount'] = $sanitized_post_data['earned_premium_amount']; + $insert_data['claims_incurred_amount'] = $sanitized_post_data['claims_incurred_amount']; + $insert_data['base_policy'] = ($sanitized_post_data['base_policy'] === '' || $sanitized_post_data['base_policy'] == 0) ? null : $sanitized_post_data['base_policy']; + $insert_data['policy_status'] = 1; + $insert_data['inception_type'] = $sanitized_post_data['inception_type'] ? 2 : 1; + $insert_data['client_branch_id'] = $sanitized_post_data['client_branch_id']; + $insert_data['cd_ac_pk'] = $sanitized_post_data['cd_ac_no']; + $insert_data['gst'] = $sanitized_post_data['gst']; + $insert_data['disclaimer'] = $sanitized_post_data['disclaimer']; + $insert_data['is_member_modify_allowed'] = $sanitized_post_data['is_member_modify_allowed'] ? 1 : 0; + $insert_data['enrolment_visibility'] = $sanitized_post_data['enrolment_visibility'] ? 1 : 0; + $insert_data['is_lgbtq'] = $sanitized_post_data['is_lgbtq'] ? 1 : 0; + $insert_data['wellness_plan_id'] = $sanitized_post_data['wellness_plan_id']; + $insert_data['wellness_vendor_id'] = $sanitized_post_data['wellness_vendor_id']; + $insert_data['wellness_vendor_id'] = !empty($insert_data['wellness_vendor_id']) ? $insert_data['wellness_vendor_id'] : null; if ($policy_type_id == 1 || $policy_type_id == 2 || $policy_type_id == 6 || $policy_type_id == 7) { - $data['is_addon'] = 1; // Base Policy + $insert_data['is_addon'] = 1; // Base Policy } else if ($policy_type_id == 4 || $policy_type_id == 5) { - $data['is_addon'] = 2; // SI TOPUP + $insert_data['is_addon'] = 2; // SI TOPUP } else if ($policy_type_id == 3) { if ($base_policy) { - $data['is_addon'] = 3; // Dependent Addon + $insert_data['is_addon'] = 3; // Dependent Addon } else { - $data['is_addon'] = 1; + $insert_data['is_addon'] = 1; } } - $data['policy_start_date'] = change_date_format($this->request->getPost('policy_start_date'), 'd-m-Y', 'Y-m-d'); - $data['policy_end_date'] = change_date_format($this->request->getPost('policy_end_date'), 'd-m-Y', 'Y-m-d'); - $data['policy_no'] = $this->request->getPost('policy_no'); - if ($data['inception_type'] == 2) { - $data['open_date'] = change_date_format($this->request->getPost('open_date'), 'd-m-Y', 'Y-m-d'); - $data['close_date'] = change_date_format($this->request->getPost('close_date'), 'd-m-Y', 'Y-m-d'); + $insert_data['policy_start_date'] = change_date_format($sanitized_post_data['policy_start_date'], 'd-m-Y', 'Y-m-d'); + $insert_data['policy_end_date'] = change_date_format($sanitized_post_data['policy_end_date'], 'd-m-Y', 'Y-m-d'); + $insert_data['policy_no'] = $sanitized_post_data['policy_no']; + if ($insert_data['inception_type'] == 2) { + $insert_data['open_date'] = change_date_format($sanitized_post_data['open_date'], 'd-m-Y', 'Y-m-d'); + $insert_data['close_date'] = change_date_format($sanitized_post_data['close_date'], 'd-m-Y', 'Y-m-d'); // $data['reminder_date'] = change_date_format($this->request->getPost('reminder_date'), 'd-m-Y', 'Y-m-d'); - $data['reminder_date'] = $this->request->getPost('reminder_date'); + $insert_data['reminder_date'] = $sanitized_post_data['reminder_date']; } else { - $data['open_date'] = null; - $data['closedate'] = null; - $data['reminder_date'] = null; + $insert_data['open_date'] = null; + $insert_data['closedate'] = null; + $insert_data['reminder_date'] = null; } - $data['created_by'] = get_session_userid(); + $insert_data['created_by'] = get_session_userid(); - $insert = $this->clientPolicyModel->insert($data); + $insert = $this->clientPolicyModel->insert($insert_data); if ($insert) { - $clientPoliceData = $this->clientPolicyModel->getClientPolicyByClientId($this->request->getPost('client_id')); + $clientPoliceData = $this->clientPolicyModel->getClientPolicyByClientId($sanitized_post_data['client_id']); $clientPoliceData['role'] = get_role_id(); - return $this->respond(['status' => true, 'code' => 200, 'data' => $clientPoliceData, 'method' => 'CERATE', 'post_data' => $data], 200); + return $this->respond(['status' => true, 'code' => 200, 'data' => $clientPoliceData, 'method' => 'CERATE', 'post_data' => $insert_data], 200); } else { return $this->respond(['status' => false, 'code' => 404, 'message' => 'no data found'], 200); } } + /** here ci4 rules not implemented, because UI screen Fields are hide/show implemented thats why */ public function editClientPolicy() { $this->myLogger->logme('error', 'Client policy function called'); + $data = $this->request->getPost(); + $sanitized_post_data = sanitizeInputArrayAdvanced($data); - $id = $this->request->getPost('PrimaryKey'); - $client_id = $this->request->getPost('client_id'); - $policy_type_id = $this->request->getPost('policy_type_id'); - $base_policy = $this->request->getPost('base_policy'); + $id = $sanitized_post_data['PrimaryKey']; + $client_id = $sanitized_post_data['client_id']; + $policy_type_id = $sanitized_post_data['policy_type_id']; + $base_policy = $sanitized_post_data['base_policy']; - $insurerValue = (string) $this->request->getPost('insurer'); + $insurerValue = (string) $sanitized_post_data['insurer']; list($insurerBranchId, $insurerId) = explode('-', $insurerValue); $data['insurer_branch_id'] = $insurerBranchId; $data['insurer_id'] = $insurerId; - $tpaValue = (string) $this->request->getPost('tpa'); + $tpaValue = (string) $sanitized_post_data['tpa']; if (!empty($tpaValue) || $tpaValue !== '') { list($tpaBranchId, $tpaId) = explode('-', $tpaValue); } else { @@ -1759,75 +2097,75 @@ class ClientController extends AdminController $tpaId = null; } - $data['tpa_branch_id'] = $tpaBranchId; - $data['client_id'] = $client_id; - $data['tpa_id'] = $tpaId; - $data['policy_type_id'] = $this->request->getPost('policy_type_id'); - $data['policy_no'] = $this->request->getPost('policy_no'); + $update_data['tpa_branch_id'] = $tpaBranchId; + $update_data['client_id'] = $client_id; + $update_data['tpa_id'] = $tpaId; + $update_data['policy_type_id'] = $sanitized_post_data['policy_type_id']; + $update_data['policy_no'] = $sanitized_post_data['policy_no']; - $data['insured'] = $this->request->getPost('insured'); - $data['no_of_lives'] = $this->request->getPost('no_of_lives'); - $data['policy_status'] = $this->request->getPost('policy_status'); - $data['no_of_employees'] = $this->request->getPost('no_of_employees'); - $data['earned_premium_date'] = change_date_format($this->request->getPost('earned_premium_date'), 'd-m-Y', 'Y-m-d') ?? null; - $data['claims_incurred_date'] = change_date_format($this->request->getPost('claims_incurred_date'), 'd-m-Y', 'Y-m-d') ?? null; - $data['incurred_claims_ratio'] = $this->request->getPost('incurred_claims_ratio'); - $data['no_lives_at_inception'] = $this->request->getPost('no_lives_at_inception'); - $data['premium_paid_at_inception'] = $this->request->getPost('premium_paid_at_inception'); - $data['claims_experience_for_last_3_years'] = $this->request->getPost('claims_experience_for_last_3_years'); - $data['earned_premium_amount'] = $this->request->getPost('earned_premium_amount'); - $data['claims_incurred_amount'] = $this->request->getPost('claims_incurred_amount'); - $data['base_policy'] = ($this->request->getPost('base_policy') === '' || $this->request->getPost('base_policy') == 0) ? null : $this->request->getPost('base_policy'); - $data['policy_status'] = 1; - $data['inception_type'] = $this->request->getPost('inception_type') ? 2 : 1; - $data['enrolment_visibility'] = $this->request->getPost('enrolment_visibility') ? 1 : 0; - $data['client_branch_id'] = $this->request->getPost('client_branch_id'); - $data['cd_ac_pk'] = $this->request->getPost('cd_ac_no'); - $data['gst'] = $this->request->getPost('gst'); - $data['disclaimer'] = $this->request->getPost('disclaimer'); - $data['policy_start_date'] = change_date_format($this->request->getPost('policy_start_date'), 'd-m-Y', 'Y-m-d'); - $data['policy_end_date'] = change_date_format($this->request->getPost('policy_end_date'), 'd-m-Y', 'Y-m-d'); - $data['is_member_modify_allowed'] = $this->request->getPost('is_member_modify_allowed') ? 1 : 0; - $data['is_lgbtq'] = $this->request->getPost('is_lgbtq') ? 1 : 0; - $data['wellness_plan_id'] = $this->request->getPost('wellness_plan_id'); - $data['wellness_vendor_id'] = $this->request->getPost('wellness_vendor_id'); - $data['wellness_vendor_id'] = !empty($data['wellness_vendor_id']) ? $data['wellness_vendor_id'] : null; + $update_data['insured'] = $sanitized_post_data['insured']; + $update_data['no_of_lives'] = $sanitized_post_data['no_of_lives']; + $update_data['policy_status'] = $sanitized_post_data['policy_status']; + $update_data['no_of_employees'] = $sanitized_post_data['no_of_employees']; + $update_data['earned_premium_date'] = change_date_format($sanitized_post_data['earned_premium_date'], 'd-m-Y', 'Y-m-d') ?? null; + $update_data['claims_incurred_date'] = change_date_format($sanitized_post_data['claims_incurred_date'], 'd-m-Y', 'Y-m-d') ?? null; + $update_data['incurred_claims_ratio'] = $sanitized_post_data['incurred_claims_ratio']; + $update_data['no_lives_at_inception'] = $sanitized_post_data['no_lives_at_inception']; + $update_data['premium_paid_at_inception'] = $sanitized_post_data['premium_paid_at_inception']; + $update_data['claims_experience_for_last_3_years'] = $sanitized_post_data['claims_experience_for_last_3_years']; + $update_data['earned_premium_amount'] = $sanitized_post_data['earned_premium_amount']; + $update_data['claims_incurred_amount'] = $sanitized_post_data['claims_incurred_amount']; + $update_data['base_policy'] = ($sanitized_post_data['base_policy'] === '' || $sanitized_post_data['base_policy'] == 0) ? null : $sanitized_post_data['base_policy']; + $update_data['policy_status'] = 1; + $update_data['inception_type'] = $sanitized_post_data['inception_type'] ? 2 : 1; + $update_data['enrolment_visibility'] = $sanitized_post_data['enrolment_visibility'] ? 1 : 0; + $update_data['client_branch_id'] = $sanitized_post_data['client_branch_id']; + $update_data['cd_ac_pk'] = $sanitized_post_data['cd_ac_no']; + $update_data['gst'] = $sanitized_post_data['gst']; + $update_data['disclaimer'] = $sanitized_post_data['disclaimer']; + $update_data['policy_start_date'] = change_date_format($sanitized_post_data['policy_start_date'], 'd-m-Y', 'Y-m-d'); + $update_data['policy_end_date'] = change_date_format($sanitized_post_data['policy_end_date'], 'd-m-Y', 'Y-m-d'); + $update_data['is_member_modify_allowed'] = $sanitized_post_data['is_member_modify_allowed'] ? 1 : 0; + $update_data['is_lgbtq'] = $sanitized_post_data['is_lgbtq'] ? 1 : 0; + $update_data['wellness_plan_id'] = $sanitized_post_data['wellness_plan_id']; + $update_data['wellness_vendor_id'] = $sanitized_post_data['wellness_vendor_id']; + $update_data['wellness_vendor_id'] = !empty($update_data['wellness_vendor_id']) ? $update_data['wellness_vendor_id'] : null; - if ($data['inception_type'] == 2) { - $data['open_date'] = change_date_format($this->request->getPost('open_date'), 'd-m-Y', 'Y-m-d'); - $data['close_date'] = change_date_format($this->request->getPost('close_date'), 'd-m-Y', 'Y-m-d'); - // $data['reminder_date'] = change_date_format($this->request->getPost('reminder_date'), 'd-m-Y', 'Y-m-d'); - $data['reminder_date'] = $this->request->getPost('reminder_date'); + if ($update_data['inception_type'] == 2) { + $update_data['open_date'] = change_date_format($sanitized_post_data['open_date'], 'd-m-Y', 'Y-m-d'); + $update_data['close_date'] = change_date_format($sanitized_post_data['close_date'], 'd-m-Y', 'Y-m-d'); + // $data['reminder_date'] = change_date_format($sanitized_post_data['reminder_date'), 'd-m-Y', 'Y-m-d'); + $update_data['reminder_date'] = $sanitized_post_data['reminder_date']; } else { - $data['open_date'] = null; - $data['close_date'] = null; - $data['reminder_date'] = null; + $update_data['open_date'] = null; + $update_data['close_date'] = null; + $update_data['reminder_date'] = null; } if ($policy_type_id == 1 || $policy_type_id == 2 || $policy_type_id == 6 || $policy_type_id == 7) { - $data['is_addon'] = 1; // Base Policy + $update_data['is_addon'] = 1; // Base Policy } else if ($policy_type_id == 4 || $policy_type_id == 5) { - $data['is_addon'] = 2; // SI TOPUP + $update_data['is_addon'] = 2; // SI TOPUP } else if ($policy_type_id == 3) { if ($base_policy) { - $data['is_addon'] = 3; // Dependent Addon + $update_data['is_addon'] = 3; // Dependent Addon } else { - $data['is_addon'] = 1; + $update_data['is_addon'] = 1; } } - $policy_terms = $this->clientPolicyModel->where('id', $this->request->getPost('base_policy'))->first(); + $policy_terms = $this->clientPolicyModel->where('id', $sanitized_post_data['base_policy'])->first(); $old_client_policy_data = $this->clientPolicyModel->where('is_active', 1)->where('id', $id)->first(); - $data['updated_by'] = get_session_userid(); - $insert = $this->clientPolicyModel->update($id, $data); + $update_data['updated_by'] = get_session_userid(); + $update = $this->clientPolicyModel->update($id, $update_data); - if ($insert) { + if ($update) { $new_client_policy_data = $this->clientPolicyModel->where('is_active', 1)->where('id', $id)->first(); $policy_transaction_data = $this->policyTransactionModel->where('is_active', 1)->where('client_policy_id', $id)->countAllResults(); @@ -1917,10 +2255,13 @@ class ClientController extends AdminController // echo json_encode(['key' => $this->request->getPost()]); die; try { - $client_id = $this->request->getPost('client_id'); - $client_policy_id = $this->request->getPost('client_policy_id'); + $data = $this->request->getPost(); + $sanitized_post_data = sanitizeInputArrayAdvanced($data); + + $client_id = $sanitized_post_data['client_id']; + $client_policy_id = $sanitized_post_data['client_policy_id']; $record = $this->clientPolicyModel->where('client_policy.id', $client_policy_id)->first(); - $premium_type = $this->request->getPost('premium_type'); + $premium_type = $sanitized_post_data['premium_type']; if (!empty($client_id) && $client_id != null) { $client_policy_data = $this->clientPolicyModel->where('id', $client_policy_id)->first(); $client_id = $client_policy_data['client_id']; @@ -1929,24 +2270,24 @@ class ClientController extends AdminController $branch_units = $this->getBranchUnitsByBranchId($record['client_branch_id']); $branch_units = json_decode($branch_units); - $policy_grid_id = $this->request->getPost('policy_grid_id'); - $rack_rate_name = $this->request->getPost('rack_rate_name'); + $policy_grid_id = $sanitized_post_data['policy_grid_id']; + $rack_rate_name = $sanitized_post_data['rack_rate_name']; $relation_data = [ - 'self' => $this->request->getPost('self') ?? 'NA', - 'spouse' => $this->request->getPost('spouse') ?? 'NA', - 'childrens' => $this->request->getPost('childrens') ?? 'NA', - 'parents' => $this->request->getPost('parents') ?? 'NA', - 'parents-in-law' => $this->request->getPost('parents-in-law') ?? 'NA', + 'self' => $sanitized_post_data['self'] ?? 'NA', + 'spouse' => $sanitized_post_data['spouse'] ?? 'NA', + 'childrens' => $sanitized_post_data['childrens'] ?? 'NA', + 'parents' => $sanitized_post_data['parents'] ?? 'NA', + 'parents-in-law' => $sanitized_post_data['parents-in-law'] ?? 'NA', ]; $relation_data_for_form_submit_check = [ $rack_rate_name => [ - 'self' => $this->request->getPost('self') ?? 'NA', - 'spouse' => $this->request->getPost('spouse') ?? 'NA', - 'childrens' => $this->request->getPost('childrens') ?? 'NA', - 'parents' => $this->request->getPost('parents') ?? 'NA', - 'parents-in-law' => $this->request->getPost('parents-in-law') ?? 'NA', + 'self' => $sanitized_post_data['self'] ?? 'NA', + 'spouse' => $sanitized_post_data['spouse'] ?? 'NA', + 'childrens' => $sanitized_post_data['childrens'] ?? 'NA', + 'parents' => $sanitized_post_data['parents'] ?? 'NA', + 'parents-in-law' => $sanitized_post_data['parents-in-law'] ?? 'NA', ] ]; @@ -1964,11 +2305,11 @@ class ClientController extends AdminController $jsonDataForRelation = json_encode($relation_data); $json_data_relation_data_for_form_submit_check = json_encode($relation_data_for_form_submit_check); - $si_or_bp = $this->request->getPost('si_or_bp'); - $basic_multiplier = str_replace(',', '', $this->request->getPost('basic_multiplier')); - $premium_multiplier = str_replace(',', '', $this->request->getPost('premium_multiplier')); - $multiplier = str_replace(',', '', $this->request->getPost('multiplier')); - $basic_pay = str_replace(',', '', $this->request->getPost('basic_pay')); + $si_or_bp = $sanitized_post_data['si_or_bp']; + $basic_multiplier = str_replace(',', '', $sanitized_post_data['basic_multiplier']); + $premium_multiplier = str_replace(',', '', $sanitized_post_data['premium_multiplier']); + $multiplier = str_replace(',', '', $sanitized_post_data['multiplier']); + $basic_pay = str_replace(',', '', $sanitized_post_data['basic_pay']); $data = []; $data['client_id'] = $client_id; @@ -1990,16 +2331,16 @@ class ClientController extends AdminController if ($si_or_bp == '1') { - $premium = str_replace(',', '', $this->request->getPost('gpa_sum_premium[]')); - $sum_insure = str_replace(',', '', $this->request->getPost('gpa_sum_si[]')); - $multiplier = $this->request->getPost('gpa_sum_multiplier'); - $unit = $this->request->getPost('gpa_unit_1[]'); + $premium = str_replace(',', '', $sanitized_post_data['gpa_sum_premium[]']); + $sum_insure = str_replace(',', '', $sanitized_post_data['gpa_sum_si[]']); + $multiplier = $sanitized_post_data['gpa_sum_multiplier']; + $unit = $sanitized_post_data['gpa_unit_1[]']; for ($i = 0; $i < count($premium); $i++) { $data['si'] = $sum_insure[$i]; $data['premium'] = $premium[$i]; $data['multiplier'] = $multiplier; - $data['si_or_bp'] = $this->request->getPost('si_or_bp'); + $data['si_or_bp'] = $sanitized_post_data['si_or_bp']; if (empty($unit) || !isset($unit[$i]) || empty($unit[$i])) { $data['unit'] = $branch_units[0]; } else { @@ -2010,11 +2351,11 @@ class ClientController extends AdminController } } else if ($si_or_bp == '3') { - $premium = str_replace(',', '', $this->request->getPost('gpa_sum_premium2[]')); - $sum_insure = str_replace(',', '', $this->request->getPost('gpa_sum_si2[]')); - $multiplier = $this->request->getPost('gpa_sum_multiplier2'); - $grade = $this->request->getPost('gpa_band[]'); - $unit = $this->request->getPost('gpa_unit_3[]'); + $premium = str_replace(',', '', $sanitized_post_data['gpa_sum_premium2[]']); + $sum_insure = str_replace(',', '', $sanitized_post_data['gpa_sum_si2[]']); + $multiplier = $sanitized_post_data['gpa_sum_multiplier2']; + $grade = $sanitized_post_data['gpa_band[]']; + $unit = $sanitized_post_data['gpa_unit_3[]']; for ($i = 0; $i < count($premium); $i++) { @@ -2022,7 +2363,7 @@ class ClientController extends AdminController $data['premium'] = $premium[$i]; $data['grade'] = $grade[$i]; $data['multiplier'] = $multiplier; - $data['si_or_bp'] = $this->request->getPost('si_or_bp'); + $data['si_or_bp'] = $sanitized_post_data['si_or_bp']; if (empty($unit) || !isset($unit[$i]) || empty($unit[$i])) { $data['unit'] = $branch_units[0]; } else { @@ -2033,17 +2374,17 @@ class ClientController extends AdminController } } else if ($si_or_bp == '2') { - $premium = str_replace(',', '', $this->request->getPost('gpa_basic_premium[]')); - $sum_insure = str_replace(',', '', $this->request->getPost('gpa_basic_si[]')); - $basic_pay = str_replace(',', '', $this->request->getPost('basic_pay[]')); - $unit = $this->request->getPost('gpa_unit[]'); + $premium = str_replace(',', '', $sanitized_post_data['gpa_basic_premium[]']); + $sum_insure = str_replace(',', '', $sanitized_post_data['gpa_basic_si[]']); + $basic_pay = str_replace(',', '', $sanitized_post_data['basic_pay[]']); + $unit = $sanitized_post_data['gpa_unit[]']; for ($i = 0; $i < count($premium); $i++) { - $data['si_or_bp'] = $this->request->getPost('si_or_bp'); - $data['basic_multiplier'] = str_replace(',', '', $this->request->getPost('basic_multiplier')); - $data['multiplier'] = $this->request->getPost('premium_multiplier'); + $data['si_or_bp'] = $sanitized_post_data['si_or_bp']; + $data['basic_multiplier'] = str_replace(',', '', $sanitized_post_data['basic_multiplier']); + $data['multiplier'] = $sanitized_post_data['premium_multiplier']; $data['basic_pay'] = $basic_pay[$i]; $data['si'] = $sum_insure[$i]; $data['premium'] = $premium[$i]; @@ -2057,23 +2398,23 @@ class ClientController extends AdminController } } else { - $data['premium'] = str_replace(',', '', $this->request->getPost('gpa_basic_premium')); - $data['si'] = str_replace(',', '', $this->request->getPost('gpa_basic_si')); - $data['basic_multiplier'] = str_replace(',', '', $this->request->getPost('basic_multiplier')); - $data['multiplier'] = $this->request->getPost('premium_multiplier'); - $data['basic_pay'] = str_replace(',', '', $this->request->getPost('basic_pay')); - $data['si_or_bp'] = $this->request->getPost('si_or_bp'); + $data['premium'] = str_replace(',', '', $sanitized_post_data['gpa_basic_premium']); + $data['si'] = str_replace(',', '', $sanitized_post_data['gpa_basic_si']); + $data['basic_multiplier'] = str_replace(',', '', $sanitized_post_data['basic_multiplier']); + $data['multiplier'] = $sanitized_post_data['premium_multiplier']; + $data['basic_pay'] = str_replace(',', '', $sanitized_post_data['basic_pay']); + $data['si_or_bp'] = $sanitized_post_data['si_or_bp']; $policyPremium = $this->policyPremium1Model->insert($data); } - $data = $this->request->getPost(); + $data = $sanitized_post_data; $insert = true; } else if ($policy_grid_id == '2') { - $premium = $this->request->getPost('gpa_premium29[]'); - $sum_insure = $this->request->getPost('gpa_si29[]'); - $unit = $this->request->getPost('gpa_unit29[]'); + $premium = $sanitized_post_data['gpa_premium29[]']; + $sum_insure = $sanitized_post_data['gpa_si29[]']; + $unit = $sanitized_post_data['gpa_unit29[]']; for ($i = 0; $i < count($premium); $i++) { $data['premium'] = str_replace(',', '', $premium[$i]); @@ -2086,13 +2427,13 @@ class ClientController extends AdminController $dataa = $this->policyPremium1Model->insert($data); } - $data = $this->request->getPost(); + $data = $sanitized_post_data; $insert = true; } else if ($policy_grid_id == '3') { - $premium = $this->request->getPost('3_premium[]'); - $sum_insure = $this->request->getPost('3_si[]'); - $unit = $this->request->getPost('3_unit[]'); + $premium = $sanitized_post_data['3_premium[]']; + $sum_insure = $sanitized_post_data['3_si[]']; + $unit = $sanitized_post_data['3_unit[]']; for ($i = 0; $i < count($premium); $i++) { $data['premium'] = str_replace(',', '', $premium[$i]); @@ -2104,15 +2445,15 @@ class ClientController extends AdminController } $dataa = $this->policyPremium2Model->insert($data); } - $data = $this->request->getPost(); + $data = $sanitized_post_data; $insert = true; } else if ($policy_grid_id == '4') { - $premium = $this->request->getPost('4_premium[]'); - $sum_insure = $this->request->getPost('4_si'); - $age_from = $this->request->getPost('4_age_from[]'); - $age_to = $this->request->getPost('4_age_to[]'); - $unit = $this->request->getPost('4_unit[]'); + $premium = $sanitized_post_data['4_premium[]']; + $sum_insure = $sanitized_post_data['4_si']; + $age_from = $sanitized_post_data['4_age_from[]']; + $age_to = $sanitized_post_data['4_age_to[]']; + $unit = $sanitized_post_data['4_unit[]']; for ($i = 0; $i < count($premium); $i++) { $data['premium'] = str_replace(',', '', $premium[$i]); @@ -2127,15 +2468,15 @@ class ClientController extends AdminController $dataa = $this->policyPremium2Model->insert($data); } - $data = $this->request->getPost(); + $data = $sanitized_post_data; $insert = true; } else if ($policy_grid_id == '5') { - $premium = $this->request->getPost('5_premium[]'); - $sum_insure = $this->request->getPost('5_si[]'); - $age_from = $this->request->getPost('5_age_from[]'); - $age_to = $this->request->getPost('5_age_to[]'); - $unit = $this->request->getPost('5_unit[]'); + $premium = $sanitized_post_data['5_premium[]']; + $sum_insure = $sanitized_post_data['5_si[]']; + $age_from = $sanitized_post_data['5_age_from[]']; + $age_to = $sanitized_post_data['5_age_to[]']; + $unit = $sanitized_post_data['5_unit[]']; for ($i = 0; $i < count($premium); $i++) { $data['premium'] = str_replace(',', '', $premium[$i]); @@ -2151,15 +2492,15 @@ class ClientController extends AdminController $dataa = $this->policyPremium2Model->insert($data); } - $data = $this->request->getPost(); + $data = $sanitized_post_data; $insert = true; } else if ($policy_grid_id == '6') { - $premium = $this->request->getPost('6_premium[]'); - $sum_insure = $this->request->getPost('6_si'); - $age_from = $this->request->getPost('6_age_from[]'); - $age_to = $this->request->getPost('6_age_to[]'); - $unit = $this->request->getPost('6_unit[]'); + $premium = $sanitized_post_data['6_premium[]']; + $sum_insure = $sanitized_post_data['6_si']; + $age_from = $sanitized_post_data['6_age_from[]']; + $age_to = $sanitized_post_data['6_age_to[]']; + $unit = $sanitized_post_data['6_unit[]']; for ($i = 0; $i < count($premium); $i++) { $data['premium'] = str_replace(',', '', $premium[$i]); @@ -2174,14 +2515,14 @@ class ClientController extends AdminController $dataa = $this->policyPremium2Model->insert($data); } - $data = $this->request->getPost(); + $data = $sanitized_post_data; $insert = true; } else if ($policy_grid_id == '7') { - $premium = $this->request->getPost('7_premium[]'); - $sum_insure = $this->request->getPost('7_si[]'); - $age_from = $this->request->getPost('7_age_from[]'); - $age_to = $this->request->getPost('7_age_to[]'); - $unit = $this->request->getPost('7_unit[]'); + $premium = $sanitized_post_data['7_premium[]']; + $sum_insure = $sanitized_post_data['7_si[]']; + $age_from = $sanitized_post_data['7_age_from[]']; + $age_to = $sanitized_post_data['7_age_to[]']; + $unit = $sanitized_post_data['7_unit[]']; for ($i = 0; $i < count($premium); $i++) { $data['premium'] = str_replace(',', '', $premium[$i]); @@ -2196,13 +2537,13 @@ class ClientController extends AdminController $dataa = $this->policyPremium2Model->insert($data); } - $data = $this->request->getPost(); + $data = $sanitized_post_data; $insert = true; } else if ($policy_grid_id == '8') { - $premium = $this->request->getPost('8_premium[]'); - $sum_insure = $this->request->getPost('8_si[]'); - $grade = $this->request->getPost('8_grade[]'); - $unit = $this->request->getPost('8_unit[]'); + $premium = $sanitized_post_data['8_premium[]']; + $sum_insure = $sanitized_post_data['8_si[]']; + $grade = $sanitized_post_data['8_grade[]']; + $unit = $sanitized_post_data['8_unit[]']; for ($i = 0; $i < count($premium); $i++) { $data['premium'] = str_replace(',', '', $premium[$i]); @@ -2216,13 +2557,13 @@ class ClientController extends AdminController $dataa = $this->policyPremium2Model->insert($data); } - $data = $this->request->getPost(); + $data = $sanitized_post_data; $insert = true; } else if ($policy_grid_id == '9') { - $premium = $this->request->getPost('gpa_premium29[]'); - $sum_insure = $this->request->getPost('gpa_si29[]'); - $unit = $this->request->getPost('gpa_unit29[]'); + $premium = $sanitized_post_data['gpa_premium29[]']; + $sum_insure = $sanitized_post_data['gpa_si29[]']; + $unit = $sanitized_post_data['gpa_unit29[]']; for ($i = 0; $i < count($premium); $i++) { $data['premium'] = str_replace(',', '', $premium[$i]); @@ -2235,14 +2576,14 @@ class ClientController extends AdminController $dataa = $this->policyPremium2Model->insert($data); } - $data = $this->request->getPost(); + $data = $sanitized_post_data; $insert = true; } else if ($policy_grid_id == '10') { - $premium = $this->request->getPost('10_premium[]'); - $sum_insure = $this->request->getPost('10_si[]'); - $age_from = $this->request->getPost('10_age_from[]'); - $age_to = $this->request->getPost('10_age_to[]'); - $unit = $this->request->getPost('10_unit[]'); + $premium = $sanitized_post_data['10_premium[]']; + $sum_insure = $sanitized_post_data['10_si[]']; + $age_from = $sanitized_post_data['10_age_from[]']; + $age_to = $sanitized_post_data['10_age_to[]']; + $unit = $sanitized_post_data['10_unit[]']; for ($i = 0; $i < count($premium); $i++) { $data['premium'] = str_replace(',', '', $premium[$i]); @@ -2258,15 +2599,15 @@ class ClientController extends AdminController $policyPremium = $this->policyPremium2Model->insert($data); } - $data = $this->request->getPost(); + $data = $sanitized_post_data; $insert = true; } else if ($policy_grid_id == '11') { - $premium = $this->request->getPost('11_premium[]'); - $sum_insure = $this->request->getPost('11_si[]'); - $grade = $this->request->getPost('11_grade[]'); - $max_sum_insure = $this->request->getPost('11_max_si[]'); - $unit = $this->request->getPost('11_unit[]'); + $premium = $sanitized_post_data['11_premium[]']; + $sum_insure = $sanitized_post_data['11_si[]']; + $grade = $sanitized_post_data['11_grade[]']; + $max_sum_insure = $sanitized_post_data['11_max_si[]']; + $unit = $sanitized_post_data['11_unit[]']; for ($i = 0; $i < count($premium); $i++) { $data['premium'] = str_replace(',', '', $premium[$i]); @@ -2281,14 +2622,14 @@ class ClientController extends AdminController $dataa = $this->policyPremium2Model->insert($data); } - $data = $this->request->getPost(); + $data = $sanitized_post_data; $insert = true; } else if ($policy_grid_id == '12') { - $premium = $this->request->getPost('12_premium[]'); - $sum_insure = $this->request->getPost('12_si[]'); - $relationship = $this->request->getPost('12_relationship[]'); - $unit = $this->request->getPost('12_unit[]'); + $premium = $sanitized_post_data['12_premium[]']; + $sum_insure = $sanitized_post_data['12_si[]']; + $relationship = $sanitized_post_data['12_relationship[]']; + $unit = $sanitized_post_data['12_unit[]']; for ($i = 0; $i < count($premium); $i++) { $data['premium'] = str_replace(',', '', $premium[$i]); @@ -2302,16 +2643,16 @@ class ClientController extends AdminController $dataa = $this->policyPremium2Model->insert($data); } - $data = $this->request->getPost(); + $data = $sanitized_post_data; $insert = true; } else if ($policy_grid_id == '13') { - $premium = $this->request->getPost('13_premium[]'); - $sum_insure = $this->request->getPost('13_si[]'); - $age_from = $this->request->getPost('13_age_from[]'); - $age_to = $this->request->getPost('13_age_to[]'); - $relationship = $this->request->getPost('13_relationship[]'); - $unit = $this->request->getPost('13_unit[]'); + $premium = $sanitized_post_data['13_premium[]']; + $sum_insure = $sanitized_post_data['13_si[]']; + $age_from = $sanitized_post_data['13_age_from[]']; + $age_to = $sanitized_post_data['13_age_to[]']; + $relationship = $sanitized_post_data['13_relationship[]']; + $unit = $sanitized_post_data['13_unit[]']; for ($i = 0; $i < count($premium); $i++) { $data['premium'] = str_replace(',', '', $premium[$i]); @@ -2327,7 +2668,7 @@ class ClientController extends AdminController $dataa = $this->policyPremium2Model->insert($data); } - $data = $this->request->getPost(); + $data = $sanitized_post_data; $insert = true; } @@ -2498,10 +2839,11 @@ class ClientController extends AdminController if(empty($params) && $this->request){ $data = $this->request->getPost(); + $sanitized_post_data = sanitizeInputArrayAdvanced($data); $files = $this->request->getFiles(); - $client_id = $data['client_id'] ?? null; - $vehicle_id = $data['vehicle_id'] ?? null; - $docs_name = $data['other_docs_name'] ?? null; + $client_id = $sanitized_post_data['client_id'] ?? null; + $vehicle_id = $sanitized_post_data['vehicle_id'] ?? null; + $docs_name = $sanitized_post_data['other_docs_name'] ?? null; }else { $client_id = $params['client_id'] ?? null; $vehicle_id = $params['vehicle_id'] ?? null; @@ -2552,8 +2894,8 @@ class ClientController extends AdminController if (!empty($insertedDocs)) { // Fetch all documents for the client $vehicleDocs = $this->clientKYCDocsModel - ->where('client_id', $data['client_id']) - ->where('vehicle_id', $data['vehicle_id']) + ->where('client_id', $sanitized_post_data['client_id']) + ->where('vehicle_id', $sanitized_post_data['vehicle_id']) ->findAll(); return $this->respond(['status' => true, 'code' => 200, 'vehicle_docs' => $vehicleDocs, 'inserted_docs' => $insertedDocs, 'message' => 'File uploaded successfully'], 200); } else { @@ -5192,12 +5534,72 @@ class ClientController extends AdminController public function createVehicleWithMinimalData() { + $rules = [ + 'Owner_type' => [ + 'rules' => 'required|in_list[1,2]', + 'errors' => [ + 'required' => 'Owner type is required', + 'in_list' => 'Invalid owner type selected' + ] + ], + 'vehicle_no' => [ + 'rules' => 'required|regex_match[/^[A-Z]{2}[0-9]{2}[A-Z]{1,2}[0-9]{4}$/]', + 'errors' => [ + 'required' => 'Vehicle number is required', + 'regex_match' => 'Invalid Vehicle Number. Example: TN22AB1234' + ] + ], + 'rc' => [ + 'rules' => 'required|trim', + 'errors' => [ + 'required' => 'RC Book number is required' + ] + ], + + 'type' => [ + 'rules' => 'required|is_natural_no_zero', + 'errors' => [ + 'required' => 'Vehicle type is required' + ] + ], + + 'description' => [ + 'rules' => 'required|is_natural_no_zero', + 'errors' => [ + 'required' => 'Vehicle description is required' + ] + ], + 'owner' => [ + 'rules' => 'required|is_natural_no_zero', + 'errors' => [ + 'required' => 'Owner is required' + ] + ], + + 'old_onwer' => [ + 'rules' => 'permit_empty|alpha_space', + 'errors' => [ + 'alpha_space' => 'Old owner name can contain only letters and spaces' + ] + ], + + ]; + if (!$this->validate($rules)) { + return $this->response->setStatusCode(400)->setJSON([ + 'status' => false, + 'message' => 'Input validation failed', + 'code' => 400, + 'errors' => $this->validator->getErrors() + ]); + } $data = $this->request->getPost(); - $id = $this->request->getPost('vehicle_primary_key'); + $sanitized_post_data = sanitizeInputArrayAdvanced($data); + $id = $sanitized_post_data['vehicle_primary_key']; + if ($id) { - $vehicle_update = $this->vehicleModel->where('id', $id)->set($data)->update(); + $vehicle_update = $this->vehicleModel->where('id', $id)->set($sanitized_post_data)->update(); if ($vehicle_update) { return $this->respond(['status' => true, 'message' => 'Vehicle details updated successfully'], 200); @@ -5206,7 +5608,7 @@ class ClientController extends AdminController } } else { - $vehicle_insert = $this->vehicleModel->insert($data); + $vehicle_insert = $this->vehicleModel->insert($sanitized_post_data); if ($vehicle_insert) { @@ -5219,9 +5621,9 @@ class ClientController extends AdminController return $this->respond([ 'status' => true, 'vehicle_id' => $vehicle_insert, - 'owner_id' => $data['owner'], - 'owner_branch_id' => $data['branch_id'] ?? null, - 'owner_type' => $data['Owner_type'], + 'owner_id' => $sanitized_post_data['owner'], + 'owner_branch_id' => $sanitized_post_data['branch_id'] ?? null, + 'owner_type' => $sanitized_post_data['Owner_type'], 'vehicles' => $vehicles, 'message' => 'Vehicle created successfully ' diff --git a/app/Controllers/EmployeeController.php b/app/Controllers/EmployeeController.php index 1f996e53..41eef6df 100755 --- a/app/Controllers/EmployeeController.php +++ b/app/Controllers/EmployeeController.php @@ -2676,12 +2676,73 @@ class EmployeeController extends AdminController //UPDATE EMPLOYEE public function update_emp_data() { - $data = $this->request->getPost(); + + $rules = [ + 'emp_code' => [ + 'rules' => 'required', + 'errors' => [ + 'required' => 'Employee Code is missing' + ] + ], + + 'name' => [ + 'rules' => 'required|min_length[2]|max_length[100]', + 'errors' => [ + 'required' => 'Employee name is required', + 'min_length' => 'Name must be at least 2 characters', + 'max_length' => 'Name cannot exceed 100 characters' + ] + ], + 'gender' => [ + 'rules' => 'permit_empty|in_list[M,F]', + 'errors' => [ + 'in_list' => 'Invalid gender selected' + ] + ], + 'email_corporate' => [ + 'rules' => 'required|valid_email', + 'errors' => [ + 'required' => 'Email is required', + 'valid_email' => 'Enter a valid email address' + ] + ], + + 'mobile' => [ + 'rules' => 'required|numeric|exact_length[10]', + 'errors' => [ + 'required' => 'Mobile number is required', + 'numeric' => 'Mobile number must contain digits only', + 'exact_length' => 'Mobile number must be exactly 10 digits' + ] + ], + ]; + $request_post_data = $this->request->getPost(); + $data = sanitizeInputArrayAdvanced($request_post_data); + if (isset($data['relationship'])) { + $rules['relationship'] = [ + 'rules' => 'required|in_list[Self,Spouse,Child,Father,Mother,Father-in-law,Mother-in-law]', + 'errors' => [ + 'required' => 'Relationship is required', + 'in_list' => 'The selected relationship is invalid.' + ] + ]; + } + + + if (!$this->validate($rules)) { + return $this->response->setStatusCode(400)->setJSON([ + 'status' => false, + 'message' => 'Input validation failed', + 'code' => 400, + 'errors' => $this->validator->getErrors() + ]); + } + + + // print_rr($data);die(); // $data['dob'] = date('Y-m-d', strtotime($data['dob'])); - if(isset( $data['dob'])){ - $data['dob'] = change_date_format($data['dob'], null, 'Y-m-d'); - } + $data['dob'] = (!empty($data['dob'])) ? change_date_format($data['dob'], null, 'Y-m-d') : null; // print_rr($data); die; // Fetch current employee data @@ -2971,12 +3032,15 @@ class EmployeeController extends AdminController } public function mapEmployees(){ - $client_id = $this->request->getPost('client_id'); - $branch_id = $this->request->getPost('branch_id'); - $policy_id = $this->request->getPost('client_policy_id'); - $selected_employees = (array)$this->request->getPost('selected'); - $si_amt = $this->request->getPost('si_amt'); - $policy_start_date_unformatted = $this->request->getPost('policy_start_date'); + $request_post_data = $this->request->getPost(); + $sanitized_post_data = sanitizeInputArrayAdvanced($request_post_data); + + $client_id = $sanitized_post_data['client_id']; + $branch_id = $sanitized_post_data['branch_id']; + $policy_id = $sanitized_post_data['client_policy_id']; + $selected_employees = (array)$sanitized_post_data['selected']; + $si_amt = $sanitized_post_data['si_amt']; + $policy_start_date_unformatted = $sanitized_post_data['policy_start_date']; $policy_start_date = change_date_format($policy_start_date_unformatted, 'd/M/Y', 'Y-m-d'); @@ -3013,7 +3077,9 @@ class EmployeeController extends AdminController } public function unmapEmployees($actionType){ - $selected_employees = (array)$this->request->getPost('selected'); + $request_post_data = $this->request->getPost(); + $sanitized_post_data = sanitizeInputArrayAdvanced($request_post_data); + $selected_employees = (array)$sanitized_post_data['selected']; if($actionType == 0){ for($i = 0;$iemployeeModel->set(['client_id' => null, 'client_branch_id' => null])->where('id',$selected_employees[$i])->update();log_message('error',$result1); @@ -3273,7 +3339,31 @@ class EmployeeController extends AdminController public function retailendorsementsave() { try { - $data = $this->request->getPost(); + $rules = [ + 'endorsement_no' => [ + 'rules' => 'required', + 'errors' => [ + 'required' => 'Endorsement Number is missing' + ] + ], + 'status' => [ + 'rules' => 'required', + 'errors' => [ + 'required' => 'Status is required', + ] + ] + ]; + if (!$this->validate($rules)) { + return $this->response->setStatusCode(400)->setJSON([ + 'status' => false, + 'message' => 'Input validation failed', + 'code' => 400, + 'errors' => $this->validator->getErrors() + ]); + } + $request_post_data = $this->request->getPost(); + $data = sanitizeInputArrayAdvanced($request_post_data); + if (!empty($data['id'])) { $text = "update"; $updateID = $data['id']; diff --git a/app/Controllers/LeadsController.php b/app/Controllers/LeadsController.php index 22300690..8154fc82 100644 --- a/app/Controllers/LeadsController.php +++ b/app/Controllers/LeadsController.php @@ -378,7 +378,95 @@ class LeadsController extends BaseController private function prepareLeadData() { - $data = $this->request->getPost(); + $rules = [ + 'lead_type' => [ + 'rules' => 'required', + 'errors' => ['required' => 'Lead Type is required'] + ], + 'issuer' => [ + 'rules' => 'required', + 'errors' => ['required' => 'Issuer is required'] + ], + 'entity_type_id' => [ + 'rules' => 'required', + 'errors' => ['required' => 'Entity Type is required'] + ], + 'client_name' => [ + 'rules' => 'required', + 'errors' => ['required' => 'Client Name is required'] + ], + 'client_short_name' => [ + 'rules' => 'required', + 'errors' => ['required' => 'Client Short Name is required'] + ], + 'gst' => [ + 'rules' => 'required', + 'errors' => ['required' => 'GST Number is required'] + ], + 'branch_name' => [ + 'rules' => 'required', + 'errors' => ['required' => 'Branch Name is required'] + ], + 'branch_code' => [ + 'rules' => 'required', + 'errors' => ['required' => 'Branch Code is required'] + ], + 'contact_person_name' => [ + 'rules' => 'required', + 'errors' => ['required' => 'Contact Person Name is required'] + ], + 'contact_person_mobile' => [ + 'rules' => 'required', + 'errors' => ['required' => 'Contact Person Mobile is required'] + ], + 'contact_person_email' => [ + 'rules' => 'required|valid_email', + 'errors' => [ + 'required' => 'Contact Person Email is required', + 'valid_email' => 'Please enter a valid email address' + ] + ], + 'salse_person_id' => [ + 'rules' => 'required', + 'errors' => ['required' => 'Sales Person is required'] + ], + 'status' => [ + 'rules' => 'required', + 'errors' => ['required' => 'Status is required'] + ] + ]; + $request_data = $this->request->getPost(); + $data = sanitizeInputArrayAdvanced($request_data); + if($data['lead_form_type'] == 2){ + $rules['client_type'] = [ + 'rules' => 'required', + 'errors' => ['required' => 'Client Type is required'] + ]; + $rules['policy_type_id'] = [ + 'rules' => 'required', + 'errors' => ['required' => 'Policy Type is required'] + ]; + $rules['policy_start_date'] = [ + 'rules' => 'required', + 'errors' => ['required' => 'Date of Commencement is required'] + ]; + $rules['policy_end_date'] = [ + 'rules' => 'required', + 'errors' => ['required' => 'Date of Expiry is required'] + ]; + } + + if (!$this->validate($rules)) { + return $this->response->setStatusCode(400)->setJSON([ + 'status' => false, + 'message' => 'Input validation failed', + 'code' => 400, + 'errors' => $this->validator->getErrors() + ]); + } + + + $data['client_type'] = 1; $data['pan'] = ""; @@ -5739,7 +5827,7 @@ class LeadsController extends BaseController $first_file_name = $isFirstField ? 'Member List' : ''; $member_data_link = $isFirstField ? $sample_dwn_link : ''; $read_only = $isFirstField ? 'readonly' : ''; - $accept = $isFirstField ? '.xls,.xlsx' : ''; + $accept = $isFirstField ? '.xls,.xlsx' : '.xls,.xlsx,.pdf,.jpg,.jpeg,.png'; $displayIndex = $index + 1; $html .= ' diff --git a/app/Controllers/MasterController.php b/app/Controllers/MasterController.php index 475c8a97..be71e82c 100755 --- a/app/Controllers/MasterController.php +++ b/app/Controllers/MasterController.php @@ -283,26 +283,53 @@ class MasterController extends AdminController { $this->myLogger->logme('error','Insurer general info function called'); + $rules = [ + 'name' => [ + 'rules' => 'required', + 'errors' => [ + 'required' => 'Name is required' + ] + ], + 'short_name' => [ + 'rules' => 'required|min_length[3]|max_length[8]', + 'errors' => [ + 'required' => 'Short name is required', + 'min_length' => 'Short name must be at least 3 characters', + 'max_length' => 'Short name cannot exceed 8 characters' + ] + ], + 'insurer_logo' => [ + 'rules' => 'if_exist|is_image[insurer_logo]|max_size[insurer_logo,200]|ext_in[insurer_logo,jpg,jpeg,png]', + 'errors' => [ + 'is_image' => 'The uploaded file must be an image', + 'max_size' => 'File size should not exceed 200 KB', + 'ext_in' => 'Allowed file types: jpg, jpeg, png', + ] + ], + ]; + + if (!$this->validate($rules)) { + return $this->response->setStatusCode(400)->setJSON([ + 'status' => false, + 'message' => 'Input validation failed', + 'code' => 400, + 'errors' => $this->validator->getErrors() + ]); + } + $uploadFilePath = ROOTPATH . 'public/uploads/logo/'; $file_name = file_Upload($this->request->getFile('insurer_logo'), $uploadFilePath); $data = $this->request->getPost(); + $sanitized_post_data = sanitizeInputArrayAdvanced($data); - if($this->request->getPost('addition_add_day')){ - $data['addition_add_day'] = 1; - } - - if($this->request->getPost('deletion_add_day')){ - $data['deletion_add_day'] = 1; - } - - if($this->request->getPost('is_multi_event')){ - $data['is_multi_event'] = 1; - } - - $data['created_by'] = get_session_userid(); - $data['insurer_logo'] = $file_name; + $insert_data['addition_add_day'] = (!empty($sanitized_post_data['addition_add_day'])) ? 1 : 0; + $insert_data['deletion_add_day'] = (!empty($sanitized_post_data['deletion_add_day'])) ? 1 : 0; + $insert_data['is_multi_event'] = (!empty($sanitized_post_data['is_multi_event'])) ? 1 : 0; + $insert_data['created_by'] = get_session_userid(); + $insert_data['insurer_logo'] = $file_name; - $insert = $this->insurerModel->insert($data); + $insert = $this->insurerModel->insert($insert_data); + if($insert){ $insurer_data = $this->insurerModel->where(['id' => $insert, 'is_active' => 1])->first(); $insurer_templete_count = $this->insurerTemplateModel->where(['insurer_id' => $insert, 'is_active' => 1])->countAllResults(); @@ -316,28 +343,129 @@ class MasterController extends AdminController { $this->myLogger->logme('error','Client branch CREATE function called'); + $rules = [ + + // ====================== + // Branch Details + // ====================== + 'branch_name' => [ + 'rules' => 'required|trim', + 'errors' => [ + 'required' => 'Branch name is required' + ] + ], + + 'branch_code' => [ + 'rules' => 'required|trim', + 'errors' => [ + 'required' => 'Branch code is required' + ] + ], + + 'address1' => [ + 'rules' => 'required|trim', + 'errors' => [ + 'required' => 'Address Line 1 is required' + ] + ], + + 'state' => [ + 'rules' => 'required|is_natural_no_zero', + 'errors' => [ + 'required' => 'State is required' + ] + ], + + 'district' => [ + 'rules' => 'required|trim', + 'errors' => [ + 'required' => 'District is required' + ] + ], + + 'city' => [ + 'rules' => 'required|trim', + 'errors' => [ + 'required' => 'City is required' + ] + ], + + 'pincode' => [ + 'rules' => 'required|numeric|exact_length[6]', + 'errors' => [ + 'required' => 'Pincode is required', + 'numeric' => 'Pincode must contain only numbers', + 'exact_length' => 'Pincode must be exactly 6 digits' + ] + ], + + // ====================== + // Contact Details (Array) + // ====================== + 'name.*' => [ + 'rules' => 'required|trim|min_length[2]', + 'errors' => [ + 'required' => 'Contact name is required', + 'min_length' => 'Contact name must be at least 2 characters' + ] + ], + + 'designation.*' => [ + 'rules' => 'required|trim', + 'errors' => [ + 'required' => 'Designation is required' + ] + ], + + 'email.*' => [ + 'rules' => 'required|valid_email', + 'errors' => [ + 'required' => 'Email is required', + 'valid_email' => 'Invalid email format' + ] + ], + + 'mobile.*' => [ + 'rules' => 'required|numeric|exact_length[10]', + 'errors' => [ + 'required' => 'Mobile number is required', + 'numeric' => 'Mobile must contain only digits', + 'exact_length' => 'Mobile number must be exactly 10 digits' + ] + ], + ]; + + if (!$this->validate($rules)) { + return $this->response->setStatusCode(400)->setJSON([ + 'status' => false, + 'message' => 'Input validation failed', + 'code' => 400, + 'errors' => $this->validator->getErrors() + ]); + } $data = $this->request->getPost(); - $data['created_by'] = get_session_userid(); - $insert = $this->insurerBranchModel->insert($data); + $sanitized_post_data = sanitizeInputArrayAdvanced($data); + $sanitized_post_data['created_by'] = get_session_userid(); + $insert = $this->insurerBranchModel->insert($sanitized_post_data); if($insert){ - for ($i = 0; $i < count($this->request->getPost('name')); $i++) { + for ($i = 0; $i < count($sanitized_post_data('name')); $i++) { // Prepare data to insert - $data = [ + $sanitized_post_data_for_level = [ 'contact_type' => 'insurer', 'ref_id' => $insert, 'created_by' => get_session_userid(), - 'name' => $this->request->getPost('name')[$i], - 'email' => $this->request->getPost('email')[$i], - 'mobile' => $this->request->getPost('mobile')[$i], - 'designation' => $this->request->getPost('designation')[$i] + 'name' => $sanitized_post_data['name'][$i], + 'email' => $sanitized_post_data['email'][$i], + 'mobile' => $sanitized_post_data['mobile'][$i], + 'designation' => $sanitized_post_data['designation'][$i] ]; - $contacts = $this->levelContactModel->insert($data); + $contacts = $this->levelContactModel->insert($sanitized_post_data_for_level); } } if($insert){ - $branchData = $this->insurerBranchModel->where('insurer_id', $this->request->getPost('insurer_id'))->findAll(); + $branchData = $this->insurerBranchModel->where('insurer_id', $sanitized_post_data_for_level['insurer_id'])->findAll(); echo json_encode(array("status" => true , 'data' => $branchData)); }else{ echo json_encode(array("status" => false)); @@ -367,38 +495,59 @@ class MasterController extends AdminController public function editInsurerGeneralInfo() { - $this->myLogger->logme('error','edit Insurer general info function called'); + + $this->myLogger->logme('error','Edit Insurer general info function called'); + $rules = [ + 'name' => [ + 'rules' => 'required', + 'errors' => [ + 'required' => 'Name is required' + ] + ], + 'short_name' => [ + 'rules' => 'required|min_length[3]|max_length[8]', + 'errors' => [ + 'required' => 'Short name is required', + 'min_length' => 'Short name must be at least 3 characters', + 'max_length' => 'Short name cannot exceed 8 characters' + ] + ], + 'insurer_logo' => [ + 'rules' => 'if_exist|is_image[insurer_logo]|max_size[insurer_logo,200]|ext_in[insurer_logo,jpg,jpeg,png]', + 'errors' => [ + 'is_image' => 'The uploaded file must be an image', + 'max_size' => 'File size should not exceed 200 KB', + 'ext_in' => 'Allowed file types: jpg, jpeg, png', + ] + ], + ]; + + if (!$this->validate($rules)) { + return $this->response->setStatusCode(400)->setJSON([ + 'status' => false, + 'message' => 'Input validation failed', + 'code' => 400, + 'errors' => $this->validator->getErrors() + ]); + } $uploadFilePath = ROOTPATH . 'public/uploads/logo/'; - $file_name = file_Upload($this->request->getFile('insurer_logo'), $uploadFilePath); - - $id = $this->request->getPost('PrimaryKey'); - $data = $this->request->getPost(); - $data['updated_by'] = get_session_userid(); - + $file_name = file_Upload($this->request->getFile('insurer_logo'), $uploadFilePath); + $data = $this->request->getPost(); + $sanitized_post_data = sanitizeInputArrayAdvanced($data); + $id = $sanitized_post_data['PrimaryKey']; + + $update_data['addition_add_day'] = (!empty($sanitized_post_data['addition_add_day'])) ? 1 : 0; + $update_data['deletion_add_day'] = (!empty($sanitized_post_data['deletion_add_day'])) ? 1 : 0; + $update_data['is_multi_event'] = (!empty($sanitized_post_data['is_multi_event'])) ? 1 : 0; + $update_data['updated_by'] = get_session_userid(); + if(!empty($file_name)){ - $data['insurer_logo'] = $file_name; + $update_data['insurer_logo'] = $file_name; } - if($this->request->getPost('addition_add_day')){ - $data['addition_add_day'] = 1; - }else{ - $data['addition_add_day'] = 0; - } + $update = $this->insurerModel->update($id,$update_data); - if($this->request->getPost('deletion_add_day')){ - $data['deletion_add_day'] = 1; - }else{ - $data['deletion_add_day'] = 0; - } - - if($this->request->getPost('is_multi_event')){ - $data['is_multi_event'] = 1; - }else{ - $data['is_multi_event'] = 0; - } - - $update = $this->insurerModel->update($id,$data); if($update){ echo json_encode(array("status" => true , 'data' => $data)); }else{ @@ -422,33 +571,133 @@ class MasterController extends AdminController public function editInsurerBranch() { - $this->myLogger->logme('error','Insurer branch CREATE function called'); - $id = $this->request->getPost('PrimaryKey'); - $data = $this->request->getPost(); - $update = $this->insurerBranchModel->update($id, $data); + $this->myLogger->logme('error','Insurer branch EDIT function called'); + $rules = [ + + // ====================== + // Branch Details + // ====================== + 'branch_name' => [ + 'rules' => 'required|trim', + 'errors' => [ + 'required' => 'Branch name is required' + ] + ], + + 'branch_code' => [ + 'rules' => 'required|trim', + 'errors' => [ + 'required' => 'Branch code is required' + ] + ], + + 'address1' => [ + 'rules' => 'required|trim', + 'errors' => [ + 'required' => 'Address Line 1 is required' + ] + ], + + 'state' => [ + 'rules' => 'required|is_natural_no_zero', + 'errors' => [ + 'required' => 'State is required' + ] + ], + + 'district' => [ + 'rules' => 'required|trim', + 'errors' => [ + 'required' => 'District is required' + ] + ], + + 'city' => [ + 'rules' => 'required|trim', + 'errors' => [ + 'required' => 'City is required' + ] + ], + + 'pincode' => [ + 'rules' => 'required|numeric|exact_length[6]', + 'errors' => [ + 'required' => 'Pincode is required', + 'numeric' => 'Pincode must contain only numbers', + 'exact_length' => 'Pincode must be exactly 6 digits' + ] + ], + + // ====================== + // Contact Details (Array) + // ====================== + 'name.*' => [ + 'rules' => 'required|trim|min_length[2]', + 'errors' => [ + 'required' => 'Contact name is required', + 'min_length' => 'Contact name must be at least 2 characters' + ] + ], + + 'designation.*' => [ + 'rules' => 'required|trim', + 'errors' => [ + 'required' => 'Designation is required' + ] + ], + + 'email.*' => [ + 'rules' => 'required|valid_email', + 'errors' => [ + 'required' => 'Email is required', + 'valid_email' => 'Invalid email format' + ] + ], + + 'mobile.*' => [ + 'rules' => 'required|numeric|exact_length[10]', + 'errors' => [ + 'required' => 'Mobile number is required', + 'numeric' => 'Mobile must contain only digits', + 'exact_length' => 'Mobile number must be exactly 10 digits' + ] + ], + ]; + if (!$this->validate($rules)) { + return $this->response->setStatusCode(400)->setJSON([ + 'status' => false, + 'message' => 'Input validation failed', + 'code' => 400, + 'errors' => $this->validator->getErrors() + ]); + } + $data = $this->request->getPost(); + $sanitized_post_data = sanitizeInputArrayAdvanced($data); + $id = $sanitized_post_data['PrimaryKey']; + $update = $this->insurerBranchModel->update($id, $sanitized_post_data); if($update){ $contactsToDelete = $this->levelContactModel->where(['ref_id' => $id,'contact_type' => 'insurer', 'is_active' => 1])->get()->getResult(); foreach ($contactsToDelete as $contact) { $this->levelContactModel->delete($contact->id); } - for ($i = 0; $i < count($this->request->getPost('name')); $i++) { + for ($i = 0; $i < count($sanitized_post_data['name']); $i++) { // Prepare data to update - $data = [ + $sanitized_post_data_for_level = [ 'contact_type' => 'insurer', 'ref_id' => $id, 'created_by' => get_session_userid(), - 'name' => $this->request->getPost('name')[$i], - 'email' => $this->request->getPost('email')[$i], - 'mobile' => $this->request->getPost('mobile')[$i], - 'designation' => $this->request->getPost('designation')[$i] + 'name' => $sanitized_post_data['name'][$i], + 'email' => $sanitized_post_data['email'][$i], + 'mobile' => $sanitized_post_data['mobile'][$i], + 'designation' => $sanitized_post_data['designation'][$i] ]; - $contacts = $this->levelContactModel->insert($data); + $contacts = $this->levelContactModel->insert($sanitized_post_data_for_level); } } if($update){ - $branchData = $this->insurerBranchModel->where('insurer_id', $this->request->getPost('insurer_id'))->findAll(); + $branchData = $this->insurerBranchModel->where('insurer_id', $sanitized_post_data['insurer_id'])->findAll(); echo json_encode(array("status" => true , 'data' => $branchData, 'edit')); }else{ echo json_encode(array("status" => false, 'edit')); @@ -594,6 +843,74 @@ class MasterController extends AdminController { $this->myLogger->logme('error','TPA general info function called'); + $rules = [ + + // ====================== + // TPA Basic Details + // ====================== + 'name' => [ + 'rules' => 'required|trim|min_length[2]', + 'errors' => [ + 'required' => 'TPA name is required', + 'min_length' => 'TPA name must be at least 2 characters' + ] + ], + + 'short_name' => [ + 'rules' => 'required|trim|min_length[3]', + 'errors' => [ + 'required' => 'TPA short name is required', + 'min_length' => 'Short name must be at least 3 characters', + ] + ], + + 'network_hospitals' => [ + 'rules' => 'required|valid_url', + 'errors' => [ + 'required' => 'Network hospitals URL is required', + 'valid_url' => 'Please enter a valid URL' + ] + ], + 'tpa_logo' => [ + 'rules' => 'if_exist|is_image[tpa_logo]|max_size[tpa_logo,200]|ext_in[tpa_logo,jpg,jpeg,png]', + 'errors' => [ + 'is_image' => 'TPA logo must be an image', + 'max_size' => 'TPA logo should not exceed 200 KB', + 'ext_in' => 'Allowed logo types: jpg, jpeg, png' + ] + ], + + 'fc' => [ + 'rules' => 'if_exist|is_image[fc]|max_size[fc,500]|ext_in[fc,jpg,jpeg,png]', + 'errors' => [ + 'is_image' => 'Front card must be an image', + 'max_size' => 'Front card image should not exceed 500 KB', + 'ext_in' => 'Allowed types: jpg, jpeg, png' + ] + ], + + 'bc' => [ + 'rules' => 'if_exist|is_image[bc]|max_size[bc,500]|ext_in[bc,jpg,jpeg,png]', + 'errors' => [ + 'is_image' => 'Back card must be an image', + 'max_size' => 'Back card image should not exceed 500 KB', + 'ext_in' => 'Allowed types: jpg, jpeg, png' + ] + ], + ]; + + + if (!$this->validate($rules)) { + return $this->response->setStatusCode(400)->setJSON([ + 'status' => false, + 'message' => 'Input validation failed', + 'code' => 400, + 'errors' => $this->validator->getErrors() + ]); + } + $data = $this->request->getPost(); + $sanitized_post_data = sanitizeInputArrayAdvanced($data); + $uploadFilePath = ROOTPATH . 'public/uploads/logo/'; $file_name = file_Upload($this->request->getFile('tpa_logo'), $uploadFilePath); @@ -603,18 +920,18 @@ class MasterController extends AdminController $back_card_file_name = file_Upload($this->request->getFile('bc'), $template_bg_path); - $eCardTemplate = $this->request->getPost('ecard_content'); - $data = $this->request->getPost(); - $data['created_by'] = get_session_userid(); - $data['tpa_logo'] = $file_name; - $data['front_card'] = $front_card_file_name; - $data['back_card'] = $back_card_file_name; - $data['network_hospitals'] = $this->request->getPost('network_hospitals'); + $eCardTemplate = $sanitized_post_data['ecard_content']; - $insert = $this->tpaModel->insert($data); + $insert_data['created_by'] = get_session_userid(); + $insert_data['tpa_logo'] = $file_name; + $insert_data['front_card'] = $front_card_file_name; + $insert_data['back_card'] = $back_card_file_name; + $insert_data['network_hospitals'] = $sanitized_post_data['network_hospitals']; + + $insert = $this->tpaModel->insert($insert_data); - $tpa_name = (string) $this->request->getPost('name'); - $short_name = (string) $this->request->getPost('short_name'); + $tpa_name = (string) $sanitized_post_data['name']; + $short_name = (string) $sanitized_post_data['short_name']; $filename = strtolower(str_replace(' ', '_', $short_name)) . '.html'; $file_directory = WRITEPATH . 'e_card_template/'; @@ -629,10 +946,10 @@ class MasterController extends AdminController header('Content-type:text/html; charset=utf-8'); // Write the HTML content to the file - $data = file_put_contents($file_path, $eCardTemplate); + $html_data = file_put_contents($file_path, $eCardTemplate); - if ($data !== false) { + if ($html_data !== false) { $this->myLogger->logme('error', 'TPA: {tpa}, e-Card HTML template file saved successfully: {data}, filepath is: {path}', ['data' => $filename, 'tpa' => $tpa_name, 'path' => $file_path]); } else { $this->myLogger->logme('error', 'TPA: {tpa}, e-Card HTML template file unable to save: {data}', ['data' => $filename, 'tpa' => $tpa_name]); @@ -651,28 +968,129 @@ class MasterController extends AdminController { $this->myLogger->logme('error','TPA branch CREATE function called'); + $rules = [ + + // ====================== + // Branch Details + // ====================== + 'branch_name' => [ + 'rules' => 'required|trim', + 'errors' => [ + 'required' => 'Branch name is required' + ] + ], + + 'branch_code' => [ + 'rules' => 'required|trim', + 'errors' => [ + 'required' => 'Branch code is required' + ] + ], + + 'address1' => [ + 'rules' => 'required|trim', + 'errors' => [ + 'required' => 'Address Line 1 is required' + ] + ], + + 'state' => [ + 'rules' => 'required|is_natural_no_zero', + 'errors' => [ + 'required' => 'State is required' + ] + ], + + 'district' => [ + 'rules' => 'required|trim', + 'errors' => [ + 'required' => 'District is required' + ] + ], + + 'city' => [ + 'rules' => 'required|trim', + 'errors' => [ + 'required' => 'City is required' + ] + ], + + 'pincode' => [ + 'rules' => 'required|numeric|exact_length[6]', + 'errors' => [ + 'required' => 'Pincode is required', + 'numeric' => 'Pincode must contain only numbers', + 'exact_length' => 'Pincode must be exactly 6 digits' + ] + ], + + // ====================== + // Contact Details (Array) + // ====================== + 'name.*' => [ + 'rules' => 'required|trim|min_length[2]', + 'errors' => [ + 'required' => 'Contact name is required', + 'min_length' => 'Contact name must be at least 2 characters' + ] + ], + + 'designation.*' => [ + 'rules' => 'required|trim', + 'errors' => [ + 'required' => 'Designation is required' + ] + ], + + 'email.*' => [ + 'rules' => 'required|valid_email', + 'errors' => [ + 'required' => 'Email is required', + 'valid_email' => 'Invalid email format' + ] + ], + + 'mobile.*' => [ + 'rules' => 'required|numeric|exact_length[10]', + 'errors' => [ + 'required' => 'Mobile number is required', + 'numeric' => 'Mobile must contain only digits', + 'exact_length' => 'Mobile number must be exactly 10 digits' + ] + ], + ]; + + if (!$this->validate($rules)) { + return $this->response->setStatusCode(400)->setJSON([ + 'status' => false, + 'message' => 'Input validation failed', + 'code' => 400, + 'errors' => $this->validator->getErrors() + ]); + } $data = $this->request->getPost(); - $data['created_by'] = get_session_userid(); - $insert = $this->tpaBranchModel->insert($data); + $sanitized_post_data = sanitizeInputArrayAdvanced($data); + $sanitized_post_data['created_by'] = get_session_userid(); + $insert = $this->tpaBranchModel->insert($sanitized_post_data); if($insert){ - for ($i = 0; $i < count($this->request->getPost('name')); $i++) { + for ($i = 0; $i < count($sanitized_post_data['name']); $i++) { // Prepare data to insert - $data = [ + $sanitized_post_data_for_level = [ 'contact_type' => 'tpa', 'ref_id' => $insert, 'created_by' => get_session_userid(), - 'name' => $this->request->getPost('name')[$i], - 'email' => $this->request->getPost('email')[$i], - 'mobile' => $this->request->getPost('mobile')[$i], - 'designation' => $this->request->getPost('designation')[$i] + 'name' => $sanitized_post_data['name'][$i], + 'email' => $sanitized_post_data['email'][$i], + 'mobile' => $sanitized_post_data['mobile'][$i], + 'designation' => $sanitized_post_data['designation'][$i] ]; - $contacts = $this->levelContactModel->insert($data); + $contacts = $this->levelContactModel->insert($sanitized_post_data_for_level); } } if($insert){ - $branchData = $this->tpaBranchModel->where('tpa_id', $this->request->getPost('tpa_id'))->findAll(); + $branchData = $this->tpaBranchModel->where('tpa_id', $sanitized_post_data['tpa_id'])->findAll(); echo json_encode(array("status" => true , 'data' => $branchData)); }else{ echo json_encode(array("status" => false)); @@ -715,6 +1133,74 @@ class MasterController extends AdminController public function editTPAGeneralInfo() { $this->myLogger->logme('error','edit TPA general info function called'); + $rules = [ + + // ====================== + // TPA Basic Details + // ====================== + 'name' => [ + 'rules' => 'required|trim|min_length[2]', + 'errors' => [ + 'required' => 'TPA name is required', + 'min_length' => 'TPA name must be at least 2 characters' + ] + ], + + 'short_name' => [ + 'rules' => 'required|trim|min_length[3]', + 'errors' => [ + 'required' => 'TPA short name is required', + 'min_length' => 'Short name must be at least 3 characters', + ] + ], + + 'network_hospitals' => [ + 'rules' => 'required|valid_url', + 'errors' => [ + 'required' => 'Network hospitals URL is required', + 'valid_url' => 'Please enter a valid URL' + ] + ], + 'tpa_logo' => [ + 'rules' => 'if_exist|is_image[tpa_logo]|max_size[tpa_logo,200]|ext_in[tpa_logo,jpg,jpeg,png]', + 'errors' => [ + 'is_image' => 'TPA logo must be an image', + 'max_size' => 'TPA logo should not exceed 200 KB', + 'ext_in' => 'Allowed logo types: jpg, jpeg, png' + ] + ], + + 'fc' => [ + 'rules' => 'if_exist|is_image[fc]|max_size[fc,500]|ext_in[fc,jpg,jpeg,png]', + 'errors' => [ + 'is_image' => 'Front card must be an image', + 'max_size' => 'Front card image should not exceed 500 KB', + 'ext_in' => 'Allowed types: jpg, jpeg, png' + ] + ], + + 'bc' => [ + 'rules' => 'if_exist|is_image[bc]|max_size[bc,500]|ext_in[bc,jpg,jpeg,png]', + 'errors' => [ + 'is_image' => 'Back card must be an image', + 'max_size' => 'Back card image should not exceed 500 KB', + 'ext_in' => 'Allowed types: jpg, jpeg, png' + ] + ], + ]; + + + if (!$this->validate($rules)) { + return $this->response->setStatusCode(400)->setJSON([ + 'status' => false, + 'message' => 'Input validation failed', + 'code' => 400, + 'errors' => $this->validator->getErrors() + ]); + } + $data = $this->request->getPost(); + $sanitized_post_data = sanitizeInputArrayAdvanced($data); + $uploadFilePath = ROOTPATH . 'public/uploads/logo/'; $file_name = file_Upload($this->request->getFile('tpa_logo'), $uploadFilePath); @@ -723,29 +1209,29 @@ class MasterController extends AdminController $front_card_file_name = file_Upload($this->request->getFile('fc'), $template_bg_path); $back_card_file_name = file_Upload($this->request->getFile('bc'), $template_bg_path); - $id = $this->request->getPost('PrimaryKey'); - $data = $this->request->getPost(); - $data['updated_by'] = get_session_userid(); + $id = $sanitized_post_data['PrimaryKey']; + + $update_data['updated_by'] = get_session_userid(); if(!empty($file_name)){ - $data['tpa_logo'] = $file_name; + $update_data['tpa_logo'] = $file_name; } if(!empty($front_card_file_name)){ - $data['front_card'] = $front_card_file_name; + $update_data['front_card'] = $front_card_file_name; } if(!empty($back_card_file_name)){ - $data['back_card'] = $back_card_file_name; + $update_data['back_card'] = $back_card_file_name; } - $data['network_hospitals'] = $this->request->getPost('network_hospitals'); - $update = $this->tpaModel->update($id,$data); + $update_data['network_hospitals'] = $sanitized_post_data['network_hospitals']; + $update = $this->tpaModel->update($id,$update_data); - $tpa_name = (string) $this->request->getPost('name'); - $short_name = (string) $this->request->getPost('short_name'); - $eCardTemplate = $this->request->getPost('ecard_content'); + $tpa_name = (string) $sanitized_post_data['name']; + $short_name = (string) $sanitized_post_data['short_name']; + $eCardTemplate = $sanitized_post_data['ecard_content']; $filename = strtolower(str_replace(' ', '_', $short_name)) . '.html'; $file_directory = WRITEPATH . 'e_card_template/'; @@ -760,10 +1246,10 @@ class MasterController extends AdminController header('Content-type:text/html; charset=utf-8'); // Write the HTML content to the file - $data = file_put_contents($file_path, $eCardTemplate); + $html_data = file_put_contents($file_path, $eCardTemplate); - if ($data !== false) { + if ($html_data !== false) { $this->myLogger->logme('error', 'TPA: {tpa}, e-Card HTML template file saved successfully: {data}, filepath is: {path}', ['data' => $filename, 'tpa' => $tpa_name, 'path' => $file_path]); } else { $this->myLogger->logme('error', 'TPA: {tpa}, e-Card HTML template file unable to save: {data}', ['data' => $filename, 'tpa' => $tpa_name]); @@ -772,7 +1258,7 @@ class MasterController extends AdminController if($update){ - echo json_encode(array("status" => true , 'data' => $data)); + echo json_encode(array("status" => true , 'data' => $update_data)); }else{ echo json_encode(array("status" => false)); } @@ -795,9 +1281,110 @@ class MasterController extends AdminController public function editTPABranch() { $this->myLogger->logme('error','TPA branch CREATE function called'); - $id = $this->request->getPost('PrimaryKey'); + $rules = [ + + // ====================== + // Branch Details + // ====================== + 'branch_name' => [ + 'rules' => 'required|trim', + 'errors' => [ + 'required' => 'Branch name is required' + ] + ], + + 'branch_code' => [ + 'rules' => 'required|trim', + 'errors' => [ + 'required' => 'Branch code is required' + ] + ], + + 'address1' => [ + 'rules' => 'required|trim', + 'errors' => [ + 'required' => 'Address Line 1 is required' + ] + ], + + 'state' => [ + 'rules' => 'required|is_natural_no_zero', + 'errors' => [ + 'required' => 'State is required' + ] + ], + + 'district' => [ + 'rules' => 'required|trim', + 'errors' => [ + 'required' => 'District is required' + ] + ], + + 'city' => [ + 'rules' => 'required|trim', + 'errors' => [ + 'required' => 'City is required' + ] + ], + + 'pincode' => [ + 'rules' => 'required|numeric|exact_length[6]', + 'errors' => [ + 'required' => 'Pincode is required', + 'numeric' => 'Pincode must contain only numbers', + 'exact_length' => 'Pincode must be exactly 6 digits' + ] + ], + + // ====================== + // Contact Details (Array) + // ====================== + 'name.*' => [ + 'rules' => 'required|trim|min_length[2]', + 'errors' => [ + 'required' => 'Contact name is required', + 'min_length' => 'Contact name must be at least 2 characters' + ] + ], + + 'designation.*' => [ + 'rules' => 'required|trim', + 'errors' => [ + 'required' => 'Designation is required' + ] + ], + + 'email.*' => [ + 'rules' => 'required|valid_email', + 'errors' => [ + 'required' => 'Email is required', + 'valid_email' => 'Invalid email format' + ] + ], + + 'mobile.*' => [ + 'rules' => 'required|numeric|exact_length[10]', + 'errors' => [ + 'required' => 'Mobile number is required', + 'numeric' => 'Mobile must contain only digits', + 'exact_length' => 'Mobile number must be exactly 10 digits' + ] + ], + ]; + + if (!$this->validate($rules)) { + return $this->response->setStatusCode(400)->setJSON([ + 'status' => false, + 'message' => 'Input validation failed', + 'code' => 400, + 'errors' => $this->validator->getErrors() + ]); + } $data = $this->request->getPost(); - $update = $this->tpaBranchModel->update($id, $data); + $sanitized_post_data = sanitizeInputArrayAdvanced($data); + $id = $sanitizeInputArrayAdvanced['PrimaryKey']; + $update = $this->tpaBranchModel->update($id, $sanitized_post_data); // print_r($this->request->getPost('name[]')); // print_r($this->request->getPost('email[]')); @@ -809,18 +1396,18 @@ class MasterController extends AdminController foreach ($contactsToDelete as $contact) { $this->levelContactModel->delete($contact->id); } - for ($i = 0; $i < count($this->request->getPost('name')); $i++) { + for ($i = 0; $i < count($sanitized_post_data['name']); $i++) { // Prepare data to update - $data = [ + $sanitized_post_data_for_level = [ 'contact_type' => 'tpa', 'ref_id' => $id, 'created_by' => get_session_userid(), - 'name' => $this->request->getPost('name')[$i], - 'email' => $this->request->getPost('email')[$i], - 'mobile' => $this->request->getPost('mobile')[$i], - 'designation' => $this->request->getPost('designation')[$i] + 'name' => $sanitized_post_data['name'][$i], + 'email' => $sanitized_post_data['email'][$i], + 'mobile' => $sanitized_post_data['mobile'][$i], + 'designation' => $sanitized_post_data['designation'][$i] ]; - $contacts = $this->levelContactModel->insert($data); + $contacts = $this->levelContactModel->insert($sanitized_post_data_for_level); } } @@ -926,10 +1513,28 @@ class MasterController extends AdminController { $this->myLogger->logme('error','KYC Entity Type general info function called'); + $rules = [ + 'name' => [ + 'rules' => 'required', + 'errors' => [ + 'required' => 'KYC Entity Type Name is required' + ] + ], + ]; + + if (!$this->validate($rules)) { + return $this->response->setStatusCode(400)->setJSON([ + 'status' => false, + 'message' => 'Input validation failed', + 'code' => 400, + 'errors' => $this->validator->getErrors() + ]); + } $data = $this->request->getPost(); - $data['created_by'] = get_session_userid(); + $sanitized_post_data = sanitizeInputArrayAdvanced($data); + $sanitized_post_data['created_by'] = get_session_userid(); - $insert = $this->kycEntityTypeModel->insert($data); + $insert = $this->kycEntityTypeModel->insert($sanitized_post_data); if($insert){ $kyc_data = $this->kycEntityTypeModel->where(['id' => $insert, 'is_active' => 1])->first(); echo json_encode(array("status" => true , 'data' => $kyc_data)); @@ -942,20 +1547,40 @@ class MasterController extends AdminController { $this->myLogger->logme('error','Kyc Docs CREATE function called'); + $rules = [ + 'file_name' => [ + 'rules' => 'required', + 'errors' => [ + 'required' => 'KYC Docs File Name is required' + ] + ], + ]; + + if (!$this->validate($rules)) { + return $this->response->setStatusCode(400)->setJSON([ + 'status' => false, + 'message' => 'Input validation failed', + 'code' => 400, + 'errors' => $this->validator->getErrors() + ]); + } + $data = $this->request->getPost(); + $sanitized_post_data = sanitizeInputArrayAdvanced($data); + // print_r($data);die; - if($data['kyc_type_id'] == ''){ + if($sanitized_post_data['kyc_type_id'] == ''){ // PrimaryKey - $data['kyc_type_id'] =$data['PrimaryKey']; + $sanitized_post_data['kyc_type_id'] =$data['PrimaryKey']; } // print_r($data);die; - $data['created_by'] = get_session_userid(); - $insert = $this->kycDocsModel->insert($data); + $sanitized_post_data['created_by'] = get_session_userid(); + $insert = $this->kycDocsModel->insert($sanitized_post_data); if($insert){ - $kycDocsData = $this->kycDocsModel->where('kyc_type_id', $data['kyc_type_id'])->where('is_active',1)->findAll(); + $kycDocsData = $this->kycDocsModel->where('kyc_type_id', $sanitized_post_data['kyc_type_id'])->where('is_active',1)->findAll(); echo json_encode(array("status" => true , 'data' => $kycDocsData)); }else{ echo json_encode(array("status" => false)); @@ -999,12 +1624,31 @@ class MasterController extends AdminController public function editKYCInfo() { $this->myLogger->logme('error','edit KYC general info function called'); - $id = $this->request->getPost('PrimaryKey'); - $data = $this->request->getPost(); - $data['updated_by'] = get_session_userid(); - $update = $this->kycEntityTypeModel->update($id,$data); + $rules = [ + 'file_name' => [ + 'rules' => 'required', + 'errors' => [ + 'required' => 'KYC Docs File Name is required' + ] + ], + ]; + + if (!$this->validate($rules)) { + return $this->response->setStatusCode(400)->setJSON([ + 'status' => false, + 'message' => 'Input validation failed', + 'code' => 400, + 'errors' => $this->validator->getErrors() + ]); + } + + $data = $this->request->getPost(); + $sanitized_post_data = sanitizeInputArrayAdvanced($data); + $id = $sanitized_post_data['PrimaryKey']; + $sanitized_post_data['updated_by'] = get_session_userid(); + $update = $this->kycEntityTypeModel->update($id,$sanitized_post_data); if($update){ - echo json_encode(array("status" => true , 'data' => $data)); + echo json_encode(array("status" => true , 'data' => $sanitized_post_data)); }else{ echo json_encode(array("status" => false)); } @@ -1138,11 +1782,97 @@ class MasterController extends AdminController public function createPolicyType() { $this->myLogger->logme('error','Policy Type CREATE function called'); + $rules = [ + 'policy_type' => [ + 'rules' => 'required|trim|min_length[2]', + 'errors' => [ + 'required' => 'Policy type name is required', + 'min_length' => 'Policy type name must be at least 2 characters' + ] + ], + + 'bap' => [ + 'rules' => 'required|trim', + 'errors' => [ + 'required' => 'BAP is required' + ] + ], + + 'allocg' => [ + 'rules' => 'required|trim', + 'errors' => [ + 'required' => 'Category is required' + ] + ], + + 'alloci' => [ + 'rules' => 'required|trim', + 'errors' => [ + 'required' => 'BAP category is required' + ] + ], + + + 'ebp' => [ + 'rules' => 'permit_empty|numeric|greater_than_equal_to[0]', + 'errors' => [ + 'numeric' => 'Group base premium must be numeric', + 'greater_than_equal_to' => 'Value cannot be negative' + ] + ], + + 'etp' => [ + 'rules' => 'permit_empty|numeric|greater_than_equal_to[0]', + 'errors' => [ + 'numeric' => 'Group third-party premium must be numeric', + 'greater_than_equal_to' => 'Value cannot be negative' + ] + ], + + 'etep' => [ + 'rules' => 'permit_empty|numeric|greater_than_equal_to[0]', + 'errors' => [ + 'numeric' => 'Group terrorism premium must be numeric', + 'greater_than_equal_to' => 'Value cannot be negative' + ] + ], + + 'iep' => [ + 'rules' => 'permit_empty|numeric|greater_than_equal_to[0]', + 'errors' => [ + 'numeric' => 'Individual base premium must be numeric', + 'greater_than_equal_to' => 'Value cannot be negative' + ] + ], + + 'itp' => [ + 'rules' => 'permit_empty|numeric|greater_than_equal_to[0]', + 'errors' => [ + 'numeric' => 'Individual third-party premium must be numeric', + 'greater_than_equal_to' => 'Value cannot be negative' + ] + ], + + 'itep' => [ + 'rules' => 'permit_empty|numeric|greater_than_equal_to[0]', + 'errors' => [ + 'numeric' => 'Individual terrorism premium must be numeric', + 'greater_than_equal_to' => 'Value cannot be negative' + ] + ], + ]; + if (!$this->validate($rules)) { + return $this->response->setStatusCode(400)->setJSON([ + 'status' => false, + 'message' => 'Input validation failed', + 'code' => 400, + 'errors' => $this->validator->getErrors() + ]); + } $data = $this->request->getPost(); - - $data['created_by'] = get_session_userid(); - $insert = $this->policyTypeModel->insert($data); - + $sanitized_post_data = sanitizeInputArrayAdvanced($data); + $sanitized_post_data['created_by'] = get_session_userid(); + $insert = $this->policyTypeModel->insert($sanitized_post_data); if($insert){ $policyTypeData = $this->policyTypeModel->where('id', $insert)->first(); echo json_encode(array("status" => true , 'data' => $policyTypeData)); @@ -1175,12 +1905,101 @@ class MasterController extends AdminController public function editPolicyType() { $this->myLogger->logme('error','edit Policy general info function called'); - $id = $this->request->getPost('PrimaryKey'); - $data = $this->request->getPost(); - $data['updated_by'] = get_session_userid(); - $update = $this->policyTypeModel->update($id,$data); + $rules = [ + 'policy_type' => [ + 'rules' => 'required|trim|min_length[2]', + 'errors' => [ + 'required' => 'Policy type name is required', + 'min_length' => 'Policy type name must be at least 2 characters' + ] + ], + + 'bap' => [ + 'rules' => 'required|trim', + 'errors' => [ + 'required' => 'BAP is required' + ] + ], + + 'allocg' => [ + 'rules' => 'required|trim', + 'errors' => [ + 'required' => 'Category is required' + ] + ], + + 'alloci' => [ + 'rules' => 'required|trim', + 'errors' => [ + 'required' => 'BAP category is required' + ] + ], + + + 'ebp' => [ + 'rules' => 'permit_empty|numeric|greater_than_equal_to[0]', + 'errors' => [ + 'numeric' => 'Group base premium must be numeric', + 'greater_than_equal_to' => 'Value cannot be negative' + ] + ], + + 'etp' => [ + 'rules' => 'permit_empty|numeric|greater_than_equal_to[0]', + 'errors' => [ + 'numeric' => 'Group third-party premium must be numeric', + 'greater_than_equal_to' => 'Value cannot be negative' + ] + ], + + 'etep' => [ + 'rules' => 'permit_empty|numeric|greater_than_equal_to[0]', + 'errors' => [ + 'numeric' => 'Group terrorism premium must be numeric', + 'greater_than_equal_to' => 'Value cannot be negative' + ] + ], + + 'iep' => [ + 'rules' => 'permit_empty|numeric|greater_than_equal_to[0]', + 'errors' => [ + 'numeric' => 'Individual base premium must be numeric', + 'greater_than_equal_to' => 'Value cannot be negative' + ] + ], + + 'itp' => [ + 'rules' => 'permit_empty|numeric|greater_than_equal_to[0]', + 'errors' => [ + 'numeric' => 'Individual third-party premium must be numeric', + 'greater_than_equal_to' => 'Value cannot be negative' + ] + ], + + 'itep' => [ + 'rules' => 'permit_empty|numeric|greater_than_equal_to[0]', + 'errors' => [ + 'numeric' => 'Individual terrorism premium must be numeric', + 'greater_than_equal_to' => 'Value cannot be negative' + ] + ], + ]; + if (!$this->validate($rules)) { + return $this->response->setStatusCode(400)->setJSON([ + 'status' => false, + 'message' => 'Input validation failed', + 'code' => 400, + 'errors' => $this->validator->getErrors() + ]); + } + $data = $this->request->getPost(); + $sanitized_post_data = sanitizeInputArrayAdvanced($data); + + $id = $sanitized_post_data['PrimaryKey']; + $sanitized_post_data['updated_by'] = get_session_userid(); + $update = $this->policyTypeModel->update($id,$sanitized_post_data); if($update){ - echo json_encode(array("status" => true , 'data' => $data)); + echo json_encode(array("status" => true , 'data' => $sanitized_post_data)); }else{ echo json_encode(array("status" => false)); } @@ -1347,12 +2166,74 @@ class MasterController extends AdminController public function createCDMasterData() { $this->myLogger->logme("error", 'Create CD Master Data API called.'); - $data = $this->request->getPost(); + $rules = [ + + // ====================== + // Client / Insurer Mapping + // ====================== + 'client_id' => [ + 'rules' => 'required|is_natural_no_zero', + 'errors' => [ + 'required' => 'Client is required' + ] + ], + + 'insurer_id' => [ + 'rules' => 'required|is_natural_no_zero', + 'errors' => [ + 'required' => 'Insurer is required' + ] + ], + + 'insurer_branch_id' => [ + 'rules' => 'required|is_natural_no_zero', + 'errors' => [ + 'required' => 'Insurer branch is required' + ] + ], + + // ====================== + // CD Account Details + // ====================== + 'opening_date' => [ + 'rules' => 'required|valid_date[Y-m-d]', + 'errors' => [ + 'required' => 'Opening date is required', + 'valid_date' => 'Opening date must be in YYYY-MM-DD format' + ] + ], + + 'cd_ac_no' => [ + 'rules' => 'required|trim', + 'errors' => [ + 'required' => 'CD account number is required' + ] + ], + + 'opening_bal' => [ + 'rules' => 'required|numeric|greater_than_equal_to[0]', + 'errors' => [ + 'required' => 'Opening amount is required', + 'numeric' => 'Opening amount must be numeric', + 'greater_than_equal_to' => 'Opening amount cannot be negative' + ] + ], + ]; + if (!$this->validate($rules)) { + return $this->response->setStatusCode(400)->setJSON([ + 'status' => false, + 'message' => 'Input validation failed', + 'code' => 400, + 'errors' => $this->validator->getErrors() + ]); + } + $data = $this->request->getPost(); + $sanitized_post_data = sanitizeInputArrayAdvanced($data); $this->myLogger->logme("error", 'Received POST data: ' . json_encode($data)); - $id = $data['PrimaryKey'] ?? null; - $date = (string) ($data['opening_date'] ?? ''); - $data['opening_date'] = date('Y-m-d', strtotime($date)); + $id = $sanitized_post_data['PrimaryKey'] ?? null; + $date = (string) ($sanitized_post_data['opening_date'] ?? ''); + $sanitized_post_data['opening_date'] = date('Y-m-d', strtotime($date)); $this->myLogger->logme("error", 'Formatted opening_date: ' . $data['opening_date']); $loggedInUserID = get_session_userid(); @@ -1362,9 +2243,9 @@ class MasterController extends AdminController if (empty($id)) { $cd_acc_count = $this->CDMasterModel->where('is_active', 1) - ->where('client_id', $data['client_id']) - ->where('insurer_id', $data['insurer_id']) - ->where('insurer_branch_id', $data['insurer_branch_id']) + ->where('client_id', $sanitized_post_data['client_id']) + ->where('insurer_id', $sanitized_post_data['insurer_id']) + ->where('insurer_branch_id', $sanitized_post_data['insurer_branch_id']) ->countAllResults(); if($cd_acc_count > 0){ @@ -1372,19 +2253,19 @@ class MasterController extends AdminController } $this->myLogger->logme("error", 'Performing INSERT operation.'); - $insert = $this->CDMasterModel->insert($data); + $insert = $this->CDMasterModel->insert($sanitized_post_data); $this->myLogger->logme("error", 'Insert result: ' . json_encode($insert)); if ($insert) { $cd_tranction_data = [ - 'amount' => $data['opening_bal'], + 'amount' => $sanitized_post_data['opening_bal'], 'sub_type_id' => 7, - 'client_id' => $data['client_id'], + 'client_id' => $sanitized_post_data['client_id'], 'client_policy_id' => null, - 'cd_ac_no' => $data['cd_ac_no'], + 'cd_ac_no' => $sanitized_post_data['cd_ac_no'], 'endorsement_no' => null, - 'insurer_id' => $data['insurer_id'], + 'insurer_id' => $sanitized_post_data['insurer_id'], 'description' => 'Opening Amount', 'transaction_type' => 'Credit', 'event_name' => null, @@ -1400,9 +2281,9 @@ class MasterController extends AdminController $this->myLogger->logme("error", 'Inserted CD Master data: ' . json_encode($cd_master_data)); $cd_master_full_data = $this->CDMasterModel->where('is_active', 1) - ->where('client_id', $data['client_id']) - ->where('insurer_id', $data['insurer_id']) - ->where('insurer_branch_id', $data['insurer_branch_id']) + ->where('client_id', $sanitized_post_data['client_id']) + ->where('insurer_id', $sanitized_post_data['insurer_id']) + ->where('insurer_branch_id', $sanitized_post_data['insurer_branch_id']) ->findAll(); return $this->respond([ @@ -1427,7 +2308,7 @@ class MasterController extends AdminController // === UPDATE === $this->myLogger->logme("error", 'Performing UPDATE operation for ID: ' . $id); - $updated = $this->CDMasterModel->where('id', $id)->set($data)->update(); + $updated = $this->CDMasterModel->where('id', $id)->set($sanitized_post_data)->update(); $this->myLogger->logme("error", 'Update result: ' . json_encode($updated)); $existingData = $this->CDMasterModel->where('is_active', 1)->where('id', $id)->first(); @@ -1465,27 +2346,89 @@ class MasterController extends AdminController public function editCDMasterData($id = null) { + $this->myLogger->logme("error", 'Edit CD Master Data API called.'); + $rules = [ - $id = $this->request->getPost('PrimaryKey'); - $date = (string) $this->request->getPost('opening_date'); - $data = $this->request->getPost(); - $data['opening_date'] = date('Y-m-d', strtotime($date)); + // ====================== + // Client / Insurer Mapping + // ====================== + 'client_id' => [ + 'rules' => 'required|is_natural_no_zero', + 'errors' => [ + 'required' => 'Client is required' + ] + ], + + 'insurer_id' => [ + 'rules' => 'required|is_natural_no_zero', + 'errors' => [ + 'required' => 'Insurer is required' + ] + ], + + 'insurer_branch_id' => [ + 'rules' => 'required|is_natural_no_zero', + 'errors' => [ + 'required' => 'Insurer branch is required' + ] + ], + + // ====================== + // CD Account Details + // ====================== + 'opening_date' => [ + 'rules' => 'required|valid_date[Y-m-d]', + 'errors' => [ + 'required' => 'Opening date is required', + 'valid_date' => 'Opening date must be in YYYY-MM-DD format' + ] + ], + + 'cd_ac_no' => [ + 'rules' => 'required|trim', + 'errors' => [ + 'required' => 'CD account number is required' + ] + ], + + 'opening_bal' => [ + 'rules' => 'required|numeric|greater_than_equal_to[0]', + 'errors' => [ + 'required' => 'Opening amount is required', + 'numeric' => 'Opening amount must be numeric', + 'greater_than_equal_to' => 'Opening amount cannot be negative' + ] + ], + ]; + if (!$this->validate($rules)) { + return $this->response->setStatusCode(400)->setJSON([ + 'status' => false, + 'message' => 'Input validation failed', + 'code' => 400, + 'errors' => $this->validator->getErrors() + ]); + } + $data = $this->request->getPost(); + $sanitized_post_data = sanitizeInputArrayAdvanced($data); + $id = $sanitized_post_data['PrimaryKey']; + $date = (string) $sanitized_post_data['opening_date']; + $sanitized_post_data['opening_date'] = date('Y-m-d', strtotime($date)); if ($data) { - $insert = $this->CDMasterModel->where('id', $id)->set($data)->update(); + $insert = $this->CDMasterModel->where('id', $id)->set($sanitized_post_data)->update(); - $data = $this->CDMasterModel->where('id', $id)->first(); + $get_data = $this->CDMasterModel->where('id', $id)->first(); $cd_transaction_updated_data = [ - 'balance' => $data['opening_bal'], - 'amount' => $data['opening_bal'] + 'balance' => $get_data['opening_bal'], + 'amount' => $get_data['opening_bal'] ]; $cd_tranction = $this->clientDepositModel - ->where('client_id', $data['client_id']) - ->where('insurer_id', $data['insurer_id']) - ->where('cd_ac_no', $data['cd_ac_no']) + ->where('client_id', $sanitized_post_data['client_id']) + ->where('insurer_id', $sanitized_post_data['insurer_id']) + ->where('cd_ac_no', $sanitized_post_data['cd_ac_no']) ->where('sub_type', 7) ->set($cd_transaction_updated_data)->update(); @@ -1731,35 +2674,72 @@ class MasterController extends AdminController { // return $this->respond($this->request->getPost()); $template_id = $this->request->getPost('template_id'); + + $rules = [ + 'policy_type' => [ + 'rules' => 'required|is_natural_no_zero', + 'errors' => [ + 'required' => 'Policy type is required' + ] + ], + + 'event' => [ + 'rules' => 'required|trim', + 'errors' => [ + 'required' => 'Event is required' + ] + ], + + + 'json_data' => [ + 'rules' => 'required', + 'errors' => [ + 'required' => 'Template mapping data is required' + ] + ], + ]; + + if (! $this->validate($rules)) { + return $this->response->setStatusCode(400)->setJSON([ + 'status' => false, + 'message' => 'Input validation failed', + 'code' => 400, + 'errors' => $this->validator->getErrors() + ]); + } + $data = $this->request->getPost(); + $sanitized_post_data = sanitizeInputArrayAdvanced($data); + + - $data = [ - 'insurer_id' => $this->request->getPost('insurer_id'), - 'policy_type_id' => $this->request->getPost('policy_type'), - 'event_name' => $this->request->getPost('event'), + $fetch_data = [ + 'insurer_id' => $sanitized_post_data['insurer_id'], + 'policy_type_id' => $sanitized_post_data['policy_type'], + 'event_name' => $sanitized_post_data['event'], 'type_name' => 'export', - 'jsoncolumns' => $this->request->getPost('json_data'), + 'jsoncolumns' => $sanitized_post_data['json_data'], 'is_active' => 1, 'created_by' => get_session_userid(), ]; if($template_id){ - $update = $this->insurerTemplateModel->where('id', $template_id)->set($data)->update(); + $update = $this->insurerTemplateModel->where('id', $template_id)->set($fetch_data)->update(); if($update){ - return $this->respond(['status' => true, 'message' => 'Template updated successfully', $data]); + return $this->respond(['status' => true, 'message' => 'Template updated successfully', $fetch_data]); }else{ - return $this->respond(['status' => true, 'message' => 'Failed to update template', $data]); + return $this->respond(['status' => true, 'message' => 'Failed to update template', $fetch_data]); } }else{ - $insert = $this->insurerTemplateModel->insert($data); + $insert = $this->insurerTemplateModel->insert($fetch_data); if($insert){ - return $this->respond(['status' => true, 'message' => 'Template created successfully', $data]); + return $this->respond(['status' => true, 'message' => 'Template created successfully', $fetch_data]); }else{ - return $this->respond(['status' => true, 'message' => 'Failed to create template', $data]); + return $this->respond(['status' => true, 'message' => 'Failed to create template', $fetch_data]); } } @@ -2161,13 +3141,34 @@ class MasterController extends AdminController if ($method === 'post') { - $id = $this->request->getPost('pk') ?? null; - $data = $this->request->getPost(); + + $rules = [ + 'branch_name' => [ + 'rules' => 'required', + 'errors' => [ + 'required' => 'Branch Name is required' + ] + ] + ]; + if (! $this->validate($rules)) { + return $this->response->setStatusCode(400)->setJSON([ + 'status' => false, + 'message' => 'Input validation failed', + 'code' => 400, + 'errors' => $this->validator->getErrors() + ]); + } + + $data = $this->request->getPost(); + $sanitized_post_data = sanitizeInputArrayAdvanced($data); + $id = $sanitized_post_data['pk'] ?? null; + unset($sanitized_post_data['pk']); + if (empty($id)) { - $update_status = $nhanceBranchModel->insert($data); + $update_status = $nhanceBranchModel->insert($sanitized_post_data); } else { - $update_status = $nhanceBranchModel->where('id', $id)->set($data)->update(); + $update_status = $nhanceBranchModel->where('id', $id)->set($sanitized_post_data)->update(); } if ($update_status) { @@ -2243,13 +3244,34 @@ class MasterController extends AdminController if ($method === 'post') { - $id = $this->request->getPost('pk') ?? null; - $data = $this->request->getPost(); + + $rules = [ + 'vehicle_type' => [ + 'rules' => 'required', + 'errors' => [ + 'required' => 'Vehicle Type is required' + ] + ] + ]; + + if (! $this->validate($rules)) { + return $this->response->setStatusCode(400)->setJSON([ + 'status' => false, + 'message' => 'Input validation failed', + 'code' => 400, + 'errors' => $this->validator->getErrors() + ]); + } + + $data = $this->request->getPost(); + $sanitized_post_data = sanitizeInputArrayAdvanced($data); + $id = $sanitized_post_data['pk'] ?? null; + unset($sanitized_post_data['pk']); if (empty($id)) { - $update_status = $vehicleTypeModel->insert($data); + $update_status = $vehicleTypeModel->insert($sanitized_post_data); } else { - $update_status = $vehicleTypeModel->where('id', $id)->set($data)->update(); + $update_status = $vehicleTypeModel->where('id', $id)->set($sanitized_post_data)->update(); } if ($update_status) { @@ -2257,14 +3279,14 @@ class MasterController extends AdminController 'status' => true, 'code' => 200, 'message' => 'Vehicle Type Master updated successfully', - 'data' => $data + 'data' => $sanitized_post_data ], 200); } else { return $this->respond([ 'status' => false, 'code' => 400, 'message' => 'Failed to update', - 'data' => $data + 'data' => $sanitized_post_data ], 200); } @@ -2324,13 +3346,62 @@ class MasterController extends AdminController if ($method === 'post') { - $id = $this->request->getPost('pk') ?? null; - $data = $this->request->getPost(); + $rules = [ + // ====================== + // RTO Office Name + // ====================== + 'rto_name' => [ + 'rules' => 'required|trim|min_length[3]|max_length[100]|alpha_numeric_space', + 'errors' => [ + 'required' => 'RTO Office Name is required', + 'min_length' => 'RTO Office Name must be at least 3 characters' + ] + ], + // ====================== + // RTO Code (2 digits only) + // ====================== + 'rto_code' => [ + 'rules' => 'required|exact_length[2]|numeric', + 'errors' => [ + 'required' => 'RTO Code is required', + 'exact_length' => 'RTO Code must be exactly 2 digits', + 'numeric' => 'RTO Code must contain only numbers' + ] + ], + // ====================== + // RTO State (2 letters only) + // ====================== + 'rto_state' => [ + 'rules' => 'required|exact_length[2]|alpha', + 'errors' => [ + 'required' => 'RTO State is required', + 'exact_length' => 'RTO State must be exactly 2 letters', + 'alpha' => 'RTO State must contain only alphabets' + ] + ], + + ]; + + if (! $this->validate($rules)) { + return $this->response->setStatusCode(400)->setJSON([ + 'status' => false, + 'message' => 'Input validation failed', + 'code' => 400, + 'errors' => $this->validator->getErrors() + ]); + } + + + $data = $this->request->getPost(); + $sanitized_post_data = sanitizeInputArrayAdvanced($data); + $id = $sanitized_post_data['pk'] ?? null; + unset($sanitized_post_data['pk']); + if (empty($id)) { - $update_status = $rtoModel->insert($data); + $update_status = $rtoModel->insert($sanitized_post_data); } else { - $update_status = $rtoModel->where('id', $id)->set($data)->update(); + $update_status = $rtoModel->where('id', $id)->set($sanitized_post_data)->update(); } if ($update_status) { @@ -2338,14 +3409,14 @@ class MasterController extends AdminController 'status' => true, 'code' => 200, 'message' => 'RTO Master updated successfully', - 'data' => $data + 'data' => $sanitized_post_data ], 200); } else { return $this->respond([ 'status' => false, 'code' => 400, 'message' => 'Failed to update', - 'data' => $data + 'data' => $sanitized_post_data ], 200); } @@ -2405,47 +3476,172 @@ class MasterController extends AdminController if ($this->request->getMethod() === 'post') { - $id = $this->request->getPost('pk'); - $data = $this->request->getPost(); + $rules = [ + 'manager_id' => [ + 'rules' => 'required|integer', + 'errors' => [ + 'required' => 'Manager is required', + 'integer' => 'Invalid Manager selected' + ] + ], + 'name' => [ + 'rules' => 'required|min_length[3]|max_length[100]|alpha_space', + 'errors' => [ + 'required' => 'Name is required', + 'min_length' => 'Name must be at least 3 characters', + 'max_length' => 'Name cannot exceed 100 characters', + 'alpha_space'=> 'Name can contain only letters and spaces' + ] + ], + 'pos_code' => [ + 'rules' => 'required|alpha_numeric|max_length[20]', + 'errors' => [ + 'required' => 'POS Code is required', + 'alpha_numeric' => 'POS Code must be alphanumeric', + 'max_length' => 'POS Code cannot exceed 20 characters' + ] + ], + 'email' => [ + 'rules' => 'required|valid_email', + 'errors' => [ + 'required' => 'Email is required', + 'valid_email' => 'Enter a valid email address' + ] + ], + 'mobile' => [ + 'rules' => 'required|numeric|exact_length[10]', + 'errors' => [ + 'required' => 'Mobile number is required', + 'numeric' => 'Mobile number must contain only digits', + 'exact_length' => 'Mobile number must be exactly 10 digits' + ] + ], + 'address' => [ + 'rules' => 'required|min_length[5]', + 'errors' => [ + 'required' => 'Address is required', + 'min_length' => 'Address must be at least 5 characters' + ] + ], + 'city' => [ + 'rules' => 'required|alpha_space', + 'errors' => [ + 'required' => 'City is required', + 'alpha_space' => 'City must contain only letters and spaces' + ] + ], + 'state' => [ + 'rules' => 'required|alpha_space', + 'errors' => [ + 'required' => 'State is required', + 'alpha_space' => 'State must contain only letters and spaces' + ] + ], + 'pincode' => [ + 'rules' => 'required|numeric|exact_length[6]', + 'errors' => [ + 'required' => 'Pincode is required', + 'numeric' => 'Pincode must contain only digits', + 'exact_length' => 'Pincode must be exactly 6 digits' + ] + ], + 'aadhar' => [ + 'rules' => 'required|numeric|exact_length[12]', + 'errors' => [ + 'required' => 'Aadhaar number is required', + 'numeric' => 'Aadhaar must contain only digits', + 'exact_length' => 'Aadhaar must be exactly 12 digits' + ] + ], + 'pan' => [ + 'rules' => 'required|regex_match[/^[A-Z]{5}[0-9]{4}[A-Z]{1}$/]', + 'errors' => [ + 'required' => 'PAN number is required', + 'regex_match' => 'Enter a valid PAN number (ABCDE1234F)' + ] + ], + 'gst' => [ + 'rules' => 'permit_empty|max_length[15]', + 'errors' => [ + 'max_length' => 'GST number cannot exceed 15 characters' + ] + ], + 'aadhar_file_name' => [ + 'rules' => 'permit_empty|uploaded[aadhar_file_name]|max_size[aadhar_file_name,5120]|ext_in[aadhar_file_name,pdf,jpg,jpeg,png]', + 'errors' => [ + 'uploaded' => 'Invalid Aadhaar file', + 'max_size' => 'Aadhaar file size should not exceed 5MB', + 'ext_in' => 'Aadhaar must be PDF or image (jpg, jpeg, png)' + ] + ], + 'pan_file_name' => [ + 'rules' => 'permit_empty|uploaded[pan_file_name]|max_size[pan_file_name,5120]|ext_in[pan_file_name,pdf,jpg,jpeg,png]', + 'errors' => [ + 'uploaded' => 'Invalid PAN file', + 'max_size' => 'PAN file size should not exceed 5MB', + 'ext_in' => 'PAN must be PDF or image (jpg, jpeg, png)' + ] + ], + 'certificate_file_name' => [ + 'rules' => 'permit_empty|uploaded[certificate_file_name]|max_size[certificate_file_name,5120]|ext_in[certificate_file_name,pdf,jpg,jpeg,png]', + 'errors' => [ + 'uploaded' => 'Invalid Certificate file', + 'max_size' => 'Certificate file size should not exceed 5MB', + 'ext_in' => 'Certificate must be PDF or image (jpg, jpeg, png)' + ] + ], + ]; - unset($data['pk']); + if (! $this->validate($rules)) { + return $this->response->setStatusCode(400)->setJSON([ + 'status' => false, + 'message' => 'Input validation failed', + 'code' => 400, + 'errors' => $this->validator->getErrors() + ]); + } + + $data = $this->request->getPost(); + $sanitized_post_data = sanitizeInputArrayAdvanced($data); + $id = $sanitized_post_data['pk'] ?? null; + unset($sanitized_post_data['pk']); try { // Certificate $certificate = $this->uploadPOSFile('certificate_file_name', 'pos_certificate_files'); - if ($certificate !== null) { $data['certificate_file_name'] = $certificate; } else { unset($data['certificate_file_name']); } + if ($certificate !== null) { $sanitized_post_data['certificate_file_name'] = $certificate; } else { unset($sanitized_post_data['certificate_file_name']); } // PAN file $panFile = $this->uploadPOSFile('pan_file_name', 'pos_certificate_files'); - if ($panFile !== null) { $data['pan_file_name'] = $panFile; } else { unset($data['pan_file_name']);} + if ($panFile !== null) { $sanitized_post_data['pan_file_name'] = $panFile; } else { unset($sanitized_post_data['pan_file_name']);} // Aadhaar file $aadharFile = $this->uploadPOSFile('aadhar_file_name', 'pos_certificate_files'); - if ($aadharFile !== null) { $data['aadhar_file_name'] = $aadharFile; } else { unset($data['aadhar_file_name']);} + if ($aadharFile !== null) { $sanitized_post_data['aadhar_file_name'] = $aadharFile; } else { unset($sanitized_post_data['aadhar_file_name']);} } catch (\RuntimeException $e) { - return $this->respond([ 'status' => false, 'code' => 400, 'message' => $e->getMessage(), 'data' => $data ], 400); + return $this->respond([ 'status' => false, 'code' => 400, 'message' => $e->getMessage(), 'data' => $sanitized_post_data ], 400); } - foreach ($data as $k => $v) { + foreach ($sanitized_post_data as $k => $v) { if ($v === '' || $v === null) { - unset($data[$k]); + unset($sanitized_post_data[$k]); } } // INSERT / UPDATE if (empty($id)) { - $status = $posModel->insert($data); + $status = $posModel->insert($sanitized_post_data); } else { - $status = $posModel->update($id, $data); + $status = $posModel->update($id, $sanitized_post_data); } if ($status) { - return $this->respond([ 'status' => true, 'code' => 200, 'message' => 'POS updated successfully', 'data' => $data ], 200); + return $this->respond([ 'status' => true, 'code' => 200, 'message' => 'POS updated successfully', 'data' => $sanitized_post_data ], 200); } - return $this->respond([ 'status' => false, 'code' => 400, 'message' => 'Failed to update', 'data' => $data ], 400); + return $this->respond([ 'status' => false, 'code' => 400, 'message' => 'Failed to update', 'data' => $sanitized_post_data ], 400); } elseif ($method === 'get') { diff --git a/app/Controllers/PayoutController.php b/app/Controllers/PayoutController.php index bba35e99..bf992d88 100644 --- a/app/Controllers/PayoutController.php +++ b/app/Controllers/PayoutController.php @@ -281,13 +281,17 @@ class PayoutController extends BaseController //... Payout-invoice Mapping - Save/update/soft Delete/Hard Delete Data public function saveInvoice() { - $json = $this->request->getJSON(true); - // print_rr($json);die(); - - if (!$json) { + $raw_json = $this->request->getJSON(true); + + // 1. Check if the JSON was actually valid/parsed before sanitizing + if (is_null($raw_json)) { return $this->response->setJSON(['error' => 'Invalid JSON','message' => 'Invalid JSON received.'])->setStatusCode(400); } + // 2. Sanitize the data + $json = sanitizeInputArrayAdvanced($raw_json); + + // 3. Now you can safely use $json (even if it is an empty array) $id = $json['invoice_id'] ?? null; try { diff --git a/app/Controllers/PolicyTransactionController.php b/app/Controllers/PolicyTransactionController.php index f0d6fc56..4ca42ed4 100644 --- a/app/Controllers/PolicyTransactionController.php +++ b/app/Controllers/PolicyTransactionController.php @@ -917,12 +917,14 @@ // policy Transaction Create function start public function createInceptionPolicy() { - $post_data = $this->request->getPost() ?? []; + $post_data = $this->request->getPost(); + $post_data = $post_data ? sanitizeInputArrayAdvanced($post_data) : []; + $this->myLogger->logme('error', 'Policy Trancaction form data : '. json_encode($post_data)); - $id = $this->request->getPost('id'); + $id = $post_data['id'] ?? null; $data = $this->preparePolicyData(); - $data['cd_ac_pk'] = $this->request->getPost('cd_ac_no'); + $data['cd_ac_pk'] = $post_data['cd_ac_no']; $data['issuer'] = 2; $data['status'] = 'completed'; $this->myLogger->logme('error', 'Policy Trancaction modified form data ( insert data ) : '. json_encode($data)); @@ -937,7 +939,8 @@ private function preparePolicyData() { - $data = $this->request->getPost(); + $request_data = $this->request->getPost(); + $data = sanitizeInputArrayAdvanced($request_data); $file_data = $this->request->getFiles() ?? null; $data['file_data'] = $file_data ?? null; @@ -2247,9 +2250,10 @@ public function createEndorsementPolicy() { - $id = $this->request->getPost('id'); + // $id = $this->request->getPost('id'); $data = $this->preparePolicyTransactionData(); $data['status'] = 'completed'; + $id = $data['id'] ?? null; // print_r($data); die; if (!$id) { @@ -2261,8 +2265,8 @@ private function preparePolicyTransactionData() { - $data = $this->request->getPost(); - + $request_post_data = $this->request->getPost(); + $data = sanitizeInputArrayAdvanced($request_post_data); // echo '
';
             // print_r($data); 
             // die;
@@ -3250,10 +3254,12 @@
             $client_policy_id = (!isset($client_policy_id) || $client_policy_id === '' || $client_policy_id === null) ? 0 : $client_policy_id;
             $user_id = (!isset($user_id) || $user_id === '' || $user_id === null) ? 0 : $user_id;
             if ($this->request->is('post')) {
-                $isFromDashboard = $this->request->getPost("is_dashboard");
+                $request_post_data   = $this->request->getPost();
+                $sanitized_post_data = sanitizeInputArrayAdvanced($request_post_data);
+                $isFromDashboard = $sanitized_post_data["is_dashboard"];
 
                 if (isset($isFromDashboard) && !empty($isFromDashboard) && $isFromDashboard == 1) {
-                    $ids = $this->request->getPost('ids');
+                    $ids = $sanitized_post_data['ids'];
 
                     $ids = array_filter(explode(',', $ids));
 
@@ -4221,10 +4227,12 @@
             // echo 'scbsc';die();
             if ($this->request->is('post')) {
                 // $jsonData = (array)$this->request->getJSON();
-                $customer_id = $this->request->getPost('customer_id');
-                $policy_id = $this->request->getPost('policy_id');
-                $cus_doc_name = $this->request->getPost('cus_doc_name');
-                $policy_doc_name = $this->request->getPost('policy_doc_name');
+                $request_data   = $this->request->getPost();
+                $data = sanitizeInputArrayAdvanced($request_data);
+                $customer_id = $data['customer_id'];
+                $policy_id = $data['policy_id'];
+                $cus_doc_name = $data['cus_doc_name'];
+                $policy_doc_name = $data['policy_doc_name'];
                 $pt_files = [];
                 $kyc_files = [];
                 $batch_files = [];
diff --git a/app/Controllers/ThzController.php b/app/Controllers/ThzController.php
index df886d2a..713a8fb7 100644
--- a/app/Controllers/ThzController.php
+++ b/app/Controllers/ThzController.php
@@ -63,7 +63,98 @@ class ThzController extends BaseController
     public function ticketSave()
     {
         try {
-            $data = $this->request->getPost();
+            $rules = [
+                    'client_id' => [
+                        'rules'  => 'permit_empty|integer',
+                        'errors' => [
+                            'integer' => 'Invalid client selected'
+                        ]
+                    ],
+
+                    'mobile' => [
+                        'rules'  => 'required|regex_match[/^[0-9]{10}$/]',
+                        'errors' => [
+                            'required'     => 'Mobile number is required',
+                            'regex_match'  => 'Mobile number must be exactly 10 digits'
+                        ]
+                    ],
+
+                    'name' => [
+                        'rules'  => 'required|min_length[3]|max_length[100]|alpha_space',
+                        'errors' => [
+                            'required'   => 'Name is required',
+                            'min_length' => 'Name must be at least 3 characters',
+                            'alpha_space'=> 'Name can contain only letters and spaces'
+                        ]
+                    ],
+
+                    'email' => [
+                        'rules'  => 'required|valid_email|max_length[150]',
+                        'errors' => [
+                            'required'    => 'Email is required',
+                            'valid_email' => 'Please enter a valid email address'
+                        ]
+                    ],
+
+                    'empcode' => [
+                        'rules'  => 'permit_empty|max_length[50]',
+                        'errors' => [
+                            'max_length' => 'Employee code is too long'
+                        ]
+                    ],
+
+                    'ticket_type' => [
+                        'rules'  => 'required|in_list[Sales,Service]',
+                        'errors' => [
+                            'required' => 'Ticket Type is required',
+                            'in_list'  => 'Invalid Ticket Type selected'
+                        ]
+                    ],
+
+                    'assign_to' => [
+                        'rules'  => 'permit_empty|integer',
+                        'errors' => [
+                            'integer' => 'Invalid assignee selected'
+                        ]
+                    ],
+
+                    'subject' => [
+                        'rules'  => 'required|min_length[5]|max_length[150]',
+                        'errors' => [
+                            'required'   => 'Subject is required',
+                            'min_length' => 'Subject must be at least 5 characters',
+                            'max_length' => 'Subject cannot exceed 150 characters'
+                        ]
+                    ],
+
+                    'message' => [
+                        'rules'  => 'required|min_length[10]|max_length[1500]',
+                        'errors' => [
+                            'required'   => 'Message is required',
+                            'min_length' => 'Message must be at least 10 characters',
+                            'max_length' => 'Message cannot exceed 1500 characters'
+                        ]
+                    ],
+                    'status' => [
+                        'rules'  => 'permit_empty|in_list[Open,In Progress,Resolved,Closed]',
+                        'errors' => [
+                            'in_list' => 'Invalid ticket status'
+                        ]
+                    ],
+            ];
+
+            if (!$this->validate($rules)) {
+                return $this->response->setStatusCode(400)->setJSON([
+                    'status' => false,
+                    'message' => 'Input validation failed',
+                    'code' => 400,
+                    'errors' => $this->validator->getErrors()
+                ]);
+            }
+
+            $request_post_data = $this->request->getPost();
+            $data = sanitizeInputArrayAdvanced($request_post_data);
+                
             $references   = "";
             if (!empty($data['thz_id'])) {
 
@@ -157,7 +248,30 @@ class ThzController extends BaseController
     {
 
         try {
-            $data = $this->request->getPost();
+            
+            $rules = [
+                'notes' => [
+                    'rules'  => 'required|string|min_length[1]|max_length[1500]',
+                    'errors' => [
+                        'required'   => 'Notes is required',
+                        'string'     => 'Notes must be valid text',
+                        'min_length' => 'Notes cannot be empty',
+                        'max_length' => 'Notes cannot exceed 1500 characters'
+                    ]
+                ],
+            ];
+
+            if (!$this->validate($rules)) {
+                return $this->response->setStatusCode(400)->setJSON([
+                    'status' => false,
+                    'message' => 'Input validation failed',
+                    'code' => 400,
+                    'errors' => $this->validator->getErrors()
+                ]);
+            }
+
+            $request_post_data = $this->request->getPost();
+            $data = sanitizeInputArrayAdvanced($request_post_data);
 
             $data['notes_type'] = $data['notes_type'] ?? 'External';
 
diff --git a/app/Controllers/TicketController.php b/app/Controllers/TicketController.php
index 09021a99..4d8c7bcc 100644
--- a/app/Controllers/TicketController.php
+++ b/app/Controllers/TicketController.php
@@ -1122,8 +1122,130 @@ class TicketController extends BaseController
 
     public function createTicket()
     {
-        $ticket_data = $this->request->getPost();
-        $ticket_data = $this->formatDateForClaim($ticket_data);
+        $rules = [
+            'emp_code' => [
+                'rules'  => 'required',
+                'errors' => ['required' => 'Employee Code is required']
+            ],
+
+            'emp_name' => [
+                'rules'  => 'required',
+                'errors' => ['required' => 'Employee Name is required']
+            ],
+
+            'insured_name' => [
+                'rules'  => 'required',
+                'errors' => ['required' => 'Insured Name is required']
+            ],
+
+            'relationship' => [
+                'rules'  => 'required',
+                'errors' => ['required' => 'Relationship is required']
+            ],
+
+            'emp_mobile' => [
+                'rules'  => 'required',
+                'errors' => ['required' => 'Employee Mobile is required']
+            ],
+
+            'emp_mail' => [
+                'rules'  => 'required',
+                'errors' => ['required' => 'Employee Email is required']
+            ],
+
+            'client_name' => [
+                'rules'  => 'required',
+                'errors' => ['required' => 'Client Name is required']
+            ],
+
+            'insurer_id' => [
+                'rules'  => 'required',
+                'errors' => ['required' => 'Insurer is required']
+            ],
+
+            'client_policy_id' => [
+                'rules'  => 'required',
+                'errors' => ['required' => 'Policy is required']
+            ],
+
+            'claim_status_id' => [
+                'rules'  => 'required',
+                'errors' => ['required' => 'Claim Status is required']
+            ],
+
+            'priority' => [
+                'rules'  => 'required',
+                'errors' => ['required' => 'Priority is required']
+            ],
+
+            'mode_of_intimation' => [
+                'rules'  => 'required',
+                'errors' => ['required' => 'Mode of Intimation is required']
+            ],
+
+            'claim_type' => [
+                'rules'  => 'required',
+                'errors' => ['required' => 'Claim Type is required']
+            ],
+
+            'hospital_name' => [
+                'rules'  => 'required',
+                'errors' => ['required' => 'Hospital Name is required']
+            ],
+
+            'hospital_address' => [
+                'rules'  => 'required',
+                'errors' => ['required' => 'Hospital Address is required']
+            ],
+
+            'hospital_city' => [
+                'rules'  => 'required',
+                'errors' => ['required' => 'Hospital City is required']
+            ],
+
+            'hospital_state' => [
+                'rules'  => 'required',
+                'errors' => ['required' => 'Hospital State is required']
+            ],
+
+            'hospital_pin_code' => [
+                'rules'  => 'required',
+                'errors' => ['required' => 'Hospital Pincode is required']
+            ],
+
+            'hospital_phone_no' => [
+                'rules'  => 'required',
+                'errors' => ['required' => 'Hospital Phone Number is required']
+            ],
+
+            'doa' => [
+                'rules'  => 'required',
+                'errors' => ['required' => 'Date of Admission is required']
+            ],
+
+            'dod' => [
+                'rules'  => 'required',
+                'errors' => ['required' => 'Date of Discharge is required']
+            ],
+
+            'claim_amount' => [
+                'rules'  => 'required',
+                'errors' => ['required' => 'Claim Amount is required']
+            ],
+        ];
+
+        if (!$this->validate($rules)) {
+            return $this->response->setStatusCode(400)->setJSON([
+                'status' => false,
+                'message' => 'Input validation failed',
+                'code' => 400,
+                'errors' => $this->validator->getErrors()
+            ]);
+        }
+
+        $request_data = $this->request->getPost();
+        $sanitized_data = sanitizeInputArrayAdvanced($request_data);
+        $ticket_data = $this->formatDateForClaim($sanitized_data);
         // $ticket_data = $this->getLastMatchedStatus($ticket_data, );
         // print_rr($ticket_data); die;
 
@@ -1183,9 +1305,132 @@ class TicketController extends BaseController
 
     public function updateTicket()
     {
+
+        $rules = [
+            'emp_code' => [
+                'rules'  => 'required',
+                'errors' => ['required' => 'Employee Code is required']
+            ],
+
+            'emp_name' => [
+                'rules'  => 'required',
+                'errors' => ['required' => 'Employee Name is required']
+            ],
+
+            'insured_name' => [
+                'rules'  => 'required',
+                'errors' => ['required' => 'Insured Name is required']
+            ],
+
+            'relationship' => [
+                'rules'  => 'required',
+                'errors' => ['required' => 'Relationship is required']
+            ],
+
+            'emp_mobile' => [
+                'rules'  => 'required',
+                'errors' => ['required' => 'Employee Mobile is required']
+            ],
+
+            'emp_mail' => [
+                'rules'  => 'required',
+                'errors' => ['required' => 'Employee Email is required']
+            ],
+
+            'client_name' => [
+                'rules'  => 'required',
+                'errors' => ['required' => 'Client Name is required']
+            ],
+
+            'insurer_id' => [
+                'rules'  => 'required',
+                'errors' => ['required' => 'Insurer is required']
+            ],
+
+            'client_policy_id' => [
+                'rules'  => 'required',
+                'errors' => ['required' => 'Policy is required']
+            ],
+
+            'claim_status_id' => [
+                'rules'  => 'required',
+                'errors' => ['required' => 'Claim Status is required']
+            ],
+
+            'priority' => [
+                'rules'  => 'required',
+                'errors' => ['required' => 'Priority is required']
+            ],
+
+            'mode_of_intimation' => [
+                'rules'  => 'required',
+                'errors' => ['required' => 'Mode of Intimation is required']
+            ],
+
+            'claim_type' => [
+                'rules'  => 'required',
+                'errors' => ['required' => 'Claim Type is required']
+            ],
+
+            'hospital_name' => [
+                'rules'  => 'required',
+                'errors' => ['required' => 'Hospital Name is required']
+            ],
+
+            'hospital_address' => [
+                'rules'  => 'required',
+                'errors' => ['required' => 'Hospital Address is required']
+            ],
+
+            'hospital_city' => [
+                'rules'  => 'required',
+                'errors' => ['required' => 'Hospital City is required']
+            ],
+
+            'hospital_state' => [
+                'rules'  => 'required',
+                'errors' => ['required' => 'Hospital State is required']
+            ],
+
+            'hospital_pin_code' => [
+                'rules'  => 'required',
+                'errors' => ['required' => 'Hospital Pincode is required']
+            ],
+
+            'hospital_phone_no' => [
+                'rules'  => 'required',
+                'errors' => ['required' => 'Hospital Phone Number is required']
+            ],
+
+            'doa' => [
+                'rules'  => 'required',
+                'errors' => ['required' => 'Date of Admission is required']
+            ],
+
+            'dod' => [
+                'rules'  => 'required',
+                'errors' => ['required' => 'Date of Discharge is required']
+            ],
+
+            'claim_amount' => [
+                'rules'  => 'required',
+                'errors' => ['required' => 'Claim Amount is required']
+            ],
+        ];
+
+        if (!$this->validate($rules)) {
+            return $this->response->setStatusCode(400)->setJSON([
+                'status' => false,
+                'message' => 'Input validation failed',
+                'code' => 400,
+                'errors' => $this->validator->getErrors()
+            ]);
+        }
+        
+        $request_data = $this->request->getPost();
+        $sanitized_data = sanitizeInputArrayAdvanced($request_data);
+        $ticket_data = $this->formatDateForClaim($sanitized_data);
         $ticket_id = $this->request->getPost('ticket_master_id');
-        $ticket_data = $this->request->getPost();
-        $ticket_data = $this->formatDateForClaim($ticket_data);
         $old_ticket_data = $this->ticketMasterModel->where('id', $ticket_id)->where('is_active', 1)->first();
         $ticket_data['claim_status_id'] = $this->getLastMatchedStatus($ticket_data, $old_ticket_data);
         // print_rr($ticket_data); die;
@@ -1250,7 +1495,49 @@ class TicketController extends BaseController
     {
         //action 1 is create. action 2 is edit and action 3 is delete
         if ($action == 1) {
-            $received_data = $this->request->getPost();
+                $rules = [
+                    'template_name' => [
+                        'rules'  => 'required',
+                        'errors' => [
+                            'required' => 'Template Name is required'
+                        ]
+                    ],
+                    'ticket_type' => [
+                        'rules'  => 'required',
+                        'errors' => [
+                            'required' => 'Policy Type is required'
+                        ]
+                    ],
+                    'trigger_type' => [
+                        'rules'  => 'required',
+                        'errors' => [
+                            'required' => 'Trigger Type is required'
+                        ]
+                    ],
+                    'subject' => [
+                        'rules'  => 'required',
+                        'errors' => [
+                            'required' => 'Subject is required'
+                        ]
+                    ],
+                    'mail_content' => [
+                        'rules'  => 'required',
+                        'errors' => [
+                            'required' => 'Mail Content is required'
+                        ]
+                    ]
+                ];
+                 if (!$this->validate($rules)) {
+                    return $this->response->setStatusCode(400)->setJSON([
+                        'status' => false,
+                        'message' => 'Input validation failed',
+                        'code' => 400,
+                        'errors' => $this->validator->getErrors()
+                    ]);
+                }
+                $data   = $this->request->getPost();
+                $received_data = sanitizeInputArrayAdvanced($data);
+
             if (isset($received_data['id']) && $received_data['id'] != '') {
                 $status = $this->ticketMailTemplateModel->save($received_data);
                 if ($status) {
@@ -3002,6 +3289,70 @@ class TicketController extends BaseController
 
     public function uploadClaimMisFile()
     {
+
+        $filename = '';
+        $fileSize = '';
+
+            //validate uploaded file
+            $validated = $this->validate([
+                'file' => [
+                    'uploaded[file]',
+                    'mime_in[file,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.oasis.opendocument.spreadsheet]',
+                    'max_size[file,16384]',
+                ],
+            ]);
+            
+            if ($validated) 
+            {
+                    
+                    $file = $this->request->getFile('file');
+                    if (!$file) {
+                        $this->myLogger->logme("error", 'File not found');
+                        return $this->respond(['status' => false, 'code' => 400, 'message' => 'File not found'], 400);
+                    }
+
+                    $is_moved = $file->move(WRITEPATH . 'uploads/claims_mis/');
+                
+                    if ($is_moved) {
+                        $filename = file_Upload_for_lead($file, $file_path);
+                        $fileSize = $file->getSize(); // File size in bytes
+                        $fileSize = $fileSize / (1024 * 1024); // Convert to MB
+
+                        $this->myLogger->logme("error", 'File move successful');
+                        
+                            $request_data   = $this->request->getPost();
+                            $data = sanitizeInputArrayAdvanced($request_data);
+
+                            if(isset($data['from_date']) && !empty($data['from_date'])){
+                                $data['from_date'] = change_date_format($data['from_date'], 'd/m/Y', 'Y-m-d');
+                            }
+
+                            if(isset($data['to_date']) && !empty($data['to_date'])){
+                                $data['to_date'] = change_date_format($data['to_date'], 'd/m/Y', 'Y-m-d');
+                            }
+                            if(!empty($file_name)){
+                                $data['file_name'] = $file;
+                            }
+
+                            $response = $this->claimmisFileModel->insert($data);
+                        
+                            if($response){
+                                return $this->respond(['status'=>true, 'code'=>200, 'message'=>'MIS file uploaded successfully'], 200);
+                            }else{
+                                return $this->respond(['status'=>true, 'code'=>500, 'message'=>'Failed to upload'], 200);
+                            }
+                        
+                    } else {
+                        $this->myLogger->logme("error", 'File move failed');
+                        return $this->respond(['status' => false, 'code' => 500, 'message' => 'File move failed'], 500);
+                    }
+
+            } else {
+                $this->myLogger->logme("error", 'Upload failed Invalid file');
+                return $this->respond(['status' => false, 'code' => 404, 'message' => 'Invalid file'], 404);
+            }
+
+        /*** OLD CODE KEEP it Safe 
         $file = $this->request->getFile('file');
         $data = $this->request->getPost();
 
@@ -3027,6 +3378,7 @@ class TicketController extends BaseController
         }else{
             return $this->respond(['status'=>true, 'code'=>500, 'message'=>'Failed to upload'], 200);
         }
+        ****/
     }
 
     public function downloadClaimMisFile()
diff --git a/app/Controllers/UserController.php b/app/Controllers/UserController.php
index 668144a6..daaadb9f 100755
--- a/app/Controllers/UserController.php
+++ b/app/Controllers/UserController.php
@@ -83,7 +83,114 @@ class UserController extends AdminController
             return redirect()->to(base_url('/user/list'));
         } else {
 
-            $userData = $this->request->getPost();
+            // $userData = $this->request->getPost();
+            $data      = $this->request->getPost();
+            $userData  = sanitizeInputArrayAdvanced($data);
+            $rules = [
+
+                // ======================
+                // Nhance Branch
+                // ======================
+                'nhance_branch_id' => [
+                    'rules'  => 'required|integer',
+                    'errors' => [
+                        'required' => 'Nhance Branch is required',
+                        'integer'  => 'Invalid Nhance Branch selected'
+                    ]
+                ],
+
+                // ======================
+                // Reporting Manager
+                // ======================
+                'rm_id' => [
+                    'rules'  => 'required|integer',
+                    'errors' => [
+                        'required' => 'Reporting Manager is required',
+                        'integer'  => 'Invalid Reporting Manager selected'
+                    ]
+                ],
+
+                // ======================
+                // Employee Code
+                // ======================
+                'emp_code' => [
+                    'rules'  => 'required|alpha_numeric|min_length[3]|max_length[20]|is_unique[user_profiles.emp_code,id,{PrimaryKey}]',
+                    'errors' => [
+                        'required'      => 'Employee Code is required',
+                        'alpha_numeric' => 'Employee Code must be alphanumeric',
+                        'min_length'    => 'Employee Code must be at least 3 characters',
+                        'max_length'    => 'Employee Code cannot exceed 20 characters',
+                        'is_unique'     => 'Employee Code already exists'
+                    ]
+                ],
+
+                // ======================
+                // First Name
+                // ======================
+                'first_name' => [
+                    'rules'  => 'required|alpha_space|min_length[2]|max_length[100]',
+                    'errors' => [
+                        'required'    => 'Name is required',
+                        'alpha_space' => 'Name can contain only letters and spaces',
+                        'min_length'  => 'Name must be at least 2 characters',
+                        'max_length'  => 'Name cannot exceed 100 characters'
+                    ]
+                ],
+
+                // ======================
+                // Email
+                // ======================
+                'email' => [
+                    'rules'  => 'required|valid_email|is_unique[user_profiles.email,id,{PrimaryKey}]',
+                    'errors' => [
+                        'required'    => 'Email is required',
+                        'valid_email' => 'Please enter a valid email address',
+                        'is_unique'   => 'Email already exists'
+                    ]
+                ],
+
+                // ======================
+                // Mobile
+                // ======================
+                'mobile' => [
+                    'rules'  => 'required|regex_match[/^[6-9][0-9]{9}$/]|is_unique[user_profiles.mobile,id,{PrimaryKey}]',
+                    'errors' => [
+                        'required'     => 'Mobile number is required',
+                        'regex_match'  => 'Enter a valid 10-digit mobile number starting with 6, 7, 8, or 9',
+                        'is_unique'    => 'Mobile number already exists'
+                    ]
+                ],
+
+                // ======================
+                // Role
+                // ======================
+                'role' => [
+                    'rules'  => 'required|integer',
+                    'errors' => [
+                        'required' => 'User Role is required',
+                        'integer'  => 'Invalid User Role selected'
+                    ]
+                ],
+
+                // ======================
+                // Team (Multiple select)
+                // ======================
+                'team' => [
+                    'rules'  => 'required',
+                    'errors' => [
+                        'required' => 'At least one User Team must be selected'
+                    ]
+                ],
+            ];
+            if (!$this->validate($rules)) {
+                return $this->response->setStatusCode(400)->setJSON([
+                    'status' => false,
+                    'message' => 'Input validation failed',
+                    'code' => 400,
+                    'errors' => $this->validator->getErrors()
+                ]);
+            }
+
             $userData['created_by'] =  get_session_userid();
             $temp_team = $userData['team'];
             unset($userData['team']);
@@ -167,9 +274,116 @@ class UserController extends AdminController
             return redirect()->to(base_url('/user/list'));
         } else {
             // echo ":/ in 163";
-            $id = $this->request->getPost('PrimaryKey');
-            $teams = $this->request->getPost('team');
-            $userData = $this->request->getPost();
+            $rules = [
+
+                // ======================
+                // Nhance Branch
+                // ======================
+                'nhance_branch_id' => [
+                    'rules'  => 'required|integer',
+                    'errors' => [
+                        'required' => 'Nhance Branch is required',
+                        'integer'  => 'Invalid Nhance Branch selected'
+                    ]
+                ],
+
+                // ======================
+                // Reporting Manager
+                // ======================
+                'rm_id' => [
+                    'rules'  => 'required|integer',
+                    'errors' => [
+                        'required' => 'Reporting Manager is required',
+                        'integer'  => 'Invalid Reporting Manager selected'
+                    ]
+                ],
+
+                // ======================
+                // Employee Code
+                // ======================
+                'emp_code' => [
+                    'rules'  => 'required|alpha_numeric|min_length[3]|max_length[20]|is_unique[user_profiles.emp_code,id,{PrimaryKey}]',
+                    'errors' => [
+                        'required'      => 'Employee Code is required',
+                        'alpha_numeric' => 'Employee Code must be alphanumeric',
+                        'min_length'    => 'Employee Code must be at least 3 characters',
+                        'max_length'    => 'Employee Code cannot exceed 20 characters',
+                        'is_unique'     => 'Employee Code already exists'
+                    ]
+                ],
+
+                // ======================
+                // First Name
+                // ======================
+                'first_name' => [
+                    'rules'  => 'required|alpha_space|min_length[2]|max_length[100]',
+                    'errors' => [
+                        'required'    => 'Name is required',
+                        'alpha_space' => 'Name can contain only letters and spaces',
+                        'min_length'  => 'Name must be at least 2 characters',
+                        'max_length'  => 'Name cannot exceed 100 characters'
+                    ]
+                ],
+
+                // ======================
+                // Email
+                // ======================
+                'email' => [
+                    'rules'  => 'required|valid_email|is_unique[user_profiles.email,id,{PrimaryKey}]',
+                    'errors' => [
+                        'required'    => 'Email is required',
+                        'valid_email' => 'Please enter a valid email address',
+                        'is_unique'   => 'Email already exists'
+                    ]
+                ],
+
+                // ======================
+                // Mobile
+                // ======================
+                'mobile' => [
+                    'rules'  => 'required|regex_match[/^[6-9][0-9]{9}$/]|is_unique[user_profiles.mobile,id,{PrimaryKey}]',
+                    'errors' => [
+                        'required'     => 'Mobile number is required',
+                        'regex_match'  => 'Enter a valid 10-digit mobile number starting with 6, 7, 8, or 9',
+                        'is_unique'    => 'Mobile number already exists'
+                    ]
+                ],
+
+                // ======================
+                // Role
+                // ======================
+                'role' => [
+                    'rules'  => 'required|integer',
+                    'errors' => [
+                        'required' => 'User Role is required',
+                        'integer'  => 'Invalid User Role selected'
+                    ]
+                ],
+
+                // ======================
+                // Team (Multiple select)
+                // ======================
+                'team' => [
+                    'rules'  => 'required',
+                    'errors' => [
+                        'required' => 'At least one User Team must be selected'
+                    ]
+                ],
+            ];
+            if (!$this->validate($rules)) {
+                return $this->response->setStatusCode(400)->setJSON([
+                    'status' => false,
+                    'message' => 'Input validation failed',
+                    'code' => 400,
+                    'errors' => $this->validator->getErrors()
+                ]);
+            }
+            
+            $data      = $this->request->getPost();
+            $userData  = sanitizeInputArrayAdvanced($data);
+            $id = $userData['PrimaryKey'];
+            $teams = $userData['team'];
+            
             unset($userData['csrf_test_name']);
             unset($userData['PrimaryKey']);
 
@@ -594,29 +808,100 @@ class UserController extends AdminController
             
             // add/update
             if ($method === 'post') {
-                $data = $this->request->getPost();
-                $id = !empty($data['PrimaryKey']) ? $data['PrimaryKey'] : null;
+
+                $rules = [
+                    // ======================
+                    // Partner Name
+                    // ======================
+                    'name' => [
+                        'rules'  => 'required|alpha_space|min_length[2]|max_length[100]',
+                        'errors' => [
+                            'required'    => 'Partner name is required',
+                            'alpha_space' => 'Partner name can contain only letters and spaces',
+                            'min_length'  => 'Partner name must be at least 2 characters',
+                            'max_length'  => 'Partner name cannot exceed 100 characters'
+                        ]
+                    ],
+                    // ======================
+                    // Mobile Number
+                    // ======================
+                    'mobile' => [
+                        'rules'  => 'required|regex_match[/^[6-9][0-9]{9}$/]',
+                        'errors' => [
+                            'required'    => 'Mobile number is required',
+                            'regex_match' => 'Enter a valid 10-digit mobile number starting with 6, 7, 8, or 9',
+                        ]
+                    ],
+
+                    // ======================
+                    // Email
+                    // ======================
+                    'email' => [
+                        'rules'  => 'required|valid_email',
+                        'errors' => [
+                            'required'    => 'Email is required',
+                            'valid_email' => 'Please enter a valid email address',
+                        ]
+                    ],
+                    // ======================
+                    // Retention Rate
+                    // ======================
+                     'retention_rate' => [
+        'rules'  => [
+            'required',
+            'regex_match[/^(100(\.0{1,2})?|([0-9]{1,2})(\.[0-9]{1,2})?)$/]'
+        ],
+        'errors' => [
+            'required'    => 'Retention Rate is required',
+            'regex_match' => 'Retention Rate must be between 0 and 100 with up to 2 decimal places'
+        ]
+        ],
+                    // ======================
+                    // Nhance Branch
+                    // ======================
+                    'nhance_branch_id' => [
+                        'rules'  => 'required|integer',
+                        'errors' => [
+                            'required' => 'Nhance Branch is required',
+                            'integer'  => 'Invalid Nhance Branch selected'
+                        ]
+                    ],
+                ];
+                if (! $this->validate($rules)) {
+                return $this->response->setStatusCode(400)->setJSON([
+                    'status'  => false,
+                    'message' => 'Input validation failed',
+                    'code'    => 400,
+                    'errors'  => $this->validator->getErrors()
+                ]);
+            }
+
+
+                $data           = $this->request->getPost();
+                $sanitized_post_data = sanitizeInputArrayAdvanced($data);
+                $id = !empty($sanitized_post_data['PrimaryKey']) ? $sanitized_post_data['PrimaryKey'] : null;
+                unset($sanitized_post_data['pk']); 
                 
                 // don't forgot same means just unset the key because partner_staff some UNIQUE KEY sets in table thats why
                 if ($id) {
                     $existing = $this->partnerStaffModel->find((int)$id);
                     if ($existing) {
-                        if ($data['email'] === $existing['email']) { unset($data['email']); }
-                        if ($data['mobile'] === $existing['mobile']) { unset($data['mobile']); }
+                        if ($sanitized_post_data['email'] === $existing['email']) { unset($sanitized_post_data['email']); }
+                        if ($sanitized_post_data['mobile'] === $existing['mobile']) { unset($sanitized_post_data['mobile']); }
                     }
                 }
 
                 $errors = [];
 
                 // Check Email Duplicate (if it wasn't unset)
-                if (isset($data['email'])) {
-                    $count = $this->partnerStaffModel->where('email', $data['email'])->countAllResults();
+                if (isset($sanitized_post_data['email'])) {
+                    $count = $this->partnerStaffModel->where('email', $sanitized_post_data['email'])->countAllResults();
                     if ($count > 0) $errors['email'] = "This email is already taken by another user.";
                 }
 
                 // Check Mobile Duplicate (if it wasn't unset)
-                if (isset($data['mobile'])) {
-                    $count = $this->partnerStaffModel->where('mobile', $data['mobile'])->countAllResults();
+                if (isset($sanitized_post_data['mobile'])) {
+                    $count = $this->partnerStaffModel->where('mobile', $sanitized_post_data['mobile'])->countAllResults();
                     if ($count > 0) $errors['mobile'] = "This mobile is already taken by another user.";
                 }
 
@@ -632,14 +917,14 @@ class UserController extends AdminController
                 // --- Save/Update ---
                 if ($id) {
                     $text   = "update";            
-                    $data['updated_by'] =  get_session_userid();
+                    $sanitized_post_data['updated_by'] =  get_session_userid();
                     
-                    $result = $this->partnerStaffModel->update($id, $data);
+                    $result = $this->partnerStaffModel->update($id, $sanitized_post_data);
                 } else {
                     $text = "create";
-                    $data['role_id'] = 1;
-                    $data['created_by'] = get_session_userid();
-                    $id = $this->partnerStaffModel->insert($data);
+                    $sanitized_post_data['role_id'] = 1;
+                    $sanitized_post_data['created_by'] = get_session_userid();
+                    $id = $this->partnerStaffModel->insert($sanitized_post_data);
                     if($id){
                         $details['manager_id'] = $id;
                         $details['updated_by'] =  get_session_userid();
diff --git a/app/Views/UserList.php b/app/Views/UserList.php
index e1f0f127..28cde270 100755
--- a/app/Views/UserList.php
+++ b/app/Views/UserList.php
@@ -684,7 +684,7 @@ table.dataTable tbody td {
                             
- +
@@ -1134,6 +1134,16 @@ table.dataTable tbody td { console.error("Response Headers:", xhr.getAllResponseHeaders()); console.error("Error Thrown:", error); console.error("Status:", status); + if (xhr.status === 400) { + let response = JSON.parse(xhr.responseText); + if (response.errors) { + $.each(response.errors, function (field, message) { + toastr.warning(message, 'Validation Error'); + }); + } else { + toastr.warning(response.message || 'Validation failed', 'Warning'); + } + }else{toastr.error('Server error occurred.', 'Error');} } }); @@ -1333,7 +1343,16 @@ table.dataTable tbody td { }, error: function(xhr) { console.log("Error: " + xhr.statusText); - toastr.error('Server error occurred.', 'Error'); + if (xhr.status === 400) { + let response = JSON.parse(xhr.responseText); + if (response.errors) { + $.each(response.errors, function (field, message) { + toastr.warning(message, 'Validation Error'); + }); + } else { + toastr.warning(response.message || 'Validation failed', 'Warning'); + } + }else{toastr.error('Server error occurred.', 'Error');} }, complete: function() { btn.disabled = false; @@ -1395,6 +1414,16 @@ table.dataTable tbody td { error: function(xhr) { console.log("Error: " + xhr.statusText); toastr.error('Server error occurred.', 'Error'); + if (xhr.status === 400) { + let response = JSON.parse(xhr.responseText); + if (response.errors) { + $.each(response.errors, function (field, message) { + toastr.warning(message, 'Validation Error'); + }); + } else { + toastr.warning(response.message || 'Validation failed', 'Warning'); + } + }else{toastr.error('Server error occurred.', 'Error');} }, complete: function() { btn.disabled = false; diff --git a/app/Views/add_image_list.php b/app/Views/add_image_list.php index a69924ea..c91db897 100755 --- a/app/Views/add_image_list.php +++ b/app/Views/add_image_list.php @@ -126,7 +126,7 @@ table.dataTable thead th {
- +
@@ -227,7 +227,15 @@ table.dataTable thead th { switch (xhr.status) { case 400: - msg = xhr.responseJSON?.message || 'Bad Request — Invalid input.'; + let response = xhr.responseJSON || JSON.parse(xhr.responseText); + if (response.errors) { + $.each(response.errors, function (field, message) { + toastr.warning(message, 'Validation Error'); + }); + } else { + toastr.warning(response.message || 'Validation failed', 'Warning'); + } + msg = response.message || 'Bad Request — Invalid input.'; break; case 401: msg = 'Unauthorized — Please log in again.'; diff --git a/app/Views/bds_dump_file_list.php b/app/Views/bds_dump_file_list.php index 2c243dcd..bd6e23ff 100644 --- a/app/Views/bds_dump_file_list.php +++ b/app/Views/bds_dump_file_list.php @@ -197,6 +197,14 @@ // Handle error response console.error('Upload failed:', error); console.error('Upload failed:', error); + if (xhr.status === 400) { + var response = JSON.parse(xhr.responseText); + toastr.warning(response.message || 'Validation failed', 'Warning'); + } + if (xhr.status === 500) { + var response = JSON.parse(xhr.responseText); + toastr.warning(response.message || 'Validation failed', 'Warning'); + } }, complete: function() { // Reset button state diff --git a/app/Views/cd_master_add_modal.php b/app/Views/cd_master_add_modal.php index 9089d35f..84de0dd8 100644 --- a/app/Views/cd_master_add_modal.php +++ b/app/Views/cd_master_add_modal.php @@ -204,6 +204,16 @@ console.error(status, error); $('.loader').fadeOut(); $('.loader-mask').delay(350).fadeOut('slow'); + if (xhr.status === 400) { + let response = JSON.parse(xhr.responseText); + if (response.errors) { + $.each(response.errors, function (field, message) { + toastr.warning(message, 'Validation Error'); + }); + } else { + toastr.warning(response.message || 'Validation failed', 'Warning'); + } + } toastr.error('An error occurred while adding the CD account number.', 'ERROR'); } }); diff --git a/app/Views/claim_mis_file_list.php b/app/Views/claim_mis_file_list.php index 4ce6d111..fc636bcb 100644 --- a/app/Views/claim_mis_file_list.php +++ b/app/Views/claim_mis_file_list.php @@ -236,6 +236,14 @@ // Handle error response console.error('Upload failed:', error); console.error('Upload failed:', error); + if (xhr.status === 400) { + var response = JSON.parse(xhr.responseText); + toastr.warning(response.message || 'Validation failed', 'Warning'); + } + if (xhr.status === 500) { + var response = JSON.parse(xhr.responseText); + toastr.warning(response.message || 'Validation failed', 'Warning'); + } }, complete: function() { // Reset button state diff --git a/app/Views/client_basic_info.php b/app/Views/client_basic_info.php index f3ac5144..625efc1e 100755 --- a/app/Views/client_basic_info.php +++ b/app/Views/client_basic_info.php @@ -81,7 +81,7 @@ input:checked + .slider:before { style="border-radius:25px; border:1px solid #00999E;padding:10px;color:#00999E;" alt="avatar"/> -
+
( Image dimensions 100 x 100 pixels and size of 200KB. )

@@ -324,7 +324,7 @@ input:checked + .slider:before { $.each(res.data, function (index, item) { var row = ` ${item.file_name} -
+ @@ -349,7 +349,16 @@ input:checked + .slider:before { $('.loader').fadeOut(); $('.loader-mask').delay(350).fadeOut('slow'); $submitButton.prop('disabled', false); - if (xhr.status === 404) { + if (xhr.status === 400) { + let response = JSON.parse(xhr.responseText); + if (response.errors) { + $.each(response.errors, function (field, message) { + toastr.warning(message, 'Validation Error'); + }); + } else { + toastr.warning(response.message || 'Validation failed', 'Warning'); + } + } else if (xhr.status === 404) { toastr.warning('Resource not found', 'Warning'); } else if (xhr.status === 500) { toastr.warning('Internal server error', 'Warning'); diff --git a/app/Views/client_branch.php b/app/Views/client_branch.php index 01ff9597..99ddb30f 100755 --- a/app/Views/client_branch.php +++ b/app/Views/client_branch.php @@ -281,7 +281,7 @@ $(document).ready(function() { `; } - + }); $('#branch_list').append(branchTable); } diff --git a/app/Views/client_kyc.php b/app/Views/client_kyc.php index e68543e2..f2d9adac 100755 --- a/app/Views/client_kyc.php +++ b/app/Views/client_kyc.php @@ -304,7 +304,8 @@ ${item.file_name} - + diff --git a/app/Views/client_kyc_2.php b/app/Views/client_kyc_2.php index 5032e615..28e22522 100755 --- a/app/Views/client_kyc_2.php +++ b/app/Views/client_kyc_2.php @@ -36,6 +36,7 @@
diff --git a/app/Views/client_kyc_other_table.php b/app/Views/client_kyc_other_table.php index 04bcce83..119c7831 100644 --- a/app/Views/client_kyc_other_table.php +++ b/app/Views/client_kyc_other_table.php @@ -4,7 +4,7 @@ - + diff --git a/app/Views/client_kyc_primary_table.php b/app/Views/client_kyc_primary_table.php index 4373a373..20317d97 100644 --- a/app/Views/client_kyc_primary_table.php +++ b/app/Views/client_kyc_primary_table.php @@ -7,7 +7,7 @@ - + diff --git a/app/Views/client_kyc_single_table.php b/app/Views/client_kyc_single_table.php index 58d1b68c..0b67be02 100644 --- a/app/Views/client_kyc_single_table.php +++ b/app/Views/client_kyc_single_table.php @@ -48,6 +48,7 @@ name="file_name" id="kyc_docs_file_" class="form-control edit-file-input" + accept=".pdf,.jpg,.jpeg,.png" style="box-shadow:none!important; outline:none!important; border:none; height:unset!important;padding: 0px !important;background: transparent !important;"> diff --git a/app/Views/client_policy.php b/app/Views/client_policy.php index 88e2300e..c558e0e1 100755 --- a/app/Views/client_policy.php +++ b/app/Views/client_policy.php @@ -832,7 +832,16 @@ input:checked + .slider_blue::before { setTimeout(function() { $('.loader').fadeOut(); $('.loader-mask').delay(350).fadeOut('slow'); - if (xhr.status === 404) { + if (xhr.status === 400) { + let response = JSON.parse(xhr.responseText); + if (response.errors) { + $.each(response.errors, function (field, message) { + toastr.warning(message, 'Validation Error'); + }); + } else { + toastr.warning(response.message || 'Validation failed', 'Warning'); + } + } else if (xhr.status === 404) { //console.log('Resource not found', 'Warning'); } else if (xhr.status === 500) { //console.log('Internal server error', 'Warning'); diff --git a/app/Views/employee_data_list.php b/app/Views/employee_data_list.php index 517adfa5..fb404134 100755 --- a/app/Views/employee_data_list.php +++ b/app/Views/employee_data_list.php @@ -548,8 +548,16 @@ console.error('Response Text: ', xhr.responseText); } - toastr.warning('Error uploading file', 'WARNING'); - console.error('Upload error:', error); + if (xhr.status === 400) { + let response = JSON.parse(xhr.responseText); + if (response.errors) { + $.each(response.errors, function (field, message) { + toastr.warning(message, 'Validation Error'); + }); + } else { + toastr.warning(response.message || 'Validation failed', 'Warning'); + } + }else{ toastr.warning('Error uploading file', 'WARNING'); } }, complete: function() { $('.loader').fadeOut(); diff --git a/app/Views/faq_list.php b/app/Views/faq_list.php index 9a4d6d8c..4c095b0c 100644 --- a/app/Views/faq_list.php +++ b/app/Views/faq_list.php @@ -326,6 +326,18 @@ }, error: function () { $('.loader, .loader-mask').fadeOut(); + if (xhr.status === 400) { + let response = JSON.parse(xhr.responseText); + if (response.errors) { + $.each(response.errors, function (field, message) { + toastr.warning(message, 'Validation Error'); + }); + } else { + toastr.warning(response.message || 'Validation failed', 'Warning'); + } + }else{ + toastr.error("Something went wrong!", 'Error'); + } } }); } diff --git a/app/Views/frontend_content_list.php b/app/Views/frontend_content_list.php index ce3db484..c88484f3 100644 --- a/app/Views/frontend_content_list.php +++ b/app/Views/frontend_content_list.php @@ -449,7 +449,18 @@ }, error: function () { $('.loader, .loader-mask').fadeOut(); - } + if (xhr.status === 400) { + let response = JSON.parse(xhr.responseText); + if (response.errors) { + $.each(response.errors, function (field, message) { + toastr.warning(message, 'Validation Error'); + }); + } else { + toastr.warning(response.message || 'Validation failed', 'Warning'); + } + }else{ + toastr.error("Something went wrong!", 'Error'); + } }); } diff --git a/app/Views/insurer_basic_info.php b/app/Views/insurer_basic_info.php index f7834580..aadc43d3 100755 --- a/app/Views/insurer_basic_info.php +++ b/app/Views/insurer_basic_info.php @@ -254,6 +254,16 @@ input:checked + .slider:before { $('.loader').fadeOut(); $('.loader-mask').delay(350).fadeOut('slow'); console.log('Something Wrong!', 'warning'); + if (xhr.status === 400) { + let response = JSON.parse(xhr.responseText); + if (response.errors) { + $.each(response.errors, function (field, message) { + toastr.warning(message, 'Validation Error'); + }); + } else { + toastr.warning(response.message || 'Validation failed', 'Warning'); + } + } } }); } diff --git a/app/Views/insurer_export_templete.php b/app/Views/insurer_export_templete.php index a92543a4..81f6fba6 100755 --- a/app/Views/insurer_export_templete.php +++ b/app/Views/insurer_export_templete.php @@ -305,7 +305,7 @@ window.location.reload(); }, - error: function(xhr, status, error) { + error: function (xhr, status, error) { $('.loader').fadeOut(); $('.loader-mask').delay(350).fadeOut('slow'); @@ -323,14 +323,37 @@ console.error('Response headers:', xhr.getAllResponseHeaders()); console.error('Response URL:', xhr.responseURL); - // Example of throwing a detailed error for further handling - throw new Error(`AJAX Request failed: - Status: ${status}, - Error: ${error}, - Status Code: ${xhr.status}, - Status Text: ${xhr.statusText}, - Response: ${xhr.responseText} - `); + // Handle validation errors (CI4) + if (xhr.status === 400) { + + let response = null; + + try { + response = JSON.parse(xhr.responseText); + } catch (e) { + toastr.error('Invalid server response', 'Error'); + return; + } + + if (response.errors) { + $.each(response.errors, function (field, message) { + toastr.warning(message, 'Validation Error'); + }); + } else { + toastr.warning(response.message || 'Validation failed', 'Warning'); + } + + return; + } + + // Handle server errors + if (xhr.status >= 500) { + toastr.error('Server error. Please try again later.', 'Error'); + return; + } + + // Fallback + toastr.error('Unexpected error occurred.', 'Error'); }, complete: function() { $('.loader').fadeOut(); diff --git a/app/Views/kyc_docs.php b/app/Views/kyc_docs.php index 8b9a703c..3c6631e5 100755 --- a/app/Views/kyc_docs.php +++ b/app/Views/kyc_docs.php @@ -254,6 +254,16 @@ $(document).ready(function () { setTimeout(function() { $('.loader').fadeOut(); $('.loader-mask').delay(350).fadeOut('slow'); + if (xhr.status === 400) { + let response = JSON.parse(xhr.responseText); + if (response.errors) { + $.each(response.errors, function (field, message) { + toastr.warning(message, 'Validation Error'); + }); + } else { + toastr.warning(response.message || 'Validation failed', 'Warning'); + } + } toastr.warning('Something Wrong!', 'warning'); }, 1000); } @@ -296,6 +306,16 @@ $(document).ready(function () { setTimeout(function() { $('.loader').fadeOut(); $('.loader-mask').delay(350).fadeOut('slow'); + if (xhr.status === 400) { + let response = JSON.parse(xhr.responseText); + if (response.errors) { + $.each(response.errors, function (field, message) { + toastr.warning(message, 'Validation Error'); + }); + } else { + toastr.warning(response.message || 'Validation failed', 'Warning'); + } + } toastr.warning('Something Wrong!', 'warning'); }, 1000); } diff --git a/app/Views/leads_form.php b/app/Views/leads_form.php index 52902934..364a2da4 100644 --- a/app/Views/leads_form.php +++ b/app/Views/leads_form.php @@ -1646,7 +1646,7 @@ console.log('Form is Empty', 'Warning'); return; } - + var salse_person_id = $("#salse_person_id").val(); console.log('salse_person_id : ', salse_person_id); @@ -1701,6 +1701,16 @@ console.error(status, error); $('.loader').fadeOut(); $('.loader-mask').delay(350).fadeOut('slow'); + if (xhr.status === 400) { + let response = JSON.parse(xhr.responseText); + if (response.errors) { + $.each(response.errors, function (field, message) { + toastr.warning(message, 'Validation Error'); + }); + } else { + toastr.warning(response.message || 'Validation failed', 'Warning'); + } + } } }); }); diff --git a/app/Views/leads_form_handler.php b/app/Views/leads_form_handler.php index 563c5933..10924bf5 100644 --- a/app/Views/leads_form_handler.php +++ b/app/Views/leads_form_handler.php @@ -553,7 +553,7 @@ if (isset($selected_lead_type)) { let isFirstField = container.childElementCount === 0; // Check if it's the first field let placeholder = isFirstField ? 'First file must be Demography.' : ''; - let accept = isFirstField ? '.xls,.xlsx' : ''; + let accept = isFirstField ? '.xls,.xlsx' : '.xls,.xlsx,.pdf,.jpg,.jpeg,.png'; if(selected_lead_form_type != 1){ diff --git a/app/Views/leads_non_eb.php b/app/Views/leads_non_eb.php index df5d5a9a..2f59fe29 100644 --- a/app/Views/leads_non_eb.php +++ b/app/Views/leads_non_eb.php @@ -628,6 +628,16 @@ console.error(status, error); $('.loader').fadeOut(); $('.loader-mask').delay(350).fadeOut('slow'); + if (xhr.status === 400) { + let response = JSON.parse(xhr.responseText); + if (response.errors) { + $.each(response.errors, function (field, message) { + toastr.warning(message, 'Validation Error'); + }); + } else { + toastr.warning(response.message || 'Validation failed', 'Warning'); + } + } } }); }); diff --git a/app/Views/nhance_branch_list.php b/app/Views/nhance_branch_list.php index 29700edd..11725ff2 100644 --- a/app/Views/nhance_branch_list.php +++ b/app/Views/nhance_branch_list.php @@ -283,6 +283,16 @@ console.error(xhr.responseText); $('.loader').fadeOut(); $('.loader-mask').delay(350).fadeOut('slow'); + if (xhr.status === 400) { + let response = JSON.parse(xhr.responseText); + if (response.errors) { + $.each(response.errors, function (field, message) { + toastr.warning(message, 'Validation Error'); + }); + } else { + toastr.warning(response.message || 'Validation failed', 'Warning'); + } + } }); } diff --git a/app/Views/policy_transaction_inception_list.php b/app/Views/policy_transaction_inception_list.php index 14e54f2b..37166f8a 100644 --- a/app/Views/policy_transaction_inception_list.php +++ b/app/Views/policy_transaction_inception_list.php @@ -1030,7 +1030,7 @@ function addHTMLInput(data = null, container_id = 'dynamic-form-container')
- +
x @@ -1216,7 +1216,7 @@ function addHTMLInputForVehicleFileUpload(data = null, container_id = 'dynamic-f
- +
x diff --git a/app/Views/policy_transaction_inception_list_2.php b/app/Views/policy_transaction_inception_list_2.php index 99ef4eb2..c7172902 100644 --- a/app/Views/policy_transaction_inception_list_2.php +++ b/app/Views/policy_transaction_inception_list_2.php @@ -1013,7 +1013,7 @@ function addHTMLInput(data = null)
- +
x @@ -1192,7 +1192,7 @@ function addHTMLInputForVehicleFileUpload(data = null)
- +
x diff --git a/app/Views/pos_list.php b/app/Views/pos_list.php index 2c1c1af5..d94e45c2 100644 --- a/app/Views/pos_list.php +++ b/app/Views/pos_list.php @@ -175,21 +175,21 @@
- +
- +
- +
@@ -363,6 +363,16 @@ }, error: function () { $('.loader, .loader-mask').fadeOut(); + if (xhr.status === 400) { + let response = JSON.parse(xhr.responseText); + if (response.errors) { + $.each(response.errors, function (field, message) { + toastr.warning(message, 'Validation Error'); + }); + } else { + toastr.warning(response.message || 'Validation failed', 'Warning'); + } + } } }); } diff --git a/app/Views/retail_endorsement_list.php b/app/Views/retail_endorsement_list.php index d01de408..97a163a3 100755 --- a/app/Views/retail_endorsement_list.php +++ b/app/Views/retail_endorsement_list.php @@ -312,6 +312,16 @@ error: function(xhr) { toastr.error("Something went wrong!", 'Error'); console.error(xhr.responseText); + if (xhr.status === 400) { + let response = JSON.parse(xhr.responseText); + if (response.errors) { + $.each(response.errors, function (field, message) { + toastr.warning(message, 'Validation Error'); + }); + } else { + toastr.warning(response.message || 'Validation failed', 'Warning'); + } + } }, complete: function() { btn.disabled = false; diff --git a/app/Views/rfq/multi_files.php b/app/Views/rfq/multi_files.php index 09ba89ab..bea6da48 100644 --- a/app/Views/rfq/multi_files.php +++ b/app/Views/rfq/multi_files.php @@ -7,7 +7,7 @@ $increment = 1; foreach ($lead_edit_data["multi_file_data"] as $index => $value) { $isFirstField = ($index === 0); $placeholder = $isFirstField ? 'First file must be Demography.' : ''; - $accept = $isFirstField ? '.xls,.xlsx' : ''; + $accept = $isFirstField ? '.xls,.xlsx' : '.xls,.xlsx,.pdf,.jpg,.jpeg,.png'; $displayIndex = $index + 1; ?> diff --git a/app/Views/rto_master_list.php b/app/Views/rto_master_list.php index f95d688b..3c8c912a 100644 --- a/app/Views/rto_master_list.php +++ b/app/Views/rto_master_list.php @@ -243,6 +243,16 @@ console.error(xhr.responseText); $('.loader').fadeOut(); $('.loader-mask').delay(350).fadeOut('slow'); + if (xhr.status === 400) { + let response = JSON.parse(xhr.responseText); + if (response.errors) { + $.each(response.errors, function (field, message) { + toastr.warning(message, 'Validation Error'); + }); + } else { + toastr.warning(response.message || 'Validation failed', 'Warning'); + } + } }); } diff --git a/app/Views/test_members_list.php b/app/Views/test_members_list.php index 4f880091..b09c362d 100644 --- a/app/Views/test_members_list.php +++ b/app/Views/test_members_list.php @@ -715,8 +715,19 @@ document.addEventListener("DOMContentLoaded", function () { console.error('Response Text: ', xhr.responseText); } - toastr.warning('Error uploading file', 'WARNING'); - console.error('Upload error:', error); + if (xhr.status === 400) { + let response = JSON.parse(xhr.responseText); + if (response.errors) { + $.each(response.errors, function (field, message) { + toastr.warning(message, 'Validation Error'); + }); + } else { + toastr.warning(response.message || 'Validation failed', 'Warning'); + } + }else{ toastr.warning('Error uploading file', 'WARNING'); } + + // toastr.warning('Error uploading file', 'WARNING'); + // console.error('Upload error:', error); }, complete: function() { $('.loader').fadeOut(); diff --git a/app/Views/thz_list.php b/app/Views/thz_list.php index dde7ad77..84d8f4cf 100644 --- a/app/Views/thz_list.php +++ b/app/Views/thz_list.php @@ -506,7 +506,17 @@ beccause = dataTables_length and dataTables_paginate need in same line thats why } }, error: function(xhr) { - toastr.error("Something went wrong!", 'Error'); + if (xhr.status === 400) { + let response = JSON.parse(xhr.responseText); + if (response.errors) { + $.each(response.errors, function (field, message) { + toastr.warning(message, 'Validation Error'); + }); + } else { + toastr.warning(response.message || 'Validation failed', 'Warning'); + } + }else{ + toastr.error("Something went wrong!", 'Error');} console.error(xhr.responseText); }, complete: function() { diff --git a/app/Views/thz_notes.php b/app/Views/thz_notes.php index 959a1633..91c916b8 100644 --- a/app/Views/thz_notes.php +++ b/app/Views/thz_notes.php @@ -571,7 +571,16 @@ data-backdrop="static" } }, error: function(xhr) { - toastr.error("Something went wrong!", 'Error'); + if (xhr.status === 400) { + let response = JSON.parse(xhr.responseText); + if (response.errors) { + $.each(response.errors, function (field, message) { + toastr.warning(message, 'Validation Error'); + }); + } else { + toastr.warning(response.message || 'Validation failed', 'Warning'); + } + }else{ toastr.error("Something went wrong!", 'Error'); } console.error(xhr.responseText); }, complete: function() { @@ -619,8 +628,19 @@ data-backdrop="static" } }, error: function(xhr) { - toastr.error("Something went wrong!", 'Error'); - console.error(xhr.responseText); + if (xhr.status === 400) { + let response = JSON.parse(xhr.responseText); + if (response.errors) { + $.each(response.errors, function (field, message) { + toastr.warning(message, 'Validation Error'); + }); + } else { + toastr.warning(response.message || 'Validation failed', 'Warning'); + } + }else{ + toastr.error("Something went wrong!", 'Error'); + console.error(xhr.responseText); + } }, complete: function() { btn.disabled = false;} }); diff --git a/app/Views/ticket_mail_template.php b/app/Views/ticket_mail_template.php index e55956db..9cda359e 100644 --- a/app/Views/ticket_mail_template.php +++ b/app/Views/ticket_mail_template.php @@ -434,7 +434,16 @@ setTimeout(function() { $('.loader').fadeOut(); $('.loader-mask').delay(350).fadeOut('slow'); - toastr.error('Something Wrong!', 'warning'); + if (xhr.status === 400) { + let response = JSON.parse(xhr.responseText); + if (response.errors) { + $.each(response.errors, function (field, message) { + toastr.warning(message, 'Validation Error'); + }); + } else { + toastr.warning(response.message || 'Validation failed', 'Warning'); + } + } else{toastr.error('Something Wrong!', 'warning');} }, 1000); } }); diff --git a/app/Views/tpa_basic_info.php b/app/Views/tpa_basic_info.php index 9830c520..b0ee3724 100755 --- a/app/Views/tpa_basic_info.php +++ b/app/Views/tpa_basic_info.php @@ -328,6 +328,17 @@ $('.loader').fadeOut(); $('.loader-mask').delay(350).fadeOut('slow'); console.log('Something Wrong!', 'warning'); + // Handle validation errors (CI4) + if (xhr.status === 400) { + let response = JSON.parse(xhr.responseText); + if (response.errors) { + $.each(response.errors, function (field, message) { + toastr.warning(message, 'Validation Error'); + }); + } else { + toastr.warning(response.message || 'Validation failed', 'Warning'); + } + } }, 1000); } }); diff --git a/app/Views/tpa_branch.php b/app/Views/tpa_branch.php index 4237421b..d3da93aa 100755 --- a/app/Views/tpa_branch.php +++ b/app/Views/tpa_branch.php @@ -478,6 +478,16 @@ $(document).ready(function () { setTimeout(function() { $('.loader').fadeOut(); $('.loader-mask').delay(350).fadeOut('slow'); + if (xhr.status === 400) { + let response = JSON.parse(xhr.responseText); + if (response.errors) { + $.each(response.errors, function (field, message) { + toastr.warning(message, 'Validation Error'); + }); + } else { + toastr.warning(response.message || 'Validation failed', 'Warning'); + } + } toastr.warning('Something Wrong!', 'warning'); }, 1000); }, diff --git a/app/Views/vehicle_details.php b/app/Views/vehicle_details.php index df98d9d2..f4bb4e27 100644 --- a/app/Views/vehicle_details.php +++ b/app/Views/vehicle_details.php @@ -222,7 +222,7 @@ $(document).ready(function() { $.each(res.data, function(index, item) { var row = ` ${item.file_name} - + @@ -247,7 +247,16 @@ $(document).ready(function() { $('.loader').fadeOut(); $('.loader-mask').delay(350).fadeOut('slow'); $submitButton.prop('disabled', false); - if (xhr.status === 404) { + if (xhr.status === 400) { + let response = JSON.parse(xhr.responseText); + if (response.errors) { + $.each(response.errors, function (field, message) { + toastr.warning(message, 'Validation Error'); + }); + } else { + toastr.warning(response.message || 'Validation failed', 'Warning'); + } + } else if (xhr.status === 404) { toastr.warning('Resource not found', 'Warning'); } else if (xhr.status === 500) { toastr.warning('Internal server error', 'Warning'); diff --git a/app/Views/vehicle_master_list.php b/app/Views/vehicle_master_list.php index f4b29f8e..b153b534 100644 --- a/app/Views/vehicle_master_list.php +++ b/app/Views/vehicle_master_list.php @@ -787,6 +787,16 @@ $("#vehicle_form").submit(function(event) { console.error(status, error); $('.loader').fadeOut(); $('.loader-mask').delay(350).fadeOut('slow'); + if (xhr.status === 400) { + let response = JSON.parse(xhr.responseText); + if (response.errors) { + $.each(response.errors, function (field, message) { + toastr.warning(message, 'Validation Error'); + }); + } else { + toastr.warning(response.message || 'Validation failed', 'Warning'); + } + } } }); }); diff --git a/app/Views/vehicle_type_list.php b/app/Views/vehicle_type_list.php index 4c7bbb09..53456a0f 100644 --- a/app/Views/vehicle_type_list.php +++ b/app/Views/vehicle_type_list.php @@ -581,7 +581,7 @@
- +
diff --git a/app/Views/vehicle_type_master_list.php b/app/Views/vehicle_type_master_list.php index a2001b8c..984f4ecc 100755 --- a/app/Views/vehicle_type_master_list.php +++ b/app/Views/vehicle_type_master_list.php @@ -222,6 +222,16 @@ console.error(xhr.responseText); $('.loader').fadeOut(); $('.loader-mask').delay(350).fadeOut('slow'); + if (xhr.status === 400) { + let response = JSON.parse(xhr.responseText); + if (response.errors) { + $.each(response.errors, function (field, message) { + toastr.warning(message, 'Validation Error'); + }); + } else { + toastr.warning(response.message || 'Validation failed', 'Warning'); + } + } }); } diff --git a/app/Views/view_rfq.php b/app/Views/view_rfq.php index 01d8aed9..5d332d35 100644 --- a/app/Views/view_rfq.php +++ b/app/Views/view_rfq.php @@ -7345,7 +7345,7 @@ function appendMultiFileData(data) { let isFirstField = container.childElementCount === 0; // Check if it's the first field let placeholder = isFirstField ? 'First file must be Demography.' : ''; - let accept = isFirstField ? '.xls,.xlsx' : ''; + let accept = isFirstField ? '.xls,.xlsx' : '.xls,.xlsx,.pdf,.jpg,.jpeg,.png'; if(isFirstField == 1){ From 8ed82a4148c7c5adf9716e6d8ac953e6be17c0f4 Mon Sep 17 00:00:00 2001 From: "venkatesh.r" Date: Tue, 27 Jan 2026 09:20:29 +0530 Subject: [PATCH 2/9] FEAT_CLAIM_DUMP_TPA_IMPORTER --- app/Controllers/ClientController.php | 7 +- app/Controllers/JobWorker.php | 8 + .../PolicyTransactionController.php | 3 + app/Controllers/TicketController.php | 24 +- app/Controllers/TicketServiceController.php | 254 ++++++ app/Helpers/utility_helper.php | 14 +- .../AbhiClaimImportService.php | 466 ++++++++++ .../BaseTpaClaimImportService.php | 368 ++++++++ .../FhplClaimImportService.php | 503 +++++++++++ .../IciciClaimImportService.php | 445 ++++++++++ .../MediAssistClaimImportService.php | 491 +++++++++++ .../RcareClaimImportService.php | 447 ++++++++++ .../VidalClaimImportService.php | 811 ++++++++++++++++++ app/Libraries/TpaClaimsImportFactory.php | 37 + app/Models/ClaimDumpFileModel.php | 3 + app/Models/ClaimsDumpFhplModel.php | 141 +++ app/Models/PolicyTransactionModel.php | 6 +- app/Views/claim_dump_file_list.php | 219 ++++- 18 files changed, 4230 insertions(+), 17 deletions(-) create mode 100644 app/Libraries/TPAClaimsImportServices/AbhiClaimImportService.php create mode 100644 app/Libraries/TPAClaimsImportServices/BaseTpaClaimImportService.php create mode 100644 app/Libraries/TPAClaimsImportServices/FhplClaimImportService.php create mode 100644 app/Libraries/TPAClaimsImportServices/IciciClaimImportService.php create mode 100644 app/Libraries/TPAClaimsImportServices/MediAssistClaimImportService.php create mode 100644 app/Libraries/TPAClaimsImportServices/RcareClaimImportService.php create mode 100644 app/Libraries/TPAClaimsImportServices/VidalClaimImportService.php create mode 100644 app/Libraries/TpaClaimsImportFactory.php create mode 100644 app/Models/ClaimsDumpFhplModel.php diff --git a/app/Controllers/ClientController.php b/app/Controllers/ClientController.php index 4bbf2189..d974f31c 100755 --- a/app/Controllers/ClientController.php +++ b/app/Controllers/ClientController.php @@ -6179,7 +6179,12 @@ class ClientController extends AdminController // $response = $ticketServiceController->getClaimExcelErrorData(["file_id" => 41]); // $response = $ticketServiceController->claimDumpOnBoardProcess(["file_id" => 17]); // $response = $ticketServiceController->extractExcelData("claims_dump_form_client.xlsx"); - // $response = $ticketServiceController->tpaClaimDumpImporter(["file_id" => 48]); + // $response = $ticketServiceController->tpaClaimDumpImporter(["file_id" => 52]); //reliance + // $response = $ticketServiceController->tpaClaimDumpImporter(["file_id" => 50]); //fhpl + // $response = $ticketServiceController->tpaClaimDumpImporter(["file_id" => 51]); //abhi + // $response = $ticketServiceController->tpaClaimDumpImporter(["file_id" => 48]); //vidal + // $response = $ticketServiceController->tpaClaimDumpImporter(["file_id" => 53]); //icici + // $response = $ticketServiceController->tpaClaimDumpToTicketMasterImporters(["file_id" => 48]); // $response = $ticketServiceController->tpaClaimDumpToTicketMasterImporters(["file_id" => 48]); // dd($response); diff --git a/app/Controllers/JobWorker.php b/app/Controllers/JobWorker.php index 9cc001dd..160c6fe9 100755 --- a/app/Controllers/JobWorker.php +++ b/app/Controllers/JobWorker.php @@ -155,6 +155,14 @@ class JobWorker extends AdminController 'type' => 'CC', // Handler Category 'handler' => 'App\Controllers\TicketServiceController', ], + 'tpaClaimDumpImporter' => [ + 'type' => 'CC', // Handler Category + 'handler' => 'App\Controllers\TicketServiceController', + ], + 'tpaClaimDumpToTicketMasterImporters' => [ + 'type' => 'CC', // Handler Category + 'handler' => 'App\Controllers\TicketServiceController', + ], 'excelMultieventFileFormateValidation' => [ 'type' => 'CC', // Handler Category 'handler' => 'App\Controllers\EmployeeMultiEventServiceController', diff --git a/app/Controllers/PolicyTransactionController.php b/app/Controllers/PolicyTransactionController.php index f0d6fc56..81eede97 100644 --- a/app/Controllers/PolicyTransactionController.php +++ b/app/Controllers/PolicyTransactionController.php @@ -1094,6 +1094,7 @@ private function updateInceptionPolicy($id, $data) { // print_r($data); die; + $data['updated_by'] = get_session_userid(); $old_pt_data = $this->policyTransactionModel->where('is_active', 1)->where("id", $id)->first(); $old_pt_co_share_data = $this->PTCOShareDetailsModel->where('is_active', 1)->where("id", $id)->first(); if ($this->policyTransactionModel->update($id, $data)) { @@ -2007,6 +2008,7 @@ { if ($id) { $data['is_active'] = 0; + $data['updated_by'] = get_session_userid(); $policy_transaction_data = $this->policyTransactionModel->where('id', $id)->first(); if($policy_transaction_data['policy_type_id'] > 7 && $type == 0){ @@ -2418,6 +2420,7 @@ private function updateEndorsementTransaction($id, $data) { + $data['updated_by'] = get_session_userid(); $old_endorse_data = $this->policyTransactionModel->where('id', $id)->where('is_active', 1)->first(); $update = $this->policyTransactionModel->where('id', $id)->set($data)->update(); diff --git a/app/Controllers/TicketController.php b/app/Controllers/TicketController.php index 09021a99..05ceb883 100644 --- a/app/Controllers/TicketController.php +++ b/app/Controllers/TicketController.php @@ -2813,6 +2813,8 @@ class TicketController extends BaseController { $data['tab_name'] = "Claim Dupm Upload"; $data['page_name'] = "Claims"; + $data['tpa_list'] = $this->TPAModel->where('is_active', 1)->findAll(); + if($this->request->is('get')){ @@ -2877,17 +2879,25 @@ class TicketController extends BaseController $status = 'inprogress'; $insert_data = [ 'file_name' => $filename, - 'status' => $status + 'status' => $status, + 'client_id' => !empty($this->request->getPost('client_id')) ? $this->request->getPost('client_id') : null, + 'client_policy_id' => !empty($this->request->getPost('client_policy_id')) ? $this->request->getPost('client_policy_id') : null, + 'tpa_id' => !empty($this->request->getPost('tpa_id')) ? $this->request->getPost('tpa_id') : null, ]; $file_id = $this->claimDumpFileModel->insert($insert_data); $this->myLogger->logme("error", 'claim_dumb_file_id : {file_id}, uploaded success', ['file_id' => $file_id]); //after file upload success than call the file formate validation in service controller - $ticketServiceController = new TicketServiceController(); - // $response = $ticketServiceController->claimDumpExcelFileFormatValidation(["file_id" => $file_id]); - $r = Jobs::addJob(['job_name' => 'claimDumpExcelFileFormatValidation', 'payload' => ['file_id' => $file_id]]); + // $ticketServiceController = new TicketServiceController(); + if(!empty($insert_data['tpa_id'])){ + $r = Jobs::addJob(['job_name' => 'tpaClaimDumpImporter', 'payload' => ['file_id' => $file_id]]); + // $response = $ticketServiceController->claimDumpExcelFileFormatValidation(["file_id" => $file_id]); + }else{ + $r = Jobs::addJob(['job_name' => 'claimDumpExcelFileFormatValidation', 'payload' => ['file_id' => $file_id]]); + // $response = $ticketServiceController->claimDumpExcelFileFormatValidation(["file_id" => $file_id]); + } return $this->respond(['status' => true, 'code' => 200, 'message' => 'File uploaded successfully. File being validated'], 200); } @@ -2986,8 +2996,12 @@ class TicketController extends BaseController } + + // -------- CLAIM MIS UPLOAD ---------------------------------------------------------------------------------------------- + public function claimMisFileList() - { + { + $data['tab_name'] = "Claim MIS Upload"; $data['page_name'] = "Cliam MIS Files"; $data['claim_mis_file_list'] = $this->claimmisFileModel ->select('claims_mis_files.*, user_profiles.first_name as user_name') diff --git a/app/Controllers/TicketServiceController.php b/app/Controllers/TicketServiceController.php index 5cfa99f4..14c1b19a 100644 --- a/app/Controllers/TicketServiceController.php +++ b/app/Controllers/TicketServiceController.php @@ -7,6 +7,9 @@ use CodeIgniter\HTTP\ResponseInterface; use CodeIgniter\API\ResponseTrait; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use Kint\Kint; +use App\Libraries\TpaClaimsImportFactory; +use App\Libraries\TPAClaimsImportServices\FhplClaimImportService; +use App\Libraries\TPAClaimsImportServices\BaseTpaClaimImportService; use App\Models\ClaimDumpFileModel; use App\Models\EmployeeModel; @@ -15,10 +18,14 @@ use App\Models\TPAModel; use App\Models\ClientModel; use App\Models\TicketClaimStatusModel; use App\Models\ClientPolicyModel; +use App\Models\ClaimsDumpFhplModel; use App\Helpers\ExcelSanitizeHelper; use App\Models\TicketMasterModel; +use PhpOffice\PhpSpreadsheet\IOFactory; +use PhpOffice\PhpSpreadsheet\Spreadsheet; + class TicketServiceController extends BaseController { use ResponseTrait; @@ -35,6 +42,10 @@ class TicketServiceController extends BaseController protected $ticketClaimStatusModel; protected $clientPolicyModel; + protected $medi_assist_primary_key; + protected $vidal_primary_key; + protected $icici_primary_key; + public function __construct() { @@ -50,6 +61,11 @@ class TicketServiceController extends BaseController $this->ticketClaimStatusModel = new TicketClaimStatusModel(); $this->clientPolicyModel = new ClientPolicyModel(); + $this->medi_assist_primary_key = getenv('MEDI_ASSIST_PRIMARY_KEY_CONSTANT'); + $this->vidal_primary_key = getenv('VIDAL_PRIMARY_KEY_CONSTANT'); + $this->icici_primary_key = getenv('ICICI_PRIMARY_KEY_CONSTANT'); + + $this->claim_dump_excel_columns = [ // Mandatory Fields @@ -1819,5 +1835,243 @@ class TicketServiceController extends BaseController { } + + + // -------------------------------------------------------------------------------------------------------------------------------- + + + public function tpaClaimImporter($params) + { + $file_id = $params['file_id']; + $tpa_claims_files_data = $this->claimDumpFileModel->where('id', $file_id)->first(); + + + if($this->vidal_primary_key == $tpa_claims_files_data['tpa_id']){ + + }else if($this->icici_primary_key == $tpa_claims_files_data['tpa_id']){ + + }else{ + $this->myLogger->logme('error', 'No TPA found to import'); + return ['status' => false, 'message' => 'No TPA found to import']; + } + } + + public function tpaClaimDumpImporter($params) + { + try { + + $file_id = $params['file_id'] ?? null; + $file_path = WRITEPATH . 'uploads/claim_dump_excel/'; + + if (!$file_id) { + return ['status' => false, 'message' => 'File ID is missing']; + } + + $fileData = $this->claimDumpFileModel->where('id', $file_id)->first(); + + 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']; + } + + $handler = TpaClaimsImportFactory::make($fileData['tpa_id'] ?? 0); + $result = $handler->runTpaClaimDumpInsert($file_full_path, $file_id); + + // ---------- Prepare update data ---------- + $data = []; + + if (!empty($result['status']) && $result['status'] === true) { + $data['status'] = 'success'; + $data['reason'] = null; + } else { + $data['status'] = 'failed'; + + $errorMessage = $result['message'] ?? 'Unknown import error'; + + $reason = [ + 'error_summary' => array_count_values([5]), + 'error_data' => $errorMessage + ]; + + $data['reason'] = json_encode($reason, JSON_UNESCAPED_UNICODE); + } + + // dd($data); + // ---------- Update DB ---------- + $sql = "UPDATE claim_dump_files SET status = ?, reason = ? WHERE id = ?"; + + $updated = db_connect()->query( + $sql, + [ + $data['status'] ?? null, + $data['reason'] ?? null, + $file_id + ] + ); + + if (!$updated) { + $this->myLogger->logme('error', 'Claim dump file update failed for file_id: ' . $file_id); + } + + dd(db_connect()->getLastQuery()->getQuery()); + + if(!empty($result['status']) && $result['status'] === true){ + $r = Jobs::addJob(['job_name' => 'tpaClaimDumpToTicketMasterImporters', 'payload' => ['file_id' => $file_id]]); + } + + return $result; + + } catch (\Throwable $th) { + + $this->myLogger->logme( + "error", + 'TPA_CLAIM_IMPORTER_JOB : ' . + $th->getMessage() . ' | Line: ' . $th->getLine() + ); + + return [ + 'status' => false, + 'message' => 'TPA Claim dump import failed', + 'error_data' => [ + 'message' => $th->getMessage(), + 'file' => $th->getFile(), + 'line' => $th->getLine(), + 'trace' => $th->getTraceAsString() + ] + ]; + } + } + + public function tpaClaimDumpToTicketMasterImporters($params) + { + try { + + $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']; + } + + $handler = TpaClaimsImportFactory::make($fileData['tpa_id'] ?? 0); + $result = $handler->runTicketMasterInsert($params); + + return $result; + + } catch (\Throwable $th) { + + $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, + ]; + + return [ + 'status' => false, + 'message' => $th->getMessage(), + 'error_data' => json_encode($errorData, JSON_PRETTY_PRINT) + ]; + } + } + + public function tpaClaimDumpToTicketMasterImportBatchSeperater($params) + { + try { + + $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']; + } + + $handler = TpaClaimsImportFactory::make($fileData['tpa_id'] ?? 0); + $result = $handler->runTicketMasterInsert($params); + + return $result; + + } catch (\Throwable $th) { + + $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, + ]; + + return [ + 'status' => false, + 'message' => $th->getMessage(), + 'error_data' => json_encode($errorData, JSON_PRETTY_PRINT) + ]; + } + } + + public function readExcelBySheetName(string $filePath, string $sheetName): array + { + if (!file_exists($filePath)) { + return []; + } + + $spreadsheet = IOFactory::load($filePath); + + // Get sheet by name + $sheet = $spreadsheet->getSheetByName($sheetName); + + if ($sheet === null) { + return []; + } + + $rows = $sheet->toArray(null, true, true, true); + + // Need at least header + one row + if (count($rows) < 2) { + return []; + } + + // First row = headers + $headers = array_shift($rows); + $headers = array_map('trim', $headers); + + $data = []; + + foreach ($rows as $row) { + // Skip completely empty rows + if (!array_filter($row)) { + continue; + } + + $item = []; + + foreach ($headers as $key => $headerName) { + if ($headerName !== '') { + $item[$headerName] = $row[$key] ?? null; + } + } + + $data[] = $item; + } + + return $data; + } + } diff --git a/app/Helpers/utility_helper.php b/app/Helpers/utility_helper.php index 15d873eb..5295224b 100755 --- a/app/Helpers/utility_helper.php +++ b/app/Helpers/utility_helper.php @@ -649,7 +649,7 @@ if (!function_exists('change_date_format')) { $date = DateTime::createFromFormat($source_format, $date_str); if (!$date) { // throw new Exception("Invalid date string for source format: $source_format"); - log_message('error', "❌ Date format error : Invalid date string | Params => date_str: {$date_str}, source_format: {$source_format}, output_format: {$output_format}"); + // log_message('error', "❌ Date format error : Invalid date string | Params => date_str: {$date_str}, source_format: {$source_format}, output_format: {$output_format}"); return null; } return $date->format($output_format); @@ -660,7 +660,7 @@ if (!function_exists('change_date_format')) { $date = DateTime::createFromFormat($source_format, $date_str); if (!$date) { // throw new Exception("Invalid date string for source format: $source_format"); - log_message('error', "❌ Date format error : Invalid date string | Params => date_str: {$date_str}, source_format: {$source_format}, output_format: {$output_format}"); + // log_message('error', "❌ Date format error : Invalid date string | Params => date_str: {$date_str}, source_format: {$source_format}, output_format: {$output_format}"); return null; } return $date->format('Y-m-d'); // MySQL default format @@ -677,15 +677,15 @@ if (!function_exists('change_date_format')) { // If no format matches, throw an exception $allowed_placeholders = implode(', ', $allowed_formats); // throw new Exception("Invalid date string format. Allowed formats: $allowed_placeholders"); - log_message( - 'error', - "❌ Date format error: Invalid date string. Allowed formats: {$allowed_placeholders} | Params => date_str: {$date_str}, source_format: {$source_format}, output_format: {$output_format}" - ); + // log_message( + // 'error', + // "❌ Date format error: Invalid date string. Allowed formats: {$allowed_placeholders} | Params => date_str: {$date_str}, source_format: {$source_format}, output_format: {$output_format}" + // ); return null; } } catch (Exception $e) { // return "Error: " . $e->getMessage(); - log_message('error', "❌ Date format error: {$e->getMessage()} | Params => date_str: {$date_str}, source_format: {$source_format}, output_format: {$output_format}"); + // log_message('error', "❌ Date format error: {$e->getMessage()} | Params => date_str: {$date_str}, source_format: {$source_format}, output_format: {$output_format}"); return null; } diff --git a/app/Libraries/TPAClaimsImportServices/AbhiClaimImportService.php b/app/Libraries/TPAClaimsImportServices/AbhiClaimImportService.php new file mode 100644 index 00000000..1f62ea7f --- /dev/null +++ b/app/Libraries/TPAClaimsImportServices/AbhiClaimImportService.php @@ -0,0 +1,466 @@ + ["col_name" => "ABHI Claim No", "col_index" => 0], "db_column" => "abhi_claim_no"], + ["excel_column" => ["col_name" => "New ABHI Claim No With Extension", "col_index" => 1], "db_column" => "new_abhi_claim_no_with_extension"], + ["excel_column" => ["col_name" => "Unique Count", "col_index" => 2], "db_column" => "unique_count"], + ["excel_column" => ["col_name" => "Proposer Name", "col_index" => 3], "db_column" => "proposer_name"], + ["excel_column" => ["col_name" => "Patient Name", "col_index" => 4], "db_column" => "patient_name"], + ["excel_column" => ["col_name" => "Family ID", "col_index" => 5], "db_column" => "family_id"], + ["excel_column" => ["col_name" => "Member Code", "col_index" => 6], "db_column" => "member_code"], + ["excel_column" => ["col_name" => "Patient Age", "col_index" => 7], "db_column" => "patient_age"], + ["excel_column" => ["col_name" => "Relation", "col_index" => 8], "db_column" => "relation"], + ["excel_column" => ["col_name" => "Gender", "col_index" => 9], "db_column" => "gender"], + ["excel_column" => ["col_name" => "Certificate No", "col_index" => 10], "db_column" => "certificate_no"], + ["excel_column" => ["col_name" => "Master Policy No", "col_index" => 11], "db_column" => "master_policy_no"], + ["excel_column" => ["col_name" => "Policy Number", "col_index" => 12], "db_column" => "policy_number"], + ["excel_column" => ["col_name" => "Policy From", "col_index" => 13], "db_column" => "policy_from"], + ["excel_column" => ["col_name" => "Policy Upto", "col_index" => 14], "db_column" => "policy_upto"], + ["excel_column" => ["col_name" => "Product Name", "col_index" => 15], "db_column" => "product_name"], + ["excel_column" => ["col_name" => "Product Name 1", "col_index" => 16], "db_column" => "product_name_1"], + ["excel_column" => ["col_name" => "Sub - Product", "col_index" => 17], "db_column" => "sub_product"], + ["excel_column" => ["col_name" => "Policy Category", "col_index" => 18], "db_column" => "policy_category"], + ["excel_column" => ["col_name" => "Policy Category (Carry Forward till Q3 18-19)+(New Q4 18-19 Onward)", "col_index" => 19], "db_column" => "policy_category_cf_q3_q4"], + ["excel_column" => ["col_name" => "Sum Insured", "col_index" => 20], "db_column" => "sum_insured"], + ["excel_column" => ["col_name" => "Bonus", "col_index" => 21], "db_column" => "bonus"], + ["excel_column" => ["col_name" => "Intimation Date", "col_index" => 22], "db_column" => "intimation_date"], + ["excel_column" => ["col_name" => "Date Of Doc Rec", "col_index" => 23], "db_column" => "date_of_doc_rec"], + ["excel_column" => ["col_name" => "Intimation Final Month", "col_index" => 24], "db_column" => "intimation_final_month"], + ["excel_column" => ["col_name" => "Reported Year", "col_index" => 25], "db_column" => "reported_year"], + ["excel_column" => ["col_name" => "Reported Qurter", "col_index" => 26], "db_column" => "reported_quarter"], + ["excel_column" => ["col_name" => "Hospital Name", "col_index" => 27], "db_column" => "hospital_name"], + ["excel_column" => ["col_name" => "Hospital City", "col_index" => 28], "db_column" => "hospital_city"], + ["excel_column" => ["col_name" => "Hospital State", "col_index" => 29], "db_column" => "hospital_state"], + ["excel_column" => ["col_name" => "Diagnosis", "col_index" => 30], "db_column" => "diagnosis"], + ["excel_column" => ["col_name" => "ICD Chapter", "col_index" => 31], "db_column" => "icd_chapter"], + ["excel_column" => ["col_name" => "ICD Block", "col_index" => 32], "db_column" => "icd_block"], + ["excel_column" => ["col_name" => "ICD Level1", "col_index" => 33], "db_column" => "icd_level1"], + ["excel_column" => ["col_name" => "ICD Level2", "col_index" => 34], "db_column" => "icd_level2"], + ["excel_column" => ["col_name" => "Procedure Description", "col_index" => 35], "db_column" => "procedure_description"], + ["excel_column" => ["col_name" => "PCS Description", "col_index" => 36], "db_column" => "pcs_description"], + ["excel_column" => ["col_name" => "DOA", "col_index" => 37], "db_column" => "doa"], + ["excel_column" => ["col_name" => "DOD", "col_index" => 38], "db_column" => "dod"], + ["excel_column" => ["col_name" => "Claim Type", "col_index" => 39], "db_column" => "claim_type"], + ["excel_column" => ["col_name" => "Claim Category", "col_index" => 40], "db_column" => "claim_category"], + ["excel_column" => ["col_name" => "Disc Datails", "col_index" => 41], "db_column" => "disc_details"], + ["excel_column" => ["col_name" => "Disc Date", "col_index" => 42], "db_column" => "disc_date"], + ["excel_column" => ["col_name" => "Hospital Code", "col_index" => 43], "db_column" => "hospital_code"], + ["excel_column" => ["col_name" => "Claim Status", "col_index" => 44], "db_column" => "claim_status"], + ["excel_column" => ["col_name" => "Final ABHI Status-Current Month", "col_index" => 45], "db_column" => "final_abhi_status_current_month"], + ["excel_column" => ["col_name" => "Claimed Amount", "col_index" => 46], "db_column" => "claimed_amount"], + ["excel_column" => ["col_name" => "ABHI Amount Less Coins - Current Month", "col_index" => 47], "db_column" => "abhi_amount_less_coins_current_month"], + ["excel_column" => ["col_name" => "Repudiation Date", "col_index" => 48], "db_column" => "repudiation_date"], + ["excel_column" => ["col_name" => "Settled Date", "col_index" => 49], "db_column" => "settled_date"], + ["excel_column" => ["col_name" => "Settled Month", "col_index" => 50], "db_column" => "settled_month"], + ["excel_column" => ["col_name" => "Settled Year", "col_index" => 51], "db_column" => "settled_year"], + ["excel_column" => ["col_name" => "Settled Quarter", "col_index" => 52], "db_column" => "settled_quarter"], + ["excel_column" => ["col_name" => "Rejection Category", "col_index" => 53], "db_column" => "rejection_category"], + ["excel_column" => ["col_name" => "Rejection Category - Level 1", "col_index" => 54], "db_column" => "rejection_category_level_1"], + ["excel_column" => ["col_name" => "Rejection Category - Level 2", "col_index" => 55], "db_column" => "rejection_category_level_2"], + ["excel_column" => ["col_name" => "COVID tagging - Current Month", "col_index" => 56], "db_column" => "covid_tagging_current_month"], + ["excel_column" => ["col_name" => "EXPECTED DOA", "col_index" => 57], "db_column" => "expected_doa"], + ["excel_column" => ["col_name" => "EXPECTED DOD", "col_index" => 58], "db_column" => "expected_dod"], + ["excel_column" => ["col_name" => "AGENT/BROKER CODE", "col_index" => 59], "db_column" => "agent_broker_code"], + ["excel_column" => ["col_name" => "AGENT/BROKER NAME", "col_index" => 60], "db_column" => "agent_broker_name"], + ["excel_column" => ["col_name" => "HEALTHCARD_ID", "col_index" => 61], "db_column" => "healthcard_id"], + ["excel_column" => ["col_name" => "ABHI_NETWORK_NON_NETWORK", "col_index" => 62], "db_column" => "abhi_network_non_network"], + ["excel_column" => ["col_name" => "CORPORATE_EMPLOYEE_CODE", "col_index" => 63], "db_column" => "corporate_employee_code"], + ]; + + + protected $ticketMasterMapping = [ + + // Employee / Member details + 'member_code' => 'emp_code', + 'relation' => 'relationship', + + // Policy / Claim identifiers + 'policy_number' => 'policy_no', + 'abhi_claim_no' => 'claim_number', + + // Dates + 'doa' => 'doa', + 'dod' => 'dod', + 'intimation_date' => 'date_of_intimat', + + // Claim info + 'claim_status' => 'tpa_claim_status', + 'claimed_amount' => 'claim_amount', + + // Hospital details + 'hospital_name' => 'hospital_name', + 'hospital_city' => 'hospital_city', + 'hospital_state' => 'hospital_state', + + // Settlement / decision + 'repudiation_date' => 'denial_date', + 'settled_date' => 'settled_date', + 'rejection_category' => 'denial_reason', + + // Misc + 'diagnosis' => 'claim_description', + 'healthcard_id' => 'tpa_no', + + 'priority' => 1, + 'mode_of_intimation' => 5, + 'ticket_type_id' => 1, + ]; + + + protected $statusMapping = [ + 'Settled' => 11, + 'Rejected' => 8, + 'Cancelled' => 13, + ]; + + + /** + * ABSTRACT FUNCTIONs + */ + public function bulkInsertTPATable(array $data): bool + { + if (empty($data)) { + return false; + } + + $builder = $this->db->table('claims_dump_abhi'); + + foreach ($data as $value) { + + if (!$builder->insert($value)) { + + // 🔍 Debug purpose + log_message('error', print_r($this->db->error(), true)); + log_message('error', $this->db->getLastQuery()); + + return false; + } + } + + return true; + } + + + public function importClaimMaster(array $data): bool + { + if (empty($data)) { + return false; + } + + $ticketMasterModel = new TicketMasterModel(); + $ticketMasterModel->insertBatch($data); + + return true; + } + + + public function updateTicketIdInTPATable(): bool + { + if (empty($data)) { + return false; + } + + $builder = $this->db->table('claims_dump_abhi'); + $builder->insertBatch($data); + + return true; + } + + + public function updateTicketMasterRejectedReasonInTPATable($data): bool + { + if (empty($data)) { + return false; + } + + $builder = $this->db->table('claims_dump_abhi'); + $builder->insertBatch($data); + + return true; + } + + + /** + * MAPPING FUNCTIONs + */ + + public function mapTPAData(array $rows, $file_id): array + { + $ClientPolicyModel = new ClaimDumpFileModel(); + $file_data = $ClientPolicyModel->where('id', $file_id)->first(); + + $mapped = []; + + foreach ($rows as $row) { + + $item = []; + + foreach ($this->mapping as $map) { + $excelColumn = $map['excel_column']['col_name']; + $dbColumn = $map['db_column']; + + $value = $row[$excelColumn] ?? null; + + if ($this->isDateValue($value)) { + $value = $this->normalizeDate($value); + } + + $item[$dbColumn] = trim($value); + } + + $params = [ + 'doa' => $item['doa'] ?? null, + 'member_code' => $item['member_code'] ?? null, + 'claimed_amount' => $item['claimed_amount'] ?? null, + 'healthcard_id' => $item['healthcard_id'] ?? null + ]; + + $is_duplicate = $this->checkDuplicateTpaClaim('claims_dump_abhi', $params); + + if ($is_duplicate) { + $item = []; + continue; + } + + $item['file_id'] = $file_id ?? null; + $item['client_id'] = $file_data['client_id'] ?? null; + $item['client_policy_id'] = $file_data['client_policy_id'] ?? null; + $item['created_by'] = $file_data['created_by'] ?? null; + + $mapped[] = $item; + } + + return $mapped; + } + + public function mapClaimMasterData($file_id): array + { + + $ClientPolicyModel = new ClaimDumpFileModel(); + $file_data = $ClientPolicyModel->where('id', $file_id)->first(); + + $tpaClaimDumpData = $this->getTpaClaimDumpData('claims_dump_abhi', ['file_id' => $file_id]); + + if (empty($tpaClaimDumpData)) { + return ['status' => false, 'message' => "No data to insert in TICKET MASTER"]; + } + + + $ClientPolicyModel = new ClientPolicyModel(); + $client_policy_data = $ClientPolicyModel + ->select(" + client_policy.*, + ( + SELECT id + FROM client_rm + WHERE is_active = 1 + AND level = 3 + AND client_id = client_policy.client_id + ORDER BY id ASC + LIMIT 1 + ) AS acm_id + ") + ->where('client_policy.id', $file_data['client_policy_id']) + ->where('client_policy.is_active', 1) + ->first(); + + try { + + $mapped = []; + $rejecetd_reason = []; + + foreach ($tpaClaimDumpData as $row) { + + $params = [ + 'doa' => change_date_format($row['doa'] ?? '') ?? null, + 'emp_code' => $row['member_code'] ?? null, + 'claim_amount' => $row['claimed_amount'] ?? null, + 'tpa_no' => $row['healthcard_id'] ?? null + ]; + + $isduplicate = $this->checkDublicateTicketMasterClaim($params); + + if ($isduplicate) { + $reason = "This claim already exists in our system."; + $rejecetd_reason[$row['id']] = ["ticket_master_insert_reject_reason" => $reason]; + continue; + } + + $item = []; + + $item['client_id'] = $client_policy_data['client_id'] ?? null; + $item['client_policy_id'] = $client_policy_data['id'] ?? null; + $item['insurer_id'] = $client_policy_data['insurer_id'] ?? null; + $item['tpa_id'] = $client_policy_data['tpa_id'] ?? null; + $item['acm_id'] = $client_policy_data['acm_id'] ?? null; + $item['policy_no'] = $client_policy_data['policy_no'] ?? null; + $item['relationship'] = $this->convertRelation($row['relation'] ?? null); + + $employee_data = $this->getEmployeeDetails($file_data['client_id'], $file_data['client_policy_id'], $row['member_code'], $item['relationship']); + + if (!empty($employee_data)) { + $item['emp_id'] = $employee_data['id'] ?? null; + $item['emp_name'] = $employee_data['name'] ?? null; + $item['emp_mail'] = $employee_data['email_corporate'] ?? null; + $item['emp_mobile'] = $employee_data['mobile'] ?? null; + $item['insured_emp_id'] = $employee_data['insured_emp_id'] ?? null; + $item['insured_name'] = $employee_data['insured_name'] ?? null; + } else { + + $reason = sprintf( + 'The policy number "%s" does not exist in our system. ' . + 'Details - Client ID: %s, Client Policy ID: %s, Employee Number: %s, Relationship: %s', + $row['insurer_policy_number'], + $file_data['client_id'], + $file_data['client_policy_id'], + $row['employee_number'], + $item['relationship'] + ); + + $rejecetd_reason[$row['id']] = ["ticket_master_insert_reject_reason" => $reason]; + continue; + } + + foreach ($this->ticketMasterMapping as $tpaKey => $ticketMasterKey) { + $item[$ticketMasterKey] = array_key_exists($tpaKey, $row) ? $row[$tpaKey] : null; + } + + // Meta fields + $item['claim_status_id'] = $statusMapping[$row['claim_status']] ?? 61; + $item['file_id'] = $file_id; + $item['claim_dump_ref_id'] = $row['id']; + $item['created_by'] = $file_data['created_by'] ?? null; + $item['claim_type'] = isset($row['mainclaim_prepost_type']) && !empty($row['mainclaim_prepost_type']) && strtolower($row['mainclaim_prepost_type']) == 'normal' ? 1 : 3; + + $mapped[] = $item; + } + + return ['status' => true, 'mapped_array' => $mapped, 'rejected_reason_array' => $rejecetd_reason]; + } 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, + ]; + + return ['status' => false, "message" => $errorData['message'], 'error_data' => $errorData]; + } + } + + + /** + * HELPER FUNCTIONs + */ + + public function isDateValue($value): bool + { + if (empty($value)) { + return false; + } + + // Excel numeric date + if (is_numeric($value) && $value > 30000) { + return true; + } + + return strtotime(str_replace('/', '-', $value)) !== false; + } + + public function normalizeDate($value): ?string + { + try { + if (empty($value)) { + return null; + } + + // Excel numeric date + if (is_numeric($value)) { + return date( + 'Y-m-d', + \PhpOffice\PhpSpreadsheet\Shared\Date::excelToTimestamp($value) + ); + } + + $value = trim((string) $value); + + // Replace / with - for strtotime compatibility + $value = str_replace('/', '-', $value); + + $timestamp = strtotime($value); + + if ($timestamp === false) { + return null; + } + + return date('Y-m-d', $timestamp); + + } catch (\Throwable $e) { + return null; + } + } + + public function convertRelation(?string $relation): ?string + { + if (empty($relation)) { + return null; + } + + $relation = strtolower($relation); + + if (str_contains($relation, 'self')) { + return 'self'; + } + + if (str_contains($relation, 'spouse') || str_contains($relation, 'wife') || str_contains($relation, 'husband')) { + return 'spouse'; + } + + if (str_contains($relation, 'daughter')) { + return 'daughter'; + } + + if (str_contains($relation, 'son')) { + return 'son'; + } + + if (str_contains($relation, 'father in law') || str_contains($relation, 'father-in-law')) { + return 'father-in-law'; + } + + if (str_contains($relation, 'mother in law') || str_contains($relation, 'mother-in-law')) { + return 'mother-in-law'; + } + + if (str_contains($relation, 'father')) { + return 'father'; + } + + if (str_contains($relation, 'mother')) { + return 'mother'; + } + + return null; // unmatched case + } + +} diff --git a/app/Libraries/TPAClaimsImportServices/BaseTpaClaimImportService.php b/app/Libraries/TPAClaimsImportServices/BaseTpaClaimImportService.php new file mode 100644 index 00000000..33fbedc9 --- /dev/null +++ b/app/Libraries/TPAClaimsImportServices/BaseTpaClaimImportService.php @@ -0,0 +1,368 @@ +db = db_connect(); + $this->claimDumpFileModel = new ClaimDumpFileModel(); + } + + /** + * First JOB for insert TPA wise Bulk Upload + */ + public function runTpaClaimDumpInsert(string $filePath, int $fileId): array + { + $this->db->transStart(); + + $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); + } + // 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.']; + } + + if (env('FHPL_PRIMARY_KEY_CONSTANT') == $fileData['tpa_id']) { + $ClaimsDumpFhplModel = $this->db->table('claims_dump_fhpl'); + $return_res = $ClaimsDumpFhplModel->insertBatch($tpaInsertData); + } else if (env('R_CARE_PRIMARY_KEY_CONSTANT') == $fileData['tpa_id']) { + $ClaimsDumpIciciModel = $this->db->table('claims_dump_reliance'); + $return_res = $ClaimsDumpIciciModel->insertBatch($tpaInsertData); + } else if (env('ICICI_PRIMARY_KEY_CONSTANT') == $fileData['tpa_id']) { + $ClaimsDumpIciciModel = $this->db->table('claims_dump_icici'); + $return_res = $ClaimsDumpIciciModel->insertBatch($tpaInsertData); + } else if (env('ABHI_PRIMARY_KEY_CONSTANT') == $fileData['tpa_id']) { + // $ClaimsDumpAbhiModel = $this->db->table('claims_dump_abhi'); + // $return_res = $ClaimsDumpAbhiModel->insertBatch($tpaInsertData); + $return_res = $this->bulkInsertTPATable($tpaInsertData); + } else if (env('VIDAL_PRIMARY_KEY_CONSTANT') == $fileData['tpa_id']) { + $ClaimsDumpVidalModel = $this->db->table('claims_dump_vidal'); + $return_res = $ClaimsDumpVidalModel->insertBatch($tpaInsertData); + } else if (env('MEDI_ASSIST_PRIMARY_KEY_CONSTANT') == $fileData['tpa_id']) { + $ClaimsDumpMediAssistModel = $this->db->table('claims_dump_medi_assist'); + $return_res = $ClaimsDumpMediAssistModel->insertBatch($tpaInsertData); + } else{ + + } + + // $return_res = $this->bulkInsertTPATable($tpaInsertData); + + if (!$return_res) { + 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 ?? [])]; + } + + /** + * Second JOB for insert Ticket Master table after insert the TPA bulk upload success + */ + public function runTicketMasterInsert(array $params): array + { + $this->db->transStart(); + + $file_id = $params['file_id']; + + $ticketMasterData = $this->mapClaimMasterData($file_id); + + if (!$ticketMasterData['status']) { + return $ticketMasterData; + } + + $return_res = $this->importClaimMaster($ticketMasterData['mapped_array']); + + if(!$return_res){ + return ['status' => false, 'message' => 'Ticket Master Claim bulk insert failed']; + } + + $this->updateTicketMasterRejectedReasonInTPATable($ticketMasterData['rejected_reason_array']); + + $this->db->transComplete(); + + if ($this->db->transStatus() === false) { + return ['status' => false, 'message' => 'Ticket Master Claim bulk insert failed']; + } + + + + return ['status' => true, 'message' => 'Ticket Master Claim inserted successfully']; + + } + + /** + * Read Excel and return associative rows (header based) + */ + protected function readExcel(string $filePath): array + { + helper('excel_util_helper'); + + if (!file_exists($filePath)) { + throw new RuntimeException("File not found: {$filePath}"); + } + + $spreadsheet = IOFactory::load($filePath); + $sheet = $spreadsheet->getActiveSheet(); + + $rows = $sheet->toArray(null, true, true, true); + + // dd($rows); + + if (count($rows) < 2) { + return []; + } + + // First row is header + $headers = array_shift($rows); + $headers = array_map('trim', $headers); + + $data = []; + + foreach ($rows as $row) { + + if(check_row_is_empty_or_null($row)){ + break; + } + + $item = []; + foreach ($headers as $key => $headerName) { + if ($headerName !== '') { + $item[$headerName] = $row[$key] ?? null; + } + } + $data[] = $item; + } + + return $data; + } + + /** + * Read Excel By Sheet name and return associative rows (header based) + */ + + protected function readExcelBySheetName(string $filePath, string $sheetName): array + { + if (!file_exists($filePath)) { + throw new RuntimeException("File not found: {$filePath}"); + } + + $spreadsheet = IOFactory::load($filePath); + + // Get sheet by name + $sheet = $spreadsheet->getSheetByName($sheetName); + + if ($sheet === null) { + throw new RuntimeException("Sheet '{$sheetName}' not found in Excel file"); + } + + $rows = $sheet->toArray(null, true, true, true); + + // Need at least header + one row + if (count($rows) < 2) { + return []; + } + + // First row = headers + $headers = array_shift($rows); + $headers = array_map('trim', $headers); + + $data = []; + + foreach ($rows as $row) { + // Skip completely empty rows + if (!array_filter($row)) { + continue; + } + + $item = []; + + foreach ($headers as $key => $headerName) { + if ($headerName !== '') { + $item[$headerName] = $row[$key] ?? null; + } + } + + $data[] = $item; + } + + return $data; + } + + + /** + * Dublicate check in the ticket_master table records + */ + protected function checkDublicateTicketMasterClaim(array $param): bool + { + $ticketMaster = new TicketMasterModel(); + $ticket_master_data = $ticketMaster + ->where('doa', $param['doa']) + ->where('tpa_no', $param['tpa_no']) + ->where('claim_amount', $param['claim_amount']) + ->where('emp_code', $param['emp_code']) + ->where('is_active', 1) + ->findAll(); + + if(count($ticket_master_data) > 0){ + return true; + } + + return false; + } + + /** + * Dublicate check in the TPA specific table records + */ + protected function checkDuplicateTpaClaim(string $table, array $params): bool + { + return $this->db->table($table) + ->where($params) + ->where('is_active', 1) + ->countAllResults() > 0; + } + + /** + * Dublicate check in the TPA specific table records + */ + protected function getTpaClaimDumpData(string $table, array $params): array + { + $tpaClaimDumpDataCount = $this->db + ->table($table) + ->where('is_active', 1) + ->where('file_id', $params['file_id']) + ->where('ticket_id IS NULL') + ->countAllResults(); + + $batch_size = 100; + $total_batch = (int) ceil($tpaClaimDumpDataCount / $batch_size); + $batch_no = isset($params['batch_no']) ? (int) $params['batch_no'] : null; + $last_emp_id = (int) ($params['last_emp_id'] ?? 0); + + + return $this->db + ->table($table) + ->where('is_active', 1) + ->where('file_id', $params['file_id']) + ->where('ticket_id IS NULL') + ->get() + ->getResultArray(); + + } + + /** + * Dublicate check in the TPA specific table records + */ + public function getEmployeeDetails(int $client_id, int $client_policy_id, string $emp_code, string $relation): array + { + $EmployeeModel = new EmployeeModel(); + $employeeData = $EmployeeModel + ->select([ + 'employees.id AS emp_id', + 'employees.email_corporate AS emp_mail', + 'employees.mobile AS emp_mobile', + 'employees.name AS emp_name', + + // insured employee + 'insured.id AS insured_emp_id', + 'insured.name AS insured_name' + ]) + ->join( + 'employee_polices', + 'employees.id = employee_polices.employee_id' + ) + ->join( + 'employees AS insured', + "insured.emp_code = employees.emp_code + AND insured.client_id = employees.client_id + AND LOWER(insured.relationship) = " . $EmployeeModel->db->escape(strtolower($relation)), + 'left' + ) + ->where('employees.is_active', 1) + ->where('employee_polices.is_active', 1) + ->where('employee_polices.client_policy_id', $client_policy_id) + ->where('employees.client_id', $client_id) + ->where('employees.emp_code', $emp_code) + ->where('LOWER(employees.relationship)', 'self') + ->first(); + + + return $employeeData ?? []; + } + + /** + * Map Excel rows to TPA table structure + */ + abstract protected function mapTPAData(array $rows, $fileId): array; + + /** + * Map DB rows to Ticket Master table structure + */ + abstract protected function mapClaimMasterData($fileId): array; + + /** + * Insert into TPA-specific table (bulk) + */ + abstract protected function bulkInsertTPATable(array $data): bool; + + /** + * Insert into Ticket-Master-specific table (bulk) + */ + abstract protected function importClaimMaster(array $data): bool; + + /** + * Update TPA table with ticket_master primary key + */ + abstract protected function updateTicketIdInTPATable(): bool; + + /** + * Update TPA table with ticket_master insert rejected reason + */ + abstract protected function updateTicketMasterRejectedReasonInTPATable(array $data): bool; +} diff --git a/app/Libraries/TPAClaimsImportServices/FhplClaimImportService.php b/app/Libraries/TPAClaimsImportServices/FhplClaimImportService.php new file mode 100644 index 00000000..ced6c2f3 --- /dev/null +++ b/app/Libraries/TPAClaimsImportServices/FhplClaimImportService.php @@ -0,0 +1,503 @@ +["col_name"=>"Requesttype","col_index"=>0],"db_column"=>"request_type"], + ["excel_column"=>["col_name"=>"Intimation ID","col_index"=>1],"db_column"=>"intimation_id"], + ["excel_column"=>["col_name"=>"Intimation Date","col_index"=>2],"db_column"=>"intimation_date"], + ["excel_column"=>["col_name"=>"claimid","col_index"=>3],"db_column"=>"claim_id"], + ["excel_column"=>["col_name"=>"slno","col_index"=>4],"db_column"=>"sl_no"], + ["excel_column"=>["col_name"=>"UHIDNO","col_index"=>5],"db_column"=>"uhid_no"], + ["excel_column"=>["col_name"=>"Membername","col_index"=>6],"db_column"=>"member_name"], + ["excel_column"=>["col_name"=>"Main Memuhidno","col_index"=>7],"db_column"=>"main_member_uhid_no"], + ["excel_column"=>["col_name"=>"Main Memname","col_index"=>8],"db_column"=>"main_member_name"], + ["excel_column"=>["col_name"=>"Gender","col_index"=>9],"db_column"=>"gender"], + ["excel_column"=>["col_name"=>"DOB","col_index"=>10],"db_column"=>"dob"], + ["excel_column"=>["col_name"=>"Yrs","col_index"=>11],"db_column"=>"years"], + ["excel_column"=>["col_name"=>"relationship","col_index"=>12],"db_column"=>"relationship"], + ["excel_column"=>["col_name"=>"employeeid","col_index"=>13],"db_column"=>"employee_id"], + ["excel_column"=>["col_name"=>"Mobile","col_index"=>14],"db_column"=>"mobile"], + ["excel_column"=>["col_name"=>"Email","col_index"=>15],"db_column"=>"email"], + ["excel_column"=>["col_name"=>"Policy No","col_index"=>16],"db_column"=>"policy_no"], + ["excel_column"=>["col_name"=>"Policy Start Date","col_index"=>17],"db_column"=>"policy_start_date"], + ["excel_column"=>["col_name"=>"Policy Commencing Date","col_index"=>18],"db_column"=>"policy_commencing_date"], + ["excel_column"=>["col_name"=>"Policy Expiry Date","col_index"=>19],"db_column"=>"policy_expiry_date"], + ["excel_column"=>["col_name"=>"Organisationname","col_index"=>20],"db_column"=>"organisation_name"], + ["excel_column"=>["col_name"=>"Claimreceiveddate","col_index"=>21],"db_column"=>"claim_received_date"], + ["excel_column"=>["col_name"=>"Admdate","col_index"=>22],"db_column"=>"admission_date"], + ["excel_column"=>["col_name"=>"Dis Date","col_index"=>23],"db_column"=>"discharge_date"], + ["excel_column"=>["col_name"=>"Diagnosis","col_index"=>24],"db_column"=>"diagnosis"], + ["excel_column"=>["col_name"=>"Service Type","col_index"=>25],"db_column"=>"service_type"], + ["excel_column"=>["col_name"=>"Service Sub Type","col_index"=>26],"db_column"=>"service_sub_type"], + ["excel_column"=>["col_name"=>"icdcode First Level","col_index"=>27],"db_column"=>"icd_code_first_level"], + ["excel_column"=>["col_name"=>"icdcode Second Level","col_index"=>28],"db_column"=>"icd_code_second_level"], + ["excel_column"=>["col_name"=>"icdcode Third Level","col_index"=>29],"db_column"=>"icd_code_third_level"], + ["excel_column"=>["col_name"=>"Claim Type","col_index"=>30],"db_column"=>"claim_type"], + ["excel_column"=>["col_name"=>"Providername","col_index"=>31],"db_column"=>"provider_name"], + ["excel_column"=>["col_name"=>"provideraddress","col_index"=>32],"db_column"=>"provider_address"], + ["excel_column"=>["col_name"=>"providerplace","col_index"=>33],"db_column"=>"provider_place"], + ["excel_column"=>["col_name"=>"providerstate","col_index"=>34],"db_column"=>"provider_state"], + ["excel_column"=>["col_name"=>"Provider Pincode","col_index"=>35],"db_column"=>"provider_pincode"], + ["excel_column"=>["col_name"=>"PROVIDERTYPE","col_index"=>36],"db_column"=>"provider_type"], + ["excel_column"=>["col_name"=>"Provider Identification","col_index"=>37],"db_column"=>"provider_identification"], + ["excel_column"=>["col_name"=>"coverageamount","col_index"=>38],"db_column"=>"coverage_amount"], + ["excel_column"=>["col_name"=>"claimamount","col_index"=>39],"db_column"=>"claim_amount"], + ["excel_column"=>["col_name"=>"billedamount","col_index"=>40],"db_column"=>"billed_amount"], + ["excel_column"=>["col_name"=>"Disallowed Amount","col_index"=>41],"db_column"=>"disallowed_amount"], + ["excel_column"=>["col_name"=>"Dis Allowence Reason1","col_index"=>42],"db_column"=>"dis_allowance_reason_1"], + ["excel_column"=>["col_name"=>"Dis Allowence Reason2","col_index"=>43],"db_column"=>"dis_allowance_reason_2"], + ["excel_column"=>["col_name"=>"settledamt","col_index"=>44],"db_column"=>"settled_amount"], + ["excel_column"=>["col_name"=>"Incurred Amount","col_index"=>45],"db_column"=>"incurred_amount"], + ["excel_column"=>["col_name"=>"Discountamount","col_index"=>46],"db_column"=>"discount_amount"], + ["excel_column"=>["col_name"=>"TDSAmount","col_index"=>47],"db_column"=>"tds_amount"], + ["excel_column"=>["col_name"=>"Net Amount Paid","col_index"=>48],"db_column"=>"net_amount_paid"], + ["excel_column"=>["col_name"=>"Co Payment","col_index"=>49],"db_column"=>"co_payment"], + ["excel_column"=>["col_name"=>"Current Claim Status","col_index"=>50],"db_column"=>"current_claim_status"], + ["excel_column"=>["col_name"=>"Balance Suminsured","col_index"=>51],"db_column"=>"balance_sum_insured"], + ["excel_column"=>["col_name"=>"Chequeno","col_index"=>52],"db_column"=>"cheque_no"], + ["excel_column"=>["col_name"=>"chequedate","col_index"=>53],"db_column"=>"cheque_date"], + ["excel_column"=>["col_name"=>"Claim Passed Date","col_index"=>54],"db_column"=>"claim_passed_date"], + ["excel_column"=>["col_name"=>"Settled Date","col_index"=>55],"db_column"=>"settled_date"], + ["excel_column"=>["col_name"=>"Pending Remarks","col_index"=>56],"db_column"=>"pending_remarks"], + ["excel_column"=>["col_name"=>"Ir Investigation","col_index"=>57],"db_column"=>"ir_investigation"], + ["excel_column"=>["col_name"=>"Date of IR","col_index"=>58],"db_column"=>"ir_date"], + ["excel_column"=>["col_name"=>"Date of IRretrieval Date","col_index"=>59],"db_column"=>"ir_retrieval_date"], + ["excel_column"=>["col_name"=>"first Reminder","col_index"=>60],"db_column"=>"first_reminder"], + ["excel_column"=>["col_name"=>"Second Reminder","col_index"=>61],"db_column"=>"second_reminder"], + ["excel_column"=>["col_name"=>"Rejection Remarks","col_index"=>62],"db_column"=>"rejection_remarks"], + ["excel_column"=>["col_name"=>"Payee name","col_index"=>63],"db_column"=>"payee_name"], + ["excel_column"=>["col_name"=>"Treatment Type","col_index"=>64],"db_column"=>"treatment_type"], + ["excel_column"=>["col_name"=>"roomdays","col_index"=>65],"db_column"=>"room_days"], + ["excel_column"=>["col_name"=>"icudays","col_index"=>66],"db_column"=>"icu_days"], + ["excel_column"=>["col_name"=>"totalstay","col_index"=>67],"db_column"=>"total_stay"], + ["excel_column"=>["col_name"=>"Room Rent Claimed","col_index"=>68],"db_column"=>"room_rent_claimed"], + ["excel_column"=>["col_name"=>"ICU Claimed","col_index"=>69],"db_column"=>"icu_claimed"], + ["excel_column"=>["col_name"=>"ICU Related","col_index"=>70],"db_column"=>"icu_related"], + ["excel_column"=>["col_name"=>"Nursing Claimed","col_index"=>71],"db_column"=>"nursing_claimed"], + ["excel_column"=>["col_name"=>"Nursing Charges","col_index"=>72],"db_column"=>"nursing_charges"], + ["excel_column"=>["col_name"=>"Room Rent Related","col_index"=>73],"db_column"=>"room_rent_related"], + ["excel_column"=>["col_name"=>"Professional Charges","col_index"=>74],"db_column"=>"professional_charges"], + ["excel_column"=>["col_name"=>"Drugs Medication Consumables Investigationsetc","col_index"=>75],"db_column"=>"drugs_medication_consumables"], + ["excel_column"=>["col_name"=>"Investigations Procedures IP","col_index"=>76],"db_column"=>"investigations_procedures_ip"], + ["excel_column"=>["col_name"=>"Domicillary Hospitalization","col_index"=>77],"db_column"=>"domicillary_hospitalization"], + ["excel_column"=>["col_name"=>"Maternity","col_index"=>78],"db_column"=>"maternity"], + ["excel_column"=>["col_name"=>"Day Care","col_index"=>79],"db_column"=>"day_care"], + ["excel_column"=>["col_name"=>"Operation Theatre","col_index"=>80],"db_column"=>"operation_theatre"], + ["excel_column"=>["col_name"=>"Organ Donar","col_index"=>81],"db_column"=>"organ_donor"], + ["excel_column"=>["col_name"=>"Ancilliary Services","col_index"=>82],"db_column"=>"ancillary_services"], + ["excel_column"=>["col_name"=>"Dental","col_index"=>83],"db_column"=>"dental"], + ["excel_column"=>["col_name"=>"Out Patient Coverage","col_index"=>84],"db_column"=>"out_patient_coverage"], + ["excel_column"=>["col_name"=>"Personal Accident","col_index"=>85],"db_column"=>"personal_accident"], + ["excel_column"=>["col_name"=>"Critical Illness","col_index"=>86],"db_column"=>"critical_illness"], + ["excel_column"=>["col_name"=>"Health Check Up","col_index"=>87],"db_column"=>"health_check_up"], + ["excel_column"=>["col_name"=>"Spectacles Contact Lenses Hearing Aid","col_index"=>88],"db_column"=>"spectacles_contact_lenses_hearing_aid"], + ["excel_column"=>["col_name"=>"Notes","col_index"=>89],"db_column"=>"notes"], + ["excel_column"=>["col_name"=>"Buffer Amount","col_index"=>90],"db_column"=>"buffer_amount"], + ["excel_column"=>["col_name"=>"tertiaryamount","col_index"=>91],"db_column"=>"tertiary_amount"], + ["excel_column"=>["col_name"=>"insurancename","col_index"=>92],"db_column"=>"insurance_name"], + ["excel_column"=>["col_name"=>"Roname","col_index"=>93],"db_column"=>"ro_name"], + ["excel_column"=>["col_name"=>"Class Of Accommodation","col_index"=>94],"db_column"=>"class_of_accommodation"], + ["excel_column"=>["col_name"=>"claimcreateddatetime","col_index"=>95],"db_column"=>"claim_created_datetime"], + ["excel_column"=>["col_name"=>"Insurer Claim ID","col_index"=>96],"db_column"=>"insurer_claim_id"], + ["excel_column"=>["col_name"=>"Gipsa","col_index"=>97],"db_column"=>"gipsa"], + ["excel_column"=>["col_name"=>"Date Of Joining","col_index"=>98],"db_column"=>"date_of_joining"], + ["excel_column"=>["col_name"=>"GIPSAHospital","col_index"=>99],"db_column"=>"gipsa_hospital"], + ["excel_column"=>["col_name"=>"Package","col_index"=>100],"db_column"=>"package"], + ["excel_column"=>["col_name"=>"Is NIDB","col_index"=>101],"db_column"=>"is_nidb"], + ["excel_column"=>["col_name"=>"NIDB Removed Date","col_index"=>102],"db_column"=>"nidb_removed_date"], + ["excel_column"=>["col_name"=>"Investigationdate","col_index"=>103],"db_column"=>"investigation_date"], + ["excel_column"=>["col_name"=>"Investigation Retrieval Date","col_index"=>104],"db_column"=>"investigation_retrieval_date"], + ["excel_column"=>["col_name"=>"Reopeneddate","col_index"=>105],"db_column"=>"reopened_date"], + ["excel_column"=>["col_name"=>"Referto Insurer Date","col_index"=>106],"db_column"=>"refer_to_insurer_date"], + ["excel_column"=>["col_name"=>"Receiveddatefrom Insurer","col_index"=>107],"db_column"=>"received_date_from_insurer"], + ["excel_column"=>["col_name"=>"Rejection Category","col_index"=>108],"db_column"=>"rejection_category"], + ["excel_column"=>["col_name"=>"Referto Insurer Reasons","col_index"=>109],"db_column"=>"refer_to_insurer_reasons"], + ["excel_column"=>["col_name"=>"Is VIP","col_index"=>110],"db_column"=>"is_vip"], + ["excel_column"=>["col_name"=>"Main Claim Status","col_index"=>111],"db_column"=>"main_claim_status"], + ["excel_column"=>["col_name"=>"Main Claimtype","col_index"=>112],"db_column"=>"main_claim_type"], + ["excel_column"=>["col_name"=>"icd Third Level Code","col_index"=>113],"db_column"=>"icd_third_level_code"], + ["excel_column"=>["col_name"=>"Benefit Plan Name","col_index"=>114],"db_column"=>"benefit_plan_name"], + ["excel_column"=>["col_name"=>"zone","col_index"=>115],"db_column"=>"zone"], + ["excel_column"=>["col_name"=>"Grade","col_index"=>116],"db_column"=>"grade"], + ["excel_column"=>["col_name"=>"Last Modified Date","col_index"=>117],"db_column"=>"last_modified_date"], + ["excel_column"=>["col_name"=>"Temp MOU","col_index"=>118],"db_column"=>"temp_mou"], + ]; + + protected $ticketMasterMapping = [ + + // Employee / Member details + 'member_code' => 'emp_code', + 'relation' => 'relationship', + + // Policy / Claim identifiers + 'policy_number' => 'policy_no', + 'certificate_no' => 'claim_number', + 'abhi_claim_no' => 'tpa_claim_id', + + // Dates + 'doa' => 'doa', + 'dod' => 'dod', + 'intimation_date' => 'date_of_intimat', + + // Claim info + 'claim_type' => 'claim_type', + 'claim_status' => 'tpa_claim_status', + 'claimed_amount' => 'claim_amount', + 'abhi_amount_less_coins_current_month' => 'approved_amount', + + // Hospital details + 'hospital_name' => 'hospital_name', + 'hospital_city' => 'hospital_city', + 'hospital_state' => 'hospital_state', + + // Settlement / decision + 'repudiation_date' => 'denial_date', + 'settled_date' => 'settled_date', + 'rejection_category' => 'denial_reason', + + // Misc + 'diagnosis' => 'claim_description', + 'healthcard_id' => 'tpa_no', + + 'priority' => 1, + 'mode_of_intimation' => 5, + 'ticket_type_id' => 1, + ]; + + protected $statusMapping = [ + 'Settled' => 11, + 'Rejected' => 8, + ]; + + /** + * ABSTRACT FUNCTIONs + */ + public function bulkInsertTPATable(array $data): bool + { + if (empty($data)) { + return false; + } + + $ClaimsDumpFhplModel = new ClaimsDumpFhplModel(); + $result = $ClaimsDumpFhplModel->insertBatch($data); + + return true; + + } + + + public function importClaimMaster(array $data): bool + { + if (empty($data)) { + return false; + } + + $ticketMasterModel = new TicketMasterModel(); + $ticketMasterModel->insertBatch($data); + + return true; + } + + + public function updateTicketIdInTPATable(): bool + { + if (empty($data)) { + return false; + } + + $builder = $this->db->table('claims_dump_fhpl'); + $builder->insertBatch($data); + + return true; + } + + + public function updateTicketMasterRejectedReasonInTPATable($data): bool + { + if (empty($data)) { + return false; + } + + $builder = $this->db->table('claims_dump_fhpl'); + $builder->insertBatch($data); + + return true; + } + + + /** + * MAPPING FUNCTIONs + */ + + public function mapTPAData(array $rows, $file_id): array + { + $ClientPolicyModel = new ClaimDumpFileModel(); + $file_data = $ClientPolicyModel->where('id', $file_id)->first(); + + $mapped = []; + + foreach ($rows as $row) { + + $item = []; + + foreach ($this->mapping as $map) { + $excelColumn = $map['excel_column']['col_name']; + $dbColumn = $map['db_column']; + + $value = $row[$excelColumn] ?? null; + + if ($this->isDateValue($value)) { + $value = $this->normalizeDate($value); + } + + $item[$dbColumn] = trim($value); + } + + // $params = [ + // 'admission_date' => change_date_format($item['admission_date'] ?? '') ?? null, + // 'employee_number' => $item['employee_number'] ?? null, + // 'claim_amount' => $item['claim_amount'] ?? null, + // 'primary_policy_holder_card_id' => $item['primary_policy_holder_card_id'] ?? null + // ]; + + // $is_duplicate = $this->checkDuplicateTpaClaim('claims_dump_fhpl', $params); + + // if ($is_duplicate) { + // $item = []; + // continue; + // } + + $item['file_id'] = $file_id ?? null; + $item['client_id'] = $file_data['client_id'] ?? null; + $item['client_policy_id'] = $file_data['client_policy_id'] ?? null; + $item['created_by'] = $file_data['created_by'] ?? null; + + $mapped[] = $item; + } + + return $mapped; + } + + public function mapClaimMasterData($file_id): array + { + + $ClientPolicyModel = new ClaimDumpFileModel(); + $file_data = $ClientPolicyModel->where('id', $file_id)->first(); + + $tpaClaimDumpData = $this->getTpaClaimDumpData('claims_dump_fhpl', ['file_id' => $file_id]); + + if (empty($tpaClaimDumpData)) { + return ['status' => false, 'message' => "No data to insert in TICKET MASTER"]; + } + + + $ClientPolicyModel = new ClientPolicyModel(); + $client_policy_data = $ClientPolicyModel + ->select(" + client_policy.*, + ( + SELECT id + FROM client_rm + WHERE is_active = 1 + AND level = 3 + AND client_id = client_policy.client_id + ORDER BY id ASC + LIMIT 1 + ) AS acm_id + ") + ->where('client_policy.id', $file_data['client_policy_id']) + ->where('client_policy.is_active', 1) + ->first(); + + try { + + $mapped = []; + $rejecetd_reason = []; + + foreach ($tpaClaimDumpData as $row) { + + $params = [ + 'doa' => change_date_format($row['date_of_admission'] ?? '') ?? null, + 'emp_code' => $row['employee_number'] ?? null, + 'claim_amount' => $row['claim_amount'] ?? null, + 'tpa_no' => $row['primary_policy_holder_card_id'] ?? null + ]; + + $isduplicate = $this->checkDublicateTicketMasterClaim($params); + + if ($isduplicate) { + $reason = "This claim already exists in our system."; + $rejecetd_reason[$row['id']] = ["ticket_master_insert_reject_reason" => $reason]; + continue; + } + + $item = []; + + $item['client_id'] = $client_policy_data['client_id'] ?? null; + $item['client_policy_id'] = $client_policy_data['id'] ?? null; + $item['insurer_id'] = $client_policy_data['insurer_id'] ?? null; + $item['tpa_id'] = $client_policy_data['tpa_id'] ?? null; + $item['acm_id'] = $client_policy_data['acm_id'] ?? null; + $item['policy_no'] = $client_policy_data['policy_no'] ?? null; + $item['relationship'] = $this->convertRelation($row['relation'] ?? null, $row['gender'] ?? null); + + $employee_data = $this->getEmployeeDetails($file_data['client_id'], $file_data['client_policy_id'], $row['employee_number'], $item['relationship']); + + if (!empty($employee_data)) { + $item['emp_id'] = $employee_data['id'] ?? null; + $item['emp_name'] = $employee_data['name'] ?? null; + $item['emp_mail'] = $employee_data['email_corporate'] ?? null; + $item['emp_mobile'] = $employee_data['mobile'] ?? null; + $item['insured_emp_id'] = $employee_data['insured_emp_id'] ?? null; + $item['insured_name'] = $employee_data['insured_name'] ?? null; + } else { + + $reason = sprintf( + 'The policy number "%s" does not exist in our system. ' . + 'Details - Client ID: %s, Client Policy ID: %s, Employee Number: %s, Relationship: %s', + $row['insurer_policy_number'], + $file_data['client_id'], + $file_data['client_policy_id'], + $row['employee_number'], + $item['relationship'] + ); + + $rejecetd_reason[$row['id']] = ["ticket_master_insert_reject_reason" => $reason]; + continue; + } + + foreach ($this->ticketMasterMapping as $tpaKey => $ticketMasterKey) { + $item[$ticketMasterKey] = array_key_exists($tpaKey, $row) ? $row[$tpaKey] : null; + } + + // Meta fields + $item['claim_status_id'] = $statusMapping[$row['current_claim_status']] ?? 61; + $item['file_id'] = $file_id; + $item['claim_dump_ref_id'] = $row['id']; + $item['created_by'] = $file_data['created_by'] ?? null; + $item['claim_type'] = isset($row['mainclaim_prepost_type']) && !empty($row['mainclaim_prepost_type']) && strtolower($row['mainclaim_prepost_type']) == 'normal' ? 1 : 3; + + $mapped[] = $item; + } + + return ['status' => true, 'mapped_array' => $mapped, 'rejected_reason_array' => $rejecetd_reason]; + + } 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, + ]; + + return ['status' => false, "message" => $errorData['message'], 'error_data' => $errorData]; + } + } + + + /** + * HELPER FUNCTIONs + */ + + public function isDateValue($value): bool + { + if (empty($value)) { + return false; + } + + // Excel numeric date (e.g. 44927) + if (is_numeric($value) && $value > 30000) { + return true; + } + + // Common date formats + return preg_match( + '/^\d{1,2}[\/\-]\d{1,2}[\/\-]\d{2,4}$|^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/', + (string) $value + ) === 1; + } + + + public function normalizeDate($value): ?string + { + try { + // Excel numeric date + if (is_numeric($value)) { + return date('Y-m-d', \PhpOffice\PhpSpreadsheet\Shared\Date::excelToTimestamp($value)); + } + + // String date + return date('Y-m-d', strtotime(str_replace('/', '-', $value))); + } catch (\Throwable $e) { + return null; + } + } + + + public function convertRelation(string $relation, string $gender): ?string + { + if (empty($relation)) { + return null; + } + + $relation = strtolower($relation); + $gender = strtolower($gender); + + if ($relation == 'self') { + return $relation; + } + + if ($relation == 'spouse') { + return $relation; + } + + if ($relation == 'child' && $gender == 'male') { + return 'son'; + } + + if ($relation == 'child' && $gender == 'female') { + return 'daughter'; + } + + if ($relation == 'parents' && $gender == 'male') { + return 'father'; + } + + if ($relation == 'parents' && $gender == 'female') { + return 'mother'; + } + + if ($relation == 'parents-in-law' && $gender == 'male') { + return 'father-in-law'; + } + + if ($relation == 'parents-in-law' && $gender == 'female') { + return 'mother-in-law'; + } + + return null; + } + + + +} diff --git a/app/Libraries/TPAClaimsImportServices/IciciClaimImportService.php b/app/Libraries/TPAClaimsImportServices/IciciClaimImportService.php new file mode 100644 index 00000000..9f1ddfe3 --- /dev/null +++ b/app/Libraries/TPAClaimsImportServices/IciciClaimImportService.php @@ -0,0 +1,445 @@ + ["col_name" => "POLICY_NAME", "col_index" => 0], "db_column" => "policy_name"], + ["excel_column" => ["col_name" => "POLICY_NO", "col_index" => 1], "db_column" => "policy_no"], + ["excel_column" => ["col_name" => "UHID", "col_index" => 2], "db_column" => "uhid"], + ["excel_column" => ["col_name" => "INSURED_NAME", "col_index" => 3], "db_column" => "insured_name"], + ["excel_column" => ["col_name" => "MAIN_MEMBER_NAME", "col_index" => 4], "db_column" => "main_member_name"], + ["excel_column" => ["col_name" => "EMPLOYEE_MEMBER_ID", "col_index" => 5], "db_column" => "employee_member_id"], + ["excel_column" => ["col_name" => "GRADE", "col_index" => 6], "db_column" => "grade"], + ["excel_column" => ["col_name" => "RELATION", "col_index" => 7], "db_column" => "relation"], + ["excel_column" => ["col_name" => "AGE", "col_index" => 8], "db_column" => "age"], + ["excel_column" => ["col_name" => "GENDER", "col_index" => 9], "db_column" => "gender"], + ["excel_column" => ["col_name" => "DIAGNOSIS", "col_index" => 10], "db_column" => "diagnosis"], + ["excel_column" => ["col_name" => "CLAIMED_AMOUNT", "col_index" => 11], "db_column" => "claimed_amount"], + ["excel_column" => ["col_name" => "NET_SANCT_AMT", "col_index" => 12], "db_column" => "net_sanct_amt"], + ["excel_column" => ["col_name" => "COPAYMENT_AMT", "col_index" => 13], "db_column" => "copayment_amt"], + ["excel_column" => ["col_name" => "DISALLOWED_AMOUNT", "col_index" => 14], "db_column" => "disallowed_amount"], + ["excel_column" => ["col_name" => "REASON_FOR_DISALLOWANCE", "col_index" => 15], "db_column" => "reason_for_disallowance"], + ["excel_column" => ["col_name" => "PAYMENT_AMOUNT", "col_index" => 16], "db_column" => "payment_amount"], + ["excel_column" => ["col_name" => "SUM_INSURED", "col_index" => 17], "db_column" => "sum_insured"], + ["excel_column" => ["col_name" => "BAL_SUM_INSURED", "col_index" => 18], "db_column" => "bal_sum_insured"], + ["excel_column" => ["col_name" => "TYPE_OF_CLAIM", "col_index" => 19], "db_column" => "type_of_claim"], + ["excel_column" => ["col_name" => "Claim_r_Os_Amt", "col_index" => 20], "db_column" => "claim_r_os_amt"], + ["excel_column" => ["col_name" => "Updated_status", "col_index" => 21], "db_column" => "updated_status"], + ["excel_column" => ["col_name" => "Disease_Category", "col_index" => 22], "db_column" => "disease_category"], + ["excel_column" => ["col_name" => "POLICY_START_DATE", "col_index" => 23], "db_column" => "policy_start_date"], + ["excel_column" => ["col_name" => "POLICY_END_DATE", "col_index" => 24], "db_column" => "policy_end_date"], + ["excel_column" => ["col_name" => "CLAIM_NUMBER", "col_index" => 25], "db_column" => "claim_number"], + ["excel_column" => ["col_name" => "AL_NO", "col_index" => 26], "db_column" => "al_no"], + ["excel_column" => ["col_name" => "HOSPITAL_CODE", "col_index" => 27], "db_column" => "hospital_code"], + ["excel_column" => ["col_name" => "HOSPITAL_ID", "col_index" => 28], "db_column" => "hospital_id"], + ["excel_column" => ["col_name" => "HOSPITAL_NAME", "col_index" => 29], "db_column" => "hospital_name"], + ["excel_column" => ["col_name" => "TREATMENT_TAKEN", "col_index" => 30], "db_column" => "treatment_taken"], + ["excel_column" => ["col_name" => "CF_Utilised_Amounnt", "col_index" => 31], "db_column" => "cf_utilised_amount"], + ["excel_column" => ["col_name" => "DT_OF_DEFICIENCIES_SENT", "col_index" => 32], "db_column" => "dt_of_deficiencies_sent"], + ["excel_column" => ["col_name" => "DT_OF_DEFICIENCIES_RECIEVED", "col_index" => 33], "db_column" => "dt_of_deficiencies_received"], + ["excel_column" => ["col_name" => "PAYMENT_DATE", "col_index" => 34], "db_column" => "payment_date"], + ["excel_column" => ["col_name" => "PAYEE_NAME", "col_index" => 35], "db_column" => "payee_name"], + ["excel_column" => ["col_name" => "PAYMENT_MODE", "col_index" => 36], "db_column" => "payment_mode"], + ["excel_column" => ["col_name" => "CHEQUE_NUMBER", "col_index" => 37], "db_column" => "cheque_number"], + ["excel_column" => ["col_name" => "DOA", "col_index" => 38], "db_column" => "doa"], + ["excel_column" => ["col_name" => "DOD", "col_index" => 39], "db_column" => "dod"], + ["excel_column" => ["col_name" => "HOSPITAL_CITY", "col_index" => 40], "db_column" => "hospital_city"], + ["excel_column" => ["col_name" => "HOSPITAL_STATE", "col_index" => 41], "db_column" => "hospital_state"], + ["excel_column" => ["col_name" => "REJECTED_QUERY_REASON", "col_index" => 42], "db_column" => "rejected_query_reason"], + ["excel_column" => ["col_name" => "REJECTED_QUERY_DESC", "col_index" => 43], "db_column" => "rejected_query_desc"], + ["excel_column" => ["col_name" => "REJECTED_QUERY_CLOSED_DATE", "col_index" => 44], "db_column" => "rejected_query_closed_date"], + ["excel_column" => ["col_name" => "REJREOPEN_CLOSURE_DATE", "col_index" => 45], "db_column" => "rejreopen_closure_date"], + ["excel_column" => ["col_name" => "CLAIM_CLASSIFICATION", "col_index" => 46], "db_column" => "claim_classification"], + ["excel_column" => ["col_name" => "TAGGED_INWARD_NO", "col_index" => 47], "db_column" => "tagged_inward_no"], + ["excel_column" => ["col_name" => "INWARD_DATE", "col_index" => 48], "db_column" => "inward_date"], + ["excel_column" => ["col_name" => "ICD_ID_L3", "col_index" => 49], "db_column" => "icd_id_l3"], + ["excel_column" => ["col_name" => "Incidence_Count", "col_index" => 50], "db_column" => "incidence_count"], + ["excel_column" => ["col_name" => "FLEXI_OPTION", "col_index" => 51], "db_column" => "flexi_option"], + ["excel_column" => ["col_name" => "Base_TopUp_Option", "col_index" => 52], "db_column" => "base_topup_option"], + ["excel_column" => ["col_name" => "POLICY_GROUP_NAME", "col_index" => 53], "db_column" => "policy_group_name"], + ["excel_column" => ["col_name" => "Relation_Group", "col_index" => 54], "db_column" => "relation_group"], + ["excel_column" => ["col_name" => "Age_Band", "col_index" => 55], "db_column" => "age_band"], + ["excel_column" => ["col_name" => "Work_Location", "col_index" => 56], "db_column" => "work_location"], + ["excel_column" => ["col_name" => "ILTC_TAG", "col_index" => 57], "db_column" => "iltc_tag"], + ]; + + protected $ticketMasterMapping = [ + + // Employee / Member + 'employee_member_id' => 'emp_code', + 'relation_group' => 'relationship', + + // Claim + 'claim_number' => 'claim_number', + 'claimed_amount' => 'claim_amount', + 'claim_status' => 'tpa_claim_status', + + // Dates + 'doa' => 'doa', + 'dod' => 'dod', + 'payment_date' => 'settled_date', + + // Hospital + 'hospital_name' => 'hospital_name', + 'hospital_city' => 'hospital_city', + 'hospital_state' => 'hospital_state', + + 'cheque_number' => 'utr_details', + 'tpa_no' => 'uhid', + 'rejected_query_desc' => 'claim_description', + ]; + + protected $statusMapping = [ + 'PAID' => 11, + 'REJECTED' => 8, + ]; + + + /** + * ABSTRACT FUNCTIONs + */ + public function bulkInsertTPATable(array $data): bool + { + if (empty($data)) { + return false; + } + + try { + + + $ClaimsDumpFhplModel = new ClaimsDumpFhplModel(); + $result = $ClaimsDumpFhplModel->insertBatch($data); + + return true; + + } 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, + ]; + return false; + } + + } + + + public function importClaimMaster(array $data): bool + { + if (empty($data)) { + return false; + } + + $ticketMasterModel = new TicketMasterModel(); + $ticketMasterModel->insertBatch($data); + + return true; + } + + + public function updateTicketIdInTPATable(): bool + { + if (empty($data)) { + return false; + } + + $builder = $this->db->table('claims_dump_icici'); + $builder->insertBatch($data); + + return true; + } + + + public function updateTicketMasterRejectedReasonInTPATable($data): bool + { + if (empty($data)) { + return false; + } + + $builder = $this->db->table('claims_dump_icici'); + $builder->insertBatch($data); + + return true; + } + + + /** + * MAPPING FUNCTIONs + */ + + public function mapTPAData(array $rows, $file_id): array + { + $ClientPolicyModel = new ClaimDumpFileModel(); + $file_data = $ClientPolicyModel->where('id', $file_id)->first(); + + $mapped = []; + + foreach ($rows as $row) { + + $item = []; + + foreach ($this->mapping as $map) { + $excelColumn = $map['excel_column']['col_name']; + $dbColumn = $map['db_column']; + + $value = $row[$excelColumn] ?? null; + + if ($this->isDateValue($value)) { + $value = $this->normalizeDate($value); + } + + $item[$dbColumn] = $value; + } + + $params = [ + 'doa' => change_date_format($item['doa'] ?? '') ?? null, + 'employee_member_id' => $item['employee_member_id'] ?? null, + 'claimed_amount' => $item['claimed_amount'] ?? null, + 'uhid' => $item['uhid'] ?? null + ]; + + $is_duplicate = $this->checkDuplicateTpaClaim('claims_dump_icici', $params); + + if ($is_duplicate) { + $item = []; + continue; + } + + $item['file_id'] = $file_id ?? null; + $item['client_id'] = $file_data['client_id'] ?? null; + $item['client_policy_id'] = $file_data['client_policy_id'] ?? null; + $item['created_by'] = $file_data['created_by'] ?? null; + + $mapped[] = $item; + } + + return $mapped; + } + + public function mapClaimMasterData($file_id): array + { + + $ClientPolicyModel = new ClaimDumpFileModel(); + $file_data = $ClientPolicyModel->where('id', $file_id)->first(); + + $tpaClaimDumpData = $this->getTpaClaimDumpData('claims_dump_icici', ['file_id' => $file_id]); + + if (empty($tpaClaimDumpData)) { + return ['status' => false, 'message' => "No data to insert in TICKET MASTER"]; + } + + + $ClientPolicyModel = new ClientPolicyModel(); + $client_policy_data = $ClientPolicyModel + ->select(" + client_policy.*, + ( + SELECT id + FROM client_rm + WHERE is_active = 1 + AND level = 3 + AND client_id = client_policy.client_id + ORDER BY id ASC + LIMIT 1 + ) AS acm_id + ") + ->where('client_policy.id', $file_data['client_policy_id']) + ->where('client_policy.is_active', 1) + ->first(); + + try { + + $mapped = []; + $rejecetd_reason = []; + + foreach ($tpaClaimDumpData as $row) { + + $params = [ + 'doa' => change_date_format($row['doa'] ?? '') ?? null, + 'emp_code' => $row['employee_member_id'] ?? null, + 'claim_amount' => $row['claim_amount'] ?? null, + 'tpa_no' => $row['uhid'] ?? null + ]; + + $isduplicate = $this->checkDublicateTicketMasterClaim($params); + + if ($isduplicate) { + $reason = "This claim already exists in our system."; + $rejecetd_reason[$row['id']] = ["ticket_master_insert_reject_reason" => $reason]; + continue; + } + + $item = []; + + $item['client_id'] = $client_policy_data['client_id'] ?? null; + $item['client_policy_id'] = $client_policy_data['id'] ?? null; + $item['insurer_id'] = $client_policy_data['insurer_id'] ?? null; + $item['tpa_id'] = $client_policy_data['tpa_id'] ?? null; + $item['acm_id'] = $client_policy_data['acm_id'] ?? null; + $item['policy_no'] = $client_policy_data['policy_no'] ?? null; + $item['relationship'] = strtolower($row['relation_group'] ?? ''); + + $employee_data = $this->getEmployeeDetails($file_data['client_id'], $file_data['client_policy_id'], $row['employee_number'], $item['relationship']); + + if (!empty($employee_data)) { + $item['emp_id'] = $employee_data['id'] ?? null; + $item['emp_name'] = $employee_data['name'] ?? null; + $item['emp_mail'] = $employee_data['email_corporate'] ?? null; + $item['emp_mobile'] = $employee_data['mobile'] ?? null; + $item['insured_emp_id'] = $employee_data['insured_emp_id'] ?? null; + $item['insured_name'] = $employee_data['insured_name'] ?? null; + } else { + + $reason = sprintf( + 'The policy number "%s" does not exist in our system. ' . + 'Details - Client ID: %s, Client Policy ID: %s, Employee Number: %s, Relationship: %s', + $row['insurer_policy_number'], + $file_data['client_id'], + $file_data['client_policy_id'], + $row['employee_number'], + $item['relationship'] + ); + + $rejecetd_reason[$row['id']] = ["ticket_master_insert_reject_reason" => $reason]; + continue; + } + + foreach ($this->ticketMasterMapping as $tpaKey => $ticketMasterKey) { + $item[$ticketMasterKey] = array_key_exists($tpaKey, $row) ? $row[$tpaKey] : null; + } + + // Meta fields + $item['claim_status_id'] = $statusMapping[$row['updated_status']] ?? 61; + $item['file_id'] = $file_id; + $item['created_by'] = $file_data['created_by'] ?? null; + $item['claim_type'] = 1; + + $mapped[] = $item; + } + + return ['status' => true, 'mapped_array' => $mapped, 'rejected_reason_array' => $rejecetd_reason]; + + } 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, + ]; + + return ['status' => false, "message" => $errorData['message'], 'error_data' => $errorData]; + } + } + + + /** + * HELPER FUNCTIONs + */ + + public function isDateValue($value): bool + { + if (empty($value)) { + return false; + } + + // Excel numeric date (e.g. 44927) + if (is_numeric($value) && $value > 30000) { + return true; + } + + // Common date formats + return preg_match( + '/^\d{1,2}[\/\-]\d{1,2}[\/\-]\d{2,4}$|^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/', + (string) $value + ) === 1; + } + + + public function normalizeDate($value): ?string + { + try { + // Excel numeric date + if (is_numeric($value)) { + return date('Y-m-d', \PhpOffice\PhpSpreadsheet\Shared\Date::excelToTimestamp($value)); + } + + // String date + return date('Y-m-d', strtotime(str_replace('/', '-', $value))); + } catch (\Throwable $e) { + return null; + } + } + + + public function convertRelation(string $relation, string $gender): ?string + { + if (empty($relation)) { + return null; + } + + $relation = strtolower($relation); + $gender = strtolower($gender); + + if ($relation == 'self') { + return $relation; + } + + if ($relation == 'spouse') { + return $relation; + } + + if ($relation == 'child' && $gender == 'male') { + return 'son'; + } + + if ($relation == 'child' && $gender == 'female') { + return 'daughter'; + } + + if ($relation == 'parents' && $gender == 'male') { + return 'father'; + } + + if ($relation == 'parents' && $gender == 'female') { + return 'mother'; + } + + if ($relation == 'parents-in-law' && $gender == 'male') { + return 'father-in-law'; + } + + if ($relation == 'parents-in-law' && $gender == 'female') { + return 'mother-in-law'; + } + + return null; + } + + + +} diff --git a/app/Libraries/TPAClaimsImportServices/MediAssistClaimImportService.php b/app/Libraries/TPAClaimsImportServices/MediAssistClaimImportService.php new file mode 100644 index 00000000..c8e39b21 --- /dev/null +++ b/app/Libraries/TPAClaimsImportServices/MediAssistClaimImportService.php @@ -0,0 +1,491 @@ + ["col_name" => "insurance_company", "col_index" => 0], "db_column" => "insurance_company"], + ["excel_column" => ["col_name" => "insurer_region_name", "col_index" => 1], "db_column" => "insurer_region_name"], + ["excel_column" => ["col_name" => "insurer_ro_code", "col_index" => 2], "db_column" => "insurer_ro_code"], + ["excel_column" => ["col_name" => "insurer_do_code", "col_index" => 3], "db_column" => "insurer_do_code"], + ["excel_column" => ["col_name" => "insurer_bo_code", "col_index" => 4], "db_column" => "insurer_bo_code"], + ["excel_column" => ["col_name" => "event_id", "col_index" => 5], "db_column" => "event_id"], + ["excel_column" => ["col_name" => "claim_id", "col_index" => 6], "db_column" => "claim_id"], + ["excel_column" => ["col_name" => "insurer_claim_ref_no", "col_index" => 7], "db_column" => "insurer_claim_ref_no"], + ["excel_column" => ["col_name" => "claim_pre_auths", "col_index" => 8], "db_column" => "claim_pre_auths"], + ["excel_column" => ["col_name" => "ma_policy_id", "col_index" => 9], "db_column" => "ma_policy_id"], + ["excel_column" => ["col_name" => "policy_no", "col_index" => 10], "db_column" => "policy_no"], + ["excel_column" => ["col_name" => "policy_holder_name", "col_index" => 11], "db_column" => "policy_holder_name"], + ["excel_column" => ["col_name" => "policy_type", "col_index" => 12], "db_column" => "policy_type"], + ["excel_column" => ["col_name" => "policy_subtype_desc", "col_index" => 13], "db_column" => "policy_subtype_desc"], + ["excel_column" => ["col_name" => "policy_start_date", "col_index" => 14], "db_column" => "policy_start_date"], + ["excel_column" => ["col_name" => "policy_end_date", "col_index" => 15], "db_column" => "policy_end_date"], + ["excel_column" => ["col_name" => "devlopment_officer", "col_index" => 16], "db_column" => "devlopment_officer"], + ["excel_column" => ["col_name" => "agent", "col_index" => 17], "db_column" => "agent"], + ["excel_column" => ["col_name" => "broker", "col_index" => 18], "db_column" => "broker"], + ["excel_column" => ["col_name" => "pribenef_employee_code", "col_index" => 19], "db_column" => "pribenef_employee_code"], + ["excel_column" => ["col_name" => "pribenef_name", "col_index" => 20], "db_column" => "pribenef_name"], + ["excel_column" => ["col_name" => "pribenef_floater_sum", "col_index" => 21], "db_column" => "pribenef_floater_sum"], + ["excel_column" => ["col_name" => "benef_maid", "col_index" => 22], "db_column" => "benef_maid"], + ["excel_column" => ["col_name" => "benef_insurer_id", "col_index" => 23], "db_column" => "benef_insurer_id"], + ["excel_column" => ["col_name" => "benef_name", "col_index" => 24], "db_column" => "benef_name"], + ["excel_column" => ["col_name" => "benef_gender", "col_index" => 25], "db_column" => "benef_gender"], + ["excel_column" => ["col_name" => "benef_relation", "col_index" => 26], "db_column" => "benef_relation"], + ["excel_column" => ["col_name" => "benef_age", "col_index" => 27], "db_column" => "benef_age"], + ["excel_column" => ["col_name" => "benef_sum_insured", "col_index" => 28], "db_column" => "benef_sum_insured"], + ["excel_column" => ["col_name" => "balance_sum_insured", "col_index" => 29], "db_column" => "balance_sum_insured"], + ["excel_column" => ["col_name" => "intimation_id", "col_index" => 30], "db_column" => "intimation_id"], + ["excel_column" => ["col_name" => "intimation_date", "col_index" => 31], "db_column" => "intimation_date"], + ["excel_column" => ["col_name" => "settled_date", "col_index" => 32], "db_column" => "settled_date"], + ["excel_column" => ["col_name" => "ClaimSource", "col_index" => 33], "db_column" => "claim_source"], + ["excel_column" => ["col_name" => "claim_mode_of_rcpt", "col_index" => 34], "db_column" => "claim_mode_of_rcpt"], + ["excel_column" => ["col_name" => "claim_type", "col_index" => 35], "db_column" => "claim_type"], + ["excel_column" => ["col_name" => "claim_sub_type", "col_index" => 36], "db_column" => "claim_sub_type"], + ["excel_column" => ["col_name" => "claim_stage", "col_index" => 37], "db_column" => "claim_stage"], + ["excel_column" => ["col_name" => "claim_status", "col_index" => 38], "db_column" => "claim_status"], + ["excel_column" => ["col_name" => "is_cashlessanywhere", "col_index" => 39], "db_column" => "is_cashlessanywhere"], + ["excel_column" => ["col_name" => "date_of_admission", "col_index" => 40], "db_column" => "date_of_admission"], + ["excel_column" => ["col_name" => "date_of_discharge", "col_index" => 41], "db_column" => "date_of_discharge"], + ["excel_column" => ["col_name" => "claim_amount", "col_index" => 42], "db_column" => "claim_amount"], + ["excel_column" => ["col_name" => "claim_approved_amount", "col_index" => 43], "db_column" => "claim_approved_amount"], + ["excel_column" => ["col_name" => "incurred_amount", "col_index" => 44], "db_column" => "incurred_amount"], + ["excel_column" => ["col_name" => "primary_icd_group", "col_index" => 45], "db_column" => "primary_icd_group"], + ["excel_column" => ["col_name" => "primary_ailment_name", "col_index" => 46], "db_column" => "primary_ailment_name"], + ["excel_column" => ["col_name" => "primary_ailment_code", "col_index" => 47], "db_column" => "primary_ailment_code"], + ["excel_column" => ["col_name" => "treatment_type", "col_index" => 48], "db_column" => "treatment_type"], + ["excel_column" => ["col_name" => "treatment_name", "col_index" => 49], "db_column" => "treatment_name"], + ["excel_column" => ["col_name" => "hospital_id", "col_index" => 50], "db_column" => "hospital_id"], + ["excel_column" => ["col_name" => "hospital_name", "col_index" => 51], "db_column" => "hospital_name"], + ["excel_column" => ["col_name" => "hospital_city", "col_index" => 52], "db_column" => "hospital_city"], + ["excel_column" => ["col_name" => "hospital_state", "col_index" => 53], "db_column" => "hospital_state"], + ["excel_column" => ["col_name" => "hospital_pincode", "col_index" => 54], "db_column" => "hospital_pincode"], + ["excel_column" => ["col_name" => "hospital_address", "col_index" => 55], "db_column" => "hospital_address"], + ["excel_column" => ["col_name" => "Clinic_DoctorName_Hospital", "col_index" => 56], "db_column" => "clinic_doctorname_hospital"], + ["excel_column" => ["col_name" => "OPD_pincode", "col_index" => 57], "db_column" => "opd_pincode"], + ["excel_column" => ["col_name" => "payable_amount_OPD_Consultation", "col_index" => 58], "db_column" => "payable_amount_opd_consultation"], + ["excel_column" => ["col_name" => "payable_amount_Dental", "col_index" => 59], "db_column" => "payable_amount_dental"], + ["excel_column" => ["col_name" => "payable_amount_Diagnostics", "col_index" => 60], "db_column" => "payable_amount_diagnostics"], + ["excel_column" => ["col_name" => "payable_amount_Other", "col_index" => 61], "db_column" => "payable_amount_other"], + ["excel_column" => ["col_name" => "payable_amount_Pharmacy", "col_index" => 62], "db_column" => "payable_amount_pharmacy"], + ["excel_column" => ["col_name" => "payable_amount_Vaccination", "col_index" => 63], "db_column" => "payable_amount_vaccination"], + ["excel_column" => ["col_name" => "payable_amount_Miscellaneous_Charges", "col_index" => 64], "db_column" => "payable_amount_miscellaneous_charges"], + ["excel_column" => ["col_name" => "payable_amount_Health_Checkup", "col_index" => 65], "db_column" => "payable_amount_health_checkup"], + ["excel_column" => ["col_name" => "deduction_amount_copay", "col_index" => 66], "db_column" => "deduction_amount_copay"], + ["excel_column" => ["col_name" => "deduction_amount_excess_ailment", "col_index" => 67], "db_column" => "deduction_amount_excess_ailment"], + ["excel_column" => ["col_name" => "deduction_amount_excess_policy", "col_index" => 68], "db_column" => "deduction_amount_excess_policy"], + ["excel_column" => ["col_name" => "deduction_amount_prorata", "col_index" => 69], "db_column" => "deduction_amount_prorata"], + ["excel_column" => ["col_name" => "deduction_amount_hospital_discount", "col_index" => 70], "db_column" => "deduction_amount_hospital_discount"], + ["excel_column" => ["col_name" => "deduction_amount_paid_by_patient", "col_index" => 71], "db_column" => "deduction_amount_paid_by_patient"], + ["excel_column" => ["col_name" => "deduction_amount_issurer_approved", "col_index" => 72], "db_column" => "deduction_amount_issurer_approved"], + ["excel_column" => ["col_name" => "deduction_amount_deductible", "col_index" => 73], "db_column" => "deduction_amount_deductible"], + ["excel_column" => ["col_name" => "deduction_amount_intimation_penalty", "col_index" => 74], "db_column" => "deduction_amount_intimation_penalty"], + ["excel_column" => ["col_name" => "claim_payable_to_name", "col_index" => 75], "db_column" => "claim_payable_to_name"], + ["excel_column" => ["col_name" => "utr_no", "col_index" => 76], "db_column" => "utr_no"], + ["excel_column" => ["col_name" => "utr_date", "col_index" => 77], "db_column" => "utr_date"], + ["excel_column" => ["col_name" => "denial_short_description", "col_index" => 78], "db_column" => "denial_short_description"], + ["excel_column" => ["col_name" => "claim_received_date", "col_index" => 79], "db_column" => "claim_received_date"], + ["excel_column" => ["col_name" => "last_necessary_doc_rec_date", "col_index" => 80], "db_column" => "last_necessary_doc_rec_date"], + ["excel_column" => ["col_name" => "processed_date", "col_index" => 81], "db_column" => "processed_date"], + ["excel_column" => ["col_name" => "first_document_attached_date", "col_index" => 82], "db_column" => "first_document_attached_date"], + ["excel_column" => ["col_name" => "claim_processing_tat_days", "col_index" => 83], "db_column" => "claim_processing_tat_days"], + ["excel_column" => ["col_name" => "ready_for_payment_date", "col_index" => 84], "db_column" => "ready_for_payment_date"], + ["excel_column" => ["col_name" => "payment_date", "col_index" => 85], "db_column" => "payment_date"], + ["excel_column" => ["col_name" => "claim_payment_tat_days", "col_index" => 86], "db_column" => "claim_payment_tat_days"], + ["excel_column" => ["col_name" => "denial_description", "col_index" => 87], "db_column" => "denial_description"], + ["excel_column" => ["col_name" => "error_group", "col_index" => 88], "db_column" => "error_group"], + ["excel_column" => ["col_name" => "tpa_name", "col_index" => 89], "db_column" => "tpa_name"], + ["excel_column" => ["col_name" => "new_short_error_group", "col_index" => 90], "db_column" => "new_short_error_group"], + ["excel_column" => ["col_name" => "death_claim", "col_index" => 91], "db_column" => "death_claim"], + ["excel_column" => ["col_name" => "vip_claim", "col_index" => 92], "db_column" => "vip_claim"], + ["excel_column" => ["col_name" => "balance_sum_insured_exhausted", "col_index" => 93], "db_column" => "balance_sum_insured_exhausted"], + ]; + + + protected $ticketMasterMapping = [ + + // Employee / Beneficiary details + 'pribenef_employee_code' => 'emp_code', + 'benef_relation' => 'relationship', + + // Policy / Claim identifiers + 'policy_no' => 'policy_no', + 'claim_id' => 'tpa_claim_id', + 'insurer_claim_ref_no' => 'tpa_no', + 'claim_pre_auths' => 'tpa_claim_push_reference_no', + + // Claim type & status + 'claim_type' => 'claim_type', + 'claim_status' => 'tpa_claim_status', + + // Dates + 'date_of_admission' => 'doa', + 'date_of_discharge' => 'dod', + 'intimation_date' => 'date_of_intimat', + 'settled_date' => 'settled_date', + 'claim_received_date' => 'registration_date', + 'processed_date' => 'approved_date', + + // Amounts + 'claim_amount' => 'claim_amount', + 'claim_approved_amount' => 'approved_amount', + + // Hospital details + 'hospital_name' => 'hospital_name', + 'hospital_address' => 'hospital_address', + 'hospital_city' => 'hospital_city', + 'hospital_state' => 'hospital_state', + 'hospital_pincode' => 'hospital_pin_code', + 'hospital_phone_no' => 'hospital_phone_no', + + // Denial / approval + 'denial_description' => 'denial_reason', + 'approved_description' => 'approved_description', + + // Payment + 'utr_no' => 'utr_details', + 'priority' => 1, + 'mode_of_intimation' => 5, + 'ticket_type_id' => 1, + ]; + + + protected $statusMapping = [ + 'Settled' => 11, + 'Rejected' => 8, + 'Denied' => 8, + 'Cancelled' => 13, + 'Processed' => 61, + 'Information Awaited' => 4, + 'Denied Letter Sent' => 66, + 'Cashless Document Awaited' => 3, + ]; + + + /** + * ABSTRACT FUNCTIONs + */ + public function bulkInsertTPATable(array $data): bool + { + if (empty($data)) { + return false; + } + + $builder = $this->db->table('claims_dump_medi_assist'); + $builder->insertBatch($data); + + return true; + } + + + public function importClaimMaster(array $data): bool + { + if (empty($data)) { + return false; + } + + $ticketMasterModel = new TicketMasterModel(); + $ticketMasterModel->insertBatch($data); + + return true; + } + + + public function updateTicketIdInTPATable(): bool + { + if (empty($data)) { + return false; + } + + $builder = $this->db->table('claims_dump_medi_assist'); + $builder->insertBatch($data); + + return true; + } + + + public function updateTicketMasterRejectedReasonInTPATable($data): bool + { + if (empty($data)) { + return false; + } + + $builder = $this->db->table('claims_dump_medi_assist'); + $builder->insertBatch($data); + + return true; + } + + + /** + * MAPPING FUNCTIONs + */ + + public function mapTPAData(array $rows, $file_id): array + { + $ClientPolicyModel = new ClaimDumpFileModel(); + $file_data = $ClientPolicyModel->where('id', $file_id)->first(); + + $mapped = []; + + foreach ($rows as $row) { + + $item = []; + + foreach ($this->mapping as $map) { + $excelColumn = $map['excel_column']['col_name']; + $dbColumn = $map['db_column']; + + $value = $row[$excelColumn] ?? null; + + if ($this->isDateValue($value)) { + $value = $this->normalizeDate($value); + } + + $item[$dbColumn] = $value; + } + + $params = [ + 'date_of_admission' => change_date_format($item['date_of_admission'] ?? '') ?? null, + 'employee_number' => $item['employee_number'] ?? null, + 'claim_amount' => $item['claim_amount'] ?? null, + 'primary_policy_holder_card_id' => $item['primary_policy_holder_card_id'] ?? null + ]; + + $is_duplicate = $this->checkDuplicateTpaClaim('claims_dump_medi_assist', $params); + + if ($is_duplicate) { + $item = []; + continue; + } + + $item['file_id'] = $file_id ?? null; + $item['client_id'] = $file_data['client_id'] ?? null; + $item['client_policy_id'] = $file_data['client_policy_id'] ?? null; + $item['created_by'] = $file_data['created_by'] ?? null; + + $mapped[] = $item; + } + + return $mapped; + } + + public function mapClaimMasterData($file_id): array + { + + $ClientPolicyModel = new ClaimDumpFileModel(); + $file_data = $ClientPolicyModel->where('id', $file_id)->first(); + + $tpaClaimDumpData = $this->getTpaClaimDumpData('claims_dump_medi_assist', ['file_id' => $file_id]); + + if (empty($tpaClaimDumpData)) { + return ['status' => false, 'message' => "No data to insert in TICKET MASTER"]; + } + + + $ClientPolicyModel = new ClientPolicyModel(); + $client_policy_data = $ClientPolicyModel + ->select(" + client_policy.*, + ( + SELECT id + FROM client_rm + WHERE is_active = 1 + AND level = 3 + AND client_id = client_policy.client_id + ORDER BY id ASC + LIMIT 1 + ) AS acm_id + ") + ->where('client_policy.id', $file_data['client_policy_id']) + ->where('client_policy.is_active', 1) + ->first(); + + try { + + $mapped = []; + $rejecetd_reason = []; + + foreach ($tpaClaimDumpData as $row) { + + $params = [ + 'doa' => change_date_format($row['date_of_admission'] ?? '') ?? null, + 'emp_code' => $row['employee_number'] ?? null, + 'claim_amount' => $row['claim_amount'] ?? null, + 'tpa_no' => $row['primary_policy_holder_card_id'] ?? null + ]; + + $isduplicate = $this->checkDublicateTicketMasterClaim($params); + + if ($isduplicate) { + $reason = "This claim already exists in our system."; + $rejecetd_reason[$row['id']] = ["ticket_master_insert_reject_reason" => $reason]; + continue; + } + + $item = []; + + $item['client_id'] = $client_policy_data['client_id'] ?? null; + $item['client_policy_id'] = $client_policy_data['id'] ?? null; + $item['insurer_id'] = $client_policy_data['insurer_id'] ?? null; + $item['tpa_id'] = $client_policy_data['tpa_id'] ?? null; + $item['acm_id'] = $client_policy_data['acm_id'] ?? null; + $item['policy_no'] = $client_policy_data['policy_no'] ?? null; + $item['relationship'] = $this->convertRelation($row['relation'] ?? null, $row['gender'] ?? null); + + $employee_data = $this->getEmployeeDetails($file_data['client_id'], $file_data['client_policy_id'], $row['employee_number'], $item['relationship']); + + if (!empty($employee_data)) { + $item['emp_id'] = $employee_data['id'] ?? null; + $item['emp_name'] = $employee_data['name'] ?? null; + $item['emp_mail'] = $employee_data['email_corporate'] ?? null; + $item['emp_mobile'] = $employee_data['mobile'] ?? null; + $item['insured_emp_id'] = $employee_data['insured_emp_id'] ?? null; + $item['insured_name'] = $employee_data['insured_name'] ?? null; + } else { + + $reason = sprintf( + 'The policy number "%s" does not exist in our system. ' . + 'Details - Client ID: %s, Client Policy ID: %s, Employee Number: %s, Relationship: %s', + $row['insurer_policy_number'], + $file_data['client_id'], + $file_data['client_policy_id'], + $row['employee_number'], + $item['relationship'] + ); + + $rejecetd_reason[$row['id']] = ["ticket_master_insert_reject_reason" => $reason]; + continue; + } + + foreach ($this->ticketMasterMapping as $tpaKey => $ticketMasterKey) { + $item[$ticketMasterKey] = array_key_exists($tpaKey, $row) ? $row[$tpaKey] : null; + } + + // Meta fields + $item['claim_dump_ref_id'] = $row['id']; + $item['file_id'] = $file_id; + $item['claim_status_id'] = $statusMapping[$row['claim_status']] ?? 61; + $item['created_by'] = $file_data['created_by'] ?? null; + $item['claim_type'] = isset($row['mainclaim_prepost_type']) && !empty($row['mainclaim_prepost_type']) && strtolower($row['mainclaim_prepost_type']) == 'normal' ? 1 : 3; + + $mapped[] = $item; + } + + return ['status' => true, 'mapped_array' => $mapped, 'rejected_reason_array' => $rejecetd_reason]; + + } 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, + ]; + + return ['status' => false, "message" => $errorData['message'], 'error_data' => $errorData]; + } + } + + + /** + * HELPER FUNCTIONs + */ + + public function isDateValue($value): bool + { + if (empty($value)) { + return false; + } + + // Excel numeric date (e.g. 44927) + if (is_numeric($value) && $value > 30000) { + return true; + } + + // Common date formats + return preg_match( + '/^\d{1,2}[\/\-]\d{1,2}[\/\-]\d{2,4}$|^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/', + (string) $value + ) === 1; + } + + + public function normalizeDate($value): ?string + { + try { + // Excel numeric date + if (is_numeric($value)) { + return date('Y-m-d', \PhpOffice\PhpSpreadsheet\Shared\Date::excelToTimestamp($value)); + } + + // String date + return date('Y-m-d', strtotime(str_replace('/', '-', $value))); + } catch (\Throwable $e) { + return null; + } + } + + + public function convertRelation(string $relation, string $gender): ?string + { + if (empty($relation)) { + return null; + } + + $relation = strtolower($relation); + $gender = strtolower($gender); + + if ($relation == 'self') { + return $relation; + } + + if ($relation == 'spouse') { + return $relation; + } + + if ($relation == 'child' && $gender == 'male') { + return 'son'; + } + + if ($relation == 'child' && $gender == 'female') { + return 'daughter'; + } + + if ($relation == 'parents' && $gender == 'male') { + return 'father'; + } + + if ($relation == 'parents' && $gender == 'female') { + return 'mother'; + } + + if ($relation == 'parents-in-law' && $gender == 'male') { + return 'father-in-law'; + } + + if ($relation == 'parents-in-law' && $gender == 'female') { + return 'mother-in-law'; + } + + return null; + } + + + +} diff --git a/app/Libraries/TPAClaimsImportServices/RcareClaimImportService.php b/app/Libraries/TPAClaimsImportServices/RcareClaimImportService.php new file mode 100644 index 00000000..8fef8232 --- /dev/null +++ b/app/Libraries/TPAClaimsImportServices/RcareClaimImportService.php @@ -0,0 +1,447 @@ + ["col_name" => "CLInwardNo", "col_index" => 0], "db_column" => "cl_inward_no"], + ["excel_column" => ["col_name" => "Inward Date", "col_index" => 1], "db_column" => "inward_date"], + ["excel_column" => ["col_name" => "Claim Classification", "col_index" => 2], "db_column" => "claim_classification"], + ["excel_column" => ["col_name" => "Policy Name", "col_index" => 3], "db_column" => "policy_name"], + ["excel_column" => ["col_name" => "Policy Number", "col_index" => 4], "db_column" => "policy_number"], + ["excel_column" => ["col_name" => "Policy Start Date", "col_index" => 5], "db_column" => "policy_start_date"], + ["excel_column" => ["col_name" => "Policy End Date", "col_index" => 6], "db_column" => "policy_end_date"], + ["excel_column" => ["col_name" => "UHID", "col_index" => 7], "db_column" => "uhid"], + ["excel_column" => ["col_name" => "Insured Name", "col_index" => 8], "db_column" => "insured_name"], + ["excel_column" => ["col_name" => "Patient Name", "col_index" => 9], "db_column" => "patient_name"], + ["excel_column" => ["col_name" => "Employee/Member Id", "col_index" => 10], "db_column" => "employee_member_id"], + ["excel_column" => ["col_name" => "Grade", "col_index" => 11], "db_column" => "grade"], + ["excel_column" => ["col_name" => "Relation", "col_index" => 12], "db_column" => "relation"], + ["excel_column" => ["col_name" => "Age", "col_index" => 13], "db_column" => "age"], + ["excel_column" => ["col_name" => "Gender", "col_index" => 14], "db_column" => "gender"], + ["excel_column" => ["col_name" => "DF/DNF idenitifcation", "col_index" => 15], "db_column" => "df_dnf_identification"], + ["excel_column" => ["col_name" => "Sum Insured", "col_index" => 16], "db_column" => "sum_insured"], + ["excel_column" => ["col_name" => "DOA/OPD Treatment From", "col_index" => 17], "db_column" => "doa_opd_treatment_from"], + ["excel_column" => ["col_name" => "DOD/OPD Treatment To", "col_index" => 18], "db_column" => "dod_opd_treatment_to"], + ["excel_column" => ["col_name" => "Hospital Name", "col_index" => 19], "db_column" => "hospital_name"], + ["excel_column" => ["col_name" => "Hospital District", "col_index" => 20], "db_column" => "hospital_district"], + ["excel_column" => ["col_name" => "Hospital State", "col_index" => 21], "db_column" => "hospital_state"], + ["excel_column" => ["col_name" => "ICDCode", "col_index" => 22], "db_column" => "icd_code"], + ["excel_column" => ["col_name" => "Disease Category", "col_index" => 23], "db_column" => "disease_category"], + ["excel_column" => ["col_name" => "Final Status", "col_index" => 24], "db_column" => "final_status"], + ["excel_column" => ["col_name" => "Approved Date", "col_index" => 25], "db_column" => "approved_date"], + ["excel_column" => ["col_name" => "Claimed Amount", "col_index" => 26], "db_column" => "claimed_amount"], + ["excel_column" => ["col_name" => "Disallowed Amount", "col_index" => 27], "db_column" => "disallowed_amount"], + ["excel_column" => ["col_name" => "Net Sanct Amt", "col_index" => 28], "db_column" => "net_sanction_amount"], + ["excel_column" => ["col_name" => "Reason For Disallowance", "col_index" => 29], "db_column" => "reason_for_disallowance"], + ["excel_column" => ["col_name" => "External Query Remarks", "col_index" => 30], "db_column" => "external_query_remarks"], + ["excel_column" => ["col_name" => "Rejection Remarks", "col_index" => 31], "db_column" => "rejection_remarks"], + ["excel_column" => ["col_name" => "Cheque/NEFT Number", "col_index" => 32], "db_column" => "cheque_neft_number"], + ["excel_column" => ["col_name" => "Cheque/NEFT Date", "col_index" => 33], "db_column" => "cheque_neft_date"], + ["excel_column" => ["col_name" => "Diagnosis", "col_index" => 34], "db_column" => "diagnosis"], + ["excel_column" => ["col_name" => "Treatment Detail", "col_index" => 35], "db_column" => "treatment_detail"], + ["excel_column" => ["col_name" => "Member Reimbursement CL Type", "col_index" => 36], "db_column" => "member_reimbursement_cl_type"], + ]; + + protected $ticketMasterMapping = [ + + // Employee / Member + 'employee_member_id' => 'emp_code', + 'insured_name' => 'insured_name', + 'patient_name' => 'emp_name', + 'relation' => 'relationship', + + // Policy + 'policy_number' => 'policy_no', + 'policy_start_date' => 'date_of_incep', + + // Claim Dates + 'doa_opd_treatment_from' => 'doa', + 'dod_opd_treatment_to' => 'dod', + 'approved_date' => 'approved_date', + + // Claim Amounts + 'claimed_amount' => 'claim_amount', + 'net_sanction_amount' => 'approved_amount', + + // Status / Remarks + 'final_status' => 'tpa_claim_status', + 'reason_for_disallowance' => 'denial_reason', + 'rejection_remarks' => 'return_remark', + + // Hospital + 'hospital_name' => 'hospital_name', + 'hospital_state' => 'hospital_state', + 'hospital_district' => 'hospital_city', + + 'diagnosis' => 'claim_description', + + // Payment + 'cheque_neft_number' => 'utr_details', + 'cheque_neft_date' => 'settled_date', + + // References + 'cl_inward_no' => 'claim_number', + + 'priority' => 1, + 'mode_of_intimation' => 5, + 'ticket_type_id' => 1, + ]; + + protected $statusMapping = [ + 'Settled' => 11, + 'Rejected' => 8, + 'Denied' => 8, + 'Cancelled' => 13, + 'Processed' => 61, + 'Information Awaited' => 4, + 'Denied Letter Sent' => 66, + 'Cashless Document Awaited' => 3, + ]; + + /** + * ABSTRACT FUNCTIONs + */ + public function bulkInsertTPATable(array $data): bool + { + if (empty($data)) { + return false; + } + + try { + + $builder = $this->db->table('claims_dump_reliance'); + $builder->insertBatch($data); + + return true; + + } 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, + ]; + dd($errorData); + return false; + } + + } + + + public function importClaimMaster(array $data): bool + { + if (empty($data)) { + return false; + } + + $ticketMasterModel = new TicketMasterModel(); + $ticketMasterModel->insertBatch($data); + + return true; + } + + + public function updateTicketIdInTPATable(): bool + { + if (empty($data)) { + return false; + } + + $builder = $this->db->table('claims_dump_reliance'); + $builder->insertBatch($data); + + return true; + } + + + public function updateTicketMasterRejectedReasonInTPATable($data): bool + { + if (empty($data)) { + return false; + } + + $builder = $this->db->table('claims_dump_reliance'); + $builder->insertBatch($data); + + return true; + } + + + /** + * MAPPING FUNCTIONs + */ + + public function mapTPAData(array $rows, $file_id): array + { + $ClientPolicyModel = new ClaimDumpFileModel(); + $file_data = $ClientPolicyModel->where('id', $file_id)->first(); + + $mapped = []; + foreach ($rows as $row) { + + $item = []; + + foreach ($this->mapping as $map) { + $excelColumn = $map['excel_column']['col_name']; + $dbColumn = $map['db_column']; + + $value = $row[$excelColumn] ?? null; + + if ($this->isDateValue($value)) { + $value = $this->normalizeDate($value); + } + + $item[$dbColumn] = $value; + } + + $params = [ + 'doa_opd_treatment_from' => $item['doa_opd_treatment_from'] ?? null, + 'employee_member_id' => $item['employee_member_id'] ?? null, + 'claimed_amount' => $item['claimed_amount'] ?? null, + 'uhid' => $item['uhid'] ?? null + ]; + + $is_duplicate = $this->checkDuplicateTpaClaim('claims_dump_reliance', $params); + + if ($is_duplicate) { + $item = []; + continue; + } + + $item['file_id'] = $file_id ?? null; + $item['client_id'] = $file_data['client_id'] ?? null; + $item['client_policy_id'] = $file_data['client_policy_id'] ?? null; + $item['created_by'] = $file_data['created_by'] ?? null; + + $mapped[] = $item; + } + + return $mapped; + } + + public function mapClaimMasterData($file_id): array + { + + $ClientPolicyModel = new ClaimDumpFileModel(); + $file_data = $ClientPolicyModel->where('id', $file_id)->first(); + + $tpaClaimDumpData = $this->getTpaClaimDumpData('claims_dump_reliance', ['file_id' => $file_id]); + + if (empty($tpaClaimDumpData)) { + return ['status' => false, 'message' => "No data to insert in TICKET MASTER"]; + } + + + $ClientPolicyModel = new ClientPolicyModel(); + $client_policy_data = $ClientPolicyModel + ->select(" + client_policy.*, + ( + SELECT id + FROM client_rm + WHERE is_active = 1 + AND level = 3 + AND client_id = client_policy.client_id + ORDER BY id ASC + LIMIT 1 + ) AS acm_id + ") + ->where('client_policy.id', $file_data['client_policy_id']) + ->where('client_policy.is_active', 1) + ->first(); + + try { + + $mapped = []; + $rejecetd_reason = []; + + foreach ($tpaClaimDumpData as $row) { + + $params = [ + 'doa' => change_date_format($row['doa_opd_treatment_from'] ?? '') ?? null, + 'emp_code' => $row['employee_member_id'] ?? null, + 'claim_amount' => $row['claimed_amount'] ?? null, + 'tpa_no' => $row['uhid'] ?? null + ]; + + $isduplicate = $this->checkDublicateTicketMasterClaim($params); + + if ($isduplicate) { + $reason = "This claim already exists in our system."; + $rejecetd_reason[$row['id']] = ["ticket_master_insert_reject_reason" => $reason]; + continue; + } + + $item = []; + + $item['client_id'] = $client_policy_data['client_id'] ?? null; + $item['client_policy_id'] = $client_policy_data['id'] ?? null; + $item['insurer_id'] = $client_policy_data['insurer_id'] ?? null; + $item['tpa_id'] = $client_policy_data['tpa_id'] ?? null; + $item['acm_id'] = $client_policy_data['acm_id'] ?? null; + $item['policy_no'] = $client_policy_data['policy_no'] ?? null; + $item['relationship'] = $this->convertRelation($row['relation'] ?? null, $row['gender'] ?? null); + + $employee_data = $this->getEmployeeDetails($file_data['client_id'], $file_data['client_policy_id'], $row['employee_member_id'], $item['relationship']); + + if (!empty($employee_data)) { + $item['emp_id'] = $employee_data['id'] ?? null; + $item['emp_name'] = $employee_data['name'] ?? null; + $item['emp_mail'] = $employee_data['email_corporate'] ?? null; + $item['emp_mobile'] = $employee_data['mobile'] ?? null; + $item['insured_emp_id'] = $employee_data['insured_emp_id'] ?? null; + $item['insured_name'] = $employee_data['insured_name'] ?? null; + } else { + + $reason = sprintf( + 'The policy number "%s" does not exist in our system. ' . + 'Details - Client ID: %s, Client Policy ID: %s, Employee Number: %s, Relationship: %s', + $row['insurer_policy_number'], + $file_data['client_id'], + $file_data['client_policy_id'], + $row['employee_number'], + $item['relationship'] + ); + + $rejecetd_reason[$row['id']] = ["ticket_master_insert_reject_reason" => $reason]; + continue; + } + + foreach ($this->ticketMasterMapping as $tpaKey => $ticketMasterKey) { + $item[$ticketMasterKey] = array_key_exists($tpaKey, $row) ? $row[$tpaKey] : null; + } + + // Meta fields + $item['claim_status_id'] = $statusMapping[$row['final_status']] ?? 61; + $item['file_id'] = $file_id; + $item['created_by'] = $file_data['created_by'] ?? null; + $item['claim_type'] = 1; + + $mapped[] = $item; + } + + return ['status' => true, 'mapped_array' => $mapped, 'rejected_reason_array' => $rejecetd_reason]; + + } 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, + ]; + + return ['status' => false, "message" => $errorData['message'], 'error_data' => $errorData]; + } + } + + + /** + * HELPER FUNCTIONs + */ + + public function isDateValue($value): bool + { + if (empty($value)) { + return false; + } + + // Excel numeric date (e.g. 44927) + if (is_numeric($value) && $value > 30000) { + return true; + } + + // Common date formats + return preg_match( + '/^\d{1,2}[\/\-]\d{1,2}[\/\-]\d{2,4}$|^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/', + (string) $value + ) === 1; + } + + + public function normalizeDate($value): ?string + { + try { + // Excel numeric date + if (is_numeric($value)) { + return date('Y-m-d', \PhpOffice\PhpSpreadsheet\Shared\Date::excelToTimestamp($value)); + } + + // String date + return date('Y-m-d', strtotime(str_replace('/', '-', $value))); + } catch (\Throwable $e) { + return null; + } + } + + + public function convertRelation(string $relation, string $gender): ?string + { + if (empty($relation)) { + return null; + } + + $relation = strtolower($relation); + $gender = strtolower($gender); + + if ($relation == 'self') { + return $relation; + } + + if ($relation == 'spouse') { + return $relation; + } + + if ($relation == 'child' && $gender == 'male') { + return 'son'; + } + + if ($relation == 'child' && $gender == 'female') { + return 'daughter'; + } + + if ($relation == 'parents' && $gender == 'male') { + return 'father'; + } + + if ($relation == 'parents' && $gender == 'female') { + return 'mother'; + } + + if ($relation == 'parents-in-law' && $gender == 'male') { + return 'father-in-law'; + } + + if ($relation == 'parents-in-law' && $gender == 'female') { + return 'mother-in-law'; + } + + return null; + } + + + +} diff --git a/app/Libraries/TPAClaimsImportServices/VidalClaimImportService.php b/app/Libraries/TPAClaimsImportServices/VidalClaimImportService.php new file mode 100644 index 00000000..33243d22 --- /dev/null +++ b/app/Libraries/TPAClaimsImportServices/VidalClaimImportService.php @@ -0,0 +1,811 @@ + "TPA Policy Number", "db_column" => "tpa_policy_number"], + ["excel_column" => "Insurer Policy Number", "db_column" => "insurer_policy_number"], + ["excel_column" => "Corporate Name", "db_column" => "corporate_name"], + ["excel_column" => "Proposer Name", "db_column" => "proposer_name"], + ["excel_column" => "Corporate Group ID", "db_column" => "corporate_group_id"], + + ["excel_column" => "Policy Start Date", "db_column" => "policy_start_date"], + ["excel_column" => "Policy End date", "db_column" => "policy_end_date"], + + ["excel_column" => "Insurance Company Name", "db_column" => "insurance_company_name"], + + ["excel_column" => "Employee Number", "db_column" => "employee_number"], + ["excel_column" => "Employee Location", "db_column" => "employee_location"], + + ["excel_column" => "Primary Policy Holder Name", "db_column" => "primary_policy_holder_name"], + ["excel_column" => "Primary Policy Holder Card ID", "db_column" => "primary_policy_holder_card_id"], + + ["excel_column" => "Employee Grade", "db_column" => "employee_grade"], + + ["excel_column" => "Patient Health Card ID", "db_column" => "patient_health_card_id"], + ["excel_column" => "Patient Name", "db_column" => "patient_name"], + ["excel_column" => "Date of Birth", "db_column" => "date_of_birth"], + ["excel_column" => "Age", "db_column" => "age"], + ["excel_column" => "Gender", "db_column" => "gender"], + ["excel_column" => "Relation", "db_column" => "relation"], + + ["excel_column" => "Sum Insured", "db_column" => "sum_insured"], + ["excel_column" => "Balance Sum Insured", "db_column" => "balance_sum_insured"], + ["excel_column" => "Top Up Sum Insured", "db_column" => "top_up_sum_insured"], + + ["excel_column" => "Enrollment status", "db_column" => "enrollment_status"], + + ["excel_column" => "Policy Inception date", "db_column" => "policy_inception_date"], + ["excel_column" => "Policy Exit Date", "db_column" => "policy_exit_date"], + + ["excel_column" => "Insurer Risk ID", "db_column" => "insurer_risk_id"], + + ["excel_column" => "Claim Preauth Identifier", "db_column" => "claim_preauth_identifier"], + ["excel_column" => "TPA Claim Number", "db_column" => "tpa_claim_number"], + ["excel_column" => "Preauth Number", "db_column" => "preauth_number"], + ["excel_column" => "Insurer Claim Number", "db_column" => "insurer_claim_number"], + + ["excel_column" => "Claim Received date", "db_column" => "claim_received_date"], + ["excel_column" => "Date of Admission", "db_column" => "date_of_admission"], + ["excel_column" => "Date of Discharge", "db_column" => "date_of_discharge"], + + ["excel_column" => "Hospital Name", "db_column" => "hospital_name"], + ["excel_column" => "Hospital ID", "db_column" => "hospital_id"], + ["excel_column" => "Hospital Address", "db_column" => "hospital_address"], + ["excel_column" => "Hospital City", "db_column" => "hospital_city"], + ["excel_column" => "Hospital State", "db_column" => "hospital_state"], + ["excel_column" => "Hospital Pincode", "db_column" => "hospital_pincode"], + ["excel_column" => "Hospital Network status", "db_column" => "hospital_network_status"], + ["excel_column" => "PPN Hospital Status", "db_column" => "ppn_hospital_status"], + + ["excel_column" => "Room Category", "db_column" => "room_category"], + ["excel_column" => "Room Days", "db_column" => "room_days"], + ["excel_column" => "ICU Days", "db_column" => "icu_days"], + + ["excel_column" => "Medical Surgical Identifier", "db_column" => "medical_surgical_identifier"], + ["excel_column" => "Treatment Type of AYUSH", "db_column" => "treatment_type_of_ayush"], + ["excel_column" => "Package", "db_column" => "package"], + + ["excel_column" => "Diagnosis", "db_column" => "diagnosis"], + ["excel_column" => "Illness Details", "db_column" => "illness_details"], + ["excel_column" => "Ailment Grouping", "db_column" => "ailment_grouping"], + + ["excel_column" => "Primary ICD Code", "db_column" => "primary_icd_code"], + ["excel_column" => "Secondary ICD Code", "db_column" => "secondary_icd_code"], + + ["excel_column" => "Procedure Code", "db_column" => "procedure_code"], + ["excel_column" => "Procedure Description", "db_column" => "procedure_description"], + ["excel_column" => "Procedure Grouping", "db_column" => "procedure_grouping"], + + ["excel_column" => "Claim Submission mode", "db_column" => "claim_submission_mode"], + ["excel_column" => "Admission Category", "db_column" => "admission_category"], + ["excel_column" => "Type of Claim", "db_column" => "type_of_claim"], + ["excel_column" => "MainClaim_Prepost type", "db_column" => "mainclaim_prepost_type"], + ["excel_column" => "Type of Hospitalization", "db_column" => "type_of_hospitalization"], + ["excel_column" => "Death Status", "db_column" => "death_status"], + ["excel_column" => "Treatement Given", "db_column" => "treatment_given"], + + ["excel_column" => "Claim Amount", "db_column" => "claim_amount"], + ["excel_column" => "Total Billed Amount", "db_column" => "total_billed_amount"], + + ["excel_column" => "Claim Consultation Charges", "db_column" => "claim_consultation_charges"], + ["excel_column" => "Claim Investigation Charges", "db_column" => "claim_investigation_charges"], + ["excel_column" => "Claim Medicines", "db_column" => "claim_medicines"], + ["excel_column" => "Claim Nursing", "db_column" => "claim_nursing"], + ["excel_column" => "Claim Room Charges", "db_column" => "claim_room_charges"], + ["excel_column" => "Claim Icu Charges", "db_column" => "claim_icu_charges"], + ["excel_column" => "Claim Stay Charges", "db_column" => "claim_stay_charges"], + ["excel_column" => "Claim Surgeon Charges", "db_column" => "claim_surgeon_charges"], + ["excel_column" => "Claim Surgery Charges", "db_column" => "claim_surgery_charges"], + ["excel_column" => "Claim Miscellaneous Charges", "db_column" => "claim_miscellaneous_charges"], + ["excel_column" => "Claim Other Charges", "db_column" => "claim_other_charges"], + + ["excel_column" => "Approved Consultation Charges", "db_column" => "approved_consultation_charges"], + ["excel_column" => "Approved Investigation Charges", "db_column" => "approved_investigation_charges"], + ["excel_column" => "Approved Medicines", "db_column" => "approved_medicines"], + ["excel_column" => "Approved Nursing", "db_column" => "approved_nursing"], + ["excel_column" => "Approved Room Charges", "db_column" => "approved_room_charges"], + ["excel_column" => "Approved Icu Charges", "db_column" => "approved_icu_charges"], + ["excel_column" => "Approved Stay Charges", "db_column" => "approved_stay_charges"], + ["excel_column" => "Approved Surgeon Charges", "db_column" => "approved_surgeon_charges"], + ["excel_column" => "Approved Surgery Charges", "db_column" => "approved_surgery_charges"], + ["excel_column" => "Approved Miscellaneous Charges", "db_column" => "approved_miscellaneous_charges"], + ["excel_column" => "Approved Others Charges", "db_column" => "approved_others_charges"], + + ["excel_column" => "Total Disallowed Amount", "db_column" => "total_disallowed_amount"], + ["excel_column" => "Copayment Amount", "db_column" => "copayment_amount"], + ["excel_column" => "Deposit Amount", "db_column" => "deposit_amount"], + + ["excel_column" => "Exceeds Policy Limit", "db_column" => "exceeds_policy_limit"], + ["excel_column" => "Copay Buffer", "db_column" => "copay_buffer"], + ["excel_column" => "Hospital Discount Amount", "db_column" => "hospital_discount_amount"], + ["excel_column" => "Deductible Amount", "db_column" => "deductible_amount"], + + ["excel_column" => "Approved Amount", "db_column" => "approved_amount"], + ["excel_column" => "Total Incurred Amount", "db_column" => "total_incurred_amount"], + ["excel_column" => "Total Buffer Approved", "db_column" => "total_buffer_approved"], + ["excel_column" => "Total Buffer Utlilized", "db_column" => "total_buffer_utilized"], + + ["excel_column" => "TDS Amount", "db_column" => "tds_amount"], + ["excel_column" => "Net Amount", "db_column" => "net_amount"], + + ["excel_column" => "Claim Decision date", "db_column" => "claim_decision_date"], + ["excel_column" => "Payment Reference Number", "db_column" => "payment_reference_number"], + ["excel_column" => "Payment Reference Date", "db_column" => "payment_reference_date"], + + ["excel_column" => "Claim Status", "db_column" => "claim_status"], + ["excel_column" => "Deduction Remarks", "db_column" => "deduction_remarks"], + ["excel_column" => "Rejection Reasons", "db_column" => "rejection_reasons"], + ["excel_column" => "Claim Query Reasons", "db_column" => "claim_query_reasons"], + + ["excel_column" => "Insurer Request Sent date", "db_column" => "insurer_request_sent_date"], + ["excel_column" => "Insurer Conf. Received date", "db_column" => "insurer_conf_received_date"], + ["excel_column" => "Claim Reopen Date", "db_column" => "claim_reopen_date"], + + ["excel_column" => "First Query Raised date", "db_column" => "first_query_raised_date"], + ["excel_column" => "First Query response date", "db_column" => "first_query_response_date"], + ["excel_column" => "Last Query Raised date", "db_column" => "last_query_raised_date"], + ["excel_column" => "Last Query response date", "db_column" => "last_query_response_date"], + ["excel_column" => "Last Document Received date", "db_column" => "last_document_received_date"], + ]; + + + protected $mapping = [ + + ["excel_column" => ["col_name" => "TPA Policy Number", "col_index" => 0], "db_column" => "tpa_policy_number"], + ["excel_column" => ["col_name" => "Insurer Policy Number", "col_index" => 1], "db_column" => "insurer_policy_number"], + ["excel_column" => ["col_name" => "Corporate Name", "col_index" => 2], "db_column" => "corporate_name"], + ["excel_column" => ["col_name" => "Proposer Name", "col_index" => 3], "db_column" => "proposer_name"], + ["excel_column" => ["col_name" => "Corporate Group ID", "col_index" => 4], "db_column" => "corporate_group_id"], + + ["excel_column" => ["col_name" => "Policy Start Date", "col_index" => 5], "db_column" => "policy_start_date"], + ["excel_column" => ["col_name" => "Policy End date", "col_index" => 6], "db_column" => "policy_end_date"], + + ["excel_column" => ["col_name" => "Insurance Company Name", "col_index" => 7], "db_column" => "insurance_company_name"], + + ["excel_column" => ["col_name" => "Employee Number", "col_index" => 8], "db_column" => "employee_number"], + ["excel_column" => ["col_name" => "Employee Location", "col_index" => 9], "db_column" => "employee_location"], + + ["excel_column" => ["col_name" => "Primary Policy Holder Name", "col_index" => 10], "db_column" => "primary_policy_holder_name"], + ["excel_column" => ["col_name" => "Primary Policy Holder Card ID", "col_index" => 11], "db_column" => "primary_policy_holder_card_id"], + + ["excel_column" => ["col_name" => "Employee Grade", "col_index" => 12], "db_column" => "employee_grade"], + + ["excel_column" => ["col_name" => "Patient Health Card ID", "col_index" => 13], "db_column" => "patient_health_card_id"], + ["excel_column" => ["col_name" => "Patient Name", "col_index" => 14], "db_column" => "patient_name"], + ["excel_column" => ["col_name" => "Date of Birth", "col_index" => 15], "db_column" => "date_of_birth"], + ["excel_column" => ["col_name" => "Age", "col_index" => 16], "db_column" => "age"], + ["excel_column" => ["col_name" => "Gender", "col_index" => 17], "db_column" => "gender"], + ["excel_column" => ["col_name" => "Relation", "col_index" => 18], "db_column" => "relation"], + + ["excel_column" => ["col_name" => "Sum Insured", "col_index" => 19], "db_column" => "sum_insured"], + ["excel_column" => ["col_name" => "Balance Sum Insured", "col_index" => 20], "db_column" => "balance_sum_insured"], + ["excel_column" => ["col_name" => "Top Up Sum Insured", "col_index" => 21], "db_column" => "top_up_sum_insured"], + + ["excel_column" => ["col_name" => "Enrollment status", "col_index" => 22], "db_column" => "enrollment_status"], + + ["excel_column" => ["col_name" => "Policy Inception date", "col_index" => 23], "db_column" => "policy_inception_date"], + ["excel_column" => ["col_name" => "Policy Exit Date", "col_index" => 24], "db_column" => "policy_exit_date"], + + ["excel_column" => ["col_name" => "Insurer Risk ID", "col_index" => 25], "db_column" => "insurer_risk_id"], + + ["excel_column" => ["col_name" => "Claim Preauth Identifier", "col_index" => 26], "db_column" => "claim_preauth_identifier"], + ["excel_column" => ["col_name" => "TPA Claim Number", "col_index" => 27], "db_column" => "tpa_claim_number"], + ["excel_column" => ["col_name" => "Preauth Number", "col_index" => 28], "db_column" => "preauth_number"], + ["excel_column" => ["col_name" => "Insurer Claim Number", "col_index" => 29], "db_column" => "insurer_claim_number"], + + ["excel_column" => ["col_name" => "Claim Received date", "col_index" => 30], "db_column" => "claim_received_date"], + ["excel_column" => ["col_name" => "Date of Admission", "col_index" => 31], "db_column" => "date_of_admission"], + ["excel_column" => ["col_name" => "Date of Discharge", "col_index" => 32], "db_column" => "date_of_discharge"], + + ["excel_column" => ["col_name" => "Hospital Name", "col_index" => 33], "db_column" => "hospital_name"], + ["excel_column" => ["col_name" => "Hospital ID", "col_index" => 34], "db_column" => "hospital_id"], + ["excel_column" => ["col_name" => "Hospital Address", "col_index" => 35], "db_column" => "hospital_address"], + ["excel_column" => ["col_name" => "Hospital City", "col_index" => 36], "db_column" => "hospital_city"], + ["excel_column" => ["col_name" => "Hospital State", "col_index" => 37], "db_column" => "hospital_state"], + ["excel_column" => ["col_name" => "Hospital Pincode", "col_index" => 38], "db_column" => "hospital_pincode"], + ["excel_column" => ["col_name" => "Hospital Network status", "col_index" => 39], "db_column" => "hospital_network_status"], + ["excel_column" => ["col_name" => "PPN Hospital Status", "col_index" => 40], "db_column" => "ppn_hospital_status"], + + ["excel_column" => ["col_name" => "Room Category", "col_index" => 41], "db_column" => "room_category"], + ["excel_column" => ["col_name" => "Room Days", "col_index" => 42], "db_column" => "room_days"], + ["excel_column" => ["col_name" => "ICU Days", "col_index" => 43], "db_column" => "icu_days"], + + ["excel_column" => ["col_name" => "Medical Surgical Identifier", "col_index" => 44], "db_column" => "medical_surgical_identifier"], + ["excel_column" => ["col_name" => "Treatment Type of AYUSH", "col_index" => 45], "db_column" => "treatment_type_of_ayush"], + ["excel_column" => ["col_name" => "Package", "col_index" => 46], "db_column" => "package"], + + ["excel_column" => ["col_name" => "Diagnosis", "col_index" => 47], "db_column" => "diagnosis"], + ["excel_column" => ["col_name" => "Illness Details", "col_index" => 48], "db_column" => "illness_details"], + ["excel_column" => ["col_name" => "Ailment Grouping", "col_index" => 49], "db_column" => "ailment_grouping"], + + ["excel_column" => ["col_name" => "Primary ICD Code", "col_index" => 50], "db_column" => "primary_icd_code"], + ["excel_column" => ["col_name" => "Secondary ICD Code", "col_index" => 51], "db_column" => "secondary_icd_code"], + + ["excel_column" => ["col_name" => "Procedure Code", "col_index" => 52], "db_column" => "procedure_code"], + ["excel_column" => ["col_name" => "Procedure Description", "col_index" => 53], "db_column" => "procedure_description"], + ["excel_column" => ["col_name" => "Procedure Grouping", "col_index" => 54], "db_column" => "procedure_grouping"], + + ["excel_column" => ["col_name" => "Claim Submission mode", "col_index" => 55], "db_column" => "claim_submission_mode"], + ["excel_column" => ["col_name" => "Admission Category", "col_index" => 56], "db_column" => "admission_category"], + ["excel_column" => ["col_name" => "Type of Claim", "col_index" => 57], "db_column" => "type_of_claim"], + ["excel_column" => ["col_name" => "MainClaim_Prepost type", "col_index" => 58], "db_column" => "mainclaim_prepost_type"], + ["excel_column" => ["col_name" => "Type of Hospitalization", "col_index" => 59], "db_column" => "type_of_hospitalization"], + ["excel_column" => ["col_name" => "Death Status", "col_index" => 60], "db_column" => "death_status"], + ["excel_column" => ["col_name" => "Treatement Given", "col_index" => 61], "db_column" => "treatment_given"], + + ["excel_column" => ["col_name" => "Claim Amount", "col_index" => 62], "db_column" => "claim_amount"], + ["excel_column" => ["col_name" => "Total Billed Amount", "col_index" => 63], "db_column" => "total_billed_amount"], + + ["excel_column" => ["col_name" => "Claim Consultation Charges", "col_index" => 64], "db_column" => "claim_consultation_charges"], + ["excel_column" => ["col_name" => "Claim Investigation Charges", "col_index" => 65], "db_column" => "claim_investigation_charges"], + ["excel_column" => ["col_name" => "Claim Medicines", "col_index" => 66], "db_column" => "claim_medicines"], + ["excel_column" => ["col_name" => "Claim Nursing", "col_index" => 67], "db_column" => "claim_nursing"], + ["excel_column" => ["col_name" => "Claim Room Charges", "col_index" => 68], "db_column" => "claim_room_charges"], + ["excel_column" => ["col_name" => "Claim Icu Charges", "col_index" => 69], "db_column" => "claim_icu_charges"], + ["excel_column" => ["col_name" => "Claim Stay Charges", "col_index" => 70], "db_column" => "claim_stay_charges"], + ["excel_column" => ["col_name" => "Claim Surgeon Charges", "col_index" => 71], "db_column" => "claim_surgeon_charges"], + ["excel_column" => ["col_name" => "Claim Surgery Charges", "col_index" => 72], "db_column" => "claim_surgery_charges"], + ["excel_column" => ["col_name" => "Claim Miscellaneous Charges", "col_index" => 73], "db_column" => "claim_miscellaneous_charges"], + ["excel_column" => ["col_name" => "Claim Other Charges", "col_index" => 74], "db_column" => "claim_other_charges"], + + ["excel_column" => ["col_name" => "Approved Consultation Charges", "col_index" => 75], "db_column" => "approved_consultation_charges"], + ["excel_column" => ["col_name" => "Approved Investigation Charges", "col_index" => 76], "db_column" => "approved_investigation_charges"], + ["excel_column" => ["col_name" => "Approved Medicines", "col_index" => 77], "db_column" => "approved_medicines"], + ["excel_column" => ["col_name" => "Approved Nursing", "col_index" => 78], "db_column" => "approved_nursing"], + ["excel_column" => ["col_name" => "Approved Room Charges", "col_index" => 79], "db_column" => "approved_room_charges"], + ["excel_column" => ["col_name" => "Approved Icu Charges", "col_index" => 80], "db_column" => "approved_icu_charges"], + ["excel_column" => ["col_name" => "Approved Stay Charges", "col_index" => 81], "db_column" => "approved_stay_charges"], + ["excel_column" => ["col_name" => "Approved Surgeon Charges", "col_index" => 82], "db_column" => "approved_surgeon_charges"], + ["excel_column" => ["col_name" => "Approved Surgery Charges", "col_index" => 83], "db_column" => "approved_surgery_charges"], + ["excel_column" => ["col_name" => "Approved Miscellaneous Charges", "col_index" => 84], "db_column" => "approved_miscellaneous_charges"], + ["excel_column" => ["col_name" => "Approved Others Charges", "col_index" => 85], "db_column" => "approved_others_charges"], + + ["excel_column" => ["col_name" => "Total Disallowed Amount", "col_index" => 86], "db_column" => "total_disallowed_amount"], + ["excel_column" => ["col_name" => "Copayment Amount", "col_index" => 87], "db_column" => "copayment_amount"], + ["excel_column" => ["col_name" => "Deposit Amount", "col_index" => 88], "db_column" => "deposit_amount"], + + ["excel_column" => ["col_name" => "Exceeds Policy Limit", "col_index" => 89], "db_column" => "exceeds_policy_limit"], + ["excel_column" => ["col_name" => "Copay Buffer", "col_index" => 90], "db_column" => "copay_buffer"], + ["excel_column" => ["col_name" => "Hospital Discount Amount", "col_index" => 91], "db_column" => "hospital_discount_amount"], + ["excel_column" => ["col_name" => "Deductible Amount", "col_index" => 92], "db_column" => "deductible_amount"], + + ["excel_column" => ["col_name" => "Approved Amount", "col_index" => 93], "db_column" => "approved_amount"], + ["excel_column" => ["col_name" => "Total Incurred Amount", "col_index" => 94], "db_column" => "total_incurred_amount"], + ["excel_column" => ["col_name" => "Total Buffer Approved", "col_index" => 95], "db_column" => "total_buffer_approved"], + ["excel_column" => ["col_name" => "Total Buffer Utlilized", "col_index" => 96], "db_column" => "total_buffer_utilized"], + + ["excel_column" => ["col_name" => "TDS Amount", "col_index" => 97], "db_column" => "tds_amount"], + ["excel_column" => ["col_name" => "Net Amount", "col_index" => 98], "db_column" => "net_amount"], + + ["excel_column" => ["col_name" => "Claim Decision date", "col_index" => 99], "db_column" => "claim_decision_date"], + ["excel_column" => ["col_name" => "Payment Reference Number", "col_index" => 100], "db_column" => "payment_reference_number"], + ["excel_column" => ["col_name" => "Payment Reference Date", "col_index" => 101], "db_column" => "payment_reference_date"], + + ["excel_column" => ["col_name" => "Claim Status", "col_index" => 102], "db_column" => "claim_status"], + ["excel_column" => ["col_name" => "Deduction Remarks", "col_index" => 103], "db_column" => "deduction_remarks"], + ["excel_column" => ["col_name" => "Rejection Reasons", "col_index" => 104], "db_column" => "rejection_reasons"], + ["excel_column" => ["col_name" => "Claim Query Reasons", "col_index" => 105], "db_column" => "claim_query_reasons"], + + ["excel_column" => ["col_name" => "Insurer Request Sent date", "col_index" => 106], "db_column" => "insurer_request_sent_date"], + ["excel_column" => ["col_name" => "Insurer Conf. Received date", "col_index" => 107], "db_column" => "insurer_conf_received_date"], + ["excel_column" => ["col_name" => "Claim Reopen Date", "col_index" => 108], "db_column" => "claim_reopen_date"], + + ["excel_column" => ["col_name" => "First Query Raised date", "col_index" => 109], "db_column" => "first_query_raised_date"], + ["excel_column" => ["col_name" => "First Query response date", "col_index" => 110], "db_column" => "first_query_response_date"], + ["excel_column" => ["col_name" => "Last Query Raised date", "col_index" => 111], "db_column" => "last_query_raised_date"], + ["excel_column" => ["col_name" => "Last Query response date", "col_index" => 112], "db_column" => "last_query_response_date"], + ["excel_column" => ["col_name" => "Last Document Received date", "col_index" => 113], "db_column" => "last_document_received_date"], + ]; + + + protected $ticketMasterMapping = [ + + // Policy / Claim identifiers + 'insurer_policy_number' => 'policy_no', + 'insurer_claim_number' => 'claim_number', + 'tpa_claim_number' => 'tpa_claim_id', + + // Employee / Insured details + 'employee_number' => 'emp_code', + 'primary_policy_holder_name' => 'emp_name', + 'patient_name' => 'insured_name', + + // Dates + 'date_of_admission' => 'doa', + 'date_of_discharge' => 'dod', + 'date_of_birth' => 'dob', + 'claim_received_date' => 'registration_date', + + // Claim details + 'claim_amount' => 'claim_amount', + 'approved_amount' => 'approved_amount', + 'sum_insured' => 'si_amt', + 'claim_status' => 'tpa_claim_status', + + // Hospital details + 'hospital_name' => 'hospital_name', + 'hospital_address' => 'hospital_address', + 'hospital_city' => 'hospital_city', + 'hospital_state' => 'hospital_state', + 'hospital_pincode' => 'hospital_pin_code', + + // Meta + 'file_id' => 'file_id', + 'priority' => 1, + 'mode_of_intimation' => 5, + 'ticket_type_id' => 1, + ]; + + + protected $statusMapping = [ + 'CL Paid with Settlement Letter' => 11, + 'CL Rejected' => 8, + 'CL Approved' => 9, + 'AL Closed' => 12, + ]; + + + /** + * ABSTRACT FUNCTIONs + */ + public function bulkInsertTPATable(array $data): bool + { + if (empty($data)) { + return false; + } + + $builder = $this->db->table('claims_dump_vidal'); + $builder->insertBatch($data); + + return true; + } + + + public function importClaimMaster(array $data): bool + { + if (empty($data)) { + return false; + } + + $ticketMasterModel = new TicketMasterModel(); + $ticketMasterModel->insertBatch($data); + + return true; + } + + + public function updateTicketIdInTPATable(): bool + { + if (empty($data)) { + return false; + } + + $builder = $this->db->table('claims_dump_vidal'); + $builder->insertBatch($data); + + return true; + } + + + public function updateTicketMasterRejectedReasonInTPATable($data): bool + { + if (empty($data)) { + return false; + } + + $builder = $this->db->table('claims_dump_vidal'); + $builder->insertBatch($data); + + return true; + } + + + /** + * MAPPING FUNCTIONs + */ + + public function mapTPAData(array $rows, $file_id): array + { + $ClientPolicyModel = new ClaimDumpFileModel(); + $file_data = $ClientPolicyModel->where('id', $file_id)->first(); + + $mapped = []; + + foreach ($rows as $row) { + + $item = []; + + foreach ($this->mapping as $map) { + $excelColumn = $map['excel_column']['col_name']; + $dbColumn = $map['db_column']; + + $value = $row[$excelColumn] ?? null; + + if ($this->isDateValue($value)) { + $value = $this->normalizeDate($value); + } + + $item[$dbColumn] = $value; + } + + $params = [ + 'date_of_admission' => change_date_format($item['date_of_admission'] ?? '') ?? null, + 'employee_number' => $item['employee_number'] ?? null, + 'claim_amount' => $item['claim_amount'] ?? null, + 'primary_policy_holder_card_id' => $item['primary_policy_holder_card_id'] ?? null + ]; + + $is_duplicate = $this->checkDuplicateTpaClaim('claims_dump_vidal', $params); + + if ($is_duplicate) { + $item = []; + continue; + } + + $item['file_id'] = $file_id ?? null; + $item['client_id'] = $file_data['client_id'] ?? null; + $item['client_policy_id'] = $file_data['client_policy_id'] ?? null; + $item['created_by'] = $file_data['created_by'] ?? null; + + $mapped[] = $item; + } + + return $mapped; + } + + public function mapClaimMasterData($file_id): array + { + + $ClientPolicyModel = new ClaimDumpFileModel(); + $file_data = $ClientPolicyModel->where('id', $file_id)->first(); + + $tpaClaimDumpData = $this->getTpaClaimDumpData('claims_dump_vidal', ['file_id' => $file_id]); + + if (empty($tpaClaimDumpData)) { + return ['status' => false, 'message' => "No data to insert in TICKET MASTER"]; + } + + + $ClientPolicyModel = new ClientPolicyModel(); + $client_policy_data = $ClientPolicyModel + ->select(" + client_policy.*, + ( + SELECT id + FROM client_rm + WHERE is_active = 1 + AND level = 3 + AND client_id = client_policy.client_id + ORDER BY id ASC + LIMIT 1 + ) AS acm_id + ") + ->where('client_policy.id', $file_data['client_policy_id']) + ->where('client_policy.is_active', 1) + ->first(); + + try { + + $mapped = []; + $rejecetd_reason = []; + + foreach ($tpaClaimDumpData as $row) { + + $params = [ + 'doa' => change_date_format($row['date_of_admission'] ?? '') ?? null, + 'emp_code' => $row['employee_number'] ?? null, + 'claim_amount' => $row['claim_amount'] ?? null, + 'tpa_no' => $row['primary_policy_holder_card_id'] ?? null + ]; + + $isduplicate = $this->checkDublicateTicketMasterClaim($params); + + if ($isduplicate) { + $reason = "This claim already exists in our system."; + $rejecetd_reason[$row['id']] = ["ticket_master_insert_reject_reason" => $reason]; + continue; + } + + $item = []; + + $item['client_id'] = $client_policy_data['client_id'] ?? null; + $item['client_policy_id'] = $client_policy_data['id'] ?? null; + $item['insurer_id'] = $client_policy_data['insurer_id'] ?? null; + $item['tpa_id'] = $client_policy_data['tpa_id'] ?? null; + $item['acm_id'] = $client_policy_data['acm_id'] ?? null; + $item['policy_no'] = $client_policy_data['policy_no'] ?? null; + $item['relationship'] = $this->convertRelation($row['relation'] ?? null, $row['gender'] ?? null); + + $employee_data = $this->getEmployeeDetails($file_data['client_id'], $file_data['client_policy_id'], $row['employee_number'], $item['relationship']); + + if (!empty($employee_data)) { + $item['emp_id'] = $employee_data['id'] ?? null; + $item['emp_name'] = $employee_data['name'] ?? null; + $item['emp_mail'] = $employee_data['email_corporate'] ?? null; + $item['emp_mobile'] = $employee_data['mobile'] ?? null; + $item['insured_emp_id'] = $employee_data['insured_emp_id'] ?? null; + $item['insured_name'] = $employee_data['insured_name'] ?? null; + } else { + + $reason = sprintf( + 'The policy number "%s" does not exist in our system. ' . + 'Details - Client ID: %s, Client Policy ID: %s, Employee Number: %s, Relationship: %s', + $row['insurer_policy_number'], + $file_data['client_id'], + $file_data['client_policy_id'], + $row['employee_number'], + $item['relationship'] + ); + + $rejecetd_reason[$row['id']] = ["ticket_master_insert_reject_reason" => $reason]; + continue; + } + + foreach ($this->ticketMasterMapping as $tpaKey => $ticketMasterKey) { + $item[$ticketMasterKey] = array_key_exists($tpaKey, $row) ? $row[$tpaKey] : null; + } + + // Meta fields + $item['claim_status_id'] = $statusMapping[$row['status']] ?? 61; + $item['file_id'] = $file_id; + $item['claim_dump_ref_id'] = $row['id']; + $item['created_by'] = $file_data['created_by'] ?? null; + $item['claim_type'] = isset($row['mainclaim_prepost_type']) && !empty($row['mainclaim_prepost_type']) && strtolower($row['mainclaim_prepost_type']) == 'normal' ? 1 : 3; + + $mapped[] = $item; + } + + return ['status' => true, 'mapped_array' => $mapped, 'rejected_reason_array' => $rejecetd_reason]; + + } 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, + ]; + + return ['status' => false, "message" => $errorData['message'], 'error_data' => $errorData]; + } + } + + public function mapClaimMasterDataOld($file_id): array + { + + $tpaClaimDumpData = $this->db + ->table('claims_dump_vidal') + ->where('is_active', 1) + ->where('file_id', $file_id) + ->where('ticket_id IS NULL') + ->get() + ->getResultArray(); + + if (empty($tpaClaimDumpData)) { + return []; + } + + $ClientPolicyModel = new ClientPolicyModel(); + $client_policy_data = $ClientPolicyModel->where('is_active', 1)->findAll(); + + $mapped = []; + $rejecetd_reason = []; + + foreach ($tpaClaimDumpData as $row) { + + $item = []; + + if(isset($row['insurer_policy_number']) && !empty($row['insurer_policy_number'])){ + + $basic_claim_data = $this->getClientPolicyDataBypolicyNo($client_policy_data, $row['insurer_policy_number']); + if(empty($basic_claim_data)){ + $reason = " This policy no ( " . $row['insurer_policy_number'] ." ) does not exist in our system"; + $rejecetd_reason[$row['id']] = ["ticket_master_insert_reject_reason" => $reason]; + continue; + } + + $item['client_id'] = $basic_claim_data['client_id'] ?? null; + $item['client_policy_id'] = $basic_claim_data['id'] ?? null; + $item['insurer_id'] = $basic_claim_data['insurer_id'] ?? null; + $item['tpa_id'] = $basic_claim_data['tpa_id'] ?? null; + $item['acm_id'] = $basic_claim_data['acm_id'] ?? null; + $item['policy_no'] = $basic_claim_data['policy_no'] ?? null; + $item['relationship'] = $this->convertRelation($row['relation'] ?? null, $row['gender'] ?? null); + + $employee_data = $this->getEmployeeDetails($item['client_id'], $item['client_policy_id'], $row['employee_number'], $item['relationship']); + if(!empty($employee_data)){ + $item['emp_id'] = $employee_data['client_id'] ?? null; + $item['emp_name'] = $employee_data['id'] ?? null; + $item['emp_mail'] = $employee_data['insurer_id'] ?? null; + $item['emp_mobile'] = $employee_data['tpa_id'] ?? null; + $item['insured_emp_id'] = $employee_data['insured_emp_id'] ?? null; + $item['insured_name'] = $employee_data['insured_name'] ?? null; + }else{ + $reason = " This policy no ( " . $row['insurer_policy_number'] ." ) does not exist in our system"; + $rejecetd_reason[$row['id']] = ["ticket_master_insert_reject_reason" => $reason]; + continue; + } + + }else{ + $reason = " Policy Number is empty"; + $rejecetd_reason[$row['id']] = ["ticket_master_insert_reject_reason" => $reason]; + continue; + } + + foreach ($this->ticketMasterMapping as $tpaKey => $ticketMasterKey) { + $item[$ticketMasterKey] = array_key_exists($tpaKey, $row) + ? $row[$tpaKey] + : null; + } + + $isduplicate = checkDuplicateClaim([ + 'doa' => change_date_format($item['doa'] ?? '') ?? null, + 'emp_code' => $item['emp_code'] ?? null, + 'claim_amount' => $item['claim_amount'] ?? null, + 'policy_no' => $item['policy_no'] ?? null + ]); + + if($isduplicate){ + $reason = " This claim ( " . $row['insurer_policy_number'] ." ) does not exist in our system"; + $rejecetd_reason[$row['id']] = ["ticket_master_insert_reject_reason" => $reason]; + continue; + } + + // Meta fields + $item['file_id'] = $file_id; + $item['created_by'] = get_session_userid() ?? null; + $item['claim_type'] = isset($row['mainclaim_prepost_type']) && !empty($row['mainclaim_prepost_type']) && strtolower($row['mainclaim_prepost_type']) == 'normal' ? 1 : 3; + + $mapped[] = $item; + + } + + return ['mapped_array' => $mapped, 'rejected_reason_array' => $rejecetd_reason]; + } + + + /** + * HELPER FUNCTIONs + */ + + public function isDateValue($value): bool + { + if (empty($value)) { + return false; + } + + // Excel numeric date (e.g. 44927) + if (is_numeric($value) && $value > 30000) { + return true; + } + + // Common date formats + return preg_match( + '/^\d{1,2}[\/\-]\d{1,2}[\/\-]\d{2,4}$|^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/', + (string) $value + ) === 1; + } + + + public function normalizeDate($value): ?string + { + try { + // Excel numeric date + if (is_numeric($value)) { + return date('Y-m-d', \PhpOffice\PhpSpreadsheet\Shared\Date::excelToTimestamp($value)); + } + + // String date + return date('Y-m-d', strtotime(str_replace('/', '-', $value))); + } catch (\Throwable $e) { + return null; + } + } + + + public function looksLikeDate($value): bool + { + if (empty($value)) { + return false; + } + + // Excel numeric date + if (is_numeric($value) && $value > 30000) { + return true; + } + + return preg_match( + '/\d{1,2}[\/\-]\d{1,2}[\/\-]\d{2,4}| + \d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}| + \d{1,2}\s?[A-Za-z]{3,}\s?\d{2,4}| + \d{8}/x', + (string) $value + ) === 1; + } + + + public function convertRelation(string $relation, string $gender): ?string + { + if (empty($relation)) { + return null; + } + + $relation = strtolower($relation); + $gender = strtolower($gender); + + if ($relation == 'self') { + return $relation; + } + + if ($relation == 'spouse') { + return $relation; + } + + if ($relation == 'child' && $gender == 'male') { + return 'son'; + } + + if ($relation == 'child' && $gender == 'female') { + return 'daughter'; + } + + if ($relation == 'parents' && $gender == 'male') { + return 'father'; + } + + if ($relation == 'parents' && $gender == 'female') { + return 'mother'; + } + + if ($relation == 'parents-in-law' && $gender == 'male') { + return 'father-in-law'; + } + + if ($relation == 'parents-in-law' && $gender == 'female') { + return 'mother-in-law'; + } + + return null; + } + + + public function getClientPolicyDataBypolicyNo(array $client_policy_data, string $policy_number): array + { + $matched_data = []; + foreach ($client_policy_data as $key => $value) { + if(trim($value) == trim($policy_number)){ + $matched_data = $value; + } + } + + if(!empty($matched_data)){ + $ClientRMModel = new ClientRMModel(); + $acm_data = $ClientRMModel->where('is_active', 1)->where('level', 3)->where('client_id', $matched_data['client_id'])->orderBy('id', 'asc')->first(); + if(!empty($acm_data)){ + $matched_data['acm_id'] = $acm_data['id'] ?? null; + } + } + + return $matched_data; + } + +} diff --git a/app/Libraries/TpaClaimsImportFactory.php b/app/Libraries/TpaClaimsImportFactory.php new file mode 100644 index 00000000..baeef074 --- /dev/null +++ b/app/Libraries/TpaClaimsImportFactory.php @@ -0,0 +1,37 @@ + new VidalClaimImportService(), + (int) env('ABHI_PRIMARY_KEY_CONSTANT') => new AbhiClaimImportService(), + (int) env('MEDI_ASSIST_PRIMARY_KEY_CONSTANT') => new MediAssistClaimImportService(), + (int) env('FHPL_PRIMARY_KEY_CONSTANT') => new FhplClaimImportService(), + (int) env('R_CARE_PRIMARY_KEY_CONSTANT') => new RcareClaimImportService(), + (int) env('ICICI_PRIMARY_KEY_CONSTANT') => new IciciClaimImportService(), + default => throw new InvalidArgumentException( + "Unsupported TPA ID: {$tpaId}" + ), + }; + } +} diff --git a/app/Models/ClaimDumpFileModel.php b/app/Models/ClaimDumpFileModel.php index 224adafc..e34d6116 100644 --- a/app/Models/ClaimDumpFileModel.php +++ b/app/Models/ClaimDumpFileModel.php @@ -10,6 +10,9 @@ class ClaimDumpFileModel extends Model protected $primaryKey = 'id'; protected $allowedFields = [ "id", + "client_id", + "client_policy_id", + "tpa_id", "file_name", "status", "reason", diff --git a/app/Models/ClaimsDumpFhplModel.php b/app/Models/ClaimsDumpFhplModel.php new file mode 100644 index 00000000..d8cd6632 --- /dev/null +++ b/app/Models/ClaimsDumpFhplModel.php @@ -0,0 +1,141 @@ +getResultArray(); // $countofalldata = count($result); // dd($result); - // dd($this->db->getLastQuery()->getQuery()); + dd($this->db->getLastQuery()->getQuery()); $keys = []; $filtered = []; diff --git a/app/Views/claim_dump_file_list.php b/app/Views/claim_dump_file_list.php index 696d97ce..0cf55ed9 100644 --- a/app/Views/claim_dump_file_list.php +++ b/app/Views/claim_dump_file_list.php @@ -22,6 +22,8 @@ } .dataTables_length label {height: 21px !important;} + + .readonly-select { background-color: #f3f3f3 !important; cursor: not-allowed; pointer-events: none; } +  [ Sample Excel ]
@@ -172,14 +199,47 @@
+ + \ No newline at end of file From e0eeb42779a434fc70b1ee380a4c925a008c55ca Mon Sep 17 00:00:00 2001 From: "venkatesh.r" Date: Tue, 27 Jan 2026 09:54:24 +0530 Subject: [PATCH 3/9] FIX_FIXES --- .env.sample | 10 +++++++++- app/Filters/AuthMVC.php | 2 +- .../BaseTpaClaimImportService.php | 2 +- 3 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.env.sample b/.env.sample index 6a9a2f06..9c0f9e71 100755 --- a/.env.sample +++ b/.env.sample @@ -99,4 +99,12 @@ CORS_DEBUG=true APP_SIGNATURE = TOKENTIMEOUT = -JWT_SECRET = \ No newline at end of file +JWT_SECRET = + +ICICI_PRIMARY_KEY_CONSTANT = + +ABHI_PRIMARY_KEY_CONSTANT = + +R_CARE_PRIMARY_KEY_CONSTANT = + +FHPL_PRIMARY_KEY_CONSTANT = \ No newline at end of file diff --git a/app/Filters/AuthMVC.php b/app/Filters/AuthMVC.php index e5826b6b..ef2da046 100755 --- a/app/Filters/AuthMVC.php +++ b/app/Filters/AuthMVC.php @@ -23,7 +23,7 @@ class AuthMVC implements FilterInterface // } // Fingerprint validation - $fp = generateFingerprint() + $fp = generateFingerprint(); // log_message('error',$fp); if (session()->get('fingerprint') !== $fp) { return AuthLogout::logout(); diff --git a/app/Libraries/TPAClaimsImportServices/BaseTpaClaimImportService.php b/app/Libraries/TPAClaimsImportServices/BaseTpaClaimImportService.php index 33fbedc9..1485dee2 100644 --- a/app/Libraries/TPAClaimsImportServices/BaseTpaClaimImportService.php +++ b/app/Libraries/TPAClaimsImportServices/BaseTpaClaimImportService.php @@ -47,7 +47,7 @@ abstract class BaseTpaClaimImportService } $tpaInsertData = $this->mapTPAData($rows, $fileId); - dd($tpaInsertData); + // dd($tpaInsertData); if (empty($tpaInsertData)) { return ['status' => false, 'message' => 'These records already exist in the system.']; From 88cd33e2f0e7f1e7944b348e9c85a2d1d2db7e10 Mon Sep 17 00:00:00 2001 From: "sanjeev.p" Date: Tue, 27 Jan 2026 10:09:25 +0530 Subject: [PATCH 4/9] FIX_due filepath missing --- app/Controllers/ClientController.php | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/app/Controllers/ClientController.php b/app/Controllers/ClientController.php index 7289c89e..9563cbe2 100755 --- a/app/Controllers/ClientController.php +++ b/app/Controllers/ClientController.php @@ -1134,6 +1134,7 @@ class ClientController extends AdminController $data = $this->request->getPost(); $sanitized_data = sanitizeInputArrayAdvanced($data); $form_type = $sanitized_data['form_type'] ?? null; + $uploadFilePath = WRITEPATH . 'uploads/client_kyc_documents'; unset($data['file_name']); @@ -1188,6 +1189,7 @@ class ClientController extends AdminController $data = $this->request->getPost(); $sanitized_data = sanitizeInputArrayAdvanced($data); $form_type = $sanitized_data['form_type'] ?? null; + $uploadFilePath = WRITEPATH . 'uploads/client_kyc_documents'; unset($sanitized_data['file_name']); @@ -1279,6 +1281,7 @@ class ClientController extends AdminController $file = $this->request->getFile('file_name'); + $uploadFilePath = WRITEPATH . 'uploads/client_kyc_documents'; $fileName = file_Upload($file, $uploadFilePath); if (!empty($fileName)) { @@ -1286,10 +1289,10 @@ class ClientController extends AdminController } $sanitized_data['created_by'] = get_session_userid(); - $uploadFilePath = WRITEPATH . 'uploads/client_kyc_documents'; - $File = file_Upload($uploadedFile, $uploadFilePath); - $this->myLogger->logme('info', 'Result of file_Upload: ' . $File); + + + $this->myLogger->logme('info', 'Result of file_Upload: ' . $fileName); unset($data['file_name']); $insertID = $this->clientKYCDocsModel->insert($sanitized_data); @@ -1297,7 +1300,7 @@ class ClientController extends AdminController if ($insertID) { $html = $this->generateKycSingleTable($sanitized_data['client_id']); $dropdown = $this->fetch_dropdown($sanitized_data['client_id']); - return $this->respond(['status' => true, 'code' => 200, 'file_name' => $File, 'html' => $html,'dropdown'=>$dropdown], 200); + return $this->respond(['status' => true, 'code' => 200, 'file_name' => $fileName, 'html' => $html,'dropdown'=>$dropdown], 200); } else { $this->myLogger->logme('error', 'Database insert failed.'); return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to add document'], 200); From 9623492a01196f1df9ff0c874a32522d0ea74530 Mon Sep 17 00:00:00 2001 From: "sanjeev.p" Date: Tue, 27 Jan 2026 11:32:39 +0530 Subject: [PATCH 5/9] FIX_minor issues --- app/Controllers/AppContentManagementController.php | 2 +- app/Controllers/ClientController.php | 5 +++-- app/Controllers/MasterController.php | 2 +- app/Controllers/TicketController.php | 1 + app/Views/add_image_list.php | 2 +- app/Views/cd_master_list.php | 2 +- app/Views/client_list.php | 2 +- app/Views/client_policy.php | 8 ++++---- app/Views/employee_data_list.php | 2 +- app/Views/insurer_export_templete.php | 2 +- app/Views/kyc_list.php | 2 +- app/Views/payout_list.php | 2 +- app/Views/policy_type_list.php | 2 +- app/Views/test_members_list.php | 2 +- 14 files changed, 19 insertions(+), 17 deletions(-) diff --git a/app/Controllers/AppContentManagementController.php b/app/Controllers/AppContentManagementController.php index ac62129d..ac00f848 100755 --- a/app/Controllers/AppContentManagementController.php +++ b/app/Controllers/AppContentManagementController.php @@ -230,7 +230,7 @@ class AppContentManagementController extends AdminController ]); } $request_post_data = $this->request->getPost(); - $data = sanitizeInputArrayAdvanced($data); + $data = sanitizeInputArrayAdvanced($request_post_data); $id = $data['fe_id']; diff --git a/app/Controllers/ClientController.php b/app/Controllers/ClientController.php index 9563cbe2..65b805b4 100755 --- a/app/Controllers/ClientController.php +++ b/app/Controllers/ClientController.php @@ -1155,7 +1155,8 @@ class ClientController extends AdminController } else { $kycDocs = $this->generateKycPrimaryTable($sanitized_data['client_id']); } - return $this->respond(['status' => true, 'code' => 200, 'data' => $kycDocs, 'file_name' => $File], 200); + return $this->respond(['status' => true, 'code' => 200, 'data' => $kycDocs, 'file_name' => $file + ], 200); } else { return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to upload KYC document'], 200); } @@ -1212,7 +1213,7 @@ class ClientController extends AdminController } else { $kycDocs = $this->generateKycPrimaryTable($sanitized_data['client_id']); } - return $this->respond(['status' => true, 'code' => 200, 'data' => $kycDocs, 'file_name' => $File], 200); + return $this->respond(['status' => true, 'code' => 200, 'data' => $kycDocs, 'file_name' => $file], 200); } else { return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to upload KYC document'], 200); } diff --git a/app/Controllers/MasterController.php b/app/Controllers/MasterController.php index be71e82c..e645daf2 100755 --- a/app/Controllers/MasterController.php +++ b/app/Controllers/MasterController.php @@ -1383,7 +1383,7 @@ class MasterController extends AdminController } $data = $this->request->getPost(); $sanitized_post_data = sanitizeInputArrayAdvanced($data); - $id = $sanitizeInputArrayAdvanced['PrimaryKey']; + $id = $sanitized_post_data['PrimaryKey']; $update = $this->tpaBranchModel->update($id, $sanitized_post_data); // print_r($this->request->getPost('name[]')); diff --git a/app/Controllers/TicketController.php b/app/Controllers/TicketController.php index 7dee25b6..275797f7 100644 --- a/app/Controllers/TicketController.php +++ b/app/Controllers/TicketController.php @@ -3328,6 +3328,7 @@ class TicketController extends BaseController $is_moved = $file->move(WRITEPATH . 'uploads/claims_mis/'); if ($is_moved) { + $file_path = WRITEPATH.'uploads/claims_mis'; $filename = file_Upload_for_lead($file, $file_path); $fileSize = $file->getSize(); // File size in bytes $fileSize = $fileSize / (1024 * 1024); // Convert to MB diff --git a/app/Views/add_image_list.php b/app/Views/add_image_list.php index c91db897..113ce962 100755 --- a/app/Views/add_image_list.php +++ b/app/Views/add_image_list.php @@ -56,7 +56,7 @@ table.dataTable thead th {