Files
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

636 lines
24 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
from core.access.deps import require
from core.access.check import holds
from core.timeutil import utcnow
from fastapi import APIRouter, Depends, status
from sqlalchemy.orm import Session
from typing import Optional
from datetime import datetime, timezone
from database import get_db
from models.shift import WaiterShift, ShiftBreak
from models.business_day import BusinessDay
from models.order import OrderItem
from models.settings import PosSettings
from models.user import User
from schemas.shift import StartShiftRequest, EndShiftRequest
from routers.deps import get_current_user, require_manager
from core.errors import XeniaError
router = APIRouter()
def _dt(dt):
"""Serialize a naive-UTC datetime to ISO string with Z so JS parses it as UTC."""
if dt is None:
return None
return (dt.isoformat() + "Z") if dt.tzinfo is None else dt.isoformat()
def _get_setting(db: Session, key: str, default: str = "true") -> str:
s = db.query(PosSettings).filter(PosSettings.key == key).first()
return s.value if s else default
def compute_shift_total(shift_id: int, db: Session) -> float:
"""The money the shift took (cash + card: items paid and tab payments), net of its refunds."""
split = compute_shift_payment_split(shift_id, db)
return round(split["cash_sales"] + split["card_sales"] + split["tab_cash"] + split["tab_card"]
- split["cash_refunds"] - split["card_refunds"], 2)
def compute_shift_payment_split(shift_id: int, db: Session) -> dict:
"""The shift's money by kind (6.13c: every movement apart).
cash_sales / card_sales: items paid in this shift (with their price changes) in cash / by card;
other_sales: items paid any other way (transfer, on the house…): recorded, in no drawer
(until 6.13c they were counted as cash). tab_cash / tab_card / tab_other: payments on
customers' tabs this shift received. cash_refunds / card_refunds: money it gave back (3.3e).
"""
from services import tab_books
from services.refunds import item_value, shift_refunds
items = db.query(OrderItem).filter(
OrderItem.paid_in_shift_id == shift_id,
OrderItem.status == "paid",
).all()
out = {"cash": 0.0, "card": 0.0, "other": 0.0}
for i in items:
method = (i.payment_method or "cash").lower()
out[method if method in ("cash", "card") else "other"] += item_value(i)
refunds = shift_refunds(db, shift_id)
tab = tab_books.for_shift(db, shift_id)["received"]
return {"cash_sales": round(out["cash"], 2), "card_sales": round(out["card"], 2), "other_sales": round(out["other"], 2),
"tab_cash": tab["cash"], "tab_card": tab["card"], "tab_other": tab["other"],
"cash_refunds": refunds["cash"], "card_refunds": refunds["card"]}
def expected_cash(split: dict, starting_cash: float | None) -> float:
"""What should be in the drawer: starting cash + cash for items + cash on tabs − cash refunded."""
return round((starting_cash or 0.0) + split["cash_sales"] + split["tab_cash"] - split["cash_refunds"], 2)
def compute_shift_pay(shift: WaiterShift) -> dict:
"""Return duration_hours and shift_pay. shift_pay is None if no rate snapshot."""
now = utcnow()
start = shift.started_at
if start and start.tzinfo is None:
start = start.replace(tzinfo=timezone.utc)
end = shift.ended_at
if end and end.tzinfo is None:
end = end.replace(tzinfo=timezone.utc)
reference = end or now
total_seconds = (reference - start).total_seconds() if start else 0
# Subtract completed breaks
break_seconds = 0
for b in shift.breaks:
bs = b.started_at
be = b.ended_at
if bs and be:
if bs.tzinfo is None:
bs = bs.replace(tzinfo=timezone.utc)
if be.tzinfo is None:
be = be.replace(tzinfo=timezone.utc)
break_seconds += (be - bs).total_seconds()
worked_seconds = max(0, total_seconds - break_seconds)
duration_hours = round(worked_seconds / 3600, 4)
shift_pay = None
if shift.hourly_rate_snapshot is not None:
shift_pay = round(duration_hours * shift.hourly_rate_snapshot, 2)
return {"duration_hours": round(duration_hours, 2), "shift_pay": shift_pay}
def shift_activity(shift: WaiterShift, db: Session) -> dict:
"""What happened in the shift (6.13c): orders opened and items made by this person in it,
items paid in it (by anyone's lines) and items it put on customers' tabs, with their values."""
from models.order import Order
from services import tab_books
from services.sales import gross
end = shift.ended_at or utcnow()
made = db.query(OrderItem).filter(OrderItem.added_by == shift.waiter_id, OrderItem.added_at >= shift.started_at,
OrderItem.added_at <= end, OrderItem.status != "cancelled").all()
paid = db.query(OrderItem).filter(OrderItem.paid_in_shift_id == shift.id, OrderItem.status == "paid").all()
orders = db.query(Order).filter(Order.opened_by == shift.waiter_id, Order.opened_at >= shift.started_at,
Order.opened_at <= end, Order.status != "cancelled").count()
tab = tab_books.for_shift(db, shift.id)["on_tab"]
r = lambda v: round(v, 2) # noqa: E731
return {"orders": orders,
"made_items": sum(i.quantity for i in made), "made_value": r(sum(gross(i) for i in made)),
"paid_items": sum(i.quantity for i in paid), "paid_value": r(sum(gross(i) for i in paid)),
"tab_items": tab["items"], "tab_value": tab["value"]}
def _enrich_shift(shift: WaiterShift, db: Session) -> dict:
w = shift.waiter
wname = (w.full_name or w.username) if w else f"#{shift.waiter_id}"
total = compute_shift_total(shift.id, db) if shift.ended_at is None else (shift.total_collected or 0.0)
split = compute_shift_payment_split(shift.id, db)
pay_data = compute_shift_pay(shift)
# Count cancelled items and their value attributed to this waiter during shift window
cancelled_q = db.query(OrderItem).filter(
OrderItem.status == "cancelled",
OrderItem.added_by == shift.waiter_id,
OrderItem.added_at >= shift.started_at,
)
if shift.ended_at:
cancelled_q = cancelled_q.filter(OrderItem.added_at <= shift.ended_at)
cancelled_rows = cancelled_q.all()
cancellation_events = len(cancelled_rows)
cancellations = sum(r.quantity for r in cancelled_rows)
cancellation_value = round(sum(r.unit_price * r.quantity for r in cancelled_rows), 2)
return {
"id": shift.id,
"waiter_id": shift.waiter_id,
"waiter_name": wname,
"business_day_id": shift.business_day_id,
"started_at": _dt(shift.started_at),
"ended_at": _dt(shift.ended_at),
"starting_cash": shift.starting_cash,
"total_collected": total,
"cash_sales": split["cash_sales"],
"card_sales": split["card_sales"],
"cash_refunds": split["cash_refunds"],
"card_refunds": split["card_refunds"],
"other_sales": split["other_sales"],
"tab_cash": split["tab_cash"],
"tab_card": split["tab_card"],
"tab_other": split["tab_other"],
"net_to_deliver": expected_cash(split, shift.starting_cash),
"activity": shift_activity(shift, db),
"is_active": shift.ended_at is None,
"notes": shift.notes,
"hourly_rate_snapshot": shift.hourly_rate_snapshot,
"duration_hours": pay_data["duration_hours"],
"shift_pay": pay_data["shift_pay"],
"cancellation_events": cancellation_events,
"cancellations": cancellations,
"cancellation_value": cancellation_value,
# 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 - expected_cash(split, shift.starting_cash), 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)}
for b in shift.breaks
],
}
@router.get("/my")
def my_shift(db: Session = Depends(get_db), user: User = Depends(get_current_user)):
shift = db.query(WaiterShift).filter(
WaiterShift.waiter_id == user.id,
WaiterShift.ended_at == None,
).first()
return _enrich_shift(shift, db) if shift else None
@router.post("/start", status_code=status.HTTP_201_CREATED)
def start_shift(
body: StartShiftRequest,
db: Session = Depends(get_db),
user: User = Depends(get_current_user),
):
target_id = body.waiter_id
if target_id and target_id != user.id:
if not holds(user, "core.dashboard.access"):
raise XeniaError("shift.others_need_manager")
target = db.query(User).filter(User.id == target_id, User.is_active == True).first()
if not target:
raise XeniaError("staff.not_found")
else:
target_id = user.id
if not holds(user, "core.dashboard.access") and _get_setting(db, "shifts.waiter_self_start") != "true":
raise XeniaError("shift.start_needs_manager")
active_day = db.query(BusinessDay).filter(BusinessDay.status == "open").first()
if not active_day:
raise XeniaError("business_day.closed", status=400)
existing = db.query(WaiterShift).filter(
WaiterShift.waiter_id == target_id,
WaiterShift.ended_at == None,
).first()
if existing:
raise XeniaError("shift.already_active")
target_user = db.query(User).filter(User.id == target_id).first()
shift = WaiterShift(
waiter_id=target_id,
business_day_id=active_day.id,
starting_cash=body.starting_cash,
hourly_rate_snapshot=target_user.hourly_rate if target_user else None,
)
db.add(shift)
db.commit()
db.refresh(shift)
return _enrich_shift(shift, db)
@router.post("/end")
def end_shift(
body: EndShiftRequest,
db: Session = Depends(get_db),
user: User = Depends(get_current_user),
):
if not holds(user, "core.dashboard.access") and _get_setting(db, "shifts.waiter_self_end") != "true":
raise XeniaError("shift.end_needs_manager")
shift = db.query(WaiterShift).filter(
WaiterShift.waiter_id == user.id,
WaiterShift.ended_at == None,
).first()
if not shift:
raise XeniaError("shift.none_active")
now = utcnow()
total = compute_shift_total(shift.id, db)
shift.total_collected = total
shift.ended_at = now
if body.notes:
shift.notes = body.notes
# Phase 2E: cash reconciliation — store counted amount; discrepancy computed live in _enrich_shift
if body.counted_cash_end is not None:
shift.counted_cash_end = body.counted_cash_end
open_break = db.query(ShiftBreak).filter(
ShiftBreak.shift_id == shift.id, ShiftBreak.ended_at == None
).first()
if open_break:
open_break.ended_at = now
db.commit()
db.refresh(shift)
return _enrich_shift(shift, db)
@router.post("/manager/start", status_code=status.HTTP_201_CREATED)
def manager_start_shift(
body: StartShiftRequest,
db: Session = Depends(get_db),
user: User = Depends(require_manager),
):
if not body.waiter_id:
raise XeniaError("validation.missing", field='waiter_id')
target = db.query(User).filter(User.id == body.waiter_id, User.is_active == True).first()
if not target:
raise XeniaError("staff.not_found")
active_day = db.query(BusinessDay).filter(BusinessDay.status == "open").first()
if not active_day:
raise XeniaError("business_day.none_open", status=400)
existing = db.query(WaiterShift).filter(
WaiterShift.waiter_id == body.waiter_id,
WaiterShift.ended_at == None,
).first()
if existing:
raise XeniaError("shift.already_active")
shift = WaiterShift(
waiter_id=body.waiter_id,
business_day_id=active_day.id,
starting_cash=body.starting_cash,
hourly_rate_snapshot=target.hourly_rate,
)
db.add(shift)
db.commit()
db.refresh(shift)
return _enrich_shift(shift, db)
@router.post("/manager/end/{shift_id}")
def manager_end_shift(
shift_id: int,
body: EndShiftRequest,
db: Session = Depends(get_db),
user: User = Depends(require_manager),
):
shift = db.query(WaiterShift).filter(
WaiterShift.id == shift_id,
WaiterShift.ended_at == None,
).first()
if not shift:
raise XeniaError("shift.none_active")
now = utcnow()
total = compute_shift_total(shift.id, db)
shift.total_collected = total
shift.ended_at = now
if body.notes:
shift.notes = body.notes
# Phase 2E: cash reconciliation — store counted amount; discrepancy computed live in _enrich_shift
if body.counted_cash_end is not None:
shift.counted_cash_end = body.counted_cash_end
open_break = db.query(ShiftBreak).filter(
ShiftBreak.shift_id == shift.id, ShiftBreak.ended_at == None
).first()
if open_break:
open_break.ended_at = now
db.commit()
db.refresh(shift)
return _enrich_shift(shift, db)
@router.post("/{shift_id}/break/start")
def start_break(
shift_id: int,
db: Session = Depends(get_db),
user: User = Depends(get_current_user),
):
shift = db.query(WaiterShift).filter(WaiterShift.id == shift_id).first()
if not shift:
raise XeniaError("shift.not_found")
if shift.waiter_id != user.id and not holds(user, "core.dashboard.access"):
raise XeniaError("shift.not_yours")
if shift.ended_at:
raise XeniaError("shift.ended")
open_break = db.query(ShiftBreak).filter(
ShiftBreak.shift_id == shift_id, ShiftBreak.ended_at == None
).first()
if open_break:
raise XeniaError("shift.on_break")
b = ShiftBreak(shift_id=shift_id)
db.add(b)
db.commit()
db.refresh(b)
return {"id": b.id, "shift_id": b.shift_id, "started_at": _dt(b.started_at), "ended_at": _dt(b.ended_at)}
@router.post("/{shift_id}/break/end")
def end_break(
shift_id: int,
db: Session = Depends(get_db),
user: User = Depends(get_current_user),
):
shift = db.query(WaiterShift).filter(WaiterShift.id == shift_id).first()
if not shift:
raise XeniaError("shift.not_found")
if shift.waiter_id != user.id and not holds(user, "core.dashboard.access"):
raise XeniaError("shift.not_yours")
open_break = db.query(ShiftBreak).filter(
ShiftBreak.shift_id == shift_id, ShiftBreak.ended_at == None
).first()
if not open_break:
raise XeniaError("shift.no_break")
open_break.ended_at = utcnow()
db.commit()
db.refresh(open_break)
return {"id": open_break.id, "shift_id": open_break.shift_id, "started_at": _dt(open_break.started_at), "ended_at": _dt(open_break.ended_at)}
@router.get("/")
def list_shifts(
waiter_id: Optional[int] = None,
business_day_id: Optional[int] = None,
active_only: bool = False,
db: Session = Depends(get_db),
user: User = Depends(require_manager),
):
q = db.query(WaiterShift)
if waiter_id:
q = q.filter(WaiterShift.waiter_id == waiter_id)
if business_day_id:
q = q.filter(WaiterShift.business_day_id == business_day_id)
if active_only:
q = q.filter(WaiterShift.ended_at == None)
shifts = q.order_by(WaiterShift.started_at.desc()).all()
return {"shifts": [_enrich_shift(s, db) for s in shifts]}
@router.get("/{shift_id}")
def get_shift(
shift_id: int,
db: Session = Depends(get_db),
user: User = Depends(require_manager),
):
shift = db.query(WaiterShift).filter(WaiterShift.id == shift_id).first()
if not shift:
raise XeniaError("shift.not_found")
return _enrich_shift(shift, db)
@router.delete("/{shift_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_shift(
shift_id: int,
db: Session = Depends(get_db),
user: User = Depends(require("core.settings.manage")),
):
"""Permanently delete a shift, its breaks, and all orders opened during that shift."""
from models.order import Order, OrderItem, OrderAuditLog, OrderWaiter
import json as _json
shift = db.query(WaiterShift).filter(WaiterShift.id == shift_id).first()
if not shift:
raise XeniaError("shift.not_found")
if shift.ended_at is None:
raise XeniaError("shift.delete_active")
# Find all orders opened during this shift's time window by this waiter
orders = db.query(Order).filter(
Order.opened_by == shift.waiter_id,
Order.opened_at >= shift.started_at,
Order.opened_at <= shift.ended_at,
).all()
for order in orders:
db.query(OrderAuditLog).filter(OrderAuditLog.order_id == order.id).delete(synchronize_session=False)
db.query(OrderWaiter).filter(OrderWaiter.order_id == order.id).delete(synchronize_session=False)
db.query(OrderItem).filter(OrderItem.order_id == order.id).delete(synchronize_session=False)
db.delete(order)
db.delete(shift)
db.commit()
@router.get("/{shift_id}/summary")
def get_shift_summary(
shift_id: int,
db: Session = Depends(get_db),
user: User = Depends(require_manager),
):
"""Full shift summary with complete per-item waiter attribution.
Returns all items that either:
- were paid in this shift (paid_in_shift_id == shift_id), OR
- were added by this waiter (added_by == waiter_id) and are active/unpaid or paid in another shift.
Each item includes added_by_name, paid_by_name, timestamps, and order context.
Orders include opener_name and closer_name.
"""
from models.order import Order
from models.table import Table
from sqlalchemy.orm import joinedload
shift = db.query(WaiterShift).filter(WaiterShift.id == shift_id).first()
if not shift:
raise XeniaError("shift.not_found")
waiter_id = shift.waiter_id
# Collect all relevant items: paid in this shift OR added by this waiter (any status)
paid_items = db.query(OrderItem).options(
joinedload(OrderItem.product),
joinedload(OrderItem.order),
).filter(
OrderItem.paid_in_shift_id == shift_id,
OrderItem.status == "paid",
).all()
from datetime import timezone as tz
upper_bound = shift.ended_at or utcnow()
ordered_items = db.query(OrderItem).options(
joinedload(OrderItem.product),
joinedload(OrderItem.order),
).filter(
OrderItem.added_by == waiter_id,
OrderItem.added_at >= shift.started_at,
OrderItem.added_at <= upper_bound,
(OrderItem.paid_in_shift_id != shift_id) | (OrderItem.paid_in_shift_id == None),
).all()
# Deduplicate: union by item id, paid_items takes precedence
items_by_id: dict[int, OrderItem] = {}
for item in ordered_items:
items_by_id[item.id] = item
for item in paid_items:
items_by_id[item.id] = item
all_items = list(items_by_id.values())
# Also include items cancelled within this shift window (may not be in ordered_items
# if they were cancelled after the shift ended or deduped out)
cancelled_items_for_summary = db.query(OrderItem).options(
joinedload(OrderItem.product),
joinedload(OrderItem.order),
).filter(
OrderItem.added_by == waiter_id,
OrderItem.status == "cancelled",
OrderItem.added_at >= shift.started_at,
OrderItem.added_at <= upper_bound,
).all()
for item in cancelled_items_for_summary:
if item.id not in items_by_id:
items_by_id[item.id] = item
all_items = list(items_by_id.values())
# Build lookup maps
all_waiter_ids = set()
for item in all_items:
all_waiter_ids.add(item.added_by)
if item.paid_by:
all_waiter_ids.add(item.paid_by)
all_order_ids = {item.order_id for item in all_items}
# Load orders with opener/closer
orders_db: dict[int, Order] = {}
if all_order_ids:
for o in db.query(Order).filter(Order.id.in_(all_order_ids)).all():
orders_db[o.id] = o
if o.opened_by:
all_waiter_ids.add(o.opened_by)
if o.closed_by:
all_waiter_ids.add(o.closed_by)
# Load table names
table_ids = {o.table_id for o in orders_db.values() if o.table_id}
tables_map: dict[int, str] = {}
if table_ids:
for t in db.query(Table).filter(Table.id.in_(table_ids)).all():
prefix = (t.group.prefix if t.group and t.group.prefix else "") if t.group else ""
tables_map[t.id] = t.label if t.label else f"{prefix}{t.number}"
# Load waiter names
waiters_map: dict[int, str] = {}
if all_waiter_ids:
for w in db.query(User).filter(User.id.in_(all_waiter_ids)).all():
waiters_map[w.id] = w.full_name or w.username
def _wname(wid):
if wid is None:
return None
return waiters_map.get(wid, f"#{wid}")
# Build orders dict
orders_out: dict[int, dict] = {}
for oid, o in orders_db.items():
tid = o.table_id
orders_out[oid] = {
"order_id": oid,
"table_id": tid,
"table_name": tables_map.get(tid) if tid else None,
"opened_at": _dt(o.opened_at),
"closed_at": _dt(o.closed_at),
"opener_name": _wname(o.opened_by),
"closer_name": _wname(o.closed_by),
"status": o.status,
"items": [],
}
# Attach items to their orders
for item in all_items:
oid = item.order_id
if oid not in orders_out:
continue
orders_out[oid]["items"].append({
"id": item.id,
"product_name": item.product.name if item.product else f"#{item.product_id}",
"quantity": item.quantity,
"unit_price": float(item.unit_price),
"subtotal": round(float(item.unit_price) * item.quantity, 2),
"status": item.status,
"added_by_id": item.added_by,
"added_by_name": _wname(item.added_by),
"added_at": _dt(item.added_at),
"paid_by_id": item.paid_by,
"paid_by_name": _wname(item.paid_by),
"paid_at": _dt(item.paid_at),
"paid_in_shift_id": item.paid_in_shift_id,
"payment_method": item.payment_method,
})
# Remove orders with no items (shouldn't happen but safety net)
populated_orders = [o for o in orders_out.values() if o["items"]]
# Compute duration
started = shift.started_at
ended = shift.ended_at
duration_minutes = None
if started and ended:
duration_minutes = int((ended - started).total_seconds() / 60)
elif started:
from datetime import timezone as tz
now = utcnow()
s = started if started.tzinfo else started.replace(tzinfo=tz.utc)
duration_minutes = int((now - s).total_seconds() / 60)
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