diff --git a/backend/app/api/correspondence.py b/backend/app/api/correspondence.py index 6d79b22..1ee8bfa 100644 --- a/backend/app/api/correspondence.py +++ b/backend/app/api/correspondence.py @@ -14,6 +14,7 @@ from app.api.schemas import ( AttachmentDetachIn, AttachmentOrderIn, DispatchCorrectIn, + DispatchEvidenceDetachIn, DispatchEvidenceIn, DispatchIn, FoldIn, @@ -22,6 +23,7 @@ from app.correspondence import ( GapNote, add_dispatch_evidence, assign_attachments, + detach_dispatch_evidence, correct_dispatch, detach_attachment, dispatch_view, @@ -173,6 +175,25 @@ def post_evidence( ) +@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, diff --git a/backend/app/api/schemas.py b/backend/app/api/schemas.py index 2ede6b0..7fa123d 100644 --- a/backend/app/api/schemas.py +++ b/backend/app/api/schemas.py @@ -424,6 +424,12 @@ class DispatchEvidenceIn(APIModel): 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 diff --git a/backend/app/correspondence.py b/backend/app/correspondence.py index 654abb2..25274e5 100644 --- a/backend/app/correspondence.py +++ b/backend/app/correspondence.py @@ -291,6 +291,33 @@ def add_dispatch_evidence( return row +def detach_dispatch_evidence( + conn, + actor: UUID, + dispatch_id: UUID, + element_id: UUID, + expected: int, + context: Ctx, + placement: Ctx | None, +) -> None: + container_row, page, scope = open_container(conn, actor, context, placement, "edit") + dispatch = _dispatch_in(conn, dispatch_id, scope) + _bump_dispatch(conn, dispatch_id, expected) + deleted = conn.execute( + """ + DELETE FROM dispatch_evidence + WHERE dispatch_id = %s AND element_id = %s + RETURNING id + """, + (dispatch_id, element_id), + ).fetchone() + if deleted is None: + raise not_found() + _clear_evidence_fold(conn, scope, element_id) + _log(conn, dispatch_id, actor, "Nachweis aus diesem Versand gelöst") + audit(conn, actor, container_row["home_scope_id"], "dispatch_evidence_detached", "element", dispatch["host_element_id"], page) + + def correct_dispatch( conn, actor: UUID, @@ -1254,6 +1281,18 @@ def _set_binding_fold(conn, scope: Ctx, element_id: UUID, fold: str) -> None: ) +def _clear_evidence_fold(conn, scope: Ctx, element_id: UUID) -> None: + if _is_evidence(conn, scope, element_id): + return + conn.execute( + """ + UPDATE bindings SET list_fold = NULL + WHERE element_id = %s AND context_kind = %s AND context_id = %s AND list_fold = 'evidence' + """, + (element_id, scope.kind, scope.id), + ) + + def _clear_attachment_fold(conn, scope: Ctx, element_id: UUID) -> None: if _is_attachment(conn, scope, element_id): return diff --git a/backend/tests/test_correspondence.py b/backend/tests/test_correspondence.py index a7ea527..6c9f056 100644 --- a/backend/tests/test_correspondence.py +++ b/backend/tests/test_correspondence.py @@ -470,6 +470,17 @@ def test_dispatch_keeps_the_secured_stand_and_distinct_mail_parts(client, db, mo 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", diff --git a/docs/architecture/API_REFERENZ.md b/docs/architecture/API_REFERENZ.md index dbc7c10..73db9d2 100644 --- a/docs/architecture/API_REFERENZ.md +++ b/docs/architecture/API_REFERENZ.md @@ -188,6 +188,7 @@ Alle schreibenden Aufrufe prüfen den Handlungskontext, `expected_version` und d | 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 | diff --git a/docs/architecture/TSUMUGU_TECHNICAL_SPEC.md b/docs/architecture/TSUMUGU_TECHNICAL_SPEC.md index ff24d4b..9a4f528 100644 --- a/docs/architecture/TSUMUGU_TECHNICAL_SPEC.md +++ b/docs/architecture/TSUMUGU_TECHNICAL_SPEC.md @@ -223,7 +223,7 @@ Auth-Tabellen `auth_accounts` und `auth_sessions` folgen dem Auth-Blueprint. Ein 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/` 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. 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. +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/` 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 diff --git a/frontend/src/pages/content.jsx b/frontend/src/pages/content.jsx index 7c52f9b..54740b8 100644 --- a/frontend/src/pages/content.jsx +++ b/frontend/src/pages/content.jsx @@ -27,6 +27,7 @@ import { scopeBody, unitMarks, UnitDetail, + writeAssign, } from "./correspondence.jsx"; export function formatDate(value) { @@ -839,9 +840,9 @@ function EntryActions({ ) : null} {canSort && custom ? : null} {canSort && custom ? : null} - {canEdit && onAttach ? : null} + {canEdit && onAttach ? : null} {canEdit && onDispatch ? : null} - {canEdit && onEvidence ? : null} + {canEdit && onEvidence ? : null} {canEdit ? : null} {canEdit && canDestroy ? : null} @@ -857,11 +858,12 @@ function TypeGlyph({ name, tone, size = 28 }) { width={size} height={size} alt="" + draggable={false} /> ); } -function EntryMark({ element, context }) { +function EntryMark({ element, context, assignable = false, onAssignStart, onAssignEnd }) { const symbol = elementSymbol(element); const photo = symbol === "image" && Boolean(element.preview?.available); const [url, setUrl] = useState(""); @@ -883,8 +885,16 @@ function EntryMark({ element, context }) { }; }, [photo, element.id, element.preview?.source, context?.kind, context?.id]); return ( - - {url ? : ( + + {url ? : ( <> @@ -939,14 +949,16 @@ export function ContentBoard({ const [error, setError] = useState(""); const [pending, setPending] = useState(false); const [dialog, setDialog] = useState(null); - const [openUnits, setOpenUnits] = useState(() => new Set()); const [draggingId, setDraggingId] = useState(""); + const [carry, setCarry] = useState(null); const [indicator, setIndicator] = useState(null); const [folded, setFolded] = useState(() => new Set()); const [picking, setPicking] = useState(false); const [picked, setPicked] = useState(() => new Set()); const [pickTarget, setPickTarget] = useState(""); const dragRef = useRef(null); + const carryRef = useRef(null); + const releaseRef = useRef(null); const rootRef = useRef(null); const savingDirection = useRef(false); const custom = record?.content_order === "position"; @@ -1081,6 +1093,10 @@ export function ContentBoard({ const node = rootRef.current; if (!node) return undefined; function place(event) { + if (carryRef.current) { + event.preventDefault(); + return; + } const drag = dragRef.current; if (!drag?.html5) return; event.preventDefault(); @@ -1096,6 +1112,17 @@ export function ContentBoard({ setIndicator({ sectionId, index: drag.index }); } function drop(event) { + const carried = carryRef.current; + if (carried) { + if (event.target?.closest?.(".drop-well")) return; + if (carried.source === "attachment" || carried.source === "evidence") { + event.preventDefault(); + releaseRef.current?.(carried); + } + carryRef.current = null; + setCarry(null); + return; + } if (!dragRef.current?.html5) return; place(event); finishDragRef.current(dragRef.current); @@ -1456,6 +1483,125 @@ export function ContentBoard({ }, 0); } + function beginCarry(payload) { + carryRef.current = payload; + setCarry(payload); + } + + function endCarry() { + carryRef.current = null; + setCarry(null); + } + + function bindingByElement(elementId) { + return source.find((item) => item.element?.id === elementId) || null; + } + + function dispatchOf(dispatchId) { + for (const item of source) { + const found = (item.correspondence?.dispatches || []).find((entry) => entry.id === dispatchId); + if (found) return { host: item, dispatch: found }; + } + return null; + } + + const correspondenceScope = () => scopeBody(actionContext(), containerKind, containerId); + + async function releaseToList(payload) { + setPending(true); + setError(""); + try { + const scope = correspondenceScope(); + if (payload.source === "attachment") { + const host = bindingByElement(payload.hostElementId); + if (!host) return; + await api(`/api/v1/elements/${host.element.id}/attachments/${payload.elementId}/detach`, { + method: "POST", + body: { expected_version: host.element.version, ...scope }, + }); + } else if (payload.source === "evidence") { + const found = dispatchOf(payload.dispatchId); + if (!found) return; + await api(`/api/v1/dispatches/${found.dispatch.id}/evidence/${payload.elementId}/detach`, { + method: "POST", + body: { expected_version: found.dispatch.version, ...scope }, + }); + } + const item = bindingByElement(payload.elementId); + if (item?.correspondence?.fold) { + await restoreFold(item.id, item.element.version, scope); + } + onChange(); + } catch (err) { + setError(err.message); + } finally { + setPending(false); + } + } + + releaseRef.current = releaseToList; + + async function dropAttachment(hostBinding, payload) { + if (!payload || payload.elementId === hostBinding.element.id) return; + const already = (hostBinding.correspondence?.attachments || []).some((item) => item.element_id === payload.elementId); + if (payload.source === "attachment" && payload.hostElementId === hostBinding.element.id) return; + if (already) { + setError("Diese Anlage ist dem Schreiben bereits zugeordnet."); + return; + } + setPending(true); + setError(""); + try { + const scope = correspondenceScope(); + if (payload.source === "attachment") { + const from = bindingByElement(payload.hostElementId); + if (!from) return; + await api(`/api/v1/elements/${from.element.id}/attachments/${payload.elementId}/detach`, { + method: "POST", + body: { expected_version: from.element.version, ...scope }, + }); + } + if (payload.source === "evidence") { + const found = dispatchOf(payload.dispatchId); + if (!found) return; + await api(`/api/v1/dispatches/${found.dispatch.id}/evidence/${payload.elementId}/detach`, { + method: "POST", + body: { expected_version: found.dispatch.version, ...scope }, + }); + } + await api(`/api/v1/elements/${hostBinding.element.id}/attachments`, { + method: "POST", + body: { + expected_version: hostBinding.element.version, + attachment_element_ids: [payload.elementId], + fold: "attachment", + ...scope, + }, + }); + onChange(); + } catch (err) { + setError(err.message); + } finally { + setPending(false); + } + } + + function dropReceipt(hostBinding, payload, dispatch) { + if (!payload || payload.elementId === hostBinding.element.id) return; + if (payload.source === "evidence" && dispatch && payload.dispatchId === dispatch.id) return; + const item = bindingByElement(payload.elementId); + const found = payload.source === "evidence" ? dispatchOf(payload.dispatchId) : null; + setDialog({ + type: "evidence", + binding: item || { element: { id: payload.elementId, title: payload.title || "Unterlage", version: 1 } }, + hosts: [hostBinding], + dispatchId: dispatch ? dispatch.id : "", + replace: found && (!dispatch || found.dispatch.id !== dispatch.id) + ? { dispatchId: found.dispatch.id, version: found.dispatch.version } + : null, + }); + } + function beginDrag(event, drag) { if (pending || (event.button != null && event.button !== 0)) return; event.preventDefault(); @@ -1509,7 +1655,7 @@ export function ContentBoard({ - + ) : null} @@ -1520,34 +1666,54 @@ export function ContentBoard({ ) : (

Noch keine Unterlage und keine Notiz.

)} - setDialog(null)}> + setDialog(null)}> {dialog?.type === "bulk" && !dialog.host ? ( -
{ + { event.preventDefault(); - const host = listed.find((item) => item.id === new FormData(event.currentTarget).get("host")); - if (!host) return; - const candidates = listed.filter((item) => picked.has(item.id) && item.id !== host.id); - setDialog({ type: "attach", host, candidates }); + const host = source.find((item) => item.id === new FormData(event.currentTarget).get("host")); + const ids = [...picked].map((id) => source.find((item) => item.id === id)).filter((item) => item && item.id !== host?.id).map((item) => item.element.id); + if (!host || !ids.length) return; + setPending(true); + setError(""); + try { + await api(`/api/v1/elements/${host.element.id}/attachments`, { + method: "POST", + body: { + expected_version: host.element.version, + attachment_element_ids: ids, + fold: "attachment", + ...scopeBody(actionContext(), containerKind, containerId), + }, + }); + setDialog(null); + setPicked(new Set()); + setPicking(false); + onChange(); + } catch (err) { + setError(err.message); + } finally { + setPending(false); + } }}> -

Hauptschriftstück für die ausgewählten Unterlagen wählen. Die Kapitel bleiben bestehen, bis sie separat aufgelöst werden.

+

Die ausgewählten Unterlagen werden Anlagen dieses Schriftstücks und verschwinden aus der normalen Liste. Zurückziehen legt sie wieder dorthin.

- +
) : null} {dialog?.type === "attach" && dialog.host ? ( item.id === dialog.host.id) || dialog.host} + candidates={source.filter((item) => item.element.id !== (source.find((entry) => entry.id === dialog.host.id) || dialog.host).element.id)} scope={scopeBody(actionContext(), containerKind, containerId)} pending={pending} onClose={() => setDialog(null)} - onDone={() => { setDialog(null); setPicked(new Set()); setPicking(false); onChange(); }} + onDone={() => onChange()} /> ) : null}
@@ -1562,11 +1728,34 @@ export function ContentBoard({ /> ) : null}
- setDialog(null)}> + setDialog(null)}> + {dialog?.type === "receipt-source" ? ( +
+

Unterlage aus diesem Vorgang als Beleg von {dialog.host.element.title}.

+
    + {source.filter((item) => item.element.id !== dialog.host.element.id).map((item) => ( +
  • + {item.element.title} + +
  • + ))} +
+ {!source.filter((item) => item.element.id !== dialog.host.element.id).length ?

Keine weitere Unterlage.

: null} +
+ ) : null} +
+ setDialog(null)}> {dialog?.type === "evidence" ? ( item.element.id !== dialog.binding.element.id)} + hosts={dialog.hosts || source.filter((item) => item.element.id !== dialog.binding.element.id)} + presetDispatchId={dialog.dispatchId} + replace={dialog.replace || null} scope={scopeBody(actionContext(), containerKind, containerId)} pending={pending} onClose={() => setDialog(null)} @@ -1749,11 +1938,32 @@ export function ContentBoard({