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>
This commit is contained in:
@@ -89,9 +89,24 @@ def venue_clock(snapshot: dict, now: datetime | None = None) -> tuple[int, str]:
|
||||
|
||||
|
||||
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)]
|
||||
"""The active areas: [{id, name, kind}] (no postcodes, no rules). A postcode area is picked
|
||||
from a list; a shape (6R.G: polygon / circle) also gives its geometry, so the customer's map
|
||||
can draw where the venue delivers; the cloud matches it by the customer's pin."""
|
||||
out = []
|
||||
for a in (snapshot.get("fees") or {}).get("areas") or []:
|
||||
if not a.get("is_active", True):
|
||||
continue
|
||||
kind = a.get("kind") or "postcodes"
|
||||
item = {"id": a.get("id"), "name": a.get("name"), "kind": kind}
|
||||
if kind in fee_engine.SHAPES:
|
||||
item["geometry"] = a.get("geometry")
|
||||
out.append(item)
|
||||
return out
|
||||
|
||||
|
||||
def venue_point(snapshot: dict):
|
||||
"""The venue's place on the map (6R.G): {lat, lng} or None; the customer's map starts there."""
|
||||
return (snapshot.get("fees") or {}).get("venue_point")
|
||||
|
||||
|
||||
def products_of(snapshot: dict) -> dict[int, dict]:
|
||||
@@ -135,9 +150,9 @@ def _option_ids(raw) -> list:
|
||||
|
||||
|
||||
def price_cart(snapshot: dict, order_type: str, items: list[dict], area_id=None, postcode=None,
|
||||
now: datetime | None = None) -> Priced:
|
||||
now: datetime | None = None, pin=None) -> Priced:
|
||||
"""Price the cart from the snapshot. items: [{product_id, quantity, options?}]; the
|
||||
customer's area (picked, or by postcode) for the fee."""
|
||||
customer's area (picked, by their `pin` [lat, lng] on the map (6R.G), 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)
|
||||
@@ -170,7 +185,8 @@ def price_cart(snapshot: dict, order_type: str, items: list[dict], area_id=None,
|
||||
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)
|
||||
area_id=area_id, postcode=postcode, weekday=weekday, hhmm=hhmm,
|
||||
point=pin)
|
||||
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":
|
||||
|
||||
@@ -7,11 +7,19 @@ an order", the site's check of pulled orders) and cloud-service/cloud_backend/se
|
||||
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"}
|
||||
weekday=None, hhmm=None, point=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.
|
||||
Areas: {id, name, kind, postcodes: [str], geometry, is_active}. `kind` (6R.G; missing =
|
||||
"postcodes"): "postcodes" (a list), "polygon" (geometry [[lat, lng], …], at least 3 corners) or
|
||||
"circle" (geometry {"center": [lat, lng], "radius_m": metres}). The customer's area, in this order:
|
||||
1. the one picked (by id); a shape (polygon / circle) only when the customer's `point`
|
||||
[lat, lng] lies in it (a pin is the only proof of where a shape delivery goes);
|
||||
2. by `point`: the first active shape that holds it (on its edge counts as inside);
|
||||
3. by postcode: the first active postcode area that lists 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. A point is inside a polygon by the even-odd rule on
|
||||
latitude / longitude (fine for a village or a town); inside a circle when the great-circle
|
||||
(haversine) distance to its centre is at most its radius.
|
||||
|
||||
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}.
|
||||
@@ -29,25 +37,98 @@ never negative and is rounded to cents.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
|
||||
EPS = 0.0005
|
||||
ACTIONS = ("set", "add", "percent", "free", "minimum")
|
||||
SHAPES = ("polygon", "circle")
|
||||
EARTH_M = 6371008.8 # mean Earth radius, metres
|
||||
EDGE = 1e-9 # degrees: a point this close to an edge is on it
|
||||
|
||||
|
||||
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."""
|
||||
def _point(value):
|
||||
"""[lat, lng] as two floats, or None when it isn't a usable point."""
|
||||
try:
|
||||
lat, lng = float(value[0]), float(value[1])
|
||||
except (TypeError, ValueError, IndexError, KeyError):
|
||||
return None
|
||||
if not (math.isfinite(lat) and math.isfinite(lng)) or abs(lat) > 90 or abs(lng) > 180:
|
||||
return None
|
||||
return lat, lng
|
||||
|
||||
|
||||
def _on_segment(p, a, b) -> bool:
|
||||
(y, x), (y1, x1), (y2, x2) = p, a, b
|
||||
cross = (x - x1) * (y2 - y1) - (y - y1) * (x2 - x1)
|
||||
if abs(cross) > EDGE * max(1.0, abs(x2 - x1) + abs(y2 - y1)):
|
||||
return False
|
||||
return min(x1, x2) - EDGE <= x <= max(x1, x2) + EDGE and min(y1, y2) - EDGE <= y <= max(y1, y2) + EDGE
|
||||
|
||||
|
||||
def in_polygon(point, corners) -> bool:
|
||||
"""Even-odd rule on (lat, lng); a point on an edge or a corner is inside."""
|
||||
pts = [c for c in (_point(c) for c in corners or []) if c is not None]
|
||||
p = _point(point)
|
||||
if p is None or len(pts) < 3:
|
||||
return False
|
||||
lat, lng = p
|
||||
inside = False
|
||||
for i in range(len(pts)):
|
||||
a, b = pts[i], pts[i - 1]
|
||||
if _on_segment(p, a, b):
|
||||
return True
|
||||
if (a[0] > lat) != (b[0] > lat):
|
||||
cross_lng = a[1] + (lat - a[0]) * (b[1] - a[1]) / (b[0] - a[0])
|
||||
if lng < cross_lng:
|
||||
inside = not inside
|
||||
return inside
|
||||
|
||||
|
||||
def distance_m(a, b) -> float:
|
||||
"""Great-circle (haversine) distance in metres between two [lat, lng] points."""
|
||||
(lat1, lng1), (lat2, lng2) = _point(a), _point(b)
|
||||
p1, p2 = math.radians(lat1), math.radians(lat2)
|
||||
dp, dl = p2 - p1, math.radians(lng2 - lng1)
|
||||
h = math.sin(dp / 2) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(dl / 2) ** 2
|
||||
return 2 * EARTH_M * math.asin(min(1.0, math.sqrt(h)))
|
||||
|
||||
|
||||
def holds(area, point) -> bool:
|
||||
"""Does a shape area hold the point? (A postcode area never does.)"""
|
||||
if _point(point) is None:
|
||||
return False
|
||||
kind, geo = area.get("kind") or "postcodes", area.get("geometry")
|
||||
if kind == "polygon":
|
||||
return in_polygon(point, geo)
|
||||
if kind == "circle" and isinstance(geo, dict) and _point(geo.get("center")) is not None:
|
||||
try:
|
||||
radius = float(geo.get("radius_m"))
|
||||
except (TypeError, ValueError):
|
||||
return False
|
||||
return radius > 0 and distance_m(point, geo["center"]) <= radius + 0.01
|
||||
return False
|
||||
|
||||
|
||||
def resolve_area(areas: list, area_id=None, postcode=None, point=None):
|
||||
"""The customer's active area: picked by id (a shape only with a point inside it), else the
|
||||
first shape holding the point, else by postcode; None when nothing 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:
|
||||
if a.get("id") == area_id and ((a.get("kind") or "postcodes") not in SHAPES or holds(a, point)):
|
||||
return a
|
||||
if _point(point) is not None:
|
||||
for a in active:
|
||||
if (a.get("kind") or "postcodes") in SHAPES and holds(a, point):
|
||||
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 []}:
|
||||
if (a.get("kind") or "postcodes") not in SHAPES and code in {_norm_postcode(p) for p in a.get("postcodes") or []}:
|
||||
return a
|
||||
return None
|
||||
|
||||
@@ -92,8 +173,8 @@ def applies(rule, *, sales_point, subtotal, items, area, weekday, hhmm) -> bool:
|
||||
|
||||
|
||||
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)
|
||||
weekday=None, hhmm=None, point=None) -> dict:
|
||||
area = resolve_area(areas, area_id, postcode, point)
|
||||
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"
|
||||
|
||||
Reference in New Issue
Block a user