feat(backend,terminal): tables at the counter, shared live with the waiter phones (platform-v2 3.3c)

- POS: GET /api/pos/tables (the cashier's zones as in the waiter app, each open order's
  totals, people, ready items, flags, reservation), POST /api/pos/tables/{id}/items (into
  the table's order or a new one via orders.open_order + add_items), POST
  /api/pos/orders/{id}/pay (chosen items, cash/card/split, drawer on cash), POST
  /api/pos/orders/{id}/close (only when nothing is unpaid). Quote takes order_id so the
  order's items count for cart conditions (shared pos_cart.order_cart, used by add_items).
- New codes pos.table_not_found, pos.table_not_yours, pos.items_changed, pos.order_unpaid.
- Fix: item cancels (DELETE item, cancel-items) now broadcast order_updated, so phones and
  kitchen screens see them at once.
- Terminal: Sale | Tables switch, zone list, table cards by zone, TablePanel (order lines,
  new lines, send, pay selected/all, cancel with approval, close), generic PaymentDialog.
- Tests: test_pos_tables.py (8), terminal unit, terminal.mjs +17 with a live phone socket.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-15 02:15:54 +02:00
co-authored by Claude Opus 5.5
parent bff82a332a
commit 988d413d8e
19 changed files with 1452 additions and 218 deletions
+95 -145
View File
@@ -1,19 +1,22 @@
// The counter POS screen (plan step 3.3a): categories on the left, the product grid with a
// search on top, the cart on the right. A tap adds a product (or opens its choices when it
// has preferences to pick); the (i) button checks its price without adding it. Every price is
// the backend's: the menu's and the cart's quote. Charge → PaymentDialog (3.3b); after a sale
// the cart shows what happened and "Same again".
// The counter POS screen (plan steps 3.3a–c). Two modes, switched at the top left:
// - Sale: categories on the left, the product grid with a search, the quick-sale cart on the
// right (SaleCart: Charge → payment, 3.3b).
// - Tables: the zones on the left and the table list (TablesView); a table opens with the
// product grid again and the table's order on the right (TablePanel).
// A tap adds a product (or opens its choices when it has preferences to pick); the (i) button
// checks its price without adding it. Every price is the backend's.
import { useMemo, useState } from 'react'
import { Banknote, Info, Minus, Plus, Repeat, Search, ShoppingBag, Trash2, Utensils, X } from 'lucide-react'
import { Info, LayoutGrid, Search, ShoppingBag, X } from 'lucide-react'
import { useFormat, useLanguage, useTranslation } from '@xenia/i18n'
import { useCan } from '@xenia/access'
import { Button, EmptyState, IconButton, Input, Select, Spinner, useToast } from '@xenia/ui'
import {
DISCOUNTS, addLine, categoriesWithProducts, defaultSelection, needsChoices, productsIn, searchProducts, setLineQty, toLine, unitOf,
} from './logic/cart'
import PaymentDialog from './PaymentDialog'
import { EmptyState, IconButton, Input, Spinner } from '@xenia/ui'
import { addLine, categoriesWithProducts, defaultSelection, needsChoices, productsIn, searchProducts, toLine, unitOf } from './logic/cart'
import { zoneCounts } from './logic/tables'
import ProductDialog from './ProductDialog'
import { useMenu, useQuote } from './usePos'
import SaleCart from './SaleCart'
import TablePanel from './TablePanel'
import TablesView from './TablesView'
import { useMenu, useTables } from './usePos'
export default function PosScreen() {
const { t } = useTranslation('terminal')
@@ -23,24 +26,31 @@ export default function PosScreen() {
}
function Counter({ menu, t }) {
const { formatMoney } = useFormat()
const { language } = useLanguage()
const [mode, setMode] = useState('sale') // sale | tables
const [tableId, setTableId] = useState(null) // the open table (tables mode)
const [zone, setZone] = useState(null)
const [category, setCategory] = useState(() => menu.settings.start_category_id ?? null)
const [query, setQuery] = useState('')
const [orderType, setOrderType] = useState(menu.settings.default_order_type)
const [cart, setCart] = useState([])
const [saleCart, setSaleCart] = useState([])
const [tableCart, setTableCart] = useState([])
const [dialog, setDialog] = useState(null) // product
const [paying, setPaying] = useState(false)
const [lastSale, setLastSale] = useState(null) // { lines, orderType, result }
const quote = useQuote(cart, orderType)
const toast = useToast()
const tables = useTables()
const canDiscount = useCan('ordering.prices.modify')
const ready = cart.length > 0 && !quote.pending && !quote.error && quote.quote?.lines?.length === cart.length
// a table that left the cashier's list (zone changed) shows the list again
const table = tableId != null ? tables.data?.tables.find(x => x.id === tableId) ?? null : null
const atTable = mode === 'tables' && table != null
const picking = mode === 'tables' && !atTable
const setCart = atTable ? setTableCart : setSaleCart
const leaveTable = () => { setTableId(null); setTableCart([]) }
const byId = useMemo(() => new Map(menu.products.map(p => [p.id, p])), [menu.products])
const categories = useMemo(() => categoriesWithProducts(menu.categories, menu.products), [menu])
const shown = useMemo(() => (query.trim() ? searchProducts(menu.products, query) : productsIn(menu.products, category)),
[menu.products, query, category])
const counts = useMemo(() => zoneCounts(tables.data?.tables ?? []), [tables.data])
const tap = product => {
if (needsChoices(product)) { setDialog(product); return }
@@ -50,98 +60,91 @@ function Counter({ menu, t }) {
return (
<div className="absolute inset-0 grid grid-cols-[13rem_1fr_24rem] bg-canvas text-ink" data-testid="pos-screen" lang={language}>
{/* categories */}
<nav className="border-r border-line bg-surface overflow-y-auto p-2 grid content-start gap-1" data-testid="pos-categories">
<CategoryButton active={category == null && !query} onClick={() => { setCategory(null); setQuery('') }}>{t('pos.allProducts')}</CategoryButton>
{categories.map(c => (
<CategoryButton key={c.id} colour={c.color} active={category === c.id && !query} onClick={() => { setCategory(c.id); setQuery('') }} testId={`category-${c.id}`}>
{c.name}
</CategoryButton>
))}
</nav>
{/* products */}
<main className="flex flex-col min-h-0 min-w-0">
<div className="p-3 border-b border-line bg-surface flex items-center gap-2">
<div className="relative flex-1">
<Search size={18} className="absolute left-3 top-1/2 -translate-y-1/2 text-ink-3 pointer-events-none" />
<Input value={query} onChange={e => setQuery(e.target.value)} placeholder={t('pos.search')} className="pl-10" data-testid="pos-search" aria-label={t('pos.search')} />
</div>
{query && <IconButton label={t('pos.clearSearch')} onClick={() => setQuery('')}><X size={18} /></IconButton>}
<nav className="border-r border-line bg-surface min-h-0 flex flex-col">
<div className="p-2 grid grid-cols-2 gap-1 border-b border-line" role="tablist" aria-label={t('pos.mode.label')}>
<ModeButton active={mode === 'sale'} onClick={() => setMode('sale')} icon={ShoppingBag} testId="mode-sale">{t('pos.mode.sale')}</ModeButton>
<ModeButton active={mode === 'tables'} onClick={() => { setMode('tables'); leaveTable() }} icon={LayoutGrid} testId="mode-tables"
badge={counts.all.busy || null}>{t('pos.mode.tables')}</ModeButton>
</div>
<div className="flex-1 overflow-y-auto p-3">
{shown.length === 0 ? (
<EmptyState title={query ? t('pos.noResults', { query }) : t('pos.noProducts')} />
<div className="flex-1 overflow-y-auto p-2 grid content-start gap-1" data-testid={picking ? 'pos-zones' : 'pos-categories'}>
{picking ? (
<>
<NavButton active={zone == null} onClick={() => setZone(null)} count={counts.all}>{t('pos.tables.allZones')}</NavButton>
{(tables.data?.groups ?? []).map(g => (
<NavButton key={g.id} colour={g.color} active={zone === g.id} onClick={() => setZone(g.id)} count={counts[g.id]} testId={`zone-${g.id}`}>{g.name}</NavButton>
))}
</>
) : (
<div className="grid gap-3" style={{ gridTemplateColumns: 'repeat(auto-fill, minmax(9.5rem, 1fr))' }} data-testid="pos-grid">
{shown.map(p => <ProductCard key={p.id} product={p} onTap={() => tap(p)} onInfo={() => setDialog(p)} />)}
</div>
<>
<NavButton active={category == null && !query} onClick={() => { setCategory(null); setQuery('') }}>{t('pos.allProducts')}</NavButton>
{categories.map(c => (
<NavButton key={c.id} colour={c.color} active={category === c.id && !query} onClick={() => { setCategory(c.id); setQuery('') }} testId={`category-${c.id}`}>
{c.name}
</NavButton>
))}
</>
)}
</div>
</main>
</nav>
{/* cart */}
<aside className="border-l border-line bg-surface flex flex-col min-h-0" data-testid="pos-cart">
<div className="p-3 border-b border-line grid grid-cols-2 gap-1" role="radiogroup" aria-label={t('pos.orderType')}>
{[['takeaway', ShoppingBag], ['here', Utensils]].map(([type, Icon]) => (
<button key={type} type="button" role="radio" aria-checked={orderType === type} onClick={() => setOrderType(type)} data-testid={`type-${type}`}
className={`min-h-[var(--x-control-md)] rounded-control flex items-center justify-center gap-2 text-body font-medium transition-colors duration-fast
${orderType === type ? 'bg-accent text-accent-fg' : 'bg-surface-2 text-ink-2 hover:bg-surface-3'}`}>
<Icon size={16} />{t(`pos.type.${type}`)}
</button>
))}
</div>
<div className="flex-1 overflow-y-auto">
{cart.length === 0 && lastSale && <SaleDone sale={lastSale} onAgain={() => { setCart(lastSale.lines); setOrderType(lastSale.orderType); setLastSale(null) }} />}
{cart.length === 0
? !lastSale && <EmptyState compact title={t('pos.cartEmpty')} description={t('pos.cartEmptyBody')} />
: cart.map((line, i) => (
<CartLine key={i} line={line} priced={quote.quote?.lines?.[i]} product={byId.get(line.product_id)} canDiscount={canDiscount}
onQty={q => setCart(c => setLineQty(c, i, q))}
onDiscount={pct => setCart(c => c.map((l, j) => (j === i ? { ...l, discount_pct: pct || undefined } : l)))} />
))}
</div>
<div className="border-t border-line p-3 grid gap-3">
{quote.error && <p role="alert" className="text-label text-danger-ink">{t('pos.quoteFailed')}</p>}
<div className="flex items-baseline justify-between">
<span className="text-body-lg text-ink-2">{t('pos.total')}</span>
<span className={`text-display font-semibold ${quote.pending ? 'opacity-50' : ''}`} data-testid="cart-total">
{formatMoney(quote.quote?.total ?? 0)}
</span>
</div>
<Button size="lg" icon={<Banknote size={20} />} disabled={!ready} onClick={() => setPaying(true)} data-testid="charge">
{t('pos.charge', { total: formatMoney(quote.quote?.total ?? 0) })}
</Button>
<Button variant="secondary" icon={<Trash2 size={16} />} disabled={!cart.length} onClick={() => setCart([])}>{t('pos.clearCart')}</Button>
</div>
</aside>
{paying && quote.quote && (
<PaymentDialog cart={cart} quote={quote.quote} orderType={orderType} names={cart.map(l => byId.get(l.product_id)?.name ?? '')}
onClose={() => setPaying(false)}
onPaid={result => {
setPaying(false)
setLastSale({ lines: cart, orderType, result })
setCart([])
toast.success(result.change != null ? t('pos.done.toastChange', { change: formatMoney(result.change) }) : t('pos.done.toast'))
}} />
{picking ? (
<main className="col-span-2 flex flex-col min-h-0 min-w-0">
<TablesView data={tables.data} zone={zone} onPick={id => { setTableId(id); setTableCart([]) }} />
</main>
) : (
<>
<main className="flex flex-col min-h-0 min-w-0">
<div className="p-3 border-b border-line bg-surface flex items-center gap-2">
<div className="relative flex-1">
<Search size={18} className="absolute left-3 top-1/2 -translate-y-1/2 text-ink-3 pointer-events-none" />
<Input value={query} onChange={e => setQuery(e.target.value)} placeholder={t('pos.search')} className="pl-10" data-testid="pos-search" aria-label={t('pos.search')} />
</div>
{query && <IconButton label={t('pos.clearSearch')} onClick={() => setQuery('')}><X size={18} /></IconButton>}
</div>
<div className="flex-1 overflow-y-auto p-3">
{shown.length === 0 ? (
<EmptyState title={query ? t('pos.noResults', { query }) : t('pos.noProducts')} />
) : (
<div className="grid gap-3" style={{ gridTemplateColumns: 'repeat(auto-fill, minmax(9.5rem, 1fr))' }} data-testid="pos-grid">
{shown.map(p => <ProductCard key={p.id} product={p} onTap={() => tap(p)} onInfo={() => setDialog(p)} />)}
</div>
)}
</div>
</main>
{atTable
? <TablePanel key={table.id} table={table} cart={tableCart} setCart={setTableCart} byId={byId} canDiscount={canDiscount}
onBack={leaveTable} onTablesChanged={tables.reload} />
: <SaleCart cart={saleCart} setCart={setSaleCart} orderType={orderType} setOrderType={setOrderType} byId={byId} canDiscount={canDiscount} />}
</>
)}
{dialog && (
<ProductDialog product={dialog} orderType={orderType} onClose={() => setDialog(null)}
<ProductDialog product={dialog} orderType={atTable ? 'here' : orderType} onClose={() => setDialog(null)}
onAdd={line => setCart(c => addLine(c, line))} />
)}
</div>
)
}
function CategoryButton({ active, colour, onClick, children, testId }) {
function ModeButton({ active, onClick, icon: Icon, badge, children, testId }) {
return (
<button type="button" role="tab" aria-selected={active} onClick={onClick} data-testid={testId}
className={`relative min-h-[var(--x-control-lg)] rounded-control flex flex-col items-center justify-center gap-0.5 text-label font-semibold transition-colors duration-fast
${active ? 'bg-accent text-accent-fg' : 'bg-surface-2 text-ink-2 hover:bg-surface-3'}`}>
<Icon size={18} aria-hidden="true" />{children}
{badge ? <span className="absolute top-1 right-1 min-w-5 h-5 px-1 rounded-full bg-warning text-warning-fg text-caption font-bold flex items-center justify-center">{badge}</span> : null}
</button>
)
}
function NavButton({ active, colour, onClick, children, testId, count }) {
return (
<button type="button" onClick={onClick} data-testid={testId} aria-pressed={active}
className={`min-h-[var(--x-control-lg)] px-3 rounded-control text-left text-body font-medium flex items-center gap-2 transition-colors duration-fast
${active ? 'bg-accent-soft text-accent-ink' : 'text-ink hover:bg-surface-2'}`}>
{colour && <span className="size-2.5 rounded-full shrink-0" style={{ background: colour }} aria-hidden="true" />}
<span className="truncate">{children}</span>
<span className="flex-1 truncate">{children}</span>
{count && <span className="text-caption text-ink-3">{count.busy}/{count.total}</span>}
</button>
)
}
@@ -168,56 +171,3 @@ function ProductCard({ product, onTap, onInfo }) {
</div>
)
}
function SaleDone({ sale, onAgain }) {
const { t } = useTranslation('terminal')
const { formatMoney } = useFormat()
const r = sale.result
return (
<div className="m-3 p-4 rounded-card bg-success-soft text-success-ink grid gap-2" data-testid="sale-done" data-order={r.order_id}>
<div className="text-title font-semibold">{t('pos.done.paid', { total: formatMoney(r.total) })}</div>
{r.change != null && <div className="text-heading font-semibold" data-testid="sale-change">{t('pos.pay.change', { amount: formatMoney(r.change) })}</div>}
<div className="text-label">
{r.payments.map(p => t(`pos.done.${p.method}`, { amount: formatMoney(p.amount) })).join(' · ')}
{r.drawer === 'opened' && ` · ${t('pos.done.drawerOpened')}`}
{r.drawer === 'failed' && <span className="text-danger-ink"> · {t('pos.done.drawerFailed')}</span>}
{r.fiscal === 'pending' && ` · ${t('pos.done.fiscal')}`}
</div>
<Button variant="secondary" icon={<Repeat size={16} />} onClick={onAgain} data-testid="same-again">{t('pos.done.again')}</Button>
</div>
)
}
function CartLine({ line, priced, product, canDiscount, onQty, onDiscount }) {
const { t } = useTranslation('terminal')
const { formatMoney } = useFormat()
const unit = product ? unitOf(product) : null
const step = unit ? unit.step : 1
const qtyText = unit ? `${Number(line.quantity).toFixed(step < 1 ? 1 : 0)} ${unit.label}` : `${line.quantity}×`
return (
<div className="px-3 py-2 border-b border-line grid gap-1" data-testid="cart-line" data-product={line.product_id}>
<div className="flex items-start gap-2">
<span className="flex-1 min-w-0 text-body font-medium text-ink">{product?.name ?? priced?.name}</span>
<span className="text-body text-ink" data-testid="line-total">{priced ? formatMoney(priced.total) : '…'}</span>
</div>
{priced && (priced.entries.length > 0 || priced.removed.length > 0 || priced.notes) && (
<div className="text-label text-ink-2 grid">
{priced.entries.map((e, i) => <span key={i}>+ {e.name}{e.price ? ` (${formatMoney(e.price)})` : ''}</span>)}
{priced.removed.map(n => <span key={n} className="text-danger-ink">− {n}</span>)}
{priced.notes && <span className="italic">“{priced.notes}”</span>}
</div>
)}
<div className="flex items-center gap-2">
<IconButton size="sm" variant="secondary" label={t('pos.less')} onClick={() => onQty(line.quantity - step)}><Minus size={16} /></IconButton>
<span className="min-w-12 text-center text-body font-semibold" data-testid="line-qty">{qtyText}</span>
<IconButton size="sm" variant="secondary" label={t('pos.more')} onClick={() => onQty(line.quantity + step)}><Plus size={16} /></IconButton>
{priced && line.quantity !== 1 && <span className="text-caption text-ink-3">{t('pos.each', { price: formatMoney(priced.unit_price) })}</span>}
<span className="flex-1" />
<Select size="sm" value={String(line.discount_pct ?? 0)} onChange={e => onDiscount(Number(e.target.value))} aria-label={t('pos.discount')}
title={canDiscount ? undefined : t('pos.discountNeedsApproval')} data-testid="line-discount" className="w-36"
options={DISCOUNTS.map(d => ({ value: String(d), label: d ? `−${d}%` : t('pos.noDiscount') }))} />
</div>
{priced?.discount ? <span className="text-label text-success-ink">{t('pos.discountLine', { pct: priced.discount_pct, amount: formatMoney(priced.discount) })}</span> : null}
</div>
)
}