feat(connect): the QR menu at the table: one code per table, orders straight onto the table

Plan phase 3S, step S.7.
- tables.qr_token (migration 0021): a random token per active table; services/table_qr.py
  (tokens, rotate, the snapshot's `qr` with the tokens' sha256 only, the code's link from the
  cloud's apps_url); setting connect_menu.table_ordering (read-only by default).
- /api/connect/qr (connect_menu.manage): the codes, ordering on/off, a new code per table or
  for all; table and QR changes push the menu at once (MENU_PATHS).
- Pull: a QR order with a table id goes onto the table's open order or a new one
  (services/qr_orders.py): items at the cloud's prices, kitchen tickets, KDS, order_updated
  (the waiters' phones and the counter), a `qr_order` message to the order's waiters or the
  table's zone waiters; audit QR_ORDER (a repeated pull adds nothing); the cloud is told
  "accepted" (the guest's page: in the kitchen). No usable table or no open day → the counter
  gets it as before. Waiter app: the message's look.
- Manager: Online → Table QR codes (/online/qr): ordering switch, the menu link, a QR card
  per table (print all), new code per table / for all.
- Heartbeat: apps_url kept in the license state.
- Tests: tests/test_qr_table.py (5); e2e qr_table.mjs (a real cloud and venue: table 5's
  code → two dishes on table 5's order, KDS, live event, the guest's page; a forged code
  refused; a new code kills the old one), in run-all.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-16 01:26:55 +02:00
co-authored by Claude Opus 5.5
parent 70c8f2bb57
commit 652e6a26af
19 changed files with 773 additions and 13 deletions
+42 -8
View File
@@ -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