diff --git a/app/Config/Database.php b/app/Config/Database.php index 388b1b03..1a43584f 100755 --- a/app/Config/Database.php +++ b/app/Config/Database.php @@ -45,6 +45,9 @@ class Database extends Config 'numberNative' => false, ]; + + public array $book_stack = []; + /** * This database connection is used when * running PHPUnit database tests. @@ -75,6 +78,29 @@ class Database extends Config { parent::__construct(); + // Initialize book_stack configuration with environment variables + $this->book_stack = [ + 'DSN' => '', + 'hostname' => getenv('bookStack_hostname'), + 'username' => getenv('bookStack_username'), + 'password' => getenv('bookStack_password'), + 'database' => getenv('bookStack_database'), + 'DBDriver' => 'MySQLi', + 'DBPrefix' => '', + 'pConnect' => false, + 'DBDebug' => true, + 'charset' => 'utf8', + 'DBCollat' => 'utf8_general_ci', + 'swapPre' => '', + 'encrypt' => false, + 'compress' => false, + 'strictOn' => false, + 'failover' => [], + 'port' => 3306, + 'foreignKeys' => true, + 'busyTimeout' => 1000, + ]; + // Ensure that we always set the database group to 'tests' if // we are currently running an automated test suite, so that // we don't overwrite live data on accident. @@ -82,4 +108,5 @@ class Database extends Config $this->defaultGroup = 'tests'; } } + } diff --git a/app/Config/Routes.php b/app/Config/Routes.php index 73fe07a4..80a25075 100755 --- a/app/Config/Routes.php +++ b/app/Config/Routes.php @@ -448,6 +448,7 @@ $routes->cli('cli/new_gdrive_token', 'GoogleDriveController::generateNewGoogleDr //crone job $routes->cli('cli/enrollOpendAndClose', 'DashboardController::updatePolicyEnrollmentStatus'); $routes->cli("cli/sendCroneRemainderMail", "DashboardController::sendCroneRemainderMail"); +$routes->cli('cli/update-emp-policy-status', 'ClientController::updateEmpAndPolicyStatus'); //Employee login api's $routes->post("/employeeRest/verifyEmployeeNumber", "RestAuthenticationController::verifyEmployeeWithMobileNumber"); @@ -462,7 +463,9 @@ $routes->post("/employeeRest/updateEmpMPIN", "RestAuthenticationController::upda //HR login api's $routes->post("/employeeRest/verifyHrWithMobileNumber", "RestAuthenticationController::verifyHrWithMobileNumber"); +$routes->post("/employeeRest/verifyHrWithEmail", "RestAuthenticationController::verifyHrWithEmail"); $routes->post("/employeeRest/getVerifiedHrData", "RestAuthenticationController::getVerifiedHrData"); +$routes->post("/employeeRest/updateHROTP", "RestAuthenticationController::updateHROTP"); // Test initiate Claim $routes->post('initiateClaim',"EmployeeRestController::initiateClaim"); @@ -513,7 +516,12 @@ $routes->group("employeeRest", ["filter" => "authJWT"], function ($routes) { $routes->post("iAgreeForAddOn", "EmployeeRestController::iAgreeForAddOn"); $routes->get("exportDataByClientPolicyId", "EmployeeRestController::exportDataByClientPolicyId"); - $routes->get("getCashDepositData", "EmployeeRestController::getCashDepositData"); + + $routes->get("getPolicyLevelEmployeeSummaryData", "EmployeeRestController::getPolicyLevelEmployeeSummaryData"); + $routes->get("cdSummaryData", "EmployeeRestController::cdSummaryData"); + $routes->get("cdTransactionData", "EmployeeRestController::cdTransactionData"); + $routes->match( ['get', 'post'], 'claimsSearch','EmployeeRestController::claimsSearch'); + $routes->get("claimView", "EmployeeRestController::claimView"); $routes->get("exportCashDepositData", "EmployeeRestController::exportCashDepositData"); $routes->get("removeEmpAndEmpPolicyData", "EmployeeRestController::removeEmpAndEmpPolicyData"); @@ -525,8 +533,8 @@ $routes->group("employeeRest", ["filter" => "authJWT"], function ($routes) { $routes->get("getFEContent", "EmployeeRestController::getFEContent"); $routes->get("getAdvertisementImage", "EmployeeRestController::getAdvertisementImage"); $routes->get("getWellnessURL", "EmployeeRestController::getWellnessURL"); + //$routes->post('postDataForTicket',"EmployeeRestController::postDataForTicket"); - // $routes->post('postDataForTicket',"EmployeeRestController::postDataForTicket"); }); $routes->get("getEmployeeActiveOrInactivePolicy", "EmployeeRestController::getEmployeeActiveOrInactivePolicy"); $routes->get("sendPushNotification", "EmployeeRestController::sendPushNotification"); @@ -538,7 +546,7 @@ $routes->get("getBackToEnrolledDetails", "EmployeeRestController::getBackToEnrol // Ticketing System End's - +$routes->get("autobookstackLogin", "RestAuthenticationController::bookstackLoginToken"); //BDSReports $routes->group("/bdsReport", ["filter" => "authMVC"], function ($routes) { $routes->match( ['get', 'post'], 'irba_report','BDSReportController::irba_report'); diff --git a/app/Controllers/ClientController.php b/app/Controllers/ClientController.php index 7228dac8..be5f2664 100755 --- a/app/Controllers/ClientController.php +++ b/app/Controllers/ClientController.php @@ -618,7 +618,7 @@ class ClientController extends AdminController } // In your controller - public function deposit($id = null) + public function deposit($id = null , $requestFrom = null ) { $headerData['page_name'] = 'Client Deposit'; @@ -629,13 +629,15 @@ class ClientController extends AdminController // Fetch associated insurer names and balances $balances = $this->clientPolicyModel->getBalances($id); $data['balances'] = $balances; - // dd($data); + + if($requestFrom == 'rest'){ return $data; } + echo view('layout/header', $headerData); echo view('client_deposit_list', $data); echo view('layout/footer'); } - public function view_Deposit($insurerId) + public function view_Deposit($insurerId , $requestFrom = null , $param = null) { // Load your model to fetch data based on $clientId and $insurerId // $subTypeOptions = [ @@ -660,15 +662,23 @@ class ClientController extends AdminController $headerData['page_name'] = 'Client Deposit'; $loggedInUserID = get_session_userid(); // $data['clientData']= $this->clientPolicyModel->getinsurerswithinsurenceid($insurerId); - $clientId = $this->request->getGet('client_id'); + if($requestFrom == 'rest') + { + $clientId = $param['client_id']; + $cd_ac_pk = $param['cd_ac_pk']; + }else{ + $clientId = $this->request->getGet('client_id'); + $cd_ac_pk = $this->request->getGet('cd_ac_pk'); + } + $data['insurerName'] = $this->insurerModel->getInsurerName($insurerId, $clientId); - $data['depositdata'] = $this->clientPolicyModel->getdepositData($clientId, $insurerId); + $data['depositdata'] = $this->clientPolicyModel->getdepositData($clientId, $insurerId, $cd_ac_pk); $data['clientData'] = $this->clientPolicyModel->getClientById($clientId); - $data['deposiamount'] = $this->clientPolicyModel->getDepositSummary($clientId, $insurerId); + $data['deposiamount'] = $this->clientPolicyModel->getDepositSummary($clientId, $insurerId, $cd_ac_pk); + $data['cd_ac_pk'] = $cd_ac_pk; - // dd($data); - - // print_r($data['depositdata'] );die; + if($requestFrom == 'rest'){ return $data; } + // Load the view for the new list page; echo view('layout/header', $headerData); echo view('view_deposit', $data); @@ -689,9 +699,16 @@ class ClientController extends AdminController ->where('insurer_id', $insurer_id) ->where('is_active', 1) ->first(); - // Prepare the array with data - $date = \DateTime::createFromFormat('d/m/Y', $record_date); - $record_date = $date->format('Y-m-d'); + + + if(!empty($record_date)){ + // Prepare the array with data + $date = \DateTime::createFromFormat('d/m/Y', $record_date); + $record_date = $date->format('Y-m-d'); + }else{ + $record_date = null; + } + $data = [ 'amount' => $this->request->getPost('amount'), 'sub_type_id' => $this->request->getPost('sub_type_id'), @@ -1273,7 +1290,12 @@ class ClientController extends AdminController $data['insurer_id'] = $insurerId; $tpaValue = (string) $this->request->getPost('tpa'); - list($tpaBranchId, $tpaId) = explode('-', $tpaValue); + if(!empty($tpaValue) || $tpaValue !== ''){ + list($tpaBranchId, $tpaId) = explode('-', $tpaValue); + }else{ + $tpaBranchId = null; + $tpaId = null; + } $data['tpa_branch_id'] = $tpaBranchId; $data['client_id'] = $client_id; @@ -4053,13 +4075,13 @@ class ClientController extends AdminController // Additional logic for non-individual clients (client_type != 2) if ($client_type != 2) { - $unit = $postData['short_name'] . '-' . $postData['branch_code']; + $unit[] = $postData['short_name'] . '-' . $postData['branch_code']; $branch_data = [ 'client_id' => $client_insert, 'branch_name' => $postData['branch_name'], 'branch_code' => $postData['branch_code'], 'gst' => $postData['gst'], - 'units' => $unit, + 'units' => json_encode($unit) ?? null, ]; $branch_insert = $this->clientBranchModel->insert($branch_data); @@ -4825,10 +4847,22 @@ class ClientController extends AdminController // ----------EMP DATA SERVICE CONTROLLER-------------------------------------------------------------------------------- // $batch_data = [ - // 'client_id' => 17, - // 'client_policy_id' => 30, - // 'client_branch_id' => 18, - // 'event_type' => "inception", + // 'client_id' => 29, + // 'client_policy_id' => 17, + // 'client_branch_id' => 15, + // 'insurer_or_tpa' => "insurer", + // 'event_type' => "deletion", + // ]; + + // $batch_data = [ + // 'client_id' => 89, + // 'client_policy_id' => 328, + // 'client_branch_id' => 88, + // 'insurer_or_tpa' => "insurer", + // // 'insurer_or_tpa' => "tpa", + // 'event_type' => "si_enhancement", + // 'file_name' => "si_enhancement_test_file.xlsx", + // 'actions' => "export", // ]; // $batch_data['insurer_or_tpa'] = 'insurer'; @@ -4844,13 +4878,17 @@ class ClientController extends AdminController // $EmpDataServiceController->sendMailForDownloadingECard($ids); $EmpDataServiceController = new EmpDataServiceController(); + // $EmpDataServiceController->generateExcelForSIEnhancement($batch_data); die; + // $EmpDataServiceController->importInceptionFileValidation(['file_id' => 1932]); die; // $EmpDataServiceController->importDeletionValidation(['file_id' => 304]); //for live // $EmpDataServiceController->importSIEnhancementUpdateEndorsementID(['file_id' => 1199]); //for live // $EmpDataServiceController->importSIEnhancementValidation(['file_id' => 1205]); //for live // $EmpDataServiceController->importInceptionUpdateTPAandUHID(['file_id' => 214]); //for live // $result = $this->employeePolicyModel->getDeletionEmployeeDataForExportExcel($batch_data); - // print_rr($result); die; + // $result = $this->employeePolicyModel->getSIEnhancementEmployeesDataForExportExcel($batch_data, 1); + // return $this->downloadInsurerExcelExport($batch_data); + // dd($result); die; // $empServiceController = new EmployeeServiceController(); // $res = $empServiceController->employeesOnboardPreprocess(['file_id' => '741']); @@ -4859,7 +4897,7 @@ class ClientController extends AdminController // $res = $PolicyTransactionController->validateInsurerStatement(['file_id' => '36']); // $empServiceController = new EmployeeServiceController(); - // $res = $empServiceController->excelFileDataValidation(['file_id' => '319']); + // $res = $empServiceController->excelFileDataValidation(['file_id' => '1101']); // dd($res); // $EmpDataServiceController = new EmpDataServiceController(); @@ -5192,8 +5230,10 @@ class ClientController extends AdminController ->where('insurers.is_active', 1) ->where('tpa.is_active', 1) ->where('employees.is_active', 1) + ->where('employees.emp_status', "active") ->where('employees.relationship', "Self") ->where('employee_polices.is_active', 1) + ->where('employee_polices.status', "active") ->where($field_name, $param); if (!empty($client_id)) { diff --git a/app/Controllers/EmpDataServiceController.php b/app/Controllers/EmpDataServiceController.php index cb93e213..3dbf91d5 100755 --- a/app/Controllers/EmpDataServiceController.php +++ b/app/Controllers/EmpDataServiceController.php @@ -185,7 +185,7 @@ class EmpDataServiceController extends BaseController $balance = $this->CDMasterModel ->where('client_id', $export_data['client_id']) ->where('insurer_id', $policy_details['insurer_id']) - ->where('cd_ac_no', $policy_details['cd_ac_no']) + ->where('id', $policy_details['cd_ac_pk']) ->first(); $cash_balance['balance'] = $balance['opening_bal']; @@ -683,7 +683,7 @@ class EmpDataServiceController extends BaseController $balance = $this->CDMasterModel ->where('client_id', $export_data['client_id']) ->where('insurer_id', $policy_details['insurer_id']) - ->where('cd_ac_no', $policy_details['cd_ac_no']) + ->where('id', $policy_details['cd_ac_pk']) ->first(); $cash_balance['balance'] = $balance['opening_bal']; @@ -1411,7 +1411,8 @@ class EmpDataServiceController extends BaseController // dd($inceptionHeader); foreach ($inceptionHeader as $key => $value) { - if($excel_header[$key] != $value){ + if (!isset($excel_header[$key]) || $excel_header[$key] != $value) { + $data = [ 'status' => 'failed-5', ]; @@ -3046,25 +3047,28 @@ class EmpDataServiceController extends BaseController // dd($emp_policy_ids, $emp_details, $endorsement_details); - $this->employeePolicyModel->updateBatch($emp_policy_ids, 'id'); + if ($file['insurer_or_tpa'] == 'insurer') { - // $this->employeePolicyModel->insertBatch($emp_details); - // $insertedIds = []; - // $startId = $db->insertID(); // Get the first inserted ID - - // for ($i = 0; $i < count($emp_details); $i++) { - // $insertedIds[] = $startId + $i; - // } + $this->employeePolicyModel->updateBatch($emp_policy_ids, 'id'); - $insertedIds = []; - foreach ($emp_details as $emp) { - $insertedIds[] = $this->employeePolicyModel->insert($emp); + // $this->employeePolicyModel->insertBatch($emp_details); + // $insertedIds = []; + // $startId = $db->insertID(); // Get the first inserted ID + + // for ($i = 0; $i < count($emp_details); $i++) { + // $insertedIds[] = $startId + $i; + // } + + $insertedIds = []; + foreach ($emp_details as $emp) { + $insertedIds[] = $this->employeePolicyModel->insert($emp); + } + + // dd($insertedIds); + + $this->employeePolicyModel->bulkUpdateForEndorsement($endorsement_details); + $this->storeEndorsementNumber($file_id, $endorsement_id, $enrollment_file_id); } - - // dd($insertedIds); - - $this->employeePolicyModel->bulkUpdateForEndorsement($endorsement_details); - $this->storeEndorsementNumber($file_id, $endorsement_id, $enrollment_file_id); // Update batch file status and amount @@ -3537,20 +3541,29 @@ class EmpDataServiceController extends BaseController // return ['status' => 'error', 'message' => 'Employees table data is empty or null.']; // } - // Check if $employee_policy_table_data is null or empty - if (empty($employee_policy_table_data)) { - return ['status' => 'error', 'message' => 'Employee policy table data is empty or null.']; - } + if ($file['insurer_or_tpa'] == 'insurer') { - // Check if $emp_endorsement_table_data is null or empty - if (empty($emp_endorsement_table_data)) { - return ['status' => 'error', 'message' => 'Employee endorsement table data is empty or null.']; - } + // Check if $employee_policy_table_data is null or empty + if (empty($employee_policy_table_data)) { + $this->batchFileModel->update($file_id, [ + 'status' => "failed", + ]); + return ['status' => 'error', 'message' => 'Employee policy table data is empty or null.']; + } - // $this->employeeModel->updateBatch($employees_table_data, 'id'); - $this->employeePolicyModel->updateBatch($employee_policy_table_data, 'id'); - $this->employeePolicyModel->bulkUpdateForEndorsement($emp_endorsement_table_data); - $this->storeEndorsementNumber($file_id, $endorsement_id, $enrollment_file_id); + // Check if $emp_endorsement_table_data is null or empty + if (empty($emp_endorsement_table_data)) { + $this->batchFileModel->update($file_id, [ + 'status' => "failed", + ]); + return ['status' => 'error', 'message' => 'Employee endorsement table data is empty or null.']; + } + + // $this->employeeModel->updateBatch($employees_table_data, 'id'); + $this->employeePolicyModel->updateBatch($employee_policy_table_data, 'id'); + $this->employeePolicyModel->bulkUpdateForEndorsement($emp_endorsement_table_data); + $this->storeEndorsementNumber($file_id, $endorsement_id, $enrollment_file_id); + } // Update batch file status and amount $this->batchFileModel->update($file_id, [ diff --git a/app/Controllers/EmployeeController.php b/app/Controllers/EmployeeController.php index b6e1c007..6541e011 100755 --- a/app/Controllers/EmployeeController.php +++ b/app/Controllers/EmployeeController.php @@ -336,15 +336,16 @@ class EmployeeController extends AdminController ->join('client_branch cb', 'files.client_branch_id = cb.id', 'left') ->join('policy_type', 'policy_type.id = cp.policy_type_id') ->join('clients c', 'files.client_id = c.id and files.client_id = cp.client_id', 'left') - ->join("client_rm cr","cr.client_id = c.id and cr.is_active = 1",'left'); + ->join("client_rm cr","cr.client_id = c.id and cr.is_active = 1",'left') + ->where('files.is_active', 1); if (in_array($role_id, [2, 3])) { // If the user is a Account Manager or Manager, filter by user_id $query->where('cr.user_id', $user_id); } // ->where('files.created_by', get_session_userid()) - $data['fileList'] = $query->orderBy('files.created_at', 'desc') - ->limit(100) + $data['fileList'] = $query->groupBy("c.id")->orderBy('files.created_at', 'desc') + ->limit(1500) ->find(); // dd($data['fileList']); @@ -386,15 +387,16 @@ class EmployeeController extends AdminController ->join('client_branch', 'client_branch.id = batch_files.client_branch_id') ->join('policy_type', 'policy_type.id = client_policy.policy_type_id') ->join('clients', 'clients.id = client_policy.client_id') - ->join("client_rm cr","cr.client_id = clients.id and cr.is_active = 1",'left'); + ->join("client_rm cr","cr.client_id = clients.id and cr.is_active = 1",'left') + ->where('batch_files.is_active', 1); if (in_array($role_id, [2, 3])) { // If the user is a Account Manager or Manager, filter by user_id $query2->where('cr.user_id', $user_id); } // ->where('files.created_by', get_session_userid()) - $data['batch_list'] = $query2->orderBy('batch_files.id', 'desc') - ->limit(1000) + $data['batch_list'] = $query2->groupBy("clients.id")->orderBy('batch_files.id', 'desc') + ->limit(1500) ->find(); @@ -1040,6 +1042,7 @@ class EmployeeController extends AdminController $data = $this->employeePolicyModel->select('employee_polices.id') ->where('employee_polices.is_active', 1) + ->where('employee_polices.status', 'active') ->where('employee_polices.client_policy_id', $id) ->findAll(); @@ -2401,7 +2404,7 @@ class EmployeeController extends AdminController } else if ($actionType == 'deletion') { $filePath = ROOTPATH . 'public/sample_import_excel/sample_import_Deletion.xlsx'; }else if ($actionType == 'missed_inception') { - $filePath = ROOTPATH . 'public/sample_import_excel/sample_import_Inception.xlsx'; + $filePath = ROOTPATH . 'public/sample_import_excel/sample_import_Addition.xlsx'; } // Check if the file exists diff --git a/app/Controllers/EmployeeRestController.php b/app/Controllers/EmployeeRestController.php index 711366a3..db9a0ea2 100755 --- a/app/Controllers/EmployeeRestController.php +++ b/app/Controllers/EmployeeRestController.php @@ -2276,72 +2276,47 @@ class EmployeeRestController extends AdminController } - public function getCashDepositData() + public function getPolicyLevelEmployeeSummaryData() { - $ClientPolicyData = $this->clientPolicyModel->select('client_policy.client_id as clientId , client_policy.insurer_id as insurerId,insurers.name as insurer_name') - ->join('insurers', 'client_policy.insurer_id = insurers.id', 'left') - ->where('client_policy.client_id', $this->request->getGet('client_id') ) - ->where('client_policy.client_branch_id', $this->request->getGet('client_branch_id') ) - ->where('client_policy.is_active', 1 ) - ->where('client_policy.policy_status', 1) - ->groupBy('client_policy.insurer_id') - ->findAll(); - $result = []; - - if(count($ClientPolicyData)) - { - foreach ($ClientPolicyData as $key => $value) { - - $data['clientId'] = $value['clientId']; - $data['insurerId'] = $value['insurerId']; - $data['insurerName'] = $value['insurer_name']; - $data['depositData'] = $this->clientPolicyModel->getdepositData($value['clientId'],$value['insurerId']); - $data['balance'] = count($data['depositData']) ? $data['depositData'][0]->balance : 0; - - $data['policyDetails'] = []; - $ClientPolicyData = $this->clientPolicyModel->select('client_policy.id as client_policy_id , client_policy.client_id as client_id, client_policy.policy_type_id as policy_type_id, client_policy.is_addon as is_addon , client_policy.open_for_enrollment as OpenForEnrollment , client_policy.inception_type as inception_type ') - - ->where('client_policy.insurer_id', $value['insurerId'] ) - ->where('client_policy.client_id', $this->request->getGet('client_id') ) - ->where('client_policy.client_branch_id', $this->request->getGet('client_branch_id') ) - ->where('client_policy.is_active', 1 ) - ->where('client_policy.policy_status', 1) - ->findAll(); - // dd( $ClientPolicyData); - foreach ($ClientPolicyData as $key => $value) + + $ClientPolicyData = $this->clientPolicyModel->select('client_policy.id as client_policy_id , client_policy.client_id as client_id, client_policy.policy_type_id as policy_type_id, client_policy.is_addon as is_addon , client_policy.open_for_enrollment as OpenForEnrollment , client_policy.inception_type as inception_type ') + ->where('client_policy.client_id', $this->request->getGet('client_id') ) + ->where('client_policy.client_branch_id', $this->request->getGet('client_branch_id') ) + ->where('client_policy.is_active', 1 ) + ->where('client_policy.policy_status', $this->request->getGet('policy_status')) + ->findAll(); + $result = []; + // dd( $ClientPolicyData); + foreach ($ClientPolicyData as $key => $value) + { + $policyTypeData = $this->policyTypeModel->where('id',$value['policy_type_id'])->get()->getRow(); + $value['type'] = $policyTypeData->policy_type; + $value['policy_name'] = $policyTypeData->long_name; + $employeeDetails = $this->employeePolicyModel->getEmployeePolicy( client_id:$value['client_id'],policy_id: $value['client_policy_id'],status:0,branch_id:$this->request->getGet('client_branch_id')); + // dd($employeeDetails); + $activeCount = 0; + $inactiveCount = 0; + if(count($employeeDetails)) { - $policyTypeData = $this->policyTypeModel->where('id',$value['policy_type_id'])->get()->getRow(); - $value['type'] = $policyTypeData->policy_type; - $value['policy_name'] = $policyTypeData->long_name; - $employeeDetails = $this->employeePolicyModel->getEmployeePolicy( client_id:$value['client_id'],policy_id: $value['client_policy_id'],status:0,branch_id:$this->request->getGet('client_branch_id')); - $enrolledCount = 0; - $draftCount = 0; - if(count($employeeDetails)) - { - foreach ($employeeDetails as $item) { - if ($item['emp_status'] === 'enrolled') { - $enrolledCount++; - } elseif ($item['emp_status'] === 'draft') { - $draftCount++; - } + foreach ($employeeDetails as $item) { + if ($item['emp_status'] === 'active') { + $activeCount++; + } elseif ($item['emp_status'] === 'inactive') { + $inactiveCount++; } } - - $value['totalMembersCount'] = count($employeeDetails); - $value['membersCountOfEnrolled'] = $enrolledCount; - $value['membersCountOfDraft'] = $draftCount; - - array_push($data['policyDetails'],$value); } - - - array_push($result,$data); - } - } - + $value['totalMembersCount'] = count($employeeDetails); + $value['membersCountOfActive'] = $activeCount; + $value['membersCountOfInactive'] = $inactiveCount; + + array_push($result,$value); + } + + if($result) { @@ -2353,6 +2328,218 @@ class EmployeeRestController extends AdminController } + public function cdSummaryData() + { + + $clientId = $this->request->getGet('client_id'); + + $clientController = new ClientController; + $result = $clientController->deposit($clientId , $requestFrom = 'rest'); + + $data = []; + + foreach ($result['clientData'] as $key => $value) + { + $temp['client_id'] = $value->client_id; + $temp['insurer_id'] = $value->insurer_id; + $temp['cd_ac_pk'] = $value->cd_ac_pk; + $temp['insurer_name'] = $value->insurer_name; + $temp['cd_master_account_no'] = $value->cd_master_account_no; + if (isset($result['balances'][$temp['insurer_id']])) { + $balance = $result['balances'][$temp['insurer_id']]->balance; + $temp['balance'] = $balance; + } else { + $temp['balance'] = "N/A"; + } + + array_push($data,$temp); + } + + + if($data) + { + return $this->respond(['status' => 'success','code' => (count($data) ? 200 : 404),'data' => $data ], 200); + }else{ + return $this->respond(['status' => 'failed','code' => (count($data) ? 200 : 404),'data' => [] ], 200); + } + + } + + public function cdTransactionData() + { + + $clientId = $this->request->getGet('client_id'); + $insurerId = $this->request->getGet('insurer_id'); + $cdAccountPrimaryKey = $this->request->getGet('cd_ac_pk'); + + $clientController = new ClientController; + $result = $clientController->view_Deposit($insurerId , $requestFrom = 'rest' , $param = ['client_id'=>$clientId, 'cd_ac_pk'=>$cdAccountPrimaryKey ]); + + $data['insurer_name'] = $result['insurerName']->name; + $data['account_number'] = $result['insurerName']->cd_master_account_no; + $data['total_deposit'] = $result['deposiamount']->total_credit; + $data['total_consumed'] = $result['deposiamount']->total_withdraw; + $data['total_refund'] = $result['deposiamount']->total_refund; + $data['currect_balance'] = $result['deposiamount']->balance; + $data['deposit_data'] = $result['depositdata']; + + + // dd($data); + + if($data) + { + return $this->respond(['status' => 'success','code' => (count($data) ? 200 : 404),'data' => $data ], 200); + }else{ + return $this->respond(['status' => 'failed','code' => (count($data) ? 200 : 404),'data' => [] ], 200); + } + + } + + + public function claimsSearch() + { + + if ($this->request->is('get')) { + + $data['claim_status'] = $this->claimStatusModel->select('id,ticket_type,claim_status')->where('is_active', 1)->findAll(); + $data['ticket_type'] = [ + ["ticket_type" => "1", "type_name" => "Claim-GMC"], + ["ticket_type" => "2", "type_name" => "Claim-GPA"], + ["ticket_type" => "3", "type_name" => "EDLI"], + ["ticket_type" => "4", "type_name" => "GTLI"], + ]; + + return $this->respond(['status' => (count($data) ? 'success' : 'failed'),'code' => (count($data) ? 200 : 404),'data' => $data ], 200); + + } + + $db = db_connect(); + + $search_data = $this->request->getJSON(true); // Get JSON as associative array + + $client_id = isset($search_data['client_id']) ? (int) $search_data['client_id'] : 0; + unset($search_data['client_id']); + + $from_date = isset($search_data['from_date']) ? $search_data['from_date'] : null; + $to_date = isset($search_data['to_date']) ? $search_data['to_date'] : null; + unset($search_data['from_date'], $search_data['to_date']); + + $where = []; + + // Dynamically build WHERE conditions from non-empty parameters + foreach ($search_data as $key => $value) { + if (!empty($value) && $value !== 0 && $value !== '0') { + $where["tm.$key"] = $value; + } + } + + $builder = $db->table('ticket_master tm'); + $builder->select([ + 'tm.id', + 'tm.ticket_type_id', + 'tcs.claim_status AS status', + 'tm.claim_number AS claim_no', + 'tm.claim_status_id', + 'tm.is_head_approved', + 'tm.tpa_id', + 'tm.tpa_no', + 'tm.emp_name', + 'tm.emp_code', + 'tm.relationship', + 'i.name AS insurer_name', + 'c.client_name', + 'tm.insured_name', + 'c.short_name', + 'DATE_FORMAT(tm.created_at, "%d-%m-%Y") AS ticket_created_date', + + '(SELECT first_name FROM user_profiles WHERE user_profiles.id = tm.acm_id) AS acm_name', + '(SELECT name FROM insurers WHERE insurers.id = tm.insurer_id) AS insurer_name_sub', + '(SELECT name FROM tpa WHERE tpa.id = tm.tpa_id) AS tpa_name', + + 'tm.acm_id', + 'tm.insurer_id', + 'tm.client_policy_id', + 'tm.policy_no', + 'tm.priority', + 'tm.emp_mobile', + 'tm.emp_mail', + 'tm.emp_personal_mail', + 'tm.mode_of_intimation', + 'tm.claim_type', + 'tm.hospital_name', + 'tm.doa', + 'tm.dod', + 'tm.claim_amount', + 'tm.pod_no', + 'tm.date_of_join', + 'tm.date_of_incep', + 'tm.dob', + 'tm.date_of_accident', + 'tm.date_of_death', + 'tm.date_of_intimat', + 'tm.si_amt', + 'tm.raised_date', + 'tm.registration_date', + 'tm.query_received_date', + 'tm.denial_date', + 'tm.approved_date', + 'tm.settled_date', + 'tm.denial_reason', + 'tm.approved_letter', + 'tm.approved_amount', + 'tm.utr_details', + 'tm.settle_letter', + 'tm.return_remark', + 'tm.cancel_remark', + 'tm.awb_no_courier_name', + 'tm.non_id_reason', + 'tm.pay_initiate_date', + 'tm.approved_description' + ]); + + $builder->join('insurers i', 'i.id = tm.insurer_id AND i.is_active = 1', 'left'); + $builder->join('clients c', 'c.id = tm.client_id AND c.is_active = 1', 'left'); + $builder->join('ticket_claim_status tcs', 'tcs.id = tm.claim_status_id AND tcs.is_active = 1', 'left'); + + $builder->where('tm.is_active', 1); + + if ($client_id > 0) { + $builder->where('tm.client_id', $client_id); + } + + if (!empty($from_date) && !empty($to_date)) { + $from_date_mysql = date('Y-m-d', strtotime($from_date)); + $to_date_mysql = date('Y-m-d', strtotime($to_date)); + $builder->where("DATE(tm.created_at) BETWEEN '$from_date_mysql' AND '$to_date_mysql'"); + } + + if (!empty($where)) { + $builder->where($where); + } + + $builder->orderBy('tm.id', 'DESC'); + + $data = $builder->get()->getResultArray(); + + return $this->respond(['status' => (count($data) ? 'success' : 'failed'),'code' => (count($data) ? 200 : 404),'data' => $data ], 200); + + } + + public function claimView() + { + $ticket_id = $this->request->getGet('ticket_id'); + $ticketController = new TicketController; + $data['ticket_history'] = $ticketController->ticketHistory($ticket_id); + $data['claims_data'] = $this->ticketMaster->getTicketDataByTicketID($ticket_id); + $data['ticket_data'] = $ticketController->getMoreInfo($requestFrom = 'rest', $ticket_id); + + + + return $this->respond(['status' => (count($data) ? 'success' : 'failed'),'code' => (count($data) ? 200 : 404),'data' => $data ], 200); + } + + + public function exportCashDepositData() @@ -2501,8 +2688,9 @@ class EmployeeRestController extends AdminController function getEmployeeActiveOrInactivePolicy() { - if($this->request->getGet('type') == 'Active'){ $policy_status = 1; }else{ $policy_status = 0; } - $ClientPolicyData = $this->clientPolicyModel->select('client_policy.* , policy_type.policy_type as policy_type,insurers.name as insurer_name,tpa.name as tpa_name,tpa.network_hospitals as network_hospitals_url, policy_type.long_name as policy_long_name') + if($this->request->getGet('type') == 'Active'){ $policy_status = 1; $policy_status_key = "Active"; }else{ $policy_status = 0; $policy_status_key = "InActive";} + $dayInterval = 10; + $ClientPolicyData = $this->clientPolicyModel->select("client_policy.* , policy_type.policy_type as policy_type,insurers.name as insurer_name,tpa.name as tpa_name,tpa.network_hospitals as network_hospitals_url, policy_type.long_name as policy_long_name, DATE_ADD(client_policy.policy_end_date, INTERVAL {$dayInterval} DAY) as claims_grace_date") ->join('insurers', 'client_policy.insurer_id = insurers.id', 'left') ->join('tpa', 'client_policy.tpa_id = tpa.id', 'left') ->join('policy_type', 'client_policy.policy_type_id = policy_type.id', 'left') @@ -2526,12 +2714,16 @@ class EmployeeRestController extends AdminController ->get()->getRow()->name; $whereArrayForId = []; foreach ( $employeeData as $key => $value) { array_push($whereArrayForId, $value['id']); } - + if(count($ClientPolicyData) > 0 && count($employeeData) > 0) { $result = []; foreach ($ClientPolicyData as $key => $ClientPolicyValue) { + if (strtotime(date('Y-m-d') > strtotime($ClientPolicyValue['claims_grace_date']))) { + continue; + } + if($ClientPolicyValue['policy_type_id'] == 1) { $policyGroup = 'gpa'; @@ -2565,6 +2757,8 @@ class EmployeeRestController extends AdminController $data['policy_start_date'] = $this->convertDateFormatDisplay($ClientPolicyValue['policy_start_date']); $data['policy_end_date'] = $this->convertDateFormatDisplay($ClientPolicyValue['policy_end_date']); $data['heading'] = $ClientPolicyValue['policy_long_name']; + $data['claims_grace_date'] = $this->convertDateFormatDisplay($ClientPolicyValue['claims_grace_date']); + $data['policy_status'] = $policy_status_key; // $data['policy_terms'] = $terms; // if($ClientPolicyValue['policy_type_id'] == 1){ $data['heading'] = 'Group Personal Accident Coverage'; }else @@ -3325,7 +3519,8 @@ class EmployeeRestController extends AdminController public function getWellnessUrl() { - $url = "https://aam.mohfw.gov.in/home/login"; + // $url = "https://aam.mohfw.gov.in/home/login"; + $url = ""; if (!empty($url)) { return $this->respond([ @@ -3335,7 +3530,7 @@ class EmployeeRestController extends AdminController } else { return $this->respond([ 'status' => 'failed', - 'message' => 'No link found' + 'message' => 'Coming soon........!' ], 200); } } diff --git a/app/Controllers/LeadsController.php b/app/Controllers/LeadsController.php index b5f4701a..ee908837 100644 --- a/app/Controllers/LeadsController.php +++ b/app/Controllers/LeadsController.php @@ -42,6 +42,7 @@ use App\Controllers\Jobs; use App\Controllers\JobWorker; use Google\Service\FactCheckTools\Resource\Claims; use GPBMetadata\Google\Type\Datetime; +use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; class LeadsController extends BaseController { @@ -118,7 +119,7 @@ class LeadsController extends BaseController 'completed_with_corrections' => 'Completed with Corrections', 'completed_without_corrections' => 'Completed without Corrections', ]; - + $this->claim_type_for_gpa = [ 'accident_death' => 'Accident Death', 'permanent_total_disablement' => 'Permanent Total Disablement', @@ -214,9 +215,13 @@ class LeadsController extends BaseController $data['entity_type_id'] = $client_data['entity_type_id']; $data['client_type'] = $client_data['client_type']; } else { - $data['client_id'] = 0; - $data['client_branch_id'] = 0; - $data['source_policy_id'] = 0; + if(!empty($data['client_id'])){ + $data['is_client_created'] = $data['client_id']; + }else{ + $data['client_id'] = 0; + $data['client_branch_id'] = 0; + $data['source_policy_id'] = 0; + } } $data['client_code'] = generate_client_code(); @@ -243,7 +248,7 @@ class LeadsController extends BaseController $leads_file_primary_key = $data['leads_file_id'] ?? []; $multi_file_data = []; - if(isset($data[$form_docs_name])){ + if (isset($data[$form_docs_name])) { $files = $this->request->getFileMultiple($form_file_name); $multi_file_data = $this->uploadMultiFiles($files, $data[$form_docs_name], $leads_file_primary_key); } @@ -361,13 +366,13 @@ class LeadsController extends BaseController // $premium_date = null; // } - if (!empty($data['source_policy_start_date'])) { + if (!empty($data['source_policy_start_date']) && $data['lead_type'] == 2) { $data['source_policy_start_date'] = change_date_format($data['source_policy_start_date'], 'd/m/Y', 'Y-m-d'); } else { $data['source_policy_start_date'] = null; } - if (!empty($data['source_policy_end_date'])) { + if (!empty($data['source_policy_end_date']) && $data['lead_type'] == 2) { $data['source_policy_end_date'] = change_date_format($data['source_policy_end_date'], 'd/m/Y', 'Y-m-d'); } else { $data['source_policy_end_date'] = null; @@ -394,6 +399,7 @@ class LeadsController extends BaseController 'contact_person_email' => $data['contact_person_email'], 'client_id' => $data['client_id'] ?? 0, 'client_branch_id' => $data['client_branch_id'] ?? 0, + 'is_client_created' => $data['is_client_created'] ?? null, 'source_policy_id' => $data['source_policy_id'] ?? 0, 'policy_type_id' => $value, 'salse_person_id' => $data['salse_person_id'] ?? 0, @@ -447,6 +453,7 @@ class LeadsController extends BaseController 'source_policy_start_date' => $data['source_policy_start_date'] ?? null, 'source_policy_end_date' => $data['source_policy_end_date'] ?? null, + 'claim_history' => $data['claim_history'] ?? 0 ]; } // print_r($processedData);die(); @@ -486,7 +493,7 @@ class LeadsController extends BaseController { if ($this->leadsModel->where('id', $id)->set($data[0])->update()) { - $this->insertMultiFilesData($data[0]['multi_file_data'], $id); + $this->insertMultiFilesData($data[0]['multi_file_data'], $id, $data[0]['lead_form_type']); $this->insertLeadStatus($id, $data[0]['status'], 3); return $this->respond(['status' => true, 'lead_id' => $id, 'message' => "Lead updated successfully", 'data' => $data], 200); } @@ -584,14 +591,18 @@ class LeadsController extends BaseController return $multi_file_data; } - public function insertMultiFilesData($data, $lead_id) + public function insertMultiFilesData($data, $lead_id, $lead_form_type = null) { - // print_r($data); die; + log_message('info', 'insertMultiFilesData() called with lead_id: ' . $lead_id); if (!empty($data)) { + log_message('info', 'Data is not empty. Total items: ' . count($data)); + foreach ($data as $key => $value) { + log_message('info', "Processing item at index {$key}: " . json_encode($value)); if (!empty($value['id'])) { + log_message('info', "Record with ID {$value['id']} exists. Preparing to update."); $lead_file_data = [ 'lead_id' => $lead_id, @@ -600,10 +611,22 @@ class LeadsController extends BaseController if (!empty($value['file_name'])) { $lead_file_data['file_name'] = $value['file_name']; + log_message('info', "file_name found: {$value['file_name']}"); + + if (!empty($lead_form_type) && $lead_form_type == 1 && $key == 0) { + //for this push the job to the calculateMembersDemography() function + $job_details = new Jobs(); + $r = Jobs::addJob(['job_name' => 'calculateMembersDemography', 'payload' => [ + 'lead_id' => $lead_id, + ]]); + log_message('info', "calculateMembersDemography JOB PUSHED"); + } } + log_message('info', "Updating leadFilesModel where id = {$value['id']} with data: " . json_encode($lead_file_data)); $this->leadFilesModel->where('id', $value['id'])->set($lead_file_data)->update(); } else { + log_message('info', "No ID found. Preparing to insert new record."); if (!empty($value['file_name'])) { $lead_file_data = [ @@ -611,16 +634,24 @@ class LeadsController extends BaseController 'docs_name' => $value['docs_name'], 'file_name' => $value['file_name'], ]; + + log_message('info', "Inserting into leadFilesModel: " . json_encode($lead_file_data)); $this->leadFilesModel->insert($lead_file_data); + } else { + log_message('warning', "Skipped insert: file_name missing in data at index {$key}"); } } if ($key == 0 && !empty($value['file_name'])) { + log_message('info', "Setting first file_name '{$value['file_name']}' to leadsModel for lead_id: {$lead_id}"); $this->leadsModel->where('id', $lead_id)->set('file_name', $value['file_name'])->update(); } } + } else { + log_message('warning', 'insertMultiFilesData() received empty data array.'); } + log_message('info', 'insertMultiFilesData() completed successfully.'); return true; } @@ -681,9 +712,9 @@ class LeadsController extends BaseController if ($lead_data['lead_type'] != 1) { $client_policy_data = $this->clientPolicyModel->where('is_active', 1)->where('id', $lead_data['source_policy_id'])->first(); - if (isset($client_policy_data)) { + if (isset($client_policy_data)) { $data['policy_terms'] = $client_policy_data['policy_terms']; - } + } } $data['question_json'] = $lead_data['question_json']; @@ -716,15 +747,15 @@ class LeadsController extends BaseController $subject = "{{CLIENT_NAME}} _ {{POLICY_TYPE}} _ {{RFQ_OR_QCR}} _ {{POLICY_YEAR}}"; } - if($lead_data['policy_type_id'] == 1){ - $data['totalSumAssured'] = $this->handleMemberDataGPATotalSumInsurerFromExcel(['lead_id' => $id]); - }else{ - $data['totalSumAssured'] = []; + if ($lead_data['policy_type_id'] == 1) { + $data['totalSumAssured'] = $this->handleMemberDataGPATotalSumInsurerFromExcel(['lead_id' => $id]); + } else { + $data['totalSumAssured'] = []; } $data['mail_content'] = $this->transformMailContent($lead_data, $mail_content, $data['page_name']); $data['subject'] = $this->transformMailContent($lead_data, $subject, $data['page_name']); - + $data['placement_mail_content'] = $this->transformMailContent($lead_data, $mail_content, 'Placement'); $data['placement_subject'] = $this->transformMailContent($lead_data, $subject, 'Placement'); @@ -746,7 +777,7 @@ class LeadsController extends BaseController if ($lead_data['lead_type'] != 1 && $data['rfq_count'] == 0) { $client_policy_data = $this->clientPolicyModel->where('is_active', 1)->where('id', $lead_data['source_policy_id'])->first(); if (isset($client_policy_data)) { - + $data['rfq_data']['json'] = $client_policy_data['placement_json']; } } @@ -817,13 +848,13 @@ class LeadsController extends BaseController $qcr_created = true; } - if(($data['submit_type'] ?? "") == 'QCR'){ + if (($data['submit_type'] ?? "") == 'QCR') { $inputJson = json_decode($data['json'], true); $proposal_data = array_pop($inputJson); - if(isset($proposal_data['proposal_data']['over_all_column_data'])){ + if (isset($proposal_data['proposal_data']['over_all_column_data'])) { $proposel_count = $proposal_data['proposal_data']['over_all_column_data']; foreach ($proposel_count as $key => $value) { - if(!empty($value['insurers'])){ + if (!empty($value['insurers'])) { $qcr_created = true; } } @@ -869,11 +900,11 @@ class LeadsController extends BaseController if ($insertId) { - if(empty($rfq_created)){ + if (empty($rfq_created)) { $this->leadsModel->update($lead_id, ['status' => "rfq_created"]); } - if($qcr_created == true){ + if ($qcr_created == true) { $this->leadsModel ->where('id', $lead_id) ->whereNotIn('status', ['qcr_sent', 'lost', 'co_insurer_pending', 'won', 'completed_with_corrections', 'completed_without_corrections']) @@ -936,7 +967,7 @@ class LeadsController extends BaseController foreach ($original as $key => $value) { // Match only keys that look like 'Proposal X' - if (preg_match('/^Proposal\s+\d+$/', $key)) { + if (preg_match('/^(Proposal\s+\d+|Existing Renewal|Existing Rollover)$/', $key)) { // Get the insurer entry (not 'Quote Asked') foreach ($value as $subKey => $subVal) { if ($subKey !== 'Quote Asked' && isset($subVal['Total'])) { @@ -996,7 +1027,7 @@ class LeadsController extends BaseController // Collect proposal keys that match the pattern "Proposal X" foreach ($premiumProposals as $key) { - if (preg_match('/^Proposal\s+\d+$/', $key) && isset($data['proposal_data']['over_all_column_data'][$key])) { + if (preg_match('/^(Proposal\s+\d+|Existing Renewal|Existing Rollover)$/', $key) && isset($data['proposal_data']['over_all_column_data'][$key])) { $filteredProposals[$key] = $data['proposal_data']['over_all_column_data'][$key]; } } @@ -1042,8 +1073,12 @@ class LeadsController extends BaseController } // print_rr($reorderedHeaders); die; + $proposel_count = 1; foreach ($reorderedHeaders as $key => &$value) { - $value['parentHeader'] = 'Proposal ' . ($key + 1); + if(!in_array($value['parentHeader'], ["Existing Renewal", "Existing Rollover"])){ + $value['parentHeader'] = 'Proposal ' . $proposel_count; + $proposel_count++; + } } unset($value); @@ -1083,11 +1118,15 @@ class LeadsController extends BaseController foreach ($reorderedProposalData as $key => &$value) { if ($dubParTh == $value['parentth']) { - $value['parentth'] = 'Proposal ' . ($increament); + if(!in_array($value['parentth'], ["Existing Renewal", "Existing Rollover"])){ + $value['parentth'] = 'Proposal ' . ($increament); + } } else { $dubParTh = $value['parentth']; - $increament = $increament + 1; - $value['parentth'] = 'Proposal ' . ($increament); + if(!in_array($value['parentth'], ["Existing Renewal", "Existing Rollover"])){ + $increament = $increament + 1; + $value['parentth'] = 'Proposal ' . ($increament); + } } } unset($value); @@ -1137,13 +1176,12 @@ class LeadsController extends BaseController $lead_id = $this->request->getGet('lead_id'); $data = [ 'no_of_installment' => 0, - 'is_installment'=> 0 + 'is_installment' => 0 ]; $this->leadsModel->where('id', $lead_id)->set($data)->update(); } return $this->respond(['status' => true, 'message' => 'Removed successfully'], 200); - } //-----RFQ and QCR EXPORT------------------------------------------------------------------------------------------------ @@ -1212,15 +1250,17 @@ class LeadsController extends BaseController //Construct excel file and save the file to the folder and return file path public function constructExcelToSaveTemp($lead_id, $type, $propsal_and_insurer = null) { + helper('excel_util_helper'); $rfq_data = $this->RFQModel->getRFQTableDataWithLeadIDAndType($lead_id, $type); $is_placement = false; + $length = 0; // dd($rfq_data, $lead_id, $type, $propsal_and_insurer); // print_r($propsal_and_insurer); die; if ($rfq_data['lead_type'] == 1) { - if (in_array($rfq_data['policy_type_id'], [2,3,4,5])) { + if (in_array($rfq_data['policy_type_id'], [2, 3, 4, 5])) { $lead_data = [ 'Insured' => $rfq_data['client_name'], 'Policy Type' => $this->leadType[$rfq_data['lead_type']] ?? "", @@ -1229,21 +1269,24 @@ class LeadsController extends BaseController 'No of Dependents' => $rfq_data['incept_dept_count'], 'Total Lives' => $rfq_data['incept_no_of_lives'], - 'Period of Insurance ' => !empty($rfq_data['policy_start_date']) && !empty($rfq_data['policy_end_date']) ? date('d/m/Y', strtotime($rfq_data['policy_start_date'])) . ' to ' . date('d/m/Y', strtotime($rfq_data['policy_end_date'])) : "To be decided", + 'Period of Insurance ' => !empty($rfq_data['policy_start_date']) && !empty($rfq_data['policy_end_date']) ? date('d-m-Y', strtotime($rfq_data['policy_start_date'])) . ' to ' . date('d-m-Y', strtotime($rfq_data['policy_end_date'])) : "To be decided", + 'Insurer' => $rfq_data['insurer_name'] ?? " - ", + 'TPA' => $rfq_data['tpa_name'] ?? " - ", // 'Policy Run Days' => $rfq_data['policy_run_days'], ]; - } else if (in_array( $rfq_data['policy_type_id'], [1, 6, 7])) { + } else if (in_array($rfq_data['policy_type_id'], [1, 6, 7])) { $lead_data = [ 'Insured' => $rfq_data['client_name'], 'No of Employees at Inception' => $rfq_data['incept_emp_count'], 'Total Sum Insured at Inception ' => $rfq_data['total_si_at_incept'], - 'Policy Period' => !empty($rfq_data['policy_start_date']) && !empty($rfq_data['policy_end_date']) ? date('d/m/Y', strtotime($rfq_data['policy_start_date'])) . ' to ' . date('d/m/Y', strtotime($rfq_data['policy_end_date'])) : "To be decided", + 'Policy Period' => !empty($rfq_data['policy_start_date']) && !empty($rfq_data['policy_end_date']) ? date('d-m-Y', strtotime($rfq_data['policy_start_date'])) . ' to ' . date('d-m-Y', strtotime($rfq_data['policy_end_date'])) : "To be decided", + 'Insurer' => $rfq_data['insurer_name'] ?? " - ", + 'TPA' => $rfq_data['tpa_name'] ?? " - ", 'Policy Type' => $this->leadType[$rfq_data['lead_type']] ?? "", ]; } - } else { - if (in_array($rfq_data['policy_type_id'], [2,3,4,5])) { + if (in_array($rfq_data['policy_type_id'], [2, 3, 4, 5])) { $lead_data = [ 'Insured' => $rfq_data['client_name'], @@ -1261,22 +1304,26 @@ class LeadsController extends BaseController 'No of Dependents at Renewal' => $rfq_data['renewal_dept_count'], 'Total Lives at Renewal ' => $rfq_data['renewal_no_of_lives'], - 'Period of Insurance ' => !empty($rfq_data['policy_start_date']) && !empty($rfq_data['policy_end_date']) ? date('d/m/Y', strtotime($rfq_data['policy_start_date'])) . ' to ' . date('d/m/Y', strtotime($rfq_data['policy_end_date'])) : "To be decided", + 'Period of Insurance ' => !empty($rfq_data['policy_start_date']) && !empty($rfq_data['policy_end_date']) ? date('d-m-Y', strtotime($rfq_data['policy_start_date'])) . ' to ' . date('d-m-Y', strtotime($rfq_data['policy_end_date'])) : "To be decided", + 'Insurer' => $rfq_data['insurer_name'] ?? " - ", + 'TPA' => $rfq_data['tpa_name'] ?? " - ", 'Policy Run Days' => $rfq_data['policy_run_days'], - 'Inception Premium' => $rfq_data['premium_at_inception'], - 'Premium as on (Date - DD MM YYYY should be entered based on the claims dump report)' => $rfq_data['premium_date'], + 'Inception Premium' => formatIndianCurrency($rfq_data['premium_at_inception']), + 'Premium as on (' . date('d-m-Y', strtotime($rfq_data['incurred_claims_date'])) . ')' => formatIndianCurrency($rfq_data['premium_date']), 'Earned Premium' => $rfq_data['earned_premium'], - 'Incurred Claims as on (Date - DD MM YYYY should be entered based on the claims dump report)' => $rfq_data['incurred_claims_date'], - 'Annualised Claims' => $rfq_data['annualised_claims'], - 'Incurred Claims Ratio' => $rfq_data['incurred_claims_ratio'], - 'Earned Claims Ratio' => $rfq_data['earned_claims_ratio'], + 'Incurred Claims as on (' . date('d-m-Y', strtotime($rfq_data['incurred_claims_date'])) . ')' => formatIndianCurrency($rfq_data['incurred_claims']), + 'Annualised Claims' => formatIndianCurrency($rfq_data['annualised_claims']), + 'Incurred Claims Ratio' => $rfq_data['incurred_claims_ratio'] . " %", + 'Earned Claims Ratio' => $rfq_data['earned_claims_ratio'] . " %", ]; - } else if (in_array( $rfq_data['policy_type_id'], [1, 6, 7])) { + } else if (in_array($rfq_data['policy_type_id'], [1, 6, 7])) { $lead_data = [ 'Insured' => $rfq_data['client_name'], 'No of Employees at Renewal' => $rfq_data['renewal_emp_count'], 'Total Sum Insured at Renewal ' => $rfq_data['total_si_at_renewal'], - 'Policy Period' => !empty($rfq_data['policy_start_date']) && !empty($rfq_data['policy_end_date']) ? date('d/m/Y', strtotime($rfq_data['policy_start_date'])) . ' to ' . date('d/m/Y', strtotime($rfq_data['policy_end_date'])) : "To be decided", + 'Policy Period' => !empty($rfq_data['policy_start_date']) && !empty($rfq_data['policy_end_date']) ? date('d-m-Y', strtotime($rfq_data['policy_start_date'])) . ' to ' . date('d-m-Y', strtotime($rfq_data['policy_end_date'])) : "To be decided", + 'Insurer' => $rfq_data['insurer_name'] ?? " - ", + 'TPA' => $rfq_data['tpa_name'] ?? " - ", 'Policy Type' => $this->leadType[$rfq_data['lead_type']] ?? "", 'Existing Insurer' => $rfq_data['insurer_name'], 'TPA ' => $rfq_data['tpa_name'], @@ -1295,6 +1342,7 @@ class LeadsController extends BaseController list($proposal_key, $insurer_key) = explode('-', $propsal_and_insurer, 2); $data = $this->transformProposelData($data, $proposal_key, $insurer_key); $is_placement = true; + $sheetName = 'Placement'; } } else if ($type == 1) { $sheetName = 'RFQ'; @@ -1317,7 +1365,7 @@ class LeadsController extends BaseController $sheet->getStyle("A{$rowNumber}")->applyFromArray([ 'font' => [ 'bold' => true, - 'size' => 20 + 'size' => 23 ], 'alignment' => [ 'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER, @@ -1373,8 +1421,8 @@ class LeadsController extends BaseController // // Set column width based on max content length (adjusted for padding) $sheet->getColumnDimension('A')->setWidth($maxWidthA * 1.2); - $sheet->getColumnDimension('B')->setWidth($maxWidthA * 5); - $sheet->getColumnDimension('C')->setWidth($maxWidthB * 1.6); + // $sheet->getColumnDimension('B')->setWidth($maxWidthA * 1.5); + $sheet->getColumnDimension('C')->setWidth(35); // $rowNumber += 2; @@ -1398,8 +1446,8 @@ class LeadsController extends BaseController ], ]); $subheader_count = array_sum(array_map(fn($header) => count($header['subHeaders']), $data['table_data']['headers'])); - - if($is_placement == false){ + + if ($is_placement == false) { $subheader_count = $subheader_count - 2; } @@ -1422,18 +1470,24 @@ class LeadsController extends BaseController $sheet->mergeCells($mergeRange); $rowNumber_for_remove_quote_asked = $rowNumber; $rowNumber = $rowNumber + 1; - if($type == 2){ + if ($type == 2) { $subHeaderRow = $rowNumber + 1; - }else{ + } else { $subHeaderRow = $rowNumber_for_remove_quote_asked; } $columnLetter = 'A'; + $header_actual_count = 0; foreach ($headers as $header) { + // Kint::dump($header); if (in_array($header['parentHeader'], ['Item Key', 'Action'])) { continue; } + + if (!in_array($header['parentHeader'], ['Item Key', 'Action', 'Sno', 'Particulars'])) { + $header_actual_count++; + } if ($header['parentHeader'] === 'Sno') { $header['parentHeader'] = 'S.No.'; @@ -1441,17 +1495,20 @@ class LeadsController extends BaseController } if ($header['parentHeader'] === 'Particulars') { - $sheet->getColumnDimension('B')->setWidth(80); + $sheet->getColumnDimension('B')->setWidth(35); } $startColumn = $columnLetter; // Start of the current header range $subHeaderCount = count($header['subHeaders']); // Number of subheaders for this parent header - // Set parent header value - if($is_placement == true && !in_array($header['parentHeader'] , ['Particulars', 'S.No.'])){ + if ($is_placement == true && !in_array($header['parentHeader'], ['Particulars', 'S.No.'])) { $sheet->setCellValue("{$startColumn}{$rowNumber}", "Terms"); - }else{ - $sheet->setCellValue("{$startColumn}{$rowNumber}", $header['parentHeader']); + } else { + if(in_array($header['parentHeader'], ["Existing Renewal", "Existing Rollover"])){ + $sheet->setCellValue("{$startColumn}{$rowNumber}", "Terms"); + }else{ + $sheet->setCellValue("{$startColumn}{$rowNumber}", $header['parentHeader']); + } } $sheet->getStyle("{$startColumn}{$rowNumber}")->applyFromArray([ 'font' => ['bold' => true], @@ -1472,7 +1529,7 @@ class LeadsController extends BaseController // Add subheaders foreach ($header['subHeaders'] as $subHeader) { - if($type == 2 && $is_placement == false){ + if ($type == 2 && $is_placement == false) { $sheet->setCellValue("{$columnLetter}{$subHeaderRow}", $subHeader); } @@ -1482,7 +1539,7 @@ class LeadsController extends BaseController $sheet->getColumnDimension('A')->setWidth(10); } - if($is_placement == false){ + if ($is_placement == false) { $sheet->getStyle("{$columnLetter}{$subHeaderRow}")->applyFromArray([ 'font' => ['bold' => true], 'alignment' => [ @@ -1493,9 +1550,19 @@ class LeadsController extends BaseController } $columnLetter++; // Move to the next column for subheaders + // Kint::dump($subHeader); + $length++; } } + if($header_actual_count == 1 && $type == 1){ + $sheet->getColumnDimension('B')->setWidth(80); + }else{ + $sheet->getColumnDimension('B')->setWidth(35); + } + + // die(); + // Apply border to the header range $prevColumn1 = $this->getPreviousColumn($columnLetter); $headerRange = "A{$rowNumber}:" . "{$prevColumn1}" . "{$subHeaderRow}"; @@ -1512,9 +1579,9 @@ class LeadsController extends BaseController $sheet->getRowDimension($rowNumber)->setRowHeight(25); // Header row height $sheet->getRowDimension($subHeaderRow)->setRowHeight(20); // Subheader row height - if($is_placement == true){ + if ($is_placement == true) { $rowNumber = $subHeaderRow; - }else{ + } else { $rowNumber = $subHeaderRow + 2; } // dd($rowNumber); @@ -1570,10 +1637,17 @@ class LeadsController extends BaseController foreach ($premiumData as $proposal => $insurers) { if ($proposal != 'Particulars') { foreach ($insurers as $insurer => $values) { - $premium[] = $values[$labelArray[0]]; - $gst[] = $values[$labelArray[1]]; - $gstAmt[] = $values[$labelArray[2]]; - $total[] = $values[$labelArray[3]]; + if($insurer == 'Quote Asked'){ + $premium[] = ""; + $gst[] = ""; + $gstAmt[] = ""; + $total[] = ""; + }else{ + $premium[] = formatIndianCurrency($values[$labelArray[0]]); + $gst[] = $values[$labelArray[1]]; + $gstAmt[] = formatIndianCurrency($values[$labelArray[2]]); + $total[] = formatIndianCurrency($values[$labelArray[3]]); + } } } } @@ -1590,9 +1664,9 @@ class LeadsController extends BaseController $rowNumber++; } - if($is_placement == true){ + if ($is_placement == true) { $prevColumn3 = $this->getPreviousColumn($columnLetter); - }else{ + } else { $prevColumn3 = $this->getPreviousColumn($columnLetter, 2); } $premiumRange = "B" . ($rowNumber - 4) . ":" . "{$prevColumn3}" . ($rowNumber - 1); @@ -1611,13 +1685,13 @@ class LeadsController extends BaseController //set imgage and align the row and column // Kint::dump($columnLetter); - if($type == 2){ - if($is_placement == true){ + if ($type == 2) { + if ($is_placement == true) { $columnLetter_img = $this->getPreviousColumn($columnLetter); - }else{ + } else { $columnLetter_img = $this->getPreviousColumn($columnLetter, 2); } - }else{ + } else { $columnLetter_img = $this->getPreviousColumn($columnLetter); } // dd($columnLetter_img); @@ -1640,22 +1714,34 @@ class LeadsController extends BaseController ]); } - $sheet->getColumnDimension($columnLetter_img)->setWidth(40); - $sheet->getRowDimension(1)->setRowHeight(40); // Adjust as needed + $sheet->getColumnDimension($columnLetter_img)->setWidth(35); + $sheet->getRowDimension(1)->setRowHeight(50); // Adjust as needed $drawing = new Drawing(); $path = ROOTPATH . "public/assets/images/Nhance-Logo-Final.png"; // Use FCPATH for server path $drawing->setPath($path); $drawing->setCoordinates("{$columnLetter_img}1"); // Set position in column B - $drawing->setHeight(35); // Adjust image height + $drawing->setHeight(35); // Adjust image + $columnWidth = $sheet->getColumnDimension("C")->getWidth(); // e.g., 20 + $cellPixelWidth = $columnWidth * 7; // Approximate conversion (1 unit ≈ 7 pixels) + $imagePixelWidth = 250; // Approximate width of your image (in pixels) + + $offsetX = max(0, ($cellPixelWidth - $imagePixelWidth) / 2); + $offsetX = $offsetX + 97; + // dd($length); + if ($length >= 4) { + $offsetX = 65; + } else if ($length == 3) { + $offsetX = 65; + } // Center align the image in the cell - $drawing->setOffsetX(110); // Adjust horizontal offset + $drawing->setOffsetX($offsetX); // Adjust horizontal offset $drawing->setOffsetY(10); // Adjust vertical offset $drawing->setWorksheet($sheet); //end - + // Auto-size columns // foreach ($sheet->getColumnIterator() as $column) { @@ -1708,7 +1794,7 @@ class LeadsController extends BaseController // Set filename - $string = ($type == 2) ? ( $is_placement == true ? 'Placement' : 'QCR') : 'RFQ'; + $string = ($type == 2) ? ($is_placement == true ? 'Placement' : 'QCR') : 'RFQ'; $current_year = date('Y'); $next_year = $current_year + 1; $policy_year = "$current_year-$next_year"; @@ -1816,7 +1902,7 @@ class LeadsController extends BaseController ['file_path' => WRITEPATH . 'uploads/lead_files/' . $lead_data['file_name'], 'sheets' => [0, 1]], ['file_path' => WRITEPATH . '/uploads/lead_files/' . $result['filename'], 'sheets' => []], ]; - $outputPath = WRITEPATH . 'uploads/lead_files/' .$lead_data['file_name']; + $outputPath = WRITEPATH . 'uploads/lead_files/' . $lead_data['file_name']; $result_merge = ExcelMergeHelper::mergeExcelFiles($filePaths, $outputPath); if ($result_merge) { // Call the delete function after the file is successfully created @@ -1842,7 +1928,8 @@ class LeadsController extends BaseController public function getDemographyData($members, $age_band_data, $members_heading, $available_col, $col_index) { $first_loop = 0; - $col_index_si = array_search('si enhancement', array_map('strtolower', $members_heading)); + // $col_index_si = array_search('si enhancement', array_map('strtolower', $members_heading)); + $col_index_si = array_search('si', array_map('strtolower', $members_heading)); $col_index_relationship = array_search('relationship', array_map('strtolower', $members_heading)); $relations = []; $si_amt = ['general']; // Initialize with 'general' as per first loop condition @@ -2205,9 +2292,9 @@ class LeadsController extends BaseController $attachment_file_ids = $params['selected_attachment_files']; $from_mail = getenv('email.fromEmail'); - if(in_array($recipient_type ,['placement', 'insurer', 'internal'])){ + if (in_array($recipient_type, ['placement', 'insurer', 'internal'])) { $from_mail = "im@nhanceindia.in"; - }else if(in_array($recipient_type, ['client'])){ + } else if (in_array($recipient_type, ['client'])) { $from_mail = "bs@nhanceindia.in"; } @@ -2237,7 +2324,7 @@ class LeadsController extends BaseController $cc_data = isset($params['cc']) ? $params['cc'] : ""; $param_cc_mail = json_decode($cc_data, true); - + if (isset($param_cc_mail) && is_array($param_cc_mail) && count($param_cc_mail) > 0) { // Fetch user data where ID is in the param_cc_mail array $userData = $this->userModel @@ -2261,7 +2348,7 @@ class LeadsController extends BaseController // Handle case where param_cc_mail is not valid // return $this->respond(['status' => 'failed','code' => 400,'data' => '','message' => 'CC mail not found!'], 200); } - }else if($recipient_type == 'placement'){ + } else if ($recipient_type == 'placement') { $cc_mails = isset($params['cc']) ? json_decode($params['cc'], true) : ""; } @@ -2353,7 +2440,6 @@ class LeadsController extends BaseController ->where(['contact_type' => 'insurer', 'is_active' => 1]) ->whereIn('id', $recipient_mail) ->findAll(); - } else if ($recipient_type == 'client') { $mailIDS = explode(',', $params['contact_mail']); @@ -2386,9 +2472,9 @@ class LeadsController extends BaseController foreach ($recipient_data as $recipient) { $message = $original_message; - $message = str_replace("{{RECIPIENT_NAME}}", $recipient['name'] != "" ? $recipient['name'] :" ", $message); + $message = str_replace("{{RECIPIENT_NAME}}", $recipient['name'] != "" ? $recipient['name'] : " ", $message); $message = str_replace("{{CLIENT_NAME}}", $lead_data['client_name'] != "" ? $lead_data['client_name'] : "", $message); - $message = str_replace("{{POLICY_LONG_NAME}}",$lead_data['long_name'] != ""? $lead_data['long_name'] : "", $message); + $message = str_replace("{{POLICY_LONG_NAME}}", $lead_data['long_name'] != "" ? $lead_data['long_name'] : "", $message); $message = str_replace("{{POLICY_START_DATE}}", change_date_format($lead_data['policy_start_date'], 'Y-m-d', 'd-m-Y'), $message); $message = str_replace("{{DURATION}}", calculate_days_bw_dates($lead_data['policy_end_date'] ?? "", $lead_data['policy_start_date'] ?? "")->days, $message) ?? '--'; @@ -2421,7 +2507,7 @@ class LeadsController extends BaseController 'placement_date' => !empty($params['placement_date']) ? change_date_format($params['placement_date']) : null, 'payment_date' => !empty($params['payment_date']) ? change_date_format($params['payment_date']) : null, 'utr_no' => $params['utr_no'] ?? null, - 'is_cd' => $params['is_cd'] ?? null , + 'is_cd' => $params['is_cd'] ?? null, 'premium_amount' => $params['premium_amount'] ?? null, 'total_amount' => $params['total_amount'] ?? null, 'cd_amount' => $params['cd_amount'] ?? null, @@ -2431,42 +2517,41 @@ class LeadsController extends BaseController $this->leadsModel->where('id', $lead_id)->set($data)->update(); - if(isset($params['installments']) && !empty($params['installments'])){ + if (isset($params['installments']) && !empty($params['installments'])) { $installment_data = json_decode($params['installments'], true); - if(!empty($installment_data)){ + if (!empty($installment_data)) { foreach ($installment_data as $key => $value) { // print_r($value);die - $value['payment_date'] = !empty($value['payment_date']) && strtotime($value['payment_date']) - ? date('Y/m/d', strtotime($value['payment_date'])) - : null; - if(isset($value['id']) && !empty($value['id'])){ + $value['payment_date'] = !empty($value['payment_date']) && strtotime($value['payment_date']) + ? date('Y/m/d', strtotime($value['payment_date'])) + : null; + if (isset($value['id']) && !empty($value['id'])) { $this->leadInstallmentPaymentDetails->where('id', $value['id'])->set($value)->update(); - }else{ + } else { $this->leadInstallmentPaymentDetails->insert($value); } } } } - } if ($recipient_type == 'client') { $this->leadsModel - ->where('id', $lead_id) - ->whereNotIn('status', ['lost', 'co_insurer_pending', 'won', 'completed_with_corrections', 'completed_without_corrections']) - ->set(['status' => "qcr_sent"]) - ->update(); + ->where('id', $lead_id) + ->whereNotIn('status', ['lost', 'co_insurer_pending', 'won', 'completed_with_corrections', 'completed_without_corrections']) + ->set(['status' => "qcr_sent"]) + ->update(); } if ($recipient_type == 'insurer') { $this->leadsModel - ->where('id', $lead_id) - ->whereNotIn('status', ['qcr_created', 'qcr_sent', 'lost', 'co_insurer_pending', 'won', 'completed_with_corrections', 'completed_without_corrections']) - ->set(['status' => "rfq_sent"]) - ->update(); + ->where('id', $lead_id) + ->whereNotIn('status', ['qcr_created', 'qcr_sent', 'lost', 'co_insurer_pending', 'won', 'completed_with_corrections', 'completed_without_corrections']) + ->set(['status' => "rfq_sent"]) + ->update(); } //delete attachment file @@ -2788,7 +2873,7 @@ class LeadsController extends BaseController return $client_id; } catch (\Throwable $e) { - $this->myLogger->logme('error','createClientWithLeadData failed'); + $this->myLogger->logme('error', 'createClientWithLeadData failed'); return false; } } @@ -2808,7 +2893,7 @@ class LeadsController extends BaseController return $branch_id; } catch (\Throwable $e) { - $this->myLogger->logme('error','createClientBranchAndContactWithLeadData failed'); + $this->myLogger->logme('error', 'createClientBranchAndContactWithLeadData failed'); return false; } } @@ -2826,7 +2911,7 @@ class LeadsController extends BaseController return $client_policy_id; } catch (\Throwable $e) { - $this->myLogger->logme('error','createClientPolicyWithLeadData failed'); + $this->myLogger->logme('error', 'createClientPolicyWithLeadData failed'); return false; } } @@ -2930,7 +3015,7 @@ class LeadsController extends BaseController // log_message('error', 'Converted JSON: ' . json_encode($converted_json)); return $this->convertQCRJsonToPolicyTerms($converted_json, $data['policy_type_id'], $proposel_data['proposel_name'], $proposel_data['insurer_name']); } catch (\Throwable $e) { - $this->myLogger->logme('error','preparePolicyTermsFromRFQ'); + $this->myLogger->logme('error', 'preparePolicyTermsFromRFQ'); return null; } } @@ -2993,7 +3078,7 @@ class LeadsController extends BaseController case str_starts_with($item, 'special_condition') && $parentth === $proposel_name && $subth === $insurer_name: // log_message("error","INPUT".json_encode($input_value)); $parts = explode('-', $input_value); - + $labelKey = $policy_type == 1 ? 'gpa_special_condition_label' : 'special_condition_label'; $inputKey = $policy_type == 1 ? 'gpa_special_condition_input' : 'special_condition_input'; @@ -3073,11 +3158,10 @@ class LeadsController extends BaseController if (!empty($item) && !empty($value)) { $finalItem = $item; - + if (strpos($tableGroup['tableId'], 'summary') !== false) { $policy_type = explode('_', $tableGroup['tableId'])[0] ?? ''; $finalItem = $policy_type . ' - ' . $item; - } $terms_array[$finalItem] = $value; } @@ -3321,7 +3405,7 @@ class LeadsController extends BaseController 3 => 'rfq/gmc', 4 => 'rfq/gmc', 5 => 'rfq/gmc', - 17=> 'rfq/burglary', + 17 => 'rfq/burglary', 22 => 'rfq/car', 23 => 'rfq/cpm', 24 => 'rfq/cyber_crime', @@ -3348,39 +3432,92 @@ class LeadsController extends BaseController public function constructNonEbExcelToSaveTemp($lead_id, $type, $propsal_and_insurer = null) { $rfq_data = $this->RFQModel->getRFQTableDataWithLeadIDAndType($lead_id, $type); + $claim_history = $rfq_data['claim_history']; + // dd($claim_history); $lead_data = json_decode($rfq_data['custom_fields'], true) ?? []; + $lead_data['claim_history'] = $claim_history; + // dd($lead_data); if (!is_array($lead_data)) { $lead_data = []; } + + if (isset($lead_data['pincode']) && isset($lead_data['address'])) { + // Reorder keys: address first, then pincode, then the rest + $reordered = ['address' => $lead_data['address'], 'pincode' => $lead_data['pincode']]; + + // Remove existing keys + unset($lead_data['address'], $lead_data['pincode']); + + // Merge reordered with the rest + $lead_data = $reordered + $lead_data; + } $lead_data = array_merge(['Insured' => $rfq_data['client_name']], $lead_data); $policy_registration_data = []; if (isset($rfq_data['registration_json']) && !empty($rfq_data['registration_json'])) { $policy_registration_data = json_decode($rfq_data['registration_json'], true); } - // dd($policy_registration_data); - - // if(!empty($rfq_data['fin_years_claims'])){ - // $claim_details = json_decode($rfq_data['fin_years_claims'], true) ?? []; - // if(!empty($claim_details['finyear'])){ - // $lead_data['claim_details'] = $claim_details['finyear']; - // } - // Kint::dump($claim_details); - // } $jsonData = json_decode($rfq_data['json'], true); $proposalData = end($jsonData); array_pop($jsonData); + $length = 0; + // dd($jsonData[0]['table_data']['headers']); + foreach ($jsonData as $key => $data) { + if ($type == 2) { + + $data = $this->convertNonEbJsonForQCR($data, $type, $proposalData, $key); + + // Kint::dump($data, 'Second'); + + if ($propsal_and_insurer !== null) { + list($proposal_key, $insurer_key) = explode('-', $propsal_and_insurer, 2); + $data = $this->transformNonEbProposelData($data, $proposal_key, $insurer_key, $key); + } + unset($data['proposalData']); + } else if ($type == 1) { + $data = $this->convertNonEbJsonForQCR($data, $type, $proposalData, $key); + unset($data['proposalData']); + } + } + // dd($data); + foreach ($data['table_data']['headers'] as $header) { + if ($header['parentHeader'] != "Action") { + foreach ($header['subHeaders'] as $subHeader) { + // Kint::dump($header['parentHeader']); + // Kint::dump($subHeader); + + $length++; + } + } + } + // dd($length); + $columnLetterForTitle = Coordinate::stringFromColumnIndex($length - 1); + $columnLetterForImage = Coordinate::stringFromColumnIndex($length); + + // dd($columnLetter); + $sheetName = 'Worksheet'; + if ($type == 2) { + $sheetName = 'QCR'; + if ($propsal_and_insurer !== null) { + $sheetName = 'Placement'; + } + } else if ($type == 1) { + $sheetName = 'RFQ'; + } $spreadsheet = new Spreadsheet(); $sheet = $spreadsheet->getActiveSheet(); + $sheet->setTitle($sheetName); + + // Start with lead_data at the top $rowNumber = 1; $title = "Nhance India Insurance Broking Pvt Ltd"; - $mergeRange1 = "A{$rowNumber}:B{$rowNumber}"; + $mergeRange1 = "A{$rowNumber}:{$columnLetterForTitle}{$rowNumber}"; $sheet->mergeCells($mergeRange1); $sheet->setCellValue("A{$rowNumber}", $title); $sheet->getStyle("A{$rowNumber}")->applyFromArray([ @@ -3397,24 +3534,23 @@ class LeadsController extends BaseController // Calculate title width $maxWidthA = mb_strlen($title); + // dd($columnLetterForImage); // Set column width to fit the image properly - $sheet->getColumnDimension('C')->setWidth(20); // Adjust as needed + $sheet->getColumnDimension($columnLetterForImage)->setWidth(40); // Adjust as needed $sheet->getRowDimension($rowNumber)->setRowHeight(40); // Adjust as needed + $drawing = new Drawing(); $path = ROOTPATH . "public/assets/images/Nhance-Logo-Final.png"; // Use FCPATH for server path $drawing->setPath($path); - $drawing->setCoordinates("C{$rowNumber}"); // Set position in column C + $drawing->setCoordinates("{$columnLetterForImage}{$rowNumber}"); // Set position in column C $drawing->setHeight(35); // Adjust image height - // Center align the image in the cell - $drawing->setOffsetX(30); // Adjust horizontal offset - $drawing->setOffsetY(5); // Adjust vertical offset - $drawing->setWorksheet($sheet); + // Apply center alignment to the cell - $sheet->getStyle("C{$rowNumber}")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER); - $sheet->getStyle("C{$rowNumber}")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER); + $sheet->getStyle("{$columnLetterForImage}{$rowNumber}")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER); + $sheet->getStyle("{$columnLetterForImage}{$rowNumber}")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER); $rowNumber++; @@ -3423,15 +3559,32 @@ class LeadsController extends BaseController //Lead Data foreach ($lead_data as $key => $value) { + + // if ($key == 'risk_location') { + // $key == 'risk_details'; + // } + // Kint::dump($key); + // Kint::dump($value); $formattedKey = ucwords(str_replace('_', ' ', $key)); + $formattedKey = $formattedKey == "Risk Location" ? "Risk Details" : $formattedKey; + $formattedKey = $formattedKey == "Address" ? "Communication Address" : $formattedKey; + $formattedValue = ucwords(str_replace("_", " ", $value)); + + if ($key == "claim_history") { + + $formattedValue = $value == "1" ? "Yes" : "No"; + $formattedKey = "Claim Experience"; + + } + // Kint::dump($formattedValue); // Merge A:B for key - $mergeRangeKey = "A{$rowNumber}:B{$rowNumber}"; + $mergeRangeKey = "A{$rowNumber}:{$columnLetterForTitle}{$rowNumber}"; $sheet->mergeCells($mergeRangeKey); // Set values in merged cells $sheet->setCellValue("A{$rowNumber}", $formattedKey); - $sheet->setCellValue("C{$rowNumber}", $value); + $sheet->setCellValue("{$columnLetterForImage}{$rowNumber}", $formattedValue); // Apply styles for alignment and bold text in A:B $sheet->getStyle($mergeRangeKey)->applyFromArray([ @@ -3452,16 +3605,22 @@ class LeadsController extends BaseController // Track max width needed for columns $maxWidthA = max($maxWidthA, mb_strlen($formattedKey)); // Consider title and keys $maxWidthB = max($maxWidthB, mb_strlen((string) $value)); + // if (!empty($policy_registration_data)) { + // dd($policy_registration_data); + + // } $rowNumber++; } + // die(); + // Set column width based on max content length (adjusted for padding) $sheet->getColumnDimension('A')->setWidth($maxWidthA * 1.2); - $sheet->getColumnDimension('B')->setWidth($maxWidthA * 1.2); - $sheet->getColumnDimension('C')->setWidth($maxWidthB * 1.2); + // $sheet->getColumnDimension('B')->setWidth($maxWidthA * 1.2); + // $sheet->getColumnDimension('C')->setWidth($maxWidthB * 1.2); - $rowNumber += 1; + // $rowNumber += 1; //Policy Registration if (!empty($policy_registration_data)) { foreach ($policy_registration_data as $key => $value) { @@ -3469,7 +3628,7 @@ class LeadsController extends BaseController $startRow = $rowNumber; // Track where the block starts // Title Row - $titleMergeRangeKey = "A{$rowNumber}:C{$rowNumber}"; + $titleMergeRangeKey = "A{$rowNumber}:{$columnLetterForImage}{$rowNumber}"; $sheet->mergeCells($titleMergeRangeKey); $sheet->setCellValue("A{$rowNumber}", ucfirst($key) . " Policy Details"); @@ -3490,9 +3649,9 @@ class LeadsController extends BaseController // Policy Type if (isset($value['policyType'])) { - $sheet->mergeCells("A{$rowNumber}:B{$rowNumber}"); + $sheet->mergeCells("A{$rowNumber}:{$columnLetterForTitle}{$rowNumber}"); $sheet->setCellValue("A{$rowNumber}", "Policy Type"); - $sheet->setCellValue("C{$rowNumber}", $value['policyType']); + $sheet->setCellValue("{$columnLetterForImage}{$rowNumber}", $value['policyType']); $sheet->getStyle("A{$rowNumber}:C{$rowNumber}")->applyFromArray([ 'font' => ['bold' => true], @@ -3504,9 +3663,9 @@ class LeadsController extends BaseController $rowNumber++; } else { - $sheet->mergeCells("A{$rowNumber}:B{$rowNumber}"); + $sheet->mergeCells("A{$rowNumber}:{$columnLetterForTitle}{$rowNumber}"); $sheet->setCellValue("A{$rowNumber}", "Policy Type"); - $sheet->setCellValue("C{$rowNumber}", ucfirst($key) . " Policy"); + $sheet->setCellValue("{$columnLetterForImage}{$rowNumber}", ucfirst($key) . " Policy"); $sheet->getStyle("A{$rowNumber}:C{$rowNumber}")->applyFromArray([ 'font' => ['bold' => true], @@ -3522,9 +3681,9 @@ class LeadsController extends BaseController // Type of Business & Nature of Business if (isset($value['productSelection']) && !empty($value['productSelection'])) { // Type of Business - $sheet->mergeCells("A{$rowNumber}:B{$rowNumber}"); + $sheet->mergeCells("A{$rowNumber}:{$columnLetterForTitle}{$rowNumber}"); $sheet->setCellValue("A{$rowNumber}", "Type of Business"); - $sheet->setCellValue("C{$rowNumber}", $this->buisnessType[$value['productSelection']['type_of_buisness']] ?? ''); + $sheet->setCellValue("{$columnLetterForImage}{$rowNumber}", $this->buisnessType[$value['productSelection']['type_of_buisness']] ?? ''); $sheet->getStyle("A{$rowNumber}")->applyFromArray([ 'font' => ['bold' => true], @@ -3537,9 +3696,9 @@ class LeadsController extends BaseController $rowNumber++; // Nature of Business - $sheet->mergeCells("A{$rowNumber}:B{$rowNumber}"); + $sheet->mergeCells("A{$rowNumber}:{$columnLetterForTitle}{$rowNumber}"); $sheet->setCellValue("A{$rowNumber}", "Nature of Business"); - $sheet->setCellValue("C{$rowNumber}", $value['productSelection']['buisness_nature'] ?? ''); + $sheet->setCellValue("{$columnLetterForImage}{$rowNumber}", $value['productSelection']['buisness_nature'] ?? ''); $sheet->getStyle("A{$rowNumber}")->applyFromArray([ 'font' => ['bold' => true], @@ -3554,9 +3713,9 @@ class LeadsController extends BaseController if (isset($value['policyDetails']) && !empty($value['policyDetails'])) { // Type of Business - $sheet->mergeCells("A{$rowNumber}:B{$rowNumber}"); + $sheet->mergeCells("A{$rowNumber}:{$columnLetterForTitle}{$rowNumber}"); $sheet->setCellValue("A{$rowNumber}", "Terrorism"); - $sheet->setCellValue("C{$rowNumber}", ucfirst($value['policyDetails']['terrorism'] ?? 'No')); + $sheet->setCellValue("{$columnLetterForImage}{$rowNumber}", ucfirst($value['policyDetails']['terrorism'] ?? 'No')); $sheet->getStyle("A{$rowNumber}")->applyFromArray([ 'font' => ['bold' => true], @@ -3567,13 +3726,40 @@ class LeadsController extends BaseController ]); $rowNumber++; + } + if (!empty($value['locations'])) { + foreach ($value['locations'] as $index => $location) { + // Merge title cell + $sheet->mergeCells("A{$rowNumber}:{$columnLetterForTitle}{$rowNumber}"); + $sheet->setCellValue("A{$rowNumber}", "Risk " . ($location['select_location'] ?? 'Unknown')); + + // Clean and safe address string + $address1 = ucfirst($location['policyRisk']['address1'] ?? ''); + $address2 = ucfirst($location['policyRisk']['address2'] ?? ''); + $pinCode = $location['policyRisk']['pin_code'] ?? 'No'; + + $fullAddress = "{$address1}, {$address2}, {$pinCode}"; + $sheet->setCellValue("{$columnLetterForImage}{$rowNumber}", $fullAddress); + + // Style the title cell + $sheet->getStyle("A{$rowNumber}")->applyFromArray([ + 'font' => ['bold' => true], + 'alignment' => [ + 'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER, + 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER, + ], + ]); + + $rowNumber++; + } } - $endRow = $rowNumber - 1; // Block ends at previous row + + $endRow = $rowNumber; // Block ends at previous row // Apply border to the whole block - $sheet->getStyle("A{$startRow}:C{$endRow}")->applyFromArray([ + $sheet->getStyle("A{$startRow}:{$columnLetterForImage}{$endRow}")->applyFromArray([ 'borders' => [ 'allBorders' => [ 'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN, @@ -3582,8 +3768,9 @@ class LeadsController extends BaseController ], ]); - $rowNumber += 1; // Add space before the next block + // $rowNumber += 1; // Add space before the next block } + $rowNumber--; // die(); } @@ -3625,6 +3812,7 @@ class LeadsController extends BaseController } $sheet->getColumnDimension($columnLetter)->setWidth(60); + $sheet->getColumnDimension('C')->setWidth(35); if ($header['parentHeader'] == 'Policy') { @@ -3644,7 +3832,7 @@ class LeadsController extends BaseController $startColumn = $columnLetter; // Start of the current header range $subHeaderCount = count($header['subHeaders']); // Number of subheaders for this parent header - + // Kint::dump($subHeaderCount); // Set parent header value $sheet->setCellValue("{$startColumn}{$rowNumber}", $header['parentHeader']); $sheet->getStyle("{$startColumn}{$rowNumber}")->applyFromArray([ @@ -3667,6 +3855,7 @@ class LeadsController extends BaseController $endColumn = $startColumn; // No merge needed if only one subheader } + // Kint::dump($header); // Add subheaders foreach ($header['subHeaders'] as $subHeader) { $sheet->setCellValue("{$columnLetter}{$subHeaderRow}", $subHeader); @@ -3699,7 +3888,6 @@ class LeadsController extends BaseController ], ]); - // Apply border to the header range $prevColumn4 = $this->getPreviousColumn($columnLetter); $headerRange = "A{$rowNumber}:" . "{$prevColumn4}" . "{$subHeaderRow}"; @@ -3718,7 +3906,7 @@ class LeadsController extends BaseController // $rowNumber = $subHeaderRow + 2; $rowNumber = $subHeaderRow + 1; - + $column_data = $data['table_data']['data']; // dd($column_data); $serial_no = 1; @@ -3819,7 +4007,7 @@ class LeadsController extends BaseController } $lastRow = count($lead_data) + 1; - $leadRange = "A1:C{$lastRow}"; + $leadRange = "A1:{$columnLetterForImage}{$lastRow}"; $sheet->getStyle($leadRange)->applyFromArray([ 'borders' => [ @@ -3831,6 +4019,92 @@ class LeadsController extends BaseController ]); } + $columnWidth = $sheet->getColumnDimension("C")->getWidth(); // e.g., 20 + $cellPixelWidth = $columnWidth * 7; // Approximate conversion (1 unit ≈ 7 pixels) + $imagePixelWidth = 250; // Approximate width of your image (in pixels) + + $offsetX = max(0, ($cellPixelWidth - $imagePixelWidth) / 2); + $offsetX = $offsetX + 97; + if ($length >= 4) { + $offsetX = 50; + } else if ($length == 3) { + $offsetX = 140; + } + + // dd($offsetX, $cellPixelWidth, $imagePixelWidth); + $drawing->setOffsetX($offsetX); // Dynamically center + $drawing->setOffsetY(10); // Dynamically center + + $drawing->setWorksheet($sheet); + + $sheet->getStyle('C1')->getAlignment() + ->setHorizontal(Alignment::HORIZONTAL_CENTER) + ->setVertical(Alignment::VERTICAL_CENTER); + + if (!empty($rfq_data['fin_years_claims']) && $claim_history == 1) { + + $claim_details = json_decode($rfq_data['fin_years_claims'], true) ?? []; + + if (!empty($claim_details['finyear'])) { + + // Get headers dynamically + $headers = array_map(function ($key) { + return ucwords(str_replace('_', ' ', $key)); + }, array_keys($claim_details['finyear'][0])); + + $newSheet = new Worksheet($spreadsheet, 'Claims Experience'); + $spreadsheet->addSheet($newSheet); + $spreadsheet->setActiveSheetIndexByName('Claims Experience'); + $sheet = $spreadsheet->getActiveSheet(); + + // Set headers + $sheet->fromArray($headers, NULL, 'A1'); + + // Apply background color and bold style to headers + $headerCellRange = 'A1:' . chr(64 + count($headers)) . '1'; // e.g., A1:G1 + + $sheet->getStyle($headerCellRange)->getFont()->setBold(true); + $sheet->getStyle($headerCellRange)->getFill()->setFillType(Fill::FILL_SOLID)->getStartColor()->setRGB('ADD8E6'); + + // Add border to header + $sheet->getStyle($headerCellRange)->getBorders()->getAllBorders()->setBorderStyle(Border::BORDER_THIN); + + // Fill data and apply borders + $row = 2; + foreach ($claim_details['finyear'] as $record) { + $col = 'A'; + foreach ($record as $value) { + $sheet->setCellValue($col . $row, $value); + $col++; + } + + // Apply border to each data row + $sheet->getStyle('A' . $row . ':' . chr(64 + count($headers)) . $row) + ->getBorders()->getAllBorders()->setBorderStyle(Border::BORDER_THIN); + + $row++; + } + // Auto-size all columns based on header count + for ($i = 0; $i < count($headers); $i++) { + $colLetter = chr(65 + $i); // 'A', 'B', etc. + $sheet->getColumnDimension($colLetter)->setAutoSize(true); + } + + // Enable wrap text for all cells + $maxColLetter = chr(64 + count($headers)); // Last column letter + $sheet->getStyle("A2:{$maxColLetter}{$row}")->getAlignment()->setWrapText(true); + + // Optional: center vertically for neatness + $sheet->getStyle("A2:{$maxColLetter}{$row}")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER); + + // Optional: Make row height auto (helps when wrap text is on) + for ($i = 2; $i < $row; $i++) { + $sheet->getRowDimension($i)->setRowHeight(-1); + } + + } + } + // dd($rowNumber); // Set filename $string = ($type == 2) ? 'QCR' : 'RFQ'; @@ -3993,11 +4267,11 @@ class LeadsController extends BaseController // Ensure 'subHeaders' exists and is an array before filtering if (isset($header['subHeaders']) && is_array($header['subHeaders'])) { $header['subHeaders'] = array_filter($header['subHeaders'], function ($subHeader) { - return in_array($subHeader, ['Quote asked', '-'], true); + return in_array($subHeader, ['Sum Insured', '-'], true); }); } } - + // Kint::dump($header); //Remove insurer Row wise data for RFQ $groupedRows = []; foreach ($first_json['table_data']['data'] as &$row) { @@ -4006,7 +4280,7 @@ class LeadsController extends BaseController $row['data'] = array_filter( $row['data'], function ($item) { - return in_array($item['subth'], ['Sum Insured', '-',"Liability Limit"]); + return in_array($item['subth'], ['Sum Insured', '-', "Liability Limit"]); } ); diff --git a/app/Controllers/PolicyTransactionController.php b/app/Controllers/PolicyTransactionController.php index c6c9aaa8..6622d0fa 100644 --- a/app/Controllers/PolicyTransactionController.php +++ b/app/Controllers/PolicyTransactionController.php @@ -461,9 +461,10 @@ class PolicyTransactionController extends BaseController $insurer_id = null; } - if($data['bro_payable_by'] == 1){ - $cop_amt = isset($data['co_premium'][$index]) && ($data['co_premium'][$index] != "0.00" || !empty($data['co_premium'][$index]) ) ? $data['co_premium'][$index] : ($data['base_premium'][$index] ?? 0); - }else{ + if ($data['bro_payable_by'] == 1) { + $cop_amt = isset($data['co_premium'][$index]) && ($data['co_premium'][$index] != "0.00" && !empty($data['co_premium'][$index])) ? $data['co_premium'][$index] : ($data['base_premium'][$index] ?? 0); + // print_r($cop_amt);die(); + } else { $cop_amt = $data['co_premium'][$index] ?? 0; } @@ -1098,13 +1099,19 @@ class PolicyTransactionController extends BaseController $data['endorsement_data_list'] = $this->policyTransactionModel->getEndorsementTranctionListData($start_date, $end_date, $client_id, $insurer_id, $policy_type_id, $date_type, $issuer, $status); $data['client'] = $this->clientModel->where('is_active', 1)->findAll(); - $data['policy_type'] = $this->policyTypeModel->where('is_active', 1)->findAll(); + $data['policy_types'] = $this->policyTypeModel->where('is_active', 1)->findAll(); $data['insurer'] = $this->insurerModel->where('is_active', 1)->findAll(); // $data['tpa'] = $this->tpaModel->where('is_active', 1)->findAll(); $data['insurer_branch'] = $this->insurerBranchModel->getInsurerBranchesWithInsurerNames(); $data['tpa'] = $this->tpaBranchModel->getTpaBranchesWithTpaNames(); + list($policyList, $policyListByClient) = $this->getPolicyForEndorsment(); + $data['endorsementPolicies'] = $policyList; + $data['endorsementPolicyListByClient'] = $policyListByClient; + + // dd($data); + // print_r($data['endorsementPolicies']);die(); $this->loadLayout('policy_transaction_endorsement_list', $data); } @@ -1648,6 +1655,7 @@ class PolicyTransactionController extends BaseController ->where('policy_transaction.client_id', $client_id) ->where('policy_transaction.client_policy_id', $client_policy_id) ->where('policy_transaction.action_type', 'inception') + ->where('policy_transaction.is_active', 1) ->findAll(); $is_copay_yes = $this->policyTransactionModel @@ -2820,11 +2828,9 @@ class PolicyTransactionController extends BaseController try { $bdsInstallmentData = $this->BdsPlacementModel->getClientInstallmentDetails(); - - }catch (Exception $e) { + } catch (Exception $e) { $this->myLogger->logme('error', 'Exception: ' . $e->getMessage() . 'Page: ' . $e->getFile() . ' Line: ' . $e->getLine()); - } $this->myLogger->logme("error", "Data for BDS Installment " . json_encode($bdsInstallmentData)); // dd($bdsInstallmentData); @@ -2904,17 +2910,17 @@ class PolicyTransactionController extends BaseController 'message' => $message, 'subject' => $subject ]; - } catch (Exception $e) { $this->myLogger->logme('error', 'Exception: ' . $e->getMessage() . 'Page: ' . $e->getFile() . ' Line: ' . $e->getLine()); } } - public function getMoreInfo() { + public function getMoreInfo() + { $pt_id = $this->request->getPost("pt_id"); - $data_to_send['bds_data'] = $this->BdsPlacementModel->where("is_active",1)->where("pt_id",$pt_id)->findAll(); + $data_to_send['bds_data'] = $this->BdsPlacementModel->where("is_active", 1)->where("pt_id", $pt_id)->findAll(); foreach ($data_to_send['bds_data'] as &$data) { @@ -2923,23 +2929,23 @@ class PolicyTransactionController extends BaseController if (!empty($data_to_send)) { - return $this->respond(['status' => true , "data" => $data_to_send],200); - }else { + return $this->respond(['status' => true, "data" => $data_to_send], 200); + } else { - return $this->respond(['status' => false,"No Data Found For the Policy Transaction"],404); + return $this->respond(['status' => false, "No Data Found For the Policy Transaction"], 404); } - } - public function saveInstallment() { - + public function saveInstallment() + { + $installments = $this->request->getPost('installments'); - + if (!$installments || !is_array($installments)) { return $this->respond(['status' => false, 'message' => 'No data received'], 400); } - $this->myLogger->logme("error",json_encode($installments)); + $this->myLogger->logme("error", json_encode($installments)); // die(); foreach ($installments as &$row) { @@ -2956,6 +2962,49 @@ class PolicyTransactionController extends BaseController return $this->respond(['status' => true, 'message' => 'Data saved successfully'], 200); } + protected function getPolicyForEndorsment() + { + + $policyList = []; + $policyListByClient = []; + $clients = $this->clientModel + ->select("*, DATE_FORMAT(dob, '%d-%m-%Y') as dob") + ->where('is_active', 1) + ->findAll(); + + $clientIds = array_column($clients, 'id'); + + $policies = $this->clientPolicyModel + ->select(" + client_policy.*, + policy_type.policy_type, + policy_type.ebp, + policy_type.etp, + policy_type.iep, + policy_type.itp, + policy_type.bap, + policy_type.allocg, + 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('policy_type', 'policy_type.id = client_policy.policy_type_id') + ->join('policy_transaction pt', 'pt.client_policy_id = client_policy.id and pt.action_type = "inception" and pt.is_active = 1 and pt.client_policy_id is not null') + ->whereIn('client_policy.client_id', $clientIds) + ->where('client_policy.is_active', 1) + ->findAll(); + + foreach ($policies as $policy) { + $policyList[$policy['client_branch_id']][] = $policy; + $policyListByClient[$policy['client_id']][] = $policy; + if (isset($policyCount[$policy['client_id']])) { + $policyCount[$policy['client_id']]++; + } else { + $policyCount[$policy['client_id']] = 1; + } + } + + return [$policyList, $policyListByClient]; + } } diff --git a/app/Controllers/RestAuthenticationController.php b/app/Controllers/RestAuthenticationController.php index 77c6854c..a31dabe7 100755 --- a/app/Controllers/RestAuthenticationController.php +++ b/app/Controllers/RestAuthenticationController.php @@ -65,6 +65,12 @@ class RestAuthenticationController extends AdminController } + + + + + + public function verifyEmployeeWithMobileNumber() { try { @@ -78,7 +84,7 @@ class RestAuthenticationController extends AdminController ->where('employees.emp_status !=', 'truncated') ->where('employees.mobile', $mobile_number) ->where('EP.is_active', 1) - ->whereIn('EP.status', ['active']) + ->whereIn('EP.status', ['active', 'expired']) ->first(); @@ -118,7 +124,7 @@ class RestAuthenticationController extends AdminController ->where('employees.emp_status !=', 'truncated') ->where('employees.email_corporate', $email) ->where('EP.is_active', 1) - ->whereIn('EP.status', ['active']) + ->whereIn('EP.status', ['active', 'expired']) ->first(); if (isset($employeeData['employee_id'])) { @@ -272,6 +278,13 @@ class RestAuthenticationController extends AdminController } } + + + + + + + public function verifyHrWithMobileNumber() { try { @@ -295,16 +308,105 @@ class RestAuthenticationController extends AdminController return $this->respond(['status' => 'failed','code' => 500,'data' => $th],500); } } + + public function verifyHrWithEmail() + { + try { + + $data = $this->request->getJSON(); + + $email = $data->email; + + $HrData = $this->hrModel->where('email', $email) + ->where('contact_type', 'client') + ->where('is_active', 1) + ->first(); + + if ($HrData) { + + $otp = random_int(100000, 999999); + + $sql = " + UPDATE level_contacts + SET otp = ? + WHERE email = ? + AND contact_type = 'client' + AND is_active = 1 + "; + + $db = db_connect(); + $update = $db->query($sql, [$otp, $email]); + + if($update) + { + $data->otp = $otp; + + $common = [ + 'login_type' => 'HR login', + 'login_email' => $email, + 'mail_type' => 'otp_mail' + ]; + $subject = 'Nhance user verification - OTP'; + $mail_content = $otp . ' is your verification code for Nhance.'; + $res = MailHelper::send_email(['mail' => $email, 'subject' => $subject, 'common' => $common, 'message' => $mail_content]); + $this->myLogger->logme("info", $res); + + if (json_decode($res)->status == 'success') { + $result = ['user_verification' => true, 'message' => "Verified Successfully"]; + return $this->respond(['status' => 'success', 'code' => 200, 'data' => $result], 200); + } else { + $result = ['user_verification' => false, 'message' => "Mail sending failed , try again"]; + return $this->respond(['status' => 'failed', 'code' => 404, 'data' => $result], 200); + } + } else { + + $result = ['user_verification' => false, 'message' => "Verification failed , try again"]; + return $this->respond(['status' => 'failed', 'code' => 404, 'data' => $result], 200); + } + + } else { + $result = ['user_verification' => false, 'message' => "User not found"]; + return $this->respond(['status' => 'failed', 'code' => 404, 'data' => $result], 200); + } + } catch (\Throwable $th) { + return $this->respond(['status' => 'failed','code' => 500,'data' => $th],500); + } + } + public function updateHROTP() + { + + $email = $this->request->getJSON()->email; + $otp = $this->request->getJSON()->otp; + + $this->hrModel->where('email', $email) ->where('contact_type', 'client') + ->where('is_active', 1)->set(array('otp' => $otp)) + ->update(); + + return true; + + } public function getVerifiedHrData() { try { - $mobile_number = $this->request->getJSON()->mobile_number; - $otp_verification = $this->request->getJSON()->otp_verification; + // mobile number + $otp_verification = isset($this->request->getJSON()->otp_verification) ? $this->request->getJSON()->otp_verification : null; + $mobile_number = isset($this->request->getJSON()->mobile_number) ? $this->request->getJSON()->mobile_number : null; + // email id + $otp = isset($this->request->getJSON()->otp) ? $this->request->getJSON()->otp : null; + $email = isset($this->request->getJSON()->email) ? $this->request->getJSON()->email : null; + + if (isset($mobile_number)) + { + $hrData = $this->hrModel->where('mobile', $mobile_number)->where('contact_type', 'client')->first(); + }else{ + $hrData = $this->hrModel->where('email', $email)->where('contact_type', 'client')->where('otp', $otp)->first(); + } + + if ($hrData && $otp_verification == true || $hrData && isset($this->request->getJSON()->otp) ) + { - $hrData = $this->hrModel->where('mobile', $mobile_number)->first(); - if ($hrData && $otp_verification == true) { $auth = HttpRequestHelper::getRequestInfo(); if ($auth) { $data = [ @@ -320,15 +422,34 @@ class RestAuthenticationController extends AdminController } - $hrData = $this->hrModel ->select('level_contacts.* , client_branch.client_id as client_id') + if(isset($this->request->getJSON()->mobile_number)){ + + $hrData = $this->hrModel ->select('level_contacts.* , client_branch.client_id as client_id') + ->join('client_branch', 'level_contacts.ref_id = client_branch.id', 'left') + ->where('level_contacts.mobile', $mobile_number ) + ->where('level_contacts.contact_type', 'client') + ->find(); + + }else if(isset($this->request->getJSON()->otp)){ + + $this->hrModel->where('email', $email)->where('otp', $otp)->where('contact_type', 'client')->set(['otp'=>null])->update(); + + $hrData = $this->hrModel ->select('level_contacts.* , client_branch.client_id as client_id') ->join('client_branch', 'level_contacts.ref_id = client_branch.id', 'left') - ->where('level_contacts.mobile', $mobile_number ) + ->where('level_contacts.email', $email ) + ->where('level_contacts.contact_type', 'client') ->find(); + } $result = JWTToken::encode($hrData['0']); - return $this->respond(['status' => 'success','code' => 200,'data' => $result],200); + + + return $this->respond(['status' => 'success','code' => 200,'data' => $result ],200); + + } else { - return $this->respond(['status' => 'failed','code' => 404,'data' => "Invalid OTP"],200); + + return $this->respond(['status' => 'failed','code' => 404,'data' => "Invalid OTP" ],200); } } catch (\Exception $e) { return $this->respond(['status' => 'failed','code' => 500,'data' => $e->getMessage()],500); @@ -505,5 +626,32 @@ class RestAuthenticationController extends AdminController } + // TokenController.php + public function bookstackLoginToken() + { + $session = \Config\Services::session(); + $user_data = session()->get('userData'); + $user = $user_data->email; + $secret = getenv('bookstack.token'); + // $user = 'staff@staff.com'; + $name = $user_data->first_name ?? 'User'; + + $payload = [ + 'email' => $user, + 'name' => $name, + 'exp' => time() + (60 * 60 * 24) // expires in 1 day + ]; + + // dd($payload); + $token = base64_encode(json_encode($payload)); + $signature = hash_hmac('sha256', $token, $secret); + $bookStackUrl = getenv('bookstack.baseURL'); + + $url = $bookStackUrl . urlencode($token) . '&sig=' . $signature; + return redirect()->to($url); + } + + + } \ No newline at end of file diff --git a/app/Controllers/TicketController.php b/app/Controllers/TicketController.php index 9474bac2..1807f9b9 100644 --- a/app/Controllers/TicketController.php +++ b/app/Controllers/TicketController.php @@ -1659,6 +1659,8 @@ class TicketController extends BaseController $policies = $this->employeePolicyModel ->select('client_policy_id') ->where('employee_id', $emp_id) + ->where('is_active', 1) + ->where('status', 'active') ->findAll(); if (empty($policies)) { @@ -1670,8 +1672,20 @@ class TicketController extends BaseController // Fetch all policy names and IDs in one query $policyNameandID = $this->clientPolicyModel - ->select('CONCAT(policy_type.policy_type, "-", client_policy.policy_no) as client_policy_name, client_policy.id as client_policy_value,client_policy.policy_type_id,client_policy.policy_no') + ->select(' + CONCAT(policy_type.policy_type, "-", client_policy.policy_no) as client_policy_name, + client_policy.id as client_policy_value, + client_policy.policy_type_id, + client_policy.policy_no, + insurers.id as insurer_id, + insurers.name as insurer_name, + tpa.name as tpa_name, + tpa.id as tpa_id, + ') ->join('policy_type', 'policy_type.id = client_policy.policy_type_id AND policy_type.is_active = 1') + ->join('insurers', 'insurers.id = client_policy.insurer_id AND insurers.is_active = 1', 'left') + ->join('tpa', 'tpa.id = client_policy.tpa_id AND tpa.is_active = 1', 'left') + ->where('client_policy.policy_status', 1) ->whereIn('client_policy.id', $policy_ids) ->findAll(); @@ -1840,8 +1854,12 @@ class TicketController extends BaseController $this->loadLayout("ticket_feedback_list",$data); } - public function getMoreInfo() { - $ticket_id = $this->request->getPost('ticket_id'); + public function getMoreInfo($requestFrom = null , $ticket_id) { + + if($requestFrom == null){ + $ticket_id = $this->request->getPost('ticket_id'); + } + $this->myLogger->logme("error", "Ticket ID : " . $ticket_id); $fields = $this->extraFields; @@ -1905,6 +1923,9 @@ class TicketController extends BaseController $this->myLogger->logme('error', "Total data: " . json_encode($data_to_send)); + if($requestFrom == 'rest'){ + return $data_to_send; + } // Send response based on data availability if (!empty($data_to_send)) { return $this->respond(['status' => true, 'data' => $data_to_send], 200); diff --git a/app/Controllers/UserController.php b/app/Controllers/UserController.php index b9f5c34e..cc23a148 100755 --- a/app/Controllers/UserController.php +++ b/app/Controllers/UserController.php @@ -12,6 +12,7 @@ use App\Models\UserModel; use App\Models\RoleModel; use App\Models\TeamModel; use App\Models\UserTeamsModel; +use App\Helpers\BookStackUserHelper; class UserController extends AdminController @@ -21,6 +22,7 @@ class UserController extends AdminController protected $roleModel; protected $teamModel; protected $userTeamsModel; + protected $bookStack; public function __construct() { @@ -31,6 +33,7 @@ class UserController extends AdminController $this->roleModel = new RoleModel(); $this->teamModel = new TeamModel(); $this->userTeamsModel = new UserTeamsModel(); + $this->bookStack = new BookStackUserHelper(); } public function list() @@ -60,10 +63,17 @@ class UserController extends AdminController $userData['created_by'] = get_session_userid(); $temp_team = $userData['team']; unset($userData['team']); + $insert = $this->userModel->insert($userData); - if ($insert) { + $bookStackData = [ + 'name' => $userData['first_name'], + 'email' => $userData['email'], + + ]; + $this->bookStack->createEditUser($bookStackData); + if ($insert) { $teamData['user_id'] = $insert; foreach ($teams as $value) { $teamData['team_id'] = $value; @@ -137,10 +147,20 @@ class UserController extends AdminController unset($userData['csrf_test_name']); unset($userData['PrimaryKey']); + $existingData = $this->userModel->where('id',$id)->first();; + // Update data in the 'users' table based on the $id $userData['updated_by'] = get_session_userid(); $update = $this->userModel->where('id', $id)->set($userData)->update(); + $bookStackData = [ + 'name' => $userData['first_name'], + 'email' => $userData['email'], + ]; + + $this->bookStack->createEditUser($bookStackData,$existingData); + + if ($update) { if ($teams) { @@ -211,7 +231,11 @@ class UserController extends AdminController public function deactive($id = null) { $model = new UserModel(); + + $emailToDelete = $model->where('id', $id)->first(); $deactive = $model->where('id', $id)->set(['is_active' => 0])->update(); + + $this->bookStack->deleteUser($emailToDelete); if($deactive) { // $db = \Config\Database::connect(); diff --git a/app/Helpers/BookStackUserHelper.php b/app/Helpers/BookStackUserHelper.php new file mode 100644 index 00000000..c27386b2 --- /dev/null +++ b/app/Helpers/BookStackUserHelper.php @@ -0,0 +1,77 @@ +userModel = new BookStackUserModel(); + $this->roleModel = new BookStackRoleModel(); + } + + public function createEditUser($data,$preData = null) { + // This function will handle the creation or editing of a user + // It will check if the user already exists and update or create accordingly + // The $data parameter should contain all necessary user information + // For example: ['name' => 'johndoe', 'email' => 'johndoe@doe.com'] + + if (!empty($preData)) { + + $isExistingUser = $this->userModel->where('email', $preData['email'])->first(); + + if ($isExistingUser) { + $id = $isExistingUser['id']; + $update = $this->userModel->where('id', $id)->set($data)->update(); + return $update; + } + } + + $password = 'password'; + $hashedPassword = ['password' => password_hash($password, PASSWORD_DEFAULT)]; + + $slug = ['slug' => $this->createSlug($data['name'])]; + + // array_push($data,$hashedPassword,$slug); + + $data['password'] = $hashedPassword['password']; + $data['slug'] = $slug['slug']; + + // dd($data); + $this->userModel->insert($data); + $userId = $this->userModel->insertID(); + + if (!empty($userId)) { + + $roleData = [ + 'user_id' => $userId, + 'role_id' => 3 // 3 is the default role ID for viewers + ]; + + $this->roleModel->insert($roleData); + } + + + } + + protected function createSlug($string) { + return strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $string))); + } + + public function deleteUser($data) { + + $isExistingUser = $this->userModel->where('email', $data['email'])->first(); + if ($isExistingUser) { + $id = $isExistingUser['id']; + $delete = $this->userModel->where('id', $id)->delete(); + $this->roleModel->where('user_id', $id)->delete(); + return $delete; + } + + } +} \ No newline at end of file diff --git a/app/Helpers/DepositHelper.php b/app/Helpers/DepositHelper.php index 5137cc5c..9549f8a1 100755 --- a/app/Helpers/DepositHelper.php +++ b/app/Helpers/DepositHelper.php @@ -102,10 +102,10 @@ class DepositHelper // $getLastBalanceParams = [$clientId, $insurerId]; if(empty($cd_ac_pk)){ - $getLastBalanceQuery = "SELECT balance FROM cash_deposit WHERE cd_ac_no = ? AND is_active = 1 ORDER BY created_at DESC LIMIT 1"; + $getLastBalanceQuery = "SELECT balance FROM cash_deposit WHERE cd_ac_no = ? AND is_active = 1 ORDER BY id DESC LIMIT 1"; $getLastBalanceParams = [$cd_ac_no]; }else{ - $getLastBalanceQuery = "SELECT balance FROM cash_deposit WHERE cd_ac_pk = ? AND is_active = 1 ORDER BY created_at DESC LIMIT 1"; + $getLastBalanceQuery = "SELECT balance FROM cash_deposit WHERE cd_ac_pk = ? AND is_active = 1 ORDER BY id DESC LIMIT 1"; $getLastBalanceParams = [$cd_ac_pk]; } diff --git a/app/Helpers/excel_util_helper.php b/app/Helpers/excel_util_helper.php index fbaa1193..141fe725 100755 --- a/app/Helpers/excel_util_helper.php +++ b/app/Helpers/excel_util_helper.php @@ -1385,7 +1385,7 @@ if (!function_exists('premium_calculation_manager')) { } //this if condition for premium calculated & premium type 3 (familiy floater but premium calculated every individual implemented later) then remove si amount only for dependents (not self) - if ($is_match_found && strtolower($emp_data['relationship']) != 'self' && $temp_slab_rates[0]['premium_type'] == 3) { + if ($is_match_found && strtolower($emp_data['relationship']) != 'self' && $temp_slab_rates[0]['premium_type'] == 3 && $policy_terms['is_addon'] != 3) { //set dependent si to 0 $emp_data['policy_details']['basic_cover_si'] = 0; } @@ -2008,4 +2008,30 @@ if (!function_exists('generate_family_floater_key')) { return $relation; } -} \ No newline at end of file +} + +if (!function_exists('formatIndianCurrency')) { + function formatIndianCurrency($amount) + { + $amount = (string) $amount; + $decimal = ''; + + // Split decimal part if exists + if (strpos($amount, '.') !== false) { + list($amount, $decimal) = explode('.', $amount); + $decimal = '.' . substr($decimal, 0, 2); // Limit to 2 decimal places + } + + $lastThree = substr($amount, -3); + $rest = substr($amount, 0, -3); + + if ($rest != '') { + $rest = preg_replace("/\B(?=(\d{2})+(?!\d))/", ",", $rest); + $formatted = $rest . ',' . $lastThree; + } else { + $formatted = $lastThree; + } + + return $formatted . $decimal; + } +} diff --git a/app/Models/BookStackRoleModel.php b/app/Models/BookStackRoleModel.php new file mode 100644 index 00000000..a57256a9 --- /dev/null +++ b/app/Models/BookStackRoleModel.php @@ -0,0 +1,19 @@ +where('client_policy.client_id', $id) ->where('cd_master.id = client_policy.cd_ac_pk') ->where('cd_master.is_active', 1) - ->groupBy('client_policy.insurer_id') ->groupBy('client_policy.client_id', $id) // Group by insurer_id + ->groupBy('client_policy.insurer_id') + ->groupBy('client_policy.cd_ac_pk') ->get() ->getResult(); @@ -225,10 +226,10 @@ class ClientPolicyModel extends Model } - public function getDepositData($clientId, $insurerId) + public function getDepositData($clientId, $insurerId, $cd_ac_pk = null) { - // Fetch the deposit data based on client and insurer IDs - return $this->db->table('cash_deposit') + // Fetch the deposit data based on client and insurer IDs + $query = $this->db->table('cash_deposit') ->select('cash_deposit.*') ->select('insurers.name as insurer_name, insurers.short_name as insurer_short') ->select('clients.client_name as clientname, clients.short_name as clientshort, client_policy.policy_no') @@ -245,15 +246,18 @@ class ClientPolicyModel extends Model ->join('policy_type', 'policy_type.id = client_policy.policy_type_id', 'left') ->where('cash_deposit.client_id', $clientId) ->where('cash_deposit.insurer_id', $insurerId) - ->where('cash_deposit.is_active', 1) + ->where('cash_deposit.is_active', 1); // ->where('cash_deposit.cd_ac_pk = cd_master.id') - ->orderBy('cash_deposit.id', 'DESC') - ->get() - ->getResult(); + if(!empty($cd_ac_pk)){ + $query->where('cash_deposit.cd_ac_pk', $cd_ac_pk); + } + $query->orderBy('cash_deposit.id', 'DESC'); + + return $query->get()->getResult(); } - public function getDepositSummary($clientId, $insurerId) + public function getDepositSummary($clientId, $insurerId, $cd_ac_pk) { // Fetch the sum of credit and debit transactions and calculate the balance return $this->db->table('cash_deposit') @@ -263,6 +267,7 @@ class ClientPolicyModel extends Model ->select('SUM(CASE WHEN sub_type = 3 THEN amount ELSE 0 END) AS total_refund') ->where('client_id', $clientId) ->where('insurer_id', $insurerId) + ->where('cd_ac_pk', $cd_ac_pk) ->where('cash_deposit.is_active', 1) ->get() ->getRow(); @@ -315,10 +320,12 @@ class ClientPolicyModel extends Model public function getDepositlistsummary($id) { return $this->db->table('cash_deposit') - ->select('insurer_id') + ->select('insurer_id, cd_ac_pk') ->select('SUM(CASE WHEN transaction_type = "Credit" THEN amount ELSE -amount END) AS balance') ->where('client_id', $id) + ->where('is_active', 1) ->groupBy('insurer_id') + // ->groupBy('cd_ac_pk') ->get() ->getResult(); } @@ -326,14 +333,18 @@ class ClientPolicyModel extends Model public function updateStatus() { - // Update client_policy table $client = $this->db->query("UPDATE client_policy SET policy_status = 0 WHERE policy_end_date < CURDATE()"); $client_count = $this->db->affectedRows(); + // Update employee_polices table $employee = $this->db->query("UPDATE employee_polices SET status = 'expired' WHERE policy_end_date < CURDATE()"); $emp_count = $this->db->affectedRows(); + // Log the result + log_message('info', "Client policies updated: {$client_count}"); + log_message('info', "Employee policies updated: {$emp_count}"); + return ['client' => $client_count, 'emp' => $emp_count]; } @@ -358,12 +369,12 @@ class ClientPolicyModel extends Model { $query = " - SELECT client_policy.*, policies.name, policies.policy_type_id - FROM client_policy - JOIN policies ON policies.id = client_policy.policy_id - JOIN policy_type ON policy_type.id = policies.policy_type_id - WHERE policy_type.policy_type = '{$type}' - AND client_policy.client_id = {$client_id}"; + SELECT client_policy.*, policies.name, policies.policy_type_id + FROM client_policy + JOIN policies ON policies.id = client_policy.policy_id + JOIN policy_type ON policy_type.id = policies.policy_type_id + WHERE policy_type.policy_type = '{$type}' + AND client_policy.client_id = {$client_id}"; $result = $this->db->query($query)->getResult(); diff --git a/app/Models/EmployeePolicyModel.php b/app/Models/EmployeePolicyModel.php index 7f6310af..f6ff81ed 100755 --- a/app/Models/EmployeePolicyModel.php +++ b/app/Models/EmployeePolicyModel.php @@ -416,7 +416,7 @@ class EmployeePolicyModel extends Model employees.designation AS emp_designation, employees.basic_pay AS emp_basic_pay, - TIMESTAMPDIFF(YEAR, employees.dob, CURDATE()) AS emp_age, + TIMESTAMPDIFF(YEAR, employees.dob, employee_polices.date_coverage) AS emp_age, employees.emp_type as emp_type, @@ -597,17 +597,17 @@ class EmployeePolicyModel extends Model public function getSIEnhancementEmployeesDataForExportExcel($ref_data, $return_type = 0) { - $client_id = $ref_data['client_id']; - $client_policy_id = $ref_data['client_policy_id']; - $client_branch_id = $ref_data['client_branch_id']; - $insurer_or_tpa = $ref_data['insurer_or_tpa']; + $client_id = $ref_data['client_id']; + $client_policy_id = $ref_data['client_policy_id']; + $client_branch_id = $ref_data['client_branch_id']; + $insurer_or_tpa = $ref_data['insurer_or_tpa']; - $endorsement_condition = "{$insurer_or_tpa}" === 'tpa' ? "AND (a.endorsement_id IS NOT NULL OR a.endorsement_id != '')" : "AND (a.endorsement_id IS NULL OR a.endorsement_id = '')"; + $endorsement_condition = "{$insurer_or_tpa}" === 'tpa' ? "AND (a.endorsement_id IS NOT NULL OR a.endorsement_id != '')" : "AND (a.endorsement_id IS NULL OR a.endorsement_id = '')"; - $query = $this->db->query(" - SELECT - a.id as endorsement_primarykey, + $query = $this->db->query(" + SELECT + a.id AS endorsement_primarykey, a.group_key, employee_polices.id AS primaryKey, employees.name AS emp_name, @@ -616,10 +616,8 @@ class EmployeePolicyModel extends Model employees.gender AS emp_gender, employees.relationship_code AS emp_relationship_code, employees.relationship AS emp_relationship, - employees.emp_type as emp_type, - 'SI' as event_type_data, - - + employees.emp_type AS emp_type, + 'SI' AS event_type_data, employees.doj AS emp_doj, employees.mobile AS emp_mobile, employees.email_corporate AS emp_email_c, @@ -627,97 +625,59 @@ class EmployeePolicyModel extends Model employees.band AS emp_grade, employees.designation AS emp_designation, employees.basic_pay AS emp_basic_pay, - employee_polices.uhid AS uhid, employee_polices.pre_existing_alignments, employee_polices.policy_end_date, - employee_polices.basic_cover_si as old_basic_cover_si, - employee_polices.rata_premimum as old_si_premium, + employee_polices.basic_cover_si AS old_basic_cover_si, + employee_polices.premium AS old_si_premium, + employee_polices.rata_premimum AS old_rata_premium, employee_polices.age_band, - - batch_data.emp_policy_id, - batch_data.bl AS batch_list_batch_code, - batch_data.bf AS batch_files_batch_code, - - sidata.new_basic_cover_si, + sidata.new_basic_cover_si, sidata.new_si_premium, + sidata.old_si_premium, sidata.date_of_coverage, - DATEDIFF(employee_polices.policy_end_date, sidata.date_of_coverage) + 1 AS no_of_days, - - sidata.new_si_premium - employee_polices.rata_premimum AS difference_premium, - - ROUND((sidata.new_si_premium - employee_polices.rata_premimum) * (DATEDIFF(employee_polices.policy_end_date, sidata.date_of_coverage) + 1) / 365, 2) AS pro_rata_premium, - - ROUND(((sidata.new_si_premium - employee_polices.rata_premimum) * (DATEDIFF(employee_polices.policy_end_date, sidata.date_of_coverage) + 1) / 365) * 0.18, 2) AS gst, - + ROUND(sidata.new_si_premium - sidata.old_si_premium, 2) AS difference_premium, ROUND( - ((sidata.new_si_premium - employee_polices.rata_premimum) * - (DATEDIFF(employee_polices.policy_end_date, sidata.date_of_coverage) + 1) / 365) + + (sidata.new_si_premium - sidata.old_si_premium) * + (DATEDIFF(employee_polices.policy_end_date, sidata.date_of_coverage) + 1) / 365, + 2 + ) AS pro_rata_premium, + ROUND( + ( + (sidata.new_si_premium - sidata.old_si_premium) * + (DATEDIFF(employee_polices.policy_end_date, sidata.date_of_coverage) + 1) / 365 + ) * 0.18, + 2 + ) AS gst, + ROUND( + ( + (sidata.new_si_premium - sidata.old_si_premium) * + (DATEDIFF(employee_polices.policy_end_date, sidata.date_of_coverage) + 1) / 365 + ) + ROUND( - ((sidata.new_si_premium - employee_polices.rata_premimum) * - (DATEDIFF(employee_polices.policy_end_date, sidata.date_of_coverage) + 1) / 365) * 0.18, 2 - ), 2 + ( + (sidata.new_si_premium - sidata.old_si_premium) * + (DATEDIFF(employee_polices.policy_end_date, sidata.date_of_coverage) + 1) / 365 + ) * 0.18, + 2 + ), + 2 ) AS total - - FROM + FROM emp_endorsement a - LEFT JOIN - employees ON employees.emp_code = a.emp_code - LEFT JOIN - employee_polices ON employees.id = employee_polices.employee_id + LEFT JOIN employees ON employees.emp_code = a.emp_code + LEFT JOIN employee_polices ON employees.id = employee_polices.employee_id LEFT JOIN ( - SELECT - aa.emp_code, - aa.new_value as 'new_basic_cover_si', - bb.new_value as 'new_si_premium', - cc.new_value as 'date_of_coverage' - FROM ( - SELECT - a1.emp_code, - a1.field_name, - a1.new_value - FROM - emp_endorsement as a1 - WHERE - a1.field_name = 'basic_cover_si' - ) aa - LEFT JOIN ( - SELECT - b1.emp_code, - b1.field_name, - b1.new_value - FROM - emp_endorsement as b1 - WHERE - b1.field_name = 'premium' - ) bb ON aa.emp_code = bb.emp_code - LEFT JOIN ( - SELECT - c1.emp_code, - c1.field_name, - c1.new_value - FROM - emp_endorsement as c1 - WHERE - c1.field_name = 'si_enhancement_date' - ) cc ON aa.emp_code = cc.emp_code - ) as sidata ON a.emp_code = sidata.emp_code - LEFT JOIN ( - SELECT DISTINCT - 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 = 'si_enhancement' - AND batch_files.actions = 'export' - AND batch_files.insurer_or_tpa = '{$insurer_or_tpa}' - ) AS batch_data ON employee_polices.id = batch_data.emp_policy_id - + SELECT + emp_code, + CAST(MAX(CASE WHEN field_name = 'basic_cover_si' THEN new_value END) AS UNSIGNED) AS new_basic_cover_si, + CAST(MAX(CASE WHEN field_name = 'premium' THEN new_value END) AS DECIMAL(10,2)) AS new_si_premium, + CAST(MAX(CASE WHEN field_name = 'premium' THEN old_value END) AS DECIMAL(10,2)) AS old_si_premium, + MAX(CASE WHEN field_name = 'si_enhancement_date' THEN new_value END) AS date_of_coverage + FROM emp_endorsement + GROUP BY emp_code + ) AS sidata ON a.emp_code = sidata.emp_code WHERE employee_polices.client_policy_id = '{$client_policy_id}' AND employees.client_branch_id = '{$client_branch_id}' $endorsement_condition @@ -730,20 +690,177 @@ class EmployeePolicyModel extends Model group by group_key "); - // Get the result set - $results = $query->getResult(); + // Get the result set + $results = $query->getResult(); - if($return_type == 1){ - $results = $query->getResultArray(); - }else{ - $results = $query->getResult(); - } - - // dd($this->db->getLastQuery()); - return $results; + if ($return_type == 1) { + $results = $query->getResultArray(); + } else { + $results = $query->getResult(); + } + // dd($this->db->getLastQuery()); + return $results; } + // DO NOT DELETE this SI ENHANCEMENT QUERY FUNCTION + + // public function getSIEnhancementEmployeesDataForExportExcel($ref_data, $return_type = 0) + // { + + // $client_id = $ref_data['client_id']; + // $client_policy_id = $ref_data['client_policy_id']; + // $client_branch_id = $ref_data['client_branch_id']; + // $insurer_or_tpa = $ref_data['insurer_or_tpa']; + + // $endorsement_condition = "{$insurer_or_tpa}" === 'tpa' ? "AND (a.endorsement_id IS NOT NULL OR a.endorsement_id != '')" : "AND (a.endorsement_id IS NULL OR a.endorsement_id = '')"; + + + // $query = $this->db->query(" + // SELECT + // a.id as endorsement_primarykey, + // a.group_key, + // employee_polices.id AS primaryKey, + // employees.name AS emp_name, + // employees.emp_code AS emp_code, + // employees.dob AS emp_dob, + // employees.gender AS emp_gender, + // employees.relationship_code AS emp_relationship_code, + // employees.relationship AS emp_relationship, + // employees.emp_type as emp_type, + // 'SI' as event_type_data, + + + // employees.doj AS emp_doj, + // employees.mobile AS emp_mobile, + // employees.email_corporate AS emp_email_c, + // employees.email_personal AS emp_email_p, + // employees.band AS emp_grade, + // employees.designation AS emp_designation, + // employees.basic_pay AS emp_basic_pay, + + // employee_polices.uhid AS uhid, + // employee_polices.pre_existing_alignments, + // employee_polices.policy_end_date, + // employee_polices.basic_cover_si as old_basic_cover_si, + // employee_polices.premium as old_si_premium, + // employee_polices.rata_premimum as old_rata_premium, + // employee_polices.age_band, + + // batch_data.emp_policy_id, + // batch_data.bl AS batch_list_batch_code, + // batch_data.bf AS batch_files_batch_code, + + // sidata.new_basic_cover_si, + // sidata.new_si_premium, + // sidata.old_si_premium, + // sidata.date_of_coverage, + + // DATEDIFF(employee_polices.policy_end_date, sidata.date_of_coverage) + 1 AS no_of_days, + + // ROUND(sidata.new_si_premium - sidata.old_si_premium, 2) AS difference_premium, + + // ROUND((sidata.new_si_premium - sidata.old_si_premium) * (DATEDIFF(employee_polices.policy_end_date, sidata.date_of_coverage) + 1) / 365, 2) AS pro_rata_premium, + + // ROUND(((sidata.new_si_premium - sidata.old_si_premium) * (DATEDIFF(employee_polices.policy_end_date, sidata.date_of_coverage) + 1) / 365) * 0.18, 2) AS gst, + + // ROUND( + // ((sidata.new_si_premium - sidata.old_si_premium) * + // (DATEDIFF(employee_polices.policy_end_date, sidata.date_of_coverage) + 1) / 365) + + // ROUND( + // ((sidata.new_si_premium - sidata.old_si_premium) * + // (DATEDIFF(employee_polices.policy_end_date, sidata.date_of_coverage) + 1) / 365) * 0.18, 2 + // ), 2 + // ) AS total + + // FROM + // emp_endorsement a + // LEFT JOIN + // employees ON employees.emp_code = a.emp_code + // LEFT JOIN + // employee_polices ON employees.id = employee_polices.employee_id + // LEFT JOIN ( + // SELECT + // aa.emp_code, + // aa.new_value as 'new_basic_cover_si', + // bb.new_value as 'new_si_premium', + // bb.old_value as 'old_si_premium', + // cc.new_value as 'date_of_coverage' + // FROM ( + // SELECT + // a1.emp_code, + // a1.field_name, + // a1.new_value, + // a1.old_value + // FROM + // emp_endorsement as a1 + // WHERE + // a1.field_name = 'basic_cover_si' + // ) aa + // LEFT JOIN ( + // SELECT + // b1.emp_code, + // b1.field_name, + // b1.new_value, + // b1.old_value + // FROM + // emp_endorsement as b1 + // WHERE + // b1.field_name = 'premium' + // ) bb ON aa.emp_code = bb.emp_code + // LEFT JOIN ( + // SELECT + // c1.emp_code, + // c1.field_name, + // c1.new_value, + // c1.old_value + // FROM + // emp_endorsement as c1 + // WHERE + // c1.field_name = 'si_enhancement_date' + // ) cc ON aa.emp_code = cc.emp_code + // ) as sidata ON a.emp_code = sidata.emp_code + // LEFT JOIN ( + // SELECT DISTINCT + // 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 = 'si_enhancement' + // AND batch_files.actions = 'export' + // AND batch_files.insurer_or_tpa = '{$insurer_or_tpa}' + // ) AS batch_data ON employee_polices.id = batch_data.emp_policy_id + + // WHERE employee_polices.client_policy_id = '{$client_policy_id}' + // AND employees.client_branch_id = '{$client_branch_id}' + // $endorsement_condition + // AND a.actions = 'si' + // AND a.status != 'truncated' + // AND employee_polices.is_active = 1 + // AND employee_polices.status = 'active' + // AND employees.is_active = 1 + // AND employees.emp_status = 'active' + // group by group_key + // "); + + // // Get the result set + // $results = $query->getResult(); + + // if($return_type == 1){ + // $results = $query->getResultArray(); + // }else{ + // $results = $query->getResult(); + // } + + // // dd($this->db->getLastQuery()); + // return $results; + + // } + // DO NOT DELETE this DELETION QUERY FUNCTION // public function getDeletionEmployeeDataForExportExcel($ref_data, $return_type = 0) @@ -944,10 +1061,10 @@ class EmployeePolicyModel extends Model } $status_condition = "{$insurer_or_tpa}" === 'tpa' - ? "employee_polices.status = 'active' AND employees.emp_status = 'active'" + ? "employee_polices.status = 'inactive' AND employees.emp_status = 'active'" : "employee_polices.status = 'active' AND employees.emp_status = 'active'"; - $endorsement_condition = "{$insurer_or_tpa}" === 'tpa' ? "AND (a.endorsement_id IS NULL OR a.endorsement_id = '')" : "AND (a.endorsement_id IS NULL OR a.endorsement_id = '')"; + $endorsement_condition = "{$insurer_or_tpa}" === 'tpa' ? "AND (a.endorsement_id IS NOT NULL OR a.endorsement_id != '')" : "AND (a.endorsement_id IS NULL OR a.endorsement_id = '')"; $query = $this->db->query(" SELECT DISTINCT @@ -972,7 +1089,8 @@ class EmployeePolicyModel extends Model employee_polices.basic_cover_si, employee_polices.uhid as uhid, - employee_polices.rata_premimum as premium, + employee_polices.rata_premimum, + ROUND(employee_polices.premium,2) as premium, employee_polices.claim_status, employee_polices.age_band, employee_polices.tpa_id, @@ -998,22 +1116,22 @@ class EmployeePolicyModel extends Model CASE WHEN deletiondata.claimstatus = 0 OR deletiondata.claimstatus IS NULL THEN - ROUND((employee_polices.rata_premimum * (DATEDIFF(employee_polices.policy_end_date, deletiondata.dateofexit) + $add_one_day)) / 365, 2) + ROUND((employee_polices.premium * (DATEDIFF(employee_polices.policy_end_date, deletiondata.dateofexit) + $add_one_day)) / 365, 2) ELSE 0 END AS pro_rata_premium, CASE WHEN deletiondata.claimstatus = 0 OR deletiondata.claimstatus IS NULL THEN - ROUND(((employee_polices.rata_premimum * (DATEDIFF(employee_polices.policy_end_date, deletiondata.dateofexit) + $add_one_day)) / 365) * 0.18, 2) + ROUND(((employee_polices.premium * (DATEDIFF(employee_polices.policy_end_date, deletiondata.dateofexit) + $add_one_day)) / 365) * 0.18, 2) ELSE 0 END AS gst, CASE WHEN deletiondata.claimstatus = 0 OR deletiondata.claimstatus IS NULL THEN - ROUND(((employee_polices.rata_premimum * (DATEDIFF(employee_polices.policy_end_date, deletiondata.dateofexit) + $add_one_day)) / 365) + - (((employee_polices.rata_premimum * (DATEDIFF(employee_polices.policy_end_date, deletiondata.dateofexit) + $add_one_day)) / 365) * 0.18), 2) + ROUND(((employee_polices.premium * (DATEDIFF(employee_polices.policy_end_date, deletiondata.dateofexit) + $add_one_day)) / 365) + + (((employee_polices.premium * (DATEDIFF(employee_polices.policy_end_date, deletiondata.dateofexit) + $add_one_day)) / 365) * 0.18), 2) ELSE 0 END AS total, diff --git a/app/Models/LeadsModel.php b/app/Models/LeadsModel.php index fc0e2bb3..6b5264e8 100644 --- a/app/Models/LeadsModel.php +++ b/app/Models/LeadsModel.php @@ -97,6 +97,7 @@ class LeadsModel extends Model 'is_installment', 'no_of_installment', 'is_policy_created', + 'claim_history' ]; diff --git a/app/Views/client_basic_info.php b/app/Views/client_basic_info.php index 9e41c616..220164b8 100755 --- a/app/Views/client_basic_info.php +++ b/app/Views/client_basic_info.php @@ -125,13 +125,13 @@ input:checked + .slider:before { -
+ diff --git a/app/Views/client_deposit_list.php b/app/Views/client_deposit_list.php index d19d0ec6..ab076ebb 100755 --- a/app/Views/client_deposit_list.php +++ b/app/Views/client_deposit_list.php @@ -49,7 +49,7 @@ insurer_id}?client_id={$value->client_id}"); ?>"> + href="insurer_id}?client_id={$value->client_id}&cd_ac_pk={$value->cd_ac_pk}"); ?>"> View Deposit diff --git a/app/Views/client_onboarding.php b/app/Views/client_onboarding.php index 6b4210a4..5327b58b 100755 --- a/app/Views/client_onboarding.php +++ b/app/Views/client_onboarding.php @@ -94,16 +94,16 @@ body { API --> -
- Is Payable by employee: + id="is_payable_employee_for_child"> --> @@ -304,12 +304,12 @@ name="other_member_max_age" id="other_member_max_age" onchange="lowerIsEighteen(this)"> - Is Payable by employee: + id="is_payable_employee_for_elders"> --> @@ -1373,46 +1373,46 @@ $('#other_member_max_age').val(jsonObject[key].elders.max); } - if (key.includes("is_payable_employee")) { + // if (key.includes("is_payable_employee")) { - if (jsonObject[key]) { + // if (jsonObject[key]) { - if (jsonObject[key].self == 0) { - $('#is_payable_employee_for_self').prop('checked', - false); - } else { - $('#is_payable_employee_for_self').prop('checked', - true); - } + // if (jsonObject[key].self == 0) { + // $('#is_payable_employee_for_self').prop('checked', + // false); + // } else { + // $('#is_payable_employee_for_self').prop('checked', + // true); + // } - if (jsonObject[key].spouse == 0) { - $('#is_payable_employee_for_spouse').prop('checked', - false); - } else { - $('#is_payable_employee_for_spouse').prop('checked', - true); - } + // if (jsonObject[key].spouse == 0) { + // $('#is_payable_employee_for_spouse').prop('checked', + // false); + // } else { + // $('#is_payable_employee_for_spouse').prop('checked', + // true); + // } - if (jsonObject[key].childern == 0) { - $('#is_payable_employee_for_child').prop('checked', - false); - } else { - $('#is_payable_employee_for_child').prop('checked', - true); - } + // if (jsonObject[key].childern == 0) { + // $('#is_payable_employee_for_child').prop('checked', + // false); + // } else { + // $('#is_payable_employee_for_child').prop('checked', + // true); + // } - if (jsonObject[key].elders == 0) { - $('#is_payable_employee_for_elders').prop('checked', - false); - } else { - $('#is_payable_employee_for_elders').prop('checked', - true); - } + // // if (jsonObject[key].elders == 0) { + // // $('#is_payable_employee_for_elders').prop('checked', + // // false); + // // } else { + // // $('#is_payable_employee_for_elders').prop('checked', + // // true); + // // } - } + // } - } + // } if (key.includes("enrollment_display_key") && key != "") { diff --git a/app/Views/policy_grid.php b/app/Views/policy_grid.php index 69e8e3db..06c945c6 100755 --- a/app/Views/policy_grid.php +++ b/app/Views/policy_grid.php @@ -108,6 +108,7 @@ onchange="addGridHTML(this)" required> +