nhance/app/Views/view_rfq.php

3142 lines
113 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<style>
/* Custom CSS */
body {
background-color: #f4f4f4;
color: #333;
/* padding: 20px; */
font-size: small;
}
.table-container {
overflow-x: auto;
/* margin-top: 20px; */
}
.table {
min-width: 100%;
table-layout: auto;
}
.table th,
.table td {
vertical-align: middle;
text-align: center;
text-wrap: pretty;
}
.table th,
.table td {
padding: 4px;
}
.table th[contenteditable],
.table td[contenteditable] {
border: 1px solid #007bff;
outline: none;
}
.table th,
.table td {
min-width: 150px;
}
.table th.sno,
.table td.sno {
width: 10px;
background-color: #bfe0e2;
}
.table th.action,
.table td.action {
width: 200px;
}
.table th.sticky,
.table td.sticky {
position: sticky;
left: 0;
background-color: #bfe0e2;
z-index: 2;
}
.suggestion-box {
border: 1px solid #ddd;
max-height: auto;
overflow-y: auto;
position: absolute;
background: #fff;
z-index: 100;
display: none;
width: auto;
background-color: #ff9999;
min-width: 80px !important;
text-align: center;
}
.suggestion-box ul {
list-style: none;
padding: 3px;
margin: 0;
list-style-type: square;
}
.suggestion-box ul li {
padding: 5px;
cursor: pointer;
}
.suggestion-box ul li:hover {
background-color: black;
color: #fff;
}
.btn-custom {
background-color: #007bff;
color: #fff;
margin-right: 10px;
}
.hidden {
display: none;
}
/* Style for the vertical three-dot menu */
.dropbtn {
background: none;
border: none;
font-size: 18px;
cursor: pointer;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #f1f1f1;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
z-index: 1;
}
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropdown-content a:hover {
background-color: #ddd;
}
/* .dropdown:hover .dropdown-content {
display: block;
}*/
.dialog {
display: none;
position: fixed;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
border: 1px solid #ccc;
background-color: #fff;
padding: 20px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
z-index: 1000;
width: 300px;
}
.dialog-header {
font-size: 18px;
margin-bottom: 10px;
}
.dialog-content {
margin-bottom: 15px;
}
.dialog-footer {
text-align: right;
}
.dialog button {
padding: 5px 10px;
}
.hidden {
display: none;
}
.swal2-html-container{
overflow: hidden !important;
}
.bold {
font-weight: bold;
color:red;
}
.select2-selection__choice {
background-color: #0a8794 !important;
color: white !important;
font-weight: bold;
}
.select2-selection__choice__remove {
color: white !important;
margin-right: 5px;
}
</style>
<div class="row" id="inception_list">
<div class="col-12">
<div class="card">
<div class="card-body">
<div class="row" style="margin-bottom:1rem;">
<div class="col-6" style="align-self: center;">
<h4 style="position: relative;"> <?= isset($page_name) ? $page_name : 'RFQ' ?> </h4>
</div>
<div class="col-2" id="status_change" style="text-align: right; position: relative;top: 56px; left: 386px;">
<a href="<?= base_url("leads/list")?>" class="btn btn-primary">Back</a>
</div>
</div>
<button id="addQuote" class="btn btn-custom">Add New Proposal</button>
<button id="submitData" class="btn btn-primary">Save RFQ</button>
<button id="submitQCRData"class="btn btn-primary">Procced to QCR</button>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<a id="submitExcel"class="btn btn-primary" id>Export Excel</a>
<button id="submitMail"class="btn btn-primary" onclick="showModal()">Send Mail</button>
<input type="hidden" id="lead_id" name="lead_id" value="<?= isset($lead_id) ? $lead_id : '' ?>">
<input type="hidden" id="qcr_count" value="<?= isset($qcr_count) ? $qcr_count : 0 ?>">
<!-- <button id="openDialogBtn">Open Dialog</button> -->
<div class="table-container">
<table id="rfqTable" class="table table-bordered mt-3">
<thead>
<tr>
<th class="sticky">Sno</th>
<th class="hidden">Item Key</th>
<th class="sticky">Particulars</th>
<th contenteditable="false">Proposal 1
<span class="dropdown" onclick="showThreeDottedMenu(event)">
<button class="dropbtn">⋮</button>
<div class="dropdown-content">
<a href="#" class="addInsurer">Add Insurer</a>
<a href="#" class="qcrProposal" style="background-color: rgb(221, 221, 221);">QCR <i class="fa fa-check-square" style="color: green; margin-left: 8px;"></i></a>
<a href="#" class="sendClientProposal" style="background-color: rgb(221, 221, 221);">Send to Client <i class="fa fa-check-square" style="color: green; margin-left: 8px;"></i></a>
<a href="#" class="removeProposal">Remove</a>
</div>
</span>
</th>
<th class="action">Action</th>
</tr>
<tr>
<th class="sticky"> - </th>
<th class="hidden"> - </th>
<th class="sticky"> - </th>
<th colspan="X" style="background-color: inherit;">Quote Asked</th>
<th class="action"> - </th>
</tr>
</thead>
<tbody>
<tr>
<td class="sno">1</td>
<td class="hidden"></td>
<td contenteditable="true" class="particulars sticky"></td>
<td contenteditable="true" class="editablecolumns"></td>
<td class="action">
<input type="checkbox" name="qcr"> QCR
<input type="checkbox" name="client"> Client
<button class="btn btn-danger btn-sm removeRow"></button>
<button id="addRow" onclick="addRow(event)" class="btn btn-primary btn-sm">+</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div><!-- end col -->
</div>
<!-- end table row -->
<div id="second"></div>
<!-- Suggestion Box -->
<div id="suggestionBox" class="suggestion-box">
<div class="text-right" style="padding-right: 10px;">
<i class="fa fa-times remove-icon" aria-hidden="true" style="color: black;text-align: right;"
onclick="hideSuggestionBox()"></i>
</div>
<ul id="suggestionList"></ul>
<!-- <br>
<div class="text-center p-2"> -->
<!-- <button id="addNewItem" class="btn btn-primary btn-sm" style="background-color: black;">Add New Item</button></div> -->
</div>
<!-- familiy floater dialog -->
<div class="dialog" id="familyFloaterDialog">
<div class="dialog-header">Family Members <i class="fa fa-times remove-icon" id="closeDialogBtn" aria-hidden="true"
style="color: black;text-align: right;margin-left: 99px;"></i></div>
<div class="dialog-content">
<label>
<input type="checkbox" id="family_self" checked>
Self
</label><br>
<label>
<input type="checkbox" id="family_spouse">
Spouse
</label><br>
<label for="children">Children:</label>
<select class="form-control" id="family_children">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select><br>
<label for="otherMembers">Other Members:</label>
<select class="form-control" id="family_other_members" onchange="setEldersCount(this)">
<option value="0">Select</option>
<option data-value="1" value="oneparent">Only one parent (Either Father / Mother)</option>
<option data-value="2" value="twoparent">Only two parents (Father+Mother)</option>
<option data-value="1" value="onepil">Only one parent in law (Either MIL / FIL)</option>
<option data-value="2" value="twopil">Only two parents in law (FIL + MIL)</option>
<option data-value="2" value="either_par_pil">Parents or PIL (Any two of Father, Mother, MIl, FIL)</option>
<option data-value="2" value="any_two">Either Parents or PIL (Parents or Parents In Law)</option>
<option data-value="4" value="all">Parents + PIL (Father + Mother + MIL + FIL)</option>
</select><br>
<label for="eldersCount">Elders Count:</label>
<input class="form-control" type="text" id="family_elders_count" readonly>
<input type="text" id="familiy_dialog_row_index" style="display: none;" readonly>
<input type="text" id="familiy_dialog_column_index" style="display: none;" readonly>
</div>
<div class="dialog-footer">
<button class="btn btn-primary btn-sm" id="savefamiliy" onclick="saveFamilyMembersDetails()">save</button>
</div>
</div>
<!-- familiy floater dialog end -->
<!-- Center modal content -->
<div class="modal fade" id="list_model" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="false">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myCenterModalLabel"></h4>
<button type="button" id="close_btn" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body">
<div class="form-group">
<div class="form-row" id="input_for_row">
</div>
</div>
<div class="form-group text-right m-b-0" id="hide_smbt_btn">
<button type="submit" class="btn btn-primary" onclick="constructURL()">Send Mail</button>
</div>
</div>
</div><!-- /.modal-content -->
</div>
</div><!-- /.modal -->
<script>
var suggestionKeys = []; // Local variable to store keys
var suggestions = {};
var RFQ_or_QCR = 0;
$(document).ready(function() {
const path = window.location.pathname; // Get the current URL path
const segments = path.split('/'); // Split the path into segments
const lead_id = segments[segments.length - 2]; // Get the second last segment (15)
const type = segments[segments.length - 1]; // Get the last segment (2)
console.log('Lead ID:', lead_id);
console.log('Type:', type);
RFQ_or_QCR = type;
var type_for_url = 1;
if (type == 2) {
type_for_url = 2
$('#submitData').hide();
$('#submitQCRData').text('Save');
} else {
$('#submitData').show();
$('#submitQCRData').text('Proceed to QCR');
}
let excel_url = '<?= base_url('leads/exportQCRandRFQ/') ?>'+lead_id + '/' + type_for_url + '/' + 'excel'
$('#submitExcel').attr('href', excel_url);
let mail_url = '<?= base_url('leads/exportQCRandRFQ/') ?>'+lead_id + '/' + type_for_url + '/' + 'mail'
$('#submitMail').attr('data-url', mail_url);
console.log('RFQ_or_QCR:', RFQ_or_QCR);
});
$(document).ready(function() {
// Ensure that $rfq_data is properly encoded and check for null/undefined
let data = <?= isset($rfq_data) ? json_encode($rfq_data['json']) : 'null' ?>;
let rfq_count = <?= isset($rfq_count) ? $rfq_count : 0 ?>;
let qcr_count = <?= isset($qcr_count) ? $qcr_count : 0 ?>;
let question_json = <?= isset($question_json) ? json_encode($question_json) : 'null' ?>;
console.log();
data = JSON.parse(data);
suggestions = JSON.parse(question_json);
console.log(data);
console.log(suggestions);
// Check if data is valid (not null or undefined) and is an object
if (data && typeof data === 'object') {
jsonToTable(data);
} else {
addSuggestionsToTable(); // Call the function to populate the table
attachEventListeners();
}
if(rfq_count == 0){
$('#submitQCRData').hide()
$('#submitExcel').hide()
$('#submitMail').hide()
}else{
$('#submitQCRData').show()
$('#submitExcel').show()
$('#submitMail').show()
}
});
</script>
<script>
const openDialogBtn = document.getElementById('openDialogBtn');
const closeDialogBtn = document.getElementById('closeDialogBtn');
// const familyFloaterDialog = document.getElementById('familyFloaterDialog');
// openDialogBtn.onclick = function() {
// familyFloaterDialog.style.display = 'block';
// };
// familyFloaterDialog.onclick = function() {
// myDialog.style.display = 'none';
// };
$('.remove-icon').on('click', function() {
$('#familyFloaterDialog').css('display', 'none');
});
var currentThrdottedMenu = '';
var proposal_colum_count = 1;
var over_all_column_data = {
"Proposal 1": {
"qcr": 1,
"stc": 1,
'insurers': []
}
};
// document.addEventListener("DOMContentLoaded", function () {
const rfqTable = document.getElementById('rfqTable');
const addQuoteButton = document.getElementById('addQuote');
const submitButton = document.getElementById('submitData');
const suggestionBox = document.getElementById('suggestionBox');
const suggestionList = document.getElementById('suggestionList');
function showFamilyFloaterDialogBox(target) {
const familyFloaterDialog = document.getElementById('familyFloaterDialog');
if (familyFloaterDialog.style.display == 'block') {
familyFloaterDialog.style.display = 'none';
}
familyFloaterDialog.style.display = 'block';
console.log('showFamilyFloaterDialogBox');
let currentTD = getCellIndices(target);
console.log(currentTD);
//set current cell row, column in modal as hidden value
$('#familiy_dialog_row_index').val(currentTD.rowIndex);
$('#familiy_dialog_column_index').val(currentTD.columnIndex);
// alert(currentColumnIndex)
let parentId = target.parentElement.id
// alert(parentId);
let hiddenInput = target.querySelector('input[type="hidden"]');
// alert(hiddenInput);
let inputValue = hiddenInput ? hiddenInput.value : null;
// console.log('hidden input value');
console.log(inputValue);
if (inputValue !== null && inputValue !== '') {
//get stored familiy composition json if any in hidden input and display it
inputValue = JSON.parse(inputValue);
console.log('from hidden value');
console.log(inputValue);
setFamilyDialogValues(inputValue);
// return true;
}
// setCellInnerHTMLByCellIndex('rfqTable', currentTD.rowIndex, (currentTD.columnIndex), '<b>TEST</b>');
}
function saveFamilyMembersDetails() {
var rowIndex = $('#familiy_dialog_row_index').val();
var columnIndex = $('#familiy_dialog_column_index').val();
console.log('Incoming Cell Index');
console.log(rowIndex + '-' + columnIndex);
let self = $('#family_self').prop('checked') ? 1 : 0;
let spouse = $('#family_spouse').prop('checked') ? 1 : 0;
var children = $('#family_children').val();
var elders = $('#family_other_members').val();
var elders_count = $('#family_elders_count').val();
console.log('Current Family Modal Values');
console.log('self' + '-' + self);
console.log('spouse' + '-' + spouse);
console.log('children' + '-' + children);
console.log('elders' + '-' + elders);
console.log('elders_count' + '-' + elders_count);
var display_value = createFamilyDisplayString({
'self': self,
'spouse': spouse,
'children': children,
'family_other_members': elders,
'elders_count': elders_count
});
var hidden_value = createFamilyJSONString({
'self': self,
'spouse': spouse,
'children': children,
'family_other_members': elders,
'elders_count': elders_count
});
console.log('display string');
console.log(display_value);
console.log('JSON string');
console.log(hidden_value);
// input.innerText = '';
//hidden text box for store choosed answers object
// const hiddenInputBox = document.createElement('input');
// hiddenInputBox.type = 'hidden';
// hiddenInputBox.value = hidden_value;
let combinedContent = `<input type="hidden" value='${hidden_value}'>` + display_value;
setCellInnerHTMLByCellIndex('rfqTable', rowIndex, columnIndex, combinedContent);
resetFamiliyDialogModalValues();
$('#familyFloaterDialog').hide();
// input.appendChild(hiddenInputBox);
// // alert(input.innerText);
// input.appendChild(document.createTextNode(details.display_value));
// // input.innerHTML += details.display_value;
// // const row = input.closest('tr');
// // row.id = display_value;
// // row.querySelector('.hidden').innerText = display_value;
// hideSuggestionBox();
// handleChildQuestions(input);
}
function resetFamiliyDialogModalValues() {
$('#familiy_dialog_row_index').val('');
$('#familiy_dialog_column_index').val('');
// $('#family_self').val('');
$('#family_self').prop('checked', true); // Checks the checkbox
// $('#family_spouse').val('');
$('#family_spouse').prop('checked', false); // Checks the checkbox
$('#family_children').val(0)
$('#family_other_members').val('0');
$('#family_elders_count').val(0);
}
function createFamilyDisplayString(familyArray) {
let displayString = [];
// Add 'self' if the value is 1 (true)
if (familyArray['self']) {
displayString.push('Self');
}
// Add 'spouse' if the value is 1 (true)
if (familyArray['spouse']) {
displayString.push('Spouse');
}
// Add 'children(count)' if count > 0
if (familyArray['children'] > 0) {
displayString.push(`Children(${familyArray['children']})`);
}
// Handle family_other_members values
let familyOtherMembersMap = {
'oneparent': 'One Parent',
'twoparent': 'Two Parents',
'onepil': 'One Parent-in-law',
'twopil': 'Two Parents-in-law',
'either_par_pil': 'Either Two Parents or Two Parents-in-law',
'any_two': 'Any Two Parents or Parents-in-law',
'all': 'All Four Parents/Parents-in-law'
};
if (familyArray['family_other_members'] && familyOtherMembersMap[familyArray['family_other_members']]) {
displayString.push(familyOtherMembersMap[familyArray['family_other_members']]);
}
// Join the array with ' + ' to create the final display string
return displayString.join(' + ');
}
function createFamilyJSONString(familyArray) {
let result = {
"self": familyArray['self'] || 0,
"spouse": familyArray['spouse'] || 0,
"childrens": familyArray['children'] || 0,
"parents": 0,
"parents-in-law": 0,
"either-parents-pil": 0,
"elders_count": familyArray['elders_count'] || "0"
};
// Process the family_other_members values to set parents and parents-in-law
switch (familyArray['family_other_members']) {
case 'oneparent':
result['parents'] = 1;
result['elders_count'] = 1;
break;
case 'twoparent':
result['parents'] = 2;
result['elders_count'] = 2;
break;
case 'onepil':
result['parents-in-law'] = 1;
result['elders_count'] = 1;
break;
case 'twopil':
result['parents-in-law'] = 2;
result['elders_count'] = 2;
break;
case 'either_par_pil':
result['either-parents-pil'] = 1;
result['elders_count'] = 2;
break;
case 'any_two':
result['either-parents-pil'] = 2;
result['elders_count'] = 2;
break;
case 'all':
result['parents'] = 2;
result['parents-in-law'] = 2;
result['elders_count'] = 4;
break;
}
// Convert the result object to a JSON string
return JSON.stringify(result);
}
function setFamilyDialogValues(familyData) {
// Set Self checkbox
$('#family_self').prop('checked', familyData.self === 1);
// Set Spouse checkbox
$('#family_spouse').prop('checked', familyData.spouse === 1);
// Set Children select
$('#family_children').val(familyData.childrens);
// Determine which value to select for family other members (parents, parents-in-law)
if (familyData.parents === 1) {
$('#family_other_members').val('oneparent');
} else if (familyData.parents === 2) {
$('#family_other_members').val('twoparent');
} else if (familyData["parents-in-law"] === 1) {
$('#family_other_members').val('onepil');
} else if (familyData["parents-in-law"] === 2) {
$('#family_other_members').val('twopil');
} else if (familyData["either-parents-pil"] === 1) {
$('#family_other_members').val('either_par_pil');
} else if (familyData["either-parents-pil"] === 2) {
$('#family_other_members').val('any_two');
} else if (familyData["either-parents-pil"] === 3) {
$('#family_other_members').val('all');
}
// Set Elders Count (readonly input)
$('#family_elders_count').val(familyData.elders_count);
}
function addSuggestionsToTable() {
var tbody = $("#rfqTable tbody");
tbody.empty(); // Clear any existing rows in the tbody
// return;
if(suggestions){
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
const snoCell = newRow.insertCell(0);
snoCell.classList.add('sno');
snoCell.innerText = tbody[0].rows.length;
const hiddenCell = newRow.insertCell(1);
hiddenCell.classList.add('hidden');
hiddenCell.innerText = key;
const particularsCell = newRow.insertCell(2);
particularsCell.setAttribute('contenteditable', 'true');
particularsCell.classList.add('particulars', 'sticky');
particularsCell.innerText = details.display_values;
const columnCount = $("#rfqTable thead tr th").length;
console.log('columnCount' + columnCount);
for (let i = 3; i < columnCount - 6; i++) {
const editableCell = newRow.insertCell(i);
editableCell.setAttribute('contenteditable', 'true');
editableCell.classList.add('editablecolumns');
const inputBox = document.createElement('input');
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);
}
editableCell.appendChild(inputBox);
// Additional handling can be added here for 'answers' or 'type'
}
const actionCell = newRow.insertCell(-1);
actionCell.classList.add('action');
actionCell.innerHTML =
'<input type="checkbox" name="qcr" checked> QCR <input type="checkbox" name="client" checked> Client <button class="btn btn-danger btn-sm removeRow"></button> ';
suggestionKeys.push(key);
}
}
moveAddRowButton();
hideQCR();
}
// Function to move add row button to last row
function moveAddRowButton() {
console.log('table', rfqTable)
const lastRow = rfqTable.rows[rfqTable.rows.length - 1];
const actionCell = lastRow.querySelector('.action');
if (actionCell && !actionCell.querySelector('#addRow')) {
actionCell.innerHTML += ' <button id="addRow" class="btn btn-primary btn-sm">+</button>';
document.getElementById('addRow').addEventListener('click', addRow);
}
// const actionCell = lastRow.cells[lastRow.cells.length - 1];
// actionCell.innerHTML =
// '<input type="checkbox" name="qcr"> QCR <input type="checkbox" name="client"> Client <button class="btn btn-danger btn-sm removeRow"></button> <button id="addRow" class="btn btn-primary btn-sm">+</button>';
// document.getElementById('addRow').addEventListener('click', addRow);
// const lastRow = rows[rows.length - 1];
}
// 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');
console.log(suggestionKeys);
// Remove the key from suggestionKeys
suggestionKeys = suggestionKeys.filter(key => key !== rowKey);
row.remove();
console.log(suggestionKeys);
updateRowNumbers(); // Update row numbers
moveAddRowButton(); // Move the add row button to the last row
realignSpecialConditions();
}
});
// Function to add new columns
addQuoteButton.addEventListener('click', function() {
const headerRow = rfqTable.rows[0];
const secondHeaderRow = rfqTable.rows[1];
// alert('FH - ' + headerRow.cells.length + ' : SH - ' + secondHeaderRow.cells.length);
const newQuoteHeader = document.createElement('th');
const quoteCount = headerRow.cells.length - 4;
proposal_colum_count = proposal_colum_count + 1;
var new_proposal_name = `Proposal ${proposal_colum_count}`;
newQuoteHeader.innerHTML = `${new_proposal_name} <span class="dropdown" onclick="showThreeDottedMenu(event)">
<button class="dropbtn">⋮</button>
<div class="dropdown-content">
<a href="#" class="addInsurer">Add Insurer</a>
<a href="#" class="qcrProposal" style="background-color: rgb(221, 221, 221);">QCR <i class="fa fa-check-square" style="color: green; margin-left: 8px;"></i></a>
<a href="#" class="sendClientProposal" style="background-color: rgb(221, 221, 221);">Send to Client <i class="fa fa-check-square" style="color: green; margin-left: 8px;"></i></a>
<a href="#" class="removeProposal">Remove</a>
</div>
</span>`;
newQuoteHeader.setAttribute('contenteditable', 'false');
headerRow.insertBefore(newQuoteHeader, headerRow.cells[headerRow.cells.length - 1]);
// Generate random light background color
let randomColor = 'hsl(' + Math.random() * 360 + ', 100%, 93%)';
newQuoteHeader.style.backgroundColor = randomColor;
console.log('rows - ' + rfqTable.rows.length);
// Add a new column to each row
for (let i = 1; i < rfqTable.rows.length; i++) {
if (i == 1) {
// Create a new <th> element
const newHeaderCell = document.createElement('th');
newHeaderCell.innerHTML = ` Quote Asked `;
newHeaderCell.style.backgroundColor = randomColor;
// Insert the <th> element at the desired position
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.style.backgroundColor = randomColor;
}
}
attachEventListeners();
//add new proposal in gobal array
var new_proposal_array = {}
over_all_column_data[new_proposal_name] = {
"qcr": 1,
"stc": 1,
'insurers': []
};
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;
// const filteredSuggestions = Object.entries(suggestions);.filter(([key, details]) =>
// details.display_values.toLowerCase().includes(value)
// );
filteredSuggestions = Object.entries(suggestions);
filteredSuggestions.forEach(([key, details]) => {
const li = document.createElement('li');
li.innerText = details.display_values;
li.dataset.key = key;
suggestionList.appendChild(li);
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
}
input.innerText = details.display_values;
const row = input.closest('tr');
row.id = key;
row.querySelector('.hidden').innerText = key;
suggestionKeys.push(key);
hideSuggestionBox();
realignSpecialConditions();
// Optionally handle 'answers' and 'type' here
// e.g., populate other cells based on details.answers and details.type
});
});
if (filteredSuggestions.length > 0) {
suggestionBox.style.display = 'block';
const rect = input.getBoundingClientRect();
const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
const scrollLeft = window.pageXOffset || document.documentElement.scrollLeft;
suggestionBox.style.top = (rect.bottom + scrollTop) + 'px';
suggestionBox.style.left = (rect.left + scrollLeft) + 'px';
} else {
hideSuggestionBox();
}
}
// Function to handle answers suggestion box
function showAnswersSuggestions(input) {
console.log(input.parentElement.id);
//return;
var questionItem = input.parentElement.id;
if(questionItem == 'family_composition')
{
showFamilyFloaterDialogBox(input);
return;
}
if(questionItem.startsWith('special_condition'))
{
return;
}
var questionAnswers = suggestions[questionItem]['answers'];
var questionType = suggestions[questionItem]['type'];
// console.log(questionItem);
// console.log(questionAnswers);
// console.log(questionType);
if(questionType == 'text')
{
return;
}
suggestionList.innerHTML = '';
// const value = input.innerText.trim().toLowerCase();
// alert(value);
// const filteredSuggestions = questionAnswers.filter((details) => {
// // console.log(key);
// // console.log(details.display_value);
// return details.display_value.toLowerCase().includes(value)
// });
// console.log(filteredSuggestions);
// if (filteredSuggestions.length === 0) {
const filteredSuggestions = questionAnswers;
// }
//return;
filteredSuggestions.forEach((details) => {
console.log('building each answers');
const li = document.createElement('li');
li.innerText = details.display_value;
li.dataset.key = details.display_value;
suggestionList.appendChild(li);
li.addEventListener('click', function () {
input.innerText = '';
//hidden text box for store choosed answers object
const hiddenInputBox = document.createElement('input');
hiddenInputBox.type = 'hidden';
hiddenInputBox.value = JSON.stringify(details);
input.appendChild(hiddenInputBox);
// alert(input.innerText);
input.appendChild(document.createTextNode(details.display_value));
// input.innerHTML += details.display_value;
// const row = input.closest('tr');
// row.id = display_value;
// row.querySelector('.hidden').innerText = display_value;
hideSuggestionBox();
handleChildQuestions(input);
checkCellValueAndHighlight();
// Optionally handle 'answers' and 'type' here
// e.g., populate other cells based on details.answers and details.type
});
});
if (filteredSuggestions.length > 0) {
console.log('display suggestion box');
console.log(input.getBoundingClientRect().bottom+'-'+input.getBoundingClientRect().left);
suggestionBox.style.display = 'block';
const rect = input.getBoundingClientRect();
const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
const scrollLeft = window.pageXOffset || document.documentElement.scrollLeft;
suggestionBox.style.top = (rect.bottom + scrollTop) + 'px';
suggestionBox.style.left = (rect.left + scrollLeft) + 'px';
// suggestionBox.style.top = '500px';
// suggestionBox.style.left = '900px';
} else {
console.log('hide suggestion box');
hideSuggestionBox();
}
}
document.addEventListener('input', function(e) {
if (e.target.classList.contains('particulars')) {
console.log(' show suggestions eventlistener ')
showSuggestions(e.target);
}
if (e.target.classList.contains('editablecolumns')) {
showAnswersSuggestions(e.target);
checkCellValueAndHighlight();
}
});
document.getElementById('rfqTable').addEventListener('focusout', function(e) {
// Ensure the event target is a td element
if (e.target && e.target.tagName === 'TD' && e.target.classList.contains('editablecolumns')) {
validateCellContent(e.target);
}
if (e.target && e.target.tagName === 'TD' && e.target.classList.contains('particulars')) {
validateQuestionCellContent(e.target);
}
});
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);
}
if (e.target.classList.contains('editablecolumns')) {
// console.log(e.target.innerText);
// if(e.target.innerText == '')
// {
showAnswersSuggestions(e.target);
// }
}
//hide currently showing any three dotted menu
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 = '';
}
else {
currentThrdottedMenu.style.display = 'block'; // Show if it's hidden
}
}
});
function hideSuggestionBox() {
suggestionBox.style.display = 'none';
}
function addRow(e) {
let columnCount = rfqTable.rows[1].cells.length;
const newRow = rfqTable.insertRow();
const snoCell = newRow.insertCell(0);
snoCell.classList.add('sno');
snoCell.innerText = rfqTable.rows.length - 1;
const hiddenCell = newRow.insertCell(1);
hiddenCell.classList.add('hidden'); // Hidden column for item key
const particularsCell = newRow.insertCell(2);
particularsCell.setAttribute('contenteditable', 'true');
particularsCell.classList.add('particulars', 'sticky');
for (let i = 3; i < columnCount - 1; i++) {
const editableCell = newRow.insertCell(i);
editableCell.setAttribute('contenteditable', 'true');
editableCell.classList.add('editablecolumns');
}
const actionCell = newRow.insertCell();
actionCell.classList.add('action');
actionCell.innerHTML =
'<input type="checkbox" name="qcr" checked> QCR <input type="checkbox" name="client" checked> Client <button class="btn btn-danger btn-sm removeRow"></button> <button class="btn btn-primary btn-sm" onclick="addRow(event)">+</button>';
e.target.remove();
updateRowNumbers();
realignSpecialConditions();
}
// Function to update row numbers
function updateRowNumbers() {
const rows = rfqTable.tBodies[0].rows;
for (let i = 0; i < rows.length; i++) {
rows[i].cells[0].innerText = i + 1;
}
}
function realignSpecialConditions() {
// Get the table by ID
const table = document.getElementById('rfqTable');
if (!table) return;
// Initialize a counter for special conditions
let specialConditionCount = 1;
// Loop through each row in the table
const rows = table.getElementsByTagName('tr');
for (let i = 0; i < rows.length; i++) {
const row = rows[i];
const rowId = row.id; // Get the row ID
// Check if the row ID starts with "special_condition"
if (rowId.startsWith('special_condition')) {
// Update the row ID to special_condition_1, special_condition_2, etc.
const newId = `special_condition_${specialConditionCount}`;
row.id = newId;
// Update the inner text of the hidden cell (index 1)
const hiddenCell = row.getElementsByTagName('td')[1];
hiddenCell.innerText = newId;
// Update the inner text of the visible cell (index 0)
const visibleCell = row.getElementsByTagName('td')[2];
visibleCell.innerText = `Special condition ${specialConditionCount}`;
// Increment the special condition counter
specialConditionCount++;
}
}
}
function attachEventListeners() {
// Detach existing listeners before attaching new ones
detachDynamicEventListeners();
// Attach listeners to all elements with the class 'addInsurer'
document.querySelectorAll('.addInsurer').forEach(function(element) {
element.addEventListener('click', addInsurer);
});
document.querySelectorAll('.removeProposal').forEach(function(element) {
element.addEventListener('click', removeProposal);
});
document.querySelectorAll('.removeInsurer').forEach(function(element) {
element.addEventListener('click', removeInsurer);
});
document.querySelectorAll('.changeInsurer').forEach(function(element) {
element.addEventListener('click', changeInsurer);
});
document.querySelectorAll('.qcrProposal').forEach(function(element) {
element.addEventListener('click', changeState);
});
document.querySelectorAll('.sendClientProposal').forEach(function(element) {
element.addEventListener('click', changeState);
});
document.querySelectorAll('.qcrInsurer').forEach(function(element) {
element.addEventListener('click', changeState);
});
document.querySelectorAll('.sendClientInsurer').forEach(function(element) {
element.addEventListener('click', changeState);
});
document.querySelectorAll('.copyInsurerNext').forEach(function(element) {
element.addEventListener('click', dupInsurer);
});
document.querySelectorAll('.copyInsurerLast').forEach(function(element) {
element.addEventListener('click', dupInsurer);
});
// document.querySelectorAll('.editablecolumns').forEach(function(element) {
// element.addEventListener('input', showAnswersSuggestions(element));
// });
}
function detachDynamicEventListeners() {
document.querySelectorAll('.addInsurer').forEach(function(element) {
element.removeEventListener('click', addInsurer);
});
document.querySelectorAll('.changeInsurer').forEach(function(element) {
element.removeEventListener('click', changeInsurer);
});
document.querySelectorAll('.qcrProposal').forEach(function(element) {
element.removeEventListener('click', changeState);
});
document.querySelectorAll('.sendClientProposal').forEach(function(element) {
element.removeEventListener('click', changeState);
});
document.querySelectorAll('.qcrInsurer').forEach(function(element) {
element.removeEventListener('click', changeState);
});
document.querySelectorAll('.sendClientInsurer').forEach(function(element) {
element.removeEventListener('click', changeState);
});
document.querySelectorAll('.copyInsurerNext').forEach(function(element) {
element.removeEventListener('click', dupInsurer);
});
document.querySelectorAll('.copyInsurerLast').forEach(function(element) {
element.removeEventListener('click', dupInsurer);
});
// document.querySelectorAll('.editablecolumns').forEach(function(element) {
// element.removeEventListener('input', showAnswersSuggestions);
// });
}
function addInsurer(event) {
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) {
const closestTh = event.target.closest('th');
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;
}
let rfqTable = document.getElementById('rfqTable');
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 <= colIndex; i++) {
const colspan = parseInt(thElements[i].getAttribute('colspan')) || 1;
totalColspan += colspan;
}
// alert(colIndex+' - '+totalColspan);
// add colspan of current th
let parentTh = rfqTable.querySelector('thead tr th:nth-child(' + (colIndex + 1) + ')');
let columnIndextoCopyData = totalColspan - parentTh.colSpan;
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 <th> element
const newHeaderCell = document.createElement('th');
newHeaderCell.innerHTML = ` ${insurerName} <span class="dropdown" onclick="showThreeDottedMenu(event)">
<button class="dropbtn">⋮</button>
<div class="dropdown-content">
<a href="#" class="changeInsurer">Change Insurer</a>
<a href="#" class="qcrInsurer" style="background-color: rgb(221, 221, 221);">QCR <i class="fa fa-check-square" style="color: green; margin-left: 8px;"></i></a>
<a href="#" class="sendClientInsurer" style="background-color: rgb(221, 221, 221);">Send to Client <i class="fa fa-check-square" style="color: green; margin-left: 8px;"></i></a>
<a href="#" class="removeInsurer">Remove</a>
<!-- <a href="#" class="copyInsurerNext">Copy to next</a> -->
<a href="#" class="copyInsurerLast">Copy</a>
</div>
</span>`;
newHeaderCell.style.backgroundColor = parentTh.style.backgroundColor;;
// Insert the <th> 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;;
}
}
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 (currentThrdottedMenu != '') {
currentThrdottedMenu.style.display = 'none'; // Show if it's hidden
}
});
return;
}
function dupInsurer(event) {
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');
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;
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();
// 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 <th> element
const newHeaderCell = document.createElement('th');
newHeaderCell.innerHTML = ` ${insurerName} <span class="dropdown" onclick="showThreeDottedMenu(event)">
<button class="dropbtn">⋮</button>
<div class="dropdown-content">
<a href="#" class="changeInsurer">Change Insurer</a>
<a href="#" class="qcrInsurer" style="background-color: rgb(221, 221, 221);">QCR <i class="fa fa-check-square" style="color: green; margin-left: 8px;"></i></a>
<a href="#" class="sendClientInsurer" style="background-color: rgb(221, 221, 221);">Send to Client <i class="fa fa-check-square" style="color: green; margin-left: 8px;"></i></a>
<a href="#" class="removeInsurer">Remove</a>
<!-- <a href="#" class="copyInsurerNext">Copy to next</a> -->
<a href="#" class="copyInsurerLast">Copy</a>
</div>
</span>`;
newHeaderCell.style.backgroundColor = parentTh.style.backgroundColor;;
// Insert the <th> 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
});
}
if (currentThrdottedMenu != '') {
currentThrdottedMenu.style.display = 'none'; // Show if it's hidden
}
return;
}
function removeProposal(event) {
const closestTh = event.target.closest('th');
let colIndex = closestTh.cellIndex;
let rfqTable = document.getElementById('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();
const parentColspan = parseInt(parentTh.getAttribute('colspan')) || 1;
const startIndex = Array.from(headerRows[1].children).findIndex(th => th.offsetLeft >= parentTh.offsetLeft);
// Remove the parent TH
headerRows[0].removeChild(parentTh);
// Remove the relevant sub THs and corresponding TDs
for (let i = startIndex; i < startIndex + parentColspan; i++) {
// Remove the sub THs
headerRows[1].removeChild(headerRows[1].children[startIndex]);
// Remove the corresponding TDs from each row
document.querySelectorAll('tbody tr').forEach(row => {
row.removeChild(row.children[startIndex]);
});
}
//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.`);
} else {
console.log(`${proposal_name} does not exist.`);
}
}
}
function removeInsurer(event) {
if (confirm("Are you sure you want to remove this column?")) {
// function removeSubColumnByIndex(tableId, subThIndex) {
const table = document.getElementById('rfqTable');
const headerRows = table.querySelectorAll('thead tr');
const closestTh = event.target.closest('th');
let insurerName = closestTh.innerText.split('⋮')[0]
// alert(insurerName);return;
let subThIndex = closestTh.cellIndex;
// 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);
// 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]);
});
//remove the insurer from gobal array
let proposal_name = parentTh.innerText.split('⋮')[0];
popInsurerInArray(proposal_name, insurerName);
}
}
function showThreeDottedMenu(event) {
// Prevent the default behavior (optional, depending on your needs)
event.preventDefault();
if (currentThrdottedMenu != '') {
currentThrdottedMenu.style.display = 'none'; // Show if it's hidden
}
// Get the dropdown content element
const dropdownContent = event.currentTarget.querySelector('.dropdown-content');
currentThrdottedMenu = dropdownContent;
// Toggle the showThreeDottedMenu happening in the doc on click event listener
//here only set current dropdown menu DOM object to common variable currentThrdottedMenu
}
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);
if (over_all_column_data[proposal_name]) {
let tempInsurerList = over_all_column_data[proposal_name].insurers;
console.log(tempInsurerList);
if (!tempInsurerList.length) {
return true;
}
let result = tempInsurerList.some(item => item.display_name === insurer_name);
console.log(!result);
return !result;
}
return false;
}
function pushInsurerInArray(proposal_name, insurer_arr) {
console.log('pushInsurerInArray function called');
proposal_name = proposal_name.trim();
if (over_all_column_data[proposal_name]) {
over_all_column_data[proposal_name].insurers.push(insurer_arr);
console.log('new insurer added in golbal variable');
console.log(over_all_column_data[proposal_name].insurers);
return;
}
console.log('new insurer not added in golbal variable');
}
function popInsurerInArray(proposal_name, insurerName) {
proposal_name = proposal_name.trim();
insurerName = insurerName.trim();
console.log('Removing....' + proposal_name + ' - ' + insurerName)
if (over_all_column_data[proposal_name]) {
let tempInsurerList = over_all_column_data[proposal_name].insurers;
// console.log(tempInsurerList);
// if(!tempInsurerList.length) { return true; }
tempInsurerList = tempInsurerList.filter(item => item.display_name !== insurerName);
console.log(tempInsurerList);
over_all_column_data[proposal_name].insurers = tempInsurerList;
console.log('insurer removed in golbal variable');
console.log(over_all_column_data[proposal_name].insurers);
// over_all_column_data[proposal_name].insurers = tempInsurerList
return;
}
console.log('insurer not removed in golbal variable');
}
function changeInsurer(event) {
// let newInsurerName = prompt("Enter New insurer name:");
const insurers = <?= json_encode($insurer); ?>;
selectInsurer(insurers).then(result => {
let newInsurerName = result.selectedInsurer
let newversion = result.insurerDetails;
let dataId = result.dataId;
if (newversion.trim() !== '') {
newInsurerName = `${newInsurerName}-${newversion.trim()}`.replace(/\s+/g, '');
}
console.log('newInsurerName', newInsurerName)
console.log('newversion', newversion)
if (newInsurerName) {
const closestTh = event.target.closest('th');
let oldInsurerName = closestTh.innerText.split('⋮')[0].trim();
let subThIndex = closestTh.cellIndex;
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);
}
});
//find parent th index then it's text content
// Get the sub TH from the second header row
const table = document.getElementById('rfqTable');
const headerRows = table.querySelectorAll('thead tr');
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;
}
}
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);
// if(!tempInsurerList.length) { return true; }
//replace the old insurer with the new insuren in global array
over_all_column_data[proposal_name].insurers.forEach(item => {
if (item.display_name === oldInsurerName) {
item.display_name = newInsurerName; // Replace with new name
item.ins_name = newInsurerName.split('-')[0].trim(); // Replace with new name
item.id = dataId
}
});
// console.log(tempInsurerList);
// over_all_column_data[proposal_name].insurers = tempInsurerList;
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
return;
}
console.log('insurer name not replaced in golbal variable');
}
});
}
function changeState(event) {
let type = event.target.className;
console.log('1 : ', type);
// if (type.includes('sendClientProposal') && type.includes('fa fa-check-square')) {
// type = 'sendClientProposal';
// } 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();
// let subThIndex = closestTh.cellIndex;
if (over_all_column_data[proposal_name]) {
if (type === 'qcrProposal') {
console.log('Proposal qcrProposal');
over_all_column_data[proposal_name].qcr = !over_all_column_data[proposal_name].qcr;
this.style.backgroundColor = over_all_column_data[proposal_name].qcr ? '#ddd' : '#f1f1f1';
// Check if an icon already exists
let icon = this.querySelector('.fa-check-square');
if (over_all_column_data[proposal_name].qcr) {
// If qcr is true and no icon exists, create and append it
if (!icon) {
icon = document.createElement('i');
icon.classList.add('fa', 'fa-check-square');
icon.style.color = 'green';
icon.style.marginLeft = '8px';
this.appendChild(icon);
}
} else {
if (icon) {
this.removeChild(icon);
}
}
} else {
console.log('Proposal sendClientProposal');
over_all_column_data[proposal_name].stc = !over_all_column_data[proposal_name].stc;
this.style.backgroundColor = !over_all_column_data[proposal_name].stc ? '#f1f1f1' : "#ddd";
// Check if an icon already exists
let icon = this.querySelector('.fa-check-square');
if (over_all_column_data[proposal_name].stc) {
// If qcr is true and no icon exists, create and append it
if (!icon) {
icon = document.createElement('i');
icon.classList.add('fa', 'fa-check-square');
icon.style.color = 'green';
icon.style.marginLeft = '8px';
this.appendChild(icon);
}
} else {
if (icon) {
this.removeChild(icon);
}
}
}
}
} else {
console.log('insurer');
const closestTh = event.target.closest('th');
let insurerName = closestTh.innerText.split('⋮')[0].trim();
let subThIndex = closestTh.cellIndex;
//find parent th index then it's text content
// Get the sub TH from the second header row
const table = document.getElementById('rfqTable');
const headerRows = table.querySelectorAll('thead tr');
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;
}
}
let proposal_name = parentTh.innerText.split('⋮')[0].trim();
if (over_all_column_data[proposal_name]) {
over_all_column_data[proposal_name].insurers.forEach(item => {
if (item.display_name === insurerName) {
if (over_all_column_data[proposal_name]) {
let icon = this.querySelector('.fa-check-square'); // Check if an icon already exists
if (type === 'qcrInsurer') {
item.qcr = !item.qcr;
this.style.backgroundColor = item.qcr ? '#ddd' : '#f1f1f1';
if (item.qcr) {
// If qcr is true and no icon exists, create and append it
if (!icon) {
icon = document.createElement('i');
icon.classList.add('fa', 'fa-check-square');
icon.style.color = 'green';
icon.style.marginLeft = '8px';
this.appendChild(icon);
}
} else {
// If qcr is false and the icon exists, remove it
if (icon) {
this.removeChild(icon);
}
}
} else { // Assuming this block is for 'stc'
item.stc = !item.stc;
this.style.backgroundColor = item.stc ? '#ddd' : '#f1f1f1';
if (item.stc) {
// If stc is true and no icon exists, create and append it
if (!icon) {
icon = document.createElement('i');
icon.classList.add('fa', 'fa-check-square');
icon.style.color = 'green';
icon.style.marginLeft = '8px';
this.appendChild(icon);
}
} else {
// If stc is false and the icon exists, remove it
if (icon) {
this.removeChild(icon);
}
}
}
}
}
});
// console.log(tempInsurerList);
// over_all_column_data[proposal_name].insurers = tempInsurerList;
// 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
return;
}
console.log('insurer name not replaced in golbal variable');
}
}
function isEventObject(variable) {
return variable instanceof Event && variable.target !== undefined;
}
function getThPosition(event) {
var th = null;
if (isEventObject(event)) {
th = event.target;
} else {
th = event;
}
// const th = event.target;
// Get the parent row (tr) and all its sibling rows
const rowIndex = th.parentElement.parentElement.parentElement.parentElement.rowIndex;
const colIndex = th.parentElement.parentElement.parentElement.cellIndex;
return {
rowIndex,
colIndex
};
}
function handleChildQuestions(target) {
// Extract the parent id from the event (assuming parent id is stored in event.target's data attribute)
let parentId = target.parentElement.id
// alert(parentId);
let hiddenInput = target.querySelector('input[type="hidden"]');
// alert(hiddenInput);
let inputValue = hiddenInput ? hiddenInput.value : null;
if (inputValue === null) {
return true;
} else {
inputValue = JSON.parse(inputValue);
}
// Check if the parent id exists in the suggestions object
if (suggestions.hasOwnProperty(parentId)) {
let parentItem = suggestions[parentId];
// Check if child_questions exists and has items
if (parentItem.child_questions && parentItem.child_questions.length > 0) {
// Get the current column index from the event (assuming the target is within a table cell)
let currentColumnIndex = target.cellIndex;
// alert('currentColumnIndex :' + currentColumnIndex);
// Iterate over the child questions
parentItem.child_questions.forEach(child => {
// Find the row in the table with the child key (e.g., 'twin_delivery')
console.log('processing for ' + child.question);
let disable_at = child.disable_at;
// if(inputValue.key == disable_at.key)
// {
let childRow = document.querySelector(`tr[id='${child.question}']`);
console.log(childRow);
if (childRow) {
console.log('found row');
// Get the corresponding column in the same index as the current column
let childCell = childRow.cells[currentColumnIndex];
if (childCell) {
console.log('found cell');
if (inputValue.key == disable_at.key) {
childCell.innerHTML = '';
childCell.innerText = '';
//hidden text box for store choosed answers object
const hiddenInputBox = document.createElement('input');
hiddenInputBox.type = 'hidden';
hiddenInputBox.value = JSON.stringify(child.default_answer);
childCell.appendChild(hiddenInputBox);
// alert(input.innerText);
childCell.appendChild(document.createTextNode(child.default_answer.display_value));
// Set the default answer in the child cell
// childCell.innerHTML = child.default_answer.display_value;
console.log('setting default value');
console.log(child.default_answer.display_value)
childCell.contentEditable = false;
} else {
childCell.contentEditable = true;
}
}
}
// }
});
}
}
}
function getCellIndices(target) {
// Get the clicked <td> element
let td = target;
// Get the column index of the clicked <td>
let columnIndex = td.cellIndex;
// Get the parent <tr> (row) of the clicked <td>
let tr = td.parentElement;
// Get the row index of the parent <tr> relative to the table
let rowIndex = tr.rowIndex;
// console.log("Row Index: ", rowIndex);
// console.log("Column Index: ", columnIndex);
return {
rowIndex,
columnIndex
};
}
function setCellInnerHTMLByCellIndex(tableId, rowIndex, colIndex, htmlContent) {
console.log(tableId + '-' + rowIndex + '-' + colIndex);
console.log(htmlContent);
// Get the table by its ID
let table = document.getElementById(tableId);
// Check if the table exists
if (table) {
// Get the row at the specified rowIndex
let row = table.rows[rowIndex];
// Check if the row exists
if (row) {
// Get the cell at the specified colIndex within the row
let cell = row.cells[colIndex];
// Check if the cell exists
if (cell) {
// Set the innerHTML of the cell
cell.innerHTML = htmlContent;
console.log(`Updated cell at row ${rowIndex}, column ${colIndex} with content: ${htmlContent}`);
} else {
console.error(`Column index ${colIndex} does not exist in row ${rowIndex}`);
}
} else {
console.error(`Row index ${rowIndex} does not exist in the table`);
}
} else {
console.error(`Table with ID ${tableId} not found`);
}
}
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
rows.forEach(row => {
const cells = row.querySelectorAll('td');
compareRange(cells, compareIndices);
});
startCol += colspan; // Move to the next set of columns
});
}
function compareRange(cells, indices) {
const baseValue = cells[indices[0]].textContent; // Get the base value for comparison
indices.forEach(index => {
if (cells[index].textContent !== baseValue) {
cells[index].classList.add('bold'); // Highlight mismatched cells
}
else
{
cells[index].classList.remove('bold');
}
});
}
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;
// Get the row ID
const row = cell.closest('tr');
const rowId = row.getAttribute('id');
console.log(rowId);
const item = suggestions.hasOwnProperty(rowId) ? suggestions[rowId] : false;
console.log(item);//return;
if(item && item.type != 'text')
{
// Get the text content the user entered in the cell
const enteredValue = cell.textContent.trim();
console.log('enteredValue - ' + enteredValue);
const preDefinedAnswers = item.answers;
console.log(preDefinedAnswers);
const correctAnswer = preDefinedAnswers.some(obj => obj['display_value'] === enteredValue);
// Compare hidden value and entered value
if (!correctAnswer) {
// If they are not the same, reset the cell's text content to the hidden value
cell.textContent = JSON.parse(hiddenValue).display_value;
cell.appendChild(hiddenInput);
// Re-append the hidden input to the cell after setting textContent
// cell.appendChild(hiddenInput);
}
}
}
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)
{
cell.textContent = expected_val;
}
}
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 = `
<div class="form-row">
<div class="form-group col-md-8">
<select id="insurerSelect">
<option></option> <!-- Placeholder for Select2 -->
${insurers.map(insurer => `<option data-id="${insurer.id}-${insurer.insurer_id}" value="${insurer.insurer_name}-${insurer.branch_code}">${insurer.insurer_name}-${insurer.branch_code}</option>`).join('')}
</select>
</div>
<div class="form-group col-md-4">
<input type="text" class="form-control" id="insurerDetails" placeholder="Enter Version">
</div>
</div>
`;
// 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 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 :)");
}
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 null; // If canceled, return null
}
function setEldersCount(input){
var selectedOption = $(input).find('option:selected');
var elders_count = selectedOption.data('value')
if(elders_count){
$('#family_elders_count').val(elders_count)
}else{
$('#family_elders_count').val('')
}
}
function hideQCR(){
console.log('hideQCR() function called')
console.log(RFQ_or_QCR)
if(RFQ_or_QCR == 2){
$('.qcrProposal').hide();
$('.qcrInsurer').hide();
$('input[name="qcr"]').hide();
}else{
$('.qcrProposal').show();
$('.qcrInsurer').show();
$('input[name="qcr"]').show();
}
}
function showModal(){
var url = '';
var lead_id = $('#lead_id').val();
if(RFQ_or_QCR == 2){
$('#myCenterModalLabel').text('Client contact to send mail')
url = '<?= base_url('leads/list/') ?>' + lead_id;
}else{
$('#myCenterModalLabel').text('Choose insurer to send mail')
url = '<?= base_url('util/getLevelContects') ?>'
}
ajaxRequestForGetMailData(url);
var myModal = new bootstrap.Modal(document.getElementById('list_model'));
myModal.show();
}
function ajaxRequestForGetMailData(url){
$.ajax({
url: url,
type: "GET",
dataType: 'json',
success: function (res) {
appendInput(res.data)
},
error: function (xhr, status, error) {
console.error(xhr.responseText);
console.error(status, error);
}
});
}
function appendInput(data) {
console.log(data);
var lead_id = $('#lead_id').val();
$('#input_for_row').empty();
let html = '';
if (RFQ_or_QCR == 2) {
const url = '<?= base_url('leads/list') ?>?lead_id=' +lead_id;
html = `
<div class="form-group col-md-12">
<label for="contact_mail">Client Contact Mail</label>
<input value="${data.contact_person_email || ''}" type="text" id="contact_mail" class="form-control" placeholder="Contact Mail" readonly>
</div>
`;
if (!data.contact_person_email) {
html += `
<div class="form-group col-md-12">
<a href="${url}">Click here to update mail ID</a>
</div>
`;
}
} else {
// Assuming `data.contacts` is an array of contact objects within the main data object
const contacts = data || {};
html = `
<div class="form-group col-md-12">
<label for="insurerContact">Insurers</label>
<select id="insurerContact" class="form-control" name="insurerContact[]" multiple>
<option></option>
`;
// Loop through each contact property within the `contacts` object
for (const id in contacts) {
const contact = contacts[id];
html += `
<option value="${contact.id}">${contact.insurer_name} - ${contact.branch_code} - ${contact.contect_person_name} - ${contact.contect_person_email}</option>
`;
}
html += `
</select>
</div>
`;
}
$('#input_for_row').append(html);
// Initialize select2 for the dropdown if insurerContact is present
if ($('#insurerContact').length) {
$('#insurerContact').select2({
placeholder: 'Select an insurer',
});
$("textarea.select2-search__field").attr('rows', '1');
$("textarea.select2-search__field").css('resize', 'none');
}
}
function constructURL() {
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=';
} else {
var insurerContact = $('#insurerContact').val();
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);
}
console.log(apiURL);
ajaxRequest(apiURL);
}
function ajaxRequest(url){
console.log(url);
$('.loader').fadeIn();
$('.loader-mask').fadeIn();
$.ajax({
url: url,
type: "GET",
dataType: 'json',
success: function (res) {
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
console.log(res);
if(res.status == 'success' && res.code == 200){
toastr.success('Mail send Successfully', 'SUCCESS')
}else{
if(res.messgae){
toastr.error(res.messgae, 'ERROR')
}else{
toastr.error('Mail send failed', 'ERROR')
}
}
$('.close').click()
},
error: function (xhr, status, error) {
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
console.error(xhr.responseText);
console.error(status, error);
}
});
}
//--------------------------------------------------------------------------------------------------------------------------------------------
// not in use do not remove this function
function tableToJson() {
const headers = [];
const data = [];
const table = document.getElementById('rfqTable');
console.log('over_all_column_data', over_all_column_data)
// Get the parent headers and subheaders
const parentHeaders = table.querySelectorAll('thead tr:nth-child(1) th');
const subHeaders = table.querySelectorAll('thead tr:nth-child(2) th');
let headerIndex = 0;
parentHeaders.forEach((header, index) => {
const colspan = header.getAttribute('colspan') || 1;
const subHeaderArray = [];
for (let i = 0; i < colspan; i++) {
subHeaderArray.push(subHeaders[headerIndex].innerText.replace('⋮', '').trim());
headerIndex++;
}
headers.push({
// parentHeader: header.innerText,
parentHeader: header.innerText.replace('⋮', '').trim(),
subHeaders: subHeaderArray
});
});
console.log('tableToJson headers', headers);
// Get the data from the table body
const rows = table.querySelectorAll('tbody tr');
console.log('rows', rows);
rows.forEach(row => {
const rowId = row.id;
console.log('rowId : ', rowId);
console.log(suggestions)
console.log(suggestions[rowId]['type'])
let inputType = suggestions[rowId]['type']
const cells = row.querySelectorAll('td');
console.log('Table row cells', cells);
const rowData = {
SNO: cells[0].innerText,
items: cells[1].innerText,
data: []
};
console.log('Table row rowData', rowData);
let dataIndex = 0;
headers.forEach(header => {
header.subHeaders.forEach(subHeader => {
const cell = cells[dataIndex];
console.log(cell)
let content = cells[dataIndex].innerText;
if (inputType == "text") {
if (header.parentHeader == 'Action') {
if (!cell) {
console.error(`Cell not found for dataIndex: ${dataIndex}`);
return;
}
const qcrInput = cell.querySelector('input[name="qcr"]');
const clientInput = cell.querySelector('input[name="client"]');
// console.log('qcrInput', qcrInput)
// console.log('clientInput', clientInput)
// console.log('qcrInput', qcrInput.checked)
// console.log('clientInput', clientInput.checked)
if (qcrInput != null && clientInput != null) {
content = {
qcr: qcrInput.checked ? 1 : 0, // Checkbox handling
stc: clientInput.checked ? 1 : 0
};
}
} else {
const input = cell.querySelector('input');
console.log('input cell', input)
if (input) {
content = input.value;
// console.log('hidden input value', content);
} else {
content = cells[dataIndex].innerText;
}
}
} else {
if (!cell) {
console.error(`Cell not found for dataIndex: ${dataIndex}`);
return;
}
let value = '';
const input = cell.querySelector('input');
console.log('input cell', input)
if (input) {
if (header.parentHeader == 'Action') {
const qcrInput = cell.querySelector('input[name="qcr"]');
const clientInput = cell.querySelector('input[name="client"]');
console.log('qcrInput', qcrInput)
console.log('clientInput', clientInput)
if (qcrInput != null && clientInput != null) {
value = {
qcr: qcrInput.checked ? 1 : 0, // Checkbox handling
stc: clientInput.checked ? 1 : 0
};
}
} else {
value = input.value;
}
} else {
value = cell.innerText;
}
content = value;
}
rowData.data.push({
parentth: header.parentHeader,
subth: subHeader,
value: cells[dataIndex].innerText,
input_value: content
});
dataIndex++;
});
});
data.push(rowData);
});
const d = JSON.stringify({
table_data: {
headers: headers,
data: data
},
proposal_data: {
over_all_column_data: over_all_column_data
}
});
localStorage.setItem('data', d);
console.log({
headers,
data
});
jsonToTable(JSON.parse(d));
}
function jsonToTable(json) {
const table = document.getElementById('rfqTable');
const thead = table.querySelector('thead');
const tbody = table.querySelector('tbody');
// Clear existing rows to avoid duplicates
thead.innerHTML = '';
tbody.innerHTML = '';
// Create header rows
const parentHeaderRow = document.createElement('tr');
const subHeaderRow = document.createElement('tr');
var proposels = json.proposal_data.over_all_column_data;
let randomColor = 'hsl(' + Math.random() * 360 + ', 100%, 93%)';
var proposel_count = 0;
var proposel_color_count = [];
// Add dynamic headers and subheaders
json.table_data.headers.forEach(header => {
const parentTh = document.createElement('th');
parentTh.colSpan = header.subHeaders.length;
let randomColor = 'hsl(' + Math.random() * 360 + ', 100%, 93%)';
// Check if header is not "Sno", "Item Key", "Particulars", or "Action" before adding dropdown
if (!["Sno", "Item Key", "Particulars", "Action"].includes(header.parentHeader)) {
proposel_count++;
// Extract qcr and stc status for the main headers
const dropdown_data_qcr = proposels[header.parentHeader]?.qcr == 1 ?
'style="background-color: rgb(221, 221, 221);"' : '';
const dropdown_data_stc = proposels[header.parentHeader]?.stc == 1 ?
'style="background-color: rgb(221, 221, 221);"' : '';
const check_icon_qcr = proposels[header.parentHeader]?.qcr == 1 ?
`<i class="fa fa-check-square" style="color: green; margin-left: 8px;"></i>` : '';
const check_icon_stc = proposels[header.parentHeader]?.stc == 1 ?
`<i class="fa fa-check-square" style="color: green; margin-left: 8px;"></i>` : '';
parentTh.innerHTML = `${header.parentHeader} <span class="dropdown" onclick="showThreeDottedMenu(event)">
<button class="dropbtn">⋮</button>
<div class="dropdown-content">
<a href="#" class="addInsurer">Add Insurer</a>
<a href="#" class="qcrProposal" ${dropdown_data_qcr}>QCR${check_icon_qcr}</a>
<a href="#" class="sendClientProposal" ${dropdown_data_stc}>Send to Client${check_icon_stc}</a>
<a href="#" class="removeProposal">Remove</a>
</div>
</span>`;
// console.log('proposel_count', proposel_count);
if (proposel_count > 1) {
parentTh.style.backgroundColor = randomColor;
proposel_color_count[header.parentHeader] = randomColor;
}
} else {
parentTh.innerText = header.parentHeader;
}
// Hide column if header is "Item Key"
if (header.parentHeader === "Item Key") {
parentTh.classList.add('hidden');
}
if (header.parentHeader === "Particulars") {
parentTh.classList.add('sticky');
}
if (header.parentHeader === "Sno") {
parentTh.classList.add('sticky');
}
parentHeaderRow.appendChild(parentTh);
// Add subheaders, hiding those under "Item Key"
header.subHeaders.forEach((subHeader, index) => {
const subTh = document.createElement('th');
// Hide if parent header is "Item Key"
if (header.parentHeader === "Item Key") {
subTh.classList.add('hidden');
}
if (header.parentHeader === "Particulars") {
subTh.classList.add('sticky');
}
if (header.parentHeader === "Sno") {
subTh.classList.add('sticky');
}
// Add dropdown menu only if subHeader is not "Quote Asked" or "-"
if (!["Quote Asked", "-"].includes(subHeader)) {
// Set default values for dropdown data
let dropdownDataQCRForInsurer = '';
let dropdownDataSTCForInsurer = '';
let checkDropdownDataQCRForInsurer = '';
let checkDropdownDataSTCForInsurer = '';
// Check if header is allowed to have insurer data
if (!["Sno", "Item Key", "Particulars", "Action"].includes(header.parentHeader)) {
const insurerData = proposels[header.parentHeader]?.insurers[index - 1] || {};
dropdownDataQCRForInsurer = insurerData.qcr == 1 ?
'style="background-color: rgb(221, 221, 221);"' : '';
dropdownDataSTCForInsurer = insurerData.stc == 1 ?
'style="background-color: rgb(221, 221, 221);"' : '';
checkDropdownDataQCRForInsurer = insurerData.qcr == 1 ?
`<i class="fa fa-check-square" style="color: green; margin-left: 8px;"></i>` :
'';
checkDropdownDataSTCForInsurer = insurerData.stc == 1 ?
`<i class="fa fa-check-square" style="color: green; margin-left: 8px;"></i>` :
'';
// console.log('Proposal data for insurer (insurerData):', insurerData);
// console.log('Proposal data for insurer (QCR):', dropdownDataQCRForInsurer);
// console.log('Proposal data for insurer (STC):', dropdownDataSTCForInsurer);
}
subTh.innerHTML = `${subHeader} <span class="dropdown" onclick="showThreeDottedMenu(event)">
<button class="dropbtn">⋮</button>
<div class="dropdown-content">
<a href="#" class="changeInsurer">Change Insurer</a>
<a href="#" class="qcrInsurer" ${dropdownDataQCRForInsurer}>QCR${checkDropdownDataQCRForInsurer}</a>
<a href="#" class="sendClientInsurer" ${dropdownDataSTCForInsurer}>Send to Client${checkDropdownDataSTCForInsurer}</a>
<a href="#" class="removeInsurer">Remove</a>
<a href="#" class="copyInsurerLast">Copy</a>
</div>
</span>`;
} else {
subTh.innerText = subHeader;
}
if (!["-"].includes(subHeader) && proposel_count > 1) {
subTh.style.backgroundColor = randomColor;
}
subHeaderRow.appendChild(subTh);
});
});
// console.log('proposel_color_count', proposel_color_count);
thead.appendChild(parentHeaderRow);
thead.appendChild(subHeaderRow);
// Populate table rows based on JSON data
json.table_data.data.forEach((rowData, rowIndex) => {
// console.log(rowData)
// console.log(rowData.items)
const row = document.createElement('tr');
// Serial number column
const snoTd = document.createElement('td');
snoTd.classList.add('sno');
snoTd.innerText = rowIndex + 1;
row.appendChild(snoTd);
// Hidden Item Key column
const itemKeyTd = document.createElement('td');
itemKeyTd.classList.add('hidden');
itemKeyTd.innerText = rowData.items || '';
row.appendChild(itemKeyTd);
row.id = rowData.items || '';
suggestionKeys.push(rowData.items);
// Particulars column
const particularsTd = document.createElement('td');
particularsTd.classList.add('particulars', 'sticky');
particularsTd.contentEditable = true;
// particularsTd.innerText = rowData.particulars || '';
particularsTd.innerText = rowData.data.find(d => d.parentth === "Particulars").input_value;
row.appendChild(particularsTd);
// Proposal columns and other data columns
rowData.data.forEach(dataEntry => {
// console.log('dataEntry', dataEntry)
const td = document.createElement('td');
if (dataEntry.parentth === "Action") {
td.classList.add('action');
const qcrChecked = dataEntry.input_value?.qcr ? "checked" : "";
const clientChecked = dataEntry.input_value?.stc ? "checked" : "";
td.innerHTML = `
<input type="checkbox" name="qcr" ${qcrChecked}> QCR
<input type="checkbox" name="client" ${clientChecked}> Client
<button class="btn btn-danger btn-sm removeRow"></button>
`;
} else {
td.contentEditable = true;
td.classList.add('editablecolumns');
td.innerText = dataEntry.value || '';
const hiddenInput = document.createElement('input');
hiddenInput.type = 'hidden';
hiddenInput.value = dataEntry.input_value || '';
// console.log('dataEntry.parentth', dataEntry.parentth);
if (proposel_color_count.hasOwnProperty(dataEntry.parentth)) {
// console.log('dataEntry.parentth', dataEntry.parentth);
td.style.backgroundColor = proposel_color_count[dataEntry.parentth];
}
td.appendChild(hiddenInput);
}
if (dataEntry.parentth !== "Sno" && dataEntry.parentth !== "Item Key" && dataEntry
.parentth !== "Particulars") {
row.appendChild(td);
}
});
tbody.appendChild(row);
});
proposal_colum_count = proposal_colum_count + proposel_count - 1;
proposel_count = 0;
// // Display JSON data for debugging
// const div = document.getElementById('second');
// console.log(div);
// div.innerHTML = ''; // Clear previous content
// const p = document.createElement('pre');
// p.innerText = JSON.stringify(json, null, 2);
// div.appendChild(p);
over_all_column_data = json.proposal_data.over_all_column_data;
moveAddRowButton();
attachEventListeners();
checkCellValueAndHighlight();
hideQCR()
}
</script>
<script>
$(document).ready(function () {
$('#submitData').on('click', async function () {
console.log(over_all_column_data);
try {
// $('.loader').fadeIn();
// $('.loader-mask').fadeIn();
const jsonData = await tableToJsonForFormSubmit(); // Construct the JSON data
console.log(jsonData);
// return false;
// Create a FormData object
const formData = new FormData();
let lead_id = $('#lead_id').val();
formData.append('json', JSON.stringify(jsonData));
formData.append('lead_id', lead_id);
const postUrl = '<?= base_url('rfq/create')?>';
console.log(postUrl);
const response = await $.ajax({
url: postUrl,
type: 'POST',
data: formData,
processData: false, // Important to prevent jQuery from processing the data
contentType: false, // Important to set this to false to let jQuery set the content type correctly
});
console.log('Data sent successfully:', response);
if(response.status == true){
toastr.success(response.message, 'SUCCESS');
}else{
toastr.warning(response.message, 'WARNING');
}
window.location.reload();
} catch (error) {
console.error('An error occurred during the AJAX request:');
if (error.responseText) {
try {
const errorResponse = JSON.parse(error.responseText);
console.error('Server Response:', errorResponse);
} catch (parseError) {
console.error('Error Message:', error.message);
console.error('Could not parse error response:', error.responseText);
}
} else {
console.error('Error Message:', error.message);
}
console.error('Full Error Object:', error);
}
});
});
$(document).ready(function () {
$('#submitQCRData').on('click', async function () {
console.log(over_all_column_data);
let qcr_count = $('#qcr_count').val()
let lead_id = $('#lead_id').val()
if(qcr_count != 0 && RFQ_or_QCR == 1){
console.log('qcr found')
url = '<?= base_url('rfq/list/') ?>' + lead_id + '/' + 2;
window.location.href = url;
}else{
console.log('qcr not found')
try {
$('.loader').fadeIn();
$('.loader-mask').fadeIn();
const jsonData = await convertJsonForQCR(); // Construct the JSON data
// Create a FormData object
const formData = new FormData();
let lead_id = $('#lead_id').val();
formData.append('json', JSON.stringify(jsonData));
formData.append('lead_id', lead_id);
const postUrl = '<?= base_url('rfq/createQCR')?>';
console.log(postUrl);
const response = await $.ajax({
url: postUrl,
type: 'POST',
data: formData,
processData: false, // Important to prevent jQuery from processing the data
contentType: false, // Important to set this to false to let jQuery set the content type correctly
});
console.log('Data sent successfully:', response);
if(response.status == true){
toastr.success(response.message, 'SUCCESS');
}else{
toastr.warning(response.message, 'WARNING');
}
window.location.href = '<?= base_url('rfq/list/') ?>' + lead_id + '/' + 2;
} catch (error) {
console.error('An error occurred during the AJAX request:');
if (error.responseText) {
try {
const errorResponse = JSON.parse(error.responseText);
console.error('Server Response:', errorResponse);
} catch (parseError) {
console.error('Error Message:', error.message);
console.error('Could not parse error response:', error.responseText);
}
} else {
console.error('Error Message:', error.message);
}
console.error('Full Error Object:', error);
}
}
});
});
async function tableToJsonForFormSubmit() {
return new Promise((resolve) => {
const headers = [];
const data = [];
const table = document.getElementById('rfqTable');
// Collect parent and subheaders
const parentHeaders = table.querySelectorAll('thead tr:nth-child(1) th');
const subHeaders = table.querySelectorAll('thead tr:nth-child(2) th');
let headerIndex = 0;
parentHeaders.forEach((header) => {
console.log('header names', header);
console.log('header header.innerText', header.innerText);
const colspan = header.getAttribute('colspan') || 1;
const subHeaderArray = [];
for (let i = 0; i < colspan; i++) {
const cleanedText = subHeaders[headerIndex].innerText.split('⋮')[0].trim();
subHeaderArray.push(cleanedText);
headerIndex++;
}
headers.push({
parentHeader: header.innerText.split('⋮')[0].trim(),
subHeaders: subHeaderArray
});
});
// Get the data from table rows
const rows = table.querySelectorAll('tbody tr');
rows.forEach(row => {
const rowId = row.id;
const cells = row.querySelectorAll('td');
const rowData = {
SNO: cells[0].innerText,
items: cells[1].innerText,
data: []
};
let dataIndex = 0;
headers.forEach(header => {
header.subHeaders.forEach(subHeader => {
const cell = cells[dataIndex];
let content = cells[dataIndex]?.innerText || '';
// Ensure suggestions[rowId] exists
const inputType = suggestions[rowId]?.type;
// Handle 'text' input types
if (inputType === "text") {
if (header.parentHeader === 'Action' && cell) {
const qcrInput = cell.querySelector('input[name="qcr"]');
const clientInput = cell.querySelector('input[name="client"]');
content = {
qcr: qcrInput?.checked ? 1 : 0,
stc: clientInput?.checked ? 1 : 0
};
} else {
const input = cell.querySelector('input');
if (input) {
content = input.value;
// console.log('hidden input value', content);
} else {
content = cells[dataIndex].innerText;
}
}
} else {
if (cell) {
const input = cell.querySelector('input');
if (input && header.parentHeader === 'Action') {
const qcrInput = cell.querySelector('input[name="qcr"]');
const clientInput = cell.querySelector('input[name="client"]');
content = {
qcr: qcrInput?.checked ? 1 : 0,
stc: clientInput?.checked ? 1 : 0
};
} else {
content = input ? input.value : cell.innerText;
}
}
}
rowData.data.push({
parentth: header.parentHeader,
subth: subHeader,
value: cells[dataIndex]?.innerText || '',
input_value: content
});
dataIndex++;
});
});
data.push(rowData);
});
const jsonData = {
table_data: {
headers: headers,
data: data
},
proposal_data: {
over_all_column_data: over_all_column_data
}
};
localStorage.setItem('data', JSON.stringify(jsonData));
resolve(jsonData);
});
}
async function convertJsonForQCR() {
var json = await tableToJsonForFormSubmit()
if(json){
const first_json = JSON.parse(JSON.stringify(json)); // Deep copy
console.log("Original JSON:", json);
let rowIndexArray = [];
let rowIndexArray2 = [];
// Column-wise Check: Remove headers and relevant data if qcr == 0
Object.entries(json.proposal_data.over_all_column_data).forEach(([proposalKey, proposalData], index) => {
// console.log('over_all_column_data index', index);
if (proposalData.qcr == 0 || proposalData.qcr == false) {
// Remove matching parentHeader in headers
const headerIndex = first_json.table_data.headers.findIndex(header => header.parentHeader === proposalKey);
if (headerIndex !== -1) first_json.table_data.headers.splice(headerIndex, 1);
first_json.table_data.data.forEach(item => {
item.data = item.data.filter(entry => entry.parentth !== proposalKey);
});
// Remove data entries with matching parentth
// Object.values(first_json.table_data.data).forEach(dataEntry => {
// const dataArray = dataEntry.data;
// if (dataArray) {
// const dataIndex = dataArray.findIndex(dataItem => dataItem.parentth === proposalKey);
// if (dataIndex !== -1) dataArray.splice(dataIndex, 1);
// }
// });
// Remove proposalKey from over_all_column_data
// Object.entries(first_json.proposal_data.over_all_column_data).splice(index, 1);
const updatedData = Object.keys(first_json.proposal_data.over_all_column_data)
.filter(key => key !== proposalKey)
.reduce((acc, key) => {
acc[key] = first_json.proposal_data.over_all_column_data[key];
return acc;
}, {});
// Assign the updated data back if needed
first_json.proposal_data.over_all_column_data = updatedData;
}
// Insurer Check: Remove subHeaders and relevant data for insurers with qcr == 0
proposalData.insurers.forEach((insurer, insurerIndex) => {
// console.log('insurer', insurer)
if (insurer.qcr === 0 || insurer.qcr == false) {
console.log(insurer.qcr)
first_json.table_data.headers.forEach(header => {
const subHeaderIndex = header.subHeaders.findIndex(sub => sub === insurer.display_name);
if (subHeaderIndex !== -1) header.subHeaders.splice(subHeaderIndex, 1);
});
first_json.table_data.data.forEach(item => {
item.data = item.data.filter(entry => entry.subth !== insurer.display_name);
});
// Object.values(first_json.table_data.data).forEach(dataEntry => {
// const dataArray = dataEntry.data;
// if (dataArray) {
// const dataIndex = dataArray.findIndex(dataItem => dataItem.subth === insurer.display_name);
// if (dataIndex !== -1) dataArray.splice(dataIndex, 1);
// }
// });
// Remove insurer from proposal's insurers array
console.log('insurerIndex', insurerIndex)
first_json.proposal_data.over_all_column_data[proposalKey].insurers.splice(insurerIndex, 1);
}
});
});
// rowIndexArray.sort((a, b) => b - a);
// rowIndexArray2.forEach((index) => {
// rowIndexArray.forEach((index2) => {
// first_json.table_data.data[index].data.splice(index2, 1);
// })
// });
// Row-wise Check: Remove rows if qcr == 0 for actions
Object.entries(first_json.table_data.data).forEach(([rowKey, rowData]) => {
const actionData = rowData.data.find(data => data.parentth === "Action" && data.input_value.qcr === 0);
if (actionData) first_json.table_data.data.splice(rowKey, 1);
});
console.log("Modified JSON:", first_json);
return first_json;
}
}
</script>