Files
xenia-pos-local/local_backend/tests/test_pos.py
T
bonaminandClaude Opus 5.5 17bee66df1 feat(terminal): counter POS screen with server-priced cart and shift gate (platform-v2 3.3a)
- Backend /api/pos (pos_counter): session (business day, the cashier's own shift,
  self-start, who can open the day), menu (sellable products with every kind of choice,
  no costs; price now from the pricing engine), quote (lines by id → the waiter's
  selected_options entries with DB prices → resolve_price as orders do; pos.line_invalid).
- POS device settings: default order type, start category, receipt printer (new ref
  sources categories / printers, also in the manager's Devices dialogs).
- Terminal apps/pos: shift gate (start shift with drawer cash), categories, search,
  product grid, price check, options dialog, cart priced by the backend.
- Tests: backend test_pos (13), terminal pos.test.mjs, manager refOptions,
  terminal.mjs +10 POS checks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 21:55:30 +02:00

146 lines
8.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Counter POS: menu, server-priced cart, shift gate (plan step 3.3a)."""
import json
import pytest
from tests.test_live import err, owner_h, pair, terminal_login # noqa: F401 (fixtures)
@pytest.fixture
def menu(db):
"""A burger with every kind of option, a coffee, an unavailable dish and a service item."""
from models.product import (Category, Product, ProductIngredient, ProductOption, ProductPreferenceChoice,
ProductPreferenceSet, ProductQuickOption)
food, drinks = Category(name="Food", sort_order=1), Category(name="Drinks", sort_order=2)
db.add_all([food, drinks])
db.flush()
burger = Product(name="Burger", base_price=10.0, primary_category_id=food.id, description="Beef, brioche",
tags=json.dumps(["spicy"]), cost_simple=3.5)
coffee = Product(name="Freddo", base_price=3.0, primary_category_id=drinks.id)
gone = Product(name="Old dish", base_price=5.0, primary_category_id=food.id, is_available=False)
cutlery = Product(name="Cutlery", base_price=0.0, primary_category_id=food.id, is_service_item=True)
db.add_all([burger, coffee, gone, cutlery])
db.flush()
db.add(ProductQuickOption(product_id=burger.id, name="Extra cheese", price=1.0, allow_multiple=True))
db.add(ProductOption(product_id=burger.id, name="Sauce", extra_cost=0.5,
sub_choices=json.dumps([{"name": "BBQ", "extra_cost": 0.2, "is_default": True}, {"name": "Mayo"}])))
db.add(ProductIngredient(product_id=burger.id, name="Onion"))
cook = ProductPreferenceSet(product_id=burger.id, name="Cooking",
shared_subset=json.dumps({"name": "Side", "choices": [{"name": "Fries", "is_default": True},
{"name": "Salad", "extra_cost": 1.0}]}))
db.add(cook)
db.flush()
rare = ProductPreferenceChoice(set_id=cook.id, name="Rare")
well = ProductPreferenceChoice(set_id=cook.id, name="Well done", extra_cost=0.5, disables_subset=True)
db.add_all([rare, well])
db.commit()
return {"food": food, "drinks": drinks, "burger": burger, "coffee": coffee, "cook": cook, "rare": rare, "well": well,
"gone": gone, "cutlery": cutlery}
@pytest.fixture
def till(client, pair, make_user):
token, r = pair("pos_counter", "Till")
assert r.status_code == 201, r.text
cashier = make_user(role="waiter")
jwt = terminal_login(client, token, cashier)
return {"h": {"X-Xenia-Device": token, "Authorization": f"Bearer {jwt}"}, "cashier": cashier, "id": r.json()["id"]}
def burger_line(m, **extra):
return {"product_id": m["burger"].id, "quantity": 1,
"prefs": [{"set_id": m["cook"].id, "choices": [{"id": m["rare"].id}], "shared": "Fries"}], **extra}
def test_menu_lists_what_a_cashier_sells(client, till, menu):
data = client.get("/api/pos/menu", headers=till["h"]).json()
names = [p["name"] for p in data["products"]]
assert "Burger" in names and "Freddo" in names and "Old dish" not in names and "Cutlery" not in names
burger = next(p for p in data["products"] if p["name"] == "Burger")
assert burger["price"] == 10.0 and burger["description"] == "Beef, brioche" and burger["tags"] == ["spicy"]
assert "cost_simple" not in burger and "cost_breakdown" not in burger
assert burger["options"][0]["subs"][0] == {"name": "BBQ", "price": 0.2, "is_default": True}
assert burger["prefs"][0]["shared"]["name"] == "Side" and burger["prefs"][0]["choices"][1]["disables_shared"] is True
assert {c["name"] for c in data["categories"]} >= {"Food", "Drinks"}
assert data["settings"]["default_order_type"] == "takeaway"
def test_quote_prices_on_the_server(client, till, menu):
m = menu
line = burger_line(m, quick=[{"id": m["burger"].quick_options[0].id, "qty": 2}],
options=[{"id": m["burger"].options[0].id, "subs": ["BBQ"]}],
removed=[m["burger"].ingredients[0].id], notes="no salt")
r = client.post("/api/pos/quote", headers=till["h"], json={"order_type": "takeaway", "lines": [line, {"product_id": m["coffee"].id, "quantity": 2}]})
assert r.status_code == 200, r.text
burger, coffee = r.json()["lines"]
# 10 + 2×1 cheese + 0.5 sauce + 0.2 BBQ + 0 rare + 0 fries
assert burger["unit_price"] == 12.7 and burger["total"] == 12.7
assert [e["name"] for e in burger["entries"]] == ["Extra cheese x2", "Sauce", "BBQ", "Rare", "Fries"]
assert burger["removed"] == ["Onion"] and burger["notes"] == "no salt"
assert coffee["total"] == 6.0 and r.json()["total"] == 18.7
# well done has no side
r = client.post("/api/pos/quote", headers=till["h"],
json={"lines": [{"product_id": m["burger"].id, "prefs": [{"set_id": m["cook"].id, "choices": [{"id": m["well"].id}]}]}]})
assert r.json()["lines"][0]["unit_price"] == 10.5
@pytest.mark.parametrize("bad,reason", [
(lambda m: {"product_id": m["burger"].id}, "choice_required"),
(lambda m: {"product_id": m["burger"].id, "prefs": [{"set_id": m["cook"].id, "choices": [{"id": m["rare"].id}]}]}, "sub_required"),
(lambda m: burger_line(m, options=[{"id": m["burger"].options[0].id}]), "sub_required"),
(lambda m: burger_line(m, options=[{"id": m["burger"].options[0].id, "subs": ["Ketchup"]}]), "unknown_sub"),
(lambda m: burger_line(m, options=[{"id": m["burger"].options[0].id, "subs": ["BBQ", "Mayo"]}]), "unknown_sub"),
(lambda m: burger_line(m, removed=[999999]), "unknown_ingredient"),
(lambda m: {"product_id": m["gone"].id}, "product_unavailable"),
(lambda m: {"product_id": m["coffee"].id, "quantity": 0}, "quantity"),
])
def test_quote_refuses_what_the_waiter_dialog_refuses(client, till, menu, bad, reason):
r = client.post("/api/pos/quote", headers=till["h"], json={"lines": [bad(menu)]})
assert r.status_code == 422 and r.json()["error"]["code"] == "pos.line_invalid"
assert r.json()["error"]["params"] == {"line": 0, "reason": reason}
def test_quote_applies_price_modifiers_like_orders(client, db, till, menu):
from models.pricing import PriceModifier
db.add(PriceModifier(name="Happy hour", scope="item", item_id=menu["coffee"].id, action_type="add_percent", action_value=-10, is_active=1))
db.commit()
line = client.post("/api/pos/quote", headers=till["h"], json={"lines": [{"product_id": menu["coffee"].id}]}).json()["lines"][0]
assert line["unit_price"] == 2.7 and line["adjustments"] == [{"label": "Happy hour", "delta": -0.3}]
coffee = next(p for p in client.get("/api/pos/menu", headers=till["h"]).json()["products"] if p["name"] == "Freddo")
assert coffee["price"] == 2.7 and coffee["base_price"] == 3.0
def test_session_shift_gate(client, db, till, make_user):
from models.business_day import BusinessDay
from models.settings import PosSettings
db.query(BusinessDay).filter(BusinessDay.status == "open").update({"status": "closed"})
db.commit()
boss = make_user(role="store_manager", nickname="Eleni")
s = client.get("/api/pos/session", headers=till["h"]).json()
assert s["business_day"] is None and s["shift"] is None and "Eleni" in s["day_openers"]
assert client.post("/api/business-day/open", headers=till["h"], json={}).status_code in (401, 403) # not from the till
# the day opens elsewhere; self-start allowed → the cashier starts their own shift
from core.timeutil import utcnow, business_date_of
db.add(BusinessDay(status="open", opened_at=utcnow(), business_date=business_date_of(utcnow()), opened_by_id=boss.id))
row = db.get(PosSettings, "shifts.waiter_self_start")
if row is None:
db.add(PosSettings(key="shifts.waiter_self_start", value="true"))
else:
row.value = "true"
db.commit()
s = client.get("/api/pos/session", headers=till["h"]).json()
assert s["business_day"] is not None and s["self_start"] is True and s["shift"] is None
r = client.post("/api/shifts/start", headers=till["h"], json={"starting_cash": 50})
assert r.status_code == 201, r.text
s = client.get("/api/pos/session", headers=till["h"]).json()
assert s["shift"]["starting_cash"] == 50
def test_pos_settings_validate_their_references(client, owner_h, till, menu):
ok = client.patch(f"/api/devices/{till['id']}", headers=owner_h,
json={"config": {"default_order_type": "here", "start_category_id": menu["drinks"].id}})
assert ok.status_code == 200 and ok.json()["config"]["start_category_id"] == menu["drinks"].id
assert err(client.patch(f"/api/devices/{till['id']}", headers=owner_h,
json={"config": {"receipt_printer_id": 999999}})) == "validation.device_config"
assert client.get("/api/pos/menu", headers=till["h"]).json()["settings"]["default_order_type"] == "here"