feat(backend): expense lines (quantity, price before VAT, VAT %) and documents (PDF / photo)
An expense can list what it bought; the lines make its total (net, VAT half up per line), are
replaced on edit ([] removes them) and the total still can't drop below what was paid. Files kept
with an expense: POST/GET/DELETE /api/expenses/{id}/documents[/{doc}], PDF / JPG / PNG / WebP /
HEIC by their bytes, at most 15 MB, under MEDIA_DIR/expenses/<id>/ (removed with the expense).
Migration 0039.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -7,12 +7,14 @@ in one or more payments; it is "due", "partial" or "paid" from what was paid. A
|
||||
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 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, ExpensePayment
|
||||
from models.expenses import Contact, Expense, ExpenseDocument, ExpenseLine, ExpensePayment
|
||||
from models.user import User
|
||||
from schemas.expenses import (
|
||||
ContactCreate, ContactUpdate, ContactOut,
|
||||
@@ -22,6 +24,7 @@ from schemas.expenses import (
|
||||
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()
|
||||
@@ -43,6 +46,45 @@ def _check_contact(fields: dict):
|
||||
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")
|
||||
@@ -103,6 +145,11 @@ def _expense_out(e: Expense) -> dict:
|
||||
"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],
|
||||
}
|
||||
|
||||
|
||||
@@ -220,9 +267,13 @@ 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 = 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)
|
||||
@@ -237,12 +288,16 @@ def update_expense(expense_id: int, body: ExpenseUpdate, db: Session = Depends(g
|
||||
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()
|
||||
@@ -256,6 +311,7 @@ def delete_expense(expense_id: int, db: Session = Depends(get_db), user: User =
|
||||
raise XeniaError("expense.not_found")
|
||||
db.delete(expense)
|
||||
db.commit()
|
||||
expense_docs.remove_all(expense_id)
|
||||
_changed()
|
||||
|
||||
|
||||
@@ -289,3 +345,49 @@ def record_payment(
|
||||
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)
|
||||
|
||||
Reference in New Issue
Block a user