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
+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