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
+291
View File
@@ -0,0 +1,291 @@
"""Delivery areas and fee rules (plan phase 3S, step S.3). Key: connect_orders.fees.
GET /api/connect/fees {areas, rules}
POST /api/connect/fees/areas add an area PUT/DELETE /areas/{id}
POST /api/connect/fees/rules add a rule PUT/DELETE /rules/{id}
PUT /api/connect/fees/rules/order [rule ids] in their new order
POST /api/connect/fees/preview "test an order": the engine's answer and why
The rules and areas travel to the cloud with the menu snapshot (services/cloud_sync.py,
contract C-2) and are applied there at checkout by the same engine (services/fees.py). Each
change pushes the menu soon (main.py middleware). Rule semantics: services/fees.py.
"""
from __future__ import annotations
import json
import re
from typing import List, Literal, Optional
from fastapi import APIRouter, Depends
from pydantic import BaseModel, Field, field_validator, model_validator
from sqlalchemy.orm import Session
from core import sales_points
from core.access.deps import require
from core.errors import XeniaError
from database import get_db
router = APIRouter()
KEY = "connect_orders.fees"
HHMM = re.compile(r"^([01]\d|2[0-3]):[0-5]\d$")
SalesPoint = Literal["in_store", "in_store_takeaway", "qr_table", "online_takeaway", "online_delivery", "online_preorder"]
# ── shapes ─────────────────────────────────────────────────────────────────────
def area_out(a) -> dict:
return {"id": a.id, "name": a.name, "postcodes": json.loads(a.postcodes or "[]"),
"is_active": bool(a.is_active), "sort_order": a.sort_order}
def rule_out(r) -> dict:
return {"id": r.id, "name": r.name, "is_active": bool(r.is_active), "sort_order": r.sort_order,
"sales_points": json.loads(r.sales_points or "[]"), "area_ids": json.loads(r.area_ids or "[]"),
"subtotal_min": r.subtotal_min, "subtotal_max": r.subtotal_max,
"items_min": r.items_min, "items_max": r.items_max, "days": json.loads(r.days or "[]"),
"time_from": r.time_from, "time_to": r.time_to, "action": r.action, "value": r.value, "stop": bool(r.stop)}
def fees_payload(db) -> dict:
"""What the engine needs (and the cloud gets): active and inactive alike, in order."""
from models.fees import DeliveryArea, FeeRule
areas = db.query(DeliveryArea).order_by(DeliveryArea.sort_order, DeliveryArea.id).all()
rules = db.query(FeeRule).order_by(FeeRule.sort_order, FeeRule.id).all()
return {"areas": [area_out(a) for a in areas], "rules": [rule_out(r) for r in rules]}
class AreaBody(BaseModel):
name: str = Field(min_length=1, max_length=80)
postcodes: List[str] = Field(default_factory=list, max_length=100)
is_active: bool = True
@field_validator("name")
@classmethod
def _name(cls, v):
v = v.strip()
if not v:
raise ValueError("name is empty")
return v
@field_validator("postcodes")
@classmethod
def _codes(cls, v):
out = []
for code in v:
code = " ".join(str(code).split())
if not code or len(code) > 20:
raise ValueError("a postcode is empty or longer than 20 characters")
if code not in out:
out.append(code)
return out
class RuleBody(BaseModel):
name: str = Field(min_length=1, max_length=80)
is_active: bool = True
sales_points: List[SalesPoint] = Field(default_factory=lambda: ["online_delivery"])
area_ids: List[int] = Field(default_factory=list, max_length=200)
subtotal_min: Optional[float] = Field(default=None, ge=0, le=100000)
subtotal_max: Optional[float] = Field(default=None, gt=0, le=100000)
items_min: Optional[int] = Field(default=None, ge=0, le=10000)
items_max: Optional[int] = Field(default=None, ge=0, le=10000)
days: List[int] = Field(default_factory=list, max_length=7)
time_from: Optional[str] = None
time_to: Optional[str] = None
action: Literal["set", "add", "percent", "free", "minimum"] = "set"
value: float = Field(default=0.0, ge=-1000, le=100000)
stop: bool = False
@field_validator("name")
@classmethod
def _name(cls, v):
v = v.strip()
if not v:
raise ValueError("name is empty")
return v
@field_validator("days")
@classmethod
def _days(cls, v):
if any(d < 0 or d > 6 for d in v):
raise ValueError("days are 0 (Monday) to 6 (Sunday)")
return sorted(set(v))
@field_validator("time_from", "time_to")
@classmethod
def _time(cls, v):
if v in (None, ""):
return None
if not HHMM.match(v):
raise ValueError("times are HH:MM")
return v
@model_validator(mode="after")
def _ranges(self):
if self.subtotal_min is not None and self.subtotal_max is not None and self.subtotal_min >= self.subtotal_max:
raise ValueError("the lower amount must be below the upper one")
if self.items_min is not None and self.items_max is not None and self.items_min > self.items_max:
raise ValueError("the lower item count must not be above the upper one")
if (self.time_from is None) != (self.time_to is None):
raise ValueError("give both times or neither")
if self.action != "add" and self.value < 0:
raise ValueError("only 'add' takes a negative amount")
if self.action == "percent" and self.value > 100:
raise ValueError("a percentage is at most 100")
self.sales_points = sales_points.normalize(self.sales_points)
self.area_ids = sorted(set(self.area_ids))
return self
def _check_areas(db, ids):
from models.fees import DeliveryArea
if ids:
known = {a.id for a in db.query(DeliveryArea).filter(DeliveryArea.id.in_(ids)).all()}
missing = [i for i in ids if i not in known]
if missing:
raise XeniaError("fees.area_not_found", area_id=missing[0])
def _apply_rule(rule, body: RuleBody):
rule.name, rule.is_active, rule.action, rule.value, rule.stop = body.name, int(body.is_active), body.action, body.value, int(body.stop)
rule.sales_points, rule.area_ids, rule.days = json.dumps(body.sales_points), json.dumps(body.area_ids), json.dumps(body.days)
rule.subtotal_min, rule.subtotal_max = body.subtotal_min, body.subtotal_max
rule.items_min, rule.items_max = body.items_min, body.items_max
rule.time_from, rule.time_to = body.time_from, body.time_to
def _changed():
from services.sse_bus import broadcast_sync
broadcast_sync("fees_changed", {})
# ── endpoints ──────────────────────────────────────────────────────────────────
@router.get("")
def list_fees(db: Session = Depends(get_db), user=Depends(require(KEY))):
return fees_payload(db)
@router.post("/areas", status_code=201)
def add_area(body: AreaBody, db: Session = Depends(get_db), user=Depends(require(KEY))):
from models.fees import DeliveryArea
count = db.query(DeliveryArea).count()
area = DeliveryArea(name=body.name, postcodes=json.dumps(body.postcodes), is_active=int(body.is_active), sort_order=count)
db.add(area)
db.commit()
_changed()
return area_out(area)
@router.put("/areas/{area_id}")
def edit_area(area_id: int, body: AreaBody, db: Session = Depends(get_db), user=Depends(require(KEY))):
from models.fees import DeliveryArea
area = db.get(DeliveryArea, area_id)
if area is None:
raise XeniaError("fees.area_not_found", area_id=area_id)
area.name, area.postcodes, area.is_active = body.name, json.dumps(body.postcodes), int(body.is_active)
db.commit()
_changed()
return area_out(area)
@router.delete("/areas/{area_id}", status_code=204)
def delete_area(area_id: int, db: Session = Depends(get_db), user=Depends(require(KEY))):
"""Refused while a rule names the area (fees.area_in_use {rules}): change those rules first."""
from models.fees import DeliveryArea, FeeRule
area = db.get(DeliveryArea, area_id)
if area is None:
raise XeniaError("fees.area_not_found", area_id=area_id)
users = [r.name for r in db.query(FeeRule).all() if area_id in json.loads(r.area_ids or "[]")]
if users:
raise XeniaError("fees.area_in_use", rules=", ".join(users))
db.delete(area)
db.commit()
_changed()
@router.post("/rules", status_code=201)
def add_rule(body: RuleBody, db: Session = Depends(get_db), user=Depends(require(KEY))):
from models.fees import FeeRule
_check_areas(db, body.area_ids)
rule = FeeRule(sort_order=db.query(FeeRule).count())
_apply_rule(rule, body)
db.add(rule)
db.commit()
_changed()
return rule_out(rule)
@router.put("/rules/order")
def order_rules(ids: List[int], db: Session = Depends(get_db), user=Depends(require(KEY))):
"""The rules in their new order: every rule id once."""
from models.fees import FeeRule
rules = {r.id: r for r in db.query(FeeRule).all()}
if sorted(ids) != sorted(rules):
raise XeniaError("fees.order_invalid")
for n, rid in enumerate(ids):
rules[rid].sort_order = n
db.commit()
_changed()
return fees_payload(db)
@router.put("/rules/{rule_id}")
def edit_rule(rule_id: int, body: RuleBody, db: Session = Depends(get_db), user=Depends(require(KEY))):
from models.fees import FeeRule
rule = db.get(FeeRule, rule_id)
if rule is None:
raise XeniaError("fees.rule_not_found", rule_id=rule_id)
_check_areas(db, body.area_ids)
_apply_rule(rule, body)
db.commit()
_changed()
return rule_out(rule)
@router.delete("/rules/{rule_id}", status_code=204)
def delete_rule(rule_id: int, db: Session = Depends(get_db), user=Depends(require(KEY))):
from models.fees import FeeRule
rule = db.get(FeeRule, rule_id)
if rule is None:
raise XeniaError("fees.rule_not_found", rule_id=rule_id)
db.delete(rule)
db.commit()
_changed()
class PreviewBody(BaseModel):
sales_point: SalesPoint = "online_delivery"
area_id: Optional[int] = None
postcode: Optional[str] = Field(default=None, max_length=20)
subtotal: float = Field(ge=0, le=100000)
items: int = Field(ge=0, le=10000)
weekday: Optional[int] = Field(default=None, ge=0, le=6) # venue's now when omitted
time: Optional[str] = None # "HH:MM", venue's now when omitted
@field_validator("time")
@classmethod
def _time(cls, v):
if v in (None, ""):
return None
if not HHMM.match(v):
raise ValueError("times are HH:MM")
return v
@router.post("/preview")
def preview(body: PreviewBody, db: Session = Depends(get_db), user=Depends(require(KEY))):
"""Test an order: the fee (or why it's refused) and the rules that applied, exactly as the
cloud will compute it at checkout."""
from core.timeutil import venue_now
from services import fees
data = fees_payload(db)
now = venue_now()
weekday = body.weekday if body.weekday is not None else now.weekday()
hhmm = body.time or now.strftime("%H:%M")
result = fees.compute(data["rules"], data["areas"], sales_point=body.sales_point, subtotal=body.subtotal,
items=body.items, area_id=body.area_id, postcode=body.postcode, weekday=weekday, hhmm=hhmm)
area = next((a for a in data["areas"] if a["id"] == result["area_id"]), None)
return {**result, "area_name": area["name"] if area else None, "weekday": weekday, "time": hhmm,
"total": round(body.subtotal + result["fee"], 2) if not result["refused"] else None}