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
+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)