An area is a list of postcodes, a shape drawn on a map or a circle around a point. The fee engine (both copies, byte-identical) matches a shape only by the customer's pin, then postcodes; point-in-polygon (edges inside) and haversine circles; shared cases in fee_cases.json. - Alembic 0053: delivery_areas.kind / geometry, orders.online_lat / lng - /api/connect/fees: areas with kind + geometry (validated: 3-200 corners, 50 m - 50 km), the venue's place (PUT /venue-point, setting venue.location, sent to the cloud as fees.venue_point), preview by lat / lng - manager: DeliveryMap (Leaflet + OpenStreetMap tiles): draw / move / remove corners, circles, the venue on the map, an overview, test an order by a point - pulled online orders keep the pin; the site re-checks the fee with it; the counter links the pin to a map - tests: backend (shapes, venue point, pinned orders), manager logic, e2e manager.mjs and order_app.mjs 6R.G blocks Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
207 lines
12 KiB
Python
207 lines
12 KiB
Python
"""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)
|
|
|
|
|
|
def test_online_ordering_settings(client, db, owner_h):
|
|
"""S.4: the services, hours and timing the online ordering app follows (the cloud
|
|
enforces them); off until the venue turns a service on."""
|
|
from services.cloud_sync import menu_snapshot
|
|
assert client.get("/api/connect/fees/ordering", headers=owner_h).json()["services"] == []
|
|
body = {"services": ["delivery", "takeaway"], "hours": {"5": [["20:00", "02:00"]], "6": [["12:00", "16:00"], ["18:00", "23:00"]]},
|
|
"prep_minutes": 30, "slot_minutes": 15, "days_ahead": 1, "asap": False}
|
|
r = client.put("/api/connect/fees/ordering", headers=owner_h, json=body)
|
|
assert r.status_code == 200, r.text
|
|
assert r.json()["services"] == ["takeaway", "delivery"] # fixed order
|
|
assert client.get("/api/connect/fees", headers=owner_h).json()["ordering"]["days_ahead"] == 1
|
|
snap, _ = menu_snapshot(db)
|
|
assert snap["ordering"]["hours"]["6"] == [["12:00", "16:00"], ["18:00", "23:00"]] and snap["ordering"]["asap"] is False
|
|
for bad in ({"services": ["teleport"]}, {"hours": {"7": [["10:00", "11:00"]]}}, {"hours": {"1": [["10:00", "10:00"]]}},
|
|
{"hours": {"1": [["25:00", "11:00"]]}}, {"slot_minutes": 1}, {"days_ahead": 30}, {"prep_minutes": -5}):
|
|
assert client.put("/api/connect/fees/ordering", headers=owner_h, json=bad).status_code == 422, bad
|
|
|
|
|
|
# ── 6R.G: areas drawn on a map ────────────────────────────────────────────────
|
|
|
|
SQUARE = [[37.0, 22.0], [37.0, 22.1], [37.1, 22.1], [37.1, 22.0]]
|
|
|
|
|
|
def test_areas_drawn_on_the_map_and_tested_by_a_point(client, owner_h):
|
|
h = owner_h
|
|
centre = _area(client, h, "Village centre", ["24100"])
|
|
drawn = _area(client, h, "Drawn", kind="polygon", geometry=SQUARE, postcodes=["ignored"])
|
|
ring = _area(client, h, "2 km", kind="circle", geometry={"center": [37.5, 22.5], "radius_m": 2000.4})
|
|
assert (drawn["kind"], drawn["geometry"], drawn["postcodes"]) == ("polygon", SQUARE, [])
|
|
assert ring["geometry"] == {"center": [37.5, 22.5], "radius_m": 2000}
|
|
assert centre["kind"] == "postcodes" and centre["geometry"] is None
|
|
_rule(client, h, name="Drawn", area_ids=[drawn["id"]], action="set", value=1.5)
|
|
_rule(client, h, name="Ring", area_ids=[ring["id"]], action="set", value=3)
|
|
p = _preview(client, h, lat=37.05, lng=22.05, subtotal=12, items=2)
|
|
assert (p["area_name"], p["fee"]) == ("Drawn", 1.5)
|
|
assert _preview(client, h, lat=37.51, lng=22.5, subtotal=12, items=2)["area_name"] == "2 km"
|
|
assert _preview(client, h, lat=36.0, lng=22.0, subtotal=12, items=2)["refused"] == "area_not_served"
|
|
assert _preview(client, h, area_id=drawn["id"], subtotal=12, items=2)["refused"] == "area_not_served" # a shape needs a point
|
|
assert _preview(client, h, postcode="24100", subtotal=12, items=2)["area_name"] == "Village centre"
|
|
# an area can change kind: back to postcodes drops the shape
|
|
r = client.put(f"/api/connect/fees/areas/{drawn['id']}", headers=h, json={"name": "Drawn", "postcodes": ["24131"]})
|
|
assert r.status_code == 200 and (r.json()["kind"], r.json()["geometry"], r.json()["postcodes"]) == ("postcodes", None, ["24131"])
|
|
|
|
|
|
@pytest.mark.parametrize("body", [
|
|
{"kind": "polygon", "geometry": [[37, 22], [37, 22.1]]}, # two corners
|
|
{"kind": "polygon", "geometry": [[37, 22], [37, 22.1], [91, 22]]}, # latitude past 90
|
|
{"kind": "polygon", "geometry": "a square"},
|
|
{"kind": "circle", "geometry": {"center": [37, 22], "radius_m": 10}}, # under 50 m
|
|
{"kind": "circle", "geometry": {"center": [37, 22], "radius_m": 60000}}, # over 50 km
|
|
{"kind": "circle", "geometry": {"center": [37], "radius_m": 500}},
|
|
{"kind": "triangle", "geometry": None},
|
|
])
|
|
def test_bad_shapes_are_refused(client, owner_h, body):
|
|
assert client.post("/api/connect/fees/areas", headers=owner_h, json={"name": "x", **body}).status_code == 422
|
|
|
|
|
|
def test_the_venues_place_on_the_map(db, client, owner_h):
|
|
from services.cloud_sync import menu_snapshot
|
|
assert client.get("/api/connect/fees", headers=owner_h).json()["venue_point"] is None
|
|
r = client.put("/api/connect/fees/venue-point", headers=owner_h, json={"lat": 37.0365123456, "lng": 22.1142})
|
|
assert r.json()["venue_point"] == {"lat": 37.0365123, "lng": 22.1142}
|
|
assert client.get("/api/connect/fees", headers=owner_h).json()["venue_point"] == {"lat": 37.0365123, "lng": 22.1142}
|
|
_area(client, owner_h, "Drawn", kind="polygon", geometry=SQUARE)
|
|
snap, _ = menu_snapshot(db)
|
|
assert snap["fees"]["venue_point"] == {"lat": 37.0365123, "lng": 22.1142}
|
|
assert snap["fees"]["areas"][0]["geometry"] == SQUARE and snap["fees"]["areas"][0]["kind"] == "polygon"
|
|
assert client.put("/api/connect/fees/venue-point", headers=owner_h, json={}).json()["venue_point"] is None
|
|
assert client.put("/api/connect/fees/venue-point", headers=owner_h, json={"lat": 95, "lng": 1}).status_code == 422
|