diff --git a/app/Config/Routes.php b/app/Config/Routes.php index e63fe383..3baa4314 100755 --- a/app/Config/Routes.php +++ b/app/Config/Routes.php @@ -37,7 +37,6 @@ $routes->get("view", "EmployeeController::viewECard/$1"); $routes->get("checkWellnessOnboardStatus/(:any)", "EmployeeController::checkWellnessOnboardStatus/$1"); $routes->get("initiateWellnessOnboard/(:any)", "EmployeeController::initiateWellnessOnboard/$1"); $routes->get("exportQCRandRFQ/(:any)", "LeadsController::exportQCRandRFQ/$1"); -$routes->get("smapletest", "ClientController::smapletest"); $routes->get("testMailAttachments", "ClientController::testMailAttachments"); $routes->get("updatePolicyTermsKey", "ClientController::updatePolicyTermsKey"); $routes->get("updateRemainderDate", "ClientController::updateRemainderDate"); @@ -560,6 +559,8 @@ $routes->group("/api", ["filter" => "authJWT"], function ($routes) { $routes->get("getSSORedirectUrl", "ApiServiceController::getSSORedirectUrl"); $routes->get("getEmployeePolicy", "EmployeeRestController::getEmployeePolicy"); +$routes->get("downloadCdSplitUpFile", "EmployeeRestController::downloadCdSplitUpFile"); + $routes->group("employeeRest", ['filter' => ['appSignature'] ], function ($routes) { @@ -604,7 +605,7 @@ $routes->group("employeeRest", ['filter' => ['appSignature'] ], function ($route }); - $routes->group("employeeRest", ["filter" => ['GlobalPostFileUploadGuard', 'appSignature', 'authJWT']], function ($routes) { +$routes->group("employeeRest", ["filter" => ['GlobalPostFileUploadGuard', 'appSignature', 'authJWT']], function ($routes) { $routes->post('logout', 'RestAuthenticationController::logout'); @@ -687,8 +688,10 @@ $routes->group("employeeRest", ['filter' => ['appSignature'] ], function ($route // get insurer and policy type $routes->get("getPolicyTypeAndInsurer", "EmployeeRestController::getPolicyTypeAndInsurer"); - $routes->get("downloadCdSplitUpFile", "EmployeeRestController::downloadCdSplitUpFile"); $routes->get("getExcelFileErrors/(:any)", "EmployeeController::getExcelFileErrors/$1"); + $routes->get("getPolicyAndEndorsementFiles", "EmployeeRestController::getPolicyAndEndorsementFiles"); + $routes->get("downloadPolicyFiles", "EmployeeRestController::downloadPolicyFiles"); + $routes->post("bulkEcardDownloadAsZip", "EmployeeRestController::bulkEcardDownloadAsZip"); }); $routes->get("hrFileDownload", "EmployeeRestController::hrFileDownload"); diff --git a/app/Controllers/ClientController.php b/app/Controllers/ClientController.php index 8ba51997..894f98c4 100755 --- a/app/Controllers/ClientController.php +++ b/app/Controllers/ClientController.php @@ -141,6 +141,7 @@ class ClientController extends AdminController $isDuplicate = $this->clientModel->isDuplicateByClientBranch($value, $field, $clientId, $branchId); return $this->response->setJSON(['isDuplicate' => $isDuplicate]); } + public function checkDuplicateTableFieldValue() { $table = $this->request->getPost('table'); @@ -162,35 +163,6 @@ class ClientController extends AdminController return $this->response->setJSON(['isDuplicate' => $isDuplicate]); } - public function smapletest() - { - $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', - 'PRO RATA PREMIUM', - 'GST', - 'TOTAL AMOUNT' - ]; - $filePath = generateExcelWithHeader($headers); - echo "Excel file created at: $filePath"; - } - public function testMailAttachments($email = 'venkateshraman786@gmail.com') { $message = '

Request for Quotation (RFQ)

Dear {{RECIPIENT_NAME}},

We are reaching out to request a quotation for the following insurance coverage. Please review the details below and provide your quote at your earliest convenience.

RFQ Details

Client name{{CLIENT_NAME}}
Coverage Type{{POLICY_LONG_NAME}}
Policy Start Date{{POLICY_START_DATE}}
Policy Duration{{DURATION}}
Please note: Additional terms and details are included in the attachment for your reference.

Please feel free to reach out if you require any further information to prepare the quote. We look forward to receiving your proposal.

Best regards,

Nhance India Pvt Ltd

'; @@ -510,7 +482,6 @@ class ClientController extends AdminController // $this->loadLayout('client_onboarding', $data); } - public function typeList($id = null) { try { @@ -547,7 +518,6 @@ class ClientController extends AdminController } } - public function updateEmpAndPolicyStatus() { $return = $this->clientPolicyModel->updateStatus(); @@ -678,7 +648,7 @@ class ClientController extends AdminController // echo "
";
         // print_r($data); die;
-        $data['placeHolders'] = ['member_name', 'nhance_logo', 'tpa_id', 'ecard_download_link', 'client_logo', 'policy_no', 'member_summary', 'app_link', 'post_enrollment_app_link', 'client_name'];
+        $data['placeHolders'] = ['hr_name', 'member_name', 'nhance_logo', 'tpa_id', 'ecard_download_link', 'client_logo', 'policy_no', 'member_summary', 'app_link', 'post_enrollment_app_link', 'client_name'];
 
         // dd($data['placeHolders']);
 
@@ -982,7 +952,7 @@ class ClientController extends AdminController
                 }, $rawList)) : [];
         $editData['client_policy']['role'] = get_role_id();
         $editData['notification'] = $this->notificationModel->select('template_name,enabled')->where('client_id', $id)->findAll();
-        $editData['placeHolders'] = ['member_name', 'member_mobile', 'nhance_logo', 'tpa_id', 'ecard_download_link', 'client_logo', 'policy_no', 'member_summary', 'app_link', 'post_enrollment_app_link', 'client_name'];
+        $editData['placeHolders'] = ['hr_name', 'member_name', 'member_mobile', 'nhance_logo', 'tpa_id', 'ecard_download_link', 'client_logo', 'policy_no', 'member_summary', 'app_link', 'post_enrollment_app_link', 'client_name'];
         $editData['api_data'] = $this->clientApi->where("client_id", $id)->where("is_active", 1)->first();
         // dd($editData);
 
@@ -2088,6 +2058,7 @@ class ClientController extends AdminController
         $sanitized_post_data['enrolment_visibility']               = $sanitized_post_data['enrolment_visibility'] ?? null ? 1 : 0;
         $sanitized_post_data['is_lgbtq']                           = $sanitized_post_data['is_lgbtq'] ?? null ? 1 : 0;
         $sanitized_post_data['wellness_vendor_id']                 = !empty($sanitized_post_data['wellness_vendor_id']) ? $sanitized_post_data['wellness_vendor_id'] : null;
+        $sanitized_post_data['cd_ac_pk']                           = $sanitized_post_data['cd_ac_no']  ?? null;
 
 
         if ($policy_type_id == 1 || $policy_type_id == 2 || $policy_type_id == 6 || $policy_type_id == 7) {
@@ -2126,6 +2097,8 @@ class ClientController extends AdminController
 
         $insert = $this->clientPolicyModel->insert($sanitized_post_data);
         if ($insert) {
+            // this function to create a policy transaction entry at the time of client policy create
+            $this->createPolicyTransactionInceptionEntry($insert, $sanitized_post_data);
             $clientPoliceData =  $this->clientPolicyModel->getClientPolicyByClientId($sanitized_post_data['client_id']);
             $clientPoliceData['role'] = get_role_id();
             return $this->respond(['status' => true, 'code' => 200, 'data' => $clientPoliceData, 'client_id' => $client_id, 'method' => 'CERATE', 'post_data' => $insert], 200);
@@ -2310,6 +2283,29 @@ class ClientController extends AdminController
         }
     }
 
+    public function createPolicyTransactionInceptionEntry($client_policy_id, $data)
+    {   
+        $data['action_type'] = 'inception';
+        $data['client_policy_id'] = $client_policy_id;
+        $data['entry_from'] = 3;
+        $data['issuer_branch'] = 1;
+        $data['issuer'] = 2;
+        $data['status'] = 'completed';
+        $data['renewal_date'] = $data['policy_end_date'];
+        $data['bro_payable_by'] = 1;
+        $insert = $this->policyTransactionModel->insert($data);
+
+        if($insert){
+
+            $pcsd_data['pt_id'] = $insert;
+            $pcsd_data['insurer_id'] = $data['insurer_id'] ?? null;
+            $pcsd_data['insurer_branch_id'] = $data['insurer_branch_id'] ?? null;
+
+            $this->PTCOShareDetailsModel->insert($pcsd_data);
+        }
+        return $insert;
+    }
+
 
 
     // Save Rack Rate function
@@ -2843,7 +2839,6 @@ class ClientController extends AdminController
         }
     }
 
-
     private function updatePTCoShareTableEntry($policy_transaction_data, $old_client_policy_data, $data)
     {
         $updated_ids = [];
@@ -2889,9 +2884,6 @@ class ClientController extends AdminController
         ];
     }
 
-
-
-
     public function uploadVehicleFile($params = null)
     {
         $this->myLogger->logme('error', 'uploadVehicleFile function called');
@@ -6463,7 +6455,7 @@ class ClientController extends AdminController
         // $res = $EmpDataServiceController->importInceptionUpdateTPAandUHID(['file_id' => 310]); dd($res);//for live
         // $res = $EmpDataServiceController->getInceptionBasePremium(["13332","13333","13334","13335","13336"]); dd($res);//for live
         // $res = $EmpDataServiceController->getDeletionBasePremium(["13248","13250","13249","13247"], json_decode('{"employeeIds":["13248","13250","13249","13247"],"client_id":"3927","client_policy_id":"6183","client_branch_id":"1874","cd_ac_no":"CD9751909505","endorsement_no":"END1238","count":4,"event_name":"deletion","policy_name":"GMC","user_id":"48"}', true)); dd($res);//for live
-        // $res = $EmpDataServiceController->makeEntryForBDSPolicyTransaction(json_decode('{"client_policy_id":"6187","endorsement_no":null,"emp_count":5,"action_type":"inception","no_of_insured":3,"no_of_dependent":0}', true)); dd($res);//for live
+        // $res = $EmpDataServiceController->makeEntryForBDSPolicyTransaction(json_decode('{"client_policy_id":"6187","endorsement_no":"000000001","emp_count":5,"action_type":"addition","no_of_insured":3,"no_of_dependent":0, "base_premium" : "1000", "gst" : "180", "policy_issue_date" : "2025-12-31"}', true)); dd($res);//for live
         // $res = $EmpDataServiceController->sendMailForDownloadingECard(['ids' => $ids, 'client_policy_id' => $client_policy_id]);
         // $res = $this->employeePolicyModel->getDeletionEmployeeDataForExportExcel($batch_data, 1); dd($result);
         // $res = $this->employeePolicyModel->getSIEnhancementEmployeesDataForExportExcel($batch_data, 1);
@@ -8737,6 +8729,8 @@ class ClientController extends AdminController
         $member_ecard_mail_template              = $this->notificationModel->where('client_id', NULL)->where('template_name', 'member_ecard_mail')->get()->getResultArray()[0] ?? [];
 
         $member_common_mail_template             = $this->notificationModel->where('client_id', NULL)->where('template_name', 'member_common_mail')->get()->getResultArray()[0] ?? [];
+        
+        $hr_cd_insufficient_balance_mail_template  = $this->notificationModel->where('client_id', NULL)->where('template_name', 'hr_cd_insufficient_balance_mail')->get()->getResultArray()[0] ?? [];
 
         $default_member_welcome_mail_template = [
             'client_id'        => $client_id,
@@ -8808,6 +8802,20 @@ class ClientController extends AdminController
             'mail_content_copy' => null
         ];
 
+        $hr_cd_insufficient_balance_mail_template = [
+            'client_id'        => $client_id,
+            'template_name'    => 'hr_cd_insufficient_balance_mail',
+            'subject'          => $hr_cd_insufficient_balance_mail_template['subject'] ?? '',
+            'mail_content'     => $hr_cd_insufficient_balance_mail_template['mail_content'] ?? '',
+            'mail_content_json' => $hr_cd_insufficient_balance_mail_template['mail_content_json'] ?? '',
+
+            'created_by'       => get_session_userid(),
+            'created_at'       => date('Y-m-d H:i:s'),
+            'updated_by'       => null,
+            'updated_at'       => date('Y-m-d H:i:s'),
+            'mail_content_copy' => null
+        ];
+
         $this->myLogger->logme('error', 'Default Mail Template Data ' . json_encode([
             $default_member_welcome_mail_template,
             $default_member_remainder_mail_template,
@@ -8821,7 +8829,8 @@ class ClientController extends AdminController
             $default_member_remainder_mail_template,
             $default_member_review_and_summary_mail_template,
             $default_member_ecard_mail_template,
-            $default_member_common_mail_template
+            $default_member_common_mail_template,
+            $hr_cd_insufficient_balance_mail_template,
         ]);
 
 
diff --git a/app/Controllers/EmpDataServiceController.php b/app/Controllers/EmpDataServiceController.php
index f6cfb67a..4a4e9faf 100755
--- a/app/Controllers/EmpDataServiceController.php
+++ b/app/Controllers/EmpDataServiceController.php
@@ -734,17 +734,23 @@ class EmpDataServiceController extends BaseController
         if($export_data['insurer_or_tpa'] == 'insurer')
         {
             if (!empty($cash_balance)) {
-                if ((int) $cash_balance['balance']  < (int) $rounded_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]);
-                    session()->set('cd_balance', false);
-                    session()->set('cd_amount', $cash_balance['balance']);
-                    session()->set('excel_file_amt', $rounded_totals);
+                if ((int) $cash_balance['balance'] < (int) $totals) {
+                    clear_cd_balance_session(); // Clear old junk first
+                    
+                    $cd_session_data = json_encode([
+                        'cd_balance' => false, 
+                        'cd_amount' => $cash_balance['balance'], 
+                        'excel_file_amt' => $totals
+                    ]);
+                    
+                    session()->set('cd_balance_info', $cd_session_data);
+                    session()->set('cd_balance', 'insufficient'); // Use a string status for clarity
+                    
+                    $hr_data = $this->getHrdataForInsufficientMailSend($export_data['client_branch_id']);
+                    session()->set('hr_data', json_encode(['client_id' => $export_data['client_id'], 'hr_data' => $hr_data]));
                 }else{
-                    session()->set('cd_balance', true);
-                    session()->set('cd_amount', $cash_balance['balance']);
-                    session()->set('excel_file_amt', $rounded_totals);
-
+                    session()->set('cd_balance', 'sufficient'); // Use a string status for clarity
+                    session()->set('cd_balance_info', null);
                 }
             }
         }
@@ -1065,17 +1071,23 @@ class EmpDataServiceController extends BaseController
             if($export_data['insurer_or_tpa'] != 'tpa')// check overal emp premium amt with cd balance only for insurer export, not tpa export
             { 
                 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]);
-                        session()->set('cd_balance', false);
-                        session()->set('cd_amount', $cash_balance['balance']);
-                        session()->set('excel_file_amt', $totals);
+                    if ((int) $cash_balance['balance'] < (int) $totals) {
+                        clear_cd_balance_session(); // Clear old junk first
+                        
+                        $cd_session_data = json_encode([
+                            'cd_balance' => false, 
+                            'cd_amount' => $cash_balance['balance'], 
+                            'excel_file_amt' => $totals
+                        ]);
+                        
+                        session()->set('cd_balance_info', $cd_session_data);
+                        session()->set('cd_balance', 'insufficient'); // Use a string status for clarity
+                        
+                        $hr_data = $this->getHrdataForInsufficientMailSend($export_data['client_branch_id']);
+                        session()->set('hr_data', json_encode(['client_id' => $export_data['client_id'], 'hr_data' => $hr_data]));
                     }else{
-                        session()->set('cd_balance', true);
-                        session()->set('cd_amount', $cash_balance['balance']);
-                        session()->set('excel_file_amt', $totals);
-
+                        session()->set('cd_balance', 'sufficient'); // Use a string status for clarity
+                        session()->set('cd_balance_info', null);
                     }
                 }
             }
@@ -2218,7 +2230,7 @@ class EmpDataServiceController extends BaseController
         //send ecard mail if the event is tpa only
         if ($file['insurer_or_tpa'] == 'tpa') {
 
-            if ($get_policy_type['policy_type_id'] != 1) {
+            if (in_array($get_policy_type['policy_type_id'], [2, 3])) {
 
                 // generate e-card and store S3
                 $r = Jobs::addJob(['job_name' => 'bulkGenerateEcardAndStoreinS3', 'payload' => ['client_policy_id' => $client_policy_id]]);
@@ -2634,7 +2646,7 @@ class EmpDataServiceController extends BaseController
             'status' =>  $status_val,
         ]);
 
-        if($client_policy_data['policy_type_id'] != 1){
+        if(in_array($client_policy_data['policy_type_id'], [2, 3])){
             // re-generate e-card and store S3
             $r = Jobs::addJob(['job_name' => 'bulkGenerateEcardAndStoreinS3', 'payload' => ['client_policy_id' => $client_policy_id]]);
         }
diff --git a/app/Controllers/EmployeeController.php b/app/Controllers/EmployeeController.php
index db0468ae..8baab690 100755
--- a/app/Controllers/EmployeeController.php
+++ b/app/Controllers/EmployeeController.php
@@ -31,6 +31,7 @@ use App\Models\UserModel;
 use App\Models\PartnerEndorsementRequestModel;
 use App\Models\TpaApiDataModel;
 use App\Models\LevelContactModel;
+use App\Models\NotificationModel;
 
 
 use App\Controllers\Jobs;
@@ -484,7 +485,17 @@ class EmployeeController extends AdminController
     }
 
     public function getExcelFileErrors($file_id, $retun_type = null)
-    {
+    {   
+
+        $file_data = $this->fileModel->where('id', $file_id)->first();
+        $error = json_decode($file_data['reason'] ?? '{}', true);
+        if(!empty($error) && $retun_type == 'api'){
+            $send = isset($error['error_summary'][5]) || isset($error['error_summary'][6]) ? true : false;
+            if($send){
+                return $this->respond(['status' => false, 'code' => 404,  'message' => $error['error_data'] ?? 'System error', 'data' => []], 200);
+            }
+        }
+
         // $file_id = $this->request->uri->getSegment(3);
         $empServiceController = new EmployeeServiceController();
 
@@ -4544,7 +4555,6 @@ class EmployeeController extends AdminController
         }
     }
 
-
     public function insufficientCdBalanceHrMailSend()
     {
         $post_data = $this->request->getJson(true);
@@ -4555,29 +4565,38 @@ class EmployeeController extends AdminController
 
         $client_data = $this->clientModel->where('is_active', 1)->where('id', $post_data['client_id'])->first();
 
-        $common['mail_type'] = "insufficient_cd_balance_by_hr";
+        if(empty($client_data)){
+            return $this->respond(['status' => false, 'code' => 404, 'message' => 'No client found'], 200);
+        }
+
+        $notificationModal = new NotificationModel();
+        $notification_data = $notificationModal
+                ->where('client_id', $post_data['client_id'])
+                ->where('template_name', 'hr_cd_insufficient_balance_mail')
+                ->first();
+
+        if(empty($notification_data)){
+            return $this->respond(['status' => false, 'code' => 404, 'message' => 'No template found'], 200);
+        }
+
+        if(empty($notification_data['subject']) || empty($notification_data['mail_content'])){
+            return $this->respond(['status' => false, 'code' => 404, 'message' => 'Template subject or mail content is empty'], 200);
+        }
+    
+        if(empty($notification_data['enabled']) || $notification_data['enabled'] != 1){
+            return $this->respond(['status' => false, 'code' => 404, 'message' => 'Template is disabled'], 200);
+
+        }
+
+        $common['mail_type'] = "hr_cd_insufficient_balance_mail";
         $common['client_id'] = $post_data['client_id'];
-        $subject = 'Insufficient CD Balance Notification';
-        $mail_content = '
-            Dear {{HR_NAME}},
-
-            Greetings from Nhance.
-
-            We would like to inform you that the CD balance for {{CLIENT_NAME}} is currently low / insufficient, which may impact further processing of insurance-related activities.
-
-            Kindly request you to credit the required amount at the earliest to avoid any service disruption.
-
-            Please let us know once the amount is credited, or if you need any clarification from our end.
-
-            Thank you for your support and cooperation.
-        ';
-
+        $subject = $notification_data['subject'];
+        $mail_content = $notification_data['mail_content'];
 
         foreach ($post_data['mails'] as $hr_id => $hr_data) {
 
-            $mail_content = str_ireplace('{{HR_NAME}}', $hr_data['name'], $mail_content);
-            $mail_content = str_ireplace('{{CLIENT_NAME}}', $client_data['client_name'], $mail_content);
-
+            $mail_content = str_ireplace('{{hr_name}}', $hr_data['name'], $mail_content);
+            $mail_content = str_ireplace('{{client_name}}', $client_data['client_name'], $mail_content);
             $res = MailHelper::send_email(['mail' => $hr_data['mail'], 'subject' => $subject, 'message' => $mail_content, 'common' => $common]);
         }
 
diff --git a/app/Controllers/EmployeeRestController.php b/app/Controllers/EmployeeRestController.php
index 14c8d1e2..11a9ebc9 100755
--- a/app/Controllers/EmployeeRestController.php
+++ b/app/Controllers/EmployeeRestController.php
@@ -41,6 +41,8 @@ use App\Models\InsurerModel;
 use App\Models\HrFileUploadModel;
 use App\Models\EmployeeRetailPolicy;
 use App\Models\BatchFileModel;
+use App\Models\ClientDepositModel;
+use App\Models\PTFileModel;
 
 
 
@@ -2372,6 +2374,8 @@ class EmployeeRestController extends AdminController
             $value['totalMembersCount'] = count($employeeDetails);
             $value['membersCountOfActive'] = $activeCount;
             $value['membersCountOfInactive'] = $inactiveCount;
+            $value['is_ecard_bulk_download'] = 0;
+            $value['is_ecard_bulk_download_for_employee'] = 0;
 
 
             array_push($result, $value);
@@ -3625,6 +3629,12 @@ class EmployeeRestController extends AdminController
         $get_docs_name = $this->request->getPost('claim_doc_names') ?? [];
         $policy_transaction_id = $this->request->getPost('policy_transaction_id') ?? null;
 
+
+        if (is_string($received_data['client_id']) && preg_match('/^[a-f0-9]{32}$/i', $received_data['client_id'])) {
+            $client_data = $this->clientModel->where('MD5(id)', $received_data['client_id'])->first();
+            $received_data['client_id'] = $client_data['id'] ?? null;
+        } 
+
         $client_policy_data = $this->clientPolicyModel->where('id', $received_data['client_policy_id'] ?? null)->first();
 
         $isduplicate = checkDuplicateClaim([
@@ -4578,15 +4588,15 @@ class EmployeeRestController extends AdminController
 
         // Prepare data
         $data = [
-            'client_id'        => $this->request->getPost('client_id'),
-            'client_branch_id' => $this->request->getPost('client_branch_id'),
-            'policy_id'        => $this->request->getPost('policy_id'),
-            'policy_no'        => $this->request->getPost('policy_no'),
+            'client_id'        => $post_data['client_id'],
+            'client_branch_id' => $post_data['client_branch_id'],
+            'policy_id'        => $post_data['policy_id'],
+            'policy_no'        => $post_data['policy_no'],
             'file_name'        => $newFileName,
-            'file_action'      => $this->request->getPost('file_action'),
+            'file_action'      => $post_data['file_action'],
             'status'           => 'Yet to start',
-            'created_by'       => $this->request->getPost('created_by'),
-            'updated_by'       => $this->request->getPost('created_by'),
+            'created_by'       => $post_data['created_by'],
+            'updated_by'       => $post_data['created_by'],
         ];
 
         // Save into DB
@@ -4609,14 +4619,16 @@ class EmployeeRestController extends AdminController
         $responce = $employeeController->employeesUplodWithEvents($post_data);
         // print_r($responce); die;
 
-        if($responce['status']){
-            $file_data = $this->getDataFromHrFilesTable(['file_id' => $responce['file_id']]);
-            $responce['data'] = $file_data;
-            return $responce;
-        }else{
-            $responce['data'] = [];
-            return $responce;
-        }
+        return $responce;
+
+        // if(isset($responce['file_id'])){
+        //     $file_data = $this->getDataFromHrFilesTable(['hr_id' => $responce['created_by']]);
+        //     $responce['data'] = $file_data;
+        //     return $responce;
+        // }else{
+        //     $responce['data'] = [];
+        //     return $responce;
+        // }
     }
 
     private function giveNotificationToClientsAccountManager($data)
@@ -4848,7 +4860,7 @@ class EmployeeRestController extends AdminController
                         THEN hr_file_upload.status 
                         ELSE CONCAT(UCASE(LEFT(f.status, 1)), LCASE(SUBSTRING(f.status, 2))) 
                     END AS status,
-                    '1' as file_error_status
+                    '0' as file_error_status
                 ", false)
             ->join('clients c', 'c.id = hr_file_upload.client_id AND c.is_active = 1', 'left')
             ->join('client_branch cb', 'cb.id = hr_file_upload.client_branch_id AND cb.is_active = 1', 'left')
@@ -4883,6 +4895,7 @@ class EmployeeRestController extends AdminController
         }
 
         // Execute query
+        $builder->orderBy('hr_file_upload.id', 'DESC');
         $data = $builder->get()->getResultArray();
 
         if(!empty($data)){
@@ -4903,7 +4916,7 @@ class EmployeeRestController extends AdminController
                     files.policy_id, 
                     cp.policy_no, 
                     files.file_name, 
-                    files.action, 
+                    files.action as file_action, 
                     files.created_at, 
                     files.created_by, 
                     files.updated_at, 
@@ -4937,7 +4950,11 @@ class EmployeeRestController extends AdminController
         }
 
         if (isset($search_data['client_id']) && !empty($search_data['client_id'])) {
-            $builder->where("files.client_id", $search_data['client_id']);
+            if (is_string($search_data['client_id']) && preg_match('/^[a-f0-9]{32}$/i', $search_data['client_id'])) {
+                $builder->where("MD5(files.client_id)", $search_data['client_id']);
+            } else {
+                $builder->where("files.client_id", $search_data['client_id']);
+            }
         }
 
         if (isset($search_data['file_id']) && !empty($search_data['file_id'])) {
@@ -4946,6 +4963,7 @@ class EmployeeRestController extends AdminController
 
 
         // Execute query
+        $builder->orderBy('files.id', 'DESC');
         $data = $builder->get()->getResultArray();
 
         if (!empty($data)) {
@@ -5412,6 +5430,7 @@ class EmployeeRestController extends AdminController
         }
     }
 
+
     public function getHrDashboad()
     {
         // $dashboard_id = $this->request->getGet('dashboard_id') ?? null;
@@ -5455,4 +5474,116 @@ class EmployeeRestController extends AdminController
     }
           
 
+    // get policy files
+    public function getPolicyAndEndorsementFiles()
+    {
+        $cd_ac_pk = $this->request->getGet('cd_ac_pk') ?? null;
+
+        $cdModel = new ClientDepositModel();
+        $cd_data = $cdModel->where('id', $cd_ac_pk)
+                            ->where('is_active', 1)
+                            ->where('client_policy_id IS NOT NULL')
+                            ->first();
+
+        if(empty($cd_data)){
+            $this->myLogger->logme('error', 'getPolicyAndEndorsementFiles: No Client Deposit data found for cd_ac_pk=' . $cd_ac_pk);
+            return $this->respond(['status' => false, 'code' => 404, 'message' => 'No file found', 'data' => []], 200);
+        }
+
+        $client_policy_data = $this->clientPolicyModel
+                                    ->where('id', $cd_data['client_policy_id'])
+                                    ->where('is_active', 1)
+                                    ->first();
+
+        if(empty($client_policy_data)){
+            $this->myLogger->logme('error', 'getPolicyAndEndorsementFiles: No Client Policy data found for client_policy_id=' . $cd_data['client_policy_id']);
+            return $this->respond(['status' => false, 'code' => 404, 'message' => 'No file found', 'data' => []], 200);
+        }
+
+        $policyTransactionModel = new PolicyTransactionModel();
+        $policy_transaction_data = $policyTransactionModel
+                                ->where('is_active', 1)
+                                ->where('policy_no', $client_policy_data['policy_no'])
+                                ->where('action_type', $cd_data['event_name'])
+                                ->findAll();
+
+        if(empty($policy_transaction_data)){
+            $this->myLogger->logme('error', 'getPolicyAndEndorsementFiles: No Policy Transaction data found for policy_no=' . $client_policy_data['policy_no']);
+            return $this->respond(['status' => false, 'code' => 404, 'message' => 'No file found', 'data' => []], 200);
+        }
+
+        $policy_transaction_ids = array_column($policy_transaction_data, 'id');
+
+
+        $ptFilesModel = new PTFileModel();
+        $pt_files_data = $ptFilesModel->where('is_active', 1)->whereIn('pt_id', $policy_transaction_ids)->findAll();
+
+        if(empty($pt_files_data)){
+            $this->myLogger->logme('error', 'getPolicyAndEndorsementFiles: No PT Files data found for pt_ids=' . implode(',', $policy_transaction_ids));
+            return $this->respond(['status' => false, 'code' => 404, 'message' => 'No file found', 'data' => []], 200);
+        }
+
+                   
+        return $this->respond(['status' => true, 'code' => 200, 'message' => 'Files found', 'data' => $pt_files_data], 200);
+ 
+    }
+
+    // download policy file
+    public function downloadPolicyFiles()
+    {   
+        $pt_file_id = $this->request->getGet('file_id') ?? null;
+
+        if(empty($pt_file_id)){
+            return $this->respond(['status' => false, 'code' => 404, 'message' => 'File ID is required'], 200);
+        }
+
+        $uploadFilePath = WRITEPATH . 'uploads/client_kyc_documents';
+
+        $ptFilesModel = new PTFileModel();
+        $pt_files_data = $ptFilesModel->where('is_active', 1)->where('id', $pt_file_id)->first();
+
+        if(empty($pt_files_data)){
+            return $this->respond(['status' => false, 'code' => 404, 'message' => 'The Physical File Not Found in server'], 200);
+        }
+
+        $filePath = $uploadFilePath . '/' . $pt_files_data['file_name'];
+
+        if (!file_exists($filePath)) {
+            return $this->respond(['status' => false, 'code' => 404, 'message' => 'The Physical File Not Found in server'], 200);
+        }
+
+        // Force file download
+        return $this->response->download($filePath, null)->setFileName($pt_files_data['file_name']);
+    }
+
+    public function bulkEcardDownloadAsZip()
+    {
+        $received_data = $this->request->getJSON(true) ?? null;
+        $this->myLogger->logme('error', 'bulkEcardDownloadAsZip: Received payload = ' . json_encode($received_data ?? []));
+
+        if(empty($received_data['client_policy_id']) && empty($received_data['emp_policy_ids'])){
+            return $this->respond(['status' => false, 'code' => 404, 'message' => 'client_policy_id or employee_policy_ids is required'], 200);
+        }
+
+        if(empty($received_data['hr_id'])){
+            return $this->respond(['status' => false, 'code' => 404, 'message' => 'hr_id is required'], 200);
+        }
+
+        $employee_data = $this->employeePolicyModel->getEmployeeDataWithPolicyUsingClientPolicyIdOrEmployeePolicyIds($received_data);
+
+        if(empty($employee_data)){
+            return $this->respond(['status' => false, 'code' => 404, 'message' => 'No employee data found for the policy'], 200);
+        }
+        
+        $received_data['folder_name'] = 'bulk_ecards_' . $employee_data[0]['policy_no'] . '_' . date('Y-m-d_H-i-s');
+
+        // Dispatch background job to process the bulk e-card download
+        $r = Jobs::addJob(['job_name' => 'bulkEcardDownloadAsZipFromS3', 'payload'  => $received_data]);
+        $this->myLogger->logme('error', 'bulkEcardDownloadAsZip: Job dispatched with result = ' . json_encode($r ?? []));
+        
+        return $this->respond(['status' => true, 'code' => 200, 'message' => 'Bulk E-card download process started. Link share your mail'], 200);
+
+    }        
+
+
 }
diff --git a/app/Controllers/NotificationController.php b/app/Controllers/NotificationController.php
index b0e5b4cf..8014f0c5 100755
--- a/app/Controllers/NotificationController.php
+++ b/app/Controllers/NotificationController.php
@@ -94,7 +94,8 @@ class NotificationController extends AdminController
             'member_ecard_mail_btn',
             'member_review_and_summary_mail_btn',
             'account_maneger_summary_mail_btn',
-            'client_hr_summary_mail_btn'
+            'client_hr_summary_mail_btn',
+            'hr_cd_insufficient_balance_mail_btn',
         ];
         $data = [];
         $emptyTemplate = [];
diff --git a/app/Controllers/PolicyTransactionController.php b/app/Controllers/PolicyTransactionController.php
index dc57d03f..592e7405 100644
--- a/app/Controllers/PolicyTransactionController.php
+++ b/app/Controllers/PolicyTransactionController.php
@@ -2273,6 +2273,9 @@
             // print_r($data); 
             // die;
 
+            $file_data = $this->request->getFiles() ?? null;
+            $data['file_data'] = $file_data ?? null;
+
             if (!isset($data['policy_with_corr'])) {
                 $data['policy_with_corr'] = 0;
             } elseif ($data['policy_with_corr']) {
@@ -2416,6 +2419,11 @@
                 $this->handleCompletedStatus($data, $insert);
                 $this->insertOrUpdateCoShareDetails($data, $insert);
 
+                // policy file upload 
+                if(isset($data['doc_name']) && isset($data['file_data']) && !empty($data['doc_name']) && !empty($data['file_data'])){
+                    $this->uploadFile($data['doc_name'], $data['file_data'], $insert);
+                }
+
                 return $this->respond(['status' => true, 'message' => 'Endorsement transaction created successfully'], 200);
             }
 
@@ -2688,6 +2696,20 @@
             // dd(db_connect()->getLastQuery() ,$pt_bp_amt);
             $data['base_cd_amount'] = $pt_bp_amt['amount'] ?? null;
 
+            $ptFileQuery = $this->PTFileModel
+                ->join('policy_transaction', 'pt_files.pt_id = policy_transaction.id')
+                ->where('pt_files.pt_id', $id)
+                ->where('pt_files.is_active', 1);
+
+            if (!in_array(get_role_id(), [1, 5]) && empty(array_intersect(user_team(), [MANAGEMENT_TEAM_ID, FINANCE_TEAM_ID, BUSINESS_TEAM_ID]))) {
+
+                if (get_role_id() == 4 && in_array(POS_TEAM_ID, user_team())) {
+                    $ptFileQuery->where('pt_files.created_by', get_session_userid());
+                }
+            }
+
+            $data['pt_files'] = $ptFileQuery->findAll();
+
             if ($data) {
                 return $this->respond(['status' => true, 'data' => $data, 'pt_id' => $pt_id], 200);
             } else {
diff --git a/app/Controllers/TicketController.php b/app/Controllers/TicketController.php
index 1dbe0636..abb02e17 100644
--- a/app/Controllers/TicketController.php
+++ b/app/Controllers/TicketController.php
@@ -1151,9 +1151,9 @@ class TicketController extends BaseController
                 'errors' => ['required' => 'Employee Email is required']
             ],
 
-            'client_name' => [
+            'client_id' => [
                 'rules'  => 'required',
-                'errors' => ['required' => 'Client Name is required']
+                'errors' => ['required' => 'Client ID is required']
             ],
 
             'insurer_id' => [
@@ -1335,9 +1335,9 @@ class TicketController extends BaseController
                 'errors' => ['required' => 'Employee Email is required']
             ],
 
-            'client_name' => [
+            'client_id' => [
                 'rules'  => 'required',
-                'errors' => ['required' => 'Client Name is required']
+                'errors' => ['required' => 'Client ID is required']
             ],
 
             'insurer_id' => [
diff --git a/app/Helpers/utility_helper.php b/app/Helpers/utility_helper.php
index 919fd49c..178ec18a 100755
--- a/app/Helpers/utility_helper.php
+++ b/app/Helpers/utility_helper.php
@@ -947,21 +947,37 @@ if (!function_exists('validateExcelFile')) {
 
     function validateExcelFile($file)
     {
-        $allowed = [
+        // 1. Check if the file was uploaded without errors
+        if (! $file->isValid() || $file->hasMoved()) {
+            return false;
+        }
+
+        // 2. Size check (16MB)
+        if ($file->getSizeByUnit('mb') > 16) {
+            return false;
+        }
+
+        // 3. Define allowed types
+        $allowedMimes = [
             'application/vnd.ms-excel',
             'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
-            'application/vnd.oasis.opendocument.spreadsheet'
+            'application/vnd.oasis.opendocument.spreadsheet',
+            'application/zip',
+            'application/octet-stream'
         ];
 
-        // if ($file->getError() !== UPLOAD_ERR_OK) return 'Upload error';
-        // if ($file->getSize() > (16 * 1024 * 1024)) return 'File too large';
-        // if (!in_array($file->getClientMimeType(), $allowed, true)) return 'Invalid file type';
-        
-        if ($file->getError() !== UPLOAD_ERR_OK) return false;
-        if ($file->getSize() > (16 * 1024 * 1024)) return false;
-        if (!in_array($file->getClientMimeType(), $allowed, true)) return false;
+        $allowedExtensions = ['xls', 'xlsx', 'ods', 'xlsm'];
 
-        return true;
+        // Get the actual values using CI4 methods
+        $mime = $file->getClientMimeType();
+        $extension = $file->getExtension(); // This is the CI4 method
+
+        // 4. Validate
+        if (in_array($mime, $allowedMimes) || in_array($extension, $allowedExtensions)) {
+            return true;
+        }
+
+        return false;
     }
 }
 
diff --git a/app/Models/ClientPolicyModel.php b/app/Models/ClientPolicyModel.php
index 6a7c3cac..b11c97f6 100755
--- a/app/Models/ClientPolicyModel.php
+++ b/app/Models/ClientPolicyModel.php
@@ -303,7 +303,7 @@ class ClientPolicyModel extends Model
             $caseSql = "";
         }
 
-        $url = base_url('employeeRest/downloadCdSplitUpFile?id=');
+        $url = base_url('downloadCdSplitUpFile?id=');
 
         // Fetch the deposit data based on client and insurer IDs       
        $query = $this->db->table('cash_deposit')
diff --git a/app/Models/EmployeePolicyModel.php b/app/Models/EmployeePolicyModel.php
index 7df0e021..395e97bf 100755
--- a/app/Models/EmployeePolicyModel.php
+++ b/app/Models/EmployeePolicyModel.php
@@ -280,6 +280,14 @@ class EmployeePolicyModel extends Model
             'cp.policy_no',
             'cp.policy_type_id',
             'cp.is_addon',
+            '( 
+                select id from employees 
+                where emp_code = emp.emp_code 
+                and client_id = emp.client_id 
+                and lower(relationship) = "self" 
+                and is_active = 1 
+                limit 1 
+            ) as self_employee_id',
             $ecard_download_link
         ])
             ->join('employees emp', 'employee_polices.employee_id = emp.id')
diff --git a/app/Views/fedeploy.php b/app/Views/fedeploy.php
index eca24795..56228bac 100644
--- a/app/Views/fedeploy.php
+++ b/app/Views/fedeploy.php
@@ -1,54 +1,90 @@
-
- -
- - -
+
+
+ +
+
+
+
+ + +
+ +
+
+ + +
+
+
-
- - -
+ +
+ +
+ +
+
-
- - -
+
+ +
+ +
+
-
- - -
+ +
+ +
+ +
+
-
- - - -
+ +
+ +
+ +
+
-
- - - -
+ +
+ +
+ +
+
+ + + +
+
+ +
+
+ +
+
+
+
+ +
+
- - + - \ No newline at end of file diff --git a/app/Views/policy_transaction_inception_form.php b/app/Views/policy_transaction_inception_form.php index 6a0cb78c..6d29b5a6 100644 --- a/app/Views/policy_transaction_inception_form.php +++ b/app/Views/policy_transaction_inception_form.php @@ -2255,7 +2255,7 @@ var page_title = 'Edit Policy' + (res.data.client_short_name || res.data.policy_type || res.data.policy_no ? ' - ' + [res.data.client_short_name, res.data.policy_type, res.data.policy_no] .filter(Boolean).join('-') : ''); - + $('#page_title').text(page_title); $('#client_id_kyc').val(res.data.client_id); $('#policy_tranction_primarykey_for_file_upload').val(res.data.id); @@ -2384,6 +2384,9 @@ $('#table_tr_37').hide(); } + $('#client_id').addClass('readonly-select ').select2('destroy'); + $('#client_branch_id').addClass('readonly-select ').select2('destroy'); + }, 4000) // Set additional fields @@ -2485,7 +2488,7 @@ // } else { // $('#bro_payable_by').prop('checked', false); // } - $('#bro_payable_by').val(res.data.bro_payable_by); + $('#bro_payable_by').val(res.data.bro_payable_by ?? 1); // Policy transaction status handling if (res.data.status == "completed") { diff --git a/app/Views/policy_transaction_inception_list.php b/app/Views/policy_transaction_inception_list.php index 37166f8a..cc850c55 100644 --- a/app/Views/policy_transaction_inception_list.php +++ b/app/Views/policy_transaction_inception_list.php @@ -316,7 +316,7 @@ table.dataTable tbody td { $row){ ?> - + diff --git a/app/Views/pt_endorsement_form_file_upload_tab.php b/app/Views/pt_endorsement_form_file_upload_tab.php new file mode 100644 index 00000000..d871de22 --- /dev/null +++ b/app/Views/pt_endorsement_form_file_upload_tab.php @@ -0,0 +1,34 @@ +