"""Delivery areas and fee rules (plan phase 3S, step S.3). Key: connect_orders.fees. 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 The rules and areas travel to the cloud with the menu snapshot (services/cloud_sync.py, contract C-2) and are applied there at checkout by the same engine (services/fees.py). Each change pushes the menu soon (main.py middleware). Rule semantics: services/fees.py. """ from __future__ import annotations import json import re from typing import List, Literal, Optional from fastapi import APIRouter, Depends from pydantic import BaseModel, Field, field_validator, model_validator from sqlalchemy.orm import Session from core import sales_points from core.access.deps import require from core.errors import XeniaError from database import get_db router = APIRouter() KEY = "connect_orders.fees" HHMM = re.compile(r"^([01]\d|2[0-3]):[0-5]\d$") SalesPoint = Literal["in_store", "in_store_takeaway", "qr_table", "online_takeaway", "online_delivery", "online_preorder"] # ── shapes ───────────────────────────────────────────────────────────────────── def area_out(a) -> dict: 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: return {"id": r.id, "name": r.name, "is_active": bool(r.is_active), "sort_order": r.sort_order, "sales_points": json.loads(r.sales_points or "[]"), "area_ids": json.loads(r.area_ids or "[]"), "subtotal_min": r.subtotal_min, "subtotal_max": r.subtotal_max, "items_min": r.items_min, "items_max": r.items_max, "days": json.loads(r.days or "[]"), "time_from": r.time_from, "time_to": r.time_to, "action": r.action, "value": r.value, "stop": bool(r.stop)} ORDERING_KEY = "connect_orders.ordering" SERVICES = ("takeaway", "delivery") def ordering_settings(db) -> dict: """Online ordering (S.4), with defaults: no services until the venue turns them on.""" from models.settings import PosSettings row = db.query(PosSettings).filter(PosSettings.key == ORDERING_KEY).first() try: raw = json.loads(row.value) if row and row.value else {} except ValueError: raw = {} try: return OrderingBody(**{k: v for k, v in raw.items() if k in OrderingBody.model_fields}).model_dump() except Exception: return OrderingBody().model_dump() def fees_payload(db) -> dict: """What the engine needs (and the cloud gets): active and inactive alike, in order.""" 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], "venue_point": venue_point(db)} # 6R.G: where the customer's map starts (the engine ignores it) def _clean_hours(v): out = {} for day, ranges in (v or {}).items(): if str(day) not in {str(d) for d in range(7)}: raise ValueError("hours are keyed 0 (Monday) to 6 (Sunday)") if not isinstance(ranges, list) or len(ranges) > 4: raise ValueError("at most 4 time ranges a day") clean = [] for r in ranges: if not (isinstance(r, (list, tuple)) and len(r) == 2 and all(isinstance(x, str) and HHMM.match(x) for x in r)) or r[0] == r[1]: raise ValueError("a time range is [\"HH:MM\", \"HH:MM\"], start and end different") clean.append([r[0], r[1]]) if clean: out[str(day)] = sorted(clean) return out class ReservationsBody(BaseModel): """Table bookings online (plan phase 3S, S.6): a table only, or with food ordered ahead (`with_food`). The cloud enforces hours, the time grid, notice, days ahead and party size; `fire_minutes` is the site's: the kitchen gets pre-ordered food that long before arrival.""" enabled: bool = False with_food: bool = False hours: dict = Field(default_factory=dict) # like OrderingBody.hours; none = any time slot_minutes: int = Field(default=30, ge=5, le=120) days_ahead: int = Field(default=30, ge=0, le=90) notice_minutes: int = Field(default=60, ge=0, le=7 * 24 * 60) # the earliest booking from now party_max: int = Field(default=10, ge=1, le=100) fire_minutes: int = Field(default=20, ge=0, le=240) @field_validator("hours") @classmethod def _hours(cls, v): return _clean_hours(v) class OrderingBody(BaseModel): """What the online ordering app offers and when (plan phase 3S, S.4). The cloud enforces it at checkout. hours: {"0".."6" (Mon..Sun): [["HH:MM", "HH:MM"], ...]}; no hours at all = any time; once any day has hours, a day without them is closed. An end before its start runs past midnight.""" services: List[Literal["takeaway", "delivery"]] = Field(default_factory=list) hours: dict = Field(default_factory=dict) prep_minutes: int = Field(default=20, ge=0, le=24 * 60) # earliest collection/delivery after ordering slot_minutes: int = Field(default=15, ge=5, le=120) # the times offered, every N minutes days_ahead: int = Field(default=0, ge=0, le=7) # 0 = today only asap: bool = True # "as soon as possible" offered while open reservations: ReservationsBody = Field(default_factory=ReservationsBody) # S.6 @field_validator("services") @classmethod def _services(cls, v): return [s for s in SERVICES if s in v] @field_validator("hours") @classmethod def _hours(cls, v): 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): v = v.strip() if not v: raise ValueError("name is empty") return v @field_validator("postcodes") @classmethod def _codes(cls, v): out = [] for code in v: code = " ".join(str(code).split()) if not code or len(code) > 20: raise ValueError("a postcode is empty or longer than 20 characters") if code not in out: out.append(code) return out class RuleBody(BaseModel): name: str = Field(min_length=1, max_length=80) is_active: bool = True sales_points: List[SalesPoint] = Field(default_factory=lambda: ["online_delivery"]) area_ids: List[int] = Field(default_factory=list, max_length=200) subtotal_min: Optional[float] = Field(default=None, ge=0, le=100000) subtotal_max: Optional[float] = Field(default=None, gt=0, le=100000) items_min: Optional[int] = Field(default=None, ge=0, le=10000) items_max: Optional[int] = Field(default=None, ge=0, le=10000) days: List[int] = Field(default_factory=list, max_length=7) time_from: Optional[str] = None time_to: Optional[str] = None action: Literal["set", "add", "percent", "free", "minimum"] = "set" value: float = Field(default=0.0, ge=-1000, le=100000) stop: bool = False @field_validator("name") @classmethod def _name(cls, v): v = v.strip() if not v: raise ValueError("name is empty") return v @field_validator("days") @classmethod def _days(cls, v): if any(d < 0 or d > 6 for d in v): raise ValueError("days are 0 (Monday) to 6 (Sunday)") return sorted(set(v)) @field_validator("time_from", "time_to") @classmethod def _time(cls, v): if v in (None, ""): return None if not HHMM.match(v): raise ValueError("times are HH:MM") return v @model_validator(mode="after") def _ranges(self): if self.subtotal_min is not None and self.subtotal_max is not None and self.subtotal_min >= self.subtotal_max: raise ValueError("the lower amount must be below the upper one") if self.items_min is not None and self.items_max is not None and self.items_min > self.items_max: raise ValueError("the lower item count must not be above the upper one") if (self.time_from is None) != (self.time_to is None): raise ValueError("give both times or neither") if self.action != "add" and self.value < 0: raise ValueError("only 'add' takes a negative amount") if self.action == "percent" and self.value > 100: raise ValueError("a percentage is at most 100") self.sales_points = sales_points.normalize(self.sales_points) self.area_ids = sorted(set(self.area_ids)) return self def _check_areas(db, ids): from models.fees import DeliveryArea if ids: known = {a.id for a in db.query(DeliveryArea).filter(DeliveryArea.id.in_(ids)).all()} missing = [i for i in ids if i not in known] if missing: raise XeniaError("fees.area_not_found", area_id=missing[0]) def _apply_rule(rule, body: RuleBody): rule.name, rule.is_active, rule.action, rule.value, rule.stop = body.name, int(body.is_active), body.action, body.value, int(body.stop) rule.sales_points, rule.area_ids, rule.days = json.dumps(body.sales_points), json.dumps(body.area_ids), json.dumps(body.days) rule.subtotal_min, rule.subtotal_max = body.subtotal_min, body.subtotal_max rule.items_min, rule.items_max = body.items_min, body.items_max rule.time_from, rule.time_to = body.time_from, body.time_to def _changed(): from services.ws_bus import broadcast_sync broadcast_sync("fees_changed", {}) # ── endpoints ────────────────────────────────────────────────────────────────── @router.get("") def list_fees(db: Session = Depends(get_db), user=Depends(require(KEY))): from services import system_products fee_product = system_products.get(db, system_products.DELIVERY_FEE) db.commit() from config import settings from services.table_qr import apps_url, menu_url return {**fees_payload(db), "ordering": ordering_settings(db), "fee_product": {**system_products.out(fee_product), "vat_groups": _vat_groups(db)}, # the venue's ordering link (S.99): to share, print or put on the website "links": {"order": f"{apps_url()}/order/{settings.SITE_ID or ''}", "menu": menu_url()}} def _vat_groups(db) -> list[dict]: """The fiscal machine's VAT groups (setting fiscal.vat_groups): [{machine_id, friendly_name}].""" from models.settings import PosSettings row = db.query(PosSettings).filter(PosSettings.key == "fiscal.vat_groups").first() try: groups = json.loads(row.value or "[]") if row else [] except (TypeError, ValueError): return [] return [{"machine_id": g.get("machine_id"), "friendly_name": g.get("friendly_name")} for g in groups if isinstance(g, dict) and isinstance(g.get("machine_id"), int)] class FeeProductBody(BaseModel): """How the delivery fee line is called (on screens and the receipt) and its VAT group.""" name: str = Field(min_length=1, max_length=40) vat_group_id: Optional[int] = Field(default=None, ge=1, le=99) @field_validator("name") @classmethod def _strip(cls, v: str) -> str: v = v.strip() if not v: raise ValueError("empty") return v @router.put("/fee-product") def put_fee_product(body: FeeProductBody, db: Session = Depends(get_db), user=Depends(require(KEY))): """The delivery fee's system product (services/system_products.py). Lines already on orders keep the name they were added with; the VAT group counts from the next receipt.""" from services import system_products if body.vat_group_id is not None: groups = [g["machine_id"] for g in _vat_groups(db)] if groups and body.vat_group_id not in groups: raise XeniaError("fees.vat_group_unknown", vat_group_id=body.vat_group_id) product = system_products.get(db, system_products.DELIVERY_FEE) product.name = product.fiscal_name = body.name product.fiscal_vat_group_id = body.vat_group_id db.commit() return system_products.out(product) @router.get("/ordering") def get_ordering(db: Session = Depends(get_db), user=Depends(require(KEY))): return ordering_settings(db) @router.put("/ordering") def put_ordering(body: OrderingBody, db: Session = Depends(get_db), user=Depends(require(KEY))): """Save the online ordering settings (they reach the cloud with the menu, within seconds).""" from models.settings import PosSettings row = db.query(PosSettings).filter(PosSettings.key == ORDERING_KEY).first() value = json.dumps(body.model_dump()) if row is None: db.add(PosSettings(key=ORDERING_KEY, value=value)) else: row.value = value db.commit() _changed() 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, kind=body.kind, geometry=json.dumps(body.geometry) if body.geometry is not None else None) db.add(area) db.commit() _changed() return area_out(area) @router.put("/areas/{area_id}") def edit_area(area_id: int, body: AreaBody, db: Session = Depends(get_db), user=Depends(require(KEY))): from models.fees import DeliveryArea area = db.get(DeliveryArea, area_id) 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) @router.delete("/areas/{area_id}", status_code=204) def delete_area(area_id: int, db: Session = Depends(get_db), user=Depends(require(KEY))): """Refused while a rule names the area (fees.area_in_use {rules}): change those rules first.""" from models.fees import DeliveryArea, FeeRule area = db.get(DeliveryArea, area_id) if area is None: raise XeniaError("fees.area_not_found", area_id=area_id) users = [r.name for r in db.query(FeeRule).all() if area_id in json.loads(r.area_ids or "[]")] if users: raise XeniaError("fees.area_in_use", rules=", ".join(users)) db.delete(area) db.commit() _changed() @router.post("/rules", status_code=201) def add_rule(body: RuleBody, db: Session = Depends(get_db), user=Depends(require(KEY))): from models.fees import FeeRule _check_areas(db, body.area_ids) rule = FeeRule(sort_order=db.query(FeeRule).count()) _apply_rule(rule, body) db.add(rule) db.commit() _changed() return rule_out(rule) @router.put("/rules/order") def order_rules(ids: List[int], db: Session = Depends(get_db), user=Depends(require(KEY))): """The rules in their new order: every rule id once.""" from models.fees import FeeRule rules = {r.id: r for r in db.query(FeeRule).all()} if sorted(ids) != sorted(rules): raise XeniaError("fees.order_invalid") for n, rid in enumerate(ids): rules[rid].sort_order = n db.commit() _changed() return fees_payload(db) @router.put("/rules/{rule_id}") def edit_rule(rule_id: int, body: RuleBody, db: Session = Depends(get_db), user=Depends(require(KEY))): from models.fees import FeeRule rule = db.get(FeeRule, rule_id) if rule is None: raise XeniaError("fees.rule_not_found", rule_id=rule_id) _check_areas(db, body.area_ids) _apply_rule(rule, body) db.commit() _changed() return rule_out(rule) @router.delete("/rules/{rule_id}", status_code=204) def delete_rule(rule_id: int, db: Session = Depends(get_db), user=Depends(require(KEY))): from models.fees import FeeRule rule = db.get(FeeRule, rule_id) if rule is None: raise XeniaError("fees.rule_not_found", rule_id=rule_id) db.delete(rule) db.commit() _changed() 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 time: Optional[str] = None # "HH:MM", venue's now when omitted @field_validator("time") @classmethod def _time(cls, v): if v in (None, ""): return None if not HHMM.match(v): raise ValueError("times are HH:MM") return v @router.post("/preview") def preview(body: PreviewBody, db: Session = Depends(get_db), user=Depends(require(KEY))): """Test an order: the fee (or why it's refused) and the rules that applied, exactly as the cloud will compute it at checkout.""" from core.timeutil import venue_now from services import fees data = fees_payload(db) now = venue_now() 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, 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}