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
@@ -0,0 +1,194 @@
// A table's order in the manager (plan step 6.9; replaces the v1 order page and its desktop
// ordering tab). Taken, changed, paid and closed by the phones' rules: lines go by id and the
// server prices them (4.4); paying asks cash or card; "Close" with unpaid lines either takes
// the payment first or, when the venue allows it (orders.close_with_unpaid), writes them off
// after saying so. `/orders/new?table=5` is a table without an order: the first "Send" opens it.
import { useState } from 'react'
import { useNavigate, useParams, useSearchParams } from 'react-router-dom'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import { ArrowLeft, Ban, CheckCheck, CreditCard, Printer } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog, EmptyState, Select, Spinner, cx } from '@xenia/ui'
import client from '../../api/client'
import { useLiveQuery } from '../../live/useLiveQuery'
import { useDuration } from '../overview/hooks'
import { tableName } from '../overview/overviewLogic'
import { Money, Pill } from '../overview/parts'
import AddItems from './AddItems'
import OrderLines from './OrderLines'
import OrderPeople from './OrderPeople'
import PayDialog from './PayDialog'
import { AuditList, PriceEventList } from './OrderHistory'
import { closeStep, totals, unpaidIds, venueRules } from './orderLogic'
const ORDER_EVENTS = ['order_updated', 'order_paid', 'order_closed', 'order_refunded', 'kds_order_updated', 'kds_item_updated']
const STATUS_TONE = { open: 'success', partially_paid: 'info', paid: 'accent', closed: 'neutral', cancelled: 'danger' }
const TABS = ['order', 'prices', 'history']
export default function OrderPage() {
const { orderId } = useParams()
const [params] = useSearchParams()
if (orderId === 'new') return <NewOrder tableId={Number(params.get('table')) || null} />
return <OrderView orderId={Number(orderId)} />
}
function useVenue() {
const { data } = useLiveQuery({ queryKey: ['settings'], queryFn: () => client.get('/api/settings/').then(r => r.data), staleTime: 60_000 })
return venueRules(data)
}
function Back() {
const { t } = useTranslation('manager')
const navigate = useNavigate()
return <Button size="sm" variant="ghost" icon={<ArrowLeft size={16} />} onClick={() => navigate('/tables')}>{t('orders.toTables')}</Button>
}
function NewOrder({ tableId }) {
const { t } = useTranslation('manager')
const navigate = useNavigate()
const qc = useQueryClient()
const { data: tables = [] } = useLiveQuery({ queryKey: ['tables'], queryFn: () => client.get('/api/tables/').then(r => r.data), events: ['table_list_changed'] })
const table = tables.find(x => x.id === tableId)
const open = async () => (await client.post('/api/orders/', { table_id: tableId, order_type: 'here' })).data.id
return (
<div className="h-full overflow-y-auto p-4 lg:p-6" data-testid="order-new">
<div className="max-w-6xl mx-auto grid gap-4">
<header className="flex flex-wrap items-center gap-3">
<Back />
<h1 className="text-title font-semibold text-ink">{t('orders.newTitle', { table: table ? tableName(table) : tableId ?? '' })}</h1>
<Pill tone="neutral">{t('overview.tableState.free')}</Pill>
</header>
<p className="text-label text-ink-2">{t('orders.newHint')}</p>
<AddItems orderId={null} openOrder={open} onSent={id => {
qc.invalidateQueries({ queryKey: ['orders-active'] })
navigate(`/orders/${id}`, { replace: true })
}} />
</div>
</div>
)
}
function OrderView({ orderId }) {
const { t } = useTranslation('manager')
const { formatTime, formatMoney } = useFormat()
const since = useDuration()
const navigate = useNavigate()
const qc = useQueryClient()
const venue = useVenue()
const [tab, setTab] = useState('order')
const [paying, setPaying] = useState(null) // { ids, amount, thenClose, after }
const [confirm, setConfirm] = useState(null) // 'close' | 'writeOff' | 'cancel'
const [printerId, setPrinterId] = useState('')
const { data: order, isPending, error } = useLiveQuery({
queryKey: ['order', orderId], queryFn: () => client.get(`/api/orders/${orderId}`).then(r => r.data), events: ORDER_EVENTS,
})
const { data: staff = [] } = useLiveQuery({ queryKey: ['waiters'], queryFn: () => client.get('/api/waiters/').then(r => r.data), staleTime: 60_000 })
const { data: printers = [] } = useLiveQuery({ queryKey: ['printers'], queryFn: () => client.get('/api/system/printers').then(r => r.data), staleTime: 60_000 })
const { data: priceEvents = [] } = useLiveQuery({
queryKey: ['price-events', orderId], queryFn: () => client.get(`/api/pricing/events/order/${orderId}`).then(r => r.data), events: ['order_updated'],
})
const refresh = () => {
qc.invalidateQueries({ queryKey: ['order', orderId] })
qc.invalidateQueries({ queryKey: ['price-events', orderId] })
qc.invalidateQueries({ queryKey: ['orders-active'] })
}
const onError = err => toast.error(errorMessage(err, t))
const close = useMutation({ mutationFn: () => client.post(`/api/orders/${orderId}/close`), onSuccess: () => { setConfirm(null); toast.success(t('orders.closed')); refresh() }, onError })
const cancel = useMutation({
mutationFn: print => client.delete(`/api/orders/${orderId}`, { params: { print_cancellation: print } }),
onSuccess: () => { setConfirm(null); toast.success(t('orders.cancelled')); refresh(); navigate('/tables') }, onError,
})
const print = useMutation({ mutationFn: pid => client.post(`/api/orders/${orderId}/print`, { printer_id: pid }), onSuccess: () => toast.success(t('orders.printing')), onError })
if (isPending) return <div className="h-full grid place-items-center"><Spinner /></div>
if (error || !order) {
return <div className="p-6 grid gap-3 justify-items-center"><EmptyState title={t('orders.notFound')} description={error ? errorMessage(error, t) : undefined} /><Back /></div>
}
const editable = ['open', 'partially_paid', 'paid'].includes(order.status)
const sums = totals(order)
const due = unpaidIds(order)
function startClose() {
const step = closeStep(order, venue.closeWithUnpaid)
if (step === 'payFirst') setPaying({ ids: due, amount: sums.due, thenClose: true })
else setConfirm(step)
}
return (
<div className="h-full overflow-y-auto p-4 lg:p-6" data-testid="order-page" data-status={order.status}>
<div className="max-w-6xl mx-auto grid gap-4">
<header className="flex flex-wrap items-center gap-3">
<Back />
<h1 className="text-title font-semibold text-ink">{order.table_name ? t('orders.title', { table: order.table_name }) : t('orders.titleNoTable', { id: order.id })}</h1>
<Pill tone={STATUS_TONE[order.status] ?? 'neutral'} data-testid="order-status">{t(`overview.orderStatus.${order.status}`, { defaultValue: order.status })}</Pill>
<span className="text-label text-ink-2">{t('overview.order.sub', { id: order.id, time: formatTime(order.opened_at), since: since(order.opened_at, order.closed_at ? new Date(order.closed_at).getTime() : undefined) })}</span>
<span className="flex-1" />
<span className="flex items-baseline gap-4 text-label text-ink-2">
{sums.paid > 0 && <span>{t('orders.paid')} <Money value={sums.paid} className="font-semibold text-success-ink" /></span>}
{sums.paid > 0 && sums.due > 0 && <span>{t('orders.due')} <Money value={sums.due} className="font-semibold text-ink" data-testid="order-due" /></span>}
<span>{t('orders.total')} <Money value={sums.total} className="text-title font-semibold text-ink" data-testid="order-total" /></span>
</span>
</header>
<div className="flex flex-wrap items-center gap-2">
<span className="flex gap-1" role="tablist">
{TABS.map(k => <Button key={k} size="sm" variant={tab === k ? 'primary' : 'ghost'} role="tab" aria-selected={tab === k} onClick={() => setTab(k)} data-testid={`order-tab-${k}`}>{t(`orders.tabs.${k}`)}</Button>)}
</span>
<span className="flex-1" />
{editable && due.length > 0 && <Button icon={<CreditCard size={16} />} onClick={() => setPaying({ ids: due, amount: sums.due })} data-testid="order-pay-all">{t('orders.payAll')}</Button>}
{editable && <Button variant="secondary" icon={<CheckCheck size={16} />} onClick={startClose} data-testid="order-close">{t('orders.close')}</Button>}
{editable && <Button variant="danger" icon={<Ban size={16} />} onClick={() => setConfirm('cancel')} data-testid="order-cancel">{t('orders.cancel')}</Button>}
{printers.length > 0 && (
<span className="flex items-center gap-2">
<Select size="sm" value={printerId} onChange={e => setPrinterId(e.target.value)} aria-label={t('orders.printer')}
placeholder={t('orders.printer')} options={printers.map(p => ({ value: String(p.id), label: p.name }))} />
<Button size="sm" variant="secondary" icon={<Printer size={16} />} disabled={!printerId} loading={print.isPending} onClick={() => print.mutate(Number(printerId))}>{t('orders.print')}</Button>
</span>
)}
</div>
{tab === 'order' && (
<div className={cx('grid gap-4 items-start', editable && 'lg:grid-cols-[minmax(0,1fr)_minmax(0,1.1fr)]')}>
<div className="grid gap-4 min-w-0">
<OrderLines order={order} open={editable} priceEvents={priceEvents} onChanged={refresh}
onPay={(ids, amount, after) => setPaying({ ids, amount, after })} />
<OrderPeople order={order} open={editable} staff={staff} onChanged={refresh} />
</div>
{editable && <AddItems orderId={order.id} onSent={refresh} />}
</div>
)}
{tab === 'prices' && <section className="rounded-card border border-line bg-surface shadow-raised overflow-hidden"><PriceEventList events={priceEvents} /></section>}
{tab === 'history' && <section className="rounded-card border border-line bg-surface shadow-raised overflow-hidden"><AuditList order={order} /></section>}
</div>
{paying && <PayDialog orderId={order.id} itemIds={paying.ids} amount={paying.amount} card={venue.card} thenClose={!!paying.thenClose}
onClose={() => setPaying(null)}
onDone={() => { toast.success(paying.thenClose ? t('orders.closed') : t('orders.pay.done')); paying.after?.(); setPaying(null); refresh() }} />}
{(confirm === 'close' || confirm === 'writeOff') && (
<Dialog open size="sm" onClose={() => setConfirm(null)} title={t(confirm === 'close' ? 'orders.confirmClose' : 'orders.writeOffTitle')}
description={confirm === 'writeOff' ? t('orders.writeOffBody', { count: due.length, amount: formatMoney(sums.due) }) : undefined}
footer={<>
<Button variant="secondary" onClick={() => setConfirm(null)}>{t('orders.back')}</Button>
{confirm === 'writeOff' && <Button variant="secondary" onClick={() => { setConfirm(null); setPaying({ ids: due, amount: sums.due, thenClose: true }) }}>{t('orders.payAndClose')}</Button>}
<Button variant={confirm === 'writeOff' ? 'danger' : 'primary'} loading={close.isPending} onClick={() => close.mutate()} data-testid="order-close-confirm">
{confirm === 'writeOff' ? t('orders.writeOff') : t('orders.close')}
</Button>
</>} />
)}
{confirm === 'cancel' && (
<Dialog open size="sm" onClose={() => setConfirm(null)} title={t('orders.cancelTitle')} description={t('orders.cancelBody')}
footer={<>
<Button variant="secondary" onClick={() => setConfirm(null)}>{t('orders.back')}</Button>
<Button variant="secondary" loading={cancel.isPending && cancel.variables === false} onClick={() => cancel.mutate(false)} data-testid="order-cancel-confirm">{t('orders.lines.cancelNoPrint')}</Button>
<Button variant="danger" icon={<Printer size={16} />} loading={cancel.isPending && cancel.variables === true} onClick={() => cancel.mutate(true)}>{t('orders.lines.cancelPrint')}</Button>
</>} />
)}
</div>
)
}