feat: delivery areas drawn on a map (plan 6R.G)
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>
This commit is contained in:
@@ -0,0 +1,37 @@
|
||||
"""Delivery areas drawn on a map (owner 2026-11-20, plan 6R.G, services/fees.py).
|
||||
|
||||
- delivery_areas.kind: postcodes (the list, as before) | polygon | circle;
|
||||
delivery_areas.geometry: JSON, [[lat, lng], …] for a polygon, {center: [lat, lng], radius_m} for a circle.
|
||||
- orders.online_lat / online_lng: where the customer pinned the delivery (online orders).
|
||||
|
||||
Additive: every existing area stays a postcode list.
|
||||
|
||||
Revision ID: 0053_delivery_shapes
|
||||
Revises: 0052_day_auto
|
||||
Create Date: 2026-11-23 23:50:00
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
revision = '0053_delivery_shapes'
|
||||
down_revision = '0052_day_auto'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
with op.batch_alter_table('delivery_areas') as b:
|
||||
b.add_column(sa.Column('kind', sa.String(), nullable=False, server_default='postcodes'))
|
||||
b.add_column(sa.Column('geometry', sa.Text(), nullable=True))
|
||||
with op.batch_alter_table('orders') as b:
|
||||
b.add_column(sa.Column('online_lat', sa.Float(), nullable=True))
|
||||
b.add_column(sa.Column('online_lng', sa.Float(), nullable=True))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
with op.batch_alter_table('orders') as b:
|
||||
b.drop_column('online_lng')
|
||||
b.drop_column('online_lat')
|
||||
with op.batch_alter_table('delivery_areas') as b:
|
||||
b.drop_column('geometry')
|
||||
b.drop_column('kind')
|
||||
@@ -1,7 +1,7 @@
|
||||
"""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
|
||||
postcode matched, or since 6R.G a shape drawn on a map / a circle, matched by the customer's pin) 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.
|
||||
"""
|
||||
@@ -17,6 +17,9 @@ class DeliveryArea(Base):
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
name = Column(String, nullable=False)
|
||||
postcodes = Column(Text, nullable=False, default="[]") # JSON list of strings
|
||||
# 6R.G: postcodes | polygon | circle; geometry JSON: [[lat, lng], …] or {center: [lat, lng], radius_m}
|
||||
kind = Column(String, nullable=False, default="postcodes", server_default="postcodes")
|
||||
geometry = Column(Text, nullable=True)
|
||||
is_active = Column(Integer, nullable=False, default=1)
|
||||
sort_order = Column(Integer, nullable=False, default=0)
|
||||
created_at = Column(UTCDateTime, default=utcnow)
|
||||
|
||||
@@ -37,6 +37,8 @@ class Order(Base):
|
||||
online_customer_notes = Column(Text, nullable=True)
|
||||
online_order_type = Column(String, nullable=True) # "delivery" | "dine_in"
|
||||
online_delivery_area = Column(String, nullable=True) # the area's name (phase 3S, S.5)
|
||||
online_lat = Column(Float, nullable=True) # 6R.G: the customer's pin, when given
|
||||
online_lng = Column(Float, nullable=True)
|
||||
# the site's own price check when the order was pulled (S.5): NULL = the cloud's prices
|
||||
# match the site's; else JSON {lines: [...], fee: {...}|null} (services/online_check.py)
|
||||
online_price_diff = Column(Text, nullable=True)
|
||||
|
||||
@@ -137,6 +137,8 @@ def _board_out(order: Order) -> dict:
|
||||
},
|
||||
"requested_for": _iso(order.requested_for), # None = as soon as possible (S.5)
|
||||
"area": order.online_delivery_area,
|
||||
# 6R.G: the customer's pin, for a map link (None = typed address only)
|
||||
"pin": {"lat": order.online_lat, "lng": order.online_lng} if order.online_lat is not None and order.online_lng is not None else None,
|
||||
"price_diff": OrderOut._diff(order.online_price_diff),
|
||||
"items": [OrderItemOut.model_validate(i).model_dump(mode="json") for i in items],
|
||||
"fee": round(sum(_item_total(i) for i in items if i.system_key == "delivery_fee"), 2),
|
||||
|
||||
@@ -4,6 +4,8 @@ GET /api/connect/fees {areas, rules, ordering, fee_product}
|
||||
PUT /api/connect/fees/fee-product the delivery fee line's name and VAT group (S.5)
|
||||
GET /api/connect/fees/ordering the online ordering settings PUT: save them
|
||||
POST /api/connect/fees/areas add an area PUT/DELETE /areas/{id}
|
||||
(6R.G: kind postcodes | polygon | circle, with its geometry)
|
||||
PUT /api/connect/fees/venue-point the venue's own place on the map {lat, lng} (or null)
|
||||
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
|
||||
@@ -37,8 +39,29 @@ SalesPoint = Literal["in_store", "in_store_takeaway", "qr_table", "online_takeaw
|
||||
# ── 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}
|
||||
try:
|
||||
geometry = json.loads(a.geometry) if a.geometry else None
|
||||
except ValueError:
|
||||
geometry = None
|
||||
return {"id": a.id, "name": a.name, "kind": a.kind or "postcodes", "postcodes": json.loads(a.postcodes or "[]"),
|
||||
"geometry": geometry, "is_active": bool(a.is_active), "sort_order": a.sort_order}
|
||||
|
||||
|
||||
VENUE_POINT_KEY = "venue.location"
|
||||
|
||||
|
||||
def venue_point(db):
|
||||
"""The venue's place on the map (6R.G): {lat, lng} or None. The delivery map starts there; a
|
||||
circle's centre is it by default."""
|
||||
from models.settings import PosSettings
|
||||
row = db.query(PosSettings).filter(PosSettings.key == VENUE_POINT_KEY).first()
|
||||
try:
|
||||
v = json.loads(row.value) if row and row.value else None
|
||||
except ValueError:
|
||||
return None
|
||||
if isinstance(v, dict) and isinstance(v.get("lat"), (int, float)) and isinstance(v.get("lng"), (int, float)):
|
||||
return {"lat": float(v["lat"]), "lng": float(v["lng"])}
|
||||
return None
|
||||
|
||||
|
||||
def rule_out(r) -> dict:
|
||||
@@ -72,7 +95,8 @@ def fees_payload(db) -> dict:
|
||||
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]}
|
||||
return {"areas": [area_out(a) for a in areas], "rules": [rule_out(r) for r in rules],
|
||||
"venue_point": venue_point(db)} # 6R.G: where the customer's map starts (the engine ignores it)
|
||||
|
||||
|
||||
def _clean_hours(v):
|
||||
@@ -135,11 +159,43 @@ class OrderingBody(BaseModel):
|
||||
return _clean_hours(v)
|
||||
|
||||
|
||||
def _lat_lng(p) -> list:
|
||||
if not (isinstance(p, (list, tuple)) and len(p) == 2 and all(isinstance(x, (int, float)) and not isinstance(x, bool) for x in p)):
|
||||
raise ValueError("a point is [lat, lng]")
|
||||
lat, lng = float(p[0]), float(p[1])
|
||||
if not (-90 <= lat <= 90 and -180 <= lng <= 180):
|
||||
raise ValueError("a point is [lat, lng] within -90..90, -180..180")
|
||||
return [round(lat, 7), round(lng, 7)]
|
||||
|
||||
|
||||
class AreaBody(BaseModel):
|
||||
"""An area: a list of postcodes, a shape drawn on the map (3 to 200 corners) or a circle
|
||||
(a centre and 50 m to 50 km). 6R.G."""
|
||||
name: str = Field(min_length=1, max_length=80)
|
||||
kind: Literal["postcodes", "polygon", "circle"] = "postcodes"
|
||||
postcodes: List[str] = Field(default_factory=list, max_length=100)
|
||||
geometry: Optional[object] = None
|
||||
is_active: bool = True
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _shape(self):
|
||||
if self.kind == "postcodes":
|
||||
self.geometry = None
|
||||
elif self.kind == "polygon":
|
||||
g = self.geometry
|
||||
if not isinstance(g, list) or not 3 <= len(g) <= 200:
|
||||
raise ValueError("a drawn area has 3 to 200 corners")
|
||||
self.geometry, self.postcodes = [_lat_lng(p) for p in g], []
|
||||
else:
|
||||
g = self.geometry
|
||||
if not isinstance(g, dict):
|
||||
raise ValueError("a circle is {center: [lat, lng], radius_m}")
|
||||
r = g.get("radius_m")
|
||||
if not isinstance(r, (int, float)) or isinstance(r, bool) or not 50 <= r <= 50_000:
|
||||
raise ValueError("a circle's radius is 50 m to 50 km")
|
||||
self.geometry, self.postcodes = {"center": _lat_lng(g.get("center")), "radius_m": round(float(r))}, []
|
||||
return self
|
||||
|
||||
@field_validator("name")
|
||||
@classmethod
|
||||
def _name(cls, v):
|
||||
@@ -317,11 +373,33 @@ def put_ordering(body: OrderingBody, db: Session = Depends(get_db), user=Depends
|
||||
return body.model_dump()
|
||||
|
||||
|
||||
class VenuePointBody(BaseModel):
|
||||
lat: Optional[float] = Field(default=None, ge=-90, le=90)
|
||||
lng: Optional[float] = Field(default=None, ge=-180, le=180)
|
||||
|
||||
|
||||
@router.put("/venue-point")
|
||||
def put_venue_point(body: VenuePointBody, db: Session = Depends(get_db), user=Depends(require(KEY))):
|
||||
"""The venue's place on the map (6R.G); both empty clears it. Reaches the cloud with the menu."""
|
||||
from models.settings import PosSettings
|
||||
point = {"lat": round(body.lat, 7), "lng": round(body.lng, 7)} if body.lat is not None and body.lng is not None else None
|
||||
row = db.query(PosSettings).filter(PosSettings.key == VENUE_POINT_KEY).first()
|
||||
value = json.dumps(point) if point else ""
|
||||
if row is None:
|
||||
db.add(PosSettings(key=VENUE_POINT_KEY, value=value))
|
||||
else:
|
||||
row.value = value
|
||||
db.commit()
|
||||
_changed()
|
||||
return {"venue_point": point}
|
||||
|
||||
|
||||
@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)
|
||||
area = DeliveryArea(name=body.name, postcodes=json.dumps(body.postcodes), is_active=int(body.is_active), sort_order=count,
|
||||
kind=body.kind, geometry=json.dumps(body.geometry) if body.geometry is not None else None)
|
||||
db.add(area)
|
||||
db.commit()
|
||||
_changed()
|
||||
@@ -335,6 +413,7 @@ def edit_area(area_id: int, body: AreaBody, db: Session = Depends(get_db), user=
|
||||
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)
|
||||
area.kind, area.geometry = body.kind, (json.dumps(body.geometry) if body.geometry is not None else None)
|
||||
db.commit()
|
||||
_changed()
|
||||
return area_out(area)
|
||||
@@ -409,6 +488,8 @@ class PreviewBody(BaseModel):
|
||||
sales_point: SalesPoint = "online_delivery"
|
||||
area_id: Optional[int] = None
|
||||
postcode: Optional[str] = Field(default=None, max_length=20)
|
||||
lat: Optional[float] = Field(default=None, ge=-90, le=90) # 6R.G: a point on the map
|
||||
lng: Optional[float] = Field(default=None, ge=-180, le=180)
|
||||
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
|
||||
@@ -435,7 +516,8 @@ def preview(body: PreviewBody, db: Session = Depends(get_db), user=Depends(requi
|
||||
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)
|
||||
items=body.items, area_id=body.area_id, postcode=body.postcode, weekday=weekday, hhmm=hhmm,
|
||||
point=[body.lat, body.lng] if body.lat is not None and body.lng is not None else None)
|
||||
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}
|
||||
|
||||
@@ -440,6 +440,9 @@ def store_online_orders(db, orders: list[dict], booked: list | None = None, at_t
|
||||
online_customer_notes=_with_table(cloud_order),
|
||||
online_order_type=cloud_order.get("order_type"),
|
||||
online_delivery_area=cloud_order.get("delivery_area"),
|
||||
# 6R.G: the customer's pin (the delivery's map link)
|
||||
online_lat=(online_check.pin_of(cloud_order) or [None, None])[0],
|
||||
online_lng=(online_check.pin_of(cloud_order) or [None, None])[1],
|
||||
online_price_diff=json.dumps(diff) if diff else None,
|
||||
requested_for=_aware(cloud_order.get("requested_for")),
|
||||
)
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -22,6 +22,13 @@ from datetime import datetime
|
||||
EPS = 0.005
|
||||
|
||||
|
||||
|
||||
def pin_of(cloud_order) -> list | None:
|
||||
"""The customer's pin [lat, lng] (6R.G), when the order has one."""
|
||||
lat, lng = cloud_order.get("lat"), cloud_order.get("lng")
|
||||
ok = all(isinstance(x, (int, float)) and not isinstance(x, bool) for x in (lat, lng))
|
||||
return [float(lat), float(lng)] if ok else None
|
||||
|
||||
def _when(cloud_order: dict):
|
||||
from core.timeutil import utcnow
|
||||
raw = cloud_order.get("created_at")
|
||||
@@ -76,7 +83,8 @@ def diff(db, cloud_order: dict, sales_point: str) -> dict | None:
|
||||
subtotal=round(float(cloud_order.get("subtotal") or 0.0), 2),
|
||||
items=sum(int(i.get("quantity", 1) or 1) for i in items),
|
||||
area_id=cloud_order.get("delivery_area_id"), postcode=None,
|
||||
weekday=local.weekday(), hhmm=local.strftime("%H:%M"))
|
||||
weekday=local.weekday(), hhmm=local.strftime("%H:%M"),
|
||||
point=pin_of(cloud_order)) # 6R.G: a drawn area needs the pin
|
||||
if result["refused"]:
|
||||
fee = {"cloud": cloud_fee, "site": None,
|
||||
"reason": "area" if result["refused"] == "area_not_served" else "minimum"}
|
||||
|
||||
+41
-2
@@ -3,7 +3,10 @@
|
||||
"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}
|
||||
{"id": 3, "name": "Old area", "postcodes": ["99999"], "is_active": false},
|
||||
{"id": 4, "name": "Drawn square", "kind": "polygon", "postcodes": [], "is_active": true, "geometry": [[37.0, 22.0], [37.0, 22.1], [37.1, 22.1], [37.1, 22.0]]},
|
||||
{"id": 5, "name": "1 km around", "kind": "circle", "postcodes": [], "is_active": true, "geometry": {"center": [37.5, 22.5], "radius_m": 1000}},
|
||||
{"id": 6, "name": "Old shape", "kind": "polygon", "postcodes": [], "is_active": false, "geometry": [[38.0, 23.0], [38.0, 23.1], [38.1, 23.1]]}
|
||||
],
|
||||
"cases": [
|
||||
{"name": "no rules: free",
|
||||
@@ -103,6 +106,42 @@
|
||||
{"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}}
|
||||
"expect": {"fee": 0.3, "refused": null, "area_id": null}},
|
||||
{"name": "6R.G: a pin inside a drawn shape",
|
||||
"rules": [], "ctx": {"sales_point": "online_delivery", "subtotal": 20, "items": 2, "point": [37.05, 22.05]},
|
||||
"expect": {"refused": null, "area_id": 4}},
|
||||
{"name": "6R.G: a pin on the shape's edge counts as inside",
|
||||
"rules": [], "ctx": {"sales_point": "online_delivery", "subtotal": 20, "items": 2, "point": [37.0, 22.05]},
|
||||
"expect": {"refused": null, "area_id": 4}},
|
||||
{"name": "6R.G: a pin on a corner counts as inside",
|
||||
"rules": [], "ctx": {"sales_point": "online_delivery", "subtotal": 20, "items": 2, "point": [37.1, 22.1]},
|
||||
"expect": {"refused": null, "area_id": 4}},
|
||||
{"name": "6R.G: a pin outside every area is refused",
|
||||
"rules": [], "ctx": {"sales_point": "online_delivery", "subtotal": 20, "items": 2, "point": [37.2, 22.05]},
|
||||
"expect": {"refused": "area_not_served", "area_id": null}},
|
||||
{"name": "6R.G: inside the circle (990 m)",
|
||||
"rules": [], "ctx": {"sales_point": "online_delivery", "subtotal": 20, "items": 2, "point": [37.5089, 22.5]},
|
||||
"expect": {"refused": null, "area_id": 5}},
|
||||
{"name": "6R.G: past the circle's rim (1.1 km)",
|
||||
"rules": [], "ctx": {"sales_point": "online_delivery", "subtotal": 20, "items": 2, "point": [37.5099, 22.5]},
|
||||
"expect": {"refused": "area_not_served"}},
|
||||
{"name": "6R.G: a shape picked by id needs a pin inside it",
|
||||
"rules": [], "ctx": {"sales_point": "online_delivery", "subtotal": 20, "items": 2, "area_id": 4},
|
||||
"expect": {"refused": "area_not_served"}},
|
||||
{"name": "6R.G: a shape picked by id with its pin",
|
||||
"rules": [], "ctx": {"sales_point": "online_delivery", "subtotal": 20, "items": 2, "area_id": 4, "point": [37.05, 22.05]},
|
||||
"expect": {"area_id": 4}},
|
||||
{"name": "6R.G: a shape picked with a pin outside it falls back to the postcode",
|
||||
"rules": [], "ctx": {"sales_point": "online_delivery", "subtotal": 20, "items": 2, "area_id": 4, "point": [37.2, 22.0], "postcode": "24131"},
|
||||
"expect": {"area_id": 2}},
|
||||
{"name": "6R.G: an inactive shape holds nothing",
|
||||
"rules": [], "ctx": {"sales_point": "online_delivery", "subtotal": 20, "items": 2, "point": [38.02, 23.05]},
|
||||
"expect": {"refused": "area_not_served"}},
|
||||
{"name": "6R.G: a nonsense pin is no pin",
|
||||
"rules": [], "ctx": {"sales_point": "online_delivery", "subtotal": 20, "items": 2, "point": ["x", 200], "postcode": "241 00"},
|
||||
"expect": {"area_id": 1}},
|
||||
{"name": "6R.G: rules by area work for shapes",
|
||||
"rules": [{"id": 1, "name": "Square fee", "area_ids": [4], "action": "set", "value": 2.5, "sales_points": ["online_delivery"]}, {"id": 2, "name": "Circle fee", "area_ids": [5], "action": "set", "value": 1, "sales_points": ["online_delivery"]}], "ctx": {"sales_point": "online_delivery", "subtotal": 20, "items": 2, "point": [37.05, 22.05]},
|
||||
"expect": {"fee": 2.5, "area_id": 4}}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -151,3 +151,56 @@ def test_online_ordering_settings(client, db, owner_h):
|
||||
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
|
||||
|
||||
@@ -176,3 +176,25 @@ def test_the_venues_ordering_link(client, owner_h, monkeypatch):
|
||||
monkeypatch.setattr(cloud_sync.settings, "SITE_ID", "taverna-1")
|
||||
links = client.get("/api/connect/fees", headers=owner_h).json()["links"]
|
||||
assert links == {"order": "https://menu.example.com/order/taverna-1", "menu": "https://menu.example.com/menu/taverna-1"}
|
||||
|
||||
|
||||
def test_a_pinned_delivery_keeps_its_pin_and_is_checked_by_it(client, db, counter, menu):
|
||||
"""6R.G: an order priced by a drawn area: the site checks the fee with the pin (a shape is
|
||||
matched only by a point inside it), keeps the pin for a map link on the counter."""
|
||||
from models.fees import DeliveryArea, FeeRule
|
||||
from models.order import Order
|
||||
drawn = DeliveryArea(name="Drawn", kind="polygon", postcodes="[]", is_active=1, sort_order=0,
|
||||
geometry=json.dumps([[37.0, 22.0], [37.0, 22.1], [37.1, 22.1], [37.1, 22.0]]))
|
||||
db.add(drawn)
|
||||
db.flush()
|
||||
db.add(FeeRule(name="Drawn", is_active=1, sort_order=0, sales_points=json.dumps(["online_delivery"]),
|
||||
area_ids=json.dumps([drawn.id]), action="set", value=2.5, stop=1))
|
||||
db.commit()
|
||||
oid = pull(db, menu, cloud_id=611, area_id=drawn.id, area="Drawn", lat=37.05, lng=22.05)
|
||||
order = db.get(Order, oid)
|
||||
assert order.online_price_diff is None and (order.online_lat, order.online_lng) == (37.05, 22.05)
|
||||
assert next(x for x in board(client, counter)["incoming"] if x["id"] == oid)["pin"] == {"lat": 37.05, "lng": 22.05}
|
||||
# no pin: the site can't place it in the drawn area, and says so (the customer keeps the cloud's fee)
|
||||
oid = pull(db, menu, cloud_id=612, area_id=drawn.id, area="Drawn")
|
||||
assert json.loads(db.get(Order, oid).online_price_diff)["fee"]["reason"] == "area"
|
||||
assert next(x for x in board(client, counter)["incoming"] if x["id"] == oid)["pin"] is None
|
||||
|
||||
Reference in New Issue
Block a user