feat: delivery areas and fee rules with "test an order" (platform-v2 3S, S.3)

- models/fees.py + Alembic 0018: delivery_areas, fee_rules; key connect_orders.fees
  (owner, store manager; existing ones get it).
- services/fees.py: the pure engine (set / add / % / free / minimum, conditions: sales
  points, areas, products total, item count, days, time incl. past midnight, stop), the
  same file as the cloud's; tests/fixtures/fee_cases.json shared, plus a test that the
  cloud copy is identical.
- routers/fees.py at /api/connect/fees: areas and rules CRUD (validated), order, preview.
- Snapshot carries fees + the venue's time zone; a change to products, pricing or fees
  pushes the menu within ~5 s (middleware -> cloud_sync.request_menu_push).
- Manager: Online -> Delivery fees page (@xenia/ui): rules in order with words for each,
  areas with postcodes, "Test an order"; en/el texts; feesLogic.js unit-tested.
- Tests: test_fees.py (39), manager unit +5, manager.mjs +7 on the real page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-15 12:28:29 +02:00
co-authored by Claude Opus 5.5
parent ffeb2b45cb
commit 9bfe54554d
24 changed files with 1723 additions and 9 deletions
+38 -3
View File
@@ -292,7 +292,11 @@ def menu_snapshot(db) -> tuple[dict, list]:
if product_list:
payload_categories.append({"id": cat.id, "name": cat.name, "sort_order": cat.sort_order,
"products": product_list})
return {"categories": payload_categories}, all_products
# delivery areas and fee rules (S.3): the cloud applies them at checkout with the same
# engine (services/fees.py); the venue's time zone says what "22:00" and "Saturday" mean
from core.timeutil import venue_tz
from routers.fees import fees_payload
return {"categories": payload_categories, "fees": fees_payload(db), "timezone": venue_tz().key}, all_products
async def _push_menu_snapshot():
@@ -307,7 +311,7 @@ async def _push_menu_snapshot():
try:
snapshot, all_products = menu_snapshot(db)
payload_categories = snapshot["categories"]
snapshot_json = json.dumps({"categories": payload_categories})
snapshot_json = json.dumps(snapshot)
# Resolve numeric site_id from license state (set by heartbeat response)
site_numeric_id = license_state.get("site_numeric_id")
@@ -576,11 +580,42 @@ async def _wait_for_site_id(max_seconds: int = 30) -> None:
await asyncio.sleep(1)
# A change to what the customer apps sell (products, price rules, fees) pushes the menu soon,
# not at the next 5-minute tick (phase 3S): request_menu_push() from any thread wakes the
# worker; edits in a row within MENU_SETTLE_SECONDS become one push.
MENU_SETTLE_SECONDS = 5
MENU_PATHS = ("/api/products", "/api/pricing", "/api/connect/fees", "/api/data-transfer/import")
_menu_wake: "asyncio.Event | None" = None
_menu_loop = None
def request_menu_push() -> None:
"""Ask the menu worker to push soon. Thread-safe; nothing happens while it isn't running."""
loop, wake = _menu_loop, _menu_wake
if loop is not None and wake is not None:
try:
loop.call_soon_threadsafe(wake.set)
except RuntimeError: # the loop has closed
pass
def menu_changed(method: str, path: str, status_code: int) -> bool:
"""Whether a finished request changed what the customer apps sell."""
return method not in ("GET", "HEAD", "OPTIONS") and status_code < 400 and path.startswith(MENU_PATHS)
async def menu_push_worker():
global _menu_wake, _menu_loop
_menu_loop, _menu_wake = asyncio.get_running_loop(), asyncio.Event()
await _wait_for_site_id()
while True:
_menu_wake.clear()
await _push_menu_snapshot()
await asyncio.sleep(PUSH_INTERVAL_SECONDS)
try:
await asyncio.wait_for(_menu_wake.wait(), PUSH_INTERVAL_SECONDS)
await asyncio.sleep(MENU_SETTLE_SECONDS)
except asyncio.TimeoutError:
pass
async def stats_push_worker():
+128
View File
@@ -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