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:
@@ -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)
|
||||
|
||||
@@ -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", [])}
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user