/* TMD Portal — Invoicing (backed by tmd_invoices, tmd_invoice_items, tmd_payments). Owners and Managers only. Draft → issue (gets a number) → payments → paid. Printable. */ const { useState: uSv, useEffect: uEv, useMemo: uMv, useCallback: uCv } = React; const INV_STATUS = { draft: 'todo', issued: 'doing', 'part paid': 'waiting', paid: 'done', overdue: 'blocked', void: 'blocked' }; const ivTotal = items => (items || []).reduce((s, i) => s + Number(i.qty || 0) * Number(i.unit_price || 0), 0); const ivPaid = pays => (pays || []).reduce((s, p) => s + Number(p.amount || 0), 0); function useInvoices() { const [state, setState] = uSv({ loading: true, invoices: [], items: [], payments: [], error: '' }); const load = uCv(async () => { const [i, it, p] = await Promise.all([ SB.from('tmd_invoices').select('*').order('created_at', { ascending: false }), SB.from('tmd_invoice_items').select('*').order('position'), SB.from('tmd_payments').select('*').order('paid_on') ]); setState({ loading: false, invoices: i.data || [], items: it.data || [], payments: p.data || [], error: (i.error || it.error || p.error || {}).message || '' }); }, []); uEv(() => { load(); }, [load]); return Object.assign({}, state, { reload: load }); } function InvStatus({ s, size }) { return ; } /* ================= list ================= */ function InvoicesDb({ app }) { const inv = useInvoices(); const brands = app.work.brands; const [creating, setCreating] = uSv(false); const [status, setStatus] = uSv('open'); const [brand, setBrand] = uSv('all'); const list = inv.invoices.filter(i => (brand === 'all' || i.brand_slug === brand) && (status === 'all' ? true : status === 'open' ? !['paid', 'void'].includes(i.status) : i.status === status)); const itemsOf = id => inv.items.filter(x => x.invoice_id === id), paysOf = id => inv.payments.filter(x => x.invoice_id === id); const outstanding = inv.invoices.filter(i => ['issued', 'part paid', 'overdue'].includes(i.status)).reduce((s, i) => s + ivTotal(itemsOf(i.id)) - ivPaid(paysOf(i.id)), 0); const overdue = inv.invoices.filter(i => i.status === 'overdue').length; return (
setCreating(true)}>New invoice} /> {inv.error ?
Could not load invoices.

{inv.error}

: null}
({ v: b.slug, l: b.name })))} />
{inv.loading ?

Loading

: list.length ? ( {list.map(i => { const t = ivTotal(itemsOf(i.id)), p = ivPaid(paysOf(i.id)); return ( app.go('inv:' + i.id)}> ); })}
NumberClientPeriodStatusIssuedDueTotalBalance
{i.number || draft} {brandOf(brands, i.brand_slug).name} {i.period || '—'} {i.issued_on ? fmtDate(i.issued_on) : '—'} {i.due_on ? : —} {money(t, { bare: true })} {money(Math.max(0, t - p), { bare: true })}
) : setCreating(true)}>New invoice} />} setCreating(false)} onCreated={id => { setCreating(false); app.go('inv:' + id); }} />
); } function NewInvoice({ open, app, onClose, onCreated }) { const brands = app.work.brands.filter(b => b.status !== 'Ended'); const [f, setF] = uSv({}); const [busy, setBusy] = uSv(false); const [err, setErr] = uSv(''); uEv(() => { if (open) { setF({ brand_slug: brands[0] ? brands[0].slug : '', period: monthLabel(0, true), bill_to: '', desc: 'Monthly retainer — ' + monthLabel(0, true), amount: '' }); setErr(''); setBusy(false); } }, [open]); if (!open) return null; const set = k => e => setF(x => Object.assign({}, x, { [k]: e.target.value })); const create = async () => { setErr(''); if (!f.brand_slug) { setErr('Pick a client.'); return; } setBusy(true); const b = brands.find(x => x.slug === f.brand_slug); const { data, error } = await SB.from('tmd_invoices').insert({ brand_slug: f.brand_slug, period: f.period.trim() || null, bill_to: f.bill_to.trim() || (b ? b.name : null) }).select().single(); if (error) { setBusy(false); setErr(error.message); return; } if (f.desc.trim()) await SB.from('tmd_invoice_items').insert({ invoice_id: data.id, description: f.desc.trim(), qty: 1, unit_price: Number(f.amount) || 0, position: 0 }); setBusy(false); onCreated(data.id); }; return ( Cancel{busy ? 'Working' : 'Create draft'}}>

You can add more lines on the next screen. The number is given when you issue it.

{err ?

{err}

: null}
); } /* ================= detail / print ================= */ function InvoiceDb({ app, id }) { const inv = useInvoices(); const brands = app.work.brands; const i = inv.invoices.find(x => x.id === id); const items = inv.items.filter(x => x.invoice_id === id); const pays = inv.payments.filter(x => x.invoice_id === id); const [line, setLine] = uSv({ description: '', qty: '1', unit_price: '' }); const [pay, setPay] = uSv({ paid_on: T.TODAY, amount: '', reference: '' }); const [issueOpen, setIssueOpen] = uSv(false); const [due, setDue] = uSv(isoShift(7)); const [cfg, setCfg] = uSv({}); const [voidOpen, setVoidOpen] = uSv(false); uEv(() => { SB.from('tmd_config').select('key,value').in('key', ['invoice_from', 'invoice_from_lines', 'invoice_payment_note']).then(({ data }) => { const o = {}; (data || []).forEach(r => o[r.key] = r.value); setCfg(o); }); }, []); if (inv.loading) return

Loading

; if (!i) return
app.go('invoices')}>Back to invoices} />
; const b = brandOf(brands, i.brand_slug); const total = ivTotal(items), paid = ivPaid(pays), balance = Math.max(0, total - paid); const draft = i.status === 'draft'; const addLine = async () => { if (!line.description.trim()) return; const { error } = await SB.from('tmd_invoice_items').insert({ invoice_id: id, description: line.description.trim(), qty: Number(line.qty) || 1, unit_price: Number(line.unit_price) || 0, position: items.length }); if (error) { app.toast('Not saved: ' + error.message); return; } setLine({ description: '', qty: '1', unit_price: '' }); inv.reload(); }; const removeLine = async it => { const { error } = await SB.from('tmd_invoice_items').delete().eq('id', it.id); if (error) app.toast('Not removed: ' + error.message); inv.reload(); }; const saveField = async patch => { const { error } = await SB.from('tmd_invoices').update(patch).eq('id', id); if (error) app.toast('Not saved: ' + error.message); inv.reload(); }; const issue = async () => { const { error } = await SB.rpc('tmd_invoice_issue', { inv: id, due: due || null }); setIssueOpen(false); if (error) { app.toast(error.message); return; } app.toast('Invoice issued'); inv.reload(); }; const addPay = async () => { if (!(Number(pay.amount) > 0)) return; const { error } = await SB.from('tmd_payments').insert({ invoice_id: id, paid_on: pay.paid_on, amount: Number(pay.amount), reference: pay.reference.trim() || null }); if (error) { app.toast('Not saved: ' + error.message); return; } setPay({ paid_on: T.TODAY, amount: '', reference: '' }); app.toast('Payment recorded'); inv.reload(); }; const removePay = async p => { const { error } = await SB.from('tmd_payments').delete().eq('id', p.id); if (error) app.toast('Not removed: ' + error.message); inv.reload(); }; const voidIt = async () => { setVoidOpen(false); await saveField({ status: 'void' }); app.toast('Invoice voided'); }; return (
{draft ? setIssueOpen(true)} disabled={!items.length}>Issue invoice : null} {!draft && i.status !== 'void' ? window.print()}>Print or save PDF : null} {!draft && i.status !== 'void' && i.status !== 'paid' ? setVoidOpen(true)}>Void : null} } />
0 && i.status === 'overdue' ? 'bad' : null} />
{/* Printable document */}
{cfg.invoice_from || 'The Marketing Desk'}{(cfg.invoice_from_lines || '').split('\\n').map((l, k) => {l})}

Invoice

Number
{i.number || 'Draft'}
Issued
{i.issued_on ? fmtDate(i.issued_on, true) : '—'}
Due
{i.due_on ? fmtDate(i.due_on, true) : '—'}
Period
{i.period || '—'}
Bill to {draft ? saveFieldDebounced(saveField, { bill_to: e.target.value })} placeholder={b.name} /> : {i.bill_to || b.name}} {b.name}
{draft ? : null} {items.map(it => {draft ? : null})} {!items.length ? : null} {draft ? : null} {paid > 0 ? <> : null}
DescriptionQtyUnit priceAmount
{it.description}{Number(it.qty)}{money(Number(it.unit_price), { bare: true })}{money(Number(it.qty) * Number(it.unit_price), { bare: true })}
No lines yet.
Total{money(total, { bare: true })}
Paid{money(paid, { bare: true })}
Balance due{money(balance, { bare: true })}
{draft ? (
setLine(x => Object.assign({}, x, { description: e.target.value }))} placeholder="Line description" onKeyDown={e => e.key === 'Enter' && addLine()} /> setLine(x => Object.assign({}, x, { qty: e.target.value }))} placeholder="Qty" style={{ width: 80 }} /> setLine(x => Object.assign({}, x, { unit_price: e.target.value }))} placeholder="Unit price" style={{ width: 130 }} /> Add line
) : null}
Payment

{cfg.invoice_payment_note || 'Bank transfer. Please quote the invoice number as the reference.'}

{i.notes ?

{i.notes}

: null}
{!draft && i.status !== 'void' ? (

Payments

{money(paid, { bare: true })} received
{pays.map(p =>
{money(Number(p.amount), { bare: true })}
{fmtDate(p.paid_on, true)}{p.reference ? {p.reference} : null}
)} {balance > 0 ? (
setPay(x => Object.assign({}, x, { amount: e.target.value }))} placeholder={'Amount, up to ' + money(balance, { bare: true })} /> setPay(x => Object.assign({}, x, { paid_on: e.target.value }))} /> setPay(x => Object.assign({}, x, { reference: e.target.value }))} placeholder="Reference" /> 0)}>Record payment
) :

Paid in full.

}
) : null} setIssueOpen(false)} title="Issue this invoice" footer={<> setIssueOpen(false)}>CancelIssue}>

Issuing gives it the next number and freezes the lines. Total {money(total)}.

It stays on record as void. The number is not reused.

} confirmLabel="Void" onConfirm={voidIt} onClose={() => setVoidOpen(false)} />
); } // Debounce bill-to edits so each keystroke does not hit the database. let _billTimer = null; function saveFieldDebounced(save, patch) { clearTimeout(_billTimer); _billTimer = setTimeout(() => save(patch), 600); } Object.assign(window, { InvoicesDb, InvoiceDb, useInvoices });