Plan phase 3S, step S.5. - Pull: an online order keeps the customer's time (orders.requested_for, None = as soon as possible) and delivery area; quick options are stored in the site's entry shape; items get their cost snapshot. - The delivery fee is its own order line: a system product (products.system_key "delivery_fee", lifecycle "system", sold nowhere; services/system_products.py), created on first use in the venue's language with the VAT group most products use. Added printed and served, so kitchen tickets and the KDS never see it; paid at the counter with the items, counted in the shift, on the fiscal receipt with its VAT group. Never listed in the catalogue (products list, export, edit endpoints → 404) and never added by hand. - Price check (services/online_check.py): each line priced as the snapshot prices it, at the order's time, and the fee through the same engine with the site's rules and the cloud's area id; differences kept on orders.online_price_diff and shown. The customer pays what the cloud charged. - Counter: time chip (or as soon as possible), area, fee line, price warning; takeaway is its own kind (was shown as "at the venue") and finishes as "collected". KDS cards show the online reference and the time; kitchen tickets print the reference, the type and the time. - Manager: Online ordering → "The fee on the receipt" (name, VAT group; PUT /api/connect/fees/fee-product, fees.vat_group_unknown); the online orders page shows the time, area and price warning. - Migration 0019. Tests: tests/test_online_site_side.py (6), terminal unit test, e2e (terminal: fee, time, warning, paid in full; manager: fee line settings). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
414 lines
17 KiB
Python
414 lines
17 KiB
Python
"""Delivery areas and fee rules (plan phase 3S, step S.3). Key: connect_orders.fees.
|
|
|
|
GET /api/connect/fees {areas, rules, ordering, fee_product}
|
|
PUT /api/connect/fees/fee-product the delivery fee line's name and VAT group (S.5)
|
|
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))):
|
|
from services import system_products
|
|
fee_product = system_products.get(db, system_products.DELIVERY_FEE)
|
|
db.commit()
|
|
return {**fees_payload(db), "ordering": ordering_settings(db),
|
|
"fee_product": {**system_products.out(fee_product), "vat_groups": _vat_groups(db)}}
|
|
|
|
|
|
def _vat_groups(db) -> list[dict]:
|
|
"""The fiscal machine's VAT groups (setting fiscal.vat_groups): [{machine_id, friendly_name}]."""
|
|
from models.settings import PosSettings
|
|
row = db.query(PosSettings).filter(PosSettings.key == "fiscal.vat_groups").first()
|
|
try:
|
|
groups = json.loads(row.value or "[]") if row else []
|
|
except (TypeError, ValueError):
|
|
return []
|
|
return [{"machine_id": g.get("machine_id"), "friendly_name": g.get("friendly_name")}
|
|
for g in groups if isinstance(g, dict) and isinstance(g.get("machine_id"), int)]
|
|
|
|
|
|
class FeeProductBody(BaseModel):
|
|
"""How the delivery fee line is called (on screens and the receipt) and its VAT group."""
|
|
name: str = Field(min_length=1, max_length=40)
|
|
vat_group_id: Optional[int] = Field(default=None, ge=1, le=99)
|
|
|
|
@field_validator("name")
|
|
@classmethod
|
|
def _strip(cls, v: str) -> str:
|
|
v = v.strip()
|
|
if not v:
|
|
raise ValueError("empty")
|
|
return v
|
|
|
|
|
|
@router.put("/fee-product")
|
|
def put_fee_product(body: FeeProductBody, db: Session = Depends(get_db), user=Depends(require(KEY))):
|
|
"""The delivery fee's system product (services/system_products.py). Lines already on orders
|
|
keep the name they were added with; the VAT group counts from the next receipt."""
|
|
from services import system_products
|
|
if body.vat_group_id is not None:
|
|
groups = [g["machine_id"] for g in _vat_groups(db)]
|
|
if groups and body.vat_group_id not in groups:
|
|
raise XeniaError("fees.vat_group_unknown", vat_group_id=body.vat_group_id)
|
|
product = system_products.get(db, system_products.DELIVERY_FEE)
|
|
product.name = product.fiscal_name = body.name
|
|
product.fiscal_vat_group_id = body.vat_group_id
|
|
db.commit()
|
|
return system_products.out(product)
|
|
|
|
|
|
@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}
|