From the owner's page-by-page review (2026-11-20): - every page root is <Page> (scrolls, fills 1080p, 16:9 centred on ultrawides); not yet: products, management/tables, stock (next pass) - /dashboard: more padding in cards (p-card), quieter secondary text, 11px uppercase labels everywhere (text-overline) - day stats: xl dialog, "● Day running · Opened …" as text, the six figures in equal boxes, "On tabs" in the payments bar, shared Tabs - /tables: Segmented List / Map / QR codes (?view=; /online/qr redirects), filter chips + zones multi-select at one height, the card itself opens the table (button removed), cards ~20% wider - /online-orders: shared Tabs with Settings (= the old /online/fees page, which redirects to ?tab=settings); orders fill the width - contacts, customers, expenses: PageHeader + Toolbar + SearchInput + multi-select Dropdowns (kinds; statuses, categories); table cells vertically centred; the Spent tip opens on hover - filterCards / filterContacts / filterExpenses take several values (unit tests added) - docs/DESIGN.md: the design language (CS-20 in the pack README) - tests/e2e/manager_layout.mjs: the page rule at 1920x1080 and 3440x1440; manager.mjs and manager_look.mjs follow the moved pages Verified: manager build + lint (0 errors), unit tests (manager 99, ui 24, i18n 31, api 25, access 8), i18n guard, manager_layout.mjs all passed, manager.mjs 228 checks all passed. Not checked: the waiter app and the terminal by eye (they only get the muted ink-2 token). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
162 lines
9.9 KiB
React
162 lines
9.9 KiB
React
// Inventory → Throwaways (plan step 6.13b; replaces the v1 WastePage): log what was thrown away
|
|
// (a product, how many, why, a note), with its cost at that moment when the product has a cost,
|
|
// in the open business day. Today's entries (deletable today only) and the history of a period:
|
|
// totals, by reason, by product, every entry. Live: `waste.changed`.
|
|
import { useState } from 'react'
|
|
import { useMutation } from '@tanstack/react-query'
|
|
import toast from 'react-hot-toast'
|
|
import { Plus, Trash2 } from 'lucide-react'
|
|
import { errorMessage } from '@xenia/api'
|
|
import { useFormat, useTranslation } from '@xenia/i18n'
|
|
import { Button, Dialog, Field, IconButton, Input, Page, Select, Spinner } from '@xenia/ui'
|
|
import client from '../../api/client'
|
|
import { useLiveQuery } from '../../live/useLiveQuery'
|
|
import { Pill } from '../overview/parts'
|
|
import { BarList } from '../reports/kit/charts'
|
|
import { PeriodPicker } from '../reports/kit/Period'
|
|
import { Panel, Stat, Table } from '../reports/kit/parts'
|
|
import { defaultPeriod } from '../reports/kit/reportLogic'
|
|
import { REASONS, REASON_TONE, wasteProducts, wasteQuantity, wasteTotals } from './wasteLogic'
|
|
|
|
const LIVE = ['waste.changed']
|
|
|
|
export default function ThrowawaysPage() {
|
|
const { t } = useTranslation('manager')
|
|
const fmt = useFormat()
|
|
const [period, setPeriod] = useState(() => defaultPeriod(fmt.venueToday()))
|
|
const [removing, setRemoving] = useState(null)
|
|
const { data: day } = useLiveQuery({ queryKey: ['business-day'], queryFn: () => client.get('/api/business-day/current').then(r => r.data), refetchInterval: 60_000 })
|
|
const dayId = day?.id ?? null
|
|
const today = useLiveQuery({
|
|
queryKey: ['waste', 'day', dayId], enabled: !!dayId, events: LIVE,
|
|
queryFn: () => client.get('/api/waste/', { params: { business_day_id: dayId } }).then(r => r.data.entries),
|
|
})
|
|
const params = { ...(period.from ? { date_from: period.from } : {}), ...(period.to ? { date_to: period.to } : {}) }
|
|
const history = useLiveQuery({ queryKey: ['waste', 'period', params], events: LIVE, queryFn: () => client.get('/api/waste/', { params }).then(r => r.data.entries) })
|
|
const todayRows = today.data ?? []
|
|
const rows = history.data ?? []
|
|
const totals = wasteTotals(todayRows)
|
|
const periodTotals = wasteTotals(rows)
|
|
const remove = useMutation({
|
|
mutationFn: e => client.delete(`/api/waste/${e.id}`),
|
|
onSuccess: () => { toast.success(t('waste.deleted')); setRemoving(null); today.refetch(); history.refetch() },
|
|
onError: err => toast.error(errorMessage(err, t)),
|
|
})
|
|
const reason = r => t(`waste.reasons.${r}`, { defaultValue: r })
|
|
const group = (key, label) => Object.values(rows.reduce((m, e) => {
|
|
const k = e[key]
|
|
m[k] = m[k] ?? { key: k, label: label(e), value: 0, count: 0 }
|
|
m[k].value += e.total_cost ?? 0
|
|
m[k].count += key === 'reason' ? 1 : e.quantity
|
|
return m
|
|
}, {})).sort((a, b) => b.value - a.value || b.count - a.count)
|
|
|
|
const columns = (deletable) => [
|
|
{ key: 'logged_at', label: t('waste.when'), render: e => fmt.formatDateTime(e.logged_at, 'datetimeShort') },
|
|
{ key: 'product_name', label: t('waste.product'), render: e => <span className="font-semibold text-ink">{e.product_name}</span> },
|
|
{ key: 'quantity', label: t('waste.quantity'), align: 'right', render: e => fmt.formatNumber(e.quantity, { maxDecimals: 3 }) },
|
|
{ key: 'reason', label: t('waste.reason'), sort: e => reason(e.reason), render: e => (
|
|
<span className="grid gap-0.5"><Pill tone={REASON_TONE[e.reason] ?? 'neutral'} className="justify-self-start">{reason(e.reason)}</Pill>
|
|
{e.reason_notes && <span className="text-caption text-ink-2">{e.reason_notes}</span>}</span>) },
|
|
{ key: 'logged_by_name', label: t('waste.by') },
|
|
{ key: 'total_cost', label: t('waste.cost'), align: 'right', render: e => (e.total_cost != null ? fmt.formatMoney(e.total_cost) : <span className="text-ink-3">{t('waste.noCost')}</span>) },
|
|
...(deletable ? [{ key: 'del', label: '', sort: false, render: e => (
|
|
<IconButton size="sm" variant="ghost" label={t('waste.deleteOf', { name: e.product_name })} onClick={() => setRemoving(e)}><Trash2 size={15} /></IconButton>) }] : []),
|
|
]
|
|
|
|
return (
|
|
<Page testId="waste-page">
|
|
<header>
|
|
<h1 className="text-title font-semibold text-ink">{t('waste.title')}</h1>
|
|
<p className="text-label text-ink-2">{t('waste.subtitle')}</p>
|
|
</header>
|
|
<LogForm onLogged={() => { today.refetch(); history.refetch() }} dayOpen={!!dayId} />
|
|
<Panel padded={false} title={t('waste.today')} testId="waste-today"
|
|
actions={<span className="text-label text-ink-2">{t('waste.todaySum', { count: totals.count, cost: fmt.formatMoney(totals.cost) })}</span>}>
|
|
{!dayId ? <p className="p-4 text-label text-ink-3">{t('waste.noDay')}</p>
|
|
: today.isPending ? <div className="p-4"><Spinner /></div>
|
|
: <Table columns={columns(true)} rows={todayRows} rowTestId="waste-today-row" empty={t('waste.noneToday')} initialSort={{ key: 'logged_at', dir: 'desc' }} />}
|
|
</Panel>
|
|
|
|
<h2 className="text-body font-semibold text-ink mt-2">{t('waste.history')}</h2>
|
|
<PeriodPicker value={period} onChange={setPeriod} allowDay={false} />
|
|
<div className="grid gap-3 grid-cols-[repeat(auto-fill,minmax(12rem,1fr))]">
|
|
<Stat label={t('waste.cost')} tone={periodTotals.cost ? 'danger' : undefined} value={fmt.formatMoney(periodTotals.cost)}
|
|
sub={periodTotals.uncosted ? t('waste.uncosted', { count: periodTotals.uncosted }) : undefined} testId="waste-period-cost" />
|
|
<Stat label={t('waste.entries')} value={fmt.formatNumber(periodTotals.count)} />
|
|
</div>
|
|
{rows.length > 0 && (
|
|
<div className="grid gap-4 lg:grid-cols-2">
|
|
<Panel title={t('waste.byReason')}>
|
|
<BarList format={v => fmt.formatMoney(v)} rows={group('reason', e => reason(e.reason)).map(g => ({ ...g, sub: t('waste.times', { count: g.count }) }))} />
|
|
</Panel>
|
|
<Panel title={t('waste.byProduct')}>
|
|
<BarList format={v => fmt.formatMoney(v)} rows={group('product_id', e => e.product_name).slice(0, 10).map(g => ({ ...g, sub: t('waste.units', { qty: fmt.formatNumber(g.count, { maxDecimals: 3 }) }) }))} />
|
|
</Panel>
|
|
</div>
|
|
)}
|
|
<Panel padded={false} title={t('waste.every')}>
|
|
{history.isPending ? <div className="p-4"><Spinner /></div>
|
|
: <Table columns={columns(false)} rows={rows} rowTestId="waste-row" empty={t('waste.noneInPeriod')} initialSort={{ key: 'logged_at', dir: 'desc' }} />}
|
|
</Panel>
|
|
{removing && (
|
|
<Dialog open size="sm" onClose={() => setRemoving(null)} title={t('waste.deleteTitle', { name: removing.product_name })}
|
|
footer={<>
|
|
<Button variant="secondary" onClick={() => setRemoving(null)}>{t('waste.back')}</Button>
|
|
<Button variant="danger" loading={remove.isPending} onClick={() => remove.mutate(removing)}>{t('waste.deleteYes')}</Button>
|
|
</>} />
|
|
)}
|
|
</Page>
|
|
)
|
|
}
|
|
|
|
function LogForm({ onLogged, dayOpen }) {
|
|
const { t, i18n } = useTranslation('manager')
|
|
const fmt = useFormat()
|
|
const [form, setForm] = useState({ product_id: '', qty: '1', reason: 'kitchen_error', notes: '' })
|
|
const [tried, setTried] = useState(false)
|
|
const set = (k, v) => setForm(f => ({ ...f, [k]: v }))
|
|
const { data: products = [] } = useLiveQuery({ queryKey: ['products', 'all'], queryFn: () => client.get('/api/products/').then(r => r.data), staleTime: 300_000 })
|
|
const qty = wasteQuantity(form.qty)
|
|
const log = useMutation({
|
|
mutationFn: () => client.post('/api/waste/', { product_id: Number(form.product_id), quantity: qty, reason: form.reason, reason_notes: form.notes.trim() || null }).then(r => r.data),
|
|
onSuccess: e => {
|
|
toast.success(e.total_cost != null ? t('waste.loggedCost', { name: e.product_name, cost: fmt.formatMoney(e.total_cost) }) : t('waste.logged', { name: e.product_name }))
|
|
setForm(f => ({ ...f, product_id: '', qty: '1', notes: '' })); setTried(false); onLogged()
|
|
},
|
|
onError: err => toast.error(errorMessage(err, t)),
|
|
})
|
|
const submit = () => { setTried(true); if (form.product_id && qty != null) log.mutate() }
|
|
return (
|
|
<Panel title={t('waste.log')} testId="waste-form">
|
|
<div className="grid gap-3">
|
|
<div className="grid gap-3 sm:grid-cols-[2fr_1fr]">
|
|
<Field label={t('waste.product')} required error={tried && !form.product_id ? t('waste.pickProduct') : undefined}>
|
|
<Select value={form.product_id} onChange={e => set('product_id', e.target.value)} data-testid="waste-product"
|
|
options={[{ value: '', label: t('waste.choose') }, ...wasteProducts(products, i18n.language).map(p => ({ value: String(p.id), label: p.name }))]} />
|
|
</Field>
|
|
<Field label={t('waste.quantity')} required error={tried && qty == null ? t('waste.wrongQty') : undefined}>
|
|
<Input inputMode="decimal" value={form.qty} onChange={e => set('qty', e.target.value)} data-testid="waste-qty" />
|
|
</Field>
|
|
</div>
|
|
<Field label={t('waste.reason')}>
|
|
<span className="flex flex-wrap gap-1" role="radiogroup" aria-label={t('waste.reason')}>
|
|
{REASONS.map(r => (
|
|
<Button key={r} size="sm" variant={form.reason === r ? 'primary' : 'secondary'} role="radio" aria-checked={form.reason === r} onClick={() => set('reason', r)}>
|
|
{t(`waste.reasons.${r}`)}
|
|
</Button>
|
|
))}
|
|
</span>
|
|
</Field>
|
|
<Field label={t('waste.note')}>
|
|
<Input value={form.notes} onChange={e => set('notes', e.target.value)} placeholder={t('waste.noteHint')} />
|
|
</Field>
|
|
<div className="flex flex-wrap items-center gap-3">
|
|
<Button icon={<Plus size={16} />} loading={log.isPending} onClick={submit} data-testid="waste-log">{t('waste.logIt')}</Button>
|
|
{!dayOpen && <span className="text-caption text-ink-3">{t('waste.noDayHint')}</span>}
|
|
</div>
|
|
</div>
|
|
</Panel>
|
|
)
|
|
}
|