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
+4
View File
@@ -93,5 +93,9 @@
},
"system_product": {
"delivery_fee": "Μεταφορικά"
},
"qr": {
"order_message": "Τραπέζι {table}: νέα παραγγελία από το QR μενού ({count} τεμ.), στάλθηκε στην κουζίνα.",
"sender": "QR μενού"
}
}
+4
View File
@@ -93,5 +93,9 @@
},
"system_product": {
"delivery_fee": "Delivery fee"
},
"qr": {
"order_message": "Table {table}: new order from the QR menu ({count} items), sent to the kitchen.",
"sender": "QR menu"
}
}
@@ -0,0 +1,26 @@
"""tables: qr_token (the QR menu at the table, plan phase 3S, S.7)
Revision ID: 0021_table_qr_token
Revises: 0020_online_reservations
Create Date: 2026-11-16 23:30:00
"""
from alembic import op
import sqlalchemy as sa
revision = '0021_table_qr_token'
down_revision = '0020_online_reservations'
branch_labels = None
depends_on = None
def upgrade() -> None:
with op.batch_alter_table('tables', schema=None) as batch_op:
batch_op.add_column(sa.Column('qr_token', sa.String(), nullable=True))
batch_op.create_unique_constraint('uq_tables_qr_token', ['qr_token'])
def downgrade() -> None:
with op.batch_alter_table('tables', schema=None) as batch_op:
batch_op.drop_constraint('uq_tables_qr_token', type_='unique')
batch_op.drop_column('qr_token')
+3
View File
@@ -27,6 +27,9 @@ class Table(Base):
seat_count = Column(Integer, nullable=True)
floor_x = Column(Float, nullable=True)
floor_y = Column(Float, nullable=True)
# the table's QR code (phase 3S, S.7): a random token in the QR menu link; the cloud gets
# only its sha256 (services/table_qr.py). A new token makes the printed code useless.
qr_token = Column(String, nullable=True, unique=True)
group = relationship("TableGroup", back_populates="tables")
orders = relationship("Order", back_populates="table")
@@ -1,5 +1,5 @@
"""Module manifest — see core/modules/model.py and APPS_PLATFORM §4."""
from core.modules.model import Module, Perm
from core.modules.model import Module, Mount, Perm, SettingDef
MODULE = Module(
key='connect_menu',
@@ -10,5 +10,11 @@ MODULE = Module(
permissions=(
Perm('connect_menu.manage', 'Manage the QR menu', roles=('owner', 'store_manager')),
),
settings=(
SettingDef('connect_menu.table_ordering', 'false', 'The QR menu takes orders at the table (with a table QR code): "true" | "false" (read-only). Phase 3S, S.7.', type='bool'),
),
routers=(
Mount('routers.qr_codes', '/api/connect/qr'),
),
workers=('services.cloud_sync:menu_push_worker',),
)
+73
View File
@@ -0,0 +1,73 @@
"""The tables' QR codes (plan phase 3S, step S.7). Key: connect_menu.manage.
GET /api/connect/qr {ordering, menu_url, tables: [{id, name, group, url}]}
PUT /api/connect/qr/ordering {on}: the QR menu takes orders at the table, or is read-only
POST /api/connect/qr/tables/{id}/rotate a new code for one table (the printed one stops working)
POST /api/connect/qr/rotate new codes for every table
Each change pushes the menu soon (main.py middleware, MENU_PATHS), so the cloud knows the new
codes within seconds. services/table_qr.py has the rules.
"""
from __future__ import annotations
from fastapi import APIRouter, Depends
from pydantic import BaseModel
from sqlalchemy.orm import Session
from core.access.deps import require
from core.errors import XeniaError
from database import get_db
from services import table_qr
router = APIRouter()
KEY = "connect_menu.manage"
class OrderingBody(BaseModel):
on: bool
def _out(db) -> dict:
from models.table import Table, TableGroup
table_qr.ensure_tokens(db)
db.commit()
groups = {g.id: g.name for g in db.query(TableGroup).all()}
tables = db.query(Table).filter(Table.is_active.is_(True)).order_by(Table.group_id, Table.number).all()
return {
"ordering": table_qr.ordering_on(db),
"menu_url": table_qr.menu_url(),
"tables": [{"id": t.id, "name": table_qr.label(t), "number": t.number, "group": groups.get(t.group_id),
"url": table_qr.menu_url(t.qr_token)} for t in tables],
}
@router.get("")
def qr_codes(db: Session = Depends(get_db), user=Depends(require(KEY))):
return _out(db)
@router.put("/ordering")
def set_ordering(body: OrderingBody, db: Session = Depends(get_db), user=Depends(require(KEY))):
table_qr.set_ordering(db, body.on)
db.commit()
return _out(db)
@router.post("/tables/{table_id}/rotate")
def rotate_one(table_id: int, db: Session = Depends(get_db), user=Depends(require(KEY))):
from models.table import Table
table = db.get(Table, table_id)
if table is None or not table.is_active:
raise XeniaError("reservation.table_unknown", table_id=table_id)
table_qr.rotate(db, table)
db.commit()
return _out(db)
@router.post("/rotate")
def rotate_all(db: Session = Depends(get_db), user=Depends(require(KEY))):
from models.table import Table
for t in db.query(Table).filter(Table.is_active.is_(True)).all():
table_qr.rotate(db, t)
db.commit()
return _out(db)
+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
+99
View File
@@ -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)
+84
View File
@@ -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
+127
View File
@@ -0,0 +1,127 @@
"""The QR menu at the table (plan phase 3S, step S.7): each table's QR code carries a random
token (the cloud gets only its hash); an order placed with it goes straight onto the table's
order, to the kitchen, and the table's waiters get a message; a new code replaces the old."""
import json
import pytest
from tests.test_live import err, owner_h, pair, terminal_login # noqa: F401 (fixtures)
from tests.test_pos import drawer_printer, menu, till # noqa: F401 (fixtures)
from tests.test_pos_online import cloud, counter, kds_ids # noqa: F401 (fixtures)
@pytest.fixture
def floor(db):
from models.table import Table, TableGroup
terrace, hall = TableGroup(name="Terrace"), TableGroup(name="Hall")
db.add_all([terrace, hall])
db.flush()
t5 = Table(number=5, label="T5", group_id=terrace.id, is_active=True)
t9 = Table(number=9, group_id=hall.id, is_active=True)
old = Table(number=11, group_id=hall.id, is_active=False)
db.add_all([t5, t9, old])
db.commit()
return {"t5": t5, "t9": t9, "old": old, "terrace": terrace, "hall": hall}
def pull_at_table(db, menu, table_id, cloud_id=801, qty=2):
from services.cloud_sync import store_online_orders
at_table = []
order = {
"id": cloud_id, "public_ref": f"ORD-{cloud_id:04d}", "order_type": "dine_in", "sales_point": "qr_table",
"customer_name": "Table T5", "table_id": table_id, "table_label": "T5", "status": "pending_acceptance",
"items_json": json.dumps([{"product_id": menu["coffee"].id, "name": "Freddo", "quantity": qty, "unit_price": 3.0, "options": []}]),
"subtotal": 3.0 * qty, "delivery_fee": 0.0, "total": 3.0 * qty,
}
return store_online_orders(db, [order], None, at_table)[cloud_id], at_table
def test_qr_codes_per_table_and_what_the_cloud_gets(client, db, owner_h, floor, monkeypatch):
from services import cloud_sync, table_qr
monkeypatch.setitem(cloud_sync.license_state, "apps_url", "https://menu.example.com")
monkeypatch.setattr(cloud_sync.settings, "SITE_ID", "taverna-1")
r = client.get("/api/connect/qr", headers=owner_h)
assert r.status_code == 200, r.text
data = r.json()
assert data["ordering"] is False and data["menu_url"] == "https://menu.example.com/menu/taverna-1"
assert [(t["name"], t["group"]) for t in data["tables"]] == [("T5", "Terrace"), ("9", "Hall")] # the inactive one has none
db.refresh(floor["t5"])
token = floor["t5"].qr_token
assert len(token) >= 20 and data["tables"][0]["url"] == f"https://menu.example.com/menu/taverna-1?t={token}"
# the snapshot has the hashes only
snap, _ = cloud_sync.menu_snapshot(db)
assert snap["qr"]["ordering"] is False
assert {"id": floor["t5"].id, "label": "T5", "token_hash": table_qr.token_hash(token)} in snap["qr"]["tables"]
assert token not in json.dumps(snap)
# ordering at the table on; a new code for table 5
assert client.put("/api/connect/qr/ordering", headers=owner_h, json={"on": True}).json()["ordering"] is True
rotated = client.post(f"/api/connect/qr/tables/{floor['t5'].id}/rotate", headers=owner_h).json()
db.refresh(floor["t5"])
assert floor["t5"].qr_token != token and rotated["tables"][0]["url"].endswith(floor["t5"].qr_token)
assert cloud_sync.menu_snapshot(db)[0]["qr"]["ordering"] is True
assert err(client.post(f"/api/connect/qr/tables/{floor['old'].id}/rotate", headers=owner_h)) == "reservation.table_unknown"
def test_qr_codes_need_the_key(client, pair, make_user):
token, _ = pair("pos_counter", "Till 2")
jwt = terminal_login(client, token, make_user(role="waiter"))
assert err(client.get("/api/connect/qr", headers={"X-Xenia-Device": token, "Authorization": f"Bearer {jwt}"})) in ("access.denied", "device.out_of_scope")
def test_an_order_at_the_table_goes_on_its_order(client, db, counter, menu, owner_h, cloud, floor, make_user, monkeypatch):
from models.message import StaffMessage
from models.order import Order, OrderItem
from models.user import WaiterZone
import routers.kds as kds
sent = []
real = kds.broadcast_sync
monkeypatch.setattr(kds, "broadcast_sync", lambda kind, data, **kw: (sent.append((kind, data, kw)), real(kind, data, **kw)))
import services.qr_orders as qo # noqa: F401
terrace_waiter, hall_waiter = make_user(role="waiter", nickname="Nikos"), make_user(role="waiter", nickname="Maria")
db.add_all([WaiterZone(waiter_id=terrace_waiter.id, group_id=floor["terrace"].id), WaiterZone(waiter_id=hall_waiter.id, group_id=floor["hall"].id)])
# table 5 already has an order (a waiter's)
open_order = Order(table_id=floor["t5"].id, opened_by=terrace_waiter.id, status="open", business_day_id=counter["day"].id)
db.add(open_order)
db.flush()
db.add(OrderItem(order_id=open_order.id, product_id=menu["burger"].id, added_by=terrace_waiter.id, quantity=1, unit_price=10.0,
status="active", printed=True))
db.commit()
local, at_table = pull_at_table(db, menu, floor["t5"].id)
assert local == open_order.id and at_table == [801]
db.expire_all()
order = db.get(Order, open_order.id)
assert [(i.product_name, i.quantity, i.unit_price) for i in order.items] == [("Burger", 1, 10.0), ("Freddo", 2, 3.0)]
added = [i.id for i in order.items if i.product_name == "Freddo"]
assert cloud["printed"] == [(order.id, added)] # to the kitchen, like a waiter's
assert order.id in kds_ids(client, owner_h)
msg = db.query(StaffMessage).filter(StaffMessage.message_type == "qr_order").one()
assert json.loads(msg.target_waiter_ids) == [terrace_waiter.id] and "T5" in msg.body and "2" in msg.body
assert any(k == "message_sent" and kw.get("user_ids") == [terrace_waiter.id] for k, _, kw in sent)
# a repeated pull doesn't add it twice
again, at_table = pull_at_table(db, menu, floor["t5"].id)
assert again == -order.id and at_table == [801]
assert db.query(OrderItem).filter(OrderItem.order_id == order.id).count() == 2
def test_a_free_table_gets_a_new_order_and_its_zone_waiters_hear(db, counter, menu, cloud, floor, make_user):
from models.message import StaffMessage
from models.order import Order
from models.user import WaiterZone
hall_waiter, everywhere = make_user(role="waiter"), make_user(role="waiter")
db.add_all([WaiterZone(waiter_id=hall_waiter.id, group_id=floor["hall"].id), WaiterZone(waiter_id=everywhere.id, group_id=None)])
db.commit()
local, _ = pull_at_table(db, menu, floor["t9"].id, cloud_id=802, qty=1)
order = db.get(Order, local)
assert (order.table_id, order.source, order.sales_point, order.status) == (floor["t9"].id, "pos", "in_store", "open")
assert [i.unit_price for i in order.items] == [3.0]
msg = db.query(StaffMessage).filter(StaffMessage.message_type == "qr_order").one()
assert sorted(json.loads(msg.target_waiter_ids)) == sorted([hall_waiter.id, everywhere.id])
def test_no_usable_table_it_waits_at_the_counter(client, db, counter, menu, cloud, floor):
from models.order import Order
local, at_table = pull_at_table(db, menu, floor["old"].id, cloud_id=803)
order = db.get(Order, local)
assert at_table == [] and order.table_id is None and order.source == "online" and order.online_status == "pending_acceptance"
assert "T5" in (order.online_customer_notes or "")
assert cloud["printed"] == []