"""Handover package: selection tree, completeness review, ZIP download.""" from __future__ import annotations from urllib.parse import quote from uuid import UUID from fastapi import APIRouter, Depends, Request, Response from psycopg import Connection from app.access.policy import Ctx, parse_query_context from app.api.deps import Principal, get_conn, get_principal from app.api.schemas import ExportIn from app.core.errors import unprocessable from app.exporting import build_export, export_tree, review_export router = APIRouter() def _disposition(filename: str) -> str: # Header values stay ASCII. The readable name travels in filename*. encoded = quote(filename) return f"attachment; filename=\"uebergabe.zip\"; filename*=UTF-8''{encoded}" def _context(value) -> Ctx | None: return None if value is None else Ctx(value.kind, value.id) def _selection(body: ExportIn) -> tuple[list[str], dict[str, UUID]]: if len(body.assignments) > 200: raise unprocessable("Die Zuordnung der Zugänge ist zu umfangreich.") return list(body.selected), dict(body.assignments) @router.get("/api/v1/matters/{matter_id}/export-tree") def get_export_tree( matter_id: UUID, context_kind: str | None = None, context_id: str | None = None, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn), ): return export_tree( conn, principal.account_id, matter_id, parse_query_context(context_kind, context_id), ) @router.post("/api/v1/matters/{matter_id}/export/review") def post_export_review( matter_id: UUID, body: ExportIn, request: Request, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn), ): selected, assignments = _selection(body) plan = review_export( conn, principal.account_id, matter_id, _context(body.context), selected, assignments, request.app.state.settings.media_root, ) return plan.review() @router.post("/api/v1/matters/{matter_id}/export") def post_export( matter_id: UUID, body: ExportIn, request: Request, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn), ): selected, assignments = _selection(body) filename, payload = build_export( conn, principal.account_id, matter_id, _context(body.context), selected, assignments, request.app.state.settings.media_root, ) return Response( content=payload, media_type="application/zip", headers={ "Content-Disposition": _disposition(filename), "X-Content-Type-Options": "nosniff", "Cache-Control": "private, no-store", }, )