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

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-18 21:58:46 +02:00
co-authored by Claude Opus 5.5
parent f4aae6abbc
commit 070c9cf625
56 changed files with 2339 additions and 3846 deletions
+11 -3
View File
@@ -2,7 +2,8 @@
// and the food they ordered ahead (with a warning when the venue's prices differ). A request is
// confirmed or declined (the customer sees the answer and the reason); a confirmed booking says
// when its food goes to the kitchen, seats the guests at a free table (their food's order moves
// there, and is sent now if it hadn't been), or is cancelled / marked as a no-show.
// there, and is sent now if it hadn't been), or is cancelled / marked as a no-show. Since 6.9 a
// confirmed booking can keep its table ahead (the table shows RESERVED; seating offers it first).
import { useState } from 'react'
import { AlertTriangle, Ban, Check, ChefHat, MessageSquare, Phone, UserX, Users } from 'lucide-react'
import { errorMessage } from '@xenia/api'
@@ -18,7 +19,7 @@ export default function BookingPanel({ booking, tables, onChanged }) {
const fmt = useFormat()
const [busy, setBusy] = useState(false)
const [error, setError] = useState('')
const [table, setTable] = useState('')
const [table, setTable] = useState(booking?.table_id ? String(booking.table_id) : '')
const [declining, setDeclining] = useState(false)
if (!booking) {
@@ -32,6 +33,8 @@ export default function BookingPanel({ booking, tables, onChanged }) {
const steps = bookingSteps(booking)
const food = foodState(booking)
const free = freeTables(tables)
const all = (tables ?? []).map(x => ({ ...x, busy: !free.includes(x) })) // 6.9: a table can be kept while busy now
const kept = booking.table_id ? String(booking.table_id) : ''
const run = async (path, body) => {
setBusy(true)
setError('')
@@ -102,8 +105,13 @@ export default function BookingPanel({ booking, tables, onChanged }) {
<div className="flex gap-2">
<Select value={table} onChange={e => setTable(e.target.value)} aria-label={t('pos.bookings.table')} data-testid="booking-table" className="flex-1">
<option value="">{t('pos.bookings.noTable')}</option>
{free.map(x => <option key={x.id} value={x.id}>{x.name}</option>)}
{all.map(x => <option key={x.id} value={x.id}>{x.name}{x.busy ? ` · ${t('pos.bookings.busyNow')}` : ''}</option>)}
</Select>
{table !== kept && (
<Button variant="secondary" disabled={busy} onClick={() => run('table', { table_id: table ? Number(table) : null })} data-testid="booking-keep">
{table ? t('pos.bookings.keep') : t('pos.bookings.release')}
</Button>
)}
</div>
<Button size="lg" icon={<Check size={20} />} loading={busy} onClick={() => run('arrive', { table_id: table ? Number(table) : null })} data-testid="booking-arrive">
{t('pos.bookings.arrive')}
+8 -192
View File
@@ -1,195 +1,11 @@
// 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 { Allergens } from '@xenia/access'
import {
defaultSelection, missingChoices, pickChoice, pickChoiceSub, pickOptionSub, pickShared, setChoiceQty, setOptionQty,
setQuick, toLine, toggleOption, toggleRemoved, unitOf,
} from './logic/cart'
import { useQuote } from './usePos'
// The counter's product dialog: the shared one (@xenia/ordering, 6.9) priced by the counter's quote
// (POST /api/pos/quote, the order type chosen at the till), or by `quoteUrl` (the menu tablet, 6.6).
import { ProductDialog as Shared } from '@xenia/ordering'
import client from '../../api/client'
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'}`
const quiet = { xenia: { noOverride: true } }
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
}
// 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)
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, null, quoteUrl)
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>
)}
<Allergens allergens={product.allergens} style={{ marginTop: 4 }} />
</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>
)
export default function ProductDialog({ orderType, quoteUrl = '/api/pos/quote', ...rest }) {
const fetchQuote = lines => client.post(quoteUrl, { order_type: orderType, lines }, quiet).then(r => r.data)
return <Shared {...rest} fetchQuote={fetchQuote} />
}
+2 -236
View File
@@ -1,236 +1,2 @@
// 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
// ── paying (3.3b) ───────────────────────────────────────────────────────────
/** Amounts a customer typically hands over for `total`: the exact amount, then the next
* round amounts above it (notes of 5, 10, 20, 50, 100), at most five. */
export function quickAmounts(total) {
const out = [round2(total)]
for (const step of [5, 10, 20, 50, 100]) {
const v = Math.ceil((total + 0.0001) / step) * step
if (v > total + 0.004 && !out.includes(v)) out.push(v)
}
return out.slice(0, 5)
}
/** Change to give back (null when not enough was given). */
export function changeFor(given, due) {
if (given == null || Number.isNaN(given)) return null
const c = round2(given - due)
return c < 0 ? null : c
}
/** Cash and card parts of a split: methods[i] is 'cash' | 'card' for line i, totals from the
* quote. → { cash, card, payments } (payments as POST /api/pos/sales takes them). */
export function splitPayments(methods, totals) {
const lines = { cash: [], card: [] }
methods.forEach((m, i) => lines[m].push(i))
const sum = idx => round2(idx.reduce((s, i) => s + (totals[i] ?? 0), 0))
const payments = ['card', 'cash'].filter(m => lines[m].length).map(m => ({ method: m, lines: lines[m] }))
return { cash: sum(lines.cash), card: sum(lines.card), payments }
}
export const DISCOUNTS = [0, 5, 10, 15, 20, 25, 50, 100]
const round2 = n => Math.round(n * 100) / 100
/** The counter's sales point for an order type (phase 3S; backend pos_cart.point_for). */
export function salesPointFor(orderType) {
return orderType === 'takeaway' ? 'in_store_takeaway' : 'in_store'
}
/** The menu's products sold at a sales point, each with that sales point's price (GET
* /api/pos/menu sends `sold_at` and `prices`; older answers: everything, `price`). */
export function forSalesPoint(products, point) {
return products
.filter(p => !p.sold_at || p.sold_at.includes(point))
.map(p => (p.prices?.[point] != null ? { ...p, price: p.prices[point] } : p))
}
// The cart's rules live in @xenia/ordering since plan step 6.9 (the manager orders by them too).
export * from '@xenia/ordering/cart'
+4 -19
View File
@@ -5,10 +5,10 @@ import { useCallback, useEffect, useRef, useState } from 'react'
import { useModule } from '@xenia/access'
import client from '../../api/client'
import { useLiveEvent, useLiveEvents } from '../../device/context'
import { useQuote as useSharedQuote } from '@xenia/ordering'
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() {
@@ -46,24 +46,9 @@ export function useMenu() {
* `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, 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, 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(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 }))
}
}, QUOTE_DELAY_MS)
return () => clearTimeout(id)
}, [key]) // eslint-disable-line react-hooks/exhaustive-deps -- `key` is lines + orderType + orderId
return state
// the shared hook (@xenia/ordering, 6.9) with the counter's endpoint
return useSharedQuote(ls => client.post(url, { order_type: orderType, lines: ls, order_id: orderId ?? undefined }, quiet).then(r => r.data),
lines, JSON.stringify([orderType, orderId, url]))
}
const TABLE_EVENTS = ['order_updated', 'order_paid', 'order_closed', 'table_flags_changed', 'table_list_changed', 'kds_order_updated', 'kds_item_updated']