Halte Anlagen und Versand als eigene Verwendung fest, damit die uebermittelte Fassung und ihre Nachweise spaeter nicht still mit der Arbeitsfassung verschmelzen.
Deploy Development / deploy (push) Successful in 28s
Test Suite / pytest-backend (push) Successful in 1m37s
Test Suite / smoke-dev (push) Successful in 0s
Test Suite / frontend-build (push) Successful in 9s

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
LarsandCursor committed 2026-10-18 09:57:59 +02:00
1 parent f21c64a944
commit 3c190c87b4
27 files changed
+3953 -71

No files matched your search

+247
View File
@@ -0,0 +1,247 @@
"""HTTP for attachment roles, documented dispatches and secured editions."""
from __future__ import annotations
from uuid import UUID
from fastapi import APIRouter, Depends, Request, Response
from psycopg import Connection
from app.access.policy import Ctx
from app.api.deps import Principal, get_conn, get_principal
from app.api.schemas import (
AttachmentAssignIn,
AttachmentDetachIn,
AttachmentOrderIn,
DispatchCorrectIn,
DispatchEvidenceIn,
DispatchIn,
FoldIn,
)
from app.correspondence import (
GapNote,
add_dispatch_evidence,
assign_attachments,
correct_dispatch,
detach_attachment,
dispatch_view,
open_container,
order_attachments,
read_snapshot,
record_dispatch,
set_fold,
)
from app.core.errors import not_found
from app.media.storage import content_disposition
router = APIRouter()
def _ctx(value) -> Ctx:
return Ctx(value.kind, value.id)
def _placement(value) -> Ctx | None:
if value is None:
return None
return Ctx(value.kind, value.id)
@router.post("/api/v1/elements/{element_id}/attachments", status_code=201)
def post_attachments(
element_id: UUID,
body: AttachmentAssignIn,
principal: Principal = Depends(get_principal),
conn: Connection = Depends(get_conn),
):
return assign_attachments(
conn,
principal.account_id,
element_id,
body.expected_version,
_ctx(body.context),
_placement(body.placement),
body.attachment_element_ids,
body.fold,
[],
)
@router.post("/api/v1/elements/{element_id}/attachments/order")
def post_attachment_order(
element_id: UUID,
body: AttachmentOrderIn,
principal: Principal = Depends(get_principal),
conn: Connection = Depends(get_conn),
):
return order_attachments(
conn,
principal.account_id,
element_id,
body.expected_version,
_ctx(body.context),
_placement(body.placement),
body.attachment_element_ids,
)
@router.post("/api/v1/elements/{element_id}/attachments/{attachment_id}/detach", status_code=204)
def post_detach(
element_id: UUID,
attachment_id: UUID,
body: AttachmentDetachIn,
principal: Principal = Depends(get_principal),
conn: Connection = Depends(get_conn),
):
detach_attachment(
conn,
principal.account_id,
element_id,
attachment_id,
body.expected_version,
_ctx(body.context),
_placement(body.placement),
)
@router.patch("/api/v1/bindings/{binding_id}/fold")
def patch_fold(
binding_id: UUID,
body: FoldIn,
principal: Principal = Depends(get_principal),
conn: Connection = Depends(get_conn),
):
return set_fold(
conn,
principal.account_id,
binding_id,
body.expected_version,
_ctx(body.context),
_placement(body.placement),
body.fold,
)
@router.post("/api/v1/elements/{element_id}/dispatches", status_code=201)
def post_dispatch(
element_id: UUID,
body: DispatchIn,
request: Request,
principal: Principal = Depends(get_principal),
conn: Connection = Depends(get_conn),
):
request.state.cleanup_files = []
return record_dispatch(
conn,
principal.account_id,
element_id,
body.expected_version,
_ctx(body.context),
_placement(body.placement),
body.channel,
body.sent_on,
body.counterpart,
body.attachment_element_ids,
[item.model_dump() for item in body.evidence],
body.historical_gap,
request.app.state.settings.media_root,
request.state.cleanup_files,
)
@router.post("/api/v1/dispatches/{dispatch_id}/evidence", status_code=201)
def post_evidence(
dispatch_id: UUID,
body: DispatchEvidenceIn,
request: Request,
principal: Principal = Depends(get_principal),
conn: Connection = Depends(get_conn),
):
request.state.cleanup_files = []
return add_dispatch_evidence(
conn,
principal.account_id,
dispatch_id,
body.expected_version,
_ctx(body.context),
_placement(body.placement),
body.element_id,
body.role,
body.fold,
request.app.state.settings.media_root,
request.state.cleanup_files,
)
@router.post("/api/v1/dispatches/{dispatch_id}/correct")
def post_correct(
dispatch_id: UUID,
body: DispatchCorrectIn,
principal: Principal = Depends(get_principal),
conn: Connection = Depends(get_conn),
):
return correct_dispatch(
conn,
principal.account_id,
dispatch_id,
body.expected_version,
_ctx(body.context),
_placement(body.placement),
body.channel,
body.sent_on,
body.clear_sent_on,
body.counterpart,
body.clear_counterpart,
)
@router.get("/api/v1/dispatches/{dispatch_id}")
def get_dispatch(
dispatch_id: UUID,
context_kind: str,
context_id: UUID,
placement_kind: str | None = None,
placement_id: UUID | None = None,
principal: Principal = Depends(get_principal),
conn: Connection = Depends(get_conn),
):
context = Ctx(context_kind, context_id)
placement = Ctx(placement_kind, placement_id) if placement_kind and placement_id else None
_row, page, scope = open_container(conn, principal.account_id, context, placement, "read")
return dispatch_view(conn, principal.account_id, dispatch_id, page, scope)
@router.get("/api/v1/dispatches/{dispatch_id}/items/{item_id}/content")
def get_dispatch_item(
dispatch_id: UUID,
item_id: UUID,
context_kind: str,
context_id: UUID,
request: Request,
placement_kind: str | None = None,
placement_id: UUID | None = None,
principal: Principal = Depends(get_principal),
conn: Connection = Depends(get_conn),
):
context = Ctx(context_kind, context_id)
placement = Ctx(placement_kind, placement_id) if placement_kind and placement_id else None
result = read_snapshot(
conn,
principal.account_id,
dispatch_id,
item_id,
context,
placement,
request.app.state.settings.media_root,
)
if isinstance(result, GapNote):
raise not_found()
return Response(
content=result.data,
media_type=result.media_type or "application/octet-stream",
headers={
"Content-Disposition": content_disposition(result.filename),
"X-Content-Type-Options": "nosniff",
"Cache-Control": "private, no-store",
},
)
+12 -3
View File
@@ -1460,9 +1460,17 @@ def patch_case_order(
conn: Connection = Depends(get_conn),
):
version = set_content_order(
conn, principal.account_id, "case", case_id, body.expected_version, body.mode, body.direction, None
conn,
principal.account_id,
"case",
case_id,
body.expected_version,
body.mode,
body.direction,
None,
body.view,
)
return {"version": version, "mode": body.mode, "direction": body.direction}
return {"version": version, "mode": body.mode, "direction": body.direction, "view": body.view}
@router.post("/api/v1/cases/{case_id}/bindings/order")
@@ -1514,8 +1522,9 @@ def patch_matter_order(
body.mode,
body.direction,
_ctx_model(body.context),
body.view,
)
return {"version": version, "mode": body.mode, "direction": body.direction}
return {"version": version, "mode": body.mode, "direction": body.direction, "view": body.view}
@router.post("/api/v1/matters/{matter_id}/bindings/order")
+67
View File
@@ -197,6 +197,7 @@ class ContentOrderIn(APIModel):
expected_version: int = Field(ge=1)
mode: Literal["date", "position"]
direction: Literal["asc", "desc"] = "asc"
view: Literal["structure", "chronology"] | None = None
context: ContextIn | None = None
@@ -366,3 +367,69 @@ class ExportIn(APIModel):
context: ContextIn | None = None
selected: list[str] = Field(default_factory=list, max_length=2000)
assignments: dict[str, UUID] = Field(default_factory=dict)
class EvidenceIn(APIModel):
element_id: UUID
role: Literal["email", "submission", "delivery", "other"]
fold: Literal["keep", "evidence"] = "keep"
class AttachmentAssignIn(APIModel):
expected_version: int = Field(ge=1)
context: ContextIn
placement: ContextIn | None = None
attachment_element_ids: list[UUID] = Field(min_length=1, max_length=100)
fold: Literal["keep", "attachment"] = "keep"
class AttachmentOrderIn(APIModel):
expected_version: int = Field(ge=1)
context: ContextIn
placement: ContextIn | None = None
attachment_element_ids: list[UUID] = Field(min_length=1, max_length=100)
class AttachmentDetachIn(APIModel):
expected_version: int = Field(ge=1)
context: ContextIn
placement: ContextIn | None = None
class FoldIn(APIModel):
expected_version: int = Field(ge=1)
context: ContextIn
placement: ContextIn | None = None
fold: Literal["attachment", "evidence"] | None = None
class DispatchIn(APIModel):
expected_version: int = Field(ge=1)
context: ContextIn
placement: ContextIn | None = None
channel: Literal["email", "post", "other"]
sent_on: date | None = None
counterpart: str | None = Field(default=None, max_length=200)
attachment_element_ids: list[UUID] = Field(default_factory=list, max_length=100)
evidence: list[EvidenceIn] = Field(default_factory=list, max_length=20)
historical_gap: bool = False
class DispatchEvidenceIn(APIModel):
expected_version: int = Field(ge=1)
context: ContextIn
placement: ContextIn | None = None
element_id: UUID
role: Literal["email", "submission", "delivery", "other"]
fold: Literal["keep", "evidence"] = "keep"
class DispatchCorrectIn(APIModel):
expected_version: int = Field(ge=1)
context: ContextIn
placement: ContextIn | None = None
channel: Literal["email", "post", "other"] | None = None
sent_on: date | None = None
clear_sent_on: bool = False
counterpart: str | None = Field(default=None, max_length=200)
clear_counterpart: bool = False
File diff suppressed because it is too large. Load diff
+196 -31
View File
@@ -21,6 +21,8 @@ from app.access.policy import (
)
from app.core.errors import not_found, unprocessable
from app.core.timeutil import dump_dt, utcnow
from app.correspondence import GapNote, export_children, load_snapshot_file
from app.mailpack import parse_mail
from app.present import _chapters, _ordered_bindings
from app.retrieval import (
FilePayload,
@@ -30,7 +32,7 @@ from app.retrieval import (
load_file,
)
_NODE_KINDS = {"binding", "annotation"}
_NODE_KINDS = {"binding", "annotation", "attachment", "dispatch_item", "evidence"}
_DIRECTION = {"in": "Eingang", "out": "Ausgang"}
_KIND_LABEL = {
"note": "Notiz",
@@ -62,6 +64,10 @@ class ExportNode:
annotation_author: str | None = None
annotation_at: str | None = None
label: str = ""
relation: str | None = None
edition: str | None = None
gap_reason: str | None = None
snapshot_id: str | None = None
def public(self) -> dict:
return {
@@ -118,6 +124,7 @@ class Entry:
notice: str | None
replies: list[tuple[str, str]]
recorded_at: str | None
notes: tuple[str, ...] = ()
def public(self) -> dict:
return {
@@ -202,6 +209,16 @@ def _plan(conn, actor, matter_id, context, selected, assignments, media_root) ->
if node.kind == "annotation":
loaded[node.id] = node.annotation_body or ""
continue
if node.gap_reason and node.kind in {"dispatch_item", "evidence"}:
loaded[node.id] = GapNote(node.gap_reason)
continue
if node.snapshot_id and node.kind in {"dispatch_item", "evidence"}:
result = load_snapshot_file(conn, UUID(node.snapshot_id), media_root)
if isinstance(result, RetrievalFailure):
issues.append(Issue(node.id, node.title, result.code, result.message, [dict(item) for item in result.choices]))
continue
loaded[node.id] = result
continue
if node.content_kind == "note":
loaded[node.id] = _note_text(conn, UUID(node.element_id))
continue
@@ -217,6 +234,7 @@ def _plan(conn, actor, matter_id, context, selected, assignments, media_root) ->
loaded[node.id] = result
if isinstance(result, MailPayload):
notices.extend(_retention_notices(node, result, hashes))
notices.extend(_bundle_notices(root, chosen))
issues.extend(_reference_issues(conn, actor, page, leaves))
generated = dump_dt(utcnow()) or ""
if issues:
@@ -252,9 +270,9 @@ def _matter_node(conn, actor, matter, page: Ctx, root: bool) -> ExportNode:
for binding in bindings:
grouped.setdefault(binding.get("chapter_id"), []).append(binding)
children: list[ExportNode] = []
children.extend(_chapter_nodes(chapters, grouped))
children.extend(_chapter_nodes(conn, actor, page, chapters, grouped))
for binding in grouped.get(None, []):
children.append(_binding_node(binding))
children.append(_binding_node(conn, actor, binding, page))
rows = conn.execute(
"SELECT * FROM matters WHERE parent_matter_id = %s AND deleted_at IS NULL ORDER BY title, id",
(matter["id"],),
@@ -275,16 +293,21 @@ def _matter_node(conn, actor, matter, page: Ctx, root: bool) -> ExportNode:
)
def _chapter_nodes(chapters: list[dict], grouped: dict[str | None, list]) -> list[ExportNode]:
def _chapter_nodes(conn, actor, page, chapters: list[dict], grouped: dict[str | None, list]) -> list[ExportNode]:
by_parent: dict[str | None, list[dict]] = {}
for chapter in chapters:
by_parent.setdefault(chapter.get("parent_chapter_id"), []).append(chapter)
def build(parent_id: str | None) -> list[ExportNode]:
def build(parent_id: str | None, path: str) -> list[ExportNode]:
nodes: list[ExportNode] = []
for chapter in by_parent.get(parent_id, []):
nested = build(chapter["id"])
items = [_binding_node(item) for item in grouped.get(chapter["id"], [])]
chapter_path = f"{path} / {chapter['title']}" if path else chapter["title"]
nested = build(chapter["id"], chapter_path)
items = []
for item in grouped.get(chapter["id"], []):
node = _binding_node(conn, actor, item, page)
node.relation = f"Kapitel: {chapter_path}"
items.append(node)
if not items and not nested:
continue
nodes.append(
@@ -301,10 +324,10 @@ def _chapter_nodes(chapters: list[dict], grouped: dict[str | None, list]) -> lis
)
return nodes
return build(None)
return build(None, "")
def _binding_node(binding: dict) -> ExportNode:
def _binding_node(conn, actor, binding: dict, page) -> ExportNode:
element = binding["element"]
rights = binding["rights"]
content_kind = _content_kind(element)
@@ -340,9 +363,58 @@ def _binding_node(binding: dict) -> ExportNode:
label="Anmerkung",
)
)
for spec in export_children(conn, actor, binding, page):
node.children.append(_spec_node(spec))
return node
def _spec_node(spec: dict) -> ExportNode:
if spec["kind"] == "dispatch":
return ExportNode(
id=spec["id"],
kind="dispatch",
title=spec["title"],
exportable=True,
reason=None,
content_kind=None,
children=[_spec_node(child) for child in spec["children"]],
label="Versand",
)
element = spec.get("element")
if spec["kind"] == "dispatch_item":
content_kind = _item_content_kind(spec)
else:
content_kind = _content_kind(element) if element else "file"
rights = spec.get("rights") or {}
exportable = bool(rights.get("read") and rights.get("share"))
return ExportNode(
id=spec["id"],
kind=spec["kind"],
title=spec["title"],
exportable=exportable,
reason=None if exportable else "Für die Übergabe fehlt die Freigabebefugnis.",
content_kind=content_kind,
element_id=(element or {}).get("id") or spec.get("element_id"),
dates=spec.get("dates"),
label={"attachment": "Anlage", "dispatch_item": "Versandfassung", "evidence": "Nachweis"}.get(spec["kind"], "Inhalt"),
relation=spec.get("relation"),
edition=spec.get("edition"),
gap_reason=spec.get("gap_reason"),
snapshot_id=spec.get("snapshot_id"),
)
def _item_content_kind(spec: dict) -> str:
if spec.get("gap_reason"):
return "gap"
media = spec.get("content_type") or ""
if media == "message/rfc822":
return "email"
if media == "application/json":
return "note"
return "file"
def _content_kind(element: dict) -> str:
if element["kind"] == "note":
return "note"
@@ -470,37 +542,38 @@ def _layout(root, chosen, loaded, notices, generated: str):
if child.id in numbers:
folder = prefix + [_folder_name(child.title, numbers[child.id], prefix)]
if child.kind == "binding" and child.content_kind == "email":
_emit_email(child, folder, add, rewrite, entries, loaded, notice_for, generated)
_emit_email(child, folder, add, rewrite, entries, loaded, notice_for, generated, chosen)
else:
emit(child, folder)
else:
_emit_loose(child, prefix, add, entries, loaded, notice_for, generated)
_emit_loose(child, prefix, add, entries, loaded, notice_for, generated, chosen)
emit(root, [])
return files, entries
def _emit_email(node, folder, add, rewrite, entries, loaded, notice_for, generated: str) -> None:
mail = loaded[node.id]
assert isinstance(mail, MailPayload)
eml = add(folder + ["nachricht.eml"], mail.raw)
attachments = []
for attachment in mail.parsed.attachments:
path = add(folder + ["anlagen", attachment.filename], attachment.data)
attachments.append((attachment.filename, path))
notice = "\n".join(notice_for.get(node.id, []))
text_path = add(folder + ["lesefassung.md"], b"")
readable = _mail_markdown(node, mail, text_path, eml, attachments, notice, generated)
rewrite(text_path, readable.encode("utf-8"))
links = [("EML-Original", eml), ("Lesefassung", text_path), *attachments]
entries.append(_entry(node, eml, links, notice or None))
for child in node.children:
if child.kind == "annotation" and child.id in loaded:
path = add(folder + [_annotation_filename(child, folder)], _annotation_markdown(child).encode("utf-8"))
entries.append(_entry(child, path, [], None))
def _emit_email(node, folder, add, rewrite, entries, loaded, notice_for, generated: str, chosen: set[str]) -> None:
mail = loaded.get(node.id)
if isinstance(mail, MailPayload):
eml = add(folder + ["nachricht.eml"], mail.raw)
attachments = []
for attachment in mail.parsed.attachments:
path = add(folder + ["anlagen", attachment.filename], attachment.data)
attachments.append((attachment.filename, path))
notice = "\n".join(notice_for.get(node.id, []))
text_path = add(folder + ["lesefassung.md"], b"")
readable = _mail_markdown(node, mail, text_path, eml, attachments, notice, generated)
rewrite(text_path, readable.encode("utf-8"))
links = [("EML-Original", eml), ("Lesefassung", text_path), *attachments]
entries.append(_entry(node, eml, links, notice or None))
for child in node.children:
if child.kind == "annotation" and child.id in loaded:
path = add(folder + [_annotation_filename(child, folder)], _annotation_markdown(child).encode("utf-8"))
entries.append(_entry(child, path, [], None))
_emit_related(node, folder, add, entries, loaded, notice_for, chosen, generated)
def _emit_loose(node, prefix, add, entries, loaded, notice_for, generated: str) -> None:
def _emit_loose(node, prefix, add, entries, loaded, notice_for, generated: str, chosen: set[str]) -> None:
if node.kind == "binding" and node.id in loaded and node.content_kind != "email":
payload = loaded[node.id]
if node.content_kind == "note":
@@ -517,9 +590,99 @@ def _emit_loose(node, prefix, add, entries, loaded, notice_for, generated: str)
elif node.kind == "annotation" and node.id in loaded:
path = add(prefix + [_annotation_filename(node, prefix)], _annotation_markdown(node).encode("utf-8"))
entries.append(_entry(node, path, [], None))
if node.kind == "binding":
_emit_related(node, prefix, add, entries, loaded, notice_for, chosen, generated)
def _emit_related(node, prefix, add, entries, loaded, notice_for, chosen, generated: str) -> None:
for child in node.children:
if child.kind == "attachment" and child.id in chosen and child.id in loaded:
_emit_one(child, prefix + ["anlagen-arbeitsstand"], add, entries, loaded, notice_for, generated)
if child.kind != "dispatch":
continue
picked = [item for item in child.children if item.id in chosen and item.id in loaded]
if not picked:
continue
folder = prefix + [_segment(child.title)]
for item in picked:
_emit_one(item, folder, add, entries, loaded, notice_for, generated)
def _emit_one(node, prefix, add, entries, loaded, notice_for, generated: str) -> None:
payload = loaded[node.id]
notice = "\n".join(notice_for.get(node.id, []))
if isinstance(payload, GapNote):
path = add(prefix + [f"{_segment(node.title)}-luecke.txt"], payload.reason.encode("utf-8"))
entries.append(_entry(node, path, [( "Lücke", path)], notice or payload.reason))
return
if isinstance(payload, MailPayload) or (isinstance(payload, FilePayload) and payload.media_type == "message/rfc822"):
raw = payload.raw if isinstance(payload, MailPayload) else payload.data
eml = add(prefix + ["nachricht.eml"], raw)
links = [("EML-Original", eml)]
try:
parsed = payload.parsed if isinstance(payload, MailPayload) else parse_mail(raw)
for attachment in parsed.attachments:
path = add(prefix + ["anlagen", attachment.filename], attachment.data)
links.append((attachment.filename, path))
except Exception:
links.append(("Hinweis", eml))
entries.append(_entry(node, eml, links, notice or None))
return
if isinstance(payload, str):
path = add(prefix + [f"{_segment(node.title)}.md"], _note_markdown(node, payload, generated).encode("utf-8"))
entries.append(_entry(node, path, [], notice or None))
return
if isinstance(payload, FilePayload) and payload.media_type == "application/json":
path = add(prefix + [f"{_segment(node.title)}.stand.json"], payload.data)
text = _json_note(payload.data)
reading = add(prefix + [f"{_segment(node.title)}.md"], _note_markdown(node, text, generated).encode("utf-8"))
entries.append(_entry(node, reading, [("Gesicherter Text", path), ("Lesefassung", reading)], notice or None))
return
if isinstance(payload, FilePayload):
path = add(prefix + [payload.filename], payload.data)
entries.append(_entry(node, path, [(payload.filename, path)], notice or None))
def _json_note(data: bytes) -> str:
import json
try:
document = json.loads(data.decode("utf-8"))
except (UnicodeDecodeError, json.JSONDecodeError):
return ""
parts = []
for block in document.get("blocks") or []:
if isinstance(block, dict):
text = str(block.get("text") or "").strip()
if text:
parts.append(text)
return "\n\n".join(parts)
def _bundle_notices(root: ExportNode, chosen: set[str]) -> list[Notice]:
found = []
for node in _walk(root):
if node.kind != "dispatch":
continue
parts = [child for child in node.children if child.kind in {"dispatch_item", "evidence"}]
picked = [child for child in parts if child.id in chosen]
if not picked:
continue
if len(picked) < len(parts):
found.append(
Notice(
picked[0].id,
"Auszug dieses Versands. Die Ausgabe ist nicht der vollständige Versandstand.",
)
)
gaps = [child.gap_reason for child in picked if child.gap_reason]
if gaps:
found.append(Notice(picked[0].id, "Fehlende Fassung: " + " ".join(gaps)))
return found
def _entry(node: ExportNode, path: str | None, links, notice: str | None) -> Entry:
notes = tuple(part for part in (node.relation, node.edition, node.gap_reason) if part)
return Entry(
node.id,
node.title,
@@ -532,6 +695,7 @@ def _entry(node: ExportNode, path: str | None, links, notice: str | None) -> Ent
notice,
[],
_recorded(node),
notes,
)
@@ -650,6 +814,7 @@ def _fact_lines(entry: Entry, generated: str) -> list[str]:
lines.append(f"Erfasst am: {entry.recorded_at}")
if entry.direction in _DIRECTION:
lines.append(_DIRECTION[entry.direction])
lines.extend(entry.notes)
lines.append(f"Stand der Ausgabe: {generated}")
return lines
@@ -726,7 +891,7 @@ def _is_folder(node: ExportNode) -> bool:
def _included(node: ExportNode, chosen: set[str]) -> bool:
if node.kind == "binding" and node.content_kind == "email":
return node.id in chosen
return any(child.id in chosen for child in _walk(node) if child.kind in _NODE_KINDS)
return any(child.id in chosen for child in _walk(node) if child.kind in _NODE_KINDS)
+2
View File
@@ -9,6 +9,7 @@ from fastapi import FastAPI, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from app.api.correspondence import router as correspondence_router
from app.api.export import router as export_router
from app.api.routes import router
from app.api.sources import router as sources_router
@@ -117,6 +118,7 @@ def create_app() -> FastAPI:
app.include_router(router)
app.include_router(sources_router)
app.include_router(export_router)
app.include_router(correspondence_router)
return app
+14 -4
View File
@@ -1046,6 +1046,9 @@ def delete_element(conn, actor: UUID, element_id: UUID, expected: int, media_roo
if element is None or element["owner_subject_id"] != actor:
raise not_found()
bump_version(conn, "elements", element_id, expected)
from app.correspondence import purge_element_dispatch_files
delete_after.extend(purge_element_dispatch_files(conn, element_id, media_root))
asset = conn.execute("SELECT * FROM media_assets WHERE element_id = %s", (element_id,)).fetchone()
conn.execute("DELETE FROM bindings WHERE element_id = %s", (element_id,))
conn.execute(
@@ -1394,6 +1397,7 @@ def set_content_order(
mode: str,
direction: str,
context: Ctx | None,
view: str | None = None,
) -> int:
if kind == "case":
container, rights = require_case(conn, actor, container_id, "edit")
@@ -1404,10 +1408,16 @@ def set_content_order(
if not rights.edit:
raise forbidden()
version = bump_version(conn, table, container_id, expected)
conn.execute(
f"UPDATE {table} SET content_order = %s, content_order_dir = %s WHERE id = %s",
(mode, direction, container_id),
)
if view is None:
conn.execute(
f"UPDATE {table} SET content_order = %s, content_order_dir = %s WHERE id = %s",
(mode, direction, container_id),
)
else:
conn.execute(
f"UPDATE {table} SET content_order = %s, content_order_dir = %s, content_view = %s WHERE id = %s",
(mode, direction, view, container_id),
)
audit(conn, actor, container["home_scope_id"], "content_order", kind, container_id, context)
return version
+11 -1
View File
@@ -338,8 +338,16 @@ def _ordered_bindings(conn, actor: UUID, kind: str, container_id: UUID, context:
continue
item["_raw_position"] = binding["position"]
item["_document_on"] = item["element"]["dates"]["document_on"]
item["container"] = {"kind": kind, "id": str(container_id)}
item["_fold"] = binding.get("list_fold")
visible.append(item)
return arrange(visible, mode or "position", direction or "asc")
arranged = arrange(visible, mode or "position", direction or "asc")
from app.correspondence import attach_correspondence
attach_correspondence(conn, actor, arranged, context)
for item in arranged:
item.pop("_fold", None)
return arranged
def course_items(bindings: list[dict]) -> list[dict]:
@@ -575,6 +583,7 @@ def case_detail(conn, actor: UUID, case: dict, rights) -> dict:
payload = case_summary(case, rights)
payload["content_order"] = case.get("content_order") or "position"
payload["content_order_dir"] = case.get("content_order_dir") or "asc"
payload["content_view"] = case.get("content_view") or "structure"
payload["trail"] = case_trail(conn, actor, case)
payload["kind_label"] = "Unterakte" if case["parent_case_id"] else "Akte"
payload["home_scope_name"] = room_name(conn, case["home_scope_id"])
@@ -714,6 +723,7 @@ def matter_detail(conn, actor: UUID, matter: dict, rights, context: Ctx | None)
"is_owner": matter["owner_subject_id"] == actor,
"content_order": matter.get("content_order") or "position",
"content_order_dir": matter.get("content_order_dir") or "asc",
"content_view": matter.get("content_view") or "structure",
"trail": matter_trail(conn, actor, matter, context),
"placements": matter_placements(conn, actor, matter["id"], context),
"kind_label": "Teilvorgang" if matter["parent_matter_id"] else "Vorgang",
@@ -0,0 +1,147 @@
-- Anlagenverwendung, dokumentierter Versand und Arbeitsansicht.
-- Bestehende Kapitel, Einbindungen und Dateien bleiben unverändert.
ALTER TABLE cases
ADD COLUMN content_view text NOT NULL DEFAULT 'structure';
ALTER TABLE cases
ADD CONSTRAINT cases_content_view
CHECK (content_view IN ('structure', 'chronology'));
ALTER TABLE matters
ADD COLUMN content_view text NOT NULL DEFAULT 'structure';
ALTER TABLE matters
ADD CONSTRAINT matters_content_view
CHECK (content_view IN ('structure', 'chronology'));
ALTER TABLE bindings
ADD COLUMN list_fold text;
ALTER TABLE bindings
ADD CONSTRAINT bindings_list_fold
CHECK (list_fold IS NULL OR list_fold IN ('attachment', 'evidence'));
CREATE TABLE attachment_uses (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
home_scope_id uuid NOT NULL REFERENCES data_rooms (id),
context_kind text NOT NULL,
context_id uuid NOT NULL,
host_element_id uuid NOT NULL REFERENCES elements (id) ON DELETE CASCADE,
attachment_element_id uuid NOT NULL REFERENCES elements (id) ON DELETE CASCADE,
position integer NOT NULL,
label text,
created_by uuid NOT NULL REFERENCES auth_accounts (id),
created_at timestamptz NOT NULL DEFAULT now(),
CONSTRAINT attachment_uses_kind CHECK (context_kind IN ('case', 'matter')),
CONSTRAINT attachment_uses_not_self CHECK (host_element_id <> attachment_element_id),
CONSTRAINT attachment_uses_position CHECK (position >= 0),
CONSTRAINT attachment_uses_label CHECK (label IS NULL OR char_length(label) BETWEEN 1 AND 200),
CONSTRAINT attachment_uses_once UNIQUE (context_kind, context_id, host_element_id, attachment_element_id)
);
CREATE INDEX attachment_uses_host
ON attachment_uses (context_kind, context_id, host_element_id, position);
CREATE TABLE dispatches (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
home_scope_id uuid NOT NULL REFERENCES data_rooms (id),
context_kind text NOT NULL,
context_id uuid NOT NULL,
host_element_id uuid NOT NULL REFERENCES elements (id) ON DELETE CASCADE,
channel text NOT NULL,
sent_on date,
counterpart text,
completeness text NOT NULL,
provenance text NOT NULL,
recorded_by uuid NOT NULL REFERENCES auth_accounts (id),
recorded_at timestamptz NOT NULL DEFAULT now(),
version integer NOT NULL DEFAULT 1,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
CONSTRAINT dispatches_kind CHECK (context_kind IN ('case', 'matter')),
CONSTRAINT dispatches_channel CHECK (channel IN ('email', 'post', 'other')),
CONSTRAINT dispatches_completeness CHECK (completeness IN ('secured', 'partial', 'gap')),
CONSTRAINT dispatches_provenance CHECK (provenance IN ('captured', 'reconstructed')),
CONSTRAINT dispatches_counterpart CHECK (counterpart IS NULL OR char_length(counterpart) BETWEEN 1 AND 200),
CONSTRAINT dispatches_version CHECK (version >= 1)
);
CREATE INDEX dispatches_host
ON dispatches (context_kind, context_id, host_element_id, recorded_at);
CREATE TABLE dispatch_items (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
dispatch_id uuid NOT NULL REFERENCES dispatches (id) ON DELETE CASCADE,
role text NOT NULL,
position integer NOT NULL,
element_id uuid NOT NULL REFERENCES elements (id) ON DELETE CASCADE,
title text NOT NULL,
document_on date,
filename text,
content_type text,
byte_size bigint,
content_sha256 text,
source_state text NOT NULL,
gap_reason text,
note_document jsonb,
external_source text,
external_id text,
CONSTRAINT dispatch_items_role CHECK (role IN ('host', 'attachment')),
CONSTRAINT dispatch_items_position CHECK (position >= 0),
CONSTRAINT dispatch_items_state CHECK (source_state IN ('snapshot', 'gap')),
CONSTRAINT dispatch_items_once UNIQUE (dispatch_id, element_id)
);
CREATE INDEX dispatch_items_dispatch ON dispatch_items (dispatch_id, position);
CREATE TABLE dispatch_snapshots (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
dispatch_item_id uuid UNIQUE REFERENCES dispatch_items (id) ON DELETE CASCADE,
evidence_id uuid,
home_scope_id uuid NOT NULL REFERENCES data_rooms (id),
owner_subject_id uuid NOT NULL REFERENCES auth_accounts (id),
original_filename text NOT NULL,
content_type text NOT NULL,
byte_size bigint NOT NULL,
sha256 text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
CONSTRAINT dispatch_snapshots_filename CHECK (char_length(original_filename) BETWEEN 1 AND 240),
CONSTRAINT dispatch_snapshots_target CHECK (
(dispatch_item_id IS NOT NULL AND evidence_id IS NULL)
OR (dispatch_item_id IS NULL AND evidence_id IS NOT NULL)
)
);
CREATE TABLE dispatch_evidence (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
dispatch_id uuid NOT NULL REFERENCES dispatches (id) ON DELETE CASCADE,
element_id uuid NOT NULL REFERENCES elements (id) ON DELETE CASCADE,
role text NOT NULL,
source_state text NOT NULL,
gap_reason text,
message_id text,
identity_sha256 text,
comparisons jsonb NOT NULL DEFAULT '[]'::jsonb,
manual boolean NOT NULL DEFAULT true,
created_by uuid NOT NULL REFERENCES auth_accounts (id),
created_at timestamptz NOT NULL DEFAULT now(),
CONSTRAINT dispatch_evidence_role CHECK (role IN ('email', 'submission', 'delivery', 'other')),
CONSTRAINT dispatch_evidence_state CHECK (source_state IN ('identified', 'gap')),
CONSTRAINT dispatch_evidence_once UNIQUE (dispatch_id, element_id)
);
ALTER TABLE dispatch_snapshots
ADD CONSTRAINT dispatch_snapshots_evidence_fk
FOREIGN KEY (evidence_id) REFERENCES dispatch_evidence (id) ON DELETE CASCADE;
CREATE TABLE dispatch_corrections (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
dispatch_id uuid NOT NULL REFERENCES dispatches (id) ON DELETE CASCADE,
corrected_at timestamptz NOT NULL DEFAULT now(),
corrected_by uuid NOT NULL REFERENCES auth_accounts (id),
summary text NOT NULL,
CONSTRAINT dispatch_corrections_summary CHECK (char_length(summary) BETWEEN 1 AND 500)
);
CREATE INDEX dispatch_corrections_dispatch ON dispatch_corrections (dispatch_id, corrected_at);
+620
View File
@@ -0,0 +1,620 @@
"""Schreiben, Anlagen, Versandfassungen, Nachweise, Rechte und Export."""
from __future__ import annotations
import io
import json
import os
import zipfile
from email.message import EmailMessage
from pathlib import Path
from tests.support import ORIGIN, Actor, document, grant, register
PDF_A = b"%PDF-1.4\n1 0 obj<<>>endobj\ntrailer<<>>\n%%EOF\nA\n"
PDF_B = b"%PDF-1.4\n2 0 obj<<>>endobj\ntrailer<<>>\n%%EOF\nB\n"
PDF_C = b"%PDF-1.4\n3 0 obj<<>>endobj\ntrailer<<>>\n%%EOF\nC\n"
PDF_D = b"%PDF-1.4\n4 0 obj<<>>endobj\ntrailer<<>>\n%%EOF\nD\n"
def _detail(actor: Actor, matter_id: str, context: dict | None = None) -> dict:
params = None
if context is not None:
params = {"context_kind": context["kind"], "context_id": context["id"]}
return actor.request("GET", f"/api/v1/matters/{matter_id}", params=params)
def _binding(detail: dict, title: str) -> dict:
for item in detail["bindings"]:
if item["element"]["title"] == title:
return item
raise AssertionError(title)
def _file(actor: Actor, matter_id: str, title: str, name: str, data: bytes, document_on: str, chapter_id: str | None = None) -> dict:
form = {"title": title, "context_kind": "matter", "context_id": matter_id, "document_on": document_on}
if chapter_id:
form["chapter_id"] = chapter_id
return actor.request(
"POST",
"/api/v1/files",
data=form,
files={"upload": (name, data, "application/pdf")},
status=201,
)
def _ctx(matter_id: str) -> dict:
return {"kind": "matter", "id": matter_id}
def _eml(message_id: str, body: str, attachments: list[tuple[str, bytes]]) -> bytes:
message = EmailMessage()
message["Subject"] = "Versandnachweis"
message["From"] = "kanzlei@example.test"
message["To"] = "gegenueber@example.test"
message["Message-ID"] = message_id
message["Date"] = "Thu, 12 Mar 2026 10:00:00 +0100"
message.set_content(body)
for name, data in attachments:
message.add_attachment(data, maintype="application", subtype="pdf", filename=name)
return message.as_bytes()
def _zip(actor: Actor, matter_id: str, selected: list[str]) -> zipfile.ZipFile:
headers = {
"Origin": ORIGIN,
"X-CSRF-Token": actor.csrf,
"Content-Type": "application/json",
"X-Scope-Kind": actor.scope["kind"],
"X-Scope-Id": actor.scope["id"],
}
response = actor.client.post(
f"/api/v1/matters/{matter_id}/export",
json={"selected": selected},
headers=headers,
)
assert response.status_code == 200, response.text
return zipfile.ZipFile(io.BytesIO(response.content))
def _walk(node):
yield node
for child in node.get("children") or []:
yield from _walk(child)
def test_attachments_keep_other_uses_and_do_not_copy_files(client, db):
ada = Actor(client, "ada-anlage@example.test", "Ada Anlage")
register(db, ada.email, ada.name)
ada.login()
matter = ada.request("POST", "/api/v1/matters", json={"title": "Schreiben A"}, status=201)
other = ada.request("POST", "/api/v1/matters", json={"title": "Schreiben B"}, status=201)
chapter = ada.request("POST", f"/api/v1/matters/{matter['id']}/chapters", json={"title": "Korrespondenz"}, status=201)
sub = ada.request(
"POST",
f"/api/v1/matters/{matter['id']}/chapters",
json={"title": "Einzelbelege", "parent_chapter_id": chapter["id"]},
status=201,
)
letter = ada.request(
"POST",
"/api/v1/notes",
json={
"title": "Anschreiben",
"document": document("Bitte um Stellungnahme"),
"context": _ctx(matter["id"]),
"chapter_id": chapter["id"],
"dates": {"document_on": "2026-03-01"},
},
status=201,
)
first = _file(ada, matter["id"], "Rechnung 2023", "rechnung.pdf", PDF_A, "2023-05-01", sub["id"])
second = _file(ada, matter["id"], "Lageplan", "lage.pdf", PDF_B, "2024-01-15", sub["id"])
third = _file(ada, matter["id"], "Kontoauszug", "konto.pdf", PDF_C, "2025-11-02", sub["id"])
before = db.execute("SELECT count(*) AS n FROM media_assets").fetchone()["n"]
detail = _detail(ada, matter["id"])
host = _binding(detail, "Anschreiben")
ada.request(
"POST",
f"/api/v1/elements/{letter['id']}/attachments",
json={
"expected_version": host["element"]["version"],
"context": _ctx(matter["id"]),
"attachment_element_ids": [first["id"], second["id"], third["id"]],
"fold": "keep",
},
status=201,
)
ordered = _detail(ada, matter["id"])
host = _binding(ordered, "Anschreiben")
assert [item["title"] for item in host["correspondence"]["attachments"]] == [
"Rechnung 2023",
"Lageplan",
"Kontoauszug",
]
assert [item["document_on"] for item in host["correspondence"]["attachments"]] == [
"2023-05-01",
"2024-01-15",
"2025-11-02",
]
ada.request(
"POST",
f"/api/v1/elements/{letter['id']}/attachments/order",
json={
"expected_version": host["element"]["version"],
"context": _ctx(matter["id"]),
"attachment_element_ids": [third["id"], first["id"], second["id"]],
},
)
moved = _detail(ada, matter["id"])
host = _binding(moved, "Anschreiben")
assert [item["element_id"] for item in host["correspondence"]["attachments"]] == [third["id"], first["id"], second["id"]]
ada.request(
"POST",
f"/api/v1/elements/{letter['id']}/attachments/{second['id']}/detach",
json={"expected_version": host["element"]["version"], "context": _ctx(matter["id"])},
status=204,
)
kept = _detail(ada, matter["id"])
assert _binding(kept, "Lageplan")["chapter_id"] == sub["id"]
assert [item["title"] for item in _binding(kept, "Anschreiben")["correspondence"]["attachments"]] == [
"Kontoauszug",
"Rechnung 2023",
]
assert any(item["title"] == "Einzelbelege" and item["parent_chapter_id"] == chapter["id"] for item in kept["chapters"])
after = db.execute("SELECT count(*) AS n FROM media_assets").fetchone()["n"]
assert after == before
ada.request(
"POST",
"/api/v1/bindings",
json={"element_id": first["id"], "source_context": _ctx(matter["id"]), "target": _ctx(other["id"])},
status=201,
)
other_letter = ada.request(
"POST",
"/api/v1/notes",
json={"title": "Zweites Schreiben", "document": document("Andere Sache"), "context": _ctx(other["id"])},
status=201,
)
other_detail = _detail(ada, other["id"])
ada.request(
"POST",
f"/api/v1/elements/{other_letter['id']}/attachments",
json={
"expected_version": _binding(other_detail, "Zweites Schreiben")["element"]["version"],
"context": _ctx(other["id"]),
"attachment_element_ids": [first["id"]],
"fold": "keep",
},
status=201,
)
again = _detail(ada, matter["id"])
elsewhere = _detail(ada, other["id"])
assert [item["element_id"] for item in _binding(again, "Anschreiben")["correspondence"]["attachments"]] == [
third["id"],
first["id"],
]
assert [item["element_id"] for item in _binding(elsewhere, "Zweites Schreiben")["correspondence"]["attachments"]] == [
first["id"],
]
grants = db.execute("SELECT count(*) AS n FROM access_grants").fetchone()["n"]
assert grants == 0
ada.request(
"POST",
f"/api/v1/elements/{letter['id']}/attachments",
json={
"expected_version": _binding(again, "Anschreiben")["element"]["version"],
"context": _ctx(matter["id"]),
"attachment_element_ids": [letter["id"]],
"fold": "keep",
},
status=422,
)
ada.request(
"POST",
f"/api/v1/elements/{letter['id']}/attachments",
json={
"expected_version": _binding(again, "Anschreiben")["element"]["version"],
"context": _ctx(other["id"]),
"attachment_element_ids": [first["id"]],
"fold": "keep",
},
status=404,
)
def test_dispatch_keeps_the_secured_stand_and_distinct_mail_parts(client, db, monkeypatch):
raw = _eml(
"<versand@example.test>",
"Fachlicher Zusatz: die Frist bleibt der 1. Juni.",
[("rechnung.pdf", PDF_A), ("lage.pdf", PDF_B), ("konto.pdf", PDF_C), ("lage.pdf", PDF_D)],
)
monkeypatch.setattr("app.retrieval.pull_rfc822", lambda *args, **kwargs: raw)
ada = Actor(client, "ada-versand@example.test", "Ada Versand")
register(db, ada.email, ada.name)
ada.login()
matter = ada.request("POST", "/api/v1/matters", json={"title": "Versandakte"}, status=201)
letter = ada.request(
"POST",
"/api/v1/notes",
json={
"title": "Anschreiben",
"document": document("Ursprünglicher Text"),
"context": _ctx(matter["id"]),
"dates": {"document_on": "2026-02-01"},
},
status=201,
)
invoice = _file(ada, matter["id"], "Rechnung 2023", "rechnung.pdf", PDF_A, "2023-05-01")
plan = _file(ada, matter["id"], "Lageplan", "lage.pdf", PDF_B, "2024-01-15")
account = _file(ada, matter["id"], "Kontoauszug", "konto.pdf", PDF_C, "2025-11-02")
mailbox = ada.request(
"POST",
"/api/v1/connectors",
json={"kind": "imap", "name": "Postfach", "host": "mail.example.test", "username": "ada", "password": "secret-pass"},
status=201,
)
mail = ada.request(
"POST",
"/api/v1/external-refs",
json={
"title": "Gesendete Nachricht",
"source": "imap",
"external_id": "<versand@example.test>",
"context": _ctx(matter["id"]),
"detail": {"connector_id": mailbox["id"], "mailbox": "INBOX", "uid": 4},
},
status=201,
)
detail = _detail(ada, matter["id"])
ada.request(
"POST",
f"/api/v1/elements/{letter['id']}/attachments",
json={
"expected_version": _binding(detail, "Anschreiben")["element"]["version"],
"context": _ctx(matter["id"]),
"attachment_element_ids": [invoice["id"], plan["id"], account["id"]],
"fold": "attachment",
},
status=201,
)
folded = _detail(ada, matter["id"])
assert _binding(folded, "Rechnung 2023")["correspondence"]["fold"] == "attachment"
host = _binding(folded, "Anschreiben")
dispatch = ada.request(
"POST",
f"/api/v1/elements/{letter['id']}/dispatches",
json={
"expected_version": host["element"]["version"],
"context": _ctx(matter["id"]),
"channel": "email",
"sent_on": "2026-03-12",
"counterpart": "Gegenüber Beispiel",
"attachment_element_ids": [invoice["id"], plan["id"], account["id"]],
"evidence": [{"element_id": mail["id"], "role": "email", "fold": "evidence"}],
},
status=201,
)
assert dispatch["completeness"] == "secured"
assert dispatch["provenance"] == "captured"
assert dispatch["sent_on"] == "2026-03-12"
proof = dispatch["evidence"][0]
assert proof["source_state"] == "identified"
assert proof["manual"] is True
by_name = {item["filename"]: item["disposition"] for item in proof["comparisons"]}
assert by_name["rechnung.pdf"] == "same_bytes"
assert by_name["lage.pdf"] == "same_bytes"
assert by_name["konto.pdf"] == "same_bytes"
assert by_name["lage (2).pdf"] == "same_name_different_bytes"
uses = db.execute("SELECT count(*) AS n FROM attachment_uses").fetchone()["n"]
assert uses == 3
hidden = _detail(ada, matter["id"])
assert _binding(hidden, "Gesendete Nachricht")["correspondence"]["fold"] == "evidence"
ada.request(
"PATCH",
f"/api/v1/bindings/{_binding(hidden, 'Gesendete Nachricht')['id']}/fold",
json={
"expected_version": _binding(hidden, "Gesendete Nachricht")["element"]["version"],
"context": _ctx(matter["id"]),
"fold": None,
},
)
restored = _detail(ada, matter["id"])
assert _binding(restored, "Gesendete Nachricht")["correspondence"]["fold"] is None
ada.request(
"PATCH",
f"/api/v1/bindings/{_binding(restored, 'Gesendete Nachricht')['id']}/fold",
json={
"expected_version": _binding(restored, "Gesendete Nachricht")["element"]["version"],
"context": _ctx(matter["id"]),
"fold": "evidence",
},
)
ada.request(
"PATCH",
f"/api/v1/notes/{letter['id']}",
json={
"expected_version": _binding(restored, "Anschreiben")["element"]["version"],
"document": document("Später geänderter Text"),
"context": _ctx(matter["id"]),
},
)
changed = _detail(ada, matter["id"])
assert "Später geänderter Text" in _binding(changed, "Anschreiben")["element"]["excerpt"]
asset = db.execute("SELECT id FROM media_assets WHERE element_id = %s", (plan["id"],)).fetchone()
Path(os.environ["MEDIA_ROOT"], str(asset["id"])).write_bytes(PDF_D)
fresh = _detail(ada, matter["id"])
host = _binding(fresh, "Anschreiben")
ada.request(
"POST",
f"/api/v1/elements/{letter['id']}/attachments/{account['id']}/detach",
json={"expected_version": host["element"]["version"], "context": _ctx(matter["id"])},
status=204,
)
current = _detail(ada, matter["id"])
recorded = _binding(current, "Anschreiben")["correspondence"]["dispatches"][0]
assert [item["title"] for item in recorded["items"] if item["role"] == "attachment"] == [
"Rechnung 2023",
"Lageplan",
"Kontoauszug",
]
assert recorded["sent_on"] == "2026-03-12"
assert _binding(current, "Anschreiben")["element"]["dates"]["document_on"] == "2026-02-01"
plan_item = next(item for item in recorded["items"] if item["title"] == "Lageplan")
content = ada.client.get(
f"/api/v1/dispatches/{recorded['id']}/items/{plan_item['id']}/content",
params={"context_kind": "matter", "context_id": matter["id"]},
headers={
"Origin": ORIGIN,
"X-CSRF-Token": ada.csrf,
"X-Scope-Kind": ada.scope["kind"],
"X-Scope-Id": ada.scope["id"],
},
)
assert content.status_code == 200
assert content.content == PDF_B
tree = ada.request("GET", f"/api/v1/matters/{matter['id']}/export-tree")
nodes = list(_walk(tree["tree"]))
selected = [node["id"] for node in nodes if node["kind"] in {"dispatch_item", "evidence"}]
archive = _zip(ada, matter["id"], selected)
names = archive.namelist()
snapshot = next(name for name in names if name.endswith("/lage.pdf") and "/anlagen/" not in name)
assert archive.read(snapshot) == PDF_B
eml_name = next(name for name in names if name.endswith("nachricht.eml"))
assert b"Fachlicher Zusatz" in archive.read(eml_name)
assert archive.read(eml_name).count(b"lage.pdf") >= 2
overview = archive.read("inhalt.md").decode("utf-8")
assert "Gesicherte Versandfassung" in overview
assert "Schreiben → Versand → Nachweis" in overview
first_text = "\n".join(
archive.read(name).decode("utf-8", errors="replace")
for name in names
if name.endswith((".md", ".txt", ".eml", ".json"))
)
assert "Ursprünglicher Text" in first_text
assert "Später geänderter Text" not in first_text
gap = ada.request(
"POST",
f"/api/v1/elements/{letter['id']}/dispatches",
json={
"expected_version": _binding(current, "Anschreiben")["element"]["version"],
"context": _ctx(matter["id"]),
"channel": "post",
"sent_on": None,
"counterpart": None,
"attachment_element_ids": [invoice["id"]],
"historical_gap": True,
},
status=201,
)
assert gap["provenance"] == "reconstructed"
assert gap["completeness"] == "gap"
assert gap["undated"] is True
assert gap["sent_on"] is None
assert all(item["source_state"] == "gap" for item in gap["items"])
receipt = ada.request(
"POST",
"/api/v1/notes",
json={
"title": "Einlieferungsbeleg",
"document": document("Eingeliefert am Schalter"),
"context": _ctx(matter["id"]),
"dates": {"document_on": "2026-03-20"},
},
status=201,
)
delivery = ada.request(
"POST",
"/api/v1/notes",
json={
"title": "Zustellbestätigung",
"document": document("Zugestellt"),
"context": _ctx(matter["id"]),
"dates": {"document_on": "2026-03-28"},
},
status=201,
)
posted = ada.request(
"POST",
f"/api/v1/elements/{letter['id']}/dispatches",
json={
"expected_version": _binding(_detail(ada, matter["id"]), "Anschreiben")["element"]["version"],
"context": _ctx(matter["id"]),
"channel": "post",
"sent_on": "2026-03-18",
"counterpart": "Poststelle",
"attachment_element_ids": [invoice["id"]],
"evidence": [{"element_id": receipt["id"], "role": "submission", "fold": "keep"}],
},
status=201,
)
assert posted["evidence"][0]["role"] == "submission"
assert "zugestellt" not in json.dumps(posted).lower()
added = ada.request(
"POST",
f"/api/v1/dispatches/{posted['id']}/evidence",
json={
"expected_version": posted["version"],
"context": _ctx(matter["id"]),
"element_id": delivery["id"],
"role": "delivery",
"fold": "keep",
},
status=201,
)
assert added["role"] == "delivery"
final = _detail(ada, matter["id"])
sends = _binding(final, "Anschreiben")["correspondence"]["dispatches"]
assert len(sends) == 3
assert {item["channel"] for item in sends} == {"email", "post"}
post_send = next(item for item in sends if item["sent_on"] == "2026-03-18")
assert {item["role"] for item in post_send["evidence"]} == {"submission", "delivery"}
assert _binding(final, "Zustellbestätigung")["element"]["dates"]["document_on"] == "2026-03-28"
ada.request(
"PATCH",
f"/api/v1/matters/{matter['id']}/content-order",
json={"expected_version": final["version"], "mode": "date", "direction": "asc", "view": "chronology"},
)
viewed = _detail(ada, matter["id"])
assert viewed["content_view"] == "chronology"
assert viewed["content_order"] == "date"
assert _binding(viewed, "Anschreiben")["chapter_id"] is None
excerpt_tree = ada.request("GET", f"/api/v1/matters/{matter['id']}/export-tree")
host_item = next(
node["id"]
for node in _walk(excerpt_tree["tree"])
if node["kind"] == "dispatch_item" and node["title"] == "Anschreiben"
)
review = ada.request(
"POST",
f"/api/v1/matters/{matter['id']}/export/review",
json={"selected": [host_item]},
)
assert any("Auszug dieses Versands" in item["message"] for item in review["notices"])
whole = [node["id"] for node in _walk(excerpt_tree["tree"]) if node["id"].startswith("dispatch-item:") or node["id"].startswith("evidence:")]
full = _zip(ada, matter["id"], whole)
joined = "\n".join(full.read(name).decode("utf-8", errors="replace") for name in full.namelist() if name.endswith((".md", ".txt", ".eml", ".json")))
assert "Ursprünglicher Text" in joined
assert "Historische Fassung liegt nicht vor" in joined
gaps = [name for name in full.namelist() if name.endswith("-luecke.txt")]
assert gaps
assert all("Später geänderter Text" not in full.read(name).decode("utf-8") for name in gaps)
assert all(b"%PDF" not in full.read(name) for name in gaps)
secured = next(name for name in full.namelist() if name.endswith("/lage.pdf") and "/anlagen/" not in name)
assert full.read(secured) == PDF_B
def test_locked_parts_and_readers_stay_outside(client, db):
ada = Actor(client, "ada-sperre@example.test", "Ada Sperre")
ben = Actor(client, "ben-sperre@example.test", "Ben Sperre")
register(db, ada.email, ada.name)
register(db, ben.email, ben.name)
ada.login()
case = ada.request("POST", "/api/v1/cases", json={"title": "Geteilte Akte"}, status=201)
matter = ada.request("POST", "/api/v1/matters", json={"title": "Geteilter Vorgang"}, status=201)
ada.request("POST", f"/api/v1/matters/{matter['id']}/case-links", json={"case_id": case["id"]}, status=201)
letter = ada.request(
"POST",
"/api/v1/notes",
json={"title": "Sichtbares Schreiben", "document": document("Sichtbar"), "context": _ctx(matter["id"])},
status=201,
)
secret = ada.request(
"POST",
"/api/v1/notes",
json={"title": "Geheime AnlageXQ", "document": document("Nicht zeigen"), "context": _ctx(matter["id"])},
status=201,
)
proof = ada.request(
"POST",
"/api/v1/notes",
json={"title": "Geheimer NachweisXQ", "document": document("Auch nicht"), "context": _ctx(matter["id"])},
status=201,
)
detail = _detail(ada, matter["id"])
ada.request(
"POST",
f"/api/v1/elements/{letter['id']}/attachments",
json={
"expected_version": _binding(detail, "Sichtbares Schreiben")["element"]["version"],
"context": _ctx(matter["id"]),
"attachment_element_ids": [secret["id"]],
"fold": "keep",
},
status=201,
)
sent = ada.request(
"POST",
f"/api/v1/elements/{letter['id']}/dispatches",
json={
"expected_version": _binding(_detail(ada, matter["id"]), "Sichtbares Schreiben")["element"]["version"],
"context": _ctx(matter["id"]),
"channel": "other",
"sent_on": "2026-04-01",
"attachment_element_ids": [secret["id"]],
"evidence": [{"element_id": proof["id"], "role": "other", "fold": "keep"}],
},
status=201,
)
grant(ada, case["id"], ben.email, edit=False, share=False)
ada.request(
"PUT",
"/api/v1/exceptions",
json={
"resource_kind": "element",
"resource_id": secret["id"],
"context": {"kind": "case", "id": case["id"]},
"remove_read": True,
},
)
ada.request(
"PUT",
"/api/v1/exceptions",
json={
"resource_kind": "element",
"resource_id": proof["id"],
"context": {"kind": "case", "id": case["id"]},
"remove_read": True,
},
)
ben.login()
page = {"kind": "case", "id": case["id"]}
visible = _detail(ben, matter["id"], page)
blob = json.dumps(visible)
assert "Geheime AnlageXQ" not in blob
assert "Geheimer NachweisXQ" not in blob
assert "Nicht zeigen" not in blob
host = _binding(visible, "Sichtbares Schreiben")
assert host["correspondence"]["attachments"] == []
assert host["correspondence"]["dispatches"][0]["evidence"] == []
ben.request(
"POST",
f"/api/v1/elements/{letter['id']}/attachments",
json={
"expected_version": host["element"]["version"],
"context": page,
"placement": _ctx(matter["id"]),
"attachment_element_ids": [letter["id"]],
"fold": "keep",
},
status=403,
)
ben.request(
"POST",
f"/api/v1/dispatches/{sent['id']}/correct",
json={"expected_version": sent["version"], "context": page, "placement": _ctx(matter["id"]), "counterpart": "Fremd"},
status=403,
)
ada.login()
ada.request(
"POST",
f"/api/v1/elements/{letter['id']}/attachments",
json={
"expected_version": _binding(_detail(ada, matter["id"]), "Sichtbares Schreiben")["element"]["version"],
"context": _ctx(matter["id"]),
"attachment_element_ids": ["00000000-0000-4000-8000-000000000099"],
"fold": "keep",
},
status=404,
)