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:
2026-11-20 14:57:58 +02:00
co-authored by Claude Opus 5.5
parent 5915177c82
commit 9297cbcd3b
9 changed files with 361 additions and 5 deletions
+3
View File
@@ -198,6 +198,9 @@ CODES: dict[str, tuple[int, str]] = {
"expense.not_found": (404, "Expense not found."),
"expense.over_due": (400, "That's more than what is still due ({due})."),
"expense.below_paid": (400, "{paid} has been paid already: the total can't be less."),
"expense.document_not_found": (404, "Document not found."),
"expense.document_type": (422, "Upload a PDF or a photo (JPG, PNG, WebP or HEIC)."),
"expense.document_too_big": (413, "The file is too big (at most {max_mb} MB)."),
"flag.not_found": (404, "Mark not found."),
"flag.in_use": (409, "This mark is on {count} table(s). Remove it there first."),
"flag.invalid_ids": (400, "Some of these marks don't exist."),
@@ -0,0 +1,54 @@
"""Expense lines and documents (UI review 2026-11-20): what an expense bought (quantity, price
before VAT, VAT rate; the lines make the total) and the files kept with it (the invoice as a
PDF, a photo of the receipt).
Revision ID: 0039_expense_lines_documents
Revises: 0038_lookup_indexes
Create Date: 2026-11-20 16:00:00
"""
from alembic import op
import sqlalchemy as sa
from core.timeutil import UTCDateTime
revision = '0039_expense_lines_documents'
down_revision = '0038_lookup_indexes'
branch_labels = None
depends_on = None
def upgrade() -> None:
op.create_table(
'expense_lines',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('expense_id', sa.Integer(), nullable=False),
sa.Column('position', sa.Integer(), nullable=False),
sa.Column('description', sa.String(), nullable=False),
sa.Column('quantity', sa.Float(), nullable=False),
sa.Column('unit_price', sa.Float(), nullable=False),
sa.Column('vat_rate', sa.Float(), nullable=False),
sa.ForeignKeyConstraint(['expense_id'], ['expenses.id']),
sa.PrimaryKeyConstraint('id'),
)
op.create_index('ix_expense_lines_id', 'expense_lines', ['id'])
op.create_index('ix_expense_lines_expense_id', 'expense_lines', ['expense_id'])
op.create_table(
'expense_documents',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('expense_id', sa.Integer(), nullable=False),
sa.Column('filename', sa.String(), nullable=False),
sa.Column('stored_name', sa.String(), nullable=False),
sa.Column('content_type', sa.String(), nullable=False),
sa.Column('size', sa.Integer(), nullable=False),
sa.Column('uploaded_by_id', sa.Integer(), nullable=True),
sa.Column('uploaded_at', UTCDateTime(), nullable=True),
sa.ForeignKeyConstraint(['expense_id'], ['expenses.id']),
sa.ForeignKeyConstraint(['uploaded_by_id'], ['users.id']),
sa.PrimaryKeyConstraint('id'),
)
op.create_index('ix_expense_documents_id', 'expense_documents', ['id'])
op.create_index('ix_expense_documents_expense_id', 'expense_documents', ['expense_id'])
def downgrade() -> None:
op.drop_table('expense_documents')
op.drop_table('expense_lines')
+39
View File
@@ -40,6 +40,11 @@ class Expense(Base):
contact = relationship("Contact", back_populates="expenses")
created_by = relationship("User", foreign_keys=[created_by_id])
payments = relationship("ExpensePayment", back_populates="expense", cascade="all, delete-orphan")
# what was bought (2026-11-20): when an expense has lines, its total is theirs
lines = relationship("ExpenseLine", back_populates="expense", cascade="all, delete-orphan",
order_by="ExpenseLine.position")
documents = relationship("ExpenseDocument", back_populates="expense", cascade="all, delete-orphan",
order_by="ExpenseDocument.id")
class ExpensePayment(Base):
@@ -54,3 +59,37 @@ class ExpensePayment(Base):
expense = relationship("Expense", back_populates="payments")
paid_by = relationship("User", foreign_keys=[paid_by_id])
class ExpenseLine(Base):
"""A line of an expense (2026-11-20): what was bought, how many, the price of one before VAT
and its VAT rate. Line total = quantity × unit price × (1 + VAT %)."""
__tablename__ = "expense_lines"
id = Column(Integer, primary_key=True, index=True)
expense_id = Column(Integer, ForeignKey("expenses.id"), nullable=False, index=True)
position = Column(Integer, default=0, nullable=False)
description = Column(String, nullable=False)
quantity = Column(Float, default=1.0, nullable=False)
unit_price = Column(Float, nullable=False) # one, before VAT
vat_rate = Column(Float, default=0.0, nullable=False) # %, e.g. 24
expense = relationship("Expense", back_populates="lines")
class ExpenseDocument(Base):
"""A file kept with an expense (2026-11-20): the invoice as a PDF or a photo of the receipt.
Stored under MEDIA_DIR/expenses/<expense id>/ (services/expense_docs.py)."""
__tablename__ = "expense_documents"
id = Column(Integer, primary_key=True, index=True)
expense_id = Column(Integer, ForeignKey("expenses.id"), nullable=False, index=True)
filename = Column(String, nullable=False) # as uploaded
stored_name = Column(String, nullable=False) # on disk
content_type = Column(String, nullable=False)
size = Column(Integer, nullable=False)
uploaded_by_id = Column(Integer, ForeignKey("users.id"), nullable=True)
uploaded_at = Column(UTCDateTime, default=utcnow)
expense = relationship("Expense", back_populates="documents")
uploaded_by = relationship("User", foreign_keys=[uploaded_by_id])
+104 -2
View File
@@ -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)
+30 -1
View File
@@ -59,11 +59,35 @@ class ExpensePaymentOut(BaseModel):
model_config = {"from_attributes": True}
class ExpenseLineIn(BaseModel):
description: str
quantity: float = 1.0
unit_price: float
vat_rate: float = 0.0
class ExpenseLineOut(ExpenseLineIn):
id: int
net: float
vat: float
total: float
class ExpenseDocumentOut(BaseModel):
id: int
filename: str
content_type: str
size: int
uploaded_at: datetime
uploaded_by_name: Optional[str] = None
class ExpenseCreate(BaseModel):
description: str
category: str
contact_id: Optional[int] = None
total_amount: float
total_amount: Optional[float] = None # left out when the lines make it
lines: Optional[List[ExpenseLineIn]] = None
due_date: Optional[datetime] = None
business_day_id: Optional[int] = None
notes: Optional[str] = None
@@ -80,6 +104,7 @@ class ExpenseUpdate(BaseModel):
category: Optional[str] = None
contact_id: Optional[int] = None
total_amount: Optional[float] = None
lines: Optional[List[ExpenseLineIn]] = None # given: replaces the lines ([] = none)
due_date: Optional[datetime] = None
notes: Optional[str] = None
@@ -107,5 +132,9 @@ class ExpenseOut(BaseModel):
created_at: datetime
notes: Optional[str] = None
payments: List[ExpensePaymentOut] = []
lines: List[ExpenseLineOut] = []
net_amount: Optional[float] = None # from the lines
vat_amount: Optional[float] = None
documents: List[ExpenseDocumentOut] = []
model_config = {"from_attributes": True}
+79
View File
@@ -0,0 +1,79 @@
"""The files kept with expenses (2026-11-20): an invoice as a PDF or a photo of a receipt.
Stored under MEDIA_DIR/expenses/<expense id>/<random name><ext> (inside the site's data, next to
pos.db, so a backup takes them along). The type comes from the file's first bytes, not from
the browser: PDF, JPG, PNG, WebP or HEIC, at most 15 MB.
"""
from __future__ import annotations
import os
import shutil
import uuid
from core.errors import XeniaError
from services.media import MEDIA_DIR
MAX_BYTES = 15 * 1024 * 1024
TYPES = { # magic bytes -> (content type, extension)
b"%PDF": ("application/pdf", ".pdf"),
b"\xff\xd8\xff": ("image/jpeg", ".jpg"),
b"\x89PNG": ("image/png", ".png"),
}
def _dir(expense_id: int) -> str:
return os.path.join(MEDIA_DIR, "expenses", str(int(expense_id)))
def _kind(head: bytes) -> tuple[str, str] | None:
for magic, kind in TYPES.items():
if head.startswith(magic):
return kind
if head[:4] == b"RIFF" and head[8:12] == b"WEBP":
return "image/webp", ".webp"
if head[4:8] == b"ftyp" and head[8:12] in (b"heic", b"heix", b"mif1", b"msf1", b"hevc"):
return "image/heic", ".heic"
return None
def save(expense_id: int, upload) -> tuple[str, str, int]:
"""Write the upload → (stored name, content type, size). Refuses other types and big files."""
head = upload.file.read(16)
kind = _kind(head)
if not kind:
raise XeniaError("expense.document_type")
os.makedirs(_dir(expense_id), exist_ok=True)
name = uuid.uuid4().hex + kind[1]
target = os.path.join(_dir(expense_id), name)
size = len(head)
with open(target, "wb") as out:
out.write(head)
while chunk := upload.file.read(1024 * 1024):
size += len(chunk)
if size > MAX_BYTES:
out.close()
os.remove(target)
raise XeniaError("expense.document_too_big", max_mb=MAX_BYTES // (1024 * 1024))
out.write(chunk)
return name, kind[0], size
def path(doc) -> str | None:
p = os.path.join(_dir(doc.expense_id), os.path.basename(doc.stored_name))
return p if os.path.isfile(p) else None
def remove(doc) -> None:
p = path(doc)
if p:
os.remove(p)
def remove_all(expense_id: int) -> None:
shutil.rmtree(_dir(expense_id), ignore_errors=True)
def out(doc) -> dict:
who = doc.uploaded_by
return {"id": doc.id, "filename": doc.filename, "content_type": doc.content_type, "size": doc.size,
"uploaded_at": doc.uploaded_at, "uploaded_by_name": (who.full_name or who.username) if who else None}
+44
View File
@@ -122,3 +122,47 @@ def test_tabs_need_their_own_key(client, db, make_user, login):
no = login(make_user(role="staff_manager")) # has the dashboard, not tabs.manage
assert client.get("/api/tabs/", headers=no).status_code == 403
assert client.post("/api/orders/1/items/1/tab", headers=no).status_code == 403
def test_expense_lines_make_the_total(client, make_user, login):
"""2026-11-20: an expense can list what it bought (quantity, price before VAT, VAT %);
the lines make its total, and editing them changes it (never below what was paid)."""
h = login(make_user(role="owner"))
r = client.post("/api/expenses/", headers=h, json={"description": "Market", "category": "supplier", "lines": [
{"description": "Tomatoes", "quantity": 3, "unit_price": 2.5, "vat_rate": 13},
{"description": "Bags", "quantity": 1, "unit_price": 10, "vat_rate": 24}]})
assert r.status_code == 201, r.text
e = r.json()
assert [ln["total"] for ln in e["lines"]] == [8.48, 12.4]
assert e["net_amount"] == 17.5 and e["vat_amount"] == 3.38 and e["total_amount"] == 20.88
client.post(f"/api/expenses/{e['id']}/pay", headers=h, json={"amount": 15})
# fewer lines than what was paid: refused
r = client.put(f"/api/expenses/{e['id']}", headers=h, json={"lines": [{"description": "Bags", "quantity": 1, "unit_price": 10}]})
assert r.status_code == 400 and r.json()["error"]["code"] == "expense.below_paid"
# lines cleared: the total stays as it was and is typed again
r = client.put(f"/api/expenses/{e['id']}", headers=h, json={"lines": [], "total_amount": 21})
assert r.status_code == 200 and r.json()["lines"] == [] and r.json()["total_amount"] == 21
# a line needs a description and a positive quantity
bad = client.post("/api/expenses/", headers=h, json={"description": "X", "category": "other", "lines": [{"description": " ", "quantity": 1, "unit_price": 1}]})
assert bad.json()["error"]["code"] == "validation.missing"
# no lines and no total: refused
assert client.post("/api/expenses/", headers=h, json={"description": "X", "category": "other"}).json()["error"]["code"] == "validation.positive"
def test_expense_documents(client, make_user, login, tmp_path, monkeypatch):
"""A PDF or a photo kept with an expense: uploaded, read back, removed; other files refused."""
import services.expense_docs as docs
monkeypatch.setattr(docs, "MEDIA_DIR", str(tmp_path))
h = login(make_user(role="owner"))
e = client.post("/api/expenses/", headers=h, json={"description": "Gas", "category": "utilities", "total_amount": 40}).json()
pdf = b"%PDF-1.4\n%fake\n" + b"0" * 100
r = client.post(f"/api/expenses/{e['id']}/documents", headers=h, files={"file": ("bill.pdf", pdf, "application/pdf")})
assert r.status_code == 201, r.text
doc = r.json()["documents"][0]
assert doc["filename"] == "bill.pdf" and doc["content_type"] == "application/pdf" and doc["size"] == len(pdf)
got = client.get(f"/api/expenses/{e['id']}/documents/{doc['id']}", headers=h)
assert got.status_code == 200 and got.content == pdf
assert client.post(f"/api/expenses/{e['id']}/documents", headers=h, files={"file": ("x.exe", b"MZ\x90\x00", "application/pdf")}).status_code == 422
r = client.delete(f"/api/expenses/{e['id']}/documents/{doc['id']}", headers=h)
assert r.status_code == 200 and r.json()["documents"] == []
assert client.get(f"/api/expenses/{e['id']}/documents/{doc['id']}", headers=h).status_code == 404
+4 -1
View File
@@ -240,7 +240,10 @@
"expense": {
"not_found": "Το έξοδο δεν βρέθηκε.",
"over_due": "Είναι περισσότερα από όσα οφείλονται ακόμα ({{due}}).",
"below_paid": "Έχουν ήδη πληρωθεί {{paid}}: το σύνολο δεν μπορεί να είναι λιγότερο."
"below_paid": "Έχουν ήδη πληρωθεί {{paid}}: το σύνολο δεν μπορεί να είναι λιγότερο.",
"document_not_found": "Το έγγραφο δεν βρέθηκε.",
"document_type": "Ανεβάστε PDF ή φωτογραφία (JPG, PNG, WebP ή HEIC).",
"document_too_big": "Το αρχείο είναι πολύ μεγάλο (έως {{max_mb}} MB)."
},
"flag": {
"not_found": "Η σήμανση δεν βρέθηκε.",
+4 -1
View File
@@ -240,7 +240,10 @@
"expense": {
"not_found": "Expense not found.",
"over_due": "That's more than what is still due ({{due}}).",
"below_paid": "{{paid}} has been paid already: the total can't be less."
"below_paid": "{{paid}} has been paid already: the total can't be less.",
"document_not_found": "Document not found.",
"document_type": "Upload a PDF or a photo (JPG, PNG, WebP or HEIC).",
"document_too_big": "The file is too big (at most {{max_mb}} MB)."
},
"flag": {
"not_found": "Mark not found.",