Jeder Datenraum hat einen Eigentümer, der Verwalter bleibt, den Raum übertragen kann und im Notfall vom Betreiber ersetzt wird. Neue Akten und Vorgänge folgen der Voreinstellung des Raums: Bei "im Raum teilen" lesen Leser sie und bearbeiten Mitglieder und Verwalter; Weitergeben und Löschen bleiben beim Owner, der eine Akte privat stellen oder einzelne Personen ausnehmen kann. Bestehende Akten bleiben privat. Beim ersten weiteren Mitglied zeigt die Oberfläche, was sichtbar wird. Das Löschen von Akte und Vorgang verlangt jetzt den Owner statt nur das Bearbeitungsrecht und schließt damit R-01. Die Rechte der Raumfreigabe gelten nur bei aktivem Raum, aktiver Mitgliedschaft und aktivem Konto. Die lokale Suite läuft mit 128 Tests grün, der Frontend-Build und 19 Node-Tests ebenfalls. Die Oberfläche wurde noch nicht im Browser bedient. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
1692 lines
69 KiB
Python
1692 lines
69 KiB
Python
"""Use-cases for organisation, content and tracking. One transaction is the caller's."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from datetime import date
|
|
from pathlib import Path
|
|
from uuid import UUID, uuid4
|
|
|
|
from psycopg.types.json import Json
|
|
|
|
from app.access.roles import ensure_can_create
|
|
from app.access.policy import (
|
|
Ctx,
|
|
Rights,
|
|
audit,
|
|
block_unsharable_matter_elements,
|
|
bump_version,
|
|
can_change_status,
|
|
case_rights,
|
|
chapter_for,
|
|
deadline_rights,
|
|
display_name,
|
|
element_rights,
|
|
get_case,
|
|
get_deadline,
|
|
get_element,
|
|
get_matter,
|
|
get_task,
|
|
insert_binding,
|
|
matter_rights,
|
|
require_case,
|
|
require_element,
|
|
require_matter,
|
|
task_rights,
|
|
)
|
|
from app.content.documents import clean_document
|
|
from app.core.errors import forbidden, not_found, unprocessable, unsupported
|
|
from app.core.timeutil import utcnow
|
|
from app.media.port import LEGACY_PROFILE, StoredHandle, adapter_for, instance_for_write, publish, removal_for
|
|
from app.media.storage import display_filename, sha256, sniff
|
|
|
|
MAX_CHAPTER_DEPTH = 32
|
|
|
|
|
|
def _ctx(value) -> Ctx | None:
|
|
if value is None:
|
|
return None
|
|
if isinstance(value, Ctx):
|
|
return value
|
|
return Ctx(value.kind, value.id)
|
|
|
|
|
|
def require_container_edit(conn, actor: UUID, target: Ctx, rights_context: Ctx | None) -> None:
|
|
if target.kind == "case":
|
|
if rights_context is not None and (rights_context.kind != "case" or rights_context.id != target.id):
|
|
raise unprocessable("Der Handlungskontext passt nicht zur Akte.")
|
|
require_case(conn, actor, target.id, "edit")
|
|
return
|
|
if rights_context is None or (rights_context.kind == "matter" and rights_context.id == target.id):
|
|
require_matter(conn, actor, target.id, None, "edit")
|
|
return
|
|
require_matter(conn, actor, target.id, rights_context, "edit")
|
|
|
|
|
|
def _placement(context: Ctx, placement: Ctx | None) -> tuple[Ctx, Ctx]:
|
|
target = placement or context
|
|
rights_context = None if placement is None and context.kind == "matter" else context
|
|
if placement is None and context.kind == "matter":
|
|
return target, None
|
|
if placement is not None and placement.kind == "matter" and context.kind == "case":
|
|
return placement, context
|
|
if placement is not None and placement == context:
|
|
return target, None if context.kind == "matter" else context
|
|
return target, context if context.kind == "case" or placement is not None else None
|
|
|
|
|
|
def default_visibility(conn, scope_id: UUID) -> str:
|
|
"""New cases and matters follow the room preset. The personal room is always private."""
|
|
room = conn.execute("SELECT kind, default_visibility FROM data_rooms WHERE id = %s", (scope_id,)).fetchone()
|
|
if room is not None and room["kind"] == "organization" and room["default_visibility"] == "room":
|
|
return "room"
|
|
return "private"
|
|
|
|
|
|
def _shareable(conn, actor: UUID, kind: str, resource_id: UUID) -> dict:
|
|
"""The own case or matter of an organization room. Only the owner changes its room share."""
|
|
if kind == "case":
|
|
resource = get_case(conn, resource_id)
|
|
elif kind == "matter":
|
|
resource = get_matter(conn, resource_id)
|
|
else:
|
|
raise unprocessable("Die Raumfreigabe gilt für Akten und Vorgänge.")
|
|
if resource is None or resource["owner_subject_id"] != actor:
|
|
raise not_found()
|
|
room = conn.execute("SELECT kind FROM data_rooms WHERE id = %s", (resource["home_scope_id"],)).fetchone()
|
|
if room is None or room["kind"] != "organization":
|
|
raise unprocessable("Im persönlichen Datenraum gibt es keine Raumfreigabe.")
|
|
return resource
|
|
|
|
|
|
def set_visibility(conn, actor: UUID, kind: str, resource_id: UUID, value: str) -> dict:
|
|
if value not in {"private", "room"}:
|
|
raise unprocessable("Die Sichtbarkeit ist ungültig.")
|
|
resource = _shareable(conn, actor, kind, resource_id)
|
|
table = "cases" if kind == "case" else "matters"
|
|
if resource["visibility"] != value:
|
|
conn.execute(f"UPDATE {table} SET visibility = %s WHERE id = %s", (value, resource_id))
|
|
audit(conn, actor, resource["home_scope_id"], "visibility_changed", kind, resource_id, detail={"visibility": value})
|
|
return {"id": str(resource_id), "visibility": value}
|
|
|
|
|
|
def set_person_exclusion(conn, actor: UUID, kind: str, resource_id: UUID, subject_id: UUID, excluded: bool) -> None:
|
|
"""Take one room member out of the room share of an own case or matter."""
|
|
resource = _shareable(conn, actor, kind, resource_id)
|
|
if subject_id == actor:
|
|
raise unprocessable("Du kannst dich nicht selbst ausnehmen.")
|
|
member = conn.execute(
|
|
"SELECT 1 FROM room_memberships WHERE room_id = %s AND subject_id = %s AND status = 'active'",
|
|
(resource["home_scope_id"], subject_id),
|
|
).fetchone()
|
|
if member is None:
|
|
raise not_found()
|
|
conn.execute(
|
|
"""
|
|
DELETE FROM access_grants
|
|
WHERE is_exception AND grantee_subject_id = %s AND resource_kind = %s AND resource_id = %s
|
|
AND context_kind IS NULL
|
|
""",
|
|
(subject_id, kind, resource_id),
|
|
)
|
|
if excluded:
|
|
conn.execute(
|
|
"""
|
|
INSERT INTO access_grants (
|
|
grantee_subject_id, resource_kind, resource_id,
|
|
can_read, can_edit, can_share, can_delete, is_exception, created_by
|
|
)
|
|
VALUES (%s, %s, %s, true, true, true, true, true, %s)
|
|
""",
|
|
(subject_id, kind, resource_id, actor),
|
|
)
|
|
audit(
|
|
conn,
|
|
actor,
|
|
resource["home_scope_id"],
|
|
"person_excluded" if excluded else "person_included",
|
|
kind,
|
|
resource_id,
|
|
)
|
|
|
|
|
|
def create_case(conn, actor: UUID, scope_id: UUID, title: str, parent_case_id: UUID | None, rights_mode: str) -> dict:
|
|
ensure_can_create(conn, actor, scope_id)
|
|
title = title.strip()
|
|
if parent_case_id is None:
|
|
row = conn.execute(
|
|
"""
|
|
INSERT INTO cases (
|
|
home_scope_id, owner_subject_id, created_by, title, rights_mode,
|
|
content_order, content_order_dir, visibility
|
|
)
|
|
VALUES (%s, %s, %s, %s, 'explicit', 'date', 'asc', %s)
|
|
RETURNING *
|
|
""",
|
|
(scope_id, actor, actor, title, default_visibility(conn, scope_id)),
|
|
).fetchone()
|
|
else:
|
|
parent, _rights = require_case(conn, actor, parent_case_id, "edit")
|
|
if parent["parent_case_id"] is not None:
|
|
raise unprocessable("Im ersten Schnitt hat eine Unterakte keine weitere Unterakte.")
|
|
if rights_mode not in {"inherit_parent", "explicit"}:
|
|
raise unprocessable("Die Rechteart der Unterakte ist ungültig.")
|
|
row = conn.execute(
|
|
"""
|
|
INSERT INTO cases (
|
|
home_scope_id, owner_subject_id, created_by, title, parent_case_id, rights_mode,
|
|
content_order, content_order_dir, visibility
|
|
)
|
|
VALUES (%s, %s, %s, %s, %s, %s, 'date', 'asc', %s)
|
|
RETURNING *
|
|
""",
|
|
(
|
|
parent["home_scope_id"], actor, actor, title, parent["id"], rights_mode,
|
|
default_visibility(conn, parent["home_scope_id"]),
|
|
),
|
|
).fetchone()
|
|
audit(conn, actor, row["home_scope_id"], "case_created", "case", row["id"])
|
|
return row
|
|
|
|
|
|
def patch_case(conn, actor: UUID, case_id: UUID, expected: int, title: str | None, status: str | None) -> dict:
|
|
case, rights = require_case(conn, actor, case_id, "edit")
|
|
if title is None and status is None:
|
|
raise unprocessable("Es fehlt eine Änderung.")
|
|
if not rights.edit:
|
|
raise forbidden()
|
|
version = bump_version(conn, "cases", case_id, expected)
|
|
if title is not None:
|
|
conn.execute("UPDATE cases SET title = %s WHERE id = %s", (title.strip(), case_id))
|
|
if status is not None:
|
|
conn.execute("UPDATE cases SET record_status = %s WHERE id = %s", (status, case_id))
|
|
updated = get_case(conn, case_id)
|
|
updated["version"] = version
|
|
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,
|
|
kind: str,
|
|
container_id: UUID,
|
|
title: str,
|
|
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:
|
|
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, parent_chapter_id)
|
|
VALUES (%s, %s, %s, %s, %s, %s) RETURNING *
|
|
""",
|
|
(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, parent_chapter_id)
|
|
VALUES (%s, %s, %s, %s, %s, %s) RETURNING *
|
|
""",
|
|
(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
|
|
|
|
|
|
def reorder_chapters(
|
|
conn,
|
|
actor: UUID,
|
|
kind: str,
|
|
container_id: UUID,
|
|
expected: int,
|
|
chapter_ids: list[UUID],
|
|
context: Ctx | None,
|
|
) -> int:
|
|
if kind == "case":
|
|
container, rights = require_case(conn, actor, container_id, "edit")
|
|
table = "cases"
|
|
column = "case_id"
|
|
else:
|
|
container, rights = require_matter(conn, actor, container_id, context, "edit")
|
|
table = "matters"
|
|
column = "matter_id"
|
|
if not rights.edit:
|
|
raise forbidden()
|
|
version = bump_version(conn, table, container_id, expected)
|
|
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 existing for item in chapter_ids):
|
|
raise not_found()
|
|
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.")
|
|
_renumber_chapters(conn, chapter_ids)
|
|
audit(conn, actor, container["home_scope_id"], "chapters_reordered", kind, container_id, context)
|
|
return version
|
|
|
|
|
|
def set_chapter_date(
|
|
conn,
|
|
actor: UUID,
|
|
chapter_id: UUID,
|
|
expected: int,
|
|
document_on: date | None,
|
|
context: Ctx | None,
|
|
) -> int:
|
|
row = conn.execute("SELECT * FROM chapters WHERE id = %s", (chapter_id,)).fetchone()
|
|
if row is None:
|
|
raise not_found()
|
|
if row["case_id"] is not None:
|
|
container, rights = require_case(conn, actor, row["case_id"], "edit")
|
|
table = "cases"
|
|
container_id = row["case_id"]
|
|
kind = "case"
|
|
page = None
|
|
else:
|
|
container, rights = require_matter(conn, actor, row["matter_id"], context, "edit")
|
|
table = "matters"
|
|
container_id = row["matter_id"]
|
|
kind = "matter"
|
|
page = context
|
|
if not rights.edit:
|
|
raise forbidden()
|
|
version = bump_version(conn, table, container_id, expected)
|
|
conn.execute("UPDATE chapters SET document_on = %s WHERE id = %s", (document_on, chapter_id))
|
|
audit(conn, actor, container["home_scope_id"], "chapter_dated", kind, container_id, page)
|
|
return version
|
|
|
|
|
|
def create_matter(conn, actor: UUID, scope_id: UUID, title: str, parent_matter_id: UUID | None, context: Ctx | None) -> dict:
|
|
ensure_can_create(conn, actor, scope_id)
|
|
title = title.strip()
|
|
if parent_matter_id is None:
|
|
row = conn.execute(
|
|
"""
|
|
INSERT INTO matters (
|
|
home_scope_id, owner_subject_id, created_by, title, content_order, content_order_dir, visibility
|
|
)
|
|
VALUES (%s, %s, %s, %s, 'date', 'asc', %s) RETURNING *
|
|
""",
|
|
(scope_id, actor, actor, title, default_visibility(conn, scope_id)),
|
|
).fetchone()
|
|
else:
|
|
parent, _rights = require_matter(conn, actor, parent_matter_id, context, "edit")
|
|
if parent["parent_matter_id"] is not None:
|
|
raise unprocessable("Im ersten Schnitt hat ein Teilvorgang keinen weiteren Teilvorgang.")
|
|
row = conn.execute(
|
|
"""
|
|
INSERT INTO matters (
|
|
home_scope_id, owner_subject_id, created_by, title, parent_matter_id,
|
|
content_order, content_order_dir, visibility
|
|
)
|
|
VALUES (%s, %s, %s, %s, %s, 'date', 'asc', %s) RETURNING *
|
|
""",
|
|
(parent["home_scope_id"], actor, actor, title, parent["id"], default_visibility(conn, parent["home_scope_id"])),
|
|
).fetchone()
|
|
audit(conn, actor, row["home_scope_id"], "matter_created", "matter", row["id"], context)
|
|
return row
|
|
|
|
|
|
def _binding_in_page(conn, binding: dict, context: Ctx) -> bool:
|
|
if binding["context_kind"] == context.kind and binding["context_id"] == context.id:
|
|
return True
|
|
if context.kind != "case" or binding["context_kind"] != "matter":
|
|
return False
|
|
current = binding["context_id"]
|
|
seen: set[UUID] = set()
|
|
while current and current not in seen:
|
|
seen.add(current)
|
|
link = conn.execute(
|
|
"SELECT 1 FROM matter_case_links WHERE matter_id = %s AND case_id = %s",
|
|
(current, context.id),
|
|
).fetchone()
|
|
if link is not None:
|
|
return True
|
|
parent = conn.execute("SELECT parent_matter_id FROM matters WHERE id = %s", (current,)).fetchone()
|
|
current = parent["parent_matter_id"] if parent else None
|
|
return False
|
|
|
|
|
|
def set_communication_direction(conn, actor: UUID, binding_id: UUID, expected: int, direction: str | None, context: Ctx | None) -> dict:
|
|
row = conn.execute("SELECT * FROM bindings WHERE id = %s", (binding_id,)).fetchone()
|
|
if row is None:
|
|
raise not_found()
|
|
page = context or Ctx(row["context_kind"], row["context_id"])
|
|
if context is not None and not _binding_in_page(conn, row, context):
|
|
raise not_found()
|
|
element, rights = require_element(conn, actor, row["element_id"], page, "edit")
|
|
if not rights.edit:
|
|
raise forbidden()
|
|
bump_version(conn, "elements", element["id"], expected)
|
|
store_direction(conn, row["id"], direction, True)
|
|
audit(conn, actor, element["home_scope_id"], "communication_direction", "element", element["id"], page)
|
|
return get_element(conn, element["id"])
|
|
|
|
|
|
def _chapter_container(conn, actor: UUID, chapter_id: UUID, context: Ctx | None):
|
|
chapter = conn.execute("SELECT * FROM chapters WHERE id = %s", (chapter_id,)).fetchone()
|
|
if chapter is None:
|
|
raise not_found()
|
|
if chapter["case_id"]:
|
|
container, _rights = require_case(conn, actor, chapter["case_id"], "edit")
|
|
kind = "case"
|
|
else:
|
|
container, _rights = require_matter(conn, actor, chapter["matter_id"], context, "edit")
|
|
kind = "matter"
|
|
return chapter, container, kind
|
|
|
|
|
|
def rename_chapter(conn, actor: UUID, chapter_id: UUID, expected: int, title: str, context: Ctx | None) -> int:
|
|
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 chapters SET title = %s WHERE id = %s", (title.strip(), chapter["id"]))
|
|
audit(conn, actor, container["home_scope_id"], "chapter_renamed", kind, container["id"], context)
|
|
return version
|
|
|
|
|
|
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)
|
|
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, "read")
|
|
# Deleting the container is the owner's right. Editing, also through the room share, is not enough.
|
|
if case["owner_subject_id"] != actor and not rights.delete:
|
|
raise forbidden()
|
|
children = conn.execute(
|
|
"SELECT id FROM cases WHERE parent_case_id = %s AND deleted_at IS NULL",
|
|
(case_id,),
|
|
).fetchall()
|
|
links = conn.execute("SELECT id FROM matter_case_links WHERE case_id = %s", (case_id,)).fetchall()
|
|
if children or links:
|
|
raise unprocessable("Diese Akte enthält noch Unterakten oder Vorgänge. Verschiebe oder lösche sie zuerst.")
|
|
bump_version(conn, "cases", case_id, expected)
|
|
conn.execute("UPDATE cases SET deleted_at = now(), updated_at = now() WHERE id = %s", (case_id,))
|
|
audit(conn, actor, case["home_scope_id"], "case_deleted", "case", case_id, None)
|
|
|
|
|
|
def delete_matter(conn, actor: UUID, matter_id: UUID, expected: int, context: Ctx | None) -> None:
|
|
matter, rights = require_matter(conn, actor, matter_id, context, "read")
|
|
if matter["owner_subject_id"] != actor and not rights.delete:
|
|
raise forbidden()
|
|
children = conn.execute(
|
|
"SELECT id FROM matters WHERE parent_matter_id = %s AND deleted_at IS NULL",
|
|
(matter_id,),
|
|
).fetchall()
|
|
if children:
|
|
raise unprocessable("Dieser Vorgang enthält noch Teilvorgänge. Verschiebe oder lösche sie zuerst.")
|
|
bump_version(conn, "matters", matter_id, expected)
|
|
conn.execute("UPDATE matters SET deleted_at = now(), updated_at = now() WHERE id = %s", (matter_id,))
|
|
audit(conn, actor, matter["home_scope_id"], "matter_deleted", "matter", matter_id, context)
|
|
|
|
|
|
def _matter_parent_chain(conn, matter_id: UUID) -> set[UUID]:
|
|
seen: set[UUID] = set()
|
|
current = matter_id
|
|
while current and current not in seen:
|
|
seen.add(current)
|
|
row = conn.execute("SELECT parent_matter_id FROM matters WHERE id = %s", (current,)).fetchone()
|
|
current = row["parent_matter_id"] if row else None
|
|
return seen
|
|
|
|
|
|
def move_matter(
|
|
conn,
|
|
actor: UUID,
|
|
matter_id: UUID,
|
|
expected: int,
|
|
context: Ctx | None,
|
|
case_id: UUID | None,
|
|
parent_matter_id: UUID | None,
|
|
clear_parent: bool,
|
|
) -> dict:
|
|
matter, _rights = require_matter(conn, actor, matter_id, context, "edit")
|
|
if case_id is None and parent_matter_id is None and not clear_parent:
|
|
raise unprocessable("Es fehlt ein Ziel.")
|
|
bump_version(conn, "matters", matter_id, expected)
|
|
if clear_parent:
|
|
conn.execute("UPDATE matters SET parent_matter_id = NULL WHERE id = %s", (matter_id,))
|
|
if parent_matter_id is not None:
|
|
if parent_matter_id == matter_id or matter_id in _matter_parent_chain(conn, parent_matter_id):
|
|
raise unprocessable("Ein Vorgang kann nicht in sich selbst oder in einen eigenen Teilvorgang verschoben werden.")
|
|
parent_context = Ctx("case", case_id) if case_id is not None else context
|
|
parent, _parent_rights = require_matter(conn, actor, parent_matter_id, parent_context, "edit")
|
|
if parent["home_scope_id"] != matter["home_scope_id"]:
|
|
raise unprocessable("Der Zielvorgang liegt in einem anderen Datenraum.")
|
|
conn.execute("UPDATE matters SET parent_matter_id = %s WHERE id = %s", (parent_matter_id, matter_id))
|
|
if case_id is not None:
|
|
require_case(conn, actor, case_id, "edit")
|
|
exists = conn.execute(
|
|
"SELECT id FROM matter_case_links WHERE matter_id = %s AND case_id = %s",
|
|
(matter_id, case_id),
|
|
).fetchone()
|
|
if exists is None:
|
|
link_matter_to_case(conn, actor, matter_id, case_id, context)
|
|
if context is not None and context.kind == "case" and context.id != case_id:
|
|
conn.execute(
|
|
"DELETE FROM matter_case_links WHERE matter_id = %s AND case_id = %s",
|
|
(matter_id, context.id),
|
|
)
|
|
audit(conn, actor, matter["home_scope_id"], "matter_moved", "matter", matter_id, context)
|
|
return get_matter(conn, matter_id)
|
|
|
|
|
|
def patch_matter(conn, actor: UUID, matter_id: UUID, expected: int, title: str | None, status: str | None, context: Ctx | None) -> dict:
|
|
if title is None and status is None:
|
|
raise unprocessable("Es fehlt eine Änderung.")
|
|
_matter, _rights = require_matter(conn, actor, matter_id, context, "edit")
|
|
bump_version(conn, "matters", matter_id, expected)
|
|
if title is not None:
|
|
conn.execute("UPDATE matters SET title = %s WHERE id = %s", (title.strip(), matter_id))
|
|
if status is not None:
|
|
conn.execute("UPDATE matters SET record_status = %s WHERE id = %s", (status, matter_id))
|
|
return get_matter(conn, matter_id)
|
|
|
|
|
|
def link_matter_to_case(conn, actor: UUID, matter_id: UUID, case_id: UUID, matter_context: Ctx | None) -> dict:
|
|
matter, matter_right = require_matter(conn, actor, matter_id, matter_context, "share")
|
|
case, _case_right = require_case(conn, actor, case_id, "edit")
|
|
if not matter_right.share:
|
|
raise forbidden()
|
|
try:
|
|
link = conn.execute(
|
|
"""
|
|
INSERT INTO matter_case_links (matter_id, case_id, created_by)
|
|
VALUES (%s, %s, %s) RETURNING *
|
|
""",
|
|
(matter["id"], case["id"], actor),
|
|
).fetchone()
|
|
except Exception as exc:
|
|
if exc.__class__.__name__ == "UniqueViolation":
|
|
raise unprocessable("Der Vorgang ist dieser Akte bereits zugeordnet.") from exc
|
|
raise
|
|
block_unsharable_matter_elements(conn, actor, link["id"], matter)
|
|
audit(conn, actor, case["home_scope_id"], "matter_linked", "matter", matter["id"], Ctx("case", case["id"]))
|
|
return link
|
|
|
|
|
|
def unlink_matter_case(conn, actor: UUID, link_id: UUID) -> None:
|
|
link = conn.execute("SELECT * FROM matter_case_links WHERE id = %s", (link_id,)).fetchone()
|
|
if link is None:
|
|
raise not_found()
|
|
matter_direct = matter_rights(conn, actor, get_matter(conn, link["matter_id"]), None)
|
|
case_right = case_rights(conn, actor, get_case(conn, link["case_id"]))
|
|
if not case_right.read and not matter_direct.read:
|
|
raise not_found()
|
|
if not case_right.edit and not matter_direct.share:
|
|
raise forbidden()
|
|
conn.execute("DELETE FROM matter_case_links WHERE id = %s", (link_id,))
|
|
audit(conn, actor, None, "matter_unlinked", "matter", link["matter_id"], Ctx("case", link["case_id"]))
|
|
|
|
|
|
def create_cross_link(conn, actor: UUID, source_id: UUID, target_id: UUID, source_context: Ctx | None, target_context: Ctx) -> dict:
|
|
if source_id == target_id:
|
|
raise unprocessable("Ein Vorgang kann nicht auf sich selbst verweisen.")
|
|
source, _rights = require_matter(conn, actor, source_id, source_context, "edit")
|
|
target, target_rights = require_matter(conn, actor, target_id, target_context, "read")
|
|
if not target_rights.read:
|
|
raise not_found()
|
|
try:
|
|
row = conn.execute(
|
|
"""
|
|
INSERT INTO matter_cross_links (from_matter_id, to_matter_id, created_by)
|
|
VALUES (%s, %s, %s) RETURNING *
|
|
""",
|
|
(source["id"], target["id"], actor),
|
|
).fetchone()
|
|
except Exception as exc:
|
|
if exc.__class__.__name__ == "UniqueViolation":
|
|
raise unprocessable("Dieser Querverweis besteht bereits.") from exc
|
|
raise
|
|
audit(conn, actor, source["home_scope_id"], "cross_linked", "matter", source["id"], source_context)
|
|
return row
|
|
|
|
|
|
def delete_cross_link(conn, actor: UUID, link_id: UUID, source_context: Ctx | None) -> None:
|
|
link = conn.execute("SELECT * FROM matter_cross_links WHERE id = %s", (link_id,)).fetchone()
|
|
if link is None:
|
|
raise not_found()
|
|
require_matter(conn, actor, link["from_matter_id"], source_context, "edit")
|
|
conn.execute("DELETE FROM matter_cross_links WHERE id = %s", (link_id,))
|
|
|
|
|
|
def _actor_rights_for(conn, actor: UUID, kind: str, resource_id: UUID, context: Ctx | None) -> Rights:
|
|
if kind == "case":
|
|
_row, rights = require_case(conn, actor, resource_id, "read")
|
|
return rights
|
|
if kind == "matter":
|
|
_row, rights = require_matter(conn, actor, resource_id, context, "read")
|
|
return rights
|
|
if kind == "element":
|
|
_row, rights = require_element(conn, actor, resource_id, context, "read")
|
|
return rights
|
|
if kind == "task":
|
|
task = get_task(conn, resource_id)
|
|
if task is None:
|
|
raise not_found()
|
|
rights = task_rights(conn, actor, task, context)
|
|
if not rights.read:
|
|
raise not_found()
|
|
return rights
|
|
deadline = get_deadline(conn, resource_id)
|
|
if deadline is None:
|
|
raise not_found()
|
|
rights = deadline_rights(conn, actor, deadline, context)
|
|
if not rights.read:
|
|
raise not_found()
|
|
return rights
|
|
|
|
|
|
def _is_reader_of_home(conn, account_id: UUID, home_scope_id: UUID) -> bool:
|
|
from app.access.roles import room_role
|
|
|
|
return room_role(conn, account_id, home_scope_id) == "reader"
|
|
|
|
|
|
def grant_access(
|
|
conn,
|
|
actor: UUID,
|
|
kind: str,
|
|
resource_id: UUID,
|
|
grantee_id: UUID,
|
|
can_read: bool,
|
|
can_edit: bool,
|
|
can_share: bool,
|
|
context: Ctx | None,
|
|
use_owner_sources: bool = False,
|
|
) -> dict:
|
|
if grantee_id == actor:
|
|
raise unprocessable("Die eigene Berechtigung wird nicht als Freigabe gespeichert.")
|
|
if not can_read:
|
|
raise unprocessable("Eine Freigabe braucht mindestens Lesen.")
|
|
if kind == "case":
|
|
resource = get_case(conn, resource_id)
|
|
rights = case_rights(conn, actor, resource) if resource else Rights()
|
|
elif kind == "matter":
|
|
resource = get_matter(conn, resource_id)
|
|
rights = matter_rights(conn, actor, resource, context) if resource else Rights()
|
|
else:
|
|
raise unprocessable("Freigaben werden an der Akte oder am Vorgang erteilt.")
|
|
if resource is None or not rights.read:
|
|
raise not_found()
|
|
owner = resource["owner_subject_id"] == actor
|
|
if not owner and not rights.share:
|
|
raise forbidden()
|
|
if can_edit and not (owner or rights.edit):
|
|
raise forbidden()
|
|
if can_share and not (owner or rights.share):
|
|
raise forbidden()
|
|
account = conn.execute(
|
|
"SELECT id FROM auth_accounts WHERE id = %s AND status = 'active'",
|
|
(grantee_id,),
|
|
).fetchone()
|
|
if account is None:
|
|
raise not_found()
|
|
if (can_edit or can_share) and _is_reader_of_home(conn, grantee_id, resource["home_scope_id"]):
|
|
raise unprocessable("Diese Person ist in dem Datenraum der Akte nur Leser und kann nicht bearbeiten oder freigeben.")
|
|
existing = conn.execute(
|
|
"""
|
|
SELECT id, use_owner_sources FROM access_grants
|
|
WHERE NOT is_exception AND grantee_subject_id = %s
|
|
AND resource_kind = %s AND resource_id = %s AND context_kind IS NULL
|
|
""",
|
|
(grantee_id, kind, resource_id),
|
|
).fetchone()
|
|
if owner:
|
|
source_access = bool(use_owner_sources)
|
|
elif existing is None:
|
|
source_access = False
|
|
else:
|
|
source_access = bool(existing["use_owner_sources"])
|
|
if existing is None:
|
|
row = conn.execute(
|
|
"""
|
|
INSERT INTO access_grants (
|
|
grantee_subject_id, resource_kind, resource_id,
|
|
can_read, can_edit, can_share, can_delete, is_exception, created_by,
|
|
use_owner_sources
|
|
)
|
|
VALUES (%s, %s, %s, %s, %s, %s, false, false, %s, %s)
|
|
RETURNING *
|
|
""",
|
|
(grantee_id, kind, resource_id, can_read, can_edit, can_share, actor, source_access),
|
|
).fetchone()
|
|
else:
|
|
row = conn.execute(
|
|
"""
|
|
UPDATE access_grants
|
|
SET can_read = %s, can_edit = %s, can_share = %s, use_owner_sources = %s
|
|
WHERE id = %s
|
|
RETURNING *
|
|
""",
|
|
(can_read, can_edit, can_share, source_access, existing["id"]),
|
|
).fetchone()
|
|
audit(conn, actor, resource["home_scope_id"], "grant_created", kind, resource_id, context)
|
|
return row
|
|
|
|
|
|
def revoke_grant(conn, actor: UUID, grant_id: UUID) -> None:
|
|
grant = conn.execute("SELECT * FROM access_grants WHERE id = %s AND NOT is_exception", (grant_id,)).fetchone()
|
|
if grant is None:
|
|
raise not_found()
|
|
kind = grant["resource_kind"]
|
|
if kind == "case":
|
|
resource = get_case(conn, grant["resource_id"])
|
|
rights = case_rights(conn, actor, resource) if resource else Rights()
|
|
elif kind == "matter":
|
|
resource = get_matter(conn, grant["resource_id"])
|
|
rights = matter_rights(conn, actor, resource, None) if resource else Rights()
|
|
elif kind == "task":
|
|
resource = get_task(conn, grant["resource_id"])
|
|
rights = task_rights(conn, actor, resource, None) if resource else Rights()
|
|
elif kind == "deadline":
|
|
resource = get_deadline(conn, grant["resource_id"])
|
|
rights = deadline_rights(conn, actor, resource, None) if resource else Rights()
|
|
else:
|
|
resource = get_element(conn, grant["resource_id"])
|
|
rights = element_rights(conn, actor, resource, None) if resource else Rights()
|
|
if resource is None or not rights.read:
|
|
raise not_found()
|
|
if resource["owner_subject_id"] != actor and not rights.share:
|
|
raise forbidden()
|
|
conn.execute("DELETE FROM access_grants WHERE id = %s", (grant_id,))
|
|
audit(conn, actor, resource["home_scope_id"], "grant_revoked", kind, grant["resource_id"])
|
|
|
|
|
|
def set_exception(conn, actor: UUID, kind: str, resource_id: UUID, context: Ctx, remove_read: bool, remove_edit: bool, remove_share: bool) -> None:
|
|
if kind == "element":
|
|
resource = get_element(conn, resource_id)
|
|
elif kind == "matter":
|
|
resource = get_matter(conn, resource_id)
|
|
elif kind == "task":
|
|
resource = get_task(conn, resource_id)
|
|
else:
|
|
resource = get_deadline(conn, resource_id)
|
|
if resource is None:
|
|
raise not_found()
|
|
if resource["owner_subject_id"] != actor:
|
|
raise forbidden()
|
|
conn.execute(
|
|
"""
|
|
DELETE FROM access_grants
|
|
WHERE is_exception AND grantee_subject_id IS NULL
|
|
AND resource_kind = %s AND resource_id = %s
|
|
AND context_kind = %s AND context_id = %s
|
|
""",
|
|
(kind, resource_id, context.kind, context.id),
|
|
)
|
|
if remove_read or remove_edit or remove_share:
|
|
conn.execute(
|
|
"""
|
|
INSERT INTO access_grants (
|
|
grantee_subject_id, resource_kind, resource_id, context_kind, context_id,
|
|
can_read, can_edit, can_share, can_delete, is_exception, created_by
|
|
)
|
|
VALUES (NULL, %s, %s, %s, %s, %s, %s, %s, false, true, %s)
|
|
""",
|
|
(kind, resource_id, context.kind, context.id, remove_read, remove_edit, remove_share, actor),
|
|
)
|
|
|
|
|
|
def _new_element(conn, actor: UUID, scope_id: UUID, title: str, kind: str) -> dict:
|
|
return conn.execute(
|
|
"""
|
|
INSERT INTO elements (home_scope_id, owner_subject_id, created_by, title, kind)
|
|
VALUES (%s, %s, %s, %s, %s) RETURNING *
|
|
""",
|
|
(scope_id, actor, actor, title.strip(), kind),
|
|
).fetchone()
|
|
|
|
|
|
def record_dates(conn, actor: UUID, scope_id: UUID, element_id: UUID, context: Ctx, document_on: date | None, sent_on: date | None, received_on: date | None) -> None:
|
|
conn.execute(
|
|
"""
|
|
INSERT INTO correspondence_dates (element_id, document_on, sent_on, received_on)
|
|
VALUES (%s, %s, %s, %s)
|
|
ON CONFLICT (element_id) DO UPDATE
|
|
SET document_on = EXCLUDED.document_on,
|
|
sent_on = EXCLUDED.sent_on,
|
|
received_on = EXCLUDED.received_on
|
|
""",
|
|
(element_id, document_on, sent_on, received_on),
|
|
)
|
|
if document_on is not None:
|
|
audit(conn, actor, scope_id, "correspondence_document", "element", element_id, context, document_on)
|
|
if sent_on is not None:
|
|
audit(conn, actor, scope_id, "correspondence_sent", "element", element_id, context, sent_on)
|
|
if received_on is not None:
|
|
audit(conn, actor, scope_id, "correspondence_received", "element", element_id, context, received_on)
|
|
audit(conn, actor, scope_id, "correspondence_recorded", "element", element_id, context)
|
|
|
|
|
|
def chosen_direction(value: str | None) -> str | None:
|
|
return value if value in ("in", "out", "local") else None
|
|
|
|
|
|
def store_direction(conn, binding_id: UUID, direction: str | None, explicit: bool) -> None:
|
|
if not explicit:
|
|
return
|
|
if direction not in (None, "in", "out", "local"):
|
|
raise unprocessable("Die Richtung ist ungültig.")
|
|
conn.execute(
|
|
"""
|
|
UPDATE bindings
|
|
SET communication_direction = %s, direction_explicit = true
|
|
WHERE id = %s
|
|
""",
|
|
(direction, binding_id),
|
|
)
|
|
|
|
|
|
def create_note(
|
|
conn,
|
|
actor: UUID,
|
|
scope_id: UUID,
|
|
title: str,
|
|
document: dict,
|
|
context: Ctx,
|
|
placement: Ctx | None,
|
|
chapter_id: UUID | None,
|
|
document_on: date | None = None,
|
|
sent_on: date | None = None,
|
|
received_on: date | None = None,
|
|
communication_direction: str | None = None,
|
|
) -> dict:
|
|
ensure_can_create(conn, actor, scope_id)
|
|
document = clean_document(document)
|
|
target, rights_context = _placement(context, placement)
|
|
require_container_edit(conn, actor, target, rights_context)
|
|
element = _new_element(conn, actor, scope_id, title, "note")
|
|
conn.execute(
|
|
"INSERT INTO note_bodies (element_id, document_json, version) VALUES (%s, %s, 1)",
|
|
(element["id"], Json(document)),
|
|
)
|
|
binding = insert_binding(conn, element["id"], target.kind, target.id, chapter_id, actor)
|
|
chosen = chosen_direction(communication_direction)
|
|
store_direction(conn, binding["id"], chosen, chosen is not None)
|
|
audit(conn, actor, scope_id, "note_created", "element", element["id"], rights_context or target)
|
|
if document_on is not None or sent_on is not None or received_on is not None:
|
|
record_dates(conn, actor, scope_id, element["id"], rights_context or target, document_on, sent_on, received_on)
|
|
return {"element": element, "binding": binding, "document": document}
|
|
|
|
|
|
def update_note(conn, actor: UUID, element_id: UUID, expected: int, document: dict, context: Ctx | None) -> dict:
|
|
document = clean_document(document)
|
|
element, rights = require_element(conn, actor, element_id, context, "edit")
|
|
if element["kind"] != "note":
|
|
raise unsupported("Diese Fassung lässt sich nicht als Notiz bearbeiten.")
|
|
if not rights.edit:
|
|
raise forbidden()
|
|
version = bump_version(conn, "elements", element_id, expected)
|
|
conn.execute(
|
|
"UPDATE note_bodies SET document_json = %s, version = %s, updated_at = now() WHERE element_id = %s",
|
|
(Json(document), version, element_id),
|
|
)
|
|
audit(conn, actor, element["home_scope_id"], "note_updated", "element", element_id, context)
|
|
element = get_element(conn, element_id)
|
|
return {"element": element, "document": document}
|
|
|
|
|
|
def bind_element(conn, actor: UUID, element_id: UUID, source: Ctx, target: Ctx, target_context: Ctx | None, chapter_id: UUID | None) -> dict:
|
|
_element, source_rights = require_element(conn, actor, element_id, source, "share")
|
|
if not source_rights.share:
|
|
raise forbidden()
|
|
require_container_edit(conn, actor, target, target_context)
|
|
binding = insert_binding(conn, element_id, target.kind, target.id, chapter_id, actor)
|
|
audit(conn, actor, None, "binding_created", "element", element_id, target_context or target)
|
|
return binding
|
|
|
|
|
|
def detach_binding(conn, actor: UUID, binding_id: UUID, context: Ctx | None) -> None:
|
|
binding = conn.execute("SELECT * FROM bindings WHERE id = %s", (binding_id,)).fetchone()
|
|
if binding is None:
|
|
raise not_found()
|
|
element = get_element(conn, binding["element_id"])
|
|
if element is None:
|
|
raise not_found()
|
|
action_context = context or Ctx(binding["context_kind"], binding["context_id"])
|
|
_element, rights = require_element(conn, actor, element["id"], action_context, "edit")
|
|
if binding["context_kind"] != action_context.kind and not (
|
|
action_context.kind == "case" and binding["context_kind"] == "matter"
|
|
):
|
|
raise not_found()
|
|
if not rights.edit:
|
|
raise forbidden()
|
|
conn.execute("DELETE FROM bindings WHERE id = %s", (binding_id,))
|
|
audit(conn, actor, element["home_scope_id"], "binding_removed", "element", element["id"], action_context)
|
|
|
|
|
|
def add_annotation(conn, actor: UUID, binding_id: UUID, body: str, context: Ctx | None) -> dict:
|
|
binding = conn.execute("SELECT * FROM bindings WHERE id = %s", (binding_id,)).fetchone()
|
|
if binding is None:
|
|
raise not_found()
|
|
element = get_element(conn, binding["element_id"])
|
|
if element is None:
|
|
raise not_found()
|
|
action_context = context or Ctx(binding["context_kind"], binding["context_id"])
|
|
_element, rights = require_element(conn, actor, element["id"], action_context, "edit")
|
|
if not rights.edit:
|
|
raise forbidden()
|
|
if binding["context_id"] != action_context.id and not (
|
|
action_context.kind == "case" and binding["context_kind"] == "matter"
|
|
):
|
|
raise not_found()
|
|
row = conn.execute(
|
|
"""
|
|
INSERT INTO context_annotations (binding_id, body, author_subject_id)
|
|
VALUES (%s, %s, %s) RETURNING *
|
|
""",
|
|
(binding_id, body.strip(), actor),
|
|
).fetchone()
|
|
audit(conn, actor, element["home_scope_id"], "annotation_created", "element", element["id"], action_context)
|
|
return row
|
|
|
|
|
|
def create_external(conn, actor: UUID, scope_id: UUID, title: str, source: str, external_id: str, context: Ctx, placement: Ctx | None, chapter_id: UUID | None, document_on, sent_on, received_on, detail: dict | None = None, communication_direction: str | None = None) -> dict:
|
|
ensure_can_create(conn, actor, scope_id)
|
|
from app.sourceregistry import accepts_reference
|
|
|
|
if not accepts_reference(source):
|
|
raise unprocessable("Diese Quelle ist nicht registriert.")
|
|
target, rights_context = _placement(context, placement)
|
|
require_container_edit(conn, actor, target, rights_context)
|
|
element = _new_element(conn, actor, scope_id, title, "external_ref")
|
|
conn.execute(
|
|
"INSERT INTO external_references (element_id, source, external_id, detail) VALUES (%s, %s, %s, %s)",
|
|
(element["id"], source, external_id.strip()[:200], Json(detail or {})),
|
|
)
|
|
from app.sourcebind import attach_new_reference
|
|
|
|
attach_new_reference(conn, element["id"])
|
|
binding = insert_binding(conn, element["id"], target.kind, target.id, chapter_id, actor)
|
|
adopted = (detail or {}).get("direction")
|
|
chosen = chosen_direction(communication_direction) or (adopted if adopted in ("in", "out") else None)
|
|
store_direction(conn, binding["id"], chosen, chosen is not None)
|
|
record_dates(conn, actor, scope_id, element["id"], rights_context or target, document_on, sent_on, received_on)
|
|
audit(conn, actor, scope_id, "external_ref_added", "element", element["id"], rights_context or target)
|
|
return element | {"binding_id": binding["id"]}
|
|
|
|
|
|
def create_file(conn, actor: UUID, scope_id: UUID, title: str, filename: str, data: bytes, context: Ctx, placement: Ctx | None, chapter_id: UUID | None, document_on, sent_on, received_on, media_root: str, max_bytes: int, rollback_files: list[Path], communication_direction: str | None = None) -> dict:
|
|
ensure_can_create(conn, actor, scope_id)
|
|
if not data or len(data) > max_bytes:
|
|
raise unprocessable("Die Datei ist leer oder zu groß.")
|
|
content_type = sniff(data)
|
|
target, rights_context = _placement(context, placement)
|
|
require_container_edit(conn, actor, target, rights_context)
|
|
asset_id = uuid4()
|
|
content_revision = str(uuid4())
|
|
instance = instance_for_write(conn, media_root)
|
|
object_key = str(asset_id)
|
|
adapter = adapter_for(instance)
|
|
from app.sourceaccess import release_for_external
|
|
|
|
release_for_external(conn)
|
|
publish(adapter, object_key, data)
|
|
rollback_files.append(StoredHandle(adapter, object_key))
|
|
require_container_edit(conn, actor, target, rights_context)
|
|
element = _new_element(conn, actor, scope_id, title, "file")
|
|
digest = sha256(data)
|
|
conn.execute(
|
|
"""
|
|
INSERT INTO media_assets (
|
|
id, element_id, owner_subject_id, home_scope_id, original_filename,
|
|
content_type, byte_size, sha256, status, storage_instance_id,
|
|
storage_generation, object_key, content_revision, protection_profile,
|
|
key_responsibility
|
|
)
|
|
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, 'active', %s, %s, %s, %s, %s, 'none')
|
|
""",
|
|
(
|
|
asset_id,
|
|
element["id"],
|
|
actor,
|
|
scope_id,
|
|
display_filename(filename),
|
|
content_type,
|
|
len(data),
|
|
digest,
|
|
instance["id"],
|
|
instance["generation"],
|
|
object_key,
|
|
content_revision,
|
|
LEGACY_PROFILE,
|
|
),
|
|
)
|
|
conn.execute(
|
|
"""
|
|
INSERT INTO media_operations (element_id, asset_id, phase, status)
|
|
VALUES (%s, %s, 'active', 'committed')
|
|
""",
|
|
(element["id"], asset_id),
|
|
)
|
|
binding = insert_binding(conn, element["id"], target.kind, target.id, chapter_id, actor)
|
|
chosen = chosen_direction(communication_direction)
|
|
store_direction(conn, binding["id"], chosen, chosen is not None)
|
|
record_dates(conn, actor, scope_id, element["id"], rights_context or target, document_on, sent_on, received_on)
|
|
audit(conn, actor, scope_id, "file_added", "element", element["id"], rights_context or target)
|
|
return element | {"binding_id": binding["id"], "asset_id": asset_id}
|
|
|
|
|
|
def delete_element(conn, actor: UUID, element_id: UUID, expected: int, media_root: str, delete_after: list[Path]) -> None:
|
|
element = get_element(conn, element_id)
|
|
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(
|
|
"UPDATE elements SET deleted_at = now(), updated_at = now() WHERE id = %s",
|
|
(element_id,),
|
|
)
|
|
if asset is not None and asset["status"] == "active":
|
|
conn.execute("UPDATE media_assets SET status = 'purging' WHERE id = %s", (asset["id"],))
|
|
delete_after.append(
|
|
removal_for(
|
|
conn,
|
|
asset["storage_instance_id"],
|
|
asset["storage_generation"],
|
|
asset["object_key"] or str(asset["id"]),
|
|
media_root,
|
|
)
|
|
)
|
|
conn.execute("UPDATE media_assets SET status = 'purged' WHERE id = %s", (asset["id"],))
|
|
audit(conn, actor, element["home_scope_id"], "element_deleted", "element", element_id)
|
|
|
|
|
|
def create_task(conn, actor: UUID, scope_id: UUID, title: str, due_on: date | None, matter_id: UUID | None, context: Ctx | None) -> dict:
|
|
ensure_can_create(conn, actor, scope_id)
|
|
if matter_id is not None:
|
|
require_matter(conn, actor, matter_id, context, "edit")
|
|
row = conn.execute(
|
|
"""
|
|
INSERT INTO tasks (
|
|
home_scope_id, owner_subject_id, created_by, title, matter_id, due_on
|
|
)
|
|
VALUES (%s, %s, %s, %s, %s, %s) RETURNING *
|
|
""",
|
|
(scope_id, actor, actor, title.strip(), matter_id, due_on),
|
|
).fetchone()
|
|
audit(conn, actor, scope_id, "task_created", "task", row["id"], context)
|
|
return row
|
|
|
|
|
|
def patch_task(conn, actor: UUID, task_id: UUID, expected: int, title: str | None, due_on: date | None, clear_due: bool, status: str | None, context: Ctx | None) -> dict:
|
|
task = get_task(conn, task_id)
|
|
if task is None:
|
|
raise not_found()
|
|
rights = task_rights(conn, actor, task, context)
|
|
if not rights.read:
|
|
raise not_found()
|
|
structural = title is not None or due_on is not None or clear_due
|
|
if structural and not rights.edit:
|
|
raise forbidden()
|
|
if status is not None and not can_change_status(actor, task, rights):
|
|
raise forbidden()
|
|
if title is None and due_on is None and not clear_due and status is None:
|
|
raise unprocessable("Es fehlt eine Änderung.")
|
|
bump_version(conn, "tasks", task_id, expected)
|
|
if title is not None:
|
|
conn.execute("UPDATE tasks SET title = %s WHERE id = %s", (title.strip(), task_id))
|
|
if clear_due:
|
|
conn.execute("UPDATE tasks SET due_on = NULL WHERE id = %s", (task_id,))
|
|
elif due_on is not None:
|
|
conn.execute("UPDATE tasks SET due_on = %s WHERE id = %s", (due_on, task_id))
|
|
if status is not None:
|
|
conn.execute("UPDATE tasks SET task_status = %s WHERE id = %s", (status, task_id))
|
|
audit(
|
|
conn,
|
|
actor,
|
|
task["home_scope_id"],
|
|
"task_done" if status == "done" else "task_reopened",
|
|
"task",
|
|
task_id,
|
|
context,
|
|
)
|
|
return get_task(conn, task_id)
|
|
|
|
|
|
def assign_task(conn, actor: UUID, task_id: UUID, assignee_id: UUID | None, context: Ctx | None) -> dict:
|
|
task = get_task(conn, task_id)
|
|
if task is None:
|
|
raise not_found()
|
|
rights = task_rights(conn, actor, task, context)
|
|
if not rights.read:
|
|
raise not_found()
|
|
if task["owner_subject_id"] != actor and not rights.share:
|
|
raise forbidden()
|
|
if assignee_id is not None:
|
|
account = conn.execute(
|
|
"SELECT id FROM auth_accounts WHERE id = %s AND status = 'active'",
|
|
(assignee_id,),
|
|
).fetchone()
|
|
if account is None:
|
|
raise not_found()
|
|
existing = conn.execute(
|
|
"""
|
|
SELECT * FROM access_grants
|
|
WHERE NOT is_exception AND grantee_subject_id = %s
|
|
AND resource_kind = 'task' AND resource_id = %s AND context_kind IS NULL
|
|
""",
|
|
(assignee_id, task_id),
|
|
).fetchone()
|
|
if existing is None:
|
|
conn.execute(
|
|
"""
|
|
INSERT INTO access_grants (
|
|
grantee_subject_id, resource_kind, resource_id,
|
|
can_read, can_edit, can_share, can_delete, is_exception, created_by
|
|
)
|
|
VALUES (%s, 'task', %s, true, false, false, false, false, %s)
|
|
""",
|
|
(assignee_id, task_id, actor),
|
|
)
|
|
elif not existing["can_read"]:
|
|
conn.execute("UPDATE access_grants SET can_read = true WHERE id = %s", (existing["id"],))
|
|
elif task["assignee_subject_id"] is not None:
|
|
conn.execute(
|
|
"""
|
|
DELETE FROM access_grants
|
|
WHERE NOT is_exception AND grantee_subject_id = %s
|
|
AND resource_kind = 'task' AND resource_id = %s
|
|
AND context_kind IS NULL AND can_read AND NOT can_edit AND NOT can_share AND NOT can_delete
|
|
""",
|
|
(task["assignee_subject_id"], task_id),
|
|
)
|
|
conn.execute(
|
|
"UPDATE tasks SET assignee_subject_id = %s, updated_at = now() WHERE id = %s",
|
|
(assignee_id, task_id),
|
|
)
|
|
return get_task(conn, task_id)
|
|
|
|
|
|
def create_deadline(conn, actor: UUID, scope_id: UUID, title: str, due_on: date, matter_id: UUID | None, context: Ctx | None) -> dict:
|
|
ensure_can_create(conn, actor, scope_id)
|
|
if matter_id is not None:
|
|
require_matter(conn, actor, matter_id, context, "edit")
|
|
row = conn.execute(
|
|
"""
|
|
INSERT INTO deadlines (
|
|
home_scope_id, owner_subject_id, created_by, title, matter_id, due_on
|
|
)
|
|
VALUES (%s, %s, %s, %s, %s, %s) RETURNING *
|
|
""",
|
|
(scope_id, actor, actor, title.strip(), matter_id, due_on),
|
|
).fetchone()
|
|
audit(conn, actor, scope_id, "deadline_created", "deadline", row["id"], context)
|
|
return row
|
|
|
|
|
|
def patch_deadline(conn, actor: UUID, deadline_id: UUID, expected: int, title: str | None, due_on: date | None, context: Ctx | None) -> dict:
|
|
deadline = get_deadline(conn, deadline_id)
|
|
if deadline is None:
|
|
raise not_found()
|
|
rights = deadline_rights(conn, actor, deadline, context)
|
|
if not rights.read:
|
|
raise not_found()
|
|
if not rights.edit:
|
|
raise forbidden()
|
|
if title is None and due_on is None:
|
|
raise unprocessable("Es fehlt eine Änderung.")
|
|
bump_version(conn, "deadlines", deadline_id, expected)
|
|
if title is not None:
|
|
conn.execute("UPDATE deadlines SET title = %s WHERE id = %s", (title.strip(), deadline_id))
|
|
if due_on is not None:
|
|
conn.execute("UPDATE deadlines SET due_on = %s WHERE id = %s", (due_on, deadline_id))
|
|
return get_deadline(conn, deadline_id)
|
|
|
|
|
|
def fulfill_deadline(conn, actor: UUID, deadline_id: UUID, expected: int, context: Ctx | None) -> dict:
|
|
deadline = get_deadline(conn, deadline_id)
|
|
if deadline is None:
|
|
raise not_found()
|
|
rights = deadline_rights(conn, actor, deadline, context)
|
|
if not rights.read:
|
|
raise not_found()
|
|
if not can_change_status(actor, deadline, rights):
|
|
raise forbidden()
|
|
bump_version(conn, "deadlines", deadline_id, expected)
|
|
conn.execute(
|
|
"""
|
|
UPDATE deadlines
|
|
SET deadline_status = 'fulfilled', fulfilled_at = %s, updated_at = now()
|
|
WHERE id = %s
|
|
""",
|
|
(utcnow(), deadline_id),
|
|
)
|
|
audit(conn, actor, deadline["home_scope_id"], "deadline_fulfilled", "deadline", deadline_id, context)
|
|
return get_deadline(conn, deadline_id)
|
|
|
|
|
|
def link_task_deadline(conn, actor: UUID, task_id: UUID, deadline_id: UUID, context: Ctx | None) -> None:
|
|
task = get_task(conn, task_id)
|
|
deadline = get_deadline(conn, deadline_id)
|
|
if task is None or deadline is None:
|
|
raise not_found()
|
|
task_right = task_rights(conn, actor, task, context)
|
|
deadline_right = deadline_rights(conn, actor, deadline, context)
|
|
if not task_right.read or not deadline_right.read:
|
|
raise not_found()
|
|
if not task_right.edit:
|
|
raise forbidden()
|
|
conn.execute(
|
|
"""
|
|
INSERT INTO task_deadline_links (task_id, deadline_id, created_by)
|
|
VALUES (%s, %s, %s)
|
|
ON CONFLICT DO NOTHING
|
|
""",
|
|
(task_id, deadline_id, actor),
|
|
)
|
|
|
|
|
|
def set_task_elements(conn, actor: UUID, task_id: UUID, element_ids: list[UUID], context: Ctx | None) -> None:
|
|
task = get_task(conn, task_id)
|
|
if task is None:
|
|
raise not_found()
|
|
rights = task_rights(conn, actor, task, context)
|
|
if not rights.read:
|
|
raise not_found()
|
|
if not rights.edit:
|
|
raise forbidden()
|
|
unique: list[UUID] = []
|
|
for element_id in element_ids:
|
|
if element_id in unique:
|
|
continue
|
|
element = get_element(conn, element_id)
|
|
if element is None:
|
|
raise not_found()
|
|
visible = element_rights(conn, actor, element, context)
|
|
if not visible.read:
|
|
raise not_found()
|
|
unique.append(element_id)
|
|
conn.execute("DELETE FROM task_element_links WHERE task_id = %s", (task_id,))
|
|
for element_id in unique:
|
|
conn.execute(
|
|
"""
|
|
INSERT INTO task_element_links (task_id, element_id, created_by)
|
|
VALUES (%s, %s, %s)
|
|
""",
|
|
(task_id, element_id, actor),
|
|
)
|
|
|
|
|
|
def _dependency_chain(conn, start: UUID) -> set[UUID]:
|
|
seen: set[UUID] = set()
|
|
stack = [start]
|
|
while stack:
|
|
current = stack.pop()
|
|
if current in seen:
|
|
continue
|
|
seen.add(current)
|
|
rows = conn.execute(
|
|
"SELECT depends_on_task_id FROM task_dependencies WHERE task_id = %s",
|
|
(current,),
|
|
).fetchall()
|
|
stack.extend(row["depends_on_task_id"] for row in rows)
|
|
return seen
|
|
|
|
|
|
def link_task_dependency(conn, actor: UUID, task_id: UUID, depends_on_task_id: UUID, context: Ctx | None) -> None:
|
|
if task_id == depends_on_task_id:
|
|
raise unprocessable("Eine Aufgabe kann nicht von sich selbst abhängen.")
|
|
task = get_task(conn, task_id)
|
|
earlier = get_task(conn, depends_on_task_id)
|
|
if task is None or earlier is None:
|
|
raise not_found()
|
|
rights = task_rights(conn, actor, task, context)
|
|
earlier_rights = task_rights(conn, actor, earlier, context)
|
|
if not rights.read or not earlier_rights.read:
|
|
raise not_found()
|
|
if not rights.edit:
|
|
raise forbidden()
|
|
if task_id in _dependency_chain(conn, depends_on_task_id):
|
|
raise unprocessable("Diese Abhängigkeit würde einen Kreis bilden.")
|
|
conn.execute(
|
|
"""
|
|
INSERT INTO task_dependencies (task_id, depends_on_task_id, created_by)
|
|
VALUES (%s, %s, %s)
|
|
ON CONFLICT DO NOTHING
|
|
""",
|
|
(task_id, depends_on_task_id, actor),
|
|
)
|
|
|
|
|
|
def unlink_task_dependency(conn, actor: UUID, task_id: UUID, depends_on_task_id: UUID, context: Ctx | None) -> None:
|
|
task = get_task(conn, task_id)
|
|
if task is None:
|
|
raise not_found()
|
|
rights = task_rights(conn, actor, task, context)
|
|
if not rights.read:
|
|
raise not_found()
|
|
if not rights.edit:
|
|
raise forbidden()
|
|
conn.execute(
|
|
"DELETE FROM task_dependencies WHERE task_id = %s AND depends_on_task_id = %s",
|
|
(task_id, depends_on_task_id),
|
|
)
|
|
|
|
|
|
def _reference_chain(conn, start: UUID) -> set[UUID]:
|
|
seen: set[UUID] = set()
|
|
stack = [start]
|
|
while stack:
|
|
current = stack.pop()
|
|
if current in seen:
|
|
continue
|
|
seen.add(current)
|
|
rows = conn.execute(
|
|
"SELECT refers_to_element_id FROM element_references WHERE element_id = %s",
|
|
(current,),
|
|
).fetchall()
|
|
stack.extend(row["refers_to_element_id"] for row in rows)
|
|
return seen
|
|
|
|
|
|
def link_element_reference(conn, actor: UUID, element_id: UUID, refers_to_element_id: UUID, context: Ctx | None) -> None:
|
|
if element_id == refers_to_element_id:
|
|
raise unprocessable("Eine Unterlage kann nicht auf sich selbst Bezug nehmen.")
|
|
element = get_element(conn, element_id)
|
|
target = get_element(conn, refers_to_element_id)
|
|
if element is None or target is None:
|
|
raise not_found()
|
|
rights = element_rights(conn, actor, element, context)
|
|
target_rights = element_rights(conn, actor, target, context)
|
|
if not rights.read or not target_rights.read:
|
|
raise not_found()
|
|
if not rights.edit:
|
|
raise forbidden()
|
|
if element_id in _reference_chain(conn, refers_to_element_id):
|
|
raise unprocessable("Dieser Bezug würde einen Kreis bilden.")
|
|
conn.execute(
|
|
"""
|
|
INSERT INTO element_references (element_id, refers_to_element_id)
|
|
VALUES (%s, %s)
|
|
ON CONFLICT DO NOTHING
|
|
""",
|
|
(element_id, refers_to_element_id),
|
|
)
|
|
|
|
|
|
def unlink_element_reference(conn, actor: UUID, element_id: UUID, refers_to_element_id: UUID, context: Ctx | None) -> None:
|
|
element = get_element(conn, element_id)
|
|
if element is None:
|
|
raise not_found()
|
|
rights = element_rights(conn, actor, element, context)
|
|
if not rights.read:
|
|
raise not_found()
|
|
if not rights.edit:
|
|
raise forbidden()
|
|
conn.execute(
|
|
"DELETE FROM element_references WHERE element_id = %s AND refers_to_element_id = %s",
|
|
(element_id, refers_to_element_id),
|
|
)
|
|
|
|
|
|
def set_content_order(
|
|
conn,
|
|
actor: UUID,
|
|
kind: str,
|
|
container_id: UUID,
|
|
expected: int,
|
|
mode: str,
|
|
direction: str,
|
|
context: Ctx | None,
|
|
view: str | None = None,
|
|
) -> int:
|
|
if kind == "case":
|
|
container, rights = require_case(conn, actor, container_id, "edit")
|
|
table = "cases"
|
|
else:
|
|
container, rights = require_matter(conn, actor, container_id, context, "edit")
|
|
table = "matters"
|
|
if not rights.edit:
|
|
raise forbidden()
|
|
version = bump_version(conn, table, container_id, expected)
|
|
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
|
|
|
|
|
|
def reorder_bindings(
|
|
conn,
|
|
actor: UUID,
|
|
kind: str,
|
|
container_id: UUID,
|
|
expected: int,
|
|
binding_ids: list[UUID],
|
|
context: Ctx | None,
|
|
) -> int:
|
|
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()
|
|
version = bump_version(conn, table, container_id, expected)
|
|
rows = conn.execute(
|
|
"""
|
|
SELECT * FROM bindings
|
|
WHERE context_kind = %s AND context_id = %s
|
|
ORDER BY position, id
|
|
""",
|
|
(kind, container_id),
|
|
).fetchall()
|
|
visible_ids = []
|
|
for row in rows:
|
|
element = get_element(conn, row["element_id"])
|
|
if element is not None and element_rights(conn, actor, element, page).read:
|
|
visible_ids.append(row["id"])
|
|
submitted = list(binding_ids)
|
|
if len(submitted) != len(set(submitted)):
|
|
raise unprocessable("Dieselbe Einbindung steht mehrfach in der Ordnung.")
|
|
if any(item not in set(visible_ids) for item in submitted):
|
|
raise not_found()
|
|
if set(submitted) != set(visible_ids):
|
|
raise unprocessable("Die Ordnung ist unvollständig. Bitte neu laden.")
|
|
visible_set = set(visible_ids)
|
|
coming = iter(submitted)
|
|
sequence = []
|
|
for row in rows:
|
|
if row["id"] in visible_set:
|
|
sequence.append(next(coming))
|
|
else:
|
|
sequence.append(row["id"])
|
|
for index, binding_id in enumerate(sequence):
|
|
conn.execute("UPDATE bindings SET position = %s WHERE id = %s", (index, binding_id))
|
|
audit(conn, actor, container["home_scope_id"], "content_reordered", kind, container_id, context)
|
|
return version
|
|
|
|
|
|
def update_dates(
|
|
conn,
|
|
actor: UUID,
|
|
element_id: UUID,
|
|
expected: int,
|
|
document_on: date | None,
|
|
sent_on: date | None,
|
|
received_on: date | None,
|
|
context: Ctx | None,
|
|
) -> dict:
|
|
element, rights = require_element(conn, actor, element_id, context, "edit")
|
|
if not rights.edit:
|
|
raise forbidden()
|
|
bump_version(conn, "elements", element_id, expected)
|
|
record_dates(conn, actor, element["home_scope_id"], element_id, context or Ctx("matter", element_id), document_on, sent_on, received_on)
|
|
return get_element(conn, element_id)
|
|
|
|
|
|
def update_summary(conn, actor: UUID, element_id: UUID, expected: int, summary: str | None, context: Ctx | None) -> dict:
|
|
element, rights = require_element(conn, actor, element_id, context, "edit")
|
|
if not rights.edit:
|
|
raise forbidden()
|
|
cleaned = (summary or "").strip()
|
|
if len(cleaned) > 400:
|
|
raise unprocessable("Die Kurzbeschreibung ist zu lang.")
|
|
bump_version(conn, "elements", element_id, expected)
|
|
conn.execute("UPDATE elements SET summary = %s WHERE id = %s", (cleaned or None, element_id))
|
|
audit(conn, actor, element["home_scope_id"], "summary_changed", "element", element_id, context)
|
|
return get_element(conn, element_id)
|
|
|
|
|
|
def update_title(conn, actor: UUID, element_id: UUID, expected: int, title: str, context: Ctx | None) -> dict:
|
|
element, rights = require_element(conn, actor, element_id, context, "edit")
|
|
if not rights.edit:
|
|
raise forbidden()
|
|
cleaned = title.strip()
|
|
if not cleaned or len(cleaned) > 200:
|
|
raise unprocessable("Der Titel fehlt oder ist zu lang.")
|
|
bump_version(conn, "elements", element_id, expected)
|
|
conn.execute("UPDATE elements SET title = %s WHERE id = %s", (cleaned, element_id))
|
|
audit(conn, actor, element["home_scope_id"], "title_changed", "element", element_id, context)
|
|
return get_element(conn, element_id)
|
|
|
|
|
|
def move_binding_chapter(conn, actor: UUID, binding_id: UUID, expected: int, chapter_id: UUID | None, context: Ctx | None) -> int:
|
|
"""Move one visible binding inside its container. No new binding and no grant."""
|
|
binding = conn.execute("SELECT * FROM bindings WHERE id = %s", (binding_id,)).fetchone()
|
|
if binding is None:
|
|
raise not_found()
|
|
kind = binding["context_kind"]
|
|
container_id = binding["context_id"]
|
|
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()
|
|
require_element(conn, actor, binding["element_id"], page, "read")
|
|
chapter_for(conn, chapter_id, kind, container_id)
|
|
version = bump_version(conn, table, container_id, expected)
|
|
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
|