import { useContext, useEffect, useRef, useState } from "react"; import { Link, useNavigate, useParams, useSearchParams } from "react-router-dom"; import { api, isDirty, markDirty } from "../api.js"; import { SessionContext } from "../session.js"; import { Modal } from "./Modal.jsx"; 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, 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"; import { ExportPackage } from "./ExportPackage.jsx"; function pageContext(params) { const kind = params.get("context_kind"); const id = params.get("context_id"); if (!kind || !id || kind === "direct") return null; return { kind, id }; } export function MatterList() { const { session } = useContext(SessionContext); const navigate = useNavigate(); const [params] = useSearchParams(); const [items, setItems] = useState(null); const [error, setError] = useState(""); const [creating, setCreating] = useState(params.get("neu") === "1"); const [title, setTitle] = useState(""); const [pending, setPending] = useState(false); async function load() { const data = await api("/api/v1/matters"); setItems(data.items); } useEffect(() => { load().catch((err) => setError(err.message)); }, [session.scope.id]); return (

Vorgänge

Ein Vorgang kann eigenständig beginnen und später einer Akte zugeordnet werden.

{items === null ?

Vorgänge werden geladen …

: items.length ? ( matterOpenHref(item)} /> ) : (

Noch kein Vorgang.

)} setCreating(false)}>
{ event.preventDefault(); if (pending) return; setError(""); setPending(true); try { const matter = await api("/api/v1/matters", { method: "POST", body: { title, home_scope_id: session.scope.id } }); markDirty(false); setCreating(false); navigate(`/matters/${matter.id}`); } catch (err) { setError(err.message); } finally { setPending(false); } }}>
); } function contextQuery(inherited) { return inherited ? `?context_kind=${inherited.kind}&context_id=${inherited.id}` : ""; } function mapMatterNodes(nodes, activeId, query) { return (nodes || []).map((node) => ({ id: node.id, title: node.title, kind: node.kind_label || "Vorgang", href: `/matters/${node.id}${query}`, current: node.id === activeId, children: mapMatterNodes(node.children, activeId, query), })); } function caseNodes(caseRecord, parentRecord, activeId, contextId) { const query = `?context_kind=case&context_id=${contextId}`; const self = { id: caseRecord.id, title: caseRecord.title, kind: caseRecord.kind_label || "Akte", href: `/cases/${caseRecord.id}`, current: false, children: [ ...(caseRecord.subcases || []).map((item) => ({ id: item.id, title: item.title, kind: "Unterakte", href: `/cases/${item.id}`, current: false, children: [], })), ...mapMatterNodes(caseRecord.matters, activeId, query), ], }; if (!parentRecord) return [self]; const siblings = (parentRecord.subcases || []).map((item) => (item.id === caseRecord.id ? self : { id: item.id, title: item.title, kind: "Unterakte", href: `/cases/${item.id}`, current: false, children: [], })); return [{ id: parentRecord.id, title: parentRecord.title, kind: "Akte", href: `/cases/${parentRecord.id}`, current: false, children: [ ...(siblings.length ? siblings : [self]), ...mapMatterNodes(parentRecord.matters, activeId, `?context_kind=case&context_id=${parentRecord.id}`), ], }]; } function placementNodes(record) { const matter = { id: record.id, title: record.title, kind: record.kind_label || "Vorgang", href: null, current: true, children: (record.submatters || []).map((item) => ({ id: item.id, title: item.title, kind: "Teilvorgang", href: `/matters/${item.id}`, current: false, children: [], })), }; const rooted = record.parent_matter_id && record.parent_title ? [{ id: record.parent_matter_id, title: record.parent_title, kind: "Vorgang", href: `/matters/${record.parent_matter_id}`, current: false, children: [matter], }] : [matter]; const cases = record.placements || []; if (cases.length < 2) return rooted; return [ ...rooted, ...cases.map((item) => ({ id: item.case_id, title: item.label.replaceAll("Unterakte ", "").replaceAll("Akte ", "").replaceAll(" → ", " / "), kind: "Akte", href: `/matters/${record.id}?context_kind=case&context_id=${item.case_id}`, current: false, children: [], })), ]; } function objectTrail(record, query) { const items = [{ label: "Vorgänge", href: "/matters" }]; if (record.parent_matter_id && record.parent_title) { items.push({ label: record.parent_title, href: `/matters/${record.parent_matter_id}${query}` }); } items.push({ label: record.title, href: null }); return items; } export function MatterDetail() { const { id } = useParams(); const navigate = useNavigate(); const [params, setParams] = useSearchParams(); const inherited = pageContext(params); const chapterId = params.get("kapitel") || ""; const [record, setRecord] = useState(null); 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"); const { width, structureOpen, setStructureOpen } = useWorkspaceLayout(); const listRef = useRef(null); const [caseTree, setCaseTree] = useState(null); const [parentTree, setParentTree] = useState(null); const pendingChapter = useRef(""); const entryId = params.get("eintrag") || ""; async function load() { const query = inherited ? `?context_kind=${inherited.kind}&context_id=${inherited.id}` : ""; const detail = await api(`/api/v1/matters/${id}${query}`); pendingChapter.current = ""; setRecord(detail); return detail; } async function renameMatter() { const title = window.prompt("Vorgangsname", record.title); if (!title || title.trim() === record.title) return; setError(""); try { await api(`/api/v1/matters/${id}`, { method: "PATCH", body: { expected_version: record.version, title: title.trim(), context: rightsContext }, }); load(); } catch (err) { setError(err.message); } } async function archiveMatter() { const next = record.status === "closed" ? "open" : "closed"; setError(""); try { await api(`/api/v1/matters/${id}`, { method: "PATCH", body: { expected_version: record.version, status: next, context: rightsContext }, }); load(); } catch (err) { setError(err.message); } } async function deleteMatter() { if (!window.confirm("Diesen Vorgang löschen? Teilvorgänge müssen vorher gelöst sein. Inhalte bleiben erhalten.")) return; setError(""); try { await api(`/api/v1/matters/${id}/delete`, { method: "POST", body: { expected_version: record.version, context: rightsContext }, }); navigate("/matters"); } catch (err) { setError(err.message); } } useEffect(() => { let alive = true; setRecord(null); setError(""); setView("contents"); setModal(""); setStructureOpen(false); const query = inherited ? `?context_kind=${inherited.kind}&context_id=${inherited.id}` : ""; api(`/api/v1/matters/${id}${query}`).then((detail) => { if (!alive) return; pendingChapter.current = ""; setRecord(detail); }).catch((err) => { if (alive) setError(err.message); }); return () => { alive = false; }; }, [id, inherited?.kind, inherited?.id]); useEffect(() => { if (!record || record.id !== id) return; const known = (record.chapters || []).some((chapter) => chapter.id === chapterId); if (chapterId && !known && pendingChapter.current === chapterId) return; if (chapterId && !known) writeChapter(params, setParams, ""); if (params.get("bereich")) { const next = new URLSearchParams(params); next.delete("bereich"); setParams(next, { replace: true }); } }, [record, id, chapterId, params, setParams]); useEffect(() => { if (!record || record.id !== id || inherited?.kind === "case") return; const placements = record.placements || []; if (placements.length !== 1) return; const next = new URLSearchParams(params); next.set("context_kind", "case"); next.set("context_id", placements[0].case_id); setParams(next, { replace: true }); }, [record, id, inherited?.kind]); useEffect(() => { if (inherited?.kind !== "case") { setCaseTree(null); setParentTree(null); return undefined; } let alive = true; api(`/api/v1/cases/${inherited.id}`).then((detail) => { if (!alive) return; setCaseTree(detail); if (!detail.parent_case_id) { setParentTree(null); return; } api(`/api/v1/cases/${detail.parent_case_id}`).then((parent) => { if (alive) setParentTree(parent); }).catch(() => { if (alive) setParentTree(null); }); }).catch(() => { if (alive) setCaseTree(null); }); return () => { alive = false; }; }, [inherited?.kind, inherited?.id]); useEffect(() => { if (entryId) return; restoreScroll(listRef.current, `tsumugu-scroll:${id}:${chapterId}`); }, [entryId, id, chapterId, record]); function chooseChapter(next) { const updated = new URLSearchParams(params); if (next) updated.set("kapitel", next); else updated.delete("kapitel"); updated.delete("eintrag"); updated.delete("bereich"); setParams(updated); setView("contents"); setStructureOpen(false); } function openEntry(binding) { rememberScroll(listRef.current, `tsumugu-scroll:${id}:${chapterId}`); const updated = new URLSearchParams(params); updated.set("eintrag", binding.id); setParams(updated); setView("contents"); } function closeEntry() { const updated = new URLSearchParams(params); updated.delete("eintrag"); setParams(updated, { replace: true }); } function switchContext(caseId) { if (caseId === (inherited?.id || "")) return; if (isDirty() && !window.confirm("Ungespeicherte Eingaben verwerfen und den Aktenkontext wechseln?")) return; const updated = new URLSearchParams(); if (caseId) { updated.set("context_kind", "case"); updated.set("context_id", caseId); } setParams(updated); setStructureOpen(false); } function openChapter(parentId = "") { setChapterParentId(parentId || ""); 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); const target = index + delta; if (!record || index < 0 || target < 0 || target >= ids.length) return; const [moved] = ids.splice(index, 1); ids.splice(target, 0, moved); try { await saveChapterOrder({ containerKind: "matter", containerId: id, record, context: inherited, ids }); await load(); } catch (err) { setError(err.message); } } if (error && !record) return
; if (!record) return

Vorgang wird geladen …

; const query = contextQuery(inherited); const targetLabel = `${record.kind_label || "Vorgang"} ${record.title}`; const activeChapter = (record.chapters || []).find((chapter) => chapter.id === chapterId) || null; const canEdit = Boolean(record.rights?.edit); const chapters = (record.chapters || []).map((chapter) => ({ ...chapter, count: (record.bindings || []).filter((item) => item.chapter_id === chapter.id).length, })); const contexts = (record.placements || []).map((item) => ({ id: item.case_id, label: item.label.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 links = [ ...(record.cross_links || []).map((item) => ({ id: `cross-${item.id}`, title: item.title, kind: "Querverweis", href: `/matters/${item.matter_id}${query}`, })), ...(record.case_links || []).filter((item) => inherited?.kind === "case" && item.case_id !== inherited.id).map((item) => ({ id: `case-${item.id}`, title: item.title, kind: "Weitere Akte", href: `/cases/${item.case_id}`, })), ]; const entry = (record.bindings || []).find((item) => item.id === entryId) || null; const scrollKey = `tsumugu-scroll:${id}:${chapterId}`; return ( <> 1 && !inherited ? [{ id: "", label: "Keine Akte gewählt" }, ...contexts] : contexts} contextValue={contextValue} onContext={contexts.length > 1 ? switchContext : null} nodes={nodes} chapters={chapters} chapterId={chapterId} allLabel="" allCount={(record.bindings || []).length} chapterHeading={`Kapitel in ${record.title}`} onChapter={chooseChapter} onAddChapter={canEdit ? () => openChapter(chapterId) : null} onAddRootChapter={canEdit ? () => openChapter("") : null} canAddChapter={canEdit} onMoveChapter={moveChapter} canReorder={canEdit && chapters.length > 1} links={links} onNavigate={() => setStructureOpen(false)} onClose={width < 1500 ? () => setStructureOpen(false) : null} /> )} reader={entryId ? ( { const found = (record.bindings || []).find((item) => item.element?.id === elementId); if (found) openEntry(found); }} /> ) : null} >

{record.title}

{record.status === "open" ? "Offen" : "Geschlossen"}
{width < 1500 ? : null} {canEdit ? ( ) : null} {canEdit ? : null} {canEdit ? : null} {canEdit ? : null} {canEdit ? : null} {canEdit ? : null} {canEdit ? : null} {record.rights.share || record.is_owner ? : null}
{!canEdit ?

In {targetLabel} fehlt das Bearbeitungsrecht.

: null}
{view === "contents" ? ( { rememberScroll(listRef.current, scrollKey); openEntry(binding); }} onChange={load} itemHref={(binding) => { const search = new URLSearchParams(params); search.set("eintrag", binding.id); const text = search.toString(); return text ? `/matters/${id}?${text}` : `/matters/${id}`; }} /> ) : null} {view === "work" ? (
{record.rights.edit ? : null}
) : null} {view === "course" || view === "audit" ? ( ) : null} {view === "links" ? (

Zuordnungen

{record.case_links?.length ? record.case_links.map((item) => (

Akte {item.title}

)) :

Noch keiner Akte zugeordnet.

} {record.cross_links?.length ? record.cross_links.map((item) => (

Querverweis {item.title}

)) :

Kein Querverweis.

} {record.rights.edit ? : null}
) : null} {canEdit && view === "contents" ? ( ) : null}
setModal("")}> setModal("")} /> setModal("")}> { setModal(""); load(); }} /> setModal("")}>
{addChapterId ? : null}
setModal("")}> { setModal(""); load(); }} /> setModal("")}> { setModal(""); load(); }} /> setModal("")}> { setModal(""); load(); }} /> setModal("")}> { setModal(""); load(); }} /> setModal("")}> { setModal(""); load(); }} /> setModal("")}> { setModal(""); load(); }} /> setModal("")}> { setModal(""); if (created?.id) { pendingChapter.current = created.id; writeChapter(params, setParams, created.id); } load(); }} /> setModal("")}> setModal("")}> { setModal(""); load(); }} /> ); } function MoveMatter({ matterId, version, context, soleCaseId = "", onDone }) { const [cases, setCases] = useState([]); const [caseId, setCaseId] = useState(""); const [matters, setMatters] = useState([]); const [parentId, setParentId] = useState(""); const [clearParent, setClearParent] = useState(false); const [error, setError] = useState(""); const [pending, setPending] = useState(false); useEffect(() => { api("/api/v1/cases").then((data) => setCases(data.items || data || [])).catch((err) => setError(err.message)); }, []); useEffect(() => { if (!caseId) { setMatters([]); return undefined; } api(`/api/v1/cases/${caseId}`).then((detail) => { const direct = detail.matters || []; setMatters(direct.filter((item) => item.id !== matterId)); }).catch((err) => setError(err.message)); return undefined; }, [caseId, matterId]); async function submit(event) { event.preventDefault(); if (!caseId && !parentId && !clearParent) { setError("Wähle eine Akte oder einen übergeordneten Vorgang."); return; } setPending(true); setError(""); try { const fromCase = context?.kind === "case" ? context.id : soleCaseId; await api(`/api/v1/matters/${matterId}/move`, { method: "POST", body: { expected_version: version, context: fromCase ? { kind: "case", id: fromCase } : context, ...(caseId ? { case_id: caseId } : {}), ...(parentId ? { parent_matter_id: parentId } : {}), ...(clearParent ? { clear_parent: true } : {}), }, }); onDone(); } catch (err) { setError(err.message); } finally { setPending(false); } } return (
); } function WorkForms({ matterId, context, deadlines, onChange }) { const [taskTitle, setTaskTitle] = useState(""); const [taskDue, setTaskDue] = useState(""); const [deadlineId, setDeadlineId] = useState(""); const [deadlineTitle, setDeadlineTitle] = useState(""); const [deadlineDue, setDeadlineDue] = useState(""); const [error, setError] = useState(""); async function addDeadline(event) { event.preventDefault(); setError(""); try { await api("/api/v1/deadlines", { method: "POST", body: { title: deadlineTitle, due_on: deadlineDue, matter_id: matterId, ...(context ? { context } : {}), }, }); setDeadlineTitle(""); setDeadlineDue(""); onChange(); } catch (err) { setError(err.message); } } async function addTask(event) { event.preventDefault(); setError(""); try { const task = await api("/api/v1/tasks", { method: "POST", body: { title: taskTitle, matter_id: matterId, ...(taskDue ? { due_on: taskDue } : {}), ...(context ? { context } : {}), }, }); if (deadlineId) { await api(`/api/v1/tasks/${task.id}/deadline-links`, { method: "POST", body: { deadline_id: deadlineId, ...(context ? { context } : {}) }, }); } setTaskTitle(""); setTaskDue(""); setDeadlineId(""); onChange(); } catch (err) { setError(err.message); } } return (

Frist

setDeadlineTitle(event.target.value)} placeholder="Maßgeblicher Termin" required />

Aufgabe

setTaskTitle(event.target.value)} placeholder="Was ist vor der Frist zu tun?" required />
); } function CrossLinkForm({ matterId, context, onChange }) { const [targets, setTargets] = useState([]); const [targetId, setTargetId] = useState(""); const [error, setError] = useState(""); useEffect(() => { api("/api/v1/placement-targets") .then((data) => setTargets(data.items.filter((item) => item.kind === "matter" && item.id !== matterId))) .catch((err) => setError(err.message)); }, [matterId]); async function submit(event) { event.preventDefault(); const target = targets.find((item) => item.id === targetId); if (!target) return; const via = (target.contexts || []).find((item) => item.kind === "direct") || target.contexts?.[0]; const targetContext = !via || via.kind === "direct" ? { kind: "matter", id: target.id } : { kind: via.kind, id: via.id }; setError(""); try { await api(`/api/v1/matters/${matterId}/cross-links`, { method: "POST", body: { target_matter_id: target.id, target_context: targetContext, ...(context ? { source_context: context } : {}), }, }); onChange(); } catch (err) { setError(err.message); } } return (
); } function SubmatterForm({ parentId, context, onChange }) { const [title, setTitle] = useState(""); async function submit(event) { event.preventDefault(); await api("/api/v1/matters", { method: "POST", body: { title, parent_matter_id: parentId, ...(context ? { context } : {}) }, }); setTitle(""); onChange(); } return (
setTitle(event.target.value)} placeholder="Teilvorgang" required />
); }