"""The QR menu at the table (plan phase 3S, step S.7). Each table's QR code carries a random token the venue's server made for that table (client-services services/table_qr.py). The menu snapshot brings, under `qr`: {ordering: bool, tables: [{id, label, token_hash}]} token_hash = sha256(token) hex so the cloud never holds the tokens themselves, and a token is checked by its hash. A new QR code for a table (the venue "rotates" it) makes the old one useless at the next menu push. Ordering at the table needs the venue's `ordering`, the site's menu_mode "order" (sysadmin) and a valid token; otherwise the QR menu is read-only. The public menu never shows `qr`. """ from __future__ import annotations import hashlib import hmac def token_hash(token: str) -> str: return hashlib.sha256(token.encode("utf-8")).hexdigest() def table_for(snapshot: dict, token: str | None) -> dict | None: """{id, label} of the table this token belongs to, or None.""" if not token or not isinstance(token, str) or len(token) > 100: return None wanted = token_hash(token) for t in (snapshot.get("qr") or {}).get("tables") or []: if isinstance(t, dict) and hmac.compare_digest(str(t.get("token_hash") or ""), wanted): return {"id": t.get("id"), "label": t.get("label")} return None def ordering_on(snapshot: dict, site) -> bool: return site.menu_mode == "order" and bool((snapshot.get("qr") or {}).get("ordering"))