Files
xenia-pos-local/manager_dashboard/src/pages/reports/expenses/ExpensesReport.jsx
T
bonaminandClaude Opus 5.5 93c0dd7d9c 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>
2026-11-19 12:54:21 +02:00

96 lines
6.9 KiB
React

// Reports → Expenses (plan step 6.12c; replaces the v1 expenses report): what the venue spent in
// a period (by the day each expense was entered), paid and still due; split by category or by
// supplier; every expense, a tap shows its payments. Entering expenses is Finance → Expenses.
// The period is filtered by the server (venue dates, 6.13a); categories / statuses are `finance.*` texts.
import { useState } from 'react'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog, Select } from '@xenia/ui'
import client from '../../../api/client'
import { useLiveQuery } from '../../../live/useLiveQuery'
import { Pill } from '../../overview/parts'
import { BarList } from '../kit/charts'
import { Failed, Loading, Panel, ReportPage, Stat, Table } from '../kit/parts'
import { PeriodPicker } from '../kit/Period'
import { defaultPeriod } from '../kit/reportLogic'
import { CATEGORIES, STATUS_TONE } from '../../finance/financeLogic'
export default function ExpensesReport() {
const { t } = useTranslation('manager')
return <ReportPage title={t('reports.exp.title')} testId="report-expenses"><Expenses /></ReportPage>
}
function Expenses() {
const { t } = useTranslation('manager')
const fmt = useFormat()
const [period, setPeriod] = useState(() => defaultPeriod(fmt.venueToday()))
const [status, setStatus] = useState('')
const [category, setCategory] = useState('')
const [split, setSplit] = useState('category')
const [open, setOpen] = useState(null)
const params = { ...(period.from ? { from: period.from } : {}), ...(period.to ? { to: period.to } : {}), ...(status ? { status } : {}), ...(category ? { category } : {}) }
const { data, isPending, error, refetch } = useLiveQuery({ queryKey: ['report-expenses', params], queryFn: () => client.get('/api/expenses/', { params }).then(r => r.data), events: ['expenses.changed'] })
const catName = c => t(`finance.categories.${c}`, { defaultValue: c })
const rows = data ?? []
const sum = k => rows.reduce((s, e) => s + (e[k] ?? 0), 0)
const groups = Object.values(rows.reduce((m, e) => {
const k = split === 'category' ? e.category : (e.contact_name || t('reports.exp.noSupplier'))
m[k] = m[k] ?? { key: k, label: split === 'category' ? catName(k) : k, value: 0, due: 0 }
m[k].value += e.total_amount
m[k].due += e.due_amount
return m
}, {})).sort((a, b) => b.value - a.value)
const columns = [
{ key: 'created_at', label: t('reports.exp.date'), render: e => fmt.formatDate(e.created_at) },
{ key: 'description', label: t('reports.exp.what'), render: e => <span className="font-semibold text-ink">{e.description}</span> },
{ key: 'category', label: t('reports.prod.category'), sort: e => catName(e.category), render: e => catName(e.category) },
{ key: 'contact_name', label: t('reports.exp.supplier'), render: e => e.contact_name || '' },
{ key: 'total_amount', label: t('reports.exp.total'), align: 'right', render: e => fmt.formatMoney(e.total_amount) },
{ key: 'due_amount', label: t('reports.exp.due'), align: 'right', render: e => (e.due_amount ? <span className="text-danger-ink">{fmt.formatMoney(e.due_amount)}</span> : '') },
{ key: 'status', label: t('reports.status'), render: e => <Pill tone={STATUS_TONE[e.status] ?? 'neutral'}>{t(`finance.status.${e.status}`, { defaultValue: e.status })}</Pill> },
]
return (
<div className="grid gap-4">
<PeriodPicker value={period} onChange={setPeriod} allowDay={false} right={<span className="flex gap-2 items-end">
<Select size="sm" value={status} onChange={e => setStatus(e.target.value)} aria-label={t('reports.status')}
options={[{ value: '', label: t('reports.store.anyStatus') }, ...['due', 'partial', 'paid'].map(s => ({ value: s, label: t(`finance.status.${s}`) }))]} />
<Select size="sm" value={category} onChange={e => setCategory(e.target.value)} aria-label={t('reports.prod.category')}
options={[{ value: '', label: t('reports.prod.allCategories') }, ...CATEGORIES.map(c => ({ value: c, label: catName(c) }))]} />
</span>} />
{isPending ? <Loading /> : error ? <Failed error={error} retry={refetch} /> : (<>
<div className="grid gap-3 grid-cols-[repeat(auto-fill,minmax(12rem,1fr))]">
<Stat label={t('reports.exp.spent')} value={fmt.formatMoney(sum('total_amount'))} sub={t('reports.exp.count', { count: rows.length })} testId="expenses-total" />
<Stat label={t('reports.exp.paid')} tone="success" value={fmt.formatMoney(sum('paid_amount'))} />
<Stat label={t('reports.exp.due')} tone={sum('due_amount') ? 'danger' : undefined} value={fmt.formatMoney(sum('due_amount'))} />
</div>
{groups.length > 0 && (
<Panel title={t('reports.exp.split')} actions={<span className="flex gap-1">{['category', 'supplier'].map(s => (
<Button key={s} size="sm" variant={split === s ? 'primary' : 'ghost'} onClick={() => setSplit(s)}>{t(`reports.exp.by.${s}`)}</Button>))}</span>}>
<BarList testId="expenses-split" format={v => fmt.formatMoney(v)} rows={groups.map(g => ({ ...g, sub: g.due ? t('reports.exp.dueSub', { amount: fmt.formatMoney(g.due) }) : undefined }))} />
</Panel>
)}
<Panel padded={false} title={t('reports.exp.list')}>
<Table columns={columns} rows={rows} onRow={setOpen} rowTestId="report-expense" initialSort={{ key: 'created_at', dir: 'desc' }} />
</Panel>
</>)}
{open && (
<Dialog open size="sm" onClose={() => setOpen(null)} title={open.description}
description={`${catName(open.category)}${open.contact_name ? ` · ${open.contact_name}` : ''} · ${fmt.formatDate(open.created_at)}`}
footer={<Button variant="secondary" onClick={() => setOpen(null)}>{t('reports.back')}</Button>}>
<div className="grid gap-2 text-body">
<p>{t('reports.exp.total')}: <b>{fmt.formatMoney(open.total_amount)}</b> · {t('reports.exp.paid')}: <b>{fmt.formatMoney(open.paid_amount)}</b>{open.due_amount ? <> · {t('reports.exp.due')}: <b className="text-danger-ink">{fmt.formatMoney(open.due_amount)}</b></> : null}</p>
{open.due_date && <p className="text-label text-ink-2">{t('reports.exp.dueDate', { date: fmt.formatDate(open.due_date) })}</p>}
{open.notes && <p className="text-label text-ink-2">{open.notes}</p>}
<h3 className="text-caption font-semibold uppercase tracking-wide text-ink-3 mt-2">{t('reports.exp.payments')}</h3>
{open.payments?.length ? (
<ul className="divide-y divide-line">
{open.payments.map(p => <li key={p.id} className="py-1.5 flex justify-between text-label"><span>{fmt.formatDate(p.paid_at)}{p.paid_by_name ? ` · ${p.paid_by_name}` : ''}{p.notes ? ` · ${p.notes}` : ''}</span><b className="tabular-nums">{fmt.formatMoney(p.amount)}</b></li>)}
</ul>
) : <p className="text-label text-ink-3">{t('reports.exp.noPayments')}</p>}
</div>
</Dialog>
)}
</div>
)
}