From 96f16e948d40bba859054d3455ba96086dc78935 Mon Sep 17 00:00:00 2001 From: bonamin Date: Sun, 15 Nov 2026 12:28:15 +0200 Subject: [PATCH] feat(cloud): delivery fees and minimum orders at checkout (platform-v2 3S, S.3) - services/fees.py: the site's fee engine, byte-identical (the site's tests check it); tests/fixtures/fee_cases.json: the shared cases, run here too. - checkout: the snapshot's fees (areas, rules) at the venue's time zone; refused order.area_not_served / order.minimum_not_met {minimum, subtotal}; quote and order take area_id / postcode and return area_name, fee_rules; the order stores delivery_area. - GET /api/menu/{site}: delivery_areas [{id, name}] for the customer; the rules and postcodes are never sent to the browser. - Alembic 0003 (unreleased) gains online_orders.delivery_area. - Tests: test_fees.py (22 shared cases + checkout fees, refusals, public menu, clock). Co-Authored-By: Claude Opus 5.5 --- .../versions/0003_order_sales_point.py | 5 +- cloud_backend/models/online_order.py | 1 + cloud_backend/routers/menu.py | 3 + cloud_backend/routers/orders.py | 9 +- cloud_backend/schemas/online_order.py | 5 + cloud_backend/services/checkout.py | 52 ++++++- cloud_backend/services/fees.py | 128 ++++++++++++++++++ cloud_backend/tests/fixtures/fee_cases.json | 108 +++++++++++++++ cloud_backend/tests/test_fees.py | 86 ++++++++++++ 9 files changed, 387 insertions(+), 10 deletions(-) create mode 100644 cloud_backend/services/fees.py create mode 100644 cloud_backend/tests/fixtures/fee_cases.json create mode 100644 cloud_backend/tests/test_fees.py diff --git a/cloud_backend/migrations/versions/0003_order_sales_point.py b/cloud_backend/migrations/versions/0003_order_sales_point.py index c96d7e8..798fb49 100644 --- a/cloud_backend/migrations/versions/0003_order_sales_point.py +++ b/cloud_backend/migrations/versions/0003_order_sales_point.py @@ -1,4 +1,4 @@ -"""online orders: sales_point, table_label, tracking_token; public_ref unique per site (plan phase 3S, S.2) +"""online orders: sales_point, table_label, delivery_area, tracking_token; public_ref unique per site (plan phase 3S, S.2/S.3) - sales_point / table_label: the cloud prices orders per sales point; the QR menu's table - public_ref ("ORD-0001") counts per site but was unique across all sites, so a second @@ -59,6 +59,7 @@ def _base(*extra): def upgrade() -> None: with op.batch_alter_table('online_orders', copy_from=_base(), recreate='always') as batch_op: batch_op.add_column(sa.Column('table_label', sa.String(), nullable=True)) + batch_op.add_column(sa.Column('delivery_area', sa.String(), nullable=True)) batch_op.add_column(sa.Column('sales_point', sa.String(), nullable=True)) batch_op.add_column(sa.Column('tracking_token', sa.String(), nullable=True)) batch_op.create_unique_constraint('uq_online_orders_site_ref', ['site_id', 'public_ref']) @@ -71,10 +72,12 @@ def upgrade() -> None: def downgrade() -> None: current = _base(sa.Column('table_label', sa.String(), nullable=True), + sa.Column('delivery_area', sa.String(), nullable=True), sa.Column('sales_point', sa.String(), nullable=True), sa.Column('tracking_token', sa.String(), nullable=True)) with op.batch_alter_table('online_orders', copy_from=current, recreate='always') as batch_op: batch_op.drop_column('tracking_token') batch_op.drop_column('sales_point') + batch_op.drop_column('delivery_area') batch_op.drop_column('table_label') batch_op.create_unique_constraint('uq_online_orders_public_ref', ['public_ref']) diff --git a/cloud_backend/models/online_order.py b/cloud_backend/models/online_order.py index ebb65bf..256b176 100644 --- a/cloud_backend/models/online_order.py +++ b/cloud_backend/models/online_order.py @@ -25,6 +25,7 @@ class OnlineOrder(Base): customer_address = Column(Text, nullable=True) # required for delivery customer_notes = Column(Text, nullable=True) table_label = Column(String, nullable=True) # the QR menu's table, as the customer gave it + delivery_area = Column(String, nullable=True) # the delivery area's name (S.3) sales_point = Column(String, nullable=True) # the site's sales point (phase 3S, S.2) # Order content — JSON array of ordered items diff --git a/cloud_backend/routers/menu.py b/cloud_backend/routers/menu.py index 74dd17e..426a3a1 100644 --- a/cloud_backend/routers/menu.py +++ b/cloud_backend/routers/menu.py @@ -42,6 +42,9 @@ def get_menu(site_slug: str, db: Session = Depends(get_db)): import json data = json.loads(snapshot.snapshot_json) + from services.checkout import delivery_areas + data["delivery_areas"] = delivery_areas(data) # S.3: what the customer picks from + data.pop("fees", None) # the rules and postcodes stay on the cloud data["menu_mode"] = site.menu_mode data["restaurant"] = { "name": site.menu_display_name, diff --git a/cloud_backend/routers/orders.py b/cloud_backend/routers/orders.py index eedd080..39ebf34 100644 --- a/cloud_backend/routers/orders.py +++ b/cloud_backend/routers/orders.py @@ -51,9 +51,9 @@ def _site_and_menu(db, site_slug): return site, json.loads(snap.snapshot_json) -def _priced(menu, order_type, items): +def _priced(menu, order_type, items, area_id=None, postcode=None): try: - return price_cart(menu, order_type, items) + return price_cart(menu, order_type, items, area_id=area_id, postcode=postcode) except CheckoutError as e: raise HTTPException(status_code=e.status, detail=e.detail()) @@ -62,7 +62,7 @@ def _priced(menu, order_type, items): def quote_order(site_slug: str, body: QuoteRequest, db: Session = Depends(get_db)): """The cart priced by the cloud from the venue's menu, for the customer apps (phase 3S).""" _site, menu = _site_and_menu(db, site_slug) - return _priced(menu, body.order_type, [i.model_dump() for i in body.items]).out() + return _priced(menu, body.order_type, [i.model_dump() for i in body.items], body.area_id, body.postcode).out() @router.post("/{site_slug}", response_model=OnlineOrderCreated, status_code=status.HTTP_201_CREATED) @@ -73,7 +73,7 @@ def create_order(site_slug: str, body: OnlineOrderCreate, db: Session = Depends( money is stored (phase 3S, S.2).""" site, menu = _site_and_menu(db, site_slug) items = [i.model_dump() for i in body.items] - priced = _priced(menu, body.order_type, items) + priced = _priced(menu, body.order_type, items, body.area_id, body.postcode) try: check_sent(priced, items, body.total) except CheckoutError as e: @@ -94,6 +94,7 @@ def create_order(site_slug: str, body: OnlineOrderCreate, db: Session = Depends( customer_address=body.customer_address, customer_notes=body.customer_notes, table_label=(body.customer_table or "").strip() or None, + delivery_area=priced.area_name, sales_point=priced.sales_point, items_json=json.dumps([line.out() for line in priced.lines]), subtotal=priced.subtotal, diff --git a/cloud_backend/schemas/online_order.py b/cloud_backend/schemas/online_order.py index 796f2d3..b317e47 100644 --- a/cloud_backend/schemas/online_order.py +++ b/cloud_backend/schemas/online_order.py @@ -17,6 +17,8 @@ class OrderItemIn(BaseModel): class QuoteRequest(BaseModel): order_type: str # dine_in | takeaway | delivery | preorder items: list[OrderItemIn] = Field(max_length=100) + area_id: Optional[int] = None # the delivery area picked (S.3) + postcode: Optional[str] = Field(default=None, max_length=20) class OnlineOrderCreate(BaseModel): @@ -26,6 +28,8 @@ class OnlineOrderCreate(BaseModel): customer_address: Optional[str] = Field(default=None, max_length=500) customer_notes: Optional[str] = Field(default=None, max_length=1000) customer_table: Optional[str] = Field(default=None, max_length=40) + area_id: Optional[int] = None # the delivery area picked (S.3) + postcode: Optional[str] = Field(default=None, max_length=20) items: list[OrderItemIn] = Field(max_length=100) # what the customer was shown: compared, never stored as sent subtotal: Optional[float] = None @@ -56,6 +60,7 @@ class PendingOrderOut(BaseModel): customer_address: Optional[str] = None customer_notes: Optional[str] = None table_label: Optional[str] = None # the QR menu's table (S.2) + delivery_area: Optional[str] = None # the delivery area's name (S.3) sales_point: Optional[str] = None # the site's sales point (S.2) items_json: str subtotal: float diff --git a/cloud_backend/services/checkout.py b/cloud_backend/services/checkout.py index 38c712d..2d7eb33 100644 --- a/cloud_backend/services/checkout.py +++ b/cloud_backend/services/checkout.py @@ -13,10 +13,18 @@ Snapshot product (site services/cloud_sync._push_menu_snapshot): sold_at: [sales point], prices: {sales point: price}, quick_options: [{id, name, price}]} Snapshots from before S.2 have no `prices` / `sold_at`: every customer-app sales point, at digital_price (or base_price) less digital_discount %. + +The fee (S.3): the snapshot's `fees` {areas, rules} through services/fees.py (the same file +as the site's) at the venue's time (`timezone`). A delivery outside the venue's areas -> +order.area_not_served; below a minimum -> order.minimum_not_met {minimum, subtotal}. """ from __future__ import annotations from dataclasses import dataclass, field +from datetime import datetime, timezone +from zoneinfo import ZoneInfo + +from services import fees as fee_engine # the cloud order's type → the site's sales point (core/sales_points.py) POINT_FOR_TYPE = { @@ -60,10 +68,30 @@ class Priced: subtotal: float delivery_fee: float total: float + area_id: int | None = None + area_name: str | None = None + fee_rules: list = field(default_factory=list) # names of the rules that applied def out(self) -> dict: return {"sales_point": self.sales_point, "lines": [x.out() for x in self.lines], - "subtotal": self.subtotal, "delivery_fee": self.delivery_fee, "total": self.total} + "subtotal": self.subtotal, "delivery_fee": self.delivery_fee, "total": self.total, + "area_id": self.area_id, "area_name": self.area_name, "fee_rules": self.fee_rules} + + +def venue_clock(snapshot: dict, now: datetime | None = None) -> tuple[int, str]: + """(weekday Mon=0, "HH:MM") at the venue, from the snapshot's time zone.""" + try: + tz = ZoneInfo(snapshot.get("timezone") or "Europe/Athens") + except Exception: + tz = ZoneInfo("Europe/Athens") + local = (now or datetime.now(timezone.utc)).astimezone(tz) + return local.weekday(), local.strftime("%H:%M") + + +def delivery_areas(snapshot: dict) -> list: + """The active areas a customer picks from: [{id, name}] (no postcodes, no rules).""" + return [{"id": a.get("id"), "name": a.get("name")} for a in (snapshot.get("fees") or {}).get("areas") or [] + if a.get("is_active", True)] def products_of(snapshot: dict) -> dict[int, dict]: @@ -106,8 +134,10 @@ def _option_ids(raw) -> list: return out -def price_cart(snapshot: dict, order_type: str, items: list[dict]) -> Priced: - """Price the cart from the snapshot. items: [{product_id, quantity, options?}].""" +def price_cart(snapshot: dict, order_type: str, items: list[dict], area_id=None, postcode=None, + now: datetime | None = None) -> Priced: + """Price the cart from the snapshot. items: [{product_id, quantity, options?}]; the + customer's area (picked, or by postcode) for the fee.""" point = POINT_FOR_TYPE.get(order_type) if point is None: raise CheckoutError(422, "order.type_invalid", order_type=order_type) @@ -136,8 +166,20 @@ def price_cart(snapshot: dict, order_type: str, items: list[dict]) -> Priced: unit = round(unit + sum(o["price"] for o in options), 2) lines.append(Line(product_id=pid, name=_display_name(product), quantity=qty, unit_price=unit, options=options)) subtotal = round(sum(x.unit_price * x.quantity for x in lines), 2) - fee = 0.0 # S.3: the venue's fee rules - return Priced(sales_point=point, lines=lines, subtotal=subtotal, delivery_fee=fee, total=round(subtotal + fee, 2)) + rules = snapshot.get("fees") or {} + weekday, hhmm = venue_clock(snapshot, now) + result = fee_engine.compute(rules.get("rules") or [], rules.get("areas") or [], sales_point=point, + subtotal=subtotal, items=sum(x.quantity for x in lines), + area_id=area_id, postcode=postcode, weekday=weekday, hhmm=hhmm) + if result["refused"] == "area_not_served": + raise CheckoutError(409, "order.area_not_served", postcode=postcode, area_id=area_id) + if result["refused"] == "minimum_not_met": + raise CheckoutError(409, "order.minimum_not_met", minimum=result["minimum"], subtotal=subtotal) + fee = result["fee"] + area = next((a for a in rules.get("areas") or [] if a.get("id") == result["area_id"]), None) + return Priced(sales_point=point, lines=lines, subtotal=subtotal, delivery_fee=fee, total=round(subtotal + fee, 2), + area_id=result["area_id"], area_name=area.get("name") if area else None, + fee_rules=[a["name"] for a in result["applied"] if a["action"] != "minimum"]) def check_sent(priced: Priced, items: list[dict], total: float | None) -> None: diff --git a/cloud_backend/services/fees.py b/cloud_backend/services/fees.py new file mode 100644 index 0000000..c58fbe6 --- /dev/null +++ b/cloud_backend/services/fees.py @@ -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 diff --git a/cloud_backend/tests/fixtures/fee_cases.json b/cloud_backend/tests/fixtures/fee_cases.json new file mode 100644 index 0000000..50ecd1c --- /dev/null +++ b/cloud_backend/tests/fixtures/fee_cases.json @@ -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}} + ] +} diff --git a/cloud_backend/tests/test_fees.py b/cloud_backend/tests/test_fees.py new file mode 100644 index 0000000..a0b4996 --- /dev/null +++ b/cloud_backend/tests/test_fees.py @@ -0,0 +1,86 @@ +"""Delivery fees at checkout (plan phase 3S, step S.3). + +The engine (services/fees.py) is the site's file; both repos run the same cases +(tests/fixtures/fee_cases.json, identical in both; the site's tests check the copies match). +Done when (cloud half): the cloud charges the venue's fee and refuses an order below the minimum.""" +import json +from datetime import datetime, timezone +from pathlib import Path + +import pytest + +from test_checkout import COLA, _code, _h, _menu, _order +from test_licensing_v2 import _heartbeat, _new_site + +CASES = json.loads((Path(__file__).resolve().parent / "fixtures" / "fee_cases.json").read_text(encoding="utf-8")) + + +@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) + + +FEES = {"areas": [{"id": 1, "name": "Centre", "postcodes": ["24100"], "is_active": True}, + {"id": 2, "name": "Far", "postcodes": ["24131"], "is_active": True}], + "rules": [{"id": 1, "name": "Minimum", "action": "minimum", "value": 5, "sales_points": ["online_delivery"]}, + {"id": 2, "name": "Base", "action": "set", "value": 2, "sales_points": ["online_delivery"]}, + {"id": 3, "name": "Far", "area_ids": [2], "action": "add", "value": 1.5, "sales_points": ["online_delivery"]}]} + + +def _venue_with_fees(client, admin_h): + site = _new_site(client, admin_h) + numeric = _heartbeat(client, site)["site_numeric_id"] + _menu(client, site, numeric) + # the same menu plus the venue's fees, as the site pushes them since S.3 + menu = client.get(f"/api/menu/{site['site_id']}").json() + snap = {"categories": menu["categories"], "fees": FEES, "timezone": "Europe/Athens"} + r = client.post("/api/menu/sync", headers=_h(site), json={"site_id": numeric, "snapshot_json": json.dumps(snap)}) + assert r.status_code == 200 + return site, numeric + + +def _quote(client, site, **body): + return client.post(f"/api/orders/{site['site_id']}/quote", json={"order_type": "delivery", **body}) + + +def test_the_cloud_charges_the_venues_fee(client, admin_h): + site, numeric = _venue_with_fees(client, admin_h) + q = _quote(client, site, items=[{"product_id": COLA, "quantity": 2}], area_id=1).json() # 2 × 2.8 delivery price + assert (q["subtotal"], q["delivery_fee"], q["total"], q["area_name"], q["fee_rules"]) == (5.6, 2.0, 7.6, "Centre", ["Base"]) + q = _quote(client, site, items=[{"product_id": COLA, "quantity": 2}], postcode="241 31").json() + assert (q["delivery_fee"], q["area_name"]) == (3.5, "Far") + # the order: the fee is the cloud's, whatever the page sends; the area is stored + assert _code(_order(client, site, "delivery", customer_address="Main sq. 3", area_id=1, delivery_fee=0, total=5.6)) == "order.price_changed" + ok = _order(client, site, "delivery", customer_address="Main sq. 3", area_id=1, total=7.6) + assert ok.status_code == 201, ok.text + stored = next(o for o in client.get(f"/api/orders/pending/{numeric}", headers=_h(site)).json() if o["public_ref"] == ok.json()["public_ref"]) + assert (stored["delivery_fee"], stored["total"], stored["delivery_area"]) == (2.0, 7.6, "Centre") + # takeaway: the delivery rules don't apply + assert client.post(f"/api/orders/{site['site_id']}/quote", json={"order_type": "takeaway", "items": [{"product_id": COLA, "quantity": 1}]}).json()["delivery_fee"] == 0 + + +def test_minimum_and_area_are_refused(client, admin_h): + site, _ = _venue_with_fees(client, admin_h) + r = _quote(client, site, items=[{"product_id": COLA, "quantity": 1}], area_id=1) + assert r.status_code == 409 and _code(r) == "order.minimum_not_met" + assert r.json()["detail"]["params"] == {"minimum": 5.0, "subtotal": 2.8} + assert _code(_order(client, site, "delivery", customer_address="x", area_id=1, items=[{"product_id": COLA, "quantity": 1}])) == "order.minimum_not_met" + assert _code(_quote(client, site, items=[{"product_id": COLA, "quantity": 2}], postcode="10431")) == "order.area_not_served" + assert _code(_quote(client, site, items=[{"product_id": COLA, "quantity": 2}])) == "order.area_not_served" + + +def test_the_public_menu_lists_areas_but_not_the_rules(client, admin_h): + site, _ = _venue_with_fees(client, admin_h) + menu = client.get(f"/api/menu/{site['site_id']}").json() + assert menu["delivery_areas"] == [{"id": 1, "name": "Centre"}, {"id": 2, "name": "Far"}] + assert "fees" not in menu + + +def test_the_venue_clock(): + from services.checkout import venue_clock + at = datetime(2026, 11, 15, 21, 30, tzinfo=timezone.utc) # Sunday 23:30 in Athens (UTC+2) + assert venue_clock({"timezone": "Europe/Athens"}, at) == (6, "23:30") + assert venue_clock({"timezone": "Nowhere/Bad"}, at) == (6, "23:30")