"""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