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:
2026-11-23 21:55:36 +02:00
co-authored by Claude Opus 5.5
parent 0840247768
commit 6f42e00684
25 changed files with 844 additions and 40 deletions
+1 -1
View File
@@ -45,7 +45,7 @@ The manager calls the API **same-origin, with relative paths**. The waiter app r
| `local_backend/services/price_changes.py` | Prices changed by hand (6F.3): the venue switch `orders.price_change`, the keys, the reason, and one `PriceEventLog` row `manual_price` per change (stage cart / sent / served, approver) |
| `local_backend/services/business_days.py`, `services/day_auto.py` | The one way to open / close the business day (the manager's buttons and the automatic loop, 6F.8). `day_auto` runs every minute from `main.py`'s lifespan: opening hours / a time / alert, closes only with no unclosed order (retry every 15 min), sticky alerts (`notifications.resolved_at`, `core.notifications.resolve`). Tests drive `tick(db, now=…)` with a fake clock |
| `local_backend/core/sessions.py` | Sessions and sign-in rules; 6F.7: `auth.single_session_waiter` `ask` (the default; `auth.session_elsewhere`, `replace: true`), only the `waiter` client counts; `terminal_requires_username` (venue + `devices.require_username`) |
| `local_backend/services/fees.py` | Delivery fee engine (phase 3S). **Byte-identical copy in `cloud-service/cloud_backend/services/fees.py`**: change both, and `tests/fixtures/fee_cases.json` in both; `tests/test_fees.py` fails if they differ |
| `local_backend/services/fees.py` | Delivery fee engine (phase 3S). **Byte-identical copy in `cloud-service/cloud_backend/services/fees.py`**: change both, and `tests/fixtures/fee_cases.json` in both; `tests/test_fees.py` fails if they differ. **6R.G:** areas are `postcodes` \| `polygon` \| `circle` (`delivery_areas.kind` / `geometry`, Alembic 0053); a shape is matched only by the customer's pin (`point`); the venue's place is the setting `venue.location` (`routers/fees.py` `venue_point`, sent as `fees.venue_point`); the manager's map is `pages/online/DeliveryMap.jsx` (Leaflet + OpenStreetMap tiles, internet needed for the tiles only); pulled orders keep the pin (`orders.online_lat` / `online_lng`) |
| `local_backend/services/sales.py`, `services/csv_export.py` | **How every report counts sales** (6.12a, 6.13c): sold = active, paid and tabbed lines (a tab line is sold, not paid), each net of what was refunded of it, system lines (the delivery fee) apart as fees; `Totals.on_tab`. **Split bills (6F.6), the settlement-line rule:** the lines settled by a split have status `split` and **are the sale** (products, categories, costs, the waiter); the split's **part lines** (`split_part` system lines) are **the money** (shift cash / card, payment methods, tabs, the day's takings) and never a product. Anything that picks lines by status uses `split_bills.sold_filter()` / `counts_as_sale()`; money paths keep reading `paid` lines. A refunded part comes off the settled lines by its share (`_split_refunds`). Every analytics endpoint, printed report and export uses it. Exports: UTF-8 mark, venue time with the zone in the header, `;` and decimal commas for a Greek venue |
| `local_backend/services/tab_books.py` | **Tabs in the books** (6.13c, owner rule "every movement recorded"): a line put on a tab and a tab payment record the business day and the shift of whoever did it; `for_shift` / `for_day`. A shift's drawer adds the tab cash it received; money taken by someone with no shift is theirs, in the day, in no drawer |
| `local_backend/services/refunds.py` | Refunds: their own records (`models/refund.py`), never edits of the paid items; shift / day totals subtract them |
@@ -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')
+4 -1
View File
@@ -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)
+2
View File
@@ -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)
+2
View File
@@ -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),
+87 -5
View File
@@ -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}
+3
View File
@@ -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")),
)
+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).
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"
+9 -1
View File
@@ -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
View File
@@ -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}}
]
}
+53
View File
@@ -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
+1
View File
@@ -20,6 +20,7 @@
"@xenia/signage": "^0.0.0",
"@xenia/ui": "^0.0.0",
"axios": "^1.21.1",
"leaflet": "^1.9.4",
"lucide-react": "^1.73.0",
"qrcode.react": "^4.2.0",
"react": "^19.3.1",
@@ -0,0 +1,147 @@
// A map of where the venue delivers (plan 6R.G, owner 2026-11-20): Leaflet on OpenStreetMap tiles
// (attribution shown, as their tile policy asks; the manager needs the internet for the tiles only).
// mode 'polygon' value [[lat, lng], …] tap the map: a corner is added; drag a corner: it moves;
// tap a corner: it is removed
// mode 'circle' value {center, radius_m} tap the map or drag the pin: the centre moves (the radius
// is typed beside the map)
// mode 'point' value [lat, lng] | null tap the map: the point (the venue's place, a test order)
// mode 'view' nothing to edit every area drawn, the venue's pin
// `areas`: the venue's areas, drawn faintly (the one being edited left out by `skipId`); `venue`
// {lat, lng} | null: its pin, and where the map starts (else the areas, else Greece).
// Colours are the tokens (the pins' HTML uses them as variables; the SVG shapes read their values).
import { useEffect, useRef } from 'react'
import L from 'leaflet'
import 'leaflet/dist/leaflet.css'
const GREECE = [38.3, 23.3]
const TILE = 'https://tile.openstreetmap.org/{z}/{x}/{y}.png'
const ATTRIBUTION = '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
// a token's value: SVG paths take colours as attributes, where CSS variables don't work
const token = name => getComputedStyle(document.documentElement).getPropertyValue(name).trim()
const dot = (colour, size = 14, square = false) => L.divIcon({
className: '',
iconSize: [size, size],
iconAnchor: [size / 2, size / 2],
html: `<span style="display:block;width:${size}px;height:${size}px;border-radius:${square ? '3px' : '50%'};background:${colour};border:2px solid var(--x-on-colour);box-shadow:0 1px 4px rgb(var(--x-scrim-rgb) / .45)"></span>`,
})
const pin = (colour, label = '') => L.divIcon({
className: '',
iconSize: [26, 26],
iconAnchor: [13, 26],
html: `<span style="display:flex;align-items:center;justify-content:center;width:26px;height:26px;border-radius:50% 50% 50% 0;transform:rotate(-45deg);background:${colour};border:2px solid var(--x-on-colour);box-shadow:0 1px 4px rgb(var(--x-scrim-rgb) / .45)"><span style="transform:rotate(45deg);color:var(--x-on-colour);font:700 11px/1 system-ui">${label}</span></span>`,
})
function drawArea(a, style) {
if (a.kind === 'polygon' && Array.isArray(a.geometry) && a.geometry.length >= 3) return L.polygon(a.geometry, style)
if (a.kind === 'circle' && a.geometry?.center) return L.circle(a.geometry.center, { radius: a.geometry.radius_m, ...style })
return null
}
export default function DeliveryMap({ mode = 'view', value = null, onChange, areas = [], skipId = null, venue = null, height = 360, testId = 'delivery-map' }) {
const box = useRef(null)
const map = useRef(null)
const others = useRef(null)
const edit = useRef(null)
const latest = useRef({ mode, value, onChange })
useEffect(() => { latest.current = { mode, value, onChange } }) // the map's click handler reads the newest
// the map, once
useEffect(() => {
const m = L.map(box.current, { zoomControl: true, attributionControl: true })
L.tileLayer(TILE, { maxZoom: 19, attribution: ATTRIBUTION }).addTo(m)
m.attributionControl.setPrefix('<a href="https://leafletjs.com">Leaflet</a>')
others.current = L.layerGroup().addTo(m)
edit.current = L.layerGroup().addTo(m)
m.on('click', e => {
const { mode: md, value: v, onChange: change } = latest.current
const p = [round(e.latlng.lat), round(e.latlng.lng)]
if (md === 'polygon') change?.([...(v || []), p])
else if (md === 'circle') change?.({ ...(v || { radius_m: 1000 }), center: p })
else if (md === 'point') change?.(p)
})
map.current = m
// fit what there is to see: the edited shape, else the areas, else the venue, else Greece
// (bounds worked out here: a circle's own bounds need a map that already has a view)
const boxes = [mode === 'polygon' ? boundsOf({ kind: 'polygon', geometry: value }) : null,
mode === 'circle' ? boundsOf({ kind: 'circle', geometry: value }) : null,
...areas.map(boundsOf)].filter(Boolean)
if (boxes.length) {
m.fitBounds(boxes.reduce((all, b) => all.extend(b), L.latLngBounds(boxes[0].getSouthWest(), boxes[0].getNorthEast())).pad(0.15))
} else if (mode === 'point' && value) {
m.setView(value, 15)
} else if (venue) {
m.setView([venue.lat, venue.lng], 14)
} else {
m.setView(GREECE, 7)
}
// the dialog may still be opening: size the map once it is laid out
const ro = new ResizeObserver(() => m.invalidateSize())
ro.observe(box.current)
return () => { ro.disconnect(); m.remove(); map.current = null }
}, []) // eslint-disable-line react-hooks/exhaustive-deps
// the other areas and the venue's pin
useEffect(() => {
const g = others.current
if (!g) return
g.clearLayers()
const faint = token('--x-info')
for (const a of areas) {
if (a.id === skipId || !a.is_active) continue
const layer = drawArea(a, { color: faint, weight: 1.5, fillOpacity: 0.08, interactive: mode === 'view' })
if (layer) layer.bindTooltip(a.name).addTo(g)
}
if (venue && mode !== 'point') L.marker([venue.lat, venue.lng], { icon: pin('var(--x-danger)'), interactive: false }).addTo(g)
}, [areas, skipId, venue, mode])
// what is being edited
useEffect(() => {
const g = edit.current
if (!g) return
g.clearLayers()
const accent = token('--x-accent')
if (mode === 'polygon') {
const corners = value || []
if (corners.length >= 2) L.polygon(corners, { color: accent, weight: 2.5, fillOpacity: 0.2, interactive: false }).addTo(g)
corners.forEach((c, i) => {
const mk = L.marker(c, { icon: dot('var(--x-accent)', 14, true), draggable: true, bubblingMouseEvents: false, keyboard: false })
mk.on('dragend', e => {
const ll = e.target.getLatLng()
onChange?.(corners.map((x, j) => (j === i ? [round(ll.lat), round(ll.lng)] : x)))
})
mk.on('click', () => onChange?.(corners.filter((_, j) => j !== i)))
mk.addTo(g)
})
} else if (mode === 'circle' && value?.center) {
L.circle(value.center, { radius: value.radius_m || 0, color: accent, weight: 2.5, fillOpacity: 0.2, interactive: false }).addTo(g)
const mk = L.marker(value.center, { icon: dot('var(--x-accent)', 16), draggable: true, bubblingMouseEvents: false, keyboard: false })
mk.on('dragend', e => { const ll = e.target.getLatLng(); onChange?.({ ...value, center: [round(ll.lat), round(ll.lng)] }) })
mk.addTo(g)
} else if (mode === 'point' && value) {
L.marker(value, { icon: pin('var(--x-accent)'), interactive: false }).addTo(g)
}
}, [mode, value, onChange])
const count = mode === 'polygon' ? (value || []).length : mode === 'circle' ? (value?.center ? 1 : 0) : (value ? 1 : 0)
return (
<div ref={box} className="w-full rounded-control border border-line overflow-hidden z-0 relative"
style={{ height }} data-testid={testId} data-mode={mode} data-count={count} />
)
}
function round(x) { return Math.round(x * 1e6) / 1e6 }
/** The box around an area's shape, without a map: a polygon's corners, a circle's centre ± radius. */
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
}
+99 -14
View File
@@ -6,6 +6,8 @@
// products, free) or refuses the order below a minimum; "stop here" makes the first match
// win. The cloud applies the same rules at checkout (the same engine), so "Test an order"
// shows exactly what a customer will be charged. No rules = no fee.
// 6R.G: an area is a list of postcodes, a shape drawn on the map or a circle (DeliveryMap, Leaflet +
// OpenStreetMap); the venue's own place on the map is set once here; "Test an order" by a point.
import { useCallback, useEffect, useMemo, useState } from 'react'
import { useSearchParams } from 'react-router-dom'
import toast from 'react-hot-toast'
@@ -13,12 +15,13 @@ import { ArrowDown, ArrowUp, MapPin, Pencil, Plus, Trash2, Truck } from 'lucide-
import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n'
import { SALES_POINTS } from '@xenia/access'
import { Button, Dialog, EmptyState, Field, IconButton, Input, Select, Spinner, Switch, Tabs } from '@xenia/ui'
import { Button, Dialog, EmptyState, Field, IconButton, Input, NumberInput, Segmented, Select, Spinner, Switch, Tabs } from '@xenia/ui'
import client from '../../api/client'
import FeeProductCard from './FeeProductCard'
import OrderingLink from './OrderingLink'
import OrderingSettings from './OrderingSettings'
import { ACTIONS, DAYS, describeRule, emptyRule, moveRule, parsePostcodes, previewBody, ruleBody, ruleProblems, ruleToForm } from './feesLogic'
import { ACTIONS, AREA_KINDS, DAYS, RADIUS_MAX, RADIUS_MIN, areaBody, areaProblem, describeRule, distanceText, emptyRule, moveRule, previewBody, ruleBody, ruleProblems, ruleToForm } from './feesLogic'
import DeliveryMap from './DeliveryMap'
const chip = on => `px-3 min-h-[var(--x-control-sm)] rounded-full text-label font-medium transition-colors duration-fast
${on ? 'bg-accent text-accent-fg' : 'bg-surface-2 text-ink-2 hover:bg-surface-3'}`
@@ -95,6 +98,22 @@ export default function FeesPage() {
))}
</ol>
))}
{section === 'areas' && (
<div className="grid gap-3 mb-3">
<div className="flex items-center gap-3 px-card py-card-y rounded-card border border-line bg-surface-2" data-testid="venue-point">
<MapPin size={16} className="text-danger-ink shrink-0" aria-hidden="true" />
<span className="flex-1 min-w-0 text-body text-ink">
{data.venue_point ? t('fees.venueSet') : t('fees.venueNotSet')}
</span>
<Button size="sm" variant="secondary" onClick={() => setDialog({ kind: 'venue' })} data-testid="venue-edit">
{data.venue_point ? t('fees.venueMove') : t('fees.venueSetButton')}
</Button>
</div>
{(data.venue_point || data.areas.some(a => a.kind !== 'postcodes')) && (
<DeliveryMap mode="view" areas={data.areas} venue={data.venue_point} height={320} testId="areas-map" />
)}
</div>
)}
{section === 'areas' && (data.areas.length === 0 ? (
<EmptyState icon={<MapPin size={28} />} title={t('fees.noAreas')} />
) : (
@@ -104,7 +123,11 @@ export default function FeesPage() {
<MapPin size={16} className="text-ink-3 shrink-0" aria-hidden="true" />
<span className="flex-1 min-w-0">
<span className={`block text-body font-medium ${a.is_active ? 'text-ink' : 'text-ink-3 line-through'}`}>{a.name}</span>
<span className="block text-caption text-ink-2 truncate">{a.postcodes.length ? a.postcodes.join(', ') : t('fees.byNameOnly')}</span>
<span className="block text-caption text-ink-2 truncate">
{a.kind === 'polygon' ? t('fees.areaDrawn', { count: a.geometry?.length ?? 0 })
: a.kind === 'circle' ? t('fees.areaCircle', { distance: distanceText(a.geometry?.radius_m) })
: a.postcodes.length ? a.postcodes.join(', ') : t('fees.byNameOnly')}
</span>
</span>
<span className="flex gap-1.5">
<IconButton size="sm" variant="ghost" tone="accent" label={t('fees.edit')} onClick={() => setDialog({ kind: 'area', item: a })}><Pencil size={16} /></IconButton>
@@ -119,14 +142,18 @@ export default function FeesPage() {
: <EmptyState title={t('fees.noSettings')} />)}
</div>
</section>
<TestOrder areas={data.areas} />
<TestOrder areas={data.areas} venue={data.venue_point} />
</div>
{dialog?.kind === 'area' && (
<AreaDialog area={dialog.item} onClose={() => setDialog(null)}
<AreaDialog area={dialog.item} areas={data.areas} venue={data.venue_point} onClose={() => setDialog(null)}
onSave={body => act(() => (dialog.item ? client.put(`/api/connect/fees/areas/${dialog.item.id}`, body) : client.post('/api/connect/fees/areas', body)),
t('fees.saved')).then(ok => ok && setDialog(null))} />
)}
{dialog?.kind === 'venue' && (
<VenuePointDialog venue={data.venue_point} areas={data.areas} onClose={() => setDialog(null)}
onSave={body => act(() => client.put('/api/connect/fees/venue-point', body), t('fees.saved')).then(ok => ok && setDialog(null))} />
)}
{dialog?.kind === 'rule' && (
<RuleDialog rule={dialog.item} areas={data.areas} onClose={() => setDialog(null)}
onSave={body => act(() => (dialog.item ? client.put(`/api/connect/fees/rules/${dialog.item.id}`, body) : client.post('/api/connect/fees/rules', body)),
@@ -184,32 +211,87 @@ function RuleRow({ rule, n, areaNames, first, last, onMove, onToggle, onEdit, on
)
}
function AreaDialog({ area, onClose, onSave }) {
function AreaDialog({ area, areas, venue, onClose, onSave }) {
const { t } = useTranslation('manager')
const [name, setName] = useState(area?.name ?? '')
const [kind, setKind] = useState(area?.kind ?? 'postcodes')
const [codes, setCodes] = useState((area?.postcodes ?? []).join(', '))
const [corners, setCorners] = useState(area?.kind === 'polygon' ? area.geometry : [])
const [circle, setCircle] = useState(area?.kind === 'circle' ? area.geometry
: { center: venue ? [venue.lat, venue.lng] : null, radius_m: 2000 })
const [active, setActive] = useState(area?.is_active ?? true)
const [busy, setBusy] = useState(false)
const save = async () => { setBusy(true); await onSave({ name: name.trim(), postcodes: parsePostcodes(codes), is_active: active }); setBusy(false) }
const form = { name, kind, codes, corners, circle, active }
const problem = areaProblem(form)
const save = async () => { setBusy(true); await onSave(areaBody(form)); setBusy(false) }
return (
<Dialog open size="sm" title={area ? t('fees.editArea') : t('fees.addArea')} onClose={busy ? undefined : onClose}
<Dialog open size={kind === 'postcodes' ? 'sm' : 'lg'} title={area ? t('fees.editArea') : t('fees.addArea')} onClose={busy ? undefined : onClose}
footer={<>
<Button variant="secondary" onClick={onClose} disabled={busy}>{t('fees.cancel')}</Button>
<Button onClick={save} loading={busy} disabled={!name.trim()} data-testid="area-save">{t('fees.save')}</Button>
<Button onClick={save} loading={busy} disabled={!!problem} data-testid="area-save">{t('fees.save')}</Button>
</>}>
<div className="grid gap-3">
<Field label={t('fees.areaName')} hint={t('fees.areaNameHint')} required>
<Input value={name} onChange={e => setName(e.target.value)} maxLength={80} autoFocus data-testid="area-name" />
</Field>
<Field label={t('fees.postcodes')} hint={t('fees.postcodesHint')}>
<Input value={codes} onChange={e => setCodes(e.target.value)} data-testid="area-postcodes" />
<Field label={t('fees.areaKind')}>
<Segmented value={kind} onChange={setKind} options={AREA_KINDS.map(k => ({ value: k, label: t(`fees.kind.${k}`), testId: `area-kind-${k}` }))} />
</Field>
{kind === 'postcodes' && (
<Field label={t('fees.postcodes')} hint={t('fees.postcodesHint')}>
<Input value={codes} onChange={e => setCodes(e.target.value)} data-testid="area-postcodes" />
</Field>
)}
{kind === 'polygon' && (
<div className="grid gap-2">
<p className="text-label text-ink-2">{t('fees.drawHint')}</p>
<DeliveryMap mode="polygon" value={corners} onChange={setCorners} areas={areas} skipId={area?.id} venue={venue} height={420} />
<div className="flex items-center gap-3">
<span className="text-label text-ink-2 flex-1" data-testid="area-corners">{t('fees.corners', { count: corners.length })}</span>
<Button size="sm" variant="secondary" onClick={() => setCorners(c => c.slice(0, -1))} disabled={!corners.length}>{t('fees.undoCorner')}</Button>
<Button size="sm" variant="secondary" onClick={() => setCorners([])} disabled={!corners.length}>{t('fees.clearShape')}</Button>
</div>
</div>
)}
{kind === 'circle' && (
<div className="grid gap-2">
<p className="text-label text-ink-2">{t('fees.circleHint')}</p>
<DeliveryMap mode="circle" value={circle} onChange={setCircle} areas={areas} skipId={area?.id} venue={venue} height={420} />
<Field label={t('fees.radius')} hint={t('fees.radiusHint', { distance: distanceText(circle?.radius_m) })}>
<NumberInput value={circle?.radius_m ?? null} min={RADIUS_MIN} max={RADIUS_MAX} step={100} suffix="m"
onChange={v => setCircle(c => ({ ...c, radius_m: v }))} invalid={problem === 'radius'} data-testid="area-radius" />
</Field>
</div>
)}
{problem && problem !== 'name' && <p className="text-label text-warning-ink" data-testid="area-problem">{t(`fees.areaProblem.${problem}`)}</p>}
<Switch checked={active} onChange={setActive} label={t('fees.areaActive')} />
</div>
</Dialog>
)
}
function VenuePointDialog({ venue, areas, onClose, onSave }) {
const { t } = useTranslation('manager')
const [point, setPoint] = useState(venue ? [venue.lat, venue.lng] : null)
const [busy, setBusy] = useState(false)
const save = async p => { setBusy(true); await onSave(p ? { lat: p[0], lng: p[1] } : {}); setBusy(false) }
return (
<Dialog open size="lg" title={t('fees.venueOnMap')} onClose={busy ? undefined : onClose}
footer={<>
{venue && <Button variant="secondary" onClick={() => save(null)} disabled={busy}>{t('fees.venueClear')}</Button>}
<Button variant="secondary" onClick={onClose} disabled={busy}>{t('fees.cancel')}</Button>
<Button onClick={() => save(point)} loading={busy} disabled={!point} data-testid="venue-save">{t('fees.save')}</Button>
</>}>
<div className="grid gap-2">
<p className="text-label text-ink-2">{t('fees.venueHint')}</p>
<DeliveryMap mode="point" value={point} onChange={setPoint} areas={areas} venue={venue} height={420} testId="venue-map" />
</div>
</Dialog>
)
}
function RuleDialog({ rule, areas, onClose, onSave }) {
const { t } = useTranslation('manager')
const { t: tc } = useTranslation('common')
@@ -318,13 +400,13 @@ function RuleDialog({ rule, areas, onClose, onSave }) {
)
}
function TestOrder({ areas }) {
function TestOrder({ areas, venue }) {
const { t } = useTranslation('manager')
const { t: tc } = useTranslation('common')
const { formatMoney } = useFormat()
// where / area_id stay null until picked: they follow the areas as they're added or removed
const [picked, setForm] = useState({ sales_point: 'online_delivery', where: null, area_id: null,
postcode: '', subtotal: '15', items: '2', day: 'now', time: '' })
postcode: '', point: null, subtotal: '15', items: '2', day: 'now', time: '' })
const form = {
...picked,
where: picked.where ?? (areas.length ? 'area' : 'postcode'),
@@ -351,8 +433,11 @@ function TestOrder({ areas }) {
<Select value={form.where} onChange={e => set('where', e.target.value)} aria-label={t('fees.testWhere')}>
<option value="area">{t('fees.testByArea')}</option>
<option value="postcode">{t('fees.testByPostcode')}</option>
<option value="point">{t('fees.testByPoint')}</option>
</Select>
{form.where === 'area' ? (
{form.where === 'point' ? (
<DeliveryMap mode="point" value={form.point} onChange={p => set('point', p)} areas={areas} venue={venue} height={240} testId="test-map" />
) : form.where === 'area' ? (
<Select value={form.area_id} onChange={e => set('area_id', e.target.value)} aria-label={t('fees.areas')} data-testid="test-area">
<option value="">{t('fees.testNoArea')}</option>
{areas.map(a => <option key={a.id} value={a.id}>{a.name}</option>)}
@@ -98,6 +98,9 @@ export function previewBody(form) {
sales_point: form.sales_point,
area_id: form.where === 'area' && form.area_id !== '' ? Number(form.area_id) : null,
postcode: form.where === 'postcode' ? form.postcode.trim() || null : null,
// 6R.G: a point picked on the map
lat: form.where === 'point' && form.point ? form.point[0] : null,
lng: form.where === 'point' && form.point ? form.point[1] : null,
subtotal: num(form.subtotal) ?? 0, items: Math.max(0, Math.round(num(form.items) ?? 0)),
weekday: form.day === 'now' ? null : Number(form.day),
time: form.day === 'now' ? null : (form.time || null),
@@ -150,3 +153,32 @@ export function orderingBody(form) {
},
}
}
// ── 6R.G: areas drawn on a map ───────────────────────────────────────────────────────────
export const AREA_KINDS = ['postcodes', 'polygon', 'circle']
export const RADIUS_MIN = 50
export const RADIUS_MAX = 50000
/** The area dialog's form → the request body; `kind` decides which of the three is sent. */
export function areaBody({ name, kind = 'postcodes', codes = '', corners = [], circle = null, active = true }) {
const body = { name: String(name ?? '').trim(), kind, is_active: active, postcodes: [] }
if (kind === 'postcodes') body.postcodes = parsePostcodes(codes)
else if (kind === 'polygon') body.geometry = corners
else body.geometry = { center: circle?.center ?? null, radius_m: circle?.radius_m ?? null }
return body
}
/** What keeps the area from being saved: 'name' | 'corners' | 'centre' | 'radius' | null. */
export function areaProblem({ name, kind = 'postcodes', corners = [], circle = null }) {
if (!String(name ?? '').trim()) return 'name'
if (kind === 'polygon' && corners.length < 3) return 'corners'
if (kind === 'circle' && !circle?.center) return 'centre'
if (kind === 'circle' && !(circle?.radius_m >= RADIUS_MIN && circle.radius_m <= RADIUS_MAX)) return 'radius'
return null
}
/** A distance for people: "800 m", "2.5 km" (one decimal at most). */
export function distanceText(m) {
if (m == null || Number.isNaN(m)) return ''
return m < 1000 ? `${Math.round(m)} m` : `${Math.round(m / 100) / 10} km`
}
+25 -2
View File
@@ -45,9 +45,9 @@ test('moving rules and the test form', () => {
assert.deepEqual(moveRule(rules, 2, -1), [2, 1, 3])
assert.deepEqual(moveRule(rules, 3, 1), [1, 2, 3])
assert.deepEqual(previewBody({ sales_point: 'online_delivery', where: 'postcode', area_id: '1', postcode: ' 24131 ', subtotal: '12,5', items: '3', day: 'now', time: '' }),
{ sales_point: 'online_delivery', area_id: null, postcode: '24131', subtotal: 12.5, items: 3, weekday: null, time: null })
{ sales_point: 'online_delivery', area_id: null, postcode: '24131', lat: null, lng: null, subtotal: 12.5, items: 3, weekday: null, time: null })
assert.deepEqual(previewBody({ sales_point: 'online_delivery', where: 'area', area_id: '2', postcode: '', subtotal: '', items: '', day: '5', time: '23:30' }),
{ sales_point: 'online_delivery', area_id: 2, postcode: null, subtotal: 0, items: 0, weekday: 5, time: '23:30' })
{ sales_point: 'online_delivery', area_id: 2, postcode: null, lat: null, lng: null, subtotal: 0, items: 0, weekday: 5, time: '23:30' })
})
test('online ordering settings: hours per day, any time, numbers', async () => {
@@ -75,3 +75,26 @@ test('table bookings online: settings round trip (S.6)', async () => {
assert.deepEqual(orderingBody({ ...form, res: { ...form.res, anyTime: true, party_max: '' } }).reservations,
{ ...reservations, hours: {}, party_max: 10 })
})
test('6R.G: an area form for each kind, and what keeps it from saving', async () => {
const { areaBody, areaProblem, distanceText } = await import('../src/pages/online/feesLogic.js')
assert.deepEqual(areaBody({ name: ' Centre ', codes: '24100, 24131' }), { name: 'Centre', kind: 'postcodes', is_active: true, postcodes: ['24100', '24131'] })
const sq = [[37, 22], [37, 22.1], [37.1, 22.1]]
assert.deepEqual(areaBody({ name: 'Drawn', kind: 'polygon', corners: sq, codes: '1' }), { name: 'Drawn', kind: 'polygon', is_active: true, postcodes: [], geometry: sq })
assert.deepEqual(areaBody({ name: 'Ring', kind: 'circle', circle: { center: [37, 22], radius_m: 1500 }, active: false }).geometry, { center: [37, 22], radius_m: 1500 })
assert.equal(areaProblem({ name: ' ' }), 'name')
assert.equal(areaProblem({ name: 'x', kind: 'polygon', corners: sq.slice(0, 2) }), 'corners')
assert.equal(areaProblem({ name: 'x', kind: 'polygon', corners: sq }), null)
assert.equal(areaProblem({ name: 'x', kind: 'circle', circle: { radius_m: 500 } }), 'centre')
assert.equal(areaProblem({ name: 'x', kind: 'circle', circle: { center: [37, 22], radius_m: 20 } }), 'radius')
assert.equal(areaProblem({ name: 'x', kind: 'circle', circle: { center: [37, 22], radius_m: null } }), 'radius')
assert.equal(distanceText(800), '800 m')
assert.equal(distanceText(2549), '2.5 km')
})
test('6R.G: a test order by a point on the map', () => {
const body = previewBody({ sales_point: 'online_delivery', where: 'point', point: [37.05, 22.05], area_id: 3, postcode: '1', subtotal: '10', items: '1', day: 'now' })
assert.deepEqual([body.lat, body.lng, body.area_id, body.postcode], [37.05, 22.05, null, null])
const none = previewBody({ sales_point: 'online_delivery', where: 'area', area_id: '', postcode: '', subtotal: '10', items: '1', day: 'now' })
assert.deepEqual([none.lat, none.lng], [null, null])
})
+7
View File
@@ -25,6 +25,7 @@
"@xenia/signage": "^0.0.0",
"@xenia/ui": "^0.0.0",
"axios": "^1.21.1",
"leaflet": "^1.9.4",
"lucide-react": "^1.73.0",
"qrcode.react": "^4.2.0",
"react": "^19.3.1",
@@ -6278,6 +6279,12 @@
"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/leven": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/leven/-/leven-3.1.0.tgz",
+31 -1
View File
@@ -1047,7 +1047,37 @@
"refused": {
"minimum_not_met": "Απορρίπτεται: η ελάχιστη παραγγελία είναι {{minimum}}.",
"area_not_served": "Απορρίπτεται: δεν γίνεται διανομή σε αυτή τη διεύθυνση."
}
},
"areaKind": "Πού είναι",
"kind": {
"postcodes": "Ταχυδρομικοί κώδικες",
"polygon": "Σχέδιο στον χάρτη",
"circle": "Κύκλος γύρω από σημείο"
},
"drawHint": "Πατήστε στον χάρτη για να προσθέσετε γωνία. Σύρετε μια γωνία για να τη μετακινήσετε· πατήστε τη για να τη βγάλετε. Το σχήμα κλείνει μόνο του.",
"corners_one": "{{count}} γωνία",
"corners_other": "{{count}} γωνίες",
"undoCorner": "Αναίρεση τελευταίας γωνίας",
"clearShape": "Από την αρχή",
"circleHint": "Πατήστε στον χάρτη ή σύρετε την κουκκίδα για το κέντρο· γράψτε πόσο μακριά φτάνει.",
"radius": "Φτάνει μέχρι",
"radiusHint": "Μέτρα από το κέντρο ({{distance}})· 50 μ. έως 50 χλμ.",
"areaProblem": {
"corners": "Σχεδιάστε τουλάχιστον 3 γωνίες στον χάρτη.",
"centre": "Πατήστε στον χάρτη για το κέντρο του κύκλου.",
"radius": "Η απόσταση είναι από 50 μ. έως 50 χλμ."
},
"venueOnMap": "Το κατάστημα στον χάρτη",
"venueHint": "Πατήστε στον χάρτη εκεί που είναι το κατάστημα. Ο χάρτης των πελατών ξεκινά από εδώ και ένας νέος κύκλος σχεδιάζεται γύρω του.",
"venueClear": "Αφαίρεση της θέσης",
"venueSet": "Η θέση του καταστήματος στον χάρτη έχει οριστεί.",
"venueNotSet": "Η θέση του καταστήματος στον χάρτη δεν έχει οριστεί: ο χάρτης των πελατών ξεκινά τότε από τις περιοχές που σχεδιάζετε.",
"venueMove": "Μετακίνηση",
"venueSetButton": "Ορισμός στον χάρτη",
"areaDrawn_one": "Σχέδιο στον χάρτη · {{count}} γωνία",
"areaDrawn_other": "Σχέδιο στον χάρτη · {{count}} γωνίες",
"areaCircle": "Έως {{distance}} από ένα σημείο",
"testByPoint": "Σημείο στον χάρτη"
},
"ordering": {
"pageTitle": "Online παραγγελίες",
+2 -1
View File
@@ -375,7 +375,8 @@
"fee_area": "{{online}} online, η περιοχή δεν εξυπηρετείται πλέον",
"fee_minimum": "{{online}} online, κάτω από την ελάχιστη παραγγελία εδώ"
}
}
},
"pin": "Η καρφίτσα του πελάτη στον χάρτη"
},
"receipts": {
"scope": {
+31 -1
View File
@@ -1047,7 +1047,37 @@
"refused": {
"minimum_not_met": "Refused: the minimum order is {{minimum}}.",
"area_not_served": "Refused: no delivery to this address."
}
},
"areaKind": "Where it is",
"kind": {
"postcodes": "Postcodes",
"polygon": "Drawn on the map",
"circle": "Circle around a point"
},
"drawHint": "Tap the map to add a corner. Drag a corner to move it; tap a corner to remove it. The shape closes by itself.",
"corners_one": "{{count}} corner",
"corners_other": "{{count}} corners",
"undoCorner": "Undo the last corner",
"clearShape": "Start again",
"circleHint": "Tap the map or drag the dot to place the centre; type how far out it reaches.",
"radius": "Reaches out to",
"radiusHint": "Metres from the centre ({{distance}}); 50 m to 50 km.",
"areaProblem": {
"corners": "Draw at least 3 corners on the map.",
"centre": "Tap the map to place the circle's centre.",
"radius": "The distance is 50 m to 50 km."
},
"venueOnMap": "The venue on the map",
"venueHint": "Tap the map where the venue is. The customers' map starts here and a new circle is drawn around it.",
"venueClear": "Remove the venue's place",
"venueSet": "The venue's place on the map is set.",
"venueNotSet": "The venue's place on the map isn't set yet: the customers' map then starts at the areas you draw.",
"venueMove": "Move it",
"venueSetButton": "Set it on the map",
"areaDrawn_one": "Drawn on the map · {{count}} corner",
"areaDrawn_other": "Drawn on the map · {{count}} corners",
"areaCircle": "Within {{distance}} of a point",
"testByPoint": "A point on the map"
},
"ordering": {
"pageTitle": "Online ordering",
+2 -1
View File
@@ -375,7 +375,8 @@
"fee_area": "{{online}} online, the area isn't served here any more",
"fee_minimum": "{{online}} online, below the minimum here"
}
}
},
"pin": "The customer's pin on the map"
},
"receipts": {
"scope": {
+7
View File
@@ -78,6 +78,13 @@ export default function OnlinePanel({ order, onChanged }) {
<div className="text-body-lg font-semibold">{order.customer.name}</div>
{order.customer.phone && <Detail icon={Phone}>{order.customer.phone}</Detail>}
{order.customer.address && <Detail icon={MapPin}>{order.customer.address}{order.area ? ` · ${order.area}` : ''}</Detail>}
{/* 6R.G: the customer's pin, opened in a map (the driver's phone or the browser) */}
{order.pin && (
<a href={`https://www.openstreetmap.org/?mlat=${order.pin.lat}&mlon=${order.pin.lng}#map=18/${order.pin.lat}/${order.pin.lng}`}
target="_blank" rel="noreferrer" className="text-label text-accent-ink underline" data-testid="online-pin">
{t('pos.online.pin')}
</a>
)}
{order.customer.notes && (
<div className="p-2 rounded-control bg-warning-soft text-warning-ink flex gap-2">
<MessageSquare size={16} className="mt-0.5 shrink-0" aria-hidden="true" /><span>{order.customer.notes}</span>
+66
View File
@@ -578,6 +578,72 @@ try {
await page.getByTestId('test-run').click()
await page.waitForFunction(() => document.querySelector('[data-testid="test-result"]')?.dataset.refused, null, { timeout: 5000 }).catch(() => {})
r.check('fees: …a postcode outside the areas is refused', await page.getByTestId('test-result').getAttribute('data-refused') === 'area_not_served')
// ── 6R.G: the venue on the map, an area drawn on it, a circle, "test an order" by a point ──
{
await page.getByTestId('fees-tab-areas').click()
await page.getByTestId('venue-edit').click()
const vmap = page.getByTestId('venue-map')
await vmap.waitFor({ timeout: 5000 })
const vb = await vmap.boundingBox()
await vmap.click({ position: { x: vb.width / 2, y: vb.height / 2 } })
await page.getByTestId('venue-save').click()
let venuePoint = null
for (let i = 0; i < 30 && !venuePoint; i++) { venuePoint = (await api('GET', '/api/connect/fees', { token: boss })).venue_point; if (!venuePoint) await sleep(150) }
r.check('6R.G: the venue\'s place set by a tap on the map', !!venuePoint && Math.abs(venuePoint.lat) > 1, JSON.stringify(venuePoint))
// a shape: four taps, then a tap on the last corner takes it away
await page.getByTestId('area-add').click()
await page.getByTestId('area-name').fill('Drawn')
await page.getByTestId('area-kind-polygon').click()
const dmap = page.getByTestId('delivery-map')
await dmap.waitFor({ timeout: 5000 })
await sleep(500)
const db = await dmap.boundingBox()
const cx = db.width / 2, cy = db.height / 2
for (const [dx, dy] of [[-150, -100], [150, -100], [0, 120], [120, 110]]) {
await dmap.click({ position: { x: cx + dx, y: cy + dy } })
await sleep(150)
}
const four = await dmap.getAttribute('data-count')
await dmap.click({ position: { x: cx + 120, y: cy + 110 } }) // the 4th corner: removed
await sleep(200)
r.check('6R.G: corners added by taps on the map, one taken away by a tap on it', four === '4' && await dmap.getAttribute('data-count') === '3',
`${four} → ${await dmap.getAttribute('data-count')}`)
await page.screenshot({ path: path.join(OUT, 'manager-area-drawn.png') })
await page.getByTestId('area-save').click()
await page.getByTestId('area').filter({ hasText: 'Drawn' }).waitFor({ timeout: 5000 }).catch(() => {})
// a circle around the venue (its centre starts there), 1.5 km
await page.getByTestId('area-add').click()
await page.getByTestId('area-name').fill('Ring')
await page.getByTestId('area-kind-circle').click()
await page.screenshot({ path: path.join(OUT, 'manager-area-circle.png') })
await page.getByTestId('area-radius').fill('1500')
await page.getByTestId('area-save').click()
await page.getByTestId('area').filter({ hasText: 'Ring' }).waitFor({ timeout: 5000 }).catch(() => {})
const areasNow = (await api('GET', '/api/connect/fees', { token: boss })).areas
const drawnA = areasNow.find(a => a.name === 'Drawn'), ring = areasNow.find(a => a.name === 'Ring')
r.check('6R.G: saved as a shape with 3 corners and a 1.5 km circle around the venue',
drawnA?.kind === 'polygon' && drawnA.geometry.length === 3 && ring?.kind === 'circle' && ring.geometry.radius_m === 1500
&& ring.geometry.center[0] === venuePoint.lat && ring.geometry.center[1] === venuePoint.lng, JSON.stringify([drawnA, ring]))
r.check('6R.G: the list says what each area is', (await page.getByTestId('area').filter({ hasText: 'Drawn' }).textContent()).includes('3 corners')
&& (await page.getByTestId('area').filter({ hasText: 'Ring' }).textContent()).includes('1.5 km') && await page.getByTestId('areas-map').count() === 1)
// "test an order" by a point: the middle of the map is inside the drawn shape (the first shape wins)
await page.getByTestId('test-subtotal').fill('15')
await page.getByRole('combobox', { name: 'Where' }).selectOption('point')
const tmap = page.getByTestId('test-map')
await tmap.waitFor({ timeout: 5000 })
await sleep(500)
const tb = await tmap.boundingBox()
await tmap.click({ position: { x: tb.width / 2, y: tb.height / 2 } })
await page.getByTestId('test-run').click()
await page.waitForFunction(() => document.querySelector('[data-testid="test-result"]')?.textContent.includes('Drawn'), null, { timeout: 5000 }).catch(() => {})
const tr = page.getByTestId('test-result')
r.check('6R.G: "test an order" by a point on the map finds the drawn area and its fee', (await tr.textContent()).includes('Drawn')
&& await tr.getAttribute('data-refused') === '' && await tr.getAttribute('data-fee') === '2', await tr.textContent())
await page.screenshot({ path: path.join(OUT, 'manager-test-point.png') })
for (const a of [drawnA, ring]) if (a) await api('DELETE', `/api/connect/fees/areas/${a.id}`, { token: boss }).catch(() => {})
await page.reload()
await page.getByTestId('fees-page').waitFor({ timeout: 10_000 })
}
// S.5: the fee's line on the bill and the receipt (a system product, never in the catalogue)
await page.getByTestId('fees-tab-settings').click()
await page.getByTestId('fee-product-name').fill('Delivery')
+42
View File
@@ -208,6 +208,48 @@ try {
.then(() => true).catch(() => false) && (await page.getByTestId('track').textContent()).includes('Confirmed'))
await page.screenshot({ path: path.join(OUT, 'order-app-booking-track.png'), fullPage: true })
// ── 6R.G: the venue drew an area on the map: the customer pins the address ──
{
const shaped = { ...snapshot, fees: { ...snapshot.fees,
areas: [...snapshot.fees.areas, { id: 3, name: 'Harbour', kind: 'circle', postcodes: [], is_active: true, geometry: { center: [37.0, 22.0], radius_m: 3000 } }],
rules: [...snapshot.fees.rules, { id: 4, name: 'Harbour', area_ids: [3], action: 'add', value: 0.5, sales_points: ['online_delivery'] }],
venue_point: { lat: 37.0, lng: 22.0 } } }
await call('POST', '/api/menu/sync', { headers: siteH, body: { site_id: numeric, snapshot_json: JSON.stringify(shaped) } })
const ctx = await browser.newContext({ viewport: { width: 390, height: 844 }, locale: 'en-GB',
geolocation: { latitude: 37.004, longitude: 22.003 }, permissions: ['geolocation'] })
const pg = await ctx.newPage()
pg.on('pageerror', e => errors.push(e.message))
const prod = id => pg.locator(`[data-testid="product"][data-product="${id}"]`).first()
await pg.goto(`http://localhost:${APP_PORT}/order/${site.site_id}`)
await pg.getByTestId('service-delivery').click()
await prod(11).getByTestId('add').click()
await pg.getByTestId('extras-add').click()
await prod(12).getByTestId('add').click() // €7.00 of products
await pg.getByTestId('view-order').click()
const map = pg.getByTestId('pin-map')
r.check('6R.G: with an area drawn by the venue, the checkout opens on the map', await map.waitFor({ timeout: 8000 }).then(() => true).catch(() => false)
&& await pg.getByTestId('where-map').getAttribute('aria-checked') === 'true' && await pg.getByTestId('where-area').count() === 1)
await sleep(500)
const mb = await map.boundingBox()
await map.click({ position: { x: mb.width / 2, y: mb.height / 2 } }) // the middle of the venue's circle
await pg.waitForFunction(() => document.querySelector('[data-testid="totals"]')?.dataset.fee === '2.5', null, { timeout: 8000 }).catch(() => {})
r.check('6R.G: a tap on the map pins it; the cloud finds the area and its fee (€2.00 + €0.50)', await map.getAttribute('data-pinned') === 'true'
&& await pg.getByTestId('totals').getAttribute('data-fee') === '2.5' && (await pg.getByTestId('totals').textContent()).includes('Harbour'),
await pg.getByTestId('totals').textContent())
await pg.getByTestId('locate').click() // the browser's location (allowed here)
await sleep(800)
await pg.getByTestId('f-name').fill('Eleni')
await pg.getByTestId('f-phone').fill('6922222222')
await pg.getByTestId('f-address').fill('Harbour road 12')
await pg.screenshot({ path: path.join(OUT, 'order-app-pin.png'), fullPage: true })
await pg.getByTestId('place-order').click()
await pg.getByTestId('track').waitFor({ timeout: 10_000 }).catch(() => {})
const got = (await call('GET', `/api/orders/pending/${numeric}`, { headers: siteH })).find(o => o.customer_name === 'Eleni')
r.check('6R.G: placed with the pin from the browser\'s location; the site gets the area, the fee and the pin',
got?.delivery_area === 'Harbour' && got.delivery_fee === 2.5 && got.lat === 37.004 && got.lng === 22.003, JSON.stringify(got && { a: got.delivery_area, f: got.delivery_fee, lat: got.lat, lng: got.lng }))
await ctx.close()
}
// ── Greek ────────────────────────────────────────────────────────────────
await page.goto(`http://localhost:${APP_PORT}/order/${site.site_id}`)
await page.getByRole('button', { name: 'EL' }).click()