MERGE_CODE_MERGE : RV

This commit is contained in:
VENKATESHWARAN 2025-05-08 10:06:50 +05:30
commit 2f48da98cf
23 changed files with 950 additions and 272 deletions

View File

@ -949,6 +949,9 @@ class EmpDataServiceController extends BaseController
$export_data['event_type'] = 'correction';
$correctionData = $this->employeePolicyModel->getCorrectionEmployeesDataForExportExcel($export_data);
}else if($value == "missed_inception"){
$export_data['event_type'] = 'missed_inception';
$additionData = $this->employeePolicyModel->getInceptionEmployeeDataForExportExcel($export_data);
}
}

View File

@ -1035,6 +1035,14 @@ class EmployeeServiceController extends AdminController
// kint::dump($family);
$family = data_group_by_family($family)[ $emp_id ];// reason to call this again bring self to first index of the array
}
$firstNonTemp = null;
foreach ($family as $fam) {
if (!isset($fam['temp'])) {
$firstNonTemp = $fam;
break;
}
}
// kint::dump($family);//die();
//check name dup within a family
@ -1070,7 +1078,7 @@ class EmployeeServiceController extends AdminController
if(!count($self_details))
{
array_push($result['error_summary'],14); // Self not found
$result['error_data'][ $family[0][0] ]['sno']['error'][] = "Self not found in Database";
$result['error_data'][ $firstNonTemp[0] ]['sno']['error'][] = "Self not found in Database";
}
}
@ -1078,7 +1086,7 @@ class EmployeeServiceController extends AdminController
if($file['action'] == 'dependent_addition' || $file['action'] == 'addition' || $file['action'] == 'inception'|| $file['action'] == 'missed_inception' || $file['action'] == 'enrollment')
{
$res = check_dependent_conflict($family,$policy_terms,$file['action'],$is_lgbtq);
// dd($res);
// Kint::dump($res);
if(!$res['status'])
{
foreach($res['error_data'] as $key => $value)
@ -1091,7 +1099,7 @@ class EmployeeServiceController extends AdminController
//check dup with empid and name with db
$res = name_and_empid_check_in_db($family,$file);
// dd($res);
// Kint::dump($res['del']);
// echo '<br/>';
// print_r($res);
if(count($res['del']))
@ -1113,7 +1121,7 @@ class EmployeeServiceController extends AdminController
}// end of foreach
}// end of if current action I,DA,A
// return $result;
// return $result;
// die();
if(isset($result['error_summary']) && count($result['error_summary']))
{

View File

@ -103,8 +103,9 @@ class LeadsController extends BaseController
$this->issuer = [1 => 'JIBS', 2 => 'Nhance'];
$this->clientType = [1 => 'Group', 2 => 'Individual'];
$this->leadType = [1 => 'Fresh', 2 => 'Renewal', 3 => 'Roll Over'];
$this->buisnessType = [1 => 'Industrial', 2 => 'Non Industrial'];
$data = $this->kycEntityTypeModel->where('is_active', 1)->findAll();
$this->buisnessType = array_column($data, 'name', 'id');
// $this->buisnessType = [1 => 'Public Sector', 2 => 'Private Sector',3=> 'Trust',4 => 'Proprietorship',5 => 'Partnership',6 => 'Private',7 => 'Individual'];
$this->leadsStatus = [
'queued' => 'In-Queued',
'rfq_created' => 'RFQ Created',
@ -739,11 +740,14 @@ class LeadsController extends BaseController
$data["child_table_data"] = json_decode($data['question_json'], true)['child_table_data'];
}
$data['product'] = $this->leadsModel->select("policy_type.policy_type")->join('policy_type', 'leads.policy_type_id = policy_type.id')->where('leads.id', $id)->first()['policy_type'];
// $data['lead_register_data'] = json_decode($data['lead_data']['custom_fields']);
// dd($data['lead_register_data']);
// $data['entity_type'] = $this->kycEntityTypeModel->where('is_active', 1)->findAll();
$data['buisness_type'] = $this->buisnessType;
// dd($data);
$data['client_type'] = $this->clientType;
$data['buisness_type'] = $this->buisnessType;
$this->loadLayout('view_rfq_non_eb', $data);
}
}
@ -2148,6 +2152,7 @@ class LeadsController extends BaseController
->where('leads.id', $lead_id)
->first();
// log_message('error', 'Lead Data' . json_encode($lead_data));
// print_r($lead_data ); die;
$cc_mails = [];
@ -2308,9 +2313,9 @@ class LeadsController extends BaseController
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("{{RECIPIENT_NAME}}", $recipient['name'] != "" ? $recipient['name'] :" ", $message);
$message = str_replace("{{CLIENT_NAME}}", $lead_data['client_name'] != "" ? $lead_data['client_name'] : "", $message);
$message = str_replace("{{POLICY_LONG_NAME}}",$lead_data['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) ?? '--';
@ -2917,7 +2922,7 @@ class LeadsController extends BaseController
$value = $cellData['display_content'] ?? '';
// Skip unwanted keys
if (in_array($parentth, ['SNO', 'Particulars', 'Action']) || $subth === 'Quote Asked') {
if (in_array($parentth, ['SNO', 'Particulars', 'Action']) || $subth === 'Sum Insured' || $subth === 'Fidelity Limit') {
continue;
}
@ -3158,7 +3163,6 @@ class LeadsController extends BaseController
$data['lead_edit_data']['claims_details_html'] = "";
}
}
// dd($data);
return $this->loadLayout('leads_form_handler', $data);
@ -3191,6 +3195,7 @@ class LeadsController extends BaseController
3 => 'rfq/gmc',
4 => 'rfq/gmc',
5 => 'rfq/gmc',
17=> 'rfq/burglary',
22 => 'rfq/car',
23 => 'rfq/cpm',
24 => 'rfq/cyber_crime',
@ -3330,11 +3335,11 @@ class LeadsController extends BaseController
$sheet->getColumnDimension('B')->setWidth($maxWidthA * 1.2);
$sheet->getColumnDimension('C')->setWidth($maxWidthB * 1.2);
$rowNumber += 2;
$rowNumber += 1;
//Policy Registration
if (!empty($policy_registration_data)) {
foreach ($policy_registration_data as $key => $value) {
// kint::dump($value);
$startRow = $rowNumber; // Track where the block starts
// Title Row
@ -3421,6 +3426,24 @@ class LeadsController extends BaseController
$rowNumber++;
}
if (isset($value['policyDetails']) && !empty($value['policyDetails'])) {
// Type of Business
$sheet->mergeCells("A{$rowNumber}:B{$rowNumber}");
$sheet->setCellValue("A{$rowNumber}", "Terrorism");
$sheet->setCellValue("C{$rowNumber}", ucfirst($value['policyDetails']['terrorism'] ?? 'No'));
$sheet->getStyle("A{$rowNumber}")->applyFromArray([
'font' => ['bold' => true],
'alignment' => [
'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
],
]);
$rowNumber++;
}
$endRow = $rowNumber - 1; // Block ends at previous row
// Apply border to the whole block
@ -3433,8 +3456,9 @@ class LeadsController extends BaseController
],
]);
$rowNumber += 2; // Add space before the next block
$rowNumber += 1; // Add space before the next block
}
// die();
}
//Table Data
@ -3538,6 +3562,18 @@ class LeadsController extends BaseController
}
}
// For the subheader row, merge B and C and set the value
$sheet->setCellValue("B{$subHeaderRow}", "Sum Insured");
$sheet->mergeCells("B{$subHeaderRow}:C{$subHeaderRow}");
$sheet->getStyle("B{$subHeaderRow}:C{$subHeaderRow}")->applyFromArray([
'font' => ['bold' => true],
'alignment' => [
'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
],
]);
// Apply border to the header range
$prevColumn4 = $this->getPreviousColumn($columnLetter);
$headerRange = "A{$rowNumber}:" . "{$prevColumn4}" . "{$subHeaderRow}";
@ -3554,7 +3590,9 @@ class LeadsController extends BaseController
$sheet->getRowDimension($rowNumber)->setRowHeight(25); // Header row height
$sheet->getRowDimension($subHeaderRow)->setRowHeight(20); // Subheader row height
$rowNumber = $subHeaderRow + 2;
// $rowNumber = $subHeaderRow + 2;
$rowNumber = $subHeaderRow + 1;
$column_data = $data['table_data']['data'];
// dd($column_data);
$serial_no = 1;
@ -3842,7 +3880,7 @@ class LeadsController extends BaseController
$row['data'] = array_filter(
$row['data'],
function ($item) {
return in_array($item['subth'], ['Quote asked', '-']);
return in_array($item['subth'], ['Sum Insured', '-',"Liability Limit"]);
}
);
@ -3931,7 +3969,7 @@ class LeadsController extends BaseController
if ($subHeader === $insurer) {
$headerData[] = [
'parentHeader' => $header['parentHeader'],
'subHeaders' => ['Quote asked', $subHeader]
'subHeaders' => ['Sum Insured', $subHeader]
];
break 2; // Exit both loops after match is found
}
@ -3964,8 +4002,8 @@ class LeadsController extends BaseController
$filteredData[] = $item;
}
// Include Proposal with Quote Asked
if ($item['parentth'] === $proposal && $item['subth'] === "Quote asked") {
// Include Proposal with Sum Insured
if ($item['parentth'] === $proposal && ($item['subth'] === "Sum Insured" || $item['subth'] === "Liability Limit")) {
$filteredData[] = $item;
}

View File

@ -440,8 +440,20 @@ if (!function_exists('name_dup_check_within_family'))
foreach ($family_data as $rkey => $row)
{
if(in_array($row[2],$temp))
{
array_push($result,$row[0]);
{
// Kint::dump($row);
$emp_code = $row[1];
$tempFam = null;
foreach ($family_data as $family) {
if ($family[1] == $emp_code &&!isset($family['temp'])) {
$tempFam = $family;
break; // Stop at the first match
}
}
// Kint::dump($tempFam);
// die();
array_push($result,$tempFam[0]);
}
else
{
@ -449,7 +461,7 @@ if (!function_exists('name_dup_check_within_family'))
}
}
// dd($result);
return $result;
}
}
@ -519,7 +531,15 @@ if (!function_exists('name_and_empid_check_in_db'))
}
if(($current_action == 'inception' || $current_action == 'dependent_addition' || $current_action == 'addition' || $current_action == 'enrollment') && count($res))
{
array_push($result['i'],$row[0]);
$emp_code = $row[1];
$tempFam = null;
foreach ($family_data as $family) {
if ($family[1] == $emp_code &&!isset($family['temp'])) {
$tempFam = $family;
break; // Stop at the first match
}
}
array_push($result['i'],$tempFam[0]);
}
}

View File

@ -884,7 +884,7 @@
<?php
if (isset($policy_type) && count($policy_type)) {
foreach ($policy_type as $value) {
if ($value['allocg'] != "Non-EB") {
if ($value['allocg'] != "Non-EB" && $value['allocg'] != "Marine") {
echo "<option value='" . $value['id'] . "'>" . $value['policy_type'] . "</option>";
}
}

View File

@ -256,19 +256,19 @@ hr.solid {
</select>
</div>
<div class="form-group col-md-3">
<!-- <div class="form-group col-md-3">
<label for="tpa">TPA <span class="text-danger"></span></label>
<select class="form-control" id="tpa" name="tpa">
<option value="">Select TPA</option>
<?php if (isset($tpa)) { ?>
<?php foreach ($tpa as $value) { ?>
<option value="<?= $value['id'] . '-' . $value['tpa_id'] ?>">
<?= $value['tpa_short_name'] . '-' . $value['branch_code'] ?>
<?php //if (isset($tpa)) { ?>
<?php //foreach ($tpa as $value) { ?>
<option value="<?php // echo $value['id'] . '-' . $value['tpa_id'] ?>">
<?php // echo $value['tpa_short_name'] . '-' . $value['branch_code'] ?>
</option>
<?php } ?>
<?php } ?>
<?php //} ?>
<?php //} ?>
</select>
</div>
</div> -->
<div class="form-group col-md-3">
<label for="">Date of Commencement <span class="text-danger">*</span></label>

View File

@ -1,9 +1,9 @@
<div class="modal fade" id="policyRegisterModel" tabindex="-1" aria-labelledby="fullWidthModalLabel" aria-hidden="true">
<div class="modal fade" id="policyRegisterModel" tabindex="-1" aria-labelledby="fullWidthModalLabel" aria-hidden="true" data-backdrop="static" data-keyboard="false">
<div class="modal-dialog modal-xl modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="fullWidthModalLabel">REGISTER POLICY INFORMATION</h4>
<button type="button" onclick="resetAllform()" class="close" data-dismiss="modal" aria-label="Close">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
@ -150,10 +150,10 @@
</div>
<div class="row">
<div class="col-md-4">
<div class="form-check">
<input type="checkbox" class="form-check-input" id="terrorismSwitch">
<label class="form-check-label" for="terrorismSwitch">Is Terrorism Required?</label>
<div class="col-md-4 dt-switch-wrapper">
<div class="custom-control custom-switch">
<input type="checkbox" class="custom-control-input" id="terrorismSwitch">
<label class="custom-control-label" for="terrorismSwitch">Is Terrorism Required?</label>
</div>
</div>
<div class="form-group col-md-4">
@ -166,7 +166,21 @@
<option value="4_month">4 Months</option>
<option value="5_month">5 Months</option>
<option value="6_month">6 Months</option>
<option value="7_month">7 Months</option>
<option value="8_month">8 Months</option>
<option value="9_month">9 Months</option>
<option value="10_month">10 Months</option>
<option value="11_month">11 Months</option>
<option value="12_month">12 Months</option>
<option value="2_year">2 Year</option>
<option value="3_year">3 Year</option>
<option value="4_year">4 Year</option>
<option value="5_year">5 Year</option>
<option value="6_year">6 Year</option>
<option value="7_year">7 Year</option>
<option value="8_year">8 Year</option>
<option value="9_year">9 Year</option>
<option value="10_year">10 Year</option>
</select>
</div>
<div id="locationNoDIV" class="form-group col-md-4">
@ -203,11 +217,11 @@
<div class="text-right">
<button type="submit" id="riskSplitup" class="btn btn-primary">Validate and Add Risk Split up</button>
</div>
<div class="row">
<!-- <div class="row">
<div class="col-md-12 text-right">
<button type="submit" id="submitPolicyRisk" class="btn btn-primary">Submit For Validation</button>
</div>
</div>
</div> -->
</form>
</div>
@ -244,6 +258,20 @@
// console.log("Occupancy : ", occupancyMaster);
var storedPolicyData = {};
storedPolicyData = JSON.parse(localStorage.getItem('policyData'));
var isFormDirty = false;
$(document).ready(function() {
// Listen for changes in all inputs, selects, and textareas within your modal
$('#policyRegisterModel').on('change input', 'input, select, textarea', function() {
// alert("function called");
isFormDirty = true;
// console.log("Form is dirty",isFormDirty);
});
});
$(document).ready(function() {
// resetAllform();
// console.log("Stored date Found : ", typeof(storedPolicyData));
@ -306,6 +334,7 @@
});
$('#productSelectionForm').submit(function(event) {
// console.log("Submit function called");
event.preventDefault();
var isValid = $('#productSelectionForm').parsley().validate();
@ -358,7 +387,8 @@
$("#policyRiskSplitUpForm").submit(function(event) {
event.preventDefault();
isFormDirty = false;
var isValid = $('#policyRiskSplitUpForm').parsley().validate();
// console.log('isValid', isValid);
@ -402,26 +432,38 @@
let InProcess = [...document.querySelectorAll('[id^="stockInProcess_"]')].map(el => Number(el.value) || 0);
let rawMaterial = [...document.querySelectorAll('[id^="rawMaterial_"]')].map(el => Number(el.value) || 0);
let findMaterial = [...document.querySelectorAll('[id^="finishedStock_"]')].map(el => Number(el.value) || 0);
let building = [...document.querySelectorAll('[id^="building_"]')].map(el => Number(el.value) || 0);
let content = [...document.querySelectorAll('[id^="content_"]')].map(el => Number(el.value) || 0);
let furniture = [...document.querySelectorAll('[id^="furniture_"]')].map(el => Number(el.value) || 0);
let plantAndMachinery = [...document.querySelectorAll('[id^="plantAndMachinery_"]')].map(el => Number(el.value) || 0);
let electricalFittings = [...document.querySelectorAll('[id^="electricalFittings_"]')].map(el => Number(el.value) || 0);
totalSI = InProcess.reduce((acc, val) => acc + val, 0) +
rawMaterial.reduce((acc, val) => acc + val, 0) +
findMaterial.reduce((acc, val) => acc + val, 0);
totalSI = InProcess.reduce((acc, val) => acc + val, 0) +
rawMaterial.reduce((acc, val) => acc + val, 0) +
findMaterial.reduce((acc, val) => acc + val, 0) +
building.reduce((acc, val) => acc + val, 0) +
content.reduce((acc, val) => acc + val, 0) +
furniture.reduce((acc, val) => acc + val, 0) +
plantAndMachinery.reduce((acc, val) => acc + val, 0) +
electricalFittings.reduce((acc, val) => acc + val, 0);
let allowedSI = Number($("#policySI").val()) || 0;
// alert(allowedSI);
if (totalSI > allowedSI) {
toastr.error("Sum Insured Exceeds Allowed Limit", "ERROR");
return false;
if (totalSI != allowedSI) {
console.log("allowedSI : ", allowedSI, " totalSI : ", totalSI);
toastr.error("Sum Insured Does not Match Allowed Limit", "ERROR");
return false;
}
// console.log("Total SI: ", totalSI);
}else{
} else {
let InProcess = [...document.querySelectorAll('[id^="stockInProcess_"]')].map(el => Number(el.value) || 0);
let rawMaterial = [...document.querySelectorAll('[id^="rawMaterial_"]')].map(el => Number(el.value) || 0);
let findMaterial = [...document.querySelectorAll('[id^="finishedStock_"]')].map(el => Number(el.value) || 0);
totalSI = InProcess.reduce((acc, val) => acc + val, 0) +
rawMaterial.reduce((acc, val) => acc + val, 0) +
findMaterial.reduce((acc, val) => acc + val, 0);
totalSI = InProcess.reduce((acc, val) => acc + val, 0) +
rawMaterial.reduce((acc, val) => acc + val, 0) +
findMaterial.reduce((acc, val) => acc + val, 0);
}
}
@ -432,6 +474,10 @@
// Determine the number of dynamic rows based on a field that appears per row
const totalRows = formDataSplitUp.filter(field => field.name === "building[]").length;
if (totalRows != policyDetailsData.location_no) {
toastr.error("Please Enter All Risk Address", "ERROR");
return;
}
// Initialize empty objects for each row
for (let i = 0; i < totalRows; i++) {
groupData.push({});
@ -465,6 +511,7 @@
// console.log("Grouped Data as Objects: ", policyRiskSplitUpData);
savePolicyDataLocal();
});
@ -484,11 +531,28 @@
return;
}
const formData = $("#policyRiskAddressForm").serializeArray();
console.log("formdata 1 : ", formData);
$("[id^='isBasement_']").each(function() {
let checkbox = $(this);
let isChecked = checkbox.is(":checked");
let increment = checkbox.attr("id").split("_")[1];
formData.push({
name: `is_basement[]`,
value: isChecked ? "yes" : "no"
});
});
console.log("formdata 2 : ", formData);
const groupedData = [];
// Determine the number of dynamic rows
const totalRows = formData.filter(field => field.name === "pin_code[]").length;
if (totalRows != policyDetailsData.location_no) {
toastr.error("Please Enter All Risk Address", "ERROR");
return;
}
// Initialize empty objects for each row
for (let i = 0; i < totalRows; i++) {
groupedData.push({});
@ -513,13 +577,14 @@
});
policyRiskAddress = groupedData;
// console.log("Grouped Data as Objects: ", policyRiskAddress);
console.log("Grouped Data as Objects: ", policyRiskAddress);
if (productSelectionData.singleProduct == 'on') {
savePolicyDataLocal();
} else {
// if (productSelectionData.singleProduct == 'on') {
// savePolicyDataLocal();
// } else {
riskSplitup();
}
// }
});
$("#policyDetailsForm").submit(function(event) {
@ -538,14 +603,17 @@
return;
}
var formData = $("#policyDetailsForm").serializeArray();
formData.push({
name: "terrorism",
value: $('#terrorismSwitch').is(':checked') ? 'yes' : 'no'
})
$.each(formData, function(i, field) {
policyDetailsData[field.name] = field.value;
});
// // console.log("form data", policyDetailsData.location_no);
console.log("form data", formData);
if (formData !== null && formData !== '') {
// console.log("form submitted trying to open the ris info tab");
// riskInfoTabOpened();
const riskTab = new bootstrap.Tab(document.getElementById('risk-info-tab'));
riskTab.show();
@ -585,6 +653,14 @@
hideAndShowBurglary();
})
}else{
// alert("you got ir");
policyRiskAddress.forEach(function() {
// console.log("increment count is ", increment2)
addHTMLInputForRiskSplitUP();
validatePolicyBasedOnProductSelection();
hideAndShowBurglary();
})
}
} else {
if (contianertoCheck.innerHTML == "") {
@ -640,29 +716,29 @@
// policyRiskAddress
newRowRisk.innerHTML += `
<h5 class = "fire">Fire (Sookshma/Laghu) Details</h5>
<h5 class = "fire">Fire <?= isset($product) ? $product : "" ?> Details</h5>
<h5>Risk Split Up for Address : ${policyRiskAddress[increment2-1].address1} ${policyRiskAddress[increment2-1].address2}</h5>
<input type = "hidden" name = "location_selected[]" value = "${policyRiskAddress[increment2-1].select_location}" id = "location_selected_${increment2}" />
<div class = "row">
<div class="form-group col-md-4 multi_location_company">
<label for="building_${increment2}">Building</label>
<input type="text" id="building_${increment2}" name="building[]" class="form-control multi_location_company " />
<input type="number" id="building_${increment2}" name="building[]" class="form-control multi_location_company " />
</div>
<div class="form-group col-md-4 multi_location_company ">
<div class="form-group col-md-4 multi_location_company ">
<label for="content_${increment2}">Content</label>
<input type="text" id="content_${increment2}" name="content[]" class="form-control multi_location_company " />
<input type="number" id="content_${increment2}" name="content[]" class="form-control multi_location_company " />
</div>
<div class="form-group col-md-4 multi_location_company ">
<label for="furniture_${increment2}">Furniture/Office Equipment</label>
<input type="text" id="furniture_${increment2}" name="furniture[]" class="form-control multi_location_company " />
<input type="number" id="furniture_${increment2}" name="furniture[]" class="form-control multi_location_company " />
</div>
<div class="form-group col-md-4 multi_location_company ">
<label for="plantAndMachinery_${increment2}">Plant and Machinery</label>
<input type="text" id="plantAndMachinery_${increment2}" name="plant_and_machinery[]" class="form-control multi_location_company " />
<input type="number" id="plantAndMachinery_${increment2}" name="plant_and_machinery[]" class="form-control multi_location_company " />
</div>
<div class="form-group col-md-4 multi_location_company">
<label for="electricalFittings_${increment2}">Electrical Fittings</label>
<input type="text" id="electricalFittings_${increment2}" name="electrical_fittings[]" class="form-control multi_location_company "/>
<input type="number" id="electricalFittings_${increment2}" name="electrical_fittings[]" class="form-control multi_location_company "/>
</div>
</div>
<br>
@ -678,7 +754,7 @@
<input type="number" id="rawMaterial_${increment2}" name="raw_material[]" class="form-control multi_location_company" />
</div>
<div class="form-group col-md-4 multi_location_company">
<label for="finishedStock_${increment2}">Finished Stock</label>
<label for="finishedStock_${increment2}">Stock</label>
<input type="number" id="finishedStock_${increment2}" name="finished_stock[]" class="form-control multi_location_company"/>
</div>
</div>
@ -782,20 +858,9 @@
<label for="address3_${increment}">Address 3</label>
<input type="text" id="address3_${increment}" name="address3[]" class="form-control" />
</div>
<div class="form-group col-md-4">
<label for="constructionType_${increment}">Construction Type<span class="text-danger">*</span></label>
<select id="constructionType_${increment}" name="construction_type[]" class="form-control">
<option value="kutcha" selected>Kutcha</option>
<option value="pucca">Pucca</option>
</select>
</div>
<div class="form-group col-md-4">
<label for="basementSI_${increment}">Basement Sum Insured</label>
<input type="text" id="basementSI_${increment}" name="basement_si[]" class="form-control"/>
</div>
<div class="form-group col-md-4">
<label for="occupancy_${increment}">Occupancy<span class="text-danger">*</span></label>
<select id="occupancy_${increment}" name="occupancy[]" class="form-control" onchange="showRequiredFieldsBasedOnLocation('occupancy_${increment}')" required>
<div class="form-group col-md-4" style = "width: 10px !important;">
<label for="occupancy_${increment}">Occupancy Risk<span class="text-danger">*</span></label>
<select id="occupancy_${increment}" name="occupancy[]" class="form-control" onchange="showRequiredFieldsBasedOnLocation(this)" required>
<option value="">Select</option>
${occupancyMaster.map(occupancy =>
`<option value="${occupancy.id}">${occupancy.description}</option>`
@ -803,16 +868,30 @@
</select>
</div>
<div class="form-group col-md-4 common_location_occupancy">
<label for="isBasement_${increment}">Basement<span class="text-danger">*</span></label>
<select id="isBasement_${increment}" name="is_basement[]" class="form-control common_location_occupancy" required>
<option value="yes" selected>Yes</option>
<option value="no">No</option>
<label for="iibCode_${increment}">IIB Code<span class="text-danger">*</span></label>
<input type="text" onchange = "updateOccupancyRisk(this)" id="iibCode_${increment}" name="iib_code[]" class="form-control common_location_occupancy" required>
</div>
<div class="form-group col-md-4">
<label for="constructionType_${increment}">Construction Type<span class="text-danger">*</span></label>
<select id="constructionType_${increment}" name="construction_type[]" class="form-control">
<option value="kutcha" selected>Kutcha</option>
<option value="pucca">Pucca</option>
</select>
</div>
<div class="form-group col-md-4 common_location_occupancy">
<label for="iibCode_${increment}">IIB Code<span class="text-danger">*</span></label>
<input type="text" id="iibCode_${increment}" name="iib_code[]" class="form-control common_location_occupancy" required>
<div class="dt-switch-wrapper col-md-4 common_location_occupancy d-flex align-items-center">
<div class="custom-control custom-switch d-flex justify-content-center">
<input type="checkbox" class="custom-control-input" id="isBasement_${increment}" onchange="hideShowBasement(this)">
<label class="custom-control-label" for="isBasement_${increment}">Basement</label>
</div>
</div>
<div class="form-group col-md-4" style="display:none" >
<label for="basementSI_${increment}">Basement Utilisation</label>
<input type="text" id="basementSI_${increment}" name="basement_si[]" class="form-control"/>
</div>
<div class="form-group col-md-4 multiLocationOccupancy">
<label for="select_location_${increment}">Location <span class="text-danger">*</span></label>
<select required id="select_location_${increment}" name="select_location[]" class="form-control multiLocationOccupancy">
@ -850,26 +929,13 @@
`;
// newRow2.innerHTML += `
// <div class = "row">
// <div class="col-md-12 text-right">
// <button type ="submit" id="riskSplitup" class="btn btn-primary">Validate and Add Risk Split up</button>
// </div>
// </div>
// <div class = "row">
// <div class="col-md-12 text-right">
// <button type ="submit" id="submitPolicyRisk" class="btn btn-primary">Submit For Validation</button>
// </div>
// </div>
// `;
container.appendChild(newRow);
// container.appendChild(newRow2);
const selectElement = document.getElementById(`select_location_${increment}`);
selectElement.innerHTML = "";
for (let i = 1; i <= policyDetailsData.location_no; i++) {
console.log("location no : ", policyDetailsData.location_no);
const option = document.createElement('option');
option.value = `Location ${i}`;
option.textContent = `Location ${i}`;
@ -887,37 +953,33 @@
});
$(document).on('click', '.duplicate-btn', function() {
// console.log("button is clicked");
// console.log("increment cout ", increment);
$(document).on('click', '.duplicate-btn', function () {
if (policyDetailsData.location_no >= increment) {
const $rowToClone = $(this).closest('.form-row');
// Destroy Select2 for the current and previous occupancy fields
$(`#occupancy_${increment}`).select2('destroy');
$(`#occupancy_${increment - 1}`).select2('destroy');
// Clone the row
const $clone = $rowToClone.clone();
$clone.find('.select2-hidden-accessible').each(function() {
// Clean up select2 artifacts from the clone
$clone.find('.select2-hidden-accessible').each(function () {
$(this).select2('destroy');
});
$clone.find('.select2-container').remove();
// Increment the counter
// Update all IDs and reset values in the clone
$clone.find('[id]').each(function() {
// Update all IDs in the clone
$clone.find('[id]').each(function () {
const oldId = $(this).attr('id');
const newId = oldId.replace(/_(\d+)$/, `_${increment}`);
$(this).attr('id', newId);
});
// Update labels to match new IDs
$clone.find('label').each(function() {
// Update all labels
$clone.find('label').each(function () {
const oldFor = $(this).attr('for');
if (oldFor) {
const newFor = oldFor.replace(/_(\d+)$/, `_${increment}`);
@ -928,18 +990,35 @@
// Insert the cloned row after the original
$clone.insertAfter($rowToClone);
let selectedLocation = $(`#select_location_${increment}`).val();
$(`#select_location_${increment} option[value="${selectedLocation}"]`).remove();
$(`#occupancy_${increment}`).select2();
// Refill and update the select_location dropdown
const selectElement = document.getElementById(`select_location_${increment}`);
selectElement.innerHTML = "";
for (let i = 1; i <= policyDetailsData.location_no; i++) {
const option = document.createElement('option');
option.value = `Location ${i}`;
option.textContent = `Location ${i}`;
selectElement.appendChild(option);
}
for (let i = 1;i<increment;i++){
let selectedLocation = $(`#select_location_${i}`).val();
$(`#select_location_${increment} option[value="${selectedLocation}"]`).remove();
}
// Re-initialize Select2 for both fields
$(`#occupancy_${increment - 1}`).select2(); // previous
$(`#occupancy_${increment}`).select2(); // current
$(`#iibCode_${increment}`).val(""); // current
increment++;
} else {
toastr.error("Maximum no of allowed locations reached", "Error")
toastr.error("Maximum number of allowed locations reached", "Error");
}
});
})
function addOrRemoveAdd() {
// console.log("chceck box clicked");
if ($("#sameAsCommunicationAddress").is(":checked")) {
@ -969,10 +1048,10 @@
$('[id^="select_location"]').hide().prev('label').hide();
$("[id^='select_location']").removeAttr('required', false);
// $('[class*="single_location_occupancy"]').hide().removeAttr("required", false);
$('[class*="multi_location_company"]').hide().removeAttr('required');
$("#riskSplitup").hide();
// $('[class*="multi_location_company"]').hide().removeAttr('required');
// $("#riskSplitup").hide();
$("#submitPolicyRisk").show();
$("#risksplitupTab").hide();
// $("#risksplitupTab").hide();
// $('[class*="multiLocationOccupancy"]').hide().removeAttr('required', false);
// $('[class*="multiLocationOccupancyWithoutFloater"]').hide().removeAttr('required', false);
@ -1005,79 +1084,56 @@
}
function showRequiredFieldsBasedOnLocation(element) {
if (element) {
// alert(element);
var selectedOccupancy = $(`#${element}`).val();
var selectedOccupancy = $(element).val(); // FIXED
var selectedOccupancyMasterRow = occupancyMaster.find(iib => iib.id == selectedOccupancy);
// console.log("selected occupancy masater ", selectedOccupancyMasterRow)
// console.log("selected occupancy masater ", occupancyMaster)
if (!selectedOccupancyMasterRow) return;
var iibCODE = selectedOccupancyMasterRow.iib_code;
// console.log("selected occupancy masater ", iibCODE)
var elementID = element;
var elementID = element.id; // FIXED
let increment = elementID.split("_").pop();
// console.log("selected occupancy masater increment ", increment)
// console.log("selected occupancy masater element ", $(`#iibCode_${increment}`))
setTimeout(function() {
$(`#iibCode_${increment}`).val(iibCODE); // Set the value
// console.log("Selected --------------------", $(`#iibCode_${increment}`).val()); // Log the value
}, 1000);
$(`#iibCode_${increment}`).val(iibCODE);
}, 500);
}
// console.log("onchange occupancy function called ");
// // console.log("onchange occupancy function called ", selectedOccupancy);
// // console.log("onchange occupancy function called ", selectedOccupancyMasterRow);
// // console.log("onchange occupancy function called ", iibCODE);
// // console.log("onchange occupancy function called ", increment);
$('[class*="common_location_occupancy"]').show().prop("required", "required");
$('[class*="common_location_occupancy"]').show().prop("required", true);
var selectedProduct = productSelectionData;
if (selectedProduct.singleProduct == 'on') {
$('[class*="single_location_occupancy"]').show().prop("required", "required");
} else if (selectedProduct.multipleProduct == 'on') {
// // console.log("Muliple location");f
$('[class*="multiLocationOccupancy"]').show().prop('required', 'required');
if (selectedProduct.singleProduct === 'on') {
$('[class*="single_location_occupancy"]').show().prop("required", true);
} else if (selectedProduct.multipleProduct === 'on') {
$('[class*="multiLocationOccupancy"]').show().prop('required', true);
if (selectedProduct.multilocation_type == "multiLocation") {
// // console.log("multiple location without Floater");
$('[class*="multiLocationOccupancyWithoutFloater"]').show().prop('required', 'required');
} else if (selectedProduct.multilocation_type == "multiFloater") {
// // console.log("Muliple location With Floater");
$('[class*="multiLocationOccupancyWithoutFloater"]').hide().removeAttr('required', false);
} else if (selectedProduct.multilocation_type == "stockFloater") {
// // console.log("multiple location with stock floater");
$('[class*="multiLocationOccupancyWithoutFloater"]').show().prop('required', 'required');
$('[class*="stockSI"]').hide().removeAttr('required', false);
if (selectedProduct.multilocation_type === "multiLocation") {
$('[class*="multiLocationOccupancyWithoutFloater"]').show().prop('required', true);
} else if (selectedProduct.multilocation_type === "multiFloater") {
$('[class*="multiLocationOccupancyWithoutFloater"]').hide().removeAttr('required');
} else if (selectedProduct.multilocation_type === "stockFloater") {
$('[class*="multiLocationOccupancyWithoutFloater"]').show().prop('required', true);
$('[class*="stockSI"]').hide().removeAttr('required');
}
}
}
function registerPolicyData() {
var policyType;
if (totalSI<50000000){
if (totalSI < 50000000) {
policyType = "Bharat Sookshma Udyam Suraksha (BSUS)"
} else if (totalSI > 50000000 && totalSI < 500000000){
} else if (totalSI > 50000000 && totalSI < 500000000) {
policyType = "Bharat Laghu Udyam Suraksha (BLUS)"
}else if (totalSI >500000000 ){
} else if (totalSI > 500000000) {
policyType = "Standard Fire and Special Perils (SFSP)";
}
}
// Build the initial JSON object with productSelection and policyDetails
var outputData = {
policyType:policyType,
policyType: policyType,
productSelection: productSelectionData,
policyDetails: policyDetailsData,
locations: []
@ -1108,6 +1164,8 @@
}
function savePolicyDataLocal() {
isSaved = false;
// Generate the JSON structure using the registerPolicyData function
var policyData = registerPolicyData();
@ -1127,18 +1185,20 @@
// Save the updated data back to localStorage
localStorage.setItem('policyData', JSON.stringify(existingData));
if (!$.isEmptyObject(existingData)) {
// console.log("DATA FROM DB : ", (existingData));
let data = (existingData);
Object.keys(data).forEach(key => {
policySummary[key] = addPolicySummaryTable(data[key], key);
prependTable(policySummary[key],key);
prependTable(policySummary[key], key);
});
}
$('.loader').fadeIn();
$('.loader-mask').fadeIn();
toastr.success("Policy Information Collected ","SUCCESS");
toastr.success("Policy Information Collected ", "SUCCESS");
closeModal();
changeTerrorism(Number($("#policySI").val()));
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
// console.log("Updated policy data in localStorage:", existingData);
@ -1220,7 +1280,7 @@
loadPolicyDataBack(data);
assignDataToFields(data);
// alert("inside else");
}else{
} else {
// alert("nothing");
}
// console.log("policy data : ", data);
@ -1255,9 +1315,9 @@
const policyDetails = data.policyDetails;
Object.keys(policyDetails).forEach(key => {
$(`#${key}`).val(policyDetails[key]);
// // console.log("Key ",key," set value : ",policyDetails[key]);
// console.log("Key ", key, " set value : ", policyDetails[key]);
});
$('#terrorismSwitch').prop('checked', policyDetails.terrorism === "yes")
// Populate Risk Addresses
data.locations.forEach((location, index) => {
addHTMLInputForRiskAddress();
@ -1277,12 +1337,13 @@
$(`#constructionType${prefix}`).val(risk.construction_type);
$(`#occupancy${prefix}`).select2();
$(`#occupancy${prefix}`).val(risk.occupancy).trigger("change");
$(`#isBasement${prefix}`).val(risk.is_basement);
// $(`#isBasement${prefix}`).val(risk.is_basement);
$(`#iibCode${prefix}`).val(risk.iib_code);
$(`#buisness_desc${prefix}`).val(risk.buisness_desc);
$(`#select_location${prefix}`).val(risk.select_location);
$(`#basementSI${prefix}`).val(risk.basement_si);
$(`#isBasement${prefix}`).prop('checked', risk.is_basement === "yes").trigger("change");
@ -1318,7 +1379,7 @@
});
isFormDirty = false; // Reset the form dirty flag
}
function checkandassignLeadData() {
@ -1332,11 +1393,12 @@
function assignLeadData() {
const lead_data = <?= json_encode(json_decode($lead_data['custom_fields'])) ?>;
var clientName = <?= isset($lead_data['client_name']) ? json_encode($lead_data['client_name']) : ""?>;
var clientName = <?= isset($lead_data['client_name']) ? json_encode($lead_data['client_name']) : "" ?>;
var client_type = <?= isset($lead_data['client_type']) ? $lead_data['client_type'] : "" ?>;
var mobile = <?= isset($lead_data['client_type']) ? $lead_data['client_type'] : "" ?>;
var email = <?= isset($lead_data['client_type']) ? $lead_data['client_type'] : "" ?>;
var mobile = <?= isset($lead_data['contact_person_mobile']) ? $lead_data['contact_person_mobile'] : "" ?>;
var contact_email = "<?= isset($lead_data['contact_person_email']) ? $lead_data['contact_person_email'] : "" ?>";
var panNo = <?= isset($lead_data['client_type']) ? $lead_data['client_type'] : "" ?>;
var buisnessType = <?= isset($lead_data['entity_type_id']) ? $lead_data['entity_type_id'] : "" ?>;
// console.log("client_type : ".client_type);
if (lead_data) {
// lead_data = JSON.parse(lead_data);
@ -1358,9 +1420,16 @@
}
}
$("#client_type").val(client_type).trigger("change");
$("#insured_name").val(clientName);
$("#address1").val(lead_data.address);
$("#pin_code").val(lead_data.pincode);
$("#mobile").val(mobile);
$("#email").val(contact_email);
console.log("buisness type : ", buisnessType);
$("#type_of_buisness").val(buisnessType);
// var policy_type = lead_data.policy_type_id;
}
}
@ -1378,6 +1447,8 @@
}
function resetAllform() {
// isFormDirty = false;
// console.log("FORM RESETED SUCCESSFULLY");
$("#productSelectionForm")[0].reset();
$("#policyDetailsForm")[0].reset();
@ -1403,12 +1474,39 @@
hideAndShowBurglary()
}
$('.close').on('click', function() {
$('.tab-pane').removeClass('active show');
$('.close').on('click', function(e) {
console.log("is form dirty : ", isFormDirty);
if (isFormDirty) {
e.preventDefault();
e.stopPropagation();
Swal.fire({
title: 'You have unsaved changes!',
text: 'Do you want to close without saving your data?',
icon: 'warning',
showCancelButton: true,
confirmButtonText: 'Yes, close it',
cancelButtonText: 'No, stay here',
}).then((result) => {
if (result.isConfirmed) {
isFormDirty = false; // Reset flag
closeModal();
resetAllform();
// $('#policyRegisterModel').modal('hide');
$('.tab-pane').removeClass('active show');
$("#addRiskInfo, #addRiskSplitUp").empty();
}
});
return false;
} else {
resetAllform();
$('.tab-pane').removeClass('active show');
$("#addRiskInfo, #addRiskSplitUp").empty();
}
});
$("#addRiskInfo, #addRiskSplitUp").empty();
})
function copyFirePolicy() {
// console.log("Copying Fire Policy Data...");
@ -1429,4 +1527,108 @@
hideAndShowBurglary();
}
$(document).on('input', 'input[id^="pin_code"]', function() {
// alert("inside");
let value = $(this).val().replace(/\D/g, '').slice(0, 6);
$(this).val(value);
});
function closeModal() {
document.querySelector('#policyRegisterModel [data-dismiss="modal"]').click();
}
function updateOccupancyRisk(element) {
let iibCode = $(element).val();
// Find matching occupancy row
let matchedOccupancy = occupancyMaster.find(iib => iib.iib_code == iibCode);
let matchedId = matchedOccupancy ? matchedOccupancy.id : null;
// Get increment from the element ID, like "iibCode_3"
let elementID = element.id;
let increment = elementID.split("_").pop(); // Extract "3" from "iibCode_3"
if (matchedId) {
$(`#occupancy_${increment}`).val(matchedId).trigger("change");
$(`#occupancy_${increment}`).select2();
} else {
toastr.error("Invalid IIB Code", "Error");
}
}
function hideShowBasement(element) {
let elementID = element.id;
let increment = elementID.split("_").pop();
let isBasement = $(`#isBasement_${increment}`).is(":checked");
// Get the label associated with the input
let label = $(`label[for='basementSI_${increment}']`);
if (isBasement) {
$(`#basementSI_${increment}`).parent().show();
$(`#basementSI_${increment}`).prop("required", "required");
// Add * if not already there
if (label.find(".text-danger").length === 0) {
label.append('<span class="text-danger">*</span>');
}
} else {
$(`#basementSI_${increment}`).parent().hide();
$(`#basementSI_${increment}`).removeAttr("required");
// Remove * if exists
label.find(".text-danger").remove();
}
}
// function saveDataAsDraft() {
// return new Promise((resolve) => {
// const forms = [
// document.getElementById('productSelectionForm'),
// document.getElementById('policyDetailsForm'),
// document.getElementById('policyRiskAddressForm'),
// document.getElementById('policyRiskSplitUpForm')
// ];
// let isDirty = false;
// forms.forEach(form => {
// if (form) {
// const formInputs = form.querySelectorAll('input, select, textarea');
// formInputs.forEach(input => {
// if (input.defaultValue !== input.value && input.value !== '') {
// isDirty = true;
// }
// if (input.type === 'checkbox' || input.type === 'radio') {
// if (input.checked !== input.defaultChecked) {
// isDirty = true;
// }
// }
// });
// }
// });
// if (isDirty) {
// Swal.fire({
// title: 'You have unsaved changes!',
// text: 'Do you want to close without saving your data?',
// icon: 'warning',
// showCancelButton: true,
// confirmButtonText: 'Yes, close it',
// cancelButtonText: 'No, stay here',
// }).then((result) => {
// resolve(result.isConfirmed);
// });
// } else {
// resolve(true); // No unsaved changes, allow closing
// }
// });
// }
</script>

View File

@ -4,7 +4,7 @@
<?php foreach ($multi_file_data as $file) : ?>
<div class="form-check">
<input type="checkbox" class="form-check-input multi_file_attachment" id="file_<?= $file['id'] ?>" name="selected_attachment_files[]" value="<?= $file['id'] ?>" checked>
<input type="checkbox" class="form-check-input multi_file_attachment" id="file_<?= $file['id'] ?>" name="selected_attachment_files[]" value="<?= $file['id'] ?>">
<label class="form-check-label" for="file_<?= $file['id'] ?>">
<?= htmlspecialchars($file['docs_name']) ?> - <?= htmlspecialchars($file['file_name']) ?>
</label>

View File

@ -20,7 +20,11 @@
</div>
<!-- Address -->
<div class="form-group col-md-6">
<div class="form-group col-md-3">
<label for="pinCode">Pin Code</label>
<input type="text" class="form-control" id="pinCode" name="pincode" value="<?= isset($lead_edit_data['pincode']) ? htmlspecialchars($lead_edit_data['pincode']) : ''; ?>">
</div>
<div class="form-group col-md-3">
<label for="address">Address</label>
<textarea class="form-control" id="address" name="address" rows="1"><?= isset($lead_edit_data['address']) ? htmlspecialchars($lead_edit_data['address']) : ''; ?></textarea>
</div>

View File

@ -20,7 +20,11 @@
</div>
<!-- Address -->
<div class="form-group col-md-6">
<div class="form-group col-md-3">
<label for="pinCode">Pin Code</label>
<input type="text" class="form-control" id="pinCode" name="pincode" value="<?= isset($lead_edit_data['pincode']) ? htmlspecialchars($lead_edit_data['pincode']) : ''; ?>">
</div>
<div class="form-group col-md-3">
<label for="address">Address</label>
<textarea class="form-control" id="address" name="address" rows="1"><?= isset($lead_edit_data['address']) ? htmlspecialchars($lead_edit_data['address']) : ''; ?></textarea>
</div>

View File

@ -0,0 +1,32 @@
<hr>
<div class="form-row custom_fields">
<!-- Risk Location -->
<div class="form-group col-md-6">
<label>Risk Location</label><br>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="risk_location" value="single" <?= isset($lead_edit_data['risk_location']) && $lead_edit_data['risk_location'] == 'single' ? 'checked' : ''; ?>>
<label class="form-check-label">Single</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="risk_location" value="multi_with_floter" <?= isset($lead_edit_data['risk_location']) && $lead_edit_data['risk_location'] == 'multi_with_floter' ? 'checked' : ''; ?>>
<label class="form-check-label">Multi with Floter</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="risk_location" value="multi_without_floter" <?= isset($lead_edit_data['risk_location']) && $lead_edit_data['risk_location'] == 'multi_without_floter' ? 'checked' : ''; ?>>
<label class="form-check-label">Multi without Floter</label>
</div>
</div>
<!-- Address -->
<div class="form-group col-md-3">
<label for="pinCode">Pin Code</label>
<input type="text" class="form-control" id="pinCode" name="pincode" value="<?= isset($lead_edit_data['pincode']) ? htmlspecialchars($lead_edit_data['pincode']) : ''; ?>">
</div>
<div class="form-group col-md-3">
<label for="address">Address</label>
<textarea class="form-control" id="address" name="address" rows="1"><?= isset($lead_edit_data['address']) ? htmlspecialchars($lead_edit_data['address']) : ''; ?></textarea>
</div>
</div>

View File

@ -68,7 +68,11 @@
</div>
<!-- Address -->
<div class="form-group col-md-6">
<div class="form-group col-md-3">
<label for="pinCode">Pin Code</label>
<input type="text" class="form-control" id="pinCode" name="pincode" value="<?= isset($lead_edit_data['pincode']) ? htmlspecialchars($lead_edit_data['pincode']) : ''; ?>">
</div>
<div class="form-group col-md-3">
<label for="address">Address:</label>
<textarea class="form-control" id="address" name="address"><?= isset($lead_edit_data['address']) ? htmlspecialchars($lead_edit_data['address']) : ''; ?></textarea>
</div>

View File

@ -14,7 +14,7 @@
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" id="multi_floater" name="risk_location" value="multi_with_floter"
<?= isset($lead_edit_data['risk_location']) && $lead_edit_data['risk_location'] == 'multi_with_floter' ? 'checked' : ''; ?>>
<label class="form-check-label" for="multi_floater">multi_with_floter</label>
<label class="form-check-label" for="multi_floater">Multi With Floater</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" id="multi_no_floater" name="risk_location" value="multi_without_floter"
@ -81,7 +81,11 @@
</div>
<!-- Communication Address -->
<div class="form-group col-md-6">
<div class="form-group col-md-3">
<label for="pinCode">Pin Code</label>
<input type="text" class="form-control" id="pinCode" name="pincode" value="<?= isset($lead_edit_data['pincode']) ? htmlspecialchars($lead_edit_data['pincode']) : ''; ?>">
</div>
<div class="form-group col-md-3">
<label for="address">Communication Address</label>
<textarea class="form-control" id="address" name="address" rows="1"><?= isset($lead_edit_data['address']) ? htmlspecialchars($lead_edit_data['address']) : ''; ?></textarea>
</div>

View File

@ -68,7 +68,11 @@
</div>
<!-- Address -->
<div class="form-group col-md-6">
<div class="form-group col-md-3">
<label for="pinCode">Pin Code</label>
<input type="text" class="form-control" id="pinCode" name="pincode" value="<?= isset($lead_edit_data['pincode']) ? htmlspecialchars($lead_edit_data['pincode']) : ''; ?>">
</div>
<div class="form-group col-md-3">
<label for="address">Address</label>
<textarea class="form-control" id="address" name="address" rows="1"><?= isset($lead_edit_data['address']) ? htmlspecialchars($lead_edit_data['address']) : ''; ?></textarea>
</div>

View File

@ -14,7 +14,11 @@
</div>
<!-- Address of the Insured -->
<div class="form-group col-md-6">
<div class="form-group col-md-3">
<label for="pinCode">Pin Code</label>
<input type="text" class="form-control" id="pinCode" name="pincode" value="<?= isset($lead_edit_data['pincode']) ? htmlspecialchars($lead_edit_data['pincode']) : ''; ?>">
</div>
<div class="form-group col-md-3">
<label for="address">Address of the Insured</label>
<textarea class="form-control" id="address" name="address" rows="1"><?= isset($lead_edit_data['address']) ? htmlspecialchars($lead_edit_data['address']) : ''; ?></textarea>
</div>

View File

@ -35,7 +35,11 @@
</div>
<!-- Address of the Insured -->
<div class="form-group col-md-6">
<div class="form-group col-md-3">
<label for="pinCode">Pin Code</label>
<input type="text" class="form-control" id="pinCode" name="pincode" value="<?= isset($lead_edit_data['pincode']) ? htmlspecialchars($lead_edit_data['pincode']) : ''; ?>">
</div>
<div class="form-group col-md-3">
<label for="address">Address of the Insured</label>
<textarea class="form-control" id="address" name="address" rows="1"><?= isset($lead_edit_data['address']) ? htmlspecialchars($lead_edit_data['address']) : ''; ?></textarea>
</div>

View File

@ -35,7 +35,11 @@
</div>
<!-- Address of the Insured -->
<div class="form-group col-md-6">
<div class="form-group col-md-3">
<label for="pinCode">Pin Code</label>
<input type="text" class="form-control" id="pinCode" name="pincode" value="<?= isset($lead_edit_data['pincode']) ? htmlspecialchars($lead_edit_data['pincode']) : ''; ?>">
</div>
<div class="form-group col-md-3">
<label for="address">Address of the Insured</label>
<textarea class="form-control" id="address" name="address" rows="1"></textarea>
</div>

View File

@ -178,7 +178,11 @@
</div>
<!-- Address -->
<div class="form-group col-md-6">
<div class="form-group col-md-3">
<label for="pinCode">Pin Code</label>
<input type="text" class="form-control" id="pinCode" name="pincode" value="<?= isset($lead_edit_data['pincode']) ? htmlspecialchars($lead_edit_data['pincode']) : ''; ?>">
</div>
<div class="form-group col-md-3">
<label for="address">Address</label>
<textarea class="form-control" id="address" name="address" rows="1">value="<?= isset($lead_edit_data['address']) ? $lead_edit_data['address'] : '' ?>"</textarea>
</div>

View File

@ -2,7 +2,7 @@
<div class="form-row custom_fields">
<!-- Risk Location -->
<div class="form-group col-md-6">
<!-- <div class="form-group col-md-6">
<label>Risk Location</label>
<div>
<?php
@ -21,7 +21,7 @@
<label class="form-check-label" for="multi_no_floater">Multi without Floater</label>
</div>
</div>
</div>
</div> -->
<!-- Policy Period -->
<div class="form-group col-md-3">
@ -67,7 +67,11 @@
</div>
<!-- Communication Address -->
<div class="form-group col-md-6">
<div class="form-group col-md-3">
<label for="pinCode">Pin Code</label>
<input type="text" class="form-control" id="pinCode" name="pincode" value="<?= isset($lead_edit_data['pincode']) ? htmlspecialchars($lead_edit_data['pincode']) : ''; ?>">
</div>
<div class="form-group col-md-3">
<label for="address">Communication Address</label>
<textarea class="form-control" id="address" name="address" rows="1"><?= isset($lead_edit_data['address']) ? htmlspecialchars($lead_edit_data['address']) : ''; ?></textarea>
</div>

View File

@ -27,6 +27,10 @@
</div>
<!-- Address -->
<div class="form-group col-md-3">
<label for="pinCode">Pin Code</label>
<input type="text" class="form-control" id="pinCode" name="pincode" value="<?= isset($lead_edit_data['pincode']) ? htmlspecialchars($lead_edit_data['pincode']) : ''; ?>">
</div>
<div class="form-group col-md-4">
<label for="address">Address</label>
<textarea class="form-control" id="address" name="address" rows="1"><?= isset($lead_edit_data['address']) ? htmlspecialchars($lead_edit_data['address']) : ''; ?></textarea>

View File

@ -35,7 +35,11 @@
</div>
<!-- Communication Address -->
<div class="form-group col-md-6">
<div class="form-group col-md-3">
<label for="pinCode">Pin Code</label>
<input type="text" class="form-control" id="pinCode" name="pincode" value="<?= isset($lead_edit_data['pincode']) ? htmlspecialchars($lead_edit_data['pincode']) : ''; ?>">
</div>
<div class="form-group col-md-3">
<label for="address">Communication Address</label>
<textarea class="form-control" id="address" name="address" rows="1"><?= isset($lead_edit_data['address']) ? htmlspecialchars($lead_edit_data['address']) : ''; ?></textarea>
</div>

View File

@ -33,7 +33,11 @@
</div>
<!-- Communication Address -->
<div class="form-group col-md-6">
<div class="form-group col-md-3">
<label for="pinCode">Pin Code</label>
<input type="text" class="form-control" id="pinCode" name="pincode" value="<?= isset($lead_edit_data['pincode']) ? htmlspecialchars($lead_edit_data['pincode']) : ''; ?>">
</div>
<div class="form-group col-md-3">
<label for="address">Communication Address</label>
<textarea class="form-control" id="address" name="address" rows="1"><?= isset($lead_edit_data['address']) ? htmlspecialchars($lead_edit_data['address']) : ''; ?></textarea>
</div>

View File

@ -516,10 +516,13 @@
</div><!-- /.modal -->
<script>
var isSaved = true;
// var randomColor = 'hsl(' + Math.random() * 360 + ', 100%, 93%)';
var rfq_data = <?= isset($rfq_data['json']) ? json_encode($rfq_data['json'], JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT) : '""' ?>;
rfq_data = rfq_data ? JSON.parse(rfq_data) : {}; // Convert to object if not already
var policySI = "";
var rfq_or_qcr = 1;
var proposalDataForDropDown = {};
var lead_type = "<?= $lead_data['lead_type'] ?>";
@ -536,7 +539,7 @@
// alert(rollover_or_renewal);
var policyConfig = {
1: ['Quote asked']
1: ['Sum Insured']
};
let myModal;
@ -547,6 +550,9 @@
'insurers': []
}
};
var tdChanged = false;
var changedNewSI = "";
var suggestions = {};
var policyInformationData = <?= isset($rfq_data['registration_json']) ? json_encode($rfq_data['registration_json'], JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT) : '""' ?>;
var storedData = {};
@ -564,6 +570,7 @@
// // console.log("policy summary is set :", !$.isEmptyObject(policySummary) ? "no" : "yes")
$(document).ready(function() {
myModal = new bootstrap.Modal(document.getElementById('policyRegisterModel'));
// monitorTableChanges();
});
var tableCount = 0;
const policies = <?= json_encode($policies) ?>;
@ -634,7 +641,7 @@
let proposalCount = 1;
// // console.log("Proposal count changed", proposalCount);
let quotesConfig = {
1: ['Quote asked']
1: ['Sum Insured']
}; // Stores quote columns for each proposal
@ -688,6 +695,7 @@
// Remove a proposal column
function removeProposal(proposalNumber) {
isSaved = false;
// alert(proposalNumber);
var rowIdCount = {};
@ -801,6 +809,7 @@
function addRow(event, element) {
// // console.log(' event ', element);
isSaved = false;
const button = event.target;
const row = button.closest('tr');
const table = row.closest('table');
@ -826,6 +835,7 @@
// Remove a row
function removeRow(event) {
isSaved = false;
const button = event.target;
const row = button.closest('tr');
const table = row.closest('table');
@ -1000,10 +1010,11 @@
document.getElementById('addProposal').addEventListener('click', () => {
// // console.log("proposal count before ", proposalCount);
proposalCount++;
isSaved = false;
// // console.log("proposal count after ", proposalCount);
quotesConfig[proposalCount] = ['Quote asked'];
policyConfig[proposalCount] = ['Quote asked'];
quotesConfig[proposalCount] = ['Sum Insured'];
policyConfig[proposalCount] = ['Sum Insured'];
const tables = document.querySelectorAll('table');
let increaseBy = 150;
increaseTableWidth(increaseBy);
@ -1037,7 +1048,13 @@
// Add new quote sub-header
const newQuoteHeader = document.createElement('th');
newQuoteHeader.textContent = 'Quote asked';
if (table.id != "public_liability_addOnCoverage"){
newQuoteHeader.textContent = 'Sum Insured';
}else{
newQuoteHeader.textContent = "Liability Limit";
}
newQuoteHeader.style.backgroundColor = randomColor;
headerRow2.insertBefore(newQuoteHeader, headerRow2.querySelector('th:last-child'));
@ -1586,19 +1603,26 @@
</th>
`).join('')}
<th>Action</th>`;
console.log("quotesConfig",quotesConfig);
const headerRow2 = document.createElement('tr');
headerRow2.innerHTML = `
<th>-</th>
<th>-</th>
${Object.entries(quotesConfig).flatMap(([proposal, codes]) =>
${Object.entries(quotesConfig).flatMap(([proposal, codes]) =>
// codes.map(code => `
// <th data-proposal="${proposal}" data-quote="${code}" class="${code !== 'Sum Insured' && code !== "Liability Limit" ? 'insurer_proposal' : ''}">
// ${table.id == "public_liability_addOnCoverage" ? "Liability Limit" : code}
// <span class="three-dot-menu" onclick="showDropdown(event)">&#8942;</span>
// <div class="dropdown-content">
// <button onclick="removeQuote(event, ${proposal}, '${code}')">Remove Quote</button>
// </div>
// </th>
// `)
// ).join('')}
codes.map(code => `
<th data-proposal="${proposal}" data-quote="${code}" class="${code !== 'Quote asked' ? 'insurer_proposal' : ''}">
${code}
<span class="three-dot-menu" onclick="showDropdown(event)">&#8942;</span>
<div class="dropdown-content">
<button onclick="removeQuote(event, ${proposal}, '${code}')">Remove Quote</button>
</div>
<th data-proposal="${proposal}" data-quote="${code}" class="${code !== 'Sum Insured' && code !== "Liability Limit" ? 'insurer_proposal' : ''}">
${table.id == "public_liability_addOnCoverage" ? "Liability Limit" : code}
</th>
`)
).join('')}
@ -1723,8 +1747,8 @@
// }
let subHeaderText = subHeaderTh ? subHeaderTh.textContent.trim() : '';
// // console.log("Subheader th: below code",subHeaderText);
// Check if subheader is NOT "Quote asked"
let className = !subHeaderText.startsWith("Quote asked") && subHeaderText != "-" ?
// Check if subheader is NOT "Sum Insured"
let className = !subHeaderText.startsWith("Sum Insured") && subHeaderText != "-" && !subHeaderText.startsWith("Liability Limit")?
"insurer_proposal" : "";
// console.log("className", className);
// alert(subHeaderText);
@ -1776,6 +1800,17 @@
tableContainer.appendChild(collapsibleBar);
tableContainer.appendChild(tableContent);
container.appendChild(tableContainer);
monitorTableChanges();
if (changedNewSI != null && changedNewSI != ""){
console.log("Changed new SI",changedNewSI);
setTimeout(function() {
updateAddON(changedNewSI)
}, 500);
}
}
@ -1826,8 +1861,8 @@
let subHeaderTh = validSubHeaders.find(th => th.textContent.trim());
let subHeaderText = subHeaderTh ? subHeaderTh.textContent.trim() : '';
// Check if subheader is NOT "Quote asked"
let className = !subHeaderText.startsWith("Quote asked") && subHeaderText != "-" ?
// Check if subheader is NOT "Sum Insured"
let className = !subHeaderText.startsWith("Sum Insured") && subHeaderText != "-" && !subHeaderText.startsWith("Liability Limit")?
"insurer_proposal" : ""; // alert(subHeaderText);
let defaultJsonString = typeof default_answers_array == "object" ? JSON.stringify(default_answers_array[0]) : String(default_answers_array);
@ -1863,10 +1898,12 @@
});
moveExcessTableLast();
styleTableColumns();
monitorTableChanges()
return false;
} else {
return true;
}
}
// Initialize the parent table
document.addEventListener('DOMContentLoaded', () => {
@ -1883,6 +1920,7 @@
localStorage.setItem('allTablesJsonData', JSON.stringify(rfq_data));
jsonToTables();
styleTableColumns();
monitorTableChanges();
proposalDataForDropDown = rfq_data[rfq_data.length - 1].proposal_data;
// // console.log("proposalDataForDropDown", proposalDataForDropDown);
if (!$.isEmptyObject(storedData)) {
@ -2190,6 +2228,7 @@
}
function addOrRemoveIcon(element, event) {
isSaved = false;
event.stopPropagation();
// Get the parent dropdown to access both buttons reliably
@ -2257,16 +2296,20 @@
// // console.log("anchor link clicked ", policyName);
myModal = new bootstrap.Modal(document.getElementById('policyRegisterModel'));
myModal = new bootstrap.Modal(document.getElementById('policyRegisterModel'),{
backdrop: 'static',
keyboard: false
});
// // console.log("inside if condition");
var leadID = $("#lead_id").val();
let policy = policies.find(p => p.name === policyName);
// alert(policy.quote_asked[0]);
// var policySI = policies[]
policySI = rfq_count == 0 && !tdChanged ? policy.quote_asked[0] : (changedNewSI) != "" && changedNewSI != 0? changedNewSI : policy.quote_asked[0];
console.log("policy si",policySI,"rfq ount ",rfq_count,"tdchanged ",tdChanged,"changedNewSI",changedNewSI);
$("#policyName").val(policyName);
$("#policySI").val(policy.quote_asked[0]);
$("#policySI").val(policySI);
$("#leadID").val(leadID);
$("#multilocation_type_div").hide();
$('.loader').fadeIn();
@ -2296,7 +2339,68 @@
// Loop through each location and generate the summary rows dynamically
for (let i = 0; i < locationCount; i++) {
let locationIndex = i + 1; // To make it 1-based instead of 0-based
let locationIndex = i + 1;
let rowContents = [
{
[`fire_plantMachineries_${locationIndex}`]: {
"display_value": "Plant & Machineries and Accessories",
"answer_type": "free-text",
"default_answer": storedData.locations[i].policyRiskSplitUp?.plant_and_machinery || ""
}
},
{
[`fire_electricalFittings_${locationIndex}`]: {
"display_value": "Electronic Equipments and Accessories",
"answer_type": "free-text",
"default_answer": storedData.locations[i].policyRiskSplitUp?.electrical_fittings || ""
}
},
{
[`fire_furnitureFittings_${locationIndex}`]: {
"display_value": "FFF (Furniture, Fixtures & Fittings)",
"answer_type": "free-text",
"default_answer": storedData.locations[i].policyRiskSplitUp?.furniture || ""
}
},
{
[`fire_content_${locationIndex}`]: {
"display_value": "Other Contents Related to Insured",
"answer_type": "free-text",
"default_answer": storedData.locations[i].policyRiskSplitUp?.content || ""
}
},
{
[`fire_content_${locationIndex}`]: {
"display_value": "Stock",
"answer_type": "free-text",
"default_answer": storedData.locations[i].policyRiskSplitUp?.finished_stock || ""
}
}
];
// ✅ Keep the structure, add extra only if value is present
const riskSplit = storedData.locations[i].policyRiskSplitUp || {};
if (riskSplit.stock_in_process) {
rowContents.push({
[`fire_content_${locationIndex}`]: {
"display_value": "Stock In Process",
"answer_type": "free-text",
"default_answer": riskSplit.stock_in_process
}
});
}
if (riskSplit.raw_material) {
rowContents.push({
[`fire_content_${locationIndex}`]: {
"display_value": "Raw Materials",
"answer_type": "free-text",
"default_answer": riskSplit.raw_material
}
});
}
tableRowContent.push({
table_type: "new",
@ -2306,40 +2410,12 @@
storedData.locations[i].policyRisk['occupancy'] + "- " +
storedData.locations[i].policyRisk['address1'] + " " +
storedData.locations[i].policyRisk['address2'],
table_row_contents: [{
[`fire_plantMachineries_${locationIndex}`]: {
"display_value": "Plant & Machineries and Accessories",
"answer_type": "free-text",
"default_answer": storedData.locations[i].policyRiskSplitUp?.plantAndMachinery || ""
}
},
{
[`fire_electricalFittings_${locationIndex}`]: {
"display_value": "Electronic Equipments and Accessories",
"answer_type": "free-text",
"default_answer": storedData.locations[i].policyRiskSplitUp?.electricalFittings || ""
}
},
{
[`fire_furnitureFittings_${locationIndex}`]: {
"display_value": "FFF (Furniture, Fixtures & Fittings)",
"answer_type": "free-text",
"default_answer": storedData.locations[i].policyRiskSplitUp?.furniture || ""
}
},
{
[`fire_content_${locationIndex}`]: {
"display_value": "Other Contents Related to Insured",
"answer_type": "free-text",
"default_answer": storedData.locations[i].policyRiskSplitUp?.content || ""
}
}
]
table_row_contents: rowContents
});
}
var policySummary = tableRowContent;
// // console.log("policy summary ", policySummary);
console.log("policy summary ", policySummary);
return policySummary;
}
@ -2406,6 +2482,8 @@
}
function saveRFQ() {
// alert("Function Called");
isSaved = true;
// // console.log("save button clicked");
leadJson = tablesToJson();
// // console.log("json from function ", leadJson);
@ -2775,8 +2853,13 @@
return allTablesData;
}
function openQCR() {
async function openQCR() {
if (!isSaved){
const proceed = await confirmUnsavedChanges();
// if (!proceed) {}
// return;
}
const url = window.location.pathname; // Get the path (e.g., "/nhance/rfq/list/75/1")
const segments = url.split("/"); // Split by "/"
segments[segments.length - 1] = "2"; // Change the last segment
@ -2820,8 +2903,8 @@
// if (!proposalNumber) return; // Skip if extraction fails
// Initialize with "Quote asked"
result[proposalNumber] = ["Quote asked"];
// Initialize with "Sum Insured"
result[proposalNumber] = ["Sum Insured"];
// Check if insurers exist and filter those with qcr = 1
if (Array.isArray(proposalData.insurers)) {
@ -2862,8 +2945,8 @@
let proposal = overallColumnData[proposalKey];
let insurersList = proposal.insurers.map(ins => ins.ins_name); // Extract insurer names
// Create output format: index { "Quote asked", ...insurers }
quotesConfiguration[index] = ["Quote asked", ...insurersList];
// Create output format: index { "Sum Insured", ...insurers }
quotesConfiguration[index] = ["Sum Insured", ...insurersList];
});
@ -2987,13 +3070,14 @@
// Create body
const tbody = document.createElement('tbody');
var cellCount = 0;
tableEntry.table_data.data.forEach((rowData, rowDataIndex) => {
const tr = document.createElement('tr');
tr.id = rowData.row_id;
if (tableEntry.tableId === "excess" && rowData.parentPolicy) {
tr.setAttribute('data-excess-row-parent', rowData.parentPolicy);
}
// Process each cell
rowData.data.forEach((cellData, cellIndex) => {
const td = document.createElement(cellIndex === 0 ? 'td' : 'td');
@ -3032,19 +3116,28 @@
if (lead_type == 1){
td.onclick = () => getAnswer(table.id, tr.id);
if (cellData.subth != "Quote asked") {
if (cellData.subth != "Sum Insured" && cellData.subth != "Liability Limit") {
td.onclick = () => getAnswer(table.id, tr.id);
td.classList.add("insurer_proposal");
}
}else{
td.onclick = () => getAnswer(table.id, tr.id);
if (cellData.subth != "Quote asked") {
if (cellData.subth != "Sum Insured" && cellData.subth != "Liability Limit") {
td.onclick = () => getAnswer(table.id, tr.id);
td.classList.add("insurer_proposal");
}
}
if (cellData.subth == "Sum Insured" && cellData.parentth == "Proposal 1" && table.id == "" && cellCount === 0){
console.log("cell count : ",cellCount)
changedNewSI = cellData.input_value;
console.log("changed new si from jsontotables",changedNewSI);
$("#policySI").val(changedNewSI);
cellCount = cellCount + 1;
}
}
td.contentEditable = true;
@ -3246,8 +3339,8 @@
const matchedInsurer = insurers.find(ins => ins.ins_name == subHeader);
if (subHeader != "Quote asked") {
// // console.log("trying to find something : matchedInsurer", matchedInsurer);
if (subHeader != "Sum Insured" && subHeader != "Liability Limit") {
console.log("trying to find something : matchedInsurer", subHeader);
// // console.log("trying to find something :matchedInsurer stc ", matchedInsurer.stc);
// // console.log("trying to find something : ", matchedInsurer.stc);
@ -3642,7 +3735,7 @@
}
function makeQuoteAskedColumnNonEditableorEditable() {
// alert("Quote asked");
// alert("Sum Insured");
$("table").each(function() {
var table = $(this);
var subHeaderRow = table.find("tr:nth-child(2)"); // Assuming second row is the sub-header
@ -3652,18 +3745,18 @@
var colIndexTracker = []; // Maps visual column index to actual index
var visualIndex = 0; // Tracks the visual column position considering rowspan/colspan
// Step 1: Find the "Quote asked" column index
// Step 1: Find the "Sum Insured" column index
subHeaderRow.children("th, td").each(function(actualIndex) {
colIndexTracker[visualIndex] = actualIndex;
if ($(this).text().trim() === "Quote asked") {
if ($(this).text().trim() === "Sum Insured" || $(this).text().trim() === "Liability Limit") {
targetColumnIndexes.push(visualIndex);
}
visualIndex += parseInt($(this).attr("colspan") || 1, 10);
});
if (targetColumnIndexes === 0) return; // If "Quote asked" column is not found, exit
if (targetColumnIndexes === 0) return; // If "Sum Insured" column is not found, exit
// Step 2: Make all cells in the found column non-editable, considering rowspan
var rowSpans = {}; // Keeps track of rowspans per column
@ -4238,8 +4331,13 @@
})
function checkTheTableDataChanged(redirect_type) {
async function checkTheTableDataChanged(redirect_type) {
if (!isSaved){
const proceed = await confirmUnsavedChanges();
// if (!proceed) {}
// return;
}
if (redirect_type == 1) {
//BACK BUTTON
@ -4868,4 +4966,229 @@
createIcon(stcButton);
}
}
function monitorTableChanges() {
console.log("monitoring table changes");
var proposalValue = "";
// Get the first table
const table = document.querySelector("table");
if (!table) return;
// Get the first row in the tbody
const firstRow = table.querySelector("tbody tr");
if (!firstRow) return;
// console.log("firstRow : ",firstRow);
// Get all cells in the first row
const cells = firstRow.querySelectorAll("td");
// Get header rows to identify which columns are "Sum Insured"
const headerRow1 = table.querySelector("thead tr:nth-child(1)");
const headerRow2 = table.querySelector("thead tr:nth-child(2)");
if (!headerRow1 || !headerRow2) return;
// console.log("headerRow1 : ",headerRow1);
// console.log("headerRow2 : ",headerRow2);
// Find which column is the "Sum Insured" column
let sumInsuredColumnIndex = -1;
const subHeaders = headerRow2.querySelectorAll("th");
subHeaders.forEach((th, index) => {
if (th.textContent.trim() === "Sum Insured") {
proposalValue = th.getAttribute("data-proposal");
sumInsuredColumnIndex = index;
}
});
// console.log("sumInsuredColumnIndex : ",sumInsuredColumnIndex);
if (sumInsuredColumnIndex === -1) return;
// Check if we have a cell at that index
if (cells.length > sumInsuredColumnIndex) {
console.log("It is there");
const sumInsuredCell = cells[sumInsuredColumnIndex];
let previousValue = "";
// Add event listener for changes
sumInsuredCell.addEventListener("focus", function () {
previousValue = this.textContent.trim();
});
sumInsuredCell.addEventListener("blur", function () {
const newValue = this.textContent.trim();
if (newValue !== previousValue) {
tdChanged = true;
changedNewSI = newValue;
$("#policySI").val(newValue);
console.log("new Value",changedNewSI);
// alert(newValue);
updateAddON(newValue,proposalValue);
console.log("Sum Insured value changed to:", newValue);
}
});
}else{
console.log("Sum Insured column not found");
}
}
function updateAddON(newValue,proposalValue = null) {
console.log("Function called");
var table = document.getElementById("fire_addOnCoverage");
console.log("table : ",table);
if (!table) return;
const thead = table.querySelector("thead");
const tbody = table.querySelector("tbody");
if (!thead || !tbody) return;
const topHeaderCells = thead.rows[0].cells;
const subHeaderCells = thead.rows[1].cells;
let targetIndexes = [];
// Find indexes of columns with the required headers
for (let i = 0; i < topHeaderCells.length; i++) {
const topHeaderText = topHeaderCells[i].textContent.trim();
const subHeaderText = subHeaderCells[i] ? subHeaderCells[i].textContent.trim() : "";
const subheaderProposalValue = subHeaderCells[i]?.getAttribute("data-proposal");
console.log("subheaderProposalValue : ",subheaderProposalValue);
console.log("proposalValue : ",proposalValue);
if (proposalValue != "" && proposalValue != null){
if (subheaderProposalValue !== proposalValue) {
continue;
}
}
if ((topHeaderText.startsWith("Pro") || topHeaderText.startsWith("Exis")) && subHeaderText === "Sum Insured") {
targetIndexes.push(i);
}
}
// Loop through the first 3 rows of tbody and update the matching cells
for (let rowIndex = 0; rowIndex < Math.min(3, tbody.rows.length); rowIndex++) {
const row = tbody.rows[rowIndex];
targetIndexes.forEach(colIndex => {
if (row.cells[colIndex]) {
console.log("Found row to update")
if (['fire_stfi', 'fire_eq'].includes(row.id)) {
row.cells[colIndex].textContent = newValue;
}
if (row.id == "fire_terrorism"){
if (storedPolicyData){
console.log("storedPolicyData : ",storedPolicyData);
var is_terrorism = storedPolicyData.fire.policyDetails.terrorism;
console.log("is terrorism",is_terrorism);
if (is_terrorism == "yes"){
row.cells[colIndex].textContent = `Yes, ${newValue}`;
}else{
row.cells[colIndex].textContent = "No"
}
}else{
row.cells[colIndex].textContent = "No"
}
}
}
});
}
}
function changeTerrorism(newValue){
storedPolicyData = JSON.parse(localStorage.getItem('policyData'));
console.log("Stroredpolicy data : ",storedPolicyData);
console.log("Change terrorism Function Called");
var table = document.getElementById("fire_addOnCoverage");
if (!table) return;
const thead = table.querySelector("thead");
const tbody = table.querySelector("tbody");
if (!thead || !tbody) return;
const topHeaderCells = thead.rows[0].cells;
const subHeaderCells = thead.rows[1].cells;
let targetIndexes = [];
// Find indexes of columns with the required headers
for (let i = 0; i < topHeaderCells.length; i++) {
const topHeaderText = topHeaderCells[i].textContent.trim();
const subHeaderText = subHeaderCells[i] ? subHeaderCells[i].textContent.trim() : "";
if ((topHeaderText.startsWith("Pro") || topHeaderText.startsWith("Exis")) && subHeaderText === "Sum Insured") {
targetIndexes.push(i);
}
}
// Loop through the first 3 rows of tbody and update the matching cells
for (let rowIndex = 0; rowIndex < Math.min(3, tbody.rows.length); rowIndex++) {
const row = tbody.rows[rowIndex];
targetIndexes.forEach(colIndex => {
if (row.cells[colIndex]) {
if (row.id == "fire_terrorism"){
console.log("Found the row");
if (storedPolicyData){
console.log("storedPolicyData : ",storedPolicyData);
var is_terrorism = storedPolicyData.fire.policyDetails.terrorism;
updateAddON(newValue);
if (is_terrorism == "yes"){
row.cells[colIndex].textContent = `Yes, ${newValue}`;
}else{
row.cells[colIndex].textContent = "No"
}
}else{
row.cells[colIndex].textContent = "No"
}
}
}
});
}
}
document.addEventListener('input', function (e) {
if (e.target.matches('td[contenteditable]')) {
isSaved = false;
// alert("status changed");
}
});
async function confirmUnsavedChanges() {
const result = await Swal.fire({
title: 'Unsaved changes',
text: 'Please save your changes before continuing.',
icon: 'warning',
showCancelButton: true,
confirmButtonText: 'Save Now',
cancelButtonText: 'Cancel'
});
if (result.isConfirmed) {
saveRFQ();
return true;
}
return false;
}
</script>