From 1885bfc521d5edd60567d79cf72d16d261d5d164 Mon Sep 17 00:00:00 2001 From: flfeders Date: Fri, 2 Oct 2026 17:12:05 +0200 Subject: [PATCH] feat(documents): allow archiving inbox documents --- backend/src/modules/scanner-inbox.service.ts | 25 +++++- backend/src/routes/documentInbox.ts | 3 + backend/tests/scannerInbox.test.ts | 55 ++++++++++++ docs/scanner-dokumentenablage.md | 9 +- .../pages/organisation/dokumentenablage.vue | 86 ++++++++++++++++--- frontend/tests/document-inbox.test.cjs | 78 +++++++++++++++++ 6 files changed, 243 insertions(+), 13 deletions(-) diff --git a/backend/src/modules/scanner-inbox.service.ts b/backend/src/modules/scanner-inbox.service.ts index b119812c..4e62c423 100644 --- a/backend/src/modules/scanner-inbox.service.ts +++ b/backend/src/modules/scanner-inbox.service.ts @@ -184,6 +184,29 @@ export function createScannerInboxService(db: FastifyInstance["db"], storage: Sc if (!file) throw scannerError(404, "Dokument nicht gefunden.") return currentAssignments(db, tenantId, file) } + const archiveDocument = async (tenantId: number, userId: string, fileId: string) => db.transaction(async tx => { + const [tenant] = await tx.select({ locked: tenants.locked }).from(tenants) + .where(eq(tenants.id, tenantId)).for("share") + if (!tenant) throw scannerError(404, "Mandant nicht gefunden.") + if (tenant.locked === "maintenance_tenant") throw scannerError(423, "Der Mandant wird gerade gewartet.") + // Use the same lock order as filing so both actions cannot succeed concurrently. + const [entry] = await tx.select({ filedAt: scannerInboxDocuments.filedAt }).from(scannerInboxDocuments) + .where(and(eq(scannerInboxDocuments.tenantId, tenantId), eq(scannerInboxDocuments.fileId, fileId))).for("update") + if (!entry) throw scannerError(404, "Dokument nicht in der Ablage gefunden.") + if (entry.filedAt) throw scannerError(409, "Dieses Dokument wurde bereits abgelegt. Bitte den Eingang aktualisieren.") + const [file] = await tx.select({ archived: files.archived }).from(files) + .where(and(eq(files.id, fileId), eq(files.tenant, tenantId))).for("update") + if (!file) throw scannerError(404, "Dokument nicht gefunden.") + if (!file.archived) { + await tx.update(files).set({ archived: true, updatedAt: new Date(), updatedBy: userId }) + .where(and(eq(files.id, fileId), eq(files.tenant, tenantId))) + } + // Keep the receipt for scanner retries; invalidate any analysis already in flight. + await tx.update(scannerInboxDocuments).set({ suggestionClaim: null, + suggestionStatus: sql`CASE WHEN ${scannerInboxDocuments.suggestionStatus} = 'processing' THEN 'pending' ELSE ${scannerInboxDocuments.suggestionStatus} END` }) + .where(and(eq(scannerInboxDocuments.fileId, fileId), eq(scannerInboxDocuments.tenantId, tenantId))) + return { id: fileId, archived: true } + }) const fileDocument = async (tenantId: number, userId: string, fileId: string, folderId: string | null, typeId: string, assignments: FileAssignments = {}) => db.transaction(async tx => { const [tenant] = await tx.select({ locked: tenants.locked }).from(tenants) .where(eq(tenants.id, tenantId)).for("share") @@ -277,7 +300,7 @@ export function createScannerInboxService(db: FastifyInstance["db"], storage: Sc } } return { connection, credentials, disable, authenticate, find, list, openCount, filingOptions, getSuggestion, queueSuggestion, processNextSuggestion, - getAssignments, assignmentOptions: (tenantId: number, kind: string, search: string) => assignmentOptions(db, tenantId, kind, search), fileDocument, probe, accept } + getAssignments, assignmentOptions: (tenantId: number, kind: string, search: string) => assignmentOptions(db, tenantId, kind, search), archiveDocument, fileDocument, probe, accept } } export type ScannerInboxService = ReturnType diff --git a/backend/src/routes/documentInbox.ts b/backend/src/routes/documentInbox.ts index f2fcfd08..5a896310 100644 --- a/backend/src/routes/documentInbox.ts +++ b/backend/src/routes/documentInbox.ts @@ -41,6 +41,9 @@ export default async function documentInboxRoutes(server: FastifyInstance, optio server.post<{ Params: { id: string } }>("/document-inbox/:id/suggestion", { schema: { params: { type: "object", required: ["id"], properties: { id: { type: "string", format: "uuid" } } } }, }, async (req, reply) => reply.code(202).send(await service.queueSuggestion(req.user.tenant_id!, req.params.id))) + server.post<{ Params: { id: string } }>("/document-inbox/:id/archive", { + schema: { params: { type: "object", required: ["id"], properties: { id: { type: "string", format: "uuid" } } } }, + }, async req => service.archiveDocument(req.user.tenant_id!, req.user.user_id, req.params.id)) server.post<{ Params: { id: string }; Body: { folder: string | null; type: string; assignments?: FileAssignments } }>("/document-inbox/:id/file", { schema: { params: { type: "object", required: ["id"], properties: { id: { type: "string", format: "uuid" } } }, diff --git a/backend/tests/scannerInbox.test.ts b/backend/tests/scannerInbox.test.ts index f89475bd..0e88c4b4 100644 --- a/backend/tests/scannerInbox.test.ts +++ b/backend/tests/scannerInbox.test.ts @@ -527,6 +527,61 @@ test("scanner inbox integration: migration, persistence, isolation, retries and assert.equal((await fileInto(id)).statusCode, 404) await pool.query("UPDATE files SET archived=false WHERE id=$1", [id]) }) + await t.test("archiving is tenant scoped, preserves the original and invalidates an ongoing analysis", async () => { + assert.equal((await send("archive.pdf")).statusCode, 201) + const id = (await service.list(1, 50, 0, "archive.pdf")).documents[0].id + const archive = (fileId = id, headers = {}) => app.inject({ method: "POST", url: `/api/document-inbox/${fileId}/archive`, headers }) + assert.equal((await archive(id, { "x-test-tenant": "2" })).statusCode, 404) + assert.equal((await archive(randomUUID())).statusCode, 404) + assert.equal((await archive("invalid")).statusCode, 400) + const filedId = (await pool.query("SELECT file_id FROM scanner_inbox_documents WHERE tenant_id=1 AND remote_filename='scan.pdf'")).rows[0].file_id + assert.equal((await archive(filedId)).statusCode, 409) + await pool.query("UPDATE tenants SET locked='maintenance_tenant' WHERE id=1") + assert.equal((await archive()).statusCode, 423) + await pool.query("UPDATE tenants SET locked=null WHERE id=1") + await pool.query("INSERT INTO auth_profiles (tenant_id, user_id, customer_for_portal) VALUES (1, $1, 123)", [userId]) + assert.equal((await archive()).statusCode, 403) + await pool.query("DELETE FROM auth_profiles") + const before = (await pool.query("SELECT * FROM files WHERE id=$1", [id])).rows[0] + const countBefore = (await service.openCount(1)).total + const storedBefore = stored.size + // Run this document first, then archive it while its provider response is still pending. + await pool.query("UPDATE scanner_inbox_documents SET received_at=now()-interval '1 day' WHERE file_id=$1", [id]) + let finish!: () => void + analysisGate = new Promise(resolve => { finish = resolve }) + const started = new Promise(resolve => { analysisStarted = resolve }) + const pending = service.processNextSuggestion() + await started + assert.equal(analyses.at(-1).document.name, "archive.pdf") + const result = await archive(id, { "x-test-admin": "false" }) + finish() + await pending + analysisGate = undefined + analysisStarted = undefined + assert.equal(result.statusCode, 200, result.body) + assert.deepEqual(result.json(), { id, archived: true }) + const row = (await pool.query("SELECT * FROM files WHERE id=$1", [id])).rows[0] + assert.equal(row.archived, true) + assert.equal(row.updated_by, userId) + assert.ok(row.updated_at) + assert.equal(row.path, before.path) + assert.equal(row.folder, before.folder) + assert.equal(row.type, before.type) + assert.deepEqual(stored.get(row.path), pdf) + const receipt = (await pool.query("SELECT filed_at, suggestion_claim, suggestion_status FROM scanner_inbox_documents WHERE file_id=$1", [id])).rows[0] + assert.deepEqual(receipt, { filed_at: null, suggestion_claim: null, suggestion_status: "pending" }) + assert.equal((await service.list(1, 50, 0, "archive.pdf")).total, 0) + assert.equal((await service.openCount(1)).total, countBefore - 1) + assert.equal((await suggest(id)).statusCode, 404) + assert.equal((await fileInto(id)).statusCode, 404) + assert.equal((await archive()).statusCode, 200, "repeated requests remain successful") + assert.equal((await pool.query("SELECT updated_at FROM files WHERE id=$1", [id])).rows[0].updated_at.getTime(), row.updated_at.getTime()) + assert.equal((await send("archive.pdf")).statusCode, 204) + assert.equal((await service.list(1, 50, 0, "archive.pdf")).total, 0) + assert.equal(stored.size, storedBefore) + while (await service.processNextSuggestion()) { /* drain the remaining fixtures */ } + assert.equal(analyses.filter(item => item.document.name === "archive.pdf").length, 1) + }) await t.test("maintenance, portal access and administrator-only settings are enforced", async () => { await pool.query("UPDATE tenants SET locked='maintenance_tenant' WHERE id=1") assert.equal((await send("maintenance.pdf")).statusCode, 423) diff --git a/docs/scanner-dokumentenablage.md b/docs/scanner-dokumentenablage.md index fc26839f..cdf34a5e 100644 --- a/docs/scanner-dokumentenablage.md +++ b/docs/scanner-dokumentenablage.md @@ -12,7 +12,13 @@ Unter **Organisation → Dokumentenablage** erscheinen noch nicht abgelegte Scan Nur aktive Ordner, Typen und Zuordnungsziele desselben Mandanten sind zulässig. Mitarbeiter müssen aktiv und interne Benutzer sein. Bei einem Fehler bleibt das Dokument im Eingang; auch die übrigen Änderungen werden nicht teilweise gespeichert. Ein erneuter Scanner-Upload mit demselben Namen und Inhalt bestätigt weiterhin den ursprünglichen Empfang, ohne einen neuen Eingangseintrag oder Analyseauftrag anzulegen. -### KI-Vorschläge +## Archivieren + +**Archivieren** steht sowohl in jeder Listenzeile als auch im Vorschaufenster zur Verfügung. Nach Bestätigung wird die bestehende Datei als archiviert markiert, ohne sie zu löschen. Ordner und Dokumenttyp müssen dafür nicht ausgewählt sein; ungespeicherte Zuordnungen aus der Vorschau werden nicht übernommen. Das Dokument verschwindet aus der Ablage und der Menüzähler wird sofort aktualisiert. Bei einem Fehler bleibt es sichtbar und der Vorgang kann erneut versucht werden. + +Das Original und sein Empfangseintrag bleiben erhalten. Eine identische Wiederholung durch den Scanner aktiviert die Datei nicht erneut. Wartende KI-Aufträge werden für archivierte Dateien übersprungen und Ergebnisse bereits laufender Analysen verworfen. Die Änderung hält Zeitpunkt und Benutzer fest. Bereits unter Dateien abgelegte Dokumente können nicht mehr über die Ablage archiviert werden. + +## KI-Vorschläge Die Analyse nutzt die bestehende zentrale FEDEO-KI-Anbindung oder den konfigurierten `OPENAI_API_KEY`, entsprechend den E-Mail-Zuordnungsvorschlägen. Die Antwort verwendet [Structured Outputs](https://developers.openai.com/api/docs/guides/structured-outputs) und `store: false`. Dokumentinhalt, Dateiname und Kandidatennamen gelten als Daten, nicht als Anweisungen. Das Backend prüft vorgeschlagene IDs und verpflichtende Ordnertypen gegen die aktiven Stammdaten des Mandanten, auch noch einmal nach der Analyse. Der Scanner-Zugang kann diese API nicht nutzen. @@ -49,6 +55,7 @@ Nach der Dateinamenprüfung sendet der ES-580W zunächst einen leeren `PUT` mit - Die Browser-API unter `/api/document-inbox` erfordert die normale FEDEO-Anmeldung und einen aktiven Mandanten. Portalbenutzer sind ausgeschlossen. Scanner-Zugänge verwalten nur Administratoren. Die Originale sind außerdem über die bestehende Dateiverwaltung zugänglich. - `GET /api/document-inbox/count` liefert `{ "total": 3 }` für den aktiven Mandanten. `GET /api/document-inbox/filing-options` liefert verfügbare Ordner, Typen und `assignmentKinds`. `GET /api/document-inbox/assignment-options?kind=project&search=Beispiel` liefert bis zu 100 passende Ziele mit `id` und `name`; `GET /api/document-inbox/:id/assignments` die bereits bestehenden Verknüpfungen des Dokuments. - `POST /api/document-inbox/:id/file` mit JSON `{ "folder": "", "type": "", "assignments": { "project": 123, "customer": 456 } }` klassifiziert das Original, speichert die optionalen Verknüpfungen und markiert den Eingang atomar als abgelegt. Weggelassene Zuordnungen bleiben erhalten; JSON-`null` entfernt eine vorhandene Zuordnung. Die Schlüssel entsprechen den Dateifeldern; `check` und `authProfile` verwenden UUIDs, die übrigen Bereiche numerische IDs. Für die Hauptebene ist `folder` als JSON-`null` zu senden. Ein bereits abgelegtes Dokument ergibt `409`; zwischenzeitlich archivierte oder fremde Ziele werden abgewiesen. Dateiänderungen enthalten Zeitpunkt und Benutzer. +- `POST /api/document-inbox/:id/archive` archiviert eine Eingangsdatei des aktiven Mandanten ohne weitere Pflichtangaben und antwortet mit `{ "id": "", "archived": true }`. Wiederholte Aufrufe sind erfolgreich, ohne den ursprünglichen Archivierungszeitpunkt zu ändern. Bereits abgelegte Dokumente ergeben `409`, fremde oder nicht im Eingang registrierte Dateien `404` und Mandantenwartung `423`. Archivieren und Ablegen sind gegeneinander abgesichert. - `GET /api/document-inbox/:id/suggestion` liest den gespeicherten Status `pending`, `processing`, `ready` oder `failed` und liefert bei Erfolg beispielsweise `{ "status": "ready", "suggestion": { "folderId": "", "typeId": "", "confidence": "high|medium", "reason": "…" } }`. Ohne passende Zuordnung ist `suggestion` gleich `null` und `message` erklärt den Grund. `POST /api/document-inbox/:id/suggestion` fordert eine erneute Vorbereitung an und antwortet mit `202` und demselben Statusformat, ohne auf die Analyse zu warten. Ein bereits wartender oder laufender Auftrag wird nicht dupliziert. Nur offene, nicht archivierte Dokumente des aktiven Mandanten sind zugänglich. Diese Anfragen legen nichts ab; dafür bleibt der separate `/file`-Aufruf erforderlich. ## Lokaler Funktionstest diff --git a/frontend/pages/organisation/dokumentenablage.vue b/frontend/pages/organisation/dokumentenablage.vue index ce68b1a5..30ed0c3a 100644 --- a/frontend/pages/organisation/dokumentenablage.vue +++ b/frontend/pages/organisation/dokumentenablage.vue @@ -36,6 +36,12 @@ const previewDocument = ref(null) const filingDocument = ref(null) const filingLoading = ref(false) const filingSaving = ref(false) +const archiveOpen = ref(false) +const archiveTarget = ref(null) +const archiveSaving = ref(false) +const archiveError = ref("") +let archiveVersion = 0 +const documentBusy = computed(() => filingSaving.value || archiveSaving.value) const filingError = ref("") const filingFolders = ref([]) const filingTypes = ref([]) @@ -80,7 +86,7 @@ const folderOptions = computed(() => { return [{ id: "root", name: "Dateien (Hauptebene)" }, ...filingFolders.value .map(folder => ({ id: folder.id, name: path(folder) })).sort((a, b) => a.name.localeCompare(b.name, "de"))] }) -const canFile = computed(() => Boolean(filingDocument.value && !filingLoading.value && !filingSaving.value +const canFile = computed(() => Boolean(filingDocument.value && !filingLoading.value && !documentBusy.value && (filingFolder.value === "root" || selectedFolder.value) && filingTypes.value.some(type => type.id === filingType.value) && (!fixedType.value || filingType.value === selectedFolder.value?.standardFiletype))) @@ -225,6 +231,7 @@ const removeAssignment = (kind: string) => { const openPreview = (entry: InboxDocument) => openFiling(entry) const openFiling = async (entry: InboxDocument) => { + if (disposed || documentBusy.value) return suggestionVersion++ clearTimeout(suggestionTimer) suggestionController?.abort() @@ -278,6 +285,44 @@ const openFiling = async (entry: InboxDocument) => { } } +const removeInboxEntry = (id: string) => { + // Discard older list responses that still contain the completed document. + requestVersion++ + clearTimeout(pollTimer) + if (documents.value.some(document => document.id === id)) total.value = Math.max(0, total.value - 1) + documents.value = documents.value.filter(document => document.id !== id) + page.value = Math.min(page.value, Math.max(1, Math.ceil(total.value / pageSize))) + void inboxCount.refresh() + if (previewDocument.value?.id === id) previewOpen.value = false +} + +const openArchive = (entry: InboxDocument) => { + if (disposed || documentBusy.value || !auth.activeTenant) return + archiveTarget.value = entry + archiveError.value = "" + archiveOpen.value = true +} + +const archiveDocument = async () => { + const entry = archiveTarget.value + if (!entry || !archiveOpen.value || disposed || documentBusy.value || !auth.activeTenant) return + const version = ++archiveVersion + archiveSaving.value = true + archiveError.value = "" + try { + await $api(`/api/document-inbox/${entry.id}/archive`, { method: "POST" }) + if (disposed || version !== archiveVersion) return + removeInboxEntry(entry.id) + archiveOpen.value = false + toast.add({ title: "Dokument archiviert", description: `${entry.name} wurde aus der Ablage entfernt.`, color: "success" }) + await load(true) + } catch (cause: any) { + if (!disposed && version === archiveVersion) archiveError.value = cause?.data?.error || cause?.data?.message || "Das Dokument konnte nicht archiviert werden." + } finally { + if (version === archiveVersion) archiveSaving.value = false + } +} + const fileDocument = async () => { if (!canFile.value) return const entry = filingDocument.value! @@ -288,14 +333,7 @@ const fileDocument = async () => { try { await $api(`/api/document-inbox/${entry.id}/file`, { method: "POST", body: { folder, type: filingType.value, assignments: { ...assignmentChanges.value } } }) if (disposed || version !== filingVersion) return - // Cancel pending polling responses before removing the successfully filed entry. - requestVersion++ - clearTimeout(pollTimer) - documents.value = documents.value.filter(document => document.id !== entry.id) - total.value = Math.max(0, total.value - 1) - page.value = Math.min(page.value, Math.max(1, Math.ceil(total.value / pageSize))) - void inboxCount.refresh() - previewOpen.value = false + removeInboxEntry(entry.id) toast.add({ title: "Dokument abgelegt", description: `${entry.name} ist unter Dateien verfügbar.`, color: "success" }) await load(true) } catch (cause: any) { @@ -429,7 +467,15 @@ watch(previewOpen, open => { filingLoading.value = false } }) +watch(archiveOpen, open => { + if (!open) { archiveTarget.value = null; archiveError.value = "" } +}) watch(() => auth.activeTenant, () => { + archiveVersion++ + archiveOpen.value = false + archiveTarget.value = null + archiveError.value = "" + archiveSaving.value = false requestVersion++ setupVersion++ filingVersion++ @@ -455,6 +501,7 @@ watch(() => auth.activeTenant, () => { onMounted(() => { origin.value = window.location.origin; load() }) onBeforeUnmount(() => { disposed = true + archiveVersion++ requestVersion++ setupVersion++ filingVersion++ @@ -507,7 +554,12 @@ onBeforeUnmount(() => { {{ dayjs(entry.receivedAt).format('DD.MM.YYYY HH:mm') }} {{ formatSize(entry.size) }} -
AblegenVorschau
+
+ Ablegen + Vorschau + + Archivieren +
@@ -522,7 +574,7 @@ onBeforeUnmount(() => { - +