Files
itflow/js/billing_items.js

234 lines
9.4 KiB
JavaScript

/*
* The lines on an invoice, quote or recurring invoice page
* (includes/billing_paper.php):
*
* - the add-a-line row: type a product's name or code and pick it to fill
* in its description, price and tax; the amount it comes to shows as you
* type; after adding, the page comes back here ready for the next
* - drag a line by its handle to move it - saved as it drops
* - the line just edited is picked out when the page comes back
*
* Call once the page has loaded:
*
* itflowBillingItems({ products: [...], csrf: '...', currency: 'USD', locale: 'en-US' });
*
* products is what getProductsForAutocomplete() gives.
*
* itflowBillingLineForm(form, options) does the product pick and the amount
* for any other line form - the Edit Line window uses it.
*/
function itflowBillingMoney(amount, currency, locale) {
try {
return new Intl.NumberFormat(locale || undefined, { style: 'currency', currency: currency || 'USD' }).format(amount);
} catch (e) {
return (Math.round(amount * 100) / 100).toFixed(2);
}
}
/* A number from a form field - "1,250.50", "$99" - or NaN */
function itflowBillingNumber(value) {
var text = String(value == null ? '' : value).replace(/[\s,$€£]/g, '');
return text === '' ? NaN : Number(text);
}
function itflowBillingLineForm(root, options) {
if (!root) {
return;
}
var opts = options || {};
var name = root.querySelector('[data-line-name]');
var description = root.querySelector('[data-line-description]');
var qty = root.querySelector('[data-line-qty]');
var price = root.querySelector('[data-line-price]');
var tax = root.querySelector('[data-line-tax]');
var preview = root.querySelector('[data-line-preview]');
// The hidden product id can sit in a separate form (the add row's inputs use form="")
var product = root.querySelector('[data-line-product]') || (opts.productInput || null);
function update() {
if (!preview) {
return;
}
var q = itflowBillingNumber(qty && qty.value !== '' ? qty.value : '1');
var p = itflowBillingNumber(price ? price.value : '');
if (isNaN(q) || isNaN(p)) {
preview.textContent = price && price.value !== '' ? 'Not a number' : '';
return;
}
var option = tax && tax.options[tax.selectedIndex];
var percent = option ? Number(option.getAttribute('data-percent') || 0) : 0;
var subtotal = Math.round(q * p * 100) / 100;
var total = subtotal + Math.round(subtotal * percent) / 100;
preview.textContent = itflowBillingMoney(total, opts.currency, opts.locale);
}
[qty, price, tax].forEach(function (el) {
if (el) {
el.addEventListener('input', update);
el.addEventListener('change', update);
}
});
update();
// The description grows with what is typed into it
if (description && description.tagName === 'TEXTAREA') {
var grow = function () {
description.style.height = 'auto';
description.style.height = Math.min(description.scrollHeight + 2, 240) + 'px';
};
description.addEventListener('input', grow);
if (description.value) {
grow();
}
}
if (!name || !opts.products || !opts.products.length || typeof itflowAutocomplete !== 'function') {
return;
}
itflowAutocomplete(name, {
minLength: 1,
source: opts.products,
match: function (item, term) {
return String(item.label || '').toLowerCase().indexOf(term) !== -1
|| String(item.product_name || '').toLowerCase().indexOf(term) !== -1
|| String(item.product_code || '').toLowerCase().indexOf(term) !== -1;
},
render: function (item) {
var esc = itflowEscapeHtml;
var isService = String(item.type || '').toLowerCase() === 'service';
var stock = Number(item.available_stock || 0);
return "<div class='d-flex justify-content-between align-items-start gap-3'>" +
"<div class='min-w-0'>" +
"<div class='fw-semibold'>" + esc(item.label) + "</div>" +
(item.description ? "<div class='small text-body-secondary text-truncate'>" + esc(item.description) + "</div>" : "") +
"<div class='small mt-1'>" +
"<span class='badge rounded-pill bg-secondary-subtle text-secondary-emphasis fw-normal me-1'>" + (isService ? 'Service' : 'Product') + "</span>" +
(item.tax_percent != null ? "<span class='badge rounded-pill bg-secondary-subtle text-secondary-emphasis fw-normal me-1'>Tax " + esc(parseFloat(item.tax_percent)) + "%</span>" : "") +
(!isService ? "<span class='badge rounded-pill fw-normal " + (stock > 0 ? "bg-success-subtle text-success-emphasis" : "bg-danger-subtle text-danger-emphasis") + "'>" + esc(stock) + " in stock</span>" : "") +
"</div>" +
"</div>" +
"<div class='fw-semibold text-nowrap'>" + esc(item.price != null && item.price !== '' ? itflowBillingMoney(Number(item.price), opts.currency, opts.locale) : '') + "</div>" +
"</div>";
},
onSelect: function (item) {
name.value = item.product_name;
if (description) {
description.value = item.description || '';
description.dispatchEvent(new Event('input', { bubbles: true }));
}
if (qty && (qty.value === '' || qty.value === '0')) {
qty.value = 1;
}
if (price) {
price.value = item.price;
}
if (tax) {
tax.value = item.tax || 0;
if (tax.selectedIndex < 0) {
tax.value = 0;
}
tax.dispatchEvent(new Event('change', { bubbles: true }));
}
if (product) {
product.value = item.prod_id;
}
update();
if (price) {
price.focus();
price.select();
}
}
});
// Typing over the name by hand breaks the link to the product
if (product) {
name.addEventListener('input', function () {
product.value = 0;
});
}
}
function itflowBillingItems(options) {
var opts = options || {};
var paper = document.querySelector('.itflow-paper[data-billing-type]');
if (!paper) {
return;
}
var type = paper.getAttribute('data-billing-type');
var docId = paper.getAttribute('data-billing-id');
var addRow = paper.querySelector('[data-billing-add]');
var addForm = document.getElementById('billingAddLine');
if (addRow) {
itflowBillingLineForm(addRow, {
products: opts.products,
currency: opts.currency,
locale: opts.locale,
productInput: addForm ? addForm.querySelector('[data-line-product]') : null
});
// Enter in the name, quantity or price adds the line
addRow.querySelectorAll('input').forEach(function (input) {
input.addEventListener('keydown', function (e) {
if (e.key === 'Enter' && !e.defaultPrevented && !document.querySelector('.itflow-ac-menu.show')) {
e.preventDefault();
if (addForm && addForm.reportValidity()) {
addForm.requestSubmit ? addForm.requestSubmit() : addForm.submit();
}
}
});
});
}
// Back from adding a line - ready for the next; back from editing one - show which
var hash = window.location.hash;
if (hash === '#add-line' && addRow) {
var nameInput = addRow.querySelector('[data-line-name]');
addRow.scrollIntoView({ block: 'center' });
if (nameInput) {
nameInput.focus();
}
} else if (/^#line-\d+$/.test(hash)) {
var line = document.querySelector(hash);
if (line) {
line.scrollIntoView({ block: 'center' });
line.classList.add('itflow-paper-flash');
}
}
// Drag to reorder
var body = paper.querySelector('[data-billing-items] tbody');
if (body && typeof Sortable !== 'undefined' && paper.querySelector('.drag-handle')) {
new Sortable(body, {
handle: '.drag-handle',
animation: 150,
onEnd: function (evt) {
if (evt.oldIndex === evt.newIndex) {
return;
}
var ids = Array.prototype.map.call(body.querySelectorAll('tr[data-item-id]'), function (row) {
return row.getAttribute('data-item-id');
});
itflowPost('ajax.php', {
billing_items_order: 1,
type: type,
doc_id: docId,
items: ids.join(','),
csrf_token: opts.csrf
}, function () {
if (typeof itflowToast === 'function') {
itflowToast('Order saved', 'success');
}
}, function () {
if (typeof itflowToast === 'function') {
itflowToast("The new order didn't save - reloading", 'error');
}
setTimeout(function () { window.location.reload(); }, 1200);
});
}
});
}
}