- Online orders -> Settings: takeaway / delivery / any time side by side (wrapping, with room), the days of the week apart; fee rules, delivery areas and fee settings (the fee line) as tabs on the left, Test an order on the right; a rule's switch at the far right, equal padding, 'Order price from' / 'Total items count from' in the rule editor. - Expenses: the dialog lists what was bought (quantity, price before VAT, VAT; they make the total, with net / VAT / total) and keeps documents (attach a PDF or photo, open, remove; picked for a new expense, uploaded when it's saved); a paperclip in the list. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
162 lines
10 KiB
React
162 lines
10 KiB
React
// 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, Trash2, Paperclip } from 'lucide-react'
|
|
import { errorMessage } from '@xenia/api'
|
|
import { useFormat, useTranslation } from '@xenia/i18n'
|
|
import { Button, Dialog, Dropdown, EmptyState, IconButton, Page, PageHeader, SearchInput, Spinner, Toolbar } 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()
|
|
// what's still to pay first: due + partly paid (= v1's "unpaid")
|
|
const [filter, setFilter] = useState({ status: ['due', 'partial'], 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 flex items-center gap-1.5">{e.description}
|
|
{e.documents?.length > 0 && <Paperclip size={13} className="text-ink-3" aria-label={t('finance.exp.documents')} />}</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 (
|
|
<Page testId="expenses-page">
|
|
<PageHeader title={t('finance.exp.title')} subtitle={t('finance.exp.subtitle')}
|
|
actions={<Button icon={<Plus size={16} />} onClick={() => open('new')} data-testid="expense-new">{t('finance.exp.new')}</Button>} />
|
|
|
|
<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>
|
|
|
|
<Toolbar>
|
|
<SearchInput value={filter.q} onChange={v => set('q', v)} placeholder={t('finance.exp.search')} />
|
|
<Dropdown multiple value={filter.status} onChange={v => set('status', v)} aria-label={t('finance.exp.status')} data-testid="expenses-status" allLabel={t('finance.exp.all')}
|
|
options={['due', 'partial', 'paid'].map(s => ({ value: s, label: t(`finance.status.${s}`) }))} />
|
|
<Dropdown multiple value={filter.category} onChange={v => set('category', v)} aria-label={t('finance.exp.category')} allLabel={t('finance.exp.allCategories')}
|
|
options={CATEGORIES.map(c => ({ value: c, label: cat(c) }))} />
|
|
</Toolbar>
|
|
|
|
{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>
|
|
)}
|
|
|
|
{(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>
|
|
</>} />
|
|
)}
|
|
</Page>
|
|
)
|
|
}
|
|
|
|
/** 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-overline 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-overline font-semibold uppercase tracking-wide text-ink-3">{label}</span>
|
|
<span className={`text-body font-semibold tabular-nums ${tone ?? 'text-ink'}`}>{value}</span>
|
|
</div>
|
|
)
|
|
}
|