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:
@@ -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
|
||||
|
||||
|
||||
@@ -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)
|
||||
@@ -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
|
||||
Reference in New Issue
Block a user