Files
xenia-pos-local/local_backend/tests/test_pos_refunds.py
T
bonaminandClaude Opus 5.5 f2182dcb37 feat(pos): refunds at the counter on a fiscal driver layer (platform-v2 3.3e)
- services/fiscal/: one driver interface (prepare_receipt / prepare_credit_note -> send,
  credit_notes flag, status); the dTEC100extra folder bridge moved into txt_file.py as the
  first driver, same command files. fiscal_service.py removed, callers moved.
- Refunds: models/refund.py + Alembic 0016 (refunds, refund_items; ordering.refunds for
  existing owners/managers). services/refunds.py: today's business day, the cashier's open
  shift, partial quantities, items from another shift need ordering.refunds or a manager's
  approval (check()/authorize() return the override row). Paid items are never edited.
- POS: GET /api/pos/receipts, GET /api/pos/receipts/{id}, POST /api/pos/orders/{id}/refund
  (cash opens the drawer; fiscal "manual" when the driver can't issue credit notes).
- Shift totals subtract refunds and now count discounts; day close and business-day
  reports carry refunds.
- Terminal: Receipts mode (ReceiptsView, ReceiptPanel, logic/refunds.js), en/el texts.
- Tests: test_pos_refunds.py (12), terminal unit +1, terminal.mjs +7.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 09:44:17 +02:00

239 lines
13 KiB
Python

"""Counter POS: refunds on a fiscal driver layer (plan step 3.3e, D-27).
Done when: a paid quick sale is refunded in cash at the counter, the drawer opens, the shift's
cash goes down by the amount; with fiscal on, the driver issues the credit note — or, for a
driver that can't (today's text-file bridge), the refund is marked for the cashier to issue on
the machine (owner decision 2026-11-15)."""
import time
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, sale, till # noqa: F401 (fixtures)
def refund(client, till, order_id, items, method="cash", headers=None, **extra):
return client.post(f"/api/pos/orders/{order_id}/refund", headers=headers or till["h"],
json={"items": items, "method": method, **extra})
def shift_of(client, till):
return client.get("/api/shifts/my", headers=till["h"]).json()
def fiscal_on(db, 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()
def wait_for(fn, tries=40):
for _ in range(tries):
if fn():
return True
time.sleep(0.05)
return False
def test_cash_refund_opens_the_drawer_and_lowers_the_shift(client, db, till, menu, on_shift, drawer_printer):
"""The done-when: a paid quick sale, refunded in cash at the counter."""
from models.order import OrderAuditLog, 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
order_id = r.json()["order_id"]
assert wait_for(lambda: len(drawer_printer) == 1)
assert shift_of(client, till)["net_to_deliver"] == 66.0 # 50 + 16
listed = client.get("/api/pos/receipts?scope=mine", headers=till["h"]).json()["orders"]
assert [(o["id"], o["paid"], o["refunded"], o["mine"]) for o in listed] == [(order_id, 16.0, 0.0, True)]
receipt = client.get(f"/api/pos/receipts/{order_id}", headers=till["h"]).json()
assert receipt["today"] is True and receipt["fiscal"] == {"enabled": False, "credit_notes": False}
coffee = next(i for i in receipt["items"] if i["name"] == "Freddo")
assert (coffee["quantity"], coffee["refundable"], coffee["unit_total"], coffee["mine"]) == (2, 2, 3.0, True)
# one of the two coffees comes back, in cash
r = refund(client, till, order_id, [{"item_id": coffee["id"], "quantity": 1}], reason="Spilled")
assert r.status_code == 201, r.text
body = r.json()
assert (body["amount"], body["method"], body["drawer"], body["fiscal"]) == (3.0, "cash", "opened", None)
assert wait_for(lambda: len(drawer_printer) == 2), "the drawer opened for the cash going back"
s = shift_of(client, till)
assert (s["cash_sales"], s["cash_refunds"], s["net_to_deliver"], s["total_collected"]) == (16.0, 3.0, 63.0, 13.0)
# the sale itself is untouched: the item stays paid, the refund is its own record
item = db.get(OrderItem, coffee["id"])
db.refresh(item)
assert item.status == "paid" and item.quantity == 2
audit = db.query(OrderAuditLog).filter(OrderAuditLog.order_id == order_id, OrderAuditLog.event_type == "REFUND").one()
assert audit.amount == 3.0 and audit.payment_method == "cash" and "Spilled" in audit.note
after = client.get(f"/api/pos/receipts/{order_id}", headers=till["h"]).json()
assert next(i for i in after["items"] if i["id"] == coffee["id"])["refundable"] == 1
assert [(x["amount"], x["method"], x["reason"]) for x in after["refunds"]] == [(3.0, "cash", "Spilled")]
# more than what's left is refused, and nothing is written
assert err(refund(client, till, order_id, [{"item_id": coffee["id"], "quantity": 2}])) == "refund.items_changed"
assert shift_of(client, till)["cash_refunds"] == 3.0
def test_card_refund_and_the_business_day(client, db, till, menu, on_shift, drawer_printer, owner_h):
m = menu
order_id = sale(client, till, [burger_line(m)], [{"method": "card"}]).json()["order_id"]
burger = client.get(f"/api/pos/receipts/{order_id}", headers=till["h"]).json()["items"][0]
r = refund(client, till, order_id, [{"item_id": burger["id"], "quantity": 1}], method="card")
assert r.status_code == 201 and r.json()["drawer"] == "none"
s = shift_of(client, till)
assert (s["card_sales"], s["card_refunds"], s["cash_refunds"], s["net_to_deliver"]) == (10.0, 10.0, 0.0, 50.0)
day = client.get("/api/reports/business-days/current", headers=owner_h).json()["business_day"]
assert day["refunds"] == {"amount": 10.0, "count": 1, "cash": 0.0, "card": 10.0}
def test_refund_checks(client, db, till, menu, on_shift):
from models.business_day import BusinessDay
from models.order import Order
from models.refund import Refund
m = menu
order_id = sale(client, till, [{"product_id": m["coffee"].id}], [{"method": "cash"}]).json()["order_id"]
item = client.get(f"/api/pos/receipts/{order_id}", headers=till["h"]).json()["items"][0]
assert err(refund(client, till, order_id, [{"item_id": item["id"], "quantity": 1}, {"item_id": item["id"], "quantity": 1}])) == "refund.invalid"
assert err(refund(client, till, order_id, [{"item_id": 99999, "quantity": 1}])) == "refund.invalid"
assert refund(client, till, order_id, [{"item_id": item["id"], "quantity": 0}]).status_code == 422
# an order of an earlier business day
old_day = BusinessDay(status="closed", opened_at=on_shift.started_at, business_date=on_shift.business_day.business_date,
opened_by_id=on_shift.waiter_id)
db.add(old_day)
db.flush()
db.get(Order, order_id).business_day_id = old_day.id
db.commit()
assert err(refund(client, till, order_id, [{"item_id": item["id"], "quantity": 1}])) == "refund.too_old"
assert db.query(Refund).count() == 0
def test_refund_needs_the_shift(client, db, till, menu, on_shift):
from core.timeutil import utcnow
m = menu
order_id = sale(client, till, [{"product_id": m["coffee"].id}], [{"method": "cash"}]).json()["order_id"]
item = client.get(f"/api/pos/receipts/{order_id}", headers=till["h"]).json()["items"][0]
on_shift.ended_at = utcnow()
db.commit()
assert err(refund(client, till, order_id, [{"item_id": item["id"], "quantity": 1}])) == "pos.shift_required"
def test_someone_elses_payment_needs_a_manager(client, db, pair, make_user, till, menu, on_shift):
"""Items paid in another shift: ordering.refunds, or a manager's approval on the spot
(recorded on the refund)."""
from models.refund import Refund
from models.shift import WaiterShift
m = menu
order_id = sale(client, till, [{"product_id": m["coffee"].id, "quantity": 3}], [{"method": "cash"}]).json()["order_id"]
item = client.get(f"/api/pos/receipts/{order_id}", headers=till["h"]).json()["items"][0]
# a second cashier at another till
token, _ = pair("pos_counter", "Till 2")
other = make_user(role="barista")
h2 = {"X-Xenia-Device": token, "Authorization": f"Bearer {terminal_login(client, token, other)}"}
db.add(WaiterShift(waiter_id=other.id, business_day_id=on_shift.business_day_id, starting_cash=0))
db.commit()
assert client.get("/api/pos/receipts?scope=mine", headers=h2).json()["orders"] == []
assert [o["id"] for o in client.get("/api/pos/receipts", headers=h2).json()["orders"]] == [order_id]
assert err(refund(client, till, order_id, [{"item_id": item["id"], "quantity": 1}], headers=h2)) == "access.override_possible"
manager = make_user(role="store_manager")
tok = client.post("/api/access/override", headers=h2,
json={"key": "ordering.refunds", "username": manager.username, "pin": TEST_PIN}).json()["override_token"]
r = refund(client, till, order_id, [{"item_id": item["id"], "quantity": 1}], headers=dict(h2, **{"X-Xenia-Override": tok}))
assert r.status_code == 201, r.text
row = db.get(Refund, r.json()["refund_id"])
assert row.approved_by == manager.id and row.refunded_by == other.id
# the money came out of the second cashier's drawer, not the first one's
s2 = client.get("/api/shifts/my", headers=h2).json()
assert (s2["cash_refunds"], s2["net_to_deliver"]) == (3.0, -3.0)
assert shift_of(client, till)["cash_refunds"] == 0.0
# a manager with the key at the counter doesn't need anyone's approval
boss = make_user(role="owner")
h3 = {"X-Xenia-Device": token, "Authorization": f"Bearer {terminal_login(client, token, boss)}"}
db.add(WaiterShift(waiter_id=boss.id, business_day_id=on_shift.business_day_id))
db.commit()
assert refund(client, till, order_id, [{"item_id": item["id"], "quantity": 1}], headers=h3).status_code == 201
def test_fiscal_driver_without_credit_notes_marks_it_manual(client, db, till, menu, on_shift, tmp_path):
"""Today's text-file bridge can't issue credit notes: the refund is recorded, nothing is
written to the bridge, and the counter is told to issue it on the machine."""
from models.refund import Refund
fiscal_on(db, tmp_path)
menu["coffee"].fiscal_vat_group_id = 2
db.commit()
order_id = sale(client, till, [{"product_id": menu["coffee"].id}], [{"method": "card"}]).json()["order_id"]
assert wait_for(lambda: (tmp_path / "out").exists() and len(list((tmp_path / "out").glob("*"))) == 1)
receipt = client.get(f"/api/pos/receipts/{order_id}", headers=till["h"]).json()
assert receipt["fiscal"] == {"enabled": True, "credit_notes": False}
r = refund(client, till, order_id, [{"item_id": receipt["items"][0]["id"], "quantity": 1}], method="card")
assert r.status_code == 201 and r.json()["fiscal"] == "manual"
time.sleep(0.2)
assert len(list((tmp_path / "out").glob("*"))) == 1, "no file for the refund: the bridge's command isn't known"
assert db.get(Refund, r.json()["refund_id"]).fiscal_status == "manual"
def test_fiscal_driver_with_credit_notes_issues_one(client, db, till, menu, on_shift, tmp_path, monkeypatch):
"""A driver that can (a future machine): the credit note goes through it in the background
with the refunded quantities, and the refund records the device's answer."""
from models.refund import Refund
from services import fiscal
from services.fiscal.base import FiscalDriver
issued = []
class Machine(FiscalDriver):
key, credit_notes = "test_machine", True
def prepare_receipt(self, db, items, method, total):
return lambda timeout: {"success": True, "reference": "R1", "reply": None, "error": None}
def prepare_credit_note(self, db, items, method, total, original=None):
def send(timeout):
issued.append((items, method, total, original))
return {"success": True, "reference": "CN-1", "reply": None, "error": None}
return send
monkeypatch.setitem(fiscal.DRIVERS, "test_machine", Machine())
stored = []
monkeypatch.setattr(fiscal, "_set_status", lambda *a: stored.append(a))
fiscal_on(db, tmp_path)
from models.settings import PosSettings
db.add(PosSettings(key="fiscal.type", value="test_machine")) if db.get(PosSettings, "fiscal.type") is None \
else setattr(db.get(PosSettings, "fiscal.type"), "value", "test_machine")
menu["coffee"].fiscal_vat_group_id = 2
db.commit()
order_id = sale(client, till, [{"product_id": menu["coffee"].id, "quantity": 2}], [{"method": "cash"}]).json()["order_id"]
item = client.get(f"/api/pos/receipts/{order_id}", headers=till["h"]).json()["items"][0]
r = refund(client, till, order_id, [{"item_id": item["id"], "quantity": 1}])
assert r.status_code == 201 and r.json()["fiscal"] == "pending"
assert wait_for(lambda: issued)
items, method, total, original = issued[0]
assert items == [{"name": "Freddo", "qty": 1, "unit_price": 3.0, "vat_group_id": 2}]
assert (method, total, original["order_id"]) == ("cash", 3.0, order_id)
# the answer is stored on the refund (by the thread's own session, so checked at the call)
assert wait_for(lambda: any(x[1] is Refund for x in stored))
assert next(x[1:] for x in stored if x[1] is Refund) == (Refund, r.json()["refund_id"], "success", "CN-1")
def test_receipt_driver_moved_without_behaviour_change(db, tmp_path):
"""The text-file bridge as a driver writes the same command file as before."""
from services import fiscal
from services.fiscal.txt_file import _build_command_file
fiscal_on(db, tmp_path)
assert fiscal.driver_for(db).key == "txt_file" and fiscal.status(db)["configured"] is True
content = _build_command_file([{"name": "Freddo", "qty": 2, "unit_price": 3.0, "vat_group_id": 2},
{"name": "Feta", "qty": 0.25, "unit_price": 12.0, "vat_group_id": 1}], "card", 10.5, db)
assert content == "FR\r\nSI|FREDDO|2|3.00|2\r\nSI|FETA|0.250|12.00|1\r\nCD|2|1|1|10.50\r\n"
@pytest.mark.parametrize("role,has", [("owner", True), ("store_manager", True), ("barista", False), ("waiter", False)])
def test_who_holds_the_refund_key(make_user, role, has):
from core.access.check import holds
assert holds(make_user(role=role), "ordering.refunds") is has