feat(terminal): quick sale at the counter: cash/card/split, change, cash drawer, fiscal (platform-v2 3.3b)

- POST /api/pos/sales: all checks first (shift, lines, payment split, cash given,
  discount → ordering.prices.modify or manager approval, fiscal VAT groups), then the
  existing open_order / add_items / pay_items functions, so tickets, KDS, price events,
  shift totals and the fiscal receipt work as for any order.
- Cash drawer: printer_service.open_cash_drawer (ESC @ + ESC p 0 25 250) to the screen's
  receipt printer on cash, logged and audited (DRAWER_OPENED / DRAWER_FAILED).
- orders._can_access_order: the people assigned to an order may act on it (a cashier's
  own takeaway order); pos_cart prices a batch with the lines before it, as add_items does.
- Terminal: Charge → payment dialog (exact cash pre-selected, quick amounts, change,
  card, split by line), per-line discounts, sale summary and "Same again".
- Tests: backend +6 (socket printer receives the drawer kick, fiscal file in the bridge
  folder), terminal unit +1, terminal.mjs +9.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-15 00:28:33 +02:00
co-authored by Claude Opus 5.5
parent 17bee66df1
commit bff82a332a
15 changed files with 632 additions and 14 deletions
+152
View File
@@ -143,3 +143,155 @@ def test_pos_settings_validate_their_references(client, owner_h, till, menu):
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"