// 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 => {e.product_name} }, { 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 => ( {reason(e.reason)} {e.reason_notes && {e.reason_notes}}) }, { 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) : {t('waste.noCost')}) }, ...(deletable ? [{ key: 'del', label: '', sort: false, render: e => ( setRemoving(e)}>) }] : []), ] return ( {t('waste.title')} {t('waste.subtitle')} { today.refetch(); history.refetch() }} dayOpen={!!dayId} /> {t('waste.todaySum', { count: totals.count, cost: fmt.formatMoney(totals.cost) })}}> {!dayId ? {t('waste.noDay')} : today.isPending ? : } {t('waste.history')} {rows.length > 0 && ( fmt.formatMoney(v)} rows={group('reason', e => reason(e.reason)).map(g => ({ ...g, sub: t('waste.times', { count: g.count }) }))} /> 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 }) }) }))} /> )} {history.isPending ? : } {removing && ( setRemoving(null)} title={t('waste.deleteTitle', { name: removing.product_name })} footer={<> setRemoving(null)}>{t('waste.back')} remove.mutate(removing)}>{t('waste.deleteYes')} >} /> )} ) } 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 ( 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 }))]} /> set('qty', e.target.value)} data-testid="waste-qty" /> {REASONS.map(r => ( set('reason', r)}> {t(`waste.reasons.${r}`)} ))} set('notes', e.target.value)} placeholder={t('waste.noteHint')} /> } loading={log.isPending} onClick={submit} data-testid="waste-log">{t('waste.logIt')} {!dayOpen && {t('waste.noDayHint')}} ) }
{t('waste.subtitle')}
{t('waste.noDay')}