nhance-enrollment/app/Views/test_members_list.php

1137 lines
45 KiB
PHP
Executable File
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>
.badge2 {
box-shadow: none;
}
.badge2-secondary2 {
color: #fff;
background-color: #187607;
}
.badge2 {
display: inline-block;
padding: .25em .4em;
font-size: 75%;
font-weight: 700;
line-height: 1;
text-align: center;
white-space: nowrap;
vertical-align: baseline;
border-radius: .25rem;
transition: color .15s ease-in-out, background-color .15s ease-in-out, border-color .15s ease-in-out, box-shadow .15s ease-in-out;
}
.table-responsive {
overflow-x: auto;
}
.word-wrap {
word-wrap: break-word;
white-space: normal;
}
.dataTables_filter{
position: absolute;
}
.right-align-input {
text-align: right;
}
/* Center the modal horizontally and vertically */
#map_emp_modal .modal-dialog {
max-width: 600px; /* Adjust the width as needed */
margin: 30px auto; /* Horizontally center the modal */
}
/* Vertically center the modal in the viewport */
#map_emp_modal .modal {
display: flex !important;
align-items: center; /* Center content vertically */
justify-content: center; /* Center content horizontally */
}
/* Make the modal content responsive */
#map_emp_modal .modal-content {
width: 100%;
border-radius: 10px; /* Optional: for rounded corners */
}
/* Optional: Adjust backdrop for better focus on modal */
#map_emp_modal .modal-backdrop.show {
opacity: 0.5; /* Darken backdrop for better focus */
}
.custom-dropdown-menu {
display: none;
position: absolute;
background-color: #ffffff !important;
border: 1px solid rgba(0, 0, 0, 0.15);
border-radius: 0.25rem;
padding: 0.5rem 0;
min-width: 10rem;
z-index: 9999;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
.custom-dropdown-menu .dropdown-item {
display: block !important;
width: 100% !important;
padding: 0.5rem 1rem !important;
color: #212529 !important;
text-decoration: none !important;
background-color: transparent !important;
}
.custom-dropdown-menu .dropdown-item:hover {
background-color: #f8f9fa !important;
color: #16181b !important;
cursor: pointer !important;
}
th, td {
text-align: center; /* Or left/right depending on your preference */
vertical-align: middle; /* Ensures content is vertically centered */
}
input[type="checkbox"] {
width: 16px; /* Standard checkbox size */
height: 16px;
margin: 0; /* Remove default margin */
vertical-align: middle; /* Align with text or other elements */
}
th:first-child, td:first-child {
width: 50px; /* Adjust width as needed */
}
.table-responsive {
overflow-x: auto;
}
.table {
table-layout: fixed; /* Prevent columns from resizing dynamically */
}
</style>
<?php $pro_rata_total = 0; $gst_total = 0 ?>
<div class="row" id="client_list">
<div class="col-12">
<div class="card">
<div class="card-body">
<div class="row" style="padding-bottom: 10px;">
<div class="col-6" style="align-self: center;">
<h4 style="position: relative;">Employees</h4>
</div>
</div>
<table class="table table-striped mb-0 nowrap" cellspacing="0" id="tickets-table">
<thead class="bg-light">
<tr>
<th><input type="checkbox" id="selectAll" onclick="toggleAll(this)"></th>
<th class="font-weight-medium">SNO</th>
<?php if (isset($getData)) {
if ($getData['client_id'] == '0' && $getData['policy_id'] == '0' && $getData['branch_id'] == '0' && ($getData['emp_code'] != "" || $getData['emp_name'] != "" || $getData['status'] != "")) { ?>
<th class="font-weight-medium">Client/Branch</th>
<?php }
if ($getData['client_id'] != '0' && $getData['branch_id'] == '0') { ?>
<th class="font-weight-medium">Branch</th>
<?php } } ?>
<th class="font-weight-medium">Name</th>
<th class="font-weight-medium">EMP Code</th>
<th class="font-weight-medium">Relationship</th>
<th class="font-weight-medium">Gender</th>
<th class="font-weight-medium">Date of Birth</th>
<th class="font-weight-medium">Existing Policy Count</th>
<!-- <th class="font-weight-medium">Policy name</th>
<th class="font-weight-medium">Insurer name</th>
<th class="font-weight-medium">TPA ID</th>
<th class="font-weight-medium">Risk ID</th>
<th class="font-weight-medium">Policy status</th>
<th class="font-weight-medium">(₹)Sum Insured</th>
<th class="font-weight-medium">(₹)Premium</th>
<th class="font-weight-medium" id="rata_premium" data-toggle="tooltip" data-placement="top">(₹)Pro Rata <br> Premium</th>
<th class="font-weight-medium" id="gst" data-toggle="tooltip" data-placement="top">(₹)GST</th> -->
<th class="font-weight-medium" > Action </th>
</tr>
</thead>
<tbody class="font-12">
<?php
if (isset($employees)) {
$pro_rata_total = 0;
$gst_total = 0;
foreach ($employees as $key => $employee) { ?>
<tr>
<td><input type="checkbox" class="rowCheckbox" value="<?= isset($employee['id'])?$employee['id']:$key+1?>"></td>
<td><b><?php echo ($key + 1); ?></b></td>
<?php if (isset($getData)) {
if ($getData['client_id'] == '0' && $getData['policy_id'] == '0' && $getData['branch_id'] == '0' && ($getData['emp_code'] != "" || $getData['emp_name'] != "" || $getData['status'] != "")) { ?>
<td><?php echo $employee['client_short_name'] . ' - ' . $employee['client_branch_name']; ?></td>
<?php }
if ($getData['client_id'] != '0' && $getData['branch_id'] == '0') { ?>
<td><?php echo $employee['client_branch_name']; ?></td>
<?php } } ?>
<td><?php echo $employee['name']; ?></td>
<td><?php echo $employee['emp_code']; ?></td>
<td><?php echo $employee['relationship']; ?></td>
<td><?php echo $employee['gender']; ?></td>
<td><?php echo date('d/M/Y', strtotime($employee['dob'])); ?></td>
<?php /*
<!-- <td><?php //echo isset($employee['policy_type']) ? $employee['policy_type'] : ''; ?> - <?php echo isset($employee['policy_no']) ? $employee['policy_no'] : ''; ?></td>
<td><?php //echo isset($employee['insurer_short_name'])?$employee['insurer_short_name']:''; ?></td>
<td><?php // echo isset($employee['tpa_id'])?$employee['tpa_id']:''; ?></td>
<td><?php //echo isset($employee['uhid'])?$employee['uhid']: ""; ?></td>
<td>
if(isset($employee['status'])){
switch ($employee['status']) {
case 'draft':
echo '<span class="badge badge-secondary">' . $employee['status'] . '</span>';
break;
case 'active':
echo '<span class="badge badge-success">' . $employee['status'] . '</span>';
break;
case 'inactive':
echo '<span class="badge badge-warning">' . $employee['status'] . '</span>';
break;
case 'expired':
echo '<span class="badge badge-danger">' . $employee['status'] . '</span>';
break;
case 'enrolled':
echo '<span class="badge2 badge2-secondary2">' . $employee['status'] . '</span>';
break;
default:
echo $employee['status'];
break;
}
}
</td>
<td><?php // if(isset($employee['basic_cover_si'])) {echo (format_indian_number($employee['basic_cover_si']))?format_indian_number($employee['basic_cover_si']):''; }?></td>
<td><?php //if(isset($employee['premium'])) { echo null!=(format_indian_number($employee['premium']))? format_indian_number($employee['premium']):''; } ?></td>
<td><?php //if(isset($employee['rata_premimum'])){$pro_rata_total += $employee['rata_premimum']; echo format_indian_number($employee['rata_premimum']);} ?></td>
<td><?php // if(isset($employee['gst'])){$gst_total += $employee['gst']; echo format_indian_number($employee['gst']); }?></td> -->
*/
?>
<td><?= $employee['policy_count'] ?></td>
<td>
<div class="btn-group dropdown">
<a href="javascript: void(0);" class="dropdown-toggle arrow-none btn btn-light btn-sm" data-toggle="dropdown"aria-expanded="false"><i class="mdi mdi-dots-horizontal"></i></a>
<div class="dropdown-menu dropdown-menu-right">
<a class="dropdown-item" onclick="get_emp_master_data_for_update(this, '<?= $employee['id'];?>')" ><i class="mdi mdi-pencil mr-2 text-muted font-18 vertical-middle"></i>Edit</a>
</div>
</div>
</td>
</tr>
<?php } } ?>
</tbody>
<tfoot>
<tr><?php /*
<th></th>
<?php if (isset($getData)) {
if ($getData['client_id'] == '0' && $getData['policy_id'] == '0' && $getData['branch_id'] == '0' && ($getData['emp_code'] != "" || $getData['emp_name'] != "" || $getData['status'] != "")) { ?>
<th></th>
<?php }
if ($getData['client_id'] != '0' && $getData['branch_id'] == '0') { ?>
<th></th>
<?php } } ?>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<!-- <th>Total</th>
<th><?php echo format_indian_number($pro_rata_total); ?></th>
<th><?php echo format_indian_number($gst_total); ?></th> -->
<th></th>
</tr> */ ?>
</tfoot>
</table>
</div>
</div>
</div><!-- end col -->
</div>
<!-- Map Employee Modal -->
<div id="map_emp_modal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="mapEmpModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="mapEmpModalLabel">Map Employees</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
<form id="mapEmployeesForm" onsubmit="mapEmployeeSave(event)">
<div class="row">
<div class="col-xl-12">
<div class="card-body">
<div class="form-row">
<div class="form-group col-md-4">
<label>Client</label>
<select class="form-control" id="clients">
<option value="0">Select</option>
</select>
</div>
<div class="form-group col-md-4">
<label>Branch</label>
<select name="branch_id" class="form-control" id="branch_id">
<option value="0">Select</option>
</select>
</div>
<div class="form-group col-md-4">
<label>Policy</label>
<select class="form-control" id="policies">
<option value="0">Select</option>
</select>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label>Policy Start Date</label>
<input type="text" class="form-control" id="policy_start_date" name="policy_start_date" placeholder="Enter Policy Start Date">
</div>
<div class="form-group col-md-6">
<label>SI Amount</label>
<select class="form-control" id="si_amt" name="si_amt">
<option value="0">Select</option>
</select><input type="hidden" name="employee_ids" id="employee_ids">
</div>
</div>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary" form="mapEmployeesForm">Save changes</button>
</div>
</div>
</div>
</div>
<!-- end modal -->
<!-- Edit modal content -->
<div id="emp_modal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="display: none;">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Edit Employee</h4>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body p-4">
<form role="form" class="parsley-examples" id="empForm" onsubmit="update_emp_master_data_submit_function(event, this)" enctype="multipart/form-data">
<input type="hidden" name="employee_primary_id" id="employee_primary_id"/>
<div class="form-group">
<div class="form-row">
<div class="form-group col-md-4">
<label for="emp_code">Employee Code<span class="text-danger">*</span></label>
<input type="text" class="form-control" id="emp_code_for_edit" placeholder="Enter Code">
</div>
<div class="form-group col-md-8">
<label for="name">Name<span class="text-danger">*</span></label>
<input type="text" class="form-control" name="name" id="name" placeholder="Ente Name">
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="gender">Gender</label>
<select class="form-control" id="gender" name="gender">
<option value="">Select Gender</option>
<option value="M">Male</option>
<option value="F">Female</option>
</select>
</div>
<div class="form-group col-md-6">
<label for="dob">Date of Birth</label>
<input type="text" class="form-control" id="dob" placeholder="Enter DOB" name="dob">
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="relationship">Relationship<span class="text-danger">*</span></label>
<select class="form-control" id="relationship" name="relationship">
<option value="">Select Relationship</option>
<option value="Self">Self</option>
<option value="Spouse">Spouse</option>
<option value="Child">Child</option>
<option value="Father">Father</option>
<option value="Mother">Mother</option>
<option value="Father-in-law">Father-in-law</option>
<option value="Mother-in-law">Mother-in-law</option>
</select>
</div>
<div class="form-group col-md-6">
<label for="mobile">Mobile Number<span class="text-danger">*</span></label>
<input type="text" class="form-control" id="mobile" placeholder="Enter Mobile Number" name="mobile" onkeypress="return onlyNumbers(event)" maxlength="10" minlength="10">
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="basic_pay">Basic Pay</label>
<input type="text" class="form-control" id="basic_pay" placeholder="Enter Basic Pay" name="basic_pay" >
</div>
<div class="form-group col-md-6">
<label for="band">Band</label>
<input type="text" class="form-control" id="band" placeholder="Enter Band" name="band">
</div>
</div>
<div class="form-group col-md-12">
<label for="email">Email<span class="text-danger">*</span></label>
<input type="text" class="form-control" id="email_corporate" placeholder="Enter Email" name="email_corporate" data-parsley-trigger="change" data-parsley-type="email" >
</div>
</div>
<div class="form-group text-right m-b-0">
<button type="submit" class="btn btn-primary waves-effect waves-light mr-1" id="btnSubmit">Submit</button>
</div>
</form>
</div>
</div>
</div>
</div><!-- /.modal -->
<script>
document.addEventListener("DOMContentLoaded", function () {
const table = document.getElementById("tickets-table");
// Create custom dropdown
function createCustomDropdown(row) {
const originalDropdown = row.querySelector('.dropdown-menu');
if (!originalDropdown) return null;
const customDropdown = document.createElement('div');
customDropdown.className = 'custom-dropdown-menu';
customDropdown.innerHTML = originalDropdown.innerHTML;
// Remove inline onclick handlers and store them in data attributes
const originalItems = originalDropdown.querySelectorAll('.dropdown-item');
customDropdown.querySelectorAll('.dropdown-item').forEach((item, index) => {
const originalOnclick = originalItems[index].getAttribute('onclick');
item.removeAttribute('onclick'); // Remove the inline handler
item.setAttribute('data-onclick', originalOnclick); // Store in data attribute
});
return customDropdown;
}
let activeDropdown = null;
// Add click event listener to rows
table.querySelectorAll("tbody tr").forEach(row => {
const customDropdown = createCustomDropdown(row);
if (!customDropdown) return;
document.body.appendChild(customDropdown);
row.addEventListener("click", function(event) {
// Ignore clicks on the first column
if (event.target.closest('td:first-child')) return;
if (activeDropdown) activeDropdown.style.display = 'none';
const rect = event.target.getBoundingClientRect();
customDropdown.style.display = 'block';
customDropdown.style.position = 'fixed';
customDropdown.style.left = `${rect.left}px`;
customDropdown.style.top = `${rect.bottom + 5}px`;
activeDropdown = customDropdown;
event.stopPropagation();
});
// Handle custom dropdown clicks
customDropdown.querySelectorAll('.dropdown-item').forEach(item => {
item.addEventListener('click', function(e) {
e.preventDefault();
// Execute the original onclick from data attribute
const onclickAttr = this.getAttribute('data-onclick');
if (onclickAttr) eval(onclickAttr);
// Handle href navigation
const href = this.getAttribute('href');
if (href && href !== '#') window.location.href = href;
if (activeDropdown) {
activeDropdown.style.display = 'none';
activeDropdown = null;
}
e.stopPropagation();
});
});
});
// Close dropdown on outside click
document.addEventListener("click", function() {
if (activeDropdown) {
activeDropdown.style.display = 'none';
activeDropdown = null;
}
});
});
</script>
<script>
function toggleAll(selectAllCheckbox) {
const rowCheckboxes = document.querySelectorAll('.rowCheckbox');
rowCheckboxes.forEach(checkbox => {
checkbox.checked = selectAllCheckbox.checked;
});
}
$(document).ready(function(){
var dob = flatpickr("#dob", {
dateFormat: "d/M/Y",
allowInput: false
});
var policy_start_date = flatpickr("#policy_start_date", {
dateFormat: "d/M/Y",
allowInput: false
});
fetchClientPolicies();
})
$(document).ready(function() {
var ticketsTable = $('#tickets-table');
if (ticketsTable.length) {
ticketsTable.DataTable({
scrollX: true,
dom: "<'row'<'col-sm-6'f><'col-sm-6 text-right'B>>" + // Filter left, buttons right
"<'row'<'col-sm-12'tr>>" +
"<'row'<'col-sm-5'i><'col-sm-7'p>>", // Pagination at the bottom, without page length selector
buttons: [{
text:'Map Employees',
action: function(e, dt, node, config) {
mapEmployees();
}
},
{
text:'Unmap Employees',
action: function(e, dt, node, config) {
unmapEmployees();
}
}],
language: {
search: "_INPUT_",
searchPlaceholder: "Search..."
},
paging: true, // Enable pagination
pageLength: 25 // Set default number of rows per page (optional)
});
} else {
console.error("Table not found.");
}
});
function get_emp_master_data_for_update(input, id){
get_emp_master_data_for_update_ajax(id)
}
function get_emp_master_data_for_update_ajax(id){
$('.loader').fadeIn();
$('.loader-mask').fadeIn();
$.ajax({
url: '<?php echo base_url('util/get_emp_master_data_for_update/');?>'+id,
type: "GET",
dataType: 'json',
success: function (res) {
console.log('get_emp_master_data_for_update response', res)
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
let data = res.data
if(res.status == true){
if(data.relationship == 'Self'){
$('#gender').prop('disabled', false)
}else{
$('#gender').prop('disabled', true)
}
$('#employee_primary_id').val(data.id);
$('#emp_code_for_edit').val(data.emp_code);
$('#name').val(data.name);
$('#gender').val(data.gender);
$('#dob').val(data.formatted_dob);
$('#email_corporate').val(data.email_corporate);
$('#mobile').val(data.mobile);
$('#basic_pay').val(data.basic_pay);
$('#band').val(data.band);
$('#relationship').val(data.relationship);
$('#emp_modal').modal('show');
var myModal = new bootstrap.Modal(document.getElementById('emp_modal'));
myModal.show();
}else{
$('#employee_primary_id').val('');
$('#emp_code_for_edit').val('');
$('#name').val('');
$('#gender').val('');
$('#dob').val('');
$('#email_corporate').val('');
$('#mobile').val('');
toastr.warning(res.message, 'Warning');
}
},
error: function (xhr, status, error) {
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
console.error(xhr.responseText);
console.error(status, error);
}
});
}
function update_emp_master_data_submit_function(event, form){
event.preventDefault(); // Prevent the default form submission
var isValid = $(form).parsley().validate();
if (!isValid) {
console.log('Form is Empty', 'Warning');
return ;
}
const formData = new FormData(form);
const submitButton = form.querySelector('button[type="submit"]');
submitButton.disabled = true;
submitButton.innerText = 'Updating...';
$('.loader').fadeIn();
$('.loader-mask').fadeIn();
// AJAX request to update the individual employee
$.ajax({
url: '<?= base_url('/util/update_emp_data') ?>',
type: 'POST',
data: formData,
processData: false,
contentType: false,
success: function(response) {
console.log(response)
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
if(response.status == true){
toastr.success(response.message, 'Success');
$('.close').click();
$('#employee_primary_id').val('');
$('#emp_code_for_edit').val('');
$('#name').val('');
$('#gender').val('');
$('#dob').val('');
$('#email_corporate').val('');
$('#mobile').val('');
window.location.reload();
}else{
toastr.error(response.message, 'Error');
}
},
error: function(xhr, status, error) {
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
// Handle error
console.error('Upload error occurred:');
console.error('Status: ', status); // Status of the request
console.error('Error: ', error); // Specific error message
console.error('XHR Object: ', xhr); // Full XHR object with response details
// Optionally log server response, if available
if (xhr.responseText) {
console.error('Response Text: ', xhr.responseText);
}
toastr.warning('Error uploading file', 'Warning');
console.error('Upload error:', error);
},
complete: function() {
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
// Re-enable the submit button and reset its text
submitButton.disabled = false;
submitButton.innerText = 'Submit';
}
});
}
// function send_mail_for_individual_employee_ecard(id){
// Swal.fire({
// title: "Do you want to send Ecard Mail?",
// showDenyButton: true,
// showCancelButton: false,
// confirmButtonText: "Yes,Send",
// denyButtonText: "Don't Send"
// }).then((result) => {
// if (result.isConfirmed) {
// $('.loader').fadeIn();
// $('.loader-mask').fadeIn();
// $.ajax({
// url: '<?php echo base_url('util/send_mail_for_individual_employee_ecard/');?>'+id,
// type: "GET",
// dataType: 'json',
// success: function (res) {
// console.log('send_mail_for_individual_employee_ecard response', res)
// $('.loader').fadeOut();
// $('.loader-mask').delay(350).fadeOut('slow');
// if(res.status == true){
// toastr.success(res.message, 'Success');
// }else{
// toastr.error(res.message, 'Error');
// }
// },
// error: function (xhr, status, error) {
// $('.loader').fadeOut();
// $('.loader-mask').delay(350).fadeOut('slow');
// console.error(xhr.responseText);
// console.error(status, error);
// }
// });
// }
// });
// }
function mapEmployees(){
var selected = [];
$('.rowCheckbox:checked').each(function() {
selected.push($(this).val());
})
if(selected.length == 0){
toastr.warning('Please select atleast one employee', 'Warning');
return;
}
$('#employee_ids').val(selected);
// console.log($('#map_emp_modal').length); // Should print "1" if the modal is found
$('#map_emp_modal').modal('show');
var map_emp_modal = new bootstrap.Modal(document.getElementById('map_emp_modal'));
map_emp_modal.show();
}
$('#map_emp_modal').on('shown.bs.modal', function() {
console.log('Modal is shown');
fetchClientPolicies();
});
var clientPolicies = [];
var clientPoliciesWithBranch = {
policies: []
};
var client_id = '<?= isset($getData) ? $getData['client_id'] : '0' ?>';
var client_branch_id = '<?= isset($getData) ? $getData['branch_id'] : '0' ?>';
function fetchClientPolicies() {
$('.loader').fadeIn();
$('.loader-mask').fadeIn();
var apiURL = '<?php echo base_url();?>' + 'util/clients-with-policies';
console.log('fetchClientPolicies');
console.log(apiURL);
$.ajax({
url: apiURL,
method: 'GET',
headers: {
"Content-Type": "application/json",
"X-Requested-With": "XMLHttpRequest"
},
success: function(response) {
// console.log(response.code);
// console.log(response.dataStatus);
// console.log(response.data);
if (response.code === 200 && response.dataStatus === true && response.data !== "") {
try {
clientPolicies = (response.data);
response.data.forEach(policy => {
// console.log('policies', policy.policies);
policy.policies.forEach(p => {
clientPoliciesWithBranch.policies.push(p);
});
});
// console.log('1',clientPolicies);
appendClients(clientPolicies);
//this function for reselect the policy
setTimeout(function() {
if (client_id != 0 ) {
var foundPolicies = clientPolicies.find(function(item) {
// console.log(typeof item.id)
return item.id == client_id;
});
appendBranch(foundPolicies.branchs);
}
}, 500);
setTimeout(function() {
if (client_branch_id != 0 ) {
var foundPolicies = clientPoliciesWithBranch.policies.filter(function(item) {
// console.log('item', item);
return item.branch_id === client_branch_id;
});
if (foundPolicies) {
// console.log('foundPolicies', foundPolicies);
appendPolicies(foundPolicies);
} else {
console.log('No policies found for the selected client');
}
}
}, 500);
//end
} catch (error) {
console.error('Error parsing API response data:', error);
}
} else if (response.code === 404 && response.dataStatus === false) {
console.error('no data found', response);
} else {
console.error('Something went wrong!');
}
},
error: function(xhr, status, error) {
console.error('Error fetching data from API:', error);
}
});
}
function appendClients(data) {
console.log("inside appendClients");
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
var clientID = <?= isset($getData) ? $getData['client_id'] : '0' ?>;
$.each(data, function(index, item) {
var option = $('<option>', {
value: item.id,
text: item.client_name
});
if (clientID == item.id) {
option.attr('selected', true);
}
$('#clients').append(option);
});
}
function appendBranch(data) {
$('#branch_id').empty();
$('#branch_id').append($('<option>', {
value: '0',
text: 'Select'
}));
$.each(data, function(index, item) {
var option = $('<option>', {
value: item.id,
text: item.branch_name
});
if (client_branch_id == item.id) {
option.attr('selected', true);
}
$('#branch_id').append(option);
});
}
function appendPolicies(data) {
$('#policies').empty();
$('#policies').append($('<option>', {
value: '0',
text: 'Select'
}));
var PolicyID = <?= isset($getData) ? $getData['policy_id'] : '0'?>;
// console.log(PolicyID)
$.each(data, function(index, item) {
var option = $('<option>', {
value: item.client_policy_id,
// text: `${item.name ?? ''} - ${item.policy_no ?? ''} - ${item.policy_type ?? ''}`
text:`${item.policy_type ?? ''} - ${item.policy_no ?? ''}`
});
if (PolicyID == item.client_policy_id) {
option.attr('selected', true);
}
$('#policies').append(option);
});
}
$(document).ready(function() {
$('#clients').on('change', function() {
$('#policies').empty();
$('#policies').append($('<option>', {
value: '0',
text: 'Select'
}));
var selectedClient = $(this).val();
// console.log('selectedClient', selectedClient);
// $('#selectedOptionInfo').text('Selected option: ' + selectedOption);
// Check if the selected option exists in apiData
var foundPolicies = clientPolicies.find(function(item) {
return item.id === selectedClient;
});
// console.log(foundPolicies.branchs);
appendBranch(foundPolicies.branchs);
});
});
$(document).ready(function() {
$('#branch_id').on('change', function() {
var selectedClient = $(this).val();
// console.log('selectedBranch', selectedClient);
// console.log('clientPolicies', clientPoliciesWithBranch);
var foundPolicies = clientPoliciesWithBranch.policies.filter(function(item) {
// console.log('item', item);
return item.branch_id === selectedClient;
});
if (Array.isArray(foundPolicies) && foundPolicies.length === 0) {
appendPolicies(foundPolicies);
toastr.warning('No policies found for the selected client branch.');
} else {
// console.log('foundPolicies', foundPolicies);
appendPolicies(foundPolicies);
}
});
});
// Function to convert object to query parameters
function objectToQueryString(obj) {
return Object.keys(obj).map(key => `${encodeURIComponent(key)}=${encodeURIComponent(obj[key])}`).join('&');
}
$(document).ready(function(){
$('#policies').on('change', function() {
$.ajax({
url:'<?php echo base_url('util/get_data_for_mapping') ?>',
type: 'POST',
data: {
policy_id: $('#policies').val(),
},
success: function(response) {
// console.log(response);
if(response.code === 200 && response.data !== ""){
console.log(response.data.si_amt);
const date = new Date(response.data.policy_start_date); // Parse the date string
const day = String(date.getDate()).padStart(2, '0'); // Ensure two digits for the day
const month = date.toLocaleString('en-GB', { month: 'short' }); // Get short month name
const year = date.getFullYear(); // Get the year
const formattedDate = `${day}/${month}/${year}`;
$('#policy_start_date').val(formattedDate);
for (var i = 0; i < response.data.si_amt.length; i++) {
console.log(response.data.si_amt[i]['si']);
$('#si_amt').append($('<option>', {
value: response.data.si_amt[i]['si'],
text: response.data.si_amt[i]['si']
}));
}
}
// $('#si_amt').val(response.data.si_amt);
}
})
});
})
function mapEmployeeSave(event) {
event.preventDefault(); // Prevent the default form submission
selected_id = $('#employee_ids').val()
selected_count = selected_id.split(',');console.log(selected_count);
// console.log('selected is '+selected_count.length);return;
// console.log('selected is '+ typeof selected);return;
// Initialize a counter to track completed requests
let completedRequests = 0;
// Iterate through the selected_count array
for (let i = 0; i < selected_count.length; i++) {
// Create an object to store form data as key-value pairs
let formData = {
client_id: $('#clients').val(),
branch_id: $('#branch_id').val(),
client_policy_id: $('#policies').val(),
policy_start_date: $('#policy_start_date').val(),
si_amt: $('#si_amt').val(),
selected: selected_count[i]
};
// Perform the AJAX request
$.ajax({
url: '<?php echo base_url('util/map_employees') ?>',
type: 'POST',
data: formData,
success: function(response) {
// Check the response for success or error
if (response.code === 200) {
console.log(`Iteration ${i}: Success - ${response.message}`);
} else {
toastr.error(response.message, 'Error');
}
},
error: function(xhr, status, error) {
console.error('AJAX Error:', error);
toastr.error('An error occurred. Please try again.', 'Error');
},
complete: function() {
// Increment the completed requests counter
completedRequests++;
// Check if all AJAX requests have completed
if (completedRequests === selected_count.length) {
toastr.success('All employees have been successfully mapped.', 'Success');
$('#map_emp_modal').modal('hide');
window.location.reload();
}
}
});
}
}
function unmapEmployees(){
var selected = [];
$('.rowCheckbox:checked').each(function() {
selected.push($(this).val());
})
if(selected.length == 0){
toastr.warning('Please select atleast one employee', 'Warning');
return;
}
Swal.fire({
title: "Do you want to unmap selected employees?",
showDenyButton: true,
showCancelButton: false,
confirmButtonText: "Yes, Unmap",
denyButtonText: "Don't Unmap"
}).then((result) => {
if (result.isConfirmed) {
// Nested SweetAlert to ask if the user wants to delete dependencies
Swal.fire({
title: "Do you also want to delete the dependencies?",
showDenyButton: true,
showCancelButton: true,
confirmButtonText: "Yes, Delete Dependencies and Unmap",
denyButtonText: "Don't Delete Dependencies, Unmap Only"
}).then((subResult) => {
$('.loader').fadeIn();
$('.loader-mask').fadeIn();
if (subResult.isConfirmed) {
var url = '<?php echo base_url('util/unmap_employees/1');?>';
}
else if (subResult.isDenied) {
var url = '<?php echo base_url('util/unmap_employees/0');?>';
}
// If they confirm to delete dependencies as well
$.ajax({
url: url,
type: "POST",
data: { selected: selected },
dataType: 'json',
success: function (res) {
console.log('unmap_employees', res);
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
if (res.status === true) {
toastr.success(res.message, 'Success');
window.location.reload();
} else {
toastr.error(res.message, 'Error');
}
},
error: function (xhr, status, error) {
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
console.error(xhr.responseText);
console.error(status, error);
}
});
});
} else if (result.isDenied) {
// If the user denies unmapping, nothing happens
}
});
}
</script>