Stelle den ersten nutzbaren Ablauf zum Organisieren und Nachverfolgen bereit.
Deploy Development / deploy (push) Successful in 23s

Anmeldung, Datenraeume, Akten, Vorgaenge, gemeinsame Notizen, Dateien, manuelle Paperless-Referenzen, Aufgaben und unabhaengige Fristen laufen damit in der Entwicklungsumgebung.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
LarsandCursor committed 2026-10-16 22:09:08 +02:00
1 parent cfe17ff909
commit 2558239bfd
60 files changed
+8467 -71

No files matched your search

+7
View File
@@ -0,0 +1,7 @@
# Tsumugu
Fachlich führend ist `docs/product/TSUMUGU_PRODUCT_SPEC.md`. Der technische Entwurf ist `docs/architecture/TSUMUGU_TECHNICAL_SPEC.md`. Vorläufige Rechte- und Löschregeln der ersten Lieferung stehen in `docs/MVP_ANNAHMEN.md` und sind keine endgültigen Produktentscheidungen.
Deployment und Ports: `docs/DEPLOYMENT.md`. Gearbeitet wird auf `develop`. Ein Push dorthin startet das Development-Deploy auf dem Raspberry Pi. Production entsteht nur durch einen Merge nach `main`.
Die Anwendung bleibt produktlokal: FastAPI, PostgreSQL, React. Keine gemeinsame Fachdatenbank mit anderen Jinkendo-Anwendungen. Finanzfunktionen, Paperless-Abgleich, KI und externer Anwaltszugang gehören nicht in diese Lieferung.
+11 -2
View File
@@ -6,7 +6,9 @@ Remote: `http://192.168.2.144:3000/Lars/tsumugu.git`
## Stand
Das Repository enthält das Deploy-Gerüst. Ein Push auf `develop` baut und startet Development, ein Merge von `develop` nach `main` die Produktion. Der Gitea-Runner auf dem Raspberry Pi (`192.168.2.49`) übernimmt Build und Deploy.
Die erste benutzbare Lieferung organisiert und verfolgt: Anmeldung, Datenräume, Akten und Vorgänge, Notizen, Dateien, manuelle Paperless-Referenzen, Chronologie, Aufgaben und unabhängige Fristen. Finanzfunktionen, automatische Paperless-Synchronisation, KI und externer Anwaltszugang folgen später.
Ein Push auf `develop` baut und startet Development, ein Merge von `develop` nach `main` die Produktion. Der Gitea-Runner auf dem Raspberry Pi (`192.168.2.49`) übernimmt Build und Deploy. Beim Start führt das Backend die Migrationen aus. In Development legt es synthetische Beispieldaten an, in Production nicht.
| | Development | Production |
|---|---|---|
@@ -17,4 +19,11 @@ Das Repository enthält das Deploy-Gerüst. Ein Push auf `develop` baut und star
Details, Ports und der Synology-Reverse-Proxy: `docs/DEPLOYMENT.md`.
Backend und Frontend sind bewusst schmal: `/api/health` prüft Postgres, das Frontend reicht `/api/` an das Backend durch. Die Anwendung selbst ist noch nicht begonnen.
Development ist nach dem Deploy unter https://dev.tsumugu.jinkendo.de oder http://192.168.2.49:3094 erreichbar. Die Beispielkonten stehen auf der Anmeldeseite:
| | E-Mail | Passwort |
|---|---|---|
| Ada Beispiel | ada@example.test | Beispiel-Ada-2026 |
| Ben Beispiel | ben@example.test | Beispiel-Ben-2026 |
Ada führt den Mietstreit Musterstraße. Ben darf diesen Kontext bearbeiten und sieht die private Verhandlungsstrategie nicht. Vorläufige Rechte- und Löschannahmen: `docs/MVP_ANNAHMEN.md`. `/api/health` prüft weiterhin nur, ob die Anwendung und die Datenbank antworten.
+5
View File
@@ -0,0 +1,5 @@
__pycache__
.pytest_cache
.venv
data
*.pyc
+5 -1
View File
@@ -2,11 +2,15 @@ FROM python:3.12-slim
WORKDIR /app
ENV PYTHONDONTWRITEBYTECODE=1
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY main.py .
COPY app ./app
COPY migrations ./migrations
EXPOSE 8000
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
CMD ["python", "-m", "app.entrypoint"]
+1
View File
@@ -0,0 +1 @@
"""Tsumugu application package."""
+1
View File
@@ -0,0 +1 @@
"""Data rooms and the case-based access policy."""
+763
View File
@@ -0,0 +1,763 @@
"""Context rights for the first delivery.
Provisional MVP assumptions, not final product decisions, live in docs/MVP_ANNAHMEN.md.
The action context is the only rights path used here. A case link inherits that case's
rights. Cross-links do not. Exceptions apply only in the context they name.
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import Any
from uuid import UUID
from app.core.errors import conflict, forbidden, not_found, unprocessable
SHARED_NOTICE = "Diese Änderung betrifft den gemeinsamen Inhalt der Notiz."
@dataclass(frozen=True)
class Rights:
read: bool = False
edit: bool = False
share: bool = False
delete: bool = False
@classmethod
def full(cls) -> Rights:
return cls(True, True, True, True)
@classmethod
def from_row(cls, row: dict | None) -> Rights:
if row is None:
return cls()
return cls(bool(row["can_read"]), bool(row["can_edit"]), bool(row["can_share"]), bool(row["can_delete"]))
def without(self, blocked: Rights) -> Rights:
return Rights(
self.read and not blocked.read,
self.edit and not blocked.edit,
self.share and not blocked.share,
self.delete and not blocked.delete,
)
def allows(self, need: str) -> bool:
return bool(getattr(self, need))
def as_dict(self) -> dict[str, bool]:
return {"read": self.read, "edit": self.edit, "share": self.share, "delete": self.delete}
@dataclass(frozen=True)
class Ctx:
kind: str
id: UUID
def as_dict(self) -> dict[str, str]:
return {"kind": self.kind, "id": str(self.id)}
def parse_context(payload: dict | None, *, required: bool = False) -> Ctx | None:
if not payload:
if required:
raise unprocessable("Der Handlungskontext fehlt.")
return None
kind = payload.get("kind")
raw = payload.get("id")
if kind not in ("case", "matter") or not raw:
raise unprocessable("Der Handlungskontext ist ungültig.")
try:
return Ctx(kind, UUID(str(raw)))
except ValueError as exc:
raise unprocessable("Der Handlungskontext ist ungültig.") from exc
def parse_query_context(kind: str | None, raw: str | None) -> Ctx | None:
if kind is None and raw is None:
return None
return parse_context({"kind": kind, "id": raw}, required=True)
def audit(
conn,
actor_id: UUID | None,
scope_id: UUID | None,
action: str,
resource_kind: str,
resource_id: UUID,
context: Ctx | None = None,
occurred_on=None,
) -> None:
conn.execute(
"""
INSERT INTO domain_events (
actor_subject_id, scope_id, action, resource_kind, resource_id,
context_kind, context_id, occurred_on
)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
""",
(
actor_id,
scope_id,
action,
resource_kind,
resource_id,
context.kind if context else None,
context.id if context else None,
occurred_on,
),
)
def bump_version(conn, table: str, row_id: UUID, expected: int) -> int:
if table not in {"cases", "matters", "elements", "tasks", "deadlines"}:
raise RuntimeError("unsupported version table")
row = conn.execute(
f"UPDATE {table} SET version = version + 1, updated_at = now() "
f"WHERE id = %s AND version = %s AND deleted_at IS NULL RETURNING version",
(row_id, expected),
).fetchone()
if row is None:
current = conn.execute(
f"SELECT version, deleted_at FROM {table} WHERE id = %s",
(row_id,),
).fetchone()
if current is None or current["deleted_at"] is not None:
raise not_found()
raise conflict()
return int(row["version"])
def _get(conn, table: str, row_id: UUID) -> dict | None:
if table not in {"cases", "matters", "elements", "tasks", "deadlines", "data_rooms"}:
raise RuntimeError("unsupported lookup")
return conn.execute(f"SELECT * FROM {table} WHERE id = %s", (row_id,)).fetchone()
def get_case(conn, case_id: UUID) -> dict | None:
row = _get(conn, "cases", case_id)
if row is None or row["deleted_at"] is not None:
return None
return row
def get_matter(conn, matter_id: UUID) -> dict | None:
row = _get(conn, "matters", matter_id)
if row is None or row["deleted_at"] is not None:
return None
return row
def get_element(conn, element_id: UUID) -> dict | None:
row = _get(conn, "elements", element_id)
if row is None or row["deleted_at"] is not None:
return None
return row
def get_task(conn, task_id: UUID) -> dict | None:
row = _get(conn, "tasks", task_id)
if row is None or row["deleted_at"] is not None:
return None
return row
def get_deadline(conn, deadline_id: UUID) -> dict | None:
row = _get(conn, "deadlines", deadline_id)
if row is None or row["deleted_at"] is not None:
return None
return row
def _direct_grant(conn, actor: UUID, kind: str, resource_id: UUID) -> Rights:
row = conn.execute(
"""
SELECT can_read, can_edit, can_share, can_delete
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
""",
(actor, kind, resource_id),
).fetchone()
return Rights.from_row(row)
def _exceptions(conn, actor: UUID, kind: str, resource_id: UUID, context: Ctx | None) -> Rights:
rows = conn.execute(
"""
SELECT can_read, can_edit, can_share, can_delete
FROM access_grants
WHERE is_exception
AND resource_kind = %s
AND resource_id = %s
AND context_kind IS NOT DISTINCT FROM %s
AND context_id IS NOT DISTINCT FROM %s
AND (grantee_subject_id IS NULL OR grantee_subject_id = %s)
""",
(
kind,
resource_id,
context.kind if context else None,
context.id if context else None,
actor,
),
).fetchall()
blocked = Rights()
for row in rows:
blocked = Rights(
blocked.read or row["can_read"],
blocked.edit or row["can_edit"],
blocked.share or row["can_share"],
blocked.delete or row["can_delete"],
)
return blocked
def case_rights(conn, actor: UUID, case: dict) -> Rights:
if case["parent_case_id"] is not None and case["rights_mode"] == "inherit_parent":
parent = get_case(conn, case["parent_case_id"])
base = case_rights(conn, actor, parent) if parent else Rights()
elif case["owner_subject_id"] == actor:
base = Rights.full()
else:
base = _direct_grant(conn, actor, "case", case["id"])
return base.without(_exceptions(conn, actor, "case", case["id"], None))
def _linked(conn, matter_id: UUID, case_id: UUID) -> bool:
row = conn.execute(
"SELECT 1 FROM matter_case_links WHERE matter_id = %s AND case_id = %s",
(matter_id, case_id),
).fetchone()
return row is not None
def matter_rights(conn, actor: UUID, matter: dict, context: Ctx | None) -> Rights:
if context is None:
base = Rights.full() if matter["owner_subject_id"] == actor else _direct_grant(conn, actor, "matter", matter["id"])
return base.without(_exceptions(conn, actor, "matter", matter["id"], None))
if context.kind == "case":
anchor_id = matter["id"]
if not _linked(conn, matter["id"], context.id) and matter["parent_matter_id"] is not None:
if _linked(conn, matter["parent_matter_id"], context.id):
anchor_id = matter["parent_matter_id"]
else:
return Rights()
elif not _linked(conn, matter["id"], context.id):
return Rights()
case = get_case(conn, context.id)
if case is None:
return Rights()
base = case_rights(conn, actor, case)
if anchor_id != matter["id"]:
parent = get_matter(conn, anchor_id)
if parent is None:
return Rights()
base = matter_rights(conn, actor, parent, context)
return base.without(_exceptions(conn, actor, "matter", matter["id"], context))
if context.kind == "matter":
if matter["parent_matter_id"] != context.id:
return Rights()
parent = get_matter(conn, context.id)
if parent is None:
return Rights()
base = matter_rights(conn, actor, parent, None)
return base.without(_exceptions(conn, actor, "matter", matter["id"], context))
return Rights()
def _bindings(conn, element_id: UUID) -> list[dict]:
return conn.execute(
"SELECT * FROM bindings WHERE element_id = %s ORDER BY position, created_at",
(element_id,),
).fetchall()
def _blocked(conn, case_id: UUID, element_id: UUID) -> bool:
row = conn.execute(
"""
SELECT 1
FROM case_link_blocks b
JOIN matter_case_links l ON l.id = b.link_id
WHERE l.case_id = %s AND b.element_id = %s
""",
(case_id, element_id),
).fetchone()
return row is not None
def _matter_reaches_case(conn, matter_id: UUID, case_id: UUID) -> bool:
matter = get_matter(conn, matter_id)
if matter is None:
return False
if _linked(conn, matter_id, case_id):
return True
return bool(matter["parent_matter_id"] and _linked(conn, matter["parent_matter_id"], case_id))
def element_rights(conn, actor: UUID, element: dict, context: Ctx | None) -> Rights:
if context is None:
base = (
Rights.full()
if element["owner_subject_id"] == actor
else _direct_grant(conn, actor, "element", element["id"])
)
return base.without(_exceptions(conn, actor, "element", element["id"], None))
bindings = _bindings(conn, element["id"])
if context.kind == "case":
on_case = any(item["context_kind"] == "case" and item["context_id"] == context.id for item in bindings)
via_matter = [
item
for item in bindings
if item["context_kind"] == "matter" and _matter_reaches_case(conn, item["context_id"], context.id)
]
if not on_case and not via_matter:
return Rights()
if not on_case and _blocked(conn, context.id, element["id"]):
return Rights()
case = get_case(conn, context.id)
if case is None:
return Rights()
base = case_rights(conn, actor, case)
return base.without(_exceptions(conn, actor, "element", element["id"], context))
if context.kind == "matter":
matter = get_matter(conn, context.id)
if matter is None:
return Rights()
hosted = any(
item["context_kind"] == "matter"
and (item["context_id"] == context.id or _child_of(conn, item["context_id"], context.id))
for item in bindings
)
if not hosted:
return Rights()
base = matter_rights(conn, actor, matter, None)
return base.without(_exceptions(conn, actor, "element", element["id"], context))
return Rights()
def _child_of(conn, matter_id: UUID, parent_id: UUID) -> bool:
matter = get_matter(conn, matter_id)
return bool(matter and matter["parent_matter_id"] == parent_id)
def element_rights_via_case_or_direct(conn, actor: UUID, element: dict, context: Ctx | None) -> Rights:
"""Rights for an element bound to a matter when the caller names a case path.
A matter context uses direct matter rights. A case context uses that case only.
"""
if context is None:
return element_rights(conn, actor, element, None)
if context.kind == "matter":
return element_rights(conn, actor, element, context)
return element_rights(conn, actor, element, context)
def task_rights(conn, actor: UUID, task: dict, context: Ctx | None) -> Rights:
if task["assignee_subject_id"] == actor and context is None:
granted = _direct_grant(conn, actor, "task", task["id"])
base = Rights(read=True, edit=granted.edit, share=False, delete=False)
if task["owner_subject_id"] == actor:
base = Rights.full()
return base.without(_exceptions(conn, actor, "task", task["id"], None))
if context is None:
base = Rights.full() if task["owner_subject_id"] == actor else _direct_grant(conn, actor, "task", task["id"])
return base.without(_exceptions(conn, actor, "task", task["id"], None))
if task["matter_id"] is None:
return Rights()
matter = get_matter(conn, task["matter_id"])
if matter is None:
return Rights()
if context.kind == "matter" and context.id == task["matter_id"]:
base = matter_rights(conn, actor, matter, None)
elif context.kind == "case":
base = matter_rights(conn, actor, matter, context)
elif context.kind == "matter" and matter["parent_matter_id"] == context.id:
base = matter_rights(conn, actor, matter, context)
else:
return Rights()
return base.without(_exceptions(conn, actor, "task", task["id"], context))
def deadline_rights(conn, actor: UUID, deadline: dict, context: Ctx | None) -> Rights:
if deadline["assignee_subject_id"] == actor and context is None:
base = Rights(read=True, edit=False, share=False, delete=False)
if deadline["owner_subject_id"] == actor:
base = Rights.full()
return base.without(_exceptions(conn, actor, "deadline", deadline["id"], None))
if context is None:
base = (
Rights.full()
if deadline["owner_subject_id"] == actor
else _direct_grant(conn, actor, "deadline", deadline["id"])
)
return base.without(_exceptions(conn, actor, "deadline", deadline["id"], None))
if deadline["matter_id"] is None:
return Rights()
matter = get_matter(conn, deadline["matter_id"])
if matter is None:
return Rights()
if context.kind == "matter" and context.id == deadline["matter_id"]:
base = matter_rights(conn, actor, matter, None)
elif context.kind == "case":
base = matter_rights(conn, actor, matter, context)
else:
return Rights()
return base.without(_exceptions(conn, actor, "deadline", deadline["id"], context))
def require_case(conn, actor: UUID, case_id: UUID, need: str) -> tuple[dict, Rights]:
case = get_case(conn, case_id)
if case is None:
raise not_found()
rights = case_rights(conn, actor, case)
_require(rights, need)
return case, rights
def require_matter(conn, actor: UUID, matter_id: UUID, context: Ctx | None, need: str) -> tuple[dict, Rights]:
matter = get_matter(conn, matter_id)
if matter is None:
raise not_found()
rights = matter_rights(conn, actor, matter, context)
_require(rights, need)
return matter, rights
def require_element(conn, actor: UUID, element_id: UUID, context: Ctx | None, need: str) -> tuple[dict, Rights]:
element = get_element(conn, element_id)
if element is None:
raise not_found()
rights = element_rights(conn, actor, element, context)
_require(rights, need)
return element, rights
def _require(rights: Rights, need: str) -> None:
if not rights.read:
raise not_found()
if need != "read" and not rights.allows(need):
raise forbidden()
def can_change_status(actor: UUID, row: dict, rights: Rights, assignee_key: str = "assignee_subject_id") -> bool:
if rights.edit or row["owner_subject_id"] == actor:
return True
return row[assignee_key] == actor and rights.read
def readable_matter_contexts(conn, actor: UUID, matter: dict) -> list[dict]:
found: list[dict] = []
direct = matter_rights(conn, actor, matter, None)
if direct.read:
found.append({"kind": "matter", "id": str(matter["id"]), "title": matter["title"], "rights": direct.as_dict()})
links = conn.execute(
"""
SELECT l.case_id, c.title
FROM matter_case_links l
JOIN cases c ON c.id = l.case_id
WHERE l.matter_id = %s AND c.deleted_at IS NULL
""",
(matter["id"],),
).fetchall()
if matter["parent_matter_id"] is not None:
links = list(links) + list(
conn.execute(
"""
SELECT l.case_id, c.title
FROM matter_case_links l
JOIN cases c ON c.id = l.case_id
WHERE l.matter_id = %s AND c.deleted_at IS NULL
""",
(matter["parent_matter_id"],),
).fetchall()
)
seen: set[UUID] = set()
for link in links:
if link["case_id"] in seen:
continue
seen.add(link["case_id"])
rights = matter_rights(conn, actor, matter, Ctx("case", link["case_id"]))
if rights.read:
found.append(
{
"kind": "case",
"id": str(link["case_id"]),
"title": link["title"],
"rights": rights.as_dict(),
}
)
return found
def list_cases(conn, actor: UUID) -> list[dict]:
rows = conn.execute(
"""
SELECT c.*
FROM cases c
WHERE c.deleted_at IS NULL
AND (
c.owner_subject_id = %(actor)s
OR EXISTS (
SELECT 1 FROM access_grants g
WHERE g.resource_kind = 'case' AND g.resource_id = c.id
AND g.grantee_subject_id = %(actor)s AND NOT g.is_exception AND g.can_read
AND g.context_id IS NULL
)
OR (
c.rights_mode = 'inherit_parent' AND c.parent_case_id IS NOT NULL AND EXISTS (
SELECT 1 FROM cases p
WHERE p.id = c.parent_case_id AND p.deleted_at IS NULL
AND (
p.owner_subject_id = %(actor)s
OR EXISTS (
SELECT 1 FROM access_grants g
WHERE g.resource_kind = 'case' AND g.resource_id = p.id
AND g.grantee_subject_id = %(actor)s AND NOT g.is_exception
AND g.can_read AND g.context_id IS NULL
)
)
)
)
)
ORDER BY c.updated_at DESC, c.id DESC
""",
{"actor": actor},
).fetchall()
visible = []
for row in rows:
rights = case_rights(conn, actor, row)
if rights.read:
visible.append((row, rights))
return visible
def list_matters(conn, actor: UUID) -> list[tuple[dict, list[dict]]]:
rows = conn.execute(
"""
SELECT m.*
FROM matters m
WHERE m.deleted_at IS NULL
AND (
m.owner_subject_id = %(actor)s
OR EXISTS (
SELECT 1 FROM access_grants g
WHERE g.resource_kind = 'matter' AND g.resource_id = m.id
AND g.grantee_subject_id = %(actor)s AND NOT g.is_exception AND g.can_read
AND g.context_id IS NULL
)
OR EXISTS (
SELECT 1 FROM matter_case_links l
JOIN cases c ON c.id = l.case_id AND c.deleted_at IS NULL
WHERE l.matter_id = m.id
AND (
c.owner_subject_id = %(actor)s
OR EXISTS (
SELECT 1 FROM access_grants g
WHERE g.resource_kind = 'case' AND g.resource_id = c.id
AND g.grantee_subject_id = %(actor)s AND NOT g.is_exception
AND g.can_read AND g.context_id IS NULL
)
)
)
)
ORDER BY m.updated_at DESC, m.id DESC
""",
{"actor": actor},
).fetchall()
visible = []
for row in rows:
contexts = readable_matter_contexts(conn, actor, row)
if contexts:
visible.append((row, contexts))
return visible
def assert_scope_can_host(conn, scope_id: UUID) -> dict:
room = _get(conn, "data_rooms", scope_id)
if room is None or room["status"] != "active":
raise forbidden("Der gewählte Datenraum ist nicht verfügbar.")
return room
def same_home(row: dict, scope_id: UUID) -> None:
if row["home_scope_id"] != scope_id:
raise unprocessable(
"Unterakten, Teilvorgänge und Kapitel bleiben im Datenraum ihres Behälters. "
"Wähle diesen Datenraum, wenn du dort Mitglied bist, oder lege einen Querverweis an."
)
def account_by_email(conn, email: str) -> dict | None:
return conn.execute(
"SELECT id, email, display_name, status FROM auth_accounts WHERE email = %s",
(email.strip().lower(),),
).fetchone()
def display_name(conn, account_id: UUID | None) -> str | None:
if account_id is None:
return None
row = conn.execute("SELECT display_name FROM auth_accounts WHERE id = %s", (account_id,)).fetchone()
return row["display_name"] if row else None
def room_name(conn, room_id: UUID) -> str | None:
row = conn.execute("SELECT name FROM data_rooms WHERE id = %s", (room_id,)).fetchone()
return row["name"] if row else None
def visible_bindings_for_element(conn, actor: UUID, element: dict) -> list[dict]:
"""Names and counts only bindings the actor can actually read."""
result = []
for binding in _bindings(conn, element["id"]):
if binding["context_kind"] == "case":
context = Ctx("case", binding["context_id"])
rights = element_rights(conn, actor, element, context)
if not rights.read:
continue
case = get_case(conn, binding["context_id"])
if case is None:
continue
title = case["title"]
else:
matter = get_matter(conn, binding["context_id"])
if matter is None:
continue
contexts = readable_matter_contexts(conn, actor, matter)
if not contexts:
continue
direct = element_rights(conn, actor, element, Ctx("matter", matter["id"]))
via_cases = []
for item in contexts:
if item["kind"] != "case":
continue
case_rights_now = element_rights(conn, actor, element, Ctx("case", UUID(item["id"])))
if case_rights_now.read:
via_cases.append(item)
if not direct.read and not via_cases:
continue
title = matter["title"]
context = Ctx("matter", matter["id"])
result.append(
{
"id": str(binding["id"]),
"context_kind": binding["context_kind"],
"context_id": str(binding["context_id"]),
"context_title": title,
}
)
return result
def chapter_for(conn, chapter_id: UUID | None, kind: str, container_id: UUID) -> None:
if chapter_id is None:
return
column = "case_id" if kind == "case" else "matter_id"
row = conn.execute(
f"SELECT id FROM chapters WHERE id = %s AND {column} = %s",
(chapter_id, container_id),
).fetchone()
if row is None:
raise unprocessable("Das Kapitel gehört nicht zu diesem Kontext.")
def next_position(conn, kind: str, container_id: UUID) -> int:
row = conn.execute(
"SELECT COALESCE(MAX(position), 0) + 1 AS pos FROM bindings WHERE context_kind = %s AND context_id = %s",
(kind, container_id),
).fetchone()
return int(row["pos"])
def insert_binding(conn, element_id: UUID, kind: str, container_id: UUID, chapter_id: UUID | None, actor: UUID) -> dict:
existing = conn.execute(
"""
SELECT id FROM bindings
WHERE element_id = %s AND context_kind = %s AND context_id = %s
""",
(element_id, kind, container_id),
).fetchone()
if existing is not None:
raise unprocessable("Die Notiz ist in diesem Kontext bereits eingebunden.")
chapter_for(conn, chapter_id, kind, container_id)
row = conn.execute(
"""
INSERT INTO bindings (element_id, context_kind, context_id, chapter_id, position, created_by)
VALUES (%s, %s, %s, %s, %s, %s)
RETURNING *
""",
(element_id, kind, container_id, chapter_id, next_position(conn, kind, container_id), actor),
).fetchone()
return row
def block_unsharable_matter_elements(conn, actor: UUID, link_id: UUID, matter: dict) -> None:
"""Contents the linking actor cannot share stay invisible in that case. No titles are stored."""
matter_ids = [matter["id"]]
children = conn.execute(
"SELECT id FROM matters WHERE parent_matter_id = %s AND deleted_at IS NULL",
(matter["id"],),
).fetchall()
matter_ids.extend(item["id"] for item in children)
for matter_id in matter_ids:
bindings = conn.execute(
"SELECT element_id FROM bindings WHERE context_kind = 'matter' AND context_id = %s",
(matter_id,),
).fetchall()
container = get_matter(conn, matter_id)
if container is None:
continue
for binding in bindings:
element = get_element(conn, binding["element_id"])
if element is None:
continue
rights = element_rights(conn, actor, element, Ctx("matter", matter_id))
if matter_id != matter["id"]:
parent_rights = element_rights(conn, actor, element, Ctx("matter", matter["id"]))
if parent_rights.share:
rights = parent_rights
if rights.share:
continue
conn.execute(
"INSERT INTO case_link_blocks (link_id, element_id) VALUES (%s, %s) ON CONFLICT DO NOTHING",
(link_id, element["id"]),
)
def matter_title_if_readable(conn, actor: UUID, matter_id: UUID | None) -> str | None:
if matter_id is None:
return None
matter = get_matter(conn, matter_id)
if matter is None:
return None
if readable_matter_contexts(conn, actor, matter):
return matter["title"]
return None
def ensure_member_or_personal(conn, account_id: UUID, kind: str, scope_id: UUID) -> dict:
room = assert_scope_can_host(conn, scope_id)
if kind == "personal":
if room["kind"] != "personal" or room["id"] != account_id:
raise forbidden("Der persönliche Datenraum gehört zu einem anderen Konto.")
return room
if kind != "organization" or room["kind"] != "organization":
raise forbidden("Dieser Datenraum kann nicht gewählt werden.")
membership = conn.execute(
"""
SELECT role FROM room_memberships
WHERE room_id = %s AND subject_id = %s AND status = 'active'
""",
(scope_id, account_id),
).fetchone()
if membership is None:
raise forbidden("Du bist in diesem Datenraum nicht Mitglied.")
return room
+1
View File
@@ -0,0 +1 @@
"""HTTP adapters. Authorization stays in the domain services."""
+97
View File
@@ -0,0 +1,97 @@
"""Request scope: one transaction, a session principal, and no client-supplied identity."""
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from uuid import UUID
from fastapi import Depends, Request
from psycopg import Connection
from app.access.policy import ensure_member_or_personal
from app.auth.security import hash_secret, read_session_token
from app.core.errors import forbidden, unauthorized
from app.core.timeutil import utcnow
@dataclass(frozen=True)
class Principal:
account_id: UUID
email: str
display_name: str
session_id: UUID
scope_kind: str
scope_id: UUID
scope_name: str
epoch: int
def get_conn(request: Request):
pool = request.app.state.pool
with pool.connection() as conn:
try:
conn.execute("SET TIME ZONE 'UTC'")
yield conn
conn.commit()
for path in getattr(request.state, "delete_after_commit", []):
Path(path).unlink(missing_ok=True)
except Exception:
conn.rollback()
for path in getattr(request.state, "cleanup_files", []):
Path(path).unlink(missing_ok=True)
raise
def _session_row(conn: Connection, request: Request) -> dict:
token = read_session_token(request)
if not token:
raise unauthorized()
row = conn.execute(
"""
SELECT s.id, s.account_id, s.csrf_token, s.scope_kind, s.scope_id, s.epoch,
s.expires_at, s.revoked_at, a.email, a.display_name, a.status AS account_status
FROM auth_sessions s
JOIN auth_accounts a ON a.id = s.account_id
WHERE s.secret_hash = %s
""",
(hash_secret(token),),
).fetchone()
if row is None or row["revoked_at"] is not None or row["expires_at"] <= utcnow():
raise unauthorized()
if row["account_status"] != "active":
raise unauthorized()
if request.method not in {"GET", "HEAD", "OPTIONS"}:
sent = request.headers.get("x-csrf-token") or ""
if not sent or sent != row["csrf_token"]:
raise forbidden("Die Anfrage konnte der Sitzung nicht zugeordnet werden.")
return row
def get_session(request: Request, conn: Connection = Depends(get_conn)) -> dict:
return _session_row(conn, request)
def get_principal(request: Request, conn: Connection = Depends(get_conn)) -> Principal:
row = _session_row(conn, request)
kind = request.headers.get("x-scope-kind")
raw_scope = request.headers.get("x-scope-id")
if not kind or not raw_scope:
raise forbidden("Der Datenraum ist nicht gewählt.")
try:
scope_id = UUID(raw_scope)
except ValueError as exc:
raise forbidden("Der Datenraum ist nicht gewählt.") from exc
if kind != row["scope_kind"] or scope_id != row["scope_id"]:
raise forbidden("Der gewählte Datenraum entspricht nicht mehr der Sitzung.")
room = ensure_member_or_personal(conn, row["account_id"], kind, scope_id)
return Principal(
account_id=row["account_id"],
email=row["email"],
display_name=row["display_name"],
session_id=row["id"],
scope_kind=kind,
scope_id=scope_id,
scope_name=room["name"],
epoch=row["epoch"],
)
File diff suppressed because it is too large. Load diff
+203
View File
@@ -0,0 +1,203 @@
"""Request bodies. Unknown fields are rejected."""
from __future__ import annotations
from datetime import date
from typing import Annotated, Literal
from uuid import UUID
from pydantic import BaseModel, ConfigDict, Field
Email = Annotated[str, Field(min_length=3, max_length=320, pattern=r"^[^@\s]+@[^@\s]+\.[^@\s]+$")]
class APIModel(BaseModel):
model_config = ConfigDict(extra="forbid")
class LoginIn(APIModel):
email: Email
password: str = Field(min_length=1, max_length=200)
class ScopeIn(APIModel):
kind: Literal["personal", "organization"]
id: UUID
class AcceptInviteIn(APIModel):
token: str = Field(min_length=20, max_length=200)
display_name: str = Field(min_length=1, max_length=120)
password: str = Field(min_length=10, max_length=200)
class InvitationIn(APIModel):
email: Email
room_id: UUID
class RoomIn(APIModel):
name: str = Field(min_length=1, max_length=160)
class MemberIn(APIModel):
email: Email
role: Literal["member", "manager"]
class ContextIn(APIModel):
kind: Literal["case", "matter"]
id: UUID
class CaseIn(APIModel):
title: str = Field(min_length=1, max_length=200)
parent_case_id: UUID | None = None
rights_mode: Literal["inherit_parent", "explicit"] = "inherit_parent"
class CasePatch(APIModel):
expected_version: int = Field(ge=1)
title: str | None = Field(default=None, min_length=1, max_length=200)
status: Literal["open", "closed"] | None = None
class ChapterIn(APIModel):
title: str = Field(min_length=1, max_length=200)
position: int | None = Field(default=None, ge=0, le=10000)
class MatterIn(APIModel):
title: str = Field(min_length=1, max_length=200)
parent_matter_id: UUID | None = None
context: ContextIn | None = None
class MatterPatch(APIModel):
expected_version: int = Field(ge=1)
title: str | None = Field(default=None, min_length=1, max_length=200)
status: Literal["open", "closed"] | None = None
context: ContextIn | None = None
class CaseLinkIn(APIModel):
case_id: UUID
context: ContextIn | None = None
class CrossLinkIn(APIModel):
target_matter_id: UUID
target_context: ContextIn
source_context: ContextIn | None = None
class GrantIn(APIModel):
email: Email
can_read: bool = True
can_edit: bool = False
can_share: bool = False
class ExceptionIn(APIModel):
resource_kind: Literal["element", "matter", "task", "deadline"]
resource_id: UUID
context: ContextIn
remove_read: bool = False
remove_edit: bool = False
remove_share: bool = False
class DocumentIn(APIModel):
version: Literal[1] = 1
blocks: list[dict]
class NoteIn(APIModel):
title: str = Field(min_length=1, max_length=200)
document: DocumentIn
context: ContextIn
placement: ContextIn | None = None
chapter_id: UUID | None = None
class NotePatch(APIModel):
expected_version: int = Field(ge=1)
document: DocumentIn
context: ContextIn | None = None
class BindingIn(APIModel):
element_id: UUID
source_context: ContextIn
target: ContextIn
target_context: ContextIn | None = None
chapter_id: UUID | None = None
class AnnotationIn(APIModel):
body: str = Field(min_length=1, max_length=4000)
class DatesIn(APIModel):
document_on: date | None = None
sent_on: date | None = None
received_on: date | None = None
class ExternalIn(APIModel):
title: str = Field(min_length=1, max_length=200)
source: Literal["paperless", "url"]
external_id: str = Field(min_length=1, max_length=200)
context: ContextIn
placement: ContextIn | None = None
chapter_id: UUID | None = None
dates: DatesIn = DatesIn()
class DeleteElementIn(APIModel):
expected_version: int = Field(ge=1)
class TaskIn(APIModel):
title: str = Field(min_length=1, max_length=200)
due_on: date | None = None
matter_id: UUID | None = None
context: ContextIn | None = None
class TaskPatch(APIModel):
expected_version: int = Field(ge=1)
title: str | None = Field(default=None, min_length=1, max_length=200)
due_on: date | None = None
clear_due_on: bool = False
status: Literal["open", "done"] | None = None
context: ContextIn | None = None
class AssigneeIn(APIModel):
email: str | None = None
context: ContextIn | None = None
class DeadlineIn(APIModel):
title: str = Field(min_length=1, max_length=200)
due_on: date
matter_id: UUID | None = None
context: ContextIn | None = None
class DeadlinePatch(APIModel):
expected_version: int = Field(ge=1)
title: str | None = Field(default=None, min_length=1, max_length=200)
due_on: date | None = None
context: ContextIn | None = None
class FulfillIn(APIModel):
expected_version: int = Field(ge=1)
context: ContextIn | None = None
class TaskDeadlineIn(APIModel):
deadline_id: UUID
context: ContextIn | None = None
+1
View File
@@ -0,0 +1 @@
"""Accounts, sessions and cookies."""
+78
View File
@@ -0,0 +1,78 @@
"""Accounts, personal rooms and sessions."""
from __future__ import annotations
from uuid import UUID, uuid4
from app.auth.security import hash_password, hash_secret, new_secret, session_expiry
from app.core.errors import unprocessable
from app.core.settings import Settings
def normalize_email(email: str) -> str:
return email.strip().lower()
def create_account(conn, email: str, display_name: str, password: str) -> dict:
email = normalize_email(email)
display_name = display_name.strip()
if conn.execute("SELECT 1 FROM auth_accounts WHERE email = %s", (email,)).fetchone():
raise unprocessable("Für diese E-Mail gibt es bereits ein Konto.")
account_id = uuid4()
password_hash = hash_password(password)
conn.execute(
"""
INSERT INTO auth_accounts (id, email, display_name, password_hash)
VALUES (%s, %s, %s, %s)
""",
(account_id, email, display_name, password_hash),
)
conn.execute(
"""
INSERT INTO data_rooms (id, kind, name, created_by)
VALUES (%s, 'personal', 'Persönlicher Raum', %s)
""",
(account_id, account_id),
)
return conn.execute(
"SELECT id, email, display_name FROM auth_accounts WHERE id = %s",
(account_id,),
).fetchone()
def start_session(conn, settings: Settings, account_id: UUID) -> tuple[str, str]:
token = new_secret()
csrf = new_secret()
conn.execute(
"""
INSERT INTO auth_sessions (
account_id, secret_hash, csrf_token, scope_kind, scope_id, expires_at
)
VALUES (%s, %s, %s, 'personal', %s, %s)
""",
(account_id, hash_secret(token), csrf, account_id, session_expiry(settings)),
)
return token, csrf
def list_rooms(conn, account_id: UUID) -> list[dict]:
personal = conn.execute(
"SELECT id, kind, name FROM data_rooms WHERE id = %s AND kind = 'personal'",
(account_id,),
).fetchone()
rooms = []
if personal is not None:
rooms.append({"id": str(personal["id"]), "kind": personal["kind"], "name": personal["name"], "role": "owner"})
shared = conn.execute(
"""
SELECT r.id, r.kind, r.name, m.role
FROM room_memberships m
JOIN data_rooms r ON r.id = m.room_id
WHERE m.subject_id = %s AND m.status = 'active' AND r.status = 'active' AND r.kind = 'organization'
ORDER BY r.name, r.id
""",
(account_id,),
).fetchall()
for room in shared:
rooms.append({"id": str(room["id"]), "kind": room["kind"], "name": room["name"], "role": room["role"]})
return rooms
+74
View File
@@ -0,0 +1,74 @@
"""Password hashing, session cookies and CSRF."""
from __future__ import annotations
import hashlib
import secrets
from datetime import timedelta
import bcrypt
from fastapi import Request, Response
from app.core.settings import Settings
from app.core.timeutil import utcnow
HOST_COOKIE = "__Host-jinkendo-session"
PLAIN_COOKIE = "jinkendo-session"
def hash_password(password: str) -> str:
return bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt(rounds=12)).decode("utf-8")
def verify_password(password: str, password_hash: str) -> bool:
try:
return bcrypt.checkpw(password.encode("utf-8"), password_hash.encode("utf-8"))
except ValueError:
return False
def new_secret() -> str:
return secrets.token_urlsafe(32)
def hash_secret(secret: str) -> str:
return hashlib.sha256(secret.encode("utf-8")).hexdigest()
def cookie_name_and_secure(request: Request, settings: Settings) -> tuple[str, bool]:
# __Host- cookies require Secure. Production is only published behind HTTPS.
# Development also serves the documented plain HTTP LAN addresses, which cannot store them.
if settings.tsumugu_env == "production":
return HOST_COOKIE, True
forwarded = request.headers.get("x-forwarded-proto", request.url.scheme)
if forwarded == "https":
return HOST_COOKIE, True
return PLAIN_COOKIE, False
def read_session_token(request: Request) -> str | None:
return request.cookies.get(HOST_COOKIE) or request.cookies.get(PLAIN_COOKIE)
def set_session_cookie(response: Response, request: Request, settings: Settings, token: str) -> None:
name, secure = cookie_name_and_secure(request, settings)
response.set_cookie(
key=name,
value=token,
httponly=True,
secure=secure,
samesite="lax",
path="/",
max_age=settings.session_ttl_hours * 3600,
)
def clear_session_cookie(response: Response, request: Request, settings: Settings) -> None:
name, secure = cookie_name_and_secure(request, settings)
response.delete_cookie(key=name, path="/", secure=secure, httponly=True, samesite="lax")
if name != PLAIN_COOKIE:
response.delete_cookie(key=PLAIN_COOKIE, path="/", httponly=True, samesite="lax")
def session_expiry(settings: Settings):
return utcnow() + timedelta(hours=settings.session_ttl_hours)
+44
View File
@@ -0,0 +1,44 @@
"""Operator commands: migrate, seed demo data, create the first account."""
from __future__ import annotations
import argparse
from app.auth.accounts import create_account
from app.core.settings import get_settings
from app.db.migrate import migrate
from app.seed import seed_demo
import psycopg
from psycopg.rows import dict_row
def main() -> None:
parser = argparse.ArgumentParser(prog="tsumugu")
sub = parser.add_subparsers(dest="command", required=True)
sub.add_parser("migrate")
sub.add_parser("seed-demo")
create = sub.add_parser("create-account")
create.add_argument("--email", required=True)
create.add_argument("--name", required=True)
create.add_argument("--password", required=True)
args = parser.parse_args()
settings = get_settings()
if args.command == "migrate":
applied = migrate(settings)
print("applied" if applied else "up to date")
return
if args.command == "seed-demo":
created = seed_demo(settings)
print("seeded" if created else "unchanged")
return
if len(args.password) < 10:
raise SystemExit("password must be at least 10 characters")
with psycopg.connect(settings.dsn(), row_factory=dict_row) as conn:
account = create_account(conn, args.email, args.name, args.password)
conn.commit()
print(account["id"])
if __name__ == "__main__":
main()
+1
View File
@@ -0,0 +1 @@
"""Notes, bindings, files and external references."""
+25
View File
@@ -0,0 +1,25 @@
"""Bounded note documents. Only paragraph text is stored."""
from __future__ import annotations
from app.core.errors import unprocessable
def clean_document(document: dict) -> dict:
blocks = document.get("blocks")
if not isinstance(blocks, list) or len(blocks) > 400:
raise unprocessable("Die Notiz hat kein gültiges Dokument.")
clean = []
for block in blocks:
if not isinstance(block, dict) or set(block) - {"type", "text"}:
raise unprocessable("Die Notiz enthält einen nicht unterstützten Block.")
if block.get("type") != "paragraph" or not isinstance(block.get("text"), str):
raise unprocessable("Die Notiz enthält einen nicht unterstützten Block.")
if len(block["text"]) > 20000:
raise unprocessable("Ein Absatz ist zu lang.")
clean.append({"type": "paragraph", "text": block["text"]})
return {"version": 1, "blocks": clean}
def document_text(document: dict) -> str:
return "\n".join(block["text"] for block in document.get("blocks", []))
+1
View File
@@ -0,0 +1 @@
"""Core settings, errors and request helpers."""
+71
View File
@@ -0,0 +1,71 @@
"""RFC 9457 problem responses. Hidden objects use the same 404 as missing ones."""
from __future__ import annotations
from fastapi import Request
from fastapi.responses import JSONResponse
class Problem(Exception):
def __init__(self, status: int, title: str, detail: str, code: str) -> None:
super().__init__(detail)
self.status = status
self.title = title
self.detail = detail
self.code = code
def body(self, instance: str) -> dict:
return {
"type": "about:blank",
"title": self.title,
"status": self.status,
"detail": self.detail,
"instance": instance,
"code": self.code,
}
def unauthorized() -> Problem:
return Problem(401, "Anmeldung erforderlich", "Die Sitzung fehlt oder ist abgelaufen.", "unauthorized")
def forbidden(detail: str = "Diese Aktion ist im gewählten Kontext nicht erlaubt.") -> Problem:
return Problem(403, "Keine Berechtigung", detail, "forbidden")
def not_found() -> Problem:
return Problem(404, "Nicht gefunden", "Der Eintrag ist nicht vorhanden.", "not_found")
def conflict() -> Problem:
return Problem(
409,
"Versionskonflikt",
"Der Stand hat sich geändert. Bitte neu laden.",
"conflict",
)
def unprocessable(detail: str) -> Problem:
return Problem(422, "Eingabe ungültig", detail, "unprocessable")
def too_many() -> Problem:
return Problem(429, "Zu viele Versuche", "Bitte kurz warten und es erneut versuchen.", "too_many_requests")
def storage_unavailable() -> Problem:
return Problem(
503,
"Speicher nicht verfügbar",
"Die Datei kann gerade nicht gelesen oder geschrieben werden.",
"storage_unavailable",
)
def problem_response(problem: Problem, request: Request) -> JSONResponse:
return JSONResponse(
status_code=problem.status,
content=problem.body(request.url.path),
media_type="application/problem+json",
)
+47
View File
@@ -0,0 +1,47 @@
"""Process settings. Unknown environments refuse to start."""
from __future__ import annotations
from functools import lru_cache
from typing import Literal
from pydantic import field_validator
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
model_config = SettingsConfigDict(extra="ignore")
tsumugu_env: Literal["development", "production"]
db_host: str = "localhost"
db_port: int = 5432
db_name: str
db_user: str
db_password: str
db_runtime_user: str = "tsumugu_runtime"
app_url: str = "http://localhost:5173"
allowed_origins: str = "http://localhost:5173,http://localhost:3094"
media_root: str = "data/media"
seed_demo: bool = False
session_ttl_hours: int = 336
upload_max_bytes: int = 20 * 1024 * 1024
@field_validator("allowed_origins")
@classmethod
def strip_origins(cls, value: str) -> str:
return value.strip()
@property
def origin_set(self) -> set[str]:
return {item.strip() for item in self.allowed_origins.split(",") if item.strip()}
def dsn(self, user: str | None = None) -> str:
return (
f"host={self.db_host} port={self.db_port} dbname={self.db_name} "
f"user={user or self.db_user} password={self.db_password} connect_timeout=5"
)
@lru_cache
def get_settings() -> Settings:
return Settings()
+23
View File
@@ -0,0 +1,23 @@
"""UTC formatting for API values."""
from __future__ import annotations
from datetime import date, datetime, timezone
def utcnow() -> datetime:
return datetime.now(timezone.utc)
def dump_dt(value: datetime | None) -> str | None:
if value is None:
return None
if value.tzinfo is None:
value = value.replace(tzinfo=timezone.utc)
return value.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
def dump_date(value: date | None) -> str | None:
if value is None:
return None
return value.isoformat()
+1
View File
@@ -0,0 +1 @@
"""Database pool and migrations."""
+90
View File
@@ -0,0 +1,90 @@
"""SQL migrations with a checksum ledger, then a runtime role without DDL."""
from __future__ import annotations
import hashlib
from pathlib import Path
import psycopg
from psycopg import ClientCursor, sql
from app.core.settings import Settings, get_settings
MIGRATIONS = Path(__file__).resolve().parent.parent.parent / "migrations"
def _checksum(path: Path) -> str:
return hashlib.sha256(path.read_bytes()).hexdigest()
def migrate(settings: Settings | None = None) -> list[str]:
settings = settings or get_settings()
applied: list[str] = []
with psycopg.connect(settings.dsn(), autocommit=True, cursor_factory=ClientCursor) as conn:
conn.execute(
"""
CREATE TABLE IF NOT EXISTS schema_migrations (
version text PRIMARY KEY,
checksum text NOT NULL,
applied_at timestamptz NOT NULL DEFAULT now()
)
"""
)
for path in sorted(MIGRATIONS.glob("*.sql")):
version = path.name
checksum = _checksum(path)
row = conn.execute(
"SELECT checksum FROM schema_migrations WHERE version = %s",
(version,),
).fetchone()
if row is not None:
if row[0] != checksum:
raise RuntimeError(f"checksum mismatch for migration {version}")
continue
with conn.transaction():
conn.execute(path.read_text(encoding="utf-8"))
conn.execute(
"INSERT INTO schema_migrations (version, checksum) VALUES (%s, %s)",
(version, checksum),
)
applied.append(version)
_ensure_runtime_role(conn, settings)
return applied
def _ensure_runtime_role(conn: psycopg.Connection, settings: Settings) -> None:
role = sql.Identifier(settings.db_runtime_user)
database = sql.Identifier(settings.db_name)
owner = sql.Identifier(settings.db_user)
password = sql.Literal(settings.db_password)
exists = conn.execute(
"SELECT 1 FROM pg_roles WHERE rolname = %s",
(settings.db_runtime_user,),
).fetchone()
if exists is None:
conn.execute(
sql.SQL(
"CREATE ROLE {} LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT PASSWORD {}"
).format(role, password)
)
else:
conn.execute(
sql.SQL(
"ALTER ROLE {} WITH LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT PASSWORD {}"
).format(role, password)
)
conn.execute(sql.SQL("GRANT CONNECT ON DATABASE {} TO {}").format(database, role))
conn.execute(sql.SQL("GRANT USAGE ON SCHEMA public TO {}").format(role))
conn.execute(sql.SQL("REVOKE CREATE ON SCHEMA public FROM {}").format(role))
conn.execute(
sql.SQL(
"GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO {}"
).format(role)
)
conn.execute(sql.SQL("REVOKE ALL ON TABLE schema_migrations FROM {}").format(role))
conn.execute(
sql.SQL(
"ALTER DEFAULT PRIVILEGES FOR ROLE {} IN SCHEMA public "
"GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO {}"
).format(owner, role)
)
+19
View File
@@ -0,0 +1,19 @@
"""Runtime connection pool. Importing the app does not open it."""
from __future__ import annotations
from psycopg.rows import dict_row
from psycopg_pool import ConnectionPool
from app.core.settings import Settings
def open_pool(settings: Settings) -> ConnectionPool:
return ConnectionPool(
conninfo=settings.dsn(settings.db_runtime_user),
kwargs={"row_factory": dict_row},
min_size=1,
max_size=10,
open=True,
timeout=10,
)
+18
View File
@@ -0,0 +1,18 @@
"""Migrate, optionally seed development data, then serve."""
from __future__ import annotations
import os
from app.db.migrate import migrate
from app.seed import seed_demo
def main() -> None:
migrate()
seed_demo()
os.execvp("uvicorn", ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"])
if __name__ == "__main__":
main()
+119
View File
@@ -0,0 +1,119 @@
"""Application factory. Importing this module does not open a database connection."""
from __future__ import annotations
import logging
from contextlib import asynccontextmanager
from fastapi import FastAPI, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from app.api.routes import router
from app.core.errors import Problem, problem_response
from app.core.settings import get_settings
from app.db.pool import open_pool
logger = logging.getLogger("tsumugu")
def _database_ok(app: FastAPI) -> bool:
pool = getattr(app.state, "pool", None)
if pool is None:
return False
try:
with pool.connection() as conn:
conn.execute("SELECT 1")
conn.rollback()
return True
except Exception:
logger.warning("database check failed")
return False
def create_app() -> FastAPI:
settings = get_settings()
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s %(message)s")
@asynccontextmanager
async def lifespan(app: FastAPI):
app.state.pool = open_pool(settings)
try:
yield
finally:
app.state.pool.close()
app = FastAPI(title="Tsumugu", docs_url=None, redoc_url=None, openapi_url=None, lifespan=lifespan)
app.state.settings = settings
@app.middleware("http")
async def origin_guard(request: Request, call_next):
if request.method not in {"GET", "HEAD", "OPTIONS"} and request.url.path.startswith("/api/"):
origin = request.headers.get("origin")
if origin not in settings.origin_set:
problem = Problem(403, "Keine Berechtigung", "Der Ursprung der Anfrage ist nicht erlaubt.", "forbidden")
return problem_response(problem, request)
response = await call_next(request)
logger.info("%s %s -> %s", request.method, request.url.path, response.status_code)
return response
@app.exception_handler(Problem)
async def handle_problem(request: Request, exc: Problem):
return problem_response(exc, request)
@app.exception_handler(RequestValidationError)
async def handle_validation(request: Request, exc: RequestValidationError):
return JSONResponse(
status_code=422,
content={
"type": "about:blank",
"title": "Eingabe ungültig",
"status": 422,
"detail": "Die Eingabe ist unvollständig oder ungültig.",
"instance": request.url.path,
"code": "unprocessable",
},
media_type="application/problem+json",
)
@app.exception_handler(Exception)
async def handle_unexpected(request: Request, exc: Exception):
logger.exception("unhandled error")
return JSONResponse(
status_code=500,
content={
"type": "about:blank",
"title": "Unerwarteter Fehler",
"status": 500,
"detail": "Die Aktion konnte nicht abgeschlossen werden.",
"instance": request.url.path,
"code": "internal",
},
media_type="application/problem+json",
)
@app.get("/api/health")
def api_health():
ok = _database_ok(app)
return JSONResponse(
status_code=200 if ok else 503,
content={"status": "ok" if ok else "degraded", "app": "tsumugu"},
)
@app.get("/health/live")
def health_live():
return {"status": "ok", "app": "tsumugu"}
@app.get("/health/ready")
def health_ready():
ok = _database_ok(app)
return JSONResponse(
status_code=200 if ok else 503,
content={"status": "ok" if ok else "degraded", "app": "tsumugu"},
)
app.include_router(router)
return app
app = create_app()
+1
View File
@@ -0,0 +1 @@
"""Private file storage. Paths are server-generated."""
+71
View File
@@ -0,0 +1,71 @@
"""Sniff uploads and keep client names out of the storage path."""
from __future__ import annotations
import hashlib
from pathlib import Path
from uuid import UUID
from app.core.errors import storage_unavailable, unprocessable
ALLOWED = {
"application/pdf": "pdf",
"image/png": "png",
"image/jpeg": "jpg",
"image/webp": "webp",
}
def sniff(data: bytes) -> str:
if data.startswith(b"%PDF"):
return "application/pdf"
if data.startswith(b"\x89PNG\r\n\x1a\n"):
return "image/png"
if data.startswith(b"\xff\xd8\xff"):
return "image/jpeg"
if len(data) >= 12 and data[:4] == b"RIFF" and data[8:12] == b"WEBP":
return "image/webp"
raise unprocessable("Erlaubt sind PDF, PNG, JPEG und WebP.")
def asset_path(media_root: str, asset_id: UUID) -> Path:
root = Path(media_root).resolve()
root.mkdir(parents=True, exist_ok=True)
target = (root / str(asset_id)).resolve()
if target.parent != root:
raise unprocessable("Ungültiger Speicherpfad.")
return target
def write_bytes(path: Path, data: bytes) -> None:
try:
path.write_bytes(data)
except OSError as exc:
raise storage_unavailable() from exc
def read_bytes(path: Path) -> bytes:
try:
if not path.is_file():
raise storage_unavailable()
return path.read_bytes()
except OSError as exc:
raise storage_unavailable() from exc
def sha256(data: bytes) -> str:
return hashlib.sha256(data).hexdigest()
def display_filename(name: str) -> str:
cleaned = []
for char in name.replace("\\", "/").split("/")[-1]:
if char.isprintable() and char not in {'"', "\r", "\n", ":"}:
cleaned.append(char)
text = "".join(cleaned).strip() or "datei"
return text[:240]
def content_disposition(filename: str) -> str:
safe = display_filename(filename).replace('"', "")
return f'attachment; filename="{safe}"'
+784
View File
@@ -0,0 +1,784 @@
"""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.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
from app.core.timeutil import utcnow
from app.media.storage import asset_path, display_filename, sha256, sniff, write_bytes
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 create_case(conn, actor: UUID, scope_id: UUID, title: str, parent_case_id: UUID | None, rights_mode: str) -> dict:
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
)
VALUES (%s, %s, %s, %s, 'explicit')
RETURNING *
""",
(scope_id, actor, actor, title),
).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
)
VALUES (%s, %s, %s, %s, %s, %s)
RETURNING *
""",
(parent["home_scope_id"], actor, actor, title, parent["id"], rights_mode),
).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 create_chapter(conn, actor: UUID, kind: str, container_id: UUID, title: str, position: int | None, context: Ctx | 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")
if position is None:
column = "case_id" if kind == "case" else "matter_id"
current = conn.execute(
f"SELECT COALESCE(MAX(position), -1) + 1 AS pos FROM chapters WHERE {column} = %s",
(container_id,),
).fetchone()
position = int(current["pos"])
if kind == "case":
row = conn.execute(
"""
INSERT INTO chapters (home_scope_id, case_id, title, position)
VALUES (%s, %s, %s, %s) RETURNING *
""",
(container["home_scope_id"], container_id, title.strip(), position),
).fetchone()
else:
row = conn.execute(
"""
INSERT INTO chapters (home_scope_id, matter_id, title, position)
VALUES (%s, %s, %s, %s) RETURNING *
""",
(container["home_scope_id"], container_id, title.strip(), position),
).fetchone()
audit(conn, actor, container["home_scope_id"], "chapter_created", kind, container_id, context)
return row
def create_matter(conn, actor: UUID, scope_id: UUID, title: str, parent_matter_id: UUID | None, context: Ctx | None) -> dict:
title = title.strip()
if parent_matter_id is None:
row = conn.execute(
"""
INSERT INTO matters (home_scope_id, owner_subject_id, created_by, title)
VALUES (%s, %s, %s, %s) RETURNING *
""",
(scope_id, actor, actor, title),
).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
)
VALUES (%s, %s, %s, %s, %s) RETURNING *
""",
(parent["home_scope_id"], actor, actor, title, parent["id"]),
).fetchone()
audit(conn, actor, row["home_scope_id"], "matter_created", "matter", row["id"], context)
return row
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 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) -> 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()
existing = conn.execute(
"""
SELECT id 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 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
)
VALUES (%s, %s, %s, %s, %s, %s, false, false, %s)
RETURNING *
""",
(grantee_id, kind, resource_id, can_read, can_edit, can_share, actor),
).fetchone()
else:
row = conn.execute(
"""
UPDATE access_grants
SET can_read = %s, can_edit = %s, can_share = %s
WHERE id = %s
RETURNING *
""",
(can_read, can_edit, can_share, 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 create_note(conn, actor: UUID, scope_id: UUID, title: str, document: dict, context: Ctx, placement: Ctx | None, chapter_id: UUID | None) -> dict:
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)
audit(conn, actor, scope_id, "note_created", "element", element["id"], rights_context or target)
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 not_found()
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) -> dict:
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) VALUES (%s, %s, %s)",
(element["id"], source, external_id.strip()),
)
binding = insert_binding(conn, element["id"], target.kind, target.id, chapter_id, actor)
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]) -> dict:
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)
element = _new_element(conn, actor, scope_id, title, "file")
asset_id = uuid4()
path = asset_path(media_root, asset_id)
write_bytes(path, data)
rollback_files.append(path)
conn.execute(
"""
INSERT INTO media_assets (
id, element_id, owner_subject_id, home_scope_id, original_filename,
content_type, byte_size, sha256, status
)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, 'active')
""",
(
asset_id,
element["id"],
actor,
scope_id,
display_filename(filename),
content_type,
len(data),
sha256(data),
),
)
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)
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)
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(asset_path(media_root, asset["id"]))
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:
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:
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),
)
+490
View File
@@ -0,0 +1,490 @@
"""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,
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
def rights_dict(rights) -> dict:
return rights.as_dict()
def _chapters(conn, kind: str, container_id: UUID) -> list[dict]:
column = "case_id" if kind == "case" else "matter_id"
rows = conn.execute(
f"SELECT id, title, position FROM chapters WHERE {column} = %s ORDER BY position, created_at",
(container_id,),
).fetchall()
return [{"id": str(row["id"]), "title": row["title"], "position": row["position"]} for row in rows]
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 _element_body(conn, element: dict) -> dict:
payload = {
"id": str(element["id"]),
"kind": element["kind"],
"title": element["title"],
"version": element["version"],
"owner_subject_id": str(element["owner_subject_id"]),
"dates": _dates(conn, element),
}
if element["kind"] == "note":
body = conn.execute(
"SELECT document_json FROM note_bodies WHERE element_id = %s",
(element["id"],),
).fetchone()
payload["document"] = body["document_json"] if body else {"version": 1, "blocks": []}
elif element["kind"] == "file":
asset = conn.execute(
"""
SELECT original_filename, content_type, byte_size, status
FROM media_assets WHERE element_id = %s
""",
(element["id"],),
).fetchone()
if asset is not None:
payload["file"] = {
"filename": asset["original_filename"],
"content_type": asset["content_type"],
"byte_size": asset["byte_size"],
"status": asset["status"],
}
elif element["kind"] == "external_ref":
ref = conn.execute(
"SELECT source, external_id FROM external_references WHERE element_id = %s",
(element["id"],),
).fetchone()
if ref is not None:
payload["external"] = {"source": ref["source"], "external_id": ref["external_id"]}
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 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
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"]),
"element": _element_body(conn, element),
}
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, 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"],
}
for row in rows
]
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["home_scope_name"] = room_name(conn, case["home_scope_id"])
payload["is_owner"] = case["owner_subject_id"] == actor
payload["chapters"] = _chapters(conn, "case", case["id"])
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(
{
"id": str(link["id"]),
"link_id": str(link["link_id"]),
"title": link["title"],
"status": link["record_status"],
}
)
payload["matters"] = matters
context = Ctx("case", case["id"])
bindings = []
for binding in conn.execute(
"""
SELECT * FROM bindings
WHERE context_kind = 'case' AND context_id = %s
ORDER BY position, created_at
""",
(case["id"],),
).fetchall():
item = binding_payload(conn, actor, binding, context)
if item is not None:
bindings.append(item)
payload["bindings"] = bindings
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"],
"parent_matter_id": str(matter["parent_matter_id"]) if matter["parent_matter_id"] else None,
"home_scope_id": str(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,
"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,
"rights": rights.as_dict(),
"context": None if context is None else context.as_dict(),
"chapters": _chapters(conn, "matter", matter["id"]),
}
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
bindings = []
for binding in conn.execute(
"""
SELECT * FROM bindings
WHERE context_kind = 'matter' AND context_id = %s
ORDER BY position, created_at
""",
(matter["id"],),
).fetchall():
item = binding_payload(conn, actor, binding, page)
if item is not None:
bindings.append(item)
payload["bindings"] = bindings
payload["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:
payload["tasks"].append(task_payload(conn, actor, task, task_right))
payload["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:
payload["deadlines"].append(deadline_payload(conn, actor, deadline))
visible_deadlines.add(deadline["id"])
visible_tasks = {UUID(item["id"]) for item in payload["tasks"]}
links = []
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"])})
payload["task_deadline_links"] = 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 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
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",
"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",
"correspondence_document": "Dokumentdatum",
"correspondence_sent": "Versand",
"correspondence_received": "Zugang",
"correspondence_recorded": "Erfassung",
"chapter_created": "Kapitel angelegt",
}
+211
View File
@@ -0,0 +1,211 @@
"""Synthetic development accounts and a rental matter. Never runs in production."""
from __future__ import annotations
from datetime import date
from pathlib import Path
import psycopg
from psycopg.rows import dict_row
from app.access.policy import Ctx
from app.auth.accounts import create_account
from app.core.errors import not_found
from app.core.settings import Settings, get_settings
from app.ops import (
add_annotation,
assign_task,
bind_element,
create_case,
create_chapter,
create_deadline,
create_external,
create_file,
create_matter,
create_note,
create_task,
grant_access,
link_matter_to_case,
link_task_deadline,
)
ADA_EMAIL = "ada@example.test"
BEN_EMAIL = "ben@example.test"
ADA_PASSWORD = "Beispiel-Ada-2026"
BEN_PASSWORD = "Beispiel-Ben-2026"
SAMPLE_PDF = b"""%PDF-1.1
1 0 obj<</Type/Catalog/Pages 2 0 R>>endobj
2 0 obj<</Type/Pages/Count 1/Kids[3 0 R]>>endobj
3 0 obj<</Type/Page/Parent 2 0 R/MediaBox[0 0 320 160]/Contents 4 0 R>>endobj
4 0 obj<</Length 55>>stream
BT /F1 12 Tf 40 90 Td (Mietschreiben Beispiel) Tj ET
endstream
endobj
trailer<</Root 1 0 R>>
%%EOF
"""
def demo_public(settings: Settings) -> dict:
if settings.tsumugu_env != "development" or not settings.seed_demo:
raise not_found()
return {
"accounts": [
{"email": ADA_EMAIL, "password": ADA_PASSWORD, "display_name": "Ada Beispiel"},
{"email": BEN_EMAIL, "password": BEN_PASSWORD, "display_name": "Ben Beispiel"},
]
}
def seed_demo(settings: Settings | None = None) -> bool:
settings = settings or get_settings()
if settings.tsumugu_env != "development" or not settings.seed_demo:
return False
cleanup: list[Path] = []
with psycopg.connect(settings.dsn(), row_factory=dict_row) as conn:
try:
if conn.execute("SELECT 1 FROM auth_accounts WHERE email = %s", (ADA_EMAIL,)).fetchone():
return False
ada = create_account(conn, ADA_EMAIL, "Ada Beispiel", ADA_PASSWORD)
ben = create_account(conn, BEN_EMAIL, "Ben Beispiel", BEN_PASSWORD)
room = conn.execute(
"""
INSERT INTO data_rooms (id, kind, name, created_by)
VALUES (gen_random_uuid(), 'organization', 'Haushalt Musterstraße', %s)
RETURNING id
""",
(ada["id"],),
).fetchone()
conn.execute(
"INSERT INTO room_memberships (room_id, subject_id, role) VALUES (%s, %s, 'manager'), (%s, %s, 'member')",
(room["id"], ada["id"], room["id"], ben["id"]),
)
private_case = create_case(conn, ada["id"], ada["id"], "Persönliche Verhandlungsstrategie", None, "explicit")
shared_case = create_case(conn, ada["id"], ada["id"], "Mietstreit Musterstraße 12", None, "explicit")
grant_access(conn, ada["id"], "case", shared_case["id"], ben["id"], True, True, False, None)
strategy = create_matter(conn, ada["id"], ada["id"], "Interne Verhandlungsstrategie", None, None)
moisture = create_matter(conn, ada["id"], ada["id"], "Mängelanzeige Feuchtigkeit", None, None)
link_matter_to_case(conn, ada["id"], moisture["id"], shared_case["id"], None)
link_matter_to_case(conn, ada["id"], strategy["id"], private_case["id"], None)
note = create_note(
conn,
ada["id"],
ada["id"],
"Gespräch mit der Hausverwaltung",
{
"version": 1,
"blocks": [
{
"type": "paragraph",
"text": (
"Am 1. Oktober die Feuchtigkeit im Schlafzimmer angezeigt. "
"Die Verwaltung will bis Ende November antworten."
),
}
],
},
Ctx("case", shared_case["id"]),
None,
None,
)
matter_binding = bind_element(
conn,
ada["id"],
note["element"]["id"],
Ctx("case", shared_case["id"]),
Ctx("matter", moisture["id"]),
None,
None,
)
add_annotation(
conn,
ada["id"],
note["binding"]["id"],
"Nur in der Akte: Original im blauen Ordner.",
Ctx("case", shared_case["id"]),
)
add_annotation(
conn,
ada["id"],
matter_binding["id"],
"Nur in diesem Vorgang: Zeugin Frau Keller erinnern.",
Ctx("matter", moisture["id"]),
)
create_note(
conn,
ada["id"],
ada["id"],
"Nicht weitergeben",
{
"version": 1,
"blocks": [
{
"type": "paragraph",
"text": "Vergleich nur anbieten, wenn die Gegenseite zuerst einen Betrag nennt.",
}
],
},
Ctx("case", private_case["id"]),
None,
None,
)
chapter = create_chapter(conn, ada["id"], "matter", moisture["id"], "Schriftwechsel", 0, None)
create_file(
conn,
ada["id"],
ada["id"],
"Schreiben an die Hausverwaltung",
"Schreiben-Hausverwaltung.pdf",
SAMPLE_PDF,
Ctx("matter", moisture["id"]),
None,
chapter["id"],
date(2026, 10, 1),
date(2026, 10, 2),
None,
settings.media_root,
settings.upload_max_bytes,
cleanup,
)
create_external(
conn,
ada["id"],
ada["id"],
"Antwort der Hausverwaltung",
"paperless",
"4821",
Ctx("matter", moisture["id"]),
None,
chapter["id"],
date(2026, 10, 8),
None,
date(2026, 10, 10),
)
task = create_task(
conn,
ada["id"],
ada["id"],
"Unterlagen für die Antwort zusammenstellen",
date(2026, 11, 25),
moisture["id"],
None,
)
assign_task(conn, ada["id"], task["id"], ben["id"], None)
deadline = create_deadline(
conn,
ada["id"],
ada["id"],
"Antwort an die Gegenseite",
date(2026, 11, 30),
moisture["id"],
None,
)
link_task_deadline(conn, ada["id"], task["id"], deadline["id"], None)
conn.commit()
return True
except Exception:
conn.rollback()
for path in cleanup:
path.unlink(missing_ok=True)
raise
+3 -40
View File
@@ -1,42 +1,5 @@
"""Tsumugu — schmales Startgerüst, damit der Pi-Deploy einen Health-Check hat."""
"""Uvicorn entry: `uvicorn main:app`."""
from __future__ import annotations
from app.main import app
import os
import psycopg2
from fastapi import FastAPI
from fastapi.responses import JSONResponse
app = FastAPI(title="Tsumugu", docs_url=None, redoc_url=None)
def _database_status() -> str:
try:
connection = psycopg2.connect(
host=os.environ.get("DB_HOST", "postgres"),
port=os.environ.get("DB_PORT", "5432"),
dbname=os.environ.get("DB_NAME", "tsumugu"),
user=os.environ.get("DB_USER", "tsumugu"),
password=os.environ.get("DB_PASSWORD", ""),
connect_timeout=3,
)
connection.close()
except Exception:
return "error"
return "ok"
@app.get("/api/health")
def api_health():
database = _database_status()
status = "ok" if database == "ok" else "degraded"
return JSONResponse(
status_code=200 if database == "ok" else 503,
content={
"status": status,
"app": "tsumugu",
"env": os.environ.get("TSUMUGU_ENV", "development"),
"db": database,
},
)
__all__ = ["app"]
@@ -0,0 +1,356 @@
-- Erster Fachschnitt: Identität, Struktur, Inhalte, Nachverfolgung, eigene Dateien.
-- Finanz-, Zusammenstellungs- und Paperless-Abgleichstabellen gehören nicht in diese Lieferung.
CREATE TABLE auth_accounts (
id uuid PRIMARY KEY,
email text NOT NULL UNIQUE,
display_name text NOT NULL,
password_hash text NOT NULL,
status text NOT NULL DEFAULT 'active',
created_at timestamptz NOT NULL DEFAULT now(),
CONSTRAINT auth_accounts_status CHECK (status IN ('active', 'disabled')),
CONSTRAINT auth_accounts_email_len CHECK (char_length(email) <= 320),
CONSTRAINT auth_accounts_name_len CHECK (char_length(display_name) BETWEEN 1 AND 120)
);
CREATE TABLE data_rooms (
id uuid PRIMARY KEY,
kind text NOT NULL,
name text NOT NULL,
status text NOT NULL DEFAULT 'active',
created_by uuid NOT NULL REFERENCES auth_accounts (id),
created_at timestamptz NOT NULL DEFAULT now(),
CONSTRAINT data_rooms_kind CHECK (kind IN ('personal', 'organization')),
CONSTRAINT data_rooms_status CHECK (status IN ('active', 'archived')),
CONSTRAINT data_rooms_name_len CHECK (char_length(name) BETWEEN 1 AND 160)
);
CREATE TABLE auth_sessions (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
account_id uuid NOT NULL REFERENCES auth_accounts (id),
secret_hash text NOT NULL UNIQUE,
csrf_token text NOT NULL,
scope_kind text NOT NULL,
scope_id uuid NOT NULL REFERENCES data_rooms (id),
epoch integer NOT NULL DEFAULT 1,
expires_at timestamptz NOT NULL,
revoked_at timestamptz,
created_at timestamptz NOT NULL DEFAULT now(),
CONSTRAINT auth_sessions_scope_kind CHECK (scope_kind IN ('personal', 'organization'))
);
CREATE INDEX auth_sessions_account ON auth_sessions (account_id);
CREATE TABLE auth_invitations (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
email text NOT NULL,
room_id uuid NOT NULL REFERENCES data_rooms (id),
token_hash text NOT NULL UNIQUE,
invited_by uuid NOT NULL REFERENCES auth_accounts (id),
expires_at timestamptz NOT NULL,
accepted_at timestamptz,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE room_memberships (
room_id uuid NOT NULL REFERENCES data_rooms (id),
subject_id uuid NOT NULL REFERENCES auth_accounts (id),
role text NOT NULL,
status text NOT NULL DEFAULT 'active',
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (room_id, subject_id),
CONSTRAINT room_memberships_role CHECK (role IN ('member', 'manager')),
CONSTRAINT room_memberships_status CHECK (status IN ('active', 'removed'))
);
CREATE TABLE cases (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
home_scope_id uuid NOT NULL REFERENCES data_rooms (id),
owner_subject_id uuid NOT NULL REFERENCES auth_accounts (id),
created_by uuid NOT NULL REFERENCES auth_accounts (id),
version integer NOT NULL DEFAULT 1,
title text NOT NULL,
parent_case_id uuid,
rights_mode text NOT NULL DEFAULT 'explicit',
record_status text NOT NULL DEFAULT 'open',
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
deleted_at timestamptz,
CONSTRAINT cases_title_len CHECK (char_length(title) BETWEEN 1 AND 200),
CONSTRAINT cases_rights_mode CHECK (rights_mode IN ('inherit_parent', 'explicit')),
CONSTRAINT cases_status CHECK (record_status IN ('open', 'closed')),
CONSTRAINT cases_root_explicit CHECK (
(parent_case_id IS NULL AND rights_mode = 'explicit')
OR parent_case_id IS NOT NULL
),
UNIQUE (id, home_scope_id)
);
ALTER TABLE cases
ADD CONSTRAINT cases_parent_same_scope
FOREIGN KEY (parent_case_id, home_scope_id) REFERENCES cases (id, home_scope_id);
CREATE INDEX cases_owner ON cases (owner_subject_id) WHERE deleted_at IS NULL;
CREATE INDEX cases_home ON cases (home_scope_id) WHERE deleted_at IS NULL;
CREATE TABLE matters (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
home_scope_id uuid NOT NULL REFERENCES data_rooms (id),
owner_subject_id uuid NOT NULL REFERENCES auth_accounts (id),
created_by uuid NOT NULL REFERENCES auth_accounts (id),
version integer NOT NULL DEFAULT 1,
title text NOT NULL,
parent_matter_id uuid,
record_status text NOT NULL DEFAULT 'open',
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
deleted_at timestamptz,
CONSTRAINT matters_title_len CHECK (char_length(title) BETWEEN 1 AND 200),
CONSTRAINT matters_status CHECK (record_status IN ('open', 'closed')),
UNIQUE (id, home_scope_id)
);
ALTER TABLE matters
ADD CONSTRAINT matters_parent_same_scope
FOREIGN KEY (parent_matter_id, home_scope_id) REFERENCES matters (id, home_scope_id);
CREATE INDEX matters_owner ON matters (owner_subject_id) WHERE deleted_at IS NULL;
CREATE TABLE chapters (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
home_scope_id uuid NOT NULL REFERENCES data_rooms (id),
case_id uuid,
matter_id uuid,
title text NOT NULL,
position integer NOT NULL DEFAULT 0,
created_at timestamptz NOT NULL DEFAULT now(),
CONSTRAINT chapters_title_len CHECK (char_length(title) BETWEEN 1 AND 200),
CONSTRAINT chapters_one_container CHECK ((case_id IS NULL) <> (matter_id IS NULL))
);
ALTER TABLE chapters
ADD CONSTRAINT chapters_case_same_scope
FOREIGN KEY (case_id, home_scope_id) REFERENCES cases (id, home_scope_id);
ALTER TABLE chapters
ADD CONSTRAINT chapters_matter_same_scope
FOREIGN KEY (matter_id, home_scope_id) REFERENCES matters (id, home_scope_id);
CREATE TABLE matter_case_links (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
matter_id uuid NOT NULL REFERENCES matters (id),
case_id uuid NOT NULL REFERENCES cases (id),
created_by uuid NOT NULL REFERENCES auth_accounts (id),
created_at timestamptz NOT NULL DEFAULT now(),
UNIQUE (matter_id, case_id)
);
CREATE INDEX matter_case_links_case ON matter_case_links (case_id);
CREATE TABLE case_link_blocks (
link_id uuid NOT NULL REFERENCES matter_case_links (id) ON DELETE CASCADE,
element_id uuid NOT NULL,
PRIMARY KEY (link_id, element_id)
);
CREATE TABLE matter_cross_links (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
from_matter_id uuid NOT NULL REFERENCES matters (id),
to_matter_id uuid NOT NULL REFERENCES matters (id),
created_by uuid NOT NULL REFERENCES auth_accounts (id),
created_at timestamptz NOT NULL DEFAULT now(),
UNIQUE (from_matter_id, to_matter_id),
CONSTRAINT matter_cross_links_distinct CHECK (from_matter_id <> to_matter_id)
);
CREATE TABLE elements (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
home_scope_id uuid NOT NULL REFERENCES data_rooms (id),
owner_subject_id uuid NOT NULL REFERENCES auth_accounts (id),
created_by uuid NOT NULL REFERENCES auth_accounts (id),
version integer NOT NULL DEFAULT 1,
title text NOT NULL,
kind text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
deleted_at timestamptz,
CONSTRAINT elements_title_len CHECK (char_length(title) BETWEEN 1 AND 200),
CONSTRAINT elements_kind CHECK (kind IN ('note', 'file', 'external_ref')),
UNIQUE (id, home_scope_id)
);
CREATE INDEX elements_owner ON elements (owner_subject_id) WHERE deleted_at IS NULL;
CREATE TABLE note_bodies (
element_id uuid PRIMARY KEY REFERENCES elements (id),
document_json jsonb NOT NULL,
version integer NOT NULL DEFAULT 1,
updated_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE correspondence_dates (
element_id uuid PRIMARY KEY REFERENCES elements (id),
document_on date,
sent_on date,
received_on date
);
CREATE TABLE external_references (
element_id uuid PRIMARY KEY REFERENCES elements (id),
source text NOT NULL,
external_id text NOT NULL,
CONSTRAINT external_references_source CHECK (source IN ('paperless', 'url')),
CONSTRAINT external_references_id_len CHECK (char_length(external_id) BETWEEN 1 AND 200)
);
CREATE TABLE bindings (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
element_id uuid NOT NULL REFERENCES elements (id),
context_kind text NOT NULL,
context_id uuid NOT NULL,
chapter_id uuid REFERENCES chapters (id),
position integer NOT NULL DEFAULT 0,
created_by uuid NOT NULL REFERENCES auth_accounts (id),
created_at timestamptz NOT NULL DEFAULT now(),
UNIQUE (element_id, context_kind, context_id),
CONSTRAINT bindings_context_kind CHECK (context_kind IN ('case', 'matter'))
);
CREATE INDEX bindings_context ON bindings (context_kind, context_id);
CREATE TABLE context_annotations (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
binding_id uuid NOT NULL REFERENCES bindings (id) ON DELETE CASCADE,
body text NOT NULL,
author_subject_id uuid NOT NULL REFERENCES auth_accounts (id),
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
CONSTRAINT context_annotations_body CHECK (char_length(body) BETWEEN 1 AND 4000)
);
CREATE TABLE access_grants (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
grantee_subject_id uuid REFERENCES auth_accounts (id),
resource_kind text NOT NULL,
resource_id uuid NOT NULL,
context_kind text,
context_id uuid,
can_read boolean NOT NULL DEFAULT false,
can_edit boolean NOT NULL DEFAULT false,
can_share boolean NOT NULL DEFAULT false,
can_delete boolean NOT NULL DEFAULT false,
is_exception boolean NOT NULL DEFAULT false,
created_by uuid NOT NULL REFERENCES auth_accounts (id),
created_at timestamptz NOT NULL DEFAULT now(),
CONSTRAINT access_grants_kind CHECK (resource_kind IN ('case', 'matter', 'element', 'task', 'deadline')),
CONSTRAINT access_grants_context_pair CHECK ((context_kind IS NULL) = (context_id IS NULL)),
CONSTRAINT access_grants_context_kind CHECK (context_kind IS NULL OR context_kind IN ('case', 'matter')),
CONSTRAINT access_grants_grantee CHECK (is_exception OR grantee_subject_id IS NOT NULL),
CONSTRAINT access_grants_exception_flag CHECK (
NOT is_exception OR can_read OR can_edit OR can_share OR can_delete
)
);
CREATE UNIQUE INDEX access_grants_identity ON access_grants (
resource_kind,
resource_id,
COALESCE(grantee_subject_id, '00000000-0000-0000-0000-000000000000'::uuid),
COALESCE(context_kind, ''),
COALESCE(context_id, '00000000-0000-0000-0000-000000000000'::uuid),
is_exception
);
CREATE INDEX access_grants_grantee ON access_grants (grantee_subject_id);
CREATE INDEX access_grants_resource ON access_grants (resource_kind, resource_id);
CREATE TABLE tasks (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
home_scope_id uuid NOT NULL REFERENCES data_rooms (id),
owner_subject_id uuid NOT NULL REFERENCES auth_accounts (id),
created_by uuid NOT NULL REFERENCES auth_accounts (id),
version integer NOT NULL DEFAULT 1,
title text NOT NULL,
matter_id uuid REFERENCES matters (id),
assignee_subject_id uuid REFERENCES auth_accounts (id),
due_on date,
task_status text NOT NULL DEFAULT 'open',
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
deleted_at timestamptz,
CONSTRAINT tasks_title_len CHECK (char_length(title) BETWEEN 1 AND 200),
CONSTRAINT tasks_status CHECK (task_status IN ('open', 'done'))
);
CREATE INDEX tasks_open ON tasks (task_status) WHERE deleted_at IS NULL;
CREATE TABLE deadlines (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
home_scope_id uuid NOT NULL REFERENCES data_rooms (id),
owner_subject_id uuid NOT NULL REFERENCES auth_accounts (id),
created_by uuid NOT NULL REFERENCES auth_accounts (id),
version integer NOT NULL DEFAULT 1,
title text NOT NULL,
matter_id uuid REFERENCES matters (id),
element_id uuid REFERENCES elements (id),
assignee_subject_id uuid REFERENCES auth_accounts (id),
due_on date NOT NULL,
deadline_status text NOT NULL DEFAULT 'open',
fulfilled_at timestamptz,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
deleted_at timestamptz,
CONSTRAINT deadlines_title_len CHECK (char_length(title) BETWEEN 1 AND 200),
CONSTRAINT deadlines_status CHECK (deadline_status IN ('open', 'fulfilled'))
);
CREATE INDEX deadlines_open ON deadlines (deadline_status) WHERE deleted_at IS NULL;
CREATE TABLE task_deadline_links (
task_id uuid NOT NULL REFERENCES tasks (id),
deadline_id uuid NOT NULL REFERENCES deadlines (id),
created_by uuid NOT NULL REFERENCES auth_accounts (id),
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (task_id, deadline_id)
);
CREATE TABLE media_assets (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
element_id uuid NOT NULL UNIQUE REFERENCES elements (id),
owner_subject_id uuid NOT NULL REFERENCES auth_accounts (id),
home_scope_id uuid NOT NULL REFERENCES data_rooms (id),
original_filename text NOT NULL,
content_type text NOT NULL,
byte_size bigint NOT NULL,
sha256 text NOT NULL,
revision integer NOT NULL DEFAULT 1,
status text NOT NULL DEFAULT 'active',
created_at timestamptz NOT NULL DEFAULT now(),
CONSTRAINT media_assets_status CHECK (status IN ('active', 'purging', 'purged')),
CONSTRAINT media_assets_filename CHECK (char_length(original_filename) BETWEEN 1 AND 240)
);
CREATE TABLE media_operations (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
element_id uuid,
asset_id uuid,
phase text NOT NULL,
status text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE domain_events (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
actor_subject_id uuid REFERENCES auth_accounts (id),
scope_id uuid,
action text NOT NULL,
resource_kind text NOT NULL,
resource_id uuid NOT NULL,
context_kind text,
context_id uuid,
occurred_on date,
occurred_at timestamptz NOT NULL DEFAULT now(),
result text NOT NULL DEFAULT 'ok'
);
CREATE INDEX domain_events_resource ON domain_events (resource_kind, resource_id);
CREATE INDEX domain_events_context ON domain_events (context_kind, context_id);
+3
View File
@@ -0,0 +1,3 @@
-r requirements.txt
pytest==8.3.4
httpx==0.28.1
+5 -1
View File
@@ -1,3 +1,7 @@
fastapi==0.115.6
uvicorn[standard]==0.34.0
psycopg2-binary==2.9.10
psycopg[binary]==3.2.3
psycopg-pool==3.2.4
bcrypt==4.2.1
pydantic-settings==2.6.1
python-multipart==0.0.18
+6 -1
View File
@@ -32,8 +32,12 @@ services:
DB_PASSWORD: "${DB_PASSWORD:-dev_password_change_me}"
APP_URL: "${APP_URL:-https://dev.tsumugu.jinkendo.de}"
ALLOWED_ORIGINS: "${ALLOWED_ORIGINS:-https://dev.tsumugu.jinkendo.de,http://192.168.2.49:3094,http://localhost:3094}"
MEDIA_ROOT: /data/media
SEED_DEMO: "${SEED_DEMO:-true}"
volumes:
- dev-tsumugu-media:/data/media
ports:
- "${TSUMUGU_BACKEND_PORT:-8094}:8000"
- "127.0.0.1:${TSUMUGU_BACKEND_PORT:-8094}:8000"
depends_on:
postgres:
condition: service_healthy
@@ -68,6 +72,7 @@ services:
volumes:
dev-tsumugu-db-data:
dev-tsumugu-media:
networks:
dev-tsumugu-network:
+6 -1
View File
@@ -34,8 +34,12 @@ services:
DB_PASSWORD: "${DB_PASSWORD:?set DB_PASSWORD in .env}"
APP_URL: "${APP_URL:-https://tsumugu.jinkendo.de}"
ALLOWED_ORIGINS: "${ALLOWED_ORIGINS:-https://tsumugu.jinkendo.de}"
MEDIA_ROOT: /data/media
SEED_DEMO: "${SEED_DEMO:-false}"
volumes:
- tsumugu-media:/data/media
ports:
- "${TSUMUGU_BACKEND_PORT:-8007}:8000"
- "127.0.0.1:${TSUMUGU_BACKEND_PORT:-8007}:8000"
depends_on:
postgres:
condition: service_healthy
@@ -71,6 +75,7 @@ services:
volumes:
tsumugu-db-data:
tsumugu-media:
networks:
tsumugu-network:
+2
View File
@@ -35,6 +35,8 @@ Gearbeitet wird auf `develop`. Production entsteht nur durch einen Merge-Commit
Fehlt beim ersten Lauf die Host-`.env`, legt der Workflow sie an. Development bekommt die dokumentierten Dev-Defaults. Production bekommt ein zufälliges `DB_PASSWORD`, das nur in `/home/lars/docker/tsumugu/.env` steht und nicht ins Log geschrieben wird. Spätere Läufe überschreiben eine vorhandene `.env` nicht. `git reset --hard` lässt die Datei liegen, weil sie nicht im Repo ist.
Der Backend-Container migriert beim Start und bedient danach den API-Prozess. Der Host-Port des Backends bleibt an `127.0.0.1` gebunden; von außen ist nur das Frontend erreichbar, das `/api/` im Compose-Netz weiterreicht. Eigene Dateien liegen im Volume `dev-tsumugu-media` bzw. `tsumugu-media`. Development setzt `SEED_DEMO` standardmäßig und legt dabei nur synthetische Konten an. Production lässt das aus. Eine schon vorhandene Host-`.env` muss `SEED_DEMO` nicht enthalten.
---
## Erreichbarkeit von außen
+12
View File
@@ -0,0 +1,12 @@
# Vorläufige MVP-Annahmen
Diese Regeln sind die Arbeitsgrundlage der ersten Lieferung. Sie sind keine endgültigen Produktentscheidungen und lassen sich später ändern, ohne das Datenmodell umzubauen.
1. **Widersprüchliche Rechte.** Es gilt nur der Kontext der Aktion. Ein Schreibschutz in Akte A sperrt die Bearbeitung in Kontext B nicht. Rechte werden nicht über unsichtbare Kontexte vereinigt.
2. **Neue Einbindung.** Weitere Sicht entsteht nur mit Weitergaberecht am Element und Bearbeitungsrecht am Ziel. Bearbeiten allein gibt niemandem neuen Zugriff.
3. **Einbindung und Löschen.** „Aus diesem Kontext entfernen“ löscht die Einbindung und ihre Anmerkungen. Das Element bleibt bei der Eigentümerin oder dem Eigentümer, auch ohne Einbindung. „Überall löschen“ darf nur diese Person. Paperless-Originale werden nicht gelöscht.
4. **Aktenvererbung.** Die Zuordnung eines Vorgangs gibt die Rechte dieser Akte an den Vorgang und an Inhalte ohne ausdrückliche Ausnahme weiter. Was die zuordnende Person nicht weitergeben darf, bleibt in diesem Aktenkontext unsichtbar, ohne Titel und ohne Anzahl. Querverweise vererben nichts. Die Ownership bleibt unverändert.
Der gewählte Datenraum legt fest, wo neue Objekte entstehen. Er ist nicht selbst der Rechtepfad. Eine gültige Sitzung muss einen Datenraum gewählt haben; der Server prüft danach den mitgeschickten Handlungskontext.
Technische Anpassung: Das Session-Cookie heißt in Production `__Host-jinkendo-session` und ist `Secure`. Development nutzt diesen Namen nur bei HTTPS. Über die dokumentierten HTTP-Adressen im LAN heißt es `jinkendo-session`, weil ein `__Host-`-Cookie dort nicht gespeichert werden kann.
+1 -1
View File
@@ -1,6 +1,6 @@
# Tsumugu – Technische MVP-Spezifikation
**Stand:** 16.10.2026 · **Fassung:** 0.3 · **Status:** Erster fachlicher Lieferumfang bestätigt; technische Ausgestaltung und offene Produktregeln bleiben Vorschläge. Keine Implementierung, keine Migration, kein Testnachweis.
**Stand:** 16.10.2026 · **Fassung:** 0.3 · **Status:** Erster fachlicher Lieferumfang ist als Anwendung umgesetzt. Offene Rechte- und Löschregeln bleiben vorläufig und stehen in [MVP_ANNAHMEN.md](../MVP_ANNAHMEN.md). Diese Datei bleibt der technische Entwurf, nicht der Nachweis eines Produktionstests.
**Fachliche Grundlage:** [TSUMUGU_PRODUCT_SPEC.md](../product/TSUMUGU_PRODUCT_SPEC.md), Arbeitsstand 0.25 einschließlich Lieferentscheidung F-05a. Die historische [Recovery-Baseline](../product/Tsumugu_Product_Recovery_Baseline_v0.1.md) bleibt unverändert; wo das Interview eine Recovery-Aussage präzisiert hat, gilt die Fachspec.
+2
View File
@@ -0,0 +1,2 @@
node_modules
dist
+12 -1
View File
@@ -1,7 +1,18 @@
FROM node:22-alpine AS build
WORKDIR /src
COPY package.json package-lock.json ./
RUN npm ci
COPY index.html vite.config.js ./
COPY src ./src
RUN npm run build
FROM nginx:alpine
COPY nginx.conf /etc/nginx/conf.d/default.conf
COPY index.html /usr/share/nginx/html/index.html
COPY --from=build /src/dist /usr/share/nginx/html
EXPOSE 80
+2 -22
View File
@@ -4,29 +4,9 @@
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Tsumugu</title>
<style>
body {
margin: 0;
min-height: 100vh;
display: grid;
place-items: center;
font-family: Georgia, "Times New Roman", serif;
background: #f4f1ea;
color: #1c1915;
}
main {
max-width: 28rem;
padding: 2rem;
}
p {
line-height: 1.5;
}
</style>
</head>
<body>
<main>
<h1>Tsumugu</h1>
<p>Das Deploy-Gerüst der Jinkendo-Familie läuft. Die Anwendung selbst folgt.</p>
</main>
<div id="root"></div>
<script type="module" src="/src/main.jsx"></script>
</body>
</html>
+20 -1
View File
@@ -3,6 +3,14 @@ server {
server_name localhost;
root /usr/share/nginx/html;
index index.html;
server_tokens off;
client_max_body_size 21m;
add_header Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' blob:; connect-src 'self'; frame-ancestors 'none'; base-uri 'self'; form-action 'self'" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "DENY" always;
add_header Referrer-Policy "no-referrer" always;
add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always;
resolver 127.0.0.11 valid=10s ipv6=off;
@@ -13,10 +21,21 @@ server {
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-Proto $http_x_forwarded_proto;
proxy_read_timeout 600s;
}
location ^~ /health/ {
set $docker_backend_svc backend;
proxy_pass http://$docker_backend_svc:8000$request_uri;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $http_x_forwarded_proto;
proxy_read_timeout 30s;
}
location / {
try_files $uri $uri/ /index.html;
}
+1735
View File
File diff suppressed because it is too large. Load diff
+19
View File
@@ -0,0 +1,19 @@
{
"name": "tsumugu-frontend",
"private": true,
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
},
"dependencies": {
"react": "18.3.1",
"react-dom": "18.3.1",
"react-router-dom": "6.28.1"
},
"devDependencies": {
"@vitejs/plugin-react": "4.3.4",
"vite": "5.4.11"
}
}
+85
View File
@@ -0,0 +1,85 @@
import { useEffect, useState } from "react";
import { Navigate, Route, Routes, useNavigate } from "react-router-dom";
import { api, applySession, clearSession, isDirty } from "./api.js";
import { SessionContext } from "./session.js";
import { Login } from "./pages/Login.jsx";
import { Shell } from "./pages/Shell.jsx";
import { Overview } from "./pages/Overview.jsx";
import { CaseList, CaseDetail } from "./pages/Cases.jsx";
import { MatterList, MatterDetail } from "./pages/Matters.jsx";
import { Rooms } from "./pages/Rooms.jsx";
import { Search } from "./pages/Search.jsx";
export function App() {
const [session, setSession] = useState(undefined);
const navigate = useNavigate();
useEffect(() => {
let active = true;
api("/api/v1/auth/session")
.then((data) => {
if (!active) return;
applySession(data);
setSession(data);
})
.catch(() => {
if (!active) return;
clearSession();
setSession(null);
});
return () => {
active = false;
};
}, []);
async function refresh() {
const data = await api("/api/v1/auth/session");
applySession(data);
setSession(data);
return data;
}
async function changeScope(next) {
if (isDirty() && !window.confirm("Ungespeicherte Eingaben verwerfen und den Datenraum wechseln?")) {
return;
}
const data = await api("/api/v1/auth/session/scope", { method: "POST", body: { kind: next.kind, id: next.id } });
applySession(data);
setSession(data);
navigate("/");
}
async function logout() {
try {
await api("/api/v1/auth/logout", { method: "POST" });
} catch {
/* Die lokale Sitzung endet auch, wenn der Server schon abgemeldet hat. */
}
clearSession();
setSession(null);
navigate("/login");
}
if (session === undefined) {
return <p className="boot">Tsumugu wird geladen …</p>;
}
const value = { session, setSession, refresh, changeScope, logout };
return (
<SessionContext.Provider value={value}>
<Routes>
<Route path="/login" element={session ? <Navigate to="/" replace /> : <Login />} />
<Route element={session ? <Shell /> : <Navigate to="/login" replace />}>
<Route index element={<Overview />} />
<Route path="cases" element={<CaseList />} />
<Route path="cases/:id" element={<CaseDetail />} />
<Route path="matters" element={<MatterList />} />
<Route path="matters/:id" element={<MatterDetail />} />
<Route path="rooms" element={<Rooms />} />
<Route path="search" element={<Search />} />
</Route>
</Routes>
</SessionContext.Provider>
);
}
+101
View File
@@ -0,0 +1,101 @@
let csrf = "";
let scope = null;
let epoch = 0;
let dirty = false;
export function sessionState() {
return { csrf, scope, epoch };
}
export function applySession(data) {
csrf = data.csrf_token || "";
scope = data.scope || null;
epoch = data.epoch || 0;
dirty = false;
return data;
}
export function clearSession() {
csrf = "";
scope = null;
epoch = 0;
dirty = false;
}
export function markDirty(value) {
dirty = value;
}
export function isDirty() {
return dirty;
}
function scopeHeaders() {
if (!scope) return {};
return { "X-Scope-Kind": scope.kind, "X-Scope-Id": scope.id };
}
export async function api(path, { method = "GET", body, form } = {}) {
const started = epoch;
const headers = { ...scopeHeaders() };
if (csrf && method !== "GET" && method !== "HEAD") {
headers["X-CSRF-Token"] = csrf;
}
let payload;
if (form) {
payload = form;
} else if (body !== undefined) {
headers["Content-Type"] = "application/json";
payload = JSON.stringify(body);
}
const response = await fetch(path, { method, headers, body: payload, credentials: "include" });
if (started !== epoch) {
const error = new Error("Der Datenraum wurde gewechselt.");
error.status = 0;
throw error;
}
if (response.status === 204) return null;
const text = await response.text();
const data = text ? JSON.parse(text) : null;
if (!response.ok) {
const error = new Error(data?.detail || "Die Anfrage ist fehlgeschlagen.");
error.status = response.status;
error.code = data?.code;
if (response.status === 401) clearSession();
throw error;
}
return data;
}
export async function downloadFile(elementId, context, filename) {
const params = new URLSearchParams();
if (context?.kind && context?.id) {
params.set("context_kind", context.kind);
params.set("context_id", context.id);
}
const response = await fetch(`/api/v1/files/${elementId}/content?${params}`, {
credentials: "include",
headers: scopeHeaders(),
});
if (!response.ok) {
throw new Error("Die Datei ist nicht verfügbar.");
}
const blob = await response.blob();
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = filename || "datei";
document.body.appendChild(link);
link.click();
link.remove();
URL.revokeObjectURL(url);
}
export function textToDocument(text) {
const blocks = text.split(/\n/).map((line) => ({ type: "paragraph", text: line }));
return { version: 1, blocks: blocks.length ? blocks : [{ type: "paragraph", text: "" }] };
}
export function documentToText(document) {
return (document?.blocks || []).map((block) => block.text || "").join("\n");
}
+13
View File
@@ -0,0 +1,13 @@
import React from "react";
import { createRoot } from "react-dom/client";
import { BrowserRouter } from "react-router-dom";
import { App } from "./App.jsx";
import "./styles.css";
createRoot(document.getElementById("root")).render(
<React.StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
</React.StrictMode>,
);
+395
View File
@@ -0,0 +1,395 @@
import { useContext, useEffect, useState } from "react";
import { Link, useParams } from "react-router-dom";
import { api, markDirty, textToDocument } from "../api.js";
import { SessionContext } from "../session.js";
import { BindingList, Chronology, ErrorNote, ShareBox } from "./widgets.jsx";
export function CaseList() {
const { session } = useContext(SessionContext);
const [items, setItems] = useState([]);
const [title, setTitle] = useState("");
const [error, setError] = useState("");
async function load() {
const data = await api("/api/v1/cases");
setItems(data.items);
}
useEffect(() => {
load().catch((err) => setError(err.message));
}, [session.scope.id]);
async function create(event) {
event.preventDefault();
setError("");
try {
await api("/api/v1/cases", { method: "POST", body: { title } });
setTitle("");
markDirty(false);
await load();
} catch (err) {
setError(err.message);
}
}
return (
<main className="page">
<header className="page-head">
<div>
<h1>Akten</h1>
<p className="muted">Sichtbar ist, was du lesen darfst — auch aus anderen Datenräumen. Neue Akten entstehen in „{session.scope.name}“.</p>
</div>
</header>
<form onSubmit={create} className="inline">
<input
value={title}
onChange={(event) => {
setTitle(event.target.value);
markDirty(true);
}}
placeholder="Neue Akte, zum Beispiel Mietstreit"
required
/>
<button type="submit">Akte anlegen</button>
</form>
<ErrorNote error={error} />
<ul className="index">
{items.map((item) => (
<li key={item.id}>
<Link to={`/cases/${item.id}`}>{item.title}</Link>
<span>{item.status === "open" ? "Offen" : "Geschlossen"}</span>
</li>
))}
</ul>
</main>
);
}
export function CaseDetail() {
const { id } = useParams();
const [record, setRecord] = useState(null);
const [events, setEvents] = useState([]);
const [error, setError] = useState("");
const context = { kind: "case", id };
async function load() {
const [detail, chronology] = await Promise.all([
api(`/api/v1/cases/${id}`),
api(`/api/v1/cases/${id}/chronology`),
]);
setRecord(detail);
setEvents(chronology.items);
}
useEffect(() => {
load().catch((err) => setError(err.message));
}, [id]);
if (error && !record) return <main className="page"><ErrorNote error={error} /></main>;
if (!record) return <main className="page"><p className="muted">Akte wird geladen …</p></main>;
return (
<main className="page">
<header className="page-head">
<div>
<p className="eyebrow">{record.home_scope_name}</p>
<h1>{record.title}</h1>
<p className="muted">{rightsText(record.rights)} {record.status === "open" ? "Offen" : "Geschlossen"}.</p>
</div>
</header>
<ErrorNote error={error} />
<div className="split">
<section className="card">
<h2>Vorgänge</h2>
<ul>
{record.matters.map((matter) => (
<li key={matter.id}>
<Link to={`/matters/${matter.id}?context_kind=case&context_id=${id}`}>{matter.title}</Link>
</li>
))}
</ul>
{record.rights.edit ? <NewMatter caseId={id} onChange={load} /> : null}
{record.subcases?.length ? (
<>
<h3>Unterakten</h3>
<ul>
{record.subcases.map((item) => (
<li key={item.id}><Link to={`/cases/${item.id}`}>{item.title}</Link></li>
))}
</ul>
</>
) : null}
{record.rights.edit ? <NewSubcase parentId={id} onChange={load} /> : null}
</section>
<section className="card">
<h2>Kapitel</h2>
<ul>{record.chapters.map((chapter) => <li key={chapter.id}>{chapter.title}</li>)}</ul>
{record.rights.edit ? <ChapterForm path={`/api/v1/cases/${id}/chapters`} onChange={load} /> : null}
</section>
</div>
<section className="card">
<h2>Inhalte</h2>
<BindingList bindings={record.bindings} context={context} canEdit={record.rights.edit} isOwner={record.is_owner} onChange={load} />
{record.rights.edit ? <ContentForms context={context} chapters={record.chapters} onChange={load} /> : null}
</section>
{record.grants || record.rights.share || record.is_owner ? (
record.rights.share || record.is_owner ? (
<ShareBox path={`/api/v1/cases/${id}/grants`} grants={record.grants || []} onChange={load} />
) : null
) : null}
<section className="card">
<h2>Chronologie</h2>
<Chronology items={events} />
</section>
</main>
);
}
function NewMatter({ caseId, onChange }) {
const [title, setTitle] = useState("");
const [error, setError] = useState("");
async function submit(event) {
event.preventDefault();
setError("");
try {
const matter = await api("/api/v1/matters", { method: "POST", body: { title } });
await api(`/api/v1/matters/${matter.id}/case-links`, { method: "POST", body: { case_id: caseId } });
setTitle("");
markDirty(false);
onChange();
} catch (err) {
setError(err.message);
}
}
return (
<form onSubmit={submit} className="stack compact">
<h3>Vorgang anlegen und zuordnen</h3>
<input value={title} onChange={(event) => { setTitle(event.target.value); markDirty(true); }} placeholder="Zum Beispiel Mängelanzeige" required />
<button type="submit">Vorgang verbinden</button>
<ErrorNote error={error} />
</form>
);
}
function NewSubcase({ parentId, onChange }) {
const [title, setTitle] = useState("");
const [rightsMode, setRightsMode] = useState("inherit_parent");
async function submit(event) {
event.preventDefault();
await api("/api/v1/cases", { method: "POST", body: { title, parent_case_id: parentId, rights_mode: rightsMode } });
setTitle("");
onChange();
}
return (
<form onSubmit={submit} className="stack compact">
<h3>Unterakte</h3>
<input value={title} onChange={(event) => setTitle(event.target.value)} placeholder="Titel der Unterakte" required />
<select value={rightsMode} onChange={(event) => setRightsMode(event.target.value)}>
<option value="inherit_parent">Rechte der Akte übernehmen</option>
<option value="explicit">Eigene Rechte</option>
</select>
<button type="submit">Unterakte anlegen</button>
</form>
);
}
export function ChapterForm({ path, onChange }) {
const [title, setTitle] = useState("");
async function submit(event) {
event.preventDefault();
await api(path, { method: "POST", body: { title } });
setTitle("");
onChange();
}
return (
<form onSubmit={submit} className="inline">
<input value={title} onChange={(event) => setTitle(event.target.value)} placeholder="Kapitel" required />
<button type="submit">Kapitel</button>
</form>
);
}
export function ContentForms({ context, placement, chapters, onChange }) {
return (
<div className="forms">
<NoteForm context={context} placement={placement} chapters={chapters} onChange={onChange} />
<FileForm context={context} placement={placement} chapters={chapters} onChange={onChange} />
<ExternalForm context={context} placement={placement} chapters={chapters} onChange={onChange} />
</div>
);
}
function chapterSelect(chapters, value, setValue) {
return (
<select value={value} onChange={(event) => setValue(event.target.value)}>
<option value="">Ohne Kapitel</option>
{chapters.map((chapter) => (
<option key={chapter.id} value={chapter.id}>{chapter.title}</option>
))}
</select>
);
}
function NoteForm({ context, placement, chapters, onChange }) {
const [title, setTitle] = useState("");
const [text, setText] = useState("");
const [chapterId, setChapterId] = useState("");
const [error, setError] = useState("");
async function submit(event) {
event.preventDefault();
setError("");
try {
await api("/api/v1/notes", {
method: "POST",
body: {
title,
document: textToDocument(text),
context,
...(placement ? { placement } : {}),
...(chapterId ? { chapter_id: chapterId } : {}),
},
});
setTitle("");
setText("");
markDirty(false);
onChange();
} catch (err) {
setError(err.message);
}
}
return (
<form onSubmit={submit} className="stack compact">
<h3>Notiz</h3>
<input value={title} onChange={(event) => { setTitle(event.target.value); markDirty(true); }} placeholder="Titel" required />
<textarea rows={4} value={text} onChange={(event) => { setText(event.target.value); markDirty(true); }} placeholder="Gemeinsamer Text" />
{chapterSelect(chapters, chapterId, setChapterId)}
<button type="submit">Notiz anlegen</button>
<ErrorNote error={error} />
</form>
);
}
function FileForm({ context, placement, chapters, onChange }) {
const [title, setTitle] = useState("");
const [file, setFile] = useState(null);
const [chapterId, setChapterId] = useState("");
const [documentOn, setDocumentOn] = useState("");
const [sentOn, setSentOn] = useState("");
const [receivedOn, setReceivedOn] = useState("");
const [error, setError] = useState("");
async function submit(event) {
event.preventDefault();
if (!file) return;
const form = new FormData();
form.set("title", title);
form.set("upload", file);
form.set("context_kind", context.kind);
form.set("context_id", context.id);
if (placement) {
form.set("placement_kind", placement.kind);
form.set("placement_id", placement.id);
}
if (chapterId) form.set("chapter_id", chapterId);
if (documentOn) form.set("document_on", documentOn);
if (sentOn) form.set("sent_on", sentOn);
if (receivedOn) form.set("received_on", receivedOn);
setError("");
try {
await api("/api/v1/files", { method: "POST", form });
setTitle("");
setFile(null);
markDirty(false);
onChange();
} catch (err) {
setError(err.message);
}
}
return (
<form onSubmit={submit} className="stack compact">
<h3>Datei</h3>
<input value={title} onChange={(event) => setTitle(event.target.value)} placeholder="Titel des Schreibens" required />
<input type="file" accept="application/pdf,image/png,image/jpeg,image/webp" onChange={(event) => setFile(event.target.files?.[0] || null)} required />
<label>Dokumentdatum <input type="date" value={documentOn} onChange={(event) => setDocumentOn(event.target.value)} /></label>
<label>Versand <input type="date" value={sentOn} onChange={(event) => setSentOn(event.target.value)} /></label>
<label>Zugang <input type="date" value={receivedOn} onChange={(event) => setReceivedOn(event.target.value)} /></label>
{chapterSelect(chapters, chapterId, setChapterId)}
<button type="submit">Datei hinzufügen</button>
<ErrorNote error={error} />
</form>
);
}
function ExternalForm({ context, placement, chapters, onChange }) {
const [title, setTitle] = useState("");
const [externalId, setExternalId] = useState("");
const [source, setSource] = useState("paperless");
const [chapterId, setChapterId] = useState("");
const [documentOn, setDocumentOn] = useState("");
const [sentOn, setSentOn] = useState("");
const [receivedOn, setReceivedOn] = useState("");
const [error, setError] = useState("");
async function submit(event) {
event.preventDefault();
setError("");
try {
await api("/api/v1/external-refs", {
method: "POST",
body: {
title,
source,
external_id: externalId,
context,
...(placement ? { placement } : {}),
...(chapterId ? { chapter_id: chapterId } : {}),
dates: {
document_on: documentOn || null,
sent_on: sentOn || null,
received_on: receivedOn || null,
},
},
});
setTitle("");
setExternalId("");
onChange();
} catch (err) {
setError(err.message);
}
}
return (
<form onSubmit={submit} className="stack compact">
<h3>Paperless oder andere Referenz</h3>
<input value={title} onChange={(event) => setTitle(event.target.value)} placeholder="Anzeigetitel" required />
<select value={source} onChange={(event) => setSource(event.target.value)}>
<option value="paperless">Paperless</option>
<option value="url">Andere Quelle</option>
</select>
<input value={externalId} onChange={(event) => setExternalId(event.target.value)} placeholder="Externe ID" required />
<label>Dokumentdatum <input type="date" value={documentOn} onChange={(event) => setDocumentOn(event.target.value)} /></label>
<label>Versand <input type="date" value={sentOn} onChange={(event) => setSentOn(event.target.value)} /></label>
<label>Zugang <input type="date" value={receivedOn} onChange={(event) => setReceivedOn(event.target.value)} /></label>
{chapterSelect(chapters, chapterId, setChapterId)}
<button type="submit">Referenz erfassen</button>
<ErrorNote error={error} />
</form>
);
}
function rightsText(rights) {
const parts = ["Lesen"];
if (rights.edit) parts.push("Bearbeiten");
if (rights.share) parts.push("Weitergeben");
if (rights.delete) parts.push("Löschen");
return parts.join(", ") + ".";
}
+82
View File
@@ -0,0 +1,82 @@
import { useContext, useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { api, applySession } from "../api.js";
import { SessionContext } from "../session.js";
export function Login() {
const { setSession } = useContext(SessionContext);
const navigate = useNavigate();
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [error, setError] = useState("");
const [demo, setDemo] = useState(null);
const [pending, setPending] = useState(false);
useEffect(() => {
api("/api/v1/auth/demo")
.then(setDemo)
.catch(() => setDemo(null));
}, []);
async function submit(event) {
event.preventDefault();
setPending(true);
setError("");
try {
const data = await api("/api/v1/auth/login", { method: "POST", body: { email, password } });
applySession(data);
setSession(data);
navigate("/");
} catch (err) {
setError(err.message);
} finally {
setPending(false);
}
}
return (
<main className="login">
<section className="card login-card">
<p className="eyebrow">Jinkendo</p>
<h1>Tsumugu</h1>
<p className="lead">Akten, Vorgänge und Fristen an einem Ort. Die erste Lieferung organisiert und verfolgt.</p>
<form onSubmit={submit} className="stack">
<label>
E-Mail
<input type="email" autoComplete="username" value={email} onChange={(event) => setEmail(event.target.value)} required />
</label>
<label>
Passwort
<input type="password" autoComplete="current-password" value={password} onChange={(event) => setPassword(event.target.value)} required />
</label>
{error ? <p className="error">{error}</p> : null}
<button type="submit" disabled={pending}>{pending ? "Anmeldung …" : "Anmelden"}</button>
</form>
{demo ? (
<div className="demo">
<h2>Beispieldaten</h2>
<p>Zwei synthetische Konten. Private Inhalte von Ada bleiben für Ben unsichtbar.</p>
<ul>
{demo.accounts.map((account) => (
<li key={account.email}>
<button
type="button"
className="linkish"
onClick={() => {
setEmail(account.email);
setPassword(account.password);
}}
>
{account.display_name}
</button>
<span>{account.email}</span>
<code>{account.password}</code>
</li>
))}
</ul>
</div>
) : null}
</section>
</main>
);
}
+343
View File
@@ -0,0 +1,343 @@
import { useContext, useEffect, useState } from "react";
import { Link, useParams, useSearchParams } from "react-router-dom";
import { api, markDirty } from "../api.js";
import { SessionContext } from "../session.js";
import { BindingList, Chronology, ErrorNote, ShareBox } from "./widgets.jsx";
import { ChapterForm, ContentForms } from "./Cases.jsx";
function pageContext(params) {
const kind = params.get("context_kind");
const id = params.get("context_id");
if (!kind || !id || kind === "direct") return null;
return { kind, id };
}
export function MatterList() {
const { session } = useContext(SessionContext);
const [items, setItems] = useState([]);
const [title, setTitle] = useState("");
const [error, setError] = useState("");
async function load() {
const data = await api("/api/v1/matters");
setItems(data.items);
}
useEffect(() => {
load().catch((err) => setError(err.message));
}, [session.scope.id]);
async function create(event) {
event.preventDefault();
try {
await api("/api/v1/matters", { method: "POST", body: { title } });
setTitle("");
markDirty(false);
await load();
} catch (err) {
setError(err.message);
}
}
return (
<main className="page">
<header className="page-head">
<div>
<h1>Vorgänge</h1>
<p className="muted">Ein Vorgang kann ohne Akte bestehen und mehreren Akten zugeordnet werden. Neu angelegt wird er in „{session.scope.name}“.</p>
</div>
</header>
<form onSubmit={create} className="inline">
<input value={title} onChange={(event) => { setTitle(event.target.value); markDirty(true); }} placeholder="Neuer Vorgang" required />
<button type="submit">Vorgang anlegen</button>
</form>
<ErrorNote error={error} />
<ul className="index">
{items.map((item) => {
const context = item.contexts?.[0];
const params = new URLSearchParams();
if (context && context.kind !== "direct") {
params.set("context_kind", context.kind);
params.set("context_id", context.id);
}
const suffix = params.toString() ? `?${params}` : "";
return (
<li key={item.id}>
<Link to={`/matters/${item.id}${suffix}`}>{item.title}</Link>
<span>{item.status === "open" ? "Offen" : "Geschlossen"}</span>
</li>
);
})}
</ul>
</main>
);
}
export function MatterDetail() {
const { id } = useParams();
const [params] = useSearchParams();
const inherited = pageContext(params);
const [record, setRecord] = useState(null);
const [events, setEvents] = useState([]);
const [error, setError] = useState("");
const rightsContext = inherited || { kind: "matter", id };
const placement = inherited?.kind === "case" ? { kind: "matter", id } : null;
async function load() {
const query = inherited ? `?context_kind=${inherited.kind}&context_id=${inherited.id}` : "";
const [detail, chronology] = await Promise.all([
api(`/api/v1/matters/${id}${query}`),
api(`/api/v1/matters/${id}/chronology${query}`),
]);
setRecord(detail);
setEvents(chronology.items);
}
useEffect(() => {
setRecord(null);
load().catch((err) => setError(err.message));
}, [id, inherited?.kind, inherited?.id]);
if (error && !record) return <main className="page"><ErrorNote error={error} /></main>;
if (!record) return <main className="page"><p className="muted">Vorgang wird geladen …</p></main>;
return (
<main className="page">
<header className="page-head">
<div>
<p className="eyebrow">{record.home_scope_name}{inherited ? " · über die Akte geöffnet" : ""}</p>
<h1>{record.title}</h1>
<p className="muted">{record.status === "open" ? "Offen" : "Geschlossen"}. Eine Aufgabe und eine Frist bleiben unabhängig.</p>
</div>
</header>
<ErrorNote error={error} />
{record.case_links?.length ? (
<section className="card">
<h2>Akten</h2>
<ul>
{record.case_links.map((link) => (
<li key={link.id}><Link to={`/cases/${link.case_id}`}>{link.title}</Link></li>
))}
</ul>
</section>
) : null}
<section className="card">
<h2>Nachverfolgung</h2>
<p className="notice">Das Erledigen einer Aufgabe erfüllt eine verknüpfte Frist nicht.</p>
<WorkLists record={record} context={inherited} onChange={load} />
{record.rights.edit ? <WorkForms matterId={id} context={inherited} tasks={record.tasks} onChange={load} /> : null}
</section>
<section className="card">
<h2>Inhalte</h2>
<BindingList bindings={record.bindings} context={rightsContext} canEdit={record.rights.edit} isOwner={record.is_owner} onChange={load} />
{record.rights.edit ? (
<ContentForms context={rightsContext} placement={placement} chapters={record.chapters} onChange={load} />
) : null}
</section>
<section className="card">
<h2>Kapitel, Teilvorgänge, Querverweise</h2>
<ul>{record.chapters.map((chapter) => <li key={chapter.id}>{chapter.title}</li>)}</ul>
{record.rights.edit ? <ChapterForm path={`/api/v1/matters/${id}/chapters${inherited ? `?context_kind=${inherited.kind}&context_id=${inherited.id}` : ""}`} onChange={load} /> : null}
{record.submatters?.length ? (
<ul>
{record.submatters.map((item) => (
<li key={item.id}>
<Link to={`/matters/${item.id}${inherited ? `?context_kind=${inherited.kind}&context_id=${inherited.id}` : ""}`}>{item.title}</Link>
</li>
))}
</ul>
) : null}
{record.cross_links?.length ? (
<ul>
{record.cross_links.map((item) => (
<li key={item.id}><Link to={`/matters/${item.matter_id}`}>{item.title}</Link></li>
))}
</ul>
) : null}
{record.rights.edit ? <SubmatterForm parentId={id} context={inherited} onChange={load} /> : null}
</section>
{record.rights.share || record.is_owner ? (
<ShareBox path={`/api/v1/matters/${id}/grants`} grants={record.grants || []} onChange={load} />
) : null}
<section className="card">
<h2>Chronologie</h2>
<Chronology items={events} />
</section>
</main>
);
}
function WorkLists({ record, context, onChange }) {
const linked = new Set((record.task_deadline_links || []).map((item) => item.task_id));
async function complete(task) {
await api(`/api/v1/tasks/${task.id}`, {
method: "PATCH",
body: { expected_version: task.version, status: "done", ...(context ? { context } : {}) },
});
onChange();
}
async function fulfill(deadline) {
await api(`/api/v1/deadlines/${deadline.id}/fulfill`, {
method: "POST",
body: { expected_version: deadline.version, ...(context ? { context } : {}) },
});
onChange();
}
return (
<div className="split">
<div>
<h3>Aufgaben</h3>
<ul className="work">
{record.tasks.map((task) => (
<li key={task.id}>
<div>
<strong>{task.title}</strong>
<span>{task.status === "done" ? "Erledigt" : "Offen"}{task.due_on ? ` · ${task.due_on}` : ""}</span>
{task.assignee_display_name ? <small>Zugewiesen: {task.assignee_display_name}</small> : null}
{linked.has(task.id) ? <small>Mit einer Frist verknüpft, ohne sie zu erfüllen.</small> : null}
</div>
{task.status === "open" ? <button type="button" onClick={() => complete(task)}>Erledigen</button> : null}
</li>
))}
</ul>
</div>
<div>
<h3>Fristen</h3>
<ul className="work">
{record.deadlines.map((deadline) => (
<li key={deadline.id}>
<div>
<strong>{deadline.title}</strong>
<span>{deadline.status === "fulfilled" ? "Erfüllt" : "Offen"} · {deadline.due_on}</span>
</div>
{deadline.status === "open" ? <button type="button" onClick={() => fulfill(deadline)}>Frist erfüllen</button> : null}
</li>
))}
</ul>
</div>
</div>
);
}
function WorkForms({ matterId, context, tasks, onChange }) {
const [taskTitle, setTaskTitle] = useState("");
const [taskDue, setTaskDue] = useState("");
const [deadlineTitle, setDeadlineTitle] = useState("");
const [deadlineDue, setDeadlineDue] = useState("");
const [linkTask, setLinkTask] = useState("");
const [error, setError] = useState("");
async function addTask(event) {
event.preventDefault();
setError("");
try {
const task = await api("/api/v1/tasks", {
method: "POST",
body: {
title: taskTitle,
matter_id: matterId,
...(taskDue ? { due_on: taskDue } : {}),
...(context ? { context } : {}),
},
});
if (linkTask === "new-deadline" && deadlineTitle && deadlineDue) {
const deadline = await api("/api/v1/deadlines", {
method: "POST",
body: {
title: deadlineTitle,
due_on: deadlineDue,
matter_id: matterId,
...(context ? { context } : {}),
},
});
await api(`/api/v1/tasks/${task.id}/deadline-links`, {
method: "POST",
body: { deadline_id: deadline.id, ...(context ? { context } : {}) },
});
setDeadlineTitle("");
setDeadlineDue("");
}
setTaskTitle("");
setTaskDue("");
setLinkTask("");
onChange();
} catch (err) {
setError(err.message);
}
}
async function addDeadline(event) {
event.preventDefault();
setError("");
try {
const deadline = await api("/api/v1/deadlines", {
method: "POST",
body: {
title: deadlineTitle,
due_on: deadlineDue,
matter_id: matterId,
...(context ? { context } : {}),
},
});
if (linkTask && linkTask !== "new-deadline") {
await api(`/api/v1/tasks/${linkTask}/deadline-links`, {
method: "POST",
body: { deadline_id: deadline.id, ...(context ? { context } : {}) },
});
}
setDeadlineTitle("");
setDeadlineDue("");
onChange();
} catch (err) {
setError(err.message);
}
}
return (
<div className="forms">
<form onSubmit={addTask} className="stack compact">
<h3>Aufgabe</h3>
<input value={taskTitle} onChange={(event) => setTaskTitle(event.target.value)} placeholder="Was ist zu tun?" required />
<label>Arbeitstermin <input type="date" value={taskDue} onChange={(event) => setTaskDue(event.target.value)} /></label>
<button type="submit">Aufgabe anlegen</button>
</form>
<form onSubmit={addDeadline} className="stack compact">
<h3>Unabhängige Frist</h3>
<input value={deadlineTitle} onChange={(event) => setDeadlineTitle(event.target.value)} placeholder="Maßgebliche Frist" required />
<label>Frist <input type="date" value={deadlineDue} onChange={(event) => setDeadlineDue(event.target.value)} required /></label>
<select value={linkTask} onChange={(event) => setLinkTask(event.target.value)}>
<option value="">Nicht mit einer Aufgabe verknüpfen</option>
{tasks.map((task) => (
<option key={task.id} value={task.id}>{task.title}</option>
))}
</select>
<button type="submit">Frist erfassen</button>
<ErrorNote error={error} />
</form>
</div>
);
}
function SubmatterForm({ parentId, context, onChange }) {
const [title, setTitle] = useState("");
async function submit(event) {
event.preventDefault();
await api("/api/v1/matters", {
method: "POST",
body: { title, parent_matter_id: parentId, ...(context ? { context } : {}) },
});
setTitle("");
onChange();
}
return (
<form onSubmit={submit} className="inline">
<input value={title} onChange={(event) => setTitle(event.target.value)} placeholder="Teilvorgang" required />
<button type="submit">Teilvorgang</button>
</form>
);
}
+119
View File
@@ -0,0 +1,119 @@
import { useEffect, useState } from "react";
import { api } from "../api.js";
import { ErrorNote, RecordLink } from "./widgets.jsx";
export function Overview() {
const [tasks, setTasks] = useState([]);
const [deadlines, setDeadlines] = useState([]);
const [loose, setLoose] = useState([]);
const [error, setError] = useState("");
async function load() {
try {
const [taskData, deadlineData, elementData] = await Promise.all([
api("/api/v1/views/open-tasks"),
api("/api/v1/views/open-deadlines"),
api("/api/v1/elements"),
]);
setTasks(taskData.items);
setDeadlines(deadlineData.items);
setLoose(elementData.items);
setError("");
} catch (err) {
setError(err.message);
}
}
useEffect(() => {
load();
}, []);
async function complete(task) {
await api(`/api/v1/tasks/${task.id}`, {
method: "PATCH",
body: {
expected_version: task.version,
status: "done",
...(task.action_context ? { context: task.action_context } : {}),
},
});
load();
}
async function fulfill(deadline) {
await api(`/api/v1/deadlines/${deadline.id}/fulfill`, {
method: "POST",
body: {
expected_version: deadline.version,
...(deadline.action_context ? { context: deadline.action_context } : {}),
},
});
load();
}
return (
<main className="page">
<section className="assumption">
<strong>Vorläufige Annahmen.</strong> Es gilt nur der Kontext der Aktion. Eine Einbindung zu entfernen löscht das Element nicht.
Globales Löschen bleibt bei der Eigentümerin oder dem Eigentümer. Eine erledigte Aufgabe erfüllt keine Frist.
</section>
<ErrorNote error={error} />
<div className="split">
<section className="card">
<h2>Offene Aufgaben</h2>
<p className="muted">Über alle Kontexte, die du lesen darfst. Erledigen lässt eine verknüpfte Frist offen.</p>
{tasks.length ? (
<ul className="work">
{tasks.map((task) => (
<li key={task.id}>
<div>
<strong>{task.title}</strong>
<span>{task.due_on ? `Arbeitstermin ${task.due_on}` : "Ohne Arbeitstermin"}</span>
{task.matter_title ? (
<RecordLink kind="matter" id={task.matter_id} title={task.matter_title} context={task.action_context} />
) : null}
</div>
<button type="button" onClick={() => complete(task)}>Erledigen</button>
</li>
))}
</ul>
) : (
<p className="muted">Keine offene Aufgabe.</p>
)}
</section>
<section className="card">
<h2>Offene Fristen</h2>
<p className="muted">Eine Frist bleibt bestehen, bis sie selbst als erfüllt gekennzeichnet wird.</p>
{deadlines.length ? (
<ul className="work">
{deadlines.map((deadline) => (
<li key={deadline.id}>
<div>
<strong>{deadline.title}</strong>
<span>Frist {deadline.due_on}</span>
{deadline.matter_title ? (
<RecordLink kind="matter" id={deadline.matter_id} title={deadline.matter_title} context={deadline.action_context} />
) : null}
</div>
<button type="button" onClick={() => fulfill(deadline)}>Frist erfüllen</button>
</li>
))}
</ul>
) : (
<p className="muted">Keine offene Frist.</p>
)}
</section>
</div>
{loose.length ? (
<section className="card">
<h2>Eigene Elemente ohne Einbindung</h2>
<ul>
{loose.map((item) => (
<li key={item.id}>{item.title}</li>
))}
</ul>
</section>
) : null}
</main>
);
}
+87
View File
@@ -0,0 +1,87 @@
import { useContext, useEffect, useState } from "react";
import { api, markDirty } from "../api.js";
import { SessionContext } from "../session.js";
import { ErrorNote } from "./widgets.jsx";
export function Rooms() {
const { session, refresh } = useContext(SessionContext);
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [members, setMembers] = useState([]);
const [error, setError] = useState("");
const current = session.rooms.find((room) => room.id === session.scope.id);
useEffect(() => {
if (!current || current.kind !== "organization" || current.role !== "manager") {
setMembers([]);
return;
}
api(`/api/v1/rooms/${current.id}/members`)
.then((data) => setMembers(data.items))
.catch((err) => setError(err.message));
}, [current?.id, current?.role]);
async function create(event) {
event.preventDefault();
setError("");
try {
await api("/api/v1/rooms", { method: "POST", body: { name } });
setName("");
markDirty(false);
await refresh();
} catch (err) {
setError(err.message);
}
}
async function addMember(event) {
event.preventDefault();
setError("");
try {
await api(`/api/v1/rooms/${current.id}/members`, { method: "POST", body: { email, role: "member" } });
setEmail("");
const data = await api(`/api/v1/rooms/${current.id}/members`);
setMembers(data.items);
} catch (err) {
setError(err.message);
}
}
return (
<main className="page">
<header className="page-head">
<div>
<h1>Datenräume</h1>
<p className="muted">Mitgliedschaft öffnet nicht die persönlichen Akten anderer. Freigaben stehen an der Akte oder am Vorgang.</p>
</div>
</header>
<ul className="index">
{session.rooms.map((room) => (
<li key={room.id}>
<strong>{room.name}</strong>
<span>{room.kind === "personal" ? "Persönlich" : room.role === "manager" ? "Gemeinsam, Verwalter" : "Gemeinsam"}</span>
</li>
))}
</ul>
<form onSubmit={create} className="inline">
<input value={name} onChange={(event) => { setName(event.target.value); markDirty(true); }} placeholder="Name des gemeinsamen Datenraums" required />
<button type="submit">Datenraum anlegen</button>
</form>
{current?.kind === "organization" && current.role === "manager" ? (
<section className="card">
<h2>Mitglieder in {current.name}</h2>
<ul>
{members.map((member) => (
<li key={member.subject_id}>{member.display_name} · {member.email} · {member.role === "manager" ? "Verwalter" : "Mitglied"}</li>
))}
</ul>
<form onSubmit={addMember} className="inline">
<input type="email" value={email} onChange={(event) => setEmail(event.target.value)} placeholder="E-Mail eines bestehenden Kontos" required />
<button type="submit">Mitglied hinzufügen</button>
</form>
</section>
) : null}
<ErrorNote error={error} />
</main>
);
}
+68
View File
@@ -0,0 +1,68 @@
import { useEffect, useState } from "react";
import { Link, useSearchParams } from "react-router-dom";
import { api } from "../api.js";
import { ErrorNote } from "./widgets.jsx";
export function Search() {
const [params] = useSearchParams();
const query = params.get("q") || "";
const [items, setItems] = useState([]);
const [error, setError] = useState("");
useEffect(() => {
if (query.trim().length < 2) {
setItems([]);
return;
}
api(`/api/v1/search?q=${encodeURIComponent(query)}`)
.then((data) => {
setItems(data.items);
setError("");
})
.catch((err) => setError(err.message));
}, [query]);
return (
<main className="page">
<h1>Suche</h1>
<p className="muted">Nur Titel und Notiztexte, die du lesen darfst. „{query}“</p>
<ErrorNote error={error} />
<ul className="index">
{items.map((item) => (
<li key={`${item.kind}-${item.id}`}>
<Result item={item} />
<span>{label(item.kind)}</span>
</li>
))}
</ul>
{!items.length && !error ? <p className="muted">Keine sichtbaren Treffer.</p> : null}
</main>
);
}
function Result({ item }) {
if (item.kind === "case") return <Link to={`/cases/${item.id}`}>{item.title}</Link>;
if (item.kind === "matter") {
const context = item.contexts?.find((entry) => entry.kind !== "direct") || item.contexts?.[0];
const params = new URLSearchParams();
if (context && context.kind !== "direct") {
params.set("context_kind", context.kind);
params.set("context_id", context.id);
}
const suffix = params.toString() ? `?${params}` : "";
return <Link to={`/matters/${item.id}${suffix}`}>{item.title}</Link>;
}
const context = item.contexts?.[0];
if (!context) return <span>{item.title}</span>;
if (context.kind === "case") return <Link to={`/cases/${context.id}`}>{item.title}</Link>;
return <Link to={`/matters/${context.id}`}>{item.title}</Link>;
}
function label(kind) {
if (kind === "case") return "Akte";
if (kind === "matter") return "Vorgang";
if (kind === "note") return "Notiz";
if (kind === "file") return "Datei";
if (kind === "external_ref") return "Referenz";
return kind;
}
+66
View File
@@ -0,0 +1,66 @@
import { useContext, useState } from "react";
import { NavLink, Outlet, useNavigate } from "react-router-dom";
import { SessionContext } from "../session.js";
export function Shell() {
const { session, changeScope, logout } = useContext(SessionContext);
const navigate = useNavigate();
const [query, setQuery] = useState("");
const [error, setError] = useState("");
async function onScope(event) {
const room = session.rooms.find((item) => item.id === event.target.value);
if (!room || room.id === session.scope.id) return;
setError("");
try {
await changeScope(room);
} catch (err) {
setError(err.message);
}
}
function onSearch(event) {
event.preventDefault();
const term = query.trim();
if (term.length < 2) return;
navigate(`/search?q=${encodeURIComponent(term)}`);
}
return (
<div className="app">
<header className="top">
<div className="brand">
<NavLink to="/">Tsumugu</NavLink>
<span>{session.account.display_name}</span>
</div>
<label className="scope">
Datenraum
<select value={session.scope.id} onChange={onScope}>
{session.rooms.map((room) => (
<option key={room.id} value={room.id}>
{room.name}
</option>
))}
</select>
</label>
<form className="search" onSubmit={onSearch}>
<input
value={query}
onChange={(event) => setQuery(event.target.value)}
placeholder="Suchen"
aria-label="Suchen"
/>
</form>
<button type="button" className="quiet" onClick={logout}>Abmelden</button>
</header>
<nav className="nav">
<NavLink to="/" end>Übersicht</NavLink>
<NavLink to="/cases">Akten</NavLink>
<NavLink to="/matters">Vorgänge</NavLink>
<NavLink to="/rooms">Datenräume</NavLink>
</nav>
{error ? <p className="error banner">{error}</p> : null}
<Outlet />
</div>
);
}
+339
View File
@@ -0,0 +1,339 @@
import { useState } from "react";
import { Link } from "react-router-dom";
import { api, documentToText, downloadFile, markDirty, textToDocument } from "../api.js";
export function ErrorNote({ error }) {
if (!error) return null;
return <p className="error">{error}</p>;
}
export function Chronology({ items }) {
if (!items?.length) return <p className="muted">Noch keine sichtbaren Ereignisse.</p>;
return (
<ol className="timeline">
{items.map((item) => (
<li key={item.id}>
<time>{item.occurred_on || item.occurred_at.slice(0, 10)}</time>
<div>
<strong>{item.label}</strong>
<span>{item.title}</span>
{item.occurred_at ? <small>Erfasst {item.occurred_at.replace("T", " ").replace("Z", " UTC")}</small> : null}
</div>
</li>
))}
</ol>
);
}
export function BindingList({ bindings, context, canEdit, isOwner, onChange }) {
if (!bindings.length) return <p className="muted">In diesem Kontext liegt noch nichts.</p>;
return (
<div className="stack">
{bindings.map((binding) => (
<Binding key={binding.id} binding={binding} context={context} canEdit={canEdit} isOwner={isOwner} onChange={onChange} />
))}
</div>
);
}
function Binding({ binding, context, canEdit, isOwner, onChange }) {
const element = binding.element;
const [text, setText] = useState(element.kind === "note" ? documentToText(element.document) : "");
const [note, setNote] = useState("");
const [targets, setTargets] = useState([]);
const [targetKey, setTargetKey] = useState("");
const [error, setError] = useState("");
const [notice, setNotice] = useState("");
async function saveNote(event) {
event.preventDefault();
setError("");
try {
const updated = await api(`/api/v1/notes/${element.id}`, {
method: "PATCH",
body: {
expected_version: element.version,
document: textToDocument(text),
...(context ? { context } : {}),
},
});
markDirty(false);
setNotice(updated.notice);
onChange();
} catch (err) {
setError(err.message);
}
}
async function annotate(event) {
event.preventDefault();
setError("");
const params = new URLSearchParams();
if (context) {
params.set("context_kind", context.kind);
params.set("context_id", context.id);
}
try {
await api(`/api/v1/bindings/${binding.id}/annotations?${params}`, { method: "POST", body: { body: note } });
setNote("");
markDirty(false);
onChange();
} catch (err) {
setError(err.message);
}
}
async function detach() {
if (!window.confirm("Nur diese Einbindung entfernen? Das Element und andere Kontexte bleiben erhalten.")) return;
const params = new URLSearchParams();
if (context) {
params.set("context_kind", context.kind);
params.set("context_id", context.id);
}
await api(`/api/v1/bindings/${binding.id}?${params}`, { method: "DELETE" });
onChange();
}
async function destroy() {
if (!window.confirm("Das Element überall löschen? Alle Einbindungen verschwinden. Eine Paperless-Quelle bleibt unangetastet.")) return;
await api(`/api/v1/elements/${element.id}/delete`, { method: "POST", body: { expected_version: element.version } });
onChange();
}
async function loadTargets() {
if (targets.length) return;
const data = await api("/api/v1/placement-targets");
setTargets(data.items);
}
async function bindElsewhere(event) {
event.preventDefault();
const target = targets.find((item) => `${item.kind}:${item.id}` === targetKey);
if (!target || !context) return;
const body = {
element_id: element.id,
source_context: context,
target: { kind: target.kind, id: target.id },
};
if (target.kind === "matter") {
const via = (target.contexts || []).find((item) => item.kind === "direct") || target.contexts?.[0];
if (via && via.kind !== "direct") body.target_context = { kind: via.kind, id: via.id };
}
setError("");
try {
await api("/api/v1/bindings", { method: "POST", body });
setTargetKey("");
onChange();
} catch (err) {
setError(err.message);
}
}
async function protect(event) {
const remove = event.target.checked;
await api("/api/v1/exceptions", {
method: "PUT",
body: {
resource_kind: "element",
resource_id: element.id,
context,
remove_read: false,
remove_edit: remove,
remove_share: false,
},
});
onChange();
}
const dates = element.dates || {};
return (
<article className="item">
<header className="item-head">
<div>
<p className="eyebrow">{kindLabel(element.kind)}</p>
<h3>{element.title}</h3>
</div>
<div className="row">
{canEdit ? <button type="button" className="quiet" onClick={detach}>Aus diesem Kontext entfernen</button> : null}
{isOwner ? <button type="button" className="danger" onClick={destroy}>Überall löschen</button> : null}
</div>
</header>
<DateLine dates={dates} />
{element.kind === "note" ? (
<form onSubmit={saveNote} className="stack">
<label>
Gemeinsamer Text
<textarea
rows={5}
value={text}
onChange={(event) => {
setText(event.target.value);
markDirty(true);
}}
disabled={!binding.rights.edit}
/>
</label>
<p className="muted">Diese Änderung betrifft den gemeinsamen Inhalt der Notiz.</p>
{notice ? <p className="notice">{notice}</p> : null}
{binding.rights.edit ? <button type="submit">Text speichern</button> : <p className="muted">In diesem Kontext nur lesbar.</p>}
</form>
) : null}
{element.kind === "file" && element.file ? (
element.file.status === "active" ? (
<button type="button" onClick={() => downloadFile(element.id, context, element.file.filename)}>
{element.file.filename} herunterladen
</button>
) : (
<p className="error">Die Datei ist gerade nicht verfügbar.</p>
)
) : null}
{element.kind === "external_ref" && element.external ? (
<p className="ref">
{element.external.source === "paperless" ? "Paperless" : "Externe Adresse"} {element.external.external_id}
<span>Nur eine Referenz, keine Kopie und kein Abruf.</span>
</p>
) : null}
{binding.rights.share && context ? (
<form onSubmit={bindElsewhere} className="inline" onFocus={loadTargets}>
<select value={targetKey} onChange={(event) => setTargetKey(event.target.value)} onFocus={loadTargets}>
<option value="">In weiteren Kontext einbinden</option>
{targets
.filter((item) => !(item.kind === context.kind && item.id === context.id))
.map((item) => (
<option key={`${item.kind}:${item.id}`} value={`${item.kind}:${item.id}`}>
{item.kind === "case" ? "Akte" : "Vorgang"}: {item.title}
</option>
))}
</select>
<button type="submit" disabled={!targetKey}>Einbinden</button>
</form>
) : null}
{isOwner && context ? (
<label className="check">
<input type="checkbox" checked={Boolean(binding.exception?.remove_edit)} onChange={protect} />
Schreibschutz in diesem Kontext
</label>
) : null}
<div className="annotations">
<h4>Anmerkungen nur hier</h4>
{binding.annotations.length ? (
<ul>
{binding.annotations.map((item) => (
<li key={item.id}>
<strong>{item.author_display_name}</strong>
<span>{item.body}</span>
</li>
))}
</ul>
) : (
<p className="muted">Keine Anmerkung in diesem Kontext.</p>
)}
{canEdit ? (
<form onSubmit={annotate} className="inline">
<input
value={note}
onChange={(event) => {
setNote(event.target.value);
markDirty(true);
}}
placeholder="Anmerkung für diesen Kontext"
/>
<button type="submit">Anmerken</button>
</form>
) : null}
</div>
<ErrorNote error={error} />
</article>
);
}
function DateLine({ dates }) {
const parts = [
["Dokumentdatum", dates.document_on],
["Versand", dates.sent_on],
["Zugang", dates.received_on],
["Erfassung", dates.recorded_at ? dates.recorded_at.slice(0, 10) : null],
].filter(([, value]) => value);
if (!parts.length) return null;
return (
<dl className="dates">
{parts.map(([label, value]) => (
<div key={label}>
<dt>{label}</dt>
<dd>{value}</dd>
</div>
))}
</dl>
);
}
function kindLabel(kind) {
if (kind === "note") return "Notiz";
if (kind === "file") return "Datei";
if (kind === "external_ref") return "Externe Referenz";
return kind;
}
export function ShareBox({ path, grants, onChange }) {
const [email, setEmail] = useState("");
const [canEdit, setCanEdit] = useState(true);
const [canShare, setCanShare] = useState(false);
const [error, setError] = useState("");
async function submit(event) {
event.preventDefault();
setError("");
try {
await api(path, { method: "POST", body: { email, can_read: true, can_edit: canEdit, can_share: canShare } });
setEmail("");
onChange();
} catch (err) {
setError(err.message);
}
}
async function revoke(id) {
await api(`/api/v1/grants/${id}`, { method: "DELETE" });
onChange();
}
return (
<section className="card">
<h2>Freigeben</h2>
<p className="muted">Bearbeiten und Weitergeben sind getrennt. Die Freigabe gilt für diesen Kontext, nicht für andere Akten.</p>
<form onSubmit={submit} className="stack">
<label>
E-Mail
<input type="email" value={email} onChange={(event) => setEmail(event.target.value)} required />
</label>
<label className="check"><input type="checkbox" checked={canEdit} onChange={(event) => setCanEdit(event.target.checked)} /> Bearbeiten</label>
<label className="check"><input type="checkbox" checked={canShare} onChange={(event) => setCanShare(event.target.checked)} /> Weitergeben</label>
<button type="submit">Freigeben</button>
<ErrorNote error={error} />
</form>
{grants?.length ? (
<ul className="people">
{grants.map((grant) => (
<li key={grant.id}>
<span>{grant.display_name} · {grant.email}</span>
<small>{grant.can_edit ? "Bearbeiten" : "Lesen"}{grant.can_share ? ", Weitergeben" : ""}</small>
<button type="button" className="quiet" onClick={() => revoke(grant.id)}>Entziehen</button>
</li>
))}
</ul>
) : null}
</section>
);
}
export function RecordLink({ kind, id, title, context }) {
const params = new URLSearchParams();
if (context?.kind && context.kind !== "direct") {
params.set("context_kind", context.kind);
params.set("context_id", context.id);
}
const suffix = params.toString() ? `?${params}` : "";
const path = kind === "case" ? `/cases/${id}` : `/matters/${id}${suffix}`;
return <Link to={path}>{title}</Link>;
}
+3
View File
@@ -0,0 +1,3 @@
import { createContext } from "react";
export const SessionContext = createContext(null);
+113
View File
@@ -0,0 +1,113 @@
:root {
color: #1c1915;
background: #f3efe6;
font-family: "Segoe UI", "Helvetica Neue", sans-serif;
line-height: 1.45;
}
* { box-sizing: border-box; }
body { margin: 0; }
button, input, select, textarea {
font: inherit;
color: inherit;
}
button, .linkish {
background: #1f4d3a;
color: #f7f4ee;
border: 0;
border-radius: 999px;
padding: 0.45rem 0.9rem;
cursor: pointer;
}
button.quiet, button.danger {
background: transparent;
color: #1f4d3a;
border: 1px solid #cfc4b2;
}
button.danger { color: #8c3a32; }
button:disabled { opacity: 0.6; }
input, select, textarea {
width: 100%;
border: 1px solid #d9d0c2;
background: #fffdf8;
border-radius: 0.6rem;
padding: 0.55rem 0.7rem;
}
label { display: grid; gap: 0.3rem; font-size: 0.92rem; }
a { color: #1f4d3a; }
h1, h2, h3, h4 { font-family: Georgia, "Iowan Old Style", serif; font-weight: 500; margin: 0; }
.boot, .login { min-height: 100vh; display: grid; place-items: center; padding: 2rem; }
.login-card { width: min(32rem, 100%); }
.card, .assumption {
background: #fffdf8;
border: 1px solid #e4dccb;
border-radius: 1rem;
padding: 1rem 1.1rem;
}
.assumption { background: #f6f1e4; }
.stack { display: grid; gap: 0.75rem; }
.stack.compact { align-content: start; }
.inline { display: flex; gap: 0.6rem; flex-wrap: wrap; align-items: center; }
.inline > input, .inline > select { flex: 1 1 14rem; }
.row { display: flex; gap: 0.4rem; flex-wrap: wrap; }
.eyebrow { letter-spacing: 0.08em; text-transform: uppercase; font-size: 0.75rem; margin: 0; color: #6d6458; }
.lead, .muted, .notice { color: #5e564c; }
.error { color: #8c3a32; }
.banner { margin: 0 1.25rem; }
.app { min-height: 100vh; }
.top, .nav, .page { padding: 0.9rem 1.25rem; }
.top { display: flex; gap: 1rem; align-items: end; flex-wrap: wrap; border-bottom: 1px solid #e4dccb; }
.brand { display: grid; }
.brand a { font-family: Georgia, serif; font-size: 1.5rem; text-decoration: none; }
.scope { min-width: 14rem; }
.search { flex: 1 1 12rem; }
.nav { display: flex; gap: 1rem; }
.nav a { text-decoration: none; }
.nav a.active { border-bottom: 2px solid #1f4d3a; }
.page { display: grid; gap: 1rem; }
.page-head { display: flex; justify-content: space-between; gap: 1rem; }
.split, .forms { display: grid; gap: 1rem; grid-template-columns: repeat(auto-fit, minmax(16rem, 1fr)); }
.index, .work, .people, .timeline { list-style: none; padding: 0; margin: 0; display: grid; gap: 0.7rem; }
.index li, .work li, .people li { display: flex; justify-content: space-between; gap: 0.8rem; align-items: center; padding-bottom: 0.6rem; border-bottom: 1px solid #eee6d8; }
.work li { align-items: start; }
.work li div, .people li { display: grid; }
.item { border-top: 1px solid #eee6d8; padding-top: 0.8rem; display: grid; gap: 0.6rem; }
.item-head { display: flex; justify-content: space-between; gap: 1rem; align-items: start; }
.dates { display: flex; gap: 1rem; flex-wrap: wrap; margin: 0; }
.dates div { display: grid; }
.dates dt { font-size: 0.75rem; color: #6d6458; }
.dates dd { margin: 0; }
.annotations ul { padding-left: 1rem; }
.annotations li { display: grid; }
.ref { display: grid; }
.check { display: flex; gap: 0.5rem; align-items: center; }
.check input { width: auto; }
.demo { border-top: 1px solid #eee6d8; padding-top: 0.8rem; }
.demo ul { padding-left: 1.1rem; }
.demo li { margin: 0.4rem 0; }
.timeline li { display: grid; grid-template-columns: 7.5rem 1fr; gap: 0.8rem; }
.timeline div { display: grid; }
@media (max-width: 720px) {
.timeline li { grid-template-columns: 1fr; }
.item-head, .index li, .work li { display: grid; }
}
+13
View File
@@ -0,0 +1,13 @@
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
export default defineConfig({
plugins: [react()],
server: {
port: 5173,
proxy: {
"/api": "http://127.0.0.1:8000",
"/health": "http://127.0.0.1:8000",
},
},
});