"""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, "translations": {}} 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_menu_carries_every_name_per_language_lines_keep_the_venues(client, db, till, menu, on_shift): """6R.L: the counter gets each text per language to show in the cashier's language; what it sends is ids (and sub-choices by their stored name), so the order keeps the venue's text.""" from models.order import OrderItem m = menu m["burger"].translations = json.dumps({"el": {"name": "Μπέργκερ", "description": "Μοσχάρι"}, "en": {"name": "Burger"}}) m["food"].translations = json.dumps({"el": {"name": "Φαγητό"}}) m["rare"].translations = json.dumps({"el": "Λίγο ψημένο"}) m["cook"].translations = json.dumps({"el": "Ψήσιμο"}) m["cook"].shared_subset = json.dumps({"name": "Side", "translations": {"el": "Συνοδευτικό"}, "choices": [{"name": "Fries", "is_default": True, "translations": {"el": "Πατάτες"}}, {"name": "Salad", "extra_cost": 1.0}]}) db.commit() data = client.get("/api/pos/menu", headers=till["h"]).json() burger = next(p for p in data["products"] if p["id"] == m["burger"].id) assert burger["translations"]["el"] == {"name": "Μπέργκερ", "description": "Μοσχάρι"} pref = burger["prefs"][0] assert pref["translations"] == {"el": "Ψήσιμο"} and pref["shared"]["translations"] == {"el": "Συνοδευτικό"} assert pref["shared"]["subs"][0]["translations"] == {"el": "Πατάτες"} and pref["shared"]["subs"][1]["translations"] == {} assert next(c for c in pref["choices"] if c["id"] == m["rare"].id)["translations"] == {"el": "Λίγο ψημένο"} assert next(c for c in data["categories"] if c["id"] == m["food"].id)["translations"] == {"el": {"name": "Φαγητό"}} assert burger["quick"][0]["translations"] == {} and burger["ingredients"][0]["translations"] == {} r = sale(client, till, [burger_line(m)], [{"method": "cash"}], cash_given=20) assert r.status_code == 201, r.text item = db.query(OrderItem).filter(OrderItem.order_id == r.json()["order_id"]).one() assert [o["name"] for o in json.loads(item.selected_options)] == ["Rare", "Fries"] # the stored names, not a translation 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" # ── quick sale (3.3b) ──────────────────────────────────────────────────────── import socket import threading import time @pytest.fixture def on_shift(db, till, make_user): """An open business day and the cashier's own shift with 50 in the drawer.""" from core.timeutil import business_date_of, utcnow from models.business_day import BusinessDay from models.shift import WaiterShift day = db.query(BusinessDay).filter(BusinessDay.status == "open").first() if day is None: day = BusinessDay(status="open", opened_at=utcnow(), business_date=business_date_of(utcnow()), opened_by_id=make_user(role="owner").id) db.add(day) db.flush() shift = WaiterShift(waiter_id=till["cashier"].id, business_day_id=day.id, starting_cash=50) db.add(shift) db.commit() return shift @pytest.fixture def drawer_printer(db, client, owner_h, till): """A printer on a local socket that records what it gets; the till's receipt printer.""" from models.printer import Printer srv = socket.socket() srv.bind(("127.0.0.1", 0)) srv.listen(4) got = [] def serve(): while True: try: conn, _ = srv.accept() except OSError: return data = b"" while chunk := conn.recv(1024): data += chunk got.append(data) conn.close() threading.Thread(target=serve, daemon=True).start() printer = Printer(name="Counter receipt", ip_address="127.0.0.1", port=srv.getsockname()[1], is_active=True) db.add(printer) db.commit() assert client.patch(f"/api/devices/{till['id']}", headers=owner_h, json={"config": {"receipt_printer_id": printer.id}}).status_code == 200 yield got srv.close() def sale(client, till, lines, payments, **extra): return client.post("/api/pos/sales", headers=till["h"], json={"order_type": "takeaway", "lines": lines, "payments": payments, **extra}) def test_cash_sale_pays_gives_change_and_opens_the_drawer(client, db, till, menu, on_shift, drawer_printer): from models.order import OrderItem m = menu r = sale(client, till, [burger_line(m), {"product_id": m["coffee"].id, "quantity": 2}], [{"method": "cash"}], cash_given=20) assert r.status_code == 201, r.text body = r.json() assert body["total"] == 16.0 and body["change"] == 4.0 and body["drawer"] == "opened" for _ in range(20): if drawer_printer: break time.sleep(0.05) assert drawer_printer and drawer_printer[0].endswith(bytes([0x1b, 0x70, 0x00, 0x19, 0xfa])) # ESC p 0 25 250 items = db.query(OrderItem).filter(OrderItem.order_id == body["order_id"]).order_by(OrderItem.id).all() assert [i.status for i in items] == ["paid", "paid"] and {i.payment_method for i in items} == {"cash"} assert {i.paid_in_shift_id for i in items} == {on_shift.id} # the burger's choices were stored as the waiter app stores them, with the database's prices assert json.loads(items[0].selected_options) == [{"id": m["rare"].id, "name": "Rare", "price_delta": 0.0, "extra_cost": None, "type": "pref"}, {"id": None, "name": "Fries", "price_delta": 0.0, "extra_cost": None, "type": "pref_sub"}] shift = client.get("/api/shifts/my", headers=till["h"]).json() assert shift["cash_sales"] == 16.0 and shift["net_to_deliver"] == 66.0 def test_card_and_split_payments(client, db, till, menu, on_shift, drawer_printer): m = menu r = sale(client, till, [{"product_id": m["coffee"].id}], [{"method": "card"}]) assert r.status_code == 201 and r.json()["drawer"] == "none" and r.json()["change"] is None r = sale(client, till, [burger_line(m), {"product_id": m["coffee"].id}], [{"method": "card", "lines": [0]}, {"method": "cash", "lines": [1]}], cash_given=5) assert r.status_code == 201, r.text assert [(p["method"], p["amount"]) for p in r.json()["payments"]] == [("card", 10.0), ("cash", 3.0)] assert r.json()["change"] == 2.0 and r.json()["drawer"] == "opened" shift = client.get("/api/shifts/my", headers=till["h"]).json() assert (shift["cash_sales"], shift["card_sales"]) == (3.0, 13.0) def test_sale_checks_run_before_anything_is_written(client, db, till, menu, on_shift): from models.order import Order before = db.query(Order).count() m = menu assert err(sale(client, till, [{"product_id": m["coffee"].id}], [{"method": "cash"}], cash_given=1)) == "pos.payment_invalid" assert err(sale(client, till, [{"product_id": m["coffee"].id}, {"product_id": m["coffee"].id}], [{"method": "cash", "lines": [0]}, {"method": "card", "lines": [0]}])) == "pos.payment_invalid" assert err(sale(client, till, [{"product_id": m["burger"].id}], [{"method": "cash"}])) == "pos.line_invalid" # a discount needs ordering.prices.modify, or a manager's approval assert err(sale(client, till, [{"product_id": m["coffee"].id, "discount_pct": 10}], [{"method": "card"}])) == "access.override_possible" assert db.query(Order).count() == before def test_a_manager_can_sell_with_a_discount(client, pair, make_user, menu, db): from core.timeutil import business_date_of, utcnow from models.business_day import BusinessDay from models.shift import WaiterShift token, _ = pair("pos_counter", "Till 2") boss = make_user(role="owner") h = {"X-Xenia-Device": token, "Authorization": f"Bearer {terminal_login(client, token, boss)}"} day = db.query(BusinessDay).filter(BusinessDay.status == "open").first() or BusinessDay( status="open", opened_at=utcnow(), business_date=business_date_of(utcnow()), opened_by_id=boss.id) db.add(day) db.flush() db.add(WaiterShift(waiter_id=boss.id, business_day_id=day.id)) db.commit() q = client.post("/api/pos/quote", headers=h, json={"lines": [{"product_id": menu["coffee"].id, "discount_pct": 10}]}).json() assert q["lines"][0]["unit_price"] == 2.7 and q["lines"][0]["discount"] == -0.3 r = client.post("/api/pos/sales", headers=h, json={"lines": [{"product_id": menu["coffee"].id, "discount_pct": 10}], "payments": [{"method": "card"}]}) assert r.status_code == 201 and r.json()["total"] == 2.7 def test_sale_needs_the_cashiers_shift(client, till, menu): assert err(sale(client, till, [{"product_id": menu["coffee"].id}], [{"method": "card"}])) == "pos.shift_required" def test_fiscal_receipt_follows_the_payment(client, db, till, menu, on_shift, tmp_path): from models.settings import PosSettings for key, value in (("fiscal.enabled", "true"), ("fiscal.out_folder", str(tmp_path / "out")), ("fiscal.in_folder", str(tmp_path / "in"))): row = db.get(PosSettings, key) if row is None: db.add(PosSettings(key=key, value=value)) else: row.value = value db.commit() assert err(sale(client, till, [{"product_id": menu["coffee"].id}], [{"method": "cash"}])) == "pos.fiscal_vat_missing" menu["coffee"].fiscal_vat_group_id = 2 db.commit() r = sale(client, till, [{"product_id": menu["coffee"].id}], [{"method": "cash"}]) assert r.status_code == 201 and r.json()["fiscal"] == "pending" for _ in range(40): files = list((tmp_path / "out").glob("*")) if (tmp_path / "out").exists() else [] if files: break time.sleep(0.05) assert files, "the fiscal file was written to the bridge's OUT folder"