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>
This commit is contained in:
2026-11-15 09:44:17 +02:00
co-authored by Claude Opus 5.5
parent d542cf7d34
commit f2182dcb37
32 changed files with 1486 additions and 169 deletions
+144
View File
@@ -0,0 +1,144 @@
"""Fiscal receipts and credit notes behind one driver interface (plan step 3.3e, D-27).
from services import fiscal
fiscal.is_fiscal_enabled(db) # the master switch (setting fiscal.enabled)
fiscal.driver_for(db) # the venue's driver (setting fiscal.type)
fiscal.validate_items_for_fiscal(...) # products without a VAT group
fiscal.build_fiscal_items(order_items) # OrderItems → the dicts drivers take
fiscal.send_fiscal_receipt_background(...) # issue + order.fiscal_status, off the request
fiscal.can_issue_credit_notes(db) # False → the cashier issues it on the machine
Drivers: services/fiscal/base.py (the interface), txt_file.py (dTEC100extra folder bridge).
A new machine is a new module listed in DRIVERS.
"""
from __future__ import annotations
import logging
import threading
from services.fiscal.base import FiscalDriver
from services.fiscal.txt_file import TxtFileDriver
logger = logging.getLogger(__name__)
DRIVERS: dict[str, FiscalDriver] = {d.key: d for d in (TxtFileDriver(),)}
DEFAULT_DRIVER = "txt_file"
def _setting(db, key: str, default: str = "") -> str:
from models.settings import PosSettings
row = db.query(PosSettings).filter(PosSettings.key == key).first()
return row.value if row else default
def is_fiscal_enabled(db) -> bool:
return _setting(db, "fiscal.enabled", "false") == "true"
def driver_for(db) -> FiscalDriver:
"""The venue's driver (`fiscal.type`); an unknown type falls back to the default driver."""
key = (_setting(db, "fiscal.type", DEFAULT_DRIVER) or DEFAULT_DRIVER).strip()
driver = DRIVERS.get(key)
if driver is None:
logger.warning("Fiscal: unknown fiscal.type %r, using %s", key, DEFAULT_DRIVER)
driver = DRIVERS[DEFAULT_DRIVER]
return driver
def can_issue_credit_notes(db) -> bool:
return driver_for(db).credit_notes
def status(db) -> dict:
"""What a screen needs to know: {"enabled", "driver", "credit_notes", "configured"}."""
driver = driver_for(db)
return {"enabled": is_fiscal_enabled(db), "driver": driver.key, "credit_notes": driver.credit_notes,
"configured": driver.status(db)["configured"]}
def validate_items_for_fiscal(order_items, db=None) -> list[str]:
"""Names of the products without a fiscal_vat_group_id among these items (empty = all OK)."""
missing = []
for item in order_items:
product = item.product
if product is None:
missing.append(f"#product_{item.product_id}")
continue
if not getattr(product, "fiscal_vat_group_id", None):
missing.append(product.name)
return missing
def build_fiscal_items(order_items, quantities: dict[int, float] | None = None) -> list[dict]:
"""OrderItems → driver item dicts. Uses fiscal_name if set, else the product's name; the
unit price includes the item's price_adjustment. `quantities` {item_id: qty} overrides the
quantity (a partial refund)."""
result = []
for item in order_items:
product = item.product
name = (getattr(product, "fiscal_name", None) or "").strip() or (product.name if product else f"#{item.product_id}")
adj = getattr(item, "price_adjustment", 0.0) or 0.0
result.append({
"name": name,
"qty": quantities.get(item.id, item.quantity) if quantities else item.quantity,
"unit_price": item.unit_price + adj,
"vat_group_id": product.fiscal_vat_group_id if product else None,
})
return result
def _set_status(db_factory, model, row_id: int, status_value: str, reference: str | None = None) -> None:
try:
session = db_factory()
try:
row = session.get(model, row_id)
if row is not None:
row.fiscal_status = status_value
if reference is not None and hasattr(row, "fiscal_reference"):
row.fiscal_reference = reference
session.commit()
logger.info("Fiscal: %s %s fiscal_status → %s", model.__tablename__, row_id, status_value)
finally:
session.close()
except Exception as e:
logger.error("Fiscal: failed to update fiscal_status for %s %s: %s", model.__tablename__, row_id, e)
def _in_background(db_factory, model, row_id: int, prepare, timeout_seconds: int) -> None:
"""prepare() → send, with the request's session (settings, the document); then send() in a
thread, and success/failed stored on the row with a fresh session from db_factory."""
try:
send = prepare()
except Exception as e:
logger.error("Fiscal: %s %s setup failed: %s", model.__tablename__, row_id, e)
_set_status(db_factory, model, row_id, "failed")
return
def _run():
try:
result = send(timeout_seconds)
except Exception as e:
logger.error("Fiscal: %s %s failed: %s", model.__tablename__, row_id, e)
result = {"success": False, "reference": None}
_set_status(db_factory, model, row_id, "success" if result.get("success") else "failed", result.get("reference"))
threading.Thread(target=_run, daemon=True).start()
def send_fiscal_receipt_background(items: list[dict], payment_method: str, total: float, db, order_id: int,
db_factory, timeout_seconds: int = 60) -> None:
"""Issue the receipt through the venue's driver in a background thread; order.fiscal_status
becomes success or failed when the device answers (or the wait times out)."""
from models.order import Order
driver = driver_for(db)
_in_background(db_factory, Order, order_id, lambda: driver.prepare_receipt(db, items, payment_method, total),
timeout_seconds)
def send_credit_note_background(items: list[dict], method: str, total: float, db, refund_id: int, original: dict,
db_factory, timeout_seconds: int = 60) -> None:
"""Issue a refund's credit note through the venue's driver in a background thread
(only for drivers with credit_notes); refund.fiscal_status becomes success or failed."""
from models.refund import Refund
driver = driver_for(db)
_in_background(db_factory, Refund, refund_id,
lambda: driver.prepare_credit_note(db, items, method, total, original), timeout_seconds)
+51
View File
@@ -0,0 +1,51 @@
"""The fiscal driver interface (plan step 3.3e, D-27).
A driver speaks to one kind of fiscal device. Callers never talk to a device directly: they
ask services.fiscal for the venue's driver (setting `fiscal.type`) and use these methods.
Adding a machine means adding a module with a FiscalDriver subclass and listing it in
services/fiscal/__init__.py DRIVERS; nothing else changes.
Items are plain dicts built by services.fiscal.build_fiscal_items:
{"name": str, "qty": int | float, "unit_price": float, "vat_group_id": int}
Results are dicts: {"success": bool, "reference": str | None, "reply": str | None, "error": str | None}
(`reference`: what the device or bridge calls this document, e.g. the command file's name).
Two steps, so the slow part can run off the request: prepare_*(db, ...) reads the settings and
builds the document with the request's session and returns send(timeout_seconds) -> result,
which talks to the device without touching the database. issue_* does both (blocking).
"""
from __future__ import annotations
from typing import Callable
Send = Callable[[int], dict]
class FiscalDriver:
key: str = ""
name: str = ""
# Whether issue_credit_note works. A driver without it: refunds are still recorded and the
# cashier is told to issue the credit note on the machine itself (owner decision 2026-11-15).
credit_notes: bool = False
def prepare_receipt(self, db, items: list[dict], method: str, total: float) -> Send:
"""A sales receipt, ready to send."""
raise NotImplementedError
def prepare_credit_note(self, db, items: list[dict], method: str, total: float, original: dict | None = None) -> Send:
"""A credit note for refunded items, ready to send. `original`: what is known about the
receipt being refunded ({"order_id", "reference"}), for devices that need it."""
raise NotImplementedError(f"{self.key}: credit notes are not supported")
def issue_receipt(self, db, items: list[dict], method: str, total: float, timeout_seconds: int = 30) -> dict:
"""Issue a sales receipt and wait for the device's answer (blocking)."""
return self.prepare_receipt(db, items, method, total)(timeout_seconds)
def issue_credit_note(self, db, items: list[dict], method: str, total: float, original: dict | None = None,
timeout_seconds: int = 30) -> dict:
"""Issue a credit note and wait for the device's answer (blocking)."""
return self.prepare_credit_note(db, items, method, total, original)(timeout_seconds)
def status(self, db) -> dict:
"""{"configured": bool, "detail": str | None}: whether the driver has what it needs."""
return {"configured": True, "detail": None}
@@ -1,5 +1,5 @@
"""
Fiscal printer service for dTEC100extra ΦΗΜ machines.
Fiscal driver `txt_file`: the dTEC100extra ΦΗΜ folder bridge (the first driver, D-27).
Protocol: plain TXT files dropped into an OUT folder. The fiscal driver reads
them, processes the receipt, then writes a reply into the IN folder.
@@ -9,6 +9,10 @@ All item text must be UPPER CASE.
File naming: fp-YYMMDD-HHMM-NNNNNNN.txt (NNNNNNN = zero-padded counter)
The driver deletes the command file after reading it and will never re-read the
same filename, so uniqueness is critical.
Credit notes: not supported yet — the bridge's refund command isn't known to us (owner
decision 2026-11-15: refunds are recorded and the cashier issues the credit note on the
machine until the command is added here).
"""
import os
@@ -16,9 +20,9 @@ import json
import time
import threading
import logging
from datetime import datetime, timezone
from core.timeutil import venue_now
from services.fiscal.base import FiscalDriver
logger = logging.getLogger(__name__)
@@ -43,30 +47,19 @@ def _unique_filename() -> str:
return f"fp-{date_part}-{time_part}-{seq:07d}.txt"
def _get_folders(db) -> tuple[str, str]:
"""Return (out_folder, in_folder) from pos_settings. Raises if not configured."""
from models.settings import PosSettings
rows = {
r.key: r.value
for r in db.query(PosSettings).filter(
PosSettings.key.in_(["fiscal.out_folder", "fiscal.in_folder"])
).all()
}
out_folder = rows.get("fiscal.out_folder", "").strip()
in_folder = rows.get("fiscal.in_folder", "").strip()
if not out_folder or not in_folder:
raise ValueError("Fiscal folder paths are not configured")
return out_folder, in_folder
def _get_setting(db, key: str, default: str = "") -> str:
from models.settings import PosSettings
row = db.query(PosSettings).filter(PosSettings.key == key).first()
return row.value if row else default
def is_fiscal_enabled(db) -> bool:
return _get_setting(db, "fiscal.enabled", "false") == "true"
def _get_folders(db) -> tuple[str, str]:
"""Return (out_folder, in_folder) from pos_settings. Raises if not configured."""
out_folder = _get_setting(db, "fiscal.out_folder", "").strip()
in_folder = _get_setting(db, "fiscal.in_folder", "").strip()
if not out_folder or not in_folder:
raise ValueError("Fiscal folder paths are not configured")
return out_folder, in_folder
def _build_command_file(items: list[dict], payment_method: str, total: float, db) -> str:
@@ -114,9 +107,7 @@ def _build_command_file(items: list[dict], payment_method: str, total: float, db
return "\r\n".join(lines) + "\r\n"
def _write_and_poll(items: list[dict], payment_method: str, total: float,
out_folder: str, in_folder: str, content: str,
filename: str, timeout_seconds: int) -> dict:
def _write_and_poll(out_folder: str, in_folder: str, content: str, filename: str, timeout_seconds: int) -> dict:
"""Write the command file and poll for a reply. Pure logic, no DB access."""
out_path = os.path.join(out_folder, filename)
reply_filename = f"answer{filename}"
@@ -126,7 +117,7 @@ def _write_and_poll(items: list[dict], payment_method: str, total: float,
with open(out_path, "w", encoding="cp737", errors="replace") as f:
f.write(content)
except OSError as e:
return {"success": False, "filename": filename, "reply": None,
return {"success": False, "reference": filename, "reply": None,
"error": f"Failed to write fiscal file: {e}"}
logger.info("Fiscal: wrote %s (%d bytes)", out_path, len(content))
@@ -144,122 +135,21 @@ def _write_and_poll(items: list[dict], payment_method: str, total: float,
time.sleep(0.5)
if reply_content is None:
return {"success": False, "filename": filename, "reply": None,
return {"success": False, "reference": filename, "reply": None,
"error": f"Fiscal timeout: no reply after {timeout_seconds}s"}
first_line = reply_content.splitlines()[0].strip() if reply_content else "1"
success = first_line == "0"
logger.info("Fiscal: reply for %s — success=%s content=%r", filename, success, reply_content)
return {"success": success, "filename": filename, "reply": reply_content,
return {"success": success, "reference": filename, "reply": reply_content,
"error": None if success else f"ΦΗΜ error: {reply_content}"}
def send_fiscal_receipt(items: list[dict], payment_method: str, total: float, db,
timeout_seconds: int = 30) -> dict:
"""
Build and send a fiscal receipt, then block waiting for the reply.
Returns: {"success": bool, "filename": str, "reply": str | None, "error": str | None}
"""
out_folder, in_folder = _get_folders(db)
os.makedirs(out_folder, exist_ok=True)
os.makedirs(in_folder, exist_ok=True)
filename = _unique_filename()
content = _build_command_file(items, payment_method, total, db)
return _write_and_poll(items, payment_method, total, out_folder, in_folder,
content, filename, timeout_seconds)
def send_fiscal_receipt_background(items: list[dict], payment_method: str, total: float,
db, order_id: int, db_factory,
timeout_seconds: int = 60) -> None:
"""
Write the fiscal file and poll for the reply in a background thread.
Updates order.fiscal_status in the DB when done (success or failure/timeout).
db_factory: a callable () -> Session (e.g. SessionLocal) so the thread can
open its own DB session independently of the request session.
"""
try:
out_folder, in_folder = _get_folders(db)
os.makedirs(out_folder, exist_ok=True)
os.makedirs(in_folder, exist_ok=True)
filename = _unique_filename()
content = _build_command_file(items, payment_method, total, db)
except Exception as e:
logger.error("Fiscal background setup failed for order %s: %s", order_id, e)
_update_fiscal_status(order_id, "failed", db_factory)
return
def _run():
result = _write_and_poll(items, payment_method, total, out_folder, in_folder,
content, filename, timeout_seconds)
status = "success" if result["success"] else "failed"
_update_fiscal_status(order_id, status, db_factory)
thread = threading.Thread(target=_run, daemon=True)
thread.start()
def _update_fiscal_status(order_id: int, status: str, db_factory) -> None:
"""Open a fresh DB session and set order.fiscal_status."""
try:
session = db_factory()
try:
from models.order import Order
order = session.query(Order).filter(Order.id == order_id).first()
if order:
order.fiscal_status = status
session.commit()
logger.info("Fiscal: order %s fiscal_status → %s", order_id, status)
finally:
session.close()
except Exception as e:
logger.error("Fiscal: failed to update fiscal_status for order %s: %s", order_id, e)
def validate_items_for_fiscal(order_items, db) -> list[str]:
"""
Check that every non-cancelled item in the list has a fiscal_vat_group_id.
Returns a list of product names that are missing it (empty = all OK).
"""
missing = []
for item in order_items:
product = item.product
if product is None:
missing.append(f"#product_{item.product_id}")
continue
vat_group = getattr(product, "fiscal_vat_group_id", None)
if not vat_group:
missing.append(product.name)
return missing
def build_fiscal_items(order_items) -> list[dict]:
"""
Convert a list of OrderItem objects into the dicts that send_fiscal_receipt expects.
Uses fiscal_name if set, else falls back to product.name.
Applies price_adjustment to the unit price.
"""
result = []
for item in order_items:
product = item.product
name = (getattr(product, "fiscal_name", None) or "").strip() or (product.name if product else f"#{item.product_id}")
adj = getattr(item, "price_adjustment", 0.0) or 0.0
unit_price = item.unit_price + adj
result.append({
"name": name,
"qty": item.quantity,
"unit_price": unit_price,
"vat_group_id": product.fiscal_vat_group_id,
})
return result
def test_folders(out_folder: str, in_folder: str) -> dict:
"""
Verify the two folders are accessible (read + write).
Returns {"ok": bool, "out_folder": str|None, "in_folder": str|None}
Returns {"ok": bool, "out_folder_error": str|None, "in_folder_error": str|None}
where each value is None if accessible, or an error string if not.
"""
def check(path):
@@ -280,3 +170,24 @@ def test_folders(out_folder: str, in_folder: str) -> dict:
"out_folder_error": out_err,
"in_folder_error": in_err,
}
class TxtFileDriver(FiscalDriver):
key = "txt_file"
name = "dTEC100extra (text-file bridge)"
credit_notes = False
def prepare_receipt(self, db, items, method, total):
out_folder, in_folder = _get_folders(db)
os.makedirs(out_folder, exist_ok=True)
os.makedirs(in_folder, exist_ok=True)
content = _build_command_file(items, method, total, db)
filename = _unique_filename()
return lambda timeout_seconds: _write_and_poll(out_folder, in_folder, content, filename, timeout_seconds)
def status(self, db):
try:
_get_folders(db)
return {"configured": True, "detail": None}
except ValueError as e:
return {"configured": False, "detail": str(e)}
+117
View File
@@ -0,0 +1,117 @@
"""Refunds (plan step 3.3e): give money back for paid items without touching the sale.
refund(request, db, user, order, lines, method, reason) → Refund
refunded_quantities(db, item_ids) → {order_item_id: quantity already refunded}
shift_refunds(db, shift_id) → {"cash": x, "card": y}
day_refunds(db, day_id) → {"amount", "count", "cash", "card"}
Rules (the counter, D-26):
- the cashier refunds from their own open shift: cash comes out of their drawer and their
shift's cash goes down, card refunds count against the shift's card total;
- only orders of the open business day (refund.too_old otherwise);
- items paid in the cashier's own open shift need nothing more; anything else needs
`ordering.refunds` (owners and managers) or a manager's approval on the spot;
- quantities can be partial (one of two coffees, 0.250 of a kilo) up to what's still unrefunded;
- with fiscal on: the venue's driver issues the credit note when it can, otherwise the refund
is marked `manual` and the cashier issues it on the machine (owner decision 2026-11-15).
"""
from __future__ import annotations
from sqlalchemy import func
from core.errors import XeniaError
EPS = 0.0005
def item_value(item, quantity: float | None = None) -> float:
"""What `quantity` (default: all) of a paid item cost: unit price + its adjustment."""
qty = item.quantity if quantity is None else quantity
return ((item.unit_price or 0.0) + (item.price_adjustment or 0.0)) * qty
def refunded_quantities(db, item_ids) -> dict[int, float]:
from models.refund import RefundItem
ids = list(item_ids)
if not ids:
return {}
rows = db.query(RefundItem.order_item_id, func.sum(RefundItem.quantity)).filter(
RefundItem.order_item_id.in_(ids)).group_by(RefundItem.order_item_id).all()
return {item_id: float(qty or 0.0) for item_id, qty in rows}
def shift_refunds(db, shift_id: int) -> dict:
from models.refund import Refund
out = {"cash": 0.0, "card": 0.0}
for method, amount in db.query(Refund.method, func.sum(Refund.amount)).filter(
Refund.shift_id == shift_id).group_by(Refund.method).all():
out["card" if method == "card" else "cash"] += float(amount or 0.0)
return {k: round(v, 2) for k, v in out.items()}
def day_refunds(db, day_id: int) -> dict:
from models.refund import Refund
rows = db.query(Refund.method, Refund.amount).filter(Refund.business_day_id == day_id).all()
cash = sum(a for m, a in rows if m != "card")
card = sum(a for m, a in rows if m == "card")
return {"amount": round(cash + card, 2), "count": len(rows), "cash": round(cash, 2), "card": round(card, 2)}
def open_shift(db, user):
from models.shift import WaiterShift
return db.query(WaiterShift).filter(WaiterShift.waiter_id == user.id, WaiterShift.ended_at.is_(None)).first()
def refund(request, db, user, order, lines: list[tuple[int, float]], method: str, reason: str | None):
"""Check everything, then write the refund (one commit). `lines`: [(order_item_id, qty)].
Returns the Refund (fiscal_status: None | manual | pending). The caller opens the drawer,
broadcasts and starts the credit note."""
from core.access.context import authorize, current_device
from models.business_day import BusinessDay
from models.order import OrderItem
from models.refund import Refund, RefundItem
from routers import orders as orders_api
from services import fiscal
shift = open_shift(db, user)
if shift is None:
raise XeniaError("pos.shift_required")
day = db.query(BusinessDay).filter(BusinessDay.status == "open").first()
if day is None or order.business_day_id != day.id:
raise XeniaError("refund.too_old")
ids = [item_id for item_id, _ in lines]
if not ids or len(set(ids)) != len(ids):
raise XeniaError("refund.invalid", reason="items")
if any(qty <= 0 for _, qty in lines):
raise XeniaError("refund.invalid", reason="quantity")
items = {i.id: i for i in db.query(OrderItem).filter(OrderItem.order_id == order.id, OrderItem.id.in_(ids)).all()}
if len(items) != len(ids) or any(i.status != "paid" for i in items.values()):
raise XeniaError("refund.invalid", reason="items")
done = refunded_quantities(db, ids)
for item_id, qty in lines:
if qty > items[item_id].quantity - done.get(item_id, 0.0) + EPS:
raise XeniaError("refund.items_changed")
approval = None
if any(i.paid_in_shift_id != shift.id for i in items.values()):
approval = authorize(request, db, user, "ordering.refunds", target=f"refund order {order.id}")
amounts = {item_id: round(item_value(items[item_id], qty), 2) for item_id, qty in lines}
total = round(sum(amounts.values()), 2)
fiscal_status = None
if fiscal.is_fiscal_enabled(db):
fiscal_status = "pending" if fiscal.can_issue_credit_notes(db) else "manual"
dev = current_device(request, db)
row = Refund(order_id=order.id, business_day_id=day.id, shift_id=shift.id, refunded_by=user.id,
approved_by=approval.approved_by if approval is not None else None,
device_id=dev.id if dev is not None else None, method=method, amount=total,
reason=(reason or "").strip()[:300] or None, fiscal_status=fiscal_status)
row.items = [RefundItem(order_item_id=item_id, quantity=qty, amount=amounts[item_id]) for item_id, qty in lines]
db.add(row)
db.flush()
note = f"refund #{row.id}" + (f" · {row.reason}" if row.reason else "") + (" · approved by a manager" if approval else "")
orders_api._audit(db, order.id, "REFUND", waiter_id=user.id, item_ids=ids, amount=total, payment_method=method, note=note)
db.commit()
db.refresh(row)
return row