"""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 decimal import ROUND_HALF_UP, Decimal from fastapi import APIRouter, Depends, File, Query, UploadFile, status from fastapi.responses import FileResponse from sqlalchemy.orm import Session from typing import List, Optional from database import get_db from models.expenses import Contact, Expense, ExpenseDocument, ExpenseLine, ExpensePayment from models.user import User from schemas.expenses import ( ContactCreate, ContactUpdate, ContactOut, ExpenseCreate, ExpenseUpdate, ExpenseOut, ExpensePaymentCreate, ExpensePaymentOut, ) from core.access.deps import require, require_any from core.errors import XeniaError from core.timeutil import venue_day_window from services import expense_docs 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 _line_money(ln) -> tuple[float, float, float]: """(net, vat, total) of a line, rounded to cents.""" q = ln["quantity"] if isinstance(ln, dict) else ln.quantity p = ln["unit_price"] if isinstance(ln, dict) else ln.unit_price r = ln["vat_rate"] if isinstance(ln, dict) else ln.vat_rate cents = Decimal("0.01") net = (Decimal(str(q or 0)) * Decimal(str(p or 0))).quantize(cents, ROUND_HALF_UP) vat = (net * Decimal(str(r or 0)) / 100).quantize(cents, ROUND_HALF_UP) # as on a Greek invoice: half up return float(net), float(vat), float(net + vat) def _take_lines(fields: dict) -> list | None: """The lines sent (checked), and the total they make into fields["total_amount"].""" lines = fields.pop("lines", None) if lines is None: return None out = [] for ln in lines: d = (ln.get("description") or "").strip() if not d: raise XeniaError("validation.missing", field="lines.description") if ln.get("quantity") is None or ln["quantity"] <= 0: raise XeniaError("validation.positive", field="lines.quantity") if ln.get("unit_price") is None or ln["unit_price"] < 0: raise XeniaError("validation.positive", field="lines.unit_price") if (ln.get("vat_rate") or 0) < 0 or (ln.get("vat_rate") or 0) > 100: raise XeniaError("validation.choice", field="lines.vat_rate", value=ln.get("vat_rate")) out.append({**ln, "description": d[:200], "vat_rate": ln.get("vat_rate") or 0.0}) if out: fields["total_amount"] = round(sum(_line_money(ln)[2] for ln in out), 2) return out def _set_lines(expense: Expense, lines: list | None): if lines is None: return expense.lines = [ExpenseLine(position=i, **ln) for i, ln in enumerate(lines)] 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: return "paid" if paid > 0: return "partial" return "due" def _expense_out(e: Expense) -> dict: contact_name = None if e.contact: contact_name = e.contact.name creator_name = None if e.created_by: creator_name = e.created_by.full_name or e.created_by.username due_amount = round(max(0.0, e.total_amount - e.paid_amount), 2) payments_out = [] for p in e.payments: payer_name = None if p.paid_by: payer_name = p.paid_by.full_name or p.paid_by.username payments_out.append({ "id": p.id, "expense_id": p.expense_id, "amount": p.amount, "paid_at": p.paid_at, "paid_by_id": p.paid_by_id, "paid_by_name": payer_name, "notes": p.notes, }) return { "id": e.id, "description": e.description, "category": e.category, "contact_id": e.contact_id, "contact_name": contact_name, "total_amount": e.total_amount, "paid_amount": e.paid_amount, "due_amount": due_amount, "status": _expense_status(e.total_amount, e.paid_amount), "due_date": e.due_date, "business_day_id": e.business_day_id, "created_by_id": e.created_by_id, "created_by_name": creator_name, "created_at": e.created_at, "notes": e.notes, "payments": payments_out, "lines": [{"id": ln.id, "description": ln.description, "quantity": ln.quantity, "unit_price": ln.unit_price, "vat_rate": ln.vat_rate, **dict(zip(("net", "vat", "total"), _line_money(ln)))} for ln in e.lines], "net_amount": round(sum(_line_money(ln)[0] for ln in e.lines), 2) if e.lines else None, "vat_amount": round(sum(_line_money(ln)[1] for ln in e.lines), 2) if e.lines else None, "documents": [expense_docs.out(d) for d in e.documents], } # ── Contacts ────────────────────────────────────────────────────────────────── @contacts_router.get("/", response_model=List[ContactOut]) def list_contacts( include_inactive: bool = False, db: Session = Depends(get_db), user: User = MANAGE, ): q = db.query(Contact) if not include_inactive: q = q.filter(Contact.is_active == True) return q.order_by(Contact.name).all() @contacts_router.post("/", response_model=ContactOut, status_code=status.HTTP_201_CREATED) 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 = MANAGE): contact = db.query(Contact).filter(Contact.id == contact_id).first() if not contact: raise XeniaError("contact.not_found") # 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 = 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 ────────────────────────────────────────────────────────────────── @expenses_router.get("/summary") def expense_summary( db: Session = Depends(get_db), 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) total_paid = sum(e.paid_amount for e in expenses) by_category: dict = {} for e in expenses: c = e.category if c not in by_category: by_category[c] = {"category": c, "total": 0.0, "paid": 0.0, "due": 0.0} by_category[c]["total"] += e.total_amount by_category[c]["paid"] += e.paid_amount by_category[c]["due"] += max(0.0, e.total_amount - e.paid_amount) return { "total_due": round(total_due, 2), "total_paid": round(total_paid, 2), "by_category": list(by_category.values()), } @expenses_router.get("/", response_model=List[ExpenseOut]) def list_expenses( expense_status: Optional[str] = Query(default=None, alias="status"), 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_any("expenses.manage", "reports.view")), ): """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] if category: result = [e for e in result if e["category"] == category] if contact_id: result = [e for e in result if e["contact_id"] == contact_id] if business_day_id: result = [e for e in result if e["business_day_id"] == business_day_id] return result @expenses_router.post("/", response_model=ExpenseOut, status_code=status.HTTP_201_CREATED) def create_expense(body: ExpenseCreate, db: Session = Depends(get_db), user: User = MANAGE): fields = body.model_dump() lines = _take_lines(fields) if fields.get("total_amount") is None: raise XeniaError("validation.positive", field="total_amount") _check_expense(db, fields) fields["description"] = fields["description"].strip() expense = Expense(**fields, created_by_id=user.id) _set_lines(expense, lines) 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 = MANAGE): expense = db.query(Expense).filter(Expense.id == expense_id).first() if not expense: raise XeniaError("expense.not_found") # Fields sent as null are cleared (supplier, due date, notes); the rest only change when given fields = body.model_dump(exclude_unset=True) if fields.get("lines") is None: fields.pop("lines", None) lines = _take_lines(fields) 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) _set_lines(expense, lines) 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 = MANAGE): expense = db.query(Expense).filter(Expense.id == expense_id).first() if not expense: raise XeniaError("expense.not_found") db.delete(expense) db.commit() expense_docs.remove_all(expense_id) _changed() @expenses_router.post("/{expense_id}/pay", response_model=ExpenseOut) def record_payment( expense_id: int, body: ExpensePaymentCreate, 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") 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, paid_by_id=user.id, notes=body.notes, ) db.add(payment) db.flush() # recompute paid_amount from all payments (never trust client totals) all_payments = db.query(ExpensePayment).filter(ExpensePayment.expense_id == expense_id).all() expense.paid_amount = round(sum(p.amount for p in all_payments), 2) db.commit() db.refresh(expense) _changed() return _expense_out(expense) # ── Documents: the invoice / receipt kept with an expense (2026-11-20) ──────────── def _expense(db: Session, expense_id: int) -> Expense: expense = db.query(Expense).filter(Expense.id == expense_id).first() if not expense: raise XeniaError("expense.not_found") return expense @expenses_router.post("/{expense_id}/documents", response_model=ExpenseOut, status_code=status.HTTP_201_CREATED) def upload_document(expense_id: int, file: UploadFile = File(...), db: Session = Depends(get_db), user: User = MANAGE): """A PDF or a photo (JPG, PNG, WebP, HEIC), at most 15 MB.""" expense = _expense(db, expense_id) stored, content_type, size = expense_docs.save(expense_id, file) expense.documents.append(ExpenseDocument(filename=(file.filename or "document")[:200], stored_name=stored, content_type=content_type, size=size, uploaded_by_id=user.id)) db.commit() db.refresh(expense) _changed() return _expense_out(expense) @expenses_router.get("/{expense_id}/documents/{doc_id}") def get_document(expense_id: int, doc_id: int, db: Session = Depends(get_db), user: User = Depends(require_any("expenses.manage", "reports.view"))): doc = db.query(ExpenseDocument).filter(ExpenseDocument.id == doc_id, ExpenseDocument.expense_id == expense_id).first() path = expense_docs.path(doc) if doc else None if not path: raise XeniaError("expense.document_not_found") return FileResponse(path, media_type=doc.content_type, filename=doc.filename, content_disposition_type="inline") @expenses_router.delete("/{expense_id}/documents/{doc_id}", response_model=ExpenseOut) def delete_document(expense_id: int, doc_id: int, db: Session = Depends(get_db), user: User = MANAGE): expense = _expense(db, expense_id) doc = next((d for d in expense.documents if d.id == doc_id), None) if not doc: raise XeniaError("expense.document_not_found") expense_docs.remove(doc) expense.documents.remove(doc) db.commit() db.refresh(expense) _changed() return _expense_out(expense)