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
+40
View File
@@ -0,0 +1,40 @@
// One cart line at the counter (plan steps 3.3a–c): name, chosen options, quantity buttons,
// a per-line discount, and the backend's price for it (POST /api/pos/quote).
import { Minus, Plus } from 'lucide-react'
import { useFormat, useTranslation } from '@xenia/i18n'
import { IconButton, Select } from '@xenia/ui'
import { DISCOUNTS, unitOf } from './logic/cart'
export default 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>
)
}
+14 -17
View File
@@ -1,26 +1,26 @@
// Taking the payment at the counter (plan step 3.3b, D-26): cash (amount given → change,
// Taking a payment at the counter (plan steps 3.3b, 3.3c, D-26): cash (amount given → change,
// quick amounts), card (typed on the card terminal, recorded as card), or split between them
// by line. One call does the whole sale (POST /api/pos/sales): order, kitchen tickets,
// payment(s) on the cashier's shift, fiscal receipt, cash drawer. Cash with the exact amount
// is pre-selected: Charge → Cash → Take = three taps.
// by row. The caller's `submit({ method, rowMethods, cashGiven })` makes the one call: a quick
// sale (POST /api/pos/sales, rows = cart lines) or a table's items (POST /api/pos/orders/{id}/pay,
// rows = order items). Cash with the exact amount is pre-selected: Charge → Take = two taps.
import { useState } from 'react'
import { Banknote, Check, CreditCard, Split } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { parseNumber, useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog, Input } from '@xenia/ui'
import client from '../../api/client'
import { changeFor, quickAmounts, splitPayments } from './logic/cart'
const tab = on => `flex-1 min-h-[var(--x-control-lg)] rounded-control flex items-center justify-center gap-2 text-body-lg font-medium transition-colors duration-fast
${on ? 'bg-accent text-accent-fg' : 'bg-surface-2 text-ink-2 hover:bg-surface-3'}`
export default function PaymentDialog({ cart, quote, orderType, names, onPaid, onClose }) {
/** rows: [{ label, total }]; submit({ method: 'cash'|'card'|'split', rowMethods, payments, cashGiven })
* → the result passed to onPaid. `payments` are by row index (splitPayments). */
export default function PaymentDialog({ total, rows, submit, onPaid, onClose }) {
const { t } = useTranslation('terminal')
const { formatMoney } = useFormat()
const total = quote.total
const totals = quote.lines.map(l => l.total)
const totals = rows.map(r => r.total)
const [method, setMethod] = useState('cash')
const [split, setSplit] = useState(() => cart.map(() => 'card'))
const [split, setSplit] = useState(() => rows.map(() => 'card'))
const parts = splitPayments(split, totals)
const cashDue = method === 'cash' ? total : method === 'split' ? parts.cash : 0
const [givenText, setGivenText] = useState('') // empty = the exact amount
@@ -34,12 +34,9 @@ export default function PaymentDialog({ cart, quote, orderType, names, onPaid, o
if (busy || short) return
setBusy(true)
setError('')
const payments = method === 'split' ? parts.payments : [{ method }]
const payments = method === 'split' ? parts.payments : [{ method, lines: rows.map((_, i) => i) }]
try {
const { data } = await client.post('/api/pos/sales', {
order_type: orderType, lines: cart, payments, cash_given: cashDue > 0 ? (given ?? cashDue) : null,
})
onPaid(data)
onPaid(await submit({ method, rowMethods: split, payments, cashGiven: cashDue > 0 ? (given ?? cashDue) : null }))
} catch (err) {
setError(errorMessage(err, t))
} finally {
@@ -68,10 +65,10 @@ export default function PaymentDialog({ cart, quote, orderType, names, onPaid, o
</div>
{method === 'split' && (
<div className="grid gap-1" data-testid="split-lines">
{cart.map((line, i) => (
<div className="grid gap-1 max-h-72 overflow-y-auto" data-testid="split-lines">
{rows.map((row, i) => (
<div key={i} className="flex items-center gap-2 py-1 border-b border-line">
<span className="flex-1 min-w-0 text-body text-ink truncate">{line.quantity}× {names[i]}</span>
<span className="flex-1 min-w-0 text-body text-ink truncate">{row.label}</span>
<span className="text-body text-ink-2">{formatMoney(totals[i])}</span>
<span className="flex gap-1">
{['cash', 'card'].map(m => (
+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>
)
}
+102
View File
@@ -0,0 +1,102 @@
// The quick-sale cart (plan steps 3.3a–b): order type, the lines priced by the backend,
// Charge → PaymentDialog (POST /api/pos/sales); after a sale it shows what happened and
// "Same again".
import { useState } from 'react'
import { Banknote, Repeat, ShoppingBag, Trash2, Utensils } from 'lucide-react'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, EmptyState, useToast } from '@xenia/ui'
import client from '../../api/client'
import CartLine from './CartLine'
import { setLineQty } from './logic/cart'
import PaymentDialog from './PaymentDialog'
import { useQuote } from './usePos'
export default function SaleCart({ cart, setCart, orderType, setOrderType, byId, canDiscount }) {
const { t } = useTranslation('terminal')
const { formatMoney } = useFormat()
const toast = useToast()
const [paying, setPaying] = useState(false)
const [lastSale, setLastSale] = useState(null) // { lines, orderType, result }
const quote = useQuote(cart, orderType)
const ready = cart.length > 0 && !quote.pending && !quote.error && quote.quote?.lines?.length === cart.length
const submit = async ({ method, payments, cashGiven }) => (await client.post('/api/pos/sales', {
order_type: orderType, lines: cart, payments: method === 'split' ? payments : [{ method }], cash_given: cashGiven,
})).data
return (
<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>
{paying && quote.quote && (
<PaymentDialog total={quote.quote.total} submit={submit}
rows={cart.map((l, i) => ({ label: `${l.quantity}× ${byId.get(l.product_id)?.name ?? ''}`, total: quote.quote.lines[i].total }))}
onClose={() => setPaying(false)}
onPaid={result => {
setPaying(false)
setLastSale({ lines: cart, orderType, result })
setCart([])
toast.success(result.change > 0 ? t('pos.done.toastChange', { change: formatMoney(result.change) }) : t('pos.done.toast'))
}} />
)}
</aside>
)
}
export function PaidSummary({ result }) {
const { t } = useTranslation('terminal')
const { formatMoney } = useFormat()
return (
<div className="text-label">
{result.payments.map(p => t(`pos.done.${p.method}`, { amount: formatMoney(p.amount) })).join(' · ')}
{result.drawer === 'opened' && ` · ${t('pos.done.drawerOpened')}`}
{result.drawer === 'failed' && <span className="text-danger-ink"> · {t('pos.done.drawerFailed')}</span>}
{result.fiscal === 'pending' && ` · ${t('pos.done.fiscal')}`}
</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 > 0 && <div className="text-heading font-semibold" data-testid="sale-change">{t('pos.pay.change', { amount: formatMoney(r.change) })}</div>}
<PaidSummary result={r} />
<Button variant="secondary" icon={<Repeat size={16} />} onClick={onAgain} data-testid="same-again">{t('pos.done.again')}</Button>
</div>
)
}
+241
View File
@@ -0,0 +1,241 @@
// A table at the counter (plan step 3.3c): the right column while a table is open. It shows
// what's on the table's order (the waiter app's order, live), new lines from the product grid
// (priced with the order's items counted, as when sent), and the actions: send to the table,
// pay some or all items (cash/card/split, drawer), cancel sent items (a manager approves when
// the cashier can't: the shared approval dialog), close once everything is paid.
import { useEffect, useState } from 'react'
import { ArrowLeft, Ban, Banknote, Check, CheckCircle2, Lock, Send, Trash2 } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog, EmptyState, IconButton, Spinner, useToast } from '@xenia/ui'
import client from '../../api/client'
import CartLine from './CartLine'
import { setLineQty } from './logic/cart'
import { itemPayments, orderLines, orderSums, qtyLabel, tableState, toPay } from './logic/tables'
import PaymentDialog from './PaymentDialog'
import { PaidSummary } from './SaleCart'
import { useOrder, useQuote } from './usePos'
export default function TablePanel({ table, cart, setCart, byId, canDiscount, onBack, onTablesChanged }) {
const { t } = useTranslation('terminal')
const { formatMoney, formatTime } = useFormat()
const toast = useToast()
const orderId = table.order?.id ?? null
const { order, gone, reload } = useOrder(orderId)
const quote = useQuote(cart, 'here', orderId)
const [picked, setPicked] = useState([])
const [busy, setBusy] = useState(false)
const [paying, setPaying] = useState(null) // rows being paid
const [cancelling, setCancelling] = useState(false)
const [lastPay, setLastPay] = useState(null)
const [error, setError] = useState('')
const lines = orderLines(order)
const sums = orderSums(lines)
const state = tableState(table)
const ready = cart.length > 0 && !quote.pending && !quote.error && quote.quote?.lines?.length === cart.length
// only items still unpaid stay selected (a phone may pay or cancel meanwhile)
const selected = picked.filter(id => sums.unpaidIds.includes(id))
const setSelected = setPicked
const chosen = toPay(lines, selected)
useEffect(() => {
if (gone && orderId != null) { toast.info(t('pos.table.closedElsewhere', { table: table.name })); onBack() }
}, [gone]) // eslint-disable-line react-hooks/exhaustive-deps -- once, when the order goes
const run = async (fn) => {
setBusy(true)
setError('')
try { return await fn() } catch (err) { setError(errorMessage(err, t)); return null } finally { setBusy(false) }
}
const send = () => run(async () => {
await client.post(`/api/pos/tables/${table.id}/items`, { lines: cart })
setCart([])
setLastPay(null)
toast.success(t('pos.table.sent', { table: table.name }))
onTablesChanged()
reload()
})
const close = () => run(async () => {
await client.post(`/api/pos/orders/${orderId}/close`)
toast.success(t('pos.table.closed', { table: table.name }))
onTablesChanged()
onBack()
})
const cancel = () => run(async () => {
const ids = lines.filter(l => !l.paid && selected.includes(l.id)).map(l => l.id)
await client.post(`/api/orders/${orderId}/cancel-items`, { item_ids: ids, print_cancellation: true })
setCancelling(false)
setSelected([])
toast.success(t('pos.table.cancelled', { count: ids.length }))
reload()
})
const payRows = chosen.map(l => ({ id: l.id, label: `${qtyLabel(l.quantity, l.unitType)} ${l.name}`, total: l.total }))
const submitPay = async ({ method, payments, cashGiven }) => (await client.post(`/api/pos/orders/${orderId}/pay`, {
payments: method === 'split' ? itemPayments(payments, paying) : [{ method, item_ids: paying.map(r => r.id) }],
cash_given: cashGiven,
})).data
const toggle = id => setSelected(sel => (sel.includes(id) ? sel.filter(x => x !== id) : [...sel, id]))
return (
<aside className="border-l border-line bg-surface flex flex-col min-h-0" data-testid="table-panel" data-table={table.id} data-order={orderId ?? ''}>
<div className="p-3 border-b border-line flex items-center gap-2">
<IconButton label={t('pos.table.back')} variant="secondary" onClick={onBack} data-testid="table-back"><ArrowLeft size={18} /></IconButton>
<div className="flex-1 min-w-0">
<div className="text-title font-semibold truncate">{table.name}</div>
<div className="text-caption text-ink-2 truncate">
{table.order
? `${table.order.people.join(', ')} · ${t('pos.tables.since', { time: formatTime(table.order.opened_at) })}`
: t('pos.tables.state.free')}
</div>
</div>
</div>
<div className="flex-1 overflow-y-auto">
{orderId != null && !order && <div className="p-6 flex justify-center"><Spinner /></div>}
{lastPay && cart.length === 0 && (
<div className="m-3 p-3 rounded-card bg-success-soft text-success-ink grid gap-1" data-testid="table-paid">
<div className="text-body-lg font-semibold">{t('pos.done.paid', { total: formatMoney(lastPay.total) })}</div>
{lastPay.change > 0 && <div className="text-heading font-semibold" data-testid="table-change">{t('pos.pay.change', { amount: formatMoney(lastPay.change) })}</div>}
<PaidSummary result={lastPay} />
</div>
)}
{lines.length > 0 && (
<section data-testid="order-lines">
<h3 className="px-3 pt-3 pb-1 text-label font-semibold text-ink-2 flex justify-between">
<span>{t('pos.table.onOrder')}</span><span>{formatMoney(sums.total)}</span>
</h3>
{lines.map(l => (
<OrderLine key={l.id} line={l} selected={selected.includes(l.id)} onToggle={() => toggle(l.id)} />
))}
</section>
)}
{cart.length > 0 && (
<section data-testid="new-lines">
<h3 className="px-3 pt-3 pb-1 text-label font-semibold text-accent-ink">{t('pos.table.new')}</h3>
{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((x, j) => (j === i ? { ...x, discount_pct: pct || undefined } : x)))} />
))}
</section>
)}
{lines.length === 0 && cart.length === 0 && (orderId == null || order) && (
<EmptyState compact title={t('pos.table.empty')} description={t('pos.table.emptyBody')} />
)}
</div>
<div className="border-t border-line p-3 grid gap-2">
{(error || quote.error) && <p role="alert" className="text-label text-danger-ink">{error || t('pos.quoteFailed')}</p>}
{cart.length > 0 ? (
<>
<div className="flex items-baseline justify-between">
<span className="text-body-lg text-ink-2">{t('pos.table.newTotal')}</span>
<span className={`text-heading font-semibold ${quote.pending ? 'opacity-50' : ''}`} data-testid="cart-total">{formatMoney(quote.quote?.total ?? 0)}</span>
</div>
<Button size="lg" icon={<Send size={18} />} disabled={!ready} loading={busy} onClick={send} data-testid="table-send">
{t('pos.table.send', { table: table.name })}
</Button>
<Button variant="secondary" icon={<Trash2 size={16} />} onClick={() => setCart([])}>{t('pos.clearCart')}</Button>
</>
) : sums.unpaid > 0 ? (
<>
<div className="flex items-baseline justify-between">
<span className="text-body-lg text-ink-2">{t('pos.table.due')}</span>
<span className="text-display font-semibold" data-testid="table-due-total">{formatMoney(sums.unpaid)}</span>
</div>
<Button size="lg" icon={<Banknote size={20} />} disabled={busy} onClick={() => setPaying(payRows)} data-testid="table-pay">
{selected.length ? t('pos.table.paySelected', { amount: formatMoney(orderSums(chosen).total) }) : t('pos.table.payAll', { amount: formatMoney(sums.unpaid) })}
</Button>
<div className="grid grid-cols-2 gap-2">
<Button variant="secondary" icon={<Ban size={16} />} disabled={!selected.length || busy} onClick={() => setCancelling(true)} data-testid="table-cancel">
{t('pos.table.cancel')}
</Button>
<Button variant="secondary" icon={<Check size={16} />} disabled={busy}
onClick={() => setSelected(selected.length ? [] : sums.unpaidIds)}>
{selected.length ? t('pos.table.selectNone') : t('pos.table.selectAll')}
</Button>
</div>
</>
) : orderId != null && order && state === 'paid' ? (
<Button size="lg" icon={<Lock size={18} />} loading={busy} onClick={close} data-testid="table-close">
{t('pos.table.close', { table: table.name })}
</Button>
) : null}
</div>
{paying && (
<PaymentDialog total={orderSums(paying).total} rows={paying} submit={submitPay}
onClose={() => setPaying(null)}
onPaid={result => {
setPaying(null)
setSelected([])
setLastPay(result)
toast.success(result.change > 0 ? t('pos.done.toastChange', { change: formatMoney(result.change) }) : t('pos.done.toast'))
onTablesChanged()
if (result.auto_closed) onBack()
else reload()
}} />
)}
{cancelling && (
<Dialog open size="sm" title={t('pos.table.cancelTitle', { count: selected.length })} onClose={busy ? undefined : () => setCancelling(false)}
footer={<>
<Button variant="secondary" onClick={() => setCancelling(false)} disabled={busy}>{t('pos.table.keep')}</Button>
<Button variant="danger" icon={<Ban size={16} />} loading={busy} onClick={cancel} data-testid="cancel-confirm">{t('pos.table.cancelConfirm')}</Button>
</>}>
<div className="grid gap-2">
<p className="text-body text-ink-2">{t('pos.table.cancelBody')}</p>
<ul className="text-body text-ink grid gap-0.5">
{lines.filter(l => selected.includes(l.id)).map(l => <li key={l.id}>{qtyLabel(l.quantity, l.unitType)} {l.name}</li>)}
</ul>
{error && <p role="alert" className="text-label text-danger-ink">{error}</p>}
</div>
</Dialog>
)}
</aside>
)
}
function OrderLine({ line, selected, onToggle }) {
const { t } = useTranslation('terminal')
const { formatMoney } = useFormat()
const body = (
<>
<span className="flex items-start gap-2">
{!line.paid && (
<span aria-hidden="true" className={`mt-0.5 size-5 shrink-0 rounded-control border-2 flex items-center justify-center
${selected ? 'bg-accent border-accent text-accent-fg' : 'border-line-strong'}`}>
{selected && <Check size={14} />}
</span>
)}
{line.paid && <CheckCircle2 size={18} className="mt-0.5 shrink-0 text-success-ink" aria-hidden="true" />}
<span className="flex-1 min-w-0">
<span className="text-body font-medium">{qtyLabel(line.quantity, line.unitType)} {line.name}</span>
{(line.options.length > 0 || line.notes) && (
<span className="block text-caption text-ink-2 truncate">{[...line.options, line.notes && `“${line.notes}”`].filter(Boolean).join(' · ')}</span>
)}
</span>
<span className="text-body text-right">
{formatMoney(line.total)}
{line.paid && <span className="block text-caption text-success-ink">{t(`pos.table.paidBy.${line.method === 'card' ? 'card' : 'cash'}`)}</span>}
{!line.paid && line.kds === 'done' && <span className="block text-caption text-success-ink">{t('pos.table.readyItem')}</span>}
</span>
</span>
</>
)
if (line.paid) {
return <div className="px-3 py-2 border-b border-line text-ink-3" data-testid="order-line" data-item={line.id} data-paid="true">{body}</div>
}
return (
<button type="button" onClick={onToggle} aria-pressed={selected} data-testid="order-line" data-item={line.id} data-paid="false"
className={`w-full text-left px-3 py-2 border-b border-line transition-colors duration-fast ${selected ? 'bg-accent-soft text-accent-ink' : 'text-ink hover:bg-surface-2'}`}>
{body}
</button>
)
}
+93
View File
@@ -0,0 +1,93 @@
// The table list at the counter (plan step 3.3c): the cashier's tables (their zones, as in
// the waiter app), each with its state, what's still due, who is on it, ready items, flags
// and a reservation due soon. A tap opens the table: the product grid adds to its order and
// the right column shows the order (TablePanel). Live: a waiter's change shows at once.
import { CalendarClock, ChefHat, Users } from 'lucide-react'
import { useFormat, useTranslation } from '@xenia/i18n'
import { EmptyState, Spinner } from '@xenia/ui'
import { tableState, tablesIn } from './logic/tables'
const LOOK = {
free: 'bg-surface border-line text-ink',
mine: 'bg-accent-soft border-accent text-accent-ink',
open: 'bg-info-soft border-info text-info-ink',
paid: 'bg-success-soft border-success text-success-ink',
}
export default function TablesView({ data, zone, onPick }) {
const { t } = useTranslation('terminal')
if (!data) return <div className="flex-1 flex items-center justify-center"><Spinner /></div>
// all zones: one section per zone (table numbers can repeat between zones)
const sections = zone != null
? [{ id: zone, name: null, tables: tablesIn(data.tables, zone) }]
: [...data.groups.map(g => ({ id: g.id, name: g.name, tables: tablesIn(data.tables, g.id) })),
{ id: 'none', name: t('pos.tables.noZone'), tables: data.tables.filter(x => x.group_id == null) }].filter(s => s.tables.length)
if (!data.tables.length) {
return <div className="flex-1 flex items-center justify-center p-6"><EmptyState title={t('pos.tables.none')} description={t('pos.tables.noneBody')} /></div>
}
return (
<div className="flex-1 overflow-y-auto p-3 grid content-start gap-4" data-testid="pos-tables">
{sections.map(s => (
<section key={s.id} className="grid gap-2">
{s.name && <h2 className="text-label font-semibold text-ink-2">{s.name}</h2>}
<div className="grid gap-3" style={{ gridTemplateColumns: 'repeat(auto-fill, minmax(11rem, 1fr))' }}>
{s.tables.map(table => <TableCard key={table.id} table={table} onPick={() => onPick(table.id)} />)}
</div>
</section>
))}
</div>
)
}
function TableCard({ table, onPick }) {
const { t } = useTranslation('terminal')
const { formatMoney, formatTime } = useFormat()
const state = tableState(table)
const o = table.order
return (
<button type="button" onClick={onPick} data-testid="pos-table" data-table={table.id} data-state={state}
className={`min-h-32 p-3 rounded-card border-2 shadow-raised text-left flex flex-col gap-1 active:scale-[0.98] transition-transform duration-fast ${LOOK[state]}`}>
<span className="flex items-start gap-2">
<span className="flex-1 min-w-0 text-title font-semibold truncate">{table.name}</span>
{table.seats ? <span className="text-label opacity-70 flex items-center gap-1"><Users size={14} aria-hidden="true" />{table.seats}</span> : null}
</span>
<span className="text-label font-medium" data-testid="table-state">
{state === 'open' ? (o.people.join(', ') || t('pos.tables.state.open')) : t(`pos.tables.state.${state}`)}
</span>
{o && (
<>
<span className="text-heading font-semibold" data-testid="table-due">
{state === 'paid' ? formatMoney(o.total) : formatMoney(o.unpaid)}
</span>
<span className="text-caption opacity-80">
{o.unpaid < o.total - 0.004 && state !== 'paid' ? `${t('pos.tables.ofTotal', { total: formatMoney(o.total) })} · ` : ''}
{t('pos.tables.since', { time: formatTime(o.opened_at) })}
</span>
{o.ready > 0 && (
<span className="self-start px-2 py-0.5 rounded-control bg-success text-success-fg text-caption font-semibold flex items-center gap-1" data-testid="table-ready">
<ChefHat size={12} aria-hidden="true" />{t('pos.tables.ready', { count: o.ready })}
</span>
)}
</>
)}
{!o && table.reservation && (
<span className="text-caption text-warning-ink flex items-center gap-1">
<CalendarClock size={12} aria-hidden="true" />
{t('pos.tables.reserved', { time: formatTime(table.reservation.reserved_for), name: table.reservation.guest_name, count: table.reservation.party_size })}
</span>
)}
{table.flags.length > 0 && (
<span className="flex flex-wrap gap-1 mt-auto pt-1">
{table.flags.map(f => (
// flag colours are the venue's own data (manager → flags), like category colours
<span key={f.id} title={f.name}
className={`px-1.5 py-0.5 rounded-control text-caption font-medium ${f.color ? 'text-accent-fg' : 'bg-surface-2 text-ink'}`}
style={{ background: f.color || undefined, color: f.text_color || undefined }}>
{f.emoji ? `${f.emoji} ` : ''}{f.name}
</span>
))}
</span>
)}
</button>
)
}
+88
View File
@@ -0,0 +1,88 @@
// Tables at the counter (plan step 3.3c): what the table list and a table's order show.
// Amounts come from the backend (GET /api/pos/tables, GET /api/orders/{id}); this file only
// groups, labels and adds up what it was given. Pure: unit-tested in Node (tests/pos.test.mjs).
/** free | mine | open (someone else's) | paid (nothing left to pay). */
export function tableState(table) {
const o = table.order
if (!o) return 'free'
if (o.items > 0 && o.unpaid <= 0.004) return 'paid'
return o.mine ? 'mine' : 'open'
}
/** Tables of one zone (null = all), in the backend's order. */
export function tablesIn(tables, groupId) {
return groupId == null ? tables : tables.filter(t => t.group_id === groupId)
}
/** Counts for the zone list: { [groupId|'all']: { total, busy } }. */
export function zoneCounts(tables) {
const out = { all: { total: 0, busy: 0 } }
for (const t of tables) {
const k = t.group_id ?? 'none'
out[k] = out[k] ?? { total: 0, busy: 0 }
for (const c of [out.all, out[k]]) {
c.total += 1
if (t.order) c.busy += 1
}
}
return out
}
const round2 = n => Math.round(n * 100) / 100
/** The option names stored on an order item (selected_options is JSON text or a list). */
export function optionNames(selected) {
let list = selected
if (typeof selected === 'string') {
try { list = JSON.parse(selected) } catch { list = [] }
}
return Array.isArray(list) ? list.map(o => o?.name).filter(Boolean) : []
}
/** An order's items as the counter lists them (cancelled and written-off ones left out),
* unpaid first, each with its total. */
export function orderLines(order) {
if (!order?.items) return []
const lines = order.items
.filter(i => i.status === 'active' || i.status === 'ready' || i.status === 'paid')
.map(i => ({
id: i.id,
name: i.product_name ?? i.product?.name ?? '',
quantity: i.quantity,
unitType: i.unit_type,
total: round2((i.unit_price + (i.price_adjustment || 0)) * i.quantity),
paid: i.status === 'paid',
method: i.payment_method,
options: optionNames(i.selected_options),
notes: i.notes,
kds: i.kds_status ?? 'pending',
}))
return [...lines.filter(l => !l.paid), ...lines.filter(l => l.paid)]
}
/** { total, paid, unpaid, unpaidIds } of the lines. */
export function orderSums(lines) {
const sum = ls => round2(ls.reduce((s, l) => s + l.total, 0))
const open = lines.filter(l => !l.paid)
return { total: sum(lines), paid: sum(lines.filter(l => l.paid)), unpaid: sum(open), unpaidIds: open.map(l => l.id) }
}
/** What "Pay" takes: the selected unpaid lines, or every unpaid line when none is selected. */
export function toPay(lines, selected) {
const open = lines.filter(l => !l.paid)
const chosen = open.filter(l => selected.includes(l.id))
return chosen.length ? chosen : open
}
/** The dialog's payments (by row index) as POST /api/pos/orders/{id}/pay takes them. */
export function itemPayments(payments, rows) {
return payments.map(p => ({ method: p.method, item_ids: p.lines.map(i => rows[i].id) }))
}
/** "2×" or "0.5 kg" for an order line. */
export function qtyLabel(quantity, unitType) {
const units = { kg: 'kg', liter: 'L', gram: 'g', ml: 'mL' }
if (!units[unitType]) return `${quantity}×`
return unitType === 'kg' || unitType === 'liter' ? `${Number(quantity).toFixed(1)} ${units[unitType]}` : `${quantity} ${units[unitType]}`
}
+57 -7
View File
@@ -1,5 +1,6 @@
// The counter POS's server data (plan step 3.3a): the cashier's session (shift gate), the
// menu, and the cart priced by the backend. Kept fresh by the live connection.
// The counter POS's server data (plan steps 3.3a, 3.3c): the cashier's session (shift gate),
// the menu, the cart priced by the backend, the tables and a table's order. Kept fresh by the
// live connection, so a waiter's phone and the counter see each other's changes at once.
import { useCallback, useEffect, useRef, useState } from 'react'
import client from '../../api/client'
import { useLiveEvent, useLiveEvents } from '../../device/context'
@@ -40,25 +41,74 @@ export function useMenu() {
return { menu, reload: load }
}
/** The cart priced by POST /api/pos/quote whenever it changes (latest answer wins).
/** 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) {
export function useQuote(lines, orderType, orderId = null) {
const [state, setState] = useState({ quote: null, pending: false, error: null })
const seq = useRef(0)
const key = JSON.stringify([lines, orderType])
const key = JSON.stringify([lines, orderType, orderId])
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 }, quiet)
const { data } = await client.post('/api/pos/quote', { 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 }))
}
}, QUOTE_DELAY_MS)
return () => clearTimeout(id)
}, [key]) // eslint-disable-line react-hooks/exhaustive-deps -- `key` is lines + orderType
}, [key]) // eslint-disable-line react-hooks/exhaustive-deps -- `key` is lines + orderType + orderId
return state
}
const TABLE_EVENTS = ['order_updated', 'order_paid', 'order_closed', 'table_flags_changed', 'table_list_changed', 'kds_order_updated', 'kds_item_updated']
const COALESCE_MS = 150
/** Calls `load` once for a burst of events (a payment sends several). */
function useCoalesced(load) {
const timer = useRef(null)
useEffect(() => () => clearTimeout(timer.current), [])
return useCallback(() => {
clearTimeout(timer.current)
timer.current = setTimeout(load, COALESCE_MS)
}, [load])
}
/** GET /api/pos/tables: { groups, tables } (null while loading); live. */
export function useTables() {
const [data, setData] = useState(null)
const load = useCallback(async () => {
try { setData((await client.get('/api/pos/tables', quiet)).data) } catch { /* the shell shows offline */ }
}, [])
const soon = useCoalesced(load)
useEffect(() => { load() }, [load])
useLiveEvent('ready', load)
useLiveEvents(TABLE_EVENTS, soon)
return { data, reload: load }
}
/** GET /api/orders/{id} for one order (null id → null); reloads on that order's events.
* → { order, gone, reload } (gone: closed or removed meanwhile). */
export function useOrder(orderId) {
const [order, setOrder] = useState(null)
const [gone, setGone] = useState(false)
const load = useCallback(async () => {
if (orderId == null) { setOrder(null); setGone(false); return }
try {
const { data } = await client.get(`/api/orders/${orderId}`, quiet)
setOrder(data)
setGone(data.status === 'closed' || data.status === 'cancelled')
} catch (err) {
if (err?.xenia?.status === 404) setGone(true)
}
}, [orderId])
const soon = useCoalesced(load)
useEffect(() => { load() }, [load])
useLiveEvent('ready', load)
useLiveEvents(TABLE_EVENTS, (_type, data) => { if (data?.order_id === orderId) soon() })
return { order, gone, reload: load }
}
+30
View File
@@ -98,3 +98,33 @@ test('paying: quick amounts, change, split parts (3.3b)', async () => {
assert.deepEqual(splitPayments(['card', 'cash', 'cash'], [10, 3, 2.5]),
{ cash: 5.5, card: 10, payments: [{ method: 'card', lines: [0] }, { method: 'cash', lines: [1, 2] }] })
})
test('tables at the counter: state, zones, order lines, what Pay takes (3.3c)', async () => {
const { itemPayments, optionNames, orderLines, orderSums, qtyLabel, tableState, tablesIn, toPay, zoneCounts } = await import('../src/apps/pos/logic/tables.js')
const free = { id: 1, group_id: 7, order: null }
const mine = { id: 2, group_id: 7, order: { items: 2, unpaid: 6, total: 6, mine: true } }
const theirs = { id: 3, group_id: 8, order: { items: 1, unpaid: 3, total: 3, mine: false } }
const paid = { id: 4, group_id: 8, order: { items: 1, unpaid: 0, total: 3, mine: false } }
assert.deepEqual([free, mine, theirs, paid].map(tableState), ['free', 'mine', 'open', 'paid'])
assert.deepEqual(tablesIn([free, mine, theirs], 8).map(t => t.id), [3])
assert.deepEqual(zoneCounts([free, mine, theirs, paid]), { all: { total: 4, busy: 3 }, 7: { total: 2, busy: 1 }, 8: { total: 2, busy: 2 } })
assert.deepEqual(optionNames('[{"name":"Rare"},{"name":"Fries"}]'), ['Rare', 'Fries'])
assert.deepEqual(optionNames('not json'), [])
const order = { items: [
{ id: 10, product_name: 'Freddo', quantity: 2, unit_price: 3, price_adjustment: 0, status: 'paid', payment_method: 'cash' },
{ id: 11, product_name: 'Burger', quantity: 1, unit_price: 10, price_adjustment: -1, status: 'active', selected_options: '[{"name":"Rare"}]' },
{ id: 12, product_name: 'Old', quantity: 1, unit_price: 5, status: 'cancelled' },
{ id: 13, product_name: 'Wine', quantity: 0.5, unit_type: 'liter', unit_price: 12, status: 'ready', kds_status: 'done' },
] }
const lines = orderLines(order)
assert.deepEqual(lines.map(l => [l.id, l.total, l.paid]), [[11, 9, false], [13, 6, false], [10, 6, true]])
assert.deepEqual(lines[0].options, ['Rare'])
assert.deepEqual(orderSums(lines), { total: 21, paid: 6, unpaid: 15, unpaidIds: [11, 13] })
assert.deepEqual(toPay(lines, []).map(l => l.id), [11, 13]) // nothing selected → everything unpaid
assert.deepEqual(toPay(lines, [13, 10]).map(l => l.id), [13]) // a paid line can't be chosen
const rows = toPay(lines, []).map(l => ({ id: l.id, total: l.total }))
assert.deepEqual(itemPayments([{ method: 'card', lines: [1] }, { method: 'cash', lines: [0] }], rows),
[{ method: 'card', item_ids: [13] }, { method: 'cash', item_ids: [11] }])
assert.equal(qtyLabel(2, 'piece'), '2×')
assert.equal(qtyLabel(0.5, 'liter'), '0.5 L')
})