From f57894dcb760afef786eef82b35275e6467775dd Mon Sep 17 00:00:00 2001 From: bonamin Date: Tue, 17 Nov 2026 10:10:14 +0200 Subject: [PATCH] feat(waiter): table bookings on the phone; shared ReasonPicker (platform-v2 step 4.8c) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 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 --- local_backend/routers/connect_orders.py | 17 +- packages/i18n/locales/el/waiter.json | 34 +++- packages/i18n/locales/en/waiter.json | 34 +++- packages/ui/gallery/Gallery.jsx | 11 +- packages/ui/src/components.css | 13 ++ packages/ui/src/components/ReasonPicker.jsx | 33 ++++ packages/ui/src/components/reasons.js | 7 + packages/ui/src/index.js | 1 + packages/ui/tests/reasons.test.mjs | 10 ++ terminal/src/apps/pos/BookingPanel.jsx | 17 +- terminal/src/apps/pos/OnlinePanel.jsx | 19 +- tests/e2e/waiter.mjs | 22 +++ waiter_pwa/src/App.jsx | 2 + waiter_pwa/src/components/AppShell.jsx | 19 +- waiter_pwa/src/main.jsx | 2 +- waiter_pwa/src/pages/BookingsPage.jsx | 183 ++++++++++++++++++++ 16 files changed, 387 insertions(+), 37 deletions(-) create mode 100644 packages/ui/src/components/ReasonPicker.jsx create mode 100644 packages/ui/src/components/reasons.js create mode 100644 packages/ui/tests/reasons.test.mjs create mode 100644 waiter_pwa/src/pages/BookingsPage.jsx diff --git a/local_backend/routers/connect_orders.py b/local_backend/routers/connect_orders.py index 8caa241..e00b18c 100644 --- a/local_backend/routers/connect_orders.py +++ b/local_backend/routers/connect_orders.py @@ -32,7 +32,7 @@ from pydantic import BaseModel, Field from sqlalchemy.orm import Session, selectinload 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.timeutil import utcnow 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}) +# 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") -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 `upcoming` (confirmed, from 4 hours ago on, soonest first; any source).""" 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") 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 (at once if that time has passed and the day is open).""" 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") 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 r = _booking(db, reservation_id) 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") 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 (and goes to the kitchen now if it hadn't yet).""" 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") 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 r = _booking(db, reservation_id) svc.cancel(db, r, body.status, body.reason) diff --git a/packages/i18n/locales/el/waiter.json b/packages/i18n/locales/el/waiter.json index b5b6091..afa2a2d 100644 --- a/packages/i18n/locales/el/waiter.json +++ b/packages/i18n/locales/el/waiter.json @@ -44,7 +44,8 @@ "orderLog": "Αρχείο Παραγγελιών", "settings": "Ρυθμίσεις", "installApp": "Εγκατάσταση εφαρμογής", - "chat": "Chat" + "chat": "Chat", + "bookings": "Κρατήσεις" }, "shell": { "notifications": "Ειδοποιήσεις", @@ -810,5 +811,36 @@ "table_one": "Τραπέζι για {{count}}", "table_other": "Τραπέζι για {{count}}", "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": "Άλλος λόγος" + } } } diff --git a/packages/i18n/locales/en/waiter.json b/packages/i18n/locales/en/waiter.json index f984e8b..ee8a267 100644 --- a/packages/i18n/locales/en/waiter.json +++ b/packages/i18n/locales/en/waiter.json @@ -44,7 +44,8 @@ "orderLog": "Order log", "settings": "Settings", "installApp": "Install the app", - "chat": "Chat" + "chat": "Chat", + "bookings": "Bookings" }, "shell": { "notifications": "Notifications", @@ -810,5 +811,36 @@ "table_one": "Table for {{count}}", "table_other": "Table for {{count}}", "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" + } } } diff --git a/packages/ui/gallery/Gallery.jsx b/packages/ui/gallery/Gallery.jsx index f80e752..f73cc4a 100644 --- a/packages/ui/gallery/Gallery.jsx +++ b/packages/ui/gallery/Gallery.jsx @@ -4,7 +4,7 @@ import { useEffect, useState } from 'react' import { 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' import '../src/styles.css' @@ -41,6 +41,8 @@ function Demo() { const [theme, setTheme] = useState('light') const [venue, setVenue] = useState('teal') const [dialog, setDialog] = useState(false) + const [reason, setReason] = useState(null) + const [reasonOther, setReasonOther] = useState('') const [locked, setLocked] = useState(false) const [sheet, setSheet] = useState(null) const [on, setOn] = useState(true) @@ -139,6 +141,13 @@ function Demo() { +
+
+ +
+
+
diff --git a/packages/ui/src/components.css b/packages/ui/src/components.css index b4cd78a..035f79e 100644 --- a/packages/ui/src/components.css +++ b/packages/ui/src/components.css @@ -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__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; } + +/* ── 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); } diff --git a/packages/ui/src/components/ReasonPicker.jsx b/packages/ui/src/components/ReasonPicker.jsx new file mode 100644 index 0000000..2bb7de4 --- /dev/null +++ b/packages/ui/src/components/ReasonPicker.jsx @@ -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). + * + * `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 ( +
+
+ {all.map(o => ( + + ))} +
+ {value === 'other' && ( + onOther?.(e.target.value)} data-testid={`${testIdPrefix}-other-text`} /> + )} +
+ ) +} + diff --git a/packages/ui/src/components/reasons.js b/packages/ui/src/components/reasons.js new file mode 100644 index 0000000..747335f --- /dev/null +++ b/packages/ui/src/components/reasons.js @@ -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 ?? '' +} diff --git a/packages/ui/src/index.js b/packages/ui/src/index.js index 98bbaab..fb97005 100644 --- a/packages/ui/src/index.js +++ b/packages/ui/src/index.js @@ -21,6 +21,7 @@ export { Spinner } from './components/Spinner.jsx' export { Field, Input, Textarea, Select } from './components/Field.jsx' export { Switch } from './components/Switch.jsx' export { Stepper } from './components/Stepper.jsx' +export { ReasonPicker, reasonText } from './components/ReasonPicker.jsx' export { UiLabelsProvider, DEFAULT_LABELS } from './components/labels.js' export { cx } from './internal/cx.js' export { THEMES, THEME_STORAGE_KEY, applyTheme, getStoredTheme } from './theme.js' diff --git a/packages/ui/tests/reasons.test.mjs b/packages/ui/tests/reasons.test.mjs new file mode 100644 index 0000000..b76cdc0 --- /dev/null +++ b/packages/ui/tests/reasons.test.mjs @@ -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), '') +}) diff --git a/terminal/src/apps/pos/BookingPanel.jsx b/terminal/src/apps/pos/BookingPanel.jsx index 4e4b99d..e1f8f4f 100644 --- a/terminal/src/apps/pos/BookingPanel.jsx +++ b/terminal/src/apps/pos/BookingPanel.jsx @@ -7,7 +7,7 @@ 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 { Button, Dialog, EmptyState, ReasonPicker, Select, reasonText } from '@xenia/ui' import client from '../../api/client' import { bookingSteps, foodState, freeTables, whenLabel } from './logic/bookings' @@ -129,7 +129,8 @@ 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}`) : '' + const options = REASONS.map(r => ({ value: r, label: t(`pos.bookings.reasons.${r}`) })) + const reason = reasonText(choice, options, other) return ( @@ -140,16 +141,8 @@ function DeclineDialog({ busy, error, onClose, onDecline }) { }>

{t('pos.online.rejectBody')}

-
- {[...REASONS, 'other'].map(r => ( - - ))} -
- {choice === 'other' && setOther(e.target.value)} maxLength={300} autoFocus aria-label={t('pos.online.reason')} />} + {error &&

{error}

}
diff --git a/terminal/src/apps/pos/OnlinePanel.jsx b/terminal/src/apps/pos/OnlinePanel.jsx index ff99c41..c911b9b 100644 --- a/terminal/src/apps/pos/OnlinePanel.jsx +++ b/terminal/src/apps/pos/OnlinePanel.jsx @@ -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 { errorMessage } from '@xenia/api' 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 { diffRows, finishWord as finishOf, kindOf, nextStep } from './logic/online' import { itemPayments, orderLines, orderSums, qtyLabel } from './logic/tables' @@ -190,7 +190,8 @@ function RejectDialog({ busy, error, onClose, onReject }) { const { t } = useTranslation('terminal') const [choice, setChoice] = useState(null) 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 ( @@ -201,18 +202,8 @@ function RejectDialog({ busy, error, onClose, onReject }) { }>

{t('pos.online.rejectBody')}

-
- {[...REASONS, 'other'].map(r => ( - - ))} -
- {choice === 'other' && ( - setOther(e.target.value)} maxLength={300} autoFocus aria-label={t('pos.online.reason')} data-testid="reason-text" /> - )} + {error &&

{error}

}
diff --git a/tests/e2e/waiter.mjs b/tests/e2e/waiter.mjs index 47e945f..29574f9 100644 --- a/tests/e2e/waiter.mjs +++ b/tests/e2e/waiter.mjs @@ -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') 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 ── 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') diff --git a/waiter_pwa/src/App.jsx b/waiter_pwa/src/App.jsx index b4dc8bb..9cd818d 100644 --- a/waiter_pwa/src/App.jsx +++ b/waiter_pwa/src/App.jsx @@ -25,6 +25,7 @@ import ChatListPage from './pages/ChatListPage' import ChatThreadPage from './pages/ChatThreadPage' import ShiftOverviewPage from './pages/ShiftOverviewPage' import OrderLogPage from './pages/OrderLogPage' +import BookingsPage from './pages/BookingsPage' import { NotificationProvider } from './context/NotificationContext' import { LiveProvider } from './context/LiveContext' import ConnectivityBar from './components/ConnectivityBar' @@ -504,6 +505,7 @@ function Routed() { } /> } /> } /> + } /> } /> } /> diff --git a/waiter_pwa/src/components/AppShell.jsx b/waiter_pwa/src/components/AppShell.jsx index 76b8431..89b7bb0 100644 --- a/waiter_pwa/src/components/AppShell.jsx +++ b/waiter_pwa/src/components/AppShell.jsx @@ -275,6 +275,19 @@ const DRAWER_NAV_ITEMS = [ }, { ...NAV_REGISTRY.orders }, { ...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: ( + + + + + ), + }, { key: 'shift-overview', label: 'nav.shiftSummary', @@ -375,6 +388,10 @@ function SideDrawer({ open, onClose }) { const { t } = useTranslation('waiter') const navigate = useNavigate() 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 { activeZoneTab, setActiveZoneTab } = useTableViewStore() @@ -425,7 +442,7 @@ function SideDrawer({ open, onClose }) {
{t('shell.navigation')}
- {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 active = item.key === 'standalone' ? isStandaloneActive diff --git a/waiter_pwa/src/main.jsx b/waiter_pwa/src/main.jsx index 40b08a0..573e0cf 100644 --- a/waiter_pwa/src/main.jsx +++ b/waiter_pwa/src/main.jsx @@ -1,6 +1,6 @@ import { StrictMode } from 'react' 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' // The theme before anything renders (no light flash on a dark phone): the user's light/dark diff --git a/waiter_pwa/src/pages/BookingsPage.jsx b/waiter_pwa/src/pages/BookingsPage.jsx new file mode 100644 index 0000000..78b6a97 --- /dev/null +++ b/waiter_pwa/src/pages/BookingsPage.jsx @@ -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 ( + +
+ {error &&

{error}

} + {!data && !error &&

{t('common.loading')}

} + {data && ( + <> +

{t('bookings.requests', { count: requested.length })}

+ {requested.length === 0 &&

{t('bookings.noRequests')}

} + {requested.map(b => ( + +
+ + +
+
+ ))} + +

{t('bookings.upcoming', { count: upcoming.length })}

+ {upcoming.length === 0 &&

{t('bookings.noUpcoming')}

} + {upcoming.map(b => ( + + run(b, 'arrive', { table_id: tableId })} + onCancel={status => run(b, 'cancel', { status })} /> + + ))} + + )} +
+ {declining && setDeclining(null)} onDecline={reason => run(declining, 'decline', { reason })} />} +
+ ) +} + +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 ( +
+
+ + {today ? t('bookings.today', { time: formatTime(b.reserved_for) }) : formatDateTime(b.reserved_for, 'datetimeShort')} + + {b.ref && {b.ref}} +
+
+ {b.guest_name} · {t('bookings.people', { count: b.party_size })} + {b.table_label && · {b.table_label}} +
+ {b.phone && {b.phone}} + {b.note &&
{b.note}
} + {b.lines?.length > 0 && ( +
+
+ {b.order_id ? t('bookings.foodSent') : b.fire_at ? t('bookings.foodAt', { time: formatTime(b.fire_at) }) : t('bookings.foodOnConfirm')} +
+ {b.lines.map((l, i) =>
{l.quantity}× {l.name}
)} +
{formatMoney(b.total)}
+
+ )} + {children} +
+ ) +} + +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 ( +
+ + +
+ + +
+
+ ) +} + +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 ( +
+
e.stopPropagation()} data-testid="decline-sheet"> +
+

{t('bookings.declineTitle', { name: booking.guest_name })}

+

{t('bookings.declineBody')}

+ +
+ + +
+
+
+ ) +}