- services/checkout.py: orders and quotes priced from the site's snapshot per sales point
(prices map; older snapshots: digital_price less discount); refused: unavailable or
not sold there, bad quantity/option/type, empty, order.price_changed when the browser's
unit price or total differs. Nothing the browser says about money is stored.
- POST /api/orders/{site}/quote; delivery needs phone + address.
- Fixes: pending orders, menu sync and stats snapshot acted on the site_id given, not the
authenticated site (a site could read another's orders or overwrite its menu/stats).
- Order refs are unique per site (a second site's first order failed); tracking by a
random token GET /api/orders/track/{token}; old /status/{ref} only while unambiguous.
- Alembic 0003: online_orders sales_point, table_label, tracking_token; table rebuilt.
- menu-app: tracking link uses the token, shows the order number; tells the customer when
the menu changed or the order failed.
- Tests: test_checkout.py (6), 0003 data migration.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
153 lines
6.3 KiB
Python
153 lines
6.3 KiB
Python
"""The cloud prices online orders itself (plan phase 3S, step S.2).
|
|
|
|
The customer's browser sends what it wants (product ids, quantities, chosen quick options);
|
|
the price of everything comes from the venue's menu snapshot (pushed by the site), for the
|
|
order's sales point. A total the browser sends is only compared: a difference means the
|
|
customer saw old prices (or edited them) and the order is refused with the current ones.
|
|
|
|
price_cart(snapshot, order_type, items) -> Priced
|
|
CheckoutError(status, code, **params) the router turns it into {"detail": {code, params}}
|
|
|
|
Snapshot product (site services/cloud_sync._push_menu_snapshot):
|
|
{id, name, digital_name, base_price, digital_price, digital_discount, digital_available,
|
|
sold_at: [sales point], prices: {sales point: price}, quick_options: [{id, name, price}]}
|
|
Snapshots from before S.2 have no `prices` / `sold_at`: every customer-app sales point, at
|
|
digital_price (or base_price) less digital_discount %.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
from dataclasses import dataclass, field
|
|
|
|
# the cloud order's type → the site's sales point (core/sales_points.py)
|
|
POINT_FOR_TYPE = {
|
|
"dine_in": "qr_table",
|
|
"takeaway": "online_takeaway",
|
|
"delivery": "online_delivery",
|
|
"preorder": "online_preorder",
|
|
}
|
|
DIGITAL = tuple(POINT_FOR_TYPE.values())
|
|
MAX_QTY = 99
|
|
MAX_LINES = 100
|
|
EPS = 0.005
|
|
|
|
|
|
class CheckoutError(Exception):
|
|
def __init__(self, status: int, code: str, **params):
|
|
super().__init__(code)
|
|
self.status, self.code, self.params = status, code, params
|
|
|
|
def detail(self) -> dict:
|
|
return {"code": self.code, "params": self.params}
|
|
|
|
|
|
@dataclass
|
|
class Line:
|
|
product_id: int
|
|
name: str
|
|
quantity: int
|
|
unit_price: float
|
|
options: list = field(default_factory=list) # [{id, name, price}]
|
|
|
|
def out(self) -> dict:
|
|
return {"product_id": self.product_id, "name": self.name, "quantity": self.quantity,
|
|
"unit_price": self.unit_price, "options": self.options}
|
|
|
|
|
|
@dataclass
|
|
class Priced:
|
|
sales_point: str
|
|
lines: list
|
|
subtotal: float
|
|
delivery_fee: float
|
|
total: float
|
|
|
|
def out(self) -> dict:
|
|
return {"sales_point": self.sales_point, "lines": [x.out() for x in self.lines],
|
|
"subtotal": self.subtotal, "delivery_fee": self.delivery_fee, "total": self.total}
|
|
|
|
|
|
def products_of(snapshot: dict) -> dict[int, dict]:
|
|
out: dict[int, dict] = {}
|
|
for cat in snapshot.get("categories", []):
|
|
for p in cat.get("products", []):
|
|
if isinstance(p.get("id"), int):
|
|
out.setdefault(p["id"], p) # a product listed in several categories: once
|
|
return out
|
|
|
|
|
|
def price_at(product: dict, point: str) -> float | None:
|
|
"""The product's price at a sales point; None = not sold there."""
|
|
sold = product.get("sold_at")
|
|
if sold is not None and point not in sold:
|
|
return None
|
|
prices = product.get("prices")
|
|
if prices is not None:
|
|
value = prices.get(point)
|
|
return None if value is None else round(float(value), 2)
|
|
base = product.get("digital_price")
|
|
if base is None:
|
|
base = product.get("base_price") or 0.0
|
|
pct = product.get("digital_discount") or 0.0
|
|
return round(float(base) * (1 - float(pct) / 100.0), 2)
|
|
|
|
|
|
def _display_name(product: dict) -> str:
|
|
name = product.get("digital_name") or product.get("name") or f"#{product.get('id')}"
|
|
return name if isinstance(name, str) else str(name)
|
|
|
|
|
|
def _option_ids(raw) -> list:
|
|
out = []
|
|
for o in raw or []:
|
|
oid = o.get("id") if isinstance(o, dict) else o
|
|
if not isinstance(oid, int) or isinstance(oid, bool):
|
|
raise CheckoutError(422, "order.option_unavailable", option_id=oid)
|
|
out.append(oid)
|
|
return out
|
|
|
|
|
|
def price_cart(snapshot: dict, order_type: str, items: list[dict]) -> Priced:
|
|
"""Price the cart from the snapshot. items: [{product_id, quantity, options?}]."""
|
|
point = POINT_FOR_TYPE.get(order_type)
|
|
if point is None:
|
|
raise CheckoutError(422, "order.type_invalid", order_type=order_type)
|
|
if not items:
|
|
raise CheckoutError(422, "order.empty")
|
|
if len(items) > MAX_LINES:
|
|
raise CheckoutError(422, "order.too_many_lines", max=MAX_LINES)
|
|
products = products_of(snapshot)
|
|
lines = []
|
|
for it in items:
|
|
pid, qty = it.get("product_id"), it.get("quantity")
|
|
if isinstance(qty, bool) or not isinstance(qty, int) or not 1 <= qty <= MAX_QTY:
|
|
raise CheckoutError(422, "order.quantity_invalid", product_id=pid, max=MAX_QTY)
|
|
product = products.get(pid) if isinstance(pid, int) else None
|
|
unit = price_at(product, point) if product is not None else None
|
|
if product is None or unit is None or product.get("digital_available") is False:
|
|
raise CheckoutError(409, "order.item_unavailable", product_id=pid,
|
|
name=_display_name(product) if product else None)
|
|
quick = {q.get("id"): q for q in product.get("quick_options") or [] if isinstance(q, dict)}
|
|
options = []
|
|
for oid in _option_ids(it.get("options")):
|
|
q = quick.get(oid)
|
|
if q is None:
|
|
raise CheckoutError(409, "order.option_unavailable", product_id=pid, option_id=oid)
|
|
options.append({"id": oid, "name": q.get("name"), "price": round(float(q.get("price") or 0.0), 2)})
|
|
unit = round(unit + sum(o["price"] for o in options), 2)
|
|
lines.append(Line(product_id=pid, name=_display_name(product), quantity=qty, unit_price=unit, options=options))
|
|
subtotal = round(sum(x.unit_price * x.quantity for x in lines), 2)
|
|
fee = 0.0 # S.3: the venue's fee rules
|
|
return Priced(sales_point=point, lines=lines, subtotal=subtotal, delivery_fee=fee, total=round(subtotal + fee, 2))
|
|
|
|
|
|
def check_sent(priced: Priced, items: list[dict], total: float | None) -> None:
|
|
"""What the browser showed must be what we charge: each line's unit price (if sent) and
|
|
the total (if sent). Otherwise order.price_changed with the current prices."""
|
|
changed = total is not None and abs(float(total) - priced.total) > EPS
|
|
for sent, line in zip(items, priced.lines):
|
|
up = sent.get("unit_price")
|
|
if up is not None and abs(float(up) - line.unit_price) > EPS:
|
|
changed = True
|
|
if changed:
|
|
raise CheckoutError(409, "order.price_changed", **priced.out())
|