feat(terminal): counter POS screen with server-priced cart and shift gate (platform-v2 3.3a)

- Backend /api/pos (pos_counter): session (business day, the cashier's own shift,
  self-start, who can open the day), menu (sellable products with every kind of choice,
  no costs; price now from the pricing engine), quote (lines by id → the waiter's
  selected_options entries with DB prices → resolve_price as orders do; pos.line_invalid).
- POS device settings: default order type, start category, receipt printer (new ref
  sources categories / printers, also in the manager's Devices dialogs).
- Terminal apps/pos: shift gate (start shift with drawer cash), categories, search,
  product grid, price check, options dialog, cart priced by the backend.
- Tests: backend test_pos (13), terminal pos.test.mjs, manager refOptions,
  terminal.mjs +10 POS checks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-14 21:55:30 +02:00
co-authored by Claude Opus 5.5
parent b1112b249e
commit 17bee66df1
25 changed files with 1556 additions and 21 deletions
+1
View File
@@ -66,6 +66,7 @@ CODES: dict[str, tuple[int, str]] = {
"auth.support_not_configured": (503, "Support access isn't set up on this site."),
"auth.support_code_invalid": (401, "That support code is wrong or has expired. Ask for a new challenge."),
"auth.support_rate_limited": (429, "Too many support challenges. Wait a few minutes and try again."),
"pos.line_invalid": (422, "Cart line {line} can't be sold as chosen ({reason})."),
"kds.item_not_found": (404, "Item {item_id} not found on this order."),
"kds.item_claimed": (409, "{name} is already on this item."),
"kds.claim_needs_staff": (403, "Only a staff member can claim an item."),
+9 -1
View File
@@ -14,7 +14,8 @@ Agent notes:
field needs its label in packages/i18n/locales/{en,el}/modules.json
(`<app>.config.<key>.label`, plus `.choices.<value>` per choice); test_module_texts fails
otherwise. The manager renders the fields generically (DeviceConfigFields.jsx).
- `ref` sources: "prep_zones" (PrepZone ids), "devices:<app_key>" (live devices of that app).
- `ref` sources: "prep_zones" (PrepZone ids), "categories" (Category ids), "printers" (active
Printer ids), "devices:<app_key>" (live devices of that app).
- `color` = "#rrggbb" (lower-cased when stored). `after="<key>"` (int fields): the value must be
greater than that field's (stored or default) value, e.g. KDS age thresholds; a stored
config that breaks the order reads back as the defaults of every ordered field (3.2a).
@@ -44,6 +45,13 @@ def _ref_exists(source: str, value: int, db) -> bool:
if source == "prep_zones":
from models.prep_zone import PrepZone
return db.get(PrepZone, value) is not None
if source == "categories":
from models.product import Category
return db.get(Category, value) is not None
if source == "printers":
from models.printer import Printer
p = db.get(Printer, value)
return p is not None and bool(p.is_active)
if source.startswith("devices:"):
from models.device import Device
d = db.get(Device, value)
+1 -1
View File
@@ -70,7 +70,7 @@ class ConfigField:
choices: tuple = () # enum, or int limited to these values
min: Optional[int] = None # int
max: Optional[int] = None # int
choices_from: Optional[str] = None # ref: "prep_zones" | "devices:<app_key>"; value = id or None
choices_from: Optional[str] = None # ref: "prep_zones" | "categories" | "printers" | "devices:<app_key>"; value = id or None
group: Optional[str] = None # section in the manager's dialogs (3.2a)
after: Optional[str] = None # int: must be greater than this other field (age thresholds)
+16 -3
View File
@@ -1,15 +1,25 @@
"""Module manifest — see core/modules/model.py and APPS_PLATFORM §4."""
from core.modules.model import ConfigField, DeviceApp, Limit, Module, Perm
from core.modules.model import ConfigField, DeviceApp, Limit, Module, Mount, Perm
# Back to the sign-in screen after this many idle minutes (shared screens; 0 = never). Used by
# the terminal from step 3.1c.
AUTO_SIGN_OUT = ConfigField('auto_sign_out_minutes', 'int', default=0, choices=(0, 2, 5, 10, 30, 60))
# A counter screen's settings (plan step 3.3a): the order type a sale starts as, the receipt
# printer whose drawer opens on cash payments (used from 3.3b), and the category the product
# grid opens on (none = all products).
POS_CONFIG = (
ConfigField('default_order_type', 'enum', default='takeaway', choices=('takeaway', 'here')),
ConfigField('start_category_id', 'ref', default=None, choices_from='categories'),
ConfigField('receipt_printer_id', 'ref', default=None, choices_from='printers'),
AUTO_SIGN_OUT,
)
MODULE = Module(
key='pos_counter',
kind='app',
name='Counter POS',
description='A counter terminal for quick orders (coming in phase 3).',
description='A counter terminal for quick sales, tables, price checks and online orders.',
depends=('ordering',),
permissions=(
Perm('pos_counter.access', 'Use the counter POS', roles=('owner', 'store_manager', 'barista', 'barman', 'waiter')),
@@ -18,5 +28,8 @@ MODULE = Module(
Limit('devices', 'Number of counter terminals', free=0, licensed_default=1),
),
device_app=DeviceApp(login_modes=('pin', 'tap', 'password'), scope=('pos_counter.*', 'ordering.*'),
config=(AUTO_SIGN_OUT,)),
config=POS_CONFIG),
routers=(
Mount('routers.pos', '/api/pos'),
),
)
+160
View File
@@ -0,0 +1,160 @@
"""Counter POS (plan step 3.3a, D-26): what a paired counter screen needs, in its own scope.
GET /api/pos/session the signed-in cashier's shift and the business day (shift gate)
GET /api/pos/menu categories and products to sell, with options and today's price
POST /api/pos/quote a cart priced by the backend (services/pos_cart.py)
Prices are never computed on the screen: the menu's `price` is the pricing engine's answer for
one unit with no options right now (happy hours, price groups), and the cart is priced with
POST /quote. The menu leaves out what a cashier doesn't need (costs, fiscal fields, digital
menu overrides). Starting a shift uses POST /api/shifts/start (ordering, in the POS scope).
"""
from __future__ import annotations
from typing import List, Literal, Optional
from fastapi import APIRouter, Depends, Request
from pydantic import BaseModel, Field
from sqlalchemy.orm import Session, selectinload
from core.access.check import holds
from core.access.deps import require
from core.errors import XeniaError
from database import get_db
from services import pos_cart
router = APIRouter()
ACCESS = "pos_counter.access"
def _iso(dt):
return (dt.isoformat() + "Z") if dt is not None and dt.tzinfo is None else (dt.isoformat() if dt else None)
# ── session (shift gate) ─────────────────────────────────────────────────────
@router.get("/session")
def pos_session(db: Session = Depends(get_db), user=Depends(require(ACCESS))):
"""The open business day, the cashier's own open shift, whether they may start one
themselves, and who can open the day (shown when it's closed)."""
from core.access.queries import users_with_key
from models.business_day import BusinessDay
from models.settings import PosSettings
from models.shift import WaiterShift
from models.user import User
day = db.query(BusinessDay).filter(BusinessDay.status == "open").first()
shift = db.query(WaiterShift).filter(WaiterShift.waiter_id == user.id, WaiterShift.ended_at.is_(None)).first() \
if isinstance(user, User) else None
row = db.get(PosSettings, "shifts.waiter_self_start")
self_start = holds(user, "core.dashboard.access") or (row is not None and row.value == "true")
openers = [u.nickname or u.full_name for u in users_with_key(db, "ordering.business_day.manage").order_by(User.full_name)
if u.role != "superadmin"]
return {
"business_day": {"id": day.id, "business_date": str(day.business_date) if day.business_date else None,
"opened_at": _iso(day.opened_at)} if day else None,
"shift": {"id": shift.id, "started_at": _iso(shift.started_at), "starting_cash": shift.starting_cash} if shift else None,
"self_start": bool(self_start),
"day_openers": openers,
}
# ── menu ────────────────────────────────────────────────────────────────────
def _subs_out(raw):
return [{"name": s["name"], "price": round(float(s.get("extra_cost") or 0.0), 2), "is_default": bool(s.get("is_default"))}
for s in pos_cart._subs(raw)]
def _product_out(p, price: float) -> dict:
shared = lambda ps: pos_cart._shared(ps.shared_subset) # noqa: E731
return {
"id": p.id, "name": p.name, "description": p.description, "image_url": p.image_url,
"price": round(price, 2), "base_price": round(p.base_price, 2), "unit_type": p.unit_type or "piece",
"tags": _tags(p.tags),
"primary_category_id": p.primary_category_id,
"categories": [{"category_id": m.category_id, "sort_order": m.sort_order} for m in p.memberships],
"sort_order": p.sort_order,
"quick": [{"id": q.id, "name": q.name, "price": round(q.price or 0.0, 2), "allow_multiple": bool(q.allow_multiple)}
for q in sorted(p.quick_options, key=lambda q: q.sort_order)],
"options": [{"id": o.id, "name": o.name, "price": round(o.extra_cost or 0.0, 2), "allow_multiple": bool(o.allow_multiple),
"multi_select": bool(o.multi_select), "subs": _subs_out(o.sub_choices)}
for o in p.options],
"prefs": [{"id": ps.id, "name": ps.name, "default_choice_id": ps.default_choice_id, "multi": bool(ps.allow_multi_select),
"shared": ({"name": shared(ps)["name"], "subs": _subs_out(shared(ps)["choices"])} if shared(ps) else None),
"choices": [{"id": c.id, "name": c.name, "price": round(c.extra_cost or 0.0, 2),
"disables_shared": bool(c.disables_subset), "subs": _subs_out(c.sub_choices)}
for c in ps.choices]}
for ps in p.preference_sets],
"ingredients": [{"id": i.id, "name": i.name} for i in p.ingredients],
}
def _tags(raw):
import json
try:
v = json.loads(raw) if isinstance(raw, str) else (raw or [])
except ValueError:
return []
return [t for t in v if isinstance(t, str)]
@router.get("/menu")
def pos_menu(request: Request, db: Session = Depends(get_db), user=Depends(require(ACCESS))):
"""Categories and the products a cashier can sell (available, active, not service
items), each with its price right now for one unit without options (pricing engine)."""
from models.product import Category, Product, ProductPreferenceSet
from core.access.context import current_device
from core.modules import device_config
dev = current_device(request, db)
settings = device_config.effective(device_config.for_app("pos_counter"), dev.config if dev is not None else None, db)
products = (db.query(Product)
.filter(Product.is_available.is_(True), Product.lifecycle_status == "active", Product.is_service_item.is_(False))
.options(selectinload(Product.quick_options), selectinload(Product.options), selectinload(Product.ingredients),
selectinload(Product.preference_sets).selectinload(ProductPreferenceSet.choices),
selectinload(Product.memberships))
.order_by(Product.sort_order, Product.name).all())
lines = [pos_cart.Line(product=p, quantity=1) for p in products]
prices = pos_cart.price_lines(db, lines, settings["default_order_type"]) if lines else []
cats = db.query(Category).order_by(Category.sort_order, Category.name).all()
return {
"settings": settings,
"categories": [{"id": c.id, "name": c.name, "color": c.color, "parent_id": c.parent_id, "sort_order": c.sort_order}
for c in cats],
"products": [_product_out(p, unit) for p, (unit, _) in zip(products, prices)],
}
# ── quote ───────────────────────────────────────────────────────────────────
class QuoteBody(BaseModel):
order_type: Literal["takeaway", "here"] = "takeaway"
lines: List[dict] = Field(default_factory=list, max_length=200)
def _adjustments(db, events) -> list[dict]:
from models.pricing import PriceModifier
out = []
for e in events:
if not e.delta_amount:
continue
m = db.get(PriceModifier, e.modifier_id) if e.modifier_id else None
out.append({"label": m.name if m is not None else e.event_type, "delta": round(e.delta_amount, 2)})
return out
@router.post("/quote")
def pos_quote(body: QuoteBody, db: Session = Depends(get_db), user=Depends(require(ACCESS))):
"""The cart priced exactly as the order will be: per line the unit price (base + options,
then price groups/modifiers), its total, what was chosen (names) and any adjustment."""
lines = [pos_cart.resolve_line(db, raw if isinstance(raw, dict) else {}, n) for n, raw in enumerate(body.lines)]
priced = pos_cart.price_lines(db, lines, body.order_type) if lines else []
out = []
for line, (unit, events) in zip(lines, priced):
out.append({
"product_id": line.product.id, "name": line.product.name, "quantity": line.quantity,
"base_price": round(line.product.base_price, 2), "extra": line.extra,
"unit_price": round(unit, 2), "total": round(unit * line.quantity, 2),
"entries": [{"name": e["name"], "price": e["price_delta"], "type": e["type"]} for e in line.entries],
"removed": line.removed, "notes": line.notes, "adjustments": _adjustments(db, events),
})
return {"order_type": body.order_type, "lines": out, "total": round(sum(x["total"] for x in out), 2)}
+189
View File
@@ -0,0 +1,189 @@
"""The counter POS's cart, priced by the backend (plan step 3.3a, D-26).
The POS never computes a price. It sends what was chosen by id (and sub-choices by name, as
they are stored), and this module turns that into the same `selected_options` entries the
waiter app sends (types quick | extra | extra_sub | pref | pref_sub) with the prices taken
from the database, then runs the pricing engine (services/pricing.py::resolve_price) exactly
as POST /api/orders/{id}/items does. 3.3b sends the same lines to create the order.
A line:
{product_id, quantity, notes?,
quick: [{id, qty?}], quick add-ons (qty only if allow_multiple)
options: [{id, qty?, subs?: [name]}], extras; one sub unless multi_select
prefs: [{set_id, choices: [{id, qty?, sub?: name}], shared?: name}],
removed: [ingredient_id]}
Rules (the same as the waiter's options dialog, waiter_pwa ItemOptionsModal.jsx):
- every preference set needs a choice (one, or one or more for allow_multi_select sets);
- a choice/extra with sub-choices needs one of them (the default is pre-selected on screen);
- a set's shared sub-choice applies unless the chosen choice `disables_subset`;
- quantities: per-choice qty only on multi-select sets, per-add-on qty only on allow_multiple.
Anything else → XeniaError("pos.line_invalid", line=n, reason=...), reason one of
product_unavailable | unknown_quick | unknown_option | unknown_choice | unknown_sub |
choice_required | sub_required | unknown_ingredient | quantity.
"""
from __future__ import annotations
import json
from dataclasses import dataclass, field
from typing import Optional
from core.errors import XeniaError
CHANNELS = {"here": "pos", "takeaway": "takeaway"}
def _subs(raw) -> list[dict]:
if not raw:
return []
try:
data = json.loads(raw) if isinstance(raw, str) else raw
except ValueError:
return []
return [s for s in (data or []) if isinstance(s, dict) and s.get("name")]
def _shared(raw) -> Optional[dict]:
if not raw:
return None
try:
data = json.loads(raw) if isinstance(raw, str) else raw
except ValueError:
return None
return data if isinstance(data, dict) and _subs(data.get("choices")) else None
@dataclass
class Line:
"""A resolved line: what the order item will be."""
product: object
quantity: float
entries: list = field(default_factory=list) # selected_options entries
removed: list = field(default_factory=list) # ingredient names
notes: Optional[str] = None
@property
def extra(self) -> float:
return round(sum(e["price_delta"] for e in self.entries), 2)
def _bad(n: int, reason: str):
return XeniaError("pos.line_invalid", line=n, reason=reason)
def _qty(value, n: int, allowed: bool) -> int:
q = value if value is not None else 1
if isinstance(q, bool) or not isinstance(q, int) or q < 1 or (q > 1 and not allowed) or q > 99:
raise _bad(n, "quantity")
return q
def _sub(subs: list[dict], name, n: int) -> Optional[dict]:
if name is None:
return None
found = next((s for s in subs if s["name"] == name), None)
if found is None:
raise _bad(n, "unknown_sub")
return found
def resolve_line(db, raw: dict, n: int) -> Line:
from models.product import Product
product = db.get(Product, raw.get("product_id")) if isinstance(raw.get("product_id"), int) else None
if product is None or not product.is_available or product.lifecycle_status != "active":
raise _bad(n, "product_unavailable")
quantity = raw.get("quantity", 1)
if isinstance(quantity, bool) or not isinstance(quantity, (int, float)) or quantity <= 0 or quantity > 999:
raise _bad(n, "quantity")
line = Line(product=product, quantity=quantity, notes=(raw.get("notes") or "").strip() or None)
quick = {q.id: q for q in product.quick_options}
for sel in raw.get("quick") or []:
q = quick.get(sel.get("id"))
if q is None:
raise _bad(n, "unknown_quick")
qty = _qty(sel.get("qty"), n, q.allow_multiple)
line.entries.append({"id": q.id, "name": q.name if qty == 1 else f"{q.name} x{qty}",
"price_delta": round((q.price or 0.0) * qty, 2), "type": "quick"})
options = {o.id: o for o in product.options}
for sel in raw.get("options") or []:
o = options.get(sel.get("id"))
if o is None:
raise _bad(n, "unknown_option")
qty = _qty(sel.get("qty"), n, o.allow_multiple)
subs = _subs(o.sub_choices)
names = sel.get("subs") or []
if subs and not names:
raise _bad(n, "sub_required")
if len(names) > 1 and not o.multi_select:
raise _bad(n, "unknown_sub")
line.entries.append({"id": o.id, "name": o.name if qty == 1 else f"{o.name} x{qty}",
"price_delta": round((o.extra_cost or 0.0) * qty, 2), "type": "extra"})
for name in names:
s = _sub(subs, name, n)
line.entries.append({"id": None, "name": s["name"], "price_delta": round(float(s.get("extra_cost") or 0.0), 2),
"type": "extra_sub"})
chosen = {p.get("set_id"): p for p in (raw.get("prefs") or [])}
for ps in product.preference_sets:
sel = chosen.pop(ps.id, None)
picks = (sel or {}).get("choices") or []
if not picks or (len(picks) > 1 and not ps.allow_multi_select):
raise _bad(n, "choice_required")
by_id = {c.id: c for c in ps.choices}
shared = _shared(ps.shared_subset)
for pick in picks:
c = by_id.get(pick.get("id"))
if c is None:
raise _bad(n, "unknown_choice")
if ps.allow_multi_select:
qty = _qty(pick.get("qty"), n, True)
line.entries.append({"id": c.id, "name": c.name if qty == 1 else f"{c.name} x{qty}",
"price_delta": round((c.extra_cost or 0.0) * qty, 2), "type": "pref"})
continue
line.entries.append({"id": c.id, "name": c.name, "price_delta": round(c.extra_cost or 0.0, 2), "type": "pref"})
subs = _subs(c.sub_choices)
if subs:
s = _sub(subs, pick.get("sub"), n) if pick.get("sub") is not None else None
if s is None:
raise _bad(n, "sub_required")
line.entries.append({"id": None, "name": s["name"], "price_delta": round(float(s.get("extra_cost") or 0.0), 2),
"type": "pref_sub"})
if shared and not c.disables_subset:
s = _sub(_subs(shared.get("choices")), sel.get("shared"), n) if sel.get("shared") is not None else None
if s is None:
raise _bad(n, "sub_required")
line.entries.append({"id": None, "name": s["name"], "price_delta": round(float(s.get("extra_cost") or 0.0), 2),
"type": "pref_sub"})
if chosen:
raise _bad(n, "unknown_choice")
ingredients = {i.id: i for i in product.ingredients}
for iid in raw.get("removed") or []:
ing = ingredients.get(iid)
if ing is None:
raise _bad(n, "unknown_ingredient")
line.removed.append(ing.name)
return line
def price_lines(db, lines: list[Line], order_type: str, existing_cart: list | None = None):
"""[(unit_price, [PriceEvent])] for each line, with the same context POST
/api/orders/{id}/items builds: the order's existing items plus this line (the other new
lines of the same batch don't count, as there)."""
from core.timeutil import utcnow
from services.pricing import OrderContext, build_active_price_group_ids, resolve_price
now = utcnow()
active = build_active_price_group_ids(db, now)
channel = CHANNELS.get(order_type, "pos")
cart = list(existing_cart or [])
out = []
for line in lines:
p = line.product
here = {"product_id": p.id, "category_id": p.primary_category_id, "category_ids": p.category_ids,
"quantity": line.quantity, "unit_price": p.base_price + line.extra}
ctx = OrderContext(channel=channel, now=now, cart_items=cart + [here], active_price_group_ids=active)
unit, events = resolve_price(p, line.quantity, line.extra, ctx, db)
out.append((unit, events))
return out
+5 -3
View File
@@ -204,9 +204,11 @@ def test_config_validated_and_effective(client, pair, owner_h): # "done when" 4
def test_module_catalogue_describes_config(client, owner_h):
mods = {m["key"]: m for m in client.get("/api/platform/modules", headers=owner_h).json()["modules"]}
assert mods["pos_counter"]["device_app"]["config"] == [{"key": "auto_sign_out_minutes", "type": "int", "default": 0,
"choices": [0, 2, 5, 10, 30, 60], "min": None, "max": None,
"choices_from": None, "group": None, "after": None}]
pos = {f["key"]: f for f in mods["pos_counter"]["device_app"]["config"]}
assert pos["auto_sign_out_minutes"] == {"key": "auto_sign_out_minutes", "type": "int", "default": 0,
"choices": [0, 2, 5, 10, 30, 60], "min": None, "max": None,
"choices_from": None, "group": None, "after": None}
assert pos["receipt_printer_id"]["choices_from"] == "printers" and pos["start_category_id"]["choices_from"] == "categories"
kds = {f["key"]: f for f in mods["kds"]["device_app"]["config"]}
assert kds["prep_zone_id"] == {"key": "prep_zone_id", "type": "ref", "default": None, "choices": [], "min": None,
"max": None, "choices_from": "prep_zones", "group": "zone", "after": None}
+145
View File
@@ -0,0 +1,145 @@
"""Counter POS: menu, server-priced cart, shift gate (plan step 3.3a)."""
import json
import pytest
from tests.test_live import err, owner_h, pair, terminal_login # noqa: F401 (fixtures)
@pytest.fixture
def menu(db):
"""A burger with every kind of option, a coffee, an unavailable dish and a service item."""
from models.product import (Category, Product, ProductIngredient, ProductOption, ProductPreferenceChoice,
ProductPreferenceSet, ProductQuickOption)
food, drinks = Category(name="Food", sort_order=1), Category(name="Drinks", sort_order=2)
db.add_all([food, drinks])
db.flush()
burger = Product(name="Burger", base_price=10.0, primary_category_id=food.id, description="Beef, brioche",
tags=json.dumps(["spicy"]), cost_simple=3.5)
coffee = Product(name="Freddo", base_price=3.0, primary_category_id=drinks.id)
gone = Product(name="Old dish", base_price=5.0, primary_category_id=food.id, is_available=False)
cutlery = Product(name="Cutlery", base_price=0.0, primary_category_id=food.id, is_service_item=True)
db.add_all([burger, coffee, gone, cutlery])
db.flush()
db.add(ProductQuickOption(product_id=burger.id, name="Extra cheese", price=1.0, allow_multiple=True))
db.add(ProductOption(product_id=burger.id, name="Sauce", extra_cost=0.5,
sub_choices=json.dumps([{"name": "BBQ", "extra_cost": 0.2, "is_default": True}, {"name": "Mayo"}])))
db.add(ProductIngredient(product_id=burger.id, name="Onion"))
cook = ProductPreferenceSet(product_id=burger.id, name="Cooking",
shared_subset=json.dumps({"name": "Side", "choices": [{"name": "Fries", "is_default": True},
{"name": "Salad", "extra_cost": 1.0}]}))
db.add(cook)
db.flush()
rare = ProductPreferenceChoice(set_id=cook.id, name="Rare")
well = ProductPreferenceChoice(set_id=cook.id, name="Well done", extra_cost=0.5, disables_subset=True)
db.add_all([rare, well])
db.commit()
return {"food": food, "drinks": drinks, "burger": burger, "coffee": coffee, "cook": cook, "rare": rare, "well": well,
"gone": gone, "cutlery": cutlery}
@pytest.fixture
def till(client, pair, make_user):
token, r = pair("pos_counter", "Till")
assert r.status_code == 201, r.text
cashier = make_user(role="waiter")
jwt = terminal_login(client, token, cashier)
return {"h": {"X-Xenia-Device": token, "Authorization": f"Bearer {jwt}"}, "cashier": cashier, "id": r.json()["id"]}
def burger_line(m, **extra):
return {"product_id": m["burger"].id, "quantity": 1,
"prefs": [{"set_id": m["cook"].id, "choices": [{"id": m["rare"].id}], "shared": "Fries"}], **extra}
def test_menu_lists_what_a_cashier_sells(client, till, menu):
data = client.get("/api/pos/menu", headers=till["h"]).json()
names = [p["name"] for p in data["products"]]
assert "Burger" in names and "Freddo" in names and "Old dish" not in names and "Cutlery" not in names
burger = next(p for p in data["products"] if p["name"] == "Burger")
assert burger["price"] == 10.0 and burger["description"] == "Beef, brioche" and burger["tags"] == ["spicy"]
assert "cost_simple" not in burger and "cost_breakdown" not in burger
assert burger["options"][0]["subs"][0] == {"name": "BBQ", "price": 0.2, "is_default": True}
assert burger["prefs"][0]["shared"]["name"] == "Side" and burger["prefs"][0]["choices"][1]["disables_shared"] is True
assert {c["name"] for c in data["categories"]} >= {"Food", "Drinks"}
assert data["settings"]["default_order_type"] == "takeaway"
def test_quote_prices_on_the_server(client, till, menu):
m = menu
line = burger_line(m, quick=[{"id": m["burger"].quick_options[0].id, "qty": 2}],
options=[{"id": m["burger"].options[0].id, "subs": ["BBQ"]}],
removed=[m["burger"].ingredients[0].id], notes="no salt")
r = client.post("/api/pos/quote", headers=till["h"], json={"order_type": "takeaway", "lines": [line, {"product_id": m["coffee"].id, "quantity": 2}]})
assert r.status_code == 200, r.text
burger, coffee = r.json()["lines"]
# 10 + 2×1 cheese + 0.5 sauce + 0.2 BBQ + 0 rare + 0 fries
assert burger["unit_price"] == 12.7 and burger["total"] == 12.7
assert [e["name"] for e in burger["entries"]] == ["Extra cheese x2", "Sauce", "BBQ", "Rare", "Fries"]
assert burger["removed"] == ["Onion"] and burger["notes"] == "no salt"
assert coffee["total"] == 6.0 and r.json()["total"] == 18.7
# well done has no side
r = client.post("/api/pos/quote", headers=till["h"],
json={"lines": [{"product_id": m["burger"].id, "prefs": [{"set_id": m["cook"].id, "choices": [{"id": m["well"].id}]}]}]})
assert r.json()["lines"][0]["unit_price"] == 10.5
@pytest.mark.parametrize("bad,reason", [
(lambda m: {"product_id": m["burger"].id}, "choice_required"),
(lambda m: {"product_id": m["burger"].id, "prefs": [{"set_id": m["cook"].id, "choices": [{"id": m["rare"].id}]}]}, "sub_required"),
(lambda m: burger_line(m, options=[{"id": m["burger"].options[0].id}]), "sub_required"),
(lambda m: burger_line(m, options=[{"id": m["burger"].options[0].id, "subs": ["Ketchup"]}]), "unknown_sub"),
(lambda m: burger_line(m, options=[{"id": m["burger"].options[0].id, "subs": ["BBQ", "Mayo"]}]), "unknown_sub"),
(lambda m: burger_line(m, removed=[999999]), "unknown_ingredient"),
(lambda m: {"product_id": m["gone"].id}, "product_unavailable"),
(lambda m: {"product_id": m["coffee"].id, "quantity": 0}, "quantity"),
])
def test_quote_refuses_what_the_waiter_dialog_refuses(client, till, menu, bad, reason):
r = client.post("/api/pos/quote", headers=till["h"], json={"lines": [bad(menu)]})
assert r.status_code == 422 and r.json()["error"]["code"] == "pos.line_invalid"
assert r.json()["error"]["params"] == {"line": 0, "reason": reason}
def test_quote_applies_price_modifiers_like_orders(client, db, till, menu):
from models.pricing import PriceModifier
db.add(PriceModifier(name="Happy hour", scope="item", item_id=menu["coffee"].id, action_type="add_percent", action_value=-10, is_active=1))
db.commit()
line = client.post("/api/pos/quote", headers=till["h"], json={"lines": [{"product_id": menu["coffee"].id}]}).json()["lines"][0]
assert line["unit_price"] == 2.7 and line["adjustments"] == [{"label": "Happy hour", "delta": -0.3}]
coffee = next(p for p in client.get("/api/pos/menu", headers=till["h"]).json()["products"] if p["name"] == "Freddo")
assert coffee["price"] == 2.7 and coffee["base_price"] == 3.0
def test_session_shift_gate(client, db, till, make_user):
from models.business_day import BusinessDay
from models.settings import PosSettings
db.query(BusinessDay).filter(BusinessDay.status == "open").update({"status": "closed"})
db.commit()
boss = make_user(role="store_manager", nickname="Eleni")
s = client.get("/api/pos/session", headers=till["h"]).json()
assert s["business_day"] is None and s["shift"] is None and "Eleni" in s["day_openers"]
assert client.post("/api/business-day/open", headers=till["h"], json={}).status_code in (401, 403) # not from the till
# the day opens elsewhere; self-start allowed → the cashier starts their own shift
from core.timeutil import utcnow, business_date_of
db.add(BusinessDay(status="open", opened_at=utcnow(), business_date=business_date_of(utcnow()), opened_by_id=boss.id))
row = db.get(PosSettings, "shifts.waiter_self_start")
if row is None:
db.add(PosSettings(key="shifts.waiter_self_start", value="true"))
else:
row.value = "true"
db.commit()
s = client.get("/api/pos/session", headers=till["h"]).json()
assert s["business_day"] is not None and s["self_start"] is True and s["shift"] is None
r = client.post("/api/shifts/start", headers=till["h"], json={"starting_cash": 50})
assert r.status_code == 201, r.text
s = client.get("/api/pos/session", headers=till["h"]).json()
assert s["shift"]["starting_cash"] == 50
def test_pos_settings_validate_their_references(client, owner_h, till, menu):
ok = client.patch(f"/api/devices/{till['id']}", headers=owner_h,
json={"config": {"default_order_type": "here", "start_category_id": menu["drinks"].id}})
assert ok.status_code == 200 and ok.json()["config"]["start_category_id"] == menu["drinks"].id
assert err(client.patch(f"/api/devices/{till['id']}", headers=owner_h,
json={"config": {"receipt_printer_id": 999999}})) == "validation.device_config"
assert client.get("/api/pos/menu", headers=till["h"]).json()["settings"]["default_order_type"] == "here"