feat: ordering from the menu tablet at a table (platform-v2 step 6.6, D-30)

- tablet_orders (0034) + services/tablet_orders.py: venue rules (menu_tablet.ordering) with
  per-tablet overrides: kitchen or waiter confirms first, no open order open/refuse, limits
  (items per order, of one dish, time between orders)
- /api/menu-tablet: quote, order, order/{id}, bill (see + ask), requests accept/decline, ordering
- terminal: Add to the order (POS ProductDialog), cart, note, send, live status, the bill
- waiter: TabletRequests on the table page, tablet_order message theme with Open the table
- manager: Settings -> Menu tablets
- tests: test_tablet_orders.py, menu-tablet unit, menu_tablet.mjs e2e (the done-when)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-18 14:42:37 +02:00
co-authored by Claude Opus 5.5
parent c43dc8b55b
commit c1af7770cf
34 changed files with 1491 additions and 28 deletions
@@ -4,7 +4,8 @@
// compact / expanded / full view, photos, descriptions, grouped or one A–Z list, whose prices,
// sold-out style, search, one category or all, languages, back to the start after a while, light /
// dark. Keeps the last menu for offline; a menu change arrives live (`menu_tablet.changed`).
// A tablet set at a table (5.7b) can call the table's waiters (once a minute at most).
// A tablet set at a table (5.7b) can call the table's waiters (once a minute at most), and with
// "Guests can order" on take the table's orders and show its bill (6.6, TableOrdering.jsx).
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { BellRing, Search, X } from 'lucide-react'
import { useFormat, useLanguage, useTranslation } from '@xenia/i18n'
@@ -13,6 +14,8 @@ import { Allergens } from '@xenia/access'
import client from '../../api/client'
import { useLiveEvent, useLiveEvents } from '../../device/context'
import { idle, languagesOf, localize, search, sections } from './logic'
import { addToCart } from './ordering'
import { AddToOrder, BillButton, CartBar, OrderStatus } from './TableOrdering'
const quiet = { xenia: { noOverride: true } }
const CACHE_KEY = 'xenia:menu-tablet:menu'
@@ -28,6 +31,8 @@ export default function MenuTabletApp() {
const [data, setData] = useState(readCache)
const [q, setQ] = useState('')
const [open, setOpen] = useState(null)
const [cart, setCart] = useState([]) // the guests' order before it's sent (6.6)
const [lastOrder, setLastOrder] = useState(null) // what happened to the last one sent
const lastTouch = useRef(0) // set on the first touch and when the tablet starts (below)
const scroller = useRef(null)
@@ -61,6 +66,7 @@ export default function MenuTabletApp() {
const reset = useCallback(() => {
setQ('')
setOpen(null)
setCart([]) // new guests: a new order
scroller.current?.scrollTo?.({ top: 0 })
if (langs.length > 1 && language !== langs[0]) changeLanguage(langs[0])
}, [langs, language, changeLanguage])
@@ -93,6 +99,7 @@ export default function MenuTabletApp() {
{q && <button type="button" onClick={() => setQ('')} aria-label={t('menuTablet.clear')} className="absolute right-2 top-1/2 -translate-y-1/2 p-1 text-ink-3"><X size={16} /></button>}
</div>
)}
{data.table?.can_order && data.table?.can_see_bill && <BillButton language={language} />}
{data.table?.can_call && <CallWaiter table={data.table} />}
{langs.length > 1 && (
<div className="flex rounded-control border border-line overflow-hidden" role="group" aria-label={t('menuTablet.language')}>
@@ -113,6 +120,8 @@ export default function MenuTabletApp() {
</nav>
)}
<OrderStatus last={lastOrder} setLast={setLastOrder} />
<div ref={scroller} className="flex-1 overflow-y-auto px-4 py-4">
{q ? (
found.length ? <Items products={found} cfg={cfg} onOpen={setOpen} testid="menu-results" />
@@ -127,7 +136,10 @@ export default function MenuTabletApp() {
)}
</div>
{open && <Details product={open} cfg={cfg} onClose={() => setOpen(null)} />}
{data.table?.can_order && <CartBar cart={cart} setCart={setCart} onSent={setLastOrder} />}
{open && <Details product={open} cfg={cfg} onClose={() => setOpen(null)}
order={data.table?.can_order ? <AddToOrder product={open} ordering={data.ordering} onAdd={item => { setCart(c => addToCart(c, item)); setOpen(null) }} /> : null} />}
</main>
)
}
@@ -193,7 +205,7 @@ function Items({ products, cfg, onOpen, testid = 'menu-items' }) {
}
/** One product, big: its photo, price, description and tags. */
function Details({ product: p, cfg, onClose }) {
function Details({ product: p, cfg, onClose, order }) {
const { t } = useTranslation('terminal')
return (
<Dialog open size="md" title={p.name} onClose={onClose} closeLabel={t('menuTablet.close')}>
@@ -208,7 +220,7 @@ function Details({ product: p, cfg, onClose }) {
<div className="flex flex-wrap gap-1.5">{p.tags.map(tag => <span key={tag} className="px-2 py-0.5 rounded-control bg-surface-2 text-label text-ink-2">{tag}</span>)}</div>
)}
<Allergens allergens={p.allergens} />
{order}
</div>
</Dialog>
)
@@ -0,0 +1,209 @@
// Ordering from the menu tablet at a table (plan step 6.6, owner decisions D-30). On a tablet set
// at a table with "Guests can order" on:
// - a dish's "Add to the order" opens its choices (the counter's dialog, priced by the server at
// the in-store prices); the cart at the bottom collects them;
// - "Your order" shows the lines (more / less / remove), a note for the kitchen and the server's
// total; "Send to the kitchen" asks once more, then sends. Depending on the venue's (or this
// tablet's) rules the order goes straight to the kitchen, or waits for a waiter to confirm it:
// the tablet then says so and shows the answer when it comes (`menu_tablet.order`);
// - "The bill" (when on) lists what the table ordered so far and lets the guests ask for the bill.
// The limits (items per order, of one dish, time between orders) are the server's; its answer
// is shown as it comes.
import { useCallback, useEffect, useState } from 'react'
import { Minus, Plus, Receipt, ShoppingBag, Trash2 } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog, Field, IconButton, Spinner, Textarea } from '@xenia/ui'
import client from '../../api/client'
import { useLiveEvent } from '../../device/context'
import ProductDialog from '../pos/ProductDialog'
import { useQuote } from '../pos/usePos'
import { QUOTE_URL, cartCount, cartLines, changeQty } from './ordering'
const quiet = { xenia: { noOverride: true } }
/** "Add to the order" on a dish's details: its choices, then into the cart. */
export function AddToOrder({ product, ordering, onAdd }) {
const { t } = useTranslation('terminal')
const [choosing, setChoosing] = useState(false)
const choices = ordering?.choices?.[String(product.id)]
if (!choices || !product.available) return null
// the dialog shows the dish in the tablet's language
const shown = { ...choices, name: product.name, description: product.description || choices.description }
return (
<>
<Button size="lg" icon={<Plus size={18} />} onClick={() => setChoosing(true)} data-testid="menu-order-add">{t('menuTablet.order.add')}</Button>
{choosing && <ProductDialog product={shown} orderType="here" quoteUrl={QUOTE_URL} onClose={() => setChoosing(false)}
onAdd={line => onAdd({ line, name: product.name })} />}
</>
)
}
/** The cart bar and its sheet. `cart` = [{line, name}]. */
export function CartBar({ cart, setCart, onSent }) {
const { t } = useTranslation('terminal')
const { formatMoney } = useFormat()
const [open, setOpen] = useState(false)
const lines = cartLines(cart)
const { quote } = useQuote(lines, 'here', null, QUOTE_URL)
if (cart.length === 0) return null
return (
<>
<button type="button" onClick={() => setOpen(true)} data-testid="menu-cart"
className="mx-4 mb-4 h-14 px-5 rounded-card bg-accent text-accent-fg shadow-overlay flex items-center gap-3 text-body-lg font-semibold">
<ShoppingBag size={22} aria-hidden="true" />
<span className="flex-1 text-left">{t('menuTablet.order.yours', { count: cartCount(cart) })}</span>
{quote && <span className="tabular-nums" data-testid="menu-cart-total">{formatMoney(quote.total)}</span>}
</button>
{open && <CartDialog cart={cart} setCart={setCart} quote={quote} onClose={() => setOpen(false)}
onSent={result => { setOpen(false); onSent(result) }} />}
</>
)
}
function CartDialog({ cart, setCart, quote, onClose, onSent }) {
const { t } = useTranslation('terminal')
const { formatMoney } = useFormat()
const [note, setNote] = useState('')
const [confirming, setConfirming] = useState(false)
const [busy, setBusy] = useState(false)
const [problem, setProblem] = useState(null)
const send = async () => {
setBusy(true)
setProblem(null)
try {
const { data } = await client.post('/api/menu-tablet/order', { lines: cartLines(cart), note: note.trim() || null }, quiet)
setCart([])
onSent(data)
} catch (err) {
setProblem(errorMessage(err, t))
setConfirming(false)
} finally { setBusy(false) }
}
return (
<Dialog open size="lg" onClose={onClose} title={t('menuTablet.order.title')} closeLabel={t('menuTablet.close')}
footer={<>
<Button variant="secondary" size="lg" onClick={onClose}>{t('menuTablet.order.more')}</Button>
<Button size="lg" disabled={!cart.length} onClick={() => setConfirming(true)} data-testid="menu-order-send">{t('menuTablet.order.send')}</Button>
</>}>
<div className="grid gap-3" data-testid="menu-order">
<ul className="grid gap-2">
{cart.map((item, i) => {
const priced = quote?.lines?.[i]
return (
<li key={i} className="flex items-center gap-3 p-3 rounded-card bg-surface-2" data-testid="menu-order-line">
<span className="flex-1 min-w-0 grid">
<span className="text-body-lg font-medium truncate">{item.name}</span>
{priced?.entries?.length > 0 && <span className="text-label text-ink-2 truncate">{priced.entries.map(e => e.name).join(', ')}</span>}
</span>
<IconButton size="sm" variant="secondary" label={t('menuTablet.order.less')} onClick={() => setCart(c => changeQty(c, i, -1))}><Minus size={16} /></IconButton>
<span className="w-8 text-center tabular-nums font-semibold" data-testid="menu-order-qty">{item.line.quantity}</span>
<IconButton size="sm" variant="secondary" label={t('menuTablet.order.moreOf')} onClick={() => setCart(c => changeQty(c, i, 1))}><Plus size={16} /></IconButton>
<span className="w-20 text-right tabular-nums">{priced ? formatMoney(priced.total) : ''}</span>
<IconButton size="sm" variant="ghost" label={t('menuTablet.order.remove')} onClick={() => setCart(c => c.filter((_, j) => j !== i))}><Trash2 size={16} /></IconButton>
</li>
)
})}
</ul>
<div className="flex items-baseline justify-between">
<span className="text-body text-ink-2">{t('menuTablet.order.total')}</span>
<span className="text-heading font-semibold tabular-nums" data-testid="menu-order-total">{quote ? formatMoney(quote.total) : <Spinner size="sm" />}</span>
</div>
<Field label={t('menuTablet.order.note')}>
<Textarea rows={2} maxLength={300} value={note} onChange={e => setNote(e.target.value)} placeholder={t('menuTablet.order.notePlaceholder')} />
</Field>
{problem && <p role="alert" className="p-3 rounded-control bg-danger-soft text-danger-ink" data-testid="menu-order-problem">{problem}</p>}
</div>
{confirming && (
<Dialog open size="sm" onClose={() => setConfirming(false)} title={t('menuTablet.order.confirmTitle')}
footer={<>
<Button variant="secondary" size="lg" onClick={() => setConfirming(false)}>{t('menuTablet.order.notYet')}</Button>
<Button size="lg" loading={busy} onClick={send} data-testid="menu-order-confirm">{t('menuTablet.order.yesSend')}</Button>
</>}>
<p>{t('menuTablet.order.confirmBody', { count: cartCount(cart), total: quote ? formatMoney(quote.total) : '' })}</p>
</Dialog>
)}
</Dialog>
)
}
/** What happened to the last order: sent, waiting for a waiter, then the waiter's answer (live). */
export function OrderStatus({ last, setLast }) {
const { t } = useTranslation('terminal')
const check = useCallback(async () => {
if (!last) return
try {
const { data } = await client.get(`/api/menu-tablet/order/${last.id}`, quiet)
setLast(data)
} catch { /* offline: keep showing what we know */ }
}, [last, setLast])
useLiveEvent('menu_tablet.order', ev => { if (last && ev?.id === last.id) check() })
useLiveEvent('ready', check)
useEffect(() => {
if (!last || last.status === 'waiting') return undefined
const id = setTimeout(() => setLast(null), 15_000)
return () => clearTimeout(id)
}, [last, setLast])
if (!last) return null
const tone = last.status === 'declined' ? 'bg-danger-soft text-danger-ink' : last.status === 'waiting' ? 'bg-warning-soft text-warning-ink' : 'bg-success-soft text-success-ink'
return (
<div className={`mx-4 mt-3 p-3 rounded-card ${tone} flex items-center gap-3`} role="status" data-testid="menu-order-status" data-status={last.status}>
<span className="flex-1">
{t(`menuTablet.order.status.${last.status}`)}
{last.status === 'declined' && last.reason && ` ${t('menuTablet.order.reason', { reason: last.reason })}`}
</span>
{last.status !== 'waiting' && <Button size="sm" variant="ghost" onClick={() => setLast(null)}>{t('menuTablet.close')}</Button>}
</div>
)
}
/** "The bill": what the table ordered so far; ask the waiters for the bill. */
export function BillButton({ language }) {
const { t } = useTranslation('terminal')
const { formatMoney } = useFormat()
const [bill, setBill] = useState(null)
const [asked, setAsked] = useState(null) // 'sent' | an error text
const open = async () => {
setAsked(null)
try { setBill((await client.get('/api/menu-tablet/bill', quiet)).data) } catch (err) { setBill({ error: errorMessage(err, t) }) }
}
const ask = async () => {
try { await client.post('/api/menu-tablet/bill', {}, quiet); setAsked('sent') } catch (err) { setAsked(errorMessage(err, t)) }
}
return (
<>
<button type="button" onClick={open} data-testid="menu-bill-button"
className="flex items-center gap-2 px-4 py-2 rounded-control border border-line bg-surface text-label font-semibold whitespace-nowrap">
<Receipt size={18} aria-hidden="true" />{t('menuTablet.bill.title')}
</button>
{bill && (
<Dialog open size="md" onClose={() => setBill(null)} title={t('menuTablet.bill.title')} closeLabel={t('menuTablet.close')}
footer={!bill.error && <>
<Button variant="secondary" size="lg" onClick={() => setBill(null)}>{t('menuTablet.close')}</Button>
<Button size="lg" disabled={asked === 'sent'} onClick={ask} data-testid="menu-bill-ask">{t('menuTablet.bill.ask')}</Button>
</>}>
{bill.error ? <p className="text-danger-ink">{bill.error}</p> : (
<div className="grid gap-3" data-testid="menu-bill">
{bill.lines.length === 0 ? <p className="text-ink-2">{t('menuTablet.bill.empty')}</p> : (
<ul className="grid gap-1">
{bill.lines.map((l, i) => (
<li key={i} className={`flex justify-between gap-3 ${l.paid ? 'text-ink-3 line-through' : ''}`} data-testid="menu-bill-line">
<span>{l.quantity} × {l.names?.[language] || l.name}</span><span className="tabular-nums">{formatMoney(l.total)}</span>
</li>
))}
</ul>
)}
<div className="flex justify-between border-t border-line pt-2 text-body-lg font-semibold">
<span>{t('menuTablet.bill.due')}</span><span className="tabular-nums" data-testid="menu-bill-due">{formatMoney(bill.due)}</span>
</div>
{bill.paid > 0 && <p className="text-label text-ink-2">{t('menuTablet.bill.paid', { amount: formatMoney(bill.paid) })}</p>}
{asked === 'sent' && <p className="p-3 rounded-control bg-success-soft text-success-ink" role="status" data-testid="menu-bill-asked">{t('menuTablet.bill.asked')}</p>}
{asked && asked !== 'sent' && <p className="p-3 rounded-control bg-danger-soft text-danger-ink" role="alert">{asked}</p>}
<p className="text-label text-ink-3">{t('menuTablet.bill.note')}</p>
</div>
)}
</Dialog>
)}
</>
)
}
+28
View File
@@ -0,0 +1,28 @@
// The menu tablet's cart (plan step 6.6). Pure: unit-tested in Node (tests/menu-tablet.test.mjs).
// A cart item is { line, name }: the counter's line by id (apps/pos/logic/cart.js toLine) and the
// dish's name in the tablet's language. Prices are always the server's (POST /api/menu-tablet/quote).
export const QUOTE_URL = '/api/menu-tablet/quote'
/** The lines as the server takes them. */
export const cartLines = cart => cart.map(item => item.line)
/** How many items (quantities added up). */
export const cartCount = cart => cart.reduce((s, item) => s + (item.line.quantity || 1), 0)
/** One more / one less of a line; at 0 the line goes. */
export function changeQty(cart, index, step) {
return cart.flatMap((item, i) => {
if (i !== index) return [item]
const quantity = (item.line.quantity || 1) + step
return quantity > 0 ? [{ ...item, line: { ...item.line, quantity } }] : []
})
}
/** Add a line; the same dish with the same choices joins the existing line. */
export function addToCart(cart, item) {
const key = l => JSON.stringify({ ...l, quantity: undefined })
const at = cart.findIndex(c => key(c.line) === key(item.line))
if (at < 0) return [...cart, item]
return cart.map((c, i) => (i === at ? { ...c, line: { ...c.line, quantity: c.line.quantity + item.line.quantity } } : c))
}
+3 -2
View File
@@ -30,7 +30,8 @@ function Price({ value }) {
return value ? <span className="text-ink-2 text-label">{value > 0 ? '+' : ''}{formatMoney(value)}</span> : null
}
export default function ProductDialog({ product, orderType, onAdd, onClose }) {
// quoteUrl: the menu tablet (6.6) prices a guest's choices with its own endpoint (in-store prices, no discounts)
export default function ProductDialog({ product, orderType, onAdd, onClose, quoteUrl }) {
const { t } = useTranslation('terminal')
const { formatMoney } = useFormat()
const unit = unitOf(product)
@@ -38,7 +39,7 @@ export default function ProductDialog({ product, orderType, onAdd, onClose }) {
const [qty, setQty] = useState(unit ? unit.start : 1)
const missing = missingChoices(product, sel)
const line = useMemo(() => toLine(product, sel, qty), [product, sel, qty])
const { quote, pending } = useQuote(missing.length ? [] : [line], orderType)
const { quote, pending } = useQuote(missing.length ? [] : [line], orderType, null, quoteUrl)
const priced = quote?.lines?.[0]
const add = () => { onAdd(line); onClose() }
+3 -3
View File
@@ -45,17 +45,17 @@ export function useMenu() {
/** The cart priced by POST /api/pos/quote whenever it changes (latest answer wins). With
* `orderId` (a table's order) the order's items count for deals, as when it's sent.
* → { quote, pending, error } */
export function useQuote(lines, orderType, orderId = null) {
export function useQuote(lines, orderType, orderId = null, url = '/api/pos/quote') {
const [state, setState] = useState({ quote: null, pending: false, error: null })
const seq = useRef(0)
const key = JSON.stringify([lines, orderType, orderId])
const key = JSON.stringify([lines, orderType, orderId, url])
useEffect(() => {
const mine = ++seq.current
if (!lines.length) { setState({ quote: { lines: [], total: 0 }, pending: false, error: null }); return undefined }
setState(s => ({ ...s, pending: true }))
const id = setTimeout(async () => {
try {
const { data } = await client.post('/api/pos/quote', { order_type: orderType, lines, order_id: orderId ?? undefined }, quiet)
const { data } = await client.post(url, { order_type: orderType, lines, order_id: orderId ?? undefined }, quiet)
if (mine === seq.current) setState({ quote: data, pending: false, error: null })
} catch (err) {
if (mine === seq.current) setState(s => ({ ...s, pending: false, error: err }))