// ---- invoices: business details, customers, invoices and their payment ---- // Uses $, state, call, esc, fmt, fmtDate, plural, toast, guard and render from index.html. const todayIso = () => { const d = new Date(); return new Date(d - d.getTimezoneOffset() * 6e4).toISOString().slice(0, 10); }; const addDays = (iso, n) => { const d = new Date(iso + "T00:00:00Z"); d.setUTCDate(d.getUTCDate() + n); return d.toISOString().slice(0, 10); }; document.body.insertAdjacentHTML("beforeend", `

New invoice

DescriptionQtyUnit price (excl GST)GSTAmount

Record payment

Business details

Shown on every invoice. With a GST number, invoices with GST are titled “Tax invoice”.
`); document.head.insertAdjacentHTML("beforeend", ``); async function loadInvoices() { [state.invoices, state.business, state.customers] = await Promise.all([ call("/api/invoices"), call("/api/business"), call("/api/customers")]); state.view = "invoices"; render(); } function renderInvoices() { const all = state.invoices || [], b = state.business || {}; const filter = state.invoiceFilter || "all"; const unpaid = all.filter(i => i.status === "sent" || i.status === "draft"); const cust = state.invoiceCustomer || ""; const list = (filter === "unpaid" ? unpaid : filter === "paid" ? all.filter(i => i.status === "paid") : all) .filter(i => !cust || String(i.customer_id) === cust); const owed = all.filter(i => i.status === "sent").reduce((n, i) => n + i.total, 0); const overdue = all.filter(i => i.overdue).reduce((n, i) => n + i.total, 0); const chip = i => i.overdue ? `overdue` : `${i.status}`; const btn = (act, i, label, cls = "") => ``; const actions = i => [ ``, i.status === "draft" ? btn("edit", i, "Edit") + btn("sent", i, "Mark sent") : "", i.status === "sent" ? btn("draft", i, "Back to draft") : "", ["draft", "sent"].includes(i.status) ? btn("pay", i, "Paid…", "primary") + btn("void", i, "Void") : "", i.status === "paid" ? btn("unpay", i, "Undo payment") : "", ].join(""); return `
Invoices
${[["all", `All (${all.length})`], ["unpaid", `Unpaid (${unpaid.length})`], ["paid", "Paid"]].map(([k, l]) => ``).join("")}
${b.name ? "" : `

Add your (name, GST number, bank account) before sending invoices.

`}
Owed to you
${fmt(owed)}
Overdue
${fmt(overdue)}
${list.length ? `
${list.map(i => ``).join("")}
NumberDateCustomerDueGSTTotalStatus
${esc(i.number)}${fmtDate(i.issue_date)}${esc(i.customer_name)} ${fmtDate(i.due_date)}${fmt(i.gst)}${fmt(i.total)} ${chip(i)}${i.status === "paid" ? `
${fmtDate(i.paid_date)}${i.payments.length ? ` · ${esc(i.payments[0].book)}` : ""}
` : ""}
${actions(i)}
` : `
${all.length ? "No invoices here." : "No invoices yet."}
`}

Marking an invoice paid records the money in the cashbook as Sales, in the book for the payment date. If the bank statement is already imported, pick the matching deposit so it isn't counted twice; statements imported later recognise the payment. An invoice with both GST and non-GST items is recorded as two rows (Incl GST and Excl GST).

`; } // -- invoice editor -- function lineRow(l = { description: "", qty: 1, unit: "", taxable: true }) { return ` `; } function readLines() { return [...$("#invLines").rows].map(r => ({ description: r.querySelector("[data-l=description]").value, qty: Number(r.querySelector("[data-l=qty]").value), unit: Number(r.querySelector("[data-l=unit]").value), taxable: r.querySelector("[data-l=taxable]").checked })); } function updateInvTotals() { const cents = l => Math.round(l.qty * Math.round(l.unit * 100)); const lines = readLines(); [...$("#invLines").rows].forEach((r, i) => r.querySelector("[data-amount]").textContent = fmt(cents(lines[i]) / 100)); const taxable = lines.filter(l => l.taxable).reduce((n, l) => n + cents(l), 0); const exempt = lines.filter(l => !l.taxable).reduce((n, l) => n + cents(l), 0); const gst = Math.floor((taxable * 6 + 20) / 40); // same rounding as the server $("#invTotals").innerHTML = `
Subtotal (excl GST)
${fmt((taxable + exempt) / 100)}
GST 15%${exempt && taxable ? ` on ${fmt(taxable / 100)}` : ""}
${fmt(gst / 100)}
Total
${fmt((taxable + exempt + gst) / 100)}
`; } function customerOptions(selected) { return `` + (state.customers || []).map(c => ``).join("") + ``; } function openInvoice(inv) { state.editingInvoice = inv || null; $("#invTitle").textContent = inv ? `Edit ${inv.number}` : "New invoice"; $("#invCustomer").innerHTML = customerOptions(inv?.customer_id); $("#invIssue").value = inv?.issue_date || todayIso(); $("#invDue").value = inv?.due_date || addDays($("#invIssue").value, state.business?.payment_terms_days ?? 14); $("#invLines").innerHTML = (inv?.lines || [undefined]).map(lineRow).join(""); $("#invNotes").value = inv?.notes || ""; updateInvTotals(); $("#invDialog").returnValue = ""; $("#invDialog").showModal(); } $("#invLines").addEventListener("input", updateInvTotals); $("#invLines").addEventListener("click", e => { if (!e.target.closest("[data-remove]")) return; if ($("#invLines").rows.length > 1) e.target.closest("tr").remove(); updateInvTotals(); }); $("#invAddLine").addEventListener("click", () => { $("#invLines").insertAdjacentHTML("beforeend", lineRow()); $("#invLines").lastElementChild.querySelector("input").focus(); updateInvTotals(); }); $("#invIssue").addEventListener("change", () => { if (!state.editingInvoice) $("#invDue").value = addDays($("#invIssue").value, state.business?.payment_terms_days ?? 14); }); $("#invCustomer").addEventListener("change", guard(async e => { if (e.target.value !== "new") return; const name = prompt("Customer name"); if (!name?.trim()) { e.target.value = ""; return; } const c = await call("/api/customers", { name }); state.customers = await call("/api/customers"); e.target.innerHTML = customerOptions(c.id); toast(`Added ${c.name}. Add their address under Customers.`); })); $("#invSave").addEventListener("click", guard(async e => { e.preventDefault(); if (!$("#invForm").reportValidity()) return; const body = { customer_id: Number($("#invCustomer").value), issue_date: $("#invIssue").value, due_date: $("#invDue").value, lines: readLines(), notes: $("#invNotes").value }; const inv = state.editingInvoice ? await call(`/api/invoices/${state.editingInvoice.id}`, body, "PUT") : await call("/api/invoices", body); $("#invDialog").close(); toast(state.editingInvoice ? `Saved ${inv.number}` : `Created ${inv.number}. Download the PDF to send it.`); await loadInvoices(); })); // -- payment -- async function showPayOptions(inv) { const matches = await call(`/api/invoices/${inv.id}/matches?date=${$("#payDate").value}`); $("#payOptions").innerHTML = (matches.length ? `
Imported deposits of ${fmt(inv.total)} near that date:
` : "") + matches.map((m, i) => ``).join("") + ``; } function openPay(inv) { state.payingInvoice = inv; $("#paySub").textContent = `${inv.number} · ${inv.customer_name} · ${fmt(inv.total)}`; $("#payDate").value = todayIso(); $("#payDialog").returnValue = ""; $("#payDialog").showModal(); return showPayOptions(inv); } $("#payDate").addEventListener("change", guard(() => showPayOptions(state.payingInvoice))); $("#payDialog").addEventListener("close", guard(async () => { if ($("#payDialog").returnValue !== "ok") return; const row = document.querySelector("input[name=payRow]:checked")?.value; const inv = await call(`/api/invoices/${state.payingInvoice.id}/pay`, { date: $("#payDate").value, row: row ? Number(row) : null }); toast(`${inv.number} paid: recorded in ${inv.payments[0]?.book || "the cashbook"}`); if (state.book) state.summary = await call(`/api/summary?book=${encodeURIComponent(state.book)}`); await loadInvoices(); })); // -- customers -- async function loadCustomers() { [state.customers, state.invoices] = await Promise.all([call("/api/customers"), call("/api/invoices")]); state.view = "customers"; render(); } function renderCustomers() { const list = state.customers || []; const owed = id => (state.invoices || []).filter(i => i.customer_id === id && i.status === "sent").reduce((n, i) => n + i.total, 0); return `
Customers
${list.length ? `
${list.map(c => `${["name", "email"].map(k => ``).join("")} `).join("")}
NameEmailAddressOwing
${c.invoices ? `
${plural(c.invoices, "invoice")}
` : ""}
${c.invoices ? "" : ``}
Changes are saved as you leave each box. Invoices already made keep the details they were made with.
` : `
No customers yet.
`}
`; } $("#main").addEventListener("change", guard(async e => { const k = e.target.dataset.cust; if (!k) return; const c = state.customers.find(x => x.id === Number(e.target.dataset.id)); await call(`/api/customers/${c.id}`, { name: c.name, email: c.email, address: c.address, [k]: e.target.value }, "PUT"); state.customers = await call("/api/customers"); toast("Saved"); })); $("#main").addEventListener("click", guard(async e => { const del = e.target.dataset.custDelete, show = e.target.dataset.custShow; if (show) { state.invoiceCustomer = show; state.invoiceFilter = "all"; await loadInvoices(); return; } if (del) { await call(`/api/customers/${del}`, undefined, "DELETE"); await loadCustomers(); } })); $("#main").addEventListener("submit", guard(async e => { if (e.target.id !== "custAdd") return; e.preventDefault(); await call("/api/customers", { name: $("#custName").value, email: $("#custEmail").value, address: $("#custAddress").value }); await loadCustomers(); })); // -- business details -- function showLogo() { const has = !!state.business.logo_file; $("#bizLogo").hidden = !has; $("#bizLogoRemove").hidden = !has; if (has) $("#bizLogo").src = `/api/business/logo?t=${Date.now()}`; } async function openBusiness() { state.business = await call("/api/business"); for (const input of document.querySelectorAll("[data-biz]")) input.value = state.business[input.dataset.biz] ?? ""; showLogo(); $("#bizDialog").returnValue = ""; $("#bizDialog").showModal(); } $("#bizDialog").addEventListener("close", guard(async () => { if ($("#bizDialog").returnValue !== "ok") return; const body = {}; for (const input of document.querySelectorAll("[data-biz]")) { const k = input.dataset.biz, v = input.type === "number" ? Number(input.value) : input.value; if (v !== state.business[k]) body[k] = v; } state.business = await call("/api/business", body, "PUT"); toast("Business details saved"); if (state.view === "invoices") render(); })); $("#bizLogoAdd").addEventListener("click", () => $("#bizLogoInput").click()); $("#bizLogoInput").addEventListener("change", guard(async e => { const f = e.target.files[0]; e.target.value = ""; if (!f) return; const res = await fetch("/api/business/logo", { method: "POST", body: f }); const data = await res.json().catch(() => ({})); if (!res.ok) throw new Error(errorText(data, res)); state.business = data; showLogo(); })); $("#bizLogoRemove").addEventListener("click", guard(async () => { state.business = await call("/api/business/logo", undefined, "DELETE"); showLogo(); })); // buttons with data-inv in the Invoices view async function invoiceAction(b) { const id = Number(b.dataset.id), inv = (state.invoices || []).find(i => i.id === id); switch (b.dataset.inv) { case "filter": state.invoiceFilter = b.dataset.filter; return render(); case "new": return openInvoice(); case "edit": return openInvoice(inv); case "business": return openBusiness(); case "pay": return openPay(inv); case "sent": case "draft": await call(`/api/invoices/${id}/status`, { status: b.dataset.inv }); break; case "void": if (!confirm(`Void ${inv.number}? It keeps its number but can't be used again.`)) return; await call(`/api/invoices/${id}/status`, { status: "void" }); break; case "unpay": if (!confirm(`Undo the payment of ${inv.number}? The cashbook entries it made are removed (an imported bank line is put back as it was).`)) return; await call(`/api/invoices/${id}/unpay`, {}); if (state.book) state.summary = await call(`/api/summary?book=${encodeURIComponent(state.book)}`); break; } await loadInvoices(); }