feat(ordering): orders priced by the server (platform-v2 step 4.4)

The waiter app (and the manager's ordering tab) send what was chosen, by id; the
server prices it with the counter's code. No app sends a price any more.

- POST /api/orders/{id}/items takes `lines` (pos_cart's line + course_id,
  price_adjustment, is_service_item): sales point checked first, refusals name the
  product and line (order.line.*, order.not_sold_here); prices or selected_options in a
  line -> order.line.client_price, the old `items` shape -> order.lines_required; a
  by-hand price change needs ordering.prices.modify or a manager's approval (audited
  PRICE_SET_BY_HAND). add_priced_items is the one writer of priced items (pos too).
- POST /api/orders/quote: the cart's total before sending; /api/pos/quote shares
  pos_cart.quote().
- pos_cart: a preference set left out takes its default; a set at its free default
  isn't stored; a default that costs is charged (the waiter never sent it: fixed);
  an extra's sub-choice is charged per extra (the counter charged it once: fixed).
- @xenia/api lines.js: lineFromOptions / wireLine / estimate / LineError.
- Waiter: lines on send; cart total from the quote ("≈ estimate" offline); summary
  shows the same prices; offline orders queued by id, priced on sync, refused lines
  shown on a "Δεν στάλθηκαν" sheet (no empty order opened); dead ItemOptionsModal gone.
- Tests: test_order_lines.py (14), lines.test.mjs, waiter e2e +6.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-17 03:35:03 +02:00
co-authored by Claude Opus 5.5
parent bcf91bf6e9
commit 8e0a786bbc
25 changed files with 1052 additions and 656 deletions
+1 -1
View File
@@ -65,7 +65,7 @@ def test_the_fee_is_its_own_line_and_never_reaches_the_kitchen(client, db, count
assert product.id not in [p["id"] for p in client.get("/api/pos/menu", headers=counter["h"]).json()["products"]]
assert client.put(f"/api/products/{product.id}", headers=owner_h, json={"name": "x"}).status_code == 404
assert err(client.post(f"/api/orders/{oid}/items", headers=owner_h,
json={"items": [{"product_id": product.id, "quantity": 1}]})) == "order.not_sold_here"
json={"lines": [{"product_id": product.id, "quantity": 1}]})) == "order.line.product_unavailable"
# the board: the time, the area, the fee
o = board(client, counter)["incoming"][0]
assert (o["requested_for"], o["area"], o["fee"], o["total"], o["price_diff"]) == ("2026-11-16T19:30:00+00:00", "Centre", 2.5, 27.5, None)
+186
View File
@@ -0,0 +1,186 @@
"""Orders priced by the server (plan step 4.4).
The waiter app sends what was chosen by id (services/pos_cart.py's line) to POST
/api/orders/{id}/items, exactly like the counter; the server prices it. Prices from an app
are refused, a by-hand price change needs ordering.prices.modify or a manager's PIN, and the
cart's total before sending comes from POST /api/orders/quote.
"""
import json
import pytest
from conftest import TEST_PIN
from tests.test_live import err, owner_h, pair, terminal_login # noqa: F401 (fixtures)
from tests.test_pos import burger_line, drawer_printer, menu, on_shift, till # noqa: F401 (fixtures)
from tests.test_pos_tables import floor, phone # noqa: F401 (fixtures)
@pytest.fixture(autouse=True)
def _no_printing(monkeypatch):
import routers.orders as orders
monkeypatch.setattr(orders, "route_and_print_sync", lambda *a, **k: [])
@pytest.fixture
def full(db, menu):
"""The test menu's burger plus: a 'Bread' set with a default (the usual costs nothing), a
'Size' set whose default costs 1.00, and an extra that can be taken more than once."""
from models.product import ProductOption, ProductPreferenceChoice, ProductPreferenceSet
b = menu["burger"]
bread = ProductPreferenceSet(product_id=b.id, name="Bread")
size = ProductPreferenceSet(product_id=b.id, name="Size")
db.add_all([bread, size])
db.flush()
brioche = ProductPreferenceChoice(set_id=bread.id, name="Brioche",
sub_choices=json.dumps([{"name": "Toasted", "is_default": True}, {"name": "Soft"}]))
rye = ProductPreferenceChoice(set_id=bread.id, name="Rye", extra_cost=0.3)
double = ProductPreferenceChoice(set_id=size.id, name="Double", extra_cost=1.0)
single = ProductPreferenceChoice(set_id=size.id, name="Single")
db.add_all([brioche, rye, double, single])
db.flush()
bread.default_choice_id, size.default_choice_id = brioche.id, double.id
pickles = ProductOption(product_id=b.id, name="Pickles", extra_cost=0.4, allow_multiple=True,
sub_choices=json.dumps([{"name": "Sweet", "extra_cost": 0.1}, {"name": "Sour"}]))
db.add(pickles)
db.commit()
return {**menu, "bread": bread, "size": size, "brioche": brioche, "rye": rye, "double": double, "single": single,
"pickles": pickles}
def every_kind(m):
"""One burger with every kind of choice (the same line from the phone and the counter)."""
b = m["burger"]
return burger_line(
m, quantity=2, notes="no salt",
quick=[{"id": b.quick_options[0].id, "qty": 2}],
options=[{"id": b.options[0].id, "subs": ["BBQ"]}, {"id": m["pickles"].id, "qty": 2, "subs": ["Sweet"]}],
removed=[b.ingredients[0].id],
prefs=[{"set_id": m["cook"].id, "choices": [{"id": m["rare"].id}], "shared": "Salad"},
{"set_id": m["bread"].id, "choices": [{"id": m["rye"].id}]}])
def open_order(client, h, table=None, order_type="here"):
r = client.post("/api/orders/", headers=h, json={"table_id": table.id if table else None, "order_type": order_type})
assert r.status_code == 201, r.text
return r.json()["id"]
def items_of(db, order_id):
from models.order import OrderItem
db.expire_all()
return db.query(OrderItem).filter(OrderItem.order_id == order_id).order_by(OrderItem.id).all()
def test_same_price_from_the_phone_and_the_counter(client, db, full, till, phone, floor):
m = full
# 10 + cheese 2×1 + sauce 0.5 + BBQ 0.2 + pickles 2×(0.4 + 0.1) + rare 0 + salad 1 + rye 0.3 + double 1 (default, costs)
want = 10 + 2 + 0.5 + 0.2 + 1.0 + 1.0 + 0.3 + 1.0
oid = open_order(client, phone["h"], floor["t1"])
r = client.post(f"/api/orders/{oid}/items", headers=phone["h"], json={"lines": [every_kind(m)]})
assert r.status_code == 200, r.text
from_phone = items_of(db, oid)[0]
r = client.post(f"/api/pos/tables/{floor['t2'].id}/items", headers=till["h"], json={"lines": [every_kind(m)]})
assert r.status_code == 201, r.text
from_counter = items_of(db, r.json()["order_id"])[0]
assert from_phone.unit_price == from_counter.unit_price == pytest.approx(want)
assert from_phone.selected_options == from_counter.selected_options
names = [e["name"] for e in json.loads(from_phone.selected_options)]
# the cheaper default ("Brioche · Toasted") isn't stored; a default that costs ("Double") is
assert names == ["Extra cheese x2", "Sauce", "BBQ", "Pickles x2", "Sweet x2", "Rare", "Salad", "Rye", "Double"]
assert json.loads(from_phone.removed_ingredients) == ["Onion"] and from_phone.notes == "no salt"
# the quote said the same before sending
q = client.post("/api/orders/quote", headers=phone["h"], json={"order_id": oid, "lines": [every_kind(m)]}).json()
assert q["lines"][0]["unit_price"] == pytest.approx(want) and q["total"] == pytest.approx(want * 2)
def test_a_set_left_out_takes_its_default(client, db, full, phone, floor):
m = full
oid = open_order(client, phone["h"], floor["t1"])
line = {"product_id": m["burger"].id, "prefs": [{"set_id": m["cook"].id, "choices": [{"id": m["well"].id}]}]}
assert client.post(f"/api/orders/{oid}/items", headers=phone["h"], json={"lines": [line]}).status_code == 200
item = items_of(db, oid)[0]
# 10 + well done 0.5 + double 1 (Bread and Size left out: their defaults)
assert item.unit_price == pytest.approx(11.5)
assert [e["name"] for e in json.loads(item.selected_options)] == ["Well done", "Double"]
# a set without a default can't be left out
r = client.post(f"/api/orders/{oid}/items", headers=phone["h"], json={"lines": [{"product_id": m["burger"].id}]})
assert err(r) == "order.line.choice_missing" and r.json()["error"]["params"]["name"] == "Burger"
@pytest.mark.parametrize("tamper", [
{"selected_options": [{"id": None, "name": "Gold leaf", "price_delta": -9.0, "type": "extra"}]},
{"unit_price": 0.01},
{"price_delta": -5},
])
def test_prices_from_the_app_are_refused(client, db, full, phone, floor, tamper):
oid = open_order(client, phone["h"], floor["t1"])
r = client.post(f"/api/orders/{oid}/items", headers=phone["h"], json={"lines": [{**burger_line(full), **tamper}]})
assert r.status_code == 422 and err(r) == "order.line.client_price"
assert r.json()["error"]["params"]["line"] == 1
assert items_of(db, oid) == []
def test_the_old_shape_is_refused(client, db, full, phone, floor):
oid = open_order(client, phone["h"], floor["t1"])
r = client.post(f"/api/orders/{oid}/items", headers=phone["h"],
json={"items": [{"product_id": full["coffee"].id, "quantity": 1, "price_adjustment": -3}]})
assert err(r) == "order.lines_required" and items_of(db, oid) == []
def test_a_price_set_by_hand_needs_the_key_or_a_managers_pin(client, db, full, phone, floor, make_user):
from models.order import OrderAuditLog
oid = open_order(client, phone["h"], floor["t1"])
line = {"product_id": full["coffee"].id, "quantity": 1, "price_adjustment": -1.0}
url = f"/api/orders/{oid}/items"
r = client.post(url, headers=phone["h"], json={"lines": [line]})
assert r.status_code == 403 and err(r) == "access.override_possible"
assert r.json()["error"]["params"]["key"] == "ordering.prices.modify" and items_of(db, oid) == []
boss = make_user(role="owner")
a = client.post("/api/access/override", headers=phone["h"],
json={"key": "ordering.prices.modify", "username": boss.username, "pin": TEST_PIN})
assert a.status_code == 200, a.text
r = client.post(url, headers=dict(phone["h"], **{"X-Xenia-Override": a.json()["override_token"]}), json={"lines": [line]})
assert r.status_code == 200, r.text
item = items_of(db, oid)[0]
assert item.unit_price == 3.0 and item.price_adjustment == -1.0
log = db.query(OrderAuditLog).filter(OrderAuditLog.event_type == "PRICE_SET_BY_HAND").one()
assert "override #" in log.note
# out of range → refused whoever asks
r = client.post(url, headers=dict(phone["h"]), json={"lines": [{**line, "price_adjustment": 1e9}]})
assert err(r) == "order.line.price"
@pytest.mark.parametrize("bad,code", [
(lambda m: burger_line(m, options=[{"id": 999999}]), "order.line.option_gone"),
(lambda m: burger_line(m, removed=[999999]), "order.line.option_gone"),
(lambda m: {"product_id": m["gone"].id}, "order.line.product_unavailable"),
(lambda m: {"product_id": m["coffee"].id, "quantity": 0}, "order.line.quantity"),
(lambda m: burger_line(m, quick=[{"id": m["burger"].quick_options[0].id, "qty": 1.5}]), "order.line.quantity"),
])
def test_refusals_name_the_product_and_the_line(client, db, full, phone, floor, bad, code):
oid = open_order(client, phone["h"], floor["t1"])
good = {"product_id": full["coffee"].id, "quantity": 1}
r = client.post(f"/api/orders/{oid}/items", headers=phone["h"], json={"lines": [good, bad(full)]})
assert r.status_code == 422 and err(r) == code
assert r.json()["error"]["params"]["line"] == 2 and items_of(db, oid) == [] # nothing half-added
def test_quote_for_a_new_order_and_its_sales_point(client, db, full, phone):
from tests.test_sales_points import takeaway_price
takeaway_price(db, full["coffee"], 2.7)
line = {"product_id": full["coffee"].id, "quantity": 2}
here = client.post("/api/orders/quote", headers=phone["h"], json={"lines": [line]}).json()
away = client.post("/api/orders/quote", headers=phone["h"], json={"order_type": "takeaway", "lines": [line]}).json()
assert here["total"] == 6.0 and away["total"] == pytest.approx(5.4)
assert err(client.post("/api/orders/quote", headers=phone["h"], json={"lines": [{**line, "price_delta": 1}]})) == "order.line.client_price"
def test_service_items_and_courses_still_work(client, db, full, phone, floor):
oid = open_order(client, phone["h"], floor["t1"])
r = client.post(f"/api/orders/{oid}/items", headers=phone["h"], json={"lines": [
{"product_id": full["cutlery"].id, "quantity": 2, "is_service_item": True}, # priceless: printed, not saved
{"product_id": full["coffee"].id, "quantity": 1, "course_id": 2},
]})
assert r.status_code == 200, r.text
items = items_of(db, oid)
assert [(i.product_id, i.course_id) for i in items] == [(full["coffee"].id, 2)]
+3 -3
View File
@@ -67,7 +67,7 @@ def test_tables_follow_the_cashiers_zones(client, db, till, floor, phone, menu):
assert by_name["Corner"]["flags"] == [{"id": flag.id, "name": "VIP", "emoji": "⭐", "color": "#aa0000", "text_color": None}]
# the waiter opens T1 on the phone; the counter sees it with totals and who is on it
o = client.post("/api/orders/", headers=phone["h"], json={"table_id": floor["t1"].id}).json()
client.post(f"/api/orders/{o['id']}/items", headers=phone["h"], json={"items": [{"product_id": menu["coffee"].id, "quantity": 2}]})
client.post(f"/api/orders/{o['id']}/items", headers=phone["h"], json={"lines": [{"product_id": menu["coffee"].id, "quantity": 2}]})
t1 = tables(client, till)[0]["T1"]["order"]
assert t1["id"] == o["id"] and t1["total"] == 6.0 and t1["unpaid"] == 6.0 and t1["items"] == 1
assert t1["people"] == ["Maria"] and t1["mine"] is False
@@ -85,7 +85,7 @@ def test_counter_and_phone_share_a_table(client, db, till, floor, phone, menu, e
seen = client.get(f"/api/orders/{oid}", headers=phone["h"]).json()
assert [i["product_name"] for i in seen["items"]] == ["Freddo"]
assert client.post(f"/api/orders/{oid}/items", headers=phone["h"],
json={"items": [{"product_id": m["coffee"].id, "quantity": 1}]}).status_code == 200
json={"lines": [{"product_id": m["coffee"].id, "quantity": 1}]}).status_code == 200
# the counter adds a burger to the same order (not a second one)
assert send(client, till, floor["t1"], [burger_line(m)]).json()["order_id"] == oid
t1 = tables(client, till)[0]["T1"]["order"]
@@ -125,7 +125,7 @@ def test_tables_outside_the_zones_are_refused(client, db, till, floor, menu, on_
db.commit()
h = login(nikos, "waiter")
o = client.post("/api/orders/", headers=h, json={"table_id": floor["t3"].id}).json()
client.post(f"/api/orders/{o['id']}/items", headers=h, json={"items": [{"product_id": menu["coffee"].id, "quantity": 1}]})
client.post(f"/api/orders/{o['id']}/items", headers=h, json={"lines": [{"product_id": menu["coffee"].id, "quantity": 1}]})
item = client.get(f"/api/orders/{o['id']}", headers=h).json()["items"][0]["id"]
assert err(client.post("/api/pos/quote", headers=till["h"], json={"order_id": o["id"], "lines": []})) == "pos.table_not_yours"
assert err(client.post(f"/api/pos/orders/{o['id']}/pay", headers=till["h"],
+1 -1
View File
@@ -85,7 +85,7 @@ def test_waiter_orders_follow_the_sales_point(client, db, make_user, login, menu
assert "Burger" in [p["name"] for p in client.get("/api/products/", headers=h).json()] # no filter: as before
order = client.post("/api/orders/", headers=h, json={"table_id": None, "order_type": "here"}).json()
assert db.get(Order, order["id"]).sales_point == "in_store"
r = client.post(f"/api/orders/{order['id']}/items", headers=h, json={"items": [{"product_id": menu["burger"].id, "quantity": 1}]})
r = client.post(f"/api/orders/{order['id']}/items", headers=h, json={"lines": [{"product_id": menu["burger"].id, "quantity": 1}]})
assert err(r) == "order.not_sold_here"