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
@@ -0,0 +1,80 @@
"""online orders: sales_point, table_label, tracking_token; public_ref unique per site (plan phase 3S, S.2)
- sales_point / table_label: the cloud prices orders per sales point; the QR menu's table
- public_ref ("ORD-0001") counts per site but was unique across all sites, so a second
site's first online order failed → unique per (site_id, public_ref)
- tracking_token: the customer's tracking page used the public ref alone (ambiguous across
sites and guessable) → a random token per order (existing orders get one)
The table is rebuilt from an explicit definition (SQLite can't drop the unnamed
UNIQUE(public_ref) in place; copy_from leaves it out, the indexes are kept).
Revision ID: 0003_order_sales_point
Revises: 0002_v2_licensing
Create Date: 2026-11-15 23:00:00
"""
import secrets
from alembic import op
import sqlalchemy as sa
revision = '0003_order_sales_point'
down_revision = '0002_v2_licensing'
branch_labels = None
depends_on = None
def _base(*extra):
"""online_orders as 0001 created it, without UNIQUE(public_ref), plus `extra`."""
return sa.Table(
'online_orders', sa.MetaData(),
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('site_id', sa.Integer(), nullable=False),
sa.Column('public_ref', sa.String(), nullable=False),
sa.Column('order_type', sa.String(), nullable=False),
sa.Column('customer_name', sa.String(), nullable=False),
sa.Column('customer_phone', sa.String(), nullable=True),
sa.Column('customer_address', sa.Text(), nullable=True),
sa.Column('customer_notes', sa.Text(), nullable=True),
sa.Column('items_json', sa.Text(), nullable=False),
sa.Column('subtotal', sa.Float(), nullable=False),
sa.Column('delivery_fee', sa.Float(), nullable=False),
sa.Column('total', sa.Float(), nullable=False),
sa.Column('status', sa.String(), nullable=False),
sa.Column('rejection_reason', sa.String(), nullable=True),
sa.Column('synced_to_local', sa.Integer(), nullable=False),
sa.Column('local_order_id', sa.Integer(), nullable=True),
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=True),
sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=True),
*extra,
sa.ForeignKeyConstraint(['site_id'], ['sites.id'], ),
sa.PrimaryKeyConstraint('id'),
sa.Index('ix_online_orders_id', 'id'),
sa.Index('ix_online_orders_site_id', 'site_id'),
sa.Index('ix_online_orders_status', 'status'),
)
def upgrade() -> None:
with op.batch_alter_table('online_orders', copy_from=_base(), recreate='always') as batch_op:
batch_op.add_column(sa.Column('table_label', sa.String(), nullable=True))
batch_op.add_column(sa.Column('sales_point', sa.String(), nullable=True))
batch_op.add_column(sa.Column('tracking_token', sa.String(), nullable=True))
batch_op.create_unique_constraint('uq_online_orders_site_ref', ['site_id', 'public_ref'])
batch_op.create_unique_constraint('uq_online_orders_tracking_token', ['tracking_token'])
conn = op.get_bind()
for (oid,) in conn.execute(sa.text("select id from online_orders where tracking_token is null")).fetchall():
conn.execute(sa.text("update online_orders set tracking_token = :t where id = :i"),
{"t": secrets.token_urlsafe(12), "i": oid})
def downgrade() -> None:
current = _base(sa.Column('table_label', sa.String(), nullable=True),
sa.Column('sales_point', sa.String(), nullable=True),
sa.Column('tracking_token', sa.String(), nullable=True))
with op.batch_alter_table('online_orders', copy_from=current, recreate='always') as batch_op:
batch_op.drop_column('tracking_token')
batch_op.drop_column('sales_point')
batch_op.drop_column('table_label')
batch_op.create_unique_constraint('uq_online_orders_public_ref', ['public_ref'])
+11 -3
View File
@@ -1,23 +1,31 @@
from sqlalchemy import Column, Integer, String, Text, Float, DateTime, ForeignKey
from sqlalchemy import Column, Integer, String, Text, Float, DateTime, ForeignKey, UniqueConstraint
from sqlalchemy.sql import func
from database import Base
class OnlineOrder(Base):
__tablename__ = "online_orders"
__table_args__ = (
UniqueConstraint("site_id", "public_ref", name="uq_online_orders_site_ref"), # S.2: per site
UniqueConstraint("tracking_token", name="uq_online_orders_tracking_token"),
)
id = Column(Integer, primary_key=True, index=True)
site_id = Column(Integer, ForeignKey("sites.id"), nullable=False, index=True)
# Human-readable reference, unique per site (e.g. "ORD-0042")
public_ref = Column(String, unique=True, nullable=False)
order_type = Column(String, nullable=False) # "delivery" | "dine_in"
public_ref = Column(String, nullable=False)
# the customer's tracking page: random, unguessable (S.2; the ref alone was ambiguous across sites)
tracking_token = Column(String, nullable=True)
order_type = Column(String, nullable=False) # dine_in | takeaway | delivery | preorder
# Customer info
customer_name = Column(String, nullable=False)
customer_phone = Column(String, nullable=True)
customer_address = Column(Text, nullable=True) # required for delivery
customer_notes = Column(Text, nullable=True)
table_label = Column(String, nullable=True) # the QR menu's table, as the customer gave it
sales_point = Column(String, nullable=True) # the site's sales point (phase 3S, S.2)
# Order content — JSON array of ordered items
items_json = Column(Text, nullable=False)
+12 -3
View File
@@ -71,12 +71,21 @@ def get_menu(site_slug: str, db: Session = Depends(get_db)):
@router.post("/sync", response_model=MenuSyncResponse)
def sync_menu(body: MenuSyncRequest, site: Site = Depends(_require_site), db: Session = Depends(get_db)):
"""Upsert the menu snapshot for this site. Called by local_backend on each sync."""
snapshot = db.query(MenuSnapshot).filter(MenuSnapshot.site_id == body.site_id).first()
"""Upsert the menu snapshot for this site. Called by local_backend on each sync. Only the
authenticated site's own (before S.2 the body's site_id was trusted: one site could
overwrite another's menu)."""
if body.site_id != site.id:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Not this site's menu")
import json
try:
json.loads(body.snapshot_json)
except ValueError:
raise HTTPException(status_code=422, detail="snapshot_json is not JSON")
snapshot = db.query(MenuSnapshot).filter(MenuSnapshot.site_id == site.id).first()
if snapshot:
snapshot.snapshot_json = body.snapshot_json
else:
snapshot = MenuSnapshot(site_id=body.site_id, snapshot_json=body.snapshot_json)
snapshot = MenuSnapshot(site_id=site.id, snapshot_json=body.snapshot_json)
db.add(snapshot)
db.commit()
return MenuSyncResponse(ok=True)
+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)
+4 -2
View File
@@ -91,11 +91,13 @@ def push_stats_snapshot(
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")
snap = db.query(StatsSnapshot).filter(StatsSnapshot.site_id == body.site_id).first()
if body.site_id != site.id: # S.2: only its own (the body's site_id was trusted before)
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Not this site's stats")
snap = db.query(StatsSnapshot).filter(StatsSnapshot.site_id == site.id).first()
if snap:
snap.snapshot_json = body.snapshot_json
else:
snap = StatsSnapshot(site_id=body.site_id, snapshot_json=body.snapshot_json)
snap = StatsSnapshot(site_id=site.id, snapshot_json=body.snapshot_json)
db.add(snap)
db.commit()
+26 -13
View File
@@ -1,33 +1,44 @@
from __future__ import annotations
from datetime import datetime
from typing import Optional
from pydantic import BaseModel
from pydantic import BaseModel, Field
class OrderItemIn(BaseModel):
"""What the customer wants. Prices come from the venue's menu (services/checkout.py);
name and unit_price, if sent, are only compared (phase 3S, S.2)."""
product_id: int
name: str
quantity: int
unit_price: float
options: list = []
name: Optional[str] = None
unit_price: Optional[float] = None
options: list = [] # quick option ids (or {id})
class QuoteRequest(BaseModel):
order_type: str # dine_in | takeaway | delivery | preorder
items: list[OrderItemIn] = Field(max_length=100)
class OnlineOrderCreate(BaseModel):
order_type: str # "delivery" | "dine_in"
customer_name: str
customer_phone: Optional[str] = None
customer_address: Optional[str] = None
customer_notes: Optional[str] = None
items: list[OrderItemIn]
subtotal: float
delivery_fee: float = 0.0
total: float
order_type: str # dine_in | takeaway | delivery | preorder
customer_name: str = Field(min_length=1, max_length=100)
customer_phone: Optional[str] = Field(default=None, max_length=40)
customer_address: Optional[str] = Field(default=None, max_length=500)
customer_notes: Optional[str] = Field(default=None, max_length=1000)
customer_table: Optional[str] = Field(default=None, max_length=40)
items: list[OrderItemIn] = Field(max_length=100)
# what the customer was shown: compared, never stored as sent
subtotal: Optional[float] = None
delivery_fee: Optional[float] = None
total: Optional[float] = None
class OnlineOrderCreated(BaseModel):
order_id: int
public_ref: str
status: str
tracking_token: Optional[str] = None # the tracking page: GET /api/orders/track/{token} (S.2)
total: Optional[float] = None
class OrderStatusOut(BaseModel):
@@ -44,6 +55,8 @@ class PendingOrderOut(BaseModel):
customer_phone: Optional[str] = None
customer_address: Optional[str] = None
customer_notes: Optional[str] = None
table_label: Optional[str] = None # the QR menu's table (S.2)
sales_point: Optional[str] = None # the site's sales point (S.2)
items_json: str
subtotal: float
delivery_fee: float
+152
View File
@@ -0,0 +1,152 @@
"""The cloud prices online orders itself (plan phase 3S, step S.2).
The customer's browser sends what it wants (product ids, quantities, chosen quick options);
the price of everything comes from the venue's menu snapshot (pushed by the site), for the
order's sales point. A total the browser sends is only compared: a difference means the
customer saw old prices (or edited them) and the order is refused with the current ones.
price_cart(snapshot, order_type, items) -> Priced
CheckoutError(status, code, **params) the router turns it into {"detail": {code, params}}
Snapshot product (site services/cloud_sync._push_menu_snapshot):
{id, name, digital_name, base_price, digital_price, digital_discount, digital_available,
sold_at: [sales point], prices: {sales point: price}, quick_options: [{id, name, price}]}
Snapshots from before S.2 have no `prices` / `sold_at`: every customer-app sales point, at
digital_price (or base_price) less digital_discount %.
"""
from __future__ import annotations
from dataclasses import dataclass, field
# the cloud order's type → the site's sales point (core/sales_points.py)
POINT_FOR_TYPE = {
"dine_in": "qr_table",
"takeaway": "online_takeaway",
"delivery": "online_delivery",
"preorder": "online_preorder",
}
DIGITAL = tuple(POINT_FOR_TYPE.values())
MAX_QTY = 99
MAX_LINES = 100
EPS = 0.005
class CheckoutError(Exception):
def __init__(self, status: int, code: str, **params):
super().__init__(code)
self.status, self.code, self.params = status, code, params
def detail(self) -> dict:
return {"code": self.code, "params": self.params}
@dataclass
class Line:
product_id: int
name: str
quantity: int
unit_price: float
options: list = field(default_factory=list) # [{id, name, price}]
def out(self) -> dict:
return {"product_id": self.product_id, "name": self.name, "quantity": self.quantity,
"unit_price": self.unit_price, "options": self.options}
@dataclass
class Priced:
sales_point: str
lines: list
subtotal: float
delivery_fee: float
total: float
def out(self) -> dict:
return {"sales_point": self.sales_point, "lines": [x.out() for x in self.lines],
"subtotal": self.subtotal, "delivery_fee": self.delivery_fee, "total": self.total}
def products_of(snapshot: dict) -> dict[int, dict]:
out: dict[int, dict] = {}
for cat in snapshot.get("categories", []):
for p in cat.get("products", []):
if isinstance(p.get("id"), int):
out.setdefault(p["id"], p) # a product listed in several categories: once
return out
def price_at(product: dict, point: str) -> float | None:
"""The product's price at a sales point; None = not sold there."""
sold = product.get("sold_at")
if sold is not None and point not in sold:
return None
prices = product.get("prices")
if prices is not None:
value = prices.get(point)
return None if value is None else round(float(value), 2)
base = product.get("digital_price")
if base is None:
base = product.get("base_price") or 0.0
pct = product.get("digital_discount") or 0.0
return round(float(base) * (1 - float(pct) / 100.0), 2)
def _display_name(product: dict) -> str:
name = product.get("digital_name") or product.get("name") or f"#{product.get('id')}"
return name if isinstance(name, str) else str(name)
def _option_ids(raw) -> list:
out = []
for o in raw or []:
oid = o.get("id") if isinstance(o, dict) else o
if not isinstance(oid, int) or isinstance(oid, bool):
raise CheckoutError(422, "order.option_unavailable", option_id=oid)
out.append(oid)
return out
def price_cart(snapshot: dict, order_type: str, items: list[dict]) -> Priced:
"""Price the cart from the snapshot. items: [{product_id, quantity, options?}]."""
point = POINT_FOR_TYPE.get(order_type)
if point is None:
raise CheckoutError(422, "order.type_invalid", order_type=order_type)
if not items:
raise CheckoutError(422, "order.empty")
if len(items) > MAX_LINES:
raise CheckoutError(422, "order.too_many_lines", max=MAX_LINES)
products = products_of(snapshot)
lines = []
for it in items:
pid, qty = it.get("product_id"), it.get("quantity")
if isinstance(qty, bool) or not isinstance(qty, int) or not 1 <= qty <= MAX_QTY:
raise CheckoutError(422, "order.quantity_invalid", product_id=pid, max=MAX_QTY)
product = products.get(pid) if isinstance(pid, int) else None
unit = price_at(product, point) if product is not None else None
if product is None or unit is None or product.get("digital_available") is False:
raise CheckoutError(409, "order.item_unavailable", product_id=pid,
name=_display_name(product) if product else None)
quick = {q.get("id"): q for q in product.get("quick_options") or [] if isinstance(q, dict)}
options = []
for oid in _option_ids(it.get("options")):
q = quick.get(oid)
if q is None:
raise CheckoutError(409, "order.option_unavailable", product_id=pid, option_id=oid)
options.append({"id": oid, "name": q.get("name"), "price": round(float(q.get("price") or 0.0), 2)})
unit = round(unit + sum(o["price"] for o in options), 2)
lines.append(Line(product_id=pid, name=_display_name(product), quantity=qty, unit_price=unit, options=options))
subtotal = round(sum(x.unit_price * x.quantity for x in lines), 2)
fee = 0.0 # S.3: the venue's fee rules
return Priced(sales_point=point, lines=lines, subtotal=subtotal, delivery_fee=fee, total=round(subtotal + fee, 2))
def check_sent(priced: Priced, items: list[dict], total: float | None) -> None:
"""What the browser showed must be what we charge: each line's unit price (if sent) and
the total (if sent). Otherwise order.price_changed with the current prices."""
changed = total is not None and abs(float(total) - priced.total) > EPS
for sent, line in zip(items, priced.lines):
up = sent.get("unit_price")
if up is not None and abs(float(up) - line.unit_price) > EPS:
changed = True
if changed:
raise CheckoutError(409, "order.price_changed", **priced.out())
+129
View File
@@ -0,0 +1,129 @@
"""The cloud prices online orders itself; sites only touch their own data (plan phase 3S, S.2).
Done when: a tampered price or total is refused, a correct order is stored with the cloud's
prices, and one site can't read or overwrite another's data."""
import json
from test_licensing_v2 import _heartbeat, _new_site
COLA, PIE, SOUP = 11, 12, 13
def _h(site):
return {"X-Site-ID": site["site_id"], "X-Site-Key": site["secret_key"]}
def _menu(client, site, numeric):
"""A snapshot as the site pushes it after S.2: prices per sales point, where it's sold."""
snap = {"categories": [{"id": 1, "name": "All", "products": [
{"id": COLA, "name": "Cola 1.5L", "base_price": 3.5, "digital_price": 3.0, "digital_available": True,
"sold_at": ["qr_table", "online_takeaway", "online_delivery"],
"prices": {"qr_table": 3.0, "online_takeaway": 2.5, "online_delivery": 2.8},
"quick_options": [{"id": 7, "name": "Ice", "price": 0.2}]},
{"id": PIE, "name": "Pie", "base_price": 5.0, "digital_price": 5.0, "digital_available": True,
"sold_at": ["qr_table"], "prices": {"qr_table": 5.0}, "quick_options": []},
{"id": SOUP, "name": "Soup", "base_price": 6.0, "digital_price": 6.0, "digital_available": False,
"sold_at": ["qr_table", "online_delivery"], "prices": {"qr_table": 6.0, "online_delivery": 6.0}, "quick_options": []},
]}]}
r = client.post("/api/menu/sync", headers=_h(site), json={"site_id": numeric, "snapshot_json": json.dumps(snap)})
assert r.status_code == 200, r.text
def _venue(client, admin_h):
site = _new_site(client, admin_h)
numeric = _heartbeat(client, site)["site_numeric_id"]
_menu(client, site, numeric)
return site, numeric
def _order(client, site, order_type="takeaway", **extra):
body = {"order_type": order_type, "customer_name": "Maria", "customer_phone": "6900000000",
"items": [{"product_id": COLA, "quantity": 2}], **extra}
return client.post(f"/api/orders/{site['site_id']}", json=body)
def _code(r):
return r.json()["detail"]["code"]
def test_the_cloud_prices_by_sales_point(client, admin_h):
site, _ = _venue(client, admin_h)
q = lambda t, items: client.post(f"/api/orders/{site['site_id']}/quote", json={"order_type": t, "items": items}) # noqa: E731
take = q("takeaway", [{"product_id": COLA, "quantity": 2, "options": [7]}]).json()
assert (take["sales_point"], take["lines"][0]["unit_price"], take["total"]) == ("online_takeaway", 2.7, 5.4)
assert q("dine_in", [{"product_id": COLA, "quantity": 1}]).json()["total"] == 3.0
assert q("delivery", [{"product_id": COLA, "quantity": 1}]).json()["total"] == 2.8
assert _code(q("takeaway", [{"product_id": PIE, "quantity": 1}])) == "order.item_unavailable" # QR menu only
assert _code(q("delivery", [{"product_id": SOUP, "quantity": 1}])) == "order.item_unavailable" # out of stock now
assert _code(q("takeaway", [{"product_id": 999, "quantity": 1}])) == "order.item_unavailable"
assert _code(q("takeaway", [{"product_id": COLA, "quantity": 0}])) == "order.quantity_invalid"
assert _code(q("takeaway", [{"product_id": COLA, "quantity": 1, "options": [8]}])) == "order.option_unavailable"
assert _code(q("teleport", [{"product_id": COLA, "quantity": 1}])) == "order.type_invalid"
assert _code(q("takeaway", [])) == "order.empty"
def test_a_tampered_order_is_refused_and_a_correct_one_stored_at_the_clouds_prices(client, admin_h):
"""The done-when, first part."""
site, numeric = _venue(client, admin_h)
r = _order(client, site, items=[{"product_id": COLA, "quantity": 2, "unit_price": 0.01}], subtotal=0.02, total=0.02)
assert r.status_code == 409 and _code(r) == "order.price_changed"
assert r.json()["detail"]["params"]["total"] == 5.0 # the current prices come back
assert _code(_order(client, site, total=1.0)) == "order.price_changed"
ok = _order(client, site, total=5.0, delivery_fee=-3, customer_table=" ")
assert ok.status_code == 201, ok.text
pending = client.get(f"/api/orders/pending/{numeric}", headers=_h(site)).json()
stored = next(o for o in pending if o["public_ref"] == ok.json()["public_ref"])
assert (stored["subtotal"], stored["delivery_fee"], stored["total"], stored["sales_point"]) == (5.0, 0.0, 5.0, "online_takeaway")
assert json.loads(stored["items_json"]) == [{"product_id": COLA, "name": "Cola 1.5L", "quantity": 2, "unit_price": 2.5, "options": []}]
# no total sent at all: priced by the cloud anyway (the old menu app's fields are optional)
assert _order(client, site).status_code == 201
def test_the_qr_menus_table_and_delivery_details(client, admin_h):
site, numeric = _venue(client, admin_h)
r = _order(client, site, "dine_in", customer_table="5", items=[{"product_id": PIE, "quantity": 1}])
assert r.status_code == 201
stored = next(o for o in client.get(f"/api/orders/pending/{numeric}", headers=_h(site)).json()
if o["public_ref"] == r.json()["public_ref"])
assert (stored["table_label"], stored["sales_point"]) == ("5", "qr_table")
assert _code(_order(client, site, "delivery")) == "order.details_missing"
assert _order(client, site, "delivery", customer_address="Main square 3").status_code == 201
def test_a_site_only_touches_its_own_data(client, admin_h):
"""The done-when, second part: a site's key can't read or overwrite another site's data."""
a, a_num = _venue(client, admin_h)
b, b_num = _venue(client, admin_h)
assert _order(client, a).status_code == 201
assert client.get(f"/api/orders/pending/{a_num}", headers=_h(b)).status_code == 403
assert client.post("/api/menu/sync", headers=_h(b), json={"site_id": a_num, "snapshot_json": "{}"}).status_code == 403
assert client.post("/api/remote/snapshot", headers=_h(b), json={"site_id": a_num, "snapshot_json": "{}"}).status_code == 403
# a's menu is intact
assert _order(client, a, total=5.0).status_code == 201
assert client.post("/api/menu/sync", headers=_h(a), json={"site_id": a_num, "snapshot_json": "not json"}).status_code == 422
def test_a_snapshot_from_before_s2_still_prices(client, admin_h):
"""A site that hasn't updated yet pushes digital_price / digital_discount only."""
site = _new_site(client, admin_h)
numeric = _heartbeat(client, site)["site_numeric_id"]
old = {"categories": [{"id": 1, "name": "All", "products": [
{"id": COLA, "name": "Cola", "base_price": 4.0, "digital_price": None, "digital_discount": 25, "digital_available": True,
"quick_options": []}]}]}
client.post("/api/menu/sync", headers=_h(site), json={"site_id": numeric, "snapshot_json": json.dumps(old)})
r = client.post(f"/api/orders/{site['site_id']}/quote", json={"order_type": "dine_in", "items": [{"product_id": COLA, "quantity": 1}]})
assert r.json()["total"] == 3.0
def test_order_numbers_per_site_and_tracking_by_token(client, admin_h):
"""Two venues both have an ORD-0001 (the second used to fail); the customer tracks their
order by its random token, and the bare number no longer identifies it."""
a, _ = _venue(client, admin_h)
b, _ = _venue(client, admin_h)
ra, rb = _order(client, a).json(), _order(client, b).json()
assert ra["public_ref"] == rb["public_ref"] == "ORD-0001"
assert ra["tracking_token"] != rb["tracking_token"] and ra["total"] == 5.0
t = client.get(f"/api/orders/track/{ra['tracking_token']}")
assert t.status_code == 200 and t.json() == {"public_ref": "ORD-0001", "status": "pending_acceptance", "rejection_reason": None}
assert client.get("/api/orders/status/ORD-0001").status_code == 404 # ambiguous now
assert client.get("/api/orders/track/nope").status_code == 404
+30
View File
@@ -89,3 +89,33 @@ def test_nothing_calls_create_all():
if not p.relative_to(root).as_posix().startswith(("tests/", "migrations/"))
and re.search(r"\.create_all\(", p.read_text(encoding="utf-8", errors="ignore"))]
assert bad == []
def test_0003_keeps_orders_gives_tokens_and_refs_per_site(tmp_path):
"""Existing online orders survive the table rebuild, get a tracking token, and two sites
may now both have ORD-0001 (plan phase 3S, S.2)."""
from schema import alembic_config
from alembic import command
import sqlalchemy as sa
eng = create_engine(f"sqlite:///{(tmp_path / 'c.db').as_posix()}")
with eng.begin() as conn:
command.upgrade(alembic_config(conn), "0002_v2_licensing")
for sid in (1, 2):
conn.execute(text("insert into sites (id, site_id, name, owner_name, contact_email, secret_key_hash, is_active, "
"license_expires_at, created_at, order_counter, menu_mode) "
"values (:i, :s, 'S', 'O', 'o@x', 'x', 1, '2027-01-01', '2026-01-01', 1, 'order')"), {"i": sid, "s": f"site-{sid}"})
conn.execute(text("insert into online_orders (site_id, public_ref, order_type, customer_name, items_json, subtotal, "
"delivery_fee, total, status, synced_to_local) values (1, 'ORD-0001', 'dine_in', 'A', '[]', 1, 0, 1, 'delivered', 1)"))
upgrade_to_head(eng)
with eng.begin() as conn:
row = conn.execute(text("select public_ref, tracking_token from online_orders")).one()
assert row[0] == "ORD-0001" and row[1]
conn.execute(text("insert into online_orders (site_id, public_ref, order_type, customer_name, items_json, subtotal, "
"delivery_fee, total, status, synced_to_local) values (2, 'ORD-0001', 'dine_in', 'B', '[]', 1, 0, 1, 'delivered', 0)"))
with pytest.raises(sa.exc.IntegrityError):
with conn.begin_nested():
conn.execute(text("insert into online_orders (site_id, public_ref, order_type, customer_name, items_json, subtotal, "
"delivery_fee, total, status, synced_to_local) values (2, 'ORD-0001', 'dine_in', 'C', '[]', 1, 0, 1, 'delivered', 0)"))
idx = {i["name"] for i in sa.inspect(conn).get_indexes("online_orders")}
eng.dispose()
assert {"ix_online_orders_site_id", "ix_online_orders_status"} <= idx
+11 -3
View File
@@ -14,7 +14,15 @@ export async function submitOrder(siteSlug, body) {
return data // { order_id, public_ref, status }
}
export async function fetchOrderStatus(publicRef) {
const { data } = await api.get(`/api/orders/status/${publicRef}`)
return data // { public_ref, status, rejection_reason }
// The tracking link carries the order's random token (phase 3S, S.2); links from before that
// carry the public ref and use the old endpoint.
export async function fetchOrderStatus(ref) {
try {
const { data } = await api.get(`/api/orders/track/${ref}`)
return data // { public_ref, status, rejection_reason }
} catch (err) {
if (err?.response?.status !== 404 || !/^ORD-\d+$/.test(ref)) throw err
const { data } = await api.get(`/api/orders/status/${ref}`)
return data
}
}
@@ -30,6 +30,8 @@ const I18N = {
yourOrder: 'Your order', emptyCart: 'Your cart is empty',
emptyCartSub: 'Add a few dishes to get started.',
continue: 'Continue', placeOrder: 'Place order', sending: 'Sending…',
orderChanged: 'Something on the menu changed since you opened it. Please reload the page and check your order.',
orderFailed: 'The order could not be sent. Please try again.',
orderPlaced: 'Order placed!', orderPlacedSub: 'Your order has been sent to the kitchen.',
newOrder: 'Back to menu', table: 'Table no.', name: 'Your name',
namePh: 'e.g. Alex', tablePh: 'e.g. 12', orderSummary: 'Order summary',
@@ -44,6 +46,8 @@ const I18N = {
yourOrder: 'Η παραγγελία σου', emptyCart: 'Το καλάθι σου είναι άδειο',
emptyCartSub: 'Πρόσθεσε μερικά πιάτα για να ξεκινήσεις.',
continue: 'Συνέχεια', placeOrder: 'Αποστολή παραγγελίας', sending: 'Αποστολή…',
orderChanged: 'Κάτι άλλαξε στο μενού από τότε που το άνοιξες. Ανανέωσε τη σελίδα και έλεγξε την παραγγελία σου.',
orderFailed: 'Η παραγγελία δεν στάλθηκε. Δοκίμασε ξανά.',
orderPlaced: 'Η παραγγελία στάλθηκε!', orderPlacedSub: 'Η παραγγελία σου εστάλη στην κουζίνα.',
newOrder: 'Πίσω στο μενού', table: 'Τραπέζι', name: 'Το όνομά σου',
namePh: 'π.χ. Αλέξης', tablePh: 'π.χ. 12', orderSummary: 'Σύνοψη παραγγελίας',
@@ -572,6 +576,7 @@ function SearchOverlay({ open, onClose, categories, lang, t, onOpen, onAdd, cart
function CartFlow({ stage, setStage, cart, setCart, categories, lang, t, onOpenProduct, siteSlug, navigate }) {
const [form, setForm] = useState({ name: '', table: '' })
const [sending, setSending] = useState(false)
const [sendError, setSendError] = useState('')
const allProducts = useMemo(() => categories.flatMap(c => c.products), [categories])
@@ -593,6 +598,7 @@ function CartFlow({ stage, setStage, cart, setCart, categories, lang, t, onOpenP
const submit = async () => {
setSending(true)
setSendError('')
try {
const result = await submitOrder(siteSlug, {
order_type: 'dine_in',
@@ -612,8 +618,12 @@ function CartFlow({ stage, setStage, cart, setCart, categories, lang, t, onOpenP
setCart({})
setForm({ name: '', table: '' })
setStage(null)
navigate(`/${siteSlug}/confirm/${result.public_ref}`)
} catch {
// the cloud prices the order itself (phase 3S, S.2); the tracking link is the order's token
navigate(`/${siteSlug}/confirm/${result.tracking_token ?? result.public_ref}`)
} catch (err) {
const code = err?.response?.data?.detail?.code
setSendError(code === 'order.price_changed' || code === 'order.item_unavailable' || code === 'order.option_unavailable'
? t.orderChanged : t.orderFailed)
setSending(false)
}
}
@@ -740,6 +750,7 @@ function CartFlow({ stage, setStage, cart, setCart, categories, lang, t, onOpenP
<span className="text-[13px] font-medium text-[#7d7660]">{t.total}</span>
<span className="font-display text-[24px] font-semibold tabular-nums text-[#2d3b2d]">{eur(total)}</span>
</div>
{sendError && <p role="alert" className="mb-2.5 text-[13px] text-[#c2602f]">{sendError}</p>}
<button
disabled={!valid || sending}
onClick={submit}
@@ -20,6 +20,7 @@ export default function OrderConfirm() {
const { ref } = useParams()
const [orderStatus, setOrderStatus] = useState(null)
const [rejectionReason, setRejectionReason] = useState(null)
const [publicRef, setPublicRef] = useState(null) // the link carries a token (S.2); show the order number
const [error, setError] = useState(false)
useEffect(() => {
@@ -29,6 +30,7 @@ export default function OrderConfirm() {
try {
const data = await fetchOrderStatus(ref)
setOrderStatus(data.status)
setPublicRef(data.public_ref)
setRejectionReason(data.rejection_reason)
if (!TERMINAL.has(data.status)) {
timer = setTimeout(poll, POLL_MS)
@@ -65,7 +67,7 @@ export default function OrderConfirm() {
{/* Ref number */}
<p className="mt-5 font-sans text-[11px] font-semibold uppercase tracking-[0.22em] text-[#b3aa90]">
{ref}
{publicRef ?? ''}
</p>
{/* Status label */}
+1 -1
View File
@@ -26,7 +26,7 @@ TLS and domains are handled in front of these ports on the VPS (`xenia-api.bonam
| `/api/sites` | `sites.py` | admin bearer | sysadmin panel |
| `/api/heartbeat` | `heartbeat.py` | `X-Site-ID` + `X-Site-Key` | local sites |
| `/api/menu` | `menu.py` | public GET; site headers for sync | menu-app, local sites |
| `/api/orders` | `orders.py` | public create/status; site headers for pending/synced/status | menu-app, local sites |
| `/api/orders` | `orders.py` | public create/quote/track (priced by `services/checkout.py` from the site's snapshot, never the browser's numbers); site headers for pending/synced/status (own site only) | menu-app, local sites |
| `/api/manager` | `manager_auth.py` | manager bearer | manager-app, sysadmin |
| `/api/remote` | `remote_dashboard.py` | manager bearer; site headers for `POST /snapshot` | manager-app, local sites |