From ad6240a5da51d271f73039c68fcb5041026ac495 Mon Sep 17 00:00:00 2001 From: Lars Date: Sat, 17 Oct 2026 18:30:26 +0200 Subject: [PATCH] Unterscheide Eingang und Ausgang an der Einbindung und ermoegliche Umbenennen, Archivieren, Loeschen und Verschieben. Co-authored-by: Cursor --- backend/app/api/routes.py | 100 +++++++++ backend/app/api/schemas.py | 31 +++ backend/app/content/documents.py | 7 +- backend/app/ops.py | 171 +++++++++++++++- backend/app/present.py | 51 +++-- backend/app/sources.py | 65 +++++- ...261017T180000Z_communication_direction.sql | 7 + backend/tests/test_direction.py | 192 ++++++++++++++++++ backend/tests/test_mailboxes.py | 46 +++++ backend/tests/test_references.py | 30 +-- docs/architecture/TSUMUGU_TECHNICAL_SPEC.md | 2 +- .../TSUMUGU_KOMMUNIKATIONSRICHTUNG_AUFTRAG.md | 87 ++++++++ docs/product/TSUMUGU_PRODUCT_SPEC.md | 14 +- .../TSUMUGU_SYMBOLS_LOGOFRAME_AUFTRAG.md | 2 +- docs/product/TSUMUGU_UX_MVP_ERGAENZUNG.md | 8 +- .../dark/communication-in.svg | 1 + .../dark/communication-out.svg | 1 + .../light/communication-in.svg | 1 + .../light/communication-out.svg | 1 + frontend/src/api.js | 3 +- frontend/src/markdown.jsx | 65 ++++++ frontend/src/pages/Cases.jsx | 53 ++++- frontend/src/pages/Matters.jsx | 136 +++++++++++++ frontend/src/pages/ReadingPane.jsx | 53 +++-- frontend/src/pages/Sources.jsx | 12 +- frontend/src/pages/content.jsx | 125 ++++++++++-- frontend/src/styles.css | 15 ++ 27 files changed, 1191 insertions(+), 88 deletions(-) create mode 100644 backend/migrations/20261017T180000Z_communication_direction.sql create mode 100644 backend/tests/test_direction.py create mode 100644 docs/product/TSUMUGU_KOMMUNIKATIONSRICHTUNG_AUFTRAG.md create mode 100644 frontend/public/ui/content-symbols-v1/dark/communication-in.svg create mode 100644 frontend/public/ui/content-symbols-v1/dark/communication-out.svg create mode 100644 frontend/public/ui/content-symbols-v1/light/communication-in.svg create mode 100644 frontend/public/ui/content-symbols-v1/light/communication-out.svg create mode 100644 frontend/src/markdown.jsx diff --git a/backend/app/api/routes.py b/backend/app/api/routes.py index df511aa..9814ae7 100644 --- a/backend/app/api/routes.py +++ b/backend/app/api/routes.py @@ -43,6 +43,11 @@ from app.api.schemas import ( CaseLinkIn, CasePatch, ChapterDateIn, + ChapterDeleteIn, + ChapterTitleIn, + CommunicationIn, + MatterMoveIn, + RecordDeleteIn, ChapterIn, ChapterOrderIn, CrossLinkIn, @@ -100,8 +105,11 @@ from app.ops import ( create_matter, create_note, create_task, + delete_case, + delete_chapter, delete_cross_link, delete_element, + delete_matter, detach_binding, fulfill_deadline, grant_access, @@ -118,9 +126,12 @@ from app.ops import ( patch_task, revoke_grant, move_binding_chapter, + move_matter, reorder_bindings, + rename_chapter, reorder_chapters, set_chapter_date, + set_communication_direction, set_content_order, set_exception, unlink_matter_case, @@ -688,6 +699,92 @@ def post_matter_chapter_order( return {"version": version} +@router.patch("/api/v1/chapters/{chapter_id}/title") +def patch_chapter_title( + chapter_id: UUID, + body: ChapterTitleIn, + principal: Principal = Depends(get_principal), + conn: Connection = Depends(get_conn), +): + version = rename_chapter( + conn, principal.account_id, chapter_id, body.expected_version, body.title, _ctx_model(body.context) + ) + return {"version": version, "title": body.title} + + +@router.post("/api/v1/chapters/{chapter_id}/delete") +def post_delete_chapter( + chapter_id: UUID, + body: ChapterDeleteIn, + principal: Principal = Depends(get_principal), + conn: Connection = Depends(get_conn), +): + version = delete_chapter( + conn, principal.account_id, chapter_id, body.expected_version, _ctx_model(body.context) + ) + return {"version": version} + + +@router.post("/api/v1/cases/{case_id}/delete") +def post_delete_case( + case_id: UUID, + body: RecordDeleteIn, + principal: Principal = Depends(get_principal), + conn: Connection = Depends(get_conn), +): + delete_case(conn, principal.account_id, case_id, body.expected_version) + return {"ok": True} + + +@router.post("/api/v1/matters/{matter_id}/delete") +def post_delete_matter( + matter_id: UUID, + body: RecordDeleteIn, + principal: Principal = Depends(get_principal), + conn: Connection = Depends(get_conn), +): + delete_matter(conn, principal.account_id, matter_id, body.expected_version, _ctx_model(body.context)) + return {"ok": True} + + +@router.post("/api/v1/matters/{matter_id}/move") +def post_move_matter( + matter_id: UUID, + body: MatterMoveIn, + principal: Principal = Depends(get_principal), + conn: Connection = Depends(get_conn), +): + matter = move_matter( + conn, + principal.account_id, + matter_id, + body.expected_version, + _ctx_model(body.context), + body.case_id, + body.parent_matter_id, + body.clear_parent, + ) + return matter_summary(conn, principal.account_id, matter) + + +@router.patch("/api/v1/bindings/{binding_id}/communication") +def patch_communication( + binding_id: UUID, + body: CommunicationIn, + principal: Principal = Depends(get_principal), + conn: Connection = Depends(get_conn), +): + element = set_communication_direction( + conn, + principal.account_id, + binding_id, + body.expected_version, + body.direction, + _ctx_model(body.context), + ) + return {"version": element["version"], "direction": body.direction} + + @router.patch("/api/v1/chapters/{chapter_id}") def patch_chapter_date( chapter_id: UUID, @@ -799,6 +896,7 @@ def post_note(body: NoteIn, principal: Principal = Depends(get_principal), conn: body.dates.document_on if body.dates else None, body.dates.sent_on if body.dates else None, body.dates.received_on if body.dates else None, + body.communication_direction, ) element = created["element"] return _created( @@ -899,6 +997,7 @@ def post_file( document_on: str | None = Form(default=None), sent_on: str | None = Form(default=None), received_on: str | None = Form(default=None), + communication_direction: str | None = Form(default=None), principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn), ): @@ -928,6 +1027,7 @@ def post_file( settings.media_root, settings.upload_max_bytes, request.state.cleanup_files, + communication_direction if communication_direction in {"in", "out"} else None, ) return _created(f"/api/v1/elements/{element['id']}", {"id": str(element["id"]), "title": element["title"]}) diff --git a/backend/app/api/schemas.py b/backend/app/api/schemas.py index 926f664..8390e50 100644 --- a/backend/app/api/schemas.py +++ b/backend/app/api/schemas.py @@ -93,6 +93,36 @@ class ChapterDateIn(APIModel): context: ContextIn | None = None +class ChapterTitleIn(APIModel): + expected_version: int = Field(ge=1) + title: str = Field(min_length=1, max_length=200) + context: ContextIn | None = None + + +class ChapterDeleteIn(APIModel): + expected_version: int = Field(ge=1) + context: ContextIn | None = None + + +class RecordDeleteIn(APIModel): + expected_version: int = Field(ge=1) + context: ContextIn | None = None + + +class MatterMoveIn(APIModel): + expected_version: int = Field(ge=1) + context: ContextIn | None = None + case_id: UUID | None = None + parent_matter_id: UUID | None = None + clear_parent: bool = False + + +class CommunicationIn(APIModel): + expected_version: int = Field(ge=1) + direction: Literal["in", "out"] | None = None + context: ContextIn | None = None + + class MatterIn(APIModel): title: str = Field(min_length=1, max_length=200) parent_matter_id: UUID | None = None @@ -146,6 +176,7 @@ class NoteIn(APIModel): placement: ContextIn | None = None chapter_id: UUID | None = None dates: DatesIn | None = None + communication_direction: Literal["in", "out"] | None = None class ContentOrderIn(APIModel): diff --git a/backend/app/content/documents.py b/backend/app/content/documents.py index e30d524..37079b4 100644 --- a/backend/app/content/documents.py +++ b/backend/app/content/documents.py @@ -1,4 +1,4 @@ -"""Bounded note documents. Only paragraph text is stored.""" +"""Bounded note documents. Paragraphs or one Markdown block are stored.""" from __future__ import annotations @@ -9,6 +9,11 @@ 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.") + if len(blocks) == 1 and isinstance(blocks[0], dict) and blocks[0].get("type") == "markdown": + text = blocks[0].get("text") + if not isinstance(text, str) or len(text) > 100_000: + raise unprocessable("Die Notiz enthält einen nicht unterstützten Block.") + return {"version": 1, "blocks": [{"type": "markdown", "text": text}]} clean = [] for block in blocks: if not isinstance(block, dict) or set(block) - {"type", "text"}: diff --git a/backend/app/ops.py b/backend/app/ops.py index 00dba3e..67994e8 100644 --- a/backend/app/ops.py +++ b/backend/app/ops.py @@ -257,6 +257,152 @@ def create_matter(conn, actor: UUID, scope_id: UUID, title: str, parent_matter_i return row +def _binding_in_page(conn, binding: dict, context: Ctx) -> bool: + if binding["context_kind"] == context.kind and binding["context_id"] == context.id: + return True + if context.kind != "case" or binding["context_kind"] != "matter": + return False + current = binding["context_id"] + seen: set[UUID] = set() + while current and current not in seen: + seen.add(current) + link = conn.execute( + "SELECT 1 FROM matter_case_links WHERE matter_id = %s AND case_id = %s", + (current, context.id), + ).fetchone() + if link is not None: + return True + parent = conn.execute("SELECT parent_matter_id FROM matters WHERE id = %s", (current,)).fetchone() + current = parent["parent_matter_id"] if parent else None + return False + + +def set_communication_direction(conn, actor: UUID, binding_id: UUID, expected: int, direction: str | None, context: Ctx | None) -> dict: + row = conn.execute("SELECT * FROM bindings WHERE id = %s", (binding_id,)).fetchone() + if row is None: + raise not_found() + page = context or Ctx(row["context_kind"], row["context_id"]) + if context is not None and not _binding_in_page(conn, row, context): + raise not_found() + element, rights = require_element(conn, actor, row["element_id"], page, "edit") + if not rights.edit: + raise forbidden() + bump_version(conn, "elements", element["id"], expected) + store_direction(conn, row["id"], direction, True) + audit(conn, actor, element["home_scope_id"], "communication_direction", "element", element["id"], page) + return get_element(conn, element["id"]) + + +def _chapter_container(conn, actor: UUID, chapter_id: UUID, context: Ctx | None): + chapter = conn.execute("SELECT * FROM chapters WHERE id = %s", (chapter_id,)).fetchone() + if chapter is None: + raise not_found() + if chapter["case_id"]: + container, _rights = require_case(conn, actor, chapter["case_id"], "edit") + kind = "case" + else: + container, _rights = require_matter(conn, actor, chapter["matter_id"], context, "edit") + kind = "matter" + return chapter, container, kind + + +def rename_chapter(conn, actor: UUID, chapter_id: UUID, expected: int, title: str, context: Ctx | None) -> int: + chapter, container, kind = _chapter_container(conn, actor, chapter_id, context) + version = bump_version(conn, "cases" if kind == "case" else "matters", container["id"], expected) + conn.execute("UPDATE chapters SET title = %s WHERE id = %s", (title.strip(), chapter["id"])) + audit(conn, actor, container["home_scope_id"], "chapter_renamed", kind, container["id"], context) + return version + + +def delete_chapter(conn, actor: UUID, chapter_id: UUID, expected: int, context: Ctx | None) -> int: + chapter, container, kind = _chapter_container(conn, actor, chapter_id, context) + version = bump_version(conn, "cases" if kind == "case" else "matters", container["id"], expected) + conn.execute("UPDATE bindings SET chapter_id = NULL WHERE chapter_id = %s", (chapter["id"],)) + conn.execute("DELETE FROM chapters WHERE id = %s", (chapter["id"],)) + audit(conn, actor, container["home_scope_id"], "chapter_deleted", kind, container["id"], context) + return version + + +def delete_case(conn, actor: UUID, case_id: UUID, expected: int) -> None: + case, rights = require_case(conn, actor, case_id, "edit") + if not rights.edit: + raise forbidden() + children = conn.execute( + "SELECT id FROM cases WHERE parent_case_id = %s AND deleted_at IS NULL", + (case_id,), + ).fetchall() + links = conn.execute("SELECT id FROM matter_case_links WHERE case_id = %s", (case_id,)).fetchall() + if children or links: + raise unprocessable("Diese Akte enthält noch Unterakten oder Vorgänge. Verschiebe oder lösche sie zuerst.") + bump_version(conn, "cases", case_id, expected) + conn.execute("UPDATE cases SET deleted_at = now(), updated_at = now() WHERE id = %s", (case_id,)) + audit(conn, actor, case["home_scope_id"], "case_deleted", "case", case_id, None) + + +def delete_matter(conn, actor: UUID, matter_id: UUID, expected: int, context: Ctx | None) -> None: + matter, _rights = require_matter(conn, actor, matter_id, context, "edit") + children = conn.execute( + "SELECT id FROM matters WHERE parent_matter_id = %s AND deleted_at IS NULL", + (matter_id,), + ).fetchall() + if children: + raise unprocessable("Dieser Vorgang enthält noch Teilvorgänge. Verschiebe oder lösche sie zuerst.") + bump_version(conn, "matters", matter_id, expected) + conn.execute("UPDATE matters SET deleted_at = now(), updated_at = now() WHERE id = %s", (matter_id,)) + audit(conn, actor, matter["home_scope_id"], "matter_deleted", "matter", matter_id, context) + + +def _matter_parent_chain(conn, matter_id: UUID) -> set[UUID]: + seen: set[UUID] = set() + current = matter_id + while current and current not in seen: + seen.add(current) + row = conn.execute("SELECT parent_matter_id FROM matters WHERE id = %s", (current,)).fetchone() + current = row["parent_matter_id"] if row else None + return seen + + +def move_matter( + conn, + actor: UUID, + matter_id: UUID, + expected: int, + context: Ctx | None, + case_id: UUID | None, + parent_matter_id: UUID | None, + clear_parent: bool, +) -> dict: + matter, _rights = require_matter(conn, actor, matter_id, context, "edit") + if case_id is None and parent_matter_id is None and not clear_parent: + raise unprocessable("Es fehlt ein Ziel.") + bump_version(conn, "matters", matter_id, expected) + if clear_parent: + conn.execute("UPDATE matters SET parent_matter_id = NULL WHERE id = %s", (matter_id,)) + if parent_matter_id is not None: + if parent_matter_id == matter_id or matter_id in _matter_parent_chain(conn, parent_matter_id): + raise unprocessable("Ein Vorgang kann nicht in sich selbst oder in einen eigenen Teilvorgang verschoben werden.") + parent_context = Ctx("case", case_id) if case_id is not None else context + parent, _parent_rights = require_matter(conn, actor, parent_matter_id, parent_context, "edit") + if parent["home_scope_id"] != matter["home_scope_id"]: + raise unprocessable("Der Zielvorgang liegt in einem anderen Datenraum.") + conn.execute("UPDATE matters SET parent_matter_id = %s WHERE id = %s", (parent_matter_id, matter_id)) + if case_id is not None: + require_case(conn, actor, case_id, "edit") + exists = conn.execute( + "SELECT id FROM matter_case_links WHERE matter_id = %s AND case_id = %s", + (matter_id, case_id), + ).fetchone() + if exists is None: + link_matter_to_case(conn, actor, matter_id, case_id, context) + if context is not None and context.kind == "case" and context.id != case_id: + conn.execute( + "DELETE FROM matter_case_links WHERE matter_id = %s AND case_id = %s", + (matter_id, context.id), + ) + audit(conn, actor, matter["home_scope_id"], "matter_moved", "matter", matter_id, context) + return get_matter(conn, matter_id) + + def patch_matter(conn, actor: UUID, matter_id: UUID, expected: int, title: str | None, status: str | None, context: Ctx | None) -> dict: if title is None and status is None: raise unprocessable("Es fehlt eine Änderung.") @@ -519,6 +665,21 @@ def record_dates(conn, actor: UUID, scope_id: UUID, element_id: UUID, context: C audit(conn, actor, scope_id, "correspondence_recorded", "element", element_id, context) +def store_direction(conn, binding_id: UUID, direction: str | None, explicit: bool) -> None: + if not explicit: + return + if direction not in (None, "in", "out"): + raise unprocessable("Die Richtung ist ungültig.") + conn.execute( + """ + UPDATE bindings + SET communication_direction = %s, direction_explicit = true + WHERE id = %s + """, + (direction, binding_id), + ) + + def create_note( conn, actor: UUID, @@ -531,6 +692,7 @@ def create_note( document_on: date | None = None, sent_on: date | None = None, received_on: date | None = None, + communication_direction: str | None = None, ) -> dict: document = clean_document(document) target, rights_context = _placement(context, placement) @@ -541,6 +703,7 @@ def create_note( (element["id"], Json(document)), ) binding = insert_binding(conn, element["id"], target.kind, target.id, chapter_id, actor) + store_direction(conn, binding["id"], communication_direction, communication_direction in ("in", "out")) audit(conn, actor, scope_id, "note_created", "element", element["id"], rights_context or target) if document_on is not None or sent_on is not None or received_on is not None: record_dates(conn, actor, scope_id, element["id"], rights_context or target, document_on, sent_on, received_on) @@ -619,7 +782,7 @@ def add_annotation(conn, actor: UUID, binding_id: UUID, body: str, context: Ctx return row -def create_external(conn, actor: UUID, scope_id: UUID, title: str, source: str, external_id: str, context: Ctx, placement: Ctx | None, chapter_id: UUID | None, document_on, sent_on, received_on, detail: dict | None = None) -> dict: +def create_external(conn, actor: UUID, scope_id: UUID, title: str, source: str, external_id: str, context: Ctx, placement: Ctx | None, chapter_id: UUID | None, document_on, sent_on, received_on, detail: dict | None = None, communication_direction: str | None = None) -> dict: target, rights_context = _placement(context, placement) require_container_edit(conn, actor, target, rights_context) element = _new_element(conn, actor, scope_id, title, "external_ref") @@ -628,12 +791,15 @@ def create_external(conn, actor: UUID, scope_id: UUID, title: str, source: str, (element["id"], source, external_id.strip()[:200], Json(detail or {})), ) binding = insert_binding(conn, element["id"], target.kind, target.id, chapter_id, actor) + adopted = (detail or {}).get("direction") if source == "imap" else None + chosen = communication_direction if communication_direction in ("in", "out") else adopted if adopted in ("in", "out") else None + store_direction(conn, binding["id"], chosen, chosen in ("in", "out")) 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: +def create_file(conn, actor: UUID, scope_id: UUID, title: str, filename: str, data: bytes, context: Ctx, placement: Ctx | None, chapter_id: UUID | None, document_on, sent_on, received_on, media_root: str, max_bytes: int, rollback_files: list[Path], communication_direction: str | None = None) -> dict: if not data or len(data) > max_bytes: raise unprocessable("Die Datei ist leer oder zu groß.") content_type = sniff(data) @@ -671,6 +837,7 @@ def create_file(conn, actor: UUID, scope_id: UUID, title: str, filename: str, da (element["id"], asset_id), ) binding = insert_binding(conn, element["id"], target.kind, target.id, chapter_id, actor) + store_direction(conn, binding["id"], communication_direction, communication_direction in ("in", "out")) 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} diff --git a/backend/app/present.py b/backend/app/present.py index 05bb5f9..fe163bb 100644 --- a/backend/app/present.py +++ b/backend/app/present.py @@ -195,12 +195,13 @@ def _exception(conn, kind: str, resource_id: UUID, context: Ctx | None) -> dict return {"remove_read": row["can_read"], "remove_edit": row["can_edit"], "remove_share": row["can_share"]} -def _reference_view(conn, actor: UUID, element_id: UUID, context: Ctx) -> dict | None: - element = get_element(conn, element_id) - if element is None or not element_rights(conn, actor, element, context).read: - return None - dates = _dates(conn, element) - direction = None +def communication_from_row(conn, binding: dict, element: dict) -> dict: + """Explicit binding direction wins. An adopted mailbox direction may prefill. Dates never do.""" + stored = binding.get("communication_direction") + stored = stored if stored in ("in", "out") else None + if binding.get("direction_explicit"): + return {"direction": stored, "explicit": True} + source = None if element["kind"] == "external_ref": ref = conn.execute( "SELECT source, detail FROM external_references WHERE element_id = %s", @@ -208,12 +209,28 @@ def _reference_view(conn, actor: UUID, element_id: UUID, context: Ctx) -> dict | ).fetchone() detail = (ref["detail"] or {}) if ref is not None and ref["source"] == "imap" else {} if detail.get("direction") in ("in", "out"): - direction = detail["direction"] - if direction is None: - if dates["sent_on"] and not dates["received_on"]: - direction = "out" - elif dates["received_on"] and not dates["sent_on"]: - direction = "in" + source = detail["direction"] + return {"direction": source, "explicit": False} + + +def _reference_view(conn, actor: UUID, element_id: UUID, context: Ctx, container: Ctx) -> dict | None: + element = get_element(conn, element_id) + if element is None or not element_rights(conn, actor, element, context).read: + return None + dates = _dates(conn, element) + row = conn.execute( + """ + SELECT communication_direction, direction_explicit + FROM bindings + WHERE element_id = %s AND context_kind = %s AND context_id = %s + """, + (element["id"], container.kind, container.id), + ).fetchone() + direction = communication_from_row( + conn, + row or {"communication_direction": None, "direction_explicit": False}, + element, + )["direction"] return { "id": str(element["id"]), "title": element["title"], @@ -222,7 +239,7 @@ def _reference_view(conn, actor: UUID, element_id: UUID, context: Ctx) -> dict | } -def _attach_references(conn, actor: UUID, element: dict, context: Ctx, body: dict) -> None: +def _attach_references(conn, actor: UUID, element: dict, context: Ctx, container: Ctx, body: dict) -> None: refers = [] for row in conn.execute( """ @@ -233,7 +250,7 @@ def _attach_references(conn, actor: UUID, element: dict, context: Ctx, body: dic """, (element["id"],), ).fetchall(): - view = _reference_view(conn, actor, row["refers_to_element_id"], context) + view = _reference_view(conn, actor, row["refers_to_element_id"], context, container) if view is not None: refers.append(view) replies = [] @@ -246,7 +263,7 @@ def _attach_references(conn, actor: UUID, element: dict, context: Ctx, body: dic """, (element["id"],), ).fetchall(): - view = _reference_view(conn, actor, row["element_id"], context) + view = _reference_view(conn, actor, row["element_id"], context, container) if view is not None: replies.append(view) if refers: @@ -263,13 +280,15 @@ def binding_payload(conn, actor: UUID, binding: dict, context: Ctx) -> dict | No if not rights.read: return None body = _element_body(conn, element) - _attach_references(conn, actor, element, context, body) + container = Ctx(binding["context_kind"], binding["context_id"]) + _attach_references(conn, actor, element, context, container, body) payload = { "id": str(binding["id"]), "position": binding["position"], "chapter_id": str(binding["chapter_id"]) if binding["chapter_id"] else None, "rights": rights.as_dict(), "annotations": _annotations(conn, binding["id"]), + "communication": communication_from_row(conn, binding, element), "element": body, } if element["owner_subject_id"] == actor: diff --git a/backend/app/sources.py b/backend/app/sources.py index 6a50e3e..58e96d2 100644 --- a/backend/app/sources.py +++ b/backend/app/sources.py @@ -508,8 +508,8 @@ def _fetch_message(client: imaplib.IMAP4, uid: int, mailbox: str) -> dict: raw = _literal(fetched) if status != "OK" or raw is None: raise unprocessable("Die Nachricht lässt sich nicht lesen.") - if len(raw) > 1_500_000: - raise unprocessable("Die Nachricht ist zu groß für die Vorschau.") + if len(raw) > 8_000_000: + return _oversized_message(client, uid, mailbox) message = BytesParser().parsebytes(raw) subject = _decode(message.get("Subject")) or "(ohne Betreff)" return { @@ -522,7 +522,8 @@ def _fetch_message(client: imaplib.IMAP4, uid: int, mailbox: str) -> dict: "direction": _direction(mailbox), "document_on": _mail_date(message.get("Date")), "attachments": _message_attachments(message), - "text": _message_text(message), + "text": (_text := _message_text(message))[:200_000], + "text_truncated": len(_text) > 200_000, } @@ -532,9 +533,61 @@ _SENT_FOLDER = re.compile( ) -def _direction(mailbox: str) -> str: +_INBOX_FOLDER = re.compile( + r"(^|/)(inbox|posteingang|eingang)($|/)", + re.IGNORECASE, +) + + +def _direction(mailbox: str) -> str | None: + """Sent folders are outgoing, an inbox is incoming. Other folder names prove nothing.""" folded = mailbox.casefold().replace("\\", "/") - return "out" if _SENT_FOLDER.search(folded) else "in" + if _SENT_FOLDER.search(folded): + return "out" + if _INBOX_FOLDER.search(folded): + return "in" + return None + + +def _oversized_message(client: imaplib.IMAP4, uid: int, mailbox: str) -> dict: + header = _fetch_header(client, uid, mailbox) or {} + text = _partial_text(client, uid) + if not header and not text: + raise unprocessable("Die Nachricht lässt sich nicht lesen.") + return { + "uid": uid, + "mailbox": mailbox, + "title": header.get("title") or "(ohne Betreff)", + "message_from": header.get("message_from") or "", + "message_to": header.get("message_to") or "", + "message_cc": header.get("message_cc") or "", + "direction": header.get("direction", _direction(mailbox)), + "document_on": header.get("document_on"), + "attachments": header.get("attachments") or [], + "text": text, + "text_truncated": True, + } + + +def _partial_text(client: imaplib.IMAP4, uid: int) -> str: + try: + status, fetched = client.uid("FETCH", str(uid), "(BODY.PEEK[TEXT]<0.200000>)") + except imaplib.IMAP4.error: + return "" + if status != "OK": + return "" + raw = _literal(fetched) + if not raw: + return "" + sample = raw[:200_000] + try: + message = BytesParser().parsebytes(b"Subject: x\r\n\r\n" + sample) + text = _message_text(message) + except Exception: + text = "" + if not text: + text = sample.decode("utf-8", errors="replace") + return text.strip()[:200_000] def _literal(fetched) -> bytes | None: @@ -598,7 +651,7 @@ def _message_text(message) -> str: text = "\n".join(chunk for chunk in plain if chunk).strip() if not text: text = "\n".join(chunk for chunk in html if chunk).strip() - return text[:8000] + return text def _part_text(part) -> str: diff --git a/backend/migrations/20261017T180000Z_communication_direction.sql b/backend/migrations/20261017T180000Z_communication_direction.sql new file mode 100644 index 0000000..0285748 --- /dev/null +++ b/backend/migrations/20261017T180000Z_communication_direction.sql @@ -0,0 +1,7 @@ +ALTER TABLE bindings + ADD COLUMN communication_direction text, + ADD COLUMN direction_explicit boolean NOT NULL DEFAULT false; + +ALTER TABLE bindings + ADD CONSTRAINT bindings_communication_direction + CHECK (communication_direction IS NULL OR communication_direction IN ('in', 'out')); diff --git a/backend/tests/test_direction.py b/backend/tests/test_direction.py new file mode 100644 index 0000000..5a6c25d --- /dev/null +++ b/backend/tests/test_direction.py @@ -0,0 +1,192 @@ +"""Communication direction lives on the binding and is never inferred from dates.""" + +from __future__ import annotations + +from tests.support import Actor, bind_to, case_of, document, matter_of, register + + +def _matter(actor: Actor, matter_id: str) -> dict: + return actor.request("GET", f"/api/v1/matters/{matter_id}") + + +def _binding(detail: dict, title: str) -> dict: + return next(item for item in detail["bindings"] if item["element"]["title"] == title) + + +def _note(actor: Actor, matter_id: str, title: str, direction: str | None = None, **dates) -> dict: + body = { + "title": title, + "document": document(title), + "context": {"kind": "matter", "id": matter_id}, + } + if dates: + body["dates"] = dates + if direction in ("in", "out"): + body["communication_direction"] = direction + return actor.request("POST", "/api/v1/notes", json=body, status=201) + + +def test_dates_do_not_invent_a_direction_and_explicit_choice_survives(client, db): + ada = Actor(client, "ada-richtung@example.test", "Ada Richtung") + ben = Actor(client, "ben-richtung@example.test", "Ben Richtung") + register(db, ada.email, ada.name) + register(db, ben.email, ben.name) + ada.login() + matter = matter_of(ada, "Kautionsabrechnung") + _note(ada, matter["id"], "Beide Daten", document_on="2026-10-12", sent_on="2026-10-01", received_on="2026-10-12") + _note(ada, matter["id"], "Telefon Eingang", "in") + _note(ada, matter["id"], "Telefon Ausgang", "out") + _note(ada, matter["id"], "Gedankenprotokoll") + ada.request( + "POST", + "/api/v1/external-refs", + json={ + "title": "Scan ohne Richtung", + "source": "paperless", + "external_id": "scan-42", + "context": {"kind": "matter", "id": matter["id"]}, + "detail": {"open_url": "https://example.test/scan-42"}, + }, + status=201, + ) + ada.request( + "POST", + "/api/v1/external-refs", + json={ + "title": "Mail der Verwaltung", + "source": "imap", + "external_id": "", + "context": {"kind": "matter", "id": matter["id"]}, + "detail": { + "direction": "in", + "message_from": "Hausverwaltung Mueller", + "mailbox": "INBOX", + }, + }, + status=201, + ) + shown = _matter(ada, matter["id"]) + both = _binding(shown, "Beide Daten") + assert both["communication"] == {"direction": None, "explicit": False} + assert both["element"]["dates"]["sent_on"] == "2026-10-01" + assert both["element"]["dates"]["received_on"] == "2026-10-12" + assert _binding(shown, "Telefon Eingang")["communication"]["direction"] == "in" + assert _binding(shown, "Telefon Ausgang")["communication"]["direction"] == "out" + assert _binding(shown, "Gedankenprotokoll")["communication"]["direction"] is None + assert _binding(shown, "Scan ohne Richtung")["communication"]["direction"] is None + mail = _binding(shown, "Mail der Verwaltung") + assert mail["communication"] == {"direction": "in", "explicit": True} + + ada.request( + "PATCH", + f"/api/v1/bindings/{mail['id']}/communication", + json={"expected_version": mail["element"]["version"], "direction": None, "context": {"kind": "matter", "id": matter["id"]}}, + ) + cleared = _binding(_matter(ada, matter["id"]), "Mail der Verwaltung") + assert cleared["communication"] == {"direction": None, "explicit": True} + + ada.request( + "PATCH", + f"/api/v1/bindings/{both['id']}/communication", + json={"expected_version": both["element"]["version"], "direction": "out", "context": {"kind": "matter", "id": matter["id"]}}, + ) + chosen = _binding(_matter(ada, matter["id"]), "Beide Daten") + assert chosen["communication"] == {"direction": "out", "explicit": True} + + ada.request( + "POST", + f"/api/v1/matters/{matter['id']}/grants", + json={"email": ben.email, "can_read": True, "can_edit": False, "can_share": False}, + status=201, + ) + ben.login() + visible = _binding(_matter(ben, matter["id"]), "Beide Daten") + assert visible["communication"]["direction"] == "out" + ben.request( + "PATCH", + f"/api/v1/bindings/{visible['id']}/communication", + json={"expected_version": visible["element"]["version"], "direction": "in", "context": {"kind": "matter", "id": matter["id"]}}, + status=403, + ) + + +def test_a_second_binding_keeps_its_own_direction(client, db): + ada = Actor(client, "ada-bindung@example.test", "Ada Bindung") + register(db, ada.email, ada.name) + ada.login() + first = case_of(ada, "Erste Akte") + second = case_of(ada, "Zweite Akte") + created = ada.request( + "POST", + "/api/v1/notes", + json={ + "title": "Gemeinsame Notiz", + "document": {"version": 1, "blocks": [{"type": "markdown", "text": "# Anruf\n\n**Eingang**"}]}, + "context": {"kind": "case", "id": first["id"]}, + "communication_direction": "in", + }, + status=201, + ) + bind_to(ada, created["id"], first["id"], second["id"]) + left = ada.request("GET", f"/api/v1/cases/{first['id']}") + right = ada.request("GET", f"/api/v1/cases/{second['id']}") + left_binding = next(item for item in left["bindings"] if item["element"]["title"] == "Gemeinsame Notiz") + right_binding = next(item for item in right["bindings"] if item["element"]["title"] == "Gemeinsame Notiz") + assert left_binding["communication"]["direction"] == "in" + assert right_binding["communication"]["direction"] is None + assert left_binding["element"]["document"]["blocks"][0]["type"] == "markdown" + ada.request( + "PATCH", + f"/api/v1/bindings/{right_binding['id']}/communication", + json={"expected_version": right_binding["element"]["version"], "direction": "out", "context": {"kind": "case", "id": second["id"]}}, + ) + left_again = ada.request("GET", f"/api/v1/cases/{first['id']}") + right_again = ada.request("GET", f"/api/v1/cases/{second['id']}") + assert next(item for item in left_again["bindings"] if item["element"]["id"] == created["id"])["communication"]["direction"] == "in" + assert next(item for item in right_again["bindings"] if item["element"]["id"] == created["id"])["communication"]["direction"] == "out" + + +def test_chapter_and_matter_can_be_renamed_and_moved(client, db): + ada = Actor(client, "ada-struktur@example.test", "Ada Struktur") + register(db, ada.email, ada.name) + ada.login() + case = case_of(ada, "Vermietung") + other = case_of(ada, "Ferienhaus") + matter = matter_of(ada, "Nebenkosten") + ada.request("POST", f"/api/v1/matters/{matter['id']}/case-links", json={"case_id": case["id"]}, status=201) + parent = matter_of(ada, "Wohnung") + ada.request("POST", f"/api/v1/matters/{parent['id']}/case-links", json={"case_id": other["id"]}, status=201) + chapter = ada.request( + "POST", + f"/api/v1/matters/{matter['id']}/chapters", + json={"title": "Schreiben"}, + status=201, + ) + detail = _matter(ada, matter["id"]) + ada.request( + "PATCH", + f"/api/v1/chapters/{chapter['id']}/title", + json={"expected_version": detail["version"], "title": "Korrespondenz", "context": {"kind": "case", "id": case["id"]}}, + ) + current = _matter(ada, matter["id"]) + assert current["chapters"][0]["title"] == "Korrespondenz" + ada.request( + "POST", + f"/api/v1/matters/{matter['id']}/move", + json={ + "expected_version": current["version"], + "context": {"kind": "case", "id": case["id"]}, + "case_id": other["id"], + "parent_matter_id": parent["id"], + }, + ) + moved = _matter(ada, matter["id"]) + assert moved["parent_matter_id"] == parent["id"] + assert any(item["case_id"] == other["id"] for item in moved["placements"]) + assert all(item["case_id"] != case["id"] for item in moved["placements"]) + ada.request( + "POST", + f"/api/v1/cases/{case['id']}/delete", + json={"expected_version": ada.request("GET", f"/api/v1/cases/{case['id']}")["version"]}, + ) + ada.request("GET", f"/api/v1/cases/{case['id']}", status=404) diff --git a/backend/tests/test_mailboxes.py b/backend/tests/test_mailboxes.py index 4105b00..3a73bbe 100644 --- a/backend/tests/test_mailboxes.py +++ b/backend/tests/test_mailboxes.py @@ -149,6 +149,12 @@ def test_folder_pages_newest_first_and_search_stays_inside(client, db, monkeypat assert preview["direction"] == "in" assert preview["message_to"] == "Gegenseite " assert "Einwendung" in preview["text"] + other = ada.request( + "GET", + "/api/v1/sources/imap/messages", + params={"connector_id": account, "mailbox": "&AMQ-nderungen"}, + ) + assert other["items"][0]["direction"] is None assert preview["attachments"][0]["filename"] == "einwendung.pdf" ada.request( "GET", @@ -169,3 +175,43 @@ def test_foreign_mailbox_stays_hidden(client, db, monkeypatch): ben.login() ben.request("GET", "/api/v1/sources/imap/mailboxes", params={"connector_id": account}, status=404) ben.request("GET", "/api/v1/sources/imap/messages", params={"connector_id": account}, status=404) + + +class HugeIMAP(FakeIMAP): + def uid(self, command, *args): + spec = " ".join(str(part) for part in args[1:]) if len(args) > 1 else "" + if command == "FETCH" and "BODY.PEEK[]" in spec: + return "OK", [(b"rfc822", b"x" * 8_000_001)] + if "BODY.PEEK[TEXT]" in spec: + return "OK", [(b"text", "Kurzer Auszug der grossen Nachricht.".encode())] + return super().uid(command, *args) + + +def test_oversized_message_still_returns_text(client, db, monkeypatch): + ada = Actor(client, "ada-huge@example.test", "Ada Gross") + register(db, ada.email, ada.name) + ada.login() + monkeypatch.setattr(sources.imaplib, "IMAP4_SSL", HugeIMAP) + account = ada.request( + "POST", + "/api/v1/connectors", + json={ + "kind": "imap", + "name": "Gross", + "host": "imap.example.test", + "port": 993, + "username": "ada@example.test", + "password": "Postfach-Geheim", + "security": "ssl", + }, + status=201, + )["id"] + preview = ada.request( + "GET", + "/api/v1/sources/imap/message", + params={"connector_id": account, "mailbox": "INBOX", "uid": 2}, + ) + assert "Kurzer Auszug" in preview["text"] + assert preview["text_truncated"] is True + assert preview["direction"] == "in" + assert preview["message_from"] diff --git a/backend/tests/test_references.py b/backend/tests/test_references.py index 27d2fdb..1b6d151 100644 --- a/backend/tests/test_references.py +++ b/backend/tests/test_references.py @@ -5,18 +5,16 @@ from __future__ import annotations from tests.support import Actor, document, register -def _note(actor: Actor, title: str, matter_id: str, **dates) -> None: - actor.request( - "POST", - "/api/v1/notes", - json={ - "title": title, - "document": document(title), - "context": {"kind": "matter", "id": matter_id}, - "dates": dates, - }, - status=201, - ) +def _note(actor: Actor, title: str, matter_id: str, direction: str | None = None, **dates) -> None: + body = { + "title": title, + "document": document(title), + "context": {"kind": "matter", "id": matter_id}, + "dates": dates, + } + if direction in ("in", "out"): + body["communication_direction"] = direction + actor.request("POST", "/api/v1/notes", json=body, status=201) def _by_title(detail: dict) -> dict: @@ -30,9 +28,9 @@ def test_reply_names_its_letter_and_leaves_the_gap(client, db): register(db, ben.email, ben.name) ada.login() matter = ada.request("POST", "/api/v1/matters", json={"title": "Schriftwechsel"}, status=201) - _note(ada, "Anschreiben", matter["id"], document_on="2026-03-12", received_on="2026-03-12") - _note(ada, "Zwischennachricht", matter["id"], document_on="2026-04-02", received_on="2026-04-02") - _note(ada, "Antwort", matter["id"], document_on="2026-05-18", sent_on="2026-05-18") + _note(ada, "Anschreiben", matter["id"], "in", document_on="2026-03-12", received_on="2026-03-12") + _note(ada, "Zwischennachricht", matter["id"], document_on="2026-04-02", received_on="2026-04-02", sent_on="2026-04-02") + _note(ada, "Antwort", matter["id"], "out", document_on="2026-05-18", sent_on="2026-05-18") detail = ada.request("GET", f"/api/v1/matters/{matter['id']}") ada.request( "PATCH", @@ -80,6 +78,8 @@ def test_reply_names_its_letter_and_leaves_the_gap(client, db): ] assert linked["Anschreiben"]["referred_by"][0]["title"] == "Antwort" assert linked["Anschreiben"]["referred_by"][0]["direction"] == "out" + gap = next(item for item in shown["bindings"] if item["element"]["title"] == "Zwischennachricht") + assert gap["communication"]["direction"] is None assert "refers_to" not in linked["Zwischennachricht"] assert "referred_by" not in linked["Zwischennachricht"] ada.request( diff --git a/docs/architecture/TSUMUGU_TECHNICAL_SPEC.md b/docs/architecture/TSUMUGU_TECHNICAL_SPEC.md index 8794278..7e184fa 100644 --- a/docs/architecture/TSUMUGU_TECHNICAL_SPEC.md +++ b/docs/architecture/TSUMUGU_TECHNICAL_SPEC.md @@ -196,7 +196,7 @@ Gemeinsame Spalten der fachlichen Ankerobjekte `cases`, `matters`, `elements`, ` | `elements` | `kind` `note`, `correspondence`, `file` oder `external_ref` | Gemeinsamer Inhaltsträger. Rechnungen verweisen auf ein Element, sind aber eigene Finanzobjekte. | | `note_bodies` | `element_id`, `document_json`, `version` | Ein Text je Notiz. Begrenzter Renderbaum aus dem Datei-Blueprint, keine freie HTML-Ablage. | | `correspondence_dates` | `element_id`, `document_on`, `sent_on`, `received_on` | Vier getrennte Datumssachen. `recorded_at` ist `elements.created_at`. | -| `bindings` | `element_id`, `context_kind`, `context_id`, `chapter_id` null, `position`, `release_state` | Kontext ist Akte, Vorgang oder Zusammenstellung. `release_state` `visible` oder `pending` für noch nicht freigegebene neue Zusammenstellungsinhalte. | +| `bindings` | `element_id`, `context_kind`, `context_id`, `chapter_id` null, `position`, `release_state`, `communication_direction` null, `direction_explicit` | Kontext ist Akte, Vorgang oder Zusammenstellung. `release_state` `visible` oder `pending` für noch nicht freigegebene neue Zusammenstellungsinhalte. `communication_direction` ist `in`, `out` oder leer und gilt nur für diese Einbindung. `direction_explicit` wahr hält eine bewusste Wahl oder ein bewusstes Leeren; sonst darf nur eine übernommene IMAP-Richtung `in` oder `out` vorgefüllt werden. Versand- und Zugangsdatum sind keine Richtung. | | `context_annotations` | `binding_id`, `body`, `author_subject_id` | Gehört zur Einbindung, nicht zum gemeinsamen Text. | | `access_grants` | `grantee_subject_id`, `resource_kind`, `resource_id`, `context_kind`, `context_id`, `can_read`, `can_edit`, `can_share`, `can_delete` | Explizite Grants. Vererbung wird berechnet und nur bei Abweichung materialisiert. | | `compilations` | Ankerfelder | Virtuelle Zusammenstellung. | diff --git a/docs/product/TSUMUGU_KOMMUNIKATIONSRICHTUNG_AUFTRAG.md b/docs/product/TSUMUGU_KOMMUNIKATIONSRICHTUNG_AUFTRAG.md new file mode 100644 index 0000000..172493d --- /dev/null +++ b/docs/product/TSUMUGU_KOMMUNIKATIONSRICHTUNG_AUFTRAG.md @@ -0,0 +1,87 @@ +# Tsumugu: Kommunikationsrichtung – Spezifikation und Cursor-Auftrag + +**Stand:** 17.10.2026 · **Fassung:** 1.0 · **Umfang:** bestehendes MVP gezielt ergänzen, lokal prüfbar umsetzen. + +## Ziel und Einordnung + +Beim Lesen eines Vorgangs muss unmittelbar erkennbar sein, welche Kommunikation eingegangen und welche ausgegangen ist. Eine Notiz bezeichnet eine Gesprächs-/Gedankenaufzeichnung, ein PDF ein Dateiformat und Paperless eine Quelle. Diese Merkmale sind unabhängig von der Kommunikationsrichtung. + +Dieser Auftrag präzisiert F-06e der [Produktspezifikation](TSUMUGU_PRODUCT_SPEC.md). Er ergänzt den [Symbolauftrag](TSUMUGU_SYMBOLS_LOGOFRAME_AUFTRAG.md) und die vorhandenen Beziehungen/Schriftwechsel aus F-06d. Bestehende Antworten-/Bezugsverknüpfungen, Kapitel, Reihenfolge und große Leseransicht bleiben erhalten. Die bisherige pauschale Ableitung „Zugangsdatum = Eingang, Versanddatum = Ausgang“ ist durch die folgenden Regeln ersetzt. + +## 1. Darstellung + +- Inhaltstyp-Symbol behalten. Daneben ein kleines Richtungssignal mit sichtbarem Text **„Eingang“** oder **„Ausgang“**. Keine eigene kombinierte Bilddatei für jede Kombination aus Format und Richtung. +- Bekannte Beteiligte als **„Von: …“** beziehungsweise **„An: …“** anzeigen. Keine Person erfinden, wenn nur die Richtung bekannt ist. Bei Bedarf sind beide Angaben in den Details sichtbar. +- Kommunikationsdatum verständlich benennen, etwa „Eingegangen am“ bzw. „Versendet am“. Dokumentdatum, Zugangsdatum, Versanddatum und Import-/Änderungszeitpunkt nicht gleichsetzen. Bestehende fachliche Sortierung und manuelle Reihenfolge nicht stillschweigend verändern. +- Beispiel einer Zeile: `PDF · [Richtungszeichen] Eingang · Von: Hausverwaltung Müller · Eingegangen am 12.10.2026`, darunter Titel und kurzer Auszug. Bei Ausgang entsprechend Empfänger und Versanddatum. +- In Liste, Leser und vorhandenem Schriftwechsel dieselbe Richtungslogik verwenden. In schmalen Ansichten darf die Metadatenzeile umbrechen; Titel, Typ und Richtung bleiben lesbar. Kein zusätzlicher Navigationsbereich. +- Form und Text vermitteln die Bedeutung; Farbe kann ergänzen. Keine nur per Hover verfügbare Kennzeichnung. Dekorative Bilddatei neben dem Text mit leerem Alttext einbinden. Pfeile nicht als unbeschriftete Aktionstasten darstellen. + +## 2. Bedeutung und einfache Eingabe + +**Richtung ist optional.** Minimaler fachlicher Zustand: + +| Angabe | Bedeutung | Listenanzeige | +|---|---|---| +| Eingang | Kommunikation an die im Vorgang vertretene Seite | Zeichen + „Eingang“ | +| Ausgang | Kommunikation von der im Vorgang vertretenen Seite | Zeichen + „Ausgang“ | +| Keine Richtungsangabe | Keine Kommunikation oder Richtung noch unbekannt | Kein Richtungssignal | + +Im Bearbeiten-Dialog reicht eine Auswahl **„Keine Angabe / Eingang / Ausgang“**. Leer ist weder automatisch „intern“ noch „eingegangen“. Kein zusätzliches Pflichtfeld und keine neue Statusmaschine. Das Entfernen einer zuvor gesetzten Richtung muss speicherbar sein und darf anschließend nicht durch einen Fallback sofort zurückgesetzt werden. + +- Gesprächsnotiz über einen eingehenden Anruf: Notizsymbol + Eingang. Selbst initiierter Anruf: Notizsymbol + Ausgang. Gedankenprotokoll oder Gespräch ohne sinnvolle Richtung: Notizsymbol ohne Richtungszeichen. Keine neue Notiz-Untertypenverwaltung erforderlich. +- Eine Richtung ist keine Versandbestätigung: Die Auswahl versendet keine Nachricht, setzt keine Frist und erledigt keine Aufgabe. Ein Entwurf darf nicht ohne bestätigten Versand als tatsächlich versendet erscheinen. + +## 3. Bezugsseite und Mehrfacheinbindung + +- Eingang/Ausgang bezieht sich auf die Person oder Organisation, deren Kommunikation im aktiven Vorgang dokumentiert wird. Die Richtung darf bei Benutzerwechsel oder späterem Anwaltszugang nicht umspringen. +- Vorhandene geeignete Angaben zur vertretenen Seite nutzen. Wo diese nicht eindeutig ist, Richtung bewusst manuell erfassen; keine automatische Vermutung aus Login, Eigentümer, Anleger oder Importeur. Für diesen Ausbau kein neues Kontakt-/Parteienregister bauen. +- Bei Einbindung desselben Elements in unterschiedliche Kontexte darf eine dort abweichende Bezugsseite nicht zu einer global falschen Richtungsänderung führen. Dafür vorhandene Einbindungs-/Kontextmetadaten nutzen oder minimal ergänzen. Der Datei-/Notizinhalt bleibt gemeinsam. Eine lokale Zuordnung oder Korrektur darf keine fremde Einbindung überschreiben oder deren Daten offenlegen. +- Gleiche Bezugsseite und unveränderte Kommunikationsdaten konsistent anzeigen. Keine neue Kopie der Datei zur bloßen Richtungsänderung anlegen. Konkrete Speicherung anhand des vorhandenen Modells dokumentieren; keine zusätzliche generische Kommunikationsplattform entwickeln. + +## 4. Quellen, Bestandsdaten und Korrekturen + +- Belastbare explizite Quellinformation darf die Richtung vorbelegen, beispielsweise eine beim Übernehmen gesicherte E-Mail-Richtung. Bloße Ordnernamen, Paperless als Quelle, PDF als Format, Titel, Importzeit oder Ersteller sind kein hinreichender Nachweis. +- Ein Versand- oder Zugangsdatum allein ist ohne eindeutige Bezugsseite kein allgemeiner Richtungsbeweis. Ein Schreiben hat häufig beide Daten. Daraus nicht gleichzeitig „Eingang · Ausgang“ als Richtung desselben Eintrags ableiten. Beide Daten bleiben als unterschiedliche Sachangaben erhalten. +- Vorhandene eindeutige Richtungsangaben erhalten. Unklare Bestandsdaten leer lassen; keine Massenklassifizierung nach Vermutung. Bei Widersprüchen keine zufällige Vorrangentscheidung treffen: Richtung als ungeklärt behandeln und eine gezielte Korrektur ermöglichen, Daten nicht löschen. +- Manuelle Korrektur und bewusstes Leeren müssen Vorrang vor einer automatischen Vorbelegung behalten. Hierfür die kleinste geeignete Kennzeichnung im bestehenden Datenmodell verwenden. Kein Hintergrundimport darf die Korrektur still überschreiben. +- Lese- und Änderungsrechte des aktiven Kontexts gelten unverändert auch für Richtung und Beteiligte. Ein lesender Anwalt sieht dieselben freigegebenen Angaben; er erhält daraus keine neuen Rechte. + +## 5. Fertige Zeichen verwenden + +Symbolpaket **1.2**, weiterhin unter: + +`C:/Dev/jinkendo-app-design-2026-10-17/assets/content-symbols-v1/` + +- `light/communication-in.svg`, `light/communication-out.svg`: dunkelgrün für helle Arbeitsflächen. +- `dark/communication-in.svg`, `dark/communication-out.svg`: mintfarben für dunkle Flächen. +- Entsprechende PNGs unter `/png/24`, `48`, `96`. +- Passende SVG-Größe ungefähr 16–18px neben dem sichtbaren Text. Die gelieferten Konturen aus Lucide verwenden und Lizenz übernehmen; keine Emoji-Pfeile oder frei gezeichneten Ersatzsymbole. Das bestehende `note.svg` bleibt die Sprechblase mit Stift aus Fassung 1.1. + +Keine neue Bibliothek installieren. Das Richtungszeichen ergänzt Typ und Quelle; ein PDF aus Paperless behält sein PDF-Symbol und seine Quellenangabe. + +## 6. Gezielter Umsetzungseinstieg + +Vor Änderungen den aktuellen Stand prüfen und laufende Änderungen erhalten. Bei Erstellung dieses Auftrags waren bereits `content.jsx`, `ReadingPane.jsx`, `Sources.jsx`, API-Schemas und Korrespondenzdaten vorhanden. Wiederverwenden, keine zweite parallele Richtungslogik aufbauen. + +Insbesondere prüfen/korrigieren: + +- `mailFacts` in `frontend/src/pages/content.jsx` verwendet bisher für jede Richtung außer `out` den Text „Eingang“. Fehlend/ungültig muss ohne Richtung bleiben. +- `dateFlow` leitet bisher aus `sent_on`/`received_on` Richtungsangaben ab und zeigt bei beiden „Eingang · Ausgang“. Durch die fachlich eindeutige Logik ersetzen; Datumsfelder erhalten. +- Entsprechende Standardannahmen in E-Mail-Vorschau und Leser (`Sources.jsx`, `ReadingPane.jsx`) angleichen. +- Vorhandene API-/Persistenzfelder gezielt ergänzen, soweit für explizite Richtung, Korrekturen und Kontextbezug erforderlich. Rückwärtskompatible Migration; keine destruktive Umdeutung der Bestandsdaten. Relevante technische Dokumentation anpassen. + +## 7. Abnahme + +Mit synthetischen Daten prüfen und konkrete Ergebnisse liefern: + +1. Eingehendes PDF und ausgehendes PDF: gleicher Inhaltstyp, klar unterschiedliche Richtung, richtige Beteiligte/Datumsbezeichnung. +2. Eingehende und ausgehende E-Mail: konsistent in Liste, Leser und Schriftwechsel; unbekannte Richtung wird nicht als Eingang angezeigt. +3. Telefonnotiz mit Eingang, Telefonnotiz mit Ausgang und Gedankenprotokoll ohne Richtung: Notizsymbol bleibt immer eindeutig erhalten. +4. Paperless-Referenz ohne Richtungsnachweis sowie Schreiben mit beiden Datumsfeldern: keine erfundene oder doppelte Richtung. +5. Richtung ändern und leeren, neu laden und erneut öffnen: Änderung bleibt erhalten; automatische Vorbelegung stellt den alten Wert nicht wieder her. +6. Benutzerwechsel bei gleichem Kontext ändert die Richtung nicht. Zweite Einbindung mit anderer Bezugsseite wird nicht durch die erste Korrektur überschrieben. Keine Einsicht in fremde Kontexte. +7. Leserecht allein erlaubt keine Änderung der Kommunikationsangaben. Vorhandene Antwortbezüge, Ordnung und Dokumentöffnung funktionieren weiter. +8. Desktop und Handy, lange Namen/Titel und Bedienung per Tastatur prüfen. Relevante fachliche Tests für Speicherung/Zuordnung/Rechte und vorhandenen Frontend-Build ausführen. Screenshots der synthetischen Beispiele liefern; ausgeführte und nicht ausführbare Prüfungen trennen. + +Arbeite bis zur lokal prüfbaren Umsetzung. Keine erneute Spezifikationsrunde als Endergebnis. Kein Commit, Push oder Deployment durch diesen Auftrag; ein Push auf `develop` würde Development auslösen. Ergebnisse, betroffene Dateien, Prüfungen und tatsächliche Einschränkungen knapp übergeben. Es wird keine erfolgreiche Live-Integration durch das bloße Vorhandensein der Dateien behauptet. diff --git a/docs/product/TSUMUGU_PRODUCT_SPEC.md b/docs/product/TSUMUGU_PRODUCT_SPEC.md index b37c4b5..8d8398a 100644 --- a/docs/product/TSUMUGU_PRODUCT_SPEC.md +++ b/docs/product/TSUMUGU_PRODUCT_SPEC.md @@ -1,6 +1,6 @@ # Tsumugu – Fachliche Produktspezifikation -**Stand:** 17.10.2026 · **Arbeitsstand:** 0.29, Notiz als Gesprächs- / Gedankenaufzeichnung visuell von Schriftstücken getrennt. +**Stand:** 17.10.2026 · **Arbeitsstand:** 0.31, optionale Kommunikationsrichtung unabhängig von Inhaltstyp und Quelle präzisiert. **Status:** Führende fachliche Arbeitsdatei; noch keine freigegebene Gesamtspezifikation. **Aktuelle Ergänzung:** [Bedienung, Orientierung und Aktenordnung im MVP](TSUMUGU_UX_MVP_ERGAENZUNG.md). Sie sichert den Nutzerbedarf aus der Prüfung der inzwischen bestehenden Anwendung und konkrete Umsetzungsvorgaben für deren Überarbeitung. Bestätigter Bedarf und empfohlene Ausgestaltung sind dort getrennt; die historischen Etappenbeschreibungen dieser Datei bleiben als solche erhalten. @@ -372,6 +372,16 @@ Der Nutzer nennt folgende tatsächlich genutzte Felder. Schreibweisen sind als G **Ausgestaltung:** Der Bezug verbindet zwei Elemente. Er ist kein zweites Elternteil und kein Vorgangsquerverweis. Die Inhaltsliste bleibt in ihrer gewählten Ordnung; die Zwischenstücke bleiben eigene Zeilen. An beiden Enden steht der Bezug mit Datum und Titel. Im Leser zeigt der Schriftwechsel nur die verbundenen Unterlagen und ihre Daten. Ein Kreis und ein Selbstbezug sind unzulässig. Ein nicht lesbares Gegenstück wird nicht benannt. E-Mail-Eingang und -Ausgang folgen dem Postfach. Andere Unterlagen zeigen Eingang oder Ausgang, wenn Zugangs- oder Versanddatum gesetzt ist. Die E-Mail-Vorschau lädt den Nachrichtentext; Paperless bleibt der Dateiweg. +### F-06e – Eingehende und ausgehende Kommunikation: 17.10.2026 + +**Nutzerbedarf und Auftrag:** Die Richtung der Kommunikation ist für das Verständnis des Vorgangs entscheidend. Der Nutzer beauftragt nach Besprechung der Trennung von Inhaltstyp und Richtung die Spezifikation und einen Cursor-Prompt. + +**Konkrete Ausgestaltung:** Eingang/Ausgang sind optionale Kommunikationsangaben zusätzlich zum unveränderten Inhaltstyp-Symbol. Eigene Gedankenaufzeichnungen benötigen keine Richtung, Telefonnotizen können Eingang oder Ausgang dokumentieren. Kleine Richtungszeichen mit sichtbarem Text ergänzen bekannte Beteiligte und passend benannte Kommunikationsdaten. Ohne sichere Angabe kein Richtungszeichen und kein automatischer Eingang. Bezugsseite ist die im Vorgang vertretene Person/Organisation, unabhängig vom angemeldeten Betrachter. Abweichende Perspektiven bei Mehrfacheinbindung bleiben kontextbezogen, ohne Kopie des gemeinsamen Inhalts oder neue Rechte. + +**Präzisierung gegenüber F-06d:** Datumsfelder allein sind kein allgemeiner Richtungsnachweis; ein Schriftstück kann sowohl Versand- als auch Zugangsdatum haben. Keine gleichzeitige Richtung „Eingang · Ausgang“ daraus ableiten. Eindeutige explizite Quelldaten dürfen vorbelegen, manuelle Korrektur oder bewusstes Leeren bleiben erhalten. Kein Pflichtfeld, keine Massenklassifizierung, kein Versandworkflow und kein neues Parteienregister. + +**Lieferung:** Symbolpaket 1.2 ergänzt zwei einzelne Richtungszeichen. Fachliche Details, gezielte technische Einstiegspunkte und Abnahme stehen in [TSUMUGU_KOMMUNIKATIONSRICHTUNG_AUFTRAG.md](TSUMUGU_KOMMUNIKATIONSRICHTUNG_AUFTRAG.md). Der Beziehungsausbau F-06d wird erhalten; die Richtungsregeln werden durch diesen späteren Auftrag präzisiert. + ## 6. Fortschreibung 16.10.2026, Arbeitsstand 0.1: Recovery vollständig gelesen, Repository-Unterlagen gezielt abgeglichen, ursprüngliche Nutzernachrichten geprüft und Ergänzungen gesichert. Historische Baseline unverändert übernommen. @@ -434,4 +444,6 @@ Der Nutzer nennt folgende tatsächlich genutzte Felder. Schreibweisen sind als G 17.10.2026, Arbeitsstand 0.30: Nutzerauftrag F-06d aufgenommen. Ein Element kann sich auf ein anderes beziehen; die chronologische Lücke bleibt in der Liste. E-Mail-Vorschau, Richtung und Anhänge werden nach Typ und Herkunft geladen. Kein neues Elternverhältnis und keine Änderung an Aktenrechten. +17.10.2026, Arbeitsstand 0.31: F-06e und Cursor-Auftrag zur optionalen Kommunikationsrichtung ergänzt. Unbekannt ist kein Eingang; Bezugsseite, manuelle Korrekturen und Mehrfacheinbindung berücksichtigt. Symbolpaket 1.2 um Eingang/Ausgang ergänzt. Keine Anwendungscode- oder Deploymentänderung durch diesen Dokumentationsauftrag. + Nach jeder Entscheidung diese Datei mit kurzer Begründung und Auswirkungen auf Fachmodell/MVP aktualisieren. Die historische Baseline bleibt unverändert. Keine Implementierung ohne ausdrückliche Freigabe; technische Umsetzung später anhand der dann freigegebenen Jinkendo-Blueprints. diff --git a/docs/product/TSUMUGU_SYMBOLS_LOGOFRAME_AUFTRAG.md b/docs/product/TSUMUGU_SYMBOLS_LOGOFRAME_AUFTRAG.md index 2cd7046..6ea8682 100644 --- a/docs/product/TSUMUGU_SYMBOLS_LOGOFRAME_AUFTRAG.md +++ b/docs/product/TSUMUGU_SYMBOLS_LOGOFRAME_AUFTRAG.md @@ -4,7 +4,7 @@ ## Fertige Lieferungen lesen und verwenden -1. [Inhalts-/Struktursymbole](C:/Dev/jinkendo-app-design-2026-10-17/assets/content-symbols-v1/README.md): 24 Motive, je eine einzelne SVG-Datei für helle und dunkle Flächen; transparente PNGs zusätzlich. Lizenz mit übernehmen. Keine neue Iconbibliothek installieren; keine SVG-Geometrien neu zeichnen. +1. [Inhalts-/Struktursymbole](C:/Dev/jinkendo-app-design-2026-10-17/assets/content-symbols-v1/README.md): inzwischen 26 Motive, Paketfassung 1.2, je eine einzelne SVG-Datei für helle und dunkle Flächen; transparente PNGs zusätzlich. Lizenz mit übernehmen. Keine neue Iconbibliothek installieren; keine SVG-Geometrien neu zeichnen. Die zwei zusätzlichen Richtungszeichen ergänzen den Inhaltstyp gemäß [Kommunikationsauftrag](TSUMUGU_KOMMUNIKATIONSRICHTUNG_AUFTRAG.md). 2. [Logo auf dunkler Fläche](C:/Dev/jinkendo-app-design-2026-10-17/assets/logos-on-dark-v1/README.md): vorbereitete transparente gerahmte PNGs aller fünf Produkte sowie CSS für einen stationären Rahmen um die vorhandene Markenanimation. 3. [Bestehender Animationsauftrag](TSUMUGU_ENSO_ANIMATION_AUFTRAG.md): gilt weiter; durch diesen Auftrag wird nur die passende dunkle Trägerfläche ergänzt. Die Favicons bleiben die statischen Innenmotive v2. diff --git a/docs/product/TSUMUGU_UX_MVP_ERGAENZUNG.md b/docs/product/TSUMUGU_UX_MVP_ERGAENZUNG.md index e058cef..6ed9c3a 100644 --- a/docs/product/TSUMUGU_UX_MVP_ERGAENZUNG.md +++ b/docs/product/TSUMUGU_UX_MVP_ERGAENZUNG.md @@ -1,6 +1,6 @@ # Tsumugu – Ergänzung zur Bedienung, Orientierung und Aktenordnung im MVP -**Stand:** 17.10.2026 · **Fassung:** 0.4, Bezug zwischen Unterlagen und herkunftsabhängige Vorschau konkretisiert +**Stand:** 17.10.2026 · **Fassung:** 0.5, optionale Kommunikationsrichtung mit eindeutiger Bezugsseite ergänzt **Zweck:** Referenz für die Überarbeitung der bestehenden MVP-Anwendung durch den Coding-Agenten. **Bezug:** [Fachliche Produktspezifikation](TSUMUGU_PRODUCT_SPEC.md), insbesondere S-01a–d, F-04a und F-05a; [technischer Entwurf](../architecture/TSUMUGU_TECHNICAL_SPEC.md). @@ -11,6 +11,8 @@ ## 1. Ziel und Verbindlichkeit +**Neueste Präzisierung F-06e:** Inhaltstyp, Quelle und Kommunikationsrichtung getrennt darstellen. Eingang/Ausgang erscheinen als kleines Zusatzzeichen mit Text; unbekannte Richtung oder eigene Gedanken bleiben ohne Richtungssignal. Die Richtung bezieht sich auf die vertretene Seite im aktiven Vorgang, nicht auf den angemeldeten Nutzer. Datumsfelder allein begründen keine eindeutige Richtung, beide Felder nicht zu „Eingang · Ausgang“ verbinden. Bestehende Vorbelegung nur bei belastbaren Quelldaten, bewusste Korrektur/Leeren erhalten. [Spezifikation und konkreter Cursor-Auftrag](TSUMUGU_KOMMUNIKATIONSRICHTUNG_AUFTRAG.md), einschließlich fertiger SVG-/PNG-Zeichen im Symbolpaket 1.2. + Die bestehende erste Lieferung „Organisieren und Nachverfolgen“ soll im Alltag verständlich und praktisch bedienbar werden. Die Überarbeitung umfasst Darstellung und Bedienabläufe sowie die dafür erforderlichen gezielten Anpassungen an Schnittstellen und Speicherung. Ein reiner Austausch von Farben und Abständen erfüllt diesen Auftrag nicht. Die Reihenfolge innerhalb einer Akte kann selbst fachliche Information tragen. Nutzer müssen Zusammenhänge erkennen, Inhalte sinnvoll anordnen und die nächste Arbeit schnell erreichen können. Das technische Änderungsprotokoll darf diese Arbeitsansicht nicht bestimmen. @@ -173,7 +175,7 @@ Ein Schreiben kann die Antwort auf ein bestimmtes früheres Schreiben sein. Der - Der Leser zeigt denselben Schriftwechsel als eigene Folge, nur aus den verbundenen Unterlagen. Die Lücke bleibt in der Inhaltsliste sichtbar. - Ein Klick auf den Bezug öffnet die andere Unterlage, ohne die gewählte Liste oder ihre Position zu wechseln. - Der Bezug ist kein Kapitel, kein zweites Elternteil und kein Querverweis zwischen Vorgängen. -- Eingang und Ausgang sind an E-Mails aus dem Postfach erkennbar, an anderen Unterlagen aus Versand- oder Zugangsdatum. Absender, Empfänger und Anhänge bleiben an der übernommenen E-Mail sichtbar. +- Eingang und Ausgang folgen der optionalen, eindeutigen Kommunikationsangabe gemäß F-06e. Eindeutige Postfachmetadaten können vorbelegen; Versand-/Zugangsdatum allein ist kein allgemeiner Richtungsnachweis. Absender, Empfänger und Anhänge bleiben an der übernommenen E-Mail sichtbar. ### 7.4 Speicherung und Interaktion @@ -304,6 +306,8 @@ Ein Push auf `develop` löst laut Repository einen Development-Deploy aus. Der r ## 15. Fortschreibung +- **0.5:** F-06e: optionale Kommunikationsrichtung unabhängig von Format/Quelle, stabile Bezugsseite, sichtbare Zeichen mit Text und keine falschen Standardwerte. Symbolpaket 1.2 und gesonderter Cursor-Auftrag verlinkt. Beziehungsausbau aus 0.4 bleibt erhalten. + - **0.3:** Aktueller Nutzerbedarf F-06c: gelieferte Typ-Symbole als verlässliche Orientierung; Miniaturen nur bei erkennbarem Nutzen; Notiz mit Auszug; keine Leerboxen oder ewiges Thumbnail-Laden; große Leseansicht bleibt. Frühere pauschale Thumbnail-Pflicht ersetzt. Kein Fachmodell-/Rechtewechsel. - **0.1:** Erste lesende Oberflächenprüfung, Ausgangsanforderungen und 13 Abnahmekriterien. diff --git a/frontend/public/ui/content-symbols-v1/dark/communication-in.svg b/frontend/public/ui/content-symbols-v1/dark/communication-in.svg new file mode 100644 index 0000000..e27d404 --- /dev/null +++ b/frontend/public/ui/content-symbols-v1/dark/communication-in.svg @@ -0,0 +1 @@ +Kommunikation: Eingang diff --git a/frontend/public/ui/content-symbols-v1/dark/communication-out.svg b/frontend/public/ui/content-symbols-v1/dark/communication-out.svg new file mode 100644 index 0000000..ba23dd0 --- /dev/null +++ b/frontend/public/ui/content-symbols-v1/dark/communication-out.svg @@ -0,0 +1 @@ +Kommunikation: Ausgang diff --git a/frontend/public/ui/content-symbols-v1/light/communication-in.svg b/frontend/public/ui/content-symbols-v1/light/communication-in.svg new file mode 100644 index 0000000..ee8f2c1 --- /dev/null +++ b/frontend/public/ui/content-symbols-v1/light/communication-in.svg @@ -0,0 +1 @@ +Kommunikation: Eingang diff --git a/frontend/public/ui/content-symbols-v1/light/communication-out.svg b/frontend/public/ui/content-symbols-v1/light/communication-out.svg new file mode 100644 index 0000000..7be84cd --- /dev/null +++ b/frontend/public/ui/content-symbols-v1/light/communication-out.svg @@ -0,0 +1 @@ +Kommunikation: Ausgang diff --git a/frontend/src/api.js b/frontend/src/api.js index a3f75f1..05210f3 100644 --- a/frontend/src/api.js +++ b/frontend/src/api.js @@ -123,8 +123,7 @@ export async function downloadFile(elementId, context, filename) { } 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: "" }] }; + return { version: 1, blocks: [{ type: "markdown", text: text || "" }] }; } export function documentToText(document) { diff --git a/frontend/src/markdown.jsx b/frontend/src/markdown.jsx new file mode 100644 index 0000000..14fce46 --- /dev/null +++ b/frontend/src/markdown.jsx @@ -0,0 +1,65 @@ +import { Fragment } from "react"; + +function inline(text, keyPrefix) { + const pattern = /(\*\*[^*]+\*\*|\*[^*]+\*|`[^`]+`|\[[^\]]+\]\(https?:\/\/[^)\s]+\))/g; + const nodes = []; + let last = 0; + let index = 0; + for (const match of text.matchAll(pattern)) { + if (match.index > last) nodes.push(text.slice(last, match.index)); + const token = match[0]; + const key = `${keyPrefix}-${index}`; + if (token.startsWith("**")) nodes.push({token.slice(2, -2)}); + else if (token.startsWith("*")) nodes.push({token.slice(1, -1)}); + else if (token.startsWith("`")) nodes.push({token.slice(1, -1)}); + else { + const linked = token.match(/^\[([^\]]+)\]\((https?:\/\/[^)\s]+)\)$/); + if (linked) { + nodes.push({linked[1]}); + } + } + last = match.index + token.length; + index += 1; + } + if (last < text.length) nodes.push(text.slice(last)); + return nodes; +} + +export function MarkdownView({ text }) { + const lines = String(text || "").replace(/\r\n/g, "\n").split("\n"); + const blocks = []; + let list = null; + function closeList() { + if (!list) return; + const items = list.items.map((item, index) =>
  • {inline(item, `${list.key}-${index}`)}
  • ); + blocks.push(list.ordered ?
      {items}
    :
      {items}
    ); + list = null; + } + lines.forEach((line, index) => { + const heading = line.match(/^(#{1,3})\s+(.*)$/); + const bullet = line.match(/^\s*[-*]\s+(.*)$/); + const numbered = line.match(/^\s*\d+\.\s+(.*)$/); + if (heading) { + closeList(); + const Tag = heading[1].length === 1 ? "h3" : heading[1].length === 2 ? "h4" : "h5"; + blocks.push({inline(heading[2], `h-${index}`)}); + return; + } + if (bullet || numbered) { + if (!list || list.ordered !== Boolean(numbered)) { + closeList(); + list = { key: `l-${index}`, ordered: Boolean(numbered), items: [] }; + } + list.items.push((bullet || numbered)[1]); + return; + } + closeList(); + if (!line.trim()) { + blocks.push(); + return; + } + blocks.push(

    {inline(line, `p-${index}`)}

    ); + }); + closeList(); + return
    {blocks}
    ; +} diff --git a/frontend/src/pages/Cases.jsx b/frontend/src/pages/Cases.jsx index b9c8ee1..bdb9599 100644 --- a/frontend/src/pages/Cases.jsx +++ b/frontend/src/pages/Cases.jsx @@ -5,7 +5,7 @@ import { SessionContext } from "../session.js"; import { Modal } from "./Modal.jsx"; import { MailPicker, PaperlessPicker } from "./Sources.jsx"; import { ErrorNote, ShareBox } from "./widgets.jsx"; -import { ContentBoard, ObjectMenu, OrderChoice, RecordTree, SurfaceView, TargetLine, Trail, WorkLists, WorkSwitch, saveChapterOrder, writeSelection } from "./content.jsx"; +import { ContentBoard, DirectionChoice, MarkdownEditor, ObjectMenu, OrderChoice, RecordTree, SurfaceView, TargetLine, Trail, WorkLists, WorkSwitch, saveChapterOrder, writeSelection } from "./content.jsx"; import { ReadingPane } from "./ReadingPane.jsx"; import { StructureNavigator, Workspace, rememberScroll, restoreScroll, useWorkspaceLayout } from "./workspace.jsx"; import { NavIcon } from "./icons.jsx"; @@ -276,7 +276,10 @@ function caseNodes(record, parentRecord) { kind: "Akte", href: `/cases/${parentRecord.id}`, current: false, - children: siblings.length ? siblings : [self], + children: [ + ...(siblings.length ? siblings : [self]), + ...(parentRecord.matters || []).map((matter) => matterNode(matter, parentRecord.id)), + ], }]; } @@ -306,6 +309,40 @@ export function CaseDetail() { return detail; } + async function renameCase() { + const title = window.prompt("Aktenname", record.title); + if (!title || title.trim() === record.title) return; + setError(""); + try { + await api(`/api/v1/cases/${id}`, { method: "PATCH", body: { expected_version: record.version, title: title.trim() } }); + load(); + } catch (err) { + setError(err.message); + } + } + + async function archiveCase() { + const next = record.status === "closed" ? "open" : "closed"; + setError(""); + try { + await api(`/api/v1/cases/${id}`, { method: "PATCH", body: { expected_version: record.version, status: next } }); + load(); + } catch (err) { + setError(err.message); + } + } + + async function deleteCase() { + if (!window.confirm("Diese Akte löschen? Unterakten und zugeordnete Vorgänge müssen vorher gelöst sein. Inhalte bleiben erhalten.")) return; + setError(""); + try { + await api(`/api/v1/cases/${id}/delete`, { method: "POST", body: { expected_version: record.version } }); + navigate("/cases"); + } catch (err) { + setError(err.message); + } + } + useEffect(() => { let alive = true; setRecord(null); @@ -496,6 +533,9 @@ export function CaseDetail() { {record.rights.edit ? : null} {record.rights.edit ? : null} {record.rights.share || record.is_owner ? : null} + {record.rights.edit ? : null} + {record.rights.edit ? : null} + {record.rights.edit ? : null} @@ -821,6 +861,7 @@ export function NoteForm({ context, placement, chapters = [], initialChapter = " const [documentOn, setDocumentOn] = useState(""); const [sentOn, setSentOn] = useState(""); const [receivedOn, setReceivedOn] = useState(""); + const [direction, setDirection] = useState(""); const [chapterId, setChapterId] = useState(initialChapter); const [error, setError] = useState(""); const [pending, setPending] = useState(false); @@ -848,6 +889,7 @@ export function NoteForm({ context, placement, chapters = [], initialChapter = " received_on: receivedOn || null, }, } : {}), + ...(direction ? { communication_direction: direction } : {}), }, }); setTitle(""); @@ -855,6 +897,7 @@ export function NoteForm({ context, placement, chapters = [], initialChapter = " setDocumentOn(""); setSentOn(""); setReceivedOn(""); + setDirection(""); markDirty(false); onChange(); } catch (err) { @@ -869,7 +912,8 @@ export function NoteForm({ context, placement, chapters = [], initialChapter = "

    Notiz

    -