Files
xenia-pos-local/local_backend/routers/fees.py
T
bonaminandClaude Opus 5.5 8ea44d71aa feat: online ordering settings (services, hours, preparation, slots) and the order app e2e (platform-v2 3S, S.4)
- connect_orders.ordering setting; GET/PUT /api/connect/fees/ordering (validated:
  services, hours per day incl. past midnight, preparation, slot minutes, days ahead,
  ASAP); pushed to the cloud with the menu (snapshot `ordering`).
- Manager: the Online ordering page gains "Services and hours" (OrderingSettings.jsx; logic
  in feesLogic.js, unit-tested); nav label "Online ordering".
- tests/e2e/order_app.mjs: a real cloud + the built order app in a phone-sized browser:
  takeaway and delivery placed, priced by the cloud (fee by area, minimum refused), the
  site moves the delivery to delivered and the page follows; a rejection with its reason;
  Greek. In run-all, with the order app's unit tests.
- Tests: backend +1 (406), manager unit +1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 13:39:13 +02:00

367 lines
15 KiB
Python

"""Delivery areas and fee rules (plan phase 3S, step S.3). Key: connect_orders.fees.
GET /api/connect/fees {areas, rules, ordering}
GET /api/connect/fees/ordering the online ordering settings PUT: save them
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)}
ORDERING_KEY = "connect_orders.ordering"
SERVICES = ("takeaway", "delivery")
def ordering_settings(db) -> dict:
"""Online ordering (S.4), with defaults: no services until the venue turns them on."""
from models.settings import PosSettings
row = db.query(PosSettings).filter(PosSettings.key == ORDERING_KEY).first()
try:
raw = json.loads(row.value) if row and row.value else {}
except ValueError:
raw = {}
try:
return OrderingBody(**{k: v for k, v in raw.items() if k in OrderingBody.model_fields}).model_dump()
except Exception:
return OrderingBody().model_dump()
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 OrderingBody(BaseModel):
"""What the online ordering app offers and when (plan phase 3S, S.4). The cloud enforces
it at checkout. hours: {"0".."6" (Mon..Sun): [["HH:MM", "HH:MM"], ...]}; no hours at all =
any time; once any day has hours, a day without them is closed. An end before its start
runs past midnight."""
services: List[Literal["takeaway", "delivery"]] = Field(default_factory=list)
hours: dict = Field(default_factory=dict)
prep_minutes: int = Field(default=20, ge=0, le=24 * 60) # earliest collection/delivery after ordering
slot_minutes: int = Field(default=15, ge=5, le=120) # the times offered, every N minutes
days_ahead: int = Field(default=0, ge=0, le=7) # 0 = today only
asap: bool = True # "as soon as possible" offered while open
@field_validator("services")
@classmethod
def _services(cls, v):
return [s for s in SERVICES if s in v]
@field_validator("hours")
@classmethod
def _hours(cls, v):
out = {}
for day, ranges in (v or {}).items():
if str(day) not in {str(d) for d in range(7)}:
raise ValueError("hours are keyed 0 (Monday) to 6 (Sunday)")
if not isinstance(ranges, list) or len(ranges) > 4:
raise ValueError("at most 4 time ranges a day")
clean = []
for r in ranges:
if not (isinstance(r, (list, tuple)) and len(r) == 2 and all(isinstance(x, str) and HHMM.match(x) for x in r)) or r[0] == r[1]:
raise ValueError("a time range is [\"HH:MM\", \"HH:MM\"], start and end different")
clean.append([r[0], r[1]])
if clean:
out[str(day)] = sorted(clean)
return out
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), "ordering": ordering_settings(db)}
@router.get("/ordering")
def get_ordering(db: Session = Depends(get_db), user=Depends(require(KEY))):
return ordering_settings(db)
@router.put("/ordering")
def put_ordering(body: OrderingBody, db: Session = Depends(get_db), user=Depends(require(KEY))):
"""Save the online ordering settings (they reach the cloud with the menu, within seconds)."""
from models.settings import PosSettings
row = db.query(PosSettings).filter(PosSettings.key == ORDERING_KEY).first()
value = json.dumps(body.model_dump())
if row is None:
db.add(PosSettings(key=ORDERING_KEY, value=value))
else:
row.value = value
db.commit()
_changed()
return body.model_dump()
@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}