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

+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)