feat(terminal): counter POS screen with server-priced cart and shift gate (platform-v2 3.3a)

- Backend /api/pos (pos_counter): session (business day, the cashier's own shift,
  self-start, who can open the day), menu (sellable products with every kind of choice,
  no costs; price now from the pricing engine), quote (lines by id → the waiter's
  selected_options entries with DB prices → resolve_price as orders do; pos.line_invalid).
- POS device settings: default order type, start category, receipt printer (new ref
  sources categories / printers, also in the manager's Devices dialogs).
- Terminal apps/pos: shift gate (start shift with drawer cash), categories, search,
  product grid, price check, options dialog, cart priced by the backend.
- Tests: backend test_pos (13), terminal pos.test.mjs, manager refOptions,
  terminal.mjs +10 POS checks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-14 21:55:30 +02:00
co-authored by Claude Opus 5.5
parent b1112b249e
commit 17bee66df1
25 changed files with 1556 additions and 21 deletions
+13 -3
View File
@@ -1,6 +1,16 @@
// Placeholder until step 3.3 builds this app (plan phase 3). Lazily loaded (apps/registry.js).
import AppPlaceholder from '../AppPlaceholder'
// The counter POS on a paired screen (plan phase 3.3, D-26). 3.3a: the shift gate, then the
// sale screen (categories, product grid, search, price check, a cart priced by the backend).
// Payment (3.3b), tables (3.3c) and online orders (3.3d) follow. Look: the shared tokens and
// components in the screen's theme.
import PosScreen from './PosScreen'
import ShiftGate from './ShiftGate'
export default function PosApp() {
return <AppPlaceholder appKey="pos_counter" />
return (
<div className="absolute inset-0" data-testid="app-pos_counter">
<ShiftGate>
<PosScreen />
</ShiftGate>
</div>
)
}
+175
View File
@@ -0,0 +1,175 @@
// 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. Paying comes in 3.3b.
import { useMemo, useState } from 'react'
import { Info, Minus, Plus, Search, ShoppingBag, Trash2, Utensils, X } from 'lucide-react'
import { useFormat, useLanguage, useTranslation } from '@xenia/i18n'
import { Button, EmptyState, IconButton, Input, Spinner } from '@xenia/ui'
import {
addLine, categoriesWithProducts, defaultSelection, needsChoices, productsIn, searchProducts, setLineQty, toLine, unitOf,
} from './logic/cart'
import ProductDialog from './ProductDialog'
import { useMenu, useQuote } from './usePos'
export default function PosScreen() {
const { t } = useTranslation('terminal')
const { menu } = useMenu()
if (!menu) return <div className="absolute inset-0 flex items-center justify-center bg-canvas"><Spinner /></div>
return <Counter menu={menu} key={menu.settings.start_category_id ?? 'all'} t={t} />
}
function Counter({ menu, t }) {
const { formatMoney } = useFormat()
const { language } = useLanguage()
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 [dialog, setDialog] = useState(null) // product
const quote = useQuote(cart, orderType)
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 tap = product => {
if (needsChoices(product)) { setDialog(product); return }
const unit = unitOf(product)
setCart(c => addLine(c, toLine(product, defaultSelection(product), unit ? unit.start : 1)))
}
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>}
</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>
{/* 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
? <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)}
onQty={q => setCart(c => setLineQty(c, i, q))} />
))}
</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 variant="secondary" icon={<Trash2 size={16} />} disabled={!cart.length} onClick={() => setCart([])}>{t('pos.clearCart')}</Button>
</div>
</aside>
{dialog && (
<ProductDialog product={dialog} orderType={orderType} onClose={() => setDialog(null)}
onAdd={line => setCart(c => addLine(c, line))} />
)}
</div>
)
}
function CategoryButton({ active, colour, onClick, children, testId }) {
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>
</button>
)
}
function ProductCard({ product, onTap, onInfo }) {
const { t } = useTranslation('terminal')
const { formatMoney } = useFormat()
const unit = unitOf(product)
return (
<div className="relative bg-surface border border-line rounded-card shadow-raised overflow-hidden flex flex-col" data-testid="pos-product" data-product={product.id}>
<button type="button" onClick={onTap} className="flex-1 flex flex-col text-left active:scale-[0.98] transition-transform duration-fast">
{product.image_url
? <img src={product.image_url} alt="" loading="lazy" className="w-full aspect-[4/3] object-cover bg-surface-2" />
: <span className="w-full aspect-[4/3] bg-surface-2 flex items-center justify-center text-heading text-ink-3" aria-hidden="true">{product.name.slice(0, 1)}</span>}
<span className="p-2 grid gap-0.5">
<span className="text-body font-medium text-ink line-clamp-2">{product.name}</span>
<span className="text-label text-ink-2">{formatMoney(product.price)}{unit ? ` / ${unit.label}` : ''}</span>
</span>
</button>
<IconButton label={t('pos.checkPrice', { name: product.name })} size="sm" variant="secondary" onClick={onInfo}
className="absolute top-1.5 right-1.5" data-testid="product-info">
<Info size={16} />
</IconButton>
</div>
)
}
function CartLine({ line, priced, product, onQty }) {
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>}
</div>
</div>
)
}
+191
View File
@@ -0,0 +1,191 @@
// A product on the counter POS (plan step 3.3a): price check and choices in one dialog.
// "Check price" opens it from the product's info button without adding anything; a product
// with preferences to pick opens it on tap. The price shown is the backend's (the menu price,
// then POST /api/pos/quote for what's chosen), never added up here.
import { useMemo, useState } from 'react'
import { Minus, Plus } from 'lucide-react'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog, Input, Stepper } from '@xenia/ui'
import {
defaultSelection, missingChoices, pickChoice, pickChoiceSub, pickOptionSub, pickShared, setChoiceQty, setOptionQty,
setQuick, toLine, toggleOption, toggleRemoved, unitOf,
} from './logic/cart'
import { useQuote } from './usePos'
const chip = on => `min-h-[var(--x-control-md)] px-3 rounded-control border-2 text-body text-left flex items-center gap-2 transition-colors duration-fast
${on ? 'border-accent bg-accent-soft text-accent-ink font-medium' : 'border-line bg-surface-2 text-ink hover:bg-surface-3'}`
function Section({ title, hint, children }) {
return (
<section className="grid gap-2">
<h3 className="text-label font-semibold text-ink-2 uppercase tracking-wide">{title}{hint && <span className="ml-2 normal-case font-normal text-warning-ink">{hint}</span>}</h3>
<div className="flex flex-wrap gap-2">{children}</div>
</section>
)
}
function Price({ value }) {
const { formatMoney } = useFormat()
return value ? <span className="text-ink-2 text-label">{value > 0 ? '+' : ''}{formatMoney(value)}</span> : null
}
export default function ProductDialog({ product, orderType, onAdd, onClose }) {
const { t } = useTranslation('terminal')
const { formatMoney } = useFormat()
const unit = unitOf(product)
const [sel, setSel] = useState(() => defaultSelection(product))
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 priced = quote?.lines?.[0]
const add = () => { onAdd(line); onClose() }
return (
<Dialog open onClose={onClose} size="lg" title={product.name} description={product.description || undefined}
footer={<>
<Button variant="secondary" size="lg" onClick={onClose}>{t('pos.dialog.close')}</Button>
<Button size="lg" disabled={missing.length > 0} onClick={add} data-testid="dialog-add">
{t('pos.dialog.add')}{priced && !pending ? ` · ${formatMoney(priced.total)}` : ''}
</Button>
</>}>
<div className="grid gap-5" data-testid="product-dialog" data-product={product.id}>
<div className="flex gap-4 items-start">
{product.image_url && <img src={product.image_url} alt="" className="size-28 rounded-card object-cover shrink-0 bg-surface-2" />}
<div className="grid gap-1">
<div className="text-display font-semibold text-ink" data-testid="dialog-price">
{formatMoney(priced ? priced.unit_price : product.price)}
{unit && <span className="text-body text-ink-2"> / {unit.label}</span>}
</div>
{product.price !== product.base_price && !priced && (
<div className="text-label text-ink-3 line-through">{formatMoney(product.base_price)}</div>
)}
{priced?.adjustments?.map(a => (
<div key={a.label} className="text-label text-success-ink">{a.label} {a.delta > 0 ? '+' : ''}{formatMoney(a.delta)}</div>
))}
{product.tags?.length > 0 && (
<div className="flex flex-wrap gap-1 mt-1">
{product.tags.map(tag => <span key={tag} className="px-2 py-0.5 rounded-full bg-surface-2 text-caption text-ink-2">{tag}</span>)}
</div>
)}
</div>
</div>
{product.prefs.map(ps => {
const picked = sel.prefs[ps.id]?.choices ?? []
const one = !ps.multi && picked[0] ? ps.choices.find(c => c.id === picked[0].id) : null
const need = missing.find(m => m.kind === 'pref' && m.name === ps.name)
return (
<div key={ps.id} className="grid gap-3" data-pref={ps.id}>
<Section title={ps.name} hint={need ? t('pos.dialog.pickOne') : null}>
{ps.choices.map(c => {
const p = picked.find(x => x.id === c.id)
return (
<span key={c.id} className="flex items-center gap-1">
<button type="button" className={chip(!!p)} onClick={() => setSel(s => pickChoice(product, s, ps.id, c.id))} data-choice={c.id}>
{c.name} <Price value={c.price} />
</button>
{ps.multi && p && (
<Stepper value={p.qty} min={1} max={99} onChange={v => setSel(s => setChoiceQty(s, ps.id, c.id, v))} label={c.name} />
)}
</span>
)
})}
</Section>
{one?.subs?.length > 0 && (
<Section title={one.name}>
{one.subs.map(s => (
<button key={s.name} type="button" className={chip(picked[0].sub === s.name)} onClick={() => setSel(x => pickChoiceSub(x, ps.id, s.name))}>
{s.name} <Price value={s.price} />
</button>
))}
</Section>
)}
{ps.shared && one && !one.disables_shared && (
<Section title={ps.shared.name}>
{ps.shared.subs.map(s => (
<button key={s.name} type="button" className={chip(sel.prefs[ps.id]?.shared === s.name)} onClick={() => setSel(x => pickShared(x, ps.id, s.name))}>
{s.name} <Price value={s.price} />
</button>
))}
</Section>
)}
</div>
)
})}
{product.quick.length > 0 && (
<Section title={t('pos.dialog.quick')}>
{product.quick.map(q => {
const n = sel.quick[q.id] ?? 0
return (
<span key={q.id} className="flex items-center gap-1">
<button type="button" className={chip(n > 0)} onClick={() => setSel(s => setQuick(s, q.id, n > 0 ? 0 : 1))} data-quick={q.id}>
{q.name} <Price value={q.price} />
</button>
{q.allow_multiple && n > 0 && (
<Stepper value={n} min={1} max={99} onChange={v => setSel(s => setQuick(s, q.id, v))} label={q.name} />
)}
</span>
)
})}
</Section>
)}
{product.options.length > 0 && (
<Section title={t('pos.dialog.extras')}>
{product.options.map(o => {
const s = sel.options[o.id]
return (
<span key={o.id} className="grid gap-2">
<span className="flex items-center gap-1">
<button type="button" className={chip(!!s)} onClick={() => setSel(x => toggleOption(product, x, o.id))} data-option={o.id}>
{o.name} <Price value={o.price} />
</button>
{o.allow_multiple && s && <Stepper value={s.qty} min={1} max={99} onChange={v => setSel(x => setOptionQty(x, o.id, v))} label={o.name} />}
</span>
{s && o.subs.length > 0 && (
<span className="flex flex-wrap gap-1 pl-3">
{o.subs.map(sub => (
<button key={sub.name} type="button" className={chip(s.subs.includes(sub.name))} onClick={() => setSel(x => pickOptionSub(product, x, o.id, sub.name))}>
{sub.name} <Price value={sub.price} />
</button>
))}
</span>
)}
</span>
)
})}
</Section>
)}
{product.ingredients.length > 0 && (
<Section title={t('pos.dialog.without')}>
{product.ingredients.map(i => (
<button key={i.id} type="button" className={chip(sel.removed.includes(i.id))} onClick={() => setSel(s => toggleRemoved(s, i.id))} data-ingredient={i.id}>
{sel.removed.includes(i.id) ? <Minus size={14} /> : <Plus size={14} className="opacity-40" />}{i.name}
</button>
))}
</Section>
)}
<div className="grid sm:grid-cols-[1fr_auto] gap-3 items-end">
<label className="grid gap-1 text-label text-ink-2">
{t('pos.dialog.note')}
<Input value={sel.notes} onChange={e => setSel(s => ({ ...s, notes: e.target.value }))} maxLength={200} />
</label>
<div className="grid gap-1 text-label text-ink-2">
{t('pos.dialog.quantity')}
<Stepper value={qty} min={unit ? unit.step : 1} max={unit ? 999 : 99} step={unit ? unit.step : 1}
format={v => (unit ? `${Number(v).toFixed(unit.step < 1 ? 1 : 0)} ${unit.label}` : String(v))}
onChange={v => setQty(Math.round(v * 1000) / 1000)} label={t('pos.dialog.quantity')} data-testid="dialog-qty" />
</div>
</div>
{missing.length > 0 && (
<p className="text-label text-warning-ink" data-testid="dialog-missing">{t('pos.dialog.missing', { list: missing.map(m => m.name).join(', ') })}</p>
)}
</div>
</Dialog>
)
}
+89
View File
@@ -0,0 +1,89 @@
// Before selling (plan step 3.3a, D-26): the business day must be open, and the cash goes to
// the cashier's own shift. Shows who can open the day when it's closed; starts the cashier's
// shift (with the cash in the drawer) when they may start it themselves, else says to ask a
// manager. Follows live shift/day changes.
import { useState } from 'react'
import { CalendarX2, Clock, Play } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { parseNumber, useFormat, useTranslation } from '@xenia/i18n'
import { Button, EmptyState, Field, Input, Spinner } from '@xenia/ui'
import client from '../../api/client'
import { usePosSession } from './usePos'
export default function ShiftGate({ children }) {
const { t } = useTranslation('terminal')
const { session, error, reload } = usePosSession()
if (!session) {
return (
<Centered>
{error ? <EmptyState title={errorMessage(error, t)} action={<Button variant="secondary" onClick={reload}>{t('common:actions.retry')}</Button>} /> : <Spinner />}
</Centered>
)
}
if (!session.business_day) {
return (
<Centered testId="pos-day-closed">
<EmptyState icon={<CalendarX2 size={40} />} title={t('pos.gate.dayClosed')}
description={session.day_openers.length
? t('pos.gate.dayOpeners', { names: session.day_openers.join(', ') })
: t('pos.gate.dayOpenersNone')}
action={<Button variant="secondary" onClick={reload}>{t('common:actions.retry')}</Button>} />
</Centered>
)
}
if (!session.shift) {
return session.self_start
? <StartShift onStarted={reload} />
: (
<Centered testId="pos-shift-needed">
<EmptyState icon={<Clock size={40} />} title={t('pos.gate.noShift')} description={t('pos.gate.askManager')}
action={<Button variant="secondary" onClick={reload}>{t('common:actions.retry')}</Button>} />
</Centered>
)
}
return children
}
function StartShift({ onStarted }) {
const { t } = useTranslation('terminal')
const { formatMoney } = useFormat()
const [cash, setCash] = useState('')
const [busy, setBusy] = useState(false)
const [error, setError] = useState('')
const amount = cash.trim() === '' ? 0 : parseNumber(cash, { decimals: 2, allowNegative: false })
const valid = Number.isFinite(amount) && amount >= 0
const start = async e => {
e.preventDefault()
if (!valid || busy) return
setBusy(true)
setError('')
try {
await client.post('/api/shifts/start', { starting_cash: amount })
onStarted()
} catch (err) {
setError(errorMessage(err, t))
} finally {
setBusy(false)
}
}
return (
<Centered testId="pos-start-shift">
<form onSubmit={start} className="bg-surface border border-line rounded-card shadow-raised p-6 grid gap-4 w-full max-w-sm">
<div className="grid gap-1">
<h1 className="text-title font-semibold text-ink">{t('pos.gate.startTitle')}</h1>
<p className="text-label text-ink-2">{t('pos.gate.startBody')}</p>
</div>
<Field label={t('pos.gate.startingCash')} hint={valid && amount > 0 ? formatMoney(amount) : undefined} error={!valid ? t('pos.gate.badAmount') : undefined}>
<Input inputMode="decimal" value={cash} onChange={e => setCash(e.target.value)} placeholder="0" autoFocus data-testid="starting-cash" />
</Field>
{error && <p role="alert" className="text-label text-danger-ink">{error}</p>}
<Button type="submit" size="lg" icon={<Play size={18} />} loading={busy} disabled={!valid}>{t('pos.gate.start')}</Button>
</form>
</Centered>
)
}
function Centered({ children, testId }) {
return <div className="absolute inset-0 flex items-center justify-center p-6 bg-canvas" data-testid={testId}>{children}</div>
}
+189
View File
@@ -0,0 +1,189 @@
// The counter POS's menu and cart, without prices (plan step 3.3a). Prices always come from
// the backend: the menu's `price` and POST /api/pos/quote (services/pos_cart.py). This file
// only knows what was chosen; the rules for a complete choice mirror the backend's, so the
// screen can say what's missing before asking. Pure: unit-tested in Node (tests/pos.test.mjs).
// ── menu ────────────────────────────────────────────────────────────────────
/** Lower case, accents and Greek tonos removed: "Φρέντο" matches "φρεντο". */
export function fold(text) {
return String(text ?? '').normalize('NFD').replace(/[̀-ͯ]/g, '').toLowerCase().trim()
}
/** Products in a category (a product listed in several shows in each), in that category's
* order; categoryId null = all products (each once). */
export function productsIn(products, categoryId) {
if (categoryId == null) return products
const pos = p => p.categories.find(c => c.category_id === categoryId)
return products.filter(pos).sort((a, b) => pos(a).sort_order - pos(b).sort_order || a.name.localeCompare(b.name))
}
/** Search by name (any word order, accents ignored), each product once whatever its
* categories. */
export function searchProducts(products, query) {
const words = fold(query).split(/\s+/).filter(Boolean)
if (!words.length) return []
return products.filter(p => { const name = fold(p.name); return words.every(w => name.includes(w)) })
}
/** Categories that have products, in their order (top level first, then by sort order). */
export function categoriesWithProducts(categories, products) {
const used = new Set(products.flatMap(p => p.categories.map(c => c.category_id)))
return categories.filter(c => used.has(c.id))
}
// ── one product's choices ───────────────────────────────────────────────────
const defaultSub = subs => (subs?.length ? (subs.find(s => s.is_default) ?? subs[0]).name : null)
/** The choices a product starts with: default preference choices (+ their default subs and
* the set's default shared sub), nothing else. */
export function defaultSelection(product) {
const prefs = {}
for (const ps of product.prefs ?? []) {
const def = ps.choices.find(c => c.id === ps.default_choice_id)
prefs[ps.id] = def
? { choices: [{ id: def.id, qty: 1, sub: ps.multi ? null : defaultSub(def.subs) }], shared: ps.shared && !def.disables_shared ? defaultSub(ps.shared.subs) : null }
: { choices: [], shared: null }
}
return { quick: {}, options: {}, prefs, removed: [], notes: '' }
}
/** Does the product need the options dialog (a preference to pick)? Otherwise a tap adds it. */
export function needsChoices(product) {
return (product.prefs ?? []).length > 0
}
/** What's still missing: [{ kind: 'pref' | 'sub' | 'option_sub', name }] (empty = complete). */
export function missingChoices(product, sel) {
const out = []
for (const ps of product.prefs ?? []) {
const picked = sel.prefs[ps.id]?.choices ?? []
if (!picked.length) { out.push({ kind: 'pref', name: ps.name }); continue }
if (ps.multi) continue
const c = ps.choices.find(x => x.id === picked[0].id)
if (c?.subs?.length && !picked[0].sub) out.push({ kind: 'sub', name: c.name })
if (ps.shared && c && !c.disables_shared && !sel.prefs[ps.id]?.shared) out.push({ kind: 'sub', name: ps.shared.name })
}
for (const o of product.options ?? []) {
const s = sel.options[o.id]
if (s && o.subs?.length && !(s.subs?.length)) out.push({ kind: 'option_sub', name: o.name })
}
return out
}
/** Pick a single-choice preference (its default sub and the set's shared sub come with it). */
export function pickChoice(product, sel, setId, choiceId) {
const ps = product.prefs.find(p => p.id === setId)
const c = ps.choices.find(x => x.id === choiceId)
const prev = sel.prefs[setId] ?? { choices: [], shared: null }
if (ps.multi) {
const has = prev.choices.some(x => x.id === choiceId)
const choices = has ? prev.choices.filter(x => x.id !== choiceId) : [...prev.choices, { id: choiceId, qty: 1, sub: null }]
return { ...sel, prefs: { ...sel.prefs, [setId]: { ...prev, choices } } }
}
const shared = ps.shared && !c.disables_shared ? (prev.shared ?? defaultSub(ps.shared.subs)) : null
return { ...sel, prefs: { ...sel.prefs, [setId]: { choices: [{ id: choiceId, qty: 1, sub: defaultSub(c.subs) }], shared } } }
}
export function setChoiceQty(sel, setId, choiceId, qty) {
const prev = sel.prefs[setId]
return { ...sel, prefs: { ...sel.prefs, [setId]: { ...prev, choices: prev.choices.map(x => (x.id === choiceId ? { ...x, qty: Math.max(1, qty) } : x)) } } }
}
export function pickChoiceSub(sel, setId, sub) {
const prev = sel.prefs[setId]
return { ...sel, prefs: { ...sel.prefs, [setId]: { ...prev, choices: prev.choices.map((x, i) => (i === 0 ? { ...x, sub } : x)) } } }
}
export function pickShared(sel, setId, shared) {
return { ...sel, prefs: { ...sel.prefs, [setId]: { ...sel.prefs[setId], shared } } }
}
/** Toggle an extra (with its default sub). */
export function toggleOption(product, sel, optionId) {
const options = { ...sel.options }
if (options[optionId]) delete options[optionId]
else {
const o = product.options.find(x => x.id === optionId)
const sub = defaultSub(o.subs)
options[optionId] = { qty: 1, subs: sub ? [sub] : [] }
}
return { ...sel, options }
}
export function pickOptionSub(product, sel, optionId, name) {
const o = product.options.find(x => x.id === optionId)
const cur = sel.options[optionId]?.subs ?? []
const subs = o.multi_select ? (cur.includes(name) ? cur.filter(n => n !== name) : [...cur, name]) : [name]
return { ...sel, options: { ...sel.options, [optionId]: { ...sel.options[optionId], subs } } }
}
export function setOptionQty(sel, optionId, qty) {
return { ...sel, options: { ...sel.options, [optionId]: { ...sel.options[optionId], qty: Math.max(1, qty) } } }
}
/** Quick add-ons: qty 0 removes it. */
export function setQuick(sel, quickId, qty) {
const quick = { ...sel.quick }
if (qty > 0) quick[quickId] = qty
else delete quick[quickId]
return { ...sel, quick }
}
export function toggleRemoved(sel, ingredientId) {
const removed = sel.removed.includes(ingredientId) ? sel.removed.filter(i => i !== ingredientId) : [...sel.removed, ingredientId]
return { ...sel, removed }
}
/** The cart line POST /api/pos/quote (and 3.3b's sale) takes. */
export function toLine(product, sel, quantity) {
const line = { product_id: product.id, quantity }
const quick = Object.entries(sel.quick).map(([id, qty]) => ({ id: Number(id), qty }))
const options = Object.entries(sel.options).map(([id, o]) => ({ id: Number(id), qty: o.qty, subs: o.subs }))
const prefs = Object.entries(sel.prefs).filter(([, p]) => p.choices.length)
.map(([id, p]) => ({ set_id: Number(id), choices: p.choices.map(c => ({ id: c.id, qty: c.qty, sub: c.sub })), shared: p.shared }))
if (quick.length) line.quick = quick
if (options.length) line.options = options
if (prefs.length) line.prefs = prefs
if (sel.removed.length) line.removed = [...sel.removed]
if (sel.notes?.trim()) line.notes = sel.notes.trim()
return line
}
// ── the cart ────────────────────────────────────────────────────────────────
/** Two lines are the same sale when everything but the quantity is the same. */
export function lineKey(line) {
const { quantity, ...rest } = line // eslint-disable-line no-unused-vars
return stable(rest)
}
const stable = v => (Array.isArray(v) ? `[${v.map(stable).join(',')}]`
: v && typeof v === 'object' ? `{${Object.keys(v).sort().map(k => `${k}:${stable(v[k])}`).join(',')}}`
: JSON.stringify(v))
/** Add a line; the same product with the same choices adds to its quantity. */
export function addLine(cart, line) {
const key = lineKey(line)
const i = cart.findIndex(l => lineKey(l) === key)
if (i < 0) return [...cart, line]
return cart.map((l, j) => (j === i ? { ...l, quantity: round(l.quantity + line.quantity) } : l))
}
export function setLineQty(cart, index, quantity) {
if (quantity <= 0) return cart.filter((_, i) => i !== index)
return cart.map((l, i) => (i === index ? { ...l, quantity: round(quantity) } : l))
}
const round = n => Math.round(n * 1000) / 1000
// Weighed products (kg, L, g, mL): step and starting amount (the waiter app's)
export const UNITS = {
kg: { step: 0.1, start: 0.5, label: 'kg' },
liter: { step: 0.1, start: 0.5, label: 'L' },
gram: { step: 10, start: 100, label: 'g' },
ml: { step: 5, start: 100, label: 'mL' },
}
export const unitOf = product => UNITS[product.unit_type] ?? null
+64
View File
@@ -0,0 +1,64 @@
// 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.
import { useCallback, useEffect, useRef, useState } from 'react'
import client from '../../api/client'
import { useLiveEvent, useLiveEvents } from '../../device/context'
const quiet = { xenia: { noOverride: true } }
const MENU_REFRESH_MS = 5 * 60_000 // prices can change with the time (happy hours)
const QUOTE_DELAY_MS = 120
/** GET /api/pos/session: { business_day, shift, self_start, day_openers } (null while loading). */
export function usePosSession() {
const [session, setSession] = useState(null)
const [error, setError] = useState(null)
const load = useCallback(async () => {
try {
setSession((await client.get('/api/pos/session', quiet)).data)
setError(null)
} catch (err) { setError(err) }
}, [])
useEffect(() => { load() }, [load])
useLiveEvent('ready', load)
useLiveEvents(['shift_changed', 'business_day_changed'], load)
return { session, error, reload: load }
}
/** GET /api/pos/menu: { settings, categories, products } (null while loading). */
export function useMenu() {
const [menu, setMenu] = useState(null)
const load = useCallback(async () => {
try { setMenu((await client.get('/api/pos/menu', quiet)).data) } catch { /* the shell shows offline */ }
}, [])
useEffect(() => { load() }, [load])
useEffect(() => {
const id = setInterval(load, MENU_REFRESH_MS)
return () => clearInterval(id)
}, [load])
useLiveEvent('ready', load)
useLiveEvents(['products_changed', 'device.updated'], load)
return { menu, reload: load }
}
/** The cart priced by POST /api/pos/quote whenever it changes (latest answer wins).
* → { quote, pending, error } */
export function useQuote(lines, orderType) {
const [state, setState] = useState({ quote: null, pending: false, error: null })
const seq = useRef(0)
const key = JSON.stringify([lines, orderType])
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)
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
return state
}