From 5e3c126b0b9f6dd7b049c9432865bdc529dbb31e Mon Sep 17 00:00:00 2001 From: aadhavan valli Date: Sat, 20 Jul 2024 09:57:35 +0530 Subject: [PATCH 01/19] CHANGE_ADD_NEW_API_FIREBASE_TOKEN_API_EMP_REST : AADHAVAN --- app/Config/Routes.php | 2 + app/Controllers/EmployeeRestController.php | 2605 ++++++++++---------- 2 files changed, 1332 insertions(+), 1275 deletions(-) diff --git a/app/Config/Routes.php b/app/Config/Routes.php index 4778427f..06888fcb 100644 --- a/app/Config/Routes.php +++ b/app/Config/Routes.php @@ -136,6 +136,7 @@ $routes->group("/employee", ["filter" => "authMVC"], function ($routes) { $routes->post("upload", "EmployeeController::employeesUplodWithEvents"); $routes->get("excel_error/(:any)", "EmployeeController::getExcelFileErrors/$1"); $routes->get("endorsement-list", "EmployeeController::endorsementList"); + $routes->get("enrollment-list", "EmployeeController::enrollmentList"); $routes->get("truncate/(:any)", "EmployeeController::truncateFileData/$1"); }); @@ -287,6 +288,7 @@ $routes->group("/api", ["filter" => "authJWT"], function ($routes) { $routes->get("getChatResponse", "ChatBotController::getChatResponse"); $routes->group("employeeRest", ["filter" => "authJWT"], function ($routes) { + $routes->post("storeFireBase", "EmployeeRestController::storeFireBase"); $routes->post("saveMpin", "RestAuthenticationController::saveMpin"); $routes->post("updateMpin", "RestAuthenticationController::updateMpin"); $routes->get("getChatResponse", "ChatBotController::getChatResponse"); diff --git a/app/Controllers/EmployeeRestController.php b/app/Controllers/EmployeeRestController.php index d7ba79f2..40d6f8b5 100644 --- a/app/Controllers/EmployeeRestController.php +++ b/app/Controllers/EmployeeRestController.php @@ -928,634 +928,154 @@ class EmployeeRestController extends AdminController } -//------------------------------------- -public function getAgeRange($terms,$familyFloatesValue) -{ - - $ageRangeArray = ['self' => ['min' => 18, 'max' => 60] , 'spouse' => ['min' => 18, 'max' => 60] , 'child' => ['min' => 0, 'max' => 25] , 'elders' => ['min' => 18, 'max' => 60] ]; - - $ageKey = (preg_replace('/\d/', '', $familyFloatesValue) == 'parent' || preg_replace('/\d/', '', $familyFloatesValue) == 'parent_in_law') ? 'elders' : preg_replace('/\d/', '', $familyFloatesValue); - if(isset($terms->age_ratio)){ - return $terms->age_ratio->$ageKey; - }else{ - return $ageRangeArray[$ageKey]; - } - - -} - -public function getEmployeePolicy() -{ - // try { - - $id = $this->request->getGet('id'); - $emp_code = $this->request->getGet('emp_code'); - $client_id = $this->request->getGet('client_id'); - $client_branch_id = $this->request->getGet('client_branch_id'); - - // This is an array containing keys to be removed from the terms and conditions array - $keysToRemove = ["removable_keys"]; - // Retrieve employee policy data by passing the employee primary key - $empPolicy = $this->employeeModel->getEmployeePolicy($id); - - // Retrieve employee and dependents data by passing the employee code - $employeeData = $this->employeeModel->where('emp_code',$emp_code) - ->where('client_id',$client_id) - ->where('client_branch_id',$client_branch_id) - ->where('is_active', 1 ) - ->where('is_addon_value',0)->findAll(); - - - if ($empPolicy) { - - $result = []; - foreach ($empPolicy as $array) { - // Reset employee array - $empData = $employeeData; - - - // Removes specific keys from the decoded array and assigns the result to $refusingData - $decodedArray = json_decode($array->Policy_Terms); - $refusingData = (object) array_diff_key((array) $decodedArray, array_flip($keysToRemove)); - $array->Policy_Terms = $refusingData; - - // Retrieve slab rate and grid master data by passing the ClientPolicyId and ClientId - $getSlabAndGridData = $this->policesModel->getPolicySlabRatesForEmpOnboard($array->ClientPolicyId,$array->ClientId); - $array->SlabRates = $getSlabAndGridData['slab_rates']; - $array->GridMaster = $getSlabAndGridData['grid_master']; - - if($array->tpa_id != null){ - $array->eCardDownload = base_url('download-e-card/') . $array->rand_string; - }else{ $array->eCardDownload = null; } - - - // Construct value for policy type GPA - if($getSlabAndGridData['grid_master']['policy_type'] == "GPA" && $this->request->getGet('policy') == 'GPA'){ - - // Filter employee data where the family_floater_key is 'self' - $selfData = array_filter($empData, fn($arr) => trim(strtolower($arr['family_floater_key'])) === 'self'); - $employee_policy = $this->employeePolicyModel->where('employee_id',$selfData[0]['id'])->where('client_policy_id',$array->ClientPolicyId)->where('is_active', 1 )->get()->getRow(); - - $self['is_value_exist'] = true; - $self['data']['family_floater_key'] = 'self'; - $self['data']['employee_id'] = $id; - $self['data']['relationship'] = 'Self'; - $self['data']['name'] = $selfData[0]['name']; - $self['data']['dob'] = $this->convertDateFormatDMY($selfData[0]['dob']); - $self['data']['mobile'] = $selfData[0]['mobile']; - $self['data']['client_policy_id'] = $array->ClientPolicyId; - $self['data']['basic_cover_si'] = $employee_policy->basic_cover_si; - - $array->mapped_family_floaters = $self; - - // Return result - if($this->request->getGet('policy') == 'GPA') - { - return $this->respond(['status' => 'success','code' => 200,'data' => $array], 200); - } - - // Construct value for policy type GMC - }else if($getSlabAndGridData['grid_master']['policy_type'] == "GMC" && $this->request->getGet('policy') == 'GMC' ){ - - - - // Map family floaters that already exist in the employee table - $familyFloates = $array->Policy_Terms->family_floaters; - - // Generate Notes string based on familyFloates terms - $array->notes = $this->FloterNotesConvertion($familyFloates); - - if($getSlabAndGridData['slab_rates'][0]['premium_type'] == 1) - { - $array->floter_text_heading = 'Floater Sum Insured'; - $array->floter_text_description = 'This is a floater sum insured. A floater is a type of sum insured that provides coverage to more than one member ot a family at the same time. Simply put, its a single insurance cover for the entire family.'; - }else{ - $array->floter_text_heading = 'Sum Insured'; - $array->floter_text_description = ''; - } - - // remove parent and parent-in-law from familyFloaters - if($familyFloates->{'either-parents-pil'} != 0){ - unset($familyFloates->parents); - unset($familyFloates->parents_in_law); - } - $floters = $this->FloterConvertion($familyFloates); - - $data = []; - foreach ($floters as $familyFloatesValue) { - $dependent = preg_replace('/\d/', '', $familyFloatesValue); - - if(count($empData)){ - foreach ($empData as $key => $value) { - if ($value['family_floater_key'] === $dependent) { - $employee_policy = $this->employeePolicyModel->where('employee_id',$value['id'])->where('client_policy_id',$array->ClientPolicyId)->where('is_active', 1 )->get()->getRow(); - $temp['is_value_exist'] = true; - $temp['data']['family_floater_key'] = $familyFloatesValue; - $temp['data']['employee_id'] = $value['id']; - $temp['data']['relationship'] = $value['relationship']; - $temp['data']['name'] = $value['name']; - $temp['data']['dob'] = $this->convertDateFormatDMY($value['dob']); - $temp['data']['client_policy_id'] = $array->ClientPolicyId; - $temp['data']['form_type'] = $dependent; - $temp['data']['basic_cover_si'] = $employee_policy->basic_cover_si; - - - $temp['data']['age_validation'] = $this->getAgeRange($decodedArray,$familyFloatesValue); - - array_push($data,$temp); - unset($empData[$key]); - $floters = array_diff($floters, [$familyFloatesValue]); - break; - } - } - } - } - - - - // Remove Unwanted floter key from floters array based on either-parents-pil term value - if($familyFloates->{'either-parents-pil'} == 1 && count($floters)) - { - $count_parent = 0; - $count_parent_in_law = 0; - foreach ($floters as $value) { - if (preg_replace('/\d/', '', $value) == 'parent') { $count_parent++; } - if (preg_replace('/\d/', '', $value) == 'parent_in_law') {$count_parent_in_law++;} - } - if($count_parent != 2) { - $floters = array_filter($floters, fn($value) => strpos($value, 'parent_in_law') === false); - } - if($count_parent_in_law != 2) { - $floters = array_filter($floters, fn($value) => strpos($value, 'parent') === false || strpos($value, 'parent_in_law') !== false); - } - } - else if($familyFloates->{'either-parents-pil'} == 2 && count($floters)) - { - $count_parent = 0; - $count_parent_in_law = 0; - foreach ($floters as $value) { - if (preg_replace('/\d/', '', $value) == 'parent') { $count_parent++; } - if (preg_replace('/\d/', '', $value) == 'parent_in_law') {$count_parent_in_law++;} - } - if(($count_parent + $count_parent_in_law) == 2) { - $floters = array_filter($floters, fn($value) => strpos($value, 'parent') === false); - } - - } - - - // Add family floter buttons placement data for FE validation - if(count($floters)){ - foreach ($floters as $familyFloatesValue) { - - $temp2['is_value_exist'] = false; - $temp2['data']['family_floater_key'] = $familyFloatesValue; - $temp2['data']['client_policy_id'] = $array->ClientPolicyId; - $temp2['data']['button_name'] = 'Add '.ucfirst(str_replace('_', ' ', preg_replace('/\d/', '', $familyFloatesValue))); - $temp2['data']['form_type'] = preg_replace('/\d/', '', $familyFloatesValue); - - - $temp2['data']['age_validation'] = $this->getAgeRange($decodedArray,$familyFloatesValue); - - array_push($data,$temp2); - - } - } - - $array->mapped_family_floaters = $data; - $array->type = "Group Medical Coverage"; - - $checkGmcParentsPolicyExist = $this->clientPolicyModel->select('client_policy.id as ClientPolicyId , client_policy.client_id as ClientId, policies.id as PolicyId , client_policy.policy_type_id as policy_type_id, policies.name as Policy_Name , client_policy.is_addon as is_addon , client_policy.open_for_enrollment as OpenForEnrollment , client_policy.inception_type as inception_type , client_policy.policy_terms as Policy_Terms') - ->join('policies', 'client_policy.policy_id = policies.id', 'left') - ->where('client_policy.policy_type_id', 3 ) - ->where('client_policy.is_addon', 1 ) - ->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 ) - ->get() - ->getResult(); - if($checkGmcParentsPolicyExist) - { - $GmcParrentsData = $this->getGmcParrentsPolicy($checkGmcParentsPolicyExist,$emp_code,$client_id,$client_branch_id); - return $this->respond(['status' => 'success','code' => 200,'data' => [$array,$GmcParrentsData]], 200); - - } - - if($this->request->getGet('policy') == 'GMC'){ - return $this->respond(['status' => 'success','code' => 200,'data' => [$array]], 200); - } - - } - - // $result[] = $array; - } - - return $this->respond(['status' => 'success','code' => 200,'data' => []], 200); - - - }else{ - return $this->respond(['status' => 'failed','code' => 404,'data' => []], 200); - } - // } catch (\Exception $e) { - // return $this->respond(['status' => 'failed','code' => 500,'data' => $e->getMessage()], 500); - // } -} - - -public function getGmcParrentsPolicy($GmcParrentsPolicy,$emp_code,$client_id,$client_branch_id) -{ - - $employeeData = $this->employeeModel->where('emp_code',$emp_code) - ->where('client_id',$client_id) - ->where('client_branch_id',$client_branch_id) - ->where('is_active', 1 ) - ->where('is_addon_value',0)->findAll(); - foreach ($GmcParrentsPolicy as $key => $array) { - - - - // Reset employee array - $empData = $employeeData; - - - $array->Policy_Terms = json_decode($array->Policy_Terms); - - - // Retrieve slab rate and grid master data by passing the ClientPolicyId and ClientId - $getSlabAndGridData = $this->policesModel->getPolicySlabRatesForEmpOnboard($array->ClientPolicyId,$array->ClientId); - $array->SlabRates = $getSlabAndGridData['slab_rates']; - $array->GridMaster = $getSlabAndGridData['grid_master']; - - $tpaArray = $this->employeeModel->select('employees.name as name , employee_polices.tpa_id as tpa_id , employee_polices.rand_string as rand_string') - ->join('employee_polices', 'employee_polices.employee_id = employees.id') - ->where('employees.emp_code',$emp_code) - ->where('employees.is_active',1) - ->where('employee_polices.client_policy_id',$array->ClientPolicyId) - ->get() - ->getResult(); - - if(count($tpaArray)) - { - - if($tpaArray[0]->tpa_id != null) - $array->eCardDownload = base_url('download-e-card/') . $tpaArray[0]->rand_string; - else - $array->eCardDownload = null; - - }else{ - $array->eCardDownload = null; - } - - - $array->eCardDownload = null; - - // Map family floaters that already exist in the employee table - $familyFloates = $array->Policy_Terms->family_floaters; - - // Generate Notes string based on familyFloates terms - $array->notes = $this->FloterNotesConvertion($familyFloates); - - if($getSlabAndGridData['slab_rates'][0]['premium_type'] == 1) - { - $array->floter_text_heading = 'Floater Sum Insured'; - $array->floter_text_description = 'This is a floater sum insured. A floater is a type of sum insured that provides coverage to more than one member ot a family at the same time. Simply put, its a single insurance cover for the entire family.'; - }else{ - $array->floter_text_heading = 'Sum Insured'; - $array->floter_text_description = ''; - } - - - // remove parent and parent-in-law from familyFloaters - if($familyFloates->{'either-parents-pil'} != 0){ - unset($familyFloates->parents); - unset($familyFloates->parents_in_law); - } - - // Convert familyFloaters terms data to plain array - $floters = $this->FloterConvertion($familyFloates); - $data = []; - foreach ($floters as $familyFloatesValue) { - $dependent = preg_replace('/\d/', '', $familyFloatesValue); - - - if(count($empData)){ - foreach ($empData as $key => $value) { - if ($value['family_floater_key'] === $dependent) { - $employee_policy = $this->employeePolicyModel->where('employee_id',$value['id'])->where('client_policy_id',$array->ClientPolicyId)->where('is_active', 1 )->get()->getRow(); - // dd( $employee_policy); - $temp['is_value_exist'] = true; - $temp['data']['family_floater_key'] = $familyFloatesValue; - $temp['data']['employee_id'] = $value['id']; - $temp['data']['relationship'] = $value['relationship']; - $temp['data']['name'] = $value['name']; - $temp['data']['dob'] = $this->convertDateFormatDMY($value['dob']); - $temp['data']['client_policy_id'] = $array->ClientPolicyId; - $temp['data']['form_type'] = $dependent; - $temp['data']['basic_cover_si'] = $employee_policy->basic_cover_si; - $temp['data']['age_validation'] = $this->getAgeRange($array->Policy_Terms,$familyFloatesValue); - - - array_push($data,$temp); - unset($empData[$key]); - $floters = array_diff($floters, [$familyFloatesValue]); - break; - } - } - } - } - - // Remove Unwanted floter key from floters array based on either-parents-pil term value - if($familyFloates->{'either-parents-pil'} == 1 && count($floters)) - { - $count_parent = 0; - $count_parent_in_law = 0; - foreach ($floters as $value) { - if (preg_replace('/\d/', '', $value) == 'parent') { $count_parent++; } - if (preg_replace('/\d/', '', $value) == 'parent_in_law') {$count_parent_in_law++;} - } - if($count_parent != 2) { - $floters = array_filter($floters, fn($value) => strpos($value, 'parent_in_law') === false); - } - if($count_parent_in_law != 2) { - $floters = array_filter($floters, fn($value) => strpos($value, 'parent') === false || strpos($value, 'parent_in_law') !== false); - } - } - else if($familyFloates->{'either-parents-pil'} == 2 && count($floters)) - { - $count_parent = 0; - $count_parent_in_law = 0; - foreach ($floters as $value) { - if (preg_replace('/\d/', '', $value) == 'parent') { $count_parent++; } - if (preg_replace('/\d/', '', $value) == 'parent_in_law') {$count_parent_in_law++;} - } - if(($count_parent + $count_parent_in_law) == 2) { - $floters = array_filter($floters, fn($value) => strpos($value, 'parent') === false); - } - - } - - // Add family floter buttons placement data for FE validation - if(count($floters)){ - foreach ($floters as $familyFloatesValue) { - - $temp2['is_value_exist'] = false; - $temp2['data']['family_floater_key'] = $familyFloatesValue; - $temp2['data']['client_policy_id'] = $array->ClientPolicyId; - $temp2['data']['button_name'] = 'Add '.ucfirst(str_replace('_', ' ', preg_replace('/\d/', '', $familyFloatesValue))); - $temp2['data']['form_type'] = preg_replace('/\d/', '', $familyFloatesValue); - $temp2['data']['age_validation'] = $this->getAgeRange($array->Policy_Terms,$familyFloatesValue); - array_push($data,$temp2); - - } - } - - $array->mapped_family_floaters = $data; - $array->type = "Group Medical Coverage - Parents"; - - return $array; - - } - -} - -public function FloterConvertion($array){ - - $result = []; - - foreach ($array as $key => $value) { - if ($value > 0 && $key != 'elders_count') { - if ($value != 0 && $key === 'childrens') { - for ($i = 1; $i <= $value; $i++) { - $result[] = "child" . $i; - } - } else if($value != 0 && $key ==='parents') { - for ($i = 1; $i <= $value; $i++) { - $result[] = "parent" . $i; - } - }else if($value != 0 && $key ==='parents-in-law') { - for ($i = 1; $i <= $value; $i++) { - $result[] = "parent_in_law" . $i; - } - }else if($value != 0 && $key ==='either-parents-pil') { - for ($i = 1; $i <= 2; $i++) { - $result[] = "parent" . $i; - $result[] = "parent_in_law" . $i; - } - }else { - $result[] = $key; - } - } - } - - return $result; -} - -public function FloterNotesConvertion($array){ - - $result = ' '; - foreach ($array as $key => $value) { - if ($value > 0) { - if($value != 0 && $key ==='either-parents-pil') { - $result .= ' + Either 2 Parents or 2 Parents in law'; - }else if($value != 0 && $key ==='spouse') { - $string = str_replace('-', ' ', $key); - $string = ucwords($string); - $result .= ' + '.$string; - }else if($value != 0 && $key ==='self') { - $result = 'Can Add Self '; - }else if($value != 0 && $key ==='childrens') { - if($value > 1){ $result .= ' + '.$value.' Children'; }else{ $result .= ' + '.$value.' Child'; } - }else{ - $string = str_replace('-', ' ', $key); - $string = ucwords($string); - $result .= ' + '.$value.' '.$string; - } - } - } + //------------------------------------- + public function getAgeRange($terms,$familyFloatesValue) + { - return $result; -} - -public function getClientDetails() -{ - try { - - $client = $this->clientModel->where('id',$this->request->getGet('client_id'))->first(); - if($client) { - $client['client_logo'] = base_url().'public/uploads/logo/'.$client['client_logo']; - $clientPolicy = $this->clientPolicyModel->where('client_id',$this->request->getGet('client_id')) - ->where('client_branch_id',$this->request->getGet('client_branch_id'))->findAll(); - return $this->respond(['status' => 'success','code' => 200,'data' => ['client'=>$client,'client_policy'=>$clientPolicy]], 200); + $ageRangeArray = ['self' => ['min' => 18, 'max' => 60] , 'spouse' => ['min' => 18, 'max' => 60] , 'child' => ['min' => 0, 'max' => 25] , 'elders' => ['min' => 18, 'max' => 60] ]; + $ageKey = (preg_replace('/\d/', '', $familyFloatesValue) == 'parent' || preg_replace('/\d/', '', $familyFloatesValue) == 'parent_in_law') ? 'elders' : preg_replace('/\d/', '', $familyFloatesValue); + if(isset($terms->age_ratio)){ + return $terms->age_ratio->$ageKey; }else{ - return $this->respond(['status' => 'failed','code' => 404,'data' => []], 404); + return $ageRangeArray[$ageKey]; } - } catch (\Exception $e) { - return $this->respond(['status' => 'failed','code' => 500,'data' => $e->getMessage()], 500); + + } -} -public function getAddOnPolicy() -{ - try { + public function getEmployeePolicy() + { + // try { - $addOnEmployeeData = $this->employeeModel->where('is_active', 1 ) - ->where('emp_code',$this->request->getGet('emp_code')) - ->where('client_id',$this->request->getGet('client_id')) - ->where('client_branch_id',$this->request->getGet('client_branch_id')) - ->where('is_addon_value',1)->findAll(); + $id = $this->request->getGet('id'); + $emp_code = $this->request->getGet('emp_code'); + $client_id = $this->request->getGet('client_id'); + $client_branch_id = $this->request->getGet('client_branch_id'); - + // This is an array containing keys to be removed from the terms and conditions array + $keysToRemove = ["removable_keys"]; + // Retrieve employee policy data by passing the employee primary key + $empPolicy = $this->employeeModel->getEmployeePolicy($id); - $clientPolicy = $this->clientPolicyModel->where('client_id',$this->request->getGet('client_id')) - ->where('client_branch_id',$this->request->getGet('client_branch_id')) - ->where('policy_status', 1) - ->findAll(); - - if(count($clientPolicy)) - { - $band = $this->employeeModel->where('is_active', 1 )->where('emp_code',$this->request->getGet('emp_code'))->where('client_id',$this->request->getGet('client_id'))->where('client_branch_id',$this->request->getGet('client_branch_id'))->where('family_floater_key','self')->get()->getRow()->band; + // Retrieve employee and dependents data by passing the employee code + $employeeData = $this->employeeModel->where('emp_code',$emp_code) + ->where('client_id',$client_id) + ->where('client_branch_id',$client_branch_id) + ->where('is_active', 1 ) + ->where('is_addon_value',0)->findAll(); - $PolicyData = []; - foreach ($clientPolicy as $key => $array) { - $responce = []; - - $decodedArray = json_decode($array['policy_terms']); - $policy_terms = $decodedArray; - $getSlabAndGridData = $this->policesModel->getPolicySlabRatesForEmpOnboard($array['id'],$array['client_id']); - $uniqueData = []; - $siValues = []; - foreach ($getSlabAndGridData['slab_rates'] as $item) { - if($getSlabAndGridData['grid_master']['emp_band'] == 1 ){ - if ($item['grade'] == $band) { - $uniqueData[] = $item; - } - }else{ - if (!in_array($item['si'], $siValues) ) { + + if ($empPolicy) { - if ($item['policy_grid_id'] == 11 && ($item['max_si'] != 0 || $item['max_si'] != null)) { - $uniqueData[] = $item; - $siValues[] = $item['si']; - }else if($item['policy_grid_id'] != 11){ - $uniqueData[] = $item; - $siValues[] = $item['si']; - } - - } - } - - } + $result = []; + foreach ($empPolicy as $array) { + // Reset employee array + $empData = $employeeData; - + + // Removes specific keys from the decoded array and assigns the result to $refusingData + $decodedArray = json_decode($array->Policy_Terms); + $refusingData = (object) array_diff_key((array) $decodedArray, array_flip($keysToRemove)); + $array->Policy_Terms = $refusingData; - $responce['policy_name'] = $this->policesModel->where('id',$array['policy_id'])->get()->getRow()->name; - $responce['SlabRates'] = $uniqueData; - $responce['GridMaster'] = $getSlabAndGridData['grid_master']; - $responce['client_id'] = $array['client_id']; - $responce['client_policy_id'] = $array['id']; - $responce['is_addon'] = $array['is_addon']; - $responce['OpenForEnrollment'] = $array['open_for_enrollment']; - $responce['policy_terms'] = $decodedArray; - $responce['policy_type_id'] = $array['policy_type_id']; + // Retrieve slab rate and grid master data by passing the ClientPolicyId and ClientId + $getSlabAndGridData = $this->policesModel->getPolicySlabRatesForEmpOnboard($array->ClientPolicyId,$array->ClientId); + $array->SlabRates = $getSlabAndGridData['slab_rates']; + $array->GridMaster = $getSlabAndGridData['grid_master']; - $tpaArray = $this->employeeModel->select('employees.name as name , employee_polices.tpa_id as tpa_id , employee_polices.rand_string as rand_string') - ->join('employee_polices', 'employee_polices.employee_id = employees.id') - ->where('employees.emp_code',$this->request->getGet('emp_code')) - ->where('employees.is_active',1) - ->where('employee_polices.client_policy_id',$array['id']) - ->get() - ->getResult(); - - if(count($tpaArray)) - { - if($tpaArray[0]->tpa_id != null) - $responce['eCardDownload'] = base_url('download-e-card/') . $tpaArray[0]->rand_string; - else - $responce['eCardDownload'] = null; + if($array->tpa_id != null){ + $array->eCardDownload = base_url('download-e-card/') . $array->rand_string; + }else{ $array->eCardDownload = null; } - }else{ - $responce['eCardDownload'] = null; - } - - if(count($getSlabAndGridData['slab_rates'])){ - if($getSlabAndGridData['slab_rates'][0]['premium_type'] == 1) - { - $responce['floter_text_heading'] = 'Floater Sum Insured'; - }else{ - $responce['floter_text_heading'] = 'Sum Insured'; - } - } - - if($array['is_addon'] == 3 && $array['policy_type_id'] == 3)//dependent add on policy - { + // Construct value for policy type GPA + if($getSlabAndGridData['grid_master']['policy_type'] == "GPA" && $this->request->getGet('policy') == 'GPA'){ + + // Filter employee data where the family_floater_key is 'self' + $selfData = array_filter($empData, fn($arr) => trim(strtolower($arr['family_floater_key'])) === 'self'); + $employee_policy = $this->employeePolicyModel->where('employee_id',$selfData[0]['id'])->where('client_policy_id',$array->ClientPolicyId)->where('is_active', 1 )->get()->getRow(); + + $self['is_value_exist'] = true; + $self['data']['family_floater_key'] = 'self'; + $self['data']['employee_id'] = $id; + $self['data']['relationship'] = 'Self'; + $self['data']['name'] = $selfData[0]['name']; + $self['data']['dob'] = $this->convertDateFormatDMY($selfData[0]['dob']); + $self['data']['mobile'] = $selfData[0]['mobile']; + $self['data']['client_policy_id'] = $array->ClientPolicyId; + $self['data']['basic_cover_si'] = $employee_policy->basic_cover_si; + + $array->mapped_family_floaters = $self; + + // Return result + if($this->request->getGet('policy') == 'GPA') + { + return $this->respond(['status' => 'success','code' => 200,'data' => $array], 200); + } + // Construct value for policy type GMC + }else if($getSlabAndGridData['grid_master']['policy_type'] == "GMC" && $this->request->getGet('policy') == 'GMC' ){ - // Map family floaters that already exist in the employee table - $familyFloates = $policy_terms->family_floaters; - // remove parent and parent-in-law from familyFloaters - if($familyFloates->{'either-parents-pil'} != 0){ - unset($familyFloates->parents); - unset($familyFloates->parents_in_law); - } - // Convert familyFloaters terms data to plain array - $floters = $this->FloterConvertion($familyFloates); + + + // Map family floaters that already exist in the employee table + $familyFloates = $array->Policy_Terms->family_floaters; + + // Generate Notes string based on familyFloates terms + $array->notes = $this->FloterNotesConvertion($familyFloates); + + if($getSlabAndGridData['slab_rates'][0]['premium_type'] == 1) + { + $array->floter_text_heading = 'Floater Sum Insured'; + $array->floter_text_description = 'This is a floater sum insured. A floater is a type of sum insured that provides coverage to more than one member ot a family at the same time. Simply put, its a single insurance cover for the entire family.'; + }else{ + $array->floter_text_heading = 'Sum Insured'; + $array->floter_text_description = ''; + } + // remove parent and parent-in-law from familyFloaters + if($familyFloates->{'either-parents-pil'} != 0){ + unset($familyFloates->parents); + unset($familyFloates->parents_in_law); + } + $floters = $this->FloterConvertion($familyFloates); - $data = []; - $dependent_and_si_value = 0; - $dependent_and_si_premium_value = 0; - $dependent_and_si_gst_value = 0; - foreach ($floters as $familyFloatesValue) { - $dependent = preg_replace('/\d/', '', $familyFloatesValue); - if(count($addOnEmployeeData)){ - foreach ($addOnEmployeeData as $key => $value) { - if ($value['family_floater_key'] === $dependent) { - $employee_policy = $this->employeePolicyModel->where('employee_id',$value['id'])->where('client_policy_id',$array['id'])->where('is_active', 1 )->get()->getRow(); - if(isset($employee_policy->basic_cover_si)){ $dependent_and_si_value = $employee_policy->basic_cover_si; } - if(isset($employee_policy->premium)){ $dependent_and_si_premium_value = $dependent_and_si_premium_value + $employee_policy->premium;} - if(isset($employee_policy->gst)){ $dependent_and_si_gst_value = $dependent_and_si_gst_value + $employee_policy->gst;} - - $temp['is_value_exist'] = true; - $temp['data']['family_floater_key'] = $familyFloatesValue; - $temp['data']['employee_id'] = $value['id']; - $temp['data']['relationship'] = $value['relationship']; - $temp['data']['name'] = $value['name']; - $temp['data']['dob'] = $this->convertDateFormatDMY($value['dob']); - $temp['data']['client_policy_id'] = $array['id']; - $temp['data']['form_type'] = $dependent; - $temp['data']['basic_cover_si'] = isset($employee_policy->basic_cover_si) ? $employee_policy->basic_cover_si : null; - $temp['data']['premium'] = isset($employee_policy->premium) ? $employee_policy->premium : null; - $temp['data']['age_validation'] = $this->getAgeRange($decodedArray,$familyFloatesValue); - - array_push($data,$temp); - unset($addOnEmployeeData[$key]); - $floters = array_diff($floters, [$familyFloatesValue]); - break; + $data = []; + foreach ($floters as $familyFloatesValue) { + $dependent = preg_replace('/\d/', '', $familyFloatesValue); + + if(count($empData)){ + foreach ($empData as $key => $value) { + if ($value['family_floater_key'] === $dependent) { + $employee_policy = $this->employeePolicyModel->where('employee_id',$value['id'])->where('client_policy_id',$array->ClientPolicyId)->where('is_active', 1 )->get()->getRow(); + $temp['is_value_exist'] = true; + $temp['data']['family_floater_key'] = $familyFloatesValue; + $temp['data']['employee_id'] = $value['id']; + $temp['data']['relationship'] = $value['relationship']; + $temp['data']['name'] = $value['name']; + $temp['data']['dob'] = $this->convertDateFormatDMY($value['dob']); + $temp['data']['client_policy_id'] = $array->ClientPolicyId; + $temp['data']['form_type'] = $dependent; + $temp['data']['basic_cover_si'] = $employee_policy->basic_cover_si; + + + $temp['data']['age_validation'] = $this->getAgeRange($decodedArray,$familyFloatesValue); + + array_push($data,$temp); + unset($empData[$key]); + $floters = array_diff($floters, [$familyFloatesValue]); + break; + } } } } - } - - //Remove Unwanted floter key from floters array based on either-parents-pil term value - if($familyFloates->{'either-parents-pil'} == 1 && count($floters)) - { - if(count($addOnEmployeeData) == 0) - { - $GMCEmpData = $this->employeeModel->where('emp_code',$this->request->getGet('emp_code')) - ->where('is_addon_value',0) - ->where('is_active', 1 ) - ->where('family_floater_key','parent') - ->findAll(); - - if(count($GMCEmpData) > 0){ - $floters = array_diff($floters, ["parent1","parent2"]); - }else{ - $floters = array_diff($floters, ["parent_in_law1","parent_in_law2"]); - } - }else{ + + // Remove Unwanted floter key from floters array based on either-parents-pil term value + if($familyFloates->{'either-parents-pil'} == 1 && count($floters)) + { $count_parent = 0; $count_parent_in_law = 0; foreach ($floters as $value) { @@ -1569,25 +1089,8 @@ public function getAddOnPolicy() $floters = array_filter($floters, fn($value) => strpos($value, 'parent') === false || strpos($value, 'parent_in_law') !== false); } } - - - } - else if($familyFloates->{'either-parents-pil'} == 2 && count($floters)) - { - if(count($addOnEmployeeData) == 0) + else if($familyFloates->{'either-parents-pil'} == 2 && count($floters)) { - $GMCEmpData = $this->employeeModel->where('emp_code',$this->request->getGet('emp_code')) - ->where('is_addon_value',0) - ->where('is_active', 1 ) - ->where('family_floater_key','parent') - ->findAll(); - - if(count($GMCEmpData) > 0){ - $floters = array_diff($floters, ["parent1","parent2"]); - }else{ - $floters = array_diff($floters, ["parent_in_law1","parent_in_law2"]); - } - }else{ $count_parent = 0; $count_parent_in_law = 0; foreach ($floters as $value) { @@ -1597,726 +1100,1278 @@ public function getAddOnPolicy() if(($count_parent + $count_parent_in_law) == 2) { $floters = array_filter($floters, fn($value) => strpos($value, 'parent') === false); } + + } + + + // Add family floter buttons placement data for FE validation + if(count($floters)){ + foreach ($floters as $familyFloatesValue) { + + $temp2['is_value_exist'] = false; + $temp2['data']['family_floater_key'] = $familyFloatesValue; + $temp2['data']['client_policy_id'] = $array->ClientPolicyId; + $temp2['data']['button_name'] = 'Add '.ucfirst(str_replace('_', ' ', preg_replace('/\d/', '', $familyFloatesValue))); + $temp2['data']['form_type'] = preg_replace('/\d/', '', $familyFloatesValue); + + + $temp2['data']['age_validation'] = $this->getAgeRange($decodedArray,$familyFloatesValue); + + array_push($data,$temp2); + } - } + $array->mapped_family_floaters = $data; + $array->type = "Group Medical Coverage"; + + $checkGmcParentsPolicyExist = $this->clientPolicyModel->select('client_policy.id as ClientPolicyId , client_policy.client_id as ClientId, policies.id as PolicyId , client_policy.policy_type_id as policy_type_id, policies.name as Policy_Name , client_policy.is_addon as is_addon , client_policy.open_for_enrollment as OpenForEnrollment , client_policy.inception_type as inception_type , client_policy.policy_terms as Policy_Terms') + ->join('policies', 'client_policy.policy_id = policies.id', 'left') + ->where('client_policy.policy_type_id', 3 ) + ->where('client_policy.is_addon', 1 ) + ->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 ) + ->get() + ->getResult(); + if($checkGmcParentsPolicyExist) + { + $GmcParrentsData = $this->getGmcParrentsPolicy($checkGmcParentsPolicyExist,$emp_code,$client_id,$client_branch_id); + return $this->respond(['status' => 'success','code' => 200,'data' => [$array,$GmcParrentsData]], 200); + + } + if($this->request->getGet('policy') == 'GMC'){ + return $this->respond(['status' => 'success','code' => 200,'data' => [$array]], 200); + } + + } + + // $result[] = $array; + } + + return $this->respond(['status' => 'success','code' => 200,'data' => []], 200); - // Add family floter buttons placement data for FE validation - if(count($floters)){ - foreach ($floters as $familyFloatesValue) { - $temp2['is_value_exist'] = false; - $temp2['data']['family_floater_key'] = $familyFloatesValue; - $temp2['data']['client_policy_id'] = $array['id']; - $temp2['data']['button_name'] = 'Add '.ucfirst(str_replace('_', ' ', preg_replace('/\d/', '', $familyFloatesValue))); - $temp2['data']['form_type'] = preg_replace('/\d/', '', $familyFloatesValue); - - $temp2['data']['age_validation'] = $this->getAgeRange($decodedArray,$familyFloatesValue); + }else{ + return $this->respond(['status' => 'failed','code' => 404,'data' => []], 200); + } + // } catch (\Exception $e) { + // return $this->respond(['status' => 'failed','code' => 500,'data' => $e->getMessage()], 500); + // } + } - array_push($data,$temp2); + public function getGmcParrentsPolicy($GmcParrentsPolicy,$emp_code,$client_id,$client_branch_id) + { + + $employeeData = $this->employeeModel->where('emp_code',$emp_code) + ->where('client_id',$client_id) + ->where('client_branch_id',$client_branch_id) + ->where('is_active', 1 ) + ->where('is_addon_value',0)->findAll(); + foreach ($GmcParrentsPolicy as $key => $array) { + + + + // Reset employee array + $empData = $employeeData; + + + $array->Policy_Terms = json_decode($array->Policy_Terms); + + + // Retrieve slab rate and grid master data by passing the ClientPolicyId and ClientId + $getSlabAndGridData = $this->policesModel->getPolicySlabRatesForEmpOnboard($array->ClientPolicyId,$array->ClientId); + $array->SlabRates = $getSlabAndGridData['slab_rates']; + $array->GridMaster = $getSlabAndGridData['grid_master']; + + $tpaArray = $this->employeeModel->select('employees.name as name , employee_polices.tpa_id as tpa_id , employee_polices.rand_string as rand_string') + ->join('employee_polices', 'employee_polices.employee_id = employees.id') + ->where('employees.emp_code',$emp_code) + ->where('employees.is_active',1) + ->where('employee_polices.client_policy_id',$array->ClientPolicyId) + ->get() + ->getResult(); + + if(count($tpaArray)) + { + + if($tpaArray[0]->tpa_id != null) + $array->eCardDownload = base_url('download-e-card/') . $tpaArray[0]->rand_string; + else + $array->eCardDownload = null; + + }else{ + $array->eCardDownload = null; + } + + + $array->eCardDownload = null; + + // Map family floaters that already exist in the employee table + $familyFloates = $array->Policy_Terms->family_floaters; + + // Generate Notes string based on familyFloates terms + $array->notes = $this->FloterNotesConvertion($familyFloates); + + if($getSlabAndGridData['slab_rates'][0]['premium_type'] == 1) + { + $array->floter_text_heading = 'Floater Sum Insured'; + $array->floter_text_description = 'This is a floater sum insured. A floater is a type of sum insured that provides coverage to more than one member ot a family at the same time. Simply put, its a single insurance cover for the entire family.'; + }else{ + $array->floter_text_heading = 'Sum Insured'; + $array->floter_text_description = ''; + } + + + // remove parent and parent-in-law from familyFloaters + if($familyFloates->{'either-parents-pil'} != 0){ + unset($familyFloates->parents); + unset($familyFloates->parents_in_law); + } + + // Convert familyFloaters terms data to plain array + $floters = $this->FloterConvertion($familyFloates); + $data = []; + foreach ($floters as $familyFloatesValue) { + $dependent = preg_replace('/\d/', '', $familyFloatesValue); + + + if(count($empData)){ + foreach ($empData as $key => $value) { + if ($value['family_floater_key'] === $dependent) { + $employee_policy = $this->employeePolicyModel->where('employee_id',$value['id'])->where('client_policy_id',$array->ClientPolicyId)->where('is_active', 1 )->get()->getRow(); + // dd( $employee_policy); + $temp['is_value_exist'] = true; + $temp['data']['family_floater_key'] = $familyFloatesValue; + $temp['data']['employee_id'] = $value['id']; + $temp['data']['relationship'] = $value['relationship']; + $temp['data']['name'] = $value['name']; + $temp['data']['dob'] = $this->convertDateFormatDMY($value['dob']); + $temp['data']['client_policy_id'] = $array->ClientPolicyId; + $temp['data']['form_type'] = $dependent; + $temp['data']['basic_cover_si'] = $employee_policy->basic_cover_si; + $temp['data']['age_validation'] = $this->getAgeRange($array->Policy_Terms,$familyFloatesValue); + + + array_push($data,$temp); + unset($empData[$key]); + $floters = array_diff($floters, [$familyFloatesValue]); + break; + } } - } + } + } - $responce['family_floaters_of_dependent_and_si_array'] = $data; - $responce['family_floaters_of_dependent_and_si_value'] = $dependent_and_si_value; - $responce['family_floaters_of_dependent_and_si_premium_value'] = $dependent_and_si_premium_value; - $responce['family_floaters_of_dependent_and_gst_value'] = $dependent_and_si_gst_value; + // Remove Unwanted floter key from floters array based on either-parents-pil term value + if($familyFloates->{'either-parents-pil'} == 1 && count($floters)) + { + $count_parent = 0; + $count_parent_in_law = 0; + foreach ($floters as $value) { + if (preg_replace('/\d/', '', $value) == 'parent') { $count_parent++; } + if (preg_replace('/\d/', '', $value) == 'parent_in_law') {$count_parent_in_law++;} + } + if($count_parent != 2) { + $floters = array_filter($floters, fn($value) => strpos($value, 'parent_in_law') === false); + } + if($count_parent_in_law != 2) { + $floters = array_filter($floters, fn($value) => strpos($value, 'parent') === false || strpos($value, 'parent_in_law') !== false); + } + } + else if($familyFloates->{'either-parents-pil'} == 2 && count($floters)) + { + $count_parent = 0; + $count_parent_in_law = 0; + foreach ($floters as $value) { + if (preg_replace('/\d/', '', $value) == 'parent') { $count_parent++; } + if (preg_replace('/\d/', '', $value) == 'parent_in_law') {$count_parent_in_law++;} + } + if(($count_parent + $count_parent_in_law) == 2) { + $floters = array_filter($floters, fn($value) => strpos($value, 'parent') === false); + } + + } + + // Add family floter buttons placement data for FE validation + if(count($floters)){ + foreach ($floters as $familyFloatesValue) { + + $temp2['is_value_exist'] = false; + $temp2['data']['family_floater_key'] = $familyFloatesValue; + $temp2['data']['client_policy_id'] = $array->ClientPolicyId; + $temp2['data']['button_name'] = 'Add '.ucfirst(str_replace('_', ' ', preg_replace('/\d/', '', $familyFloatesValue))); + $temp2['data']['form_type'] = preg_replace('/\d/', '', $familyFloatesValue); + $temp2['data']['age_validation'] = $this->getAgeRange($array->Policy_Terms,$familyFloatesValue); + array_push($data,$temp2); + + } + } + + $array->mapped_family_floaters = $data; + $array->type = "Group Medical Coverage - Parents"; + + return $array; + + } + + } + + public function FloterConvertion($array){ + + $result = []; + + foreach ($array as $key => $value) { + if ($value > 0 && $key != 'elders_count') { + if ($value != 0 && $key === 'childrens') { + for ($i = 1; $i <= $value; $i++) { + $result[] = "child" . $i; + } + } else if($value != 0 && $key ==='parents') { + for ($i = 1; $i <= $value; $i++) { + $result[] = "parent" . $i; + } + }else if($value != 0 && $key ==='parents-in-law') { + for ($i = 1; $i <= $value; $i++) { + $result[] = "parent_in_law" . $i; + } + }else if($value != 0 && $key ==='either-parents-pil') { + for ($i = 1; $i <= 2; $i++) { + $result[] = "parent" . $i; + $result[] = "parent_in_law" . $i; + } + }else { + $result[] = $key; + } + } + } + + return $result; + } + + public function FloterNotesConvertion($array){ + + $result = ' '; + foreach ($array as $key => $value) { + if ($value > 0) { + if($value != 0 && $key ==='either-parents-pil') { + $result .= ' + Either 2 Parents or 2 Parents in law'; + }else if($value != 0 && $key ==='spouse') { + $string = str_replace('-', ' ', $key); + $string = ucwords($string); + $result .= ' + '.$string; + }else if($value != 0 && $key ==='self') { + $result = 'Can Add Self '; + }else if($value != 0 && $key ==='childrens') { + if($value > 1){ $result .= ' + '.$value.' Children'; }else{ $result .= ' + '.$value.' Child'; } + }else{ + $string = str_replace('-', ' ', $key); + $string = ucwords($string); + $result .= ' + '.$value.' '.$string; + } + } + } + + return $result; + } + + public function getClientDetails() + { + try { + + $client = $this->clientModel->where('id',$this->request->getGet('client_id'))->first(); + if($client) { + $client['client_logo'] = base_url().'public/uploads/logo/'.$client['client_logo']; + $clientPolicy = $this->clientPolicyModel->where('client_id',$this->request->getGet('client_id')) + ->where('client_branch_id',$this->request->getGet('client_branch_id'))->findAll(); + return $this->respond(['status' => 'success','code' => 200,'data' => ['client'=>$client,'client_policy'=>$clientPolicy]], 200); + + }else{ + return $this->respond(['status' => 'failed','code' => 404,'data' => []], 404); + } + } catch (\Exception $e) { + return $this->respond(['status' => 'failed','code' => 500,'data' => $e->getMessage()], 500); + } + } + + public function getAddOnPolicy() + { + try { + + $addOnEmployeeData = $this->employeeModel->where('is_active', 1 ) + ->where('emp_code',$this->request->getGet('emp_code')) + ->where('client_id',$this->request->getGet('client_id')) + ->where('client_branch_id',$this->request->getGet('client_branch_id')) + ->where('is_addon_value',1)->findAll(); + + + + $clientPolicy = $this->clientPolicyModel->where('client_id',$this->request->getGet('client_id')) + ->where('client_branch_id',$this->request->getGet('client_branch_id')) + ->where('policy_status', 1) + ->findAll(); + + if(count($clientPolicy)) + { + $band = $this->employeeModel->where('is_active', 1 )->where('emp_code',$this->request->getGet('emp_code'))->where('client_id',$this->request->getGet('client_id'))->where('client_branch_id',$this->request->getGet('client_branch_id'))->where('family_floater_key','self')->get()->getRow()->band; + + $PolicyData = []; + foreach ($clientPolicy as $key => $array) { + $responce = []; + + $decodedArray = json_decode($array['policy_terms']); + $policy_terms = $decodedArray; + $getSlabAndGridData = $this->policesModel->getPolicySlabRatesForEmpOnboard($array['id'],$array['client_id']); + $uniqueData = []; + $siValues = []; + foreach ($getSlabAndGridData['slab_rates'] as $item) { + if($getSlabAndGridData['grid_master']['emp_band'] == 1 ){ + if ($item['grade'] == $band) { + $uniqueData[] = $item; + } + }else{ + if (!in_array($item['si'], $siValues) ) { + + if ($item['policy_grid_id'] == 11 && ($item['max_si'] != 0 || $item['max_si'] != null)) { + $uniqueData[] = $item; + $siValues[] = $item['si']; + }else if($item['policy_grid_id'] != 11){ + $uniqueData[] = $item; + $siValues[] = $item['si']; + } + + } + } + + } + + + + $responce['policy_name'] = $this->policesModel->where('id',$array['policy_id'])->get()->getRow()->name; + $responce['SlabRates'] = $uniqueData; + $responce['GridMaster'] = $getSlabAndGridData['grid_master']; + $responce['client_id'] = $array['client_id']; + $responce['client_policy_id'] = $array['id']; + $responce['is_addon'] = $array['is_addon']; + $responce['OpenForEnrollment'] = $array['open_for_enrollment']; + $responce['policy_terms'] = $decodedArray; + $responce['policy_type_id'] = $array['policy_type_id']; + + $tpaArray = $this->employeeModel->select('employees.name as name , employee_polices.tpa_id as tpa_id , employee_polices.rand_string as rand_string') + ->join('employee_polices', 'employee_polices.employee_id = employees.id') + ->where('employees.emp_code',$this->request->getGet('emp_code')) + ->where('employees.is_active',1) + ->where('employee_polices.client_policy_id',$array['id']) + ->get() + ->getResult(); + + if(count($tpaArray)) + { + if($tpaArray[0]->tpa_id != null) + $responce['eCardDownload'] = base_url('download-e-card/') . $tpaArray[0]->rand_string; + else + $responce['eCardDownload'] = null; + + }else{ + $responce['eCardDownload'] = null; + } + + if(count($getSlabAndGridData['slab_rates'])){ + if($getSlabAndGridData['slab_rates'][0]['premium_type'] == 1) + { + $responce['floter_text_heading'] = 'Floater Sum Insured'; + }else{ + $responce['floter_text_heading'] = 'Sum Insured'; + } + } + + + if($array['is_addon'] == 3 && $array['policy_type_id'] == 3)//dependent add on policy + { + + + // Map family floaters that already exist in the employee table + $familyFloates = $policy_terms->family_floaters; + // remove parent and parent-in-law from familyFloaters + if($familyFloates->{'either-parents-pil'} != 0){ + unset($familyFloates->parents); + unset($familyFloates->parents_in_law); + } + // Convert familyFloaters terms data to plain array + $floters = $this->FloterConvertion($familyFloates); + + + $data = []; + $dependent_and_si_value = 0; + $dependent_and_si_premium_value = 0; + $dependent_and_si_gst_value = 0; + foreach ($floters as $familyFloatesValue) { + $dependent = preg_replace('/\d/', '', $familyFloatesValue); + if(count($addOnEmployeeData)){ + foreach ($addOnEmployeeData as $key => $value) { + if ($value['family_floater_key'] === $dependent) { + $employee_policy = $this->employeePolicyModel->where('employee_id',$value['id'])->where('client_policy_id',$array['id'])->where('is_active', 1 )->get()->getRow(); + if(isset($employee_policy->basic_cover_si)){ $dependent_and_si_value = $employee_policy->basic_cover_si; } + if(isset($employee_policy->premium)){ $dependent_and_si_premium_value = $dependent_and_si_premium_value + $employee_policy->premium;} + if(isset($employee_policy->gst)){ $dependent_and_si_gst_value = $dependent_and_si_gst_value + $employee_policy->gst;} + + $temp['is_value_exist'] = true; + $temp['data']['family_floater_key'] = $familyFloatesValue; + $temp['data']['employee_id'] = $value['id']; + $temp['data']['relationship'] = $value['relationship']; + $temp['data']['name'] = $value['name']; + $temp['data']['dob'] = $this->convertDateFormatDMY($value['dob']); + $temp['data']['client_policy_id'] = $array['id']; + $temp['data']['form_type'] = $dependent; + $temp['data']['basic_cover_si'] = isset($employee_policy->basic_cover_si) ? $employee_policy->basic_cover_si : null; + $temp['data']['premium'] = isset($employee_policy->premium) ? $employee_policy->premium : null; + $temp['data']['age_validation'] = $this->getAgeRange($decodedArray,$familyFloatesValue); + + array_push($data,$temp); + unset($addOnEmployeeData[$key]); + $floters = array_diff($floters, [$familyFloatesValue]); + break; + } + } + } + } + + + //Remove Unwanted floter key from floters array based on either-parents-pil term value + if($familyFloates->{'either-parents-pil'} == 1 && count($floters)) + { + if(count($addOnEmployeeData) == 0) + { + $GMCEmpData = $this->employeeModel->where('emp_code',$this->request->getGet('emp_code')) + ->where('is_addon_value',0) + ->where('is_active', 1 ) + ->where('family_floater_key','parent') + ->findAll(); + + if(count($GMCEmpData) > 0){ + $floters = array_diff($floters, ["parent1","parent2"]); + }else{ + $floters = array_diff($floters, ["parent_in_law1","parent_in_law2"]); + } + }else{ + + $count_parent = 0; + $count_parent_in_law = 0; + foreach ($floters as $value) { + if (preg_replace('/\d/', '', $value) == 'parent') { $count_parent++; } + if (preg_replace('/\d/', '', $value) == 'parent_in_law') {$count_parent_in_law++;} + } + if($count_parent != 2) { + $floters = array_filter($floters, fn($value) => strpos($value, 'parent_in_law') === false); + } + if($count_parent_in_law != 2) { + $floters = array_filter($floters, fn($value) => strpos($value, 'parent') === false || strpos($value, 'parent_in_law') !== false); + } + } + + + } + else if($familyFloates->{'either-parents-pil'} == 2 && count($floters)) + { + if(count($addOnEmployeeData) == 0) + { + $GMCEmpData = $this->employeeModel->where('emp_code',$this->request->getGet('emp_code')) + ->where('is_addon_value',0) + ->where('is_active', 1 ) + ->where('family_floater_key','parent') + ->findAll(); + + if(count($GMCEmpData) > 0){ + $floters = array_diff($floters, ["parent1","parent2"]); + }else{ + $floters = array_diff($floters, ["parent_in_law1","parent_in_law2"]); + } + }else{ + $count_parent = 0; + $count_parent_in_law = 0; + foreach ($floters as $value) { + if (preg_replace('/\d/', '', $value) == 'parent') { $count_parent++; } + if (preg_replace('/\d/', '', $value) == 'parent_in_law') {$count_parent_in_law++;} + } + if(($count_parent + $count_parent_in_law) == 2) { + $floters = array_filter($floters, fn($value) => strpos($value, 'parent') === false); + } + } + + } - + // Add family floter buttons placement data for FE validation + if(count($floters)){ + foreach ($floters as $familyFloatesValue) { - if($this->request->getGet('policy') == 'GMC-DEPENDENT-ADDON'){ - return $this->respond(['status' => 'success','code' => 200,'data' => ['gmc_dependent_addon'=>$responce]], 200); - } - - //array_push($PolicyData, $responce); + $temp2['is_value_exist'] = false; + $temp2['data']['family_floater_key'] = $familyFloatesValue; + $temp2['data']['client_policy_id'] = $array['id']; + $temp2['data']['button_name'] = 'Add '.ucfirst(str_replace('_', ' ', preg_replace('/\d/', '', $familyFloatesValue))); + $temp2['data']['form_type'] = preg_replace('/\d/', '', $familyFloatesValue); + + $temp2['data']['age_validation'] = $this->getAgeRange($decodedArray,$familyFloatesValue); - }else if($array['is_addon'] == 2 && $array['policy_type_id'] == 4)//Topup policy - { - + array_push($data,$temp2); - $whereArray = []; - foreach ( $decodedArray->family_floaters as $key => $value) { - if($value != 0){ - if($key == 'parents'){ $text = 'parent'; }else if($key == 'childrens'){ $text = 'child'; }else if($key == 'parents-in-law'){$text = 'parent_in_law';}else{ $text = $key; } - array_push($whereArray,$text); - } - } - - - $getAddOnType = $this->clientPolicyModel->where('id',$array['base_policy'])->where('policy_status', 1)->get()->getRow(); - $basePolicyAddOnType = $getAddOnType->is_addon; - // if is_addon value is 1 it is GMC if not it is one of the Add On policy - if($basePolicyAddOnType == 1){ $is_addon_value = 0; }else{ $is_addon_value = 1; } - $only_si_array = []; - $only_si_value = 0; - $only_si_premium_value = 0; - $only_si_gst_value = 0; - $BasePolicyEmployeeData = $this->employeeModel->where('is_active', 1 )->where('emp_code',$this->request->getGet('emp_code'))->where('client_id',$this->request->getGet('client_id'))->where('is_addon_value',$is_addon_value)->whereIn('family_floater_key',$whereArray)->findAll(); - foreach ($BasePolicyEmployeeData as $key => $value) { - - $employee_policy = $this->employeePolicyModel->where('employee_id',$value['id'])->where('client_policy_id',$array['id'])->where('is_active', 1 )->get()->getRow(); - if(isset($employee_policy->basic_cover_si)){ $only_si_value = $employee_policy->basic_cover_si; } - if(isset($employee_policy->premium)){ $only_si_premium_value = $only_si_premium_value + $employee_policy->rata_premimum;} - if(isset($employee_policy->gst)){ $only_si_gst_value = $only_si_gst_value + $employee_policy->gst;} - $temp3['is_value_exist'] = true; - $temp3['data']['employee_id'] = $value['id']; - $temp3['data']['relationship'] = $value['relationship']; - $temp3['data']['name'] = $value['name']; - $temp3['data']['dob'] = $this->convertDateFormatDMY($value['dob']); - $temp3['data']['client_policy_id'] = $array['id']; - $temp3['data']['basic_cover_si'] = isset($employee_policy->basic_cover_si) ? $employee_policy->basic_cover_si : null; - $temp3['data']['premium'] = isset($employee_policy->premium) ? $employee_policy->premium : null; - array_push($only_si_array,$temp3); - - } - - $responce['family_floaters_of_only_si_array'] = $only_si_array; - $responce['family_floaters_of_only_si_value'] = $only_si_value; - $responce['family_floaters_of_only_si_premium_value'] = $only_si_premium_value; - $responce['family_floaters_of_only_si_gst_value'] = $only_si_gst_value; - $responce['type'] = "Group Medical Coverage - Top Up"; - - if($this->request->getGet('policy') == 'GMC-SI-TOPUP'){ - return $this->respond(['status' => 'success','code' => 200,'data' => ['gmc_si_topup'=>$responce]], 200); - } - - - }else if($array['is_addon'] == 2 && $array['policy_type_id'] == 5)//Parents Topup policy - { - - $whereArray = []; - foreach ( $decodedArray->family_floaters as $key => $value) { - if($value != 0){ - if($key == 'parents'){ $text = 'parent'; }else if($key == 'childrens'){ $text = 'child'; }else if($key == 'parents-in-law'){$text = 'parent_in_law';}else{ $text = $key; } - array_push($whereArray,$text); - } - } - - $getAddOnType = $this->clientPolicyModel->where('id',$array['base_policy'])->where('policy_status', 1)->get()->getRow(); - $basePolicyAddOnType = $getAddOnType->is_addon; - // if is_addon value is 1 it is GMC if not it is one of the Add On policy - if($basePolicyAddOnType == 1){ $is_addon_value = 0; }else{ $is_addon_value = 1; } - $only_si_array = []; - $only_si_value = 0; - $only_si_premium_value = 0; - $only_si_gst_value = 0; - $BasePolicyEmployeeData = $this->employeeModel->where('is_active', 1 )->where('emp_code',$this->request->getGet('emp_code'))->where('client_id',$this->request->getGet('client_id'))->where('is_addon_value',$is_addon_value)->whereIn('family_floater_key',$whereArray)->findAll(); - foreach ($BasePolicyEmployeeData as $key => $value) { - - $employee_policy = $this->employeePolicyModel->where('employee_id',$value['id'])->where('client_policy_id',$array['id'])->where('is_active', 1 )->get()->getRow(); - if(isset($employee_policy->basic_cover_si)){ $only_si_value = $employee_policy->basic_cover_si; } - if(isset($employee_policy->premium)){ $only_si_premium_value = $only_si_premium_value + $employee_policy->rata_premimum;} - if(isset($employee_policy->gst)){ $only_si_gst_value = $only_si_gst_value + $employee_policy->gst;} - $temp3['is_value_exist'] = true; - $temp3['data']['employee_id'] = $value['id']; - $temp3['data']['relationship'] = $value['relationship']; - $temp3['data']['name'] = $value['name']; - $temp3['data']['dob'] = $this->convertDateFormatDMY($value['dob']); - $temp3['data']['client_policy_id'] = $array['id']; - $temp3['data']['basic_cover_si'] = isset($employee_policy->basic_cover_si) ? $employee_policy->basic_cover_si : null; - $temp3['data']['premium'] = isset($employee_policy->premium) ? $employee_policy->premium : null; - array_push($only_si_array,$temp3); - - } - - $responce['family_floaters_of_only_si_array'] = $only_si_array; - $responce['family_floaters_of_only_si_value'] = $only_si_value; - $responce['family_floaters_of_only_si_premium_value'] = $only_si_premium_value; - $responce['family_floaters_of_only_si_gst_value'] = $only_si_gst_value; - $responce['type'] = "Group Medical Coverage - Parents Top Up"; - - if($this->request->getGet('policy') == 'GMC-SI-PARENT-TOPUP'){ - return $this->respond(['status' => 'success','code' => 200,'data' => ['gmc_si_parent_topup'=>$responce]], 200); - } - - - } - - } - - - return $this->respond(['status' => 'success','code' => 200,'data' => []], 200); - - }else{ - return $this->respond(['status' => 'failed','code' => 404,'data' => []], 200); - } - } catch (\Exception $e) { - return $this->respond(['status' => 'failed','code' => 500,'data' => $e->getMessage()], 500); - } -} - -public function iAgreeForAddOn() -{ - $postData = json_decode($this->request->getBody(), true); - $client_policy_id = $postData['client_policy_id']; - sort($client_policy_id); - // Alternatively, you can use echo to see the type - $emp_code = $postData['emp_code']; - $client_id = $postData['client_id']; - - $this->employeeModel->where('emp_code', $emp_code ) - ->where('client_id', $client_id ) - ->where('is_active', 1 ) - ->set(array('emp_status'=>'enrolled')) - ->update(); - - $empData = $this->employeeModel->where('emp_code', $emp_code )->where('client_id', $client_id ) ->where('is_active', 1 )->findAll(); - - if (!is_null($client_policy_id) && is_array($client_policy_id)) - { - $array_list = []; - foreach ($client_policy_id as $key => $value) - { - foreach ($empData as $empDataKey => $empDataValue) - { - $this->employeePolicyModel->where('client_policy_id', $value ) - ->where('is_active', 1 ) - ->where('employee_id', $empDataValue['id'] ) - ->set(array('status'=>'enrolled')) - ->update(); - } - - $find = $this->employeeModel->getEmpFamilybyEmpCode(client_policy_id: $value,emp_code: $emp_code,client_id: $client_id,emp_status:['draft','enrolled'],policy_status:['draft','enrolled']); - if(count($find) > 0){ - $array_list[] = $find; - } - } - - $notification = $this->notificationModel->where('client_id' ,$client_id)->where('template_name', 'member_review_and_summary_mail')->first(); - - - if (isset($notification) && $notification['enabled'] == 1) { - $params ['array_list'] = $array_list; - $params ['client_policy_id'] = $client_policy_id; - $params ['emp_code'] = $emp_code; - $params ['client_id'] = $client_id; - $params ['notification'] = $notification; - // print_r($params);die; - $wholeData =sendMailNotification::sendMailNotification('member_review_and_summary_mail', $params); - $mail_send_return = MailHelper::send_email($wholeData[0]); - $this->myLogger->logme("info", $mail_send_return); - - if (isset($wholeData[0])) { - - $account_manager_wholeData =sendMailNotification::sendMailNotification('account_maneger_summary_mail', $params); - - foreach ($account_manager_wholeData as $key => $value) { - $mail_send_return1 = MailHelper::send_email($value); - $this->myLogger->logme("info", $mail_send_return1); - } - - $client_hr_wholeData =sendMailNotification::sendMailNotification('client_hr_summary_mail', $params); - - foreach ($client_hr_wholeData as $key => $value) { - $mail_send_return2 = MailHelper::send_email($value); - $this->myLogger->logme("info", $mail_send_return2); - } - } - } - - } - - return $this->respond(['status' => 'success','code' => 200,'data' => [] ], 200); -} - -//Post method - which receives client_policy id and empcode of the family. -//Pull records againest emp code and calculate premium -// retun array -public function calculatePremium($clientPolicyId = null , $empCode = null, $default_si = null)//family level -{ - helper('excel_util_helper'); - $client_policy_id = $this->request->getVar('client_policy_id') ?? $clientPolicyId; - $emp_code = $this->request->getVar('emp_code') ?? $empCode; - $default_si = $this->request->getVar('si') ?? $default_si;// si amt which choosed in add on policy - // dd($client_policy_id); - - - $client_id = ($this->clientPolicyModel->select('client_id')->find($client_policy_id))['client_id']; - // get policy and rack details - $policy_terms = $this->clientPolicyModel->getPolicyDetails($client_id,$client_policy_id); - $policy_type = $policy_terms[0]->is_addon; - $base_policy = $policy_terms[0]->base_policy; - $policy_terms = (array) $policy_terms[0];// convert obj to array - - //get policy slab rates - $slab_details = $this->policesModel->getPolicySlabRatesForEmpOnboard($client_policy_id,$client_id); - // print_r($slab_details);die(); - - $existing_famility_details = $this->employeeModel->getEmpFamilybyEmpCode(client_id: $client_id,client_policy_id: $client_policy_id,emp_code: $emp_code,emp_status:['draft','enrolled'],policy_status:['draft','enrolled']); - - if(!count($existing_famility_details) && $policy_type == 2)//top up addon only - { - //get basepolicy id then pull emplist from base policy if only current policy is DA addon policy and emplist is zero - // echo 'inside'; - $client_policy_id = $base_policy; - $existing_famility_details = $this->employeeModel->getEmpFamilybyEmpCode(client_id: $client_id,client_policy_id: $client_policy_id,emp_code: $emp_code,emp_status:['draft','enrolled'],policy_status:['draft','enrolled']); - } - - $file = ['id' => null,'client_id' => $client_id,'policy_id' => $client_policy_id,'action' => 'inception']; - // dd($this->employeeModel->getLastQuery()); - // print_r($existing_famility_details);die(); - $employee_data_group_by_family = data_group_by_family($existing_famility_details,$data_source = 'db'); - // print_r(($employee_data_group_by_family));die(); - foreach ($employee_data_group_by_family as $emp_id => $family) - { - $transformed_famility_details = transform_db_data_to_excel($family); - // print_r($transformed_famility_details);die(); - $data = calculate_premimum($transformed_famility_details,$policy_terms,$slab_details,$file,$default_si); - // dd($data); - $employee_data_group_by_family[$emp_id] = $data; - - } - - if($clientPolicyId != null && $empCode != null) - { - return $employee_data_group_by_family; - }else{ - // dd ($employee_data_group_by_family); - return $this->respond(['status' => 'success','code' => (count($employee_data_group_by_family) ? 200 : 404),'data' => [$employee_data_group_by_family] ], 200); - - } - -} - - -public function getCashDepositData() -{ - - $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, policies.id as policy_id , client_policy.policy_type_id as policy_type_id, policies.name as policy_name , client_policy.is_addon as is_addon , client_policy.open_for_enrollment as OpenForEnrollment , client_policy.inception_type as inception_type ') - ->join('policies', 'client_policy.policy_id = policies.id', 'left') - ->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) - { - - $value['type'] = $this->policyTypeModel->where('id',$value['policy_type_id'])->get()->getRow()->policy_type; - $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++; } + } + + $responce['family_floaters_of_dependent_and_si_array'] = $data; + $responce['family_floaters_of_dependent_and_si_value'] = $dependent_and_si_value; + $responce['family_floaters_of_dependent_and_si_premium_value'] = $dependent_and_si_premium_value; + $responce['family_floaters_of_dependent_and_gst_value'] = $dependent_and_si_gst_value; + + + + + + if($this->request->getGet('policy') == 'GMC-DEPENDENT-ADDON'){ + return $this->respond(['status' => 'success','code' => 200,'data' => ['gmc_dependent_addon'=>$responce]], 200); + } + + //array_push($PolicyData, $responce); + + }else if($array['is_addon'] == 2 && $array['policy_type_id'] == 4)//Topup policy + { + + + $whereArray = []; + foreach ( $decodedArray->family_floaters as $key => $value) { + if($value != 0){ + if($key == 'parents'){ $text = 'parent'; }else if($key == 'childrens'){ $text = 'child'; }else if($key == 'parents-in-law'){$text = 'parent_in_law';}else{ $text = $key; } + array_push($whereArray,$text); } } - - $value['totalMembersCount'] = count($employeeDetails); - $value['membersCountOfEnrolled'] = $enrolledCount; - $value['membersCountOfDraft'] = $draftCount; - - array_push($data['policyDetails'],$value); + + + $getAddOnType = $this->clientPolicyModel->where('id',$array['base_policy'])->where('policy_status', 1)->get()->getRow(); + $basePolicyAddOnType = $getAddOnType->is_addon; + // if is_addon value is 1 it is GMC if not it is one of the Add On policy + if($basePolicyAddOnType == 1){ $is_addon_value = 0; }else{ $is_addon_value = 1; } + $only_si_array = []; + $only_si_value = 0; + $only_si_premium_value = 0; + $only_si_gst_value = 0; + $BasePolicyEmployeeData = $this->employeeModel->where('is_active', 1 )->where('emp_code',$this->request->getGet('emp_code'))->where('client_id',$this->request->getGet('client_id'))->where('is_addon_value',$is_addon_value)->whereIn('family_floater_key',$whereArray)->findAll(); + foreach ($BasePolicyEmployeeData as $key => $value) { + + $employee_policy = $this->employeePolicyModel->where('employee_id',$value['id'])->where('client_policy_id',$array['id'])->where('is_active', 1 )->get()->getRow(); + if(isset($employee_policy->basic_cover_si)){ $only_si_value = $employee_policy->basic_cover_si; } + if(isset($employee_policy->premium)){ $only_si_premium_value = $only_si_premium_value + $employee_policy->rata_premimum;} + if(isset($employee_policy->gst)){ $only_si_gst_value = $only_si_gst_value + $employee_policy->gst;} + $temp3['is_value_exist'] = true; + $temp3['data']['employee_id'] = $value['id']; + $temp3['data']['relationship'] = $value['relationship']; + $temp3['data']['name'] = $value['name']; + $temp3['data']['dob'] = $this->convertDateFormatDMY($value['dob']); + $temp3['data']['client_policy_id'] = $array['id']; + $temp3['data']['basic_cover_si'] = isset($employee_policy->basic_cover_si) ? $employee_policy->basic_cover_si : null; + $temp3['data']['premium'] = isset($employee_policy->premium) ? $employee_policy->premium : null; + array_push($only_si_array,$temp3); + + } + + $responce['family_floaters_of_only_si_array'] = $only_si_array; + $responce['family_floaters_of_only_si_value'] = $only_si_value; + $responce['family_floaters_of_only_si_premium_value'] = $only_si_premium_value; + $responce['family_floaters_of_only_si_gst_value'] = $only_si_gst_value; + $responce['type'] = "Group Medical Coverage - Top Up"; + + if($this->request->getGet('policy') == 'GMC-SI-TOPUP'){ + return $this->respond(['status' => 'success','code' => 200,'data' => ['gmc_si_topup'=>$responce]], 200); + } + + + }else if($array['is_addon'] == 2 && $array['policy_type_id'] == 5)//Parents Topup policy + { + + $whereArray = []; + foreach ( $decodedArray->family_floaters as $key => $value) { + if($value != 0){ + if($key == 'parents'){ $text = 'parent'; }else if($key == 'childrens'){ $text = 'child'; }else if($key == 'parents-in-law'){$text = 'parent_in_law';}else{ $text = $key; } + array_push($whereArray,$text); + } + } + + $getAddOnType = $this->clientPolicyModel->where('id',$array['base_policy'])->where('policy_status', 1)->get()->getRow(); + $basePolicyAddOnType = $getAddOnType->is_addon; + // if is_addon value is 1 it is GMC if not it is one of the Add On policy + if($basePolicyAddOnType == 1){ $is_addon_value = 0; }else{ $is_addon_value = 1; } + $only_si_array = []; + $only_si_value = 0; + $only_si_premium_value = 0; + $only_si_gst_value = 0; + $BasePolicyEmployeeData = $this->employeeModel->where('is_active', 1 )->where('emp_code',$this->request->getGet('emp_code'))->where('client_id',$this->request->getGet('client_id'))->where('is_addon_value',$is_addon_value)->whereIn('family_floater_key',$whereArray)->findAll(); + foreach ($BasePolicyEmployeeData as $key => $value) { + + $employee_policy = $this->employeePolicyModel->where('employee_id',$value['id'])->where('client_policy_id',$array['id'])->where('is_active', 1 )->get()->getRow(); + if(isset($employee_policy->basic_cover_si)){ $only_si_value = $employee_policy->basic_cover_si; } + if(isset($employee_policy->premium)){ $only_si_premium_value = $only_si_premium_value + $employee_policy->rata_premimum;} + if(isset($employee_policy->gst)){ $only_si_gst_value = $only_si_gst_value + $employee_policy->gst;} + $temp3['is_value_exist'] = true; + $temp3['data']['employee_id'] = $value['id']; + $temp3['data']['relationship'] = $value['relationship']; + $temp3['data']['name'] = $value['name']; + $temp3['data']['dob'] = $this->convertDateFormatDMY($value['dob']); + $temp3['data']['client_policy_id'] = $array['id']; + $temp3['data']['basic_cover_si'] = isset($employee_policy->basic_cover_si) ? $employee_policy->basic_cover_si : null; + $temp3['data']['premium'] = isset($employee_policy->premium) ? $employee_policy->premium : null; + array_push($only_si_array,$temp3); + + } + + $responce['family_floaters_of_only_si_array'] = $only_si_array; + $responce['family_floaters_of_only_si_value'] = $only_si_value; + $responce['family_floaters_of_only_si_premium_value'] = $only_si_premium_value; + $responce['family_floaters_of_only_si_gst_value'] = $only_si_gst_value; + $responce['type'] = "Group Medical Coverage - Parents Top Up"; + + if($this->request->getGet('policy') == 'GMC-SI-PARENT-TOPUP'){ + return $this->respond(['status' => 'success','code' => 200,'data' => ['gmc_si_parent_topup'=>$responce]], 200); + } + + } - - - array_push($result,$data); - + + } + + + return $this->respond(['status' => 'success','code' => 200,'data' => []], 200); + + }else{ + return $this->respond(['status' => 'failed','code' => 404,'data' => []], 200); + } + } catch (\Exception $e) { + return $this->respond(['status' => 'failed','code' => 500,'data' => $e->getMessage()], 500); } } - + public function iAgreeForAddOn() + { + $postData = json_decode($this->request->getBody(), true); + $client_policy_id = $postData['client_policy_id']; + sort($client_policy_id); + // Alternatively, you can use echo to see the type + $emp_code = $postData['emp_code']; + $client_id = $postData['client_id']; - if($result) - { - return $this->respond(['status' => 'success','code' => (count($result) ? 200 : 404),'data' => $result ], 200); - }else{ - return $this->respond(['status' => 'failed','code' => (count($result) ? 200 : 404),'data' => [] ], 200); - } - -} + $this->employeeModel->where('emp_code', $emp_code ) + ->where('client_id', $client_id ) + ->where('is_active', 1 ) + ->set(array('emp_status'=>'enrolled')) + ->update(); + + $empData = $this->employeeModel->where('emp_code', $emp_code )->where('client_id', $client_id ) ->where('is_active', 1 )->findAll(); + + if (!is_null($client_policy_id) && is_array($client_policy_id)) + { + $array_list = []; + foreach ($client_policy_id as $key => $value) + { + foreach ($empData as $empDataKey => $empDataValue) + { + $this->employeePolicyModel->where('client_policy_id', $value ) + ->where('is_active', 1 ) + ->where('employee_id', $empDataValue['id'] ) + ->set(array('status'=>'enrolled')) + ->update(); + } + + $find = $this->employeeModel->getEmpFamilybyEmpCode(client_policy_id: $value,emp_code: $emp_code,client_id: $client_id,emp_status:['draft','enrolled'],policy_status:['draft','enrolled']); + if(count($find) > 0){ + $array_list[] = $find; + } + } + + $notification = $this->notificationModel->where('client_id' ,$client_id)->where('template_name', 'member_review_and_summary_mail')->first(); + if (isset($notification) && $notification['enabled'] == 1) { + $params ['array_list'] = $array_list; + $params ['client_policy_id'] = $client_policy_id; + $params ['emp_code'] = $emp_code; + $params ['client_id'] = $client_id; + $params ['notification'] = $notification; + // print_r($params);die; + $wholeData =sendMailNotification::sendMailNotification('member_review_and_summary_mail', $params); + $mail_send_return = MailHelper::send_email($wholeData[0]); + $this->myLogger->logme("info", $mail_send_return); + + if (isset($wholeData[0])) { + + $account_manager_wholeData =sendMailNotification::sendMailNotification('account_maneger_summary_mail', $params); + + foreach ($account_manager_wholeData as $key => $value) { + $mail_send_return1 = MailHelper::send_email($value); + $this->myLogger->logme("info", $mail_send_return1); + } + + $client_hr_wholeData =sendMailNotification::sendMailNotification('client_hr_summary_mail', $params); + + foreach ($client_hr_wholeData as $key => $value) { + $mail_send_return2 = MailHelper::send_email($value); + $this->myLogger->logme("info", $mail_send_return2); + } + } + } + + } + + return $this->respond(['status' => 'success','code' => 200,'data' => [] ], 200); + } + + //Post method - which receives client_policy id and empcode of the family. + //Pull records againest emp code and calculate premium + // retun array + public function calculatePremium($clientPolicyId = null , $empCode = null, $default_si = null)//family level + { + helper('excel_util_helper'); + $client_policy_id = $this->request->getVar('client_policy_id') ?? $clientPolicyId; + $emp_code = $this->request->getVar('emp_code') ?? $empCode; + $default_si = $this->request->getVar('si') ?? $default_si;// si amt which choosed in add on policy + // dd($client_policy_id); -public function exportCashDepositData() -{ + $client_id = ($this->clientPolicyModel->select('client_id')->find($client_policy_id))['client_id']; + // get policy and rack details + $policy_terms = $this->clientPolicyModel->getPolicyDetails($client_id,$client_policy_id); + $policy_type = $policy_terms[0]->is_addon; + $base_policy = $policy_terms[0]->base_policy; + $policy_terms = (array) $policy_terms[0];// convert obj to array - $CashDepositData = $this->clientPolicyModel->getdepositData($this->request->getGet('client_id'),$this->request->getGet('insurer_id')); + //get policy slab rates + $slab_details = $this->policesModel->getPolicySlabRatesForEmpOnboard($client_policy_id,$client_id); + // print_r($slab_details);die(); - // echo '
';print_r($CashDepositData); echo '
';die; + $existing_famility_details = $this->employeeModel->getEmpFamilybyEmpCode(client_id: $client_id,client_policy_id: $client_policy_id,emp_code: $emp_code,emp_status:['draft','enrolled'],policy_status:['draft','enrolled']); - if(count($CashDepositData)) - { - // Define headers and map database fields to Excel fields - $headers = [ - 'Date' => 'created_at', - 'Type' => 'transaction_type', - 'Amount' => 'amount', - 'Balance' => 'balance', - 'Description' => 'description', - 'Insurer Name' => 'insurer_name', - 'Client Name' => 'clientname' - ]; - - // Create a new Spreadsheet object - $spreadsheet = new Spreadsheet(); - - // Get the active sheet - $sheet = $spreadsheet->getActiveSheet(); - - // Add headers - $column = 'A'; - foreach ($headers as $header => $dbField) { - $sheet->setCellValue($column . '1', $header); - $column++; + if(!count($existing_famility_details) && $policy_type == 2)//top up addon only + { + //get basepolicy id then pull emplist from base policy if only current policy is DA addon policy and emplist is zero + // echo 'inside'; + $client_policy_id = $base_policy; + $existing_famility_details = $this->employeeModel->getEmpFamilybyEmpCode(client_id: $client_id,client_policy_id: $client_policy_id,emp_code: $emp_code,emp_status:['draft','enrolled'],policy_status:['draft','enrolled']); } - // Add data - $row = 2; - foreach ($CashDepositData as $Cashvalue) { + $file = ['id' => null,'client_id' => $client_id,'policy_id' => $client_policy_id,'action' => 'inception']; + // dd($this->employeeModel->getLastQuery()); + // print_r($existing_famility_details);die(); + $employee_data_group_by_family = data_group_by_family($existing_famility_details,$data_source = 'db'); + // print_r(($employee_data_group_by_family));die(); + foreach ($employee_data_group_by_family as $emp_id => $family) + { + $transformed_famility_details = transform_db_data_to_excel($family); + // print_r($transformed_famility_details);die(); + $data = calculate_premimum($transformed_famility_details,$policy_terms,$slab_details,$file,$default_si); + // dd($data); + $employee_data_group_by_family[$emp_id] = $data; + + } + + if($clientPolicyId != null && $empCode != null) + { + return $employee_data_group_by_family; + }else{ + // dd ($employee_data_group_by_family); + return $this->respond(['status' => 'success','code' => (count($employee_data_group_by_family) ? 200 : 404),'data' => [$employee_data_group_by_family] ], 200); + + } + + } + + + public function getCashDepositData() + { + + $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, policies.id as policy_id , client_policy.policy_type_id as policy_type_id, policies.name as policy_name , client_policy.is_addon as is_addon , client_policy.open_for_enrollment as OpenForEnrollment , client_policy.inception_type as inception_type ') + ->join('policies', 'client_policy.policy_id = policies.id', 'left') + ->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) + { + + $value['type'] = $this->policyTypeModel->where('id',$value['policy_type_id'])->get()->getRow()->policy_type; + $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++; + } + } + } + + $value['totalMembersCount'] = count($employeeDetails); + $value['membersCountOfEnrolled'] = $enrolledCount; + $value['membersCountOfDraft'] = $draftCount; + + array_push($data['policyDetails'],$value); + } + + + array_push($result,$data); + + } + } + + + + if($result) + { + return $this->respond(['status' => 'success','code' => (count($result) ? 200 : 404),'data' => $result ], 200); + }else{ + return $this->respond(['status' => 'failed','code' => (count($result) ? 200 : 404),'data' => [] ], 200); + } + + } + + + + + public function exportCashDepositData() + { + + $CashDepositData = $this->clientPolicyModel->getdepositData($this->request->getGet('client_id'),$this->request->getGet('insurer_id')); + + // echo '
';print_r($CashDepositData); echo '
';die; + + if(count($CashDepositData)) + { + // Define headers and map database fields to Excel fields + $headers = [ + 'Date' => 'created_at', + 'Type' => 'transaction_type', + 'Amount' => 'amount', + 'Balance' => 'balance', + 'Description' => 'description', + 'Insurer Name' => 'insurer_name', + 'Client Name' => 'clientname' + ]; + + // Create a new Spreadsheet object + $spreadsheet = new Spreadsheet(); + + // Get the active sheet + $sheet = $spreadsheet->getActiveSheet(); + + // Add headers $column = 'A'; - foreach ($headers as $dbField) { - $sheet->setCellValue($column . $row, $Cashvalue->$dbField); + foreach ($headers as $header => $dbField) { + $sheet->setCellValue($column . '1', $header); $column++; } - $row++; + + // Add data + $row = 2; + foreach ($CashDepositData as $Cashvalue) { + $column = 'A'; + foreach ($headers as $dbField) { + $sheet->setCellValue($column . $row, $Cashvalue->$dbField); + $column++; + } + $row++; + } + + + // Set the header for download + $filename = $CashDepositData[0]->insurer_name.'-CashDeposit.xlsx'; + header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); + header('Content-Disposition: attachment;filename="' . $filename . '"'); + header('Cache-Control: max-age=0'); + + // Save the Excel file to output + $writer = new Xlsx($spreadsheet); + $writer->save('php://output'); + exit; + + return $this->respond(['status' => 'success', 'code' => 200, 'data' => []], 200); + + }else{ + + return $this->respond(['status' => 'failed', 'code' => 404, 'data' => []], 200); } - - - // Set the header for download - $filename = $CashDepositData[0]->insurer_name.'-CashDeposit.xlsx'; - header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); - header('Content-Disposition: attachment;filename="' . $filename . '"'); - header('Cache-Control: max-age=0'); - - // Save the Excel file to output - $writer = new Xlsx($spreadsheet); - $writer->save('php://output'); - exit; - - return $this->respond(['status' => 'success', 'code' => 200, 'data' => []], 200); - - }else{ - - return $this->respond(['status' => 'failed', 'code' => 404, 'data' => []], 200); - } - -} - - -public function removeEmpAndEmpPolicyData() -{ - try { - - $clientPolicy = $this->clientPolicyModel->where('id',$this->request->getGet('client_policy_id'))->findAll(); - if(count($clientPolicy)) - { + } - if($clientPolicy[0]['is_addon'] == 2)//Topup + public function removeEmpAndEmpPolicyData() + { + try { + + $clientPolicy = $this->clientPolicyModel->where('id',$this->request->getGet('client_policy_id'))->findAll(); + + if(count($clientPolicy)) { - $empData = $this->employeeModel->where('emp_code',$this->request->getGet('emp_code')) - ->where('is_addon_value', 0 )->findAll(); - if(count($empData)) + + + if($clientPolicy[0]['is_addon'] == 2)//Topup { + $empData = $this->employeeModel->where('emp_code',$this->request->getGet('emp_code')) + ->where('is_addon_value', 0 )->findAll(); + if(count($empData)) + { + foreach ($empData as $key => $value) { + + $this->employeePolicyModel->where('client_policy_id',$this->request->getGet('client_policy_id') ) + ->where('employee_id', $value['id'] ) + ->set(array('is_active'=> 0 )) + ->update(); + + } + } + + } + else if($clientPolicy[0]['is_addon'] == 3)//Dependent addon + { + $empData = $this->employeeModel->where('emp_code',$this->request->getGet('emp_code')) + ->where('is_addon_value', 1 )->findAll(); + if(count($empData)) + { foreach ($empData as $key => $value) { $this->employeePolicyModel->where('client_policy_id',$this->request->getGet('client_policy_id') ) - ->where('employee_id', $value['id'] ) - ->set(array('is_active'=> 0 )) - ->update(); - + ->where('employee_id', $value['id'] ) + ->set(array('is_active'=> 0 )) + ->update(); + } + + $this->employeeModel->where('emp_code', $this->request->getGet('emp_code') ) + ->where('is_active', 1 )->where('is_addon_value', 1 ) + ->set(array('is_active'=> 0 )) + ->update(); + } + + } + + + + return $this->respond(['status' => 'success','code' => 200,'data' =>[] ], 200); + + }else{ + return $this->respond(['status' => 'failed','code' => 404,'data' => [] ], 200); + } + + + } catch (\Exception $e) { + return $this->respond(['status' => 'failed','code' => 500,'data' => $e->getMessage()], 500); + } + + } + + + function getEmployeeActiveOrInactivePolicy() + { + + if($this->request->getGet('type') == 'Active'){ $policy_status = 1; }else{ $policy_status = 0; } + $ClientPolicyData = $this->clientPolicyModel->select('client_policy.* , policies.name as policy_name , policy_type.policy_type as policy_type') + ->join('policies', 'client_policy.policy_id = policies.id', 'left') + ->join('policy_type', 'client_policy.policy_type_id = policy_type.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', $policy_status) + ->orderby('client_policy.id' , 'ASC') + ->findAll(); + + // Retrieve employee and dependents data by passing the employee code + $employeeData = $this->employeeModel->where('emp_code',$this->request->getGet('emp_code')) + ->where('client_id',$this->request->getGet('client_id')) + ->where('client_branch_id',$this->request->getGet('client_branch_id')) + ->where('is_active', 1 )->findAll(); + $employeeName = $this->employeeModel->where('emp_code',$this->request->getGet('emp_code')) + ->where('client_id',$this->request->getGet('client_id')) + ->where('client_branch_id',$this->request->getGet('client_branch_id')) + ->where('family_floater_key','self')->where('is_active', 1 ) + ->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) { + + + + $terms = json_decode($ClientPolicyValue['policy_terms']); + + if($ClientPolicyValue['policy_type_id'] == 1){ $data['policy_terms'] = $this->policyTermsFiter($terms,'gpa'); } + else{ $data['policy_terms'] = $this->policyTermsFiter($terms,'gmc'); } + + $data['client_id'] = $ClientPolicyValue['client_id']; + $data['client_policy_id'] = $ClientPolicyValue['id']; + $data['policy_name'] = $ClientPolicyValue['policy_name']; + $data['policy_type'] = $ClientPolicyValue['policy_type']; + $data['policy_type'] = $ClientPolicyValue['policy_type']; + $data['policy_no'] = $ClientPolicyValue['policy_no']; + $data['policy_start_date'] = $this->convertDateFormatDisplay($ClientPolicyValue['policy_start_date']); + $data['policy_end_date'] = $this->convertDateFormatDisplay($ClientPolicyValue['policy_end_date']); + // $data['policy_terms'] = $terms; + + if($ClientPolicyValue['policy_type_id'] == 1){ $data['heading'] = 'Group Personal Accident Coverage'; }else + if($ClientPolicyValue['policy_type_id'] == 2){ $data['heading'] = 'Group Medical Coverage'; }else + if($ClientPolicyValue['policy_type_id'] == 3){ $data['heading'] = 'Group Medical Coverage - Parents'; }else + if($ClientPolicyValue['policy_type_id'] == 4){ $data['heading'] = 'Group Medical Coverage - Top Up'; }else + if($ClientPolicyValue['policy_type_id'] == 5){ $data['heading'] = 'Group Medical Coverage - Parents (Top Up)'; } + + if($ClientPolicyValue['policy_type_id'] == 1){ $data['floter_text_heading'] = 'Sum Insured'; } + else + { + if($terms->family_floater == 1){ $data['floter_text_heading'] = 'Floter Sum Insured'; }else{ $data['floter_text_heading'] = 'Sum Insured'; } + } + + $employee_policy = $this->employeePolicyModel->select('employees.*,employee_polices.employee_id , employee_polices.basic_cover_si , employee_polices.premium , employee_polices.gst , employee_polices.tpa_id , employee_polices.rand_string , employee_polices.uhid as uhid') + ->join('employees', 'employee_polices.employee_id = employees.id', 'left') + ->whereIn('employee_polices.employee_id',$whereArrayForId) + ->where('employee_polices.client_policy_id',$ClientPolicyValue['id']) + ->where('employee_polices.is_active', 1 )->findAll(); + if(count($employee_policy) > 0) + { + $si_value = 0; + $si_premium_value = 0; + $si_gst_value = 0; + + foreach ($employee_policy as $key => $value) { + if(isset($value['basic_cover_si'])){ $si_value = $value['basic_cover_si']; } + if(isset($value['premium'])){ $si_premium_value = $si_premium_value + $value['premium'];} + if(isset($value['gst'])){ $si_gst_value = $si_gst_value + $value['gst'];} + } + + + if($employee_policy[0]['tpa_id'] != null) + $data['eCardDownload'] = base_url('download-e-card/') . $employee_policy[0]['rand_string']; + else + $data['eCardDownload'] = null; + + + + $data['si_value'] = $si_value; + $data['si_premium_value'] = ($ClientPolicyValue['policy_type_id'] == 1 || $ClientPolicyValue['policy_type_id'] == 2) ? 0 : $si_premium_value; + $data['si_gst_value'] = ($ClientPolicyValue['policy_type_id'] == 1 || $ClientPolicyValue['policy_type_id'] == 2) ? 0 : $si_gst_value; + + $data['EmployeePolicy'] = $employee_policy; + array_push($result, $data); } } - else if($clientPolicy[0]['is_addon'] == 3)//Dependent addon - { - $empData = $this->employeeModel->where('emp_code',$this->request->getGet('emp_code')) - ->where('is_addon_value', 1 )->findAll(); - if(count($empData)) - { - foreach ($empData as $key => $value) { - $this->employeePolicyModel->where('client_policy_id',$this->request->getGet('client_policy_id') ) - ->where('employee_id', $value['id'] ) - ->set(array('is_active'=> 0 )) - ->update(); + return $this->respond(['status' => 'success','code' => 200,'data' => $result , 'emp_name' => $employeeName ], 200); - } - - $this->employeeModel->where('emp_code', $this->request->getGet('emp_code') ) - ->where('is_active', 1 )->where('is_addon_value', 1 ) - ->set(array('is_active'=> 0 )) - ->update(); - } - - } - - - - return $this->respond(['status' => 'success','code' => 200,'data' =>[] ], 200); - }else{ return $this->respond(['status' => 'failed','code' => 404,'data' => [] ], 200); } - - - } catch (\Exception $e) { - return $this->respond(['status' => 'failed','code' => 500,'data' => $e->getMessage()], 500); + } - -} -function getEmployeeActiveOrInactivePolicy() -{ - - if($this->request->getGet('type') == 'Active'){ $policy_status = 1; }else{ $policy_status = 0; } - $ClientPolicyData = $this->clientPolicyModel->select('client_policy.* , policies.name as policy_name , policy_type.policy_type as policy_type') - ->join('policies', 'client_policy.policy_id = policies.id', 'left') - ->join('policy_type', 'client_policy.policy_type_id = policy_type.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', $policy_status) - ->orderby('client_policy.id' , 'ASC') - ->findAll(); - - // Retrieve employee and dependents data by passing the employee code - $employeeData = $this->employeeModel->where('emp_code',$this->request->getGet('emp_code')) - ->where('client_id',$this->request->getGet('client_id')) - ->where('client_branch_id',$this->request->getGet('client_branch_id')) - ->where('is_active', 1 )->findAll(); - $employeeName = $this->employeeModel->where('emp_code',$this->request->getGet('emp_code')) - ->where('client_id',$this->request->getGet('client_id')) - ->where('client_branch_id',$this->request->getGet('client_branch_id')) - ->where('family_floater_key','self')->where('is_active', 1 ) - ->get()->getRow()->name; - $whereArrayForId = []; - foreach ( $employeeData as $key => $value) { array_push($whereArrayForId, $value['id']); } - - if(count($ClientPolicyData) > 0 && count($employeeData) > 0) + function policyTermsFiter($terms , $type) { - $result = []; - foreach ($ClientPolicyData as $key => $ClientPolicyValue) { + + $gpa = [ + "sumInsured2" => "Sum Insured", + "totalSumInsured" => "Total Sum Assured", + "self" => "Self", + "self_min_age" => "Min Age", + "self_max_age" => "Max Age", + "accidentalDeathBenefit" => "Accidental Death Benefit", + "permanentTotalDisablement" => "Permanent Total Disablement", + "permanentPartialDisablement" => "Permanent Partial Disablement", + "temporaryTotalDisablementBenefit" => "Temporary Total Disablement benefit", + "accidentalHospitalizationExpenses" => "Accidental Hospitalization Expenses", + "childrenEducationWelfareFund" => "Children Education Welfare Fund", + "compassionateVisitExpenses" => "Compassionate Visit Expenses", + "compassionateVisitExpensesData" => "Compassionate Visit Expenses Data", + "brokenBoneExpenses" => "Broken Bone Expenses", + "brokenBoneExpensesData" => "Broken Bone Expenses Data", + "ambulanceCharges" => "Ambulance charges", + "ambulanceChargesData" => "Ambulance charges Data", + "burnExpenses" => "Burn Expenses", + "burnExpensesData" => "Burn Expenses Data", + "carriageOfDeadBody" => "Carriage of Dead Body", + "carriageOfDeadBodyData" => "Carriage of Dead Body Data", + "animalSnakeInsectBite" => "Animal/Snake/Insect bite", + "terrorism" => "Terrorism", + "worldwideCover" => "Worldwide Cover" + ]; + + $gmc = [ + "sum_insured" => "Sum Insured", + "waiverofpreexistingdiseases" => "Waiver of Pre-existing Diseases", + "maternitycoverage" => "Maternity Coverage", + "babyday1cover" => "Baby Day 1 Cover", + "9monthwaitingperiodwaived" => "9-month waiting Period –waived", + "coverfromthedateofjoining" => "Cover from the date of Joining", + "waiverof1,2,3&4thyearexclusions" => "Waiver of 1, 2, 3 & 4th year Exclusions", + "waiverof30dayswaitingperiod" => "Waiver of 30 days waiting period", + "prehospitalizationcover" => "Pre Hospitalization Cover", + "copayzonewisecopay" => "Co-Pay/Zone wise Co Pay", + "roomrentlimit" => "Room Rent Limit", + "ailmentcapping" => "Ailment capping", + ]; - - $terms = json_decode($ClientPolicyValue['policy_terms']); - - if($ClientPolicyValue['policy_type_id'] == 1){ $data['policy_terms'] = $this->policyTermsFiter($terms,'gpa'); } - else{ $data['policy_terms'] = $this->policyTermsFiter($terms,'gmc'); } - - $data['client_id'] = $ClientPolicyValue['client_id']; - $data['client_policy_id'] = $ClientPolicyValue['id']; - $data['policy_name'] = $ClientPolicyValue['policy_name']; - $data['policy_type'] = $ClientPolicyValue['policy_type']; - $data['policy_type'] = $ClientPolicyValue['policy_type']; - $data['policy_no'] = $ClientPolicyValue['policy_no']; - $data['policy_start_date'] = $this->convertDateFormatDisplay($ClientPolicyValue['policy_start_date']); - $data['policy_end_date'] = $this->convertDateFormatDisplay($ClientPolicyValue['policy_end_date']); - // $data['policy_terms'] = $terms; - - if($ClientPolicyValue['policy_type_id'] == 1){ $data['heading'] = 'Group Personal Accident Coverage'; }else - if($ClientPolicyValue['policy_type_id'] == 2){ $data['heading'] = 'Group Medical Coverage'; }else - if($ClientPolicyValue['policy_type_id'] == 3){ $data['heading'] = 'Group Medical Coverage - Parents'; }else - if($ClientPolicyValue['policy_type_id'] == 4){ $data['heading'] = 'Group Medical Coverage - Top Up'; }else - if($ClientPolicyValue['policy_type_id'] == 5){ $data['heading'] = 'Group Medical Coverage - Parents (Top Up)'; } - - if($ClientPolicyValue['policy_type_id'] == 1){ $data['floter_text_heading'] = 'Sum Insured'; } - else - { - if($terms->family_floater == 1){ $data['floter_text_heading'] = 'Floter Sum Insured'; }else{ $data['floter_text_heading'] = 'Sum Insured'; } - } - - $employee_policy = $this->employeePolicyModel->select('employees.*,employee_polices.employee_id , employee_polices.basic_cover_si , employee_polices.premium , employee_polices.gst , employee_polices.tpa_id , employee_polices.rand_string , employee_polices.uhid as uhid') - ->join('employees', 'employee_polices.employee_id = employees.id', 'left') - ->whereIn('employee_polices.employee_id',$whereArrayForId) - ->where('employee_polices.client_policy_id',$ClientPolicyValue['id']) - ->where('employee_polices.is_active', 1 )->findAll(); - if(count($employee_policy) > 0) - { - $si_value = 0; - $si_premium_value = 0; - $si_gst_value = 0; - - foreach ($employee_policy as $key => $value) { - if(isset($value['basic_cover_si'])){ $si_value = $value['basic_cover_si']; } - if(isset($value['premium'])){ $si_premium_value = $si_premium_value + $value['premium'];} - if(isset($value['gst'])){ $si_gst_value = $si_gst_value + $value['gst'];} - } - - - if($employee_policy[0]['tpa_id'] != null) - $data['eCardDownload'] = base_url('download-e-card/') . $employee_policy[0]['rand_string']; - else - $data['eCardDownload'] = null; - - - $data['si_value'] = $si_value; - $data['si_premium_value'] = ($ClientPolicyValue['policy_type_id'] == 1 || $ClientPolicyValue['policy_type_id'] == 2) ? 0 : $si_premium_value; - $data['si_gst_value'] = ($ClientPolicyValue['policy_type_id'] == 1 || $ClientPolicyValue['policy_type_id'] == 2) ? 0 : $si_gst_value; - - $data['EmployeePolicy'] = $employee_policy; - array_push($result, $data); + $finalarray = []; + if($type == 'gpa'){ + foreach ($gpa as $key => $value) { + if(isset($terms->$key)) + $finalarray[$value] = $terms->$key; } + }else{ + foreach ($gmc as $key => $value) { + if(isset($terms->$key)) + $finalarray[$value] = $terms->$key; + } + } + + + return $finalarray; + + } + + + private function convertDateFormatDisplay($dateString) + { + // Attempt to create a DateTime object from the provided date string + $dateTime = \DateTime::createFromFormat('Y-m-d', $dateString); + + if ($dateTime instanceof \DateTime) { + return $dateTime->format('d-M-Y'); + } else { + return null; + } + } + + public function getFEContent() + { + try { + + $feContentData = $this->feContentModel->findAll(); + if (count($feContentData) > 0) { - } + return $this->respond(['status' => 'success','code' => 200,'data' => $feContentData ],200); - return $this->respond(['status' => 'success','code' => 200,'data' => $result , 'emp_name' => $employeeName ], 200); - - }else{ - return $this->respond(['status' => 'failed','code' => 404,'data' => [] ], 200); - } - -} - - -function policyTermsFiter($terms , $type) -{ - - $gpa = [ - "sumInsured2" => "Sum Insured", - "totalSumInsured" => "Total Sum Assured", - "self" => "Self", - "self_min_age" => "Min Age", - "self_max_age" => "Max Age", - "accidentalDeathBenefit" => "Accidental Death Benefit", - "permanentTotalDisablement" => "Permanent Total Disablement", - "permanentPartialDisablement" => "Permanent Partial Disablement", - "temporaryTotalDisablementBenefit" => "Temporary Total Disablement benefit", - "accidentalHospitalizationExpenses" => "Accidental Hospitalization Expenses", - "childrenEducationWelfareFund" => "Children Education Welfare Fund", - "compassionateVisitExpenses" => "Compassionate Visit Expenses", - "compassionateVisitExpensesData" => "Compassionate Visit Expenses Data", - "brokenBoneExpenses" => "Broken Bone Expenses", - "brokenBoneExpensesData" => "Broken Bone Expenses Data", - "ambulanceCharges" => "Ambulance charges", - "ambulanceChargesData" => "Ambulance charges Data", - "burnExpenses" => "Burn Expenses", - "burnExpensesData" => "Burn Expenses Data", - "carriageOfDeadBody" => "Carriage of Dead Body", - "carriageOfDeadBodyData" => "Carriage of Dead Body Data", - "animalSnakeInsectBite" => "Animal/Snake/Insect bite", - "terrorism" => "Terrorism", - "worldwideCover" => "Worldwide Cover" - ]; - - $gmc = [ - "sum_insured" => "Sum Insured", - "waiverofpreexistingdiseases" => "Waiver of Pre-existing Diseases", - "maternitycoverage" => "Maternity Coverage", - "babyday1cover" => "Baby Day 1 Cover", - "9monthwaitingperiodwaived" => "9-month waiting Period –waived", - "coverfromthedateofjoining" => "Cover from the date of Joining", - "waiverof1,2,3&4thyearexclusions" => "Waiver of 1, 2, 3 & 4th year Exclusions", - "waiverof30dayswaitingperiod" => "Waiver of 30 days waiting period", - "prehospitalizationcover" => "Pre Hospitalization Cover", - "copayzonewisecopay" => "Co-Pay/Zone wise Co Pay", - "roomrentlimit" => "Room Rent Limit", - "ailmentcapping" => "Ailment capping", - ]; - - - - $finalarray = []; - if($type == 'gpa'){ - foreach ($gpa as $key => $value) { - if(isset($terms->$key)) - $finalarray[$value] = $terms->$key; - } - }else{ - foreach ($gmc as $key => $value) { - if(isset($terms->$key)) - $finalarray[$value] = $terms->$key; - } - } - - - return $finalarray; - -} - - -private function convertDateFormatDisplay($dateString) -{ - // Attempt to create a DateTime object from the provided date string - $dateTime = \DateTime::createFromFormat('Y-m-d', $dateString); - - if ($dateTime instanceof \DateTime) { - return $dateTime->format('d-M-Y'); - } else { - return null; - } -} - -public function getFEContent() -{ - try { - - $feContentData = $this->feContentModel->findAll(); - if (count($feContentData) > 0) { - - return $this->respond(['status' => 'success','code' => 200,'data' => $feContentData ],200); - - } else { - - return $this->respond(['status' => 'failed','code' => 404,'data' => 'No Data'],404); - } - } catch (\Throwable $th) { - return $this->respond(['status' => 'failed','code' => 500,'data' => $th],500); - } -} - -public function getAdvertisementImage() -{ - try { - - $img = $this->addImgModel->where('is_active',1)->findAll(); - - if (count($img) > 0) { - $data=[]; - foreach ($img as $key => $value) { - $url = base_url('public/uploads/add_image_upload/').$value['name']; - array_push($data,$url); + } else { + + return $this->respond(['status' => 'failed','code' => 404,'data' => 'No Data'],404); } - - return $this->respond(['status' => 'success','code' => 200,'data' => $data ],200); + } catch (\Throwable $th) { + return $this->respond(['status' => 'failed','code' => 500,'data' => $th],500); + } + } - } else { - - return $this->respond(['status' => 'failed','code' => 404,'data' => 'No Data'],404); + public function getAdvertisementImage() + { + try { + + $img = $this->addImgModel->where('is_active',1)->findAll(); + + if (count($img) > 0) { + $data=[]; + foreach ($img as $key => $value) { + $url = base_url('public/uploads/add_image_upload/').$value['name']; + array_push($data,$url); + } + + return $this->respond(['status' => 'success','code' => 200,'data' => $data ],200); + + } else { + + return $this->respond(['status' => 'failed','code' => 404,'data' => 'No Data'],404); + } + } catch (\Throwable $th) { + return $this->respond(['status' => 'failed','code' => 500,'data' => $th],500); } - } catch (\Throwable $th) { - return $this->respond(['status' => 'failed','code' => 500,'data' => $th],500); - } -} + } + + + public function storeFireBase() + { + try { + $firebase_token = $this->request->getPost('firebase_token'); + $mobile = $this->request->getPost('mobile'); + + // Ensure the mobile number is provided + if (empty($mobile)) { + return $this->respond(['status' => 'failed', 'code' => 400, 'message' => 'Mobile number is required'], 400); + } + + // Fetch employee by mobile number + $employee = $this->employeeModel->where('mobile', $mobile)->first(); + + if ($employee) { + // Check if firebase_token is provided + if (!empty($firebase_token)) { + + // Check if the current firebase_token is different from the new one + if ($employee['firebase_token'] !== $firebase_token) { + // Update the employee's firebase_token + $data['firebase_token'] = $firebase_token; + $id = $employee['id']; + // return json_encode($data); + // Direct database update query for testing + $db = \Config\Database::connect(); + $builder = $db->table('employees'); + $update_emp = $builder->update($data, ['id' => $id]); + + // Check if the update was successful + if ($db->affectedRows() > 0) { + // Fetch the updated employee data + $updated_employee = $this->employeeModel->find($id); + return $this->respond(['status' => 'success', 'code' => 200, 'data' => $updated_employee], 200); + } else { + log_message('error', 'Update failed. No rows affected.'); + return $this->respond(['status' => 'failed', 'code' => 500, 'message' => 'Failed to update employee data'], 500); + } + } else { + return $this->respond(['status' => 'failed', 'code' => 400, 'message' => 'New Firebase Token is the same as the current one'], 400); + } + } else { + return $this->respond(['status' => 'failed', 'code' => 400, 'message' => 'Firebase Token is required'], 400); + } + } else { + return $this->respond(['status' => 'failed', 'code' => 404, 'message' => 'Employee not found'], 404); + } + } catch (\Throwable $th) { + log_message('error', 'An error occurred: ' . $th->getMessage()); + return $this->respond(['status' => 'failed', 'code' => 500, 'message' => 'An error occurred', 'error' => $th->getMessage()], 500); + } + } + } \ No newline at end of file From 3d03a6f063f6b4fda5be9c2f8f5d91d9d755bf11 Mon Sep 17 00:00:00 2001 From: aadhavan valli Date: Sat, 20 Jul 2024 14:20:41 +0530 Subject: [PATCH 02/19] CHANGE_EMP_REST_BASIC_PAY : AADHAVAN --- app/Controllers/EmployeeRestController.php | 1 + 1 file changed, 1 insertion(+) diff --git a/app/Controllers/EmployeeRestController.php b/app/Controllers/EmployeeRestController.php index 40d6f8b5..92c36a0a 100644 --- a/app/Controllers/EmployeeRestController.php +++ b/app/Controllers/EmployeeRestController.php @@ -785,6 +785,7 @@ class EmployeeRestController extends AdminController 'client_id' => $client_id, 'emp_status'=>'draft', 'band'=> $extra['10'][$index], + 'basic_pay'=> $extra['11'][$index], 'client_branch_id' => $client_branch_id ]; From 816c49cc53ef20604d2c2f250b9400c57b69ea4d Mon Sep 17 00:00:00 2001 From: Venba Date: Sat, 20 Jul 2024 09:24:29 +0000 Subject: [PATCH 03/19] CHANGE_EMP_REST_UNTI_FILED_ADDED --- app/Controllers/EmployeeRestController.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/app/Controllers/EmployeeRestController.php b/app/Controllers/EmployeeRestController.php index 92c36a0a..9b4db74a 100644 --- a/app/Controllers/EmployeeRestController.php +++ b/app/Controllers/EmployeeRestController.php @@ -786,6 +786,7 @@ class EmployeeRestController extends AdminController 'emp_status'=>'draft', 'band'=> $extra['10'][$index], 'basic_pay'=> $extra['11'][$index], + 'unit'=> $extra['12'][$index], 'client_branch_id' => $client_branch_id ]; @@ -2235,7 +2236,7 @@ class EmployeeRestController extends AdminController "waiverofpreexistingdiseases" => "Waiver of Pre-existing Diseases", "maternitycoverage" => "Maternity Coverage", "babyday1cover" => "Baby Day 1 Cover", - "9monthwaitingperiodwaived" => "9-month waiting Period –waived", + "9monthwaitingperiodwaived" => "9-month waiting Period –waived", "coverfromthedateofjoining" => "Cover from the date of Joining", "waiverof1,2,3&4thyearexclusions" => "Waiver of 1, 2, 3 & 4th year Exclusions", "waiverof30dayswaitingperiod" => "Waiver of 30 days waiting period", From 8d3f31413c5502cffd13d701052e6c61d6853a9d Mon Sep 17 00:00:00 2001 From: aadhavan valli Date: Sat, 20 Jul 2024 16:40:29 +0530 Subject: [PATCH 04/19] CHANGE_EMP_REST_EMP_UPLOAD_FIREBASE_JSON : AADHAVAN --- app/Controllers/EmployeeRestController.php | 30 ++++++++++++---------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/app/Controllers/EmployeeRestController.php b/app/Controllers/EmployeeRestController.php index 92c36a0a..f3f28503 100644 --- a/app/Controllers/EmployeeRestController.php +++ b/app/Controllers/EmployeeRestController.php @@ -632,6 +632,7 @@ class EmployeeRestController extends AdminController $policy_id = $this->request->getPost('policy_id'); $client_data = $this->clientModel->where('id', $client_id)->first(); + $notification = $this->notificationModel->where('client_id',$client_id)->where('template_name','member_welcome_mail')->first(); $jwt = $this->request->getHeader('Authorization'); @@ -742,13 +743,13 @@ class EmployeeRestController extends AdminController $basic_cover_si= []; foreach ($extra['0'] as $index => $id) { $relation =''; - if ($extra['5'][$index] === 'Mother' || $extra['5'][$index] === 'Father') { + if (strtolower(trim($extra['5'][$index])) === 'mother' || strtolower(trim($extra['5'][$index])) === 'father') { $relation = 'parent'; - } else if($extra['5'][$index] === 'Son' || $extra['5'][$index] === 'Daughter'){ + } else if(strtolower(trim($extra['5'][$index])) === 'son' || strtolower(trim($extra['5'][$index])) === 'daughter'){ $relation = 'child'; - }else if($extra['5'][$index] === 'Father in Law' || $extra['5'][$index] === 'Mother in Law'){ + }else if(strtolower(trim($extra['5'][$index])) === 'father in law' || strtolower(trim($extra['5'][$index])) === 'mother in law'){ $relation = 'parent_in_law'; - }else if($extra['5'][$index] === 'Spouse'){ + }else if(strtolower(trim($extra['5'][$index])) === 'spouse'){ $relation = 'spouse'; }else{ $relation = 'self'; @@ -777,7 +778,7 @@ class EmployeeRestController extends AdminController // Check if the 'doj' key exists before accessing it 'doj' => $doj_new_format, 'gender' => $extra['4'][$index], - 'relationship' => ucfirst($extra['5'][$index]), + 'relationship' => ucfirst(trim($extra['5'][$index])), 'family_floater_key' => $relation, 'dob' => $dob_new_format, 'email_corporate' => $extra['7'][$index], @@ -888,10 +889,10 @@ class EmployeeRestController extends AdminController $emp_policy = $this->employeePolicyModel->insert($emp_policy_data); } - $notification = $this->notificationModel->where('client_id',$client_id)->where('template_name','member_welcome_mail')->first(); + if (isset($notification) && $notification['enabled'] == 1 && !empty($notification['mail_content'])) { - if (isset($notification) && $notification['enabled'] == 1) { //trigger + $wholeData=[]; if ($dataToInsert[$a]['relationship'] == 'Self' && isset($dataToInsert[$a]['email_corporate']) && !empty($dataToInsert[$a]['email_corporate'])) { $params['dataToInsert'] = $dataToInsert[$a]; @@ -2323,9 +2324,10 @@ class EmployeeRestController extends AdminController public function storeFireBase() { - try { - $firebase_token = $this->request->getPost('firebase_token'); - $mobile = $this->request->getPost('mobile'); + // try { + $json = $this->request->getJSON(); + $firebase_token = $json->firebase_token; + $mobile = $json->mobile; // Ensure the mobile number is provided if (empty($mobile)) { @@ -2368,10 +2370,10 @@ class EmployeeRestController extends AdminController } else { return $this->respond(['status' => 'failed', 'code' => 404, 'message' => 'Employee not found'], 404); } - } catch (\Throwable $th) { - log_message('error', 'An error occurred: ' . $th->getMessage()); - return $this->respond(['status' => 'failed', 'code' => 500, 'message' => 'An error occurred', 'error' => $th->getMessage()], 500); - } + // } catch (\Throwable $th) { + // log_message('error', 'An error occurred: ' . $th->getMessage()); + // return $this->respond(['status' => 'failed', 'code' => 500, 'message' => 'An error occurred', 'error' => $th->getMessage()], 500); + // } } From 469d0d92fe002ef14bdaf221fbf47c64110b077d Mon Sep 17 00:00:00 2001 From: aadhavan valli Date: Sat, 20 Jul 2024 16:45:40 +0530 Subject: [PATCH 05/19] CHANGE_ROUTE_FILE : AADHAVAN --- app/Config/Routes.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/app/Config/Routes.php b/app/Config/Routes.php index 06888fcb..14f1ef6a 100644 --- a/app/Config/Routes.php +++ b/app/Config/Routes.php @@ -136,7 +136,8 @@ $routes->group("/employee", ["filter" => "authMVC"], function ($routes) { $routes->post("upload", "EmployeeController::employeesUplodWithEvents"); $routes->get("excel_error/(:any)", "EmployeeController::getExcelFileErrors/$1"); $routes->get("endorsement-list", "EmployeeController::endorsementList"); - $routes->get("enrollment-list", "EmployeeController::enrollmentList"); + $routes->get("enrollment-list", "EmployeeController::enrollmentClientList"); + $routes->get("empby_client_clientbranch/(:any)/(:any)", "EmployeeController::empby_client_clientbranch/$1/$2"); $routes->get("truncate/(:any)", "EmployeeController::truncateFileData/$1"); }); From a147cf313055a23c64e869baa97347ace62c41f3 Mon Sep 17 00:00:00 2001 From: bitbucket Date: Mon, 22 Jul 2024 13:41:45 +0530 Subject: [PATCH 06/19] CHNAGE_ push notification : GWM --- app/Config/Routes.php | 2 ++ app/Config/google-services.json | 13 ++++++++ app/Controllers/EmployeeRestController.php | 38 +++++++++++++++++++++- composer.json | 4 ++- 4 files changed, 55 insertions(+), 2 deletions(-) create mode 100644 app/Config/google-services.json diff --git a/app/Config/Routes.php b/app/Config/Routes.php index 14f1ef6a..aae95756 100644 --- a/app/Config/Routes.php +++ b/app/Config/Routes.php @@ -323,6 +323,8 @@ $routes->group("employeeRest", ["filter" => "authJWT"], function ($routes) { $routes->get("getAdvertisementImage", "EmployeeRestController::getAdvertisementImage"); }); +$routes->get("sendPushNotification", "EmployeeRestController::sendPushNotification"); + diff --git a/app/Config/google-services.json b/app/Config/google-services.json new file mode 100644 index 00000000..f465fcd7 --- /dev/null +++ b/app/Config/google-services.json @@ -0,0 +1,13 @@ +{ + "type": "service_account", + "project_id": "push-notification-enrollment", + "private_key_id": "979d0fcd0ce95d31367f3150d34ee0044ca51b0d", + "private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC4Xsan6ESIzM12\nG15gRU361Yy6PVmoMzTToWtZHPEcDRd9weFNlCXjmX+WAqdgD/hQ42GcZQVCndse\nEQGJHbRu/ifMKGo53zxOpshNZnCSxojAGWIGrIHFE5kFumiKz9drW9vPWsFLtgx0\nEAW0T7su1MejjH33GftHG8k/q3uyWoU0+OFRD6emhYkFdVsucwR27hE7GsFwE+CF\nnRdSWQ5mu2e8J7q9Qbpgot5d7uk7iJgpiyNdChPvqUZ7XeknVrw1F4REZlbAkVjb\nFuwKg5qtG97LZ1NkyYqFmssA1rNkqSi4+T+2/ERegdwyA6W4/HLT9fPbSl4v1MvB\ntJlGYkMpAgMBAAECggEABhspdCUmo+s4gMleQkz5TK3m58IhZocvoDSv4/cn6xhp\n50HVDucxrAyI47R5y54ryK4HLRFRb8ffmmrQxLRFpgln0wShpAIHMsmmR531a38E\nx2vvya3L7HV+M2jdjn9csJMNwBvO3A2O8wcW0UZ0uhPU+s8r2tOy9UNv0lqBEcKM\nUxCtk7UxcLEM3btDP5I4oEHVo2f5jzPeb99KHbYQV/vc0BtA1wtuYTzGT2EhBpTG\nN1rbQhlj6iJ6vMwHETWrctNMohCQNQEv/QIC/NWYPNRqmtrJfNe29XGWN9IIhv0e\n/ZmhdzoO+uhJW4VaWpI93nB5ZAa6LHqJSg+OyrPoawKBgQDd45Aiq7d+4Z+kDZYu\n72bgW5CGhyck2hrqHpBdHA960AYIftw/wHgI9xb9Z8hi+Lh+W18xDywOLoaz7TJV\nElj2Gh3oj2ZLzDpeyqV9UOgz11dbm6yYUK8jl7zyajBt7RhGcdj+4x+YjUTT6O61\nuxm2ZbKsb/0er/W6DlKDVvpWSwKBgQDUtqowATEaGTrd+eutanRwtv+rdptVcadj\nD4H3XdY4PAsVSp1mT9knGgh7c5elI0lBH/VD/IbM5uPXOc7judnIK4RgKScrJT2P\nekyEJnXyFAZGS3WTFG7fzeXn/cNNx5MCZE2Yay7LqqON8Kg08IvvesiTushrDlMJ\nX8cunSyz2wKBgDIOwZigxq/QNNSs4AHMrpfU8GD5IqKUtde1d3oZ94AMaCAIhqW3\nRR04qS4X+MQjOnP/JxWJR7YXVvpGe8FndzxmHfM2Tqyw8UYrT3RbCVeQsDuRfjmK\nkkhkVhMWU8Co6X4S9xJhqOIglLN97ESBZkaY4Ns4FJGUvsnvqzvIJofLAoGBAKJO\ny2eb0TK/46ozJEELxNOo30efVgGJmpa844e0A1yffDl/2MCT1ve+JpDEcAbi+OeH\nkieRTe6Vk27LvnEHhAT4J6cUX73NSb7sK+x+SGsyGmOS+qEC62M8gdxWRqtXyHX/\nwTG3P1rK1sfcxQy4K57NSrVmxbzijjvN6HdKGS0XAoGATtsid5pypcZ0BsYUp/27\neS6z++ewo7QCVCBPa4Ag4nX56/0kdrECvy/ISMDjggNv+mR8hpyCjfm9ztJ88njB\nUBu1jzLBZ+u5gEjmtu43qvuDJNobyb+evDSReEJmify943vFZqnkIhFlwg1PcS6S\nCd+pr559KWURPIgfxb7S/JU=\n-----END PRIVATE KEY-----\n", + "client_email": "firebase-adminsdk-gzzkw@push-notification-enrollment.iam.gserviceaccount.com", + "client_id": "109128197176743587316", + "auth_uri": "https://accounts.google.com/o/oauth2/auth", + "token_uri": "https://oauth2.googleapis.com/token", + "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", + "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-gzzkw%40push-notification-enrollment.iam.gserviceaccount.com", + "universe_domain": "googleapis.com" +} diff --git a/app/Controllers/EmployeeRestController.php b/app/Controllers/EmployeeRestController.php index 95e93d2e..3851457e 100644 --- a/app/Controllers/EmployeeRestController.php +++ b/app/Controllers/EmployeeRestController.php @@ -42,6 +42,11 @@ use Illuminate\Http\Request; use App\Controllers\EmployeeServiceController; +use Kreait\Firebase\Factory; +use Kreait\Firebase\Messaging\CloudMessage; +use Kreait\Firebase\Messaging\Notification; +use Kreait\Firebase\Exception\MessagingException; + class EmployeeRestController extends AdminController { @@ -2237,7 +2242,7 @@ class EmployeeRestController extends AdminController "waiverofpreexistingdiseases" => "Waiver of Pre-existing Diseases", "maternitycoverage" => "Maternity Coverage", "babyday1cover" => "Baby Day 1 Cover", - "9monthwaitingperiodwaived" => "9-month waiting Period –waived", + "9monthwaitingperiodwaived" => "9-month waiting Period �waived", "coverfromthedateofjoining" => "Cover from the date of Joining", "waiverof1,2,3&4thyearexclusions" => "Waiver of 1, 2, 3 & 4th year Exclusions", "waiverof30dayswaitingperiod" => "Waiver of 30 days waiting period", @@ -2376,6 +2381,37 @@ class EmployeeRestController extends AdminController // return $this->respond(['status' => 'failed', 'code' => 500, 'message' => 'An error occurred', 'error' => $th->getMessage()], 500); // } } + + + + + + public function sendPushNotification() + { + $deviceToken = 'ffvc39yhRk-J-vGE9luw6l:APA91bFgNv7lzvA3lGuJ_pMDHdZ_rey6SMg11P2DvJk-WWiBs0nXWCF0lo5nEka3dn3DeTCS5yx0WrHs1yKj5faitBQYKeKxLg2VpUkDcmk3FrTDGkZdHcnW1Go0G0K8dYAkajRIjSEJ'; + $title = 'Nhance'; + $body = 'All your policy enrolled successfully ..!'; + + // Initialize Firebase with the service account + $firebase = (new Factory) + ->withServiceAccount(APPPATH . 'Config/google-services.json') + ->createMessaging(); + + $notification = Notification::create($title, $body); + $message = CloudMessage::withTarget('token', $deviceToken) + ->withNotification($notification); + + try { + $firebase->send($message); + return $this->response->setJSON(['status' => 'success']); + } catch (MessagingException $e) { + return $this->response->setJSON(['status' => 'error', 'message' => $e->getMessage()]); + } + } + + + + } \ No newline at end of file diff --git a/composer.json b/composer.json index 9f2ec667..da1c83ff 100644 --- a/composer.json +++ b/composer.json @@ -23,7 +23,9 @@ "phpoffice/phpspreadsheet": "^2.1", "psr/log": "^1.1", "slim/slim": "^4.13", - "zircote/swagger-php": "^4.8" + "zircote/swagger-php": "^4.8", + "psr/http-message": "^1.0", + "kreait/firebase-php":"^7.0" }, "require-dev": { "codeigniter/coding-standard": "^1.7", From c90b57ce9130cfd72cfee409c5fb627d23c47b40 Mon Sep 17 00:00:00 2001 From: "venkatesh.r" Date: Tue, 23 Jul 2024 11:11:35 +0530 Subject: [PATCH 07/19] CHANGE_RACK_RATE_FLOW_AND_UI_CHANGE_IMPORT_EXPORT_FLOW_AND_OTHERS : RV --- app/Config/Routes.php | 4 + app/Controllers/ClientController.php | 541 ++- app/Controllers/EmpDataServiceController.php | 853 ++++- app/Controllers/EmployeeController.php | 321 +- app/Controllers/EmployeeServiceController.php | 6 +- app/Controllers/MasterController.php | 99 +- app/Controllers/PendingActionsController.php | 26 +- app/Helpers/excel_import_export_helper.php | 2 +- app/Models/CDMasterModel.php | 41 +- app/Models/ClientBranchModel.php | 1 + app/Models/ClientModel.php | 4 +- app/Models/ClientPolicyModel.php | 65 +- app/Models/EmployeePolicyModel.php | 194 +- .../InsurerExcelExportTemplateModel.php | 23 + app/Models/InsurerModel.php | 4 +- app/Models/PolicyPremium1Model.php | 3 + app/Models/PolicyPremium2Model.php | 2 + app/Models/PolicyTypeModel.php | 1 + app/Views/batch_list.php | 3 +- app/Views/cd_master_list.php | 4 +- app/Views/client_branch.php | 224 +- app/Views/client_policy.php | 421 +-- app/Views/employee_data_list.php | 3 +- app/Views/employee_list.php | 3 +- app/Views/employee_upload.php | 16 +- app/Views/endorsement_list.php | 6 +- app/Views/file_list.php | 3 +- app/Views/insurer_or_tpa_data.php | 85 +- app/Views/layout/footer.php | 707 ++-- app/Views/policy_gmc_terms.php | 2 +- app/Views/policy_gpa_terms.php | 2 +- app/Views/policy_grid.php | 3123 +++++++++-------- app/Views/policy_grid_excel.php | 268 +- app/Views/policy_type_basic_info.php | 6 + app/Views/policy_type_list.php | 2 + app/Views/policy_type_onboarding.php | 4 +- app/Views/view_deposit.php | 16 +- writable/logs/.gitkeep | 11 - 38 files changed, 4338 insertions(+), 2761 deletions(-) create mode 100644 app/Models/InsurerExcelExportTemplateModel.php delete mode 100644 writable/logs/.gitkeep diff --git a/app/Config/Routes.php b/app/Config/Routes.php index 77cf4c62..acb2757f 100644 --- a/app/Config/Routes.php +++ b/app/Config/Routes.php @@ -14,6 +14,8 @@ $routes->get('/swagger', 'SwaggerController::index', ['filter' => 'authMVC']); $routes->get("reminder_mail", "NotificationController::reminder_mail"); $routes->get("testing", "ClientController::Testing"); $routes->get("update-policy-terms-for-corrections", "ClientController::updatePolicyTermsForCorrections"); +$routes->get("update_rack_rate_json", "ClientController::updateRackRateJson"); +$routes->get("updatajson", "EmpDataServiceController::updatajson"); $routes->post("add_advertise_image", "AppContentManagementController::add_advertise_image"); @@ -260,6 +262,8 @@ $routes->group("/util", ["filter" => "authMVC"], function ($routes) { $routes->get("getPolicyTermsFormJson/(:any)", "ClientController::getPolicyTermsFormJson/$1"); $routes->get("checkHRNumber/(:any)", "ClientController::checkHRNumber/$1"); $routes->get("check_addition_premium_JSON/(:any)", "ClientController::checkAdditionPremiumJSON/$1"); + $routes->get("get_policy_type_for_base_policy/(:any)", "ClientController::getPolicyTypeForBasePolicy/$1"); + $routes->get("get_client_details/(:any)", "ClientController::getClientDetails/$1"); }); $routes->cli('cli/processjob', 'JobWorker::processJob'); diff --git a/app/Controllers/ClientController.php b/app/Controllers/ClientController.php index e7e80b36..788a31ca 100644 --- a/app/Controllers/ClientController.php +++ b/app/Controllers/ClientController.php @@ -172,8 +172,8 @@ class ClientController extends AdminController } - - public function updatePolicyTermsForCorrections(){ + public function updatePolicyTermsForCorrections() + { $results = $this->clientPolicyModel ->select('id, policy_terms') @@ -240,7 +240,6 @@ class ClientController extends AdminController } } - public function removeClientBranch($id = null) { $this->myLogger->logme('error','Client Branch Remove function called'); @@ -269,6 +268,7 @@ class ClientController extends AdminController $data['state'] = $this->stateModel->getAllStates(); $data['RM'] = $this->userModel->findAll(); $data['policyGridData'] = $this->policyGridModel->findAll(); + $data['policy_types'] = $this->policyTypeModel->findAll(); $data['policy_type'] = ['1'=>'Base Policy', '2' => 'SI Topup', '3' => 'Dependent Addon']; // echo "
";
@@ -318,6 +318,7 @@ class ClientController extends AdminController
             4 => 'Debit',
             5 => 'Non EB',
             6 => 'Refund By Insurer',
+            7 => 'Opening Amount',
         ];
 
         $data['subTypeOptions'] = $subTypeOptions;
@@ -330,6 +331,7 @@ class ClientController extends AdminController
         $data['clientData'] = $this->clientPolicyModel->getClientById($clientId);
         $data['deposiamount'] = $this->clientPolicyModel->getDepositSummary($clientId, $insurerId);  
         
+        // dd($data['depositdata']);
         
         // print_r($data['depositdata'] );die;
         // Load the view for the new list page
@@ -338,7 +340,6 @@ class ClientController extends AdminController
         echo view('layout/footer');
     }
 
-
     public function saveDeposit()
     {
         // Retrieve form data from POST request
@@ -375,7 +376,6 @@ class ClientController extends AdminController
         return $this->response->setJSON(['success' => $response['success']]);
     }
 
-
     public function editClientOnboarding($id = null)
     {    
 
@@ -390,8 +390,10 @@ class ClientController extends AdminController
         $editData['insurer']        = $this->insurerBranchModel ->getInsurerBranchesWithInsurerNames();
         $editData['kyc_docs']       = $this->kycDocsModel->findAll();
         $editData['policyGridData'] = $this->policyGridModel->findAll();
+        $editData['policy_types'] = $this->policyTypeModel->findAll();
         $editData['policy_type'] = ['1'=>'Base Policy', '2' => 'SI Topup', '3' => 'Dependent Addon'];
 
+        // dd($editData['policy_types']);
 
         $editData['client']           = $this->clientModel->where(['id' => $id])->first();
         $editData['client_kyc']       = $this->clientKYCDocsModel->where('client_id', $id)->findAll();
@@ -720,9 +722,11 @@ class ClientController extends AdminController
 
         $this->myLogger->logme('error','Client policy CREATE function called');
 
-        $policy_type_id = $this->request->getPost('policy_type_id');
+        $policy_type_id   = $this->request->getPost('policy_type_id');
         $client_branch_id = $this->request->getPost('client_branch_id');
-        $client_id = $this->request->getPost('client_id');
+        $client_id        = $this->request->getPost('client_id');
+        $policy_type_id   = $this->request->getPost('policy_type_id');
+        $base_policy      = $this->request->getPost('base_policy');
 
 
         $insurerValue                      = (string) $this->request->getPost('insurer');
@@ -745,7 +749,7 @@ class ClientController extends AdminController
         $data['client_id']         = $client_id;
         $data['tpa_branch_id']     = $tpaBranchId;
         $data['tpa_id']            = $tpaId;
-        $data['policy_id']         = $this->request->getPost('policy_id');
+        // $data['policy_id']         = $this->request->getPost('policy_id');
         $data['policy_type_id']    = $this->request->getPost('policy_type_id');
 
         $data['no_of_lives']                        = $this->request->getPost('no_of_lives');
@@ -759,17 +763,30 @@ class ClientController extends AdminController
         $data['claims_experience_for_last_3_years'] = $this->request->getPost('claims_experience_for_last_3_years');
         $data['earned_premium_amount']              = $this->request->getPost('earned_premium_amount');
         $data['claims_incurred_amount']             = $this->request->getPost('claims_incurred_amount');
-        $data['is_addon']                           = $this->request->getPost('is_addon');
-        $data['base_policy']                        = $this->request->getPost('base_policy');
+        $data['base_policy']                        = ($this->request->getPost('base_policy') === '' || $this->request->getPost('base_policy') == 0) ? null : $this->request->getPost('base_policy');
         $data['policy_status']                      = 1;
         $data['inception_type']                     = $this->request->getPost('inception_type') ? 2 : 1;
         $data['client_branch_id']                   = $this->request->getPost('client_branch_id');
         $data['cd_ac_no']                           = $this->request->getPost('cd_ac_no');
         $data['gst']                                = $this->request->getPost('gst');
+        
+        if($policy_type_id == 1 || $policy_type_id == 2 || $policy_type_id == 6 || $policy_type_id == 7){
 
+            $data['is_addon'] = 1;
 
+        }else if($policy_type_id == 4 || $policy_type_id == 5){
 
+            $data['is_addon'] = 2;
 
+        }else if($policy_type_id == 3){
+           
+            if($base_policy){
+                $data['is_addon'] = 3;
+            }else{
+                $data['is_addon'] = 1;
+            }
+        }
+                    
         $policy_terms =  $this->clientPolicyModel->where('id', $this->request->getPost('base_policy'))->first();
 
         // if ($this->request->getPost('is_addon') == 2 || $this->request->getPost('is_addon') == 3) {
@@ -804,12 +821,7 @@ class ClientController extends AdminController
         $insert = $this->clientPolicyModel->insert($data);
         if($insert){
             $clientPoliceData =  $this->clientPolicyModel->getClientPolicyByClientId($this->request->getPost('client_id'));
-            // foreach ($clientPoliceData as $key => $value) {
-            
-            //     $clientPoliceData[$key]->policy_start_date = date('d-M-Y', strtotime($value->policy_start_date));
-            //     $clientPoliceData[$key]->policy_end_date = date('d-M-Y', strtotime($value->policy_end_date));
-            // }
-            return $this->respond(['status' => true,'code' => 200,'data' => $clientPoliceData, 'method' => 'CERATE'], 200);
+            return $this->respond(['status' => true,'code' => 200,'data' => $clientPoliceData, 'method' => 'CERATE', 'post_data' => $data], 200);
         }else{
             return $this->respond(['status' => false,'code' => 404, 'message' => 'no data found'], 200);
         }
@@ -823,8 +835,7 @@ class ClientController extends AdminController
 
         $id        = $this->request->getPost('PrimaryKey');
         $client_id = $this->request->getPost('client_id');
-
-
+        $policy_type_id = $this->request->getPost('policy_type_id');
 
         $insurerValue                      = (string) $this->request->getPost('insurer');
         list($insurerBranchId, $insurerId) = explode('-', $insurerValue);
@@ -838,7 +849,6 @@ class ClientController extends AdminController
         $data['tpa_branch_id']     = $tpaBranchId;
         $data['client_id']         = $client_id;
         $data['tpa_id']            = $tpaId;
-        $data['policy_id']         = $this->request->getPost('policy_id');
         $data['policy_type_id']    = $this->request->getPost('policy_type_id');
         $data['policy_no'] = $this->request->getPost('policy_no');
         $data['policy_start_date'] = change_date_format($this->request->getPost('policy_start_date'), 'd-m-Y', 'Y-m-d');
@@ -856,14 +866,28 @@ class ClientController extends AdminController
         $data['claims_experience_for_last_3_years'] = $this->request->getPost('claims_experience_for_last_3_years');
         $data['earned_premium_amount']              = $this->request->getPost('earned_premium_amount');
         $data['claims_incurred_amount']             = $this->request->getPost('claims_incurred_amount');
-        $data['is_addon']                           = $this->request->getPost('is_addon');
-        $data['base_policy']                        = $this->request->getPost('base_policy');
+        $data['base_policy']                        = ($this->request->getPost('base_policy') === '' || $this->request->getPost('base_policy') == 0) ? null : $this->request->getPost('base_policy');
         $data['policy_status']                      = 1;
         $data['inception_type']                     = $this->request->getPost('inception_type') ? 2 : 1;
+        $data['enrolment_visibility']               = $this->request->getPost('enrolment_visibility') ? 1 : 0;
         $data['client_branch_id']                   = $this->request->getPost('client_branch_id');
         $data['cd_ac_no']                           = $this->request->getPost('cd_ac_no');
         $data['gst']                                = $this->request->getPost('gst');
 
+        if($policy_type_id == 1 || $policy_type_id == 2 || $policy_type_id == 3 || $policy_type_id == 6 || $policy_type_id == 7){
+
+            $data['is_addon'] = 1;
+
+        }else if($policy_type_id == 4){
+
+            $data['is_addon'] = 2;
+
+        }else if($policy_type_id == 5){
+
+            $data['is_addon'] = 3;
+        }
+          
+
         
         $policy_terms =  $this->clientPolicyModel->where('id', $this->request->getPost('base_policy'))->first();
 
@@ -916,40 +940,43 @@ class ClientController extends AdminController
         // echo json_encode(['key' => $this->request->getPost()]); die;
 
         try {
-            $policy_type = $this->request->getPost('policy_type');
             $client_id = $this->request->getPost('client_id');
             $client_policy_id = $this->request->getPost('client_policy_id');
+            $record    = $this->clientPolicyModel->where('client_policy.id', $client_policy_id)->first();
             $premium_type = $this->request->getPost('premium_type');
             if (!empty($client_id) && $client_id != null) {
                 $client_policy_data = $this->clientPolicyModel->where('id', $client_policy_id)->first();
                 $client_id =  $client_policy_data['client_id'];
             }
+            $branch_units = $this->getBranchUnitsByBranchId($record['client_branch_id']);
+            $branch_units = json_decode($branch_units);
+
+
             $policy_grid_id = $this->request->getPost('policy_grid_id');
-            $rack_rate_type = $this->request->getPost('rack_rate_type');
+            $rack_rate_name = $this->request->getPost('rack_rate_name');
 
-            $self = $this->request->getPost('self') ? 1 : 0;
-            $spouse = $this->request->getPost('spouse')? 1 : 0;
-            $childrens = $this->request->getPost('childrens')? 1 : 0;
-            $parents = $this->request->getPost('parents')? 1 : 0;
-            $parents_in_law = $this->request->getPost('parents-in-law')? 1 : 0;
-            $either_parents_pil = $this->request->getPost('either-parents-pil')? 1 : 0;
+            $self               = $this->request->getPost('self') ? 1 : 0;
+            $spouse             = $this->request->getPost('spouse');
+            $childrens          = $this->request->getPost('childrens');
+            $parents            = $this->request->getPost('parents');
+            $parents_in_law     = $this->request->getPost('parents-in-law');
 
-            $relation_data['self'] = $self;
-            $relation_data['spouse'] = $spouse;
-            $relation_data['childrens'] = $childrens;
-            $relation_data['parents'] = $parents;
-            $relation_data['parents-in-law'] = $parents_in_law;
-            $relation_data['either-parents-pil'] = $either_parents_pil;
+            if($policy_grid_id == 1 || $policy_grid_id == 2){
+                $self               =  1;
+                $spouse             = 'NA';
+                $childrens          = 'NA';
+                $parents            = 'NA';
+                $parents_in_law     = 'NA';    
+            }
 
+            $relation_data['self']               = $self;
+            $relation_data['spouse']             = $spouse;
+            $relation_data['childrens']          = $childrens;
+            $relation_data['parents']            = $parents;
+            $relation_data['parents-in-law']     = $parents_in_law;
 
             $jsonDataForRelation = json_encode($relation_data);
 
-            // if($policy_grid_id == 10 || $policy_grid_id == 11){
-            //     $premium_type = 1;
-            // }else{
-            //     $premium_type = 2;
-            // }
-
             $si_or_bp = $this->request->getPost('si_or_bp');
             $basic_multiplier = str_replace(',', '', $this->request->getPost('basic_multiplier'));
             $premium_multiplier = str_replace(',', '', $this->request->getPost('premium_multiplier'));
@@ -961,36 +988,36 @@ class ClientController extends AdminController
             $data['client_policy_id'] = $client_policy_id;
             $data['policy_grid_id'] = $policy_grid_id;
             $data['premium_type'] = $premium_type;
-            $data['rack_rate_type'] = $rack_rate_type;
-
-            if($rack_rate_type == 1){
-                $data['additional_relationship'] = $jsonDataForRelation;
-            }
-
+            $data['rack_rate_name'] = $rack_rate_name;
+            $data['additional_relationship'] = $jsonDataForRelation;
 
             $premium = [];
 
             if ($policy_grid_id == '1' || $policy_grid_id == '2') {
                 $this->policyPremium1Model->where('client_id', $client_id)->where('client_policy_id', $client_policy_id)->set('is_active', 0)->update();
             } else {
-                $this->policyPremium2Model->where('client_id', $client_id)->where('client_policy_id', $client_policy_id)->where('rack_rate_type', $rack_rate_type)->set('is_active', 0)->update();
+                $this->policyPremium2Model->where('client_id', $client_id)->where('client_policy_id', $client_policy_id)->where('rack_rate_name', $rack_rate_name)->set('is_active', 0)->update();
             }
 
-
             if ($policy_grid_id == '1') {
 
-
                 if ($si_or_bp == '1') {
 
                     $premium = str_replace(',', '', $this->request->getPost('gpa_sum_premium[]'));
                     $sum_insure = str_replace(',', '', $this->request->getPost('gpa_sum_si[]'));
                     $multiplier = $this->request->getPost('gpa_sum_multiplier');
+                    $unit = $this->request->getPost('gpa_unit[]');
 
                     for ($i = 0; $i < count($premium); $i++) {
                         $data['si'] = $sum_insure[$i];
                         $data['premium'] = $premium[$i];
                         $data['multiplier'] = $multiplier;
                         $data['si_or_bp'] = $this->request->getPost('si_or_bp');
+                        if (empty($unit) || !isset($unit[$i]) || empty($unit[$i])) {
+                            $data['unit'] = $branch_units[0];
+                        } else {
+                            $data['unit'] = $unit[$i];
+                        }
 
                         $policyPremium = $this->policyPremium1Model->insert($data);
                     }
@@ -1001,6 +1028,8 @@ class ClientController extends AdminController
                     $sum_insure = str_replace(',', '', $this->request->getPost('gpa_sum_si2[]'));
                     $multiplier = $this->request->getPost('gpa_sum_multiplier2');
                     $grade = $this->request->getPost('gpa_band[]');
+                    $unit = $this->request->getPost('gpa_unit[]');
+
 
                     for ($i = 0; $i < count($premium); $i++) {
                         $data['si'] = $sum_insure[$i];
@@ -1008,6 +1037,11 @@ class ClientController extends AdminController
                         $data['grade'] = $grade[$i];
                         $data['multiplier'] = $multiplier;
                         $data['si_or_bp'] = $this->request->getPost('si_or_bp');
+                        if (empty($unit) || !isset($unit[$i]) || empty($unit[$i])) {
+                            $data['unit'] = $branch_units[0];
+                        } else {
+                            $data['unit'] = $unit[$i];
+                        }
 
                         $policyPremium = $this->policyPremium1Model->insert($data);
                     }
@@ -1017,6 +1051,8 @@ class ClientController extends AdminController
                     $premium = str_replace(',', '', $this->request->getPost('gpa_basic_premium[]'));
                     $sum_insure = str_replace(',', '', $this->request->getPost('gpa_basic_si[]'));
                     $basic_pay = str_replace(',', '', $this->request->getPost('basic_pay[]'));
+                    $unit = $this->request->getPost('gpa_unit[]');
+
 
                     for ($i = 0; $i < count($premium); $i++) {
 
@@ -1026,6 +1062,11 @@ class ClientController extends AdminController
                         $data['basic_pay'] = $basic_pay[$i];
                         $data['si'] = $sum_insure[$i];
                         $data['premium'] = $premium[$i];
+                        if (empty($unit) || !isset($unit[$i]) || empty($unit[$i])) {
+                            $data['unit'] = $branch_units[0];
+                        } else {
+                            $data['unit'] = $unit[$i];
+                        }
 
                         $policyPremium = $this->policyPremium1Model->insert($data);
                     }
@@ -1047,33 +1088,55 @@ class ClientController extends AdminController
             } else if ($policy_grid_id == '2') {
                 $data['premium'] = str_replace(',', '', $this->request->getPost('gpa_premium'));
                 $data['si'] = str_replace(',', '', $this->request->getPost('gpa_si'));
+                $unit = $this->request->getPost('gpa_unit');
+                if (empty($unit)) {
+                    $data['unit'] = $branch_units[0];
+                } else {
+                    $data['unit'] = $unit;
+                }
 
                 $policyPremium = $this->policyPremium1Model->insert($data);
 
                 $data = $this->request->getPost();
                 $insert = true;
             } else if ($policy_grid_id == '3') {
+
                 $premium = $this->request->getPost('3_premium[]');
                 $sum_insure = $this->request->getPost('3_si[]');
+                $unit = $this->request->getPost('3_unit[]');
+                
                 for ($i = 0; $i < count($premium); $i++) {
                     $data['premium'] = str_replace(',', '', $premium[$i]);
                     $data['si'] = str_replace(',', '', $sum_insure[$i]);
+                    if (empty($unit) || !isset($unit[$i]) || empty($unit[$i])) {
+                        $data['unit'] = $branch_units[0];
+                    } else {
+                        $data['unit'] = $unit[$i];
+                    }
                     $dataa = $this->policyPremium2Model->insert($data);
                 }
                 $data = $this->request->getPost();
                 $insert = true;
-            } else if ($policy_grid_id == '4') {
 
+            } else if ($policy_grid_id == '4') {
 
                 $premium = $this->request->getPost('4_premium[]');
                 $sum_insure = $this->request->getPost('4_si');
                 $age_from = $this->request->getPost('4_age_from[]');
                 $age_to = $this->request->getPost('4_age_to[]');
+                $unit = $this->request->getPost('4_unit[]');
+
                 for ($i = 0; $i < count($premium); $i++) {
                     $data['premium'] = str_replace(',', '', $premium[$i]);
                     $data['si'] = str_replace(',', '', $sum_insure);
                     $data['age_from'] = $age_from[$i];
                     $data['age_to'] = $age_to[$i];
+                    if (empty($unit) || !isset($unit[$i]) || empty($unit[$i])) {
+                        $data['unit'] = $branch_units[0];
+                    } else {
+                        $data['unit'] = $unit[$i];
+                    }
+
                     $dataa = $this->policyPremium2Model->insert($data);
                 }
                 $data = $this->request->getPost();
@@ -1085,30 +1148,42 @@ class ClientController extends AdminController
                 $sum_insure = $this->request->getPost('5_si[]');
                 $age_from = $this->request->getPost('5_age_from[]');
                 $age_to = $this->request->getPost('5_age_to[]');
+                $unit = $this->request->getPost('5_unit[]');
+
                 for ($i = 0; $i < count($premium); $i++) {
                     $data['premium'] = str_replace(',', '', $premium[$i]);
                     $data['si'] = str_replace(',', '', $sum_insure[$i]);
                     $data['age_from'] = $age_from[$i];
                     $data['age_to'] = $age_to[$i];
+                    if (empty($unit) || !isset($unit[$i]) || empty($unit[$i])) {
+                        $data['unit'] = $branch_units[0];
+                    } else {
+                        $data['unit'] = $unit[$i];
+                    }
+
                     $dataa = $this->policyPremium2Model->insert($data);
                 }
                 $data = $this->request->getPost();
                 $insert = true;
             } else if ($policy_grid_id == '6') {
 
-
                 $premium = $this->request->getPost('6_premium[]');
-
-                print_r($premium);
-
                 $sum_insure = $this->request->getPost('6_si');
                 $age_from = $this->request->getPost('6_age_from[]');
                 $age_to = $this->request->getPost('6_age_to[]');
+                $unit = $this->request->getPost('6_unit[]');
+
                 for ($i = 0; $i < count($premium); $i++) {
                     $data['premium'] = str_replace(',', '', $premium[$i]);
                     $data['si'] = str_replace(',', '', $sum_insure);
                     $data['age_from'] = $age_from[$i];
                     $data['age_to'] = $age_to[$i];
+                    if (empty($unit) || !isset($unit[$i]) || empty($unit[$i])) {
+                        $data['unit'] = $branch_units[0];
+                    } else {
+                        $data['unit'] = $unit[$i];
+                    }
+                    
                     $dataa = $this->policyPremium2Model->insert($data);
                 }
                 $data = $this->request->getPost();
@@ -1120,11 +1195,19 @@ class ClientController extends AdminController
                 $sum_insure = $this->request->getPost('7_si[]');
                 $age_from = $this->request->getPost('7_age_from[]');
                 $age_to = $this->request->getPost('7_age_to[]');
+                $unit = $this->request->getPost('7_unit[]');
+
                 for ($i = 0; $i < count($premium); $i++) {
                     $data['premium'] = str_replace(',', '', $premium[$i]);
                     $data['si'] = str_replace(',', '', $sum_insure[$i]);
                     $data['age_from'] = $age_from[$i];
                     $data['age_to'] = $age_to[$i];
+                    if (empty($unit) || !isset($unit[$i]) || empty($unit[$i])) {
+                        $data['unit'] = $branch_units[0];
+                    } else {
+                        $data['unit'] = $unit[$i];
+                    }
+
                     $dataa = $this->policyPremium2Model->insert($data);
                 }
                 $data = $this->request->getPost();
@@ -1133,10 +1216,18 @@ class ClientController extends AdminController
                 $premium = $this->request->getPost('8_premium[]');
                 $sum_insure = $this->request->getPost('8_si[]');
                 $grade = $this->request->getPost('8_grade[]');
+                $unit = $this->request->getPost('8_unit[]');
+
                 for ($i = 0; $i < count($premium); $i++) {
                     $data['premium'] = str_replace(',', '', $premium[$i]);
                     $data['si'] = str_replace(',', '', $sum_insure[$i]);
                     $data['grade'] = $grade[$i];
+                    if (empty($unit) || !isset($unit[$i]) || empty($unit[$i])) {
+                        $data['unit'] = $branch_units[0];
+                    } else {
+                        $data['unit'] = $unit[$i];
+                    }
+
                     $dataa = $this->policyPremium2Model->insert($data);
                 }
                 $data = $this->request->getPost();
@@ -1145,6 +1236,12 @@ class ClientController extends AdminController
 
                 $data['premium'] = str_replace(',', '', $this->request->getPost('gpa_premium'));
                 $data['si'] = str_replace(',', '', $this->request->getPost('gpa_si'));
+                $unit = $this->request->getPost('gpa_unit');
+                if (empty($unit)) {
+                    $data['unit'] = $branch_units[0];
+                } else {
+                    $data['unit'] = $unit;
+                }
 
                 $policyPremium = $this->policyPremium2Model->insert($data);
                 // $premium = $this->request->getPost('9_premium[]');
@@ -1163,11 +1260,20 @@ class ClientController extends AdminController
                 $sum_insure = $this->request->getPost('10_si[]');
                 $age_from = $this->request->getPost('10_age_from[]');
                 $age_to = $this->request->getPost('10_age_to[]');
+                $unit = $this->request->getPost('10_unit[]');
+
                 for ($i = 0; $i < count($premium); $i++) {
                     $data['premium'] = str_replace(',', '', $premium[$i]);
                     $data['si'] = str_replace(',', '', $sum_insure[$i]);
                     $data['age_from'] = $age_from[$i];
                     $data['age_to'] = $age_to[$i];
+                    if (empty($unit) || !isset($unit[$i]) || empty($unit[$i])) {
+                        $data['unit'] = $branch_units[0];
+                    } else {
+                        $data['unit'] = $unit[$i];
+                    }
+
+
                     $policyPremium = $this->policyPremium2Model->insert($data);
                 }
                 $data = $this->request->getPost();
@@ -1178,11 +1284,19 @@ class ClientController extends AdminController
                 $sum_insure = $this->request->getPost('11_si[]');
                 $grade = $this->request->getPost('11_grade[]');
                 $max_sum_insure = $this->request->getPost('11_max_si[]');
+                $unit = $this->request->getPost('11_max_si[]');
+
                 for ($i = 0; $i < count($premium); $i++) {
                     $data['premium'] = str_replace(',', '', $premium[$i]);
                     $data['si'] = str_replace(',', '', $sum_insure[$i]);
                     $data['grade'] = $grade[$i];
                     $data['max_si'] = str_replace(',', '', $max_sum_insure[$i]);
+                    if (empty($unit) || !isset($unit[$i]) || empty($unit[$i])) {
+                        $data['unit'] = $branch_units[0];
+                    } else {
+                        $data['unit'] = $unit[$i];
+                    }
+
                     $dataa = $this->policyPremium2Model->insert($data);
                 }
                 $data = $this->request->getPost();
@@ -1192,10 +1306,17 @@ class ClientController extends AdminController
                 $premium = $this->request->getPost('12_premium[]');
                 $sum_insure = $this->request->getPost('12_si[]');
                 $relationship = $this->request->getPost('12_relationship[]');
+                $unit = $this->request->getPost('12_unit[]');
+
                 for ($i = 0; $i < count($premium); $i++) {
                     $data['premium'] = str_replace(',', '', $premium[$i]);
                     $data['si'] = str_replace(',', '', $sum_insure[$i]);
                     $data['relationship'] = $relationship[$i];
+                    if (empty($unit) || !isset($unit[$i]) || empty($unit[$i])) {
+                        $data['unit'] = $branch_units[0];
+                    } else {
+                        $data['unit'] = $unit[$i];
+                    }
 
                     $dataa = $this->policyPremium2Model->insert($data);
                 }
@@ -1208,6 +1329,7 @@ class ClientController extends AdminController
                 $age_from = $this->request->getPost('13_age_from[]');
                 $age_to = $this->request->getPost('13_age_to[]');
                 $relationship = $this->request->getPost('13_relationship[]');
+                $unit = $this->request->getPost('13_unit[]');
 
                 for ($i = 0; $i < count($premium); $i++) {
                     $data['premium'] = str_replace(',', '', $premium[$i]);
@@ -1215,6 +1337,11 @@ class ClientController extends AdminController
                     $data['age_from'] = $age_from[$i];
                     $data['age_to'] = $age_to[$i];
                     $data['relationship'] = $relationship[$i];
+                    if (empty($unit) || !isset($unit[$i]) || empty($unit[$i])) {
+                        $data['unit'] = $branch_units[0];
+                    } else {
+                        $data['unit'] = $unit[$i];
+                    }
 
                     $dataa = $this->policyPremium2Model->insert($data);
                 }
@@ -1223,18 +1350,23 @@ class ClientController extends AdminController
             }
 
             if ($insert) {
-                return $this->respond(['status' => true, 'code' => 200, 'data' => $data], 200);
+                return $this->respond(['status' => true, 'code' => 200, 'data' => $data, 'rack_rate_json'=>$jsonDataForRelation,], 200);
             } else {
                 return $this->respond(['status' => false, 'code' => 404, 'data' => $data, 'message' => 'no data found'], 200);
             }
+
         } catch (\Exception $e) {
-            // Handle exceptions here
             echo 'Error: ' . $e->getMessage();
         }
     }
 
 
 
+
+
+
+
+    
     public function getKycDocsById($id=null)
     {
 
@@ -1286,20 +1418,23 @@ class ClientController extends AdminController
             $insurer_id = $client_policy_data['insurer_id'];
             $client_id = $client_policy_data['client_id'];
             
-            $base_policy_policy_type_id = 0;
-            if($client_policy_data['base_policy'] != null){
-                $base_policy_policy_type_id = $this->clientPolicyModel->select('policy_type_id')->where(['id' => $client_policy_data['base_policy'], 'is_active' => 1])->first();
-            }
-
             $polices = $this->policesModel
                 ->select('policies.*, policy_type.policy_type') 
                 ->join('policy_type', 'policy_type.id = policies.policy_type_id')
                 ->where(['policies.insurer_id' => $insurer_id, 'policies.is_active' => 1])
                 ->findAll();
-            $client_policy_list = $this->clientPolicyModel->getpolicyWithPattern( $client_id );
+            $client_policy_list = $this->clientPolicyModel->getPolicyTypeForPolicyBinding($client_id);
             $cd_data = $this->CDMasterModel->where('client_id', $client_id)->where('insurer_id', $insurer_id)->findAll();
                                    
-            return $this->respond(['status' => true,'code' => 200, 'client_policy_list' => $client_policy_list, 'data' => $client_policy_data, 'cd_data' => $cd_data, "insurer_id" => $client_policy_data['insurer_id'], 'policy' => $polices, 'base_policy_type_id' => $base_policy_policy_type_id['policy_type_id']], 200);
+            return $this->respond([
+                'status' => true,
+                'code' => 200, 
+                'data' => $client_policy_data, 
+                'cd_data' => $cd_data, 
+                "insurer_id" => $client_policy_data['insurer_id'], 
+                'policy' => $polices, 
+                'client_policy_list' =>  $client_policy_list
+            ], 200);
         }else{
             return $this->respond(['status' => false,'code' => 404, 'message' => 'no data found'], 200);
         }
@@ -1310,7 +1445,13 @@ class ClientController extends AdminController
     {
 
         $client_policy_id = $this->request->getGet('client_policy_id');
-        $record    = $this->clientPolicyModel->where('id', $client_policy_id)->first();
+        $terms_si_amount_array = $this->getPolicyTerms($client_policy_id);
+
+        $record    = $this->clientPolicyModel
+                        ->select('client_policy.*, policy_type.policy_type')
+                        ->join('policy_type', 'policy_type.id = client_policy.policy_type_id')
+                        ->where('client_policy.id', $client_policy_id)
+                        ->first();
         $family_floater = '';
         if (isset(json_decode($record['policy_terms'])->family_floater)) {
             $family_floater = json_decode($record['policy_terms'])->family_floater;
@@ -1322,16 +1463,7 @@ class ClientController extends AdminController
             $self = $policy_terms_data->family_floaters;
         }
 
-        // $emp_count = $this->employeeModel
-        // ->join('client_policy cp', "employees.client_id = cp.client_id")
-        // ->join('employee_polices ep', "cp.id = ep.client_policy_id AND employees.id = ep.employee_id")
-        // ->where("employees.client_id", $record['client_id'])
-        // ->where("employees.emp_status", 'active')
-        // ->where("ep.status", 'active')
-        // ->where("employees.is_active", 1)
-        // ->where("ep.is_active", 1)
-        // ->countAllResults();
-
+        $branch_units = $this->getBranchUnitsByBranchId($record['client_branch_id']);
 
         $emp_count = $this->employeePolicyModel
             ->join('client_policy cp', "cp.id = employee_polices.client_policy_id")
@@ -1340,13 +1472,10 @@ class ClientController extends AdminController
             ->where("employee_polices.is_active", 1)
             ->countAllResults();
 
-
-        $data = $this->policesModel->getPolicyPremium($record['policy_id']);
-        $policy_name = $data[0]->policy_name;
         $gmc_pattern = '/gmc/i';
         $gpa_pattern = '/gpa/i';
-        $subject = $data[0]->policy_type;
-        $policy_type_id = $data[0]->id;
+        $subject = $record['policy_type'];
+        $policy_type_id = $record['policy_type_id'];
 
         if (preg_match($gmc_pattern, $subject)) {
             $search_term = 'GMC';
@@ -1440,14 +1569,47 @@ class ClientController extends AdminController
             // print_r($premium1);
             // print_r($premium2); die;
 
-            return $this->respond(['status' => true, 'code' => 200, 'data' => $resultss, 'premiumData' => json_encode($premiumDataa), 'count' => $emp_count, 'policy_name' => $policy_name, 'family_floater' => $family_floater, 'self' => $self, 'client_policy_id' => $client_policy_id], 200);
+            return $this->respond([
+                'status' => true, 
+                'code' => 200, 
+                'data' => $resultss, 
+                'premiumData' => json_encode($premiumDataa), 
+                'count' => $emp_count,  
+                'family_floater' => $family_floater, 
+                'self' => $self, 
+                'client_policy_id' => $client_policy_id, 
+                'terms_si_amount_array' => $terms_si_amount_array,
+                'branch_units' => $branch_units
+            ], 200);
 
         } else if ($search_term === 'GPA' || $policy_type_id == 6 || $policy_type_id == 7) {
 
-            return $this->respond(['status' => true, 'code' => 200, 'data' => $results, 'premiumData' => json_encode($premiumData), 'count' => $emp_count, 'policy_name' => $policy_name, 'family_floater' => $family_floater, 'self' => $self, 'client_policy_id' => $client_policy_id], 200);
+            return $this->respond([
+                'status' => true, 
+                'code' => 200, 
+                'data' => $results, 
+                'premiumData' => json_encode($premiumData), 
+                'count' => $emp_count, 
+                'family_floater' => $family_floater, 
+                'self' => $self, 
+                'client_policy_id' => $client_policy_id, 
+                'terms_si_amount_array' => $terms_si_amount_array,
+                'branch_units' => $branch_units
+            ], 200);
         } else {
 
-            return $this->respond(['status' => false, 'code' => 200, 'data' => $results, 'premiumData' => json_encode($premiumData), 'count' => $emp_count, 'policy_name' => $policy_name, 'family_floater' => $family_floater, 'self' => $self, 'client_policy_id' => $client_policy_id], 200);
+            return $this->respond([
+                'status' => false, 
+                'code' => 200, 
+                'data' => $results, 
+                'premiumData' => json_encode($premiumData), 
+                'count' => $emp_count,  
+                'family_floater' => $family_floater, 
+                'self' => $self, 
+                'client_policy_id' => $client_policy_id,
+                'terms_si_amount_array' => $terms_si_amount_array,
+                'branch_units' => $branch_units 
+            ], 200);
         }
     }
 
@@ -1657,7 +1819,6 @@ class ClientController extends AdminController
     {
         $client_policy_id = $this->request->getVar('client_policy_id');
         $record    = $this->clientPolicyModel->where('id', $client_policy_id)->first();
-        $policy_name = $this->policesModel->select('name')->where('id', $record['policy_id'])->first();
 
         // $emp_count = $this->employeeModel ->join('client_policy cp',"employees.client_id = cp.client_id")
         //     ->join('employee_polices ep',"cp.id = ep.client_policy_id AND employees.id = ep.employee_id")
@@ -1677,12 +1838,11 @@ class ClientController extends AdminController
                 'Status' => true,
                 'code' => 200,        
                 'data' => $record['policy_terms'],  
-                'policy_name' => $policy_name,
                 'policy_addon' => $record['is_addon'], 
                 'emp_count_by_policy'=>$emp_count_by_policy],
             200);
         } else {
-            return $this->respond(['Status' => false,'code' => 200,'message' => 'Record not found.',  'policy_name' => $policy_name], 200);
+            return $this->respond(['Status' => false,'code' => 200,'message' => 'Record not found.'], 200);
         }
 
     }
@@ -1875,7 +2035,6 @@ class ClientController extends AdminController
         return $this->respond(['status' => true, 'code' => 200, 'message' => $message, 'data' => $termsData, 'racRate' => $racRate, 'open_for_enrollment' => $json_data, 'client_policy_data' => $record], 200);
     }
 
-
     public function getClientPolicyList($client_id = null)
     {
 
@@ -1889,7 +2048,6 @@ class ClientController extends AdminController
 
     }
 
-
     public function fetchPolicyDataForPolicyType($client_policy_id){
 
         $client_policy_id = $this->request->getGet('client_policy_id');
@@ -1923,7 +2081,6 @@ class ClientController extends AdminController
 
     }
 
-
     public function downloadKYCDocument($file_name)
     {
 
@@ -1936,7 +2093,6 @@ class ClientController extends AdminController
         }
     }
 
-
     public function getClientBranch($client_id){
 
          $branchs = $this->clientBranchModel
@@ -2165,8 +2321,6 @@ class ClientController extends AdminController
 
     }
 
-
-
     public function transformArray($data, $mapping)
     {
 
@@ -2214,7 +2368,6 @@ class ClientController extends AdminController
         return json_encode($transformedData, JSON_PRETTY_PRINT);
     }
 
-
     public function transformFamilyFloaters($familyFloaters, $json)
     {
         $result = [];
@@ -2259,7 +2412,6 @@ class ClientController extends AdminController
         return implode(", ", $result);
     }
 
-
     public function deleteAdditionalRackRate($client_id, $client_policy_id, $rack_rate_type)
     {
         try {
@@ -2284,8 +2436,6 @@ class ClientController extends AdminController
         return $this->respond(['status' => true,'code' => 200, 'message' => 'Additionaly Rack Rate Data Remove Successfully'], 200);
     }
     
-
-
     public function get_cd_ac($client_id, $insurer_id)
     {
 
@@ -2303,7 +2453,6 @@ class ClientController extends AdminController
 
     }
 
-
     public function otherPolicyTermsFormSubmit()
     {
 
@@ -2327,7 +2476,6 @@ class ClientController extends AdminController
         }
     }
 
-
     public function checkPolicyType($policy_type_id, $client_branch_id, $client_id)
     {
 
@@ -2346,31 +2494,36 @@ class ClientController extends AdminController
 
     }
 
-
     public function getPolicyTerms($client_policy_id)
     {
         $policy_terms = $this->clientPolicyModel->where('id', $client_policy_id)->first();
     
         if (!$policy_terms) {
-            return $this->respond(['status' => false, 'error' => 'Policy not found'], 404);
+            // return $this->respond(['status' => false, 'error' => 'Policy not found'], 404);
+            return [];
         }
     
         if (is_array($policy_terms)) {
             if (!isset($policy_terms['policy_terms'])) {
-                return $this->respond(['status' => false, 'error' => 'Policy terms not found in array'], 500);
+                // return $this->respond(['status' => false, 'error' => 'Policy terms not found in array'], 500);
+                return [];
+
             }
             $JSON = json_decode($policy_terms['policy_terms']);
         } elseif (is_object($policy_terms)) {
             if (!isset($policy_terms->policy_terms)) {
-                return $this->respond(['status' => false, 'error' => 'Policy terms not found in object'], 500);
+                // return $this->respond(['status' => false, 'error' => 'Policy terms not found in object'], 500);
+                return [];
             }
             $JSON = json_decode($policy_terms->policy_terms);
         } else {
-            return $this->respond(['status' => false, 'error' => 'Unexpected data type for policy terms'], 500);
+            // return $this->respond(['status' => false, 'error' => 'Unexpected data type for policy terms'], 500);
+            return [];
         }
     
         if (!$JSON) {
-            return $this->respond(['status' => false, 'error' => 'Invalid JSON format in policy terms'], 500);
+            // return $this->respond(['status' => false, 'error' => 'Invalid JSON format in policy terms'], 500);
+            return [];
         }
     
         $multi_si = [];
@@ -2389,11 +2542,10 @@ class ClientController extends AdminController
             }
         }
     
-        return $this->respond(['status' => true, 'data' => $multi_si], 200);
+        // return $this->respond(['status' => true, 'data' => $multi_si], 200);
+        return $multi_si;
     }
     
-    
-
     public function getPolicyTermsFormJson($policy_type_id)
     {
 
@@ -2401,9 +2553,10 @@ class ClientController extends AdminController
         return $this->respond(['status' => true, 'data' => $JSON], 200);
     }
 
-    public function createPolicyTermsHtmlAsJSON(){
+    public function createPolicyTermsHtmlAsJSON()
+    {
 
-        
+        echo 'hi';
     }
 
     public function checkHRNumber($mobileNumber)
@@ -2425,7 +2578,6 @@ class ClientController extends AdminController
         }
     }
  
-    
     public function checkAdditionPremiumJSON($client_id, $client_policy_id)
     {
 
@@ -2439,4 +2591,173 @@ class ClientController extends AdminController
         return $this->respond(['status' => true, 'data' => $get_additional_rack_rate_relationship_json, 'message' => "try"], 200);    
     }
 
+    public function getPolicyTypeForBasePolicy($client_id)
+    {
+
+     $result = $this->clientPolicyModel->getPolicyTypeForPolicyBinding($client_id);   
+     return $this->respond(['status' => true, 'data' => $result], 200);
+
+    }
+
+    public function getClientDetails($client_id)
+    {
+
+     $result = $this->clientModel->where('id', $client_id)->first();   
+     return $this->respond(['status' => true, 'data' => $result], 200);
+    }
+
+    public function getBranchUnitsByBranchId($branch_id)
+    {
+
+        $units = $this->clientBranchModel->select('units')->where('id', $branch_id)->first();
+
+        if($units){
+            return $units['units'];
+        }else{
+            return [];
+        }
+
+    }
+
+    public function updateRackRateJson()
+    {   
+        // $client_policy_id = 13;
+
+        $results = $this->policyPremium2Model
+            ->select('*')
+            // ->where('client_policy_id', $client_policy_id)
+            ->where('is_active', 1)
+            ->groupBy('client_policy_id')
+            ->get()
+            ->getResultArray();
+       
+
+        $results2 = $this->policyPremium1Model
+            ->select('*')
+            // ->where('client_policy_id', $client_policy_id)
+            ->where('is_active', 1)
+            ->groupBy('client_policy_id')
+            ->get()
+            ->getResultArray();
+       
+
+        $client_policy_ids = [];
+        $json = [];
+        $json1 = [];
+
+        foreach ($results as $key => $result) 
+        {
+            $client_policy_id = $result['client_policy_id'];
+            $client_policy_data = $this->clientPolicyModel->where('id', $client_policy_id)->first();
+            $policy_terms = [];
+            
+            if(isset($client_policy_data['policy_terms'])) 
+            {
+                $policy_terms = json_decode($client_policy_data['policy_terms'], true);
+            } 
+                        
+            if (isset($policy_terms['family_floaters'])) {
+                $family_floaters = $policy_terms['family_floaters'];
+               
+                if(isset($family_floaters['self']) && isset($family_floaters['spouse']) && isset($family_floaters['childrens']) && isset($family_floaters['parents']) && isset($family_floaters['parents-in-law']) && isset($family_floaters['either-parents-pil']) && isset($family_floaters['elders_count'])) {
+                   
+                    $json1[] = $family_floaters;
+
+                    $self = 1;
+                    $spouse = 'any';
+                    $childrens = 'any';
+                    $parents = 'any';
+                    $parents_in_law = 'any';
+
+                    if($family_floaters['self'] == 0){
+                        $self = 'NA';
+                    }
+                    if($family_floaters['spouse'] == 0){
+                        $spouse = 'NA';
+                    }
+                    if($family_floaters['childrens'] == 0){
+                        $childrens = 'NA';
+                    }
+                    if($family_floaters['parents'] == 0){
+                        $parents = 'NA';
+                    }
+                    if($family_floaters['parents-in-law'] == 0){
+                        $parents_in_law = 'NA';
+                    }
+
+                    $transformed_family_floaters = [
+                        "self" => $self,
+                        "spouse" => $spouse,
+                        "childrens" => $childrens,
+                        "parents" =>  $parents,
+                        "parents-in-law" => $parents_in_law,
+                    ];
+                    
+                    $formatedJSON = json_encode($transformed_family_floaters);
+                    $json[] = $formatedJSON;
+
+                    $forUpdateData = [
+                            "additional_relationship" => $formatedJSON,
+                            "rack_rate_name" => 'Primary',
+                    ];
+
+                    $this->policyPremium2Model
+                        ->where('client_policy_id', $client_policy_id)
+                        ->set($forUpdateData)
+                        ->update();
+                }
+
+                $client_policy_ids[] = $client_policy_id;
+            }
+        }
+
+        foreach ($results2 as $key => $result) 
+        {
+            $client_policy_id = $result['client_policy_id'];
+            $client_policy_data = $this->clientPolicyModel->where('id', $client_policy_id)->first();
+
+            if($client_policy_data['policy_terms']){
+
+                $self = 1;
+                $spouse = 'NA';
+                $childrens = 'NA';
+                $parents = 'NA';
+                $parents_in_law = 'NA';
+
+                $transformed_family_floaters = [
+                    "self" => $self,
+                    "spouse" => $spouse,
+                    "childrens" => $childrens,
+                    "parents" =>  $parents,
+                    "parents-in-law" => $parents_in_law,
+                ];
+                
+                $formatedJSON = json_encode($transformed_family_floaters);
+                $json[] = $formatedJSON;
+
+                $forUpdateData = [
+                    "additional_relationship" => $formatedJSON,
+                    "rack_rate_name" => 'Primary',
+                ];
+
+                $this->policyPremium1Model
+                        ->where('client_policy_id', $client_policy_id)
+                        ->set($forUpdateData)
+                        ->update();
+            }
+        }
+
+        $client_policy_ids[] = $client_policy_id;
+        
+
+        if(count($client_policy_ids) > 0){
+            echo 'There are ' . count($client_policy_ids) . ' records to be updated.';
+            echo '
'; + dd($client_policy_ids); + }else{ + echo 'There is no records to be update.'; + } + + } + } \ No newline at end of file diff --git a/app/Controllers/EmpDataServiceController.php b/app/Controllers/EmpDataServiceController.php index 96537b76..e472ef43 100644 --- a/app/Controllers/EmpDataServiceController.php +++ b/app/Controllers/EmpDataServiceController.php @@ -25,6 +25,7 @@ use App\Models\NotificationModel; use App\Models\MessageModel; use App\Models\UserMessageModel; use App\Models\CDMasterModel; +use App\Models\InsurerExcelExportTemplateModel; use App\Controllers\Jobs; use App\Controllers\JobWorker; @@ -54,6 +55,7 @@ class EmpDataServiceController extends BaseController protected $messageModel; protected $userMessageModel; protected $CDMasterModel; + protected $excelExportTemplateModel; public function __construct() @@ -74,6 +76,7 @@ class EmpDataServiceController extends BaseController $this->messageModel = new MessageModel(); $this->userMessageModel = new UserMessageModel(); $this->CDMasterModel = new CDMasterModel(); + $this->excelExportTemplateModel = new InsurerExcelExportTemplateModel(); } @@ -110,7 +113,8 @@ class EmpDataServiceController extends BaseController } - public function insertBatchList($params){ + public function insertBatchList($params) + { foreach ($params['batch_list_data'] as $value) { @@ -142,10 +146,7 @@ class EmpDataServiceController extends BaseController $objects = $this->employeePolicyModel->getInceptionEmployeeDataForExportExcel($export_data); $policy_details = $this->clientPolicyModel->where('id', $export_data['client_policy_id'])->first(); - // dd($export_data, $policy_details['cd_ac_no']); - if ($policy_details['cd_ac_no'] == null) { - // dd("The policy does not have a CD account number"); $this->myLogger->logme('error', 'The policy does not have a CD account number.'); return 5; } @@ -153,7 +154,6 @@ class EmpDataServiceController extends BaseController $cash_balance = $this->clientDepositModel->where('cd_ac_no', $policy_details['cd_ac_no'])->orderBy('id', 'DESC')->first(); if ($cash_balance == null) { - $balance = $this->CDMasterModel ->where('client_id', $export_data['client_id']) ->where('insurer_id', $policy_details['insurer_id']) @@ -163,17 +163,14 @@ class EmpDataServiceController extends BaseController $cash_balance['balance'] = $balance['opening_bal']; } - // dd($cash_balance); - // Calculate the total amount from the objects - $totals = array_reduce($objects, function ($carry, $item) { - return $carry + $item->total; - }, 0); - + $totals = 0; + foreach ($objects as $item) { + $totals = $totals + $item->total; + } + $totals = round($totals, 2); - if (!empty($cash_balance)) { - if ((int) $cash_balance['balance'] < (int) $totals) { $this->myLogger->logme('error', 'Inception export failed due to insufficient deposit amount.'); $this->myLogger->logme('error', 'Inception export failed due to insufficient deposit amount. CASH BALANCE : {balance} and TOTAL AMOUNT : {total}', ['balance' => $cash_balance['balance'], 'total' => $totals]); @@ -181,22 +178,16 @@ class EmpDataServiceController extends BaseController } } - - $this->removeOldExportInfoFromBatchFile($export_data); - - // Log the count of exported data $count = count($objects); $export_data['count'] = $count; $export_data['amount'] = $totals; $export_data['status'] = 'success'; - $this->myLogger->logme('error', 'Inception export data count : {data}', ['data' => $count]); // If no data is found for export, return false if ($count == 0) { - $this->myLogger->logme('error', 'No Record found. TPA ID or UHID are Alread Updated. Correction export data count : {data}', ['data' => $count]); return false; } @@ -204,37 +195,249 @@ class EmpDataServiceController extends BaseController // Log the export file name $this->myLogger->logme('error', 'Inception export file name : {data}', ['data' => $export_data['file_name']]); - // Transform retrieved objects to an array suitable for export - $data = transform_objects_to_array_for_inception($objects); + // remove existing batch file anf batch list data every time export + $this->removeOldExportInfoFromBatchFile($export_data); - // Define headers for the Excel file - $headers = [ - 'S.No', - 'NAME OF EMP/DEP', - 'EMP ID', - 'EMP/DEP TYPE', - 'RELATIONSHIP CODE', - 'DOB', - 'GENDER', - 'PRE EXISTING AILMENTS', - 'BASIC COVER SI', - 'DATE OF COVERAGE', - 'AGE', - 'RELATIONSHIP', - 'REMARKS', - 'POLICY END DATE', - 'NO OF DAYS', - 'TPA ID', - 'UHID', - 'PREMIUM', - 'PR0 RATA PREMIUM', - 'GST', - 'TOTAL' + // default excel header information + $excel_header_columns = [ + [ + 'column_index' => 0, + 'column_name' => 'S.No', + 'db_column_name' => 'index' + ], + [ + 'column_index' => 1, + 'column_name' => 'NAME OF EMP/DEP', + 'db_column_name' => 'emp_name' + ], + [ + 'column_index' => 2, + 'column_name' => 'EMP ID', + 'db_column_name' => 'emp_code' + ], + [ + 'column_index' => 3, + 'column_name' => 'EMP/DEP TYPE', + 'db_column_name' => 'emp_type' + ], + [ + 'column_index' => 4, + 'column_name' => 'RELATIONSHIP CODE', + 'db_column_name' => 'emp_relationship_code' + ], + [ + 'column_index' => 5, + 'column_name' => 'DOB', + 'db_column_name' => 'emp_dob' + ], + [ + 'column_index' => 6, + 'column_name' => 'GENDER', + 'db_column_name' => 'emp_gender' + ], + [ + 'column_index' => 7, + 'column_name' => 'PRE EXISTING AILMENTS', + 'db_column_name' => 'pre_existing_alignments' + ], + [ + 'column_index' => 8, + 'column_name' => 'BASIC COVER SI', + 'db_column_name' => 'basic_cover_si' + ], + [ + 'column_index' => 9, + 'column_name' => 'DATE OF COVERAGE', + 'db_column_name' => 'date_coverage' + ], + [ + 'column_index' => 10, + 'column_name' => 'AGE', + 'db_column_name' => 'emp_age' + ], + [ + 'column_index' => 11, + 'column_name' => 'RELATIONSHIP', + 'db_column_name' => 'emp_relationship' + ], + [ + 'column_index' => 12, + 'column_name' => 'REMARKS', + 'db_column_name' => 'remarks' + ], + [ + 'column_index' => 13, + 'column_name' => 'POLICY END DATE', + 'db_column_name' => 'policy_end_date' + ], + [ + 'column_index' => 14, + 'column_name' => 'NO OF DAYS', + 'db_column_name' => 'days' + ], + [ + 'column_index' => 15, + 'column_name' => 'TPA ID', + 'db_column_name' => 'tpa_id' + ], + [ + 'column_index' => 16, + 'column_name' => 'UHID', + 'db_column_name' => 'uhid' + ], + [ + 'column_index' => 17, + 'column_name' => 'PREMIUM', + 'db_column_name' => 'premium' + ], + [ + 'column_index' => 18, + 'column_name' => 'PR0 RATA PREMIUM', + 'db_column_name' => 'rata_premimum' + ], + [ + 'column_index' => 19, + 'column_name' => 'GST', + 'db_column_name' => 'gst' + ], + [ + 'column_index' => 20, + 'column_name' => 'TOTAL AMOUNT', + 'db_column_name' => 'total' + ] ]; + // get excel export format structure array + $template_json = $this->clientPolicyModel + ->select('insurer_excel_export_template.jsoncolumns') + ->join('insurer_excel_export_template', 'insurer_excel_export_template.insurer_id = client_policy.insurer_id and insurer_excel_export_template.policy_type_id = client_policy.policy_type_id') + ->where('client_policy.id', $export_data['client_policy_id']) + ->where('insurer_excel_export_template.event_name', $export_data['event_type']) + ->where('insurer_excel_export_template.type_name', $export_data['actions']) + ->first(); + + if(!empty($template_json) && $template_json != null){ + $excel_header_columns = json_decode($template_json['jsoncolumns'], true); + }else{ + return 6; + } + + if( $export_data['insurer_or_tpa'] == 'tpa'){ + + $excel_header_columns = [ + [ + 'column_index' => 0, + 'column_name' => 'S.No', + 'header_name' => 'index' + ], + [ + 'column_index' => 1, + 'column_name' => 'NAME OF EMP/DEP', + 'db_column_name' => 'emp_name' + ], + [ + 'column_index' => 2, + 'column_name' => 'EMP ID', + 'db_column_name' => 'emp_code' + ], + [ + 'column_index' => 3, + 'column_name' => 'EMP/DEP TYPE', + 'db_column_name' => 'emp_type' + ], + [ + 'column_index' => 4, + 'column_name' => 'RELATIONSHIP CODE', + 'db_column_name' => 'emp_relationship_code' + ], + [ + 'column_index' => 5, + 'column_name' => 'DOB', + 'db_column_name' => 'emp_dob' + ], + [ + 'column_index' => 6, + 'column_name' => 'GENDER', + 'db_column_name' => 'emp_gender' + ], + [ + 'column_index' => 7, + 'column_name' => 'PRE EXISTING AILMENTS', + 'db_column_name' => 'pre_existing_alignments' + ], + [ + 'column_index' => 8, + 'column_name' => 'BASIC COVER SI', + 'db_column_name' => 'basic_cover_si' + ], + [ + 'column_index' => 9, + 'column_name' => 'DATE OF COVERAGE', + 'db_column_name' => 'date_of_coverage' + ], + [ + 'column_index' => 10, + 'column_name' => 'AGE', + 'db_column_name' => 'emp_age' + ], + [ + 'column_index' => 11, + 'column_name' => 'RELATIONSHIP', + 'db_column_name' => 'emp_relationship' + ], + [ + 'column_index' => 12, + 'column_name' => 'REMARKS', + 'db_column_name' => 'remarks' + ], + [ + 'column_index' => 13, + 'column_name' => 'POLICY END DATE', + 'db_column_name' => 'policy_end_date' + ], + [ + 'column_index' => 14, + 'column_name' => 'NO OF DAYS', + 'db_column_name' => 'no_of_days' + ], + [ + 'column_index' => 15, + 'column_name' => 'TPA ID', + 'db_column_name' => 'tpa_id' + ], + [ + 'column_index' => 16, + 'column_name' => 'UHID', + 'db_column_name' => 'uhid' + ], + [ + 'column_index' => 17, + 'column_name' => 'PREMIUM', + 'db_column_name' => 'premium' + ], + [ + 'column_index' => 18, + 'column_name' => 'PR0 RATA PREMIUM', + 'db_column_name' => 'pro_rata_premium' + ], + [ + 'column_index' => 19, + 'column_name' => 'GST', + 'db_column_name' => 'gst' + ], + [ + 'column_index' => 20, + 'column_name' => 'TOTAL AMOUNT', + 'db_column_name' => 'total' + ] + ]; + } + + $excel_data_info = generate_insurer_based_excel($excel_header_columns, $objects); + // Generate Excel file $tempFile = tmpfile(); - $success = generate_excel($headers, $data, $tempFile, 1); + $success = generate_excel($excel_data_info['header'], $excel_data_info['data'], $tempFile); // If Excel generation is successful if ($success) { @@ -305,42 +508,59 @@ class EmpDataServiceController extends BaseController if ($count == 0) { $this->myLogger->logme('error', 'No Record found. Endorsement ID Alread Updated. Correction export data count : {data}', ['data' => $count]); - return false; + // return false; } + $this->removeOldExportInfoFromBatchFile($export_data); $this->myLogger->logme('error', 'Correction export file name : {data}', ['data' => $export_data['file_name']]); + + + // get excel export format structure array + $template_json = $this->clientPolicyModel + ->select('insurer_excel_export_template.jsoncolumns') + ->join('insurer_excel_export_template', 'insurer_excel_export_template.insurer_id = client_policy.insurer_id and insurer_excel_export_template.policy_type_id = client_policy.policy_type_id') + ->where('client_policy.id', $export_data['client_policy_id']) + ->where('insurer_excel_export_template.event_name', $export_data['event_type']) + ->where('insurer_excel_export_template.type_name', $export_data['actions']) + ->first(); + + if(!empty($template_json) && $template_json != null){ + $excel_header_columns = json_decode($template_json['jsoncolumns'], true); + }else{ + return 6; + } - $correction_data = transform_objects_to_array_for_correction($objects); - $headers = [ - 'Emp Code', - 'RISK ID', - 'NAME OF EMP/DEP', - 'EMP/DEP TYPE', - 'RELATION', - 'DOB', - 'GENDER', - 'Wrong Data', - 'Correct Data', - 'Remarks', - 'Endorsement_Id' - ]; + if( $export_data['insurer_or_tpa'] == 'tpa'){ + + $excel_header_columns = [ + ['column_index' => 0, 'column_name' => 'Emp Code', 'db_column_name' => 'emp_code'], + ['column_index' => 1, 'column_name' => 'RISK ID', 'db_column_name' => 'uhid'], + ['column_index' => 1, 'column_name' => 'NAME OF EMP/DEP', 'db_column_name' => 'emp_name'], + ['column_index' => 3, 'column_name' => 'EMP/DEP TYPE', 'db_column_name' => 'emp_type'], + ['column_index' => 4, 'column_name' => 'RELATION', 'db_column_name' => 'relationship_code'], + ['column_index' => 5, 'column_name' => 'DOB', 'db_column_name' => 'emp_dob'], + ['column_index' => 6, 'column_name' => 'GENDER', 'db_column_name' => 'emp_gender'], + ['column_index' => 7, 'column_name' => 'Wrong Data', 'db_column_name' => 'old_value'], + ['column_index' => 8, 'column_name' => 'Correct Data', 'db_column_name' => 'new_value'], + ['column_index' => 9, 'column_name' => 'Remarks', 'db_column_name' => 'remarks'], + ['column_index' => 10, 'column_name' => 'Endorsement_Id', 'db_column_name' => null] + ]; + } - // Create a temporary file in memory + + $excel_data_info = generate_insurer_based_excel($excel_header_columns, $objects); + + // Generate Excel file $tempFile = tmpfile(); + $success = generate_excel($excel_data_info['header'], $excel_data_info['data'], $tempFile); - // Generate Excel file with the temporary file - $value = generate_excel($headers, $correction_data, $tempFile); - - if ($value) { - - + if ($success) { $return = $this->batchFilesAndBatchListEntry($export_data, $objects); - if ($return) { foreach ($ids as $key => $id) { @@ -432,39 +652,57 @@ class EmpDataServiceController extends BaseController $this->removeOldExportInfoFromBatchFile($export_data); $this->myLogger->logme('error', 'SI_Enhancement export file name : {data}', ['data' => $export_data['file_name']]); - $si_data = transform_objects_to_array_for_si_enhancement($objects); - $headers = [ - 'S.No', - 'NAME OF EMP/DEP', - 'EMP ID', - 'EMP/DEP TYPE', - 'RELATION', - 'DOB', - 'GENDER', - 'PRE EXISTING AILMENTS', - 'BASIC COVER SI', - 'Old Sum Insured', - 'Date of Coverage', - 'Policy End Date', - 'No Of Days', - 'Old SI Premium', - 'New SI premium', - 'Difference premium', - 'Pro Rata Premium', - 'GST', - 'Total', - 'ENDORSEMENT_ID' - ]; + // get excel export format structure array + $template_json = $this->clientPolicyModel + ->select('insurer_excel_export_template.jsoncolumns') + ->join('insurer_excel_export_template', 'insurer_excel_export_template.insurer_id = client_policy.insurer_id and insurer_excel_export_template.policy_type_id = client_policy.policy_type_id') + ->where('client_policy.id', $export_data['client_policy_id']) + ->where('insurer_excel_export_template.event_name', $export_data['event_type']) + ->where('insurer_excel_export_template.type_name', $export_data['actions']) + ->first(); + + if(!empty($template_json) && $template_json != null){ + $excel_header_columns = json_decode($template_json['jsoncolumns'], true); + }else{ + return 6; + } + + if( $export_data['insurer_or_tpa'] == 'tpa'){ + + $excel_header_columns = [ + ['column_index' => 0, 'column_name' => 'S.No', 'db_column_name' => 'index'], + ['column_index' => 1, 'column_name' => 'NAME OF EMP/DEP', 'db_column_name' => 'emp_name'], + ['column_index' => 2, 'column_name' => 'EMP ID', 'db_column_name' => 'emp_code'], + ['column_index' => 3, 'column_name' => 'EMP/DEP TYPE', 'db_column_name' => 'emp_type'], + ['column_index' => 4, 'column_name' => 'RELATION', 'db_column_name' => 'emp_relationship_code'], + ['column_index' => 5, 'column_name' => 'DOB', 'db_column_name' => 'emp_dob'], + ['column_index' => 6, 'column_name' => 'GENDER', 'db_column_name' => 'emp_gender'], + ['column_index' => 7, 'column_name' => 'PRE EXISTING AILMENTS', 'db_column_name' => 'pre_existing_alignments'], + ['column_index' => 8, 'column_name' => 'BASIC COVER SI', 'db_column_name' => 'new_basic_cover_si'], + ['column_index' => 9, 'column_name' => 'Old Sum Insured', 'db_column_name' => 'old_basic_cover_si'], + ['column_index' => 10, 'column_name' => 'Date of Coverage', 'db_column_name' => 'date_of_coverage'], + ['column_index' => 11, 'column_name' => 'Policy End Date', 'db_column_name' => 'policy_end_date'], + ['column_index' => 12, 'column_name' => 'No Of Days', 'db_column_name' => 'no_of_days'], + ['column_index' => 13, 'column_name' => 'Old SI Premium', 'db_column_name' => 'old_si_premium'], + ['column_index' => 14, 'column_name' => 'New SI premium', 'db_column_name' => 'new_si_premium'], + ['column_index' => 15, 'column_name' => 'Difference premium', 'db_column_name' => 'difference_premium'], + ['column_index' => 16, 'column_name' => 'Pro Rata Premium', 'db_column_name' => 'pro_rata_premium'], + ['column_index' => 17, 'column_name' => 'GST', 'db_column_name' => 'gst'], + ['column_index' => 18, 'column_name' => 'Total', 'db_column_name' => 'total'], + ['column_index' => 19, 'column_name' => 'ENDORSEMENT_ID', 'db_column_name' => null] + ]; + + } - // Create a temporary file in memory + $excel_data_info = generate_insurer_based_excel($excel_header_columns, $objects); + + // Generate Excel file $tempFile = tmpfile(); + $success = generate_excel($excel_data_info['header'], $excel_data_info['data'], $tempFile); - // Generate Excel file with the temporary file - $value = generate_excel($headers, $si_data, $tempFile); - - if ($value) { + if ($success) { $return = $this->batchFilesAndBatchListEntry($export_data, $objects); if ($return) { @@ -526,35 +764,51 @@ class EmpDataServiceController extends BaseController $this->removeOldExportInfoFromBatchFile($export_data); $this->myLogger->logme('error', 'Deletion export file name : {data}', ['data' => $export_data['file_name']]); - $si_data = transform_objects_to_array_for_deletion($objects); - // dd($si_data); - $headers = [ - 'S.No', - 'EMP ID', - 'EMP NAME', - 'DOB', - 'GENDER', - 'RELATIONSHIP', - 'SUM INSURED', - 'Date of Leaving', - 'Policy End Date', - 'No Of Days', - 'Premium', - 'Pro Rata Premium', - 'GST', - 'Total', - 'Claim Status', - 'ENDORSEMENT_ID' - ]; + // get excel export format structure array + $template_json = $this->clientPolicyModel + ->select('insurer_excel_export_template.jsoncolumns') + ->join('insurer_excel_export_template', 'insurer_excel_export_template.insurer_id = client_policy.insurer_id and insurer_excel_export_template.policy_type_id = client_policy.policy_type_id') + ->where('client_policy.id', $export_data['client_policy_id']) + ->where('insurer_excel_export_template.event_name', $export_data['event_type']) + ->where('insurer_excel_export_template.type_name', $export_data['actions']) + ->first(); + + if(!empty($template_json) && $template_json != null){ + $excel_header_columns = json_decode($template_json['jsoncolumns'], true); + }else{ + return 6; + } + if( $export_data['insurer_or_tpa'] == 'tpa'){ + + $excel_header_columns = [ + ['column_index' => 0, 'column_name' => 'S.No', 'db_column_name' => 'index'], + ['column_index' => 1, 'column_name' => 'EMP ID', 'db_column_name' => 'emp_code'], + ['column_index' => 2, 'column_name' => 'EMP NAME', 'db_column_name' => 'emp_name'], + ['column_index' => 3, 'column_name' => 'DOB', 'db_column_name' => 'emp_dob'], + ['column_index' => 4, 'column_name' => 'GENDER', 'db_column_name' => 'emp_gender'], + ['column_index' => 5, 'column_name' => 'RELATIONSHIP', 'db_column_name' => 'emp_relationship_code'], + ['column_index' => 6, 'column_name' => 'SUM INSURED', 'db_column_name' => 'basic_cover_si'], + ['column_index' => 7, 'column_name' => 'Date of Leaving', 'db_column_name' => 'date_of_leaving'], + ['column_index' => 8, 'column_name' => 'Policy End Date', 'db_column_name' => 'policy_end_date'], + ['column_index' => 9, 'column_name' => 'No Of Days', 'db_column_name' => 'no_of_days'], + ['column_index' => 10, 'column_name' => 'Premium', 'db_column_name' => 'premium'], + ['column_index' => 11, 'column_name' => 'Pro Rata Premium', 'db_column_name' => 'pro_rata_premium'], + ['column_index' => 12, 'column_name' => 'GST', 'db_column_name' => 'gst'], + ['column_index' => 13, 'column_name' => 'Total', 'db_column_name' => 'total'], + ['column_index' => 14, 'column_name' => 'Claim Status', 'db_column_name' => null], + ['column_index' => 15, 'column_name' => 'ENDORSEMENT_ID', 'db_column_name' => null] + ]; - // Create a temporary file in memory + } + + $excel_data_info = generate_insurer_based_excel($excel_header_columns, $objects); + + // Generate Excel file $tempFile = tmpfile(); + $success = generate_excel($excel_data_info['header'], $excel_data_info['data'], $tempFile); - // Generate Excel file with the temporary file - $value = generate_excel($headers, $si_data, $tempFile, 2); - - if ($value) { + if ($success) { $return = $this->batchFilesAndBatchListEntry($export_data, $objects); if ($return) { @@ -587,6 +841,281 @@ class EmpDataServiceController extends BaseController } + public function generateExcelForAllEventType($export_data) + { + + $additionData = []; + $deletionData = []; + $inceptionData = []; + $correctionData = []; + $enhancementData = []; + $dependentAdditionData = []; + + $event_type_array = $export_data['event_type']; + + foreach ($export_data['event_type'] as $value) + { + + if($value == 'addition'){ + $export_data['event_type'] = 'addition'; + $additionData = $this->employeePolicyModel->getInceptionEmployeeDataForExportExcel($export_data); + + }else if($value == 'inception'){ + $export_data['event_type'] = 'inception'; + $dependentAdditionData = $this->employeePolicyModel->getInceptionEmployeeDataForExportExcel($export_data); + + }else if($value == 'dependent_addition'){ + $export_data['event_type'] = 'dependent_addition'; + $dependentAdditionData = $this->employeePolicyModel->getInceptionEmployeeDataForExportExcel($export_data); + + }else if($value == 'deletion'){ + $export_data['event_type'] = 'deletion'; + $deletionData = $this->employeePolicyModel->getDeletionEmployeeDataForExportExcel($export_data); + + }else if($value == 'si_enhancement'){ + $export_data['event_type'] = 'si_enhancement'; + $enhancementData = $this->employeePolicyModel->getSIEnhancementEmployeesDataForExportExcel($export_data); + + }else if($value == 'correction'){ + $export_data['event_type'] = 'correction'; + $correctionData = $this->employeePolicyModel->getCorrectionEmployeesDataForExportExcel($export_data); + + } + + } + + if(empty($additionData) && empty($deletionData) && empty($inceptionData) && empty($correctionData) && empty($enhancementData) && empty($dependentAdditionData)){ + + return 0; + } + + //for cd tranction and cd master data is empty check + if(!empty($inceptionData) && $inceptionData != null){ + + $policy_details = $this->clientPolicyModel->where('id', $export_data['client_policy_id'])->first(); + + if ($policy_details['cd_ac_no'] == null) { + $this->myLogger->logme('error', 'The policy does not have a CD account number.'); + return 5; + } + + $cash_balance = $this->clientDepositModel->where('cd_ac_no', $policy_details['cd_ac_no'])->orderBy('id', 'DESC')->first(); + + if ($cash_balance == null) { + $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']) + ->first(); + + $cash_balance['balance'] = $balance['opening_bal']; + } + + // Calculate the total amount from the objects + $totals = 0; + foreach ($inceptionData as $item) { + $totals = $totals + $item->total; + } + + $totals = round($totals, 2); + if (!empty($cash_balance)) { + if ((int) $cash_balance['balance'] < (int) $totals) { + $this->myLogger->logme('error', 'Inception export failed due to insufficient deposit amount.'); + $this->myLogger->logme('error', 'Inception export failed due to insufficient deposit amount. CASH BALANCE : {balance} and TOTAL AMOUNT : {total}', ['balance' => $cash_balance['balance'], 'total' => $totals]); + return 0; + } + } + } + + $this->removeOldExportInfoFromBatchFile($export_data); + + + // Merging all data into a single array + $mergedData = array_merge($inceptionData, $additionData, $dependentAdditionData, $correctionData, $enhancementData, $deletionData); + + // dd($inceptionData, $additionData, $dependentAdditionData, $correctionData, $enhancementData, $deletionData, $mergedData); + + + $template_json = $this->clientPolicyModel + ->select('insurer_excel_export_template.jsoncolumns') + ->join('insurer_excel_export_template', 'insurer_excel_export_template.insurer_id = client_policy.insurer_id and insurer_excel_export_template.policy_type_id = client_policy.policy_type_id') + ->where('client_policy.id', $export_data['client_policy_id']) + ->where('insurer_excel_export_template.event_name', 'inception') + ->where('insurer_excel_export_template.type_name', $export_data['actions']) + ->first(); + + + if(!empty($template_json) && $template_json != null){ + $excel_header_columns = json_decode($template_json['jsoncolumns'], true); + }else{ + return 6; + } + + + // Generating Excel data + $excel_data_info = generate_insurer_based_excel($excel_header_columns, $mergedData); + + // Generate Excel file + $tempFile = tmpfile(); + $success = generate_excel($excel_data_info['header'], $excel_data_info['data'], $tempFile); + + // If Excel generation is successful + if ($success) { + + $random_number_count = 4; + $batch_code = generate_random_string($random_number_count); + session()->set('batch_code', $batch_code); + + foreach ($event_type_array as $value) + { + $random_number_count = 4; + $export_data['batch_code'] = session()->get('batch_code'); + $export_data['created_by'] = get_session_userid(); + + if($value == 'addition'){ + + if(!empty($additionData) && $additionData != null){ + + $count = count($additionData); + $export_data['count'] = $count; + $export_data['status'] = 'success'; + $export_data['event_type'] = 'addition'; + + $insert = $this->batchFileModel->insert($export_data); + $batch_file_batch_code = $this->batchFileModel->where('id', $insert)->first(); + // $this->insertBatchList(['batch_code' => $batch_code, 'batch_list_data' => $objects ]); + + $job_details = new Jobs(); + $r = Jobs::addJob(['job_name' => 'insertBatchList', 'payload' => ['batch_code' => $batch_code, 'user_id' => get_session_userid(), 'batch_list_data' => $additionData]]); + + } + + }else if($value == 'inception'){ + + if(!empty($inceptionData) && $inceptionData != null){ + + $count = count($inceptionData); + $export_data['count'] = $count; + $export_data['status'] = 'success'; + $export_data['event_type'] = 'inception'; + + $insert = $this->batchFileModel->insert($export_data); + $batch_file_batch_code = $this->batchFileModel->where('id', $insert)->first(); + // $this->insertBatchList(['batch_code' => $batch_code, 'batch_list_data' => $objects ]); + + $job_details = new Jobs(); + $r = Jobs::addJob(['job_name' => 'insertBatchList', 'payload' => ['batch_code' => $batch_code, 'user_id' => get_session_userid(), 'batch_list_data' => $inceptionData]]); + } + + }else if($value == 'dependent_addition'){ + + if(!empty($dependentAdditionData) && $dependentAdditionData != null){ + + $count = count($dependentAdditionData); + $export_data['count'] = $count; + $export_data['status'] = 'success'; + $export_data['event_type'] = 'dependent_addition'; + + $insert = $this->batchFileModel->insert($export_data); + $batch_file_batch_code = $this->batchFileModel->where('id', $insert)->first(); + // $this->insertBatchList(['batch_code' => $batch_code, 'batch_list_data' => $objects ]); + + $job_details = new Jobs(); + $r = Jobs::addJob(['job_name' => 'insertBatchList', 'payload' => ['batch_code' => $batch_code, 'user_id' => get_session_userid(), 'batch_list_data' => $dependentAdditionData]]); + } + }else if($value == 'deletion'){ + + if(!empty($deletionData) && $deletionData != null){ + + $count = count($deletionData); + $export_data['count'] = $count; + $export_data['status'] = 'success'; + $export_data['event_type'] = 'deletion'; + + $insert = $this->batchFileModel->insert($export_data); + $batch_file_batch_code = $this->batchFileModel->where('id', $insert)->first(); + // $this->insertBatchList(['batch_code' => $batch_code, 'batch_list_data' => $objects ]); + + $job_details = new Jobs(); + $r = Jobs::addJob(['job_name' => 'insertBatchList', 'payload' => ['batch_code' => $batch_code, 'user_id' => get_session_userid(), 'batch_list_data' => $deletionData]]); + } + + }else if($value == 'si_enhancement'){ + + if(!empty($enhancementData) && $enhancementData != null){ + + $count = count($enhancementData); + $export_data['count'] = $count; + $export_data['status'] = 'success'; + $export_data['event_type'] = 'si_enhancement'; + + $insert = $this->batchFileModel->insert($export_data); + $batch_file_batch_code = $this->batchFileModel->where('id', $insert)->first(); + // $this->insertBatchList(['batch_code' => $batch_code, 'batch_list_data' => $objects ]); + + $job_details = new Jobs(); + $r = Jobs::addJob(['job_name' => 'insertBatchList', 'payload' => ['batch_code' => $batch_code, 'user_id' => get_session_userid(), 'batch_list_data' => $enhancementData]]); + } + + }else if($value == 'correction'){ + + if(!empty($correctionData) && $correctionData != null){ + + $count = count($correctionData); + $export_data['count'] = $count; + $export_data['status'] = 'success'; + $export_data['event_type'] = 'correction'; + + $insert = $this->batchFileModel->insert($export_data); + $batch_file_batch_code = $this->batchFileModel->where('id', $insert)->first(); + // $this->insertBatchList(['batch_code' => $batch_code, 'batch_list_data' => $objects ]); + + $job_details = new Jobs(); + $r = Jobs::addJob(['job_name' => 'insertBatchList', 'payload' => ['batch_code' => $batch_code, 'user_id' => get_session_userid(), 'batch_list_data' => $correctionData]]); + } + } + + } + + session()->remove('batch_code'); + + // If batch operation is successful + if (true) { + + // Clear the output buffer to avoid any unwanted output + if (ob_get_level()) { + ob_end_clean(); + } + + // Set headers for Excel file download + header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); + header('Content-Disposition: attachment; filename="' . $export_data['file_name'] . '"'); + header('Content-Transfer-Encoding: binary'); + header('Cache-Control: must-revalidate'); + header('Pragma: public'); + header('Expires: 0'); + + // Output file contents + rewind($tempFile); + fpassthru($tempFile); + + // Close and remove temporary file + fclose($tempFile); + + return true; // Excel file successfully generated and exported + + } else { + + return false; // Batch operation failed + } + } + + return false; // Excel generation failed + + + + } + //not in use public function generateExcelForAdditionAndDependentAddition($export_data) { @@ -1229,7 +1758,7 @@ class EmpDataServiceController extends BaseController $this->myLogger->logme('error', 'Inception Update TPA and UHID -- total amount for cash deposite : {data}', ['data' => $totals]); - if ($file['insurer_or_tpa'] == 'tpa') { + if ($file['insurer_or_tpa'] == 'insurer') { $this->myLogger->logme('error', 'Inception Update TPA and UHID -- set cashDepositCalculationForInception and sendMailForDownloadingECard in JOB QUEUE'); @@ -3378,8 +3907,8 @@ class EmpDataServiceController extends BaseController public function getPolicyNameUsingClientPolicyId($client_policy_id) { - return $this->clientPolicyModel->select('policies.name as policy_name') - ->join('policies', 'policies.id = client_policy.policy_id') + return $this->clientPolicyModel->select('policy_type.policy_type as policy_name') + ->join('policy_type', 'policy_type.id = client_policy.policy_type_id') ->where('client_policy.id', $client_policy_id) ->first(); } @@ -3701,8 +4230,6 @@ class EmpDataServiceController extends BaseController } } - - public function readExcelFileToArray($path) { $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($path); @@ -3725,9 +4252,8 @@ class EmpDataServiceController extends BaseController return $filtered_data; } - - - public function removeOldExportInfoFromBatchFile($params){ + public function removeOldExportInfoFromBatchFile($params) + { $client_id = $params['client_id']; $client_policy_id = $params['client_policy_id']; @@ -3750,21 +4276,18 @@ class EmpDataServiceController extends BaseController $batch_code = $batch_data['batch_code']; $this->batchFileModel->where('id', $id)->delete(); $this->batchListModel->where('batch_code', $batch_code)->delete(); - } - - } - - public function getDataByFileId($file_id, $status = 'success'){ + public function getDataByFileId($file_id, $status = 'success') + { $data = $this->batchFileModel - ->select('batch_files.*, clients.client_name, clients.short_name, policies.name as policy_name, client_branch.branch_name') + ->select('batch_files.*, clients.client_name, clients.short_name, policy_type.policy_type as policy_name, client_branch.branch_name') ->join('clients', 'clients.id = batch_files.client_id') ->join('client_policy', 'client_policy.id = batch_files.client_policy_id') ->join('client_branch', 'client_branch.id = batch_files.client_branch_id') - ->join('policies', 'policies.id = client_policy.policy_id') + ->join('policy_type', 'policy_type.id = client_policy.policy_type_id') ->where('batch_files.id', $file_id) ->first(); @@ -3786,8 +4309,8 @@ class EmpDataServiceController extends BaseController return ['msg_txt' => $msg_txt, 'user_id' => $user_id, 'url' => $url, 'status' => $status, 'title' => $msg_title]; } - - public function setPullNotification($data){ + public function setPullNotification($data) + { $array = ['message_text' => $data['msg_txt'], 'action_url' => $data['url'], 'msg_status' => $data['status'], 'msg_title' => $data['title']]; @@ -3808,6 +4331,60 @@ class EmpDataServiceController extends BaseController } + public function updatajson() + { + + // $columns = [ + // ["column_index" => 0, "column_name" => "MEMBERID / EMPID", "db_column_name" => "emp_code"], + // ["column_index" => 1, "column_name" => "UHID", "db_column_name" => "uhid"], + // ["column_index" => 2, "column_name" => "GRADE", "db_column_name" => null], + // ["column_index" => 3, "column_name" => "DOJ", "db_column_name" => "emp_doj"], + // ["column_index" => 4, "column_name" => "INSURED NAME", "db_column_name" => "insured_name"], + // ["column_index" => 5, "column_name" => "ADDRESS 1", "db_column_name" => null], + // ["column_index" => 6, "column_name" => "ADDRESS 2", "db_column_name" => null], + // ["column_index" => 7, "column_name" => "CITY", "db_column_name" => null], + // ["column_index" => 8, "column_name" => "STATE", "db_column_name" => null], + // ["column_index" => 9, "column_name" => "PINCODE", "db_column_name" => null], + // ["column_index" => 10, "column_name" => "Age", "db_column_name" => "emp_age"], + // ["column_index" => 11, "column_name" => "DOB", "db_column_name" => "emp_dob"], + // ["column_index" => 12, "column_name" => "RELATION SHIP", "db_column_name" => "emp_relationship"], + // ["column_index" => 13, "column_name" => "Gender", "db_column_name" => "emp_gender"], + // ["column_index" => 14, "column_name" => "DOC", "db_column_name" => "doc"], + // ["column_index" => 15, "column_name" => "DOE", "db_column_name" => "doe"], + // ["column_index" => 16, "column_name" => "SUM INSURED", "db_column_name" => "basic_cover_si"], + // ["column_index" => 17, "column_name" => "PROPOSER NAME", "db_column_name" => null], + // ["column_index" => 18, "column_name" => "DOS", "db_column_name" => "dos"], + // ["column_index" => 19, "column_name" => "MOBILE NO", "db_column_name" => null], + // ["column_index" => 20, "column_name" => "EMAIL ID", "db_column_name" => null], + // ["column_index" => 21, "column_name" => "FATHER/HUSBAND NAME", "db_column_name" => null], + // ["column_index" => 22, "column_name" => "REMARKS", "db_column_name" => null], + // ["column_index" => 23, "column_name" => "FLAG STATUS", "db_column_name" => "flag_status"], + // ["column_index" => 24, "column_name" => "EXCEPTIONS", "db_column_name" => "exceptions"], + // ["column_index" => 25, "column_name" => "ABHA", "db_column_name" => null] + // ]; + + // $columns = [ + // ["column_index" => 0, "column_name" => "Sr.No", "db_column_name" => "index"], + // ["column_index" => 1, "column_name" => "Tata Aig Ref. No", "db_column_name" => "uhid"], + // ["column_index" => 2, "column_name" => "EMP ID", "db_column_name" => "emp_code"], + // ["column_index" => 3, "column_name" => "Name of Insured", "db_column_name" => "emp_name"], + // ["column_index" => 4, "column_name" => "GC Current Details", "db_column_name" => "old_value"], + // ["column_index" => 5, "column_name" => "Modified Details", "db_column_name" => "new_value"], + // ["column_index" => 6, "column_name" => "Revision W.E.F (DD/MM/YYYY)", "db_column_name" => null], + // ["column_index" => 7, "column_name" => "NEW TTD", "db_column_name" => null], + // ["column_index" => 8, "column_name" => "New Category's", "db_column_name" => null], + // ["column_index" => 9, "column_name" => "Remarks", "db_column_name" => "remarks"], + // ["column_index" => 10, "column_name" => "DOC", "db_column_name" => null], + // ["column_index" => 11, "column_name" => "Errors", "db_column_name" => null] + // ]; + + + + // $json = json_encode($columns); + // $this->excelExportTemplateModel->where('id', 31)->set('jsoncolumns', $json)->update(); + + } + } diff --git a/app/Controllers/EmployeeController.php b/app/Controllers/EmployeeController.php index ec8467e6..99b54b88 100644 --- a/app/Controllers/EmployeeController.php +++ b/app/Controllers/EmployeeController.php @@ -18,6 +18,9 @@ use App\Models\BatchFileModel; use App\Models\EmpEndorsementModel; use App\Models\ClientPolicyModel; use App\Models\TPAModel; +use App\Models\InsurerExcelExportTemplateModel; +use App\Models\InsurerModel; + use App\Controllers\Jobs; use App\Controllers\JobWorker; @@ -51,6 +54,8 @@ class EmployeeController extends AdminController protected $clientPolicyModel; protected $TPAModel; protected $policiesModel; + protected $excelExportTemplateModel; + protected $insurerModel; public function __construct() { @@ -67,6 +72,7 @@ class EmployeeController extends AdminController $this->clientPolicyModel = new ClientPolicyModel(); $this->TPAModel = new TPAModel(); $this->policiesModel = new PolicesModel(); + $this->insurerModel = new InsurerModel(); } public function list() @@ -257,7 +263,6 @@ class EmployeeController extends AdminController 'files.*', 'up.emp_code', 'up.first_name', - 'pm.name as policy_name', 'c.short_name', 'cb.branch_name', 'cp.id as client_policy_id', @@ -275,8 +280,7 @@ class EmployeeController extends AdminController ->join('user_profiles up', 'files.created_by = up.id') ->join('client_policy cp', 'files.policy_id = cp.id', 'left') ->join('client_branch cb', 'files.client_branch_id = cb.id', 'left') - ->join('policies pm', 'cp.policy_id = pm.id', 'left') - ->join('policy_type', 'policy_type.id = pm.policy_type_id') + ->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') ->where('files.created_by', get_session_userid()) ->orderBy('files.created_at', 'desc') @@ -285,7 +289,6 @@ class EmployeeController extends AdminController $data['batch_list'] = $this->batchFileModel->select( 'batch_files.*, - policies.name as policy_name, clients.short_name as client_short_name, client_branch.branch_name, client_policy.policy_no, @@ -293,8 +296,7 @@ class EmployeeController extends AdminController ') ->join('client_policy', 'client_policy.id = batch_files.client_policy_id') ->join('client_branch', 'client_branch.id = batch_files.client_branch_id') - ->join('policies', 'policies.id = client_policy.policy_id') - ->join('policy_type', 'policy_type.id = policies.policy_type_id') + ->join('policy_type', 'policy_type.id = client_policy.policy_type_id') ->join('clients', 'clients.id = client_policy.client_id') ->orderBy('batch_files.id', 'desc') ->findAll(); @@ -387,6 +389,15 @@ class EmployeeController extends AdminController public function importExport() { + $array = $this->request->getPost('event_type'); + + if (is_array($array)) { + $event_type = 'MultipleEvents'; + } else { + $event_type = $this->request->getPost('event_type'); + } + + $this->myLogger->logme('error', 'Import Export -- Function called'); $empDataServiceController = new EmpDataServiceController(); @@ -394,16 +405,12 @@ class EmployeeController extends AdminController $client_policy_id = $this->request->getPost('client_policy_id'); $client_branch_id = $this->request->getPost('client_branch_id'); $insurer_or_tpa = $this->request->getPost('insurer_or_tpa'); - $event_type = $this->request->getPost('event_type'); $actions = $this->request->getPost('action_type'); - $client_data = $this->clientModel->where('id', $client_id)->first(); - $policy_name_and_branch_name = $this->clientPolicyModel->select('policies.name, client_branch.branch_code') - ->join('client_branch', 'client_branch.id = client_policy.client_branch_id') - ->join('policies', 'policies.id = client_policy.policy_id') - ->where('client_policy.id', $client_policy_id) - ->first(); - $file_name = generate_filename($client_data['short_name'], $event_type, $actions, $insurer_or_tpa, $policy_name_and_branch_name['name'], $policy_name_and_branch_name['branch_code']); + $client_data = $this->clientPolicyModel->getCliendDataForExcelFileName($client_policy_id); + $file_name = generate_filename($client_data['short_name'], $event_type, $actions, $insurer_or_tpa, $client_data['policy_type'], $client_data['branch_code']); + + // dd($client_data, $file_name); $batch_data = [ 'client_id' => $client_id, @@ -415,7 +422,6 @@ class EmployeeController extends AdminController 'file_name' => $file_name, ]; - if ($actions == 'export') { if ($event_type == 'inception' || $event_type == 'addition' || $event_type == 'dependent_addition') { @@ -432,6 +438,11 @@ class EmployeeController extends AdminController session()->setFlashdata('error', "The policy does not have a CD account number."); return redirect()->to(base_url('employee/upload')); } + else if($return === 6){ + + session()->setFlashdata('error', "The Insurer does not have an Excel export template format."); + return redirect()->to(base_url('employee/upload')); + } if (!$return) { @@ -448,6 +459,12 @@ class EmployeeController extends AdminController } else if ($event_type == 'correction') { $return = $empDataServiceController->generateExcelForCorrection($batch_data); + + if($return === 6){ + session()->setFlashdata('error', "The Insurer does not have an Excel export template format."); + return redirect()->to(base_url('employee/upload')); + } + if (!$return) { session()->setFlashdata('error', 'No data found about this action'); return redirect()->to(base_url('employee/upload')); @@ -466,6 +483,10 @@ class EmployeeController extends AdminController session()->setFlashdata('error', "The policy does not have a CD account number."); return redirect()->to(base_url('employee/upload')); + }else if($return === 6){ + + session()->setFlashdata('error', "The Insurer does not have an Excel export template format."); + return redirect()->to(base_url('employee/upload')); } if (!$return) { @@ -477,12 +498,38 @@ class EmployeeController extends AdminController } else if ($event_type == 'deletion') { $return = $empDataServiceController->generateExcelForDeletion($batch_data); + + if($return === 6){ + + session()->setFlashdata('error', "The Insurer does not have an Excel export template format."); + return redirect()->to(base_url('employee/upload')); + } + if (!$return) { session()->setFlashdata('error', 'No data found about this action'); return redirect()->to(base_url('employee/upload')); } else { $this->myLogger->logme('error', 'Successfully exported Excel file in Deletion.'); } + } else if($event_type == 'MultipleEvents'){ + + $batch_data['event_type'] = $array; + $return = $empDataServiceController->generateExcelForAllEventType($batch_data); + + + if($return === 6){ + + session()->setFlashdata('error', "The Insurer does not have an Excel export template format."); + return redirect()->to(base_url('employee/upload')); + } + + if (!$return) { + session()->setFlashdata('error', 'No data found about this action'); + return redirect()->to(base_url('employee/upload')); + } else { + $this->myLogger->logme('error', 'Excel exported successfully.'); + } + } } else if ($actions == 'import') { @@ -908,13 +955,14 @@ class EmployeeController extends AdminController return $response; } - public function generateIDCardForEmployee($rand_string, $people = 0) { // dd($rand_string, $people); - try { - + $this->myLogger->logme('error', 'generateIDCardForEmployee function started.'); + + // Step 1: Attempt to fetch employee code and client policy ID + $this->myLogger->logme('error', 'Fetching employee code and client policy ID.'); $get_emp_code_and_client_policy_id = $this->employeePolicyModel ->select('employee_polices.client_policy_id, employees.emp_code, tpa.short_name') ->join('client_policy', 'client_policy.id = employee_polices.client_policy_id') @@ -925,53 +973,51 @@ class EmployeeController extends AdminController ->where("employee_polices.tpa_id IS NOT NULL AND employee_polices.tpa_id <> ''") ->where('employee_polices.status', 'active') ->where('employee_polices.is_active', '1') - ->where('employee_polices.rand_string', $rand_string)->first(); - - // dd($get_emp_code_and_client_policy_id); - - + ->where('employee_polices.rand_string', $rand_string) + ->first(); + if ($get_emp_code_and_client_policy_id == null || $get_emp_code_and_client_policy_id == "") { - + $this->myLogger->logme('error', 'Member not found in this rand_string: ' . $rand_string); $data['message'] = 'Record Not Found'; return view('errors/404', $data); } - + + $this->myLogger->logme('error', 'Member found. Client policy ID: ' . $get_emp_code_and_client_policy_id['client_policy_id']); + $client_policy_id = $get_emp_code_and_client_policy_id['client_policy_id']; $emp_code = $get_emp_code_and_client_policy_id['emp_code']; - - + + // Step 2: Fetch ECard data + $this->myLogger->logme('error', 'Fetching ECard data using client_policy_id: ' . $client_policy_id . ' and emp_code: ' . $emp_code); $data = $this->employeePolicyModel->getECardDataUsingMd5($client_policy_id, $emp_code); - - if($people == 0){ - $data = $this->employeePolicyModel->getECardSingleData($rand_string, $emp_code); + + if ($people == 0) { + $this->myLogger->logme('error', 'Fetching single ECard data using rand_string: ' . $rand_string . ' and emp_code: ' . $emp_code); + $data = $this->employeePolicyModel->getECardSingleData($rand_string, $emp_code); } - - // dd($data); - - $template_data_path = WRITEPATH . 'e_card_template/'; + + // Step 3: Prepare template path + $template_data_path = WRITEPATH . 'e_card_template/'; $tpa_short_name = strtolower(str_replace(' ', '_', $get_emp_code_and_client_policy_id['short_name'])) . '.html'; - $final_path = $template_data_path . $tpa_short_name; - - // dd($template_data_path, $tpa_short_name, $final_path); - + $final_path = $template_data_path . $tpa_short_name; + + $this->myLogger->logme('error', 'Checking if template file exists at: ' . $final_path); + if (!file_exists($final_path)) { - - $data['message'] = 'Record Not Found'; + $this->myLogger->logme('error', 'Template file not found: ' . $final_path); + $data['message'] = 'Template File Not Found'; return view('errors/404', $data); - } - + } + + $this->myLogger->logme('error', 'Template file found. Reading template data.'); $tmplt_data = file_get_contents($final_path); - - // dd($tmplt_data); - - $html = ""; // Initialize the HTML variable + + // Step 4: Generate HTML content + $this->myLogger->logme('error', 'Generating HTML content from template.'); + $html = ""; foreach ($data as $key => $value) { - - // Get the HTML content from the template - // $htmlContent = view('ecard_template/md_tpa'); $htmlContent = $tmplt_data; - - // Define the placeholders and their corresponding values + $placeholders = [ '{TPA_ID}' => $value['tpa_id'], '{NAME}' => $value['name'], @@ -986,12 +1032,12 @@ class EmployeeController extends AdminController '{INSURER_LOGO}' => base_url() . 'public/uploads/logo/' . $value['insurer_logo'], '{FRONT_CARD}' => base_url() . 'public/uploads/template_bg/' . $value['front_card'], '{BACK_CARD}' => base_url() . 'public/uploads/template_bg/' . $value['back_card'], - '{EMP_ID}' =>$value['emp_code'], - '{CORPORATE_NAME}' =>$value['client_name'], - '{AGE}' =>$value['emp_age'], - '{TPA_NAME}' =>$value['tpa_name'], - '{INSURER_BRANCH}' =>$value['insurer_branch_city'], - '{RELATION}' =>$value['relationship'], + '{EMP_ID}' => $value['emp_code'], + '{CORPORATE_NAME}' => $value['client_name'], + '{AGE}' => $value['emp_age'], + '{TPA_NAME}' => $value['tpa_name'], + '{INSURER_BRANCH}' => $value['insurer_branch_city'], + '{RELATION}' => $value['relationship'], '{TPA_LOGO}' => base_url() . 'public/uploads/logo/' . $value['tpa_logo'], '{MEDI_USER}' => base_url() . 'public/e_card_imgs/medi_uesr.jpg', '{MEDI_INSURER}' => base_url() . 'public/e_card_imgs/Magma.png', @@ -1000,17 +1046,17 @@ class EmployeeController extends AdminController '{QR_IOS}' => base_url() . 'public/e_card_imgs/ios.png', '{QR_ANDROID_2}' => base_url() . 'public/e_card_imgs/play_store.png', '{QR_IOS_2}' => base_url() . 'public/e_card_imgs/appstore.png', - ]; - - // Replace placeholders with values in HTML content + foreach ($placeholders as $placeholder => $replaceValue) { $htmlContent = str_replace($placeholder, $replaceValue, $htmlContent); } - + $html .= $htmlContent; } - + + // Step 5: Output HTML and script for printing + $this->myLogger->logme('error', 'Generating HTML output with print button.'); echo '' . $html . ' '; - - - - // $file_name = $get_emp_code_and_client_policy_id['short_names'] ?? 'md_tpa'; - // $file_name = strtolower(str_replace(' ', '_', $file_name)); - - - - // $file_path = ROOTPATH . 'app/Views/ecard_template/' . $file_name . '.php'; - - // if (is_file($file_path)) { - // $view_file = 'ecard_template/' . $file_name; - - // } else { - // $view_file = 'ecard_template/default_ecard'; - - // } - - - // $dpi = 132; - // $html = view('ecard_template/md_tpa'); - // // echo $html; die; - - // $options = new Options(); - // $options->set('isRemoteEnabled', true); - // $options->set('isPhpEnabled', true); - // $options->setDpi($dpi); - // $dompdf = new Dompdf($options); - - // $dompdf->loadHtml($html); - // $dompdf->setPaper('A4', 'portrait'); - // $dompdf->render(); - - - // $filename = 'ECard.pdf'; // Default filename - - // foreach ($data['data'] as $key => $value) { - - // if ($value['relationship'] == "Self") { - - // $filename = $value['tpa_id'] . '.pdf'; // Update filename if relationship is "Self" - // } elseif (!empty($value['tpa_id']) && $filename == 'ECard.pdf') { - - // $filename = $value['tpa_id'] . '.pdf'; - // } - // } - - // $dompdf->stream($filename, array("Attachment" => false)); - + + $this->myLogger->logme('error', 'generateIDCardForEmployee function completed successfully.'); + } catch (\Exception $e) { - - $data['message'] = 'Record Not Founds'; + $this->myLogger->logme('error', 'Exception occurred: ' . $e->getMessage()); + $data['message'] = 'Record Not Found'; return view('errors/404', $data); } + } - public function viewECard() { @@ -1084,7 +1084,7 @@ class EmployeeController extends AdminController $empDataServiceController = new EmpDataServiceController(); $file_name = generate_filename("TCS", 'inception', 'export', 'insurer', 'policy', 'branch'); - $batch_data = [ + $export_data = [ 'client_id' => 12, 'client_policy_id' => 12, 'client_branch_id' => 1, @@ -1094,24 +1094,88 @@ class EmployeeController extends AdminController 'file_name' => $file_name, ]; - $return = $empDataServiceController->generateExcelForAdditionandInception($batch_data); + $template_json = $this->clientPolicyModel + ->select('insurer_excel_export_template.jsoncolumns') + ->join('insurer_excel_export_template', 'insurer_excel_export_template.insurer_id = client_policy.insurer_id and insurer_excel_export_template.policy_type_id = client_policy.policy_type_id') + ->where('client_policy.id', $export_data['client_policy_id']) + ->where('insurer_excel_export_template.event_name', $export_data['event_type']) + ->where('insurer_excel_export_template.type_name', $export_data['actions']) + ->first(); + + $template_array = json_decode($template_json['jsoncolumns'], true); + + // dd($template_array); + + $objects = $this->employeePolicyModel->getInceptionEmployeeDataForExportExcel($export_data); + + $totals = 0; + foreach ($objects as $item) { + $totals += $item->total; + } + + dd($objects, $totals); + + $excel_data_info = generate_insurer_based_excel($template_array, $objects); + + // Generate Excel file + $tempFile = tmpfile(); + $success = generate_excel($excel_data_info['header'], $excel_data_info['data'], $tempFile, 1); + + // If Excel generation is successful + if ($success) { + + $random_number_count = 4; + $export_data['batch_code'] = generate_random_string($random_number_count); + $export_data['created_by'] = get_session_userid(); + + $insert = $this->batchFileModel->insert($export_data); + $batch_file_batch_code = $this->batchFileModel->where('id', $insert)->first(); + $batch_code = $batch_file_batch_code['batch_code']; + + // $this->insertBatchList(['batch_code' => $batch_code, 'batch_list_data' => $objects ]); + + $job_details = new Jobs(); + $r = Jobs::addJob(['job_name' => 'insertBatchList', 'payload' => ['batch_code' => $batch_code, 'user_id' => get_session_userid(), 'batch_list_data' => $objects]]); + + + // If batch operation is successful + if (true) { + + // Clear the output buffer to avoid any unwanted output + if (ob_get_level()) { + ob_end_clean(); + } + + // Set headers for Excel file download + header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); + header('Content-Disposition: attachment; filename="' . $export_data['file_name'] . '"'); + header('Content-Transfer-Encoding: binary'); + header('Cache-Control: must-revalidate'); + header('Pragma: public'); + header('Expires: 0'); + + // Output file contents + rewind($tempFile); + fpassthru($tempFile); + + // Close and remove temporary file + fclose($tempFile); + + return true; // Excel file successfully generated and exported + + } else { + + return false; // Batch operation failed + } + } - if ($return == 0) { - dd('error', "Insufficient deposit amount."); - }else if($return == 1){ - dd('error', "The policy does not have a CD account number."); - } - if (!$return) { - dd('error', "No data was found"); - } } - public function truncateFileData() //truncateFileDataIn DB (de activate rows) { $file_id = $this->request->uri->getSegment(3); @@ -1164,9 +1228,6 @@ class EmployeeController extends AdminController } } - - - public function previewTemplate($id = null) { @@ -1249,7 +1310,6 @@ class EmployeeController extends AdminController echo $htmlContent; } - public function errorListExportImport($file_id) { @@ -1340,6 +1400,7 @@ class EmployeeController extends AdminController { $client_policy_id = $this->request->uri->getSegment(3); $policy_details = $this->clientPolicyModel->find($client_policy_id); + $insurer_details = $this->insurerModel->where('id', $policy_details['insurer_id'])->first(); $policy_terms = isset($policy_details['policy_terms']) ? true : false; $si_enhancement_true_or_false = 1; @@ -1366,7 +1427,7 @@ class EmployeeController extends AdminController } $message = isset($message) ? ($message . ' not defined for choosed policy') : null; - return $this->respond(['dataStatus' => true, 'code' => 200, 'message' => $message, 'si_enhancement' => $si_enhancement_true_or_false], 200); + return $this->respond(['dataStatus' => true, 'code' => 200, 'message' => $message, 'si_enhancement' => $si_enhancement_true_or_false, 'insurer_multi_event' => $insurer_details['is_multi_event']], 200); } diff --git a/app/Controllers/EmployeeServiceController.php b/app/Controllers/EmployeeServiceController.php index 9ba53688..3cbcb39b 100644 --- a/app/Controllers/EmployeeServiceController.php +++ b/app/Controllers/EmployeeServiceController.php @@ -942,7 +942,7 @@ class EmployeeServiceController extends AdminController if(in_array($file['action'],['inception','addition','dependent_addition','deletion','correction','si_enhancement','enrollment']))// the below funcitons are only for I,DA,A { - $employee_data_group_by_family = data_group_by_family($excel_data,'excel','enrollment'); + $employee_data_group_by_family = data_group_by_family($excel_data,'excel',($file['action'] == 'enrollment' ? 'enrollment' : '')); // dd($employee_data_group_by_family); $is_self_available_in_policy_terms = false; if($policy_details['policy_type_id'] == 3) // GMC parents @@ -1748,10 +1748,10 @@ class EmployeeServiceController extends AdminController public function getFileMetaDataByFileId($file_id, $status = 'success'){ $data = $this->fileModel - ->select('files.*, clients.client_name, clients.short_name, policies.name as policy_name,client_branch.branch_code') + ->select('files.*, clients.client_name, clients.short_name, policy_type.policy_type as policy_name,client_branch.branch_code') ->join('clients', 'clients.id = files.client_id') ->join('client_policy', 'client_policy.id = files.policy_id') - ->join('policies', 'policies.id = client_policy.policy_id') + ->join('policy_type', 'policy_type.id = client_policy.policy_type_id') ->join('client_branch', 'client_branch.id = files.client_branch_id','left') ->where('files.id', $file_id) ->first(); diff --git a/app/Controllers/MasterController.php b/app/Controllers/MasterController.php index 0d7fde57..18e73a8e 100644 --- a/app/Controllers/MasterController.php +++ b/app/Controllers/MasterController.php @@ -9,6 +9,8 @@ use Psr\Log\LoggerInterface; use CodeIgniter\API\ResponseTrait; use CodeIgniter\Files\File; +use App\Helpers\DepositHelper; + use App\Models\UserModel; use App\Models\ClientModel; use App\Models\ClientBranchModel; @@ -26,6 +28,7 @@ use App\Models\TPAModel; use App\Models\StateModel; use App\Models\PolicyTypeModel; use App\Models\CDMasterModel; +use App\Models\ClientDepositModel; class MasterController extends AdminController { @@ -48,6 +51,7 @@ class MasterController extends AdminController protected $policyTypeModel; protected $CDMasterModel; protected $clientModel; + protected $clientDepositModel; @@ -74,9 +78,12 @@ class MasterController extends AdminController $this->policyTypeModel = new PolicyTypeModel(); $this->CDMasterModel = new CDMasterModel(); $this->clientModel = new ClientModel(); + $this->clientDepositModel = new ClientDepositModel(); } + + //start insurer public function insurerList() { $this->myLogger->logme('error','Insurer list function called'); @@ -108,7 +115,6 @@ class MasterController extends AdminController } } - public function removeInsurerBranch($id = null) { $this->myLogger->logme('error','Insurer Branch Remove function called'); @@ -124,7 +130,6 @@ class MasterController extends AdminController } } - public function editInsurerOnboarding($id = null) { @@ -156,7 +161,6 @@ class MasterController extends AdminController } - public function insurerOnboarding() { @@ -187,7 +191,6 @@ class MasterController extends AdminController } - public function createInsurerGeneralInfo() { @@ -244,7 +247,6 @@ class MasterController extends AdminController } } - public function insurerBranchList($id = null) { $this->myLogger->logme('error','Edit Insurer Onboarding function called'); @@ -257,9 +259,6 @@ class MasterController extends AdminController exit(); } - - - public function editInsurerGeneralInfo() { $this->myLogger->logme('error','edit Insurer general info function called'); @@ -289,7 +288,6 @@ class MasterController extends AdminController } } - public function editInsurerGet($id = null) { $this->myLogger->logme('error','Edit TPA Onboarding function called'); @@ -339,15 +337,12 @@ class MasterController extends AdminController } } - - -// Insurer Ends + // Insurer Ends -// TPA Start - + // TPA Start public function tpaList() { @@ -707,7 +702,6 @@ class MasterController extends AdminController } } - public function removeKYCDocs($id = null) { $this->myLogger->logme('error','KYC Docs Remove function called'); @@ -748,9 +742,6 @@ class MasterController extends AdminController } - - - public function createKYCInfo() { @@ -767,9 +758,6 @@ class MasterController extends AdminController } } - - - public function createKycDocs() { @@ -794,7 +782,6 @@ class MasterController extends AdminController } } - public function editKYCOnboarding($id = null) { @@ -814,9 +801,6 @@ class MasterController extends AdminController } - - - public function kycDocsList($id = null) { @@ -831,8 +815,6 @@ class MasterController extends AdminController exit(); } - - public function editKYCInfo() { $this->myLogger->logme('error','edit KYC general info function called'); @@ -847,7 +829,6 @@ class MasterController extends AdminController } } - public function editKYCGet($id = null) { $this->myLogger->logme('error','Edit KYC Onboarding function called'); @@ -860,8 +841,6 @@ class MasterController extends AdminController exit(); } - - public function editKYCDocs() { $this->myLogger->logme('error','edit KYC Docs function called'); @@ -875,16 +854,12 @@ class MasterController extends AdminController echo json_encode(array("status" => false)); } } - - - - - //Ends KYC - //Start Policy + //Start Policy + public function policyTypeList() { $this->myLogger->logme('error','Policy Type list function called'); @@ -901,7 +876,6 @@ class MasterController extends AdminController // $this->loadLayout('insurer_onboarding', $data); } - public function policyTypeRemove($id = null) { $this->myLogger->logme('error','Policy Type Remove function called'); @@ -956,9 +930,6 @@ class MasterController extends AdminController } - - - public function createPolicies() { $this->myLogger->logme('error','Policies CREATE function called'); @@ -980,9 +951,6 @@ class MasterController extends AdminController } } - - - public function createPolicyType() { $this->myLogger->logme('error','Policy Type CREATE function called'); @@ -999,7 +967,6 @@ class MasterController extends AdminController } } - public function editPolicyTypeOnboarding($id = null) { @@ -1020,7 +987,6 @@ class MasterController extends AdminController } - public function editPolicyType() { $this->myLogger->logme('error','edit Policy general info function called'); @@ -1035,7 +1001,6 @@ class MasterController extends AdminController } } - public function policesList($id = null) { $this->myLogger->logme('error','Edit Policies Onboarding function called'); @@ -1066,8 +1031,6 @@ class MasterController extends AdminController exit(); } - - public function editPoliciesGet($id = null) { $this->myLogger->logme('error','Edit Policies Onboarding function called'); @@ -1078,7 +1041,6 @@ class MasterController extends AdminController exit(); } - public function editPolicies() { $this->myLogger->logme('error','edit Policy general info function called'); @@ -1093,9 +1055,11 @@ class MasterController extends AdminController echo json_encode(array("status" => false)); } } + + //end policies - + //start CD Master list public function CDMasterList() { @@ -1105,7 +1069,6 @@ class MasterController extends AdminController $this->loadLayout('cd_master_list', $data); } - public function createCDMasterData() { @@ -1113,13 +1076,30 @@ class MasterController extends AdminController $date = (string) $this->request->getPost('opening_date'); $data['opening_date'] = date('Y-m-d', strtotime($date)); + // Prepare the array with data + $cd_tranction_data = [ + 'amount' => $data['opening_bal'], + 'sub_type_id' => 7, + 'client_id' => $data['client_id'], + 'client_policy_id' => null, + 'cd_ac_no' => $data['cd_ac_no'], + 'endorsement_no' => null, + 'insurer_id' => $data['insurer_id'], + 'description' => 'opening Amount', + 'transaction_type' => 'Credit', + 'updated_by' => 1, + ]; + $loggedInUserID = get_session_userid(); + if ($data) { $insert = $this->CDMasterModel->insert($data); if ($insert) { + $response = DepositHelper::saveDeposit($cd_tranction_data, $loggedInUserID); + session()->setFlashdata('success', "Cash Deposite Master Added Successfully"); return redirect()->to(base_url('/master/cash_deposite/list')); } else { @@ -1134,7 +1114,6 @@ class MasterController extends AdminController } } - public function editCDMasterData($id = null) { @@ -1147,6 +1126,18 @@ class MasterController extends AdminController $insert = $this->CDMasterModel->where('id', $id)->set($data)->update(); + $cd_transaction_updated_data = [ + 'balance' => $data['opening_bal'], + 'amount' => $data['opening_bal'] + ]; + + $cd_tranction = $this->clientDepositModel + ->where('client_id', $data['client_id']) + ->where('insurer_id', $data['insurer_id']) + ->where('cd_ac_no', $data['cd_ac_no']) + ->where('sub_type', 7) + ->set($cd_transaction_updated_data)->update(); + if ($insert) { session()->setFlashdata('success', "Cash Deposite Master Updated Successfully"); @@ -1187,8 +1178,8 @@ class MasterController extends AdminController } } - - public function removeCDMaster($id){ + public function removeCDMaster($id) + { $this->myLogger->logme('error','CDMaster Remove function called'); $data['updated_by'] = get_session_userid(); diff --git a/app/Controllers/PendingActionsController.php b/app/Controllers/PendingActionsController.php index c7764902..b47a4b2f 100644 --- a/app/Controllers/PendingActionsController.php +++ b/app/Controllers/PendingActionsController.php @@ -86,7 +86,7 @@ class PendingActionsController extends AdminController $builder = $this->db->table('client_policy cp'); $builder->select(' clients.client_name, - policies.name as policy_name, + policy_type.policy_type as policy_name, cp.id as client_policy_id, cp.client_id, cp.policy_id, @@ -102,7 +102,7 @@ class PendingActionsController extends AdminController $builder->join('employee_polices ep', 'cp.id = ep.client_policy_id AND ep.is_active = 1', 'left'); $builder->join('clients', 'cp.client_id = clients.id'); $builder->join('client_branch cb', 'cb.id = cp.client_branch_id'); - $builder->join('policies', 'cp.policy_id = policies.id'); + $builder->join('policy_type', 'cp.policy_type_id = policy_type.id'); $builder->where('cp.is_active', 1); $builder->where('cp.open_for_enrollment', 1); $builder->where('cp.is_addon', 1); @@ -234,8 +234,7 @@ class PendingActionsController extends AdminController client_branch.id as branch_id, client_branch.branch_name, client_policy.id as client_policy_id, - policies.name as policy_name, - policies.id as pid, + policy_type.policy_type as policy_name, emp_endorsement.id, emp_endorsement.pk, emp_endorsement.endorsement_id, @@ -250,7 +249,7 @@ class PendingActionsController extends AdminController ->join('client_policy', 'employee_polices.client_policy_id = client_policy.id AND client_policy.is_active = 1 AND client_policy.policy_status = 1') ->join('clients', 'client_policy.client_id = clients.id AND clients.is_active = 1') ->join('client_branch', 'client_branch.id = client_policy.client_branch_id') - ->join('policies', 'client_policy.policy_id = policies.id AND policies.is_active = 1') + ->join('policy_type', 'client_policy.policy_type_id = policy_type.id') ->where([ 'emp_endorsement.actions' => 'si', 'emp_endorsement.is_active' => 1, @@ -322,8 +321,7 @@ class PendingActionsController extends AdminController client_branch.id as branch_id, client_branch.branch_name, client_policy.id as client_policy_id, - policies.name as policy_name, - policies.id as pid, + policy_type.policy_type as policy_name, emp_endorsement.pk, emp_endorsement.id, emp_endorsement.group_key, @@ -338,7 +336,7 @@ class PendingActionsController extends AdminController ->join('client_policy', 'employee_polices.client_policy_id = client_policy.id AND client_policy.is_active = 1 AND client_policy.policy_status = 1', 'left') ->join('clients', 'client_policy.client_id = clients.id AND clients.is_active = 1', 'left') ->join('client_branch', 'client_branch.id = client_policy.client_branch_id', 'left') - ->join('policies', 'client_policy.policy_id = policies.id AND policies.is_active = 1', 'left') + ->join('policy_type', 'client_policy.policy_type_id = policy_type.id', 'left') ->where([ 'emp_endorsement.actions' => 'd', 'emp_endorsement.is_active' => 1, @@ -346,7 +344,7 @@ class PendingActionsController extends AdminController 'emp_endorsement.endorsement_id' => null, 'emp_endorsement.table_name' => 'employee_polices' ]) - ->groupBy('emp_endorsement.pk, emp_endorsement.emp_code, emp_endorsement.actions, emp_endorsement.name'); + ->groupBy('emp_endorsement.pk, emp_endorsement.emp_code, emp_endorsement.actions, emp_endorsement.name'); // Build the main query $builder = $this->db->table('clients'); @@ -406,7 +404,7 @@ class PendingActionsController extends AdminController ->select('ep.client_policy_id') ->select('c.client_name') ->select('c.short_name') - ->select('p.name as policy_name') + ->select('policy_type.policy_type as policy_name') ->select('ep.uhid') ->select('cb.branch_name, cb.id as branch_id') ->select("($subQueryExport) AS batch_export_count", false) @@ -414,11 +412,11 @@ class PendingActionsController extends AdminController ->join('client_policy cp', 'ep.client_policy_id = cp.id AND cp.is_active = 1 AND cp.policy_status = 1') ->join('clients c', 'c.id = cp.client_id') ->join('client_branch cb', 'cb.id = cp.client_branch_id') - ->join('policies p', 'p.id = cp.policy_id') + ->join('policy_type', 'policy_type.id = cp.policy_type_id') ->where('ep.uhid IS NULL') ->where('ep.status', 'active') ->where('ep.is_active', 1) - ->groupBy('ep.client_policy_id, ep.uhid, c.short_name, p.name') + ->groupBy('ep.client_policy_id, ep.uhid, c.short_name, policy_type.policy_type') ->get(); // Fetch the results @@ -459,7 +457,7 @@ class PendingActionsController extends AdminController employee_polices.tpa_id, clients.short_name, clients.client_name, - policies.name as policy_name, + policy_type.policy_type as policy_name, clients.id as client_id, client_branch.id as branch_id, client_branch.branch_name @@ -470,7 +468,7 @@ class PendingActionsController extends AdminController $builder->join('client_policy', 'employee_polices.client_policy_id = client_policy.id AND client_policy.is_active = 1 AND client_policy.policy_status = 1'); $builder->join('clients', 'clients.id = client_policy.client_id'); $builder->join('client_branch', 'client_branch.id = client_policy.client_branch_id'); - $builder->join('policies', 'policies.id = client_policy.policy_id'); + $builder->join('policy_type', 'policy_type.id = client_policy.policy_type_id'); $builder->where('employee_polices.tpa_id', null); $builder->where('employee_polices.uhid IS NOT NULL'); $builder->where('employee_polices.status', 'active'); diff --git a/app/Helpers/excel_import_export_helper.php b/app/Helpers/excel_import_export_helper.php index a86e5d80..b7eb87c8 100644 --- a/app/Helpers/excel_import_export_helper.php +++ b/app/Helpers/excel_import_export_helper.php @@ -665,7 +665,7 @@ if(!function_exists('generate_insurer_based_excel')){ $rowData = []; foreach ($excel_header_array as $header) { - $fieldName = $header['header_name']; + $fieldName = $header['db_column_name']; if ($fieldName === 'index') { $value = $serialNumber; diff --git a/app/Models/CDMasterModel.php b/app/Models/CDMasterModel.php index 0e5c39a1..b936650f 100644 --- a/app/Models/CDMasterModel.php +++ b/app/Models/CDMasterModel.php @@ -61,24 +61,33 @@ class CDMasterModel extends Model return $data; } - public function getCDMasterList(){ + public function getCDMasterList() + { $query = $this->db->table('cd_master') - ->select('cd_master.*, clients.client_name, clients.short_name, insurers.name AS insurer_name, user_profiles.first_name AS user_name, IFNULL(cd_ac_counts.cd_ac_no_count, 0) AS cd_ac_no_count') - ->join('clients', 'clients.id = cd_master.client_id') - ->join('insurers', 'insurers.id = cd_master.insurer_id') - ->join('user_profiles', 'user_profiles.id = cd_master.created_by') - ->join( - '(SELECT cd_master.cd_ac_no, COUNT(client_policy.cd_ac_no) AS cd_ac_no_count - FROM cd_master - JOIN client_policy ON client_policy.cd_ac_no = cd_master.cd_ac_no - GROUP BY cd_master.cd_ac_no) AS cd_ac_counts', - 'cd_ac_counts.cd_ac_no = cd_master.cd_ac_no', - 'left' - ) - ->where('cd_master.is_active', 1) - ->get(); - + ->select('cd_master.*, clients.client_name, clients.short_name, insurers.name AS insurer_name, user_profiles.first_name AS user_name, IFNULL(cd_ac_counts.cd_ac_no_count, 0) AS cd_ac_no_count, IFNULL(cd_ac_counts_for_cdt.cd_ac_no_count_cd_tranction, 0) AS cd_ac_no_count_cd_tranction') + ->join('clients', 'clients.id = cd_master.client_id') + ->join('insurers', 'insurers.id = cd_master.insurer_id') + ->join('user_profiles', 'user_profiles.id = cd_master.created_by') + ->join( + '(SELECT cd_master.cd_ac_no, COUNT(client_policy.cd_ac_no) AS cd_ac_no_count + FROM cd_master + JOIN client_policy ON client_policy.cd_ac_no = cd_master.cd_ac_no + GROUP BY cd_master.cd_ac_no) AS cd_ac_counts', + 'cd_ac_counts.cd_ac_no = cd_master.cd_ac_no', + 'left' + ) + ->join( + '(SELECT cd_master.cd_ac_no, COUNT(cash_deposit.cd_ac_no) AS cd_ac_no_count_cd_tranction + FROM cd_master + JOIN cash_deposit ON cash_deposit.cd_ac_no = cd_master.cd_ac_no + GROUP BY cd_master.cd_ac_no) AS cd_ac_counts_for_cdt', + 'cd_ac_counts_for_cdt.cd_ac_no = cd_master.cd_ac_no', + 'left' + ) + ->where('cd_master.is_active', 1) + ->get(); + $result = $query->getResultArray(); return $result; } diff --git a/app/Models/ClientBranchModel.php b/app/Models/ClientBranchModel.php index c6083a49..ee36cbb4 100644 --- a/app/Models/ClientBranchModel.php +++ b/app/Models/ClientBranchModel.php @@ -24,6 +24,7 @@ class ClientBranchModel extends Model "address2", "gst", "sez", + "units", ]; public function getBranchAndContactByBranchId($branch_id){ diff --git a/app/Models/ClientModel.php b/app/Models/ClientModel.php index d1d35a2f..a43c1812 100644 --- a/app/Models/ClientModel.php +++ b/app/Models/ClientModel.php @@ -68,11 +68,11 @@ class ClientModel extends Model 'client_policy.id as client_policy_id', 'client_policy.policy_terms', 'client_policy.policy_no', - 'p.name', + // 'p.name', 'pt.policy_type', ]) ->join('client_branch', 'client_branch.id = client_policy.client_branch_id') - ->join('policies p', 'p.id = client_policy.policy_id') + // ->join('policies p', 'p.id = client_policy.policy_id') ->join('policy_type pt','client_policy.policy_type_id = pt.id') ->where('client_policy.client_id',$client['id']) ->where('client_policy.is_active', 1) diff --git a/app/Models/ClientPolicyModel.php b/app/Models/ClientPolicyModel.php index b75ca69c..05d09c98 100644 --- a/app/Models/ClientPolicyModel.php +++ b/app/Models/ClientPolicyModel.php @@ -45,6 +45,7 @@ class ClientPolicyModel extends Model "client_branch_id", "cd_ac_no", "gst", + "enrolment_visibility", ]; public function getClientPolicyById($id){ @@ -73,7 +74,6 @@ class ClientPolicyModel extends Model ->select('client_policy.*') ->select('insurers.name as insurer_name, insurers.short_name as insurer_short') ->select('tpa.name as tpa_name, tpa.short_name as tpa_short') - ->select('policies.name as policy_name, policies.policy_type_id') ->select('policy_type.policy_type as policy_type_name') ->select('insurer_branch.branch_name as insurer_branch_name, insurer_branch.branch_code as insurer_branch_code') ->select('tpa_branch.branch_name as tpa_branch_name, tpa_branch.branch_code as tpa_branch_code') @@ -83,8 +83,7 @@ class ClientPolicyModel extends Model ->join('insurer_branch', 'client_policy.insurer_branch_id = insurer_branch.id') ->join('tpa', 'tpa.id = client_policy.tpa_id', 'left') ->join('tpa_branch', 'client_policy.tpa_branch_id = tpa_branch.id', 'left') - ->join('policies', 'policies.id = client_policy.policy_id') - ->join('policy_type', 'policy_type.id = policies.policy_type_id') + ->join('policy_type', 'policy_type.id = client_policy.policy_type_id') ->join('client_branch', 'client_branch.id = client_policy.client_branch_id') ->where('client_policy.client_id', $client_id) ->where('client_policy.policy_status', 1) @@ -186,14 +185,16 @@ class ClientPolicyModel extends Model return $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') - ->select('policies.name as policy_name') + ->select('clients.client_name as clientname, clients.short_name as clientshort, client_policy.policy_no') + // ->select('policies.name as policy_name') + ->select('policy_type.policy_type') ->select('user_profiles.first_name as username') ->join('user_profiles', 'user_profiles.id = cash_deposit.created_by', 'left') ->join('insurers', 'insurers.id = cash_deposit.insurer_id', 'left') ->join('clients', 'clients.id = cash_deposit.client_id', 'left') ->join('client_policy', 'client_policy.id = cash_deposit.client_policy_id', 'left') - ->join('policies', 'policies.id = client_policy.policy_id', 'left') + // ->join('policies', 'policies.id = client_policy.policy_id', 'left') + ->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) @@ -263,25 +264,13 @@ public function getBalances($clientId) public function getDepositlistsummary($id) { - // return $this->db->table('cash_deposit') - // ->select('insurer_id') - // ->select('SUM(CASE WHEN transaction_type = "Credit" THEN amount ELSE -amount END) AS balance') - // ->where('client_id', $id) - // ->groupBy('insurer_id') - // ->get() - // ->getResult(); - return $this->db->table('cash_deposit') - ->select('cash_deposit.insurer_id, cash_deposit.cd_ac_no') - ->select('(SUM(CASE WHEN cash_deposit.transaction_type = \'Credit\' THEN cash_deposit.amount ELSE -cash_deposit.amount END) + cd_master.opening_bal) AS balance') - ->join('cd_master', 'cd_master.cd_ac_no = cash_deposit.cd_ac_no') - ->where('cash_deposit.client_id', $id) - ->groupBy(['cash_deposit.insurer_id', 'cash_deposit.cd_ac_no', 'cd_master.opening_bal']) - ->orderBy('cash_deposit.insurer_id', 'DESC') - ->orderBy('cash_deposit.cd_ac_no', 'DESC') - ->get() - ->getResult(); - + ->select('insurer_id') + ->select('SUM(CASE WHEN transaction_type = "Credit" THEN amount ELSE -amount END) AS balance') + ->where('client_id', $id) + ->groupBy('insurer_id') + ->get() + ->getResult(); } @@ -365,6 +354,34 @@ public function getClientPolicyByPolicyType($client_id, $type){ } +public function getPolicyTypeForPolicyBinding($client_id){ + + $result = $this->table('client_policy') + ->select('policy_type.*, client_policy.id as client_policy_id, client_policy.policy_no') + ->join('policy_type', 'policy_type.id = client_policy.policy_type_id') + ->where('client_policy.client_id', $client_id) + ->where('client_policy.is_active', 1) + ->whereIn('policy_type.id', [2,3]) + ->findAll(); + + return $result; + + +} + + +public function getCliendDataForExcelFileName($client_policy_id){ + + return $this->table('client_policy') + ->select('clients.short_name, policy_type.policy_type, client_branch.branch_code') + ->join('clients', 'clients.id = client_policy.client_id') + ->join('client_branch', 'client_branch.id = client_policy.client_branch_id') + ->join('policy_type', 'policy_type.id = client_policy.policy_type_id') + ->where('client_policy.id', $client_policy_id) + ->where('client_policy.is_active', 1) + ->first(); + +} } diff --git a/app/Models/EmployeePolicyModel.php b/app/Models/EmployeePolicyModel.php index 160eb71e..7f2b5fd0 100644 --- a/app/Models/EmployeePolicyModel.php +++ b/app/Models/EmployeePolicyModel.php @@ -75,7 +75,7 @@ class EmployeePolicyModel extends Model return $data; } -// ----------------------------------------------------------------------------------------------------- +// ---------------------------------------------------------------------------------------------------------- public function getEmployeePolicy($client_id = 0, $policy_id=0, $status=0, $branch_id=0, $emp_code="", $emp_name="") { @@ -143,8 +143,6 @@ class EmployeePolicyModel extends Model return $result->findAll(); } - - //for emp onboard do not change public function checkExistingEmpPolicy($arr) { @@ -153,8 +151,7 @@ class EmployeePolicyModel extends Model ->where('is_active',1) ->find(); } - - //------------------------------------------------------------------ +//------------------------------------------------------------------------------------------------------- public function getInceptionEmployeeDataForExportExcel($ref_data) @@ -173,6 +170,21 @@ class EmployeePolicyModel extends Model $id = 'uhid'; } + $datas = ''; + if($event === 'inception'){ + + $datas = 'I'; + + }else if($event === 'dependent_addition'){ + + $datas = 'DA'; + + }else if($event === 'addition'){ + + $datas = 'A'; + + } + $sql = " SELECT employees.name AS emp_name, @@ -182,8 +194,19 @@ class EmployeePolicyModel extends Model employees.change_event AS change_event, employees.relationship AS emp_relationship, employees.relationship_code AS emp_relationship_code, + '$datas' 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, + TIMESTAMPDIFF(YEAR, employees.dob, CURDATE()) AS emp_age, employees.emp_type as emp_type, + employee_polices.id as primaryKey, employee_polices.tpa_id, @@ -192,16 +215,23 @@ class EmployeePolicyModel extends Model employee_polices.basic_cover_si, employee_polices.date_coverage, employee_polices.policy_end_date, - employee_polices.days, + employee_polices.days as no_of_days, employee_polices.premium, - employee_polices.rata_premimum, + employee_polices.rata_premimum as pro_rata_premium, employee_polices.gst, (employee_polices.rata_premimum + employee_polices.gst) AS total, batch_data.emp_policy_id, batch_data.bl AS batch_list_batch_code, - batch_data.bf AS batch_files_batch_code + batch_data.bf AS batch_files_batch_code, + + CASE + WHEN client_branch.sez = 0 THEN 'NON-SEZ' + WHEN client_branch.sez = 1 THEN 'SEZ' + END as sez + FROM employee_polices LEFT JOIN employees ON employees.id = employee_polices.employee_id + LEFT JOIN client_branch ON client_branch.id = employees.client_branch_id LEFT JOIN ( SELECT batch_list.emp_policy_id, @@ -220,7 +250,6 @@ class EmployeePolicyModel extends Model AND employee_polices.status = 'active' AND employees.is_active = 1 AND employees.emp_status = 'active' - "; // Get the result set @@ -254,9 +283,20 @@ class EmployeePolicyModel extends Model employees.dob AS emp_dob, employees.gender AS emp_gender, employees.client_id AS emp_client_id, - employees.emp_type as emp_type, + employees.emp_type as emp_temp_codeype, employee_polices.uhid, employees.relationship_code, + employees.relationship, + 'C' 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, + batch_data.emp_policy_id, batch_data.bl AS batch_list_batch_code, batch_data.bf AS batch_files_batch_code @@ -321,7 +361,19 @@ class EmployeePolicyModel extends Model 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 risk_id, employee_polices.pre_existing_alignments, employee_polices.policy_end_date, @@ -338,11 +390,18 @@ class EmployeePolicyModel extends Model 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_premimum, + 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, - ((sidata.new_si_premium - employee_polices.rata_premimum) * (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) AS total + ROUND( + ((sidata.new_si_premium - employee_polices.rata_premimum) * + (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 + ) AS total FROM emp_endorsement a @@ -438,12 +497,23 @@ class EmployeePolicyModel extends Model employees.dob AS emp_dob, employees.gender AS emp_gender, employees.relationship AS emp_relationship, + employees.relationship_code AS emp_relationship_code, employees.emp_type as emp_type, + 'D' 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.basic_cover_si, - employee_polices.uhid as risk_id, + employee_polices.uhid as uhid, employee_polices.policy_end_date, - employee_polices.rata_premimum as premium, + employee_polices.premium, + employee_polices.rata_premimum as pro_rata_premium, batch_data.emp_policy_id AS emp_policy_id, batch_data.bl AS batch_list_batch_code, @@ -516,96 +586,6 @@ class EmployeePolicyModel extends Model } - public function updateTPAIDorUHID($update_data) - { - $client_id = $update_data['client_id']; - $client_policy_id = $update_data['client_policy_id']; - $name = $update_data['name']; - $emp_code = $update_data['emp_code']; - $uhid = $update_data['uhid']; - $tpa_id = $update_data['tpa_id']; - - $query = " - UPDATE employee_polices - JOIN employees ON employees.id = employee_polices.employee_id - SET employee_polices.tpa_id = '{$tpa_id}', - employee_polices.uhid = '{$uhid}' - WHERE employees.emp_code = '{$emp_code}' - AND employees.name = '{$name}' - AND employees.client_id = '{$client_id}' - AND employee_polices.client_policy_id = '{$client_policy_id}' - "; - - $this->query($query); - - } - - - public function updateCorrectionData($update_data) - { - - $emp_code = $update_data['emp_code']; - $uhid = $update_data['uhid']; - $endorsement_id = $update_data['tpa_id']; - - $sql = " - UPDATE emp_endorsement - JOIN employees ON employees.id = emp_endorsement.pk - JOIN employee_polices ON employees.id = employee_polices.employee_id - SET emp_endorsement.endorsement_id = '$endorsement_id', emp_endorsement.status = 'complete' - WHERE employees.emp_code = '$emp_code' - AND employee_polices.uhid = '$uhid' - "; - $query = $this->query($sql); - } - - - public function updateEndoresmentIdForSIEnhancement($update_data){ - - $client_id = $update_data['client_id']; - $client_policy_id = $update_data['client_policy_id']; - $emp_name = $update_data['emp_name']; - $emp_code = $update_data['emp_code']; - $endorsement_id = $update_data['endorsement_id']; - - $sql = " - UPDATE emp_endorsement - JOIN employee_polices ON employee_polices.id = emp_endorsement.pk - JOIN employees ON employee_polices.employee_id = employees.id - SET emp_endorsement.endorsement_id = '$endorsement_id', emp_endorsement.status = 'complete' - WHERE emp_endorsement.emp_code = '$emp_code' - AND employees.client_id = '$client_id' - AND employee_polices.client_policy_id = '$client_policy_id' - AND emp_endorsement.actions = 'si' - AND emp_endorsement.name = '$emp_name' - "; - $query = $this->query($sql); - - } - - - public function updateEndoresmentIdForDeletion($update_data) - { - - $client_id = $update_data['client_id']; - $client_policy_id = $update_data['client_policy_id']; - $emp_name = $update_data['emp_name']; - $emp_code = $update_data['emp_code']; - $endorsement_id = $update_data['endorsement_id']; - - $sql = " - UPDATE emp_endorsement - JOIN employee_polices ON employee_polices.id = emp_endorsement.pk - JOIN employees ON employee_polices.employee_id = employees.id - SET emp_endorsement.endorsement_id = '$endorsement_id', emp_endorsement.status = 'complete' - WHERE employees.emp_code = '$emp_code' - AND employees.client_id = '$client_id' - AND employee_polices.client_policy_id = '$client_policy_id' - AND employees.name = '$emp_name' - "; - $query = $this->query($sql); - } - public function fetchEmpEndorsementData($fetch_data) { @@ -668,7 +648,8 @@ class EmployeePolicyModel extends Model } - // //for emp onboard do not change + //for emp onboard do not change + // public function checkExistingEmpPolicy($arr) // { // return $this->where('employee_id',$arr['employee_id']) @@ -814,7 +795,8 @@ class EmployeePolicyModel extends Model ->get()->getResultArray(); } - public function getECardDataUsingMd5($client_policy_id, $emp_code){ + public function getECardDataUsingMd5($client_policy_id, $emp_code) + { $result = $this->db->table('employees e') ->select('e.id, diff --git a/app/Models/InsurerExcelExportTemplateModel.php b/app/Models/InsurerExcelExportTemplateModel.php new file mode 100644 index 00000000..749a818a --- /dev/null +++ b/app/Models/InsurerExcelExportTemplateModel.php @@ -0,0 +1,23 @@ + - - - + + - diff --git a/app/Views/cd_master_list.php b/app/Views/cd_master_list.php index 6f781f49..30c848f6 100644 --- a/app/Views/cd_master_list.php +++ b/app/Views/cd_master_list.php @@ -60,7 +60,9 @@ table.dataTable thead th {