%# Inline so the page never depends on precompiled plugin assets %>
<%= javascript_tag do %>
$(function () {
var $form = $('#qbo-estimate-form');
if (!$form.length) return;
var $tbody = $('#qbo-estimate-lines tbody');
var template = document.getElementById('qbo-estimate-line-template').innerHTML;
var subtotalTemplate = document.getElementById('qbo-estimate-subtotal-template').innerHTML;
var money = new Intl.NumberFormat(<%= raw (current_language.to_s.presence || 'en').to_json %>, { style: 'currency', currency: 'USD' });
var savedSubtotal = $form.data('savedSubtotal') === '' ? null : parseFloat($form.data('savedSubtotal'));
var savedTax = $form.data('savedTax') === '' ? null : parseFloat($form.data('savedTax'));
// Discounts are kept from QuickBooks as they are; QuickBooks works out a percent discount again on save
var discount = $form.data('discount') === '' ? 0 : parseFloat($form.data('discount'));
var locked = $form.find('.qbo-estimate-sheet').prop('disabled');
// Row keys must be digits: Rails' strong parameters only keep a hash of rows when every key is a number
var nextKey = Date.now();
var dirty = false;
// ---- numbers ----
function parseNumber(value) {
var text = String(value == null ? '' : value).replace(/[$,\s]/g, '');
if (text === '') return null;
var n = Number(text);
return isFinite(n) ? n : NaN;
}
function round(n, places) { var f = Math.pow(10, places); return Math.round(n * f) / f; }
function plain(n, places) { return String(round(n, places)); }
// ---- rows ----
function rows() { return $tbody.children('tr.qbo-line'); }
function isSubtotal($row) { return $row.hasClass('qbo-line-subtotal'); }
function rowIsBlank($row) {
if (isSubtotal($row)) return false;
return !$row.find('.qbo-line-item-id').val() && !$row.find('.qbo-line-item-name').val().trim() &&
!$row.find('.qbo-line-description-input').val().trim() && !$row.find('.qbo-line-rate-input').val().trim();
}
function addRow() {
var $row = $(template.replace(/__KEY__/g, String(nextKey++)));
$tbody.append($row);
setupRow($row);
renumber();
return $row;
}
// QuickBooks keeps a spare empty line at the bottom; filling it adds another
function ensureSpareRow() {
var $last = rows().last();
if (!$last.length || !rowIsBlank($last)) addRow();
}
function renumber() {
rows().each(function (i) { $(this).find('.qbo-line-number').text(i + 1); });
}
function autoGrow(textarea) {
textarea.style.height = 'auto';
textarea.style.height = (textarea.scrollHeight + 2) + 'px';
}
// Works out the line amount from qty x rate (qty defaults to 1, like QuickBooks)
function lineAmount($row) {
var rate = parseNumber($row.find('.qbo-line-rate-input').val());
if (rate === null || isNaN(rate)) return null;
var qty = parseNumber($row.find('.qbo-line-qty-input').val());
if (qty === null) qty = 1;
if (isNaN(qty)) return null;
return round(qty * rate, 2);
}
function recalc() {
var subtotal = 0, taxable = 0, section = 0;
rows().each(function () {
var $row = $(this);
// A subtotal row totals the lines since the previous subtotal
if (isSubtotal($row)) {
$row.find('.qbo-line-subtotal-amount').text(money.format(round(section, 2)));
section = 0;
return;
}
var amount = lineAmount($row);
var $amount = $row.find('.qbo-line-amount-input');
if (!$amount.is(':focus')) $amount.val(amount === null ? '' : amount.toFixed(2));
if (amount !== null) {
subtotal += amount;
section += amount;
if ($row.find('.qbo-line-taxable').is(':checked')) taxable += amount;
}
});
subtotal = round(subtotal, 2);
// QuickBooks works out the sales tax when the estimate is saved; show the saved tax until the lines change
var $tax = $('#qbo-estimate-tax');
var total = round(subtotal - discount, 2);
if (savedTax !== null && savedSubtotal !== null && Math.abs(subtotal - savedSubtotal) < 0.005) {
$tax.text(money.format(savedTax)).removeClass('qbo-pending');
total = round(total + savedTax, 2);
} else {
$tax.text($tax.data('pendingText')).addClass('qbo-pending');
}
$('#qbo-estimate-subtotal').text(money.format(subtotal));
$('#qbo-estimate-taxable-subtotal').text(money.format(round(taxable, 2)));
$('#qbo-estimate-total').text(money.format(total));
$('#qbo-estimate-amount').text(money.format(total));
}
// ---- product/service search ----
function setupItemSearch($input) {
$input.autocomplete({
appendTo: 'body',
minLength: 0,
delay: 150,
source: function (request, response) {
$.getJSON($form.data('itemsUrl'), { q: request.term })
.done(function (items) {
response(items.map(function (item) {
return { label: item.name, value: item.name, item: item };
}));
})
.fail(function () { response([]); });
},
select: function (event, ui) {
var $row = $input.closest('tr');
var item = ui.item.item;
var $description = $row.find('.qbo-line-description-input');
var previous = $row.data('itemDescription');
$input.val(item.name);
$row.find('.qbo-line-item-id').val(item.id);
$row.removeClass('qbo-line-unmatched');
// Keep a description the user typed; replace one that came from the previous product
if (!$description.val().trim() || $description.val() === previous) {
$description.val(item.description || '');
autoGrow($description[0]);
}
$row.data('itemDescription', item.description || '');
if (item.price !== null && item.price !== undefined && item.price !== '') {
$row.find('.qbo-line-rate-input').val(plain(parseFloat(item.price), 5));
tidyNumbers($row);
}
if (!$row.find('.qbo-line-qty-input').val().trim()) $row.find('.qbo-line-qty-input').val('1');
$row.find('.qbo-line-taxable').prop('checked', item.taxable !== false);
changed();
return false;
}
});
$input.autocomplete('instance')._renderItem = function (ul, entry) {
var item = entry.item;
var $div = $('
');
if (item.price !== null && item.price !== undefined && item.price !== '') {
$('').text(money.format(parseFloat(item.price))).appendTo($div);
}
$('').text(item.name).appendTo($div);
var meta = [item.sku, item.description].filter(function (s) { return s; }).join(' · ');
if (meta) $('
').append($div).appendTo(ul);
};
// Like QuickBooks, the list opens when the box is clicked
$input.on('focus', function () {
if (!$input.val()) $input.autocomplete('search', '');
});
// Typing a different name unlinks the product until one is picked from the list
$input.on('input', function () {
var $row = $input.closest('tr');
$row.find('.qbo-line-item-id').val('');
$row.toggleClass('qbo-line-unmatched', $input.val().trim() !== '');
});
}
function setupRow($row) {
if (isSubtotal($row) || $row.data('qboSetup')) return;
$row.data('qboSetup', true);
setupItemSearch($row.find('.qbo-line-item-name'));
$row.find('.qbo-line-description-input').each(function () { autoGrow(this); });
$row.data('itemDescription', $row.find('.qbo-line-item-id').val() ? $row.find('.qbo-line-description-input').val() : null);
}
function changed() {
dirty = true;
recalc();
ensureSpareRow();
}
// ---- line events ----
$tbody.on('input', '.qbo-line-qty-input, .qbo-line-rate-input, .qbo-line-description-input, .qbo-line-item-name', changed);
$tbody.on('change', '.qbo-line-taxable', changed);
$tbody.on('input', '.qbo-line-description-input', function () { autoGrow(this); });
// Typing an amount works out the rate from the quantity
$tbody.on('input', '.qbo-line-amount-input', function () {
var $row = $(this).closest('tr');
var amount = parseNumber($(this).val());
if (amount === null || isNaN(amount)) return;
var qty = parseNumber($row.find('.qbo-line-qty-input').val());
if (qty === null || isNaN(qty) || qty === 0) qty = 1;
$row.find('.qbo-line-rate-input').val(plain(amount / qty, 5));
changed();
});
// Rates show cents (1120 -> 1120.00) unless they need more places; quantities stay plain
function tidyNumbers($row) {
$row.find('.qbo-line-qty-input, .qbo-line-rate-input').each(function () {
var n = parseNumber(this.value);
if (n === null || isNaN(n)) return;
var isRate = $(this).hasClass('qbo-line-rate-input');
this.value = isRate && round(n, 2) === round(n, 5) ? n.toFixed(2) : plain(n, 5);
});
}
$tbody.on('blur', '.qbo-line-rate-input, .qbo-line-qty-input, .qbo-line-amount-input', function () {
tidyNumbers($(this).closest('tr'));
recalc();
});
$tbody.on('click', '.qbo-line-remove-button', function () {
var $row = $(this).closest('tr');
if (rows().length > 1) {
$row.remove();
} else {
$row.find('input[type=text], textarea, .qbo-line-item-id').val('');
$row.removeClass('qbo-line-unmatched');
}
renumber();
changed();
});
$('#qbo-estimate-add-lines').on('click', function () {
for (var i = 0; i < 4; i++) addRow();
dirty = true;
});
// A subtotal goes after the last filled line, above the spare empty rows
$('#qbo-estimate-add-subtotal').on('click', function () {
var $subtotal = $(subtotalTemplate.replace(/__KEY__/g, String(nextKey++)));
var $filled = rows().filter(function () { return !rowIsBlank($(this)); });
if ($filled.length) { $filled.last().after($subtotal); } else { $tbody.prepend($subtotal); }
renumber();
changed();
});
$('#qbo-estimate-clear-lines').on('click', function () {
if (!window.confirm($(this).data('confirmText'))) return;
rows().remove();
addRow(); addRow();
changed();
});
// Drag lines by the handle to reorder them; they're saved in table order
$tbody.sortable({
handle: '.qbo-line-handle',
axis: 'y',
items: '> tr.qbo-line',
placeholder: 'qbo-line-placeholder',
helper: function (event, tr) {
var $originals = tr.children();
var $helper = tr.clone();
$helper.children().each(function (i) { $(this).width($originals.eq(i).outerWidth()); });
return $helper;
},
start: function (event, ui) { ui.placeholder.html('
'); },
// Moving a line or a subtotal changes what each subtotal covers
update: function () { renumber(); changed(); }
});
// ---- customer ----
var $email = $('#qbo_estimate_email');
var $vin = $('#qbo_estimate_vin');
var loadedEmail = $email.val();
$('#customer_id').on('change', function () {
var id = $(this).val();
if (!id) return;
dirty = true;
$.getJSON($form.data('customerInfoUrl'), { customer_id: id }).done(function (info) {
// Replace the email only if it was the previous customer's (or empty)
if (!$email.val().trim() || $email.val() === loadedEmail) $email.val(info.email || '');
loadedEmail = info.email || '';
$('#qbo-estimate-address').text(info.billing_address || '');
var $list = $('#qbo-estimate-vins').empty();
(info.vehicles || []).forEach(function (vehicle) {
$('