diff --git a/app/Config/Routes.php b/app/Config/Routes.php index 1f6d0bf9..d1195ea6 100755 --- a/app/Config/Routes.php +++ b/app/Config/Routes.php @@ -309,6 +309,11 @@ $routes->group("/util", ["filter" => "authMVC"], function ($routes) { $routes->post("update_emp_data", "EmployeeController::update_emp_data"); $routes->get("checkDeletionGetDataFunction", "EmployeeController::checkDeletionGetDataFunction"); $routes->get("download_import_excel/(:any)", "EmployeeController::downloadSampleImportExcelFile/$1"); + $routes->get("getInsurerBranchContacts/(:any)", "LeadsController::getInsurerBranchContacts/$1"); + $routes->get("download_import_file/(:any)", "EmployeeController::download_import_file/$1"); + $routes->get('log_list', 'EmployeeController::listLogs'); + $routes->get('view_log/(:any)', 'EmployeeController::viewLog/$1'); + $routes->get('download_log/(:any)', 'EmployeeController::downloadLog/$1'); }); $routes->group("policy_tranction", ["filter" => "authMVC"], function ($routes) { diff --git a/app/Controllers/EmpDataServiceController.php b/app/Controllers/EmpDataServiceController.php index 8bd4e545..9ae9e2d1 100755 --- a/app/Controllers/EmpDataServiceController.php +++ b/app/Controllers/EmpDataServiceController.php @@ -3976,22 +3976,75 @@ class EmpDataServiceController extends BaseController // print_r($arrayData); if (!empty($arrayData)) { + // dd($arrayData); + // echo '
';
// print_r($arrayData); die;
$client_branch_data = $this->clientBranchModel->where('id', $arrayData['client_branch_id'])->first();
$units = json_decode($client_branch_data['units']);
+ // dd($client_branch_data, $units);
+
+ $get_insurer_id_from_client_policy = db_connect()->table('client_policy')
+ ->select('insurer_id')
+ ->where('id', $arrayData['client_policy_id'])
+ ->get()
+ ->getRowArray();
+
+ // dd($get_insurer_id_from_client_policy);
+
+ $add_one_day = 0;
+
+ if (!empty($get_insurer_id_from_client_policy)) {
+
+ $get_the_insurer_add_one_for_delete = db_connect()
+ ->table('insurers')
+ ->select('deletion_add_day')
+ ->where('id', $get_insurer_id_from_client_policy['insurer_id'])
+ ->get()
+ ->getRowArray();
+
+ // dd($get_the_insurer_add_one_for_delete, $get_the_insurer_add_one_for_delete['deletion_add_day']);
+
+ if (!empty($get_the_insurer_add_one_for_delete) && $get_the_insurer_add_one_for_delete['deletion_add_day'] == 1) {
+ $add_one_day = 1;
+ }
+ }
+
+ // dd($add_one_day);
+
foreach($units as $unit) {
+ // $amount = $this->employeePolicyModel->query("
+ // SELECT SUM(rata_premimum + gst) AS total_sum
+ // FROM employee_polices
+ // JOIN employees ON employees.id = employee_polices.employee_id
+ // WHERE employees.unit = '$unit'
+ // AND employee_polices.id IN (" . implode(',', $arrayData['employeeIds']) . ")
+ // ")->getRow();
+
$amount = $this->employeePolicyModel->query("
- SELECT SUM(rata_premimum + gst) AS total_sum
- FROM employee_polices
- JOIN employees ON employees.id = employee_polices.employee_id
- WHERE employees.unit = '$unit'
- AND employee_polices.id IN (" . implode(',', $arrayData['employeeIds']) . ")
- ")->getRow();
-
+ SELECT
+ SUM(ROUND(
+ ((employee_polices.rata_premimum * (DATEDIFF(employee_polices.policy_end_date, emp_endorsement.new_value) + '$add_one_day')) / 365) +
+ (((employee_polices.rata_premimum * (DATEDIFF(employee_polices.policy_end_date, emp_endorsement.new_value) + '$add_one_day')) / 365) * 0.18),
+ 2
+ )) AS total_sum
+ FROM
+ employee_polices
+ JOIN
+ employees ON employees.id = employee_polices.employee_id
+ JOIN
+ emp_endorsement ON emp_endorsement.pk = employee_polices.id
+ WHERE
+ employee_polices.id IN (" . implode(',', $arrayData['employeeIds']) . ")
+ AND emp_endorsement.pk IN (" . implode(',', $arrayData['employeeIds']) . ")
+ AND emp_endorsement.field_name = 'date_of_exit'
+ ")->getRow();
+
+ // dd(db_connect()->getLastQuery(), $amount);
+
if($amount){
$insurer_id = $this->clientPolicyModel->where('id', $arrayData['client_policy_id'])->first();
@@ -4016,6 +4069,7 @@ class EmpDataServiceController extends BaseController
$response = DepositHelper::saveDeposit($data, $arrayData['user_id']);
}
}
+
$msg = "Deletion Cash Deposite Updated Successfully -- ";
return [$msg];
// print_r($response);
@@ -4255,136 +4309,103 @@ class EmpDataServiceController extends BaseController
public function sendMailForDownloadingECard(array $ids, $single_mail = null)
{
-
- $this->myLogger->logme('error', 'sendMailForDownloadingECard - function called');
- if (count($ids) > 0) {
-
- $temp_id = $ids[0];
-
- $get_client_info_for_notification = $this->employeePolicyModel
- ->select('employee_polices.client_policy_id, employees.emp_code, employees.email_corporate,employees.client_id as client_id, employees.name, employee_polices.rand_string, employee_polices.tpa_id')
- ->join('employees', 'employees.id = employee_polices.employee_id')
- ->where('employees.emp_status', 'active')
- ->where('employees.is_active', '1')
- ->where('employee_polices.status', 'active')
- ->where('employee_polices.is_active', '1')
- ->where('employee_polices.id', $ids[0])->first();
-
- $client_data = $this->clientModel->where('id', $get_client_info_for_notification['client_id'])->first();
- $notification = $this->notificationModel->where('client_id', $get_client_info_for_notification['client_id'])->where('template_name', 'member_ecard_mail')->first();
-
- if ($notification != null && !empty($notification) && $notification['enabled'] == 1) {
-
- try {
-
- $this->myLogger->logme('error', 'sendMailForDownloadingECard - inside try');
- $count = 0;
- $counts = 0;
-
- foreach ($ids as $key => $id) {
-
- $get_emp_email_and_other_details = $this->employeePolicyModel
- ->select('employee_polices.client_policy_id, employees.relationship, employees.emp_code, employees.email_corporate,employees.client_id as client_id, employees.name, employee_polices.rand_string, employee_polices.tpa_id')
- ->join('employees', 'employees.id = employee_polices.employee_id')
- ->where('employees.emp_status', 'active')
- ->where('employees.is_active', '1')
- ->where('employee_polices.status', 'active')
- ->where('employee_polices.is_active', '1')
- ->where('employee_polices.id', $id)->first();
-
- $this->myLogger->logme('error', 'sendMailForDownloadingECard - emp_policy_id : {id}', ['id' => $id]);
-
- if ($get_emp_email_and_other_details != null && !empty($get_emp_email_and_other_details)) {
-
- $this->myLogger->logme('error', 'sendMailForDownloadingECard - Send Bulk Mail function inside if condition ',);
-
- $rand_string = $get_emp_email_and_other_details['rand_string'];
- $tpa_id = $get_emp_email_and_other_details['tpa_id'];
-
- $params['rand_string'] = $rand_string;
- $params['tpa_id'] = $tpa_id;
- $params['notification'] = $notification;
- $params['client_data'] = $client_data;
- $params['notification'] = $notification;
- $params['notification'] = $notification;
- $params['get_emp_email_and_other_details'] = $get_emp_email_and_other_details;
- // $this->myLogger->logme('error', 'sendMailForDownloadingECard - Send Bulk Mail function end ',);
-
- if (isset($get_emp_email_and_other_details['email_corporate']) && !empty($get_emp_email_and_other_details['email_corporate']) && $get_emp_email_and_other_details['relationship'] == 'Self') {
- $wholeData[] = sendMailNotification::sendMailNotification('member_ecard_mail', $params);
- // print_r($wholeData);die;
- $count++;
- }
-
- $counts++;
-
- $this->myLogger->logme('error', 'sendMailForDownloadingECard - counts : {data}', ['data' => $counts]);
- $this->myLogger->logme('error', 'sendMailForDownloadingECard - count : {data}', ['data' => $count]);
- $this->myLogger->logme('error', 'sendMailForDownloadingECard - ids count : {data}', ['data' => count($ids)]);
- $this->myLogger->logme('error', 'sendMailForDownloadingECard - whole count : {data}', ['data' => count($wholeData)]);
-
- if ($count == 20 || $counts == count($ids) - 1) {
-
- $this->myLogger->logme('error', 'sendMailForDownloadingECard - ids count : {data}', ['data' => count($ids)]);
-
- if(count($wholeData) > 0){
-
- $this->myLogger->logme('error', 'sendMailForDownloadingECard - create a job to bulk mail',);
-
- $job_details = new Jobs();
- $r = Jobs::addJob(['job_name' => 'bulk_mail', 'payload' => $wholeData]);
- $wholeData = [];
- $count = 0;
-
- }
- }else{
-
- // for view member individual employee send self and self family ecard
- if($single_mail){
-
- if(count($wholeData) > 0){
-
- $this->myLogger->logme('error', 'sendMailForDownloadingECard - create a job for single mail to bulk mail function',);
+ $this->myLogger->logme('info', 'sendMailForDownloadingECard - Function called');
- $mail_send_return = MailHelper::send_email($wholeData[0]);
- $this->myLogger->logme("info", $mail_send_return);
- return $mail_send_return;
-
- // $job_details = new Jobs();
- // $r = Jobs::addJob(['job_name' => 'bulk_mail', 'payload' => $wholeData]);
- // $wholeData = [];
- // $count = 0;
-
- }
-
- }
-
- }
-
- $this->myLogger->logme('error', 'sendMailForDownloadingECard - Send Bulk Mail function end ',);
- }
- }
- return true; // Email(s) sent successfully
-
- } catch (\Exception $e) {
-
- // Log the error
- $this->myLogger->logme('error', 'sendMailForDownloadingECard : inside catch');
- $this->myLogger->logme('error', 'Error occurred while sending email: ' . $e->getMessage());
- return false; // Email(s) sending failed
- }
- } else {
-
- $this->myLogger->logme('error', 'sendMailForDownloadingECard - the client notification setup not created or not enabled the E-Card Notification');
- return false;
- }
-
- } else {
-
+ if (empty($ids)) {
$this->myLogger->logme('error', 'sendMailForDownloadingECard - employee_policy_ids are empty');
return false;
}
+
+ $temp_id = $ids[0];
+
+ $get_client_info = $this->employeePolicyModel
+ ->select('employee_polices.client_policy_id, employees.emp_code, employees.email_corporate, employees.client_id, employees.name, employee_polices.rand_string, employee_polices.tpa_id')
+ ->join('employees', 'employees.id = employee_polices.employee_id')
+ ->where('employees.emp_status', 'active')
+ ->where('employees.is_active', '1')
+ ->where('employee_polices.status', 'active')
+ ->where('employee_polices.is_active', '1')
+ ->where('employee_polices.id', $temp_id)
+ ->first();
+
+ if (!$get_client_info) {
+ $this->myLogger->logme('error', 'sendMailForDownloadingECard - No client information found for the first ID');
+ return false;
+ }
+
+ $client_data = $this->clientModel->where('id', $get_client_info['client_id'])->first();
+ $notification = $this->notificationModel
+ ->where('client_id', $get_client_info['client_id'])
+ ->where('template_name', 'member_ecard_mail')
+ ->first();
+
+ if (empty($notification) || $notification['enabled'] != 1) {
+ $this->myLogger->logme('error', 'sendMailForDownloadingECard - Notification setup not enabled or missing for E-Card Notification');
+ return false;
+ }
+
+ try {
+ $this->myLogger->logme('error', 'sendMailForDownloadingECard - Inside try block');
+
+ $count = 0;
+ $processedCount = 0;
+ $wholeData = [];
+
+ foreach ($ids as $id) {
+ $emp_details = $this->employeePolicyModel
+ ->select('employee_polices.client_policy_id, employees.relationship, employees.emp_code, employees.email_corporate, employees.client_id, employees.name, employee_polices.rand_string, employee_polices.tpa_id')
+ ->join('employees', 'employees.id = employee_polices.employee_id')
+ ->where('employees.emp_status', 'active')
+ ->where('employees.is_active', '1')
+ ->where('employee_polices.status', 'active')
+ ->where('employee_polices.is_active', '1')
+ ->where('employee_polices.id', $id)
+ ->first();
+
+ if ($emp_details) {
+ $this->myLogger->logme('error', 'sendMailForDownloadingECard - Processing employee_policy_id: {id}', ['id' => $id]);
+
+ if (!empty($emp_details['email_corporate']) && $emp_details['relationship'] === 'Self') {
+ $params = [
+ 'rand_string' => $emp_details['rand_string'],
+ 'tpa_id' => $emp_details['tpa_id'],
+ 'notification' => $notification,
+ 'client_data' => $client_data,
+ 'get_emp_email_and_other_details' => $emp_details,
+ ];
+ $wholeData[] = sendMailNotification::sendMailNotification('member_ecard_mail', $params);
+ $count++;
+ }
+ $processedCount++;
+
+ // Send batch emails or handle single email
+ if ($count == 20 || $processedCount == count($ids)) {
+ if (!empty($wholeData)) {
+ if ($single_mail == 1) {
+ $this->myLogger->logme('error', 'sendMailForDownloadingECard - Sending single mail');
+ $mail_result = MailHelper::send_email($wholeData[0]);
+ $this->myLogger->logme('info', 'sendMailForDownloadingECard - Single mail result: {result}', ['result' => $mail_result]);
+ return $mail_result;
+ } else {
+ $this->myLogger->logme('error', 'sendMailForDownloadingECard - Creating a job for bulk mail');
+ Jobs::addJob(['job_name' => 'bulk_mail', 'payload' => $wholeData]);
+ $wholeData = [];
+ $count = 0;
+ }
+ }
+ }
+ }
+ }
+
+ $this->myLogger->logme('error', 'sendMailForDownloadingECard - Email processing completed');
+ return true;
+
+ } catch (\Exception $e) {
+ $this->myLogger->logme('error', 'sendMailForDownloadingECard - Exception occurred: {message}', ['message' => $e->getMessage()]);
+ return false;
+ }
}
+
public function readExcelFileToArray($path)
{
diff --git a/app/Controllers/EmployeeController.php b/app/Controllers/EmployeeController.php
index 40a3bedb..9c616c4f 100755
--- a/app/Controllers/EmployeeController.php
+++ b/app/Controllers/EmployeeController.php
@@ -1062,6 +1062,7 @@ class EmployeeController extends AdminController
// Step 1: Attempt to fetch employee code and client policy ID
$this->myLogger->logme('error', 'Fetching employee code and client policy ID.');
+
$get_emp_code_and_client_policy_id = $this->employeePolicyModel
->select('employee_polices.client_policy_id, employees.emp_code, tpa.short_name,employees.client_id')
->join('client_policy', 'client_policy.id = employee_polices.client_policy_id')
@@ -1074,6 +1075,10 @@ class EmployeeController extends AdminController
->where('employee_polices.is_active', '1')
->where('employee_polices.rand_string', $rand_string)
->first();
+
+ // dd($this->employeePolicyModel->getLastQuery());
+
+ // dd($rand_string, $get_emp_code_and_client_policy_id);
if ($get_emp_code_and_client_policy_id == null || $get_emp_code_and_client_policy_id == "") {
$this->myLogger->logme('error', 'Member not found in this rand_string: ' . $rand_string);
@@ -1210,7 +1215,8 @@ class EmployeeController extends AdminController
// $file['action'] = 'si_enhancement';
// $result = [];
// !dd($file);
- if ($file['action'] == 'inception' || $file['action'] == 'dependent_addition' || $file['action'] == 'addition' || $file['action'] == 'enrollment') {
+ if ($file['action'] == 'inception' || $file['action'] == 'dependent_addition' || $file['action'] == 'addition' || $file['action'] == 'enrollment' || $file['action'] == 'missed_inception') {
+
if($file['action'] == 'enrollment'){
$result = $this->employeeModel->getEmpListByFileId(file_id: $file_id, emp_status: ['draft','enrolled'], policy_status: ['draft','enrolled']);
@@ -1430,9 +1436,9 @@ class EmployeeController extends AdminController
// array_pop($excel_data);
// }
- if($event_type == 'deletion'){
- array_pop($excel_data);
- }
+ // if($event_type == 'deletion'){
+ // array_pop($excel_data);
+ // }
$finalArray = [];
foreach ($error_data as $key => $values) {
@@ -1773,20 +1779,37 @@ class EmployeeController extends AdminController
public function checkDeletionGetDataFunction()
{
- $batch_data = [
- 'client_id' => 77,
- 'client_policy_id' => 203,
- 'client_branch_id' => 53,
- 'insurer_or_tpa' => 'tpa',
- ];
+ // $batch_data = [
+ // 'client_id' => 77,
+ // 'client_policy_id' => 203,
+ // 'client_branch_id' => 53,
+ // 'insurer_or_tpa' => 'tpa',
+ // ];
- $result = $this->employeePolicyModel->getDeletionEmployeeDataForExportExcel($batch_data);
+ // $result = $this->employeePolicyModel->getDeletionEmployeeDataForExportExcel($batch_data);
+
+ // print_rr($result); die;
+
+ //-------------------------------------------------------------------------------------------------------------
+
+ // $ids = [
+ // 'employeeIds' => [20252, 20258, 20277, 20282, 20196, 20237, 20314, 20325, 20356],
+ // 'client_id' => 17,
+ // 'client_policy_id' => 30,
+ // 'client_branch_id' => 18,
+ // 'cd_ac_no' => $CD_Account_Number['cd_ac_no'] ?? null,
+ // 'endorsement_no' => $endorsement_id ?? null,
+ // 'count' => 9,
+ // // 'event_name' => $file['event_type'],
+ // // 'policy_name' => $policy_name['policy_name'],
+ // // 'user_id' => $user_id,
+ // ];
+ // $empDataServiceController = new EmpDataServiceController();
+ // $result = $empDataServiceController->cashDepositCalculationForDeletion($ids);
- print_rr($result); die;
}
-
- // ----------------------------------------------------------------------------------------------------------
+ // ---------- DOWNLOAD IMPORT BATCH FILE AND SAMPLE FILE ------------------------------------------------------------------------------------------------
public function downloadSampleImportExcelFile($actionType = null)
{
@@ -1822,4 +1845,85 @@ class EmployeeController extends AdminController
echo view('errors/html/production');
}
}
+
+ public function download_import_file($file_id)
+ {
+ // $actionType = $this->request->getGet();
+ $file_data = $this->batchFileModel->where('id', $file_id)->first();
+ $fileName = $file_data['file_name'];
+
+ $filePath = WRITEPATH . '/uploads/import_excel/' . $fileName;
+
+ try {
+
+ // Check if the file exists
+ if (file_exists($filePath)) {
+ // Set the appropriate MIME type
+ $mimeType = mime_content_type($filePath);
+
+ // Send the file to the client for download
+ return $this->response->download($filePath, null, $mimeType);
+ } else {
+
+ $data['message'] = 'The Physical File Not Found';
+ echo view('errors/404', $data);
+ }
+ } catch (\Exception $e) {
+ // Handle any exceptions
+ $errorMessage = $e->getMessage();
+ $this->myLogger->logme('error', $errorMessage);
+ // You can return an error response here
+ echo $errorMessage;
+ }
+ }
+
+ //--------- LOG FILE VIEW AND DOWNLOAD ---------------------------------------------------------------------------------------------
+
+ public function listLogs()
+ {
+ $logPath = WRITEPATH . 'logs/';
+ $logs = [];
+
+ // Check if the log directory exists
+ if (is_dir($logPath)) {
+ $files = array_diff(scandir($logPath), ['.', '..']); // Exclude '.' and '..'
+
+ foreach ($files as $file) {
+ if (is_file($logPath . $file)) {
+ $logs[] = $file; // Add log files to the list
+ }
+ }
+ }
+
+ // Pass log files to the view
+ return view('log_view', ['logs' => $logs]);
+ }
+
+ public function downloadLog($fileName)
+ {
+ $logPath = WRITEPATH . 'logs/' . $fileName;
+
+ // Check if the requested file exists
+ if (file_exists($logPath)) {
+ return $this->response->download($logPath, null)->setFileName($fileName);
+ }
+
+ // Redirect back with an error if file doesn't exist
+ return redirect()->back()->with('error', 'Log file not found.');
+ }
+
+ public function viewLog($fileName)
+ {
+ $logPath = WRITEPATH . 'logs/' . $fileName;
+
+ if (file_exists($logPath)) {
+ $content = file_get_contents($logPath);
+
+ return view('log_content_view', ['fileName' => $fileName, 'content' => $content]);
+ }
+
+ return redirect()->back()->with('error', 'Log file not found.');
+ }
+
+
}
diff --git a/app/Controllers/LeadsController.php b/app/Controllers/LeadsController.php
index 9d2c246c..91c08094 100644
--- a/app/Controllers/LeadsController.php
+++ b/app/Controllers/LeadsController.php
@@ -5,6 +5,8 @@ namespace App\Controllers;
use CodeIgniter\API\ResponseTrait;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
+use PhpOffice\PhpSpreadsheet\Style\Border;
+use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use App\Models\UserModel;
@@ -164,14 +166,27 @@ class LeadsController extends BaseController
}
private function prepareMultipleLeadData($data)
- {
+ {
+ // print_r($data); die;
$processedData = [];
foreach($data['policy_type_id'] as $index => $value){
- // Separate the insurer and insurer branch
- list($insurer_branch_id, $insurer_id) = explode('-',$data['insurer'][$index]);
- // Separate the tpa and tpa branch
- list($tpa_branch_id, $tpa_id) = explode('-',$data['tpa'][$index]);
+
+ // 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]);
+ } else {
+ $insurer_branch_id = 0;
+ $insurer_id = 0;
+ }
+ // Separate the insurer and insurer branch, handle missing or invalid data
+ if (isset($data['tpa'][$index]) && strpos($data['tpa'][$index], '-') !== false) {
+ list($tpa_branch_id, $tpa_id) = explode('-', $data['tpa'][$index]);
+ } else {
+ $tpa_branch_id = 0;
+ $tpa_id = 0;
+ }
+
// Separate the insurer and insurer branch, handle missing or invalid data
if (isset($data['proposed_insurer'][$index]) && strpos($data['proposed_insurer'][$index], '-') !== false) {
@@ -337,16 +352,25 @@ class LeadsController extends BaseController
$data['lead_id'] = $id;
$lead_data = $this->leadsModel
- ->select('policy_type.question_json')
+ ->select('leads.*, policy_type.question_json')
->join('policy_type', 'leads.policy_type_id = policy_type.id')
->where('leads.id', $id)
+ ->where('leads.is_active', 1)
->first();
+ // dd($lead_data);
+
+ if($lead_data['lead_type'] == 2){
+ $client_policy_data = $this->clientPolicyModel->where('is_active', 1)->where('id', $lead_data['source_policy_id'])->first();
+ $data['policy_terms'] = $client_policy_data['policy_terms'];
+ }
+
$data['question_json'] = $lead_data['question_json'];
$data['page_name'] = isset($data['rfq_data']['type']) && $data['rfq_data']['type'] == 2 ? 'QCR' : 'RFQ';
$data['insurer'] = $this->insurerBranchModel->getInsurerBranchesWithInsurerNames();
+ $data['userList'] = $this->userModel->getUserListForRFQ();
+ $data['lead_data'] = $lead_data;
- $data['lead_data'] = $this->leadsModel->where('leads.id', $id)->where('leads.is_active', 1)->first();
// dd($data);
$this->loadLayout('view_rfq.php', $data);
}
@@ -401,12 +425,7 @@ class LeadsController extends BaseController
//export main route function
public function exportQCRandRFQ($lead_id, $type, $export_type){
-
- if($export_type == 'mail'){
- $this-> exportMailForQCRandRFQ($lead_id, $type);
- }else{
- $this-> exportExcelForQCRandRFQ($lead_id, $type);
- }
+ $this-> exportExcelForQCRandRFQ($lead_id, $type);
}
//FOR EXCEL
@@ -435,53 +454,27 @@ class LeadsController extends BaseController
}
}
- //FOR MAIL
- public function exportMailForQCRandRFQ($lead_id, $type){
-
- $filepath = $this->constructExcelToSaveTemp($lead_id, $type);
-
- if ($filepath) {
- return $this->respond(['status' => true, 'file_path' => $filepath, 'message' => 'Mail send successfully'], 200);
- }
-
- return $this->respond(['status' => false, 'file_path' => $filepath, 'message' => "Mail send failed"], 200);
- }
-
//Construct excel file and save the file to the folder and return file path
- public function constructExcelToSaveTemp($lead_id, $type)
+ public function constructExcelToSaveTemp($lead_id, $type, $propsal_and_insurer = null)
{
- $rfq_data = $this->RFQModel
- ->select('
- leads.client_name,
- leads.client_short_name,
- insurers.name as insurer_name,
- insurer_branch.branch_name as insurer_branch_name,
- tpa.name as tpa_name,
- tpa_branch.branch_name as tpa_branch_name,
- policy_type.policy_type,
- rfq.json
- ')
- ->join('leads', 'rfq.lead_id = leads.id')
- ->join('policy_type', 'leads.policy_type_id = policy_type.id')
- ->join('insurers', 'leads.insurer_id = insurers.id')
- ->join('insurer_branch', 'leads.insurer_branch_id = insurer_branch.id')
- ->join('tpa', 'leads.tpa_id = tpa.id')
- ->join('tpa_branch', 'leads.tpa_branch_id = tpa_branch.id')
- ->where('rfq.lead_id', $lead_id)
- ->where('rfq.type', $type)
- ->where('rfq.is_active', 1)
- ->first();
+ $rfq_data = $this->RFQModel->getRFQTableDataWithLeadIDAndType($lead_id, $type);
$lead_data = [
'Insured' => $rfq_data['client_name'],
'Insurer' => $rfq_data['insurer_name'] . ' - ' . $rfq_data['insurer_branch_name'],
'TPA' => $rfq_data['tpa_name'] . ' - ' . $rfq_data['tpa_branch_name'],
];
+
+ $data = json_decode($rfq_data['json'], true);
+
+ if($type == 2){
+ $data = $this->convertJsonForQCR($data, 'stc');
+ if($propsal_and_insurer !== null){
+ list($proposal_key, $insurer_key) = explode('-', $propsal_and_insurer, 2);
+ $data = $this->transformProposelData($data, $proposal_key, $insurer_key);
+ }
+ }
- $jsonData = $rfq_data['json'];
- $data = json_decode($jsonData, true);
-
- // Initialize PhpSpreadsheet
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
@@ -490,96 +483,173 @@ class LeadsController extends BaseController
foreach ($lead_data as $key => $value) {
$sheet->setCellValue("A{$rowNumber}", $key);
$sheet->setCellValue("B{$rowNumber}", $value);
-
- // Apply bold style to the key
- $sheet->getStyle("A{$rowNumber}")->applyFromArray([
- 'font' => [
- 'bold' => true,
- ],
- ]);
-
+ $sheet->getStyle("A{$rowNumber}")->applyFromArray(['font' => ['bold' => true]]);
$rowNumber++;
}
- // Leave two blank rows
+ $leadRange = "A1:B" . (count($lead_data));
+ $sheet->getStyle($leadRange)->applyFromArray([
+ 'borders' => [
+ 'allBorders' => [
+ 'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
+ 'color' => ['argb' => 'FF000000'], // Black color
+ ],
+ ],
+ ]);
+
+
$rowNumber += 2;
- // Set headers and subheaders starting from current row
+ // Add headers and subheaders
$headers = $data['table_data']['headers'];
$subHeaderRow = $rowNumber + 1;
$columnLetter = 'A';
-
- // Set column width and apply word wrap to headers and subheaders
+
foreach ($headers as $header) {
- if ($header['parentHeader'] === 'Item Key' || $header['parentHeader'] == 'Action') {
- continue; // Skip "Item Key" and "Action" columns
+ if (in_array($header['parentHeader'], ['Item Key', 'Action'])) {
+ continue;
}
-
+
if ($header['parentHeader'] === 'Sno') {
$header['parentHeader'] = 'S.No.';
}
-
- // Set the header cell value
- $sheet->setCellValue("{$columnLetter}{$rowNumber}", $header['parentHeader']);
-
- // Set column width for header
- $sheet->getColumnDimension($columnLetter)->setWidth(20); // Adjust width as needed
- $sheet->getStyle("{$columnLetter}{$rowNumber}")->getAlignment()->setWrapText(true);
-
- // Apply bold style to the header
- $sheet->getStyle("{$columnLetter}{$rowNumber}")->applyFromArray([
- 'font' => [
- 'bold' => true,
+
+ $startColumn = $columnLetter; // Start of the current header range
+ $subHeaderCount = count($header['subHeaders']); // Number of subheaders for this parent header
+
+ // Set parent header value
+ $sheet->setCellValue("{$startColumn}{$rowNumber}", $header['parentHeader']);
+ $sheet->getStyle("{$startColumn}{$rowNumber}")->applyFromArray([
+ 'font' => ['bold' => true],
+ 'alignment' => [
+ 'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
+ 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
],
]);
-
- // Add subheaders in the second row
+
+ // Merge header cells if it spans multiple subheaders
+ if ($subHeaderCount > 1) {
+ $endColumn = chr(ord($startColumn) + $subHeaderCount - 1); // Calculate the end column
+ $sheet->mergeCells("{$startColumn}{$rowNumber}:{$endColumn}{$rowNumber}");
+ } else {
+ $endColumn = $startColumn; // No merge needed if only one subheader
+ }
+
+ // Add subheaders
foreach ($header['subHeaders'] as $subHeader) {
$sheet->setCellValue("{$columnLetter}{$subHeaderRow}", $subHeader);
-
- // Enable word wrap for subheaders
- $sheet->getStyle("{$columnLetter}{$subHeaderRow}")->getAlignment()->setWrapText(true);
-
- // Apply bold style to the subheader
$sheet->getStyle("{$columnLetter}{$subHeaderRow}")->applyFromArray([
- 'font' => [
- 'bold' => true,
+ 'font' => ['bold' => true],
+ 'alignment' => [
+ 'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
+ 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
],
]);
-
- $columnLetter++;
+ $columnLetter++; // Move to the next column for subheaders
}
}
+
+ // Apply border to the header range
+ $headerRange = "A{$rowNumber}:" . chr(ord($columnLetter) - 1) . "{$subHeaderRow}";
+ $sheet->getStyle($headerRange)->applyFromArray([
+ 'borders' => [
+ 'allBorders' => [
+ 'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
+ 'color' => ['argb' => 'FF000000'], // Black color
+ ],
+ ],
+ ]);
- // Move to next row for data entries
- $rowNumber = $subHeaderRow + 1;
+ // Increase row height for headers and subheaders
+ $sheet->getRowDimension($rowNumber)->setRowHeight(30); // Header row height
+ $sheet->getRowDimension($subHeaderRow)->setRowHeight(25); // Subheader row height
+
+ $rowNumber = $subHeaderRow + 2;
+ $column_data = $data['table_data']['data'];
+ $serial_no = 1;
- // Add data rows and enable word wrap for data cells
- foreach ($data['table_data']['data'] as $dataRow) {
+ // Add table data rows
+ foreach ($column_data as $dataRow) {
$columnLetter = 'A';
foreach ($dataRow['data'] as $cellData) {
- if ($cellData['parentth'] === 'Item Key' || $cellData['parentth'] == 'Action') {
- continue; // Skip "Item Key" data
+ if (in_array($cellData['parentth'], ['Item Key', 'Action'])) {
+ continue;
}
- $sheet->setCellValue("{$columnLetter}{$rowNumber}", $cellData['value']);
-
- // Enable word wrap for data cells
- $sheet->getStyle("{$columnLetter}{$rowNumber}")->getAlignment()->setWrapText(true);
-
+
+ if ($cellData['parentth'] == 'Sno') {
+ $sheet->setCellValue("{$columnLetter}{$rowNumber}", $serial_no);
+ } else {
+ $sheet->setCellValue("{$columnLetter}{$rowNumber}", $cellData['value']);
+ }
+
$columnLetter++;
}
$rowNumber++;
+ $serial_no++;
}
- // Auto-size all columns after data is entered
+ $dataRange = "A" . ($subHeaderRow + 1) . ":" . chr(ord($columnLetter) - 1) . ($rowNumber - 1);
+ $sheet->getStyle($dataRange)->applyFromArray([
+ 'borders' => [
+ 'allBorders' => [
+ 'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
+ 'color' => ['argb' => 'FF000000'], // Black color
+ ],
+ ],
+ ]);
+
+
+ if($type == 2){
+
+ $rowNumber += 2;
+
+ // Add premium data
+ $premiumData = $data['premium_data']['data'];
+ $premium = ['Premium'];
+ $gst = ['GST'];
+ $total = ['Total'];
+
+ foreach ($premiumData as $proposal => $insurers) {
+ foreach ($insurers as $insurer => $values) {
+ $premium[] = $values['Premium'];
+ $gst[] = $values['GST'];
+ $total[] = $values['Total'];
+ }
+ }
+
+ foreach ([$premium, $gst, $total] as $index => $rowData) {
+ $columnLetter = 'B';
+ foreach ($rowData as $key => $value) {
+ $sheet->setCellValue("{$columnLetter}{$rowNumber}", $value);
+ if ($key === 0) {
+ $sheet->getStyle("{$columnLetter}{$rowNumber}")->applyFromArray(['font' => ['bold' => true,],]);
+ }
+ $columnLetter++;
+ }
+ $rowNumber++;
+ }
+
+ $premiumRange = "B" . ($rowNumber - 3) . ":" . chr(ord($columnLetter) - 1) . ($rowNumber - 1);
+ $sheet->getStyle($premiumRange)->applyFromArray([
+ 'borders' => [
+ 'allBorders' => [
+ 'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
+ 'color' => ['argb' => 'FF000000'], // Black color
+ ],
+ ],
+ ]);
+
+ }
+
+ // Auto-size columns
foreach ($sheet->getColumnIterator() as $column) {
$sheet->getColumnDimension($column->getColumnIndex())->setAutoSize(true);
}
-
- // Set filename based on type
+
+ // Set filename
$string = ($type == 2) ? 'QCR' : 'RFQ';
- $filename = $string . '_' . $rfq_data['client_short_name'] . '_' . $rfq_data['policy_type'] . '_' . date('Ymdhis') . '.xlsx';
-
+ $filename = "{$string}_{$rfq_data['client_short_name']}_{$rfq_data['policy_type']}_" . date('YmdHis') . '.xlsx';
+
// Save to temporary location
$uploadFilePath = WRITEPATH . 'tmp/' . $filename;
$writer = new Xlsx($spreadsheet);
@@ -588,98 +658,150 @@ class LeadsController extends BaseController
return [
'filePath' => $uploadFilePath,
'fileName' => $filename,
- ]; // Return file path and file name
+ ];
}
//this funciton for send mail to insurer and client with either RFQ/QCR
public function sendMailWithAttachement()
{
- helper('excel_util_helper');
- helper('MailHelper');
+ helper('excel_util_helper');
+ helper('MailHelper');
- $params = $this->request->getGet();
- // dd($params);
- $lead_id = $params['lead_id'];
- $file_type = $params['file_type']; //rfq or qcr
- $recipient_type = $params['recipient_type'];//insurer or client
- $recipient_mail = $params['recipient_mail'];// - only primary key of contacts
- $recipient_mail = json_decode($params['recipient_mail'], true);;// - only primary key of contacts
- // $cc = 'velz1990@gmail.com,vitvelz@gmail.com';
- $cc = "";
-
- $result_data = [];
- // dd($recipient_mail);
- if($recipient_type == 'insurer' && (!is_array($recipient_mail) || count($recipient_mail) == 0))
- {
- return $this->respond(['status' => 'failed','code' => 400,'data' => '','messgae' => 'Recipient mail not found ! ' ], 200);
- }
- // dd();
- //gather lead info
- $lead_data = $this->leadsModel
- ->select('leads.*,policy_type.long_name,policy_type.policy_type,user_profiles.email as created_person_email')
- ->join('policy_type','leads.policy_type_id = policy_type.id')
- ->join('user_profiles','leads.created_by = user_profiles.id')
- ->where('leads.id', $lead_id)
- ->first();
- if( $recipient_type == 'client' && ($lead_data['contact_person_email'] == '' || $lead_data['contact_person_email'] == null))
- {
- return $this->respond(['status' => 'failed','code' => 400,'data' => '','messgae' => 'Recipient mail not found ! ' ], 200);
- }
- // dd($lead_data);
- $reply_to = $lead_data['created_person_email'];
- //get file path to attach
- $file_info = $this->constructExcelToSaveTemp($lead_id, ( $file_type == 'rfq' ? 1 : 2) );
- // $file_path = WRITEPATH."uploads/excel/sample/correction.xls";
- // $file_name = $file_type.'.xlsx';
- // !dd($file_info);
- $file_path = $file_info['filePath'];
- $file_name = $file_info['fileName'];
- $attachments = [['fileName' => $file_name,'filePath' => $file_path]];
-
- //get recipient address
- if($recipient_type == 'insurer')
- {
- $recipient_data = $this->levelContactModel
- ->where(['contact_type' => $recipient_type, 'is_active' => 1])
- ->whereIn('id', $recipient_mail)
- ->findAll();
- }
- else
- {
- $recipient_data = [['name' => $lead_data['contact_person_name'],'email' => $lead_data['contact_person_email']] ];
- }
- // !dd($recipient_data);
+ $params = $this->request->getGet();
+ // print_r($params); die;
+ $lead_id = $params['lead_id'];
+ $file_type = $params['file_type']; //rfq or qcr
+ $recipient_type = $params['recipient_type']; //insurer or client or internal or placement
+ $recipient_mail = $params['recipient_mail']; // - only primary key of contacts
+ $recipient_mail = json_decode($params['recipient_mail'], true); // - only primary key of contacts
+ $propsal_and_insurer = isset($params['proposal_insurer']) ? $params['proposal_insurer'] : null;
- $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.
';
+ $result_data = [];
+ // dd($recipient_mail);
+ if ($recipient_type == 'insurer' && (!is_array($recipient_mail) || count($recipient_mail) == 0)) {
+ return $this->respond(['status' => 'failed', 'code' => 400, 'data' => '', 'messgae' => 'Recipient mail not found ! '], 200);
+ }
+ // dd();
+ //gather lead info
+ $lead_data = $this->leadsModel
+ ->select('leads.*,policy_type.long_name,policy_type.policy_type,user_profiles.email as created_person_email')
+ ->join('policy_type', 'leads.policy_type_id = policy_type.id')
+ ->join('user_profiles', 'leads.created_by = user_profiles.id')
+ ->where('leads.id', $lead_id)
+ ->first();
+
+ $cc_mails = [];
+
+ //get CC Mails
+ if($recipient_type == 'internal' || $recipient_type == 'placement'){
+
+ $cc_data = isset($params['cc']) ? $params['cc'] : "";
+ $param_cc_mail = json_decode($cc_data, true);
+ if (isset($param_cc_mail) && is_array($param_cc_mail) && count($param_cc_mail) > 0) {
+ // Fetch user data where ID is in the param_cc_mail array
+ $userData = $this->userModel
+ ->where('is_active', 1)
+ ->whereIn('id', $param_cc_mail)
+ ->findAll();
+
+ // print_r($userData); die;
+
+ // Extract emails from the fetched user data
+ $cc_mails = array_column($userData, 'email');
+
+ // print_r(json_encode($cc_mails)); die;
+ // If no emails were found, return an error response
+ if (empty($cc_mails)) {
+ return $this->respond(['status' => 'failed','code' => 400,'data' => '','message' => 'No valid CC mail addresses found!'], 200);
+ }
+
+ } else {
+ // Handle case where param_cc_mail is not valid
+ return $this->respond(['status' => 'failed','code' => 400,'data' => '','message' => 'CC mail not found!'], 200);
+ }
+ }
- foreach($recipient_data as $recipient)
- {
+ if ($recipient_type == 'client' && ($lead_data['contact_person_email'] == '' || $lead_data['contact_person_email'] == null)) {
+ return $this->respond(['status' => 'failed', 'code' => 400, 'data' => '', 'messgae' => 'Recipient mail not found ! '], 200);
+ }
+
+ // dd($lead_data);
+ $reply_to = $lead_data['created_person_email'];
+
+ //get file path to attach
+ $file_info = $this->constructExcelToSaveTemp($lead_id, ($file_type == 'rfq' ? 1 : 2), $propsal_and_insurer);
+ // $file_path = WRITEPATH."uploads/excel/sample/correction.xls";
+ // $file_name = $file_type.'.xlsx';
+ // !dd($file_info);
+
+ $file_path = $file_info['filePath'];
+ $file_name = $file_info['fileName'];
+ $attachments = [['fileName' => $file_name, 'filePath' => $file_path]];
+
+ //get recipient address
+ if ($recipient_type == 'insurer' || $recipient_type == 'placement') {
+
+ // print_r($recipient_mail); die;
+
+ $recipient_data = $this->levelContactModel
+ ->where(['contact_type' => 'insurer', 'is_active' => 1])
+ ->whereIn('id', $recipient_mail)
+ ->findAll();
+
+ // print_r($recipient_data); die;
+
+ } else if($recipient_type == 'client') {
+ $recipient_data = [['name' => $lead_data['contact_person_name'], 'email' => $lead_data['contact_person_email']]];
+ }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.
';
+
+ if($recipient_data){
+ foreach ($recipient_data as $recipient) {
+
$message = $original_message;
$message = str_replace("{{RECIPIENT_NAME}}", $recipient['name'], $message);
$message = str_replace("{{CLIENT_NAME}}", $lead_data['client_name'], $message);
$message = str_replace("{{POLICY_LONG_NAME}}", $lead_data['long_name'], $message);
- $message = str_replace("{{POLICY_START_DATE}}", change_date_format($lead_data['policy_start_date'],'Y-m-d','d-m-Y'), $message);
- $message = str_replace("{{DURATION}}", calculate_days_bw_dates($lead_data['policy_end_date'],$lead_data['policy_start_date'])->days, $message);
-
- // print_rr($message);
-
- $res = MailHelper::send_email(['mail' => $recipient['email'], 'subject' => $subject, 'message' => $message,'attachments' => $attachments,'reply_to' => $reply_to]);
- // !dd($res);
-
- $result_data[] = ['mail' => $recipient['email'],'status' => $res];
- }
- //delete attachment file
- unlink($file_path);
- return $this->respond(['status' => 'success','code' => 200,'data' => $result_data ], 200);
+ $message = str_replace("{{POLICY_START_DATE}}", change_date_format($lead_data['policy_start_date'], 'Y-m-d', 'd-m-Y'), $message);
+ $message = str_replace("{{DURATION}}", calculate_days_bw_dates($lead_data['policy_end_date'], $lead_data['policy_start_date'])->days, $message);
+ // print_rr($message);
+
+ $res = MailHelper::send_email(['mail' => $recipient['email'], 'cc'=> $cc_mails, 'subject' => $subject, 'message' => $message, 'attachments' => $attachments, 'reply_to' => $reply_to]);
+ // !dd($res);
+ $result_data[] = ['mail' => $recipient['email'], 'status' => $res];
+ }
+ }
+
+ if($recipient_type == 'placement'){
+
+ list($proposal_key, $insurer_key) = explode('-', $propsal_and_insurer, 2);
+
+ $lead_update_data = [
+ 'proposel_name' => $proposal_key,
+ 'insurer_name' => $insurer_key,
+ 'insurer' => $params['insurer_and_branch'],
+ ] ;
+
+ $lead_update_data = json_encode($lead_update_data);
+ $this->leadsModel->where('id', $lead_id)->set('proposel_data', $lead_update_data)->update();
+ }
+
+ //delete attachment file
+ unlink($file_path);
+ return $this->respond(['status' => 'success', 'code' => 200, 'data' => $result_data], 200);
}
public function getLevelContects()
{
- $data = $this->levelContactModel->getContectForRFQ();
+ $data = $this->levelContactModel->getContactForRFQ();
if($data){
return $this->respond(['status' => true, 'data' => $data], 200);
@@ -689,11 +811,219 @@ class LeadsController extends BaseController
}
+ public function getInsurerBranchContacts($insurer_and_branch_id)
+ {
+ if (strpos($insurer_and_branch_id, '-') === false) {
+ return $this->respond(['status' => false, 'message' => 'Invalid ID format'], 400);
+ }
+
+ // Split the insurer_and_branch_id
+ list($insurerBranchId, $insurerId) = explode('-', $insurer_and_branch_id);
+
+ $data = $this->levelContactModel->getContactForRFQ($insurerId, $insurerBranchId);
+
+ if (!empty($data)) {
+ return $this->respond(['status' => true, 'data' => $data], 200);
+ } else {
+ return $this->respond(['status' => false, 'data' => $data, 'message' => 'No contacts were found for the selected insurer.'], 200);
+ }
+ }
+ function transformProposelData($data, $proposel, $insurer){
+
+ // print_r($data['premium_data']['data']); die;
+
+ $headerData = [];
+
+ // Default headers: S. No and Particulars
+ $defaultHeaders = [
+ [
+ 'parentHeader' => 'Sno',
+ 'subHeaders' => ['-']
+ ],
+ [
+ 'parentHeader' => 'Particulars',
+ 'subHeaders' => ['-']
+ ]
+ ];
+
+ // Add default headers to the result
+ $headerData = array_merge($headerData, $defaultHeaders);
+
+ foreach ($data['table_data']['headers'] as $header) {
+ // Check if the parentHeader matches the target proposal
+ if ($header['parentHeader'] === $proposel) {
+ // Check if subHeaders contain the target insurer key
+ foreach ($header['subHeaders'] as $subHeader) {
+ if ($subHeader === $insurer) {
+ $headerData[] = [
+ 'parentHeader' => $header['parentHeader'],
+ 'subHeaders' => [
+ 'Quote Asked', // Default value
+ $subHeader // Matched insurer key
+ ]
+ ];
+ break;
+ }
+ }
+ }
+ }
+
+ $columnData = [];
+
+ foreach ($data['table_data']['data'] as $entry) {
+
+ $sno = $entry['SNO'];
+ $items = $entry['items'];
+ $dataEntry = $entry['data'];
+
+ $result = [
+ "SNO" => $sno,
+ "items" => $items,
+ "data" => []
+ ];
+
+ foreach ($dataEntry as $item) {
+
+ // Include Sno and Particulars by default
+ if (in_array($item['parentth'], ['Sno', 'Particulars'])) {
+ $result['data'][] = [
+ "parentth" => $item['parentth'],
+ "subth" => $item['subth'],
+ "value" => $item['value'],
+ "input_value" => $item['input_value']
+ ];
+ }
+
+ // Include Proposal with Quote Asked by default
+ if ($item['parentth'] === $proposel && $item['subth'] === "Quote Asked") {
+ $result['data'][] = [
+ "parentth" => $item['parentth'],
+ "subth" => $item['subth'],
+ "value" => $item['value'],
+ "input_value" => $item['input_value']
+ ];
+ }
+
+ // Example of including matching specific proposals and insurers
+ if ($item['parentth'] === $proposel && $item['subth'] === $insurer) {
+ $result['data'][] = [
+ "parentth" => $item['parentth'],
+ "subth" => $item['subth'],
+ "value" => $item['value'],
+ "input_value" => $item['input_value']
+ ];
+ }
+ }
+
+ // Add to the final result
+ $columnData[] = $result;
+ }
+
+ $premiumData = [];
+
+ foreach ($data['premium_data']['data'] as $key => $value) {
+ if ($key === $proposel) {
+ $premiumData[$key]['Quote Asked'] = $value['Quote Asked'];
+ $premiumData[$key][$insurer] = $value[$insurer];
+ }
+ }
+
+ $data['table_data']['headers'] = $headerData;
+ $data['table_data']['data'] = $columnData;
+ $data['premium_data']['data'] = $premiumData;
+
+ return $data;
+
+ }
+
+ function convertJsonForQCR($json, $type)
+ {
+ if ($json) {
+ // Deep copy of JSON
+ $first_json = json_decode(json_encode($json), true);
+
+ // Column-wise Check: Remove headers and relevant data if qcr == 0
+ foreach ($json['proposal_data']['over_all_column_data'] as $proposalKey => $proposalData) {
+ if ($proposalData['stc'] == 0 || $proposalData['stc'] === false) {
+ // Remove matching parentHeader in headers
+ foreach ($first_json['table_data']['headers'] as $index => $header) {
+ if ($header['parentHeader'] === $proposalKey) {
+ unset($first_json['table_data']['headers'][$index]);
+ }
+ }
+
+ // Remove data entries with matching parentth
+ foreach ($first_json['table_data']['data'] as &$item) {
+ $item['data'] = array_values(array_filter($item['data'], function ($entry) use ($proposalKey) {
+ return $entry['parentth'] !== $proposalKey;
+ }));
+ }
+
+ // Remove proposalKey from over_all_column_data
+ unset($first_json['proposal_data']['over_all_column_data'][$proposalKey]);
+
+ if($type == 'stc'){
+ // Remove proposalKey from premium_data
+ unset($first_json['premium_data']['data'][$proposalKey]);
+ }
+ }
+
+ // Insurer Check: Remove subHeaders and relevant data for insurers with qcr == 0
+ foreach ($proposalData['insurers'] as $insurerIndex => $insurer) {
+ if ($insurer['stc'] === 0 || $insurer['stc'] === false) {
+ foreach ($first_json['table_data']['headers'] as &$header) {
+ if (isset($header['subHeaders'])) {
+ $header['subHeaders'] = array_values(array_filter($header['subHeaders'], function ($sub) use ($insurer) {
+ return $sub !== $insurer['display_name'];
+ }));
+ }
+ }
+
+
+ foreach ($first_json['table_data']['data'] as &$item) {
+ $item['data'] = array_values(array_filter($item['data'], function ($entry) use ($insurer) {
+ return $entry['subth'] !== $insurer['display_name'];
+ }));
+ }
+
+ // Remove insurer from proposal's insurers array
+ unset($first_json['proposal_data']['over_all_column_data'][$proposalKey]['insurers'][$insurerIndex]);
+
+ if($type == 'stc'){
+ unset($first_json['premium_data']['data'][$proposalKey][$insurer['display_name']]);
+ }
+ }
+ }
+ }
+
+ // Row-wise Check: Remove rows if qcr == 0 for actions
+ foreach ($first_json['table_data']['data'] as $rowKey => $rowData) {
+ foreach ($rowData['data'] as $data) {
+ if ($data['parentth'] === "Action" && isset($data['input_value']['stc']) && $data['input_value']['stc'] == 0) {
+ unset($first_json['table_data']['data'][$rowKey]);
+ break;
+ }
+ }
+ }
+
+ // Reindex arrays to maintain proper structure
+ $first_json['table_data']['headers'] = array_values($first_json['table_data']['headers']);
+ $first_json['table_data']['data'] = array_values($first_json['table_data']['data']);
+ $first_json['proposal_data']['over_all_column_data'] = array_map(function ($proposal) {
+ $proposal['insurers'] = array_values($proposal['insurers']);
+ return $proposal;
+ }, $first_json['proposal_data']['over_all_column_data']);
+
+ return $first_json;
+ }
+
+ return null;
+ }
+
//----- Featch Lead data and insert Client -------------------------------------------------------------------------------------------
-
public function featchLeadDataAndInsertClient($lead_id)
{
$data = $this->leadsModel->where('leads.id', $lead_id)->where('leads.is_active', 1)->first();
diff --git a/app/Controllers/MasterController.php b/app/Controllers/MasterController.php
index e3123418..1599bac2 100755
--- a/app/Controllers/MasterController.php
+++ b/app/Controllers/MasterController.php
@@ -173,7 +173,7 @@ class MasterController extends AdminController
$editData['policy_type'] = $this->policyTypeModel->whereIn('id', [1,2,6,7])->findAll();
- $editData['events'] = ['inception' => 'Inception', 'addition' => 'Addition', 'dependent_addition' => 'Dependent Addition', 'deletion' => 'Deletion', 'correction' => 'Correction', 'si_enhancement' => 'SI Enhancement', 'all' => 'All'];
+ $editData['events'] = ['inception' => 'Inception', 'missed_inception' => 'Missed Inception', 'addition' => 'Addition', 'dependent_addition' => 'Dependent Addition', 'deletion' => 'Deletion', 'correction' => 'Correction', 'si_enhancement' => 'SI Enhancement', 'all' => 'All'];
$editData['action'] = ['import' => 'Import', 'export' => 'Export'];
$editData['db_column_name'] = [
diff --git a/app/Helpers/MailHelper.php b/app/Helpers/MailHelper.php
index a65a5b31..0bc21c46 100755
--- a/app/Helpers/MailHelper.php
+++ b/app/Helpers/MailHelper.php
@@ -106,7 +106,9 @@ class MailHelper
//check CC mail
if (isset($params['cc'])) {
$cc = $params['cc'];
- $cc = explode(',', $cc);
+ if(!is_array($cc)){
+ $cc = explode(',', $cc);
+ }
}else{
$cc = [];
}
diff --git a/app/Helpers/sendMailNotification.php b/app/Helpers/sendMailNotification.php
index 31114293..fbc374a8 100755
--- a/app/Helpers/sendMailNotification.php
+++ b/app/Helpers/sendMailNotification.php
@@ -151,6 +151,11 @@ class sendMailNotification
$mail_content = $notification['mail_content'];
$mail = $get_emp_email_and_other_details['email_corporate'];
$subject = $notification['subject'];
+
+ $cleanedText = mb_convert_encoding($subject, 'UTF-8', 'UTF-8'); // Normalize encoding
+ $cleanedText = preg_replace('/[^\x20-\x7E]/', '', $cleanedText);
+
+ $subject = $cleanedText;
$link = generate_download_link($rand_string);
@@ -258,6 +263,7 @@ class sendMailNotification
$si = '';
$premium = '';
$gst_forself = '';
+
if(checkFamilyFloaters($policy_premium_data, $client_policy_data, $inner_item)){
$si = '₹ ' .format_indian_number($inner_item['basic_cover_si']);
$premium = '₹ ' .format_indian_number(round($inner_item['premium']));
diff --git a/app/Models/EmployeePolicyModel.php b/app/Models/EmployeePolicyModel.php
index 688b8abf..c0ae9e98 100755
--- a/app/Models/EmployeePolicyModel.php
+++ b/app/Models/EmployeePolicyModel.php
@@ -75,11 +75,11 @@ class EmployeePolicyModel extends Model
return $data;
}
-// ----------------------------------------------------------------------------------------------------------
- public function getEmployeePolicy($client_id = 0, $policy_id=0, $status=[], $branch_id=0, $emp_code="", $emp_name="")
- {
+ // ----------------------------------------------------------------------------------------------------------
+ public function getEmployeePolicy($client_id = 0, $policy_id = 0, $status = [], $branch_id = 0, $emp_code = "", $emp_name = "")
+ {
// dd($status);
-
+
$result = $this->select([
'employee_polices.*',
'policy_type.policy_type as policy_name',
@@ -91,7 +91,7 @@ class EmployeePolicyModel extends Model
'tpab.branch_code as tpa_branch_code',
'cm.client_name',
'cm.short_name as client_short_name',
- 'emp.id as employee_primary_id',
+ // 'emp.id as employee_primary_id',
'emp.relationship',
'emp.relationship_code',
'emp.change_event',
@@ -112,27 +112,27 @@ class EmployeePolicyModel extends Model
'client_branch.branch_code as client_branch_code',
'cp.policy_no',
])
- ->join('employees emp', 'employee_polices.employee_id = emp.id')
- ->join('client_policy cp', 'employee_polices.client_policy_id = cp.id') //cp - client policy
- ->join('policies pm', 'cp.policy_id = pm.id', 'left') //pm - policy master
- ->join('policy_type', 'policy_type.id = cp.policy_type_id')
- ->join('insurers im', 'cp.insurer_id = im.id') //im - insurer master
- ->join('insurer_branch ib', 'cp.insurer_branch_id = ib.id') //ib - insurer branch
- ->join('tpa tpam', 'cp.tpa_id = tpam.id', 'left') //tpam - tpa master
- ->join('tpa_branch tpab', 'cp.tpa_branch_id = tpab.id', 'left') //tpab - tpa branch
- ->join('clients cm', 'cp.client_id = cm.id') //cm - client master
- ->join('client_branch', 'emp.client_branch_id = client_branch.id') //cm - client master
- ->orderBy('emp.emp_code', 'ASC')
- ->orderBy('employee_polices.employee_id', 'ASC');
-
+ ->join('employees emp', 'employee_polices.employee_id = emp.id')
+ ->join('client_policy cp', 'employee_polices.client_policy_id = cp.id') //cp - client policy
+ ->join('policies pm', 'cp.policy_id = pm.id', 'left') //pm - policy master
+ ->join('policy_type', 'policy_type.id = cp.policy_type_id')
+ ->join('insurers im', 'cp.insurer_id = im.id') //im - insurer master
+ ->join('insurer_branch ib', 'cp.insurer_branch_id = ib.id') //ib - insurer branch
+ ->join('tpa tpam', 'cp.tpa_id = tpam.id', 'left') //tpam - tpa master
+ ->join('tpa_branch tpab', 'cp.tpa_branch_id = tpab.id', 'left') //tpab - tpa branch
+ ->join('clients cm', 'cp.client_id = cm.id') //cm - client master
+ ->join('client_branch', 'emp.client_branch_id = client_branch.id') //cm - client master
+ ->orderBy('emp.emp_code', 'ASC')
+ ->orderBy('employee_polices.employee_id', 'ASC');
+
// Conditionally add where clauses
- if ($client_id !=0 && !empty($client_id)) {
+ if ($client_id != 0 && !empty($client_id)) {
$result->where('emp.client_id', $client_id);
}
- if ($branch_id !=0 && !empty($branch_id)) {
+ if ($branch_id != 0 && !empty($branch_id)) {
$result->where('emp.client_branch_id', $branch_id);
}
- if ($policy_id !=0 && !empty($policy_id)) {
+ if ($policy_id != 0 && !empty($policy_id)) {
$result->where('employee_polices.client_policy_id', $policy_id);
}
@@ -141,22 +141,20 @@ class EmployeePolicyModel extends Model
$result->where('employee_polices.status !=', 'expired');
if (in_array("active", $status)) {
-
+
$result->where('employee_polices.tpa_id IS NOT NULL');
$result->where('employee_polices.uhid IS NOT NULL');
$result->whereIn('employee_polices.status', $status);
-
} elseif (in_array("pending", $status)) {
-
+
$result->where('employee_polices.tpa_id IS NULL');
$result->where('employee_polices.uhid IS NULL');
$result->whereIn('employee_polices.status', array_merge($status, ['active']));
-
} else {
-
+
$result->whereIn('employee_polices.status', $status);
}
-
+
// if($status == 'active'){
// $result->where('employee_polices.tpa_id IS NOT NULL');
// $result->where('employee_polices.uhid IS NOT NULL');
@@ -174,13 +172,13 @@ class EmployeePolicyModel extends Model
if (!empty($emp_name)) {
$result->like('emp.name', $emp_name);
}
-
+
// Always check these conditions
$result->where('employee_polices.is_active', 1)
- ->where('emp.is_active', 1);
-
+ ->where('emp.is_active', 1);
+
return $result->findAll();
- }
+ }
public function getEmployeePolicyForEcard($policy_id = 0)
{
@@ -575,6 +573,12 @@ class EmployeePolicyModel extends Model
}
}
+ $status_condition = "{$insurer_or_tpa}" === 'tpa'
+ ? "employee_polices.status = 'inactive' AND employees.emp_status = 'inactive'"
+ : "employee_polices.status = 'active' AND employees.emp_status = 'active'";
+
+ $endorsement_condition = "{$insurer_or_tpa}" === 'tpa' ? "AND (a.endorsement_id IS NOT NULL OR a.endorsement_id != '')" : "AND (a.endorsement_id IS NULL OR a.endorsement_id = '')";
+
$query = $this->db->query("
SELECT DISTINCT
a.id as endorsement_primarykey,
@@ -659,23 +663,22 @@ class EmployeePolicyModel extends Model
WHERE employee_polices.client_policy_id = {$client_policy_id}
AND employees.client_branch_id = {$client_branch_id}
- AND (a.endorsement_id IS NULL OR a.endorsement_id = '')
+ $endorsement_condition
AND a.actions = 'd'
AND employee_polices.is_active = 1
- AND employee_polices.status = 'active'
AND employees.is_active = 1
- AND employees.emp_status = 'active'
+ AND $status_condition
group by group_key
");
$result = $query->getResult();
+ // dd($this->db->getLastQuery(), $result);
return $result;
}
-
public function fetchEmpEndorsementData($fetch_data)
{
// dd($fetch_data);
diff --git a/app/Models/LeadsModel.php b/app/Models/LeadsModel.php
index 705f1587..7b7cc54a 100644
--- a/app/Models/LeadsModel.php
+++ b/app/Models/LeadsModel.php
@@ -43,6 +43,7 @@ class LeadsModel extends Model
'proposed_insurer_branch_id',
'proposed_tpa_id',
'proposed_tpa_branch_id',
+ 'proposel_data',
'status',
'notes',
'created_at',
diff --git a/app/Models/LevelContactModel.php b/app/Models/LevelContactModel.php
index 234db3aa..cf5d596d 100755
--- a/app/Models/LevelContactModel.php
+++ b/app/Models/LevelContactModel.php
@@ -26,27 +26,35 @@ class LevelContactModel extends Model
];
- public function getContectForRFQ(){
-
- $result = $this
-
- ->select('
- level_contacts.id,
- insurers.short_name as insurer_name,
- insurer_branch.branch_code,
- level_contacts.name as contect_person_name,
- level_contacts.email as contect_person_email,
- ')
- ->join('insurer_branch', 'level_contacts.ref_id = insurer_branch.id')
- ->join('insurers', 'insurer_branch.insurer_id = insurers.id')
- ->where('level_contacts.contact_type', 'insurer')
- ->where('level_contacts.is_active', 1)
- ->where('insurer_branch.is_active', 1)
- ->where('insurers.is_active', 1)
- ->findAll();
-
+ public function getContactForRFQ($insurer_id = null, $insurer_branch_id = null)
+ {
+ $query =
+ $this->db->table('level_contacts')
+ ->select('
+ level_contacts.id,
+ insurers.short_name as insurer_name,
+ insurer_branch.branch_code,
+ level_contacts.name as contact_person_name,
+ level_contacts.email as contact_person_email
+ ')
+ ->join('insurer_branch', 'level_contacts.ref_id = insurer_branch.id')
+ ->join('insurers', 'insurer_branch.insurer_id = insurers.id')
+ ->where('level_contacts.contact_type', 'insurer')
+ ->where('level_contacts.is_active', 1)
+ ->where('insurer_branch.is_active', 1)
+ ->where('insurers.is_active', 1);
+
+ if ($insurer_branch_id) {
+ $query->where('insurer_branch.id', $insurer_branch_id);
+ }
+ if ($insurer_id) {
+ $query->where('insurer_branch.insurer_id', $insurer_id);
+ }
+
+ $result = $query->get()->getResultArray();
return $result;
-
}
+
+
}
diff --git a/app/Models/RFQModel.php b/app/Models/RFQModel.php
index f74a1313..fa00c3a9 100644
--- a/app/Models/RFQModel.php
+++ b/app/Models/RFQModel.php
@@ -57,4 +57,29 @@ class RFQModel extends Model
return $data;
}
+ public function getRFQTableDataWithLeadIDAndType($lead_id, $type){
+
+ return $this->select('
+ leads.client_name,
+ leads.client_short_name,
+ insurers.name as insurer_name,
+ insurer_branch.branch_name as insurer_branch_name,
+ tpa.name as tpa_name,
+ tpa_branch.branch_name as tpa_branch_name,
+ policy_type.policy_type,
+ rfq.json
+ ')
+ ->join('leads', 'rfq.lead_id = leads.id')
+ ->join('policy_type', 'leads.policy_type_id = policy_type.id')
+ ->join('insurers', 'leads.insurer_id = insurers.id')
+ ->join('insurer_branch', 'leads.insurer_branch_id = insurer_branch.id')
+ ->join('tpa', 'leads.tpa_id = tpa.id')
+ ->join('tpa_branch', 'leads.tpa_branch_id = tpa_branch.id')
+ ->where('rfq.lead_id', $lead_id)
+ ->where('rfq.type', $type)
+ ->where('rfq.is_active', 1)
+ ->first();
+
+ }
+
}
diff --git a/app/Models/TPABranchModel.php b/app/Models/TPABranchModel.php
index 9e528194..f811aa04 100755
--- a/app/Models/TPABranchModel.php
+++ b/app/Models/TPABranchModel.php
@@ -28,6 +28,8 @@ class TPABranchModel extends Model
{
$query = $this->select('tpa_branch.*, T.short_name as tpa_short_name, T.name as tpa_name')
->join('tpa T', 'tpa_branch.tpa_id = T.id', 'left')
+ ->where('T.is_active', 1)
+ ->where('tpa_branch.is_active', 1)
->find();
return $query;
}
diff --git a/app/Models/UserModel.php b/app/Models/UserModel.php
index 8eb0e6f7..49b84400 100755
--- a/app/Models/UserModel.php
+++ b/app/Models/UserModel.php
@@ -124,5 +124,15 @@ class UserModel extends Model
}
}
+ public function getUserListForRFQ(){
+
+ return $this->db->table('user_profiles')
+ ->select('user_profiles.*')
+ ->select('roles.role as user_role')
+ ->join('roles', 'roles.id = user_profiles.role')
+ ->get()
+ ->getResultArray();
+ }
+
}
?>
\ No newline at end of file
diff --git a/app/Views/batch_list.php b/app/Views/batch_list.php
index a2c371b2..b5747912 100755
--- a/app/Views/batch_list.php
+++ b/app/Views/batch_list.php
@@ -71,36 +71,73 @@
-
+
+
+
+
+
+
+
+
+
failed
+
+
+
+
failed
+
+
+
failed
+
+
+
failed
failed
+
+
+
+
+
diff --git a/app/Views/employee_data_list.php b/app/Views/employee_data_list.php
index 8ca32f6b..e023579b 100755
--- a/app/Views/employee_data_list.php
+++ b/app/Views/employee_data_list.php
@@ -142,7 +142,7 @@
-
-
-
-
+
+
@@ -312,7 +327,7 @@ body {
-
+
@@ -328,101 +343,288 @@ body {
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
@@ -524,6 +726,7 @@ function saveFamilyMembersDetails() {
'family_other_members': elders,
'elders_count': elders_count
});
+
var hidden_value = createFamilyJSONString({
'self': self,
'spouse': spouse,
@@ -571,6 +774,7 @@ function resetFamiliyDialogModalValues() {
}
function createFamilyDisplayString(familyArray) {
+
let displayString = [];
// Add 'self' if the value is 1 (true)
@@ -692,8 +896,37 @@ function addSuggestionsToTable() {
tbody.empty(); // Clear any existing rows in the tbody
// return;
- if(suggestions){
+ if (suggestions) {
+
+ console.log(' addSuggestionsToTable suggestions ', suggestions);
+ console.log(' addSuggestionsToTable suggestions type', typeof suggestions);
+
+ if (policy_terms && RFQ_or_QCR == 1) {
+ let special_condition_count = 0;
+
+ if (policy_terms['special_condition_label']) {
+ special_condition_count += policy_terms['special_condition_label'].length;
+ }
+
+ if (policy_terms['gpa_special_condition_label']) {
+ special_condition_count += policy_terms['gpa_special_condition_label'].length;
+ }
+
+ console.log(special_condition_count);
+
+ for (let i = 1; i < special_condition_count; i++) {
+ suggestions[`special_condition_${i + 1}`] = {
+ "display_values": `Special condition ${i + 1}`,
+ "answers": [],
+ "type": "text",
+ "object_value": 0
+ };
+ }
+ }
+
+ let special_condition_index = 0;
for (const [key, details] of Object.entries(suggestions)) {
+
const newRow = tbody[0].insertRow();
newRow.setAttribute('id', key); // Set the row ID to the suggestion key
@@ -720,10 +953,57 @@ function addSuggestionsToTable() {
inputBox.type = 'hidden';
//add default values for default proposal for both hidden valuse as well as cell textContent
- if(details.answers.length != 0)
- {
- inputBox.value = JSON.stringify(details.answers[0]);
- editableCell.textContent = (details.answers[0].display_value);
+ if(policy_terms && RFQ_or_QCR == 1){
+
+ if (policy_terms[key] == 1) {
+
+ if (details.answers[0]) {
+ editableCell.textContent = details.answers[0].display_value || '';
+ inputBox.value = JSON.stringify(details.answers[0]);
+ } else {
+ editableCell.textContent = '';
+ inputBox.value = '';
+ }
+ } else if (policy_terms[key] == 0) {
+ if (details.answers[1]) {
+ editableCell.textContent = details.answers[1].display_value || '';
+ inputBox.value = JSON.stringify(details.answers[1]);
+ } else {
+ editableCell.textContent = '';
+ inputBox.value = '';
+ }
+ } else if (policy_terms[key]) {
+ editableCell.textContent = policy_terms[key];
+ inputBox.value = JSON.stringify(policy_terms[key]);
+ } else {
+ editableCell.textContent = '';
+ inputBox.value = '';
+ }
+
+ if(key == 'family_composition'){
+ editableCell.textContent = createFamilyDisplayStringPolicyTerms(policy_terms['family_floaters']);
+ inputBox.value = JSON.stringify(policy_terms['family_floaters']);
+ }
+
+ if (key.startsWith('special_condition')) {
+
+ if(policy_terms['special_condition_label']){
+ editableCell.textContent = policy_terms['special_condition_label'][special_condition_index] + ' - ' + policy_terms['special_condition_input'][special_condition_index];
+ inputBox.value = policy_terms['special_condition_label'][special_condition_index] + '--' + policy_terms['special_condition_input'][special_condition_index];
+ special_condition_index++
+ }else{
+ editableCell.textContent = policy_terms['gpa_special_condition_label'][special_condition_index] + ' - ' + policy_terms['gpa_special_condition_input'][special_condition_index];
+ inputBox.value = policy_terms['gpa_special_condition_label'][special_condition_index] + '--' + policy_terms['gpa_special_condition_input'][special_condition_index];
+ special_condition_index++
+ }
+ }
+
+ }else{
+
+ if (details.answers.length != 0) {
+ inputBox.value = JSON.stringify(details.answers[0]);
+ editableCell.textContent = (details.answers[0].display_value);
+ }
}
editableCell.appendChild(inputBox);
@@ -733,7 +1013,7 @@ function addSuggestionsToTable() {
const actionCell = newRow.insertCell(-1);
actionCell.classList.add('action');
actionCell.innerHTML =
- ' QCR Client ';
+ ' QCR Client ';
suggestionKeys.push(key);
}
@@ -741,12 +1021,13 @@ function addSuggestionsToTable() {
moveAddRowButton();
hideQCR();
+ isFormDataModified = false;
}
// Function to move add row button to last row
function moveAddRowButton() {
- console.log('table', rfqTable)
+ // console.log('table', rfqTable)
const lastRow = rfqTable.rows[rfqTable.rows.length - 1];
const actionCell = lastRow.querySelector('.action');
@@ -766,7 +1047,7 @@ function moveAddRowButton() {
// Event listener to handle row removal
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');
@@ -779,18 +1060,25 @@ rfqTable.addEventListener('click', function(e) {
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
}
-
+
});
// Function to add new columns
addQuoteButton.addEventListener('click', function() {
const headerRow = rfqTable.rows[0];
+ console.log(headerRow);
const secondHeaderRow = rfqTable.rows[1];
+ console.log(secondHeaderRow);
// alert('FH - ' + headerRow.cells.length + ' : SH - ' + secondHeaderRow.cells.length);
const newQuoteHeader = document.createElement('th');
const quoteCount = headerRow.cells.length - 4;
+ console.log('quoteCount', quoteCount);
+ console.log('quoteCount', headerRow.cells);
+ console.log('quoteCount', headerRow.cells);
proposal_colum_count = proposal_colum_count + 1;
var new_proposal_name = `Proposal ${proposal_colum_count}`;
newQuoteHeader.innerHTML = `${new_proposal_name}
@@ -813,19 +1101,23 @@ addQuoteButton.addEventListener('click', function() {
// Add a new column to each row
for (let i = 1; i < rfqTable.rows.length; i++) {
+ // console.log(rfqTable.rows[i]);
+ // console.log('fourth cell html', rfqTable.rows[i].cells[3]);
+ // console.log('fourth cell innerText', rfqTable.rows[i].cells[3].innerText);
+
if (i == 1) {
// Create a new element
const newHeaderCell = document.createElement('th');
newHeaderCell.innerHTML = ` Quote Asked `;
newHeaderCell.style.backgroundColor = randomColor;
// Insert the element at the desired position
- rfqTable.rows[i].insertBefore(newHeaderCell, rfqTable.rows[i].cells[secondHeaderRow.cells.length -
- 1]);
+ rfqTable.rows[i].insertBefore(newHeaderCell, rfqTable.rows[i].cells[secondHeaderRow.cells.length - 1]);
} else {
const newCell = rfqTable.rows[i].insertCell(secondHeaderRow.cells.length - 2);
newCell.setAttribute('contenteditable', 'true');
newCell.classList.add('editablecolumns');
+ newCell.innerHTML = rfqTable.rows[i].cells[3].innerHTML;
newCell.style.backgroundColor = randomColor;
}
@@ -838,12 +1130,15 @@ addQuoteButton.addEventListener('click', function() {
"stc": 1,
'insurers': []
};
+
+ isFormDataModified = true; // if any value changeing in the table to set true
+
console.log(over_all_column_data);
});
// Function to handle suggestion box
function showSuggestions(input) {
-
+
suggestionList.innerHTML = '';
const value = input.innerText.trim().toLowerCase();
const rowID = event.target.parentNode.id;
@@ -857,12 +1152,13 @@ function showSuggestions(input) {
li.innerText = details.display_values;
li.dataset.key = key;
suggestionList.appendChild(li);
- li.addEventListener('click', function () {
+ li.addEventListener('click', function() {
// alert(value+' - '+key);
- if ((rowID == "" || rowID != key ) && suggestionKeys.includes(key) && key != 'special_condition') {
- alert('Duplicate entry detected');
- return false; // Prevent adding duplicate
- }
+ if ((rowID == "" || rowID != key) && suggestionKeys.includes(key) && key !=
+ 'special_condition') {
+ alert('Duplicate entry detected');
+ return false; // Prevent adding duplicate
+ }
input.innerText = details.display_values;
const row = input.closest('tr');
@@ -885,7 +1181,7 @@ function showSuggestions(input) {
const scrollLeft = window.pageXOffset || document.documentElement.scrollLeft;
suggestionBox.style.top = (rect.bottom + scrollTop) + 'px';
suggestionBox.style.left = (rect.left + scrollLeft) + 'px';
-
+
} else {
hideSuggestionBox();
}
@@ -898,13 +1194,11 @@ function showAnswersSuggestions(input) {
//return;
var questionItem = input.parentElement.id;
- if(questionItem == 'family_composition')
- {
+ if (questionItem == 'family_composition') {
showFamilyFloaterDialogBox(input);
return;
}
- if(questionItem.startsWith('special_condition'))
- {
+ if (questionItem.startsWith('special_condition')) {
return;
}
var questionAnswers = suggestions[questionItem]['answers'];
@@ -912,11 +1206,10 @@ function showAnswersSuggestions(input) {
// console.log(questionItem);
// console.log(questionAnswers);
// console.log(questionType);
- if(questionType == 'text')
- {
- return;
+ if (questionType == 'text') {
+ return;
}
-
+
suggestionList.innerHTML = '';
// const value = input.innerText.trim().toLowerCase();
// alert(value);
@@ -938,7 +1231,7 @@ function showAnswersSuggestions(input) {
li.innerText = details.display_value;
li.dataset.key = details.display_value;
suggestionList.appendChild(li);
- li.addEventListener('click', function () {
+ li.addEventListener('click', function() {
input.innerText = '';
//hidden text box for store choosed answers object
@@ -964,7 +1257,7 @@ function showAnswersSuggestions(input) {
if (filteredSuggestions.length > 0) {
console.log('display suggestion box');
- console.log(input.getBoundingClientRect().bottom+'-'+input.getBoundingClientRect().left);
+ console.log(input.getBoundingClientRect().bottom + '-' + input.getBoundingClientRect().left);
suggestionBox.style.display = 'block';
const rect = input.getBoundingClientRect();
const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
@@ -1002,36 +1295,34 @@ document.getElementById('rfqTable').addEventListener('focusout', function(e) {
}
});
-document.addEventListener('click', function (e) {
+document.addEventListener('click', function(e) {
+
if (!e.target.closest('.suggestion-box') && !e.target.classList.contains('particulars')) {
suggestionBox.style.display = 'none';
}
if (e.target.classList.contains('particulars')) {
- showSuggestions(e.target);
+ showSuggestions(e.target);
}
- if (e.target.classList.contains('editablecolumns')) {
+ if (e.target.classList.contains('editablecolumns')) {
// console.log(e.target.innerText);
// if(e.target.innerText == '')
// {
- showAnswersSuggestions(e.target);
+ showAnswersSuggestions(e.target);
// }
}
-
//hide currently showing any three dotted menu
- if(currentThrdottedMenu != '')
- {
+ if (currentThrdottedMenu != '') {
// console.log('currentThrdottedMenu hide called');
// Toggle the display property
if (currentThrdottedMenu.style.display === 'block') {
// console.log('currentThrdottedMenu hidden');
- currentThrdottedMenu.style.display = 'none'; // Hide if it's already shown
+ currentThrdottedMenu.style.display = 'none'; // Hide if it's already shown
currentThrdottedMenu = '';
- }
- else {
- currentThrdottedMenu.style.display = 'block'; // Show if it's hidden
+ } else {
+ currentThrdottedMenu.style.display = 'block'; // Show if it's hidden
}
}
});
@@ -1065,12 +1356,13 @@ function addRow(e) {
const actionCell = newRow.insertCell();
actionCell.classList.add('action');
actionCell.innerHTML =
- ' QCR Client ';
-
+ ' QCR Client ';
e.target.remove();
updateRowNumbers();
realignSpecialConditions();
+
+ isFormDataModified = true; // if any value changeing in the table to set true
}
// Function to update row numbers
@@ -1198,6 +1490,8 @@ function detachDynamicEventListeners() {
// });
}
+//----------------------------------------------------------------------------------------------------------
+
function addInsurer(event) {
const insurers = = json_encode($insurer); ?>;
@@ -1221,73 +1515,213 @@ function addInsurer(event) {
let colIndex = closestTh.cellIndex;
let columnText = closestTh.innerText;
let proposal_name = columnText.split('⋮')[0].trim();
- // alert(colIndex);
+
if (!checkExistingInsurer(proposal_name, insurerName)) {
- alert('Dup insurer');
- return false;
+
+ Swal.fire({
+ title: "Insurer Dublicate Found?",
+ text: "Do you want version control!",
+ icon: "warning",
+ showCancelButton: true,
+ confirmButtonColor: "#3085d6",
+ cancelButtonColor: "#d33",
+ confirmButtonText: "Yes, Procced!"
+ }).then((result) => {
+ if (result.isConfirmed) {
+
+ let insurer_index = checkExistingInsurerIndex(proposal_name, insurerName);
+ // console.log('insurer_index', insurer_index);
+ // console.log('insurerName', insurerName);
+ let modifiedInsurerName = constructInsurerNameWithVersion(proposal_name, insurerName);
+ console.log('modifiedInsurerName', modifiedInsurerName);
+ addInsurerData(event, modifiedInsurerName, dataId, insurer_index)
+ }else{
+ return false;
+ }
+ });
+
+ }else{
+ addInsurerData(event, insurerName, dataId)
}
+ if (currentThrdottedMenu != '') {
+ currentThrdottedMenu.style.display = 'none'; // Show if it's hidden
+ }
+ }
+ });
+
+ return;
+}
+
+function addInsurerData(event, insurerName, dataId, nextIndex = null) {
+
+ const closestTh = event.target.closest('th');
+ let colIndex = closestTh.cellIndex;
+ // console.log('column index of first table', colIndex);
+ let columnText = closestTh.innerText;
+ let proposal_name = columnText.split('⋮')[0].trim();
+
+ let rfqTable = document.getElementById('rfqTable');
+ const headerRow = rfqTable.rows[1];
+
+ const thElements = rfqTable.querySelectorAll('thead tr:first-child th');
+ let totalColspan = 0;
+
+ for (let i = 0; i <= colIndex; i++) {
+ const colspan = parseInt(thElements[i].getAttribute('colspan')) || 1;
+ totalColspan += colspan;
+ }
+
+ let parentTh = rfqTable.querySelector('thead tr th:nth-child(' + (colIndex + 1) + ')');
+ // console.log('parentTh', parentTh);
+ let columnIndextoCopyData = totalColspan - parentTh.colSpan;
+ parentTh.colSpan += 1;
+
+ // Determine the position for inserting the column
+ let insertPosition = totalColspan; // Default to inserting at the end of the current insurer's columns
+ if(nextIndex){
+ insertPosition = nextIndex;
+ }
+
+ // if (nextIndex) {
+ // insertPosition = totalColspan - parentTh.colSpan + 0; // Insert right after the current insurer's column
+ // }
+
+ // Add a new column to each row
+ for (let i = 1; i < rfqTable.rows.length; i++) {
+ if (i === 1) {
+
+ const newHeaderCell = document.createElement('th');
+ newHeaderCell.innerHTML = `${insurerName}
+
+
+ `;
+ newHeaderCell.style.backgroundColor = parentTh.style.backgroundColor;
+ rfqTable.rows[i].insertBefore(newHeaderCell, rfqTable.rows[i].cells[insertPosition]);
+ } else {
+ const newCell = rfqTable.rows[i].insertCell(insertPosition);
+ newCell.setAttribute('contenteditable', 'true');
+ newCell.classList.add('editablecolumns');
+ newCell.innerHTML = rfqTable.rows[i].cells[columnIndextoCopyData].innerHTML;
+ newCell.style.backgroundColor = parentTh.style.backgroundColor;
+ }
+ }
+
+ attachEventListeners();
+
+ pushInsurerInArray(proposal_name, {
+ 'ins_name': insurerName.split('-')[0],
+ 'qcr': 1,
+ 'stc': 1,
+ 'display_name': insurerName,
+ 'id': dataId
+ });
+
+ if(RFQ_or_QCR == 2){
+ addInsurerDataForPremiumTable(event, insurerName, proposal_name)
+ }
+
+ isFormDataModified = true; // if any value changeing in the table to set true
+}
+
+function dupInsurer(event) {
+
+ const thPosition = getThPosition(event);
+ console.log(thPosition);
+
+ const insurers = = json_encode($insurer); ?>;
+
+ selectInsurer(insurers).then(result => {
+
+ insurerName = result.selectedInsurer;
+ version = result.insurerDetails;
+ dataId = result.dataId;
+
+ if (version.trim() !== '') {
+ insurerName = `${insurerName}-${version.trim()}`.replace(/\s+/g, '');
+ }
+
+ console.log('insurerName', insurerName)
+ console.log('version', version)
+
+ if (insurerName) {
+
+ let parentThIndex = null;
+ const closestTh = event.target.closest('th');
+ let colIndex = closestTh.cellIndex;
+ let columnText = closestTh.innerText;
+ let proposal_name = columnText.split('⋮')[0].trim();
let rfqTable = document.getElementById('rfqTable');
- const headerRow = rfqTable.rows[1];
- // console.log('current col index' + colIndex);
+ const headerRows = rfqTable.querySelectorAll('thead tr');
- //find total no of columns (sub th) untill current parent th
- const thElements = rfqTable.querySelectorAll('thead tr:first-child th');
- let totalColspan = 0;
+ if (thPosition.rowIndex == 1) //copy insurer
+ {
+ var copyType = event.target.className;
+ // alert(copyType);
+ let accumulatedColspan = 0;
+ let parentTh = null;
- // Loop through the parent th elements within the specified index range
- for (let i = 0; i <= colIndex; i++) {
- const colspan = parseInt(thElements[i].getAttribute('colspan')) || 1;
- totalColspan += colspan;
- }
- // alert(colIndex+' - '+totalColspan);
+ let subThIndex = colIndex;
+ 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;
- // add colspan of current th
- let parentTh = rfqTable.querySelector('thead tr th:nth-child(' + (colIndex + 1) + ')');
- let columnIndextoCopyData = totalColspan - parentTh.colSpan;
- parentTh.colSpan += 1;
+ accumulatedColspan += currentColspan;
-
- // Add a new column to each row
- for (let i = 1; i < rfqTable.rows.length; i++) {
-
- if (i == 1) {
- // Create a new element
- const newHeaderCell = document.createElement('th');
- newHeaderCell.innerHTML = ` ${insurerName}
-
-
- `;
- newHeaderCell.style.backgroundColor = parentTh.style.backgroundColor;;
- // Insert the element at the desired position
- rfqTable.rows[i].insertBefore(newHeaderCell, rfqTable.rows[i].cells[totalColspan]);
-
- } else {
- const newCell = rfqTable.rows[i].insertCell(totalColspan);
- newCell.setAttribute('contenteditable', 'true');
- newCell.classList.add('editablecolumns');
- newCell.innerHTML = rfqTable.rows[i].cells[columnIndextoCopyData].innerHTML;
- newCell.style.backgroundColor = parentTh.style.backgroundColor;;
+ if (subThIndex < accumulatedColspan) {
+ parentTh = currentParentTh;
+ break;
+ }
}
-
+ console.log(parentTh.cellIndex);
+ parentTh = headerRows[0].children[parentTh.cellIndex];
+ parentThIndex = parentTh.cellIndex;
+ console.log(accumulatedColspan + ' - ' + parentTh + ' - ' + subThIndex);
+ proposal_name = parentTh.innerText.split('⋮')[0].trim();
+ // if(copyType == 'copyInsurerLast')
+ // {
+ // colIndex = parentTh.cellIndex;
+ // }
+ // else
+ // {
+ // colIndex = colIndex;
+ // }
}
- attachEventListeners();
- //add insurer into over all column data
- pushInsurerInArray(proposal_name, {
- 'ins_name': (insurerName.split('-')[0]),
- 'qcr': 1,
- 'stc': 1,
- 'display_name': insurerName,
- 'id': dataId
- });
+ console.log(colIndex);
+
+ if (!checkExistingInsurer(proposal_name, insurerName)) {
+
+ Swal.fire({
+ title: "Insurer Dublicate Found?",
+ text: "Do you want version control!",
+ icon: "warning",
+ showCancelButton: true,
+ confirmButtonColor: "#3085d6",
+ cancelButtonColor: "#d33",
+ confirmButtonText: "Yes, Procced!"
+ }).then((result) => {
+ if (result.isConfirmed) {
+ console.log('insurerName', insurerName);
+ let modifiedInsurerName = constructInsurerNameWithVersion(proposal_name, insurerName);
+ console.log('modifiedInsurerName', modifiedInsurerName);
+ copyInsurerData(event, modifiedInsurerName, dataId)
+ }else{
+ return false;
+ }
+ });
+
+ }else{
+ copyInsurerData(event, insurerName, dataId)
+ }
}
if (currentThrdottedMenu != '') {
@@ -1298,152 +1732,141 @@ function addInsurer(event) {
return;
}
-function dupInsurer(event) {
-
+function copyInsurerData(event, insurerName, dataId){
+
const thPosition = getThPosition(event);
- console.log(thPosition);
- // if(thPosition.rowIndex == 1)
- // {
- //return false;
- // }
- // alert('addInsurer clicked');
- let insurerName = prompt("Enter Insurer Name:");
- if (insurerName) {
- let parentThIndex = null;
- const closestTh = event.target.closest('th');
- let colIndex = closestTh.cellIndex;
- let columnText = closestTh.innerText;
- let proposal_name = columnText.split('⋮')[0].trim();
- let rfqTable = document.getElementById('rfqTable');
- const headerRows = rfqTable.querySelectorAll('thead tr');
+ let parentThIndex = null;
+ const closestTh = event.target.closest('th');
+ let colIndex = closestTh.cellIndex;
+ let columnText = closestTh.innerText;
+ let proposal_name = columnText.split('⋮')[0].trim();
+ let rfqTable = document.getElementById('rfqTable');
+ const headerRows = rfqTable.querySelectorAll('thead tr');
- if (thPosition.rowIndex == 1) //copy insurer
- {
- var copyType = event.target.className;
- // alert(copyType);
- let accumulatedColspan = 0;
- let parentTh = null;
+ if (thPosition.rowIndex == 1) //copy insurer
+ {
+ var copyType = event.target.className;
+ // alert(copyType);
+ let accumulatedColspan = 0;
+ let parentTh = null;
- let subThIndex = colIndex;
- 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 subThIndex = colIndex;
+ 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.cellIndex);
- parentTh = headerRows[0].children[parentTh.cellIndex];
- parentThIndex = parentTh.cellIndex;
- console.log(accumulatedColspan + ' - ' + parentTh + ' - ' + subThIndex);
- proposal_name = parentTh.innerText.split('⋮')[0].trim();
- // if(copyType == 'copyInsurerLast')
- // {
- // colIndex = parentTh.cellIndex;
- // }
- // else
- // {
- // colIndex = colIndex;
- // }
}
-
- alert(colIndex);
- if (!checkExistingInsurer(proposal_name, insurerName)) {
- alert('Dup insurer');
- return false;
- }
-
-
- const headerRow = rfqTable.rows[1];
- // console.log('current col index' + colIndex);
-
- //find total no of columns (sub th) untill current parent th
- const thElements = rfqTable.querySelectorAll('thead tr:first-child th');
- let totalColspan = 0;
-
- // Loop through the parent th elements within the specified index range
- for (let i = 0; i <= parentThIndex; i++) {
- const colspan = parseInt(thElements[i].getAttribute('colspan')) || 1;
- totalColspan += colspan;
- }
- // alert(colIndex+' - '+totalColspan);
-
-
- // if(copyType == 'copyInsurerNext')
- // {
- // totalColspan = colIndex;
- // colIndex = colIndex - 1;
- // }
- // add colspan of current th
- let parentTh = rfqTable.querySelector('thead tr th:nth-child(' + (parentThIndex + 1) + ')');
- parentTh.colSpan += 1;
- // Add a new column to each row
- for (let i = 1; i < rfqTable.rows.length; i++) {
-
- if (i == 1) {
- // Create a new element
- const newHeaderCell = document.createElement('th');
- newHeaderCell.innerHTML = ` ${insurerName}
-
-
- `;
- newHeaderCell.style.backgroundColor = parentTh.style.backgroundColor;;
- // Insert the element at the desired position
- rfqTable.rows[i].insertBefore(newHeaderCell, rfqTable.rows[i].cells[totalColspan]);
-
- } else {
- const newCell = rfqTable.rows[i].insertCell(totalColspan);
- newCell.setAttribute('contenteditable', 'true');
- newCell.classList.add('editablecolumns');
- newCell.innerHTML = rfqTable.rows[i].cells[colIndex].innerHTML;
- newCell.style.backgroundColor = parentTh.style.backgroundColor;;
- }
-
- }
- attachEventListeners();
-
- //add insurer into over all column data
- pushInsurerInArray(proposal_name, {
- 'ins_name': (insurerName.split('-')[0]),
- 'qcr': 0,
- 'stc': 0,
- 'display_name': insurerName
- });
-
+ console.log(parentTh.cellIndex);
+ parentTh = headerRows[0].children[parentTh.cellIndex];
+ parentThIndex = parentTh.cellIndex;
+ console.log(accumulatedColspan + ' - ' + parentTh + ' - ' + subThIndex);
+ proposal_name = parentTh.innerText.split('⋮')[0].trim();
+ // if(copyType == 'copyInsurerLast')
+ // {
+ // colIndex = parentTh.cellIndex;
+ // }
+ // else
+ // {
+ // colIndex = colIndex;
+ // }
}
- if (currentThrdottedMenu != '') {
- currentThrdottedMenu.style.display = 'none'; // Show if it's hidden
+ console.log(colIndex);
+
+ const headerRow = rfqTable.rows[1];
+ // console.log('current col index' + colIndex);
+
+ //find total no of columns (sub th) untill current parent th
+ const thElements = rfqTable.querySelectorAll('thead tr:first-child th');
+ let totalColspan = 0;
+
+ // Loop through the parent th elements within the specified index range
+ for (let i = 0; i <= parentThIndex; i++) {
+ const colspan = parseInt(thElements[i].getAttribute('colspan')) || 1;
+ totalColspan += colspan;
}
- return;
+ // alert(colIndex+' - '+totalColspan);
+ // if(copyType == 'copyInsurerNext')
+ // {
+ // totalColspan = colIndex;
+ // colIndex = colIndex - 1;
+ // }
+
+
+ // add colspan of current th
+ let parentTh = rfqTable.querySelector('thead tr th:nth-child(' + (parentThIndex + 1) + ')');
+ parentTh.colSpan += 1;
+ // Add a new column to each row
+ for (let i = 1; i < rfqTable.rows.length; i++) {
+
+ if (i == 1) {
+ // Create a new element
+ const newHeaderCell = document.createElement('th');
+ newHeaderCell.innerHTML = ` ${insurerName}
+
+
+ `;
+ newHeaderCell.style.backgroundColor = parentTh.style.backgroundColor;;
+ // Insert the element at the desired position
+ rfqTable.rows[i].insertBefore(newHeaderCell, rfqTable.rows[i].cells[totalColspan]);
+
+ } else {
+ const newCell = rfqTable.rows[i].insertCell(totalColspan);
+ newCell.setAttribute('contenteditable', 'true');
+ newCell.classList.add('editablecolumns');
+ newCell.innerHTML = rfqTable.rows[i].cells[colIndex].innerHTML;
+ newCell.style.backgroundColor = parentTh.style.backgroundColor;
+ }
+
+ }
+
+ attachEventListeners();
+
+ //add insurer into over all column data
+ pushInsurerInArray(proposal_name, {
+ 'ins_name': (insurerName.split('-')[0]),
+ 'qcr': 1,
+ 'stc': 1,
+ 'display_name': insurerName,
+ 'id': dataId
+ });
+
+ if(RFQ_or_QCR == 2){
+ copyInsurerDataForPremiumTable(event, insurerName)
+ }
+
+ isFormDataModified = true; // if any value changeing in the table to set true
}
+//--------------------------------------------------------------------------------------------------------
+
function removeProposal(event) {
const closestTh = event.target.closest('th');
let colIndex = closestTh.cellIndex;
let rfqTable = document.getElementById('rfqTable');
-
+ console.log(rfqTable)
if (confirm("Are you sure you want to remove this column?")) {
-
const headerRows = rfqTable.querySelectorAll('thead tr');
const parentTh = headerRows[0].children[colIndex];
const proposal_name = parentTh.innerText.split('⋮')[0].trim();
@@ -1459,16 +1882,22 @@ function removeProposal(event) {
headerRows[1].removeChild(headerRows[1].children[startIndex]);
// Remove the corresponding TDs from each row
- document.querySelectorAll('tbody tr').forEach(row => {
+ rfqTable.querySelectorAll('tbody tr').forEach(row => {
row.removeChild(row.children[startIndex]);
});
}
- //remove proposal in global array
+ if(RFQ_or_QCR == 2){
+ removeProposalForPremiumTable(colIndex);
+ }
+ //remove proposal in global array
if (over_all_column_data.hasOwnProperty(proposal_name)) {
delete over_all_column_data[proposal_name]; // Delete the property
console.log(`${proposal_name} deleted successfully.`);
+
+ isFormDataModified = true; // if any value changeing in the table to set true
+
} else {
console.log(`${proposal_name} does not exist.`);
}
@@ -1486,9 +1915,11 @@ function removeInsurer(event) {
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);
let accumulatedColspan = 0;
let parentTh = null;
@@ -1526,9 +1957,13 @@ function removeInsurer(event) {
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
}
}
@@ -1546,23 +1981,91 @@ function showThreeDottedMenu(event) {
}
function checkExistingInsurer(proposal_name, insurer_name) {
+
proposal_name = proposal_name.trim(proposal_name);
- console.log('proposal_name - ' + proposal_name);
- console.log(over_all_column_data[proposal_name]);
- console.log('insurer_name - ' + insurer_name);
+ // console.log('proposal_name - ' + proposal_name);
+ // console.log(over_all_column_data[proposal_name]);
+ // console.log('insurer_name - ' + insurer_name);
+
if (over_all_column_data[proposal_name]) {
let tempInsurerList = over_all_column_data[proposal_name].insurers;
- console.log(tempInsurerList);
+ // console.log('tempInsurerList', tempInsurerList);
if (!tempInsurerList.length) {
return true;
}
let result = tempInsurerList.some(item => item.display_name === insurer_name);
- console.log(!result);
return !result;
}
return false;
}
+function checkExistingInsurerIndex(proposal_name, insurer_name) {
+
+ console.log('#####################################################');
+
+ proposal_name = proposal_name.trim();
+
+ if (over_all_column_data[proposal_name]) {
+
+ console.log('over_all_column_data', over_all_column_data);
+
+ const currentProposalInsurers = over_all_column_data[proposal_name].insurers;
+
+ // Calculate duplicate insurer IDs within the current proposal
+ let duplicate_insurer_id_count = 0;
+ const insurerIdCountMap = {};
+
+ currentProposalInsurers.forEach((insurer) => {
+ const insurerId = insurer.id;
+ if (insurerId) {
+ insurerIdCountMap[insurerId] = (insurerIdCountMap[insurerId] || 0) + 1;
+ }
+ });
+
+ duplicate_insurer_id_count = Object.values(insurerIdCountMap).reduce((count, occurrences) => {
+ return count + (occurrences > 1 ? occurrences - 1 : 0);
+ }, 0);
+
+ console.log("Duplicate insurer IDs found:", duplicate_insurer_id_count);
+
+ // Find the proposal index
+ const proposalKeys = Object.keys(over_all_column_data);
+ const proposalIndex = proposalKeys.indexOf(proposal_name);
+ console.log('proposalIndex:', proposalIndex);
+
+ // Calculate quote and insurer count up to the current proposal
+ let quote_count = 0;
+ let insurer_count = 0;
+
+ for (let i = 0; i < proposalIndex; i++) {
+ quote_count++;
+ const previousProposal = over_all_column_data[proposalKeys[i]];
+ if (previousProposal.insurers && Array.isArray(previousProposal.insurers)) {
+ insurer_count += previousProposal.insurers.length;
+ }
+ }
+
+ let tempInsurerList = over_all_column_data[proposal_name].insurers;
+ const insurer_index = tempInsurerList.findIndex(item => item.display_name === insurer_name);
+
+
+ console.log('quote_count:', quote_count);
+ console.log('insurer_count:', insurer_count);
+ console.log('insurer_index:', insurer_index);
+
+ // Calculate total index
+ const sno_hiddenitem_particulers = 3;
+ const current_insurer_and_quote_sum = 2;
+ const total = insurer_count + insurer_index + (quote_count + current_insurer_and_quote_sum) + sno_hiddenitem_particulers + duplicate_insurer_id_count;
+ console.log('total:', total);
+
+ console.log('#####################################################');
+ return total;
+ }
+
+ return false;
+}
+
function pushInsurerInArray(proposal_name, insurer_arr) {
console.log('pushInsurerInArray function called');
@@ -1598,7 +2101,7 @@ function popInsurerInArray(proposal_name, insurerName) {
function changeInsurer(event) {
-
+
// let newInsurerName = prompt("Enter New insurer name:");
const insurers = = json_encode($insurer); ?>;
@@ -1616,6 +2119,7 @@ function changeInsurer(event) {
console.log('newversion', newversion)
if (newInsurerName) {
+
const closestTh = event.target.closest('th');
let oldInsurerName = closestTh.innerText.split('⋮')[0].trim();
let subThIndex = closestTh.cellIndex;
@@ -1650,7 +2154,11 @@ function changeInsurer(event) {
break;
}
}
+
+ changeInsurerForPremiumTable(event, newInsurerName, subThIndex)
+
let proposal_name = parentTh.innerText.split('⋮')[0].trim();
+
if (over_all_column_data[proposal_name]) {
// let tempInsurerList = over_all_column_data[proposal_name].insurers;
// console.log(tempInsurerList);
@@ -1668,8 +2176,12 @@ function changeInsurer(event) {
console.log('insurer name replaced in golbal variable');
console.log(over_all_column_data[proposal_name].insurers);
// over_all_column_data[proposal_name].insurers = tempInsurerList
+
+ isFormDataModified = true; // if any value changeing in the table to set true
+
return;
}
+
console.log('insurer name not replaced in golbal variable');
@@ -1679,6 +2191,7 @@ function changeInsurer(event) {
function changeState(event) {
+ console.log('changeState Function called')
let type = event.target.className;
console.log('1 : ', type);
@@ -1687,11 +2200,10 @@ function changeState(event) {
// } else if (type.includes('qcrProposal') && type.includes('fa fa-check-square')) {
// type = 'qcrProposal';
// }
-
// console.log('2 : ',type);
if (['qcrProposal', 'sendClientProposal'].includes(type)) {
-
+
console.log('Proposal');
const closestTh = event.target.closest('th');
let proposal_name = closestTh.innerText.split('⋮')[0].trim();
@@ -1840,6 +2352,8 @@ function changeState(event) {
console.log('insurer name not replaced in golbal variable');
}
+
+ isFormDataModified = true; // if any value changeing in the table to set true
}
function isEventObject(variable) {
@@ -1986,23 +2500,23 @@ function setCellInnerHTMLByCellIndex(tableId, rowIndex, colIndex, htmlContent) {
}
}
-function checkCellValueAndHighlight()
-{
+function checkCellValueAndHighlight() {
console.log('checkCellValueAndHighlight called');
-
+
const table = document.getElementById('rfqTable');
const headerRow1 = table.querySelectorAll('thead tr')[0]; // First header row (main headers)
const headerRow2 = table.querySelectorAll('thead tr')[1]; // Second header row (sub headers)
const rows = table.querySelectorAll('tbody tr');
-
+
let startCol = 2; // Start after omitting SNO and items columns
-
+
headerRow1.querySelectorAll('th').forEach((th, index) => {
if (index < 2) return; // Skip SNO and items
const colspan = th.getAttribute('colspan') ? parseInt(th.getAttribute('colspan')) : 1;
- const compareIndices = [...Array(colspan).keys()].map(i => i + startCol); // Get column indices to compare
-
+ const compareIndices = [...Array(colspan).keys()].map(i => i +
+ startCol); // Get column indices to compare
+
rows.forEach(row => {
const cells = row.querySelectorAll('td');
compareRange(cells, compareIndices);
@@ -2010,6 +2524,8 @@ function checkCellValueAndHighlight()
startCol += colspan; // Move to the next set of columns
});
+
+ isFormDataModified = true; // if any value changeing in the table to set true
}
function compareRange(cells, indices) {
@@ -2017,19 +2533,16 @@ function compareRange(cells, indices) {
indices.forEach(index => {
if (cells[index].textContent !== baseValue) {
cells[index].classList.add('bold'); // Highlight mismatched cells
- }
- else
- {
- cells[index].classList.remove('bold');
+ } else {
+ cells[index].classList.remove('bold');
}
});
}
-function validateCellContent(cell)
-{
+function validateCellContent(cell) {
+
console.log('onblur check td text content');
-
// Get the hidden value from the input field inside the cell
const hiddenInput = cell.querySelector('input[type="hidden"]');
const hiddenValue = hiddenInput.value;
@@ -2039,10 +2552,9 @@ function validateCellContent(cell)
const rowId = row.getAttribute('id');
console.log(rowId);
const item = suggestions.hasOwnProperty(rowId) ? suggestions[rowId] : false;
- console.log(item);//return;
+ console.log(item); //return;
- if(item && item.type != 'text')
- {
+ if (item && item.type != 'text') {
// Get the text content the user entered in the cell
const enteredValue = cell.textContent.trim();
@@ -2059,41 +2571,38 @@ function validateCellContent(cell)
// Re-append the hidden input to the cell after setting textContent
// cell.appendChild(hiddenInput);
}
+
+ isFormDataModified = true; // if any value changeing in the table to set true
}
}
-function validateQuestionCellContent(cell)
-{
- console.log('onblur check td text content for questions');
+function validateQuestionCellContent(cell) {
+ console.log('onblur check td text content for questions');
// Get the row ID
const row = cell.closest('tr');
const rowId = row.getAttribute('id');
console.log(rowId);
console.log(cell.textContent);
- if(rowId && suggestions.hasOwnProperty(rowId) && !rowId.startsWith('special'))
- {
- const item = suggestions.hasOwnProperty(rowId) ? suggestions[rowId] : false;
- // console.log(item);//return;
- let current_val = cell.textContent;
- let expected_val = item.display_values;
- if(current_val != expected_val)
- {
+ if (rowId && suggestions.hasOwnProperty(rowId) && !rowId.startsWith('special')) {
+ const item = suggestions.hasOwnProperty(rowId) ? suggestions[rowId] : false;
+ // console.log(item);//return;
+ let current_val = cell.textContent;
+ let expected_val = item.display_values;
+ if (current_val != expected_val) {
cell.textContent = expected_val;
- }
- }
- else if(!rowId && cell.textContent != '')
- {
+ }
+ } else if (!rowId && cell.textContent != '') {
alert('Not allowed,Please choose applicable question');
cell.textContent = '';
}
-
+
}
async function selectInsurer(insurers) {
- // Build the HTML for the Select2 dropdown and the input text field
- const selectHTML = `
+ // Build the HTML for the Select2 dropdown and the input text field
+ const selectHTML = `
@@ -2110,82 +2619,107 @@ async function selectInsurer(insurers) {
`;
- // Display SweetAlert with the Select2 dropdown and text input as HTML content
- const result = await Swal.fire({
- title: 'Select an insurer',
- html: selectHTML,
- showCancelButton: true,
- preConfirm: () => {
+ // Display SweetAlert with the Select2 dropdown and text input as HTML content
+ const result = await Swal.fire({
+ title: 'Select an insurer',
+ html: selectHTML,
+ showCancelButton: true,
+ preConfirm: () => {
- const selectedInsurer = document.getElementById('insurerSelect').value;
- const insurerDetails = document.getElementById('insurerDetails').value;
+ const selectedInsurer = document.getElementById('insurerSelect').value;
+ const insurerDetails = document.getElementById('insurerDetails').value;
- const insurerSelect = document.getElementById('insurerSelect');
- const selectedOption = insurerSelect.options[insurerSelect.selectedIndex];
- const dataId = selectedOption.getAttribute('data-id');
+ const insurerSelect = document.getElementById('insurerSelect');
+ const selectedOption = insurerSelect.options[insurerSelect.selectedIndex];
+ const dataId = selectedOption.getAttribute('data-id');
- if (!selectedInsurer) {
- Swal.showValidationMessage("You need to select an insurer :)");
- }
+ if (!selectedInsurer) {
+ Swal.showValidationMessage("You need to select an insurer :)");
+ }
- return { selectedInsurer, insurerDetails, dataId};
- },
- didOpen: () => {
- // Initialize Select2 on the dropdown
- $('#insurerSelect').select2({
- placeholder: 'Select an insurer',
- dropdownParent: $('.swal2-popup') // Ensure Select2 is rendered inside SweetAlert
- });
+ return {
+ selectedInsurer,
+ insurerDetails,
+ dataId
+ };
+ },
+ didOpen: () => {
+ // Initialize Select2 on the dropdown
+ $('#insurerSelect').select2({
+ placeholder: 'Select an insurer',
+ dropdownParent: $(
+ '.swal2-popup') // Ensure Select2 is rendered inside SweetAlert
+ });
+ }
+ });
+
+ // Return the selected insurer and input details if confirmed
+ if (result.isConfirmed) {
+ return result.value;
}
- });
-
- // Return the selected insurer and input details if confirmed
- if (result.isConfirmed) {
- return result.value;
- }
- return null; // If canceled, return null
+ return null; // If canceled, return null
}
-function setEldersCount(input){
+function setEldersCount(input) {
var selectedOption = $(input).find('option:selected');
- var elders_count = selectedOption.data('value')
- if(elders_count){
+ var elders_count = selectedOption.data('value')
+ if (elders_count) {
$('#family_elders_count').val(elders_count)
- }else{
+ } else {
$('#family_elders_count').val('')
- }
+ }
}
-function hideQCR(){
-
- console.log('hideQCR() function called')
- console.log(RFQ_or_QCR)
+function hideQCR() {
- if(RFQ_or_QCR == 2){
+ // console.log('hideQCR() function called')
+ // console.log(RFQ_or_QCR)
+
+ if (RFQ_or_QCR == 2) {
$('.qcrProposal').hide();
$('.qcrInsurer').hide();
+ $('#addQuote').hide();
$('input[name="qcr"]').hide();
- }else{
+ } else {
$('.qcrProposal').show();
$('.qcrInsurer').show();
+ $('#addQuote').show();
$('input[name="qcr"]').show();
}
}
+function setRowWiseQCRandSTCDatachange(){
+ console.log('isFormDataModified', isFormDataModified);
+ isFormDataModified = true; // if any value changeing in the table to set true
+}
+//-----------------------------------------------------------------------------------------------------------
-function showModal(){
+function showModal(mail_type) {
+
+ if(mail_type == 1){
+ insurerAndClientMailPopUp()
+ }else if(mail_type == 2){
+ var myModal = new bootstrap.Modal(document.getElementById('internal_mail_modal'));
+ myModal.show();
+ }else if(mail_type == 3){
+ placementMailPopUp()
+ }
+
+}
+
+function insurerAndClientMailPopUp(){
var url = '';
var lead_id = $('#lead_id').val();
- if(RFQ_or_QCR == 2){
+ if (RFQ_or_QCR == 2) {
$('#myCenterModalLabel').text('Client contact to send mail')
url = '= base_url('leads/list/') ?>' + lead_id;
- }else{
+ } else {
$('#myCenterModalLabel').text('Choose insurer to send mail')
url = '= base_url('util/getLevelContects') ?>'
}
@@ -2196,21 +2730,53 @@ function showModal(){
myModal.show();
}
-function ajaxRequestForGetMailData(url){
+function placementMailPopUp() {
+
+ console.log(proposalDataForDropDown);
+
+ const selectElement = document.getElementById('proposals');
+
+ // Clear existing options
+ selectElement.innerHTML = '';
+
+ // Loop through the proposal data and append options
+ for (const [proposalKey, proposalValue] of Object.entries(proposalDataForDropDown.over_all_column_data)) {
+ proposalValue.insurers.forEach(insurer => {
+ const option = document.createElement('option');
+ option.value = insurer.id;
+ option.setAttribute("data-id", `${proposalKey}-${insurer.display_name}`);
+ option.textContent = `${proposalKey} - ${insurer.display_name}`;
+ selectElement.appendChild(option);
+ });
+ }
+
+ // Show the modal
+ const myModal = new bootstrap.Modal(document.getElementById('placement_mail_modal'));
+ myModal.show();
+}
+
+function ajaxRequestForGetMailData(url) {
+
+ console.log(url);
+
+ $('.loader').fadeIn();
+ $('.loader-mask').fadeIn();
$.ajax({
url: url,
type: "GET",
dataType: 'json',
- success: function (res) {
-
+ success: function(res) {
+ $('.loader').fadeOut();
+ $('.loader-mask').delay(350).fadeOut('slow');
appendInput(res.data)
-
},
- error: function (xhr, status, error) {
+ error: function(xhr, status, error) {
+ $('.loader').fadeOut();
+ $('.loader-mask').delay(350).fadeOut('slow');
console.error(xhr.responseText);
console.error(status, error);
- }
+ }
});
}
@@ -2223,7 +2789,7 @@ function appendInput(data) {
if (RFQ_or_QCR == 2) {
- const url = '= base_url('leads/list') ?>?lead_id=' +lead_id;
+ const url = '= base_url('leads/list') ?>?lead_id=' + lead_id;
html = `
@@ -2254,7 +2820,7 @@ function appendInput(data) {
for (const id in contacts) {
const contact = contacts[id];
html += `
-
+
`;
}
@@ -2278,33 +2844,135 @@ function appendInput(data) {
}
}
-function constructURL() {
+function constructURL(url_type) {
+
+ if(url_type == 1){
+ constructURL_ForInsurerAndClientMailSend()
+ }else if(url_type == 2){
+ constructURL_ForInternalMailSend()
+ }else if(url_type == 3){
+
+ Swal.fire({
+ title: "Do you want to place the proposal data?",
+ // text: "Do you want Save this!",
+ icon: "warning",
+ showCancelButton: true,
+ confirmButtonColor: "#3085d6",
+ cancelButtonColor: "#d33",
+ confirmButtonText: "Yes, Procced!"
+ }).then((result) => {
+ if (result.isConfirmed) {
+ constructURL_ForPlacementMailSend()
+ }else{
+ return false;
+ }
+ });
+ }
+}
+
+function constructURL_ForInsurerAndClientMailSend() {
var lead_id = $('#lead_id').val();
var apiURL;
if (RFQ_or_QCR == 2) {
apiURL = '= base_url('leads/sendMail') ?>?lead_id=' + encodeURIComponent(lead_id) +
- '&file_type=qcr' +
- '&recipient_type=client' +
- '&recipient_mail=';
+ '&file_type=qcr' +
+ '&recipient_type=client' +
+ '&recipient_mail=';
} else {
-
var insurerContact = $('#insurerContact').val();
- insurerContact = insurerContact.map(Number);
+ insurerContact = insurerContact.map(Number);
console.log(insurerContact);
apiURL = '= base_url('leads/sendMail') ?>?lead_id=' + encodeURIComponent(lead_id) +
- '&file_type=rfq' +
- '&recipient_type=insurer' +
- '&recipient_mail=' + JSON.stringify(insurerContact);
+ '&file_type=rfq' +
+ '&recipient_type=insurer' +
+ '&recipient_mail=' + JSON.stringify(insurerContact);
}
console.log(apiURL);
ajaxRequest(apiURL);
}
-function ajaxRequest(url){
+function constructURL_ForInternalMailSend() {
+
+ var lead_id = $('#lead_id').val();
+ let to = $('#to').val();
+ let = subject = $('#subject').val();
+
+ let cc = $('#cc').val();
+ cc = cc.map(Number);
+ cc = JSON.stringify(cc)
+
+ var file_type = 'rfq';
+ if (RFQ_or_QCR == 2) {
+ file_type = 'qcr'
+ }
+
+ var queryParams = {
+ lead_id: lead_id,
+ file_type: file_type,
+ recipient_type: 'internal',
+ to: to,
+ cc: cc,
+ subject: subject,
+ // mail_content: mail_content,
+ recipient_mail: '',
+ };
+
+ const queryString = objectToQueryString(queryParams);
+ console.log(queryString);
+
+ var apiURL = '= base_url('leads/sendMail') ?>?'+queryString
+
+ console.log(apiURL);
+ ajaxRequest(apiURL);
+}
+
+function constructURL_ForPlacementMailSend() {
+
+ var lead_id = $('#lead_id').val();
+ let to = $('#placement_to').val();
+ let subject = $('#placement_subject').val();
+ // let = mail_content = $('#placement_mail_content').val();
+ let proposal_insurer = $('#proposals option:selected').data('id');
+ let insurer_and_branch = $('#proposals').val();
+
+ let cc = $('#placement_cc').val();
+ cc = cc.map(Number);
+ cc = JSON.stringify(cc)
+
+ to = to.map(Number);
+ to = JSON.stringify(to)
+
+ var file_type = 'rfq';
+ if (RFQ_or_QCR == 2) {
+ file_type = 'qcr'
+ }
+
+ var queryParams = {
+ lead_id: lead_id,
+ file_type: file_type,
+ recipient_type: 'placement',
+ to: to,
+ cc: cc,
+ subject: subject,
+ proposal_insurer: proposal_insurer,
+ insurer_and_branch: insurer_and_branch,
+ recipient_mail: to,
+ };
+
+ const queryString = objectToQueryString(queryParams);
+ console.log(queryString);
+
+ var apiURL = '= base_url('leads/sendMail') ?>?'+queryString
+
+ console.log(apiURL);
+ ajaxRequest(apiURL);
+}
+
+function ajaxRequest(url) {
console.log(url);
@@ -2315,35 +2983,298 @@ function ajaxRequest(url){
url: url,
type: "GET",
dataType: 'json',
- success: function (res) {
+ success: function(res) {
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
console.log(res);
- if(res.status == 'success' && res.code == 200){
+ if (res.status == 'success' && res.code == 200) {
toastr.success('Mail send Successfully', 'SUCCESS')
- }else{
- if(res.messgae){
+ } else {
+ if (res.messgae) {
toastr.error(res.messgae, 'ERROR')
- }else{
+ } else {
toastr.error('Mail send failed', 'ERROR')
}
}
$('.close').click()
},
- error: function (xhr, status, error) {
+ error: function(xhr, status, error) {
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
console.error(xhr.responseText);
console.error(status, error);
- }
+ }
+ });
+
+ $('#to').select2({
+ placeholder: 'Select To Mail',
+ });
+ $('#cc').val('').select2({
+ placeholder : 'select CC Mail'
+ });
+ $('#subject').val('');
+ $('#proposals').val('');
+ $('#placement_to').val('').select2({
+ placeholder : 'select To Mail'
+ });
+ $('#placement_cc').val('').select2({
+ placeholder : 'select CC Mail'
+ });
+ $('#placement_subject').val('');
+
+ $("textarea.select2-search__field").attr('rows', '1');
+ $("textarea.select2-search__field").css('resize', 'none');
+}
+
+function objectToQueryString(obj) {
+ return Object.keys(obj).map(key => `${encodeURIComponent(key)}=${encodeURIComponent(obj[key])}`).join('&');
+}
+
+function getInsurerBranchContacts(input){
+
+ let insurer_and_branch = $(input).val();
+ console.log('insurer_and_branch', insurer_and_branch);
+
+ $('.loader').fadeIn();
+ $('.loader-mask').fadeIn();
+
+ $.ajax({
+ url: '= base_url('util/getInsurerBranchContacts/') ?>' + insurer_and_branch,
+ type: "GET",
+ dataType: 'json',
+ success: function(res) {
+ console.log(res)
+ $('.loader').fadeOut();
+ $('.loader-mask').delay(350).fadeOut('slow');
+ if(res.status == false){
+ toastr.warning(res.message, 'WARNING')
+ }else{
+ appendInsurerContact(res.data)
+ }
+ },
+ error: function(xhr, status, error) {
+ $('.loader').fadeOut();
+ $('.loader-mask').delay(350).fadeOut('slow');
+ console.error(xhr.responseText);
+ console.error(status, error);
+ }
});
}
+function appendInsurerContact(data) {
+
+ console.log(data)
+
+ $('#placement_to').empty();
+ $('#placement_to').append($('
`;
} else {
@@ -2727,8 +3658,8 @@ function jsonToTable(json) {
const qcrChecked = dataEntry.input_value?.qcr ? "checked" : "";
const clientChecked = dataEntry.input_value?.stc ? "checked" : "";
td.innerHTML = `
- QCR
- Client
+ QCR
+ Client
`;
} else {
@@ -2776,57 +3707,628 @@ function jsonToTable(json) {
attachEventListeners();
checkCellValueAndHighlight();
hideQCR()
+
+ isFormDataModified = false;
+ populateTable(json)
}
+function populateTable(json) {
+
+ console.log(json);
+
+ const table = document.getElementById("rfqTable_for_calc");
+ const thead = document.createElement("thead");
+ const tbody = document.createElement("tbody");
+
+ const headerRow1 = document.createElement("tr");
+ const headerRow2 = document.createElement("tr");
+
+
+ // Iterate over the headers to create thead
+ json.table_data.headers.forEach(header => {
+
+ let randomColor = 'hsl(' + Math.random() * 360 + ', 100%, 93%)';
+
+ // Skip unwanted parent headers
+ if (!["Item Key", "Sno", "Action"].includes(header.parentHeader)) {
+ // console.log(header.parentHeader);
+
+ // Create the parent header
+ const th = document.createElement("th");
+ th.textContent = header.parentHeader;
+ th.className = header.parentHeader === "Particulars" ? "sticky" : "";
+ if(header.parentHeader !== 'Particulars'){
+ th.style.backgroundColor = randomColor;
+ }
+ // Calculate colspan based on the number of subheaders
+ const subHeaderCount = header.subHeaders.length;
+ if (subHeaderCount > 0) {
+ th.setAttribute("colspan", subHeaderCount);
+ } else {
+ th.setAttribute("rowspan", 2); // No subheaders, span both rows
+ }
+
+ headerRow1.appendChild(th);
+
+ // Create and append subheaders to the second row
+ header.subHeaders.forEach(subHeader => {
+ const subTh = document.createElement("th");
+ subTh.textContent = subHeader;
+ if(subHeader == '-'){
+ subTh.className = "sticky";
+ }else{
+ subTh.style.backgroundColor = randomColor;
+ }
+ headerRow2.appendChild(subTh);
+ });
+
+ }
+ });
+
+ // Append rows to thead
+ thead.appendChild(headerRow1);
+ thead.appendChild(headerRow2);
+
+ // Append thead to table
+ table.appendChild(thead);
+
+ // Generate tbody rows based on subheaders
+ const rowLabels = ["Premium", "GST", "Total"];
+ rowLabels.forEach(label => {
+ const tr = document.createElement("tr");
+
+ // First column: Row label
+ const tdLabel = document.createElement("td");
+ tdLabel.textContent = label;
+ tdLabel.className = "sticky";
+ tr.appendChild(tdLabel);
+
+ // Create a td for each subheader
+ json.table_data.headers.forEach(header => {
+ if (!["Item Key", "Particulars", "Sno", "Action"].includes(header.parentHeader)) {
+ header.subHeaders.forEach((value, index) => {
+ // if(value != '-'){
+ const td = document.createElement("td");
+ td.setAttribute("contenteditable", "true");
+ td.textContent = json.premium_data?.data?.[header.parentHeader]?.[value]?.[label] || "";
+ tr.appendChild(td);
+ // }
+ });
+ }
+ });
+
+ // Add the row to tbody
+ tbody.appendChild(tr);
+ });
+
+ // Append tbody to table
+ table.appendChild(tbody);
+}
+
+// function generateJSONFromTable() {
+
+// const table = document.getElementById("rfqTable_for_calc");
+// const jsonData = { data: {} };
+
+// // Get the header rows
+// const headerRows = table.querySelectorAll("thead tr");
+// const parentHeaders = [];
+// const subHeadersMap = {};
+
+// // Extract parent headers and map them to subheaders
+// headerRows[0].querySelectorAll("th").forEach((th, index) => {
+// if (index > 0) parentHeaders.push(th.textContent.trim());
+// });
+
+// const subHeaderCountPerParent = Math.floor(headerRows[1].children.length / parentHeaders.length);
+// console.log('subHeaderCountPerParent', subHeaderCountPerParent);
+// console.log('subHeaderCountPerParent', subHeaderCountPerParent-1);
+
+// headerRows[1].querySelectorAll("th").forEach((th, index) => {
+// if (index > 0) {
+// const parentIndex = Math.floor(index / subHeaderCountPerParent); // Adjust parent grouping
+// const parentHeader = parentHeaders[parentIndex] || "Unknown";
+// if (!subHeadersMap[parentHeader]) {
+// subHeadersMap[parentHeader] = [];
+// }
+// subHeadersMap[parentHeader].push(th.textContent.trim());
+// }
+// });
+
+// // Initialize JSON structure for each parent header
+// parentHeaders.forEach(parentHeader => {
+// jsonData.data[parentHeader] = {};
+// subHeadersMap[parentHeader]?.forEach(subHeader => {
+// jsonData.data[parentHeader][subHeader] = {};
+// });
+// });
+
+// // Extract tbody data and populate JSON
+// const bodyRows = table.querySelectorAll("tbody tr");
+// const rowLabels = Array.from(bodyRows).map(row =>
+// row.querySelector("td").textContent.trim()
+// );
+
+// bodyRows.forEach((row, rowIndex) => {
+// const cells = row.querySelectorAll("td");
+// let cellIndex = 1; // Start after the first column (row labels)
+
+// parentHeaders.forEach(parentHeader => {
+// subHeadersMap[parentHeader]?.forEach(subHeader => {
+// const cellValue = cells[cellIndex]?.textContent.trim() || "";
+// jsonData.data[parentHeader][subHeader][rowLabels[rowIndex]] =
+// cellValue;
+// cellIndex++;
+// });
+// });
+// });
+
+// console.log(jsonData);
+// console.log(JSON.stringify(jsonData, null, 2));
+// localStorage.setItem('premium_data', JSON.stringify(jsonData));
+// return jsonData;
+// }
+
+function generateJSONFromTable() {
+
+ const table = document.getElementById("rfqTable_for_calc");
+ const jsonData = { data: {} };
+
+ // Get header rows
+ const headerRows = table.querySelectorAll("thead tr");
+ const parentHeaders = [];
+ const subHeaders = [];
+
+ // console.log('headerRows', headerRows);
+ // console.log('headerRows 1', headerRows[1]);
+ // console.log('headerRows 0', headerRows[0]);
+ // console.log('headerRows 0', headerRows[1].length);
+
+ // Extract parent headers
+ headerRows[0].querySelectorAll("th").forEach((th, index) => {
+ if (index > 0) parentHeaders.push(th.textContent.trim());
+ });
+
+ // Calculate how many subheaders belong to each parent header using `colspan`
+ let currentParentIndex = 0;
+ let remainingColspan = 0;
+
+ headerRows[1].querySelectorAll("th").forEach((th, index) => {
+ if (index > 0) { // Skip the first column if it's for row labels
+ const subHeaderText = th.textContent.trim();
+
+ // If no remainingColspan, move to the next parent header
+ if (remainingColspan === 0) {
+ remainingColspan = parseInt(headerRows[0].querySelectorAll("th")[currentParentIndex + 1]?.getAttribute("colspan") || "1", 10);
+ currentParentIndex++;
+ }
+
+ // Add subheader under the current parent header
+ subHeaders.push({
+ parent: parentHeaders[currentParentIndex - 1], // Adjust for 0-based index
+ subHeader: subHeaderText,
+ });
+
+ // Decrease remainingColspan as a subheader is assigned
+ remainingColspan--;
+ }
+ });
+
+ // Initialize the structure for all parent headers and subheaders
+ parentHeaders.forEach(parent => {
+ jsonData.data[parent] = {};
+ });
+
+ // console.log('jsonData', jsonData);
+ // console.log('parentHeaders', parentHeaders);
+ // console.log('subHeaders', subHeaders);
+
+ // Extract tbody data
+ const bodyRows = table.querySelectorAll("tbody tr");
+ // console.log('bodyRows', bodyRows);
+
+ bodyRows.forEach(row => {
+ const cells = row.querySelectorAll("td");
+ const rowLabel = cells[0]?.textContent.trim();
+
+ let cellIndex = 1; // Start after the first column (row labels)
+ subHeaders.forEach(({ parent, subHeader }) => {
+
+ // console.log('parent', parent)
+ // console.log('subHeader', subHeader)
+ // console.log('parent', jsonData.data[parent])
+ // console.log('subHeader', jsonData.data[parent][subHeader])
+ if (!jsonData.data[parent][subHeader]) {
+ jsonData.data[parent][subHeader] = {};
+ }
+
+ const cellValue = cells[cellIndex]?.textContent.trim() || "";
+ jsonData.data[parent][subHeader][rowLabel] = cellValue;
+ cellIndex++;
+ });
+ });
+
+ console.log(jsonData);
+ // console.log(JSON.stringify(jsonData, null, 2));
+ localStorage.setItem("premium_data", JSON.stringify(jsonData));
+ return jsonData;
+}
+
+function addInsurerDataForPremiumTable(event, insurerName, proposal_name) {
+
+ console.log('########################################################################')
+
+ const closestTh = event.target.closest('th');
+ let colIndex = closestTh.cellIndex;
+ console.log('column index of second table', colIndex);
+ colIndex = colIndex -2
+ console.log('column index of second table', colIndex);
+
+ let rfqTable = document.getElementById('rfqTable_for_calc');
+ const headerRow = rfqTable.rows[1];
+
+ const thElements = rfqTable.querySelectorAll('thead tr:first-child th');
+ let totalColspan = 0;
+
+ for (let i = 0; i <= colIndex; i++) {
+ const colspan = parseInt(thElements[i].getAttribute('colspan')) || 1;
+ totalColspan += colspan;
+ }
+
+ let parentTh = rfqTable.querySelector('thead tr th:nth-child(' + (colIndex + 1) + ')');
+ let columnIndextoCopyData = totalColspan - parentTh.colSpan;
+ parentTh.colSpan += 1;
+
+ // Determine the position for inserting the column
+ let insertPosition = totalColspan; // Default to inserting at the end of the current insurer's columns
+
+ // Add a new column to each row
+ for (let i = 1; i < rfqTable.rows.length; i++) {
+ if (i === 1) {
+ const newHeaderCell = document.createElement('th');
+ newHeaderCell.innerHTML = insurerName;
+ newHeaderCell.style.backgroundColor = parentTh.style.backgroundColor;
+ rfqTable.rows[i].insertBefore(newHeaderCell, rfqTable.rows[i].cells[insertPosition]);
+ } else {
+ const newCell = rfqTable.rows[i].insertCell(insertPosition);
+ newCell.setAttribute('contenteditable', 'true');
+ // newCell.classList.add('editablecolumns');
+ newCell.innerHTML = rfqTable.rows[i].cells[columnIndextoCopyData].innerHTML;
+ newCell.style.backgroundColor = parentTh.style.backgroundColor;
+ }
+ }
+
+ isFormDataModified = true; // if any value changeing in the table to set true
+
+ console.log('########################################################################')
+
+}
+
+function copyInsurerDataForPremiumTable(event, insurerName){
+
+ const thPosition = getThPosition(event);
+
+ let parentThIndex = null;
+ const closestTh = event.target.closest('th');
+ let colIndex = closestTh.cellIndex;
+ console.log('colIndex', colIndex);
+ colIndex = colIndex - 2;
+ let columnText = closestTh.innerText;
+ let proposal_name = columnText.split('⋮')[0].trim();
+ let rfqTable = document.getElementById('rfqTable_for_calc');
+ const headerRows = rfqTable.querySelectorAll('thead tr');
+
+ if (thPosition.rowIndex == 1) //copy insurer
+ {
+ var copyType = event.target.className;
+ let accumulatedColspan = 0;
+ let parentTh = null;
+
+ let subThIndex = colIndex;
+ 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;
+
+ if (subThIndex < accumulatedColspan) {
+ parentTh = currentParentTh;
+ break;
+ }
+ }
+ console.log(parentTh.cellIndex);
+ parentTh = headerRows[0].children[parentTh.cellIndex];
+ parentThIndex = parentTh.cellIndex;
+ console.log(accumulatedColspan + ' - ' + parentTh + ' - ' + subThIndex);
+ proposal_name = parentTh.innerText.split('⋮')[0].trim();
+ }
+
+ console.log(colIndex);
+
+ const headerRow = rfqTable.rows[1];
+
+ //find total no of columns (sub th) untill current parent th
+ const thElements = rfqTable.querySelectorAll('thead tr:first-child th');
+ let totalColspan = 0;
+
+ // Loop through the parent th elements within the specified index range
+ for (let i = 0; i <= parentThIndex; i++) {
+ const colspan = parseInt(thElements[i].getAttribute('colspan')) || 1;
+ totalColspan += colspan;
+ }
+
+
+ // add colspan of current th
+ let parentTh = rfqTable.querySelector('thead tr th:nth-child(' + (parentThIndex + 1) + ')');
+ parentTh.colSpan += 1;
+ // Add a new column to each row
+ for (let i = 1; i < rfqTable.rows.length; i++) {
+
+ if (i == 1) {
+
+ // Create a new element
+ const newHeaderCell = document.createElement('th');
+ newHeaderCell.innerHTML = insurerName;
+ newHeaderCell.style.backgroundColor = parentTh.style.backgroundColor;
+
+ // Insert the element at the desired position
+ rfqTable.rows[i].insertBefore(newHeaderCell, rfqTable.rows[i].cells[totalColspan]);
+
+ } else {
+ const newCell = rfqTable.rows[i].insertCell(totalColspan);
+ newCell.setAttribute('contenteditable', 'true');
+ newCell.innerHTML = rfqTable.rows[i].cells[colIndex].innerHTML;
+ newCell.style.backgroundColor = parentTh.style.backgroundColor;
+ }
+
+ }
+}
+
+function changeInsurerForPremiumTable(event, newInsurerName, secondRowIndex) {
+
+ const table = document.getElementById('rfqTable_for_calc');
+ const headerRows = table.querySelectorAll('thead tr');
+ secondRowIndex = secondRowIndex - 2
+ const secondRow = headerRows[1];
+ const thElements = secondRow.querySelectorAll('th');
+ const closestTh = thElements[secondRowIndex];
+
+ let oldInsurerName = closestTh.innerText.split('⋮')[0].trim();
+
+ let subThIndex = secondRowIndex - 2;
+ console.log(oldInsurerName + ' - ' + newInsurerName);
+
+ // Iterate over child nodes to find the text node containing "Myname"
+ closestTh.childNodes.forEach(node => {
+ if (node.nodeType === Node.TEXT_NODE && node.textContent.includes(oldInsurerName)) {
+ // Replace the old name with the new name
+ node.textContent = node.textContent.replace(oldInsurerName, newInsurerName);
+ }
+ });
+}
+
+function removeInsurerFromPremiumTable(event, secondRowIndex) {
+
+ console.log('########################################################################')
+
+ const table = document.getElementById('rfqTable_for_calc');
+ const headerRows = table.querySelectorAll('thead tr');
+
+ console.log('secondRowIndex', secondRowIndex)
+ const closestTh = event.target.closest('th');
+ let insurerName = closestTh.innerText.split('⋮')[0]
+ console.log('insurerName', insurerName);
+ // let subThIndex = closestTh.cellIndex;
+ // console.log('subThIndex', subThIndex);
+ subThIndex = secondRowIndex - 2
+ console.log('subThIndex', subThIndex);
+
+ // Get the sub TH from the second header row
+ const subTh = headerRows[1].children[subThIndex];
+
+ 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;
+ 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);
+ console.log('startIndex', startIndex);
+
+ // 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]);
+ });
+
+ console.log('########################################################################')
+
+}
+
+function removeProposalForPremiumTable(secondRowIndex) {
+
+ let colIndex = secondRowIndex - 2;
+ console.log('colIndex', colIndex);
+
+ const rfqPremiumTable = document.getElementById('rfqTable_for_calc');
+ console.log(rfqPremiumTable)
+ const headerRows = rfqPremiumTable.querySelectorAll('thead tr');
+
+ const parentTh = headerRows[0].children[colIndex];
+ console.log('parentTh', parentTh);
+ const parentColspan = parseInt(parentTh.getAttribute('colspan')) || 1;
+ const startIndex = Array.from(headerRows[1].children).findIndex(
+ th => th.offsetLeft >= parentTh.offsetLeft
+ );
+ console.log('startIndex', startIndex);
+ console.log('parentColspan', parentColspan);
+
+ // Remove the parent TH
+ headerRows[0].removeChild(parentTh);
+
+ // Remove the relevant sub THs and corresponding TDs
+ for (let i = 0; i < parentColspan; i++) {
+ const subThIndex = startIndex; // The index doesn't shift since we're always removing the same `startIndex`
+
+ // Remove the sub THs
+ const subTh = headerRows[1].children[subThIndex];
+ console.log('Removing subTh', subTh);
+ headerRows[1].removeChild(subTh);
+
+ // Remove the corresponding TDs from each row
+ rfqPremiumTable.querySelectorAll('tbody tr').forEach(row => {
+ const tdToRemove = row.children[subThIndex];
+ console.log('Removing td', tdToRemove);
+ row.removeChild(tdToRemove);
+ });
+ }
+}
+
+