Owner 2026-11-23 (plan 6F.6). Venue setting payments.split_amount (off | two_equal | two_custom |
multiple_equal, each level with the ones before; default off) and payments.split_max_parts (10);
key ordering.payments.split_amount (everyone who takes payments; Alembic 0050 grants it).
POST /api/orders/{id}/split-bills settles the chosen unpaid lines (status 'split': sold, no shift,
no payment method) and adds part lines (system product split_part, "Split bill 1/3", printed and
served; equal parts with the remainder on the last, or two parts with part 1 typed). Parts are paid
like any line (cash, card, tab). POST .../split-bills/{bill}/undo while no part is paid or tabbed.
Counting (services/sales.py): settled lines are the sales, parts never (a refunded part comes off
the settled lines by share); drawers and payment methods count the parts. Older reports use
split_bills.sold_filter / counts_as_sale. Locks: parts can't be cancelled, moved, combined or
re-priced; settled lines are no longer active; closing or cancelling an order with unpaid parts is
refused. Fiscal: one receipt with the settled lines when the last part is paid, with each method's
amount (txt driver: CD per card amount, then CR for cash).
Waiter: Pay -> "Split the amount" (pre-filled from the customers), the split bill above the lines
with Undo. Counter: "By amount" in the payment (quick sale split and paid at once, Q-4; a table's
lines split then paid). Manager: the pay dialog splits, the order shows its split bills, Settings ->
Operation card. Shared rules in @xenia/ordering/split.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
407 lines
19 KiB
Python
407 lines
19 KiB
Python
"""The menu tablet (plan step 5.7a): the venue's menu on a tablet, for staff ("how much is the
|
|
steak?") and for guests (a menu at the entrance, later a digital menu at the table). Just the
|
|
products and their categories: no ordering, no tables, no sign-in.
|
|
|
|
GET /api/menu-tablet/menu (a paired menu tablet) the categories in the catalogue's order
|
|
(sub-categories after their parent), each with its products in its
|
|
own order (a product listed in several categories shows in each),
|
|
the products once with name, description, tags, photo, the price
|
|
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.
|
|
|
|
Ordering at the table (6.6, D-30, services/tablet_orders.py), a tablet at a table with
|
|
"Guests can order" on:
|
|
POST /quote {lines} the cart priced by the server (the counter's lines by id)
|
|
POST /order {lines, note} sent to the kitchen, or waiting for a waiter (the rules)
|
|
GET /order/{id} what happened to one of this tablet's orders
|
|
GET /bill · POST /bill the table's bill so far · ask for the bill (a message)
|
|
Staff (phones): GET /requests?table_id=, POST /requests/{id}/accept | decline (waiting orders).
|
|
The venue's rules: GET / PUT /ordering (menu_tablet.manage).
|
|
|
|
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).
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
|
|
import threading
|
|
import time
|
|
|
|
from fastapi import APIRouter, Depends
|
|
from pydantic import BaseModel, Field
|
|
from typing import List, Optional
|
|
from sqlalchemy.orm import Session
|
|
|
|
from core import allergens, menu_languages, sales_points
|
|
from core.access.deps import require
|
|
from services import tablet_orders
|
|
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:
|
|
from core.modules.device_config import effective, for_app
|
|
return effective(for_app("menu_tablet"), dev.config)
|
|
|
|
|
|
def tablets(db) -> list[int]:
|
|
from models.device import Device
|
|
return [i for (i,) in db.query(Device.id).filter(Device.app_key == "menu_tablet", Device.revoked_at.is_(None))]
|
|
|
|
|
|
def menu_changed(db) -> None:
|
|
"""Products, categories or prices changed (main.py): every tablet reads its menu again."""
|
|
from services.ws_bus import broadcast_sync
|
|
ids = tablets(db)
|
|
if ids:
|
|
broadcast_sync("menu_tablet.changed", {}, device_ids=ids)
|
|
|
|
|
|
def _tags(p) -> list[str]:
|
|
raw = getattr(p, "tags", None)
|
|
if isinstance(raw, str):
|
|
try:
|
|
raw = json.loads(raw)
|
|
except ValueError:
|
|
raw = []
|
|
return [t for t in (raw or []) if isinstance(t, str)]
|
|
|
|
|
|
@router.get("/menu")
|
|
def menu(db: Session = Depends(get_db), dev=Depends(require_device("menu_tablet"))):
|
|
from models.product import Category, Product, ProductCategory
|
|
from models.settings import PosSettings
|
|
from services import media as media_store
|
|
from services.pos_cart import unit_prices
|
|
cfg = _config(dev)
|
|
cats = db.query(Category).order_by(Category.sort_order, Category.name).all()
|
|
by_parent: dict = {}
|
|
for c in cats:
|
|
by_parent.setdefault(c.parent_id, []).append(c)
|
|
ordered = [] # parents, each followed by its sub-categories
|
|
|
|
def walk(parent_id, depth):
|
|
for c in by_parent.get(parent_id, []):
|
|
ordered.append((c, depth))
|
|
walk(c.id, depth + 1)
|
|
walk(None, 0)
|
|
if cfg.get("category"):
|
|
root = next(((c, d) for c, d in ordered if c.id == cfg["category"]), None)
|
|
keep = set()
|
|
if root:
|
|
stack = [root[0].id]
|
|
while stack:
|
|
cid = stack.pop()
|
|
keep.add(cid)
|
|
stack.extend(x.id for x in by_parent.get(cid, []))
|
|
ordered = [(c, d) for c, d in ordered if c.id in keep]
|
|
|
|
point = None if cfg["sales_point"] == "none" else cfg["sales_point"]
|
|
products = db.query(Product).filter(Product.lifecycle_status == "active", Product.system_key.is_(None)).all()
|
|
if point:
|
|
products = [p for p in products if sales_points.is_sold_at(p, point)]
|
|
if cfg["sold_out"] == "hide":
|
|
products = [p for p in products if p.is_available]
|
|
by_id = {p.id: p for p in products}
|
|
members = db.query(ProductCategory).order_by(ProductCategory.sort_order).all()
|
|
in_cat: dict = {}
|
|
for m in members:
|
|
if m.product_id in by_id:
|
|
in_cat.setdefault(m.category_id, []).append(m.product_id)
|
|
|
|
out_cats, used = [], set()
|
|
for c, depth in ordered:
|
|
ids = in_cat.get(c.id, [])
|
|
has_sub = any(in_cat.get(x.id) for x in by_parent.get(c.id, []))
|
|
if ids or has_sub:
|
|
out_cats.append({"id": c.id, "name": c.name, "names": menu_languages.texts(c.name, menu_languages.of(c), "name"),
|
|
"parent_id": c.parent_id, "depth": depth, "products": ids})
|
|
used.update(ids)
|
|
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)
|
|
ordering = bool(table and cfg.get("ordering"))
|
|
choices = {}
|
|
if ordering: # what a guest can choose (the counter's shape)
|
|
from routers.pos import _product_out
|
|
order_prices = dict(zip([p.id for p in shown], unit_prices(db, shown, tablet_orders.POINT))) if shown else {}
|
|
choices = {str(p.id): _product_out(p, order_prices.get(p.id, p.base_price)) for p in shown
|
|
if p.is_available and sales_points.is_sold_at(p, tablet_orders.POINT)}
|
|
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")),
|
|
"can_order": ordering, "can_see_bill": bool(cfg.get("bill"))} if table else None,
|
|
"ordering": {**tablet_orders.rules(db, cfg), "choices": choices} if ordering 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),
|
|
"allergens": allergens.of(p), **menu_languages.product_texts(p, customer=False),
|
|
"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()
|
|
|
|
|
|
# ── ordering at the table (6.6, D-30) ─────────────────────────────────────────
|
|
|
|
class LinesBody(BaseModel):
|
|
lines: List[dict] = Field(min_length=1, max_length=100)
|
|
note: Optional[str] = Field(default=None, max_length=300)
|
|
|
|
|
|
def _ordering_table(db, dev):
|
|
cfg = _config(dev)
|
|
table = _table(db, cfg)
|
|
if table is None or not cfg.get("ordering"):
|
|
raise XeniaError("menu_tablet.no_ordering")
|
|
return cfg, table
|
|
|
|
|
|
def _lines(db, body: LinesBody):
|
|
"""The guest's lines, resolved and checked by the server; never a discount or a price."""
|
|
from services import pos_cart
|
|
out = []
|
|
for n, raw in enumerate(body.lines):
|
|
raw = {k: v for k, v in (raw if isinstance(raw, dict) else {}).items() if k in ("product_id", "quantity", "quick", "options", "prefs", "removed", "notes")}
|
|
line = pos_cart.resolve_line(db, raw, n)
|
|
if not line.product.is_available or not sales_points.is_sold_at(line.product, tablet_orders.POINT):
|
|
raise XeniaError("order.product_unavailable", product_id=line.product.id)
|
|
out.append(line)
|
|
return out
|
|
|
|
|
|
@router.post("/quote")
|
|
def quote(body: LinesBody, db: Session = Depends(get_db), dev=Depends(require_device("menu_tablet"))):
|
|
from services import pos_cart
|
|
_ordering_table(db, dev)
|
|
return pos_cart.quote(db, _lines(db, body), "here", point=tablet_orders.POINT)
|
|
|
|
|
|
@router.post("/order")
|
|
def send_order(body: LinesBody, db: Session = Depends(get_db), dev=Depends(require_device("menu_tablet"))):
|
|
"""The guests' order: on the table's order and in the kitchen, or waiting for a waiter."""
|
|
from models.tablet_order import TabletOrder
|
|
from services import pos_cart
|
|
cfg, table = _ordering_table(db, dev)
|
|
rules = tablet_orders.rules(db, cfg)
|
|
lines = _lines(db, body)
|
|
tablet_orders.check(db, dev.id, lines, rules)
|
|
if rules["no_order"] == "refuse" and tablet_orders.open_order_of(db, table) is None:
|
|
raise XeniaError("menu_tablet.table_closed")
|
|
priced = pos_cart.quote(db, lines, "here", point=tablet_orders.POINT)
|
|
row = TabletOrder(device_id=dev.id, table_id=table.id, note=(body.note or "").strip() or None, total=priced["total"],
|
|
lines=[{**{k: v for k, v in raw.items() if k in ("product_id", "quantity", "quick", "options", "prefs", "removed", "notes")},
|
|
"name": q["name"], "quantity": q["quantity"], "total": q["total"],
|
|
"entries": [e["name"] for e in q["entries"]], "removed_names": q["removed"]}
|
|
for raw, q in zip(body.lines, priced["lines"])],
|
|
status="waiting")
|
|
db.add(row)
|
|
db.commit()
|
|
actor = tablet_orders.system_user(db)
|
|
count = sum(line.quantity for line in lines)
|
|
if rules["confirm"] == "kitchen":
|
|
try:
|
|
tablet_orders.place(db, row, table, lines, actor=actor, no_order=rules["no_order"])
|
|
except XeniaError:
|
|
db.delete(row)
|
|
db.commit()
|
|
raise
|
|
tablet_orders.tell_waiters(db, table, "tablet.order_sent", actor.id, count=count)
|
|
else:
|
|
tablet_orders.tell_waiters(db, table, "tablet.order_waiting", actor.id, count=count)
|
|
tablet_orders.announce(row)
|
|
return tablet_orders.out(db, row)
|
|
|
|
|
|
@router.get("/order/{order_id}")
|
|
def tablet_order(order_id: int, db: Session = Depends(get_db), dev=Depends(require_device("menu_tablet"))):
|
|
from models.tablet_order import TabletOrder
|
|
row = db.get(TabletOrder, order_id)
|
|
if row is None or row.device_id != dev.id:
|
|
raise XeniaError("menu_tablet.order_not_found")
|
|
return tablet_orders.out(db, row)
|
|
|
|
|
|
@router.get("/bill")
|
|
def bill(db: Session = Depends(get_db), dev=Depends(require_device("menu_tablet"))):
|
|
"""The table's bill so far: the open order's lines (cancelled ones left out) and what's left to pay."""
|
|
cfg = _config(dev)
|
|
table = _table(db, cfg)
|
|
if table is None or not cfg.get("bill"):
|
|
raise XeniaError("menu_tablet.no_table")
|
|
order = tablet_orders.open_order_of(db, table)
|
|
if order is None:
|
|
return {"lines": [], "total": 0, "paid": 0, "due": 0}
|
|
lines = []
|
|
for i in order.items:
|
|
if i.status in ("cancelled", "split"): # 6F.6: a split bill's parts stand for the lines it settled
|
|
continue
|
|
unit = (i.unit_price or 0) + (i.price_adjustment or 0)
|
|
texts = menu_languages.product_texts(i.product, customer=False) if i.product else {}
|
|
lines.append({"name": i.product_name or (i.product.name if i.product else ""), "names": texts.get("names"),
|
|
"quantity": i.quantity, "total": round(unit * i.quantity, 2), "paid": i.status == "paid"})
|
|
total = round(sum(x["total"] for x in lines), 2)
|
|
paid = round(sum(x["total"] for x in lines if x["paid"]), 2)
|
|
return {"lines": lines, "total": total, "paid": paid, "due": round(total - paid, 2)}
|
|
|
|
|
|
_bills: dict[int, float] = {}
|
|
|
|
|
|
@router.post("/bill")
|
|
def ask_for_bill(db: Session = Depends(get_db), dev=Depends(require_device("menu_tablet"))):
|
|
"""The guests ask for the bill: a message to the table's waiters, once a minute at most."""
|
|
cfg = _config(dev)
|
|
table = _table(db, cfg)
|
|
if table is None or not cfg.get("bill"):
|
|
raise XeniaError("menu_tablet.no_table")
|
|
now = time.monotonic()
|
|
with _lock:
|
|
last = _bills.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)
|
|
_bills[dev.id] = now
|
|
actor = tablet_orders.system_user(db)
|
|
from core.i18n import t, venue_language
|
|
from routers.kds import _save_and_broadcast_message
|
|
lang = venue_language()
|
|
_save_and_broadcast_message(db, actor.id, t("tablet.bill_message", lang, table=_label(table)), tablet_orders.waiters(db, table),
|
|
"table_call", t("tablet.sender", lang), table_ids=[table.id])
|
|
return {"again_in": CALL_EVERY_S}
|
|
|
|
|
|
# ── staff: the orders that wait for a waiter ──────────────────────────────────
|
|
|
|
class DeclineBody(BaseModel):
|
|
reason: Optional[str] = Field(default=None, max_length=200)
|
|
|
|
|
|
@router.get("/requests")
|
|
def waiting(table_id: Optional[int] = None, db: Session = Depends(get_db), user=Depends(require("ordering.orders.open"))):
|
|
from models.tablet_order import TabletOrder
|
|
tablet_orders.expire_waiting(db)
|
|
q = db.query(TabletOrder).filter(TabletOrder.status == "waiting")
|
|
if table_id is not None:
|
|
q = q.filter(TabletOrder.table_id == table_id)
|
|
return [tablet_orders.out(db, r) for r in q.order_by(TabletOrder.created_at).all()]
|
|
|
|
|
|
def _waiting(db, request_id: int):
|
|
from models.tablet_order import TabletOrder
|
|
row = db.get(TabletOrder, request_id)
|
|
if row is None:
|
|
raise XeniaError("menu_tablet.order_not_found")
|
|
if row.status != "waiting":
|
|
raise XeniaError("menu_tablet.order_answered")
|
|
return row
|
|
|
|
|
|
@router.post("/requests/{request_id}/accept")
|
|
def accept(request_id: int, db: Session = Depends(get_db), user=Depends(require("ordering.orders.open"))):
|
|
"""A waiter confirms the guests' order: on the table's order and in the kitchen."""
|
|
from core.timeutil import utcnow
|
|
from models.device import Device
|
|
from models.table import Table
|
|
from services import pos_cart
|
|
row = _waiting(db, request_id)
|
|
table = db.get(Table, row.table_id) if row.table_id else None
|
|
if table is None or not table.is_active:
|
|
raise XeniaError("menu_tablet.no_table")
|
|
dev = db.get(Device, row.device_id) if row.device_id else None
|
|
rules = tablet_orders.rules(db, _config(dev) if dev is not None else {})
|
|
lines = [pos_cart.resolve_line(db, {k: v for k, v in raw.items() if k in ("product_id", "quantity", "quick", "options", "prefs", "removed", "notes")}, n)
|
|
for n, raw in enumerate(row.lines)]
|
|
row.decided_by_id, row.decided_at = user.id, utcnow()
|
|
# the waiter accepts on the table's behalf: opening the table is theirs (refuse only stops guests)
|
|
tablet_orders.place(db, row, table, lines, actor=user, no_order="open" if rules["no_order"] == "refuse" else rules["no_order"])
|
|
tablet_orders.announce(row)
|
|
return tablet_orders.out(db, row)
|
|
|
|
|
|
@router.post("/requests/{request_id}/decline")
|
|
def decline(request_id: int, body: DeclineBody, db: Session = Depends(get_db), user=Depends(require("ordering.orders.open"))):
|
|
from core.timeutil import utcnow
|
|
row = _waiting(db, request_id)
|
|
row.status, row.reason = "declined", (body.reason or "").strip() or None
|
|
row.decided_by_id, row.decided_at = user.id, utcnow()
|
|
db.commit()
|
|
tablet_orders.announce(row)
|
|
return tablet_orders.out(db, row)
|
|
|
|
|
|
# ── the venue's rules ────────────────────────────────────────────────────────
|
|
|
|
@router.get("/ordering")
|
|
def ordering_rules(db: Session = Depends(get_db), user=Depends(require("menu_tablet.manage"))):
|
|
return tablet_orders.venue_rules(db)
|
|
|
|
|
|
@router.put("/ordering")
|
|
def save_ordering_rules(body: tablet_orders.Rules, db: Session = Depends(get_db), user=Depends(require("menu_tablet.manage"))):
|
|
return tablet_orders.save_venue_rules(db, body)
|