feat(cloud): the cloud prices online orders itself; sites only touch their own data (platform-v2 3S, S.2)

- services/checkout.py: orders and quotes priced from the site's snapshot per sales point
  (prices map; older snapshots: digital_price less discount); refused: unavailable or
  not sold there, bad quantity/option/type, empty, order.price_changed when the browser's
  unit price or total differs. Nothing the browser says about money is stored.
- POST /api/orders/{site}/quote; delivery needs phone + address.
- Fixes: pending orders, menu sync and stats snapshot acted on the site_id given, not the
  authenticated site (a site could read another's orders or overwrite its menu/stats).
- Order refs are unique per site (a second site's first order failed); tracking by a
  random token GET /api/orders/track/{token}; old /status/{ref} only while unambiguous.
- Alembic 0003: online_orders sales_point, table_label, tracking_token; table rebuilt.
- menu-app: tracking link uses the token, shows the order number; tells the customer when
  the menu changed or the order failed.
- Tests: test_checkout.py (6), 0003 data migration.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-15 11:38:37 +02:00
co-authored by Claude Opus 5.5
parent 2541a5782e
commit 5bdd19d9fb
13 changed files with 539 additions and 41 deletions
+67 -13
View File
@@ -1,4 +1,5 @@
import json
import secrets
from fastapi import APIRouter, Depends, HTTPException, Header, status
from passlib.context import CryptContext
from sqlalchemy.orm import Session
@@ -6,10 +7,12 @@ 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,
PendingOrderOut, OrderSyncedRequest, OrderStatusUpdateRequest, QuoteRequest,
)
from services.checkout import CheckoutError, check_sent, price_cart
from auth_utils import get_current_admin # manager JWT checked separately in manager_auth
router = APIRouter()
@@ -38,12 +41,45 @@ def _require_site(
# ── Public endpoints ──────────────────────────────────────────────────────────
@router.post("/{site_slug}", response_model=OnlineOrderCreated, status_code=status.HTTP_201_CREATED)
def create_order(site_slug: str, body: OnlineOrderCreate, db: Session = Depends(get_db)):
"""Customer submits an order from the public menu SPA."""
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 _priced(menu, order_type, items):
try:
return price_cart(menu, order_type, items)
except CheckoutError as e:
raise HTTPException(status_code=e.status, detail=e.detail())
@router.post("/{site_slug}/quote")
def quote_order(site_slug: str, body: QuoteRequest, db: Session = Depends(get_db)):
"""The cart priced by the cloud from the venue's menu, for the customer apps (phase 3S)."""
_site, menu = _site_and_menu(db, site_slug)
return _priced(menu, body.order_type, [i.model_dump() for i in body.items]).out()
@router.post("/{site_slug}", response_model=OnlineOrderCreated, status_code=status.HTTP_201_CREATED)
def create_order(site_slug: str, body: OnlineOrderCreate, 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)."""
site, menu = _site_and_menu(db, site_slug)
items = [i.model_dump() for i in body.items]
priced = _priced(menu, body.order_type, items)
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
@@ -57,24 +93,39 @@ def create_order(site_slug: str, body: OnlineOrderCreate, db: Session = Depends(
customer_phone=body.customer_phone,
customer_address=body.customer_address,
customer_notes=body.customer_notes,
items_json=json.dumps([item.model_dump() for item in body.items]),
subtotal=body.subtotal,
delivery_fee=body.delivery_fee,
total=body.total,
table_label=(body.customer_table or "").strip() or None,
sales_point=priced.sales_point,
items_json=json.dumps([line.out() for line in priced.lines]),
subtotal=priced.subtotal,
delivery_fee=priced.delivery_fee,
total=priced.total,
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)
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, db: Session = Depends(get_db)):
"""The customer's tracking page (S.2): by the order's random token."""
order = db.query(OnlineOrder).filter(OnlineOrder.tracking_token == token).first()
if not order:
raise HTTPException(status_code=404, detail="Order not found")
return OrderStatusOut(public_ref=order.public_ref, status=order.status, rejection_reason=order.rejection_reason)
@router.get("/status/{public_ref}", response_model=OrderStatusOut)
def get_order_status(public_ref: str, db: Session = Depends(get_db)):
"""Customer polls this to track their order."""
order = db.query(OnlineOrder).filter(OnlineOrder.public_ref == public_ref).first()
if not order:
"""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,
@@ -86,7 +137,10 @@ def get_order_status(public_ref: str, db: Session = Depends(get_db)):
@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."""
"""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)