feat(cloud): delivery fees and minimum orders at checkout (platform-v2 3S, S.3)
- services/fees.py: the site's fee engine, byte-identical (the site's tests check it);
tests/fixtures/fee_cases.json: the shared cases, run here too.
- checkout: the snapshot's fees (areas, rules) at the venue's time zone; refused
order.area_not_served / order.minimum_not_met {minimum, subtotal}; quote and order take
area_id / postcode and return area_name, fee_rules; the order stores delivery_area.
- GET /api/menu/{site}: delivery_areas [{id, name}] for the customer; the rules and
postcodes are never sent to the browser.
- Alembic 0003 (unreleased) gains online_orders.delivery_area.
- Tests: test_fees.py (22 shared cases + checkout fees, refusals, public menu, clock).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -13,10 +13,18 @@ Snapshot product (site services/cloud_sync._push_menu_snapshot):
|
||||
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 = {
|
||||
@@ -60,10 +68,30 @@ class Priced:
|
||||
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}
|
||||
"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 a customer picks from: [{id, name}] (no postcodes, no rules)."""
|
||||
return [{"id": a.get("id"), "name": a.get("name")} for a in (snapshot.get("fees") or {}).get("areas") or []
|
||||
if a.get("is_active", True)]
|
||||
|
||||
|
||||
def products_of(snapshot: dict) -> dict[int, dict]:
|
||||
@@ -106,8 +134,10 @@ def _option_ids(raw) -> list:
|
||||
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?}]."""
|
||||
def price_cart(snapshot: dict, order_type: str, items: list[dict], area_id=None, postcode=None,
|
||||
now: datetime | None = None) -> Priced:
|
||||
"""Price the cart from the snapshot. items: [{product_id, quantity, options?}]; the
|
||||
customer's area (picked, 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)
|
||||
@@ -136,8 +166,20 @@ def price_cart(snapshot: dict, order_type: str, items: list[dict]) -> Priced:
|
||||
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))
|
||||
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)
|
||||
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:
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
"""Delivery fees and minimum orders (plan phase 3S, step S.3).
|
||||
|
||||
ONE engine, two copies: client-services/local_backend/services/fees.py (the manager's "test
|
||||
an order", the site's check of pulled orders) and cloud-service/cloud_backend/services/fees.py
|
||||
(checkout). The files are identical and both repos run the same cases
|
||||
(tests/fixtures/fee_cases.json); a site test fails if the copies differ. Pure Python: plain
|
||||
dicts in, a dict out, no database, no clock (the caller gives the venue's weekday and time).
|
||||
|
||||
compute(rules, areas, *, sales_point, subtotal, items, area_id=None, postcode=None,
|
||||
weekday=None, hhmm=None) -> {"fee", "refused", "minimum", "area_id", "applied"}
|
||||
|
||||
Areas: {id, name, postcodes: [str], is_active}. The customer's area is the one picked (by id)
|
||||
or the one whose postcodes contain theirs (spaces ignored). When the venue has active areas,
|
||||
a delivery to none of them is refused ("area_not_served"); with no areas, anywhere is fine.
|
||||
|
||||
Rules: {id, name, is_active, sort_order, sales_points: [..], area_ids: [..], subtotal_min,
|
||||
subtotal_max, items_min, items_max, days: [0-6], time_from, time_to, action, value, stop}.
|
||||
Inactive rules are skipped; the rest are looked at in (sort_order, id) order. A rule applies
|
||||
when every condition it sets holds (empty lists / nulls = any):
|
||||
sales point in sales_points · area in area_ids · subtotal_min <= subtotal < subtotal_max ·
|
||||
items_min <= items <= items_max · weekday in days · time_from <= time < time_to (crosses
|
||||
midnight when time_from > time_to)
|
||||
What an applying rule does to the fee (which starts at 0):
|
||||
set fee = value add fee += value
|
||||
percent fee += subtotal × value / 100
|
||||
free fee = 0 minimum refuse the order when subtotal < value
|
||||
`stop`: once this rule applies, no later rule is looked at (first match wins). The fee is
|
||||
never negative and is rounded to cents.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
EPS = 0.0005
|
||||
ACTIONS = ("set", "add", "percent", "free", "minimum")
|
||||
|
||||
|
||||
def _norm_postcode(value) -> str:
|
||||
return "".join(str(value or "").split()).upper()
|
||||
|
||||
|
||||
def resolve_area(areas: list, area_id=None, postcode=None):
|
||||
"""The customer's active area: by id, else by postcode; None when neither matches."""
|
||||
active = [a for a in areas or [] if a.get("is_active", True)]
|
||||
if area_id is not None:
|
||||
for a in active:
|
||||
if a.get("id") == area_id:
|
||||
return a
|
||||
code = _norm_postcode(postcode)
|
||||
if code:
|
||||
for a in active:
|
||||
if code in {_norm_postcode(p) for p in a.get("postcodes") or []}:
|
||||
return a
|
||||
return None
|
||||
|
||||
|
||||
def _minutes(hhmm):
|
||||
try:
|
||||
h, m = str(hhmm).split(":")
|
||||
h, m = int(h), int(m)
|
||||
except (ValueError, TypeError):
|
||||
return None
|
||||
return h * 60 + m if 0 <= h <= 23 and 0 <= m <= 59 else None
|
||||
|
||||
|
||||
def _in_time(rule, hhmm) -> bool:
|
||||
start, end = _minutes(rule.get("time_from")), _minutes(rule.get("time_to"))
|
||||
if start is None and end is None:
|
||||
return True
|
||||
now = _minutes(hhmm)
|
||||
if now is None:
|
||||
return False
|
||||
start = 0 if start is None else start
|
||||
end = 24 * 60 if end is None else end
|
||||
return start <= now < end if start <= end else (now >= start or now < end)
|
||||
|
||||
|
||||
def applies(rule, *, sales_point, subtotal, items, area, weekday, hhmm) -> bool:
|
||||
if rule.get("sales_points") and sales_point not in rule["sales_points"]:
|
||||
return False
|
||||
if rule.get("area_ids") and (area is None or area.get("id") not in rule["area_ids"]):
|
||||
return False
|
||||
if rule.get("subtotal_min") is not None and subtotal + EPS < rule["subtotal_min"]:
|
||||
return False
|
||||
if rule.get("subtotal_max") is not None and subtotal + EPS >= rule["subtotal_max"]:
|
||||
return False
|
||||
if rule.get("items_min") is not None and items < rule["items_min"]:
|
||||
return False
|
||||
if rule.get("items_max") is not None and items > rule["items_max"]:
|
||||
return False
|
||||
if rule.get("days") and weekday not in rule["days"]:
|
||||
return False
|
||||
return _in_time(rule, hhmm)
|
||||
|
||||
|
||||
def compute(rules, areas, *, sales_point, subtotal, items, area_id=None, postcode=None,
|
||||
weekday=None, hhmm=None) -> dict:
|
||||
area = resolve_area(areas, area_id, postcode)
|
||||
result = {"fee": 0.0, "refused": None, "minimum": None, "area_id": area.get("id") if area else None, "applied": []}
|
||||
if sales_point == "online_delivery" and area is None and any(a.get("is_active", True) for a in areas or []):
|
||||
result["refused"] = "area_not_served"
|
||||
return result
|
||||
fee = 0.0
|
||||
ordered = sorted((r for r in rules or [] if r.get("is_active", True) and r.get("action") in ACTIONS),
|
||||
key=lambda r: (r.get("sort_order") or 0, r.get("id") or 0))
|
||||
for rule in ordered:
|
||||
if not applies(rule, sales_point=sales_point, subtotal=subtotal, items=items, area=area,
|
||||
weekday=weekday, hhmm=hhmm):
|
||||
continue
|
||||
action, value = rule["action"], float(rule.get("value") or 0.0)
|
||||
if action == "minimum":
|
||||
if subtotal + EPS < value:
|
||||
result.update(refused="minimum_not_met", minimum=round(value, 2), fee=round(max(fee, 0.0), 2))
|
||||
result["applied"].append({"rule_id": rule.get("id"), "name": rule.get("name"), "action": action,
|
||||
"value": value, "fee": round(max(fee, 0.0), 2)})
|
||||
return result
|
||||
elif action == "set":
|
||||
fee = value
|
||||
elif action == "add":
|
||||
fee += value
|
||||
elif action == "percent":
|
||||
fee += subtotal * value / 100.0
|
||||
elif action == "free":
|
||||
fee = 0.0
|
||||
result["applied"].append({"rule_id": rule.get("id"), "name": rule.get("name"), "action": action,
|
||||
"value": value, "fee": round(max(fee, 0.0), 2)})
|
||||
if rule.get("stop"):
|
||||
break
|
||||
result["fee"] = round(max(fee, 0.0), 2)
|
||||
return result
|
||||
Reference in New Issue
Block a user