feat(manager): expenses, the supplier book and tabs on v2 (platform-v2 step 6.13a)

- Finance -> Expenses: still owed, late, filters, new/edit (supplier picked or added there), pay in parts, details with payments, delete
- CRM -> Contacts: the supplier book with what each one is owed
- Finance -> Tabs: open (who owes most first) / settled, charges and payments, pay (cash/card/other), close, forgive
- backend: expenses.manage / tabs.manage (the list also reports.view, a customer's tabs also crm.manage, put-on-tab needs tabs.manage);
  payment <= due (expense.over_due), total >= paid (expense.below_paid), categories/kinds/methods checked, null clears a field;
  live events expenses.changed / tabs.changed; GET /api/expenses ?from=&to= venue dates (the report uses it); tab_status=settled
- fix: an expense with a due date failed to save (naive date refused by D-11)
- @xenia/i18n/number subpath; tests: test_finance.py (6), finance.test.mjs (5), e2e manager.mjs finance flow

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-19 12:54:21 +02:00
co-authored by Claude Opus 5.5
parent 6bdf0bdd79
commit 93c0dd7d9c
32 changed files with 1667 additions and 1153 deletions
@@ -0,0 +1,170 @@
// Finance → Expenses (plan step 6.13a; replaces the v1 ExpensesPage): what the venue owes and has
// paid. New expense (what, category, supplier, amount, due by), a payment (in parts until it's
// paid), edit, delete; filters (unpaid / status, category, text); what is due and what is late.
// The analysis of a period is Reports → Expenses. Live: `expenses.changed`.
import { useState } from 'react'
import { useMutation } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import { Banknote, Pencil, Plus, Receipt, Search, Trash2 } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog, EmptyState, IconButton, Input, Select, Spinner } from '@xenia/ui'
import client from '../../api/client'
import { useLiveQuery } from '../../live/useLiveQuery'
import { Pill } from '../overview/parts'
import { Panel, Stat, Table } from '../reports/kit/parts'
import ExpenseDialog from './ExpenseDialog'
import ExpensePayDialog from './ExpensePayDialog'
import { CATEGORIES, STATUS_TONE, expenseTotals, filterExpenses, isLate } from './financeLogic'
export default function ExpensesPage() {
const { t } = useTranslation('manager')
const fmt = useFormat()
const [filter, setFilter] = useState({ status: 'unpaid', category: '', q: '' })
const [dialog, setDialog] = useState(null) // { kind: 'new' | 'edit' | 'pay' | 'view' | 'delete', expense }
const { data, isPending, refetch } = useLiveQuery({ queryKey: ['expenses'], queryFn: () => client.get('/api/expenses/').then(r => r.data), events: ['expenses.changed'] })
const all = data ?? []
const today = fmt.venueToday()
const rows = filterExpenses(all, filter)
const owed = expenseTotals(all, today, fmt.venueDateKey)
const shown = expenseTotals(rows, today, fmt.venueDateKey)
const set = (k, v) => setFilter(f => ({ ...f, [k]: v }))
const open = (kind, expense = null) => setDialog({ kind, expense })
const close = () => setDialog(null)
const saved = () => { close(); refetch() }
const remove = useMutation({
mutationFn: e => client.delete(`/api/expenses/${e.id}`),
onSuccess: (_r, e) => { toast.success(t('finance.exp.deleted', { what: e.description })); saved() },
onError: err => toast.error(errorMessage(err, t)),
})
const cat = c => t(`finance.categories.${c}`, { defaultValue: c })
const stop = fn => ev => { ev.stopPropagation(); fn() }
const columns = [
{ key: 'description', label: t('finance.exp.what'), render: e => (
<span className="grid">
<span className="font-semibold text-ink">{e.description}</span>
{e.contact_name && <span className="text-caption text-ink-2">{e.contact_name}</span>}
</span>) },
{ key: 'category', label: t('finance.exp.category'), sort: e => cat(e.category), render: e => cat(e.category) },
{ key: 'created_at', label: t('finance.exp.entered'), render: e => fmt.formatDate(e.created_at) },
{ key: 'due_date', label: t('finance.exp.dueBy'), sort: e => e.due_date ?? '', render: e => (e.due_date
? <span className={isLate(e, today, fmt.venueDateKey) ? 'text-danger-ink font-semibold' : ''}>{fmt.formatDate(e.due_date)}</span> : '') },
{ key: 'total_amount', label: t('finance.exp.total'), align: 'right', render: e => fmt.formatMoney(e.total_amount) },
{ key: 'due_amount', label: t('finance.exp.due'), align: 'right', render: e => (e.due_amount > 0 ? <span className="text-danger-ink font-semibold">{fmt.formatMoney(e.due_amount)}</span> : '') },
{ key: 'status', label: t('finance.exp.status'), render: e => (
<span className="flex flex-wrap gap-1">
<Pill tone={STATUS_TONE[e.status] ?? 'neutral'}>{t(`finance.status.${e.status}`, { defaultValue: e.status })}</Pill>
{isLate(e, today, fmt.venueDateKey) && <Pill tone="danger">{t('finance.exp.late')}</Pill>}
</span>) },
{ key: 'actions', label: '', sort: false, render: e => (
<span className="flex justify-end gap-0.5">
{e.status !== 'paid' && <IconButton size="sm" variant="ghost" label={t('finance.exp.payOf', { what: e.description })} onClick={stop(() => open('pay', e))} data-testid="expense-pay"><Banknote size={15} /></IconButton>}
<IconButton size="sm" variant="ghost" label={t('finance.exp.editOf', { what: e.description })} onClick={stop(() => open('edit', e))}><Pencil size={15} /></IconButton>
<IconButton size="sm" variant="ghost" label={t('finance.exp.deleteOf', { what: e.description })} onClick={stop(() => open('delete', e))}><Trash2 size={15} /></IconButton>
</span>) },
]
return (
<div className="h-full overflow-y-auto p-4 lg:p-6" data-testid="expenses-page">
<div className="max-w-6xl mx-auto grid gap-4">
<header className="flex flex-wrap items-center gap-3">
<div className="flex-1 min-w-0">
<h1 className="text-title font-semibold text-ink">{t('finance.exp.title')}</h1>
<p className="text-label text-ink-2">{t('finance.exp.subtitle')}</p>
</div>
<Button icon={<Plus size={16} />} onClick={() => open('new')} data-testid="expense-new">{t('finance.exp.new')}</Button>
</header>
<div className="grid gap-3 grid-cols-[repeat(auto-fill,minmax(12rem,1fr))]">
<Stat label={t('finance.exp.owed')} tone={owed.due ? 'danger' : 'success'} value={fmt.formatMoney(owed.due)}
sub={t('finance.exp.unpaid', { count: owed.unpaid })} testId="expenses-owed" />
<Stat label={t('finance.exp.lateTitle')} tone={owed.late ? 'danger' : undefined} value={fmt.formatNumber(owed.late)} sub={t('finance.exp.lateSub')} />
<Stat label={t('finance.exp.shown')} value={fmt.formatMoney(shown.total)}
sub={t('finance.exp.shownSub', { paid: fmt.formatMoney(shown.paid), count: rows.length })} />
</div>
<div className="flex flex-wrap items-center gap-2">
<div className="relative flex-1 min-w-56">
<Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-ink-3" aria-hidden="true" />
<Input value={filter.q} onChange={e => set('q', e.target.value)} placeholder={t('finance.exp.search')} aria-label={t('finance.exp.search')} className="pl-9" />
</div>
<Select size="sm" value={filter.status} onChange={e => set('status', e.target.value)} aria-label={t('finance.exp.status')} data-testid="expenses-status"
options={[{ value: '', label: t('finance.exp.all') }, { value: 'unpaid', label: t('finance.exp.unpaidOnly') },
...['due', 'partial', 'paid'].map(s => ({ value: s, label: t(`finance.status.${s}`) }))]} />
<Select size="sm" value={filter.category} onChange={e => set('category', e.target.value)} aria-label={t('finance.exp.category')}
options={[{ value: '', label: t('finance.exp.allCategories') }, ...CATEGORIES.map(c => ({ value: c, label: cat(c) }))]} />
</div>
{isPending ? <div className="py-10 flex justify-center"><Spinner /></div>
: !all.length ? <EmptyState icon={<Receipt size={28} />} title={t('finance.exp.none')} description={t('finance.exp.noneHint')} />
: (
<Panel padded={false}>
<Table columns={columns} rows={rows} onRow={e => open('view', e)} rowTestId="expense-row" empty={t('finance.exp.noMatch')}
initialSort={{ key: 'created_at', dir: 'desc' }} />
</Panel>
)}
</div>
{(dialog?.kind === 'new' || dialog?.kind === 'edit') && <ExpenseDialog expense={dialog.expense} onClose={close} onSaved={saved} />}
{dialog?.kind === 'pay' && <ExpensePayDialog expense={dialog.expense} onClose={close} onSaved={saved} />}
{dialog?.kind === 'view' && (
<ExpenseView expense={dialog.expense} cat={cat} onClose={close}
onPay={() => open('pay', dialog.expense)} onEdit={() => open('edit', dialog.expense)} />
)}
{dialog?.kind === 'delete' && (
<Dialog open size="sm" onClose={close} title={t('finance.exp.deleteTitle', { what: dialog.expense.description })}
description={dialog.expense.payments?.length ? t('finance.exp.deleteBodyPaid', { count: dialog.expense.payments.length }) : t('finance.exp.deleteBody')}
footer={<>
<Button variant="secondary" onClick={close}>{t('finance.back')}</Button>
<Button variant="danger" loading={remove.isPending} onClick={() => remove.mutate(dialog.expense)} data-testid="expense-delete-confirm">{t('finance.exp.deleteYes')}</Button>
</>} />
)}
</div>
)
}
/** One expense: amounts, who entered it, notes and every payment. */
function ExpenseView({ expense: e, cat, onClose, onPay, onEdit }) {
const { t } = useTranslation('manager')
const fmt = useFormat()
return (
<Dialog open size="md" onClose={onClose} title={e.description}
description={[cat(e.category), e.contact_name, t('finance.exp.enteredBy', { date: fmt.formatDate(e.created_at), name: e.created_by_name ?? '' })].filter(Boolean).join(' · ')}
footer={<>
<Button variant="secondary" onClick={onClose}>{t('finance.back')}</Button>
<Button variant="secondary" icon={<Pencil size={14} />} onClick={onEdit}>{t('finance.exp.edit')}</Button>
{e.status !== 'paid' && <Button icon={<Banknote size={14} />} onClick={onPay}>{t('finance.exp.pay')}</Button>}
</>}>
<div className="grid gap-3 text-body" data-testid="expense-view">
<div className="grid grid-cols-3 gap-2">
<Figure label={t('finance.exp.total')} value={fmt.formatMoney(e.total_amount)} />
<Figure label={t('finance.exp.paid')} value={fmt.formatMoney(e.paid_amount)} tone="text-success-ink" />
<Figure label={t('finance.exp.due')} value={fmt.formatMoney(e.due_amount)} tone={e.due_amount > 0 ? 'text-danger-ink' : undefined} />
</div>
{e.due_date && <p className="text-label text-ink-2">{t('finance.exp.dueOn', { date: fmt.formatDate(e.due_date) })}</p>}
{e.notes && <p className="text-label text-ink-2 whitespace-pre-wrap">{e.notes}</p>}
<h3 className="text-caption font-semibold uppercase tracking-wide text-ink-3">{t('finance.exp.payments')}</h3>
{e.payments?.length ? (
<ul className="divide-y divide-line">
{e.payments.map(p => (
<li key={p.id} className="py-1.5 flex justify-between gap-3 text-label">
<span>{fmt.formatDateTime(p.paid_at, 'datetimeShort')}{p.paid_by_name ? ` · ${p.paid_by_name}` : ''}{p.notes ? ` · ${p.notes}` : ''}</span>
<b className="tabular-nums text-success-ink">{fmt.formatMoney(p.amount)}</b>
</li>
))}
</ul>
) : <p className="text-label text-ink-3">{t('finance.exp.noPayments')}</p>}
</div>
</Dialog>
)
}
function Figure({ label, value, tone }) {
return (
<div className="rounded-card bg-surface-2 p-3 grid gap-0.5 text-center">
<span className="text-caption font-semibold uppercase tracking-wide text-ink-3">{label}</span>
<span className={`text-body font-semibold tabular-nums ${tone ?? 'text-ink'}`}>{value}</span>
</div>
)
}