// The rules of Finance → Expenses, the supplier book and Finance → Tabs (plan step 6.13a), kept // out of the components so they are unit-tested (tests/finance.test.mjs). The backend checks the // same things (routers/expenses.py, routers/tabs.py); these give the message before saving. import { parseNumber } from '@xenia/i18n/number' // plain JS: Node tests import this file // As routers/expenses.py CATEGORIES / CONTACT_TYPES and routers/tabs.py METHODS export const CATEGORIES = ['supplier', 'utilities', 'rent', 'maintenance', 'staff', 'equipment', 'other'] export const CONTACT_TYPES = ['supplier', 'staff', 'utility', 'other'] export const PAY_METHODS = ['cash', 'card', 'other'] export const STATUS_TONE = { paid: 'success', partial: 'warning', due: 'danger' } export const TAB_TONE = { open: 'danger', closed: 'success', forgiven: 'neutral' } const money = text => parseNumber(String(text ?? ''), { decimals: 2, allowNegative: false }) const cents = v => Math.round(v * 100) // ── Expenses ───────────────────────────────────────────────────────────────── /** The dialog's fields for a new expense or an existing one (amounts as typed text; the due * date as the venue date 'YYYY-MM-DD' through `dateKey`, useFormat().venueDateKey). */ export function expenseForm(e, dateKey = d => d) { return { description: e?.description ?? '', category: e?.category ?? 'supplier', contact_id: e?.contact_id ? String(e.contact_id) : '', total_amount: e ? String(e.total_amount) : '', due_date: e?.due_date ? dateKey(e.due_date) : '', notes: e?.notes ?? '', } } /** Which fields are wrong: description, total_amount (none, zero, or less than what was paid). */ export function expenseProblems(form, paid = 0) { const out = [] if (!form.description.trim()) out.push('description') const total = money(form.total_amount) if (!(total > 0)) out.push('total_amount') else if (cents(total) < cents(paid)) out.push('below_paid') return out } /** What the API takes. `due_date` is the venue date picked ('' clears it). */ export function expenseBody(form) { return { description: form.description.trim(), category: form.category, contact_id: form.contact_id ? Number(form.contact_id) : null, total_amount: money(form.total_amount), due_date: form.due_date || null, notes: form.notes.trim() || null, } } /** A payment's amount: a number above zero and no more than what is due, or null. */ export function paymentAmount(text, due) { const v = money(text) return v > 0 && cents(v) <= cents(due) ? v : null } /** Is it late? Due before today (venue dates, 'YYYY-MM-DD') and not paid. */ export function isLate(expense, today, dateKey) { return expense.status !== 'paid' && !!expense.due_date && dateKey(expense.due_date) < today } /** The page's list after its filters: status ('' | 'unpaid' | due | partial | paid), category, text. */ /** A filter's chosen values: a list (the toolbars' multi-selects, 2026-11-20), one value, or none = all. */ const picked = v => (Array.isArray(v) ? v : v ? [v] : []) export function filterExpenses(list, { status = '', category = '', q = '' } = {}) { const words = q.trim().toLowerCase().split(/\s+/).filter(Boolean) const statuses = picked(status) const categories = picked(category) return list.filter(e => (!statuses.length || statuses.some(s => (s === 'unpaid' ? e.status !== 'paid' : e.status === s))) && (!categories.length || categories.includes(e.category)) && words.every(w => `${e.description} ${e.contact_name ?? ''} ${e.notes ?? ''}`.toLowerCase().includes(w))) } /** Totals of a list: spent, paid, due, how many unpaid, how many late. */ export function expenseTotals(list, today, dateKey) { const sum = k => Math.round(list.reduce((s, e) => s + (e[k] ?? 0), 0) * 100) / 100 return { total: sum('total_amount'), paid: sum('paid_amount'), due: sum('due_amount'), unpaid: list.filter(e => e.status !== 'paid').length, late: list.filter(e => isLate(e, today, dateKey)).length, } } /** What is owed to each supplier: { [contact_id]: { due, count } } from the expenses. */ export function owedByContact(expenses) { const out = {} for (const e of expenses) { if (!e.contact_id || !(e.due_amount > 0)) continue const o = (out[e.contact_id] ??= { due: 0, count: 0 }) o.due = Math.round((o.due + e.due_amount) * 100) / 100 o.count += 1 } return out } // ── Suppliers and contacts ─────────────────────────────────────────────────── export function contactForm(c) { return { name: c?.name ?? '', type: c?.type ?? 'supplier', phone: c?.phone ?? '', email: c?.email ?? '', address: c?.address ?? '', notes: c?.notes ?? '' } } export function contactProblems(form) { const out = [] if (!form.name.trim()) out.push('name') if (form.email.trim() && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email.trim())) out.push('email') return out } /** Empty fields are sent as null, so clearing a phone number clears it. */ export function contactBody(form) { const v = k => form[k].trim() || null return { name: form.name.trim(), type: form.type, phone: v('phone'), email: v('email'), address: v('address'), notes: v('notes') } } export function filterContacts(list, { type = '', q = '' } = {}) { const words = q.trim().toLowerCase().split(/\s+/).filter(Boolean) const types = picked(type) return list.filter(c => (!types.length || types.includes(c.type)) && words.every(w => `${c.name} ${c.phone ?? ''} ${c.email ?? ''} ${c.notes ?? ''}`.toLowerCase().includes(w))) } // ── Tabs ───────────────────────────────────────────────────────────────────── /** Whole venue days a tab has been open ('YYYY-MM-DD' keys). */ export function daysBetween(fromKey, toKey) { return Math.max(0, Math.round((Date.parse(`${toKey}T00:00:00Z`) - Date.parse(`${fromKey}T00:00:00Z`)) / 86_400_000)) } /** What can be done with a tab now. */ export function tabActions(tab) { const open = tab.status === 'open' return { pay: open && tab.balance > 0.005, close: open && tab.balance <= 0.005 && tab.entries.length > 0, forgive: open && tab.balance > 0.005, } } export function filterTabs(list, q = '') { const words = q.trim().toLowerCase().split(/\s+/).filter(Boolean) return list.filter(tab => words.every(w => `${tab.customer_name ?? ''} ${tab.customer_phone ?? ''}`.toLowerCase().includes(w))) } export function tabTotals(open) { return { owed: Math.round(open.reduce((s, tab) => s + tab.balance, 0) * 100) / 100, count: open.length } }