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
+2 -5
View File
@@ -136,11 +136,8 @@ def close_business_day(
WaiterShift.ended_at == None,
).all()
for shift in active_shifts:
items = db.query(OrderItem).filter(
OrderItem.paid_in_shift_id == shift.id,
OrderItem.status == "paid",
).all()
shift.total_collected = sum(i.unit_price * i.quantity for i in items)
from routers.shifts import compute_shift_total
shift.total_collected = compute_shift_total(shift.id, db)
shift.ended_at = now
# Clear all table flags and staff messages — fresh slate for the next day
+1 -1
View File
@@ -21,5 +21,5 @@ def test_folders(
user: User = Depends(require_settings_manager),
):
"""Verify that both fiscal folders are accessible (read + write) from inside the container."""
from services.fiscal_service import test_folders
from services.fiscal.txt_file import test_folders
return test_folders(body.out_folder.strip(), body.in_folder.strip())
+1 -1
View File
@@ -812,7 +812,7 @@ def pay_items(order_id: int, body: PayItemsRequest, db: Session = Depends(get_db
raise HTTPException(status_code=403, detail="Access denied")
from models.shift import WaiterShift
from services.fiscal_service import (
from services.fiscal import (
is_fiscal_enabled, validate_items_for_fiscal, build_fiscal_items,
send_fiscal_receipt_background,
)
+150 -1
View File
@@ -10,6 +10,11 @@ GET /api/pos/tables the tables the cashier may serve (their zones, as in the
POST /api/pos/tables/{id}/items send cart lines to a table (opens its order if it has none)
POST /api/pos/orders/{id}/pay pay chosen items of a table's order (cash/card/split, drawer)
POST /api/pos/orders/{id}/close close a fully paid order (never writes unpaid items off)
GET /api/pos/receipts today's paid orders, newest first (3.3e; scope=mine|all)
GET /api/pos/receipts/{id} one paid order: items with what's refundable, its refunds
POST /api/pos/orders/{id}/refund money back for paid items (services/refunds.py): cash opens
the drawer, the cashier's shift goes down, credit note via
the fiscal driver or by hand on the machine (D-27)
Tables use the waiter app's rules and functions (routers/orders.py): zone access, the person
assigned to an order, business day, kitchen tickets, shift totals. Cancelling items is the
@@ -261,7 +266,7 @@ def _check_discounts(request, db, user, lines):
def _check_fiscal(db, products):
from services.fiscal_service import is_fiscal_enabled
from services.fiscal import is_fiscal_enabled
if is_fiscal_enabled(db):
missing = sorted({p.name for p in products if p is not None and not p.fiscal_vat_group_id})
if missing:
@@ -482,3 +487,147 @@ def pos_order_close(order_id: int, db: Session = Depends(get_db), user=Depends(r
if unpaid:
raise XeniaError("pos.order_unpaid", count=unpaid)
return orders_api.close_order(order.id, db, user)
# ── receipts and refunds (3.3e) ────────────────────────────────────────────────
def _order_label(o) -> str:
if o.table is not None:
return _table_name(o.table)
if o.source == "online" and o.online_order_ref:
return o.online_order_ref
return f"#{o.id}"
def _names(db, ids) -> dict:
from models.user import User
ids = {i for i in ids if i}
return {u.id: u.full_name or u.username for u in db.query(User).filter(User.id.in_(ids)).all()} if ids else {}
def _option_names(raw) -> list:
import json
try:
return [o.get("name") for o in (json.loads(raw) if raw else []) if isinstance(o, dict) and o.get("name")]
except (ValueError, TypeError):
return []
@router.get("/receipts")
def pos_receipts(scope: Literal["mine", "all"] = "all", db: Session = Depends(get_db), user=Depends(require(ACCESS))):
"""Today's paid orders (the open business day), newest payment first: what the counter can
refund. `mine` = with items paid in the cashier's open shift. → {orders: [{id, label, type,
source, paid_at, paid, refunded, methods, mine, cashier}]} (at most 200)"""
from models.business_day import BusinessDay
from models.order import Order, OrderItem
from models.refund import Refund
from services.refunds import item_value, open_shift
day = db.query(BusinessDay).filter(BusinessDay.status == "open").first()
if day is None:
return {"orders": []}
shift = open_shift(db, user)
paid = db.query(OrderItem).join(Order, Order.id == OrderItem.order_id).filter(
Order.business_day_id == day.id, OrderItem.status == "paid").all()
by_order: dict[int, list] = {}
for i in paid:
by_order.setdefault(i.order_id, []).append(i)
if not by_order:
return {"orders": []}
orders = {o.id: o for o in db.query(Order).options(selectinload(Order.table)).filter(Order.id.in_(by_order)).all()}
refunded: dict[int, float] = {}
for oid, amount in db.query(Refund.order_id, Refund.amount).filter(Refund.order_id.in_(by_order)).all():
refunded[oid] = refunded.get(oid, 0.0) + amount
last = {oid: max(items, key=lambda i: (i.paid_at.isoformat() if i.paid_at else "", i.id))
for oid, items in by_order.items()}
names = _names(db, [i.paid_by for i in last.values()])
out = []
for oid, items in by_order.items():
o = orders[oid]
mine = shift is not None and any(i.paid_in_shift_id == shift.id for i in items)
if scope == "mine" and not mine:
continue
out.append({
"id": oid, "label": _order_label(o), "type": o.order_type, "source": o.source, "paid_at": _iso(last[oid].paid_at),
"paid": round(sum(item_value(i) for i in items), 2), "refunded": round(refunded.get(oid, 0.0), 2),
"methods": sorted({i.payment_method or "cash" for i in items}), "mine": mine,
"cashier": names.get(last[oid].paid_by),
})
out.sort(key=lambda r: (r["paid_at"] or "", r["id"]), reverse=True)
return {"orders": out[:200]}
@router.get("/receipts/{order_id}")
def pos_receipt(order_id: int, db: Session = Depends(get_db), user=Depends(require(ACCESS))):
"""One paid order for a refund: its paid items (with what's already refunded and what's
left), its refunds, whether it's from today, and what fiscal will do with a refund."""
from models.business_day import BusinessDay
from models.order import Order, OrderItem
from models.refund import Refund
from services import fiscal
from services.refunds import item_value, open_shift, refunded_quantities
order = db.get(Order, order_id)
if order is None:
raise XeniaError("order.not_found", order_id=order_id)
shift = open_shift(db, user)
day = db.query(BusinessDay).filter(BusinessDay.status == "open").first()
items = db.query(OrderItem).options(selectinload(OrderItem.product)).filter(
OrderItem.order_id == order.id, OrderItem.status == "paid").order_by(OrderItem.id).all()
done = refunded_quantities(db, [i.id for i in items])
refunds = db.query(Refund).filter(Refund.order_id == order.id).order_by(Refund.created_at).all()
names = _names(db, [i.paid_by for i in items] + [r.refunded_by for r in refunds] + [r.approved_by for r in refunds])
st = fiscal.status(db)
return {
"id": order.id, "label": _order_label(order), "type": order.order_type, "source": order.source,
"today": day is not None and order.business_day_id == day.id,
"fiscal": {"enabled": st["enabled"], "credit_notes": st["credit_notes"]},
"items": [{
"id": i.id, "name": i.product_name, "options": _option_names(i.selected_options), "notes": i.notes,
"quantity": i.quantity, "unit_type": i.product.unit_type if i.product else "piece",
"unit_total": round(item_value(i, 1), 2), "total": round(item_value(i), 2),
"method": i.payment_method or "cash", "paid_at": _iso(i.paid_at), "paid_by": names.get(i.paid_by),
"mine": shift is not None and i.paid_in_shift_id == shift.id,
"refunded": round(done.get(i.id, 0.0), 3), "refundable": round(max(0.0, i.quantity - done.get(i.id, 0.0)), 3),
} for i in items],
"refunds": [{
"id": r.id, "created_at": _iso(r.created_at), "method": r.method, "amount": r.amount, "reason": r.reason,
"by": names.get(r.refunded_by), "approved_by": names.get(r.approved_by), "fiscal": r.fiscal_status,
} for r in refunds],
}
class RefundLine(BaseModel):
item_id: int
quantity: float = Field(gt=0, le=100000)
class RefundBody(BaseModel):
items: List[RefundLine] = Field(min_length=1, max_length=500)
method: Literal["cash", "card"]
reason: Optional[str] = Field(default=None, max_length=300)
@router.post("/orders/{order_id}/refund", status_code=201)
def pos_refund(order_id: int, body: RefundBody, request: Request, db: Session = Depends(get_db),
user=Depends(require(ACCESS))):
"""Give money back for paid items of today's order (services/refunds.py): from the cashier's
shift, cash opens the drawer. Items paid in another shift need ordering.refunds or a
manager's approval. With fiscal on, the credit note goes through the venue's driver, or
`fiscal: "manual"` tells the cashier to issue it on the machine.
→ {refund_id, order_id, amount, method, drawer, fiscal}"""
from models.order import Order, OrderItem
from services import fiscal, refunds
from services.sse_bus import broadcast_sync
order = db.get(Order, order_id)
if order is None:
raise XeniaError("order.not_found", order_id=order_id)
row = refunds.refund(request, db, user, order, [(x.item_id, x.quantity) for x in body.items], body.method, body.reason)
if row.fiscal_status == "pending":
from database import SessionLocal
qty = {ri.order_item_id: ri.quantity for ri in row.items}
items = db.query(OrderItem).filter(OrderItem.id.in_(qty)).all()
fiscal.send_credit_note_background(fiscal.build_fiscal_items(items, qty), row.method, row.amount, db, row.id,
{"order_id": order.id, "reference": None}, SessionLocal)
drawer = _open_drawer(request, db, user, order.id) if row.method == "cash" else "none"
broadcast_sync("order_refunded", {"order_id": order.id, "refund_id": row.id, "amount": row.amount, "method": row.method})
return {"refund_id": row.id, "order_id": order.id, "amount": row.amount, "method": row.method,
"drawer": drawer, "fiscal": row.fiscal_status}
+5
View File
@@ -63,6 +63,9 @@ router = APIRouter(dependencies=[Depends(_business_day_guard("reports"))])
history_router = APIRouter(dependencies=[Depends(_business_day_guard("history"))])
from services.refunds import day_refunds # noqa: E402 (3.3e: refunds shown apart from revenue)
def _item_val(item) -> float:
"""Effective line value: unit_price + any price adjustment, times quantity."""
return ((item.unit_price or 0.0) + (item.price_adjustment or 0.0)) * item.quantity
@@ -1260,6 +1263,7 @@ def business_days_list(
"waiter_count": len(waiter_ids),
"shift_count": len(day_shifts),
"revenue": round(revenue, 2),
"refunds": day_refunds(db, d.id),
"total_cost": round(total_cost, 2),
"trackable_profit": round(trackable_profit, 2),
"has_gap": has_gap,
@@ -1336,6 +1340,7 @@ def current_business_day(
"id": day.id,
"opened_at": _dt(day.opened_at),
"revenue": round(revenue, 2),
"refunds": day_refunds(db, day.id),
"total_cost": round(total_cost, 2),
"trackable_profit": round(trackable_profit, 2),
"has_gap": has_gap,
+29 -10
View File
@@ -30,15 +30,15 @@ def _get_setting(db: Session, key: str, default: str = "true") -> str:
def compute_shift_total(shift_id: int, db: Session) -> float:
items = db.query(OrderItem).filter(
OrderItem.paid_in_shift_id == shift_id,
OrderItem.status == "paid",
).all()
return round(sum(i.unit_price * i.quantity for i in items), 2)
"""What the shift took, net of its refunds (3.3e)."""
split = compute_shift_payment_split(shift_id, db)
return round(split["cash_sales"] + split["card_sales"] - split["cash_refunds"] - split["card_refunds"], 2)
def compute_shift_payment_split(shift_id: int, db: Session) -> dict:
"""Return cash_sales and card_sales for a shift (items paid in this shift)."""
"""cash_sales / card_sales (items paid in this shift, with their price adjustments, i.e.
discounts) and cash_refunds / card_refunds (money this shift gave back, 3.3e)."""
from services.refunds import item_value, shift_refunds
items = db.query(OrderItem).filter(
OrderItem.paid_in_shift_id == shift_id,
OrderItem.status == "paid",
@@ -46,13 +46,15 @@ def compute_shift_payment_split(shift_id: int, db: Session) -> dict:
cash = 0.0
card = 0.0
for i in items:
amount = float(i.unit_price) * i.quantity
amount = item_value(i)
method = (i.payment_method or "cash").lower()
if method == "card":
card += amount
else:
cash += amount
return {"cash_sales": round(cash, 2), "card_sales": round(card, 2)}
refunds = shift_refunds(db, shift_id)
return {"cash_sales": round(cash, 2), "card_sales": round(card, 2),
"cash_refunds": refunds["cash"], "card_refunds": refunds["card"]}
def compute_shift_pay(shift: WaiterShift) -> dict:
@@ -119,7 +121,9 @@ def _enrich_shift(shift: WaiterShift, db: Session) -> dict:
"total_collected": total,
"cash_sales": split["cash_sales"],
"card_sales": split["card_sales"],
"net_to_deliver": round(split["cash_sales"] + (shift.starting_cash or 0.0), 2),
"cash_refunds": split["cash_refunds"],
"card_refunds": split["card_refunds"],
"net_to_deliver": round(split["cash_sales"] - split["cash_refunds"] + (shift.starting_cash or 0.0), 2),
"is_active": shift.ended_at is None,
"notes": shift.notes,
"hourly_rate_snapshot": shift.hourly_rate_snapshot,
@@ -131,7 +135,7 @@ def _enrich_shift(shift: WaiterShift, db: Session) -> dict:
# Phase 2E — discrepancy computed live against cash-only expected (starting_cash + cash_sales)
"counted_cash_end": shift.counted_cash_end,
"cash_discrepancy": round(
shift.counted_cash_end - (split["cash_sales"] + (shift.starting_cash or 0.0)), 2
shift.counted_cash_end - (split["cash_sales"] - split["cash_refunds"] + (shift.starting_cash or 0.0)), 2
) if shift.counted_cash_end is not None else None,
"breaks": [
{"id": b.id, "shift_id": b.shift_id, "started_at": _dt(b.started_at), "ended_at": _dt(b.ended_at)}
@@ -578,4 +582,19 @@ def get_shift_summary(
enriched = _enrich_shift(shift, db)
enriched["orders"] = populated_orders
enriched["duration_minutes"] = duration_minutes
from models.refund import Refund
refunds = db.query(Refund).filter(Refund.shift_id == shift_id).order_by(Refund.created_at).all()
for r in refunds:
all_waiter_ids.update(x for x in (r.refunded_by, r.approved_by) if x)
missing = [w for w in all_waiter_ids if w not in waiters_map]
if missing:
for w in db.query(User).filter(User.id.in_(missing)).all():
waiters_map[w.id] = w.full_name or w.username
enriched["refunds"] = [{
"id": r.id, "order_id": r.order_id, "created_at": _dt(r.created_at), "method": r.method, "amount": r.amount,
"reason": r.reason, "refunded_by_name": _wname(r.refunded_by), "approved_by_name": _wname(r.approved_by),
"fiscal_status": r.fiscal_status,
"items": [{"order_item_id": ri.order_item_id, "name": ri.order_item.product_name if ri.order_item else None,
"quantity": ri.quantity, "amount": ri.amount} for ri in r.items],
} for r in refunds]
return enriched