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 "./Sources.jsx";
import { SourcePicker, moduleFor, sourceModules } from "../sources/registry.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, SurfaceView, TargetLine, Trail, WorkLists, WorkSwitch, matterOpenHref, saveChapterOrder, writeChapter } from "./content.jsx";
import { ReadingPane } from "./ReadingPane.jsx";
import { Workspace, rememberScroll, restoreScroll, useWorkspaceLayout } from "./workspace.jsx";
import { useLibrary, useLibraryFocus } from "../library/LibraryLayout.jsx";
import { outlineSignature } from "../library/library-core.js";
import { NavIcon } from "./icons.jsx";
import { ExportPackage } from "./ExportPackage.jsx";
import { RoomShare } from "../admin/RoomShare.jsx";
import { writableRooms } from "../admin/admin-core.js";
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 };
}
function contextQuery(inherited) {
return inherited ? `?context_kind=${inherited.kind}&context_id=${inherited.id}` : "";
}
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 library = useLibrary();
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 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 (!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}`);
}, [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);
}
}
useLibraryFocus(
record && record.id === id
? {
kind: "matter",
id,
contextId: inherited?.kind === "case" ? inherited.id : "",
chapterId,
canEdit: Boolean(record.rights?.edit),
canReorder: Boolean(record.rights?.edit) && (record.chapters || []).length > 1,
stamp: outlineSignature(record),
}
: null,
{ addChapter: (parentId) => openChapter(parentId), moveChapter },
);
useEffect(() => {
setView("contents");
}, [chapterId]);
if (error && !record) return Vorgang wird geladen …
{links.map((item, index) => (
{index ? : null}
{item.kind}: {item.title}
))}
In {targetLabel} fehlt das Bearbeitungsrecht. Akte {item.title} Noch keiner Akte zugeordnet. Querverweis {item.title} Kein Querverweis.
{view === "contents" ? (
{record.title}
{record.status === "open" ? "Offen" : "Geschlossen"}
{canEdit ? (
) : null}
{record.rights.edit ? : null}
) : null}
{view === "course" || view === "audit" ? (
) : null}
{canEdit && view === "contents" ? (
) : null}
Zuordnungen
{record.case_links?.length ? record.case_links.map((item) => (
{addChapterId ? : null}
{sourceModules().map((module) => (
))}
„{title}“ bleibt mit allen Inhalten erhalten und wird nur aus der gewählten Akte gelöst. In anderen Akten und unter „Vorgänge“ bleibt er sichtbar.