feat: call a waiter from a menu tablet at a table (platform-v2 step 5.7b)
- backend: menu tablet device config `table` (ref, validated against active
tables) and `call_waiter`; GET /api/menu-tablet/menu gives the table and
whether it can call; POST /api/menu-tablet/call sends a `table_call` staff
message ("Table 5: the guests call a waiter.", venue language) to the table's
waiters (its open order's, else the zone's), at most once a minute per tablet
(menu_tablet.call_too_soon with the seconds left; menu_tablet.no_table).
- terminal: "Call a waiter" only on a tablet at a table; "A waiter is on the
way to table 5", then a countdown before it can call again; a failed call
says to ask at the counter.
- waiter: the call shows with its own look and "Open the table".
- manager: tables as the choices of a device setting.
- tests: backend +2 (535 → 533 passed total), e2e menu_tablet.mjs +3.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -113,6 +113,8 @@ CODES: dict[str, tuple[int, str]] = {
|
||||
"signage.content_invalid": (422, "This slide's setting isn't valid ({field}: {reason})."),
|
||||
"signage.order_mismatch": (409, "The playlist changed in the meantime. Reload it and try again."),
|
||||
"signage.weather_offline": (503, "The weather service can't be reached: the venue's server needs internet for it."),
|
||||
"menu_tablet.no_table": (409, "This tablet isn't at a table, so it can't call a waiter."),
|
||||
"menu_tablet.call_too_soon": (429, "A waiter was just called. Try again in {seconds} seconds."),
|
||||
"media.builtin": (409, "Built-in pictures can't be deleted or renamed."),
|
||||
"reservation.not_found": (404, "Booking {reservation_id} not found."),
|
||||
"reservation.status_changed": (409, "This booking was changed on another screen in the meantime (it is now {current})."),
|
||||
|
||||
@@ -97,5 +97,9 @@
|
||||
"qr": {
|
||||
"order_message": "Τραπέζι {table}: νέα παραγγελία από το QR μενού ({count} τεμ.), στάλθηκε στην κουζίνα.",
|
||||
"sender": "QR μενού"
|
||||
},
|
||||
"tablet": {
|
||||
"call_message": "Τραπεζι {table}: οι πελατες καλουν σερβιτορο.",
|
||||
"sender": "Tablet μενου"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -97,5 +97,9 @@
|
||||
"qr": {
|
||||
"order_message": "Table {table}: new order from the QR menu ({count} items), sent to the kitchen.",
|
||||
"sender": "QR menu"
|
||||
},
|
||||
"tablet": {
|
||||
"call_message": "Table {table}: the guests call a waiter.",
|
||||
"sender": "Menu tablet"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -55,6 +55,10 @@ def _ref_exists(source: str, value: int, db) -> bool:
|
||||
if source == "signage_playlists":
|
||||
from models.signage import SignagePlaylist
|
||||
return db.get(SignagePlaylist, value) is not None
|
||||
if source == "tables":
|
||||
from models.table import Table
|
||||
t = db.get(Table, value)
|
||||
return t is not None and bool(t.is_active)
|
||||
if source == "signage_schedules":
|
||||
from models.signage import SignageSchedule
|
||||
return db.get(SignageSchedule, value) is not None
|
||||
|
||||
@@ -31,5 +31,8 @@ MODULE = Module(
|
||||
ConfigField('search', 'bool', default=True, group='use'),
|
||||
ConfigField('languages', 'enum', default='both', choices=('both', 'el', 'en'), group='use'),
|
||||
ConfigField('idle_seconds', 'int', default=120, choices=(0, 30, 60, 120, 300, 600), group='use'),
|
||||
# A tablet on a table (5.7b): only then guests can call a waiter
|
||||
ConfigField('table', 'ref', default=None, choices_from='tables', group='table'),
|
||||
ConfigField('call_waiter', 'bool', default=True, group='table'),
|
||||
)),
|
||||
)
|
||||
|
||||
@@ -9,6 +9,9 @@ products and their categories: no ordering, no tables, no sign-in.
|
||||
of the tablet's sales point and whether it is available; the
|
||||
tablet's settings (device config) and the venue's name.
|
||||
|
||||
POST /api/menu-tablet/call (a tablet set at a table, 5.7b) call a waiter: a message to the
|
||||
table's waiters (its order's, else the zone's), once a minute at most.
|
||||
|
||||
How it looks is the tablet's device config (modules/menu_tablet/manifest.py): view, photos,
|
||||
descriptions, grouping, whose prices, sold-out style, search, one category or all, languages,
|
||||
idle reset, light / dark. Any menu change sends `menu_tablet.changed` to every tablet (main.py).
|
||||
@@ -17,14 +20,21 @@ from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
import threading
|
||||
import time
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from core import sales_points
|
||||
from core.access.deps import require_device
|
||||
from core.errors import XeniaError
|
||||
from database import get_db
|
||||
|
||||
router = APIRouter()
|
||||
CALL_EVERY_S = 60
|
||||
_calls: dict[int, float] = {} # tablet id → its last call (monotonic)
|
||||
_lock = threading.Lock()
|
||||
|
||||
|
||||
def _config(dev) -> dict:
|
||||
@@ -107,11 +117,67 @@ def menu(db: Session = Depends(get_db), dev=Depends(require_device("menu_tablet"
|
||||
shown = [by_id[i] for i in by_id if i in used]
|
||||
prices = dict(zip([p.id for p in shown], unit_prices(db, shown, point))) if point and shown else {}
|
||||
name_row = db.query(PosSettings).filter(PosSettings.key == "venue.name").first()
|
||||
table = _table(db, cfg)
|
||||
return {
|
||||
"venue": {"name": (name_row.value if name_row else "") or None},
|
||||
"table": {"id": table.id, "name": _label(table), "can_call": bool(cfg.get("call_waiter"))} if table else None,
|
||||
"config": cfg,
|
||||
"categories": out_cats,
|
||||
"products": {str(p.id): {"id": p.id, "name": p.name, "description": p.description or None, "tags": _tags(p),
|
||||
"price": round(prices[p.id], 2) if p.id in prices else None, "available": bool(p.is_available),
|
||||
"image": media_store.image_of(p.media)} for p in shown},
|
||||
}
|
||||
|
||||
|
||||
# ── calling a waiter from a tablet at a table (5.7b) ──────────────────────────
|
||||
|
||||
def _table(db, cfg):
|
||||
from models.table import Table
|
||||
t = db.get(Table, cfg["table"]) if cfg.get("table") else None
|
||||
return t if t is not None and t.is_active else None
|
||||
|
||||
|
||||
def _label(table) -> str:
|
||||
from services.table_qr import label
|
||||
return label(table)
|
||||
|
||||
|
||||
def _waiters(db, table) -> list[int]:
|
||||
"""The table's waiters: its open order's, else the waiters whose zone covers the table."""
|
||||
from models.order import Order
|
||||
from services.qr_orders import waiters_for
|
||||
order = db.query(Order).filter(Order.table_id == table.id, Order.status.in_(("open", "partially_paid", "paid"))).first()
|
||||
|
||||
class _NoOrder:
|
||||
waiters = []
|
||||
return waiters_for(db, order or _NoOrder(), table)
|
||||
|
||||
|
||||
@router.post("/call")
|
||||
def call_waiter(db: Session = Depends(get_db), dev=Depends(require_device("menu_tablet"))):
|
||||
"""A guest at the table asks for a waiter. The message reaches the table's waiters' phones."""
|
||||
from core.access.queries import holders_filter
|
||||
from core.i18n import t, venue_language
|
||||
from models.user import User
|
||||
from routers.kds import _save_and_broadcast_message
|
||||
cfg = _config(dev)
|
||||
table = _table(db, cfg)
|
||||
if table is None or not cfg.get("call_waiter"):
|
||||
raise XeniaError("menu_tablet.no_table")
|
||||
now = time.monotonic()
|
||||
with _lock:
|
||||
last = _calls.get(dev.id)
|
||||
if last is not None and now - last < CALL_EVERY_S:
|
||||
raise XeniaError("menu_tablet.call_too_soon", seconds=int(CALL_EVERY_S - (now - last)) + 1)
|
||||
_calls[dev.id] = now
|
||||
sender = db.query(User).filter(holders_filter("core.dashboard.access")).first()
|
||||
lang = venue_language()
|
||||
waiters = _waiters(db, table)
|
||||
_save_and_broadcast_message(db, sender.id if sender else 1, t("tablet.call_message", lang, table=_label(table)), waiters,
|
||||
"table_call", t("tablet.sender", lang), table_ids=[table.id])
|
||||
return {"table": {"id": table.id, "name": _label(table)}, "waiters": len(waiters), "again_in": CALL_EVERY_S}
|
||||
|
||||
|
||||
def reset_calls() -> None:
|
||||
with _lock:
|
||||
_calls.clear()
|
||||
|
||||
@@ -86,3 +86,66 @@ def test_only_menu_tablets(client, pair):
|
||||
token, _ = pair("kds", "Kitchen")
|
||||
assert err(client.get("/api/menu-tablet/menu", headers={"X-Xenia-Device": token})) == "device.out_of_scope"
|
||||
assert err(client.get("/api/menu-tablet/menu")) == "device.not_paired"
|
||||
|
||||
|
||||
# ── 5.7b: calling a waiter from a tablet at a table ─────────────────────────
|
||||
|
||||
@pytest.fixture
|
||||
def table(db):
|
||||
from models.table import Table
|
||||
t = Table(number=5, is_active=True)
|
||||
db.add(t)
|
||||
db.commit()
|
||||
return t
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _calls():
|
||||
import routers.menu_tablet as mt
|
||||
mt.reset_calls()
|
||||
yield
|
||||
mt.reset_calls()
|
||||
|
||||
|
||||
def test_a_tablet_at_a_table_calls_a_waiter(client, owner_h, tablet, menu, table, make_user, db, monkeypatch):
|
||||
"""Done when (5.7b): a tablet set to table 5 calls a waiter and the waiter gets the message."""
|
||||
import routers.kds as kds
|
||||
from models.user import WaiterZone
|
||||
maria = make_user(role="waiter")
|
||||
db.add(WaiterZone(waiter_id=maria.id, group_id=None))
|
||||
db.commit()
|
||||
got = []
|
||||
monkeypatch.setattr(kds, "broadcast_sync", lambda kind, data, **kw: got.append((kind, data, kw)), raising=False)
|
||||
assert client.get("/api/menu-tablet/menu", headers=tablet["h"]).json()["table"] is None
|
||||
assert err(client.post("/api/menu-tablet/call", headers=tablet["h"])) == "menu_tablet.no_table"
|
||||
client.patch(f"/api/devices/{tablet['id']}", headers=owner_h, json={"config": {"table": table.id}})
|
||||
assert client.get("/api/menu-tablet/menu", headers=tablet["h"]).json()["table"] == {"id": table.id, "name": "5", "can_call": True}
|
||||
r = client.post("/api/menu-tablet/call", headers=tablet["h"])
|
||||
assert r.status_code == 200 and r.json()["waiters"] >= 1 and r.json()["again_in"] == 60
|
||||
from models.message import StaffMessage
|
||||
msg = db.query(StaffMessage).order_by(StaffMessage.id.desc()).first()
|
||||
assert msg.message_type == "table_call" and msg.body == "Table 5: the guests call a waiter." and str(maria.id) in msg.target_waiter_ids
|
||||
assert str(table.id) in msg.table_ids
|
||||
# once a minute at most
|
||||
again = client.post("/api/menu-tablet/call", headers=tablet["h"])
|
||||
assert again.status_code == 429 and err(again) == "menu_tablet.call_too_soon" and again.json()["error"]["params"]["seconds"] <= 60
|
||||
# the option off: no calls, the menu says so
|
||||
client.patch(f"/api/devices/{tablet['id']}", headers=owner_h, json={"config": {"table": table.id, "call_waiter": False}})
|
||||
assert client.get("/api/menu-tablet/menu", headers=tablet["h"]).json()["table"]["can_call"] is False
|
||||
assert err(client.post("/api/menu-tablet/call", headers=tablet["h"])) == "menu_tablet.no_table"
|
||||
|
||||
|
||||
def test_the_tables_open_order_decides_who_hears_it(client, owner_h, tablet, table, make_user, db):
|
||||
from models.order import Order, OrderWaiter
|
||||
from models.message import StaffMessage
|
||||
nikos, eleni = make_user(role="waiter"), make_user(role="waiter")
|
||||
order = Order(table_id=table.id, opened_by=nikos.id, status="open", order_type="dine_in")
|
||||
db.add(order)
|
||||
db.flush()
|
||||
db.add(OrderWaiter(order_id=order.id, waiter_id=nikos.id))
|
||||
db.commit()
|
||||
client.patch(f"/api/devices/{tablet['id']}", headers=owner_h, json={"config": {"table": table.id}})
|
||||
assert client.post("/api/menu-tablet/call", headers=tablet["h"]).status_code == 200
|
||||
msg = db.query(StaffMessage).order_by(StaffMessage.id.desc()).first()
|
||||
assert msg.target_waiter_ids == f"[{nikos.id}]" and eleni.id
|
||||
assert err(client.patch(f"/api/devices/{tablet['id']}", headers=owner_h, json={"config": {"table": 99999}})) == "validation.device_config"
|
||||
|
||||
Reference in New Issue
Block a user