- services/fees.py: the site's engine (shapes matched by the pin), shared cases - checkout: price_cart(pin=), delivery_areas with kind (+ geometry for shapes), venue_point in the public menu (postcodes and rules stay on the cloud) - orders: quote / create take lat / lng; online_orders.lat / lng (Alembic 0007), sent to the site with the pending orders - order app: PinMap (Leaflet + OpenStreetMap tiles), 'Pin it on the map' first when the venue drew areas, the browser's location offered; lat / lng sent - tests: cloud test_fees (pinned quote and order), order-app logic Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
211 lines
9.3 KiB
Python
211 lines
9.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 %.
|
|
|
|
The fee (S.3): the snapshot's `fees` {areas, rules} through services/fees.py (the same file
|
|
as the site's) at the venue's time (`timezone`). A delivery outside the venue's areas ->
|
|
order.area_not_served; below a minimum -> order.minimum_not_met {minimum, subtotal}.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
from dataclasses import dataclass, field
|
|
from datetime import datetime, timezone
|
|
from zoneinfo import ZoneInfo
|
|
|
|
from services import fees as fee_engine
|
|
|
|
# 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
|
|
area_id: int | None = None
|
|
area_name: str | None = None
|
|
fee_rules: list = field(default_factory=list) # names of the rules that applied
|
|
|
|
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,
|
|
"area_id": self.area_id, "area_name": self.area_name, "fee_rules": self.fee_rules}
|
|
|
|
|
|
def venue_clock(snapshot: dict, now: datetime | None = None) -> tuple[int, str]:
|
|
"""(weekday Mon=0, "HH:MM") at the venue, from the snapshot's time zone."""
|
|
try:
|
|
tz = ZoneInfo(snapshot.get("timezone") or "Europe/Athens")
|
|
except Exception:
|
|
tz = ZoneInfo("Europe/Athens")
|
|
local = (now or datetime.now(timezone.utc)).astimezone(tz)
|
|
return local.weekday(), local.strftime("%H:%M")
|
|
|
|
|
|
def delivery_areas(snapshot: dict) -> list:
|
|
"""The active areas: [{id, name, kind}] (no postcodes, no rules). A postcode area is picked
|
|
from a list; a shape (6R.G: polygon / circle) also gives its geometry, so the customer's map
|
|
can draw where the venue delivers; the cloud matches it by the customer's pin."""
|
|
out = []
|
|
for a in (snapshot.get("fees") or {}).get("areas") or []:
|
|
if not a.get("is_active", True):
|
|
continue
|
|
kind = a.get("kind") or "postcodes"
|
|
item = {"id": a.get("id"), "name": a.get("name"), "kind": kind}
|
|
if kind in fee_engine.SHAPES:
|
|
item["geometry"] = a.get("geometry")
|
|
out.append(item)
|
|
return out
|
|
|
|
|
|
def venue_point(snapshot: dict):
|
|
"""The venue's place on the map (6R.G): {lat, lng} or None; the customer's map starts there."""
|
|
return (snapshot.get("fees") or {}).get("venue_point")
|
|
|
|
|
|
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], area_id=None, postcode=None,
|
|
now: datetime | None = None, pin=None) -> Priced:
|
|
"""Price the cart from the snapshot. items: [{product_id, quantity, options?}]; the
|
|
customer's area (picked, by their `pin` [lat, lng] on the map (6R.G), or by postcode) for the fee."""
|
|
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)
|
|
rules = snapshot.get("fees") or {}
|
|
weekday, hhmm = venue_clock(snapshot, now)
|
|
result = fee_engine.compute(rules.get("rules") or [], rules.get("areas") or [], sales_point=point,
|
|
subtotal=subtotal, items=sum(x.quantity for x in lines),
|
|
area_id=area_id, postcode=postcode, weekday=weekday, hhmm=hhmm,
|
|
point=pin)
|
|
if result["refused"] == "area_not_served":
|
|
raise CheckoutError(409, "order.area_not_served", postcode=postcode, area_id=area_id)
|
|
if result["refused"] == "minimum_not_met":
|
|
raise CheckoutError(409, "order.minimum_not_met", minimum=result["minimum"], subtotal=subtotal)
|
|
fee = result["fee"]
|
|
area = next((a for a in rules.get("areas") or [] if a.get("id") == result["area_id"]), None)
|
|
return Priced(sales_point=point, lines=lines, subtotal=subtotal, delivery_fee=fee, total=round(subtotal + fee, 2),
|
|
area_id=result["area_id"], area_name=area.get("name") if area else None,
|
|
fee_rules=[a["name"] for a in result["applied"] if a["action"] != "minimum"])
|
|
|
|
|
|
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())
|