Files
wms-app/app/finance/receipt_billing.php
T

380 lines
13 KiB
PHP

<?php
require_once __DIR__ . '/../session.php';
require '../config.php';
require '../include_header.php';
?>
<body>
<?php require '../include_topbar.php'; ?>
<?php require '../include_sidebar_ac.php'; ?>
<main id="content" class="content py-15">
<div class="container-fluid">
<div class="row mb-6">
<div class="col-12">
<div class="d-flex justify-content-between align-items-center">
<div>
<h1 class="fs-3 mb-1">Receipt Billings</h1>
<p class="mb-0 text-muted">Customer collection bills from invoices and credit notes</p>
</div>
<button class="btn btn-primary" onclick="show_billing_form()">
<i class="ti ti-plus me-1"></i>New Receipt Billing
</button>
</div>
</div>
</div>
<div class="row g-5 d-none" id="billing_form">
<div class="col-lg-8">
<div class="card mb-5">
<div class="card-body p-5">
<h2 class="fs-5 mb-4">Billing Information</h2>
<div class="row gx-5">
<div class="mb-3 col-lg-8">
<label class="form-label">Customer</label>
<input type="text" id="contact" class="form-control contact_search"
placeholder="Search customer..." autocomplete="off">
<input type="hidden" id="contact_id">
</div>
<div class="mb-3 col-lg-4">
<label class="form-label">Billing Date</label>
<input type="text" id="billing_date" class="form-control" placeholder="DD/MM/YYYY">
</div>
<div class="mb-3 col-12">
<label class="form-label">Notes</label>
<textarea id="notes" class="form-control" rows="2"></textarea>
</div>
</div>
<button class="btn btn-outline-secondary" onclick="load_billable_documents()">
<i class="ti ti-search me-1"></i>Load Billable Documents
</button>
</div>
</div>
<div class="card">
<div class="card-body p-5">
<h2 class="fs-5 mb-4">Documents</h2>
<div class="table-responsive">
<table class="table mb-0" id="document_table">
<thead class="table-light">
<tr>
<th>Document</th>
<th>Type</th>
<th>Billable</th>
<th style="width:150px;">Include</th>
</tr>
</thead>
<tbody id="document_tbody">
<tr><td colspan="4" class="text-center py-5 text-muted">Select a customer and load billable documents.</td></tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
<div class="col-lg-4">
<div class="card mb-5">
<div class="card-body p-4">
<h2 class="fs-5 mb-3">Summary</h2>
<div class="d-flex justify-content-between mb-2">
<span class="text-muted">Invoices</span>
<span id="summary_invoice">0.00</span>
</div>
<div class="d-flex justify-content-between mb-2">
<span class="text-muted">Credit Notes</span>
<span id="summary_cn" class="text-danger">0.00</span>
</div>
<hr>
<div class="d-flex justify-content-between fw-bold fs-5">
<span>Amount Due</span>
<span id="summary_due">0.00</span>
</div>
</div>
</div>
<div class="card">
<div class="card-body p-4 d-flex flex-column gap-2">
<button class="btn btn-primary w-100" onclick="create_billing()">
<i class="ti ti-check me-1"></i>Create Billing
</button>
<button class="btn btn-light w-100" onclick="hide_billing_form()">Cancel</button>
</div>
</div>
</div>
</div>
<div class="row mt-5" id="billing_list_section">
<div class="col-12">
<div class="card">
<div class="card-body p-5">
<div class="table-responsive">
<table class="table table-hover mb-0 table-centered" id="billing_list">
<thead class="table-primary border-light">
<tr>
<th>Billing #</th>
<th>Date</th>
<th>Customer</th>
<th>Amount Due</th>
<th>Received</th>
<th>Balance</th>
<th>Status</th>
<th>Action</th>
</tr>
</thead>
<tbody></tbody>
<tfoot></tfoot>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</main>
<?php require '../include_ending.php'; ?>
<script>
const can_delete = ['admin', 'owner'].includes(user_role);
var billable_documents = [];
function show_billing_form() {
$('#billing_form').removeClass('d-none');
$('#billing_list_section').addClass('d-none');
$('#billing_date').val(flatpickr.formatDate(new Date(), 'd/m/Y'));
}
function hide_billing_form() {
$('#billing_form').addClass('d-none');
$('#billing_list_section').removeClass('d-none');
}
function status_badge(status) {
const map = {
'1': '<span class="badge bg-info text-white">Open</span>',
'2': '<span class="badge bg-success">Settled</span>',
'3': '<span class="badge bg-warning text-dark">Partial</span>',
'4': '<span class="badge bg-light text-dark">Void</span>',
};
return map[String(status)] || '—';
}
function doc_type_label(doc_type) {
return doc_type === 'credit_note'
? '<span class="badge bg-warning text-dark">Credit Note</span>'
: '<span class="badge bg-primary">Invoice</span>';
}
function load_billings() {
return ajax_request({
url: '<?php echo $server_url?>finance/api/engine/manage_receipt_billing.php',
autoPrepare: true,
checkRequired: 0,
action: 'read',
onSuccess: function(res) {
var data = res.output || [];
alasql('DROP TABLE IF EXISTS billing_list');
alasql('CREATE TABLE billing_list');
alasql.tables.billing_list.data = data;
$('table#billing_list tfoot').html(generate_pagination('billing_list', data.length));
change_page_billing_list(1);
}
});
}
function change_page_billing_list(page_num) {
var offset = (page_num - 1) * prop_limit;
var rows = alasql(`SELECT * FROM billing_list LIMIT ${prop_limit} OFFSET ${offset}`);
var body = '';
if (!rows.length) {
$('table#billing_list tbody').html('<tr><td colspan="8" class="text-center py-5 text-muted">No receipt billings found.</td></tr>');
return;
}
$.each(rows, function(i, r) {
body += `<tr>
<td class="py-3 fw-semibold">${escape_html(r.billing_number || '')}</td>
<td class="py-3">${r.billing_date ? format_date(r.billing_date) : '<span class="text-muted">—</span>'}</td>
<td class="py-3">${escape_html(r.contact_name || '—')}</td>
<td class="py-3 fw-semibold">${format_number(r.amount, 2)}</td>
<td class="py-3">${format_number(r.received_amount, 2)}</td>
<td class="py-3">${format_number(r.balance_amount, 2)}</td>
<td class="py-3">${status_badge(r.status)}</td>
<td class="py-3">
<a href="<?php echo $server_url?>finance/manage_receipt_billing.php?id=${r.id}" title="View receipt billing">
<i class="ti ti-eye fs-5"></i>
</a>
${can_delete ? `<a href="javascript:void(0);" class="link-danger ms-2" title="Delete" onclick="delete_billing(${r.id})"><i class="ti ti-trash fs-5"></i></a>` : ''}
</td>
</tr>`;
});
$('table#billing_list tbody').html(body);
}
function load_billable_documents() {
var contact_id = parseInt($('#contact_id').val() || $('#contact').attr('data-id')) || 0;
ajax_request({
url: '<?php echo $server_url?>finance/api/engine/manage_receipt_billing.php',
autoPrepare: true,
checkRequired: 0,
action: 'billable_documents',
data: { contact_id: contact_id },
onSuccess: function(res) {
billable_documents = res.output || [];
render_billable_documents();
}
});
}
function render_billable_documents() {
var body = '';
if (!billable_documents.length) {
$('#document_tbody').html('<tr><td colspan="4" class="text-center py-5 text-muted">No issued unbilled invoices or credit notes for this contact.</td></tr>');
recalc_billing();
return;
}
$.each(billable_documents, function(i, d) {
var balance = parseFloat(d.balance_amount || 0);
var is_cn = d.doc_type === 'credit_note';
var display_balance = is_cn ? -balance : balance;
body += `<tr data-doc-id="${d.id}" data-doc-type="${d.doc_type}" data-balance="${balance}">
<td>
<div class="fw-semibold">${escape_html(d.invoice_number || '')}</div>
<div class="small text-muted">${d.order_number ? escape_html(d.order_number) : ''}</div>
</td>
<td>${doc_type_label(d.doc_type)}</td>
<td class="fw-semibold ${is_cn ? 'text-danger' : ''}">${format_number(display_balance, 2)}</td>
<td>
<input type="number" class="form-control form-control-sm billing_amount"
${is_cn ? `min="${-balance}" max="0" value="${-balance}"` : `min="0" max="${balance}" value="${balance}"`}
step="any" oninput="recalc_billing()">
</td>
</tr>`;
});
$('#document_tbody').html(body);
recalc_billing();
}
function recalc_billing() {
var invoice_total = 0;
var cn_total = 0;
$('#document_tbody tr[data-doc-id]').each(function() {
var type = $(this).data('doc-type');
var amount = Math.abs(parseFloat($(this).find('.billing_amount').val()) || 0);
if (type === 'credit_note') cn_total += amount;
else invoice_total += amount;
});
$('#summary_invoice').text(format_number(invoice_total, 2));
$('#summary_cn').text('-' + format_number(cn_total, 2));
$('#summary_due').text(format_number(invoice_total - cn_total, 2));
}
function collect_allocations() {
var allocations = [];
$('#document_tbody tr[data-doc-id]').each(function() {
var amount = Math.abs(parseFloat($(this).find('.billing_amount').val()) || 0);
var balance = parseFloat($(this).data('balance')) || 0;
if (amount <= 0) return;
if (amount - balance > 0.0001) {
throw new Error('Billing amount exceeds document balance.');
}
allocations.push({
invoice_id: parseInt($(this).data('doc-id')),
amount: amount,
});
});
return allocations;
}
function get_billing_net_amount() {
var invoice_total = 0;
var cn_total = 0;
$('#document_tbody tr[data-doc-id]').each(function() {
var amount = Math.abs(parseFloat($(this).find('.billing_amount').val()) || 0);
if ($(this).data('doc-type') === 'credit_note') cn_total += amount;
else invoice_total += amount;
});
return invoice_total - cn_total;
}
function create_billing() {
var allocations;
try {
allocations = collect_allocations();
} catch(e) {
bootbox.alert(e.message);
return;
}
if (!allocations.length) {
bootbox.alert('Please include at least one invoice or credit note.');
return;
}
if (get_billing_net_amount() <= 0.0001) {
bootbox.alert('Receipt billing amount must be greater than zero.');
return;
}
ajax_request({
url: '<?php echo $server_url?>finance/api/engine/manage_receipt_billing.php',
autoPrepare: true,
checkRequired: 0,
action: 'create',
data: {
contact_id: $('#contact_id').val() || $('#contact').attr('data-id') || 0,
billing_date: to_iso_date($('#billing_date').val()),
notes: $('#notes').val(),
allocations: JSON.stringify(allocations),
},
onSuccess: function(res) {
window.location.href = '<?php echo $server_url?>finance/manage_receipt_billing.php?id=' + res.new_id;
}
});
}
$(document).on('contact:selected', '#contact', function(e, contact) {
$('#contact_id').val(contact.id);
$('#contact').attr('data-id', contact.id);
});
$(document).on('input', '#contact', function() {
$('#contact_id').val('');
$(this).removeAttr('data-id');
});
function delete_billing(id) {
bootbox.confirm({
message: 'Delete this billing? All linked receipts must be deleted first.',
buttons: { confirm: { label: 'Delete', className: 'btn-danger' }, cancel: { label: 'Back', className: 'btn-secondary' } },
callback: function(result) {
if (!result) return;
ajax_request({
url: '<?php echo $server_url?>finance/api/engine/delete_receipt_billing.php',
autoPrepare: false,
checkRequired: 0,
action: 'delete',
data: { id: id },
onSuccess: function() { load_billings(); }
});
}
});
}
$(function() {
flatpickr('#billing_date', { dateFormat: 'd/m/Y', allowInput: true });
load_billings();
});
</script>
</body>
</html>