Files
tsumugu/frontend/src/pages/content.jsx
T
LarsandCursor 1621a7eb2f
Deploy Development / deploy (push) Successful in 25s
Test Suite / pytest-backend (push) Successful in 1m6s
Test Suite / smoke-dev (push) Successful in 0s
Test Suite / frontend-build (push) Successful in 5s
Lass ein Kapitel im Vorgang am Kopf ziehen, damit die Reihenfolge samt Inhalt erhalten bleibt.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-17 12:46:06 +02:00

974 lines
37 KiB
React

import { useEffect, useRef, useState } from "react";
import { Link } from "react-router-dom";
import { api, fetchFile, fetchPaperless } from "../api.js";
import { Modal } from "./Modal.jsx";
import { ErrorNote } from "./widgets.jsx";
export 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 formatStamp(value) {
if (!value) return "";
const [day, time = ""] = String(value).split("T");
return `${formatDate(day)} ${time.replace("Z", " UTC").slice(0, 8)}`.trim();
}
export function selectionOf(params) {
return {
scope: params.get("bereich") || "all",
chapterId: params.get("kapitel") || "",
};
}
export function writeSelection(params, setParams, scope, chapterId) {
const next = new URLSearchParams(params);
if (!scope || scope === "all") next.delete("bereich");
else next.set("bereich", scope);
if (chapterId) next.set("kapitel", chapterId);
else next.delete("kapitel");
setParams(next, { replace: true });
}
export function writeChapter(params, setParams, chapterId) {
const next = new URLSearchParams(params);
if (chapterId) next.set("kapitel", chapterId);
else next.delete("kapitel");
setParams(next, { replace: true });
}
export function withSelection(href, params) {
const url = new URL(href, "http://tsumugu.local");
for (const key of ["bereich", "kapitel"]) {
const value = params.get(key);
if (value && !url.searchParams.has(key)) url.searchParams.set(key, value);
}
const search = url.searchParams.toString();
return `${url.pathname}${search ? `?${search}` : ""}`;
}
export function TargetLine({ label, chapters = [], chapterId = "", chapterTitle = "" }) {
if (!label) return null;
const chapter = chapters.find((item) => item.id === chapterId);
const namedChapter = chapter?.title || chapterTitle;
return (
<p className="target-line">
Ziel: <strong>{label}</strong>
{namedChapter ? <> · Kapitel <strong>{namedChapter}</strong></> : null}
</p>
);
}
export function kindLabel(kind) {
if (kind === "note") return "Notiz";
if (kind === "file") return "Datei";
if (kind === "external_ref") return "Paperless";
return "Unterlage";
}
export function fachDate(element) {
return element?.dates?.document_on || null;
}
export function Trail({ items }) {
if (!items?.length) return null;
return (
<nav className="trail" aria-label="Pfad">
{items.map((item, index) => (
<span key={`${item.label}-${index}`}>
{index ? <span className="trail__sep" aria-hidden="true">/</span> : null}
{item.href ? <Link to={item.href}>{item.label}</Link> : <span aria-current="page">{item.label}</span>}
</span>
))}
</nav>
);
}
export function nestRecords(items, parentKey) {
const ids = new Set((items || []).map((item) => item.id));
const children = new Map();
const roots = [];
for (const item of items || []) {
const parentId = item[parentKey];
if (parentId && ids.has(parentId)) {
const list = children.get(parentId) || [];
list.push(item);
children.set(parentId, list);
} else {
roots.push(item);
}
}
return { roots, children };
}
function TreeBranch({ item, children, hrefFor, nested }) {
const kids = children.get(item.id) || [];
return (
<li>
<Link className="hierarchy__row" to={hrefFor(item)}>
<span className="hierarchy__kind">{item.kind_label || "Eintrag"}</span>
<strong>{item.title}</strong>
{!nested && item.parent_title ? <span className="muted">in {item.parent_title}</span> : null}
<span className="muted">{item.status === "open" ? "Offen" : item.status === "closed" ? "Geschlossen" : ""}</span>
</Link>
{kids.length ? (
<ul>
{kids.map((child) => (
<TreeBranch key={child.id} item={child} children={children} hrefFor={hrefFor} nested />
))}
</ul>
) : null}
</li>
);
}
export function RecordTree({ items, parentKey, hrefFor }) {
const { roots, children } = nestRecords(items, parentKey);
if (!roots.length) return null;
return (
<ul className="hierarchy">
{roots.map((item) => (
<TreeBranch key={item.id} item={item} children={children} hrefFor={hrefFor} nested={false} />
))}
</ul>
);
}
function sectionsOf(chapters, bindings) {
const buckets = new Map();
const loose = [];
for (const binding of bindings || []) {
if (binding.chapter_id && chapters.some((chapter) => chapter.id === binding.chapter_id)) {
const list = buckets.get(binding.chapter_id) || [];
list.push(binding);
buckets.set(binding.chapter_id, list);
} else {
loose.push(binding);
}
}
const sections = (chapters || []).map((chapter) => ({
id: chapter.id,
title: chapter.title,
documentOn: chapter.document_on || "",
items: buckets.get(chapter.id) || [],
}));
if (sections.length && loose.length) {
sections.push({ id: "loose", title: "Ohne Kapitel", documentOn: "", items: loose });
} else if (!sections.length) {
sections.push({ id: "loose", title: "", documentOn: "", items: loose });
}
return sections;
}
export function matterOpenHref(item) {
const contexts = item?.contexts || [];
if (contexts.some((entry) => entry.kind === "direct")) return `/matters/${item.id}`;
const context = contexts.find((entry) => entry.kind === "case");
if (!context) return `/matters/${item.id}`;
return `/matters/${item.id}?context_kind=case&context_id=${context.id}`;
}
export function Placements({ items }) {
if (!items?.length) return null;
const current = items.find((item) => item.current);
return (
<p className="placements">
<span>In Akte: </span>
{items.map((item, index) => (
<span key={item.case_id}>
{index ? <span aria-hidden="true"> · </span> : null}
<Link to={item.href} aria-current={item.current ? "true" : undefined}>{item.label.replaceAll("Unterakte ", "").replaceAll("Akte ", "")}</Link>
</span>
))}
{current ? <span className="muted"> · aktueller Handlungskontext</span> : <span className="muted"> · Handlungskontext direkt, solange keine Akte gewählt ist</span>}
</p>
);
}
export function ObjectMenu({ view, onView, children }) {
const [open, setOpen] = useState(false);
function choose(next) {
setOpen(false);
onView(next);
}
return (
<>
<button type="button" className="quiet" onClick={() => setOpen(true)}>Aktionen</button>
<Modal open={open} title="Aktionen" onClose={() => setOpen(false)}>
<div className="menu-list" onClick={() => setOpen(false)}>
<button type="button" className={view === "course" ? "" : "quiet"} onClick={() => choose("course")}>Fachlicher Verlauf</button>
<button type="button" className={view === "audit" ? "" : "quiet"} onClick={() => choose("audit")}>Änderungsprotokoll</button>
<button type="button" className={view === "links" ? "" : "quiet"} onClick={() => choose("links")}>Zuordnungen</button>
{children}
</div>
</Modal>
</>
);
}
export function WorkSwitch({ view, onView }) {
return (
<div className="order-bar" role="tablist" aria-label="Arbeitsfläche">
<button type="button" role="tab" aria-selected={view === "contents"} className={view === "contents" ? "" : "quiet"} onClick={() => onView("contents")}>Inhalte</button>
<button type="button" role="tab" aria-selected={view === "work"} className={view === "work" ? "" : "quiet"} onClick={() => onView("work")}>Aufgaben und Fristen</button>
{view !== "contents" && view !== "work" ? (
<button type="button" className="quiet" onClick={() => onView("contents")}>Zurück zu den Inhalten</button>
) : null}
</div>
);
}
function sourceLabel(element) {
if (element.kind === "note") return "Notiz";
if (element.kind === "external_ref") return element.external?.source === "paperless" ? "Paperless" : "Referenz";
if (element.file?.content_type === "application/pdf") return "PDF";
if (element.file?.content_type?.startsWith("image/")) return "Bild";
if (element.kind === "file") return "Datei";
return kindLabel(element.kind);
}
function blurb(element) {
return element.summary || element.excerpt || "";
}
function Thumb({ element, context }) {
const [url, setUrl] = useState("");
const [media, setMedia] = useState("");
const [failed, setFailed] = useState(false);
useEffect(() => {
if (!element.preview?.available) return undefined;
let alive = true;
let current = "";
const load = element.preview.source === "paperless" ? fetchPaperless(element.id, context) : fetchFile(element.id, context);
load.then((blob) => {
if (!alive) return;
current = URL.createObjectURL(blob);
setUrl(current);
if (blob.type.startsWith("image/")) setMedia("image");
else if (blob.type.includes("pdf")) setMedia("pdf");
else setMedia("other");
}).catch(() => {
if (alive) setFailed(true);
});
return () => {
alive = false;
if (current) URL.revokeObjectURL(current);
};
}, [element.id, element.preview?.available, element.preview?.source, context?.kind, context?.id]);
if (element.kind === "note") return <span className="thumb thumb--note">Notiz</span>;
if (url && media === "image") return <img className="thumb" alt="" src={url} />;
if (url && media === "pdf") return <iframe className="thumb thumb--pdf" title={`Vorschau ${element.title}`} src={url} />;
if (failed) return <span className="thumb thumb--empty">Vorschau nicht verfügbar</span>;
if (element.preview?.available) return <span className="thumb thumb--empty">Vorschau wird geladen</span>;
return <span className="thumb thumb--empty">Keine Vorschau</span>;
}
export function ContentBoard({
record,
bindings,
context,
containerKind,
containerId,
sortable = true,
onChange,
itemHref,
onlyChapter = "",
}) {
const source = bindings || record?.bindings || [];
const chapters = record?.chapters || [];
const [error, setError] = useState("");
const [pending, setPending] = useState(false);
const [draggingId, setDraggingId] = useState("");
const [indicator, setIndicator] = useState(null);
const dragRef = useRef(null);
const rootRef = useRef(null);
const custom = record?.content_order === "position";
const direction = record?.content_order_dir === "desc" ? "desc" : "asc";
const sections = sectionsOf(chapters, source);
const visibleSections = onlyChapter ? sections.filter((section) => section.id !== "loose") : sections;
const canSort = sortable && record?.rights?.edit;
const canMoveChapters = Boolean(canSort && chapters.length > 1);
const orderPath = `/api/v1/${containerKind === "case" ? "cases" : "matters"}/${containerId}`;
const orderContext = context && containerKind === "matter" ? { context } : {};
const finishDragRef = useRef(finishDrag);
finishDragRef.current = finishDrag;
useEffect(() => {
function onKey(event) {
if (event.key !== "Escape" || !dragRef.current) return;
dragRef.current = null;
setDraggingId("");
setIndicator(null);
}
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, []);
useEffect(() => {
const node = rootRef.current;
if (!node) return undefined;
function place(event) {
const drag = dragRef.current;
if (!drag?.html5) return;
event.preventDefault();
if (drag.kind === "chapter") {
drag.index = chapterUnder(event.clientY);
setIndicator({ sectionId: drag.chapterId, index: drag.index, kind: "chapter" });
return;
}
const sectionId = event.target?.closest?.("[data-section]")?.getAttribute("data-section");
if (!sectionId) return;
drag.targetSectionId = sectionId;
drag.index = indexAt(sectionId, event.clientY);
setIndicator({ sectionId, index: drag.index });
}
function drop(event) {
if (!dragRef.current?.html5) return;
place(event);
finishDragRef.current(dragRef.current);
}
node.addEventListener("dragover", place);
node.addEventListener("drop", drop);
return () => {
node.removeEventListener("dragover", place);
node.removeEventListener("drop", drop);
};
}, []);
async function saveMode(mode, nextDirection) {
setError("");
setPending(true);
try {
await api(`${orderPath}/content-order`, {
method: "PATCH",
body: { expected_version: record.version, mode, direction: nextDirection, ...orderContext },
});
onChange();
} catch (err) {
setError(err.message);
} finally {
setPending(false);
}
}
async function persist(next, version = record.version) {
setError("");
setPending(true);
try {
await api(`${orderPath}/bindings/order`, {
method: "POST",
body: {
expected_version: version,
binding_ids: next.flatMap((section) => section.items.map((item) => item.id)),
...orderContext,
},
});
onChange();
} catch (err) {
setError(err.message);
} finally {
setPending(false);
}
}
async function reorderChapters(ids) {
setError("");
setPending(true);
try {
let version = record.version;
if (!custom) {
const switched = await api(`${orderPath}/content-order`, {
method: "PATCH",
body: { expected_version: version, mode: "position", direction, ...orderContext },
});
version = switched.version;
}
await api(`${orderPath}/chapters/order`, {
method: "POST",
body: { expected_version: version, chapter_ids: ids, ...orderContext },
});
onChange();
} catch (err) {
setError(err.message);
} finally {
setPending(false);
}
}
function moveChapter(chapterId, delta) {
const ids = chapters.map((chapter) => chapter.id);
const index = ids.indexOf(chapterId);
const target = index + delta;
if (index < 0 || target < 0 || target >= ids.length) return;
const [id] = ids.splice(index, 1);
ids.splice(target, 0, id);
reorderChapters(ids);
}
async function saveChapterDate(chapterId, value) {
setError("");
setPending(true);
try {
await api(`/api/v1/chapters/${chapterId}`, {
method: "PATCH",
body: { expected_version: record.version, document_on: value || null, ...orderContext },
});
onChange();
} catch (err) {
setError(err.message);
} finally {
setPending(false);
}
}
async function move(bindingId, delta) {
const next = sections.map((section) => ({ ...section, items: [...section.items] }));
let moved = false;
for (const section of next) {
const index = section.items.findIndex((item) => item.id === bindingId);
const target = index + delta;
if (index < 0 || target < 0 || target >= section.items.length) continue;
const [item] = section.items.splice(index, 1);
section.items.splice(target, 0, item);
moved = true;
}
if (!moved) return;
await persist(next);
}
async function placeChapter(bindingId, chapterId) {
setError("");
setPending(true);
try {
await api(`/api/v1/bindings/${bindingId}/chapter`, {
method: "PATCH",
body: { expected_version: record.version, chapter_id: chapterId || null, ...orderContext },
});
onChange();
} catch (err) {
setError(err.message);
} finally {
setPending(false);
}
}
function indexAt(sectionId, clientY) {
const rows = [...(rootRef.current?.querySelectorAll(`[data-section="${sectionId}"] [data-binding]`) || [])];
for (let i = 0; i < rows.length; i += 1) {
const rect = rows[i].getBoundingClientRect();
if (clientY < rect.top + rect.height / 2) return i;
}
return rows.length;
}
function sectionUnder(clientY) {
const nodes = [...(rootRef.current?.querySelectorAll("[data-section]") || [])];
const hit = nodes.find((node) => {
const rect = node.getBoundingClientRect();
return clientY >= rect.top && clientY <= rect.bottom;
});
return hit?.getAttribute("data-section") || null;
}
function chapterUnder(clientY) {
const nodes = [...(rootRef.current?.querySelectorAll("[data-chapter] .chapter-head") || [])];
if (!nodes.length) return 0;
for (let i = 0; i < nodes.length; i += 1) {
const next = nodes[i + 1]?.getBoundingClientRect();
const bottom = next ? next.top : Number.POSITIVE_INFINITY;
if (clientY < bottom) return i;
}
return nodes.length - 1;
}
function finishDrag(drag) {
dragRef.current = null;
setDraggingId("");
setIndicator(null);
if (!drag || !drag.moved || drag.index == null) return;
if (drag.kind === "chapter") {
const ids = chapters.map((chapter) => chapter.id);
const from = ids.indexOf(drag.chapterId);
const target = drag.index;
if (from < 0 || target == null || target === from) return;
const [id] = ids.splice(from, 1);
ids.splice(Math.max(0, Math.min(target, ids.length)), 0, id);
reorderChapters(ids);
return;
}
const next = sections.map((section) => ({ ...section, items: [...section.items] }));
const source = next.find((item) => item.id === drag.sectionId);
const targetSection = next.find((item) => item.id === (drag.targetSectionId || drag.sectionId));
if (!source || !targetSection) return;
const from = source.items.findIndex((item) => item.id === drag.bindingId);
if (from < 0) return;
let target = drag.index;
if (source.id === targetSection.id && from < target) target -= 1;
if (target < 0) target = 0;
if (target > targetSection.items.length) target = targetSection.items.length;
if (source.id === targetSection.id && target === from) return;
const [item] = source.items.splice(from, 1);
const nextChapter = targetSection.id === "loose" ? null : targetSection.id;
const changed = (item.chapter_id || null) !== nextChapter;
item.chapter_id = nextChapter;
const insertAt = source.id === targetSection.id ? target : Math.min(target, targetSection.items.length);
targetSection.items.splice(insertAt, 0, item);
if (!changed) {
persist(next);
return;
}
setPending(true);
setError("");
api(`/api/v1/bindings/${item.id}/chapter`, {
method: "PATCH",
body: { expected_version: record.version, chapter_id: nextChapter, ...orderContext },
}).then((moved) => persist(next, moved.version)).catch((err) => {
setError(err.message);
setPending(false);
});
}
function track(event) {
const drag = dragRef.current;
if (!drag || drag.pointerId !== event.pointerId) return;
if (Math.abs(event.clientY - drag.startY) > 4) drag.moved = true;
if (event.clientY < 72) window.scrollBy(0, -16);
if (event.clientY > window.innerHeight - 72) window.scrollBy(0, 16);
if (drag.kind === "chapter") {
drag.index = chapterUnder(event.clientY);
setIndicator({ sectionId: drag.chapterId, index: drag.index, kind: "chapter" });
return;
}
drag.targetSectionId = sectionUnder(event.clientY) || drag.sectionId;
drag.index = indexAt(drag.targetSectionId, event.clientY);
setIndicator({ sectionId: drag.targetSectionId, index: drag.index });
}
function release(event) {
const drag = dragRef.current;
window.removeEventListener("pointermove", track);
window.removeEventListener("pointerup", release);
window.removeEventListener("pointercancel", cancel);
if (!drag || drag.html5 || drag.pointerId !== event.pointerId) return;
finishDrag(drag);
}
function cancel() {
const drag = dragRef.current;
window.removeEventListener("pointermove", track);
window.removeEventListener("pointerup", release);
window.removeEventListener("pointercancel", cancel);
if (drag?.html5) return;
dragRef.current = null;
setDraggingId("");
setIndicator(null);
}
function markHtml5(drag) {
const current = dragRef.current;
if (current && (current.chapterId === drag.chapterId || current.bindingId === drag.bindingId)) {
current.html5 = true;
current.moved = true;
return;
}
dragRef.current = { ...drag, html5: true, moved: true, index: null, pointerId: "html5", startY: 0 };
}
function endHtml5() {
setTimeout(() => {
const drag = dragRef.current;
if (!drag?.html5) return;
dragRef.current = null;
setDraggingId("");
setIndicator(null);
}, 0);
}
function beginDrag(event, drag) {
if (pending || (event.button != null && event.button !== 0)) return;
event.preventDefault();
dragRef.current = { ...drag, pointerId: event.pointerId, startY: event.clientY, moved: false, index: null };
setDraggingId(drag.bindingId || drag.chapterId || "");
window.addEventListener("pointermove", track);
window.addEventListener("pointerup", release);
window.addEventListener("pointercancel", cancel);
try {
event.currentTarget.setPointerCapture?.(event.pointerId);
} catch {
// The window listeners still follow the pointer when capture is unavailable.
}
}
return (
<div className="contents" ref={rootRef}>
{canSort ? (
<OrderChoice
mode={custom ? "position" : "date"}
direction={direction}
disabled={pending}
allowPosition
onChange={saveMode}
/>
) : sortable ? (
<p className="muted">{custom ? "Eigene Reihenfolge" : `Fachliches Datum, ${direction === "desc" ? "absteigend" : "aufsteigend"}`}</p>
) : null}
{pending ? <p className="muted">Ordnung wird gespeichert …</p> : null}
<ErrorNote error={error} />
{source.length || chapters.length ? (
visibleSections.map((section) => {
const chapterIndex = chapters.findIndex((chapter) => chapter.id === section.id);
const expanded = !onlyChapter || section.id === onlyChapter;
const movable = canMoveChapters && section.id !== "loose";
const classes = ["content-section"];
if (draggingId === section.id) classes.push("is-dragging");
if (!expanded) classes.push("is-collapsed");
if (indicator?.kind === "chapter" && chapterIndex === indicator.index && draggingId !== section.id) classes.push("is-chapter-target");
return (
<section
key={section.id}
className={classes.join(" ")}
data-section={section.id}
data-chapter={section.id === "loose" ? undefined : section.id}
>
{section.title ? (
<div
className={movable ? "chapter-head is-movable" : "chapter-head"}
draggable={movable && !pending}
onPointerDownCapture={(event) => {
if (!movable) return;
if (event.target.closest("input, textarea, select, a, label, .chapter-move")) return;
beginDrag(event, { kind: "chapter", chapterId: section.id });
}}
onDragStart={(event) => {
if (!movable || event.target.closest("input, textarea, select, a, label, .chapter-move")) {
event.preventDefault();
return;
}
event.dataTransfer.effectAllowed = "move";
event.dataTransfer.setData("text/plain", section.id);
markHtml5({ kind: "chapter", chapterId: section.id });
setDraggingId(section.id);
}}
onDragEnd={endHtml5}
>
{movable ? (
<span className="handle" aria-hidden="true">
<span className="handle__grip" />
</span>
) : null}
<h3 className="chapter-title">{section.title}</h3>
{section.documentOn ? <span className="muted">{formatDate(section.documentOn)}</span> : null}
{movable ? (
<span className="chapter-move">
<button type="button" className="quiet" aria-label={`${section.title} nach oben`} disabled={pending || chapters[0]?.id === section.id} onClick={() => moveChapter(section.id, -1)}>Nach oben</button>
<button type="button" className="quiet" aria-label={`${section.title} nach unten`} disabled={pending || chapters[chapters.length - 1]?.id === section.id} onClick={() => moveChapter(section.id, 1)}>Nach unten</button>
</span>
) : null}
{canSort && section.id !== "loose" ? (
<label className="chapter-date">
Datum
<input
type="date"
aria-label={`Datum für ${section.title}`}
value={section.documentOn || ""}
disabled={pending}
onChange={(event) => saveChapterDate(section.id, event.target.value)}
/>
</label>
) : null}
</div>
) : null}
{expanded && section.title && !section.items.length ? <p className="muted">Noch nichts in diesem Kapitel.</p> : null}
{expanded ? <ol className="preview-list">
{section.items.map((binding, index) => {
const element = binding.element;
const href = itemHref(binding);
const text = blurb(element);
return (
<li key={binding.id} data-binding={binding.id} className={draggingId === binding.id ? "preview-row is-dragging" : "preview-row"}>
{indicator?.sectionId === section.id && indicator?.kind !== "chapter" && indicator.index === index ? <div className="insert-line" /> : null}
{canSort && custom ? (
<button
type="button"
className="handle"
aria-label={`${element.title} ziehen`}
draggable={!pending}
disabled={pending}
onPointerDown={(event) => beginDrag(event, { bindingId: binding.id, sectionId: section.id })}
onDragStart={(event) => {
event.dataTransfer.effectAllowed = "move";
event.dataTransfer.setData("text/plain", binding.id);
markHtml5({ bindingId: binding.id, sectionId: section.id, targetSectionId: section.id });
setDraggingId(binding.id);
}}
onDragEnd={endHtml5}
>
<span className="handle__grip" aria-hidden="true" />
</button>
) : null}
<Thumb element={element} context={context} />
<Link className="preview-row__main" to={href}>
<strong>{element.title}</strong>
<span className="preview-row__meta">{formatDate(fachDate(element))} · {sourceLabel(element)}</span>
{text ? <span className="preview-row__text">{text}</span> : null}
{binding.origin ? <span className="preview-row__origin">{binding.origin}{binding.shared ? " · weitere Einbindung" : ""}</span> : null}
</Link>
{(canSort && custom) || (canSort && chapters.length) ? (
<div className="preview-row__actions">
{canSort && custom ? (
<details className="row-menu">
<summary>Reihenfolge</summary>
<button type="button" aria-label={`${element.title} nach oben`} disabled={pending || index === 0} onClick={() => move(binding.id, -1)}>Nach oben</button>
<button type="button" aria-label={`${element.title} nach unten`} disabled={pending || index === section.items.length - 1} onClick={() => move(binding.id, 1)}>Nach unten</button>
</details>
) : null}
{canSort && chapters.length ? (
<details className="row-menu">
<summary>In Kapitel einordnen</summary>
<label>
Kapitel
<select value={binding.chapter_id || ""} disabled={pending} onChange={(event) => placeChapter(binding.id, event.target.value)}>
<option value="">Ohne Kapitel</option>
{chapters.map((chapter) => <option key={chapter.id} value={chapter.id}>{chapter.title}</option>)}
</select>
</label>
</details>
) : null}
</div>
) : null}
</li>
);
})}
{indicator?.sectionId === section.id && indicator?.kind !== "chapter" && indicator.index === section.items.length ? <li className="insert-line" aria-hidden="true" /> : null}
</ol> : null}
</section>
);
})
) : (
<p className="muted">Noch keine Unterlage und keine Notiz.</p>
)}
</div>
);
}
export function OrderChoice({ mode, direction, disabled, allowPosition = false, onChange }) {
const value = mode === "position" ? "position" : direction === "desc" ? "date-desc" : "date-asc";
return (
<label className="order-choice">
<span>Ordnung</span>
<select
aria-label="Ordnung der Inhalte"
value={value}
disabled={disabled}
onChange={(event) => {
const next = event.target.value;
if (next === "position") onChange("position", direction === "desc" ? "desc" : "asc");
else onChange("date", next === "date-desc" ? "desc" : "asc");
}}
>
<option value="date-asc">Fachliches Datum, aufsteigend</option>
<option value="date-desc">Fachliches Datum, absteigend</option>
{allowPosition ? <option value="position">Eigene Reihenfolge</option> : null}
</select>
</label>
);
}
export function CourseList({ items }) {
if (!items) return <p className="muted">Verlauf wird geladen …</p>;
if (!items.length) return <p className="muted">Noch kein fachlicher Verlauf.</p>;
return (
<ol className="timeline">
{items.map((item) => (
<li key={item.id}>
<time>{item.dated ? formatDate(item.document_on) : "Ohne Datum"}</time>
<div>
<strong>{item.title}</strong>
<span>{kindLabel(item.kind)}{item.sent_on ? ` · Versand ${formatDate(item.sent_on)}` : ""}{item.received_on ? ` · Zugang ${formatDate(item.received_on)}` : ""}</span>
</div>
</li>
))}
</ol>
);
}
export function RecordTabs({ coursePath, auditPath }) {
const [tab, setTab] = useState("");
const [course, setCourse] = useState(null);
const [audit, setAudit] = useState(null);
const [cursor, setCursor] = useState(null);
const [error, setError] = useState("");
async function showCourse() {
setTab("course");
if (course) return;
setError("");
try {
const data = await api(coursePath);
setCourse(data.items);
} catch (err) {
setError(err.message);
}
}
async function showAudit(nextCursor) {
setTab("audit");
setError("");
try {
const joiner = auditPath.includes("?") ? "&" : "?";
const data = await api(`${auditPath}${nextCursor ? `${joiner}cursor=${encodeURIComponent(nextCursor)}` : ""}`);
setAudit((current) => (nextCursor ? [...(current || []), ...data.items] : data.items));
setCursor(data.next_cursor);
} catch (err) {
setError(err.message);
}
}
return (
<section className="section">
<div className="order-bar">
<button type="button" className={tab === "course" ? "" : "quiet"} onClick={showCourse}>Fachlicher Verlauf</button>
<button type="button" className={tab === "audit" ? "" : "quiet"} onClick={() => showAudit("")}>Änderungsprotokoll</button>
</div>
<ErrorNote error={error} />
{tab === "course" ? <CourseList items={course} /> : null}
{tab === "audit" ? <AuditLog items={audit} nextCursor={cursor} onMore={() => showAudit(cursor)} /> : null}
</section>
);
}
export function AuditLog({ items, nextCursor, onMore }) {
if (!items) return <p className="muted">Protokoll wird geladen …</p>;
if (!items.length) return <p className="muted">Noch kein Eintrag.</p>;
return (
<div className="stack">
<ol className="timeline">
{items.map((item) => (
<li key={item.id}>
<time>{formatStamp(item.occurred_at)}</time>
<div>
<strong>{item.label}</strong>
<span>{item.title}{item.actor_display_name ? ` · ${item.actor_display_name}` : ""}</span>
</div>
</li>
))}
</ol>
{nextCursor ? <button type="button" className="quiet" onClick={onMore}>Weitere Einträge</button> : null}
</div>
);
}
export function WorkLists({ record, context, onChange }) {
const linked = new Set((record.task_deadline_links || []).map((item) => item.task_id));
async function complete(task) {
const body = { expected_version: task.version, status: "done" };
const taskContext = task.action_context || context;
if (taskContext) body.context = taskContext;
await api(`/api/v1/tasks/${task.id}`, { method: "PATCH", body });
onChange();
}
async function fulfill(deadline) {
const body = { expected_version: deadline.version };
if (context) body.context = context;
await api(`/api/v1/deadlines/${deadline.id}/fulfill`, { method: "POST", body });
onChange();
}
return (
<div className="stack">
<p className="muted">Erledigen und Erfüllen bleiben getrennte Aktionen.</p>
<div>
<h3>Aufgaben</h3>
{record.tasks?.length ? (
<ul className="work">
{record.tasks.map((task) => (
<li key={task.id}>
<div>
<strong>{task.title}</strong>
<span>{task.status === "done" ? "Erledigt" : "Offen"}{task.due_on ? ` · ${formatDate(task.due_on)}` : ""}{task.matter_title ? ` · ${task.matter_title}` : ""}</span>
{linked.has(task.id) ? <small>Mit einer Frist verknüpft, ohne sie zu erfüllen.</small> : null}
</div>
{task.status === "open" && task.rights?.edit !== false ? <button type="button" onClick={() => complete(task)}>Erledigen</button> : null}
</li>
))}
</ul>
) : <p className="muted">Keine Aufgabe.</p>}
</div>
<div>
<h3>Fristen</h3>
{record.deadlines?.length ? (
<ul className="work">
{record.deadlines.map((deadline) => (
<li key={deadline.id}>
<div>
<strong>{deadline.title}</strong>
<span>{deadline.status === "fulfilled" ? "Erfüllt" : "Offen"} · {formatDate(deadline.due_on)}{deadline.matter_title ? ` · ${deadline.matter_title}` : ""}</span>
</div>
{deadline.status === "open" ? <button type="button" onClick={() => fulfill(deadline)}>Frist erfüllen</button> : null}
</li>
))}
</ul>
) : <p className="muted">Keine Frist.</p>}
</div>
</div>
);
}
export function SurfaceView({ view, coursePath, auditPath }) {
const [course, setCourse] = useState(null);
const [audit, setAudit] = useState(null);
const [cursor, setCursor] = useState(null);
const [error, setError] = useState("");
useEffect(() => {
setCourse(null);
setAudit(null);
setCursor(null);
}, [coursePath, auditPath]);
useEffect(() => {
if (view !== "course") return undefined;
let alive = true;
api(coursePath).then((data) => {
if (alive) setCourse(data.items);
}).catch((err) => {
if (alive) setError(err.message);
});
return () => {
alive = false;
};
}, [view, coursePath]);
async function showAudit(nextCursor) {
const joiner = auditPath.includes("?") ? "&" : "?";
const data = await api(`${auditPath}${nextCursor ? `${joiner}cursor=${encodeURIComponent(nextCursor)}` : ""}`);
setAudit((current) => (nextCursor ? [...(current || []), ...data.items] : data.items));
setCursor(data.next_cursor);
}
useEffect(() => {
if (view !== "audit") return undefined;
let alive = true;
showAudit("").catch((err) => {
if (alive) setError(err.message);
});
return () => {
alive = false;
};
}, [view, auditPath]);
if (view !== "course" && view !== "audit") return null;
return (
<div>
<ErrorNote error={error} />
{view === "course" ? <CourseList items={course} /> : <AuditLog items={audit} nextCursor={cursor} onMore={() => showAudit(cursor).catch((err) => setError(err.message))} />}
</div>
);
}