Verkuerze die Inhaltsliste und fuehre Unterkapitel ein, damit Richtung, Bezuge und Struktur ohne Zusatzzeilen bedienbar bleiben.
Deploy Development / deploy (push) Successful in 29s
Test Suite / pytest-backend (push) Successful in 1m24s
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-17 21:13:21 +02:00
1 parent eeeb81148a
commit e4380261fc
30 files changed
+2384 -430

No files matched your search

+94 -4
View File
@@ -44,6 +44,8 @@ from app.api.schemas import (
CasePatch,
ChapterDateIn,
ChapterDeleteIn,
ChapterParentIn,
BindingChaptersIn,
ChapterTitleIn,
CommunicationIn,
MatterMoveIn,
@@ -126,6 +128,8 @@ from app.ops import (
patch_task,
revoke_grant,
move_binding_chapter,
move_bindings_chapter,
move_chapter_parent,
move_matter,
reorder_bindings,
rename_chapter,
@@ -174,6 +178,16 @@ def _ctx_model(value) -> Ctx | None:
return None if value is None else Ctx(value.kind, value.id)
def _chapter_payload(row) -> dict:
return {
"id": str(row["id"]),
"title": row["title"],
"position": row["position"],
"document_on": dump_date(row["document_on"]),
"parent_chapter_id": str(row["parent_chapter_id"]) if row["parent_chapter_id"] else None,
}
def _session_body(conn, account_id: UUID, scope_kind: str, scope_id: UUID, csrf: str, epoch: int) -> dict:
account = conn.execute(
"SELECT id, email, display_name, is_superadmin FROM auth_accounts WHERE id = %s",
@@ -588,10 +602,20 @@ def post_case_chapter(
principal: Principal = Depends(get_principal),
conn: Connection = Depends(get_conn),
):
row = create_chapter(conn, principal.account_id, "case", case_id, body.title, body.position, None, body.document_on)
row = create_chapter(
conn,
principal.account_id,
"case",
case_id,
body.title,
body.position,
None,
body.document_on,
body.parent_chapter_id,
)
return _created(
f"/api/v1/cases/{case_id}/chapters/{row['id']}",
{"id": str(row["id"]), "title": row["title"], "position": row["position"], "document_on": dump_date(row["document_on"])},
_chapter_payload(row),
)
@@ -678,11 +702,19 @@ def post_matter_chapter(
):
context = parse_query_context(context_kind, context_id)
row = create_chapter(
conn, principal.account_id, "matter", matter_id, body.title, body.position, context, body.document_on
conn,
principal.account_id,
"matter",
matter_id,
body.title,
body.position,
context,
body.document_on,
body.parent_chapter_id,
)
return _created(
f"/api/v1/matters/{matter_id}/chapters/{row['id']}",
{"id": str(row["id"]), "title": row["title"], "position": row["position"], "document_on": dump_date(row["document_on"])},
_chapter_payload(row),
)
@@ -725,6 +757,24 @@ def post_delete_chapter(
return {"version": version}
@router.post("/api/v1/chapters/{chapter_id}/parent")
def post_chapter_parent(
chapter_id: UUID,
body: ChapterParentIn,
principal: Principal = Depends(get_principal),
conn: Connection = Depends(get_conn),
):
version = move_chapter_parent(
conn,
principal.account_id,
chapter_id,
body.expected_version,
body.parent_chapter_id,
_ctx_model(body.context),
)
return {"version": version, "parent_chapter_id": str(body.parent_chapter_id) if body.parent_chapter_id else None}
@router.post("/api/v1/cases/{case_id}/delete")
def post_delete_case(
case_id: UUID,
@@ -1426,6 +1476,26 @@ def post_case_binding_order(
return {"version": version}
@router.post("/api/v1/cases/{case_id}/bindings/chapters")
def post_case_binding_chapters(
case_id: UUID,
body: BindingChaptersIn,
principal: Principal = Depends(get_principal),
conn: Connection = Depends(get_conn),
):
version = move_bindings_chapter(
conn,
principal.account_id,
"case",
case_id,
body.expected_version,
body.binding_ids,
body.chapter_id,
None,
)
return {"version": version}
@router.patch("/api/v1/matters/{matter_id}/content-order")
def patch_matter_order(
matter_id: UUID,
@@ -1465,6 +1535,26 @@ def post_matter_binding_order(
return {"version": version}
@router.post("/api/v1/matters/{matter_id}/bindings/chapters")
def post_matter_binding_chapters(
matter_id: UUID,
body: BindingChaptersIn,
principal: Principal = Depends(get_principal),
conn: Connection = Depends(get_conn),
):
version = move_bindings_chapter(
conn,
principal.account_id,
"matter",
matter_id,
body.expected_version,
body.binding_ids,
body.chapter_id,
_ctx_model(body.context),
)
return {"version": version}
@router.patch("/api/v1/elements/{element_id}/dates")
def patch_element_dates(
element_id: UUID,
+14
View File
@@ -79,6 +79,7 @@ class ChapterIn(APIModel):
title: str = Field(min_length=1, max_length=200)
position: int | None = Field(default=None, ge=0, le=10000)
document_on: date | None = None
parent_chapter_id: UUID | None = None
class ChapterOrderIn(APIModel):
@@ -104,6 +105,19 @@ class ChapterDeleteIn(APIModel):
context: ContextIn | None = None
class ChapterParentIn(APIModel):
expected_version: int = Field(ge=1)
parent_chapter_id: UUID | None = None
context: ContextIn | None = None
class BindingChaptersIn(APIModel):
expected_version: int = Field(ge=1)
binding_ids: list[UUID] = Field(min_length=1, max_length=500)
chapter_id: UUID | None = None
context: ContextIn | None = None
class RecordDeleteIn(APIModel):
expected_version: int = Field(ge=1)
context: ContextIn | None = None
+45 -19
View File
@@ -252,22 +252,7 @@ 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] = []
for chapter in chapters:
items = grouped.get(chapter["id"], [])
if not items:
continue
children.append(
ExportNode(
id=f"chapter:{chapter['id']}",
kind="chapter",
title=chapter["title"],
exportable=True,
reason=None,
content_kind=None,
children=[_binding_node(item) for item in items],
label="Kapitel",
)
)
children.extend(_chapter_nodes(chapters, grouped))
for binding in grouped.get(None, []):
children.append(_binding_node(binding))
rows = conn.execute(
@@ -290,6 +275,35 @@ def _matter_node(conn, actor, matter, page: Ctx, root: bool) -> ExportNode:
)
def _chapter_nodes(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]:
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"], [])]
if not items and not nested:
continue
nodes.append(
ExportNode(
id=f"chapter:{chapter['id']}",
kind="chapter",
title=chapter["title"],
exportable=True,
reason=None,
content_kind=None,
children=[*items, *nested],
label="Unterkapitel" if parent_id else "Kapitel",
)
)
return nodes
return build(None)
def _binding_node(binding: dict) -> ExportNode:
element = binding["element"]
rights = binding["rights"]
@@ -454,7 +468,7 @@ def _layout(root, chosen, loaded, notices, generated: str):
numbers = {child.id: index + 1 for index, child in enumerate(folders)}
for child in node.children:
if child.id in numbers:
folder = prefix + [f"{numbers[child.id]:02d} {_segment(child.title)}"]
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)
else:
@@ -726,7 +740,7 @@ def _recorded(node: ExportNode) -> str | None:
return node.dates.get("recorded_at")
def _segment(value: str) -> str:
def _segment(value: str, limit: int = 80) -> str:
cleaned = []
for char in value or "":
if char in '\\/:*?"<>|' or ord(char) < 32:
@@ -734,7 +748,19 @@ def _segment(value: str) -> str:
else:
cleaned.append(char)
text = " ".join("".join(cleaned).split()).strip(" .")
return (text or "Inhalt")[:80]
if text in {"", ".", ".."}:
text = "Inhalt"
return text[:limit]
def _folder_name(title: str, number: int, prefix: list[str]) -> str:
"""Keep a readable directory name inside a bounded path. The overview keeps the full title."""
limit = 80
while True:
name = f"{number:02d} {_segment(title, limit)}"
if len("/".join([*prefix, name])) <= 180 or limit <= 24:
return name
limit -= 8
def _file_segment(value: str) -> str:
+211 -19
View File
@@ -37,6 +37,8 @@ from app.core.errors import forbidden, not_found, unprocessable
from app.core.timeutil import utcnow
from app.media.storage import asset_path, display_filename, sha256, sniff, write_bytes
MAX_CHAPTER_DEPTH = 32
def _ctx(value) -> Ctx | None:
if value is None:
@@ -121,6 +123,105 @@ def patch_case(conn, actor: UUID, case_id: UUID, expected: int, title: str | Non
return updated
def _chapter_column(kind: str) -> str:
return "case_id" if kind == "case" else "matter_id"
def _parent_chain(conn, chapter_id: UUID | None) -> list[UUID]:
chain: list[UUID] = []
current = chapter_id
seen: set[UUID] = set()
while current and current not in seen:
seen.add(current)
chain.append(current)
row = conn.execute("SELECT parent_chapter_id FROM chapters WHERE id = %s", (current,)).fetchone()
current = row["parent_chapter_id"] if row else None
return chain
def _subtree_height(conn, chapter_id: UUID) -> int:
rows = conn.execute("SELECT id FROM chapters WHERE parent_chapter_id = %s", (chapter_id,)).fetchall()
if not rows:
return 1
return 1 + max(_subtree_height(conn, row["id"]) for row in rows)
def _assert_chapter_parent(
conn,
kind: str,
container_id: UUID,
parent_id: UUID | None,
moving_id: UUID | None = None,
) -> None:
if parent_id is None:
return
if moving_id is not None and parent_id == moving_id:
raise unprocessable("Ein Kapitel kann nicht unter sich selbst stehen.")
column = _chapter_column(kind)
parent = conn.execute(
f"SELECT id FROM chapters WHERE id = %s AND {column} = %s",
(parent_id, container_id),
).fetchone()
if parent is None:
raise unprocessable("Das Elternkapitel gehört nicht zu diesem Kontext.")
if moving_id is not None and moving_id in _parent_chain(conn, parent_id):
raise unprocessable("Diese Zuordnung würde einen Kreis erzeugen.")
extra = _subtree_height(conn, moving_id) if moving_id is not None else 1
if len(_parent_chain(conn, parent_id)) + extra > MAX_CHAPTER_DEPTH:
raise unprocessable(
f"Die Kapiteltiefe überschreitet die technische Schutzgrenze von {MAX_CHAPTER_DEPTH} Ebenen."
)
def _sibling_ids(conn, kind: str, container_id: UUID, parent_id: UUID | None) -> list[UUID]:
column = _chapter_column(kind)
if parent_id is None:
rows = conn.execute(
f"""
SELECT id FROM chapters
WHERE {column} = %s AND parent_chapter_id IS NULL
ORDER BY position, id
""",
(container_id,),
).fetchall()
else:
rows = conn.execute(
f"""
SELECT id FROM chapters
WHERE {column} = %s AND parent_chapter_id = %s
ORDER BY position, id
""",
(container_id, parent_id),
).fetchall()
return [row["id"] for row in rows]
def _renumber_chapters(conn, chapter_ids: list[UUID]) -> None:
for index, chapter_id in enumerate(chapter_ids):
conn.execute("UPDATE chapters SET position = %s WHERE id = %s", (index, chapter_id))
def _next_sibling_position(conn, kind: str, container_id: UUID, parent_id: UUID | None) -> int:
column = _chapter_column(kind)
if parent_id is None:
row = conn.execute(
f"""
SELECT COALESCE(MAX(position), -1) + 1 AS pos FROM chapters
WHERE {column} = %s AND parent_chapter_id IS NULL
""",
(container_id,),
).fetchone()
else:
row = conn.execute(
f"""
SELECT COALESCE(MAX(position), -1) + 1 AS pos FROM chapters
WHERE {column} = %s AND parent_chapter_id = %s
""",
(container_id, parent_id),
).fetchone()
return int(row["pos"])
def create_chapter(
conn,
actor: UUID,
@@ -130,33 +231,30 @@ def create_chapter(
position: int | None,
context: Ctx | None,
document_on: date | None = None,
parent_chapter_id: UUID | None = None,
) -> dict:
if kind == "case":
container, _rights = require_case(conn, actor, container_id, "edit")
else:
container, _rights = require_matter(conn, actor, container_id, context, "edit")
_assert_chapter_parent(conn, kind, container_id, parent_chapter_id)
if position is None:
column = "case_id" if kind == "case" else "matter_id"
current = conn.execute(
f"SELECT COALESCE(MAX(position), -1) + 1 AS pos FROM chapters WHERE {column} = %s",
(container_id,),
).fetchone()
position = int(current["pos"])
position = _next_sibling_position(conn, kind, container_id, parent_chapter_id)
if kind == "case":
row = conn.execute(
"""
INSERT INTO chapters (home_scope_id, case_id, title, position, document_on)
VALUES (%s, %s, %s, %s, %s) RETURNING *
INSERT INTO chapters (home_scope_id, case_id, title, position, document_on, parent_chapter_id)
VALUES (%s, %s, %s, %s, %s, %s) RETURNING *
""",
(container["home_scope_id"], container_id, title.strip(), position, document_on),
(container["home_scope_id"], container_id, title.strip(), position, document_on, parent_chapter_id),
).fetchone()
else:
row = conn.execute(
"""
INSERT INTO chapters (home_scope_id, matter_id, title, position, document_on)
VALUES (%s, %s, %s, %s, %s) RETURNING *
INSERT INTO chapters (home_scope_id, matter_id, title, position, document_on, parent_chapter_id)
VALUES (%s, %s, %s, %s, %s, %s) RETURNING *
""",
(container["home_scope_id"], container_id, title.strip(), position, document_on),
(container["home_scope_id"], container_id, title.strip(), position, document_on, parent_chapter_id),
).fetchone()
audit(conn, actor, container["home_scope_id"], "chapter_created", kind, container_id, context)
return row
@@ -182,16 +280,28 @@ def reorder_chapters(
if not rights.edit:
raise forbidden()
version = bump_version(conn, table, container_id, expected)
rows = conn.execute(f"SELECT id FROM chapters WHERE {column} = %s", (container_id,)).fetchall()
existing = [row["id"] for row in rows]
rows = conn.execute(
f"SELECT id, parent_chapter_id FROM chapters WHERE {column} = %s",
(container_id,),
).fetchall()
existing = {row["id"]: row["parent_chapter_id"] for row in rows}
if len(chapter_ids) != len(set(chapter_ids)):
raise unprocessable("Dasselbe Kapitel steht mehrfach in der Ordnung.")
if any(item not in set(existing) for item in chapter_ids):
if any(item not in existing for item in chapter_ids):
raise not_found()
if set(chapter_ids) != set(existing):
if not chapter_ids:
if existing:
raise unprocessable("Die Kapitelordnung ist unvollständig. Bitte neu laden.")
audit(conn, actor, container["home_scope_id"], "chapters_reordered", kind, container_id, context)
return version
parents = {existing[item] for item in chapter_ids}
if len(parents) != 1:
raise unprocessable("Die Kapitelordnung mischt verschiedene Ebenen.")
parent_id = next(iter(parents))
siblings = {item for item, parent in existing.items() if parent == parent_id}
if set(chapter_ids) != siblings:
raise unprocessable("Die Kapitelordnung ist unvollständig. Bitte neu laden.")
for index, chapter_id in enumerate(chapter_ids):
conn.execute("UPDATE chapters SET position = %s WHERE id = %s", (index, chapter_id))
_renumber_chapters(conn, chapter_ids)
audit(conn, actor, container["home_scope_id"], "chapters_reordered", kind, container_id, context)
return version
@@ -315,14 +425,96 @@ def rename_chapter(conn, actor: UUID, chapter_id: UUID, expected: int, title: st
def delete_chapter(conn, actor: UUID, chapter_id: UUID, expected: int, context: Ctx | None) -> int:
"""Dissolve one chapter. Direct bindings and direct children move to its parent."""
chapter, container, kind = _chapter_container(conn, actor, chapter_id, context)
version = bump_version(conn, "cases" if kind == "case" else "matters", container["id"], expected)
conn.execute("UPDATE bindings SET chapter_id = NULL WHERE chapter_id = %s", (chapter["id"],))
parent_id = chapter["parent_chapter_id"]
children = _sibling_ids(conn, kind, container["id"], chapter["id"])
siblings = _sibling_ids(conn, kind, container["id"], parent_id)
merged: list[UUID] = []
for item in siblings:
if item == chapter["id"]:
merged.extend(children)
else:
merged.append(item)
if children:
conn.execute(
"UPDATE chapters SET parent_chapter_id = %s WHERE parent_chapter_id = %s",
(parent_id, chapter["id"]),
)
_renumber_chapters(conn, merged)
conn.execute("UPDATE bindings SET chapter_id = %s WHERE chapter_id = %s", (parent_id, chapter["id"]))
conn.execute("DELETE FROM chapters WHERE id = %s", (chapter["id"],))
audit(conn, actor, container["home_scope_id"], "chapter_deleted", kind, container["id"], context)
return version
def move_chapter_parent(
conn,
actor: UUID,
chapter_id: UUID,
expected: int,
parent_id: UUID | None,
context: Ctx | None,
) -> int:
"""Reparent one chapter inside its own container. The subtree stays together."""
chapter, container, kind = _chapter_container(conn, actor, chapter_id, context)
if chapter["parent_chapter_id"] == parent_id:
return bump_version(conn, "cases" if kind == "case" else "matters", container["id"], expected)
_assert_chapter_parent(conn, kind, container["id"], parent_id, chapter["id"])
version = bump_version(conn, "cases" if kind == "case" else "matters", container["id"], expected)
old_siblings = [item for item in _sibling_ids(conn, kind, container["id"], chapter["parent_chapter_id"]) if item != chapter["id"]]
_renumber_chapters(conn, old_siblings)
position = len(_sibling_ids(conn, kind, container["id"], parent_id))
conn.execute(
"UPDATE chapters SET parent_chapter_id = %s, position = %s WHERE id = %s",
(parent_id, position, chapter["id"]),
)
audit(conn, actor, container["home_scope_id"], "chapter_moved", kind, container["id"], context)
return version
def move_bindings_chapter(
conn,
actor: UUID,
kind: str,
container_id: UUID,
expected: int,
binding_ids: list[UUID],
chapter_id: UUID | None,
context: Ctx | None,
) -> int:
"""Move visible bindings inside one container. One failure leaves every binding in place."""
if kind == "case":
container, rights = require_case(conn, actor, container_id, "edit")
table = "cases"
page = Ctx("case", container_id)
else:
container, rights = require_matter(conn, actor, container_id, context, "edit")
table = "matters"
page = context or Ctx("matter", container_id)
if not rights.edit:
raise forbidden()
if len(binding_ids) != len(set(binding_ids)):
raise unprocessable("Dieselbe Einbindung steht mehrfach in der Auswahl.")
chapter_for(conn, chapter_id, kind, container_id)
rows = conn.execute(
"SELECT id, element_id FROM bindings WHERE context_kind = %s AND context_id = %s",
(kind, container_id),
).fetchall()
by_id = {row["id"]: row for row in rows}
for binding_id in binding_ids:
row = by_id.get(binding_id)
if row is None:
raise not_found()
require_element(conn, actor, row["element_id"], page, "read")
version = bump_version(conn, table, container_id, expected)
for binding_id in binding_ids:
conn.execute("UPDATE bindings SET chapter_id = %s WHERE id = %s", (chapter_id, binding_id))
audit(conn, actor, container["home_scope_id"], "binding_chapter", kind, container_id, page)
return version
def delete_case(conn, actor: UUID, case_id: UUID, expected: int) -> None:
case, rights = require_case(conn, actor, case_id, "edit")
if not rights.edit:
+3 -1
View File
@@ -33,7 +33,7 @@ def rights_dict(rights) -> dict:
def _chapters(conn, kind: str, container_id: UUID, mode: str = "position", direction: str = "asc") -> list[dict]:
column = "case_id" if kind == "case" else "matter_id"
rows = conn.execute(
f"SELECT id, title, position, document_on FROM chapters WHERE {column} = %s",
f"SELECT id, title, position, document_on, parent_chapter_id FROM chapters WHERE {column} = %s",
(container_id,),
).fetchall()
items = [
@@ -42,6 +42,7 @@ def _chapters(conn, kind: str, container_id: UUID, mode: str = "position", direc
"title": row["title"],
"position": row["position"],
"document_on": dump_date(row["document_on"]),
"parent_chapter_id": str(row["parent_chapter_id"]) if row["parent_chapter_id"] else None,
}
for row in rows
]
@@ -956,6 +957,7 @@ LABELS = {
"binding_chapter": "In ein Kapitel eingeordnet",
"chapters_reordered": "Kapitelreihenfolge geändert",
"chapter_dated": "Kapiteldatum geändert",
"chapter_moved": "Kapitel umgehängt",
"content_order": "Ordnungsart geändert",
"content_reordered": "Eigene Reihenfolge geändert",
}
@@ -0,0 +1,54 @@
ALTER TABLE chapters
ADD COLUMN parent_chapter_id uuid;
ALTER TABLE chapters
ADD CONSTRAINT chapters_not_self
CHECK (parent_chapter_id IS NULL OR parent_chapter_id <> id);
ALTER TABLE chapters
ADD CONSTRAINT chapters_parent_fk
FOREIGN KEY (parent_chapter_id) REFERENCES chapters (id);
CREATE INDEX chapters_parent ON chapters (parent_chapter_id);
CREATE FUNCTION chapters_parent_guard() RETURNS trigger
LANGUAGE plpgsql AS $$
DECLARE
parent chapters%ROWTYPE;
current_id uuid;
seen uuid[] := ARRAY[]::uuid[];
depth integer := 1;
BEGIN
IF NEW.parent_chapter_id IS NULL THEN
RETURN NEW;
END IF;
SELECT * INTO parent FROM chapters WHERE id = NEW.parent_chapter_id;
IF NOT FOUND THEN
RAISE EXCEPTION 'Kapiteleltern ungültig';
END IF;
IF NEW.case_id IS DISTINCT FROM parent.case_id
OR NEW.matter_id IS DISTINCT FROM parent.matter_id
OR NEW.home_scope_id IS DISTINCT FROM parent.home_scope_id THEN
RAISE EXCEPTION 'Kapiteleltern ungültig';
END IF;
current_id := NEW.parent_chapter_id;
WHILE current_id IS NOT NULL LOOP
IF current_id = NEW.id OR current_id = ANY (seen) THEN
RAISE EXCEPTION 'Kapiteleltern ungültig';
END IF;
seen := array_append(seen, current_id);
depth := depth + 1;
IF depth > 32 THEN
RAISE EXCEPTION 'Kapiteleltern ungültig';
END IF;
SELECT parent_chapter_id INTO current_id FROM chapters WHERE id = current_id;
END LOOP;
RETURN NEW;
END;
$$;
CREATE TRIGGER chapters_parent_guard
BEFORE INSERT OR UPDATE OF parent_chapter_id, case_id, matter_id, home_scope_id
ON chapters
FOR EACH ROW
EXECUTE FUNCTION chapters_parent_guard();
+338
View File
@@ -0,0 +1,338 @@
"""Nested chapters stay outline only: same object, no rights, no partial moves."""
from __future__ import annotations
import psycopg
import pytest
from tests.support import Actor, binding_for, case_of, document, grant, matter_of, register
def _note(actor: Actor, title: str, matter: dict, chapter_id: str | None = None) -> dict:
body = {
"title": title,
"document": document(title),
"context": {"kind": "matter", "id": matter["id"]},
}
if chapter_id:
body["chapter_id"] = chapter_id
return actor.request("POST", "/api/v1/notes", json=body, status=201)
def _detail(actor: Actor, matter_id: str) -> dict:
return actor.request("GET", f"/api/v1/matters/{matter_id}")
def _by_title(detail: dict) -> dict[str, dict]:
return {item["title"]: item for item in detail["chapters"]}
def test_flat_chapters_keep_identity_order_and_bindings(client, db):
ada = Actor(client, "ada-flach@example.test", "Ada Flach")
register(db, ada.email, ada.name)
ada.login()
matter = matter_of(ada, "Bestehender Vorgang")
first = ada.request(
"POST",
f"/api/v1/matters/{matter['id']}/chapters",
json={"title": "Schriftverkehr", "document_on": "2024-02-02"},
status=201,
)
second = ada.request(
"POST",
f"/api/v1/matters/{matter['id']}/chapters",
json={"title": "Nachweise", "document_on": "2024-01-01"},
status=201,
)
_note(ada, "Altes Schreiben", matter, first["id"])
detail = _detail(ada, matter["id"])
assert [item["id"] for item in detail["chapters"]] == [second["id"], first["id"]]
assert all(item["parent_chapter_id"] is None for item in detail["chapters"])
assert binding_for(detail, "Altes Schreiben")["chapter_id"] == first["id"]
ada.login()
again = _detail(ada, matter["id"])
assert [(item["id"], item["title"], item["parent_chapter_id"]) for item in again["chapters"]] == [
(second["id"], "Nachweise", None),
(first["id"], "Schriftverkehr", None),
]
assert binding_for(again, "Altes Schreiben")["chapter_id"] == first["id"]
def test_three_levels_bulk_move_reorder_reparent_and_dissolve(client, db):
ada = Actor(client, "ada-nest@example.test", "Ada Nest")
register(db, ada.email, ada.name)
ada.login()
matter = matter_of(ada, "Nebenkostenabrechnung")
root = ada.request(
"POST",
f"/api/v1/matters/{matter['id']}/chapters",
json={"title": "Nebenkostenabrechnung 2025"},
status=201,
)
sent = ada.request(
"POST",
f"/api/v1/matters/{matter['id']}/chapters",
json={"title": "Übermittelte Abrechnungsunterlagen", "parent_chapter_id": root["id"]},
status=201,
)
receipts = ada.request(
"POST",
f"/api/v1/matters/{matter['id']}/chapters",
json={"title": "Einzelbelege", "parent_chapter_id": sent["id"]},
status=201,
)
sibling = ada.request(
"POST",
f"/api/v1/matters/{matter['id']}/chapters",
json={"title": "Weiterer Ordner", "parent_chapter_id": root["id"]},
status=201,
)
_note(ada, "Anschreiben", matter, sent["id"])
_note(ada, "Abrechnung", matter, sent["id"])
_note(ada, "Rückfrage zur Abrechnung", matter, root["id"])
_note(ada, "Antwort des Vermieters", matter, root["id"])
for index in range(8):
ada.request(
"POST",
"/api/v1/external-refs",
json={
"title": f"Beleg {index + 1}",
"source": "paperless",
"external_id": str(700 + index),
"context": {"kind": "matter", "id": matter["id"]},
"chapter_id": root["id"],
},
status=201,
)
detail = _detail(ada, matter["id"])
chapters = _by_title(detail)
assert chapters["Übermittelte Abrechnungsunterlagen"]["parent_chapter_id"] == root["id"]
assert chapters["Einzelbelege"]["parent_chapter_id"] == sent["id"]
assert binding_for(detail, "Rückfrage zur Abrechnung")["chapter_id"] == root["id"]
assert binding_for(detail, "Anschreiben")["chapter_id"] == sent["id"]
receipt_ids = [binding_for(detail, f"Beleg {index + 1}")["id"] for index in range(8)]
moved = ada.request(
"POST",
f"/api/v1/matters/{matter['id']}/bindings/chapters",
json={"expected_version": detail["version"], "binding_ids": receipt_ids, "chapter_id": receipts["id"]},
)
detail = _detail(ada, matter["id"])
assert detail["version"] == moved["version"]
assert all(binding_for(detail, f"Beleg {index + 1}")["chapter_id"] == receipts["id"] for index in range(8))
assert binding_for(detail, "Rückfrage zur Abrechnung")["chapter_id"] == root["id"]
assert binding_for(detail, "Anschreiben")["chapter_id"] == sent["id"]
stale = detail["version"]
ada.request(
"POST",
f"/api/v1/matters/{matter['id']}/bindings/chapters",
json={
"expected_version": stale,
"binding_ids": [receipt_ids[0], "00000000-0000-4000-8000-000000000099"],
"chapter_id": root["id"],
},
status=404,
)
detail = _detail(ada, matter["id"])
assert detail["version"] == stale
assert binding_for(detail, "Beleg 1")["chapter_id"] == receipts["id"]
ada.request(
"POST",
f"/api/v1/matters/{matter['id']}/chapters/order",
json={"expected_version": detail["version"], "chapter_ids": [sibling["id"], sent["id"]]},
)
detail = _detail(ada, matter["id"])
ordered = [item["id"] for item in detail["chapters"] if item["parent_chapter_id"] == root["id"]]
assert ordered == [sibling["id"], sent["id"]]
assert _by_title(detail)["Einzelbelege"]["parent_chapter_id"] == sent["id"]
ada.request(
"POST",
f"/api/v1/matters/{matter['id']}/chapters/order",
json={"expected_version": detail["version"], "chapter_ids": [root["id"], sent["id"]]},
status=422,
)
stale_parent = detail["version"]
ada.request(
"POST",
f"/api/v1/chapters/{receipts['id']}/parent",
json={"expected_version": stale_parent, "parent_chapter_id": root["id"]},
)
detail = _detail(ada, matter["id"])
assert _by_title(detail)["Einzelbelege"]["parent_chapter_id"] == root["id"]
assert all(binding_for(detail, f"Beleg {index + 1}")["chapter_id"] == receipts["id"] for index in range(8))
ada.login()
detail = _detail(ada, matter["id"])
assert _by_title(detail)["Einzelbelege"]["parent_chapter_id"] == root["id"]
assert [item["id"] for item in detail["chapters"] if item["parent_chapter_id"] == root["id"]][:2] == [
sibling["id"],
sent["id"],
]
ada.request(
"POST",
f"/api/v1/chapters/{sent['id']}/parent",
json={"expected_version": stale_parent, "parent_chapter_id": receipts["id"]},
status=409,
)
other = matter_of(ada, "Fremder Vorgang")
foreign = ada.request("POST", f"/api/v1/matters/{other['id']}/chapters", json={"title": "Fremd"}, status=201)
detail = _detail(ada, matter["id"])
ada.request(
"POST",
f"/api/v1/chapters/{sent['id']}/parent",
json={"expected_version": detail["version"], "parent_chapter_id": foreign["id"]},
status=422,
)
ada.request(
"POST",
f"/api/v1/chapters/{sent['id']}/parent",
json={"expected_version": detail["version"], "parent_chapter_id": sent["id"]},
status=422,
)
ada.request(
"POST",
f"/api/v1/chapters/{root['id']}/parent",
json={"expected_version": detail["version"], "parent_chapter_id": sent["id"]},
status=422,
)
detail = _detail(ada, matter["id"])
assert _by_title(detail)["Übermittelte Abrechnungsunterlagen"]["parent_chapter_id"] == root["id"]
dissolved = ada.request(
"POST",
f"/api/v1/chapters/{sent['id']}/delete",
json={"expected_version": detail["version"]},
)
detail = _detail(ada, matter["id"])
assert detail["version"] == dissolved["version"]
assert "Übermittelte Abrechnungsunterlagen" not in _by_title(detail)
assert binding_for(detail, "Anschreiben")["chapter_id"] == root["id"]
assert binding_for(detail, "Abrechnung")["chapter_id"] == root["id"]
assert binding_for(detail, "Rückfrage zur Abrechnung")["chapter_id"] == root["id"]
assert _by_title(detail)["Einzelbelege"]["parent_chapter_id"] == root["id"]
assert binding_for(detail, "Beleg 8")["chapter_id"] == receipts["id"]
def test_reclassifying_one_context_leaves_the_other_and_hidden_rows_alone(client, db):
ada = Actor(client, "ada-zwei@example.test", "Ada Zwei")
ben = Actor(client, "ben-zwei@example.test", "Ben Zwei")
register(db, ada.email, ada.name)
register(db, ben.email, ben.name)
ada.login()
case = case_of(ada, "Wohnung")
left = matter_of(ada, "Vorgang A")
right = matter_of(ada, "Vorgang B")
ada.request("POST", f"/api/v1/matters/{left['id']}/case-links", json={"case_id": case["id"]}, status=201)
chapter_a = ada.request("POST", f"/api/v1/matters/{left['id']}/chapters", json={"title": "Lage A"}, status=201)
other_a = ada.request("POST", f"/api/v1/matters/{left['id']}/chapters", json={"title": "Ziel A"}, status=201)
chapter_b = ada.request("POST", f"/api/v1/matters/{right['id']}/chapters", json={"title": "Lage B"}, status=201)
shared = _note(ada, "Gemeinsame Notiz", left, chapter_a["id"])
ada.request(
"POST",
"/api/v1/bindings",
json={
"element_id": shared["id"],
"source_context": {"kind": "matter", "id": left["id"]},
"target": {"kind": "matter", "id": right["id"]},
"chapter_id": chapter_b["id"],
},
status=201,
)
hidden = _note(ada, "Verborgene Strategie", left, chapter_a["id"])
reply = _note(ada, "Antwort", left, chapter_a["id"])
ada.request(
"POST",
f"/api/v1/elements/{reply['id']}/references",
json={"refers_to_element_id": shared["id"], "context": {"kind": "matter", "id": left["id"]}},
status=204,
)
detail = _detail(ada, left["id"])
ada.request(
"POST",
f"/api/v1/matters/{left['id']}/bindings/chapters",
json={
"expected_version": detail["version"],
"binding_ids": [binding_for(detail, "Gemeinsame Notiz")["id"], binding_for(detail, "Antwort")["id"]],
"chapter_id": other_a["id"],
},
)
left_view = _detail(ada, left["id"])
right_view = _detail(ada, right["id"])
assert binding_for(left_view, "Gemeinsame Notiz")["chapter_id"] == other_a["id"]
assert binding_for(right_view, "Gemeinsame Notiz")["chapter_id"] == chapter_b["id"]
assert binding_for(left_view, "Gemeinsame Notiz")["element"]["excerpt"] == "Gemeinsame Notiz"
assert binding_for(right_view, "Gemeinsame Notiz")["element"]["excerpt"] == "Gemeinsame Notiz"
assert binding_for(left_view, "Antwort")["element"]["refers_to"][0]["title"] == "Gemeinsame Notiz"
grant(ada, case["id"], ben.email, edit=False, share=False)
ada.request(
"PUT",
"/api/v1/exceptions",
json={
"resource_kind": "element",
"resource_id": hidden["id"],
"context": {"kind": "case", "id": case["id"]},
"remove_read": True,
},
)
ben.login()
visible = ben.request("GET", f"/api/v1/matters/{left['id']}?context_kind=case&context_id={case['id']}")
titles = [item["element"]["title"] for item in visible["bindings"]]
assert "Verborgene Strategie" not in titles
assert "Gemeinsame Notiz" in titles
assert "Lage B" not in str(visible)
ben.request("GET", f"/api/v1/matters/{right['id']}", status=404)
def test_child_matter_keeps_its_own_chapters_and_depth_is_guarded(client, db):
ada = Actor(client, "ada-tiefe@example.test", "Ada Tiefe")
register(db, ada.email, ada.name)
ada.login()
parent = matter_of(ada, "Hauptvorgang")
child = ada.request(
"POST",
"/api/v1/matters",
json={"title": "Belegeinsicht", "parent_matter_id": parent["id"]},
status=201,
)
own = ada.request("POST", f"/api/v1/matters/{child['id']}/chapters", json={"title": "Nur hier"}, status=201)
parent_view = _detail(ada, parent["id"])
child_view = _detail(ada, child["id"])
assert parent_view["chapters"] == []
assert child_view["chapters"][0]["id"] == own["id"]
assert child_view["chapters"][0]["parent_chapter_id"] is None
case = case_of(ada, "Akte")
outer = ada.request("POST", f"/api/v1/cases/{case['id']}/chapters", json={"title": "Aktenkapitel"}, status=201)
inner = ada.request(
"POST",
f"/api/v1/cases/{case['id']}/chapters",
json={"title": "Unterlagen", "parent_chapter_id": outer["id"]},
status=201,
)
case_view = ada.request("GET", f"/api/v1/cases/{case['id']}")
assert {item["title"]: item["parent_chapter_id"] for item in case_view["chapters"]} == {
"Aktenkapitel": None,
"Unterlagen": outer["id"],
}
current = None
for level in range(1, 33):
body = {"title": f"Ebene {level}"}
if current:
body["parent_chapter_id"] = current
created = ada.request("POST", f"/api/v1/matters/{parent['id']}/chapters", json=body, status=201)
current = created["id"]
ada.request(
"POST",
f"/api/v1/matters/{parent['id']}/chapters",
json={"title": "Ebene 33", "parent_chapter_id": current},
status=422,
)
stored = _detail(ada, parent["id"])
assert len(stored["chapters"]) == 32
root_id = next(item["id"] for item in stored["chapters"] if item["title"] == "Ebene 1")
with pytest.raises(psycopg.Error):
db.execute(
"UPDATE chapters SET parent_chapter_id = %s WHERE id = %s",
(current, root_id),
)
+177
View File
@@ -600,3 +600,180 @@ def test_export_names_gaps_and_hides_unreadable_counterparts(client, db, monkeyp
)
assert "GeheimtitelXQ" not in json.dumps(missing)
assert "unbekannten oder nicht sichtbaren" in missing["detail"]
def test_nested_chapter_export_keeps_path_and_complete_mail(client, db, monkeypatch):
raw = _eml(
"<nested-mail@example.test>",
"Die Antwort bleibt vollständig.",
[("lage.pdf", PDF_A), ("konto.pdf", PDF_B)],
)
monkeypatch.setattr("app.retrieval.pull_rfc822", lambda *args, **kwargs: raw)
ada = Actor(client, "ada-nested-export@example.test", "Ada Verschachtelt")
register(db, ada.email, ada.name)
ada.login()
matter = ada.request("POST", "/api/v1/matters", json={"title": "Nebenkosten"}, status=201)
root = ada.request(
"POST",
f"/api/v1/matters/{matter['id']}/chapters",
json={"title": "Nebenkostenabrechnung 2025"},
status=201,
)
sent = ada.request(
"POST",
f"/api/v1/matters/{matter['id']}/chapters",
json={"title": "Übermittelte Abrechnungsunterlagen", "parent_chapter_id": root["id"]},
status=201,
)
receipts = ada.request(
"POST",
f"/api/v1/matters/{matter['id']}/chapters",
json={"title": "Einzelbelege", "parent_chapter_id": sent["id"]},
status=201,
)
skipped = ada.request(
"POST",
f"/api/v1/matters/{matter['id']}/chapters",
json={"title": "../Nicht/mitnehmen", "parent_chapter_id": root["id"]},
status=201,
)
ada.request(
"POST",
"/api/v1/notes",
json={
"title": "Anschreiben",
"document": document("Anschreiben bleibt"),
"context": {"kind": "matter", "id": matter["id"]},
"chapter_id": sent["id"],
},
status=201,
)
ada.request(
"POST",
"/api/v1/files",
data={
"title": "Heizkostenbeleg",
"context_kind": "matter",
"context_id": matter["id"],
"chapter_id": receipts["id"],
},
files={"upload": ("heiz.pdf", PDF_A, "application/pdf")},
status=201,
)
ada.request(
"POST",
"/api/v1/files",
data={
"title": "Hausmeisterbeleg",
"context_kind": "matter",
"context_id": matter["id"],
"chapter_id": receipts["id"],
},
files={"upload": ("haus.pdf", PDF_C, "application/pdf")},
status=201,
)
ada.request(
"POST",
"/api/v1/notes",
json={
"title": "Rückfrage",
"document": document("Direkt im Elternkapitel"),
"context": {"kind": "matter", "id": matter["id"]},
"chapter_id": root["id"],
},
status=201,
)
ada.request(
"POST",
"/api/v1/notes",
json={
"title": "Ausgelassen",
"document": document("Geschwister bleibt draussen"),
"context": {"kind": "matter", "id": matter["id"]},
"chapter_id": skipped["id"],
},
status=201,
)
ada.request(
"POST",
"/api/v1/files",
data={
"title": "Gespiegelte Anlage",
"context_kind": "matter",
"context_id": matter["id"],
"chapter_id": skipped["id"],
},
files={"upload": ("konto.pdf", PDF_B, "application/pdf")},
status=201,
)
mailbox = ada.request(
"POST",
"/api/v1/connectors",
json={
"kind": "imap",
"name": "Postfach",
"host": "mail.example.test",
"username": "ada",
"password": "secret-pass",
},
status=201,
)
ada.request(
"POST",
"/api/v1/external-refs",
json={
"title": "Antwort des Vermieters",
"source": "imap",
"external_id": "<nested-mail@example.test>",
"context": {"kind": "matter", "id": matter["id"]},
"chapter_id": root["id"],
"detail": {"connector_id": mailbox["id"], "mailbox": "INBOX", "uid": 4},
},
status=201,
)
tree = ada.request("GET", f"/api/v1/matters/{matter['id']}/export-tree")["tree"]
flat = list(_walk(tree))
parents = _parents(tree)
einzel = next(node for node in flat if node["title"] == "Einzelbelege")
assert einzel["label"] == "Unterkapitel"
assert parents[einzel["id"]]["title"] == "Übermittelte Abrechnungsunterlagen"
leaves = [node["id"] for node in flat if node["kind"] in {"binding", "annotation"} and node["exportable"]]
hidden = {
node["id"]
for node in flat
if node["kind"] in {"binding", "annotation"}
and (
_under(node["id"], "Einzelbelege", parents)
or _under(node["id"], "../Nicht/mitnehmen", parents)
)
}
kept = next(node["id"] for node in flat if node["title"] == "Heizkostenbeleg")
selected = [item for item in leaves if item not in hidden or item == kept]
body = {"context": {"kind": "matter", "id": matter["id"]}, "selected": selected}
review = ada.request("POST", f"/api/v1/matters/{matter['id']}/export/review", json=body)
assert review["ready"] is True
reviewed = [item["title"] for item in review["entries"]]
assert "Heizkostenbeleg" in reviewed
assert "Hausmeisterbeleg" not in reviewed
assert "Ausgelassen" not in reviewed
assert "Anschreiben" in reviewed
assert any("bleibt Bestandteil" in item["message"] for item in review["notices"])
response = _post_zip(ada, matter["id"], body)
assert response.status_code == 200, response.text
names = _archive(response.content).namelist()
heating = next(name for name in names if name.endswith("/heiz.pdf"))
assert heating.startswith(
"01 Nebenkostenabrechnung 2025/02 Übermittelte Abrechnungsunterlagen/01 Einzelbelege/"
)
assert any(
name.startswith("01 Nebenkostenabrechnung 2025/01 ") and "Antwort des Vermieters" in name
for name in names
)
assert not any("Hausmeister" in name or name.endswith("/haus.pdf") for name in names)
assert not any(name.startswith("02 ") and "Nicht" in name for name in names)
assert any("Antwort des Vermieters" in name and name.endswith("/anlagen/lage.pdf") for name in names)
assert any("Antwort des Vermieters" in name and name.endswith("/anlagen/konto.pdf") for name in names)
overview = _archive(response.content).read("inhalt.md").decode("utf-8")
assert overview.index("Anschreiben") < overview.index("Heizkostenbeleg")
assert "Hausmeisterbeleg" not in overview
assert "Ausgelassen" not in overview