diff --git a/app/Config/Routes.php b/app/Config/Routes.php index 4778427f..80babc57 100644 --- a/app/Config/Routes.php +++ b/app/Config/Routes.php @@ -14,6 +14,10 @@ $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->get("view", "EmployeeController::viewECard/$1"); + $routes->post("add_advertise_image", "AppContentManagementController::add_advertise_image"); @@ -107,6 +111,7 @@ $routes->group("/client", ["filter" => "authMVC"], function ($routes) { $routes->get("list/(:any)", "ClientController::getClientPolicyById/$1"); $routes->post("policyGMCTerms", "ClientController::policyGMCTerms"); $routes->get("getterms", "ClientController::getterms"); + $routes->get("remove/(:any)", "ClientController::removePolicy/$1"); }); $routes->group("kyc", ["filter" => "authMVC"], function ($routes) { @@ -136,7 +141,11 @@ $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->match(['get','post'],'enrollment-list','EmployeeController::enrollmentClientList'); + $routes->get("empby_client_clientbranch/(:any)/(:any)", "EmployeeController::empby_client_clientbranch/$1/$2"); $routes->get("truncate/(:any)", "EmployeeController::truncateFileData/$1"); + $routes->get("test-rack-rate", "EmployeeController::testRackRate"); + $routes->post("test-rack-rate", "EmployeeController::testRackRate"); }); @@ -246,7 +255,6 @@ $routes->group("/util", ["filter" => "authMVC"], function ($routes) { $routes->get("fetch-emp-count/(:any)", "EmployeeController::getEmpCount/$1"); $routes->get("init-Emp-onboard/(:any)", "EmployeeController::initiateManualEmployeesOnboardProcess/$1"); $routes->get("full-excel-error-file/(:any)", "EmployeeController::downloadFullExcelErrorFile/$1"); - $routes->get("id-card", "EmployeeController::viewECard/$1"); $routes->get("preview-card/(:any)", "EmployeeController::previewTemplate/$1"); $routes->get("export-import-error-list/(:any)", "EmployeeController::errorListExportImport/$1"); $routes->get("has_policy_config_completed/(:any)", "EmployeeController::hasPolicyConfigCompleted/$1"); @@ -260,10 +268,14 @@ $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->get("featch_dashboard_data/(:any)", "DashboardController::featch_dashboard_data/$1"); }); $routes->cli('cli/processjob', 'JobWorker::processJob'); $routes->cli('cli/processjobs', 'JobWorker::processJobs'); +$routes->cli('cli/enrollment_status', 'JobWorker::enrollment_status'); $routes->get("processjob", "JobWorker::processJob"); @@ -285,8 +297,10 @@ $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"); @@ -320,6 +334,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/ClientController.php b/app/Controllers/ClientController.php index 464e9a04..77bd79e8 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') @@ -229,17 +229,25 @@ class ClientController extends AdminController public function removeClient($id = null) { $this->myLogger->logme('error','Client Remove function called'); - // $data = $this->request->getPost(); - $data['updated_by'] = get_session_userid(); - $data['is_active'] = 0; - $update = $this->clientModel->update($id,$data); - if($update){ - return $this->respond(['status' => true,'code' => 200], 200); - }else{ - return $this->respond(['status' => false,'code' => 404], 200); - } - } + $client_policy_data = $this->clientPolicyModel + ->where('policy_status', 1) + ->where('Is_active', 1) + ->where('client_id', $id) + ->countAllResults(); + if($client_policy_data == 0){ + + $data['updated_by'] = get_session_userid(); + $data['is_active'] = 0; + $update = $this->clientModel->update($id,$data); + return $this->respond(['status' => true,'code' => 200], 200); + + }else{ + + return $this->respond(['status' => false,'code' => 404, 'message' => 'The Client has active policy'], 200); + } + + } public function removeClientBranch($id = null) { @@ -269,6 +277,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 "
";
@@ -319,6 +328,7 @@ class ClientController extends AdminController
             5 => 'Non EB',
             6 => 'Refund By Insurer',
             7 => 'Opening Amount',
+            8 => 'Truncated',
         ];
 
         $data['subTypeOptions'] = $subTypeOptions;
@@ -340,7 +350,6 @@ class ClientController extends AdminController
         echo view('layout/footer');
     }
 
-
     public function saveDeposit()
     {
         // Retrieve form data from POST request
@@ -377,7 +386,6 @@ class ClientController extends AdminController
         return $this->response->setJSON(['success' => $response['success']]);
     }
 
-
     public function editClientOnboarding($id = null)
     {    
 
@@ -392,8 +400,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();
@@ -409,6 +419,7 @@ class ClientController extends AdminController
         }
 
         $editData['client_policy']    = $clientPoliceData;
+        $editData['client_policy']['role'] = get_role_id();
         $editData['notification'] =$this->notificationModel->select('template_name,enabled')->where('client_id',$id)->findAll();
         $editData['placeHolders'] = ['member_name','nhance_logo','tpa_id','ecard_download_link', 'client_logo', 'policy_no', 'member_summary', 'app_link', 'post_enrollment_app_link', 'client_name'];
 
@@ -722,12 +733,14 @@ 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');
+        $insurerValue  = (string) $this->request->getPost('insurer');
         list($insurerBranchId, $insurerId) = explode('-', $insurerValue);
         
 
@@ -747,7 +760,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');
@@ -761,17 +774,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) {
@@ -799,19 +825,24 @@ class ClientController extends AdminController
 
 
         $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');
-        $data['policy_end_date']   = change_date_format($this->request->getPost('policy_end_date'), 'd-m-Y', 'Y-m-d');
+        if($data['inception_type'] == 2){
+            $data['policy_start_date'] = change_date_format($this->request->getPost('policy_start_date'), 'd-m-Y', 'Y-m-d');
+            $data['policy_end_date']   = change_date_format($this->request->getPost('policy_end_date'), 'd-m-Y', 'Y-m-d');
+            $data['reminder_date']   = change_date_format($this->request->getPost('reminder_date'), 'd-m-Y', 'Y-m-d');
+
+        }else{
+            $data['policy_start_date'] = null; 
+            $data['policy_end_date'] = null;
+            $data['reminder_date'] = null;
+        }
+
         $data['created_by']        = get_session_userid();
 
         $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);
+            $clientPoliceData['role'] = get_role_id();
+            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);
         }
@@ -825,8 +856,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);
@@ -840,11 +870,10 @@ 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');
-        $data['policy_end_date']   = change_date_format($this->request->getPost('policy_end_date'), 'd-m-Y', 'Y-m-d');
+        // $data['policy_start_date'] = change_date_format($this->request->getPost('policy_start_date'), 'd-m-Y', 'Y-m-d');
+        // $data['policy_end_date']   = change_date_format($this->request->getPost('policy_end_date'), 'd-m-Y', 'Y-m-d');
 
         $data['insured']                            = $this->request->getPost('insured');
         $data['no_of_lives']                        = $this->request->getPost('no_of_lives');
@@ -858,14 +887,38 @@ 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($data['inception_type'] == 2){
+            $data['policy_start_date'] = change_date_format($this->request->getPost('policy_start_date'), 'd-m-Y', 'Y-m-d');
+            $data['policy_end_date']   = change_date_format($this->request->getPost('policy_end_date'), 'd-m-Y', 'Y-m-d');
+            $data['reminder_date']   = change_date_format($this->request->getPost('reminder_date'), 'd-m-Y', 'Y-m-d');
+        }else{
+            $data['policy_start_date'] = null; 
+            $data['policy_end_date'] = null;
+            $data['reminder_date'] = null;
+        }
+
+        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();
 
@@ -900,7 +953,7 @@ class ClientController extends AdminController
 
         if($insert){
             $clientPoliceData =  $this->clientPolicyModel->getClientPolicyByClientId($client_id);
-
+            $clientPoliceData['role'] = get_role_id();
             // foreach ($clientPoliceData as $key => $value) {
             
             //     $clientPoliceData[$key]->policy_start_date = date('d-M-Y', strtotime($value->policy_start_date));
@@ -912,46 +965,84 @@ class ClientController extends AdminController
         }
     }
 
+    public function removePolicy($id = null)
+    {   
+        $this->myLogger->logme('error', 'Client Policy Remove function called');
+
+        $data = [
+            'updated_by' => get_session_userid(),
+            'is_active' => 0
+        ];
+
+        $emp_details = $this->employeePolicyModel
+                ->join('employees', 'employees.id = employee_polices.employee_id')
+                ->where('client_policy_id', $id)
+                ->where('employee_polices.status', 'active')
+                ->where('employee_polices.is_active', 1)
+                ->where('employees.emp_status', 'active')
+                ->where('employees.is_active', 1)
+                ->countAllResults();
+        if($emp_details == 0){
+
+            $update = $this->clientPolicyModel->where('id', $id)->set($data)->update();
+        
+            if ($update) {
+                return $this->respond(['status' => true, 'code' => 200], 200);
+            } else {
+                return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to remove policy'], 200);
+            }
+    
+        }else{
+
+            return $this->respond(['status' => false, 'code' => 404, 'message' => 'The policy has active employees'], 200);
+
+        }
+        
+    }
+
     public function createClientPolicyPremium()
     {
 
         // 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'));
@@ -963,36 +1054,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);
                     }
@@ -1003,6 +1094,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];
@@ -1010,6 +1103,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);
                     }
@@ -1019,6 +1117,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++) {
 
@@ -1028,6 +1128,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);
                     }
@@ -1049,33 +1154,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();
@@ -1087,30 +1214,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();
@@ -1122,11 +1261,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();
@@ -1135,10 +1282,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();
@@ -1147,6 +1302,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[]');
@@ -1165,11 +1326,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();
@@ -1180,11 +1350,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();
@@ -1194,10 +1372,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);
                 }
@@ -1210,6 +1395,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]);
@@ -1217,6 +1403,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);
                 }
@@ -1225,18 +1416,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)
     {
 
@@ -1293,11 +1489,18 @@ class ClientController extends AdminController
                 ->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], 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);
         }
@@ -1308,7 +1511,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;
@@ -1320,16 +1529,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")
@@ -1338,13 +1538,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';
@@ -1438,14 +1635,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);
         }
     }
 
@@ -1527,10 +1757,12 @@ class ClientController extends AdminController
                             $data['family_floaters']['parents-in-law'] =2;
                             $data['family_floaters']['either-parents-pil'] =0;
                         }else if($temp_family_floaters[$value] == '2EPORPIL'){
+                            //Parents or PIL (Any two of Father, Mother, MIl, FIL)
                             $data['family_floaters']['parents'] =0;
                             $data['family_floaters']['parents-in-law'] =0;
                             $data['family_floaters']['either-parents-pil'] =2;
                         }else if($temp_family_floaters[$value] == 'EPORPIL'){
+                            //Either Parents or PIL (Parents or Parents In Law)
                             $data['family_floaters']['parents'] =0;
                             $data['family_floaters']['parents-in-law'] =0;
                             $data['family_floaters']['either-parents-pil'] =1;
@@ -1655,7 +1887,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")
@@ -1675,12 +1906,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);
         }
 
     }
@@ -1873,7 +2103,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)
     {
 
@@ -1887,7 +2116,6 @@ class ClientController extends AdminController
 
     }
 
-
     public function fetchPolicyDataForPolicyType($client_policy_id){
 
         $client_policy_id = $this->request->getGet('client_policy_id');
@@ -1921,7 +2149,6 @@ class ClientController extends AdminController
 
     }
 
-
     public function downloadKYCDocument($file_name)
     {
 
@@ -1934,7 +2161,6 @@ class ClientController extends AdminController
         }
     }
 
-
     public function getClientBranch($client_id){
 
          $branchs = $this->clientBranchModel
@@ -1943,8 +2169,6 @@ class ClientController extends AdminController
                 ->findAll();
 
         return $this->respond(['status' => true,'code' => 200, 'data' => $branchs], 200);
-
-
     }
 
     public function getClientAllDetailsByUsingClientID($client_id)
@@ -1954,7 +2178,7 @@ class ClientController extends AdminController
 
         $builder = $db->table('clients');
         $builder->select('
-            policies.name as policy_name,
+
             policy_type.policy_type,
             insurers.name as insurer_name,
             insurers.short_name as insurer_short_name,
@@ -1968,9 +2192,9 @@ class ClientController extends AdminController
             CASE
             WHEN client_policy.base_policy IS NULL THEN "Not Appear"
             WHEN client_policy.base_policy = 0 THEN "Not Appear"
-            ELSE (SELECT policies.name 
+            ELSE (SELECT policy_type.policy_type 
                   FROM client_policy AS base_client_policy 
-                  JOIN policies ON policies.id = base_client_policy.policy_id 
+                  JOIN policy_type ON policy_type.id = base_client_policy.policy_type_id 
                   WHERE base_client_policy.id = client_policy.base_policy)
             END as base_policy_name,
 
@@ -2003,13 +2227,11 @@ class ClientController extends AdminController
         ', false);
         $builder->join('client_policy', 'client_policy.client_id = clients.id');
         $builder->join('client_branch', 'client_policy.client_branch_id = client_branch.id');
-        $builder->join('policies', 'policies.id = client_policy.policy_id');
-        $builder->join('policy_type', 'policy_type.id = policies.policy_type_id');
+        $builder->join('policy_type', 'policy_type.id = client_policy.policy_type_id');
         $builder->join('insurers', 'insurers.id = client_policy.insurer_id');
         $builder->join('tpa', 'tpa.id = client_policy.tpa_id');
         $builder->where('clients.is_active', 1);
         $builder->where('client_policy.is_active', 1);
-        $builder->where('policies.is_active', 1);
         $builder->where('policy_type.is_active', 1);
         $builder->where('client_policy.policy_status', 1);
         $builder->where('clients.id', $client_id);
@@ -2099,8 +2321,6 @@ class ClientController extends AdminController
         }
 
 
-
-
         $data['client_policy'] = $client_policy;
         $data['client_branch'] = $this->clientModel
 
@@ -2124,10 +2344,7 @@ class ClientController extends AdminController
             ->get()->getResultArray();
 
 
-       $data['client'] = $this->clientModel
-       ->select('clients.*, states.state as state')
-       ->join('states', 'states.id = clients.state')
-        ->where('clients.id', $client_id)->first();   
+       $data['client'] = $this->clientModel->where('clients.id', $client_id)->first();   
         
         
        $client_rm = $this->clientRMModel
@@ -2155,7 +2372,7 @@ class ClientController extends AdminController
        $data['heads'] = $heads;
 
         // dd($data);
-        //$this->loadLayout('client_info', $data);
+        // $this->loadLayout('client_info', $data);
 
 
        $html = view('client_info', $data);
@@ -2163,8 +2380,6 @@ class ClientController extends AdminController
 
     }
 
-
-
     public function transformArray($data, $mapping)
     {
 
@@ -2212,7 +2427,6 @@ class ClientController extends AdminController
         return json_encode($transformedData, JSON_PRETTY_PRINT);
     }
 
-
     public function transformFamilyFloaters($familyFloaters, $json)
     {
         $result = [];
@@ -2257,7 +2471,6 @@ class ClientController extends AdminController
         return implode(", ", $result);
     }
 
-
     public function deleteAdditionalRackRate($client_id, $client_policy_id, $rack_rate_type)
     {
         try {
@@ -2282,8 +2495,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)
     {
 
@@ -2301,7 +2512,6 @@ class ClientController extends AdminController
 
     }
 
-
     public function otherPolicyTermsFormSubmit()
     {
 
@@ -2325,7 +2535,6 @@ class ClientController extends AdminController
         }
     }
 
-
     public function checkPolicyType($policy_type_id, $client_branch_id, $client_id)
     {
 
@@ -2344,31 +2553,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 = [];
@@ -2387,11 +2601,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)
     {
 
@@ -2399,9 +2612,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)
@@ -2423,7 +2637,6 @@ class ClientController extends AdminController
         }
     }
  
-    
     public function checkAdditionPremiumJSON($client_id, $client_policy_id)
     {
 
@@ -2437,4 +2650,176 @@ 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 = 12;
+
+        $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();
+       
+        // dd($results, $results2);
+
+        $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();
+
+            // dd($client_policy_data);
+
+            if(isset($client_policy_data) && $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/DashboardController.php b/app/Controllers/DashboardController.php index 8642c0a5..16a4d50f 100644 --- a/app/Controllers/DashboardController.php +++ b/app/Controllers/DashboardController.php @@ -11,27 +11,119 @@ use CodeIgniter\API\ResponseTrait; use App\Models\MessageModel; use App\Models\UserMessageModel; +use App\Models\ClientModel; + +use App\Controllers\PendingActionsContrller; class DashboardController extends AdminController { - + use ResponseTrait; protected $messageModel; + protected $clientModel; protected $userMessageModel; protected $myLogger; - + public function __construct() { set_session_context('Dashboard'); $this->messageModel = new MessageModel(); $this->userMessageModel = new UserMessageModel(); $this->myLogger = \Config\Services::mylogger(); + $this->clientModel = new ClientModel(); } public function dashboard() { + $data = []; + + $pendingActionsController = new PendingActionsController; + $pendingActionsData = $pendingActionsController->getPendingActionsForDashBoard(); + + $results = $this->clientModel->select('clients.id as client_id, clients.client_name, clients.short_name, + client_branch.id as client_branch_id, client_branch.branch_name, + client_branch.branch_code, employees.id as employee_id, + employees.name as employee_name, employees.relationship, + employees.emp_code, employees.emp_status, auth_history.user_type') + ->join('client_branch', 'clients.id = client_branch.client_id', 'left') + ->join('employees', 'client_branch.id = employees.client_branch_id', 'left') + ->join('auth_history', 'employees.id = auth_history.user_id AND "employee" = auth_history.user_type', 'left') + ->findAll(); + + $groupedData = []; + $employeeId = ''; + foreach ($results as $row) { + $clientId = $row['client_id']; + $clientName = $row['client_name']; + $shortName = $row['short_name']; + $branchId = $row['client_branch_id']; + $branchName = $row['branch_name']; + $branchCode = $row['branch_code']; + if ($employeeId != $row['employee_id']) { + $employeeId = $row['employee_id']; + } else { + $employeeId = null; + } + $employeeName = $row['employee_name']; + $employeeRelationship = $row['relationship']; + $employeeEmpCode = $row['emp_code']; + $employeeEmpStatus = $row['emp_status']; + $employeeUserType = $row['user_type']; + + // Initialize the client entry if it doesn't exist + if (!isset($groupedData[$clientId])) { + $groupedData[$clientId] = [ + 'client_id' => $clientId, + 'client_name' => $clientName, + 'short_name' => $shortName, + 'branches' => [] + ]; + } + + // Initialize the branch entry if it doesn't exist + if (!isset($groupedData[$clientId]['branches'][$branchId])) { + $groupedData[$clientId]['branches'][$branchId] = [ + 'client_branch_id' => $branchId, + 'branch_name' => $branchName, + 'branch_code' => $branchCode, + 'emp_login' => 0, + 'emp_enroll' => 0, + 'employees' => [] + ]; + } + if ($employeeId !== null && $employeeRelationship == 'Self') { + // Append employee info to the branch's employees list + $groupedData[$clientId]['branches'][$branchId]['employees'][] = [ + 'employee_id' => $employeeId, + 'employee_name' => $employeeName, + 'relationship' => $employeeRelationship, + 'emp_code' => $employeeEmpCode, + 'emp_status' => $employeeEmpStatus, + 'user_type' => $employeeUserType + ]; + if (!empty($employeeUserType)) { + $groupedData[$clientId]['branches'][$branchId]['emp_login']++; + } + + // Increment emp_enroll if emp_status is not 'draft' + if ($employeeEmpStatus !== 'draft') { + $groupedData[$clientId]['branches'][$branchId]['emp_enroll']++; + } + } + $employeeId = $row['employee_id']; + } + + // Re-index the arrays to match the expected structure + foreach ($groupedData as &$client) { + $client['branches'] = array_values($client['branches']); + } + // echo "
";
+        $data['client_branch_emp_list'] = $groupedData;
+        $data['pendingActionsData'] = $pendingActionsData;
+        // print_r($data);die;
+
         echo view('layout/header');
-        echo view('DashBoard');
+        echo view('DashBoard', $data);
         echo view('layout/footer');
     }
 
@@ -41,7 +133,7 @@ class DashboardController extends AdminController
         $userId = get_session_userid();
         $roleId = 5;
         $teamId = 1;
-    
+
         if ($userId != null && $roleId != null && $teamId != null) {
             $messages = $this->messageModel->getMessagesForUser($userId, $roleId, $teamId);
             return $this->respond(['status' => true, 'code' => 200, 'message' => $messages], 200);
@@ -50,7 +142,7 @@ class DashboardController extends AdminController
             return $this->respond(['status' => false, 'code' => 404, 'message' => 'No data found'], 200);
         }
     }
-    
+
 
     public function acknowledgeMessage($messageId)
     {
@@ -62,4 +154,41 @@ class DashboardController extends AdminController
     }
 
 
+    public function featch_dashboard_data($type)
+    {
+        $pendingActionsController = new PendingActionsController;
+        $pendingActionsData = $pendingActionsController->getPendingActionsForClientData();
+
+        $data = [];
+
+        if($type == 'insurer'){
+
+            $data = $pendingActionsData['uhid'];
+
+        }else if($type == 'TPA'){
+            $data = $pendingActionsData['tpa'];
+
+        }else if($type == 'I'){
+            $data = $pendingActionsData['inception'];
+
+        }else if($type == 'D'){
+            $data = $pendingActionsData['deletion'];
+
+        }else if($type == 'C'){
+            $data = $pendingActionsData['correction'];
+
+        }else if($type == 'SI'){
+            $data = $pendingActionsData['si_enhancement'];
+
+        }else if($type == 'policy'){
+            $data = $pendingActionsData['policy'];
+
+        }else if($type == 'ticket'){
+            $data = $pendingActionsData['uhid'];
+        }
+
+        return $this->respond(['status' => true, 'data' => $data], 200);
+    }
+
+
 }
diff --git a/app/Controllers/EmpDataServiceController.php b/app/Controllers/EmpDataServiceController.php
index f1d6f143..2df33a79 100644
--- a/app/Controllers/EmpDataServiceController.php
+++ b/app/Controllers/EmpDataServiceController.php
@@ -25,6 +25,8 @@ use App\Models\NotificationModel;
 use App\Models\MessageModel;
 use App\Models\UserMessageModel;
 use App\Models\CDMasterModel;
+use App\Models\InsurerExcelExportTemplateModel;
+use App\Models\ClientBranchModel;
 
 use App\Controllers\Jobs;
 use App\Controllers\JobWorker;
@@ -54,6 +56,8 @@ class EmpDataServiceController extends BaseController
     protected $messageModel;
     protected $userMessageModel;
     protected $CDMasterModel;
+    protected $excelExportTemplateModel;
+    protected $clientBranchModel;
 
 
     public function __construct()
@@ -74,6 +78,8 @@ class EmpDataServiceController extends BaseController
         $this->messageModel        = new MessageModel();
         $this->userMessageModel          = new UserMessageModel();
         $this->CDMasterModel    = new CDMasterModel();
+        $this->excelExportTemplateModel    = new InsurerExcelExportTemplateModel();
+        $this->clientBranchModel  = new ClientBranchModel();
 
     }
 
@@ -110,7 +116,8 @@ class EmpDataServiceController extends BaseController
     }
 
 
-    public function insertBatchList($params){
+    public function insertBatchList($params)
+    {
 
         foreach ($params['batch_list_data'] as $value) {
 
@@ -142,10 +149,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 +157,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 +166,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 +181,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 +198,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 +511,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 +655,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 +767,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 +844,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 +1761,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');
 
@@ -1256,7 +1788,7 @@ class EmpDataServiceController extends BaseController
                 'endorsement_no' => null,
                 'client_branch_id' => $client_branch_id,
                 'count' => $emp_count,
-                'event' => $file['event_type'],
+                'event_name' => $file['event_type'],
                 'policy_name' => $policy_name['policy_name'],
                 'user_id' => $user_id,
             ]]);
@@ -2301,7 +2833,7 @@ class EmpDataServiceController extends BaseController
             'cd_ac_no' => $CD_Account_Number['cd_ac_no'] ?? null,
             'endorsement_no' => $endorsement_id ?? null,
             'count' => $emp_count,
-            'event' => $file['event_type'],
+            'event_name' => $file['event_type'],
             'policy_name' => $policy_name['policy_name'],
             'user_id' => $user_id,
         ]]);
@@ -2816,7 +3348,7 @@ class EmpDataServiceController extends BaseController
             'cd_ac_no' => $CD_Account_Number['cd_ac_no'] ?? null,
             'endorsement_no' => $endorsement_id ?? null,
             'count' => $emp_count,
-            'event' => $file['event_type'],
+            'event_name' => $file['event_type'],
             'policy_name' => $policy_name['policy_name'],
             'user_id' => $user_id,
         ]]);
@@ -3241,38 +3773,52 @@ class EmpDataServiceController extends BaseController
     {
         if (!empty($arrayData)) {
 
-            $amount = $this->employeePolicyModel->query("
-                    SELECT SUM(rata_premimum + gst) AS total_sum
-                    FROM employee_polices
-                    WHERE id IN (" . implode(',', $arrayData['employeeIds']) . ")
-                ")->getRow();
 
-            $insurer_id = $this->clientPolicyModel->where('id', $arrayData['client_policy_id'])->first();
-            $description = 'The following amount of Rs. ' . round($amount->total_sum, 2) . '/- has been debited for the ' . $arrayData['count'] . ' employees at ' . remove_underscore_capitalize_first_letter($arrayData['event']) . ' to ' . remove_underscore_capitalize_first_letter($arrayData['policy_name']) . '.';
-            
-            if(get_session_userid() == null){
+            $client_branch_data = $this->clientBranchModel->where('id', $arrayData['client_branch_id'])->first();
+            $units = json_decode($client_branch_data['units']);
+
+            // dd(json_decode($client_branch_data['units'])); 
+
+
+            foreach($units as $unit)
+            {
+
+                $amount = $this->employeePolicyModel->query("
+                        SELECT SUM(rata_premimum + gst) AS total_sum
+                        FROM employee_polices
+                        JOIN employees ON employees.id = employee_polices.employee_id
+                        WHERE employees.unit = '$unit'
+                        AND employee_polices.id IN (" . implode(',', $arrayData['employeeIds']) . ")
+                    ")->getRow();
+
+                if($amount){      
+
+                    $insurer_id = $this->clientPolicyModel->where('id', $arrayData['client_policy_id'])->first();
+                    $description = 'The following amount of Rs. ' . round($amount->total_sum, 2) . '/- has been debited for the ' . $arrayData['count'] . ' employees at ' . remove_underscore_capitalize_first_letter($arrayData['event_name']) . ' to ' . remove_underscore_capitalize_first_letter($arrayData['policy_name']) . '.';
+
+                    $data = [
+                        'amount' => $amount->total_sum ?? 0,
+                        'sub_type_id' => 4,
+                        'client_id' => $arrayData['client_id'],
+                        'client_policy_id' => $arrayData['client_policy_id'],
+                        'endorsement_no' => $arrayData['endorsement_no'] ?? null,
+                        'cd_ac_no' => $arrayData['cd_ac_no'] ?? null,
+                        'insurer_id' => $insurer_id['insurer_id'],
+                        'unit' => $unit,
+                        'description' => $description,
+                        'transaction_type' => 'Debit',
+                        'updated_by' => $arrayData['user_id'],
+                        'event_name' => $arrayData['event_name'],
+                        'is_active' => 1,
+                    ];
+
+                    $response = DepositHelper::saveDeposit($data,  $arrayData['user_id']);
+                }
 
             }
 
-
-            $data = [
-                'amount' => $amount->total_sum ?? 0,
-                'sub_type_id' => 4,
-                'client_id' => $arrayData['client_id'],
-                'client_policy_id' => $arrayData['client_policy_id'],
-                'endorsement_no' => $arrayData['endorsement_no'] ?? null,
-                'cd_ac_no' => $arrayData['cd_ac_no'] ?? null,
-                'insurer_id' => $insurer_id['insurer_id'],
-                'description' => $description,
-                'transaction_type' => 'Debit',
-                'updated_by' => $arrayData['user_id'],
-                'is_active' => 1,
-            ];
-            $response = DepositHelper::saveDeposit($data,  $arrayData['user_id']);
             return true;
-            // print_r($response);
-            // $query = $this->employeePolicyModel->getLastQuery();
-            // echo $query . "
"; + } else { return 0; @@ -3286,32 +3832,49 @@ class EmpDataServiceController extends BaseController if (!empty($arrayData)) { - $amount = $this->employeePolicyModel->query(" - SELECT SUM(rata_premimum + gst) AS total_sum - FROM employee_polices - WHERE id IN (" . implode(',', $arrayData['employeeIds']) . ") - ")->getRow(); + $client_branch_data = $this->clientBranchModel->where('id', $arrayData['client_branch_id'])->first(); + $units = json_decode($client_branch_data['units']); - $insurer_id = $this->clientPolicyModel->where('id', $arrayData['client_policy_id'])->first(); - $description = 'The following amount of ' . round($amount->total_sum, 2) . ' has been credited for the ' . $arrayData['count'] . ' employees at ' . remove_underscore_capitalize_first_letter($arrayData['event']) . ' to ' . remove_underscore_capitalize_first_letter($arrayData['policy_name']) . '.'; + foreach($units as $unit) + { - $data = [ + $amount = $this->employeePolicyModel->query(" + SELECT SUM(rata_premimum + gst) AS total_sum + FROM employee_polices + JOIN employees ON employees.id = employee_polices.employee_id + WHERE employees.unit = '$unit' + AND id IN (" . implode(',', $arrayData['employeeIds']) . ") + ")->getRow(); + + if($amount){ + + $insurer_id = $this->clientPolicyModel->where('id', $arrayData['client_policy_id'])->first(); + $description = 'The following amount of ' . round($amount->total_sum, 2) . ' has been credited for the ' . $arrayData['count'] . ' employees at ' . remove_underscore_capitalize_first_letter($arrayData['event_name']) . ' to ' . remove_underscore_capitalize_first_letter($arrayData['policy_name']) . '.'; + + $data = [ + + 'amount' => $amount->total_sum, + 'sub_type_id' => 4, + 'client_id' => $arrayData['client_id'], + 'client_policy_id' => $arrayData['client_policy_id'], + 'endorsement_no' => $arrayData['endorsement_no'] ?? null, + 'cd_ac_no' => $arrayData['cd_ac_no'] ?? null, + 'insurer_id' => $insurer_id['insurer_id'], + 'unit' => $unit, + 'description' => $description, + 'transaction_type' => 'Debit', + 'updated_by' => $arrayData['user_id'], + 'event_name' => $arrayData['event_name'], + 'is_active' => 1, + ]; + + $response = DepositHelper::saveDeposit($data, $arrayData['user_id']); + } + } + + $msg = "SI Enhancement Cash Deposite Updated Successfully "; + return [$msg]; - 'amount' => $amount->total_sum, - 'sub_type_id' => 4, - 'client_id' => $arrayData['client_id'], - 'client_policy_id' => $arrayData['client_policy_id'], - 'endorsement_no' => $arrayData['endorsement_no'] ?? null, - 'cd_ac_no' => $arrayData['cd_ac_no'] ?? null, - 'insurer_id' => $insurer_id['insurer_id'], - 'description' => $description, - 'transaction_type' => 'Debit', - 'updated_by' => $arrayData['user_id'], - 'is_active' => 1, - ]; - $response = DepositHelper::saveDeposit($data, $arrayData['user_id']); - $msg = "SI Enhancement Cash Deposite Updated Successfully -- " . $description; - return [$msg, $response]; // print_r($response); // $query = $this->employeePolicyModel->getLastQuery(); // echo $query . "
"; @@ -3329,34 +3892,46 @@ class EmpDataServiceController extends BaseController // echo '
';
             // print_r($arrayData); die;
-            $amount = $this->employeePolicyModel->query("
-                SELECT SUM(rata_premimum + gst) AS total_sum
-                    FROM employee_polices
-                    WHERE id IN (" . implode(',', $arrayData['employeeIds']) . ")
-                ")->getRow();
 
-            $insurer_id = $this->clientPolicyModel->where('id', $arrayData['client_policy_id'])->first();
-            $description = 'The following amount of ' . round($amount->total_sum, 2) . ' has been credited for the ' . $arrayData['count'] . ' employees at ' . remove_underscore_capitalize_first_letter($arrayData['event']) . ' to ' . remove_underscore_capitalize_first_letter($arrayData['policy_name']) . '.';
+            $client_branch_data = $this->clientBranchModel->where('id', $arrayData['client_branch_id'])->first();
+            $units = json_decode($client_branch_data['units']);
 
-            $data = [
+            foreach($units as $unit) {
 
-                'amount' => $amount->total_sum,
-                'sub_type_id' => 3,
-                'client_id' => $arrayData['client_id'],
-                'client_policy_id' => $arrayData['client_policy_id'],
-                'endorsement_no' => $arrayData['endorsement_no'] ?? null,
-                'cd_ac_no' => $arrayData['cd_ac_no'] ?? null,
-                'insurer_id' => $insurer_id['insurer_id'],
-                'description' => $description,
-                'transaction_type' => 'Credit',
-                'updated_by' => $arrayData['user_id'],
-                'is_active' => 1,
-            ];
-            $response = DepositHelper::saveDeposit($data, $arrayData['user_id']);
-            $msg = "Deletion Cash Deposite Updated Successfully -- " . $description;
-            return [$msg, $response];
+                $amount = $this->employeePolicyModel->query("
+                    SELECT SUM(rata_premimum + gst) AS total_sum
+                        FROM employee_polices
+                        JOIN employees ON employees.id = employee_polices.employee_id
+                        WHERE employees.unit = '$unit'
+                        AND id IN (" . implode(',', $arrayData['employeeIds']) . ")
+                    ")->getRow();
+                
+                if($amount){
 
-            return true;
+                    $insurer_id = $this->clientPolicyModel->where('id', $arrayData['client_policy_id'])->first();
+                    $description = 'The following amount of ' . round($amount->total_sum, 2) . ' has been credited for the ' . $arrayData['count'] . ' employees at ' . remove_underscore_capitalize_first_letter($arrayData['event_name']) . ' to ' . remove_underscore_capitalize_first_letter($arrayData['policy_name']) . '.';
+
+                    $data = [
+
+                        'amount' => $amount->total_sum,
+                        'sub_type_id' => 3,
+                        'client_id' => $arrayData['client_id'],
+                        'client_policy_id' => $arrayData['client_policy_id'],
+                        'endorsement_no' => $arrayData['endorsement_no'] ?? null,
+                        'cd_ac_no' => $arrayData['cd_ac_no'] ?? null,
+                        'insurer_id' => $insurer_id['insurer_id'],
+                        'description' => $description,
+                        'transaction_type' => 'Credit',
+                        'updated_by' => $arrayData['user_id'],
+                        'event_name' => $arrayData['event_name'],
+                        'is_active' => 1,
+                    ];
+
+                    $response = DepositHelper::saveDeposit($data, $arrayData['user_id']);
+                }
+            }
+            $msg = "Deletion Cash Deposite Updated Successfully -- ";
+            return [$msg];
             // print_r($response);
             // $query = $this->employeePolicyModel->getLastQuery();
             // echo $query . "
"; @@ -3378,8 +3953,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(); } @@ -3533,12 +4108,9 @@ class EmpDataServiceController extends BaseController return $result; } - // ----------------------------------------------------------------------------------- - - public function readExcelToArray($file) { if ($file->isValid() && !$file->hasMoved()) { @@ -3573,8 +4145,6 @@ class EmpDataServiceController extends BaseController } } - - public function insertBatchFileAndBatchListForImportExcel($data, $ids) { @@ -3597,7 +4167,6 @@ class EmpDataServiceController extends BaseController return true; } - public function sendMailForDownloadingECard(array $ids) { @@ -3703,8 +4272,6 @@ class EmpDataServiceController extends BaseController } } - - public function readExcelFileToArray($path) { $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($path); @@ -3727,9 +4294,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']; @@ -3752,25 +4318,20 @@ 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(); - if($status == 'success'){ $msg_txt = $data['client_name'] . '( ' . $data['branch_name'] . ' )' . ' - ' . $data['policy_name'] . ' - ' . $data['event_type'] . ' - ' . $data['actions'] . ' - ' . $data['insurer_or_tpa']; @@ -3788,10 +4349,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']]; $jsonEncodeData = json_encode($array); @@ -3804,12 +4363,37 @@ class EmpDataServiceController extends BaseController 'message_type' => '1to1', ]; - $this->messageModel->insert($msg_data); - + } + + public function updatajson() + { + + // $columns = [ + // ["column_index" => 0, "column_name" => "SR NO", "db_column_name" => 'index'], + // ["column_index" => 1, "column_name" => "EmployeeId", "db_column_name" => "emp_code"], + // ["column_index" => 2, "column_name" => "UHID", "db_column_name" => "uhid"], + // ["column_index" => 3, "column_name" => "DOJ", "db_column_name" => "emp_doj"], + // ["column_index" => 4, "column_name" => "Name OF Insured", "db_column_name" => "emp_name"], + // ["column_index" => 5, "column_name" => "Age", "db_column_name" => "emp_age"], + // ["column_index" => 6, "column_name" => "Gender", "db_column_name" => "emp_gender"], + // ["column_index" => 7, "column_name" => "DOC", "db_column_name" => null], + // ["column_index" => 8, "column_name" => "TOTALSI", "db_column_name" => "basic_cover_si"], + // ["column_index" => 9, "column_name" => "DOS", "db_column_name" => "dateofexit"], + // ["column_index" => 10, "column_name" => "Mobile", "db_column_name" => 'emp_mobile'], + // ["column_index" => 11, "column_name" => "EmailID", "db_column_name" => 'emp_email_c'], + // ["column_index" => 12, "column_name" => "REMARKS", "db_column_name" => "remarks"], + // ["column_index" => 13, "column_name" => "FLAG STATUS", "db_column_name" => null], + // ["column_index" => 14, "column_name" => "EXCEPTIONS", "db_column_name" => null], + // ["column_index" => 15, "column_name" => "ABHA", "db_column_name" => null] + // ]; + + + + + // $json = json_encode($columns); + // $this->excelExportTemplateModel->where('id', 37)->set('jsoncolumns', $json)->update(); } - - } diff --git a/app/Controllers/EmployeeController.php b/app/Controllers/EmployeeController.php index db9b306c..42bd37bd 100644 --- a/app/Controllers/EmployeeController.php +++ b/app/Controllers/EmployeeController.php @@ -7,10 +7,13 @@ use CodeIgniter\HTTP\RequestInterface; use CodeIgniter\HTTP\ResponseInterface; use Psr\Log\LoggerInterface; +use App\Helpers\DepositHelper; + use App\Models\EmployeeModel; use App\Models\EmployeePolicyModel; use App\Models\ClientModel; +use App\Models\ClientBranchModel; use App\Models\PolicesModel; use App\Models\FileModel; use App\Models\BatchListModel; @@ -18,6 +21,10 @@ 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\Models\ClientDepositModel; + use App\Controllers\Jobs; use App\Controllers\JobWorker; @@ -44,6 +51,7 @@ class EmployeeController extends AdminController protected $employeeModel; protected $employeePolicyModel; protected $clientModel; + protected $clientBranchModel; protected $fileModel; protected $batchListModel; protected $batchFileModel; @@ -51,6 +59,9 @@ class EmployeeController extends AdminController protected $clientPolicyModel; protected $TPAModel; protected $policiesModel; + protected $excelExportTemplateModel; + protected $insurerModel; + protected $cashDepositModel; public function __construct() { @@ -60,6 +71,7 @@ class EmployeeController extends AdminController $this->employeeModel = new EmployeeModel(); $this->employeePolicyModel = new EmployeePolicyModel(); $this->clientModel = new ClientModel(); + $this->clientBranchModel = new ClientBranchModel(); $this->fileModel = new FileModel(); $this->batchListModel = new BatchListModel(); $this->batchFileModel = new BatchFileModel(); @@ -67,13 +79,15 @@ class EmployeeController extends AdminController $this->clientPolicyModel = new ClientPolicyModel(); $this->TPAModel = new TPAModel(); $this->policiesModel = new PolicesModel(); + $this->insurerModel = new InsurerModel(); + $this->cashDepositModel = new ClientDepositModel(); } public function list() { // $model = new UserModel(); $data = []; - $data['status'] = ['draft' => 'Draft', 'active' => 'Active', 'inactive' => 'In-Active', 'expired' => 'Expired']; + $data['status'] = ['draft' => 'Draft', 'active' => 'Active', 'inactive' => 'In-Active', 'pending' => 'Pending']; if (count($this->request->getGet())) { $filterData = $this->request->getGet(); $data['employees'] = $this->employeePolicyModel->getEmployeePolicy( @@ -212,6 +226,7 @@ class EmployeeController extends AdminController //process post variable entry in file table $loggedInUserID = get_session_userid(); + // dd($loggedInUserID); // $loggedInUserID = 8; $client_id = $this->request->getPost('client_id'); @@ -220,7 +235,7 @@ class EmployeeController extends AdminController $action = $this->request->getPost('upload-action-type'); $status = 'inprogress'; - $file_id = $this->fileModel->insert(['file_name' => $filename, 'client_id' => $client_id, 'policy_id' => $policy_id, 'created_by' => $loggedInUserID, 'status' => $status, 'action' => $action, 'client_branch_id' => $branch_id]); //here field policy_id have client_policy_id and not policy id from policy master + $file_id = $this->fileModel->insert(['file_name' => $filename, 'client_id' => $client_id, 'policy_id' => $policy_id, 'created_by' => $loggedInUserID, 'status' => $status, 'action' => $action, 'client_branch_id' => $branch_id,'uploaded_by' => 1]); //here field policy_id have client_policy_id and not policy id from policy master $this->myLogger->logme("error", '{file_id} uploaded success', ['file_id' => $file_id]); //start validation process @@ -236,9 +251,10 @@ class EmployeeController extends AdminController } - - $data['events'] = ['inception' => 'Inception (Employee + Dependents)', 'addition' => 'Addition (Employee + Dependents)', 'dependent_addition' => 'Dependent Addition (Only Dependents)', 'deletion' => 'Deletion', 'correction' => 'Correction', 'si_enhancement' => 'SI Enhancement']; - $data['actions'] = ['inception' => 'Inception (Employee + Dependents)', 'addition' => 'Addition (Employee + Dependents)', 'dependent_addtion' => 'Dependent Addition (Only Dependents)', 'deletion' => 'Deletion', 'correction' => 'Correction', 'si_enhancement' => 'SI Enhancement']; + //for TPA/insurer upload + $data['events'] = ['inception' => 'Inception (Employee + Dependents)', 'missed_inception' => 'Missed Inception (Employee + Dependents)', 'addition' => 'Addition (Employee + Dependents)', 'dependent_addition' => 'Dependent Addition (Only Dependents)', 'deletion' => 'Deletion', 'correction' => 'Correction', 'si_enhancement' => 'SI Enhancement']; + //for inception upload + $data['actions'] = ['inception' => 'Inception (Employee + Dependents)', 'missed_inception' => 'Missed Inception (Employee + Dependents)', 'addition' => 'Addition (Employee + Dependents)', 'dependent_addtion' => 'Dependent Addition (Only Dependents)', 'deletion' => 'Deletion', 'correction' => 'Correction', 'si_enhancement' => 'SI Enhancement','enrollment' => 'Enrollment']; $data['import_or_export'] = ['import' => 'Import', 'export' => 'Export']; $data['insurer_or_tpa'] = ['insurer' => 'Insurer', 'tpa' => 'TPA']; @@ -257,7 +273,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 +290,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 +299,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 +306,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(); @@ -357,6 +369,10 @@ class EmployeeController extends AdminController $filePath = ROOTPATH . 'public/sample_excel/sample_addition.xls'; } else if ($actionType == 'deletion') { $filePath = ROOTPATH . 'public/sample_excel/sample_deletion.xls'; + } else if ($actionType == 'enrollment') { + $filePath = ROOTPATH . 'public/sample_excel/enrollment.xls'; + }else if ($actionType == 'missed_inception') { + $filePath = ROOTPATH . 'public/sample_excel/sample_inception.xls'; } // Check if the file exists @@ -387,6 +403,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 +419,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,10 +436,9 @@ class EmployeeController extends AdminController 'file_name' => $file_name, ]; - if ($actions == 'export') { - if ($event_type == 'inception' || $event_type == 'addition' || $event_type == 'dependent_addition') { + if ($event_type == 'inception' || $event_type == 'addition' || $event_type == 'dependent_addition' || $event_type == 'missed_inception') { $return = $empDataServiceController->generateExcelForAdditionandInception($batch_data); @@ -432,6 +452,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 +473,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 +497,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 +512,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') { @@ -499,7 +560,7 @@ class EmployeeController extends AdminController $batch_data['status'] = 'pending'; $batch_data['file_name'] = $filename; - if ($event_type == 'inception' || $event_type == 'addition' || $event_type == 'dependent_addition') { + if ($event_type == 'inception' || $event_type == 'addition' || $event_type == 'dependent_addition' || $event_type == 'missed_inception') { $file_id = $this->batchFileModel->insert($batch_data); @@ -609,6 +670,78 @@ class EmployeeController extends AdminController $this->loadLayout('endorsement_list', $data); } + + /** + * Below function displays the Enrollment list page. + * + * This method retrieves filter data from the request and fetches the Enrollment list + * based on the provided filters such as client , client_branch , employee - ( Log-in-or-not , ENrolled-or-not). + */ + + public function enrollmentClientList() + { + $data = []; + $client_list = $this->clientModel->findAll(); + $branch_list = $this->clientBranchModel->findAll(); + $data['client_list'] = $client_list; + $data['branch_list'] = $branch_list; + + // Get session data if available + $data['selected_client_id'] = session()->get('client_id'); + $data['selected_branch_id'] = session()->get('branch_id'); + $data['selected_type'] = session()->get('type'); + + $this->myLogger->logme('error', 'list called'); + return $this->loadLayout('enrollment_list', $data); + + } + + public function empby_client_clientbranch($client_id, $branch_id) + { + + $results = $this->clientModel->select('employees.id as employee_id, employees.name as employee_name, + employees.relationship, employees.emp_code, + employees.emp_status, auth_history.user_type') + ->join('employees', $client_id .'= employees.client_id AND ' . $branch_id . '= employees.client_branch_id', 'left') + ->join('auth_history', 'employees.id = auth_history.user_id AND "employee" = auth_history.user_type', 'left') + ->findAll(); + + $groupedData = []; + $employeeId = ''; + foreach ($results as $row) { + if($employeeId != $row['employee_id']){ + $employeeId = $row['employee_id']; + }else{ + $employeeId = null; + } + $employeeName = $row['employee_name'] ; + $employeeRelationship = $row['relationship'] ; + $employeeEmpCode = $row['emp_code'] ; + $employeeEmpStatus = $row['emp_status']; + $employeeUserType = $row['user_type']; + + + if ($employeeId !== null && $employeeRelationship == 'Self') { + // Append employee info to the branch's employees list + $groupedData[] = [ + 'employee_id' => $employeeId, + 'employee_name' => $employeeName, + 'relationship' => $employeeRelationship, + 'emp_code' => $employeeEmpCode, + 'emp_status' => $employeeEmpStatus, + 'user_type' => $employeeUserType + ]; + + } + $employeeId = $row['employee_id']; + } + + + return json_encode($groupedData); + } + + + /** * Beleo function retrieves employee endorsement (emp_endorsement table) data. @@ -690,7 +823,6 @@ class EmployeeController extends AdminController return redirect()->to(base_url('/employee/upload')); } - public function downloadFileList($file_id = null) { // $actionType = $this->request->getGet(); @@ -724,7 +856,6 @@ class EmployeeController extends AdminController } } - public function featchEmpList() { $client_id = $this->request->getGet('client_id'); @@ -736,7 +867,6 @@ class EmployeeController extends AdminController return $this->respond(['dataStatus' => true, 'code' => 200, 'data' => $html], 200); } - public function viewUploadedEmployeeList() { @@ -785,7 +915,6 @@ class EmployeeController extends AdminController } } - public function getEmpCount($id = null) { @@ -800,7 +929,6 @@ class EmployeeController extends AdminController } - public function downloadFullExcelErrorFile($file_id, $rowIndex = 1, $colIndex = 1) { // Get file data from the database @@ -908,13 +1036,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,employees.client_id') ->join('client_policy', 'client_policy.id = employee_polices.client_policy_id') @@ -925,53 +1054,52 @@ 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']; - - + $client_id = $get_emp_code_and_client_policy_id['client_id']; + + // 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,$client_id); - - if($people == 0){ - $data = $this->employeePolicyModel->getECardSingleData($rand_string, $emp_code,$client_id); + + 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,$client_id); } - - // 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 +1114,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 +1128,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() { // $this->loadLayout('ecard_template/default_ecard'); - - $empDataServiceController = new EmpDataServiceController(); - $file_name = generate_filename("TCS", 'inception', 'export', 'insurer', 'policy', 'branch'); - $batch_data = [ - 'client_id' => 12, - 'client_policy_id' => 12, - 'client_branch_id' => 1, - 'insurer_or_tpa' => 'insurer', - 'event_type' => 'inception', - 'actions' => 'export', - 'file_name' => $file_name, - ]; + $data = [ + 'employeeIds' => [6,8,10], + 'client_id' => 12, + 'client_policy_id' => 12, + 'client_branch_id' => 1, + 'cd_ac_no' => '34567834567892', + 'endorsement_no' => null, + 'count' => 3, + 'event_name' =>'inception', + 'policy_name' => 'new policy', + 'user_id' => 1, + ]; - $return = $empDataServiceController->generateExcelForAdditionandInception($batch_data); - - 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"); - } + $empDataServiceController = new EmpDataServiceController(); + $empData= $empDataServiceController->cashDepositCalculationForInception($data); } - - - public function truncateFileData() //truncateFileDataIn DB (de activate rows) + + //truncateFileDataIn DB (de activate rows) + public function truncateFileData($file_id, $role_id = null) { $file_id = $this->request->uri->getSegment(3); // $file_id = 112; $file = $this->fileModel->find($file_id); + $client_id = $file['client_id']; + $client_policy_id = $file['policy_id']; + $loggedInUserID = get_session_userid(); + + $policy_data = $this->clientPolicyModel->where('id', $client_policy_id)->first(); + $cd_tranction = $this->cashDepositModel + ->where('client_id', $client_id) + ->where('insurer_id', $policy_data['insurer_id']) + ->where('event_name',$file['action']) + ->where('client_policy_id', $client_policy_id) + ->orderBy('id', 'desc') + ->first(); + // $file['action'] = 'si_enhancement'; // $result = []; // !dd($file); if ($file['action'] == 'inception' || $file['action'] == 'dependent_addition' || $file['action'] == 'addition') { $result = $this->employeeModel->getEmpListByFileId(file_id: $file_id, emp_status: ['active'], policy_status: ['active']); // ~dd($result); - if (count($result)) { - return $this->respond(['dataStatus' => false, 'code' => 404, 'message' => 'File data already processed'], 200); + if (count($result) && $role_id == null) { + if(get_role_id() == 1 || get_role_id() == 5){ + return $this->respond(['role' => get_role_id(), 'dataStatus' => false, 'code' => 404, 'message' => 'File data already processed. Do you want to truncate data from uploaded file?'], 200); + }else{ + return $this->respond(['role' => get_role_id(), 'dataStatus' => false, 'code' => 404, 'message' => 'File data already processed'], 200); + } } else { //update emp and emp plocies @@ -1137,9 +1224,30 @@ class EmployeeController extends AdminController //update file status $this->fileModel->where('id', $file_id)->set(['status' => 'truncated'])->update(); + if($cd_tranction){ + + $cd_data = [ + 'amount' => $cd_tranction['amount'], + 'sub_type_id' => 8, + 'endorsement_no' => null, + 'insurer_id' =>$policy_data['insurer_id'], + 'description' => 'The policy Truncated by Admin or Head', + 'transaction_type' => 'Credit', + 'updated_by' => 1, + 'client_id' => $client_id, + 'client_policy_id' => $client_policy_id, + 'cd_ac_no' => $policy_data['cd_ac_no'] ?? null, + 'event_name' => $file['action'], + ]; + + $response = DepositHelper::saveDeposit($cd_data, $loggedInUserID); + } + return $this->respond(['dataStatus' => true, 'code' => 200, 'data' => round($affectedRows / 2)], 200); } + } else if ($file['action'] == 'si_enhancement' || $file['action'] == 'correction' || $file['action'] == 'deletion') { + $res = $this->empEndorsementModel->select(['count(id) as count']) ->where('emp_endorsement.file_id', $file_id) ->groupStart() @@ -1148,25 +1256,52 @@ class EmployeeController extends AdminController ->groupEnd() ->get() ->getResult(); + // print_r($this->empEndorsementModel->getLastQuery()); // echo $res[0]->count;die(); - if ($res[0]->count == 0) { + if ($res[0]->count == 0 || $role_id == 5 || $role_id == 1) { //update truncated status to db $this->empEndorsementModel->where('file_id', $file_id) ->set(['status' => 'truncated']) ->update(); //update file status $this->fileModel->where('id', $file_id)->set(['status' => 'truncated'])->update(); + + if($cd_tranction && $file['action'] != 'correction'){ + + $transaction_type = 'Credit'; + if($file['action'] == 'deletion'){ + $transaction_type = 'Debit'; + } + + $cd_data = [ + 'amount' => $cd_tranction['amount'], + 'sub_type_id' => 8, + 'endorsement_no' => null, + 'insurer_id' =>$policy_data['insurer_id'], + 'description' => 'The policy Truncated by Admin or Head', + 'transaction_type' => $transaction_type, + 'updated_by' => 1, + 'client_id' => $client_id, + 'client_policy_id' => $client_policy_id, + 'cd_ac_no' => $policy_data['cd_ac_no'] ?? null, + 'event_name' => $file['action'], + ]; + + $response = DepositHelper::saveDeposit($cd_data, $loggedInUserID); + } + return $this->respond(['dataStatus' => true, 'code' => 200, 'data' => 'success'], 200); } else { - return $this->respond(['dataStatus' => false, 'code' => 404, 'message' => 'File data already processed'], 200); + if(get_role_id() == 1 || get_role_id() == 5){ + return $this->respond(['role' => get_role_id(), 'dataStatus' => false, 'code' => 404, 'message' => 'File data already processed. Do you want to truncate data from uploaded file?'], 200); + }else{ + return $this->respond(['dataStatus' => false, 'code' => 404, 'message' => 'File data already processed'], 200); + } } } } - - - public function previewTemplate($id = null) { @@ -1249,7 +1384,6 @@ class EmployeeController extends AdminController echo $htmlContent; } - public function errorListExportImport($file_id) { @@ -1340,6 +1474,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,8 +1501,83 @@ 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); } + public function testRackRate() + { + if ($this->request->getMethod() == 'get') { + $filterData = $this->request->getGet('client_policy_id'); + //just load UI only + $this->loadLayout('rack_rate_test'); + } + + + if ($this->request->getMethod() == 'post') { + $json = $this->request->getJSON(); + // return $this->respond(['dataStatus' => false, 'code' => 200, 'data' => $data], 200); + // $data = (json_decode(json_encode($data),true)); + $client_id = $json->client_id; + $policy_id = $json->policy_id; + $branch_id = $json->branch_id; + $tabledata = $json->data; + + if(count($tabledata)) + { + $family_details = []; + foreach($tabledata as $key => $row) + { + $row = (array)$row; + if(!$row['column12']) + { + + $temp[0] = $row['column1'];//sno + $temp[1] = $row['column2'];//emp code + $temp[2] = $row['column3'];//name + $temp[3] = $row['column4'];//DOB + $temp[4] = strtoupper($row['column5']);//Gender + $temp[5] = $row['column6'];//relation + $temp[6] = $row['column7'];//SI + $temp[7] = $row['column8'];//DOC + $temp[8] = '';//DOJ + $temp[9] = $row['column9'];//BP + $temp[10] = $row['column10'];//band + $temp[11] = '';//designation + $temp[12] = '';//mobile + $temp[13] = '';//EMail + $temp[14] = '';//CE + $temp[15] = '';//RFE + $temp[16] = '';//DOE + $temp[17] = '';//Unit + $temp[18] = $row['column11'];//unit + $family_details[] = $temp; + } + } + } + + // print_r($family_details); + return $this->respond(['dataStatus' => true, 'code' => 200, 'data' => $family_details], 200); + //get policy details + $policy_details = $this->clientPolicyModel->getPolicyDetails($file['client_id'],$file['policy_id']); + //get rack rates + $slab_details = $this->policiesModel->getPolicySlabRatesForEmpOnboard($file['policy_id'],$file['client_id']); + //get file array or construnct dummy file array here + $file = ['id' => null,'client_id' => 10,'policy_id' => 10,'action' => 'inception','client_branch_id' => 1,'created_by' => 1]; + //get familiy details in inception file format array from post method + $family_details = [ + [2,'TEST001','John Doe', '01-Jan-1988', 'M', 'Self', '5000000', NULL, '', '', 'G', '', '', '', '', '', '',''], + [1,'TEST001','Jane Doe', '01-Jan-1985', 'F', 'Spouse', 5000000, '01-Jan-2024', '01-Jan-2020', 50000, 'A', 'Manager', '1234567890', 'john.doe@example.com', '0', '', '', ''], + + // [3,'TEST001','Peter Doe', '01-Jan-1955', 'M', 'Father', '', NULL, '', '', '', '', '', '', '', '', '',''], + [4,'TEST001','Mary Doe', '01-Jan-1953', 'F', 'Mother', '', NULL, '', '', '', '', '', '', '', '', '',''], + [5,'TEST001','Grace Doe', '01-Jan-1954', 'F', 'Mother in law', '', NULL, '', '', '', '', '', '', '', '', '',''], + //[6,'TEST001','George Doe', '01-Jan-1948', 'M', 'Father in law', '', NULL, '', '', '', '', '', '', '', '', '',''], + [7,'TEST001','Alice Doe', '01-Jan-1990', 'F', 'Daughter', 5000000, '01-Jan-2024', '01-Jan-2024', 40000, 'B', 'Supervisor', '9876543210', '', '', '', '',''], + [6,'TEST001','Bob Doe', '01-Jan-1993', 'M', 'son', '50000', NULL, '', '', '', '', '', '', '', '', '',''], + ]; + $data = calculate_premimum_new($family_details,$policy_details,$all_rack_rates,$file); + } + } + } diff --git a/app/Controllers/EmployeeRestController.php b/app/Controllers/EmployeeRestController.php index d7ba79f2..2b2e017c 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 { @@ -632,6 +637,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 +748,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 +783,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], @@ -785,6 +791,8 @@ class EmployeeRestController extends AdminController 'client_id' => $client_id, 'emp_status'=>'draft', 'band'=> $extra['10'][$index], + 'basic_pay'=> $extra['11'][$index], + 'unit'=> isset($extra['12'][$index]) ? $extra['12'][$index] : null, 'client_branch_id' => $client_branch_id ]; @@ -822,7 +830,7 @@ class EmployeeRestController extends AdminController $count = 0; for ($a=0; $a employeeModel->checkExistingEmployee($dataToInsert[$a]); + $employee = $this->employeeModel->checkExistingEmployee($dataToInsert[$a],$client_branch_id); $emp_id =0; $data_after_gpa_or_gmc =[]; @@ -887,10 +895,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]; @@ -928,634 +936,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 +1097,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 +1108,1316 @@ 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); + + + }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 == 1 && $key ==='either-parents-pil') { + $result .= ' + Either 2 Parents or 2 Parents in law'; + }if($value == 2 && $key ==='either-parents-pil') { + $result .= ' + Any 2 of Parents and 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 if($value != 0 && $key ==='elders_count') { + + }else{ + $string = str_replace('-', ' ', $key); + $string = ucwords($string); + $result .= ' + '.$value.' '.$string; + } - // Add family floter buttons placement data for FE validation - if(count($floters)){ - foreach ($floters as $familyFloatesValue) { + } + } + + return $result; + } - $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); + public function getClientDetails() + { + try { - array_push($data,$temp2); + $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) ) { - $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 ($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_premium($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 { + $json = $this->request->getJSON(); + $firebase_token = $json->firebase_token; + $mobile = $json->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'], 200); + } + } 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); + // } + } + + + + + + 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()]); + log_message('error', $e->getMessage()); + } + } + + + + + } \ No newline at end of file diff --git a/app/Controllers/EmployeeServiceController.php b/app/Controllers/EmployeeServiceController.php index 31e23163..4ddd51e6 100644 --- a/app/Controllers/EmployeeServiceController.php +++ b/app/Controllers/EmployeeServiceController.php @@ -16,6 +16,10 @@ use App\Models\PolicesModel; use App\Models\FileModel; use App\Models\EmpEndorsementModel; use App\Models\MessageModel; +use App\Models\ClientBranchModel; +use App\Models\NotificationModel; + +use App\Helpers\sendMailNotification; use App\Controllers\Jobs ; use App\Controllers\JobWorker ; @@ -35,6 +39,8 @@ class EmployeeServiceController extends AdminController protected $policiesModel; protected $empEndorsementModel; protected $messageModel; + protected $clientBranchModel; + protected $notificationModel; protected $general_relationships = [ 'self' => [ @@ -155,7 +161,7 @@ class EmployeeServiceController extends AdminController 'format' => null, 'allowed_values' => null, 'custom' => 'check_si', - 'params' => ['row', 'policy_terms', 'slab_details'] + 'params' => ['row', 'policy_details', 'slab_details'] ], 'doc' => [ 'col_idx' => 7, @@ -266,6 +272,18 @@ class EmployeeServiceController extends AdminController 'format' => null, 'allowed_values' => null ] + , + 'unit' => [ + 'col_idx' => 18, + 'col_cell_name' => 'S', + 'col_name' => 'Unit', + 'is_mandatory' => false, + 'data_type' => 'str', + 'format' => null, + 'allowed_values' => null, + 'custom' => 'check_unit', + 'params' => ['row', 'existing_units'] + ] ]; protected $deletion_excel_columns = [ @@ -565,6 +583,15 @@ class EmployeeServiceController extends AdminController 'format' => null, 'allowed_values' => null, 'custom' => null + ], + 'unit' => [ + 'col_idx' => 12, + 'col_cell_name' => 'M', + 'col_name' => 'Unit', + 'is_mandatory' => false, + 'data_type' => 'str', + 'format' => null, + 'allowed_values' => null ] ]; @@ -586,7 +613,8 @@ class EmployeeServiceController extends AdminController 14 => null, // inception: pre_existing_ailments (PRE EXISTING AILMENTS) -> No match in enrollment 15 => null, // inception: change_event (Change event) -> No match in enrollment 16 => null, // inception: date_of_exit (Date of exit) -> No match in enrollment - 17 => null // inception: reason_for_exit (Reason for exit) -> No match in enrollment + 17 => null, // inception: reason_for_exit (Reason for exit) -> No match in enrollment + 18 => null // inception: reason_for_exit (Reason for exit) -> No match in enrollment ]; protected $enrollment_to_inception_mapping = [ @@ -619,6 +647,8 @@ class EmployeeServiceController extends AdminController $this->policiesModel = new PolicesModel(); $this->empEndorsementModel = new EmpEndorsementModel(); $this->messageModel = new MessageModel(); + $this->clientBranchModel = new ClientBranchModel(); + $this->notificationModel = new NotificationModel(); } public function excelFileFormatValidation($params) @@ -663,6 +693,7 @@ class EmployeeServiceController extends AdminController if($file['action'] == 'correction'){ $columns_to_check = $this->correction_excel_columns; } if($file['action'] == 'si_enhancement'){ $columns_to_check = $this->si_enhance_excel_columns; } if($file['action'] == 'enrollment'){ $columns_to_check = $this->enrollment_excel_columns; } + if($file['action'] == 'missed_inception'){ $columns_to_check = $this->inception_excel_columns; } $result = ['error_type' => 1,'error_summary' => [], 'error_data' => [] ]; @@ -722,7 +753,10 @@ class EmployeeServiceController extends AdminController $relationship = $this->general_relationships; //get exisiting mobilr nos $existing_mobilenos = $this->employeePolicyModel->getExisitingMobileNos(client_policy_id: $file['policy_id']); - // dd($existing_mobilenos); + + //get existing units in the current branch + $existing_units = $this->clientBranchModel->getExisitingUnits(client_id: $file['client_id'],client_branch_id: $file['client_branch_id']); + // dd($existing_units); foreach ($excel_data as $row_key => $row) { //define row wise action/event in temporary variable @@ -734,6 +768,7 @@ class EmployeeServiceController extends AdminController else if($file['action'] == 'correction'){ $current_column_action = 'C'; } else if($file['action'] == 'si_enhancement'){ $current_column_action = 'SI'; } else if($file['action'] == 'enrollment'){ $current_column_action = 'I'; } + else if($file['action'] == 'missed_inception'){ $current_column_action = 'MI'; } //1. avoid empty rows if(check_row_is_empty_or_null($row)) { @@ -862,16 +897,17 @@ class EmployeeServiceController extends AdminController } else //trigger next data validation via job queue server - { - if($file['action'] == 'enrollment') // if current action is enrollment call next validation and return result + { + if($file['action'] == 'enrollment' && $file['uploaded_by'] != 1) // if current action is enrollment and uploaded by HR (0 or NULL) call next validation and return result { + // dd(); $res = $this->excelFileDataValidation(['file_id' => $file['id']]); return $res; } //proceed next data level validation in JOB queue - $job_details = new Jobs(); - $r = Jobs::addJob(['job_name' => 'excelFileDataValidation','payload' => ['file_id' => $file_id]]); + // $job_details = new Jobs(); + // $r = Jobs::addJob(['job_name' => 'excelFileDataValidation','payload' => ['file_id' => $file_id]]); // $jobWorker = new JobWorker(); // JobWorker::processJob($r); @@ -914,6 +950,7 @@ class EmployeeServiceController extends AdminController if($file['action'] == 'correction'){ $columns_to_check = $this->correction_excel_columns; } if($file['action'] == 'si_enhancement'){ $columns_to_check = $this->si_enhance_excel_columns; } if($file['action'] == 'enrollment'){ $columns_to_check = $this->enrollment_excel_columns; } + if($file['action'] == 'missed_inception'){ $columns_to_check = $this->inception_excel_columns; } // get policy and rack details $policy_terms = $this->clientPolicyModel->getPolicyDetails($file['client_id'],$file['policy_id']); @@ -940,7 +977,7 @@ class EmployeeServiceController extends AdminController $relationship = $this->general_relationships; - if(in_array($file['action'],['inception','addition','dependent_addition','deletion','correction','si_enhancement','enrollment']))// the below funcitons are only for I,DA,A + if(in_array($file['action'],['inception','missed_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',($file['action'] == 'enrollment' ? 'enrollment' : '')); // dd($employee_data_group_by_family); @@ -968,12 +1005,12 @@ class EmployeeServiceController extends AdminController // dd(array_keys($existing_famility_details[0])); $family = array_merge($family,$existing_famility_details); // kint::dump($family); - $family = data_group_by_family($family)[ $emp_id ];// reason to call this again is bring self to first index of the array + $family = data_group_by_family($family)[ $emp_id ];// reason to call this again bring self to first index of the array } // kint::dump($family);//die(); //check name dup within a family - if($file['action'] == 'inception' || $file['action'] == 'addition' || $file['action'] == 'dependent_addition' || $file['action'] == 'enrollment') + if($file['action'] == 'inception' || $file['action'] == 'missed_inception' || $file['action'] == 'addition' || $file['action'] == 'dependent_addition' || $file['action'] == 'enrollment') { $res = name_dup_check_within_family($family,$file['action']);//in both file data & DB data // dd($res); @@ -987,7 +1024,7 @@ class EmployeeServiceController extends AdminController } } - if(($policy_details['base_policy'] == null && ($file['action'] == 'inception' || $file['action'] == 'addition' || $file['action'] == 'enrollment')) || ($policy_details['policy_type_id'] == 3 && $is_self_available_in_policy_terms)) // 3 is GMC parents dep addon) + if(($policy_details['base_policy'] == null || $policy_details['base_policy'] == 0 && ($file['action'] == 'inception' || $file['action'] == 'missed_inception' || $file['action'] == 'addition' || $file['action'] == 'enrollment')) || ($policy_details['policy_type_id'] == 3 && $is_self_available_in_policy_terms)) // 3 is GMC parents dep addon) { $res = check_self_available_in_family($family,$file['action']); if(!$res['is_self_found']) @@ -1010,7 +1047,7 @@ class EmployeeServiceController extends AdminController } - if($file['action'] == 'dependent_addition' || $file['action'] == 'addition' || $file['action'] == 'inception' || $file['action'] == 'enrollment') + if($file['action'] == 'dependent_addition' || $file['action'] == 'addition' || $file['action'] == 'inception'|| $file['action'] == 'missed_inception' || $file['action'] == 'enrollment') { $res = check_dependent_conflict($family,$policy_terms,$file['action']); // dd($res); @@ -1081,14 +1118,18 @@ class EmployeeServiceController extends AdminController $r = Jobs::addJob(['job_name' => 'employeesCorrectionProcess','payload' => ['file_id' => $file_id]]); } - else if ($file['action'] == 'inception' || $file['action'] == 'addition' || $file['action'] == 'dependent_addition')//inception OR addition OR dependent addition + else if ($file['action'] == 'inception' || $file['action'] == 'missed_inception' || $file['action'] == 'addition' || $file['action'] == 'dependent_addition')//inception OR addition OR dependent addition { //proceed next data level validation in JOB queue - $job_details = new Jobs(); + // $job_details = new Jobs(); $r = Jobs::addJob(['job_name' => 'employeesOnboardPreprocess','payload' => ['file_id' => $file_id]]); // $jobWorker = new JobWorker(); // JobWorker::processJob($r); } + else if($file['action'] == 'enrollment' && $file['uploaded_by'] == 1)// enrollment uploaded by nhance user not by hr + { + $r = Jobs::addJob(['job_name' => 'employeesEnrollmentInsert','payload' => ['file_id' => $file_id]]); + } return $result; @@ -1134,6 +1175,7 @@ class EmployeeServiceController extends AdminController if($file['action'] == 'deletion'){ $columns_to_check = $this->deletion_excel_columns; } if($file['action'] == 'correction'){ $columns_to_check = $this->correction_excel_columns; } if($file['action'] == 'si_enhancement'){ $columns_to_check = $this->si_enhance_excel_columns; } + if($file['action'] == 'missed_inception'){ $columns_to_check = $this->inception_excel_columns; } // get policy and rack details $policy_terms = $this->clientPolicyModel->getPolicyDetails($file['client_id'],$file['policy_id']); @@ -1155,6 +1197,8 @@ class EmployeeServiceController extends AdminController //get policy slab rates $slab_details = $this->policiesModel->getPolicySlabRatesForEmpOnboard($file['policy_id'],$file['client_id']); // dd($slab_details); + //get existing units in the current branch + $existing_units = $this->clientBranchModel->getExisitingUnits(client_id: $file['client_id'],client_branch_id: $file['client_branch_id']); $employee_data_group_by_family = data_group_by_family($excel_data); // dd($employee_data_group_by_family); @@ -1175,7 +1219,7 @@ class EmployeeServiceController extends AdminController } // Kint::dump($family);die(); - $data = calculate_premimum($family,$policy_terms,$slab_details,$file); + $data = calculate_premium_new(family_data:$family,policy_terms: $policy_terms,slab_details : $slab_details,fileArr: $file, existing_units:$existing_units); // dd($data); $employee_data_group_by_family[$emp_id] = $data; $this->employeesOnboardProcess(['familiy_data' => $data,'file' => $file]); @@ -1204,6 +1248,9 @@ class EmployeeServiceController extends AdminController $existing_famility_details = $this->employeeModel->getEmpFamilybyEmpCode(client_id: $client_id,client_policy_id: $client_policy_id,emp_status: ['enrolled','draft'],policy_status:['enrolled','draft']); + //get existing units in the current branch + $existing_units = $this->clientBranchModel->getExisitingUnits(client_id: $file['client_id'],client_branch_id: $file['client_branch_id']); + // $file = ['id' => null,'client_id' => $client_id,'policy_id' => $client_policy_id,'action' => 'inception']; $file = ['id' => null,'client_id' => $client_id,'policy_id' => $client_policy_id,'action' => 'inception','created_by' => get_session_userid(),'client_branch_id' => $params['client_branch_id']]; @@ -1214,7 +1261,8 @@ class EmployeeServiceController extends AdminController foreach ($employee_data_group_by_family as $emp_id => $family) { $transformed_famility_details = transform_db_data_to_excel($family); - $data = calculate_premimum($transformed_famility_details,$policy_terms,$slab_details,$file); + // $data = calculate_premium_new($transformed_famility_details,$policy_terms,$slab_details,$file); + $data = calculate_premium_new(family_data:$transformed_famility_details,policy_terms: $policy_terms,slab_details : $slab_details,fileArr: $file, existing_units:$existing_units); // dd($data); $employee_data_group_by_family[$emp_id] = $data; $this->employeesOnboardProcess(['familiy_data' => $data,'file' => $file]); @@ -1448,17 +1496,43 @@ class EmployeeServiceController extends AdminController if(!count($existing_endorsements)) { //transform data to send + + //get applicable slab rate for current member relation + $pre_rack_rate_name = ''; + $applicable_rack_rate_name = ''; + $applicable_rack_rate_master = ''; foreach ($slab_details['slab_rates'] as $skey => $slab_value) { - if($slab_value['si'] == $row[3]) + if($pre_rack_rate_name != $slab_value['rack_rate_name']) { - $group_key = rand(100000, 999999); - $this->empEndorsementModel->save(['pk' => (int)$employee_policy['id'],'emp_code' => $employee['emp_code'],'table_name' => 'employee_polices','actions' => 'si','name' => $employee['name'],'field_name' => 'basic_cover_si','old_value' => $employee_policy['basic_cover_si'],'new_value' => $row[3],'created_by' => $file['created_by'],'remarks' => 'general si enhancement','group_key' => $group_key,'file_id' => $file['id'],'status' => 'pending']); - $this->empEndorsementModel->save(['pk' => (int)$employee_policy['id'],'emp_code' => $employee['emp_code'],'table_name' => 'employee_polices','actions' => 'si','name' => $employee['name'],'field_name' => 'premium','old_value' => $employee_policy['premium'],'new_value' => $slab_value['premium'],'created_by' => $file['created_by'],'remarks' => 'general si enhancement','group_key' => $group_key,'file_id' => $file['id'],'status' => 'pending']); - $this->empEndorsementModel->save(['pk' => (int)$employee_policy['id'],'emp_code' => $employee['emp_code'],'table_name' => 'employee_polices','actions' => 'si','name' => $employee['name'],'field_name' => 'si_enhancement_date','old_value' => null,'new_value' => change_date_format($row[4],'d-M-Y','Y-m-d'),'created_by' => $file['created_by'],'remarks' => 'general si enhancement','group_key' => $group_key,'file_id' => $file['id'],'status' => 'pending']); - break; + $pre_rack_rate_name = $slab_value['rack_rate_name']; + $rack_rate_json = json_decode($slab_value['additional_relationship']); + if(in_array(strtolower($employee['relationship']), $rack_rate_json) && $rack_rate_json[ strtolower($employee['relationship']) ] != 0 && $rack_rate_json[ strtolower($employee['relationship']) ] != NA) + { + $applicable_rack_rate_name = $slab_value['rack_rate_name']; + $applicable_rack_rate_master = $slab_value['grid_master']; + break; + } } } + + //get max age,max count of the familiy + $max_age_and_max_count_of_current_member = $this->employeeModel->getFamiliyCountAndMaxage($employee['emp_code']); + //transform SI excel row data as inception excel OR premium calculateable fomart + + $data = transform_si_excel_row_to_calculatable_format(employee: $employee,employee_policy: $employee_policy,maxage_and_maxcount: $max_age_and_max_count_of_current_member,slab_details: $slab_details,applicable_slab_name: $applicable_rack_rate_name,augmented_si: $row[3],grid_master: $applicable_rack_rate_master); + $policy_terms = $this->clientPolicyModel->getPolicyDetails($file['client_id'],$file['policy_id']); + //grouping slab details by rack rate name + $temp_slab_rates = group_slab_rates_basedon_name($slab_details); + + $calculated_data = premium_calculation_manager($data,$policy_terms,$temp_slab_rates,$row[3]); + + $group_key = rand(100000, 999999); + $this->empEndorsementModel->save(['pk' => (int)$employee_policy['id'],'emp_code' => $employee['emp_code'],'table_name' => 'employee_polices','actions' => 'si','name' => $employee['name'],'field_name' => 'basic_cover_si','old_value' => $employee_policy['basic_cover_si'],'new_value' => $row[3],'created_by' => $file['created_by'],'remarks' => 'general si enhancement','group_key' => $group_key,'file_id' => $file['id'],'status' => 'pending']); + $this->empEndorsementModel->save(['pk' => (int)$employee_policy['id'],'emp_code' => $employee['emp_code'],'table_name' => 'employee_polices','actions' => 'si','name' => $employee['name'],'field_name' => 'premium','old_value' => $employee_policy['premium'],'new_value' => $calculated_data['policy_details']['premium'],'created_by' => $file['created_by'],'remarks' => 'general si enhancement','group_key' => $group_key,'file_id' => $file['id'],'status' => 'pending']); + $this->empEndorsementModel->save(['pk' => (int)$employee_policy['id'],'emp_code' => $employee['emp_code'],'table_name' => 'employee_polices','actions' => 'si','name' => $employee['name'],'field_name' => 'si_enhancement_date','old_value' => null,'new_value' => change_date_format($row[4],'d-M-Y','Y-m-d'),'created_by' => $file['created_by'],'remarks' => 'general si enhancement','group_key' => $group_key,'file_id' => $file['id'],'status' => 'pending']); + + } @@ -1474,105 +1548,114 @@ class EmployeeServiceController extends AdminController // insert or update in db for inception addition depent addition - public function employeesOnboardProcess($params) + public function employeesOnboardProcess($params) { $familiy_data = $params['familiy_data']; $file = $params['file']; - $slab_details = $this->policiesModel->getPolicySlabRatesForEmpOnboard($file['policy_id'],$file['client_id']); foreach($familiy_data as $fkey => $value) { - if($file['id'] == null || $value['temp']['source'] == 'excel' || (($file['action'] == 'dependent_addition' && ($slab_details['slab_rates'][0]['premium_type'] == 1 && strtolower($value['relationship']) == 'self') || ($slab_details['slab_rates'][0]['premium_type'] == 2 || $slab_details['slab_rates'][0]['premium_type'] == null)))) //insert data come from excel and from db i.e. ( $file['id'] == null for enrollment data) + if(is_array($value)) { - - $employee = $this->employeeModel->checkExistingEmp($value,$file['client_branch_id']); - $policy_data = $value['policy_details']; - $temp = $value['temp']; - unset($value['policy_details']); - unset($value['temp']); - // Kint::dump($value); - // Kint::dump($temp); - // Kint::dump($policy_data); - // echo '---------------------------------------'; - - //start implemet of si enhancement of grid type 10,11 - if(count($employee) && $file['action'] == 'dependent_addition' && $temp['source'] == 'db' && in_array($value['temp']['grid_id'],[10,11]) && ( ($slab_details['slab_rates'][0]['premium_type'] == 1 && (strtolower($value['relationship']) == 'self' || $temp['additional_rack_rate_acting_self'])) || ($slab_details['slab_rates'][0]['premium_type'] == 2 || $slab_details['slab_rates'][0]['premium_type'] == null))) - { - $log_message = 'Employee record from DB,Checking SI for - '.$employee[0]['name'].'('.$employee[0]['emp_code'].')'; - $this->myLogger->logme('error',$log_message); - $res = $this->employeesSIEnhanceProcessWhileOnbboard(employee:$employee[0],policy_data: $policy_data,file:$file);// where employee holds existing emp data and policy_data holds new si enhancement - break;//skip db employee - } - //end implemet of si enhancement of grid type - - //save employee table - if(count($employee)) - { - $value['updated_by'] = $file['created_by']; - $value['id'] = $employee[0]['id']; - $value['emp_status'] = 'active'; - $value['client_branch_id'] = $file['client_branch_id']; - $log_message = 'Update Employee - '.$employee[0]['name'].'('.$employee[0]['emp_code'].') with PK '.$employee[0]['id']; - // $this->myLogger->logme('error',('Update - ' . $employee[0]['id'].' - '. $employee[0]['emp_code'] .' - '.$employee[0]['name'])); - } - else - { - $value['emp_status'] = 'active'; - $value['created_by'] = $file['created_by']; - $value['client_branch_id'] = $file['client_branch_id']; - $log_message = 'Insert Employee- '.$value['name'] .'('.$value['emp_code'] .') with PK '; - // $this->myLogger->logme('error',('Insert - ' . $value['emp_code'] .' - '. $value['name'])); - } - - $this->employeeModel->save($value); - $emp_id = $this->employeeModel->getInsertID(); - if($emp_id != 0){ $log_message .= $emp_id; } - else{ $emp_id = $employee[0]['id']; } - - $this->myLogger->logme('error',$log_message); - - //save policy table - $employee_policy = $this->employeePolicyModel->checkExistingEmpPolicy(['employee_id' => $emp_id,'client_policy_id' => $file['policy_id']]); - if(count($employee_policy)) - { - $policy_data['updated_by'] = $file['created_by']; - $policy_data['id'] = $employee_policy[0]['id']; - $policy_data['status'] = 'active'; - - $log_message = 'Update Employee Policy for '. $value['name'].'('. $value['emp_code'].') with PK- ' . $employee_policy[0]['id'] .' client policy ID '.$employee_policy[0]['client_policy_id'].' with SI '.$policy_data['basic_cover_si']; - } - else - { - $policy_data['employee_id'] = $emp_id; - $policy_data['client_policy_id'] = $file['policy_id']; - $policy_data['created_by'] = $file['created_by']; - $policy_data['status'] = 'active'; - $log_message = 'Insert Employee Policy for '. $value['name'].'('. $value['emp_code'].') - client policy id -'. $file['policy_id'].' - with SI '.$policy_data['basic_cover_si']; - } - - $this->employeePolicyModel->save($policy_data); - $emp_policy_id = $this->employeePolicyModel->getInsertID(); - if($emp_policy_id != 0)//emp policy inserted - { - $log_message .= ' with PK ' . $emp_policy_id; - - //make endorsement entry if action is addition OR Dependt addition - if(($file['action'] == 'dependent_addition' || $file['action'] == 'addition') && $temp['source'] == 'excel') + + if($file['id'] == null || $value['temp']['source'] == 'excel' || (($file['action'] == 'dependent_addition' && ($value['temp']['premium_type'] == 1 && strtolower($value['relationship']) == 'self') || ($value['temp']['premium_type'] == 2 || $value['temp']['premium_type'] == null)))) //insert data come from excel and from db i.e. ( $file['id'] == null for enrollment data) { - $log_message = $file['action'].' - endorsement'. $value['emp_code'].' - '.$value['name'].' - with policy id'.$emp_policy_id; - $this->myLogger->logme('error',$log_message); - $actions = ($file['action'] == 'dependent_addition' ? 'da' : ($file['action'] == 'addition' ? 'a' : NULL)); - $addition_endorse_data = ['pk' => $emp_policy_id,'group_key' => rand(100000, 999999),'emp_code' => $value['emp_code'],'table_name' => 'employee_polices','actions' => $actions,'name' => $value['name'],'field_name' => 'basic_cover_si','old_value' => NULL,'new_value' => $policy_data['basic_cover_si'],'remarks' => 'addition endorsement','file_id' => $file['id'],'created_by' => $file['created_by']]; - $this->employeeEndorsementforAddtionAndDependentAddition($addition_endorse_data); - } + + $employee = $this->employeeModel->checkExistingEmp($value,$file['client_branch_id']); + $policy_data = $value['policy_details']; + $temp = $value['temp']; + unset($value['policy_details']); + unset($value['temp']); + // Kint::dump($value); + // Kint::dump($temp); + // Kint::dump($policy_data); + // echo '---------------------------------------'; + + //start implemet of si enhancement of grid type 10,11 + if(count($employee) && $file['action'] == 'dependent_addition' && $temp['source'] == 'db' && in_array($value['temp']['grid_id'],[10,11]) && ( ($value['temp']['premium_type'] == 1 && (strtolower($value['relationship']) == 'self' || $temp['acting_self'])) || ($value['temp']['premium_type'] == 2 || $value['temp']['premium_type'] == null))) + { + $log_message = 'Employee record from DB,Checking SI for - '.$employee[0]['name'].'('.$employee[0]['emp_code'].')'; + $this->myLogger->logme('error',$log_message); + $res = $this->employeesSIEnhanceProcessWhileOnbboard(employee:$employee[0],policy_data: $policy_data,file:$file);// where employee holds existing emp data and policy_data holds new si enhancement - } - else{ $emp_policy_id = $employee_policy[0]['id']; } + break;//skip db employee + } + //end implemet of si enhancement of grid type + + //save employee table + $value['relationship'] = ucfirst(trim($value['relationship'])); + if(count($employee)) + { + $value['updated_by'] = $file['created_by']; + $value['id'] = $employee[0]['id']; + $value['emp_status'] = 'active'; + $value['client_branch_id'] = $file['client_branch_id']; + $log_message = 'Update Employee - '.$employee[0]['name'].'('.$employee[0]['emp_code'].') with PK '.$employee[0]['id']; + // $this->myLogger->logme('error',('Update - ' . $employee[0]['id'].' - '. $employee[0]['emp_code'] .' - '.$employee[0]['name'])); + // echo 'insert emp'; + } + else + { + $value['emp_status'] = 'active'; + $value['created_by'] = $file['created_by']; + $value['client_branch_id'] = $file['client_branch_id']; + $log_message = 'Insert Employee- '.$value['name'] .'('.$value['emp_code'] .') with PK '; + // $this->myLogger->logme('error',('Insert - ' . $value['emp_code'] .' - '. $value['name'])); + // echo 'update emp'; + } + + $this->employeeModel->save($value); + $emp_id = $this->employeeModel->getInsertID(); + if($emp_id != 0){ $log_message .= $emp_id; } + else{ $emp_id = $employee[0]['id']; } + + $this->myLogger->logme('error',$log_message); + + //save policy table + $employee_policy = $this->employeePolicyModel->checkExistingEmpPolicy(['employee_id' => $emp_id,'client_policy_id' => $file['policy_id']]); + if(count($employee_policy)) + { + $policy_data['updated_by'] = $file['created_by']; + $policy_data['id'] = $employee_policy[0]['id']; + $policy_data['status'] = 'active'; + + $log_message = 'Update Employee Policy for '. $value['name'].'('. $value['emp_code'].') with PK- ' . $employee_policy[0]['id'] .' client policy ID '.$employee_policy[0]['client_policy_id'].' with SI '.$policy_data['basic_cover_si']; + // echo 'insert policy'; + } + else + { + $policy_data['employee_id'] = $emp_id; + $policy_data['client_policy_id'] = $file['policy_id']; + $policy_data['created_by'] = $file['created_by']; + $policy_data['status'] = 'active'; + $log_message = 'Insert Employee Policy for '. $value['name'].'('. $value['emp_code'].') - client policy id -'. $file['policy_id'].' - with SI '.$policy_data['basic_cover_si']; + // echo 'update policy'; + } + + $this->employeePolicyModel->save($policy_data); + $emp_policy_id = $this->employeePolicyModel->getInsertID(); + if($emp_policy_id != 0)//emp policy inserted + { + $log_message .= ' with PK ' . $emp_policy_id; + + //make endorsement entry if action is addition OR Dependt addition + if(($file['action'] == 'missed_inception' || $file['action'] == 'dependent_addition' || $file['action'] == 'addition') && $temp['source'] == 'excel') + { + $log_message = $file['action'].' - endorsement'. $value['emp_code'].' - '.$value['name'].' - with policy id'.$emp_policy_id; + $this->myLogger->logme('error',$log_message); + $actions = ($file['action'] == 'dependent_addition' ? 'da' : ($file['action'] == 'addition' ? 'a' : NULL)); + $addition_endorse_data = ['pk' => $emp_policy_id,'group_key' => rand(100000, 999999),'emp_code' => $value['emp_code'],'table_name' => 'employee_polices','actions' => $actions,'name' => $value['name'],'field_name' => 'basic_cover_si','old_value' => NULL,'new_value' => $policy_data['basic_cover_si'],'remarks' => 'addition endorsement','file_id' => $file['id'],'created_by' => $file['created_by']]; + $this->employeeEndorsementforAddtionAndDependentAddition($addition_endorse_data); + } + + } + else{ $emp_policy_id = $employee_policy[0]['id']; } - $this->myLogger->logme('error',$log_message); + $this->myLogger->logme('error',$log_message); }// if end - }// for end + }// is array check end + }// for end }//function end @@ -1748,10 +1831,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(); @@ -1792,8 +1875,173 @@ class EmployeeServiceController extends AdminController $this->messageModel->insert($msg_data); - } - - - +} + + +public function employeesEnrollmentInsert($params) +{ + + helper('excel_util_helper'); + //get file name + $file_id = $params['file_id']; + $file = $this->fileModel->find($file_id); + // dd($file); + $return = []; + if(!isset($file)) + { + //file not found in DB + return array('status' => false, 'msg' => 'file not found in DB'); + } + $file_name_with_path = WRITEPATH."/uploads/excel/".$file['file_name']; + + //check physical file + if(!file_exists($file_name_with_path)) + { + //file not found update status and reason + $message = "Physical file not found"; + // echo $message; + $this->myLogger->logme('error',($message . ' for file id ' . $file_id)); + $this->fileModel->where('id', $file_id)->set(['status' => 'failed','reason' => json_encode(['error_summary' => array_count_values([5]),'error_data' => $message])])->update(); + return array('error_summary' => [5], 'error_data' => $message); + } + + //get excel data + $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file_name_with_path); + $sheet = $spreadsheet->getActiveSheet(); + + $highestRowAndColumn = $sheet->getHighestRowAndColumn(); + $result = ['error_type' => 2,'error_summary' => [], 'error_data' => [] ]; + $columns_to_check = $this->enrollment_excel_columns; + $keys = array_keys($columns_to_check); + $allowedHighestColumn = end($columns_to_check); + $excel_data = $sheet->rangeToArray('A1:' . $allowedHighestColumn['col_cell_name'] . $highestRowAndColumn['row']); + // print_r($keys);die(); + + //remove header + unset($excel_data[0]); + // dd($excel_data); + $emp_emails = []; + + //check is welcome notification enabled + $notification = $this->notificationModel->where('client_id',$file['client_id'])->where('template_name','member_welcome_mail')->first(); + // dd($notification); + $client_details = $this->clientModel->where('id', $file['client_id'])->first(); + + foreach ($excel_data as $key => $row) + { + // dd($key.'-'.count($excel_data)); + $value = []; + $policy_data = []; + + $value['emp_code'] = $row[1]; + $value['name'] = $row[2]; + $value['doj'] = (!empty($row[3]) ? convert_string_to_date($row[3],'Y-m-d'): null); + $value['gender'] = $row[4]; + $value['relationship'] = ucfirst(trim($row[5])); + $value['dob'] = convert_string_to_date($row[6],'Y-m-d'); + $value['email_corporate'] = $row[7]; + $value['mobile'] = $row[8]; + $value['band'] = $row[10]; + $value['basic_pay'] = $row[11]; + $value['unit'] = $row[12]; + $value['family_floater_key'] = null; + $value['client_id'] = $file['client_id']; + $value['client_branch_id'] = $file['client_branch_id']; + + $value['temp']['emp_id'] = null; // dummy value for using exisitng funciton in model + if (strtolower(trim($value['relationship'])) === 'mother' || strtolower(trim($value['relationship'])) === 'Father') { + $relation = 'parent'; + } else if(strtolower(trim($value['relationship'])) === 'son' || strtolower(trim($value['relationship'])) === 'daughter'){ + $relation = 'child'; + }else if(strtolower(trim($value['relationship'])) === 'father in Law' || strtolower(trim($value['relationship'])) === 'mother in Law'){ + $relation = 'parent_in_law'; + }else if(strtolower(trim($value['relationship'])) === 'spouse'){ + $relation = 'spouse'; + }else{ + $relation = 'self'; + } + $value['family_floater_key'] = $relation; + + $policy_data['basic_cover_si'] = $row[9]; + $policy_data['client_policy_id'] = $file['policy_id']; + + $employee = $this->employeeModel->checkExistingEmployee($value,$file['client_branch_id']); + unset($value['temp']); + //save employee table + // dd($employee['id']); + if($employee !== null) + { + $value['updated_by'] = $file['created_by']; + $value['id'] = $employee['id']; + $value['emp_status'] = 'draft'; + + $log_message = 'Enrollment Update Employee - '.$employee['name'].'('.$employee['emp_code'].') with PK '.$employee['id']; + } + else + { + $value['emp_status'] = 'draft'; + $value['created_by'] = $file['created_by']; + $log_message = 'Enrollment Insert Employee- '.$value['name'] .'('.$value['emp_code'] .') with PK '; + } + + $this->employeeModel->save($value); + $emp_id = $this->employeeModel->getInsertID(); + if($emp_id != 0){ $log_message .= $emp_id; } + else{ $emp_id = $employee['id']; } + + $this->myLogger->logme('error',$log_message); + + //save policy table + $employee_policy = $this->employeePolicyModel->checkExistingEmpPolicy(['employee_id' => $emp_id,'client_policy_id' => $file['policy_id']]); + if(count($employee_policy)) + { + $policy_data['updated_by'] = $file['created_by']; + $policy_data['id'] = $employee_policy[0]['id']; + $policy_data['status'] = 'draft'; + + $log_message = 'Update Employee Policy for '. $value['name'].'('. $value['emp_code'].') with PK- ' . $employee_policy[0]['id'] .' client policy ID '.$employee_policy[0]['client_policy_id'].' with SI '.$policy_data['basic_cover_si']; + // echo 'insert policy'; + } + else + { + $policy_data['employee_id'] = $emp_id; + $policy_data['client_policy_id'] = $file['policy_id']; + $policy_data['created_by'] = $file['created_by']; + $policy_data['status'] = 'draft'; + $log_message = 'Insert Employee Policy for '. $value['name'].'('. $value['emp_code'].') - client policy id -'. $file['policy_id'].' - with SI '.$policy_data['basic_cover_si']; + // echo 'update policy'; + } + + $this->employeePolicyModel->save($policy_data); + $emp_policy_id = $this->employeePolicyModel->getInsertID(); + $this->myLogger->logme('error',$log_message); + + //save email of self for send mail later + if (isset($notification) && $notification['enabled'] == 1 && $notification['mail_content'] != '') + { + if(strtolower($value['relationship']) == 'self' && $value['email_corporate'] != "") + { + $params['dataToInsert'] = $value; //holds employee master data + $params['notification'] = $notification; + $params['client_data'] = $client_details; + + //store email and mail content via helper to send notification + $emp_emails[] = sendMailNotification::sendMailNotification('member_welcome_mail', $params); + Kint::dump($emp_emails); + Kint::dump($key.'-'.count($excel_data)); + // if mail count is 20 send bulk mail and reset emp_emails variable + if (count($emp_emails) == 20 || $key == count($excel_data) ) { + $job_details = new Jobs(); + $r = Jobs::addJob(['job_name' => 'bulk_mail','payload' => $emp_emails]); + echo 'Mail triggered'; + $emp_emails = []; + } + + } + } + } //end of for loop + + return true; +} + } diff --git a/app/Controllers/JobWorker.php b/app/Controllers/JobWorker.php index 38fd648a..eb9f96e2 100644 --- a/app/Controllers/JobWorker.php +++ b/app/Controllers/JobWorker.php @@ -4,6 +4,13 @@ namespace App\Controllers; use App\Models\JobModel; +use App\Models\ClientModel; +use App\Models\ClientPolicyModel; +use App\Models\NotificationModel; +use App\Models\EmployeePolicyModel; + +use App\Helpers\sendMailNotification; + class JobWorker extends AdminController { const STATUS_DONE = 'done'; @@ -14,25 +21,120 @@ class JobWorker extends AdminController * Constructs the class */ - private static $event_class_mapping = [ - 'add' => ['type' => 'HC', 'handler' => 'App\\Helpers\\HttpRequestHelper'], 'sub' => ['type' => 'CC', 'handler' => 'App\\Controllers\\Jobs\SubJob'], 'fancy_date_time_format' => ['type' => 'HF', 'handler' => 'fancy_date_time_format'], 'addNumber' => ['type' => 'HC', 'handler' => 'App\\Model\\HttpRequestHelper'], 'excelFileFormatValidation' => ['type' => 'CC', 'handler' => 'App\\Controllers\\EmployeeServiceController'], 'excelFileDataValidation' => ['type' => 'CC', 'handler' => 'App\\Controllers\\EmployeeServiceController'], 'employeesOnboardPreprocess' => ['type' => 'CC', 'handler' => 'App\\Controllers\\EmployeeServiceController'], 'employeeDisembark' => ['type' => 'CC', 'handler' => 'App\\Controllers\\EmployeeServiceController'], 'employeesSIEnhanceProcess' => ['type' => 'CC', 'handler' => 'App\\Controllers\\EmployeeServiceController'], 'employeesCorrectionProcess' => ['type' => 'CC', 'handler' => 'App\\Controllers\\EmployeeServiceController'], 'send_email' => ['type' => 'HC', 'handler' => 'App\\Helpers\\MailHelper'], 'bulk_mail' => ['type' => 'HC', 'handler' => 'App\\Helpers\\MailHelper'], 'insertBatchList' => ['type' => 'CC', 'handler' => 'App\\Controllers\\EmpDataServiceController'], - - 'importInceptionFileValidation' => ['type' => 'CC', 'handler' => 'App\\Controllers\\EmpDataServiceController'], - 'importInceptionUpdateTPAandUHID' => ['type' => 'CC', 'handler' => 'App\\Controllers\\EmpDataServiceController'], - 'cashDepositCalculationForInception' => ['type' => 'CC', 'handler' => 'App\\Controllers\\EmpDataServiceController'], - 'sendMailForDownloadingECard' => ['type' => 'CC', 'handler' => 'App\\Controllers\\EmpDataServiceController'], - - 'importCorrectionValidation' => ['type' => 'CC', 'handler' => 'App\\Controllers\\EmpDataServiceController'], - 'importCorrectionUpdateEndorsementID' => ['type' => 'CC', 'handler' => 'App\\Controllers\\EmpDataServiceController'], - - 'cashDepositCalculationForSIEnhancement' => ['type' => 'CC', 'handler' => 'App\\Controllers\\EmpDataServiceController'], - 'importSIEnhancementValidation' => ['type' => 'CC', 'handler' => 'App\\Controllers\\EmpDataServiceController'], - 'importSIEnhancementUpdateEndorsementID' => ['type' => 'CC', 'handler' => 'App\\Controllers\\EmpDataServiceController'], - - 'cashDepositCalculationForDeletion' => ['type' => 'CC', 'handler' => 'App\\Controllers\\EmpDataServiceController'], - 'importDeletionValidation' => ['type' => 'CC', 'handler' => 'App\\Controllers\\EmpDataServiceController'], - 'importDeletionUpdateEndorsementID' => ['type' => 'CC', 'handler' => 'App\\Controllers\\EmpDataServiceController'], - ]; + private static $event_class_mapping = [ + 'add' => [ + 'type' => 'HC', // Handler Category (Possible values: HC, CC, HF) + 'handler' => 'App\Helpers\HttpRequestHelper', + ], + 'sub' => [ + 'type' => 'CC', // Handler Category + 'handler' => 'App\Controllers\Jobs\SubJob', + ], + 'fancy_date_time_format' => [ + 'type' => 'HF', // Handler Category (Possible values: HC, CC, HF) + 'handler' => 'fancy_date_time_format', // Likely a custom function + ], + 'addNumber' => [ + 'type' => 'HC', // Handler Category + 'handler' => 'App\Model\HttpRequestHelper', + ], + 'excelFileFormatValidation' => [ + 'type' => 'CC', // Handler Category + 'handler' => 'App\Controllers\EmployeeServiceController', + ], + 'excelFileDataValidation' => [ + 'type' => 'CC', // Handler Category + 'handler' => 'App\Controllers\EmployeeServiceController', + ], + 'employeesOnboardPreprocess' => [ + 'type' => 'CC', // Handler Category + 'handler' => 'App\Controllers\EmployeeServiceController', + ], + 'employeeDisembark' => [ + 'type' => 'CC', // Handler Category + 'handler' => 'App\Controllers\EmployeeServiceController', + ], + 'employeesSIEnhanceProcess' => [ + 'type' => 'CC', // Handler Category + 'handler' => 'App\Controllers\EmployeeServiceController', + ], + 'employeesCorrectionProcess' => [ + 'type' => 'CC', // Handler Category + 'handler' => 'App\Controllers\EmployeeServiceController', + ], + 'send_email' => [ + 'type' => 'HC', // Handler Category + 'handler' => 'App\Helpers\MailHelper', + ], + 'bulk_mail' => [ + 'type' => 'HC', // Handler Category + 'handler' => 'App\Helpers\MailHelper', + ], + 'insertBatchList' => [ + 'type' => 'CC', // Handler Category + 'handler' => 'App\Controllers\EmpDataServiceController', + ], + + // Employee Data Service Events + 'importInceptionFileValidation' => [ + 'type' => 'CC', // Handler Category + 'handler' => 'App\Controllers\EmpDataServiceController', + ], + 'importInceptionUpdateTPAandUHID' => [ + 'type' => 'CC', // Handler Category + 'handler' => 'App\Controllers\EmpDataServiceController', + ], + 'cashDepositCalculationForInception' => [ + 'type' => 'CC', // Handler Category + 'handler' => 'App\Controllers\EmpDataServiceController', + ], + 'sendMailForDownloadingECard' => [ + 'type' => 'CC', // Handler Category + 'handler' => 'App\Controllers\EmpDataServiceController', + ], + + 'importCorrectionValidation' => [ + 'type' => 'CC', // Handler Category + 'handler' => 'App\Controllers\EmpDataServiceController', + ], + 'importCorrectionUpdateEndorsementID' => [ + 'type' => 'CC', // Handler Category + 'handler' => 'App\Controllers\EmpDataServiceController', + ], + + 'cashDepositCalculationForSIEnhancement' => [ + 'type' => 'CC', // Handler Category + 'handler' => 'App\Controllers\EmpDataServiceController', + ], + 'importSIEnhancementValidation' => [ + 'type' => 'CC', // Handler Category + 'handler' => 'App\Controllers\EmpDataServiceController', + ], + 'importSIEnhancementUpdateEndorsementID' => [ + 'type' => 'CC', // Handler Category + 'handler' => 'App\Controllers\EmpDataServiceController', + ], + + 'cashDepositCalculationForDeletion' => [ + 'type' => 'CC', // Handler Category + 'handler' => 'App\Controllers\EmpDataServiceController', + ], + 'importDeletionValidation' => [ + 'type' => 'CC', // Handler Category + 'handler' => 'App\Controllers\EmpDataServiceController', + ], + 'importDeletionUpdateEndorsementID' => [ + 'type' => 'CC', // Handler Category + 'handler' => 'App\Controllers\EmpDataServiceController', + ], + 'employeesEnrollmentInsert' => [ + 'type' => 'CC', // Handler Category + 'handler' => 'App\Controllers\EmployeeServiceController', + ] +]; + + + public function __construct() { // echo 'HiC';//die(); @@ -228,6 +330,71 @@ class JobWorker extends AdminController } + public static function enrollment_status() { + $clientModel = new ClientModel(); + $clientPolicyModel = new ClientPolicyModel(); + $notificationModel = new NotificationModel(); + $employeePolicyModel = new EmployeePolicyModel(); + $myLogger = \Config\Services::mylogger(); + + $client_policy_data = $clientPolicyModel->where('is_active', 1) + ->where('policy_status', 1) + ->where('inception_type', 2) + ->findAll(); + $currentDate = date('Y-m-d'); + + // Update policy status based on start and end dates + foreach ($client_policy_data as $client_policy) { + $id = $client_policy['id']; + + if ($currentDate == $client_policy['policy_start_date']) { + $clientPolicyModel->update($id, ['open_for_enrollment' => 1]); + } + if ($client_policy['policy_end_date'] < $currentDate) { + $clientPolicyModel->update($id, ['open_for_enrollment' => 0]); + } + } + + $reminder_whole_mail = []; + foreach ($client_policy_data as $client_policy) { + $employee = $employeePolicyModel->select('employees.*') + ->join('employees', 'employee_polices.employee_id = employees.id', 'left') + ->where('employee_polices.client_policy_id', $client_policy['id']) + ->first(); + $client_data = $clientModel->find($client_policy['client_id']); + $notification_data = $notificationModel->where('client_id', $client_policy['client_id']) + ->where('template_name', 'member_reminder_mail') + ->first(); + + if ($notification_data && $notification_data['enabled'] == 1 && $currentDate == $client_policy['reminder_date']) { + $params['emp_data'] = $employee; + $params['client_data'] = $client_data; + $params['notification_data'] = $notification_data; + $reminder_whole_mail[] = sendMailNotification::sendMailNotification('member_reminder_mail', $params); + } + } + // Process and queue bulk emails + $temp_whole_data = []; + $count = 0; + foreach ($reminder_whole_mail as $whole_index => $values) { + foreach ($values as $index => $value) { + $temp_whole_data[] = $value; + $count++; + + if ($count == 20 || ($whole_index == count($reminder_whole_mail) - 1 && $index == count($values) - 1)) { + if (!empty($temp_whole_data)) { + Jobs::addJob(['job_name' => 'bulk_mail', 'payload' => $temp_whole_data]); + $temp_whole_data = []; + $count = 0; + } + } + } + } + + return json_encode(true); + } + + } diff --git a/app/Controllers/MasterController.php b/app/Controllers/MasterController.php index 18e73a8e..f364d1de 100644 --- a/app/Controllers/MasterController.php +++ b/app/Controllers/MasterController.php @@ -1062,10 +1062,9 @@ class MasterController extends AdminController //start CD Master list public function CDMasterList() { - $data['CD_Master_Data'] = $this->CDMasterModel->getCDMasterList(); - $data['insurers'] = $this->insurerModel->findAll(); - $data['clients'] = $this->clientModel->findAll(); + $data['insurers'] = $this->insurerModel->where('is_active', 1)->findAll(); + $data['clients'] = $this->clientModel->where('is_active', 1)->findAll(); $this->loadLayout('cd_master_list', $data); } @@ -1157,7 +1156,12 @@ class MasterController extends AdminController public function getCDMasterDataByID($id = null) { - $cd_data = $this->CDMasterModel->where('id', $id)->first(); + $cd_data = $this->CDMasterModel + ->where('id', $id) + ->where('is_active', 1) + ->first(); + + // convert the date formate 2000-01-01 to 01-01-2000 $cd_data['opening_date'] = date('d-m-Y', strtotime($cd_data['opening_date'])); if ($cd_data) { @@ -1169,7 +1173,10 @@ class MasterController extends AdminController public function checkUniqueCDAccountNumber($AccountNumber) { - $uniqueAC = $this->CDMasterModel->where('cd_ac_no', $AccountNumber)->findAll(); + $uniqueAC = $this->CDMasterModel + ->where('cd_ac_no', $AccountNumber) + ->where('is_active', 1) + ->findAll(); if($uniqueAC != null){ return $this->respond(['status' => true, 'message' => 'The CD Account Number is Already Exist', 'code' => 200], 200); @@ -1184,7 +1191,18 @@ class MasterController extends AdminController $this->myLogger->logme('error','CDMaster Remove function called'); $data['updated_by'] = get_session_userid(); $data['is_active'] = 0; - $update = $this->CDMasterModel->where('id', $id)->set($data)->update(); + $cash_transaction_data = $this->CDMasterModel->where('id', $id)->first(); + + $update = $this->CDMasterModel->where('id', $id)->set($data)->update(); + + $cd_tranction_update = $this->clientDepositModel + ->where('client_id', $cash_transaction_data['client_id']) + ->where('insurer_id', $cash_transaction_data['insurer_id']) + ->where('cd_ac_no', $cash_transaction_data['cd_ac_no']) + ->where('sub_type', 7) + ->set($data) + ->update(); + if($update){ return $this->respond(['status' => true,'code' => 200], 200); }else{ diff --git a/app/Controllers/PendingActionsController.php b/app/Controllers/PendingActionsController.php index c7764902..bb8f2e92 100644 --- a/app/Controllers/PendingActionsController.php +++ b/app/Controllers/PendingActionsController.php @@ -7,7 +7,6 @@ use CodeIgniter\HTTP\RequestInterface; use CodeIgniter\HTTP\ResponseInterface; use Psr\Log\LoggerInterface; -use App\Helpers\DepositHelper; use App\Helpers\MailHelper; use App\Helpers\sendMailNotification; @@ -43,10 +42,10 @@ class PendingActionsController extends AdminController public function __construct() { - //section + //session set_session_context('PendingActionsController Called'); - //services + //log services $this->myLogger = \Config\Services::mylogger(); $this->db = \Config\Database::connect(); @@ -60,7 +59,7 @@ class PendingActionsController extends AdminController $this->empEndorsementModel = new EmpEndorsementModel(); } - + //for AJAX public function getPendingActions() { //get pending actions like inception, corrections,deletions,SI enhanccnement to users @@ -71,12 +70,144 @@ class PendingActionsController extends AdminController $deletion = $this->getPendingActionForDeletion(); $tpa = $this->getPendingActionForTPAIDEmpty(); $uhid = $this->getPendingActionForUHIDEmpty(); + $PolicyRenewalData = $this->getPolicyRenewalDataForAllClient(); + // dd($inception, $si_enhancement, $correction, $deletion, $tpa, $uhid); - $data = ['inception' => $inception, 'correction' => $correction, 'si_enhancement' => $si_enhancement, 'deletion' => $deletion, 'tpa' => $tpa, 'uhid' => $uhid]; + $data = ['inception' => $inception, 'correction' => $correction, 'si_enhancement' => $si_enhancement, 'deletion' => $deletion, 'tpa' => $tpa, 'uhid' => $uhid, 'policy' => $PolicyRenewalData]; return $this->respond($data); } + + //for NORMAL + public function getPendingActionsForClientData() + { + + $inception = $this->getPendingActionForInception(); + $correction = $this->getPendingActionForCorrection(); + $si_enhancement = $this->getPendingActionForSIEnhancement(); + $deletion = $this->getPendingActionForDeletion(); + $tpa = $this->getPendingActionForTPAIDEmpty(); + $uhid = $this->getPendingActionForUHIDEmpty(); + $PolicyRenewalData = $this->getPolicyRenewalDataForAllClient(); + + // dd($inception, $si_enhancement, $correction, $deletion, $tpa, $uhid); + + $data = ['inception' => $inception, 'correction' => $correction, 'si_enhancement' => $si_enhancement, 'deletion' => $deletion, 'tpa' => $tpa, 'uhid' => $uhid, 'policy' => $PolicyRenewalData]; + return $data; + } + + //for only COUNT + public function getPendingActionsForDashBoard() + { + $tpa = $this->getPendingActionForTPAIDEmpty(); + $uhid = $this->getPendingActionForUHIDEmpty(); + $deletion = $this->getPendingActionForDeletion(); + $inception = $this->getPendingActionForInception(); + $ticketData = $this->getTicketsDataForDashBoard(); + $correction = $this->getPendingActionForCorrection(); + $si_enhancement = $this->getPendingActionForSIEnhancement(); + $PolicyRenewalData = $this->getPolicyRenewalDataForAllClient(); + + $uhid_export_count = []; + $uhid_not_export_count = []; + foreach ($uhid as $value) { + if($value['batch_export_count'] == 1){ + $uhid_export_count[] = $value['batch_export_count']; + }else{ + $uhid_not_export_count[] = $value['batch_export_count']; + } + } + $tpa_export_count = []; + $tpa_not_export_count = []; + foreach ($tpa as $value) { + if($value['batch_export_count'] == 1){ + $tpa_export_count[] = $value['batch_export_count']; + }else{ + $tpa_not_export_count[] = $value['batch_export_count']; + } + } + $deletion_export_count = []; + $deletion_not_export_count = []; + foreach ($deletion as $value) { + if($value['batch_export_count'] == 1){ + $deletion_export_count[] = $value['batch_export_count']; + }else{ + $deletion_not_export_count[] = $value['batch_export_count']; + } + } + $correction_export_count = []; + $correction_not_export_count = []; + foreach ($correction as $value) { + if($value['batch_export_count'] == 1){ + $correction_export_count[] = $value['batch_export_count']; + }else{ + $correction_not_export_count[] = $value['batch_export_count']; + } + } + $si_export_count = []; + $si_not_export_count = []; + foreach ($si_enhancement as $value) { + if($value['batch_export_count'] == 1){ + $si_export_count[] = $value['batch_export_count']; + }else{ + $si_not_export_count[] = $value['batch_export_count']; + } + } + + // dd($uhid_export_count, $tpa_export_count ,$deletion_export_count, $correction_export_count, $si_export_count, $ticketData, $inception, $si_enhancement, $correction, $deletion, $tpa, $uhid, $PolicyRenewalData); + + $inception = count($inception); + $correction = count($correction); + $si_enhancement = count($si_enhancement); + $deletion = count($deletion); + $tpa = count($tpa); + $uhid = count($uhid); + $PolicyRenewalData = count($PolicyRenewalData); + $ticketData = count($ticketData); + + $uhid_export_count = count($uhid_export_count); + $tpa_export_count = count($tpa_export_count); + $deletion_export_count = count($deletion_export_count); + $correction_export_count = count($correction_export_count); + $si_export_count = count($si_export_count); + + $uhid_not_export_count = count($uhid_not_export_count); + $tpa_not_export_count = count($tpa_not_export_count); + $deletion_not_export_count = count($deletion_not_export_count); + $correction_not_export_count = count($correction_not_export_count); + $si_not_export_count = count($si_not_export_count); + + + // dd($inception, $si_enhancement, $correction, $deletion, $tpa, $uhid, $PolicyRenewalData); + + $data = [ + 'inception' => $inception, + 'correction' => $correction, + 'si_enhancement' => $si_enhancement, + 'deletion' => $deletion, + 'tpa' => $tpa, + 'uhid' => $uhid, + 'PolicyRenewalData' => $PolicyRenewalData, + 'ticketData' => $ticketData, + + 'uhid_export_count' => $uhid_export_count, + 'tpa_export_count' => $tpa_export_count, + 'deletion_export_count' => $deletion_export_count, + 'correction_export_count' => $correction_export_count, + 'si_export_count' => $si_export_count, + + 'uhid_not_export_count' => $uhid_not_export_count, + 'tpa_not_export_count' => $tpa_not_export_count, + 'deletion_not_export_count' => $deletion_not_export_count, + 'correction_not_export_count' => $correction_not_export_count, + 'si_not_export_count' => $si_not_export_count, + ]; + return $data; + } + + + public function getPendingActionForInception() @@ -86,7 +217,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 +233,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); @@ -121,7 +252,6 @@ class PendingActionsController extends AdminController return $results; } - public function getPendingActionForCorrection() { @@ -152,6 +282,7 @@ class PendingActionsController extends AdminController clients.id as client_id, client_branch.id as branch_id, client_branch.branch_name, + policy_type.policy_type as policy_name, emp_endorsement.id, emp_endorsement.pk, emp_endorsement.endorsement_id, @@ -161,10 +292,20 @@ class PendingActionsController extends AdminController emp_endorsement.actions, emp_endorsement.name, emp_endorsement.status, - employees.name as ename + employees.name as ename, + ( + SELECT COUNT(*) + FROM batch_files bl + WHERE bl.client_id = clients.id + AND bl.actions = "export" + AND bl.event_type = "correction" + AND bl.insurer_or_tpa = "tpa" + ) AS export_count ') ->join('employees', 'emp_endorsement.pk = employees.id AND employees.is_active = 1 AND employees.emp_status = \'active\'') ->join('clients', 'employees.client_id = clients.id AND clients.is_active = 1', 'left') + ->join('client_policy', 'client_policy.client_id = clients.id AND clients.is_active = 1', 'left') + ->join('policy_type', 'client_policy.policy_type_id = policy_type.id ') ->join('client_branch', 'client_branch.id = employees.client_branch_id', 'left') ->where([ 'emp_endorsement.actions' => 'c', @@ -195,14 +336,16 @@ class PendingActionsController extends AdminController $results = $query->getResultArray(); - $filteredResults = array_filter($results, function ($value) { - return $value['subquery_count'] != 0; - }); + $filteredResults = []; + foreach ($results as $value) { + if ($value['subquery_count'] != 0) { + $filteredResults[] = $value; + } + } return $filteredResults; } - public function getPendingActionForSIEnhancement() { @@ -234,8 +377,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 +392,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, @@ -283,14 +425,16 @@ class PendingActionsController extends AdminController $results = $query->getResultArray(); - $filteredResults = array_filter($results, function ($value) { - return $value['subquery_count'] != 0; - }); + $filteredResults = []; + foreach ($results as $value) { + if ($value['subquery_count'] != 0) { + $filteredResults[] = $value; + } + } return $filteredResults; } - public function getPendingActionForDeletion() { @@ -322,8 +466,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 +481,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 +489,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'); @@ -371,14 +514,16 @@ class PendingActionsController extends AdminController // Fetch the results $results = $query->getResultArray(); - $filteredResults = array_filter($results, function ($value) { - return $value['subquery_count'] != 0; - }); - + $filteredResults = []; + foreach ($results as $value) { + if ($value['subquery_count'] != 0) { + $filteredResults[] = $value; + } + } + return $filteredResults; } - public function getPendingActionForUHIDEmpty() { // Subquery for batch_export_count @@ -406,7 +551,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 +559,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 @@ -427,7 +572,6 @@ class PendingActionsController extends AdminController return $results; } - public function getPendingActionForTPAIDEmpty() { @@ -459,7 +603,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 +614,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'); @@ -485,4 +629,86 @@ class PendingActionsController extends AdminController return $results; } + + public function getPolicyRenewalDataForAllClient() + { + $PolicyRenewalData = $this->clientPolicyModel + ->select(' + clients.client_name, + client_branch.branch_name, + policy_type.policy_type as policy_name, + client_policy.policy_end_date, + client_branch.id as branch_id + ') + ->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.is_active', 1) + ->where('client_policy.policy_status', 0) + ->where('clients.is_active', 1) + ->where('client_branch.is_active', 1) + ->where('client_policy.policy_end_date < DATE_ADD(CURDATE(), INTERVAL 2 MONTH)', null, false) + ->get() + ->getResultArray(); + + return $PolicyRenewalData; + + } + + public function getTicketsDataForDashBoard() + { + $db = \Config\Database::connect(); + + $ticket_data = $db->table('hdz_tickets') + ->select('hdz_tickets.*, hdz_status.status') + ->join('hdz_status', 'hdz_status.id = hdz_tickets.status') + ->where('hdz_status.active', 1) + ->where('hdz_tickets.status !=', 5) + ->get() + ->getResultArray(); + + return $ticket_data; + } + + //ticket status count + public function getTicketStatusCount() + { + + $db = \Config\Database::connect(); + + // Count status = 1 + $countStatus1 = $db->table('hdz_tickets') + ->selectCount('status') + ->where('status', 1) + ->get() + ->getRowArray()['status']; + + // Count status = 4 + $countStatus4 = $db->table('hdz_tickets') + ->selectCount('status') + ->where('status', 4) + ->get() + ->getRowArray()['status']; + + // Count status = 2 + $countStatus2 = $db->table('hdz_tickets') + ->selectCount('status') + ->where('status', 2) + ->get() + ->getRowArray()['status']; + + // Count status = 3 + $countStatus3 = $db->table('hdz_tickets') + ->selectCount('status') + ->where('status', 3) + ->get() + ->getRowArray()['status']; + + + } + + public function getexportCount() + { + + } } diff --git a/app/Controllers/RestAuthenticationController.php b/app/Controllers/RestAuthenticationController.php index 6efaa163..b313789e 100644 --- a/app/Controllers/RestAuthenticationController.php +++ b/app/Controllers/RestAuthenticationController.php @@ -69,15 +69,13 @@ class RestAuthenticationController extends AdminController { try { $mobile_number = $this->request->getJSON()->mobile_number; - $randomNumber = rand(100000, 999999); - $randomNumber = 123456; + $employeeData = $this->employeeModel->where('mobile', $mobile_number)->where('relationship', 'self')->first(); if ($employeeData) { - $id= $employeeData["id"]; - $otp = $this->employeeModel->where('id', $id)->set('otp', $randomNumber)->update(); - $result = ['user_verification' => true ,'message' => "Verified Successfully", 'otp'=>$randomNumber]; + + $result = ['user_verification' => true ,'message' => "Verified Successfully"]; return $this->respond(['status' => 'success','code' => 200,'data' => $result],200); } else { $result = ['user_verification' => false , 'message' => "User not found"]; @@ -92,13 +90,13 @@ class RestAuthenticationController extends AdminController public function getVerifiedUserData() { - // try { + try { $mobile_number = $this->request->getJSON()->mobile_number; - $otp = $this->request->getJSON()->otp; + $otp_verification = $this->request->getJSON()->otp_verification; $employeeData = $this->employeeModel->where('mobile', $mobile_number)->where('relationship', 'self')->first(); - if ($employeeData && $otp == $employeeData["otp"] || $employeeData && isset($this->request->getJSON()->login_by_hr)) { + if ($employeeData && $otp_verification == true || $employeeData && isset($this->request->getJSON()->login_by_hr)) { $auth = HttpRequestHelper::getRequestInfo(); if ($auth) { $data = [ @@ -108,36 +106,31 @@ class RestAuthenticationController extends AdminController 'platform' => $auth['platform'], 'broswer' => $auth['browser'], ]; - - $authdata= $this->authHistoryModel->insert($data); - + $this->authHistoryModel->insert($data); } - $otp_null = $this->employeeModel->where('id', $employeeData["id"])->set('otp', null)->update(); - - + $result = JWTToken::encode($employeeData); - return $this->respond(['status' => 'success','code' => 200,'data' => $result],200); + return $this->respond(['status' => 'success','code' => 200,'data' => $result],200); + } else { return $this->respond(['status' => 'failed','code' => 404,'data' => "Invalid OTP"],200); } - // } catch (\Exception $e) { - // return $this->respond(['status' => 'failed','code' => 500,'data' => $e->getMessage()],500); - // } + } catch (\Exception $e) { + return $this->respond(['status' => 'failed','code' => 500,'data' => $e->getMessage()],500); + } } public function verifyHrWithMobileNumber() { try { $mobile_number = $this->request->getJSON()->mobile_number; - $randomNumber = rand(100000, 999999); - $randomNumber = 123456; + $HrData = $this->hrModel->where('mobile', $mobile_number)->where('contact_type', 'client')->first(); if ($HrData) { - $id= $HrData["id"]; - $otp = $this->hrModel->where('id', $id)->set('otp', $randomNumber)->update(); - $result = ['user_verification' => true ,'message' => "Verified Successfully", 'otp'=>$randomNumber]; + + $result = ['user_verification' => true ,'message' => "Verified Successfully"]; return $this->respond(['status' => 'success','code' => 200,'data' => $result],200); } else { $result = ['user_verification' => false , 'message' => "User not found"]; @@ -154,10 +147,10 @@ class RestAuthenticationController extends AdminController { try { $mobile_number = $this->request->getJSON()->mobile_number; - $otp = $this->request->getJSON()->otp; + $otp_verification = $this->request->getJSON()->otp_verification; $hrData = $this->hrModel->where('mobile', $mobile_number)->first(); - if ($hrData && $otp == $hrData["otp"]) { + if ($hrData && $otp_verification == true) { $auth = HttpRequestHelper::getRequestInfo(); if ($auth) { $data = [ @@ -168,10 +161,10 @@ class RestAuthenticationController extends AdminController 'broswer' => $auth['browser'], ]; - $authdata= $this->authHistoryModel->insert($data); + $this->authHistoryModel->insert($data); } - $otp_null = $this->hrModel->where('id', $hrData["id"])->set('otp', null)->update(); + $hrData = $this->hrModel ->select('level_contacts.* , client_branch.client_id as client_id') ->join('client_branch', 'level_contacts.ref_id = client_branch.id', 'left') @@ -179,7 +172,7 @@ class RestAuthenticationController extends AdminController ->find(); $result = JWTToken::encode($hrData['0']); - return $this->respond(['status' => 'success','code' => 200,'data' => $result],200); + return $this->respond(['status' => 'success','code' => 200,'data' => $result],200); } else { return $this->respond(['status' => 'failed','code' => 404,'data' => "Invalid OTP"],200); } @@ -190,11 +183,6 @@ class RestAuthenticationController extends AdminController - public function employeeLogout() - { - - } - public function getUserIdFromToken() { $id = JWTToken::getUserIdFromToken(); diff --git a/app/Filters/AuthJWT.php b/app/Filters/AuthJWT.php index b64a2a76..484372a7 100644 --- a/app/Filters/AuthJWT.php +++ b/app/Filters/AuthJWT.php @@ -37,6 +37,9 @@ class AuthJWT implements FilterInterface $model->update($id, $data); return true; }else{ + + // if($user_data['token_time_out'] != "" && $user_data['token_time_out'] != NULL) + $data =["token_time_out" => '']; $model->update($id, $data); header('Content-Type: application/json'); diff --git a/app/Helpers/DepositHelper.php b/app/Helpers/DepositHelper.php index 3565646e..5d45709e 100644 --- a/app/Helpers/DepositHelper.php +++ b/app/Helpers/DepositHelper.php @@ -54,7 +54,9 @@ class DepositHelper 'cd_ac_no' => $data['cd_ac_no'], 'endorsement_no' => $data['endorsement_no'], 'insurer_id' => $data['insurer_id'], + 'unit' => $data['unit'] ?? null, 'description' => $data['description'], + 'event_name' => $data['event_name'], 'transaction_type' => $data['transaction_type'], 'is_active' => 1, 'created_by' => $loggedInUserID, diff --git a/app/Helpers/MailHelper.php b/app/Helpers/MailHelper.php index da8d2624..7b1a9bc7 100644 --- a/app/Helpers/MailHelper.php +++ b/app/Helpers/MailHelper.php @@ -18,6 +18,7 @@ class MailHelper { // print_r($params);die; + $myLogger = \Config\Services::mylogger(); $emaill = $params['mail']; $subject = $params['subject']; $message = $params['message']; @@ -48,12 +49,16 @@ class MailHelper $email->setMessage($message); if ($email->send()) { + return json_encode(['status' => 'success','code' => 200, 'message'=>'Email Sent Successfully...','data' => $emaill,],200); } else { + $myLogger->logme('error', "mail sent failed - $emaill"); return json_encode(['status' => 'failed','code' => 404,'message'=>'Email Sent Failed...','data' => $emaill ],404); } } catch (Exception $e) { + $msg = $e->getMessage(); + $myLogger->logme('error', "mail sent failed - $msg"); return json_encode(['status' => 'failed','code' => 500,'data' => $emaill],500); } } 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/Helpers/excel_util_helper.php b/app/Helpers/excel_util_helper.php index d14d71a7..4f81d9d3 100644 --- a/app/Helpers/excel_util_helper.php +++ b/app/Helpers/excel_util_helper.php @@ -90,7 +90,7 @@ if(!function_exists('check_relationship')) { // print_r($relationship); // echo '
'; - if($row['current_action'] != null && in_array(strtoupper($row['current_action']), ['I','A','DA']))// check rule only of action column data available + if($row['current_action'] != null && in_array(strtoupper($row['current_action']), ['I','A','DA','MI']))// check rule only of action column data available { if($row[5] != null && $row[4] != null)//$row[5] = relationship $row[4] = Gender { @@ -141,7 +141,7 @@ if(!function_exists('check_doj')) function check_doj($row) { - if($row['current_action'] != null && in_array(strtoupper($row['current_action']), ['I','A','DA']))// check rule only of action column data available + if($row['current_action'] != null && in_array(strtoupper($row['current_action']), ['I','A','DA','MI']))// check rule only of action column data available { $slug = \Config\Services::slug(); $relationship = $slug->slugify($row[5]); @@ -188,7 +188,7 @@ if(!function_exists('check_employee_band')) { function check_employee_band($row,$policy_terms,$slab_details) { - if($row['current_action'] != null && in_array(strtoupper($row['current_action']), ['I','A','DA']))// check rule only of action column data available + if($row['current_action'] != null && in_array(strtoupper($row['current_action']), ['I','A','DA','MI']))// check rule only of action column data available { $is_emp_band_needed = $slab_details['grid_master']['emp_band']; // $is_emp_band_needed = true; @@ -225,12 +225,20 @@ if(!function_exists('check_employee_band')) if(!function_exists('check_si')) { - function check_si($row,$policy_terms,$slab_details) + function check_si($row,$policy_details,$slab_details) { $return_array = array('status' => true,'error' => ''); $is_si_found = false; $is_age_slab_found = false; - if($row['current_action'] != null && in_array(strtoupper($row['current_action']), ['I','A','DA','SI']))// check rule only of action column data available + + if($policy_details[0]['policy_type_id'] == 1 && $slab_details[0]['policy_grid_id'] == 1 && $slab_details[0]['si_or_bp'] == 2) // GPA && grid type 1 for GPA && sub type is basic pay + { + $is_si_found = true; + $is_age_slab_found = true; + $return_array = array('status' => true,'error' => ''); + } + + if($row['current_action'] != null && in_array(strtoupper($row['current_action']), ['I','A','DA','SI','MI']))// check rule only of action column data available { $received_si = $row['current_action'] == 'SI' ? $row[3] : $row[6]; foreach ($slab_details['slab_rates'] as $skey => $slab_value) @@ -247,7 +255,7 @@ if(!function_exists('check_si')) } // check age slab - if(in_array(strtoupper($row['current_action']), ['I','A','DA']) && (($slab_value['premium_type'] == 1 && strtolower($row['5']) == 'self' ) || ($slab_value['premium_type'] == 2) ) ) + if(in_array(strtoupper($row['current_action']), ['I','A','DA','MI']) && (($slab_value['premium_type'] == 1 && strtolower($row['5']) == 'self' ) || ($slab_value['premium_type'] == 2) ) ) { if($row[3] != '' && $row[3] != null)// dob { @@ -311,7 +319,7 @@ if(!function_exists('check_basic_pay')) { function check_basic_pay($row,$policy_terms,$slab_details) { - if($row['current_action'] != null && in_array(strtoupper($row['current_action']), ['I','A','DA']))// check rule only of action column data available + if($row['current_action'] != null && in_array(strtoupper($row['current_action']), ['I','A','DA','MI']))// check rule only of action column data available { $is_basic_pay_needed = $slab_details['grid_master']['basicpay']; // $is_basic_pay_needed = true; @@ -329,7 +337,7 @@ if (!function_exists('check_dob_diff')) { function check_dob_diff($row,$relationships,$default_age_ratio) { // echo 'called'; - if($row['current_action'] != null && in_array(strtoupper($row['current_action']), ['I','A','DA']))// check rule only of action column data available + if($row['current_action'] != null && in_array(strtoupper($row['current_action']), ['I','A','DA','MI']))// check rule only of action column data available { if($row[3] != null && $row[5] != null) { @@ -667,9 +675,10 @@ if (!function_exists('generate_relationship_code')) } } -if (!function_exists('calculate_premimum')) +if (!function_exists('calculate_premium')) { - function calculate_premimum($family_data,$policy_terms,$slab_details,$fileArr,$default_si = null) + // function calculate_premimum($family_data,$policy_terms,$slab_details,$fileArr,$default_si = null) + function calculate_premium(array $family_data,array $policy_terms,array $slab_details,array $fileArr,string $default_si = null,array $existing_units = []) { // dd($family_data); $slug = \Config\Services::slug(); @@ -865,6 +874,116 @@ if (!function_exists('calculate_premimum')) } } +if (!function_exists('calculate_premium_new')) +{ + function calculate_premium_new(array $family_data,array $policy_terms,array $slab_details,array $fileArr,array $existing_units,string $default_si = null,) + { + + //grouping slab details by rack rate name + $temp_slab_rates = group_slab_rates_basedon_name($slab_details); + // dd($temp_slab_rates); + /* 1. construct available/incoming family members composition & count */ + $incoming_familiy_composition = get_familiy_composition($family_data); + // dd($incoming_familiy_composition); + + //2 .get applicable familiy members composition & count from slab details & constrcut an array + //3 in for another loop compare slab level applicable familiy composition with available family composition + $result = []; + foreach($temp_slab_rates as $key => $slab) + { + // dd($slab); + $res = compare_incoming_family_slab_with_configured_slab($slab,$incoming_familiy_composition); + // kint::dump($key); + // kint::dump($res); + + if($res['is_applicable']) + { + $temp_slab_rates[$key]['is_applicable'] = true; + $temp_slab_rates[$key]['members'] = $res['applicable_members']; + + //get applicable members for current rack rate from over all familiy members and calculate max age and max count,self/acting self and grid type and set it in individual familiy member level + $applicable_members_from_familiy = get_applicable_familiy_members($family_data,$res['applicable_members']); + // dd( $applicable_members_from_familiy); + $is_self_acting_self_set = false; + foreach($applicable_members_from_familiy['index'] as $val) + { + $acting_self = false; + if(!$is_self_acting_self_set) + { + if(strtolower($family_data[$val][5]) == 'self' || !$is_self_acting_self_set) $acting_self = true; + $is_self_acting_self_set = true; + } + + $family_data[$val]['temp'] = ['max_age' => max($applicable_members_from_familiy['max_age']),'max_count' => $applicable_members_from_familiy['max_count'],'grid_name' => $key,'grid_master' => $slab['grid_master'],'acting_self' => $acting_self,'premium_type' => $slab['slab_rates'][0]['premium_type']]; + } + } + else + { + $temp_slab_rates[$key]['is_applicable'] = false; + } + } + // dd(); + + //4. if macthed then the current rack rate is applicable and find common variables link max age,max count,grade, basic pay,SI, self/acting self for current rack rate + + foreach($family_data as $fkey => $member) + { + // dd($member); + //get grid type either primary or additional based on current member relationship available in primary_rack_rate_applicable_familiy_members or not. if yes then primaty grid type else additional grid type + + $fileArr['grid_info'] = ['type' => isset($member['temp']['grid_name']) ? $member['temp']['grid_name'] : NULL , 'grid_id' => isset($member['temp']['grid_master']['ui_type']) ? $member['temp']['grid_master']['ui_type'] : NULL]; + + + + //set self (first index of familiy) SI and grade to rest of the familiy + $member[6] = $family_data[0][6]; + $member[10] = $family_data[0][10]; + $member[18] = $family_data[0][18]; + //set default unit if unit is not available in self/members level + if(empty($member[18])){ $member[18] = $existing_units[0]; } + //transform as db row column + $transformed_familiy_member_data = transform_excel_data_to_db($member,$fileArr); + // kint::dump($transformed_familiy_member_data); + //generate relationship code + if($transformed_familiy_member_data['temp']['action'] != 'D' && $transformed_familiy_member_data['temp']['action'] != 'C' && $transformed_familiy_member_data['temp']['action'] != 'SI') + { + $temp_res = generate_relationship_code($transformed_familiy_member_data); + $transformed_familiy_member_data['relationship_code'] = $temp_res['relationship_code']; + $transformed_familiy_member_data['emp_type'] = $temp_res['emp_type_code']; + } + + // // this array hold conditions to allow calculate premium amt + $conditions = [ + 'isEmployeeSourceEnrollment' => $fileArr['id'] == null, + 'isEmployeeSourceExcelFile' => $transformed_familiy_member_data['temp']['source'] == 'excel', + 'isCurrentActionDependentAddition' => $fileArr['action'] == 'dependent_addition', + // 'isPrimaryGridPremiumTypeSingle' => $transformed_familiy_member_data['temp']['premium_type'] == 1, + 'isCurrentRelationshipSelf' => (strtolower($transformed_familiy_member_data['relationship']) == 'self' || (isset($transformed_familiy_member_data['temp']['acting_self']) && $transformed_familiy_member_data['temp']['acting_self'] === true)), + 'isBasicCoverCalculatedToCurrentEmployee' => ($transformed_familiy_member_data['policy_details']['basic_cover_si'] != null && $transformed_familiy_member_data['policy_details']['basic_cover_si'] != 0) + ]; + + $primaryGridTypeCondition = $conditions['isCurrentActionDependentAddition'] && $conditions['isPrimaryGridPremiumTypeSingle'] && $conditions['isCurrentRelationshipSelf'] && $conditions['isBasicCoverCalculatedToCurrentEmployee']; + + // // Final combined condition + if ($conditions['isEmployeeSourceEnrollment'] || $conditions['isEmployeeSourceExcelFile'] || $primaryGridTypeCondition ) { + // dd($transformed_familiy_member_data); + $transformed_familiy_member_data = premium_calculation_manager($transformed_familiy_member_data,$policy_terms,$temp_slab_rates,$default_si); + // dd($transformed_familiy_member_data); + $result[] = $transformed_familiy_member_data; + } + + + // $result[] = $transformed_familiy_member_data; + } + + // dd($result); + return ($result); + // + + + } +} + if (!function_exists('transform_excel_data_to_db')) { @@ -878,14 +997,16 @@ if (!function_exists('transform_excel_data_to_db')) else if($actionArr['action'] == 'deletion'){ $current_column_action = 'D'; } else if($actionArr['action'] == 'correction'){ $current_column_action = 'C'; } else if($actionArr['action'] == 'si_enhancement'){ $current_column_action = 'SI'; } + else if($actionArr['action'] == 'missed_inception'){ $current_column_action = 'MI'; } - if($actionArr['action'] == 'inception' || $actionArr['action'] == 'addition' || $actionArr['action'] == 'dependent_addition') + if($actionArr['action'] == 'inception' || $actionArr['action'] == 'missed_inception' || $actionArr['action'] == 'addition' || $actionArr['action'] == 'dependent_addition') { $policy['basic_cover_si'] = $memArr[6]; $policy['pre_existing_alignments'] = $memArr[14]; // $policy['date_of_exit'] = isset($memArr[16]) ? change_date_format($memArr[16],'d-M-Y','Y-m-d') : NULL; // $policy['reason_for_exit'] = $memArr[17]; + $policy['client_policy_id'] = $actionArr['policy_id']; $policy['date_coverage'] = isset($memArr[7]) ? convert_string_to_date($memArr[7],'Y-m-d') : NULL; $policy['policy_end_date'] = null; @@ -910,7 +1031,11 @@ if (!function_exists('transform_excel_data_to_db')) $result['file_id'] = $actionArr['id']; $result['client_id'] = $actionArr['client_id']; $result['change_event'] = $memArr[15]; + $result['unit'] = $memArr[18]; + $result['temp'] = []; + if(isset($memArr['temp'])) $result['temp'] = array_merge($result['temp'],$memArr['temp']); $result['temp']['grid_type'] = $actionArr['grid_info']['type']; + $result['temp']['band'] = $result['band']; $result['temp']['grid_id'] = $actionArr['grid_info']['grid_id']; $result['temp']['action'] = isset($memArr['current_action']) ? $memArr['current_action'] : $current_column_action; $result['temp']['source'] = isset($memArr['temp']['source']) ? $memArr['temp']['source'] : 'excel'; @@ -932,7 +1057,7 @@ if (!function_exists('premium_calculation_manager')) { function premium_calculation_manager($emp_data,$policy_terms,$slab_details,$default_si = null) { - // Kint::dump($emp_data); + // Kint::dump($emp_data);die(); $myLogger = \Config\Services::mylogger(); // grid type @@ -964,13 +1089,21 @@ if (!function_exists('premium_calculation_manager')) $emp_data['policy_details'] = replace_original_data(original_data:$original_emp_policy_records,current_data:$emp_data['policy_details']); // Kint::dump($policy_data); } - } - //end of fetching data from audit history table + + }//end of fetching data from audit history table //gird and calculation start $slug = \Config\Services::slug(); $grid_type = $emp_data['temp']['grid_id']; - $temp_slab_rates = $emp_data['temp']['grid_type'] == 'primary' ? $slab_details['slab_rates'] : $slab_details['additional_slab_info']['slab_rates']; + $slab_index = isset($emp_data['temp']['grid_name']) ? $emp_data['temp']['grid_name'] : false; + // echo $emp_data['name']; + // kint::dump($slab_index); + if ($slab_index === false) + { + // echo 'not set'; + return false; + } + $temp_slab_rates = $slab_details[ $slab_index ]['slab_rates']; //if curent action is dependent addition OR addition then pull insurer master to set whether add one day from employee date of coverage if($emp_data['temp']['action'] == 'DA' || $emp_data['temp']['action'] == 'A') @@ -984,6 +1117,7 @@ if (!function_exists('premium_calculation_manager')) } // dd($emp_data); $is_match_found = false; + $gst = isset($policy_terms['gst']) && $policy_terms['gst'] != 0 ? $policy_terms['gst'] : 18; switch ($grid_type) { case "1": //GPA - Sum Insured (SI) * Multiplier @@ -991,7 +1125,7 @@ if (!function_exists('premium_calculation_manager')) $employee_received_band = $emp_data['temp']['band']; foreach ($temp_slab_rates as $skey => $slab_value) { - if(($slab_value['si'] == $employee_received_si) || ($slab_value['grade'] != null && $slab_value['grade'] == $employee_received_band && $slab_value['si'] == $employee_received_si)) + if(($slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit']) || ($slab_value['grade'] != null && $slab_value['grade'] == $employee_received_band && $slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'])) { $emp_data['policy_details']['basic_cover_si'] = $slab_value['si']; $emp_data['policy_details']['date_coverage'] = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']); @@ -999,19 +1133,40 @@ if (!function_exists('premium_calculation_manager')) $emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'],$policy_terms['policy_end_date'])->days + 1); $emp_data['policy_details']['premium'] = $slab_value['premium']; $emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'],$emp_data['policy_details']['days'],(calculate_days_bw_dates($policy_terms['policy_start_date'],$policy_terms['policy_end_date'])->days + 1)); - $emp_data['policy_details']['gst'] = (float) number_format(($emp_data['policy_details']['rata_premimum'] * (18/100)),2,'.',''); + $emp_data['policy_details']['gst'] = (float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst/100)),2,'.',''); $is_match_found = true; break; } } + //auto calculate of SI and premium for basic pay type + if(!$is_match_found) + { + if($temp_slab_rates[0]['si_or_bp'] == 2) + { + $temp_si = $emp_data['basic_pay'] * $temp_slab_rates[0]['si_or_bp']; + $temp_premium = ($temp_si * $temp_slab_rates[0]['multiplier']) / 1000; + $emp_data['policy_details']['basic_cover_si'] = $temp_si; + $emp_data['policy_details']['date_coverage'] = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']); + $emp_data['policy_details']['policy_end_date'] = $policy_terms['policy_end_date']; + $emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'],$policy_terms['policy_end_date'])->days + 1); + $emp_data['policy_details']['premium'] = $temp_premium; + $emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'],$emp_data['policy_details']['days'],(calculate_days_bw_dates($policy_terms['policy_start_date'],$policy_terms['policy_end_date'])->days + 1)); + $emp_data['policy_details']['gst'] = (float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst/100)),2,'.',''); + $is_match_found = true; + + $log_message = 'Pre defined SI not found. auto calc SI & premium for -' . $emp_data['emp_code'].' - '. $emp_data['name'].' - '. $temp_si.' - '. $temp_premium; + $myLogger->logme('error',$log_message); + + } + } break; case "2": //GPA - Flat Rate for all SI $employee_received_si = $default_si == null ? $emp_data['policy_details']['basic_cover_si'] : $default_si; foreach ($temp_slab_rates as $skey => $slab_value) { - if($slab_value['si'] == $employee_received_si) + if($slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit']) { $emp_data['policy_details']['basic_cover_si'] = $slab_value['si']; $emp_data['policy_details']['date_coverage'] = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']); @@ -1019,7 +1174,7 @@ if (!function_exists('premium_calculation_manager')) $emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'],$policy_terms['policy_end_date'])->days + 1); $emp_data['policy_details']['premium'] = $slab_value['premium']; $emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'],$emp_data['policy_details']['days'],(calculate_days_bw_dates($policy_terms['policy_start_date'],$policy_terms['policy_end_date'])->days + 1)); - $emp_data['policy_details']['gst'] = (float) number_format(($emp_data['policy_details']['rata_premimum'] * (18/100)),2,'.',''); + $emp_data['policy_details']['gst'] = (float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst/100)),2,'.',''); $is_match_found = true; break; } @@ -1030,7 +1185,7 @@ if (!function_exists('premium_calculation_manager')) $employee_received_si = $default_si == null ? $emp_data['policy_details']['basic_cover_si'] : $default_si; foreach ($temp_slab_rates as $skey => $slab_value) { - if($slab_value['si'] == $employee_received_si && (($slab_value['premium_type'] == 1 && ( strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['primary_rack_rate_acting_self'] || $emp_data['temp']['additional_rack_rate_acting_self']) ) || ($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null) )) + if($slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'] && (($slab_value['premium_type'] == 1 && ( strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['acting_self'] ) ) || ($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null) )) { $emp_data['policy_details']['basic_cover_si'] = $slab_value['si']; $emp_data['policy_details']['date_coverage'] = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']); @@ -1038,7 +1193,7 @@ if (!function_exists('premium_calculation_manager')) $emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'],$policy_terms['policy_end_date'])->days + 1); $emp_data['policy_details']['premium'] = $slab_value['premium']; $emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'],$emp_data['policy_details']['days'],(calculate_days_bw_dates($policy_terms['policy_start_date'],$policy_terms['policy_end_date'])->days + 1)); - $emp_data['policy_details']['gst'] = (float) number_format(($emp_data['policy_details']['rata_premimum'] * (18/100)),2,'.',''); + $emp_data['policy_details']['gst'] = (float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst/100)),2,'.',''); $is_match_found = true; break; } @@ -1053,7 +1208,7 @@ if (!function_exists('premium_calculation_manager')) foreach ($temp_slab_rates as $skey => $slab_value) { $age = calculate_days_bw_dates(from_date: $emp_data['dob'])->y; - if($slab_value['si'] == $employee_received_si && ($slab_value['age_from'] <= $age && $slab_value['age_to'] >= $age) && (($slab_value['premium_type'] == 1 && ( strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['primary_rack_rate_acting_self'] || $emp_data['temp']['additional_rack_rate_acting_self']) ) || ($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null) )) + if($slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'] && ($slab_value['age_from'] <= $age && $slab_value['age_to'] >= $age) && (($slab_value['premium_type'] == 1 && ( strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['acting_self'] ) ) || ($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null) )) { // dd($slab_value); $emp_data['policy_details']['basic_cover_si'] = $slab_value['si']; @@ -1062,7 +1217,7 @@ if (!function_exists('premium_calculation_manager')) $emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'],$policy_terms['policy_end_date'])->days + 1); $emp_data['policy_details']['premium'] = $slab_value['premium']; $emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'],$emp_data['policy_details']['days'],(calculate_days_bw_dates($policy_terms['policy_start_date'],$policy_terms['policy_end_date'])->days + 1)); - $emp_data['policy_details']['gst'] = (float) number_format(($emp_data['policy_details']['rata_premimum'] * (18/100)),2,'.',''); + $emp_data['policy_details']['gst'] = (float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst/100)),2,'.',''); $is_match_found = true; break; } @@ -1074,7 +1229,7 @@ if (!function_exists('premium_calculation_manager')) foreach ($temp_slab_rates as $skey => $slab_value) { $age = calculate_days_bw_dates(from_date: $emp_data['dob'])->y; - if($slab_value['si'] == $employee_received_si && ($slab_value['age_from'] <= $age && $slab_value['age_to'] >= $age) && (($slab_value['premium_type'] == 1 && ( strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['primary_rack_rate_acting_self'] || $emp_data['temp']['additional_rack_rate_acting_self']) ) || ($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null) )) + if($slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'] && ($slab_value['age_from'] <= $age && $slab_value['age_to'] >= $age) && (($slab_value['premium_type'] == 1 && ( strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['acting_self'] ) ) || ($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null) )) { $emp_data['policy_details']['basic_cover_si'] = $slab_value['si']; $emp_data['policy_details']['date_coverage'] = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']); @@ -1082,7 +1237,7 @@ if (!function_exists('premium_calculation_manager')) $emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'],$policy_terms['policy_end_date'])->days + 1); $emp_data['policy_details']['premium'] = $slab_value['premium']; $emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'],$emp_data['policy_details']['days'],(calculate_days_bw_dates($policy_terms['policy_start_date'],$policy_terms['policy_end_date'])->days + 1)); - $emp_data['policy_details']['gst'] = (float) number_format(($emp_data['policy_details']['rata_premimum'] * (18/100)),2,'.',''); + $emp_data['policy_details']['gst'] = (float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst/100)),2,'.',''); $is_match_found = true; break; } @@ -1094,7 +1249,7 @@ if (!function_exists('premium_calculation_manager')) foreach ($temp_slab_rates as $skey => $slab_value) { $age = calculate_days_bw_dates(from_date: $emp_data['dob'])->y; - if($slab_value['si'] == $employee_received_si && ($slab_value['age_from'] <= $age && $slab_value['age_to'] >= $age) && (($slab_value['premium_type'] == 1 && ( strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['primary_rack_rate_acting_self'] || $emp_data['temp']['additional_rack_rate_acting_self']) ) || ($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null) )) + if($slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'] && ($slab_value['age_from'] <= $age && $slab_value['age_to'] >= $age) && (($slab_value['premium_type'] == 1 && ( strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['acting_self'] ) ) || ($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null) )) { // echo $emp_data['name']; $emp_data['policy_details']['basic_cover_si'] = $slab_value['si']; @@ -1103,7 +1258,7 @@ if (!function_exists('premium_calculation_manager')) $emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'],$policy_terms['policy_end_date'])->days + 1); $emp_data['policy_details']['premium'] = $slab_value['premium']; $emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'],$emp_data['policy_details']['days'],(calculate_days_bw_dates($policy_terms['policy_start_date'],$policy_terms['policy_end_date'])->days + 1)); - $emp_data['policy_details']['gst'] = (float) number_format(($emp_data['policy_details']['rata_premimum'] * (18/100)),2,'.',''); + $emp_data['policy_details']['gst'] = (float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst/100)),2,'.',''); $is_match_found = true; break; } @@ -1116,7 +1271,7 @@ if (!function_exists('premium_calculation_manager')) foreach ($temp_slab_rates as $skey => $slab_value) { $age = calculate_days_bw_dates(from_date: $emp_data['dob'])->y; - if($slab_value['si'] == $employee_received_si && ($slab_value['age_from'] <= $age && $slab_value['age_to'] >= $age) && (($slab_value['premium_type'] == 1 && ( strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['primary_rack_rate_acting_self'] || $emp_data['temp']['additional_rack_rate_acting_self']) ) || ($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null) )) + if($slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'] && ($slab_value['age_from'] <= $age && $slab_value['age_to'] >= $age) && (($slab_value['premium_type'] == 1 && ( strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['acting_self'] ) ) || ($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null) )) { $emp_data['policy_details']['basic_cover_si'] = $slab_value['si']; $emp_data['policy_details']['date_coverage'] = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']); @@ -1124,7 +1279,7 @@ if (!function_exists('premium_calculation_manager')) $emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'],$policy_terms['policy_end_date'])->days + 1); $emp_data['policy_details']['premium'] = $slab_value['premium']; $emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'],$emp_data['policy_details']['days'],(calculate_days_bw_dates($policy_terms['policy_start_date'],$policy_terms['policy_end_date'])->days + 1)); - $emp_data['policy_details']['gst'] = (float) number_format(($emp_data['policy_details']['rata_premimum'] * (18/100)),2,'.',''); + $emp_data['policy_details']['gst'] = (float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst/100)),2,'.',''); $is_match_found = true; break; @@ -1138,7 +1293,7 @@ if (!function_exists('premium_calculation_manager')) foreach ($temp_slab_rates as $skey => $slab_value) { - if($slab_value['grade'] == $employee_received_band && $slab_value['si'] == $employee_received_si && (($slab_value['premium_type'] == 1 && ( strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['primary_rack_rate_acting_self'] || $emp_data['temp']['additional_rack_rate_acting_self']) ) || ($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null) )) + if($slab_value['grade'] == $employee_received_band && $slab_value['unit'] == $emp_data['unit'] && $slab_value['si'] == $employee_received_si && (($slab_value['premium_type'] == 1 && ( strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['acting_self'] ) ) || ($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null) )) { // $emp_data['policy_details']['basic_cover_si'] = $slab_value['si']; $emp_data['policy_details']['basic_cover_si'] = $slab_value['si']; @@ -1147,7 +1302,7 @@ if (!function_exists('premium_calculation_manager')) $emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'],$policy_terms['policy_end_date'])->days + 1); $emp_data['policy_details']['premium'] = $slab_value['premium']; $emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'],$emp_data['policy_details']['days'],(calculate_days_bw_dates($policy_terms['policy_start_date'],$policy_terms['policy_end_date'])->days + 1)); - $emp_data['policy_details']['gst'] = (float) number_format(($emp_data['policy_details']['rata_premimum'] * (18/100)),2,'.',''); + $emp_data['policy_details']['gst'] = (float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst/100)),2,'.',''); $is_match_found = true; break; } @@ -1160,7 +1315,7 @@ if (!function_exists('premium_calculation_manager')) foreach ($temp_slab_rates as $skey => $slab_value) { - if($slab_value['si'] == $employee_received_si && (($slab_value['premium_type'] == 1 && ( strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['primary_rack_rate_acting_self'] || $emp_data['temp']['additional_rack_rate_acting_self'])) || ($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null) )) + if($slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'] && (($slab_value['premium_type'] == 1 && ( strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['acting_self'] )) || ($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null) )) { $emp_data['policy_details']['basic_cover_si'] = $slab_value['si']; $emp_data['policy_details']['date_coverage'] = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']); @@ -1168,7 +1323,7 @@ if (!function_exists('premium_calculation_manager')) $emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'],$policy_terms['policy_end_date'])->days + 1); $emp_data['policy_details']['premium'] = $slab_value['premium']; $emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'],$emp_data['policy_details']['days'],(calculate_days_bw_dates($policy_terms['policy_start_date'],$policy_terms['policy_end_date'])->days + 1)); - $emp_data['policy_details']['gst'] = (float) number_format(($emp_data['policy_details']['rata_premimum'] * (18/100)),2,'.',''); + $emp_data['policy_details']['gst'] = (float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst/100)),2,'.',''); $is_match_found = true; break; } @@ -1176,7 +1331,7 @@ if (!function_exists('premium_calculation_manager')) break; case "10": //GMC - Maximum age of Dependents - $max_age = $emp_data['temp']['maxage']; + $max_age = $emp_data['temp']['max_age']; $employee_received_si = $default_si == null ? $emp_data['policy_details']['basic_cover_si'] : $default_si; // echo $emp_data['name'].'-'.$employee_received_si.'
'; // echo $emp_data['temp']['grid_type'].'
'; @@ -1184,10 +1339,10 @@ if (!function_exists('premium_calculation_manager')) foreach ($temp_slab_rates as $skey => $slab_value) { // echo $slab_value['si'].'-'.$slab_value['age_from'].'-'.$slab_value['age_to'].'-'.$max_age.'
'; - if( $slab_value['si'] == $employee_received_si && + if( $slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'] && ($slab_value['age_from'] <= $max_age && $slab_value['age_to'] >= $max_age) && (($slab_value['premium_type'] == 1 && - ( strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['primary_rack_rate_acting_self'] || $emp_data['temp']['additional_rack_rate_acting_self'])) || ($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null) ) ) + ( strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['acting_self'] )) || ($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null) ) ) { $emp_data['policy_details']['basic_cover_si'] = $employee_received_si; $emp_data['policy_details']['date_coverage'] = isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']; @@ -1195,7 +1350,7 @@ if (!function_exists('premium_calculation_manager')) $emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'],$policy_terms['policy_end_date'])->days + 1); $emp_data['policy_details']['premium'] = $slab_value['premium']; $emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'],$emp_data['policy_details']['days'],(calculate_days_bw_dates($policy_terms['policy_start_date'],$policy_terms['policy_end_date'])->days + 1)); - $emp_data['policy_details']['gst'] = ((float) number_format(($emp_data['policy_details']['rata_premimum'] * (18/100)),2,'.','')); + $emp_data['policy_details']['gst'] = ((float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst/100)),2,'.','')); $is_match_found = true; break; } @@ -1203,16 +1358,16 @@ if (!function_exists('premium_calculation_manager')) break; case "11": //GMC - Maximum count per Family - $max_count = $emp_data['temp']['maxcount']; - $employee_received_band = $emp_data['temp']['band']; + $max_count = $emp_data['temp']['max_count']; + $employee_received_band = $emp_data['band']; // echo $employee_received_band; $employee_received_si = $default_si == null ? $emp_data['policy_details']['basic_cover_si'] : $default_si; $emp_data['policy_details']['basic_cover_si'] = null; foreach ($temp_slab_rates as $skey => $slab_value) { - if($slab_value['si'] == $employee_received_si && $slab_value['grade'] == $employee_received_band && (($slab_value['premium_type'] == 1 && - ( strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['primary_rack_rate_acting_self'] || $emp_data['temp']['additional_rack_rate_acting_self'])) || ($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null) )) + if($slab_value['si'] == $employee_received_si && $slab_value['grade'] == $employee_received_band && $slab_value['unit'] == $emp_data['unit'] && (($slab_value['premium_type'] == 1 && + ( strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['acting_self'] )) || ($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null) )) { //calculate premium based on count // echo $emp_data['name']; @@ -1223,9 +1378,9 @@ if (!function_exists('premium_calculation_manager')) $emp_data['policy_details']['date_coverage'] = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']); $emp_data['policy_details']['policy_end_date'] = $policy_terms['policy_end_date']; $emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'],$policy_terms['policy_end_date'])->days + 1); - $emp_data['policy_details']['premium'] = get_premium_for_si(slab_details: $slab_details,si_amount: $familiy_si_covered,band: $employee_received_band); + $emp_data['policy_details']['premium'] = get_premium_for_si(slab_details: $temp_slab_rates,si_amount: $familiy_si_covered,band: $employee_received_band,unit:$emp_data['unit']); $emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'],$emp_data['policy_details']['days'],(calculate_days_bw_dates($policy_terms['policy_start_date'],$policy_terms['policy_end_date'])->days + 1)); - $emp_data['policy_details']['gst'] = ((float) number_format(($emp_data['policy_details']['rata_premimum'] * (18/100)),2,'.','')); + $emp_data['policy_details']['gst'] = ((float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst/100)),2,'.','')); $is_match_found = true; break; } @@ -1241,7 +1396,7 @@ if (!function_exists('premium_calculation_manager')) $emp_data['policy_details']['basic_cover_si'] = null; foreach ($temp_slab_rates as $skey => $slab_value) { - if( $slab_value['si'] == $employee_received_si && ((($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null) && $slab_value['relationship'] == $employee_relationship) || ($slab_value['premium_type'] == 1 && ( strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['primary_rack_rate_acting_self'] || $emp_data['temp']['additional_rack_rate_acting_self']) )) ) + if( $slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'] && ((($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null) && $slab_value['relationship'] == $employee_relationship) || ($slab_value['premium_type'] == 1 && ( strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['acting_self'] ) )) ) { $emp_data['policy_details']['basic_cover_si'] = $employee_received_si; @@ -1250,7 +1405,7 @@ if (!function_exists('premium_calculation_manager')) $emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'],$policy_terms['policy_end_date'])->days + 1); $emp_data['policy_details']['premium'] = $slab_value['premium']; $emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'],$emp_data['policy_details']['days'],(calculate_days_bw_dates($policy_terms['policy_start_date'],$policy_terms['policy_end_date'])->days + 1)); - $emp_data['policy_details']['gst'] = ((float) number_format(($emp_data['policy_details']['rata_premimum'] * (18/100)),2,'.','')); + $emp_data['policy_details']['gst'] = ((float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst/100)),2,'.','')); $is_match_found = true; break; } @@ -1266,7 +1421,7 @@ if (!function_exists('premium_calculation_manager')) $age = calculate_days_bw_dates(from_date: $emp_data['dob'])->y; foreach ($temp_slab_rates as $skey => $slab_value) { - if( $slab_value['si'] == $employee_received_si && ($slab_value['age_from'] <= $age && $slab_value['age_to'] >= $age) && ((($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null) && $slab_value['relationship'] == $employee_relationship) || ($slab_value['premium_type'] == 1 && ( strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['primary_rack_rate_acting_self'] || $emp_data['temp']['additional_rack_rate_acting_self']) )) ) + if( $slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'] && ($slab_value['age_from'] <= $age && $slab_value['age_to'] >= $age) && ((($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null) && $slab_value['relationship'] == $employee_relationship) || ($slab_value['premium_type'] == 1 && ( strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['acting_self'] ) )) ) { $emp_data['policy_details']['basic_cover_si'] = $employee_received_si; @@ -1275,7 +1430,7 @@ if (!function_exists('premium_calculation_manager')) $emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'],$policy_terms['policy_end_date'])->days + 1); $emp_data['policy_details']['premium'] = $slab_value['premium']; $emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'],$emp_data['policy_details']['days'],calculate_days_bw_dates($policy_terms['policy_start_date'],$policy_terms['policy_end_date'])->days); - $emp_data['policy_details']['gst'] = ((float) number_format(($emp_data['policy_details']['rata_premimum'] * (18/100)),2,'.','')); + $emp_data['policy_details']['gst'] = ((float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst/100)),2,'.','')); $is_match_found = true; break; } @@ -1295,7 +1450,7 @@ if (!function_exists('premium_calculation_manager')) { $log_message .= ' - skipping, calculating only self..!'; //reset emp si and others policy level data if premium only for self - $emp_data['policy_details']['policy_end_date'] = $policy_terms['policy_end_date']; + // $emp_data['policy_details']['policy_end_date'] = $policy_terms['policy_end_date']; $emp_data['policy_details']['basic_cover_si'] = 0; $emp_data['policy_details']['premium'] = 0; $emp_data['policy_details']['rata_premimum'] = 0; @@ -1347,6 +1502,7 @@ if (!function_exists('transform_db_data_to_excel')) $row[14] = $value['pre_existing_alignments']; $row[16] = isset($value['date_of_exit']) ? change_date_format($value['date_of_exit'], 'Y-m-d', 'd-M-Y') : NULL; $row[17] = $value['reason_for_exit']; + $row[18] = $value['unit']; $row[7] = isset($value['date_coverage']) ? change_date_format($value['date_coverage'], 'Y-m-d', 'd-M-Y') : NULL; @@ -1461,11 +1617,12 @@ if(!function_exists('replace_original_data')) if(!function_exists('get_premium_for_si')) { - function get_premium_for_si(array $slab_details,string $si_amount,string $band) + function get_premium_for_si(array $slab_details,string $si_amount,string $band,string $unit) { - foreach ($slab_details['slab_rates'] as $skey => $slab_value) + // dd($slab_details); + foreach ($slab_details as $skey => $slab_value) { - if($slab_value['si'] == $si_amount && $slab_value['grade'] == $band && $slab_value['max_si'] == 0) + if($slab_value['si'] == $si_amount && $slab_value['grade'] == $band && $slab_value['unit'] == $unit && $slab_value['max_si'] == 0) { return $slab_value['premium']; } @@ -1632,4 +1789,309 @@ if(!function_exists('transform_enrollment_row_to_inception_row')) $res[17] = null; // inception: reason_for_exit (Reason for exit) -> No match in enrollment return $res; } +} + +if(!function_exists('get_familiy_composition')) +{ + + function get_familiy_composition($family_data) + { + // dd($family_data); + $family_composition = []; + $slug = \Config\Services::slug(); + foreach ($family_data as $key => $row) + { + // Kint::dump($row); + $relationship = $slug->slugify($row[5]); + // echo $relationship; + if($relationship == 'self') + { + $family_composition['self'] = 1; + } + else if(!array_key_exists('self', $family_composition)) + { + $family_composition['self'] = 0; + } + + if($relationship == 'spouse') + { + $family_composition['spouse'] = 1; + } + else if(!array_key_exists('spouse', $family_composition)) + { + $family_composition['spouse'] = 0; + } + + if($relationship == 'son' || $relationship == 'daughter') + { + $family_composition['childrens'] = (isset($family_composition['childrens']) ? $family_composition['childrens'] + 1 : 1); + } + else if(!array_key_exists('childrens', $family_composition)) + { + $family_composition['childrens'] = 0; + } + + if($relationship == 'father' || $relationship == 'mother') + { + $family_composition['parents'] = (isset($family_composition['parents']) ? $family_composition['parents'] + 1 : 1); + } + else if(!array_key_exists('parents', $family_composition)) + { + $family_composition['parents'] = 0; + } + + if($relationship == 'father-in-law' || $relationship == 'mother-in-law') + { + $family_composition['parents-in-law'] = (isset($family_composition['parents-in-law']) ? $family_composition['parents-in-law'] + 1 : 1); + } + else if(!array_key_exists('parents-in-law', $family_composition)) + { + $family_composition['parents-in-law'] = 0; + } + + } + + return ($family_composition); + } +} + +if(!function_exists('compare_incoming_family_slab_with_configured_slab')) +{ + // function compare_incoming_family_slab_with_configured_slab($slab,$incoming_familiy_composition) + // { + // $relationship_mapping = [ + // "self" => ["self"], + // "spouse" => ["spouse"], + // "childrens" => ["son", "daughter"], + // "parents" => ["father", "mother"], + // "parents-in-law" => ["father-in-law", "mother-in-law"], + // "either-parents-pil" => ["either-parents-pil"] + // ]; + + // $result = ['is_applicable' => false,'applicable_members' => []]; + // $configured_familiy_composition = json_decode($slab['slab_rates'][0]['additional_relationship'],true); + // Kint::dump($incoming_familiy_composition);//die(); + // Kint::dump($configured_familiy_composition);//die(); + // unset($configured_familiy_composition['either-parents-pil']); + // unset($configured_familiy_composition['elders_count']); + + // if(count($configured_familiy_composition)) + // { + // foreach($configured_familiy_composition as $key => $value) + // { + // if($value != 'NA') + // { + // // echo 'OUTSIDE - ' . $value . $incoming_familiy_composition[$key]; + // if(isset($incoming_familiy_composition[$key]) && ($incoming_familiy_composition[$key] == $value || $value == 'any') ) + // { + // // echo 'INSIDE - ' . $value; + // $result['is_applicable'] = true; + // $result['applicable_members'] = array_merge($result['applicable_members'],$relationship_mapping[ $key ]); + // } + // else + // { + // $result['is_applicable'] = false; + // $result['applicable_members'] = []; + // // break; + // } + // } + // } + // } + // else + // { + // $result['is_applicable'] = false; + // $result['applicable_members'] = []; + // } + // // dd($result); + // return $result; + // } + + function compare_incoming_family_slab_with_configured_slab($slab, $incoming_familiy_composition) +{ + $relationship_mapping = [ + "self" => ["self"], + "spouse" => ["spouse"], + "childrens" => ["son", "daughter"], + "parents" => ["father", "mother"], + "parents-in-law" => ["father-in-law", "mother-in-law"], + "either-parents-pil" => ["either-parents-pil"] + ]; + + $result = ['is_applicable' => false, 'applicable_members' => []]; + $configured_familiy_composition = json_decode($slab['slab_rates'][0]['additional_relationship'], true); + + // Remove unnecessary keys + // kint::dump($incoming_familiy_composition); + // kint::dump($configured_familiy_composition); + unset($configured_familiy_composition['either-parents-pil']); + unset($configured_familiy_composition['elders_count']); + + // foreach ($configured_familiy_composition as $key => $value) { + // if ($value === 0) { + // // If any relationship is zero, make the rack rate not applicable + // return $result; + // } + // } + + if (count($configured_familiy_composition)) { + foreach ($configured_familiy_composition as $key => $value) { + if ( $value != 'NA') { + if (isset($incoming_familiy_composition[$key])) { + if ($incoming_familiy_composition[$key] == $value || $value == 'any') { + $result['is_applicable'] = true; + $result['applicable_members'] = array_merge($result['applicable_members'], $relationship_mapping[$key]); + } else { + $result['is_applicable'] = false; + $result['applicable_members'] = []; + break; + } + } else { + $result['is_applicable'] = false; + $result['applicable_members'] = []; + break; + } + } + } + } else { + $result['is_applicable'] = false; + $result['applicable_members'] = []; + } + // dd($result); + return $result; +} + + +} + +if(!function_exists('get_applicable_familiy_members')) +{ + function get_applicable_familiy_members($family_data,$applicable_members) + { + $slug = \Config\Services::slug(); + $result = ['index' => [],'max_age'=> [],'max_count' => 0]; + foreach ($family_data as $index => $family_member) + { + if(in_array($slug->slugify($family_member[5]),$applicable_members)) + { + $result['index'] = array_merge($result['index'],[$index]); + $result['max_age'] = array_merge($result['max_age'],[calculate_days_bw_dates(from_date: $family_member[3])->y]); + } + } + $result['max_count'] = count($result['index']); + return $result; + } +} + +if(!function_exists('check_unit')) +{ + function check_unit($row,$existing_units) + { + + + if(in_array($row['current_action'], ['I','A','MI']) ) + { + if(count($existing_units) == 1) + { + if(empty(trim($row[18]))) + { + return array('status' => true); + } + } + + if(strtolower($row[5]) == 'self') + { + if(in_array(trim($row[18]),$existing_units)) //18 is unit name + { + return array('status' => true); + } + else if(!empty(trim($row[18]))) + { + return array('status' => false,'error' => 'wrong unit name'); + } + else + { + return array('status' => false,'error' => 'name of the unit is mandantory'); + } + } + else + { + if(empty(trim($row[18]))) + { + return array('status' => true); + } + else + { + if(in_array(trim($row[18]),$existing_units)) //18 is unit name + { + return array('status' => true); + } + else + { + return array('status' => false,'error' => 'wrong unit name'); + } + } + } + + + } + else + { + return array('status' => true); + } + } +} + + +if(!function_exists('transform_si_excel_row_to_calculatable_format')) +{ + function transform_si_excel_row_to_calculatable_format(array $employee,array$employee_policy,array $maxage_and_maxcount,array $slab_details,string $applicable_slab_name,string $augmented_si,array $grid_master) + { + $employee['temp'] = []; + $employee['temp']['max_age'] = $maxage_and_maxcount[0]['max_age']; + $employee['temp']['max_count'] = $maxage_and_maxcount[0]['family_member_count']; + $employee['temp']['grid_name'] = $applicable_slab_name; + $employee['temp']['grid_master'] = $grid_master; + $employee['temp']['acting_self'] = true; + $employee['temp']['premium_type'] = $grid_master['premium_type']; + $employee['temp']['grid_type'] = $applicable_slab_name; + $employee['temp']['grid_id'] = $grid_master['ui_type']; + $employee['temp']['action'] = 'SI'; + $employee['temp']['source'] = 'excel'; + $employee['temp']['emp_id'] = null; + $employee['temp']['emp_policy_id'] = null; + $employee['temp']['policy_status'] = null; + $employee['temp']['emp_status'] = null; + $employee['temp']['rata_premimum'] = null; + + return $employee; + + + + } +} + +if(!function_exists('group_slab_rates_basedon_name')) +{ + function group_slab_rates_basedon_name($slab_details) + { + // dd($slab_details); + //grouping slab details by rack rate name + $temp_slab_rates = []; + $pre_name = ''; + $pre_grid_master = []; + foreach ($slab_details['slab_rates'] as $key => $value) + { + $pre_grid_master = $value['grid_master']; + unset($value['grid_master']); + if($value['rack_rate_name'] != $pre_name) + { + $pre_name = $value['rack_rate_name']; + $temp_slab_rates[ $value['rack_rate_name'] ]['slab_rates'][] = $value; + } + $temp_slab_rates[ $value['rack_rate_name'] ]['slab_rates'][] = $value; + $temp_slab_rates[ $value['rack_rate_name'] ]['grid_master'] = $pre_grid_master; + } + + return $temp_slab_rates; + } } \ No newline at end of file diff --git a/app/Helpers/sendMailNotification.php b/app/Helpers/sendMailNotification.php index 5a35ccd2..7b8fc5c8 100644 --- a/app/Helpers/sendMailNotification.php +++ b/app/Helpers/sendMailNotification.php @@ -12,7 +12,7 @@ class sendMailNotification { public static function sendMailNotification($action, $params) { - print_r($params);die; + $wholeData =[]; if ($action == 'member_welcome_mail') { $dataToInsert = $params['dataToInsert']; $notification = $params['notification']; @@ -37,7 +37,6 @@ class sendMailNotification } return $wholeData; } else if($action == 'member_reminder_mail'){ - $EmployeeModel = new EmployeeModel(); $emp_data = $params['emp_data']; $notification_data = $params['notification_data']; @@ -51,27 +50,46 @@ class sendMailNotification $mail_content = str_replace("[[client_name]]", $client_data['client_name'], $mail_content); $mail_content = str_replace("[[nhance_logo]]", "Nhance Logo", $mail_content); $mail_content = str_replace("[[app_link]]", "Review Details", $mail_content); - if ($emp_data && (isset($notification_data) && $notification_data['enabled'] == 1)) { + if(isset($emp_data['relationship'])){ + if ($emp_data['relationship'] == 'Self') { + if(count($emp_data) > 0){ + $mail =''; + if ($emp_data['relationship'] == 'Self') { + $employee_name =$emp_data['name']; + $mail_content = str_replace("[[member_name]]", $employee_name, $mail_content); + $mail = $emp_data['email_corporate']; + } + } + }else{ + $mail =''; + } + + }else{ + $employee_name =$emp_data['name']; + $mail_content = str_replace("[[member_name]]", $employee_name, $mail_content); + $mail = $emp_data['email_corporate']; + } + + if (isset($mail) && !empty($mail)) { + $wholeData[] = ['mail' => $mail, 'subject' => $subject,'message'=> $mail_content, 'bcc'=> $client_data['common_mails']]; + } + }else{ foreach ($emp_data as $key => $value) { - if ($value['relationship'] != 'Self') { - + if ($value['relationship'] != 'Self') { $emp_data = $EmployeeModel->where('client_id', $client_data['id'])->where('emp_code', $value['emp_code'])->where('is_active',1)->findAll(); - if(count($emp_data) > 1){ $mail =''; foreach ($emp_data as $key => $values) { if ($value['relationship'] == 'Self') { $employee_name =$values['name']; $mail_content = str_replace("[[member_name]]", $employee_name, $mail_content); - $mail = $values['email_corporate']; } } }else{ $mail =''; } - }else{ $employee_name =$value['name']; $mail_content = str_replace("[[member_name]]", $employee_name, $mail_content); @@ -81,13 +99,15 @@ class sendMailNotification $wholeData[] = ['mail' => $mail, 'subject' => $subject,'message'=> $mail_content, 'bcc'=> $client_data['common_mails']]; } } - if (count($wholeData) < 1) { - $wholeData = []; - } - return $wholeData; - }else{ - return "false"; } + + if (count($wholeData) < 1) { + $wholeData = []; + } + return $wholeData; + // }else{ + // return "false"; + // } } else if($action == 'member_ecard_mail'){ $notification = $params['notification']; @@ -129,7 +149,7 @@ class sendMailNotification return $wholeData; } else if($action == 'member_review_and_summary_mail'){ - $array_list = $params['array_list']; + $array_list = $params['array_list'];//employeee lst $client_policy_id = $params['client_policy_id']; $emp_code = $params['emp_code']; $client_id = $params['client_id']; diff --git a/app/Models/CDMasterModel.php b/app/Models/CDMasterModel.php index b936650f..8c7581a3 100644 --- a/app/Models/CDMasterModel.php +++ b/app/Models/CDMasterModel.php @@ -42,7 +42,7 @@ class CDMasterModel extends Model protected function checkAndADDCreatedByValue(array $data) { // Check if 'updated_by' value is null or empty - if (empty($data['data']['created_by'])) { + if (empty($data['data']['created_by'])) { // Set 'updated_by' value to the current session user ID $data['data']['created_by'] = get_session_userid(); } @@ -53,7 +53,7 @@ class CDMasterModel extends Model protected function checkAndUpdateUpdatedByValue(array $data) { // Check if 'updated_by' value is null or empty - if (empty($data['data']['updated_by'])) { + if (empty($data['data']['updated_by'])) { // Set 'updated_by' value to the current session user ID $data['data']['updated_by'] = get_session_userid(); } @@ -65,31 +65,37 @@ class CDMasterModel extends Model { $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, 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 + ->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 + WHERE client_policy.is_active = 1 + AND cd_master.is_active = 1 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 + '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 + WHERE cash_deposit.is_active = 1 + AND cd_master.is_active = 1 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(); - + 'cd_ac_counts_for_cdt.cd_ac_no = cd_master.cd_ac_no', + 'left' + ) + ->where('cd_master.is_active', 1) + ->where('clients.is_active', 1) + ->where('insurers.is_active', 1) + ->where('user_profiles.is_active', 1) + ->get(); + $result = $query->getResultArray(); return $result; } - } diff --git a/app/Models/ClientBranchModel.php b/app/Models/ClientBranchModel.php index c6083a49..100f503d 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){ @@ -38,4 +39,14 @@ class ClientBranchModel extends Model ->getResult(); } + public function getExisitingUnits(string $client_id,string $client_branch_id) + { + $res = $this->select('client_branch.units') + ->where('client_id', $client_id) + ->where('id', $client_branch_id) + ->find(); + //->getResult(); + return (json_decode($res[0]['units'])); + } + } diff --git a/app/Models/ClientDepositModel.php b/app/Models/ClientDepositModel.php index 9f520dd2..00530dec 100644 --- a/app/Models/ClientDepositModel.php +++ b/app/Models/ClientDepositModel.php @@ -25,6 +25,8 @@ class ClientDepositModel extends Model "client_policy_id", "cd_ac_no", "endorsement_no", + "event_name", + "unit", ]; 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 65bb32cd..f6d8b942 100644 --- a/app/Models/ClientPolicyModel.php +++ b/app/Models/ClientPolicyModel.php @@ -19,6 +19,7 @@ class ClientPolicyModel extends Model "policy_type_id", "policy_start_date", "policy_end_date", + "reminder_date", "insured", "no_of_employees", "no_of_lives", @@ -45,6 +46,8 @@ class ClientPolicyModel extends Model "client_branch_id", "cd_ac_no", "gst", + "enrolment_visibility", + "is_active", ]; public function getClientPolicyById($id){ @@ -73,7 +76,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 +85,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,7 +187,7 @@ 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('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') @@ -355,6 +356,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/EmployeeModel.php b/app/Models/EmployeeModel.php index 13a1e5e7..bd6a5e6f 100644 --- a/app/Models/EmployeeModel.php +++ b/app/Models/EmployeeModel.php @@ -41,6 +41,7 @@ class EmployeeModel extends Model "client_branch_id", "token_time_out", "emp_type", + "unit", "mpin" ]; @@ -105,7 +106,7 @@ class EmployeeModel extends Model public function getEmpFamilybyEmpCode(string $client_policy_id = null,string $emp_code = null,string $client_id = null,array $emp_status = [],array $policy_status = [],array $relationship = [],array $client_branch_id = []) { - $result = $this->select(['employees.id as emp_id', 'employees.client_id','employees.client_branch_id', 'employees.relationship', 'employees.relationship_code', 'employees.change_event', 'employees.emp_code', 'employees.name', 'employees.email_personal', 'employees.email_corporate', 'employees.mobile', 'employees.gender', 'employees.dob', 'employees.doj', 'employees.basic_pay', 'employees.band', 'employees.designation', 'employees.emp_status','employee_polices.id as emp_policy_id', 'employee_polices.employee_id', 'employee_polices.client_policy_id', 'employee_polices.tpa_id', 'employee_polices.uhid', 'employee_polices.batch_code', 'employee_polices.status', 'employee_polices.pre_existing_alignments', 'employee_polices.basic_cover_si', 'employee_polices.date_coverage', 'employee_polices.policy_end_date', 'employee_polices.days', 'employee_polices.premium', 'employee_polices.rata_premimum', 'employee_polices.gst', 'employee_polices.date_of_exit', 'employee_polices.reason_for_exit','policies.name as policy_name','client_policy.is_addon']) + $result = $this->select(['employees.id as emp_id', 'employees.client_id','employees.client_branch_id', 'employees.relationship', 'employees.relationship_code', 'employees.change_event', 'employees.emp_code', 'employees.name', 'employees.email_personal', 'employees.email_corporate', 'employees.mobile', 'employees.gender', 'employees.dob', 'employees.doj', 'employees.basic_pay', 'employees.band', 'employees.designation', 'employees.emp_status','employees.unit','employee_polices.id as emp_policy_id', 'employee_polices.employee_id', 'employee_polices.client_policy_id', 'employee_polices.tpa_id', 'employee_polices.uhid', 'employee_polices.batch_code', 'employee_polices.status', 'employee_polices.pre_existing_alignments', 'employee_polices.basic_cover_si', 'employee_polices.date_coverage', 'employee_polices.policy_end_date', 'employee_polices.days', 'employee_polices.premium', 'employee_polices.rata_premimum', 'employee_polices.gst', 'employee_polices.date_of_exit', 'employee_polices.reason_for_exit','policies.name as policy_name','client_policy.is_addon']) ->join('employee_polices', 'employee_polices.employee_id = employees.id') ->join('client_policy', 'client_policy.id = employee_polices.client_policy_id') ->join('policies', 'policies.id = client_policy.policy_id') @@ -158,9 +159,9 @@ class EmployeeModel extends Model } // for EMP rest API process do not change - public function checkExistingEmployee($arr) + public function checkExistingEmployee($arr,$client_branch_id) { - return $this->where('emp_code',$arr['emp_code'])->where('name',$arr['name'])->where('client_id', $arr['client_id'])->first(); + return $this->where('emp_code',$arr['emp_code'])->where('name',$arr['name'])->where('client_id', $arr['client_id'])->where('client_branch_id', $client_branch_id)->first(); } @@ -189,4 +190,24 @@ class EmployeeModel extends Model return ($result); } + + public function getFamiliyCountAndMaxage(string $emp_code) + { + $query = " + SELECT emp_code,family_member_count,max_age + FROM + ( + SELECT + emp_code, + COUNT(*) AS family_member_count, + MAX(TIMESTAMPDIFF(YEAR, dob, CURDATE())) AS max_age + FROM employees where emp_code = '{$emp_code}' + GROUP BY emp_code + ) AS family_stats + ORDER BY family_member_count DESC, max_age DESC + LIMIT 1;"; + $results = $this->db->query($query)->getResult(); + return $results; + } + } diff --git a/app/Models/EmployeePolicyModel.php b/app/Models/EmployeePolicyModel.php index 3dfe16ec..52ffe324 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="") { @@ -130,7 +130,15 @@ class EmployeePolicyModel extends Model $result->where('employee_polices.client_policy_id', $policy_id); } if ($status !=0 && !empty($status)) { - $result->where('employee_polices.status', $status); + if($status == 'active'){ + $result->where('employee_polices.tpa_id IS NOT NULL'); + $result->where('employee_polices.uhid IS NOT NULL'); + }else if($status == 'pending'){ + $status = 'active'; + $result->where('employee_polices.status', $status); + }else{ + $result->where('employee_polices.status', $status); + } } if (!empty($emp_code)) { $result->where('emp.emp_code', $emp_code); @@ -146,8 +154,6 @@ class EmployeePolicyModel extends Model return $result->findAll(); } - - //for emp onboard do not change public function checkExistingEmpPolicy($arr) { @@ -156,8 +162,7 @@ class EmployeePolicyModel extends Model ->where('is_active',1) ->find(); } - - //------------------------------------------------------------------ +//------------------------------------------------------------------------------------------------------- public function getInceptionEmployeeDataForExportExcel($ref_data) @@ -176,6 +181,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, @@ -185,8 +205,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, @@ -195,16 +226,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, @@ -223,7 +261,6 @@ class EmployeePolicyModel extends Model AND employee_polices.status = 'active' AND employees.is_active = 1 AND employees.emp_status = 'active' - "; // Get the result set @@ -257,9 +294,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 @@ -324,7 +372,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, @@ -341,11 +401,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 @@ -441,12 +508,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, @@ -519,96 +597,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) { @@ -671,7 +659,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']) diff --git a/app/Models/FileModel.php b/app/Models/FileModel.php index 51f397ec..9262e796 100644 --- a/app/Models/FileModel.php +++ b/app/Models/FileModel.php @@ -19,6 +19,7 @@ class FileModel extends Model "client_id", "policy_id", "client_branch_id", + "uploaded_by" ]; 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 @@ +where(['client_id' => $client_id, 'client_policy_id' => $policy_id, 'is_active' => 1,'rack_rate_type' => 0])->findAll(); + $premium_slab_data = $policyPremium2Model->where(['client_id' => $client_id, 'client_policy_id' => $policy_id, 'is_active' => 1])->findAll(); - //check any additional rack rate configured + // check any additional rack rate configured $additional_premium_slab_data = $policyPremium2Model->where(['client_id' => $client_id, 'client_policy_id' => $policy_id, 'is_active' => 1,'rack_rate_type' => 1])->findAll(); @@ -60,9 +60,20 @@ class PolicesModel extends Model if(isset($premium_slab_data[0]['policy_grid_id'])) { - $grid_id = $premium_slab_data[0]['policy_grid_id']; - $policyGridModel = new PolicyGridModel(); - $grid_type = $policyGridModel->find($grid_id); + $pre_grid_id = 0; + $grid_type = []; + foreach ($premium_slab_data as $key => $value) + { + if($value['policy_grid_id'] != $pre_grid_id) + { + $grid_id = $value['policy_grid_id']; + $policyGridModel = new PolicyGridModel(); + $grid_type = $policyGridModel->find($grid_id); + $premium_slab_data[$key]['grid_master'] = $grid_type; + } + $premium_slab_data[$key]['grid_master'] = $grid_type; + } + } if(isset($additional_premium_slab_data[0]['policy_grid_id'])) { diff --git a/app/Models/PolicyPremium1Model.php b/app/Models/PolicyPremium1Model.php index 5609ba08..02e10ba0 100644 --- a/app/Models/PolicyPremium1Model.php +++ b/app/Models/PolicyPremium1Model.php @@ -26,6 +26,9 @@ class PolicyPremium1Model extends Model 'is_active', 'grade', 'premium_type', + 'rack_rate_name', + 'unit', + 'additional_relationship', ]; diff --git a/app/Models/PolicyPremium2Model.php b/app/Models/PolicyPremium2Model.php index b302a53c..ce949d97 100644 --- a/app/Models/PolicyPremium2Model.php +++ b/app/Models/PolicyPremium2Model.php @@ -27,6 +27,8 @@ class PolicyPremium2Model extends Model 'relationship', 'additional_relationship', 'rack_rate_type', + 'rack_rate_name', + 'unit', ]; diff --git a/app/Models/PolicyTypeModel.php b/app/Models/PolicyTypeModel.php index 2b147308..fff3f62a 100644 --- a/app/Models/PolicyTypeModel.php +++ b/app/Models/PolicyTypeModel.php @@ -17,5 +17,6 @@ class PolicyTypeModel extends Model "created_by", "updated_by", "is_active", + "long_name", ]; } diff --git a/app/Views/DashBoard.php b/app/Views/DashBoard.php index fc335f73..c174e936 100644 --- a/app/Views/DashBoard.php +++ b/app/Views/DashBoard.php @@ -1 +1,78 @@ -

Welcome !

+ + + +
+
+ +
+
+
+
+
+
+
+ +
+ + +
+ + +
+
+ +
+
+ + + + + diff --git a/app/Views/batch_list.php b/app/Views/batch_list.php index a909008c..00e5b465 100644 --- a/app/Views/batch_list.php +++ b/app/Views/batch_list.php @@ -58,7 +58,8 @@ - - - + + - diff --git a/app/Views/cd_master_list.php b/app/Views/cd_master_list.php index 30c848f6..04a52784 100644 --- a/app/Views/cd_master_list.php +++ b/app/Views/cd_master_list.php @@ -57,17 +57,25 @@ table.dataTable thead th { by -