Files
xenia-pos-local/local_backend/services/qr_orders.py
T
bonaminandClaude Opus 5.5 f85894a72e refactor(connect): one live connection, no token in any address (SSE removed)
Plan step 4.0. Owner (2026-11-17): no phone in use needs to keep working, so no
compatibility path.
- Removed the SSE channel: routers/sse.py (/api/sse/stream, which still accepted a JWT whose
  session had ended — a signed-out phone could keep listening), services/sse_bus.py (every
  backend module now calls services/ws_bus.broadcast_sync directly), waiter useSSE.js.
- Credentials only in the first frame: the waiter's useWebSocket and the manager's
  LiveProvider send {token} there like the terminal; routers/ws.py no longer reads ?token=
  (a token in a URL ends up in proxy and server logs).
- Waiter: SSEContext → LiveContext (LiveProvider, useLiveContext, liveAlive, the
  'live-event' / 'live-reconnected' window events), dead SSE compat code removed.
- Tests: a token in the address is refused, /api/sse/stream is 404; e2e browser (3 delivery
  modes) and manager assert no token in the live connection's address. Android taps now
  wait for their element (the fixed sleeps made the suite flaky, KI-009).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 10:49:21 +02:00

100 lines
5.1 KiB
Python

"""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.ws_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)