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
+4
View File
@@ -75,6 +75,10 @@ CODES: dict[str, tuple[int, str]] = {
"pos.items_changed": (409, "Some of these items were paid or cancelled in the meantime. Check the order and try again."),
"pos.order_unpaid": (409, "Items still unpaid: {count}. Take the payment or cancel them first."),
"order.not_sold_here": (422, "{name} isn't sold for this kind of order."),
"fees.area_not_found": (404, "Delivery area {area_id} not found."),
"fees.rule_not_found": (404, "Fee rule {rule_id} not found."),
"fees.area_in_use": (409, "This area is used by fee rules: {rules}. Change those rules first."),
"fees.order_invalid": (422, "The new order must list every rule once."),
"refund.invalid": (422, "This refund doesn't add up ({reason})."),
"refund.too_old": (409, "Only payments from today's business day can be refunded at the counter."),
"refund.items_changed": (409, "Some of these items were refunded in the meantime. Check the order and try again."),
+13
View File
@@ -93,6 +93,19 @@ app.add_middleware(
allow_headers=["*"],
)
# (v1's LicenseCheckMiddleware is gone: an unlicensed site gets the free tier, module by module, D-5.)
@app.middleware("http")
async def _menu_change_push(request, call_next):
"""A successful change to products, price rules or fees pushes the customer apps' menu
soon (phase 3S; services/cloud_sync.request_menu_push)."""
response = await call_next(request)
from services.cloud_sync import menu_changed, request_menu_push
if menu_changed(request.method, request.url.path, response.status_code):
request_menu_push()
return response
# Added last = outermost: the request id exists before any other middleware runs.
app.add_middleware(RequestContextMiddleware)
@@ -0,0 +1,62 @@
"""delivery_areas + fee_rules; key connect_orders.fees for owners and managers (plan phase 3S, S.3)
Revision ID: 0018_fee_rules
Revises: 0017_sales_points
Create Date: 2026-11-16 10:00:00
"""
from alembic import op
import sqlalchemy as sa
from core.timeutil import UTCDateTime
revision = '0018_fee_rules'
down_revision = '0017_sales_points'
branch_labels = None
depends_on = None
def upgrade() -> None:
op.create_table('delivery_areas',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(), nullable=False),
sa.Column('postcodes', sa.Text(), nullable=False),
sa.Column('is_active', sa.Integer(), nullable=False),
sa.Column('sort_order', sa.Integer(), nullable=False),
sa.Column('created_at', UTCDateTime(), nullable=True),
sa.PrimaryKeyConstraint('id'),
)
with op.batch_alter_table('delivery_areas', schema=None) as batch_op:
batch_op.create_index(batch_op.f('ix_delivery_areas_id'), ['id'], unique=False)
op.create_table('fee_rules',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(), nullable=False),
sa.Column('is_active', sa.Integer(), nullable=False),
sa.Column('sort_order', sa.Integer(), nullable=False),
sa.Column('sales_points', sa.Text(), nullable=False),
sa.Column('area_ids', sa.Text(), nullable=False),
sa.Column('subtotal_min', sa.Float(), nullable=True),
sa.Column('subtotal_max', sa.Float(), nullable=True),
sa.Column('items_min', sa.Integer(), nullable=True),
sa.Column('items_max', sa.Integer(), nullable=True),
sa.Column('days', sa.Text(), nullable=False),
sa.Column('time_from', sa.String(), nullable=True),
sa.Column('time_to', sa.String(), nullable=True),
sa.Column('action', sa.String(), nullable=False),
sa.Column('value', sa.Float(), nullable=False),
sa.Column('stop', sa.Integer(), nullable=False),
sa.Column('created_at', UTCDateTime(), nullable=True),
sa.PrimaryKeyConstraint('id'),
)
with op.batch_alter_table('fee_rules', schema=None) as batch_op:
batch_op.create_index(batch_op.f('ix_fee_rules_id'), ['id'], unique=False)
op.get_bind().execute(sa.text("insert or ignore into user_permissions (user_id, key) "
"select id, 'connect_orders.fees' from users where role in ('owner', 'store_manager')"))
def downgrade() -> None:
op.get_bind().execute(sa.text("delete from user_permissions where key = 'connect_orders.fees'"))
op.drop_table('fee_rules')
op.drop_table('delivery_areas')
+1
View File
@@ -34,4 +34,5 @@ import models.device # noqa: F401 Device, DevicePairRequest (step 1.8)
import models.access_override # noqa: F401 AccessOverride (manager override, step 1.9)
import models.support_challenge # noqa: F401 SupportChallenge (support access, step 1.10)
import models.notification # noqa: F401 Notification, NotificationRead (step 1.11)
import models.fees # noqa: F401 DeliveryArea, FeeRule (phase 3S, S.3)
import models.refund # noqa: F401 Refund, RefundItem (step 3.3e)
+46
View File
@@ -0,0 +1,46 @@
"""Delivery areas and fee rules (plan phase 3S, step S.3).
The venue lists the areas it delivers to (by name, with postcodes when it wants the customer's
postcode matched) and fee rules evaluated in order by services/fees.py — the same engine the
cloud runs at checkout (the rules travel with the menu snapshot). See that module for the
rule semantics.
"""
from sqlalchemy import Column, Float, Integer, String, Text
from core.timeutil import UTCDateTime, utcnow
from database import Base
class DeliveryArea(Base):
__tablename__ = "delivery_areas"
id = Column(Integer, primary_key=True, index=True)
name = Column(String, nullable=False)
postcodes = Column(Text, nullable=False, default="[]") # JSON list of strings
is_active = Column(Integer, nullable=False, default=1)
sort_order = Column(Integer, nullable=False, default=0)
created_at = Column(UTCDateTime, default=utcnow)
class FeeRule(Base):
__tablename__ = "fee_rules"
id = Column(Integer, primary_key=True, index=True)
name = Column(String, nullable=False)
is_active = Column(Integer, nullable=False, default=1)
sort_order = Column(Integer, nullable=False, default=0)
# conditions (empty / null = any)
sales_points = Column(Text, nullable=False, default='["online_delivery"]') # JSON list
area_ids = Column(Text, nullable=False, default="[]") # JSON list of ints
subtotal_min = Column(Float, nullable=True) # products total >= this
subtotal_max = Column(Float, nullable=True) # products total < this
items_min = Column(Integer, nullable=True) # number of items >= this
items_max = Column(Integer, nullable=True) # number of items <= this
days = Column(Text, nullable=False, default="[]") # JSON list, Mon=0 … Sun=6
time_from = Column(String, nullable=True) # "HH:MM", venue time
time_to = Column(String, nullable=True) # "HH:MM"; before time_from = crosses midnight
# what it does: set | add | percent | free | minimum
action = Column(String, nullable=False, default="set")
value = Column(Float, nullable=False, default=0.0)
stop = Column(Integer, nullable=False, default=0) # no later rule is looked at once this one applies
created_at = Column(UTCDateTime, default=utcnow)
@@ -9,8 +9,10 @@ MODULE = Module(
depends=('ordering', 'connect_menu'),
permissions=(
Perm('connect_orders.manage', 'Accept and manage online orders', roles=('owner', 'store_manager', 'staff_manager', 'barista', 'barman')),
Perm('connect_orders.fees', 'Set delivery areas and fees', roles=('owner', 'store_manager')),
),
routers=(
Mount('routers.fees', '/api/connect/fees'),
Mount('routers.connect_orders', '/api/connect'),
),
workers=('services.cloud_sync:order_pull_worker',),
+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}
+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
+108
View File
@@ -0,0 +1,108 @@
{
"_about": "Delivery fee cases (plan phase 3S, S.3). The SAME file in client-services/local_backend/tests/fixtures and cloud-service/cloud_backend/tests/fixtures; both repos run every case through their copy of services/fees.py.",
"areas": [
{"id": 1, "name": "Village centre", "postcodes": ["241 00"], "is_active": true},
{"id": 2, "name": "Kalamata", "postcodes": ["24100", "24131"], "is_active": true},
{"id": 3, "name": "Old area", "postcodes": ["99999"], "is_active": false}
],
"cases": [
{"name": "no rules: free",
"rules": [], "ctx": {"sales_point": "online_delivery", "subtotal": 12, "items": 2, "area_id": 1},
"expect": {"fee": 0.0, "refused": null, "area_id": 1}},
{"name": "fixed fee",
"rules": [{"id": 1, "name": "Delivery", "sales_points": ["online_delivery"], "action": "set", "value": 2.5}],
"ctx": {"sales_point": "online_delivery", "subtotal": 12, "items": 2, "area_id": 1},
"expect": {"fee": 2.5, "refused": null, "area_id": 1}},
{"name": "fixed fee does not touch takeaway",
"rules": [{"id": 1, "name": "Delivery", "sales_points": ["online_delivery"], "action": "set", "value": 2.5}],
"ctx": {"sales_point": "online_takeaway", "subtotal": 12, "items": 2},
"expect": {"fee": 0.0, "refused": null, "area_id": null}},
{"name": "by area: the far area costs more (area by postcode, spaces ignored)",
"rules": [{"id": 1, "name": "Base", "action": "set", "value": 1.5},
{"id": 2, "name": "Kalamata", "area_ids": [2], "action": "set", "value": 3.5}],
"ctx": {"sales_point": "online_delivery", "subtotal": 20, "items": 3, "postcode": "241 31"},
"expect": {"fee": 3.5, "refused": null, "area_id": 2}},
{"name": "by area: the near area keeps the base",
"rules": [{"id": 1, "name": "Base", "action": "set", "value": 1.5},
{"id": 2, "name": "Kalamata", "area_ids": [2], "action": "set", "value": 3.5}],
"ctx": {"sales_point": "online_delivery", "subtotal": 20, "items": 3, "area_id": 1},
"expect": {"fee": 1.5, "refused": null, "area_id": 1}},
{"name": "area not served (unknown postcode)",
"rules": [{"id": 1, "name": "Base", "action": "set", "value": 1.5}],
"ctx": {"sales_point": "online_delivery", "subtotal": 20, "items": 3, "postcode": "11111"},
"expect": {"fee": 0.0, "refused": "area_not_served", "area_id": null}},
{"name": "an inactive area is not served",
"rules": [], "ctx": {"sales_point": "online_delivery", "subtotal": 20, "items": 3, "area_id": 3},
"expect": {"fee": 0.0, "refused": "area_not_served", "area_id": null}},
{"name": "free above 25 (first match wins)",
"rules": [{"id": 1, "name": "Free over 25", "subtotal_min": 25, "action": "free", "stop": true, "sort_order": 0},
{"id": 2, "name": "Base", "action": "set", "value": 2.0, "sort_order": 1}],
"ctx": {"sales_point": "online_delivery", "subtotal": 30, "items": 4, "area_id": 1},
"expect": {"fee": 0.0, "refused": null, "area_id": 1}},
{"name": "free above 25: below it pays",
"rules": [{"id": 1, "name": "Free over 25", "subtotal_min": 25, "action": "free", "stop": true, "sort_order": 0},
{"id": 2, "name": "Base", "action": "set", "value": 2.0, "sort_order": 1}],
"ctx": {"sales_point": "online_delivery", "subtotal": 24.99, "items": 4, "area_id": 1},
"expect": {"fee": 2.0, "refused": null, "area_id": 1}},
{"name": "lower above 15 (subtotal range)",
"rules": [{"id": 1, "name": "Under 15", "subtotal_max": 15, "action": "set", "value": 3.0},
{"id": 2, "name": "15 and up", "subtotal_min": 15, "action": "set", "value": 1.0}],
"ctx": {"sales_point": "online_delivery", "subtotal": 15, "items": 2, "area_id": 1},
"expect": {"fee": 1.0, "refused": null, "area_id": 1}},
{"name": "item-count tier: a big order adds 1",
"rules": [{"id": 1, "name": "Base", "action": "set", "value": 2.0},
{"id": 2, "name": "Big order", "items_min": 10, "action": "add", "value": 1.0}],
"ctx": {"sales_point": "online_delivery", "subtotal": 40, "items": 12, "area_id": 1},
"expect": {"fee": 3.0, "refused": null, "area_id": 1}},
{"name": "item-count tier: a small order pays the base only",
"rules": [{"id": 1, "name": "Base", "action": "set", "value": 2.0},
{"id": 2, "name": "Big order", "items_min": 10, "action": "add", "value": 1.0}],
"ctx": {"sales_point": "online_delivery", "subtotal": 40, "items": 9, "area_id": 1},
"expect": {"fee": 2.0, "refused": null, "area_id": 1}},
{"name": "percent of the products",
"rules": [{"id": 1, "name": "5 %", "action": "percent", "value": 5}],
"ctx": {"sales_point": "online_delivery", "subtotal": 33, "items": 3, "area_id": 1},
"expect": {"fee": 1.65, "refused": null, "area_id": 1}},
{"name": "minimum order refused",
"rules": [{"id": 1, "name": "Minimum", "action": "minimum", "value": 10},
{"id": 2, "name": "Base", "action": "set", "value": 2.0}],
"ctx": {"sales_point": "online_delivery", "subtotal": 8.5, "items": 1, "area_id": 1},
"expect": {"fee": 0.0, "refused": "minimum_not_met", "minimum": 10.0, "area_id": 1}},
{"name": "minimum met: the fee rules go on",
"rules": [{"id": 1, "name": "Minimum", "action": "minimum", "value": 10},
{"id": 2, "name": "Base", "action": "set", "value": 2.0}],
"ctx": {"sales_point": "online_delivery", "subtotal": 10, "items": 1, "area_id": 1},
"expect": {"fee": 2.0, "refused": null, "area_id": 1}},
{"name": "a higher minimum for the far area",
"rules": [{"id": 1, "name": "Far minimum", "area_ids": [2], "action": "minimum", "value": 15},
{"id": 2, "name": "Minimum", "action": "minimum", "value": 10}],
"ctx": {"sales_point": "online_delivery", "subtotal": 12, "items": 2, "area_id": 2},
"expect": {"fee": 0.0, "refused": "minimum_not_met", "minimum": 15.0, "area_id": 2}},
{"name": "stacking: base + late-night surcharge",
"rules": [{"id": 1, "name": "Base", "action": "set", "value": 2.0},
{"id": 2, "name": "Late", "time_from": "22:00", "time_to": "02:00", "action": "add", "value": 0.5}],
"ctx": {"sales_point": "online_delivery", "subtotal": 20, "items": 2, "area_id": 1, "weekday": 4, "hhmm": "23:30"},
"expect": {"fee": 2.5, "refused": null, "area_id": 1}},
{"name": "time window crossing midnight, after midnight",
"rules": [{"id": 2, "name": "Late", "time_from": "22:00", "time_to": "02:00", "action": "add", "value": 0.5}],
"ctx": {"sales_point": "online_delivery", "subtotal": 20, "items": 2, "area_id": 1, "weekday": 5, "hhmm": "01:15"},
"expect": {"fee": 0.5, "refused": null, "area_id": 1}},
{"name": "time window, outside",
"rules": [{"id": 2, "name": "Late", "time_from": "22:00", "time_to": "02:00", "action": "add", "value": 0.5}],
"ctx": {"sales_point": "online_delivery", "subtotal": 20, "items": 2, "area_id": 1, "weekday": 5, "hhmm": "12:00"},
"expect": {"fee": 0.0, "refused": null, "area_id": 1}},
{"name": "weekend only",
"rules": [{"id": 1, "name": "Weekend", "days": [5, 6], "action": "set", "value": 1.0}],
"ctx": {"sales_point": "online_delivery", "subtotal": 20, "items": 2, "area_id": 1, "weekday": 2, "hhmm": "12:00"},
"expect": {"fee": 0.0, "refused": null, "area_id": 1}},
{"name": "an inactive rule is skipped; the fee is never negative",
"rules": [{"id": 1, "name": "Off", "is_active": false, "action": "set", "value": 9},
{"id": 2, "name": "Discount", "action": "add", "value": -2}],
"ctx": {"sales_point": "online_delivery", "subtotal": 20, "items": 2, "area_id": 1},
"expect": {"fee": 0.0, "refused": null, "area_id": 1}},
{"name": "a takeaway packaging fee (areas only matter for delivery)",
"rules": [{"id": 1, "name": "Packaging", "sales_points": ["online_takeaway"], "action": "set", "value": 0.3}],
"ctx": {"sales_point": "online_takeaway", "subtotal": 9, "items": 3, "postcode": "nowhere"},
"expect": {"fee": 0.3, "refused": null, "area_id": null}}
]
}
+135
View File
@@ -0,0 +1,135 @@
"""Delivery areas and fee rules (plan phase 3S, step S.3).
Done when: the four rule kinds (fixed, area, free above €X, item-count tier) and the minimum
give the right answer on both sides from the same cases, and the cloud refuses an order below
the minimum (that half: cloud-service tests/test_checkout.py)."""
import json
from pathlib import Path
import pytest
from tests.test_live import err, owner_h # noqa: F401 (fixtures)
HERE = Path(__file__).resolve().parent
CASES = json.loads((HERE / "fixtures" / "fee_cases.json").read_text(encoding="utf-8"))
SITE_ENGINE = HERE.parent / "services" / "fees.py"
CLOUD = HERE.parents[2] / "cloud-service" / "cloud_backend"
@pytest.mark.parametrize("case", CASES["cases"], ids=[c["name"] for c in CASES["cases"]])
def test_shared_fee_cases(case):
from services.fees import compute
got = compute(case["rules"], CASES["areas"], **case["ctx"])
for key, value in case["expect"].items():
assert got[key] == value, (key, got)
def test_the_cloud_runs_the_same_engine_and_cases():
"""The two copies must not drift (the cloud sits next to this repo in the parent checkout)."""
if not CLOUD.exists():
pytest.skip("cloud-service isn't checked out next to client-services")
assert (CLOUD / "services" / "fees.py").read_text(encoding="utf-8") == SITE_ENGINE.read_text(encoding="utf-8")
assert json.loads((CLOUD / "tests" / "fixtures" / "fee_cases.json").read_text(encoding="utf-8")) == CASES
def _area(client, h, name, codes=(), **extra):
r = client.post("/api/connect/fees/areas", headers=h, json={"name": name, "postcodes": list(codes), **extra})
assert r.status_code == 201, r.text
return r.json()
def _rule(client, h, **body):
r = client.post("/api/connect/fees/rules", headers=h, json={"name": body.pop("name", "Rule"), **body})
assert r.status_code == 201, r.text
return r.json()
def _preview(client, h, **body):
r = client.post("/api/connect/fees/preview", headers=h, json={"sales_point": "online_delivery", **body})
assert r.status_code == 200, r.text
return r.json()
def test_set_up_and_test_an_order(client, owner_h):
"""The manager's flow: areas, rules of every kind, "test an order"."""
h = owner_h
centre = _area(client, h, "Village centre", ["241 00"])
far = _area(client, h, "Kalamata", ["24131", " 24131 ", "24100"])
assert far["postcodes"] == ["24131", "24100"] # tidied, no duplicates
_rule(client, h, name="Minimum", action="minimum", value=10)
_rule(client, h, name="Free over 25", subtotal_min=25, action="free", stop=True)
_rule(client, h, name="Base", action="set", value=2)
_rule(client, h, name="Far", area_ids=[far["id"]], action="add", value=1.5)
_rule(client, h, name="Big order", items_min=10, action="add", value=1)
p = _preview(client, h, area_id=centre["id"], subtotal=12, items=2)
assert (p["fee"], p["total"], p["area_name"], [a["name"] for a in p["applied"]]) == (2.0, 14.0, "Village centre", ["Minimum", "Base"])
assert _preview(client, h, postcode="241 31", subtotal=12, items=2)["fee"] == 3.5 # far, by postcode
assert _preview(client, h, area_id=centre["id"], subtotal=12, items=11)["fee"] == 3.0 # big order
assert _preview(client, h, area_id=far["id"], subtotal=30, items=11)["fee"] == 0.0 # free over 25 stops
low = _preview(client, h, area_id=centre["id"], subtotal=8, items=1)
assert (low["refused"], low["minimum"], low["total"]) == ("minimum_not_met", 10.0, None)
assert _preview(client, h, postcode="10431", subtotal=12, items=2)["refused"] == "area_not_served"
assert _preview(client, h, sales_point="online_takeaway", subtotal=12, items=2)["fee"] == 0.0 # delivery rules only
listed = client.get("/api/connect/fees", headers=h).json()
assert [r["name"] for r in listed["rules"]] == ["Minimum", "Free over 25", "Base", "Far", "Big order"]
def test_order_edit_and_delete(client, owner_h):
h = owner_h
area = _area(client, h, "A")
a = _rule(client, h, name="First", action="set", value=1)
b = _rule(client, h, name="Second", area_ids=[area["id"]], action="set", value=2)
assert client.put("/api/connect/fees/rules/order", headers=h, json=[a["id"]]).json()["error"]["code"] == "fees.order_invalid"
r = client.put("/api/connect/fees/rules/order", headers=h, json=[b["id"], a["id"]])
assert [x["name"] for x in r.json()["rules"]] == ["Second", "First"]
assert err(client.delete(f"/api/connect/fees/areas/{area['id']}", headers=h)) == "fees.area_in_use"
r = client.put(f"/api/connect/fees/rules/{b['id']}", headers=h, json={"name": "Second", "action": "set", "value": 2.5})
assert r.status_code == 200 and r.json()["area_ids"] == [] and r.json()["value"] == 2.5
assert client.delete(f"/api/connect/fees/areas/{area['id']}", headers=h).status_code == 204
assert client.delete(f"/api/connect/fees/rules/{a['id']}", headers=h).status_code == 204
assert err(client.delete(f"/api/connect/fees/rules/{a['id']}", headers=h)) == "fees.rule_not_found"
@pytest.mark.parametrize("body", [
{"name": " "},
{"name": "x", "subtotal_min": 20, "subtotal_max": 10},
{"name": "x", "items_min": 5, "items_max": 2},
{"name": "x", "time_from": "22:00"},
{"name": "x", "time_from": "25:00", "time_to": "02:00"},
{"name": "x", "days": [7]},
{"name": "x", "action": "set", "value": -1},
{"name": "x", "action": "percent", "value": 150},
{"name": "x", "action": "teleport"},
{"name": "x", "sales_points": ["moon"]},
])
def test_bad_rules_are_refused(client, owner_h, body):
assert client.post("/api/connect/fees/rules", headers=owner_h, json=body).status_code == 422
def test_unknown_area_in_a_rule(client, owner_h):
assert err(client.post("/api/connect/fees/rules", headers=owner_h, json={"name": "x", "area_ids": [999]})) == "fees.area_not_found"
def test_only_the_key_holders(client, make_user, login):
barista = make_user(role="barista")
r = client.get("/api/connect/fees", headers=login(barista))
assert r.status_code == 403 and r.json()["error"]["code"] == "access.denied"
def test_the_cloud_gets_the_rules_with_the_menu(db, client, owner_h):
from services.cloud_sync import menu_snapshot
_area(client, owner_h, "Centre", ["24100"])
_rule(client, owner_h, name="Base", action="set", value=2)
snap, _ = menu_snapshot(db)
assert [a["name"] for a in snap["fees"]["areas"]] == ["Centre"]
assert snap["fees"]["rules"][0]["action"] == "set" and snap["timezone"]
def test_changes_push_the_menu_soon():
from services.cloud_sync import menu_changed
assert menu_changed("POST", "/api/connect/fees/rules", 201)
assert menu_changed("PUT", "/api/products/5", 200)
assert menu_changed("PATCH", "/api/pricing/modifiers/3/toggle", 200)
assert not menu_changed("GET", "/api/products/", 200)
assert not menu_changed("POST", "/api/pricing/modifiers", 422)
assert not menu_changed("POST", "/api/orders/1/items", 200)