diff --git a/app/Config/Autoload.php b/app/Config/Autoload.php index a1a4356c..be0e2476 100755 --- a/app/Config/Autoload.php +++ b/app/Config/Autoload.php @@ -100,5 +100,7 @@ class Autoload extends AutoloadConfig * @var string[] * @phpstan-var list */ - public $helpers = ['uuid','session','utility', 'form', 'url', 'oauth', 'fileupload', 'excel_import_export', 'file', 'drive','ExcelSanitizeHelper', 'api_helper']; + public $helpers = ['uuid','session','utility', 'form', 'url', 'oauth', 'fileupload', + 'excel_import_export', 'file', 'drive','ExcelSanitizeHelper', 'api_helper','exception' +]; } diff --git a/app/Config/Routes.php b/app/Config/Routes.php index c217dd5b..a9cd0ae2 100755 --- a/app/Config/Routes.php +++ b/app/Config/Routes.php @@ -329,6 +329,7 @@ $routes->group("/util", ["filter" => "authMVC"], function ($routes) { $routes->get("getCDAccNoByClientAndInsurer/(:any)", "ClientController::getCDAccNoByClientAndInsurer/$1"); $routes->post("createClientWithMinimalData", "ClientController::createClientWithMinimalData"); $routes->post("createVehicleWithMinimalData", "ClientController::createVehicleWithMinimalData"); + $routes->post("createVehicleWithMinimalDataForBDS", "ClientController::createVehicleWithMinimalDataForBDS"); $routes->post("createClientBranchWithMinamalData", "ClientController::createClientBranchWithMinamalData"); $routes->post("createClientPolicyWithMinimalData", "ClientController::createClientPolicyWithMinimalData"); $routes->post("createCDAccountNumberUsingAjax", "MasterController::createCDAccountNumberUsingAjax"); @@ -690,6 +691,7 @@ $routes->group('test', function($routes) { $routes->get('generatePDF', 'TestingController::generatePDF'); $routes->get('viewPDF', 'TestingController::viewPDF'); $routes->get('generate-pdf-view', 'TestingController::generatePDFWithView'); + $routes->get('param/(:any)', 'TestingController::ptedfitdata/$1'); }); $routes->cli('cli/testcli', 'TestingController::testcli'); diff --git a/app/Controllers/ClientController.php b/app/Controllers/ClientController.php index 2e9e11c9..164bee10 100755 --- a/app/Controllers/ClientController.php +++ b/app/Controllers/ClientController.php @@ -999,31 +999,52 @@ class ClientController extends AdminController $data['client_id'] = $this->request->getPost('client_id'); $data['updated_by'] = get_session_userid(); $inserted = false; + // print_r($this->request->getPost()); die; if ($this->request->getPost('head')) { + $data['user_id'] = $this->request->getPost('head'); - $checkHead = $this->clientRMModel->checkExistenceOfClientRelation($id, $this->request->getPost('head'), 1); - if ($checkHead) { - $inserted = $this->clientRMModel->where('client_id', $id)->where('level', 1)->set($data)->update(); - } else { - $data['level'] = "1"; - $data['user_id'] = $this->request->getPost('head'); - $inserted = $this->clientRMModel->insert($data); - } + $this->clientRMModel->where('client_id', $id)->where('level', 1)->delete(); + + $data['level'] = "1"; + $data['user_id'] = $this->request->getPost('head'); + $inserted = $this->clientRMModel->insert($data); } if ($this->request->getPost('manager')) { + $data['user_id'] = $this->request->getPost('manager'); - $checkHead = $this->clientRMModel->checkExistenceOfClientRelation($id, $this->request->getPost('manager'), 2); - if ($checkHead) { - $inserted = $this->clientRMModel->where('client_id', $id)->where('level', 2)->set($data)->update(); - } else { - $data['level'] = "2"; - $data['user_id'] = $this->request->getPost('manager'); - $inserted = $this->clientRMModel->insert($data); - } + $this->clientRMModel->where('client_id', $id)->where('level', 2)->delete(); + + $data['level'] = "2"; + $data['user_id'] = $this->request->getPost('manager'); + $inserted = $this->clientRMModel->insert($data); } + // if ($this->request->getPost('head')) { + // $data['user_id'] = $this->request->getPost('head'); + // $checkHead = $this->clientRMModel->checkExistenceOfClientRelation($id, $this->request->getPost('head'), 1); + // if ($checkHead) { + // $inserted = $this->clientRMModel->where('client_id', $id)->where('level', 1)->set($data)->update(); + // } else { + // $data['level'] = "1"; + // $data['user_id'] = $this->request->getPost('head'); + // $inserted = $this->clientRMModel->insert($data); + // } + // } + + // if ($this->request->getPost('manager')) { + // $data['user_id'] = $this->request->getPost('manager'); + // $checkHead = $this->clientRMModel->checkExistenceOfClientRelation($id, $this->request->getPost('manager'), 2); + // if ($checkHead) { + // $inserted = $this->clientRMModel->where('client_id', $id)->where('level', 2)->set($data)->update(); + // } else { + // $data['level'] = "2"; + // $data['user_id'] = $this->request->getPost('manager'); + // $inserted = $this->clientRMModel->insert($data); + // } + // } + if ($this->request->getPost('account_manager')) { $this->clientRMModel->where('client_id', $id)->where('level', 3)->delete(); @@ -1517,7 +1538,7 @@ class ClientController extends AdminController - + // Save Rack Rate function public function createClientPolicyPremium() { @@ -4422,7 +4443,9 @@ class ClientController extends AdminController // } // } - public function createClientWithMinimalData() + // ------------- CLIENT AND VEHICLE ------------------------------------------------------------------------------------------------ + + public function createClientWithMinimalData2() { $postData = $this->request->getPost(); // print_r($postData); die; @@ -4474,7 +4497,6 @@ class ClientController extends AdminController 'name' => $postData['name'], 'mobile' => $postData['mobile'], 'email' => $postData['email'], - ]; $this->levelContactModel->insert($contact_data); } @@ -4489,6 +4511,89 @@ class ClientController extends AdminController ], 200); } + public function createClientWithMinimalData() + { + $postData = $this->request->getPost(); + + // print_r($postData); die; + $client_type = $postData['client_type'] ?? null; + + $client_insert = null; + if($client_type == 2){ + + $client_data = [ + 'client_type' => $postData['client_type'], + 'client_name' => $postData['client_name'], + 'email' => $postData['short_name'] ?? $postData['client_name'], + 'phone' => $postData['mobile'], + 'client_code' => generate_client_code() + ]; + + $client_insert = $this->clientModel->insert($client_data); + + }else if($client_type == 1){ + + $client_data = [ + 'client_type' => $postData['client_type'], + 'client_name' => $postData['client_name'], + 'short_name' => $postData['short_name'] ?? $postData['client_name'], + 'client_code' => generate_client_code(), + 'entity_type_id' => 2 + ]; + + $client_insert = $this->clientModel->insert($client_data); + } + + if (!$client_insert) { + return $this->respond(['status' => false, 'message' => 'Failed to create client'], 200); + } + + // Additional logic for non-individual clients (client_type != 2) + $branch_insert = null; + if ($client_type != 2) { + $unit[] = $postData['short_name'] . '-' . 001; + $branch_data = [ + 'client_id' => $client_insert, + 'branch_name' => $postData['branch_name'], + 'branch_code' => 001, + 'gst' => $postData['gst'], + 'units' => json_encode($unit) ?? null, + ]; + + $branch_insert = $this->clientBranchModel->insert($branch_data); + if ($branch_insert) { + $contact_data = [ + 'ref_id' => $branch_insert, + 'contact_type' => 'client', + 'name' => $postData['name'], + 'email' => $postData['email'], + ]; + $this->levelContactModel->insert($contact_data); + } + } + + $clients = $this->clientModel + ->select("*, DATE_FORMAT(dob, '%d-%m-%Y') as dob") + ->where('is_active', 1) + ->findAll(); + + // Fetch branches in a single query + $branches = $this->clientBranchModel + ->where('client_id', $client_insert) + ->where('is_active', 1) + ->findAll(); + + return $this->respond([ + 'status' => true, + 'data' => $postData, + 'client_id' => $client_insert, + 'branch_id' => $branch_insert ?? null, + 'clients' => $clients, + 'branches' => $branches, + 'message' => 'Client created successfully' + ], 200); + } + public function createVehicleWithMinimalData() { $data = $this->request->getPost(); @@ -4508,7 +4613,13 @@ class ClientController extends AdminController $vehicle_insert = $this->vehicleModel->insert($data); if ($vehicle_insert) { - $vehicles = $this->vehicleModel->where('is_active', 1)->findAll(); + + // $vehicles = $this->vehicleModel->where('is_active', 1)->findAll(); + $vehicles = $this->vehicleModel->select('vehicle.*, clients.client_type') + ->join('clients', 'clients.id=vehicle.owner') + ->where('vehicle.is_active', 1) + ->findAll(); + return $this->respond([ 'status' => true, 'vehicle_id' => $vehicle_insert, @@ -4525,6 +4636,160 @@ class ClientController extends AdminController } } + public function createVehicleWithMinimalDataForBDS() + { + $data = $this->request->getPost(); + // print_r($data); die; + if (isset($data['client_name']) && !empty($data['client_name'])) { + + $client_type = $data['client_type'] ?? null; + + $client_insert = null; + if ($client_type == 2) { + + $client_data = [ + 'client_type' => $data['client_type'], + 'client_name' => $data['client_name'], + 'email' => $data['short_name'] ?? $data['client_name'], + 'phone' => $data['mobile'], + 'client_code' => generate_client_code() + ]; + + $client_insert = $this->clientModel->insert($client_data); + + } else if ($client_type == 1) { + + $client_data = [ + 'client_type' => $data['client_type'], + 'client_name' => $data['client_name'], + 'short_name' => $data['short_name'] ?? $data['client_name'], + 'client_code' => generate_client_code(), + 'entity_type_id' => 2 + ]; + + $client_insert = $this->clientModel->insert($client_data); + } + + // Additional logic for non-individual clients (client_type != 2) + $branch_insert = null; + if ($client_type != 2) { + $unit[] = $data['short_name'] . '-' . 001; + $branch_data = [ + 'client_id' => $client_insert, + 'branch_name' => $data['branch_name'], + 'branch_code' => 001, + 'gst' => $data['gst'], + 'units' => json_encode($unit) ?? null, + ]; + + $branch_insert = $this->clientBranchModel->insert($branch_data); + if ($branch_insert) { + $contact_data = [ + 'ref_id' => $branch_insert, + 'contact_type' => 'client', + 'name' => $data['name'], + 'email' => $data['email'], + ]; + $this->levelContactModel->insert($contact_data); + } + } + + $vehicle_data = [ + 'vehicle_no' => $data['vehicle_no'], + 'type' => $data['type'], + 'rc' => $data['rc'], + 'branch_id' => $branch_insert, + 'owner' => $client_insert, + ]; + + $vehicle_insert = $this->vehicleModel->insert($vehicle_data); + + if ($vehicle_insert) { + + // $vehicles = $this->vehicleModel->where('is_active', 1)->findAll(); + $vehicles = $this->vehicleModel->select('vehicle.*, clients.client_type') + ->join('clients', 'clients.id = vehicle.owner') + ->where('vehicle.is_active', 1) + ->findAll(); + + $clients = $this->clientModel + ->select("*, DATE_FORMAT(dob, '%d-%m-%Y') as dob") + ->where('is_active', 1) + ->findAll(); + + // Fetch branches in a single query + $branches = $this->clientBranchModel + ->where('client_id', $client_insert) + ->where('is_active', 1) + ->findAll(); + + return $this->respond([ + 'status' => true, + 'vehicle_id' => $vehicle_insert, + 'client_id' => $client_insert, + 'branch_id' => $branch_insert, + 'data' => $data, + 'clients' => $clients, + 'branches' => $branches, + 'vehicles' => $vehicles, + 'message' => 'Vehicle created successfully' + ], 200); + + } else { + return $this->respond(['status' => false, 'message' => 'Failed to created vehicle'], 200); + } + + } else if (isset($data['owner']) && !empty($data['owner'])) { + + $vehicle_data = [ + 'vehicle_no' => $data['vehicle_no'], + 'type' => $data['type'], + 'rc' => $data['rc'], + 'branch_id' => $data['branch_id'] ?? null, + 'owner' => $data['owner'], + ]; + + $vehicle_insert = $this->vehicleModel->insert($vehicle_data); + + $vehicles = $this->vehicleModel->select('vehicle.*, clients.client_type') + ->join('clients', 'clients.id = vehicle.owner') + ->where('vehicle.is_active', 1) + ->findAll(); + + $clients = $this->clientModel + ->select("*, DATE_FORMAT(dob, '%d-%m-%Y') as dob") + ->where('is_active', 1) + ->findAll(); + + // Fetch branches in a single query + $branches = $this->clientBranchModel + ->where('client_id', $data['owner']) + ->where('is_active', 1) + ->findAll(); + + if ($vehicle_insert) { + + return $this->respond([ + 'status' => true, + 'vehicle_id' => $vehicle_insert, + 'client_id' => $data['owner'], + 'branch_id' => $data['branch_id'], + 'data' => $data, + 'clients' => $clients, + 'branches' => $branches, + 'vehicles' => $vehicles, + 'message' => 'Vehicle created successfully' + ], 200); + + } else { + return $this->respond(['status' => false, 'message' => 'Failed to created vehicle'], 200); + } + } else { + + return $this->respond(['status' => false, 'message' => 'Failed to created vehicle'], 200); + } + } + public function createClientPolicyWithMinimalData() { $data = $this->request->getPost(); @@ -4560,6 +4825,9 @@ class ClientController extends AdminController } } + // ------------- CLIENT AND VEHICLE ------------------------------------------------------------------------------------------------ + + public function getPolicyDetailsByPolicyId($id) { $policies = $this->clientPolicyModel @@ -4604,6 +4872,68 @@ class ClientController extends AdminController } } + // public function get_client_policy_data_using_policy_no() + // { + // $received_data = $this->request->getGet(); + // $policy_no = $this->request->getGet('policy_no'); + // $client_id = $this->request->getGet('client_id'); + // $client_branch_id = $this->request->getGet('client_branch_id'); + // $policy_type_id = $this->request->getGet('policy_type_id'); + // $client_type = $this->request->getGet('client_type'); + + // $data = $this->clientPolicyModel + // ->select(" + // client_policy.*, + // policy_type.policy_type, + // clients.client_type, + // clients.client_name, + // DATE_FORMAT(client_policy.policy_start_date, '%d/%m/%Y') as policy_start_date, + // DATE_FORMAT(client_policy.policy_end_date, '%d/%m/%Y') as policy_end_date + // ") + // ->join('clients', 'client_policy.client_id = clients.id') + // ->join('policy_type', 'client_policy.policy_type_id = policy_type.id') + // ->where('client_policy.policy_no', $policy_no) + // ->where('client_policy.is_active', 1) + // ->where('client_policy.policy_status', 1) + // ->first(); + + // if ($data) { + + // if ($client_type == 1) { + // if ($data['client_id'] == $client_id && $data['client_branch_id'] == $client_branch_id) { + + // if ($data['policy_type_id'] == $policy_type_id) { + // return $this->respond(['status' => true, 'data' => $data, 'code' => 200, 'received_data' => $received_data], 200); + // } else { + // $policy_type = $this->policyTypeModel->where('id', $policy_type_id)->first(); + // $message = 'This policy number is mapped to the selected client with policy type: ' . (!empty($data['policy_type']) ? $data['policy_type'] : 'N/A') . '. You selected: ' . (!empty($policy_type['policy_type']) ? $policy_type['policy_type'] : 'N/A') . '. Please check.'; + // return $this->respond(['status' => true, 'data' => $data, 'code' => 409, "message" => $message, 'received_data' => $received_data], 200); + // } + // } else { + // $message = 'This policy number is already linked to another client' . (!empty($data['client_name']) ? '. Client name : ' . $data['client_name'] : '') . '. Please check'; + // return $this->respond(['status' => true, 'code' => 409, "message" => $message, 'received_data' => $received_data, 'db_data' => $data], 200); + // } + // } else { + // if ($data['client_id'] == $client_id) { + + // if ($data['policy_type_id'] == $policy_type_id) { + // return $this->respond(['status' => true, 'data' => $data, 'code' => 200, 'received_data' => $received_data], 200); + // } else { + // $policy_type = $this->policyTypeModel->where('id', $policy_type_id)->first(); + // $message = 'This policy number is mapped to the selected client with policy type: ' . (!empty($data['policy_type']) ? $data['policy_type'] : 'N/A') . '. You selected: ' . (!empty($policy_type['policy_type']) ? $policy_type['policy_type'] : 'N/A') . '. Please check.'; + // return $this->respond(['status' => true, 'data' => $data, 'code' => 409, "message" => $message, 'received_data' => $received_data], 200); + // } + // } else { + // $message = 'This policy number is already linked to another client' . (!empty($data['client_name']) ? '. Client name : ' . $data['client_name'] : '') . '. Please check'; + // return $this->respond(['status' => true, 'code' => 409, "message" => $message, 'received_data' => $received_data, 'db_data' => $data], 200); + // } + // } + + // } else { + // return $this->respond(['status' => false, 'message' => 'No Data Found', 'code' => 404, 'received_data' => $received_data], 200); + // } + // } + public function get_client_policy_data_using_policy_no() { $received_data = $this->request->getGet(); @@ -4613,54 +4943,14 @@ class ClientController extends AdminController $policy_type_id = $this->request->getGet('policy_type_id'); $client_type = $this->request->getGet('client_type'); - $data = $this->clientPolicyModel - ->select(" - client_policy.*, - policy_type.policy_type, - clients.client_type, - clients.client_name, - DATE_FORMAT(client_policy.policy_start_date, '%d/%m/%Y') as policy_start_date, - DATE_FORMAT(client_policy.policy_end_date, '%d/%m/%Y') as policy_end_date - ") - ->join('clients', 'client_policy.client_id = clients.id') - ->join('policy_type', 'client_policy.policy_type_id = policy_type.id') - ->where('client_policy.policy_no', $policy_no) - ->where('client_policy.is_active', 1) - ->where('client_policy.policy_status', 1) - ->first(); + $data = $this->policyTransactionModel + ->where('is_active', 1) + ->where('action_type', 'inception') + ->where('policy_no', $policy_no) + ->countAllResults(); - if ($data) { - - if ($client_type == 1) { - if ($data['client_id'] == $client_id && $data['client_branch_id'] == $client_branch_id) { - - if ($data['policy_type_id'] == $policy_type_id) { - return $this->respond(['status' => true, 'data' => $data, 'code' => 200, 'received_data' => $received_data], 200); - } else { - $policy_type = $this->policyTypeModel->where('id', $policy_type_id)->first(); - $message = 'This policy number is mapped to the selected client with policy type: ' . (!empty($data['policy_type']) ? $data['policy_type'] : 'N/A') . '. You selected: ' . (!empty($policy_type['policy_type']) ? $policy_type['policy_type'] : 'N/A') . '. Please check.'; - return $this->respond(['status' => true, 'data' => $data, 'code' => 409, "message" => $message, 'received_data' => $received_data], 200); - } - } else { - $message = 'This policy number is already linked to another client' . (!empty($data['client_name']) ? '. Client name : ' . $data['client_name'] : '') . '. Please check'; - return $this->respond(['status' => true, 'code' => 409, "message" => $message, 'received_data' => $received_data, 'db_data' => $data], 200); - } - } else { - if ($data['client_id'] == $client_id) { - - if ($data['policy_type_id'] == $policy_type_id) { - return $this->respond(['status' => true, 'data' => $data, 'code' => 200, 'received_data' => $received_data], 200); - } else { - $policy_type = $this->policyTypeModel->where('id', $policy_type_id)->first(); - $message = 'This policy number is mapped to the selected client with policy type: ' . (!empty($data['policy_type']) ? $data['policy_type'] : 'N/A') . '. You selected: ' . (!empty($policy_type['policy_type']) ? $policy_type['policy_type'] : 'N/A') . '. Please check.'; - return $this->respond(['status' => true, 'data' => $data, 'code' => 409, "message" => $message, 'received_data' => $received_data], 200); - } - } else { - $message = 'This policy number is already linked to another client' . (!empty($data['client_name']) ? '. Client name : ' . $data['client_name'] : '') . '. Please check'; - return $this->respond(['status' => true, 'code' => 409, "message" => $message, 'received_data' => $received_data, 'db_data' => $data], 200); - } - } - + if ($data > 0) { + return $this->respond(['status' => true, 'message' => 'This policy number is already linked to another client', 'data' => $data, 'code' => 409, 'received_data' => $received_data], 200); } else { return $this->respond(['status' => false, 'message' => 'No Data Found', 'code' => 404, 'received_data' => $received_data], 200); } @@ -5259,15 +5549,15 @@ class ClientController extends AdminController // ---------- EMP SERVICE CONTROLLER -------------------------------------------------------------------------------- $empServiceController = new EmployeeServiceController(); - // $res = $empServiceController->excelFileFormatValidation(['file_id' => '865']); + $res = $empServiceController->excelFileFormatValidation(['file_id' => '2055']); // $res = $empServiceController->excelFileDataValidation(['file_id' => '865']); // $res = $empServiceController->employeesOnboardPreprocess(['file_id' => 726]); // $res = $empServiceController->employeesOnboardProcess(['file_id' => 835]); // $res = $empServiceController->employeesEnrollmentInsert(['file_id' => 836]); // $res = $empServiceController->employeesSIEnhanceProcess(['file_id' => '978']); // $res = $empServiceController->employeeDisembark(['file_id' => '1681']); - // $res = $empServiceController->employeesCorrectionProcess(['file_id' => '1681']); - // dd( $res); + // $res = $empServiceController->employeesCorrectionProcess(['file_id' => '2033']); + dd( $res); $EmployeeMultiEventServiceController = new EmployeeMultiEventServiceController(); // $res = $EmployeeMultiEventServiceController->constructMultiEventData(['file_id' => '1069']); @@ -5324,6 +5614,7 @@ class ClientController extends AdminController $EmpDataServiceController = new EmpDataServiceController(); // $res = $EmpDataServiceController->generateExcelForDeletion($batch_data); dd($return); die; // $res = $EmpDataServiceController->generateExcelForSIEnhancement($batch_data); die; + // $res = $EmpDataServiceController->generateExcelForCorrection($batch_data); // $res = $EmpDataServiceController->importInceptionFileValidation(['file_id' => 1932]); die; // $res = $EmpDataServiceController->importDeletionValidation(['file_id' => 304]); //for live // $res = $EmpDataServiceController->importSIEnhancementUpdateEndorsementID(['file_id' => 1199]); //for live diff --git a/app/Controllers/EmpDataServiceController.php b/app/Controllers/EmpDataServiceController.php index 1aec089e..1c9fac18 100755 --- a/app/Controllers/EmpDataServiceController.php +++ b/app/Controllers/EmpDataServiceController.php @@ -2020,7 +2020,16 @@ class EmpDataServiceController extends BaseController // dd($emp_endorsement_table_data, $enrollment_file_id, $no_of_insured, $no_of_dependent); //update the employee policy data (TPAID or UHID) - $return = $this->employeePolicyModel->bulkUpdate($emp_details); + if(!empty($emp_details)){ + $return = $this->employeePolicyModel->bulkUpdate($emp_details); + }else{ + $this->batchFileModel->update($file_id, [ + 'count' => 0, + 'status' => "failed-6", + 'amount' => 0, + ]); + return ['status' => 'error', 'message' => 'There is no data to update']; // Return error code + } if(in_array($file['event_type'], ['addition', 'dependent_addition']) && !empty($emp_endorsement_table_data)){ $this->employeePolicyModel->updateEmpEndorsementAddition($emp_endorsement_table_data); @@ -2048,7 +2057,6 @@ class EmpDataServiceController extends BaseController $this->storeEndorsementNumber($file_id, $endorsement_id, $enrollment_file_id); } - $this->myLogger->logme('error', 'Inception Update TPA and UHID -- set cashDepositCalculationForInception and sendMailForDownloadingECard in JOB QUEUE'); $policy_name = $this->getPolicyNameUsingClientPolicyId($client_policy_id); @@ -2078,18 +2086,18 @@ class EmpDataServiceController extends BaseController 'user_id' => $user_id, ]]); - $r = Jobs::addJob(['job_name' => 'makeEntryForBDSPolicyTransaction', 'payload' => [ - 'client_policy_id' => $client_policy_id ?? null, - 'endorsement_no' => $endorsement_id ?? null, - 'emp_count' => $emp_count ?? null, - 'action_type' => $file['event_type'] ?? null, - 'no_of_insured' => count($no_of_insured ?? []) ?? null, - 'no_of_dependent' => count($no_of_dependent ?? []) ?? null, - 'base_premium' => $base_bremium_and_gst['base_premium'] ?? null, - 'gst' => $base_bremium_and_gst['gst'] ?? null, - 'policy_issue_date' => $policy_issue_date ?? null, - 'created_by' => $file['created_by'] ?? null, - ]]); + // $r = Jobs::addJob(['job_name' => 'makeEntryForBDSPolicyTransaction', 'payload' => [ + // 'client_policy_id' => $client_policy_id ?? null, + // 'endorsement_no' => $endorsement_id ?? null, + // 'emp_count' => $emp_count ?? null, + // 'action_type' => $file['event_type'] ?? null, + // 'no_of_insured' => count($no_of_insured ?? []) ?? null, + // 'no_of_dependent' => count($no_of_dependent ?? []) ?? null, + // 'base_premium' => $base_bremium_and_gst['base_premium'] ?? null, + // 'gst' => $base_bremium_and_gst['gst'] ?? null, + // 'policy_issue_date' => $policy_issue_date ?? null, + // 'created_by' => $file['created_by'] ?? null, + // ]]); // $this->cashDepositCalculationForInception($depositeData); // $this->sendMailForDownloadingECard($emp_policy_ids); @@ -2518,14 +2526,14 @@ class EmpDataServiceController extends BaseController $file_data = $this->getDataByFileId($file_id, 'success'); $this->setPullNotification($file_data); - $r = Jobs::addJob(['job_name' => 'makeEntryForBDSPolicyTransaction', 'payload' => [ - 'client_policy_id' => $client_policy_id ?? null, - 'endorsement_no' => $endorsement_id[0] ?? null, - 'emp_count' => $emp_count ?? null, - 'action_type' => $file['event_type'] ?? null, - 'policy_issue_date' => $policy_issue_date ?? null, - 'created_by' => $file['created_by'] ?? null, - ]]); + // $r = Jobs::addJob(['job_name' => 'makeEntryForBDSPolicyTransaction', 'payload' => [ + // 'client_policy_id' => $client_policy_id ?? null, + // 'endorsement_no' => $endorsement_id[0] ?? null, + // 'emp_count' => $emp_count ?? null, + // 'action_type' => $file['event_type'] ?? null, + // 'policy_issue_date' => $policy_issue_date ?? null, + // 'created_by' => $file['created_by'] ?? null, + // ]]); //import file to upload Google Drive @@ -3177,18 +3185,18 @@ class EmpDataServiceController extends BaseController 'user_id' => $user_id, ]]); - $r = Jobs::addJob(['job_name' => 'makeEntryForBDSPolicyTransaction', 'payload' => [ - 'client_policy_id' => $client_policy_id ?? null, - 'endorsement_no' => $endorsement_id ?? null, - 'emp_count' => $emp_count ?? null, - 'action_type' => $file['event_type'] ?? null, - 'no_of_insured' => count($no_of_insured ?? []) ?? null, - 'no_of_dependent' => count($no_of_dependent ?? []) ?? null, - 'base_premium' => $base_bremium_and_gst['base_premium'] ?? null, - 'gst' => $base_bremium_and_gst['gst'] ?? null, - 'policy_issue_date' => $policy_issue_date ?? null, - 'created_by' => $file['created_by'] ?? null, - ]]); + // $r = Jobs::addJob(['job_name' => 'makeEntryForBDSPolicyTransaction', 'payload' => [ + // 'client_policy_id' => $client_policy_id ?? null, + // 'endorsement_no' => $endorsement_id ?? null, + // 'emp_count' => $emp_count ?? null, + // 'action_type' => $file['event_type'] ?? null, + // 'no_of_insured' => count($no_of_insured ?? []) ?? null, + // 'no_of_dependent' => count($no_of_dependent ?? []) ?? null, + // 'base_premium' => $base_bremium_and_gst['base_premium'] ?? null, + // 'gst' => $base_bremium_and_gst['gst'] ?? null, + // 'policy_issue_date' => $policy_issue_date ?? null, + // 'created_by' => $file['created_by'] ?? null, + // ]]); } @@ -3688,18 +3696,18 @@ class EmpDataServiceController extends BaseController 'user_id' => $user_id, ]]); - $r = Jobs::addJob(['job_name' => 'makeEntryForBDSPolicyTransaction', 'payload' => [ - 'client_policy_id' => $client_policy_id ?? null, - 'endorsement_no' => $endorsement_id ?? null, - 'emp_count' => $emp_count ?? null, - 'action_type' => $file['event_type'] ?? null, - 'no_of_insured' => count($no_of_insured ?? []) ?? null, - 'no_of_dependent' => count($no_of_dependent ?? []) ?? null, - 'base_premium' => $base_bremium_and_gst['base_premium'] ?? null, - 'gst' => $base_bremium_and_gst['gst'] ?? null, - 'policy_issue_date' => $policy_issue_date ?? null, - 'created_by' => $file['created_by'] ?? null, - ]]); + // $r = Jobs::addJob(['job_name' => 'makeEntryForBDSPolicyTransaction', 'payload' => [ + // 'client_policy_id' => $client_policy_id ?? null, + // 'endorsement_no' => $endorsement_id ?? null, + // 'emp_count' => $emp_count ?? null, + // 'action_type' => $file['event_type'] ?? null, + // 'no_of_insured' => count($no_of_insured ?? []) ?? null, + // 'no_of_dependent' => count($no_of_dependent ?? []) ?? null, + // 'base_premium' => $base_bremium_and_gst['base_premium'] ?? null, + // 'gst' => $base_bremium_and_gst['gst'] ?? null, + // 'policy_issue_date' => $policy_issue_date ?? null, + // 'created_by' => $file['created_by'] ?? null, + // ]]); } $file_data = $this->getDataByFileId($file_id, 'success'); diff --git a/app/Controllers/EmployeeController.php b/app/Controllers/EmployeeController.php index b97bd1b0..3751da86 100755 --- a/app/Controllers/EmployeeController.php +++ b/app/Controllers/EmployeeController.php @@ -526,7 +526,7 @@ class EmployeeController extends AdminController $client_branch_id = $this->request->getPost('client_branch_id'); $insurer_or_tpa = $this->request->getPost('insurer_or_tpa'); $actions = $this->request->getPost('action_type'); - $policy_issue_date = $this->request->getPost('policy_issue_date'); + $policy_issue_date = $this->request->getPost('policy_issue_date') ?? null; $client_data = $this->clientPolicyModel->getCliendDataForExcelFileName($client_policy_id); $file_name = generate_filename($client_data['short_name'], $event_type, $actions, $insurer_or_tpa, $client_data['policy_type'], $client_data['branch_code']); @@ -544,9 +544,7 @@ class EmployeeController extends AdminController ]; - $batch_data['policy_issue_date'] = (!empty($policy_issue_date) && strtotime($policy_issue_date) !== false) - ? change_date_format($policy_issue_date) - : null; + $batch_data['policy_issue_date'] = (!empty($policy_issue_date) && strtotime($policy_issue_date) !== false) ? change_date_format($policy_issue_date) : null; if ($actions == 'export') { diff --git a/app/Controllers/EmployeeMultiEventServiceController.php b/app/Controllers/EmployeeMultiEventServiceController.php index a7519fea..e3027d01 100644 --- a/app/Controllers/EmployeeMultiEventServiceController.php +++ b/app/Controllers/EmployeeMultiEventServiceController.php @@ -1956,14 +1956,29 @@ class EmployeeMultiEventServiceController extends BaseController $field_value = ($field_name == 'dob' ? change_date_format($row[4], 'd-M-Y', 'Y-m-d') : $row[4]); + // $employee = $this->employeeModel + // ->where('emp_code', $row[1]) + // ->where('name', $row[2]) + // ->where('client_id', $file['client_id']) + // ->where('client_branch_id', $file['client_branch_id']) + // ->where('emp_status', 'active') + // ->where('is_active', 1) + // ->first(); + $employee = $this->employeeModel - ->where('emp_code', $row[1]) - ->where('name', $row[2]) - ->where('client_id', $file['client_id']) - ->where('client_branch_id', $file['client_branch_id']) - ->where('emp_status', 'active') - ->where('is_active', 1) - ->first(); + ->select('employees.*') + ->join('employee_polices', 'employees.id = employee_polices.employee_id') + ->where('employees.emp_code', $row[1]) + ->where('employees.name',$row[2]) + ->where('employees.client_id',$file['client_id']) + ->where('employees.client_branch_id',$file['client_branch_id']) + ->where('employee_polices.client_policy_id',$file['policy_id']) + ->where('employees.emp_status','active') + ->where('employees.is_active',1) + ->where('employee_polices.status','active') + ->where('employee_polices.is_active',1) + ->first(); + $existing_endorsements = $this->empEndorsementModel->where('actions', 'c') ->where('table_name', 'employees') ->where('endorsement_id is null') diff --git a/app/Controllers/EmployeeRestController.php b/app/Controllers/EmployeeRestController.php index 1dd19735..341bfcf2 100755 --- a/app/Controllers/EmployeeRestController.php +++ b/app/Controllers/EmployeeRestController.php @@ -3,6 +3,7 @@ namespace App\Controllers; use App\Helpers\MailHelper; +use App\Helpers\NhanceWelnessSsoHelper; use CodeIgniter\HTTP\IncomingRequest; use CodeIgniter\HTTP\RequestInterface; @@ -133,12 +134,25 @@ class EmployeeRestController extends AdminController $client_branch_id = $this->request->getGet('client_branch_id'); if ($emp_code) { $relationship = 'self'; - $employee = $this->employeeModel->where('emp_code', $emp_code) - ->where('client_id', $client_id) - ->where('client_branch_id', $client_branch_id) - ->where('is_active', 1 ) - ->where('relationship', $relationship) - ->first(); + // $employee = $this->employeeModel->where('emp_code', $emp_code) + // ->where('client_id', $client_id) + // ->where('client_branch_id', $client_branch_id) + // ->where('is_active', 1 ) + // ->where('relationship', $relationship) + // ->first(); + $employee = $this->employeeModel + ->select('employees.*') + ->join('employee_polices', 'employees.id = employee_polices.employee_id') + ->where('employees.emp_code', $emp_code) + ->where('employees.client_id', $client_id) + ->where('employees.client_branch_id', $client_branch_id) + ->where('employees.is_active', 1 ) + ->where('employees.relationship', $relationship) + ->where('employee_polices.status', ['active']) + ->where('employees.is_active', 1) + ->where('employees.emp_status', ['active']) + ->first(); + if (null !== $this->request->getGet('client_policy_id')) { $date_coverage = $this->employeePolicyModel->where('employee_id',$employee['id'])->where('client_policy_id',$this->request->getGet('client_policy_id'))->get()->getRow()->date_coverage; @@ -3809,22 +3823,147 @@ class EmployeeRestController extends AdminController public function getWellnessUrl() { - // $url = "https://aam.mohfw.gov.in/home/login"; - $url = ""; - if (!empty($url)) { - return $this->respond([ - 'status' => 'success', - 'data' => $url - ], 200); + $emp_id = $this->request->getGet('emp_id'); + $db = \Config\Database::connect(); + $data = $db->table('employees e') + ->select('pt.policy_type, + e.name, e.email_corporate as email, e.mobile as phone, e.emp_code as memberId, e.gender, e.dob, e.relationship as relation, + cp.policy_no as policyNumber, cp.policy_no as employeeId, cp.policy_start_date as policyStartDate, cp.policy_end_date as policyEndDate') + ->join('employee_polices ep', 'e.id = ep.employee_id') + ->join('client_policy cp', 'ep.client_policy_id = cp.id') + ->join('policy_type pt', 'cp.policy_type_id = pt.id') + ->where('e.id', $emp_id) + ->where('e.emp_status', 'active') + ->where('ep.status', 'active') + ->where('e.is_active', 1) + ->where('ep.is_active', 1) + ->get() + ->getResultArray(); + + + // Loop through $data and check for policy_type = GMC + $userParams = []; + foreach ($data as $row) { + if ($row['policy_type'] === 'GMC') { + $userParams['name'] = $row['name']; + $userParams['email'] = $row['email']; + $userParams['phone'] = $row['phone']; + $userParams['memberId'] = $row['memberId']; + $userParams['gender'] = $row['gender']; + $userParams['dob'] = $row['dob']; + $userParams['relation'] = $row['relation']; + $userParams['policyNumber'] = $row['policyNumber']; + $userParams['employeeId'] = $row['employeeId']; + $userParams['policyStartDate']= $row['policyStartDate']; + $userParams['policyEndDate'] = $row['policyEndDate']; + $userParams['policyName'] = 'Nhance ' . $row['policy_type']; + $userParams['planId'] = 'NHANCE-PLAN-' . $row['policy_type']; + $userParams['moduleName'] = 'home'; + break; // stop after first GMC match + } + } + + if (empty($userParams)) { + return $this->respond(['status' => 'failed','message' => 'Coming soon........!'], 200); + } + + + // Derive 32-byte key from SHA256 + $derivedKey = hash('sha256', env('VISIT_SECRET_KEY'), true); + + // Build query string like Node.js + $plainText = ''; + foreach ($userParams as $k => $v) { + $plainText .= "&{$k}={$v}"; + } + $plainText = ltrim($plainText, '&'); + + // Encrypt + $algorithm = "aes-256-cbc"; + $encrypted = openssl_encrypt($plainText, $algorithm, $derivedKey, OPENSSL_RAW_DATA, env('VISIT_IV')); + + // Base64URL encode (same as Node.js output) + $output = rtrim(strtr(base64_encode($encrypted), '+/', '-_'), '='); + + $baseURL = env('VISIT_BASE_URL'); + $clientId = env('VISIT_CLIENT_ID'); + $finalUrl = $baseURL . '/sso?userParams=' . $output . '&clientId=' . $clientId; + + if (!empty($finalUrl)) { + return $this->respond(['status' => 'success','data' => $finalUrl], 200); } else { - return $this->respond([ - 'status' => 'failed', - 'message' => 'Coming soon........!' - ], 200); + return $this->respond(['status' => 'failed','message' => 'Coming soon........!'], 200); } } + + + // not in use did for testing + function encrypt_for_sso(): string { + + + $key = "32D1D5535157AF3D4667ADAB0CC795D77D022BB281AD3272EB134C72BD0B185E"; + + $userParams = [ + "name" => "John Doe 3", + "email" => "john.doe3@email.com", + "memberId" => "TEST-REL-01", + "gender" => "Male", + "dob" => "1997-01-01", + "policyName" => "Nhance DEMO", + "phone" => "6676126763", + "employeeId" => "EMP-NHANCE-TEST-03", + "policyNumber" => "EMP-NHANCE-TEST-03", + "policyStartDate" => "2025-09-08", + "policyEndDate" => "2026-09-08", + "moduleName" => "home", + "relation" => "self", + "planId" => "NHANCE-PLAN-1" + ]; + + $algorithm = "aes-256-cbc"; + + // Derive 32-byte key from SHA256 + $derivedKey = hash('sha256', $key, true); + + // Fixed IV (must be 16 bytes) + $iv = "getvisitappdocom"; + + // Build query string like Node.js + $plainText = ''; + foreach ($userParams as $k => $v) { + $plainText .= "&{$k}={$v}"; + } + $plainText = ltrim($plainText, '&'); + + + // echo ($plainText); die; + + // Encrypt + $encrypted = openssl_encrypt($plainText, $algorithm, $derivedKey, OPENSSL_RAW_DATA, $iv); + + // Base64URL encode (same as Node.js output) + $output = rtrim(strtr(base64_encode($encrypted), '+/', '-_'), '='); + + // return $output; + + + $baseURL = 'https://web.getvisitapp.net'; + $clientId = 'nhance-gt-2tx7'; + $finalUrl = $baseURL . '/sso?userParams=' . $output . '&clientId=' . $clientId; + + return $finalUrl; + + + } + + + + + + + public function getEmployeePolicyCount() { $db2 = \Config\Database::connect('preDB'); diff --git a/app/Controllers/EmployeeServiceController.php b/app/Controllers/EmployeeServiceController.php index a80ec116..07bf7ad5 100755 --- a/app/Controllers/EmployeeServiceController.php +++ b/app/Controllers/EmployeeServiceController.php @@ -1470,10 +1470,11 @@ class EmployeeServiceController extends AdminController //get file name $file_id = $params['file_id']; $file = $this->fileModel->find($file_id); + // dd($file); $file_name_with_path = WRITEPATH."/uploads/excel/".$file['file_name']; - $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file_name_with_path); + $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file_name_with_path); $sheet = $spreadsheet->getActiveSheet(); $highestRowAndColumn = $sheet->getHighestRowAndColumn(); @@ -1498,13 +1499,21 @@ class EmployeeServiceController extends AdminController $employee = $this->employeeModel - ->where('emp_code', $row[1]) - ->where('name',$row[2]) - ->where('client_id',$file['client_id']) - ->where('client_branch_id',$file['client_branch_id']) - ->where('emp_status','active') - ->where('is_active',1) + ->select('employees.*') + ->join('employee_polices', 'employees.id = employee_polices.employee_id') + ->where('employees.emp_code', $row[1]) + ->where('employees.name',$row[2]) + ->where('employees.client_id',$file['client_id']) + ->where('employees.client_branch_id',$file['client_branch_id']) + ->where('employee_polices.client_policy_id',$file['policy_id']) + ->where('employees.emp_status','active') + ->where('employees.is_active',1) + ->where('employee_polices.status','active') + ->where('employee_polices.is_active',1) ->first(); + + // Kint::dump($employee); + $existing_endorsements = $this->empEndorsementModel->where('actions','c') ->where('table_name','employees') ->where('endorsement_id is null') @@ -1530,7 +1539,7 @@ class EmployeeServiceController extends AdminController $this->myLogger->logme("error",'{file_id} uploaded success',['file_id' => $file_id]); //set success msg to pull notifications $this->setPullNotification($this->getFileMetaDataByFileId($file_id,'success')); - return true; + return true; } diff --git a/app/Controllers/ICICILombardController.php b/app/Controllers/ICICILombardController.php index 9433f7f1..928fbc2f 100644 --- a/app/Controllers/ICICILombardController.php +++ b/app/Controllers/ICICILombardController.php @@ -4,30 +4,31 @@ namespace App\Controllers; use CodeIgniter\Controller; use Kint; +use Ramsey\Uuid\Uuid; + class ICICILombardController extends AdminController { public function generateAuthToken($scope = 'esbhealth') { helper('api'); - // dd($scope); - $url = 'https://ilesbapigee.insurancearticlez.com/generate-jwt-token'; + $url = env('ICICI_TOKEN_URL'); $method = 'POST'; $headers = [ 'Content-Type: application/x-www-form-urlencoded' ]; $body = [ - 'grant_type' => 'password', - 'username' => 'Nhanceins', - 'password' => 'SSWW7bFNaLxxQyw', - 'scope' => $scope, - 'client_id' => 'Nhanceins', - 'client_secret' => 'P4W0G6TAYMa0MV8bbVSx4pTAqbCcUIg48kCWa6PJykAhGWzPmpPr0iLuNWtz5wqN' + 'grant_type' => env('ICICI_GRANT_TYPE'), + 'username' => env('ICICI_USER_NAME'), + 'password' => env('ICICI_PASSWORD'), + 'scope' => env('ICICI_API_SCOPE'), + 'client_id' => env('ICICI_CLIENT_ID'), + 'client_secret' => env('ICICI_CLIENT_SECRET') ]; - print_rr(json_encode($body));//die; + $response = call_third_party_api($url, $method, $headers, $body); - print_rr(json_encode($response));//die; + if($response['status'] != true){ return $this->response->setJSON([ 'status' => false, @@ -41,7 +42,10 @@ class ICICILombardController extends AdminController public function createEnrollmentBatch() { - helper('api'); + $client_id = $this->request->getGet('client_id'); + $client_branch_id = $this->request->getGet('client_branch_id'); + $policy_id = $this->request->getGet('policy_id'); + $event = $this->request->getGet('event'); //fetch token $tokenResponse = $this->generateAuthToken(); @@ -53,72 +57,36 @@ class ICICILombardController extends AdminController ]); } $token = $tokenResponse['data']['access_token']; - // dd($token); + - $url = 'https://ilesbapigee.insurancearticlez.com/health/ilservices/health/v1/enrollment/batchcreation'; + $url = env('ICICI_BASE_URL').'/batchcreation'; $headers = [ 'Authorization: Bearer ' . $token, 'Content-Type: application/json', - //'Scope: esbgpabatchcreation' ]; - #old policy info start - #"PolicyNumber" => "4016/A/51974976/00/000", - # "CDBGAccountNumber" => "CD-MUM-3344", - #"CorrelationId" => "86383c78-4c67-4e4d-9aa0-8f926fb0d55f", - #old policy inf end - $body = [ - "PolicyNumber" => "4016/A/O/53077718/00/000", - "CDBGAccountNumber" => "CD-MUM-0026", - "CorrelationId" => "86383c78-4c67-4e4d-9aa0-8f926fb0d55f", - "MemberDetails" => [ - [ - "EmployeeMemberId" => "EMPID3625556", - "DOJ" => "21-MAR-2019", - "InsuredName" => "ABC28144", - "DOB" => "7-JUL-1983", - "Relationship" => "SELF", - "Gender" => "MALE", - "DOC" => "08-JUL-2025", - "SumInsured" => "400000", - "EmailId" => "ABC@GMAIL.COM", - "FlagStatus" => "A" - ], - [ - "EmployeeMemberId" => "EMPID3625556", - "DOJ" => "21-MAR-2019", - "InsuredName" => "ABC28146", - "DOB" => "8-AUG-1970", - "Relationship" => "MOTHER", - "Gender" => "FEMALE", - "DOC" => "08-JUL-2025", - "SumInsured" => "400000", - "EmailId" => "ABC@GMAIL.COM", - "FlagStatus" => "A" - ], - [ - "EmployeeMemberId" => "EMPID0502220011", - "UHID" => "IL00688842553", - "InsuredName" => "ABC28142", - "DOB" => "8-SEP-1970", - "Gender" => "MALE", - "SumInsured" => "400000", - "EmailId" => "ABC@GMAIL.COM", - "FlagStatus" => "M" - ], - [ - "UHID" => "IL00688842552", - "DOL" => "08-JUL-2025", - "FlagStatus" => "D" - ] - ] - ]; - // Kint::dump($body); - print_rr(json_encode($body)); - // dd(); - $response = call_third_party_api($url, 'POST', $headers, ($body),true); // true = raw body mode - print_rr(json_encode($response));die(); + //Prepare body data + $db = \Config\Database::connect(); + $data = $db->table('employee_polices ep') + ->select('cp.policy_no as policyNumber, cp.cd_ac_no as CDBGAccountNumber, + e.id,e.emp_code as MemberEmpId, e.doj as DOJ, e.name as InsuredName, e.dob as DOB, e.relationship as Relationship, + e.gender as Gender, ep.date_coverage as DOC,ep.basic_cover_si as SumInsured, e.email_corporate as EmailId + ') + ->join('employees e', 'e.id = ep.employee_id') + ->join('client_policy cp', 'ep.client_policy_id = cp.id') + ->where('ep.client_policy_id', $policy_id) + ->where('ep.status', 'active') + ->where('ep.is_active', 1) + // ->where('ep.uhid', null) + ->get() + ->getResultArray(); + + $body = $this->formatPolicyData($data); + // dd($body); + + $response = call_third_party_api($url, 'POST', $headers, $body, true); // true = raw body mode + // print_rr(json_encode($response));die(); return $this->response->setJSON($response); } @@ -127,7 +95,7 @@ class ICICILombardController extends AdminController helper('api'); //fetch token - $tokenResponse = $this->generateAuthToken('esbgpabatchstatus'); + $tokenResponse = $this->generateAuthToken(); if (!$tokenResponse || empty($tokenResponse['data']['access_token'])) { return $this->response->setJSON([ 'status' => false, @@ -138,19 +106,21 @@ class ICICILombardController extends AdminController $token = $tokenResponse['data']['access_token']; - $url = 'https://ilesbapigee.insurancearticlez.com/health/ilservices/health/v1/enrollment/batchstatus'; + $url = env('ICICI_BASE_URL').'/batchstatus'; $headers = [ 'Authorization: Bearer ' . $token, 'Content-Type: application/json' ]; - $body = [ - "PolicyNumber" => "4016/A/51974976/00/000", - "BatchId" => "2345617878", - "CorrelationId" => "86383c78-4c67-4e4d-9aa0-8f926fb0d55f" + // dd($headers); + + $body = [ + "PolicyNumber" => "4016/A/O/53077718/00/000", + "BatchId" => "3646145", + "CorrelationId" => "550e8400-e29b-41d4-a716-446655440001" ]; - $response = call_third_party_api($url, 'POST', $headers, json_encode($body), true); + $response = call_third_party_api($url, 'POST', $headers, $body, true); return $this->response->setJSON($response); } @@ -170,7 +140,9 @@ class ICICILombardController extends AdminController } $token = $tokenResponse['data']['access_token']; - $url = 'https://ilesbapigee.insurancearticlez.com/health/ilservices/health/v1/enrollment/fetchuhid'; + // print_rr($token); + + $url = env('ICICI_BASE_URL').'/fetchuhid'; $headers = [ 'Authorization: Bearer ' . $token, 'Content-Type: application/json' @@ -179,14 +151,113 @@ class ICICILombardController extends AdminController $body = [ "PolicyNumber" => "4016/A/51974976/00/000", "IMID" => "2345617878", - "CorrelationId" => "86383c78-4c67-4e4d-9aa0-8f926fb0d55f" + "CorrelationId" => "86383c78-4c67-4e4d-9aa0-9f926fb0d55e" ]; - $response = call_third_party_api($url, 'POST', $headers, json_encode($body), true); + $response = call_third_party_api($url, 'POST', $headers, $body, true); return $this->response->setJSON($response); } + public function formatPolicyData($data) + { + // Helper to format date + $formatDate = function ($date) { + return strtoupper(date('j-M-Y', strtotime($date))); // Example: 7-JUL-1983 + }; + + // Generate UUID v4 for CorrelationId + $generateUUID = function () { + return sprintf( + '%04x%04x-%04x-%04x-%04x-%04x%04x%04x', + mt_rand(0, 0xffff), + mt_rand(0, 0xffff), + mt_rand(0, 0xffff), + mt_rand(0, 0x0fff) | 0x4000, + mt_rand(0, 0x3fff) | 0x8000, + mt_rand(0, 0xffff), + mt_rand(0, 0xffff), + mt_rand(0, 0xffff) + ); + }; + + // Map MemberDetails + $memberDetails = array_map(function ($row) use ($formatDate) { + return [ + "MemberEmpId" => $row['MemberEmpId'], + "DOJ" => $formatDate($row['DOJ']), + "InsuredName" => $row['InsuredName'], + "DOB" => $formatDate($row['DOB']), + "Relationship" => strtoupper($row['Relationship']), + "Gender" => strtoupper($row['Gender']), + "DOC" => $formatDate($row['DOC']), + "SumInsured" => $row['SumInsured'], + "EmailId" => $row['EmailId'], + "FlagStatus" => "A" // fixed value + ]; + }, $data); + + // Final body + return [ + "PolicyNumber" => $data[0]['policyNumber'] ?? null, + "CDBGAccountNumber" => $data[0]['CDBGAccountNumber'] ?? null , // "CD-MUM-0026", + "CorrelationId" => $generateUUID(), + "MemberDetails" => $memberDetails + ]; + } + + + + + + + + + + + + + + + + + + + + + + + // $body = [ + // "PolicyNumber" => "4016/A/O/53077718/00/000", + // "CDBGAccountNumber" => "CD-MUM-0026", + // "CorrelationId" => "550e8400-e29b-41d4-a716-446655440001", + // "MemberDetails" => [ + // [ + // "MemberEmpId" => "EMPID3625557", + // "DOJ" => "21-MAR-2019", + // "InsuredName" => "Kumar", + // "DOB" => "7-JUL-1983", + // "Relationship" => "SELF", + // "Gender" => "MALE", + // "DOC" => "08-JUL-2025", + // "SumInsured" => "400000", + // "EmailId" => "KUMAR@GMAIL.COM", + // "FlagStatus" => "A" + // ], + // [ + // "MemberEmpId" => "EMPID3625557", + // "DOJ" => "21-MAR-2019", + // "InsuredName" => "Saranya", + // "DOB" => "8-AUG-1970", + // "Relationship" => "MOTHER", + // "Gender" => "FEMALE", + // "DOC" => "08-JUL-2025", + // "SumInsured" => "400000", + // "EmailId" => "Saranya@GMAIL.COM", + // "FlagStatus" => "A" + // ], + // ] + // ]; } diff --git a/app/Controllers/MasterController.php b/app/Controllers/MasterController.php index 60d3b955..c26d6fb8 100755 --- a/app/Controllers/MasterController.php +++ b/app/Controllers/MasterController.php @@ -1550,6 +1550,14 @@ class MasterController extends AdminController $date = (string) $this->request->getPost('opening_date'); $data['opening_date'] = date('Y-m-d', strtotime($date)); + $insurer_id = null; + $insurer_branch_id = null; + if(isset($data['insurer_and_insurer_branch']) && !empty($data['insurer_and_insurer_branch'])){ + list($insurer_branch_id, $insurer_id) = explode('-', $data['insurer_and_insurer_branch']); + } + + $data['insurer_branch_id'] = $insurer_branch_id; + // array with data for CD Traction table $cd_tranction_data = [ @@ -1578,7 +1586,16 @@ class MasterController extends AdminController $cd_data = $this->CDMasterModel->where('client_id', $data['client_id'])->where('insurer_id', $data['insurer_id'])->findAll(); - return $this->respond(['status' => true, 'data' => $cd_data, 'cd_ac_no'=>$data['cd_ac_no'], 'message' => 'CD Account number created successfully', "FOR BDS PURPOSE"], 200); + return $this->respond([ + 'status' => true, + 'cd_ac_pk' => $insert, + 'data' => $cd_data, + 'received_data' => $data, + 'cd_ac_no'=>$data['cd_ac_no'], + 'message' => 'CD Account number created successfully', + "FOR BDS PURPOSE" + ], 200); + }else{ return $this->respond(['status' => false, 'message' => 'Failed to created CD Account number'], 200); } diff --git a/app/Controllers/PolicyTransactionController.php b/app/Controllers/PolicyTransactionController.php index 2b9afb78..8b2a80bb 100644 --- a/app/Controllers/PolicyTransactionController.php +++ b/app/Controllers/PolicyTransactionController.php @@ -36,6 +36,7 @@ use App\Models\BdsPlacementModel; use Kint\Kint; use App\Helpers\MailHelper; use App\Helpers\ExcelSanitizeHelper; +use App\Models\NhanceBranchModel; use Exception; class PolicyTransactionController extends BaseController @@ -69,6 +70,7 @@ class PolicyTransactionController extends BaseController protected $filesModel; protected $coShareStmtDetailsModel; protected $BdsPlacementModel; + protected $nhanceBranchModel; public function __construct() { @@ -100,6 +102,7 @@ class PolicyTransactionController extends BaseController $this->filesModel = new FileModel(); $this->coShareStmtDetailsModel = new COShareStmtDetailsModel(); $this->BdsPlacementModel = new BdsPlacementModel(); + $this->nhanceBranchModel = new NhanceBranchModel(); $this->invoiceStatus = [ 'pending' => 'Pending', 'generated' => 'Generated', @@ -115,6 +118,7 @@ class PolicyTransactionController extends BaseController // Static arrays for dropdowns $data['issuer'] = [1 => 'JIBS', 2 => 'Nhance']; + $data['issuer_branch'] = $this->nhanceBranchModel->where('is_active', 1)->findAll(); $data['client_type'] = [1 => 'Group', 2 => 'Individual']; $data['issuing_type'] = [1 => 'Fresh', 2 => 'Renewal', 3 => 'Roll Over']; $data['policy_status'] = [ @@ -255,6 +259,7 @@ class PolicyTransactionController extends BaseController $id = $this->request->getPost('id'); $data = $this->preparePolicyData(); $data['cd_ac_pk'] = $this->request->getPost('cd_ac_no'); + $data['issuer'] = 2; $this->myLogger->logme('error', 'Policy Trancaction modified form data ( insert data ) : '. json_encode($data)); @@ -334,11 +339,8 @@ class PolicyTransactionController extends BaseController $data['policy_with_corr'] = 1; } - if (!isset($data['is_cd_reduce_from_bds'])) { - $data['is_cd_reduce_from_bds'] = 0; - } elseif ($data['is_cd_reduce_from_bds']) { - $data['is_cd_reduce_from_bds'] = 1; - } + $data['is_cd_reduce_from_bds'] = ($data['policy_type_id'] > 7 && $data['client_type'] == 1) ? 1 : 0; + if ($data['ct_type'] == "") { $data['ct_type'] = 1; @@ -400,6 +402,8 @@ class PolicyTransactionController extends BaseController private function updateInceptionPolicy($id, $data) { // print_r($data); die; + $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)) { $this->insertTransactionStatus($id, $data, 1); @@ -427,15 +431,22 @@ class PolicyTransactionController extends BaseController } } - if ($data['status'] == 'completed' && $data['ct_type'] == 2) { - if ($data['client_type'] == 1 && $data['is_cd_reduce_from_bds'] == 1) { - $this->processCompletedStatus($data, $data['client_policy_id'], $data['insurer_id']); + if($old_pt_data['status'] != "completed"){ + if ($data['status'] == 'completed' && $data['ct_type'] == 2) { + if ($data['client_type'] == 1 && $data['is_cd_reduce_from_bds'] == 1) { + $this->processCompletedStatus($data, $data['client_policy_id'], $data['insurer_id']); + } } } $data['pt_co_share_details'] = $this->PTCOShareDetailsModel->where('pt_id', $id)->where('is_active', 1)->findAll(); } + if(isset($data['cd_amt_changed']) && !empty($data['cd_amt_changed'])){ + $policy_data = $this->policyTransactionModel->where('is_active', 1)->where('id', $id)->first(); + $this->cdCorrection($policy_data, $data['cd_amt_changed']); + } + $client_data = $this->clientModel->where('id', $data['client_id'])->first(); $data['client_kyc'] = $this->clientKYCDocsModel->where('client_id', $data['client_id'])->findAll(); @@ -621,6 +632,30 @@ class PolicyTransactionController extends BaseController DepositHelper::saveDeposit($cdTransactionData, get_session_userid()); } + private function cdCorrection($data, $amt) + { + $totalAmount = (int)($amt ?? 0); + $description = 'The following amount of Rs. ' . $totalAmount . '/- has been debited towards the difference arising from the change in the BDS base premium.'; + + $cdTransactionData = [ + 'amount' => abs($totalAmount), + 'sub_type_id' => 4, + 'client_id' => $data['client_id'], + 'client_policy_id' => $data['client_policy_id'] ?? 0, + 'endorsement_no' => null, + 'cd_ac_no' => $data['cd_ac_no'] ?? null, + 'insurer_id' => $data['insurer_id'], + 'description' => $description, + 'transaction_type' => $totalAmount < 0 ? 'Credit' : 'Debit', + 'updated_by' => get_session_userid(), + 'event_name' => 'inception', + 'is_active' => 1, + 'cd_ac_pk' => $data['cd_ac_pk'] + ]; + + DepositHelper::saveDeposit($cdTransactionData, get_session_userid()); + } + private function processInsertIndividualMemberInEmpTable($data) { // print_r($data); @@ -753,31 +788,6 @@ class PolicyTransactionController extends BaseController ->where('policy_transaction.is_active', 1) ->first(); - // $data['policy_issue_date'] = (isset($data['policy_issue_date']) && $data['policy_issue_date'] !== null && $data['policy_issue_date'] !== '') - // ? date('d/m/Y', strtotime($data['policy_issue_date'])) - // : null; - - // $data['policy_start_date'] = (isset($data['policy_start_date']) && $data['policy_start_date'] !== null && $data['policy_start_date'] !== '') - // ? date('d/m/Y', strtotime($data['policy_start_date'])) - // : null; - - // $data['policy_end_date'] = (isset($data['policy_end_date']) && $data['policy_end_date'] !== null && $data['policy_end_date'] !== '') - // ? date('d/m/Y', strtotime($data['policy_end_date'])) - // : null; - - // $data['renewal_date'] = (isset($data['renewal_date']) && $data['renewal_date'] !== null && $data['renewal_date'] !== '') - // ? date('d/m/Y', strtotime($data['renewal_date'])) - // : null; - - // $data['rollover_date'] = (isset($data['rollover_date']) && $data['rollover_date'] !== null && $data['rollover_date'] !== '') - // ? date('d/m/Y', strtotime($data['rollover_date'])) - // : null; - - // $data['month'] = (isset($data['month']) && $data['month'] !== null && $data['month'] !== '') - // ? date('M/Y', strtotime($data['month'])) - // : null; - - $data['created_at'] = (isset($data['created_at']) && $data['created_at'] !== null && $data['created_at'] !== '') ? date('d/m/Y h:i:s A', strtotime($data['created_at'])) : null; @@ -821,8 +831,6 @@ class PolicyTransactionController extends BaseController $data['month'] = null; } - - // print_r($data); die; $data['renewal_policy'] = $this->clientPolicyModel @@ -833,7 +841,6 @@ class PolicyTransactionController extends BaseController ->where('client_policy.is_active', 1) ->findAll(); - $data['base_policy_data'] = $this->clientPolicyModel ->select('client_policy.*, policy_type.policy_type') ->join('policy_type', 'policy_type.id = client_policy.policy_type_id') @@ -843,6 +850,16 @@ class PolicyTransactionController extends BaseController ->where('client_policy.is_active', 1) ->findAll(); + $pt_bp_amt = $this->PTCOShareDetailsModel + ->select('bp_amt, amount') + ->where('pt_id', $id) + ->where('co_share_type', 1) + ->where('is_active', 1) + ->first(); + + // dd(db_connect()->getLastQuery() ,$pt_bp_amt); + $data['base_cd_amount'] = $pt_bp_amt['amount'] ?? null; + $ptFileQuery = $this->PTFileModel ->join('policy_transaction', 'pt_files.pt_id = policy_transaction.id') @@ -999,7 +1016,7 @@ class PolicyTransactionController extends BaseController ->findAll(); // print_r( $data['pt_co_share_details']); die; - + // return $data; if ($data) { return $this->respond(['status' => true, 'data' => $data], 200); } else { @@ -1059,8 +1076,8 @@ class PolicyTransactionController extends BaseController // !dd($this->getEndorsementDataForEdit(17)); $data['page_name'] = 'Endorsement'; - $data['issuer'] = [1 => 'JIBS', 2 => 'Nhance']; + $data['issuer_branch'] = $this->nhanceBranchModel->where('is_active', 1)->findAll(); $data['client_type'] = [1 => 'Group', 2 => 'Individual']; $data['policy_status'] = [ @@ -1170,11 +1187,11 @@ class PolicyTransactionController extends BaseController $data['policy_with_corr'] = 1; } - if (!isset($data['is_cd_reduce_from_bds'])) { - $data['is_cd_reduce_from_bds'] = 0; - } elseif ($data['is_cd_reduce_from_bds']) { - $data['is_cd_reduce_from_bds'] = 1; - } + // if (!isset($data['is_cd_reduce_from_bds'])) { + // $data['is_cd_reduce_from_bds'] = 0; + // } elseif ($data['is_cd_reduce_from_bds']) { + // $data['is_cd_reduce_from_bds'] = 1; + // } if (empty($data['data_received_date'])) { $data['data_received_date'] = null; @@ -1235,6 +1252,8 @@ class PolicyTransactionController extends BaseController $client_branch_id = $issue_type['client_branch_id']; } + $data['is_cd_reduce_from_bds'] = (isset($issue_type['policy_type_id']) && $issue_type['policy_type_id'] > 7 && $data['client_type'] == 1) ? 1 : 0; + // if($data['bro_payable_by'] == ""){ // $data['bro_payable_by'] = $issue_type['bro_payable_by']; // } @@ -1242,7 +1261,8 @@ class PolicyTransactionController extends BaseController if (!$data['id']) { $data += [ - 'issuer' => $issue_type['issuer'] ?? null, + 'issuer' => 2, + 'issuer_branch' => $data['issuer_branch'] ?? 1, 'client_type' => $data['client_type'] ?? $issue_type['client_type'] ?? null, 'policy_type_id' => $issue_type['policy_type_id'] ?? null, 'issue_type' => $issue_type['issue_type'] ?? null, @@ -1303,13 +1323,16 @@ class PolicyTransactionController extends BaseController } private function updateEndorsementTransaction($id, $data) - { + { + $old_endorse_data = $this->policyTransactionModel->where('id', $id)->where('is_active', 1)->first(); $update = $this->policyTransactionModel->where('id', $id)->set($data)->update(); if ($update) { $this->insertTransactionStatus($id, $data, 1); - $this->handleCompletedStatus($data, $id); + if($old_endorse_data['status'] != "completed"){ + $this->handleCompletedStatus($data, $id); + } $this->insertOrUpdateCoShareDetails($data, $id); @@ -1323,11 +1346,10 @@ class PolicyTransactionController extends BaseController { if ($data['client_type'] == 1 && $data['status'] == 'completed' && $data['is_cd_reduce_from_bds'] == 1) { - $tolamt = $data['total'][0] ?? 0; + $tolamt = (int) $data['total'][0] ?? 0; $description = 'The following amount of Rs. ' . round($tolamt, 2) . '/- has been' . ($data['action_type'] == 'deletion' ? ' Credit ' : ' Debit ') . 'from the policy transaction (BDS)'; - $cd_tranction_data = [ 'amount' => $tolamt, 'sub_type_id' => $data['action_type'] == 'deletion' ? 3 : 4, diff --git a/app/Controllers/TestingController.php b/app/Controllers/TestingController.php index d866cb7f..cb432d24 100644 --- a/app/Controllers/TestingController.php +++ b/app/Controllers/TestingController.php @@ -4,6 +4,7 @@ namespace App\Controllers; use App\Controllers\BaseController; use App\Models\EmployeePolicyModel; +use App\Models\InsurerBranchModel; use CodeIgniter\HTTP\ResponseInterface; use CodeIgniter\API\ResponseTrait; use Dompdf\Dompdf; @@ -236,4 +237,80 @@ class TestingController extends BaseController ->findAll(); } + + public function ptedfitdata($id){ + $policy_transaction = new PolicyTransactionController(); + $data = $policy_transaction->getInceptionDataForEdit($id); + // dd($data); + $insurerBranchModel = new InsurerBranchModel(); + $insurer_branch = $insurerBranchModel->getInsurerBranchesWithInsurerNames(); + + $dataArray = $data['pt_co_share_details']; // Example + $cd_ac_pk = 'CD12345'; + $role_id = 1; + $team_id = ['6']; + $insurer_branch = $insurer_branch; + + return view('pt_calc_table', [ + 'dataArray' => $dataArray, + 'cd_ac_pk' => $cd_ac_pk, + 'role_id' => $role_id, + 'team_id' => $team_id, + 'insurer_branch' => $insurer_branch + ]); + } + + function generateInsurerTable($dataArray, $cd_ac_pk, $role_id, $team_id, $insurer_branch) + { + $html = ''; + + foreach ($dataArray as $index => $data) { + $disable_td = ($data['record_count'] > 0) ? 'readonly-select' : ''; + $insurer = $data['insurer_branch_id'] . '-' . $data['insurer_id']; + + $html .= ''; + + // Insurer selection + $html .= ''; + + // Leader toggle + $checked = ($data['co_share_type'] == 1) ? 'checked' : ''; + $html .= ''; + + // CD Account + $html .= ''; + + // CD Amount + $html .= ''; + + // Example of follower policy no + $html .= ''; + + // Add other fields (bp_amt, tp_amt, gst, etc.) + $html .= ''; + $html .= ''; + $html .= ''; + $html .= ''; + + $html .= ''; + } + + $html .= '
'; + + return $html; + } + } diff --git a/app/Controllers/ThzController.php b/app/Controllers/ThzController.php index 0dea90c1..c1896be4 100644 --- a/app/Controllers/ThzController.php +++ b/app/Controllers/ThzController.php @@ -1,723 +1,654 @@ -thzMasterModel = new ThzMasterModel(); - $this->thzMasterNotesModel = new ThzMasterNotesModel(); - $this->thzTypeModel = new thzTypeModel(); - $this->thzHistoryModel = new ThzHistoryModel(); - $this->thzControllerCleaner = new ThzControllerCleaner(); - $this->userModel = new UserModel(); - $this->clientPolicyModel = new ClientPolicyModel(); - $this->clientModel = new ClientModel(); - $this->cientRmModel = new ClientRMModel(); - $this->ticketMailTemplateModel = new TicketMailTemplateModel(); - $this->myLogger = \Config\Services::mylogger(); - } - - public function index() - { - // - } - - public function ticketSave() - { - try { - $data = $this->request->getPost(); - $references = ""; - if (!empty($data['thz_id'])) { - - $text = "update"; - // here insert history Status. - $old = $this->thzMasterModel->where('thz_id', $data['thz_id'])->get()->getRowArray(); - $result = $this->updateTicket($data); - - if ($old && isset($data['status'])) { - - if ($old['status'] != $data['status']) { - $history = [ - 'thz_id' => $data['thz_id'], - 'field_name' => 'status', - 'display_name' => 'Status', - 'old_value' => $old['status'], - 'new_value' => $data['status'], - 'is_active' => 1 - ]; - - if (!empty(get_session_userid())) { - $history['created_by'] = get_session_userid(); - } - - $hist_id = $this->thzHistoryModel->insert($history); - $references = $old['status'] . " - " . $data['status'] . " - " . $hist_id; - } else { - $references = $old['status'] . " - " . $data['status']; - } - } else { - $references = "No Details"; - } - - $updateID = $data['thz_id']; - } else { - - $text = "create"; - $insertID = $this->insertTicket($data); - $result = true; - $references = ""; - } - - $id = isset($insertID) && !empty($insertID) ? $insertID : $updateID; - - $emailNotificationResult = $this->ticketSaveNotification($data, $insertOrUpdate = $text, $id); - - return $this->response->setJSON([ - 'status' => $result ? 'success' : 'error', - 'message' => $result ? "Ticket {$text}d successfully " : "Unable to {$text} ticket. Please try again.", - 'notification' => $emailNotificationResult ? 'Email Notification Success..!!' : 'Email Notification Failed..!!', - 'ref' => $references - ])->setStatusCode($result ? 200 : 400); - } catch (\Throwable $e) { - $code = ($e->getCode() && $e->getCode() >= 100 && $e->getCode() < 600) ? $e->getCode() : 500; - - $isDbError = $e instanceof \CodeIgniter\Database\Exceptions\DatabaseException - || $e instanceof \mysqli_sql_exception - || $e instanceof \PDOException; - - $context = ['title' => get_class($e), 'type' => get_class($e), 'code' => $code, 'message' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]; - - $this->myLogger->logme('error', "Exception: {message} in {file} on line {line}", $context, 0); - - return $this->response->setJSON([ - 'status' => 'error', - 'message' => $isDbError ? 'Data Access Error' : $e->getMessage(), - 'ref' => $isDbError ? 'database - ' : 'application - ' . $code . ' - ' . $e->getLine() - ])->setStatusCode($code); - } - } - - public function ticketList() - { - - try { - $returnType = strtolower($this->request->getGet('return_type') ?? 'api'); - - - $data = $this->request->getGet(); - if ($returnType === 'web' && in_array(get_role_id(), [2, 3, 4])) { - $data['assign_to'] = $data['assign_to'] ?? get_session_userid(); - } - - $tickets = $this->fetchTicketsBasedOnrole($data); - - - if ($returnType === 'api') { - if (empty($tickets)) { - // return $this->response->setJSON([ 'status' => 'error','message' => 'No tickets found'])->setStatusCode(404); - throw new \RuntimeException('No tickets found', 400); - } - } else { - - $data['page_name'] = "Tickets"; - $data['ticket_data'] = $tickets; - $data['assignee'] = $this->userModel->where('is_active', 1)->whereIn('role', ['2', '3', '4'])->findAll(); // enga 5-"head" and 1-"admin" assign pannvaga so dropdown la varakudhathu - // 2,3,4 remain person varannum. - $data['client_list'] = $this->clientModel->getCreatedByUserName(); - $data['ticket_type'] = $this->thzTypeModel->where('is_active', 1)->findAll(); - - return $this->loadLayout('thz_list', $data); - } - - - return $this->response->setJSON([ - 'status' => 'success', - 'data' => $tickets, - ])->setStatusCode(200); - } catch (\Throwable $e) { - $code = ($e->getCode() && $e->getCode() >= 100 && $e->getCode() < 600) ? $e->getCode() : 500; - - $isDbError = $e instanceof \CodeIgniter\Database\Exceptions\DatabaseException - || $e instanceof \mysqli_sql_exception - || $e instanceof \PDOException; - - $context = ['title' => get_class($e), 'type' => get_class($e), 'code' => $code, 'message' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]; - - $this->myLogger->logme('error', "Exception: {message} in {file} on line {line}", $context, 0); - - return $this->response->setJSON([ - 'status' => 'error', - 'message' => $isDbError ? 'Data Access Error' : $e->getMessage(), - 'ref' => $isDbError ? 'database - ' : 'application - ' . $code . ' - ' . $e->getLine() - ])->setStatusCode($code); - } - } - - public function ticketConversationSave() - { - - try { - $data = $this->request->getPost(); - - $data['notes_type'] = $data['notes_type'] ?? 'External'; - - $result = $this->thzMasterNotesModel->insert($data); - - if (empty($result)) { - // return $this->response->setJSON((['status' => 'error', 'message' => 'No tickets found']))->setStatusCode(404); - throw new \RuntimeException('No tickets found', 404); - } - - if ($data['notes_type'] == "External") { - $emailNotificationResult = $this->ticketConversationSaveNotification($data); - } else { - $emailNotificationResult = false; - } - - - - return $this->response->setJSON([ - 'status' => $result ? 'success' : 'error', - 'message' => $result ? "Ticket Notes created successfully" : "Unable to create ticket notes. Please try again.", - 'notification' => $emailNotificationResult ? 'Email Notification Success..!!' : 'Email Notification Failed Or No Need..!!' - ])->setStatusCode($result ? 200 : 400); - } catch (\Throwable $e) { - $code = ($e->getCode() && $e->getCode() >= 100 && $e->getCode() < 600) ? $e->getCode() : 500; - - $isDbError = $e instanceof \CodeIgniter\Database\Exceptions\DatabaseException - || $e instanceof \mysqli_sql_exception - || $e instanceof \PDOException; - - $context = ['title' => get_class($e), 'type' => get_class($e), 'code' => $code, 'message' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]; - - $this->myLogger->logme('error', "Exception: {message} in {file} on line {line}", $context, 0); - - return $this->response->setJSON([ - 'status' => 'error', - 'message' => $isDbError ? 'Data Access Error' : $e->getMessage(), - 'ref' => $isDbError ? 'database - ' : 'application - ' . $code . ' - ' . $e->getLine() - ])->setStatusCode($code); - } - } - - public function ticketAutoFetchDetails() - { - try { - $data = $this->request->getPost(); - - $client_id = $data['client_id'] ?? null; - $mobile = $data['mobile'] ?? null; - - if ($client_id && $mobile) { - $details = $this->thzMasterModel->ticketAutoFetchDetails($client_id, $mobile); - - if (empty($details)) { - throw new \RuntimeException('No Data found', 400); - } - - $policyIds = array_filter(array_column($details, 'policy_id')); - $clientPolicy = !empty($policyIds) - ? $this->clientPolicyModel->whereIn('id', $policyIds)->where('is_active', 1)->get()->getResultArray() - : []; - - $result['client_details'] = $details; - $result['policy_details'] = $clientPolicy ?? []; - } else { - throw new \RuntimeException('Client and Mobile Not found', 400); - } - - return $this->response->setJSON(['status' => 'success', 'data' => $result])->setStatusCode(200); - } catch (\Throwable $e) { - $code = ($e->getCode() && $e->getCode() >= 100 && $e->getCode() < 600) ? $e->getCode() : 500; - - $isDbError = $e instanceof \CodeIgniter\Database\Exceptions\DatabaseException - || $e instanceof \mysqli_sql_exception - || $e instanceof \PDOException; - - $context = ['title' => get_class($e), 'type' => get_class($e), 'code' => $code, 'message' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]; - - $this->myLogger->logme('error', "Exception: {message} in {file} on line {line}", $context, 0); - - return $this->response->setJSON([ - 'status' => 'error', - 'message' => $isDbError ? 'Data Access Error' : $e->getMessage(), - 'ref' => $isDbError ? 'database - ' : 'application - ' . $code . ' - ' . $e->getLine() - ])->setStatusCode($code); - } - } - - public function ticketConversationList() - { - $data = $this->request->getGet(); - - $returnType = strtolower($this->request->getGet('return_type') ?? 'api'); - - $thz_id = $data['thz_id'] ?? null; - - $ticketType = $data['notes_type'] ?? 'External'; - - if ($thz_id) { - $result['master'] = $this->thzMasterModel - ->select('thz_master.*, CONCAT(user_profiles.first_name, " ", user_profiles.last_name) as assignee_name') - ->join('user_profiles', 'user_profiles.id = thz_master.assign_to', 'left') - ->where('thz_master.thz_id', $thz_id) - ->findAll(); - - if (!empty($result['master'])) { - $notes = $this->thzMasterNotesModel->ticketConversationList($thz_id, $returnType); - $result['notes'] = !empty($notes) ? $notes : []; - } else { - // return $this->response->setJSON((['status' => 'error', 'message' => 'No tickets found']))->setStatusCode(400); - throw new \RuntimeException('No tickets found', 400); - } - } else { - // return $this->response->setJSON((['status' => 'error', 'message' => 'No tickets found']))->setStatusCode(404); - throw new \RuntimeException('No tickets found', 404); - } - - if ($returnType === 'api') { - try { - return $this->response->setJSON((['status' => 'success', 'data' => $result]))->setStatusCode(200); - } catch (\Throwable $e) { - $code = ($e->getCode() && $e->getCode() >= 100 && $e->getCode() < 600) ? $e->getCode() : 500; - - $isDbError = $e instanceof \CodeIgniter\Database\Exceptions\DatabaseException - || $e instanceof \mysqli_sql_exception - || $e instanceof \PDOException; - - $context = ['title' => get_class($e), 'type' => get_class($e), 'code' => $code, 'message' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]; - - $this->myLogger->logme('error', "Exception: {message} in {file} on line {line}", $context, 0); - - return $this->response->setJSON([ - 'status' => 'error', - 'message' => $isDbError ? 'Data Access Error' : $e->getMessage(), - 'ref' => $isDbError ? 'database - ' : 'application - ' . $code . ' - ' . $e->getLine() - ])->setStatusCode($code); - } - } else { - - $assign_to = $result['master'][0]['assign_to']; - $mobile = $result['master'][0]['mobile']; - - $toGetPolicyId = (!empty($result['master'][0]['policy_id']) && strtolower($result['master'][0]['policy_id']) !== 'null') - ? $result['master'][0]['policy_id'] - : ''; - - $result['related_tickets'] = $this->thzMasterModel - ->select('thz_master.*, CONCAT(user_profiles.first_name, " ", user_profiles.last_name) as assignee_name') - ->join('user_profiles', 'user_profiles.id = thz_master.assign_to', 'left') - ->where('thz_master.assign_to', $assign_to) - ->where('thz_master.mobile', $mobile) - ->where('thz_master.thz_id !=', $thz_id) - ->where('thz_master.status !=', 'Closed') - ->where('thz_master.status !=', 'Resolved') - ->findAll(); - - $result['assignee'] = $this->userModel->where('is_active', 1)->whereIn('role', ['2', '3', '4'])->findAll(); // enga 5-"head" and 1-"admin" assign pannvaga so dropdown la varakudhathu - // 2,3,4 remain person varannum. - $result['policy_terms'] = $toGetPolicyId ? $this->getPolicyTerms($toGetPolicyId) : ''; - - $result['ticket_type'] = $this->thzTypeModel->where('is_active', 1)->findAll(); - - return $this->loadLayout('thz_notes', $result); - } - } - - public function ticketType() - { - $method = $this->request->getMethod(); // get, post - try { - if ($method === 'get') { - $types = $this->thzTypeModel->select('id,name,is_active')->where('is_active', 1)->findAll(); - if (empty($types)) { - return $this->response->setJSON(['status' => 'error', 'message' => 'No ticket types found'])->setStatusCode(404); - } - return $this->response->setJSON(['status' => 'success', 'data' => $types])->setStatusCode(200); - } - - if ($method === 'post') { - - $data = $this->request->getPost(); - if (!empty($data['id'])) { - $text = "update"; - $result = $this->thzTypeModel->update($data['id'], $data); - $updateID = $data['id']; - } else { - $text = "create"; - $insertID = $this->thzTypeModel->insert($data); - $result = true; - } - - $id = isset($insertID) && !empty($insertID) ? $insertID : ($updateID ?? null); - - return $this->response->setJSON([ - 'status' => $id ? 'success' : 'error', - 'message' => $id ? "Ticket Type {$text}d successfully" : "Unable to {$text} ticket type. Please try again.", - 'id' => $id - ])->setStatusCode($id ? 200 : 400); - } - return $this->response->setJSON(['status' => 'error', 'message' => 'Invalid request method'])->setStatusCode(405); - } catch (\Throwable $e) { - $code = ($e->getCode() && $e->getCode() >= 100 && $e->getCode() < 600) ? $e->getCode() : 500; - - $isDbError = $e instanceof \CodeIgniter\Database\Exceptions\DatabaseException - || $e instanceof \mysqli_sql_exception - || $e instanceof \PDOException; - - $context = ['title' => get_class($e), 'type' => get_class($e), 'code' => $code, 'message' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]; - - $this->myLogger->logme('error', "Exception: {message} in {file} on line {line}", $context, 0); - - return $this->response->setJSON([ - 'status' => 'error', - 'message' => $isDbError ? 'Data Access Error' : $e->getMessage(), - 'ref' => $isDbError ? 'database - ' : 'application - ' . $code . ' - ' . $e->getLine() - ])->setStatusCode($code); - } - } - - public function ticketHistoryList() - { - try { - $data = $this->request->getGet(); - $thz_id = $data['thz_id']; - // $details = $this->thzHistoryModal->whereIn('thz_id', $thz_id)->where('is_active', 1)->get()->getResultArray(); - $details = $this->thzHistoryModel->select('thz_history.*, CONCAT(user_profiles.first_name, " ", user_profiles.last_name) as created_name') - ->join('user_profiles', 'user_profiles.id = thz_history.created_by', 'left') - ->where('thz_history.thz_id', $thz_id)->where('thz_history.is_active', 1) - ->orderBy('thz_history.created_at', 'desc') - ->get()->getResultArray(); - - - - if (empty($details)) { - // return $this->response->setJSON([ 'status' => 'error','message' => 'No History found'])->setStatusCode(404); - throw new \RuntimeException('No History found', 404); - } - - - return $this->response->setJSON(['status' => 'success', 'data' => $details])->setStatusCode(200); - } catch (\Throwable $e) { - $code = ($e->getCode() && $e->getCode() >= 100 && $e->getCode() < 600) ? $e->getCode() : 500; - - $isDbError = $e instanceof \CodeIgniter\Database\Exceptions\DatabaseException - || $e instanceof \mysqli_sql_exception - || $e instanceof \PDOException; - - $context = ['title' => get_class($e), 'type' => get_class($e), 'code' => $code, 'message' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]; - - $this->myLogger->logme('error', "Exception: {message} in {file} on line {line}", $context, 0); - - return $this->response->setJSON([ - 'status' => 'error', - 'message' => $isDbError ? 'Data Access Error' : $e->getMessage(), - 'ref' => $isDbError ? 'database - ' : 'application - ' . $code . ' - ' . $e->getLine() - ])->setStatusCode($code); - } - } - - - /************************************************** PRIVATE FUNCTIONS ********************************************************/ - - - private function fetchTicketsBasedOnrole(array $data): array - { - // $id = $data['thz_id'] ?? null; - $assign_to = $data['assign_to'] ?? null; - $mobile = $data['mobile'] ?? null; - - if (!empty($assign_to)) { - // Tickets assigned to a staff - return $this->thzMasterModel - ->select('thz_master.*, CONCAT(user_profiles.first_name, " ", user_profiles.last_name) as assignee_name') - ->join('user_profiles', 'user_profiles.id = thz_master.assign_to', 'left') - ->where('thz_master.assign_to', $assign_to) - ->orderBy('thz_master.created_at', 'desc') - ->findAll(); - } - - // if (!empty($id) && !empty($mobile)) { - if (!empty($mobile)) { - // Specific ticket by ID and mobile - return $this->thzMasterModel - ->select('thz_master.*, CONCAT(user_profiles.first_name, " ", user_profiles.last_name) as assignee_name') - ->join('user_profiles', 'user_profiles.id = thz_master.assign_to', 'left') - // ->where('thz_id', $id) - ->where('thz_master.mobile', $mobile) - ->orderBy('thz_master.created_at', 'desc') - ->findAll(); - } - - // All tickets (e.g., for managers) - return $this->thzMasterModel - ->select('thz_master.*, CONCAT(user_profiles.first_name, " ", user_profiles.last_name) as assignee_name') - ->join('user_profiles', 'user_profiles.id = thz_master.assign_to', 'left') - ->orderBy('thz_master.created_at', 'desc') - ->findAll(); - } - - - - private function ticketSaveNotification($data, $insertOrUpdate, $id) - { - - $user_email = $data['email'] ?? null; - - $assignee_id = $data['assign_to'] ?? null; - - $assignee_email = $this->findAssigneeEmail($assignee_id); - - $client_id = $data['client_id'] ?? null; - - $emailToNotified = [ - 'user_email' => $user_email, - 'assignee_email' => $assignee_email - ]; - - $ticketId = $id; - - $result = $this->ticketSaveEmailNotificationBasedOnRole($emailToNotified, $insertOrUpdate, $ticketId, $data, $client_id); - - return $result; - } - - private function ticketConversationSaveNotification($data) - { - - $thz_id = $data['thz_id']; // thz is alias of ticket - - $data['subject'] = $this->findSubject($data['thz_id']); - - $assignee_id = $this->findAssigneeId($data['thz_id']); - - $user_email = $this->findUserEmail($data['thz_id']); - - $assignee_email = $this->findAssigneeEmail($assignee_id) ?? ''; - - $sender_mail = $data['notes_by'] == "User" ? $user_email : $assignee_email; - $receiver_mail = $data['notes_by'] == "User" ? $assignee_email : $user_email; - - $templateName = "ticket_conversation_save_notification"; - - $to_email = $receiver_mail; - - $ticketId = $thz_id; - - $message = $data['notes'] ?? ''; - - $this->sendEmail($templateName, $data, $to_email, $ticketId, $message); - - return true; - } - - - private function findAssigneeEmail($assignee_id) - { - - $row = $this->userModel->where('id', $assignee_id)->get()->getRow(); - $assigneeEmail = $row ? $row->email : null; - return $assigneeEmail ? $assigneeEmail : ""; - } - - private function findAssigneeId($ticketId) - { - $row = $this->thzMasterModel->where('thz_id', $ticketId)->get()->getRow(); - $assigneeId = $row ? $row->assign_to : null; - return $assigneeId ? $assigneeId : 0; - } - - private function findUserEmail($ticket_id) - { - $row = $this->thzMasterModel->where('thz_id', $ticket_id)->get()->getRow(); - $email = $row ? $row->email : null; - return $email ? $email : " "; - } - - private function findSubject($ticketId) - { - $row = $this->thzMasterModel->where('thz_id', $ticketId)->get()->getRow(); - $subject = $row ? $row->subject : null; - return $subject ? $subject : " "; - } - - private function ticketSaveEmailNotificationBasedOnRole($emailToNotified, $insertOrUpdate, $ticketId, $data, $client_id) - { - - $user_email = $emailToNotified['user_email'] ?? null; - $assignee_email = $emailToNotified['assignee_email'] ?? null; - - - if (!empty($assignee_email)) { - - switch ($insertOrUpdate) { - - case 'update': - - $this->sendEmail('ticket_save_update_assignee', $data, $assignee_email, $ticketId); - - break; - - case 'create': - - $this->sendEmail('ticket_save_create_assignee', $data, $assignee_email, $ticketId); - - break; - - default: - # code... - break; - } - } - - if (!empty($user_email)) { - - switch ($insertOrUpdate) { - - case 'update': - - $data['assigneeAndStatus'] = empty($assignee_email) - ? "Not Yet Assigned" - : "Assigned With {$assignee_email}"; - - $this->sendEmail('ticket_save_update_user', $data, $user_email, $ticketId); - - - break; - - case 'create': - - $account_manager_email = $this->cientRmModel->findAccountManagerEmail($client_id); - - $cc = getenv(' G_ticketing_system_cc'); - - $template = empty($assignee_email) - ? 'ticket_save_create_user_unassigned' - : 'ticket_save_create_user_assigned'; - - if (!empty($assignee_email)) { - $data['assignee_email'] = $assignee_email; - } - - $this->sendEmail($template, $data, $user_email, $ticketId); - - // send to account manager and if it is more than one email also no problem we send to all account managers - if (!empty($account_manager_email)) { - $this->sendEmail($template, $data, $account_manager_email, $ticketId, $cc); - } - - break; - - default: - # code... - break; - } - } - - return true; - } - - private function updateTicket($data) - { - - $data['updated_by'] = get_session_userid(); - $ticket_id = $data['thz_id']; - $result = $this->thzMasterModel->where('thz_id', $ticket_id)->set($data)->update(); - - return $result; - } - - private function insertTicket($data) - { - $data['created_by'] = get_session_userid(); - $this->thzMasterModel->insert($data); - - return $this->thzMasterModel->insertID(); // returns the inserted row's ID - } - - - private function sendEmail($templateName, $data, $to_email, $ticketId , $cc = "", $message = "", $bcc = "") - { - - $mailTemplate = $this->ticketMailTemplateModel->where('template_name', $templateName)->findAll()[0] ?? []; - - if (empty($mailTemplate)) { - return; - } - - $mailTemplate['subject'] = str_replace('%subject%', $data['subject'] ?? '', $mailTemplate['subject']); - - $mailTemplate['mail_content'] = str_replace('%subject%', $data['subject'] ?? '', $mailTemplate['mail_content']); - - $mailTemplate['mail_content'] = str_replace('%ticketId%', $ticketId ?? '', $mailTemplate['mail_content']); - - $mailTemplate['mail_content'] = str_replace('%message%', $message ?? '', $mailTemplate['mail_content']); - - $mailTemplate['mail_content'] = str_replace('%assignee_email%', $data['assignee_email'] ?? '', $mailTemplate['mail_content']); - - $mailTemplate['mail_content'] = str_replace('%assigneeAndStatus%', $data['assigneeAndStatus'] ?? '', $mailTemplate['mail_content']); - - $from_mail = ""; - $to_mail = $to_email; - $cc_string = $cc; - $subject = $mailTemplate['subject']; - $message = $mailTemplate['mail_content']; - $attachments = ""; - $reply_to = ""; - $bcc_string = $bcc; - - $res = MailHelper::send_email(['from_mail' => $from_mail, 'mail' => $to_mail, 'cc' => $cc_string, 'subject' => $subject, 'message' => $message, 'attachments' => $attachments, 'reply_to' => $reply_to, 'bcc' => $bcc_string]); - } - - - public function getPolicyTerms($client_policy_id) - { - $policy_data = $this->clientPolicyModel->where('is_active', 1)->where('id', $client_policy_id)->first(); - - $policy_terms = []; - if (isset($policy_data['policy_terms']) && !empty($policy_data['policy_terms'])) { - - $raw_terms = json_decode($policy_data['policy_terms'] ?? [], true) ?? []; - - $ticketController = new TicketController(); - $policy_terms = $ticketController->convertTermsToDisplay($raw_terms); - } - - $data['policy_terms'] = $policy_terms; - return view('view_policy_terms', $data); - } -} +thzMasterModel = new ThzMasterModel(); + $this->thzMasterNotesModel = new ThzMasterNotesModel(); + $this->thzTypeModel = new thzTypeModel(); + $this->thzHistoryModel = new ThzHistoryModel(); + $this->thzControllerCleaner = new ThzControllerCleaner(); + $this->userModel = new UserModel(); + $this->clientPolicyModel = new ClientPolicyModel(); + $this->clientModel = new ClientModel(); + $this->cientRmModel = new ClientRMModel(); + $this->ticketMailTemplateModel = new TicketMailTemplateModel(); + $this->myLogger = \Config\Services::mylogger(); + } + + public function index() + { + // + } + + public function ticketSave() + { + try { + $data = $this->request->getPost(); + $references = ""; + if (!empty($data['thz_id'])) { + + $text = "update"; + // here insert history Status. + $old = $this->thzMasterModel->where('thz_id', $data['thz_id'])->get()->getRowArray(); + $result = $this->updateTicket($data); + + $references = ($old && isset($data['status'])) ? $this->handleTicketHistory($old, $data) : "No Details" ; + + $updateID = $data['thz_id']; + } else { + + $text = "create"; + $insertID = $this->insertTicket($data); + $result = true; + $references = ""; + } + + $id = isset($insertID) && !empty($insertID) ? $insertID : $updateID; + + $emailNotificationResult = $this->ticketSaveNotification($data, $insertOrUpdate = $text, $id); + + $this->myLogger->logme('error', 'emailNotificationResult: ' . json_encode($emailNotificationResult)); + + return $this->response->setJSON([ + 'status' => $result ? 'success' : 'error', + 'message' => $result ? "Ticket {$text}d successfully " : "Unable to {$text} ticket. Please try again.", + 'notification' => $emailNotificationResult ? 'Email Notification Success..!!' : 'Email Notification Failed..!!', + 'ref' => $references + ])->setStatusCode($result ? 200 : 400); + + + } catch (\Throwable $e) { + return handle_exception($e, $this->myLogger, $this->response); + } + } + + public function ticketList() + { + + $data['tab_name'] = "Tickets"; + $data['page_name'] = "Tickets"; + try { + $returnType = strtolower($this->request->getGet('return_type') ?? 'api'); + + + $data = $this->request->getGet(); + + if ($returnType === 'web' && in_array(get_role_id(), [3, 4])) { + $data['assign_to'] = $data['assign_to'] ?? get_session_userid(); + } + + + $tickets = $this->fetchTicketsBasedOnrole($data); + + + if ($returnType === 'api') { + if (empty($tickets)) { + $this->myLogger->logme('error', 'empty tickets in ticket list: ' . json_encode($tickets)); + return $this->response->setJSON([ 'status' => 'error','message' => 'No tickets found'])->setStatusCode(404); + } + } else { + $data['ticket_data'] = $tickets; + $data['assignee'] = $this->userModel->where('is_active', 1)->whereIn('role', ['3', '4'])->findAll(); + // enga 5-"head" and 1-"admin" assign pannvaga so dropdown la varakudhathu , 2-"manager l2 " - ivangalum assign pannalam + // 3,4 remain person varannum. + $data['client_list'] = $this->clientModel->getCreatedByUserName(); + $data['ticket_type'] = $this->thzTypeModel->where('is_active', 1)->findAll(); + + return $this->loadLayout('thz_list', $data); + } + + + return $this->response->setJSON([ + 'status' => 'success', + 'data' => $tickets, + ])->setStatusCode(200); + } catch (\Throwable $e) { + return handle_exception($e, $this->myLogger, $this->response); + } + } + + public function ticketConversationSave() + { + + try { + $data = $this->request->getPost(); + + $data['notes_type'] = $data['notes_type'] ?? 'External'; + + $result = $this->thzMasterNotesModel->insert($data); + + if (empty($result)) { + $this->myLogger->logme('error', 'Ticket conversation insert failed..!!: ' . json_encode($result)); + throw new \RuntimeException('No tickets found', 404); + } + + $emailNotificationResult = ($data['notes_type'] === "External") + ? $this->ticketConversationSaveNotification($data) + : false; + + return $this->response->setJSON([ + 'status' => $result ? 'success' : 'error', + 'message' => $result ? "Ticket Notes created successfully" : "Unable to create ticket notes. Please try again.", + 'notification' => $emailNotificationResult ? 'Email Notification Success..!!' : 'Email Notification Failed Or No Need..!!' + ])->setStatusCode($result ? 200 : 400); + + + } catch (\Throwable $e) { + return handle_exception($e, $this->myLogger, $this->response); + } + } + + public function ticketAutoFetchDetails() + { + try { + $data = $this->request->getPost(); + + $client_id = $data['client_id'] ?? null; + $mobile = $data['mobile'] ?? null; + + if ($client_id && $mobile) { + $details = $this->thzMasterModel->ticketAutoFetchDetails($client_id, $mobile); + + if (empty($details)) { + $this->myLogger->logme('error', 'empty AutoFetchDetails for client_id : ' . json_encode($client_id)); + throw new \RuntimeException('No Data found', 400); + } + + $policyIds = array_filter(array_column($details, 'policy_id')); + $clientPolicy = !empty($policyIds) + ? $this->clientPolicyModel->whereIn('id', $policyIds)->where('is_active', 1)->get()->getResultArray() + : []; + + $result['client_details'] = $details; + $result['policy_details'] = $clientPolicy ?? []; + } else { + throw new \RuntimeException('Client and Mobile Not found', 400); + } + + return $this->response->setJSON(['status' => 'success', 'data' => $result])->setStatusCode(200); + } catch (\Throwable $e) { + return handle_exception($e, $this->myLogger, $this->response); + } + } + + public function ticketConversationList() + { + $data = $this->request->getGet(); + + $returnType = strtolower($this->request->getGet('return_type') ?? 'api'); + + $thz_id = $data['thz_id'] ?? null; + + $ticketType = $data['notes_type'] ?? 'External'; + + if ($thz_id) { + $result['master'] = $this->thzMasterModel + ->select('thz_master.*, user_profiles.first_name as assignee_name') + ->join('user_profiles', 'user_profiles.id = thz_master.assign_to', 'left') + ->where('thz_master.thz_id', $thz_id) + ->findAll(); + + if (!empty($result['master'])) { + $notes = $this->thzMasterNotesModel->ticketConversationList($thz_id, $returnType); + $result['notes'] = !empty($notes) ? $notes : []; + } else { + $this->myLogger->logme('error', 'No tickets found for ticket id ' . json_encode($thz_id)); + throw new \RuntimeException('No tickets found', 400); + } + } else { + // return $this->response->setJSON((['status' => 'error', 'message' => 'No tickets found']))->setStatusCode(404); + throw new \RuntimeException('No tickets found', 404); + } + + if ($returnType === 'api') { + try { + return $this->response->setJSON((['status' => 'success', 'data' => $result]))->setStatusCode(200); + } catch (\Throwable $e) { + return handle_exception($e, $this->myLogger, $this->response); + } + } else { + + $assign_to = $result['master'][0]['assign_to']; + $mobile = $result['master'][0]['mobile']; + + $toGetPolicyId = (!empty($result['master'][0]['policy_id']) && strtolower($result['master'][0]['policy_id']) !== 'null') + ? $result['master'][0]['policy_id'] + : ''; + + $result['related_tickets'] = $this->thzMasterModel + ->select('thz_master.*, user_profiles.first_name as assignee_name') + ->join('user_profiles', 'user_profiles.id = thz_master.assign_to', 'left') + ->where('thz_master.assign_to', $assign_to) + ->where('thz_master.mobile', $mobile) + ->where('thz_master.thz_id !=', $thz_id) + ->where('thz_master.status !=', 'Closed') + ->where('thz_master.status !=', 'Resolved') + ->findAll(); + + $result['assignee'] = $this->userModel->where('is_active', 1)->whereIn('role', ['2', '3', '4'])->findAll(); // enga 5-"head" and 1-"admin" assign pannvaga so dropdown la varakudhathu + // 2,3,4 remain person varannum. + $result['policy_terms'] = $toGetPolicyId ? $this->getPolicyTerms($toGetPolicyId) : ''; + + $result['ticket_type'] = $this->thzTypeModel->where('is_active', 1)->findAll(); + + return $this->loadLayout('thz_notes', $result); + } + } + + public function ticketType() + { + $method = $this->request->getMethod(); // get, post + try { + if ($method === 'get') { + $types = $this->thzTypeModel->select('id,name,is_active')->where('is_active', 1)->findAll(); + if (empty($types)) { + $this->myLogger->logme('error', 'No ticket types found '); + return $this->response->setJSON(['status' => 'error', 'message' => 'No ticket types found'])->setStatusCode(404); + } + return $this->response->setJSON(['status' => 'success', 'data' => $types])->setStatusCode(200); + } + + if ($method === 'post') { + + $data = $this->request->getPost(); + if (!empty($data['id'])) { + $text = "update"; + $result = $this->thzTypeModel->update($data['id'], $data); + $updateID = $data['id']; + } else { + $text = "create"; + $insertID = $this->thzTypeModel->insert($data); + $result = true; + } + + $id = isset($insertID) && !empty($insertID) ? $insertID : ($updateID ?? null); + + return $this->response->setJSON([ + 'status' => $id ? 'success' : 'error', + 'message' => $id ? "Ticket Type {$text}d successfully" : "Unable to {$text} ticket type. Please try again.", + 'id' => $id + ])->setStatusCode($id ? 200 : 400); + } + return $this->response->setJSON(['status' => 'error', 'message' => 'Invalid request method'])->setStatusCode(405); + } catch (\Throwable $e) { + return handle_exception($e, $this->myLogger, $this->response); + } + } + + public function ticketHistoryList() + { + try { + $data = $this->request->getGet(); + $thz_id = $data['thz_id']; + // $details = $this->thzHistoryModal->whereIn('thz_id', $thz_id)->where('is_active', 1)->get()->getResultArray(); + $details = $this->thzHistoryModel->select('thz_history.*, user_profiles.first_name as created_name') + ->join('user_profiles', 'user_profiles.id = thz_history.created_by', 'left') + ->where('thz_history.thz_id', $thz_id)->where('thz_history.is_active', 1) + ->orderBy('thz_history.created_at', 'desc') + ->get()->getResultArray(); + + + + if (empty($details)) { + $this->myLogger->logme('error', 'No history details found for ticket id ' . json_encode($thz_id)); + throw new \RuntimeException('No History found', 404); + } + + + return $this->response->setJSON(['status' => 'success', 'data' => $details])->setStatusCode(200); + } catch (\Throwable $e) { + return handle_exception($e, $this->myLogger, $this->response); + } + } + + + /************************************************** PRIVATE FUNCTIONS ********************************************************/ + + + private function fetchTicketsBasedOnrole(array $data): array + { + // $id = $data['thz_id'] ?? null; + $assign_to = $data['assign_to'] ?? null; + $mobile = $data['mobile'] ?? null; + + if (!empty($assign_to)) { + // Tickets assigned to a staff + return $this->thzMasterModel + ->select('thz_master.*, user_profiles.first_name as assignee_name') + ->join('user_profiles', 'user_profiles.id = thz_master.assign_to', 'left') + ->where('thz_master.assign_to', $assign_to) + ->orderBy('thz_master.created_at', 'desc') + ->findAll(); + } + + // if (!empty($id) && !empty($mobile)) { + if (!empty($mobile)) { + // Specific ticket by ID and mobile + return $this->thzMasterModel + ->select('thz_master.*, user_profiles.first_name as assignee_name') + ->join('user_profiles', 'user_profiles.id = thz_master.assign_to', 'left') + // ->where('thz_id', $id) + ->where('thz_master.mobile', $mobile) + ->orderBy('thz_master.created_at', 'desc') + ->findAll(); + } + + // All tickets (e.g., for managers) + return $this->thzMasterModel + ->select('thz_master.*, user_profiles.first_name as assignee_name') + ->join('user_profiles', 'user_profiles.id = thz_master.assign_to', 'left') + ->orderBy('thz_master.created_at', 'desc') + ->findAll(); + } + + + + private function ticketSaveNotification($data, $insertOrUpdate, $id) + { + + $user_email = $data['email'] ?? null; + + $assignee_id = $data['assign_to'] ?? null; + + $assignee_email = $this->findAssigneeEmail($assignee_id); + + $client_id = $data['client_id'] ?? null; + + $emailToNotified = [ + 'user_email' => $user_email, + 'assignee_email' => $assignee_email + ]; + + $ticketId = $id; + + $result = $this->ticketSaveEmailNotificationBasedOnRole($emailToNotified, $insertOrUpdate, $ticketId, $data, $client_id); + + return $result; + } + + private function ticketConversationSaveNotification($data) + { + + $thz_id = $data['thz_id']; // thz is alias of ticket + + $data['subject'] = $this->findSubject($data['thz_id']); + + $assignee_id = $this->findAssigneeId($data['thz_id']); + + $user_email = $this->findUserEmail($data['thz_id']); + + $assignee_email = $this->findAssigneeEmail($assignee_id) ?? ''; + + $sender_mail = $data['notes_by'] == "User" ? $user_email : $assignee_email; + $receiver_mail = $data['notes_by'] == "User" ? $assignee_email : $user_email; + + $templateName = "ticket_conversation_save_notification"; + + $to_email = $receiver_mail; + + $ticketId = $thz_id; + + // $message = $data['notes'] ?? ''; + + $this->sendEmail($templateName, $data, $to_email, $ticketId); + + return true; + } + + + private function findAssigneeEmail($assignee_id) + { + + $row = $this->userModel->where('id', $assignee_id)->get()->getRow(); + $assigneeEmail = $row ? $row->email : null; + return $assigneeEmail ? $assigneeEmail : ""; + } + + private function findAssigneeId($ticketId) + { + $row = $this->thzMasterModel->where('thz_id', $ticketId)->get()->getRow(); + $assigneeId = $row ? $row->assign_to : null; + return $assigneeId ? $assigneeId : 0; + } + + private function findUserEmail($ticket_id) + { + $row = $this->thzMasterModel->where('thz_id', $ticket_id)->get()->getRow(); + $email = $row ? $row->email : null; + return $email ? $email : " "; + } + + private function findSubject($ticketId) + { + $row = $this->thzMasterModel->where('thz_id', $ticketId)->get()->getRow(); + $subject = $row ? $row->subject : null; + return $subject ? $subject : " "; + } + + private function ticketSaveEmailNotificationBasedOnRole($emailToNotified, $insertOrUpdate, $ticketId, $data, $client_id) + { + + $user_email = $emailToNotified['user_email'] ?? null; + $assignee_email = $emailToNotified['assignee_email'] ?? null; + + + if (!empty($assignee_email)) { + + switch ($insertOrUpdate) { + + case 'update': + + $this->sendEmail('ticket_save_update_assignee', $data, $assignee_email, $ticketId); + + break; + + case 'create': + + $this->sendEmail('ticket_save_create_assignee', $data, $assignee_email, $ticketId); + + break; + + default: + # code... + break; + } + } + + if (!empty($user_email)) { + + switch ($insertOrUpdate) { + + case 'update': + + $data['assigneeAndStatus'] = empty($assignee_email) + ? "Not Yet Assigned" + : "Assigned With {$assignee_email}"; + + $this->sendEmail('ticket_save_update_user', $data, $user_email, $ticketId); + + + break; + + case 'create': + + $account_manager_email = $this->cientRmModel->findAccountManagerEmail($client_id); + + $cc = getenv('G_ticketing_system_cc'); + + $this->myLogger->logme('error', "env for cc G_ticketing_system_cc " . $cc); + + $template = empty($assignee_email) + ? 'ticket_save_create_user_unassigned' + : 'ticket_save_create_user_assigned'; + + if (!empty($assignee_email)) { + $data['assignee_email'] = $assignee_email; + } + + $this->sendEmail($template, $data, $user_email, $ticketId); + + // send to account manager and if it is more than one email also no problem we send to all account managers + if (!empty($account_manager_email)) { + $this->myLogger->logme('error', "mail sent for account manager " . json_encode($account_manager_email)); + $this->sendEmail($template, $data, $account_manager_email, $ticketId, $cc); + } else { + $this->myLogger->logme('error', "mail not sent for account manager "); + } + + break; + + default: + # code... + break; + } + } + + return true; + } + + private function updateTicket($data) + { + + $data['updated_by'] = get_session_userid(); + $ticket_id = $data['thz_id']; + $result = $this->thzMasterModel->where('thz_id', $ticket_id)->set($data)->update(); + + return $result; + } + + private function insertTicket($data) + { + $data['created_by'] = get_session_userid(); + $this->thzMasterModel->insert($data); + + return $this->thzMasterModel->insertID(); // returns the inserted row's ID + } + + + private function sendEmail($templateName, $data, $to_email, $ticketId, $cc = "", $bcc = "") + { + + $mailTemplate = $this->ticketMailTemplateModel->where('template_name', $templateName)->findAll()[0] ?? []; + + if (empty($mailTemplate)) { + $this->myLogger->logme('error', 'No Mail Template Found To send email in ticketing system'); + return; + } + + if (empty($cc)) { + $this->myLogger->logme('error', 'empty cc attached for template name : ' . json_encode($templateName)); + } else { + $this->myLogger->logme('error', "cc attached for template name : " . json_encode($templateName)); + } + + $mailTemplate['subject'] = str_replace('%subject%', $data['subject'] ?? '', $mailTemplate['subject']); + + $mailTemplate['mail_content'] = str_replace('%subject%', $data['subject'] ?? '', $mailTemplate['mail_content']); + + $mailTemplate['mail_content'] = str_replace('%ticketId%', $ticketId ?? '', $mailTemplate['mail_content']); + + $mailTemplate['mail_content'] = str_replace('%message%', $data['notes'] ?? '', $mailTemplate['mail_content']); + + $mailTemplate['mail_content'] = str_replace('%assignee_email%', $data['assignee_email'] ?? '', $mailTemplate['mail_content']); + + $mailTemplate['mail_content'] = str_replace('%assigneeAndStatus%', $data['assigneeAndStatus'] ?? '', $mailTemplate['mail_content']); + + $from_mail = ""; + $to_mail = $to_email; + $cc_string = $cc; + $subject = $mailTemplate['subject']; + $message = $mailTemplate['mail_content']; + $attachments = ""; + $reply_to = ""; + $bcc_string = $bcc; + + $res = MailHelper::send_email(['from_mail' => $from_mail, 'mail' => $to_mail, 'cc' => $cc_string, 'subject' => $subject, 'message' => $message, 'attachments' => $attachments, 'reply_to' => $reply_to, 'bcc' => $bcc_string]); + + $this->myLogger->logme('error', 'Mail Response : ' . json_encode($res)); + } + + + public function getPolicyTerms($client_policy_id) + { + $policy_data = $this->clientPolicyModel->where('is_active', 1)->where('id', $client_policy_id)->first(); + + $policy_terms = []; + if (isset($policy_data['policy_terms']) && !empty($policy_data['policy_terms'])) { + + $raw_terms = json_decode($policy_data['policy_terms'] ?? [], true) ?? []; + + $ticketController = new TicketController(); + $policy_terms = $ticketController->convertTermsToDisplay($raw_terms); + } + + $data['policy_terms'] = $policy_terms; + return view('view_policy_terms', $data); + } + + + private function handleTicketHistory(array $old, array $data): string + { + if ($old['status'] != $data['status']) { + $history = [ + 'thz_id' => $data['thz_id'], + 'field_name' => 'status', + 'display_name' => 'Status', + 'old_value' => $old['status'], + 'new_value' => $data['status'], + 'is_active' => 1 + ]; + + if (!empty(get_session_userid())) { + $history['created_by'] = get_session_userid(); + } + + $hist_id = $this->thzHistoryModel->insert($history); + + return $old['status'] . " - " . $data['status'] . " - " . $hist_id; + } + + return $old['status'] . " - " . $data['status']; + } + + + + + +} diff --git a/app/Controllers/ThzController_old.php b/app/Controllers/ThzController_old.php new file mode 100644 index 00000000..0dea90c1 --- /dev/null +++ b/app/Controllers/ThzController_old.php @@ -0,0 +1,723 @@ +thzMasterModel = new ThzMasterModel(); + $this->thzMasterNotesModel = new ThzMasterNotesModel(); + $this->thzTypeModel = new thzTypeModel(); + $this->thzHistoryModel = new ThzHistoryModel(); + $this->thzControllerCleaner = new ThzControllerCleaner(); + $this->userModel = new UserModel(); + $this->clientPolicyModel = new ClientPolicyModel(); + $this->clientModel = new ClientModel(); + $this->cientRmModel = new ClientRMModel(); + $this->ticketMailTemplateModel = new TicketMailTemplateModel(); + $this->myLogger = \Config\Services::mylogger(); + } + + public function index() + { + // + } + + public function ticketSave() + { + try { + $data = $this->request->getPost(); + $references = ""; + if (!empty($data['thz_id'])) { + + $text = "update"; + // here insert history Status. + $old = $this->thzMasterModel->where('thz_id', $data['thz_id'])->get()->getRowArray(); + $result = $this->updateTicket($data); + + if ($old && isset($data['status'])) { + + if ($old['status'] != $data['status']) { + $history = [ + 'thz_id' => $data['thz_id'], + 'field_name' => 'status', + 'display_name' => 'Status', + 'old_value' => $old['status'], + 'new_value' => $data['status'], + 'is_active' => 1 + ]; + + if (!empty(get_session_userid())) { + $history['created_by'] = get_session_userid(); + } + + $hist_id = $this->thzHistoryModel->insert($history); + $references = $old['status'] . " - " . $data['status'] . " - " . $hist_id; + } else { + $references = $old['status'] . " - " . $data['status']; + } + } else { + $references = "No Details"; + } + + $updateID = $data['thz_id']; + } else { + + $text = "create"; + $insertID = $this->insertTicket($data); + $result = true; + $references = ""; + } + + $id = isset($insertID) && !empty($insertID) ? $insertID : $updateID; + + $emailNotificationResult = $this->ticketSaveNotification($data, $insertOrUpdate = $text, $id); + + return $this->response->setJSON([ + 'status' => $result ? 'success' : 'error', + 'message' => $result ? "Ticket {$text}d successfully " : "Unable to {$text} ticket. Please try again.", + 'notification' => $emailNotificationResult ? 'Email Notification Success..!!' : 'Email Notification Failed..!!', + 'ref' => $references + ])->setStatusCode($result ? 200 : 400); + } catch (\Throwable $e) { + $code = ($e->getCode() && $e->getCode() >= 100 && $e->getCode() < 600) ? $e->getCode() : 500; + + $isDbError = $e instanceof \CodeIgniter\Database\Exceptions\DatabaseException + || $e instanceof \mysqli_sql_exception + || $e instanceof \PDOException; + + $context = ['title' => get_class($e), 'type' => get_class($e), 'code' => $code, 'message' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]; + + $this->myLogger->logme('error', "Exception: {message} in {file} on line {line}", $context, 0); + + return $this->response->setJSON([ + 'status' => 'error', + 'message' => $isDbError ? 'Data Access Error' : $e->getMessage(), + 'ref' => $isDbError ? 'database - ' : 'application - ' . $code . ' - ' . $e->getLine() + ])->setStatusCode($code); + } + } + + public function ticketList() + { + + try { + $returnType = strtolower($this->request->getGet('return_type') ?? 'api'); + + + $data = $this->request->getGet(); + if ($returnType === 'web' && in_array(get_role_id(), [2, 3, 4])) { + $data['assign_to'] = $data['assign_to'] ?? get_session_userid(); + } + + $tickets = $this->fetchTicketsBasedOnrole($data); + + + if ($returnType === 'api') { + if (empty($tickets)) { + // return $this->response->setJSON([ 'status' => 'error','message' => 'No tickets found'])->setStatusCode(404); + throw new \RuntimeException('No tickets found', 400); + } + } else { + + $data['page_name'] = "Tickets"; + $data['ticket_data'] = $tickets; + $data['assignee'] = $this->userModel->where('is_active', 1)->whereIn('role', ['2', '3', '4'])->findAll(); // enga 5-"head" and 1-"admin" assign pannvaga so dropdown la varakudhathu + // 2,3,4 remain person varannum. + $data['client_list'] = $this->clientModel->getCreatedByUserName(); + $data['ticket_type'] = $this->thzTypeModel->where('is_active', 1)->findAll(); + + return $this->loadLayout('thz_list', $data); + } + + + return $this->response->setJSON([ + 'status' => 'success', + 'data' => $tickets, + ])->setStatusCode(200); + } catch (\Throwable $e) { + $code = ($e->getCode() && $e->getCode() >= 100 && $e->getCode() < 600) ? $e->getCode() : 500; + + $isDbError = $e instanceof \CodeIgniter\Database\Exceptions\DatabaseException + || $e instanceof \mysqli_sql_exception + || $e instanceof \PDOException; + + $context = ['title' => get_class($e), 'type' => get_class($e), 'code' => $code, 'message' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]; + + $this->myLogger->logme('error', "Exception: {message} in {file} on line {line}", $context, 0); + + return $this->response->setJSON([ + 'status' => 'error', + 'message' => $isDbError ? 'Data Access Error' : $e->getMessage(), + 'ref' => $isDbError ? 'database - ' : 'application - ' . $code . ' - ' . $e->getLine() + ])->setStatusCode($code); + } + } + + public function ticketConversationSave() + { + + try { + $data = $this->request->getPost(); + + $data['notes_type'] = $data['notes_type'] ?? 'External'; + + $result = $this->thzMasterNotesModel->insert($data); + + if (empty($result)) { + // return $this->response->setJSON((['status' => 'error', 'message' => 'No tickets found']))->setStatusCode(404); + throw new \RuntimeException('No tickets found', 404); + } + + if ($data['notes_type'] == "External") { + $emailNotificationResult = $this->ticketConversationSaveNotification($data); + } else { + $emailNotificationResult = false; + } + + + + return $this->response->setJSON([ + 'status' => $result ? 'success' : 'error', + 'message' => $result ? "Ticket Notes created successfully" : "Unable to create ticket notes. Please try again.", + 'notification' => $emailNotificationResult ? 'Email Notification Success..!!' : 'Email Notification Failed Or No Need..!!' + ])->setStatusCode($result ? 200 : 400); + } catch (\Throwable $e) { + $code = ($e->getCode() && $e->getCode() >= 100 && $e->getCode() < 600) ? $e->getCode() : 500; + + $isDbError = $e instanceof \CodeIgniter\Database\Exceptions\DatabaseException + || $e instanceof \mysqli_sql_exception + || $e instanceof \PDOException; + + $context = ['title' => get_class($e), 'type' => get_class($e), 'code' => $code, 'message' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]; + + $this->myLogger->logme('error', "Exception: {message} in {file} on line {line}", $context, 0); + + return $this->response->setJSON([ + 'status' => 'error', + 'message' => $isDbError ? 'Data Access Error' : $e->getMessage(), + 'ref' => $isDbError ? 'database - ' : 'application - ' . $code . ' - ' . $e->getLine() + ])->setStatusCode($code); + } + } + + public function ticketAutoFetchDetails() + { + try { + $data = $this->request->getPost(); + + $client_id = $data['client_id'] ?? null; + $mobile = $data['mobile'] ?? null; + + if ($client_id && $mobile) { + $details = $this->thzMasterModel->ticketAutoFetchDetails($client_id, $mobile); + + if (empty($details)) { + throw new \RuntimeException('No Data found', 400); + } + + $policyIds = array_filter(array_column($details, 'policy_id')); + $clientPolicy = !empty($policyIds) + ? $this->clientPolicyModel->whereIn('id', $policyIds)->where('is_active', 1)->get()->getResultArray() + : []; + + $result['client_details'] = $details; + $result['policy_details'] = $clientPolicy ?? []; + } else { + throw new \RuntimeException('Client and Mobile Not found', 400); + } + + return $this->response->setJSON(['status' => 'success', 'data' => $result])->setStatusCode(200); + } catch (\Throwable $e) { + $code = ($e->getCode() && $e->getCode() >= 100 && $e->getCode() < 600) ? $e->getCode() : 500; + + $isDbError = $e instanceof \CodeIgniter\Database\Exceptions\DatabaseException + || $e instanceof \mysqli_sql_exception + || $e instanceof \PDOException; + + $context = ['title' => get_class($e), 'type' => get_class($e), 'code' => $code, 'message' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]; + + $this->myLogger->logme('error', "Exception: {message} in {file} on line {line}", $context, 0); + + return $this->response->setJSON([ + 'status' => 'error', + 'message' => $isDbError ? 'Data Access Error' : $e->getMessage(), + 'ref' => $isDbError ? 'database - ' : 'application - ' . $code . ' - ' . $e->getLine() + ])->setStatusCode($code); + } + } + + public function ticketConversationList() + { + $data = $this->request->getGet(); + + $returnType = strtolower($this->request->getGet('return_type') ?? 'api'); + + $thz_id = $data['thz_id'] ?? null; + + $ticketType = $data['notes_type'] ?? 'External'; + + if ($thz_id) { + $result['master'] = $this->thzMasterModel + ->select('thz_master.*, CONCAT(user_profiles.first_name, " ", user_profiles.last_name) as assignee_name') + ->join('user_profiles', 'user_profiles.id = thz_master.assign_to', 'left') + ->where('thz_master.thz_id', $thz_id) + ->findAll(); + + if (!empty($result['master'])) { + $notes = $this->thzMasterNotesModel->ticketConversationList($thz_id, $returnType); + $result['notes'] = !empty($notes) ? $notes : []; + } else { + // return $this->response->setJSON((['status' => 'error', 'message' => 'No tickets found']))->setStatusCode(400); + throw new \RuntimeException('No tickets found', 400); + } + } else { + // return $this->response->setJSON((['status' => 'error', 'message' => 'No tickets found']))->setStatusCode(404); + throw new \RuntimeException('No tickets found', 404); + } + + if ($returnType === 'api') { + try { + return $this->response->setJSON((['status' => 'success', 'data' => $result]))->setStatusCode(200); + } catch (\Throwable $e) { + $code = ($e->getCode() && $e->getCode() >= 100 && $e->getCode() < 600) ? $e->getCode() : 500; + + $isDbError = $e instanceof \CodeIgniter\Database\Exceptions\DatabaseException + || $e instanceof \mysqli_sql_exception + || $e instanceof \PDOException; + + $context = ['title' => get_class($e), 'type' => get_class($e), 'code' => $code, 'message' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]; + + $this->myLogger->logme('error', "Exception: {message} in {file} on line {line}", $context, 0); + + return $this->response->setJSON([ + 'status' => 'error', + 'message' => $isDbError ? 'Data Access Error' : $e->getMessage(), + 'ref' => $isDbError ? 'database - ' : 'application - ' . $code . ' - ' . $e->getLine() + ])->setStatusCode($code); + } + } else { + + $assign_to = $result['master'][0]['assign_to']; + $mobile = $result['master'][0]['mobile']; + + $toGetPolicyId = (!empty($result['master'][0]['policy_id']) && strtolower($result['master'][0]['policy_id']) !== 'null') + ? $result['master'][0]['policy_id'] + : ''; + + $result['related_tickets'] = $this->thzMasterModel + ->select('thz_master.*, CONCAT(user_profiles.first_name, " ", user_profiles.last_name) as assignee_name') + ->join('user_profiles', 'user_profiles.id = thz_master.assign_to', 'left') + ->where('thz_master.assign_to', $assign_to) + ->where('thz_master.mobile', $mobile) + ->where('thz_master.thz_id !=', $thz_id) + ->where('thz_master.status !=', 'Closed') + ->where('thz_master.status !=', 'Resolved') + ->findAll(); + + $result['assignee'] = $this->userModel->where('is_active', 1)->whereIn('role', ['2', '3', '4'])->findAll(); // enga 5-"head" and 1-"admin" assign pannvaga so dropdown la varakudhathu + // 2,3,4 remain person varannum. + $result['policy_terms'] = $toGetPolicyId ? $this->getPolicyTerms($toGetPolicyId) : ''; + + $result['ticket_type'] = $this->thzTypeModel->where('is_active', 1)->findAll(); + + return $this->loadLayout('thz_notes', $result); + } + } + + public function ticketType() + { + $method = $this->request->getMethod(); // get, post + try { + if ($method === 'get') { + $types = $this->thzTypeModel->select('id,name,is_active')->where('is_active', 1)->findAll(); + if (empty($types)) { + return $this->response->setJSON(['status' => 'error', 'message' => 'No ticket types found'])->setStatusCode(404); + } + return $this->response->setJSON(['status' => 'success', 'data' => $types])->setStatusCode(200); + } + + if ($method === 'post') { + + $data = $this->request->getPost(); + if (!empty($data['id'])) { + $text = "update"; + $result = $this->thzTypeModel->update($data['id'], $data); + $updateID = $data['id']; + } else { + $text = "create"; + $insertID = $this->thzTypeModel->insert($data); + $result = true; + } + + $id = isset($insertID) && !empty($insertID) ? $insertID : ($updateID ?? null); + + return $this->response->setJSON([ + 'status' => $id ? 'success' : 'error', + 'message' => $id ? "Ticket Type {$text}d successfully" : "Unable to {$text} ticket type. Please try again.", + 'id' => $id + ])->setStatusCode($id ? 200 : 400); + } + return $this->response->setJSON(['status' => 'error', 'message' => 'Invalid request method'])->setStatusCode(405); + } catch (\Throwable $e) { + $code = ($e->getCode() && $e->getCode() >= 100 && $e->getCode() < 600) ? $e->getCode() : 500; + + $isDbError = $e instanceof \CodeIgniter\Database\Exceptions\DatabaseException + || $e instanceof \mysqli_sql_exception + || $e instanceof \PDOException; + + $context = ['title' => get_class($e), 'type' => get_class($e), 'code' => $code, 'message' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]; + + $this->myLogger->logme('error', "Exception: {message} in {file} on line {line}", $context, 0); + + return $this->response->setJSON([ + 'status' => 'error', + 'message' => $isDbError ? 'Data Access Error' : $e->getMessage(), + 'ref' => $isDbError ? 'database - ' : 'application - ' . $code . ' - ' . $e->getLine() + ])->setStatusCode($code); + } + } + + public function ticketHistoryList() + { + try { + $data = $this->request->getGet(); + $thz_id = $data['thz_id']; + // $details = $this->thzHistoryModal->whereIn('thz_id', $thz_id)->where('is_active', 1)->get()->getResultArray(); + $details = $this->thzHistoryModel->select('thz_history.*, CONCAT(user_profiles.first_name, " ", user_profiles.last_name) as created_name') + ->join('user_profiles', 'user_profiles.id = thz_history.created_by', 'left') + ->where('thz_history.thz_id', $thz_id)->where('thz_history.is_active', 1) + ->orderBy('thz_history.created_at', 'desc') + ->get()->getResultArray(); + + + + if (empty($details)) { + // return $this->response->setJSON([ 'status' => 'error','message' => 'No History found'])->setStatusCode(404); + throw new \RuntimeException('No History found', 404); + } + + + return $this->response->setJSON(['status' => 'success', 'data' => $details])->setStatusCode(200); + } catch (\Throwable $e) { + $code = ($e->getCode() && $e->getCode() >= 100 && $e->getCode() < 600) ? $e->getCode() : 500; + + $isDbError = $e instanceof \CodeIgniter\Database\Exceptions\DatabaseException + || $e instanceof \mysqli_sql_exception + || $e instanceof \PDOException; + + $context = ['title' => get_class($e), 'type' => get_class($e), 'code' => $code, 'message' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]; + + $this->myLogger->logme('error', "Exception: {message} in {file} on line {line}", $context, 0); + + return $this->response->setJSON([ + 'status' => 'error', + 'message' => $isDbError ? 'Data Access Error' : $e->getMessage(), + 'ref' => $isDbError ? 'database - ' : 'application - ' . $code . ' - ' . $e->getLine() + ])->setStatusCode($code); + } + } + + + /************************************************** PRIVATE FUNCTIONS ********************************************************/ + + + private function fetchTicketsBasedOnrole(array $data): array + { + // $id = $data['thz_id'] ?? null; + $assign_to = $data['assign_to'] ?? null; + $mobile = $data['mobile'] ?? null; + + if (!empty($assign_to)) { + // Tickets assigned to a staff + return $this->thzMasterModel + ->select('thz_master.*, CONCAT(user_profiles.first_name, " ", user_profiles.last_name) as assignee_name') + ->join('user_profiles', 'user_profiles.id = thz_master.assign_to', 'left') + ->where('thz_master.assign_to', $assign_to) + ->orderBy('thz_master.created_at', 'desc') + ->findAll(); + } + + // if (!empty($id) && !empty($mobile)) { + if (!empty($mobile)) { + // Specific ticket by ID and mobile + return $this->thzMasterModel + ->select('thz_master.*, CONCAT(user_profiles.first_name, " ", user_profiles.last_name) as assignee_name') + ->join('user_profiles', 'user_profiles.id = thz_master.assign_to', 'left') + // ->where('thz_id', $id) + ->where('thz_master.mobile', $mobile) + ->orderBy('thz_master.created_at', 'desc') + ->findAll(); + } + + // All tickets (e.g., for managers) + return $this->thzMasterModel + ->select('thz_master.*, CONCAT(user_profiles.first_name, " ", user_profiles.last_name) as assignee_name') + ->join('user_profiles', 'user_profiles.id = thz_master.assign_to', 'left') + ->orderBy('thz_master.created_at', 'desc') + ->findAll(); + } + + + + private function ticketSaveNotification($data, $insertOrUpdate, $id) + { + + $user_email = $data['email'] ?? null; + + $assignee_id = $data['assign_to'] ?? null; + + $assignee_email = $this->findAssigneeEmail($assignee_id); + + $client_id = $data['client_id'] ?? null; + + $emailToNotified = [ + 'user_email' => $user_email, + 'assignee_email' => $assignee_email + ]; + + $ticketId = $id; + + $result = $this->ticketSaveEmailNotificationBasedOnRole($emailToNotified, $insertOrUpdate, $ticketId, $data, $client_id); + + return $result; + } + + private function ticketConversationSaveNotification($data) + { + + $thz_id = $data['thz_id']; // thz is alias of ticket + + $data['subject'] = $this->findSubject($data['thz_id']); + + $assignee_id = $this->findAssigneeId($data['thz_id']); + + $user_email = $this->findUserEmail($data['thz_id']); + + $assignee_email = $this->findAssigneeEmail($assignee_id) ?? ''; + + $sender_mail = $data['notes_by'] == "User" ? $user_email : $assignee_email; + $receiver_mail = $data['notes_by'] == "User" ? $assignee_email : $user_email; + + $templateName = "ticket_conversation_save_notification"; + + $to_email = $receiver_mail; + + $ticketId = $thz_id; + + $message = $data['notes'] ?? ''; + + $this->sendEmail($templateName, $data, $to_email, $ticketId, $message); + + return true; + } + + + private function findAssigneeEmail($assignee_id) + { + + $row = $this->userModel->where('id', $assignee_id)->get()->getRow(); + $assigneeEmail = $row ? $row->email : null; + return $assigneeEmail ? $assigneeEmail : ""; + } + + private function findAssigneeId($ticketId) + { + $row = $this->thzMasterModel->where('thz_id', $ticketId)->get()->getRow(); + $assigneeId = $row ? $row->assign_to : null; + return $assigneeId ? $assigneeId : 0; + } + + private function findUserEmail($ticket_id) + { + $row = $this->thzMasterModel->where('thz_id', $ticket_id)->get()->getRow(); + $email = $row ? $row->email : null; + return $email ? $email : " "; + } + + private function findSubject($ticketId) + { + $row = $this->thzMasterModel->where('thz_id', $ticketId)->get()->getRow(); + $subject = $row ? $row->subject : null; + return $subject ? $subject : " "; + } + + private function ticketSaveEmailNotificationBasedOnRole($emailToNotified, $insertOrUpdate, $ticketId, $data, $client_id) + { + + $user_email = $emailToNotified['user_email'] ?? null; + $assignee_email = $emailToNotified['assignee_email'] ?? null; + + + if (!empty($assignee_email)) { + + switch ($insertOrUpdate) { + + case 'update': + + $this->sendEmail('ticket_save_update_assignee', $data, $assignee_email, $ticketId); + + break; + + case 'create': + + $this->sendEmail('ticket_save_create_assignee', $data, $assignee_email, $ticketId); + + break; + + default: + # code... + break; + } + } + + if (!empty($user_email)) { + + switch ($insertOrUpdate) { + + case 'update': + + $data['assigneeAndStatus'] = empty($assignee_email) + ? "Not Yet Assigned" + : "Assigned With {$assignee_email}"; + + $this->sendEmail('ticket_save_update_user', $data, $user_email, $ticketId); + + + break; + + case 'create': + + $account_manager_email = $this->cientRmModel->findAccountManagerEmail($client_id); + + $cc = getenv(' G_ticketing_system_cc'); + + $template = empty($assignee_email) + ? 'ticket_save_create_user_unassigned' + : 'ticket_save_create_user_assigned'; + + if (!empty($assignee_email)) { + $data['assignee_email'] = $assignee_email; + } + + $this->sendEmail($template, $data, $user_email, $ticketId); + + // send to account manager and if it is more than one email also no problem we send to all account managers + if (!empty($account_manager_email)) { + $this->sendEmail($template, $data, $account_manager_email, $ticketId, $cc); + } + + break; + + default: + # code... + break; + } + } + + return true; + } + + private function updateTicket($data) + { + + $data['updated_by'] = get_session_userid(); + $ticket_id = $data['thz_id']; + $result = $this->thzMasterModel->where('thz_id', $ticket_id)->set($data)->update(); + + return $result; + } + + private function insertTicket($data) + { + $data['created_by'] = get_session_userid(); + $this->thzMasterModel->insert($data); + + return $this->thzMasterModel->insertID(); // returns the inserted row's ID + } + + + private function sendEmail($templateName, $data, $to_email, $ticketId , $cc = "", $message = "", $bcc = "") + { + + $mailTemplate = $this->ticketMailTemplateModel->where('template_name', $templateName)->findAll()[0] ?? []; + + if (empty($mailTemplate)) { + return; + } + + $mailTemplate['subject'] = str_replace('%subject%', $data['subject'] ?? '', $mailTemplate['subject']); + + $mailTemplate['mail_content'] = str_replace('%subject%', $data['subject'] ?? '', $mailTemplate['mail_content']); + + $mailTemplate['mail_content'] = str_replace('%ticketId%', $ticketId ?? '', $mailTemplate['mail_content']); + + $mailTemplate['mail_content'] = str_replace('%message%', $message ?? '', $mailTemplate['mail_content']); + + $mailTemplate['mail_content'] = str_replace('%assignee_email%', $data['assignee_email'] ?? '', $mailTemplate['mail_content']); + + $mailTemplate['mail_content'] = str_replace('%assigneeAndStatus%', $data['assigneeAndStatus'] ?? '', $mailTemplate['mail_content']); + + $from_mail = ""; + $to_mail = $to_email; + $cc_string = $cc; + $subject = $mailTemplate['subject']; + $message = $mailTemplate['mail_content']; + $attachments = ""; + $reply_to = ""; + $bcc_string = $bcc; + + $res = MailHelper::send_email(['from_mail' => $from_mail, 'mail' => $to_mail, 'cc' => $cc_string, 'subject' => $subject, 'message' => $message, 'attachments' => $attachments, 'reply_to' => $reply_to, 'bcc' => $bcc_string]); + } + + + public function getPolicyTerms($client_policy_id) + { + $policy_data = $this->clientPolicyModel->where('is_active', 1)->where('id', $client_policy_id)->first(); + + $policy_terms = []; + if (isset($policy_data['policy_terms']) && !empty($policy_data['policy_terms'])) { + + $raw_terms = json_decode($policy_data['policy_terms'] ?? [], true) ?? []; + + $ticketController = new TicketController(); + $policy_terms = $ticketController->convertTermsToDisplay($raw_terms); + } + + $data['policy_terms'] = $policy_terms; + return view('view_policy_terms', $data); + } +} diff --git a/app/Controllers/VidalApiController.php b/app/Controllers/VidalApiController.php index 36dc3f01..b7418dbf 100644 --- a/app/Controllers/VidalApiController.php +++ b/app/Controllers/VidalApiController.php @@ -145,7 +145,7 @@ class VidalApiController extends BaseController 'Authorization:' .getenv('VIDAL_API_KEY').'', ]; - $body = [ + $body = [ 'username' => getenv('VIDAL_API_USERNAME'), 'password' => getenv('VIDAL_API_PASSWORD'), 'policyNo' => $postData['policyNo'] ?? '', @@ -191,15 +191,14 @@ class VidalApiController extends BaseController return $this->response->setJSON($response); } - - - public function enrollment(){ + public function enrollment() + { $postData = $this->request->getJSON(true); helper('api'); - $url = ''. getenv('VIDAL_API_BASE_URL').'/enrollmendataservice'; + $url = getenv('VIDAL_API_BASE_URL').'/enrollmendataservice'; $method = 'POST'; $headers = [ diff --git a/app/Helpers/NhanceWelnessSsoHelper.php b/app/Helpers/NhanceWelnessSsoHelper.php new file mode 100644 index 00000000..e9e5c24d --- /dev/null +++ b/app/Helpers/NhanceWelnessSsoHelper.php @@ -0,0 +1,410 @@ +generateSSOUrl($userParams); + } +} + +if (!function_exists('decrypt_nhance_sso_params')) { + /** + * Decrypt Nhance SSO parameters for testing + * + * @param string|null $encryptedParams Encrypted parameters, uses sample if null + * @return array Decrypted user parameters + */ + function decrypt_nhance_sso_params($encryptedParams = null) { + $helper = new NhanceSsoHelper(); + return $helper->decryptUserParams($encryptedParams); + } +} + +if (!function_exists('test_nhance_sso_encryption')) { + /** + * Test Nhance SSO encryption/decryption functionality + * + * @return array Test results + */ + function test_nhance_sso_encryption() { + $helper = new NhanceSsoHelper(); + return $helper->runTests(); + } +} + +/** + * Nhance SSO Helper Class + */ +class NhanceWelnessSsoHelper { + + private static $baseUrl = 'https://web.samuraijack.xyz/sso'; + private static $clientId = 'nhance-gt-2tx7'; + private static $encryptionKey = '32D1D5535157AF3D4667ADAB0CC795D77D022BB281AD3272EB134C72BD0B185E'; + private static $algorithm = 'aes-256-cbc'; + + /** + * Get sample user parameters + */ + private static function getSampleUserParams() { + return [ + 'name' => 'John Doe 3', + 'email' => 'john.doe3@email.com', + 'memberId' => 'TEST-REL-01', + 'gender' => 'Male', + 'dob' => '1997-01-01', + 'policyName' => 'Nhance DEMO', + 'phone' => '6676126763', + 'employeeId' => 'EMP-NHANCE-TEST-03', + 'policyNumber' => "EMP-NHANCE-TEST-03", + 'policyStartDate' => '2025-09-08', + 'policyEndDate' => '2026-09-08', + 'moduleName' => 'home', + 'relation' => 'self', + 'planId' => 'NHANCE-PLAN-1', + + ]; + } + + /** + * Get sample encrypted parameters for testing + */ + private static function getSampleEncryptedParams() { + // Generate sample encrypted params using sample data + $sampleParams = (SELF::getSampleUserParams()); + return SELF::encryptUserParams($sampleParams); + } + + /** + * Encrypt user parameters using AES-256-CBC + */ + private static function encryptUserParams($userParams) { + try { + // $jsonData = json_encode($userParams); + + // // Generate a random IV + // $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length(SELF::$algorithm)); + // // $iv = 'getvisitappdotcom'; + + // // Convert hex key to binary + // $key = hex2bin(SELF::$encryptionKey); + // // $key = (SELF::$encryptionKey); + + // // Encrypt the data + // $encrypted = openssl_encrypt($jsonData, SELF::$algorithm, $key, 0, $iv); + + // if ($encrypted === false) { + // throw new Exception("Encryption failed"); + // } + + // // Combine IV and encrypted data, then encode + // $encryptedData = base64_encode($iv . base64_decode($encrypted)); + + // // Make URL safe + // return str_replace(['+', '/', '='], ['-', '_', ''], $encryptedData); + + + + + $key = "getvisitappdotcom"; + // Step 1: Build plaintext exactly like Node (raw join with '&') + $str = ''; + foreach ($userParams as $k => $v) { + $str .= '&' . $k . '=' . $v; + } + $plainText = substr($str, 1); // remove leading & + + // Step 2: Derive 32-byte key with SHA256 + $sha256Key = hash('sha256', $key, true); + + // Step 3: Fixed IV + $iv = "getvisitappdocom"; // 16 bytes + + // Step 4: Encrypt + $cipherRaw = openssl_encrypt( + $plainText, + 'aes-256-cbc', + $sha256Key, + OPENSSL_RAW_DATA, + $iv + ); + + // Step 5: base64url encode + return rtrim(strtr(base64_encode($cipherRaw), '+/', '-_'), '='); + + + } catch (Exception $e) { + log_message('error', 'Nhance SSO Encryption Error: ' . $e->getMessage()); + throw new Exception("Encryption failed: " . $e->getMessage()); + } + } + + /** + * Decrypt user parameters for testing purposes + */ + public static function decryptUserParams($encryptedParams = null) { + try { + // Use sample encrypted params if none provided + if ($encryptedParams === null) { + $encryptedParams = SELF::getSampleEncryptedParams(); + log_message('info', 'Using sample encrypted parameters for decryption test'); + } + + // Handle URL format if full URL is passed + if (strpos($encryptedParams, 'userParams=') !== false) { + $encryptedParams = SELF::extractParamsFromUrl($encryptedParams); + } + + // Make URL-safe characters back to base64 + $encryptedParams = str_replace(['-', '_'], ['+', '/'], $encryptedParams); + + // Add padding if needed + $encryptedParams = $encryptedParams . str_repeat('=', (4 - strlen($encryptedParams) % 4) % 4); + + // Decode base64 + $data = base64_decode($encryptedParams); + + if ($data === false) { + throw new Exception("Failed to decode base64 data"); + } + + // Extract IV and encrypted data + $ivLength = openssl_cipher_iv_length(SELF::$algorithm); + $iv = substr($data, 0, $ivLength); + $encrypted = base64_encode(substr($data, $ivLength)); + + // Convert hex key to binary + $key = hex2bin(SELF::$encryptionKey); + + // Decrypt the data + $decrypted = openssl_decrypt($encrypted, SELF::$algorithm, $key, 0, $iv); + + if ($decrypted === false) { + throw new Exception("Decryption failed"); + } + + // Decode JSON + $userParams = json_decode($decrypted, true); + + if ($userParams === null) { + throw new Exception("Failed to decode JSON data"); + } + + return $userParams; + + } catch (Exception $e) { + log_message('error', 'Nhance SSO Decryption Error: ' . $e->getMessage()); + throw new Exception("Decryption error: " . $e->getMessage()); + } + } + + /** + * Generate SSO URL with encrypted parameters + */ + public static function generateSSOUrl($userParams = null) { + try { + // Use sample parameters if none provided + if ($userParams === null) { + $userParams = SELF::getSampleUserParams(); + log_message('info', 'Using sample user parameters for SSO URL generation'); + } + + // Validate required parameters + SELF::validateUserParams($userParams); + + // Encrypt user parameters + $encryptedParams = SELF::encryptUserParams($userParams); + + // Build the SSO URL + $ssoUrl = SELF::$baseUrl . '?userParams=' . $encryptedParams . '&clientId=' . SELF::$clientId; + + log_message('info', 'Nhance SSO URL generated successfully for user: ' . $userParams['email']); + + return $ssoUrl; + + } catch (Exception $e) { + log_message('error', 'Nhance SSO URL Generation Error: ' . $e->getMessage()); + throw new Exception("Failed to generate SSO URL: " . $e->getMessage()); + } + } + + /** + * Validate user parameters + */ + private static function validateUserParams($userParams) { + $requiredFields = [ + 'name', 'email', 'phone', 'memberId', 'gender', 'dob', + 'policyName', 'policyNumber', 'employeeId', 'moduleName', + 'relation', 'planId', 'policyStartDate', 'policyEndDate' + ]; + + foreach ($requiredFields as $field) { + if (!isset($userParams[$field]) || empty($userParams[$field])) { + throw new Exception("Required field '$field' is missing or empty"); + } + } + + // Validate date formats + if (!SELF::validateDate($userParams['dob']) || + !SELF::validateDate($userParams['policyStartDate']) || + !SELF::validateDate($userParams['policyEndDate'])) { + throw new Exception("Invalid date format. Use YYYY-MM-DD format"); + } + + // Validate gender + if (!in_array($userParams['gender'], ['Male', 'Female'])) { + throw new Exception("Gender must be 'Male' or 'Female'"); + } + + // Validate email + if (!filter_var($userParams['email'], FILTER_VALIDATE_EMAIL)) { + throw new Exception("Invalid email format"); + } + } + + /** + * Validate date format (YYYY-MM-DD) + */ + private static function validateDate($date) { + $d = \DateTime::createFromFormat('Y-m-d', $date); + return $d && $d->format('Y-m-d') === $date; + } + + /** + * Extract encrypted parameters from SSO URL + */ + private static function extractParamsFromUrl($ssoUrl) { + $parsedUrl = parse_url($ssoUrl); + if (!isset($parsedUrl['query'])) { + throw new Exception("No query parameters found in URL"); + } + + parse_str($parsedUrl['query'], $queryParams); + + if (!isset($queryParams['userParams'])) { + throw new Exception("userParams not found in URL"); + } + + return $queryParams['userParams']; + } + + /** + * Run comprehensive tests + */ + public static function runTests() { + $results = [ + 'tests_passed' => 0, + 'tests_failed' => 0, + 'test_details' => [] + ]; + + try { + // Test 1: Sample data encryption/decryption + log_message('info', 'Running Nhance SSO Test 1: Sample data round-trip'); + $sampleParams = SELF::getSampleUserParams(); + $ssoUrl = SELF::generateSSOUrl($sampleParams); + $encryptedParams = SELF::extractParamsFromUrl($ssoUrl); + $decryptedParams = SELF::decryptUserParams($encryptedParams); + + $test1Pass = json_encode($sampleParams) === json_encode($decryptedParams); + $results['test_details']['sample_round_trip'] = [ + 'status' => $test1Pass ? 'PASSED' : 'FAILED', + 'original_params' => $sampleParams, + 'decrypted_params' => $decryptedParams, + 'sso_url' => $ssoUrl + ]; + + if ($test1Pass) { + $results['tests_passed']++; + } else { + $results['tests_failed']++; + } + + // Test 2: Custom parameters + log_message('info', 'Running Nhance SSO Test 2: Custom parameters'); + $customParams = [ + 'name' => 'Jane Smith Test', + 'email' => 'jane.test@example.com', + 'phone' => '1122334455', + 'memberId' => 'TEST-CUSTOM-001', + 'gender' => 'Female', + 'dob' => '1985-03-20', + 'policyName' => 'Custom Test Policy', + 'policyNumber' => 'CUSTOM-POL-001', + 'employeeId' => 'EMP-CUSTOM-001', + 'moduleName' => 'home', + 'relation' => 'self', + 'planId' => 'NHANCE-PLAN-1', + 'policyStartDate' => date('Y-m-d'), + 'policyEndDate' => date('Y-m-d', strtotime('+2 years')) + ]; + + $customSsoUrl = SELF::generateSSOUrl($customParams); + $customEncryptedParams = SELF::extractParamsFromUrl($customSsoUrl); + $customDecryptedParams = SELF::decryptUserParams($customEncryptedParams); + + $test2Pass = json_encode($customParams) === json_encode($customDecryptedParams); + $results['test_details']['custom_round_trip'] = [ + 'status' => $test2Pass ? 'PASSED' : 'FAILED', + 'original_params' => $customParams, + 'decrypted_params' => $customDecryptedParams, + 'sso_url' => $customSsoUrl + ]; + + if ($test2Pass) { + $results['tests_passed']++; + } else { + $results['tests_failed']++; + } + + // Test 3: Null parameter handling + log_message('info', 'Running Nhance SSO Test 3: Null parameter handling'); + $nullTestUrl = SELF::generateSSOUrl(null); + $nullDecrypted = SELF::decryptUserParams(null); + + $test3Pass = !empty($nullTestUrl) && !empty($nullDecrypted); + $results['test_details']['null_parameter_handling'] = [ + 'status' => $test3Pass ? 'PASSED' : 'FAILED', + 'generated_url' => $nullTestUrl, + 'decrypted_sample' => $nullDecrypted + ]; + + if ($test3Pass) { + $results['tests_passed']++; + } else { + $results['tests_failed']++; + } + + } catch (Exception $e) { + $results['tests_failed']++; + $results['test_details']['error'] = $e->getMessage(); + log_message('error', 'Nhance SSO Test Error: ' . $e->getMessage()); + } + + $results['overall_status'] = $results['tests_failed'] === 0 ? 'ALL_PASSED' : 'SOME_FAILED'; + log_message('info', 'Nhance SSO Tests completed. Passed: ' . $results['tests_passed'] . ', Failed: ' . $results['tests_failed']); + + return $results; + } +} + +?> \ No newline at end of file diff --git a/app/Helpers/excel_util_helper.php b/app/Helpers/excel_util_helper.php index 3b52ce83..932e53c8 100755 --- a/app/Helpers/excel_util_helper.php +++ b/app/Helpers/excel_util_helper.php @@ -305,10 +305,12 @@ if (!function_exists('check_si')) { if (!function_exists('check_basic_pay')) { function check_basic_pay($row, $policy_terms, $slab_details) - { + { + // dd($row, $policy_terms, $slab_details); if ($row['current_action'] != null && in_array(strtoupper($row['current_action']), ['I', 'A', 'DA', 'MI'])) // check rule only of action column data available { - $is_basic_pay_needed = $slab_details['grid_master']['basicpay']; + // $is_basic_pay_needed = $slab_details['grid_master']['basicpay']; + $is_basic_pay_needed = ($slab_details['grid_master']['basicpay'] == 1 && $slab_details['slab_rates'][0]['si_or_bp'] == 2 && $slab_details['slab_rates'][0]['basic_pay'] != null) ? 1 : 0; // $is_basic_pay_needed = true; $slug = \Config\Services::slug(); $relationship = $slug->slugify($row[5]); diff --git a/app/Helpers/exception_helper.php b/app/Helpers/exception_helper.php new file mode 100644 index 00000000..c3211950 --- /dev/null +++ b/app/Helpers/exception_helper.php @@ -0,0 +1,35 @@ +getCode() && $e->getCode() >= 100 && $e->getCode() < 600) ? $e->getCode() : 500; + + $isDbError = $e instanceof \CodeIgniter\Database\Exceptions\DatabaseException + || $e instanceof \mysqli_sql_exception + || $e instanceof \PDOException; + + $context = [ + 'title' => get_class($e), + 'type' => get_class($e), + 'code' => $code, + 'message' => $e->getMessage(), + 'file' => $e->getFile(), + 'line' => $e->getLine() + ]; + + if ($logger) { + $logger->logme('error', "Exception: {message} in {file} on line {line}", $context, 0); + } else { + log_message('error', "Exception: {$context['message']} in {$context['file']} on line {$context['line']}"); + } + + return $response->setJSON([ + 'status' => 'error', + 'message' => $isDbError ? 'Data Access Error' : $e->getMessage(), + 'ref' => $isDbError ? 'database - ' : 'application - ' . $code . ' - ' . $e->getLine() + ])->setStatusCode($code); + } +} + diff --git a/app/Models/EmployeePolicyModel.php b/app/Models/EmployeePolicyModel.php index bf34881a..348d309d 100755 --- a/app/Models/EmployeePolicyModel.php +++ b/app/Models/EmployeePolicyModel.php @@ -563,36 +563,19 @@ class EmployeePolicyModel extends Model employees.email_personal AS emp_email_p, employees.band AS emp_grade, employees.designation AS emp_designation, - employees.basic_pay AS emp_basic_pay, - - batch_data.emp_policy_id, - batch_data.bl AS batch_list_batch_code, - batch_data.bf AS batch_files_batch_code - + employees.basic_pay AS emp_basic_pay FROM emp_endorsement LEFT JOIN employees ON employees.id = emp_endorsement.pk LEFT JOIN employee_polices ON employees.id = employee_polices.employee_id - LEFT JOIN ( - SELECT batch_list.emp_policy_id, - batch_list.batch_code AS bl, - batch_files.batch_code AS bf - FROM - batch_files - LEFT JOIN - batch_list ON batch_files.batch_code = batch_list.batch_code - WHERE batch_files.event_type = 'correction' - AND batch_files.actions = 'export' - AND batch_files.insurer_or_tpa = '{$insurer_or_tpa}' - ) AS batch_data ON emp_endorsement.pk = batch_data.emp_policy_id - WHERE employees.client_id = '{$client_id}' AND employee_polices.client_policy_id = '{$client_policy_id}' AND employees.client_branch_id = '{$client_branch_id}' AND emp_endorsement.actions = 'c' AND emp_endorsement.status != 'truncated' + AND emp_endorsement.is_active = 1 AND employee_polices.is_active = 1 AND employee_polices.status = 'active' AND employees.is_active = 1 diff --git a/app/Models/NhanceBranchModel.php b/app/Models/NhanceBranchModel.php new file mode 100644 index 00000000..d94d5fc9 --- /dev/null +++ b/app/Models/NhanceBranchModel.php @@ -0,0 +1,51 @@ + failed + data-placement="top" title="Wrong File Uploaded"> + + + + failed diff --git a/app/Views/client_policy.php b/app/Views/client_policy.php index 90a5a4bf..541a6a98 100755 --- a/app/Views/client_policy.php +++ b/app/Views/client_policy.php @@ -129,7 +129,7 @@
- +
@@ -1832,33 +1832,35 @@ } - $('#policy_no').change(function(){ + //check dublicate policy number + function checkPolicyNo() { - var policy_no = $(this).val(); - console.log(policy_no +'-'+policy_no.length); + var policy_no = $('#policy_no').val(); + console.log(policy_no + '-' + policy_no.length); policy_no = policy_no.trim(); - console.log(policy_no +'-'+policy_no.length); - + console.log(policy_no + '-' + policy_no.length); $.ajax({ - url: ''+policy_no, + url: '' + policy_no, type: "GET", dataType: 'json', success: function (res) { + console.log(res); + if (res.status == true) { - console.log(res) - if(res.status == true){ toastr.warning(res.message, 'warning'); $('#policy_no').val(''); + + }else{ + } }, error: function (xhr, status, error) { console.error(xhr.responseText); console.error(status, error); - } + } }); - - }) + } $(document).ready(function () { // Check if the URL contains a hash diff --git a/app/Views/insurer_or_tpa_data.php b/app/Views/insurer_or_tpa_data.php index dc07ab1c..fc822a52 100755 --- a/app/Views/insurer_or_tpa_data.php +++ b/app/Views/insurer_or_tpa_data.php @@ -90,13 +90,14 @@ -