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:
@@ -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}
|
||||
|
||||
Reference in New Issue
Block a user