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>
99 lines
4.8 KiB
Python
99 lines
4.8 KiB
Python
"""The site checks the cloud's prices when it pulls an online order (plan phase 3S, step S.5).
|
|
|
|
The cloud prices online orders from the menu the site last pushed (S.2), so its prices may be
|
|
up to one push old (a change pushes about 5 s later; the 5-minute push is the fallback). The
|
|
customer was promised the cloud's prices and is charged them; this check only tells the venue
|
|
when the site's own engine says something else, so nobody is surprised at the counter.
|
|
|
|
diff(db, cloud_order, sales_point) -> None (all matched) | {
|
|
"lines": [{product_id, name, quantity, cloud, site, reason}], reason: price | not_sold | option
|
|
"fee": {cloud, site, reason} | None, reason: price | area | minimum
|
|
"cloud_total", "site_total"}
|
|
|
|
Each line is priced as the snapshot prices it (services/cloud_sync.menu_snapshot): the product
|
|
on its own at the order's sales point, plus its quick options, at the time the customer
|
|
ordered. The fee goes through the same engine (services/fees.py) with the site's rules, the
|
|
area the cloud matched (by id) and the order's time at the venue.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
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")
|
|
if isinstance(raw, str):
|
|
try:
|
|
when = datetime.fromisoformat(raw.replace("Z", "+00:00"))
|
|
if when.tzinfo is not None:
|
|
return when
|
|
except ValueError:
|
|
pass
|
|
return utcnow()
|
|
|
|
|
|
def diff(db, cloud_order: dict, sales_point: str) -> dict | None:
|
|
import json
|
|
from core import sales_points
|
|
from core.timeutil import to_venue
|
|
from models.product import Product
|
|
from routers.fees import fees_payload
|
|
from services import fees
|
|
from services.pos_cart import unit_prices
|
|
|
|
when = _when(cloud_order)
|
|
lines, site_subtotal = [], 0.0
|
|
items = json.loads(cloud_order.get("items_json") or "[]")
|
|
for item in items:
|
|
qty = item.get("quantity", 1) or 1
|
|
cloud = round(float(item.get("unit_price") or 0.0), 2)
|
|
entry = {"product_id": item.get("product_id"), "name": item.get("name"), "quantity": qty, "cloud": cloud}
|
|
product = db.get(Product, item.get("product_id")) if isinstance(item.get("product_id"), int) else None
|
|
if product is None or product.lifecycle_status != "active" or not sales_points.is_sold_at(product, sales_point):
|
|
lines.append({**entry, "site": None, "reason": "not_sold"})
|
|
site_subtotal += cloud * qty
|
|
continue
|
|
quick = {q.id: q for q in product.quick_options}
|
|
chosen = [o.get("id") if isinstance(o, dict) else o for o in item.get("options") or []]
|
|
if any(oid not in quick for oid in chosen):
|
|
lines.append({**entry, "site": None, "reason": "option"})
|
|
site_subtotal += cloud * qty
|
|
continue
|
|
site = round(unit_prices(db, [product], sales_point, now=when)[0] + sum(quick[o].price or 0.0 for o in chosen), 2)
|
|
site_subtotal += site * qty
|
|
if abs(site - cloud) > EPS:
|
|
lines.append({**entry, "site": site, "reason": "price"})
|
|
|
|
fee = None
|
|
cloud_fee = round(float(cloud_order.get("delivery_fee") or 0.0), 2)
|
|
if sales_point == sales_points.ONLINE_DELIVERY or cloud_fee:
|
|
data = fees_payload(db)
|
|
local = to_venue(when)
|
|
result = fees.compute(data["rules"], data["areas"], sales_point=sales_point,
|
|
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"),
|
|
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"}
|
|
elif abs(result["fee"] - cloud_fee) > EPS:
|
|
fee = {"cloud": cloud_fee, "site": result["fee"], "reason": "price"}
|
|
if not lines and fee is None:
|
|
return None
|
|
site_fee = fee["site"] if fee and fee["site"] is not None else cloud_fee
|
|
return {"lines": lines, "fee": fee,
|
|
"cloud_total": round(float(cloud_order.get("total") or 0.0), 2),
|
|
"site_total": round(site_subtotal + site_fee, 2)}
|