Files
xenia-pos-local/local_backend/services/pos_cart.py
T
bonaminandClaude Opus 5.5 17bee66df1 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>
2026-11-14 21:55:30 +02:00

190 lines
8.3 KiB
Python

"""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