Warne vor bereits eingefügten Quelldokumenten und biete Nicht einfügen, erneut einfügen oder zusätzliches Einbinden an.
Deploy Development / deploy (push) Successful in 44s

Prüfstufen hier, darin, Umfeld stehen als Kontoeinstellung bereit. Der Server antwortet bei einem sicheren Treffer mit 409 und bindet auf Wunsch das vorhandene Element zusätzlich ein.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
StommerandClaude Sonnet 5.5 committed 2026-10-25 10:06:52 +01:00
1 parent a6dc24d8fe
commit f925661937
19 files changed
+748 -133

No files matched your search

+3 -3
View File
@@ -6,9 +6,9 @@ const PATH = "/api/v1/auth/preferences/duplicate_check";
export const DUPLICATE_LEVELS = {
off: "Keine Prüfung",
case: "Nur dieser Vorgang",
case_matters: "Vorgang und verknüpfte Akten",
case_tree: "Vorgang mit Ober- und Unterordnung",
here: "Nur hier (direkt in diesem Vorgang oder dieser Akte)",
inside: "Hier und was darin angezeigt wird (Teilvorgänge, zugeordnete Vorgänge)",
around: "Zusätzlich dort, wo es liegt (übergeordneter Vorgang, zugeordnete Akten)",
};
// Where a document that is inserted again counts as already present. Only a warning, never a block.
+22 -17
View File
@@ -15,6 +15,7 @@ import { Workspace, rememberScroll, restoreScroll, useWorkspaceLayout } from "./
import { useLibraryFocus } from "../library/LibraryLayout.jsx";
import { outlineSignature } from "../library/library-core.js";
import { NavIcon } from "./icons.jsx";
import { useExternalPlacement } from "../sources/duplicates.jsx";
function matterOrigin(group) {
const kind = group.kind_label === "Teilvorgang" ? "Teilvorgang" : "Vorgang";
@@ -905,6 +906,15 @@ function ExternalForm({ context, placement, chapters = [], initialChapter = "",
const [sentOn, setSentOn] = useState("");
const [receivedOn, setReceivedOn] = useState("");
const [error, setError] = useState("");
const { place, panel } = useExternalPlacement({
context,
placement,
onPlaced: () => {
setTitle("");
setExternalId("");
onChange();
},
});
useEffect(() => { setChapterId(initialChapter || ""); }, [initialChapter]);
@@ -912,25 +922,19 @@ function ExternalForm({ context, placement, chapters = [], initialChapter = "",
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,
},
await place({
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);
}
@@ -951,6 +955,7 @@ function ExternalForm({ context, placement, chapters = [], initialChapter = "",
{chapterSelect(chapters, chapterId, setChapterId)}
<button type="submit">Referenz erfassen</button>
<ErrorNote error={error} />
{panel}
</form>
);
}
+132 -49
View File
@@ -5,6 +5,7 @@ import { api, fetchBlob } from "../api.js";
import { MailBody } from "../mail-view.jsx";
import { NewConnector, useSourceModules } from "../sources/connector-config.jsx";
import { SourceFrame, registerSourceModule } from "../sources/registry.jsx";
import { PresentNote, bindable, describeMatch, lookupPresent, presentKey, useExternalPlacement } from "../sources/duplicates.jsx";
const SEARCH_LIMITS = {
paperless: "Die Suche läuft in Paperless selbst, über Titel und Inhalt, den Titel allein, den Inhalt allein oder den Volltextindex. Filter nach Korrespondent, Dokumenttyp, Speicherpfad, Tags, Dokumentdatum, Hinzugefügt-Datum und Archivnummer grenzen sie ein.",
@@ -303,6 +304,9 @@ export function PaperlessPicker({ context, placement, chapterId = "", chapterTit
const [total, setTotal] = useState(null);
const [searched, setSearched] = useState(false);
const [picked, setPicked] = useState(() => new Map());
// Documents that are already present around the target, by presentKey. `review` holds the choices while the user decides.
const [present, setPresent] = useState(() => new Map());
const [review, setReview] = useState(null);
const [previewKey, setPreviewKey] = useState("");
const [previewUrl, setPreviewUrl] = useState("");
const [pending, setPending] = useState(false);
@@ -417,12 +421,33 @@ export function PaperlessPicker({ context, placement, chapterId = "", chapterTit
setTotal(typeof data.total === "number" ? data.total : null);
setSearched(true);
if (!asked && data.connector_id) setConnectorId(data.connector_id);
refreshPresent(data.items || [], asked || data.connector_id || "");
} catch (err) {
if (token !== searchRef.current) return;
setError(err.message);
}
}
function presentEntry(item, bound = connectorId) {
return { source: "paperless", external_id: String(item.id), connector_id: item.connector_id || bound };
}
function matchesOf(item) {
const entry = presentEntry(item);
return present.get(presentKey(entry.source, entry.connector_id, entry.external_id)) || [];
}
async function refreshPresent(list, bound) {
const entries = list.map((item) => presentEntry(item, bound));
const found = await lookupPresent(context, placement, entries);
setPresent((current) => {
const next = new Map(current);
entries.forEach((entry) => next.delete(presentKey(entry.source, entry.connector_id, entry.external_id)));
found.forEach((value, key) => next.set(key, value));
return next;
});
}
function resetFilters() {
invalidate();
closePreview();
@@ -469,52 +494,82 @@ export function PaperlessPicker({ context, placement, chapterId = "", chapterTit
}
}
async function linkMany() {
async function linkMany(choices = null) {
const chosen = [...picked.values()];
if (!chosen.length) return;
setError("");
const keyOf = (item) => `${item.connector_id || connectorId}:${item.id}`;
if (!choices) {
const known = chosen.filter((item) => matchesOf(item).length);
if (known.length) {
setReview(new Map(known.map((item) => [keyOf(item), "skip"])));
return;
}
}
setReview(null);
setPending(true);
const inserted = [];
const skipped = [];
const conflicts = [];
try {
for (const item of chosen) {
await api("/api/v1/external-refs", {
method: "POST",
body: {
title: item.title,
source: "paperless",
external_id: String(item.id),
context,
...(placement ? { placement } : {}),
...(chapterId ? { chapter_id: chapterId } : {}),
...(item.document_on || item.correspondent || item.open_url || connectorId
? {
dates: { document_on: item.document_on || null, sent_on: null, received_on: null },
detail: {
...(item.connector_id || connectorId ? { connector_id: item.connector_id || connectorId } : {}),
...(item.correspondent ? { correspondent: item.correspondent } : {}),
...(item.open_url ? { open_url: item.open_url } : {}),
},
}
: {}),
},
});
inserted.push(`${item.connector_id || connectorId}:${item.id}`);
const key = keyOf(item);
const choice = choices?.get(key);
if (choice === "skip") {
skipped.push(key);
continue;
}
const existing = choice === "bind" ? bindable(matchesOf(item)) : null;
try {
await api("/api/v1/external-refs", {
method: "POST",
body: {
title: item.title,
source: "paperless",
external_id: String(item.id),
context,
...(placement ? { placement } : {}),
...(chapterId ? { chapter_id: chapterId } : {}),
...(choice === "insert" ? { duplicate: "insert" } : {}),
...(existing ? { bind_element_id: existing.element_id } : {}),
...(item.document_on || item.correspondent || item.open_url || connectorId
? {
dates: { document_on: item.document_on || null, sent_on: null, received_on: null },
detail: {
...(item.connector_id || connectorId ? { connector_id: item.connector_id || connectorId } : {}),
...(item.correspondent ? { correspondent: item.correspondent } : {}),
...(item.open_url ? { open_url: item.open_url } : {}),
},
}
: {}),
},
});
inserted.push(key);
} catch (err) {
// Inserted by someone else in the meantime: ask again instead of failing.
if (err.code !== "already_present") throw err;
conflicts.push(item);
}
}
} catch (err) {
setError(err.message);
} finally {
setPending(false);
}
if (conflicts.length) {
await refreshPresent(conflicts, connectorId);
setReview(new Map(conflicts.map((item) => [keyOf(item), "skip"])));
}
if (inserted.length) {
setItems((current) => current.filter((item) => !inserted.includes(`${connectorId}:${item.id}`)));
setPicked((current) => {
const next = new Map(current);
inserted.forEach((id) => next.delete(id));
return next;
});
onInserted?.();
}
if (inserted.length === chosen.length) onDone();
setPicked((current) => {
const next = new Map(current);
[...inserted, ...skipped].forEach((id) => next.delete(id));
return next;
});
if (inserted.length && inserted.length + skipped.length === chosen.length) onDone();
}
function setFilter(name, value) {
@@ -706,8 +761,37 @@ export function PaperlessPicker({ context, placement, chapterId = "", chapterTit
<ErrorNote error={error} />
<p className="muted">{SEARCH_LIMITS.paperless}</p>
<p className="muted">Die Verbindung richtest du unter <Link to="/sources">Quellen</Link> ein. Ausgewählte Belege bleiben erhalten, wenn du weiterblätterst oder neu suchst.</p>
{review ? (
<div className="card stack duplicate-panel" role="alert">
<strong>Diese Belege sind schon vorhanden. Was soll geschehen?</strong>
<ul className="duplicate-list">
{[...picked.values()].filter((item) => review.has(`${item.connector_id || connectorId}:${item.id}`)).map((item) => {
const key = `${item.connector_id || connectorId}:${item.id}`;
const matches = matchesOf(item);
return (
<li key={key}>
<span>{item.title}: {matches.length ? describeMatch(matches[0]) : "schon vorhanden"}</span>
<select
value={review.get(key)}
aria-label={`Entscheidung für ${item.title}`}
onChange={(event) => setReview((current) => new Map(current).set(key, event.target.value))}
>
<option value="skip">Nicht einfügen</option>
<option value="insert">Trotzdem erneut einfügen</option>
{bindable(matches) ? <option value="bind">Vorhandenes zusätzlich einbinden</option> : null}
</select>
</li>
);
})}
</ul>
<div className="row">
<button type="button" className="quiet" disabled={pending} onClick={() => setReview(null)}>Zurück zur Auswahl</button>
<button type="button" disabled={pending} onClick={() => linkMany(review)}>Entscheidung ausführen</button>
</div>
</div>
) : null}
{items.length || picked.size ? (
<button type="button" disabled={pending || picked.size === 0} onClick={linkMany}>
<button type="button" disabled={pending || picked.size === 0 || Boolean(review)} onClick={() => linkMany()}>
{picked.size ? `${picked.size} Belege einfügen` : "Belege auswählen"}
</button>
) : null}
@@ -745,6 +829,7 @@ export function PaperlessPicker({ context, placement, chapterId = "", chapterTit
</button>
<div className="paperless-card__body">
<strong>{item.title}</strong>
<PresentNote matches={matchesOf(item)} />
{facts.length ? <span className="paperless-card__facts">{facts.join(" · ")}</span> : null}
{item.tags?.length ? (
<ul className="paperless-card__tags" aria-label="Tags">
@@ -901,6 +986,7 @@ export function MailPicker({ context, placement, chapterId = "", chapterTitle =
const [preview, setPreview] = useState(null);
const [previewError, setPreviewError] = useState("");
const [adopting, setAdopting] = useState(false);
const { place, panel } = useExternalPlacement({ context, placement, onPlaced: () => onDone() });
const [loading, setLoading] = useState("");
const [error, setError] = useState("");
const requestRef = useRef(0);
@@ -1083,26 +1169,22 @@ export function MailPicker({ context, placement, chapterId = "", chapterTitle =
if (cc) detail.message_cc = cc;
if (attachments.length) detail.attachments = attachments;
try {
await api("/api/v1/external-refs", {
method: "POST",
body: {
title: item.title,
source: "imap",
external_id: item.id,
context,
...(placement ? { placement } : {}),
...(chapterId ? { chapter_id: chapterId } : {}),
...(item.document_on ? {
dates: {
document_on: item.document_on,
sent_on: direction === "out" ? item.document_on : null,
received_on: direction === "in" ? item.document_on : null,
},
} : {}),
detail,
},
await place({
title: item.title,
source: "imap",
external_id: item.id,
context,
...(placement ? { placement } : {}),
...(chapterId ? { chapter_id: chapterId } : {}),
...(item.document_on ? {
dates: {
document_on: item.document_on,
sent_on: direction === "out" ? item.document_on : null,
received_on: direction === "in" ? item.document_on : null,
},
} : {}),
detail,
});
onDone();
} catch (err) {
setError(err.message);
} finally {
@@ -1183,6 +1265,7 @@ export function MailPicker({ context, placement, chapterId = "", chapterTitle =
{selected && !preview && !previewError ? <p className="muted">Vorschau wird geladen …</p> : null}
{preview ? <MailBody html={preview.html} text={preview.text} truncated={preview.text_truncated} notices={preview.notices} /> : null}
<ErrorNote error={error} />
{panel}
<button type="button" onClick={() => link(selected)} disabled={!selected.uid || adopting}>{adopting ? "Wird übernommen …" : "Übernehmen"}</button>
</>
)}
+122
View File
@@ -0,0 +1,122 @@
import { useState } from "react";
import { api } from "../api.js";
import { ErrorNote } from "../pages/widgets.jsx";
// A document that is already present around the target. The server decides; this only asks and explains.
export function presentKey(source, connectorId, externalId) {
return `${source}:${connectorId || ""}:${externalId}`;
}
export function describeMatch(match) {
const title = match.container?.title;
const maybe = match.certain ? "" : "möglicherweise ";
if (match.where === "here") return `${maybe}schon hier${match.chapter ? ` (Kapitel „${match.chapter}“)` : ""}`;
if (match.where === "inside") return `${maybe}schon ${title ? `in „${title}“` : "in einem zugehörigen Teil"}`;
const kind = match.container?.kind === "case" ? "in der Akte" : "im Vorgang";
return `${maybe}schon ${kind}${title ? ` „${title}“` : ""}`;
}
export function bindable(matches) {
return (matches || []).find((item) => item.certain && item.can_bind && item.where !== "here") || null;
}
// entries: [{ source, external_id, connector_id }]. Answers a Map of presentKey -> matches, only for documents that are present.
// A failed lookup answers nothing: the warning is a help, the server still protects on insert.
export async function lookupPresent(context, placement, entries) {
const found = new Map();
if (!entries.length) return found;
try {
const data = await api("/api/v1/external-refs/existing", {
method: "POST",
body: {
context,
...(placement ? { placement } : {}),
items: entries.map((item) => ({ source: item.source, external_id: item.external_id, ...(item.connector_id ? { connector_id: item.connector_id } : {}) })),
},
});
for (const entry of data.items || []) {
if (entry.matches?.length) found.set(presentKey(entry.source, entry.connector_id, entry.external_id), entry.matches);
}
} catch {
return found;
}
return found;
}
export function PresentNote({ matches }) {
if (!matches?.length) return null;
return <p className="duplicate-note" role="status">Schon vorhanden: {matches.map(describeMatch).join(", ")}.</p>;
}
// Choices when a document is already present: do not insert, insert again, or bind the existing element as well.
export function DuplicatePanel({ matches, busy, onCancel, onInsert, onBind }) {
const existing = bindable(matches);
return (
<div className="card stack duplicate-panel" role="alert">
<strong>Dieses Dokument ist schon vorhanden.</strong>
<ul>
{matches.map((item) => <li key={item.element_id}>{item.title}: {describeMatch(item)}</li>)}
</ul>
<div className="row">
<button type="button" className="quiet" disabled={busy} onClick={onCancel}>Nicht einfügen</button>
<button type="button" className="quiet" disabled={busy} onClick={onInsert}>Trotzdem erneut einfügen</button>
{existing ? <button type="button" disabled={busy} onClick={() => onBind(existing.element_id)}>Vorhandenes zusätzlich einbinden</button> : null}
</div>
</div>
);
}
// One document at a time. `place(body)` posts it. If the server finds it already present, `panel` offers the choices
// and `onPlaced` runs once the document is in, whichever way.
export function useExternalPlacement({ context, placement, onPlaced }) {
const [conflict, setConflict] = useState(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState("");
async function send(body) {
await api("/api/v1/external-refs", { method: "POST", body });
setConflict(null);
await onPlaced?.();
}
async function place(body) {
setError("");
try {
await send(body);
} catch (err) {
if (err.code !== "already_present") throw err;
const entry = { source: body.source, external_id: body.external_id, connector_id: body.detail?.connector_id };
const found = await lookupPresent(context, placement, [entry]);
const matches = found.get(presentKey(entry.source, entry.connector_id, entry.external_id)) || [];
if (!matches.length) throw err;
setConflict({ body, matches });
}
}
async function resolve(extra) {
if (!conflict) return;
setBusy(true);
setError("");
try {
await send({ ...conflict.body, ...extra });
} catch (err) {
setError(err.message);
} finally {
setBusy(false);
}
}
const panel = conflict ? (
<>
<DuplicatePanel
matches={conflict.matches}
busy={busy}
onCancel={() => setConflict(null)}
onInsert={() => resolve({ duplicate: "insert" })}
onBind={(elementId) => resolve({ bind_element_id: elementId })}
/>
<ErrorNote error={error} />
</>
) : null;
return { place, panel };
}
+11 -13
View File
@@ -2,6 +2,7 @@ import { useEffect, useRef, useState } from "react";
import { api } from "../api.js";
import { TargetLine } from "../pages/content.jsx";
import { ErrorNote } from "../pages/widgets.jsx";
import { useExternalPlacement } from "./duplicates.jsx";
import { defineSourceModules, moduleFor, registerSourceModule, sourceModules, unregisterSourceModule } from "./registry-core.js";
export { defineSourceModules, moduleFor, registerSourceModule, sourceModules, unregisterSourceModule };
@@ -71,6 +72,7 @@ export function StandardSourcePicker({ sourceKind, context, placement, chapterId
const [error, setError] = useState("");
const [pending, setPending] = useState(false);
const searchRef = useRef(0);
const { place, panel } = useExternalPlacement({ context, placement, onPlaced: () => { onInserted?.(); onDone?.(); } });
const hint = module?.searchHint || "Suche im heute unterstützten Umfang dieser Quelle.";
useEffect(() => {
@@ -111,20 +113,15 @@ export function StandardSourcePicker({ sourceKind, context, placement, chapterId
setPending(true);
setError("");
try {
await api("/api/v1/external-refs", {
method: "POST",
body: {
title: item.title,
source: sourceKind,
external_id: String(item.id),
context,
...(placement ? { placement } : {}),
...(chapterId ? { chapter_id: chapterId } : {}),
...(connectorId ? { detail: { connector_id: connectorId } } : {}),
},
await place({
title: item.title,
source: sourceKind,
external_id: String(item.id),
context,
...(placement ? { placement } : {}),
...(chapterId ? { chapter_id: chapterId } : {}),
...(connectorId ? { detail: { connector_id: connectorId } } : {}),
});
onInserted?.();
onDone?.();
} catch (err) {
setError(err.message);
} finally {
@@ -149,6 +146,7 @@ export function StandardSourcePicker({ sourceKind, context, placement, chapterId
<button type="submit">Suchen</button>
</form>
<ErrorNote error={error} />
{panel}
<p className="muted">{hint}</p>
<div className="stack">
{items.map((item) => (
+14
View File
@@ -1837,3 +1837,17 @@ button.pick-tree__twist {
.mini-icon--link { color: var(--kind-room); }
.structure__links { margin-top: 12px; padding-top: 8px; border-top: 1px solid var(--border); }
.structure__links h3 { font-size: 11px; letter-spacing: 0.06em; text-transform: uppercase; color: var(--text2); margin: 0 8px 4px; }
.duplicate-note { margin: 0; color: var(--text); font-size: 13px; font-weight: 600; }
.duplicate-panel { border: 1px solid var(--border); background: var(--surface2); }
.duplicate-panel ul { margin: 0; padding-left: 18px; }
.duplicate-list { list-style: none; padding-left: 0 !important; display: grid; gap: 8px; }
.duplicate-list li { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; justify-content: space-between; }
.duplicate-list select { max-width: 100%; }
.duplicate-note { margin: 0; color: var(--text); font-size: 13px; font-weight: 600; }
.duplicate-panel { border: 1px solid var(--border); background: var(--surface2); }
.duplicate-panel ul { margin: 0; padding-left: 18px; }
.duplicate-list { list-style: none; padding-left: 0 !important; display: grid; gap: 8px; }
.duplicate-list li { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; justify-content: space-between; }
.duplicate-list select { max-width: 100