1027 lines
39 KiB
Python
1027 lines
39 KiB
Python
"""Response shapes. Hidden objects are omitted, not counted and not titled."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from uuid import UUID
|
|
|
|
from app.access.policy import (
|
|
Ctx,
|
|
case_rights,
|
|
deadline_rights,
|
|
display_name,
|
|
element_rights,
|
|
get_case,
|
|
get_element,
|
|
get_matter,
|
|
get_task,
|
|
matter_rights,
|
|
matter_title_if_readable,
|
|
readable_matter_contexts,
|
|
room_name,
|
|
task_rights,
|
|
visible_bindings_for_element,
|
|
)
|
|
from app.access.policy import SHARED_NOTICE
|
|
from app.core.timeutil import dump_date, dump_dt
|
|
from app.order import arrange
|
|
|
|
|
|
def rights_dict(rights) -> dict:
|
|
return rights.as_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, parent_chapter_id FROM chapters WHERE {column} = %s",
|
|
(container_id,),
|
|
).fetchall()
|
|
items = [
|
|
{
|
|
"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,
|
|
}
|
|
for row in rows
|
|
]
|
|
if mode == "date":
|
|
dated = [item for item in items if item["document_on"]]
|
|
undated = [item for item in items if not item["document_on"]]
|
|
dated.sort(key=lambda item: (item["document_on"], item["position"], item["id"]))
|
|
undated.sort(key=lambda item: (item["position"], item["id"]))
|
|
if direction == "desc":
|
|
dated.reverse()
|
|
return dated + undated
|
|
items.sort(key=lambda item: (item["position"], item["id"]))
|
|
return items
|
|
|
|
|
|
def _annotations(conn, binding_id: UUID) -> list[dict]:
|
|
rows = conn.execute(
|
|
"""
|
|
SELECT a.id, a.body, a.created_at, p.display_name
|
|
FROM context_annotations a
|
|
JOIN auth_accounts p ON p.id = a.author_subject_id
|
|
WHERE a.binding_id = %s
|
|
ORDER BY a.created_at, a.id
|
|
""",
|
|
(binding_id,),
|
|
).fetchall()
|
|
return [
|
|
{
|
|
"id": str(row["id"]),
|
|
"body": row["body"],
|
|
"author_display_name": row["display_name"],
|
|
"created_at": dump_dt(row["created_at"]),
|
|
}
|
|
for row in rows
|
|
]
|
|
|
|
|
|
def _dates(conn, element: dict) -> dict:
|
|
row = conn.execute(
|
|
"SELECT document_on, sent_on, received_on FROM correspondence_dates WHERE element_id = %s",
|
|
(element["id"],),
|
|
).fetchone()
|
|
return {
|
|
"document_on": dump_date(row["document_on"]) if row else None,
|
|
"sent_on": dump_date(row["sent_on"]) if row else None,
|
|
"received_on": dump_date(row["received_on"]) if row else None,
|
|
"recorded_at": dump_dt(element["created_at"]),
|
|
}
|
|
|
|
|
|
def _plain_excerpt(document: dict | None) -> str | None:
|
|
if not isinstance(document, dict):
|
|
return None
|
|
parts = []
|
|
for block in document.get("blocks") or []:
|
|
if not isinstance(block, dict):
|
|
continue
|
|
text = str(block.get("text") or "").strip()
|
|
if text:
|
|
parts.append(text)
|
|
raw = " ".join(parts).strip()
|
|
if not raw:
|
|
return None
|
|
return raw[:180]
|
|
|
|
|
|
def _preview_meta(kind: str, content_type: str | None, source: str | None) -> dict:
|
|
if kind == "note":
|
|
return {"available": False, "media": "note", "source": "note"}
|
|
media = (content_type or "").split(";")[0].strip().lower()
|
|
if kind == "file" and media.startswith("image/"):
|
|
return {"available": True, "media": "image", "source": "file"}
|
|
if kind == "file" and media == "application/pdf":
|
|
return {"available": True, "media": "pdf", "source": "file"}
|
|
if kind == "external_ref" and source:
|
|
from app.sourceregistry import get_source
|
|
|
|
module = get_source(source)
|
|
if module is not None:
|
|
return {
|
|
"available": bool(module.capabilities.get("read_preview")),
|
|
"media": module.representation,
|
|
"source": source,
|
|
}
|
|
if kind == "file":
|
|
return {"available": False, "media": "file", "source": "file"}
|
|
return {"available": False, "media": "none", "source": source}
|
|
|
|
|
|
_HIDDEN_SOURCE_FIELDS = frozenset({
|
|
"connector_id",
|
|
"mailbox",
|
|
"uid",
|
|
"host",
|
|
"username",
|
|
"port",
|
|
"password",
|
|
"secret",
|
|
"base_url",
|
|
"server",
|
|
"security",
|
|
"open_url",
|
|
})
|
|
|
|
|
|
def _connector_owner(conn, raw) -> UUID | None:
|
|
try:
|
|
connector_id = UUID(str(raw))
|
|
except (TypeError, ValueError):
|
|
return None
|
|
row = conn.execute("SELECT owner_id FROM connectors WHERE id = %s", (connector_id,)).fetchone()
|
|
return row["owner_id"] if row else None
|
|
|
|
|
|
def _element_body(conn, actor: UUID, element: dict) -> dict:
|
|
payload = {
|
|
"id": str(element["id"]),
|
|
"kind": element["kind"],
|
|
"title": element["title"],
|
|
"summary": element.get("summary") or None,
|
|
"excerpt": None,
|
|
"version": element["version"],
|
|
"owner_subject_id": str(element["owner_subject_id"]),
|
|
"dates": _dates(conn, element),
|
|
"preview": _preview_meta(element["kind"], None, None),
|
|
}
|
|
if element["kind"] == "note":
|
|
body = conn.execute(
|
|
"SELECT document_json FROM note_bodies WHERE element_id = %s",
|
|
(element["id"],),
|
|
).fetchone()
|
|
document = body["document_json"] if body else {"version": 1, "blocks": []}
|
|
payload["document"] = document
|
|
payload["excerpt"] = _plain_excerpt(document)
|
|
payload["preview"] = _preview_meta("note", None, "note")
|
|
elif element["kind"] == "file":
|
|
asset = conn.execute(
|
|
"""
|
|
SELECT original_filename, content_type, byte_size, status, protection_profile
|
|
FROM media_assets WHERE element_id = %s
|
|
""",
|
|
(element["id"],),
|
|
).fetchone()
|
|
if asset is not None:
|
|
profile = asset["protection_profile"] or "legacy-plaintext"
|
|
payload["file"] = {
|
|
"filename": asset["original_filename"],
|
|
"content_type": asset["content_type"],
|
|
"byte_size": asset["byte_size"],
|
|
"status": asset["status"],
|
|
"protection_profile": profile,
|
|
}
|
|
if profile != "legacy-plaintext":
|
|
payload["preview"] = {"available": False, "media": "locked", "source": "file"}
|
|
else:
|
|
payload["preview"] = _preview_meta("file", asset["content_type"], "file")
|
|
elif element["kind"] == "external_ref":
|
|
ref = conn.execute(
|
|
"""
|
|
SELECT source, external_id, detail, connector_id, resolution
|
|
FROM external_references WHERE element_id = %s
|
|
""",
|
|
(element["id"],),
|
|
).fetchone()
|
|
if ref is not None:
|
|
detail = dict(ref["detail"] or {})
|
|
connector_owner = _connector_owner(conn, ref["connector_id"] or detail.get("connector_id"))
|
|
revealed = actor == element["owner_subject_id"] or (connector_owner is not None and actor == connector_owner)
|
|
if not revealed:
|
|
detail = {key: value for key, value in detail.items() if key not in _HIDDEN_SOURCE_FIELDS}
|
|
resolution = ref["resolution"] or "unresolved"
|
|
external = {"source": ref["source"], "detail": detail, "resolution": resolution}
|
|
if revealed:
|
|
external["external_id"] = ref["external_id"]
|
|
payload["external"] = external
|
|
from app.sourceregistry import get_source
|
|
|
|
if resolution in {"ambiguous", "unresolved"} and get_source(ref["source"]) is not None:
|
|
payload["preview"] = {"available": False, "media": "unassigned", "source": ref["source"]}
|
|
else:
|
|
payload["preview"] = _preview_meta("external_ref", None, ref["source"])
|
|
return payload
|
|
|
|
|
|
def _exception(conn, kind: str, resource_id: UUID, context: Ctx | None) -> dict | None:
|
|
if context is None:
|
|
return None
|
|
row = conn.execute(
|
|
"""
|
|
SELECT can_read, can_edit, can_share
|
|
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),
|
|
).fetchone()
|
|
if row is None:
|
|
return {"remove_read": False, "remove_edit": False, "remove_share": False}
|
|
return {"remove_read": row["can_read"], "remove_edit": row["can_edit"], "remove_share": row["can_share"]}
|
|
|
|
|
|
def communication_from_row(conn, binding: dict, element: dict) -> dict:
|
|
"""Explicit binding direction wins. An adopted mailbox direction may prefill. Dates never do."""
|
|
stored = binding.get("communication_direction")
|
|
stored = stored if stored in ("in", "out", "local") else None
|
|
if binding.get("direction_explicit"):
|
|
return {"direction": stored, "explicit": True}
|
|
source = None
|
|
if element["kind"] == "external_ref":
|
|
ref = conn.execute(
|
|
"SELECT source, detail FROM external_references WHERE element_id = %s",
|
|
(element["id"],),
|
|
).fetchone()
|
|
detail = (ref["detail"] or {}) if ref is not None else {}
|
|
if detail.get("direction") in ("in", "out"):
|
|
source = detail["direction"]
|
|
return {"direction": source, "explicit": False}
|
|
|
|
|
|
def _reference_view(conn, actor: UUID, element_id: UUID, context: Ctx, container: Ctx) -> dict | None:
|
|
element = get_element(conn, element_id)
|
|
if element is None or not element_rights(conn, actor, element, context).read:
|
|
return None
|
|
dates = _dates(conn, element)
|
|
row = conn.execute(
|
|
"""
|
|
SELECT communication_direction, direction_explicit
|
|
FROM bindings
|
|
WHERE element_id = %s AND context_kind = %s AND context_id = %s
|
|
""",
|
|
(element["id"], container.kind, container.id),
|
|
).fetchone()
|
|
direction = communication_from_row(
|
|
conn,
|
|
row or {"communication_direction": None, "direction_explicit": False},
|
|
element,
|
|
)["direction"]
|
|
return {
|
|
"id": str(element["id"]),
|
|
"title": element["title"],
|
|
"document_on": dates["document_on"],
|
|
"direction": direction,
|
|
}
|
|
|
|
|
|
def _attach_references(conn, actor: UUID, element: dict, context: Ctx, container: Ctx, body: dict) -> None:
|
|
refers = []
|
|
for row in conn.execute(
|
|
"""
|
|
SELECT refers_to_element_id
|
|
FROM element_references
|
|
WHERE element_id = %s
|
|
ORDER BY created_at, refers_to_element_id
|
|
""",
|
|
(element["id"],),
|
|
).fetchall():
|
|
view = _reference_view(conn, actor, row["refers_to_element_id"], context, container)
|
|
if view is not None:
|
|
refers.append(view)
|
|
replies = []
|
|
for row in conn.execute(
|
|
"""
|
|
SELECT element_id
|
|
FROM element_references
|
|
WHERE refers_to_element_id = %s
|
|
ORDER BY created_at, element_id
|
|
""",
|
|
(element["id"],),
|
|
).fetchall():
|
|
view = _reference_view(conn, actor, row["element_id"], context, container)
|
|
if view is not None:
|
|
replies.append(view)
|
|
if refers:
|
|
body["refers_to"] = refers
|
|
if replies:
|
|
body["referred_by"] = replies
|
|
|
|
|
|
def binding_payload(conn, actor: UUID, binding: dict, context: Ctx) -> dict | None:
|
|
element = get_element(conn, binding["element_id"])
|
|
if element is None:
|
|
return None
|
|
rights = element_rights(conn, actor, element, context)
|
|
if not rights.read:
|
|
return None
|
|
body = _element_body(conn, actor, element)
|
|
container = Ctx(binding["context_kind"], binding["context_id"])
|
|
_attach_references(conn, actor, element, context, container, body)
|
|
payload = {
|
|
"id": str(binding["id"]),
|
|
"position": binding["position"],
|
|
"chapter_id": str(binding["chapter_id"]) if binding["chapter_id"] else None,
|
|
"rights": rights.as_dict(),
|
|
"annotations": _annotations(conn, binding["id"]),
|
|
"communication": communication_from_row(conn, binding, element),
|
|
"element": body,
|
|
}
|
|
if element["owner_subject_id"] == actor:
|
|
payload["exception"] = _exception(conn, "element", element["id"], context)
|
|
return payload
|
|
|
|
|
|
def _grants(conn, kind: str, resource_id: UUID) -> list[dict]:
|
|
rows = conn.execute(
|
|
"""
|
|
SELECT g.id, g.grantee_subject_id, g.can_read, g.can_edit, g.can_share, g.use_owner_sources,
|
|
a.email, a.display_name
|
|
FROM access_grants g
|
|
JOIN auth_accounts a ON a.id = g.grantee_subject_id
|
|
WHERE NOT g.is_exception AND g.resource_kind = %s AND g.resource_id = %s AND g.context_kind IS NULL
|
|
ORDER BY a.display_name, g.id
|
|
""",
|
|
(kind, resource_id),
|
|
).fetchall()
|
|
return [
|
|
{
|
|
"id": str(row["id"]),
|
|
"grantee_subject_id": str(row["grantee_subject_id"]),
|
|
"email": row["email"],
|
|
"display_name": row["display_name"],
|
|
"can_read": row["can_read"],
|
|
"can_edit": row["can_edit"],
|
|
"can_share": row["can_share"],
|
|
"use_owner_sources": row["use_owner_sources"],
|
|
}
|
|
for row in rows
|
|
]
|
|
|
|
|
|
def _ordered_bindings(conn, actor: UUID, kind: str, container_id: UUID, context: Ctx, mode: str, direction: str) -> list[dict]:
|
|
rows = conn.execute(
|
|
"""
|
|
SELECT * FROM bindings
|
|
WHERE context_kind = %s AND context_id = %s
|
|
ORDER BY position, id
|
|
""",
|
|
(kind, container_id),
|
|
).fetchall()
|
|
visible = []
|
|
for binding in rows:
|
|
item = binding_payload(conn, actor, binding, context)
|
|
if item is None:
|
|
continue
|
|
item["_raw_position"] = binding["position"]
|
|
item["_document_on"] = item["element"]["dates"]["document_on"]
|
|
item["container"] = {"kind": kind, "id": str(container_id)}
|
|
item["_fold"] = binding.get("list_fold")
|
|
visible.append(item)
|
|
arranged = arrange(visible, mode or "position", direction or "asc")
|
|
from app.correspondence import attach_correspondence
|
|
|
|
attach_correspondence(conn, actor, arranged, context)
|
|
for item in arranged:
|
|
item.pop("_fold", None)
|
|
return arranged
|
|
|
|
|
|
def course_items(bindings: list[dict]) -> list[dict]:
|
|
"""One fachlicher Eintrag je Unterlage. Das Erfassungsdatum ist kein Belegdatum."""
|
|
items = []
|
|
for binding in bindings:
|
|
dates = binding["element"]["dates"]
|
|
items.append(
|
|
{
|
|
"id": binding["element"]["id"],
|
|
"binding_id": binding["id"],
|
|
"title": binding["element"]["title"],
|
|
"kind": binding["element"]["kind"],
|
|
"document_on": dates["document_on"],
|
|
"sent_on": dates["sent_on"],
|
|
"received_on": dates["received_on"],
|
|
"dated": dates["document_on"] is not None,
|
|
}
|
|
)
|
|
dated = [item for item in items if item["dated"]]
|
|
undated = [item for item in items if not item["dated"]]
|
|
dated.sort(key=lambda item: (item["document_on"], item["id"]))
|
|
undated.sort(key=lambda item: item["id"])
|
|
return dated + undated
|
|
|
|
|
|
def _matter_href(matter_id: UUID, context: Ctx | None) -> str:
|
|
href = f"/matters/{matter_id}"
|
|
if context is not None and context.kind == "case":
|
|
href += f"?context_kind=case&context_id={context.id}"
|
|
return href
|
|
|
|
|
|
def _append_matter_steps(conn, actor: UUID, trail: list[dict], matter: dict, context: Ctx | None) -> None:
|
|
"""Object path only. The same labels apply from a case, a list or a direct link."""
|
|
page = context if context is not None and context.kind == "case" else None
|
|
if matter["parent_matter_id"]:
|
|
parent = get_matter(conn, matter["parent_matter_id"])
|
|
if parent is not None and matter_title_if_readable(conn, actor, parent["id"]):
|
|
trail.append({"label": f"Vorgang {parent['title']}", "href": _matter_href(parent["id"], page if _parent_keeps_context(conn, actor, parent, page) else None)})
|
|
kind = "Teilvorgang" if matter["parent_matter_id"] else "Vorgang"
|
|
trail.append({"label": f"{kind} {matter['title']}", "href": None})
|
|
|
|
|
|
def _parent_keeps_context(conn, actor: UUID, parent: dict, page: Ctx | None) -> bool:
|
|
return page is not None and matter_rights(conn, actor, parent, page).read
|
|
|
|
|
|
def case_trail(conn, actor: UUID, case: dict) -> list[dict]:
|
|
trail = [{"label": "Akten", "href": "/cases"}]
|
|
if case["parent_case_id"]:
|
|
parent = get_case(conn, case["parent_case_id"])
|
|
if parent is not None and case_rights(conn, actor, parent).read:
|
|
trail.append({"label": f"Akte {parent['title']}", "href": f"/cases/{parent['id']}"})
|
|
kind = "Unterakte" if case["parent_case_id"] else "Akte"
|
|
trail.append({"label": f"{kind} {case['title']}", "href": None})
|
|
return trail
|
|
|
|
|
|
def _structural_case(conn, actor: UUID, matter: dict, context: Ctx | None) -> dict | None:
|
|
"""The case that places this matter in the structure. Several placements do not invent a main case."""
|
|
if context is not None and context.kind == "case":
|
|
case = get_case(conn, context.id)
|
|
if case is not None and case_rights(conn, actor, case).read:
|
|
return case
|
|
return None
|
|
placements = matter_placements(conn, actor, matter["id"], None)
|
|
if len(placements) != 1:
|
|
return None
|
|
case = get_case(conn, UUID(placements[0]["case_id"]))
|
|
if case is None or not case_rights(conn, actor, case).read:
|
|
return None
|
|
return case
|
|
|
|
|
|
def matter_trail(conn, actor: UUID, matter: dict, context: Ctx | None) -> list[dict]:
|
|
case = _structural_case(conn, actor, matter, context)
|
|
if case is None:
|
|
trail = [{"label": "Vorgänge", "href": "/matters"}]
|
|
_append_matter_steps(conn, actor, trail, matter, None)
|
|
return trail
|
|
trail = case_trail(conn, actor, case)
|
|
trail[-1]["href"] = f"/cases/{case['id']}"
|
|
_append_matter_steps(conn, actor, trail, matter, Ctx("case", case["id"]))
|
|
return trail
|
|
|
|
|
|
def _case_chain_label(conn, actor: UUID, case: dict) -> str:
|
|
parts = []
|
|
current = case
|
|
guard = 0
|
|
while current is not None and guard < 4:
|
|
if not case_rights(conn, actor, current).read:
|
|
break
|
|
kind = "Unterakte" if current["parent_case_id"] else "Akte"
|
|
parts.append(f"{kind} {current['title']}")
|
|
parent_id = current["parent_case_id"]
|
|
current = get_case(conn, parent_id) if parent_id else None
|
|
guard += 1
|
|
parts.reverse()
|
|
return " → ".join(parts)
|
|
|
|
|
|
def _placement_rows(conn, matter_id: UUID) -> list[dict]:
|
|
return conn.execute(
|
|
"""
|
|
SELECT c.*
|
|
FROM matter_case_links l
|
|
JOIN cases c ON c.id = l.case_id AND c.deleted_at IS NULL
|
|
WHERE l.matter_id = %s
|
|
ORDER BY c.title, c.id
|
|
""",
|
|
(matter_id,),
|
|
).fetchall()
|
|
|
|
|
|
def matter_placements(conn, actor: UUID, matter_id: UUID, context: Ctx | None) -> list[dict]:
|
|
"""Readable case assignments of this matter and its readable parent chain."""
|
|
items = []
|
|
seen: set[UUID] = set()
|
|
matter = get_matter(conn, matter_id)
|
|
guard = 0
|
|
while matter is not None and guard < 4:
|
|
for link in _placement_rows(conn, matter["id"]):
|
|
if link["id"] in seen or not case_rights(conn, actor, link).read:
|
|
continue
|
|
seen.add(link["id"])
|
|
items.append(
|
|
{
|
|
"case_id": str(link["id"]),
|
|
"label": _case_chain_label(conn, actor, link),
|
|
"href": f"/cases/{link['id']}",
|
|
"current": context is not None and context.kind == "case" and context.id == link["id"],
|
|
}
|
|
)
|
|
parent_id = matter["parent_matter_id"]
|
|
if parent_id is None or matter_title_if_readable(conn, actor, parent_id) is None:
|
|
break
|
|
matter = get_matter(conn, parent_id)
|
|
guard += 1
|
|
return items
|
|
|
|
|
|
def _contained_group(conn, actor: UUID, matter: dict, context: Ctx) -> dict | None:
|
|
matter_right = matter_rights(conn, actor, matter, context)
|
|
if not matter_right.read:
|
|
return None
|
|
return {
|
|
"matter_id": str(matter["id"]),
|
|
"title": matter["title"],
|
|
"kind_label": "Teilvorgang" if matter["parent_matter_id"] else "Vorgang",
|
|
"parent_title": matter_title_if_readable(conn, actor, matter["parent_matter_id"]),
|
|
"version": matter["version"],
|
|
"rights": matter_right.as_dict(),
|
|
"chapters": _chapters(
|
|
conn,
|
|
"matter",
|
|
matter["id"],
|
|
matter.get("content_order") or "position",
|
|
matter.get("content_order_dir") or "asc",
|
|
),
|
|
"content_order": matter.get("content_order") or "position",
|
|
"content_order_dir": matter.get("content_order_dir") or "asc",
|
|
"bindings": _ordered_bindings(
|
|
conn,
|
|
actor,
|
|
"matter",
|
|
matter["id"],
|
|
context,
|
|
matter.get("content_order") or "position",
|
|
matter.get("content_order_dir") or "asc",
|
|
),
|
|
}
|
|
|
|
|
|
def _matter_node(row: dict) -> dict:
|
|
return {
|
|
"id": str(row["id"]),
|
|
"title": row["title"],
|
|
"status": row["record_status"],
|
|
"kind_label": "Teilvorgang" if row["parent_matter_id"] else "Vorgang",
|
|
"parent_matter_id": str(row["parent_matter_id"]) if row["parent_matter_id"] else None,
|
|
"children": [],
|
|
}
|
|
|
|
|
|
def _matter_tree(conn, actor: UUID, case_id: UUID, linked: list[dict]) -> list[dict]:
|
|
"""One level: a Teilvorgang sits under its Vorgang, not beside it."""
|
|
context = Ctx("case", case_id)
|
|
rows = list(linked)
|
|
seen = {row["id"] for row in rows}
|
|
for row in list(rows):
|
|
children = conn.execute(
|
|
"""
|
|
SELECT * FROM matters
|
|
WHERE parent_matter_id = %s AND deleted_at IS NULL
|
|
ORDER BY title, id
|
|
""",
|
|
(row["id"],),
|
|
).fetchall()
|
|
for child in children:
|
|
if child["id"] in seen:
|
|
continue
|
|
if matter_rights(conn, actor, child, context).read:
|
|
rows.append(child)
|
|
seen.add(child["id"])
|
|
nodes = {row["id"]: _matter_node(row) for row in rows}
|
|
roots = []
|
|
for row in rows:
|
|
parent_id = row["parent_matter_id"]
|
|
node = nodes[row["id"]]
|
|
if parent_id and parent_id in nodes:
|
|
nodes[parent_id]["children"].append(node)
|
|
else:
|
|
roots.append(node)
|
|
return roots
|
|
|
|
|
|
def case_summary(case: dict, rights) -> dict:
|
|
return {
|
|
"id": str(case["id"]),
|
|
"title": case["title"],
|
|
"status": case["record_status"],
|
|
"version": case["version"],
|
|
"rights_mode": case["rights_mode"],
|
|
"parent_case_id": str(case["parent_case_id"]) if case["parent_case_id"] else None,
|
|
"home_scope_id": str(case["home_scope_id"]),
|
|
"rights": rights.as_dict(),
|
|
}
|
|
|
|
|
|
def case_detail(conn, actor: UUID, case: dict, rights) -> dict:
|
|
payload = case_summary(case, rights)
|
|
payload["content_order"] = case.get("content_order") or "position"
|
|
payload["content_order_dir"] = case.get("content_order_dir") or "asc"
|
|
payload["content_view"] = case.get("content_view") or "structure"
|
|
payload["trail"] = case_trail(conn, actor, case)
|
|
payload["kind_label"] = "Unterakte" if case["parent_case_id"] else "Akte"
|
|
payload["home_scope_name"] = room_name(conn, case["home_scope_id"])
|
|
payload["is_owner"] = case["owner_subject_id"] == actor
|
|
if case["parent_case_id"]:
|
|
parent = get_case(conn, case["parent_case_id"])
|
|
if parent is not None and case_rights(conn, actor, parent).read:
|
|
payload["parent_title"] = parent["title"]
|
|
payload["chapters"] = _chapters(
|
|
conn, "case", case["id"], case.get("content_order") or "position", case.get("content_order_dir") or "asc"
|
|
)
|
|
subcases = []
|
|
for row in conn.execute(
|
|
"""
|
|
SELECT * FROM cases
|
|
WHERE parent_case_id = %s AND deleted_at IS NULL
|
|
ORDER BY title, id
|
|
""",
|
|
(case["id"],),
|
|
).fetchall():
|
|
child_rights = case_rights(conn, actor, row)
|
|
if child_rights.read:
|
|
subcases.append(case_summary(row, child_rights))
|
|
payload["subcases"] = subcases
|
|
matters = []
|
|
for link in conn.execute(
|
|
"""
|
|
SELECT l.id AS link_id, m.*
|
|
FROM matter_case_links l
|
|
JOIN matters m ON m.id = l.matter_id
|
|
WHERE l.case_id = %s AND m.deleted_at IS NULL
|
|
ORDER BY m.title, m.id
|
|
""",
|
|
(case["id"],),
|
|
).fetchall():
|
|
matter_right = matter_rights(conn, actor, link, Ctx("case", case["id"]))
|
|
if not matter_right.read:
|
|
continue
|
|
matters.append(link)
|
|
payload["matters"] = _matter_tree(conn, actor, case["id"], matters)
|
|
context = Ctx("case", case["id"])
|
|
payload["bindings"] = _ordered_bindings(
|
|
conn, actor, "case", case["id"], context, payload["content_order"], payload["content_order_dir"]
|
|
)
|
|
contained = []
|
|
seen_matters: set[UUID] = set()
|
|
linked_matters = conn.execute(
|
|
"""
|
|
SELECT m.*
|
|
FROM matter_case_links l
|
|
JOIN matters m ON m.id = l.matter_id
|
|
WHERE l.case_id = %s AND m.deleted_at IS NULL
|
|
ORDER BY m.title, m.id
|
|
""",
|
|
(case["id"],),
|
|
).fetchall()
|
|
for link in linked_matters:
|
|
block = [link]
|
|
if not link["parent_matter_id"]:
|
|
block.extend(
|
|
conn.execute(
|
|
"""
|
|
SELECT * FROM matters
|
|
WHERE parent_matter_id = %s AND deleted_at IS NULL
|
|
ORDER BY title, id
|
|
""",
|
|
(link["id"],),
|
|
).fetchall()
|
|
)
|
|
for matter in block:
|
|
if matter["id"] in seen_matters:
|
|
continue
|
|
seen_matters.add(matter["id"])
|
|
group = _contained_group(conn, actor, matter, context)
|
|
if group is not None:
|
|
contained.append(group)
|
|
payload["contained"] = contained
|
|
payload["tasks"] = []
|
|
payload["deadlines"] = []
|
|
payload["task_deadline_links"] = []
|
|
|
|
def _walk(nodes):
|
|
for node in nodes:
|
|
yield node
|
|
yield from _walk(node["children"])
|
|
|
|
for node in _walk(payload["matters"]):
|
|
tracked = _tracking(conn, actor, UUID(node["id"]), context)
|
|
payload["tasks"].extend(tracked["tasks"])
|
|
payload["deadlines"].extend(tracked["deadlines"])
|
|
payload["task_deadline_links"].extend(tracked["links"])
|
|
if rights.share or case["owner_subject_id"] == actor:
|
|
payload["grants"] = _grants(conn, "case", case["id"])
|
|
return payload
|
|
|
|
|
|
def matter_contexts(conn, actor: UUID, matter: dict) -> list[dict]:
|
|
contexts = []
|
|
for item in readable_matter_contexts(conn, actor, matter):
|
|
kind = "direct" if item["kind"] == "matter" and item["id"] == str(matter["id"]) else item["kind"]
|
|
contexts.append({"kind": kind, "id": item["id"], "title": item["title"]})
|
|
return contexts
|
|
|
|
|
|
def matter_summary(conn, actor: UUID, matter: dict) -> dict:
|
|
return {
|
|
"id": str(matter["id"]),
|
|
"title": matter["title"],
|
|
"status": matter["record_status"],
|
|
"version": matter["version"],
|
|
"kind_label": "Teilvorgang" if matter["parent_matter_id"] else "Vorgang",
|
|
"parent_matter_id": str(matter["parent_matter_id"]) if matter["parent_matter_id"] else None,
|
|
"parent_title": matter_title_if_readable(conn, actor, matter["parent_matter_id"]),
|
|
"home_scope_id": str(matter["home_scope_id"]),
|
|
"home_scope_name": room_name(conn, matter["home_scope_id"]),
|
|
"contexts": matter_contexts(conn, actor, matter),
|
|
}
|
|
|
|
|
|
def _page_context(matter_id: UUID, context: Ctx | None) -> Ctx:
|
|
if context is None:
|
|
return Ctx("matter", matter_id)
|
|
return context
|
|
|
|
|
|
def matter_detail(conn, actor: UUID, matter: dict, rights, context: Ctx | None) -> dict:
|
|
page = _page_context(matter["id"], context)
|
|
payload = {
|
|
"id": str(matter["id"]),
|
|
"title": matter["title"],
|
|
"status": matter["record_status"],
|
|
"version": matter["version"],
|
|
"parent_matter_id": str(matter["parent_matter_id"]) if matter["parent_matter_id"] else None,
|
|
"parent_title": matter_title_if_readable(conn, actor, matter["parent_matter_id"]),
|
|
"home_scope_id": str(matter["home_scope_id"]),
|
|
"home_scope_name": room_name(conn, matter["home_scope_id"]),
|
|
"is_owner": matter["owner_subject_id"] == actor,
|
|
"content_order": matter.get("content_order") or "position",
|
|
"content_order_dir": matter.get("content_order_dir") or "asc",
|
|
"content_view": matter.get("content_view") or "structure",
|
|
"trail": matter_trail(conn, actor, matter, context),
|
|
"placements": matter_placements(conn, actor, matter["id"], context),
|
|
"kind_label": "Teilvorgang" if matter["parent_matter_id"] else "Vorgang",
|
|
"rights": rights.as_dict(),
|
|
"context": None if context is None else context.as_dict(),
|
|
"chapters": _chapters(
|
|
conn,
|
|
"matter",
|
|
matter["id"],
|
|
matter.get("content_order") or "position",
|
|
matter.get("content_order_dir") or "asc",
|
|
),
|
|
}
|
|
submatters = []
|
|
for child in conn.execute(
|
|
"SELECT * FROM matters WHERE parent_matter_id = %s AND deleted_at IS NULL ORDER BY title, id",
|
|
(matter["id"],),
|
|
).fetchall():
|
|
child_rights = matter_rights(conn, actor, child, page)
|
|
if child_rights.read:
|
|
submatters.append({"id": str(child["id"]), "title": child["title"], "status": child["record_status"]})
|
|
payload["submatters"] = submatters
|
|
case_links = []
|
|
for link in conn.execute(
|
|
"""
|
|
SELECT l.id, l.case_id, c.title
|
|
FROM matter_case_links l
|
|
JOIN cases c ON c.id = l.case_id AND c.deleted_at IS NULL
|
|
WHERE l.matter_id = %s
|
|
ORDER BY c.title, c.id
|
|
""",
|
|
(matter["id"],),
|
|
).fetchall():
|
|
linked_case = get_case(conn, link["case_id"])
|
|
if linked_case is not None and case_rights(conn, actor, linked_case).read:
|
|
case_links.append({"id": str(link["id"]), "case_id": str(link["case_id"]), "title": link["title"]})
|
|
payload["case_links"] = case_links
|
|
crosses = []
|
|
for link in conn.execute(
|
|
"""
|
|
SELECT l.id, l.to_matter_id
|
|
FROM matter_cross_links l
|
|
WHERE l.from_matter_id = %s
|
|
""",
|
|
(matter["id"],),
|
|
).fetchall():
|
|
title = matter_title_if_readable(conn, actor, link["to_matter_id"])
|
|
if title is not None:
|
|
crosses.append({"id": str(link["id"]), "matter_id": str(link["to_matter_id"]), "title": title})
|
|
payload["cross_links"] = crosses
|
|
payload["bindings"] = _ordered_bindings(
|
|
conn,
|
|
actor,
|
|
"matter",
|
|
matter["id"],
|
|
page,
|
|
payload["content_order"],
|
|
payload["content_order_dir"],
|
|
)
|
|
tracked = _tracking(conn, actor, matter["id"], context)
|
|
payload["tasks"] = tracked["tasks"]
|
|
payload["deadlines"] = tracked["deadlines"]
|
|
payload["task_deadline_links"] = tracked["links"]
|
|
if rights.share or matter["owner_subject_id"] == actor:
|
|
payload["grants"] = _grants(conn, "matter", matter["id"])
|
|
if matter["owner_subject_id"] == actor:
|
|
payload["exception"] = _exception(conn, "matter", matter["id"], context)
|
|
return payload
|
|
|
|
|
|
def _tracking(conn, actor: UUID, matter_id: UUID, context: Ctx | None) -> dict:
|
|
tasks = []
|
|
for task in conn.execute(
|
|
"""
|
|
SELECT * FROM tasks
|
|
WHERE matter_id = %s AND deleted_at IS NULL
|
|
ORDER BY due_on NULLS LAST, created_at
|
|
""",
|
|
(matter_id,),
|
|
).fetchall():
|
|
task_right = task_rights(conn, actor, task, context)
|
|
if task_right.read:
|
|
tasks.append(task_payload(conn, actor, task, task_right))
|
|
deadlines = []
|
|
visible_deadlines = set()
|
|
for deadline in conn.execute(
|
|
"""
|
|
SELECT * FROM deadlines
|
|
WHERE matter_id = %s AND deleted_at IS NULL
|
|
ORDER BY due_on, created_at
|
|
""",
|
|
(matter_id,),
|
|
).fetchall():
|
|
deadline_right = deadline_rights(conn, actor, deadline, context)
|
|
if deadline_right.read:
|
|
deadlines.append(deadline_payload(conn, actor, deadline))
|
|
visible_deadlines.add(deadline["id"])
|
|
links = []
|
|
visible_tasks = {UUID(item["id"]) for item in tasks}
|
|
if visible_tasks and visible_deadlines:
|
|
for link in conn.execute(
|
|
"SELECT task_id, deadline_id FROM task_deadline_links WHERE task_id = ANY(%s::uuid[])",
|
|
(list(visible_tasks),),
|
|
).fetchall():
|
|
if link["deadline_id"] in visible_deadlines:
|
|
links.append({"task_id": str(link["task_id"]), "deadline_id": str(link["deadline_id"])})
|
|
return {"tasks": tasks, "deadlines": deadlines, "links": links}
|
|
|
|
|
|
def task_payload(conn, actor: UUID, task: dict, rights=None) -> dict:
|
|
payload = {
|
|
"id": str(task["id"]),
|
|
"title": task["title"],
|
|
"status": task["task_status"],
|
|
"version": task["version"],
|
|
"due_on": dump_date(task["due_on"]),
|
|
"assignee_display_name": display_name(conn, task["assignee_subject_id"]),
|
|
}
|
|
if rights is not None:
|
|
payload["rights"] = rights.as_dict()
|
|
title = matter_title_if_readable(conn, actor, task["matter_id"])
|
|
if title is not None and task["matter_id"] is not None:
|
|
payload["matter_id"] = str(task["matter_id"])
|
|
payload["matter_title"] = title
|
|
action = _task_action_context(conn, actor, task)
|
|
if action is not None:
|
|
payload["action_context"] = action
|
|
elements = []
|
|
for link in conn.execute(
|
|
"SELECT element_id FROM task_element_links WHERE task_id = %s ORDER BY created_at, element_id",
|
|
(task["id"],),
|
|
).fetchall():
|
|
element = get_element(conn, link["element_id"])
|
|
if element is None or element["deleted_at"] is not None:
|
|
continue
|
|
if not element_rights(conn, actor, element, None).read:
|
|
continue
|
|
elements.append({"id": str(element["id"]), "title": element["title"]})
|
|
if elements:
|
|
payload["elements"] = elements
|
|
depends_on = []
|
|
for link in conn.execute(
|
|
"SELECT depends_on_task_id FROM task_dependencies WHERE task_id = %s ORDER BY created_at, depends_on_task_id",
|
|
(task["id"],),
|
|
).fetchall():
|
|
earlier = get_task(conn, link["depends_on_task_id"])
|
|
if earlier is None or not task_rights(conn, actor, earlier, None).read:
|
|
continue
|
|
depends_on.append({"id": str(earlier["id"]), "title": earlier["title"], "status": earlier["task_status"]})
|
|
if depends_on:
|
|
payload["depends_on"] = depends_on
|
|
return payload
|
|
|
|
|
|
def _task_action_context(conn, actor: UUID, task: dict) -> dict | None:
|
|
direct = task_rights(conn, actor, task, None)
|
|
if direct.read and (direct.edit or task["owner_subject_id"] == actor or task["assignee_subject_id"] == actor):
|
|
return None
|
|
if task["matter_id"] is None:
|
|
return None
|
|
matter = get_matter(conn, task["matter_id"])
|
|
if matter is None:
|
|
return None
|
|
for item in readable_matter_contexts(conn, actor, matter):
|
|
if item["kind"] != "case":
|
|
continue
|
|
rights = task_rights(conn, actor, task, Ctx("case", UUID(item["id"])))
|
|
if rights.edit or (rights.read and task["assignee_subject_id"] == actor):
|
|
return {"kind": "case", "id": item["id"]}
|
|
return None
|
|
|
|
|
|
def deadline_payload(conn, actor: UUID, deadline: dict) -> dict:
|
|
payload = {
|
|
"id": str(deadline["id"]),
|
|
"title": deadline["title"],
|
|
"status": deadline["deadline_status"],
|
|
"version": deadline["version"],
|
|
"due_on": dump_date(deadline["due_on"]),
|
|
"fulfilled_at": dump_dt(deadline["fulfilled_at"]),
|
|
"assignee_display_name": display_name(conn, deadline["assignee_subject_id"]),
|
|
}
|
|
title = matter_title_if_readable(conn, actor, deadline["matter_id"])
|
|
if title is not None and deadline["matter_id"] is not None:
|
|
payload["matter_id"] = str(deadline["matter_id"])
|
|
payload["matter_title"] = title
|
|
direct = deadline_rights(conn, actor, deadline, None)
|
|
if not (direct.read and (direct.edit or deadline["owner_subject_id"] == actor or deadline["assignee_subject_id"] == actor)):
|
|
if deadline["matter_id"] is not None:
|
|
matter = get_matter(conn, deadline["matter_id"])
|
|
if matter is not None:
|
|
for item in readable_matter_contexts(conn, actor, matter):
|
|
if item["kind"] != "case":
|
|
continue
|
|
rights = deadline_rights(conn, actor, deadline, Ctx("case", UUID(item["id"])))
|
|
if rights.edit or (rights.read and deadline["assignee_subject_id"] == actor):
|
|
payload["action_context"] = {"kind": "case", "id": item["id"]}
|
|
break
|
|
return payload
|
|
|
|
|
|
def note_update_payload(conn, actor: UUID, element: dict, document: dict) -> dict:
|
|
return {
|
|
"id": str(element["id"]),
|
|
"title": element["title"],
|
|
"version": element["version"],
|
|
"document": document,
|
|
"visible_bindings": visible_bindings_for_element(conn, actor, element),
|
|
"notice": SHARED_NOTICE,
|
|
}
|
|
|
|
|
|
LABELS = {
|
|
"case_created": "Akte angelegt",
|
|
"matter_created": "Vorgang angelegt",
|
|
"matter_linked": "Vorgang einer Akte zugeordnet",
|
|
"matter_unlinked": "Aktenzuordnung gelöst",
|
|
"cross_linked": "Querverweis erfasst",
|
|
"note_created": "Notiz angelegt",
|
|
"note_updated": "Gemeinsamer Notizinhalt geändert",
|
|
"annotation_created": "Kontextbezogene Anmerkung erfasst",
|
|
"file_added": "Datei hinzugefügt",
|
|
"external_ref_added": "Externe Referenz erfasst",
|
|
"export_created": "Übergabepaket erzeugt",
|
|
"binding_created": "Einbindung ergänzt",
|
|
"binding_removed": "Einbindung entfernt",
|
|
"element_deleted": "Element gelöscht",
|
|
"task_created": "Aufgabe angelegt",
|
|
"task_done": "Aufgabe erledigt",
|
|
"task_reopened": "Aufgabe wieder geöffnet",
|
|
"deadline_created": "Frist erfasst",
|
|
"deadline_fulfilled": "Frist erfüllt",
|
|
"grant_created": "Freigabe erteilt",
|
|
"grant_revoked": "Freigabe entzogen",
|
|
"source_read_mediated": "Verknüpftes Original gelesen",
|
|
"correspondence_document": "Dokumentdatum",
|
|
"correspondence_sent": "Versand",
|
|
"correspondence_received": "Zugang",
|
|
"correspondence_recorded": "Erfassung",
|
|
"chapter_created": "Kapitel angelegt",
|
|
"summary_changed": "Kurzbeschreibung geändert",
|
|
"title_changed": "Titel geändert",
|
|
"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",
|
|
}
|