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
+3
View File
@@ -66,6 +66,9 @@ CODES: dict[str, tuple[int, str]] = {
"auth.support_not_configured": (503, "Support access isn't set up on this site."),
"auth.support_code_invalid": (401, "That support code is wrong or has expired. Ask for a new challenge."),
"auth.support_rate_limited": (429, "Too many support challenges. Wait a few minutes and try again."),
"pos.shift_required": (409, "Start your shift before selling."),
"pos.payment_invalid": (422, "This payment doesn't add up ({reason})."),
"pos.fiscal_vat_missing": (422, "Fiscal receipts are on, but these products have no VAT group: {names}."),
"pos.line_invalid": (422, "Cart line {line} can't be sold as chosen ({reason})."),
"kds.item_not_found": (404, "Item {item_id} not found on this order."),
"kds.item_claimed": (409, "{name} is already on this item."),
+3
View File
@@ -77,6 +77,9 @@ def _can_access_order(order: Order, user: User, db: Session) -> bool:
Standalone orders (table_id=None) are accessible to all waiters with any zone assignment."""
if holds(user, "core.dashboard.access"):
return True
# Whoever the order is assigned to may act on it (e.g. a cashier's own counter sale, 3.3b)
if any(ow.waiter_id == user.id for ow in order.waiters):
return True
zones = db.query(WaiterZone).filter(WaiterZone.waiter_id == user.id).all()
if not zones:
return False
+99 -1
View File
@@ -3,6 +3,8 @@
GET /api/pos/session the signed-in cashier's shift and the business day (shift gate)
GET /api/pos/menu categories and products to sell, with options and today's price
POST /api/pos/quote a cart priced by the backend (services/pos_cart.py)
POST /api/pos/sales a quick sale (3.3b): order + items + payment(s) in one call, the
cash drawer on cash, the fiscal receipt as for any payment
Prices are never computed on the screen: the menu's `price` is the pricing engine's answer for
one unit with no options right now (happy hours, price groups), and the cart is priced with
@@ -150,11 +152,107 @@ def pos_quote(body: QuoteBody, db: Session = Depends(get_db), user=Depends(requi
priced = pos_cart.price_lines(db, lines, body.order_type) if lines else []
out = []
for line, (unit, events) in zip(lines, priced):
adj = pos_cart.discount_adjustment(unit, line.discount_pct)
out.append({
"product_id": line.product.id, "name": line.product.name, "quantity": line.quantity,
"base_price": round(line.product.base_price, 2), "extra": line.extra,
"unit_price": round(unit, 2), "total": round(unit * line.quantity, 2),
"discount_pct": line.discount_pct, "discount": adj,
"unit_price": round(unit + adj, 2), "total": round((unit + adj) * line.quantity, 2),
"entries": [{"name": e["name"], "price": e["price_delta"], "type": e["type"]} for e in line.entries],
"removed": line.removed, "notes": line.notes, "adjustments": _adjustments(db, events),
})
return {"order_type": body.order_type, "lines": out, "total": round(sum(x["total"] for x in out), 2)}
# ── quick sale (3.3b) ─────────────────────────────────────────────────────────
class Payment(BaseModel):
method: Literal["cash", "card"]
lines: Optional[List[int]] = None # indexes into `lines`; None = all of them
class SaleBody(BaseModel):
order_type: Literal["takeaway", "here"] = "takeaway"
lines: List[dict] = Field(min_length=1, max_length=200)
payments: List[Payment] = Field(min_length=1, max_length=2)
cash_given: Optional[float] = Field(default=None, ge=0, le=100000)
def _payment_groups(body: SaleBody, n: int) -> list:
if len(body.payments) == 1 and body.payments[0].lines is None:
return [(body.payments[0].method, list(range(n)))]
seen = [i for pay in body.payments for i in (pay.lines or [])]
if sorted(seen) != list(range(n)) or len({pay.method for pay in body.payments}) != len(body.payments):
raise XeniaError("pos.payment_invalid", reason="lines")
return [(pay.method, list(pay.lines)) for pay in body.payments if pay.lines]
@router.post("/sales", status_code=201)
def pos_sale(body: SaleBody, request: Request, db: Session = Depends(get_db), user=Depends(require(ACCESS))):
"""Sell the cart on the spot: open a takeaway / counter order (no table), add the lines
exactly as POST /api/orders/{id}/items would (prices, price events, deals, kitchen
tickets, KDS), take the payment(s) through POST /api/orders/{id}/pay (the cashier's
shift, the fiscal receipt, auto-close), and open the cash drawer of the screen's receipt
printer when cash was taken. The checks run before anything is written. Discounted lines
need ordering.prices.modify or a manager's approval (D-10)."""
from core.access.context import authorize, current_device
from core.modules import device_config
from models.order import OrderItem
from models.printer import Printer
from models.shift import WaiterShift
from models.user import User
from routers import orders as orders_api
from schemas.order import AddItemsRequest, OrderCreate, OrderItemInput, PayItemsRequest, SelectedOptionInput
from services.fiscal_service import is_fiscal_enabled
from services.printer_service import open_cash_drawer
if not isinstance(user, User) or db.query(WaiterShift).filter(
WaiterShift.waiter_id == user.id, WaiterShift.ended_at.is_(None)).first() is None:
raise XeniaError("pos.shift_required")
lines = [pos_cart.resolve_line(db, raw if isinstance(raw, dict) else {}, n) for n, raw in enumerate(body.lines)]
groups = _payment_groups(body, len(lines))
if any(line.discount_pct for line in lines):
authorize(request, db, user, "ordering.prices.modify", target="pos sale discount")
if is_fiscal_enabled(db):
missing = sorted({line.product.name for line in lines if not line.product.fiscal_vat_group_id})
if missing:
raise XeniaError("pos.fiscal_vat_missing", names=", ".join(missing))
priced = pos_cart.price_lines(db, lines, body.order_type)
adjs = [pos_cart.discount_adjustment(unit, line.discount_pct) for line, (unit, _) in zip(lines, priced)]
totals = [round((unit + adj) * line.quantity, 2) for line, (unit, _), adj in zip(lines, priced, adjs)]
cash_due = round(sum(totals[i] for method, idx in groups if method == "cash" for i in idx), 2)
if body.cash_given is not None and cash_due and body.cash_given + 0.004 < cash_due:
raise XeniaError("pos.payment_invalid", reason="cash_short")
order = orders_api.open_order(OrderCreate(table_id=None, order_type=body.order_type), db, user)
items_in = [OrderItemInput(
product_id=line.product.id, quantity=line.quantity,
selected_options=[SelectedOptionInput(**e) for e in line.entries] or None,
removed_ingredients=line.removed or None, notes=line.notes, price_adjustment=adj or None,
) for line, adj in zip(lines, adjs)]
added = orders_api.add_items(order.id, AddItemsRequest(items=items_in), db, user)
item_ids = [i.id for i in db.query(OrderItem).filter(OrderItem.order_id == order.id).order_by(OrderItem.id).all()]
paid, fiscal = [], None
for method, idx in groups:
res = orders_api.pay_items(order.id, PayItemsRequest(item_ids=[item_ids[i] for i in idx], payment_method=method), db, user)
paid.append({"method": method, "amount": round(sum(totals[i] for i in idx), 2), "item_ids": res["paid_item_ids"]})
fiscal = res.get("fiscal") or fiscal
drawer = "none"
if cash_due > 0:
dev = current_device(request, db)
cfg = device_config.effective(device_config.for_app("pos_counter"), dev.config if dev is not None else None, db)
printer = db.get(Printer, cfg["receipt_printer_id"]) if cfg.get("receipt_printer_id") else None
if printer is not None and printer.is_active:
ok, _ = open_cash_drawer(printer, db, reason=f"order {order.id}")
drawer = "opened" if ok else "failed"
orders_api._audit(db, order.id, "DRAWER_OPENED" if ok else "DRAWER_FAILED", waiter_id=user.id, note=printer.name)
db.commit()
change = round(body.cash_given - cash_due, 2) if body.cash_given is not None and cash_due else None
return {
"order_id": order.id, "total": round(sum(totals), 2), "payments": paid,
"cash_given": body.cash_given, "change": change, "drawer": drawer, "fiscal": fiscal,
"print_results": added.get("print_results", []), "deal_offers": added.get("deal_offers", []),
}
+17 -3
View File
@@ -20,7 +20,9 @@ Rules (the same as the waiter's options dialog, waiter_pwa ItemOptionsModal.jsx)
- quantities: per-choice qty only on multi-select sets, per-add-on qty only on allow_multiple.
Anything else → XeniaError("pos.line_invalid", line=n, reason=...), reason one of
product_unavailable | unknown_quick | unknown_option | unknown_choice | unknown_sub |
choice_required | sub_required | unknown_ingredient | quantity.
choice_required | sub_required | unknown_ingredient | quantity | discount.
A line may carry `discount_pct` (0–100, whole percent): the quote shows it; selling it needs
ordering.prices.modify or a manager's approval (routers/pos.py).
"""
from __future__ import annotations
@@ -61,6 +63,7 @@ class Line:
entries: list = field(default_factory=list) # selected_options entries
removed: list = field(default_factory=list) # ingredient names
notes: Optional[str] = None
discount_pct: int = 0 # 3.3b: needs ordering.prices.modify (or approval)
@property
def extra(self) -> float:
@@ -96,6 +99,10 @@ def resolve_line(db, raw: dict, n: int) -> Line:
if isinstance(quantity, bool) or not isinstance(quantity, (int, float)) or quantity <= 0 or quantity > 999:
raise _bad(n, "quantity")
line = Line(product=product, quantity=quantity, notes=(raw.get("notes") or "").strip() or None)
pct = raw.get("discount_pct", 0) or 0
if isinstance(pct, bool) or not isinstance(pct, int) or not 0 <= pct <= 100:
raise _bad(n, "discount")
line.discount_pct = pct
quick = {q.id: q for q in product.quick_options}
for sel in raw.get("quick") or []:
@@ -170,8 +177,8 @@ def resolve_line(db, raw: dict, n: int) -> Line:
def price_lines(db, lines: list[Line], order_type: str, existing_cart: list | None = None):
"""[(unit_price, [PriceEvent])] for each line, with the same context POST
/api/orders/{id}/items builds: the order's existing items plus this line (the other new
lines of the same batch don't count, as there)."""
/api/orders/{id}/items builds: the order's existing items, the lines before it in the
same batch (at their resolved price), and this line."""
from core.timeutil import utcnow
from services.pricing import OrderContext, build_active_price_group_ids, resolve_price
now = utcnow()
@@ -186,4 +193,11 @@ def price_lines(db, lines: list[Line], order_type: str, existing_cart: list | No
ctx = OrderContext(channel=channel, now=now, cart_items=cart + [here], active_price_group_ids=active)
unit, events = resolve_price(p, line.quantity, line.extra, ctx, db)
out.append((unit, events))
cart.append({**here, "unit_price": unit})
return out
def discount_adjustment(unit_price: float, pct) -> float:
"""A line's discount (percent of its unit price) as the order item's price_adjustment
(negative, rounded to cents)."""
return -round(unit_price * pct / 100.0, 2) if pct else 0.0
+21
View File
@@ -324,6 +324,27 @@ def send_test_beep(ip: str, port: int, n1: int, n2: int, n3: int, codepage_n: in
return False, str(e)
DRAWER_KICK = bytes([0x1b, 0x70, 0x00, 0x19, 0xfa]) # ESC p m t1 t2: pin 2, 50 ms on, 500 ms off
def open_cash_drawer(printer, db: Session, reason: str = "") -> Tuple[bool, str]:
"""Pulse the cash drawer wired to `printer` (counter POS cash payments, plan step 3.3b).
A job of its own: ESC @ then ESC p 0 25 250, nothing printed. Logs one line either way.
Spoof printing drops it like any print. -> (ok, error)"""
if _is_spoof_mode(db):
logger.info("Cash drawer: spoof printing ON, not sent to %s (%s)", printer.name, reason)
return True, ""
try:
p = Network(printer.ip_address, printer.port, timeout=PRINTER_TIMEOUT)
p._raw(bytes([0x1b, 0x40]) + DRAWER_KICK)
p.close()
logger.info("Cash drawer: opened on %s (%s:%s) %s", printer.name, printer.ip_address, printer.port, reason)
return True, ""
except Exception as e:
logger.warning("Cash drawer: FAILED on %s (%s:%s) %s: %s", printer.name, printer.ip_address, printer.port, reason, e)
return False, str(e)
def send_test_print(ip: str, port: int, name: str, codepage_n: int = 29) -> Tuple[bool, str]:
if is_spoof_mode():
logger.info("Spoof printing ON — dropping test print for %s", name)
+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"