feat: tables and orders in the manager on v2 (platform-v2 step 6.9)

- manager: new pages/orders/ (Tables page cards + quick actions, order page with
  lines, multi-select pay/discount/cancel/tab, staff + customer, price changes,
  history, the menu + cart beside it); a free table opens a new order on first
  Send; v1 TablesPage, OrderDetailPage, DesktopOrderingTab, ManagerOrderDrawer
  and PaymentMethodModal removed
- ordering by line id like the phones: GET /api/orders/menu (the counter's
  product shape, in-store prices); the product dialog, cart rules and quote hook
  move to packages/ordering (@xenia/ordering), shared by counter, menu tablet,
  manager
- close follows orders.close_with_unpaid (pay first, or write off after saying
  so) on the order page and the overview's quick view; paying asks cash or card
- a confirmed booking can keep its table ahead (manager, phones, counter):
  POST /api/connect/bookings/{id}/table, reservations create/PATCH; refused with
  reservation.table_kept within 2 h of another booking
- tests: test_manager_ordering.py, online bookings +2, manager orders.test.mjs,
  @xenia/ordering, e2e manager.mjs (take, change, pay-first close, RESERVED)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-18 21:58:46 +02:00
co-authored by Claude Opus 5.5
parent f4aae6abbc
commit 070c9cf625
56 changed files with 2339 additions and 3846 deletions
@@ -0,0 +1,135 @@
// Adding to a table's order from the manager (plan step 6.9), by the phones' rules: the menu
// (GET /api/orders/menu: in-store prices, the counter's product shape), a tap adds a product (one
// with a preference to pick opens its choices: the shared dialog, @xenia/ordering), the cart is
// priced by the server (POST /api/orders/quote with the order, so deals and the order's sales
// point count), and "Send" adds the lines by id (POST /api/orders/{id}/items; a new order is
// opened first). Prices are never sent.
import { useMemo, useState } from 'react'
import toast from 'react-hot-toast'
import { Minus, Plus, Search, Send, Trash2 } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n'
import {
ProductDialog, addLine, categoriesWithProducts, defaultSelection, needsChoices, productsIn, searchProducts, setLineQty, toLine, unitOf, useQuote,
} from '@xenia/ordering'
import { Button, EmptyState, IconButton, Input, Spinner, Textarea, cx } from '@xenia/ui'
import client from '../../api/client'
import { useLiveQuery } from '../../live/useLiveQuery'
import { sendBody } from './orderLogic'
const SERVICE = '__service__'
export default function AddItems({ orderId, onSent, openOrder }) {
const { t } = useTranslation('manager')
const { formatMoney } = useFormat()
const { data: menu } = useLiveQuery({ queryKey: ['ordering-menu'], queryFn: () => client.get('/api/orders/menu').then(r => r.data),
events: ['products_changed', 'pricing.changed'], staleTime: 30_000 })
const [category, setCategory] = useState(null)
const [query, setQuery] = useState('')
const [cart, setCart] = useState([])
const [note, setNote] = useState('')
const [choosing, setChoosing] = useState(null)
const [busy, setBusy] = useState(false)
const fetchQuote = lines => client.post('/api/orders/quote', { order_id: orderId ?? undefined, order_type: 'here', lines }).then(r => r.data)
const { quote, pending, error } = useQuote(fetchQuote, cart, String(orderId ?? 'new'))
const products = useMemo(() => (menu?.products ?? []), [menu])
const cats = useMemo(() => categoriesWithProducts((menu?.categories ?? []).filter(c => !c.parent_id), products.filter(p => !p.service)), [menu, products])
const shown = query.trim() ? searchProducts(products, query)
: category === SERVICE ? products.filter(p => p.service)
: productsIn(products.filter(p => !p.service), category)
const byId = id => products.find(p => p.id === id)
const tap = p => {
if (!p.available) return
if (needsChoices(p)) { setChoosing(p); return }
const unit = unitOf(p)
setCart(c => addLine(c, toLine(p, defaultSelection(p), unit ? unit.start : 1)))
}
const send = async () => {
setBusy(true)
try {
const id = orderId ?? (await openOrder())
const { data } = await client.post(`/api/orders/${id}/items`, sendBody(cart.map(line => ({ line })), note))
const failed = (data.print_results ?? []).filter(r => !r.success)
if (failed.length) toast.error(t('orders.add.notPrinted', { printers: failed.map(r => r.printer_name).join(', ') }))
else toast.success(t('orders.add.sent'))
setCart([])
setNote('')
onSent(id)
} catch (err) { toast.error(errorMessage(err, t)) } finally { setBusy(false) }
}
if (!menu) return <div className="flex justify-center p-6"><Spinner /></div>
return (
<section className="grid gap-3 content-start min-w-0" data-testid="order-add">
<div className="flex items-center gap-2">
<div className="relative flex-1">
<Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-ink-3" aria-hidden="true" />
<Input value={query} onChange={e => setQuery(e.target.value)} placeholder={t('orders.add.search')} aria-label={t('orders.add.search')} className="pl-9" data-testid="order-search" />
</div>
</div>
{!query.trim() && (
<div className="flex flex-wrap gap-1.5" role="tablist">
{[{ id: null, name: t('orders.add.all') }, ...cats, ...(products.some(p => p.service) ? [{ id: SERVICE, name: t('orders.add.service') }] : [])].map(c => (
<button key={c.id ?? 'all'} type="button" role="tab" aria-selected={category === c.id} onClick={() => setCategory(c.id)}
className={cx('px-3 py-1.5 rounded-full border text-label font-medium', category === c.id ? 'border-accent bg-accent-soft text-accent-ink' : 'border-line bg-surface text-ink-2 hover:bg-surface-2')}>
{c.name}
</button>
))}
</div>
)}
{shown.length === 0 ? <EmptyState compact title={t('orders.add.nothing')} /> : (
<div className="grid gap-2 max-h-[45vh] overflow-y-auto pr-1" style={{ gridTemplateColumns: 'repeat(auto-fill, minmax(9.5rem, 1fr))' }}>
{shown.map(p => (
<button key={p.id} type="button" onClick={() => tap(p)} disabled={!p.available} data-testid="order-product" data-id={p.id} data-name={p.name}
className={cx('min-h-20 p-2.5 rounded-control border text-left grid content-between gap-1 transition-colors duration-fast',
p.available ? 'border-line bg-surface hover:border-accent hover:bg-accent-soft' : 'border-line bg-surface-2 opacity-50 cursor-not-allowed')}>
<span className="text-label font-semibold text-ink line-clamp-2">{p.name}</span>
<span className="text-caption text-ink-2 tabular-nums">{p.available ? formatMoney(p.price) : t('orders.add.soldOut')}{needsChoices(p) ? ' · …' : ''}</span>
</button>
))}
</div>
)}
<div className="grid gap-2 p-3 rounded-card border border-line bg-surface shadow-raised" data-testid="order-cart">
<h3 className="text-label font-semibold text-ink">{t('orders.add.toSend')}</h3>
{cart.length === 0 ? <p className="text-caption text-ink-3">{t('orders.add.empty')}</p> : (
<ul className="grid divide-y divide-line">
{cart.map((line, i) => {
const priced = quote?.lines?.[i]
const p = byId(line.product_id)
const unit = p ? unitOf(p) : null
const step = unit ? unit.step : 1
return (
<li key={i} className="py-1.5 flex items-center gap-2" data-testid="cart-line">
<span className="flex-1 min-w-0">
<span className="block text-label font-medium text-ink truncate">{p?.name ?? priced?.name}</span>
{priced?.entries?.length > 0 && <span className="block text-caption text-ink-2 truncate">{priced.entries.map(e => e.name).join(', ')}</span>}
</span>
<IconButton size="sm" variant="secondary" label={t('orders.add.less')} onClick={() => setCart(c => setLineQty(c, i, line.quantity - step))}>
{line.quantity - step <= 0 ? <Trash2 size={14} /> : <Minus size={14} />}
</IconButton>
<span className="w-12 text-center text-label font-semibold tabular-nums" data-testid="cart-qty">{unit ? `${line.quantity} ${unit.label}` : line.quantity}</span>
<IconButton size="sm" variant="secondary" label={t('orders.add.more')} onClick={() => setCart(c => setLineQty(c, i, line.quantity + step))}><Plus size={14} /></IconButton>
<span className="w-20 text-right text-label tabular-nums">{priced ? formatMoney(priced.total) : '…'}</span>
</li>
)
})}
</ul>
)}
{error && <p role="alert" className="text-label text-danger-ink">{errorMessage(error, t)}</p>}
<Textarea rows={2} maxLength={300} value={note} onChange={e => setNote(e.target.value)} placeholder={t('orders.add.note')} aria-label={t('orders.add.note')} />
<div className="flex items-center gap-3">
<span className="flex-1 text-body font-semibold text-ink tabular-nums" data-testid="cart-total">
{cart.length ? (quote && !pending ? formatMoney(quote.total) : '…') : ''}
</span>
{cart.length > 0 && <Button variant="ghost" onClick={() => setCart([])}>{t('orders.add.clear')}</Button>}
<Button icon={<Send size={16} />} disabled={!cart.length || !!error} loading={busy} onClick={send} data-testid="order-send">{t('orders.add.send')}</Button>
</div>
</div>
{choosing && <ProductDialog product={choosing} fetchQuote={fetchQuote} onClose={() => setChoosing(null)} onAdd={line => setCart(c => addLine(c, line))} />}
</section>
)
}
@@ -0,0 +1,76 @@
// What happened to a table's order (plan step 6.9): the audit log (opened, lines added, paid,
// cancelled, closed; a payment counted twice stands out) and the price changes (rules, deals,
// discounts, by whom).
import { useFormat, useTranslation } from '@xenia/i18n'
import { EmptyState, cx } from '@xenia/ui'
import { Pill } from '../overview/parts'
import { nameOf } from './orderLogic'
const EVENT_TONE = { PAYMENT: 'success', PAYMENT_OFFLINE: 'success', ORDER_CLOSED: 'neutral', ORDER_CANCELLED: 'danger', ITEM_CANCELLED: 'danger' }
const ids = raw => { try { return raw ? JSON.parse(raw) : [] } catch { return [] } }
export function AuditList({ order }) {
const { t } = useTranslation('manager')
const { formatDateTime, formatMoney } = useFormat()
const logs = order.audit_logs ?? []
if (!logs.length) return <EmptyState compact title={t('orders.history.none')} />
const byId = new Map(order.items.map(i => [i.id, i]))
return (
<ul className="divide-y divide-line" data-testid="order-audit">
{logs.map(log => {
const dup = !!log.is_duplicate
const names = ids(log.item_ids).map(id => byId.get(id)).filter(Boolean).map(i => `${nameOf(i)} ×${i.quantity}`)
return (
<li key={log.id} className={cx('px-4 py-2.5 flex items-start gap-3', dup && 'bg-danger-soft')}>
<span className="grid gap-0.5 shrink-0">
<Pill tone={dup ? 'danger' : EVENT_TONE[log.event_type] ?? 'info'}>{t(`orders.history.event.${log.event_type}`, { defaultValue: log.event_type })}</Pill>
{dup && <span className="text-caption font-semibold text-danger-ink">{t('orders.history.duplicate')}</span>}
</span>
<span className="flex-1 min-w-0 grid gap-1 text-label text-ink">
<span>
{log.waiter_name ?? (log.waiter_id ? `#${log.waiter_id}` : '')}
{log.amount != null && <span className="ml-2 font-semibold text-success-ink tabular-nums">{formatMoney(log.amount)}</span>}
{log.payment_method && <span className="ml-2 text-ink-2">{t(`orders.pay.method.${log.payment_method}`, { defaultValue: log.payment_method })}</span>}
</span>
{names.length > 0 && <span className="flex flex-wrap gap-1">{names.map((n, i) => <Pill key={i}>{n}</Pill>)}</span>}
{log.note && <span className="text-caption text-ink-3">{log.note}</span>}
</span>
<span className="text-caption text-ink-3 text-right shrink-0">
{formatDateTime(log.offline_at || log.created_at, 'datetimeShort')}
{log.offline_at && <span className="block text-warning-ink">{t('orders.history.offline')}</span>}
</span>
</li>
)
})}
</ul>
)
}
export function PriceEventList({ events }) {
const { t } = useTranslation('manager')
const { formatDateTime, formatMoney } = useFormat()
if (!events.length) return <EmptyState compact title={t('orders.history.noPrices')} />
return (
<ul className="divide-y divide-line" data-testid="order-price-events">
{events.map(ev => (
<li key={ev.id} className="px-4 py-2.5 flex items-start gap-3">
<Pill tone="info">{t(`orders.history.price.${ev.event_type}`, { defaultValue: ev.event_type })}</Pill>
<span className="flex-1 min-w-0 grid gap-0.5 text-label text-ink">
<span className="flex flex-wrap gap-x-3">
{(ev.modifier_name || ev.deal_name) && <span className="font-semibold">{ev.modifier_name || ev.deal_name}</span>}
{ev.applied_by_username && <span className="text-ink-3">{t('orders.history.by', { name: ev.applied_by_username })}</span>}
{ev.delta_amount != null && (
<span className={cx('font-semibold tabular-nums', ev.delta_amount < 0 ? 'text-success-ink' : 'text-danger-ink')}>
{formatMoney(ev.delta_amount, { signDisplay: 'exceptZero' })}
{ev.price_before != null && ev.price_after != null && <span className="font-normal text-ink-3"> ({formatMoney(ev.price_before)} → {formatMoney(ev.price_after)})</span>}
</span>
)}
</span>
{ev.waiter_note && <span className="text-caption text-ink-3 italic">{ev.waiter_note}</span>}
</span>
<span className="text-caption text-ink-3 shrink-0">{formatDateTime(ev.applied_at, 'datetimeShort')}</span>
</li>
))}
</ul>
)
}
@@ -0,0 +1,151 @@
// A table's order lines in the manager (plan step 6.9): what was ordered with its choices, who
// paid what and how, price changes; pick unpaid lines to pay, discount, cancel or put on the
// customer's tab. The rules are the phones' (a discount needs pricing.discounts.apply, the
// server checks every key again).
import { useState } from 'react'
import { useMutation } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import { Ban, CreditCard, Percent, Printer, Receipt } from 'lucide-react'
import { useCan } from '@xenia/access'
import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog, EmptyState, Field, Input, cx } from '@xenia/ui'
import client from '../../api/client'
import { Pill } from '../overview/parts'
import { lineAmount, lineDetails, nameOf, selectable, selectedAmount, shownLines, toggleSelected, unitOf } from './orderLogic'
const STATUS_TONE = { paid: 'success', cancelled: 'danger', tabbed: 'info', closed: 'warning' }
const EVENT_TONE = { waiter_discount: 'text-accent-ink', free_item_added: 'text-success-ink', modifier_applied: 'text-info-ink' }
export default function OrderLines({ order, open, priceEvents, onPay, onChanged }) {
const { t } = useTranslation('manager')
const { formatMoney, formatTime } = useFormat()
const canDiscount = useCan('pricing.discounts.apply')
const [selected, setSelected] = useState([])
const [cancelling, setCancelling] = useState(false)
const [discounting, setDiscounting] = useState(false)
const lines = shownLines(order)
const picked = selected.filter(id => order.items.some(i => i.id === id && selectable(i)))
const amount = selectedAmount(order, picked)
const done = msg => { toast.success(msg); setSelected([]); onChanged() }
const onError = err => toast.error(errorMessage(err, t))
const cancel = useMutation({
mutationFn: print => client.post(`/api/orders/${order.id}/cancel-items`, { item_ids: picked, print_cancellation: print }),
onSuccess: () => { setCancelling(false); done(t('orders.lines.cancelled', { count: picked.length })) }, onError,
})
const toTab = useMutation({
mutationFn: async () => { for (const id of picked) await client.post(`/api/orders/${order.id}/items/${id}/tab`) },
onSuccess: () => done(t('orders.lines.tabbed')), onError: err => { onError(err); onChanged() },
})
return (
<section className="rounded-card border border-line bg-surface shadow-raised overflow-hidden" data-testid="order-lines">
{lines.length === 0 ? <EmptyState compact title={t('orders.lines.none')} /> : (
<ul className="divide-y divide-line">
{lines.map(item => {
const can = open && selectable(item)
const on = picked.includes(item.id)
const d = lineDetails(item)
const evs = priceEvents.filter(ev => ev.order_item_id === item.id && EVENT_TONE[ev.event_type])
const gone = item.status === 'cancelled'
return (
<li key={item.id} className={cx('px-4 py-2.5 flex gap-3 items-start', on && 'bg-accent-soft', gone && 'opacity-50')}
data-testid="order-line" data-status={item.status} data-name={nameOf(item)}>
<input type="checkbox" className="mt-1 size-4 accent-[var(--x-accent)]" disabled={!can} checked={on}
aria-label={t('orders.lines.pick', { name: nameOf(item) })} onChange={() => setSelected(s => toggleSelected(s, item.id))} data-testid="line-pick" />
<div className={cx('flex-1 min-w-0 grid gap-0.5', gone && 'line-through')}>
<div className="flex flex-wrap items-center gap-1.5 text-body font-semibold text-ink">
<span>{item.quantity !== 1 || item.unit_type !== 'piece' ? `${item.quantity}× ` : ''}{nameOf(item)}</span>
{item.deal_id && <Pill tone="accent">{t('orders.lines.free')}</Pill>}
{STATUS_TONE[item.status] && (
<Pill tone={STATUS_TONE[item.status]}>
{t(`orders.lines.status.${item.status}`)}{item.status === 'paid' && item.payment_method ? ` · ${t(`orders.pay.method.${item.payment_method}`, { defaultValue: item.payment_method })}` : ''}
</Pill>
)}
{item.status === 'active' && !item.printed && <Pill tone="warning"><Printer size={12} aria-hidden="true" />{t('orders.lines.notPrinted')}</Pill>}
</div>
{d.choices.length > 0 && <div className="text-caption text-ink-2">{d.choices.join(', ')}</div>}
{d.removed.length > 0 && <div className="text-caption text-ink-2">{t('orders.lines.without', { list: d.removed.join(', ') })}</div>}
{d.note && <div className="text-caption text-warning-ink">{d.note}</div>}
<div className="text-caption text-ink-3">
{t('orders.lines.added', { time: formatTime(item.added_at), name: item.added_by_name ?? '' })}
{item.paid_by_name && ` · ${t('orders.lines.paidBy', { name: item.paid_by_name })}`}
</div>
{evs.map((ev, i) => (
<div key={i} className={cx('flex items-center gap-2 text-caption', EVENT_TONE[ev.event_type])}>
<span aria-hidden="true">↳</span>
<span>{ev.modifier_name || ev.deal_name || t(`overview.order.event.${ev.event_type}`)}</span>
{ev.delta_amount != null && <span className="font-semibold">{formatMoney(ev.delta_amount, { signDisplay: 'exceptZero' })}</span>}
</div>
))}
</div>
<div className="text-right grid">
<span className={cx('text-body font-semibold tabular-nums', item.price_adjustment ? 'text-info-ink' : 'text-ink')}>{formatMoney(lineAmount(item))}</span>
{item.quantity !== 1 && <span className="text-caption text-ink-3 tabular-nums">{t('orders.lines.each', { price: formatMoney(unitOf(item)) })}</span>}
</div>
</li>
)
})}
</ul>
)}
{open && picked.length > 0 && (
<div className="sticky bottom-0 flex flex-wrap items-center gap-2 px-4 py-3 border-t border-line bg-surface-2" data-testid="line-actions">
<span className="flex-1 text-label text-ink-2">{t('orders.lines.picked', { count: picked.length, amount: formatMoney(amount) })}</span>
<Button size="sm" variant="ghost" onClick={() => setSelected([])}>{t('orders.lines.clear')}</Button>
{order.customer_id && <Button size="sm" variant="secondary" icon={<Receipt size={14} />} loading={toTab.isPending} onClick={() => toTab.mutate()}>{t('orders.lines.toTab')}</Button>}
{canDiscount && <Button size="sm" variant="secondary" icon={<Percent size={14} />} onClick={() => setDiscounting(true)} data-testid="lines-discount">{t('orders.lines.discount')}</Button>}
<Button size="sm" variant="danger" icon={<Ban size={14} />} onClick={() => setCancelling(true)} data-testid="lines-cancel">{t('orders.lines.cancel')}</Button>
<Button size="sm" icon={<CreditCard size={14} />} onClick={() => onPay(picked, amount, () => setSelected([]))} data-testid="lines-pay">{t('orders.lines.pay')}</Button>
</div>
)}
{cancelling && (
<Dialog open size="sm" onClose={() => setCancelling(false)} title={t('orders.lines.cancelTitle', { count: picked.length })}
description={t('orders.lines.cancelBody')}
footer={<>
<Button variant="secondary" onClick={() => setCancelling(false)}>{t('orders.back')}</Button>
<Button variant="secondary" loading={cancel.isPending && cancel.variables === false} onClick={() => cancel.mutate(false)} data-testid="cancel-no-print">{t('orders.lines.cancelNoPrint')}</Button>
<Button variant="danger" icon={<Printer size={16} />} loading={cancel.isPending && cancel.variables === true} onClick={() => cancel.mutate(true)}>{t('orders.lines.cancelPrint')}</Button>
</>} />
)}
{discounting && <DiscountDialog orderId={order.id} itemIds={picked} amount={amount} onClose={() => setDiscounting(false)}
onDone={() => { setDiscounting(false); done(t('orders.discount.done')) }} />}
</section>
)
}
function DiscountDialog({ orderId, itemIds, amount, onClose, onDone }) {
const { t } = useTranslation('manager')
const { formatMoney } = useFormat()
const [pct, setPct] = useState('10')
const [note, setNote] = useState('')
const value = Number(String(pct).replace(',', '.'))
const ok = value > 0 && value <= 100
const apply = useMutation({
mutationFn: () => client.post(`/api/orders/${orderId}/items/discount`, { item_ids: itemIds, discount_percent: value, note: note.trim() || null }),
onSuccess: onDone, onError: err => toast.error(errorMessage(err, t)),
})
return (
<Dialog open size="sm" onClose={onClose} title={t('orders.discount.title', { count: itemIds.length })} description={t('orders.discount.body')}
footer={<>
<Button variant="secondary" onClick={onClose}>{t('orders.back')}</Button>
<Button disabled={!ok} loading={apply.isPending} onClick={() => apply.mutate()} data-testid="discount-apply">{t('orders.discount.apply')}</Button>
</>}>
<div className="grid gap-3">
<div className="flex flex-wrap gap-1.5">
{[5, 10, 15, 20, 50, 100].map(p => (
<Button key={p} size="sm" variant={value === p ? 'primary' : 'secondary'} onClick={() => setPct(String(p))}>{p}%</Button>
))}
</div>
<Field label={t('orders.discount.pct')} hint={ok ? t('orders.discount.about', { amount: formatMoney(-(amount * value) / 100) }) : undefined}>
<Input inputMode="decimal" value={pct} onChange={e => setPct(e.target.value)} data-testid="discount-pct" />
</Field>
<Field label={t('orders.discount.note')}>
<Input value={note} maxLength={200} onChange={e => setNote(e.target.value)} />
</Field>
</div>
</Dialog>
)
}
@@ -0,0 +1,194 @@
// A table's order in the manager (plan step 6.9; replaces the v1 order page and its desktop
// ordering tab). Taken, changed, paid and closed by the phones' rules: lines go by id and the
// server prices them (4.4); paying asks cash or card; "Close" with unpaid lines either takes
// the payment first or, when the venue allows it (orders.close_with_unpaid), writes them off
// after saying so. `/orders/new?table=5` is a table without an order: the first "Send" opens it.
import { useState } from 'react'
import { useNavigate, useParams, useSearchParams } from 'react-router-dom'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import { ArrowLeft, Ban, CheckCheck, CreditCard, Printer } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog, EmptyState, Select, Spinner, cx } from '@xenia/ui'
import client from '../../api/client'
import { useLiveQuery } from '../../live/useLiveQuery'
import { useDuration } from '../overview/hooks'
import { tableName } from '../overview/overviewLogic'
import { Money, Pill } from '../overview/parts'
import AddItems from './AddItems'
import OrderLines from './OrderLines'
import OrderPeople from './OrderPeople'
import PayDialog from './PayDialog'
import { AuditList, PriceEventList } from './OrderHistory'
import { closeStep, totals, unpaidIds, venueRules } from './orderLogic'
const ORDER_EVENTS = ['order_updated', 'order_paid', 'order_closed', 'order_refunded', 'kds_order_updated', 'kds_item_updated']
const STATUS_TONE = { open: 'success', partially_paid: 'info', paid: 'accent', closed: 'neutral', cancelled: 'danger' }
const TABS = ['order', 'prices', 'history']
export default function OrderPage() {
const { orderId } = useParams()
const [params] = useSearchParams()
if (orderId === 'new') return <NewOrder tableId={Number(params.get('table')) || null} />
return <OrderView orderId={Number(orderId)} />
}
function useVenue() {
const { data } = useLiveQuery({ queryKey: ['settings'], queryFn: () => client.get('/api/settings/').then(r => r.data), staleTime: 60_000 })
return venueRules(data)
}
function Back() {
const { t } = useTranslation('manager')
const navigate = useNavigate()
return <Button size="sm" variant="ghost" icon={<ArrowLeft size={16} />} onClick={() => navigate('/tables')}>{t('orders.toTables')}</Button>
}
function NewOrder({ tableId }) {
const { t } = useTranslation('manager')
const navigate = useNavigate()
const qc = useQueryClient()
const { data: tables = [] } = useLiveQuery({ queryKey: ['tables'], queryFn: () => client.get('/api/tables/').then(r => r.data), events: ['table_list_changed'] })
const table = tables.find(x => x.id === tableId)
const open = async () => (await client.post('/api/orders/', { table_id: tableId, order_type: 'here' })).data.id
return (
<div className="h-full overflow-y-auto p-4 lg:p-6" data-testid="order-new">
<div className="max-w-6xl mx-auto grid gap-4">
<header className="flex flex-wrap items-center gap-3">
<Back />
<h1 className="text-title font-semibold text-ink">{t('orders.newTitle', { table: table ? tableName(table) : tableId ?? '' })}</h1>
<Pill tone="neutral">{t('overview.tableState.free')}</Pill>
</header>
<p className="text-label text-ink-2">{t('orders.newHint')}</p>
<AddItems orderId={null} openOrder={open} onSent={id => {
qc.invalidateQueries({ queryKey: ['orders-active'] })
navigate(`/orders/${id}`, { replace: true })
}} />
</div>
</div>
)
}
function OrderView({ orderId }) {
const { t } = useTranslation('manager')
const { formatTime, formatMoney } = useFormat()
const since = useDuration()
const navigate = useNavigate()
const qc = useQueryClient()
const venue = useVenue()
const [tab, setTab] = useState('order')
const [paying, setPaying] = useState(null) // { ids, amount, thenClose, after }
const [confirm, setConfirm] = useState(null) // 'close' | 'writeOff' | 'cancel'
const [printerId, setPrinterId] = useState('')
const { data: order, isPending, error } = useLiveQuery({
queryKey: ['order', orderId], queryFn: () => client.get(`/api/orders/${orderId}`).then(r => r.data), events: ORDER_EVENTS,
})
const { data: staff = [] } = useLiveQuery({ queryKey: ['waiters'], queryFn: () => client.get('/api/waiters/').then(r => r.data), staleTime: 60_000 })
const { data: printers = [] } = useLiveQuery({ queryKey: ['printers'], queryFn: () => client.get('/api/system/printers').then(r => r.data), staleTime: 60_000 })
const { data: priceEvents = [] } = useLiveQuery({
queryKey: ['price-events', orderId], queryFn: () => client.get(`/api/pricing/events/order/${orderId}`).then(r => r.data), events: ['order_updated'],
})
const refresh = () => {
qc.invalidateQueries({ queryKey: ['order', orderId] })
qc.invalidateQueries({ queryKey: ['price-events', orderId] })
qc.invalidateQueries({ queryKey: ['orders-active'] })
}
const onError = err => toast.error(errorMessage(err, t))
const close = useMutation({ mutationFn: () => client.post(`/api/orders/${orderId}/close`), onSuccess: () => { setConfirm(null); toast.success(t('orders.closed')); refresh() }, onError })
const cancel = useMutation({
mutationFn: print => client.delete(`/api/orders/${orderId}`, { params: { print_cancellation: print } }),
onSuccess: () => { setConfirm(null); toast.success(t('orders.cancelled')); refresh(); navigate('/tables') }, onError,
})
const print = useMutation({ mutationFn: pid => client.post(`/api/orders/${orderId}/print`, { printer_id: pid }), onSuccess: () => toast.success(t('orders.printing')), onError })
if (isPending) return <div className="h-full grid place-items-center"><Spinner /></div>
if (error || !order) {
return <div className="p-6 grid gap-3 justify-items-center"><EmptyState title={t('orders.notFound')} description={error ? errorMessage(error, t) : undefined} /><Back /></div>
}
const editable = ['open', 'partially_paid', 'paid'].includes(order.status)
const sums = totals(order)
const due = unpaidIds(order)
function startClose() {
const step = closeStep(order, venue.closeWithUnpaid)
if (step === 'payFirst') setPaying({ ids: due, amount: sums.due, thenClose: true })
else setConfirm(step)
}
return (
<div className="h-full overflow-y-auto p-4 lg:p-6" data-testid="order-page" data-status={order.status}>
<div className="max-w-6xl mx-auto grid gap-4">
<header className="flex flex-wrap items-center gap-3">
<Back />
<h1 className="text-title font-semibold text-ink">{order.table_name ? t('orders.title', { table: order.table_name }) : t('orders.titleNoTable', { id: order.id })}</h1>
<Pill tone={STATUS_TONE[order.status] ?? 'neutral'} data-testid="order-status">{t(`overview.orderStatus.${order.status}`, { defaultValue: order.status })}</Pill>
<span className="text-label text-ink-2">{t('overview.order.sub', { id: order.id, time: formatTime(order.opened_at), since: since(order.opened_at, order.closed_at ? new Date(order.closed_at).getTime() : undefined) })}</span>
<span className="flex-1" />
<span className="flex items-baseline gap-4 text-label text-ink-2">
{sums.paid > 0 && <span>{t('orders.paid')} <Money value={sums.paid} className="font-semibold text-success-ink" /></span>}
{sums.paid > 0 && sums.due > 0 && <span>{t('orders.due')} <Money value={sums.due} className="font-semibold text-ink" data-testid="order-due" /></span>}
<span>{t('orders.total')} <Money value={sums.total} className="text-title font-semibold text-ink" data-testid="order-total" /></span>
</span>
</header>
<div className="flex flex-wrap items-center gap-2">
<span className="flex gap-1" role="tablist">
{TABS.map(k => <Button key={k} size="sm" variant={tab === k ? 'primary' : 'ghost'} role="tab" aria-selected={tab === k} onClick={() => setTab(k)} data-testid={`order-tab-${k}`}>{t(`orders.tabs.${k}`)}</Button>)}
</span>
<span className="flex-1" />
{editable && due.length > 0 && <Button icon={<CreditCard size={16} />} onClick={() => setPaying({ ids: due, amount: sums.due })} data-testid="order-pay-all">{t('orders.payAll')}</Button>}
{editable && <Button variant="secondary" icon={<CheckCheck size={16} />} onClick={startClose} data-testid="order-close">{t('orders.close')}</Button>}
{editable && <Button variant="danger" icon={<Ban size={16} />} onClick={() => setConfirm('cancel')} data-testid="order-cancel">{t('orders.cancel')}</Button>}
{printers.length > 0 && (
<span className="flex items-center gap-2">
<Select size="sm" value={printerId} onChange={e => setPrinterId(e.target.value)} aria-label={t('orders.printer')}
placeholder={t('orders.printer')} options={printers.map(p => ({ value: String(p.id), label: p.name }))} />
<Button size="sm" variant="secondary" icon={<Printer size={16} />} disabled={!printerId} loading={print.isPending} onClick={() => print.mutate(Number(printerId))}>{t('orders.print')}</Button>
</span>
)}
</div>
{tab === 'order' && (
<div className={cx('grid gap-4 items-start', editable && 'lg:grid-cols-[minmax(0,1fr)_minmax(0,1.1fr)]')}>
<div className="grid gap-4 min-w-0">
<OrderLines order={order} open={editable} priceEvents={priceEvents} onChanged={refresh}
onPay={(ids, amount, after) => setPaying({ ids, amount, after })} />
<OrderPeople order={order} open={editable} staff={staff} onChanged={refresh} />
</div>
{editable && <AddItems orderId={order.id} onSent={refresh} />}
</div>
)}
{tab === 'prices' && <section className="rounded-card border border-line bg-surface shadow-raised overflow-hidden"><PriceEventList events={priceEvents} /></section>}
{tab === 'history' && <section className="rounded-card border border-line bg-surface shadow-raised overflow-hidden"><AuditList order={order} /></section>}
</div>
{paying && <PayDialog orderId={order.id} itemIds={paying.ids} amount={paying.amount} card={venue.card} thenClose={!!paying.thenClose}
onClose={() => setPaying(null)}
onDone={() => { toast.success(paying.thenClose ? t('orders.closed') : t('orders.pay.done')); paying.after?.(); setPaying(null); refresh() }} />}
{(confirm === 'close' || confirm === 'writeOff') && (
<Dialog open size="sm" onClose={() => setConfirm(null)} title={t(confirm === 'close' ? 'orders.confirmClose' : 'orders.writeOffTitle')}
description={confirm === 'writeOff' ? t('orders.writeOffBody', { count: due.length, amount: formatMoney(sums.due) }) : undefined}
footer={<>
<Button variant="secondary" onClick={() => setConfirm(null)}>{t('orders.back')}</Button>
{confirm === 'writeOff' && <Button variant="secondary" onClick={() => { setConfirm(null); setPaying({ ids: due, amount: sums.due, thenClose: true }) }}>{t('orders.payAndClose')}</Button>}
<Button variant={confirm === 'writeOff' ? 'danger' : 'primary'} loading={close.isPending} onClick={() => close.mutate()} data-testid="order-close-confirm">
{confirm === 'writeOff' ? t('orders.writeOff') : t('orders.close')}
</Button>
</>} />
)}
{confirm === 'cancel' && (
<Dialog open size="sm" onClose={() => setConfirm(null)} title={t('orders.cancelTitle')} description={t('orders.cancelBody')}
footer={<>
<Button variant="secondary" onClick={() => setConfirm(null)}>{t('orders.back')}</Button>
<Button variant="secondary" loading={cancel.isPending && cancel.variables === false} onClick={() => cancel.mutate(false)} data-testid="order-cancel-confirm">{t('orders.lines.cancelNoPrint')}</Button>
<Button variant="danger" icon={<Printer size={16} />} loading={cancel.isPending && cancel.variables === true} onClick={() => cancel.mutate(true)}>{t('orders.lines.cancelPrint')}</Button>
</>} />
)}
</div>
)
}
@@ -0,0 +1,99 @@
// Who is on a table's order (plan step 6.9): its waiters (add or take one off) and its customer
// (search and attach one, or take them off; with the customers app on).
import { useState } from 'react'
import { useMutation } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import { UserRound, X } from 'lucide-react'
import { useModule } from '@xenia/access'
import { errorMessage } from '@xenia/api'
import { useTranslation } from '@xenia/i18n'
import { Button, IconButton, Input, Select } from '@xenia/ui'
import client from '../../api/client'
import { useLiveQuery } from '../../live/useLiveQuery'
import { Pill } from '../overview/parts'
import { addableWaiters, personName } from './orderLogic'
export default function OrderPeople({ order, open, staff, onChanged }) {
const { t } = useTranslation('manager')
const crm = useModule('crm')
const onError = err => toast.error(errorMessage(err, t))
const add = useMutation({ mutationFn: id => client.put(`/api/orders/${order.id}/assign-waiter`, { waiter_id: id }), onSuccess: onChanged, onError })
const remove = useMutation({ mutationFn: id => client.delete(`/api/orders/${order.id}/waiters/${id}`), onSuccess: onChanged, onError })
const name = id => personName(staff.find(s => s.id === id)) || `#${id}`
const addable = addableWaiters(staff, order)
return (
<section className="rounded-card border border-line bg-surface shadow-raised p-4 grid gap-3" data-testid="order-people">
<div className="grid gap-2">
<h3 className="text-caption font-semibold uppercase tracking-wide text-ink-3">{t('orders.people.staff')}</h3>
<div className="flex flex-wrap items-center gap-2">
{order.waiters.length === 0 && <span className="text-label text-ink-3">{t('orders.people.noStaff')}</span>}
{order.waiters.map(w => (
<Pill key={w.waiter_id} tone="accent" data-testid="order-waiter">
{name(w.waiter_id)}
{open && (
<button type="button" className="ml-0.5 rounded-full hover:bg-surface-3" aria-label={t('orders.people.remove', { name: name(w.waiter_id) })}
onClick={() => remove.mutate(w.waiter_id)}><X size={12} /></button>
)}
</Pill>
))}
{open && addable.length > 0 && (
<Select size="sm" value="" placeholder={t('orders.people.add')} aria-label={t('orders.people.add')} data-testid="order-waiter-add"
onChange={e => e.target.value && add.mutate(Number(e.target.value))}
options={addable.map(s => ({ value: String(s.id), label: personName(s) }))} />
)}
</div>
</div>
{crm && <Customer order={order} open={open} onChanged={onChanged} />}
</section>
)
}
function Customer({ order, open, onChanged }) {
const { t } = useTranslation('manager')
const [searching, setSearching] = useState(false)
const [q, setQ] = useState('')
const { data: found = [] } = useLiveQuery({
queryKey: ['customers', q], enabled: searching, staleTime: 30_000,
queryFn: () => client.get('/api/customers/', { params: q ? { search: q } : {} }).then(r => r.data),
})
const set = useMutation({
mutationFn: id => client.put(`/api/orders/${order.id}/customer`, { customer_id: id }),
onSuccess: () => { setSearching(false); setQ(''); onChanged() },
onError: err => toast.error(errorMessage(err, t)),
})
return (
<div className="grid gap-2 border-t border-line pt-3">
<h3 className="text-caption font-semibold uppercase tracking-wide text-ink-3">{t('orders.people.customer')}</h3>
{order.customer_id ? (
<div className="flex items-center gap-2 p-2 rounded-control bg-info-soft text-info-ink">
<UserRound size={16} aria-hidden="true" />
<span className="flex-1 min-w-0 grid">
<span className="text-label font-semibold truncate">{order.customer_name || `#${order.customer_id}`}</span>
{order.customer_phone && <span className="text-caption">{order.customer_phone}</span>}
</span>
{open && <IconButton size="sm" variant="ghost" label={t('orders.people.customerRemove')} onClick={() => set.mutate(null)}><X size={14} /></IconButton>}
</div>
) : !open ? <span className="text-label text-ink-3">{t('orders.people.noCustomer')}</span>
: !searching ? <Button size="sm" variant="secondary" onClick={() => setSearching(true)}>{t('orders.people.customerAdd')}</Button>
: (
<div className="grid gap-1">
<Input autoFocus value={q} onChange={e => setQ(e.target.value)} placeholder={t('orders.people.customerSearch')} aria-label={t('orders.people.customerSearch')} />
<ul className="max-h-52 overflow-y-auto rounded-control border border-line divide-y divide-line">
{found.length === 0 && <li className="px-3 py-2 text-label text-ink-3">{t('orders.people.customerNone')}</li>}
{found.map(c => (
<li key={c.id}>
<button type="button" className="w-full text-left px-3 py-2 hover:bg-surface-2 text-label" onClick={() => set.mutate(c.id)}>
<span className="font-semibold text-ink">{c.name}</span>
{c.phone && <span className="ml-2 text-ink-3">{c.phone}</span>}
</button>
</li>
))}
</ul>
<Button size="sm" variant="ghost" onClick={() => { setSearching(false); setQ('') }}>{t('orders.back')}</Button>
</div>
)}
</div>
)
}
@@ -0,0 +1,50 @@
// Paying lines of a table's order from the manager (plan step 6.9), as the phones do: how much,
// then cash or card (card only when the venue takes cards). `thenClose` is the phones'
// "instant-pay close": the rest is paid and the order closed in one go, for venues that don't
// close with unpaid items (orders.close_with_unpaid, 4.8).
import { useState } from 'react'
import { Banknote, CreditCard } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog } from '@xenia/ui'
import client from '../../api/client'
export default function PayDialog({ orderId, itemIds, amount, card = true, thenClose = false, onClose, onDone }) {
const { t } = useTranslation('manager')
const { formatMoney } = useFormat()
const [busy, setBusy] = useState(null)
const [error, setError] = useState(null)
async function pay(method) {
setBusy(method)
setError(null)
try {
await client.post(`/api/orders/${orderId}/pay`, { item_ids: itemIds, payment_method: method })
if (thenClose) await client.post(`/api/orders/${orderId}/close`)
onDone(method)
} catch (err) {
setError(errorMessage(err, t))
} finally { setBusy(null) }
}
return (
<Dialog open size="sm" onClose={busy ? undefined : onClose}
title={thenClose ? t('orders.pay.closeTitle') : t('orders.pay.title', { count: itemIds.length })}
description={thenClose ? t('orders.pay.closeBody') : undefined}
footer={<Button variant="secondary" onClick={onClose} disabled={!!busy}>{t('orders.back')}</Button>}>
<div className="grid gap-3" data-testid="pay-dialog">
<div className="text-center text-display font-semibold tabular-nums text-ink" data-testid="pay-amount">{formatMoney(amount)}</div>
<div className="grid grid-cols-2 gap-2">
<Button size="lg" icon={<Banknote size={20} />} loading={busy === 'cash'} disabled={!!busy} onClick={() => pay('cash')} data-testid="pay-cash">
{t('orders.pay.cash')}
</Button>
<Button size="lg" variant="secondary" icon={<CreditCard size={20} />} loading={busy === 'card'} disabled={!!busy || !card}
onClick={() => pay('card')} data-testid="pay-card" title={card ? undefined : t('orders.pay.noCard')}>
{t('orders.pay.card')}
</Button>
</div>
{error && <p role="alert" className="text-label text-danger-ink">{error}</p>}
</div>
</Dialog>
)
}
@@ -0,0 +1,86 @@
// A table's quick actions from the Tables page (plan step 6.9): its flags (VIP, birthday…), and
// a message to the table's waiters or to everyone, from a ready-made text or typed.
import { useState } from 'react'
import { useQueryClient } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import { errorMessage } from '@xenia/api'
import { useTranslation } from '@xenia/i18n'
import { Button, Dialog, Field, Input, Switch, cx } from '@xenia/ui'
import client from '../../api/client'
import { useLiveQuery } from '../../live/useLiveQuery'
import { tableName } from '../overview/overviewLogic'
export default function QuickActions({ card, flagDefs, current, onClose }) {
const { t } = useTranslation('manager')
const qc = useQueryClient()
const { table, order } = card
const [ids, setIds] = useState(() => current.map(f => f.id))
const [notify, setNotify] = useState(false)
const [toAll, setToAll] = useState(!order?.waiters?.length)
const [message, setMessage] = useState('')
const [busy, setBusy] = useState(false)
const { data: templates = [] } = useLiveQuery({ queryKey: ['quick-templates'], queryFn: () => client.get('/api/notifications/templates').then(r => r.data), staleTime: 60_000 })
const toggle = id => setIds(list => (list.includes(id) ? list.filter(x => x !== id) : [...list, id]))
async function save() {
setBusy(true)
try {
await client.put(`/api/flags/table/${table.id}`, { flag_ids: ids })
if (notify && message.trim()) {
await client.post('/api/notifications/send', {
body: message.trim(), table_ids: [table.id],
target_waiter_ids: toAll ? [] : (order?.waiters ?? []).map(w => w.waiter_id),
})
toast.success(t('orders.quick.sent'))
} else toast.success(t('orders.quick.saved'))
qc.invalidateQueries({ queryKey: ['flag-assignments'] })
onClose()
} catch (err) { toast.error(errorMessage(err, t)) } finally { setBusy(false) }
}
return (
<Dialog open size="sm" onClose={onClose} title={t('orders.quick.title', { table: tableName(table) })}
footer={<>
<Button variant="secondary" onClick={onClose}>{t('orders.back')}</Button>
<Button loading={busy} disabled={notify && !message.trim()} onClick={save} data-testid="quick-save">{t('orders.quick.save')}</Button>
</>}>
<div className="grid gap-4" data-testid="quick-actions">
<Field label={t('orders.quick.flags')}>
{flagDefs.length === 0 ? <span className="text-label text-ink-3">{t('orders.quick.noFlags')}</span> : (
<span className="flex flex-wrap gap-1.5">
{flagDefs.map(f => (
<button key={f.id} type="button" aria-pressed={ids.includes(f.id)} onClick={() => toggle(f.id)} data-testid="quick-flag"
className={cx('inline-flex items-center gap-1 px-3 py-1 rounded-full border text-label',
ids.includes(f.id) ? 'border-accent bg-accent-soft text-accent-ink font-semibold' : 'border-line bg-surface text-ink-2 hover:bg-surface-2')}>
{f.emoji && <span aria-hidden="true">{f.emoji}</span>}{f.name}
</button>
))}
</span>
)}
</Field>
<label className="flex items-center gap-3 text-body text-ink">
<Switch checked={notify} onChange={setNotify} aria-label={t('orders.quick.notify')} />
{t('orders.quick.notify')}
</label>
{notify && (
<div className="grid gap-2">
{templates.length > 0 && (
<span className="flex flex-wrap gap-1.5">
{templates.slice(0, 6).map(tp => (
<Button key={tp.id} size="sm" variant={message === tp.body ? 'primary' : 'secondary'} onClick={() => setMessage(tp.body)}>{tp.body}</Button>
))}
</span>
)}
<Input value={message} maxLength={300} onChange={e => setMessage(e.target.value)} placeholder={t('orders.quick.message')} aria-label={t('orders.quick.message')} />
{order?.waiters?.length > 0 && (
<label className="flex items-center gap-3 text-label text-ink-2">
<Switch checked={toAll} onChange={setToAll} aria-label={t('orders.quick.toAll')} />
{toAll ? t('orders.quick.toAll') : t('orders.quick.toTable')}
</label>
)}
</div>
)}
</div>
</Dialog>
)
}
@@ -0,0 +1,160 @@
// The tables now, in the manager (plan step 6.9; the map since 6.8): each table's state, total,
// time open, waiters, flags and a booking kept for it soon (RESERVED). A table with an order
// opens its order page; a free one opens a new order there. Quick actions set the table's flags
// and can tell its waiters (or everyone) a message. Lines that didn't print are listed below.
// Everything stays current through the live events.
import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { Clock, Lock, Printer, Zap } from 'lucide-react'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, EmptyState, IconButton, Select, Spinner, cx } from '@xenia/ui'
import client from '../../api/client'
import { useLiveQuery } from '../../live/useLiveQuery'
import LiveFloor from '../floor/LiveFloor'
import { useDuration } from '../overview/hooks'
import { TABLE_STATES, durationParts, orderTotal, tableCards, tableName } from '../overview/overviewLogic'
import { Money, Pill } from '../overview/parts'
import PendingPrints from '../overview/PendingPrints'
import { BORDER, SOFT, SOLID } from '../overview/tones'
import QuickActions from './QuickActions'
import { NO_ZONE, cardTarget, filterCards, flagsByTable, personName } from './orderLogic'
const ORDER_EVENTS = ['order_updated', 'order_paid', 'order_closed', 'order_refunded']
const STATE_TONE = { open: 'success', partially_paid: 'info', paid: 'accent', free: 'neutral' }
export default function TablesPage() {
const { t } = useTranslation('manager')
const tc = useTranslation('common').t
const navigate = useNavigate()
const [view, setView] = useState('list')
const [states, setStates] = useState([])
const [zone, setZone] = useState('')
const [quick, setQuick] = useState(null) // a card
const { data: tables = [], isPending: loadingTables } = useLiveQuery({
queryKey: ['tables'], queryFn: () => client.get('/api/tables/').then(r => r.data),
events: ['table_list_changed', 'reservation_updated'], refetchInterval: 60_000,
})
const { data: orders = [], isPending: loadingOrders } = useLiveQuery({
queryKey: ['orders-active'], queryFn: () => client.get('/api/orders/').then(r => r.data), events: ORDER_EVENTS, refetchInterval: 60_000,
})
const { data: groups = [] } = useLiveQuery({ queryKey: ['table-groups'], queryFn: () => client.get('/api/tables/groups').then(r => r.data), events: ['table_list_changed'] })
const { data: flagDefs = [] } = useLiveQuery({ queryKey: ['flag-defs'], queryFn: () => client.get('/api/flags/defs').then(r => r.data), staleTime: 60_000 })
const { data: flagRows = [] } = useLiveQuery({ queryKey: ['flag-assignments'], queryFn: () => client.get('/api/flags/assignments').then(r => r.data), events: ['table_flags_changed'] })
const { data: staff = [] } = useLiveQuery({ queryKey: ['waiters'], queryFn: () => client.get('/api/waiters/').then(r => r.data), staleTime: 60_000 })
const cards = tableCards(tables, orders)
const shown = filterCards(cards, { states, zone })
const flags = flagsByTable(flagDefs, flagRows)
const name = id => personName(staff.find(s => s.id === id)) || `#${id}`
const toggleState = s => setStates(list => (list.includes(s) ? list.filter(x => x !== s) : [...list, s]))
if (loadingTables || loadingOrders) return <div className="h-full grid place-items-center"><Spinner /></div>
return (
<div className="h-full overflow-y-auto p-4 lg:p-6 grid gap-4 content-start" data-testid="tables-page">
<div className="flex flex-wrap items-center gap-2">
<div className="flex rounded-control border border-line overflow-hidden" role="group">
{['list', 'map'].map(v => (
<button key={v} type="button" aria-pressed={view === v} onClick={() => setView(v)} data-testid={`tables-view-${v}`}
className={cx('px-3 py-1.5 text-label font-medium', view === v ? 'bg-accent-soft text-accent-ink' : 'bg-surface text-ink-2 hover:bg-surface-2')}>
{tc(`floorMap.${v}`)}
</button>
))}
</div>
<span className="flex-1" />
{view === 'list' && TABLE_STATES.map(s => (
<button key={s} type="button" aria-pressed={states.includes(s)} onClick={() => toggleState(s)} data-testid={`tables-state-${s}`}
className={cx('inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full border text-label font-semibold',
states.includes(s) ? `${SOFT[STATE_TONE[s]]} ${BORDER[STATE_TONE[s]]}` : 'border-line bg-surface text-ink-2 hover:bg-surface-2')}>
<span className={cx('w-2 h-2 rounded-full', SOLID[STATE_TONE[s]])} aria-hidden="true" />
{t(`overview.tableState.${s}`)}
<span className="tabular-nums text-ink">{cards.filter(c => c.state === s).length}</span>
</button>
))}
<Select size="sm" value={zone} onChange={e => setZone(e.target.value)} aria-label={t('orders.tables.zone')} data-testid="tables-zone">
<option value="">{t('orders.tables.allZones')}</option>
{groups.map(g => <option key={g.id} value={String(g.id)}>{g.name}</option>)}
<option value={NO_ZONE}>{t('orders.tables.noZone')}</option>
</Select>
</div>
{view === 'map' && (
<LiveFloor zone={zone && zone !== NO_ZONE ? Number(zone) : null} onOpen={id => navigate(`/orders/${id}`)} />
)}
{view === 'list' && (shown.length === 0
? <EmptyState title={t('orders.tables.none')} />
: (
<div className="grid gap-3 grid-cols-[repeat(auto-fill,minmax(17rem,1fr))]">
{shown.map(card => (
<TableCard key={card.table.id} card={card} zone={groups.length > 1 ? groups.find(g => g.id === card.table.group_id)?.name : null} flags={flags[card.table.id] ?? []} waiterName={name}
onOpen={() => navigate(cardTarget(card))} onQuick={() => setQuick(card)} />
))}
</div>
))}
<PendingPrints cards={cards.filter(c => c.pendingPrint)} onOpen={id => navigate(`/orders/${id}`)} />
{quick && <QuickActions card={quick} flagDefs={flagDefs} current={flags[quick.table.id] ?? []} onClose={() => setQuick(null)} />}
</div>
)
}
function TableCard({ card, zone, flags, waiterName, onOpen, onQuick }) {
const { t } = useTranslation('manager')
const { formatTime } = useFormat()
const since = useDuration()
const { table, order, state, pendingPrint } = card
const tone = STATE_TONE[state]
const booking = table.upcoming_reservation
const open = order ? durationParts(order.opened_at) : null
const long = !!open && open.h * 60 + open.m >= 90 // the v1 card's "been here a while"
return (
<div className={cx('relative rounded-card border bg-surface shadow-raised overflow-hidden grid', BORDER[tone])} data-testid="table-card" data-state={state} data-table={table.id}>
<span className={cx('absolute inset-y-0 left-0 w-1.5', SOLID[tone])} aria-hidden="true" />
<button type="button" onClick={onOpen} className="text-left pl-5 pr-4 pt-3 pb-2 grid gap-2 hover:bg-surface-2 transition-colors duration-fast"
aria-label={t('orders.tables.open', { table: tableName(table), state: t(`overview.tableState.${state}`) })}>
<span className="flex items-start gap-2">
<span className="flex-1 grid gap-1">
<span className="text-display font-bold leading-none text-ink tabular-nums">{tableName(table)}</span>
{zone && <span className="text-caption text-ink-3">{zone}</span>}
</span>
<span className={cx('px-2 py-0.5 rounded-full text-caption font-semibold', SOFT[tone])}>{t(`overview.tableState.${state}`)}</span>
</span>
<span className="flex flex-wrap gap-1 min-h-6">
{pendingPrint && <Pill tone="warning"><Printer size={12} aria-hidden="true" />{t('orders.tables.notPrinted')}</Pill>}
{booking && (
<Pill tone="accent" data-testid="table-reserved" title={`${booking.guest_name} · ${booking.party_size}`}>
<Lock size={12} aria-hidden="true" />{t('orders.tables.reserved', { time: formatTime(booking.reserved_for), name: booking.guest_name })}
</Pill>
)}
{flags.slice(0, 3).map(f => (
<Pill key={f.id} tone="neutral">{f.emoji && <span aria-hidden="true">{f.emoji}</span>}{f.name}</Pill>
))}
{flags.length > 3 && <Pill tone="neutral" title={flags.slice(3).map(f => f.name).join(', ')}>+{flags.length - 3}</Pill>}
</span>
<span className="grid grid-cols-2 gap-2">
<span className="grid">
<span className="text-caption font-semibold uppercase tracking-wide text-ink-3">{t('orders.total')}</span>
{order ? <Money value={orderTotal(order.items)} className="text-title font-semibold text-ink" /> : <span className="text-title text-ink-3">—</span>}
</span>
<span className="grid">
<span className="text-caption font-semibold uppercase tracking-wide text-ink-3">{t('orders.tables.time')}</span>
<span className={cx('text-title tabular-nums inline-flex items-center gap-1', long ? 'font-bold text-warning-ink' : 'text-ink')}>
{order ? <><Clock size={14} aria-hidden="true" />{since(order.opened_at)}</> : <span className="text-ink-3">—</span>}
</span>
</span>
</span>
</button>
<div className="flex items-center gap-2 pl-5 pr-2 py-2 border-t border-line">
<span className="flex-1 min-w-0 truncate text-label text-ink-2">
{!order ? (table.seat_count ? t('orders.tables.seats', { count: table.seat_count }) : '')
: order.waiters.length ? order.waiters.map(w => waiterName(w.waiter_id)).join(', ') : t('orders.tables.noWaiter')}
</span>
<IconButton size="sm" variant="ghost" label={t('orders.quick.title', { table: tableName(table) })} onClick={onQuick} data-testid="table-quick"><Zap size={16} /></IconButton>
<Button size="sm" variant={order ? 'secondary' : 'primary'} onClick={onOpen} data-testid="table-open">{order ? t('orders.tables.view') : t('orders.tables.take')}</Button>
</div>
</div>
)
}
@@ -0,0 +1,105 @@
// A table's order in the manager, as plain data (plan step 6.9), tested in tests/orders.test.mjs.
// The rules are the phones': prices come from the server (lines by id, 4.4); closing with unpaid
// items needs the venue's "close with unpaid items" (orders.close_with_unpaid, 4.8), otherwise
// the rest is paid first.
export const OPEN_STATUSES = ['open', 'partially_paid', 'paid']
export const isOpen = order => !!order && OPEN_STATUSES.includes(order.status)
const parse = raw => { try { return raw ? JSON.parse(raw) : [] } catch { return [] } }
/** What a line has: its choices ("Well done, Fries"), what's left out, the note. */
export function lineDetails(item) {
const opts = parse(item.selected_options).map(o => (typeof o === 'string' ? o : o?.name)).filter(Boolean)
const removed = parse(item.removed_ingredients).map(o => (typeof o === 'string' ? o : o?.name)).filter(Boolean)
return { choices: opts, removed, note: item.notes || null }
}
export const unitOf = item => (item.unit_price ?? 0) + (item.price_adjustment ?? 0)
export const lineAmount = item => Math.round(unitOf(item) * item.quantity * 100) / 100
export const nameOf = item => item.product_name || item.product?.name || `#${item.product_id}`
const LIVE = ['active', 'ready', 'paid', 'closed']
const UNPAID = ['active', 'ready']
/** The order's sums: everything still on it, what's paid, what's due. */
export function totals(order) {
const items = order?.items ?? []
const sum = list => Math.round(list.reduce((s, i) => s + lineAmount(i), 0) * 100) / 100
const total = sum(items.filter(i => LIVE.includes(i.status)))
const paid = sum(items.filter(i => i.status === 'paid'))
const due = sum(items.filter(i => UNPAID.includes(i.status)))
return { total, paid, due }
}
export const unpaidIds = order => (order?.items ?? []).filter(i => UNPAID.includes(i.status)).map(i => i.id)
/** Lines in the order they were added; cancelled ones last. */
export function shownLines(order, { showCancelled = true } = {}) {
const items = [...(order?.items ?? [])].sort((a, b) => (a.added_at ?? '').localeCompare(b.added_at ?? '') || a.id - b.id)
const live = items.filter(i => i.status !== 'cancelled')
return showCancelled ? [...live, ...items.filter(i => i.status === 'cancelled')] : live
}
/** Selection: only unpaid lines can be paid or cancelled. */
export function selectable(item) { return UNPAID.includes(item.status) }
export function toggleSelected(sel, id) { return sel.includes(id) ? sel.filter(x => x !== id) : [...sel, id] }
export const selectedAmount = (order, sel) => Math.round((order?.items ?? []).filter(i => sel.includes(i.id)).reduce((s, i) => s + lineAmount(i), 0) * 100) / 100
/**
* What "Close" does: 'close' (nothing unpaid), 'writeOff' (unpaid lines and the venue allows
* closing with them: say so first), or 'payFirst' (the venue doesn't: offer to pay the rest).
*/
export function closeStep(order, closeWithUnpaid) {
const due = unpaidIds(order).length
if (!due) return 'close'
return closeWithUnpaid ? 'writeOff' : 'payFirst'
}
/** The venue's settings rows (GET /api/settings/) → the two that matter here. */
export function venueRules(settings) {
const v = key => settings?.[key]?.value
return { closeWithUnpaid: v('orders.close_with_unpaid') === 'true', card: v('payments.card_enabled') !== 'false' }
}
/** The cart's lines as the server takes them, plus the order's note (POST /api/orders/{id}/items). */
export function sendBody(cart, note) {
return { lines: cart.map(c => c.line), order_note: note?.trim() || null }
}
/** Waiters to add: the active staff not already on the order. */
export function addableWaiters(staff = [], order) {
const on = new Set((order?.waiters ?? []).map(w => w.waiter_id))
return staff.filter(s => s.is_active !== false && !on.has(s.id))
}
export const personName = p => (p ? p.nickname || p.full_name || p.username : '')
// ── the Tables page ─────────────────────────────────────────────────────────
export const NO_ZONE = 'none'
/** Cards (overviewLogic.tableCards) shown for the chosen states (none = all) and zone
* ('' = all, NO_ZONE = tables without a zone, else a zone id as text). */
export function filterCards(cards, { states = [], zone = '' } = {}) {
return cards.filter(c => {
if (states.length && !states.includes(c.state)) return false
if (zone === NO_ZONE) return !c.table.group_id
if (zone) return String(c.table.group_id ?? '') === zone
return true
})
}
/** Flags on each table: { tableId: [{ ...flag, assigned_at }] } from the definitions and the assignments. */
export function flagsByTable(defs = [], assignments = []) {
const byId = new Map(defs.map(f => [f.id, f]))
const out = {}
for (const a of assignments) {
const def = byId.get(a.flag_id)
if (def) (out[a.table_id] ??= []).push({ ...def, assigned_at: a.assigned_at })
}
return out
}
/** Where a table's card goes: its order, or a new order at that table. */
export const cardTarget = card => (card.order ? `/orders/${card.order.id}` : `/orders/new?table=${card.table.id}`)