nhance-enrollment/app/Views/insurer_statement_list.php

1304 lines
56 KiB
PHP
Executable File
Raw Permalink 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>
.table th,
.table td {
padding: 8px;
}
table.dataTable tbody td {
padding: 4px 4px !important;
}
/* table.dataTable thead th {
padding: 4px 4px !important;
} */
.col-12 {
max-width: 98% !important;
}
.dataTables_filter {
position: absolute;
}
.highlight {
border: 2px solid red;
background-color: #ffe6e6;
}
.column-header {
margin-right: 10px; /* Adjust this value as needed */
}
.form-section {
border: 1px solid #ccc;
padding: 15px;
margin-bottom: 20px;
}
.row-box {
border: 1px solid #ccc;
padding: 10px;
margin-bottom: 10px;
}
</style>
<style>
.switch {
position: relative;
display: inline-block;
width: 54px;
height: 34px;
}
.switch input {
opacity: 0;
width: 0;
height: 0;
}
.slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
-webkit-transition: .4s;
transition: .4s;
}
.slider:before {
position: absolute;
content: "";
height: 19px;
width: 19px;
left: 4px;
bottom: 4px;
background-color: white;
-webkit-transition: .4s;
transition: .4s;
}
input:checked + .slider {
background-color: #2196F3;
}
input:focus + .slider {
box-shadow: 0 0 1px #2196F3;
}
input:checked + .slider:before {
-webkit-transform: translateX(26px);
-ms-transform: translateX(26px);
transform: translateX(26px);
}
/* Rounded sliders */
.slider.round {
border-radius: 34px;
}
.slider.round:before {
border-radius: 50%;
}
.disabled-option {
color: gray;
}
.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;
}
</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;">Insurer Statement List</h4>
</div>
<div class="col-6" style="text-align: right;">
<button type="button" id="btnAdd" onclick="showFileUploadModal()" class="btn btn-primary waves-effect waves-light">Upload</button>
</div>
</div>
<div>
<table class="table table-striped mb-0 nowrap" cellspacing="0" id="tickets-table">
<thead class="bg-light">
<tr>
<th></th>
<th><div class="column-header">Insurer</div></th>
<th><div class="column-header">Month</div></th>
<th><div class="column-header">Statement<br>sno</div></th>
<th><div class="column-header">Filename</div></th>
<th><div class="column-header">Line<br>items</div></th>
<th><div class="column-header">File<br>status</div></th>
<th><div class="column-header">Invoice<br>status</div></th>
<th><div class="column-header">User/Time</div></th>
<th><div class="column-header">Action</div></th>
</tr>
</thead>
<tbody>
<?php foreach($insurer_statement_list as $row){ ?>
<tr>
<td><input type="hidden" class="row-select" data-id="<?= $row['id']; ?>"></td>
<td><?php echo $row['short_name'].'-'.$row['branch_code']; ?></td>
<td><?php echo change_date_format($row['month'],'Y-m-d','M-Y'); ?></td>
<td><?php echo $row['stmt_sno'] ?> </td>
<td><?php echo $row['file_name'] ?> </td>
<td><?php echo $row['line_items'] ?></td>
<td><?php echo $row['file_status'];
if($row['file_status'] == 'failed')
{
echo " <span class='col-xl-3 col-lg-4 col-sm-6'> <i class='fe-alert-circle' data-toggle='modal' data-target='#file-err-modal' data-err=" . $row['id'] . "></i></span>";
}
?>
</td>
<td><?php echo (isset($invoice_status_array[ $row['invoice_status'] ]) ? $invoice_status_array[ $row['invoice_status'] ] : ' - ') ?>
<span class="col-xl-3 col-lg-4 col-sm-6">
<?php if($row['file_status'] == 'success' ) { ?>
<i class="fe-alert-circle"
data-toggle="tooltip"
data-placement="right"
title="<?php echo 'Invoice Amt: ' . (isset($row['invoice_amount']) ? $row['invoice_amount'] : '0.00' ) . ' Received Amt: ' . (isset($row['received_inv_amt']) ? $row['received_inv_amt'] : '0.00') ; ?>"
data-original-title="Tooltip on right">
</i>
<?php } ?>
</span>
</td>
<td><?php echo change_date_format($row['created_at'],'Y-m-d H:i:s','d M Y h:i a').' by <br>'.$row['first_name'] ?></td>
<td>
<?php if($row['file_status'] != 'failed'){?>
<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 btnEdit" data-id="<?= $row['id'];?>" data-exp-amt="<?= $row['exp_inv_amt'];?>" data-received-amt="<?= $row['received_inv_amt'];?>" onclick="showInvoiceStatusModal(event)">
<i class="mdi mdi-pencil mr-2 text-muted font-18 vertical-middle"></i>Invoice status
</a>
<a class="dropdown-item btnEdit" data-id="<?= $row['id'];?>"onclick="deleteStatement(<?= $row['id'];?>)">
<i class="mdi mdi-delete mr-2 text-muted font-18 vertical-middle"></i>Delete
</a>
</div>
</div>
<?php } ?>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</div>
</div>
</div><!-- end col -->
</div>
<!-- end table row -->
<div class="modal fade" id="file_upload" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="title">Upload Insurer Statement</h4>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body p-4">
<div class="">
<form role="form" class="parsley-examples" method="post" id="insurer_statement_upload_form" enctype="multipart/form-data" action="upload">
<div class="form-group">
<div class="form-group col-md-10">
<label for="insurer"> Insurer <spanclass="text-danger">*</spanclass=></label>
<select class="form-control" id="insurer" name="insurer" required>
<option value="" selected>Select Insurer</option>
<?php
if (isset($insurers) && count($insurers)) {
foreach ($insurers as $key => $value) {
echo "<option value=" . $value['insurer_id'].'-'.$value['id'] . ">" . $value['insurer_name'] .'-'. $value['branch_code'] . "</option>";
}
}
?>
</select>
</div>
<div class="form-group col-md-10">
<label for="statement_month">Statement month</label>
<input type="text" class="form-control" id="statement_month" name="statement_month" placeholder="" required readonly onchange="getStatementNo()">
</div>
<div class="form-group col-md-10">
<label for="statement_no">Statement no</label>
<select class="form-control" id="statement_no" name="statement_no" required >
<option value="" selected>Select statement no</option>
<?php
$stmt_no = [1,2,3,4,5,6,7];
if (isset($stmt_no) && count($stmt_no)) {
foreach ($stmt_no as $key => $value) {
echo "<option value=" . $value . ">" . $value . "</option>";
}
}
?>
</select>
</div>
<div class="form-group col-md-10" >
<label for="statment">Statement </label> <span><a href="downloadSampleInsurerStatement" id="download_sample_file" style="font-size: small;">Download sample file</a></span>
<input type="file" class="form-control" name="statement" required accept=" application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel,application/vnd.oasis.opendocument.spreadsheet">
</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>
</div>
<!-- Center modal content -->
<div class="modal fade" id="file-err-modal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myCenterModalLabel">File Rejected Reason</h4>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body">
</div>
</div>
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<!-- Invoice status content modal-->
<div class="modal fade" id="invoice_modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg" style="max-width:1000px;">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="title">Update Invoice Status</h4>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body p-4">
<div class="">
<form role="form" class="parsley-examples" method="post" id="invoiceForm" enctype="multipart/form-data" action="<?php echo base_url().'policy_tranction/statement/saveInvoicePaymentDetails'?>">
<div class="form-group">
<div class="row">
<div class="form-group col-md-4">
<label for="addon_policy">Invoice Status <span class="text-danger">*</span></label>
<select class="form-control" id="invoice_status" name="invoice_status" required>
<option value="" selected>Select Invoice Status</option>
<?php
if (isset($invoice_status_array) && count($invoice_status_array)) {
foreach ($invoice_status_array as $key => $value) {
echo "<option value='" . $key . "'>" . $value . "</option>";
}
}
?>
</select>
<input type="hidden" id="hidden_statement_id" name="hidden_statement_id">
</div>
<!-- <div class="form-group col-md-4">
<label for="addon_policy">Exp Amount</label>
<input type="text" class="form-control" id="modal_exp_amt" placeholder="" disabled>
</div> -->
</div>
<!-- Invoice Number and Invoice Date in same row -->
<!-- <div id="invoice_no_div_modal" style="display: none;"> -->
<div class="row" id="invoice_no_div_modal" style="display: none;">
<div class="form-group col-md-4">
<label for="invoice_no">Invoice Number<span id="base_danger" class="text-danger"></span></label>
<input type="text" class="form-control" id="invoice_no_modal" name="invoice_no" placeholder="Enter Invoice Number" required>
</div>
<div class="form-group col-md-4">
<label for="invoice_date">Invoice Date</label>
<input type="text" class="form-control" id="invoice_date_modal" name="invoice_date" value="<?php echo date('Y-m-d'); ?>" readonly required>
</div>
<div class="form-group col-md-4">
<label for="invoice_value_modal">Invoice value<span id="base_danger" class="text-danger"></span></label>
<input type="number" class="form-control" id="invoice_value_modal" name="invoice_value" placeholder="Enter Invoice Value" readonly>
</div>
</div>
<div class="row" id="invoice_no_div_modal2" style="display: none;">
<div class="form-group col-md-4">
<label for="gst_value_modal">GST %<span id="base_danger" class="text-danger"></span></label>
<input type="number" class="form-control" id="gst_per_modal" name="invoice_gst_per" placeholder="Enter GST %" required onchange="calcGSTValue()">
</div>
<div class="form-group col-md-4">
<label for="gst_value_modal">GST Value<span id="base_danger" class="text-danger"></span></label>
<input type="number" class="form-control" id="gst_value_modal" name="invoice_gst" placeholder="Enter Invoice Value" required readonly step="0.01">
</div>
<div class="form-group col-md-4">
<label for="invoice_no">Invoice Amount<span id="base_danger" class="text-danger"></span></label>
<input type="number" class="form-control" id="invoice_amount_no_modal" name="invoice_amount" placeholder="Enter Invoice Amt" required readonly step="0.01">
</div>
<!-- <div class="form-group col-md-3" id="modal_received_amt_div">
<label for="addon_policy">Total Received Amount</label>
<input type="text" class="form-control" id="modal_received_amt" placeholder="" disabled>
</div> -->
</div>
<div class="row" id="modal_received_amt_div">
<div class="form-group col-md-4" >
<label for="addon_policy">Total Received Amount</label>
<input type="number" class="form-control" id="modal_received_amt" placeholder="" disabled>
</div>
</div>
<!-- </div> -->
</div>
<!-- Payment Received Table -->
<div class="form-group col-md-12" style="display: none;" id="payment_table_div_modal" style="max-width: 800px;">
<button type="button" id="add_row_btn" class="btn btn-secondary float-right"><i class="fa fa-plus"></i></button>
<table class="table table-bordered" id="payment_table_modal">
<thead>
<tr>
<th style="display: none;">pk</th>
<th>Invoice value</th>
<th>GST</th>
<th>TDS</th>
<th>UTR Number</th>
<th>Date</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr>
<td style="display: none;"><input type="hidden" class="form-control" name="pk[]" placeholder="Enter Amount"></td>
<td><input type="number" class="form-control" name="received_amount[]" placeholder="Enter Amount" required onchange="checkInvAmont(event)"></td>
<td><input type="number" class="form-control" name="gst_amount[]" placeholder="Enter GST" required step="0.01" onchange="checkInvAmont(event)"></td>
<td><input type="number" class="form-control" name="tds[]" placeholder="Enter TDS" onchange="checkInvAmont(event)" required></td>
<td><input type="text" class="form-control" name="utr_no[]" placeholder="Enter UTR No" required></td>
<td><input type="text" class="form-control payment_date" name="payment_date[]" value="<?php echo date('d/m/Y'); ?>" placeholder="dd/mm/yyyy" required readonly></td>
<td><i class="fa fa-trash mr-2 font-18 vertical-middle text-danger remove-row" style="text-align: center;"></i></td>
</tr>
</tbody>
</table>
<!-- <button type="button" id="add_row_btn" class="btn btn-secondary float-right mt-2"><i class="fa fa-plus"></i></button> -->
</div>
<div class="form-group text-right m-b-0">
<!-- <button type="button" id="add_row_btn" class="btn btn-primary waves-effect waves-light mr-1">Add payment</button> -->
<button type="submit" class="btn btn-primary waves-effect waves-light mr-1" id="btnSubmit">Save</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<script>
document.addEventListener("DOMContentLoaded", function () {
const table = document.getElementById("tickets-table");
// Create custom dropdown
function createCustomDropdown(row) {
// Get the original dropdown items
const originalDropdown = row.querySelector('.dropdown-menu');
if (!originalDropdown) return null;
// Create new dropdown with proper background and spacing
const customDropdown = document.createElement('div');
customDropdown.className = 'custom-dropdown-menu';
// Copy inner content while maintaining icon alignment
customDropdown.innerHTML = originalDropdown.innerHTML;
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 action column
if (event.target.closest('td:last-child')) {
return;
}
// Hide any active dropdown
if (activeDropdown) {
activeDropdown.style.display = 'none';
}
// Get click position
const rect = event.target.getBoundingClientRect();
// Position the dropdown with some offset
customDropdown.style.display = 'block';
customDropdown.style.position = 'fixed';
customDropdown.style.left = `${rect.left}px`;
customDropdown.style.top = `${rect.bottom + 5}px`; // Add 5px gap
// Set as active dropdown
activeDropdown = customDropdown;
event.stopPropagation();
});
// Preserve click handlers and add auto-close
customDropdown.querySelectorAll('.dropdown-item').forEach(item => {
item.addEventListener('click', function(e) {
const onclickAttr = this.getAttribute('onclick');
if (onclickAttr) {
eval(onclickAttr);
}
const href = this.getAttribute('href');
if (href && href !== '#') {
window.location.href = href;
}
// Close the dropdown after handling the click
if (activeDropdown) {
activeDropdown.style.display = 'none';
activeDropdown = null;
}
e.stopPropagation();
});
});
});
// Close dropdown when clicking outside
document.addEventListener("click", function() {
if (activeDropdown) {
activeDropdown.style.display = 'none';
activeDropdown = null;
}
});
});
</script>
<script>
document.getElementById('invoice_status').addEventListener('change', function () {
const invoiceStatus = this.value;
console.log(invoiceStatus);
const invoiceNoDiv = document.getElementById('invoice_no_div_modal');
const invoiceNoDiv2 = document.getElementById('invoice_no_div_modal2');
// const invoiceDateDiv = document.getElementById('invoice_date_div_modal');
const paymentTableDiv = document.getElementById('payment_table_div_modal');
const totalReceivedAmtDiv = document.getElementById('modal_received_amt_div');
// Hide everything initially
invoiceNoDiv.style.display = 'none';
invoiceNoDiv2.style.display = 'none';
// invoiceDateDiv.style.display = 'none';
paymentTableDiv.style.display = 'none';
totalReceivedAmtDiv.style.display = 'none';
// Show fields based on selected status
if (invoiceStatus === 'generated' || invoiceStatus === 'sent') {
invoiceNoDiv.style.display = 'flex';
invoiceNoDiv2.style.display = 'flex';
totalReceivedAmtDiv.style.display = 'none';
switchRequired('invoice_no_modal',true);
switchRequired('invoice_date_modal',true);
switchRequired('invoice_amount_no_modal',true);
switchRequired('received_amount',false,'name');
switchRequired('tds',false,'name');
switchRequired('gst_amount',false,'name');
switchRequired('utr_no',false,'name');
switchRequired('payment_date',false,'name');
switchRequired('pk',false,'name');
// invoiceDateDiv.style.display = 'block';
} else if (invoiceStatus === 'payment_received') {
invoiceNoDiv.style.display = 'flex';
invoiceNoDiv2.style.display = 'flex';
paymentTableDiv.style.display = 'block';
totalReceivedAmtDiv.style.display = 'block';
switchRequired('invoice_no_modal',true);
switchRequired('invoice_date_modal',true);
switchRequired('invoice_amount_no_modal',true);
switchRequired('received_amount',true,'name');
switchRequired('utr_no',true,'name');
switchRequired('tds',true,'name');
switchRequired('gst_amount',true,'name');
switchRequired('payment_date',true,'name');
switchRequired('pk',true,'name');
}else if(invoiceStatus === 'pending')
{
invoiceNoDiv.style.display = 'none';
invoiceNoDiv2.style.display = 'none';
paymentTableDiv.style.display = 'none';
totalReceivedAmtDiv.style.display = 'none';
// switchRequired('modal_received_amt_div',false);
switchRequired('invoice_no_modal',false);
switchRequired('invoice_date_modal',false);
switchRequired('invoice_amount_no_modal',false);
switchRequired('received_amount',false,'name');
switchRequired('utr_no',false,'name');
switchRequired('payment_date',false,'name');
switchRequired('pk',false,'name');
switchRequired('tds',false,'name');
switchRequired('gst_amount',false,'name');
}
calcGSTValue();
});
$(document).ready(function () {
$('#file-err-modal').on('show.bs.modal', function(event) {
// console.log(event.relatedTarget);
var myVal = $(event.relatedTarget).data('err');
// console.log(myVal);
var loader =
'<div style="text-align: center;"><img src="<?php echo base_url()?>public/assets/images/simple_loader.gif" height="50px" width="50px" ></div>';
$('#file-err-modal').find(".modal-body").html(loader);
var model_data = fetchFileError(myVal);
// console.log('data received.');
// console.log(model_data);
});
$('#invoiceForm').on('submit', function (e) {
e.preventDefault(); // Prevent default form submission
var res = checkInvAmont();
if(!res)
{
return false;
}
var form = document.getElementById('invoiceForm');
// alert(form.checkValidity());
// alert($('#invoice_date_modal').val());
if((!form.checkValidity()))
{
// console.log('error2');
return false;
}
if($('#invoice_date_modal').val().trim() === '' && $('#invoice_status').val() != 'pending')
{
// console.log('error1');
return false;
}
// console.log('final');
// return false;
// Serialize form data to array and then convert to JSON
var formData = new FormData(form);
var formDataJSON = {};
// Iterate over FormData entries
formData.forEach(function(value, key) {
// Check if the key ends with '[]' indicating an array-like input
if (key.endsWith('[]')) {
// Remove '[]' from the key and store it as an array in formDataJSON
var arrayKey = key.slice(0, -2);
if (!formDataJSON[arrayKey]) {
formDataJSON[arrayKey] = [];
}
formDataJSON[arrayKey].push(value); // Push the value into the array
} else {
formDataJSON[key] = value; // Standard single-value field
}
});
// Convert the JSON object to a string
var jsonData = JSON.stringify(formDataJSON);
console.log(jsonData);
$('.loader').fadeIn();
$('.loader-mask').fadeIn();
// Send the JSON data to the backend using AJAX
$.ajax({
url: 'saveInvoicePaymentDetails', // Replace with your backend URL
type: 'POST',
contentType: 'application/json',
data: jsonData,
success: function (response) {
console.log(response);
// Close the modal
$('.close').click()
// Reset the form data
// $('#invoiceForm')[0].reset();
alert('Invoice updated successfully!');
location.reload();
},
error: function (xhr, status, error) {
// Handle any errors
console.error('Form submission failed:', error);
alert('An error occurred while updating the invoice.');
}
});
// location.reload();
$('.loader').fadeOut();
$('.loader-mask').delay(10).fadeOut('slow');
});
});
// Add/Delete rows in the payment table
document.getElementById('add_row_btn').addEventListener('click', function () {
const tableBody = document.querySelector('#payment_table_modal tbody');
const newRow = document.createElement('tr');
newRow.innerHTML = `
<td style="display: none;"><input type="hidden" class="form-control" name="pk[]" placeholder="Enter Amount"></td>
<td><input type="number" class="form-control" name="received_amount[]" placeholder="Enter Amount" onchange="checkInvAmont(event)" required></td>
<td><input type="number" class="form-control" name="gst_amount[]" placeholder="Enter GST" onchange="checkInvAmont(event)" required step="0.01"></td>
<td><input type="number" class="form-control" name="tds[]" placeholder="Enter TDS" onchange="checkInvAmont(event)" required></td>
<td><input type="text" class="form-control" name="utr_no[]" placeholder="Enter UTR No" required></td>
<td><input type="text" class="form-control payment_date" value="<?php echo date('d/m/Y'); ?>" name="payment_date[]" placeholder="dd/mm/yyyy" required readonly></td>
<td><i class="fa fa-trash mr-2 font-18 vertical-middle text-danger remove-row" style="text-align: center;"></i></td>
`;
tableBody.appendChild(newRow);
$('.payment_date').datepicker({
format: 'dd/mm/yyyy',
autoclose: true
});
});
// Remove row
document.getElementById('payment_table_modal').addEventListener('click', function (e) {
if (e.target && e.target.classList.contains('remove-row')) {
if (confirm("Do you want to delete this entry?")) {
var row = e.target.closest('tr');
var pk = row.querySelector('input[name="pk[]"]').value;
if (pk === "") {
// If pk is empty, remove the row
row.remove();
} else {
// If pk is non-empty, send AJAX request to remove it from the backend
$.ajax({
url: 'deletePaymentEntry/'+pk, // Your backend URL here
type: 'GET',
// data: { pk: pk }, // Send the pk value to delete on server-side
success: function (response) {
// On success, remove the row
console.log(response);
if (response.dataStatus) {
row.remove();
alert('Payment deleted successfully.');
} else {
alert('Failed to delete the entry.');
}
},
error: function () {
alert('Error occurred while deleting the entry.');
}
});
}
}
}
});
</script>
<script>
function showFileUploadModal(input)
{
var myModal = new bootstrap.Modal(document.getElementById('file_upload'));
myModal.show();
// $(input).val('');
}
function formatDate(date) {
var day = ("0" + date.getDate()).slice(-2);
var month = ("0" + (date.getMonth() + 1)).slice(-2);
var year = date.getFullYear();
return day + "/" + month + "/" + year;
}
function formatDateToDMY(dateStr) {
// Split the date string by the hyphen
var parts = dateStr.split('-');
return parts[2] + '/' + parts[1] + '/' + parts[0]; // Rearrange to DD-MM-YYYY
}
function showInvoiceStatusModal(event)
{
console.log('############ showInvoiceStatusModal function called ##################');
var modal_received_amt_div = document.getElementById('modal_received_amt_div');
modal_received_amt_div.style.display = 'none';
// alert();
// console.log(event.target.data)
var dataId = event.target.getAttribute('data-id');
var dataExpAmt = event.target.getAttribute('data-exp-amt');
var dataReceivedAmt = event.target.getAttribute('data-received-amt');
// Set the value to a hidden input field in the modal
document.getElementById('hidden_statement_id').value = dataId;
// document.getElementById('modal_exp_amt').value = dataExpAmt;
document.getElementById('modal_received_amt').value = dataReceivedAmt;
$('.loader').fadeIn();
$('.loader-mask').fadeIn();
// AJAX call to get the invoice details based on data-id
$.ajax({
url: 'getPaymentDetails/'+ dataId, // Replace with your backend URL
method: 'get',
// data: { id: dataId },
// dataType: 'json',
success: function(response) {
$('.loader').fadeOut();
$('.loader-mask').delay(10).fadeOut('slow');
console.log(response);
// Assuming response contains the necessary data
if (response.dataStatus === true && response.code === 200) {
// Populate modal fields
if(response.data.invoice_status !== null)
{
var inv_status_element = document.getElementById('invoice_status');
inv_status_element.value = response.data.invoice_status;
var event = new Event('change');
inv_status_element.dispatchEvent(event);
}
document.getElementById('invoice_no_modal').value = response.data.invoice_no;
document.getElementById('invoice_date_modal').value = response.data.invoice_date === '' ? <?php echo date('d-m-Y')?> : response.data.invoice_date;
document.getElementById('invoice_amount_no_modal').value = response.data.invoice_amount;
document.getElementById('invoice_value_modal').value = response.data.invoice_value;
document.getElementById('gst_per_modal').value = response.data.gst_per;
document.getElementById('gst_value_modal').value = response.data.gst_value;
console.log('response.data.gst_value - ' + response.data.gst_value);
if(response.data.gst_value == 0 || response.data.gst_value == '' || response.data.gst_value == null)
{
calcGSTValue();
}
if (!$('#invoice_date_modal').val()) {
// alert('nope');
// Set today's date as the default date
$('#invoice_date_modal').datepicker('setDate', new Date());
}
// Clear existing rows in the payment table
var paymentTableBody = document.querySelector('#payment_table_modal tbody');
console.log('response.data.payments.length', response.data.payments.length)
// Populate payment table rows
if(response.data.payments.length)
{
paymentTableBody.innerHTML = '';
response.data.payments.forEach(function(payment) {
var row = paymentTableBody.insertRow();
row.innerHTML = `
<td style="display: none;"><input type="hidden" class="form-control" name="pk[]" value="${payment.id}"></td>
<td><input type="number" class="form-control" name="received_amount[]" placeholder="Enter Amount" value="${payment.inv_amt}" onchange="checkInvAmont(event)" required></td>
<td><input type="number" class="form-control" name="gst_amount[]" placeholder="Enter Amount" value="${payment.gst}" onchange="checkInvAmont(event)" required step="0.01"></td>
<td><input type="number" class="form-control" name="tds[]" placeholder="Enter Amount" value="${payment.tds}" onchange="checkInvAmont(event)" required></td>
<td><input type="text" class="form-control" name="utr_no[]" placeholder="Enter UTR No" value="${payment.utr_no}" required></td>
<td><input type="text" class="form-control payment_date" name="payment_date[]" value="${formatDateToDMY(payment.received_date)}" required readonly></td>
<td><i class="fa fa-trash mr-2 font-18 vertical-middle text-danger remove-row" style="text-align: center;"></i></td>
`;
});
}
$('.payment_date').datepicker({ format: 'dd/mm/yyyy',autoclose: true});
// Show the modal
var myModal = new bootstrap.Modal(document.getElementById('invoice_modal'));
myModal.show();
} else {
// Handle error if the response is not successful
console.error('Failed to fetch data:', response);
alert("Something went wrong! Couldn't get data");
}
},
error: function(xhr, status, error) {
// Handle AJAX errors
console.error('AJAX Error:', status, error);
alert("Something went wrong! Couldn't reach app");
}
});
$('.loader').fadeOut();
$('.loader-mask').delay(10).fadeOut('slow');
// var myModal = new bootstrap.Modal(document.getElementById('invoice_modal'));
// myModal.show();
// $(input).val('');
}
$(document).ready(function(){
// var rollover_date = flatpickr("#statement_month", {
// dateFormat: "Y-M",
// allowInput: true
// });
$('#statement_month').datepicker({
format: 'yyyy-M',
viewMode: 'months',
minViewMode: 'months',
autoclose: true
});
$('.payment_date').datepicker({
format: 'dd/mm/yyyy',
autoclose: true
});
// Get today's date
var today = new Date();
// Calculate the minimum date (60 days before today)
var minDate = new Date();
minDate.setDate(today.getDate() - 180);
// Calculate the maximum date (60 days after today)
var maxDate = new Date();
maxDate.setDate(today.getDate() + 180);
$('#invoice_date_modal').datepicker({
format: 'dd/mm/yyyy',
autoclose: true,
startDate: minDate,
endDate: maxDate
});
// var invoice_date_modal = flatpickr("#invoice_date_modal", {
// dateFormat: "d-m-Y",
// allowInput: true
// });
});
$('#insurer_statement_upload_form').submit(function(event) {
event.preventDefault();
var isValid = $('#insurer_statement_upload_form').parsley().validate();
if (!isValid) {
console.log('Form is Empty', 'Warning');
// alert('choose all fileds');
return;
}
$('#btnSubmit').prop('disabled', true).text('Submitting...');
// Create FormData object
var formData = new FormData($(this)[0]);
for (var pair of formData.entries()) {
console.log(pair[0] + ', ' + pair[1]);
}
$('.loader').fadeIn();
$('.loader-mask').fadeIn();
$.ajax({
url: $(this).attr("action"),
type: "POST",
data: formData,
processData: false, // Prevent jQuery from automatically processing the data
contentType: false, // Let jQuery handle the content type
headers: {
// "Content-Type":"multipart/form-data",
"X-Requested-With": "XMLHttpRequest"
},
success: function(response) {
console.log(response);
$('#insurer_statement_upload_form')[0].reset();
if (response.code === 200 && response.dataStatus === true && response
.data !== "") {
toastr.success(
'File upload successs',
'Success');
$('.close').click();
window.location.reload(true);
} else if (response.code === 404 && response.dataStatus === false) {
console.error('no data found', response);
// alert(response.message);
toastr.error(response.message, 'Failed');
window.location.reload(true);
} else {
console.error('Something went wrong!');
// alert('Something went wrong! Try later');
toastr.error('Something went wrong! Try later', 'Error');
window.location.reload(true);
}
$('.close').click()
$('.loader').fadeOut();
$('.loader-mask').delay(10).fadeOut('slow');
$('#btnSubmit').prop('disabled', false).text('Submit');
},
error: function(xhr, status, error) {
// Request failed, handle error
console.error("Request failed:", status, error);
toastr.error('Something went wrong! Try later', 'Error');
$('#uploadForm')[0].reset();
$('.close').click()
$('.loader').fadeOut();
$('.loader-mask').delay(10).fadeOut('slow');
window.location.reload(true);
}
});
});
function fetchFileError(file_id) {
$('#loader').show();
var apiURL = 'getFileErr/' + file_id;
// console.log('fetchFileError');
// console.log(apiURL);
$.ajax({
url: apiURL,
method: 'GET',
headers: {
"X-Requested-With": "XMLHttpRequest"
},
success: function(response) {
console.log(response);
$(this).find(".modal-body").html("");
if (response.code === 200 && response.dataStatus === true && response.data !== "") {
try {
// console.log((JSON.parse(response.data)));
var file_error_data = (JSON.parse(response.data));
var file_error_html = "";
if (file_error_data['error_code'] == 1) {
file_error_html += 'The following row no(s) from excel are <span style="font-weight:bold">not found with policy transactions / duplicates.</span>';
file_error_html += ' : ' + '<span style="font-weight:bolder">' + file_error_data['error_data'].join(',') + '</span>';
}
// console.log(file_error_html);
$('#file-err-modal').find(".modal-body").html(file_error_html);
return file_error_html;
} 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);
}
});
$('#loader').hide();
}
function checkInvAmont(event = null) {
var total = 0;
var receivedAmounts = document.querySelectorAll('input[name="received_amount[]"]');
var receivedGST = document.querySelectorAll('input[name="gst_amount[]"]');
var tdsAmounts = document.querySelectorAll('input[name="tds[]"]');
// console.log();
receivedAmounts.forEach(function(el, index) {
// Get the received amount
let receivedVal = parseFloat(el.value) || 0;
// Get the corresponding tds amount (paired with the received amount)
let gstVal = parseFloat(receivedGST[index].value) || 0;
let tdsVal = parseFloat(tdsAmounts[index].value) || 0;
// Add received amount and tds amount
// console.log();
total += (receivedVal + tdsVal + gstVal);
});
// console.log(total);
// Get the expected invoice amount
var exp_amt = parseFloat(document.getElementById('invoice_amount_no_modal').value) || 0;
// Check if the total exceeds the expected amount
if (exp_amt < total) {
alert('Exceeds Invoice amount...Plz adjust numbers');
if(event != null)
{
event.target.value = '';
}
return false; // Reset the value of the element that triggered the event
}
return true;
}
function switchRequired(elementId, isRequired, type = 'id') {
// console.log('switchRequired: ' + elementId+' - '+' - '+ type);
if(type == 'id')//id attribute
{
let element = document.getElementById(elementId);
if (isRequired) {
element.setAttribute('required', 'required');
} else {
element.removeAttribute('required');
}
}
else //name attribute
{
var name_attribute = elementId+'[]';
// Select all elements with the name 'invoice_amt[]'
var elements = document.getElementsByName(name_attribute);
// Loop through the elements and set or remove the 'required' attribute
elements.forEach(function(element) {
if (isRequired) {
element.setAttribute('required', 'required'); // Make required
} else {
element.removeAttribute('required'); // Remove required
}
});
}
}
function getStatementNo()
{
var insurer_id = $('#insurer').val();
var statement_month = $('#statement_month').val();
console.log(insurer_id+' / '+statement_month);
if(insurer_id == "")
{
alert('Choose insurer...!');
$('#statement_month').val('');
}
$('.loader').fadeIn();
$('.loader-mask').fadeIn();
var apiURL = 'getInsurerStatementMonth?insurer_id=' +insurer_id+'&month='+statement_month ;
$.ajax({
url: apiURL,
type: "GET",
headers: {
// "Content-Type":"multipart/form-data",
"X-Requested-With": "XMLHttpRequest"
},
success: function(response) {
console.log(response);
// $('#insurer_statement_upload_form')[0].reset();
if (response.code === 200 && response.dataStatus === true && response
.data !== "") {
disableStatementNo(response.data)
$('.loader').fadeOut();
$('.loader-mask').delay(10).fadeOut('slow');
} else if (response.code === 404 && response.dataStatus === false) {
console.error('no data found', response);
// alert(response.message);
// toastr.error(response.message, 'Failed');
// window.location.reload(true);
$('.loader').fadeOut();
$('.loader-mask').delay(10).fadeOut('slow');
} else {
console.error('Something went wrong!');
// alert('Something went wrong! Try later');
toastr.error('Something went wrong! Try later', 'Error');
// window.location.reload(true);
$('.loader').fadeOut();
$('.loader-mask').delay(10).fadeOut('slow');
}
},
error: function(xhr, status, error) {
// Request failed, handle error
console.error("Request failed:", status, error);
toastr.error('Something went wrong! Try later', 'Error');
// $('#uploadForm')[0].reset();
// window.location.reload(true);
$('.loader').fadeOut();
$('.loader-mask').delay(10).fadeOut('slow');
}
});
// $('.loader').fadeOut();
// $('.loader-mask').delay(10).fadeOut('slow');
}
function calcGSTValue()
{
// alert('calcGSTValue');
console.log('calcGSTValue called');
var inv_status_element = document.getElementById('invoice_status');
if(inv_status_element.value == 'generated' || inv_status_element.value == 'send' || inv_status_element.value == 'payment_received')
{
var gst_per = document.getElementById('gst_per_modal').value;
console.log('gst_per - ' + gst_per);
var invoice_value_dom_obj = document.getElementById('invoice_value_modal');
var invoice_value = invoice_value_dom_obj.value;
console.log('invoice_value - ' + invoice_value);
var gst_value_dom_obj = document.getElementById('gst_value_modal');
var gst_value = gst_value_dom_obj.value;
console.log('gst_value - ' + gst_value);
var invoice_amount_dom_obj = document.getElementById('invoice_amount_no_modal');
// var invoice_amount = invoice_amount_dom_obj.value();
gst_value_dom_obj.value = Math.round((parseFloat(gst_per) / 100 ) * invoice_value);
// gst_value_dom_obj.value = ((parseFloat(gst_per) / 100 ) * invoice_value);
invoice_amount_dom_obj.value = parseFloat(invoice_value_dom_obj.value) + parseFloat(gst_value_dom_obj.value);
if(inv_status_element.value == 'payment_received')
{
checkInvAmont();
}
}
}
function disableStatementNo(arr)
{
// JavaScript array with values to disable
// const disableValues = arr;
const disableIds = arr.map(item => item.stmt_sno);
console.log(disableIds);
// Get the select element
const selectElement = document.getElementById("statement_no");
// Variable to track if the first enabled option is selected
let firstEnabledOptionSelected = false;
// Iterate over the options in the select element
Array.from(selectElement.options).forEach(option => {
// If the option value is in the disableIds array, disable it
console.log(option.value);
option.disabled = false;
option.style.backgroundColor = "";
if (disableIds.includes((option.value))) {
option.disabled = true;
option.style.backgroundColor = "lightgray";
}
else if (!firstEnabledOptionSelected && option.value !== "") {
// Automatically select the first enabled option
option.selected = true;
firstEnabledOptionSelected = true;
}
});
}
function deleteStatement(id)
{
//alert(id);
Swal.fire({
title: "Do you want to delete statement & it's invoice data if any?",
showCancelButton: true,
confirmButtonText: "Delete",
confirmButtonColor: "#ff3333",
}).then((result) => {
console.log(result);
if (result.isConfirmed) {
$('.loader').fadeIn();
$('.loader-mask').fadeIn();
var apiURL = 'deleteStatement/' + id;
// console.log('Truncate API URL : ', apiURL);
$.ajax({
url: apiURL,
method: 'GET',
headers: {
"X-Requested-With": "XMLHttpRequest"
},
success: function(response) {
// console.log('Truncate Response', response)
$('.loader').fadeOut();
$('.loader-mask').delay(10).fadeOut('slow');
if (response.code === 200 && response.dataStatus === true) {
Swal.fire({
title: "Deleted!",
icon: "success"
});
window.location.reload(true);
} else {
Swal.fire({
title: "Failed!",
text: 'Something went wrong! Try later',
icon: "error"
});
window.location.reload(true);
}
},
error: function(xhr, status, error) {
console.error(xhr.responseText);
console.error(status, error);
$('.loader').fadeOut();
$('.loader-mask').delay(10).fadeOut('slow');
console.error('Error fetching data from API:', error);
toastr.error('Something went wrong! Try later', 'Error');
window.location.reload(true);
}
});
}
});
}
</script>