Files
xenia-pos-local/local_backend/services/pos_cart.py
T
bonaminandClaude Opus 5.5 8e0a786bbc feat(ordering): orders priced by the server (platform-v2 step 4.4)
The waiter app (and the manager's ordering tab) send what was chosen, by id; the
server prices it with the counter's code. No app sends a price any more.

- POST /api/orders/{id}/items takes `lines` (pos_cart's line + course_id,
  price_adjustment, is_service_item): sales point checked first, refusals name the
  product and line (order.line.*, order.not_sold_here); prices or selected_options in a
  line -> order.line.client_price, the old `items` shape -> order.lines_required; a
  by-hand price change needs ordering.prices.modify or a manager's approval (audited
  PRICE_SET_BY_HAND). add_priced_items is the one writer of priced items (pos too).
- POST /api/orders/quote: the cart's total before sending; /api/pos/quote shares
  pos_cart.quote().
- pos_cart: a preference set left out takes its default; a set at its free default
  isn't stored; a default that costs is charged (the waiter never sent it: fixed);
  an extra's sub-choice is charged per extra (the counter charged it once: fixed).
- @xenia/api lines.js: lineFromOptions / wireLine / estimate / LineError.
- Waiter: lines on send; cart total from the quote ("≈ estimate" offline); summary
  shows the same prices; offline orders queued by id, priced on sync, refused lines
  shown on a "Δεν στάλθηκαν" sheet (no empty order opened); dead ItemOptionsModal gone.
- Tests: test_order_lines.py (14), lines.test.mjs, waiter e2e +6.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 03:35:03 +02:00

318 lines
15 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Order lines priced by the backend: the counter POS (plan step 3.3a, D-26) and, since
step 4.4, the waiter app (POST /api/orders/{id}/items takes these lines).
No app 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 `selected_options` entries an order
item stores (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) through
routers/orders.py::add_priced_items. 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; the
same extra may be listed more than once
prefs: [{set_id, choices: [{id, qty?, sub?: name}], shared?: name}],
removed: [ingredient_id]}
Rules (the same as the waiter's options drawer, waiter_pwa OrderDrawer.jsx):
- every preference set needs a choice (one, or one or more for allow_multi_select sets); a set
left out of the line takes its default choice (with the default sub-choices) when it has one;
- a set at its default (default choice, default sub-choices) that costs nothing is not stored:
the ticket shows only what differs from the usual (the waiter app always worked that way);
- 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;
an extra's sub-choice is charged once per extra (qty 2 of "sauce: ketchup" = 2 × both).
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 | discount | not_sold_here
(the product isn't sold at this sales point, phase 3S).
A line may carry `discount_pct` (0–100, whole percent): the quote shows it; selling it needs
ordering.prices.modify or a manager's approval (routers/pos.py).
"""
from __future__ import annotations
import json
from dataclasses import dataclass, field
from typing import Optional
from core import sales_points
from core.errors import XeniaError
POINTS = {"here": sales_points.IN_STORE, "takeaway": sales_points.IN_STORE_TAKEAWAY}
def point_for(order_type: str | None) -> str:
"""The counter's sales point for an order type (phase 3S)."""
return POINTS.get(order_type or "here", sales_points.IN_STORE)
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
discount_pct: int = 0 # 3.3b: needs ordering.prices.modify (or approval)
@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 _default_sub(subs: list[dict]) -> Optional[str]:
"""The sub-choice selected to start with: the one marked default, else the first."""
return next((s for s in subs if s.get("is_default")), subs[0])["name"] if subs else None
def _usual_pick(choice, shared) -> dict:
"""A preference set at its default: the default choice, its default sub-choice and the
set's default shared sub-choice."""
return {"choices": [{"id": choice.id, "qty": 1, "sub": _default_sub(_subs(choice.sub_choices))}],
"shared": _default_sub(_subs(shared.get("choices"))) if shared and not choice.disables_subset else None}
def _same_pick(sel: dict, usual: dict, multi: bool) -> bool:
picks = sel.get("choices") or []
if len(picks) != 1 or not isinstance(picks[0], dict):
return False
p, u = picks[0], usual["choices"][0]
if p.get("id") != u["id"] or (p.get("qty") or 1) != 1:
return False
return multi or (p.get("sub") == u["sub"] and (usual["shared"] is None or sel.get("shared") == usual["shared"]))
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)
pct = raw.get("discount_pct", 0) or 0
if isinstance(pct, bool) or not isinstance(pct, int) or not 0 <= pct <= 100:
raise _bad(n, "discount")
line.discount_pct = pct
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"] if qty == 1 else f"{s['name']} x{qty}",
"price_delta": round(float(s.get("extra_cost") or 0.0) * qty, 2), "type": "extra_sub"})
chosen = {p.get("set_id"): p for p in (raw.get("prefs") or []) if isinstance(p, dict)}
for ps in product.preference_sets:
by_id = {c.id: c for c in ps.choices}
shared = _shared(ps.shared_subset)
default = by_id.get(ps.default_choice_id)
usual = _usual_pick(default, shared) if default is not None else None
sel = chosen.pop(ps.id, None)
if sel is None and usual is not None:
sel = usual # left out: the set's default (4.4)
picks = (sel or {}).get("choices") or []
if not picks or (len(picks) > 1 and not ps.allow_multi_select):
raise _bad(n, "choice_required")
entries = []
for pick in picks:
c = by_id.get(pick.get("id")) if isinstance(pick, dict) else None
if c is None:
raise _bad(n, "unknown_choice")
if ps.allow_multi_select:
qty = _qty(pick.get("qty"), n, True)
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
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")
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")
entries.append({"id": None, "name": s["name"], "price_delta": round(float(s.get("extra_cost") or 0.0), 2),
"type": "pref_sub"})
at_default = usual is not None and _same_pick(sel, usual, ps.allow_multi_select)
if not (at_default and not any(e["price_delta"] for e in entries)):
line.entries.extend(entries)
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, point: str | None = None):
"""[(unit_price, [PriceEvent])] for each line, with the same context POST
/api/orders/{id}/items builds: the order's existing items, the lines before it in the
same batch (at their resolved price), and this line. The sales point is the order type's
at the counter unless given; a product not sold there → pos.line_invalid not_sold_here."""
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 = point or point_for(order_type)
cart = list(existing_cart or [])
out = []
for n, line in enumerate(lines):
p = line.product
if not sales_points.is_sold_at(p, channel):
raise _bad(n, "not_sold_here")
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))
cart.append({**here, "unit_price": unit})
return out
def unit_prices(db, products, point: str, now=None) -> list[float]:
"""Each product's price for one unit without options at a sales point, right now (or at
`now`, UTC), priced on its own (an empty cart): what a menu shows."""
from core.timeutil import utcnow
from services.pricing import OrderContext, build_active_price_group_ids, resolve_price
now = now or utcnow()
active = build_active_price_group_ids(db, now)
out = []
for p in products:
here = {"product_id": p.id, "category_id": p.primary_category_id, "category_ids": p.category_ids,
"quantity": 1, "unit_price": p.base_price}
ctx = OrderContext(channel=point, now=now, cart_items=[here], active_price_group_ids=active)
out.append(resolve_price(p, 1, 0.0, ctx, db)[0])
return out
def order_cart(order) -> list[dict]:
"""An order's active items as the pricing engine's cart context (what POST
/api/orders/{id}/items starts from, and what a table's quote starts from, 3.3c)."""
return [
{
"product_id": i.product_id,
"category_id": i.product.primary_category_id if i.product else None,
"category_ids": i.product.category_ids if i.product else [],
"quantity": i.quantity,
"unit_price": i.unit_price,
}
for i in order.items if i.status == "active"
]
def discount_adjustment(unit_price: float, pct) -> float:
"""A line's discount (percent of its unit price) as the order item's price_adjustment
(negative, rounded to cents)."""
return -round(unit_price * pct / 100.0, 2) if pct else 0.0
def adjustments(db, events) -> list[dict]:
"""A line's price-engine adjustments (happy hour, price groups) as {label, delta}."""
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
def quote(db, lines: list[Line], order_type: str, existing_cart: list | None = None, point: str | None = None,
manual: list | None = None) -> dict:
"""The lines priced exactly as the order will be: per line the unit price (base + options,
then price groups/modifiers, then a discount or a by-hand price change), its total, what
was chosen (names) and any adjustment. `manual`: each line's by-hand change per unit (the
waiter's price change, 4.4)."""
priced = price_lines(db, lines, order_type, existing_cart, point) if lines else []
out = []
for i, (line, (unit, events)) in enumerate(zip(lines, priced)):
adj = discount_adjustment(unit, line.discount_pct)
hand = round(float((manual or [])[i] or 0.0), 2) if manual and i < len(manual) else 0.0
row = {
"product_id": line.product.id, "name": line.product.name, "quantity": line.quantity,
"base_price": round(line.product.base_price, 2), "extra": line.extra,
"discount_pct": line.discount_pct, "discount": adj,
"unit_price": round(unit + adj + hand, 2), "total": round((unit + adj + hand) * 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),
}
if manual is not None:
row["price_adjustment"] = hand
out.append(row)
return {"order_type": order_type, "lines": out, "total": round(sum(x["total"] for x in out), 2)}