Files
xenia-pos-local/local_backend/services/pos_cart.py
T
bonaminandClaude Opus 5.5 1b468fe44b feat: sales points, offerings and prices per sales point (platform-v2 phase 3S, step S.1)
- core/sales_points.py: in_store, in_store_takeaway, qr_table, online_takeaway,
  online_delivery, online_preorder (+ old channel names mapped).
- Alembic 0017: orders.sales_point (backfilled), products.sold_at (from digital_visible),
  digital_price/digital_discount -> item price modifiers for the QR menu and online,
  order_channel conditions -> sales points; drops the three digital columns.
- Every order records its sales point; the pricing engine's channel is it; items not sold
  there are refused (order.not_sold_here, pos.line_invalid not_sold_here).
- POS menu: only what the counter sells, prices per counter sales point; the screen shows
  the order type's products and prices. Waiter app asks for in-person products.
- Cloud snapshot: products sold by the customer apps, priced by the engine.
- Manager: product "Where it's sold" tab; pricing condition shows sales points.
- Products API, catalogue export/import carry sold_at.
- Tests: test_sales_points.py (8, incl. the migration), access +1, terminal +1.

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

245 lines
11 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.
"""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 | 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 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"], "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, 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) -> list[float]:
"""Each product's price for one unit without options at a sales point, right now, 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 = 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