Files
xenia-pos-cloud/cloud_backend/routers/orders.py
T
bonaminandClaude Opus 5.5 d5b8492512 feat: delivery areas drawn on a map: the customer pins the address (plan 6R.G)
- services/fees.py: the site's engine (shapes matched by the pin), shared cases
- checkout: price_cart(pin=), delivery_areas with kind (+ geometry for shapes),
  venue_point in the public menu (postcodes and rules stay on the cloud)
- orders: quote / create take lat / lng; online_orders.lat / lng (Alembic 0007),
  sent to the site with the pending orders
- order app: PinMap (Leaflet + OpenStreetMap tiles), 'Pin it on the map' first
  when the venue drew areas, the browser's location offered; lat / lng sent
- tests: cloud test_fees (pinned quote and order), order-app logic

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 21:56:13 +02:00

286 lines
13 KiB
Python

import json
import secrets
from datetime import date, timezone
from fastapi import APIRouter, Depends, HTTPException, Header, Request, status
from passlib.context import CryptContext
from sqlalchemy.orm import Session
from database import get_db
from models.site import Site
from models.online_order import OnlineOrder
from models.menu_snapshot import MenuSnapshot
from schemas.online_order import (
OnlineOrderCreate, OnlineOrderCreated, OrderStatusOut,
PendingOrderOut, OrderSyncedRequest, OrderStatusUpdateRequest, QuoteRequest,
)
from services.checkout import CheckoutError, check_sent, price_cart
from services import ordering, qr, ratelimit
# public endpoints, per caller address (CL-4)
QUOTE_LIMIT = (120, 60) # 120 quotes a minute
ORDER_LIMIT = (10, 600) # 10 orders in 10 minutes
TRACK_LIMIT = (240, 60)
def _limit(request, bucket, rule):
if not ratelimit.hit(bucket, ratelimit.client_ip(request), *rule):
raise HTTPException(status_code=429, detail={"code": "rate.limited", "params": {"seconds": rule[1]}})
from auth_utils import get_current_admin # manager JWT checked separately in manager_auth
router = APIRouter()
_pwd = CryptContext(schemes=["bcrypt"], deprecated="auto")
# Valid status transitions
_TRANSITIONS: dict[str, set[str]] = {
"pending_acceptance": {"accepted", "rejected"},
"accepted": {"preparing"},
"preparing": {"ready", "out_for_delivery"},
"ready": {"delivered"},
"out_for_delivery": {"delivered"},
}
# reservations (S.6): confirmed or declined; then the guests arrive, or the venue cancels
_RES_TRANSITIONS: dict[str, set[str]] = {
"pending_acceptance": {"accepted", "rejected"},
"accepted": {"delivered", "cancelled"},
}
def _transitions(order_type: str) -> dict[str, set[str]]:
return _RES_TRANSITIONS if order_type in ordering.RES_TYPES else _TRANSITIONS
def _require_site(
x_site_id: str = Header(..., alias="X-Site-ID"),
x_site_key: str = Header(..., alias="X-Site-Key"),
db: Session = Depends(get_db),
) -> Site:
site = db.query(Site).filter(Site.site_id == x_site_id).first()
if not site or not _pwd.verify(x_site_key, site.secret_key_hash):
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid site credentials")
return site
# ── Public endpoints ──────────────────────────────────────────────────────────
def _site_and_menu(db, site_slug):
site = db.query(Site).filter(Site.site_id == site_slug).first()
if not site:
raise HTTPException(status_code=404, detail="Site not found")
snap = db.query(MenuSnapshot).filter(MenuSnapshot.site_id == site.id).first()
if snap is None:
raise HTTPException(status_code=409, detail={"code": "order.no_menu", "params": {}})
return site, json.loads(snap.snapshot_json)
def _pin(body):
"""The customer's pin [lat, lng] (6R.G), both or nothing."""
return [body.lat, body.lng] if body.lat is not None and body.lng is not None else None
def _priced(menu, order_type, items, area_id=None, postcode=None, point=None):
try:
return price_cart(menu, order_type, items, area_id=area_id, postcode=postcode, pin=point)
except CheckoutError as e:
raise HTTPException(status_code=e.status, detail=e.detail())
@router.get("/{site_slug}/slots")
def order_slots(site_slug: str, db: Session = Depends(get_db)):
"""When online orders can be placed (S.4): services, open now, ASAP offered, time slots."""
_site, menu = _site_and_menu(db, site_slug)
return ordering.summary(menu)
@router.get("/{site_slug}/reservation-slots")
def reservation_slots(site_slug: str, day: str, db: Session = Depends(get_db)):
"""The reservation times of one venue day (S.6): ?day=YYYY-MM-DD → {day, slots: [iso]}."""
_site, menu = _site_and_menu(db, site_slug)
try:
wanted = date.fromisoformat(day)
except ValueError:
raise HTTPException(status_code=422, detail={"code": "order.time_invalid", "params": {}})
return {"day": wanted.isoformat(), "slots": [t.isoformat() for t in ordering.res_slots(menu, wanted)]}
@router.post("/{site_slug}/quote")
def quote_order(site_slug: str, body: QuoteRequest, request: Request, db: Session = Depends(get_db)):
"""The cart priced by the cloud from the venue's menu, for the customer apps (phase 3S)."""
_limit(request, "quote", QUOTE_LIMIT)
_site, menu = _site_and_menu(db, site_slug)
return _priced(menu, body.order_type, [i.model_dump() for i in body.items], body.area_id, body.postcode, _pin(body)).out()
@router.post("/{site_slug}", response_model=OnlineOrderCreated, status_code=status.HTTP_201_CREATED)
def create_order(site_slug: str, body: OnlineOrderCreate, request: Request, db: Session = Depends(get_db)):
"""Customer submits an order from a customer app. The cloud prices it from the venue's menu
for the order's sales point (services/checkout.py); a price or total the app sent that
differs → 409 order.price_changed with the current prices; nothing the browser says about
money is stored (phase 3S, S.2)."""
_limit(request, "order", ORDER_LIMIT)
site, menu = _site_and_menu(db, site_slug)
items = [i.model_dump() for i in body.items]
reservation = body.order_type in ordering.RES_TYPES # S.6: a table, maybe with food
table = None
if body.order_type == "dine_in": # S.7: only from a table's QR code
if not qr.ordering_on(menu, site):
raise HTTPException(status_code=409, detail={"code": "order.service_unavailable", "params": {"service": "dine_in"}})
table = qr.table_for(menu, body.table_token)
if table is None:
raise HTTPException(status_code=403, detail={"code": "order.table_invalid", "params": {}})
if body.order_type == "reservation":
if items:
raise HTTPException(status_code=422, detail={"code": "order.items_not_allowed", "params": {}})
priced = None
else:
priced = _priced(menu, body.order_type, items, body.area_id, body.postcode, _pin(body))
if reservation:
problem = ordering.res_check(menu, body.order_type, body.requested_for, body.party_size)
elif body.order_type in ("takeaway", "delivery"): # the online ordering app (S.4)
problem = ordering.check(menu, body.order_type, body.requested_for)
else:
problem = None
if problem:
raise HTTPException(status_code=409, detail={"code": problem[0], "params": problem[1]})
if (reservation or body.order_type in ("takeaway", "delivery")) and not (body.customer_phone or "").strip():
raise HTTPException(status_code=422, detail={"code": "order.details_missing", "params": {"fields": ["customer_phone"]}})
if priced is not None:
try:
check_sent(priced, items, body.total)
except CheckoutError as e:
raise HTTPException(status_code=e.status, detail=e.detail())
if body.order_type == "delivery" and not ((body.customer_address or "").strip() and (body.customer_phone or "").strip()):
raise HTTPException(status_code=422, detail={"code": "order.details_missing", "params": {"fields": ["customer_phone", "customer_address"]}})
# Atomically increment counter and generate public_ref
site.order_counter = (site.order_counter or 0) + 1
public_ref = f"ORD-{site.order_counter:04d}"
order = OnlineOrder(
site_id=site.id,
public_ref=public_ref,
order_type=body.order_type,
customer_name=body.customer_name,
customer_phone=body.customer_phone,
customer_address=body.customer_address,
customer_notes=body.customer_notes,
table_label=table["label"] if table else None,
table_id=table["id"] if table else None,
delivery_area=priced.area_name if priced else None,
delivery_area_id=priced.area_id if priced else None,
lat=body.lat if body.order_type == "delivery" and _pin(body) else None,
lng=body.lng if body.order_type == "delivery" and _pin(body) else None,
# stored as UTC: SQLite keeps no time zone (read back naive = UTC, schemas mark it)
requested_for=(body.requested_for.astimezone(timezone.utc).replace(tzinfo=None)
if (reservation or body.order_type in ("takeaway", "delivery")) and body.requested_for else None),
party_size=body.party_size if reservation else None,
sales_point=priced.sales_point if priced else None,
items_json=json.dumps([line.out() for line in priced.lines] if priced else []),
subtotal=priced.subtotal if priced else 0.0,
delivery_fee=priced.delivery_fee if priced else 0.0,
total=priced.total if priced else 0.0,
status="pending_acceptance",
)
order.tracking_token = secrets.token_urlsafe(12)
db.add(order)
db.commit()
db.refresh(order)
return OnlineOrderCreated(order_id=order.id, public_ref=order.public_ref, status=order.status,
tracking_token=order.tracking_token, total=order.total)
@router.get("/track/{token}", response_model=OrderStatusOut)
def track_order(token: str, request: Request, db: Session = Depends(get_db)):
"""The customer's tracking page (S.2): by the order's random token. Since S.4 also what
was ordered and when it's wanted (the token is the customer's own secret)."""
_limit(request, "track", TRACK_LIMIT)
order = db.query(OnlineOrder).filter(OnlineOrder.tracking_token == token).first()
if not order:
raise HTTPException(status_code=404, detail="Order not found")
try:
lines = json.loads(order.items_json or "[]")
except ValueError:
lines = []
return OrderStatusOut(public_ref=order.public_ref, status=order.status, rejection_reason=order.rejection_reason,
order_type=order.order_type, requested_for=order.requested_for, created_at=order.created_at,
party_size=order.party_size,
lines=[{"name": x.get("name"), "quantity": x.get("quantity"), "unit_price": x.get("unit_price"),
"options": [o.get("name") for o in x.get("options") or []]} for x in lines],
subtotal=order.subtotal, delivery_fee=order.delivery_fee, total=order.total)
@router.get("/status/{public_ref}", response_model=OrderStatusOut)
def get_order_status(public_ref: str, db: Session = Depends(get_db)):
"""Old tracking by the public ref (menu-app links before S.2): only while the ref is unique
across sites; otherwise 404 (the new link is /track/{token})."""
orders = db.query(OnlineOrder).filter(OnlineOrder.public_ref == public_ref).limit(2).all()
if len(orders) != 1:
raise HTTPException(status_code=404, detail="Order not found")
order = orders[0]
return OrderStatusOut(
public_ref=order.public_ref,
status=order.status,
rejection_reason=order.rejection_reason,
)
# ── Internal endpoints (site API key) ─────────────────────────────────────────
@router.get("/pending/{site_id}", response_model=list[PendingOrderOut])
def get_pending_orders(site_id: int, site: Site = Depends(_require_site), db: Session = Depends(get_db)):
"""Return all orders not yet synced to the local backend. Only the authenticated site's own
(before S.2 any site with a valid key could read another site's by its number)."""
if site_id != site.id:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Not this site's orders")
orders = (
db.query(OnlineOrder)
.filter(OnlineOrder.site_id == site_id, OnlineOrder.synced_to_local == 0)
.order_by(OnlineOrder.created_at)
.all()
)
return orders
@router.post("/{order_id}/synced", status_code=status.HTTP_204_NO_CONTENT)
def mark_order_synced(
order_id: int,
body: OrderSyncedRequest,
site: Site = Depends(_require_site),
db: Session = Depends(get_db),
):
"""Local backend calls this after it has created the order locally."""
order = db.query(OnlineOrder).filter(
OnlineOrder.id == order_id, OnlineOrder.site_id == site.id
).first()
if not order:
raise HTTPException(status_code=404, detail="Order not found")
order.synced_to_local = 1
order.local_order_id = body.local_order_id
db.commit()
@router.patch("/{order_id}/status", status_code=status.HTTP_204_NO_CONTENT)
def update_order_status(
order_id: int,
body: OrderStatusUpdateRequest,
site: Site = Depends(_require_site),
db: Session = Depends(get_db),
):
"""Update order status. Called by local_backend after staff accept/reject/progress."""
order = db.query(OnlineOrder).filter(
OnlineOrder.id == order_id, OnlineOrder.site_id == site.id
).first()
if not order:
raise HTTPException(status_code=404, detail="Order not found")
allowed = _transitions(order.order_type).get(order.status, set())
if body.status not in allowed:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail=f"Cannot transition from '{order.status}' to '{body.status}'",
)
order.status = body.status
if body.rejection_reason:
order.rejection_reason = body.rejection_reason
db.commit()