Files
xenia-pos-local/local_backend/routers/tabs.py
T
bonaminandClaude Opus 5.5 07c9a0aecf feat: tabs in the books (platform-v2 step 6.13c, KI-018; owner 2026-11-19: every movement recorded)
- a line on a customer's tab is sold, not paid: services/sales.py counts tabbed lines as sold (on_tab apart)
- TabEntry / TabPayment record the business day and the shift of whoever did it (Alembic 0037, rows backfilled with their day);
  services/tab_books.py: per shift and per day, on tabs and tab money received (cash / card / other, who, in a shift or not)
- shift: tab cash goes in the drawer (net_to_deliver, the counted difference, total_collected), tab card in the card total;
  items paid other ways (transfer, on the house) are recorded apart and no longer counted as drawer cash;
  'activity': orders, items made / paid / put on a tab with values
- day summary: per person put on tabs and tab money received, every tab payment with who took it, the part taken outside shifts (in no drawer);
  the day's money: paid, on tabs, sold, paid on tabs, money taken (it used to subtract tabs from paid sales)
- Today: on tabs, paid on tabs; Staff -> Cash handover: paid on tabs; the shift dialog: made / paid / on a tab / paid on tabs
- fix: a line put on a tab was charged without its price change (a discount)
- tests: test_tab_books.py (the done-when), overview unit, e2e manager.mjs (the day records the tab payments; Today shows them)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 16:32:25 +02:00

252 lines
8.7 KiB
Python

"""Customer tabs: pay later (module `tabs`; manager page in plan step 6.13a).
A customer has at most one open tab. Lines of an order go on it from the order
(POST /api/orders/{id}/items/{item}/tab: the line becomes "tabbed", the tab opens by itself);
the customer pays it off in one or more payments (cash, card or other), and it is closed when
nothing is owed, or forgiven (what is owed is written off, with a reason).
Every route needs `tabs.manage`; a customer's tabs can also be read with `crm.manage` (their
card on the customers page). Changes send the live event `tabs.changed`.
"""
from core.timeutil import utcnow
from fastapi import APIRouter, Depends, status
from sqlalchemy.orm import Session
from typing import List, Optional
from database import get_db
from models.tabs import Tab, TabEntry, TabPayment
from models.customers import Customer
from models.order import Order, OrderItem
from models.user import User
from schemas.tabs import TabOut, TabEntryOut, TabPaymentOut, TabPayRequest, TabForgiveRequest, TabCloseRequest
from core.access.deps import require, require_any
from core.errors import XeniaError
from services import tab_books
from services.ws_bus import broadcast_sync
router = APIRouter()
MANAGE = Depends(require("tabs.manage"))
METHODS = tab_books.METHODS
def changed():
broadcast_sync("tabs.changed", {})
def _tab_out(tab: Tab) -> dict:
c = tab.customer
customer_name = c.name if c else None
if c and c.nickname:
customer_name = f"{c.name} «{c.nickname}»"
customer_phone = c.phone if c else None
total_charged = round(sum(e.amount for e in tab.entries), 2)
total_paid = round(sum(p.amount for p in tab.payments), 2)
balance = round(total_charged - total_paid, 2)
closed_by_name = None
if tab.closed_by:
closed_by_name = tab.closed_by.full_name or tab.closed_by.username
entries_out = []
for e in sorted(tab.entries, key=lambda x: x.created_at):
creator = e.created_by.full_name or e.created_by.username if e.created_by else None
entries_out.append({
"id": e.id, "tab_id": e.tab_id, "order_id": e.order_id,
"order_item_id": e.order_item_id, "amount": e.amount,
"description": e.description, "created_by_id": e.created_by_id,
"created_by_name": creator, "created_at": e.created_at,
})
payments_out = []
for p in sorted(tab.payments, key=lambda x: x.created_at):
receiver = p.received_by.full_name or p.received_by.username if p.received_by else None
payments_out.append({
"id": p.id, "tab_id": p.tab_id, "amount": p.amount,
"payment_method": p.payment_method, "received_by_id": p.received_by_id,
"received_by_name": receiver, "notes": p.notes, "created_at": p.created_at,
})
return {
"id": tab.id,
"customer_id": tab.customer_id,
"customer_name": customer_name,
"customer_phone": customer_phone,
"status": tab.status,
"opened_at": tab.opened_at,
"closed_at": tab.closed_at,
"closed_by_id": tab.closed_by_id,
"notes": tab.notes,
"balance": balance,
"total_charged": total_charged,
"total_paid": total_paid,
"entries": entries_out,
"payments": payments_out,
}
@router.get("/", response_model=List[TabOut])
def list_tabs(
tab_status: Optional[str] = None,
customer_id: Optional[int] = None,
db: Session = Depends(get_db),
user: User = MANAGE,
):
q = db.query(Tab)
if tab_status == "settled":
q = q.filter(Tab.status.in_(("closed", "forgiven")))
elif tab_status:
q = q.filter(Tab.status == tab_status)
else:
q = q.filter(Tab.status == "open") # default: only open tabs
if customer_id:
q = q.filter(Tab.customer_id == customer_id)
tabs = q.order_by(Tab.opened_at.desc()).all()
result = [_tab_out(t) for t in tabs]
if tab_status in (None, "open"):
result.sort(key=lambda x: x["balance"], reverse=True) # who owes most first
return result
@router.get("/{tab_id}", response_model=TabOut)
def get_tab(tab_id: int, db: Session = Depends(get_db), user: User = MANAGE):
tab = db.query(Tab).filter(Tab.id == tab_id).first()
if not tab:
raise XeniaError("tab.not_found")
return _tab_out(tab)
@router.post("/", response_model=TabOut, status_code=status.HTTP_201_CREATED)
def open_tab(customer_id: int, db: Session = Depends(get_db), user: User = MANAGE):
customer = db.query(Customer).filter(Customer.id == customer_id, Customer.is_active == True).first()
if not customer:
raise XeniaError("customer.not_found")
existing = db.query(Tab).filter(Tab.customer_id == customer_id, Tab.status == "open").first()
if existing:
raise XeniaError("tab.already_open")
tab = Tab(customer_id=customer_id)
db.add(tab)
db.commit()
db.refresh(tab)
changed()
return _tab_out(tab)
@router.post("/{tab_id}/entries", response_model=TabOut)
def add_tab_entry(
tab_id: int,
order_id: Optional[int] = None,
order_item_id: Optional[int] = None,
amount: float = 0.0,
description: Optional[str] = None,
db: Session = Depends(get_db),
user: User = MANAGE,
):
tab = db.query(Tab).filter(Tab.id == tab_id, Tab.status == "open").first()
if not tab:
raise XeniaError("tab.not_found")
if amount <= 0:
raise XeniaError("validation.positive", field='amount')
entry = TabEntry(
tab_id=tab_id, order_id=order_id, order_item_id=order_item_id,
amount=amount, description=description, created_by_id=user.id,
)
tab_books.stamp(db, entry, user.id)
db.add(entry)
db.commit()
db.refresh(tab)
changed()
return _tab_out(tab)
@router.post("/{tab_id}/pay", response_model=TabOut)
def pay_tab(
tab_id: int,
body: TabPayRequest,
db: Session = Depends(get_db),
user: User = MANAGE,
):
tab = db.query(Tab).filter(Tab.id == tab_id, Tab.status == "open").first()
if not tab:
raise XeniaError("tab.not_found")
if body.amount <= 0:
raise XeniaError("validation.positive", field='amount')
total_charged = sum(e.amount for e in tab.entries)
total_paid = sum(p.amount for p in tab.payments)
balance = total_charged - total_paid
if body.amount > balance + 0.005:
raise XeniaError("tab.over_balance", balance=f'{balance:.2f}')
method = body.payment_method or "cash"
if method not in METHODS:
raise XeniaError("validation.choice", field="payment_method", value=method)
payment = TabPayment(
tab_id=tab_id, amount=body.amount,
payment_method=method, notes=body.notes,
received_by_id=user.id,
)
tab_books.stamp(db, payment, user.id) # 6.13c: the day and the receiver's shift (their drawer)
db.add(payment)
db.commit()
db.refresh(tab)
changed()
return _tab_out(tab)
@router.post("/{tab_id}/close", response_model=TabOut)
def close_tab(
tab_id: int,
body: TabCloseRequest,
db: Session = Depends(get_db),
user: User = MANAGE,
):
tab = db.query(Tab).filter(Tab.id == tab_id, Tab.status == "open").first()
if not tab:
raise XeniaError("tab.not_found")
total_charged = sum(e.amount for e in tab.entries)
total_paid = sum(p.amount for p in tab.payments)
balance = round(total_charged - total_paid, 2)
if balance > 0.005:
raise XeniaError("tab.has_balance", balance=f'{balance:.2f}')
tab.status = "closed"
tab.closed_at = utcnow()
tab.closed_by_id = user.id
if body.notes:
tab.notes = body.notes
db.commit()
db.refresh(tab)
changed()
return _tab_out(tab)
@router.post("/{tab_id}/forgive", response_model=TabOut)
def forgive_tab(
tab_id: int,
body: TabForgiveRequest,
db: Session = Depends(get_db),
user: User = MANAGE,
):
tab = db.query(Tab).filter(Tab.id == tab_id, Tab.status == "open").first()
if not tab:
raise XeniaError("tab.not_found")
tab.status = "forgiven"
tab.closed_at = utcnow()
tab.closed_by_id = user.id
if body.reason:
tab.notes = body.reason
db.commit()
db.refresh(tab)
changed()
return _tab_out(tab)
# ── Customer tabs ──────────────────────────────────────────────────────────────
@router.get("/customer/{customer_id}", response_model=List[TabOut])
def customer_tabs(customer_id: int, db: Session = Depends(get_db),
user: User = Depends(require_any("tabs.manage", "crm.manage"))):
tabs = db.query(Tab).filter(Tab.customer_id == customer_id).order_by(
Tab.status.asc(), # open first
Tab.opened_at.desc(),
).all()
return [_tab_out(t) for t in tabs]