From 77426aaff6300e7091bbf1f76000e8d67f3abf1b Mon Sep 17 00:00:00 2001 From: "venkatesh.r" Date: Wed, 2 Apr 2025 11:35:23 +0530 Subject: [PATCH 01/25] FEAT_CLAIM_FEADBACK_FORM : RV --- app/Config/Routes.php | 2 ++ app/Controllers/TicketController.php | 18 ++++++++++++++++-- app/Views/ticket_feedback_form.php | 0 3 files changed, 18 insertions(+), 2 deletions(-) create mode 100644 app/Views/ticket_feedback_form.php diff --git a/app/Config/Routes.php b/app/Config/Routes.php index 0059a7a1..c9bedc6f 100755 --- a/app/Config/Routes.php +++ b/app/Config/Routes.php @@ -52,6 +52,8 @@ $routes->get('/update-emp-policy-status', 'ClientController::updateEmpAndPolicyS $routes->get('download-e-card/(:any)', 'EmployeeController::generateIDCardForEmployee/$1'); $routes->get('download-kyc-docs/(:segment)', 'ClientController::downloadKYCDocument/$1'); $routes->get('claim-form-download/(:any)', 'TicketController::downloadClaimForm/$1'); +$routes->get("claims-feedback-form/(:any)", "TicketController::viewClaimFeedbackForm/$1"); + $routes->group("/user", ["filter" => "authMVC"], function ($routes) { $routes->post("create", "UserController::create"); diff --git a/app/Controllers/TicketController.php b/app/Controllers/TicketController.php index a7392860..26ecbd5e 100644 --- a/app/Controllers/TicketController.php +++ b/app/Controllers/TicketController.php @@ -120,6 +120,7 @@ class TicketController extends BaseController '((POLICY_TYPE))' => 'policy_type', '((AUTO_QUERY_CONTENT))' => 'auto_query_content', '((CLAIM_FORM_LINK))' => 'claim_form_link', + '((CLAIM_FEEDBACK_FORM))' => 'claim_feedback_form', ]; $this->extraFields = [ 1 => ['non_id_reason'], @@ -869,6 +870,8 @@ class TicketController extends BaseController $replaceData = str_replace("Claim-", "", $this->ticketType[$ticket_data['ticket_type_id']] ?? ""); } else if ($value == "claim_form_link"){ $replaceData = 'Click here to download Claim Form'; + } else if ($value == "claim_feedback_form"){ + $replaceData = 'Click to open Claim Feedback Form'; }else { $replaceData = isset($ticket_data[$value]) ? $ticket_data[$value] : ''; } @@ -1371,7 +1374,8 @@ class TicketController extends BaseController } } - public function getPoliciesbyEmpID() { + public function getPoliciesbyEmpID() + { $received_data = $this->request->getPost(); $emp_id = $received_data['emp_id']; @@ -1443,5 +1447,15 @@ class TicketController extends BaseController return $this->response->setStatusCode(500)->setBody('An error occurred while downloading the file.'); } } - + + // ------------------------------------------------------------------------------------------------------------------------- + + + public function viewClaimFeedbackForm($md5_ticket_id) + { + $ticket_id = $this->ticketMasterModel->where('MD5(id)', $md5_ticket_id)->where('is_active', 1)->first(); + $data['ticket_id'] = $ticket_id['id']; + return view('ticket_feedback_form', $data); + } + } diff --git a/app/Views/ticket_feedback_form.php b/app/Views/ticket_feedback_form.php new file mode 100644 index 00000000..e69de29b From ad86f196cc0fb155c3983322fd809b7460e3526d Mon Sep 17 00:00:00 2001 From: "venkatesh.r" Date: Thu, 3 Apr 2025 10:58:11 +0530 Subject: [PATCH 02/25] CHANGE_CLAIMS_CR : RV --- app/Controllers/EmployeeRestController.php | 10 ++- app/Controllers/TicketController.php | 90 +++++++++++++++++++++- app/Models/TicketHistoryModel.php | 2 +- app/Views/ticket_list.php | 12 ++- 4 files changed, 106 insertions(+), 8 deletions(-) diff --git a/app/Controllers/EmployeeRestController.php b/app/Controllers/EmployeeRestController.php index 2d7bf436..b4d867a3 100755 --- a/app/Controllers/EmployeeRestController.php +++ b/app/Controllers/EmployeeRestController.php @@ -3112,6 +3112,8 @@ class EmployeeRestController extends AdminController } + // ---------------- TICKET API's --------------------------------------------------------------------------------------------------- + //Get Data from post for inserting ticket and message public function initiateClaim() { @@ -3171,9 +3173,11 @@ class EmployeeRestController extends AdminController ->first()['id']; $fetchData['priority'] = 1; - $fetchData['mode_of_intimation'] = 1; + $fetchData['mode_of_intimation'] = 3; + $fetchData['claim_type'] = 1; $fetchData = array_merge($fetchData, $received_data); + $fetchData['relationship'] = strtolower($fetchData['relationship']) ?? $fetchData['relationship']; // print_r($fetchData); die; $insert_status = $this->ticketMaster->insert($fetchData); $ticket_id = $this->ticketMaster->insertID(); @@ -3185,8 +3189,8 @@ class EmployeeRestController extends AdminController 'sender' => 'user', 'claim_status' => $fetchData['claim_status_id'] ?? null, 'emp_mail' => $fetchData['emp_mail'] ?? null, - 'mail_subject' => $fetchData['subject'] ?? null, - 'mail_content' => $fetchData['message'] ?? null, + 'mail_subject' => $fetchData['subject'] ?? "New Claim", + 'mail_content' => $fetchData['message'] ?? "New Claim", ]; if (!empty($messagesData['ticket_id'])) { diff --git a/app/Controllers/TicketController.php b/app/Controllers/TicketController.php index 26ecbd5e..b8098149 100644 --- a/app/Controllers/TicketController.php +++ b/app/Controllers/TicketController.php @@ -234,6 +234,7 @@ class TicketController extends BaseController 'tm.claim_number AS claim_no', 'tm.tpa_id', 'tm.emp_name', + 'tm.emp_code', 'i.name AS insurer_name', 'c.client_name', 'tm.insured_name', @@ -274,6 +275,7 @@ class TicketController extends BaseController 'tm.is_head_approved', 'tm.tpa_id', 'tm.emp_name', + 'tm.emp_code', 'i.name AS insurer_name', 'c.client_name', 'tm.insured_name', @@ -457,7 +459,18 @@ class TicketController extends BaseController $data['placeHolders'] = $this->placeHolders; $data['message_data'] = $this->getTicketMessage($ticket_id); $data['view_ticket_page'] = []; - $data['member_data'] = $this->employeeModel->getEmployeeByEmployeeCode($ticket_data['emp_code']); + + if($ticket_data['ticket_type_id'] == 1){ + $data['member_data'] = $this->employeeModel->getEmployeeByEmployeeCode($ticket_data['emp_code']); + }else{ + $data['member_data'] = array_filter( + $this->employeeModel->getEmployeeByEmployeeCode($ticket_data['emp_code']), + function ($member) { + return isset($member['emp_relationship']) && $member['emp_relationship'] == 'Self'; + } + ); + } + $data['ticket_history'] = $this->ticketHistory($ticket_id); $data['ticket_check_list'] = db_connect()->table('ticket_check_list')->where('is_active', 1)->where('ticket_type_id', $ticket_data['ticket_type_id'])->get()->getResultArray(); if (!empty($ticket_data['client_policy_id'])){ @@ -579,7 +592,9 @@ class TicketController extends BaseController $return_value = $this->ticketMasterModel->insert($ticket_data); if ($return_value) { //mail trigger part + $this->putHistoryAfterInsert($ticket_data, $return_value); $mail_responce = $this->sendAutoMailTrigger($return_value); + $this->autoMessageInsertBasedOnMailResponse($mail_responce, $return_value); return $this->respond(['status' => true, 'ticket_id' => $return_value, 'code' => 200, 'data' => $ticket_data, "message" => "Claim created successfully", 'mail_responce' => $mail_responce], 200); } else { return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to create claim'], 200); @@ -602,8 +617,12 @@ class TicketController extends BaseController $return_value = $this->ticketMasterModel->where('id', $ticket_id)->set($ticket_data)->update(); if ($return_value) { - //mail trigger part - $mail_responce = $this->sendAutoMailTrigger($ticket_id); + $mail_responce = null; + if($old_ticket_data['claim_status_id'] != $ticket_data['claim_status_id']){ + //mail trigger part + $mail_responce = $this->sendAutoMailTrigger($ticket_id); + $this->autoMessageInsertBasedOnMailResponse($mail_responce, $ticket_id); + } //send mail to the head for rejected ticket approvel if($ticket_data['claim_status_id'] == 8 && $ticket_data['is_head_approved'] == 0){ @@ -1450,6 +1469,71 @@ class TicketController extends BaseController // ------------------------------------------------------------------------------------------------------------------------- + public function autoMessageInsertBasedOnMailResponse($mail_sent_status, $ticket_id) + { + if (gettype($mail_sent_status) == 'array') { + $this->myLogger->logme('error', "auto Message Insert Based On Mail Response Failed because is array :$ticket_id "); + } else { + $mail_sent_status = json_decode($mail_sent_status); + $this->myLogger->logme('error', "mail_sent_status is object :$ticket_id "); + } + + if (!empty($mail_sent_status) && isset($mail_sent_status->status) && $mail_sent_status->status == 'success') { + + $sent_message_data['ticket_id'] = $ticket_id; + $sent_message_data['sender'] = 'staff'; + $sent_message_data['emp_mail'] = $mail_sent_status->data->params->mail; + $sent_message_data['mail_subject'] = $mail_sent_status->data->params->subject; + $sent_message_data['mail_content'] = $mail_sent_status->data->params->message; + + $message_insert_status = $this->ticketMessageModel->insert($sent_message_data); + + if ($message_insert_status) { + $this->myLogger->logme('error', "Claim initiated, Mail sent Successfully, successfully store message:$ticket_id "); + } else { + $this->myLogger->logme('error', "Claim initiated, Mail sent Successfully, Failed to store message:$ticket_id "); + } + + return true; + } else { + + $this->myLogger->logme('error', "Failed to send Mail :$ticket_id "); + return true; + } + } + + public function putHistoryAfterInsert($ticket_data, $ticket_id) + { + $this->myLogger->logme('error', "Put History After Insert function called : $ticket_id"); + + if(!empty($ticket_data)){ + + $history_data = [ + 'ticket_id' => $ticket_id, + 'field_name' => 'claim_status_id', + 'display_name' => 'Ticket Created', + 'old_value' => null, + 'new_value' => $ticket_data['claim_status_id'], + 'created_by' => get_session_userid(), + 'is_active' => 1 + ]; + + $this->myLogger->logme('error', "Put History After Insert function called : " . json_encode($history_data)); + + + $history_insert = $this->ticketHistoryModel->insert($history_data); + + if($history_insert){ + $this->myLogger->logme('error', "Put History After Insert Ticket Data Successfully"); + }else{ + $this->myLogger->logme('error', "Put History After Insert Ticket Data Failed"); + } + + }else{ + $this->myLogger->logme('error', "Put History After Insert Ticket Data is empty"); + } + + } public function viewClaimFeedbackForm($md5_ticket_id) { diff --git a/app/Models/TicketHistoryModel.php b/app/Models/TicketHistoryModel.php index 6d7eb0f5..92041c8c 100644 --- a/app/Models/TicketHistoryModel.php +++ b/app/Models/TicketHistoryModel.php @@ -12,7 +12,7 @@ class TicketHistoryModel extends Model protected $returnType = 'array'; protected $useSoftDeletes = false; protected $protectFields = true; - protected $allowedFields = ['id','field_name','display_name','old_value', + protected $allowedFields = ['id', "ticket_id", 'field_name','display_name','old_value', 'new_value','created_by','created_at','updated_by','updated_at','is_active']; // Callbacks diff --git a/app/Views/ticket_list.php b/app/Views/ticket_list.php index a51706fd..fa5c8fcc 100644 --- a/app/Views/ticket_list.php +++ b/app/Views/ticket_list.php @@ -35,6 +35,10 @@ table.dataTable tbody td { white-space: nowrap !important; } +#scroll-horizontal-datatable tbody tr:hover { + background-color: #e0e0e0; +} + @@ -57,6 +61,7 @@ table.dataTable tbody td { Policy Type Claim number TPA ID + Emp ID Emp name Insured Name Corporate name @@ -66,7 +71,7 @@ table.dataTable tbody td { $row){ ?> - + + @@ -184,8 +190,12 @@ $(document).ready(function() { function viewTicket(ticket_id){ + $('.loader').fadeIn(); + $('.loader-mask').fadeIn(); + let url = '' + ticket_id window.location.href = url + } \ No newline at end of file From 82f131f5115c1557284888e069bceff3076ddcf6 Mon Sep 17 00:00:00 2001 From: "venkatesh.r" Date: Thu, 3 Apr 2025 11:14:47 +0530 Subject: [PATCH 03/25] CHNAGE_API_FOR_FIRST_HISTORY : RV --- app/Controllers/EmployeeRestController.php | 3 +++ app/Controllers/TicketController.php | 2 ++ app/Views/ticket_history.php | 2 +- 3 files changed, 6 insertions(+), 1 deletion(-) diff --git a/app/Controllers/EmployeeRestController.php b/app/Controllers/EmployeeRestController.php index b4d867a3..e86f5de7 100755 --- a/app/Controllers/EmployeeRestController.php +++ b/app/Controllers/EmployeeRestController.php @@ -3184,6 +3184,9 @@ class EmployeeRestController extends AdminController if ($insert_status && !empty($ticket_id)) { + //insert first history + $this->ticketController->putHistoryAfterInsert($fetchData, $ticket_id); + $messagesData = [ 'ticket_id' => $ticket_id ?? null, 'sender' => 'user', diff --git a/app/Controllers/TicketController.php b/app/Controllers/TicketController.php index b8098149..a783fa2f 100644 --- a/app/Controllers/TicketController.php +++ b/app/Controllers/TicketController.php @@ -1533,6 +1533,8 @@ class TicketController extends BaseController $this->myLogger->logme('error', "Put History After Insert Ticket Data is empty"); } + return true; + } public function viewClaimFeedbackForm($md5_ticket_id) diff --git a/app/Views/ticket_history.php b/app/Views/ticket_history.php index 7ee087e1..0a783d26 100644 --- a/app/Views/ticket_history.php +++ b/app/Views/ticket_history.php @@ -20,7 +20,7 @@ '.$row['new_value']; ?> - + From 61732f1c2e28a06059372b8d3b45986376baada7 Mon Sep 17 00:00:00 2001 From: Srinivas-Saravanan Date: Thu, 3 Apr 2025 16:49:06 +0530 Subject: [PATCH 04/25] FEAT_CLAIM_FEEDBACK_FORM_SRI --- app/Config/Routes.php | 5 +- app/Controllers/TicketController.php | 49 +- app/Models/TicketMasterModel.php | 1 + app/Views/layout/header.php | 10 + app/Views/ticket_feedback_form.php | 837 +++++++++++++++++++++++++++ app/Views/ticket_feedback_list.php | 148 +++++ 6 files changed, 1044 insertions(+), 6 deletions(-) create mode 100644 app/Views/ticket_feedback_list.php diff --git a/app/Config/Routes.php b/app/Config/Routes.php index c9bedc6f..0c5f0d0c 100755 --- a/app/Config/Routes.php +++ b/app/Config/Routes.php @@ -52,7 +52,9 @@ $routes->get('/update-emp-policy-status', 'ClientController::updateEmpAndPolicyS $routes->get('download-e-card/(:any)', 'EmployeeController::generateIDCardForEmployee/$1'); $routes->get('download-kyc-docs/(:segment)', 'ClientController::downloadKYCDocument/$1'); $routes->get('claim-form-download/(:any)', 'TicketController::downloadClaimForm/$1'); -$routes->get("claims-feedback-form/(:any)", "TicketController::viewClaimFeedbackForm/$1"); +$routes->match (['get','post'],"claims-feedback-form/(:any)/(:any)", "TicketController::viewClaimFeedbackForm/$1/$2"); +$routes->match (['get','post'],"claims-feedback-form/(:any)", "TicketController::viewClaimFeedbackForm/$1"); + $routes->group("/user", ["filter" => "authMVC"], function ($routes) { @@ -535,6 +537,7 @@ $routes->group("/bdsReport", ["filter" => "authMVC"], function ($routes) { //New Tickets $routes->group("/ticket", ["filter" => "authMVC"], function ($routes) { $routes->match( ['get', 'post'], 'list','TicketController::ticketList'); + $routes->get('feedback-list','TicketController::feedbackList'); $routes->get('new/(:any)','TicketController::ticket_form/$1'); $routes->post('create','TicketController::createTicket'); $routes->post('update','TicketController::updateTicket'); diff --git a/app/Controllers/TicketController.php b/app/Controllers/TicketController.php index 26ecbd5e..d6e62594 100644 --- a/app/Controllers/TicketController.php +++ b/app/Controllers/TicketController.php @@ -870,7 +870,7 @@ class TicketController extends BaseController $replaceData = str_replace("Claim-", "", $this->ticketType[$ticket_data['ticket_type_id']] ?? ""); } else if ($value == "claim_form_link"){ $replaceData = 'Click here to download Claim Form'; - } else if ($value == "claim_feedback_form"){ + } else if ($value == "claim_feedback_form" && $ticket_data['ticket_type_id'] == 1){ $replaceData = 'Click to open Claim Feedback Form'; }else { $replaceData = isset($ticket_data[$value]) ? $ticket_data[$value] : ''; @@ -1451,11 +1451,50 @@ class TicketController extends BaseController // ------------------------------------------------------------------------------------------------------------------------- - public function viewClaimFeedbackForm($md5_ticket_id) + public function viewClaimFeedbackForm($md5_ticket_id,$empView = null) { - $ticket_id = $this->ticketMasterModel->where('MD5(id)', $md5_ticket_id)->where('is_active', 1)->first(); - $data['ticket_id'] = $ticket_id['id']; - return view('ticket_feedback_form', $data); + + if ($this->request->is("get")){ + + $data['ticket_id'] = $md5_ticket_id; + $data['ticket_data'] = $this->ticketMasterModel->select('ticket_master.*,clients.client_name')->join('clients','clients.id = ticket_master.client_id')->where('MD5(ticket_master.id)',$md5_ticket_id)->where('ticket_master.is_active',1)->first(); + $data['form_submitted'] = !empty($data['ticket_data']['feedback_json'])? 1 : 0; + + + $data['viewer'] = !empty($empView) ? $empView : 0; + // dd($data); + return view('ticket_feedback_form', $data); + }else{ + + $formDataJson = json_encode($this->request->getPost()); + // log_message("error","Form data : ".$formDataJson); + + + $data_to_store = [ + + 'feedback_json' => $formDataJson + ]; + + if (!empty($formDataJson)){ + // $this->ticketMasterModel->save($data_to_store); + $this->ticketMasterModel->where('MD5(id)', $md5_ticket_id)->set($data_to_store)->update(); + + return $this->respond(['status' => true,'id'=> $md5_ticket_id,'received_data' => $formDataJson], 200); + + }else{ + return $this->respond(['status' => false,'id'=> $md5_ticket_id,'received_data' => $formDataJson], 200); + } + + } + + } + + public function feedbackList(){ + + $data['feedback_data'] = $this->ticketMasterModel->select("ticket_master.*,clients.client_name")->join("clients","clients.id = ticket_master.client_id")->where("ticket_master.is_active",1)->where("ticket_master.feedback_json IS NOT NULL", null, false)->where("ticket_master.feedback_json !=", "")->findAll(); + + // dd($data); + $this->loadLayout("ticket_feedback_list",$data); } } diff --git a/app/Models/TicketMasterModel.php b/app/Models/TicketMasterModel.php index 7fc418cb..1612c08e 100644 --- a/app/Models/TicketMasterModel.php +++ b/app/Models/TicketMasterModel.php @@ -15,6 +15,7 @@ class TicketMasterModel extends Model protected $allowedFields = [ 'id', 'ticket_type_id', + 'feedback_json', 'claim_status_id', 'acm_id', 'insurer_id', diff --git a/app/Views/layout/header.php b/app/Views/layout/header.php index 0abdf8d5..f7ccabb4 100755 --- a/app/Views/layout/header.php +++ b/app/Views/layout/header.php @@ -81,6 +81,13 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+
+ " class="form-control-plaintext" id="email" readonly> +
+
+ +
+
+ +
+
+ " class="form-control-plaintext" id="name" readonly> +
+
+ +
+
+ +
+
+ " class="form-control-plaintext" id="client_name" readonly> +
+
+ +
+
+ +
+
+ " class="form-control-plaintext" id="emp_code" readonly> +
+
+ +
+
+ +
+
+ " class="form-control-plaintext" id="claim_number" readonly> +
+
+
+
+
+ +
+
+ + +
+ +
+ + +
+ +
+ + +
+ +
+ + +
+ +
+ + +
+
+ +
+ +
+ +
+ + +
+ +
+ + +
+ +
+ + +
+ +
+ + +
+ +
+ + +
+
+ +
+ +
+ +
+ + +
+ +
+ + +
+ +
+ +
+ +
+ +
+ + +
+ +
+ + +
+ +
+ + +
+ +
+ + +
+ +
+ + +
+
+ +
+ + +
+ +
+ + +
+ +
+ + +
+
+ + +
+ +
+ +
+ + +
+
+ +
+ +
+
+ +
+ +
+ + +
+
+ /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 05/25] 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 06/25] 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 07/25] 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 08/25] 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 09/25] 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 10/25] 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 11/25] 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 12/25] 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 13/25] 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 14/25] 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 15/25] 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 @@
+ + + +
- +