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",
}