feat(waiter): table bookings on the phone; shared ReasonPicker (platform-v2 step 4.8c)

- Waiter: Bookings (side drawer, for whoever has connect_orders.manage or
  reservations.manage, with the online-orders app on): requests made online are
  confirmed or declined with a reason the guest sees; confirmed ones are seated at a free
  table (its seats shown, a warning mark when the party is bigger) or cancelled / marked
  as a no-show; the food ordered ahead and its kitchen time; live updates.
- Backend: the bookings routes take reservations.manage too (require_any).
- @xenia/ui ReasonPicker + reasonText (gallery, unit test), first piece moved from the
  terminal (4.6 → 4.8): the counter's online reject and booking decline dialogs use it;
  the waiter loads @xenia/ui styles.css (the .x-* components; tokens as before).
- Tests: waiter e2e +2 (request listed with the key, confirmed and seated from the phone);
  terminal.mjs and qr_table.mjs green.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-17 10:10:14 +02:00
co-authored by Claude Opus 5.5
parent 1e8271e370
commit f57894dcb7
16 changed files with 387 additions and 37 deletions
+11 -6
View File
@@ -32,7 +32,7 @@ from pydantic import BaseModel, Field
from sqlalchemy.orm import Session, selectinload from sqlalchemy.orm import Session, selectinload
from config import settings from config import settings
from core.access.deps import require from core.access.deps import require, require_any
from core.errors import XeniaError from core.errors import XeniaError
from core.timeutil import utcnow from core.timeutil import utcnow
from database import get_db from database import get_db
@@ -304,8 +304,13 @@ def _booking_changed(background: BackgroundTasks, r) -> None:
broadcast_sync("reservation_updated", {"reservation_id": r.id, "status": r.status}) broadcast_sync("reservation_updated", {"reservation_id": r.id, "status": r.status})
# Bookings: the counter and, since 4.8, the waiters' phones; whoever handles online orders or
# manages reservations
_BOOKINGS = require_any("reservations.manage", MANAGE) # the last refusal is the one reported
@router.get("/bookings") @router.get("/bookings")
def list_bookings(db: Session = Depends(get_db), user=Depends(require(MANAGE))): def list_bookings(db: Session = Depends(get_db), user=Depends(_BOOKINGS)):
"""The counter's bookings: `requested` (online, waiting for an answer, soonest first) and """The counter's bookings: `requested` (online, waiting for an answer, soonest first) and
`upcoming` (confirmed, from 4 hours ago on, soonest first; any source).""" `upcoming` (confirmed, from 4 hours ago on, soonest first; any source)."""
from datetime import timedelta from datetime import timedelta
@@ -319,7 +324,7 @@ def list_bookings(db: Session = Depends(get_db), user=Depends(require(MANAGE))):
@router.post("/bookings/{reservation_id}/confirm") @router.post("/bookings/{reservation_id}/confirm")
def confirm_booking(reservation_id: int, background: BackgroundTasks, db: Session = Depends(get_db), def confirm_booking(reservation_id: int, background: BackgroundTasks, db: Session = Depends(get_db),
user=Depends(require(MANAGE))): user=Depends(_BOOKINGS)):
"""Confirm: the customer is told; food ordered ahead goes to the kitchen at its fire time """Confirm: the customer is told; food ordered ahead goes to the kitchen at its fire time
(at once if that time has passed and the day is open).""" (at once if that time has passed and the day is open)."""
from routers import orders as orders_api from routers import orders as orders_api
@@ -338,7 +343,7 @@ def confirm_booking(reservation_id: int, background: BackgroundTasks, db: Sessio
@router.post("/bookings/{reservation_id}/decline") @router.post("/bookings/{reservation_id}/decline")
def decline_booking(reservation_id: int, body: BookingAnswer, background: BackgroundTasks, def decline_booking(reservation_id: int, body: BookingAnswer, background: BackgroundTasks,
db: Session = Depends(get_db), user=Depends(require(MANAGE))): db: Session = Depends(get_db), user=Depends(_BOOKINGS)):
from services import online_reservations as svc from services import online_reservations as svc
r = _booking(db, reservation_id) r = _booking(db, reservation_id)
svc.decline(db, r, body.reason) svc.decline(db, r, body.reason)
@@ -349,7 +354,7 @@ def decline_booking(reservation_id: int, body: BookingAnswer, background: Backgr
@router.post("/bookings/{reservation_id}/arrive") @router.post("/bookings/{reservation_id}/arrive")
def arrive_booking(reservation_id: int, body: ArriveRequest, background: BackgroundTasks, def arrive_booking(reservation_id: int, body: ArriveRequest, background: BackgroundTasks,
db: Session = Depends(get_db), user=Depends(require(MANAGE))): db: Session = Depends(get_db), user=Depends(_BOOKINGS)):
"""The guests are here: seat them (optional table); their food's order moves to the table """The guests are here: seat them (optional table); their food's order moves to the table
(and goes to the kitchen now if it hadn't yet).""" (and goes to the kitchen now if it hadn't yet)."""
from services import online_reservations as svc from services import online_reservations as svc
@@ -367,7 +372,7 @@ def arrive_booking(reservation_id: int, body: ArriveRequest, background: Backgro
@router.post("/bookings/{reservation_id}/cancel") @router.post("/bookings/{reservation_id}/cancel")
def cancel_booking(reservation_id: int, body: CancelRequest, background: BackgroundTasks, def cancel_booking(reservation_id: int, body: CancelRequest, background: BackgroundTasks,
db: Session = Depends(get_db), user=Depends(require(MANAGE))): db: Session = Depends(get_db), user=Depends(_BOOKINGS)):
from services import online_reservations as svc from services import online_reservations as svc
r = _booking(db, reservation_id) r = _booking(db, reservation_id)
svc.cancel(db, r, body.status, body.reason) svc.cancel(db, r, body.status, body.reason)
+33 -1
View File
@@ -44,7 +44,8 @@
"orderLog": "Αρχείο Παραγγελιών", "orderLog": "Αρχείο Παραγγελιών",
"settings": "Ρυθμίσεις", "settings": "Ρυθμίσεις",
"installApp": "Εγκατάσταση εφαρμογής", "installApp": "Εγκατάσταση εφαρμογής",
"chat": "Chat" "chat": "Chat",
"bookings": "Κρατήσεις"
}, },
"shell": { "shell": {
"notifications": "Ειδοποιήσεις", "notifications": "Ειδοποιήσεις",
@@ -810,5 +811,36 @@
"table_one": "Τραπέζι για {{count}}", "table_one": "Τραπέζι για {{count}}",
"table_other": "Τραπέζι για {{count}}", "table_other": "Τραπέζι για {{count}}",
"over": "{{count}} άτομα σε τραπέζι για {{seats}}: εντάξει, είναι μόνο ένδειξη" "over": "{{count}} άτομα σε τραπέζι για {{seats}}: εντάξει, είναι μόνο ένδειξη"
},
"bookings": {
"title": "Κρατήσεις",
"loadFailed": "Σφάλμα φόρτωσης κρατήσεων",
"failed": "Σφάλμα αποθήκευσης",
"requests": "Αιτήματα ({{count}})",
"noRequests": "Δεν υπάρχουν αιτήματα",
"upcoming": "Επιβεβαιωμένες ({{count}})",
"noUpcoming": "Δεν υπάρχουν επιβεβαιωμένες κρατήσεις",
"confirm": "Επιβεβαίωση",
"decline": "Απόρριψη",
"today": "Σήμερα {{time}}",
"people_one": "{{count}} άτομο",
"people_other": "{{count}} άτομα",
"foodSent": "Φαγητό εκ των προτέρων: στην κουζίνα",
"foodAt": "Φαγητό εκ των προτέρων: στην κουζίνα στις {{time}}",
"foodOnConfirm": "Φαγητό εκ των προτέρων: στην κουζίνα μόλις επιβεβαιωθεί",
"table": "Τραπέζι",
"noTable": "Χωρίς τραπέζι ακόμα",
"arrive": "Ήρθαν: τοποθέτηση",
"cancel": "Ακύρωση",
"noShow": "Δεν ήρθαν",
"declineTitle": "Απόρριψη της κράτησης του/της {{name}};",
"declineBody": "Ο πελάτης βλέπει τον λόγο.",
"reason": "Λόγος",
"reasons": {
"full": "Είμαστε πλήρεις",
"closed": "Είμαστε κλειστά τότε",
"party": "Ιδιωτική εκδήλωση",
"other": "Άλλος λόγος"
}
} }
} }
+33 -1
View File
@@ -44,7 +44,8 @@
"orderLog": "Order log", "orderLog": "Order log",
"settings": "Settings", "settings": "Settings",
"installApp": "Install the app", "installApp": "Install the app",
"chat": "Chat" "chat": "Chat",
"bookings": "Bookings"
}, },
"shell": { "shell": {
"notifications": "Notifications", "notifications": "Notifications",
@@ -810,5 +811,36 @@
"table_one": "Table for {{count}}", "table_one": "Table for {{count}}",
"table_other": "Table for {{count}}", "table_other": "Table for {{count}}",
"over": "{{count}} guests at a table for {{seats}}: fine, it is only a suggestion" "over": "{{count}} guests at a table for {{seats}}: fine, it is only a suggestion"
},
"bookings": {
"title": "Bookings",
"loadFailed": "Couldn't load the bookings",
"failed": "Couldn't save the change",
"requests": "Requests ({{count}})",
"noRequests": "No requests waiting",
"upcoming": "Confirmed ({{count}})",
"noUpcoming": "No confirmed bookings coming up",
"confirm": "Confirm",
"decline": "Decline",
"today": "Today {{time}}",
"people_one": "{{count}} person",
"people_other": "{{count}} people",
"foodSent": "Food ordered ahead: in the kitchen",
"foodAt": "Food ordered ahead: to the kitchen at {{time}}",
"foodOnConfirm": "Food ordered ahead: to the kitchen once confirmed",
"table": "Table",
"noTable": "No table yet",
"arrive": "They are here: seat them",
"cancel": "Cancel",
"noShow": "Didn't come",
"declineTitle": "Decline {{name}}'s booking?",
"declineBody": "The guest sees the reason.",
"reason": "Reason",
"reasons": {
"full": "We are fully booked",
"closed": "We're closed then",
"party": "Private event",
"other": "Other reason"
}
} }
} }
+10 -1
View File
@@ -4,7 +4,7 @@
import { useEffect, useState } from 'react' import { useEffect, useState } from 'react'
import { import {
Button, Dialog, EmptyState, Field, IconButton, InfoTip, Input, PinPad, Select, Sheet, Button, Dialog, EmptyState, Field, IconButton, InfoTip, Input, PinPad, Select, Sheet,
Spinner, Stepper, Switch, Textarea, ToastProvider, useToast, ReasonPicker, Spinner, Stepper, Switch, Textarea, ToastProvider, useToast,
} from '../src/index.js' } from '../src/index.js'
import '../src/styles.css' import '../src/styles.css'
@@ -41,6 +41,8 @@ function Demo() {
const [theme, setTheme] = useState('light') const [theme, setTheme] = useState('light')
const [venue, setVenue] = useState('teal') const [venue, setVenue] = useState('teal')
const [dialog, setDialog] = useState(false) const [dialog, setDialog] = useState(false)
const [reason, setReason] = useState(null)
const [reasonOther, setReasonOther] = useState('')
const [locked, setLocked] = useState(false) const [locked, setLocked] = useState(false)
const [sheet, setSheet] = useState(null) const [sheet, setSheet] = useState(null)
const [on, setOn] = useState(true) const [on, setOn] = useState(true)
@@ -139,6 +141,13 @@ function Demo() {
</div> </div>
</Section> </Section>
<Section title="ReasonPicker">
<div style={{ maxWidth: 360 }}>
<ReasonPicker ariaLabel="Reason" value={reason} onChange={setReason} other={reasonOther} onOther={setReasonOther}
options={[{ value: 'full', label: 'We are fully booked' }, { value: 'closed', label: 'Closed that day' }]} />
</div>
</Section>
<Section title="Switch + InfoTip"> <Section title="Switch + InfoTip">
<div style={{ display: 'grid', gap: 'var(--x-space-4)', maxWidth: 520 }}> <div style={{ display: 'grid', gap: 'var(--x-space-4)', maxWidth: 520 }}>
<Switch checked={on} onChange={setOn} label="Print kitchen tickets" description="Send new items to the kitchen printer." /> <Switch checked={on} onChange={setOn} label="Print kitchen tickets" description="Send new items to the kitchen printer." />
+13
View File
@@ -315,3 +315,16 @@
.x-switch-row__label { display: block; font-size: var(--x-text-body); line-height: var(--x-leading-body); font-weight: var(--x-weight-medium); color: var(--x-ink); cursor: pointer; } .x-switch-row__label { display: block; font-size: var(--x-text-body); line-height: var(--x-leading-body); font-weight: var(--x-weight-medium); color: var(--x-ink); cursor: pointer; }
.x-switch-row__description { margin-top: var(--x-space-0-5); font-size: var(--x-text-label); line-height: var(--x-leading-label); color: var(--x-ink-2); } .x-switch-row__description { margin-top: var(--x-space-0-5); font-size: var(--x-text-label); line-height: var(--x-leading-label); color: var(--x-ink-2); }
.x-switch-row--disabled .x-switch-row__label { cursor: not-allowed; opacity: 0.6; } .x-switch-row--disabled .x-switch-row__label { cursor: not-allowed; opacity: 0.6; }
/* ── ReasonPicker ───────────────────────────────────────────────────────────── */
.x-reasons { display: grid; gap: var(--x-space-2); }
.x-reasons__list { display: grid; gap: var(--x-space-1); }
.x-reasons__option {
min-height: var(--x-control-md); padding: 0 var(--x-space-3);
border: 0; border-radius: var(--x-radius-control); text-align: left;
font: inherit; font-size: var(--x-text-body); color: var(--x-ink); background: var(--x-surface-2);
cursor: pointer; transition: background-color var(--x-duration-fast) var(--x-ease);
}
.x-reasons__option:hover { background: var(--x-surface-3); }
.x-reasons__option:focus-visible { outline: none; box-shadow: var(--x-focus-ring); }
.x-reasons__option--on, .x-reasons__option--on:hover { background: var(--x-accent); color: var(--x-accent-fg); }
@@ -0,0 +1,33 @@
import { cx } from '../internal/cx.js'
export { reasonText } from './reasons.js'
/**
* Pick why (a booking declined, an online order rejected…): one of the given reasons or
* "other" with free text (plan step 4.8; first shared by the counter and the waiter's phone).
* <ReasonPicker options={[{ value: 'full', label: 'We are full' }]} value={choice} onChange={setChoice}
* other={text} onOther={setText} otherLabel="Other" ariaLabel="Reason" />
* `value` is the chosen option's value or 'other'. The reason to send:
* reasonText(value, options, other)
*/
export function ReasonPicker({ options, value, onChange, other = '', onOther, otherLabel = 'Other', ariaLabel, testIdPrefix = 'reason', className }) {
const all = [...options, { value: 'other', label: otherLabel }]
return (
<div className={cx('x-reasons', className)}>
<div className="x-reasons__list" role="radiogroup" aria-label={ariaLabel}>
{all.map(o => (
<button key={o.value} type="button" role="radio" aria-checked={value === o.value}
className={cx('x-reasons__option', value === o.value && 'x-reasons__option--on')}
onClick={() => onChange(o.value)} data-testid={`${testIdPrefix}-${o.value}`}>
{o.label}
</button>
))}
</div>
{value === 'other' && (
<input className="x-input" value={other} maxLength={300} autoFocus aria-label={ariaLabel}
onChange={e => onOther?.(e.target.value)} data-testid={`${testIdPrefix}-other-text`} />
)}
</div>
)
}
+7
View File
@@ -0,0 +1,7 @@
/** The text to send for a ReasonPicker choice: the option's label, the typed text for 'other',
* '' for no choice. Plain JS so Node tests can import it. */
export function reasonText(value, options, other = '') {
if (!value) return ''
if (value === 'other') return other.trim()
return options.find(o => o.value === value)?.label ?? ''
}
+1
View File
@@ -21,6 +21,7 @@ export { Spinner } from './components/Spinner.jsx'
export { Field, Input, Textarea, Select } from './components/Field.jsx' export { Field, Input, Textarea, Select } from './components/Field.jsx'
export { Switch } from './components/Switch.jsx' export { Switch } from './components/Switch.jsx'
export { Stepper } from './components/Stepper.jsx' export { Stepper } from './components/Stepper.jsx'
export { ReasonPicker, reasonText } from './components/ReasonPicker.jsx'
export { UiLabelsProvider, DEFAULT_LABELS } from './components/labels.js' export { UiLabelsProvider, DEFAULT_LABELS } from './components/labels.js'
export { cx } from './internal/cx.js' export { cx } from './internal/cx.js'
export { THEMES, THEME_STORAGE_KEY, applyTheme, getStoredTheme } from './theme.js' export { THEMES, THEME_STORAGE_KEY, applyTheme, getStoredTheme } from './theme.js'
+10
View File
@@ -0,0 +1,10 @@
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { reasonText } from '../src/components/reasons.js'
test('reasonText: the option label, the typed text for other, nothing for no choice', () => {
const options = [{ value: 'full', label: 'We are full' }]
assert.equal(reasonText('full', options), 'We are full')
assert.equal(reasonText('other', options, ' Private party '), 'Private party')
assert.equal(reasonText(null, options), '')
})
+5 -12
View File
@@ -7,7 +7,7 @@ import { useState } from 'react'
import { AlertTriangle, Ban, Check, ChefHat, MessageSquare, Phone, UserX, Users } from 'lucide-react' import { AlertTriangle, Ban, Check, ChefHat, MessageSquare, Phone, UserX, Users } from 'lucide-react'
import { errorMessage } from '@xenia/api' import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n' import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog, EmptyState, Input, Select } from '@xenia/ui' import { Button, Dialog, EmptyState, ReasonPicker, Select, reasonText } from '@xenia/ui'
import client from '../../api/client' import client from '../../api/client'
import { bookingSteps, foodState, freeTables, whenLabel } from './logic/bookings' import { bookingSteps, foodState, freeTables, whenLabel } from './logic/bookings'
@@ -129,7 +129,8 @@ function DeclineDialog({ busy, error, onClose, onDecline }) {
const { t } = useTranslation('terminal') const { t } = useTranslation('terminal')
const [choice, setChoice] = useState(null) const [choice, setChoice] = useState(null)
const [other, setOther] = useState('') const [other, setOther] = useState('')
const reason = choice === 'other' ? other.trim() : choice ? t(`pos.bookings.reasons.${choice}`) : '' const options = REASONS.map(r => ({ value: r, label: t(`pos.bookings.reasons.${r}`) }))
const reason = reasonText(choice, options, other)
return ( return (
<Dialog open size="sm" title={t('pos.bookings.declineTitle')} onClose={busy ? undefined : onClose} <Dialog open size="sm" title={t('pos.bookings.declineTitle')} onClose={busy ? undefined : onClose}
footer={<> footer={<>
@@ -140,16 +141,8 @@ function DeclineDialog({ busy, error, onClose, onDecline }) {
</>}> </>}>
<div className="grid gap-2"> <div className="grid gap-2">
<p className="text-body text-ink-2">{t('pos.online.rejectBody')}</p> <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')}> <ReasonPicker options={options} value={choice} onChange={setChoice} other={other} onOther={setOther}
{[...REASONS, 'other'].map(r => ( otherLabel={t('pos.bookings.reasons.other')} ariaLabel={t('pos.online.reason')} testIdPrefix="decline" />
<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>} {error && <p role="alert" className="text-label text-danger-ink">{error}</p>}
</div> </div>
</Dialog> </Dialog>
+5 -14
View File
@@ -11,7 +11,7 @@ import { useState } from 'react'
import { AlertTriangle, Ban, Banknote, Bike, Check, ChefHat, Clock, MapPin, MessageSquare, PackageCheck, Phone, ShoppingBag, Utensils } from 'lucide-react' import { AlertTriangle, Ban, Banknote, Bike, Check, ChefHat, Clock, MapPin, MessageSquare, PackageCheck, Phone, ShoppingBag, Utensils } from 'lucide-react'
import { errorMessage } from '@xenia/api' import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n' import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog, EmptyState, Input } from '@xenia/ui' import { Button, Dialog, EmptyState, ReasonPicker, reasonText } from '@xenia/ui'
import client from '../../api/client' import client from '../../api/client'
import { diffRows, finishWord as finishOf, kindOf, nextStep } from './logic/online' import { diffRows, finishWord as finishOf, kindOf, nextStep } from './logic/online'
import { itemPayments, orderLines, orderSums, qtyLabel } from './logic/tables' import { itemPayments, orderLines, orderSums, qtyLabel } from './logic/tables'
@@ -190,7 +190,8 @@ function RejectDialog({ busy, error, onClose, onReject }) {
const { t } = useTranslation('terminal') const { t } = useTranslation('terminal')
const [choice, setChoice] = useState(null) const [choice, setChoice] = useState(null)
const [other, setOther] = useState('') const [other, setOther] = useState('')
const reason = choice === 'other' ? other.trim() : choice ? t(`pos.online.reasons.${choice}`) : '' const options = REASONS.map(r => ({ value: r, label: t(`pos.online.reasons.${r}`) }))
const reason = reasonText(choice, options, other)
return ( return (
<Dialog open size="sm" title={t('pos.online.rejectTitle')} onClose={busy ? undefined : onClose} <Dialog open size="sm" title={t('pos.online.rejectTitle')} onClose={busy ? undefined : onClose}
footer={<> footer={<>
@@ -201,18 +202,8 @@ function RejectDialog({ busy, error, onClose, onReject }) {
</>}> </>}>
<div className="grid gap-2"> <div className="grid gap-2">
<p className="text-body text-ink-2">{t('pos.online.rejectBody')}</p> <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')}> <ReasonPicker options={options} value={choice} onChange={setChoice} other={other} onOther={setOther}
{[...REASONS, 'other'].map(r => ( otherLabel={t('pos.online.reasons.other')} ariaLabel={t('pos.online.reason')} testIdPrefix="reason" />
<button key={r} type="button" role="radio" aria-checked={choice === r} onClick={() => setChoice(r)} data-testid={`reason-${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.online.reasons.${r}`)}
</button>
))}
</div>
{choice === 'other' && (
<Input value={other} onChange={e => setOther(e.target.value)} maxLength={300} autoFocus aria-label={t('pos.online.reason')} data-testid="reason-text" />
)}
{error && <p role="alert" className="text-label text-danger-ink">{error}</p>} {error && <p role="alert" className="text-label text-danger-ink">{error}</p>}
</div> </div>
</Dialog> </Dialog>
+22
View File
@@ -322,6 +322,28 @@ try {
r.check('4.8: more guests than seats is allowed, with a hint (not a limit)', await a.getByTestId('seats-hint').getAttribute('data-over') === 'true') r.check('4.8: more guests than seats is allowed, with a hint (not a limit)', await a.getByTestId('seats-hint').getAttribute('data-over') === 'true')
await a.goto(`${APP}/tables`) await a.goto(`${APP}/tables`)
// bookings on the phone: a request made online is confirmed and the guests seated (the counter's flow)
const sqlite = sql => execFileSync(PYTHON, ['-c', `import sqlite3; c = sqlite3.connect(r"${path.join(backend.dataDir, 'pos.db')}"); r = c.execute(${JSON.stringify(sql)}).fetchall(); c.commit(); print(r)`], { encoding: 'utf8' }).trim()
sqlite("insert into reservations (guest_name, party_size, phone, reserved_for, status, source, online_ref, created_at, updated_at) values ('E2E Guest', 2, '6900000000', datetime('now', '+2 hours'), 'requested', 'online', 'ORD-E2E', datetime('now'), datetime('now'))")
const waiterRole = await api('GET', '/api/waiters/roles/waiter/permissions', { token: boss })
await api('PUT', '/api/waiters/roles/waiter/permissions', { token: boss, body: { keys: [...waiterRole.keys, 'connect_orders.manage'] } })
await a.goto(`${APP}/tables`)
await a.reload()
await a.locator('button').filter({ has: a.locator('svg') }).first().click().catch(() => {})
const drawerHasBookings = await a.getByRole('button', { name: 'Bookings' }).isVisible({ timeout: 5000 }).catch(() => false)
await a.goto(`${APP}/bookings`)
const card = () => a.locator('[data-testid="booking-card"]').filter({ hasText: 'E2E Guest' })
await card().first().waitFor({ timeout: 10_000 }).catch(() => {})
r.check('4.8: with the online-orders key the phone lists the booking request (drawer: Bookings)', drawerHasBookings && await card().getAttribute('data-status') === 'requested')
await card().getByTestId('booking-confirm').click()
await waitFor(async () => await card().getAttribute('data-status') === 'pending', 10_000, 300)
await card().getByTestId('booking-table').selectOption({ index: 1 })
await card().getByTestId('booking-arrive').click()
const seated = await waitFor(async () => /arrived', \d+/.test(sqlite("select status, table_id from reservations where online_ref = 'ORD-E2E'")) && 1, 10_000, 500)
r.check('4.8: …confirmed and seated at a table from the phone', !!seated, sqlite("select status, table_id from reservations where online_ref = 'ORD-E2E'"))
await api('PUT', '/api/waiters/roles/waiter/permissions', { token: boss, body: { keys: waiterRole.default_keys } })
await a.goto(`${APP}/tables`)
// ── 4.6: the look on the shared tokens: the venue's colour and light / dark reach the phone ── // ── 4.6: the look on the shared tokens: the venue's colour and light / dark reach the phone ──
const accentOf = () => a.evaluate(() => getComputedStyle(document.documentElement).getPropertyValue('--x-accent-rgb').trim()) const accentOf = () => a.evaluate(() => getComputedStyle(document.documentElement).getPropertyValue('--x-accent-rgb').trim())
r.check('4.6: the venue colour (default amber) is on the phone', await a.evaluate(() => document.documentElement.dataset.venueTheme) === 'amber') r.check('4.6: the venue colour (default amber) is on the phone', await a.evaluate(() => document.documentElement.dataset.venueTheme) === 'amber')
+2
View File
@@ -25,6 +25,7 @@ import ChatListPage from './pages/ChatListPage'
import ChatThreadPage from './pages/ChatThreadPage' import ChatThreadPage from './pages/ChatThreadPage'
import ShiftOverviewPage from './pages/ShiftOverviewPage' import ShiftOverviewPage from './pages/ShiftOverviewPage'
import OrderLogPage from './pages/OrderLogPage' import OrderLogPage from './pages/OrderLogPage'
import BookingsPage from './pages/BookingsPage'
import { NotificationProvider } from './context/NotificationContext' import { NotificationProvider } from './context/NotificationContext'
import { LiveProvider } from './context/LiveContext' import { LiveProvider } from './context/LiveContext'
import ConnectivityBar from './components/ConnectivityBar' import ConnectivityBar from './components/ConnectivityBar'
@@ -504,6 +505,7 @@ function Routed() {
<Route path="/settings/favorites" element={<FavoritesSetupPage />} /> <Route path="/settings/favorites" element={<FavoritesSetupPage />} />
<Route path="/shift-overview" element={<ShiftOverviewPage />} /> <Route path="/shift-overview" element={<ShiftOverviewPage />} />
<Route path="/order-log" element={<OrderLogPage />} /> <Route path="/order-log" element={<OrderLogPage />} />
<Route path="/bookings" element={<BookingsPage />} />
<Route path="/messages" element={<ChatListRoute />} /> <Route path="/messages" element={<ChatListRoute />} />
<Route path="/messages/:conversationId" element={<ChatThreadPage />} /> <Route path="/messages/:conversationId" element={<ChatThreadPage />} />
</Route> </Route>
+18 -1
View File
@@ -275,6 +275,19 @@ const DRAWER_NAV_ITEMS = [
}, },
{ ...NAV_REGISTRY.orders }, { ...NAV_REGISTRY.orders },
{ ...NAV_REGISTRY.messages }, { ...NAV_REGISTRY.messages },
{
// table bookings (4.8): for whoever handles online orders or manages reservations
key: 'bookings',
label: 'nav.bookings',
href: '/bookings',
match: (loc) => loc.pathname === '/bookings',
icon: (
<svg width="22" height="22" viewBox="0 0 24 24" fill="none">
<rect x="3" y="5" width="18" height="16" rx="2" stroke="currentColor" strokeWidth="2"/>
<path d="M3 10h18M8 3v4M16 3v4M9 15l2 2 4-4" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
</svg>
),
},
{ {
key: 'shift-overview', key: 'shift-overview',
label: 'nav.shiftSummary', label: 'nav.shiftSummary',
@@ -375,6 +388,10 @@ function SideDrawer({ open, onClose }) {
const { t } = useTranslation('waiter') const { t } = useTranslation('waiter')
const navigate = useNavigate() const navigate = useNavigate()
const chatOn = useChatOn() const chatOn = useChatOn()
const bookingsModule = useModule('connect_orders')
const bookingsOnline = useCan('connect_orders.manage')
const bookingsManage = useCan('reservations.manage')
const bookingsOn = bookingsModule && (bookingsOnline || bookingsManage)
const location = useLocation() const location = useLocation()
const { activeZoneTab, setActiveZoneTab } = useTableViewStore() const { activeZoneTab, setActiveZoneTab } = useTableViewStore()
@@ -425,7 +442,7 @@ function SideDrawer({ open, onClose }) {
<div style={{ fontSize: 10, fontWeight: 700, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: 1, padding: '4px 10px 8px' }}> <div style={{ fontSize: 10, fontWeight: 700, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: 1, padding: '4px 10px 8px' }}>
{t('shell.navigation')} {t('shell.navigation')}
</div> </div>
{DRAWER_NAV_ITEMS.filter(shown(chatOn)).map(item => { {DRAWER_NAV_ITEMS.filter(shown(chatOn)).filter(item => item.key !== 'bookings' || bookingsOn).map(item => {
const isStandaloneActive = location.pathname === '/tables' && activeZoneTab === 'standalone' const isStandaloneActive = location.pathname === '/tables' && activeZoneTab === 'standalone'
const active = item.key === 'standalone' const active = item.key === 'standalone'
? isStandaloneActive ? isStandaloneActive
+1 -1
View File
@@ -1,6 +1,6 @@
import { StrictMode } from 'react' import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client' import { createRoot } from 'react-dom/client'
import '@xenia/ui/tokens.css' // shared --x-* tokens: the waiter's --bg/--text… are made of them (4.6) import '@xenia/ui/styles.css' // shared --x-* tokens (the waiter's --bg/--text… are made of them, 4.6) + the .x-* components (4.8)
import './index.css' import './index.css'
// The theme before anything renders (no light flash on a dark phone): the user's light/dark // The theme before anything renders (no light flash on a dark phone): the user's light/dark
+183
View File
@@ -0,0 +1,183 @@
import { useCallback, useEffect, useState } from 'react'
import { useFormat, useTranslation } from '@xenia/i18n'
import { ReasonPicker, reasonText } from '@xenia/ui'
import AppShell from '../components/AppShell'
import client from '../api/client'
import { apiError } from '../api/errors'
import db from '../db/posdb'
// Table bookings on the phone (plan step 4.8), the counter's flow (terminal BookingPanel):
// requests made online are confirmed or declined (the guest sees the answer and the reason);
// today's confirmed bookings are seated at a free table (their food's order moves there) or
// cancelled / marked as a no-show. For whoever handles online orders or manages reservations.
const DECLINE_REASONS = ['full', 'closed', 'party']
const OPEN = ['open', 'partially_paid', 'paid']
export default function BookingsPage() {
const { t } = useTranslation('waiter')
const [data, setData] = useState(null)
const [error, setError] = useState('')
const [busy, setBusy] = useState(null)
const [declining, setDeclining] = useState(null)
const [free, setFree] = useState([])
const load = useCallback(async () => {
try {
const r = await client.get('/api/connect/bookings')
setData(r.data)
setError('')
} catch (err) { setError(apiError(err, t('bookings.loadFailed'))) }
try {
const [tables, orders] = await Promise.all([db.pos_tables.toArray(), db.pos_orders.toArray()])
const busyTables = new Set(orders.filter(o => OPEN.includes(o.status)).map(o => o.table_id))
setFree(tables.filter(tb => tb.is_active !== false && !busyTables.has(tb.id)))
} catch { setFree([]) }
}, [t])
useEffect(() => {
load()
const onLive = e => { if (['reservation_updated', 'order_updated', 'online_reservation'].includes(e.detail?.type)) load() }
window.addEventListener('live-event', onLive)
window.addEventListener('live-reconnected', load)
return () => { window.removeEventListener('live-event', onLive); window.removeEventListener('live-reconnected', load) }
}, [load])
async function run(booking, path, body) {
setBusy(booking.id)
setError('')
try {
await client.post(`/api/connect/bookings/${booking.id}/${path}`, body ?? {})
setDeclining(null)
} catch (err) { setError(apiError(err, t('bookings.failed'))) } finally {
setBusy(null)
load()
}
}
const requested = data?.requested ?? []
const upcoming = data?.upcoming ?? []
return (
<AppShell title={t('bookings.title')}>
<div style={{ padding: '12px 12px 96px', display: 'flex', flexDirection: 'column', gap: 10 }} data-testid="bookings">
{error && <p className="error-msg" role="alert">{error}</p>}
{!data && !error && <p style={{ textAlign: 'center', color: 'var(--muted)', padding: 24 }}>{t('common.loading')}</p>}
{data && (
<>
<h2 style={sectionTitle}>{t('bookings.requests', { count: requested.length })}</h2>
{requested.length === 0 && <p style={empty}>{t('bookings.noRequests')}</p>}
{requested.map(b => (
<BookingCard key={b.id} booking={b}>
<div style={{ display: 'flex', gap: 8 }}>
<button className="btn btn--accent" style={{ flex: 1 }} disabled={busy === b.id} onClick={() => run(b, 'confirm')} data-testid="booking-confirm">
{t('bookings.confirm')}
</button>
<button className="btn btn--secondary" style={{ flex: 1 }} disabled={busy === b.id} onClick={() => setDeclining(b)} data-testid="booking-decline">
{t('bookings.decline')}
</button>
</div>
</BookingCard>
))}
<h2 style={{ ...sectionTitle, marginTop: 12 }}>{t('bookings.upcoming', { count: upcoming.length })}</h2>
{upcoming.length === 0 && <p style={empty}>{t('bookings.noUpcoming')}</p>}
{upcoming.map(b => (
<BookingCard key={b.id} booking={b}>
<SeatControls booking={b} free={free} busy={busy === b.id} onSeat={tableId => run(b, 'arrive', { table_id: tableId })}
onCancel={status => run(b, 'cancel', { status })} />
</BookingCard>
))}
</>
)}
</div>
{declining && <DeclineSheet booking={declining} busy={busy === declining.id} onClose={() => setDeclining(null)} onDecline={reason => run(declining, 'decline', { reason })} />}
</AppShell>
)
}
const sectionTitle = { fontSize: 12, fontWeight: 700, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: 0.6, margin: '4px 2px 0' }
const empty = { color: 'var(--muted)', fontSize: 14, padding: '6px 2px' }
function BookingCard({ booking: b, children }) {
const { t } = useTranslation('waiter')
const { formatTime, formatDate, formatDateTime, formatMoney } = useFormat()
const today = formatDate(b.reserved_for) === formatDate(new Date())
return (
<div data-testid="booking-card" data-booking={b.id} data-status={b.status}
style={{ background: 'var(--bg2)', border: '1px solid var(--border)', borderRadius: 14, padding: 14, display: 'flex', flexDirection: 'column', gap: 8 }}>
<div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
<span style={{ fontSize: 17, fontWeight: 800, color: 'var(--text)', flex: 1 }}>
{today ? t('bookings.today', { time: formatTime(b.reserved_for) }) : formatDateTime(b.reserved_for, 'datetimeShort')}
</span>
{b.ref && <span style={{ fontSize: 12, color: 'var(--muted)' }}>{b.ref}</span>}
</div>
<div style={{ fontSize: 15, fontWeight: 700, color: 'var(--text)' }}>
{b.guest_name} · {t('bookings.people', { count: b.party_size })}
{b.table_label && <span style={{ color: 'var(--muted)', fontWeight: 500 }}> · {b.table_label}</span>}
</div>
{b.phone && <a href={`tel:${b.phone}`} style={{ fontSize: 14, color: 'var(--accent)' }}>{b.phone}</a>}
{b.note && <div style={{ fontSize: 13, color: 'var(--x-warning-ink)', background: 'var(--x-warning-soft)', borderRadius: 8, padding: '6px 10px' }}>{b.note}</div>}
{b.lines?.length > 0 && (
<div style={{ fontSize: 13, color: 'var(--text2)', borderTop: '1px solid var(--border)', paddingTop: 6 }}>
<div style={{ fontWeight: 700, marginBottom: 2 }}>
{b.order_id ? t('bookings.foodSent') : b.fire_at ? t('bookings.foodAt', { time: formatTime(b.fire_at) }) : t('bookings.foodOnConfirm')}
</div>
{b.lines.map((l, i) => <div key={i}>{l.quantity}× {l.name}</div>)}
<div style={{ fontWeight: 700, marginTop: 2 }}>{formatMoney(b.total)}</div>
</div>
)}
{children}
</div>
)
}
function SeatControls({ booking, free, busy, onSeat, onCancel }) {
const { t } = useTranslation('waiter')
const [table, setTable] = useState('')
const options = free.map(tb => ({ id: tb.id, name: tb.label || `T${tb.number}`, seats: tb.seat_count }))
return (
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
<select value={table} onChange={e => setTable(e.target.value)} aria-label={t('bookings.table')} data-testid="booking-table"
style={{ height: 44, borderRadius: 10, border: '1px solid var(--border)', background: 'var(--bg3)', color: 'var(--text)', padding: '0 10px', fontSize: 15 }}>
<option value="">{t('bookings.noTable')}</option>
{options.map(o => (
<option key={o.id} value={o.id}>
{o.name}{o.seats ? ` · ${t('seats.table', { count: o.seats })}` : ''}
{o.seats && booking.party_size > o.seats ? ' ⚠' : ''}
</option>
))}
</select>
<button className="btn btn--accent" disabled={busy} onClick={() => onSeat(table ? Number(table) : null)} data-testid="booking-arrive">
{t('bookings.arrive')}
</button>
<div style={{ display: 'flex', gap: 8 }}>
<button className="btn btn--secondary" style={{ flex: 1 }} disabled={busy} onClick={() => onCancel('cancelled')} data-testid="booking-cancel">{t('bookings.cancel')}</button>
<button className="btn btn--secondary" style={{ flex: 1 }} disabled={busy} onClick={() => onCancel('no_show')} data-testid="booking-noshow">{t('bookings.noShow')}</button>
</div>
</div>
)
}
function DeclineSheet({ booking, busy, onClose, onDecline }) {
const { t } = useTranslation('waiter')
const [choice, setChoice] = useState(null)
const [other, setOther] = useState('')
const options = DECLINE_REASONS.map(r => ({ value: r, label: t(`bookings.reasons.${r}`) }))
const reason = reasonText(choice, options, other)
return (
<div className="modal-overlay" onClick={busy ? undefined : onClose}>
<div className="modal-sheet" onClick={e => e.stopPropagation()} data-testid="decline-sheet">
<div className="modal-handle" />
<h2 className="modal-title">{t('bookings.declineTitle', { name: booking.guest_name })}</h2>
<p style={{ textAlign: 'center', color: 'var(--muted)', fontSize: 13, margin: '0 0 14px' }}>{t('bookings.declineBody')}</p>
<ReasonPicker options={options} value={choice} onChange={setChoice} other={other} onOther={setOther}
otherLabel={t('bookings.reasons.other')} ariaLabel={t('bookings.reason')} testIdPrefix="decline" />
<div style={{ display: 'flex', gap: 10, marginTop: 16 }}>
<button className="btn btn--secondary" style={{ flex: 1 }} onClick={onClose} disabled={busy}>{t('common.back')}</button>
<button className="btn btn--danger" style={{ flex: 1 }} disabled={!reason || busy} onClick={() => onDecline(reason)} data-testid="decline-confirm">
{t('bookings.decline')}
</button>
</div>
</div>
</div>
)
}