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:
2026-11-23 21:56:13 +02:00
co-authored by Claude Opus 5.5
parent e55157fa86
commit d5b8492512
17 changed files with 406 additions and 41 deletions
@@ -0,0 +1,26 @@
"""online orders: lat / lng, where the customer pinned the delivery (plan 6R.G: areas drawn on a map)
Revision ID: 0007_order_pin
Revises: 0006_order_table_id
Create Date: 2026-11-23 23:55:00
"""
from alembic import op
import sqlalchemy as sa
revision = '0007_order_pin'
down_revision = '0006_order_table_id'
branch_labels = None
depends_on = None
def upgrade() -> None:
with op.batch_alter_table('online_orders', schema=None) as batch_op:
batch_op.add_column(sa.Column('lat', sa.Float(), nullable=True))
batch_op.add_column(sa.Column('lng', sa.Float(), nullable=True))
def downgrade() -> None:
with op.batch_alter_table('online_orders', schema=None) as batch_op:
batch_op.drop_column('lng')
batch_op.drop_column('lat')
+2
View File
@@ -28,6 +28,8 @@ class OnlineOrder(Base):
table_id = Column(Integer, nullable=True) # the site's table id, from a valid QR token (S.7) table_id = Column(Integer, nullable=True) # the site's table id, from a valid QR token (S.7)
delivery_area = Column(String, nullable=True) # the delivery area's name (S.3) delivery_area = Column(String, nullable=True) # the delivery area's name (S.3)
delivery_area_id = Column(Integer, nullable=True) # the site's area id (S.5: the site checks the fee) delivery_area_id = Column(Integer, nullable=True) # the site's area id (S.5: the site checks the fee)
lat = Column(Float, nullable=True) # 6R.G: where the customer pinned the delivery
lng = Column(Float, nullable=True)
requested_for = Column(DateTime(timezone=True), nullable=True) # the time slot picked (S.4); null = asap requested_for = Column(DateTime(timezone=True), nullable=True) # the time slot picked (S.4); null = asap
party_size = Column(Integer, nullable=True) # reservations (S.6): how many guests party_size = Column(Integer, nullable=True) # reservations (S.6): how many guests
sales_point = Column(String, nullable=True) # the site's sales point (phase 3S, S.2) sales_point = Column(String, nullable=True) # the site's sales point (phase 3S, S.2)
+3 -2
View File
@@ -43,8 +43,9 @@ def get_menu(site_slug: str, t: str | None = None, db: Session = Depends(get_db)
import json import json
data = json.loads(snapshot.snapshot_json) data = json.loads(snapshot.snapshot_json)
from services.checkout import delivery_areas from services.checkout import delivery_areas, venue_point
data["delivery_areas"] = delivery_areas(data) # S.3: what the customer picks from data["delivery_areas"] = delivery_areas(data) # S.3: what the customer picks from (6R.G: shapes drawn)
data["venue_point"] = venue_point(data) # 6R.G: where the customer's map starts
data.pop("fees", None) # the rules and postcodes stay on the cloud data.pop("fees", None) # the rules and postcodes stay on the cloud
from services.ordering import summary from services.ordering import summary
data["ordering"] = summary(data) # S.4: services, open now, slots data["ordering"] = summary(data) # S.4: services, open now, slots
+11 -4
View File
@@ -72,9 +72,14 @@ def _site_and_menu(db, site_slug):
return site, json.loads(snap.snapshot_json) return site, json.loads(snap.snapshot_json)
def _priced(menu, order_type, items, area_id=None, postcode=None): def _pin(body):
"""The customer's pin [lat, lng] (6R.G), both or nothing."""
return [body.lat, body.lng] if body.lat is not None and body.lng is not None else None
def _priced(menu, order_type, items, area_id=None, postcode=None, point=None):
try: try:
return price_cart(menu, order_type, items, area_id=area_id, postcode=postcode) return price_cart(menu, order_type, items, area_id=area_id, postcode=postcode, pin=point)
except CheckoutError as e: except CheckoutError as e:
raise HTTPException(status_code=e.status, detail=e.detail()) raise HTTPException(status_code=e.status, detail=e.detail())
@@ -102,7 +107,7 @@ def quote_order(site_slug: str, body: QuoteRequest, request: Request, db: Sessio
"""The cart priced by the cloud from the venue's menu, for the customer apps (phase 3S).""" """The cart priced by the cloud from the venue's menu, for the customer apps (phase 3S)."""
_limit(request, "quote", QUOTE_LIMIT) _limit(request, "quote", QUOTE_LIMIT)
_site, menu = _site_and_menu(db, site_slug) _site, menu = _site_and_menu(db, site_slug)
return _priced(menu, body.order_type, [i.model_dump() for i in body.items], body.area_id, body.postcode).out() return _priced(menu, body.order_type, [i.model_dump() for i in body.items], body.area_id, body.postcode, _pin(body)).out()
@router.post("/{site_slug}", response_model=OnlineOrderCreated, status_code=status.HTTP_201_CREATED) @router.post("/{site_slug}", response_model=OnlineOrderCreated, status_code=status.HTTP_201_CREATED)
@@ -127,7 +132,7 @@ def create_order(site_slug: str, body: OnlineOrderCreate, request: Request, db:
raise HTTPException(status_code=422, detail={"code": "order.items_not_allowed", "params": {}}) raise HTTPException(status_code=422, detail={"code": "order.items_not_allowed", "params": {}})
priced = None priced = None
else: else:
priced = _priced(menu, body.order_type, items, body.area_id, body.postcode) priced = _priced(menu, body.order_type, items, body.area_id, body.postcode, _pin(body))
if reservation: if reservation:
problem = ordering.res_check(menu, body.order_type, body.requested_for, body.party_size) problem = ordering.res_check(menu, body.order_type, body.requested_for, body.party_size)
elif body.order_type in ("takeaway", "delivery"): # the online ordering app (S.4) elif body.order_type in ("takeaway", "delivery"): # the online ordering app (S.4)
@@ -162,6 +167,8 @@ def create_order(site_slug: str, body: OnlineOrderCreate, request: Request, db:
table_id=table["id"] if table else None, table_id=table["id"] if table else None,
delivery_area=priced.area_name if priced else None, delivery_area=priced.area_name if priced else None,
delivery_area_id=priced.area_id if priced else None, delivery_area_id=priced.area_id if priced else None,
lat=body.lat if body.order_type == "delivery" and _pin(body) else None,
lng=body.lng if body.order_type == "delivery" and _pin(body) else None,
# stored as UTC: SQLite keeps no time zone (read back naive = UTC, schemas mark it) # stored as UTC: SQLite keeps no time zone (read back naive = UTC, schemas mark it)
requested_for=(body.requested_for.astimezone(timezone.utc).replace(tzinfo=None) requested_for=(body.requested_for.astimezone(timezone.utc).replace(tzinfo=None)
if (reservation or body.order_type in ("takeaway", "delivery")) and body.requested_for else None), if (reservation or body.order_type in ("takeaway", "delivery")) and body.requested_for else None),
+6
View File
@@ -28,6 +28,8 @@ class QuoteRequest(BaseModel):
items: list[OrderItemIn] = Field(max_length=100) items: list[OrderItemIn] = Field(max_length=100)
area_id: Optional[int] = None # the delivery area picked (S.3) area_id: Optional[int] = None # the delivery area picked (S.3)
postcode: Optional[str] = Field(default=None, max_length=20) postcode: Optional[str] = Field(default=None, max_length=20)
lat: Optional[float] = Field(default=None, ge=-90, le=90) # 6R.G: the customer's pin on the map
lng: Optional[float] = Field(default=None, ge=-180, le=180)
class OnlineOrderCreate(BaseModel): class OnlineOrderCreate(BaseModel):
@@ -41,6 +43,8 @@ class OnlineOrderCreate(BaseModel):
table_token: Optional[str] = Field(default=None, max_length=100) # the table's QR token (S.7) table_token: Optional[str] = Field(default=None, max_length=100) # the table's QR token (S.7)
area_id: Optional[int] = None # the delivery area picked (S.3) area_id: Optional[int] = None # the delivery area picked (S.3)
postcode: Optional[str] = Field(default=None, max_length=20) postcode: Optional[str] = Field(default=None, max_length=20)
lat: Optional[float] = Field(default=None, ge=-90, le=90) # 6R.G: the customer's pin on the map
lng: Optional[float] = Field(default=None, ge=-180, le=180)
requested_for: Optional[datetime] = None # a time slot (S.4); None = as soon as possible requested_for: Optional[datetime] = None # a time slot (S.4); None = as soon as possible
items: list[OrderItemIn] = Field(default_factory=list, max_length=100) items: list[OrderItemIn] = Field(default_factory=list, max_length=100)
# what the customer was shown: compared, never stored as sent # what the customer was shown: compared, never stored as sent
@@ -88,6 +92,8 @@ class PendingOrderOut(BaseModel):
table_id: Optional[int] = None # the site's table, from a valid QR token (S.7) table_id: Optional[int] = None # the site's table, from a valid QR token (S.7)
delivery_area: Optional[str] = None # the delivery area's name (S.3) delivery_area: Optional[str] = None # the delivery area's name (S.3)
delivery_area_id: Optional[int] = None # the site's area id (S.5) delivery_area_id: Optional[int] = None # the site's area id (S.5)
lat: Optional[float] = None # 6R.G: the customer's pin
lng: Optional[float] = None
requested_for: Optional[datetime] = None # when the customer wants it (S.4); None = as soon as possible requested_for: Optional[datetime] = None # when the customer wants it (S.4); None = as soon as possible
party_size: Optional[int] = None # reservations (S.6) party_size: Optional[int] = None # reservations (S.6)
sales_point: Optional[str] = None # the site's sales point (S.2) sales_point: Optional[str] = None # the site's sales point (S.2)
+22 -6
View File
@@ -89,9 +89,24 @@ def venue_clock(snapshot: dict, now: datetime | None = None) -> tuple[int, str]:
def delivery_areas(snapshot: dict) -> list: def delivery_areas(snapshot: dict) -> list:
"""The active areas a customer picks from: [{id, name}] (no postcodes, no rules).""" """The active areas: [{id, name, kind}] (no postcodes, no rules). A postcode area is picked
return [{"id": a.get("id"), "name": a.get("name")} for a in (snapshot.get("fees") or {}).get("areas") or [] from a list; a shape (6R.G: polygon / circle) also gives its geometry, so the customer's map
if a.get("is_active", True)] 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]: 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, 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 """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) point = POINT_FOR_TYPE.get(order_type)
if point is None: if point is None:
raise CheckoutError(422, "order.type_invalid", order_type=order_type) 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) weekday, hhmm = venue_clock(snapshot, now)
result = fee_engine.compute(rules.get("rules") or [], rules.get("areas") or [], sales_point=point, 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), 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": if result["refused"] == "area_not_served":
raise CheckoutError(409, "order.area_not_served", postcode=postcode, area_id=area_id) raise CheckoutError(409, "order.area_not_served", postcode=postcode, area_id=area_id)
if result["refused"] == "minimum_not_met": if result["refused"] == "minimum_not_met":
+91 -10
View File
@@ -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). 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, 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) Areas: {id, name, kind, postcodes: [str], geometry, is_active}. `kind` (6R.G; missing =
or the one whose postcodes contain theirs (spaces ignored). When the venue has active areas, "postcodes"): "postcodes" (a list), "polygon" (geometry [[lat, lng], …], at least 3 corners) or
a delivery to none of them is refused ("area_not_served"); with no areas, anywhere is fine. "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, 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}. 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 from __future__ import annotations
import math
EPS = 0.0005 EPS = 0.0005
ACTIONS = ("set", "add", "percent", "free", "minimum") 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: def _norm_postcode(value) -> str:
return "".join(str(value or "").split()).upper() return "".join(str(value or "").split()).upper()
def resolve_area(areas: list, area_id=None, postcode=None): def _point(value):
"""The customer's active area: by id, else by postcode; None when neither matches.""" """[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)] active = [a for a in areas or [] if a.get("is_active", True)]
if area_id is not None: if area_id is not None:
for a in active: 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 return a
code = _norm_postcode(postcode) code = _norm_postcode(postcode)
if code: if code:
for a in active: 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 a
return None 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, def compute(rules, areas, *, sales_point, subtotal, items, area_id=None, postcode=None,
weekday=None, hhmm=None) -> dict: weekday=None, hhmm=None, point=None) -> dict:
area = resolve_area(areas, area_id, postcode) 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": []} 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 []): 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" result["refused"] = "area_not_served"
+41 -2
View File
@@ -3,7 +3,10 @@
"areas": [ "areas": [
{"id": 1, "name": "Village centre", "postcodes": ["241 00"], "is_active": true}, {"id": 1, "name": "Village centre", "postcodes": ["241 00"], "is_active": true},
{"id": 2, "name": "Kalamata", "postcodes": ["24100", "24131"], "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": [ "cases": [
{"name": "no rules: free", {"name": "no rules: free",
@@ -103,6 +106,42 @@
{"name": "a takeaway packaging fee (areas only matter for delivery)", {"name": "a takeaway packaging fee (areas only matter for delivery)",
"rules": [{"id": 1, "name": "Packaging", "sales_points": ["online_takeaway"], "action": "set", "value": 0.3}], "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"}, "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}}
] ]
} }
+38 -1
View File
@@ -75,7 +75,7 @@ def test_minimum_and_area_are_refused(client, admin_h):
def test_the_public_menu_lists_areas_but_not_the_rules(client, admin_h): def test_the_public_menu_lists_areas_but_not_the_rules(client, admin_h):
site, _ = _venue_with_fees(client, admin_h) site, _ = _venue_with_fees(client, admin_h)
menu = client.get(f"/api/menu/{site['site_id']}").json() menu = client.get(f"/api/menu/{site['site_id']}").json()
assert menu["delivery_areas"] == [{"id": 1, "name": "Centre"}, {"id": 2, "name": "Far"}] assert menu["delivery_areas"] == [{"id": 1, "name": "Centre", "kind": "postcodes"}, {"id": 2, "name": "Far", "kind": "postcodes"}]
assert "fees" not in menu assert "fees" not in menu
@@ -84,3 +84,40 @@ def test_the_venue_clock():
at = datetime(2026, 11, 15, 21, 30, tzinfo=timezone.utc) # Sunday 23:30 in Athens (UTC+2) 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": "Europe/Athens"}, at) == (6, "23:30")
assert venue_clock({"timezone": "Nowhere/Bad"}, 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)
+7
View File
@@ -9,6 +9,7 @@
"version": "0.1.0", "version": "0.1.0",
"dependencies": { "dependencies": {
"axios": "^1.7.9", "axios": "^1.7.9",
"leaflet": "^1.9.4",
"lucide-react": "^1.14.0", "lucide-react": "^1.14.0",
"react": "^18.3.1", "react": "^18.3.1",
"react-dom": "^18.3.1", "react-dom": "^18.3.1",
@@ -2091,6 +2092,12 @@
"node": ">=6" "node": ">=6"
} }
}, },
"node_modules/leaflet": {
"version": "1.9.4",
"resolved": "https://registry.npmjs.org/leaflet/-/leaflet-1.9.4.tgz",
"integrity": "sha512-nxS1ynzJOmOlHp+iL3FyWqK89GtNL8U8rvlMOsQdTTssxZwCXh8N2NB3GDQOL+YR3XnWyZAxwQixURb+FA74PA==",
"license": "BSD-2-Clause"
},
"node_modules/lilconfig": { "node_modules/lilconfig": {
"version": "3.1.3", "version": "3.1.3",
"resolved": "https://registry.npmjs.org/lilconfig/-/lilconfig-3.1.3.tgz", "resolved": "https://registry.npmjs.org/lilconfig/-/lilconfig-3.1.3.tgz",
+1
View File
@@ -11,6 +11,7 @@
}, },
"dependencies": { "dependencies": {
"axios": "^1.7.9", "axios": "^1.7.9",
"leaflet": "^1.9.4",
"lucide-react": "^1.14.0", "lucide-react": "^1.14.0",
"react": "^18.3.1", "react": "^18.3.1",
"react-dom": "^18.3.1", "react-dom": "^18.3.1",
+8 -2
View File
@@ -27,13 +27,16 @@ export const TEXTS = {
pricing: 'Working out the price…', details: 'Your details', name: 'Name', phone: 'Phone', pricing: 'Working out the price…', details: 'Your details', name: 'Name', phone: 'Phone',
address: 'Street and number', area: 'Area', areaPick: 'Pick your area', byPostcode: 'Or enter your postcode', address: 'Street and number', area: 'Area', areaPick: 'Pick your area', byPostcode: 'Or enter your postcode',
byArea: 'Pick from the list', postcode: 'Postcode', notes: 'Notes for the venue (optional)', byArea: 'Pick from the list', postcode: 'Postcode', notes: 'Notes for the venue (optional)',
byMap: 'Pin it on the map', pinHint: 'Tap the map where we deliver to. The coloured areas are where the venue delivers.',
myLocation: 'Use my location', locating: 'Finding you…', locationFailed: 'Your location could not be found. Tap the map instead.',
pinned: 'Pinned on the map', mapTiles: 'Map',
when: 'When', asap: 'As soon as possible', pickTime: 'Pick a time', today: 'Today', tomorrow: 'Tomorrow', when: 'When', asap: 'As soon as possible', pickTime: 'Pick a time', today: 'Today', tomorrow: 'Tomorrow',
placeOrder: 'Place order · {{total}}', sending: 'Sending…', back: 'Back', placeOrder: 'Place order · {{total}}', sending: 'Sending…', back: 'Back',
payNote: 'You pay at the venue or on delivery.', payNote: 'You pay at the venue or on delivery.',
problem: { problem: {
party: 'Pick how many people.', party: 'Pick how many people.',
name: 'Enter your name.', phone: 'Enter a phone number we can call.', address: 'Enter the delivery address.', name: 'Enter your name.', phone: 'Enter a phone number we can call.', address: 'Enter the delivery address.',
area: 'Pick your area.', postcode: 'Enter your postcode.', when: 'Pick a time.', area: 'Pick your area.', postcode: 'Enter your postcode.', when: 'Pick a time.', pin: 'Tap the map where we deliver to.',
}, },
refused: { refused: {
minimum_not_met: 'The minimum order for delivery is {{minimum}}.', area_not_served: 'Sorry, we don\'t deliver to this address.', minimum_not_met: 'The minimum order for delivery is {{minimum}}.', area_not_served: 'Sorry, we don\'t deliver to this address.',
@@ -81,13 +84,16 @@ export const TEXTS = {
pricing: 'Υπολογισμός τιμής…', details: 'Τα στοιχεία σας', name: 'Όνομα', phone: 'Τηλέφωνο', pricing: 'Υπολογισμός τιμής…', details: 'Τα στοιχεία σας', name: 'Όνομα', phone: 'Τηλέφωνο',
address: 'Οδός και αριθμός', area: 'Περιοχή', areaPick: 'Επιλέξτε περιοχή', byPostcode: 'Ή γράψτε τον Τ.Κ.', address: 'Οδός και αριθμός', area: 'Περιοχή', areaPick: 'Επιλέξτε περιοχή', byPostcode: 'Ή γράψτε τον Τ.Κ.',
byArea: 'Επιλογή από τη λίστα', postcode: 'Τ.Κ.', notes: 'Σημειώσεις για το κατάστημα (προαιρετικά)', byArea: 'Επιλογή από τη λίστα', postcode: 'Τ.Κ.', notes: 'Σημειώσεις για το κατάστημα (προαιρετικά)',
byMap: 'Σημείο στον χάρτη', pinHint: 'Πατήστε στον χάρτη εκεί που θα παραδώσουμε. Οι χρωματιστές περιοχές είναι εκεί που παραδίδει το κατάστημα.',
myLocation: 'Η τοποθεσία μου', locating: 'Αναζήτηση…', locationFailed: 'Η τοποθεσία σας δεν βρέθηκε. Πατήστε στον χάρτη.',
pinned: 'Σημείο στον χάρτη', mapTiles: 'Χάρτης',
when: 'Πότε', asap: 'Το συντομότερο', pickTime: 'Επιλέξτε ώρα', today: 'Σήμερα', tomorrow: 'Αύριο', when: 'Πότε', asap: 'Το συντομότερο', pickTime: 'Επιλέξτε ώρα', today: 'Σήμερα', tomorrow: 'Αύριο',
placeOrder: 'Αποστολή · {{total}}', sending: 'Αποστολή…', back: 'Πίσω', placeOrder: 'Αποστολή · {{total}}', sending: 'Αποστολή…', back: 'Πίσω',
payNote: 'Πληρώνετε στο κατάστημα ή κατά την παράδοση.', payNote: 'Πληρώνετε στο κατάστημα ή κατά την παράδοση.',
problem: { problem: {
party: 'Επιλέξτε πόσα άτομα.', party: 'Επιλέξτε πόσα άτομα.',
name: 'Γράψτε το όνομά σας.', phone: 'Γράψτε ένα τηλέφωνο επικοινωνίας.', address: 'Γράψτε τη διεύθυνση παράδοσης.', name: 'Γράψτε το όνομά σας.', phone: 'Γράψτε ένα τηλέφωνο επικοινωνίας.', address: 'Γράψτε τη διεύθυνση παράδοσης.',
area: 'Επιλέξτε την περιοχή σας.', postcode: 'Γράψτε τον Τ.Κ.', when: 'Επιλέξτε ώρα.', area: 'Επιλέξτε την περιοχή σας.', postcode: 'Γράψτε τον Τ.Κ.', when: 'Επιλέξτε ώρα.', pin: 'Πατήστε στον χάρτη εκεί που θα παραδώσουμε.',
}, },
refused: { refused: {
minimum_not_met: 'Η ελάχιστη παραγγελία για διανομή είναι {{minimum}}.', area_not_served: 'Δυστυχώς δεν κάνουμε διανομή σε αυτή τη διεύθυνση.', minimum_not_met: 'Η ελάχιστη παραγγελία για διανομή είναι {{minimum}}.', area_not_served: 'Δυστυχώς δεν κάνουμε διανομή σε αυτή τη διεύθυνση.',
+20
View File
@@ -104,6 +104,7 @@ export function checkoutProblems(form, service, { areas = [], asap = true, slots
if (!form.address.trim()) out.push('address') if (!form.address.trim()) out.push('address')
if (areas.length && form.where === 'area' && !form.areaId) out.push('area') if (areas.length && form.where === 'area' && !form.areaId) out.push('area')
if (form.where === 'postcode' && !form.postcode.trim()) out.push('postcode') if (form.where === 'postcode' && !form.postcode.trim()) out.push('postcode')
if (form.where === 'map' && !form.pin) out.push('pin') // 6R.G
} }
if (form.when === 'asap' ? !asap : !slots.includes(form.when)) out.push('when') if (form.when === 'asap' ? !asap : !slots.includes(form.when)) out.push('when')
return out return out
@@ -119,6 +120,8 @@ export function orderBody(form, service, lines, quote) {
customer_notes: form.notes.trim() || null, customer_notes: form.notes.trim() || null,
area_id: service === 'delivery' && form.where === 'area' && form.areaId ? Number(form.areaId) : null, area_id: service === 'delivery' && form.where === 'area' && form.areaId ? Number(form.areaId) : null,
postcode: service === 'delivery' && form.where === 'postcode' ? form.postcode.trim() || null : null, postcode: service === 'delivery' && form.where === 'postcode' ? form.postcode.trim() || null : null,
// 6R.G: the customer's pin on the map (the venue's drawn areas are matched by it); only when given
...(service === 'delivery' && form.where === 'map' && form.pin ? { lat: form.pin[0], lng: form.pin[1] } : {}),
requested_for: form.when === 'asap' ? null : form.when, requested_for: form.when === 'asap' ? null : form.when,
items: itemsBody(lines), items: itemsBody(lines),
total: quote?.total ?? undefined, total: quote?.total ?? undefined,
@@ -185,3 +188,20 @@ export function refusal(err) {
if (d && typeof d === 'object' && d.code) return [d.code.replace(/^order\./, ''), d.params ?? {}] if (d && typeof d === 'object' && d.code) return [d.code.replace(/^order\./, ''), d.params ?? {}]
return ['failed', {}] return ['failed', {}]
} }
// ── 6R.G: delivery areas drawn on a map ───────────────────────────────────────────────────
/** The venue's areas split by how the customer says where they are: `listed` (picked by name,
* postcode areas) and `shapes` (drawn on a map or a circle: the customer pins their address). */
export function areaKinds(areas = []) {
return {
listed: areas.filter(a => (a.kind ?? 'postcodes') === 'postcodes'),
shapes: areas.filter(a => a.kind === 'polygon' || a.kind === 'circle'),
}
}
/** The ways offered to say where the delivery goes, in order: 'map' (when the venue drew areas),
* 'area' (a list to pick from), 'postcode' (always). The first is the default. */
export function whereOptions(areas = []) {
const { listed, shapes } = areaKinds(areas)
return [...(shapes.length ? ['map'] : []), ...(listed.length ? ['area'] : []), 'postcode']
}
@@ -4,11 +4,14 @@
// the cloud's answer; the order is refused if it changed meanwhile and the new prices show. // the cloud's answer; the order is refused if it changed meanwhile and the new prices show.
// S.6: service 'book' = a table booking (`booking` {party, when}), with food ordered ahead // S.6: service 'book' = a table booking (`booking` {party, when}), with food ordered ahead
// when there are lines (priced as a pre-order); no address, no time picker here. // when there are lines (priced as a pre-order); no address, no time picker here.
// 6R.G: when the venue drew its delivery areas on a map, the customer pins the address (PinMap; the
// browser's location offered); the pin goes with the quote and the order and finds the area.
import { useEffect, useMemo, useRef, useState } from 'react' import { useEffect, useMemo, useRef, useState } from 'react'
import { ArrowLeft, Minus, Plus } from 'lucide-react' import { ArrowLeft, LocateFixed, Minus, Plus } from 'lucide-react'
import { fetchSlots, placeOrder, quote } from '../api' import { fetchSlots, placeOrder, quote } from '../api'
import { useT } from '../i18n' import { useT } from '../i18n'
import { bookingBody, bookingProblems, checkoutProblems, itemsBody, orderBody, refusal, setQty, slotDays } from '../logic' import { areaKinds, bookingBody, bookingProblems, checkoutProblems, itemsBody, orderBody, refusal, setQty, slotDays, whereOptions } from '../logic'
import PinMap from './PinMap'
const QUOTE_DELAY = 250 const QUOTE_DELAY = 250
const SLOTS_EVERY = 60_000 const SLOTS_EVERY = 60_000
@@ -23,10 +26,13 @@ export default function Checkout({ site, service, booking, menu, lines, setCart,
const book = service === 'book' const book = service === 'book'
const quoteType = book ? 'preorder' : service const quoteType = book ? 'preorder' : service
const areas = menu.delivery_areas ?? [] const areas = menu.delivery_areas ?? []
const { listed, shapes } = areaKinds(areas)
const ways = whereOptions(areas)
const [form, setForm] = useState(() => ({ const [form, setForm] = useState(() => ({
name: '', phone: '', address: '', notes: '', postcode: '', ...savedDetails(), name: '', phone: '', address: '', notes: '', postcode: '', ...savedDetails(),
where: areas.length ? 'area' : 'postcode', areaId: '', when: 'asap', where: ways[0], areaId: '', when: 'asap', pin: null,
})) }))
const [locating, setLocating] = useState(null) // null | 'busy' | 'failed'
const [slots, setSlots] = useState(menu.ordering ?? { slots: [], asap: false, timezone: 'Europe/Athens' }) const [slots, setSlots] = useState(menu.ordering ?? { slots: [], asap: false, timezone: 'Europe/Athens' })
const [priced, setPriced] = useState({ quote: null, problem: null, pending: true }) const [priced, setPriced] = useState({ quote: null, problem: null, pending: true })
const [tried, setTried] = useState(false) const [tried, setTried] = useState(false)
@@ -49,7 +55,7 @@ export default function Checkout({ site, service, booking, menu, lines, setCart,
// the cloud prices the order whenever what affects the price changes // the cloud prices the order whenever what affects the price changes
const quoteKey = JSON.stringify([itemsBody(lines).map(i => [i.product_id, i.quantity, i.options]), service, const quoteKey = JSON.stringify([itemsBody(lines).map(i => [i.product_id, i.quantity, i.options]), service,
service === 'delivery' ? [form.where, form.areaId, form.postcode.trim()] : null]) service === 'delivery' ? [form.where, form.areaId, form.postcode.trim(), form.pin] : null])
useEffect(() => { useEffect(() => {
const mine = ++seq.current const mine = ++seq.current
if (!lines.length) { setPriced({ quote: null, problem: null, pending: false }); return undefined } if (!lines.length) { setPriced({ quote: null, problem: null, pending: false }); return undefined }
@@ -57,7 +63,7 @@ export default function Checkout({ site, service, booking, menu, lines, setCart,
const id = setTimeout(async () => { const id = setTimeout(async () => {
const body = orderBody(form, service, lines, null) const body = orderBody(form, service, lines, null)
try { try {
const q = await quote(site, { order_type: quoteType, items: body.items, area_id: body.area_id, postcode: body.postcode }) const q = await quote(site, { order_type: quoteType, items: body.items, area_id: body.area_id, postcode: body.postcode, lat: body.lat, lng: body.lng })
if (mine === seq.current) setPriced({ quote: q, problem: null, pending: false }) if (mine === seq.current) setPriced({ quote: q, problem: null, pending: false })
} catch (err) { } catch (err) {
if (mine === seq.current) setPriced({ quote: null, problem: refusal(err), pending: false }) if (mine === seq.current) setPriced({ quote: null, problem: refusal(err), pending: false })
@@ -69,7 +75,7 @@ export default function Checkout({ site, service, booking, menu, lines, setCart,
const days = useMemo(() => slotDays(slots.slots ?? [], slots.timezone || 'Europe/Athens'), [slots]) const days = useMemo(() => slotDays(slots.slots ?? [], slots.timezone || 'Europe/Athens'), [slots])
const problems = book const problems = book
? bookingProblems(form, booking, menu.ordering?.reservations?.party_max) ? bookingProblems(form, booking, menu.ordering?.reservations?.party_max)
: checkoutProblems(form, service, { areas, asap: !!slots.asap, slots: slots.slots ?? [] }) : checkoutProblems(form, service, { areas: listed, asap: !!slots.asap, slots: slots.slots ?? [] })
const q = priced.quote const q = priced.quote
const canSend = book && !lines.length ? !sending : (q && !priced.pending && !priced.problem && !sending) const canSend = book && !lines.length ? !sending : (q && !priced.pending && !priced.problem && !sending)
const tz = menu.ordering?.timezone || 'Europe/Athens' const tz = menu.ordering?.timezone || 'Europe/Athens'
@@ -96,6 +102,14 @@ export default function Checkout({ site, service, booking, menu, lines, setCart,
} }
} }
const locate = () => {
if (!navigator.geolocation) { setLocating('failed'); return }
setLocating('busy')
navigator.geolocation.getCurrentPosition(
p => { set('pin', [Math.round(p.coords.latitude * 1e6) / 1e6, Math.round(p.coords.longitude * 1e6) / 1e6]); setLocating(null) },
() => setLocating('failed'), { enableHighAccuracy: true, timeout: 15000 })
}
const fieldErr = k => (tried && problems.includes(k) ? t(`problem.${k}`) : null) const fieldErr = k => (tried && problems.includes(k) ? t(`problem.${k}`) : null)
const input = 'w-full h-12 px-3.5 rounded-control bg-surface border border-line text-ink placeholder:text-ink-3' const input = 'w-full h-12 px-3.5 rounded-control bg-surface border border-line text-ink placeholder:text-ink-3'
@@ -144,21 +158,32 @@ export default function Checkout({ site, service, booking, menu, lines, setCart,
</Field> </Field>
{service === 'delivery' && ( {service === 'delivery' && (
<> <>
{areas.length > 0 && ( {ways.length > 1 && (
<div className="flex gap-2 text-sm" role="radiogroup" aria-label={t('area')}> <div className="flex flex-wrap gap-2 text-sm" role="radiogroup" aria-label={t('area')}>
{['area', 'postcode'].map(w => ( {ways.map(w => (
<button key={w} type="button" role="radio" aria-checked={form.where === w} onClick={() => set('where', w)} <button key={w} type="button" role="radio" aria-checked={form.where === w} onClick={() => set('where', w)} data-testid={`where-${w}`}
className={`px-3 h-9 rounded-full font-medium ${form.where === w ? 'bg-accent text-accent-fg' : 'bg-surface-2 text-ink-2'}`}> className={`px-3 h-9 rounded-full font-medium ${form.where === w ? 'bg-accent text-accent-fg' : 'bg-surface-2 text-ink-2'}`}>
{w === 'area' ? t('byArea') : t('byPostcode')} {w === 'map' ? t('byMap') : w === 'area' ? t('byArea') : t('byPostcode')}
</button> </button>
))} ))}
</div> </div>
)} )}
{form.where === 'area' && areas.length > 0 ? ( {form.where === 'map' && shapes.length > 0 ? (
<div className="grid gap-2">
<p className="text-sm text-ink-2">{t('pinHint')}</p>
<PinMap shapes={shapes} venue={menu.venue_point} value={form.pin} onChange={p => set('pin', p)} />
<button type="button" onClick={locate} disabled={locating === 'busy'} data-testid="locate"
className="justify-self-start px-3 h-10 rounded-full bg-surface-2 text-ink font-medium flex items-center gap-2">
<LocateFixed size={16} aria-hidden="true" />{locating === 'busy' ? t('locating') : t('myLocation')}
</button>
{locating === 'failed' && <p className="text-sm text-danger-ink" role="alert">{t('locationFailed')}</p>}
{fieldErr('pin') && <p className="text-sm text-danger-ink" role="alert">{fieldErr('pin')}</p>}
</div>
) : form.where === 'area' && listed.length > 0 ? (
<Field label={t('area')} error={fieldErr('area')}> <Field label={t('area')} error={fieldErr('area')}>
<select className={input} value={form.areaId} onChange={e => set('areaId', e.target.value)} data-testid="f-area"> <select className={input} value={form.areaId} onChange={e => set('areaId', e.target.value)} data-testid="f-area">
<option value="">{t('areaPick')}</option> <option value="">{t('areaPick')}</option>
{areas.map(a => <option key={a.id} value={a.id}>{a.name}</option>)} {listed.map(a => <option key={a.id} value={a.id}>{a.name}</option>)}
</select> </select>
</Field> </Field>
) : ( ) : (
@@ -0,0 +1,72 @@
// The customer pins the delivery address on a map (plan 6R.G): Leaflet on OpenStreetMap tiles
// (attribution shown). The venue's drawn areas show in the accent colour, its own place as a dot;
// a tap (or "Use my location") puts the pin, which the cloud uses to find the area and the fee.
import { useEffect, useRef } from 'react'
import L from 'leaflet'
import 'leaflet/dist/leaflet.css'
const TILE = 'https://tile.openstreetmap.org/{z}/{x}/{y}.png'
const ATTRIBUTION = '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
const rgb = name => `rgb(${getComputedStyle(document.documentElement).getPropertyValue(name).trim().split(/\s+/).join(',')})`
const pinIcon = () => L.divIcon({
className: '', iconSize: [28, 28], iconAnchor: [14, 28],
html: '<span style="display:block;width:28px;height:28px;border-radius:50% 50% 50% 0;transform:rotate(-45deg);background:rgb(var(--o-accent));border:3px solid rgb(var(--o-surface));box-shadow:0 2px 6px rgb(var(--o-shadow) / .5)"></span>',
})
const venueIcon = () => L.divIcon({
className: '', iconSize: [14, 14], iconAnchor: [7, 7],
html: '<span style="display:block;width:14px;height:14px;border-radius:50%;background:rgb(var(--o-danger-ink));border:2px solid rgb(var(--o-surface))"></span>',
})
function boundsOf(a) {
if (a.kind === 'polygon' && Array.isArray(a.geometry) && a.geometry.length) return L.latLngBounds(a.geometry)
if (a.kind === 'circle' && a.geometry?.center && a.geometry.radius_m > 0) {
const [lat, lng] = a.geometry.center
const dLat = a.geometry.radius_m / 111320
const dLng = a.geometry.radius_m / (111320 * Math.max(0.01, Math.cos(lat * Math.PI / 180)))
return L.latLngBounds([lat - dLat, lng - dLng], [lat + dLat, lng + dLng])
}
return null
}
export default function PinMap({ shapes = [], venue = null, value = null, onChange }) {
const box = useRef(null)
const map = useRef(null)
const marker = useRef(null)
const change = useRef(onChange)
useEffect(() => { change.current = onChange })
useEffect(() => {
const m = L.map(box.current, { zoomControl: true })
L.tileLayer(TILE, { maxZoom: 19, attribution: ATTRIBUTION }).addTo(m)
m.attributionControl.setPrefix('<a href="https://leafletjs.com">Leaflet</a>')
const accent = rgb('--o-accent')
for (const a of shapes) {
const style = { color: accent, weight: 2, fillOpacity: 0.12, interactive: false }
if (a.kind === 'polygon' && a.geometry?.length >= 3) L.polygon(a.geometry, style).addTo(m)
if (a.kind === 'circle' && a.geometry?.center) L.circle(a.geometry.center, { radius: a.geometry.radius_m, ...style }).addTo(m)
}
if (venue) L.marker([venue.lat, venue.lng], { icon: venueIcon(), interactive: false }).addTo(m)
const boxes = shapes.map(boundsOf).filter(Boolean)
if (value) m.setView(value, 16)
else if (boxes.length) m.fitBounds(boxes.reduce((all, b) => all.extend(b), L.latLngBounds(boxes[0].getSouthWest(), boxes[0].getNorthEast())).pad(0.1))
else if (venue) m.setView([venue.lat, venue.lng], 14)
else m.setView([38.3, 23.3], 7)
m.on('click', e => change.current?.([Math.round(e.latlng.lat * 1e6) / 1e6, Math.round(e.latlng.lng * 1e6) / 1e6]))
const ro = new ResizeObserver(() => m.invalidateSize())
ro.observe(box.current)
map.current = m
return () => { ro.disconnect(); m.remove(); map.current = null }
}, []) // eslint-disable-line react-hooks/exhaustive-deps
useEffect(() => {
const m = map.current
if (!m) return
if (marker.current) { marker.current.remove(); marker.current = null }
if (value) {
marker.current = L.marker(value, { icon: pinIcon(), interactive: false }).addTo(m)
if (!m.getBounds().contains(value)) m.setView(value, Math.max(m.getZoom(), 16))
}
}, [value])
return <div ref={box} className="w-full h-72 rounded-card border border-line overflow-hidden relative z-0" data-testid="pin-map" data-pinned={value ? 'true' : 'false'} />
}
@@ -101,3 +101,22 @@ test('a dish\'s allergens by level (6.3)', () => {
assert.deepEqual(allergensOf({ allergens: { sesame: 'may_contain', milk: 'contains', gluten: 'contains' } }), { contains: ['gluten', 'milk'], may_contain: ['sesame'] }) assert.deepEqual(allergensOf({ allergens: { sesame: 'may_contain', milk: 'contains', gluten: 'contains' } }), { contains: ['gluten', 'milk'], may_contain: ['sesame'] })
assert.deepEqual(allergensOf({ allergens: ['gluten'] }), { contains: [], may_contain: [] }) assert.deepEqual(allergensOf({ allergens: ['gluten'] }), { contains: [], may_contain: [] })
}) })
test('6R.G: where the delivery goes: a pin when the venue drew areas', async () => {
const { areaKinds, whereOptions } = await import('../src/logic.js')
const areas = [{ id: 1, name: 'Centre', kind: 'postcodes' }, { id: 2, name: 'Drawn', kind: 'polygon', geometry: [[37, 22], [37, 22.1], [37.1, 22]] },
{ id: 3, name: 'Ring', kind: 'circle', geometry: { center: [37, 22], radius_m: 900 } }, { id: 4, name: 'Old style' }]
assert.deepEqual(areaKinds(areas).listed.map(a => a.id), [1, 4])
assert.deepEqual(areaKinds(areas).shapes.map(a => a.id), [2, 3])
assert.deepEqual(whereOptions(areas), ['map', 'area', 'postcode'])
assert.deepEqual(whereOptions([areas[0]]), ['area', 'postcode'])
assert.deepEqual(whereOptions([]), ['postcode'])
const form = { name: 'Maria', phone: '6911111111', address: 'Harbour 7', notes: '', postcode: '', areaId: '', where: 'map', pin: null, when: 'asap' }
assert.deepEqual(checkoutProblems(form, 'delivery', { areas, asap: true }), ['pin'])
const pinned = { ...form, pin: [37.05, 22.05] }
assert.deepEqual(checkoutProblems(pinned, 'delivery', { areas, asap: true }), [])
const body = orderBody(pinned, 'delivery', [], null)
assert.deepEqual([body.lat, body.lng, body.area_id, body.postcode], [37.05, 22.05, null, null])
assert.deepEqual([orderBody(pinned, 'takeaway', [], null).lat, orderBody({ ...pinned, where: 'postcode' }, 'delivery', [], null).lng], [undefined, undefined])
})
+1 -1
View File
@@ -60,7 +60,7 @@ If the cloud is down, restaurants must keep taking orders (global Rule 8). Don't
**CL-10. Table QR tokens are the site's secret.** The cloud only receives their sha256 (`qr.tables[].token_hash`) and compares in constant time (`services/qr.py`). Never store or log a token the cloud receives, and never return `qr` from a public endpoint. **CL-10. Table QR tokens are the site's secret.** The cloud only receives their sha256 (`qr.tables[].token_hash`) and compares in constant time (`services/qr.py`). Never store or log a token the cloud receives, and never return `qr` from a public endpoint.
**CL-8. The fee engine has two copies.** `cloud_backend/services/fees.py` is byte-identical to the site's `local_backend/services/fees.py` (the cloud charges what the manager's "test an order" shows). Change both, and `tests/fixtures/fee_cases.json` in both repos; the site's `tests/test_fees.py` compares them. **CL-8. The fee engine has two copies.** (6R.G: areas drawn on a map are matched by the customer's pin `lat` / `lng`: `price_cart(pin=)`, `online_orders.lat` / `lng` (Alembic 0007), the order app's `PinMap.jsx` on Leaflet + OpenStreetMap tiles.) `cloud_backend/services/fees.py` is byte-identical to the site's `local_backend/services/fees.py` (the cloud charges what the manager's "test an order" shows). Change both, and `tests/fixtures/fee_cases.json` in both repos; the site's `tests/test_fees.py` compares them.
**CL-5. Frontend URLs are baked in at build time.** **CL-5. Frontend URLs are baked in at build time.**
`VITE_CLOUD_URL` is a build arg, so changing it means rebuilding the image, not restarting it. `VITE_CLOUD_URL` is a build arg, so changing it means rebuilding the image, not restarting it.