diff --git a/docs/README.md b/docs/README.md index 81df038..f140008 100644 --- a/docs/README.md +++ b/docs/README.md @@ -44,6 +44,7 @@ The manager calls the API **same-origin, with relative paths**. The waiter app r | `local_backend/services/refunds.py` | Refunds: their own records (`models/refund.py`), never edits of the paid items; shift / day totals subtract them | | `local_backend/services/system_products.py`, `services/online_check.py` | Lines the system adds itself (phase 3S): the delivery fee is an order line whose product has `system_key` and `lifecycle_status = "system"` (never on a menu or in the catalogue, never added by hand, added printed + served so the kitchen never sees it; paid, counted, receipted and refunded like any line). The site's own price check of a pulled online order (`orders.online_price_diff`): shown, never applied — the customer pays the cloud's prices | | `local_backend/services/online_reservations.py` | Table bookings from the online ordering app (phase 3S): stored as `Reservation` rows (`requested` → `pending` confirmed / `declined`; `arrived`, `cancelled`, `no_show`), food ordered ahead kept on the booking (`items_json`) and turned into an order **only at the fire time** (`fire_worker`, a connect_orders module worker; needs an open business day) or on early arrival. Every step mirrors the cloud status. The counter's Online → Bookings and `/api/connect/bookings/*` use it; the reservations router delegates online bookings to it | +| `local_backend/services/table_qr.py`, `services/qr_orders.py` | The QR menu at the table (phase 3S): every active table has a random `qr_token`; the menu snapshot carries only its sha256 (`qr`), so the cloud can check a code but never make one. A new code (rotate) kills the printed one at the next push (`/api/tables` and `/api/connect/qr` are in `MENU_PATHS`). A QR order with a valid table goes straight onto the table's open order (or a new one), to the kitchen, with a `qr_order` message to the table's waiters; the audit row `QR_ORDER` (note = the cloud ref) keeps repeats out. Manager page `/online/qr` | | `local_backend/routers/ws.py` | Real-time event stream (seq + cursor replay) | | `waiter_pwa/src/config/server.js` | **Where the backend is**: active venue, `apiBase()`, `wsUrl()`, `assetUrl()`, `storageKey()`, `dbName()`, `deliveryMode()` | | `waiter_pwa/android/`, `capacitor.config.json` | Native Android app (Capacitor 8). See "Native Android app" below | diff --git a/local_backend/core/i18n/el.json b/local_backend/core/i18n/el.json index 3a15b13..1e04c81 100644 --- a/local_backend/core/i18n/el.json +++ b/local_backend/core/i18n/el.json @@ -93,5 +93,9 @@ }, "system_product": { "delivery_fee": "Μεταφορικά" + }, + "qr": { + "order_message": "Τραπέζι {table}: νέα παραγγελία από το QR μενού ({count} τεμ.), στάλθηκε στην κουζίνα.", + "sender": "QR μενού" } } diff --git a/local_backend/core/i18n/en.json b/local_backend/core/i18n/en.json index 4be6915..59db0ca 100644 --- a/local_backend/core/i18n/en.json +++ b/local_backend/core/i18n/en.json @@ -93,5 +93,9 @@ }, "system_product": { "delivery_fee": "Delivery fee" + }, + "qr": { + "order_message": "Table {table}: new order from the QR menu ({count} items), sent to the kitchen.", + "sender": "QR menu" } } diff --git a/local_backend/migrations/versions/0021_table_qr_token.py b/local_backend/migrations/versions/0021_table_qr_token.py new file mode 100644 index 0000000..cae3baa --- /dev/null +++ b/local_backend/migrations/versions/0021_table_qr_token.py @@ -0,0 +1,26 @@ +"""tables: qr_token (the QR menu at the table, plan phase 3S, S.7) + +Revision ID: 0021_table_qr_token +Revises: 0020_online_reservations +Create Date: 2026-11-16 23:30:00 +""" +from alembic import op +import sqlalchemy as sa + + +revision = '0021_table_qr_token' +down_revision = '0020_online_reservations' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + with op.batch_alter_table('tables', schema=None) as batch_op: + batch_op.add_column(sa.Column('qr_token', sa.String(), nullable=True)) + batch_op.create_unique_constraint('uq_tables_qr_token', ['qr_token']) + + +def downgrade() -> None: + with op.batch_alter_table('tables', schema=None) as batch_op: + batch_op.drop_constraint('uq_tables_qr_token', type_='unique') + batch_op.drop_column('qr_token') diff --git a/local_backend/models/table.py b/local_backend/models/table.py index dfb6c9e..d5878a1 100644 --- a/local_backend/models/table.py +++ b/local_backend/models/table.py @@ -27,6 +27,9 @@ class Table(Base): seat_count = Column(Integer, nullable=True) floor_x = Column(Float, nullable=True) floor_y = Column(Float, nullable=True) + # the table's QR code (phase 3S, S.7): a random token in the QR menu link; the cloud gets + # only its sha256 (services/table_qr.py). A new token makes the printed code useless. + qr_token = Column(String, nullable=True, unique=True) group = relationship("TableGroup", back_populates="tables") orders = relationship("Order", back_populates="table") diff --git a/local_backend/modules/connect_menu/manifest.py b/local_backend/modules/connect_menu/manifest.py index a9632cb..54a9f04 100644 --- a/local_backend/modules/connect_menu/manifest.py +++ b/local_backend/modules/connect_menu/manifest.py @@ -1,5 +1,5 @@ """Module manifest — see core/modules/model.py and APPS_PLATFORM §4.""" -from core.modules.model import Module, Perm +from core.modules.model import Module, Mount, Perm, SettingDef MODULE = Module( key='connect_menu', @@ -10,5 +10,11 @@ MODULE = Module( permissions=( Perm('connect_menu.manage', 'Manage the QR menu', roles=('owner', 'store_manager')), ), + settings=( + SettingDef('connect_menu.table_ordering', 'false', 'The QR menu takes orders at the table (with a table QR code): "true" | "false" (read-only). Phase 3S, S.7.', type='bool'), + ), + routers=( + Mount('routers.qr_codes', '/api/connect/qr'), + ), workers=('services.cloud_sync:menu_push_worker',), ) diff --git a/local_backend/routers/qr_codes.py b/local_backend/routers/qr_codes.py new file mode 100644 index 0000000..a04434c --- /dev/null +++ b/local_backend/routers/qr_codes.py @@ -0,0 +1,73 @@ +"""The tables' QR codes (plan phase 3S, step S.7). Key: connect_menu.manage. + +GET /api/connect/qr {ordering, menu_url, tables: [{id, name, group, url}]} +PUT /api/connect/qr/ordering {on}: the QR menu takes orders at the table, or is read-only +POST /api/connect/qr/tables/{id}/rotate a new code for one table (the printed one stops working) +POST /api/connect/qr/rotate new codes for every table + +Each change pushes the menu soon (main.py middleware, MENU_PATHS), so the cloud knows the new +codes within seconds. services/table_qr.py has the rules. +""" +from __future__ import annotations + +from fastapi import APIRouter, Depends +from pydantic import BaseModel +from sqlalchemy.orm import Session + +from core.access.deps import require +from core.errors import XeniaError +from database import get_db +from services import table_qr + +router = APIRouter() +KEY = "connect_menu.manage" + + +class OrderingBody(BaseModel): + on: bool + + +def _out(db) -> dict: + from models.table import Table, TableGroup + table_qr.ensure_tokens(db) + db.commit() + groups = {g.id: g.name for g in db.query(TableGroup).all()} + tables = db.query(Table).filter(Table.is_active.is_(True)).order_by(Table.group_id, Table.number).all() + return { + "ordering": table_qr.ordering_on(db), + "menu_url": table_qr.menu_url(), + "tables": [{"id": t.id, "name": table_qr.label(t), "number": t.number, "group": groups.get(t.group_id), + "url": table_qr.menu_url(t.qr_token)} for t in tables], + } + + +@router.get("") +def qr_codes(db: Session = Depends(get_db), user=Depends(require(KEY))): + return _out(db) + + +@router.put("/ordering") +def set_ordering(body: OrderingBody, db: Session = Depends(get_db), user=Depends(require(KEY))): + table_qr.set_ordering(db, body.on) + db.commit() + return _out(db) + + +@router.post("/tables/{table_id}/rotate") +def rotate_one(table_id: int, db: Session = Depends(get_db), user=Depends(require(KEY))): + from models.table import Table + table = db.get(Table, table_id) + if table is None or not table.is_active: + raise XeniaError("reservation.table_unknown", table_id=table_id) + table_qr.rotate(db, table) + db.commit() + return _out(db) + + +@router.post("/rotate") +def rotate_all(db: Session = Depends(get_db), user=Depends(require(KEY))): + from models.table import Table + for t in db.query(Table).filter(Table.is_active.is_(True)).all(): + table_qr.rotate(db, t) + db.commit() + return _out(db) diff --git a/local_backend/services/cloud_sync.py b/local_backend/services/cloud_sync.py index 318a7dd..331e841 100644 --- a/local_backend/services/cloud_sync.py +++ b/local_backend/services/cloud_sync.py @@ -191,6 +191,7 @@ async def _sync_once(): "latest_version": data.get("latest_version"), "waiter_domain": data.get("waiter_domain"), "site_numeric_id": data.get("site_numeric_id"), + "apps_url": data.get("apps_url"), # the customer apps' address (S.7: table QR codes) "last_sync": utcnow().isoformat(), "sync_failed": False, }) @@ -296,8 +297,12 @@ def menu_snapshot(db) -> tuple[dict, list]: # engine (services/fees.py); the venue's time zone says what "22:00" and "Saturday" mean from core.timeutil import venue_tz from routers.fees import fees_payload, ordering_settings + # the tables' QR codes (S.7): only their tokens' hashes, and whether ordering at the table is on + from services import table_qr + qr = table_qr.snapshot(db) + db.commit() return {"categories": payload_categories, "fees": fees_payload(db), "ordering": ordering_settings(db), - "timezone": venue_tz().key}, all_products + "timezone": venue_tz().key, "qr": qr}, all_products async def _push_menu_snapshot(): @@ -347,7 +352,7 @@ def _with_table(cloud_order: dict): return f"Table {table}" + (f" · {notes}" if notes else "") -def store_online_orders(db, orders: list[dict], booked: list | None = None) -> dict: +def store_online_orders(db, orders: list[dict], booked: list | None = None, at_table: list | None = None) -> dict: """Store online orders as the cloud hands them over (GET /api/orders/pending/{site}): one local order each, waiting for acceptance (plan step 3.3d). An order already stored (an earlier pull whose "synced" mark didn't reach the cloud) isn't stored twice. @@ -359,11 +364,15 @@ def store_online_orders(db, orders: list[dict], booked: list | None = None) -> d (services/online_check.py: a difference is kept on the order and shown, never changed). S.6: table bookings ("reservation", "preorder") become Reservations waiting to be confirmed - (services/online_reservations.py); their ids go into `booked` (new ones) and the map.""" + (services/online_reservations.py); their ids go into `booked` (new ones) and the map. + + S.7: a QR-menu order with a table (from a valid table QR token) goes straight onto that + table's order (services/qr_orders.py); its cloud id goes into `at_table` (the puller tells + the cloud it reached the kitchen). Without a usable table it waits at the counter as before.""" from models.business_day import BusinessDay from models.order import Order, OrderItem from models.user import User - from services import online_check, online_reservations, system_products + from services import online_check, online_reservations, qr_orders, system_products # the opener is the first account with the manager dashboard (orders need one) system_user = db.query(User).filter(holders_filter("core.dashboard.access")).first() @@ -371,6 +380,23 @@ def store_online_orders(db, orders: list[dict], booked: list | None = None) -> d day = db.query(BusinessDay).filter(BusinessDay.status == "open").first() out = {} for cloud_order in orders: + if cloud_order.get("order_type") == "dine_in" and cloud_order.get("table_id"): + placed_in = qr_orders.already_placed(db, cloud_order) + if placed_in is not None: + out[cloud_order["id"]] = -placed_in + if at_table is not None: + at_table.append(cloud_order["id"]) # its "in the kitchen" may not have reached the cloud + continue + placed = qr_orders.place(db, cloud_order, opener_id) + if placed is not None: + db.commit() + qr_orders.after(db, placed, opener_id) + out[cloud_order["id"]] = placed["order"].id + if at_table is not None: + at_table.append(cloud_order["id"]) + logger.info("QR order %s placed on table %s (order %d)", cloud_order["public_ref"], placed["table"].id, placed["order"].id) + continue + db.rollback() if cloud_order.get("order_type") in ("reservation", "preorder"): seen = online_reservations.known(db, cloud_order["id"]) if seen is not None: @@ -517,9 +543,9 @@ async def _pull_pending_orders(): from services.sse_bus import broadcast_sync db = SessionLocal() - booked = [] + booked, at_table = [], [] try: - stored = store_online_orders(db, orders, booked) + stored = store_online_orders(db, orders, booked, at_table) except Exception as e: db.rollback() logger.error("Failed to process pulled orders: %s", e) @@ -527,7 +553,7 @@ async def _pull_pending_orders(): finally: db.close() - bookings = {o["id"] for o in orders if o.get("order_type") in ("reservation", "preorder")} + bookings = {o["id"] for o in orders if o.get("order_type") in ("reservation", "preorder")} | set(at_table) new_ids = [local_id for cloud_id, local_id in stored.items() if local_id > 0 and cloud_id not in bookings] if booked: broadcast_sync("reservation_requested", {"count": len(booked), "reservation_ids": booked}) @@ -543,6 +569,13 @@ async def _pull_pending_orders(): headers={"X-Site-ID": settings.SITE_ID, "X-Site-Key": settings.SITE_KEY}, json={"local_order_id": abs(local_id)}, ) + # QR orders put on their table went to the kitchen: the customer's page says so (S.7) + for cloud_id in at_table: + await client.patch( + f"{settings.CLOUD_URL}/api/orders/{cloud_id}/status", + headers={"X-Site-ID": settings.SITE_ID, "X-Site-Key": settings.SITE_KEY}, + json={"status": "accepted"}, + ) except Exception as e: logger.warning("Order pull failed: %s", e) @@ -675,7 +708,8 @@ async def _wait_for_site_id(max_seconds: int = 30) -> None: # not at the next 5-minute tick (phase 3S): request_menu_push() from any thread wakes the # worker; edits in a row within MENU_SETTLE_SECONDS become one push. MENU_SETTLE_SECONDS = 5 -MENU_PATHS = ("/api/products", "/api/pricing", "/api/connect/fees", "/api/data-transfer/import") +MENU_PATHS = ("/api/products", "/api/pricing", "/api/connect/fees", "/api/data-transfer/import", + "/api/connect/qr", "/api/tables") # S.7: the tables' QR codes travel with the menu _menu_wake: "asyncio.Event | None" = None _menu_loop = None diff --git a/local_backend/services/qr_orders.py b/local_backend/services/qr_orders.py new file mode 100644 index 0000000..59dd902 --- /dev/null +++ b/local_backend/services/qr_orders.py @@ -0,0 +1,99 @@ +"""Orders from the QR menu at the table (plan phase 3S, step S.7). + +The cloud takes a table order only with a valid table QR token (cloud services/qr.py) and +hands it over with the site's `table_id`. Here the items go straight onto the table's open +order (or a new one, eating in), at the cloud's prices, as if a waiter had added them: kitchen +tickets, the KDS, live on the waiters' phones and the counter. The table's waiters (those on the +order, else those whose zone covers the table) get a message. The audit log records it +(QR_ORDER, the order's reference), which also keeps a repeated pull from adding it twice. + +When the table is gone or inactive, or no business day is open, place() returns None and the +order waits at the counter like any online order (with the table's name in its notes). +""" +from __future__ import annotations + +import json +import logging + +logger = logging.getLogger(__name__) +EVENT = "QR_ORDER" + + +def already_placed(db, cloud_order: dict): + """The local order a repeated pull of this QR order went into, or None.""" + from models.order import OrderAuditLog + row = (db.query(OrderAuditLog).filter(OrderAuditLog.event_type == EVENT, OrderAuditLog.note == cloud_order.get("public_ref")) + .first()) + return row.order_id if row else None + + +def place(db, cloud_order: dict, opener_id: int): + """Put the order's items on its table (flushed). → {order, item_ids, table, new} or None.""" + from core import sales_points + from models.business_day import BusinessDay + from models.order import Order + from models.table import Table + from routers.orders import _audit + from services import online_check + from services.cloud_sync import add_cloud_items + table = db.get(Table, cloud_order.get("table_id")) if isinstance(cloud_order.get("table_id"), int) else None + if table is None or not table.is_active: + return None + order = (db.query(Order).filter(Order.table_id == table.id, Order.status.in_(("open", "partially_paid"))) + .order_by(Order.id.desc()).first()) + new = order is None + if new: + day = db.query(BusinessDay).filter(BusinessDay.status == "open").first() + if day is None: + return None + order = Order(table_id=table.id, opened_by=opener_id, status="open", source="pos", order_type="here", + sales_point=sales_points.IN_STORE, business_day_id=day.id) + db.add(order) + db.flush() + _audit(db, order.id, "ORDER_OPENED", waiter_id=opener_id, note="QR menu") + items = add_cloud_items(db, order.id, opener_id, json.loads(cloud_order.get("items_json") or "[]")) + db.flush() + ids = [i.id for i in items] + _audit(db, order.id, EVENT, waiter_id=opener_id, item_ids=ids, amount=cloud_order.get("total"), note=cloud_order.get("public_ref")) + if order.kds_status == "served": + order.kds_status = "pending" + diff = online_check.diff(db, cloud_order, sales_points.QR_TABLE) + if diff: + logger.warning("QR order %s: the site prices it at %.2f, the cloud charged %.2f", + cloud_order.get("public_ref"), diff["site_total"], diff["cloud_total"]) + return {"order": order, "item_ids": ids, "table": table, "new": new} + + +def waiters_for(db, order, table) -> list[int]: + """Who hears about it: the order's waiters, else the waiters whose zone covers the table.""" + from models.user import User, WaiterZone + ids = [w.waiter_id for w in order.waiters if w.waiter_id] + if ids: + return ids + rows = db.query(WaiterZone.waiter_id).join(User, User.id == WaiterZone.waiter_id).filter( + User.is_active.is_(True), (WaiterZone.group_id.is_(None)) | (WaiterZone.group_id == table.group_id)).all() + return sorted({r[0] for r in rows}) + + +def after(db, placed: dict, opener_id: int) -> None: + """After commit: kitchen tickets, live events, the waiters' message. Never raises.""" + from core.i18n import t, venue_language + from routers.kds import _save_and_broadcast_message + from services.printer_service import route_and_print_sync + from services.sse_bus import broadcast_sync + from services.table_qr import label + order, table, ids = placed["order"], placed["table"], placed["item_ids"] + try: + route_and_print_sync(order.id, ids, db) + except Exception as e: + logger.error("QR order on table %s: printing failed: %s", table.id, e) + broadcast_sync("order_updated", {"order_id": order.id, "table_id": table.id, "status": order.status, + "action": "order_opened" if placed["new"] else "items_added", "item_ids": ids}) + broadcast_sync("kds_order_updated", {"order_id": order.id, "kds_status": order.kds_status}) + try: + count = int(sum(i.quantity for i in order.items if i.id in ids)) + body = t("qr.order_message", venue_language(), table=label(table), count=count) + _save_and_broadcast_message(db, opener_id, body, waiters_for(db, order, table), "qr_order", t("qr.sender", venue_language()), + table_ids=[table.id]) + except Exception as e: + logger.error("QR order on table %s: the waiters' message failed: %s", table.id, e) diff --git a/local_backend/services/table_qr.py b/local_backend/services/table_qr.py new file mode 100644 index 0000000..a794d7d --- /dev/null +++ b/local_backend/services/table_qr.py @@ -0,0 +1,84 @@ +"""The QR menu at the table (plan phase 3S, step S.7). + +Every active table gets a random token (`tables.qr_token`); its QR code opens the QR menu at +`{apps url}/menu/{SITE_ID}?t={token}`. The menu snapshot (services/cloud_sync.menu_snapshot) +carries `qr` = {ordering, tables: [{id, label, token_hash}]}: the cloud only ever sees the +tokens' sha256, so a token can't be made up from what the cloud stores, and a new token for a +table (rotate) makes its printed code useless at the next menu push (seconds later). + + ordering_on(db) setting connect_menu.table_ordering ("true" = order at the table) + ensure_tokens(db) give every active table a token (flushed) + rotate(db, table) a new token for one table + snapshot(db) the snapshot's `qr` + menu_url(token) the link the QR code holds + +An order placed with a valid token arrives with the table's id (services/cloud_sync +store_online_orders → place_on_table): its items go straight onto the table's open order (or +a new one), to the kitchen like a waiter's, and the table's waiters get a message. +""" +from __future__ import annotations + +import hashlib +import secrets + +SETTING = "connect_menu.table_ordering" + + +def ordering_on(db) -> bool: + from models.settings import PosSettings + row = db.query(PosSettings).filter(PosSettings.key == SETTING).first() + return bool(row and row.value == "true") + + +def set_ordering(db, on: bool) -> None: + from models.settings import PosSettings + row = db.query(PosSettings).filter(PosSettings.key == SETTING).first() + if row is None: + db.add(PosSettings(key=SETTING, value="true" if on else "false")) + else: + row.value = "true" if on else "false" + + +def new_token() -> str: + return secrets.token_urlsafe(16) + + +def token_hash(token: str) -> str: + return hashlib.sha256(token.encode("utf-8")).hexdigest() + + +def ensure_tokens(db) -> None: + from models.table import Table + for t in db.query(Table).filter(Table.is_active.is_(True), Table.qr_token.is_(None)).all(): + t.qr_token = new_token() + db.flush() + + +def rotate(db, table) -> None: + table.qr_token = new_token() + db.flush() + + +def label(table) -> str: + return table.label or str(table.number) + + +def snapshot(db) -> dict: + from models.table import Table + ensure_tokens(db) + tables = db.query(Table).filter(Table.is_active.is_(True)).order_by(Table.number).all() + return {"ordering": ordering_on(db), + "tables": [{"id": t.id, "label": label(t), "token_hash": token_hash(t.qr_token)} for t in tables]} + + +def apps_url() -> str: + from config import settings + from services.cloud_sync import license_state + return (license_state.get("apps_url") or settings.CLOUD_URL or "").rstrip("/") + + +def menu_url(token: str | None = None) -> str: + from urllib.parse import quote + from config import settings + base = f"{apps_url()}/menu/{quote(settings.SITE_ID or '')}" + return f"{base}?t={quote(token)}" if token else base diff --git a/local_backend/tests/test_qr_table.py b/local_backend/tests/test_qr_table.py new file mode 100644 index 0000000..1766902 --- /dev/null +++ b/local_backend/tests/test_qr_table.py @@ -0,0 +1,127 @@ +"""The QR menu at the table (plan phase 3S, step S.7): each table's QR code carries a random +token (the cloud gets only its hash); an order placed with it goes straight onto the table's +order, to the kitchen, and the table's waiters get a message; a new code replaces the old.""" +import json + +import pytest + +from tests.test_live import err, owner_h, pair, terminal_login # noqa: F401 (fixtures) +from tests.test_pos import drawer_printer, menu, till # noqa: F401 (fixtures) +from tests.test_pos_online import cloud, counter, kds_ids # noqa: F401 (fixtures) + + +@pytest.fixture +def floor(db): + from models.table import Table, TableGroup + terrace, hall = TableGroup(name="Terrace"), TableGroup(name="Hall") + db.add_all([terrace, hall]) + db.flush() + t5 = Table(number=5, label="T5", group_id=terrace.id, is_active=True) + t9 = Table(number=9, group_id=hall.id, is_active=True) + old = Table(number=11, group_id=hall.id, is_active=False) + db.add_all([t5, t9, old]) + db.commit() + return {"t5": t5, "t9": t9, "old": old, "terrace": terrace, "hall": hall} + + +def pull_at_table(db, menu, table_id, cloud_id=801, qty=2): + from services.cloud_sync import store_online_orders + at_table = [] + order = { + "id": cloud_id, "public_ref": f"ORD-{cloud_id:04d}", "order_type": "dine_in", "sales_point": "qr_table", + "customer_name": "Table T5", "table_id": table_id, "table_label": "T5", "status": "pending_acceptance", + "items_json": json.dumps([{"product_id": menu["coffee"].id, "name": "Freddo", "quantity": qty, "unit_price": 3.0, "options": []}]), + "subtotal": 3.0 * qty, "delivery_fee": 0.0, "total": 3.0 * qty, + } + return store_online_orders(db, [order], None, at_table)[cloud_id], at_table + + +def test_qr_codes_per_table_and_what_the_cloud_gets(client, db, owner_h, floor, monkeypatch): + from services import cloud_sync, table_qr + monkeypatch.setitem(cloud_sync.license_state, "apps_url", "https://menu.example.com") + monkeypatch.setattr(cloud_sync.settings, "SITE_ID", "taverna-1") + r = client.get("/api/connect/qr", headers=owner_h) + assert r.status_code == 200, r.text + data = r.json() + assert data["ordering"] is False and data["menu_url"] == "https://menu.example.com/menu/taverna-1" + assert [(t["name"], t["group"]) for t in data["tables"]] == [("T5", "Terrace"), ("9", "Hall")] # the inactive one has none + db.refresh(floor["t5"]) + token = floor["t5"].qr_token + assert len(token) >= 20 and data["tables"][0]["url"] == f"https://menu.example.com/menu/taverna-1?t={token}" + # the snapshot has the hashes only + snap, _ = cloud_sync.menu_snapshot(db) + assert snap["qr"]["ordering"] is False + assert {"id": floor["t5"].id, "label": "T5", "token_hash": table_qr.token_hash(token)} in snap["qr"]["tables"] + assert token not in json.dumps(snap) + # ordering at the table on; a new code for table 5 + assert client.put("/api/connect/qr/ordering", headers=owner_h, json={"on": True}).json()["ordering"] is True + rotated = client.post(f"/api/connect/qr/tables/{floor['t5'].id}/rotate", headers=owner_h).json() + db.refresh(floor["t5"]) + assert floor["t5"].qr_token != token and rotated["tables"][0]["url"].endswith(floor["t5"].qr_token) + assert cloud_sync.menu_snapshot(db)[0]["qr"]["ordering"] is True + assert err(client.post(f"/api/connect/qr/tables/{floor['old'].id}/rotate", headers=owner_h)) == "reservation.table_unknown" + + +def test_qr_codes_need_the_key(client, pair, make_user): + token, _ = pair("pos_counter", "Till 2") + jwt = terminal_login(client, token, make_user(role="waiter")) + assert err(client.get("/api/connect/qr", headers={"X-Xenia-Device": token, "Authorization": f"Bearer {jwt}"})) in ("access.denied", "device.out_of_scope") + + +def test_an_order_at_the_table_goes_on_its_order(client, db, counter, menu, owner_h, cloud, floor, make_user, monkeypatch): + from models.message import StaffMessage + from models.order import Order, OrderItem + from models.user import WaiterZone + import routers.kds as kds + sent = [] + real = kds.broadcast_sync + monkeypatch.setattr(kds, "broadcast_sync", lambda kind, data, **kw: (sent.append((kind, data, kw)), real(kind, data, **kw))) + import services.qr_orders as qo # noqa: F401 + terrace_waiter, hall_waiter = make_user(role="waiter", nickname="Nikos"), make_user(role="waiter", nickname="Maria") + db.add_all([WaiterZone(waiter_id=terrace_waiter.id, group_id=floor["terrace"].id), WaiterZone(waiter_id=hall_waiter.id, group_id=floor["hall"].id)]) + # table 5 already has an order (a waiter's) + open_order = Order(table_id=floor["t5"].id, opened_by=terrace_waiter.id, status="open", business_day_id=counter["day"].id) + db.add(open_order) + db.flush() + db.add(OrderItem(order_id=open_order.id, product_id=menu["burger"].id, added_by=terrace_waiter.id, quantity=1, unit_price=10.0, + status="active", printed=True)) + db.commit() + local, at_table = pull_at_table(db, menu, floor["t5"].id) + assert local == open_order.id and at_table == [801] + db.expire_all() + order = db.get(Order, open_order.id) + assert [(i.product_name, i.quantity, i.unit_price) for i in order.items] == [("Burger", 1, 10.0), ("Freddo", 2, 3.0)] + added = [i.id for i in order.items if i.product_name == "Freddo"] + assert cloud["printed"] == [(order.id, added)] # to the kitchen, like a waiter's + assert order.id in kds_ids(client, owner_h) + msg = db.query(StaffMessage).filter(StaffMessage.message_type == "qr_order").one() + assert json.loads(msg.target_waiter_ids) == [terrace_waiter.id] and "T5" in msg.body and "2" in msg.body + assert any(k == "message_sent" and kw.get("user_ids") == [terrace_waiter.id] for k, _, kw in sent) + # a repeated pull doesn't add it twice + again, at_table = pull_at_table(db, menu, floor["t5"].id) + assert again == -order.id and at_table == [801] + assert db.query(OrderItem).filter(OrderItem.order_id == order.id).count() == 2 + + +def test_a_free_table_gets_a_new_order_and_its_zone_waiters_hear(db, counter, menu, cloud, floor, make_user): + from models.message import StaffMessage + from models.order import Order + from models.user import WaiterZone + hall_waiter, everywhere = make_user(role="waiter"), make_user(role="waiter") + db.add_all([WaiterZone(waiter_id=hall_waiter.id, group_id=floor["hall"].id), WaiterZone(waiter_id=everywhere.id, group_id=None)]) + db.commit() + local, _ = pull_at_table(db, menu, floor["t9"].id, cloud_id=802, qty=1) + order = db.get(Order, local) + assert (order.table_id, order.source, order.sales_point, order.status) == (floor["t9"].id, "pos", "in_store", "open") + assert [i.unit_price for i in order.items] == [3.0] + msg = db.query(StaffMessage).filter(StaffMessage.message_type == "qr_order").one() + assert sorted(json.loads(msg.target_waiter_ids)) == sorted([hall_waiter.id, everywhere.id]) + + +def test_no_usable_table_it_waits_at_the_counter(client, db, counter, menu, cloud, floor): + from models.order import Order + local, at_table = pull_at_table(db, menu, floor["old"].id, cloud_id=803) + order = db.get(Order, local) + assert at_table == [] and order.table_id is None and order.source == "online" and order.online_status == "pending_acceptance" + assert "T5" in (order.online_customer_notes or "") + assert cloud["printed"] == [] diff --git a/manager_dashboard/src/App.jsx b/manager_dashboard/src/App.jsx index c2fbc19..49d6f84 100644 --- a/manager_dashboard/src/App.jsx +++ b/manager_dashboard/src/App.jsx @@ -18,6 +18,7 @@ import TablesPage from './pages/TablesPage' import OrderDetailPage from './pages/OrderDetailPage' import OnlineOrdersPage from './pages/OnlineOrdersPage' import FeesPage from './pages/online/FeesPage' +import QrCodesPage from './pages/online/QrCodesPage' // CRM import ContactsPage from './pages/crm/ContactsPage' @@ -147,6 +148,7 @@ export default function App() { } /> } /> } /> + } /> } /> {/* ── CRM ── */} diff --git a/manager_dashboard/src/pages/online/QrCodesPage.jsx b/manager_dashboard/src/pages/online/QrCodesPage.jsx new file mode 100644 index 0000000..1bfd90d --- /dev/null +++ b/manager_dashboard/src/pages/online/QrCodesPage.jsx @@ -0,0 +1,86 @@ +// The tables' QR codes (plan phase 3S, step S.7): one code per table that opens the QR menu +// at that table. The venue chooses whether guests can order from it (straight onto the +// table's order, to the kitchen, with a message to the table's waiters) or only read it. A +// lost or copied code is replaced with "New code" (the printed one stops working within +// seconds). Print puts every table's code on paper, one card each. +// Backend: /api/connect/qr (connect_menu.manage), services/table_qr.py. +import { useCallback, useEffect, useState } from 'react' +import toast from 'react-hot-toast' +import { QRCodeSVG } from 'qrcode.react' +import { Printer, RefreshCw } from 'lucide-react' +import { errorMessage } from '@xenia/api' +import { useTranslation } from '@xenia/i18n' +import { Button, Dialog, EmptyState, Spinner, Switch } from '@xenia/ui' +import client from '../../api/client' + +export default function QrCodesPage() { + const { t } = useTranslation('manager') + const [data, setData] = useState(null) + const [error, setError] = useState(null) + const [confirmAll, setConfirmAll] = useState(false) + const [busy, setBusy] = useState(false) + + const load = useCallback(async () => { + try { setData((await client.get('/api/connect/qr')).data); setError(null) } catch (err) { setError(errorMessage(err, t)) } + }, [t]) + useEffect(() => { load() }, [load]) + + const act = async (fn, done) => { + setBusy(true) + try { setData((await fn()).data); if (done) toast.success(done) } catch (err) { toast.error(errorMessage(err, t)) } + setBusy(false) + } + + if (error) return
+ if (!data) return
+ + return ( +
+
+

{t('qr.title')}

+

{t('qr.intro')}

+
+ +
+ act(() => client.put('/api/connect/qr/ordering', { on }), t('fees.saved'))} + label={t('qr.ordering')} description={t(data.ordering ? 'qr.orderingOn' : 'qr.orderingOff')} /> +

{t('qr.menuLink')} {data.menu_url}

+
+ + +
+
+ + {data.tables.length === 0 ? ( + + ) : ( +
    + {data.tables.map(tb => ( +
  • + {t('qr.table', { name: tb.name })} + {tb.group && {tb.group}} + + {t(data.ordering ? 'qr.scanOrder' : 'qr.scanRead')} + +
  • + ))} +
+ )} + + {confirmAll && ( + setConfirmAll(false)} + footer={<> + + + }> +

{t('qr.rotateAllBody')}

+
+ )} +
+ ) +} diff --git a/manager_dashboard/src/shell/nav.js b/manager_dashboard/src/shell/nav.js index d346674..ec7348d 100644 --- a/manager_dashboard/src/shell/nav.js +++ b/manager_dashboard/src/shell/nav.js @@ -16,7 +16,7 @@ import { BookUser, Users, Receipt, CreditCard, Package, TableProperties, UserCog, CalendarDays, Trash2, Boxes, BarChart2, TrendingUp, Users2, ShoppingCart, Tag, Activity, Printer, ConciergeBell, FileText, - AppWindow, Settings, CookingPot, Truck, StickyNote, Percent, Plug, BadgeCheck, MonitorSmartphone, LogIn, ShieldCheck, + AppWindow, Settings, CookingPot, Truck, StickyNote, Percent, Plug, BadgeCheck, MonitorSmartphone, LogIn, ShieldCheck, QrCode, } from 'lucide-react' const DASH = 'core.dashboard.access' @@ -29,6 +29,7 @@ export const NAV = [ { to: '/tables', icon: LayoutGrid, label: 'nav.tables', module: 'ordering', perm: DASH }, { to: '/online-orders', icon: ShoppingBag, label: 'nav.onlineOrders', module: 'connect_orders', perm: DASH, badge: 'onlineOrders' }, { to: '/online/fees', icon: Truck, label: 'nav.deliveryFees', module: 'connect_orders', perm: 'connect_orders.fees' }, + { to: '/online/qr', icon: QrCode, label: 'nav.qrCodes', module: 'connect_menu', perm: 'connect_menu.manage' }, ], }, { diff --git a/packages/i18n/locales/el/manager.json b/packages/i18n/locales/el/manager.json index f04b11c..4c2660f 100644 --- a/packages/i18n/locales/el/manager.json +++ b/packages/i18n/locales/el/manager.json @@ -45,7 +45,8 @@ "devices": "Συσκευές", "sessions": "Συνδεδεμένοι τώρα", "approvals": "Εγκρίσεις υπευθύνου", - "deliveryFees": "Online παραγγελίες (ρύθμιση)" + "deliveryFees": "Online παραγγελίες (ρύθμιση)", + "qrCodes": "QR τραπεζιών" }, "profile": { "edit": "Επεξεργασία προφίλ", @@ -571,5 +572,24 @@ "party": "Μέγιστα άτομα ανά κράτηση", "fire": "Η κουζίνα παίρνει το φαγητό (λεπτά πριν την άφιξη)", "fireHint": "0 = την ώρα της κράτησης." + }, + "qr": { + "title": "QR κωδικοί τραπεζιών", + "intro": "Κάθε τραπέζι έχει τον δικό του QR κωδικό. Οι πελάτες τον σκανάρουν για να δουν το μενού στο τραπέζι και, αν το επιτρέπετε, να παραγγείλουν: η παραγγελία μπαίνει κατευθείαν στην παραγγελία του τραπεζιού και στην κουζίνα, και οι σερβιτόροι του τραπεζιού παίρνουν μήνυμα.", + "ordering": "Οι πελάτες παραγγέλνουν από το τραπέζι", + "orderingOn": "Ενεργό: οι παραγγελίες μπαίνουν στο τραπέζι και στην κουζίνα.", + "orderingOff": "Ανενεργό: το QR μενού είναι μόνο για ανάγνωση.", + "menuLink": "Το μενού (χωρίς τραπέζι):", + "print": "Εκτύπωση όλων", + "rotateAll": "Νέοι κωδικοί για όλα τα τραπέζια", + "rotate": "Νέος κωδικός", + "rotated": "Το τραπέζι {{name}} έχει νέο κωδικό. Τυπώστε τον και αντικαταστήστε τον παλιό.", + "rotatedAll": "Όλα τα τραπέζια έχουν νέους κωδικούς. Τυπώστε τους και αντικαταστήστε τους παλιούς.", + "rotateAllTitle": "Νέοι κωδικοί για όλα τα τραπέζια;", + "rotateAllBody": "Οι τυπωμένοι κωδικοί σταματούν να ισχύουν σε λίγα δευτερόλεπτα. Θα χρειαστεί να τυπώσετε και να τοποθετήσετε τους νέους.", + "noTables": "Δεν υπάρχουν τραπέζια ακόμα. Προσθέστε πρώτα τραπέζια.", + "table": "Τραπέζι {{name}}", + "scanOrder": "Σκανάρετε για μενού και παραγγελία", + "scanRead": "Σκανάρετε για το μενού" } } diff --git a/packages/i18n/locales/en/manager.json b/packages/i18n/locales/en/manager.json index 19836f9..2e93e07 100644 --- a/packages/i18n/locales/en/manager.json +++ b/packages/i18n/locales/en/manager.json @@ -45,7 +45,8 @@ "devices": "Devices", "sessions": "Signed in now", "approvals": "Manager approvals", - "deliveryFees": "Online ordering" + "deliveryFees": "Online ordering", + "qrCodes": "Table QR codes" }, "profile": { "edit": "Edit profile", @@ -571,5 +572,24 @@ "party": "Most people per booking", "fire": "Kitchen gets the food (minutes before arrival)", "fireHint": "0 = at the booking time." + }, + "qr": { + "title": "Table QR codes", + "intro": "Each table has its own QR code. Guests scan it to see the menu at the table, and, if you allow it, to order: the order goes straight onto the table's order and to the kitchen, and the table's waiters get a message.", + "ordering": "Guests can order from the table", + "orderingOn": "On: orders go onto the table's order and to the kitchen.", + "orderingOff": "Off: the QR menu is only for reading.", + "menuLink": "The menu (without a table):", + "print": "Print all codes", + "rotateAll": "New codes for all tables", + "rotate": "New code", + "rotated": "Table {{name}} has a new code. Print it and replace the old one.", + "rotatedAll": "Every table has a new code. Print them and replace the old ones.", + "rotateAllTitle": "New codes for every table?", + "rotateAllBody": "The printed codes stop working within a few seconds. You'll need to print and place the new ones.", + "noTables": "No tables yet. Add tables first.", + "table": "Table {{name}}", + "scanOrder": "Scan to see the menu and order", + "scanRead": "Scan to see the menu" } } diff --git a/tests/e2e/qr_table.mjs b/tests/e2e/qr_table.mjs new file mode 100644 index 0000000..d119758 --- /dev/null +++ b/tests/e2e/qr_table.mjs @@ -0,0 +1,164 @@ +// End-to-end: the QR menu at the table (plan phase 3S, step S.7), with a real cloud and a +// real venue server talking to each other, and the QR menu app in a phone-sized browser. +// Done when: scanning table 5's QR and ordering puts the items on table 5's order, live on +// the waiter's phone and the counter, and a forged table token is refused. +// - the cloud starts empty; a site is registered; the venue's server runs with its keys +// - the venue turns ordering at the table on; table 5's code (from the manager's QR page +// API) opens the menu app at table 5 +// - a guest orders two dishes → the items land on table 5's order, go to the kitchen +// (KDS), the live stream announces it (what the waiters' phones and the counter follow) +// and the guest's page says it's in the kitchen +// - a forged code: the menu says the code isn't valid and an order with it is refused +// - a new code for table 5: the old one stops working +// node qr_table.mjs +import { spawn } from 'node:child_process' +import { mkdirSync, openSync, rmSync } from 'node:fs' +import crypto from 'node:crypto' +import path from 'node:path' +import { chromium } from 'playwright' +import { BROWSER_CHANNEL, CLOUD, OUT, PYTHON, REPO, reporter, sleep } from './lib/env.mjs' +import { killTree, login, startBackend, waitHttp } from './lib/proc.mjs' + +const CLOUD_PORT = 8114 +const SITE_PORT = 8063 +const APP_PORT = 5212 +const CLOUD_URL = `http://127.0.0.1:${CLOUD_PORT}` +const APP_DIR = path.join(REPO, 'cloud-service', 'connect_frontend', 'menu-app') +const r = reporter('QR menu at the table: a real cloud and venue, table 5 orders') +const procs = [] +let backend, browser + +function start(cmd, args, opts, logName) { + const log = openSync(path.join(OUT, logName), 'w') + const p = spawn(cmd, args, { ...opts, shell: process.platform === 'win32', detached: process.platform !== 'win32', stdio: ['ignore', log, log] }) + procs.push(p) + return p +} + +async function call(base, method, url, { body, headers = {}, token } = {}) { + const res = await fetch(`${base}${url}`, { method, headers: { 'content-type': 'application/json', ...(token ? { authorization: `Bearer ${token}` } : {}), ...headers }, + body: body ? JSON.stringify(body) : undefined }) + const text = await res.text() + let data = null + try { data = text ? JSON.parse(text) : null } catch { data = text } + if (!res.ok) { const e = new Error(`${method} ${url} → ${res.status} ${text.slice(0, 300)}`); e.status = res.status; e.data = data; throw e } + return data +} +const cloud = (m, u, o) => call(CLOUD_URL, m, u, o) + +try { + // ── the cloud, empty; a venue registered on it ─────────────────────────── + const tmp = path.join(OUT, 'qr-table-cloud') + rmSync(tmp, { recursive: true, force: true }) + mkdirSync(tmp, { recursive: true }) + const key = crypto.generateKeyPairSync('ed25519').privateKey.export({ format: 'der', type: 'pkcs8' }).subarray(-32).toString('base64') + start(PYTHON, ['-m', 'uvicorn', 'main:app', '--port', String(CLOUD_PORT)], { + cwd: CLOUD, env: { ...process.env, DATABASE_URL: `sqlite:///${path.join(tmp, 'cloud.db').replace(/\\/g, '/')}`, ADMIN_USERNAME: 'e2eadmin', + ADMIN_PASSWORD: 'e2e-admin-pass', SECRET_KEY: 'e2e', LICENSE_SIGNING_KEY: key, PYTHONIOENCODING: 'utf-8', + PUBLIC_APPS_URL: `http://localhost:${APP_PORT}` }, + }, 'qr-table-cloud.log') + await waitHttp(`${CLOUD_URL}/docs`, true, 60_000) + const admin = await cloud('POST', '/api/auth/login', { body: { username: 'e2eadmin', password: 'e2e-admin-pass' } }) + const site = await cloud('POST', '/api/sites/', { token: admin.access_token, + body: { name: 'Taverna', owner_name: 'O', contact_email: 'o@example.com', license_expires_at: '2030-01-01T00:00:00+00:00' } }) + + // ── the venue's server, with that site's keys ──────────────────────────── + backend = await startBackend({ port: SITE_PORT, siteId: site.site_id, siteKey: site.secret_key, cloudUrl: CLOUD_URL, env: { LICENSE_MODE: 'off', CONNECT_SYNC_INTERVAL_SECONDS: '1' } }) + const boss = await login(backend.url) + const api = (m, u, o = {}) => call(backend.url, m, u, { token: boss, ...o }) + await api('PUT', '/api/platform/modules/connect_menu', { body: { enabled: true } }) + await api('PUT', '/api/platform/modules/connect_orders', { body: { enabled: true } }) + await api('POST', '/api/business-day/open', { body: {} }).catch(() => {}) + const t5 = (await api('GET', '/api/tables/')).find(t => t.number === 5) + r.check('the venue has a table 5', !!t5) + + // the venue turns ordering at the table on; table 5's code + let qr = await api('PUT', '/api/connect/qr/ordering', { body: { on: true } }) + // the heartbeat brings the apps' address; the codes then point at the menu app + for (let i = 0; i < 40 && !qr.menu_url.startsWith(`http://localhost:${APP_PORT}`); i++) { await sleep(500); qr = await api('GET', '/api/connect/qr') } + const code5 = qr.tables.find(t => t.id === t5.id) + r.check('table 5 has its own code, pointing at the QR menu app', !!code5 && code5.url.startsWith(`http://localhost:${APP_PORT}/menu/${site.site_id}?t=`), code5?.url) + const token5 = new URL(code5.url).searchParams.get('t') + // the code reaches the cloud with the menu (pushed within seconds of the change) + let seen = null + for (let i = 0; i < 60 && !seen?.table; i++) { + seen = await cloud('GET', `/api/menu/${site.site_id}?t=${encodeURIComponent(token5)}`).catch(() => null) + if (!seen?.table) await sleep(500) + } + r.check('the cloud knows table 5 by its code (the hash came with the menu), and ordering is on', seen?.table?.id === t5.id && seen.table_ordering === true, + JSON.stringify(seen?.table)) + const dishes = seen.categories.flatMap(c => c.products).filter(p => p.digital_available !== false && (!p.sold_at || p.sold_at.includes('qr_table'))) + const [d1, d2] = dishes + + // ── the menu app, built for this cloud ──────────────────────────────────── + const build = spawn('npx', ['vite', 'build'], { cwd: APP_DIR, shell: process.platform === 'win32', env: { ...process.env, VITE_CLOUD_URL: CLOUD_URL }, stdio: 'ignore' }) + r.check('the QR menu app builds with the cloud address', await new Promise(res => build.on('exit', code => res(code === 0)))) + start('npx', ['vite', 'preview', '--port', String(APP_PORT), '--strictPort'], { cwd: APP_DIR }, 'qr-table-preview.log') + await waitHttp(`http://localhost:${APP_PORT}/menu/`, true, 60_000) + + // the live stream the waiters' phones and the counter follow + const events = [] + const ws = new WebSocket(`ws://127.0.0.1:${SITE_PORT}/api/ws/connect`) + ws.onopen = () => ws.send(JSON.stringify({ cursor: 0, token: boss })) + ws.onmessage = m => { try { events.push(JSON.parse(m.data)) } catch { /* not json */ } } + + browser = await chromium.launch(BROWSER_CHANNEL ? { channel: BROWSER_CHANNEL } : {}) + const page = await browser.newPage({ viewport: { width: 390, height: 844 }, locale: 'en-GB' }) + const errors = [] + page.on('pageerror', e => errors.push(e.message)) + + // ── table 5 scans and orders ───────────────────────────────────────────── + await page.goto(code5.url) + r.check('scanning table 5: the menu says "Table 5" and lets them order', await page.getByTestId('table-banner').waitFor({ timeout: 15_000 }).then(() => true).catch(() => false) + && (await page.getByTestId('table-banner').textContent()).includes(seen.table.label)) + await page.locator(`[data-testid="menu-product"][data-product="${d1.id}"]`).getByTestId('menu-add').click() + await page.locator(`[data-testid="menu-product"][data-product="${d2.id}"]`).getByTestId('menu-add').click() + await page.getByTestId('cart-button').click() + await page.getByTestId('cart-continue').click() + r.check('checkout names the table (no table number to type)', (await page.getByTestId('checkout-table').textContent()).includes(seen.table.label)) + await page.screenshot({ path: path.join(OUT, 'qr-table-checkout.png'), fullPage: true }) + const before = events.length + await page.getByTestId('place-order').click() + const confirmed = await page.waitForFunction(() => document.querySelector('[data-testid="confirm-status"]')?.dataset.status === 'accepted', null, { timeout: 30_000 }) + .then(() => true).catch(() => false) + r.check('the guest\'s page: the order is in the kitchen', confirmed) + await page.screenshot({ path: path.join(OUT, 'qr-table-confirm.png'), fullPage: true }) + + const onTable = (await api('GET', '/api/orders/active')).find(o => o.table_id === t5.id) + const order = onTable ? await api('GET', `/api/orders/${onTable.id}`) : null + const names = (order?.items ?? []).map(i => i.product_id) + r.check('the two dishes are on table 5\'s order', !!order && names.includes(d1.id) && names.includes(d2.id), JSON.stringify(order?.items?.map(i => [i.product_name, i.unit_price]))) + r.check('…at the QR menu\'s prices', order?.items?.find(i => i.product_id === d1.id)?.unit_price === d1.prices.qr_table) + r.check('…and in the kitchen (KDS)', (await api('GET', '/api/kds/orders')).orders.some(o => o.id === order?.id)) + for (let i = 0; i < 20 && !events.slice(before).some(e => e.type === 'order_updated' && e.data?.table_id === t5.id); i++) await sleep(200) + r.check('…announced live to the waiters\' phones and the counter (order_updated for table 5)', + events.slice(before).some(e => e.type === 'order_updated' && e.data?.table_id === t5.id && e.data?.order_id === order?.id)) + + // ── a forged code ──────────────────────────────────────────────────────── + const page2 = await browser.newPage({ viewport: { width: 390, height: 844 }, locale: 'en-GB' }) + await page2.goto(`http://localhost:${APP_PORT}/menu/${site.site_id}?t=forged-token-for-table-5`) + r.check('a forged code: the menu says it isn\'t valid and offers no ordering', + await page2.getByTestId('table-invalid').waitFor({ timeout: 15_000 }).then(() => true).catch(() => false) && await page2.getByTestId('menu-add').count() === 0) + const forged = await cloud('POST', `/api/orders/${site.site_id}`, { body: { order_type: 'dine_in', table_token: 'forged-token-for-table-5', customer_name: 'X', + items: [{ product_id: d1.id, quantity: 1 }] } }).catch(e => e) + r.check('…and an order sent with it is refused', forged?.status === 403 && forged.data?.detail?.code === 'order.table_invalid', JSON.stringify(forged?.data)) + + // ── a new code for table 5: the old one stops working ──────────────────── + await api('POST', `/api/connect/qr/tables/${t5.id}/rotate`) + let old = null + for (let i = 0; i < 60; i++) { + old = await cloud('GET', `/api/menu/${site.site_id}?t=${encodeURIComponent(token5)}`) + if (old.table_invalid) break + await sleep(500) + } + r.check('a new code for table 5: the printed one stops working within seconds', old?.table_invalid === true) + ws.close() + r.check('no page errors', errors.length === 0, errors.join(' | ')) +} catch (err) { + r.check(`unexpected error: ${err.message}`, false) +} finally { + await browser?.close() + await backend?.stop() + for (const p of procs) killTree(p) +} +process.exit(r.done() ? 1 : 0) diff --git a/tests/e2e/run-all.mjs b/tests/e2e/run-all.mjs index 209b12e..4a1a5f9 100644 --- a/tests/e2e/run-all.mjs +++ b/tests/e2e/run-all.mjs @@ -24,7 +24,8 @@ const suites = [ ['ui (@xenia/ui + @xenia/i18n)', 'node', ['ui.mjs'], E2E], ['manager (login, bootstrap, approvals)', 'node', ['manager.mjs'], E2E], ['terminal (pairing, sign-in, states)', 'node', ['terminal.mjs'], E2E], - ['order app (cloud: takeaway + delivery)', 'node', ['order_app.mjs'], E2E], + ['order app (cloud: takeaway + delivery + bookings)', 'node', ['order_app.mjs'], E2E], + ['QR menu at the table (cloud + venue)', 'node', ['qr_table.mjs'], E2E], ['stack (compose: terminal :8082, LAN only)', 'node', ['stack.mjs'], E2E], ] if (!process.argv.includes('--no-android')) suites.push(['android (emulator)', 'node', ['android.mjs'], E2E]) diff --git a/waiter_pwa/src/context/NotificationContext.jsx b/waiter_pwa/src/context/NotificationContext.jsx index 915fda1..c17e132 100644 --- a/waiter_pwa/src/context/NotificationContext.jsx +++ b/waiter_pwa/src/context/NotificationContext.jsx @@ -32,6 +32,11 @@ const TYPE_THEME = { bg: '#2d1505', border: '#f59e0b', ackBg: '#d97706', labelColor: '#fde68a', icon: '👋', }, + // a table ordered from the QR menu (phase 3S, S.7): already on the table's order and in the kitchen + qr_order: { + bg: '#0c1f2e', border: '#38bdf8', ackBg: '#0284c7', + labelColor: '#bae6fd', icon: '📱', + }, } function getTheme(messageType) {