From 375d142a902439bc1c21fbcb37427a2836478c75 Mon Sep 17 00:00:00 2001 From: "venkatesh.r" Date: Mon, 24 Mar 2025 15:16:43 +0530 Subject: [PATCH 01/52] CHANGE_USER_ROLE_AND_TEAMS_BASED_SHOWING_MENU : RV --- app/Config/Constants.php | 2 + app/Controllers/DashboardController.php | 50 ++- .../PolicyTransactionController.php | 43 +- app/Models/PolicyTransactionModel.php | 26 ++ app/Views/DashBoard.php | 105 +++-- app/Views/bds_dash.php | 7 +- app/Views/layout/header.php | 408 +++++++++--------- 7 files changed, 362 insertions(+), 279 deletions(-) diff --git a/app/Config/Constants.php b/app/Config/Constants.php index fb86b921..eee4bdcd 100755 --- a/app/Config/Constants.php +++ b/app/Config/Constants.php @@ -103,6 +103,8 @@ define('BUSINESS_TEAM_ID', '3'); define('FINANCE_TEAM_ID', '4'); define('SALES_TEAM_ID', '5'); define('MANAGEMENT_TEAM_ID', '6'); +define('BUSINESS_SUPPORT_TEAM_ID', '7'); +define('POS_TEAM_ID', '8'); /** * @User Teams Constant diff --git a/app/Controllers/DashboardController.php b/app/Controllers/DashboardController.php index d1a48afb..f4eb8d34 100755 --- a/app/Controllers/DashboardController.php +++ b/app/Controllers/DashboardController.php @@ -100,8 +100,10 @@ class DashboardController extends AdminController $data = []; - $db = db_connect(); - $sql = "SELECT + if (in_array(get_role_id(), [1,2,3,5]) || (in_array(MANAGEMENT_TEAM_ID, user_team()) || in_array(FINANCE_TEAM_ID, user_team()) || in_array(BUSINESS_TEAM_ID, user_team()))) { + + $db = db_connect(); + $sql = "SELECT clients.id AS client_id, clients.client_name, clients.short_name, @@ -144,30 +146,32 @@ class DashboardController extends AdminController GROUP BY clients.id, client_branch.id"; - $query = $db->query($sql); - $results = $query->getResultArray(); + $query = $db->query($sql); + $results = $query->getResultArray(); - $pendingActionsController = new PendingActionsController; - $pendingActionsData = $pendingActionsController->getPendingActionsForDashBoard(); - $businessTeamData = $this->policyTransactionModel->getBusinessReportList(); - $financeTeamData = $this->policyTransactionModel->getFinanceReportList(); - $businessTeamStatusData = $this->data_construct_for_bds($businessTeamData); - $financeTeamStatusData = $this->data_construct_for_bds($financeTeamData); + $pendingActionsController = new PendingActionsController; + $pendingActionsData = $pendingActionsController->getPendingActionsForDashBoard(); + $businessTeamData = $this->policyTransactionModel->getBusinessReportList(); + $financeTeamData = $this->policyTransactionModel->getFinanceReportList(); + $businessTeamStatusData = $this->data_construct_for_bds($businessTeamData); + $financeTeamStatusData = $this->data_construct_for_bds($financeTeamData); - $data['client_branch_emp_list'] = $results; - $session = \Config\Services::session(); - $session->set('enrollment_data', json_encode($data)); - - // echo "
";
-        $data['pendingActionsData'] = $pendingActionsData;
-        $data['businessTeamCount'] = count($businessTeamData) ?? 0;
-        $data['financeTeamCount'] = count($financeTeamData) ?? 0;
-        $data['businessTeamStatusData'] = $businessTeamStatusData;
-        $data['financeTeamStatusData'] = $financeTeamStatusData;
-        $data['policyStatus'] =  $this->policyStatus;
-        $data['colorShades'] =  $this->colorShades;
-        // print_r($data);die;
+            $data['client_branch_emp_list'] = $results;
+            $session = \Config\Services::session();
+            $session->set('enrollment_data', json_encode($data));
+
+            // echo "
";
+            $data['pendingActionsData'] = $pendingActionsData;
+            $data['businessTeamCount'] = count($businessTeamData) ?? 0;
+            $data['financeTeamCount'] = count($financeTeamData) ?? 0;
+            $data['businessTeamStatusData'] = $businessTeamStatusData;
+            $data['financeTeamStatusData'] = $financeTeamStatusData;
+            $data['policyStatus'] =  $this->policyStatus;
+            $data['colorShades'] =  $this->colorShades;
+            // print_r($data);die;
+
+        }
 
         $data['page_name'] = 'Dashboard';
 
diff --git a/app/Controllers/PolicyTransactionController.php b/app/Controllers/PolicyTransactionController.php
index 4a2a59d6..2c40bd30 100644
--- a/app/Controllers/PolicyTransactionController.php
+++ b/app/Controllers/PolicyTransactionController.php
@@ -790,13 +790,24 @@ class PolicyTransactionController extends BaseController
                 ->whereIn('client_policy.policy_type_id', [2, 3])
                 ->where('client_policy.is_active', 1)
                 ->findAll();
-        
-        $data['pt_files'] = $this->PTFileModel
-                ->join('policy_transaction', 'pt_files.pt_id = policy_transaction.id')
-                ->where('pt_files.pt_id', $id)
-                ->where('pt_files.is_active', 1)
-                ->findAll();
-                
+
+
+        $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();
+
+
+
         $data['pt_co_share_details'] = $this->PTCOShareDetailsModel
                 ->select("
                     pt_co_share_details.*,
@@ -1501,11 +1512,19 @@ class PolicyTransactionController extends BaseController
         
         if (!empty($uploadData)) {
 
-            $data['pt_files'] = $this->PTFileModel
-                ->join('policy_transaction', 'pt_files.pt_id = policy_transaction.id')
-                ->where('pt_files.pt_id', $pt_id)
-                ->where('pt_files.is_active', 1)
-                ->findAll();           
+        $ptFileQuery = $this->PTFileModel
+            ->join('policy_transaction', 'pt_files.pt_id = policy_transaction.id')
+            ->where('pt_files.pt_id', $pt_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();        
                  
             return $this->respond(['status' => true, 'message' => 'File uploaded successfully in G-Drive', 'data' => $data]);
         } else {
diff --git a/app/Models/PolicyTransactionModel.php b/app/Models/PolicyTransactionModel.php
index 136529d6..2a77d201 100644
--- a/app/Models/PolicyTransactionModel.php
+++ b/app/Models/PolicyTransactionModel.php
@@ -973,6 +973,19 @@ class PolicyTransactionModel extends Model
             ->where('policy_transaction.is_active', 1)
             ->where('policy_transaction.action_type', 'inception');
 
+        if (
+            (!in_array(get_role_id(), [1, 5])) &&
+            !(
+                in_array(MANAGEMENT_TEAM_ID, user_team()) ||
+                in_array(FINANCE_TEAM_ID, user_team()) ||
+                in_array(BUSINESS_TEAM_ID, user_team())
+            )
+        ) {
+            if (get_role_id() == 4 && in_array(POS_TEAM_ID, user_team())) {
+                $builder->where('policy_transaction.created_by', get_session_userid());
+            }
+        }
+
         // Optimize Date Filtering
         if (!empty($start_date) && !empty($end_date) && !empty($date_type)) {
             $builder->where("policy_transaction.$date_type >=", date('Y-m-d 00:00:00', strtotime($start_date)))
@@ -1034,6 +1047,19 @@ class PolicyTransactionModel extends Model
             ->where('policy_transaction.is_active', 1)
             ->where('policy_transaction.action_type !=', 'inception');
 
+        if (
+            (!in_array(get_role_id(), [1, 5])) &&
+            !(
+                in_array(MANAGEMENT_TEAM_ID, user_team()) ||
+                in_array(FINANCE_TEAM_ID, user_team()) ||
+                in_array(BUSINESS_TEAM_ID, user_team())
+            )
+        ) {
+            if (get_role_id() == 4 && in_array(POS_TEAM_ID, user_team())) {
+                $builder->where('policy_transaction.created_by', get_session_userid());
+            }
+        }
+            
 
         if ($start_date != 0 && $end_date != 0 && $date_type != 0) {
 
diff --git a/app/Views/DashBoard.php b/app/Views/DashBoard.php
index 4da6b9c0..3102ab15 100755
--- a/app/Views/DashBoard.php
+++ b/app/Views/DashBoard.php
@@ -139,40 +139,41 @@
 
 
 
+
 
 
 
 
+
 
 
 
diff --git a/app/Views/bds_dash.php b/app/Views/bds_dash.php
index 89a92413..c6711ec9 100644
--- a/app/Views/bds_dash.php
+++ b/app/Views/bds_dash.php
@@ -125,7 +125,12 @@ body{
 }
 
 
-
+ + + + + +
- +
-
+ + + + + +
  • + + + 2 + App Content Management + + +
  • + + + +
    + +
    + -
    - - -
    - - - - + From abd43b9154bbfc57d52fc32b4aee7c731fc2629c Mon Sep 17 00:00:00 2001 From: "venkatesh.r" Date: Mon, 24 Mar 2025 16:26:03 +0530 Subject: [PATCH 02/52] FIX_ACM_IN_CLIENT_SETUP : RV --- app/Controllers/ClientController.php | 4 ++-- app/Views/layout/header.php | 2 +- app/Views/view_rfq.php | 4 +++- app/Views/view_rfq_non_eb.php | 4 +++- 4 files changed, 9 insertions(+), 5 deletions(-) diff --git a/app/Controllers/ClientController.php b/app/Controllers/ClientController.php index fb78c67b..4ca4505d 100755 --- a/app/Controllers/ClientController.php +++ b/app/Controllers/ClientController.php @@ -594,7 +594,7 @@ class ClientController extends AdminController $data['insurer'] = $this->insurerBranchModel->getInsurerBranchesWithInsurerNames(); $data['tpa'] = $this->tpaBranchModel->getTpaBranchesWithTpaNames(); $data['state'] = $this->stateModel->getAllStates(); - $data['RM'] = $this->userModel->findAll(); + $data['RM'] = $this->userModel->where('is_active', 1)->findAll(); $data['policyGridData'] = $this->policyGridModel->findAll(); $data['policy_types'] = $this->policyTypeModel->findAll(); $data['policy_type'] = ['1' => 'Base Policy', '2' => 'SI Topup', '3' => 'Dependent Addon']; @@ -717,7 +717,7 @@ class ClientController extends AdminController $this->myLogger->logme('error', 'Edit Client Onboarding function called'); $headerData['page_name'] = 'Edit Client Onboarding'; - $editData['RM'] = $this->userModel->findAll(); + $editData['RM'] = $this->userModel->where('is_active', 1)->findAll(); $editData['tpa'] = $this->tpaBranchModel->getTpaBranchesWithTpaNames(); $editData['state'] = $this->stateModel->getAllStates(); $editData['police'] = $this->policesModel->findAll(); diff --git a/app/Views/layout/header.php b/app/Views/layout/header.php index 1e7d1cbc..f10d9077 100755 --- a/app/Views/layout/header.php +++ b/app/Views/layout/header.php @@ -674,7 +674,7 @@ - +
  • diff --git a/app/Views/view_rfq.php b/app/Views/view_rfq.php index 21248ced..3922cdf6 100644 --- a/app/Views/view_rfq.php +++ b/app/Views/view_rfq.php @@ -225,7 +225,9 @@ -       + + +       Export Excel diff --git a/app/Views/view_rfq_non_eb.php b/app/Views/view_rfq_non_eb.php index 402b597e..f885138f 100644 --- a/app/Views/view_rfq_non_eb.php +++ b/app/Views/view_rfq_non_eb.php @@ -182,7 +182,9 @@
    - + + + Export Excel From 69751b02453362e8032ba5df89b0edf73d155bcc Mon Sep 17 00:00:00 2001 From: "venkatesh.r" Date: Tue, 25 Mar 2025 09:08:24 +0530 Subject: [PATCH 03/52] FIX_REST_TERMS_OBJ_ARR_ISSUE : RV --- app/Controllers/EmployeeRestController.php | 10 +--------- app/Views/layout/header.php | 2 +- 2 files changed, 2 insertions(+), 10 deletions(-) diff --git a/app/Controllers/EmployeeRestController.php b/app/Controllers/EmployeeRestController.php index f46fc522..2d7bf436 100755 --- a/app/Controllers/EmployeeRestController.php +++ b/app/Controllers/EmployeeRestController.php @@ -2532,10 +2532,6 @@ class EmployeeRestController extends AdminController $result = []; foreach ($ClientPolicyData as $key => $ClientPolicyValue) { - - - - if($ClientPolicyValue['policy_type_id'] == 1) { $policyGroup = 'gpa'; @@ -2555,11 +2551,7 @@ class EmployeeRestController extends AdminController } $terms = json_decode($ClientPolicyValue['policy_terms'] , true); - $data['policy_terms'] = isset($terms['enrollment_display_key']) - && !empty($terms['enrollment_display_key']) - ? $terms['enrollment_display_key'] - : $this->policyTermsFiter($terms, $policyGroup); - $terms = json_decode($ClientPolicyValue['policy_terms']); + $data['policy_terms'] = isset($terms['enrollment_display_key']) && !empty($terms['enrollment_display_key']) ? $terms['enrollment_display_key'] : $this->policyTermsFiter($terms, $policyGroup); $data['client_id'] = $ClientPolicyValue['client_id']; diff --git a/app/Views/layout/header.php b/app/Views/layout/header.php index f10d9077..0abdf8d5 100755 --- a/app/Views/layout/header.php +++ b/app/Views/layout/header.php @@ -563,7 +563,7 @@ - +
  • From 7c5845097395d52bc39ad0394a8afcd0204680ce Mon Sep 17 00:00:00 2001 From: "venkatesh.r" Date: Tue, 25 Mar 2025 11:39:13 +0530 Subject: [PATCH 04/52] FIX_VERIFY_MOB_EMAIL_STATUS_REST : RV --- app/Controllers/LeadsController.php | 75 ++++++++++--------- .../RestAuthenticationController.php | 2 +- app/Models/RFQModel.php | 1 + app/Views/view_rfq_non_eb.php | 11 ++- 4 files changed, 52 insertions(+), 37 deletions(-) diff --git a/app/Controllers/LeadsController.php b/app/Controllers/LeadsController.php index b361c5b3..8d926761 100644 --- a/app/Controllers/LeadsController.php +++ b/app/Controllers/LeadsController.php @@ -628,12 +628,16 @@ class LeadsController extends BaseController public function createRFQ() { - - // print_r($this->request->getPost('json')); die(); - $data = $this->request->getPost(); - $lead_id = $data['lead_id']; + $lead_id = $data['lead_id'] ?? null; + + if (!$lead_id) { + return $this->respond(['status' => false, 'message' => 'Lead ID is required'], 400); + } + $data['type'] = 1; + + // Deactivate existing RFQs for this lead and type $this->RFQModel ->where('lead_id', $lead_id) ->where('type', 1) @@ -641,41 +645,40 @@ class LeadsController extends BaseController ->set('is_active', 0) ->update(); - $registrationJson = $data['registration_json'] ?? null; // Use null coalescing operator for safety + // Handle registration_json + if (empty($data['registration_json'])) { + // Fetch the latest registration_json if not provided + $latest = $this->RFQModel + ->select('registration_json') + ->where('lead_id', $lead_id) + ->orderBy('id', 'DESC') + ->first(); - if ($registrationJson) { - // If registration_json is provided, insert the data directly - $result = $this->RFQModel->insert($data); - } else { - // If registration_json is not provided, fetch the latest registration_json from the database - $this->RFQModel->select('registration_json') - ->where("lead_id", $lead_id) - ->order_by('id', 'DESC') // Assuming 'id' is an auto-increment field - ->limit(1); - - $query = $this->RFQModel->get(); - $latestRegistrationJson = $query->row()->registration_json ?? null; - - if ($latestRegistrationJson) { - // If a valid registration_json is found, update the data and insert - $data['registration_json'] = $latestRegistrationJson; - $result = $this->RFQModel->insert($data); - } else { - // If no registration_json is found, insert the data as-is - $result = $this->RFQModel->insert($data); + if (!empty($latest['registration_json'])) { + $data['registration_json'] = $latest['registration_json']; } } - if ($result) { + // Insert new RFQ + $insertId = $this->RFQModel->insert($data); - $message = "RFQ submitted successfully"; - if ($data['submit_type'] == 'QCR') { - $message = "QCR submitted successfully"; - } - return $this->respond(['status' => true, 'id' => $result, 'message' => $message, 'data' => $data], 200); + if ($insertId) { + $message = ($data['submit_type'] ?? '') == 'QCR' ? 'QCR submitted successfully' : 'RFQ submitted successfully'; + return $this->respond([ + 'status' => true, + 'id' => $insertId, + 'message' => $message, + 'data' => $data + ], 200); } - return $this->respond(['status' => false, 'id' => $result, 'message' => "Failed to create RFQ", 'data' => $data], 200); + $message = ($data['submit_type'] ?? '') == 'QCR' ? 'Failed to create QCR' : 'Failed to create RFQ'; + return $this->respond([ + 'status' => false, + 'id' => null, + 'message' => $message, + 'data' => $data + ], 200); } public function createQCR() @@ -2575,15 +2578,19 @@ class LeadsController extends BaseController public function constructNonEbExcelToSaveTemp($lead_id, $type, $propsal_and_insurer = null) { - $rfq_data = $this->RFQModel->getRFQTableDataWithLeadIDAndType($lead_id, $type); - $lead_data = json_decode($rfq_data['custom_fields'], true) ?? []; if (!is_array($lead_data)) { $lead_data = []; } $lead_data = array_merge(['Insured' => $rfq_data['client_name']], $lead_data); + $policy_registration_data = []; + if(isset($rfq_data['registration_json']) && !empty($rfq_data['registration_json'])){ + $policy_registration_data = json_decode($rfq_data['registration_json'], true); + } + // dd($policy_registration_data); + // if(!empty($rfq_data['fin_years_claims'])){ // $claim_details = json_decode($rfq_data['fin_years_claims'], true) ?? []; // if(!empty($claim_details['finyear'])){ diff --git a/app/Controllers/RestAuthenticationController.php b/app/Controllers/RestAuthenticationController.php index 3d141b2b..27114883 100755 --- a/app/Controllers/RestAuthenticationController.php +++ b/app/Controllers/RestAuthenticationController.php @@ -118,7 +118,7 @@ class RestAuthenticationController extends AdminController ->where('employees.emp_status !=', 'truncated') ->where('employees.email_corporate', $email) ->where('EP.is_active', 1) - ->whereIn('EP.status', ['draft', 'enrolled']) + ->whereIn('EP.status', ['active']) ->first(); if (isset($employeeData['employee_id'])) { diff --git a/app/Models/RFQModel.php b/app/Models/RFQModel.php index 24d18529..4ffbf9d4 100644 --- a/app/Models/RFQModel.php +++ b/app/Models/RFQModel.php @@ -68,6 +68,7 @@ class RFQModel extends Model tpa_branch.branch_name as tpa_branch_name, policy_type.policy_type, rfq.json, + rfq.registration_json ') ->join('leads', 'rfq.lead_id = leads.id') ->join('policy_type', 'leads.policy_type_id = policy_type.id') diff --git a/app/Views/view_rfq_non_eb.php b/app/Views/view_rfq_non_eb.php index f885138f..5822cb9f 100644 --- a/app/Views/view_rfq_non_eb.php +++ b/app/Views/view_rfq_non_eb.php @@ -1989,10 +1989,13 @@ function saveRFQTODB(tableJSON, policyJson) { + let submit_type = "RFQ" + if(rfq_or_qcr == 2){submit_type = 'QCR'} + var formData = { lead_id: $("#lead_id").val(), json: JSON.stringify(tableJSON), - submit_type: "RFQ", + submit_type: submit_type, registration_json: policyJson } @@ -3209,7 +3212,11 @@ } else if (redirect_type == 2) { //EXCEL EXPORT - let url = $('#submitExcel').data('url'); + // let url = $('#submitExcel').data('url'); + + let lead_id = $('#lead_id').val(); + let url = '' + lead_id + '/' + rfq_or_qcr + '/' + 2 + window.location.href = url; } else if (redirect_type == 3) { From 33d0476728d5ed73e5877247bc65c5a89049f205 Mon Sep 17 00:00:00 2001 From: Srinivas-Saravanan Date: Wed, 26 Mar 2025 17:49:12 +0530 Subject: [PATCH 05/52] FEAT_RFQ_NONEB_COMPLETE --- app/Controllers/LeadsController.php | 51 +- app/Views/policyRegisterModel.php | 4 + app/Views/view_rfq_non_eb.php | 1720 +++++++++++++++++++-------- 3 files changed, 1232 insertions(+), 543 deletions(-) diff --git a/app/Controllers/LeadsController.php b/app/Controllers/LeadsController.php index b361c5b3..2c01c428 100644 --- a/app/Controllers/LeadsController.php +++ b/app/Controllers/LeadsController.php @@ -628,12 +628,11 @@ class LeadsController extends BaseController public function createRFQ() { - - // print_r($this->request->getPost('json')); die(); - $data = $this->request->getPost(); $lead_id = $data['lead_id']; $data['type'] = 1; + + // Deactivate previous RFQs $this->RFQModel ->where('lead_id', $lead_id) ->where('type', 1) @@ -641,43 +640,34 @@ class LeadsController extends BaseController ->set('is_active', 0) ->update(); - $registrationJson = $data['registration_json'] ?? null; // Use null coalescing operator for safety + $registrationJson = $data['registration_json'] ?? null; - if ($registrationJson) { - // If registration_json is provided, insert the data directly - $result = $this->RFQModel->insert($data); - } else { - // If registration_json is not provided, fetch the latest registration_json from the database - $this->RFQModel->select('registration_json') + if (!$registrationJson) { + // Fetch latest registration_json from database + $registrationJson = $this->RFQModel->select('registration_json') ->where("lead_id", $lead_id) - ->order_by('id', 'DESC') // Assuming 'id' is an auto-increment field - ->limit(1); - - $query = $this->RFQModel->get(); - $latestRegistrationJson = $query->row()->registration_json ?? null; - - if ($latestRegistrationJson) { - // If a valid registration_json is found, update the data and insert - $data['registration_json'] = $latestRegistrationJson; - $result = $this->RFQModel->insert($data); - } else { - // If no registration_json is found, insert the data as-is - $result = $this->RFQModel->insert($data); - } + ->orderBy('id', 'DESC') + ->limit(1) + ->get() + ->getRow('registration_json'); } - if ($result) { + if ($registrationJson) { + $data['registration_json'] = $registrationJson; + } - $message = "RFQ submitted successfully"; - if ($data['submit_type'] == 'QCR') { - $message = "QCR submitted successfully"; - } + // Insert new RFQ + $result = $this->RFQModel->insert($data); + + if ($result) { + $message = ($data['submit_type'] == 'QCR') ? "QCR submitted successfully" : "RFQ submitted successfully"; return $this->respond(['status' => true, 'id' => $result, 'message' => $message, 'data' => $data], 200); } - return $this->respond(['status' => false, 'id' => $result, 'message' => "Failed to create RFQ", 'data' => $data], 200); + return $this->respond(['status' => false, 'message' => "Failed to create RFQ", 'data' => $data], 200); } + public function createQCR() { @@ -3132,5 +3122,4 @@ class LeadsController extends BaseController // kint::dump($data); return $data; } - } diff --git a/app/Views/policyRegisterModel.php b/app/Views/policyRegisterModel.php index 680b2b12..12f86dce 100644 --- a/app/Views/policyRegisterModel.php +++ b/app/Views/policyRegisterModel.php @@ -1128,7 +1128,11 @@ prependTable(policySummary[key],key); }); } + $('.loader').fadeIn(); + $('.loader-mask').fadeIn(); toastr.success("Policy Information Collected ","SUCCESS"); + $('.loader').fadeOut(); + $('.loader-mask').delay(350).fadeOut('slow'); console.log("Updated policy data in localStorage:", existingData); } diff --git a/app/Views/view_rfq_non_eb.php b/app/Views/view_rfq_non_eb.php index 402b597e..65a4d695 100644 --- a/app/Views/view_rfq_non_eb.php +++ b/app/Views/view_rfq_non_eb.php @@ -10,35 +10,58 @@ color: #fff; margin-right: 10px; } + .readonly-select { + pointer-events: none; + background-color: #f0f0f0; + color: #666; + } table { /* border-collapse: collapse; */ margin-bottom: 20px; /* max-width: 800px; */ /* table-layout: fixed; */ - width: 1200px; - /* Set a fixed width */ + width: 1400px; + min-width: 1200px; table-layout: fixed; - /* Ensures equal column widths */ border-collapse: collapse; - /* Optional: Makes borders cleaner */ word-wrap: break-word; } - th:nth-child(1), - td:nth-child(1) { + /* Apply styles to the first column, accounting for rowspan */ + table th:nth-child(1), + table td:nth-child(1) { width: 110px; - /* Adjust first column width */ + background-color: #bfe0e2; + } + + + + /* Ensure rowspan cells in the first column inherit the same styles */ + table td[rowspan]:nth-child(1) { + width: 110px; + /* background-color: #bfe0e2; */ + } + + .table th[contenteditable], + .table td[contenteditable] { + border: 1px solid #007bff; + outline: none; } th:nth-child(2), td:nth-child(2) { width: 720px; + background-color: #bfe0e2; /* Adjust first column width */ } + .bold { + font-weight: bold; + color: red; + } th:nth-last-child(1), td:nth-last-child(1) { @@ -53,7 +76,7 @@ } th { - background-color: #f2f2f2 !important; + /* background-color: #f2f2f2 !important; */ position: relative !important; } @@ -68,6 +91,12 @@ box-shadow: 0px 8px 16px rgba(0, 0, 0, 0.2); z-index: 1; } + /* Selects the last cell in each row */ + table tr td:last-child, + table tr th:last-child { + background-color: white !important; + } + .dropdown-content button { display: block; @@ -98,11 +127,13 @@ cursor: pointer; min-width: 80px; user-select: none; + background-color: #ff9999; } /* Hover effect for options */ .dropdown-option:hover { - background-color: #f0f0f0; + background-color: #333; + color : white; } /* Optional: Add transition for smoother hover effect */ @@ -115,11 +146,6 @@ cursor: pointer; } - [contenteditable="true"] { - pointer-events: auto; - /* Ensure clicking works */ - } - /* Optional: Style for selected state */ .selected-option { background-color: #f8f9fa; @@ -160,6 +186,56 @@ color: white !important; margin-right: 5px; } + + .table-collapsible-bar { + background-color: #f1f1f1; + padding: 10px; + cursor: pointer; + border: 1px solid #ddd; + border-radius: 4px 4px 0 0; + font-weight: bold; + display: flex; + justify-content: space-between; + align-items: center; + margin-bottom: 0; + } + + .table-collapsible-bar .collapse-icon { + transition: transform 0.3s ease; + } + + .table-collapsible-bar.collapsed .collapse-icon { + transform: rotate(-90deg); + } + + .table-content { + overflow-x: auto; + width: 100%; + } + + /* Ensure these styles are present */ + .table-content { + transition: all 0.3s ease; + /* overflow: hidden; */ + } + + .table-content.collapse:not(.show) { + display: none; + } + + .table-content.collapse.show { + display: block; + } + + .collapse-icon { + transition: transform 0.3s ease; + } + + .table-collapsible-bar { + cursor: pointer; + user-select: none; + } + @@ -387,6 +463,7 @@ From 3b6733e3bb0485c23ce82aae6aefdba14ce6d9b3 Mon Sep 17 00:00:00 2001 From: Srinivas-Saravanan Date: Thu, 27 Mar 2025 13:14:22 +0530 Subject: [PATCH 09/52] FIX_RFQ_PROPOSAL_COUNT --- app/Views/view_rfq_non_eb.php | 95 ++++++++++++++++++++++++++--------- 1 file changed, 72 insertions(+), 23 deletions(-) diff --git a/app/Views/view_rfq_non_eb.php b/app/Views/view_rfq_non_eb.php index 31f7250c..da988735 100644 --- a/app/Views/view_rfq_non_eb.php +++ b/app/Views/view_rfq_non_eb.php @@ -481,10 +481,19 @@ var rfq_or_qcr = 1; var proposalDataForDropDown = {}; + var lead_type = ""; + // alert(lead_type); + var rollover_or_renewal = ""; + + if (lead_type != 1){ + + rollover_or_renewal = lead_type == 2 ? "Existing Renewal" : "Existing Roll Over"; + } var policyConfig = { 1: ['Quote asked'] }; + let myModal; var over_all_column_data = { "Proposal 1": { @@ -638,7 +647,10 @@ // console.log('removeProposal'); console.log(quotesConfig); if (!quotesConfig[proposalNumber]) return; // If proposal doesn't exist, exit - + if(Object.keys(quotesConfig).length == 1){ + toastr.warning("You cannot Delete All the Proposals","Warning"); + return; + } // Remove all child columns for the proposal const tables = document.querySelectorAll('table'); tables.forEach(table => { @@ -1574,6 +1586,7 @@ // console.log("Subheader th: colinded : ",colIndex); // Get the subheader (assuming it's the second inside ) let subHeaderThList = [...document.querySelectorAll("thead tr:nth-child(2) th")]; + console.log("subHeaderThList", subHeaderThList); // Filter elements that have a valid 'data-proposal' attribute let validSubHeaders = subHeaderThList.filter(th => { @@ -1583,18 +1596,23 @@ }); - // console.log("Subheader th: subHeaderThList",subHeaderThList); + console.log("Subheader th: validSubHeaders",validSubHeaders); // let validSubHeaders = subHeaderThList.filter(th => th.hasAttribute("data-proposal")); // console.log("Subheader th: validSubHeaders",validSubHeaders); - let subHeaderTh = validSubHeaders.find(th => th.textContent.trim() === codeValue) || null; - // console.log("Subheader th: subHeaderTh",subHeaderTh); + + + let subHeaderTh = validSubHeaders.find(th => th.textContent.trim()); + console.log("Subheader th: codeValue",codeValue); + console.log("Subheader th: subHeaderTh",subHeaderTh); // if (subHeaderTh.classList.contains("insurer_proposal")) { // alert(subHeaderTh); // } let subHeaderText = subHeaderTh ? subHeaderTh.textContent.trim() : ''; - // console.log("Subheader th: ",subHeaderText); + console.log("Subheader th: below code",subHeaderText); // Check if subheader is NOT "Quote asked" - let className = subHeaderText !== "Quote asked" && subHeaderText != "-" ? "insurer_proposal" : ""; + let className = !subHeaderText.startsWith("Quote asked") && subHeaderText != "-" ? + "insurer_proposal" : ""; + console.log("className", className); // alert(subHeaderText); let defaultJsonString = typeof default_answers_array == "object" ? JSON.stringify(default_answers_array[0]) : String(default_answers_array); @@ -2699,18 +2717,19 @@ } function addSuggestion(rowData) { - // console.log("child table data ", rowData); - // console.log("child table data ", rowData.row_id); - // console.log("child table data ", child_table_data[rowData.row_id]); + console.log("child table data rowData", rowData); + console.log("child table data rowData.id", rowData.row_id); + console.log("child table data child_table_data", child_table_data[rowData.row_id]); var table_data = child_table_data[rowData.row_id]; + table_data.forEach(table => { table.table_row_contents.forEach(row => { const key = Object.keys(row)[0]; // Get the first key in the row object const answerType = row[key].answer_type; // Get the answer_type suggestions[key] = answerType; // Store in suggestions object }); - }); + }); // console.log("child table data ", suggestions); // child_table_data[rowData.rowID] @@ -2743,13 +2762,16 @@ let keys = Object.keys(quotesConfig); let lastKey = keys[keys.length - 1]; proposalCount = lastKey; + proposalCountForTableINcrease = keys.length; console.log(proposalCount); // Calculate width increase let increaseBy = rfq_or_qcr == 2 ? getTotalCount(proposalDataArray) * 150 : - proposalCount * 150; + proposalCountForTableINcrease * 150; + console.log("Quotes COnfig : ",quotesConfig); + console.log("policy COnfig :", policyConfig); // // console.log("trying to find checkbox data : : : ", increaseBy); @@ -2833,12 +2855,21 @@ // td.onclick = () => getAnswer(table.id, tr.id); td.innerHTML = processCellContent(cellData.input_value, rowData, cellData.display_content); // console.log("DEBUG ISSUE : ",cellData.parentth) - if (cellData.parentth.startsWith("Proposal")) { - td.onclick = () => getAnswer(table.id, tr.id); - if (cellData.subth != "Quote asked") { + if (cellData.parentth.startsWith("Proposal") || cellData.parentth.startsWith("Existing")) { + + if (lead_type == 1){ td.onclick = () => getAnswer(table.id, tr.id); - td.classList.add("insurer_proposal"); + if (cellData.subth != "Quote asked") { + td.onclick = () => getAnswer(table.id, tr.id); + td.classList.add("insurer_proposal"); + } + }else{ + + if (cellData.subth != "Quote asked") { + td.classList.add("insurer_proposal"); + } } + } td.contentEditable = true; @@ -2929,11 +2960,29 @@ // Parent header const th1 = document.createElement('th'); th1.textContent = header.parentHeader; - if (header.parentHeader.startsWith('Proposal')) { - var headerName = header.parentHeader; - // console.log("header name : ", th1.textContent.trim()); - // console.log("over all column data : ", over_all_column_data) - matchedKey = Object.keys(overallColumnDataProposal).find(key => headerName.startsWith(key)); + if (header.parentHeader.startsWith('Proposal') || header.parentHeader.startsWith("Existing")) { + if (lead_type == 1){ + var headerName = header.parentHeader; + }else{ + var headerName = rollover_or_renewal; + } + + if (lead_type == 1){ + + matchedKey = Object.keys(overallColumnDataProposal).find(key => headerName.startsWith(key)); + + }else{ + + if (header.parentHeader.startsWith("Proposal")){ + var tempHeader = header.parentHeader; + matchedKey = Object.keys(overallColumnDataProposal).find(key => tempHeader.startsWith(key)); + }else{ + matchedKey = Object.keys(overallColumnDataProposal).find(key => headerName.startsWith(key)); + } + + } + + if (matchedKey) { // console.log("something wrong : ", overallColumnDataProposal[matchedKey]); var headerCheckBoxProperties = overallColumnDataProposal[matchedKey]; @@ -2965,7 +3014,7 @@ // Sub headers header.subHeaders.forEach(subHeader => { const th2 = document.createElement('th'); - if (header.parentHeader.startsWith("Proposal")) { + if (header.parentHeader.startsWith("Proposal") || header.parentHeader.startsWith("Existing")) { var insurers = overallColumnDataProposal[matchedKey].insurers; const matchedInsurer = insurers.find(ins => ins.ins_name == subHeader); @@ -3378,8 +3427,8 @@ if (rfq_or_qcr == 2) { cell.attr("contenteditable", "false"); removeOnClickFromColumnCells(cell); - - if (!cell.text().trim().startsWith("Proposal")){ + + if (!cell.text().trim().startsWith("Proposal") && !cell.text().trim().startsWith("Existing")){ cell.addClass("readonly-select"); } } else if (rfq_or_qcr == 1) { From 527c399cc6c3779d410c3085594e4f3bac533c5b Mon Sep 17 00:00:00 2001 From: Srinivas-Saravanan Date: Thu, 27 Mar 2025 19:25:56 +0530 Subject: [PATCH 10/52] FEAT_RFQ_NONEB_RENEWAL_AND_ROLLOVER --- app/Controllers/ClientController.php | 12 +- app/Controllers/LeadsController.php | 7 +- app/Views/view_rfq_non_eb.php | 781 ++++++++++++++++----------- 3 files changed, 487 insertions(+), 313 deletions(-) diff --git a/app/Controllers/ClientController.php b/app/Controllers/ClientController.php index 53de23a7..6c491bf9 100755 --- a/app/Controllers/ClientController.php +++ b/app/Controllers/ClientController.php @@ -4737,12 +4737,12 @@ class ClientController extends AdminController // echo "File does not exist."; // } - // $data = $this->leadsModel->where('leads.id', 115)->where('leads.is_active', 1)->first(); - // $RFQdata = $RFQModel->getRFQTableDataWithLeadIDAndType(115, 2); - // Kint::dump($RFQdata['json']); - // $returnData = $LeadsController->getPlacementJson($data); - // $this->clientPolicyModel->where('id', 6050)->set('placement_json', $returnData)->update(); - // dd($returnData); + $data = $this->leadsModel->where('leads.id', 125)->where('leads.is_active', 1)->first(); + $RFQdata = $RFQModel->getRFQTableDataWithLeadIDAndType(125, 2); + Kint::dump($RFQdata['json']); + $returnData = $LeadsController->getPlacementJson($data); + $this->clientPolicyModel->where('id', 6050)->set('placement_json', $returnData)->update(); + dd($returnData); } diff --git a/app/Controllers/LeadsController.php b/app/Controllers/LeadsController.php index c9f6a26a..a858ff7d 100644 --- a/app/Controllers/LeadsController.php +++ b/app/Controllers/LeadsController.php @@ -549,7 +549,7 @@ class LeadsController extends BaseController // dd($lead_data); - if ($lead_data['lead_type'] == 2) { + if ($lead_data['lead_type'] != 1) { $client_policy_data = $this->clientPolicyModel->where('is_active', 1)->where('id', $lead_data['source_policy_id'])->first(); $data['policy_terms'] = $client_policy_data['policy_terms']; } @@ -576,7 +576,7 @@ class LeadsController extends BaseController $data['subject'] = $this->transformMailContent($lead_data, $subject, $data['page_name']); - // dd($data); + if ($data['lead_data']['lead_form_type'] == 1) { $this->loadLayout('view_rfq.php', $data); @@ -585,7 +585,7 @@ class LeadsController extends BaseController $data['occupancy'] = $this->occupancyModel->findAll(); // dd($data['occupancy']); - if($lead_data['lead_type'] == 2){ + if($lead_data['lead_type'] != 1 && $data['rfq_count'] == 0){ $client_policy_data = $this->clientPolicyModel->where('is_active', 1)->where('id', $lead_data['source_policy_id'])->first(); $data['rfq_data']['json'] = $client_policy_data['placement_json']; } @@ -597,6 +597,7 @@ class LeadsController extends BaseController // $data['lead_register_data'] = json_decode($data['lead_data']['custom_fields']); // dd($data['lead_register_data']); + // dd($data); $data['client_type'] = $this->clientType; $data['buisness_type'] = $this->buisnessType; $this->loadLayout('view_rfq_non_eb', $data); diff --git a/app/Views/view_rfq_non_eb.php b/app/Views/view_rfq_non_eb.php index da988735..d30969de 100644 --- a/app/Views/view_rfq_non_eb.php +++ b/app/Views/view_rfq_non_eb.php @@ -29,6 +29,14 @@ } + table thead tr:nth-child(1) th { + background-color: #bfe0e2; + border: 1px solid #007bff; + } + table thead tr:nth-child(2) th { + background-color: #bfe0e2; + border: 1px solid #007bff; + } /* Apply styles to the first column, accounting for rowspan */ @@ -484,11 +492,15 @@ var lead_type = ""; // alert(lead_type); var rollover_or_renewal = ""; + + var rfq_count = ""; + // alert(rfq_count); if (lead_type != 1){ rollover_or_renewal = lead_type == 2 ? "Existing Renewal" : "Existing Roll Over"; } + // alert(rollover_or_renewal); var policyConfig = { 1: ['Quote asked'] @@ -505,7 +517,7 @@ var suggestions = {}; var policyInformationData = ; var storedData = {}; - // console.log("stored data : ", typeof(policyInformationData)) + // // console.log("stored data : ", typeof(policyInformationData)) if (policyInformationData.length) { @@ -515,16 +527,16 @@ var policySummary = []; - // console.log("policy summary is set :", !$.isEmptyObject(policySummary) ? "no" : "yes") + // // console.log("policy summary is set :", !$.isEmptyObject(policySummary) ? "no" : "yes") $(document).ready(function() { myModal = new bootstrap.Modal(document.getElementById('policyRegisterModel')); }); var tableCount = 0; const policies = ; - // console.log('policies', policies); + // // console.log('policies', policies); const child_table_data = ; - // console.log('child_table_data', child_table_data); + // // console.log('child_table_data', child_table_data); const policyOrder = [{ 'fire': { @@ -586,7 +598,7 @@ let selectedPolicies = new Set(); let proposalCount = 1; - // console.log("Proposal count changed", proposalCount); + // // console.log("Proposal count changed", proposalCount); let quotesConfig = { 1: ['Quote asked'] }; // Stores quote columns for each proposal @@ -613,7 +625,7 @@ } insertPosition += quotesConfig[proposalNumber].length - 1; let table_id = table.id ? table.id : 'parent'; - // console.log('insert position of ' + table.id + ' - ' + insertPosition); + // // console.log('insert position of ' + table.id + ' - ' + insertPosition); // Add new quote sub-header const newQuoteHeader = document.createElement('th'); newQuoteHeader.textContent = newQuote; @@ -632,20 +644,27 @@ // Show dropdown menu function showDropdown(event) { - // console.log("dropdown function triggered"); + // // console.log("dropdown function triggered"); const dropdown = event.target.nextElementSibling; - // console.log(dropdown); + // // console.log(dropdown); dropdown.style.display = dropdown.style.display === 'block' ? 'none' : 'block'; event.stopPropagation(); } // Remove a proposal column function removeProposal(proposalNumber) { - let startIndex = 0; - console.log("Remove Proposal : startIndex 1 ",startIndex); - // console.log('removeProposal'); - console.log(quotesConfig); + // alert(proposalNumber); + var rowIdCount = {}; + + let startIndex = 0; + // console.log("Remove Proposal startIndex : ",startIndex); + // console.log("Remove Proposal proposalNumber : ",proposalNumber); + + + // // console.log('removeProposal'); + // console.log("quotesConfig",quotesConfig); + if (!quotesConfig[proposalNumber]) return; // If proposal doesn't exist, exit if(Object.keys(quotesConfig).length == 1){ toastr.warning("You cannot Delete All the Proposals","Warning"); @@ -654,42 +673,80 @@ // Remove all child columns for the proposal const tables = document.querySelectorAll('table'); tables.forEach(table => { + const headerRow1 = table.querySelector('thead tr:first-child'); const headerRow2 = table.querySelector('thead tr:last-child'); // Find the proposal header and calculate its colspan const proposalHeader = headerRow1.querySelector(`th[data-proposal="${proposalNumber}"]`); if (proposalHeader) { - console.log("Remove Proposal : quotesConfig ",quotesConfig[proposalNumber]); - console.log("Remove Proposal : proposalHeader ",proposalHeader); + // console.log("Remove Proposal : quotesConfig ",quotesConfig[proposalNumber]); + // console.log("Remove Proposal : proposalHeader ",proposalHeader); if (rfq_or_qcr == 1){ var colspan = parseInt(quotesConfig[proposalNumber].length); }else{ var colspan = parseInt(proposalHeader.getAttribute('colspan'), 10); } - console.log("Remove Proposal : colspan ",colspan); + // console.log("Remove Proposal : colspan ",colspan); // Remove the proposal header proposalHeader.remove(); // Remove corresponding sub-headers in the second header row const subHeaders = headerRow2.querySelectorAll(`th`); startIndex = 2; // Start after the first two columns (checkbox and Particulars) - console.log("Remove Proposal : startIndex 2",startIndex); - for (let i = 1; i < proposalNumber; i++) { - startIndex += quotesConfig[i]?.length || 0; - console.log("Remove Proposal : startIndex 3",startIndex); + // console.log("Remove Proposal : startIndex 2",startIndex); + // if (lead_type != 1){ + // proposalNumber = proposalNumber + 1; + // }else{ + + // } + if (lead_type != 1){ + for (let i = 0; i < proposalNumber; i++) { + // // console.log("quotesConfig[i] be", quotesConfig[i]) + // // console.log("quotesConfig[i] length", quotesConfig[i]?.length) + + + startIndex += quotesConfig[i]?.length || 0; + + + // console.log("quotesConfig[i] after", quotesConfig[i]); + // console.log("Remove Proposal : startIndex 3",startIndex); + } + }else{ + for (let i = 1; i < proposalNumber; i++) { + // // console.log("quotesConfig[i] be", quotesConfig[i]) + // // console.log("quotesConfig[i] length", quotesConfig[i]?.length) + + + startIndex += quotesConfig[i]?.length || 0; + + + // console.log("quotesConfig[i] after", quotesConfig[i]); + // console.log("Remove Proposal : startIndex 3",startIndex); + } } + for (let i = 0; i < colspan; i++) { - console.log("Remove Proposal : colspan ",colspan); - console.log("Remove Proposal : startIndex 4",startIndex) + // console.log("Remove Proposal : colspan ",colspan); + // console.log("Remove Proposal : startIndex 4",startIndex) headerRow2.removeChild(headerRow2.children[startIndex]); } // Remove corresponding cells in all rows table.querySelectorAll('tbody tr').forEach(row => { for (let i = 0; i < colspan; i++) { - row.removeChild(row.children[startIndex]); + var rowId = row.id; + if (rowIdCount[rowId] === undefined) { + rowIdCount[rowId] = 0; + } else { + rowIdCount[rowId]++; + } + // console.log("rowIdCount[rowId]", rowIdCount[rowId]); + newStartIndex = rowIdCount[rowId] > 0 ? startIndex-1 : startIndex; + // console.log("newStartIndex", newStartIndex) + row.removeChild(row.children[newStartIndex]); + } }); } @@ -699,21 +756,22 @@ delete quotesConfig[proposalNumber]; delete policyConfig[proposalNumber]; - // console.log("DELETE INSURE : policyConfig",policyConfig); - // console.log("DELETE INSURE : quotesConfig",quotesConfig); + // // console.log("DELETE INSURE : policyConfig",policyConfig); + // // console.log("DELETE INSURE : quotesConfig",quotesConfig); // alert(quotesConfig); // alert(policyConfig) + // console.log('End of the functions') } // Add a new row function addRow(event, element) { - // console.log(' event ', element); + // // console.log(' event ', element); const button = event.target; const row = button.closest('tr'); const table = row.closest('table'); const newRow = row.cloneNode(true); - // console.log("old Row ", row); + // // console.log("old Row ", row); // return false; var tableID = table.id; @@ -721,7 +779,7 @@ // Clear input values and generate new IDs newRow.querySelectorAll('td').forEach((td, index) => { if (index === 0) { - // console.log("Trying to set sno"); + // // console.log("Trying to set sno"); td.innerHTML = ""; td.innerHTML = `${nextSNO}`; } @@ -738,7 +796,7 @@ const row = button.closest('tr'); const table = row.closest('table'); if (row && row.parentElement.children.length > 1) { - // console.log("Row Removed"); + // // console.log("Row Removed"); row.remove(); updateSNO(table.id); } @@ -746,23 +804,23 @@ //function to hide all the 3 dot actions for the child table function hideProposalOptionsForChild() { - // // console.log('function called'); + // // // console.log('function called'); const parentTable = document.querySelector("table"); const tables = document.querySelectorAll('table'); - // // console.log('parentTable : ',parentTable); + // // // console.log('parentTable : ',parentTable); tables.forEach(table => { if (table !== parentTable) { // Hide .three-dot-menu in all other tables $(table).find(".three-dot-menu").hide(); - // // console.log("hided 3 dot menu in the table",table); + // // // console.log("hided 3 dot menu in the table",table); } }); } document.addEventListener("change", function(event) { const checkbox = event.target; if (checkbox.classList.contains("qcr-checkbox")) { - // // console.log("QCR checkbox change detected"); + // // // console.log("QCR checkbox change detected"); // Get the row containing the checkbox const row = checkbox.closest('tr'); @@ -776,15 +834,15 @@ // Optionally, you can trigger any additional logic here if (checkbox.checked) { - // // console.log("QCR checkbox is checked, client-checkbox is also checked"); + // // // console.log("QCR checkbox is checked, client-checkbox is also checked"); } else { - // // console.log("QCR checkbox is unchecked, client-checkbox is also unchecked"); + // // // console.log("QCR checkbox is unchecked, client-checkbox is also unchecked"); } } else { - // console.warn("No client-checkbox found in the same row"); + // // console.warn("No client-checkbox found in the same row"); } } else if (checkbox.classList.contains("client-checkbox")) { - // console.log("trying to change"); + // // console.log("trying to change"); const row = checkbox.closest('tr'); const qcrCheckbox = row.querySelector('.qcr-checkbox'); @@ -809,7 +867,7 @@ child_table_data[rowId]?.forEach(childTable => { if (childTable.table_type == "append") { var tableName = childTable.table_id; - // console.log("table name ", tableName); + // // console.log("table name ", tableName); // Handle excess table const excessContainer = document.createElement('div'); excessContainer.setAttribute('data-parent-row', tableName); @@ -819,7 +877,7 @@ if (result) { generateTable(excessContainer, true, rowId, childTable); container.appendChild(excessContainer); - // // console.log('Row id for excess table',rowId); + // // // console.log('Row id for excess table',rowId); $("#excess .three-dot-menu").hide(); moveExcessTableLast(); } @@ -827,7 +885,7 @@ // Handle regular table childContainer.setAttribute('data-parent-row', rowId); generateTable(childContainer, true, rowId, childTable); - // // console.log('Row id for excess table', rowId); + // // // console.log('Row id for excess table', rowId); $(childContainer).find(".three-dot-menu").hide(); // alert(`${rowId.toUpperCase()}_register`); @@ -845,17 +903,17 @@ arrangeTables(); alignTableColumn(); } else { - // console.log('UNCHECKED:', rowId); + // // console.log('UNCHECKED:', rowId); selectedPolicies.delete(rowId); // Remove regular child tables const regularContainers = container.querySelectorAll(`div[data-parent-row="${rowId}"]:not([data-excess-container])`); regularContainers.forEach(container => { - // console.log(" contaitner ", container); + // // console.log(" contaitner ", container); $(`#${rowId.toUpperCase()}_register`).prop("disabled", true); container.remove(); }); - // console.log("row id ", rowId); + // // console.log("row id ", rowId); // Handle excess table rows const excessTable = document.getElementById('excess'); if (excessTable) { @@ -865,7 +923,7 @@ // Check if excess table is empty const remainingRows = excessTable.querySelector('tbody').children; - // // console.log(remainingRows); + // // // console.log(remainingRows); if (remainingRows.length === 0) { // Remove the entire excess table container // const excessContainer = excessTable.closest('div[data-excess-container]'); @@ -881,7 +939,7 @@ } } } else if (checkbox.classList.contains("qcr-checkbox")) { - // console.log("QCR checkbox change detected"); + // // console.log("QCR checkbox change detected"); // Get the row containing the checkbox const row = checkbox.closest('tr'); @@ -895,20 +953,20 @@ // Optionally, you can trigger any additional logic here if (checkbox.checked) { - // console.log("QCR checkbox is checked, client-checkbox is also checked"); + // // console.log("QCR checkbox is checked, client-checkbox is also checked"); } else { - // console.log("QCR checkbox is unchecked, client-checkbox is also unchecked"); + // // console.log("QCR checkbox is unchecked, client-checkbox is also unchecked"); } } else { - console.warn("No client-checkbox found in the same row"); + // console.warn("No client-checkbox found in the same row"); } } }); // Add a new proposal document.getElementById('addProposal').addEventListener('click', () => { - // console.log("proposal count before ", proposalCount); + // // console.log("proposal count before ", proposalCount); proposalCount++; - // console.log("proposal count after ", proposalCount); + // // console.log("proposal count after ", proposalCount); quotesConfig[proposalCount] = ['Quote asked']; policyConfig[proposalCount] = ['Quote asked']; @@ -982,9 +1040,9 @@ targetCell = cells[cells.length - 1]; } - // console.log("ADD PROPOSAL : targetCell", targetCell); + // // console.log("ADD PROPOSAL : targetCell", targetCell); const newCell = targetCell.cloneNode(true); - // console.log("ADD PROPOSAL : newCell", newCell); + // // console.log("ADD PROPOSAL : newCell", newCell); newCell.contentEditable = true; newCell.onclick = () => getAnswer(table.id, row.id); @@ -993,6 +1051,9 @@ }); }); + // console.log(quotesConfig); + // console.log(policyConfig); + hideProposalOptionsForChild(); showOrHideFieldsBasedOnRFQorQCR(); // styleTableColumns(); @@ -1001,7 +1062,7 @@ // ################################################################################# function addNewQuote(proposalNumber) { - // console.log("add new Quote start : ", quotesConfig); + // // console.log("add new Quote start : ", quotesConfig); const insurers = ; selectInsurer(insurers).then(result => { insurer = result.selectedInsurer; @@ -1012,16 +1073,16 @@ let increaseBy = 100; increaseTableWidth(increaseBy); - // // console.log("Selected Insurer:", insurerName); - // // console.log("Entered Version:", version); - // // console.log("Entered data id:", dataId); - // console.log("add new Quote : ", proposalNumber); - // console.log("add new Quote : ", quotesConfig); - // console.log("Add new quote insurer name : ", insurerName); + // // // console.log("Selected Insurer:", insurerName); + // // // console.log("Entered Version:", version); + // // // console.log("Entered data id:", dataId); + // // console.log("add new Quote : ", proposalNumber); + // // console.log("add new Quote : ", quotesConfig); + // // console.log("Add new quote insurer name : ", insurerName); if (!quotesConfig[proposalNumber]) return; - // console.log("add new quote ", quotesConfig[proposalNumber]); + // // console.log("add new quote ", quotesConfig[proposalNumber]); if (quotesConfig[proposalNumber].includes(insurerName)) { - // console.log("add new quote is duplicate"); + // // console.log("add new quote is duplicate"); Swal.fire({ title: "Insurer Dublicate Found?", text: "Do you want version control!", @@ -1041,7 +1102,7 @@ for (let i = 0; i < quotesConfig[proposalNumber].length; i++) { if (quotesConfig[proposalNumber][i].startsWith(baseInsurerName)) { count++; - // console.log("add count ", count); + // // console.log("add count ", count); } } @@ -1049,12 +1110,12 @@ if (version === "") { insurerName = `${baseInsurerName} v${count + 1}`; version = count + 1; - // console.log("add inurer name ", insurerName); + // // console.log("add inurer name ", insurerName); } else { // If user already specified version, append count to make it unique insurerName = `${baseInsurerName} v${version}_${count + 1}`; version = `${version}_${count + 1}`; - // console.log("add inurer name else", insurerName); + // // console.log("add inurer name else", insurerName); } var insurerDetails = { @@ -1065,7 +1126,7 @@ policyConfig[proposalNumber].push(insurerDetails); const newQuote = insurerName; quotesConfig[proposalNumber].push(newQuote); - // console.log("add Quotes config", quotesConfig); + // // console.log("add Quotes config", quotesConfig); updateAllTables(proposalNumber, insurerName); var proposalName = `Proposal ${proposalNumber}`; @@ -1085,13 +1146,13 @@ policyConfig[proposalNumber].push(insurerDetails); const newQuote = insurerName; quotesConfig[proposalNumber].push(newQuote); - // console.log("add Quotes config", quotesConfig); + // // console.log("add Quotes config", quotesConfig); updateAllTables(proposalNumber, insurerName); var proposalName = `Proposal ${proposalNumber}`; const proposalHeader = document.querySelector(`th[data-proposal="${proposalNumber}"]`); if (proposalHeader) { - // console.log("Proposal heade length : ", quotesConfig[proposalNumber].length) + // // console.log("Proposal heade length : ", quotesConfig[proposalNumber].length) proposalHeader.colSpan = quotesConfig[proposalNumber].length; } } @@ -1108,7 +1169,7 @@ function changeInsurer(event, proposalNumber, currentInsurer) { // Stop event propagation event.stopPropagation(); - // console.log("insurer change function called ", quotesConfig[proposalNumber]); + // // console.log("insurer change function called ", quotesConfig[proposalNumber]); if (!quotesConfig[proposalNumber]) return; const insurers = ; @@ -1125,24 +1186,24 @@ newInsurerName = `${newInsurerName}-${newversion.trim()}`.replace(/\s+/g, ''); } - // console.log('insurer newInsurerName', newInsurerName); - // console.log('insurer newversion', newversion); + // // console.log('insurer newInsurerName', newInsurerName); + // // console.log('insurer newversion', newversion); if (newInsurerName) { - // // console.log("insurer inside new insurer name : ",headerRow2); + // // // console.log("insurer inside new insurer name : ",headerRow2); // Update all tables with the new insurer document.querySelectorAll('table').forEach(table => { const headerRow2 = table.querySelector('thead tr:last-child'); - // console.log("insurer inside ", headerRow2); + // // console.log("insurer inside ", headerRow2); // Find the header cells that match our criteria Array.from(headerRow2.children).forEach(th => { // Check if this cell contains our insurer and proposal - // console.log("insurer proposal number : ", proposalNumber); - // console.log("insurer header proposal number : ", th); + // // console.log("insurer proposal number : ", proposalNumber); + // // console.log("insurer header proposal number : ", th); if (th.getAttribute('data-proposal') === proposalNumber.toString()) { // Get the first text node (the insurer name part) let content = th.innerHTML; - // console.log("insurer inside ", content); + // // console.log("insurer inside ", content); // Only replace the exact insurer name, not any menu text if (content.includes(currentInsurer)) { // Create a regex to match just the insurer name @@ -1166,10 +1227,10 @@ // Generate new quote code based on new insurer const newQuoteCode = oldQuoteCode.replace(currentInsurer, newInsurerName); quotesConfig[proposalNumber][quoteIndex] = newQuoteCode; - // console.log("Existing policy data ", policyConfig[proposalNumber][quoteIndex]); + // // console.log("Existing policy data ", policyConfig[proposalNumber][quoteIndex]); policyConfig[proposalNumber][quoteIndex] = insurerDetailsChange; - // console.log("quote index ", quoteIndex); - // console.log("changed like this ", insurerDetailsChange); + // // console.log("quote index ", quoteIndex); + // // console.log("changed like this ", insurerDetailsChange); // Update data-quote attribute th.setAttribute('data-quote', newQuoteCode); } @@ -1203,11 +1264,13 @@ function removeQuote(event, proposalNumber, quoteCode) { event.stopPropagation(); + var rowIdCount = {}; + if (!quotesConfig[proposalNumber]) return; // Remove quote from config const quoteIndex = quotesConfig[proposalNumber].indexOf(quoteCode); - // console.log("quote index ", quoteIndex); + // // console.log("quote index ", quoteIndex); if (quoteIndex !== -1) { quotesConfig[proposalNumber].splice(quoteIndex, 1); policyConfig[proposalNumber].splice(quoteIndex, 1); @@ -1227,19 +1290,19 @@ th.textContent.includes(quoteCode) && th.getAttribute('data-proposal') === proposalNumber.toString() ); - // console.log("quote target index ", targetIndex); + // // console.log("quote target index ", targetIndex); if (targetIndex !== -1) { - // console.log("quote target index inside if", targetIndex); + // // console.log("quote target index inside if", targetIndex); // Remove from header row 2 headerRow2.removeChild(headerRow2.children[targetIndex]); // Update proposal header colspan const proposalHeader = headerRow1.querySelector(`th[data-proposal="${proposalNumber}"]`); - // console.log("quote target index inside if proposal header", proposalHeader); + // // console.log("quote target index inside if proposal header", proposalHeader); if (proposalHeader) { const newColspan = parseInt(proposalHeader.colSpan) - 1; - // console.log("Quote new colspan : ", newColspan); + // // console.log("Quote new colspan : ", newColspan); if (newColspan > 0) { proposalHeader.colSpan = newColspan; } else { @@ -1250,10 +1313,21 @@ // Remove from data rows table.querySelectorAll('tbody tr').forEach(row => { const cellIndex = targetIndex; // No need to add 2 since we're using children array - // console.log("quote target index inside if proposal header", cellIndex); + // console.log("quote target index", cellIndex); + + var rowId = row.id; + if (rowIdCount[rowId] === undefined) { + rowIdCount[rowId] = 0; + } else { + rowIdCount[rowId]++; + } + // console.log("rowIdCount[rowId]", rowIdCount[rowId]); + newStartIndex = rowIdCount[rowId] > 0 ? cellIndex-1 : cellIndex; + // console.log("quote target index inside if proposal header", newStartIndex); + if (row.children[cellIndex]) { - row.removeChild(row.children[cellIndex]); - // console.log("quote target index inside if proposal header", row); + row.removeChild(row.children[newStartIndex]); + // // console.log("quote target index inside if proposal header", row); } }); @@ -1262,17 +1336,17 @@ } function updateAllTables(proposalNumber, newQuote) { - + // alert(proposalNumber); document.querySelectorAll('table').forEach(table => { const headerRow1 = table.querySelector('thead tr:first-child'); const headerRow2 = table.querySelector('thead tr:last-child'); - // console.log('headerRow2 data', headerRow2); - // console.log('headerRow2 headerRow2.children', headerRow2.children); + // // console.log('headerRow2 data', headerRow2); + // // console.log('headerRow2 headerRow2.children', headerRow2.children); const proposalHeader = headerRow1.querySelector(`th[data-proposal="${proposalNumber}"]`); - // console.log("Proposal Header : ", proposalNumber); + console.log("Proposal proposalNumber : ", proposalNumber); // Create new quote header const newQuoteHeader = document.createElement('th'); newQuoteHeader.innerHTML = ` @@ -1292,25 +1366,31 @@ // Calculate header insert position let insertPosition = 2; - for (let i = 1; i < proposalNumber; i++) { - insertPosition += quotesConfig[i]?.length || 0; + if (lead_type == 1){ + for (let i = 1; i < proposalNumber; i++) { + insertPosition += quotesConfig[i]?.length || 0; + } + }else{ + for (let i = 0; i < proposalNumber; i++) { + insertPosition += quotesConfig[i]?.length || 0; + } } + insertPosition += quotesConfig[proposalNumber].length - 1; - // console.log("Header insert position : ", insertPosition); + // // console.log("Header insert position : ", insertPosition); if (headerRow2.children[insertPosition - 1]) { let referenceChild = headerRow2.children[insertPosition - 1]; // Get the target child - // console.log("referenceChild", referenceChild); + // // console.log("referenceChild", referenceChild); let computedStyle = window.getComputedStyle(referenceChild); - // console.log("computedStyle", computedStyle); + // // console.log("computedStyle", computedStyle); // Copy all computed styles - for (let prop of computedStyle) { - // console.log("prop", prop); - newQuoteHeader.style[prop] = computedStyle.getPropertyValue(prop); - } + let backgroundColor = computedStyle.getPropertyValue("background-color"); + newQuoteHeader.style.backgroundColor = backgroundColor; + } headerRow2.insertBefore(newQuoteHeader, headerRow2.children[insertPosition]); @@ -1452,7 +1532,7 @@ } tableName = tableData ? tableData.table_name : "Particulars"; - // // console.log("table Name ",tableName); + // // // console.log("table Name ",tableName); // Header setup const thead = document.createElement('thead'); const headerRow1 = document.createElement('tr'); @@ -1493,11 +1573,11 @@ thead.append(headerRow1, headerRow2); table.appendChild(thead); let latestWidth = $("table").last().width(); - // // console.log('Latest width', latestWidth); + // // // console.log('Latest width', latestWidth); if (tableData) { - // // console.log("table ",$(table)); + // // // console.log("table ",$(table)); $(table).width(latestWidth); // Convert to jQuery object using $(table) - // // console.log('table data',tableData); + // // // console.log('table data',tableData); } @@ -1583,42 +1663,42 @@ ${Object.values(quotesConfig).flatMap(codes => codes.map((codeValue, colIndex) => { - // console.log("Subheader th: colinded : ",colIndex); + // // console.log("Subheader th: colinded : ",colIndex); // Get the subheader (assuming it's the second inside ) let subHeaderThList = [...document.querySelectorAll("thead tr:nth-child(2) th")]; - console.log("subHeaderThList", subHeaderThList); + // // console.log("subHeaderThList", subHeaderThList); // Filter elements that have a valid 'data-proposal' attribute let validSubHeaders = subHeaderThList.filter(th => { let dataProposal = th.getAttribute("data-proposal"); - // console.log("Subheader th: dataProposal : ",dataProposal); + // // console.log("Subheader th: dataProposal : ",dataProposal); return dataProposal !== null && dataProposal !== undefined && dataProposal.trim() !== ""; }); - console.log("Subheader th: validSubHeaders",validSubHeaders); + // // console.log("Subheader th: validSubHeaders",validSubHeaders); // let validSubHeaders = subHeaderThList.filter(th => th.hasAttribute("data-proposal")); - // console.log("Subheader th: validSubHeaders",validSubHeaders); + // // console.log("Subheader th: validSubHeaders",validSubHeaders); let subHeaderTh = validSubHeaders.find(th => th.textContent.trim()); - console.log("Subheader th: codeValue",codeValue); - console.log("Subheader th: subHeaderTh",subHeaderTh); + // // console.log("Subheader th: codeValue",codeValue); + // // console.log("Subheader th: subHeaderTh",subHeaderTh); // if (subHeaderTh.classList.contains("insurer_proposal")) { // alert(subHeaderTh); // } let subHeaderText = subHeaderTh ? subHeaderTh.textContent.trim() : ''; - console.log("Subheader th: below code",subHeaderText); + // // console.log("Subheader th: below code",subHeaderText); // Check if subheader is NOT "Quote asked" let className = !subHeaderText.startsWith("Quote asked") && subHeaderText != "-" ? "insurer_proposal" : ""; - console.log("className", className); + // console.log("className", className); // alert(subHeaderText); let defaultJsonString = typeof default_answers_array == "object" ? JSON.stringify(default_answers_array[0]) : String(default_answers_array); - // // console.log("defaultJsonString", defaultJsonString); - // // console.log("defaultJsonString type", typeof defaultJsonString); - // // console.log("defaultJsonString string", String(defaultJsonString)); + // // // console.log("defaultJsonString", defaultJsonString); + // // // console.log("defaultJsonString type", typeof defaultJsonString); + // // // console.log("defaultJsonString string", String(defaultJsonString)); @@ -1672,7 +1752,7 @@ if (excessTable) { // If table exists, append new rows to it const tbody = excessTable.querySelector('tbody'); - // // console.log("table data ",tableData); + // // // console.log("table data ",tableData); // Add new rows from tableData tableData.table_row_contents.forEach((rowData, index) => { let rowID = Object.keys(rowData)[0]; @@ -1687,36 +1767,36 @@ ${question} ${Object.values(quotesConfig).flatMap(codes => codes.map((codeValue, colIndex) => { - // console.log("Subheader th: colinded : ",colIndex); + // // console.log("Subheader th: colinded : ",colIndex); // Get the subheader (assuming it's the second inside ) let subHeaderThList = [...document.querySelectorAll("thead tr:nth-child(2) th")]; // Filter elements that have a valid 'data-proposal' attribute let validSubHeaders = subHeaderThList.filter(th => { let dataProposal = th.getAttribute("data-proposal"); - // console.log("Subheader th: dataProposal : ",dataProposal); + // // console.log("Subheader th: dataProposal : ",dataProposal); return dataProposal !== null && dataProposal !== undefined && dataProposal.trim() !== ""; }); - // console.log("Subheader th: subHeaderThList",subHeaderThList); + // // console.log("Subheader th: subHeaderThList",subHeaderThList); // let validSubHeaders = subHeaderThList.filter(th => th.hasAttribute("data-proposal")); - // console.log("Subheader th: validSubHeaders",validSubHeaders); + // // console.log("Subheader th: validSubHeaders",validSubHeaders); let subHeaderTh = validSubHeaders.find(th => th.textContent.trim() === codeValue) || null; - // console.log("Subheader th: subHeaderTh",subHeaderTh); + // // console.log("Subheader th: subHeaderTh",subHeaderTh); // if (subHeaderTh.classList.contains("insurer_proposal")) { // alert(subHeaderTh); // } let subHeaderText = subHeaderTh ? subHeaderTh.textContent.trim() : ''; - // console.log("Subheader th: ",subHeaderText); + // // console.log("Subheader th: ",subHeaderText); // Check if subheader is NOT "Quote asked" let className = subHeaderText !== "Quote asked" && subHeaderText != "-" ? "insurer_proposal" : ""; // alert(subHeaderText); let defaultJsonString = typeof default_answers_array == "object" ? JSON.stringify(default_answers_array[0]) : String(default_answers_array); - // // console.log("defaultJsonString", defaultJsonString); - // // console.log("defaultJsonString type", typeof defaultJsonString); - // // console.log("defaultJsonString string", String(defaultJsonString)); + // // // console.log("defaultJsonString", defaultJsonString); + // // // console.log("defaultJsonString type", typeof defaultJsonString); + // // // console.log("defaultJsonString string", String(defaultJsonString)); @@ -1753,7 +1833,7 @@ } // Initialize the parent table document.addEventListener('DOMContentLoaded', () => { - // // console.log("bjnglfkrg ", rfq_data.length); + // // // console.log("bjnglfkrg ", rfq_data.length); const url = window.location.pathname; // Get the path (e.g., "/nhance/rfq/list/75/1") const segments = url.split("/"); // Split by "/" segments[segments.length - 1] = "1"; // Change the last segment @@ -1762,13 +1842,14 @@ history.pushState(null, "", newUrl); // Change the URL without reloading if (rfq_data.length) { - // console.log("inside if conditoon"); + // // console.log("inside if conditoon"); localStorage.setItem('allTablesJsonData', JSON.stringify(rfq_data)); jsonToTables(); + styleTableColumns(); proposalDataForDropDown = rfq_data[rfq_data.length - 1].proposal_data; - // console.log("proposalDataForDropDown", proposalDataForDropDown); + // // console.log("proposalDataForDropDown", proposalDataForDropDown); if (!$.isEmptyObject(storedData)) { - // console.log("DATA FROM DB : ", JSON.parse(storedData)); + // // console.log("DATA FROM DB : ", JSON.parse(storedData)); let data = JSON.parse(storedData); Object.keys(data).forEach(key => { @@ -1779,23 +1860,23 @@ }); - // // console.log("policy summary : ",child_table_data[key]) + // // // console.log("policy summary : ",child_table_data[key]) - // console.log("generate policy summary : ", policySummary); + // // console.log("generate policy summary : ", policySummary); styleTableColumns(); } // generateTable(document.getElementById('tablesContainer')); - // // console.log("polices Length ", policies.length); + // // // console.log("polices Length ", policies.length); } else { generateTable(document.getElementById('tablesContainer')); styleTableColumns(); - // console.log("polices Length ", policies.length); + // // console.log("polices Length ", policies.length); if (policies.length == 1) { setTimeout(() => { $(".sno-checkbox").each(function() { - // console.log("time completed function called"); + // // console.log("time completed function called"); $(".sno-checkbox").prop("checked", true); this.dispatchEvent(new Event("change", { bubbles: true @@ -1818,25 +1899,28 @@ function getAnswer(table_id, rowID) { event.stopPropagation(); - // console.log("Function called", table_id); + // alert(); + // // console.log("Function called"); + + // // console.log("Function called", table_id); var policy = table_id.split('_').slice(0, -1).join('_'); // var policy = 'policy_' + table; - // console.log('policy ', rowID); + // // console.log('policy ', rowID); Object.entries(child_table_data).forEach(([key, value]) => { if (key == policy) { var table_data = value; - // // console.log("table data ",table_data); + // // // console.log("table data ",table_data); // Loop through all available table data (removing hardcoded [0]) table_data.forEach(table => { var table_row = table['table_row_contents']; - // // console.log("table Row ",table_row); + // // // console.log("table Row ",table_row); Object.entries(table_row).forEach(([key, value]) => { var question_id = Object.keys(value)[0]; - // // console.log("Question ID : ",question_id," row ID : ",rowID); + // // // console.log("Question ID : ",question_id," row ID : ",rowID); if (question_id == rowID) { let questionData = value[question_id]; - // console.log("question data", questionData); + // // console.log("question data", questionData); if (questionData.answer_type == 'dropdown') { var answerAndValues = questionData.answers; @@ -1853,7 +1937,7 @@ function createDropdown(answerAndValues) { - // // console.log(answerAndValues); + // // // console.log(answerAndValues); const originalTd = event.target; const dropdown = document.createElement("div"); dropdown.classList.add("simple-dropdown"); @@ -1906,7 +1990,7 @@ const overallContainer = document.getElementById('allTableContainer'); if (!excessTable) { - // console.log("Excess table not found."); + // // console.log("Excess table not found."); return; } @@ -1962,9 +2046,9 @@ } function updateSNO(tableID) { - // console.log("Function Called Update Sno"); + // // console.log("Function Called Update Sno"); const table = document.getElementById(tableID); - // console.log("table : ", table); + // // console.log("table : ", table); if (!table) return; const rows = table.querySelectorAll("tbody tr"); @@ -1986,17 +2070,17 @@ $('.table-collapsible-bar').each(function() { let currentWidth = ($(this).width()); - // // console.log('table width ', typeof (currentWidth)); + // // // console.log('table width ', typeof (currentWidth)); let increaseTableWidth = (currentWidth + increaseBy); - // // console.log(increaseTableWidth); + // // // console.log(increaseTableWidth); $(this).width(currentWidth + increaseBy); }); - // // console.log("function called tablewidth increase"); + // // // console.log("function called tablewidth increase"); $("table").each(function() { let currentWidth = ($(this).width()); - // // console.log('table width ', typeof(currentWidth)); + // // // console.log('table width ', typeof(currentWidth)); let increaseTableWidth = (currentWidth + increaseBy); - // // console.log(increaseTableWidth); + // // // console.log(increaseTableWidth); $(this).width(currentWidth + increaseBy); }); } @@ -2005,7 +2089,7 @@ // Target the container const container = document.getElementById('tablesContainer'); if (!container) { - console.error('Error: tablesContainer not found'); + // console.error('Error: tablesContainer not found'); return; } @@ -2028,7 +2112,7 @@ const selectedContainers = containerArray.filter(container => selectedPolicies.has(container.policyName) ); - // // console.log('container selected ',selectedContainers); + // // // console.log('container selected ',selectedContainers); // Sort by priority selectedContainers.sort((a, b) => a.priority - b.priority); @@ -2041,11 +2125,11 @@ function setValueForHiddenField(element, answer_type) { // alert("hi"); if (answer_type != 'dropdown') { - // // console.log(element); + // // // console.log(element); const hiddenInput = element.querySelector("input[type='hidden']"); const updatedText = element.textContent.trim(); var updated_Text = element.textContent.trim(); - // // console.log('updated text ',updated); + // // // console.log('updated text ',updated); if (hiddenInput) { hiddenValue = updated_Text; @@ -2053,9 +2137,9 @@ // Convert it back to a JSON string and set the value hiddenInput.value = JSON.stringify(hiddenValue); - // console.log("Updated Hidden Input Value:", hiddenInput.value); + // // console.log("Updated Hidden Input Value:", hiddenInput.value); } else { - console.warn("No hidden input found inside the element."); + // console.warn("No hidden input found inside the element."); } } checkCellValueAndHighlight(); @@ -2126,11 +2210,11 @@ }); function getPolicyInfo(policyName) { - // console.log("anchor link clicked ", policyName); + // // console.log("anchor link clicked ", policyName); myModal = new bootstrap.Modal(document.getElementById('policyRegisterModel')); - // console.log("inside if condition"); + // // console.log("inside if condition"); var leadID = $("#lead_id").val(); let policy = policies.find(p => p.name === policyName); @@ -2211,13 +2295,13 @@ } var policySummary = tableRowContent; - // console.log("policy summary ", policySummary); + // // console.log("policy summary ", policySummary); return policySummary; } async function selectInsurer(insurers) { - // console.log("Async function called"); + // // console.log("Async function called"); // Build the HTML for the Select2 dropdown and the input text field const selectHTML = `
    @@ -2278,9 +2362,9 @@ } function saveRFQ() { - // console.log("save button clicked"); + // // console.log("save button clicked"); leadJson = tablesToJson(); - // console.log("json from function ", leadJson); + // // console.log("json from function ", leadJson); var policyJson = localStorage.getItem("policyData") ?? null; saveRFQTODB(leadJson, policyJson); } @@ -2310,7 +2394,7 @@ localStorage.removeItem('policyData'); toastr.success(response.message, "Success"); - // console.log(rfq_data.length); + // // console.log(rfq_data.length); $('.actionBtns').show(); if (rfq_or_qcr == 2) { @@ -2329,16 +2413,25 @@ error: function(xhr, status, error) { $('.loader').fadeOut(); $('.loader-mask').delay(350).fadeOut('slow'); - console.error(xhr.responseText); - console.error(status, error); + // console.error(xhr.responseText); + // console.error(status, error); } }) } function prepareOverallData() { + var proposalKey = ""; const overAllData = {}; Object.entries(policyConfig).forEach(([proposalNumber, insurers]) => { - const proposalKey = `Proposal ${proposalNumber}`; + if (lead_type == 1){ + proposalKey = `Proposal ${proposalNumber}`; + }else{ + if (proposalNumber == 0){ + proposalKey = `${rollover_or_renewal} ${proposalNumber}`; + }else{ + proposalKey = `Proposal ${proposalNumber}`; + } + } overAllData[proposalKey] = { qcr: 0, stc: 0, @@ -2352,7 +2445,7 @@ overAllData[proposalKey].qcr = qcrSelected ? 1 : 0; overAllData[proposalKey].stc = stcSelected ? 1 : 0; } - // console.log("Insurers Found", insurers); + // // console.log("Insurers Found", insurers); const uniqueInsurers = []; insurers.forEach(insurer => { @@ -2362,11 +2455,11 @@ insurerHeaders.forEach(header => { const headerProposalCount = header.getAttribute("data-proposal"); if (headerProposalCount == proposalNumber) { - // console.log("Found the subheader we are searching"); + // // console.log("Found the subheader we are searching"); if (header.querySelector('.sendInsurerClientProposal .fa-check-square') !== null) { stcInsurerSelected = true; } - // console.log("STC selected for insurer:", stcInsurerSelected); + // // console.log("STC selected for insurer:", stcInsurerSelected); } }); uniqueInsurers.push({ @@ -2378,10 +2471,10 @@ }); } }); - // console.log("Unique Insurers Found", uniqueInsurers); + // // console.log("Unique Insurers Found", uniqueInsurers); overAllData[proposalKey].insurers = Array.from(uniqueInsurers.values()); }); - // console.log("overalll data created is ", overAllData); + // // console.log("overalll data created is ", overAllData); return overAllData; } @@ -2402,7 +2495,7 @@ var headers = []; const data = []; const tableId = table.id; // Ensure each table has a unique ID - // // console.log('Processing table:', tableId); + // // // console.log('Processing table:', tableId); // Get parent headers and subheaders for the current table const parentHeaders = table.querySelectorAll('thead tr:nth-child(1) th'); @@ -2410,34 +2503,34 @@ let headerIndex = 0; parentHeaders.forEach(header => { - // console.log("Found header ", header); - if (header.innerText.trim().startsWith("Proposal")) { + // // console.log("Found header ", header); + if (header.innerText.trim().startsWith("Proposal") || header.innerText.trim().startsWith("Existing")) { var policyNumber = header.getAttribute("data-proposal"); var colspan = parseInt(quotesConfig[policyNumber].length); - // console.log("Found header true colspan : ", colspan); + // // console.log("Found header true colspan : ", colspan); } else { var colspan = parseInt(header.getAttribute('colspan')) || 1; } const subHeaderArray = []; // console.log("processing save function header : ", header); - // // console.log("processing save colspn : ",colspan); + // // // console.log("processing save colspn : ",colspan); for (let i = 0; i < colspan; i++) { const subheaderHTML = subHeaders[headerIndex].innerHTML; const subheaderText = subheaderHTML.replace(//g, '').trim(); subHeaderArray.push(subheaderText); headerIndex++; } - // console.log("inside save colspn : ", colspan); + // // console.log("inside save colspn : ", colspan); const headerHTML = header.innerHTML; const headerText = headerHTML.replace(//g, '').trim(); // console.log("processing sub header array : ", subHeaderArray); - // console.log("HEader : ", header.innerText == " " ? header.innerText.trim() : headerText); + // // console.log("HEader : ", header.innerText == " " ? header.innerText.trim() : headerText); headers.push({ // parentHeader: header.innerText.replace('â‹®', '').split('\n')[0].replace(/:.*/, '').trim(), parentHeader: headerText, subHeaders: subHeaderArray }); - // console.log("processing sub header array : ", headers); + // // console.log("processing sub header array : ", headers); }); // Process each row in the current table @@ -2447,11 +2540,11 @@ let rowIdForRemoveFirstIndex = ""; rows.forEach(row => { const rowId = row.id; - // console.log("row id : ", rowId); - // console.log("Suggestions :", suggestions); + // // console.log("row id : ", rowId); + // // console.log("Suggestions :", suggestions); const inputType = suggestions[rowId]?.answer_type || 'text'; // Default to 'text' if undefined const cells = row.querySelectorAll('td'); - // // console.log("row id going to submit us ", ); + // // // console.log("row id going to submit us ", ); const rowData = { SNO: cells[0] ? getTextExcludingButton(cells[0]) : '', items: cells[1]?.innerText || '', @@ -2459,11 +2552,11 @@ data: [] }; if (tableId == "excess") { - // console.log("row Trying to set : ", row); - // console.log("row Trying to set : ", row.outerHTML); + // // console.log("row Trying to set : ", row); + // // console.log("row Trying to set : ", row.outerHTML); rowData['parentPolicy'] = row.getAttribute("data-excess-row-parent") } - // console.log("Row data foint to submit ", rowData); + // // console.log("Row data foint to submit ", rowData); let dataIndex = 0; if (rowIdCount[rowId] === undefined) { rowIdCount[rowId] = 0; @@ -2471,15 +2564,15 @@ rowIdCount[rowId]++; } const occurrence = rowIdCount[rowId]; - // console.log("NEw Method : rowIdCount",rowIdCount) - // console.log("NEw Method : occurrence",occurrence) + // // console.log("NEw Method : rowIdCount",rowIdCount) + // // console.log("NEw Method : occurrence",occurrence) let rowspan_row_id = ''; if (occurrence > 0) { var headers2 = headers; headers2 = headers2.filter((header, index) => !(index === 0 && header.parentHeader === "Policy")); - // console.log("Header 2 ",headers2); + // // console.log("Header 2 ",headers2); headers2.forEach((header2, TableDataHeaderIndex) => { header2.subHeaders.forEach(subHeader => { @@ -2490,7 +2583,7 @@ if (inputType === "text" && header2.parentHeader === 'Action') { const qcrInput = cell.querySelector('input[name="qcr"]'); const clientInput = cell.querySelector('input[name="stc"]'); - // console.log("QCR INPUT : ", qcrInput); + // // console.log("QCR INPUT : ", qcrInput); content = { qcr: qcrInput?.checked ? 1 : 0, @@ -2499,7 +2592,7 @@ } else { const input = cell.querySelector('input, select, textarea'); if (input) { - // console.log("Input type:", input.type); + // // console.log("Input type:", input.type); if (input.type === "checkbox") { content = input.checked ? "Checked" : "Not Checked"; // Handling checkboxes @@ -2507,7 +2600,7 @@ } else { content = input.value; // Handling other input types like text, select, textarea display_content = cell.innerText.trim(); - // console.log("processing sub header array : ", content); + // // console.log("processing sub header array : ", content); } } else { content = cell.innerText.trim(); // If no input is found, use the cell's text @@ -2536,11 +2629,11 @@ // let parentThDataText; // if (headers[TableDataHeaderIndex + headerIndexOffset]) { // parentThDataText = headers[TableDataHeaderIndex + headerIndexOffset].parentHeader; - // // console.log("NEw Method : parentThDataText",parentThDataText) + // // // console.log("NEw Method : parentThDataText",parentThDataText) // } else { // parentThDataText = header.parentHeader; // Fallback if there are no more headers // } - // // console.log(`Row ${rowId} occurrence ${occurrence} using header: `, parentThDataText); + // // // console.log(`Row ${rowId} occurrence ${occurrence} using header: `, parentThDataText); header.subHeaders.forEach(subHeader => { @@ -2551,7 +2644,7 @@ if (inputType === "text" && header.parentHeader === 'Action') { const qcrInput = cell.querySelector('input[name="qcr"]'); const clientInput = cell.querySelector('input[name="stc"]'); - // console.log("QCR INPUT : ", qcrInput); + // // console.log("QCR INPUT : ", qcrInput); content = { qcr: qcrInput?.checked ? 1 : 0, @@ -2560,7 +2653,7 @@ } else { const input = cell.querySelector('input, select, textarea'); if (input) { - // console.log("Input type:", input.type); + // // console.log("Input type:", input.type); if (input.type === "checkbox") { content = input.checked ? "Checked" : "Not Checked"; // Handling checkboxes @@ -2568,7 +2661,7 @@ } else { content = input.value; // Handling other input types like text, select, textarea display_content = cell.innerText.trim(); - // console.log("processing sub header array : ", content); + // // console.log("processing sub header array : ", content); } } else { content = cell.innerText.trim(); // If no input is found, use the cell's text @@ -2581,14 +2674,14 @@ // if(rowId == rowspan_row_id){ // parentThDataText = rowspan_row_id == rowId ? headers[TableDataHeaderIndex + 1].parentHeader : header.parentHeader; - // // console.log('rowspan_row_id parentThDataText', parentThDataText); - // // console.log('rowspan_row_id', rowspan_row_id); + // // // console.log('rowspan_row_id parentThDataText', parentThDataText); + // // // console.log('rowspan_row_id', rowspan_row_id); // rowspan_row_id = rowspan_row_id - 1; - // // console.log('rowspan_row_id after decrement', rowspan_row_id); + // // // console.log('rowspan_row_id after decrement', rowspan_row_id); // } - // // console.log("trying to find what this is ",cell); + // // // console.log("trying to find what this is ",cell); rowData.data.push({ parentth: header.parentHeader, subth: subHeader, @@ -2603,11 +2696,11 @@ }); data.push(rowData); - // // console.log("processing sub header array : ",content); + // // // console.log("processing sub header array : ",content); }); tablePolicyName = [...selectedPolicies].find(policy => tableId.startsWith(policy)) || null; - // console.log(selectedPolicies); - // console.log(tablePolicyName); + // // console.log(selectedPolicies); + // // console.log(tablePolicyName); // Get table-specific over_all_column_data (adjust based on your data structure) @@ -2631,7 +2724,7 @@ }); // Save all tables' data to localStorage localStorage.setItem('allTablesJsonData', JSON.stringify(allTablesData)); - // console.log('All tables data saved:', allTablesData); + // // console.log('All tables data saved:', allTablesData); // toastr.success("RFQ Saved Successfully", "SUCCESS"); // If needed, reconstruct tables from JSON (implement jsonToTable accordingly) @@ -2645,7 +2738,7 @@ segments[segments.length - 1] = "2"; // Change the last segment const newUrl = segments.join("/"); // Rebuild the URL - // console.log('newUrl', newUrl) + // // console.log('newUrl', newUrl) history.pushState(null, "", newUrl); // Change the URL without reloading @@ -2669,9 +2762,19 @@ Object.entries(overAllColumnData).forEach(([proposalKey, proposalData]) => { // Extract proposal number from the key (ensuring it's properly extracted) let match = proposalKey.match(/\d+/); // Extracts the number from "Proposal X" - let proposalNumber = match ? match[0] : undefined; + let proposalNumber = ""; + if (lead_type == 1){ + proposalNumber = match ? match[0] : undefined; + }else{ + if (rfq_count == 0){ + proposalNumber = 0; + }else{ + // alert(proposalData); + proposalNumber = match ? match[0] : undefined; + } + } - if (!proposalNumber) return; // Skip if extraction fails + // if (!proposalNumber) return; // Skip if extraction fails // Initialize with "Quote asked" result[proposalNumber] = ["Quote asked"]; @@ -2696,15 +2799,22 @@ function setQuotesConfig(overallColumnData) { let quotesConfiguration = {}; // Stores the transformed output let index = 1; // Keeps track of proposal index - // console.log(overallColumnData); + // // console.log(overallColumnData); Object.keys(overallColumnData).forEach((proposalKey) => { let parts = proposalKey.split(" "); let lastNumber = parseInt(parts[parts.length - 1], 10); - index = lastNumber; - // console.log(proposalKey); - // console.log(index); - // console.log(value); + + if (lead_type == 1){ + index = lastNumber; + }else{ + if (rfq_count == 0){ + index = 0; + }else{ + index = lastNumber; + } + } + let proposal = overallColumnData[proposalKey]; let insurersList = proposal.insurers.map(ins => ins.ins_name); // Extract insurer names @@ -2717,9 +2827,9 @@ } function addSuggestion(rowData) { - console.log("child table data rowData", rowData); - console.log("child table data rowData.id", rowData.row_id); - console.log("child table data child_table_data", child_table_data[rowData.row_id]); + // // console.log("child table data rowData", rowData); + // // console.log("child table data rowData.id", rowData.row_id); + // // console.log("child table data child_table_data", child_table_data[rowData.row_id]); var table_data = child_table_data[rowData.row_id]; @@ -2731,7 +2841,7 @@ }); }); - // console.log("child table data ", suggestions); + // // console.log("child table data ", suggestions); // child_table_data[rowData.rowID] } @@ -2761,18 +2871,28 @@ quotesConfig = setQuotesConfig(proposalDataArray.proposal_data.over_all_column_data); let keys = Object.keys(quotesConfig); let lastKey = keys[keys.length - 1]; - proposalCount = lastKey; + if (lead_type == 1){ + proposalCount = lastKey; + }else{ + if (rfq_count == 0){ + proposalCount = 0; + }else{ + proposalCount = keys.length-1; + } + } + + proposalCountForTableINcrease = keys.length; - console.log(proposalCount); + // console.log(proposalCount); // Calculate width increase let increaseBy = rfq_or_qcr == 2 ? getTotalCount(proposalDataArray) * 150 : proposalCountForTableINcrease * 150; - console.log("Quotes COnfig : ",quotesConfig); - console.log("policy COnfig :", policyConfig); - // // console.log("trying to find checkbox data : : : ", increaseBy); + // console.log("Quotes COnfig : ",quotesConfig); + // console.log("policy COnfig :", policyConfig); + // // // console.log("trying to find checkbox data : : : ", increaseBy); suggestions = {}; @@ -2854,7 +2974,7 @@ else { // td.onclick = () => getAnswer(table.id, tr.id); td.innerHTML = processCellContent(cellData.input_value, rowData, cellData.display_content); - // console.log("DEBUG ISSUE : ",cellData.parentth) + // // console.log("DEBUG ISSUE : ",cellData.parentth) if (cellData.parentth.startsWith("Proposal") || cellData.parentth.startsWith("Existing")) { if (lead_type == 1){ @@ -2864,8 +2984,9 @@ td.classList.add("insurer_proposal"); } }else{ - + td.onclick = () => getAnswer(table.id, tr.id); if (cellData.subth != "Quote asked") { + td.onclick = () => getAnswer(table.id, tr.id); td.classList.add("insurer_proposal"); } } @@ -2956,40 +3077,70 @@ const headerRow2 = document.createElement('tr'); var overallColumnDataProposal = proposal_data.proposal_data.over_all_column_data; var matchedKey = ""; + var headerName = ''; headers.forEach(header => { // Parent header const th1 = document.createElement('th'); th1.textContent = header.parentHeader; if (header.parentHeader.startsWith('Proposal') || header.parentHeader.startsWith("Existing")) { if (lead_type == 1){ - var headerName = header.parentHeader; + headerName = header.parentHeader; }else{ - var headerName = rollover_or_renewal; - } + if (rfq_count == 0){ + headerName = rollover_or_renewal; + }else{ + headerName = header.parentHeader; + } + } + var proposalHTMLNumber = ""; + console.log("Header Name : ",header.parentHeader); + // alert(headerName); if (lead_type == 1){ + console.log("Header Name lead type 1 : ",header.parentHeader); matchedKey = Object.keys(overallColumnDataProposal).find(key => headerName.startsWith(key)); + proposalHTMLNumber = header.parentHeader.split(' ')[1]; }else{ + console.log("Header Name lead type not 1 : ",header.parentHeader); + + if (rfq_count == 0 && header.parentHeader.startsWith("Proposal")){ + console.log("Header Name lead type not 1 proposal: ",header.parentHeader); - if (header.parentHeader.startsWith("Proposal")){ var tempHeader = header.parentHeader; matchedKey = Object.keys(overallColumnDataProposal).find(key => tempHeader.startsWith(key)); + proposalHTMLNumber = 0; + }else{ - matchedKey = Object.keys(overallColumnDataProposal).find(key => headerName.startsWith(key)); + + console.log("Header Name lead type not 1 noy proposal: ",header.parentHeader); + + if (header.parentHeader.startsWith("Existing")){ + var tempHeader2 = lead_type == 2 ?"Existing Renewal 0":"Existing Roll Over 0"; + matchedKey = Object.keys(overallColumnDataProposal).find(key => tempHeader2.startsWith(key)); + proposalHTMLNumber = 0; + // alert(tempHeader2); + }else if (header.parentHeader.startsWith("Proposal")){ + matchedKey = Object.keys(overallColumnDataProposal).find(key => headerName.startsWith(key)); + proposalHTMLNumber = header.parentHeader.split(' ')[1]; + } + + // alert(matchedKey); } } if (matchedKey) { - // console.log("something wrong : ", overallColumnDataProposal[matchedKey]); + // // console.log("something wrong : ", overallColumnDataProposal[matchedKey]); var headerCheckBoxProperties = overallColumnDataProposal[matchedKey]; + // // console.log("something wrong :headerCheckBoxProperties ", headerCheckBoxProperties); } + th1.innerHTML = ` - ${header.parentHeader} + ${headerName} `; th1.colSpan = header.subHeaders.length; - // // console.log("insurer data proposal set : ",th1); // See the element's attributes in the console + // // // console.log("insurer data proposal set : ",th1); // See the element's attributes in the // console } headerRow1.appendChild(th1); - // // console.log("this is the header : ", header); + // // // console.log("this is the header : ", header); // Sub headers header.subHeaders.forEach(subHeader => { const th2 = document.createElement('th'); if (header.parentHeader.startsWith("Proposal") || header.parentHeader.startsWith("Existing")) { var insurers = overallColumnDataProposal[matchedKey].insurers; + // // console.log("trying to find something :header.parentHeader ", header.parentHeader); + // // console.log("trying to find something :insurers ", insurers); + // // console.log("trying to find : subHeader",subHeader) const matchedInsurer = insurers.find(ins => ins.ins_name == subHeader); + if (subHeader != "Quote asked") { - // console.log("trying to find something : ", matchedInsurer.stc); + // // console.log("trying to find something : matchedInsurer", matchedInsurer); + // // console.log("trying to find something :matchedInsurer stc ", matchedInsurer.stc); + // // console.log("trying to find something : ", matchedInsurer.stc); - // console.log("this is the subheader : ", subHeader); - // console.log("debug 2: ", subHeader, "parent header : ", header.parentHeader); + // // console.log("this is the subheader : ", subHeader); + // // console.log("debug 2: ", subHeader, "parent header : ", header.parentHeader); th2.classList.add("insurer_proposal"); th2.innerHTML = ` ${subHeader} @@ -3032,19 +3189,34 @@ style="background-color: rgb(221, 221, 221);">Send to Client ${matchedInsurer.stc == 1 ? ``: ""} - - + +
    `; } else { th2.textContent = subHeader; } + if (lead_type == 1){ + + th1.setAttribute('data-proposal', header.parentHeader.split(' ')[1]); + th2.setAttribute('data-proposal', header.parentHeader.split(' ')[1]); - th2.setAttribute('data-proposal', header.parentHeader.split(' ')[1]); + }else{ + if (headerName.startsWith("Existing")){ + th1.setAttribute('data-proposal',0); + th2.setAttribute('data-proposal',0); + + }else{ + th1.setAttribute('data-proposal', header.parentHeader.split(' ')[1]); + th2.setAttribute('data-proposal', header.parentHeader.split(' ')[1]); + + } + + } th2.setAttribute("data-quote", subHeader); - th1.setAttribute('data-proposal', header.parentHeader.split(' ')[1]); - // // console.log("header insert position ",th1.getAttribute()) + + // // // console.log("header insert position ",th1.getAttribute()) } else { th2.textContent = subHeader; @@ -3068,7 +3240,7 @@ if (value == "Checked") { addSuggestion(cellData); } - // // console.log("insude the function value ", value); + // // // console.log("insude the function value ", value); return ` ${cellData.SNO} ${cellData.SNO == 'Fire' || cellData.SNO == 'Burglary' ? `
    + + + +
    + +
    + + +
    +
    + /assets/images/nhance-loader-fast.gif" height="40" width="40" alt="Loading..."> +
    +
    + + + +
    +

    © 2025 Nhance India Pvt Ltd. All Rights Reserved.

    +
    + + + + + + \ No newline at end of file diff --git a/app/Views/ticket_feedback_list.php b/app/Views/ticket_feedback_list.php new file mode 100644 index 00000000..f4de0f73 --- /dev/null +++ b/app/Views/ticket_feedback_list.php @@ -0,0 +1,148 @@ + + + + + +
    +
    +
    +
    +
    +

    Claim Feedback List

    +
    + +
    +
    + + + + + + + + + + + + + + + + + + + + + +
    Claim NumberEmp CodeEmp nameCorporate name
    + +
    +
    +
    +
    +
    +
    + + + + + + \ No newline at end of file From 240c821f20e84b4e6735b413dfca76b6b552198b Mon Sep 17 00:00:00 2001 From: "venkatesh.r" Date: Thu, 3 Apr 2025 17:39:06 +0530 Subject: [PATCH 36/52] CHANGE_CLAIM_CR : RV --- app/Controllers/TicketController.php | 44 ++++++++++++++++++++++++++-- app/Views/ticket_history.php | 3 +- app/Views/ticket_list.php | 2 +- 3 files changed, 45 insertions(+), 4 deletions(-) diff --git a/app/Controllers/TicketController.php b/app/Controllers/TicketController.php index a783fa2f..6c2942c9 100644 --- a/app/Controllers/TicketController.php +++ b/app/Controllers/TicketController.php @@ -121,6 +121,7 @@ class TicketController extends BaseController '((AUTO_QUERY_CONTENT))' => 'auto_query_content', '((CLAIM_FORM_LINK))' => 'claim_form_link', '((CLAIM_FEEDBACK_FORM))' => 'claim_feedback_form', + '((SETTLED_LETTER))' => 'settle_letter', ]; $this->extraFields = [ 1 => ['non_id_reason'], @@ -233,6 +234,7 @@ class TicketController extends BaseController 'tcs.claim_status AS status', 'tm.claim_number AS claim_no', 'tm.tpa_id', + 'tm.tpa_no', 'tm.emp_name', 'tm.emp_code', 'i.name AS insurer_name', @@ -274,6 +276,7 @@ class TicketController extends BaseController 'tm.claim_status_id', 'tm.is_head_approved', 'tm.tpa_id', + 'tm.tpa_no', 'tm.emp_name', 'tm.emp_code', 'i.name AS insurer_name', @@ -857,7 +860,7 @@ class TicketController extends BaseController } // Construct Mail Data - $mailData = [ + $mailData[] = [ 'mail' => $ticket_data['emp_mail'], 'subject' => $subject, 'message' => $message, @@ -865,6 +868,17 @@ class TicketController extends BaseController 'attachments' => [] ]; + // if the employee personal mail is not empty then send the mail to the employee personal mail + if(!empty($ticket_data['emp_personal_mail'])){ + $mailData[] = [ + 'mail' => $ticket_data['emp_personal_mail'], + 'subject' => $subject, + 'message' => $message, + 'cc' => $ticket_data['common_mails'] ?? '', + 'attachments' => [] + ]; + } + // print_r($mailData); die; $this->myLogger->logme('error', "Final Email Data"); @@ -891,6 +905,8 @@ class TicketController extends BaseController $replaceData = 'Click here to download Claim Form'; } else if ($value == "claim_feedback_form"){ $replaceData = 'Click to open Claim Feedback Form'; + } else if ($value == "settle_letter"){ + $replaceData = ' View Settlement Letter '; }else { $replaceData = isset($ticket_data[$value]) ? $ticket_data[$value] : ''; } @@ -949,6 +965,27 @@ class TicketController extends BaseController $this->myLogger->logme('error', "Fetched ACM emails"); + + if(!empty($ticket_data['emp_personal_mail'])){ + + $this->myLogger->logme('error', "Send employee personal mail start"); + + $emailPersonalData = [ + 'mail' => $ticket_data['emp_personal_mail'], + 'subject' => $mail_data['mail_subject'], + 'message' => $mail_data['mail_content'], + 'common' => [], + 'cc' => $acm_mails['common_mails'], + 'attachments' => [] + ]; + + $this->sendTrigger($emailPersonalData); + + $this->myLogger->logme('error', "Send employee personal mail successfully"); + }else{ + $this->myLogger->logme('error', "Send employee personal mail is empty"); + } + $emailData = [ 'mail' => $mail_data['emp_mail'], 'subject' => $mail_data['mail_subject'], @@ -972,7 +1009,10 @@ class TicketController extends BaseController if (!empty($auto_mail_enable) && $auto_mail_enable['is_auto_mail'] == 1) { $mail_content = $this->constructMailContent($ticket_id); // print_r($mail_content); die; - $mail_responce = $this->sendTrigger($mail_content); + foreach ($mail_content as $key => $value) { + $mail_responce = $this->sendTrigger($value); + $this->myLogger->logme('error', '{data} - Auto Mail Sent, Successfully', ['data' => $key + 1]); + } } elseif (!empty($auto_mail_enable) && $auto_mail_enable['is_auto_mail'] == 0) { $this->myLogger->logme('error', 'Auto Mail Not Sent, Reason: Automail Not Enabled'); } else { diff --git a/app/Views/ticket_history.php b/app/Views/ticket_history.php index 0a783d26..c0e5bfea 100644 --- a/app/Views/ticket_history.php +++ b/app/Views/ticket_history.php @@ -21,7 +21,8 @@ '.$row['new_value']; ?> - + + diff --git a/app/Views/ticket_list.php b/app/Views/ticket_list.php index fa5c8fcc..f0410316 100644 --- a/app/Views/ticket_list.php +++ b/app/Views/ticket_list.php @@ -114,7 +114,7 @@ table.dataTable tbody td { - + From 27817789addc68b17d6aefc8669fc3c4200ea062 Mon Sep 17 00:00:00 2001 From: Srinivas-Saravanan Date: Fri, 4 Apr 2025 14:25:21 +0530 Subject: [PATCH 37/52] DEBUG_CHATBOT --- .../Chatbot/EcardDownloadConversation.php | 2 ++ app/Controllers/Chatbot/MainMenuConversation.php | 8 ++++++++ .../Chatbot/NetworkHospitalConversation.php | 3 +++ app/Controllers/Chatbot/policyConversation.php | 3 +++ app/Controllers/ChatbotControllerNew.php | 14 +++++++------- 5 files changed, 23 insertions(+), 7 deletions(-) diff --git a/app/Controllers/Chatbot/EcardDownloadConversation.php b/app/Controllers/Chatbot/EcardDownloadConversation.php index b0cb78ae..84617af1 100644 --- a/app/Controllers/Chatbot/EcardDownloadConversation.php +++ b/app/Controllers/Chatbot/EcardDownloadConversation.php @@ -17,6 +17,8 @@ class EcardDownloadConversation extends Conversation protected function showEcardMenu() { + log_message('error', ('showEcardMenu function called')); + $chat_session_info = get_chatbot_session_info(); $policy_list = ChatbotHelper::getListOfPolicies($chat_session_info); $buttons = []; diff --git a/app/Controllers/Chatbot/MainMenuConversation.php b/app/Controllers/Chatbot/MainMenuConversation.php index 87d9a4ef..875ecba4 100644 --- a/app/Controllers/Chatbot/MainMenuConversation.php +++ b/app/Controllers/Chatbot/MainMenuConversation.php @@ -46,9 +46,14 @@ class MainMenuConversation extends Conversation $this->bot->reply($message); } + log_message('error', ('user_reponse before: ' . $user_reponse)); + + if (!$answer->isInteractiveMessageReply()) { $user_reponse = null; } + + // Get just the existing path array $path = $this->bot->userStorage()->get('path') ?? []; @@ -60,6 +65,9 @@ class MainMenuConversation extends Conversation 'path' => $path ]); + log_message('error', ('user_reponse : ' . $user_reponse)); + + switch ($user_reponse) { case "ecard_download": diff --git a/app/Controllers/Chatbot/NetworkHospitalConversation.php b/app/Controllers/Chatbot/NetworkHospitalConversation.php index 2e59f896..4a1e991c 100644 --- a/app/Controllers/Chatbot/NetworkHospitalConversation.php +++ b/app/Controllers/Chatbot/NetworkHospitalConversation.php @@ -59,7 +59,10 @@ class NetworkHospitalConversation extends Conversation $this->bot->userStorage()->save([ 'path' => $path ]); + log_message('error', ('user_reponse : ' . $answer->getValue())); + switch ($answer->getValue()) { + case is_string($answer->getValue()) && is_array(explode('#',$answer->getValue())) && count((explode('#',$answer->getValue()))) == 2: $client_poilicy_id = explode('#',$answer->getValue())[1]; diff --git a/app/Controllers/Chatbot/policyConversation.php b/app/Controllers/Chatbot/policyConversation.php index 04c8d9a5..f2fe91c1 100644 --- a/app/Controllers/Chatbot/policyConversation.php +++ b/app/Controllers/Chatbot/policyConversation.php @@ -46,6 +46,9 @@ class policyConversation extends Conversation if (!$answer->isInteractiveMessageReply()) { $user_reponse = null; } + + log_message('error', ('user_reponse : ' . $answer->getValue())); + $path = $this->bot->userStorage()->get('path'); array_push($path, $answer->getValue() diff --git a/app/Controllers/ChatbotControllerNew.php b/app/Controllers/ChatbotControllerNew.php index 610f2bda..2f6ca404 100644 --- a/app/Controllers/ChatbotControllerNew.php +++ b/app/Controllers/ChatbotControllerNew.php @@ -89,7 +89,7 @@ class ChatbotControllerNew extends BaseController $user = $this->botman->getUser(); $id = $user->getId(); - // $this->myLogger->logme('error', ('TEST' . $id)); + $this->myLogger->logme('error', ('TEST' . $id)); $this->session->set('CHATBOT_RANDOM_USER_ID', $id); } @@ -128,14 +128,14 @@ class ChatbotControllerNew extends BaseController $this->botman->listen(); } - private function registerHandlers() - { - // Handling Policy and Claims - $this->botman->hears('group:policy:{option}', [\App\Controllers\Chatbot\PolicyHandler::class, 'handle']); - $this->botman->hears('group:claim:{option}', [\App\Libraries\Chatbot\ClaimHandler::class, 'handle']); + // private function registerHandlers() + // { + // // Handling Policy and Claims + // $this->botman->hears('group:policy:{option}', [\App\Controllers\Chatbot\PolicyHandler::class, 'handle']); + // $this->botman->hears('group:claim:{option}', [\App\Libraries\Chatbot\ClaimHandler::class, 'handle']); - } + // } public function chatbot() { From 1897b8760711415cb008d8da3120fd69b8695c7d Mon Sep 17 00:00:00 2001 From: Srinivas-Saravanan Date: Fri, 4 Apr 2025 17:59:03 +0530 Subject: [PATCH 38/52] FIX_EXCEL_MERGE_AND_FEAT_CAL_SRI --- app/Controllers/LeadsController.php | 2 +- app/Helpers/ExcelMergeHelper.php | 26 +++++++++--- app/Views/leads_form.php | 65 ++++++++++++++++++++++++++++- app/Views/rfq/gmc.php | 4 +- 4 files changed, 88 insertions(+), 9 deletions(-) diff --git a/app/Controllers/LeadsController.php b/app/Controllers/LeadsController.php index 1c5e9f80..bde79243 100644 --- a/app/Controllers/LeadsController.php +++ b/app/Controllers/LeadsController.php @@ -1801,7 +1801,7 @@ class LeadsController extends BaseController ['file_path' => $temp_file_path, 'sheets' => []], ['file_path' => $lead_file_path, 'sheets' => []] ]; - $outputPath = dirname($temp_file_path) . '/' . 'merged_' . $temp_file_name; + $outputPath = dirname($temp_file_path) . '/' . $temp_file_name; $result = ExcelMergeHelper::mergeExcelFiles($filePaths, $outputPath); // print_rr($result); } diff --git a/app/Helpers/ExcelMergeHelper.php b/app/Helpers/ExcelMergeHelper.php index 36306692..405c4762 100644 --- a/app/Helpers/ExcelMergeHelper.php +++ b/app/Helpers/ExcelMergeHelper.php @@ -17,10 +17,13 @@ class ExcelMergeHelper { { try { log_message('debug', 'Attempting merge with original file order'); + // echo "Attempting merge with original file order\n"; return self::processFiles($filePaths, $outputPath); } catch (Exception $e) { log_message('error', 'First attempt failed: ' . $e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine()); + // echo "First attempt failed: " . $e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine() . "\n"; log_message('debug', 'Retrying with reversed file order'); + // echo "Retrying with reversed file order\n"; // Reverse the file order and try again $reversedFiles = array_reverse($filePaths); @@ -29,6 +32,7 @@ class ExcelMergeHelper { return self::processFiles($reversedFiles, $outputPath); } catch (Exception $e2) { log_message('error', 'Both attempts failed. Last error: ' . $e2->getMessage() . ' in ' . $e2->getFile() . ' on line ' . $e2->getLine()); + // echo "Both attempts failed. Last error: " . $e2->getMessage() . ' in ' . $e2->getFile() . ' on line ' . $e2->getLine() . "\n"; return null; } } @@ -45,7 +49,9 @@ class ExcelMergeHelper { private static function processFiles(array $filePaths, string $outputPath): string { log_message('debug', 'Starting Excel merge process'); + // echo "Starting Excel merge process\n"; log_message('debug', 'Files to process: ' . json_encode($filePaths)); + // echo "Files to process: " . json_encode($filePaths) . "\n"; if (empty($filePaths)) { throw new Exception("No files provided to merge"); @@ -66,6 +72,7 @@ class ExcelMergeHelper { // Save the merged file log_message('debug', "Saving merged file to: {$outputPath}"); + // echo "Saving merged file to: {$outputPath}\n"; $writer = IOFactory::createWriter($mergedSpreadsheet, 'Xlsx'); $writer->setPreCalculateFormulas(false); $writer->save($outputPath); @@ -76,6 +83,7 @@ class ExcelMergeHelper { gc_collect_cycles(); log_message('debug', 'Excel merge process completed successfully'); + // echo "Excel merge process completed successfully\n"; return $outputPath; } @@ -87,15 +95,17 @@ class ExcelMergeHelper { * @param int|null $index * @throws Exception */ - private static function processSingleFile(array $fileInfo, Spreadsheet $mergedSpreadsheet, int $index = null) + private static function processSingleFile(array $fileInfo, Spreadsheet $mergedSpreadsheet, ?int $index = null) { if (!isset($fileInfo['file_path']) || !file_exists($fileInfo['file_path'])) { $path = $fileInfo['file_path'] ?? 'undefined'; log_message('error', "File " . ($index ?? 'base') . ": Invalid or missing file path: {$path}"); + // echo "File " . ($index ?? 'base') . ": Invalid or missing file path: {$path}\n"; return; } log_message('debug', "Processing file " . ($index ?? 'base') . ": " . $fileInfo['file_path']); + // echo "Processing file " . ($index ?? 'base') . ": " . $fileInfo['file_path'] . "\n"; try { // Load the source spreadsheet @@ -105,6 +115,7 @@ class ExcelMergeHelper { $worksheets = $sourceSpreadsheet->getAllSheets(); $totalSheets = count($worksheets); log_message('debug', "Total sheets in file: " . $totalSheets); + // echo "Total sheets in file: " . $totalSheets . "\n"; $sheetsToMerge = $fileInfo['sheets'] ?? []; @@ -114,26 +125,30 @@ class ExcelMergeHelper { try { $sheetName = $worksheet->getTitle(); log_message('debug', "Processing sheet: {$sheetName}"); + // echo "Processing sheet: {$sheetName}\n"; // Generate unique sheet name before cloning $newName = $sheetName; $counter = 1; while (in_array($newName, $mergedSpreadsheet->getSheetNames())) { - $newName = $sheetName . "_" . $counter++; + // $newName = $sheetName . "_" . $counter++; log_message('debug', "Sheet name already exists. Trying new name: {$newName}"); + // echo "Sheet name already exists. Trying new name: {$newName}\n"; } // Clone the worksheet and set the new name - $clonedSheet = clone $worksheet; - $clonedSheet->setTitle($newName); + // $clonedSheet = clone $worksheet; + // $clonedSheet->setTitle($newName); // Add as external sheet - $mergedSpreadsheet->addExternalSheet($clonedSheet); + $mergedSpreadsheet->addExternalSheet($worksheet); log_message('debug', "Successfully added sheet: {$newName}"); + // echo "Successfully added sheet: {$newName}\n"; } catch (Exception $e) { log_message('error', "Error processing sheet {$sheetName} as new name {$newName}: " . $e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine()); + // echo "Error processing sheet {$sheetName} as new name {$newName}: " . $e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine() . "\n"; } } } @@ -145,6 +160,7 @@ class ExcelMergeHelper { } catch (Exception $e) { log_message('error', "Error processing file {$fileInfo['file_path']}: " . $e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine()); + // echo "Error processing file {$fileInfo['file_path']}: " . $e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine() . "\n"; } } } \ No newline at end of file diff --git a/app/Views/leads_form.php b/app/Views/leads_form.php index 003e8d96..e3be624c 100644 --- a/app/Views/leads_form.php +++ b/app/Views/leads_form.php @@ -1064,7 +1064,7 @@ console.log('incurredClaimDate', incurredClaimDate) if (policyStartDate && incurredClaimDate) { - var timeDiff = incurredClaimDate - policyStartDate; // Time difference in milliseconds + var timeDiff = (policyStartDate - incurredClaimDate) + 1; // Time difference in milliseconds console.log('timeDiff', timeDiff); var daysDiff = Math.ceil(timeDiff / (1000 * 60 * 60 * 24)); // Convert to days and add 1 console.log('daysDiff', daysDiff); @@ -1145,6 +1145,69 @@ $('#earned_premium_' + increment).val(earned_premium_roundoff); } + $(document).on("input", "#incept_emp_count, #incept_dept_count, #renewal_emp_count, #renewal_dept_count, #exp_emp_count, #exp_dept_count", function() { + calculateTotalLives(this); + }); + + function calculateTotalLives(input) { + + var lead_type = $('#lead_type').val(); + + if (lead_type == 1) { + + let formRow = input.closest('.form-row'); + + if (formRow) { + // Get the employee count and dependent count within the same row + let empCountInput = formRow.querySelector('[name="incept_emp_count[]"]'); + let depCountInput = formRow.querySelector('[name="incept_dept_count[]"]'); + let totalLivesInput = formRow.querySelector('[name="incept_no_of_lives[]"]'); + + // Parse the input values as integers, defaulting to 0 if empty + let empCount = empCountInput ? parseInt(empCountInput.value) || 0 : 0; + let depCount = depCountInput ? parseInt(depCountInput.value) || 0 : 0; + + // Calculate total lives + let totalLives = empCount + depCount; + + // Set the total lives input value + if (totalLivesInput) { + totalLivesInput.value = totalLives; + } + } + + + } else { + console.log("Function Called"); + + if (input.id === "incept_emp_count" || input.id === "incept_dept_count") { + var incept_emp_count = parseInt($("#incept_emp_count").val()) || 0; + var incept_dept_count = parseInt($("#incept_dept_count").val()) || 0; + + var totalCount = incept_emp_count + incept_dept_count; + $("#incept_no_of_lives").val(totalCount); + + } else if (input.id === "renewal_emp_count" || input.id === "renewal_dept_count") { + var renewal_emp_count = parseInt($("#renewal_emp_count").val()) || 0; + var renewal_dept_count = parseInt($("#renewal_dept_count").val()) || 0; + + var totalCount = renewal_emp_count + renewal_dept_count; + $("#renewal_no_of_lives").val(totalCount); + + } else { + var exp_emp_count = parseInt($("#exp_emp_count").val()) || 0; + var exp_dept_count = parseInt($("#exp_dept_count").val()) || 0; + + var totalCount = exp_emp_count + exp_dept_count; + $("#exp_no_of_lives").val(totalCount); + } + } + + + } + + + //------------------------ FORM SUBMIT --------------------------------------------------------------------------------- $("#leads_form_id").submit(function(event) { diff --git a/app/Views/rfq/gmc.php b/app/Views/rfq/gmc.php index 09d28d3e..9c99df08 100644 --- a/app/Views/rfq/gmc.php +++ b/app/Views/rfq/gmc.php @@ -116,14 +116,14 @@ + placeholder="Enter Lives" required oninput="calculateTotalLives(this)">
    + placeholder="Enter Lives" required oninput="calculateTotalLives(this)">
    From 12e74fc877d1c58fc8f14f86d0486b1df071f14f Mon Sep 17 00:00:00 2001 From: "venkatesh.r" Date: Sat, 5 Apr 2025 10:08:51 +0530 Subject: [PATCH 39/52] FEAT_MULTI_FILE_UPLOAD_IN_LEAD_AND_SEND_ATTACHMENTS_RFQ : RV --- app/Config/Routes.php | 1 + app/Controllers/LeadsController.php | 179 +++++++++++++++++++++++----- app/Models/LeadFilesModel.php | 55 +++++++++ app/Views/leads_form.php | 14 ++- app/Views/leads_form_handler.php | 143 +++++++++++++++++++++- app/Views/leads_non_eb.php | 10 +- app/Views/rfq/attachment_files.php | 14 +++ app/Views/rfq/multi_files.php | 50 ++++++++ app/Views/view_rfq.php | 132 ++++++++++++++------ app/Views/view_rfq_non_eb.php | 56 +++++++++ 10 files changed, 578 insertions(+), 76 deletions(-) create mode 100644 app/Models/LeadFilesModel.php create mode 100644 app/Views/rfq/attachment_files.php create mode 100644 app/Views/rfq/multi_files.php diff --git a/app/Config/Routes.php b/app/Config/Routes.php index 0059a7a1..4f3f4223 100755 --- a/app/Config/Routes.php +++ b/app/Config/Routes.php @@ -348,6 +348,7 @@ $routes->group("/util", ["filter" => "authMVC"], function ($routes) { $routes->get('getTheEmpDataForClaimSearchByMobile/(:any)', 'ClientController::getTheEmpDataForClaimSearchByMobile/$1'); $routes->get('getLeadNonEB/(:any)', 'LeadsController::getLeadNonEB/$1'); $routes->get('getPolicyTypeFields', 'LeadsController::getPolicyTypeFields'); + $routes->get('removeMultiFile', 'LeadsController::removeMultiFile'); }); $routes->group("policy_tranction", ["filter" => "authMVC"], function ($routes) { diff --git a/app/Controllers/LeadsController.php b/app/Controllers/LeadsController.php index 1c5e9f80..9c35bc48 100644 --- a/app/Controllers/LeadsController.php +++ b/app/Controllers/LeadsController.php @@ -29,6 +29,7 @@ use App\Models\TPABranchModel; use App\Models\RFQModel; use App\Models\InsurerModel; use App\Models\OccupancyMasterModel; +use App\Models\LeadFilesModel; use App\Helpers\MailHelper; use App\Helpers\ExcelMergeHelper; @@ -62,6 +63,7 @@ class LeadsController extends BaseController protected $RFQModel; protected $insurerModel; protected $occupancyModel; + protected $leadFilesModel; //variables for storing array protected $issuer; @@ -92,6 +94,7 @@ class LeadsController extends BaseController $this->RFQModel = new RFQModel(); $this->insurerModel = new InsurerModel(); $this->occupancyModel = new OccupancyMasterModel(); + $this->leadFilesModel = new LeadFilesModel(); $this->issuer = [1 => 'JIBS', 2 => 'Nhance']; $this->clientType = [1 => 'Group', 2 => 'Individual']; @@ -206,13 +209,12 @@ class LeadsController extends BaseController private function prepareSingleLeadData($data) { // print_r($data); die; - $uploadFilePath = WRITEPATH . 'uploads/lead_files/'; - - // Get all uploaded files for 'file_name[]' - $files = $this->request->getFileMultiple('file_name'); - - // print_r($files); die; - + $index_plus_one = 1; + $form_file_name = "file_name_".$index_plus_one; + $form_docs_name = "docs_name_".$index_plus_one; + $leads_file_primary_key = $data['leads_file_id'] ?? []; + $files = $this->request->getFileMultiple($form_file_name); + $multi_file_data = $this->uploadMultiFiles($files, $data[$form_docs_name], $leads_file_primary_key); // Separate the insurer and insurer branch, handle missing or invalid data if (isset($data['insurer']) && strpos($data['insurer'], '-') !== false) { @@ -249,7 +251,9 @@ class LeadsController extends BaseController $data['policy_end_date'] = null; } - $data['file_name'] = file_Upload($files, $uploadFilePath); + // $data['file_name'] = file_Upload($files, $uploadFilePath); + $data['multi_file_data']= $multi_file_data ?? null; + $processcedData[] = $data; // print_r($data);die(); @@ -260,15 +264,16 @@ class LeadsController extends BaseController { // print_r($data); die; $processedData = []; - $uploadFilePath = WRITEPATH . 'uploads/lead_files/'; - - // Get all uploaded files for 'file_name[]' - $files = $this->request->getFileMultiple('file_name'); - - // print_r($files); die; foreach ($data['policy_type_id'] as $index => $value) { + $index_plus_one = $index + 1; + $form_file_name = "file_name_".$index_plus_one; + $form_docs_name = "docs_name_".$index_plus_one; + $leads_file_primary_key = $data['leads_file_id'] ?? []; + $files = $this->request->getFileMultiple($form_file_name); + $multi_file_data = $this->uploadMultiFiles($files, $data[$form_docs_name], $leads_file_primary_key); + // Separate the insurer and insurer branch, handle missing or invalid data if (isset($data['insurer'][$index]) && strpos($data['insurer'][$index], '-') !== false) { list($insurer_branch_id, $insurer_id) = explode('-', $data['insurer'][$index]); @@ -324,7 +329,7 @@ class LeadsController extends BaseController $premium_date = null; } - $file_name = file_Upload($files[$index], $uploadFilePath); + // $file_name = file_Upload($files[$index], $uploadFilePath); $last_3_years_claims = $data['finyear']; @@ -387,7 +392,8 @@ class LeadsController extends BaseController 'total_si_at_renewal' => $data['total_si_at_renewal'][$index] ?? 0, 'fin_years_claims' => $last_3_years_claims, - 'file_name' => $file_name, + // 'file_name' => $file_name, + 'multi_file_data' => $multi_file_data ?? null, 'status' => $data['status'] ?? null, 'notes' => $data['notes'] ?? null, @@ -405,6 +411,11 @@ class LeadsController extends BaseController $insertCount = []; foreach ($data as $value) { $insert = $this->leadsModel->insert($value); + + if ($insert) { + $this->insertMultiFilesData($value['multi_file_data'], $insert); + } + $insertCount[] = $insert; $this->insertLeadStatus($insert, $value['status'], 3); @@ -427,13 +438,15 @@ class LeadsController extends BaseController private function updateOldLead($id, $data) { if ($this->leadsModel->where('id', $id)->set($data[0])->update()) { + + $this->insertMultiFilesData($data[0]['multi_file_data'], $id); $this->insertLeadStatus($id, $data[0]['status'], 3); return $this->respond(['status' => true, 'lead_id' => $id, 'message' => "Lead updated successfully", 'data' => $data], 200); } return $this->respond(['status' => false, 'lead_id' => $id, 'message' => "Failed to update Lead", 'data' => $data], 200); } - // Get the Single Lead data for edit + // Get the Single Lead data for edit uisng ajax ( do not delete) public function getLeadDataForEdit($id) { @@ -472,6 +485,8 @@ class LeadsController extends BaseController $data['premium_date'] = null; } + $data['multi_file_data'] = $this->leadFilesModel->where('lead_id', $id)->first() ?? null; + $data['lastFiveYears'] = $this->getLastFiveFinancialYears(); $data['gpaClaimType'] = $this->claim_type_for_gpa; $data['causeOfDeath'] = $this->cause_of_death; @@ -485,6 +500,8 @@ class LeadsController extends BaseController $data['html'] = $this->generateViewPageHtml($data['policy_type_id'], $data) ?? ""; + // print_r($data); die; + if ($data) { return $this->respond(['status' => true, 'data' => $data], 200); } else { @@ -503,6 +520,77 @@ class LeadsController extends BaseController $this->policyTransactionStatusModel->insert($statusData); } + public function uploadMultiFiles($files, $docs_names, $primaryKey) + { + $uploadFilePath = WRITEPATH . 'uploads/lead_files/'; + + $multi_file_data = []; + foreach ($files as $index => $value) { + $file_name = file_Upload($value, $uploadFilePath); + $multi_file_data[] = [ + 'file_name' => $file_name, + 'docs_name' => $docs_names[$index], + 'id' => $primaryKey[$index] ?? "", + ]; + } + + return $multi_file_data; + } + + public function insertMultiFilesData($data, $lead_id) + { + // print_r($data); die; + + if(!empty($data)){ + foreach ($data as $key => $value) { + + if(!empty($value['id'])){ + + $lead_file_data = [ + 'lead_id' => $lead_id, + 'docs_name' => $value['docs_name'], + ]; + + if(!empty($value['file_name'])) { + $lead_file_data['file_name'] = $value['file_name']; + } + + $this->leadFilesModel->where('id', $value['id'])->set($lead_file_data)->update(); + + }else{ + + $lead_file_data = [ + 'lead_id' => $lead_id, + 'docs_name' => $value['docs_name'], + 'file_name' => $value['file_name'], + ]; + $this->leadFilesModel->insert($lead_file_data); + } + + if($key == 0 && !empty($value['file_name'])) { + $this->leadsModel->where('id', $lead_id)->set('file_name', $value['file_name'])->update(); + } + } + } + + return true; + } + + public function removeMultiFile() + { + $id = $this->request->getGet('lead_file_id'); + if(!empty($id)){ + $this->leadFilesModel->where('id', $id)->set(['is_active' => 0])->update(); + return $this->respond(['status' => true, 'message' => 'File removed successfully'], 200); + }else{ + return $this->respond(['status' => false, 'message' => 'File could not be removed.'], 200); + } + } + + public function updateLeadTableFields() + { + + } //--------RFQ----------------------------------------------------------------------------------------------- @@ -575,8 +663,11 @@ class LeadsController extends BaseController $data['mail_content'] = $this->transformMailContent($lead_data, $mail_content, $data['page_name']); $data['subject'] = $this->transformMailContent($lead_data, $subject, $data['page_name']); + $data['multi_file_data'] = $this->leadFilesModel->where('lead_id', $id)->where('is_active', 1)->findAll() ?? null; + $data['attachment_html'] = view('rfq/attachment_files', $data) ?? ""; + + // dd($data); - if ($data['lead_data']['lead_form_type'] == 1) { $this->loadLayout('view_rfq.php', $data); @@ -635,7 +726,6 @@ class LeadsController extends BaseController } } - public function createRFQ() { $data = $this->request->getPost(); @@ -691,7 +781,6 @@ class LeadsController extends BaseController ], 200); } - public function createQCR() { @@ -1693,6 +1782,7 @@ class LeadsController extends BaseController $propsal_and_insurer = isset($params['proposal_insurer']) ? $params['proposal_insurer'] : null; $mail_content = $params['mail_content']; $mail_subject = $params['subject']; + $attachment_file_ids = $params['selected_attachment_files']; $result_data = []; // dd($recipient_mail); @@ -1817,7 +1907,12 @@ class LeadsController extends BaseController $file_path = $result; $file_name = basename($result); + + // Attacments part $attachments = [['fileName' => $file_name, 'filePath' => $file_path]]; + $other_attachments = $this->handleMultiFileAttachments($attachment_file_ids, $lead_id); + $attachments = array_merge($attachments, $other_attachments); + // print_r($attachments); die; //get recipient address if ($recipient_type == 'insurer' || $recipient_type == 'placement') { @@ -2579,6 +2674,7 @@ class LeadsController extends BaseController $this->loadLayout('view_rfq_non_eb'); } + // get lead data for edit bot EB and NON-EB public function getLeadNonEB($type, $id = null) { // Set basic data @@ -2606,9 +2702,15 @@ class LeadsController extends BaseController ->where('user_profiles.is_active', 1) ->findAll(); + + if (!empty($id)) { + $data['lead_edit_data'] = $this->leadsModel->where('id', $id)->first() ?? []; + $data['lead_edit_data']['multi_file_data'] = $this->leadFilesModel->where('lead_id', $id)->where('is_active', 1)->findAll() ?? null; + $data['lead_edit_data']['lead_file_count'] = count($data['lead_edit_data']['multi_file_data']); + // Decode and merge custom fields if present $custom_fields_data = !empty($data['lead_edit_data']['custom_fields']) ? json_decode($data['lead_edit_data']['custom_fields'], true) @@ -2633,6 +2735,8 @@ class LeadsController extends BaseController $data['lead_edit_data']['policy_type_id'] ?? null, $data ) ?? ""; + + $data['lead_edit_data']['multi_file_html'] = view('rfq/multi_files', $data) ?? ""; } if ($data['lead_edit_data']['lead_type'] != 1 && $data['lead_edit_data']['lead_form_type'] == 2) { @@ -3477,19 +3581,34 @@ class LeadsController extends BaseController return $data; } - // function getPreviousColumn($columnLetter) - // { - // $colIndex = Coordinate::columnIndexFromString($columnLetter); - // if ($colIndex > 1) { - // $colIndex--; - // } - // return Coordinate::stringFromColumnIndex($colIndex); - // } - - function getPreviousColumn($columnLetter, $decrement = 1) { + public function getPreviousColumn($columnLetter, $decrement = 1) + { $colIndex = Coordinate::columnIndexFromString($columnLetter); $colIndex = max(1, $colIndex - $decrement); // ensure column index doesn't go below 1 return Coordinate::stringFromColumnIndex($colIndex); } + public function handleMultiFileAttachments($json_string, $lead_id) + { + $attachments = []; + + if (!empty($json_string)) { + $fileIds = json_decode($json_string, true); + $lead_file_path = WRITEPATH . 'uploads/lead_files/'; + + foreach ($fileIds as $id) { + $lead_file = $this->leadFilesModel->where('lead_id', $lead_id)->where('id', $id)->where('is_active', 1)->first(); + + if ($lead_file) { + $attachments[] = [ + 'fileName' => $lead_file['file_name'], + 'filePath' => $lead_file_path . $lead_file['file_name'] + ]; + } + } + } + + return $attachments; + } + } diff --git a/app/Models/LeadFilesModel.php b/app/Models/LeadFilesModel.php new file mode 100644 index 00000000..37db8e16 --- /dev/null +++ b/app/Models/LeadFilesModel.php @@ -0,0 +1,55 @@ +
    -
    - - - -
    - +
    +
    x + @@ -931,6 +927,8 @@ container.appendChild(newRow); + //append mutli file html + addFileField(increment); var lead_type = $('#lead_type').val(); leadTypeBsedHideAndShow(lead_type) @@ -1540,4 +1538,8 @@ } }); } + + //----------------------------------------------------------------------------------------------------------- + + \ No newline at end of file diff --git a/app/Views/leads_form_handler.php b/app/Views/leads_form_handler.php index 93a82b96..30bb0d02 100644 --- a/app/Views/leads_form_handler.php +++ b/app/Views/leads_form_handler.php @@ -86,6 +86,8 @@ if (isset($selected_lead_type)) { var temp_client_id = 0; var temp_branch_id = 0; var selected_lead_form_type = ; + var fileIndex = 1; // Initialize index + // select2 document ready $(document).ready(function() { @@ -327,6 +329,122 @@ if (isset($selected_lead_type)) { } + // -------------------------------------------------------------------------------------------------------- + + function addFileField(increment) { + + console.log('addFileField function called'); + + const container = document.getElementById(`multiFileAppendArea_${increment}`); + if (!container) return; + + const div = document.createElement("div"); + div.className = "form-row d-flex align-items-end"; + div.setAttribute("id", `fileField_${fileIndex}`); + + let isFirstField = container.childElementCount === 0; // Check if it's the first field + let placeholder = isFirstField ? 'First file must be Demography.' : ''; + let accept = isFirstField ? '.xls,.xlsx' : ''; + + div.innerHTML = ` +
    + + +
    +
    + + +
    +
    + + +
    + `; + container.appendChild(div); + fileIndex++; + } + + function removeFileField(index, lead_file_id = null) { + + if(index == 1){ + toastr.warning("You can't remove the first file field", 'WARNING'); + return false; + } + + if(lead_file_id != null) { + + Swal.fire({ + title: "Do you want to remove this file?", + // text: "Do you want Save this!", + icon: "warning", + showCancelButton: true, + confirmButtonColor: "#3085d6", + cancelButtonColor: "#d33", + confirmButtonText: "Yes, Procced!" + }).then((result) => { + + if (result.isConfirmed) { + + let url = ''; + + let requestData = { + lead_file_id: lead_file_id + }; + + $('.loader').fadeIn(); + $('.loader-mask').fadeIn(); + + // Send AJAX request + sendAjaxRequestForGlobal(url, 'GET', requestData, function(response) { + console.log('Data fetched successfully:', response); + + if (response.status == true) { + toastr.success(response.message, 'SUCCESS'); + + //remove the file field + const field = document.getElementById(`fileField_${index}`); + if(index != 1){ + if (field) field.remove(); + } + + } else { + toastr.error(response.message, 'WARNING'); + } + + $('.loader').fadeOut(); + $('.loader-mask').delay(350).fadeOut('slow'); + + }, function(xhr, status, error) { + $('.loader').fadeOut(); + $('.loader-mask').delay(350).fadeOut('slow'); + console.error('Error fetching data:', error); + console.error(xhr.responseText); + toastr.error('An error occurred while checking the CD amount.', 'ERROR'); + }); + + }else{ + return false; + } + + }); + + }else{ + const field = document.getElementById(`fileField_${index}`); + if(index != 1){ + if (field) field.remove(); + } + } + + } + + function showFileName(input, index) { + if (input.files.length > 0) { + document.getElementById(`file_name_display_${index}`).textContent = input.files[0].name; + } else { + document.getElementById(`file_name_display_${index}`).textContent = "No file chosen"; + } + } + @@ -337,7 +455,7 @@ if (isset($selected_lead_type)) { setTimeout(function(){ handleEbAndNonEbEdit( ); - }, 1000) + }, 2000) function handleEbAndNonEbEdit(data){ if(data.lead_form_type == 1){ @@ -353,6 +471,7 @@ if (isset($selected_lead_type)) { console.log('Received data:', data); let dataIncrement = 1; + fileIndex = data.lead_file_count + 1; if (!data || typeof data !== 'object') { console.error('Invalid data received for editing.'); @@ -361,6 +480,7 @@ if (isset($selected_lead_type)) { $('.btnDiv').hide(); $('#appendArea_' + dataIncrement).empty(); + $('#multiFileAppendArea_' + dataIncrement).empty(); if (data.html) { $('#appendArea_' + dataIncrement).append(data.html); @@ -368,6 +488,15 @@ if (isset($selected_lead_type)) { console.warn('HTML content missing in data.'); } + if (data.multi_file_html) { + console.log(data.multi_file_html); + setTimeout(function(){ + $('#multiFileAppendArea_' + dataIncrement).append(data.multi_file_html); + }, 2000) + } else { + console.warn('MULTI FILE HTML content missing in data.'); + } + let policy_type_id = data.policy_type_id || null; let lead_type = data.lead_type || null; @@ -498,6 +627,7 @@ if (isset($selected_lead_type)) { console.log('########### THIS IS NON EB LEAD ###############') console.log('Received data:', data); let dataIncrement = 1; + fileIndex = data.lead_file_count + 1; if (!data || typeof data !== 'object') { console.error('Invalid data received for editing.'); @@ -505,6 +635,8 @@ if (isset($selected_lead_type)) { } $('#appendArea').empty(); + $('#multiFileAppendArea_' + dataIncrement).empty(); + if (data.html) { $('#appendArea').append(data.html); @@ -512,6 +644,15 @@ if (isset($selected_lead_type)) { console.warn('HTML content missing in data.'); } + if (data.multi_file_html) { + console.log(data.multi_file_html); + setTimeout(function(){ + $('#multiFileAppendArea_' + dataIncrement).append(data.multi_file_html); + }, 2000) + } else { + console.warn('MULTI FILE HTML content missing in data.'); + } + let policy_type_id = data.policy_type_id || null; let lead_type = data.lead_type || null; diff --git a/app/Views/leads_non_eb.php b/app/Views/leads_non_eb.php index 1ee910fa..fef3f394 100644 --- a/app/Views/leads_non_eb.php +++ b/app/Views/leads_non_eb.php @@ -290,14 +290,18 @@ hr.solid {
    +
    + +
    +
    -
    +
    @@ -370,6 +374,8 @@ $(document).ready(function(){ dateFormat: "d/m/Y", allowInput: false }); + + addFileField(1); }) function getPolicyTypeFields(input) { diff --git a/app/Views/rfq/attachment_files.php b/app/Views/rfq/attachment_files.php new file mode 100644 index 00000000..711fbe84 --- /dev/null +++ b/app/Views/rfq/attachment_files.php @@ -0,0 +1,14 @@ + +
    + + +
    + + + +
    + +
    + diff --git a/app/Views/rfq/multi_files.php b/app/Views/rfq/multi_files.php new file mode 100644 index 00000000..a071172b --- /dev/null +++ b/app/Views/rfq/multi_files.php @@ -0,0 +1,50 @@ + + + $value) { + $isFirstField = ($index === 0); // First file must be Demography + $placeholder = $isFirstField ? 'First file must be Demography.' : ''; + $accept = $isFirstField ? '.xls,.xlsx' : ''; + $index = $index + 1; +?> + +
    + + + + +
    + + +
    + + +
    + + + +
    + + + +
    + + +
    +
    + + \ No newline at end of file diff --git a/app/Views/view_rfq.php b/app/Views/view_rfq.php index 3922cdf6..950e9b45 100644 --- a/app/Views/view_rfq.php +++ b/app/Views/view_rfq.php @@ -373,6 +373,16 @@
    + +
    +

    Attachments Files

    +
    + +
    +
    + +
    +
    @@ -394,47 +404,58 @@ -
    + +
    +

    Attachments Files

    +
    + +
    +
    + +
    +
    + +
    +
    @@ -535,6 +556,16 @@
    +
    +

    Attachments Files

    +
    + +
    +
    + +
    +
    +
    @@ -557,6 +588,7 @@ var premium_data_check = false; var user_role_id = ; var jsonDataForHide = null; + var multi_file_data = []; const editorConfig = { buttons: [ @@ -595,7 +627,8 @@ console.log('Type:', type); let titile_client_name = ""; - + multi_file_data = ; + appendMultiFileData(multi_file_data) RFQ_or_QCR = type; var type_for_url = 1; @@ -3452,6 +3485,11 @@ function constructURL_ForInsurerAndClientMailSend() { bcc = bcc.map(Number); bcc = JSON.stringify(bcc); + var selectedFiles = []; + $('#insurer_or_clinet_mail_attachment .multi_file_attachment:checked').each(function () { + selectedFiles.push($(this).val()); + }); + // Prepare FormData object var formData = new FormData(); formData.append('lead_id', lead_id); @@ -3459,6 +3497,8 @@ function constructURL_ForInsurerAndClientMailSend() { formData.append('subject', subject); formData.append('cc', cc); formData.append('bcc', bcc); + formData.append('selected_attachment_files', JSON.stringify(selectedFiles)); + if (RFQ_or_QCR == 2) { formData.append('file_type', 'qcr'); @@ -3493,6 +3533,11 @@ function constructURL_ForInternalMailSend() { // Determine file type var file_type = RFQ_or_QCR == 2 ? 'qcr' : 'rfq'; + var selectedFiles = []; + $('#internal_mail_attachment .multi_file_attachment:checked').each(function () { + selectedFiles.push($(this).val()); + }); + // Create FormData var formData = new FormData(); formData.append('lead_id', lead_id); @@ -3503,6 +3548,7 @@ function constructURL_ForInternalMailSend() { formData.append('subject', subject); formData.append('mail_content', mail_content); formData.append('recipient_mail', ''); // Empty value as per logic + formData.append('selected_attachment_files', JSON.stringify(selectedFiles)); ajaxRequest(formData) @@ -3528,6 +3574,11 @@ function constructURL_ForPlacementMailSend() { to = to.split(',').map(email => email.trim()); cc = cc.map(Number); // or split if it's a string: `cc.split(',').map(email => email.trim())` + var selectedFiles = []; + $('#placement_mail_attachment .multi_file_attachment:checked').each(function () { + selectedFiles.push($(this).val()); + }); + // Prepare FormData var formData = new FormData(); formData.append('lead_id', lead_id); @@ -3544,6 +3595,8 @@ function constructURL_ForPlacementMailSend() { formData.append('total_amount', total_amount); formData.append('cd_amount', cd_amount); formData.append('mail_content', mail_content); + formData.append('selected_attachment_files', JSON.stringify(selectedFiles)); + ajaxRequest(formData); @@ -5157,6 +5210,11 @@ function autoCaluculationForPremiumChildTable(input) { } +function appendMultiFileData(data) { + + console.log('appendMultiFileData function called'); + console.log(data) +} diff --git a/app/Views/view_rfq_non_eb.php b/app/Views/view_rfq_non_eb.php index 6a182769..5f9aba17 100644 --- a/app/Views/view_rfq_non_eb.php +++ b/app/Views/view_rfq_non_eb.php @@ -309,11 +309,22 @@
    +
    +

    Attachments Files

    +
    + +
    +
    + +
    +
    +
    @@ -475,6 +496,16 @@
    +
    +

    Attachments Files

    +
    + +
    +
    + +
    +
    +
    @@ -4550,6 +4581,11 @@ bcc = bcc.map(Number); bcc = JSON.stringify(bcc); + var selectedFiles = []; + $('#insurer_or_clinet_mail_attachment .multi_file_attachment:checked').each(function () { + selectedFiles.push($(this).val()); + }); + // Prepare FormData object var formData = new FormData(); formData.append('lead_id', lead_id); @@ -4557,6 +4593,8 @@ formData.append('subject', subject); formData.append('cc', cc); formData.append('bcc', bcc); + formData.append('selected_attachment_files', JSON.stringify(selectedFiles)); + if (rfq_or_qcr == 2) { formData.append('file_type', 'qcr'); @@ -4591,6 +4629,12 @@ // Determine file type var file_type = rfq_or_qcr == 2 ? 'qcr' : 'rfq'; + var selectedFiles = []; + $('#internal_mail_attachment .multi_file_attachment:checked').each(function () { + selectedFiles.push($(this).val()); + }); + + // Create FormData var formData = new FormData(); formData.append('lead_id', lead_id); @@ -4601,6 +4645,8 @@ formData.append('subject', subject); formData.append('mail_content', mail_content); formData.append('recipient_mail', ''); // Empty value as per logic + formData.append('selected_attachment_files', JSON.stringify(selectedFiles)); + ajaxRequest(formData) @@ -4626,6 +4672,13 @@ to = to.split(',').map(email => email.trim()); cc = cc.map(Number); // or split if it's a string: `cc.split(',').map(email => email.trim())` + + var selectedFiles = []; + $('#placement_mail_attachment .multi_file_attachment:checked').each(function () { + selectedFiles.push($(this).val()); + }); + + // Prepare FormData var formData = new FormData(); formData.append('lead_id', lead_id); @@ -4642,11 +4695,14 @@ formData.append('total_amount', total_amount); formData.append('cd_amount', cd_amount); formData.append('mail_content', mail_content); + formData.append('selected_attachment_files', JSON.stringify(selectedFiles)); + ajaxRequest(formData); } + function ajaxRequest(formData) { var apiURL = ''; From c928f238ef8fc89d5e4786d64a7a9d4740bad223 Mon Sep 17 00:00:00 2001 From: "venkatesh.r" Date: Sat, 5 Apr 2025 11:44:45 +0530 Subject: [PATCH 40/52] FIX_ALIGNMENT_IN_EXCEL : RV --- app/Controllers/LeadsController.php | 23 ++++++++++++----------- app/Views/leads_form_handler.php | 5 +++-- 2 files changed, 15 insertions(+), 13 deletions(-) diff --git a/app/Controllers/LeadsController.php b/app/Controllers/LeadsController.php index 02134611..c432c921 100644 --- a/app/Controllers/LeadsController.php +++ b/app/Controllers/LeadsController.php @@ -966,7 +966,7 @@ class LeadsController extends BaseController // Start with lead_data at the top $rowNumber = 1; - $mergeRange1 = "A{$rowNumber}:C{$rowNumber}"; + $mergeRange1 = "A{$rowNumber}:B{$rowNumber}"; $sheet->mergeCells($mergeRange1); $sheet->setCellValue("A{$rowNumber}", "Nhance India Insurance Broking Pvt Ltd"); $sheet->getStyle("A{$rowNumber}")->applyFromArray([ @@ -981,13 +981,13 @@ class LeadsController extends BaseController ]); // Set column width to fit the image properly - $sheet->getColumnDimension('D')->setWidth(20); // Adjust as needed + $sheet->getColumnDimension('C')->setWidth(20); // Adjust as needed $sheet->getRowDimension($rowNumber)->setRowHeight(40); // Adjust as needed $drawing = new Drawing(); $path = ROOTPATH . "public/assets/images/Nhance-Logo-Final.png"; // Use FCPATH for server path $drawing->setPath($path); - $drawing->setCoordinates("D{$rowNumber}"); // Set position in column B + $drawing->setCoordinates("C{$rowNumber}"); // Set position in column B $drawing->setHeight(35); // Adjust image height // Center align the image in the cell @@ -997,8 +997,8 @@ class LeadsController extends BaseController $drawing->setWorksheet($sheet); // Apply center alignment to the cell - $sheet->getStyle("D{$rowNumber}")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER); - $sheet->getStyle("D{$rowNumber}")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER); + $sheet->getStyle("C{$rowNumber}")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER); + $sheet->getStyle("C{$rowNumber}")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER); $rowNumber = $rowNumber + 1; @@ -1011,7 +1011,7 @@ class LeadsController extends BaseController // Merge A:B for key and C:D for value $mergeRangeKey = "A{$rowNumber}:B{$rowNumber}"; - $mergeRangeValue = "C{$rowNumber}:D{$rowNumber}"; + $mergeRangeValue = "C{$rowNumber}"; $sheet->mergeCells($mergeRangeKey); $sheet->mergeCells($mergeRangeValue); @@ -1044,9 +1044,9 @@ class LeadsController extends BaseController // Set column width based on max content length (adjusted for padding) $sheet->getColumnDimension('A')->setWidth($maxWidthA * 1.2); - $sheet->getColumnDimension('B')->setWidth($maxWidthA * 1.2); + $sheet->getColumnDimension('B')->setWidth($maxWidthA * 5); $sheet->getColumnDimension('C')->setWidth($maxWidthB * 1.2); - $sheet->getColumnDimension('D')->setWidth($maxWidthB * 1.2); + // $sheet->getColumnDimension('D')->setWidth($maxWidthB * 1.2); // $rowNumber += 2; @@ -1105,7 +1105,7 @@ class LeadsController extends BaseController } if ($header['parentHeader'] === 'Particulars') { - $sheet->getColumnDimension('B')->setWidth(40); + $sheet->getColumnDimension('B')->setWidth(80); } $startColumn = $columnLetter; // Start of the current header range @@ -1289,7 +1289,7 @@ class LeadsController extends BaseController } $lastRow = count($lead_data) + 1; - $leadRange = "A1:D{$lastRow}"; + $leadRange = "A1:C{$lastRow}"; $sheet->getStyle($leadRange)->applyFromArray([ 'borders' => [ @@ -2736,7 +2736,8 @@ class LeadsController extends BaseController $data ) ?? ""; - $data['lead_edit_data']['multi_file_html'] = view('rfq/multi_files', $data) ?? ""; + $html = view('rfq/multi_files', $data); + $data['lead_edit_data']['multi_file_html'] = trim($html) !== '' ? $html : null; } if ($data['lead_edit_data']['lead_type'] != 1 && $data['lead_edit_data']['lead_form_type'] == 2) { diff --git a/app/Views/leads_form_handler.php b/app/Views/leads_form_handler.php index 30bb0d02..fdf3de07 100644 --- a/app/Views/leads_form_handler.php +++ b/app/Views/leads_form_handler.php @@ -480,7 +480,7 @@ if (isset($selected_lead_type)) { $('.btnDiv').hide(); $('#appendArea_' + dataIncrement).empty(); - $('#multiFileAppendArea_' + dataIncrement).empty(); + if (data.html) { $('#appendArea_' + dataIncrement).append(data.html); @@ -488,7 +488,8 @@ if (isset($selected_lead_type)) { console.warn('HTML content missing in data.'); } - if (data.multi_file_html) { + if (data.multi_file_html && data.multi_file_html != '') { + $('#multiFileAppendArea_' + dataIncrement).empty(); console.log(data.multi_file_html); setTimeout(function(){ $('#multiFileAppendArea_' + dataIncrement).append(data.multi_file_html); From 374b382bfac110172b82c58c18dffb1aa2a51e6d Mon Sep 17 00:00:00 2001 From: "venkatesh.r" Date: Sat, 5 Apr 2025 17:17:08 +0530 Subject: [PATCH 41/52] FIX_USER_NAME_NULL : RV --- app/Controllers/TicketController.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/app/Controllers/TicketController.php b/app/Controllers/TicketController.php index ec574927..03224684 100644 --- a/app/Controllers/TicketController.php +++ b/app/Controllers/TicketController.php @@ -1034,7 +1034,7 @@ class TicketController extends BaseController th.old_value, th.new_value, th.created_at, - CONCAT(creator.first_name, ' ', creator.last_name) as modified_by, + CONCAT_WS(' ', creator.first_name, creator.last_name) AS modified_by, -- Claim Status old_status.claim_status as old_status_value, new_status.claim_status as new_status_value, @@ -1094,6 +1094,7 @@ class TicketController extends BaseController ORDER BY th.created_at DESC"; $data = $this->ticketHistoryModel->query($sql)->getResultArray(); + // dd(db_connect()->getLastQuery()); $priorityType = $this->priorityType; $relationshipType = $this->relationshipType; $modeOFIntimate = $this->modeOFIntimate; From dfe04f5539a67ae6df2daa7560eff58e3e781fba Mon Sep 17 00:00:00 2001 From: "venkatesh.r" Date: Sat, 5 Apr 2025 17:31:54 +0530 Subject: [PATCH 42/52] FIX_USER_NAME : RV --- app/Views/ticket_history.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/Views/ticket_history.php b/app/Views/ticket_history.php index c0e5bfea..b181408c 100644 --- a/app/Views/ticket_history.php +++ b/app/Views/ticket_history.php @@ -20,7 +20,7 @@ '.$row['new_value']; ?> - + From dffc1a8508f80f4088c1d08c82c3caf85915a3fa Mon Sep 17 00:00:00 2001 From: "venkatesh.r" Date: Sun, 6 Apr 2025 09:55:01 +0530 Subject: [PATCH 43/52] FIX_CLAIM_API_DATE_ISSUE_AND_USER_LOGIN_NAME_SHOWING_ISSUE : RV --- app/Controllers/EmployeeRestController.php | 12 ++++++++++++ app/Controllers/TicketController.php | 17 ++++++++++++----- app/Views/ticket_conversation.php | 2 +- 3 files changed, 25 insertions(+), 6 deletions(-) diff --git a/app/Controllers/EmployeeRestController.php b/app/Controllers/EmployeeRestController.php index e86f5de7..199505a7 100755 --- a/app/Controllers/EmployeeRestController.php +++ b/app/Controllers/EmployeeRestController.php @@ -3124,6 +3124,18 @@ class EmployeeRestController extends AdminController $client_policy_id = $received_data['client_policy_id']; $insured_emp_id = $received_data['insured_emp_id']; + if (empty($received_data['doa'])) { + $received_data['doa'] = null; + } else{ + $ticket_data['doa'] = change_date_format($received_data['doa']); + } + + if (empty($received_data['dod'])) { + $received_data['dod'] = null; + } else{ + $ticket_data['dod'] = change_date_format($received_data['dod']); + } + $sql = " select cp.policy_type_id, diff --git a/app/Controllers/TicketController.php b/app/Controllers/TicketController.php index 03224684..f6999bdf 100644 --- a/app/Controllers/TicketController.php +++ b/app/Controllers/TicketController.php @@ -774,13 +774,20 @@ class TicketController extends BaseController { // log_message('error','Function called');die(); // $ticket_master_id = $this->request->getPost('id'); - $user_id = get_session_userid(); - $logged_user = $this->userModel->select('first_name,last_name,profile')->where('id', $user_id)->first(); $dataToSend = []; - $dataToSend['user_name'] = $logged_user['first_name'] . ' ' . $logged_user['last_name']; - $dataToSend['messages'] = $this->ticketMessageModel->where('is_active', 1) - ->where('ticket_id', $ticket_master_id)->orderBy('created_at', 'DESC') + + $user_id = get_session_userid(); + // $logged_user = $this->userModel->select('first_name,last_name,profile')->where('id', $user_id)->first(); + // $dataToSend['user_name'] = $logged_user['first_name'] . ' ' . $logged_user['last_name']; + + $dataToSend['messages'] = $this->ticketMessageModel + ->select('ticket_messages.*,up.first_name as user_name') + ->join('user_profiles up', 'up.id = ticket_messages.created_by', 'left') + ->where('ticket_messages.is_active', 1) + ->where('ticket_messages.ticket_id', $ticket_master_id) + ->orderBy('ticket_messages.created_at', 'DESC') ->findAll(); + foreach ($dataToSend['messages'] as $message) { $mail_content_converted = $this->convertHtmlToText($message['mail_content']); $message['mail_content'] = $mail_content_converted; diff --git a/app/Views/ticket_conversation.php b/app/Views/ticket_conversation.php index e0e67c6a..d2fa00c3 100644 --- a/app/Views/ticket_conversation.php +++ b/app/Views/ticket_conversation.php @@ -49,7 +49,7 @@
    -
    +
    Staff From e67f49fc5d4c992b31d5c60be9cd19d4bc0a915a Mon Sep 17 00:00:00 2001 From: "venkatesh.r" Date: Mon, 7 Apr 2025 09:40:27 +0530 Subject: [PATCH 44/52] CHANGE_CLAIMS_INITIATECLAIM_API_CHANGES : RV --- app/Controllers/EmployeeRestController.php | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/app/Controllers/EmployeeRestController.php b/app/Controllers/EmployeeRestController.php index 199505a7..9b137fda 100755 --- a/app/Controllers/EmployeeRestController.php +++ b/app/Controllers/EmployeeRestController.php @@ -3178,11 +3178,19 @@ class EmployeeRestController extends AdminController if(!empty($emp_ticket_data)){ $fetchData = $emp_ticket_data[0]; - $fetchData['claim_status_id'] = $this->claimStatusModel - ->select('id') - ->where('ticket_type', $fetchData['ticket_type_id']) - ->orderBy('id', 'asc') - ->first()['id']; + + $claimStatusQuery = $this->claimStatusModel + ->select('id') + ->where('ticket_type', $fetchData['ticket_type_id']) + ->orderBy('id', 'asc'); + + if ($fetchData['ticket_type_id'] == 1 && !empty($fetchData['tpa_no'])) { + $results = $claimStatusQuery->findAll(2); + $fetchData['claim_status_id'] = $results[1]['id'] ?? $results[0]['id']; + } else { + $fetchData['claim_status_id'] = $claimStatusQuery->first()['id']; + } + $fetchData['priority'] = 1; $fetchData['mode_of_intimation'] = 3; From cad50efdf2eaae6b48920f18c6390faa61c74f9c Mon Sep 17 00:00:00 2001 From: Srinivas-Saravanan Date: Tue, 8 Apr 2025 14:08:54 +0530 Subject: [PATCH 45/52] FEAT_RFQ_NEW_REQ_SRI --- .../Chatbot/EcardDownloadConversation.php | 2 + .../Chatbot/MainMenuConversation.php | 11 +- app/Controllers/ChatbotControllerNew.php | 2 + app/Controllers/LeadsController.php | 69 ++- app/Models/LeadsModel.php | 2 + app/Models/UserModel.php | 15 + app/Views/chatbot.php | 2 +- app/Views/layout/header.php | 3 + app/Views/view_rfq.php | 392 +++++++++++++----- 9 files changed, 384 insertions(+), 114 deletions(-) diff --git a/app/Controllers/Chatbot/EcardDownloadConversation.php b/app/Controllers/Chatbot/EcardDownloadConversation.php index 84617af1..c38d6977 100644 --- a/app/Controllers/Chatbot/EcardDownloadConversation.php +++ b/app/Controllers/Chatbot/EcardDownloadConversation.php @@ -23,6 +23,8 @@ class EcardDownloadConversation extends Conversation $policy_list = ChatbotHelper::getListOfPolicies($chat_session_info); $buttons = []; $question = 'Choose Policy to Download Ecard:'; + log_message('error', ('policy_list : ' . json_encode($policy_list))); + if(is_array($policy_list) && count($policy_list)) { foreach($policy_list as $policy) diff --git a/app/Controllers/Chatbot/MainMenuConversation.php b/app/Controllers/Chatbot/MainMenuConversation.php index 875ecba4..f06fd078 100644 --- a/app/Controllers/Chatbot/MainMenuConversation.php +++ b/app/Controllers/Chatbot/MainMenuConversation.php @@ -53,6 +53,8 @@ class MainMenuConversation extends Conversation $user_reponse = null; } + log_message('error', ('user_reponse is interactive: ' . $answer->isInteractiveMessageReply())); + // Get just the existing path array $path = $this->bot->userStorage()->get('path') ?? []; @@ -65,28 +67,35 @@ class MainMenuConversation extends Conversation 'path' => $path ]); - log_message('error', ('user_reponse : ' . $user_reponse)); + log_message('error', ('user_reponse after: ' . $user_reponse)); switch ($user_reponse) { case "ecard_download": $this->bot->startConversation(new EcardDownloadConversation()); + log_message('error', 'ecard_download clicked '); + break; case "network_hospital": $this->bot->startConversation(new NetworkHospitalConversation()); + log_message('error', 'network_hospital clicked '); break; case "reimbursement_claim": $this->bot->startConversation(new ReimbursementClaimProcessConversation()); + log_message('error', 'reimbursement_claim clicked '); break; case "reimbursement_status": $this->bot->startConversation(new ReimbursementClaimStatusConversation()); + log_message('error', 'reimbursement_status clicked '); break; case "new_policy": case "renew_policy": $this->bot->startConversation(new policyConversation()); + log_message('error', 'renew_policy || new_policy clicked '); break; default: + log_message('error', 'default shown '); $this->say("Invalid selection. Please choose an option."); $this->bot->startConversation(new MainMenuConversation()); break; diff --git a/app/Controllers/ChatbotControllerNew.php b/app/Controllers/ChatbotControllerNew.php index 2f6ca404..dc38a3c9 100644 --- a/app/Controllers/ChatbotControllerNew.php +++ b/app/Controllers/ChatbotControllerNew.php @@ -84,6 +84,7 @@ class ChatbotControllerNew extends BaseController public function index() { + if($this->session->get('CHATBOT_RANDOM_USER_ID') == '-' || $this->session->get('CHATBOT_RANDOM_USER_ID') == '') { @@ -100,6 +101,7 @@ class ChatbotControllerNew extends BaseController } $this->botman->hears('.*', function ($bot) { + log_message("error","Inside Bot Type Function"); $bot->types(); // Typing indicator for the first message sleep(0.5); // Delay diff --git a/app/Controllers/LeadsController.php b/app/Controllers/LeadsController.php index c432c921..c5854a06 100644 --- a/app/Controllers/LeadsController.php +++ b/app/Controllers/LeadsController.php @@ -40,6 +40,7 @@ use Kint\Kint; use App\Controllers\Jobs; use App\Controllers\JobWorker; use Google\Service\FactCheckTools\Resource\Claims; +use GPBMetadata\Google\Type\Datetime; class LeadsController extends BaseController { @@ -646,6 +647,7 @@ class LeadsController extends BaseController $data['page_name'] = $type == 2 ? 'QCR' : 'RFQ'; $data['insurer'] = $this->insurerBranchModel->getInsurerBranchesWithInsurerNames(); $data['userList'] = $this->userModel->getUserListForRFQ(); + $data['exclusiveUserList'] = $this->userModel->getexclusiveUserListForRFQ(); $data['lead_data'] = $lead_data; $mail_content = " @@ -654,18 +656,32 @@ class LeadsController extends BaseController

    Please find attached the {{RFQ_OR_QCR}} for {{POLICY_TYPE}} policy pertaining to {{CLIENT_NAME}}.

    Kindly request you to share the competitive quotes at the earliest.

    In case of any query, please feel free to contact us.

    -

    Thank You!

    +

    Thank You!


    +

    Best regards,

    + +
    +
    {{LOGGED_USER_NAME}}
    +
    Email: {{LOGGED_USER_EMAIL}}
    +
    Mobile: {{LOGGED_USER_MOBILE}}
    +
    + + + "; + if ($data['lead_data']['policy_end_date'] != null){ + $subject = "{{CLIENT_NAME}} _ {{POLICY_TYPE}} _ {{RFQ_OR_QCR}} _ {{POLICY_YEAR}} {{POLICY_END_DATE}}"; + }else{ + $subject = "{{CLIENT_NAME}} _ {{POLICY_TYPE}} _ {{RFQ_OR_QCR}} _ {{POLICY_YEAR}}"; - $subject = "{{CLIENT_NAME}} _ {{POLICY_TYPE}} _ {{RFQ_OR_QCR}} _ {{POLICY_YEAR}}"; + } $data['mail_content'] = $this->transformMailContent($lead_data, $mail_content, $data['page_name']); $data['subject'] = $this->transformMailContent($lead_data, $subject, $data['page_name']); $data['multi_file_data'] = $this->leadFilesModel->where('lead_id', $id)->where('is_active', 1)->findAll() ?? null; $data['attachment_html'] = view('rfq/attachment_files', $data) ?? ""; - + $data['user_team'] = $this->userModel->select("ut.team_id")->join("user_teams ut","ut.user_id = user_profiles.id and ut.is_active = 1")->where("user_profiles.is_active",1)->first()['team_id']; // dd($data); if ($data['lead_data']['lead_form_type'] == 1) { @@ -880,7 +896,7 @@ class LeadsController extends BaseController if ($rfq_data['policy_type_id'] == 2) { $lead_data = [ - + 'policy_end_date' => $rfq_data['policy_end_date'], 'Insured' => $rfq_data['client_name'], 'Policy Status' => $rfq_data['status'], @@ -893,6 +909,7 @@ class LeadsController extends BaseController ]; } else if ($rfq_data['policy_type_id'] == 1) { $lead_data = [ + 'policy_end_date' => $rfq_data['policy_end_date'], 'Insured' => $rfq_data['client_name'], 'No of Employees at Inception' => $rfq_data['incept_emp_count'], 'Total Sum Insured at Inception ' => $rfq_data['total_si_at_incept'], @@ -905,6 +922,7 @@ class LeadsController extends BaseController } else { if ($rfq_data['policy_type_id'] == 2) { $lead_data = [ + 'policy_end_date' => $rfq_data['policy_end_date'], 'Insured' => $rfq_data['client_name'], 'Policy Status' => $rfq_data['status'], @@ -933,6 +951,7 @@ class LeadsController extends BaseController ]; } else if ($rfq_data['policy_type_id'] == 1) { $lead_data = [ + 'policy_end_date' => $rfq_data['policy_end_date'], 'Insured' => $rfq_data['client_name'], 'No of Employees at Renewal' => $rfq_data['renewal_emp_count'], 'Total Sum Insured at Renewal ' => $rfq_data['total_si_at_renewal'], @@ -1300,9 +1319,25 @@ class LeadsController extends BaseController ], ]); + + // Set filename $string = ($type == 2) ? 'QCR' : 'RFQ'; - $filename = "{$string}_{$rfq_data['client_short_name']}_{$rfq_data['policy_type']}_" . date('YmdHis') . '.xlsx'; + $current_year = date('Y'); + $next_year = $current_year + 1; + $policy_year = "$current_year-$next_year"; + + if (!empty($rfq_data['policy_end_date'])){ + $policy_expiry = strtotime($lead_data['policy_end_date']); + + $formatted_policy = date("d-m-Y",$policy_expiry); + + $filename = "{$rfq_data['client_name']}_{$rfq_data['policy_type']}_{$string}_" .$policy_year.'(Due On '.$formatted_policy . ')' .'.xlsx'; + + }else{ + $filename = "{$rfq_data['client_name']}_{$rfq_data['policy_type']}_{$string}_".$policy_year.'_' . '.xlsx'; + } + // Save to temporary location $uploadFilePath = WRITEPATH . 'tmp/' . $filename; @@ -1927,13 +1962,20 @@ class LeadsController extends BaseController // print_r($recipient_data); die; } else if ($recipient_type == 'client') { - $recipient_data = [['name' => $lead_data['contact_person_name'], 'email' => $lead_data['contact_person_email']]]; + + $mailIDS = explode(',',$params['contact_mail']); + $recipient_data = []; + foreach ($mailIDS as $mail){ + $recipient_data[] = ['name' => $lead_data['contact_person_name'], 'email' => $mail]; + } + } else { $recipient_data = [['name' => "Team", 'email' => $params['to']]]; } // print_r($recipient_data); die; $subject = $file_type == 'rfq' ? 'Request for Quotation from ' . $lead_data['client_name'] . ' for ' . $lead_data['policy_type'] : 'Quotation Comparison Report for ' . $lead_data['policy_type']; + $original_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

    © Nhance India Pvt Ltd. All rights reserved.

    '; //for mail content @@ -1982,7 +2024,9 @@ class LeadsController extends BaseController 'proposel_data' => json_encode($lead_update_data), 'status' => 'won', 'placement_date' => change_date_format($params['placement_date'], 'd/m/Y', 'Y-m-d'), + 'payment_date' => change_date_format($params['payment_date'], 'd/m/Y', 'Y-m-d'), 'utr_no' => $params['utr_no'], + 'is_cd' => $params['is_cd'], 'premium_amount' => $params['premium_amount'], 'total_amount' => $params['total_amount'], 'cd_amount' => $params['cd_amount'], @@ -2629,6 +2673,13 @@ class LeadsController extends BaseController $next_year = $current_year + 1; $policy_year = "$current_year-$next_year"; + $policy_expiry = strtotime($lead_data['policy_end_date']); + + $formatted_policy = date("d-m-Y",$policy_expiry); + $logged_user_id = get_session_userid(); + + $logged_user_data = $this->userModel->where("id",$logged_user_id)->where("is_active",1)->first(); + if ($lead_data) { // Replacing placeholders with actual values @@ -2638,6 +2689,11 @@ class LeadsController extends BaseController $message = str_replace("{{POLICY_TYPE}}", $lead_data['policy_type'] ?? "Insurance Policy", $message); $message = str_replace("{{RFQ_OR_QCR}}", $page_name, $message); $message = str_replace("{{POLICY_YEAR}}", $policy_year, $message); + $message = str_replace("{{POLICY_END_DATE}}"," (Due On ".$formatted_policy.")",$message); + + $message = str_replace("{{LOGGED_USER_NAME}}",ucfirst($logged_user_data['first_name'])." ".ucfirst($logged_user_data['last_name']),$message); + $message = str_replace("{{LOGGED_USER_EMAIL}}",$logged_user_data['email'],$message); + $message = str_replace("{{LOGGED_USER_MOBILE}}",$logged_user_data['mobile'],$message); return $message; } else { @@ -2645,6 +2701,7 @@ class LeadsController extends BaseController } } + function getLastFiveFinancialYears() { $currentYear = date('Y'); diff --git a/app/Models/LeadsModel.php b/app/Models/LeadsModel.php index 84e9c9bf..c2ae9492 100644 --- a/app/Models/LeadsModel.php +++ b/app/Models/LeadsModel.php @@ -87,6 +87,8 @@ class LeadsModel extends Model 'lead_form_type', 'custom_fields', + 'payment_date', + 'is_cd' ]; diff --git a/app/Models/UserModel.php b/app/Models/UserModel.php index 49b84400..ed5a8ace 100755 --- a/app/Models/UserModel.php +++ b/app/Models/UserModel.php @@ -134,5 +134,20 @@ class UserModel extends Model ->getResultArray(); } + public function getexclusiveUserListForRFQ(){ + $data = $this->db->table('user_profiles') + ->select('user_profiles.*,user_teams.team_id') + ->select('roles.role as user_role') + ->join('roles', 'roles.id = user_profiles.role') + ->join('user_teams', 'user_teams.user_id = user_profiles.id') + ->get() + ->getResultArray(); + + + // dd($data); + + return $data; + } + } ?> \ No newline at end of file diff --git a/app/Views/chatbot.php b/app/Views/chatbot.php index 94373196..95bf5cde 100644 --- a/app/Views/chatbot.php +++ b/app/Views/chatbot.php @@ -41,7 +41,7 @@ origin: "mobile", // origin emp_code:"HTL-007", client_id:159, - client_branch_id:125 + client_branch_id:126 } }; diff --git a/app/Views/layout/header.php b/app/Views/layout/header.php index f7ccabb4..8db290b2 100755 --- a/app/Views/layout/header.php +++ b/app/Views/layout/header.php @@ -80,6 +80,9 @@ + + + diff --git a/app/Views/view_rfq.php b/app/Views/view_rfq.php index 950e9b45..adc432b8 100644 --- a/app/Views/view_rfq.php +++ b/app/Views/view_rfq.php @@ -225,12 +225,15 @@ - +       Export Excel - + + + @@ -421,12 +424,15 @@
    @@ -484,30 +490,45 @@
    +
    + + "> +
    +
    - + ">
    - + "> +
    + +
    + + + >
    - + "> +
    + + + +
    + + ">
    - + ">
    -
    - - -
    +

    @@ -530,12 +551,15 @@
    @@ -797,6 +821,11 @@ allowInput: false, }); + var payment_date_datePicker = flatpickr("#payment_date", { + dateFormat: "d/m/Y", + allowInput: false, + }); + }) @@ -830,6 +859,24 @@ var over_all_column_data = { 'insurers': [] } }; +document.addEventListener('DOMContentLoaded', function () { + const textarea = document.getElementById('placement_mail_content'); + const textarea2 = document.getElementById("placement_subject"); + + if (textarea) { + let content = textarea.value; + if (content.includes('QCR')) { + textarea.value = content.replace(/QCR/g, 'Placement'); + } + } + + if (textarea2){ + let content = textarea2.value; + if (content.includes('QCR')) { + textarea2.value = content.replace(/QCR/g, 'Placement'); + } + } +}); // document.addEventListener("DOMContentLoaded", function () { const rfqTable = document.getElementById('rfqTable'); @@ -1283,19 +1330,34 @@ function moveAddRowButton() { rfqTable.addEventListener('click', function(e) { if (e.target.classList.contains('removeRow')) { - const row = e.target.closest('tr'); // Get the row to be removed - const rowKey = row.getAttribute('id'); + Swal.fire({ + title: 'Are you sure?', + text: "Do you want to remove the row?", + icon: 'warning', + showCancelButton: true, + confirmButtonColor: '#d33', + cancelButtonColor: '#3085d6', + confirmButtonText: 'Yes, remove it!', + cancelButtonText: 'Cancel' + }).then((result) => { + if (result.isConfirmed) { + const row = e.target.closest('tr'); // Get the row to be removed + const rowKey = row.getAttribute('id'); - console.log(suggestionKeys); - // Remove the key from suggestionKeys - suggestionKeys = suggestionKeys.filter(key => key !== rowKey); - row.remove(); - console.log(suggestionKeys); - updateRowNumbers(); // Update row numbers - moveAddRowButton(); // Move the add row button to the last row - realignSpecialConditions(); + console.log(suggestionKeys); + // Remove the key from suggestionKeys + suggestionKeys = suggestionKeys.filter(key => key !== rowKey); + row.remove(); + console.log(suggestionKeys); + updateRowNumbers(); // Update row numbers + moveAddRowButton(); // Move the add row button to the last row + realignSpecialConditions(); - isFormDataModified = true; // if any value changeing in the table to set true + isFormDataModified = true; // if any value changeing in the table to set true + } + }) + + } }); @@ -1441,7 +1503,6 @@ function showSuggestions(input) { // Function to handle answers suggestion box function showAnswersSuggestions(input) { - console.log(input.parentElement.id); console.log(input); //return; @@ -2142,7 +2203,17 @@ function removeProposal(event) { let rfqTable = document.getElementById('rfqTable'); console.log(rfqTable) - if (confirm("Are you sure you want to remove this column?")) { + Swal.fire({ + title: 'Are you sure?', + text: "Do you want to remove the Proposal?", + icon: 'warning', + showCancelButton: true, + confirmButtonColor: '#d33', + cancelButtonColor: '#3085d6', + confirmButtonText: 'Yes, remove it!', + cancelButtonText: 'Cancel' + }).then((result) => { + if (result.isConfirmed) { const headerRows = rfqTable.querySelectorAll('thead tr'); const parentTh = headerRows[0].children[colIndex]; @@ -2187,69 +2258,83 @@ function removeProposal(event) { console.log(`${proposal_name} does not exist.`); } } + + }) } function removeInsurer(event) { - if (confirm("Are you sure you want to remove this column?")) { - // function removeSubColumnByIndex(tableId, subThIndex) { - const table = document.getElementById('rfqTable'); - const headerRows = table.querySelectorAll('thead tr'); + Swal.fire({ + title: 'Are you sure?', + text: "Do you want to remove the insurer?", + icon: 'warning', + showCancelButton: true, + confirmButtonColor: '#d33', + cancelButtonColor: '#3085d6', + confirmButtonText: 'Yes, remove it!', + cancelButtonText: 'Cancel' + }).then((result) => { + if (result.isConfirmed) { + // function removeSubColumnByIndex(tableId, subThIndex) { + const table = document.getElementById('rfqTable'); + const headerRows = table.querySelectorAll('thead tr'); - const closestTh = event.target.closest('th'); - let insurerName = closestTh.innerText.split('â‹®')[0] - // alert(insurerName);return; - let subThIndex = closestTh.cellIndex; - console.log('subThIndex', subThIndex); + const closestTh = event.target.closest('th'); + let insurerName = closestTh.innerText.split('â‹®')[0] + // alert(insurerName);return; + let subThIndex = closestTh.cellIndex; + console.log('subThIndex', subThIndex); - // Get the sub TH from the second header row - const subTh = headerRows[1].children[subThIndex]; - console.log('subTh', subTh); + // Get the sub TH from the second header row + const subTh = headerRows[1].children[subThIndex]; + console.log('subTh', subTh); - let accumulatedColspan = 0; - let parentTh = null; - const firstHeaderRow = headerRows[0]; - // Find the parent TH for the specified sub TH index - for (let i = 0; i < firstHeaderRow.children.length; i++) { - const currentParentTh = firstHeaderRow.children[i]; - const currentColspan = parseInt(currentParentTh.getAttribute('colspan')) || 1; + let accumulatedColspan = 0; + let parentTh = null; + const firstHeaderRow = headerRows[0]; + // Find the parent TH for the specified sub TH index + for (let i = 0; i < firstHeaderRow.children.length; i++) { + const currentParentTh = firstHeaderRow.children[i]; + const currentColspan = parseInt(currentParentTh.getAttribute('colspan')) || 1; - accumulatedColspan += currentColspan; + accumulatedColspan += currentColspan; - if (subThIndex < accumulatedColspan) { - parentTh = currentParentTh; - break; + if (subThIndex < accumulatedColspan) { + parentTh = currentParentTh; + break; + } + } + console.log('parentth' + parentTh); + console.log('sub col indexOf' + subThIndex); + + + // Get the starting position of the sub TH + const startIndex = Array.from(headerRows[1].children).indexOf(subTh); + + // Remove the sub TH + headerRows[1].removeChild(subTh); + + // Reduce colspan of parent TH + const parentColspan = parseInt(parentTh.getAttribute('colspan')) || 1; + console.log('existing colspan' + parentColspan); + parentTh.setAttribute('colspan', parentColspan - 1); + console.log('new colspan' + (parentColspan - 1)); + + // Remove the corresponding TDs from each row + table.querySelectorAll('tbody tr').forEach(row => { + row.removeChild(row.children[startIndex]); + }); + + removeInsurerFromPremiumTable(event, subThIndex) + + //remove the insurer from gobal array + let proposal_name = parentTh.innerText.split('â‹®')[0]; + popInsurerInArray(proposal_name, insurerName); + + isFormDataModified = true; // if any value changeing in the table to set true } - } - console.log('parentth' + parentTh); - console.log('sub col indexOf' + subThIndex); - - - // Get the starting position of the sub TH - const startIndex = Array.from(headerRows[1].children).indexOf(subTh); - - // Remove the sub TH - headerRows[1].removeChild(subTh); - - // Reduce colspan of parent TH - const parentColspan = parseInt(parentTh.getAttribute('colspan')) || 1; - console.log('existing colspan' + parentColspan); - parentTh.setAttribute('colspan', parentColspan - 1); - console.log('new colspan' + (parentColspan - 1)); - - // Remove the corresponding TDs from each row - table.querySelectorAll('tbody tr').forEach(row => { - row.removeChild(row.children[startIndex]); - }); - - removeInsurerFromPremiumTable(event, subThIndex) - - //remove the insurer from gobal array - let proposal_name = parentTh.innerText.split('â‹®')[0]; - popInsurerInArray(proposal_name, insurerName); - - isFormDataModified = true; // if any value changeing in the table to set true - } + + }) } function showThreeDottedMenu(event) { @@ -2739,8 +2824,8 @@ function handleChildQuestions(target) { let childCell = childRow.cells[currentColumnIndex]; if (childCell) { - console.log('found cell'); - + console.log('found cell',inputValue); + if (inputValue.key == disable_at.key) { childCell.innerHTML = ''; childCell.innerText = ''; @@ -2759,6 +2844,21 @@ function handleChildQuestions(target) { console.log(child.default_answer.display_value) childCell.contentEditable = false; } else { + childCell.innerHTML = ''; + childCell.innerText = ''; + //hidden text box for store choosed answers object + const hiddenInputBox = document.createElement('input'); + hiddenInputBox.type = 'hidden'; + hiddenInputBox.value = JSON.stringify(inputValue.display_value); + + childCell.appendChild(hiddenInputBox); + // alert(input.innerText); + childCell.appendChild(document.createTextNode(inputValue.display_value)); + + // Set the default answer in the child cell + // childCell.innerHTML = child.default_answer.display_value; + // console.log('setting default value'); + // console.log(child.default_answer.display_value) childCell.contentEditable = true; } } @@ -3136,7 +3236,7 @@ function ajaxRequestForGetMailData(url) { function appendInput(data) { - console.log(data); + console.log("append data:",data); var lead_id = $('#lead_id').val(); $('#input_for_row').empty(); let html = ''; @@ -3146,9 +3246,9 @@ function appendInput(data) { const url = '?lead_id=' + lead_id; html += ` -
    +
    - +
    `; @@ -3164,29 +3264,33 @@ function appendInput(data) { html += ` -
    +
    -
    +
    `; @@ -3196,7 +3300,7 @@ function appendInput(data) { html += `
    - '" placeholder="Subject"> + " placeholder="Subject">
    `; @@ -3229,25 +3333,28 @@ function appendInput(data) {
    @@ -3307,7 +3414,13 @@ function appendInput(data) { function constructURL(url_type) { if(url_type == 1){ - constructURL_ForInsurerAndClientMailSend() + var validationStatus = checkMailValidation(); + + if (validationStatus){ + constructURL_ForInsurerAndClientMailSend(); + }else{ + toastr.error("All Client Mail ID's Should Contain Same Domain","ERROR"); + } }else if(url_type == 2){ constructURL_ForInternalMailSend() }else if(url_type == 3){ @@ -3470,6 +3583,7 @@ function constructURL_ForInsurerAndClientMailSend() { var subject = $('#mail_subject').val(); var bcc = $('#client_bcc').val(); var cc = $('#client_cc').val(); + var contact_mail = $("#contact_mail").val(); console.log('lead_id', lead_id) console.log('subject', subject) @@ -3501,6 +3615,7 @@ function constructURL_ForInsurerAndClientMailSend() { if (RFQ_or_QCR == 2) { + formData.append('contact_mail',contact_mail); formData.append('file_type', 'qcr'); formData.append('recipient_type', 'client'); formData.append('recipient_mail', ''); @@ -3560,6 +3675,8 @@ function constructURL_ForPlacementMailSend() { var lead_id = $('#lead_id').val(); let to = $('#placement_to').val(); let placement_date = $('#placement_date').val(); + let payment_date = $('#payment_date').val(); + let is_cd = $("#is_cd_switch").is(":checked") ? 1 : 0; let utr_no = $('#utr_no').val(); let premium_amount = $('#premium_amount').val(); let total_amount = $('#total_amount').val(); @@ -3590,6 +3707,8 @@ function constructURL_ForPlacementMailSend() { formData.append('proposal_insurer', proposal_insurer); formData.append('insurer_and_branch', insurer_and_branch); formData.append('placement_date', placement_date); + formData.append('payment_date', payment_date); + formData.append("is_cd",is_cd); formData.append('utr_no', utr_no); formData.append('premium_amount', premium_amount); formData.append('total_amount', total_amount); @@ -3661,7 +3780,7 @@ function ajaxRequest(formData) { $('#placement_cc').val('').select2({ placeholder : 'select CC Mail' }); - $('#placement_subject').val(''); + // $('#placement_subject').val(''); $("textarea.select2-search__field").attr('rows', '1'); $("textarea.select2-search__field").css('resize', 'none'); @@ -3738,7 +3857,7 @@ $('.close').click(function(){ $('#placement_cc').val('').select2({ placeholder : 'select CC Mail' }); - $('#placement_subject').val(''); + // $('#placement_subject').val(''); $("textarea.select2-search__field").attr('rows', '1'); $("textarea.select2-search__field").css('resize', 'none'); @@ -5733,4 +5852,65 @@ function appendMultiFileData(data) { } + $("#is_cd_switch").change(function (){ + var switch_status = ($("#is_cd_switch").is(":checked")? "on" : "off"); + console.log("Switch status",switch_status); + if (switch_status == "on"){ + + $("#cd_amount").show(); + $("#total_amount").show(); + $("#cd_amount").closest('.form-group').show(); + $("#total_amount").closest('.form-group').show(); + + }else{ + + $("#cd_amount").hide(); + $("#total_amount").hide(); + $("#cd_amount").closest('.form-group').hide(); + $("#total_amount").closest('.form-group').hide(); + + } + }) + + $(document).on("input", "#cd_amount, #premium_amount", function() { + + // alert("Function called"); + + var cd_amount = parseInt($("#cd_amount").val()) || 0; + var premium_amount = parseInt($("#premium_amount").val()) || 0; + + var total_amount = (cd_amount + premium_amount); + $("#total_amount").val(total_amount); + + + }); + + function checkMailValidation(){ + + emailString = $("#contact_mail").val(); + + if (RFQ_or_QCR == 1){ + if (typeof emailString !== 'string' || !emailString.includes(',')) return true; + }else{ + if (typeof emailString !== 'string') return false; + } + + const invalidChars = /[;|]/; + if (invalidChars.test(emailString)) return false; + + + const emails = emailString.split(',').map(email => email.trim()); + + if (emails.length === 0) return false; + + const getDomain = email => email.split('@')[1]?.toLowerCase(); + const firstDomain = getDomain(emails[0]); + + if (!firstDomain) return false; + + return emails.every(email => getDomain(email) === firstDomain); + } + + + \ No newline at end of file From 84fb4e797152765c7de92135502e1d6e2c5ab69b Mon Sep 17 00:00:00 2001 From: "venkatesh.r" Date: Tue, 8 Apr 2025 15:45:26 +0530 Subject: [PATCH 46/52] CHANGE_RFQ_NEW_CR : RV --- app/Controllers/ClientController.php | 233 ++++++++++++++++- app/Controllers/LeadsController.php | 373 +++++++++++++++++++++------ app/Models/LeadsModel.php | 3 + app/Views/leads_form.php | 126 +++++---- app/Views/leads_form_handler.php | 53 ++-- app/Views/rfq/gmc.php | 32 +-- app/Views/view_rfq.php | 21 +- 7 files changed, 674 insertions(+), 167 deletions(-) diff --git a/app/Controllers/ClientController.php b/app/Controllers/ClientController.php index 0a096c82..21f0afa5 100755 --- a/app/Controllers/ClientController.php +++ b/app/Controllers/ClientController.php @@ -1994,9 +1994,22 @@ class ClientController extends AdminController if ($id) { $client_policy_data = $this->clientPolicyModel->where(['id' => $id, 'is_active' => 1])->first(); + $insurer_id = $client_policy_data['insurer_id']; $client_id = $client_policy_data['client_id']; + if (!empty($client_policy_data['policy_start_date'])) { + $client_policy_data['source_policy_start_date'] = change_date_format($client_policy_data['policy_start_date'], 'Y-m-d', 'd/m/Y'); + } else { + $client_policy_data['source_policy_start_date'] = null; + } + + if (!empty($client_policy_data['policy_end_date'])) { + $client_policy_data['source_policy_end_date'] = change_date_format($client_policy_data['policy_end_date'], 'Y-m-d', 'd/m/Y'); + } else { + $client_policy_data['source_policy_end_date'] = null; + } + $polices = $this->policesModel ->select('policies.*, policy_type.policy_type') ->join('policy_type', 'policy_type.id = policies.policy_type_id') @@ -2022,7 +2035,7 @@ class ClientController extends AdminController 'policy' => $polices, 'client_policy_list' => $client_policy_list, 'end_date' => $newDate, - 'new_start_date' => date('d/m/Y', strtotime($client_policy_data['policy_end_date'])) + 'new_start_date' => date('d/m/Y', strtotime($client_policy_data['policy_end_date'] . ' +1 day')), ], 200); } else { return $this->respond(['status' => false, 'code' => 404, 'message' => 'no data found'], 200); @@ -4740,8 +4753,7 @@ class ClientController extends AdminController // } // $data = $this->leadsModel->where('leads.id', 125)->where('leads.is_active', 1)->first(); - // $RFQdata = $RFQModel->getRFQTableDataWithLeadIDAndType(125, 2); - // // Kint::dump($RFQdata); + // $RFQdata = $RFQModel->getRFQTableDataWithLeadIDAndType(145, 2); // $returnData = $LeadsController->getPlacementJson($data); // Kint::dump($returnData); // $policy_terms = $LeadsController->convertNonEbQCRJsonToPolicyTerms(json_decode($returnData, true)); @@ -4751,6 +4763,20 @@ class ClientController extends AdminController // $this->clientPolicyModel->where('id', 6050)->set('policy_terms', $policy_terms)->update(); // dd($returnData); + // Kint::dump($RFQdata['json']); + // $inputJson = json_decode($RFQdata['json'], true); + // Kint::dump($inputJson); + // // print_rr($inputJson['table_data']); + // $sortedJson = $this->reorderProposalsByInsurerTotal($inputJson); + + // // If you want to convert back to JSON string + // $finalJson = json_encode($sortedJson, JSON_PRETTY_PRINT); + + // // $RFQModel->insert(['lead_id' => 145, 'json' => $finalJson, 'type' => 1]); + + // dd($finalJson); + + } // ------------------------------------------------------------------------------------------------------- @@ -5456,6 +5482,207 @@ class ClientController extends AdminController $id = $InsurerModel->insert($insurerData); return $id; } + + private function reorderProposalsByInsurerTotal(array $data): array { + + Kint::dump($data); + if (!isset($data['premium_data']['data'])) return $data; + $original = $data['premium_data']['data']; + $proposals = []; + $others = []; + $emptyKeyData = []; + foreach ($original as $key => $value) { + // Match only keys that look like 'Proposal X' + if (preg_match('/^Proposal\s+\d+$/', $key)) { + // Get the insurer entry (not 'Quote Asked') + foreach ($value as $subKey => $subVal) { + if ($subKey !== 'Quote Asked' && isset($subVal['Total'])) { + $proposals[$key] = $value; + break; + }else{ + $proposals[$key] = $value; + } + } + } else { + + if ($key === '' && isset($value['']) && is_array($value[''])) { + // Capture empty key to push it later + $emptyKeyData[$key] = $value; + }else{ + $others[$key] = $value; + + } + } + } + + // dd($proposals, $others, $emptyKeyData); + // Sort proposals by their insurer's total + uasort($proposals, function($a, $b) { + $totalA = 0; + $totalB = 0; + + foreach ($a as $key => $val) { + if ($key !== 'Quote Asked' && isset($val['Total'])) { + $totalA = floatval($val['Total']); + break; + } + } + + foreach ($b as $key => $val) { + if ($key !== 'Quote Asked' && isset($val['Total'])) { + $totalB = floatval($val['Total']); + break; + } + } + + return $totalA <=> $totalB; + }); + + // Merge back the sorted proposals into the full structure + $data['premium_data']['data'] = array_merge($others, $proposals, $emptyKeyData); + $data = $this->reorderProposalDataByPremiumOrder($data); + return $data; + } + + private function reorderProposalDataByPremiumOrder(array $data): array { + if (!isset($data['premium_data']['data'], $data['proposal_data']['over_all_column_data'])) { + return $data; + } + + $premiumProposals = array_keys($data['premium_data']['data']); + $filteredProposals = []; + + // Collect proposal keys that match the pattern "Proposal X" + foreach ($premiumProposals as $key) { + if (preg_match('/^Proposal\s+\d+$/', $key) && isset($data['proposal_data']['over_all_column_data'][$key])) { + $filteredProposals[$key] = $data['proposal_data']['over_all_column_data'][$key]; + } + } + + // dd($premiumProposals, $filteredProposals); + + $data['proposal_data']['over_all_column_data'] = $filteredProposals; + $data = $this->reorderProposalInHeaderAndData($data); + return $data; + } + + private function reorderProposalInHeaderAndData(array $data): array { + + // Kint::dump($data); + $tableData = $data['table_data']; + $sortedProposalOrder = $data['proposal_data']['over_all_column_data']; + $headers = $tableData['headers'] ?? []; + $dataRows = $tableData['data'] ?? []; + + // Step 1: Separate static and proposal headers + $staticHeaders = []; + $proposalHeaders = []; + $actionHeader = []; + foreach ($headers as $header) { + if (in_array($header['parentHeader'], array_keys($sortedProposalOrder))) { + $proposalHeaders[$header['parentHeader']] = $header; + } else { + if($header['parentHeader'] == "Action"){ + $actionHeader[] = $header; + }else{ + $staticHeaders[] = $header; + } + } + } + + // dd($staticHeaders, $proposalHeaders, $sortedProposalOrder); + + // Step 2: Reorder headers + $reorderedHeaders = []; + foreach ($sortedProposalOrder as $proposalKey => $proposalValue) { + if (isset($proposalHeaders[$proposalKey])) { + $reorderedHeaders[] = $proposalHeaders[$proposalKey]; + } + } + + // print_rr($reorderedHeaders); die; + foreach ($reorderedHeaders as $key => &$value) { + $value['parentHeader'] = 'Proposal ' . ($key + 1); + } + unset($value); + + + $reorderedHeaders = array_merge($staticHeaders, $reorderedHeaders, $actionHeader); + + + // Step 3: Reorder each row's `data` by matching parentth + foreach ($dataRows as $dataRowIndex => &$row) { + $staticData = []; + $proposalData = []; + $actionData = []; + + foreach ($row['data'] as $entry) { + if (in_array($entry['parentth'], array_keys($sortedProposalOrder))) { + $proposalData[$entry['parentth']][] = $entry; + } else { + if($entry['parentth'] == "Action"){ + $actionData[] = $entry; + }else{ + $staticData[] = $entry; + } + } + } + + $reorderedProposalData = []; + foreach ($sortedProposalOrder as $proposalKey => $proposalValue) { + if (isset($proposalData[$proposalKey])) { + foreach ($proposalData[$proposalKey] as $entry) { + $reorderedProposalData[] = $entry; + } + } + } + + $dubParTh = ""; + $increament = 0; + foreach ($reorderedProposalData as $key => &$value) { + + if($dubParTh == $value['parentth']){ + $value['parentth'] = 'Proposal ' . ($increament); + }else{ + $dubParTh = $value['parentth']; + $increament = $increament + 1; + $value['parentth'] = 'Proposal ' . ($increament); + } + } + unset($value); + + $row['data'] = array_merge($staticData, $reorderedProposalData, $actionData); + } + + $data['table_data']['headers'] = $reorderedHeaders; + $data['table_data']['data'] = $dataRows; + + // dd('-----', $data); + $renumberedArray = $this->renumberProposalKeys($data['proposal_data']['over_all_column_data']); + $updatedDataSet = $this->renumberProposalKeys($data['premium_data']['data']); + $data['proposal_data']['over_all_column_data'] = !empty($renumberedArray) ? $renumberedArray : $data['proposal_data']['over_all_column_data']; + $data['premium_data']['data'] = !empty($updatedDataSet) ? $updatedDataSet : $data['premium_data']['data']; + + return $data; + } + + private function renumberProposalKeys(array $input): array { + $result = []; + $counter = 1; + + foreach ($input as $key => $value) { + if (strpos($key, 'Proposal') === 0) { + $newKey = 'Proposal ' . $counter++; + $result[$newKey] = $value; + } else { + $result[$key] = $value; + } + } + + return $result; + } + + } diff --git a/app/Controllers/LeadsController.php b/app/Controllers/LeadsController.php index c432c921..28b856d7 100644 --- a/app/Controllers/LeadsController.php +++ b/app/Controllers/LeadsController.php @@ -101,7 +101,7 @@ class LeadsController extends BaseController $this->leadType = [1 => 'Fresh', 2 => 'Renewal', 3 => 'Roll Over']; $this->buisnessType = [1 => 'Industrial', 2 => 'Non Industrial']; $this->leadsStatus = [ - 'queued' => 'Queued', + 'queued' => 'In-Queued', 'qcr_sent' => 'QCR sent', 'lost' => 'Lost', 'co_insurer_pending' => 'Co-Insurer Pending', @@ -202,6 +202,7 @@ class LeadsController extends BaseController } else { $data = $this->prepareMultipleLeadData($data); } + // print_r($data); die; return $data; } @@ -210,8 +211,8 @@ class LeadsController extends BaseController { // print_r($data); die; $index_plus_one = 1; - $form_file_name = "file_name_".$index_plus_one; - $form_docs_name = "docs_name_".$index_plus_one; + $form_file_name = "file_name_" . $index_plus_one; + $form_docs_name = "docs_name_" . $index_plus_one; $leads_file_primary_key = $data['leads_file_id'] ?? []; $files = $this->request->getFileMultiple($form_file_name); $multi_file_data = $this->uploadMultiFiles($files, $data[$form_docs_name], $leads_file_primary_key); @@ -252,7 +253,7 @@ class LeadsController extends BaseController } // $data['file_name'] = file_Upload($files, $uploadFilePath); - $data['multi_file_data']= $multi_file_data ?? null; + $data['multi_file_data'] = $multi_file_data ?? null; $processcedData[] = $data; @@ -268,8 +269,8 @@ class LeadsController extends BaseController foreach ($data['policy_type_id'] as $index => $value) { $index_plus_one = $index + 1; - $form_file_name = "file_name_".$index_plus_one; - $form_docs_name = "docs_name_".$index_plus_one; + $form_file_name = "file_name_" . $index_plus_one; + $form_docs_name = "docs_name_" . $index_plus_one; $leads_file_primary_key = $data['leads_file_id'] ?? []; $files = $this->request->getFileMultiple($form_file_name); $multi_file_data = $this->uploadMultiFiles($files, $data[$form_docs_name], $leads_file_primary_key); @@ -323,10 +324,22 @@ class LeadsController extends BaseController $incurred_claims_date = null; } - if (!empty($data['premium_date'][$index])) { - $premium_date = change_date_format($data['premium_date'][$index], 'd/m/Y', 'Y-m-d'); + // if (!empty($data['premium_date'][$index])) { + // $premium_date = change_date_format($data['premium_date'][$index], 'd/m/Y', 'Y-m-d'); + // } else { + // $premium_date = null; + // } + + if (!empty($data['source_policy_start_date'])) { + $data['source_policy_start_date'] = change_date_format($data['source_policy_start_date'], 'd/m/Y', 'Y-m-d'); } else { - $premium_date = null; + $data['source_policy_start_date'] = null; + } + + if (!empty($data['source_policy_end_date'])) { + $data['source_policy_end_date'] = change_date_format($data['source_policy_end_date'], 'd/m/Y', 'Y-m-d'); + } else { + $data['source_policy_end_date'] = null; } // $file_name = file_Upload($files[$index], $uploadFilePath); @@ -383,7 +396,7 @@ class LeadsController extends BaseController 'outstanding_claims' => $data['outstanding_claims'][$index] ?? 0, 'policy_run_days' => $data['policy_run_days'][$index] ?? 0, 'premium_at_inception' => $data['premium_at_inception'][$index] ?? 0, - 'premium_date' => $premium_date, + 'premium_date' => $data['premium_date'][$index] ?? 0, 'earned_premium' => $data['earned_premium'][$index] ?? 0, 'annualised_claims' => $data['annualised_claims'][$index] ?? 0, 'incurred_claims_ratio' => $data['incurred_claims_ratio'][$index] ?? 0, @@ -400,6 +413,9 @@ class LeadsController extends BaseController 'lead_form_type' => $data['lead_form_type'] ?? 1, 'custom_fields' => $data['custom_fields'] ?? null, + + 'source_policy_start_date' => $data['source_policy_start_date'] ?? null, + 'source_policy_end_date' => $data['source_policy_end_date'] ?? null, ]; } // print_r($processedData);die(); @@ -479,11 +495,11 @@ class LeadsController extends BaseController $data['incurred_claims_date'] = null; } - if (!empty($data['premium_date'])) { - $data['premium_date'] = change_date_format($data['premium_date'], 'Y-m-d', 'd/m/Y'); - } else { - $data['premium_date'] = null; - } + // if (!empty($data['premium_date'])) { + // $data['premium_date'] = change_date_format($data['premium_date'], 'Y-m-d', 'd/m/Y'); + // } else { + // $data['premium_date'] = null; + // } $data['multi_file_data'] = $this->leadFilesModel->where('lead_id', $id)->first() ?? null; @@ -538,26 +554,25 @@ class LeadsController extends BaseController } public function insertMultiFilesData($data, $lead_id) - { + { // print_r($data); die; - if(!empty($data)){ + if (!empty($data)) { foreach ($data as $key => $value) { - if(!empty($value['id'])){ + if (!empty($value['id'])) { $lead_file_data = [ 'lead_id' => $lead_id, 'docs_name' => $value['docs_name'], ]; - if(!empty($value['file_name'])) { + if (!empty($value['file_name'])) { $lead_file_data['file_name'] = $value['file_name']; } $this->leadFilesModel->where('id', $value['id'])->set($lead_file_data)->update(); - - }else{ + } else { $lead_file_data = [ 'lead_id' => $lead_id, @@ -566,8 +581,8 @@ class LeadsController extends BaseController ]; $this->leadFilesModel->insert($lead_file_data); } - - if($key == 0 && !empty($value['file_name'])) { + + if ($key == 0 && !empty($value['file_name'])) { $this->leadsModel->where('id', $lead_id)->set('file_name', $value['file_name'])->update(); } } @@ -577,22 +592,16 @@ class LeadsController extends BaseController } public function removeMultiFile() - { + { $id = $this->request->getGet('lead_file_id'); - if(!empty($id)){ + if (!empty($id)) { $this->leadFilesModel->where('id', $id)->set(['is_active' => 0])->update(); return $this->respond(['status' => true, 'message' => 'File removed successfully'], 200); - }else{ + } else { return $this->respond(['status' => false, 'message' => 'File could not be removed.'], 200); } } - - public function updateLeadTableFields() - { - - } - - //--------RFQ----------------------------------------------------------------------------------------------- + //--------RFQ----------------------------------------------------------------------------------------------- public function viewRFQ($id, $type = 1) @@ -676,14 +685,14 @@ class LeadsController extends BaseController $data['occupancy'] = $this->occupancyModel->findAll(); // dd($data['occupancy']); - if($lead_data['lead_type'] != 1 && $data['rfq_count'] == 0){ + if ($lead_data['lead_type'] != 1 && $data['rfq_count'] == 0) { $client_policy_data = $this->clientPolicyModel->where('is_active', 1)->where('id', $lead_data['source_policy_id'])->first(); $data['rfq_data']['json'] = $client_policy_data['placement_json']; } - if(!empty($data['question_json'])){ + if (!empty($data['question_json'])) { $data['policies'] = json_decode($data['question_json'], true)['policies']; - $data["child_table_data"] = json_decode($data['question_json'], true)['child_table_data']; + $data["child_table_data"] = json_decode($data['question_json'], true)['child_table_data']; } // $data['lead_register_data'] = json_decode($data['lead_data']['custom_fields']); @@ -735,15 +744,24 @@ class LeadsController extends BaseController return $this->respond(['status' => false, 'message' => 'Lead ID is required'], 400); } + $inputJson = json_decode($data['json'], true); + if (isset($inputJson['premium_data']) && !empty($inputJson['premium_data'])) { + $sortedJson = $this->reorderProposalsByInsurerTotal($inputJson); + $data['json'] = json_encode($sortedJson); + } + + $data['type'] = 1; // Deactivate existing RFQs for this lead and type - $this->RFQModel - ->where('lead_id', $lead_id) - ->where('type', 1) - ->where('is_active', 1) - ->set('is_active', 0) - ->update(); + if (!isset($data['rfq_primaryKey']) && empty($data['rfq_primaryKey'])) { + $this->RFQModel + ->where('lead_id', $lead_id) + ->where('type', 1) + ->where('is_active', 1) + ->set('is_active', 0) + ->update(); + } // Handle registration_json if (empty($data['registration_json'])) { @@ -759,20 +777,29 @@ class LeadsController extends BaseController } } - // Insert new RFQ - $insertId = $this->RFQModel->insert($data); + // print_r($data); die; + // $data['json'] = ""; + if (isset($data['rfq_primaryKey']) && !empty($data['rfq_primaryKey'])) { + $this->RFQModel->update($data['rfq_primaryKey'], $data); + $insertId = $data['rfq_primaryKey']; + $affectedRows = db_connect()->affectedRows(); + } else { + // Insert new RFQ + $insertId = $this->RFQModel->insert($data); + } if ($insertId) { - $message = ($data['submit_type'] ?? '') == 'QCR' ? 'QCR submitted successfully' : 'RFQ submitted successfully'; + $message = ($data['submit_type'] ?? '') == 'QCR' ? 'QCR saved successfully' : 'RFQ saved successfully'; return $this->respond([ 'status' => true, 'id' => $insertId, 'message' => $message, - 'data' => $data + 'data' => $data, + 'affectedRows' => $affectedRows ?? null, ], 200); } - $message = ($data['submit_type'] ?? '') == 'QCR' ? 'Failed to create QCR' : 'Failed to create RFQ'; + $message = ($data['submit_type'] ?? '') == 'QCR' ? 'Failed to save QCR' : 'Failed to save RFQ'; return $this->respond([ 'status' => false, 'id' => null, @@ -805,6 +832,206 @@ class LeadsController extends BaseController } + private function reorderProposalsByInsurerTotal(array $data): array + { + + if (!isset($data['premium_data']['data'])) return $data; + + $original = $data['premium_data']['data']; + $proposals = []; + $others = []; + $emptyKeyData = []; + + foreach ($original as $key => $value) { + // Match only keys that look like 'Proposal X' + if (preg_match('/^Proposal\s+\d+$/', $key)) { + // Get the insurer entry (not 'Quote Asked') + foreach ($value as $subKey => $subVal) { + if ($subKey !== 'Quote Asked' && isset($subVal['Total'])) { + $proposals[$key] = $value; + break; + }else{ + $proposals[$key] = $value; + } + } + } else { + + if ($key === '' && isset($value['']) && is_array($value[''])) { + // Capture empty key to push it later + $emptyKeyData[$key] = $value; + } else { + $others[$key] = $value; + } + } + } + + // Sort proposals by their insurer's total + uasort($proposals, function ($a, $b) { + $totalA = 0; + $totalB = 0; + + foreach ($a as $key => $val) { + if ($key !== 'Quote Asked' && isset($val['Total'])) { + $totalA = floatval($val['Total']); + break; + } + } + + foreach ($b as $key => $val) { + if ($key !== 'Quote Asked' && isset($val['Total'])) { + $totalB = floatval($val['Total']); + break; + } + } + + return $totalA <=> $totalB; + }); + + // Merge back the sorted proposals into the full structure + $data['premium_data']['data'] = array_merge($others, $proposals, $emptyKeyData); + $data = $this->reorderProposalDataByPremiumOrder($data); + return $data; + } + + private function reorderProposalDataByPremiumOrder(array $data): array + { + if (!isset($data['premium_data']['data'], $data['proposal_data']['over_all_column_data'])) { + return $data; + } + + $premiumProposals = array_keys($data['premium_data']['data']); + $filteredProposals = []; + + // Collect proposal keys that match the pattern "Proposal X" + foreach ($premiumProposals as $key) { + if (preg_match('/^Proposal\s+\d+$/', $key) && isset($data['proposal_data']['over_all_column_data'][$key])) { + $filteredProposals[$key] = $data['proposal_data']['over_all_column_data'][$key]; + } + } + + // dd($premiumProposals, $filteredProposals); + + $data['proposal_data']['over_all_column_data'] = $filteredProposals; + $data = $this->reorderProposalInHeaderAndData($data); + return $data; + } + + private function reorderProposalInHeaderAndData(array $data): array + { + $tableData = $data['table_data']; + $sortedProposalOrder = $data['proposal_data']['over_all_column_data']; + $headers = $tableData['headers'] ?? []; + $dataRows = $tableData['data'] ?? []; + + // Step 1: Separate static and proposal headers + $staticHeaders = []; + $proposalHeaders = []; + $actionHeader = []; + foreach ($headers as $header) { + if (in_array($header['parentHeader'], array_keys($sortedProposalOrder))) { + $proposalHeaders[$header['parentHeader']] = $header; + } else { + if ($header['parentHeader'] == "Action") { + $actionHeader[] = $header; + } else { + $staticHeaders[] = $header; + } + } + } + + // dd($staticHeaders, $proposalHeaders, $sortedProposalOrder); + + // Step 2: Reorder headers + $reorderedHeaders = []; + foreach ($sortedProposalOrder as $proposalKey => $proposalValue) { + if (isset($proposalHeaders[$proposalKey])) { + $reorderedHeaders[] = $proposalHeaders[$proposalKey]; + } + } + + // print_rr($reorderedHeaders); die; + foreach ($reorderedHeaders as $key => &$value) { + $value['parentHeader'] = 'Proposal ' . ($key + 1); + } + unset($value); + + + $reorderedHeaders = array_merge($staticHeaders, $reorderedHeaders, $actionHeader); + + + // Step 3: Reorder each row's `data` by matching parentth + foreach ($dataRows as $dataRowIndex => &$row) { + $staticData = []; + $proposalData = []; + $actionData = []; + + foreach ($row['data'] as $entry) { + if (in_array($entry['parentth'], array_keys($sortedProposalOrder))) { + $proposalData[$entry['parentth']][] = $entry; + } else { + if ($entry['parentth'] == "Action") { + $actionData[] = $entry; + } else { + $staticData[] = $entry; + } + } + } + + $reorderedProposalData = []; + foreach ($sortedProposalOrder as $proposalKey => $proposalValue) { + if (isset($proposalData[$proposalKey])) { + foreach ($proposalData[$proposalKey] as $entry) { + $reorderedProposalData[] = $entry; + } + } + } + + $dubParTh = ""; + $increament = 0; + foreach ($reorderedProposalData as $key => &$value) { + + if ($dubParTh == $value['parentth']) { + $value['parentth'] = 'Proposal ' . ($increament); + } else { + $dubParTh = $value['parentth']; + $increament = $increament + 1; + $value['parentth'] = 'Proposal ' . ($increament); + } + } + unset($value); + + $row['data'] = array_merge($staticData, $reorderedProposalData, $actionData); + } + + $data['table_data']['headers'] = $reorderedHeaders; + $data['table_data']['data'] = $dataRows; + + $renumberedArray = $this->renumberProposalKeys($data['proposal_data']['over_all_column_data']); + $updatedDataSet = $this->renumberProposalKeys($data['premium_data']['data']); + $data['proposal_data']['over_all_column_data'] = !empty($renumberedArray) ? $renumberedArray : $data['proposal_data']['over_all_column_data']; + $data['premium_data']['data'] = !empty($updatedDataSet) ? $updatedDataSet : $data['premium_data']['data']; + + return $data; + } + + private function renumberProposalKeys(array $input): array + { + $result = []; + $counter = 1; + + foreach ($input as $key => $value) { + if (strpos($key, 'Proposal') === 0) { + $newKey = 'Proposal ' . $counter++; + $result[$newKey] = $value; + } else { + $result[$key] = $value; + } + } + + return $result; + } + + //-----RFQ and QCR EXPORT------------------------------------------------------------------------------------------------ @@ -2394,16 +2621,15 @@ class LeadsController extends BaseController // } } - if($data['lead_form_type'] == 1){ + if ($data['lead_form_type'] == 1) { $client_policy_data['policy_terms'] = $this->preparePolicyTermsFromRFQ($data); - }else{ + } else { $placementJson = $this->getPlacementJson($data); if ($placementJson) { $client_policy_data['placement_json'] = $placementJson; $client_policy_data['policy_terms'] = $this->convertNonEbQCRJsonToPolicyTerms(json_decode($placementJson, true)); } - } // print_r($client_policy_data); die; @@ -2542,12 +2768,11 @@ class LeadsController extends BaseController } return json_encode($terms_array); - } else { return null; } } - + public function featchClientPolicyFromLead($client_id, $branch_id, $lead_id) { $data = $this->leadsModel->where('leads.id', $lead_id)->where('leads.is_active', 1)->first(); @@ -2592,7 +2817,9 @@ class LeadsController extends BaseController return $this->transformNonEbProposelData( $jsonData, $proposel_data['proposel_name'] ?? '', - $proposel_data['insurer_name'] ?? '', null, 1 + $proposel_data['insurer_name'] ?? '', + null, + 1 ); }, $jsonArray); @@ -2612,7 +2839,7 @@ class LeadsController extends BaseController } unset($proposal); // Good practice after foreach by reference } - + $placement_json_data[] = $proposalData; @@ -2721,7 +2948,7 @@ class LeadsController extends BaseController } if (!empty($data['lead_edit_data'])) { - foreach (['policy_start_date', 'policy_end_date', 'incurred_claims_date', 'premium_date'] as $dateField) { + foreach (['policy_start_date', 'policy_end_date', 'source_policy_start_date', 'source_policy_end_date', 'incurred_claims_date'] as $dateField) { $data['lead_edit_data'][$dateField] = !empty($data['lead_edit_data'][$dateField]) ? change_date_format($data['lead_edit_data'][$dateField], 'Y-m-d', 'd/m/Y') : null; @@ -2812,7 +3039,7 @@ class LeadsController extends BaseController $lead_data = array_merge(['Insured' => $rfq_data['client_name']], $lead_data); $policy_registration_data = []; - if(isset($rfq_data['registration_json']) && !empty($rfq_data['registration_json'])){ + if (isset($rfq_data['registration_json']) && !empty($rfq_data['registration_json'])) { $policy_registration_data = json_decode($rfq_data['registration_json'], true); } // dd($policy_registration_data); @@ -2960,7 +3187,7 @@ class LeadsController extends BaseController ]); $rowNumber++; - }else{ + } else { $sheet->mergeCells("A{$rowNumber}:B{$rowNumber}"); $sheet->setCellValue("A{$rowNumber}", "Policy Type"); $sheet->setCellValue("C{$rowNumber}", ucfirst($key) . " Policy"); @@ -3148,7 +3375,7 @@ class LeadsController extends BaseController $serial_no = 1; $maxColumnWidths = []; $RowSpanEnable = false; - + // Add table data rows foreach ($column_data as $dataRow) { @@ -3173,11 +3400,11 @@ class LeadsController extends BaseController $sheet->getStyle("{$columnLetter}{$mergeStart}:{$columnLetter}{$mergeEnd}") ->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER); } else { - if(!$hasPolicy && $key == 0){ + if (!$hasPolicy && $key == 0) { $RowSpanEnable = true; $columnLetter++; $sheet->setCellValue("{$columnLetter}{$rowNumber}", $cellData['display_content']); - }else{ + } else { $sheet->setCellValue("{$columnLetter}{$rowNumber}", $cellData['display_content']); } } @@ -3185,13 +3412,12 @@ class LeadsController extends BaseController if (!($key === 0 && !$hasPolicy)) { $columnLetter++; } - } $rowNumber++; $serial_no++; } - if($key == 0 && $RowSpanEnable == true){ + if ($key == 0 && $RowSpanEnable == true) { $columnLetter++; } @@ -3494,7 +3720,7 @@ class LeadsController extends BaseController return null; } - public function transformNonEbProposelData(&$data, $proposal, $insurer, $tableCount=null, $actionColumn = null) + public function transformNonEbProposelData(&$data, $proposal, $insurer, $tableCount = null, $actionColumn = null) { // Kint::dump($data, $proposal, $insurer, $tableCount); @@ -3531,7 +3757,7 @@ class LeadsController extends BaseController // Update the original data's headers $data['table_data']['headers'] = $headerData; - if(!empty($actionColumn)){ + if (!empty($actionColumn)) { $data['table_data']['headers'][] = [ 'parentHeader' => "Action", 'subHeaders' => ['-'] @@ -3563,8 +3789,8 @@ class LeadsController extends BaseController $filteredData[] = $item; } - if(!empty($actionColumn)){ - if($item['parentth'] === "Action"){ + if (!empty($actionColumn)) { + if ($item['parentth'] === "Action") { $filteredData[] = $item; } } @@ -3582,24 +3808,24 @@ class LeadsController extends BaseController return $data; } - public function getPreviousColumn($columnLetter, $decrement = 1) + public function getPreviousColumn($columnLetter, $decrement = 1) { $colIndex = Coordinate::columnIndexFromString($columnLetter); $colIndex = max(1, $colIndex - $decrement); // ensure column index doesn't go below 1 return Coordinate::stringFromColumnIndex($colIndex); } - + public function handleMultiFileAttachments($json_string, $lead_id) - { + { $attachments = []; - + if (!empty($json_string)) { $fileIds = json_decode($json_string, true); $lead_file_path = WRITEPATH . 'uploads/lead_files/'; - + foreach ($fileIds as $id) { $lead_file = $this->leadFilesModel->where('lead_id', $lead_id)->where('id', $id)->where('is_active', 1)->first(); - + if ($lead_file) { $attachments[] = [ 'fileName' => $lead_file['file_name'], @@ -3608,8 +3834,7 @@ class LeadsController extends BaseController } } } - + return $attachments; } - } diff --git a/app/Models/LeadsModel.php b/app/Models/LeadsModel.php index 84e9c9bf..d0d6d0c8 100644 --- a/app/Models/LeadsModel.php +++ b/app/Models/LeadsModel.php @@ -87,6 +87,9 @@ class LeadsModel extends Model 'lead_form_type', 'custom_fields', + + 'source_policy_start_date', + 'source_policy_end_date', ]; diff --git a/app/Views/leads_form.php b/app/Views/leads_form.php index 566aa5e4..fc2ee0f0 100644 --- a/app/Views/leads_form.php +++ b/app/Views/leads_form.php @@ -162,6 +162,16 @@
    + + + +
    - +