diff --git a/app/Config/Routes.php b/app/Config/Routes.php index 360c6b8c..13aff9ac 100755 --- a/app/Config/Routes.php +++ b/app/Config/Routes.php @@ -524,6 +524,8 @@ $routes->cli('cli/update-emp-policy-status', 'ClientController::updateEmpAndPoli $routes->cli('cli/update-emp-policy-status', 'ClientController::updateEmpAndPolicyStatus'); $routes->cli('cli/insurerRFQRemainder', 'LeadsController::remainderForQcr'); $routes->cli('cli/sendMailWithAutoQuery','TicketController::sendMailWithAutoQuery'); +$routes->cli('cli/ClaimStatusUpdate','MediAssistApiController::ClaimStatusUpdate'); + @@ -765,10 +767,11 @@ $routes->get('claimStatus','VidalApiController::claimStatus'); $routes->get('EcardRequest','MediAssistApiController::EcardRequest'); $routes->get('HospitalNetwork','MediAssistApiController::HospitalNetwork'); $routes->get('GetBenefDetails','MediAssistApiController::GetBenefDetails'); -$routes->get('ClaimDetail','MediAssistApiController::ClaimDetail'); +$routes->get('ClaimDetail','VidalApiController::ClaimDetail'); $routes->get('SubmitClaim','MediAssistApiController::SubmitClaim'); $routes->get('IntimateClaim','MediAssistApiController::IntimateClaim'); $routes->get('IRSubmission','MediAssistApiController::IRSubmission'); +$routes->get('ClaimStatusUpdate','MediAssistApiController::ClaimStatusUpdate'); // API service diff --git a/app/Controllers/AppContentManagementController.php b/app/Controllers/AppContentManagementController.php index 0dc36282..33d592e9 100755 --- a/app/Controllers/AppContentManagementController.php +++ b/app/Controllers/AppContentManagementController.php @@ -221,7 +221,7 @@ class AppContentManagementController extends AdminController } } - + public function FAQ() { $method = strtolower($this->request->getMethod()); @@ -263,17 +263,24 @@ class AppContentManagementController extends AdminController $id = $this->request->getGet('faq_id'); if (!empty($id)) { - // $row = $this->faqModel->where('is_active', 1)->find($id); - $row = $this->faqModel->find($id); + if($returnType === 'web'){ + $row = $this->faqModel->find($id); + }else{ + $row = $this->faqModel->where('is_active', 1)->find($id); + } + $data['faq_list'] = $row ? [$row] : []; } else { - // $data['faq_list'] = $this->faqModel->where('is_active', 1)->orderBy('id', 'desc')->findAll(); - $data['faq_list'] = $this->faqModel->orderBy('id', 'desc')->findAll(); + if($returnType === 'web'){ + $data['faq_list'] = $this->faqModel->orderBy('id', 'desc')->findAll(); + }else{ + $data['faq_list'] = $this->faqModel->where('is_active', 1)->orderBy('id', 'desc')->findAll(); + } } if ($returnType === 'web') { - $data['tab_name'] = "FAQ's"; - $data['page_name'] = "FAQ's"; + $data['tab_name'] = "FAQ"; + $data['page_name'] = "FAQ"; // print_r($data);die; return $this->loadLayout('faq_list', $data); } @@ -323,4 +330,42 @@ class AppContentManagementController extends AdminController } } + // public function frontend_content_files() + // { + + // // 1. Define your physical system path + // define('UPLOAD_PATH', ROOTPATH . 'public/uploads/add_image_upload/'); + + // // 2. Define the public URL so the editor can display the image later + // // This is what the browser uses to see the image (e.g., https://site.com/uploads/...) + // // $publicUrl = "https://yourdomain.com/public/uploads/add_image_upload/"; + // $publicUrl = ROOTPATH . 'public/uploads/add_image_upload/'; + // // if (!is_dir($uploadPath)) mkdir($uploadPath, 0755, true); + + // header('Content-Type: application/json'); + + // if ($_FILES['files']) { + // // Ensure directory exists + // if (!is_dir(UPLOAD_PATH)) { + // mkdir(UPLOAD_PATH, 0775, true); + // } + + // $fileName = time() . '_' . basename($_FILES['files']['name'][0]); + // $fullPath = UPLOAD_PATH . $fileName; + + // if (move_uploaded_file($_FILES['files']['tmp_name'][0], $fullPath)) { + // echo json_encode([ + // "success" => true, + // "data" => [ + // "baseurl" => $publicUrl, + // "files" => [$fileName] + // ] + // ]); + // } else { + // echo json_encode(["success" => false, "error" => "Failed to move file to " . UPLOAD_PATH]); + // } + // } + + // } + } \ No newline at end of file diff --git a/app/Controllers/ClientController.php b/app/Controllers/ClientController.php index dea5763b..039f6f99 100755 --- a/app/Controllers/ClientController.php +++ b/app/Controllers/ClientController.php @@ -5998,7 +5998,7 @@ class ClientController extends AdminController // ---------- POLICY TRANSACTION CONTROLLER -------------------------------------------------------------------------------- $policyTransactionController = new PolicyTransactionController(); - // $res = $policyTransactionController->validateInsurerStatement(['file_id' => '62']); + // $res = $policyTransactionController->validateInsurerStatement(['file_id' => '281']); // $res = $policyTransactionController->updateInsurerStatement(['file_id' => '62']); // dd('-----', $res); diff --git a/app/Controllers/EmployeeRestController.php b/app/Controllers/EmployeeRestController.php index a672bf8f..bb64f69e 100755 --- a/app/Controllers/EmployeeRestController.php +++ b/app/Controllers/EmployeeRestController.php @@ -3164,7 +3164,7 @@ class EmployeeRestController extends AdminController { try { - $feContentData = $this->feContentModel->findAll(); + $feContentData = $this->feContentModel->where('is_active',1)->findAll(); if (count($feContentData) > 0) { return $this->respond(['status' => 'success', 'code' => 200, 'data' => $feContentData], 200); diff --git a/app/Controllers/MediAssistApiController.php b/app/Controllers/MediAssistApiController.php index 476cf2f7..245157e4 100644 --- a/app/Controllers/MediAssistApiController.php +++ b/app/Controllers/MediAssistApiController.php @@ -16,10 +16,12 @@ class MediAssistApiController extends BaseController { use ResponseTrait; protected $db; + protected $mediAssistTpaId; public function __construct() { $this->db = \Config\Database::connect(); + $this->mediAssistTpaId = getenv('MEDI_ASSIST_PRIMARY_KEY_CONSTANT'); } @@ -623,7 +625,7 @@ class MediAssistApiController extends BaseController $this->db->table('ticket_master')->where('id', $claimId)->update($updateArray); // LOG UPDATE - log_message('info', "CLAIM STATUS SUCCESS | Updated ticket ID $claimId with claim status: $currentStatus"); + log_message('error', "CLAIM STATUS SUCCESS | Updated ticket ID $claimId with claim status: $currentStatus"); return $this->response->setJSON([ 'status' => true, @@ -635,7 +637,7 @@ class MediAssistApiController extends BaseController public function IRSubmission($claimId = null) // 585 this id for test { - log_message('info', "IRSubmission INIT for ticket_id={$claimId}"); + log_message('error', "IRSubmission INIT for ticket_id={$claimId}"); // 1. FETCH TICKET DETAILS $ticket = $this->db->table('ticket_master tm') @@ -688,7 +690,7 @@ class MediAssistApiController extends BaseController log_message('error', "File NOT FOUND on server → {$fileDir}"); } - log_message('info', "IRSubmission Attachment Ready: {$filename} | URL={$downloadUrl}"); + log_message('error', "IRSubmission Attachment Ready: {$filename} | URL={$downloadUrl}"); $Attachments[] = [ "AttachmentName" => $filename, @@ -706,7 +708,7 @@ class MediAssistApiController extends BaseController "Attachments" => $Attachments ]; - log_message('info', "IRSubmission Request Body => " . json_encode($body)); + log_message('error', "IRSubmission Request Body => " . json_encode($body)); // 4. SEND API CALL helper('api'); @@ -722,7 +724,7 @@ class MediAssistApiController extends BaseController $response = call_third_party_api($url, $method, $headers, $body); - log_message('info', "IRSubmission API Response => " . json_encode($response)); + log_message('error', "IRSubmission API Response => " . json_encode($response)); // 5. HANDLE RESPONSE if (!$response['status']) { @@ -738,7 +740,7 @@ class MediAssistApiController extends BaseController ]; } - log_message('info', "IRSubmission SUCCESS → ClaimID={$ticket['ClaimID']}"); + log_message('error', "IRSubmission SUCCESS → ClaimID={$ticket['ClaimID']}"); return [ 'status' => true, @@ -796,6 +798,161 @@ class MediAssistApiController extends BaseController } + public function ClaimStatusUpdate() + { + helper('api'); + + $url = getenv('MEDI_ASSIST_API_BASE_URL_CLAIMSTATUS'); + $method = 'POST'; + + $headers = [ + 'Content-Type: application/json', + 'Username:' . getenv('MEDI_ASSIST_API_USERNAME'), + 'Password:' . getenv('MEDI_ASSIST_API_PASSWORD'), + ]; + + // Fetch ticket master details + $TicketData = $this->db->table('ticket_master tm') + ->select(" + tm.id, + tm.tpa_no as memberId, + tm.tpa_claim_push_reference_no as claimRefNo, + cp.policy_no as policyNo, + cp.policy_start_date as startDate, + cp.policy_end_date as endDate, + e.emp_code as employeeCode + ") + ->join('employees e', 'e.id = tm.emp_id', 'left') + ->join('client_policy cp', 'tm.client_policy_id = cp.id', 'left') + ->where('tm.tpa_claim_push_reference_no IS NOT NULL') + ->where('tm.is_active', 1) + ->whereNotIn('tm.claim_status_id', [8, 11, 12, 13, 66, 22, 24, 47, 49, 32, 34, 53, 55, 42, 44, 58, 60]) + ->where('tm.tpa_id', $this->mediAssistTpaId) + ->get() + ->getResultArray(); + + // dd($TicketData); + + if (!$TicketData) { + log_message('error', "Claims not found to update status"); + return $this->response->setJSON(['status' => false,'message' => 'Claims not found' ]); + } + + $error_data = []; + $status_updated_count = 0; + + foreach ($TicketData as $key => $ticket) + { + $claimId = $ticket['id']; + + // REQUEST BODY + if($ticket['claimRefNo'] != null) + { + $body = [ + "policyNo" => $ticket['policyNo'] ?? "", + "startDate" => "", + "endDate" => "", + "employeeCode" => $ticket['employeeCode'] ?? "", + "memberID" => "", + "claimNo" => "", + "claimRefNo" => $ticket['claimRefNo'] ?? "", + ]; + + }else{ + + $body = [ + "policyNo" => $ticket['policyNo'] ?? "", + "startDate" => "", + "endDate" => "", + "employeeCode" => $ticket['employeeCode'] ?? "", + "memberID" => "", + "claimNo" => "", + "claimRefNo" => "", + ]; + + } + + // CALL API + $response = call_third_party_api($url, $method, $headers, $body); + + if ($response['status'] != true || empty($response['data']['claimsData'][0])) { + log_message('error', 'CLAIM STATUS FAILED | for ticket ID: ' . $claimId.' | response: '.json_encode($response)); + $error_data[$claimId][['status' => false,'message' => 'API call failed.','data' => $response]]; + } + + // Extract claim status + $claimData = $response['data']['claimsData'][0]; + $currentStatus = $claimData['claim_Current_Status'] ?? ''; + $tpa_claim_no = $claimData['tpA_CLAIM_NO'] ?? ''; + + // VALID STATUS LIST + $validStatuses = [ + + "Claim Received" => 1, + "In Progress" => 5, + "Processed" => 11, + "Claim Paid" => 11, + "Denied" => 13, + "Cancelled" => 13, + + "Information Awaited" => 4, + "Confirmation Awaited" => 4, + "Information Awaited Reminder" => 4, + "Information Awaited Final Reminder" => 4, + "Insurer Concurrence Awaited" => 6, + "Closed" => 12, + + "Physical Documents Awaited" => 9, + "Processed - Payment Initiated" => 10, + "Processed - Transaction Failed" => 10, + "Processed - Account Details Updated" => 10, + "Processed - Debit Note Raised With Insurer for Payment"=> 10, + "Processed - Payment Initiated by Insurer" => 10, + "Payment - Refunded to Insurer" => 14, + "Processed - Processing Payment" => 10, + "Processed - Physical Documents Awaited" => 9, + + // Extra Mappings (based on your DB list) + "NON ID" => 1, + "ID NOT GENERATED" => 2, + "CDA" => 3, + "REJECTED" => 8, + "APPROVED" => 9, + "PAYMENT INITIATED" => 10, + "SETTLED" => 11, + "RETURNED" => 14, + "UNDER PROCESS - TPA" => 61, + "DENIAL REVIEW AWAITED" => 66, + ]; + + // Maping tpa claim status with local claim Status + if (isset($validStatuses[$currentStatus])) + { + $updateArray = ['claim_status_id' => $validStatuses[$currentStatus] , 'tpa_claim_status' => $currentStatus , 'tpa_claim_id' => $tpa_claim_no , 'updated_at' => date('Y-m-d H:i:s')]; + }else{ + $updateArray = ['tpa_claim_status' => $currentStatus , 'tpa_claim_id' => $tpa_claim_no , 'updated_at' => date('Y-m-d H:i:s')]; + } + + // UPDATE ticket_master + $this->db->table('ticket_master')->where('id', $claimId)->update($updateArray); + $status_updated_count ++; + + // LOG UPDATE + log_message('error', "CLAIM STATUS SUCCESS | Updated ticket ID $claimId with claim status: $currentStatus"); + + } + + return $this->response->setJSON([ + 'status' => true, + 'message' => 'Claim status updated.', + 'updated_status' => $currentStatus, + 'api_response' => $response, + 'count' => $status_updated_count, + 'error_data' => $error_data, + ]); + } + + diff --git a/app/Controllers/PolicyTransactionController.php b/app/Controllers/PolicyTransactionController.php index 000d9931..385a4bff 100644 --- a/app/Controllers/PolicyTransactionController.php +++ b/app/Controllers/PolicyTransactionController.php @@ -3628,7 +3628,7 @@ } } - public function validateInsurerStatement($params) + public function validateInsurerStatementOld($params) { helper('excel_util_helper'); //get file info @@ -3742,6 +3742,162 @@ return array('status' => $ret_status, 'error_code' => $error_data['error_code'], 'error_data' => $error_data['error_data']); } + public function validateInsurerStatement($params) + { + helper('excel_util_helper'); + + $file_id = $params['file_id']; + + try { + + //get file info + $file = $this->insurerStatements->find($file_id); + // dd($file); + + $date = new \DateTime($file['month']); + + $month = $date->format('m'); + $year = $date->format('Y'); + + $error_data = ['error_code' => '', 'error_data' => []]; + $status = 'success'; + $ret_status = true; + + $return = []; + if (!isset($file)) { + //file not found in DB + $this->insurerStatements->where('id', $file_id)->set(['file_status' => 'failed', 'reason' => json_encode(['error_code' => 0, 'error_data' => 'statement file not found in DB'])])->update(); + return array('status' => false, 'msg' => 'statement file not found in DB'); + } + $file_name_with_path = WRITEPATH . "/uploads/statements/" . $file['file_name']; + + //check physical file + if (!file_exists($file_name_with_path)) { + //file not found update status and reason + $message = "Physcial file not found"; + // echo $message; + $this->myLogger->logme('error', ($message . ' for statement file id ' . $file_id)); + $this->insurerStatements->where('id', $file_id)->set(['file_status' => 'failed', 'reason' => json_encode(['error_code' => 0, 'error_data' => $message])])->update(); + return array('status' => false, 'error_code' => 0, 'error_data' => $message); //0 - Physcial file not found + } + + //get excel data to php array + $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file_name_with_path); + $sheet = $spreadsheet->getActiveSheet(); + + $highestRow = $sheet->getHighestRow(); + $highestColumn = $sheet->getHighestColumn(); + + $excel_data = $sheet->rangeToArray('A1:' . $highestColumn . $highestRow); + unset($excel_data[0]); + $excel_data = ExcelSanitizeHelper::sanitizeArrayData($excel_data); + // dd($excel_data); + + //get no of line items and update in DB + $line_items = 0; + + // get uploaded month transactions data + $source_data = $this->PTCOShareDetailsModel->getNonReconcileredPolicyTransactions(insurer_id: $file['insurer_id'], insurer_branch_id: $file['branch_id']); + // dd($source_data); + + // check policy no,insurer and etc in DB for this month + // if all good return true, otherwise return false with messssage + $matched_entry = []; + $error_messages = []; // row-wise error storage + + foreach ($excel_data as $excel_key => $excel_row) { + + $row_number = $excel_key; + $is_row_empty = check_row_is_empty_or_null($excel_row); + $policy_source_found = 0; + $endorsement_source_found = 0; + $dublicate_found = 0; + + if (!$is_row_empty) { + + $policy_no = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[1]); //policy_number from excel + $policy_no = preg_replace('/[\x{200B}\x{200C}\x{200D}\x{FEFF}\x{00A0}\x{200E}\x{200F}\x{202A}-\x{202E}]/u', '', $excel_row[1]); //policy_number from excel + + $endorsement_no = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[2] ?? ''); //endorsement number from excel + $endorsement_no = preg_replace('/[\x{200B}\x{200C}\x{200D}\x{FEFF}\x{00A0}\x{200E}\x{200F}\x{202A}-\x{202E}]/u', '', $excel_row[2] ?? ''); //endorsement number from excel + + foreach ($source_data as $source_key => $source_row) { + + $source_endorsement_no = $source_row['endorsement_no'] !== null ? $source_row['endorsement_no'] : null; + + if (($policy_no == $source_row['policy_no']) ){ + $policy_source_found = 1; + } + + if( $endorsement_no == $source_endorsement_no) { + $endorsement_source_found = 1; + } + + // Duplicate check + if (isset($matched_entry[$policy_no . '|' . $endorsement_no])) { + $dublicate_found = 1; + continue 2; + } + + if (($policy_no == $source_row['policy_no']) && $endorsement_no == $source_endorsement_no) { + $line_items = $line_items + 1; + $matched_entry[] = $policy_no . '|' . $endorsement_no; + unset($source_data[$source_key]); + continue 2; + } + } + + // Policy number mismatch + if ($policy_source_found == 0) { + $error_messages[$row_number]['policy_no_mismatch'] = + "Policy number ({$policy_no}) not in NHance."; + } + + // Endorsement number mismatch + if (!empty($endorsement_no) && $endorsement_source_found == 0) { + $error_messages[$row_number]['endorsement_no_mismatch'] = + "Endorsement number ({$endorsement_no}) not in NHance."; + } + + // Duplicate check + if ($dublicate_found == 1) { + $error_messages[$row_number]['duplicate'] = + "Duplicate entry found. This policy and endorsement ({$policy_no} '|' {$endorsement_no}) combination has already been matched."; + } + } + + } + // print_rr($error_messages);die; + + if (!empty($error_messages)) { + $error_data['error_code'] = 2; + $error_data['error_data'] = $error_messages; + $status = 'failed'; + $ret_status = false; + } + + //update in DB + $this->insurerStatements->where('id', $file_id)->set(['line_items' => $line_items, 'file_status' => $status, 'reason' => json_encode($error_data)])->update(); + return array('status' => $ret_status, 'error_code' => $error_data['error_code'], 'error_data' => $error_data['error_data']); + } catch (\Throwable $th) { + + $errorData = [ + 'message' => $th->getMessage(), + 'file' => $th->getFile(), + 'line' => $th->getLine(), + 'code' => $th->getCode(), + 'trace' => $th->getTraceAsString(), + 'trace_array' => $th->getTrace(), // full array version (optional) + 'function' => $th->getTrace()[0]['function'] ?? null, + 'class' => $th->getTrace()[0]['class'] ?? null, + ]; + + $this->myLogger->logme("error", "POLICY-TRANSACTION-CONTROLLER - validateInsurerStatement: Exception: " . json_encode($errorData ?? [])); + $this->insurerStatements->where('id', $file_id)->set(['line_items' => 0, 'file_status' => 'failed', 'reason' => json_encode($errorData)])->update(); + return array('status' => false, 'error_code' => [], 'error_data' => $errorData); + } + } + public function updateInsurerStatement($params) { @@ -5357,11 +5513,14 @@ // ------------------------------------------- // 1. First Stage: Check if vehicle already exists // ------------------------------------------- - foreach ($vehicle_data as $v) { - if (strcasecmp(trim($v['vehicle_no']), $vehicle_number) === 0) { - $vehicle_id = $v['id']; - $client_id = $v['owner']; - break; + + if(strtolower(trim($vehicle_number)) != 'new'){ + foreach ($vehicle_data as $v) { + if (strcasecmp(trim($v['vehicle_no']), $vehicle_number) === 0) { + $vehicle_id = $v['id']; + $client_id = $v['owner']; + break; + } } } diff --git a/app/Controllers/TicketController.php b/app/Controllers/TicketController.php index ac104bf3..73997e99 100644 --- a/app/Controllers/TicketController.php +++ b/app/Controllers/TicketController.php @@ -371,6 +371,11 @@ class TicketController extends BaseController $data['insurer_list'] = $this->insurerModel->where('is_active', 1)->findAll(); $data['tpa_list'] = $this->TPAModel->where('is_active', 1)->findAll(); $data['ticket_data'] = $this->ticketSearch(1); + $data['date_type'] = [ + 'ticket_created_date' => 'Created Date', + 'ticket_updated_date' => 'Updated Date', + ]; + return $this->loadLayout('ticket_search', $data); } else { @@ -401,6 +406,7 @@ class TicketController extends BaseController } else{ $data['ticket_data'] = $this->ticketSearch(); + // print_r($data['ticket_data']);die; $html = view('ticket_list', $data); return $this->respond(['status' => true, 'html' => $html], 200); } @@ -411,6 +417,7 @@ class TicketController extends BaseController public function ticketSearch($action = null) { $db = db_connect(); + $rawWhere = []; // log_message('error', 'Ticket Search Action: ' . $action); $subquery = $db->table('ticket_master tm') ->select([ @@ -464,6 +471,7 @@ class TicketController extends BaseController 'tm.insured_name', 'c.short_name', 'DATE_FORMAT(tm.created_at, "%d-%m-%Y") AS ticket_created_date', + 'DATE_FORMAT(tm.updated_at, "%d-%m-%Y") AS ticket_updated_date', 'COALESCE(tat_category.tat, "0-6 Days") AS tat', 'tm.claim_status_id', @@ -557,14 +565,24 @@ class TicketController extends BaseController } else { $search_data = $this->request->getPost(); // print_r($search_data); die() - $where = []; + $where = []; foreach ($search_data as $search_objects => $key) { if ($key != null && $key != '' && $key != 0 && $search_objects != 'is_dashboard') { - $where[$search_objects] = $key; + + if($search_objects == "date_type" && $search_data[$search_objects] === 'ticket_created_date'){ + $startDate = date('Y-m-d 00:00:00', strtotime($search_data['start_date'])); + $endDate = date('Y-m-d 23:59:59', strtotime($search_data['end_date'])); + $rawWhere[] = "tm.created_at BETWEEN '$startDate' AND '$endDate'"; + } + elseif($search_objects == "date_type" && $search_data[$search_objects] === 'ticket_updated_date'){ + $startDate = date('Y-m-d 00:00:00', strtotime($search_data['start_date'])); + $endDate = date('Y-m-d 23:59:59', strtotime($search_data['end_date'])); + $rawWhere[] = "tm.updated_at BETWEEN '$startDate' AND '$endDate'"; + }elseif($search_objects != "date_type" && $search_objects != "start_date" && $search_objects != "end_date"){ + $where[$search_objects] = $key; + } } } - // print_rr($where); - } $query = $db->table('ticket_master tm') ->select([ @@ -584,6 +602,7 @@ class TicketController extends BaseController 'tm.insured_name', 'c.short_name', 'DATE_FORMAT(tm.created_at, "%d-%m-%Y") AS ticket_created_date', + 'DATE_FORMAT(tm.updated_at, "%d-%m-%Y") AS ticket_updated_date', 'COALESCE(tat_category.tat, "0-6 Days") AS tat', '(SELECT first_name FROM user_profiles WHERE user_profiles.id = tm.acm_id) AS acm_name', @@ -641,9 +660,14 @@ class TicketController extends BaseController ->where('tm.is_active', 1) ->where($where) ->orderBy('tm.id', 'DESC'); + if (!empty($rawWhere)) { + foreach ($rawWhere as $condition) { + $query->where($condition, null, false); // raw SQL + } + } $data = $query->get()->getResultArray(); - // dd($db->getLastQuery()->getQuery()); + // dd($db->getLastQuery()->getQuery());die; // dd($data); if ($action == 5){ diff --git a/app/Controllers/UserController.php b/app/Controllers/UserController.php index 22451e89..f6b4cc60 100755 --- a/app/Controllers/UserController.php +++ b/app/Controllers/UserController.php @@ -634,7 +634,7 @@ class UserController extends AdminController $text = "update"; $data['updated_by'] = get_session_userid(); - $result = $this->partnerStaffModel->update($updateID, $data); + $result = $this->partnerStaffModel->update($id, $data); } else { $text = "create"; $data['role_id'] = 1; diff --git a/app/Controllers/VidalApiController.php b/app/Controllers/VidalApiController.php index 78fc7d57..3fb32afe 100644 --- a/app/Controllers/VidalApiController.php +++ b/app/Controllers/VidalApiController.php @@ -400,6 +400,58 @@ class VidalApiController extends BaseController return ['status' => 'success','data' => $decryptedData["redirectUrl"]]; } + public function ClaimDetail($claimId = null) + { + helper('api'); + + $url = getenv('VIDAL_API_BASE_URL').'/claims/claim-dependent-info'; + $method = 'POST'; + + $headers = [ + 'Content-Type: application/json', + 'Ocp-Apim-Subscription-Key:' .getenv('VIDAL_API_SUBSCRIPTION_KEY').'', + ]; + + // Fetch ticket master details + $ticket = $this->db->table('ticket_master tm') + ->select(" + tm.id, + tm.tpa_no as memberId, + tm.tpa_claim_push_reference_no as claimRefNo, + cp.policy_no as policyNo, + cp.policy_start_date as startDate, + cp.policy_end_date as endDate, + e.emp_code as employeeCode + ") + ->join('employees e', 'e.id = tm.emp_id', 'left') + ->join('client_policy cp', 'tm.client_policy_id = cp.id', 'left') + ->where('tm.id', $claimId) + ->get() + ->getRowArray(); + + $body = [ + 'empNO' => "", + 'tpaCardID' => "", + 'claimID' => "BLR-0284-CL-9349459", + 'emailID' => "", + 'mobileNO' => "", + ]; + + + + $response = call_third_party_api($url, $method, $headers, $body); + + if($response['status'] != true){ + return $this->response->setJSON([ + 'status' => false, + 'message' => 'failed.', + 'data' => $response + ]); + } + + return $this->response->setJSON($response); + } + //----------yet to start only submit claim given @@ -452,40 +504,7 @@ class VidalApiController extends BaseController } - public function claimStatus ($claimId = null) - { - helper('api'); - $url = getenv('VIDAL_API_BASE_URL').'/claims/claim-dependent-info'; - $method = 'POST'; - - $headers = [ - 'Content-Type: application/json', - 'Ocp-Apim-Subscription-Key:' .getenv('VIDAL_API_SUBSCRIPTION_KEY').'', - ]; - - $body = [ - 'empNO' => "", - 'tpaCardID' => "", - 'claimID' => "BLR-0284-CL-9349459", - 'emailID' => "", - 'mobileNO' => "", - ]; - - - - $response = call_third_party_api($url, $method, $headers, $body); - - if($response['status'] != true){ - return $this->response->setJSON([ - 'status' => false, - 'message' => 'failed.', - 'data' => $response - ]); - } - - return $this->response->setJSON($response); - } public function hospitalNetwork(){ diff --git a/app/Models/PolicyTransactionModel.php b/app/Models/PolicyTransactionModel.php index f6822911..509dbd30 100644 --- a/app/Models/PolicyTransactionModel.php +++ b/app/Models/PolicyTransactionModel.php @@ -616,9 +616,9 @@ policy_transaction.*, DATE_FORMAT(policy_transaction.policy_issue_date, '%d %b %Y') AS policy_issue_date, DATE_FORMAT( - IF(policy_transaction.month IS NULL, + IF(pt_co_share_details.pt_policy_issue_date IS NULL, policy_transaction.policy_issue_date, - policy_transaction.month), + pt_co_share_details.pt_policy_issue_date), '%b %Y') AS policy_issue_month, CASE WHEN clients.client_type = 1 THEN 'Group' @@ -2430,7 +2430,7 @@ return $result; } - public function getBDSReportList($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0, $client_branch_id = 0, $insurer_branch_id = 0, $client_policy_id = 0, $user_id = 0, $where = []) + public function getBDSReportListSingleUnion($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0, $client_branch_id = 0, $insurer_branch_id = 0, $client_policy_id = 0, $user_id = 0, $where = []) { $statement_month_condition = ''; @@ -2688,6 +2688,576 @@ UNION ALL + SELECT + pt.id AS id, + pt.endorsement_no, + pt.ref, + + pt.data_received_date, + pt.renewal_date, + pt.installment, + nhance_branch.branch_name as nhance_branch, + + DATE_FORMAT(pt.policy_issue_date, '%d %b %Y') AS policy_issue_date, + DATE_FORMAT(IF(insq.month IS NULL, pcsd.pt_policy_issue_date, insq.month),'%b %Y') AS policy_issue_month, + insq.month as statement_month, + + 'statement uploaded' AS statement_uploaded, + + CASE + WHEN c.client_type = 1 THEN 'Group' + WHEN c.client_type = 2 THEN 'Retail' + ELSE '-' + END AS client_type, + + CASE + WHEN pt.revenue_type = 'NA' THEN 'Fresh' + ELSE 'Renewal' + END AS revenue_type, + + CASE + WHEN + IFNULL(cssd.actual_tep_brokerage_amt, 0) = 0 + AND IFNULL(cssd.actual_tp_brokerage_amt, 0) = 0 + AND IFNULL(cssd.actual_bp_brokerage_amt, 0) = 0 + AND IFNULL(cssd.reward, 0) != 0 + THEN 'Rewards' + + WHEN pt.action_type = 'inception' + THEN 'Policy' + + ELSE 'Endorsement' + END AS action_type, + + + pt.action_type as action_type_string, + + c.client_name, + c.short_name AS client_short_name, + cb.branch_name AS client_branch_name, + cb.address1 AS client_address, + ptype.policy_type, + ptype.bap, + ins.id AS insurer_id, + ins.name AS insurer_name, + ins.short_name AS insurer_short_name, + ib.branch_name AS insurer_branch_name, + ib.branch_code AS insurer_branch_code, + + created_user.first_name as user_name, + + v.vehicle_no, + tpa.name AS tpa_name, + + pcsd.remark AS remarks, + pcsd.cop_amt AS bp_amt, + pcsd.exp_amt, + pcsd.id AS pt_id, + + su.first_name AS salse_person_name, + se.first_name AS service_person_name, + + ROUND(pcsd.cop_amt + pcsd.cotp_amt + pcsd.cotep_amt,2) AS premium_wo_gst, + ROUND((pcsd.cop_amt + pcsd.cotp_amt + pcsd.cotep_amt) * 0.18,2) AS gst_amount, + ROUND((pcsd.cop_amt + pcsd.cotp_amt + pcsd.cotep_amt) * 1.18,2) AS total_premium, + + ROUND(pcsd.cotp_amt + pcsd.cotep_amt,2) AS tp_or_ter, + DATEDIFF(pt.policy_end_date, CURDATE()) AS days, + (pcsd.agreed_tp_per + pcsd.agreed_tep_per) AS agreed_tp_or_ter_per, + + CASE + WHEN insq.month = pt.month THEN pcsd.exp_amt + ELSE 0 + END AS total_irda_amt_2, + + COALESCE(( + SELECT SUM(cs.reward) + FROM co_share_stmt_details cs + JOIN insurer_statements i ON cs.statement_id = i.id + WHERE cs.co_share_id = pcsd.id AND i.month = insq.month + AND i.is_active = 1 + AND cs.is_active = 1 + GROUP BY pt.policy_no, i.month, pcsd.insurer_id + ),0) AS reward, + + COALESCE(( + SELECT SUM( + COALESCE(cs.actual_bp_brokerage_amt,0) + + COALESCE(cs.actual_tp_brokerage_amt,0) + + COALESCE(cs.actual_tep_brokerage_amt,0) + + COALESCE(cs.reward,0) + ) + FROM co_share_stmt_details cs + JOIN insurer_statements i ON cs.statement_id = i.id + WHERE cs.co_share_id = pcsd.id + AND i.invoice_status IS NOT NULL + AND i.month = insq.month + AND i.is_active = 1 + AND cs.is_active = 1 + GROUP BY pt.policy_no, i.month, pcsd.insurer_id + ),0) AS billed_amt, + + CASE + WHEN pcsd.co_share_type IN (0,1) THEN pt.policy_no + WHEN pcsd.co_share_type > 1 + THEN IFNULL(NULLIF(pcsd.follower_policy_no,''), pt.policy_no) + ELSE pt.policy_no + END AS policy_no, + + CASE + WHEN pt.co_share = 1 THEN 'Yes' + ELSE 'No' + END AS co_share, + + CASE + WHEN pt.bro_payable_by = 1 THEN 'Yes' + ELSE 'No' + END AS bro_payable_by, + + pcsd.non_comm_per_amt, + + pcsd.bp_igst, + pcsd.bp_sgst, + pcsd.bp_cgst, + + pcsd.agreed_bp_per, + ROUND(pcsd.agreed_tp_per + pcsd.agreed_tep_per,2) AS agreed_tp_per, + + pcsd.standerd_bp_per, + ROUND(pcsd.standerd_tp_per + pcsd.standerd_tep_per,2) AS standerd_tp_per, + + cssd.actual_bp_amt, + ROUND(cssd.actual_tp_amt + cssd.actual_tep_amt,2) AS actual_tp_amt, + + cssd.actual_bp_per, + ROUND(cssd.actual_tp_per + cssd.actual_tep_per,2) AS actual_tp_per, + + cssd.actual_tep_brokerage_amt, + ROUND(cssd.actual_tp_brokerage_amt + cssd.actual_bp_brokerage_amt,2) AS actual_tp_brokerage_amt, + + service_branch.branch_name as service_branch, + + salse_manager.first_name as salse_manager_name, + service_manager.first_name as service_manager_name, + cd_master.cd_ac_no, + pt.rollover_date, + pt.policy_holder_name, + + CASE + WHEN pt.same_as_proposer = 1 THEN 'Yes' + ELSE 'No' + END AS same_as_proposer, + + pcsd.follower_policy_no, + pcsd.co_share_per, + pcsd.stamp_duty + + FROM policy_transaction pt + LEFT JOIN pt_co_share_details pcsd ON pt.id = pcsd.pt_id + LEFT JOIN co_share_stmt_details cssd ON pcsd.id = cssd.co_share_id + LEFT JOIN insurer_statements insq ON cssd.statement_id = insq.id + JOIN clients c ON c.id = pt.client_id + LEFT JOIN client_branch cb ON pt.client_branch_id = cb.id + LEFT JOIN client_policy cp ON pt.client_policy_id = cp.id + LEFT JOIN user_profiles up ON pt.created_by = up.id + LEFT JOIN vehicle v ON pt.vehicle_id = v.id + LEFT JOIN policy_type ptype ON pt.policy_type_id = ptype.id + LEFT JOIN insurers ins ON pcsd.insurer_id = ins.id + LEFT JOIN insurer_branch ib ON pcsd.insurer_branch_id = ib.id + LEFT JOIN tpa ON pt.tpa_id = tpa.id + LEFT JOIN tpa_branch tb ON pt.tpa_branch_id = tb.id + LEFT JOIN user_profiles su ON pt.sales_generated_by = su.id + LEFT JOIN user_profiles se ON pt.serviced_by = se.id + LEFT JOIN user_profiles created_user ON pt.created_by = created_user.id + LEFT JOIN nhance_branch ON pt.issuer_branch = nhance_branch.id + + LEFT JOIN nhance_branch service_branch ON pt.service_person_branch_id = service_branch.id + LEFT JOIN user_profiles salse_manager ON pt.salse_person_manager_id = salse_manager.id + LEFT JOIN user_profiles service_manager ON pt.service_person_manager_id = service_manager.id + LEFT JOIN cd_master ON pt.cd_ac_pk = cd_master.id + + + WHERE pt.is_active = 1 + AND pcsd.is_active = 1 + AND cssd.is_active = 1 + AND insq.is_active = 1 + $default_date_filter + $conditions + + GROUP BY pt.policy_no, pt.endorsement_no, pcsd.insurer_id, insq.month + + ) AS final_result + + $statement_month_condition + -- GROUP BY statement_month, insurer_name, policy_no + -- WHERE id = 6063 + + ORDER BY + id DESC, + policy_no ASC, + insurer_branch_name ASC, + statement_uploaded ASC, + statement_month ASC, + STR_TO_DATE(policy_issue_month, '%b %Y') ASC + "; + $query = $this->db->query($sql); + $result = $query->getResultArray(); + // dd($result); + // dd($this->db->getLastQuery()); + + $keys = []; + $filtered = []; + + foreach ($result as $row) { + + $endorsement_number = "-"; + if(!empty($row['endorsement_no'])){ + $endorsement_number = $row['endorsement_no']; + } + + $key = $row['statement_month'].'|'.$row['insurer_name'].'|'.$row['policy_no'] . '|' . $endorsement_number; + + // If uploaded record exists, always keep it and override previous + if ($row['statement_uploaded'] === 'statement uploaded') { + $filtered[$key] = $row; // overwrite no-statement row if it exists + $keys[$key] = true; + + } + // Keep "no statement uploaded" only if uploaded one not added yet + elseif (!isset($keys[$key])) { + $filtered[$key] = $row; + } + } + + $result = array_values($filtered); + // dd($result); + + // $runningBilled = []; + // $totalIrdaMap = []; + // $final = []; + + // foreach ($result as $row) { + // $ptId = $row['pt_id']; + + // // Store total_irda_amt only once (first non-zero value) + // if (!isset($totalIrdaMap[$ptId]) && $row['total_irda_amt'] > 0) { + // $totalIrdaMap[$ptId] = $row['total_irda_amt']; + // } + + // // Initialize running sum + // if (!isset($runningBilled[$ptId])) { + // $runningBilled[$ptId] = 0; + // } + + // // Add billed amount to running total + // $runningBilled[$ptId] += (float)$row['billed_amt']; + + // // Calculate unbilled amount + // $row['unbilled_amount'] = ($totalIrdaMap[$ptId] ?? 0) - $runningBilled[$ptId]; + + // $final[] = $row; + // } + + $totalBilled = []; + $totalIrdaMap = []; + + foreach ($result as $row) { + $key = $row['pt_id'].'-'.$row['insurer_id']; + + // Sum billed amount + $totalBilled[$key] = ($totalBilled[$key] ?? 0) + + (float) ($row['billed_amt'] ?? 0); + + // Store total_irda_amt once + if (!isset($totalIrdaMap[$key]) && ($row['total_irda_amt'] ?? 0) > 0) { + $totalIrdaMap[$key] = (float) $row['total_irda_amt']; + } + } + + + $ptSeen = []; + $final = []; + + foreach ($result as $row) { + $ptId = $row['pt_id'].'-'.$row['insurer_id']; + if (!isset($ptSeen[$ptId])) { + // First entry → set unbilled amount + $row['unbilled_amount'] = ($totalIrdaMap[$ptId] ?? 0) - ($totalBilled[$ptId] ?? 0); + + $ptSeen[$ptId] = true; + } else { + // Other entries → zero + $row['unbilled_amount'] = 0; + } + + $final[] = $row; + } + + $result = $final; + + // print_rr($result); die; + return $result; + } + + public function getBDSReportList($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0, $client_branch_id = 0, $insurer_branch_id = 0, $client_policy_id = 0, $user_id = 0, $where = []) + { + + $statement_month_condition = ''; + if ($date_type == 'statement_month' && $start_date != 0 && $end_date != 0) { + $statement_month_condition = " + WHERE statement_month >= '" . $start_date . "' + AND statement_month <= '" . $end_date . "' + "; + } + + $default_date_filter = ''; + if ($client_id == 0 && $insurer_id == 0 && $policy_type_id == 0 && $date_type == 0 && $issuer == 0) { + + $fromDate = date('Y-m-d', strtotime('-90 days')); + $toDate = date('Y-m-d 23:59:59'); + + if (empty($where)) { + + $default_date_filter = " + AND pt.created_at >= '" . $fromDate . "' + AND pt.created_at <= '" . $toDate . "' + "; + } + } + + $conditions = ""; // start safely + + // 1. Role-based restrictions + if ( + (!in_array(get_role_id(), [1, 5])) && + !( + in_array(MANAGEMENT_TEAM_ID, user_team()) || + in_array(FINANCE_TEAM_ID, user_team()) || + in_array(BUSINESS_TEAM_ID, user_team()) + ) + ) { + if (get_role_id() == 4 && in_array(POS_TEAM_ID, user_team())) { + $conditions .= " AND pt.created_by = " . get_session_userid(); + } + } + + // 2. Dynamic $where array + if (!empty($where)) { + foreach ($where as $column => $value) { + $value = addslashes($value); + $conditions .= " AND `$column` = '$value' "; + } + } + + // 3. Date condition (except statement_month) + if ($start_date != 0 && $end_date != 0 && $date_type != 0 && $date_type != 'statement_month') { + + $startDate = date('Y-m-d 00:00:00', strtotime($start_date)); + $endDate = date('Y-m-d 23:59:59', strtotime($end_date)); + + if ($date_type === "policy_issue_date") { + $conditions .= " AND pcsd.pt_policy_issue_date >= '$startDate' "; + $conditions .= " AND pcsd.pt_policy_issue_date <= '$endDate' "; + } else { + $conditions .= " AND pt.$date_type >= '$startDate' "; + $conditions .= " AND pt.$date_type <= '$endDate' "; + } + } + + // 4. Common filters + if ($client_id != 0) { + $conditions .= " AND pt.client_id = $client_id "; + } + + if ($insurer_id != 0) { + $conditions .= " AND pt.insurer_id = $insurer_id "; + } + + if ($client_branch_id != 0) { + $conditions .= " AND pt.client_branch_id = $client_branch_id "; + } + + if ($insurer_branch_id != 0) { + $conditions .= " AND pt.insurer_branch_id = $insurer_branch_id "; + } + + if ($client_policy_id != 0) { + $conditions .= " AND pt.client_policy_id = $client_policy_id "; + } + + if ($user_id != 0) { + $conditions .= " AND pt.created_by = $user_id "; + } + + if ($policy_type_id != 0) { + $conditions .= " AND pt.policy_type_id = $policy_type_id "; + } + + if ($issuer != 0) { + $conditions .= " AND pt.issuer = $issuer "; + } + + + $sql = " + SELECT * FROM ( + + SELECT + pt.id AS id, + pt.endorsement_no, + pt.ref, + + pt.data_received_date, + pt.renewal_date, + pt.installment, + nhance_branch.branch_name as nhance_branch, + + DATE_FORMAT(pt.policy_issue_date, '%d %b %Y') AS policy_issue_date, + DATE_FORMAT(pcsd.pt_policy_issue_date, '%b %Y') AS policy_issue_month, + pt.month as statement_month, + + 'no statement uploaded' AS statement_uploaded, + + CASE + WHEN c.client_type = 1 THEN 'Group' + WHEN c.client_type = 2 THEN 'Retail' + ELSE '-' + END AS client_type, + + CASE + WHEN pt.revenue_type = 'NA' THEN 'Fresh' + ELSE 'Renewal' + END AS revenue_type, + + CASE + WHEN pt.action_type = 'inception' THEN 'Policy' + ELSE 'Endorsement' + END AS action_type, + + pt.action_type as action_type_string, + + c.client_name, + c.short_name AS client_short_name, + cb.branch_name AS client_branch_name, + cb.address1 AS client_address, + ptype.policy_type, + ptype.bap, + ins.id AS insurer_id, + ins.name AS insurer_name, + ins.short_name AS insurer_short_name, + ib.branch_name AS insurer_branch_name, + ib.branch_code AS insurer_branch_code, + + created_user.first_name AS user_name, + v.vehicle_no, + tpa.name AS tpa_name, + + pcsd.remark AS remarks, + pcsd.cop_amt AS bp_amt, + pcsd.exp_amt, + pcsd.id AS pt_id, + + su.first_name AS salse_person_name, + se.first_name AS service_person_name, + + ROUND(pcsd.cop_amt + pcsd.cotp_amt + pcsd.cotep_amt, 2) AS premium_wo_gst, + ROUND((pcsd.cop_amt + pcsd.cotp_amt + pcsd.cotep_amt) * 0.18, 2) AS gst_amount, + ROUND((pcsd.cop_amt + pcsd.cotp_amt + pcsd.cotep_amt) * 1.18, 2) AS total_premium, + + ROUND(pcsd.cotp_amt + pcsd.cotep_amt, 2) AS tp_or_ter, + DATEDIFF(pt.policy_end_date, CURDATE()) AS days, + (pcsd.agreed_tp_per + pcsd.agreed_tep_per) AS agreed_tp_or_ter_per, + + ROUND(pcsd.exp_amt, 2) AS total_irda_amt, + 0.00 AS reward, + 0.00 AS billed_amt, + + CASE + WHEN pcsd.co_share_type IN (0,1) THEN pt.policy_no + WHEN pcsd.co_share_type > 1 THEN + IFNULL(NULLIF(pcsd.follower_policy_no,''), pt.policy_no) + ELSE pt.policy_no + END AS policy_no, + + CASE + WHEN pt.co_share = 1 THEN 'Yes' + ELSE 'No' + END AS co_share, + + CASE + WHEN pt.bro_payable_by = 1 THEN 'Yes' + ELSE 'No' + END AS bro_payable_by, + + pcsd.non_comm_per_amt, + + pcsd.bp_igst, + pcsd.bp_sgst, + pcsd.bp_cgst, + + pcsd.agreed_bp_per, + ROUND(pcsd.agreed_tp_per + pcsd.agreed_tep_per,2) AS agreed_tp_per, + + pcsd.standerd_bp_per, + ROUND(pcsd.standerd_tp_per + pcsd.standerd_tep_per,2) AS standerd_tp_per, + + 0 AS actual_bp_amt, + ROUND(0, 2) AS actual_tp_amt, + + 0 AS actual_bp_per, + ROUND(0, 2) AS actual_tp_per, + + 0 AS actual_tep_brokerage_amt, + ROUND(0, 2) AS actual_tp_brokerage_amt, + + service_branch.branch_name as service_branch, + + salse_manager.first_name as salse_manager_name, + service_manager.first_name as service_manager_name, + cd_master.cd_ac_no, + pt.rollover_date, + pt.policy_holder_name, + + CASE + WHEN pt.same_as_proposer = 1 THEN 'Yes' + ELSE 'No' + END AS same_as_proposer, + + pcsd.follower_policy_no, + pcsd.co_share_per, + pcsd.stamp_duty, + 'first' as query + + FROM policy_transaction pt + LEFT JOIN pt_co_share_details pcsd ON pt.id = pcsd.pt_id + JOIN clients c ON c.id = pt.client_id + LEFT JOIN client_branch cb ON pt.client_branch_id = cb.id + LEFT JOIN client_policy cp ON pt.client_policy_id = cp.id + LEFT JOIN user_profiles up ON pt.created_by = up.id + LEFT JOIN vehicle v ON pt.vehicle_id = v.id + LEFT JOIN policy_type ptype ON pt.policy_type_id = ptype.id + LEFT JOIN insurers ins ON pcsd.insurer_id = ins.id + LEFT JOIN insurer_branch ib ON pcsd.insurer_branch_id = ib.id + LEFT JOIN tpa ON pt.tpa_id = tpa.id + LEFT JOIN tpa_branch tb ON pt.tpa_branch_id = tb.id + LEFT JOIN user_profiles su ON pt.sales_generated_by = su.id + LEFT JOIN user_profiles se ON pt.serviced_by = se.id + LEFT JOIN user_profiles created_user ON pt.created_by = created_user.id + LEFT JOIN nhance_branch ON pt.issuer_branch = nhance_branch.id + + LEFT JOIN nhance_branch service_branch ON pt.service_person_branch_id = service_branch.id + LEFT JOIN user_profiles salse_manager ON pt.salse_person_manager_id = salse_manager.id + LEFT JOIN user_profiles service_manager ON pt.service_person_manager_id = service_manager.id + LEFT JOIN cd_master ON pt.cd_ac_pk = cd_master.id + + WHERE pt.is_active = 1 + AND pcsd.is_active = 1 + $default_date_filter + $conditions + + GROUP BY pt.policy_no, pt.endorsement_no, pcsd.insurer_id + + UNION ALL + SELECT pt.id AS id, pt.endorsement_no, @@ -2831,7 +3401,8 @@ pcsd.follower_policy_no, pcsd.co_share_per, - pcsd.stamp_duty + pcsd.stamp_duty, + 'second' as query FROM policy_transaction pt LEFT JOIN pt_co_share_details pcsd ON pt.id = pcsd.pt_id @@ -3007,7 +3578,8 @@ pcsd.follower_policy_no, pcsd.co_share_per, - pcsd.stamp_duty + pcsd.stamp_duty, + 'third' as query FROM policy_transaction pt LEFT JOIN pt_co_share_details pcsd ON pt.id = pcsd.pt_id @@ -3056,119 +3628,57 @@ "; $query = $this->db->query($sql); $result = $query->getResultArray(); + // $countofalldata = count($result); // dd($result); // dd($this->db->getLastQuery()); + $keys = []; + $filtered = []; - foreach ($result as $key => &$row) { + foreach ($result as $row) { - // If both rewards and billed amount are zero, remove the row - if ( - ($row['reward'] ?? 0) == 0.00 && - ($row['billed_amt'] ?? 0) == 0.00 - ) { - unset($result[$key]); // ✅ correct way + // Normalize endorsement number + $endorsement_number = !empty($row['endorsement_no']) ? $row['endorsement_no'] : '-'; + + $reward = (float) ($row['reward'] ?? 0); + $billed_amt = (float) ($row['billed_amt'] ?? 0); + + if($reward == 0.00 && $billed_amt == 0.00 && $row['statement_uploaded'] === 'statement uploaded'){ + continue; } - // If rewards exist, zero the IRDA amount - // if (($row['reward'] ?? 0) != 0.00) { - // $row['total_irda_amt'] = '0.00'; - // $row['billed_amt'] = $row['reward']; - // } - - $reward = (float) ($row['reward'] ?? 0); - - if ($reward > 0) { - $row['total_irda_amt'] = '0.00'; - $row['billed_amt'] = $reward; + if ($reward > 0 && ($row['billed_amt'] ?? 0) == 0.00) { + $row['total_irda_amt'] = '0.00'; + $row['billed_amt'] = $reward; + $rewardFlag = 'R'; // Reward row + } else { + $rewardFlag = 'N'; // Normal row } + // ✅ Stable key (NO reward flag) + $key = implode('|', [ + $row['statement_month'], + $row['insurer_name'], + $row['policy_no'], + $endorsement_number, + $rewardFlag + ]); + + // Prefer "statement uploaded" + if ($row['statement_uploaded'] === 'statement uploaded') { + $filtered[$key] = $row; + $keys[$key] = true; + } + // Keep no-statement only if uploaded not present + elseif (!isset($keys[$key])) { + $filtered[$key] = $row; + } } - unset($row); - - // $result = array_values($result); - usort($result, function ($a, $b) { + // Reindex final output + $result = array_values($filtered); - // First: group by policy_issue_date - if ($a['policy_issue_month'] === $b['policy_issue_month']) { - - // Priority order for action_type - $priority = [ - 'Policy' => 1, - 'Endorsement' => 2, - 'Rewards' => 3 - ]; - - $aPriority = $priority[$a['action_type']] ?? 99; - $bPriority = $priority[$b['action_type']] ?? 99; - - return $aPriority <=> $bPriority; - } - - // Otherwise sort by policy_issue_date - return strtotime($a['policy_issue_month']) <=> strtotime($b['policy_issue_month']); - }); - - // dd($result); - - // -------------------------------------------------------------------------------------------------------- - - // $keys = []; - // $filtered = []; - - // foreach ($result as $row) { - - // $endorsement_number = "-"; - // if(!empty($row['endorsement_no'])){ - // $endorsement_number = $row['endorsement_no']; - // } - - // $key = $row['statement_month'].'|'.$row['insurer_name'].'|'.$row['policy_no'] . '|' . $endorsement_number; - - // // If uploaded record exists, always keep it and override previous - // if ($row['statement_uploaded'] === 'statement uploaded') { - // $filtered[$key] = $row; // overwrite no-statement row if it exists - // $keys[$key] = true; - - // } - // // Keep "no statement uploaded" only if uploaded one not added yet - // elseif (!isset($keys[$key])) { - // $filtered[$key] = $row; - // } - // } - - // $result = array_values($filtered); - // dd($result); - - // -------------------------------------------------------------------------------------------------------- - - - // $runningBilled = []; - // $totalIrdaMap = []; - // $final = []; - - // foreach ($result as $row) { - // $ptId = $row['pt_id']; - - // // Store total_irda_amt only once (first non-zero value) - // if (!isset($totalIrdaMap[$ptId]) && $row['total_irda_amt'] > 0) { - // $totalIrdaMap[$ptId] = $row['total_irda_amt']; - // } - - // // Initialize running sum - // if (!isset($runningBilled[$ptId])) { - // $runningBilled[$ptId] = 0; - // } - - // // Add billed amount to running total - // $runningBilled[$ptId] += (float)$row['billed_amt']; - - // // Calculate unbilled amount - // $row['unbilled_amount'] = ($totalIrdaMap[$ptId] ?? 0) - $runningBilled[$ptId]; - - // $final[] = $row; - // } + // dd($countofalldata, $result); // -------------------------------------------------------------------------------------------------------- @@ -3179,17 +3689,19 @@ $key = $row['pt_id'].'-'.$row['insurer_id']; // Sum billed amount - $totalBilled[$key] = ($totalBilled[$key] ?? 0) - + (float) ($row['billed_amt'] ?? 0); + $totalBilled[$key] = ($totalBilled[$key] ?? 0) + (float) ($row['billed_amt'] ?? 0); // Store total_irda_amt once if (!isset($totalIrdaMap[$key]) && ($row['total_irda_amt'] ?? 0) > 0) { $totalIrdaMap[$key] = (float) $row['total_irda_amt']; } + + if(($row['reward'] ?? 0) > 0){ + $totalIrdaMap[$key] = ($totalIrdaMap[$key] ?? 0) + (float) $row['reward']; + } } - // dd($totalBilled, $totalIrdaMap); - + // dd($totalIrdaMap); $ptSeen = []; $final = []; diff --git a/app/Views/faq_list.php b/app/Views/faq_list.php index 394034d9..e725b7e3 100644 --- a/app/Views/faq_list.php +++ b/app/Views/faq_list.php @@ -92,6 +92,10 @@