import { useEffect, useMemo, useRef, useState } from "react"; import { Link } from "react-router-dom"; import { api } from "../api.js"; import { moduleFor } from "../sources/registry-core.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" && moduleFor(proof.source)?.representation !== "email") 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 ( ); } 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 (
  • ); } 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 (
  • {expanded ? ( ) : null}
  • ); } 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 (

    Zuordnen an {host.element.title}

    {step === "pick" ? ( <>
    {selected.size} ausgewählt {needle ? : null}
    ) : (

    {selected.size} Belege. Dieselbe Rolle gilt für die Auswahl.

    {!dispatchId ? ( <> ) : null}
    Darstellung in der Liste
    )} {error ?

    {error}

    : null}
    ); } 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 (

    Versand von {host.element.title} dokumentieren. Dabei wird nichts verschickt. Die Anlagenliste ist ein Vorschlag für diesen Versand.

    Leer lassen, wenn der Versandtag unbekannt ist. Der Erfassungszeitpunkt ersetzt ihn nicht.

    Leer lassen, wenn das Gegenüber unbekannt ist.

    Tatsächlich mitversendet
      {order.map((id, index) => { const item = proposal.find((entry) => entry.element_id === id); if (!item) return null; return (
    1. ); })}
    {!proposal.length ?

    Keine zugeordnete Anlage. Das Schreiben kann allein dokumentiert werden.

    : null}
    {error ?

    {error}

    : null}
    ); } 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 (

    {element.title} als Beleg zu diesem Versand. E-Mail, Notiz, Foto und Paperless-Dokument bleiben das Original. An einem Versand können mehrere Belege liegen.

    {!dispatchId ? ( <> ) : null}
    Darstellung in der Liste
    {result ? : null} {error ?

    {error}

    : null} ); } export function ComparisonList({ comparisons = [], state, reason }) { if (!comparisons.length && state !== "gap") return null; return (
    {state === "gap" ?

    Originalfassung nicht gesichert: {reason}

    : null} {state === "identified" ?

    Nachweis manuell zugeordnet. Gleiche Dateinamen werden nicht automatisch zusammengeführt.

    : null}
      {comparisons.map((item) => (
    • {item.filename} {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}
    • ))}
    ); } 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 = ( {attachments.length ? ( ) : null} {dispatches.length ? ( ) : null} ); const lists = attachmentsOpen || receiptsOpen ? (
    {attachmentsOpen && attachments.length ? (

    Anlagen

      {attachments.map((item, index) => (
    1. {canEdit ?
    2. ))}
    ) : null} {receiptsOpen ? dispatches.map((item) => (

    {receiptHeading(item)}

    {item.evidence?.length ? (
      {item.evidence.map((proof) => (
    • {canEdit ?
    • ))}
    ) :

    Ohne Beleg

    }
    )) : null}
    ) : null; if (typeof children === "function") return children(switches, lists); return (
    {switches} {lists}
    ); } 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

    In dieser Ansicht ist noch nichts zu sehen.

    ; return (
    {groups.map((group) => (

    {group.name}

      {group.events.map((event) => (
    1. { if (click.metaKey || click.ctrlKey || click.shiftKey || click.altKey || click.button !== 0) return; click.preventDefault(); onOpen(event.binding); }}> {event.label}: {event.title} {event.detail}
    2. ))}
    ))}
    ); } export async function restoreFold(bindingId, version, scope) { await api(`/api/v1/bindings/${bindingId}/fold`, { method: "PATCH", body: fieldBody(scope, { expected_version: version, fold: null }), }); }