diff --git a/docs/README.md b/docs/README.md index eff18d6..6b5c20c 100644 --- a/docs/README.md +++ b/docs/README.md @@ -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 | diff --git a/local_backend/migrations/versions/0053_delivery_shapes.py b/local_backend/migrations/versions/0053_delivery_shapes.py new file mode 100644 index 0000000..d2a295e --- /dev/null +++ b/local_backend/migrations/versions/0053_delivery_shapes.py @@ -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') diff --git a/local_backend/models/fees.py b/local_backend/models/fees.py index 3aeb67e..428b7cf 100644 --- a/local_backend/models/fees.py +++ b/local_backend/models/fees.py @@ -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) diff --git a/local_backend/models/order.py b/local_backend/models/order.py index 48ea8ce..9e92f59 100644 --- a/local_backend/models/order.py +++ b/local_backend/models/order.py @@ -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) diff --git a/local_backend/routers/connect_orders.py b/local_backend/routers/connect_orders.py index 77f9ae5..b204339 100644 --- a/local_backend/routers/connect_orders.py +++ b/local_backend/routers/connect_orders.py @@ -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), diff --git a/local_backend/routers/fees.py b/local_backend/routers/fees.py index ba3003e..13f44ff 100644 --- a/local_backend/routers/fees.py +++ b/local_backend/routers/fees.py @@ -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} diff --git a/local_backend/services/cloud_sync.py b/local_backend/services/cloud_sync.py index 80745da..5c5f1f1 100644 --- a/local_backend/services/cloud_sync.py +++ b/local_backend/services/cloud_sync.py @@ -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")), ) diff --git a/local_backend/services/fees.py b/local_backend/services/fees.py index c58fbe6..8539fe3 100644 --- a/local_backend/services/fees.py +++ b/local_backend/services/fees.py @@ -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" diff --git a/local_backend/services/online_check.py b/local_backend/services/online_check.py index 39bda06..80b7db4 100644 --- a/local_backend/services/online_check.py +++ b/local_backend/services/online_check.py @@ -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"} diff --git a/local_backend/tests/fixtures/fee_cases.json b/local_backend/tests/fixtures/fee_cases.json index 50ecd1c..5a25a74 100644 --- a/local_backend/tests/fixtures/fee_cases.json +++ b/local_backend/tests/fixtures/fee_cases.json @@ -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}} ] } diff --git a/local_backend/tests/test_fees.py b/local_backend/tests/test_fees.py index 44054b7..a09c748 100644 --- a/local_backend/tests/test_fees.py +++ b/local_backend/tests/test_fees.py @@ -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 diff --git a/local_backend/tests/test_online_site_side.py b/local_backend/tests/test_online_site_side.py index d399804..a83da48 100644 --- a/local_backend/tests/test_online_site_side.py +++ b/local_backend/tests/test_online_site_side.py @@ -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 diff --git a/manager_dashboard/package.json b/manager_dashboard/package.json index a024e4c..e53895d 100644 --- a/manager_dashboard/package.json +++ b/manager_dashboard/package.json @@ -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", diff --git a/manager_dashboard/src/pages/online/DeliveryMap.jsx b/manager_dashboard/src/pages/online/DeliveryMap.jsx new file mode 100644 index 0000000..21d4d51 --- /dev/null +++ b/manager_dashboard/src/pages/online/DeliveryMap.jsx @@ -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 = '© OpenStreetMap 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: ``, +}) + +const pin = (colour, label = '') => L.divIcon({ + className: '', + iconSize: [26, 26], + iconAnchor: [13, 26], + html: `${label}`, +}) + +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('Leaflet') + 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 ( +
+ ) +} + +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 +} diff --git a/manager_dashboard/src/pages/online/FeesPage.jsx b/manager_dashboard/src/pages/online/FeesPage.jsx index 50ff6aa..1361051 100644 --- a/manager_dashboard/src/pages/online/FeesPage.jsx +++ b/manager_dashboard/src/pages/online/FeesPage.jsx @@ -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() { ))} ))} + {section === 'areas' && ( +