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:
@@ -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}
|
||||
|
||||
Reference in New Issue
Block a user