"""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