feat(manager): expenses, the supplier book and tabs on v2 (platform-v2 step 6.13a)

- Finance -> Expenses: still owed, late, filters, new/edit (supplier picked or added there), pay in parts, details with payments, delete
- CRM -> Contacts: the supplier book with what each one is owed
- Finance -> Tabs: open (who owes most first) / settled, charges and payments, pay (cash/card/other), close, forgive
- backend: expenses.manage / tabs.manage (the list also reports.view, a customer's tabs also crm.manage, put-on-tab needs tabs.manage);
  payment <= due (expense.over_due), total >= paid (expense.below_paid), categories/kinds/methods checked, null clears a field;
  live events expenses.changed / tabs.changed; GET /api/expenses ?from=&to= venue dates (the report uses it); tab_status=settled
- fix: an expense with a due date failed to save (naive date refused by D-11)
- @xenia/i18n/number subpath; tests: test_finance.py (6), finance.test.mjs (5), e2e manager.mjs finance flow

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-19 12:54:21 +02:00
co-authored by Claude Opus 5.5
parent 6bdf0bdd79
commit 93c0dd7d9c
32 changed files with 1667 additions and 1153 deletions
+91 -20
View File
@@ -1,5 +1,12 @@
from core.timeutil import utcnow
from datetime import datetime, timezone
"""Expenses and the supplier book (module `expenses`; manager pages in plan step 6.13a).
Every route needs `expenses.manage`; reading the list also works with `reports.view` (the
expenses report). Changes send the live event `expenses.changed` so open pages refresh.
An expense is entered once (total, category, maybe a supplier and a date it's due) and paid
in one or more payments; it is "due", "partial" or "paid" from what was paid. A payment can't
be more than what is still due, and the total can't drop below what was already paid.
"""
from datetime import date
from fastapi import APIRouter, Depends, status, Query
from sqlalchemy.orm import Session
from typing import List, Optional
@@ -12,14 +19,42 @@ from schemas.expenses import (
ExpenseCreate, ExpenseUpdate, ExpenseOut,
ExpensePaymentCreate, ExpensePaymentOut,
)
from routers.deps import require_manager
from core.access.deps import require, require_any
from core.errors import XeniaError
from core.timeutil import venue_day_window
from services.ws_bus import broadcast_sync
contacts_router = APIRouter()
expenses_router = APIRouter()
MANAGE = Depends(require("expenses.manage"))
CATEGORIES = ("supplier", "utilities", "rent", "maintenance", "staff", "equipment", "other")
CONTACT_TYPES = ("supplier", "staff", "utility", "other")
def _changed():
broadcast_sync("expenses.changed", {})
def _check_contact(fields: dict):
if "type" in fields and fields["type"] not in CONTACT_TYPES:
raise XeniaError("validation.choice", field="type", value=fields["type"])
if "name" in fields and not (fields["name"] or "").strip():
raise XeniaError("validation.missing", field="name")
def _check_expense(db: Session, fields: dict, paid: float = 0.0):
if "description" in fields and not (fields["description"] or "").strip():
raise XeniaError("validation.missing", field="description")
if "category" in fields and fields["category"] not in CATEGORIES:
raise XeniaError("validation.choice", field="category", value=fields["category"])
if "total_amount" in fields:
if fields["total_amount"] is None or fields["total_amount"] <= 0:
raise XeniaError("validation.positive", field="total_amount")
if fields["total_amount"] < paid - 0.005:
raise XeniaError("expense.below_paid", paid=f"{paid:.2f}")
if fields.get("contact_id") and not db.query(Contact).filter(Contact.id == fields["contact_id"]).first():
raise XeniaError("contact.not_found")
def _expense_status(total: float, paid: float) -> str:
if paid >= total:
@@ -77,7 +112,7 @@ def _expense_out(e: Expense) -> dict:
def list_contacts(
include_inactive: bool = False,
db: Session = Depends(get_db),
user: User = Depends(require_manager),
user: User = MANAGE,
):
q = db.query(Contact)
if not include_inactive:
@@ -86,33 +121,45 @@ def list_contacts(
@contacts_router.post("/", response_model=ContactOut, status_code=status.HTTP_201_CREATED)
def create_contact(body: ContactCreate, db: Session = Depends(get_db), user: User = Depends(require_manager)):
contact = Contact(**body.model_dump())
def create_contact(body: ContactCreate, db: Session = Depends(get_db), user: User = MANAGE):
fields = body.model_dump()
_check_contact(fields)
fields["name"] = fields["name"].strip()
contact = Contact(**fields)
db.add(contact)
db.commit()
db.refresh(contact)
_changed()
return contact
@contacts_router.put("/{contact_id}", response_model=ContactOut)
def update_contact(contact_id: int, body: ContactUpdate, db: Session = Depends(get_db), user: User = Depends(require_manager)):
def update_contact(contact_id: int, body: ContactUpdate, db: Session = Depends(get_db), user: User = MANAGE):
contact = db.query(Contact).filter(Contact.id == contact_id).first()
if not contact:
raise XeniaError("contact.not_found")
for field, value in body.model_dump(exclude_none=True).items():
setattr(contact, field, value)
# Fields sent as null are cleared (phone, e-mail...); name and type only change when given
fields = body.model_dump(exclude_unset=True)
for k in ("name", "type", "is_active"):
if fields.get(k) is None:
fields.pop(k, None)
_check_contact(fields)
for field, value in fields.items():
setattr(contact, field, value.strip() if field == "name" else value)
db.commit()
db.refresh(contact)
_changed()
return contact
@contacts_router.delete("/{contact_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_contact(contact_id: int, db: Session = Depends(get_db), user: User = Depends(require_manager)):
def delete_contact(contact_id: int, db: Session = Depends(get_db), user: User = MANAGE):
contact = db.query(Contact).filter(Contact.id == contact_id).first()
if not contact:
raise XeniaError("contact.not_found")
contact.is_active = False
db.commit()
_changed()
# ── Expenses ──────────────────────────────────────────────────────────────────
@@ -120,7 +167,7 @@ def delete_contact(contact_id: int, db: Session = Depends(get_db), user: User =
@expenses_router.get("/summary")
def expense_summary(
db: Session = Depends(get_db),
user: User = Depends(require_manager),
user: User = MANAGE,
):
expenses = db.query(Expense).all()
total_due = sum(max(0.0, e.total_amount - e.paid_amount) for e in expenses if e.paid_amount < e.total_amount)
@@ -146,10 +193,18 @@ def list_expenses(
category: Optional[str] = None,
contact_id: Optional[int] = None,
business_day_id: Optional[int] = None,
date_from: Optional[date] = Query(default=None, alias="from"),
date_to: Optional[date] = Query(default=None, alias="to"),
db: Session = Depends(get_db),
user: User = Depends(require_manager),
user: User = Depends(require_any("expenses.manage", "reports.view")),
):
expenses = db.query(Expense).order_by(Expense.created_at.desc()).all()
"""Newest first. `from` / `to` are venue dates (inclusive) of the day each was entered."""
q = db.query(Expense)
if date_from:
q = q.filter(Expense.created_at >= venue_day_window(date_from)[0])
if date_to:
q = q.filter(Expense.created_at < venue_day_window(date_to)[1])
expenses = q.order_by(Expense.created_at.desc()).all()
result = [_expense_out(e) for e in expenses]
if expense_status:
result = [e for e in result if e["status"] == expense_status]
@@ -163,33 +218,45 @@ def list_expenses(
@expenses_router.post("/", response_model=ExpenseOut, status_code=status.HTTP_201_CREATED)
def create_expense(body: ExpenseCreate, db: Session = Depends(get_db), user: User = Depends(require_manager)):
expense = Expense(**body.model_dump(), created_by_id=user.id)
def create_expense(body: ExpenseCreate, db: Session = Depends(get_db), user: User = MANAGE):
fields = body.model_dump()
_check_expense(db, fields)
fields["description"] = fields["description"].strip()
expense = Expense(**fields, created_by_id=user.id)
db.add(expense)
db.commit()
db.refresh(expense)
_changed()
return _expense_out(expense)
@expenses_router.put("/{expense_id}", response_model=ExpenseOut)
def update_expense(expense_id: int, body: ExpenseUpdate, db: Session = Depends(get_db), user: User = Depends(require_manager)):
def update_expense(expense_id: int, body: ExpenseUpdate, db: Session = Depends(get_db), user: User = MANAGE):
expense = db.query(Expense).filter(Expense.id == expense_id).first()
if not expense:
raise XeniaError("expense.not_found")
for field, value in body.model_dump(exclude_none=True).items():
setattr(expense, field, value)
# Fields sent as null are cleared (supplier, due date, notes); the rest only change when given
fields = body.model_dump(exclude_unset=True)
for k in ("description", "category", "total_amount"):
if fields.get(k) is None:
fields.pop(k, None)
_check_expense(db, fields, paid=expense.paid_amount)
for field, value in fields.items():
setattr(expense, field, value.strip() if field == "description" else value)
db.commit()
db.refresh(expense)
_changed()
return _expense_out(expense)
@expenses_router.delete("/{expense_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_expense(expense_id: int, db: Session = Depends(get_db), user: User = Depends(require_manager)):
def delete_expense(expense_id: int, db: Session = Depends(get_db), user: User = MANAGE):
expense = db.query(Expense).filter(Expense.id == expense_id).first()
if not expense:
raise XeniaError("expense.not_found")
db.delete(expense)
db.commit()
_changed()
@expenses_router.post("/{expense_id}/pay", response_model=ExpenseOut)
@@ -197,13 +264,16 @@ def record_payment(
expense_id: int,
body: ExpensePaymentCreate,
db: Session = Depends(get_db),
user: User = Depends(require_manager),
user: User = MANAGE,
):
expense = db.query(Expense).filter(Expense.id == expense_id).first()
if not expense:
raise XeniaError("expense.not_found")
if body.amount <= 0:
raise XeniaError("validation.positive", field='amount')
due = round(max(0.0, expense.total_amount - expense.paid_amount), 2)
if body.amount > due + 0.005:
raise XeniaError("expense.over_due", due=f"{due:.2f}")
payment = ExpensePayment(
expense_id=expense_id,
amount=body.amount,
@@ -217,4 +287,5 @@ def record_payment(
expense.paid_amount = round(sum(p.amount for p in all_payments), 2)
db.commit()
db.refresh(expense)
_changed()
return _expense_out(expense)
+4 -1
View File
@@ -57,6 +57,7 @@ class RevertPaymentRequest(BaseModel):
item_ids: List[int]
from routers.deps import get_current_user, require_manager
from core.access.deps import require
from services.printer_service import route_and_print, route_and_print_sync, print_order_receipt, print_order_synopsis, print_cancellation_ticket
from models.settings import PosSettings
from services.ws_bus import broadcast_sync
@@ -2019,7 +2020,7 @@ def put_item_on_tab(
order_id: int,
item_id: int,
db: Session = Depends(get_db),
user: User = Depends(require_manager),
user: User = Depends(require("tabs.manage")), # also needs the tabs module on (6.13a)
):
from models.tabs import Tab, TabEntry
@@ -2061,6 +2062,8 @@ def put_item_on_tab(
db.commit()
broadcast_sync("order_updated", {"order_id": order.id, "table_id": order.table_id, "status": order.status, "action": "item_tabbed"})
from routers.tabs import changed as tabs_changed
tabs_changed()
return {"status": "tabbed", "tab_id": tab.id, "entry_amount": entry.amount}
+39 -14
View File
@@ -1,5 +1,13 @@
"""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 datetime import datetime, timezone
from fastapi import APIRouter, Depends, status
from sqlalchemy.orm import Session
from typing import List, Optional
@@ -10,13 +18,19 @@ 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 routers.deps import require_manager
from core.access.deps import require, require_any
from core.errors import XeniaError
from services.ws_bus import broadcast_sync
router = APIRouter()
MANAGE = Depends(require("tabs.manage"))
METHODS = ("cash", "card", "other")
def changed():
broadcast_sync("tabs.changed", {})
def _tab_out(tab: Tab) -> dict:
c = tab.customer
@@ -75,10 +89,12 @@ def list_tabs(
tab_status: Optional[str] = None,
customer_id: Optional[int] = None,
db: Session = Depends(get_db),
user: User = Depends(require_manager),
user: User = MANAGE,
):
q = db.query(Tab)
if tab_status:
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
@@ -86,13 +102,13 @@ def list_tabs(
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]
# Sort open tabs by balance descending
result.sort(key=lambda x: x["balance"], reverse=True)
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 = Depends(require_manager)):
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")
@@ -100,7 +116,7 @@ def get_tab(tab_id: int, db: Session = Depends(get_db), user: User = Depends(req
@router.post("/", response_model=TabOut, status_code=status.HTTP_201_CREATED)
def open_tab(customer_id: int, db: Session = Depends(get_db), user: User = Depends(require_manager)):
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")
@@ -111,6 +127,7 @@ def open_tab(customer_id: int, db: Session = Depends(get_db), user: User = Depen
db.add(tab)
db.commit()
db.refresh(tab)
changed()
return _tab_out(tab)
@@ -122,7 +139,7 @@ def add_tab_entry(
amount: float = 0.0,
description: Optional[str] = None,
db: Session = Depends(get_db),
user: User = Depends(require_manager),
user: User = MANAGE,
):
tab = db.query(Tab).filter(Tab.id == tab_id, Tab.status == "open").first()
if not tab:
@@ -136,6 +153,7 @@ def add_tab_entry(
db.add(entry)
db.commit()
db.refresh(tab)
changed()
return _tab_out(tab)
@@ -144,7 +162,7 @@ def pay_tab(
tab_id: int,
body: TabPayRequest,
db: Session = Depends(get_db),
user: User = Depends(require_manager),
user: User = MANAGE,
):
tab = db.query(Tab).filter(Tab.id == tab_id, Tab.status == "open").first()
if not tab:
@@ -156,14 +174,18 @@ def pay_tab(
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=body.payment_method, notes=body.notes,
payment_method=method, notes=body.notes,
received_by_id=user.id,
)
db.add(payment)
db.commit()
db.refresh(tab)
changed()
return _tab_out(tab)
@@ -172,7 +194,7 @@ def close_tab(
tab_id: int,
body: TabCloseRequest,
db: Session = Depends(get_db),
user: User = Depends(require_manager),
user: User = MANAGE,
):
tab = db.query(Tab).filter(Tab.id == tab_id, Tab.status == "open").first()
if not tab:
@@ -189,6 +211,7 @@ def close_tab(
tab.notes = body.notes
db.commit()
db.refresh(tab)
changed()
return _tab_out(tab)
@@ -197,7 +220,7 @@ def forgive_tab(
tab_id: int,
body: TabForgiveRequest,
db: Session = Depends(get_db),
user: User = Depends(require_manager),
user: User = MANAGE,
):
tab = db.query(Tab).filter(Tab.id == tab_id, Tab.status == "open").first()
if not tab:
@@ -209,13 +232,15 @@ def forgive_tab(
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_manager)):
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(),