feat(connect): table bookings from the online ordering app; food fired to the kitchen before arrival

Plan phase 3S, step S.6.
- Pull: "reservation" / "preorder" orders become Reservations waiting for an answer
  (status "requested"; services/online_reservations.py), with the food ordered ahead kept on
  the booking (items_json at the cloud's prices, the site's price check) — no order yet.
  Migration 0020 (reservations: online_order_cloud_id, online_ref, items_json, total,
  online_price_diff, fire_at, order_id, response_note).
- Confirm → the food's fire time = booking time − fire minutes (setting); the fire worker
  (connect_orders, every 20 s) turns the food into an order at that time (needs an open
  business day; waits otherwise): kitchen tickets, KDS (reference and time). Early arrival
  fires at once. Seating moves the order to the table (refused if the table has an open
  order). Decline / cancel / no-show with a reason. Every step mirrored to the cloud.
- Found: the KDS filter dropped every online order without an online status (SQL NULL in
  NOT(a AND b)) — made NULL-safe.
- Counter: Online → Bookings (requests first, then upcoming), BookingPanel (confirm,
  decline with reasons, food and when it goes to the kitchen, seat at a free table, cancel,
  no-show); the Online badge and chime count booking requests.
- Manager: Online ordering → Table bookings settings (on, food ahead, hours, slot, notice,
  days ahead, party size, fire minutes); the dashboard's reservations card confirms /
  declines online requests; the reservations router delegates online bookings' status steps.
- Tests: tests/test_online_bookings.py (8), unit tests (terminal, manager), e2e: order app
  (book with food → the venue confirms), terminal (request → confirm → the two dishes reach
  the KDS at the fire time, not before → seated), manager (booking settings).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-15 19:31:44 +02:00
co-authored by Claude Opus 5.5
parent 0ca700279a
commit 70c8f2bb57
33 changed files with 1402 additions and 105 deletions
+157
View File
@@ -0,0 +1,157 @@
// One table booking at the counter (plan phase 3S, step S.6): who, how many, when, their note,
// 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.
import { useState } from 'react'
import { AlertTriangle, Ban, Check, ChefHat, MessageSquare, Phone, UserX, Users } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog, EmptyState, Input, Select } from '@xenia/ui'
import client from '../../api/client'
import { bookingSteps, foodState, freeTables, whenLabel } from './logic/bookings'
const REASONS = ['full', 'closed', 'party']
export default function BookingPanel({ booking, tables, onChanged }) {
const { t } = useTranslation('terminal')
const fmt = useFormat()
const [busy, setBusy] = useState(false)
const [error, setError] = useState('')
const [table, setTable] = useState('')
const [declining, setDeclining] = useState(false)
if (!booking) {
return (
<aside className="border-l border-line bg-surface flex items-center justify-center p-6" data-testid="booking-panel">
<EmptyState compact title={t('pos.bookings.pick')} />
</aside>
)
}
const steps = bookingSteps(booking)
const food = foodState(booking)
const free = freeTables(tables)
const run = async (path, body) => {
setBusy(true)
setError('')
try {
await client.post(`/api/connect/bookings/${booking.id}/${path}`, body ?? {})
setDeclining(false)
onChanged()
} catch (err) { setError(errorMessage(err, t)); onChanged() } finally { setBusy(false) }
}
return (
<aside className="border-l border-line bg-surface flex flex-col min-h-0" data-testid="booking-panel" data-booking={booking.id} data-status={booking.status}>
<div className="p-3 border-b border-line grid gap-1">
<div className="flex items-center gap-2">
<span className="flex-1 text-title font-semibold">{whenLabel(booking.reserved_for, fmt, t)}</span>
{booking.ref && <span className="text-label font-medium text-ink-2">{booking.ref}</span>}
</div>
<div className="text-caption text-ink-2">{t(`pos.bookings.status.${booking.status}`)}{booking.table_label ? ` · ${booking.table_label}` : ''}</div>
</div>
<div className="flex-1 overflow-y-auto">
<section className="p-3 border-b border-line grid gap-1.5 text-body" data-testid="booking-guest">
<div className="text-body-lg font-semibold">{booking.guest_name}</div>
<Detail icon={Users}>{t('pos.bookings.people', { count: booking.party_size })}</Detail>
{booking.phone && <Detail icon={Phone}>{booking.phone}</Detail>}
{booking.note && (
<div className="p-2 rounded-control bg-warning-soft text-warning-ink flex gap-2">
<MessageSquare size={16} className="mt-0.5 shrink-0" aria-hidden="true" /><span>{booking.note}</span>
</div>
)}
</section>
{food !== 'none' && (
<section className="border-b border-line" data-testid="booking-food">
<p className="px-3 pt-3 text-label font-semibold text-ink-2 flex items-center gap-1.5">
<ChefHat size={15} aria-hidden="true" />
{food === 'kitchen' ? t('pos.bookings.foodSent')
: booking.fire_at ? t('pos.bookings.foodAt', { time: whenLabel(booking.fire_at, fmt, t) }) : t('pos.bookings.foodOnConfirm')}
</p>
{booking.price_diff && (
<p className="mx-3 mt-2 p-2 rounded-control bg-warning-soft text-warning-ink text-label flex gap-1.5" role="note" data-testid="booking-price-diff">
<AlertTriangle size={15} className="mt-0.5 shrink-0" aria-hidden="true" />
{t('pos.online.diff.body', { charged: fmt.formatMoney(booking.price_diff.cloud_total), here: fmt.formatMoney(booking.price_diff.site_total) })}
</p>
)}
{booking.lines.map((l, i) => (
<div key={i} className="px-3 py-2 flex items-start gap-2 text-ink">
<span className="flex-1 min-w-0 text-body">{l.quantity}× {l.name}
{l.options?.length > 0 && <span className="block text-caption text-ink-2">{l.options.join(' · ')}</span>}
</span>
<span className="text-body">{fmt.formatMoney(l.unit_price * l.quantity)}</span>
</div>
))}
<div className="px-3 pb-3 flex justify-between font-semibold"><span>{t('pos.total')}</span><span>{fmt.formatMoney(booking.total)}</span></div>
</section>
)}
</div>
<div className="border-t border-line p-3 grid gap-2">
{error && <p role="alert" className="text-label text-danger-ink">{error}</p>}
{steps.includes('confirm') && (
<>
<Button size="lg" icon={<Check size={20} />} loading={busy} onClick={() => run('confirm')} data-testid="booking-confirm">{t('pos.bookings.confirm')}</Button>
<Button variant="secondary" icon={<Ban size={16} />} disabled={busy} onClick={() => setDeclining(true)} data-testid="booking-decline">{t('pos.bookings.decline')}</Button>
</>
)}
{steps.includes('arrive') && (
<>
<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>)}
</Select>
</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')}
</Button>
<div className="grid grid-cols-2 gap-2">
<Button variant="secondary" icon={<Ban size={16} />} disabled={busy} onClick={() => run('cancel', { status: 'cancelled' })} data-testid="booking-cancel">{t('pos.bookings.cancel')}</Button>
<Button variant="secondary" icon={<UserX size={16} />} disabled={busy} onClick={() => run('cancel', { status: 'no_show' })} data-testid="booking-noshow">{t('pos.bookings.noShow')}</Button>
</div>
</>
)}
</div>
{declining && <DeclineDialog busy={busy} error={error} onClose={() => setDeclining(false)} onDecline={reason => run('decline', { reason })} />}
</aside>
)
}
function Detail({ icon: Icon, children }) {
return <div className="flex items-start gap-2 text-ink-2"><Icon size={16} className="mt-0.5 shrink-0" aria-hidden="true" /><span className="text-ink">{children}</span></div>
}
function DeclineDialog({ busy, error, onClose, onDecline }) {
const { t } = useTranslation('terminal')
const [choice, setChoice] = useState(null)
const [other, setOther] = useState('')
const reason = choice === 'other' ? other.trim() : choice ? t(`pos.bookings.reasons.${choice}`) : ''
return (
<Dialog open size="sm" title={t('pos.bookings.declineTitle')} onClose={busy ? undefined : onClose}
footer={<>
<Button variant="secondary" onClick={onClose} disabled={busy}>{t('pos.online.keep')}</Button>
<Button variant="danger" icon={<Ban size={16} />} loading={busy} disabled={!reason} onClick={() => onDecline(reason)} data-testid="decline-confirm">
{t('pos.bookings.decline')}
</Button>
</>}>
<div className="grid gap-2">
<p className="text-body text-ink-2">{t('pos.online.rejectBody')}</p>
<div className="grid gap-1" role="radiogroup" aria-label={t('pos.online.reason')}>
{[...REASONS, 'other'].map(r => (
<button key={r} type="button" role="radio" aria-checked={choice === r} onClick={() => setChoice(r)} data-testid={`decline-${r}`}
className={`min-h-[var(--x-control-md)] px-3 rounded-control text-left text-body transition-colors duration-fast
${choice === r ? 'bg-accent text-accent-fg' : 'bg-surface-2 text-ink hover:bg-surface-3'}`}>
{t(`pos.bookings.reasons.${r}`)}
</button>
))}
</div>
{choice === 'other' && <Input value={other} onChange={e => setOther(e.target.value)} maxLength={300} autoFocus aria-label={t('pos.online.reason')} />}
{error && <p role="alert" className="text-label text-danger-ink">{error}</p>}
</div>
</Dialog>
)
}
+48
View File
@@ -0,0 +1,48 @@
// Table bookings at the counter (plan phase 3S, step S.6): Online → Bookings. Requests from the
// online ordering app waiting for an answer come first (they stand out), then the confirmed
// bookings from a few hours ago on, soonest first. A tap shows one on the right (BookingPanel).
import { CalendarClock, Users, UtensilsCrossed } from 'lucide-react'
import { useFormat, useTranslation } from '@xenia/i18n'
import { EmptyState, Spinner } from '@xenia/ui'
import { whenLabel } from './logic/bookings'
export default function BookingsView({ data, picked, onPick }) {
const { t } = useTranslation('terminal')
if (!data) return <div className="flex-1 flex items-center justify-center"><Spinner /></div>
const all = [...data.requested, ...data.upcoming]
if (!all.length) {
return (
<div className="flex-1 flex items-center justify-center p-6" data-testid="bookings">
<EmptyState title={t('pos.bookings.empty')} description={t('pos.bookings.emptyBody')} />
</div>
)
}
return (
<div className="flex-1 overflow-y-auto p-3 grid content-start gap-3" style={{ gridTemplateColumns: 'repeat(auto-fill, minmax(14rem, 1fr))' }}
data-testid="bookings">
{all.map(b => <BookingCard key={b.id} booking={b} picked={picked === b.id} onPick={() => onPick(b.id)} />)}
</div>
)
}
function BookingCard({ booking, picked, onPick }) {
const { t } = useTranslation('terminal')
const fmt = useFormat()
const asking = booking.status === 'requested'
return (
<button type="button" onClick={onPick} aria-pressed={picked} data-testid="booking" data-booking={booking.id} data-status={booking.status}
className={`min-h-28 p-3 rounded-card border-2 shadow-raised text-left flex flex-col gap-1 active:scale-[0.98] transition-transform duration-fast
${asking ? 'bg-warning-soft border-warning text-warning-ink' : 'bg-surface border-line text-ink'}
${picked ? 'ring-2 ring-accent ring-offset-2 ring-offset-canvas' : ''}`}>
<span className="flex items-center gap-2">
<CalendarClock size={18} aria-hidden="true" />
<span className="flex-1 min-w-0 text-title font-semibold truncate">{whenLabel(booking.reserved_for, fmt, t)}</span>
{booking.lines.length > 0 && <UtensilsCrossed size={16} aria-label={t('pos.bookings.withFood')} />}
</span>
<span className="text-body font-medium truncate">{booking.guest_name}</span>
<span className="text-label flex items-center gap-1"><Users size={14} aria-hidden="true" />{t('pos.bookings.people', { count: booking.party_size })}
{booking.table_label ? ` · ${booking.table_label}` : ''}</span>
<span className="text-label font-medium mt-auto">{t(`pos.bookings.status.${booking.status}`)}</span>
</button>
)
}
+24 -4
View File
@@ -20,6 +20,9 @@ import { useLiveEvent } from '../../device/context'
import { playChime } from './chime'
import { addLine, categoriesWithProducts, forSalesPoint, salesPointFor, defaultSelection, needsChoices, productsIn, searchProducts, toLine, unitOf } from './logic/cart'
import { findOnline, ONLINE_LISTS } from './logic/online'
import { BOOKING_LIST, findBooking } from './logic/bookings'
import BookingPanel from './BookingPanel'
import BookingsView from './BookingsView'
import { zoneCounts } from './logic/tables'
import OnlinePanel from './OnlinePanel'
import OnlineView from './OnlineView'
@@ -29,7 +32,7 @@ import ReceiptsView from './ReceiptsView'
import SaleCart from './SaleCart'
import TablePanel from './TablePanel'
import TablesView from './TablesView'
import { useMenu, useOnline, useReceipts, useTables } from './usePos'
import { useBookings, useMenu, useOnline, useReceipts, useTables } from './usePos'
const REMIND_MS = 30_000
@@ -61,9 +64,11 @@ function Counter({ menu, t }) {
const online = useOnline(onlineOn)
const [onlineList, setOnlineList] = useState('incoming')
const [onlineId, setOnlineId] = useState(null)
const bookings = useBookings(onlineOn) // table bookings from the online app (S.6)
const [bookingId, setBookingId] = useState(null)
const [now, setNow] = useState(() => Date.now())
const [chimes, setChimes] = useState(0)
const waiting = online.data?.incoming.length ?? 0
const waiting = (online.data?.incoming.length ?? 0) + (bookings.data?.requested.length ?? 0)
const [receiptScope, setReceiptScope] = useState('mine')
const [receiptId, setReceiptId] = useState(null)
const receipts = useReceipts(receiptScope, mode === 'receipts')
@@ -74,6 +79,11 @@ function Counter({ menu, t }) {
ring()
if (mode !== 'online') toast.info(t('pos.online.arrived', { count: data?.count ?? 1 }))
})
useLiveEvent('reservation_requested', data => {
if (!onlineOn) return
ring()
if (mode !== 'online') toast.info(t('pos.bookings.arrived', { count: data?.count ?? 1 }))
})
// a reminder while an order waits for an answer; the waiting minutes move on too
useEffect(() => {
const id = setInterval(() => {
@@ -88,6 +98,8 @@ function Counter({ menu, t }) {
const atTable = mode === 'tables' && table != null
const picking = mode === 'tables' && !atTable
const onlineOrder = findOnline(online.data, onlineId)
const booking = findBooking(bookings.data, bookingId)
const onBookings = mode === 'online' && onlineList === BOOKING_LIST
const setCart = atTable ? setTableCart : setSaleCart
const leaveTable = () => { setTableId(null); setTableCart([]) }
@@ -129,9 +141,9 @@ function Counter({ menu, t }) {
</NavButton>
))
) : mode === 'online' ? (
ONLINE_LISTS.map(list => (
[...ONLINE_LISTS, BOOKING_LIST].map(list => (
<NavButton key={list} active={onlineList === list} onClick={() => setOnlineList(list)} testId={`online-list-${list}`}
tally={list === 'finished' ? null : online.data?.[list].length}>
tally={list === 'finished' ? null : list === BOOKING_LIST ? bookings.data?.requested.length : online.data?.[list].length}>
{t(`pos.online.lists.${list}`)}
</NavButton>
))
@@ -162,6 +174,14 @@ function Counter({ menu, t }) {
</main>
<ReceiptPanel orderId={receiptId} />
</>
) : onBookings ? (
<>
<main className="flex flex-col min-h-0 min-w-0">
<BookingsView data={bookings.data} picked={bookingId} onPick={setBookingId} />
</main>
<BookingPanel key={booking?.id ?? 'none'} booking={booking} tables={tables.data?.tables}
onChanged={() => { bookings.reload(); tables.reload() }} />
</>
) : mode === 'online' ? (
<>
<main className="flex flex-col min-h-0 min-w-0">
+37
View File
@@ -0,0 +1,37 @@
// Table bookings at the counter (plan phase 3S, step S.6). Pure: unit-tested in Node
// (tests/pos.test.mjs). The bookings come from GET /api/connect/bookings.
export const BOOKING_LIST = 'bookings'
/** The booking with this id in either list (null when gone). */
export function findBooking(data, id) {
if (!data || id == null) return null
return data.requested.find(b => b.id === id) ?? data.upcoming.find(b => b.id === id) ?? null
}
/** What the counter can do next with a booking. */
export function bookingSteps(booking) {
if (!booking) return []
if (booking.status === 'requested') return ['confirm', 'decline']
if (booking.status === 'pending') return ['arrive', 'cancel', 'no_show']
return []
}
/** Where the booking's food is: none | waiting (fire time ahead) | kitchen (its order exists). */
export function foodState(booking) {
if (!booking?.lines?.length) return 'none'
return booking.order_id ? 'kitchen' : 'waiting'
}
/** Free tables for seating: active, without an open order (from GET /api/pos/tables). */
export function freeTables(tables) {
return (tables ?? []).filter(t => !t.order)
}
/** "21:30" today, "Mon 16/11 21:30" another day (venue time, via the formatters). */
export function whenLabel(iso, { formatDate, formatDateTime, formatTime }, t) {
if (!iso) return ''
return formatDate(iso) === formatDate(new Date())
? t('pos.bookings.today', { time: formatTime(iso) })
: formatDateTime(iso, 'datetimeShort')
}
+16
View File
@@ -130,6 +130,22 @@ export function useOnline(enabled) {
return { data, reload: load }
}
const BOOKING_EVENTS = ['reservation_requested', 'reservation_updated']
/** GET /api/connect/bookings: { requested, upcoming } (null while loading); live (S.6). */
export function useBookings(enabled) {
const [data, setData] = useState(null)
const load = useCallback(async () => {
if (!enabled) { setData(null); return }
try { setData((await client.get('/api/connect/bookings', quiet)).data) } catch { /* the shell shows offline */ }
}, [enabled])
const soon = useCoalesced(load)
useEffect(() => { load() }, [load])
useLiveEvent('ready', load)
useLiveEvents(BOOKING_EVENTS, soon)
return { data, reload: load }
}
const RECEIPT_EVENTS = ['order_paid', 'order_refunded', 'order_closed']
/** GET /api/pos/receipts: today's paid orders ({ orders }, null while loading); live. */
+18
View File
@@ -203,3 +203,21 @@ test('sales points at the counter: what is sold and at which price (phase 3S)',
assert.deepEqual(forSalesPoint([cola, soup, old], 'in_store_takeaway').map(p => [p.id, p.price]), [[1, 2.5], [3, 4]])
assert.deepEqual(forSalesPoint([cola, soup, old], 'in_store').map(p => [p.id, p.price]), [[1, 3.5], [2, 6], [3, 4]])
})
test('table bookings at the counter (S.6)', async () => {
const { bookingSteps, findBooking, foodState, freeTables, whenLabel } = await import('../src/apps/pos/logic/bookings.js')
const data = { requested: [{ id: 1, status: 'requested', lines: [] }], upcoming: [{ id: 2, status: 'pending', lines: [{}], order_id: null }] }
assert.equal(findBooking(data, 2).id, 2)
assert.equal(findBooking(data, 9), null)
assert.deepEqual(bookingSteps(data.requested[0]), ['confirm', 'decline'])
assert.deepEqual(bookingSteps(data.upcoming[0]), ['arrive', 'cancel', 'no_show'])
assert.deepEqual(bookingSteps({ status: 'arrived' }), [])
assert.equal(foodState(data.requested[0]), 'none')
assert.equal(foodState(data.upcoming[0]), 'waiting')
assert.equal(foodState({ lines: [{}], order_id: 5 }), 'kitchen')
assert.deepEqual(freeTables([{ id: 1, order: null }, { id: 2, order: { id: 9 } }]).map(t => t.id), [1])
const fmt = { formatDate: d => new Date(d).toISOString().slice(0, 10), formatDateTime: () => 'other day', formatTime: () => '21:30' }
const t = (k, p) => `${k}:${p?.time ?? ''}`
assert.equal(whenLabel(new Date().toISOString(), fmt, t), 'pos.bookings.today:21:30')
assert.equal(whenLabel('2020-01-01T10:00:00Z', fmt, t), 'other day')
})