diff --git a/local_backend/routers/tables.py b/local_backend/routers/tables.py index b0843e9..8a326ef 100644 --- a/local_backend/routers/tables.py +++ b/local_backend/routers/tables.py @@ -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]} diff --git a/local_backend/tests/test_table_history.py b/local_backend/tests/test_table_history.py new file mode 100644 index 0000000..d15e101 --- /dev/null +++ b/local_backend/tests/test_table_history.py @@ -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")) diff --git a/packages/i18n/locales/el/waiter.json b/packages/i18n/locales/el/waiter.json index ce40985..8a75e43 100644 --- a/packages/i18n/locales/el/waiter.json +++ b/packages/i18n/locales/el/waiter.json @@ -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}} ημέρες" } } diff --git a/packages/i18n/locales/en/waiter.json b/packages/i18n/locales/en/waiter.json index 15e318c..e6ce030 100644 --- a/packages/i18n/locales/en/waiter.json +++ b/packages/i18n/locales/en/waiter.json @@ -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" } } diff --git a/tests/e2e/waiter.mjs b/tests/e2e/waiter.mjs index 373413f..3125448 100644 --- a/tests/e2e/waiter.mjs +++ b/tests/e2e/waiter.mjs @@ -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`) diff --git a/waiter_pwa/src/components/TableHistory.jsx b/waiter_pwa/src/components/TableHistory.jsx new file mode 100644 index 0000000..384a06a --- /dev/null +++ b/waiter_pwa/src/components/TableHistory.jsx @@ -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: