Compare commits
37
Commits
03a17b0d2e
...
V1.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1bc464e36f | ||
|
|
75a3949f7c | ||
|
|
564925bb6a | ||
|
|
562c0848b1 | ||
|
|
37662c2bd8 | ||
|
|
79241831fd | ||
|
|
2b100eb934 | ||
|
|
989e1cb22a | ||
|
|
3bfd641b9b | ||
|
|
5905df6c17 | ||
|
|
60a76803e1 | ||
|
|
59434a4045 | ||
|
|
97401a6d84 | ||
|
|
ea28c4f246 | ||
|
|
8b74e63417 | ||
|
|
2b23992a1a | ||
|
|
5b23e4aab0 | ||
|
|
a5350bc76e | ||
|
|
e3274bce21 | ||
|
|
0c611763c3 | ||
|
|
430108823c | ||
|
|
3f60901b71 | ||
|
|
9b9a09b97c | ||
|
|
f8cb9f8d4b | ||
|
|
20fa183c1c | ||
|
|
7e8a3e865e | ||
|
|
7846830765 | ||
|
|
9f5327f3be | ||
|
|
be027a1025 | ||
|
|
c774fb7206 | ||
|
|
c138df5e68 | ||
|
|
3c190c87b4 | ||
|
|
81fc4d495b | ||
|
|
f21c64a944 | ||
|
|
deb5d662fe | ||
|
|
fdcc6d3475 | ||
|
|
cbd45a8997 |
No files matched your search
@@ -43,3 +43,6 @@ tmp/
|
||||
temp/
|
||||
data/local/
|
||||
*.db
|
||||
backend/data/
|
||||
backend/.pytest-tmp/
|
||||
backend/.pytest-export-tmp/
|
||||
@@ -4,4 +4,4 @@ Fachlich führend ist `docs/product/TSUMUGU_PRODUCT_SPEC.md`. Der technische Ent
|
||||
|
||||
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.
|
||||
Die Anwendung bleibt produktlokal: FastAPI, PostgreSQL, React. Keine gemeinsame Fachdatenbank mit anderen Jinkendo-Anwendungen. Finanzfunktionen, Paperless-Abgleich, KI und ein Anwaltszugang ohne eigenes Konto gehören nicht in diese Lieferung. Eine berechtigte Person mit Konto kann freigegebene verknüpfte Dokumente und E-Mails über die Zugänge des Owners lesen, ohne eigene Paperless- oder IMAP-Verbindungen.
|
||||
@@ -11,6 +11,8 @@ from dataclasses import dataclass
|
||||
from typing import Any
|
||||
from uuid import UUID
|
||||
|
||||
from psycopg.types.json import Json
|
||||
|
||||
from app.core.errors import conflict, forbidden, not_found, unprocessable
|
||||
|
||||
SHARED_NOTICE = "Diese Änderung betrifft den gemeinsamen Inhalt der Notiz."
|
||||
@@ -87,14 +89,17 @@ def audit(
|
||||
resource_id: UUID,
|
||||
context: Ctx | None = None,
|
||||
occurred_on=None,
|
||||
*,
|
||||
result: str = "ok",
|
||||
detail: dict | None = None,
|
||||
) -> None:
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO domain_events (
|
||||
actor_subject_id, scope_id, action, resource_kind, resource_id,
|
||||
context_kind, context_id, occurred_on
|
||||
context_kind, context_id, occurred_on, result, detail
|
||||
)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
|
||||
""",
|
||||
(
|
||||
actor_id,
|
||||
@@ -105,6 +110,8 @@ def audit(
|
||||
context.kind if context else None,
|
||||
context.id if context else None,
|
||||
occurred_on,
|
||||
result,
|
||||
Json(detail) if detail is not None else None,
|
||||
),
|
||||
)
|
||||
|
||||
@@ -348,6 +355,59 @@ def _child_of(conn, matter_id: UUID, parent_id: UUID) -> bool:
|
||||
return bool(matter and matter["parent_matter_id"] == parent_id)
|
||||
|
||||
|
||||
def _rights_bearing_case(conn, case: dict) -> dict:
|
||||
seen: set[UUID] = set()
|
||||
current = case
|
||||
while current["parent_case_id"] is not None and current["rights_mode"] == "inherit_parent":
|
||||
if current["id"] in seen:
|
||||
break
|
||||
seen.add(current["id"])
|
||||
parent = get_case(conn, current["parent_case_id"])
|
||||
if parent is None:
|
||||
break
|
||||
current = parent
|
||||
return current
|
||||
|
||||
|
||||
def _source_grant(conn, actor: UUID, kind: str, resource_id: UUID) -> dict | None:
|
||||
return conn.execute(
|
||||
"""
|
||||
SELECT can_read, use_owner_sources
|
||||
FROM access_grants
|
||||
WHERE NOT is_exception
|
||||
AND grantee_subject_id = %s
|
||||
AND resource_kind = %s
|
||||
AND resource_id = %s
|
||||
AND context_kind IS NULL
|
||||
""",
|
||||
(actor, kind, resource_id),
|
||||
).fetchone()
|
||||
|
||||
|
||||
def mediated_source_owner(conn, actor: UUID, element: dict, context: Ctx | None) -> UUID | None:
|
||||
"""Owner whose stored connector may serve this reader. None unless the grant allows it."""
|
||||
if context is None or not element_rights(conn, actor, element, context).read:
|
||||
return None
|
||||
if context.kind == "case":
|
||||
resource = get_case(conn, context.id)
|
||||
if resource is None:
|
||||
return None
|
||||
resource = _rights_bearing_case(conn, resource)
|
||||
grant = _source_grant(conn, actor, "case", resource["id"])
|
||||
elif context.kind == "matter":
|
||||
resource = get_matter(conn, context.id)
|
||||
if resource is None:
|
||||
return None
|
||||
grant = _source_grant(conn, actor, "matter", resource["id"])
|
||||
else:
|
||||
return None
|
||||
if resource["owner_subject_id"] == actor:
|
||||
return None
|
||||
if grant is None or not grant["can_read"] or not grant["use_owner_sources"]:
|
||||
return None
|
||||
return resource["owner_subject_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.
|
||||
|
||||
|
||||
@@ -0,0 +1,269 @@
|
||||
"""HTTP for attachment roles, documented dispatches and secured editions."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import APIRouter, Depends, Request, Response
|
||||
from psycopg import Connection
|
||||
|
||||
from app.access.policy import Ctx
|
||||
from app.api.deps import Principal, get_conn, get_principal
|
||||
from app.api.schemas import (
|
||||
AttachmentAssignIn,
|
||||
AttachmentDetachIn,
|
||||
AttachmentOrderIn,
|
||||
DispatchCorrectIn,
|
||||
DispatchEvidenceDetachIn,
|
||||
DispatchEvidenceIn,
|
||||
DispatchIn,
|
||||
FoldIn,
|
||||
)
|
||||
from app.correspondence import (
|
||||
GapNote,
|
||||
add_dispatch_evidence,
|
||||
assign_attachments,
|
||||
detach_dispatch_evidence,
|
||||
correct_dispatch,
|
||||
detach_attachment,
|
||||
dispatch_view,
|
||||
open_container,
|
||||
order_attachments,
|
||||
read_snapshot,
|
||||
record_dispatch,
|
||||
set_fold,
|
||||
)
|
||||
from app.core.errors import not_found
|
||||
from app.media.storage import content_disposition
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
def _ctx(value) -> Ctx:
|
||||
return Ctx(value.kind, value.id)
|
||||
|
||||
|
||||
def _placement(value) -> Ctx | None:
|
||||
if value is None:
|
||||
return None
|
||||
return Ctx(value.kind, value.id)
|
||||
|
||||
|
||||
@router.post("/api/v1/elements/{element_id}/attachments", status_code=201)
|
||||
def post_attachments(
|
||||
element_id: UUID,
|
||||
body: AttachmentAssignIn,
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
return assign_attachments(
|
||||
conn,
|
||||
principal.account_id,
|
||||
element_id,
|
||||
body.expected_version,
|
||||
_ctx(body.context),
|
||||
_placement(body.placement),
|
||||
body.attachment_element_ids,
|
||||
body.fold,
|
||||
[],
|
||||
)
|
||||
|
||||
|
||||
@router.post("/api/v1/elements/{element_id}/attachments/order")
|
||||
def post_attachment_order(
|
||||
element_id: UUID,
|
||||
body: AttachmentOrderIn,
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
return order_attachments(
|
||||
conn,
|
||||
principal.account_id,
|
||||
element_id,
|
||||
body.expected_version,
|
||||
_ctx(body.context),
|
||||
_placement(body.placement),
|
||||
body.attachment_element_ids,
|
||||
)
|
||||
|
||||
|
||||
@router.post("/api/v1/elements/{element_id}/attachments/{attachment_id}/detach", status_code=204)
|
||||
def post_detach(
|
||||
element_id: UUID,
|
||||
attachment_id: UUID,
|
||||
body: AttachmentDetachIn,
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
detach_attachment(
|
||||
conn,
|
||||
principal.account_id,
|
||||
element_id,
|
||||
attachment_id,
|
||||
body.expected_version,
|
||||
_ctx(body.context),
|
||||
_placement(body.placement),
|
||||
)
|
||||
|
||||
|
||||
@router.patch("/api/v1/bindings/{binding_id}/fold")
|
||||
def patch_fold(
|
||||
binding_id: UUID,
|
||||
body: FoldIn,
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
return set_fold(
|
||||
conn,
|
||||
principal.account_id,
|
||||
binding_id,
|
||||
body.expected_version,
|
||||
_ctx(body.context),
|
||||
_placement(body.placement),
|
||||
body.fold,
|
||||
)
|
||||
|
||||
|
||||
@router.post("/api/v1/elements/{element_id}/dispatches", status_code=201)
|
||||
def post_dispatch(
|
||||
element_id: UUID,
|
||||
body: DispatchIn,
|
||||
request: Request,
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
request.state.cleanup_files = []
|
||||
return record_dispatch(
|
||||
conn,
|
||||
principal.account_id,
|
||||
element_id,
|
||||
body.expected_version,
|
||||
_ctx(body.context),
|
||||
_placement(body.placement),
|
||||
body.channel,
|
||||
body.sent_on,
|
||||
body.counterpart,
|
||||
body.attachment_element_ids,
|
||||
[item.model_dump() for item in body.evidence],
|
||||
body.historical_gap,
|
||||
body.capture_editions,
|
||||
request.app.state.settings.media_root,
|
||||
request.state.cleanup_files,
|
||||
)
|
||||
|
||||
|
||||
@router.post("/api/v1/dispatches/{dispatch_id}/evidence", status_code=201)
|
||||
def post_evidence(
|
||||
dispatch_id: UUID,
|
||||
body: DispatchEvidenceIn,
|
||||
request: Request,
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
request.state.cleanup_files = []
|
||||
return add_dispatch_evidence(
|
||||
conn,
|
||||
principal.account_id,
|
||||
dispatch_id,
|
||||
body.expected_version,
|
||||
_ctx(body.context),
|
||||
_placement(body.placement),
|
||||
body.element_id,
|
||||
body.role,
|
||||
body.fold,
|
||||
request.app.state.settings.media_root,
|
||||
request.state.cleanup_files,
|
||||
)
|
||||
|
||||
|
||||
@router.post("/api/v1/dispatches/{dispatch_id}/evidence/{element_id}/detach", status_code=204)
|
||||
def post_detach_evidence(
|
||||
dispatch_id: UUID,
|
||||
element_id: UUID,
|
||||
body: DispatchEvidenceDetachIn,
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
detach_dispatch_evidence(
|
||||
conn,
|
||||
principal.account_id,
|
||||
dispatch_id,
|
||||
element_id,
|
||||
body.expected_version,
|
||||
_ctx(body.context),
|
||||
_placement(body.placement),
|
||||
)
|
||||
|
||||
|
||||
@router.post("/api/v1/dispatches/{dispatch_id}/correct")
|
||||
def post_correct(
|
||||
dispatch_id: UUID,
|
||||
body: DispatchCorrectIn,
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
return correct_dispatch(
|
||||
conn,
|
||||
principal.account_id,
|
||||
dispatch_id,
|
||||
body.expected_version,
|
||||
_ctx(body.context),
|
||||
_placement(body.placement),
|
||||
body.channel,
|
||||
body.sent_on,
|
||||
body.clear_sent_on,
|
||||
body.counterpart,
|
||||
body.clear_counterpart,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/api/v1/dispatches/{dispatch_id}")
|
||||
def get_dispatch(
|
||||
dispatch_id: UUID,
|
||||
context_kind: str,
|
||||
context_id: UUID,
|
||||
placement_kind: str | None = None,
|
||||
placement_id: UUID | None = None,
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
context = Ctx(context_kind, context_id)
|
||||
placement = Ctx(placement_kind, placement_id) if placement_kind and placement_id else None
|
||||
_row, page, scope = open_container(conn, principal.account_id, context, placement, "read")
|
||||
return dispatch_view(conn, principal.account_id, dispatch_id, page, scope)
|
||||
|
||||
|
||||
@router.get("/api/v1/dispatches/{dispatch_id}/items/{item_id}/content")
|
||||
def get_dispatch_item(
|
||||
dispatch_id: UUID,
|
||||
item_id: UUID,
|
||||
context_kind: str,
|
||||
context_id: UUID,
|
||||
request: Request,
|
||||
placement_kind: str | None = None,
|
||||
placement_id: UUID | None = None,
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
context = Ctx(context_kind, context_id)
|
||||
placement = Ctx(placement_kind, placement_id) if placement_kind and placement_id else None
|
||||
result = read_snapshot(
|
||||
conn,
|
||||
principal.account_id,
|
||||
dispatch_id,
|
||||
item_id,
|
||||
context,
|
||||
placement,
|
||||
request.app.state.settings.media_root,
|
||||
)
|
||||
if isinstance(result, GapNote):
|
||||
raise not_found()
|
||||
return Response(
|
||||
content=result.data,
|
||||
media_type=result.media_type or "application/octet-stream",
|
||||
headers={
|
||||
"Content-Disposition": content_disposition(result.filename),
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
"Cache-Control": "private, no-store",
|
||||
},
|
||||
)
|
||||
@@ -78,6 +78,7 @@ from app.api.schemas import (
|
||||
TaskDependencyIn,
|
||||
TaskElementsIn,
|
||||
SummaryPatch,
|
||||
TitlePatch,
|
||||
TaskIn,
|
||||
TaskPatch,
|
||||
)
|
||||
@@ -142,6 +143,7 @@ from app.ops import (
|
||||
update_dates,
|
||||
update_note,
|
||||
update_summary,
|
||||
update_title,
|
||||
)
|
||||
from app.present import (
|
||||
LABELS,
|
||||
@@ -641,7 +643,16 @@ def post_case_grant(
|
||||
if account is None:
|
||||
raise not_found()
|
||||
grant = grant_access(
|
||||
conn, principal.account_id, "case", case_id, account["id"], body.can_read, body.can_edit, body.can_share, None
|
||||
conn,
|
||||
principal.account_id,
|
||||
"case",
|
||||
case_id,
|
||||
account["id"],
|
||||
body.can_read,
|
||||
body.can_edit,
|
||||
body.can_share,
|
||||
None,
|
||||
body.use_owner_sources,
|
||||
)
|
||||
return _created(f"/api/v1/grants/{grant['id']}", {"id": str(grant["id"])})
|
||||
|
||||
@@ -906,7 +917,16 @@ def post_matter_grant(
|
||||
if account is None:
|
||||
raise not_found()
|
||||
grant = grant_access(
|
||||
conn, principal.account_id, "matter", matter_id, account["id"], body.can_read, body.can_edit, body.can_share, None
|
||||
conn,
|
||||
principal.account_id,
|
||||
"matter",
|
||||
matter_id,
|
||||
account["id"],
|
||||
body.can_read,
|
||||
body.can_edit,
|
||||
body.can_share,
|
||||
None,
|
||||
body.use_owner_sources,
|
||||
)
|
||||
return _created(f"/api/v1/grants/{grant['id']}", {"id": str(grant["id"])})
|
||||
|
||||
@@ -1458,9 +1478,17 @@ def patch_case_order(
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
version = set_content_order(
|
||||
conn, principal.account_id, "case", case_id, body.expected_version, body.mode, body.direction, None
|
||||
conn,
|
||||
principal.account_id,
|
||||
"case",
|
||||
case_id,
|
||||
body.expected_version,
|
||||
body.mode,
|
||||
body.direction,
|
||||
None,
|
||||
body.view,
|
||||
)
|
||||
return {"version": version, "mode": body.mode, "direction": body.direction}
|
||||
return {"version": version, "mode": body.mode, "direction": body.direction, "view": body.view}
|
||||
|
||||
|
||||
@router.post("/api/v1/cases/{case_id}/bindings/order")
|
||||
@@ -1512,8 +1540,9 @@ def patch_matter_order(
|
||||
body.mode,
|
||||
body.direction,
|
||||
_ctx_model(body.context),
|
||||
body.view,
|
||||
)
|
||||
return {"version": version, "mode": body.mode, "direction": body.direction}
|
||||
return {"version": version, "mode": body.mode, "direction": body.direction, "view": body.view}
|
||||
|
||||
|
||||
@router.post("/api/v1/matters/{matter_id}/bindings/order")
|
||||
@@ -1593,6 +1622,24 @@ def patch_element_summary(
|
||||
return {"id": str(element["id"]), "version": element["version"], "summary": element["summary"]}
|
||||
|
||||
|
||||
@router.patch("/api/v1/elements/{element_id}/title")
|
||||
def patch_element_title(
|
||||
element_id: UUID,
|
||||
body: TitlePatch,
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
element = update_title(
|
||||
conn,
|
||||
principal.account_id,
|
||||
element_id,
|
||||
body.expected_version,
|
||||
body.title,
|
||||
_ctx_model(body.context),
|
||||
)
|
||||
return {"id": str(element["id"]), "version": element["version"], "title": element["title"]}
|
||||
|
||||
|
||||
@router.patch("/api/v1/bindings/{binding_id}/chapter")
|
||||
def patch_binding_chapter(
|
||||
binding_id: UUID,
|
||||
@@ -1756,6 +1803,8 @@ def _visible_events(conn, actor: UUID, rows: list[dict], page: Ctx) -> list[dict
|
||||
names: dict = {}
|
||||
items = []
|
||||
for event in rows:
|
||||
if event["result"] != "ok":
|
||||
continue
|
||||
title = _event_title(conn, actor, event, page)
|
||||
if title is None:
|
||||
continue
|
||||
|
||||
@@ -167,6 +167,7 @@ class GrantIn(APIModel):
|
||||
can_read: bool = True
|
||||
can_edit: bool = False
|
||||
can_share: bool = False
|
||||
use_owner_sources: bool = False
|
||||
|
||||
|
||||
class ExceptionIn(APIModel):
|
||||
@@ -197,6 +198,7 @@ class ContentOrderIn(APIModel):
|
||||
expected_version: int = Field(ge=1)
|
||||
mode: Literal["date", "position"]
|
||||
direction: Literal["asc", "desc"] = "asc"
|
||||
view: Literal["structure", "chronology"] | None = None
|
||||
context: ContextIn | None = None
|
||||
|
||||
|
||||
@@ -220,6 +222,12 @@ class SummaryPatch(APIModel):
|
||||
context: ContextIn | None = None
|
||||
|
||||
|
||||
class TitlePatch(APIModel):
|
||||
expected_version: int = Field(ge=1)
|
||||
title: str = Field(min_length=1, max_length=200)
|
||||
context: ContextIn | None = None
|
||||
|
||||
|
||||
class ChapterMoveIn(APIModel):
|
||||
expected_version: int = Field(ge=1)
|
||||
chapter_id: UUID | None = None
|
||||
@@ -360,3 +368,76 @@ class ExportIn(APIModel):
|
||||
context: ContextIn | None = None
|
||||
selected: list[str] = Field(default_factory=list, max_length=2000)
|
||||
assignments: dict[str, UUID] = Field(default_factory=dict)
|
||||
|
||||
|
||||
class EvidenceIn(APIModel):
|
||||
element_id: UUID
|
||||
role: Literal["email", "submission", "delivery", "other"]
|
||||
fold: Literal["keep", "evidence"] = "keep"
|
||||
|
||||
|
||||
class AttachmentAssignIn(APIModel):
|
||||
expected_version: int = Field(ge=1)
|
||||
context: ContextIn
|
||||
placement: ContextIn | None = None
|
||||
attachment_element_ids: list[UUID] = Field(min_length=1, max_length=100)
|
||||
fold: Literal["keep", "attachment"] = "keep"
|
||||
|
||||
|
||||
class AttachmentOrderIn(APIModel):
|
||||
expected_version: int = Field(ge=1)
|
||||
context: ContextIn
|
||||
placement: ContextIn | None = None
|
||||
attachment_element_ids: list[UUID] = Field(min_length=1, max_length=100)
|
||||
|
||||
|
||||
class AttachmentDetachIn(APIModel):
|
||||
expected_version: int = Field(ge=1)
|
||||
context: ContextIn
|
||||
placement: ContextIn | None = None
|
||||
|
||||
|
||||
class FoldIn(APIModel):
|
||||
expected_version: int = Field(ge=1)
|
||||
context: ContextIn
|
||||
placement: ContextIn | None = None
|
||||
fold: Literal["attachment", "evidence"] | None = None
|
||||
|
||||
|
||||
class DispatchIn(APIModel):
|
||||
expected_version: int = Field(ge=1)
|
||||
context: ContextIn
|
||||
placement: ContextIn | None = None
|
||||
channel: Literal["email", "post", "other"]
|
||||
sent_on: date | None = None
|
||||
counterpart: str | None = Field(default=None, max_length=200)
|
||||
attachment_element_ids: list[UUID] = Field(default_factory=list, max_length=100)
|
||||
evidence: list[EvidenceIn] = Field(default_factory=list, max_length=20)
|
||||
historical_gap: bool = False
|
||||
capture_editions: bool = True
|
||||
|
||||
|
||||
class DispatchEvidenceIn(APIModel):
|
||||
expected_version: int = Field(ge=1)
|
||||
context: ContextIn
|
||||
placement: ContextIn | None = None
|
||||
element_id: UUID
|
||||
role: Literal["email", "submission", "delivery", "other"]
|
||||
fold: Literal["keep", "evidence"] = "keep"
|
||||
|
||||
|
||||
class DispatchEvidenceDetachIn(APIModel):
|
||||
expected_version: int = Field(ge=1)
|
||||
context: ContextIn
|
||||
placement: ContextIn | None = None
|
||||
|
||||
|
||||
class DispatchCorrectIn(APIModel):
|
||||
expected_version: int = Field(ge=1)
|
||||
context: ContextIn
|
||||
placement: ContextIn | None = None
|
||||
channel: Literal["email", "post", "other"] | None = None
|
||||
sent_on: date | None = None
|
||||
clear_sent_on: bool = False
|
||||
counterpart: str | None = Field(default=None, max_length=200)
|
||||
clear_counterpart: bool = False
|
||||
+48
-67
@@ -5,10 +5,10 @@ from __future__ import annotations
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
from fastapi.responses import Response
|
||||
from fastapi.responses import JSONResponse, Response
|
||||
from psycopg import Connection
|
||||
|
||||
from app.access.policy import Ctx, element_rights, get_element, parse_query_context
|
||||
from app.access.policy import element_rights, get_element, parse_query_context
|
||||
from app.api.deps import Principal, get_conn, get_principal
|
||||
from app.api.routes import _created, _ctx_model
|
||||
from app.api.schemas import ConnectorIn, ExternalIn
|
||||
@@ -23,13 +23,19 @@ from app.sources import (
|
||||
imap_messages,
|
||||
imap_preview,
|
||||
list_connectors,
|
||||
load_imap_original,
|
||||
paperless_content,
|
||||
paperless_documents,
|
||||
probe,
|
||||
read_linked_mail,
|
||||
read_linked_paperless,
|
||||
save_connector,
|
||||
)
|
||||
|
||||
_PRIVATE = {
|
||||
"Cache-Control": "private, no-store",
|
||||
"Referrer-Policy": "no-referrer",
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
}
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@@ -63,27 +69,17 @@ def view_paperless(
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
element = get_element(conn, element_id)
|
||||
if element is None or element["kind"] != "external_ref":
|
||||
raise not_found()
|
||||
rights = element_rights(conn, principal.account_id, element, parse_query_context(context_kind, context_id))
|
||||
if not rights.read:
|
||||
raise not_found()
|
||||
ref = conn.execute(
|
||||
"SELECT source, external_id FROM external_references WHERE element_id = %s",
|
||||
(element_id,),
|
||||
).fetchone()
|
||||
element, context, ref = _opened_ref(conn, principal, element_id, context_kind, context_id)
|
||||
if ref is None or ref["source"] != "paperless":
|
||||
raise unprocessable("Nur ein Paperless-Dokument lässt sich hier als Datei ansehen.")
|
||||
data, media_type, filename = paperless_content(conn, principal.account_id, ref["external_id"])
|
||||
safe_name = (filename or f"paperless-{ref['external_id']}.pdf").replace('"', "")
|
||||
data, media_type, filename = read_linked_paperless(conn, principal.account_id, element, context, ref)
|
||||
safe_name = (filename or "dokument.pdf").replace('"', "")
|
||||
return Response(
|
||||
content=data,
|
||||
media_type=media_type,
|
||||
headers={
|
||||
**_PRIVATE,
|
||||
"Content-Disposition": f'inline; filename="{safe_name}"',
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
"Cache-Control": "private, no-store",
|
||||
},
|
||||
)
|
||||
|
||||
@@ -96,52 +92,48 @@ def view_mail(
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
ref = _mail_ref(conn, principal, element_id, context_kind, context_id)
|
||||
parsed, _raw = _complete_mail(conn, principal, ref)
|
||||
return {
|
||||
"title": parsed.subject,
|
||||
"message_from": parsed.sender,
|
||||
"message_to": parsed.recipient,
|
||||
"message_cc": parsed.copy,
|
||||
"text": parsed.text,
|
||||
"text_truncated": False,
|
||||
"complete": True,
|
||||
"attachments": [
|
||||
{
|
||||
"index": index,
|
||||
"filename": item.filename,
|
||||
"content_type": item.media_type,
|
||||
"byte_size": len(item.data),
|
||||
}
|
||||
for index, item in enumerate(parsed.attachments)
|
||||
],
|
||||
}
|
||||
element, context, ref = _opened_ref(conn, principal, element_id, context_kind, context_id)
|
||||
parsed, _raw = _complete_mail(conn, principal, element, context, ref)
|
||||
return JSONResponse(
|
||||
content={
|
||||
"title": parsed.subject,
|
||||
"message_from": parsed.sender,
|
||||
"message_to": parsed.recipient,
|
||||
"message_cc": parsed.copy,
|
||||
"text": parsed.text,
|
||||
"text_truncated": False,
|
||||
"complete": True,
|
||||
"attachments": [
|
||||
{
|
||||
"index": index,
|
||||
"filename": item.filename,
|
||||
"content_type": item.media_type,
|
||||
"byte_size": len(item.data),
|
||||
}
|
||||
for index, item in enumerate(parsed.attachments)
|
||||
],
|
||||
},
|
||||
headers={"Cache-Control": "private, no-store", "Referrer-Policy": "no-referrer"},
|
||||
)
|
||||
|
||||
|
||||
def _mail_ref(conn, principal: Principal, element_id: UUID, context_kind: str | None, context_id: str | None):
|
||||
def _opened_ref(conn, principal: Principal, element_id: UUID, context_kind: str | None, context_id: str | None):
|
||||
element = get_element(conn, element_id)
|
||||
if element is None or element["kind"] != "external_ref":
|
||||
raise not_found()
|
||||
rights = element_rights(conn, principal.account_id, element, parse_query_context(context_kind, context_id))
|
||||
context = parse_query_context(context_kind, context_id)
|
||||
rights = element_rights(conn, principal.account_id, element, context)
|
||||
if not rights.read:
|
||||
raise not_found()
|
||||
ref = conn.execute(
|
||||
"SELECT source, external_id, detail FROM external_references WHERE element_id = %s",
|
||||
(element_id,),
|
||||
).fetchone()
|
||||
return ref
|
||||
return element, context, ref
|
||||
|
||||
|
||||
def _complete_mail(conn, principal: Principal, ref):
|
||||
detail = (ref or {}).get("detail") or {}
|
||||
if ref is None or ref["source"] != "imap":
|
||||
raise unprocessable("Das ist keine E-Mail.")
|
||||
connector_id = detail.get("connector_id")
|
||||
mailbox = str(detail.get("mailbox") or "").strip()
|
||||
uid = _mail_uid(detail.get("uid"))
|
||||
if not connector_id or not mailbox or uid is None:
|
||||
raise unprocessable("Für diese E-Mail fehlt die Zuordnung zu Fach und Nachricht.")
|
||||
raw = load_imap_original(conn, principal.account_id, UUID(str(connector_id)), mailbox, uid, str(ref["external_id"]))
|
||||
def _complete_mail(conn, principal: Principal, element, context, ref):
|
||||
raw = read_linked_mail(conn, principal.account_id, element, context, ref)
|
||||
parsed = parse_mail(raw)
|
||||
if parsed.missing:
|
||||
names = ", ".join(parsed.missing[:5])
|
||||
@@ -149,16 +141,6 @@ def _complete_mail(conn, principal: Principal, ref):
|
||||
return parsed, raw
|
||||
|
||||
|
||||
def _mail_uid(value) -> int | None:
|
||||
if isinstance(value, bool):
|
||||
return None
|
||||
if isinstance(value, int) and value >= 1:
|
||||
return value
|
||||
if isinstance(value, str) and value.isdigit() and int(value) >= 1:
|
||||
return int(value)
|
||||
return None
|
||||
|
||||
|
||||
@router.get("/api/v1/external-refs/{element_id}/mail/original")
|
||||
def download_mail(
|
||||
element_id: UUID,
|
||||
@@ -167,8 +149,8 @@ def download_mail(
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
ref = _mail_ref(conn, principal, element_id, context_kind, context_id)
|
||||
_parsed, raw = _complete_mail(conn, principal, ref)
|
||||
element, context, ref = _opened_ref(conn, principal, element_id, context_kind, context_id)
|
||||
_parsed, raw = _complete_mail(conn, principal, element, context, ref)
|
||||
return _mail_bytes(raw, "message/rfc822", "nachricht.eml")
|
||||
|
||||
|
||||
@@ -181,8 +163,8 @@ def download_mail_attachment(
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
ref = _mail_ref(conn, principal, element_id, context_kind, context_id)
|
||||
parsed, _raw = _complete_mail(conn, principal, ref)
|
||||
element, context, ref = _opened_ref(conn, principal, element_id, context_kind, context_id)
|
||||
parsed, _raw = _complete_mail(conn, principal, element, context, ref)
|
||||
if index < 0 or index >= len(parsed.attachments):
|
||||
raise not_found()
|
||||
item = parsed.attachments[index]
|
||||
@@ -197,9 +179,8 @@ def _mail_bytes(data: bytes, media_type: str, filename: str, inline: bool = Fals
|
||||
content=data,
|
||||
media_type=media_type,
|
||||
headers={
|
||||
**_PRIVATE,
|
||||
"Content-Disposition": disposition,
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
"Cache-Control": "private, no-store",
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
+649
-86
@@ -21,6 +21,8 @@ from app.access.policy import (
|
||||
)
|
||||
from app.core.errors import not_found, unprocessable
|
||||
from app.core.timeutil import dump_dt, utcnow
|
||||
from app.correspondence import GapNote, export_children, load_snapshot_file
|
||||
from app.mailpack import parse_mail
|
||||
from app.present import _chapters, _ordered_bindings
|
||||
from app.retrieval import (
|
||||
FilePayload,
|
||||
@@ -30,7 +32,7 @@ from app.retrieval import (
|
||||
load_file,
|
||||
)
|
||||
|
||||
_NODE_KINDS = {"binding", "annotation"}
|
||||
_NODE_KINDS = {"binding", "annotation", "attachment", "dispatch_item", "evidence"}
|
||||
_DIRECTION = {"in": "Eingang", "out": "Ausgang"}
|
||||
_KIND_LABEL = {
|
||||
"note": "Notiz",
|
||||
@@ -62,6 +64,10 @@ class ExportNode:
|
||||
annotation_author: str | None = None
|
||||
annotation_at: str | None = None
|
||||
label: str = ""
|
||||
relation: str | None = None
|
||||
edition: str | None = None
|
||||
gap_reason: str | None = None
|
||||
snapshot_id: str | None = None
|
||||
|
||||
def public(self) -> dict:
|
||||
return {
|
||||
@@ -118,6 +124,7 @@ class Entry:
|
||||
notice: str | None
|
||||
replies: list[tuple[str, str]]
|
||||
recorded_at: str | None
|
||||
notes: tuple[str, ...] = ()
|
||||
|
||||
def public(self) -> dict:
|
||||
return {
|
||||
@@ -129,6 +136,15 @@ class Entry:
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class OverviewNode:
|
||||
kind: str
|
||||
title: str
|
||||
label: str | None = None
|
||||
entry: Entry | None = None
|
||||
children: list[OverviewNode] = field(default_factory=list)
|
||||
|
||||
|
||||
@dataclass
|
||||
class ExportPlan:
|
||||
matter_title: str
|
||||
@@ -202,6 +218,16 @@ def _plan(conn, actor, matter_id, context, selected, assignments, media_root) ->
|
||||
if node.kind == "annotation":
|
||||
loaded[node.id] = node.annotation_body or ""
|
||||
continue
|
||||
if node.gap_reason and node.kind in {"dispatch_item", "evidence"}:
|
||||
loaded[node.id] = GapNote(node.gap_reason)
|
||||
continue
|
||||
if node.snapshot_id and node.kind in {"dispatch_item", "evidence"}:
|
||||
result = load_snapshot_file(conn, UUID(node.snapshot_id), media_root)
|
||||
if isinstance(result, RetrievalFailure):
|
||||
issues.append(Issue(node.id, node.title, result.code, result.message, [dict(item) for item in result.choices]))
|
||||
continue
|
||||
loaded[node.id] = result
|
||||
continue
|
||||
if node.content_kind == "note":
|
||||
loaded[node.id] = _note_text(conn, UUID(node.element_id))
|
||||
continue
|
||||
@@ -217,7 +243,10 @@ def _plan(conn, actor, matter_id, context, selected, assignments, media_root) ->
|
||||
loaded[node.id] = result
|
||||
if isinstance(result, MailPayload):
|
||||
notices.extend(_retention_notices(node, result, hashes))
|
||||
notices.extend(_bundle_notices(root, chosen))
|
||||
notices.extend(_correspondence_export_notices(root, chosen))
|
||||
issues.extend(_reference_issues(conn, actor, page, leaves))
|
||||
issues.extend(_attachment_load_issues(root, chosen, loaded))
|
||||
generated = dump_dt(utcnow()) or ""
|
||||
if issues:
|
||||
entries = [
|
||||
@@ -226,9 +255,24 @@ def _plan(conn, actor, matter_id, context, selected, assignments, media_root) ->
|
||||
]
|
||||
return ExportPlan(matter["title"], generated, False, issues, notices, entries, [], root)
|
||||
files, entries = _layout(root, chosen, loaded, notices, generated)
|
||||
emit_issues = _attachment_emit_issues(root, chosen, loaded, entries)
|
||||
if emit_issues:
|
||||
return ExportPlan(
|
||||
matter["title"],
|
||||
generated,
|
||||
False,
|
||||
emit_issues,
|
||||
notices,
|
||||
[
|
||||
Entry(node.id, node.title, _label(node), None, [], node.dates or {}, node.direction, node.summary, None, [], _recorded(node))
|
||||
for node in leaves
|
||||
],
|
||||
[],
|
||||
root,
|
||||
)
|
||||
_attach_replies(conn, actor, page, entries, leaves)
|
||||
_stitch_replies(files, entries)
|
||||
files = _with_overview(matter["title"], generated, entries, files)
|
||||
files = _with_overview(matter["title"], generated, root, entries, files)
|
||||
return ExportPlan(matter["title"], generated, True, [], notices, entries, files, root)
|
||||
|
||||
|
||||
@@ -252,9 +296,11 @@ def _matter_node(conn, actor, matter, page: Ctx, root: bool) -> ExportNode:
|
||||
for binding in bindings:
|
||||
grouped.setdefault(binding.get("chapter_id"), []).append(binding)
|
||||
children: list[ExportNode] = []
|
||||
children.extend(_chapter_nodes(chapters, grouped))
|
||||
children.extend(_chapter_nodes(conn, actor, page, chapters, grouped))
|
||||
for binding in grouped.get(None, []):
|
||||
children.append(_binding_node(binding))
|
||||
if not _stands_in_chapter(binding):
|
||||
continue
|
||||
children.append(_binding_node(conn, actor, binding, page))
|
||||
rows = conn.execute(
|
||||
"SELECT * FROM matters WHERE parent_matter_id = %s AND deleted_at IS NULL ORDER BY title, id",
|
||||
(matter["id"],),
|
||||
@@ -275,16 +321,33 @@ def _matter_node(conn, actor, matter, page: Ctx, root: bool) -> ExportNode:
|
||||
)
|
||||
|
||||
|
||||
def _chapter_nodes(chapters: list[dict], grouped: dict[str | None, list]) -> list[ExportNode]:
|
||||
def _stands_in_chapter(binding: dict) -> bool:
|
||||
"""A folded attachment or receipt stays under its letter, not as another chapter row."""
|
||||
pack = binding.get("correspondence") or {}
|
||||
if pack.get("fold") in {"attachment", "evidence"}:
|
||||
return False
|
||||
if pack.get("hosts"):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _chapter_nodes(conn, actor, page, chapters: list[dict], grouped: dict[str | None, list]) -> list[ExportNode]:
|
||||
by_parent: dict[str | None, list[dict]] = {}
|
||||
for chapter in chapters:
|
||||
by_parent.setdefault(chapter.get("parent_chapter_id"), []).append(chapter)
|
||||
|
||||
def build(parent_id: str | None) -> list[ExportNode]:
|
||||
def build(parent_id: str | None, path: str) -> list[ExportNode]:
|
||||
nodes: list[ExportNode] = []
|
||||
for chapter in by_parent.get(parent_id, []):
|
||||
nested = build(chapter["id"])
|
||||
items = [_binding_node(item) for item in grouped.get(chapter["id"], [])]
|
||||
chapter_path = f"{path} / {chapter['title']}" if path else chapter["title"]
|
||||
nested = build(chapter["id"], chapter_path)
|
||||
items = []
|
||||
for item in grouped.get(chapter["id"], []):
|
||||
if not _stands_in_chapter(item):
|
||||
continue
|
||||
node = _binding_node(conn, actor, item, page)
|
||||
node.relation = f"Kapitel: {chapter_path}"
|
||||
items.append(node)
|
||||
if not items and not nested:
|
||||
continue
|
||||
nodes.append(
|
||||
@@ -301,10 +364,10 @@ def _chapter_nodes(chapters: list[dict], grouped: dict[str | None, list]) -> lis
|
||||
)
|
||||
return nodes
|
||||
|
||||
return build(None)
|
||||
return build(None, "")
|
||||
|
||||
|
||||
def _binding_node(binding: dict) -> ExportNode:
|
||||
def _binding_node(conn, actor, binding: dict, page) -> ExportNode:
|
||||
element = binding["element"]
|
||||
rights = binding["rights"]
|
||||
content_kind = _content_kind(element)
|
||||
@@ -340,9 +403,58 @@ def _binding_node(binding: dict) -> ExportNode:
|
||||
label="Anmerkung",
|
||||
)
|
||||
)
|
||||
for spec in export_children(conn, actor, binding, page):
|
||||
node.children.append(_spec_node(spec))
|
||||
return node
|
||||
|
||||
|
||||
def _spec_node(spec: dict) -> ExportNode:
|
||||
if spec["kind"] == "dispatch":
|
||||
return ExportNode(
|
||||
id=spec["id"],
|
||||
kind="dispatch",
|
||||
title=spec["title"],
|
||||
exportable=True,
|
||||
reason=None,
|
||||
content_kind=None,
|
||||
children=[_spec_node(child) for child in spec["children"]],
|
||||
label=spec.get("label") or "Versand",
|
||||
)
|
||||
element = spec.get("element")
|
||||
if spec["kind"] == "dispatch_item":
|
||||
content_kind = _item_content_kind(spec)
|
||||
else:
|
||||
content_kind = _content_kind(element) if element else "file"
|
||||
rights = spec.get("rights") or {}
|
||||
exportable = bool(rights.get("read") and rights.get("share"))
|
||||
return ExportNode(
|
||||
id=spec["id"],
|
||||
kind=spec["kind"],
|
||||
title=spec["title"],
|
||||
exportable=exportable,
|
||||
reason=None if exportable else "Für die Übergabe fehlt die Freigabebefugnis.",
|
||||
content_kind=content_kind,
|
||||
element_id=(element or {}).get("id") or spec.get("element_id"),
|
||||
dates=spec.get("dates"),
|
||||
label={"attachment": "Anlage", "dispatch_item": "Versandfassung", "evidence": "Nachweis"}.get(spec["kind"], "Inhalt"),
|
||||
relation=spec.get("relation"),
|
||||
edition=spec.get("edition"),
|
||||
gap_reason=spec.get("gap_reason"),
|
||||
snapshot_id=spec.get("snapshot_id"),
|
||||
)
|
||||
|
||||
|
||||
def _item_content_kind(spec: dict) -> str:
|
||||
if spec.get("gap_reason"):
|
||||
return "gap"
|
||||
media = spec.get("content_type") or ""
|
||||
if media == "message/rfc822":
|
||||
return "email"
|
||||
if media == "application/json":
|
||||
return "note"
|
||||
return "file"
|
||||
|
||||
|
||||
def _content_kind(element: dict) -> str:
|
||||
if element["kind"] == "note":
|
||||
return "note"
|
||||
@@ -464,62 +576,258 @@ def _layout(root, chosen, loaded, notices, generated: str):
|
||||
return
|
||||
|
||||
def emit(node: ExportNode, prefix: list[str]) -> None:
|
||||
folders = [child for child in node.children if _is_folder(child) and _included(child, chosen)]
|
||||
numbers = {child.id: index + 1 for index, child in enumerate(folders)}
|
||||
numbered = _ordered_numbered_children(node, chosen)
|
||||
numbers = {child.id: index + 1 for index, child in enumerate(numbered)}
|
||||
for child in node.children:
|
||||
if child.id in numbers:
|
||||
folder = prefix + [_folder_name(child.title, numbers[child.id], prefix)]
|
||||
if child.kind == "binding" and child.content_kind == "email":
|
||||
_emit_email(child, folder, add, rewrite, entries, loaded, notice_for, generated)
|
||||
if child.kind == "binding":
|
||||
if child.content_kind == "email":
|
||||
_emit_email(child, folder, add, rewrite, entries, loaded, notice_for, generated, chosen)
|
||||
else:
|
||||
_emit_loose(child, folder, add, entries, loaded, notice_for, generated, chosen)
|
||||
else:
|
||||
emit(child, folder)
|
||||
else:
|
||||
_emit_loose(child, prefix, add, entries, loaded, notice_for, generated)
|
||||
_emit_loose(child, prefix, add, entries, loaded, notice_for, generated, chosen)
|
||||
|
||||
emit(root, [])
|
||||
return files, entries
|
||||
|
||||
|
||||
def _emit_email(node, folder, add, rewrite, entries, loaded, notice_for, generated: str) -> None:
|
||||
mail = loaded[node.id]
|
||||
assert isinstance(mail, MailPayload)
|
||||
eml = add(folder + ["nachricht.eml"], mail.raw)
|
||||
attachments = []
|
||||
for attachment in mail.parsed.attachments:
|
||||
path = add(folder + ["anlagen", attachment.filename], attachment.data)
|
||||
attachments.append((attachment.filename, path))
|
||||
notice = "\n".join(notice_for.get(node.id, []))
|
||||
text_path = add(folder + ["lesefassung.md"], b"")
|
||||
readable = _mail_markdown(node, mail, text_path, eml, attachments, notice, generated)
|
||||
rewrite(text_path, readable.encode("utf-8"))
|
||||
links = [("EML-Original", eml), ("Lesefassung", text_path), *attachments]
|
||||
entries.append(_entry(node, eml, links, notice or None))
|
||||
for child in node.children:
|
||||
if child.kind == "annotation" and child.id in loaded:
|
||||
path = add(folder + [_annotation_filename(child, folder)], _annotation_markdown(child).encode("utf-8"))
|
||||
entries.append(_entry(child, path, [], None))
|
||||
def _emit_email(node, folder, add, rewrite, entries, loaded, notice_for, generated: str, chosen: set[str]) -> None:
|
||||
mail = loaded.get(node.id)
|
||||
if isinstance(mail, MailPayload):
|
||||
eml = add(folder + ["nachricht.eml"], mail.raw)
|
||||
attachments = []
|
||||
for attachment in mail.parsed.attachments:
|
||||
path = add(folder + ["anlagen", attachment.filename], attachment.data)
|
||||
attachments.append((attachment.filename, path))
|
||||
notice = "\n".join(notice_for.get(node.id, []))
|
||||
text_path = add(folder + ["lesefassung.md"], b"")
|
||||
readable = _mail_markdown(node, mail, text_path, eml, attachments, notice, generated)
|
||||
rewrite(text_path, readable.encode("utf-8"))
|
||||
links = [("EML-Original", eml), ("Lesefassung", text_path), *attachments]
|
||||
entries.append(_entry(node, eml, links, notice or None))
|
||||
for child in node.children:
|
||||
if child.kind == "annotation" and child.id in loaded:
|
||||
path = add(folder + [_annotation_filename(child, folder)], _annotation_markdown(child).encode("utf-8"))
|
||||
entries.append(_entry(child, path, [], None))
|
||||
_emit_related(node, folder, add, entries, loaded, notice_for, chosen, generated)
|
||||
|
||||
|
||||
def _emit_loose(node, prefix, add, entries, loaded, notice_for, generated: str) -> None:
|
||||
def _emit_loose(node, prefix, add, entries, loaded, notice_for, generated: str, chosen: set[str]) -> None:
|
||||
bundle = _binding_bundle(prefix, node) if node.kind == "binding" else prefix
|
||||
if node.kind == "binding" and node.id in loaded and node.content_kind != "email":
|
||||
payload = loaded[node.id]
|
||||
if node.content_kind == "note":
|
||||
path = add(prefix + [f"{_segment(node.title)}.md"], _note_markdown(node, str(payload), generated).encode("utf-8"))
|
||||
path = add(bundle + [f"{_segment(node.title)}.md"], _note_markdown(node, str(payload), generated).encode("utf-8"))
|
||||
entries.append(_entry(node, path, [], None))
|
||||
elif isinstance(payload, FilePayload):
|
||||
path = add(prefix + [payload.filename], payload.data)
|
||||
entries.append(_entry(node, path, [(payload.filename, path)], None))
|
||||
name = _handover_filename(node, payload.filename)
|
||||
path = add(bundle + [name], payload.data)
|
||||
entries.append(_entry(node, path, [(name, path)], None))
|
||||
if node.kind == "binding":
|
||||
for child in node.children:
|
||||
if child.kind == "annotation" and child.id in loaded and not (node.content_kind == "email" and node.id in loaded):
|
||||
path = add(prefix + [_annotation_filename(child, prefix)], _annotation_markdown(child).encode("utf-8"))
|
||||
path = add(bundle + [_annotation_filename(child, bundle)], _annotation_markdown(child).encode("utf-8"))
|
||||
entries.append(_entry(child, path, [], None))
|
||||
elif node.kind == "annotation" and node.id in loaded:
|
||||
path = add(prefix + [_annotation_filename(node, prefix)], _annotation_markdown(node).encode("utf-8"))
|
||||
entries.append(_entry(node, path, [], None))
|
||||
if node.kind == "binding":
|
||||
_emit_related(node, prefix, add, entries, loaded, notice_for, chosen, generated)
|
||||
|
||||
|
||||
def _binding_bundle(prefix: list[str], _host: ExportNode) -> list[str]:
|
||||
"""Main file and correspondence sit inside the numbered entry folder."""
|
||||
return list(prefix)
|
||||
|
||||
|
||||
def _handover_filename(node: ExportNode, original: str) -> str:
|
||||
"""Readable name for recipients; file bytes stay unchanged."""
|
||||
stem = _segment(node.title)
|
||||
suffix = PurePosixPath(original or "").suffix
|
||||
if suffix:
|
||||
return f"{stem}{suffix}"
|
||||
return stem or _file_segment(original)
|
||||
|
||||
|
||||
def _related_bucket(node: ExportNode) -> str:
|
||||
if node.kind == "attachment":
|
||||
return "Anlagen"
|
||||
if node.kind == "evidence":
|
||||
return "Belege"
|
||||
if node.kind == "dispatch_item":
|
||||
relation = node.relation or ""
|
||||
if "Anlage → Versand" in relation:
|
||||
return "Anlagen"
|
||||
return "Belege"
|
||||
return "Belege"
|
||||
|
||||
|
||||
def _emit_related(node, prefix, add, entries, loaded, notice_for, chosen, generated: str) -> None:
|
||||
bundle = _binding_bundle(prefix, node)
|
||||
for child in node.children:
|
||||
if child.kind == "attachment" and child.id in chosen and child.id in loaded:
|
||||
_emit_one(child, bundle + ["Anlagen"], add, entries, loaded, notice_for, generated)
|
||||
if child.kind != "dispatch":
|
||||
continue
|
||||
picked = [item for item in child.children if item.id in chosen and item.id in loaded]
|
||||
for item in picked:
|
||||
_emit_one(item, bundle + [_related_bucket(item)], add, entries, loaded, notice_for, generated)
|
||||
|
||||
|
||||
def _emit_one(node, prefix, add, entries, loaded, notice_for, generated: str) -> None:
|
||||
payload = loaded[node.id]
|
||||
notice = "\n".join(notice_for.get(node.id, []))
|
||||
if isinstance(payload, GapNote):
|
||||
path = add(prefix + [f"{_segment(node.title)}-luecke.txt"], payload.reason.encode("utf-8"))
|
||||
entries.append(_entry(node, path, [( "Lücke", path)], notice or payload.reason))
|
||||
return
|
||||
if isinstance(payload, MailPayload) or (isinstance(payload, FilePayload) and payload.media_type == "message/rfc822"):
|
||||
raw = payload.raw if isinstance(payload, MailPayload) else payload.data
|
||||
eml = add(prefix + ["nachricht.eml"], raw)
|
||||
links = [("EML-Original", eml)]
|
||||
try:
|
||||
parsed = payload.parsed if isinstance(payload, MailPayload) else parse_mail(raw)
|
||||
for attachment in parsed.attachments:
|
||||
path = add(prefix + ["anlagen", attachment.filename], attachment.data)
|
||||
links.append((attachment.filename, path))
|
||||
except Exception:
|
||||
links.append(("Hinweis", eml))
|
||||
entries.append(_entry(node, eml, links, notice or None))
|
||||
return
|
||||
if isinstance(payload, str):
|
||||
path = add(prefix + [f"{_segment(node.title)}.md"], _note_markdown(node, payload, generated).encode("utf-8"))
|
||||
entries.append(_entry(node, path, [], notice or None))
|
||||
return
|
||||
if isinstance(payload, FilePayload) and payload.media_type == "application/json":
|
||||
path = add(prefix + [f"{_segment(node.title)}.stand.json"], payload.data)
|
||||
text = _json_note(payload.data)
|
||||
reading = add(prefix + [f"{_segment(node.title)}.md"], _note_markdown(node, text, generated).encode("utf-8"))
|
||||
entries.append(_entry(node, reading, [("Gesicherter Text", path), ("Lesefassung", reading)], notice or None))
|
||||
return
|
||||
if isinstance(payload, FilePayload):
|
||||
name = _handover_filename(node, payload.filename)
|
||||
path = add(prefix + [name], payload.data)
|
||||
entries.append(_entry(node, path, [(name, path)], notice or None))
|
||||
|
||||
|
||||
def _correspondence_export_notices(root: ExportNode, chosen: set[str]) -> list[Notice]:
|
||||
notices: list[Notice] = []
|
||||
for node in _walk(root):
|
||||
if node.kind != "binding":
|
||||
continue
|
||||
attachments = [child for child in node.children if child.kind == "attachment"]
|
||||
if not attachments:
|
||||
continue
|
||||
blocked = [child for child in attachments if not child.exportable]
|
||||
if blocked:
|
||||
sample = blocked[0]
|
||||
count = len(blocked)
|
||||
word = "Anlage ist" if count == 1 else f"{count} Anlagen sind"
|
||||
notices.append(
|
||||
Notice(
|
||||
sample.id,
|
||||
f"{word} dem Schreiben zugeordnet, aber für die Übergabe nicht freigegeben. "
|
||||
"Sie erscheinen in der Auswahl nicht und fehlen im Paket.",
|
||||
)
|
||||
)
|
||||
if node.id not in chosen:
|
||||
continue
|
||||
missing = [child for child in attachments if child.exportable and child.id not in chosen]
|
||||
if missing:
|
||||
sample = missing[0]
|
||||
count = len(missing)
|
||||
word = "Anlage ist" if count == 1 else f"{count} Anlagen sind"
|
||||
notices.append(
|
||||
Notice(
|
||||
sample.id,
|
||||
f"{word} dem Schreiben zugeordnet, aber nicht ausgewählt. Die Ausgabe ist unvollständig.",
|
||||
)
|
||||
)
|
||||
return notices
|
||||
|
||||
|
||||
def _attachment_load_issues(root: ExportNode, chosen: set[str], loaded: dict) -> list[Issue]:
|
||||
issues: list[Issue] = []
|
||||
for node in _walk(root):
|
||||
if node.kind != "attachment" or node.id not in chosen or not node.exportable:
|
||||
continue
|
||||
if node.id not in loaded:
|
||||
issues.append(
|
||||
Issue(
|
||||
node.id,
|
||||
node.title,
|
||||
"missing",
|
||||
"Die zugeordnete Anlage konnte nicht für die Ausgabe geladen werden.",
|
||||
)
|
||||
)
|
||||
return issues
|
||||
|
||||
|
||||
def _attachment_emit_issues(root: ExportNode, chosen: set[str], loaded: dict, entries: list[Entry]) -> list[Issue]:
|
||||
emitted = {entry.node_id for entry in entries}
|
||||
issues: list[Issue] = []
|
||||
for node in _walk(root):
|
||||
if node.kind != "attachment" or node.id not in chosen or not node.exportable:
|
||||
continue
|
||||
if node.id not in loaded:
|
||||
continue
|
||||
if node.id in emitted:
|
||||
continue
|
||||
issues.append(
|
||||
Issue(
|
||||
node.id,
|
||||
node.title,
|
||||
"missing",
|
||||
"Die ausgewählte Anlage fehlt in der erzeugten Paketstruktur.",
|
||||
)
|
||||
)
|
||||
return issues
|
||||
|
||||
|
||||
def _json_note(data: bytes) -> str:
|
||||
import json
|
||||
|
||||
try:
|
||||
document = json.loads(data.decode("utf-8"))
|
||||
except (UnicodeDecodeError, json.JSONDecodeError):
|
||||
return ""
|
||||
parts = []
|
||||
for block in document.get("blocks") or []:
|
||||
if isinstance(block, dict):
|
||||
text = str(block.get("text") or "").strip()
|
||||
if text:
|
||||
parts.append(text)
|
||||
return "\n\n".join(parts)
|
||||
|
||||
|
||||
def _bundle_notices(root: ExportNode, chosen: set[str]) -> list[Notice]:
|
||||
found = []
|
||||
for node in _walk(root):
|
||||
if node.kind != "dispatch":
|
||||
continue
|
||||
parts = [child for child in node.children if child.kind in {"dispatch_item", "evidence"}]
|
||||
picked = [child for child in parts if child.id in chosen]
|
||||
if not picked:
|
||||
continue
|
||||
if len(picked) < len(parts):
|
||||
found.append(
|
||||
Notice(
|
||||
picked[0].id,
|
||||
"Auszug dieses Versands. Die Ausgabe ist nicht der vollständige Versandstand.",
|
||||
)
|
||||
)
|
||||
gaps = [child.gap_reason for child in picked if child.gap_reason]
|
||||
if gaps:
|
||||
found.append(Notice(picked[0].id, "Fehlende Fassung: " + " ".join(gaps)))
|
||||
return found
|
||||
|
||||
|
||||
def _entry(node: ExportNode, path: str | None, links, notice: str | None) -> Entry:
|
||||
notes = tuple(part for part in (node.relation, node.edition, node.gap_reason) if part)
|
||||
return Entry(
|
||||
node.id,
|
||||
node.title,
|
||||
@@ -532,6 +840,7 @@ def _entry(node: ExportNode, path: str | None, links, notice: str | None) -> Ent
|
||||
notice,
|
||||
[],
|
||||
_recorded(node),
|
||||
notes,
|
||||
)
|
||||
|
||||
|
||||
@@ -566,67 +875,313 @@ def _attach_replies(conn, actor, page, entries: list[Entry], leaves: list[Export
|
||||
entry.replies.append((target["title"], path))
|
||||
|
||||
|
||||
def _with_overview(title: str, generated: str, entries: list[Entry], files: list[tuple[str, bytes]]):
|
||||
html_doc = _html_overview(title, generated, entries)
|
||||
markdown = _markdown_overview(title, generated, entries)
|
||||
def _with_overview(title: str, generated: str, root: ExportNode, entries: list[Entry], files: list[tuple[str, bytes]]):
|
||||
by_id = {entry.node_id: entry for entry in entries}
|
||||
sections = _overview_sections(root, by_id)
|
||||
html_doc = _html_overview(title, generated, sections)
|
||||
markdown = _markdown_overview(title, generated, sections)
|
||||
return [("index.html", html_doc.encode("utf-8")), ("inhalt.md", markdown.encode("utf-8")), *files]
|
||||
|
||||
|
||||
def _html_overview(title: str, generated: str, entries: list[Entry]) -> str:
|
||||
items = []
|
||||
for entry in entries:
|
||||
bits = [f"<h2>{html.escape(entry.title)}</h2>", f"<p>{html.escape(entry.kind_label)}</p>"]
|
||||
facts = _fact_lines(entry, generated)
|
||||
if facts:
|
||||
bits.append("<ul>" + "".join(f"<li>{html.escape(line)}</li>" for line in facts) + "</ul>")
|
||||
if entry.summary:
|
||||
bits.append(f"<p>Kurzfassung: {html.escape(entry.summary)}</p>")
|
||||
for label, path in _entry_links(entry):
|
||||
bits.append(f'<p><a href="{_href(path)}">{html.escape(label)}</a></p>')
|
||||
for reply_title, path in entry.replies:
|
||||
bits.append(
|
||||
f'<p>Antwort auf <a href="{_href(path)}">{html.escape(reply_title)}</a></p>'
|
||||
)
|
||||
if entry.notice:
|
||||
bits.append(f"<p>{html.escape(entry.notice)}</p>")
|
||||
items.append(f"<article>{''.join(bits)}</article>")
|
||||
body = "".join(items) or "<p>Die bestätigte Auswahl enthält keinen ausgebbaren Inhalt.</p>"
|
||||
def _overview_sections(root: ExportNode, entries: dict[str, Entry]) -> list[OverviewNode]:
|
||||
found: list[OverviewNode] = []
|
||||
for child in root.children:
|
||||
section = _overview_node(child, entries)
|
||||
if section is not None:
|
||||
found.append(section)
|
||||
return found
|
||||
|
||||
|
||||
def _overview_node(node: ExportNode, entries: dict[str, Entry]) -> OverviewNode | None:
|
||||
if node.kind in {"matter", "chapter"}:
|
||||
children = []
|
||||
for child in node.children:
|
||||
section = _overview_node(child, entries)
|
||||
if section is not None:
|
||||
children.append(section)
|
||||
if not children:
|
||||
return None
|
||||
return OverviewNode("container", node.title, node.label or _KIND_LABEL.get(node.kind, ""), None, children)
|
||||
if node.kind == "binding":
|
||||
return _overview_binding(node, entries)
|
||||
return None
|
||||
|
||||
|
||||
def _overview_binding(node: ExportNode, entries: dict[str, Entry]) -> OverviewNode | None:
|
||||
groups: list[OverviewNode] = []
|
||||
annotations = [
|
||||
OverviewNode("leaf", child.title, _label(child), entries[child.id])
|
||||
for child in node.children
|
||||
if child.kind == "annotation" and child.id in entries
|
||||
]
|
||||
if annotations:
|
||||
groups.append(OverviewNode("group", "Anmerkungen", None, None, annotations))
|
||||
anlagen = [
|
||||
OverviewNode("leaf", child.title, _label(child), entries[child.id])
|
||||
for child in node.children
|
||||
if child.kind == "attachment" and child.id in entries
|
||||
]
|
||||
if anlagen:
|
||||
groups.append(OverviewNode("group", "Anlagen", None, None, anlagen))
|
||||
belege: list[OverviewNode] = []
|
||||
versand: list[OverviewNode] = []
|
||||
for dispatch in node.children:
|
||||
if dispatch.kind != "dispatch":
|
||||
continue
|
||||
items = [
|
||||
OverviewNode("leaf", item.title, _label(item), entries[item.id])
|
||||
for item in dispatch.children
|
||||
if item.kind in {"dispatch_item", "evidence"} and item.id in entries
|
||||
]
|
||||
if not items:
|
||||
continue
|
||||
bucket = "Belege" if (dispatch.label or "").startswith("Beleg") else (dispatch.label or "Versand")
|
||||
target = belege if bucket == "Belege" else versand
|
||||
target.append(OverviewNode("group", dispatch.title, bucket, None, items))
|
||||
if belege:
|
||||
groups.append(OverviewNode("group", "Belege", None, None, belege))
|
||||
if versand:
|
||||
groups.extend(versand)
|
||||
host = entries.get(node.id)
|
||||
if host is None and not groups:
|
||||
return None
|
||||
return OverviewNode("binding", node.title, node.label or _label(node), host, groups)
|
||||
|
||||
|
||||
def _overview_toc(sections: list[OverviewNode], counter: list[int]) -> tuple[list[tuple[str, str]], list[int]]:
|
||||
items: list[tuple[str, str]] = []
|
||||
|
||||
def walk(nodes: list[OverviewNode]) -> None:
|
||||
for node in nodes:
|
||||
if node.kind not in {"container", "binding"}:
|
||||
continue
|
||||
counter[0] += 1
|
||||
anchor = f"inhalt-{counter[0]}"
|
||||
label = node.title
|
||||
if node.label and node.kind == "container":
|
||||
label = f"{node.label}: {node.title}"
|
||||
items.append((anchor, label))
|
||||
if node.kind == "container":
|
||||
walk(node.children)
|
||||
|
||||
walk(sections)
|
||||
return items, counter
|
||||
|
||||
|
||||
def _html_overview(title: str, generated: str, sections: list[OverviewNode]) -> str:
|
||||
counter = [0]
|
||||
toc, _counter = _overview_toc(sections, counter)
|
||||
counter[0] = 0
|
||||
toc_html = ""
|
||||
if toc:
|
||||
toc_html = (
|
||||
'<nav class="overview-toc" aria-label="Inhalt">'
|
||||
"<h2>Inhalt</h2><ol>"
|
||||
+ "".join(f'<li><a href="#{anchor}">{html.escape(label)}</a></li>' for anchor, label in toc)
|
||||
+ "</ol></nav>"
|
||||
)
|
||||
body = _html_overview_nodes(sections, generated, counter) or "<p>Die bestätigte Auswahl enthält keinen ausgebbaren Inhalt.</p>"
|
||||
return (
|
||||
"<!DOCTYPE html><html lang=\"de\"><head><meta charset=\"utf-8\">"
|
||||
f"<title>Übergabe {html.escape(title)}</title>"
|
||||
"<style>body{font-family:Segoe UI,sans-serif;line-height:1.45;max-width:46rem;margin:2rem auto;padding:0 1rem;color:#1c1b18}"
|
||||
"a{color:#085041}article{border-top:1px solid #ddd;padding:1rem 0}</style></head><body>"
|
||||
f"<h1>Übergabe {html.escape(title)}</h1>"
|
||||
f"<p>Erzeugt am {html.escape(generated)}. Fachliche Daten stehen bei den einzelnen Inhalten und sind kein Erzeugungszeitpunkt.</p>"
|
||||
f"{body}</body></html>"
|
||||
"<style>"
|
||||
":root{color:#1c1b18;background:#faf9f6;--line:#d8d3c8;--accent:#085041;--panel:#f0ebe3}"
|
||||
"body{font-family:Segoe UI,system-ui,sans-serif;line-height:1.5;max-width:52rem;margin:0 auto;padding:2rem 1.25rem 3rem}"
|
||||
"a{color:var(--accent)}"
|
||||
".overview-toc{background:var(--panel);border:1px solid var(--line);border-radius:12px;padding:1rem 1.25rem;margin:1.5rem 0 2rem}"
|
||||
".overview-toc ol{margin:0;padding-left:1.25rem}"
|
||||
".overview-branch{border:1px solid var(--line);border-radius:12px;padding:0.75rem 1rem 1rem;margin:1rem 0;background:#fff}"
|
||||
".overview-branch > .branch-head{font-size:1.05rem;font-weight:600;margin:0 0 0.75rem}"
|
||||
".overview-branch .branch-kind{display:inline-block;font-size:0.75rem;font-weight:600;letter-spacing:0.04em;text-transform:uppercase;color:#5c574e;margin-right:0.5rem}"
|
||||
".overview-entry{border-top:1px solid var(--line);padding:1rem 0 0.5rem;margin-top:0.75rem}"
|
||||
".overview-entry:first-of-type{border-top:none;margin-top:0;padding-top:0}"
|
||||
".entry-head{display:flex;flex-wrap:wrap;gap:0.35rem 0.75rem;align-items:baseline;margin-bottom:0.35rem}"
|
||||
".entry-title{font-size:1.1rem;font-weight:600;margin:0}"
|
||||
".entry-kind{font-size:0.8rem;color:#5c574e}"
|
||||
".entry-links{display:flex;flex-wrap:wrap;gap:0.5rem;margin:0.5rem 0}"
|
||||
".entry-links a{display:inline-block;padding:0.25rem 0.65rem;border-radius:999px;background:var(--panel);text-decoration:none;font-size:0.9rem}"
|
||||
".entry-group{margin:0.75rem 0 0 0.5rem;padding-left:0.85rem;border-left:3px solid var(--line)}"
|
||||
".entry-group-title{font-size:0.95rem;font-weight:600;margin:0 0 0.35rem}"
|
||||
".entry-group ul{margin:0.25rem 0 0;padding-left:1.1rem}"
|
||||
".entry-leaf{margin:0.2rem 0}"
|
||||
".entry-meta{font-size:0.92rem;color:#3d3a34;margin:0.35rem 0}"
|
||||
".entry-notice{font-size:0.92rem;color:#6b4a12;background:#fff8ea;border-radius:8px;padding:0.5rem 0.65rem;margin-top:0.5rem}"
|
||||
"</style></head><body>"
|
||||
f"<header><h1>Übergabe {html.escape(title)}</h1>"
|
||||
f"<p class=\"entry-meta\">Erzeugt am {html.escape(generated)}. Fachliche Daten stehen bei den einzelnen Inhalten und sind kein Erzeugungszeitpunkt.</p></header>"
|
||||
f"{toc_html}{body}</body></html>"
|
||||
)
|
||||
|
||||
|
||||
def _markdown_overview(title: str, generated: str, entries: list[Entry]) -> str:
|
||||
def _html_overview_nodes(sections: list[OverviewNode], generated: str, counter: list[int]) -> str:
|
||||
parts = []
|
||||
for section in sections:
|
||||
parts.append(_html_overview_node(section, generated, counter, depth=2))
|
||||
return "".join(parts)
|
||||
|
||||
|
||||
def _html_overview_node(node: OverviewNode, generated: str, counter: list[int], depth: int) -> str:
|
||||
counter[0] += 1
|
||||
anchor = f"inhalt-{counter[0]}"
|
||||
if node.kind == "container":
|
||||
inner = "".join(_html_overview_node(child, generated, counter, depth + 1) for child in node.children)
|
||||
label = f'<span class="branch-kind">{html.escape(node.label)}</span>' if node.label else ""
|
||||
return (
|
||||
f'<section class="overview-branch" id="{anchor}">'
|
||||
f'<p class="branch-head">{label}{html.escape(node.title)}</p>{inner}</section>'
|
||||
)
|
||||
if node.kind == "binding":
|
||||
bits = [
|
||||
f'<section class="overview-entry" id="{anchor}">',
|
||||
'<div class="entry-head">',
|
||||
f'<h{min(depth, 6)} class="entry-title">{html.escape(node.title)}</h{min(depth, 6)}>',
|
||||
]
|
||||
if node.label:
|
||||
bits.append(f'<span class="entry-kind">{html.escape(node.label)}</span>')
|
||||
bits.append("</div>")
|
||||
if node.entry:
|
||||
bits.append(_html_entry_body(node.entry, generated))
|
||||
for child in node.children:
|
||||
bits.append(_html_overview_group(child, generated))
|
||||
bits.append("</section>")
|
||||
return "".join(bits)
|
||||
return ""
|
||||
|
||||
|
||||
def _html_overview_group(node: OverviewNode, generated: str) -> str:
|
||||
if node.kind == "leaf":
|
||||
return _html_leaf(node.entry, generated)
|
||||
if node.kind != "group":
|
||||
return ""
|
||||
subtitle = f" · {html.escape(node.label)}" if node.label and node.title != node.label else ""
|
||||
title = html.escape(node.title)
|
||||
if node.children and all(child.kind == "leaf" for child in node.children):
|
||||
inner = "".join(_html_leaf(child.entry, generated) for child in node.children)
|
||||
return f'<div class="entry-group"><p class="entry-group-title">{title}{subtitle}</p><ul>{inner}</ul></div>'
|
||||
inner = "".join(_html_overview_group(child, generated) for child in node.children)
|
||||
return f'<div class="entry-group"><p class="entry-group-title">{title}{subtitle}</p>{inner}</div>'
|
||||
|
||||
|
||||
def _html_leaf(entry: Entry | None, generated: str) -> str:
|
||||
if entry is None:
|
||||
return ""
|
||||
links = _entry_links(entry)
|
||||
link_bits = "".join(
|
||||
f'<a href="{_href(path)}">{html.escape(label)}</a>' for label, path in links
|
||||
)
|
||||
meta = f'<span class="entry-kind">{html.escape(entry.kind_label)}</span>' if entry.kind_label else ""
|
||||
detail = ""
|
||||
if entry.notes:
|
||||
detail = f'<span class="entry-meta"> · {" · ".join(html.escape(part) for part in entry.notes)}</span>'
|
||||
return f'<li class="entry-leaf"><strong>{html.escape(entry.title)}</strong> {meta}{detail} — {link_bits}</li>'
|
||||
|
||||
|
||||
def _html_entry_body(entry: Entry, generated: str) -> str:
|
||||
bits = []
|
||||
facts = _fact_lines(entry, generated)
|
||||
if facts:
|
||||
bits.append("<ul>" + "".join(f"<li>{html.escape(line)}</li>" for line in facts) + "</ul>")
|
||||
if entry.summary:
|
||||
bits.append(f'<p class="entry-meta">Kurzfassung: {html.escape(entry.summary)}</p>')
|
||||
links = _entry_links(entry)
|
||||
if links:
|
||||
bits.append(
|
||||
'<p class="entry-links">'
|
||||
+ "".join(f'<a href="{_href(path)}">{html.escape(label)}</a>' for label, path in links)
|
||||
+ "</p>"
|
||||
)
|
||||
for reply_title, path in entry.replies:
|
||||
bits.append(f'<p class="entry-meta">Antwort auf <a href="{_href(path)}">{html.escape(reply_title)}</a></p>')
|
||||
if entry.notice:
|
||||
bits.append(f'<p class="entry-notice">{html.escape(entry.notice)}</p>')
|
||||
return "".join(bits)
|
||||
|
||||
|
||||
def _markdown_overview(title: str, generated: str, sections: list[OverviewNode]) -> str:
|
||||
lines = [
|
||||
f"# Übergabe {title}",
|
||||
"",
|
||||
f"Erzeugt am {generated}. Fachliche Daten stehen bei den einzelnen Inhalten und sind kein Erzeugungszeitpunkt.",
|
||||
"",
|
||||
]
|
||||
for entry in entries:
|
||||
lines.append(f"## {entry.title}")
|
||||
if sections:
|
||||
lines.extend(["## Inhalt", ""])
|
||||
for anchor, label in _overview_toc(sections, [0])[0]:
|
||||
lines.append(f"- [{label}](#{anchor})")
|
||||
lines.append("")
|
||||
lines.append(entry.kind_label)
|
||||
lines.append("")
|
||||
for fact in _fact_lines(entry, generated):
|
||||
lines.append(f"- {fact}")
|
||||
if entry.summary:
|
||||
lines.append(f"- Kurzfassung: {entry.summary}")
|
||||
for label, path in _entry_links(entry):
|
||||
lines.append(f"- [{label}]({_href(path)})")
|
||||
for reply_title, path in entry.replies:
|
||||
lines.append(f"- Antwort auf [{reply_title}]({_href(path)})")
|
||||
if entry.notice:
|
||||
lines.append("")
|
||||
lines.append(entry.notice)
|
||||
lines.append("")
|
||||
return "\n".join(lines).rstrip() + "\n"
|
||||
lines.extend(_markdown_overview_nodes(sections, generated, depth=2))
|
||||
return "\n".join(line for line in lines if line is not None).rstrip() + "\n"
|
||||
|
||||
|
||||
def _markdown_overview_nodes(sections: list[OverviewNode], generated: str, depth: int) -> list[str]:
|
||||
lines: list[str] = []
|
||||
counter = [0]
|
||||
|
||||
def walk(nodes: list[OverviewNode], level: int) -> None:
|
||||
for node in nodes:
|
||||
if node.kind == "container":
|
||||
counter[0] += 1
|
||||
anchor = f"inhalt-{counter[0]}"
|
||||
heading = "#" * min(level, 6)
|
||||
label = f"{node.label}: " if node.label else ""
|
||||
lines.extend(["", f"{heading} {label}{node.title}", f"<a id=\"{anchor}\"></a>", ""])
|
||||
walk(node.children, level + 1)
|
||||
elif node.kind == "binding":
|
||||
counter[0] += 1
|
||||
anchor = f"inhalt-{counter[0]}"
|
||||
heading = "#" * min(level, 6)
|
||||
label = f" ({node.label})" if node.label else ""
|
||||
lines.extend(["", f"{heading} {node.title}{label}", f"<a id=\"{anchor}\"></a>", ""])
|
||||
if node.entry:
|
||||
lines.extend(_markdown_entry_body(node.entry, generated))
|
||||
for child in node.children:
|
||||
lines.extend(_markdown_group(child, generated, level + 1))
|
||||
lines.append("")
|
||||
|
||||
walk(sections, depth)
|
||||
return lines
|
||||
|
||||
|
||||
def _markdown_group(node: OverviewNode, generated: str, depth: int) -> list[str]:
|
||||
if node.kind == "leaf":
|
||||
return _markdown_leaf(node.entry, depth)
|
||||
if node.kind != "group":
|
||||
return []
|
||||
heading = "#" * min(depth, 6)
|
||||
title = node.title
|
||||
if node.label and node.label not in title:
|
||||
title = f"{title} ({node.label})"
|
||||
lines = ["", f"{heading} {title}", ""]
|
||||
for child in node.children:
|
||||
lines.extend(_markdown_group(child, generated, depth + 1))
|
||||
return lines
|
||||
|
||||
|
||||
def _markdown_leaf(entry: Entry | None, depth: int) -> list[str]:
|
||||
if entry is None:
|
||||
return []
|
||||
indent = " " * max(0, depth - 4)
|
||||
links = _entry_links(entry)
|
||||
notes = f" — {' · '.join(entry.notes)}" if entry.notes else ""
|
||||
if not links:
|
||||
return [f"{indent}- {entry.title} ({entry.kind_label}){notes}"]
|
||||
link = " · ".join(f"[{label}]({_href(path)})" for label, path in links)
|
||||
return [f"{indent}- **{entry.title}** ({entry.kind_label}){notes}: {link}"]
|
||||
|
||||
|
||||
def _markdown_entry_body(entry: Entry, generated: str) -> list[str]:
|
||||
lines = []
|
||||
for fact in _fact_lines(entry, generated):
|
||||
lines.append(f"- {fact}")
|
||||
if entry.summary:
|
||||
lines.append(f"- Kurzfassung: {entry.summary}")
|
||||
for label, path in _entry_links(entry):
|
||||
lines.append(f"- [{label}]({_href(path)})")
|
||||
for reply_title, path in entry.replies:
|
||||
lines.append(f"- Antwort auf [{reply_title}]({_href(path)})")
|
||||
if entry.notice:
|
||||
lines.extend(["", entry.notice])
|
||||
return lines
|
||||
|
||||
|
||||
def _entry_links(entry: Entry) -> list[tuple[str, str]]:
|
||||
@@ -650,6 +1205,7 @@ def _fact_lines(entry: Entry, generated: str) -> list[str]:
|
||||
lines.append(f"Erfasst am: {entry.recorded_at}")
|
||||
if entry.direction in _DIRECTION:
|
||||
lines.append(_DIRECTION[entry.direction])
|
||||
lines.extend(entry.notes)
|
||||
lines.append(f"Stand der Ausgabe: {generated}")
|
||||
return lines
|
||||
|
||||
@@ -720,13 +1276,20 @@ def _annotation_filename(node: ExportNode, _prefix) -> str:
|
||||
return f"{_segment(node.title)}.md"
|
||||
|
||||
|
||||
def _is_folder(node: ExportNode) -> bool:
|
||||
return node.kind in {"chapter", "matter"} or (node.kind == "binding" and node.content_kind == "email")
|
||||
def _ordered_numbered_children(node: ExportNode, chosen: set[str]) -> list[ExportNode]:
|
||||
"""Chapters, Teilvorgänge and every Schriftstück share one order within the parent."""
|
||||
items: list[ExportNode] = []
|
||||
for child in node.children:
|
||||
if child.kind in {"chapter", "matter"} and _included(child, chosen):
|
||||
items.append(child)
|
||||
elif child.kind == "binding" and _included(child, chosen):
|
||||
items.append(child)
|
||||
return items
|
||||
|
||||
|
||||
def _included(node: ExportNode, chosen: set[str]) -> bool:
|
||||
if node.kind == "binding" and node.content_kind == "email":
|
||||
return node.id in chosen
|
||||
return any(child.id in chosen for child in _walk(node) if child.kind in _NODE_KINDS)
|
||||
return any(child.id in chosen for child in _walk(node) if child.kind in _NODE_KINDS)
|
||||
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ from fastapi import FastAPI, Request
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
from app.api.correspondence import router as correspondence_router
|
||||
from app.api.export import router as export_router
|
||||
from app.api.routes import router
|
||||
from app.api.sources import router as sources_router
|
||||
@@ -117,6 +118,7 @@ def create_app() -> FastAPI:
|
||||
app.include_router(router)
|
||||
app.include_router(sources_router)
|
||||
app.include_router(export_router)
|
||||
app.include_router(correspondence_router)
|
||||
return app
|
||||
|
||||
|
||||
|
||||
+52
-11
@@ -701,7 +701,18 @@ def _actor_rights_for(conn, actor: UUID, kind: str, resource_id: UUID, context:
|
||||
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:
|
||||
def grant_access(
|
||||
conn,
|
||||
actor: UUID,
|
||||
kind: str,
|
||||
resource_id: UUID,
|
||||
grantee_id: UUID,
|
||||
can_read: bool,
|
||||
can_edit: bool,
|
||||
can_share: bool,
|
||||
context: Ctx | None,
|
||||
use_owner_sources: bool = False,
|
||||
) -> dict:
|
||||
if grantee_id == actor:
|
||||
raise unprocessable("Die eigene Berechtigung wird nicht als Freigabe gespeichert.")
|
||||
if not can_read:
|
||||
@@ -731,33 +742,40 @@ def grant_access(conn, actor: UUID, kind: str, resource_id: UUID, grantee_id: UU
|
||||
raise not_found()
|
||||
existing = conn.execute(
|
||||
"""
|
||||
SELECT id FROM access_grants
|
||||
SELECT id, use_owner_sources FROM access_grants
|
||||
WHERE NOT is_exception AND grantee_subject_id = %s
|
||||
AND resource_kind = %s AND resource_id = %s AND context_kind IS NULL
|
||||
""",
|
||||
(grantee_id, kind, resource_id),
|
||||
).fetchone()
|
||||
if owner:
|
||||
source_access = bool(use_owner_sources)
|
||||
elif existing is None:
|
||||
source_access = False
|
||||
else:
|
||||
source_access = bool(existing["use_owner_sources"])
|
||||
if existing is None:
|
||||
row = conn.execute(
|
||||
"""
|
||||
INSERT INTO access_grants (
|
||||
grantee_subject_id, resource_kind, resource_id,
|
||||
can_read, can_edit, can_share, can_delete, is_exception, created_by
|
||||
can_read, can_edit, can_share, can_delete, is_exception, created_by,
|
||||
use_owner_sources
|
||||
)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, false, false, %s)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, false, false, %s, %s)
|
||||
RETURNING *
|
||||
""",
|
||||
(grantee_id, kind, resource_id, can_read, can_edit, can_share, actor),
|
||||
(grantee_id, kind, resource_id, can_read, can_edit, can_share, actor, source_access),
|
||||
).fetchone()
|
||||
else:
|
||||
row = conn.execute(
|
||||
"""
|
||||
UPDATE access_grants
|
||||
SET can_read = %s, can_edit = %s, can_share = %s
|
||||
SET can_read = %s, can_edit = %s, can_share = %s, use_owner_sources = %s
|
||||
WHERE id = %s
|
||||
RETURNING *
|
||||
""",
|
||||
(can_read, can_edit, can_share, existing["id"]),
|
||||
(can_read, can_edit, can_share, source_access, existing["id"]),
|
||||
).fetchone()
|
||||
audit(conn, actor, resource["home_scope_id"], "grant_created", kind, resource_id, context)
|
||||
return row
|
||||
@@ -1046,6 +1064,9 @@ def delete_element(conn, actor: UUID, element_id: UUID, expected: int, media_roo
|
||||
if element is None or element["owner_subject_id"] != actor:
|
||||
raise not_found()
|
||||
bump_version(conn, "elements", element_id, expected)
|
||||
from app.correspondence import purge_element_dispatch_files
|
||||
|
||||
delete_after.extend(purge_element_dispatch_files(conn, element_id, media_root))
|
||||
asset = conn.execute("SELECT * FROM media_assets WHERE element_id = %s", (element_id,)).fetchone()
|
||||
conn.execute("DELETE FROM bindings WHERE element_id = %s", (element_id,))
|
||||
conn.execute(
|
||||
@@ -1394,6 +1415,7 @@ def set_content_order(
|
||||
mode: str,
|
||||
direction: str,
|
||||
context: Ctx | None,
|
||||
view: str | None = None,
|
||||
) -> int:
|
||||
if kind == "case":
|
||||
container, rights = require_case(conn, actor, container_id, "edit")
|
||||
@@ -1404,10 +1426,16 @@ def set_content_order(
|
||||
if not rights.edit:
|
||||
raise forbidden()
|
||||
version = bump_version(conn, table, container_id, expected)
|
||||
conn.execute(
|
||||
f"UPDATE {table} SET content_order = %s, content_order_dir = %s WHERE id = %s",
|
||||
(mode, direction, container_id),
|
||||
)
|
||||
if view is None:
|
||||
conn.execute(
|
||||
f"UPDATE {table} SET content_order = %s, content_order_dir = %s WHERE id = %s",
|
||||
(mode, direction, container_id),
|
||||
)
|
||||
else:
|
||||
conn.execute(
|
||||
f"UPDATE {table} SET content_order = %s, content_order_dir = %s, content_view = %s WHERE id = %s",
|
||||
(mode, direction, view, container_id),
|
||||
)
|
||||
audit(conn, actor, container["home_scope_id"], "content_order", kind, container_id, context)
|
||||
return version
|
||||
|
||||
@@ -1497,6 +1525,19 @@ def update_summary(conn, actor: UUID, element_id: UUID, expected: int, summary:
|
||||
return get_element(conn, element_id)
|
||||
|
||||
|
||||
def update_title(conn, actor: UUID, element_id: UUID, expected: int, title: str, context: Ctx | None) -> dict:
|
||||
element, rights = require_element(conn, actor, element_id, context, "edit")
|
||||
if not rights.edit:
|
||||
raise forbidden()
|
||||
cleaned = title.strip()
|
||||
if not cleaned or len(cleaned) > 200:
|
||||
raise unprocessable("Der Titel fehlt oder ist zu lang.")
|
||||
bump_version(conn, "elements", element_id, expected)
|
||||
conn.execute("UPDATE elements SET title = %s WHERE id = %s", (cleaned, element_id))
|
||||
audit(conn, actor, element["home_scope_id"], "title_changed", "element", element_id, context)
|
||||
return get_element(conn, element_id)
|
||||
|
||||
|
||||
def move_binding_chapter(conn, actor: UUID, binding_id: UUID, expected: int, chapter_id: UUID | None, context: Ctx | None) -> int:
|
||||
"""Move one visible binding inside its container. No new binding and no grant."""
|
||||
binding = conn.execute("SELECT * FROM bindings WHERE id = %s", (binding_id,)).fetchone()
|
||||
|
||||
+52
-9
@@ -126,7 +126,32 @@ def _preview_meta(kind: str, content_type: str | None, source: str | None) -> di
|
||||
return {"available": False, "media": "none", "source": source}
|
||||
|
||||
|
||||
def _element_body(conn, element: dict) -> dict:
|
||||
_HIDDEN_SOURCE_FIELDS = frozenset({
|
||||
"connector_id",
|
||||
"mailbox",
|
||||
"uid",
|
||||
"host",
|
||||
"username",
|
||||
"port",
|
||||
"password",
|
||||
"secret",
|
||||
"base_url",
|
||||
"server",
|
||||
"security",
|
||||
"open_url",
|
||||
})
|
||||
|
||||
|
||||
def _connector_owner(conn, raw) -> UUID | None:
|
||||
try:
|
||||
connector_id = UUID(str(raw))
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
row = conn.execute("SELECT owner_id FROM connectors WHERE id = %s", (connector_id,)).fetchone()
|
||||
return row["owner_id"] if row else None
|
||||
|
||||
|
||||
def _element_body(conn, actor: UUID, element: dict) -> dict:
|
||||
payload = {
|
||||
"id": str(element["id"]),
|
||||
"kind": element["kind"],
|
||||
@@ -169,11 +194,15 @@ def _element_body(conn, element: dict) -> dict:
|
||||
(element["id"],),
|
||||
).fetchone()
|
||||
if ref is not None:
|
||||
payload["external"] = {
|
||||
"source": ref["source"],
|
||||
"external_id": ref["external_id"],
|
||||
"detail": ref["detail"] or {},
|
||||
}
|
||||
detail = dict(ref["detail"] or {})
|
||||
connector_owner = _connector_owner(conn, detail.get("connector_id"))
|
||||
revealed = actor == element["owner_subject_id"] or (connector_owner is not None and actor == connector_owner)
|
||||
if not revealed:
|
||||
detail = {key: value for key, value in detail.items() if key not in _HIDDEN_SOURCE_FIELDS}
|
||||
external = {"source": ref["source"], "detail": detail}
|
||||
if revealed:
|
||||
external["external_id"] = ref["external_id"]
|
||||
payload["external"] = external
|
||||
payload["preview"] = _preview_meta("external_ref", None, ref["source"])
|
||||
return payload
|
||||
|
||||
@@ -280,7 +309,7 @@ def binding_payload(conn, actor: UUID, binding: dict, context: Ctx) -> dict | No
|
||||
rights = element_rights(conn, actor, element, context)
|
||||
if not rights.read:
|
||||
return None
|
||||
body = _element_body(conn, element)
|
||||
body = _element_body(conn, actor, element)
|
||||
container = Ctx(binding["context_kind"], binding["context_id"])
|
||||
_attach_references(conn, actor, element, context, container, body)
|
||||
payload = {
|
||||
@@ -300,7 +329,8 @@ def binding_payload(conn, actor: UUID, binding: dict, context: Ctx) -> dict | No
|
||||
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
|
||||
SELECT g.id, g.grantee_subject_id, g.can_read, g.can_edit, g.can_share, g.use_owner_sources,
|
||||
a.email, a.display_name
|
||||
FROM access_grants g
|
||||
JOIN auth_accounts a ON a.id = g.grantee_subject_id
|
||||
WHERE NOT g.is_exception AND g.resource_kind = %s AND g.resource_id = %s AND g.context_kind IS NULL
|
||||
@@ -317,6 +347,7 @@ def _grants(conn, kind: str, resource_id: UUID) -> list[dict]:
|
||||
"can_read": row["can_read"],
|
||||
"can_edit": row["can_edit"],
|
||||
"can_share": row["can_share"],
|
||||
"use_owner_sources": row["use_owner_sources"],
|
||||
}
|
||||
for row in rows
|
||||
]
|
||||
@@ -338,8 +369,16 @@ def _ordered_bindings(conn, actor: UUID, kind: str, container_id: UUID, context:
|
||||
continue
|
||||
item["_raw_position"] = binding["position"]
|
||||
item["_document_on"] = item["element"]["dates"]["document_on"]
|
||||
item["container"] = {"kind": kind, "id": str(container_id)}
|
||||
item["_fold"] = binding.get("list_fold")
|
||||
visible.append(item)
|
||||
return arrange(visible, mode or "position", direction or "asc")
|
||||
arranged = arrange(visible, mode or "position", direction or "asc")
|
||||
from app.correspondence import attach_correspondence
|
||||
|
||||
attach_correspondence(conn, actor, arranged, context)
|
||||
for item in arranged:
|
||||
item.pop("_fold", None)
|
||||
return arranged
|
||||
|
||||
|
||||
def course_items(bindings: list[dict]) -> list[dict]:
|
||||
@@ -575,6 +614,7 @@ def case_detail(conn, actor: UUID, case: dict, rights) -> dict:
|
||||
payload = case_summary(case, rights)
|
||||
payload["content_order"] = case.get("content_order") or "position"
|
||||
payload["content_order_dir"] = case.get("content_order_dir") or "asc"
|
||||
payload["content_view"] = case.get("content_view") or "structure"
|
||||
payload["trail"] = case_trail(conn, actor, case)
|
||||
payload["kind_label"] = "Unterakte" if case["parent_case_id"] else "Akte"
|
||||
payload["home_scope_name"] = room_name(conn, case["home_scope_id"])
|
||||
@@ -714,6 +754,7 @@ def matter_detail(conn, actor: UUID, matter: dict, rights, context: Ctx | None)
|
||||
"is_owner": matter["owner_subject_id"] == actor,
|
||||
"content_order": matter.get("content_order") or "position",
|
||||
"content_order_dir": matter.get("content_order_dir") or "asc",
|
||||
"content_view": matter.get("content_view") or "structure",
|
||||
"trail": matter_trail(conn, actor, matter, context),
|
||||
"placements": matter_placements(conn, actor, matter["id"], context),
|
||||
"kind_label": "Teilvorgang" if matter["parent_matter_id"] else "Vorgang",
|
||||
@@ -948,12 +989,14 @@ LABELS = {
|
||||
"deadline_fulfilled": "Frist erfüllt",
|
||||
"grant_created": "Freigabe erteilt",
|
||||
"grant_revoked": "Freigabe entzogen",
|
||||
"source_read_mediated": "Verknüpftes Original gelesen",
|
||||
"correspondence_document": "Dokumentdatum",
|
||||
"correspondence_sent": "Versand",
|
||||
"correspondence_received": "Zugang",
|
||||
"correspondence_recorded": "Erfassung",
|
||||
"chapter_created": "Kapitel angelegt",
|
||||
"summary_changed": "Kurzbeschreibung geändert",
|
||||
"title_changed": "Titel geändert",
|
||||
"binding_chapter": "In ein Kapitel eingeordnet",
|
||||
"chapters_reordered": "Kapitelreihenfolge geändert",
|
||||
"chapter_dated": "Kapiteldatum geändert",
|
||||
|
||||
@@ -18,6 +18,7 @@ from uuid import UUID
|
||||
|
||||
from psycopg.types.json import Json
|
||||
|
||||
from app.access.policy import Ctx, audit, mediated_source_owner
|
||||
from app.core.errors import Problem, not_found, unprocessable
|
||||
from app.core.settings import get_settings
|
||||
from app.mailpack import MailIdentityError, choose_message, identities_match, header_message_id
|
||||
@@ -207,6 +208,10 @@ def paperless_content(conn, owner_id: UUID, document_id: str) -> tuple[bytes, st
|
||||
).fetchone()
|
||||
if row is None:
|
||||
raise unprocessable("Paperless ist für dieses Konto nicht verbunden.")
|
||||
return _paperless_bytes(row, document_id)
|
||||
|
||||
|
||||
def _paperless_bytes(row, document_id: str) -> tuple[bytes, str, str]:
|
||||
base = row["settings"]["base_url"].rstrip("/")
|
||||
token = row["secret"]
|
||||
misses = 0
|
||||
@@ -228,6 +233,139 @@ def paperless_content(conn, owner_id: UUID, document_id: str) -> tuple[bytes, st
|
||||
raise unprocessable("Paperless stellt diese Datei nicht zum Ansehen bereit.")
|
||||
|
||||
|
||||
ORIGINAL_UNAVAILABLE = "Das Original ist über die Freigabe nicht abrufbar."
|
||||
|
||||
|
||||
def read_linked_paperless(conn, actor_id: UUID, element: dict, context: Ctx | None, ref) -> tuple[bytes, str, str]:
|
||||
"""The stored document. A grantee never uses a connector of their own account."""
|
||||
detail = (ref or {}).get("detail") or {}
|
||||
external_id = str((ref or {}).get("external_id") or "")
|
||||
stored = _uuid(detail.get("connector_id"))
|
||||
stored_owner = _connector_owner(conn, stored)
|
||||
if element["owner_subject_id"] == actor_id or stored_owner == actor_id:
|
||||
return paperless_content(conn, actor_id, external_id)
|
||||
owner_id = mediated_source_owner(conn, actor_id, element, context)
|
||||
if owner_id is None or not external_id.isdigit() or len(external_id) > 12:
|
||||
raise unprocessable(ORIGINAL_UNAVAILABLE)
|
||||
row = _mediated_paperless(conn, owner_id, stored, element)
|
||||
if row is None:
|
||||
_audit_mediated(conn, actor_id, element, context, "paperless", stored, "unavailable")
|
||||
raise unprocessable(ORIGINAL_UNAVAILABLE)
|
||||
try:
|
||||
data, media, name = _paperless_bytes(row, external_id)
|
||||
except Problem:
|
||||
_audit_mediated(conn, actor_id, element, context, "paperless", row["id"], "unavailable")
|
||||
raise unprocessable(ORIGINAL_UNAVAILABLE) from None
|
||||
_audit_mediated(conn, actor_id, element, context, "paperless", row["id"], "ok")
|
||||
if external_id and external_id in (name or ""):
|
||||
name = "dokument.pdf"
|
||||
return data, media, name or "dokument.pdf"
|
||||
|
||||
|
||||
def read_linked_mail(conn, actor_id: UUID, element: dict, context: Ctx | None, ref) -> bytes:
|
||||
"""The stored message. Mailbox, UID and connector come only from the saved reference."""
|
||||
detail = (ref or {}).get("detail") or {}
|
||||
if ref is None or ref["source"] != "imap":
|
||||
raise unprocessable("Das ist keine E-Mail.")
|
||||
connector_id = _uuid(detail.get("connector_id"))
|
||||
mailbox = str(detail.get("mailbox") or "").strip()
|
||||
uid = _mail_uid(detail.get("uid"))
|
||||
external_id = str(ref["external_id"])
|
||||
stored_owner = _connector_owner(conn, connector_id)
|
||||
if element["owner_subject_id"] == actor_id or stored_owner == actor_id:
|
||||
if connector_id is None or not mailbox or uid is None:
|
||||
raise unprocessable("Für diese E-Mail fehlt die Zuordnung zu Fach und Nachricht.")
|
||||
return load_imap_original(conn, actor_id, connector_id, mailbox, uid, external_id)
|
||||
owner_id = mediated_source_owner(conn, actor_id, element, context)
|
||||
if owner_id is None or connector_id is None or not mailbox or uid is None:
|
||||
raise unprocessable(ORIGINAL_UNAVAILABLE)
|
||||
row = _connector_for(conn, connector_id, owner_id, "imap")
|
||||
if row is None:
|
||||
_audit_mediated(conn, actor_id, element, context, "imap", connector_id, "unavailable")
|
||||
raise unprocessable(ORIGINAL_UNAVAILABLE)
|
||||
try:
|
||||
raw = load_imap_original(conn, owner_id, connector_id, mailbox, uid, external_id)
|
||||
except Problem:
|
||||
_audit_mediated(conn, actor_id, element, context, "imap", connector_id, "unavailable")
|
||||
raise unprocessable(ORIGINAL_UNAVAILABLE) from None
|
||||
_audit_mediated(conn, actor_id, element, context, "imap", connector_id, "ok")
|
||||
return raw
|
||||
|
||||
|
||||
def _uuid(value) -> UUID | None:
|
||||
if isinstance(value, UUID):
|
||||
return value
|
||||
try:
|
||||
return UUID(str(value))
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def _mail_uid(value) -> int | None:
|
||||
if isinstance(value, bool):
|
||||
return None
|
||||
if isinstance(value, int) and value >= 1:
|
||||
return value
|
||||
if isinstance(value, str) and value.isdigit() and int(value) >= 1:
|
||||
return int(value)
|
||||
return None
|
||||
|
||||
|
||||
def _connector_owner(conn, connector_id: UUID | None) -> UUID | None:
|
||||
if connector_id is None:
|
||||
return None
|
||||
row = conn.execute("SELECT owner_id FROM connectors WHERE id = %s", (connector_id,)).fetchone()
|
||||
return row["owner_id"] if row else None
|
||||
|
||||
|
||||
def _connector_for(conn, connector_id: UUID, owner_id: UUID, kind: str):
|
||||
return conn.execute(
|
||||
"""
|
||||
SELECT id, owner_id, kind, settings, secret
|
||||
FROM connectors
|
||||
WHERE id = %s AND owner_id = %s AND kind = %s
|
||||
""",
|
||||
(connector_id, owner_id, kind),
|
||||
).fetchone()
|
||||
|
||||
|
||||
def _mediated_paperless(conn, owner_id: UUID, stored: UUID | None, element: dict):
|
||||
if stored is not None:
|
||||
return _connector_for(conn, stored, owner_id, "paperless")
|
||||
if element["owner_subject_id"] != owner_id:
|
||||
return None
|
||||
return conn.execute(
|
||||
"""
|
||||
SELECT id, owner_id, kind, settings, secret
|
||||
FROM connectors
|
||||
WHERE owner_id = %s AND kind = 'paperless'
|
||||
ORDER BY created_at DESC
|
||||
LIMIT 1
|
||||
""",
|
||||
(owner_id,),
|
||||
).fetchone()
|
||||
|
||||
|
||||
def _audit_mediated(conn, actor_id: UUID, element: dict, context: Ctx | None, source: str, connector_id, outcome: str) -> None:
|
||||
audit(
|
||||
conn,
|
||||
actor_id,
|
||||
element["home_scope_id"],
|
||||
"source_read_mediated",
|
||||
"element",
|
||||
element["id"],
|
||||
context,
|
||||
result="ok" if outcome == "ok" else "unavailable",
|
||||
detail={
|
||||
"source": source,
|
||||
"connector_id": str(connector_id) if connector_id else None,
|
||||
"outcome": outcome,
|
||||
},
|
||||
)
|
||||
if outcome != "ok":
|
||||
conn.commit()
|
||||
|
||||
|
||||
def _paperless_file(
|
||||
base: str,
|
||||
token: str,
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
-- Anlagenverwendung, dokumentierter Versand und Arbeitsansicht.
|
||||
-- Bestehende Kapitel, Einbindungen und Dateien bleiben unverändert.
|
||||
|
||||
ALTER TABLE cases
|
||||
ADD COLUMN content_view text NOT NULL DEFAULT 'structure';
|
||||
|
||||
ALTER TABLE cases
|
||||
ADD CONSTRAINT cases_content_view
|
||||
CHECK (content_view IN ('structure', 'chronology'));
|
||||
|
||||
ALTER TABLE matters
|
||||
ADD COLUMN content_view text NOT NULL DEFAULT 'structure';
|
||||
|
||||
ALTER TABLE matters
|
||||
ADD CONSTRAINT matters_content_view
|
||||
CHECK (content_view IN ('structure', 'chronology'));
|
||||
|
||||
ALTER TABLE bindings
|
||||
ADD COLUMN list_fold text;
|
||||
|
||||
ALTER TABLE bindings
|
||||
ADD CONSTRAINT bindings_list_fold
|
||||
CHECK (list_fold IS NULL OR list_fold IN ('attachment', 'evidence'));
|
||||
|
||||
CREATE TABLE attachment_uses (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
home_scope_id uuid NOT NULL REFERENCES data_rooms (id),
|
||||
context_kind text NOT NULL,
|
||||
context_id uuid NOT NULL,
|
||||
host_element_id uuid NOT NULL REFERENCES elements (id) ON DELETE CASCADE,
|
||||
attachment_element_id uuid NOT NULL REFERENCES elements (id) ON DELETE CASCADE,
|
||||
position integer NOT NULL,
|
||||
label text,
|
||||
created_by uuid NOT NULL REFERENCES auth_accounts (id),
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
CONSTRAINT attachment_uses_kind CHECK (context_kind IN ('case', 'matter')),
|
||||
CONSTRAINT attachment_uses_not_self CHECK (host_element_id <> attachment_element_id),
|
||||
CONSTRAINT attachment_uses_position CHECK (position >= 0),
|
||||
CONSTRAINT attachment_uses_label CHECK (label IS NULL OR char_length(label) BETWEEN 1 AND 200),
|
||||
CONSTRAINT attachment_uses_once UNIQUE (context_kind, context_id, host_element_id, attachment_element_id)
|
||||
);
|
||||
|
||||
CREATE INDEX attachment_uses_host
|
||||
ON attachment_uses (context_kind, context_id, host_element_id, position);
|
||||
|
||||
CREATE TABLE dispatches (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
home_scope_id uuid NOT NULL REFERENCES data_rooms (id),
|
||||
context_kind text NOT NULL,
|
||||
context_id uuid NOT NULL,
|
||||
host_element_id uuid NOT NULL REFERENCES elements (id) ON DELETE CASCADE,
|
||||
channel text NOT NULL,
|
||||
sent_on date,
|
||||
counterpart text,
|
||||
completeness text NOT NULL,
|
||||
provenance text NOT NULL,
|
||||
recorded_by uuid NOT NULL REFERENCES auth_accounts (id),
|
||||
recorded_at timestamptz NOT NULL DEFAULT now(),
|
||||
version integer NOT NULL DEFAULT 1,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
CONSTRAINT dispatches_kind CHECK (context_kind IN ('case', 'matter')),
|
||||
CONSTRAINT dispatches_channel CHECK (channel IN ('email', 'post', 'other')),
|
||||
CONSTRAINT dispatches_completeness CHECK (completeness IN ('secured', 'partial', 'gap')),
|
||||
CONSTRAINT dispatches_provenance CHECK (provenance IN ('captured', 'reconstructed')),
|
||||
CONSTRAINT dispatches_counterpart CHECK (counterpart IS NULL OR char_length(counterpart) BETWEEN 1 AND 200),
|
||||
CONSTRAINT dispatches_version CHECK (version >= 1)
|
||||
);
|
||||
|
||||
CREATE INDEX dispatches_host
|
||||
ON dispatches (context_kind, context_id, host_element_id, recorded_at);
|
||||
|
||||
CREATE TABLE dispatch_items (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
dispatch_id uuid NOT NULL REFERENCES dispatches (id) ON DELETE CASCADE,
|
||||
role text NOT NULL,
|
||||
position integer NOT NULL,
|
||||
element_id uuid NOT NULL REFERENCES elements (id) ON DELETE CASCADE,
|
||||
title text NOT NULL,
|
||||
document_on date,
|
||||
filename text,
|
||||
content_type text,
|
||||
byte_size bigint,
|
||||
content_sha256 text,
|
||||
source_state text NOT NULL,
|
||||
gap_reason text,
|
||||
note_document jsonb,
|
||||
external_source text,
|
||||
external_id text,
|
||||
CONSTRAINT dispatch_items_role CHECK (role IN ('host', 'attachment')),
|
||||
CONSTRAINT dispatch_items_position CHECK (position >= 0),
|
||||
CONSTRAINT dispatch_items_state CHECK (source_state IN ('snapshot', 'gap')),
|
||||
CONSTRAINT dispatch_items_once UNIQUE (dispatch_id, element_id)
|
||||
);
|
||||
|
||||
CREATE INDEX dispatch_items_dispatch ON dispatch_items (dispatch_id, position);
|
||||
|
||||
CREATE TABLE dispatch_snapshots (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
dispatch_item_id uuid UNIQUE REFERENCES dispatch_items (id) ON DELETE CASCADE,
|
||||
evidence_id uuid,
|
||||
home_scope_id uuid NOT NULL REFERENCES data_rooms (id),
|
||||
owner_subject_id uuid NOT NULL REFERENCES auth_accounts (id),
|
||||
original_filename text NOT NULL,
|
||||
content_type text NOT NULL,
|
||||
byte_size bigint NOT NULL,
|
||||
sha256 text NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
CONSTRAINT dispatch_snapshots_filename CHECK (char_length(original_filename) BETWEEN 1 AND 240),
|
||||
CONSTRAINT dispatch_snapshots_target CHECK (
|
||||
(dispatch_item_id IS NOT NULL AND evidence_id IS NULL)
|
||||
OR (dispatch_item_id IS NULL AND evidence_id IS NOT NULL)
|
||||
)
|
||||
);
|
||||
|
||||
CREATE TABLE dispatch_evidence (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
dispatch_id uuid NOT NULL REFERENCES dispatches (id) ON DELETE CASCADE,
|
||||
element_id uuid NOT NULL REFERENCES elements (id) ON DELETE CASCADE,
|
||||
role text NOT NULL,
|
||||
source_state text NOT NULL,
|
||||
gap_reason text,
|
||||
message_id text,
|
||||
identity_sha256 text,
|
||||
comparisons jsonb NOT NULL DEFAULT '[]'::jsonb,
|
||||
manual boolean NOT NULL DEFAULT true,
|
||||
created_by uuid NOT NULL REFERENCES auth_accounts (id),
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
CONSTRAINT dispatch_evidence_role CHECK (role IN ('email', 'submission', 'delivery', 'other')),
|
||||
CONSTRAINT dispatch_evidence_state CHECK (source_state IN ('identified', 'gap')),
|
||||
CONSTRAINT dispatch_evidence_once UNIQUE (dispatch_id, element_id)
|
||||
);
|
||||
|
||||
ALTER TABLE dispatch_snapshots
|
||||
ADD CONSTRAINT dispatch_snapshots_evidence_fk
|
||||
FOREIGN KEY (evidence_id) REFERENCES dispatch_evidence (id) ON DELETE CASCADE;
|
||||
|
||||
CREATE TABLE dispatch_corrections (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
dispatch_id uuid NOT NULL REFERENCES dispatches (id) ON DELETE CASCADE,
|
||||
corrected_at timestamptz NOT NULL DEFAULT now(),
|
||||
corrected_by uuid NOT NULL REFERENCES auth_accounts (id),
|
||||
summary text NOT NULL,
|
||||
CONSTRAINT dispatch_corrections_summary CHECK (char_length(summary) BETWEEN 1 AND 500)
|
||||
);
|
||||
|
||||
CREATE INDEX dispatch_corrections_dispatch ON dispatch_corrections (dispatch_id, corrected_at);
|
||||
@@ -0,0 +1,8 @@
|
||||
-- Owner kann an einer Freigabe erlauben, verknüpfte Originale über die eigenen Zugänge zu lesen.
|
||||
-- Bestehende Freigaben bleiben ohne diesen Abruf.
|
||||
|
||||
ALTER TABLE access_grants
|
||||
ADD COLUMN use_owner_sources boolean NOT NULL DEFAULT false;
|
||||
|
||||
ALTER TABLE domain_events
|
||||
ADD COLUMN detail jsonb;
|
||||
@@ -0,0 +1,640 @@
|
||||
"""Schreiben, Anlagen, Versandfassungen, Nachweise, Rechte und Export."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import zipfile
|
||||
from email.message import EmailMessage
|
||||
from pathlib import Path
|
||||
|
||||
from tests.support import ORIGIN, Actor, document, grant, register
|
||||
|
||||
PDF_A = b"%PDF-1.4\n1 0 obj<<>>endobj\ntrailer<<>>\n%%EOF\nA\n"
|
||||
PDF_B = b"%PDF-1.4\n2 0 obj<<>>endobj\ntrailer<<>>\n%%EOF\nB\n"
|
||||
PDF_C = b"%PDF-1.4\n3 0 obj<<>>endobj\ntrailer<<>>\n%%EOF\nC\n"
|
||||
PDF_D = b"%PDF-1.4\n4 0 obj<<>>endobj\ntrailer<<>>\n%%EOF\nD\n"
|
||||
|
||||
|
||||
def _detail(actor: Actor, matter_id: str, context: dict | None = None) -> dict:
|
||||
params = None
|
||||
if context is not None:
|
||||
params = {"context_kind": context["kind"], "context_id": context["id"]}
|
||||
return actor.request("GET", f"/api/v1/matters/{matter_id}", params=params)
|
||||
|
||||
|
||||
def _binding(detail: dict, title: str) -> dict:
|
||||
for item in detail["bindings"]:
|
||||
if item["element"]["title"] == title:
|
||||
return item
|
||||
raise AssertionError(title)
|
||||
|
||||
|
||||
def _file(actor: Actor, matter_id: str, title: str, name: str, data: bytes, document_on: str, chapter_id: str | None = None) -> dict:
|
||||
form = {"title": title, "context_kind": "matter", "context_id": matter_id, "document_on": document_on}
|
||||
if chapter_id:
|
||||
form["chapter_id"] = chapter_id
|
||||
return actor.request(
|
||||
"POST",
|
||||
"/api/v1/files",
|
||||
data=form,
|
||||
files={"upload": (name, data, "application/pdf")},
|
||||
status=201,
|
||||
)
|
||||
|
||||
|
||||
def _ctx(matter_id: str) -> dict:
|
||||
return {"kind": "matter", "id": matter_id}
|
||||
|
||||
|
||||
def _eml(message_id: str, body: str, attachments: list[tuple[str, bytes]]) -> bytes:
|
||||
message = EmailMessage()
|
||||
message["Subject"] = "Versandnachweis"
|
||||
message["From"] = "kanzlei@example.test"
|
||||
message["To"] = "gegenueber@example.test"
|
||||
message["Message-ID"] = message_id
|
||||
message["Date"] = "Thu, 12 Mar 2026 10:00:00 +0100"
|
||||
message.set_content(body)
|
||||
for name, data in attachments:
|
||||
message.add_attachment(data, maintype="application", subtype="pdf", filename=name)
|
||||
return message.as_bytes()
|
||||
|
||||
|
||||
def _zip(actor: Actor, matter_id: str, selected: list[str]) -> zipfile.ZipFile:
|
||||
headers = {
|
||||
"Origin": ORIGIN,
|
||||
"X-CSRF-Token": actor.csrf,
|
||||
"Content-Type": "application/json",
|
||||
"X-Scope-Kind": actor.scope["kind"],
|
||||
"X-Scope-Id": actor.scope["id"],
|
||||
}
|
||||
response = actor.client.post(
|
||||
f"/api/v1/matters/{matter_id}/export",
|
||||
json={"selected": selected},
|
||||
headers=headers,
|
||||
)
|
||||
assert response.status_code == 200, response.text
|
||||
return zipfile.ZipFile(io.BytesIO(response.content))
|
||||
|
||||
|
||||
def _walk(node):
|
||||
yield node
|
||||
for child in node.get("children") or []:
|
||||
yield from _walk(child)
|
||||
|
||||
|
||||
def test_attachments_keep_other_uses_and_do_not_copy_files(client, db):
|
||||
ada = Actor(client, "ada-anlage@example.test", "Ada Anlage")
|
||||
register(db, ada.email, ada.name)
|
||||
ada.login()
|
||||
matter = ada.request("POST", "/api/v1/matters", json={"title": "Schreiben A"}, status=201)
|
||||
other = ada.request("POST", "/api/v1/matters", json={"title": "Schreiben B"}, status=201)
|
||||
chapter = ada.request("POST", f"/api/v1/matters/{matter['id']}/chapters", json={"title": "Korrespondenz"}, status=201)
|
||||
sub = ada.request(
|
||||
"POST",
|
||||
f"/api/v1/matters/{matter['id']}/chapters",
|
||||
json={"title": "Einzelbelege", "parent_chapter_id": chapter["id"]},
|
||||
status=201,
|
||||
)
|
||||
letter = ada.request(
|
||||
"POST",
|
||||
"/api/v1/notes",
|
||||
json={
|
||||
"title": "Anschreiben",
|
||||
"document": document("Bitte um Stellungnahme"),
|
||||
"context": _ctx(matter["id"]),
|
||||
"chapter_id": chapter["id"],
|
||||
"dates": {"document_on": "2026-03-01"},
|
||||
},
|
||||
status=201,
|
||||
)
|
||||
first = _file(ada, matter["id"], "Rechnung 2023", "rechnung.pdf", PDF_A, "2023-05-01", sub["id"])
|
||||
second = _file(ada, matter["id"], "Lageplan", "lage.pdf", PDF_B, "2024-01-15", sub["id"])
|
||||
third = _file(ada, matter["id"], "Kontoauszug", "konto.pdf", PDF_C, "2025-11-02", sub["id"])
|
||||
before = db.execute("SELECT count(*) AS n FROM media_assets").fetchone()["n"]
|
||||
detail = _detail(ada, matter["id"])
|
||||
host = _binding(detail, "Anschreiben")
|
||||
ada.request(
|
||||
"POST",
|
||||
f"/api/v1/elements/{letter['id']}/attachments",
|
||||
json={
|
||||
"expected_version": host["element"]["version"],
|
||||
"context": _ctx(matter["id"]),
|
||||
"attachment_element_ids": [first["id"], second["id"], third["id"]],
|
||||
"fold": "keep",
|
||||
},
|
||||
status=201,
|
||||
)
|
||||
ordered = _detail(ada, matter["id"])
|
||||
host = _binding(ordered, "Anschreiben")
|
||||
assert [item["title"] for item in host["correspondence"]["attachments"]] == [
|
||||
"Rechnung 2023",
|
||||
"Lageplan",
|
||||
"Kontoauszug",
|
||||
]
|
||||
assert [item["document_on"] for item in host["correspondence"]["attachments"]] == [
|
||||
"2023-05-01",
|
||||
"2024-01-15",
|
||||
"2025-11-02",
|
||||
]
|
||||
ada.request(
|
||||
"POST",
|
||||
f"/api/v1/elements/{letter['id']}/attachments/order",
|
||||
json={
|
||||
"expected_version": host["element"]["version"],
|
||||
"context": _ctx(matter["id"]),
|
||||
"attachment_element_ids": [third["id"], first["id"], second["id"]],
|
||||
},
|
||||
)
|
||||
moved = _detail(ada, matter["id"])
|
||||
host = _binding(moved, "Anschreiben")
|
||||
assert [item["element_id"] for item in host["correspondence"]["attachments"]] == [third["id"], first["id"], second["id"]]
|
||||
ada.request(
|
||||
"POST",
|
||||
f"/api/v1/elements/{letter['id']}/attachments/{second['id']}/detach",
|
||||
json={"expected_version": host["element"]["version"], "context": _ctx(matter["id"])},
|
||||
status=204,
|
||||
)
|
||||
kept = _detail(ada, matter["id"])
|
||||
assert _binding(kept, "Lageplan")["chapter_id"] == sub["id"]
|
||||
assert [item["title"] for item in _binding(kept, "Anschreiben")["correspondence"]["attachments"]] == [
|
||||
"Kontoauszug",
|
||||
"Rechnung 2023",
|
||||
]
|
||||
assert any(item["title"] == "Einzelbelege" and item["parent_chapter_id"] == chapter["id"] for item in kept["chapters"])
|
||||
after = db.execute("SELECT count(*) AS n FROM media_assets").fetchone()["n"]
|
||||
assert after == before
|
||||
ada.request(
|
||||
"POST",
|
||||
"/api/v1/bindings",
|
||||
json={"element_id": first["id"], "source_context": _ctx(matter["id"]), "target": _ctx(other["id"])},
|
||||
status=201,
|
||||
)
|
||||
other_letter = ada.request(
|
||||
"POST",
|
||||
"/api/v1/notes",
|
||||
json={"title": "Zweites Schreiben", "document": document("Andere Sache"), "context": _ctx(other["id"])},
|
||||
status=201,
|
||||
)
|
||||
other_detail = _detail(ada, other["id"])
|
||||
ada.request(
|
||||
"POST",
|
||||
f"/api/v1/elements/{other_letter['id']}/attachments",
|
||||
json={
|
||||
"expected_version": _binding(other_detail, "Zweites Schreiben")["element"]["version"],
|
||||
"context": _ctx(other["id"]),
|
||||
"attachment_element_ids": [first["id"]],
|
||||
"fold": "keep",
|
||||
},
|
||||
status=201,
|
||||
)
|
||||
again = _detail(ada, matter["id"])
|
||||
elsewhere = _detail(ada, other["id"])
|
||||
assert [item["element_id"] for item in _binding(again, "Anschreiben")["correspondence"]["attachments"]] == [
|
||||
third["id"],
|
||||
first["id"],
|
||||
]
|
||||
assert [item["element_id"] for item in _binding(elsewhere, "Zweites Schreiben")["correspondence"]["attachments"]] == [
|
||||
first["id"],
|
||||
]
|
||||
grants = db.execute("SELECT count(*) AS n FROM access_grants").fetchone()["n"]
|
||||
assert grants == 0
|
||||
ada.request(
|
||||
"POST",
|
||||
f"/api/v1/elements/{letter['id']}/attachments",
|
||||
json={
|
||||
"expected_version": _binding(again, "Anschreiben")["element"]["version"],
|
||||
"context": _ctx(matter["id"]),
|
||||
"attachment_element_ids": [letter["id"]],
|
||||
"fold": "keep",
|
||||
},
|
||||
status=422,
|
||||
)
|
||||
ada.request(
|
||||
"POST",
|
||||
f"/api/v1/elements/{letter['id']}/attachments",
|
||||
json={
|
||||
"expected_version": _binding(again, "Anschreiben")["element"]["version"],
|
||||
"context": _ctx(other["id"]),
|
||||
"attachment_element_ids": [first["id"]],
|
||||
"fold": "keep",
|
||||
},
|
||||
status=404,
|
||||
)
|
||||
|
||||
|
||||
def test_dispatch_keeps_the_secured_stand_and_distinct_mail_parts(client, db, monkeypatch):
|
||||
raw = _eml(
|
||||
"<versand@example.test>",
|
||||
"Fachlicher Zusatz: die Frist bleibt der 1. Juni.",
|
||||
[("rechnung.pdf", PDF_A), ("lage.pdf", PDF_B), ("konto.pdf", PDF_C), ("lage.pdf", PDF_D)],
|
||||
)
|
||||
monkeypatch.setattr("app.retrieval.pull_rfc822", lambda *args, **kwargs: raw)
|
||||
ada = Actor(client, "ada-versand@example.test", "Ada Versand")
|
||||
register(db, ada.email, ada.name)
|
||||
ada.login()
|
||||
matter = ada.request("POST", "/api/v1/matters", json={"title": "Versandakte"}, status=201)
|
||||
letter = ada.request(
|
||||
"POST",
|
||||
"/api/v1/notes",
|
||||
json={
|
||||
"title": "Anschreiben",
|
||||
"document": document("Ursprünglicher Text"),
|
||||
"context": _ctx(matter["id"]),
|
||||
"dates": {"document_on": "2026-02-01"},
|
||||
},
|
||||
status=201,
|
||||
)
|
||||
invoice = _file(ada, matter["id"], "Rechnung 2023", "rechnung.pdf", PDF_A, "2023-05-01")
|
||||
plan = _file(ada, matter["id"], "Lageplan", "lage.pdf", PDF_B, "2024-01-15")
|
||||
account = _file(ada, matter["id"], "Kontoauszug", "konto.pdf", PDF_C, "2025-11-02")
|
||||
mailbox = ada.request(
|
||||
"POST",
|
||||
"/api/v1/connectors",
|
||||
json={"kind": "imap", "name": "Postfach", "host": "mail.example.test", "username": "ada", "password": "secret-pass"},
|
||||
status=201,
|
||||
)
|
||||
mail = ada.request(
|
||||
"POST",
|
||||
"/api/v1/external-refs",
|
||||
json={
|
||||
"title": "Gesendete Nachricht",
|
||||
"source": "imap",
|
||||
"external_id": "<versand@example.test>",
|
||||
"context": _ctx(matter["id"]),
|
||||
"detail": {"connector_id": mailbox["id"], "mailbox": "INBOX", "uid": 4},
|
||||
},
|
||||
status=201,
|
||||
)
|
||||
detail = _detail(ada, matter["id"])
|
||||
ada.request(
|
||||
"POST",
|
||||
f"/api/v1/elements/{letter['id']}/attachments",
|
||||
json={
|
||||
"expected_version": _binding(detail, "Anschreiben")["element"]["version"],
|
||||
"context": _ctx(matter["id"]),
|
||||
"attachment_element_ids": [invoice["id"], plan["id"], account["id"]],
|
||||
"fold": "attachment",
|
||||
},
|
||||
status=201,
|
||||
)
|
||||
folded = _detail(ada, matter["id"])
|
||||
assert _binding(folded, "Rechnung 2023")["correspondence"]["fold"] == "attachment"
|
||||
host = _binding(folded, "Anschreiben")
|
||||
dispatch = ada.request(
|
||||
"POST",
|
||||
f"/api/v1/elements/{letter['id']}/dispatches",
|
||||
json={
|
||||
"expected_version": host["element"]["version"],
|
||||
"context": _ctx(matter["id"]),
|
||||
"channel": "email",
|
||||
"sent_on": "2026-03-12",
|
||||
"counterpart": "Gegenüber Beispiel",
|
||||
"attachment_element_ids": [invoice["id"], plan["id"], account["id"]],
|
||||
"evidence": [{"element_id": mail["id"], "role": "email", "fold": "evidence"}],
|
||||
},
|
||||
status=201,
|
||||
)
|
||||
assert dispatch["completeness"] == "secured"
|
||||
assert dispatch["provenance"] == "captured"
|
||||
assert dispatch["sent_on"] == "2026-03-12"
|
||||
proof = dispatch["evidence"][0]
|
||||
assert proof["source_state"] == "identified"
|
||||
assert proof["manual"] is True
|
||||
by_name = {item["filename"]: item["disposition"] for item in proof["comparisons"]}
|
||||
assert by_name["rechnung.pdf"] == "same_bytes"
|
||||
assert by_name["lage.pdf"] == "same_bytes"
|
||||
assert by_name["konto.pdf"] == "same_bytes"
|
||||
assert by_name["lage (2).pdf"] == "same_name_different_bytes"
|
||||
uses = db.execute("SELECT count(*) AS n FROM attachment_uses").fetchone()["n"]
|
||||
assert uses == 3
|
||||
hidden = _detail(ada, matter["id"])
|
||||
assert _binding(hidden, "Gesendete Nachricht")["correspondence"]["fold"] == "evidence"
|
||||
placed = list(_walk(ada.request("GET", f"/api/v1/matters/{matter['id']}/export-tree")["tree"]))
|
||||
assert not any(node["kind"] == "binding" and node["title"] in {"Rechnung 2023", "Gesendete Nachricht"} for node in placed)
|
||||
assert sum(1 for node in placed if node["kind"] == "attachment" and node["title"] == "Rechnung 2023") == 1
|
||||
assert any(node["kind"] == "dispatch_item" and node["title"] == "Rechnung 2023" for node in placed)
|
||||
assert any(node["kind"] == "evidence" and node["title"] == "Gesendete Nachricht" for node in placed)
|
||||
ada.request(
|
||||
"PATCH",
|
||||
f"/api/v1/bindings/{_binding(hidden, 'Gesendete Nachricht')['id']}/fold",
|
||||
json={
|
||||
"expected_version": _binding(hidden, "Gesendete Nachricht")["element"]["version"],
|
||||
"context": _ctx(matter["id"]),
|
||||
"fold": None,
|
||||
},
|
||||
)
|
||||
restored = _detail(ada, matter["id"])
|
||||
assert _binding(restored, "Gesendete Nachricht")["correspondence"]["fold"] is None
|
||||
ada.request(
|
||||
"PATCH",
|
||||
f"/api/v1/bindings/{_binding(restored, 'Gesendete Nachricht')['id']}/fold",
|
||||
json={
|
||||
"expected_version": _binding(restored, "Gesendete Nachricht")["element"]["version"],
|
||||
"context": _ctx(matter["id"]),
|
||||
"fold": "evidence",
|
||||
},
|
||||
)
|
||||
ada.request(
|
||||
"PATCH",
|
||||
f"/api/v1/notes/{letter['id']}",
|
||||
json={
|
||||
"expected_version": _binding(restored, "Anschreiben")["element"]["version"],
|
||||
"document": document("Später geänderter Text"),
|
||||
"context": _ctx(matter["id"]),
|
||||
},
|
||||
)
|
||||
changed = _detail(ada, matter["id"])
|
||||
assert "Später geänderter Text" in _binding(changed, "Anschreiben")["element"]["excerpt"]
|
||||
asset = db.execute("SELECT id FROM media_assets WHERE element_id = %s", (plan["id"],)).fetchone()
|
||||
Path(os.environ["MEDIA_ROOT"], str(asset["id"])).write_bytes(PDF_D)
|
||||
fresh = _detail(ada, matter["id"])
|
||||
host = _binding(fresh, "Anschreiben")
|
||||
ada.request(
|
||||
"POST",
|
||||
f"/api/v1/elements/{letter['id']}/attachments/{account['id']}/detach",
|
||||
json={"expected_version": host["element"]["version"], "context": _ctx(matter["id"])},
|
||||
status=204,
|
||||
)
|
||||
current = _detail(ada, matter["id"])
|
||||
recorded = _binding(current, "Anschreiben")["correspondence"]["dispatches"][0]
|
||||
assert [item["title"] for item in recorded["items"] if item["role"] == "attachment"] == [
|
||||
"Rechnung 2023",
|
||||
"Lageplan",
|
||||
"Kontoauszug",
|
||||
]
|
||||
assert recorded["sent_on"] == "2026-03-12"
|
||||
assert _binding(current, "Anschreiben")["element"]["dates"]["document_on"] == "2026-02-01"
|
||||
plan_item = next(item for item in recorded["items"] if item["title"] == "Lageplan")
|
||||
content = ada.client.get(
|
||||
f"/api/v1/dispatches/{recorded['id']}/items/{plan_item['id']}/content",
|
||||
params={"context_kind": "matter", "context_id": matter["id"]},
|
||||
headers={
|
||||
"Origin": ORIGIN,
|
||||
"X-CSRF-Token": ada.csrf,
|
||||
"X-Scope-Kind": ada.scope["kind"],
|
||||
"X-Scope-Id": ada.scope["id"],
|
||||
},
|
||||
)
|
||||
assert content.status_code == 200
|
||||
assert content.content == PDF_B
|
||||
tree = ada.request("GET", f"/api/v1/matters/{matter['id']}/export-tree")
|
||||
nodes = list(_walk(tree["tree"]))
|
||||
selected = [node["id"] for node in nodes if node["kind"] in {"dispatch_item", "evidence"}]
|
||||
archive = _zip(ada, matter["id"], selected)
|
||||
names = archive.namelist()
|
||||
snapshot = next(
|
||||
name for name in names if "Anschreiben" in name and name.endswith("/Anlagen/Lageplan.pdf")
|
||||
)
|
||||
assert archive.read(snapshot) == PDF_B
|
||||
eml_name = next(name for name in names if name.endswith("nachricht.eml"))
|
||||
assert b"Fachlicher Zusatz" in archive.read(eml_name)
|
||||
assert archive.read(eml_name).count(b"lage.pdf") >= 2
|
||||
overview = archive.read("inhalt.md").decode("utf-8")
|
||||
assert "Gesicherte Versandfassung" in overview
|
||||
assert "Schreiben → Versand → Nachweis" in overview
|
||||
first_text = "\n".join(
|
||||
archive.read(name).decode("utf-8", errors="replace")
|
||||
for name in names
|
||||
if name.endswith((".md", ".txt", ".eml", ".json"))
|
||||
)
|
||||
assert "Ursprünglicher Text" in first_text
|
||||
assert "Später geänderter Text" not in first_text
|
||||
gap = ada.request(
|
||||
"POST",
|
||||
f"/api/v1/elements/{letter['id']}/dispatches",
|
||||
json={
|
||||
"expected_version": _binding(current, "Anschreiben")["element"]["version"],
|
||||
"context": _ctx(matter["id"]),
|
||||
"channel": "post",
|
||||
"sent_on": None,
|
||||
"counterpart": None,
|
||||
"attachment_element_ids": [invoice["id"]],
|
||||
"historical_gap": True,
|
||||
},
|
||||
status=201,
|
||||
)
|
||||
assert gap["provenance"] == "reconstructed"
|
||||
assert gap["completeness"] == "gap"
|
||||
assert gap["undated"] is True
|
||||
assert gap["sent_on"] is None
|
||||
assert all(item["source_state"] == "gap" for item in gap["items"])
|
||||
receipt = ada.request(
|
||||
"POST",
|
||||
"/api/v1/notes",
|
||||
json={
|
||||
"title": "Einlieferungsbeleg",
|
||||
"document": document("Eingeliefert am Schalter"),
|
||||
"context": _ctx(matter["id"]),
|
||||
"dates": {"document_on": "2026-03-20"},
|
||||
},
|
||||
status=201,
|
||||
)
|
||||
delivery = ada.request(
|
||||
"POST",
|
||||
"/api/v1/notes",
|
||||
json={
|
||||
"title": "Zustellbestätigung",
|
||||
"document": document("Zugestellt"),
|
||||
"context": _ctx(matter["id"]),
|
||||
"dates": {"document_on": "2026-03-28"},
|
||||
},
|
||||
status=201,
|
||||
)
|
||||
posted = ada.request(
|
||||
"POST",
|
||||
f"/api/v1/elements/{letter['id']}/dispatches",
|
||||
json={
|
||||
"expected_version": _binding(_detail(ada, matter["id"]), "Anschreiben")["element"]["version"],
|
||||
"context": _ctx(matter["id"]),
|
||||
"channel": "post",
|
||||
"sent_on": "2026-03-18",
|
||||
"counterpart": "Poststelle",
|
||||
"attachment_element_ids": [invoice["id"]],
|
||||
"evidence": [{"element_id": receipt["id"], "role": "submission", "fold": "keep"}],
|
||||
},
|
||||
status=201,
|
||||
)
|
||||
assert posted["evidence"][0]["role"] == "submission"
|
||||
assert "zugestellt" not in json.dumps(posted).lower()
|
||||
added = ada.request(
|
||||
"POST",
|
||||
f"/api/v1/dispatches/{posted['id']}/evidence",
|
||||
json={
|
||||
"expected_version": posted["version"],
|
||||
"context": _ctx(matter["id"]),
|
||||
"element_id": delivery["id"],
|
||||
"role": "delivery",
|
||||
"fold": "keep",
|
||||
},
|
||||
status=201,
|
||||
)
|
||||
assert added["role"] == "delivery"
|
||||
final = _detail(ada, matter["id"])
|
||||
sends = _binding(final, "Anschreiben")["correspondence"]["dispatches"]
|
||||
assert len(sends) == 3
|
||||
assert {item["channel"] for item in sends} == {"email", "post"}
|
||||
post_send = next(item for item in sends if item["sent_on"] == "2026-03-18")
|
||||
assert {item["role"] for item in post_send["evidence"]} == {"submission", "delivery"}
|
||||
ada.request(
|
||||
"POST",
|
||||
f"/api/v1/dispatches/{post_send['id']}/evidence/{delivery['id']}/detach",
|
||||
json={"expected_version": post_send["version"], "context": _ctx(matter["id"])},
|
||||
status=204,
|
||||
)
|
||||
final = _detail(ada, matter["id"])
|
||||
sends = _binding(final, "Anschreiben")["correspondence"]["dispatches"]
|
||||
post_send = next(item for item in sends if item["sent_on"] == "2026-03-18")
|
||||
assert {item["role"] for item in post_send["evidence"]} == {"submission"}
|
||||
assert _binding(final, "Zustellbestätigung")["correspondence"]["fold"] is None
|
||||
assert _binding(final, "Zustellbestätigung")["element"]["dates"]["document_on"] == "2026-03-28"
|
||||
ada.request(
|
||||
"PATCH",
|
||||
f"/api/v1/matters/{matter['id']}/content-order",
|
||||
json={"expected_version": final["version"], "mode": "date", "direction": "asc", "view": "chronology"},
|
||||
)
|
||||
viewed = _detail(ada, matter["id"])
|
||||
assert viewed["content_view"] == "chronology"
|
||||
assert viewed["content_order"] == "date"
|
||||
assert _binding(viewed, "Anschreiben")["chapter_id"] is None
|
||||
excerpt_tree = ada.request("GET", f"/api/v1/matters/{matter['id']}/export-tree")
|
||||
host_item = next(
|
||||
node["id"]
|
||||
for node in _walk(excerpt_tree["tree"])
|
||||
if node["kind"] == "dispatch_item" and node["title"] == "Anschreiben"
|
||||
)
|
||||
review = ada.request(
|
||||
"POST",
|
||||
f"/api/v1/matters/{matter['id']}/export/review",
|
||||
json={"selected": [host_item]},
|
||||
)
|
||||
assert any("Auszug dieses Versands" in item["message"] for item in review["notices"])
|
||||
whole = [node["id"] for node in _walk(excerpt_tree["tree"]) if node["id"].startswith("dispatch-item:") or node["id"].startswith("evidence:")]
|
||||
full = _zip(ada, matter["id"], whole)
|
||||
joined = "\n".join(full.read(name).decode("utf-8", errors="replace") for name in full.namelist() if name.endswith((".md", ".txt", ".eml", ".json")))
|
||||
assert "Ursprünglicher Text" in joined
|
||||
assert "Historische Fassung liegt nicht vor" in joined
|
||||
gaps = [name for name in full.namelist() if name.endswith("-luecke.txt")]
|
||||
assert gaps
|
||||
assert all("Später geänderter Text" not in full.read(name).decode("utf-8") for name in gaps)
|
||||
assert all(b"%PDF" not in full.read(name) for name in gaps)
|
||||
secured = next(
|
||||
name for name in full.namelist() if "Anschreiben" in name and name.endswith("/Anlagen/Lageplan.pdf")
|
||||
)
|
||||
assert full.read(secured) == PDF_B
|
||||
|
||||
|
||||
def test_locked_parts_and_readers_stay_outside(client, db):
|
||||
ada = Actor(client, "ada-sperre@example.test", "Ada Sperre")
|
||||
ben = Actor(client, "ben-sperre@example.test", "Ben Sperre")
|
||||
register(db, ada.email, ada.name)
|
||||
register(db, ben.email, ben.name)
|
||||
ada.login()
|
||||
case = ada.request("POST", "/api/v1/cases", json={"title": "Geteilte Akte"}, status=201)
|
||||
matter = ada.request("POST", "/api/v1/matters", json={"title": "Geteilter Vorgang"}, status=201)
|
||||
ada.request("POST", f"/api/v1/matters/{matter['id']}/case-links", json={"case_id": case["id"]}, status=201)
|
||||
letter = ada.request(
|
||||
"POST",
|
||||
"/api/v1/notes",
|
||||
json={"title": "Sichtbares Schreiben", "document": document("Sichtbar"), "context": _ctx(matter["id"])},
|
||||
status=201,
|
||||
)
|
||||
secret = ada.request(
|
||||
"POST",
|
||||
"/api/v1/notes",
|
||||
json={"title": "Geheime AnlageXQ", "document": document("Nicht zeigen"), "context": _ctx(matter["id"])},
|
||||
status=201,
|
||||
)
|
||||
proof = ada.request(
|
||||
"POST",
|
||||
"/api/v1/notes",
|
||||
json={"title": "Geheimer NachweisXQ", "document": document("Auch nicht"), "context": _ctx(matter["id"])},
|
||||
status=201,
|
||||
)
|
||||
detail = _detail(ada, matter["id"])
|
||||
ada.request(
|
||||
"POST",
|
||||
f"/api/v1/elements/{letter['id']}/attachments",
|
||||
json={
|
||||
"expected_version": _binding(detail, "Sichtbares Schreiben")["element"]["version"],
|
||||
"context": _ctx(matter["id"]),
|
||||
"attachment_element_ids": [secret["id"]],
|
||||
"fold": "keep",
|
||||
},
|
||||
status=201,
|
||||
)
|
||||
sent = ada.request(
|
||||
"POST",
|
||||
f"/api/v1/elements/{letter['id']}/dispatches",
|
||||
json={
|
||||
"expected_version": _binding(_detail(ada, matter["id"]), "Sichtbares Schreiben")["element"]["version"],
|
||||
"context": _ctx(matter["id"]),
|
||||
"channel": "other",
|
||||
"sent_on": "2026-04-01",
|
||||
"attachment_element_ids": [secret["id"]],
|
||||
"evidence": [{"element_id": proof["id"], "role": "other", "fold": "keep"}],
|
||||
},
|
||||
status=201,
|
||||
)
|
||||
grant(ada, case["id"], ben.email, edit=False, share=False)
|
||||
ada.request(
|
||||
"PUT",
|
||||
"/api/v1/exceptions",
|
||||
json={
|
||||
"resource_kind": "element",
|
||||
"resource_id": secret["id"],
|
||||
"context": {"kind": "case", "id": case["id"]},
|
||||
"remove_read": True,
|
||||
},
|
||||
)
|
||||
ada.request(
|
||||
"PUT",
|
||||
"/api/v1/exceptions",
|
||||
json={
|
||||
"resource_kind": "element",
|
||||
"resource_id": proof["id"],
|
||||
"context": {"kind": "case", "id": case["id"]},
|
||||
"remove_read": True,
|
||||
},
|
||||
)
|
||||
ben.login()
|
||||
page = {"kind": "case", "id": case["id"]}
|
||||
visible = _detail(ben, matter["id"], page)
|
||||
blob = json.dumps(visible)
|
||||
assert "Geheime AnlageXQ" not in blob
|
||||
assert "Geheimer NachweisXQ" not in blob
|
||||
assert "Nicht zeigen" not in blob
|
||||
host = _binding(visible, "Sichtbares Schreiben")
|
||||
assert host["correspondence"]["attachments"] == []
|
||||
assert host["correspondence"]["dispatches"][0]["evidence"] == []
|
||||
ben.request(
|
||||
"POST",
|
||||
f"/api/v1/elements/{letter['id']}/attachments",
|
||||
json={
|
||||
"expected_version": host["element"]["version"],
|
||||
"context": page,
|
||||
"placement": _ctx(matter["id"]),
|
||||
"attachment_element_ids": [letter["id"]],
|
||||
"fold": "keep",
|
||||
},
|
||||
status=403,
|
||||
)
|
||||
ben.request(
|
||||
"POST",
|
||||
f"/api/v1/dispatches/{sent['id']}/correct",
|
||||
json={"expected_version": sent["version"], "context": page, "placement": _ctx(matter["id"]), "counterpart": "Fremd"},
|
||||
status=403,
|
||||
)
|
||||
ada.login()
|
||||
ada.request(
|
||||
"POST",
|
||||
f"/api/v1/elements/{letter['id']}/attachments",
|
||||
json={
|
||||
"expected_version": _binding(_detail(ada, matter["id"]), "Sichtbares Schreiben")["element"]["version"],
|
||||
"context": _ctx(matter["id"]),
|
||||
"attachment_element_ids": ["00000000-0000-4000-8000-000000000099"],
|
||||
"fold": "keep",
|
||||
},
|
||||
status=404,
|
||||
)
|
||||
@@ -0,0 +1,47 @@
|
||||
"""An entry title can be renamed without touching the document body."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from tests.support import Actor, document, register
|
||||
|
||||
|
||||
def test_element_title_can_be_renamed(client, db):
|
||||
ada = Actor(client, "ada-titel@example.test", "Ada Titel")
|
||||
register(db, ada.email, ada.name)
|
||||
ada.login()
|
||||
matter = ada.request("POST", "/api/v1/matters", json={"title": "Vorgang"}, status=201)
|
||||
ada.request(
|
||||
"POST",
|
||||
"/api/v1/notes",
|
||||
json={
|
||||
"title": "Alter Titel",
|
||||
"document": document("Text"),
|
||||
"context": {"kind": "matter", "id": matter["id"]},
|
||||
},
|
||||
status=201,
|
||||
)
|
||||
detail = ada.request("GET", f"/api/v1/matters/{matter['id']}")
|
||||
element = detail["bindings"][0]["element"]
|
||||
renamed = ada.request(
|
||||
"PATCH",
|
||||
f"/api/v1/elements/{element['id']}/title",
|
||||
json={
|
||||
"expected_version": element["version"],
|
||||
"title": "Neuer Titel",
|
||||
"context": {"kind": "matter", "id": matter["id"]},
|
||||
},
|
||||
)
|
||||
assert renamed["title"] == "Neuer Titel"
|
||||
assert renamed["version"] == element["version"] + 1
|
||||
shown = ada.request("GET", f"/api/v1/matters/{matter['id']}")
|
||||
assert shown["bindings"][0]["element"]["title"] == "Neuer Titel"
|
||||
ada.request(
|
||||
"PATCH",
|
||||
f"/api/v1/elements/{element['id']}/title",
|
||||
json={
|
||||
"expected_version": renamed["version"],
|
||||
"title": " ",
|
||||
"context": {"kind": "matter", "id": matter["id"]},
|
||||
},
|
||||
status=422,
|
||||
)
|
||||
+297
-10
@@ -85,6 +85,8 @@ def _links_resolve(archive: zipfile.ZipFile) -> None:
|
||||
names = set(archive.namelist())
|
||||
for chunk in html.split('href="')[1:]:
|
||||
href = unquote(chunk.split('"', 1)[0])
|
||||
if href.startswith("#"):
|
||||
continue
|
||||
assert href in names, href
|
||||
for name in archive.namelist():
|
||||
if not name.endswith(".md"):
|
||||
@@ -93,7 +95,7 @@ def _links_resolve(archive: zipfile.ZipFile) -> None:
|
||||
base = name.rsplit("/", 1)[0] + "/" if "/" in name else ""
|
||||
for chunk in text.split("](")[1:]:
|
||||
href = unquote(chunk.split(")", 1)[0])
|
||||
if href.startswith("http"):
|
||||
if href.startswith("http") or href.startswith("#"):
|
||||
continue
|
||||
target = urljoin(base, href)
|
||||
assert target in names, (name, href, target)
|
||||
@@ -357,8 +359,7 @@ def test_handover_package_follows_the_confirmed_selection(client, db, monkeypatc
|
||||
names = archive.namelist()
|
||||
assert "index.html" in names and "inhalt.md" in names
|
||||
assert any(name.startswith("01 Vertrag/") for name in names)
|
||||
schrift_names = [name for name in names if name.startswith("02 Schrift/")]
|
||||
assert schrift_names == ["02 Schrift/schreiben.pdf"]
|
||||
assert any("02 Schrift/01 Schreiben-Datei/Schreiben-Datei.pdf" in name.replace("\\", "/") for name in names)
|
||||
assert any("Nebenpunkt" in name and name.endswith("Teilnotiz.md") for name in names)
|
||||
mail_names = [name for name in names if "Schreiben mit Anlagen" in name]
|
||||
assert any(name.endswith("/nachricht.eml") for name in mail_names)
|
||||
@@ -371,7 +372,7 @@ def test_handover_package_follows_the_confirmed_selection(client, db, monkeypatc
|
||||
assert "Gespiegelte Anlage" not in whole
|
||||
assert "Fremdtext" not in whole
|
||||
assert "bleibt Bestandteil" in whole
|
||||
note_file = next(name for name in names if name.endswith("/Vertragnotiz.md"))
|
||||
note_file = next(name for name in names if name.endswith("/01 Vertragnotiz/Vertragnotiz.md"))
|
||||
annotation_file = next(name for name in names if "Anmerkung zu Vertragnotiz" in name)
|
||||
assert "Kontextvermerk speziell" not in archive.read(note_file).decode("utf-8")
|
||||
assert "Kontextvermerk speziell" in archive.read(annotation_file).decode("utf-8")
|
||||
@@ -761,14 +762,18 @@ def test_nested_chapter_export_keeps_path_and_complete_mail(client, db, monkeypa
|
||||
response = _post_zip(ada, matter["id"], body)
|
||||
assert response.status_code == 200, response.text
|
||||
names = _archive(response.content).namelist()
|
||||
heating = next(name for name in names if name.endswith("/heiz.pdf"))
|
||||
assert heating.startswith(
|
||||
"01 Nebenkostenabrechnung 2025/02 Übermittelte Abrechnungsunterlagen/01 Einzelbelege/"
|
||||
)
|
||||
assert any(
|
||||
name.startswith("01 Nebenkostenabrechnung 2025/01 ") and "Antwort des Vermieters" in name
|
||||
heating = next(
|
||||
name
|
||||
for name in names
|
||||
if name.endswith("/Heizkostenbeleg.pdf") and "Einzelbelege" in name and "Heizkostenbeleg" in name
|
||||
)
|
||||
normalized = heating.replace("\\", "/")
|
||||
assert "Nebenkostenabrechnung 2025" in normalized
|
||||
assert "Übermittelte Abrechnungsunterlagen" in normalized
|
||||
assert "Einzelbelege/" in normalized
|
||||
assert "Heizkostenbeleg/" in normalized
|
||||
assert normalized.endswith("/Heizkostenbeleg.pdf")
|
||||
assert any("Nebenkostenabrechnung 2025" in name and "Antwort des Vermieters" in name for name in names)
|
||||
assert not any("Hausmeister" in name or name.endswith("/haus.pdf") for name in names)
|
||||
assert not any(name.startswith("02 ") and "Nicht" in name for name in names)
|
||||
assert any("Antwort des Vermieters" in name and name.endswith("/anlagen/lage.pdf") for name in names)
|
||||
@@ -777,3 +782,285 @@ def test_nested_chapter_export_keeps_path_and_complete_mail(client, db, monkeypa
|
||||
assert overview.index("Anschreiben") < overview.index("Heizkostenbeleg")
|
||||
assert "Hausmeisterbeleg" not in overview
|
||||
assert "Ausgelassen" not in overview
|
||||
|
||||
|
||||
def test_chapter_entries_share_one_numbering_sequence(client, db, monkeypatch):
|
||||
ada = Actor(client, "ada-numbering@example.test", "Ada Numbering")
|
||||
register(db, ada.email, ada.name)
|
||||
ada.login()
|
||||
matter = ada.request("POST", "/api/v1/matters", json={"title": "Nummernfolge"}, status=201)
|
||||
chapter = ada.request(
|
||||
"POST",
|
||||
f"/api/v1/matters/{matter['id']}/chapters",
|
||||
json={"title": "Post"},
|
||||
status=201,
|
||||
)
|
||||
ada.request(
|
||||
"POST",
|
||||
"/api/v1/notes",
|
||||
json={
|
||||
"title": "Erste Notiz",
|
||||
"document": document("Notiztext"),
|
||||
"context": {"kind": "matter", "id": matter["id"]},
|
||||
"chapter_id": chapter["id"],
|
||||
},
|
||||
status=201,
|
||||
)
|
||||
mailbox = ada.request(
|
||||
"POST",
|
||||
"/api/v1/connectors",
|
||||
json={
|
||||
"kind": "imap",
|
||||
"name": "Postfach",
|
||||
"host": "mail.example.test",
|
||||
"username": "ada",
|
||||
"password": "secret-pass",
|
||||
},
|
||||
status=201,
|
||||
)
|
||||
raw = _eml("<nummern@example.test>", "Mailtext", [("lage.pdf", PDF_A)])
|
||||
ada.request(
|
||||
"POST",
|
||||
"/api/v1/external-refs",
|
||||
json={
|
||||
"title": "Zweite E-Mail",
|
||||
"source": "imap",
|
||||
"external_id": "<nummern@example.test>",
|
||||
"context": {"kind": "matter", "id": matter["id"]},
|
||||
"chapter_id": chapter["id"],
|
||||
"detail": {"connector_id": mailbox["id"], "mailbox": "INBOX", "uid": 3},
|
||||
},
|
||||
status=201,
|
||||
)
|
||||
ada.request(
|
||||
"POST",
|
||||
"/api/v1/files",
|
||||
data={
|
||||
"title": "Drittes Dokument",
|
||||
"context_kind": "matter",
|
||||
"context_id": matter["id"],
|
||||
"chapter_id": chapter["id"],
|
||||
},
|
||||
files={"upload": ("drittes.pdf", PDF_C, "application/pdf")},
|
||||
status=201,
|
||||
)
|
||||
monkeypatch.setattr("app.retrieval.pull_rfc822", lambda *args, **kwargs: raw)
|
||||
tree = ada.request("GET", f"/api/v1/matters/{matter['id']}/export-tree")["tree"]
|
||||
exportable = {"binding", "annotation", "attachment", "dispatch_item", "evidence"}
|
||||
selected = [node["id"] for node in _walk(tree) if node["exportable"] and node["kind"] in exportable]
|
||||
response = _post_zip(ada, matter["id"], {"context": {"kind": "matter", "id": matter["id"]}, "selected": selected})
|
||||
assert response.status_code == 200, response.text
|
||||
names = [name.replace("\\", "/") for name in _archive(response.content).namelist()]
|
||||
assert any(name.endswith("01 Post/01 Erste Notiz/Erste Notiz.md") for name in names)
|
||||
assert any("01 Post/02 Zweite E-Mail/nachricht.eml" in name for name in names)
|
||||
assert any(name.endswith("01 Post/03 Drittes Dokument/Drittes Dokument.pdf") for name in names)
|
||||
|
||||
|
||||
def test_correspondence_attachments_stay_under_each_host_in_one_chapter(client, db):
|
||||
ada = Actor(client, "ada-host-bundle@example.test", "Ada Host Bundle")
|
||||
register(db, ada.email, ada.name)
|
||||
ada.login()
|
||||
matter = ada.request("POST", "/api/v1/matters", json={"title": "Gemeinsames Kapitel"}, status=201)
|
||||
chapter = ada.request(
|
||||
"POST",
|
||||
f"/api/v1/matters/{matter['id']}/chapters",
|
||||
json={"title": "Schriftwechsel"},
|
||||
status=201,
|
||||
)
|
||||
first = ada.request(
|
||||
"POST",
|
||||
"/api/v1/notes",
|
||||
json={
|
||||
"title": "Erstes Schreiben",
|
||||
"document": document("Text eins"),
|
||||
"context": {"kind": "matter", "id": matter["id"]},
|
||||
"chapter_id": chapter["id"],
|
||||
},
|
||||
status=201,
|
||||
)
|
||||
second = ada.request(
|
||||
"POST",
|
||||
"/api/v1/notes",
|
||||
json={
|
||||
"title": "Zweites Schreiben",
|
||||
"document": document("Text zwei"),
|
||||
"context": {"kind": "matter", "id": matter["id"]},
|
||||
"chapter_id": chapter["id"],
|
||||
},
|
||||
status=201,
|
||||
)
|
||||
att_a1 = ada.request(
|
||||
"POST",
|
||||
"/api/v1/files",
|
||||
data={"title": "Anlage A1", "context_kind": "matter", "context_id": matter["id"]},
|
||||
files={"upload": ("a1.pdf", PDF_A, "application/pdf")},
|
||||
status=201,
|
||||
)
|
||||
att_a2 = ada.request(
|
||||
"POST",
|
||||
"/api/v1/files",
|
||||
data={"title": "Anlage A2", "context_kind": "matter", "context_id": matter["id"]},
|
||||
files={"upload": ("a2.pdf", PDF_B, "application/pdf")},
|
||||
status=201,
|
||||
)
|
||||
att_b1 = ada.request(
|
||||
"POST",
|
||||
"/api/v1/files",
|
||||
data={"title": "Anlage B1", "context_kind": "matter", "context_id": matter["id"]},
|
||||
files={"upload": ("b1.pdf", PDF_C, "application/pdf")},
|
||||
status=201,
|
||||
)
|
||||
att_b2 = ada.request(
|
||||
"POST",
|
||||
"/api/v1/files",
|
||||
data={"title": "Anlage B2", "context_kind": "matter", "context_id": matter["id"]},
|
||||
files={"upload": ("a1.pdf", PDF_A, "application/pdf")},
|
||||
status=201,
|
||||
)
|
||||
receipt = ada.request(
|
||||
"POST",
|
||||
"/api/v1/notes",
|
||||
json={
|
||||
"title": "Einlieferungsbeleg",
|
||||
"document": document("Eingeliefert"),
|
||||
"context": {"kind": "matter", "id": matter["id"]},
|
||||
"dates": {"document_on": "2026-04-01"},
|
||||
},
|
||||
status=201,
|
||||
)
|
||||
detail = ada.request("GET", f"/api/v1/matters/{matter['id']}")
|
||||
host_a = next(item for item in detail["bindings"] if item["element"]["title"] == "Erstes Schreiben")
|
||||
host_b = next(item for item in detail["bindings"] if item["element"]["title"] == "Zweites Schreiben")
|
||||
ada.request(
|
||||
"POST",
|
||||
f"/api/v1/elements/{first['id']}/attachments",
|
||||
json={
|
||||
"expected_version": host_a["element"]["version"],
|
||||
"context": {"kind": "matter", "id": matter["id"]},
|
||||
"attachment_element_ids": [att_a1["id"], att_a2["id"]],
|
||||
"fold": "attachment",
|
||||
},
|
||||
status=201,
|
||||
)
|
||||
ada.request(
|
||||
"POST",
|
||||
f"/api/v1/elements/{second['id']}/attachments",
|
||||
json={
|
||||
"expected_version": host_b["element"]["version"],
|
||||
"context": {"kind": "matter", "id": matter["id"]},
|
||||
"attachment_element_ids": [att_b1["id"], att_b2["id"]],
|
||||
"fold": "attachment",
|
||||
},
|
||||
status=201,
|
||||
)
|
||||
host_a = next(
|
||||
item for item in ada.request("GET", f"/api/v1/matters/{matter['id']}")["bindings"]
|
||||
if item["element"]["title"] == "Erstes Schreiben"
|
||||
)
|
||||
ada.request(
|
||||
"POST",
|
||||
f"/api/v1/elements/{first['id']}/dispatches",
|
||||
json={
|
||||
"expected_version": host_a["element"]["version"],
|
||||
"context": {"kind": "matter", "id": matter["id"]},
|
||||
"channel": "post",
|
||||
"sent_on": "2026-04-02",
|
||||
"counterpart": "Post",
|
||||
"attachment_element_ids": [],
|
||||
"evidence": [{"element_id": receipt["id"], "role": "submission", "fold": "keep"}],
|
||||
},
|
||||
status=201,
|
||||
)
|
||||
tree = ada.request("GET", f"/api/v1/matters/{matter['id']}/export-tree")["tree"]
|
||||
selected = [
|
||||
node["id"]
|
||||
for node in _walk(tree)
|
||||
if node["kind"] in {"binding", "attachment", "evidence"} and node["exportable"]
|
||||
]
|
||||
response = _post_zip(ada, matter["id"], {"context": {"kind": "matter", "id": matter["id"]}, "selected": selected})
|
||||
assert response.status_code == 200, response.text
|
||||
names = _archive(response.content).namelist()
|
||||
assert not any("anlagen-arbeitsstand" in name.lower() for name in names)
|
||||
first_paths = [name for name in names if "/01 Erstes Schreiben/Anlagen/" in name.replace("\\", "/")]
|
||||
second_paths = [name for name in names if "/02 Zweites Schreiben/Anlagen/" in name.replace("\\", "/")]
|
||||
assert sorted(name.rsplit("/", 1)[-1] for name in first_paths) == ["Anlage A1.pdf", "Anlage A2.pdf"]
|
||||
assert sorted(name.rsplit("/", 1)[-1] for name in second_paths) == ["Anlage B1.pdf", "Anlage B2.pdf"]
|
||||
assert any("/01 Erstes Schreiben/Belege/" in name.replace("\\", "/") for name in names)
|
||||
assert not any(name.replace("\\", "/").startswith("01 Schriftwechsel/2026-04") for name in names)
|
||||
overview_md = _archive(response.content).read("inhalt.md").decode("utf-8")
|
||||
overview_html = _archive(response.content).read("index.html").decode("utf-8")
|
||||
assert "#### Anlagen" in overview_md
|
||||
assert "Anlage A1" in overview_md
|
||||
assert "entry-group" in overview_html and "Anlagen" in overview_html
|
||||
|
||||
|
||||
def test_export_warns_when_assigned_attachment_is_not_shareable(client, db):
|
||||
ada = Actor(client, "ada-share-gap@example.test", "Ada Share Gap")
|
||||
register(db, ada.email, ada.name)
|
||||
ada.login()
|
||||
matter = ada.request("POST", "/api/v1/matters", json={"title": "Anlagenfreigabe"}, status=201)
|
||||
letter = ada.request(
|
||||
"POST",
|
||||
"/api/v1/notes",
|
||||
json={"title": "Schreiben", "document": document("Text"), "context": {"kind": "matter", "id": matter["id"]}},
|
||||
status=201,
|
||||
)
|
||||
open_att = ada.request(
|
||||
"POST",
|
||||
"/api/v1/files",
|
||||
data={"title": "Offene Anlage", "context_kind": "matter", "context_id": matter["id"]},
|
||||
files={"upload": ("offen.pdf", PDF_A, "application/pdf")},
|
||||
status=201,
|
||||
)
|
||||
closed_att = ada.request(
|
||||
"POST",
|
||||
"/api/v1/files",
|
||||
data={"title": "Gesperrte Anlage", "context_kind": "matter", "context_id": matter["id"]},
|
||||
files={"upload": ("gesperrt.pdf", PDF_B, "application/pdf")},
|
||||
status=201,
|
||||
)
|
||||
detail = ada.request("GET", f"/api/v1/matters/{matter['id']}")
|
||||
host = next(item for item in detail["bindings"] if item["element"]["title"] == "Schreiben")
|
||||
ada.request(
|
||||
"POST",
|
||||
f"/api/v1/elements/{letter['id']}/attachments",
|
||||
json={
|
||||
"expected_version": host["element"]["version"],
|
||||
"context": {"kind": "matter", "id": matter["id"]},
|
||||
"attachment_element_ids": [open_att["id"], closed_att["id"]],
|
||||
"fold": "attachment",
|
||||
},
|
||||
status=201,
|
||||
)
|
||||
ada.request(
|
||||
"PUT",
|
||||
"/api/v1/exceptions",
|
||||
json={
|
||||
"resource_kind": "element",
|
||||
"resource_id": closed_att["id"],
|
||||
"context": {"kind": "matter", "id": matter["id"]},
|
||||
"remove_share": True,
|
||||
},
|
||||
)
|
||||
tree = ada.request("GET", f"/api/v1/matters/{matter['id']}/export-tree")["tree"]
|
||||
selected = [node["id"] for node in _walk(tree) if node["exportable"] and node["kind"] in {"binding", "attachment"}]
|
||||
review = ada.request(
|
||||
"POST",
|
||||
f"/api/v1/matters/{matter['id']}/export/review",
|
||||
json={"context": {"kind": "matter", "id": matter["id"]}, "selected": selected},
|
||||
)
|
||||
assert review["ready"] is True
|
||||
assert any("nicht freigegeben" in item["message"] for item in review["notices"])
|
||||
response = _post_zip(
|
||||
ada,
|
||||
matter["id"],
|
||||
{"context": {"kind": "matter", "id": matter["id"]}, "selected": selected},
|
||||
)
|
||||
assert response.status_code == 200, response.text
|
||||
names = _archive(response.content).namelist()
|
||||
anlagen = [
|
||||
name
|
||||
for name in names
|
||||
if "Schreiben" in name and name.replace("\\", "/").endswith("/Anlagen/Offene Anlage.pdf")
|
||||
]
|
||||
assert len(anlagen) == 1
|
||||
@@ -0,0 +1,451 @@
|
||||
"""Granted readers see linked originals only through the owner's stored connector."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
import app.sources as sources
|
||||
from tests.support import ORIGIN, Actor, register
|
||||
|
||||
OWNER_TOKEN = "owner-paperless-token"
|
||||
GRANTEE_TOKEN = "grantee-paperless-token"
|
||||
OWNER_MAIL = "owner-postfach-geheim"
|
||||
GRANTEE_MAIL = "grantee-postfach-geheim"
|
||||
UNAVAILABLE = "Das Original ist über die Freigabe nicht abrufbar."
|
||||
|
||||
|
||||
class RecordingIMAP:
|
||||
logins: list[str] = []
|
||||
fetches: list[int] = []
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
pass
|
||||
|
||||
def login(self, username, secret):
|
||||
RecordingIMAP.logins.append(secret)
|
||||
return "OK", [b"logged"]
|
||||
|
||||
def list(self):
|
||||
return "OK", [b'(\\HasNoChildren) "/" "INBOX"']
|
||||
|
||||
def select(self, mailbox, readonly=False):
|
||||
return "OK", [b"5"]
|
||||
|
||||
def uid(self, command, *args):
|
||||
if command == "SEARCH":
|
||||
return "OK", [b""]
|
||||
uid = int(args[0])
|
||||
spec = " ".join(str(part) for part in args[1:])
|
||||
if "BODY.PEEK[]" in spec:
|
||||
RecordingIMAP.fetches.append(uid)
|
||||
raw = (
|
||||
f"From: Ada Beispiel <ada@example.test>\r\n"
|
||||
f"To: Kanzlei <kanzlei@example.test>\r\n"
|
||||
f"Subject: Nachricht {uid}\r\n"
|
||||
f"Date: Thu, 02 May 2024 08:00:00 +0000\r\n"
|
||||
f"Message-ID: <{uid}@example.test>\r\n"
|
||||
f"MIME-Version: 1.0\r\n"
|
||||
f'Content-Type: multipart/mixed; boundary="grenze"\r\n'
|
||||
f"\r\n"
|
||||
f"--grenze\r\n"
|
||||
f"Content-Type: text/plain; charset=utf-8\r\n"
|
||||
f"\r\n"
|
||||
f"Bitte die Einwendung pruefen.\r\n"
|
||||
f"--grenze\r\n"
|
||||
f"Content-Type: application/pdf\r\n"
|
||||
f'Content-Disposition: attachment; filename="einwendung.pdf"\r\n'
|
||||
f"\r\n"
|
||||
f"%PDF\r\n"
|
||||
f"--grenze--\r\n"
|
||||
).encode()
|
||||
return "OK", [(b"rfc822", raw)]
|
||||
return "OK", [(b"body", b"From: Ada\r\n"), b")"]
|
||||
|
||||
def logout(self):
|
||||
return "BYE", [b""]
|
||||
|
||||
|
||||
def _reset_imap():
|
||||
RecordingIMAP.logins = []
|
||||
RecordingIMAP.fetches = []
|
||||
|
||||
|
||||
def _paperless(actor: Actor, token: str, name: str) -> str:
|
||||
return actor.request(
|
||||
"POST",
|
||||
"/api/v1/connectors",
|
||||
json={"kind": "paperless", "name": name, "base_url": "https://paper.example.test", "token": token},
|
||||
status=201,
|
||||
)["id"]
|
||||
|
||||
|
||||
def _mailbox(actor: Actor, password: str, name: str) -> str:
|
||||
return actor.request(
|
||||
"POST",
|
||||
"/api/v1/connectors",
|
||||
json={
|
||||
"kind": "imap",
|
||||
"name": name,
|
||||
"host": "imap.example.test",
|
||||
"port": 993,
|
||||
"username": f"{name}@example.test",
|
||||
"password": password,
|
||||
"security": "ssl",
|
||||
},
|
||||
status=201,
|
||||
)["id"]
|
||||
|
||||
|
||||
def _raw(actor: Actor, path: str):
|
||||
return actor.client.get(
|
||||
path,
|
||||
headers={
|
||||
"Origin": ORIGIN,
|
||||
"X-CSRF-Token": actor.csrf,
|
||||
"X-Scope-Kind": actor.scope["kind"],
|
||||
"X-Scope-Id": actor.scope["id"],
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def _grant(actor: Actor, kind: str, resource_id: str, email: str, **flags):
|
||||
body = {"email": email, "can_read": True, "can_edit": False, "can_share": False, "use_owner_sources": False}
|
||||
body.update(flags)
|
||||
return actor.request("POST", f"/api/v1/{kind}/{resource_id}/grants", json=body, status=201)
|
||||
|
||||
|
||||
def _events(db):
|
||||
return db.execute(
|
||||
"""
|
||||
SELECT action, result, detail
|
||||
FROM domain_events
|
||||
WHERE action = 'source_read_mediated'
|
||||
ORDER BY occurred_at, id
|
||||
"""
|
||||
).fetchall()
|
||||
|
||||
|
||||
def test_owner_alone_sets_source_access_and_a_delegate_cannot_change_it(client, db):
|
||||
ada = Actor(client, "ada-flag@example.test", "Ada Flag")
|
||||
ben = Actor(client, "ben-flag@example.test", "Ben Flag")
|
||||
cleo = Actor(client, "cleo-flag@example.test", "Cleo Flag")
|
||||
register(db, ada.email, ada.name)
|
||||
register(db, ben.email, ben.name)
|
||||
register(db, cleo.email, cleo.name)
|
||||
ada.login()
|
||||
case = ada.request("POST", "/api/v1/cases", json={"title": "Streit"}, status=201)
|
||||
_grant(ada, "cases", case["id"], ben.email, can_share=True, use_owner_sources=True)
|
||||
ada_view = ada.request("GET", f"/api/v1/cases/{case['id']}")
|
||||
ben_grant = next(item for item in ada_view["grants"] if item["email"] == ben.email)
|
||||
assert ben_grant["use_owner_sources"] is True
|
||||
|
||||
ben.login()
|
||||
_grant(ben, "cases", case["id"], cleo.email, use_owner_sources=True)
|
||||
ada.login()
|
||||
after_delegate = ada.request("GET", f"/api/v1/cases/{case['id']}")
|
||||
cleo_grant = next(item for item in after_delegate["grants"] if item["email"] == cleo.email)
|
||||
assert cleo_grant["use_owner_sources"] is False
|
||||
|
||||
_grant(ada, "cases", case["id"], cleo.email, use_owner_sources=True)
|
||||
ben.login()
|
||||
_grant(ben, "cases", case["id"], cleo.email, can_share=True, use_owner_sources=False)
|
||||
ada.login()
|
||||
kept = ada.request("GET", f"/api/v1/cases/{case['id']}")
|
||||
cleo_grant = next(item for item in kept["grants"] if item["email"] == cleo.email)
|
||||
assert cleo_grant["can_share"] is True
|
||||
assert cleo_grant["use_owner_sources"] is True
|
||||
|
||||
_grant(ada, "cases", case["id"], cleo.email, use_owner_sources=False)
|
||||
cleared = ada.request("GET", f"/api/v1/cases/{case['id']}")
|
||||
cleo_grant = next(item for item in cleared["grants"] if item["email"] == cleo.email)
|
||||
assert cleo_grant["use_owner_sources"] is False
|
||||
|
||||
|
||||
def test_grantee_reads_linked_originals_only_through_the_owner(client, db, monkeypatch):
|
||||
calls = []
|
||||
|
||||
def fake_file(base, token, path, max_bytes=40 * 1024 * 1024):
|
||||
calls.append({"token": token, "path": path})
|
||||
if path.endswith("/preview/"):
|
||||
return (b"%PDF-1.4\nverknuepft\n", "application/pdf", "vertrag.pdf")
|
||||
return None
|
||||
|
||||
def fake_get(base, token, path, params):
|
||||
calls.append({"token": token, "path": path, "query": params.get("query")})
|
||||
if token == OWNER_TOKEN:
|
||||
return {"count": 1, "results": [{"id": 15, "title": "Geheimes Archivdokument", "created": "2026-01-01"}]}
|
||||
return {"count": 0, "results": []}
|
||||
|
||||
monkeypatch.setattr(sources, "_paperless_file", fake_file)
|
||||
monkeypatch.setattr(sources, "_paperless_get", fake_get)
|
||||
monkeypatch.setattr(sources, "_paperless_metadata", lambda *args, **kwargs: None)
|
||||
monkeypatch.setattr(sources.imaplib, "IMAP4_SSL", RecordingIMAP)
|
||||
_reset_imap()
|
||||
|
||||
ada = Actor(client, "ada-quelle@example.test", "Ada Quelle")
|
||||
ben = Actor(client, "ben-quelle@example.test", "Ben Quelle")
|
||||
register(db, ada.email, ada.name)
|
||||
register(db, ben.email, ben.name)
|
||||
ada.login()
|
||||
paper = _paperless(ada, OWNER_TOKEN, "Ada Archiv")
|
||||
mailbox = _mailbox(ada, OWNER_MAIL, "Ada Post")
|
||||
case = ada.request("POST", "/api/v1/cases", json={"title": "Akte"}, status=201)
|
||||
matter = ada.request("POST", "/api/v1/matters", json={"title": "Vorgang"}, status=201)
|
||||
other = ada.request("POST", "/api/v1/matters", json={"title": "Fremder Vorgang"}, status=201)
|
||||
document = ada.request(
|
||||
"POST",
|
||||
"/api/v1/external-refs",
|
||||
json={
|
||||
"title": "Vertrag",
|
||||
"source": "paperless",
|
||||
"external_id": "15",
|
||||
"context": {"kind": "case", "id": case["id"]},
|
||||
"detail": {"connector_id": paper, "correspondent": "Hausverwaltung"},
|
||||
},
|
||||
status=201,
|
||||
)
|
||||
letter = ada.request(
|
||||
"POST",
|
||||
"/api/v1/external-refs",
|
||||
json={
|
||||
"title": "Einwendung",
|
||||
"source": "imap",
|
||||
"external_id": "<2@example.test>",
|
||||
"context": {"kind": "matter", "id": matter["id"]},
|
||||
"detail": {
|
||||
"connector_id": mailbox,
|
||||
"mailbox": "INBOX",
|
||||
"uid": 2,
|
||||
"direction": "in",
|
||||
"message_from": "Hausverwaltung",
|
||||
},
|
||||
},
|
||||
status=201,
|
||||
)
|
||||
owner_file = _raw(ada, f"/api/v1/external-refs/{document['id']}/content?context_kind=case&context_id={case['id']}")
|
||||
assert owner_file.status_code == 200
|
||||
assert owner_file.content.startswith(b"%PDF")
|
||||
assert calls[-1]["token"] == OWNER_TOKEN
|
||||
assert "/api/documents/15/" in calls[-1]["path"]
|
||||
owner_mail = ada.request(
|
||||
"GET",
|
||||
f"/api/v1/external-refs/{letter['id']}/mail",
|
||||
params={"context_kind": "matter", "context_id": matter["id"]},
|
||||
)
|
||||
assert "Einwendung" in owner_mail["text"]
|
||||
assert OWNER_MAIL in RecordingIMAP.logins
|
||||
calls.clear()
|
||||
_reset_imap()
|
||||
|
||||
ben.login()
|
||||
_paperless(ben, GRANTEE_TOKEN, "Ben Archiv")
|
||||
_mailbox(ben, GRANTEE_MAIL, "Ben Post")
|
||||
ada.login()
|
||||
_grant(ada, "cases", case["id"], ben.email)
|
||||
_grant(ada, "matters", matter["id"], ben.email)
|
||||
_grant(ada, "matters", other["id"], ben.email, use_owner_sources=True)
|
||||
|
||||
ben.login()
|
||||
shown = ben.request("GET", f"/api/v1/matters/{matter['id']}")
|
||||
visible = next(item for item in shown["bindings"] if item["element"]["title"] == "Einwendung")
|
||||
detail = visible["element"]["external"]["detail"]
|
||||
assert detail["direction"] == "in"
|
||||
assert detail["message_from"] == "Hausverwaltung"
|
||||
assert "connector_id" not in detail
|
||||
assert "mailbox" not in detail
|
||||
assert "uid" not in detail
|
||||
assert "external_id" not in visible["element"]["external"]
|
||||
dumped = json.dumps(shown)
|
||||
assert OWNER_MAIL not in dumped
|
||||
assert OWNER_TOKEN not in dumped
|
||||
assert "imap.example.test" not in dumped
|
||||
assert mailbox not in dumped
|
||||
|
||||
hidden = ben.request(
|
||||
"GET",
|
||||
f"/api/v1/external-refs/{document['id']}/content",
|
||||
params={"context_kind": "case", "context_id": case["id"], "document": "999"},
|
||||
status=422,
|
||||
)
|
||||
assert hidden["detail"] == UNAVAILABLE
|
||||
assert calls == []
|
||||
missed = ben.request(
|
||||
"GET",
|
||||
f"/api/v1/external-refs/{letter['id']}/mail",
|
||||
params={"context_kind": "matter", "context_id": matter["id"], "uid": "9", "mailbox": "Geheim"},
|
||||
status=422,
|
||||
)
|
||||
assert missed["detail"] == UNAVAILABLE
|
||||
assert RecordingIMAP.logins == []
|
||||
assert RecordingIMAP.fetches == []
|
||||
|
||||
ada.login()
|
||||
_grant(ada, "cases", case["id"], ben.email, use_owner_sources=True)
|
||||
_grant(ada, "matters", matter["id"], ben.email, use_owner_sources=True)
|
||||
ben.login()
|
||||
opened = _raw(
|
||||
ben,
|
||||
f"/api/v1/external-refs/{document['id']}/content?context_kind=case&context_id={case['id']}&document=999",
|
||||
)
|
||||
assert opened.status_code == 200
|
||||
assert opened.content.startswith(b"%PDF")
|
||||
assert opened.headers["x-content-type-options"] == "nosniff"
|
||||
assert opened.headers["cache-control"] == "private, no-store"
|
||||
assert opened.headers["referrer-policy"] == "no-referrer"
|
||||
assert calls == [{"token": OWNER_TOKEN, "path": "/api/documents/15/preview/"}]
|
||||
assert GRANTEE_TOKEN not in json.dumps(calls)
|
||||
search = ben.request("GET", "/api/v1/sources/paperless/documents", params={"q": "Geheim"})
|
||||
assert "Geheimes Archivdokument" not in json.dumps(search)
|
||||
assert all(item["token"] != OWNER_TOKEN for item in calls if "query" in item)
|
||||
|
||||
mail = ben.request(
|
||||
"GET",
|
||||
f"/api/v1/external-refs/{letter['id']}/mail",
|
||||
params={"context_kind": "matter", "context_id": matter["id"], "uid": "9", "connector_id": paper},
|
||||
)
|
||||
assert mail["text"] == "Bitte die Einwendung pruefen."
|
||||
assert mail["attachments"][0]["filename"] == "einwendung.pdf"
|
||||
assert RecordingIMAP.logins == [OWNER_MAIL]
|
||||
assert RecordingIMAP.fetches == [2]
|
||||
original = _raw(
|
||||
ben,
|
||||
f"/api/v1/external-refs/{letter['id']}/mail/original?context_kind=matter&context_id={matter['id']}",
|
||||
)
|
||||
assert original.status_code == 200
|
||||
assert b"Message-ID: <2@example.test>" in original.content
|
||||
attachment = _raw(
|
||||
ben,
|
||||
f"/api/v1/external-refs/{letter['id']}/mail/attachments/0?context_kind=matter&context_id={matter['id']}",
|
||||
)
|
||||
assert attachment.status_code == 200
|
||||
assert attachment.content.startswith(b"%PDF")
|
||||
assert attachment.headers["content-disposition"].startswith("inline;")
|
||||
assert GRANTEE_MAIL not in RecordingIMAP.logins
|
||||
page = ben.request("GET", f"/api/v1/matters/{matter['id']}/chronology")
|
||||
chronology = json.dumps(page)
|
||||
assert "source_read_mediated" in [item["action"] for item in page["items"]]
|
||||
assert "Verknüpftes Original gelesen" in [item["label"] for item in page["items"]]
|
||||
assert mailbox not in chronology
|
||||
assert OWNER_MAIL not in chronology
|
||||
|
||||
quiet = len(RecordingIMAP.logins)
|
||||
ben.request("GET", "/api/v1/sources/imap/mailboxes", params={"connector_id": mailbox}, status=404)
|
||||
ben.request(
|
||||
"GET",
|
||||
f"/api/v1/external-refs/{letter['id']}/mail",
|
||||
params={"context_kind": "matter", "context_id": other["id"]},
|
||||
status=404,
|
||||
)
|
||||
ada.login()
|
||||
ada.request(
|
||||
"PUT",
|
||||
"/api/v1/exceptions",
|
||||
json={
|
||||
"resource_kind": "element",
|
||||
"resource_id": letter["id"],
|
||||
"context": {"kind": "matter", "id": matter["id"]},
|
||||
"remove_read": True,
|
||||
},
|
||||
)
|
||||
grant_id = next(item["id"] for item in ada.request("GET", f"/api/v1/cases/{case['id']}")["grants"])
|
||||
ben.login()
|
||||
ben.request(
|
||||
"GET",
|
||||
f"/api/v1/external-refs/{letter['id']}/mail",
|
||||
params={"context_kind": "matter", "context_id": matter["id"]},
|
||||
status=404,
|
||||
)
|
||||
assert len(RecordingIMAP.logins) == quiet
|
||||
ada.login()
|
||||
ada.request("DELETE", f"/api/v1/grants/{grant_id}", status=204)
|
||||
ben.login()
|
||||
ben.request(
|
||||
"GET",
|
||||
f"/api/v1/external-refs/{document['id']}/content",
|
||||
params={"context_kind": "case", "context_id": case["id"]},
|
||||
status=404,
|
||||
)
|
||||
assert len(RecordingIMAP.logins) == quiet
|
||||
assert [item["token"] for item in calls if "query" not in item] == [OWNER_TOKEN]
|
||||
|
||||
rows = _events(db)
|
||||
blob = json.dumps(rows, default=str)
|
||||
assert OWNER_TOKEN not in blob
|
||||
assert OWNER_MAIL not in blob
|
||||
assert "Bitte die Einwendung" not in blob
|
||||
assert "imap.example.test" not in blob
|
||||
assert any(row["result"] == "ok" and row["detail"]["source"] == "paperless" for row in rows)
|
||||
assert any(row["result"] == "ok" and row["detail"]["connector_id"] == mailbox for row in rows)
|
||||
|
||||
|
||||
def test_deleted_or_foreign_connector_is_not_used(client, db, monkeypatch):
|
||||
calls = []
|
||||
monkeypatch.setattr(
|
||||
sources,
|
||||
"_paperless_file",
|
||||
lambda *args, **kwargs: calls.append("paperless") or (b"%PDF-1.4\n", "application/pdf", "x.pdf"),
|
||||
)
|
||||
monkeypatch.setattr(sources.imaplib, "IMAP4_SSL", RecordingIMAP)
|
||||
_reset_imap()
|
||||
|
||||
ada = Actor(client, "ada-weg@example.test", "Ada Weg")
|
||||
ben = Actor(client, "ben-weg@example.test", "Ben Weg")
|
||||
cleo = Actor(client, "cleo-weg@example.test", "Cleo Weg")
|
||||
register(db, ada.email, ada.name)
|
||||
register(db, ben.email, ben.name)
|
||||
register(db, cleo.email, cleo.name)
|
||||
ada.login()
|
||||
paper = _paperless(ada, OWNER_TOKEN, "Ada Archiv")
|
||||
ben.login()
|
||||
foreign = _mailbox(ben, GRANTEE_MAIL, "Ben Post")
|
||||
ada.login()
|
||||
matter = ada.request("POST", "/api/v1/matters", json={"title": "Vorgang"}, status=201)
|
||||
document = ada.request(
|
||||
"POST",
|
||||
"/api/v1/external-refs",
|
||||
json={
|
||||
"title": "Scan",
|
||||
"source": "paperless",
|
||||
"external_id": "15",
|
||||
"context": {"kind": "matter", "id": matter["id"]},
|
||||
"detail": {"connector_id": paper},
|
||||
},
|
||||
status=201,
|
||||
)
|
||||
foreign_mail = ada.request(
|
||||
"POST",
|
||||
"/api/v1/external-refs",
|
||||
json={
|
||||
"title": "Fremde Quelle",
|
||||
"source": "imap",
|
||||
"external_id": "<2@example.test>",
|
||||
"context": {"kind": "matter", "id": matter["id"]},
|
||||
"detail": {"connector_id": foreign, "mailbox": "INBOX", "uid": 2},
|
||||
},
|
||||
status=201,
|
||||
)
|
||||
_grant(ada, "matters", matter["id"], cleo.email, use_owner_sources=True)
|
||||
ada.request("DELETE", f"/api/v1/connectors/{paper}", status=204)
|
||||
cleo.login()
|
||||
blocked = cleo.request(
|
||||
"GET",
|
||||
f"/api/v1/external-refs/{document['id']}/content",
|
||||
params={"context_kind": "matter", "context_id": matter["id"]},
|
||||
status=422,
|
||||
)
|
||||
assert blocked["detail"] == UNAVAILABLE
|
||||
assert "paper.example.test" not in blocked["detail"]
|
||||
assert calls == []
|
||||
refused = cleo.request(
|
||||
"GET",
|
||||
f"/api/v1/external-refs/{foreign_mail['id']}/mail",
|
||||
params={"context_kind": "matter", "context_id": matter["id"]},
|
||||
status=422,
|
||||
)
|
||||
assert refused["detail"] == UNAVAILABLE
|
||||
assert RecordingIMAP.logins == []
|
||||
rows = _events(db)
|
||||
assert rows
|
||||
assert all(row["result"] == "unavailable" for row in rows)
|
||||
assert OWNER_TOKEN not in json.dumps(rows, default=str)
|
||||
assert GRANTEE_MAIL not in json.dumps(rows, default=str)
|
||||
@@ -63,6 +63,8 @@ services:
|
||||
build:
|
||||
context: ./frontend
|
||||
dockerfile: Dockerfile
|
||||
args:
|
||||
VITE_TSUMUGU_ENV: development
|
||||
ports:
|
||||
- "${TSUMUGU_FRONTEND_PORT:-3094}:80"
|
||||
depends_on:
|
||||
|
||||
@@ -65,6 +65,8 @@ services:
|
||||
build:
|
||||
context: ./frontend
|
||||
dockerfile: Dockerfile
|
||||
args:
|
||||
VITE_TSUMUGU_ENV: production
|
||||
container_name: tsumugu-ui
|
||||
ports:
|
||||
- "${TSUMUGU_FRONTEND_PORT:-3007}:80"
|
||||
|
||||
@@ -0,0 +1,196 @@
|
||||
# Tsumugu – API-Referenz (Ist-Stand)
|
||||
|
||||
**Stand:** 18.10.2026. Erstellt im Code-Review aus `backend/app/main.py`, `api/routes.py`, `api/sources.py`, `api/export.py` und `api/correspondence.py`.
|
||||
|
||||
Diese Datei beschreibt die tatsächlich registrierten Endpunkte. Die Sollfassung steht in der [technischen Spezifikation, Abschnitt 6.2](TSUMUGU_TECHNICAL_SPEC.md). OpenAPI ist in allen Umgebungen abgeschaltet (`docs_url=None`, `openapi_url=None`). Diese Datei ist deshalb die einzige Übersicht. Sie wird bei jeder Routenänderung mitgepflegt.
|
||||
|
||||
## Gemeinsame Regeln
|
||||
|
||||
| Thema | Regel im Code |
|
||||
|---|---|
|
||||
| Sitzung | Cookie `__Host-jinkendo-session` (Produktion, HTTPS) bzw. `jinkendo-session` (Development über HTTP). Gültigkeit `SESSION_TTL_HOURS`, Default 336 h |
|
||||
| Schreibschutz | Alle Methoden außer GET/HEAD/OPTIONS unter `/api/` verlangen einen `Origin` aus `ALLOWED_ORIGINS` (Middleware) und den Header `X-CSRF-Token` der Session |
|
||||
| Datenraum | Fachrouten verlangen `X-Scope-Kind` (`personal` oder `organization`) und `X-Scope-Id`. Beide müssen mit dem in der Session bestätigten Raum übereinstimmen, die Mitgliedschaft wird je Request geprüft |
|
||||
| Handlungskontext | Lesend als Query `context_kind` und `context_id` (`case`/`matter` + UUID), schreibend als `context: {kind, id}` im JSON. Ohne Kontext gelten nur Owner und direkte Grants |
|
||||
| Eingaben | JSON ohne unbekannte Felder (`extra="forbid"`); Upload als Multipart |
|
||||
| Fehler | `application/problem+json` mit `type`, `title`, `status`, `detail`, `instance`, `code`. 401 keine Session, 403 fehlendes Recht bei sichtbarem Objekt, 404 unsichtbar oder nicht vorhanden, 409 Versionskonflikt, 422 ungültige Eingabe, 429 Login-Begrenzung, 503 Speicher nicht verfügbar |
|
||||
| Versionen | Ändernde Aufrufe tragen `expected_version` des geänderten Ankers (Akte, Vorgang, Element, Aufgabe, Frist). Kapitel- und Ordnungsänderungen erhöhen die Version des Behälters |
|
||||
| Listen | Antwort `{items, next_cursor}`. `next_cursor` ist außer in der Chronologie immer `null` |
|
||||
|
||||
Legende Spalte „Auth“: **–** öffentlich, **S** gültige Session, **S+R** Session und Datenraum-Header, **B** Betreiber (`is_superadmin`), **M** Verwalter des Raums. Alle Tabellen ohne Spalte „Auth“ verlangen **S+R**; die Objektrechte prüft danach die Rechteauswertung ([RECHTEMODELL_IST.md](RECHTEMODELL_IST.md)).
|
||||
|
||||
## Betrieb
|
||||
|
||||
| Methode | Pfad | Auth | Zweck |
|
||||
|---|---|---|---|
|
||||
| GET | `/api/health` | – | `{status, app}`; 503 bei DB-Fehler |
|
||||
| GET | `/health/live` | – | Prozess lebt |
|
||||
| GET | `/health/ready` | – | DB antwortet |
|
||||
|
||||
## Anmeldung, Session, Konten
|
||||
|
||||
| Methode | Pfad | Auth | Zweck |
|
||||
|---|---|---|---|
|
||||
| POST | `/api/v1/auth/login` | – | E-Mail, Passwort → Session-Sicht und Cookie. 8 Versuche je IP+E-Mail in 10 min (Prozessspeicher) |
|
||||
| POST | `/api/v1/auth/logout` | S | Session widerrufen, Cookie löschen, 204 |
|
||||
| GET | `/api/v1/auth/session` | S | Konto, bestätigter Datenraum, Räume, CSRF-Token, Epoche |
|
||||
| POST | `/api/v1/auth/session/scope` | S | Datenraum wechseln (`kind`, `id`); erhöht die Epoche |
|
||||
| GET | `/api/v1/auth/bootstrap` | – | `{available: true}`, solange kein Betreiber existiert, sonst 404 |
|
||||
| POST | `/api/v1/auth/bootstrap` | – | erstes Konto als Betreiber anlegen, nur ohne vorhandenen Betreiber |
|
||||
| GET | `/api/v1/auth/demo` | – | Beispielkonten; nur Development mit Datenbank `*_test` und `SEED_DEMO=true`, sonst 404 |
|
||||
| GET | `/api/v1/accounts` | S+R, B | aktive Betreiberkonten (`origin='operator'`) |
|
||||
| POST | `/api/v1/accounts` | S+R, B | Konto mit Passwort anlegen, erhält persönlichen Raum |
|
||||
| GET | `/api/v1/principals?email=` | S+R | aktives Konto per E-Mail auflösen (ID, Anzeigename) |
|
||||
| POST | `/api/v1/invitations` | S+R, M | Einladung in einen gemeinsamen Raum; Antwort enthält das Token einmalig. Keine Oberfläche |
|
||||
| POST | `/api/v1/invitations/{id}/accept` | – | Token, Anzeigename, Passwort → Konto, Mitgliedschaft, Session |
|
||||
|
||||
## Datenräume
|
||||
|
||||
| Methode | Pfad | Auth | Zweck |
|
||||
|---|---|---|---|
|
||||
| GET | `/api/v1/rooms` | S+R | wählbare Räume |
|
||||
| POST | `/api/v1/rooms` | S+R | gemeinsamen Raum anlegen, Anlegende Person wird Verwalter |
|
||||
| GET | `/api/v1/rooms/{id}/members` | S+R, M | Mitglieder |
|
||||
| POST | `/api/v1/rooms/{id}/members` | S+R, M | bestehendes Konto als `member` oder `manager` aufnehmen |
|
||||
| DELETE | `/api/v1/rooms/{id}/members/{subject_id}` | S+R, M | Mitgliedschaft beenden; letzter Verwalter bleibt. Keine Oberfläche |
|
||||
|
||||
## Akten
|
||||
|
||||
| Methode | Pfad | Zweck |
|
||||
|---|---|---|
|
||||
| GET | `/api/v1/cases` | lesbare Akten und Unterakten |
|
||||
| POST | `/api/v1/cases` | Akte anlegen (`title`, optional `parent_case_id`, `rights_mode`, `home_scope_id`) |
|
||||
| GET | `/api/v1/cases/{id}` | Akte mit Trail, Kapiteln, Unterakten, Vorgangsbaum, direkten Einbindungen, `contained` (Inhalte zugeordneter Vorgänge), Aufgaben, Fristen, Grants (für Freigebende) |
|
||||
| PATCH | `/api/v1/cases/{id}` | Titel, Status `open`/`closed` |
|
||||
| POST | `/api/v1/cases/{id}/delete` | Akte löschen (`deleted_at`); nur ohne Unterakten und Vorgangszuordnungen. Verlangt `edit` (siehe Review R-01) |
|
||||
| POST | `/api/v1/cases/{id}/grants` | Grant per E-Mail (`can_read`, `can_edit`, `can_share`) |
|
||||
| POST | `/api/v1/cases/{id}/chapters` | Kapitel anlegen, optional `parent_chapter_id`, `document_on` |
|
||||
| POST | `/api/v1/cases/{id}/chapters/order` | Geschwisterreihenfolge |
|
||||
| PATCH | `/api/v1/cases/{id}/content-order` | Ordnungsart `date`/`position`, Richtung |
|
||||
| POST | `/api/v1/cases/{id}/bindings/order` | eigene Reihenfolge der sichtbaren Einbindungen |
|
||||
| POST | `/api/v1/cases/{id}/bindings/chapters` | mehrere Einbindungen in ein Kapitel |
|
||||
| GET | `/api/v1/cases/{id}/course` | fachlicher Verlauf |
|
||||
| GET | `/api/v1/cases/{id}/chronology?cursor=` | Änderungsprotokoll, 40 Einträge je Seite |
|
||||
|
||||
## Vorgänge
|
||||
|
||||
| Methode | Pfad | Zweck |
|
||||
|---|---|---|
|
||||
| GET | `/api/v1/matters` | lesbare Vorgänge mit lesbaren Kontexten |
|
||||
| POST | `/api/v1/matters` | Vorgang oder Teilvorgang (`parent_matter_id`, `context`) |
|
||||
| GET | `/api/v1/matters/{id}` | Vorgang mit Trail, Zuordnungen (`placements`, `case_links`), Teilvorgängen, Querverweisen, Einbindungen, Aufgaben, Fristen |
|
||||
| PATCH | `/api/v1/matters/{id}` | Titel, Status |
|
||||
| POST | `/api/v1/matters/{id}/delete` | Vorgang löschen; nur ohne Teilvorgänge. Verlangt `edit` (Review R-01) |
|
||||
| POST | `/api/v1/matters/{id}/move` | Akte wechseln (`case_id`), Elternvorgang setzen oder lösen |
|
||||
| POST | `/api/v1/matters/{id}/case-links` | Akte zuordnen; Freigaberecht am Vorgang und Bearbeitungsrecht an der Akte |
|
||||
| DELETE | `/api/v1/matter-case-links/{id}` | Zuordnung lösen |
|
||||
| POST | `/api/v1/matters/{id}/cross-links` | Querverweis (`target_matter_id`, `target_context`) |
|
||||
| DELETE | `/api/v1/matter-cross-links/{id}` | Querverweis lösen |
|
||||
| POST | `/api/v1/matters/{id}/grants` | Grant am Vorgang |
|
||||
| POST | `/api/v1/matters/{id}/chapters` | Kapitel (Kontext als Query) |
|
||||
| POST | `/api/v1/matters/{id}/chapters/order` | Geschwisterreihenfolge |
|
||||
| PATCH | `/api/v1/matters/{id}/content-order` | Ordnungsart |
|
||||
| POST | `/api/v1/matters/{id}/bindings/order` | eigene Reihenfolge |
|
||||
| POST | `/api/v1/matters/{id}/bindings/chapters` | mehrere Einbindungen in ein Kapitel |
|
||||
| GET | `/api/v1/matters/{id}/course` | fachlicher Verlauf |
|
||||
| GET | `/api/v1/matters/{id}/chronology?cursor=` | Änderungsprotokoll |
|
||||
|
||||
## Kapitel
|
||||
|
||||
| Methode | Pfad | Zweck |
|
||||
|---|---|---|
|
||||
| PATCH | `/api/v1/chapters/{id}` | Kapiteldatum |
|
||||
| PATCH | `/api/v1/chapters/{id}/title` | umbenennen |
|
||||
| POST | `/api/v1/chapters/{id}/parent` | umhängen, `parent_chapter_id: null` = oberste Ebene |
|
||||
| POST | `/api/v1/chapters/{id}/delete` | auflösen; Inhalte und Kinder rücken eine Ebene nach oben |
|
||||
|
||||
## Inhalte und Einbindungen
|
||||
|
||||
| Methode | Pfad | Zweck |
|
||||
|---|---|---|
|
||||
| POST | `/api/v1/notes` | Notiz mit Einbindung (`context`, optional `placement`, `chapter_id`, `dates`, `communication_direction`) |
|
||||
| PATCH | `/api/v1/notes/{id}` | gemeinsamen Text ändern; Antwort mit `visible_bindings` und `notice` |
|
||||
| POST | `/api/v1/files` | Datei hochladen (Multipart: `title`, `context_kind`, `context_id`, `upload`, optional Platzierung, Kapitel, Daten, Richtung); PDF, PNG, JPEG, WebP bis 20 MiB |
|
||||
| GET | `/api/v1/files/{id}/content` | Datei als `attachment`, `no-store` |
|
||||
| POST | `/api/v1/external-refs` | externe Referenz (`paperless`, `imap`, `url`) mit `detail` |
|
||||
| POST | `/api/v1/sources/link` | wie oben, nur `paperless`/`imap` (doppelter Weg, siehe Connectoren-Befund) |
|
||||
| GET | `/api/v1/elements` | eigene, nicht eingebundene Elemente (max. 100) |
|
||||
| POST | `/api/v1/elements/{id}/delete` | überall löschen; nur Element-Owner |
|
||||
| PATCH | `/api/v1/elements/{id}/title` | Titel |
|
||||
| PATCH | `/api/v1/elements/{id}/summary` | Kurzbeschreibung (≤ 400 Zeichen) |
|
||||
| PATCH | `/api/v1/elements/{id}/dates` | Dokument-, Versand-, Zugangsdatum |
|
||||
| POST | `/api/v1/elements/{id}/references` | Bezug auf eine andere Unterlage (zyklusfrei) |
|
||||
| DELETE | `/api/v1/elements/{id}/references/{target}` | Bezug lösen |
|
||||
| POST | `/api/v1/bindings` | Element in weiteren Kontext einbinden (`share` an der Quelle, `edit` am Ziel) |
|
||||
| DELETE | `/api/v1/bindings/{id}` | Einbindung lösen |
|
||||
| PATCH | `/api/v1/bindings/{id}/chapter` | Kapitel einer Einbindung |
|
||||
| PATCH | `/api/v1/bindings/{id}/communication` | Richtung `in`/`out`/`local`/`null` |
|
||||
| POST | `/api/v1/bindings/{id}/annotations` | kontextbezogene Anmerkung |
|
||||
| PUT | `/api/v1/exceptions` | Kontextausnahme am Element, Vorgang, Aufgabe oder Frist setzen bzw. löschen; nur Owner |
|
||||
| DELETE | `/api/v1/grants/{id}` | Grant entziehen |
|
||||
|
||||
## Aufgaben, Fristen, Übersichten, Suche
|
||||
|
||||
| Methode | Pfad | Zweck |
|
||||
|---|---|---|
|
||||
| POST | `/api/v1/tasks` | Aufgabe, optional mit Vorgang und Kontext |
|
||||
| PATCH | `/api/v1/tasks/{id}` | Titel, Arbeitstermin, Status `open`/`done` |
|
||||
| POST | `/api/v1/tasks/{id}/assignee` | zuweisen (E-Mail) oder lösen; legt begrenztes Grant an. Keine Oberfläche |
|
||||
| POST | `/api/v1/tasks/{id}/deadline-links` | Frist verknüpfen |
|
||||
| PUT | `/api/v1/tasks/{id}/elements` | verknüpfte Inhalte ersetzen (max. 40) |
|
||||
| POST | `/api/v1/tasks/{id}/dependencies` | Abhängigkeit von anderer Aufgabe (zyklusfrei) |
|
||||
| DELETE | `/api/v1/tasks/{id}/dependencies/{other}` | Abhängigkeit lösen |
|
||||
| POST | `/api/v1/deadlines` | Frist |
|
||||
| PATCH | `/api/v1/deadlines/{id}` | Titel, Datum |
|
||||
| POST | `/api/v1/deadlines/{id}/fulfill` | als erfüllt kennzeichnen |
|
||||
| GET | `/api/v1/views/open-tasks` | offene sichtbare Aufgaben (siehe Review R-11) |
|
||||
| GET | `/api/v1/views/open-deadlines` | offene sichtbare Fristen (siehe Review R-11) |
|
||||
| GET | `/api/v1/views/recent-matters` | acht zuletzt geänderte sichtbare Vorgänge |
|
||||
| GET | `/api/v1/placement-targets` | bearbeitbare Akten und Vorgänge als Ziele |
|
||||
| GET | `/api/v1/search?q=` | Akten, Vorgänge, Elemente (Titel und Notiztext), max. 50 |
|
||||
|
||||
## Quellen
|
||||
|
||||
| Methode | Pfad | Zweck |
|
||||
|---|---|---|
|
||||
| GET | `/api/v1/connectors` | eigene Zugänge ohne Secret |
|
||||
| POST | `/api/v1/connectors` | Paperless (überschreibt den vorhandenen) oder IMAP anlegen |
|
||||
| DELETE | `/api/v1/connectors/{id}` | Zugang löschen |
|
||||
| POST | `/api/v1/connectors/{id}/probe` | Zugang prüfen |
|
||||
| GET | `/api/v1/sources/paperless/documents?q=` | Paperless-Suche (letzter eigener Zugang) |
|
||||
| GET | `/api/v1/sources/imap/mailboxes?connector_id=` | IMAP-Fächer |
|
||||
| GET | `/api/v1/sources/imap/messages?connector_id=&mailbox=&q=&before=` | Nachrichtenliste, 30 je Seite |
|
||||
| GET | `/api/v1/sources/imap/message?connector_id=&mailbox=&uid=` | Vorschau vor dem Übernehmen |
|
||||
| GET | `/api/v1/external-refs/{id}/content` | Paperless-Datei zum Ansehen (`inline`) |
|
||||
| GET | `/api/v1/external-refs/{id}/mail` | vollständige E-Mail als JSON, Identität per Message-ID geprüft |
|
||||
| GET | `/api/v1/external-refs/{id}/mail/original` | EML |
|
||||
| GET | `/api/v1/external-refs/{id}/mail/attachments/{index}` | Anlage (`inline`, siehe Review R-03) |
|
||||
|
||||
Quelleninhalte werden mit den Zugängen der **anfragenden** Person geladen (Review R-10).
|
||||
|
||||
## Übergabepaket
|
||||
|
||||
| Methode | Pfad | Zweck |
|
||||
|---|---|---|
|
||||
| GET | `/api/v1/matters/{id}/export-tree` | Auswahlbaum mit `exportable` und Grund |
|
||||
| POST | `/api/v1/matters/{id}/export/review` | Prüfung: `ready`, `issues`, `notices`, `entries` mit Paketpfaden |
|
||||
| POST | `/api/v1/matters/{id}/export` | ZIP nur bei `ready`; Audit `export_created`. Knoten `attachment`, `dispatch-item` und `evidence` gehören zur Auswahl |
|
||||
|
||||
## Anlagen und Versand
|
||||
|
||||
Alle schreibenden Aufrufe prüfen den Handlungskontext, `expected_version` und den Behälter (`placement`, sonst der Kontext). Fremde oder unlesbare IDs antworten mit 404. Ohne Bearbeitungsrecht mit 403.
|
||||
|
||||
| Methode | Pfad | Zweck |
|
||||
|---|---|---|
|
||||
| POST | `/api/v1/elements/{id}/attachments` | Anlagen zuordnen, optional nur als Anlagenansicht |
|
||||
| POST | `/api/v1/elements/{id}/attachments/order` | Reihenfolge |
|
||||
| POST | `/api/v1/elements/{id}/attachments/{attachment_id}/detach` | nur diese Zuordnung lösen |
|
||||
| PATCH | `/api/v1/bindings/{id}/fold` | Vorkommen als Anlage, Nachweis oder wieder eigenständig |
|
||||
| POST | `/api/v1/elements/{id}/dispatches` | Versand dokumentieren und Fassung sichern oder als Lücke kennzeichnen |
|
||||
| POST | `/api/v1/dispatches/{id}/evidence` | Nachweis ergänzen |
|
||||
| POST | `/api/v1/dispatches/{id}/evidence/{element_id}/detach` | nur diesen Beleg vom Versand lösen |
|
||||
| POST | `/api/v1/dispatches/{id}/correct` | Weg, Datum oder Gegenüber berichtigen |
|
||||
| GET | `/api/v1/dispatches/{id}` | Manifest, Nachweise, Berichtigungen |
|
||||
| GET | `/api/v1/dispatches/{id}/items/{item_id}/content` | gesicherte Bytes; eine Lücke liefert 404 und nicht die aktuelle Datei |
|
||||
|
||||
Eingabe für beide POST-Aufrufe: `{context, selected: [Knoten-IDs], assignments: {Knoten-ID: connector_id}}`.
|
||||
@@ -0,0 +1,114 @@
|
||||
# Tsumugu – Datenmodell (Ist-Stand)
|
||||
|
||||
**Stand:** 18.10.2026, nach den Migrationen in `backend/migrations/` (letzte: `20261018T090000Z_correspondence.sql`). Erstellt im Code-Review.
|
||||
|
||||
Die Sollfassung steht in der [technischen Spezifikation, Abschnitt 4](TSUMUGU_TECHNICAL_SPEC.md). Diese Datei beschreibt, was tatsächlich angelegt ist. Bei jeder neuen Migration nachziehen.
|
||||
|
||||
## Migrationsverfahren
|
||||
|
||||
- Dateien `YYYYMMDDTHHMMSSZ_name.sql`, lexikalisch sortiert.
|
||||
- Ledger `schema_migrations(version, checksum, applied_at)`; eine geänderte angewandte Datei bricht den Start ab.
|
||||
- Jede Datei läuft mit ihrem Ledger-Eintrag in einer Transaktion.
|
||||
- Danach legt `migrate` die Rolle `tsumugu_runtime` an bzw. aktualisiert sie: `LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT`, DML auf alle Tabellen, kein `CREATE` im Schema, kein Zugriff auf `schema_migrations`. Das Passwort ist das des Owners (siehe Review R-09).
|
||||
- Aufruf beim Containerstart (`app.entrypoint`) und über `python -m app.cli migrate`.
|
||||
|
||||
## Identität und Räume
|
||||
|
||||
| Tabelle | Wesentliche Spalten | Regeln |
|
||||
|---|---|---|
|
||||
| `auth_accounts` | `id`, `email` (unique), `display_name`, `password_hash` (bcrypt), `status` (`active`/`disabled`), `is_superadmin`, `origin` (`operator`/`fixture`) | Konten mit `origin='fixture'` entfernt der Start in jeder Umgebung |
|
||||
| `auth_sessions` | `id`, `account_id`, `secret_hash` (SHA-256, unique), `csrf_token`, `scope_kind`, `scope_id`, `epoch`, `expires_at`, `revoked_at` | der bestätigte Datenraum steht in der Session |
|
||||
| `auth_invitations` | `email`, `room_id`, `token_hash`, `invited_by`, `expires_at`, `accepted_at` | 7 Tage gültig |
|
||||
| `data_rooms` | `id`, `kind` (`personal`/`organization`), `name`, `status` (`active`/`archived`), `created_by` | persönlicher Raum: `id = account_id` |
|
||||
| `room_memberships` | PK (`room_id`, `subject_id`), `role` (`member`/`manager`), `status` (`active`/`removed`) | – |
|
||||
|
||||
## Struktur
|
||||
|
||||
| Tabelle | Wesentliche Spalten | Regeln |
|
||||
|---|---|---|
|
||||
| `cases` | Anker¹, `title`, `parent_case_id`, `rights_mode` (`inherit_parent`/`explicit`), `record_status` (`open`/`closed`), `content_order` (`date`/`position`), `content_order_dir`, `content_view` (`structure`/`chronology`) | Wurzelakte immer `explicit`; Composite-FK (`parent_case_id`, `home_scope_id`); Anwendung erlaubt eine Unteraktenebene. `content_view` ist nur die Arbeitsansicht |
|
||||
| `matters` | Anker¹, `title`, `parent_matter_id`, `record_status`, `content_order`, `content_order_dir`, `content_view` | Composite-FK für den Elternvorgang im selben Raum; Anwendung erlaubt beim Anlegen eine Teilvorgangsebene |
|
||||
| `matter_case_links` | `matter_id`, `case_id`, `created_by` | unique (`matter_id`, `case_id`); Vererbungskontext |
|
||||
| `case_link_blocks` | PK (`link_id`, `element_id`) | Inhalte, die die zuordnende Person nicht freigeben durfte; im Aktenkontext unsichtbar. Kaskade beim Lösen der Zuordnung |
|
||||
| `matter_cross_links` | `from_matter_id`, `to_matter_id` | kein Selbstverweis, unique |
|
||||
| `chapters` | `home_scope_id`, genau eines von `case_id`/`matter_id`, `title`, `position`, `document_on`, `parent_chapter_id` | Composite-FKs zum Behälter; Trigger `chapters_parent_guard`: gleiches Objekt, gleicher Raum, kein Zyklus, höchstens 32 Ebenen |
|
||||
|
||||
¹ Anker: `id`, `home_scope_id`, `owner_subject_id`, `created_by`, `version`, `created_at`, `updated_at`, `deleted_at`.
|
||||
|
||||
## Inhalte
|
||||
|
||||
| Tabelle | Wesentliche Spalten | Regeln |
|
||||
|---|---|---|
|
||||
| `elements` | Anker¹, `title`, `kind` (`note`/`file`/`external_ref`), `summary` (≤ 400) | gemeinsamer Inhaltsträger |
|
||||
| `note_bodies` | `element_id`, `document_json`, `version` | ein Text je Notiz; Format `{version: 1, blocks: [...]}` mit Absatz- oder einem Markdown-Block |
|
||||
| `correspondence_dates` | `element_id`, `document_on`, `sent_on`, `received_on` | getrennte Datumssachen; Erfassung = `elements.created_at` |
|
||||
| `external_references` | `element_id`, `source` (`paperless`/`url`/`imap`), `external_id`, `detail` (JSON) | IMAP: Message-ID als `external_id`, `connector_id`, `mailbox`, `uid` im JSON; kein Eindeutigkeitsindex |
|
||||
| `bindings` | `element_id`, `context_kind` (`case`/`matter`), `context_id`, `chapter_id`, `position`, `communication_direction` (`in`/`out`/`local`/NULL), `direction_explicit`, `list_fold` (`attachment`/`evidence`/NULL) | unique (`element_id`, `context_kind`, `context_id`); kein FK auf den Kontext (polymorph). `list_fold` gilt nur für dieses Vorkommen |
|
||||
| `attachment_uses` | Behälter, `host_element_id`, `attachment_element_id`, `position`, optionales `label` | flache Zuordnung je Hauptschriftstück und Behälter; keine Dateikopie; kein Selbstbezug |
|
||||
| `dispatches` | Behälter, `host_element_id`, `channel`, `sent_on`, `counterpart`, `completeness`, `provenance`, `version` | mehrere Versände je Schreiben; `sent_on` leer bleibt undatiert |
|
||||
| `dispatch_items` | Rolle `host`/`attachment`, Titel, Dokumentdatum, `source_state` `snapshot`/`gap`, Hash, optionales Notiz-JSON | Manifest der übermittelten Fassung; Lücke ersetzt nicht die Arbeitsdatei |
|
||||
| `dispatch_snapshots` | Bytes, Hash, Dateiname | Datei unter `MEDIA_ROOT/dispatch/<id>`; fällt in den Löschpfad des Elements |
|
||||
| `dispatch_evidence` | `element_id`, Rolle `email`/`submission`/`delivery`/`other`, Identitätsprüfung, `comparisons` | manuelle Zuordnung; Einlieferung ist keine Zustellung |
|
||||
| `dispatch_corrections` | Zeitpunkt, Zusammenfassung | Berichtigung ohne stilles Umschreiben der Bytes |
|
||||
| `context_annotations` | `binding_id`, `body` (≤ 4 000), `author_subject_id` | Kaskade mit der Einbindung |
|
||||
| `element_references` | PK (`element_id`, `refers_to_element_id`) | kein Selbstbezug; Zyklusprüfung in der Anwendung; FK-Kaskade greift nur bei physischem Löschen, Elemente werden aber nur markiert (Review R-13) |
|
||||
| `media_assets` | `id`, `element_id` (unique), Owner, Heimatraum, `original_filename`, `content_type`, `byte_size`, `sha256`, `revision`, `status` (`active`/`purging`/`purged`) | Bytes unter `MEDIA_ROOT/<asset_id>` |
|
||||
| `media_operations` | `element_id`, `asset_id`, `phase`, `status` | derzeit reines Protokoll |
|
||||
|
||||
## Rechte
|
||||
|
||||
| Tabelle | Wesentliche Spalten | Regeln |
|
||||
|---|---|---|
|
||||
| `access_grants` | `grantee_subject_id` (NULL bei Kontextausnahme), `resource_kind` (`case`/`matter`/`element`/`task`/`deadline`), `resource_id`, `context_kind`/`context_id`, `can_read/edit/share/delete`, `is_exception` | Grant: `is_exception=false`, ohne Kontext. Ausnahme: `is_exception=true`, Kontext gesetzt, die Flags bedeuten „entfernt“. Eindeutigkeitsindex über Ressource, Empfänger, Kontext und Art |
|
||||
|
||||
## Nachverfolgung
|
||||
|
||||
| Tabelle | Wesentliche Spalten | Regeln |
|
||||
|---|---|---|
|
||||
| `tasks` | Anker¹, `title`, `matter_id`, `assignee_subject_id`, `due_on`, `task_status` (`open`/`done`) | ohne Vorgang ist die Aufgabe selbst der Rechteanker |
|
||||
| `deadlines` | Anker¹, `title`, `matter_id`, `element_id` (ungenutzt), `assignee_subject_id`, `due_on`, `deadline_status` (`open`/`fulfilled`), `fulfilled_at` | – |
|
||||
| `task_deadline_links` | PK (`task_id`, `deadline_id`) | keine Statuskopplung |
|
||||
| `task_element_links` | PK (`task_id`, `element_id`) | nicht in der Spezifikation |
|
||||
| `task_dependencies` | PK (`task_id`, `depends_on_task_id`) | kein Selbstbezug, Zyklusprüfung in der Anwendung; nicht in der Spezifikation |
|
||||
|
||||
## Quellen und Audit
|
||||
|
||||
| Tabelle | Wesentliche Spalten | Regeln |
|
||||
|---|---|---|
|
||||
| `connectors` | `owner_id`, `kind` (`paperless`/`imap`), `name`, `settings` (JSON), `secret` (Klartext, Review R-05) | Paperless höchstens einmal je Konto (in der Anwendung) |
|
||||
| `domain_events` | `actor_subject_id`, `scope_id`, `action`, `resource_kind`, `resource_id`, `context_kind/id`, `occurred_on`, `occurred_at`, `result` | append-only; Grundlage von Chronologie und fachlichem Verlauf |
|
||||
|
||||
## Nicht angelegt (bewusst)
|
||||
|
||||
`compilations`, `release_state`, Finanztabellen (`invoices`, `payments`, …), `external_field_states`, `retain_until`, Auth-Tabellen für Flows, MFA, Recovery-Codes und Rate-Limits. Sie gehören zu späteren Paketen bzw. zu offenen Befunden.
|
||||
|
||||
## Beziehungen
|
||||
|
||||
```mermaid
|
||||
erDiagram
|
||||
auth_accounts ||--|| data_rooms : "persoenlicher Raum"
|
||||
auth_accounts }o--o{ data_rooms : "room_memberships"
|
||||
data_rooms ||--o{ cases : "Heimat"
|
||||
data_rooms ||--o{ matters : "Heimat"
|
||||
data_rooms ||--o{ elements : "Heimat"
|
||||
cases ||--o{ cases : "Unterakte"
|
||||
matters ||--o{ matters : "Teilvorgang"
|
||||
matters }o--o{ cases : "matter_case_links"
|
||||
matters }o--o{ matters : "matter_cross_links"
|
||||
cases ||--o{ chapters : "Gliederung"
|
||||
matters ||--o{ chapters : "Gliederung"
|
||||
chapters ||--o{ chapters : "Unterkapitel"
|
||||
elements ||--o{ bindings : "Einbindung"
|
||||
bindings ||--o{ context_annotations : "Anmerkung"
|
||||
elements ||--o| note_bodies : "Text"
|
||||
elements ||--o| correspondence_dates : "Daten"
|
||||
elements ||--o| external_references : "Referenz"
|
||||
elements ||--o| media_assets : "Datei"
|
||||
elements }o--o{ elements : "element_references"
|
||||
matters ||--o{ tasks : "optional"
|
||||
matters ||--o{ deadlines : "optional"
|
||||
tasks }o--o{ deadlines : "task_deadline_links"
|
||||
tasks }o--o{ elements : "task_element_links"
|
||||
tasks }o--o{ tasks : "task_dependencies"
|
||||
auth_accounts ||--o{ connectors : "Zugang"
|
||||
```
|
||||
@@ -6,6 +6,10 @@
|
||||
|
||||
**Technische Grundlagen:** Jinkendo-Referenzarchitektur A/B/C v0.3 vom 16.10.2026 sowie die Blueprints Auth/Session/Scope, Release/Betrieb/Recovery und Medien/Dateien. KI-Gateway, Prompt-/Workflow-Laufzeit und Entitlements gelten nur als Grenze, nicht als MVP-Pflicht.
|
||||
|
||||
### Hinweis zum Ist-Stand (Code-Review 18.10.2026)
|
||||
|
||||
Diese Fassung ist der Entwurf vom 16.10.2026 mit späteren punktuellen Ergänzungen (Ordnung, Richtung, Unterkapitel). Abschnitt 1.3 („keine Fachanwendung“) und der Satz in Abschnitt 8, der erste Auftrag solle nur P0 umfassen, beschreiben den damaligen Ausgangspunkt. Die Anwendung umfasst inzwischen P0–P3, P4a und P5a sowie die Folgeaufträge F-06 bis F-08. P7 fehlt. Den tatsächlichen Stand beschreiben [API_REFERENZ.md](API_REFERENZ.md), [DATENMODELL_IST.md](DATENMODELL_IST.md) und [RECHTEMODELL_IST.md](RECHTEMODELL_IST.md). Abweichungen zwischen dieser Spezifikation und dem Code stehen im [Code-Review](../review/04_TECHNISCHE_SPEZIFIKATION.md).
|
||||
|
||||
### Änderungsnotiz 0.3
|
||||
|
||||
F-05a bestätigt die erste benutzbare Lieferung „Organisieren und Nachverfolgen“. Finanzfunktionen und bidirektionaler Paperless-Abgleich folgen anschließend, ohne gestrichen zu werden. Die zuvor kombinierten Pakete P4 und P5 sind dafür in unabhängig lieferbare Teile aufgeteilt; P7 sichert schon den ersten echten Betrieb ab. Die technische Präzisierung des Akten-Handlungskontexts ist in Abschnitt 6.2 ergänzt. Diese Angleichung ist keine pauschale Freigabe der offenen Rechte-/Löschvorschläge und kein Implementierungsauftrag.
|
||||
@@ -217,7 +221,9 @@ Gemeinsame Spalten der fachlichen Ankerobjekte `cases`, `matters`, `elements`, `
|
||||
|
||||
Auth-Tabellen `auth_accounts` und `auth_sessions` folgen dem Auth-Blueprint. Ein Anzeigename ist kein Identitätsbeweis.
|
||||
|
||||
Akten und Vorgänge speichern `content_order` (`date` oder `position`) und `content_order_dir` (`asc` oder `desc`). Bestehende Zeilen bleiben auf `position`, damit eine schon gesetzte Einbindungsreihenfolge nicht ersetzt wird. Neue Akten und Vorgänge beginnen mit fachlichem Datum aufsteigend. `bindings.position` gehört zur Einbindung. Die Datumssortierung schreibt sie nicht um. `PATCH /api/v1/cases/{id}/content-order` und `POST /api/v1/cases/{id}/bindings/order` sowie die gleichen Pfade unter `matters` prüfen das Bearbeitungsrecht im Handlungskontext und `expected_version`. Der fachliche Verlauf liest die Datumsfelder der sichtbaren Unterlagen einmal je Element. Das Änderungsprotokoll bleibt `GET .../chronology`, seitenweise über `cursor`. Der Breadcrumb eines Vorgangs ist der Objektpfad `Vorgänge` und gegebenenfalls der lesbare Elternvorgang; lesbare Aktenzuordnungen stehen separat in `placements` und wechseln den Handlungskontext nur bei bewusster Auswahl. `elements.summary` ist eine optionale gemeinsame Kurzbeschreibung. Ein Textauszug entsteht nur aus vorhandenem Notiztext. Bild- und PDF-Vorschauen verwenden denselben berechtigten Dateiabruf wie das Öffnen.
|
||||
Akten und Vorgänge speichern `content_order` (`date` oder `position`) und `content_order_dir` (`asc` oder `desc`). Bestehende Zeilen bleiben auf `position`, damit eine schon gesetzte Einbindungsreihenfolge nicht ersetzt wird. Neue Akten und Vorgänge beginnen mit fachlichem Datum aufsteigend. `bindings.position` gehört zur Einbindung. Die Datumssortierung schreibt sie nicht um. `PATCH /api/v1/cases/{id}/content-order` und `POST /api/v1/cases/{id}/bindings/order` sowie die gleichen Pfade unter `matters` prüfen das Bearbeitungsrecht im Handlungskontext und `expected_version`. Der fachliche Verlauf liest die Datumsfelder der sichtbaren Unterlagen einmal je Element. Das Änderungsprotokoll bleibt `GET .../chronology`, seitenweise über `cursor`. `content_view` ist `structure` oder `chronology` und nur eine Darstellung. Sie schreibt Kapitel, Positionen und Datumssortierung nicht um. Der Breadcrumb eines Vorgangs ist der Objektpfad `Vorgänge` und gegebenenfalls der lesbare Elternvorgang; lesbare Aktenzuordnungen stehen separat in `placements` und wechseln den Handlungskontext nur bei bewusster Auswahl. `elements.summary` ist eine optionale gemeinsame Kurzbeschreibung. Ein Textauszug entsteht nur aus vorhandenem Notiztext. Bild- und PDF-Vorschauen verwenden denselben berechtigten Dateiabruf wie das Öffnen.
|
||||
|
||||
Anlagen, Versand und Nachweise sind eigene Verwendungen im Behälter der Einbindung, nicht im geerbten Aktenkontext. `attachment_uses` ordnet ein vorhandenes Element einem Hauptschriftstück zu, mit eigener Reihenfolge je Behälter und ohne Dateikopie. `bindings.list_fold` blendet nur dieses Vorkommen als Anlage oder Nachweis aus; andere Einbindungen bleiben. `dispatches` hält Weg, Versanddatum, Gegenüber, Vollständigkeit und Herkunft (`captured` oder `reconstructed`). `dispatch_items` ist das Manifest. Eine sicherbare Fassung liegt als Bytes unter `MEDIA_ROOT/dispatch/<id>` in `dispatch_snapshots`, bei Notizen zusätzlich als JSON im Manifest. Eine fehlende historische Fassung bleibt `gap` und wird nicht durch die aktuelle Arbeitsdatei ersetzt. `dispatch_evidence` verknüpft einen vorhandenen Beleg in der Rolle E-Mail, Einlieferung, Zustellung oder sonstiger Nachweis. Am Schriftstück liegt dafür ein eigenes Ablagefeld; mehrere Belege eines Versands bleiben nebeneinander. Ziehen aus der Liste ordnet zu, Ziehen zurück in die Liste löst nur diese Verwendung. Einlieferung setzt keinen Zustellstatus. Berichtigungen stehen in `dispatch_corrections` und ändern die gesicherten Bytes nicht. Löschen eines Elements entfernt die Bytes seiner Versandfassungen über denselben Löschpfad wie die Arbeitsdatei. Lesen des Hauptschriftstücks öffnet keine gesperrte Anlage. Exportknoten `attachment`, `dispatch_item` und `evidence` unterscheiden Arbeitsstand, gesicherte Fassung und Nachweis. Eine unvollständige Auswahl ist ein Auszug. Eine ausgewählte E-Mail bleibt das vollständige Original.
|
||||
|
||||
### 4.3 Überblick
|
||||
|
||||
@@ -372,7 +378,7 @@ Dieselbe Grenze gilt für Finanzobjekte. Eine unzugeordnete Zahlung sehen Owner
|
||||
|
||||
### 5.6 Anwalt und RLS
|
||||
|
||||
Der spätere Anwaltszugang kann ein Leserecht auf eine Zusammenstellung an ein weiteres Subjekt vergeben. Die Zugangsform bleibt offen und ist keine MVP-Funktion. Ein Exportpaket wäre ein eigenes Asset mit dem Stand zum Erzeugungszeitpunkt; auch das liegt außerhalb des MVP.
|
||||
Ein registriertes Konto mit Leserecht an Akte oder Vorgang kann verknüpfte Paperless-Dokumente und E-Mails über die serverseitigen Zugänge des Owners lesen, wenn der Owner das an der Freigabe ausdrücklich einschaltet (`use_owner_sources`). Der Empfänger richtet dafür keine eigenen Quellen ein, erhält keine Secrets und kann das Archiv oder Postfach nicht durchsuchen. Ein Gastzugang ohne Konto bleibt offen und ist nicht Teil dieses Schnitts. Das Übergabepaket bleibt ein eigener Stand und nutzt weiter die Zugänge der exportierenden Person.
|
||||
|
||||
Vertrag ADR-06 und offener Punkt O1: vertrauliche Mehrraumdaten brauchen eine ausdrückliche RLS-Prüfung. Vorschlag: ab P1 App-Policy, zusammengesetzte Fremdschlüssel und eine Runtime-Rolle ohne DDL, Owner und `BYPASSRLS`. Vor dem ersten Produktivbetrieb mit echten Daten zusätzlich RLS als zweite Linie, mit transaktionslokalem Subjekt und einem Grant-Prädikat, das datenraumübergreifende Leserechte nur über `access_grants` zulässt. Pool-Rückgabe darf diesen Kontext nicht behalten. RLS ersetzt die App-Policy nicht. Ein stiller, auf die Scope-ID beschränkter RLS-Filter wäre ein Fehler, weil er bestätigte Freigaben aussperren oder, bei zu weiter Policy, fremde Akten öffnen würde.
|
||||
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
# Tsumugu – Erste Lieferung: vollständiges Übergabepaket
|
||||
|
||||
**Erweiterung vom 18.10.2026:** [Schreiben/Anlagen/Versand/Nachweise](TSUMUGU_SCHREIBEN_ANLAGEN_VERSAND_AUFTRAG_2026-10-18.md) erweitert den vorhandenen Export um Rollen, Ereignisse und konkrete übermittelte Fassungen. Die vollständige EML-Anlagenregel und die Auswahl nach Vorkommen bleiben erhalten; bewusste Auszüge eines Versandstands werden als solche bezeichnet. Die unten beschriebene erste Liefergrenze ist historisch.
|
||||
|
||||
Stand: 17.10.2026. Fachliches Lieferpaket und vorbereiteter Cursor-Auftrag. Führend für die bestätigten Entscheidungen ist die Produktspezifikation 0.32, F-07a–c. Neue Bestandsänderungen sind vor Umsetzung erneut abzugleichen. Dieser Dokumentationsauftrag beginnt keine Umsetzung.
|
||||
|
||||
## Ziel
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
# Tsumugu – kompakte Inhaltsliste und Bezüge
|
||||
|
||||
**Spätere Erweiterung, 18.10.2026:** [Schreiben mit Anlagen, Versand und Nachweisen](TSUMUGU_SCHREIBEN_ANLAGEN_VERSAND_AUFTRAG_2026-10-18.md) ergänzt ausdrückliche Inhaltsrollen und Chronologie. Die kompakte Darstellung bleibt; Anlagen dürfen am Hauptschriftstück gezielt geöffnet werden, allgemeine Bezüge bleiben ohne Umordnung. Der neue Auftrag präzisiert zusätzlich Kapitelgrenzen und Nachweisdarstellung.
|
||||
|
||||
**Stand:** 17.10.2026 · **Fassung:** 1.0 · **Ziel:** deutlich mehr Vorgangsinhalt auf einen Blick, direkt bedienbare Kommunikationszeichen und kompakte Beziehungen.
|
||||
|
||||
## 1. Geltung und Befund
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Tsumugu – Fachliche Produktspezifikation
|
||||
|
||||
**Stand:** 17.10.2026 · **Arbeitsstand:** 0.37, Unterkapitel als reine verschachtelte Gliederung; kompakte Inhaltsliste und Exportlieferung bleiben erhalten.
|
||||
**Stand:** 18.10.2026 · **Arbeitsstand:** 0.38, Anforderungen zu Schreiben mit Anlagen, Versand/Nachweisen, Chronologie und Kapitelgrenzen zusammengestellt.
|
||||
**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.
|
||||
@@ -418,6 +418,20 @@ Der Nutzer nennt folgende tatsächlich genutzte Felder. Schreibweisen sind als G
|
||||
|
||||
**Auswirkungen auf Fachmodell und MVP:** Jedes Kapitel hat höchstens ein Elternkapitel im selben Objekt. Direkte Inhalte eines Kapitels bleiben von den Inhalten seiner Unterkapitel unterscheidbar. Geschwister haben eine eigene Reihenfolge; die Eintragsreihenfolge bleibt die des jeweiligen Kapitels. Umhängen bleibt im selben Objekt und gibt nichts frei. Auflösen einer Kapitelgliederung löscht keine Inhalte oder Originaldateien: direkte Einbindungen und direkte Unterkapitel rücken unter das bisherige Elternkapitel, bei einem Wurzelkapitel auf die oberste Ebene. Der vorhandene Export stellt die Struktur als Verzeichnisse dar. F-07c bleibt unverändert. Eine technische Schutzgrenze von 32 Ebenen verhindert Zyklen und unbegrenzte Tiefe; sie ist keine fachliche Produktgrenze. Auftrag und Abnahme: [Unterkapitel](TSUMUGU_UNTERKAPITEL_AUFTRAG_2026-10-17.md).
|
||||
|
||||
### F-08b – Schreiben mit Anlagen und erkennbare Kapitelgrenzen: 18.10.2026
|
||||
|
||||
**Nutzerbedarf und Auftrag:** Unterkapitel werden ersatzweise verwendet, um ein Schriftstück mit seinen Anlagen zusammenzuhalten. Die Abgrenzung von Vorgang, Kapitel und Unterkapitel ist in der Oberfläche zu schwach; chronologische Einordnung und konkrete Anlagenzuordnung werden nicht ausreichend ausgedrückt. Der Nutzer benennt Anlagen ausdrücklich als neue fachliche Funktion und beauftragt Anforderungen und Cursor-Prompt für den besprochenen Ausbau.
|
||||
|
||||
**Konkrete Ausgestaltung:** Vorhandenes Hauptschriftstück mit ausdrücklicher, geordneter Anlagenverwendung ergänzen. Kapitel bleiben thematische Gliederung ohne eigene Rechte; allgemeine Antwort-/Belegbezüge bleiben eigenständig. Ein Inhalt kann Anlage mehrerer Schreiben sein, ohne Kopie zur bloßen Organisation und ohne neue Zugriffsrechte. Anlagen als kompakte, bei Bedarf öffnende Einheit darstellen. Klare Kapitelgrenzen, keine unmittelbare doppelte Überschrift und verständliche direkte/Gesamtzähler. Bestandsunterkapitel nicht automatisch umdeuten; vorhandene Belege gesammelt bewusst zuordnen. Gliederung und durchgehende Chronologie als verständliche Arbeitsansichten erhalten; Dokumentdaten nicht durch Versanddaten überschreiben.
|
||||
|
||||
### F-08c – Versand, Nachweise und übermittelte Fassung: 18.10.2026
|
||||
|
||||
**Nutzerbedarf:** Selbst erstellte Schreiben wurden per Post oder E-Mail verschickt. Einlieferungsbeleg oder E-Mail sollen als Nachweis dienen. Eine eigenständige Nachweis-E-Mail in der Struktur führt durch ihre Anhänge zu redundanten Informationen und erschwert die Übersicht. Der Nutzer beauftragt die Zusammenstellung des besprochenen fachlichen Lösungsansatzes.
|
||||
|
||||
**Konkrete Ausgestaltung:** Versandereignis mit Zeitpunkt, Kanal, Gegenüber, konkretem Inhaltsstand und zugeordneten Nachweisen dokumentieren; mehrere Versände desselben Schreibens bleiben möglich. Die tatsächliche übermittelte Fassung bleibt abrufbar und verändert sich nicht still durch spätere Bearbeitung. Fehlende historische Originale als Lücke/Rekonstruktion ausweisen. E-Mail als Nachweis vollständig erhalten, auf Wunsch im aktiven Kontext kompakt am Versand darstellen statt eine zweite sichtbare Anlagenzusammenstellung zu erzeugen. Fachlich eigenständige E-Mails bleiben weiterhin eigenständige Kommunikation. Eine Einlieferung ist keine automatisch bestätigte Zustellung. Keine echte Versandfunktion, automatische Nachweisbewertung oder neue allgemeine Versionsplattform erforderlich.
|
||||
|
||||
**Lieferung und Grenzen zu F-08b/c:** Der gemeinsame [Anforderungs- und Cursor-Auftrag vom 18.10.2026](TSUMUGU_SCHREIBEN_ANLAGEN_VERSAND_AUFTRAG_2026-10-18.md) konkretisiert Anlage-/Nachweisrollen, gesicherte Fassungen, Listen-/Chronologiedarstellung, Bestandsübergang, Kontextrechte und Export einschließlich vollständiger EML gemäß F-07c. Er ersetzt die historische Zurückstellung eines Hauptdokuments/Dokumentpakets für diese neue Lieferung; F-08a bleibt als Kapitelmodell erhalten. Detailregeln des Auftrags sind die aktuelle Umsetzungsausgestaltung, keine Behauptung bereits implementierter oder früher einzeln bestätigter Funktionen. Dieses Dokumentationspaket ändert keine Anwendung, Datenbank oder Bereitstellung.
|
||||
|
||||
## 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.
|
||||
@@ -494,4 +508,8 @@ Der Nutzer nennt folgende tatsächlich genutzte Felder. Schreibweisen sind als G
|
||||
|
||||
17.10.2026, Arbeitsstand 0.37: F-08a bestätigt Unterkapitel als verschachtelte Gliederung ohne eigene Rechte, Ownership oder Status. Die frühere Zurückstellung ist historisch. Kein Sammler und keine Freigabezusammenstellung. Der Auftrag liegt unter [TSUMUGU_UNTERKAPITEL_AUFTRAG_2026-10-17.md](TSUMUGU_UNTERKAPITEL_AUFTRAG_2026-10-17.md). Prüfergebnis und Grenzen: [TSUMUGU_UNTERKAPITEL_PRUEFBERICHT_2026-10-17.md](TSUMUGU_UNTERKAPITEL_PRUEFBERICHT_2026-10-17.md).
|
||||
|
||||
18.10.2026, Arbeitsstand 0.38: F-08b/c aus der aktuellen Besprechung gesichert und gemeinsamen Auftrag erstellt: Schreiben mit Anlagen, Versandereignisse mit vollständigen Nachweisen/konkreten Fassungen, klare Kapitelgrenzen und getrennte Gliederungs-/Chronologieansicht. Bestand und vollständiger E-Mail-Export bleiben berücksichtigt. Historische Beschränkung der Unterkapitellieferung wird gezielt erweitert. Keine Änderungen an Anwendungscode, Datenbanken, Commit/Push oder Deployment durch diesen Anforderungsauftrag.
|
||||
|
||||
18.10.2026, Arbeitsstand 0.39: F-08b/c lokal umgesetzt. Anlagenverwendung, dokumentierte Versände mit gesicherter oder ausdrücklich fehlender Fassung, Nachweisrollen und die getrennte Gliederungs-/Chronologieansicht sind in der Anwendung. Bestehende Unterkapitel werden nicht umgedeutet. Der Export unterscheidet Arbeitsstand, Versandfassung und vollständige E-Mail.
|
||||
|
||||
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.
|
||||
@@ -0,0 +1,134 @@
|
||||
# Tsumugu – Schreiben, Anlagen, Versand und klare Kapitelgrenzen
|
||||
|
||||
**Stand:** 18.10.2026 · **Fassung:** 1.0 · **Ergebnis:** zusammenhängender Ausbau des vorhandenen MVP bis zur lokal prüfbaren Umsetzung.
|
||||
|
||||
## 1. Ziel, Herkunft und Vorrang
|
||||
|
||||
Der Nutzer verwendet Unterkapitel bislang ersatzweise, um ein Schriftstück mit seinen Anlagen zusammenzuhalten. Kapitelgrenzen sind in der Vorgangsseite zu wenig erkennbar. Die zeitliche Einordnung sowie die Zuordnung von Belegen zu einem konkreten Schriftstück werden dadurch nicht ausreichend ausgedrückt. Eine versendete E-Mail oder ein Einlieferungsbeleg soll außerdem als Nachweis zum Schreiben gehören, ohne durch die E-Mail-Anhänge eine zweite sichtbare Dokumentzusammenstellung aufzubauen. Der Nutzer beauftragt die Zusammenstellung dieser Anforderungen und eines Cursor-Prompts.
|
||||
|
||||
Die folgenden Regeln sind die konkrete Ausgestaltung dieses Ausbaus. Sie sind keine Behauptung, die Funktion sei bereits vorhanden. **Anlagenzuordnung und Versand mit Nachweisen sind neue fachliche Funktionen**, kein bloßer CSS-Umbau. Bestehende Originale, Kapitel, Unterkapitel, Bezüge, Kontextrechte und der vollständige Export sind weiterzuverwenden.
|
||||
|
||||
Führend: [Produktspezifikation](TSUMUGU_PRODUCT_SPEC.md), F-08a–c. Ergänzend: [kompakte Liste](TSUMUGU_KOMPAKTE_INHALTSLISTE_AUFTRAG.md), [Unterkapitel](TSUMUGU_UNTERKAPITEL_AUFTRAG_2026-10-17.md) und [Export](TSUMUGU_EXPORT_NAECHSTE_LIEFERUNG_2026-10-17.md). Historische Beschränkungen „kein Hauptdokument/kein Dokumentpaket“ gelten für die frühere Unterkapitellieferung; sie verhindern den jetzt beauftragten Ausbau nicht. Virtuelle Freigabezusammenstellungen und dynamische Sichten bleiben eigenständige Begriffe.
|
||||
|
||||
## 2. Fachliche Trennung und minimaler Umfang
|
||||
|
||||
| Begriff | Bedeutung und Grenze |
|
||||
|---|---|
|
||||
| Kapitel / Unterkapitel | Thematische Gliederung des aktiven Fachobjekts, weiterhin ohne eigene Rechte oder Status. |
|
||||
| Schreiben mit Anlagen | Vorhandenes Hauptschriftstück mit ausdrücklich zugeordneten, geordneten Anlagen. Keine zusätzliche Vorgangsebene und kein künstliches Kapitel erforderlich. |
|
||||
| Versand | Konkrete Übermittlung eines bestimmten Stands an ein Gegenüber, zu einem Datum und über einen Kanal. Mehrere Versände desselben Schreibens sind möglich. |
|
||||
| Nachweis | Vorhandene E-Mail, Einlieferungsbeleg, Zustellbestätigung oder anderes geeignetes Element, gezielt einem Versand zugeordnet. |
|
||||
| Allgemeiner Bezug | Antwort, spätere Bestätigung oder sonstiger Zusammenhang zwischen eigenständigen Einträgen. Er macht einen Beleg nicht automatisch zur versendeten Anlage. |
|
||||
|
||||
Minimal liefern: Anlagen zuordnen/ordnen/lösen, Versand manuell dokumentieren, bestehende Nachweise zuordnen, redundant eingebundene Nachweise bewusst kompakt darstellen, konkrete übermittelte Fassungen erhalten, Gliederung und Chronologie verständlich anzeigen und den vorhandenen Export erweitern. E-Mail-Versand, Postversand, Tracking-Automatik, juristische Nachweisbewertung, OCR/KI-Klassifizierung, allgemeines Versionsverwaltungssystem und Connector-Gesamtumbau sind nicht erforderlich.
|
||||
|
||||
## 3. Schreiben mit Anlagen
|
||||
|
||||
- Ein bestehendes lesbares Dokument bzw. eine geeignete vorhandene E-Mail kann Hauptschriftstück sein. Die Zuordnung ergänzt das vorhandene Inhaltsmodell; sie kopiert nicht zur bloßen Organisation die ganze Datei und ersetzt keine Akten-/Vorgangshierarchie.
|
||||
- Über „Anlagen zuordnen“ vorhandene zugängliche Elemente einzeln oder gesammelt auswählen. Zieldokument, aktiver Vorgang/Teilvorgang und geprüfter Handlungskontext sind klar. Bei Quellenübernahme den vorhandenen Auswahlweg mit eindeutigem Ziel wiederverwenden.
|
||||
- Anlagen erhalten eine eigene Reihenfolge innerhalb des Schreibens. Dokumenttitel und ursprüngliche fachliche Daten bleiben erhalten. Optional vorhandene Anlagenbezeichnungen nutzen; kein Pflichtformular je Anlage.
|
||||
- Dasselbe Element darf Anlage mehrerer Schreiben sein. Reihenfolge, Rolle und Zuordnung gehören zur jeweiligen Verwendung. Eine Änderung im Vorgang A darf keine Zuordnung in B überschreiben. Keine Kopie des gemeinsamen Inhalts zur bloßen Mehrfachverwendung.
|
||||
- „Anlage lösen“ entfernt nur diese Zuordnung. Original, andere Einbindungen und dokumentierte frühere Versände werden nicht still geändert. Kein globales Löschen über eine Anlagenaktion.
|
||||
- Keine Selbstzuordnung, Zyklen oder versehentliche doppelte Zuordnung desselben Vorkommens. Für diesen Ausbau genügt eine flache Anlagenliste pro Hauptschriftstück. Keine rekursiven Anlagenbäume oder neue allgemeine Beziehungssprache als Voraussetzung.
|
||||
- Ein Zustellvermerk, der später erstellt wurde, ist zunächst ein eigenständiger Nachweis/Bezug; er wird nicht nachträglich zur ursprünglich versendeten Anlage erklärt. Ebenso ist ein unterstützender Beleg nicht automatisch tatsächlich mitgesendet worden. Die Rolle wird bewusst gewählt.
|
||||
|
||||
## 4. Versand und Nachweise
|
||||
|
||||
### 4.1 Benutzbarer Ablauf
|
||||
|
||||
1. Beim Hauptschriftstück „Versand dokumentieren“ öffnen.
|
||||
2. Kanal „E-Mail“, „Post“ oder „Sonstiger Weg“, tatsächliches Versanddatum und Gegenüber erfassen. Bestehende Kontaktdaten wiederverwenden; ein lesbarer Freitext ist ausreichend, kein neues Parteienregister bauen. Fehlende Einzelangaben als unbekannt belassen statt erfinden. Ein unbekannter Versandtag bleibt als undatiert kenntlich; der Erfassungszeitpunkt ersetzt ihn nicht.
|
||||
3. Hauptschriftstück und tatsächlich mitversendete Anlagen einschließlich Reihenfolge prüfen. Die aktuelle Anlagenliste ist ein Vorschlag, keine automatische Behauptung über einen früheren Versand.
|
||||
4. Vorhandene E-Mail bzw. Belege als Nachweise auswählen, alternativ zunächst ohne Nachweis dokumentieren. „Vom Nutzer dokumentiert“ und „Nachweis vorhanden“ bleiben unterscheidbar. Speichern führt keinen echten Versand aus und behauptet keinen automatisch geprüften Erfolg.
|
||||
5. Einen späteren Versand desselben Schreibens, etwa nach E-Mail zusätzlich per Post, als weiteres Ereignis dokumentieren. Eigener Zeitpunkt, Kanal, Gegenüber, Inhaltsstand und Nachweise; kein Überschreiben des ersten Versands.
|
||||
|
||||
Ein Versand kann mehrere Nachweise haben, etwa Einlieferungsbeleg und spätere Zustellbestätigung. Die Rolle des Nachweises ist verständlich benannt: E-Mail/Versanddokumentation, Einlieferung, Zustellung oder sonstiger Nachweis. Eine Einlieferung wird nicht automatisch als Zustellung angezeigt. Neue Aufgaben, Fristen oder Erledigungsstände werden daraus nicht automatisch abgeleitet.
|
||||
|
||||
### 4.2 E-Mail als Nachweis ohne doppelte sichtbare Inhalte
|
||||
|
||||
- Gezielte Aktion „Als Versandnachweis zuordnen …“ an einem vorhandenen Element oder im vorhandenen Quellen-Auswahldialog. Hauptschriftstück und konkreten vorhandenen Versand auswählen oder den Versand in demselben Ablauf anlegen.
|
||||
- Die vollständige E-Mail mit Nachrichtentext, Headern und ursprünglichen Anhängen erhalten. Ein unverändertes Original bleibt direkt erreichbar. Keine Anhänge aus der EML entfernen, keine Originale umschreiben und keine Dateien allein wegen gleicher Namen zusammenführen.
|
||||
- Im Standard der Liste zeigt das Schreiben eine kompakte Angabe, etwa „8 Anlagen · per E-Mail · Nachweis“. Die E-Mail-Anhänge erscheinen hier nicht nochmals als zweite vollständig aufgeklappte Anlagenliste. Im Nachweis-Leser bleibt die vollständige Nachricht einschließlich Anhängen zugänglich.
|
||||
- Ist die E-Mail bereits eigenständig im selben Kontext eingebunden, ausdrücklich anbieten: „Hier als Nachweis darstellen“ oder „Zusätzlich als eigenständigen Eintrag behalten“. Keine automatische Entfernung, kein globales Verstecken und kein Löschen. Andere Einbindungen bleiben unverändert. Eine reine Nachweisdarstellung muss in den Details erkennbar und wieder als eigenständiges Vorkommen darstellbar sein.
|
||||
- Enthält die E-Mail zusätzliche fachliche Aussagen, muss sie als eigenständige Kommunikation erhalten bleiben können und trotzdem Nachweis sein. Nicht nach Betreff, Dateityp oder Vorhandensein von Anhängen automatisch als bloßes Transportmittel einstufen.
|
||||
- Anhänge dürfen auf bereits bekannte Unterlagen verweisen. Zuverlässiger Inhaltsvergleich, etwa vollständiger Hash mit exakter Quellenidentität, kann einen Vorschlag liefern; gleiches Dateimaterial beweist nicht allein dieselbe fachliche Rolle oder denselben Versand. Eine manuelle Zuordnung ist möglich und als solche unterscheidbar. Abweichende Fassungen sichtbar belassen.
|
||||
- Keine vorgetäuschte Speicher-Deduplizierung: Original-EML enthält ihre Anhänge weiterhin. Ziel ist eine verständliche Darstellung und explizite Identitäts-/Verwendungszuordnung.
|
||||
|
||||
## 5. Übermittelten Stand nachvollziehbar erhalten
|
||||
|
||||
- Ein dokumentierter Versand hält Hauptschriftstück, Anlagenbestand, Reihenfolge und konkrete Fassungen fest. Spätere Bearbeitung der Arbeitsunterlagen, neue Paperless-Fassungen, geänderte Titel oder gelöste Anlagenzuordnungen ändern diesen Stand nicht still.
|
||||
- Minimal eine unveränderliche Versandfassung mit Manifest und tatsächlich wieder abrufbaren Inhalten sichern. Eine vorhandene nachweislich unveränderliche Quellen-/Dateiversion darf referenziert werden; bei veränderlicher Quelle ist ein geschützter Stand der übermittelten Daten erforderlich. Ein Hash oder eine unversionierte Paperless-ID allein erhält den Inhalt nicht. Für unveränderliche Originaldateien vorhandene Speicherung wiederverwenden.
|
||||
- Nachricht und Anhänge eines Nachweis-Originals ebenso konkret identifizieren. Beim Zuordnen einer bestehenden E-Mail bekannte Quelle und Nachricht eindeutig prüfen; keinen beliebigen Zugang oder ähnlich benannten Anhang verwenden.
|
||||
- Nicht vorhandene historische Fassungen nicht nachträglich erfinden. Ein später rekonstruierter Versand bleibt als rekonstruierter/manuell zugeordneter Stand erkennbar. Dokumentation ohne verfügbare Originalfassung darf gespeichert werden, aber keinen vollständigen gesicherten Inhaltsstand vortäuschen. Lücken klar anzeigen; vollständiger Export meldet sie.
|
||||
- Nachträgliche Korrekturen als nachvollziehbare Berichtigung mit Zeitpunkt festhalten. Bestehende Rechte-/Löschregeln gelten weiter, auch für gespeicherte Versandfassungen; daraus keine neue unbegrenzte Aufbewahrung oder undeletbare Parallelablage ableiten. Der technische Entwurf muss Schutz, Speicherung und vorhandenen Löschpfad konkret beschreiben.
|
||||
- Keine starre Kopie zu jedem UI-Klick. Sichern beim bewussten Dokumentieren des Versands, atomar bzw. mit eindeutigem unvollständigem Zustand bei Abruffehlern. Bestehende Arbeitsunterlagen bleiben normal bearbeitbar.
|
||||
|
||||
## 6. Darstellung: Kapitel, Einheit und Chronologie
|
||||
|
||||
### 6.1 Kapitelgrenzen
|
||||
|
||||
- Kapitelköpfe durch zurückhaltend abgesetzte Fläche und eindeutige Typografie von Dokumentzeilen unterscheiden. Unterkapitel mit konsistenter Einrückung und erkennbarem Ende des jeweiligen Bereichs. Keine breiten Karten und großen Leerflächen als Ersatz für Struktur.
|
||||
- Im ausgewählten Kapitel dessen Überschrift nicht unmittelbar darunter identisch wiederholen. Vorgangstitel und ausgewähltes Kapitel eindeutig benennen; Breadcrumbs und tatsächlicher Handlungskontext bleiben erhalten.
|
||||
- Zähler verständlich machen: etwa „2 direkt · 8 in Unterkapiteln“ oder nachvollziehbare Gesamtzahl. Nie eine unbeschriftete direkte Anzahl neben einer sichtbar größeren Gesamtmenge. Sichtbare Zählwerte berücksichtigen Rechte, Filter und die gewählte Darstellung; ausgeblendete Original-/Nachweisvorkommen nicht als vermeintlich sichtbare Zeilen zählen.
|
||||
- Kapitel und Unterkapitel bleiben reine Gliederung. „Einzelbelege“ darf weiterhin ein thematisches Unterkapitel sein, belegt aber keine Anlagen- oder Versandzuordnung.
|
||||
|
||||
### 6.2 Schreiben als kompakte Einheit
|
||||
|
||||
- Hauptschriftstück in einer kompakten Zeile mit Kennzeichnungen „Anlagen n“, „Versand n“ bzw. passendem Kanal und „Nachweise n“. Nur vorhandene Angaben zeigen. Keine dauerhaft aufgeklappten Anlagen-, Versand- und Nachweislisten pro Eintrag.
|
||||
- „Anlagen“ öffnet die geordnete Liste bzw. den bestehenden Leserbereich. Eintrag, Dateityp und ursprüngliches Datum bleiben erkennbar; mobile Navigation nutzt dieselbe Einheit ohne verkleinerte Mehrspaltenansicht. Anlagen sind ausdrücklich als solche benannt und sehen nicht wie Unterkapitel aus.
|
||||
- Derselbe Inhalt wird innerhalb einer gewählten Ansicht nicht ungefragt mehrfach als scheinbar unabhängige Zeile dargestellt. Ein ausdrücklich gewünschtes eigenständiges Vorkommen bleibt möglich und wird als dieselbe Unterlage kenntlich gemacht. Suche, Filter und Direktöffnung können den Inhalt weiterhin auffinden; benötigte Herkunft bleibt erreichbar.
|
||||
- Das Zusammenfassen erfolgt durch die neue ausdrückliche Anlagen-/Nachweisrolle. Allgemeine Antwortbezüge bleiben beim kompakten Bezugsauslöser und verschieben keine Zwischenstücke. Keine verbindenden Klammern über die Chronologie.
|
||||
|
||||
### 6.3 Zwei verständliche Arbeitsansichten
|
||||
|
||||
- **Gliederung:** Kapitel/Unterkapitel und ihre gespeicherte eigene oder fachliche Ordnung bleiben. Schreiben mit Anlagen erscheinen als Einheit. Die bestehende Ordnung nicht beim Erfassen eines Versands umschreiben.
|
||||
- **Chronologie:** Datierte Kommunikation, dokumentierte Versände und eigenständige Notizen/Ereignisse innerhalb des gewählten Vorgangs-/Kapitelbereichs bilden eine durchgehende zeitliche Folge. Datumsgruppen sind möglich, thematische Kapitel unterbrechen die Folge nicht. Kein gleichzeitig daneben angezeigter zweiter Verlauf. Auf-/absteigende Sortierung anbieten und undatierte Einträge kenntlich behandeln.
|
||||
- Ein dokumentierter Versand erscheint am tatsächlichen Versanddatum und verweist auf die gesicherte Fassung des Schreibens mit Anlagen. Er erscheint einmal pro Versand; Hauptschriftstück und reine Nachweis-E-Mail erzeugen dafür nicht zusätzlich identische Ausgangsereignisse. Ein weiterer echter Versand bleibt ein eigenes Ereignis. Eigenständige fachliche E-Mails/Notizen bleiben eigene Ereignisse.
|
||||
- Vorhandene Unterlagen ohne Versand behalten ihre fachliche Datierung. Dokumentdatum, Versanddatum, Zugangsdatum, Nachweisdatum und Erfassungszeitpunkt nicht gleichsetzen. Eine beigefügte Rechnung aus 2023 verschiebt das 2026 versendete Schreiben nicht nach 2023; das Rechnungsdatum bleibt am Inhalt sichtbar.
|
||||
- Ein späterer Zustellvermerk bleibt mit seinem eigenen Datum nachvollziehbar. Ein Nachweis kann aus dem Versand erreichbar sein und zugleich ein eigenständiges Ereignis dokumentieren. Doppelte Darstellung desselben Ereignisses vermeiden; Informationsrolle bewusst erhalten.
|
||||
- Wechsel der Arbeitsansicht ist eine Darstellungswahl, keine Migration der Einträge. Kapitelzuordnung, manuelle Reihenfolge, gewählter Kontext und Rückkehr aus dem Leser bleiben erhalten. Vorhandene geeignete Auswahl-/Sortierbedienung erweitern statt neue verstreute Schalter zu bauen.
|
||||
|
||||
## 7. Kontext, Bestand und bestehende Quellen
|
||||
|
||||
- Alle neuen Beziehungen und Versandverwendungen im geprüften Akten-/Vorgangskontext führen. Kapitel erzeugen keine Rechte; Anlage oder Nachweis sein erzeugt ebenso keine neue Freigabe, Ownership oder Einsicht in Herkunftsvorgänge.
|
||||
- Hauptschriftstück allein lesen zu dürfen verleiht keinen Zugriff auf gesperrte Anlagen/Nachweise. Titel, Vorschau, Parteien, Zähler und gespeicherte Versandfassungen dürfen keine Inhaltsausnahmen umgehen. Lesen, Bearbeiten und Weitergeben/Exportieren weiterhin unterscheiden.
|
||||
- Richtung je Einbindung bleibt erhalten. Das Zuordnen eines lokalen Belegs als Anlage ändert nicht seine eigene Richtung oder die Richtung anderer Dokumente. Der konkrete Ausgangsversand ist ein zusätzliches fachliches Ereignis.
|
||||
- Bestandsmigration additiv und rückwärtskompatibel. Keine vorhandenen Kapitel anhand von Namen automatisch in Schreiben/Anlagen umwandeln und keine Anlage allein wegen Reihenfolge/Unterkapitelposition erkennen.
|
||||
- Für den bestehenden Umgehungsfall einen manuellen Sammelablauf anbieten: im Unterkapitel Unterlagen auswählen, Hauptschriftstück wählen, Anlagen zuordnen und Reihenfolge prüfen. Danach ausdrücklich wählen, ob die zusätzlichen Vorkommen dort bestehen bleiben oder nur die Anlagenansicht verwendet werden soll. Keine stillen Löschungen. Ein überflüssiges Kapitel kann anschließend separat mit der vorhandenen, erklärten Funktion aufgelöst werden.
|
||||
- Paperless bleibt Quelle/Archiv. Neue Manifest-/Versanddaten sind Tsumugu-Fachdaten; kein bidirektionaler Metadatenabgleich als Vorbedingung. Den bestehenden vollständigen E-Mail-/Dateiabruf wiederverwenden und gezielt erweitern.
|
||||
|
||||
## 8. Export als Teil derselben Lieferung
|
||||
|
||||
- Bestehendes Übergabepaket um Anlagenrollen, Versandereignisse, Nachweise und gesicherte Fassungen ergänzen. HTML-/Markdown-Übersicht erklärt Kapitelzugehörigkeit und „Schreiben → Anlagen → Versand → Nachweise“ mit relativen Links, Datumsarten und Herkunft der Fassung. Dateinamen dürfen sich nicht überschreiben.
|
||||
- Die Auswahl zeigt, welche Anlagen/Nachweise beim gewählten Schreiben bzw. Versand enthalten sind. Für einen vollständigen Versandstand müssen die tatsächlich dazugehörenden Bestandteile mitgegeben werden. Bewusstes Abwählen bleibt nach der bisherigen Auswahl nach Vorkommen möglich, kennzeichnet die Ausgabe aber als Auszug dieses Versands; Vollständigkeit nicht behaupten.
|
||||
- Die bestehende Regel F-07c bleibt: Eine ausgewählte E-Mail enthält das vollständige Original mit sämtlichen ursprünglichen Anhängen. Ein separat abgewähltes Anlage-Vorkommen entfernt den Anhang nicht aus der EML. Die Auswahl/Prüfübersicht weist darauf hin. Eine ausgeblendete Nachweiszeile darf den Nachweis nicht versehentlich vom Export ausschließen; der Nutzer muss seine Aufnahme erkennen und wählen können.
|
||||
- Zugriffs- und bestehende Weitergabebefugnisse auch für Nachweise, Anlagen und gespeicherte Fassungen prüfen. Kein Export einer unveränderten vollständigen EML, wenn dessen vollständiger Inhalt im Exportkontext nicht freigegeben ist; verständlich melden statt ungeprüft redigieren oder heimlich auslassen.
|
||||
- Quellenlücken, fehlende historische Fassungen und fehlgeschlagene Abrufe ausdrücklich in der Vollständigkeitsprüfung behandeln. Gesicherte alte Fassungen und aktuelle Arbeitsstände unterscheidbar exportieren; keine aktuelle Datei als historische Versandfassung ausgeben.
|
||||
|
||||
## 9. Technische Umsetzung und Liefergrenze
|
||||
|
||||
Vor Änderungen `AGENTS.md`, aktuellen technischen Entwurf und vorhandene Dokumentation zum Ist-Datenmodell/API/Rechten lesen. Aktuelle Änderungen erhalten. Bestehende Elemente, Einbindungen, Quellidentitäten, Media-Speicherung, Audit/Versionskonflikte, Leser und Export nutzen. Die konkrete Speicherung entscheidet der Coder im Bestand; keine Tabellenstruktur aus diesem Fachauftrag blind übernehmen.
|
||||
|
||||
Zuerst knapp festhalten, welche vorhandenen Modelle erweitert werden und wie Anlagenverwendung, Versandmanifest, wiederabrufbare Fassung und Nachweisrolle voneinander getrennt werden. Technischen Entwurf/API-Dokumentation gezielt aktualisieren und anschließend den gesamten Ablauf implementieren. Nicht nach Spezifikation, leeren Tabellen oder bloßen UI-Attrappen aufhören. Kleine umsetzbare Schritte sind sinnvoll, das Ergebnis muss alle hier beschriebenen Hauptabläufe abdecken.
|
||||
|
||||
Neue API-Mutationen müssen Kontextrechte, fremde IDs, Zyklus-/Doppelzuordnung, Validierung und gleichzeitige Änderungen behandeln. Abruffehler dürfen keinen als vollständig markierten halben Versand erzeugen. Dateien und vertrauliche Daten nicht in öffentlichen Assets oder Logs ablegen. Betrieb, Backup und bestehende Löschpfade müssen die neuen gespeicherten Fassungen einschließen.
|
||||
|
||||
Die kompakte Gestaltung einschließlich vorhandener Symbole, Punkt/Kasten, Aktion über das Richtungszeichen und mobiler Auszüge beibehalten. Keine neue Symbolfamilie oder frei erfundene Logos. Bestehende Funktionsicons verwenden.
|
||||
|
||||
## 10. Abnahme mit synthetischen Daten
|
||||
|
||||
1. Ein Schreiben, drei Anlagen mit verschiedenen Dokumentdaten und ein thematisches Unterkapitel. Anlagen gesammelt zuordnen, ordnen und eine lösen. Nach Neuladen stimmt alles; andere Einbindungen bleiben unverändert.
|
||||
2. Dasselbe Dokument ist Anlage eines zweiten Schreibens in anderem Kontext. Rollen/Reihenfolgen bleiben unabhängig; keine zusätzlichen Rechte und keine Dateikopie zur bloßen Organisation.
|
||||
3. Schreiben per E-Mail dokumentieren, vorhandene vollständige E-Mail als Nachweis zuordnen. Das Original hat dieselben drei Anhänge sowie einen weiteren, abweichenden Anhang. Gleiche Namen und unterschiedliche Inhalte gesondert prüfen. Kein automatisches falsches Zusammenführen, Original vollständig erreichbar und Abweichung sichtbar.
|
||||
4. Bereits eigenständige E-Mail bewusst in reine Nachweisdarstellung überführen und zurück. Andere Einbindung und Original bleiben erhalten. E-Mail mit fachlichem Zusatzinhalt eigenständig belassen und dennoch zuordnen.
|
||||
5. Nach dokumentiertem Versand Arbeitsdokument ändern, Anlagenliste ändern und externe aktuelle Fassung austauschen. Erster Versand bleibt in ursprünglicher Fassung lesbar/exportierbar. Fehlende alte Originale werden als Lücke behandelt, nicht durch aktuelle Dateien ersetzt.
|
||||
6. Zweiten Versand per Post mit anderem Datum, anderer Anlagenzusammenstellung und Einlieferungsbeleg dokumentieren. Spätere Zustellbestätigung ergänzen. Beide Versände und alle Nachweisrollen sind eindeutig; kein automatischer Status „zugestellt“ allein durch Einlieferung.
|
||||
7. Gliederung/Chronologie wechseln. 2023er Anlage in 2026er Versand verschiebt diesen nicht. Späterer Nachweis und eigenständige Rückfrage bleiben datiert. Mehrere unabhängige Zwischenstücke bleiben in Reihenfolge, keine Klammern und keine doppelten Ausgangsereignisse. Filter, Kontext, Rückkehr und eigene Ordnung erhalten.
|
||||
8. In einem Kapitel mit zwei direkten Einträgen und acht Unterkapitel-Inhalten Grenzen und Zähler prüfen. Keine doppelte Kapitelüberschrift. Auf 1280px, 390px und kurz 360px prüfen: klare Hierarchie, kompakte geschlossene Einheiten, Leser/Anlagen/Nachweise per Touch und Tastatur erreichbar. Größere Schrift darf umbrechen.
|
||||
9. Gesperrte Anlage und Nachweis in fremdem Kontext prüfen: weder Inhalt noch Metadaten/Zähler werden offengelegt, neue Fassungen umgehen die Einschränkung nicht. Lesender Nutzer kann keine Zuordnung oder Versanddaten ändern. Fremde IDs serverseitig abweisen.
|
||||
10. Vollständigen historischen Versand und einen bewussten Auszug exportieren. Manifest/Fassungen/Nachweise stimmen, vollständige EML bleibt einschließlich aller Anhänge erhalten; separat abgewählte Vorkommen ändern dies nicht. Fehlende Quellen/Fassungen/Rechte führen zu erklärten Lücken oder gezieltem Abbruch.
|
||||
11. Bestehende Bestandseinträge und Unterkapitel bleiben ohne automatische Umwandlung erhalten. Sammelzuordnung als Anlagen funktioniert; selbst erstellte Schriftstücke ohne Versand sind weiter nutzbar. Allgemeine Bezüge und vorhandenes Exportpaket regressionsprüfen.
|
||||
|
||||
Relevante Backend-/Interaktionsprüfungen für Rollen, gesicherte Fassungen, Kontexte, Export und Fehlerfälle sowie den vorhandenen Frontend-Build ausführen. Vorhandene Tests wiederverwenden und gezielt ergänzen; keine bloßen CSS-/Implementierungs-Abbildtests. Tatsächliche Bedienung und Screenshots synthetischer Beispiele liefern. Geplante, bestandene und blockierte Prüfungen trennen; alte Prüfberichte belegen keinen aktuellen Stand.
|
||||
|
||||
**Übergabepunkt:** lokal prüfbar implementiert, Migration und relevante Doku aktualisiert, Hauptabläufe getestet, Einschränkungen benannt. Kein Commit, Push oder Deployment durch diesen Auftrag. Ein Push auf `develop` startet Development; Production bleibt separat. Keine Nachricht an andere Chats oder externe Empfänger versenden.
|
||||
@@ -1,5 +1,7 @@
|
||||
# Auftrag an Cursor: Unterkapitel in Tsumugu
|
||||
|
||||
**Spätere fachliche Erweiterung, 18.10.2026:** [Schreiben mit Anlagen und Versand/Nachweisen](TSUMUGU_SCHREIBEN_ANLAGEN_VERSAND_AUFTRAG_2026-10-18.md), Produkt F-08b/c. Der folgende Ausschluss eines Hauptdokuments/Dokumentpakets bezeichnet die damalige Liefergrenze. Der neue Auftrag ergänzt diese Funktion gezielt; die Kapitel bleiben unabhängig davon reine Gliederung. Keine automatische Umwandlung bestehender Unterkapitel.
|
||||
|
||||
Stand: 17.10.2026. Vorbereiteter Umsetzungsauftrag nach fachlicher Abstimmung. Dieser Chat hat keine Anwendung implementiert. Der Auftrag wird durch die Übergabe an Cursor erteilt.
|
||||
|
||||
## 1. Ziel und bestätigte Fachentscheidung
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
# Tsumugu – Ergänzung zur Bedienung, Orientierung und Aktenordnung im MVP
|
||||
|
||||
**Stand:** 17.10.2026 · **Fassung:** 0.8, Unterkapitel in der bestehenden Gliederung; Fassung 0.7 zur kompakten Liste bleibt erhalten.
|
||||
**Stand:** 18.10.2026 · **Fassung:** 0.9, klare Kapitelgrenzen, Schreiben mit Anlagen und Versand/Nachweise.
|
||||
|
||||
**Aktueller Ausbau F-08b/c:** [Schreiben, Anlagen, Versand und Kapitelgrenzen – gemeinsamer Auftrag](TSUMUGU_SCHREIBEN_ANLAGEN_VERSAND_AUFTRAG_2026-10-18.md). Anlagen sind eine neue ausdrückliche Inhaltsverwendung; Unterkapitel bleiben thematische Gliederung. Schreiben werden mit ihren Anlagen kompakt dargestellt, Versand mit konkretem übermitteltem Stand und vollständigen Nachweisen dokumentiert. E-Mails bleiben vollständig erhalten, ihre reine Nachweisdarstellung kann redundante Einträge im aktiven Kontext vermeiden. Gliederung und durchgehende Chronologie unterscheiden; keine stillen Datumsänderungen oder Umdeutung allgemeiner Bezüge. Kapitel/Unterkapitel durch Flächen/Typografie/Einrückung abgrenzen, doppelte Überschrift und unklare Zählwerte korrigieren. Kompakte Liste, bestehende Symbole und Kontextrechte bleiben erhalten. Der Auftrag legt die neue Darstellung gegenüber widersprechenden älteren Vorgaben fest; keine Umsetzung wird hiermit als bereits fertig behauptet.
|
||||
|
||||
**Neuester Auftrag F-06f:** [Kompakte Inhaltsliste – vollständige Anforderungen und Cursor-Auftrag](TSUMUGU_KOMPAKTE_INHALTSLISTE_AUFTRAG.md). Diese spätere Präzisierung ersetzt widersprechende ältere Darstellungsvorgaben in diesem Dokument: dauerhaftes Richtungs-Dropdown, nicht anklickbare Richtungsgrafik, fehlendes Zeichen für bewusst Lokal, Kapitelwiederholung und aufgeklappte Bezugskarten/Beziehungsleisten. Richtung direkt über das Zeichen wählen, Lokal als Punkt, Keine Angabe als leerer umrandeter Kasten ohne Checkbox-Semantik, Bezüge nur als kompakter Auslöser. Kapitel-/Vorgangsköpfe und mobile Auszüge verkürzen, Inhaltstypen, Reihenfolge, Rechte und ausführlichen Leser erhalten.
|
||||
|
||||
@@ -309,6 +311,8 @@ Ein Push auf `develop` löst laut Repository einen Development-Deploy aus. Der r
|
||||
|
||||
## 15. Fortschreibung
|
||||
|
||||
- **0.9:** F-08b/c: Hauptschriftstück und Anlagen ausdrücklich zuordnen; Versand mit Nachweisen und abrufbarem übermitteltem Stand. Redundante Nachweis-E-Mails bewusst kompakt darstellen; Original vollständig bewahren. Klare Kapitelgrenzen/Zähler und durchgehende Chronologie präzisiert. Gemeinsamer Auftrag und Abnahmefälle verlinkt.
|
||||
|
||||
- **0.8:** F-08a: verschachtelte Kapitel ohne eigene Rechte. Pfad, Mehrfachauswahl, Umhängen und Auflösen in der bestehenden Navigation und im vorhandenen Export. Teilvorgänge bleiben eigene Objekte.
|
||||
|
||||
- **0.7:** F-06f: konsolidierter Auftrag zur Reduktion der Eintrags- und Kopfhöhe; Richtungszeichen als direkte Bedienung und Punkt für Lokal. Bezugsdetails erst bei Bedarf, keine Klammern/Leisten oder zusätzliche Reihenfolgeänderung. Abnahme mit mehreren unabhängigen Zwischenstücken und vergleichbaren Zeilenhöhen.
|
||||
|
||||
@@ -10,6 +10,8 @@ Die ausgewählte Tsumugu-Oberfläche wird im vorhandenen Produkt umgesetzt. Dara
|
||||
|
||||
## 2. Führende Quellen und gezielte Lesereihenfolge
|
||||
|
||||
**Aktueller Auftrag vom 18.10.2026, Produkt 0.38 / UX 0.9:** [Schreiben mit Anlagen, Versand/Nachweise und Kapitelgrenzen](TSUMUGU_SCHREIBEN_ANLAGEN_VERSAND_AUFTRAG_2026-10-18.md). Der Nutzer beauftragt die Anforderungen und den Cursor-Prompt nach Besprechung der fachlichen Lücke. Anlagenzuordnung und Versand/Nachweise sind neue Funktionen. Hauptschriftstück mit geordneten Anlagen, konkrete übermittelte Fassung, E-Mail/Einlieferungsbeleg als Nachweis, bewusste kompakte Nachweisdarstellung, verständliche Gliederung/Chronologie und bestehender vollständiger Export bilden den nächsten zusammenhängenden Ausbau. Historische Beschränkung „kein Hauptdokument/kein Sammler“ der Unterkapitellieferung ist keine Blockade dieses neuen Auftrags. Unterkapitel, Kontextrechte und ursprüngliche E-Mails bleiben erhalten. Keine Umsetzung, Migration oder Bereitstellung durch diesen Dokumentationsauftrag.
|
||||
|
||||
**Unterkapitel, Produkt 0.37:** [Auftrag Unterkapitel](TSUMUGU_UNTERKAPITEL_AUFTRAG_2026-10-17.md) und F-08a. Unterkapitel sind reine verschachtelte Gliederung ohne eigene Rechte. Die frühere Zurückstellung ist historisch. Kein zusätzlicher Sammler und keine Freigabezusammenstellung.
|
||||
|
||||
**Neueste Präzisierung, Produkt 0.36 / UX 0.7:** [Kompakte Inhaltsliste und Bezüge](TSUMUGU_KOMPAKTE_INHALTSLISTE_AUFTRAG.md) ist der aktuelle UI-Auftrag. Richtung direkt am Zeichen ändern, Lokal als Punkt, Keine Angabe als leerer Kasten. Keine permanenten Dropdowns, Kapitelwiederholungen oder aufgeklappten Bezugskarten. Bezüge bleiben an ihren Listenpositionen und werden erst auf Anforderung aufgefächert; keine Verbindungsklammern/Beziehungsleisten über unabhängige Zwischenstücke. Symbolpaket 1.4 liefert die neuen Einzeldateien. Frühere Versionsangaben und Live-Befunde unten beschreiben den vorherigen Stand; zuletzt war das Notizmotiv korrekt eingebunden. Die fachliche Exportplanung bleibt erhalten.
|
||||
|
||||
+3
-1
@@ -5,9 +5,11 @@ WORKDIR /src
|
||||
COPY package.json package-lock.json ./
|
||||
RUN npm ci
|
||||
|
||||
COPY index.html vite.config.js ./
|
||||
COPY index.html vite.config.js mark-environment.mjs ./
|
||||
COPY public ./public
|
||||
COPY src ./src
|
||||
ARG VITE_TSUMUGU_ENV=production
|
||||
ENV VITE_TSUMUGU_ENV=$VITE_TSUMUGU_ENV
|
||||
RUN npm run build
|
||||
|
||||
FROM nginx:alpine
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
import fs from "node:fs";
|
||||
|
||||
if (process.env.VITE_TSUMUGU_ENV !== "development") {
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
const manifestPath = new URL("./dist/manifest.webmanifest", import.meta.url);
|
||||
const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf8"));
|
||||
manifest.name = "Tsumugu Entwicklung";
|
||||
manifest.short_name = "Tsumugu Dev";
|
||||
manifest.theme_color = "#8a5a12";
|
||||
fs.writeFileSync(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`);
|
||||
|
||||
const indexPath = new URL("./dist/index.html", import.meta.url);
|
||||
const html = fs
|
||||
.readFileSync(indexPath, "utf8")
|
||||
.replace("<title>Tsumugu</title>", "<title>Tsumugu · Entwicklung</title>")
|
||||
.replace('name="apple-mobile-web-app-title" content="Tsumugu"', 'name="apple-mobile-web-app-title" content="Tsumugu Dev"')
|
||||
.replace('name="theme-color" content="#085041"', 'name="theme-color" content="#8a5a12"');
|
||||
fs.writeFileSync(indexPath, html);
|
||||
@@ -4,7 +4,7 @@
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vite build",
|
||||
"build": "vite build && node mark-environment.mjs",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
|
||||
+40
-19
@@ -14,6 +14,17 @@ import { Users } from "./pages/Users.jsx";
|
||||
import { Work } from "./pages/Work.jsx";
|
||||
import { Settings } from "./pages/Settings.jsx";
|
||||
import { Reader } from "./pages/Reader.jsx";
|
||||
import { appTitle, isDevelopment } from "./environment.js";
|
||||
|
||||
function EnvironmentBanner() {
|
||||
useEffect(() => {
|
||||
document.title = appTitle;
|
||||
if (!isDevelopment) return;
|
||||
document.querySelector('meta[name="theme-color"]')?.setAttribute("content", "#8a5a12");
|
||||
}, []);
|
||||
if (!isDevelopment) return null;
|
||||
return <p className="env-banner" role="status">Entwicklungsumgebung</p>;
|
||||
}
|
||||
|
||||
export function App() {
|
||||
const [session, setSession] = useState(undefined);
|
||||
@@ -66,31 +77,41 @@ export function App() {
|
||||
}
|
||||
|
||||
if (session === undefined) {
|
||||
return <p className="boot">Tsumugu wird geladen …</p>;
|
||||
return (
|
||||
<div className="app-root">
|
||||
<EnvironmentBanner />
|
||||
<p className="boot">Tsumugu wird geladen …</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
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="matters/:id/items/:bindingId" element={<Reader />} />
|
||||
<Route path="cases/:id/items/:bindingId" element={<Reader />} />
|
||||
<Route path="work" element={<Work />} />
|
||||
<Route path="settings" element={<Settings />} />
|
||||
<Route path="rooms" element={<Rooms />} />
|
||||
<Route path="sources" element={<Sources />} />
|
||||
<Route path="users" element={<Users />} />
|
||||
<Route path="search" element={<Search />} />
|
||||
</Route>
|
||||
</Routes>
|
||||
<div className="app-root">
|
||||
<EnvironmentBanner />
|
||||
<div className="app-root__main">
|
||||
<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="matters/:id/items/:bindingId" element={<Reader />} />
|
||||
<Route path="cases/:id/items/:bindingId" element={<Reader />} />
|
||||
<Route path="work" element={<Work />} />
|
||||
<Route path="settings" element={<Settings />} />
|
||||
<Route path="rooms" element={<Rooms />} />
|
||||
<Route path="sources" element={<Sources />} />
|
||||
<Route path="users" element={<Users />} />
|
||||
<Route path="search" element={<Search />} />
|
||||
</Route>
|
||||
</Routes>
|
||||
</div>
|
||||
</div>
|
||||
</SessionContext.Provider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { countLabel, sectionCounts } from "./pages/chapters.js";
|
||||
|
||||
test("chapter counts name direct rows and rows in subchapters", () => {
|
||||
assert.equal(countLabel(2, 8), "2 direkt · 8 in Unterkapiteln");
|
||||
assert.equal(countLabel(0, 8), "8 in Unterkapiteln");
|
||||
assert.equal(countLabel(2, 0), "2");
|
||||
const section = {
|
||||
items: [{ id: "a" }, { id: "b" }],
|
||||
children: [{ items: [{ id: "c" }, { id: "d" }, { id: "e" }, { id: "f" }, { id: "g" }, { id: "h" }, { id: "i" }, { id: "j" }], children: [] }],
|
||||
};
|
||||
const counts = sectionCounts(section);
|
||||
assert.equal(countLabel(counts.direct, counts.nested), "2 direkt · 8 in Unterkapiteln");
|
||||
});
|
||||
@@ -0,0 +1,7 @@
|
||||
// Dieselbe Quellfassung läuft nach dem Merge in beiden Deployments.
|
||||
// Development setzt VITE_TSUMUGU_ENV beim Image-Build. Der lokale Vite-Server gilt ebenfalls als Entwicklung.
|
||||
export const isDevelopment =
|
||||
import.meta.env.VITE_TSUMUGU_ENV === "development" ||
|
||||
(import.meta.env.DEV && import.meta.env.VITE_TSUMUGU_ENV !== "production");
|
||||
|
||||
export const appTitle = isDevelopment ? "Tsumugu · Entwicklung" : "Tsumugu";
|
||||
+197
-48
@@ -6,7 +6,7 @@ import { chapterPathLabel, siblingChapterIds, trailWithChapter } from "./chapter
|
||||
import { Modal } from "./Modal.jsx";
|
||||
import { MailPicker, PaperlessPicker } from "./Sources.jsx";
|
||||
import { ErrorNote, ShareBox } from "./widgets.jsx";
|
||||
import { ContentBoard, DirectionChoice, MarkdownEditor, ObjectMenu, OrderChoice, RecordTree, SurfaceView, TargetLine, Trail, WorkLists, WorkSwitch, saveChapterOrder, writeSelection } from "./content.jsx";
|
||||
import { ContentBoard, DateField, 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";
|
||||
@@ -209,12 +209,12 @@ function chapterOrigin(base, chapters, chapterId) {
|
||||
|
||||
function mergedCaseItems(record, direction, caseId) {
|
||||
const rows = [
|
||||
...(record.bindings || []).map((binding) => ({
|
||||
...(record.bindings || []).filter((binding) => binding?.element).map((binding) => ({
|
||||
...binding,
|
||||
origin: chapterOrigin("Direkt in dieser Akte", record.chapters, binding.chapter_id),
|
||||
readerHref: `/cases/${caseId}?eintrag=${binding.id}${binding.chapter_id ? `&kapitel=${binding.chapter_id}` : ""}`,
|
||||
})),
|
||||
...(record.contained || []).flatMap((group) => (group.bindings || []).map((binding) => ({
|
||||
...(record.contained || []).flatMap((group) => (group.bindings || []).filter((binding) => binding?.element).map((binding) => ({
|
||||
...binding,
|
||||
origin: chapterOrigin(matterOrigin(group), group.chapters, binding.chapter_id),
|
||||
readerHref: `/matters/${group.matter_id}?context_kind=case&context_id=${caseId}&eintrag=${binding.id}${binding.chapter_id ? `&kapitel=${binding.chapter_id}` : ""}`,
|
||||
@@ -297,6 +297,7 @@ export function CaseDetail() {
|
||||
const [error, setError] = useState("");
|
||||
const [modal, setModal] = useState("");
|
||||
const [chapterParentId, setChapterParentId] = useState("");
|
||||
const [addChapterId, setAddChapterId] = useState("");
|
||||
const [view, setView] = useState("contents");
|
||||
const [dateDir, setDateDir] = useState("asc");
|
||||
const { width, structureOpen, setStructureOpen } = useWorkspaceLayout();
|
||||
@@ -395,6 +396,14 @@ export function CaseDetail() {
|
||||
}
|
||||
}, [record, id, rawScope, overview, chapterId, params, setParams, navigate]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!record || record.id !== id || overview || !entryId) return;
|
||||
if ((record.bindings || []).some((item) => item.id === entryId)) return;
|
||||
const updated = new URLSearchParams(params);
|
||||
updated.delete("eintrag");
|
||||
setParams(updated, { replace: true });
|
||||
}, [record, id, overview, entryId, params, setParams]);
|
||||
|
||||
useEffect(() => {
|
||||
if (entryId) return;
|
||||
restoreScroll(listRef.current, `tsumugu-scroll:case:${id}:${chapterId}:${overview ? "over" : "direct"}`);
|
||||
@@ -441,6 +450,11 @@ export function CaseDetail() {
|
||||
setModal("chapter");
|
||||
}
|
||||
|
||||
function openAdd(targetChapterId = chapterId) {
|
||||
setAddChapterId(targetChapterId || "");
|
||||
setModal("add");
|
||||
}
|
||||
|
||||
async function moveChapter(chapterIdToMove, delta) {
|
||||
const ids = siblingChapterIds(record?.chapters || [], chapterIdToMove);
|
||||
const index = ids.indexOf(chapterIdToMove);
|
||||
@@ -480,7 +494,7 @@ export function CaseDetail() {
|
||||
width={width}
|
||||
structureOpen={structureOpen}
|
||||
setStructureOpen={setStructureOpen}
|
||||
hasEntry={Boolean(entryId) && !overview}
|
||||
hasEntry={Boolean(entry) && !overview}
|
||||
listRef={listRef}
|
||||
nav={(
|
||||
<StructureNavigator
|
||||
@@ -505,7 +519,7 @@ export function CaseDetail() {
|
||||
onClose={width < 1500 ? () => setStructureOpen(false) : null}
|
||||
/>
|
||||
)}
|
||||
reader={entryId && !overview ? (
|
||||
reader={entry ? (
|
||||
<ReadingPane
|
||||
binding={entry}
|
||||
context={context}
|
||||
@@ -532,7 +546,7 @@ export function CaseDetail() {
|
||||
<div className="page-actions">
|
||||
{width < 1500 ? <button type="button" className="quiet" onClick={() => setStructureOpen(true)}>Struktur</button> : null}
|
||||
{canEdit ? (
|
||||
<button type="button" className="desktop-add" onClick={() => setModal("add")}>
|
||||
<button type="button" className="desktop-add" onClick={() => openAdd(chapterId)}>
|
||||
<NavIcon name="plus" /> Inhalt hinzufügen
|
||||
</button>
|
||||
) : null}
|
||||
@@ -575,6 +589,7 @@ export function CaseDetail() {
|
||||
selectedId={entryId}
|
||||
listTitle={activeChapter ? chapterPathLabel(record.chapters, activeChapter.id) : "Direkt in dieser Akte"}
|
||||
onAddSubchapter={canEdit ? openChapter : null}
|
||||
onAddContent={canEdit ? openAdd : null}
|
||||
context={context}
|
||||
onOpen={openEntry}
|
||||
onChange={load}
|
||||
@@ -601,7 +616,7 @@ export function CaseDetail() {
|
||||
</div>
|
||||
) : null}
|
||||
{canEdit && view === "contents" && !overview ? (
|
||||
<button type="button" className="mobile-add" onClick={() => setModal("add")}>
|
||||
<button type="button" className="mobile-add" onClick={() => openAdd(chapterId)}>
|
||||
<NavIcon name="plus" /> Inhalt hinzufügen
|
||||
</button>
|
||||
) : null}
|
||||
@@ -614,10 +629,10 @@ export function CaseDetail() {
|
||||
</Modal>
|
||||
<Modal open={modal === "add"} title={`Hinzufügen in ${targetLabel}`} onClose={() => setModal("")}>
|
||||
<p className="muted">Dieser Inhalt liegt direkt in der Akte. Er erscheint unter „Direkt in dieser Akte“ und im Überblick, nicht in einem Vorgang.</p>
|
||||
<TargetLine label={targetLabel} chapters={record.chapters} chapterId={activeChapter?.id || ""} />
|
||||
<TargetLine label={targetLabel} chapters={record.chapters} chapterId={addChapterId} />
|
||||
<div className="add-choices">
|
||||
<button type="button" onClick={() => openChapter(activeChapter?.id || "")}>{activeChapter ? "Unterkapitel" : "Kapitel"}</button>
|
||||
{activeChapter ? <button type="button" onClick={() => openChapter("")}>Kapitel auf oberster Ebene</button> : null}
|
||||
<button type="button" onClick={() => openChapter(addChapterId)}>{addChapterId ? "Unterkapitel" : "Kapitel"}</button>
|
||||
{addChapterId ? <button type="button" onClick={() => openChapter("")}>Kapitel auf oberster Ebene</button> : null}
|
||||
<button type="button" onClick={() => setModal("note")}>Notiz</button>
|
||||
<button type="button" onClick={() => setModal("file")}>Datei</button>
|
||||
<button type="button" onClick={() => setModal("paperless")}>Paperless</button>
|
||||
@@ -625,16 +640,16 @@ export function CaseDetail() {
|
||||
</div>
|
||||
</Modal>
|
||||
<Modal open={modal === "note"} title="Notiz" onClose={() => setModal("")}>
|
||||
<NoteForm context={context} chapters={record.chapters} initialChapter={activeChapter?.id || ""} targetLabel={targetLabel} onChange={() => { setModal(""); load(); }} />
|
||||
<NoteForm context={context} chapters={record.chapters} initialChapter={addChapterId} targetLabel={targetLabel} onChange={() => { setModal(""); load(); }} />
|
||||
</Modal>
|
||||
<Modal open={modal === "file"} title="Datei" onClose={() => setModal("")}>
|
||||
<FileForm context={context} chapters={record.chapters} initialChapter={activeChapter?.id || ""} targetLabel={targetLabel} onChange={() => { setModal(""); load(); }} />
|
||||
<FileForm context={context} chapters={record.chapters} initialChapter={addChapterId} targetLabel={targetLabel} onChange={(finished = true) => { load(); if (finished) setModal(""); }} />
|
||||
</Modal>
|
||||
<Modal open={modal === "paperless"} title="Aus Paperless" onClose={() => setModal("")}>
|
||||
<PaperlessPicker context={context} chapterId={activeChapter?.id || ""} chapterTitle={activeChapter ? chapterPathLabel(record.chapters, activeChapter.id) : ""} targetLabel={targetLabel} onDone={() => { setModal(""); load(); }} />
|
||||
<PaperlessPicker context={context} chapterId={addChapterId} chapterTitle={addChapterId ? chapterPathLabel(record.chapters, addChapterId) : ""} targetLabel={targetLabel} onInserted={load} onDone={() => { setModal(""); load(); }} />
|
||||
</Modal>
|
||||
<Modal open={modal === "mail"} title="E-Mail verbinden" wide split onClose={() => setModal("")}>
|
||||
<MailPicker context={context} chapterId={activeChapter?.id || ""} chapterTitle={activeChapter ? chapterPathLabel(record.chapters, activeChapter.id) : ""} targetLabel={targetLabel} onDone={() => { setModal(""); load(); }} />
|
||||
<MailPicker context={context} chapterId={addChapterId} chapterTitle={addChapterId ? chapterPathLabel(record.chapters, addChapterId) : ""} targetLabel={targetLabel} onDone={() => { setModal(""); load(); }} />
|
||||
</Modal>
|
||||
<Modal open={modal === "subcase"} title="Unterakte anlegen" onClose={() => setModal("")}>
|
||||
<NewSubcase parentId={id} onChange={() => { setModal(""); load(); }} />
|
||||
@@ -655,7 +670,7 @@ export function CaseDetail() {
|
||||
/>
|
||||
</Modal>
|
||||
<Modal open={modal === "share"} title="Teilen" onClose={() => setModal("")}>
|
||||
<ShareBox path={`/api/v1/cases/${id}/grants`} grants={record.grants || []} onChange={load} />
|
||||
<ShareBox path={`/api/v1/cases/${id}/grants`} grants={record.grants || []} onChange={load} allowSources={Boolean(record.is_owner)} />
|
||||
</Modal>
|
||||
</>
|
||||
);
|
||||
@@ -846,7 +861,7 @@ export function ChapterForm({ path, onChange, targetLabel = "", parentChapter =
|
||||
{parentChapter ? <>Elternkapitel: <strong>{parentChapter.title}</strong></> : <>Ebene: <strong>oberste Kapitel</strong></>}
|
||||
</p>
|
||||
<label>Titel <input value={title} onChange={(event) => setTitle(event.target.value)} placeholder={parentChapter ? "Unterkapitel" : "Kapitel"} required /></label>
|
||||
<label>Fachliches Datum, optional <input type="date" value={dated} onChange={(event) => setDated(event.target.value)} /></label>
|
||||
<label>Fachliches Datum, optional <DateField value={dated} onChange={setDated} /></label>
|
||||
<button type="submit">Hinzufügen</button>
|
||||
<ErrorNote error={error} />
|
||||
</form>
|
||||
@@ -863,12 +878,12 @@ export function ContentForms({ context, placement, chapters, onChange }) {
|
||||
);
|
||||
}
|
||||
|
||||
function chapterSelect(chapters, value, setValue) {
|
||||
function chapterSelect(chapters, value, setValue, disabled = false) {
|
||||
if (!chapters?.length) return null;
|
||||
return (
|
||||
<label>
|
||||
Kapitel
|
||||
<select value={value} onChange={(event) => setValue(event.target.value)}>
|
||||
<select value={value} disabled={disabled} onChange={(event) => setValue(event.target.value)}>
|
||||
<option value="">Ohne Kapitel</option>
|
||||
{chapters.map((chapter) => (
|
||||
<option key={chapter.id} value={chapter.id}>{chapterPathLabel(chapters, chapter.id)}</option>
|
||||
@@ -878,6 +893,12 @@ function chapterSelect(chapters, value, setValue) {
|
||||
);
|
||||
}
|
||||
|
||||
function titleFromFilename(name) {
|
||||
const trimmed = (name || "").trim();
|
||||
const stem = trimmed.replace(/\.[^.]+$/, "").trim();
|
||||
return (stem || trimmed || "Datei").slice(0, 200);
|
||||
}
|
||||
|
||||
export function NoteForm({ context, placement, chapters = [], initialChapter = "", targetLabel = "", onChange }) {
|
||||
const [title, setTitle] = useState("");
|
||||
const [text, setText] = useState("");
|
||||
@@ -937,9 +958,9 @@ export function NoteForm({ context, placement, chapters = [], initialChapter = "
|
||||
<label>Titel <input value={title} onChange={(event) => { setTitle(event.target.value); markDirty(true); }} required /></label>
|
||||
<MarkdownEditor value={text} onChange={(value) => { setText(value); markDirty(true); }} rows={8} />
|
||||
<DirectionChoice value={direction} onChange={(value) => { setDirection(value); markDirty(true); }} />
|
||||
<label>Bezugsdatum, optional <input type="date" value={documentOn} onChange={(event) => setDocumentOn(event.target.value)} /></label>
|
||||
<label>Versand, optional <input type="date" value={sentOn} onChange={(event) => setSentOn(event.target.value)} /></label>
|
||||
<label>Zugang, optional <input type="date" value={receivedOn} onChange={(event) => setReceivedOn(event.target.value)} /></label>
|
||||
<label>Bezugsdatum, optional <DateField value={documentOn} onChange={setDocumentOn} /></label>
|
||||
<label>Versand, optional <DateField value={sentOn} onChange={setSentOn} /></label>
|
||||
<label>Zugang, optional <DateField value={receivedOn} onChange={setReceivedOn} /></label>
|
||||
{chapterSelect(chapters, chapterId, setChapterId)}
|
||||
<button type="submit" disabled={pending}>{pending ? "Wird angelegt …" : "Notiz anlegen"}</button>
|
||||
<ErrorNote error={error} />
|
||||
@@ -949,22 +970,68 @@ export function NoteForm({ context, placement, chapters = [], initialChapter = "
|
||||
|
||||
export function FileForm({ context, placement, chapters = [], initialChapter = "", targetLabel = "", onChange }) {
|
||||
const [title, setTitle] = useState("");
|
||||
const [file, setFile] = useState(null);
|
||||
const [files, setFiles] = useState([]);
|
||||
const [chapterId, setChapterId] = useState(initialChapter);
|
||||
const [documentOn, setDocumentOn] = useState("");
|
||||
const [sentOn, setSentOn] = useState("");
|
||||
const [receivedOn, setReceivedOn] = useState("");
|
||||
const [direction, setDirection] = useState("");
|
||||
const [error, setError] = useState("");
|
||||
const [pending, setPending] = useState(false);
|
||||
const [progress, setProgress] = useState(null);
|
||||
const inputRef = useRef(null);
|
||||
const fileSerial = useRef(0);
|
||||
|
||||
useEffect(() => { setChapterId(initialChapter || ""); }, [initialChapter]);
|
||||
|
||||
async function submit(event) {
|
||||
event.preventDefault();
|
||||
if (!file) return;
|
||||
function nextFileKey() {
|
||||
fileSerial.current += 1;
|
||||
return `datei-${fileSerial.current}`;
|
||||
}
|
||||
|
||||
function chooseFiles(list) {
|
||||
const picked = Array.from(list || []);
|
||||
if (inputRef.current) inputRef.current.value = "";
|
||||
if (!picked.length) return;
|
||||
const carried = title.trim().slice(0, 200);
|
||||
const additions = picked.map((file) => ({
|
||||
key: nextFileKey(),
|
||||
file,
|
||||
title: titleFromFilename(file.name),
|
||||
}));
|
||||
setFiles((current) => {
|
||||
const batch = current.length === 0 && carried
|
||||
? [{ ...additions[0], title: carried }, ...additions.slice(1)]
|
||||
: additions;
|
||||
return [...current, ...batch];
|
||||
});
|
||||
markDirty(true);
|
||||
}
|
||||
|
||||
function setSingleTitle(value) {
|
||||
markDirty(true);
|
||||
if (files.length === 1) {
|
||||
const key = files[0].key;
|
||||
setFiles((current) => current.map((item) => (item.key === key ? { ...item, title: value } : item)));
|
||||
return;
|
||||
}
|
||||
setTitle(value);
|
||||
}
|
||||
|
||||
function setFileTitle(key, value) {
|
||||
markDirty(true);
|
||||
setFiles((current) => current.map((item) => (item.key === key ? { ...item, title: value } : item)));
|
||||
}
|
||||
|
||||
function removeFile(key) {
|
||||
if (files.length === 1 && files[0].key === key) setTitle(files[0].title);
|
||||
setFiles((current) => current.filter((item) => item.key !== key));
|
||||
}
|
||||
|
||||
async function uploadFile(item) {
|
||||
const form = new FormData();
|
||||
form.set("title", title);
|
||||
form.set("upload", file);
|
||||
form.set("title", item.title.trim());
|
||||
form.set("upload", item.file);
|
||||
form.set("context_kind", context.kind);
|
||||
form.set("context_id", context.id);
|
||||
if (placement) {
|
||||
@@ -976,30 +1043,112 @@ export function FileForm({ context, placement, chapters = [], initialChapter = "
|
||||
if (sentOn) form.set("sent_on", sentOn);
|
||||
if (receivedOn) form.set("received_on", receivedOn);
|
||||
if (direction === "in" || direction === "out" || direction === "local") form.set("communication_direction", direction);
|
||||
setError("");
|
||||
try {
|
||||
await api("/api/v1/files", { method: "POST", form });
|
||||
setTitle("");
|
||||
setFile(null);
|
||||
markDirty(false);
|
||||
onChange();
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
}
|
||||
await api("/api/v1/files", { method: "POST", form });
|
||||
}
|
||||
|
||||
async function submit(event) {
|
||||
event.preventDefault();
|
||||
if (pending) return;
|
||||
if (!files.length) {
|
||||
setError("Bitte mindestens eine Datei auswählen.");
|
||||
return;
|
||||
}
|
||||
const batch = files.map((item) => ({ ...item, title: item.title.trim() }));
|
||||
if (batch.some((item) => !item.title || item.title.length > 200)) {
|
||||
setError("Jeder Titel muss vorhanden und höchstens 200 Zeichen lang sein.");
|
||||
return;
|
||||
}
|
||||
setError("");
|
||||
setPending(true);
|
||||
const remaining = [];
|
||||
let failed = null;
|
||||
let uploaded = 0;
|
||||
try {
|
||||
for (let index = 0; index < batch.length; index += 1) {
|
||||
const item = batch[index];
|
||||
setProgress({ current: index + 1, total: batch.length });
|
||||
try {
|
||||
await uploadFile(item);
|
||||
uploaded += 1;
|
||||
} catch (err) {
|
||||
failed = { name: item.file.name, message: err.message };
|
||||
remaining.push(item, ...batch.slice(index + 1));
|
||||
break;
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
setPending(false);
|
||||
setProgress(null);
|
||||
}
|
||||
if (failed) {
|
||||
setFiles(remaining);
|
||||
setError(uploaded
|
||||
? `„${failed.name}“ wurde nicht eingebunden. ${failed.message} Bereits eingebundene Dateien bleiben erhalten.`
|
||||
: `„${failed.name}“ wurde nicht eingebunden. ${failed.message}`);
|
||||
if (uploaded) onChange(false);
|
||||
return;
|
||||
}
|
||||
setTitle("");
|
||||
setFiles([]);
|
||||
markDirty(false);
|
||||
onChange();
|
||||
}
|
||||
|
||||
const singleTitle = files.length === 1 ? files[0].title : title;
|
||||
const submitLabel = pending
|
||||
? (progress ? `Datei ${progress.current} von ${progress.total} wird eingebunden …` : "Wird hinzugefügt …")
|
||||
: (files.length > 1 ? `${files.length} Dateien hinzufügen` : "Datei hinzufügen");
|
||||
|
||||
return (
|
||||
<form onSubmit={submit} className="stack compact">
|
||||
<TargetLine label={targetLabel} chapters={chapters} chapterId={chapterId} />
|
||||
<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>
|
||||
<DirectionChoice value={direction} onChange={setDirection} />
|
||||
{chapterSelect(chapters, chapterId, setChapterId)}
|
||||
<button type="submit">Datei hinzufügen</button>
|
||||
{files.length <= 1 ? (
|
||||
<label>
|
||||
Titel
|
||||
<input value={singleTitle} onChange={(event) => setSingleTitle(event.target.value)} placeholder="Titel des Schreibens" maxLength={200} required={files.length === 1} disabled={pending} />
|
||||
</label>
|
||||
) : null}
|
||||
<label>
|
||||
Dateien
|
||||
<input
|
||||
ref={inputRef}
|
||||
type="file"
|
||||
multiple
|
||||
accept="application/pdf,image/png,image/jpeg,image/webp"
|
||||
onChange={(event) => chooseFiles(event.target.files)}
|
||||
disabled={pending}
|
||||
/>
|
||||
</label>
|
||||
<p className="muted">Mehrere Dateien können gleichzeitig ausgewählt werden. Jede Datei wird einzeln eingebunden.</p>
|
||||
{files.length === 1 ? (
|
||||
<div className="file-batch__file">
|
||||
<span className="muted">{files[0].file.name}</span>
|
||||
<button type="button" className="quiet" onClick={() => removeFile(files[0].key)} disabled={pending}>Entfernen</button>
|
||||
</div>
|
||||
) : null}
|
||||
{files.length > 1 ? (
|
||||
<>
|
||||
<ul className="file-batch">
|
||||
{files.map((item) => (
|
||||
<li key={item.key}>
|
||||
<label>
|
||||
{`Titel · ${item.file.name}`}
|
||||
<input value={item.title} onChange={(event) => setFileTitle(item.key, event.target.value)} maxLength={200} required disabled={pending} />
|
||||
</label>
|
||||
<button type="button" className="quiet file-batch__remove" onClick={() => removeFile(item.key)} disabled={pending}>Entfernen</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<p className="muted">Dokumentdatum, Versand, Zugang, Richtung und Kapitel gelten für alle ausgewählten Dateien.</p>
|
||||
</>
|
||||
) : null}
|
||||
<label>Dokumentdatum <DateField value={documentOn} onChange={setDocumentOn} disabled={pending} /></label>
|
||||
<label>Versand <DateField value={sentOn} onChange={setSentOn} disabled={pending} /></label>
|
||||
<label>Zugang <DateField value={receivedOn} onChange={setReceivedOn} disabled={pending} /></label>
|
||||
<DirectionChoice value={direction} onChange={setDirection} disabled={pending} />
|
||||
{chapterSelect(chapters, chapterId, setChapterId, pending)}
|
||||
<button type="submit" disabled={pending || !files.length}>{submitLabel}</button>
|
||||
<ErrorNote error={error} />
|
||||
</form>
|
||||
);
|
||||
@@ -1055,9 +1204,9 @@ function ExternalForm({ context, placement, chapters = [], initialChapter = "",
|
||||
<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>
|
||||
<label>Dokumentdatum <DateField value={documentOn} onChange={setDocumentOn} /></label>
|
||||
<label>Versand <DateField value={sentOn} onChange={setSentOn} /></label>
|
||||
<label>Zugang <DateField value={receivedOn} onChange={setReceivedOn} /></label>
|
||||
{chapterSelect(chapters, chapterId, setChapterId)}
|
||||
<button type="submit">Referenz erfassen</button>
|
||||
<ErrorNote error={error} />
|
||||
|
||||
@@ -4,7 +4,7 @@ import { symbolUrl } from "../content-symbol.mjs";
|
||||
|
||||
function leafIds(node, into = []) {
|
||||
if (!node) return into;
|
||||
if (node.kind === "binding" || node.kind === "annotation") into.push(node.id);
|
||||
if (node.kind === "binding" || node.kind === "annotation" || node.kind === "attachment" || node.kind === "dispatch_item" || node.kind === "evidence") into.push(node.id);
|
||||
(node.children || []).forEach((child) => leafIds(child, into));
|
||||
return into;
|
||||
}
|
||||
@@ -30,7 +30,7 @@ function withNode(node, selected, on) {
|
||||
function initialSelection(node) {
|
||||
const next = new Set();
|
||||
function visit(current) {
|
||||
if ((current.kind === "binding" || current.kind === "annotation") && current.exportable) {
|
||||
if ((current.kind === "binding" || current.kind === "annotation" || current.kind === "attachment" || current.kind === "dispatch_item" || current.kind === "evidence") && current.exportable) {
|
||||
next.add(current.id);
|
||||
}
|
||||
(current.children || []).forEach(visit);
|
||||
|
||||
@@ -7,7 +7,7 @@ import { MailPicker, PaperlessPicker } from "./Sources.jsx";
|
||||
import { ErrorNote, ShareBox } from "./widgets.jsx";
|
||||
import { chapterPathLabel, siblingChapterIds, trailWithChapter } from "./chapters.js";
|
||||
import { ChapterForm, FileForm, NoteForm } from "./Cases.jsx";
|
||||
import { ContentBoard, ObjectMenu, Placements, RecordTree, SurfaceView, TargetLine, Trail, WorkLists, WorkSwitch, matterOpenHref, saveChapterOrder, writeChapter } from "./content.jsx";
|
||||
import { ContentBoard, DateField, ObjectMenu, Placements, RecordTree, SurfaceView, TargetLine, Trail, WorkLists, WorkSwitch, matterOpenHref, saveChapterOrder, writeChapter } from "./content.jsx";
|
||||
import { ReadingPane } from "./ReadingPane.jsx";
|
||||
import { StructureNavigator, Workspace, rememberScroll, restoreScroll, useWorkspaceLayout } from "./workspace.jsx";
|
||||
import { NavIcon } from "./icons.jsx";
|
||||
@@ -171,7 +171,7 @@ function placementNodes(record) {
|
||||
...rooted,
|
||||
...cases.map((item) => ({
|
||||
id: item.case_id,
|
||||
title: item.label.replaceAll("Unterakte ", "").replaceAll("Akte ", "").replaceAll(" → ", " / "),
|
||||
title: String(item.label || "Akte").replaceAll("Unterakte ", "").replaceAll("Akte ", "").replaceAll(" → ", " / "),
|
||||
kind: "Akte",
|
||||
href: `/matters/${record.id}?context_kind=case&context_id=${item.case_id}`,
|
||||
current: false,
|
||||
@@ -199,6 +199,7 @@ export function MatterDetail() {
|
||||
const [error, setError] = useState("");
|
||||
const [modal, setModal] = useState("");
|
||||
const [chapterParentId, setChapterParentId] = useState("");
|
||||
const [addChapterId, setAddChapterId] = useState("");
|
||||
const rightsContext = inherited || { kind: "matter", id };
|
||||
const placement = inherited?.kind === "case" ? { kind: "matter", id } : null;
|
||||
const [view, setView] = useState("contents");
|
||||
@@ -327,6 +328,14 @@ export function MatterDetail() {
|
||||
};
|
||||
}, [inherited?.kind, inherited?.id]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!record || record.id !== id || !entryId) return;
|
||||
if ((record.bindings || []).some((item) => item.id === entryId)) return;
|
||||
const updated = new URLSearchParams(params);
|
||||
updated.delete("eintrag");
|
||||
setParams(updated, { replace: true });
|
||||
}, [record, id, entryId, params, setParams]);
|
||||
|
||||
useEffect(() => {
|
||||
if (entryId) return;
|
||||
restoreScroll(listRef.current, `tsumugu-scroll:${id}:${chapterId}`);
|
||||
@@ -374,6 +383,11 @@ export function MatterDetail() {
|
||||
setModal("chapter");
|
||||
}
|
||||
|
||||
function openAdd(targetChapterId = chapterId) {
|
||||
setAddChapterId(targetChapterId || "");
|
||||
setModal("add");
|
||||
}
|
||||
|
||||
async function moveChapter(chapterIdToMove, delta) {
|
||||
const ids = siblingChapterIds(record?.chapters || [], chapterIdToMove);
|
||||
const index = ids.indexOf(chapterIdToMove);
|
||||
@@ -402,10 +416,10 @@ export function MatterDetail() {
|
||||
}));
|
||||
const contexts = (record.placements || []).map((item) => ({
|
||||
id: item.case_id,
|
||||
label: item.label.replaceAll("Unterakte ", "").replaceAll("Akte ", "").replaceAll(" → ", " / "),
|
||||
label: String(item.label || "Akte").replaceAll("Unterakte ", "").replaceAll("Akte ", "").replaceAll(" → ", " / "),
|
||||
}));
|
||||
const contextValue = inherited?.kind === "case" ? inherited.id : (contexts.length === 1 ? contexts[0].id : "");
|
||||
const nodes = caseTree ? caseNodes(caseTree, parentTree, id, inherited.id) : placementNodes(record);
|
||||
const nodes = caseTree && inherited ? caseNodes(caseTree, parentTree, id, inherited.id) : placementNodes(record);
|
||||
const links = [
|
||||
...(record.cross_links || []).map((item) => ({
|
||||
id: `cross-${item.id}`,
|
||||
@@ -429,7 +443,7 @@ export function MatterDetail() {
|
||||
width={width}
|
||||
structureOpen={structureOpen}
|
||||
setStructureOpen={setStructureOpen}
|
||||
hasEntry={Boolean(entryId)}
|
||||
hasEntry={Boolean(entry)}
|
||||
listRef={listRef}
|
||||
nav={(
|
||||
<StructureNavigator
|
||||
@@ -439,6 +453,7 @@ export function MatterDetail() {
|
||||
nodes={nodes}
|
||||
chapters={chapters}
|
||||
chapterId={chapterId}
|
||||
allLabel=""
|
||||
allCount={(record.bindings || []).length}
|
||||
chapterHeading={`Kapitel in ${record.title}`}
|
||||
onChapter={chooseChapter}
|
||||
@@ -452,7 +467,7 @@ export function MatterDetail() {
|
||||
onClose={width < 1500 ? () => setStructureOpen(false) : null}
|
||||
/>
|
||||
)}
|
||||
reader={entryId ? (
|
||||
reader={entry ? (
|
||||
<ReadingPane
|
||||
binding={entry}
|
||||
context={rightsContext}
|
||||
@@ -468,6 +483,7 @@ export function MatterDetail() {
|
||||
/>
|
||||
) : null}
|
||||
>
|
||||
<div className="workspace-pin">
|
||||
<header className="workspace-head">
|
||||
<div>
|
||||
<Trail items={trailWithChapter(record.trail?.length ? record.trail : objectTrail(record, query), record.chapters, chapterId, `/matters/${id}${query}`)} />
|
||||
@@ -480,7 +496,7 @@ export function MatterDetail() {
|
||||
<div className="page-actions">
|
||||
{width < 1500 ? <button type="button" className="quiet" onClick={() => setStructureOpen(true)}>Struktur</button> : null}
|
||||
{canEdit ? (
|
||||
<button type="button" className="desktop-add" onClick={() => setModal("add")}>
|
||||
<button type="button" className="desktop-add" onClick={() => openAdd(chapterId)}>
|
||||
<NavIcon name="plus" /> Inhalt hinzufügen
|
||||
</button>
|
||||
) : null}
|
||||
@@ -499,6 +515,7 @@ export function MatterDetail() {
|
||||
{!canEdit ? <p className="muted">In {targetLabel} fehlt das Bearbeitungsrecht.</p> : null}
|
||||
<ErrorNote error={error} />
|
||||
<WorkSwitch view={view} onView={setView} />
|
||||
</div>
|
||||
{view === "contents" ? (
|
||||
<ContentBoard
|
||||
record={record}
|
||||
@@ -509,6 +526,7 @@ export function MatterDetail() {
|
||||
selectedId={entryId}
|
||||
listTitle={activeChapter ? chapterPathLabel(record.chapters, activeChapter.id) : "Alle Inhalte"}
|
||||
onAddSubchapter={canEdit ? openChapter : null}
|
||||
onAddContent={canEdit ? openAdd : null}
|
||||
onOpen={(binding) => {
|
||||
rememberScroll(listRef.current, scrollKey);
|
||||
openEntry(binding);
|
||||
@@ -544,7 +562,7 @@ export function MatterDetail() {
|
||||
</div>
|
||||
) : null}
|
||||
{canEdit && view === "contents" ? (
|
||||
<button type="button" className="mobile-add" onClick={() => setModal("add")}>
|
||||
<button type="button" className="mobile-add" onClick={() => openAdd(chapterId)}>
|
||||
<NavIcon name="plus" /> Inhalt hinzufügen
|
||||
</button>
|
||||
) : null}
|
||||
@@ -556,10 +574,10 @@ export function MatterDetail() {
|
||||
<WorkForms matterId={id} context={inherited} deadlines={record.deadlines || []} onChange={() => { setModal(""); load(); }} />
|
||||
</Modal>
|
||||
<Modal open={modal === "add"} title={`Hinzufügen in ${targetLabel}`} onClose={() => setModal("")}>
|
||||
<TargetLine label={targetLabel} chapters={record.chapters} chapterId={activeChapter?.id || ""} />
|
||||
<TargetLine label={targetLabel} chapters={record.chapters} chapterId={addChapterId} />
|
||||
<div className="add-choices">
|
||||
<button type="button" onClick={() => openChapter(activeChapter?.id || "")}>{activeChapter ? "Unterkapitel" : "Kapitel"}</button>
|
||||
{activeChapter ? <button type="button" onClick={() => openChapter("")}>Kapitel auf oberster Ebene</button> : null}
|
||||
<button type="button" onClick={() => openChapter(addChapterId)}>{addChapterId ? "Unterkapitel" : "Kapitel"}</button>
|
||||
{addChapterId ? <button type="button" onClick={() => openChapter("")}>Kapitel auf oberster Ebene</button> : null}
|
||||
<button type="button" onClick={() => setModal("note")}>Notiz</button>
|
||||
<button type="button" onClick={() => setModal("file")}>Datei</button>
|
||||
<button type="button" onClick={() => setModal("paperless")}>Paperless</button>
|
||||
@@ -567,16 +585,16 @@ export function MatterDetail() {
|
||||
</div>
|
||||
</Modal>
|
||||
<Modal open={modal === "note"} title="Notiz" onClose={() => setModal("")}>
|
||||
<NoteForm context={rightsContext} placement={placement} chapters={record.chapters} initialChapter={activeChapter?.id || ""} targetLabel={targetLabel} onChange={() => { setModal(""); load(); }} />
|
||||
<NoteForm context={rightsContext} placement={placement} chapters={record.chapters} initialChapter={addChapterId} targetLabel={targetLabel} onChange={() => { setModal(""); load(); }} />
|
||||
</Modal>
|
||||
<Modal open={modal === "file"} title="Datei" onClose={() => setModal("")}>
|
||||
<FileForm context={rightsContext} placement={placement} chapters={record.chapters} initialChapter={activeChapter?.id || ""} targetLabel={targetLabel} onChange={() => { setModal(""); load(); }} />
|
||||
<FileForm context={rightsContext} placement={placement} chapters={record.chapters} initialChapter={addChapterId} targetLabel={targetLabel} onChange={(finished = true) => { load(); if (finished) setModal(""); }} />
|
||||
</Modal>
|
||||
<Modal open={modal === "paperless"} title="Aus Paperless" onClose={() => setModal("")}>
|
||||
<PaperlessPicker context={rightsContext} placement={placement} chapterId={activeChapter?.id || ""} chapterTitle={activeChapter ? chapterPathLabel(record.chapters, activeChapter.id) : ""} targetLabel={targetLabel} onDone={() => { setModal(""); load(); }} />
|
||||
<PaperlessPicker context={rightsContext} placement={placement} chapterId={addChapterId} chapterTitle={addChapterId ? chapterPathLabel(record.chapters, addChapterId) : ""} targetLabel={targetLabel} onInserted={load} onDone={() => { setModal(""); load(); }} />
|
||||
</Modal>
|
||||
<Modal open={modal === "mail"} title="E-Mail verbinden" wide split onClose={() => setModal("")}>
|
||||
<MailPicker context={rightsContext} placement={placement} chapterId={activeChapter?.id || ""} chapterTitle={activeChapter ? chapterPathLabel(record.chapters, activeChapter.id) : ""} targetLabel={targetLabel} onDone={() => { setModal(""); load(); }} />
|
||||
<MailPicker context={rightsContext} placement={placement} chapterId={addChapterId} chapterTitle={addChapterId ? chapterPathLabel(record.chapters, addChapterId) : ""} targetLabel={targetLabel} onDone={() => { setModal(""); load(); }} />
|
||||
</Modal>
|
||||
<Modal open={modal === "submatter"} title="Teilvorgang anlegen" onClose={() => setModal("")}>
|
||||
<SubmatterForm parentId={id} context={inherited} onChange={() => { setModal(""); load(); }} />
|
||||
@@ -600,7 +618,7 @@ export function MatterDetail() {
|
||||
/>
|
||||
</Modal>
|
||||
<Modal open={modal === "share"} title="Teilen" onClose={() => setModal("")}>
|
||||
<ShareBox path={`/api/v1/matters/${id}/grants`} grants={record.grants || []} onChange={load} />
|
||||
<ShareBox path={`/api/v1/matters/${id}/grants`} grants={record.grants || []} onChange={load} allowSources={Boolean(record.is_owner)} />
|
||||
</Modal>
|
||||
<Modal open={modal === "move"} title="Vorgang verschieben" onClose={() => setModal("")}>
|
||||
<MoveMatter
|
||||
@@ -756,13 +774,13 @@ function WorkForms({ matterId, context, deadlines, onChange }) {
|
||||
<form onSubmit={addDeadline} className="stack compact">
|
||||
<h3>Frist</h3>
|
||||
<input value={deadlineTitle} onChange={(event) => setDeadlineTitle(event.target.value)} placeholder="Maßgeblicher Termin" required />
|
||||
<label>Frist <input type="date" value={deadlineDue} onChange={(event) => setDeadlineDue(event.target.value)} required /></label>
|
||||
<label>Frist <DateField value={deadlineDue} onChange={setDeadlineDue} required /></label>
|
||||
<button type="submit">Frist erfassen</button>
|
||||
</form>
|
||||
<form onSubmit={addTask} className="stack compact">
|
||||
<h3>Aufgabe</h3>
|
||||
<input value={taskTitle} onChange={(event) => setTaskTitle(event.target.value)} placeholder="Was ist vor der Frist zu tun?" required />
|
||||
<label>Arbeitstermin <input type="date" value={taskDue} onChange={(event) => setTaskDue(event.target.value)} /></label>
|
||||
<label>Arbeitstermin <DateField value={taskDue} onChange={setTaskDue} /></label>
|
||||
<label>
|
||||
Gehört zur Frist
|
||||
<select value={deadlineId} onChange={(event) => setDeadlineId(event.target.value)}>
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { documentToText, downloadMailPart, fetchFile, fetchMailPart, fetchPaperless, markDirty, textToDocument, api } from "../api.js";
|
||||
import { ErrorNote } from "./widgets.jsx";
|
||||
import { dateCaption, DirectionChoice, DirectionColumn, directionValue, directionWord, formatDate, mailFacts, MarkdownEditor, sourceLabel } from "./content.jsx";
|
||||
import { UnitDetail } from "./correspondence.jsx";
|
||||
import { dateCaption, DateField, DirectionChoice, DirectionColumn, directionValue, directionWord, formatDate, mailFacts, MarkdownEditor, sourceLabel } from "./content.jsx";
|
||||
import { NavIcon } from "./icons.jsx";
|
||||
import workerSrc from "pdfjs-dist/build/pdf.worker.min.mjs?url";
|
||||
|
||||
@@ -281,9 +282,10 @@ export function ReadingPane({ binding, context, backLabel, onClose, onReload, ca
|
||||
const task = { cancel: null };
|
||||
pdf.getPage(page).then((pdfPage) => {
|
||||
if (!alive) return;
|
||||
const viewport = pdfPage.getViewport({ scale });
|
||||
const canvas = canvasRef.current;
|
||||
const context2d = canvas.getContext("2d");
|
||||
const context2d = canvas?.getContext("2d");
|
||||
if (!canvas || !context2d) return;
|
||||
const viewport = pdfPage.getViewport({ scale });
|
||||
canvas.width = viewport.width;
|
||||
canvas.height = viewport.height;
|
||||
const render = pdfPage.render({ canvasContext: context2d, viewport });
|
||||
@@ -383,6 +385,21 @@ export function ReadingPane({ binding, context, backLabel, onClose, onReload, ca
|
||||
}
|
||||
}
|
||||
|
||||
async function renameTitle() {
|
||||
const title = window.prompt("Titel", element.title);
|
||||
if (!title || title.trim() === element.title) return;
|
||||
setError("");
|
||||
try {
|
||||
await api(`/api/v1/elements/${element.id}/title`, {
|
||||
method: "PATCH",
|
||||
body: { expected_version: element.version, title: title.trim(), context },
|
||||
});
|
||||
onReload();
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
}
|
||||
}
|
||||
|
||||
async function saveDate(event) {
|
||||
event.preventDefault();
|
||||
setError("");
|
||||
@@ -424,16 +441,28 @@ export function ReadingPane({ binding, context, backLabel, onClose, onReload, ca
|
||||
const search = new URLSearchParams();
|
||||
search.set("context_kind", context.kind);
|
||||
search.set("context_id", context.id);
|
||||
await api(`/api/v1/bindings/${binding.id}?${search}`, { method: "DELETE" });
|
||||
onClose();
|
||||
onReload();
|
||||
setError("");
|
||||
try {
|
||||
await api(`/api/v1/bindings/${binding.id}?${search}`, { method: "DELETE" });
|
||||
markDirty(false);
|
||||
onClose();
|
||||
onReload();
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
}
|
||||
}
|
||||
|
||||
async function destroy() {
|
||||
if (!window.confirm("Ü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 } });
|
||||
onClose();
|
||||
onReload();
|
||||
setError("");
|
||||
try {
|
||||
await api(`/api/v1/elements/${element.id}/delete`, { method: "POST", body: { expected_version: element.version } });
|
||||
markDirty(false);
|
||||
onClose();
|
||||
onReload();
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
}
|
||||
}
|
||||
|
||||
if (!binding) {
|
||||
@@ -463,6 +492,11 @@ export function ReadingPane({ binding, context, backLabel, onClose, onReload, ca
|
||||
<div className="reader-title">
|
||||
<DirectionColumn direction={shownDirection} />
|
||||
<h2>{element.title}</h2>
|
||||
{binding.rights.edit ? (
|
||||
<button type="button" className="icon-button icon-button--compact" aria-label="Titel ändern" onClick={renameTitle}>
|
||||
<NavIcon name="pencil" />
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
<p className="reader-facts">
|
||||
<span>{formatDate(element.dates?.document_on)} · {sourceLabel(element)}</span>
|
||||
@@ -485,6 +519,14 @@ export function ReadingPane({ binding, context, backLabel, onClose, onReload, ca
|
||||
<div className="reader-pane__stage">
|
||||
<ErrorNote error={error} />
|
||||
<Correspondence element={element} direction={shownDirection} onOpenRelated={onOpenRelated} />
|
||||
<UnitDetail
|
||||
binding={binding}
|
||||
canEdit={false}
|
||||
pending={false}
|
||||
onOpen={(elementId) => onOpenRelated?.(elementId)}
|
||||
onDetach={() => {}}
|
||||
onUnfold={() => {}}
|
||||
/>
|
||||
{isMail ? (
|
||||
<article className="mail-letter">
|
||||
<p className="mail-letter__way"><DirectionColumn direction={shownDirection} />{directionWord(shownDirection) ? <span>{directionWord(shownDirection)}</span> : null}</p>
|
||||
@@ -615,15 +657,15 @@ export function ReadingPane({ binding, context, backLabel, onClose, onReload, ca
|
||||
<form className="stack" onSubmit={saveDate}>
|
||||
<label>
|
||||
{element.kind === "note" ? "Bezugsdatum, optional" : "Dokumentdatum, optional"}
|
||||
<input type="date" value={documentOn} onChange={(event) => { setDocumentOn(event.target.value); markDirty(true); }} />
|
||||
<DateField value={documentOn} onChange={(value) => { setDocumentOn(value); markDirty(true); }} />
|
||||
</label>
|
||||
<label>
|
||||
Versand, optional
|
||||
<input type="date" value={sentOn} onChange={(event) => { setSentOn(event.target.value); markDirty(true); }} />
|
||||
<DateField value={sentOn} onChange={(value) => { setSentOn(value); markDirty(true); }} />
|
||||
</label>
|
||||
<label>
|
||||
Zugang, optional
|
||||
<input type="date" value={receivedOn} onChange={(event) => { setReceivedOn(event.target.value); markDirty(true); }} />
|
||||
<DateField value={receivedOn} onChange={(value) => { setReceivedOn(value); markDirty(true); }} />
|
||||
</label>
|
||||
<button type="submit" className="quiet">Datum speichern</button>
|
||||
</form>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useContext, useEffect, useRef, useState } from "react";
|
||||
import { Component, useContext, useEffect, useRef, useState } from "react";
|
||||
import { NavLink, Outlet, useLocation, useNavigate } from "react-router-dom";
|
||||
import { SessionContext } from "../session.js";
|
||||
import { Mark, NavIcon } from "./icons.jsx";
|
||||
@@ -18,6 +18,42 @@ function initials(name) {
|
||||
return parts.slice(0, 2).map((part) => part[0]).join("").toUpperCase();
|
||||
}
|
||||
|
||||
const MOBILE = [
|
||||
...WORK,
|
||||
{ to: "/settings", label: "Verwaltung", short: "Verwaltung", icon: "gear" },
|
||||
{ to: "/search", label: "Suche", short: "Suche", icon: "search" },
|
||||
];
|
||||
|
||||
class PageBoundary extends Component {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.state = { failed: false };
|
||||
}
|
||||
|
||||
static getDerivedStateFromError() {
|
||||
return { failed: true };
|
||||
}
|
||||
|
||||
componentDidUpdate(previous) {
|
||||
if (previous.resetKey !== this.props.resetKey && this.state.failed) {
|
||||
this.setState({ failed: false });
|
||||
}
|
||||
}
|
||||
|
||||
render() {
|
||||
if (this.state.failed) {
|
||||
return (
|
||||
<main className="page">
|
||||
<h1>Die Ansicht ist abgebrochen.</h1>
|
||||
<p>Die Navigation bleibt verfügbar. Öffne die Seite erneut oder wechsle über das Menü.</p>
|
||||
<button type="button" onClick={() => this.setState({ failed: false })}>Erneut anzeigen</button>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
return this.props.children;
|
||||
}
|
||||
}
|
||||
|
||||
export function Shell() {
|
||||
const { session, logout } = useContext(SessionContext);
|
||||
const navigate = useNavigate();
|
||||
@@ -32,7 +68,6 @@ export function Shell() {
|
||||
const [query, setQuery] = useState("");
|
||||
const [searchOpen, setSearchOpen] = useState(false);
|
||||
const searchRef = useRef(null);
|
||||
const [more, setMore] = useState(false);
|
||||
const [width, setWidth] = useState(() => window.innerWidth);
|
||||
const [markIntroDone, setMarkIntroDone] = useState(false);
|
||||
const markMotion = markIntroDone ? "none" : "intro";
|
||||
@@ -71,10 +106,6 @@ export function Shell() {
|
||||
return () => cancelAnimationFrame(frame);
|
||||
}, [markIntroDone]);
|
||||
|
||||
useEffect(() => {
|
||||
setMore(false);
|
||||
}, [location.pathname]);
|
||||
|
||||
const forcedCompact = width < 1180;
|
||||
const compact = forcedCompact || !expanded;
|
||||
|
||||
@@ -170,35 +201,22 @@ export function Shell() {
|
||||
) : null}
|
||||
</header>
|
||||
<div className="app-main">
|
||||
<Outlet />
|
||||
<PageBoundary resetKey={`${location.pathname}${location.search}`}>
|
||||
<Outlet />
|
||||
</PageBoundary>
|
||||
</div>
|
||||
<nav className="bottom-nav" aria-label="Hauptnavigation">
|
||||
{WORK.map((item) => (
|
||||
{MOBILE.map((item) => (
|
||||
<NavLink key={item.to} to={item.to} end={item.end} className={({ isActive }) => `nav-item${isActive ? " active" : ""}`}>
|
||||
<NavIcon name={item.icon} />
|
||||
<span>{item.short}</span>
|
||||
</NavLink>
|
||||
))}
|
||||
<button type="button" className={`nav-item${more ? " active" : ""}`} onClick={() => setMore(true)}>
|
||||
<NavIcon name="more" />
|
||||
<span>Mehr</span>
|
||||
<button type="button" className="nav-item" onClick={logout}>
|
||||
<NavIcon name="logout" />
|
||||
<span>Abmelden</span>
|
||||
</button>
|
||||
</nav>
|
||||
{more ? (
|
||||
<div className="modal-overlay" onClick={(event) => { if (event.target === event.currentTarget) setMore(false); }}>
|
||||
<div className="sheet" role="dialog" aria-modal="true" aria-label="Weitere Ziele">
|
||||
<header className="modal__bar">
|
||||
<h2>Mehr</h2>
|
||||
<button type="button" className="quiet" onClick={() => setMore(false)}>Schließen</button>
|
||||
</header>
|
||||
<div className="menu-list">
|
||||
<NavLink to="/settings" onClick={() => setMore(false)}>Verwaltung</NavLink>
|
||||
<NavLink to="/search" onClick={() => setMore(false)}>Suche</NavLink>
|
||||
<button type="button" className="quiet" onClick={logout}>Abmelden</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -135,9 +135,16 @@ function MailForm({ onSaved, onError }) {
|
||||
);
|
||||
}
|
||||
|
||||
export function PaperlessPicker({ context, placement, chapterId = "", chapterTitle = "", targetLabel = "", onDone }) {
|
||||
function paperlessLabel(item) {
|
||||
const dated = formatDate(item.document_on);
|
||||
return dated !== "Ohne Datum" ? `${dated} · ${item.title}` : item.title;
|
||||
}
|
||||
|
||||
export function PaperlessPicker({ context, placement, chapterId = "", chapterTitle = "", targetLabel = "", onDone, onInserted }) {
|
||||
const [query, setQuery] = useState("");
|
||||
const [items, setItems] = useState([]);
|
||||
const [picked, setPicked] = useState(() => new Map());
|
||||
const [pending, setPending] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
|
||||
async function search(event) {
|
||||
@@ -151,33 +158,61 @@ export function PaperlessPicker({ context, placement, chapterId = "", chapterTit
|
||||
}
|
||||
}
|
||||
|
||||
async function link(item) {
|
||||
function toggle(item) {
|
||||
const key = String(item.id);
|
||||
setPicked((current) => {
|
||||
const next = new Map(current);
|
||||
if (next.has(key)) next.delete(key);
|
||||
else next.set(key, item);
|
||||
return next;
|
||||
});
|
||||
}
|
||||
|
||||
async function linkMany() {
|
||||
const chosen = [...picked.values()];
|
||||
if (!chosen.length) return;
|
||||
setError("");
|
||||
setPending(true);
|
||||
const inserted = [];
|
||||
try {
|
||||
await api("/api/v1/external-refs", {
|
||||
method: "POST",
|
||||
body: {
|
||||
title: item.title,
|
||||
source: "paperless",
|
||||
external_id: item.id,
|
||||
context,
|
||||
...(placement ? { placement } : {}),
|
||||
...(chapterId ? { chapter_id: chapterId } : {}),
|
||||
...(item.document_on || item.correspondent || item.open_url
|
||||
? {
|
||||
dates: { document_on: item.document_on || null, sent_on: null, received_on: null },
|
||||
detail: {
|
||||
...(item.correspondent ? { correspondent: item.correspondent } : {}),
|
||||
...(item.open_url ? { open_url: item.open_url } : {}),
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
});
|
||||
onDone();
|
||||
for (const item of chosen) {
|
||||
await api("/api/v1/external-refs", {
|
||||
method: "POST",
|
||||
body: {
|
||||
title: item.title,
|
||||
source: "paperless",
|
||||
external_id: String(item.id),
|
||||
context,
|
||||
...(placement ? { placement } : {}),
|
||||
...(chapterId ? { chapter_id: chapterId } : {}),
|
||||
...(item.document_on || item.correspondent || item.open_url
|
||||
? {
|
||||
dates: { document_on: item.document_on || null, sent_on: null, received_on: null },
|
||||
detail: {
|
||||
...(item.correspondent ? { correspondent: item.correspondent } : {}),
|
||||
...(item.open_url ? { open_url: item.open_url } : {}),
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
});
|
||||
inserted.push(String(item.id));
|
||||
}
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
} finally {
|
||||
setPending(false);
|
||||
}
|
||||
if (inserted.length) {
|
||||
setItems((current) => current.filter((item) => !inserted.includes(String(item.id))));
|
||||
setPicked((current) => {
|
||||
const next = new Map(current);
|
||||
inserted.forEach((id) => next.delete(id));
|
||||
return next;
|
||||
});
|
||||
onInserted?.();
|
||||
}
|
||||
if (inserted.length === chosen.length) onDone();
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -188,10 +223,24 @@ export function PaperlessPicker({ context, placement, chapterId = "", chapterTit
|
||||
<button type="submit">Suchen</button>
|
||||
</form>
|
||||
<ErrorNote error={error} />
|
||||
<p className="muted">Die Verbindung richtest du unter <Link to="/sources">Quellen</Link> ein.</p>
|
||||
<p className="muted">Die Verbindung richtest du unter <Link to="/sources">Quellen</Link> ein. Mehrere Treffer lassen sich zusammen einfügen.</p>
|
||||
{items.length || picked.size ? (
|
||||
<button type="button" disabled={pending || picked.size === 0} onClick={linkMany}>
|
||||
{picked.size ? `${picked.size} Belege einfügen` : "Belege auswählen"}
|
||||
</button>
|
||||
) : null}
|
||||
<div className="stack">
|
||||
{[...picked.values()].filter((item) => !items.some((entry) => String(entry.id) === String(item.id))).map((item) => (
|
||||
<label key={`held-${item.id}`} className="paperless-pick">
|
||||
<input type="checkbox" checked disabled={pending} onChange={() => toggle(item)} />
|
||||
<span>{paperlessLabel(item)}</span>
|
||||
</label>
|
||||
))}
|
||||
{items.map((item) => (
|
||||
<button key={item.id} type="button" className="quiet" onClick={() => link(item)}>{item.title}</button>
|
||||
<label key={item.id} className="paperless-pick">
|
||||
<input type="checkbox" checked={picked.has(String(item.id))} disabled={pending} onChange={() => toggle(item)} />
|
||||
<span>{paperlessLabel(item)}</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -72,6 +72,23 @@ export function trailWithChapter(items, chapters, chapterId, backHref) {
|
||||
return [...base, { label: path.join(" / "), href: null }];
|
||||
}
|
||||
|
||||
export function countLabel(direct, nested) {
|
||||
const here = Number(direct) || 0;
|
||||
const below = Number(nested) || 0;
|
||||
if (here && below) return `${here} direkt · ${below} in Unterkapiteln`;
|
||||
if (!here && below) return `${below} in Unterkapiteln`;
|
||||
return String(here);
|
||||
}
|
||||
|
||||
export function sectionCounts(section) {
|
||||
const direct = (section?.items || []).length;
|
||||
const nested = (section?.children || []).reduce((sum, child) => {
|
||||
const inner = sectionCounts(child);
|
||||
return sum + inner.direct + inner.nested;
|
||||
}, 0);
|
||||
return { direct, nested };
|
||||
}
|
||||
|
||||
export function findSection(nodes, id) {
|
||||
for (const node of nodes || []) {
|
||||
if (node.id === id) return node;
|
||||
|
||||
+1052
-102
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,970 @@
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import { Link } from "react-router-dom";
|
||||
import { api } from "../api.js";
|
||||
import { buildChapterSections, sectionCounts } from "./chapters.js";
|
||||
|
||||
function formatDate(value) {
|
||||
if (!value) return "Ohne Datum";
|
||||
const [year, month, day] = String(value).slice(0, 10).split("-");
|
||||
if (!year || !month || !day) return String(value);
|
||||
return `${day}.${month}.${year}`;
|
||||
}
|
||||
|
||||
export function scopeBody(context, containerKind, containerId) {
|
||||
const rights = context || { kind: containerKind, id: containerId };
|
||||
const same = rights.kind === containerKind && rights.id === containerId;
|
||||
return { context: rights, placement: same ? null : { kind: containerKind, id: containerId } };
|
||||
}
|
||||
|
||||
export function channelWord(channel) {
|
||||
if (channel === "email") return "per E-Mail";
|
||||
if (channel === "post") return "per Post";
|
||||
if (channel === "other") return "sonstiger Weg";
|
||||
return "";
|
||||
}
|
||||
|
||||
export function unitMarks(binding) {
|
||||
const pack = binding?.correspondence;
|
||||
if (!pack) return "";
|
||||
const parts = [];
|
||||
const attachments = pack.attachments || [];
|
||||
if (attachments.length === 1) parts.push("1 Anlage");
|
||||
else if (attachments.length > 1) parts.push(`${attachments.length} Anlagen`);
|
||||
const dispatches = pack.dispatches || [];
|
||||
if (dispatches.length === 1) parts.push(channelWord(dispatches[0].channel));
|
||||
else if (dispatches.length > 1) parts.push(`${dispatches.length} Versände`);
|
||||
const evidence = dispatches.reduce((sum, item) => sum + (item.evidence || []).length, 0);
|
||||
if (evidence === 1) parts.push("1 Beleg");
|
||||
else if (evidence > 1) parts.push(`${evidence} Belege`);
|
||||
return parts.join(" · ");
|
||||
}
|
||||
|
||||
export function hostMark(binding) {
|
||||
const hosts = binding?.correspondence?.hosts || [];
|
||||
if (!hosts.length) return "";
|
||||
return `Dieselbe Unterlage · Anlage zu ${hosts.map((item) => item.title).join(", ")}`;
|
||||
}
|
||||
|
||||
function fieldBody(scope, extra) {
|
||||
const body = { ...extra, context: scope.context };
|
||||
if (scope.placement) body.placement = scope.placement;
|
||||
return body;
|
||||
}
|
||||
|
||||
export const ASSIGN_MIME = "application/x-tsumugu-item";
|
||||
|
||||
export const RECEIPT_ROLES = [
|
||||
["email", "E-Mail"],
|
||||
["submission", "Einlieferungsbeleg"],
|
||||
["delivery", "Zustellung oder Versandbestätigung"],
|
||||
["other", "Sonstiger Beleg"],
|
||||
];
|
||||
|
||||
export function receiptRoleLabel(role, fallback = "") {
|
||||
return RECEIPT_ROLES.find((item) => item[0] === role)?.[1] || fallback || role;
|
||||
}
|
||||
|
||||
function receiptCaption(proof) {
|
||||
if (proof.role === "email" && proof.source !== "imap") return "Beleg";
|
||||
return receiptRoleLabel(proof.role, proof.role_label);
|
||||
}
|
||||
|
||||
function receiptWhen(item) {
|
||||
if (item.sent_on) return formatDate(item.sent_on);
|
||||
const dated = (item.evidence || []).find((proof) => proof.document_on);
|
||||
return dated ? formatDate(dated.document_on) : "";
|
||||
}
|
||||
|
||||
function isShipment(item) {
|
||||
const proofs = item.evidence || [];
|
||||
if (item.channel === "other") return false;
|
||||
if (proofs.length > 0 && proofs.every((proof) => proof.kind === "file")) return false;
|
||||
return (item.items || []).length > 0;
|
||||
}
|
||||
|
||||
function receiptHeading(item) {
|
||||
const who = item.counterpart ? ` · ${item.counterpart}` : "";
|
||||
const when = receiptWhen(item);
|
||||
if (!isShipment(item)) return `${when || "Beleg"}${who}`;
|
||||
return `Versand ${when || "undatiert"} · ${item.channel_label}${who}`;
|
||||
}
|
||||
|
||||
export function writeAssign(event, payload) {
|
||||
event.dataTransfer.effectAllowed = "copyMove";
|
||||
event.dataTransfer.setData(ASSIGN_MIME, JSON.stringify(payload));
|
||||
event.dataTransfer.setData("text/plain", payload.title || "");
|
||||
}
|
||||
|
||||
function ancestorIds(chapters, chapterId) {
|
||||
const byId = new Map((chapters || []).map((chapter) => [chapter.id, chapter]));
|
||||
const ids = [];
|
||||
const seen = new Set();
|
||||
let current = chapterId ? byId.get(chapterId) : null;
|
||||
while (current && !seen.has(current.id)) {
|
||||
seen.add(current.id);
|
||||
ids.push(current.id);
|
||||
current = current.parent_chapter_id ? byId.get(current.parent_chapter_id) : null;
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
function branchItems(section) {
|
||||
return [
|
||||
...(section.items || []),
|
||||
...(section.children || []).flatMap(branchItems),
|
||||
];
|
||||
}
|
||||
|
||||
function titleMatches(binding, needle) {
|
||||
if (!needle) return true;
|
||||
return (binding.element?.title || "").toLowerCase().includes(needle);
|
||||
}
|
||||
|
||||
function branchVisible(section, needle) {
|
||||
if (!needle) return true;
|
||||
if ((section.items || []).some((item) => titleMatches(item, needle))) return true;
|
||||
return (section.children || []).some((child) => branchVisible(child, needle));
|
||||
}
|
||||
|
||||
function PickBox({ checked, mixed = false, disabled = false, label, onChange }) {
|
||||
const ref = useRef(null);
|
||||
useEffect(() => {
|
||||
if (ref.current) ref.current.indeterminate = mixed;
|
||||
}, [mixed]);
|
||||
return (
|
||||
<input
|
||||
ref={ref}
|
||||
type="checkbox"
|
||||
checked={checked}
|
||||
disabled={disabled}
|
||||
aria-checked={mixed ? "mixed" : checked}
|
||||
aria-label={label}
|
||||
onChange={onChange}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function selectionState(ids, selected) {
|
||||
if (!ids.length) return "off";
|
||||
const count = ids.filter((id) => selected.has(id)).length;
|
||||
if (count === 0) return "off";
|
||||
if (count === ids.length) return "on";
|
||||
return "mixed";
|
||||
}
|
||||
|
||||
export function StructureAssignDialog({ host, bindings, chapters, scope, pending, onClose, onDone }) {
|
||||
const visibleBindings = useMemo(
|
||||
() => (bindings || []).filter((item) => !item.correspondence?.fold),
|
||||
[bindings],
|
||||
);
|
||||
const tree = useMemo(() => buildChapterSections(chapters, visibleBindings), [chapters, visibleBindings]);
|
||||
const receiptIds = useMemo(() => new Set(
|
||||
(host.correspondence?.dispatches || []).flatMap((item) => (item.evidence || []).map((proof) => proof.element_id)),
|
||||
), [host]);
|
||||
const [opened, setOpened] = useState(() => new Set(host.chapter_id ? ancestorIds(chapters, host.chapter_id) : ["loose"]));
|
||||
const [query, setQuery] = useState("");
|
||||
const [selected, setSelected] = useState(() => new Set());
|
||||
const [step, setStep] = useState("pick");
|
||||
const [role, setRole] = useState("other");
|
||||
const [fold, setFold] = useState("evidence");
|
||||
const [dispatchId, setDispatchId] = useState(host.correspondence?.dispatches?.[0]?.id || "");
|
||||
const [channel, setChannel] = useState("other");
|
||||
const [sentOn, setSentOn] = useState("");
|
||||
const [counterpart, setCounterpart] = useState("");
|
||||
const [error, setError] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const needle = query.trim().toLowerCase();
|
||||
const taken = new Set((host.correspondence?.attachments || []).map((item) => item.element_id));
|
||||
const dispatches = host.correspondence?.dispatches || [];
|
||||
|
||||
function toggle(id) {
|
||||
setSelected((current) => {
|
||||
const next = new Set(current);
|
||||
if (next.has(id)) next.delete(id);
|
||||
else next.add(id);
|
||||
return next;
|
||||
});
|
||||
}
|
||||
|
||||
function toggleIds(ids) {
|
||||
if (!ids.length) return;
|
||||
setSelected((current) => {
|
||||
const next = new Set(current);
|
||||
const allOn = ids.every((id) => next.has(id));
|
||||
ids.forEach((id) => {
|
||||
if (allOn) next.delete(id);
|
||||
else next.add(id);
|
||||
});
|
||||
return next;
|
||||
});
|
||||
}
|
||||
|
||||
function selectable(id) {
|
||||
return id !== host.element.id && !taken.has(id) && !receiptIds.has(id);
|
||||
}
|
||||
|
||||
function toggleChapter(section) {
|
||||
toggleIds(branchItems(section).map((item) => item.element.id).filter(selectable));
|
||||
}
|
||||
|
||||
function visibleIds() {
|
||||
const ids = [];
|
||||
function walk(section) {
|
||||
if (!branchVisible(section, needle)) return;
|
||||
for (const item of section.items || []) {
|
||||
if (selectable(item.element.id) && titleMatches(item, needle)) ids.push(item.element.id);
|
||||
}
|
||||
for (const child of section.children || []) walk(child);
|
||||
}
|
||||
tree.roots.forEach(walk);
|
||||
for (const item of tree.loose) {
|
||||
if (selectable(item.element.id) && titleMatches(item, needle)) ids.push(item.element.id);
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
async function saveAttachments() {
|
||||
const ids = [...selected].filter((id) => selectable(id));
|
||||
if (!ids.length) {
|
||||
setError("In der Auswahl ist keine neue Anlage.");
|
||||
return;
|
||||
}
|
||||
setBusy(true);
|
||||
setError("");
|
||||
try {
|
||||
await api(`/api/v1/elements/${host.element.id}/attachments`, {
|
||||
method: "POST",
|
||||
body: fieldBody(scope, {
|
||||
expected_version: host.element.version,
|
||||
attachment_element_ids: ids,
|
||||
fold: "attachment",
|
||||
}),
|
||||
});
|
||||
onDone();
|
||||
onClose();
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
onDone();
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function saveReceipts(event) {
|
||||
event.preventDefault();
|
||||
const ids = [...selected].filter((id) => selectable(id));
|
||||
if (!ids.length) return;
|
||||
setBusy(true);
|
||||
setError("");
|
||||
try {
|
||||
if (!dispatchId) {
|
||||
await api(`/api/v1/elements/${host.element.id}/dispatches`, {
|
||||
method: "POST",
|
||||
body: fieldBody(scope, {
|
||||
expected_version: host.element.version,
|
||||
channel,
|
||||
sent_on: sentOn || null,
|
||||
counterpart: counterpart.trim() || null,
|
||||
attachment_element_ids: [],
|
||||
evidence: ids.map((id) => ({ element_id: id, role, fold })),
|
||||
historical_gap: false,
|
||||
capture_editions: false,
|
||||
}),
|
||||
});
|
||||
} else {
|
||||
const dispatch = dispatches.find((item) => item.id === dispatchId);
|
||||
const already = new Set((dispatch?.evidence || []).map((item) => item.element_id));
|
||||
const fresh = ids.filter((id) => !already.has(id));
|
||||
if (!fresh.length) {
|
||||
setError("Diese Belege liegen an dem Versand bereits.");
|
||||
return;
|
||||
}
|
||||
let version = dispatch?.version || 1;
|
||||
for (const id of fresh) {
|
||||
await api(`/api/v1/dispatches/${dispatchId}/evidence`, {
|
||||
method: "POST",
|
||||
body: fieldBody(scope, {
|
||||
expected_version: version,
|
||||
element_id: id,
|
||||
role,
|
||||
fold,
|
||||
}),
|
||||
});
|
||||
version += 1;
|
||||
}
|
||||
}
|
||||
onDone();
|
||||
onClose();
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
onDone();
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
function renderRow(item) {
|
||||
const id = item.element.id;
|
||||
const isHost = id === host.element.id;
|
||||
const notes = [
|
||||
formatDate(item.element.dates?.document_on),
|
||||
isHost ? "dieses Schriftstück" : "",
|
||||
taken.has(id) ? "bereits Anlage" : "",
|
||||
receiptIds.has(id) ? "bereits Beleg" : "",
|
||||
].filter(Boolean).join(" · ");
|
||||
const blocked = isHost || taken.has(id) || receiptIds.has(id);
|
||||
return (
|
||||
<li key={item.id}>
|
||||
<label className="pick-tree__row">
|
||||
<PickBox checked={selected.has(id)} disabled={blocked} label={item.element.title} onChange={() => toggle(id)} />
|
||||
<span className="pick-tree__title">{item.element.title}</span>
|
||||
<span className="pick-tree__kind">{notes}</span>
|
||||
</label>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
function renderSection(section) {
|
||||
if (!branchVisible(section, needle)) return null;
|
||||
const expanded = Boolean(needle) || opened.has(section.id);
|
||||
const counts = sectionCounts(section);
|
||||
const total = counts.direct + counts.nested;
|
||||
const ids = branchItems(section).map((item) => item.element.id).filter(selectable);
|
||||
const state = selectionState(ids, selected);
|
||||
return (
|
||||
<li key={section.id}>
|
||||
<div className="pick-tree__row">
|
||||
<button
|
||||
type="button"
|
||||
className="pick-tree__twist"
|
||||
aria-expanded={expanded}
|
||||
aria-label={`${section.title} ${expanded ? "zuklappen" : "aufklappen"}`}
|
||||
onClick={() => setOpened((current) => {
|
||||
const next = new Set(current);
|
||||
if (next.has(section.id)) next.delete(section.id);
|
||||
else next.add(section.id);
|
||||
return next;
|
||||
})}
|
||||
>
|
||||
{expanded ? "▾" : "▸"}
|
||||
</button>
|
||||
<label>
|
||||
<PickBox
|
||||
checked={state === "on"}
|
||||
mixed={state === "mixed"}
|
||||
disabled={!ids.length}
|
||||
label={`Alle in ${section.title}`}
|
||||
onChange={() => toggleChapter(section)}
|
||||
/>
|
||||
<span className="pick-tree__title">{section.title}</span>
|
||||
<span className="pick-tree__kind">{total}</span>
|
||||
</label>
|
||||
</div>
|
||||
{expanded ? (
|
||||
<ul>
|
||||
{(section.items || []).filter((item) => titleMatches(item, needle)).map((item) => renderRow(item))}
|
||||
{(section.children || []).map((child) => renderSection(child))}
|
||||
</ul>
|
||||
) : null}
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
const loose = tree.loose.filter((item) => titleMatches(item, needle));
|
||||
const roots = tree.roots.map((section) => renderSection(section, 0)).filter(Boolean);
|
||||
|
||||
const looseIds = loose.map((item) => item.element.id).filter(selectable);
|
||||
const looseState = selectionState(looseIds, selected);
|
||||
const looseOpen = Boolean(needle) || opened.has("loose");
|
||||
|
||||
return (
|
||||
<div className="stack pick-tree-dialog">
|
||||
<p className="pick-tree__lead">Zuordnen an {host.element.title}</p>
|
||||
<label className="pick-tree__find">
|
||||
Suchen
|
||||
<input value={query} onChange={(event) => setQuery(event.target.value)} placeholder="Titel" />
|
||||
</label>
|
||||
{step === "pick" ? (
|
||||
<>
|
||||
<ul className="pick-tree">
|
||||
{roots}
|
||||
{loose.length ? (
|
||||
<li>
|
||||
<div className="pick-tree__row">
|
||||
<button
|
||||
type="button"
|
||||
className="pick-tree__twist"
|
||||
aria-expanded={looseOpen}
|
||||
aria-label={`Ohne Kapitel ${looseOpen ? "zuklappen" : "aufklappen"}`}
|
||||
onClick={() => setOpened((current) => {
|
||||
const next = new Set(current);
|
||||
if (next.has("loose")) next.delete("loose");
|
||||
else next.add("loose");
|
||||
return next;
|
||||
})}
|
||||
>
|
||||
{looseOpen ? "▾" : "▸"}
|
||||
</button>
|
||||
<label>
|
||||
<PickBox
|
||||
checked={looseState === "on"}
|
||||
mixed={looseState === "mixed"}
|
||||
disabled={!looseIds.length}
|
||||
label="Alle ohne Kapitel"
|
||||
onChange={() => toggleIds(looseIds)}
|
||||
/>
|
||||
<span className="pick-tree__title">Ohne Kapitel</span>
|
||||
<span className="pick-tree__kind">{loose.length}</span>
|
||||
</label>
|
||||
</div>
|
||||
{looseOpen ? (
|
||||
<ul>
|
||||
{loose.map((item) => renderRow(item))}
|
||||
</ul>
|
||||
) : null}
|
||||
</li>
|
||||
) : null}
|
||||
{!roots.length && !loose.length ? <li className="pick-tree__empty">Nichts mit diesem Titel.</li> : null}
|
||||
</ul>
|
||||
<div className="pick-tree__bar">
|
||||
<span>{selected.size} ausgewählt</span>
|
||||
{needle ? <button type="button" className="quiet" onClick={() => toggleIds(visibleIds())}>Sichtbare</button> : null}
|
||||
<button type="button" disabled={pending || busy || !selected.size} onClick={saveAttachments}>Als Anlagen</button>
|
||||
<button type="button" disabled={pending || busy || !selected.size} onClick={() => { setError(""); setStep("receipt"); }}>Als Belege</button>
|
||||
<button type="button" className="quiet" onClick={onClose}>Schließen</button>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<form className="stack" onSubmit={saveReceipts}>
|
||||
<p>{selected.size} Belege. Dieselbe Rolle gilt für die Auswahl.</p>
|
||||
<label>
|
||||
Versand
|
||||
<select value={dispatchId} onChange={(event) => setDispatchId(event.target.value)}>
|
||||
<option value="">Neuen Versand anlegen</option>
|
||||
{dispatches.map((item) => (
|
||||
<option key={item.id} value={item.id}>
|
||||
{item.sent_on ? formatDate(item.sent_on) : "undatiert"} · {item.channel_label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
{!dispatchId ? (
|
||||
<>
|
||||
<label>
|
||||
Weg
|
||||
<select value={channel} onChange={(event) => setChannel(event.target.value)}>
|
||||
<option value="email">E-Mail</option>
|
||||
<option value="post">Post</option>
|
||||
<option value="other">Sonstiger Weg</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>Versanddatum<input type="date" value={sentOn} onChange={(event) => setSentOn(event.target.value)} /></label>
|
||||
<label>Gegenüber<input value={counterpart} onChange={(event) => setCounterpart(event.target.value)} maxLength={200} /></label>
|
||||
</>
|
||||
) : null}
|
||||
<label>
|
||||
Rolle
|
||||
<select value={role} onChange={(event) => setRole(event.target.value)}>
|
||||
{RECEIPT_ROLES.map(([value, label]) => <option key={value} value={value}>{label}</option>)}
|
||||
</select>
|
||||
</label>
|
||||
<fieldset>
|
||||
<legend>Darstellung in der Liste</legend>
|
||||
<label><input type="radio" name="assign-fold" checked={fold === "evidence"} onChange={() => setFold("evidence")} /> Nur am Versand zeigen</label>
|
||||
<label><input type="radio" name="assign-fold" checked={fold === "keep"} onChange={() => setFold("keep")} /> Zusätzlich als eigenen Eintrag behalten</label>
|
||||
</fieldset>
|
||||
<button type="submit" disabled={pending || busy}>Belege zuordnen</button>
|
||||
<button type="button" className="quiet" onClick={() => setStep("pick")}>Zurück zur Struktur</button>
|
||||
</form>
|
||||
)}
|
||||
{error ? <p className="error">{error}</p> : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function DispatchDialog({ host, scope, pending, onClose, onDone }) {
|
||||
const proposal = host.correspondence?.attachments || [];
|
||||
const [order, setOrder] = useState(proposal.map((item) => item.element_id));
|
||||
const [chosen, setChosen] = useState(() => new Set(proposal.map((item) => item.element_id)));
|
||||
const [channel, setChannel] = useState("email");
|
||||
const [sentOn, setSentOn] = useState("");
|
||||
const [counterpart, setCounterpart] = useState("");
|
||||
const [historical, setHistorical] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
|
||||
function move(id, delta) {
|
||||
setOrder((current) => {
|
||||
const index = current.indexOf(id);
|
||||
const target = index + delta;
|
||||
if (index < 0 || target < 0 || target >= current.length) return current;
|
||||
const next = [...current];
|
||||
const [item] = next.splice(index, 1);
|
||||
next.splice(target, 0, item);
|
||||
return next;
|
||||
});
|
||||
}
|
||||
|
||||
async function save(event) {
|
||||
event.preventDefault();
|
||||
setError("");
|
||||
try {
|
||||
await api(`/api/v1/elements/${host.element.id}/dispatches`, {
|
||||
method: "POST",
|
||||
body: fieldBody(scope, {
|
||||
expected_version: host.element.version,
|
||||
channel,
|
||||
sent_on: sentOn || null,
|
||||
counterpart: counterpart.trim() || null,
|
||||
attachment_element_ids: order.filter((id) => chosen.has(id)),
|
||||
evidence: [],
|
||||
historical_gap: historical,
|
||||
}),
|
||||
});
|
||||
onDone();
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<form className="stack" onSubmit={save}>
|
||||
<p>Versand von <strong>{host.element.title}</strong> dokumentieren. Dabei wird nichts verschickt. Die Anlagenliste ist ein Vorschlag für diesen Versand.</p>
|
||||
<label>
|
||||
Weg
|
||||
<select value={channel} onChange={(event) => setChannel(event.target.value)}>
|
||||
<option value="email">E-Mail</option>
|
||||
<option value="post">Post</option>
|
||||
<option value="other">Sonstiger Weg</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
Versanddatum
|
||||
<input type="date" value={sentOn} onChange={(event) => setSentOn(event.target.value)} />
|
||||
</label>
|
||||
<p className="muted">Leer lassen, wenn der Versandtag unbekannt ist. Der Erfassungszeitpunkt ersetzt ihn nicht.</p>
|
||||
<label>
|
||||
Gegenüber
|
||||
<input value={counterpart} onChange={(event) => setCounterpart(event.target.value)} maxLength={200} />
|
||||
</label>
|
||||
<p className="muted">Leer lassen, wenn das Gegenüber unbekannt ist.</p>
|
||||
<fieldset>
|
||||
<legend>Tatsächlich mitversendet</legend>
|
||||
<ol className="choice-list">
|
||||
{order.map((id, index) => {
|
||||
const item = proposal.find((entry) => entry.element_id === id);
|
||||
if (!item) return null;
|
||||
return (
|
||||
<li key={id}>
|
||||
<label>
|
||||
<input type="checkbox" checked={chosen.has(id)} onChange={() => setChosen((current) => {
|
||||
const next = new Set(current);
|
||||
if (next.has(id)) next.delete(id);
|
||||
else next.add(id);
|
||||
return next;
|
||||
})} />
|
||||
<span>{item.title}</span>
|
||||
<span className="muted">{formatDate(item.document_on)}</span>
|
||||
</label>
|
||||
<span className="choice-list__move">
|
||||
<button type="button" disabled={index === 0} onClick={() => move(id, -1)} aria-label={`${item.title} nach oben`}>↑</button>
|
||||
<button type="button" disabled={index === order.length - 1} onClick={() => move(id, 1)} aria-label={`${item.title} nach unten`}>↓</button>
|
||||
</span>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ol>
|
||||
{!proposal.length ? <p className="muted">Keine zugeordnete Anlage. Das Schreiben kann allein dokumentiert werden.</p> : null}
|
||||
</fieldset>
|
||||
<label>
|
||||
<input type="checkbox" checked={historical} onChange={(event) => setHistorical(event.target.checked)} />
|
||||
Historische Originalfassung liegt nicht mehr vor
|
||||
</label>
|
||||
{error ? <p className="error">{error}</p> : null}
|
||||
<button type="submit" disabled={pending}>Versand dokumentieren</button>
|
||||
<button type="button" className="quiet" onClick={onClose}>Abbrechen</button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
export function EvidenceDialog({ element, hosts, scope, pending, presetDispatchId, replace = null, onClose, onDone }) {
|
||||
const [hostId, setHostId] = useState(hosts[0]?.element.id || "");
|
||||
const host = hosts.find((item) => item.element.id === hostId) || null;
|
||||
const [dispatchId, setDispatchId] = useState(
|
||||
presetDispatchId !== undefined ? presetDispatchId : (host?.correspondence?.dispatches?.[0]?.id || ""),
|
||||
);
|
||||
const [role, setRole] = useState("other");
|
||||
const [fold, setFold] = useState("evidence");
|
||||
const [channel, setChannel] = useState("other");
|
||||
const [sentOn, setSentOn] = useState("");
|
||||
const [counterpart, setCounterpart] = useState("");
|
||||
const [result, setResult] = useState(null);
|
||||
const [error, setError] = useState("");
|
||||
|
||||
async function save(event) {
|
||||
event.preventDefault();
|
||||
if (!host) return;
|
||||
setError("");
|
||||
try {
|
||||
if (replace?.dispatchId && replace.dispatchId !== dispatchId) {
|
||||
await api(`/api/v1/dispatches/${replace.dispatchId}/evidence/${element.id}/detach`, {
|
||||
method: "POST",
|
||||
body: fieldBody(scope, { expected_version: replace.version }),
|
||||
});
|
||||
}
|
||||
let target = dispatchId;
|
||||
if (!target) {
|
||||
const created = await api(`/api/v1/elements/${host.element.id}/dispatches`, {
|
||||
method: "POST",
|
||||
body: fieldBody(scope, {
|
||||
expected_version: host.element.version,
|
||||
channel,
|
||||
sent_on: sentOn || null,
|
||||
counterpart: counterpart.trim() || null,
|
||||
attachment_element_ids: [],
|
||||
evidence: [{ element_id: element.id, role, fold }],
|
||||
historical_gap: false,
|
||||
capture_editions: false,
|
||||
}),
|
||||
});
|
||||
const proof = (created.evidence || []).find((item) => item.element_id === element.id);
|
||||
setResult(proof || created);
|
||||
onDone(false);
|
||||
return;
|
||||
}
|
||||
const dispatch = (host.correspondence?.dispatches || []).find((item) => item.id === target);
|
||||
const proof = await api(`/api/v1/dispatches/${target}/evidence`, {
|
||||
method: "POST",
|
||||
body: fieldBody(scope, {
|
||||
expected_version: dispatch?.version || 1,
|
||||
element_id: element.id,
|
||||
role,
|
||||
fold,
|
||||
}),
|
||||
});
|
||||
setResult(proof);
|
||||
onDone(false);
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<form className="stack" onSubmit={save}>
|
||||
<p><strong>{element.title}</strong> als Beleg zu diesem Versand. E-Mail, Notiz, Foto und Paperless-Dokument bleiben das Original. An einem Versand können mehrere Belege liegen.</p>
|
||||
<label>
|
||||
Hauptschriftstück
|
||||
<select value={hostId} onChange={(event) => {
|
||||
const next = event.target.value;
|
||||
setHostId(next);
|
||||
const found = hosts.find((item) => item.element.id === next);
|
||||
setDispatchId(found?.correspondence?.dispatches?.[0]?.id || "");
|
||||
}}>
|
||||
{hosts.map((item) => <option key={item.element.id} value={item.element.id}>{item.element.title}</option>)}
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
Versand
|
||||
<select value={dispatchId} onChange={(event) => setDispatchId(event.target.value)}>
|
||||
<option value="">Neuen Versand in diesem Ablauf anlegen</option>
|
||||
{(host?.correspondence?.dispatches || []).map((item) => (
|
||||
<option key={item.id} value={item.id}>
|
||||
{item.sent_on ? formatDate(item.sent_on) : "undatiert"} · {item.channel_label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
{!dispatchId ? (
|
||||
<>
|
||||
<label>
|
||||
Weg
|
||||
<select value={channel} onChange={(event) => setChannel(event.target.value)}>
|
||||
<option value="email">E-Mail</option>
|
||||
<option value="post">Post</option>
|
||||
<option value="other">Sonstiger Weg</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>Versanddatum<input type="date" value={sentOn} onChange={(event) => setSentOn(event.target.value)} /></label>
|
||||
<label>Gegenüber<input value={counterpart} onChange={(event) => setCounterpart(event.target.value)} maxLength={200} /></label>
|
||||
</>
|
||||
) : null}
|
||||
<label>
|
||||
Rolle
|
||||
<select value={role} onChange={(event) => setRole(event.target.value)}>
|
||||
{RECEIPT_ROLES.map(([value, label]) => <option key={value} value={value}>{label}</option>)}
|
||||
</select>
|
||||
</label>
|
||||
<fieldset>
|
||||
<legend>Darstellung in der Liste</legend>
|
||||
<label><input type="radio" name="evidence-fold" checked={fold === "evidence"} onChange={() => setFold("evidence")} /> Nur am Versand zeigen</label>
|
||||
<label><input type="radio" name="evidence-fold" checked={fold === "keep"} onChange={() => setFold("keep")} /> Zusätzlich als eigenen Eintrag behalten</label>
|
||||
</fieldset>
|
||||
{result ? <ComparisonList comparisons={result.comparisons || []} state={result.source_state} reason={result.gap_reason} /> : null}
|
||||
{error ? <p className="error">{error}</p> : null}
|
||||
<button type="submit" disabled={pending || !host}>Beleg zuordnen</button>
|
||||
<button type="button" className="quiet" onClick={onClose}>Schließen</button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
export function ComparisonList({ comparisons = [], state, reason }) {
|
||||
if (!comparisons.length && state !== "gap") return null;
|
||||
return (
|
||||
<div className="comparison">
|
||||
{state === "gap" ? <p>Originalfassung nicht gesichert: {reason}</p> : null}
|
||||
{state === "identified" ? <p>Nachweis manuell zugeordnet. Gleiche Dateinamen werden nicht automatisch zusammengeführt.</p> : null}
|
||||
<ul>
|
||||
{comparisons.map((item) => (
|
||||
<li key={`${item.filename}-${item.sha256}`}>
|
||||
<strong>{item.filename}</strong>
|
||||
{item.disposition === "same_bytes" ? ` · gleicher Dateiinhalt wie ${item.matches.map((match) => match.title).join(", ")} · Vorschlag, nicht automatisch zugeordnet` : null}
|
||||
{item.disposition === "same_name_different_bytes" ? ` · gleicher Name, anderer Inhalt als ${item.matches.map((match) => match.title).join(", ")}` : null}
|
||||
{item.disposition === "distinct" ? " · eigener Inhalt" : null}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function chipPointer(enabled, payload, onCarryStart) {
|
||||
if (!enabled) return {};
|
||||
return {
|
||||
onPointerDown(event) {
|
||||
onCarryStart?.(event, payload);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function openTitleProps(onOpen) {
|
||||
return {
|
||||
role: "link",
|
||||
tabIndex: 0,
|
||||
onClick(event) {
|
||||
const row = event.currentTarget.closest(".use-chip");
|
||||
if (row?.dataset.dragged === "1") {
|
||||
delete row.dataset.dragged;
|
||||
return;
|
||||
}
|
||||
onOpen();
|
||||
},
|
||||
onKeyDown(event) {
|
||||
if (event.key !== "Enter" && event.key !== " ") return;
|
||||
event.preventDefault();
|
||||
onOpen();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function UnitDetail({
|
||||
binding,
|
||||
canEdit,
|
||||
pending,
|
||||
onOpen,
|
||||
onDetach,
|
||||
onDetachEvidence,
|
||||
onUnfold,
|
||||
onCarryStart,
|
||||
children,
|
||||
}) {
|
||||
const pack = binding.correspondence || {};
|
||||
const attachments = pack.attachments || [];
|
||||
const dispatches = pack.dispatches || [];
|
||||
const [attachmentsOpen, setAttachmentsOpen] = useState(false);
|
||||
const [receiptsOpen, setReceiptsOpen] = useState(false);
|
||||
if (!attachments.length && !dispatches.length) {
|
||||
return typeof children === "function" ? children(null, null) : null;
|
||||
}
|
||||
const evidenceCount = dispatches.reduce((sum, item) => sum + (item.evidence || []).length, 0);
|
||||
const shipmentCount = dispatches.filter(isShipment).length;
|
||||
const attachmentLabel = attachments.length === 1 ? "1 Anlage" : `${attachments.length} Anlagen`;
|
||||
const receiptParts = [];
|
||||
if (shipmentCount === 1) receiptParts.push("1 Versand");
|
||||
else if (shipmentCount > 1) receiptParts.push(`${shipmentCount} Versände`);
|
||||
if (evidenceCount === 1) receiptParts.push("1 Beleg");
|
||||
else if (evidenceCount > 1) receiptParts.push(`${evidenceCount} Belege`);
|
||||
const receiptLabel = receiptParts.join(" · ");
|
||||
const switches = (
|
||||
<span className="unit-switches">
|
||||
{attachments.length ? (
|
||||
<button type="button" className="unit-switch" aria-expanded={attachmentsOpen} onClick={() => setAttachmentsOpen((value) => !value)}>
|
||||
{attachmentLabel}
|
||||
</button>
|
||||
) : null}
|
||||
{dispatches.length ? (
|
||||
<button type="button" className="unit-switch" aria-expanded={receiptsOpen} onClick={() => setReceiptsOpen((value) => !value)}>
|
||||
{receiptLabel || "Belege"}
|
||||
</button>
|
||||
) : null}
|
||||
</span>
|
||||
);
|
||||
const lists = attachmentsOpen || receiptsOpen ? (
|
||||
<div className="unit-detail unit-detail--slim">
|
||||
{attachmentsOpen && attachments.length ? (
|
||||
<section>
|
||||
<h4>Anlagen</h4>
|
||||
<ol>
|
||||
{attachments.map((item, index) => (
|
||||
<li
|
||||
key={item.id}
|
||||
className="use-chip"
|
||||
data-carry={`attachment:${item.element_id}`}
|
||||
{...chipPointer(canEdit && !pending, {
|
||||
source: "attachment",
|
||||
elementId: item.element_id,
|
||||
hostElementId: binding.element.id,
|
||||
hostBindingId: binding.id,
|
||||
bindingId: item.binding_id || "",
|
||||
title: item.title,
|
||||
}, onCarryStart)}
|
||||
>
|
||||
{canEdit ? <span className="use-chip__grip" aria-hidden="true" /> : null}
|
||||
<span className="use-chip__title" {...openTitleProps(() => onOpen(item.element_id))}>
|
||||
{index + 1}. {item.title}
|
||||
</span>
|
||||
<span className="muted">{formatDate(item.document_on)}</span>
|
||||
{canEdit ? (
|
||||
<button type="button" className="quiet" disabled={pending} onClick={() => onDetach(item.element_id)}>In die Liste</button>
|
||||
) : null}
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
</section>
|
||||
) : null}
|
||||
{receiptsOpen ? dispatches.map((item) => (
|
||||
<section key={item.id}>
|
||||
<h4>{receiptHeading(item)}</h4>
|
||||
{item.evidence?.length ? (
|
||||
<ul>
|
||||
{item.evidence.map((proof) => (
|
||||
<li
|
||||
key={proof.id}
|
||||
className="use-chip"
|
||||
data-carry={`evidence:${proof.element_id}`}
|
||||
{...chipPointer(canEdit && !pending, {
|
||||
source: "evidence",
|
||||
elementId: proof.element_id,
|
||||
dispatchId: item.id,
|
||||
hostElementId: binding.element.id,
|
||||
hostBindingId: binding.id,
|
||||
version: item.version,
|
||||
title: proof.title,
|
||||
}, onCarryStart)}
|
||||
>
|
||||
{canEdit ? <span className="use-chip__grip" aria-hidden="true" /> : null}
|
||||
<span className="use-chip__title" {...openTitleProps(() => onOpen(proof.element_id))}>
|
||||
{receiptCaption(proof)}: {proof.title}
|
||||
</span>
|
||||
<span className="muted">{formatDate(proof.document_on)}</span>
|
||||
{proof.source_state === "gap" ? <span>Lücke: {proof.gap_reason}</span> : null}
|
||||
{canEdit ? (
|
||||
<button type="button" className="quiet" disabled={pending} onClick={() => onDetachEvidence(proof, item)}>
|
||||
In die Liste
|
||||
</button>
|
||||
) : null}
|
||||
{canEdit && proof.listed_fold === "evidence" ? (
|
||||
<button type="button" className="quiet" disabled={pending} onClick={() => onUnfold(proof.element_id)}>
|
||||
Zusätzlich in der Liste zeigen
|
||||
</button>
|
||||
) : null}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
) : <p className="muted">Ohne Beleg</p>}
|
||||
</section>
|
||||
)) : null}
|
||||
</div>
|
||||
) : null;
|
||||
if (typeof children === "function") return children(switches, lists);
|
||||
return (
|
||||
<div className="unit-fold">
|
||||
{switches}
|
||||
{lists}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function Chronology({ bindings, direction, itemHref, selectedId, onOpen }) {
|
||||
const events = [];
|
||||
for (const binding of bindings || []) {
|
||||
if (binding.correspondence?.fold !== "evidence") {
|
||||
events.push({
|
||||
key: `doc-${binding.id}`,
|
||||
date: binding.element?.dates?.document_on || "",
|
||||
label: "Unterlage",
|
||||
title: binding.element?.title || "",
|
||||
detail: `Dokumentdatum ${formatDate(binding.element?.dates?.document_on)}`,
|
||||
binding,
|
||||
});
|
||||
}
|
||||
for (const dispatch of binding.correspondence?.dispatches || []) {
|
||||
events.push({
|
||||
key: `send-${dispatch.id}`,
|
||||
date: dispatch.sent_on || "",
|
||||
label: isShipment(dispatch) ? "Versand" : "Beleg",
|
||||
title: binding.element?.title || "",
|
||||
detail: [
|
||||
dispatch.undated ? "Versand undatiert" : `Versanddatum ${formatDate(dispatch.sent_on)}`,
|
||||
dispatch.channel_label,
|
||||
(dispatch.evidence || []).length === 1
|
||||
? "1 Beleg"
|
||||
: (dispatch.evidence || []).length
|
||||
? `${dispatch.evidence.length} Belege`
|
||||
: "ohne Beleg",
|
||||
].join(" · "),
|
||||
binding,
|
||||
dispatch,
|
||||
});
|
||||
}
|
||||
}
|
||||
events.sort((left, right) => {
|
||||
if (!left.date && !right.date) return left.key.localeCompare(right.key);
|
||||
if (!left.date) return 1;
|
||||
if (!right.date) return -1;
|
||||
const compared = left.date.localeCompare(right.date);
|
||||
if (compared) return direction === "desc" ? -compared : compared;
|
||||
return left.key.localeCompare(right.key);
|
||||
});
|
||||
const undated = events.filter((item) => !item.date);
|
||||
const dated = events.filter((item) => item.date);
|
||||
const ordered = direction === "desc" ? [...undated, ...dated] : [...dated, ...undated];
|
||||
const groups = [];
|
||||
for (const event of ordered) {
|
||||
const name = event.date ? formatDate(event.date) : "Ohne Datum";
|
||||
const last = groups[groups.length - 1];
|
||||
if (!last || last.name !== name) groups.push({ name, events: [event] });
|
||||
else last.events.push(event);
|
||||
}
|
||||
if (!groups.length) return <p className="muted">In dieser Ansicht ist noch nichts zu sehen.</p>;
|
||||
return (
|
||||
<div className="chrono">
|
||||
{groups.map((group) => (
|
||||
<section key={group.name}>
|
||||
<h3>{group.name}</h3>
|
||||
<ol className="preview-list">
|
||||
{group.events.map((event) => (
|
||||
<li key={event.key} className={selectedId === event.binding.id ? "preview-row is-selected" : "preview-row"}>
|
||||
<div className="preview-row__body">
|
||||
<Link to={itemHref(event.binding)} onClick={(click) => {
|
||||
if (click.metaKey || click.ctrlKey || click.shiftKey || click.altKey || click.button !== 0) return;
|
||||
click.preventDefault();
|
||||
onOpen(event.binding);
|
||||
}}>
|
||||
<strong>{event.label}: {event.title}</strong>
|
||||
</Link>
|
||||
<span className="preview-row__facts">{event.detail}</span>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
</section>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export async function restoreFold(bindingId, version, scope) {
|
||||
await api(`/api/v1/bindings/${bindingId}/fold`, {
|
||||
method: "PATCH",
|
||||
body: fieldBody(scope, { expected_version: version, fold: null }),
|
||||
});
|
||||
}
|
||||
@@ -320,17 +320,20 @@ function kindLabel(element) {
|
||||
return kind;
|
||||
}
|
||||
|
||||
export function ShareBox({ path, grants, onChange }) {
|
||||
export function ShareBox({ path, grants, onChange, allowSources = false }) {
|
||||
const [email, setEmail] = useState("");
|
||||
const [canEdit, setCanEdit] = useState(true);
|
||||
const [canShare, setCanShare] = useState(false);
|
||||
const [useOwnerSources, setUseOwnerSources] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
|
||||
async function submit(event) {
|
||||
event.preventDefault();
|
||||
setError("");
|
||||
const body = { email, can_read: true, can_edit: canEdit, can_share: canShare };
|
||||
if (allowSources) body.use_owner_sources = useOwnerSources;
|
||||
try {
|
||||
await api(path, { method: "POST", body: { email, can_read: true, can_edit: canEdit, can_share: canShare } });
|
||||
await api(path, { method: "POST", body });
|
||||
setEmail("");
|
||||
onChange();
|
||||
} catch (err) {
|
||||
@@ -354,6 +357,12 @@ export function ShareBox({ path, grants, onChange }) {
|
||||
</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>
|
||||
{allowSources ? (
|
||||
<label className="check">
|
||||
<input type="checkbox" checked={useOwnerSources} onChange={(event) => setUseOwnerSources(event.target.checked)} />
|
||||
Verknüpfte Originale über meine Zugänge zeigen
|
||||
</label>
|
||||
) : null}
|
||||
<button type="submit">Freigeben</button>
|
||||
<ErrorNote error={error} />
|
||||
</form>
|
||||
@@ -362,7 +371,11 @@ export function ShareBox({ path, grants, onChange }) {
|
||||
{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>
|
||||
<small>
|
||||
{grant.can_edit ? "Bearbeiten" : "Lesen"}
|
||||
{grant.can_share ? ", Weitergeben" : ""}
|
||||
{grant.use_owner_sources ? ", Originale über meine Zugänge" : ""}
|
||||
</small>
|
||||
<button type="button" className="quiet" onClick={() => revoke(grant.id)}>Entziehen</button>
|
||||
</li>
|
||||
))}
|
||||
|
||||
@@ -72,7 +72,7 @@ function TreeRow({ node, onNavigate, ancestor = false, toggle = null }) {
|
||||
const label = (
|
||||
<span className="nav-tree__title">
|
||||
{node.title}
|
||||
{node.kind === "Kapitel" || node.kind === "Unterkapitel" || node.kind === "Teilvorgang" ? (
|
||||
{node.kind === "Teilvorgang" ? (
|
||||
<span className="nav-tree__kind">{node.kind}</span>
|
||||
) : null}
|
||||
</span>
|
||||
@@ -159,13 +159,15 @@ function scopeContents({ chapters, chapterId, allLabel, overview, onChapter, can
|
||||
onSelect: overview.onSelect,
|
||||
});
|
||||
}
|
||||
items.push({
|
||||
id: "all-contents",
|
||||
title: allLabel,
|
||||
kind: "Inhalte",
|
||||
current: !chapterId && !overview?.active,
|
||||
onSelect: () => onChapter?.(""),
|
||||
});
|
||||
if (allLabel) {
|
||||
items.push({
|
||||
id: "all-contents",
|
||||
title: allLabel,
|
||||
kind: "Inhalte",
|
||||
current: !chapterId && !overview?.active,
|
||||
onSelect: () => onChapter?.(""),
|
||||
});
|
||||
}
|
||||
const byParent = new Map();
|
||||
chapters.forEach((chapter) => {
|
||||
const key = chapter.parent_chapter_id || "";
|
||||
@@ -192,16 +194,23 @@ function scopeContents({ chapters, chapterId, allLabel, overview, onChapter, can
|
||||
return items;
|
||||
}
|
||||
|
||||
function attachScope(nodes, extras) {
|
||||
function attachScope(nodes, extras, onContainerSelect) {
|
||||
return (nodes || []).map((node) => {
|
||||
const children = attachScope(node.children, extras);
|
||||
const children = attachScope(node.children, extras, onContainerSelect);
|
||||
if (!node.current) return { ...node, children };
|
||||
return { ...node, children: [...extras, ...children] };
|
||||
const nested = [...extras, ...children];
|
||||
const childCurrent = Boolean(onContainerSelect) && nested.some(branchHasCurrent);
|
||||
return {
|
||||
...node,
|
||||
current: onContainerSelect ? !childCurrent : node.current,
|
||||
...(onContainerSelect ? { onSelect: onContainerSelect } : {}),
|
||||
children: nested,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function treeWithScope(nodes, extras) {
|
||||
const attached = attachScope(nodes, extras);
|
||||
function treeWithScope(nodes, extras, onContainerSelect) {
|
||||
const attached = attachScope(nodes, extras, onContainerSelect);
|
||||
if (attached.some(branchHasCurrent)) return attached;
|
||||
return [...extras, ...attached];
|
||||
}
|
||||
@@ -224,7 +233,8 @@ export function StructureNavigator({
|
||||
}) {
|
||||
const [opened, setOpened] = useState(() => new Set());
|
||||
const [closed, setClosed] = useState(() => new Set());
|
||||
const tree = treeWithScope(nodes, scopeContents({ chapters, chapterId, allLabel, overview, onChapter, canReorder, onMoveChapter }));
|
||||
const extras = scopeContents({ chapters, chapterId, allLabel, overview, onChapter, canReorder, onMoveChapter });
|
||||
const tree = treeWithScope(nodes, extras, allLabel ? null : () => onChapter?.(""));
|
||||
|
||||
function isOpen(node, unfold) {
|
||||
if (!node.children?.length) return false;
|
||||
|
||||
+342
-17
@@ -98,6 +98,7 @@ input, select, textarea {
|
||||
border: 1.5px solid var(--border2);
|
||||
border-radius: 8px;
|
||||
}
|
||||
input[type="date"] { user-select: text; touch-action: manipulation; }
|
||||
input:focus, select:focus, textarea:focus { outline: none; border-color: var(--accent); }
|
||||
textarea { min-height: 7rem; resize: vertical; }
|
||||
label { display: grid; gap: 6px; font-size: 14px; font-weight: 600; color: var(--text1); }
|
||||
@@ -141,6 +142,37 @@ label { display: grid; gap: 6px; font-size: 14px; font-weight: 600; color: var(-
|
||||
.error { color: var(--danger); font-size: 14px; }
|
||||
.banner { margin: 0 16px 8px; }
|
||||
|
||||
.app-root {
|
||||
height: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
.app-root__main {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
.app-root__main > .app-shell,
|
||||
.app-root__main > .login,
|
||||
.app-root > .boot {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
height: auto;
|
||||
}
|
||||
.env-banner {
|
||||
margin: 0;
|
||||
flex: none;
|
||||
background: var(--warn);
|
||||
color: #fff;
|
||||
text-align: center;
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.06em;
|
||||
text-transform: uppercase;
|
||||
padding: calc(6px + env(safe-area-inset-top, 0px)) 12px 6px;
|
||||
}
|
||||
|
||||
.boot, .login {
|
||||
min-height: 100%;
|
||||
display: grid;
|
||||
@@ -199,14 +231,21 @@ label { display: grid; gap: 6px; font-size: 14px; font-weight: 600; color: var(-
|
||||
width: 100%;
|
||||
max-width: 600px;
|
||||
display: flex;
|
||||
flex-wrap: nowrap;
|
||||
justify-content: flex-start;
|
||||
overflow-x: auto;
|
||||
overscroll-behavior-x: contain;
|
||||
scrollbar-width: none;
|
||||
background: var(--surface);
|
||||
border-top: 1px solid var(--border);
|
||||
z-index: 20;
|
||||
padding: var(--nav-pad-top) 6px env(safe-area-inset-bottom, 0px);
|
||||
min-height: calc(var(--nav-h) + var(--nav-pad-top) + env(safe-area-inset-bottom, 0px));
|
||||
}
|
||||
.bottom-nav::-webkit-scrollbar { display: none; }
|
||||
.nav-item {
|
||||
flex: 1;
|
||||
flex: 1 0 auto;
|
||||
min-width: 4.5rem;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
@@ -219,6 +258,17 @@ label { display: grid; gap: 6px; font-size: 14px; font-weight: 600; color: var(-
|
||||
line-height: 1.15;
|
||||
padding: 2px 4px 4px;
|
||||
}
|
||||
button.nav-item {
|
||||
background: transparent;
|
||||
border: 0;
|
||||
border-radius: 0;
|
||||
min-height: 0;
|
||||
color: var(--text3);
|
||||
font-weight: 500;
|
||||
font-size: 10px;
|
||||
}
|
||||
button.nav-item:active { transform: none; }
|
||||
.nav-item span { white-space: nowrap; }
|
||||
.nav-item.active { color: var(--accent); }
|
||||
.nav-item svg { flex-shrink: 0; }
|
||||
|
||||
@@ -477,6 +527,33 @@ label { display: grid; gap: 6px; font-size: 14px; font-weight: 600; color: var(-
|
||||
.export-review > p { text-align: left; }
|
||||
.add-choices { display: grid; gap: 8px; }
|
||||
.add-choices button { min-height: 44px; justify-content: flex-start; }
|
||||
.file-batch {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
display: grid;
|
||||
gap: 10px;
|
||||
max-height: 280px;
|
||||
overflow: auto;
|
||||
}
|
||||
.file-batch li {
|
||||
display: grid;
|
||||
gap: 6px;
|
||||
padding: 10px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 10px;
|
||||
background: var(--surface2);
|
||||
}
|
||||
.file-batch label { overflow-wrap: anywhere; }
|
||||
.file-batch__remove { justify-self: start; }
|
||||
.file-batch__file {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
}
|
||||
.file-batch__file span { min-width: 0; overflow-wrap: anywhere; }
|
||||
.file-batch__file button { flex: none; }
|
||||
.hierarchy__parent { margin-bottom: 8px; }
|
||||
.order-bar { display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 12px; }
|
||||
.order-bar button { min-height: 44px; }
|
||||
@@ -496,12 +573,59 @@ label { display: grid; gap: 6px; font-size: 14px; font-weight: 600; color: var(-
|
||||
.content-row__title { font-weight: 650; }
|
||||
.content-row__kind { color: var(--text3); font-size: 13px; }
|
||||
.content-row__move { display: flex; gap: 4px; }
|
||||
.chapter-head { display: flex; flex-wrap: wrap; gap: 4px 8px; align-items: center; margin: 0 0 2px; padding: 0; border: 0; border-radius: 0; background: transparent; min-height: 32px; }
|
||||
.chapter-head { display: flex; flex-wrap: wrap; gap: 4px 8px; align-items: center; margin: 10px 0 4px; padding: 4px 8px; border: 0; border-radius: 8px; background: color-mix(in srgb, var(--brand) 8%, transparent); min-height: 32px; }
|
||||
.chapter-head.is-movable { cursor: grab; touch-action: none; user-select: none; }
|
||||
.chapter-head.is-movable:active { cursor: grabbing; }
|
||||
.chapter-head.is-movable .chapter-date,
|
||||
.chapter-head.is-movable .chapter-move { cursor: auto; touch-action: auto; user-select: auto; }
|
||||
.chapter-title { margin: 22px 0 4px; font-size: 15px; letter-spacing: 0; text-transform: none; color: var(--text1); font-weight: 700; }
|
||||
.chapter-title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin: 0;
|
||||
font-size: 15px;
|
||||
letter-spacing: 0.01em;
|
||||
text-transform: none;
|
||||
color: var(--brand);
|
||||
font-weight: 700;
|
||||
}
|
||||
.chapter-title.is-nested { font-size: 14px; font-weight: 650; }
|
||||
.chapter-title svg { width: 18px; height: 18px; flex: 0 0 18px; }
|
||||
.chapter-title span { min-width: 0; }
|
||||
.chapter-plus {
|
||||
width: 36px;
|
||||
min-width: 36px;
|
||||
height: 36px;
|
||||
min-height: 36px;
|
||||
padding: 0;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex: none;
|
||||
background: transparent;
|
||||
color: var(--brand);
|
||||
border: 1px solid var(--border2);
|
||||
border-radius: 8px;
|
||||
}
|
||||
.chapter-plus svg { width: 18px; height: 18px; }
|
||||
.chapter-fold {
|
||||
width: 28px;
|
||||
min-width: 28px;
|
||||
height: 28px;
|
||||
min-height: 28px;
|
||||
padding: 0;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex: none;
|
||||
border: 0;
|
||||
border-radius: 6px;
|
||||
background: transparent;
|
||||
color: var(--brand);
|
||||
font-size: 16px;
|
||||
line-height: 1;
|
||||
}
|
||||
.chapter-fold:hover, .chapter-fold:focus-visible { background: var(--accent-light); }
|
||||
.chapter-menu, .record-tools, .chapter-move { display: inline-flex; gap: 0; flex: 0 0 auto; align-items: center; }
|
||||
.icon-button--compact { width: 32px; min-width: 32px; height: 32px; }
|
||||
.icon-button--compact svg { width: 16px; height: 16px; }
|
||||
@@ -624,6 +748,7 @@ button.hierarchy__row { width: 100%; min-height: 34px; padding: 6px 8px; border:
|
||||
.preview-row > .insert-line { grid-column: 1 / -1; }
|
||||
.preview-row.is-dragging { opacity: 0.4; }
|
||||
.preview-row__body { display: grid; gap: 2px; min-width: 0; }
|
||||
.preview-row__headline { display: flex; flex-wrap: wrap; align-items: baseline; justify-content: flex-start; gap: 2px 12px; min-width: 0; }
|
||||
.preview-row__title, .preview-row__text { color: inherit; text-decoration: none; min-width: 0; }
|
||||
.preview-row__title strong, .preview-row__main strong {
|
||||
display: -webkit-box;
|
||||
@@ -720,6 +845,17 @@ button.hierarchy__row { width: 100%; min-height: 34px; padding: 6px 8px; border:
|
||||
.menu-popover__panel button[aria-selected="true"] { background: var(--accent-light); color: var(--brand); }
|
||||
.menu-popover__panel button.danger { background: #fcebeb; color: var(--danger); }
|
||||
.menu-popover__label { margin: 6px 4px 0; color: var(--text3); font-size: 12px; font-weight: 700; }
|
||||
.bezug-entry { display: grid; gap: 2px; }
|
||||
.paperless-pick {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
align-items: flex-start;
|
||||
min-height: 44px;
|
||||
padding: 8px 2px;
|
||||
font-weight: 600;
|
||||
}
|
||||
.paperless-pick input { width: 20px; min-width: 20px; min-height: 20px; margin-top: 2px; }
|
||||
.paperless-pick span { min-width: 0; overflow-wrap: anywhere; }
|
||||
.trail__more {
|
||||
min-height: 28px;
|
||||
height: auto;
|
||||
@@ -924,7 +1060,8 @@ button.hierarchy__row { width: 100%; min-height: 34px; padding: 6px 8px; border:
|
||||
.order-choice { align-items: center; flex-direction: row; max-width: none; }
|
||||
.order-choice select { width: auto; min-width: 0; flex: 1; }
|
||||
.preview-row__text { -webkit-line-clamp: 1; }
|
||||
.preview-row__facts { white-space: normal; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; }
|
||||
.preview-row__facts { white-space: normal; display: -webkit-box; -webkit-line-clamp: 4; -webkit-box-orient: vertical; }
|
||||
.chapter-nest { margin-left: 8px; padding-left: 8px; }
|
||||
.entry-mark, .entry-mark--photo { width: 36px; height: 36px; flex-basis: 36px; }
|
||||
}
|
||||
|
||||
@@ -1066,7 +1203,16 @@ button.hierarchy__row { width: 100%; min-height: 34px; padding: 6px 8px; border:
|
||||
box-shadow: var(--shadow);
|
||||
}
|
||||
.workspace-scrim { position: absolute; inset: 0; z-index: 5; border: 0; background: rgba(28, 27, 24, 0.28); }
|
||||
.workspace-main { padding: 22px 28px 32px; }
|
||||
.workspace-main { --pin-x: 28px; --pin-y: 22px; padding: var(--pin-y) var(--pin-x) 32px; }
|
||||
.workspace-pin {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 4;
|
||||
background: var(--bg);
|
||||
margin: calc(var(--pin-y) * -1) calc(var(--pin-x) * -1) 12px;
|
||||
padding: var(--pin-y) var(--pin-x) 0;
|
||||
}
|
||||
.workspace-pin .surface-tabs { margin-bottom: 0; }
|
||||
.workspace-reader { background: #eef2ee; border-left: 1px solid var(--border); display: flex; min-height: 0; }
|
||||
.workspace-head, .title-row, .page-actions, .content-toolbar, .reader-pane__bar, .reader-controls {
|
||||
display: flex;
|
||||
@@ -1157,25 +1303,34 @@ button.hierarchy__row { width: 100%; min-height: 34px; padding: 6px 8px; border:
|
||||
}
|
||||
.chapter-link__move { display: flex; gap: 2px; flex: none; align-items: center; }
|
||||
.chapter-link__move button {
|
||||
min-height: 44px;
|
||||
width: 44px;
|
||||
height: 44px;
|
||||
min-height: 28px;
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
padding: 0;
|
||||
font-size: 16px;
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
background: transparent;
|
||||
color: var(--text3);
|
||||
border-radius: 4px;
|
||||
}
|
||||
.nav-tree__toggle {
|
||||
width: 44px;
|
||||
min-width: 44px;
|
||||
height: 44px;
|
||||
width: 22px;
|
||||
min-width: 22px;
|
||||
height: 28px;
|
||||
min-height: 28px;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
border-radius: 4px;
|
||||
background: transparent;
|
||||
color: var(--text2);
|
||||
font-size: 16px;
|
||||
font-size: 13px;
|
||||
line-height: 1;
|
||||
}
|
||||
.structure .chapter-add {
|
||||
min-height: 32px;
|
||||
padding: 4px 10px;
|
||||
margin-top: 6px;
|
||||
font-size: 13px;
|
||||
}
|
||||
.nav-tree__toggle.is-empty { visibility: hidden; }
|
||||
.nav-tree__kind {
|
||||
@@ -1193,10 +1348,180 @@ button.hierarchy__row { width: 100%; min-height: 34px; padding: 6px 8px; border:
|
||||
font-weight: 700;
|
||||
}
|
||||
.chapter-nest {
|
||||
margin-left: 12px;
|
||||
padding-left: 10px;
|
||||
border-left: 1px solid var(--border);
|
||||
margin: 4px 0 8px 16px;
|
||||
padding: 2px 0 8px 12px;
|
||||
border-left: 2px solid color-mix(in srgb, var(--brand) 35%, var(--border));
|
||||
border-bottom: 1px solid var(--border2);
|
||||
}
|
||||
.choice-list { list-style: none; margin: 0; padding: 0; display: grid; gap: 6px; }
|
||||
.choice-list li, .choice-list label { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
|
||||
.choice-list--scroll { max-height: 240px; overflow: auto; }
|
||||
.choice-list__move { display: inline-flex; gap: 4px; margin-left: auto; }
|
||||
.unit-fold { display: grid; justify-items: start; gap: 2px; margin-top: 2px; }
|
||||
.unit-switches { display: flex; flex-wrap: wrap; justify-content: flex-start; gap: 2px 12px; }
|
||||
button.unit-switch {
|
||||
min-height: 22px;
|
||||
height: 22px;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
border-radius: 0;
|
||||
background: transparent;
|
||||
color: var(--text2);
|
||||
font-size: 13px;
|
||||
font-weight: 650;
|
||||
line-height: 22px;
|
||||
justify-content: flex-start;
|
||||
}
|
||||
button.unit-switch[aria-expanded="true"] { color: var(--brand); }
|
||||
.unit-detail, .comparison, .chrono { display: grid; gap: 8px; margin-top: 8px; }
|
||||
.unit-detail--slim { gap: 4px; margin-top: 2px; justify-items: start; text-align: left; }
|
||||
.unit-detail h4, .chrono h3 { margin: 0; font-size: 13px; text-align: left; }
|
||||
.unit-detail section { display: grid; gap: 4px; padding: 8px; border: 1px solid var(--border); border-radius: 8px; background: color-mix(in srgb, var(--surface) 88%, var(--bg)); }
|
||||
.unit-detail--slim section { padding: 0 0 0 8px; border: 0; border-left: 1px solid var(--border); border-radius: 0; background: transparent; gap: 2px; }
|
||||
.unit-detail--slim button.quiet, .unit-detail--slim summary { min-height: 22px; height: 22px; padding: 0 6px; font-size: 12px; }
|
||||
.unit-detail ol, .unit-detail ul, .comparison ul { margin: 0; padding: 0; list-style: none; display: grid; gap: 4px; }
|
||||
.unit-detail--slim ol, .unit-detail--slim ul { gap: 0; }
|
||||
.unit-detail li { display: flex; flex-wrap: wrap; justify-content: flex-start; gap: 2px 10px; align-items: center; min-width: 0; max-width: 100%; min-height: 22px; text-align: left; }
|
||||
.unit-detail li .muted { white-space: nowrap; }
|
||||
.use-chip { cursor: grab; }
|
||||
.use-chip__grip { width: 10px; height: 14px; border: 0; padding: 0; border-left: 2px dotted var(--text3); border-right: 2px dotted var(--text3); background: transparent; flex: none; }
|
||||
.use-chip__title { cursor: pointer; font-weight: 600; text-align: left; }
|
||||
.entry-mark[role="button"] { cursor: grab; touch-action: none; }
|
||||
.entry-mark, .entry-mark img, .type-glyph, .preview-row__title, .preview-row__text, .use-chip__title {
|
||||
-webkit-user-drag: none;
|
||||
}
|
||||
body.is-assigning, body.is-assigning * { user-select: none !important; }
|
||||
body.is-assigning .direction-column { pointer-events: none; }
|
||||
body.is-carrying, body.is-carrying * { user-select: none !important; cursor: grabbing; }
|
||||
body.is-carrying .direction-column { pointer-events: none; }
|
||||
body.is-carrying .entry-mark[data-assign-drop] {
|
||||
z-index: 2;
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
body.is-list-intent .preview-row:not(.is-carry-source) > .entry-mark[data-assign-drop],
|
||||
body.is-list-carry .preview-row:not(.is-carry-source) > .entry-mark[data-assign-drop] {
|
||||
z-index: 2;
|
||||
}
|
||||
body.is-list-intent .preview-row:not(.is-carry-source) > .entry-mark[data-assign-drop] .entry-mark__drop,
|
||||
body.is-list-carry .preview-row:not(.is-carry-source) > .entry-mark[data-assign-drop] .entry-mark__drop {
|
||||
display: block;
|
||||
}
|
||||
.preview-row.is-assign-target { background: var(--accent-light); }
|
||||
.entry-mark.is-assign-hot { background: var(--accent-light); }
|
||||
.entry-mark__drop {
|
||||
display: none;
|
||||
position: absolute;
|
||||
inset: -6px;
|
||||
border: 2px dashed var(--accent);
|
||||
border-radius: 12px;
|
||||
pointer-events: none;
|
||||
}
|
||||
.entry-mark.is-assign-hot .entry-mark__drop {
|
||||
border-style: solid;
|
||||
background: var(--accent-light);
|
||||
}
|
||||
.preview-row__title, .preview-row__text { touch-action: none; }
|
||||
.content-section.is-release-target {
|
||||
background: var(--accent-light);
|
||||
box-shadow: inset 0 0 0 2px var(--accent);
|
||||
}
|
||||
.release-lane {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 4;
|
||||
margin: 0 0 8px;
|
||||
padding: 8px 10px;
|
||||
min-height: 36px;
|
||||
border: 1px dashed var(--accent);
|
||||
border-radius: 6px;
|
||||
background: var(--accent-light);
|
||||
color: var(--brand);
|
||||
font-size: 13px;
|
||||
font-weight: 650;
|
||||
line-height: 20px;
|
||||
text-align: left;
|
||||
}
|
||||
.release-lane.is-hot { border-style: solid; box-shadow: inset 0 0 0 2px var(--accent); }
|
||||
.contents.is-release-target { box-shadow: inset 0 0 0 2px var(--accent); }
|
||||
.release-mark {
|
||||
position: sticky;
|
||||
top: 36px;
|
||||
z-index: 3;
|
||||
margin: 0 0 4px;
|
||||
padding: 2px 8px;
|
||||
border-radius: 4px;
|
||||
background: var(--accent-light);
|
||||
color: var(--brand);
|
||||
font-size: 12px;
|
||||
font-weight: 650;
|
||||
line-height: 22px;
|
||||
text-align: left;
|
||||
}
|
||||
.use-editions summary { cursor: pointer; color: var(--text2); font-size: 13px; text-align: left; }
|
||||
.pick-tree-dialog { justify-items: start; text-align: left; gap: 8px; }
|
||||
.pick-tree__lead { margin: 0; text-align: left; font-size: 13px; font-weight: 400; color: var(--text2); }
|
||||
.pick-tree__find { width: 100%; font-size: 13px; font-weight: 500; gap: 4px; text-align: left; }
|
||||
.pick-tree__find input { min-height: 32px; padding: 4px 8px; font-size: 13px; }
|
||||
.pick-tree, .pick-tree ul { list-style: none; margin: 0; padding: 0; text-align: left; }
|
||||
.pick-tree { max-height: min(60vh, 520px); overflow: auto; width: 100%; }
|
||||
.pick-tree ul { margin-left: 11px; padding-left: 8px; border-left: 1px solid var(--border); }
|
||||
.pick-tree__row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: flex-start;
|
||||
gap: 4px;
|
||||
width: 100%;
|
||||
min-height: 28px;
|
||||
margin: 0;
|
||||
padding: 1px 4px;
|
||||
text-align: left;
|
||||
font-size: 13px;
|
||||
font-weight: 400;
|
||||
line-height: 1.35;
|
||||
}
|
||||
.pick-tree__row > label {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
justify-content: flex-start;
|
||||
gap: 6px;
|
||||
min-width: 0;
|
||||
flex: 1;
|
||||
font-size: 13px;
|
||||
font-weight: 400;
|
||||
color: inherit;
|
||||
}
|
||||
.pick-tree__row input[type="checkbox"] {
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
min-width: 14px;
|
||||
min-height: 14px;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
flex: 0 0 14px;
|
||||
accent-color: var(--accent);
|
||||
background: transparent;
|
||||
border-radius: 2px;
|
||||
}
|
||||
button.pick-tree__twist {
|
||||
width: 22px;
|
||||
min-width: 22px;
|
||||
height: 22px;
|
||||
min-height: 22px;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
border-radius: 4px;
|
||||
background: transparent;
|
||||
color: var(--text2);
|
||||
font-size: 12px;
|
||||
font-weight: 500;
|
||||
line-height: 1;
|
||||
}
|
||||
.pick-tree__title { font-weight: 600; text-align: left; min-width: 0; overflow-wrap: anywhere; }
|
||||
.pick-tree__kind { color: var(--text3); font-size: 12px; font-weight: 500; text-align: left; white-space: nowrap; }
|
||||
.pick-tree__empty { padding: 4px; color: var(--text3); font-size: 13px; text-align: left; }
|
||||
.pick-tree__bar { display: flex; flex-wrap: wrap; justify-content: flex-start; gap: 8px; align-items: center; position: sticky; bottom: 0; background: var(--surface); padding-top: 8px; width: 100%; }
|
||||
.count { white-space: normal; }
|
||||
.chapter-children { display: grid; gap: 8px; margin-top: 8px; }
|
||||
.pick-bar {
|
||||
display: flex;
|
||||
@@ -1330,7 +1655,7 @@ button.hierarchy__row { width: 100%; min-height: 34px; padding: 6px 8px; border:
|
||||
@media (max-width: 759px) {
|
||||
.rail { display: none; }
|
||||
.app-shell { flex-direction: column; }
|
||||
.workspace-main { padding: 8px 12px 88px; }
|
||||
.workspace-main { --pin-x: 12px; --pin-y: 8px; padding: 8px 12px 88px; }
|
||||
.structure { padding-bottom: 96px; }
|
||||
.mobile-add { display: none; }
|
||||
.page-actions { flex-wrap: wrap; }
|
||||
|
||||
Reference in new issue
Block a user