Files
xenia-pos-cloud/cloud_backend/tests/test_fees.py
T
bonaminandClaude Opus 5.5 d5b8492512 feat: delivery areas drawn on a map: the customer pins the address (plan 6R.G)
- services/fees.py: the site's engine (shapes matched by the pin), shared cases
- checkout: price_cart(pin=), delivery_areas with kind (+ geometry for shapes),
  venue_point in the public menu (postcodes and rules stay on the cloud)
- orders: quote / create take lat / lng; online_orders.lat / lng (Alembic 0007),
  sent to the site with the pending orders
- order app: PinMap (Leaflet + OpenStreetMap tiles), 'Pin it on the map' first
  when the venue drew areas, the browser's location offered; lat / lng sent
- tests: cloud test_fees (pinned quote and order), order-app logic

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

124 lines
7.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""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, ORDERING, _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, "ordering": ORDERING, "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"], stored["delivery_area_id"]) == (2.0, 7.6, "Centre", 1)
# 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", "kind": "postcodes"}, {"id": 2, "name": "Far", "kind": "postcodes"}]
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")
SHAPED = {"areas": [{"id": 1, "name": "Centre", "postcodes": ["24100"], "is_active": True},
{"id": 7, "name": "Drawn", "kind": "polygon", "postcodes": [], "is_active": True,
"geometry": [[37.0, 22.0], [37.0, 22.1], [37.1, 22.1], [37.1, 22.0]]},
{"id": 8, "name": "2 km", "kind": "circle", "postcodes": [], "is_active": True,
"geometry": {"center": [37.5, 22.5], "radius_m": 2000}}],
"rules": [{"id": 1, "name": "Drawn fee", "area_ids": [7], "action": "set", "value": 1.5, "sales_points": ["online_delivery"]},
{"id": 2, "name": "Circle fee", "area_ids": [8], "action": "set", "value": 3, "sales_points": ["online_delivery"]}],
"venue_point": {"lat": 37.05, "lng": 22.05}}
def test_a_pin_on_the_map_finds_a_drawn_area_and_reaches_the_site(client, admin_h):
"""6R.G: the customer pins the address; the cloud prices it by the area holding the pin and
keeps the pin for the site (which checks the fee with the same engine)."""
site = _new_site(client, admin_h)
numeric = _heartbeat(client, site)["site_numeric_id"]
_menu(client, site, numeric)
menu = client.get(f"/api/menu/{site['site_id']}").json()
snap = {"categories": menu["categories"], "fees": SHAPED, "ordering": ORDERING, "timezone": "Europe/Athens"}
assert client.post("/api/menu/sync", headers=_h(site), json={"site_id": numeric, "snapshot_json": json.dumps(snap)}).status_code == 200
menu = client.get(f"/api/menu/{site['site_id']}").json()
assert menu["venue_point"] == {"lat": 37.05, "lng": 22.05}
assert menu["delivery_areas"][1] == {"id": 7, "name": "Drawn", "kind": "polygon", "geometry": SHAPED["areas"][1]["geometry"]}
assert "24100" not in json.dumps(menu["delivery_areas"]) # the postcodes stay on the cloud
items = [{"product_id": COLA, "quantity": 2}]
q = _quote(client, site, items=items, lat=37.05, lng=22.05).json()
assert (q["delivery_fee"], q["area_name"]) == (1.5, "Drawn")
q = _quote(client, site, items=items, lat=37.51, lng=22.5).json()
assert (q["delivery_fee"], q["area_name"]) == (3.0, "2 km")
assert _code(_quote(client, site, items=items, lat=36.0, lng=22.5)) == "order.area_not_served"
assert _code(_quote(client, site, items=items, area_id=7)) == "order.area_not_served" # a shape needs the pin
assert _quote(client, site, items=items, lat=37.05).json()["detail"]["code"] == "order.area_not_served" # half a pin is none
ok = _order(client, site, "delivery", customer_address="Main sq. 3", lat=37.05, lng=22.05, total=round(5.6 + 1.5, 2))
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_area"], stored["delivery_area_id"], stored["lat"], stored["lng"]) == ("Drawn", 7, 37.05, 22.05)