"""The files kept with expenses (2026-11-20): an invoice as a PDF or a photo of a receipt. Stored under MEDIA_DIR/expenses// (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}