Files
tsumugu/frontend/src/pages/correspondence.jsx
T
LarsandCursor f8cb9f8d4b
Deploy Development / deploy (push) Successful in 26s
Test Suite / pytest-backend (push) Successful in 1m36s
Test Suite / smoke-dev (push) Successful in 0s
Test Suite / frontend-build (push) Successful in 8s
Halte den Zug an der ganzen Zeile fest und zaehle im Dialog nur die sichtbaren Unterlagen, damit das Ablegen ankommt und Einzelbelege nicht doppelt erscheinen.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-18 12:59:52 +02:00

971 lines
37 KiB
React

import { useEffect, useMemo, useRef, useState } from "react";
import { Link } from "react-router-dom";
import { api } from "../api.js";
import { buildChapterSections, sectionCounts } from "./chapters.js";
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 scopeBody(context, containerKind, containerId) {
const rights = context || { kind: containerKind, id: containerId };
const same = rights.kind === containerKind && rights.id === containerId;
return { context: rights, placement: same ? null : { kind: containerKind, id: containerId } };
}
export function channelWord(channel) {
if (channel === "email") return "per E-Mail";
if (channel === "post") return "per Post";
if (channel === "other") return "sonstiger Weg";
return "";
}
export function unitMarks(binding) {
const pack = binding?.correspondence;
if (!pack) return "";
const parts = [];
const attachments = pack.attachments || [];
if (attachments.length === 1) parts.push("1 Anlage");
else if (attachments.length > 1) parts.push(`${attachments.length} Anlagen`);
const dispatches = pack.dispatches || [];
if (dispatches.length === 1) parts.push(channelWord(dispatches[0].channel));
else if (dispatches.length > 1) parts.push(`${dispatches.length} Versände`);
const evidence = dispatches.reduce((sum, item) => sum + (item.evidence || []).length, 0);
if (evidence === 1) parts.push("1 Beleg");
else if (evidence > 1) parts.push(`${evidence} Belege`);
return parts.join(" · ");
}
export function hostMark(binding) {
const hosts = binding?.correspondence?.hosts || [];
if (!hosts.length) return "";
return `Dieselbe Unterlage · Anlage zu ${hosts.map((item) => item.title).join(", ")}`;
}
function fieldBody(scope, extra) {
const body = { ...extra, context: scope.context };
if (scope.placement) body.placement = scope.placement;
return body;
}
export const ASSIGN_MIME = "application/x-tsumugu-item";
export const RECEIPT_ROLES = [
["email", "E-Mail"],
["submission", "Einlieferungsbeleg"],
["delivery", "Zustellung oder Versandbestätigung"],
["other", "Sonstiger Beleg"],
];
export function receiptRoleLabel(role, fallback = "") {
return RECEIPT_ROLES.find((item) => item[0] === role)?.[1] || fallback || role;
}
function receiptCaption(proof) {
if (proof.role === "email" && proof.source !== "imap") return "Beleg";
return receiptRoleLabel(proof.role, proof.role_label);
}
function receiptWhen(item) {
if (item.sent_on) return formatDate(item.sent_on);
const dated = (item.evidence || []).find((proof) => proof.document_on);
return dated ? formatDate(dated.document_on) : "";
}
function isShipment(item) {
const proofs = item.evidence || [];
if (item.channel === "other") return false;
if (proofs.length > 0 && proofs.every((proof) => proof.kind === "file")) return false;
return (item.items || []).length > 0;
}
function receiptHeading(item) {
const who = item.counterpart ? ` · ${item.counterpart}` : "";
const when = receiptWhen(item);
if (!isShipment(item)) return `${when || "Beleg"}${who}`;
return `Versand ${when || "undatiert"} · ${item.channel_label}${who}`;
}
export function writeAssign(event, payload) {
event.dataTransfer.effectAllowed = "copyMove";
event.dataTransfer.setData(ASSIGN_MIME, JSON.stringify(payload));
event.dataTransfer.setData("text/plain", payload.title || "");
}
function ancestorIds(chapters, chapterId) {
const byId = new Map((chapters || []).map((chapter) => [chapter.id, chapter]));
const ids = [];
const seen = new Set();
let current = chapterId ? byId.get(chapterId) : null;
while (current && !seen.has(current.id)) {
seen.add(current.id);
ids.push(current.id);
current = current.parent_chapter_id ? byId.get(current.parent_chapter_id) : null;
}
return ids;
}
function branchItems(section) {
return [
...(section.items || []),
...(section.children || []).flatMap(branchItems),
];
}
function titleMatches(binding, needle) {
if (!needle) return true;
return (binding.element?.title || "").toLowerCase().includes(needle);
}
function branchVisible(section, needle) {
if (!needle) return true;
if ((section.items || []).some((item) => titleMatches(item, needle))) return true;
return (section.children || []).some((child) => branchVisible(child, needle));
}
function PickBox({ checked, mixed = false, disabled = false, label, onChange }) {
const ref = useRef(null);
useEffect(() => {
if (ref.current) ref.current.indeterminate = mixed;
}, [mixed]);
return (
<input
ref={ref}
type="checkbox"
checked={checked}
disabled={disabled}
aria-checked={mixed ? "mixed" : checked}
aria-label={label}
onChange={onChange}
/>
);
}
function selectionState(ids, selected) {
if (!ids.length) return "off";
const count = ids.filter((id) => selected.has(id)).length;
if (count === 0) return "off";
if (count === ids.length) return "on";
return "mixed";
}
export function StructureAssignDialog({ host, bindings, chapters, scope, pending, onClose, onDone }) {
const visibleBindings = useMemo(
() => (bindings || []).filter((item) => !item.correspondence?.fold),
[bindings],
);
const tree = useMemo(() => buildChapterSections(chapters, visibleBindings), [chapters, visibleBindings]);
const receiptIds = useMemo(() => new Set(
(host.correspondence?.dispatches || []).flatMap((item) => (item.evidence || []).map((proof) => proof.element_id)),
), [host]);
const [opened, setOpened] = useState(() => new Set(host.chapter_id ? ancestorIds(chapters, host.chapter_id) : ["loose"]));
const [query, setQuery] = useState("");
const [selected, setSelected] = useState(() => new Set());
const [step, setStep] = useState("pick");
const [role, setRole] = useState("other");
const [fold, setFold] = useState("evidence");
const [dispatchId, setDispatchId] = useState(host.correspondence?.dispatches?.[0]?.id || "");
const [channel, setChannel] = useState("other");
const [sentOn, setSentOn] = useState("");
const [counterpart, setCounterpart] = useState("");
const [error, setError] = useState("");
const [busy, setBusy] = useState(false);
const needle = query.trim().toLowerCase();
const taken = new Set((host.correspondence?.attachments || []).map((item) => item.element_id));
const dispatches = host.correspondence?.dispatches || [];
function toggle(id) {
setSelected((current) => {
const next = new Set(current);
if (next.has(id)) next.delete(id);
else next.add(id);
return next;
});
}
function toggleIds(ids) {
if (!ids.length) return;
setSelected((current) => {
const next = new Set(current);
const allOn = ids.every((id) => next.has(id));
ids.forEach((id) => {
if (allOn) next.delete(id);
else next.add(id);
});
return next;
});
}
function selectable(id) {
return id !== host.element.id && !taken.has(id) && !receiptIds.has(id);
}
function toggleChapter(section) {
toggleIds(branchItems(section).map((item) => item.element.id).filter(selectable));
}
function visibleIds() {
const ids = [];
function walk(section) {
if (!branchVisible(section, needle)) return;
for (const item of section.items || []) {
if (selectable(item.element.id) && titleMatches(item, needle)) ids.push(item.element.id);
}
for (const child of section.children || []) walk(child);
}
tree.roots.forEach(walk);
for (const item of tree.loose) {
if (selectable(item.element.id) && titleMatches(item, needle)) ids.push(item.element.id);
}
return ids;
}
async function saveAttachments() {
const ids = [...selected].filter((id) => selectable(id));
if (!ids.length) {
setError("In der Auswahl ist keine neue Anlage.");
return;
}
setBusy(true);
setError("");
try {
await api(`/api/v1/elements/${host.element.id}/attachments`, {
method: "POST",
body: fieldBody(scope, {
expected_version: host.element.version,
attachment_element_ids: ids,
fold: "attachment",
}),
});
onDone();
onClose();
} catch (err) {
setError(err.message);
onDone();
} finally {
setBusy(false);
}
}
async function saveReceipts(event) {
event.preventDefault();
const ids = [...selected].filter((id) => selectable(id));
if (!ids.length) return;
setBusy(true);
setError("");
try {
if (!dispatchId) {
await api(`/api/v1/elements/${host.element.id}/dispatches`, {
method: "POST",
body: fieldBody(scope, {
expected_version: host.element.version,
channel,
sent_on: sentOn || null,
counterpart: counterpart.trim() || null,
attachment_element_ids: [],
evidence: ids.map((id) => ({ element_id: id, role, fold })),
historical_gap: false,
capture_editions: false,
}),
});
} else {
const dispatch = dispatches.find((item) => item.id === dispatchId);
const already = new Set((dispatch?.evidence || []).map((item) => item.element_id));
const fresh = ids.filter((id) => !already.has(id));
if (!fresh.length) {
setError("Diese Belege liegen an dem Versand bereits.");
return;
}
let version = dispatch?.version || 1;
for (const id of fresh) {
await api(`/api/v1/dispatches/${dispatchId}/evidence`, {
method: "POST",
body: fieldBody(scope, {
expected_version: version,
element_id: id,
role,
fold,
}),
});
version += 1;
}
}
onDone();
onClose();
} catch (err) {
setError(err.message);
onDone();
} finally {
setBusy(false);
}
}
function renderRow(item) {
const id = item.element.id;
const isHost = id === host.element.id;
const notes = [
formatDate(item.element.dates?.document_on),
isHost ? "dieses Schriftstück" : "",
taken.has(id) ? "bereits Anlage" : "",
receiptIds.has(id) ? "bereits Beleg" : "",
].filter(Boolean).join(" · ");
const blocked = isHost || taken.has(id) || receiptIds.has(id);
return (
<li key={item.id}>
<label className="pick-tree__row">
<PickBox checked={selected.has(id)} disabled={blocked} label={item.element.title} onChange={() => toggle(id)} />
<span className="pick-tree__title">{item.element.title}</span>
<span className="pick-tree__kind">{notes}</span>
</label>
</li>
);
}
function renderSection(section) {
if (!branchVisible(section, needle)) return null;
const expanded = Boolean(needle) || opened.has(section.id);
const counts = sectionCounts(section);
const total = counts.direct + counts.nested;
const ids = branchItems(section).map((item) => item.element.id).filter(selectable);
const state = selectionState(ids, selected);
return (
<li key={section.id}>
<div className="pick-tree__row">
<button
type="button"
className="pick-tree__twist"
aria-expanded={expanded}
aria-label={`${section.title} ${expanded ? "zuklappen" : "aufklappen"}`}
onClick={() => setOpened((current) => {
const next = new Set(current);
if (next.has(section.id)) next.delete(section.id);
else next.add(section.id);
return next;
})}
>
{expanded ? "▾" : "▸"}
</button>
<label>
<PickBox
checked={state === "on"}
mixed={state === "mixed"}
disabled={!ids.length}
label={`Alle in ${section.title}`}
onChange={() => toggleChapter(section)}
/>
<span className="pick-tree__title">{section.title}</span>
<span className="pick-tree__kind">{total}</span>
</label>
</div>
{expanded ? (
<ul>
{(section.items || []).filter((item) => titleMatches(item, needle)).map((item) => renderRow(item))}
{(section.children || []).map((child) => renderSection(child))}
</ul>
) : null}
</li>
);
}
const loose = tree.loose.filter((item) => titleMatches(item, needle));
const roots = tree.roots.map((section) => renderSection(section, 0)).filter(Boolean);
const looseIds = loose.map((item) => item.element.id).filter(selectable);
const looseState = selectionState(looseIds, selected);
const looseOpen = Boolean(needle) || opened.has("loose");
return (
<div className="stack pick-tree-dialog">
<p className="pick-tree__lead">Zuordnen an {host.element.title}</p>
<label className="pick-tree__find">
Suchen
<input value={query} onChange={(event) => setQuery(event.target.value)} placeholder="Titel" />
</label>
{step === "pick" ? (
<>
<ul className="pick-tree">
{roots}
{loose.length ? (
<li>
<div className="pick-tree__row">
<button
type="button"
className="pick-tree__twist"
aria-expanded={looseOpen}
aria-label={`Ohne Kapitel ${looseOpen ? "zuklappen" : "aufklappen"}`}
onClick={() => setOpened((current) => {
const next = new Set(current);
if (next.has("loose")) next.delete("loose");
else next.add("loose");
return next;
})}
>
{looseOpen ? "▾" : "▸"}
</button>
<label>
<PickBox
checked={looseState === "on"}
mixed={looseState === "mixed"}
disabled={!looseIds.length}
label="Alle ohne Kapitel"
onChange={() => toggleIds(looseIds)}
/>
<span className="pick-tree__title">Ohne Kapitel</span>
<span className="pick-tree__kind">{loose.length}</span>
</label>
</div>
{looseOpen ? (
<ul>
{loose.map((item) => renderRow(item))}
</ul>
) : null}
</li>
) : null}
{!roots.length && !loose.length ? <li className="pick-tree__empty">Nichts mit diesem Titel.</li> : null}
</ul>
<div className="pick-tree__bar">
<span>{selected.size} ausgewählt</span>
{needle ? <button type="button" className="quiet" onClick={() => toggleIds(visibleIds())}>Sichtbare</button> : null}
<button type="button" disabled={pending || busy || !selected.size} onClick={saveAttachments}>Als Anlagen</button>
<button type="button" disabled={pending || busy || !selected.size} onClick={() => { setError(""); setStep("receipt"); }}>Als Belege</button>
<button type="button" className="quiet" onClick={onClose}>Schließen</button>
</div>
</>
) : (
<form className="stack" onSubmit={saveReceipts}>
<p>{selected.size} Belege. Dieselbe Rolle gilt für die Auswahl.</p>
<label>
Versand
<select value={dispatchId} onChange={(event) => setDispatchId(event.target.value)}>
<option value="">Neuen Versand anlegen</option>
{dispatches.map((item) => (
<option key={item.id} value={item.id}>
{item.sent_on ? formatDate(item.sent_on) : "undatiert"} · {item.channel_label}
</option>
))}
</select>
</label>
{!dispatchId ? (
<>
<label>
Weg
<select value={channel} onChange={(event) => setChannel(event.target.value)}>
<option value="email">E-Mail</option>
<option value="post">Post</option>
<option value="other">Sonstiger Weg</option>
</select>
</label>
<label>Versanddatum<input type="date" value={sentOn} onChange={(event) => setSentOn(event.target.value)} /></label>
<label>Gegenüber<input value={counterpart} onChange={(event) => setCounterpart(event.target.value)} maxLength={200} /></label>
</>
) : null}
<label>
Rolle
<select value={role} onChange={(event) => setRole(event.target.value)}>
{RECEIPT_ROLES.map(([value, label]) => <option key={value} value={value}>{label}</option>)}
</select>
</label>
<fieldset>
<legend>Darstellung in der Liste</legend>
<label><input type="radio" name="assign-fold" checked={fold === "evidence"} onChange={() => setFold("evidence")} /> Nur am Versand zeigen</label>
<label><input type="radio" name="assign-fold" checked={fold === "keep"} onChange={() => setFold("keep")} /> Zusätzlich als eigenen Eintrag behalten</label>
</fieldset>
<button type="submit" disabled={pending || busy}>Belege zuordnen</button>
<button type="button" className="quiet" onClick={() => setStep("pick")}>Zurück zur Struktur</button>
</form>
)}
{error ? <p className="error">{error}</p> : null}
</div>
);
}
export function DispatchDialog({ host, scope, pending, onClose, onDone }) {
const proposal = host.correspondence?.attachments || [];
const [order, setOrder] = useState(proposal.map((item) => item.element_id));
const [chosen, setChosen] = useState(() => new Set(proposal.map((item) => item.element_id)));
const [channel, setChannel] = useState("email");
const [sentOn, setSentOn] = useState("");
const [counterpart, setCounterpart] = useState("");
const [historical, setHistorical] = useState(false);
const [error, setError] = useState("");
function move(id, delta) {
setOrder((current) => {
const index = current.indexOf(id);
const target = index + delta;
if (index < 0 || target < 0 || target >= current.length) return current;
const next = [...current];
const [item] = next.splice(index, 1);
next.splice(target, 0, item);
return next;
});
}
async function save(event) {
event.preventDefault();
setError("");
try {
await api(`/api/v1/elements/${host.element.id}/dispatches`, {
method: "POST",
body: fieldBody(scope, {
expected_version: host.element.version,
channel,
sent_on: sentOn || null,
counterpart: counterpart.trim() || null,
attachment_element_ids: order.filter((id) => chosen.has(id)),
evidence: [],
historical_gap: historical,
}),
});
onDone();
} catch (err) {
setError(err.message);
}
}
return (
<form className="stack" onSubmit={save}>
<p>Versand von <strong>{host.element.title}</strong> dokumentieren. Dabei wird nichts verschickt. Die Anlagenliste ist ein Vorschlag für diesen Versand.</p>
<label>
Weg
<select value={channel} onChange={(event) => setChannel(event.target.value)}>
<option value="email">E-Mail</option>
<option value="post">Post</option>
<option value="other">Sonstiger Weg</option>
</select>
</label>
<label>
Versanddatum
<input type="date" value={sentOn} onChange={(event) => setSentOn(event.target.value)} />
</label>
<p className="muted">Leer lassen, wenn der Versandtag unbekannt ist. Der Erfassungszeitpunkt ersetzt ihn nicht.</p>
<label>
Gegenüber
<input value={counterpart} onChange={(event) => setCounterpart(event.target.value)} maxLength={200} />
</label>
<p className="muted">Leer lassen, wenn das Gegenüber unbekannt ist.</p>
<fieldset>
<legend>Tatsächlich mitversendet</legend>
<ol className="choice-list">
{order.map((id, index) => {
const item = proposal.find((entry) => entry.element_id === id);
if (!item) return null;
return (
<li key={id}>
<label>
<input type="checkbox" checked={chosen.has(id)} onChange={() => setChosen((current) => {
const next = new Set(current);
if (next.has(id)) next.delete(id);
else next.add(id);
return next;
})} />
<span>{item.title}</span>
<span className="muted">{formatDate(item.document_on)}</span>
</label>
<span className="choice-list__move">
<button type="button" disabled={index === 0} onClick={() => move(id, -1)} aria-label={`${item.title} nach oben`}>↑</button>
<button type="button" disabled={index === order.length - 1} onClick={() => move(id, 1)} aria-label={`${item.title} nach unten`}>↓</button>
</span>
</li>
);
})}
</ol>
{!proposal.length ? <p className="muted">Keine zugeordnete Anlage. Das Schreiben kann allein dokumentiert werden.</p> : null}
</fieldset>
<label>
<input type="checkbox" checked={historical} onChange={(event) => setHistorical(event.target.checked)} />
Historische Originalfassung liegt nicht mehr vor
</label>
{error ? <p className="error">{error}</p> : null}
<button type="submit" disabled={pending}>Versand dokumentieren</button>
<button type="button" className="quiet" onClick={onClose}>Abbrechen</button>
</form>
);
}
export function EvidenceDialog({ element, hosts, scope, pending, presetDispatchId, replace = null, onClose, onDone }) {
const [hostId, setHostId] = useState(hosts[0]?.element.id || "");
const host = hosts.find((item) => item.element.id === hostId) || null;
const [dispatchId, setDispatchId] = useState(
presetDispatchId !== undefined ? presetDispatchId : (host?.correspondence?.dispatches?.[0]?.id || ""),
);
const [role, setRole] = useState("other");
const [fold, setFold] = useState("evidence");
const [channel, setChannel] = useState("other");
const [sentOn, setSentOn] = useState("");
const [counterpart, setCounterpart] = useState("");
const [result, setResult] = useState(null);
const [error, setError] = useState("");
async function save(event) {
event.preventDefault();
if (!host) return;
setError("");
try {
if (replace?.dispatchId && replace.dispatchId !== dispatchId) {
await api(`/api/v1/dispatches/${replace.dispatchId}/evidence/${element.id}/detach`, {
method: "POST",
body: fieldBody(scope, { expected_version: replace.version }),
});
}
let target = dispatchId;
if (!target) {
const created = await api(`/api/v1/elements/${host.element.id}/dispatches`, {
method: "POST",
body: fieldBody(scope, {
expected_version: host.element.version,
channel,
sent_on: sentOn || null,
counterpart: counterpart.trim() || null,
attachment_element_ids: [],
evidence: [{ element_id: element.id, role, fold }],
historical_gap: false,
capture_editions: false,
}),
});
const proof = (created.evidence || []).find((item) => item.element_id === element.id);
setResult(proof || created);
onDone(false);
return;
}
const dispatch = (host.correspondence?.dispatches || []).find((item) => item.id === target);
const proof = await api(`/api/v1/dispatches/${target}/evidence`, {
method: "POST",
body: fieldBody(scope, {
expected_version: dispatch?.version || 1,
element_id: element.id,
role,
fold,
}),
});
setResult(proof);
onDone(false);
} catch (err) {
setError(err.message);
}
}
return (
<form className="stack" onSubmit={save}>
<p><strong>{element.title}</strong> als Beleg zu diesem Versand. E-Mail, Notiz, Foto und Paperless-Dokument bleiben das Original. An einem Versand können mehrere Belege liegen.</p>
<label>
Hauptschriftstück
<select value={hostId} onChange={(event) => {
const next = event.target.value;
setHostId(next);
const found = hosts.find((item) => item.element.id === next);
setDispatchId(found?.correspondence?.dispatches?.[0]?.id || "");
}}>
{hosts.map((item) => <option key={item.element.id} value={item.element.id}>{item.element.title}</option>)}
</select>
</label>
<label>
Versand
<select value={dispatchId} onChange={(event) => setDispatchId(event.target.value)}>
<option value="">Neuen Versand in diesem Ablauf anlegen</option>
{(host?.correspondence?.dispatches || []).map((item) => (
<option key={item.id} value={item.id}>
{item.sent_on ? formatDate(item.sent_on) : "undatiert"} · {item.channel_label}
</option>
))}
</select>
</label>
{!dispatchId ? (
<>
<label>
Weg
<select value={channel} onChange={(event) => setChannel(event.target.value)}>
<option value="email">E-Mail</option>
<option value="post">Post</option>
<option value="other">Sonstiger Weg</option>
</select>
</label>
<label>Versanddatum<input type="date" value={sentOn} onChange={(event) => setSentOn(event.target.value)} /></label>
<label>Gegenüber<input value={counterpart} onChange={(event) => setCounterpart(event.target.value)} maxLength={200} /></label>
</>
) : null}
<label>
Rolle
<select value={role} onChange={(event) => setRole(event.target.value)}>
{RECEIPT_ROLES.map(([value, label]) => <option key={value} value={value}>{label}</option>)}
</select>
</label>
<fieldset>
<legend>Darstellung in der Liste</legend>
<label><input type="radio" name="evidence-fold" checked={fold === "evidence"} onChange={() => setFold("evidence")} /> Nur am Versand zeigen</label>
<label><input type="radio" name="evidence-fold" checked={fold === "keep"} onChange={() => setFold("keep")} /> Zusätzlich als eigenen Eintrag behalten</label>
</fieldset>
{result ? <ComparisonList comparisons={result.comparisons || []} state={result.source_state} reason={result.gap_reason} /> : null}
{error ? <p className="error">{error}</p> : null}
<button type="submit" disabled={pending || !host}>Beleg zuordnen</button>
<button type="button" className="quiet" onClick={onClose}>Schließen</button>
</form>
);
}
export function ComparisonList({ comparisons = [], state, reason }) {
if (!comparisons.length && state !== "gap") return null;
return (
<div className="comparison">
{state === "gap" ? <p>Originalfassung nicht gesichert: {reason}</p> : null}
{state === "identified" ? <p>Nachweis manuell zugeordnet. Gleiche Dateinamen werden nicht automatisch zusammengeführt.</p> : null}
<ul>
{comparisons.map((item) => (
<li key={`${item.filename}-${item.sha256}`}>
<strong>{item.filename}</strong>
{item.disposition === "same_bytes" ? ` · gleicher Dateiinhalt wie ${item.matches.map((match) => match.title).join(", ")} · Vorschlag, nicht automatisch zugeordnet` : null}
{item.disposition === "same_name_different_bytes" ? ` · gleicher Name, anderer Inhalt als ${item.matches.map((match) => match.title).join(", ")}` : null}
{item.disposition === "distinct" ? " · eigener Inhalt" : null}
</li>
))}
</ul>
</div>
);
}
function chipPointer(enabled, payload, onCarryStart) {
if (!enabled) return {};
return {
onPointerDown(event) {
onCarryStart?.(event, payload);
},
};
}
function openTitleProps(onOpen) {
return {
role: "link",
tabIndex: 0,
onClick(event) {
const row = event.currentTarget.closest(".use-chip");
if (row?.dataset.dragged === "1") {
delete row.dataset.dragged;
return;
}
onOpen();
},
onKeyDown(event) {
if (event.key !== "Enter" && event.key !== " ") return;
event.preventDefault();
onOpen();
},
};
}
export function UnitDetail({
binding,
canEdit,
pending,
onOpen,
onDetach,
onDetachEvidence,
onUnfold,
onCarryStart,
children,
}) {
const pack = binding.correspondence || {};
const attachments = pack.attachments || [];
const dispatches = pack.dispatches || [];
const [attachmentsOpen, setAttachmentsOpen] = useState(false);
const [receiptsOpen, setReceiptsOpen] = useState(false);
if (!attachments.length && !dispatches.length) {
return typeof children === "function" ? children(null, null) : null;
}
const evidenceCount = dispatches.reduce((sum, item) => sum + (item.evidence || []).length, 0);
const shipmentCount = dispatches.filter(isShipment).length;
const attachmentLabel = attachments.length === 1 ? "1 Anlage" : `${attachments.length} Anlagen`;
const receiptParts = [];
if (shipmentCount === 1) receiptParts.push("1 Versand");
else if (shipmentCount > 1) receiptParts.push(`${shipmentCount} Versände`);
if (evidenceCount === 1) receiptParts.push("1 Beleg");
else if (evidenceCount > 1) receiptParts.push(`${evidenceCount} Belege`);
const receiptLabel = receiptParts.join(" · ");
const switches = (
<span className="unit-switches">
{attachments.length ? (
<button type="button" className="unit-switch" aria-expanded={attachmentsOpen} onClick={() => setAttachmentsOpen((value) => !value)}>
{attachmentLabel}
</button>
) : null}
{dispatches.length ? (
<button type="button" className="unit-switch" aria-expanded={receiptsOpen} onClick={() => setReceiptsOpen((value) => !value)}>
{receiptLabel || "Belege"}
</button>
) : null}
</span>
);
const lists = attachmentsOpen || receiptsOpen ? (
<div className="unit-detail unit-detail--slim">
{attachmentsOpen && attachments.length ? (
<section>
<h4>Anlagen</h4>
<ol>
{attachments.map((item, index) => (
<li
key={item.id}
className="use-chip"
data-carry={`attachment:${item.element_id}`}
{...chipPointer(canEdit && !pending, {
source: "attachment",
elementId: item.element_id,
hostElementId: binding.element.id,
hostBindingId: binding.id,
bindingId: item.binding_id || "",
title: item.title,
}, onCarryStart)}
>
{canEdit ? <span className="use-chip__grip" aria-hidden="true" /> : null}
<span className="use-chip__title" {...openTitleProps(() => onOpen(item.element_id))}>
{index + 1}. {item.title}
</span>
<span className="muted">{formatDate(item.document_on)}</span>
{canEdit ? (
<button type="button" className="quiet" disabled={pending} onClick={() => onDetach(item.element_id)}>In die Liste</button>
) : null}
</li>
))}
</ol>
</section>
) : null}
{receiptsOpen ? dispatches.map((item) => (
<section key={item.id}>
<h4>{receiptHeading(item)}</h4>
{item.evidence?.length ? (
<ul>
{item.evidence.map((proof) => (
<li
key={proof.id}
className="use-chip"
data-carry={`evidence:${proof.element_id}`}
{...chipPointer(canEdit && !pending, {
source: "evidence",
elementId: proof.element_id,
dispatchId: item.id,
hostElementId: binding.element.id,
hostBindingId: binding.id,
version: item.version,
title: proof.title,
}, onCarryStart)}
>
{canEdit ? <span className="use-chip__grip" aria-hidden="true" /> : null}
<span className="use-chip__title" {...openTitleProps(() => onOpen(proof.element_id))}>
{receiptCaption(proof)}: {proof.title}
</span>
<span className="muted">{formatDate(proof.document_on)}</span>
{proof.source_state === "gap" ? <span>Lücke: {proof.gap_reason}</span> : null}
{canEdit ? (
<button type="button" className="quiet" disabled={pending} onClick={() => onDetachEvidence(proof, item)}>
In die Liste
</button>
) : null}
{canEdit && proof.listed_fold === "evidence" ? (
<button type="button" className="quiet" disabled={pending} onClick={() => onUnfold(proof.element_id)}>
Zusätzlich in der Liste zeigen
</button>
) : null}
</li>
))}
</ul>
) : <p className="muted">Ohne Beleg</p>}
</section>
)) : null}
</div>
) : null;
if (typeof children === "function") return children(switches, lists);
return (
<div className="unit-fold">
{switches}
{lists}
</div>
);
}
export function Chronology({ bindings, direction, itemHref, selectedId, onOpen }) {
const events = [];
for (const binding of bindings || []) {
if (binding.correspondence?.fold !== "evidence") {
events.push({
key: `doc-${binding.id}`,
date: binding.element?.dates?.document_on || "",
label: "Unterlage",
title: binding.element?.title || "",
detail: `Dokumentdatum ${formatDate(binding.element?.dates?.document_on)}`,
binding,
});
}
for (const dispatch of binding.correspondence?.dispatches || []) {
events.push({
key: `send-${dispatch.id}`,
date: dispatch.sent_on || "",
label: isShipment(dispatch) ? "Versand" : "Beleg",
title: binding.element?.title || "",
detail: [
dispatch.undated ? "Versand undatiert" : `Versanddatum ${formatDate(dispatch.sent_on)}`,
dispatch.channel_label,
(dispatch.evidence || []).length === 1
? "1 Beleg"
: (dispatch.evidence || []).length
? `${dispatch.evidence.length} Belege`
: "ohne Beleg",
].join(" · "),
binding,
dispatch,
});
}
}
events.sort((left, right) => {
if (!left.date && !right.date) return left.key.localeCompare(right.key);
if (!left.date) return 1;
if (!right.date) return -1;
const compared = left.date.localeCompare(right.date);
if (compared) return direction === "desc" ? -compared : compared;
return left.key.localeCompare(right.key);
});
const undated = events.filter((item) => !item.date);
const dated = events.filter((item) => item.date);
const ordered = direction === "desc" ? [...undated, ...dated] : [...dated, ...undated];
const groups = [];
for (const event of ordered) {
const name = event.date ? formatDate(event.date) : "Ohne Datum";
const last = groups[groups.length - 1];
if (!last || last.name !== name) groups.push({ name, events: [event] });
else last.events.push(event);
}
if (!groups.length) return <p className="muted">In dieser Ansicht ist noch nichts zu sehen.</p>;
return (
<div className="chrono">
{groups.map((group) => (
<section key={group.name}>
<h3>{group.name}</h3>
<ol className="preview-list">
{group.events.map((event) => (
<li key={event.key} className={selectedId === event.binding.id ? "preview-row is-selected" : "preview-row"}>
<div className="preview-row__body">
<Link to={itemHref(event.binding)} onClick={(click) => {
if (click.metaKey || click.ctrlKey || click.shiftKey || click.altKey || click.button !== 0) return;
click.preventDefault();
onOpen(event.binding);
}}>
<strong>{event.label}: {event.title}</strong>
</Link>
<span className="preview-row__facts">{event.detail}</span>
</div>
</li>
))}
</ol>
</section>
))}
</div>
);
}
export async function restoreFold(bindingId, version, scope) {
await api(`/api/v1/bindings/${bindingId}/fold`, {
method: "PATCH",
body: fieldBody(scope, { expected_version: version, fold: null }),
});
}