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>
This commit is contained in:
2026-11-17 03:35:03 +02:00
co-authored by Claude Opus 5.5
parent bcf91bf6e9
commit 8e0a786bbc
25 changed files with 1052 additions and 656 deletions
+7
View File
@@ -75,6 +75,13 @@ CODES: dict[str, tuple[int, str]] = {
"pos.items_changed": (409, "Some of these items were paid or cancelled in the meantime. Check the order and try again."),
"pos.order_unpaid": (409, "Items still unpaid: {count}. Take the payment or cancel them first."),
"order.not_sold_here": (422, "{name} isn't sold for this kind of order."),
"order.lines_required": (422, "This app sent the order in an old format. Update the app and send it again."),
"order.line.product_unavailable": (422, "{name} isn't available any more (line {line})."),
"order.line.option_gone": (422, "{name}: a chosen option doesn't exist any more (line {line}). Remove it and add it again."),
"order.line.choice_missing": (422, "{name}: a required choice is missing (line {line})."),
"order.line.quantity": (422, "{name}: that quantity isn't allowed (line {line})."),
"order.line.price": (422, "{name}: that price change isn't allowed (line {line})."),
"order.line.client_price": (422, "{name}: the app sent its own prices, but prices come from the server (line {line}). Update the app."),
"fees.area_not_found": (404, "Delivery area {area_id} not found."),
"fees.rule_not_found": (404, "Fee rule {rule_id} not found."),
"fees.area_in_use": (409, "This area is used by fee rules: {rules}. Change those rules first."),
+143 -7
View File
@@ -29,7 +29,7 @@ from services.pricing import (
build_active_price_group_ids, write_price_events,
check_waiter_discount_limits, discounts_enabled, _system_round,
)
from pydantic import BaseModel
from pydantic import BaseModel, Field
class PrintOrderRequest(BaseModel):
printer_id: int
@@ -476,13 +476,149 @@ def open_order(body: OrderCreate, db: Session = Depends(get_db), user: User = De
return order
# ── lines priced by the server (plan step 4.4) ─────────────────────────────────
# what an app may not send: prices, and the stored shape that carried them
_CLIENT_PRICE_KEYS = {"selected_options", "removed_ingredients", "unit_price", "price_delta", "extra_cost", "price"}
# pos_cart's reasons → the code the app shows (texts in errors.json, order.line.*)
_LINE_CODES = {
"product_unavailable": "order.line.product_unavailable",
"unknown_quick": "order.line.option_gone", "unknown_option": "order.line.option_gone",
"unknown_choice": "order.line.option_gone", "unknown_sub": "order.line.option_gone",
"unknown_ingredient": "order.line.option_gone",
"choice_required": "order.line.choice_missing", "sub_required": "order.line.choice_missing",
"quantity": "order.line.quantity", "discount": "order.line.price", "price": "order.line.price",
"client_price": "order.line.client_price", "not_sold_here": "order.not_sold_here",
}
class AddLinesRequest(BaseModel):
"""POST /api/orders/{id}/items: what was chosen, by id (services/pos_cart.py's line,
plus `course_id`, `price_adjustment` (a by-hand change per unit: needs
ordering.prices.modify or a manager's approval) and `is_service_item`)."""
lines: Optional[List[dict]] = Field(default=None, max_length=200)
items: Optional[list] = None # the shape before 4.4: refused (order.lines_required)
order_note: Optional[str] = None
customer_count: Optional[int] = None
class QuoteRequest(BaseModel):
lines: List[dict] = Field(default_factory=list, max_length=200)
order_id: Optional[int] = None # adding to an order: its items count, its sales point
order_type: str = "here" # a new order: here | takeaway | delivery
def _product_name(db, raw) -> str:
pid = raw.get("product_id") if isinstance(raw, dict) else None
p = db.get(Product, pid) if isinstance(pid, int) and not isinstance(pid, bool) else None
return p.name if p is not None else f"#{pid}"
def _resolve_lines(db, raws: list, point: str | None = None) -> tuple[list, list]:
"""Each raw line → (pos_cart.Line, its by-hand price change per unit). A refusal names the
product and the line (1-based): order.line.* / order.not_sold_here (checked first, at the
order's sales point)."""
from core.sales_points import is_sold_at
from services import pos_cart
lines, manual = [], []
for n, raw in enumerate(raws):
raw = raw if isinstance(raw, dict) else {}
pid = raw.get("product_id")
product = db.get(Product, pid) if isinstance(pid, int) and not isinstance(pid, bool) else None
if point is not None and product is not None and product.lifecycle_status == "active" and not is_sold_at(product, point):
raise XeniaError("order.not_sold_here", name=product.name, line=n + 1)
try:
if _CLIENT_PRICE_KEYS & raw.keys():
raise pos_cart._bad(n, "client_price")
adj = raw.get("price_adjustment") or 0.0
if isinstance(adj, bool) or not isinstance(adj, (int, float)) or not -10000 <= adj <= 10000:
raise pos_cart._bad(n, "price")
course = raw.get("course_id")
if course is not None and (isinstance(course, bool) or not isinstance(course, int)):
raise pos_cart._bad(n, "unknown_option")
lines.append(pos_cart.resolve_line(db, raw, n))
manual.append(round(float(adj), 2))
except XeniaError as e:
if e.code != "pos.line_invalid":
raise
reason = e.params.get("reason")
raise XeniaError(_LINE_CODES.get(reason, "order.line.option_gone"), line=n + 1,
name=_product_name(db, raw), reason=reason) from None
return lines, manual
@router.post("/quote")
def quote_lines(body: QuoteRequest, db: Session = Depends(get_db), user: User = Depends(get_current_user)):
"""Lines priced exactly as POST /api/orders/{id}/items will price them (the cart's total
before sending, 4.4): into an existing order (its items count for deals, its sales point)
or a new one of `order_type`."""
from core.sales_points import for_order, of_order
from services import pos_cart
order_type = body.order_type if body.order_type in ("here", "takeaway", "delivery") else "here"
existing, point = None, for_order(order_type)
if body.order_id is not None:
order = db.get(Order, body.order_id)
if order is None:
raise XeniaError("order.not_found", order_id=body.order_id)
if not _can_access_order(order, user, db):
raise HTTPException(status_code=403, detail="Access denied")
existing, order_type, point = pos_cart.order_cart(order), order.order_type or "here", of_order(order)
lines, manual = _resolve_lines(db, body.lines, point)
try:
return pos_cart.quote(db, lines, order_type, existing, point=point, manual=manual)
except XeniaError as e:
if e.code != "pos.line_invalid":
raise
n = e.params.get("line", 0)
raise XeniaError("order.not_sold_here", name=lines[n].product.name if n < len(lines) else "?") from None
@router.post("/{order_id}/items", response_model=AddItemsResponse)
def add_items(
order_id: int,
body: AddItemsRequest,
db: Session = Depends(get_db),
user: User = Depends(get_current_user),
):
def add_items(order_id: int, body: AddLinesRequest, request: Request, db: Session = Depends(get_db),
user: User = Depends(get_current_user)):
"""Add lines to an order; the server prices them (4.4). Apps send what was chosen by id,
never a price: prices or `selected_options` in a line → order.line.client_price, the
shape before 4.4 (`items`) → order.lines_required. A by-hand price change or a discount
needs ordering.prices.modify or a manager's approval (audited)."""
from core.sales_points import of_order
from schemas.order import OrderItemInput, SelectedOptionInput
from services import pos_cart
if body.items is not None or not body.lines:
raise XeniaError("order.lines_required")
order = db.query(Order).filter(Order.id == order_id).first()
if not order:
raise XeniaError("order.not_found", order_id=order_id)
if not _can_access_order(order, user, db):
raise HTTPException(status_code=403, detail="Access denied")
lines, manual = _resolve_lines(db, body.lines, of_order(order))
approval = None
if any(manual) or any(line.discount_pct for line in lines):
approval = _need(request, db, user, "ordering.prices.modify", target=f"order {order_id} new items")
discounts = [0.0] * len(lines)
if any(line.discount_pct for line in lines):
priced = pos_cart.price_lines(db, lines, order.order_type or "here", pos_cart.order_cart(order), point=of_order(order))
discounts = [pos_cart.discount_adjustment(unit, line.discount_pct) for line, (unit, _) in zip(lines, priced)]
items = []
for raw, line, hand, disc in zip(body.lines, lines, manual, discounts):
adj = round(hand + disc, 2)
items.append(OrderItemInput(
product_id=line.product.id, quantity=line.quantity,
selected_options=[SelectedOptionInput(**e) for e in line.entries] or None,
removed_ingredients=line.removed or None, notes=line.notes, price_adjustment=adj or None,
is_service_item=raw.get("is_service_item") is True, course_id=raw.get("course_id"),
))
result = add_priced_items(order_id, AddItemsRequest(items=items, order_note=body.order_note,
customer_count=body.customer_count), db, user)
if approval is not None:
_audit(db, order_id, "PRICE_SET_BY_HAND", waiter_id=user.id, note=_approval_note(approval))
db.commit()
return result
def add_priced_items(order_id: int, body: AddItemsRequest, db: Session, user: User):
"""Add items whose options carry the database's prices, built by services/pos_cart.py
from an app's lines (POST /api/orders/{id}/items above, the counter's routers/pos.py).
Never called with what an app sent as is."""
order = db.query(Order).filter(Order.id == order_id).first()
if not order:
raise XeniaError("order.not_found", order_id=order_id)
+5 -28
View File
@@ -156,17 +156,6 @@ class QuoteBody(BaseModel):
order_id: Optional[int] = None # adding to a table's order: its items count for deals (3.3c)
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,
@@ -176,19 +165,7 @@ def pos_quote(body: QuoteBody, db: Session = Depends(get_db), user=Depends(requi
if body.order_id is not None:
order = _order_for(db, user, body.order_id)
order_type, existing = order.order_type or "here", pos_cart.order_cart(order)
priced = pos_cart.price_lines(db, lines, order_type, existing) if lines else []
out = []
for line, (unit, events) in zip(lines, priced):
adj = pos_cart.discount_adjustment(unit, line.discount_pct)
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,
"discount_pct": line.discount_pct, "discount": adj,
"unit_price": round(unit + adj, 2), "total": round((unit + adj) * 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": order_type, "lines": out, "total": round(sum(x["total"] for x in out), 2)}
return pos_cart.quote(db, lines, order_type, existing)
@@ -240,7 +217,7 @@ def pos_sale(body: SaleBody, request: Request, db: Session = Depends(get_db), us
_check_cash(body.cash_given, cash_due)
order = orders_api.open_order(OrderCreate(table_id=None, order_type=body.order_type), db, user)
added = orders_api.add_items(order.id, AddItemsRequest(items=_items_in(lines, adjs)), db, user)
added = orders_api.add_priced_items(order.id, AddItemsRequest(items=_items_in(lines, adjs)), db, user)
item_ids = [i.id for i in db.query(OrderItem).filter(OrderItem.order_id == order.id).order_by(OrderItem.id).all()]
paid, fiscal = [], None
for method, idx in groups:
@@ -288,8 +265,8 @@ def _check_cash(cash_given, cash_due):
def _items_in(lines, adjs):
"""Cart lines as POST /api/orders/{id}/items takes them (the waiter's selected_options
entries with the database's prices; a discount as the item's price_adjustment)."""
"""Resolved lines as orders.add_priced_items takes them (selected_options entries with the
database's prices; a discount as the item's price_adjustment)."""
from schemas.order import OrderItemInput, SelectedOptionInput
return [OrderItemInput(
product_id=line.product.id, quantity=line.quantity,
@@ -435,7 +412,7 @@ def pos_table_items(table_id: int, body: TableItemsBody, request: Request, db: S
adjs = [pos_cart.discount_adjustment(unit, line.discount_pct) for line, (unit, _) in zip(lines, priced)]
if order is None:
order = orders_api.open_order(OrderCreate(table_id=table_id, order_type="here"), db, user)
added = orders_api.add_items(order.id, AddItemsRequest(items=_items_in(lines, adjs)), db, user)
added = orders_api.add_priced_items(order.id, AddItemsRequest(items=_items_in(lines, adjs)), db, user)
return {"order_id": order.id, "print_results": added.get("print_results", []), "deal_offers": added.get("deal_offers", [])}
+96 -23
View File
@@ -1,23 +1,29 @@
"""The counter POS's cart, priced by the backend (plan step 3.3a, D-26).
"""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).
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.
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
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 dialog, waiter_pwa ItemOptionsModal.jsx):
- every preference set needs a choice (one, or one or more for allow_multi_select sets);
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.
- 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
@@ -97,6 +103,28 @@ def _sub(subs: list[dict], name, n: int) -> Optional[dict]:
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
@@ -136,40 +164,48 @@ def resolve_line(db, raw: dict, n: int) -> Line:
"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"})
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 [])}
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")
by_id = {c.id: c for c in ps.choices}
shared = _shared(ps.shared_subset)
entries = []
for pick in picks:
c = by_id.get(pick.get("id"))
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)
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"})
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"})
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"})
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"})
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")
@@ -242,3 +278,40 @@ 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)}
+1 -1
View File
@@ -65,7 +65,7 @@ def test_the_fee_is_its_own_line_and_never_reaches_the_kitchen(client, db, count
assert product.id not in [p["id"] for p in client.get("/api/pos/menu", headers=counter["h"]).json()["products"]]
assert client.put(f"/api/products/{product.id}", headers=owner_h, json={"name": "x"}).status_code == 404
assert err(client.post(f"/api/orders/{oid}/items", headers=owner_h,
json={"items": [{"product_id": product.id, "quantity": 1}]})) == "order.not_sold_here"
json={"lines": [{"product_id": product.id, "quantity": 1}]})) == "order.line.product_unavailable"
# the board: the time, the area, the fee
o = board(client, counter)["incoming"][0]
assert (o["requested_for"], o["area"], o["fee"], o["total"], o["price_diff"]) == ("2026-11-16T19:30:00+00:00", "Centre", 2.5, 27.5, None)
+186
View File
@@ -0,0 +1,186 @@
"""Orders priced by the server (plan step 4.4).
The waiter app sends what was chosen by id (services/pos_cart.py's line) to POST
/api/orders/{id}/items, exactly like the counter; the server prices it. Prices from an app
are refused, a by-hand price change needs ordering.prices.modify or a manager's PIN, and the
cart's total before sending comes from POST /api/orders/quote.
"""
import json
import pytest
from conftest import TEST_PIN
from tests.test_live import err, owner_h, pair, terminal_login # noqa: F401 (fixtures)
from tests.test_pos import burger_line, drawer_printer, menu, on_shift, till # noqa: F401 (fixtures)
from tests.test_pos_tables import floor, phone # noqa: F401 (fixtures)
@pytest.fixture(autouse=True)
def _no_printing(monkeypatch):
import routers.orders as orders
monkeypatch.setattr(orders, "route_and_print_sync", lambda *a, **k: [])
@pytest.fixture
def full(db, menu):
"""The test menu's burger plus: a 'Bread' set with a default (the usual costs nothing), a
'Size' set whose default costs 1.00, and an extra that can be taken more than once."""
from models.product import ProductOption, ProductPreferenceChoice, ProductPreferenceSet
b = menu["burger"]
bread = ProductPreferenceSet(product_id=b.id, name="Bread")
size = ProductPreferenceSet(product_id=b.id, name="Size")
db.add_all([bread, size])
db.flush()
brioche = ProductPreferenceChoice(set_id=bread.id, name="Brioche",
sub_choices=json.dumps([{"name": "Toasted", "is_default": True}, {"name": "Soft"}]))
rye = ProductPreferenceChoice(set_id=bread.id, name="Rye", extra_cost=0.3)
double = ProductPreferenceChoice(set_id=size.id, name="Double", extra_cost=1.0)
single = ProductPreferenceChoice(set_id=size.id, name="Single")
db.add_all([brioche, rye, double, single])
db.flush()
bread.default_choice_id, size.default_choice_id = brioche.id, double.id
pickles = ProductOption(product_id=b.id, name="Pickles", extra_cost=0.4, allow_multiple=True,
sub_choices=json.dumps([{"name": "Sweet", "extra_cost": 0.1}, {"name": "Sour"}]))
db.add(pickles)
db.commit()
return {**menu, "bread": bread, "size": size, "brioche": brioche, "rye": rye, "double": double, "single": single,
"pickles": pickles}
def every_kind(m):
"""One burger with every kind of choice (the same line from the phone and the counter)."""
b = m["burger"]
return burger_line(
m, quantity=2, notes="no salt",
quick=[{"id": b.quick_options[0].id, "qty": 2}],
options=[{"id": b.options[0].id, "subs": ["BBQ"]}, {"id": m["pickles"].id, "qty": 2, "subs": ["Sweet"]}],
removed=[b.ingredients[0].id],
prefs=[{"set_id": m["cook"].id, "choices": [{"id": m["rare"].id}], "shared": "Salad"},
{"set_id": m["bread"].id, "choices": [{"id": m["rye"].id}]}])
def open_order(client, h, table=None, order_type="here"):
r = client.post("/api/orders/", headers=h, json={"table_id": table.id if table else None, "order_type": order_type})
assert r.status_code == 201, r.text
return r.json()["id"]
def items_of(db, order_id):
from models.order import OrderItem
db.expire_all()
return db.query(OrderItem).filter(OrderItem.order_id == order_id).order_by(OrderItem.id).all()
def test_same_price_from_the_phone_and_the_counter(client, db, full, till, phone, floor):
m = full
# 10 + cheese 2×1 + sauce 0.5 + BBQ 0.2 + pickles 2×(0.4 + 0.1) + rare 0 + salad 1 + rye 0.3 + double 1 (default, costs)
want = 10 + 2 + 0.5 + 0.2 + 1.0 + 1.0 + 0.3 + 1.0
oid = open_order(client, phone["h"], floor["t1"])
r = client.post(f"/api/orders/{oid}/items", headers=phone["h"], json={"lines": [every_kind(m)]})
assert r.status_code == 200, r.text
from_phone = items_of(db, oid)[0]
r = client.post(f"/api/pos/tables/{floor['t2'].id}/items", headers=till["h"], json={"lines": [every_kind(m)]})
assert r.status_code == 201, r.text
from_counter = items_of(db, r.json()["order_id"])[0]
assert from_phone.unit_price == from_counter.unit_price == pytest.approx(want)
assert from_phone.selected_options == from_counter.selected_options
names = [e["name"] for e in json.loads(from_phone.selected_options)]
# the cheaper default ("Brioche · Toasted") isn't stored; a default that costs ("Double") is
assert names == ["Extra cheese x2", "Sauce", "BBQ", "Pickles x2", "Sweet x2", "Rare", "Salad", "Rye", "Double"]
assert json.loads(from_phone.removed_ingredients) == ["Onion"] and from_phone.notes == "no salt"
# the quote said the same before sending
q = client.post("/api/orders/quote", headers=phone["h"], json={"order_id": oid, "lines": [every_kind(m)]}).json()
assert q["lines"][0]["unit_price"] == pytest.approx(want) and q["total"] == pytest.approx(want * 2)
def test_a_set_left_out_takes_its_default(client, db, full, phone, floor):
m = full
oid = open_order(client, phone["h"], floor["t1"])
line = {"product_id": m["burger"].id, "prefs": [{"set_id": m["cook"].id, "choices": [{"id": m["well"].id}]}]}
assert client.post(f"/api/orders/{oid}/items", headers=phone["h"], json={"lines": [line]}).status_code == 200
item = items_of(db, oid)[0]
# 10 + well done 0.5 + double 1 (Bread and Size left out: their defaults)
assert item.unit_price == pytest.approx(11.5)
assert [e["name"] for e in json.loads(item.selected_options)] == ["Well done", "Double"]
# a set without a default can't be left out
r = client.post(f"/api/orders/{oid}/items", headers=phone["h"], json={"lines": [{"product_id": m["burger"].id}]})
assert err(r) == "order.line.choice_missing" and r.json()["error"]["params"]["name"] == "Burger"
@pytest.mark.parametrize("tamper", [
{"selected_options": [{"id": None, "name": "Gold leaf", "price_delta": -9.0, "type": "extra"}]},
{"unit_price": 0.01},
{"price_delta": -5},
])
def test_prices_from_the_app_are_refused(client, db, full, phone, floor, tamper):
oid = open_order(client, phone["h"], floor["t1"])
r = client.post(f"/api/orders/{oid}/items", headers=phone["h"], json={"lines": [{**burger_line(full), **tamper}]})
assert r.status_code == 422 and err(r) == "order.line.client_price"
assert r.json()["error"]["params"]["line"] == 1
assert items_of(db, oid) == []
def test_the_old_shape_is_refused(client, db, full, phone, floor):
oid = open_order(client, phone["h"], floor["t1"])
r = client.post(f"/api/orders/{oid}/items", headers=phone["h"],
json={"items": [{"product_id": full["coffee"].id, "quantity": 1, "price_adjustment": -3}]})
assert err(r) == "order.lines_required" and items_of(db, oid) == []
def test_a_price_set_by_hand_needs_the_key_or_a_managers_pin(client, db, full, phone, floor, make_user):
from models.order import OrderAuditLog
oid = open_order(client, phone["h"], floor["t1"])
line = {"product_id": full["coffee"].id, "quantity": 1, "price_adjustment": -1.0}
url = f"/api/orders/{oid}/items"
r = client.post(url, headers=phone["h"], json={"lines": [line]})
assert r.status_code == 403 and err(r) == "access.override_possible"
assert r.json()["error"]["params"]["key"] == "ordering.prices.modify" and items_of(db, oid) == []
boss = make_user(role="owner")
a = client.post("/api/access/override", headers=phone["h"],
json={"key": "ordering.prices.modify", "username": boss.username, "pin": TEST_PIN})
assert a.status_code == 200, a.text
r = client.post(url, headers=dict(phone["h"], **{"X-Xenia-Override": a.json()["override_token"]}), json={"lines": [line]})
assert r.status_code == 200, r.text
item = items_of(db, oid)[0]
assert item.unit_price == 3.0 and item.price_adjustment == -1.0
log = db.query(OrderAuditLog).filter(OrderAuditLog.event_type == "PRICE_SET_BY_HAND").one()
assert "override #" in log.note
# out of range → refused whoever asks
r = client.post(url, headers=dict(phone["h"]), json={"lines": [{**line, "price_adjustment": 1e9}]})
assert err(r) == "order.line.price"
@pytest.mark.parametrize("bad,code", [
(lambda m: burger_line(m, options=[{"id": 999999}]), "order.line.option_gone"),
(lambda m: burger_line(m, removed=[999999]), "order.line.option_gone"),
(lambda m: {"product_id": m["gone"].id}, "order.line.product_unavailable"),
(lambda m: {"product_id": m["coffee"].id, "quantity": 0}, "order.line.quantity"),
(lambda m: burger_line(m, quick=[{"id": m["burger"].quick_options[0].id, "qty": 1.5}]), "order.line.quantity"),
])
def test_refusals_name_the_product_and_the_line(client, db, full, phone, floor, bad, code):
oid = open_order(client, phone["h"], floor["t1"])
good = {"product_id": full["coffee"].id, "quantity": 1}
r = client.post(f"/api/orders/{oid}/items", headers=phone["h"], json={"lines": [good, bad(full)]})
assert r.status_code == 422 and err(r) == code
assert r.json()["error"]["params"]["line"] == 2 and items_of(db, oid) == [] # nothing half-added
def test_quote_for_a_new_order_and_its_sales_point(client, db, full, phone):
from tests.test_sales_points import takeaway_price
takeaway_price(db, full["coffee"], 2.7)
line = {"product_id": full["coffee"].id, "quantity": 2}
here = client.post("/api/orders/quote", headers=phone["h"], json={"lines": [line]}).json()
away = client.post("/api/orders/quote", headers=phone["h"], json={"order_type": "takeaway", "lines": [line]}).json()
assert here["total"] == 6.0 and away["total"] == pytest.approx(5.4)
assert err(client.post("/api/orders/quote", headers=phone["h"], json={"lines": [{**line, "price_delta": 1}]})) == "order.line.client_price"
def test_service_items_and_courses_still_work(client, db, full, phone, floor):
oid = open_order(client, phone["h"], floor["t1"])
r = client.post(f"/api/orders/{oid}/items", headers=phone["h"], json={"lines": [
{"product_id": full["cutlery"].id, "quantity": 2, "is_service_item": True}, # priceless: printed, not saved
{"product_id": full["coffee"].id, "quantity": 1, "course_id": 2},
]})
assert r.status_code == 200, r.text
items = items_of(db, oid)
assert [(i.product_id, i.course_id) for i in items] == [(full["coffee"].id, 2)]
+3 -3
View File
@@ -67,7 +67,7 @@ def test_tables_follow_the_cashiers_zones(client, db, till, floor, phone, menu):
assert by_name["Corner"]["flags"] == [{"id": flag.id, "name": "VIP", "emoji": "⭐", "color": "#aa0000", "text_color": None}]
# the waiter opens T1 on the phone; the counter sees it with totals and who is on it
o = client.post("/api/orders/", headers=phone["h"], json={"table_id": floor["t1"].id}).json()
client.post(f"/api/orders/{o['id']}/items", headers=phone["h"], json={"items": [{"product_id": menu["coffee"].id, "quantity": 2}]})
client.post(f"/api/orders/{o['id']}/items", headers=phone["h"], json={"lines": [{"product_id": menu["coffee"].id, "quantity": 2}]})
t1 = tables(client, till)[0]["T1"]["order"]
assert t1["id"] == o["id"] and t1["total"] == 6.0 and t1["unpaid"] == 6.0 and t1["items"] == 1
assert t1["people"] == ["Maria"] and t1["mine"] is False
@@ -85,7 +85,7 @@ def test_counter_and_phone_share_a_table(client, db, till, floor, phone, menu, e
seen = client.get(f"/api/orders/{oid}", headers=phone["h"]).json()
assert [i["product_name"] for i in seen["items"]] == ["Freddo"]
assert client.post(f"/api/orders/{oid}/items", headers=phone["h"],
json={"items": [{"product_id": m["coffee"].id, "quantity": 1}]}).status_code == 200
json={"lines": [{"product_id": m["coffee"].id, "quantity": 1}]}).status_code == 200
# the counter adds a burger to the same order (not a second one)
assert send(client, till, floor["t1"], [burger_line(m)]).json()["order_id"] == oid
t1 = tables(client, till)[0]["T1"]["order"]
@@ -125,7 +125,7 @@ def test_tables_outside_the_zones_are_refused(client, db, till, floor, menu, on_
db.commit()
h = login(nikos, "waiter")
o = client.post("/api/orders/", headers=h, json={"table_id": floor["t3"].id}).json()
client.post(f"/api/orders/{o['id']}/items", headers=h, json={"items": [{"product_id": menu["coffee"].id, "quantity": 1}]})
client.post(f"/api/orders/{o['id']}/items", headers=h, json={"lines": [{"product_id": menu["coffee"].id, "quantity": 1}]})
item = client.get(f"/api/orders/{o['id']}", headers=h).json()["items"][0]["id"]
assert err(client.post("/api/pos/quote", headers=till["h"], json={"order_id": o["id"], "lines": []})) == "pos.table_not_yours"
assert err(client.post(f"/api/pos/orders/{o['id']}/pay", headers=till["h"],
+1 -1
View File
@@ -85,7 +85,7 @@ def test_waiter_orders_follow_the_sales_point(client, db, make_user, login, menu
assert "Burger" in [p["name"] for p in client.get("/api/products/", headers=h).json()] # no filter: as before
order = client.post("/api/orders/", headers=h, json={"table_id": None, "order_type": "here"}).json()
assert db.get(Order, order["id"]).sales_point == "in_store"
r = client.post(f"/api/orders/{order['id']}/items", headers=h, json={"items": [{"product_id": menu["burger"].id, "quantity": 1}]})
r = client.post(f"/api/orders/{order['id']}/items", headers=h, json={"lines": [{"product_id": menu["burger"].id, "quantity": 1}]})
assert err(r) == "order.not_sold_here"