nhance-enrollment/app/Views/si_mapping.php
2025-01-16 14:02:13 +05:30

466 lines
20 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.

<div id="si_mapping" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="fullWidthModalLabel" aria-hidden="true">
<div class="modal-dialog modal-full-width">
<div class="modal-content">
<div class="modal-header" style="padding: 10px 15px">
<h4 class="modal-title" id="fullWidthModalLabel">SI Mapping</h4>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true" onclick="resetFormAndRemoveRows()">×</button>
</div>
<div class="modal-body" style="padding: 5px 15px;">
<form role="form" class="parsley-examples" id="si_mapping_form" enctype="multipart/form-data">
<input type="hidden" id="auto_si_pk" name="id">
<input type="hidden" id="client_policy_pk" name="client_policy_id">
<div class="form-row" style="margin-top:-2%">
<div class="form-group col-md-6">
<label id='choose_base_policy_label' for="choose_base_policy">Base Policy<span class="text-danger">*</span></label>
<select class="form-control" id="choose_base_policy" name="choose_base_policy">
<option value="">Select a Base Policy</option>
</select>
</div>
</div>
<input type="hidden" id="client_policy_id_form">
<input type="hidden" id="base_policy_id_form">
<div id="si-mapping-container">
<div class="form-row si-mapping-row">
<input name="primary_key" type="hidden" id='pk' value="">
<div class="form-group col-md-3">
<label>Base Policy SI Amount<span class="text-danger">*</span></label>
<select class="form-control" id="choose_si_amount_from_base_policy" name="choose_si_amount_from_base_policy">
<!-- <option value="">Choose SI Amount</option> -->
</select>
</div>
<div class="form-group col-md-3">
<label>Policy SI Amount</label><br />
<select class="form-control" name="choose_si_amount_for_policy[]" id="choose_si_amount_for_policy" multiple>
</select>
</div>
<div class="form-group">
<div class="btn-group" style="margin-top: 45px;">
<button type="button" id="deleteButton" class="btn btn-danger remove-row" style="margin-right: 5px;">x</button>
<button type="button" id="addButton" class="btn btn-success add-row">+</button>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-light" data-dismiss="modal" onclick="resetFormAndRemoveRows()">Close</button>
<button type="button" class="btn btn-primary" id="submitFormButton" onclick="submitForm()">Submit</button>
</div>
</form>
</div>
</div>
</div>
</div>
<script>
function loadModal(client_policy_id, base_policy_id) {
$('.loader').fadeIn();
$('.loader-mask').fadeIn();
$('#choose_base_policy').hide();
$('#choose_base_policy_label').hide();
checkExistingMapping(client_policy_id, base_policy_id);
$('#base_policy_id_form').val(base_policy_id);
$('#client_policy_id_form').val(client_policy_id);
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
};
var si_amt_base_policy = new Set();
function checkExistingMapping(client_policy_id, base_policy_id) {
$.ajax({
url: '<?= base_url("util/checkSIMapping") ?>',
method: 'POST',
data: {
client_policy_id: client_policy_id,
client_base_policy_id: base_policy_id
},
success: function(response) {
if (response.status === true && response.code === 200 && response.data.length > 0) {
// Clear existing rows except the first one
$('.si-mapping-row:not(:first)').remove();
// First, ensure base policy and parent policy data is loaded
fetchBasePolicy(client_policy_id, base_policy_id);
fetchParentPolicy(client_policy_id, base_policy_id);
// Wait for dropdowns to be populated
setTimeout(() => {
response.data.forEach((mapping, index) => {
if (index === 0) {
// Handle first row
const firstRow = $('.si-mapping-row:first');
// Clear existing values
firstRow.find('select[name="choose_si_amount_from_base_policy"]')
.val('')
.trigger('change');
firstRow.find('select[name="choose_si_amount_for_policy[]"]')
.val([])
.trigger('change');
// Set base policy SI amount
firstRow.find('select[name="choose_si_amount_from_base_policy"]')
.val(mapping.base_policy_si_amount)
.trigger('change');
// Set policy SI amounts (parse JSON string to array)
const policyAmounts = JSON.parse(mapping.policy_si_amounts);
firstRow.find('select[name="choose_si_amount_for_policy[]"]')
.val(policyAmounts)
.trigger('change');
// Store pk value
firstRow.find('input[name="primary_key"]').val(mapping.pk);
} else {
// Add new row for subsequent mappings
addRow();
$('#addButton').trigger("click");
// Wait for the new row to be properly initialized
setTimeout(() => {
const newRow = $('.si-mapping-row:last');
// Clear existing values
newRow.find('select[name="choose_si_amount_from_base_policy"]')
.val('')
.trigger('change');
newRow.find('select[name="choose_si_amount_for_policy[]"]')
.val([])
.trigger('change');
// Set base policy SI amount
newRow.find('select[name="choose_si_amount_from_base_policy"]')
.val(mapping.base_policy_si_amount)
.trigger('change');
// Set policy SI amounts
const policyAmounts = JSON.parse(mapping.policy_si_amounts);
newRow.find('select[name="choose_si_amount_for_policy[]"]')
.val(policyAmounts)
.trigger('change');
// Store pk value
newRow.find('input[name="primary_key"]').val(mapping.pk);
}, 500);
}
});
}, 1000); // Wait for fetchBasePolicy and fetchParentPolicy to complete
}else{
fetchBasePolicy(client_policy_id, base_policy_id);
fetchParentPolicy(client_policy_id, base_policy_id);
}
},
error: function(xhr, status, error) {
console.log("Error during AJAX request:", error);
toastr.error("Failed to fetch existing mappings");
}
});
}
function fetchBasePolicy(client_policy_id, base_policy_id) {
$.ajax({
url: '<?php echo base_url("util/getPolicySIRacketData")?>',
method: 'GET',
data: {
client_policy_id: client_policy_id,
client_base_policy_id: base_policy_id
},
success: function(response) {
console.log(response); // Log the entire response
if (response.status === true) {
// Reset the Set to avoid duplication when re-fetching
si_amt_base_policy.clear();
console.log("Data to be added:", response.data);
// Loop through the response.data array and add 'si' values to the Set
for (let i = 0; i < response.data.length; i++) {
si_amt_base_policy.add(response.data[i].si); // Add to Set, duplicates will be ignored
}
// Convert Set back to an array to use in the dropdown
si_amt_base_policy = Array.from(si_amt_base_policy);
console.log("Unique SI amounts:", si_amt_base_policy); // Check the result
// Clear existing options in the dropdown
// $('#choose_si_amount_from_base_policy').empty();
$('#choose_si_amount_from_base_policy').append('<option value="">Select SI Amount</option>');
// Append the new options
for (let i = 0; i < si_amt_base_policy.length; i++) {
console.log("Appending option:", si_amt_base_policy[i]); // Log each SI value
$('#choose_si_amount_from_base_policy').append(`<option value="${si_amt_base_policy[i]}">${si_amt_base_policy[i]}</option>`);
}
} else {
console.log("Error: Response status is false");
}
},
error: function(xhr, status, error) {
console.log("Error during AJAX request:", error);
}
});
}
var si_amt_parent_policy = new Set();
function fetchParentPolicy(client_policy_id, base_policy_id) {
$.ajax({
url: '<?= base_url("util/fetchPolicySIDataForParentPolicy")?>',
method: 'GET',
data: {
client_policy_id: client_policy_id,
client_base_policy_id: base_policy_id
},
success: function(response) {
if (response.status === true) {
// Reset the Set to avoid duplication when re-fetching
si_amt_parent_policy.clear();
console.log("Data to be added:", response.data);
// Loop through the response.data array and add 'si' values to the Set
for (let i = 0; i < response.data.length; i++) {
si_amt_parent_policy.add(response.data[i].si); // Add to Set, duplicates will be ignored
}
// Convert Set back to an array to use in the dropdown
si_amt_parent_policy = Array.from(si_amt_parent_policy);
console.log("Unique SI amounts:", si_amt_parent_policy); // Check the result
// Clear existing options in the dropdown
// $('#choose_si_amount_for_policy').empty();
$('#choose_si_amount_for_policy').append('<option value="">Select SI Amount</option>');
// Append the new options
for (let i = 0; i < si_amt_parent_policy.length; i++) {
console.log("Appending option:", si_amt_parent_policy[i]); // Log each SI value
$('#choose_si_amount_for_policy').append(`<option value="${si_amt_parent_policy[i]}">${si_amt_parent_policy[i]}</option>`);
}
} else {
console.log("Error: Response status is false");
}
},
error: function(xhr, status, error) {
console.log("Error during AJAX request:", error);
}
});
}
$(document).ready(function() {
// Initialize select2 for the initial select field
$("#choose_si_amount_for_policy").select2({
placeholder: 'Select SI Amount'
});
$("textarea.select2-search__field").attr('rows', '1');
$("textarea.select2-search__field").css('resize', 'none');
// Function to get all selected base policy values
function getSelectedBasePolicies() {
var selectedBasePolicies = [];
$('.si-mapping-row').each(function() {
var selectedBasePolicy = $(this).find('select[name="choose_si_amount_from_base_policy"]').val();
if (selectedBasePolicy) {
selectedBasePolicies.push(selectedBasePolicy);
}
});
return selectedBasePolicies;
}
function addRow() {
// Get selected base policies from all previous rows
var selectedBasePolicies = getSelectedBasePolicies();
// Check if si_amt_base_policy has been populated
if (si_amt_base_policy.length === 0) {
console.log("SI amounts not yet loaded.");
return; // Prevent adding the row if the data isn't ready
}
// Create a new row with the same structure as the existing row
var newRow = $('<div class="form-row si-mapping-row">');
// Generate unique IDs for the new row's selects
var uniqueIdForBasePolicy = 'choose_base_policy_' + Date.now();
var uniqueIdForSIAmountForPolicy = 'choose_si_amount_for_policy_' + Date.now();
newRow.append(
'<input name = "primary_key" type="hidden" id="'+uniqueIdForBasePolicy+'" value="">'+
'<div class="form-group col-md-3">' +
'<label>Base Policy SI Amount<span class="text-danger">*</span></label>' +
'<select class="form-control" id="' + uniqueIdForBasePolicy + '" name="choose_si_amount_from_base_policy">' +
'<option value="">Choose SI Amount</option>' +
'</select>' +
'</div>'
);
newRow.append(
'<div class="form-group col-md-3">' +
'<label>Policy SI Amount</label><br />' +
'<select class="form-control" id="' + uniqueIdForSIAmountForPolicy + '" name="choose_si_amount_for_policy[]" multiple>' +
'</select>' +
'</div>'
);
newRow.append(
'<div class="form-group">' +
'<div class="btn-group" style="margin-top: 45px;">' +
'<button type="button" class="btn btn-danger remove-row" style="margin-right: 5px;">x</button>' +
'<button type="button" class="btn btn-success add-row">+</button>' +
'</div>' +
'</div>'
);
// Append the new row to the container
$('#si-mapping-container').append(newRow);
// Loop through and append SI amounts to the new row's 'choose_si_amount_from_base_policy' dropdown
si_amt_base_policy.forEach(function(value) {
newRow.find('select[name="choose_si_amount_from_base_policy"]').append('<option value="'+value+'">'+value+'</option>');
});
// Remove selected base policies from the new row's 'choose_si_amount_from_base_policy' options
newRow.find('select[name="choose_si_amount_from_base_policy"] option').each(function() {
var value = $(this).val();
if (selectedBasePolicies.includes(value)) {
$(this).remove();
}
});
// Append the unique SI amounts to 'choose_si_amount_for_policy[]'
si_amt_parent_policy.forEach(function(value) {
newRow.find('select[name="choose_si_amount_for_policy[]"]').append('<option value="'+value+'">'+value+'</option>');
});
// Re-initialize select2 for the new row's dropdowns
newRow.find('select[name="choose_si_amount_for_policy[]"]').select2({
placeholder: 'Select SI Amount'
});
newRow.find('select[name="choose_si_amount_from_base_policy"]').select2({
placeholder: 'Choose SI Amount'
});
$("textarea.select2-search__field").attr('rows', '1');
$("textarea.select2-search__field").css('resize', 'none');
}
// Use event delegation to bind the click event for .add-row
$(document).on('click', '.add-row', function() {
addRow();
});
// Remove an SI Mapping row
$(document).on('click', '.remove-row', function() {
var pk = $(this).closest('.si-mapping-row').find('input[name="primary_key"]').val();
console.log('The primary key is ' + pk);
if (pk) {
var delete_status = deleteROW(pk);
if ($('.si-mapping-row').length > 1) {
$(this).closest('.si-mapping-row').remove();
}
} else {
if ($('.si-mapping-row').length > 1) {
$(this).closest('.si-mapping-row').remove();
}
}
});
});
function deleteROW(pk){
$.ajax({
url: "<?= base_url('util/deleteMapping')?>",
data:{
pk:pk
},
method:'POST',
success:function(response){
console.log(response);
toastr.success(response.message);
// return true;
},
error: function(xhr, status, error) {
console.log('Mapping Deletion failed:', error);
toastr.error("Mapping Deletion failed");
// return false
}
})
}
function submitForm() {
// Initialize formData as an object
var formData = {
client_policy_id: $('#client_policy_id_form').val(),
client_base_policy_id: $('#base_policy_id_form').val(),
si_mapping: [] // Array to hold all SI mapping rows
};
// Iterate through each `.si-mapping-row`
$('.si-mapping-row').each(function() {
var basePolicyAmount = $(this).find('select[name="choose_si_amount_from_base_policy"]').val();
var policyAmounts = $(this).find('select[name="choose_si_amount_for_policy[]"]').val(); // Multiple values
var pk = $(this).find('input[name="primary_key"]').val(); // Get the `pk` value for this row
// Add the data for this row to the si_mapping array
formData.si_mapping.push({
pk: pk, // Include the pk value
base_policy_si_amount: basePolicyAmount,
policy_si_amounts: policyAmounts
});
});
// Debugging: Log the full formData object
console.log('Form Data:', JSON.stringify(formData));
$('.loader').fadeIn();
$('.loader-mask').fadeIn();
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
// Submit the form data using AJAX
$.ajax({
url: '<?= base_url("util/saveSIMapping") ?>',
method: 'POST',
data: formData,
success: function(response) {
if(response.status == true && response.code == 200){
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
toastr.success('SI Mapped Successfully');
}
else {
var message = response.message;
toastr.error(message);
}
},
error: function(xhr, status, error) {
console.log('Form submission failed:', error);
toastr.error("Failed to Map SI");
$('.loader').fadeOut();
$('.loader-mask').delay(250).fadeOut('slow');
}
});
}
function resetFormAndRemoveRows() {
// Reset the form fields
$('#si_mapping_form')[0].reset(); // Reset all form fields
// Clear hidden input fields
$('#client_policy_id_form').val('');
$('#base_policy_id_form').val('');
// Remove all rows except the first one
$('#si-mapping-container .si-mapping-row:not(:first)').remove();
// Optionally, reset the select options to default values if needed
$('#choose_base_policy').val('').trigger('change');
$('#choose_si_amount_from_base_policy').val('').trigger('change');
$('#choose_si_amount_for_policy').val('').trigger('change');
}
</script>