import { useContext, useEffect, useRef, useState } from "react";
import { Link, useParams, useSearchParams } from "react-router-dom";
import { api, markDirty, textToDocument } 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 { ContentBoard, ObjectMenu, OrderChoice, RecordTree, SurfaceView, TargetLine, Trail, WorkLists, WorkSwitch, selectionOf, withSelection, writeSelection } from "./content.jsx";
export function CaseList() {
const { session } = useContext(SessionContext);
const [items, setItems] = useState([]);
const [title, setTitle] = useState("");
const [roomId, setRoomId] = useState(session.rooms[0]?.id || "");
const [roomFilter, setRoomFilter] = useState("");
const [error, setError] = useState("");
const [creating, setCreating] = useState(false);
async function load() {
const data = await api("/api/v1/cases");
setItems(data.items);
}
useEffect(() => {
load().catch((err) => setError(err.message));
}, [session.scope.id]);
async function create(event) {
event.preventDefault();
setError("");
try {
await api("/api/v1/cases", { method: "POST", body: { title, home_scope_id: roomId } });
setTitle("");
markDirty(false);
setCreating(false);
await load();
} catch (err) {
setError(err.message);
}
}
return (
setRoomFilter("")}>Alle
{session.rooms.map((room) => (
setRoomFilter(room.id)}>
{room.name}
))}
{items.filter((item) => !roomFilter || item.home_scope_id === roomFilter).length ? (
!roomFilter || item.home_scope_id === roomFilter)}
parentKey="parent_case_id"
hrefFor={(item) => `/cases/${item.id}`}
/>
) : (
Noch keine Akte. Lege die erste an.
)}
setCreating(false)}>
);
}
function OutlineLink({ kind, title, to }) {
return (
{kind}
{title}
);
}
function matterChapters(record, matterId) {
return (record.contained || []).find((item) => item.matter_id === matterId)?.chapters || [];
}
function ChapterLinks({ chapters, scopeId, scope, chapterId, onChapter }) {
if (!chapters.length) return null;
return (
{chapters.map((chapter) => (
onChapter(scopeId, chapter.id)}
>
Kapitel
{chapter.title}
))}
);
}
function MatterBranch({ matter, caseId, scope, chapterId, record, onScope, onChapter }) {
const selected = scope === matter.id && !chapterId;
return (
onScope(matter.id)}>
{matter.kind_label || "Vorgang"}
{matter.title}
Öffnen
{matter.children?.length ? (
{matter.children.map((child) => (
))}
) : null}
);
}
function CaseOutline({ record, caseId, scope, chapterId, onScope, onChapter }) {
const hasParent = Boolean(record.parent_case_id && record.parent_title);
return (
Gliederung
onScope("all")}>
Überblick
Alle Inhalte
onScope("direct")}>
Akte
Direkt in dieser Akte
{hasParent ? (
Übergeordnet: Akte {record.parent_title}
) : null}
{record.subcases?.length ? (
<>
Unterakten
{record.subcases.map((item) => (
))}
>
) : null}
{record.matters?.length ? (
<>
Vorgänge
{record.matters.map((matter) => (
))}
>
) : null}
);
}
function matterOrigin(group) {
const kind = group.kind_label === "Teilvorgang" ? "Teilvorgang" : "Vorgang";
const parent = group.parent_title ? ` · Vorgang ${group.parent_title}` : "";
return `Aus ${kind} ${group.title}${parent}`;
}
function chapterOrigin(base, chapters, chapterId) {
const title = (chapters || []).find((chapter) => chapter.id === chapterId)?.title;
return title ? `${base} · Kapitel ${title}` : base;
}
function mergedCaseItems(record, direction, caseId) {
const rows = [
...(record.bindings || []).map((binding) => ({
...binding,
origin: chapterOrigin("Direkt in dieser Akte", record.chapters, binding.chapter_id),
readerHref: `/cases/${caseId}/items/${binding.id}`,
})),
...(record.contained || []).flatMap((group) => (group.bindings || []).map((binding) => ({
...binding,
origin: chapterOrigin(matterOrigin(group), group.chapters, binding.chapter_id),
readerHref: `/matters/${group.matter_id}/items/${binding.id}?context_kind=case&context_id=${caseId}`,
}))),
];
const counts = {};
for (const row of rows) counts[row.element.id] = (counts[row.element.id] || 0) + 1;
const marked = rows.map((row) => ({ ...row, shared: counts[row.element.id] > 1 }));
const dated = marked.filter((row) => row.element.dates?.document_on);
const undated = marked.filter((row) => !row.element.dates?.document_on);
dated.sort((a, b) => a.element.dates.document_on.localeCompare(b.element.dates.document_on) || a.id.localeCompare(b.id));
if (direction === "desc") dated.reverse();
undated.sort((a, b) => a.id.localeCompare(b.id));
return [...dated, ...undated];
}
export function CaseDetail() {
const { id } = useParams();
const [params, setParams] = useSearchParams();
const { scope, chapterId } = selectionOf(params);
const [record, setRecord] = useState(null);
const [error, setError] = useState("");
const [modal, setModal] = useState("");
const [view, setView] = useState("contents");
const [dateDir, setDateDir] = useState("asc");
const [outlineOpen, setOutlineOpen] = useState(false);
const pendingChapter = useRef("");
const context = { kind: "case", id };
async function load() {
const detail = await api(`/api/v1/cases/${id}`);
pendingChapter.current = "";
setRecord(detail);
return detail;
}
useEffect(() => {
let alive = true;
setRecord(null);
setError("");
setView("contents");
setModal("");
setDateDir("asc");
setOutlineOpen(false);
api(`/api/v1/cases/${id}`).then((detail) => {
if (!alive) return;
pendingChapter.current = "";
setRecord(detail);
}).catch((err) => {
if (alive) setError(err.message);
});
return () => { alive = false; };
}, [id]);
useEffect(() => {
if (!record || record.id !== id) return;
const known = new Set(["all", "direct", ...(record.contained || []).map((item) => item.matter_id)]);
const nextScope = known.has(scope) ? scope : "all";
const chapters = nextScope === "direct"
? (record.chapters || [])
: (record.contained || []).find((item) => item.matter_id === nextScope)?.chapters || [];
const nextChapter = chapterId && chapters.some((chapter) => chapter.id === chapterId) ? chapterId : "";
if (chapterId && !nextChapter && pendingChapter.current === chapterId) return;
if (nextScope !== scope || nextChapter !== chapterId) writeSelection(params, setParams, nextScope, nextChapter);
}, [record, id, scope, chapterId, params, setParams]);
function choose(nextScope, nextChapter = "") {
writeSelection(params, setParams, nextScope, nextChapter);
setView("contents");
setOutlineOpen(false);
}
if (error && !record) return ;
if (!record) return Akte wird geladen …
;
const group = scope !== "all" && scope !== "direct"
? (record.contained || []).find((item) => item.matter_id === scope) || null
: null;
const target = scope === "direct"
? {
scope: "direct",
label: `Akte ${record.title}`,
edit: Boolean(record.rights?.edit),
chapters: record.chapters || [],
chapterPath: `/api/v1/cases/${id}/chapters`,
}
: group
? {
scope: group.matter_id,
label: `${group.kind_label || "Vorgang"} ${group.title}`,
edit: Boolean(group.rights?.edit),
chapters: group.chapters || [],
chapterPath: `/api/v1/matters/${group.matter_id}/chapters?context_kind=case&context_id=${id}`,
}
: null;
const activeChapter = target?.chapters.find((chapter) => chapter.id === chapterId) || null;
const merged = mergedCaseItems(record, dateDir, id);
const addPlacement = group ? { kind: "matter", id: group.matter_id } : null;
return (
setOutlineOpen((open) => !open)}>{outlineOpen ? "Bereiche schließen" : "Bereiche"}
choose(next)}
onChapter={(nextScope, nextChapter) => choose(nextScope, nextChapter)}
/>
{view === "contents" ? (
{target ? (
<>Bearbeitet wird {target.label} {activeChapter ? <> · Kapitel {activeChapter.title} > : null}>
) : (
"Lesesicht aller Inhalte. Zum Bearbeiten einen Bereich in der Gliederung wählen."
)}
) : null}
{view === "contents" && scope === "all" ? (
setDateDir(next)} />
binding.readerHref}
/>
) : null}
{view === "contents" && scope === "direct" ? (
withSelection(`/cases/${id}/items/${binding.id}`, params)}
/>
) : null}
{view === "contents" && group ? (
withSelection(`/matters/${group.matter_id}/items/${binding.id}?context_kind=case&context_id=${id}`, params)}
/>
) : null}
{view === "contents" && scope !== "all" && scope !== "direct" && !group ? (
Dieser Bereich hat in der Akte keine eigenen Unterlagen.
) : null}
{view === "work" ? : null}
{view === "course" || view === "audit" ? (
) : null}
{view === "links" ? (
Zuordnungen
Unterakten, Vorgänge und Freigaben dieses Objekts.
{record.rights.edit ?
setModal("matter")}>Vorgang anlegen und zuordnen : null}
{record.rights.edit ?
setModal("assign")}>Vorhandenen Vorgang zuordnen : null}
{record.rights.edit ?
setModal("subcase")}>Unterakte anlegen : null}
) : null}
setModal("")}>
{ setModal(""); load(); }} />
setModal("")}>
{ setModal(""); load(); }} />
setModal("")}>
setModal("note")}>Notiz
setModal("file")}>Datei
setModal("paperless")}>Paperless
setModal("mail")}>E-Mail
setModal("")}>
{ setModal(""); load(); }} />
setModal("")}>
{ setModal(""); load(); }} />
setModal("")}>
{ setModal(""); load(); }} />
setModal("")}>
{ setModal(""); load(); }} />
setModal("")}>
{ setModal(""); load(); }} />
setModal("")}>
{
setModal("");
if (created?.id && target) {
pendingChapter.current = created.id;
writeSelection(params, setParams, target.scope, created.id);
}
load();
}}
/>
setModal("")}>
);
}
export function ChapterBoard({ chapters, bindings, onOpen }) {
const loose = bindings.filter((item) => !item.chapter_id);
return (
{chapters.map((chapter) => (
{chapter.title}
item.chapter_id === chapter.id)} onOpen={onOpen} />
))}
{loose.length || !chapters.length ? (
{chapters.length ?
Ohne Kapitel : null}
) : null}
);
}
function BindingTiles({ items, onOpen, empty }) {
if (!items.length) return {empty || "In diesem Kapitel liegt noch nichts."}
;
return (
{items.map((binding) => (
onOpen(binding)}>
{sourceKind(binding.element)}
{binding.element.title}
))}
);
}
function sourceKind(element) {
if (element.kind === "note") return "Notiz";
if (element.kind === "file") return "Datei";
if (element.external?.source === "paperless") return "Paperless";
if (element.external?.source === "imap") return "E-Mail";
return "Referenz";
}
function NewMatter({ caseId, homeScopeId, onChange }) {
const [title, setTitle] = useState("");
const [error, setError] = useState("");
const [pending, setPending] = useState(false);
async function submit(event) {
event.preventDefault();
if (pending) return;
setError("");
setPending(true);
try {
const matter = await api("/api/v1/matters", { method: "POST", body: { title, ...(homeScopeId ? { home_scope_id: homeScopeId } : {}) } });
await api(`/api/v1/matters/${matter.id}/case-links`, { method: "POST", body: { case_id: caseId } });
setTitle("");
markDirty(false);
onChange();
} catch (err) {
setError(err.message);
} finally {
setPending(false);
}
}
return (
);
}
function AssignMatter({ caseId, onChange }) {
const [matters, setMatters] = useState([]);
const [matterId, setMatterId] = useState("");
const [error, setError] = useState("");
useEffect(() => {
api("/api/v1/matters").then((data) => setMatters(data.items)).catch((err) => setError(err.message));
}, []);
async function submit(event) {
event.preventDefault();
setError("");
try {
await api(`/api/v1/matters/${matterId}/case-links`, { method: "POST", body: { case_id: caseId } });
onChange();
} catch (err) {
setError(err.message);
}
}
return (
);
}
function NewSubcase({ parentId, onChange }) {
const [title, setTitle] = useState("");
const [rightsMode, setRightsMode] = useState("inherit_parent");
async function submit(event) {
event.preventDefault();
await api("/api/v1/cases", { method: "POST", body: { title, parent_case_id: parentId, rights_mode: rightsMode } });
setTitle("");
onChange();
}
return (
);
}
export function ChapterForm({ path, onChange }) {
const [title, setTitle] = useState("");
const [error, setError] = useState("");
async function submit(event) {
event.preventDefault();
setError("");
try {
const created = await api(path, { method: "POST", body: { title } });
setTitle("");
onChange(created);
} catch (err) {
setError(err.message);
}
}
return (
);
}
export function ContentForms({ context, placement, chapters, onChange }) {
return (
);
}
function chapterSelect(chapters, value, setValue) {
if (!chapters?.length) return null;
return (
Kapitel
setValue(event.target.value)}>
Ohne Kapitel
{chapters.map((chapter) => (
{chapter.title}
))}
);
}
export function NoteForm({ context, placement, chapters = [], initialChapter = "", targetLabel = "", onChange }) {
const [title, setTitle] = useState("");
const [text, setText] = useState("");
const [documentOn, setDocumentOn] = useState("");
const [chapterId, setChapterId] = useState(initialChapter);
const [error, setError] = useState("");
const [pending, setPending] = useState(false);
useEffect(() => { setChapterId(initialChapter || ""); }, [initialChapter]);
async function submit(event) {
event.preventDefault();
if (pending) return;
setError("");
setPending(true);
try {
await api("/api/v1/notes", {
method: "POST",
body: {
title,
document: textToDocument(text),
context,
...(placement ? { placement } : {}),
...(chapterId ? { chapter_id: chapterId } : {}),
...(documentOn ? { dates: { document_on: documentOn } } : {}),
},
});
setTitle("");
setText("");
setDocumentOn("");
markDirty(false);
onChange();
} catch (err) {
setError(err.message);
} finally {
setPending(false);
}
}
return (
);
}
export function FileForm({ context, placement, chapters = [], initialChapter = "", targetLabel = "", onChange }) {
const [title, setTitle] = useState("");
const [file, setFile] = useState(null);
const [chapterId, setChapterId] = useState(initialChapter);
const [documentOn, setDocumentOn] = useState("");
const [sentOn, setSentOn] = useState("");
const [receivedOn, setReceivedOn] = useState("");
const [error, setError] = useState("");
useEffect(() => { setChapterId(initialChapter || ""); }, [initialChapter]);
async function submit(event) {
event.preventDefault();
if (!file) return;
const form = new FormData();
form.set("title", title);
form.set("upload", file);
form.set("context_kind", context.kind);
form.set("context_id", context.id);
if (placement) {
form.set("placement_kind", placement.kind);
form.set("placement_id", placement.id);
}
if (chapterId) form.set("chapter_id", chapterId);
if (documentOn) form.set("document_on", documentOn);
if (sentOn) form.set("sent_on", sentOn);
if (receivedOn) form.set("received_on", receivedOn);
setError("");
try {
await api("/api/v1/files", { method: "POST", form });
setTitle("");
setFile(null);
markDirty(false);
onChange();
} catch (err) {
setError(err.message);
}
}
return (
Datei
setTitle(event.target.value)} placeholder="Titel des Schreibens" required />
setFile(event.target.files?.[0] || null)} required />
Dokumentdatum setDocumentOn(event.target.value)} />
Versand setSentOn(event.target.value)} />
Zugang setReceivedOn(event.target.value)} />
{chapterSelect(chapters, chapterId, setChapterId)}
Datei hinzufügen
);
}
function ExternalForm({ context, placement, chapters = [], initialChapter = "", targetLabel = "", onChange }) {
const [title, setTitle] = useState("");
const [externalId, setExternalId] = useState("");
const [source, setSource] = useState("paperless");
const [chapterId, setChapterId] = useState(initialChapter);
const [documentOn, setDocumentOn] = useState("");
const [sentOn, setSentOn] = useState("");
const [receivedOn, setReceivedOn] = useState("");
const [error, setError] = useState("");
useEffect(() => { setChapterId(initialChapter || ""); }, [initialChapter]);
async function submit(event) {
event.preventDefault();
setError("");
try {
await api("/api/v1/external-refs", {
method: "POST",
body: {
title,
source,
external_id: externalId,
context,
...(placement ? { placement } : {}),
...(chapterId ? { chapter_id: chapterId } : {}),
dates: {
document_on: documentOn || null,
sent_on: sentOn || null,
received_on: receivedOn || null,
},
},
});
setTitle("");
setExternalId("");
onChange();
} catch (err) {
setError(err.message);
}
}
return (
Paperless oder andere Referenz
setTitle(event.target.value)} placeholder="Anzeigetitel" required />
setSource(event.target.value)}>
Paperless
Andere Quelle
setExternalId(event.target.value)} placeholder="Externe ID" required />
Dokumentdatum setDocumentOn(event.target.value)} />
Versand setSentOn(event.target.value)} />
Zugang setReceivedOn(event.target.value)} />
{chapterSelect(chapters, chapterId, setChapterId)}
Referenz erfassen
);
}
function rightsText(rights) {
const parts = ["Lesen"];
if (rights.edit) parts.push("Bearbeiten");
if (rights.share) parts.push("Weitergeben");
if (rights.delete) parts.push("Löschen");
return parts.join(", ") + ".";
}