feat(waiter): a table's earlier orders (platform-v2 step 4.7)

- GET /api/tables/{id}/history: the table's closed / cancelled orders, newest first,
  for the waiters of its zone (ordering.orders.open), never older than the history
  module's history_days (free tier 31, D-6), module.disabled when history is off;
  each order with times, total (cancelled items left out), people and items.
- Waiter: a History tab on the table (and "This table's earlier orders" on a free
  table); orders expand to their items; the last answer is kept on the phone and
  shown offline, marked as saved; the plan's day limit is shown.
- Tests: test_table_history.py (4), waiter e2e +2.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-17 04:45:31 +02:00
co-authored by Claude Opus 5.5
parent f8d91e7fae
commit 9e1912bce0
7 changed files with 306 additions and 2 deletions
+66
View File
@@ -261,3 +261,69 @@ def update_floorplan(table_id: int, body: TableFloorplanUpdate, db: Session = De
db.commit()
db.refresh(table)
return table
# ── A table's earlier orders (plan step 4.7) ──────────────────────────────────
def _table_in_zones(db: Session, user: User, table: Table) -> bool:
"""The waiter app's table rule: managers every table, staff the tables of their zones
(a zone row without a group = every zone)."""
if holds(user, "core.dashboard.access"):
return True
zones = db.query(WaiterZone).filter(WaiterZone.waiter_id == user.id).all()
return any(z.group_id is None or z.group_id == table.group_id for z in zones)
from core.access.deps import require as _require # noqa: E402
from core.modules.state import module_required as _module_required # noqa: E402
@router.get("/{table_id}/history", dependencies=[Depends(_module_required("history"))])
def table_history(table_id: int, limit: int = 20, db: Session = Depends(get_db),
user: User = Depends(_require("ordering.orders.open"))):
"""The table's finished orders (closed or cancelled), newest first: what the table had
earlier today. Never older than the `history` module allows (free tier: 31 days, D-6);
`history_days` says how far back that is (null = no limit)."""
from sqlalchemy.orm import selectinload
from core.errors import XeniaError
from core.modules.entitlements import history_floor, limit as module_limit
table = db.get(Table, table_id)
if table is None:
raise XeniaError("pos.table_not_found", table_id=table_id)
if not _table_in_zones(db, user, table):
raise XeniaError("pos.table_not_yours", table=table.label or f"T{table.number}")
q = (db.query(Order).filter(Order.table_id == table_id, Order.status.in_(("closed", "cancelled")))
.options(selectinload(Order.items), selectinload(Order.waiters)))
floor = history_floor("history")
if floor is not None:
q = q.filter(Order.opened_at >= floor)
orders = q.order_by(Order.opened_at.desc()).limit(max(1, min(limit, 100))).all()
people_ids = {w.waiter_id for o in orders for w in o.waiters}
people = {u.id: u.nickname or u.full_name or u.username
for u in db.query(User).filter(User.id.in_(people_ids)).all()} if people_ids else {}
def iso(dt):
return None if dt is None else (dt.isoformat() + "Z" if dt.tzinfo is None else dt.isoformat())
def item_out(i):
import json as _json
try:
opts = [o.get("name") for o in _json.loads(i.selected_options or "[]") if isinstance(o, dict) and o.get("name")]
except ValueError:
opts = []
unit = (i.unit_price or 0.0) + (i.price_adjustment or 0.0)
return {"id": i.id, "name": i.product_name, "quantity": i.quantity, "unit_price": round(unit, 2),
"total": round(unit * i.quantity, 2), "status": i.status, "options": opts, "notes": i.notes}
def order_out(o):
live = [i for i in o.items if i.status != "cancelled"]
return {
"id": o.id, "status": o.status, "opened_at": iso(o.opened_at), "closed_at": iso(o.closed_at),
"total": round(sum(((i.unit_price or 0.0) + (i.price_adjustment or 0.0)) * i.quantity for i in live), 2),
"customer_count": o.customer_count,
"people": [people[w.waiter_id] for w in o.waiters if w.waiter_id in people],
"items": [item_out(i) for i in o.items],
}
return {"table_id": table_id, "history_days": module_limit("history", "history_days"),
"orders": [order_out(o) for o in orders]}
+89
View File
@@ -0,0 +1,89 @@
"""A table's earlier orders on the waiter's phone (plan step 4.7).
GET /api/tables/{id}/history: the table's finished orders (closed / cancelled), newest
first, for the waiters of its zone, never older than the `history` module allows (free
tier 31 days, D-6), and refused when the module is off.
"""
from datetime import timedelta
import pytest
from core.timeutil import utcnow
from tests.test_entitlements import install
@pytest.fixture
def floor(db, make_user, login):
from models.product import Category, Product
from models.table import Table, TableGroup
from models.user import WaiterZone
terrace, inside = TableGroup(name="Terrace"), TableGroup(name="Inside")
db.add_all([terrace, inside])
db.flush()
t1, t3 = Table(number=1, group_id=terrace.id), Table(number=3, group_id=inside.id)
cat = Category(name="Drinks")
db.add_all([t1, t3, cat])
db.flush()
coffee = Product(name="Freddo", base_price=3.0, primary_category_id=cat.id)
db.add(coffee)
maria = make_user(role="waiter", nickname="Maria")
db.add(WaiterZone(waiter_id=maria.id, group_id=terrace.id))
db.commit()
return {"t1": t1, "t3": t3, "coffee": coffee, "maria": maria, "h": login(maria, "waiter")}
def order(db, f, table, status, opened_ago, items=((2, "paid"),), closed=True):
from models.order import Order, OrderItem, OrderWaiter
o = Order(table_id=table.id, opened_by=f["maria"].id, status=status, order_type="here",
opened_at=utcnow() - opened_ago, closed_at=(utcnow() - opened_ago + timedelta(minutes=40)) if closed else None)
db.add(o)
db.flush()
db.add(OrderWaiter(order_id=o.id, waiter_id=f["maria"].id))
for qty, st in items:
db.add(OrderItem(order_id=o.id, product_id=f["coffee"].id, product_name="Freddo", added_by=f["maria"].id,
quantity=qty, unit_price=3.0, status=st))
db.commit()
return o
def test_the_tables_earlier_orders_newest_first(client, db, floor):
f = floor
lunch = order(db, f, f["t1"], "closed", timedelta(hours=5), items=((2, "paid"), (1, "cancelled")))
coffee = order(db, f, f["t1"], "closed", timedelta(hours=2))
voided = order(db, f, f["t1"], "cancelled", timedelta(hours=1), items=((1, "cancelled"),))
order(db, f, f["t1"], "open", timedelta(minutes=10), closed=False) # the open one isn't history
order(db, f, f["t3"], "closed", timedelta(hours=1)) # another table
r = client.get(f"/api/tables/{f['t1'].id}/history", headers=f["h"])
assert r.status_code == 200, r.text
data = r.json()
assert [o["id"] for o in data["orders"]] == [voided.id, coffee.id, lunch.id]
first = data["orders"][2]
assert first["total"] == 6.0 and first["people"] == ["Maria"] and first["status"] == "closed"
assert [(i["name"], i["quantity"], i["status"]) for i in first["items"]] == [("Freddo", 2, "paid"), ("Freddo", 1, "cancelled")]
assert data["orders"][0]["total"] == 0.0 and data["orders"][0]["status"] == "cancelled"
def test_only_the_waiters_of_the_tables_zone(client, db, floor):
r = client.get(f"/api/tables/{floor['t3'].id}/history", headers=floor["h"])
assert r.status_code == 403 and r.json()["error"]["code"] == "pos.table_not_yours"
def test_free_tier_shows_only_its_days(client, db, floor):
f = floor
old = order(db, f, f["t1"], "closed", timedelta(days=40))
recent = order(db, f, f["t1"], "closed", timedelta(days=3))
assert [o["id"] for o in client.get(f"/api/tables/{f['t1'].id}/history", headers=f["h"]).json()["orders"]] == [recent.id, old.id]
install({"ordering": {}, "history": {"limits": {"history_days": 31}}})
data = client.get(f"/api/tables/{f['t1'].id}/history", headers=f["h"]).json()
assert [o["id"] for o in data["orders"]] == [recent.id] and data["history_days"] == 31
def test_history_off_means_no_history(client, db, floor, owner_h):
assert client.put("/api/platform/modules/history", headers=owner_h, json={"enabled": False}).status_code == 200
r = client.get(f"/api/tables/{floor['t1'].id}/history", headers=floor["h"])
assert r.status_code == 403 and r.json()["error"]["code"] == "module.disabled"
@pytest.fixture
def owner_h(make_user, login):
return login(make_user(role="owner"))
+10
View File
@@ -769,5 +769,15 @@
"tables_other": "Τραπέζια: {{tables}}",
"more_one": "+{{count}} ακόμα μήνυμα",
"more_other": "+{{count}} ακόμα μηνύματα"
},
"history": {
"tab": "Ιστορικό",
"earlier": "Προηγούμενες παραγγελίες τραπεζιού",
"failed": "Σφάλμα φόρτωσης ιστορικού",
"cached": "Αποθηκευμένο στο κινητό στις {{time}} (χωρίς σύνδεση)",
"none": "Δεν υπάρχουν προηγούμενες παραγγελίες",
"cancelled": "ΑΚΥΡΩΜΕΝΗ",
"limit_one": "Το πακέτο σας δείχνει την τελευταία {{count}} ημέρα",
"limit_other": "Το πακέτο σας δείχνει τις τελευταίες {{count}} ημέρες"
}
}
+10
View File
@@ -769,5 +769,15 @@
"tables_other": "Tables: {{tables}}",
"more_one": "+{{count}} more message",
"more_other": "+{{count}} more messages"
},
"history": {
"tab": "History",
"earlier": "This table's earlier orders",
"failed": "Couldn't load the history",
"cached": "Saved on this phone at {{time}} (offline)",
"none": "No earlier orders",
"cancelled": "CANCELLED",
"limit_one": "Your plan shows the last {{count}} day",
"limit_other": "Your plan shows the last {{count}} days"
}
}
+14 -1
View File
@@ -15,7 +15,7 @@ const vite = await startViteNative({ port: 5181, backendUrl: backend.url })
const APP = 'http://localhost:5181'
const TOKEN_KEY = 'xenia:dev:token'
const browser = await chromium.launch(BROWSER_CHANNEL ? { channel: BROWSER_CHANNEL } : {})
const r = reporter('waiter: sign-in v2, lock, approvals (4.2), keys (4.3), server prices (4.4), languages (4.5)')
const r = reporter('waiter: sign-in v2, lock, approvals (4.2), keys (4.3), server prices (4.4), languages (4.5), table history (4.7)')
const errors = []
let failures = 0
@@ -244,6 +244,19 @@ try {
for (const o of [sent, synced]) if (o) await api('DELETE', `/api/orders/${o.id}`, { token: boss }).catch(() => {})
await a.goto(`${APP}/tables`)
// ── 4.7: a table's earlier orders (the order sent above was cancelled: it is history now) ──
await a.goto(`${APP}/tables/${t4.id}`)
await a.getByTestId('history-open').click({ timeout: 10_000 })
const histShown = await shown(a, 'history-order', 10_000)
const histText = await a.getByTestId('table-history').innerText().catch(() => '')
r.check('4.7: a free table shows its earlier orders (the cancelled one, with its total)', histShown && histText.includes(`#${sent?.id}`), histText.replace(/\s+/g, ' ').slice(0, 160))
await ctxA.setOffline(true)
await a.getByTestId('history-open').click()
await a.getByTestId('history-open').click()
r.check('4.7: offline the saved history shows, marked as saved', await shown(a, 'history-cached', 10_000) && await a.getByTestId('history-order').count() > 0)
await ctxA.setOffline(false)
await a.goto(`${APP}/tables`)
// ── 4.5: English first; the language switch in the user menu, saved to the person ──
const navText = () => a.locator('body').innerText()
await a.goto(`${APP}/tables`)
@@ -0,0 +1,90 @@
import { useEffect, useState } from 'react'
import { useFormat, useTranslation } from '@xenia/i18n'
import client from '../api/client'
import { apiError } from '../api/errors'
import db from '../db/posdb'
// A table's earlier orders (plan step 4.7): GET /api/tables/{id}/history, never older than
// the venue's `history` module allows. The last answer is kept on the phone (`kv`
// history:<table id>) and shown while offline, marked as saved.
const CACHE = id => `history:${id}`
export default function TableHistory({ tableId }) {
const { t } = useTranslation('waiter')
const { formatTime, formatDate, formatMoney } = useFormat()
const [state, setState] = useState({ loading: true, data: null, cached: false, error: '' })
const [open, setOpen] = useState(null)
useEffect(() => {
let alive = true
client.get(`/api/tables/${tableId}/history`)
.then(async r => {
try { await db.kv.put({ key: CACHE(tableId), value: { ...r.data, saved_at: new Date().toISOString() } }) } catch { /* storage full: still shown */ }
if (alive) setState({ loading: false, data: r.data, cached: false, error: '' })
})
.catch(async err => {
const saved = await db.kv.get(CACHE(tableId)).then(row => row?.value ?? null).catch(() => null)
if (alive) setState({ loading: false, data: saved, cached: !!saved, error: saved ? '' : apiError(err, t('history.failed')) })
})
return () => { alive = false }
}, [tableId]) // eslint-disable-line react-hooks/exhaustive-deps
if (state.loading) return <p style={{ textAlign: 'center', color: 'var(--muted)', padding: 24 }}>{t('common.loading')}</p>
if (state.error) return <p data-testid="history-error" style={{ textAlign: 'center', color: 'var(--danger)', padding: 24, fontSize: 13 }}>{state.error}</p>
const orders = state.data?.orders ?? []
const days = state.data?.history_days
return (
<div data-testid="table-history" style={{ display: 'flex', flexDirection: 'column', gap: 8, padding: '10px 12px 24px' }}>
{state.cached && (
<div data-testid="history-cached" style={{ fontSize: 12, color: 'var(--muted)', textAlign: 'center' }}>
{t('history.cached', { time: formatTime(state.data.saved_at) })}
</div>
)}
{orders.length === 0 && (
<p style={{ textAlign: 'center', color: 'var(--muted)', padding: 24, fontSize: 14 }}>{t('history.none')}</p>
)}
{orders.map(o => {
const expanded = open === o.id
return (
<div key={o.id} data-testid="history-order" style={{ background: 'var(--bg2)', border: '1px solid var(--border)', borderRadius: 12, overflow: 'hidden' }}>
<button onClick={() => setOpen(expanded ? null : o.id)} style={{
width: '100%', display: 'flex', alignItems: 'center', gap: 10, padding: '12px 14px',
background: 'none', border: 'none', cursor: 'pointer', textAlign: 'left', color: 'var(--text)',
}}>
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{ fontSize: 14, fontWeight: 700 }}>
{formatDate(o.opened_at, 'dateShort')} · {formatTime(o.opened_at)}{o.closed_at ? `–${formatTime(o.closed_at)}` : ''}
{o.status === 'cancelled' && <span style={{ marginLeft: 8, fontSize: 11, color: 'var(--danger)' }}>{t('history.cancelled')}</span>}
</div>
<div style={{ fontSize: 12, color: 'var(--muted)', marginTop: 2 }}>
#{o.id} · {t('orders.items', { count: o.items.length })}{o.people.length ? ` · ${o.people.join(', ')}` : ''}
</div>
</div>
<span style={{ fontSize: 15, fontWeight: 800, fontVariantNumeric: 'tabular-nums' }}>{formatMoney(o.total)}</span>
</button>
{expanded && (
<div style={{ borderTop: '1px solid var(--border)', padding: '8px 14px 12px', display: 'flex', flexDirection: 'column', gap: 6 }}>
{o.items.map(i => (
<div key={i.id} style={{ display: 'flex', gap: 8, fontSize: 13, opacity: i.status === 'cancelled' ? 0.5 : 1 }}>
<span style={{ fontWeight: 700, minWidth: 28 }}>×{i.quantity}</span>
<span style={{ flex: 1, textDecoration: i.status === 'cancelled' ? 'line-through' : 'none' }}>
{i.name}
{i.options.length > 0 && <span style={{ color: 'var(--muted)' }}> · {i.options.join(', ')}</span>}
</span>
<span style={{ fontVariantNumeric: 'tabular-nums' }}>{formatMoney(i.total)}</span>
</div>
))}
</div>
)}
</div>
)
})}
{days != null && (
<div data-testid="history-limit" style={{ fontSize: 11, color: 'var(--muted)', textAlign: 'center', marginTop: 4 }}>
{t('history.limit', { count: days })}
</div>
)}
</div>
)
}
+27 -1
View File
@@ -1,7 +1,8 @@
import { useEffect, useState, useRef } from 'react'
import { useNavigate, useParams, useSearchParams } from 'react-router-dom'
import { useAllowed, useCan } from '@xenia/access'
import { useAllowed, useCan, useModule } from '@xenia/access'
import OrderSummary from '../components/OrderSummary'
import TableHistory from '../components/TableHistory'
import useConnectionStore from '../store/connectionStore'
import client from '../api/client'
import { apiError } from '../api/errors'
@@ -1079,6 +1080,8 @@ export default function TableDetailPage() {
// Tab: 'active' | 'paid'
const [activeTab, setActiveTab] = useState('active')
const historyOn = useModule('history') // 4.7: a table's earlier orders
const [showHistory, setShowHistory] = useState(false)
// Actions sheet state
const [showActions, setShowActions] = useState(false)
@@ -1702,6 +1705,12 @@ export default function TableDetailPage() {
<button className="btn btn--primary btn--lg" onClick={openOrder}>
{t('detail.openOrder')}
</button>
{historyOn && (
<button className="btn btn--secondary" data-testid="history-open" style={{ marginTop: 12 }} onClick={() => setShowHistory(s => !s)}>
{t('history.earlier')}
</button>
)}
{historyOn && showHistory && <div style={{ width: '100%', maxHeight: '50vh', overflowY: 'auto' }}><TableHistory tableId={Number(tableId)} /></div>}
</div>
)}
@@ -1780,6 +1789,21 @@ export default function TableDetailPage() {
}}>{paidItems.length}</span>
)}
</button>
{historyOn && !isStandalone && (
<button
data-testid="tab-history"
onClick={() => setActiveTab('history')}
style={{
flex: 1, padding: '9px 0', border: 'none', cursor: 'pointer',
fontWeight: 700, fontSize: 13,
background: activeTab === 'history' ? 'var(--bg3)' : 'transparent',
color: activeTab === 'history' ? 'var(--text)' : 'var(--muted)',
transition: 'background 0.15s',
}}
>
{t('history.tab')}
</button>
)}
</div>
{/* Merge view button */}
@@ -1804,6 +1828,8 @@ export default function TableDetailPage() {
)}
</div>
{activeTab === 'history' && <TableHistory tableId={Number(tableId)} />}
{activeTab === 'active' && (
<>
<OrderSummary