feat(documents): prepare inbox suggestions and add entity assignments
This commit is contained in:
13
backend/db/migrations/0077_scanner_inbox_preparation.sql
Normal file
13
backend/db/migrations/0077_scanner_inbox_preparation.sql
Normal file
@@ -0,0 +1,13 @@
|
||||
ALTER TABLE "scanner_inbox_documents"
|
||||
ADD COLUMN "suggestion_status" text NOT NULL DEFAULT 'pending',
|
||||
ADD COLUMN "suggestion" jsonb,
|
||||
ADD COLUMN "suggestion_message" text,
|
||||
ADD COLUMN "suggestion_claim" uuid,
|
||||
ADD COLUMN "suggestion_updated_at" timestamptz NOT NULL DEFAULT now();
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE "scanner_inbox_documents" ADD CONSTRAINT "scanner_inbox_suggestion_status_check"
|
||||
CHECK ("suggestion_status" IN ('pending', 'processing', 'ready', 'failed'));
|
||||
--> statement-breakpoint
|
||||
CREATE INDEX "scanner_inbox_suggestion_queue_idx"
|
||||
ON "scanner_inbox_documents" ("suggestion_status", "suggestion_updated_at", "received_at")
|
||||
WHERE "filed_at" IS NULL;
|
||||
@@ -519,6 +519,13 @@
|
||||
"when": 1790726400001,
|
||||
"tag": "0076_collaboration_federation",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 74,
|
||||
"version": "7",
|
||||
"when": 1790899200000,
|
||||
"tag": "0077_scanner_inbox_preparation",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { bigint, boolean, index, pgTable, text, timestamp, uniqueIndex, uuid } from "drizzle-orm/pg-core"
|
||||
import { bigint, boolean, index, jsonb, pgTable, text, timestamp, uniqueIndex, uuid } from "drizzle-orm/pg-core"
|
||||
import { tenants } from "./tenants"
|
||||
import { files } from "./files"
|
||||
import { sql } from "drizzle-orm"
|
||||
|
||||
export const scannerInboxConnections = pgTable("scanner_inbox_connections", {
|
||||
tenantId: bigint("tenant_id", { mode: "number" }).primaryKey().references(() => tenants.id, { onDelete: "cascade" }),
|
||||
@@ -18,7 +19,13 @@ export const scannerInboxDocuments = pgTable("scanner_inbox_documents", {
|
||||
checksum: text("checksum").notNull(),
|
||||
receivedAt: timestamp("received_at", { withTimezone: true }).notNull().defaultNow(),
|
||||
filedAt: timestamp("filed_at", { withTimezone: true }),
|
||||
suggestionStatus: text("suggestion_status").notNull().default("pending"),
|
||||
suggestion: jsonb("suggestion"),
|
||||
suggestionMessage: text("suggestion_message"),
|
||||
suggestionClaim: uuid("suggestion_claim"),
|
||||
suggestionUpdatedAt: timestamp("suggestion_updated_at", { withTimezone: true }).notNull().defaultNow(),
|
||||
}, table => ({
|
||||
filenameKey: uniqueIndex("scanner_inbox_documents_filename_key").on(table.tenantId, table.remoteFilename),
|
||||
receivedIdx: index("scanner_inbox_documents_received_idx").on(table.tenantId, table.receivedAt),
|
||||
suggestionQueueIdx: index("scanner_inbox_suggestion_queue_idx").on(table.suggestionStatus, table.suggestionUpdatedAt, table.receivedAt).where(sql`${table.filedAt} IS NULL`),
|
||||
}))
|
||||
|
||||
@@ -69,6 +69,7 @@ import {initS3} from "./utils/s3";
|
||||
import { runBootstrap } from "./modules/bootstrap.service";
|
||||
import { startCentralServicesHeartbeat } from "./modules/central-services-heartbeat.service";
|
||||
import { startDocumentImportWorker } from "./modules/document-import/document-import.worker";
|
||||
import { startScannerInboxWorker } from "./modules/scanner-inbox.worker";
|
||||
|
||||
|
||||
//Services
|
||||
@@ -97,6 +98,7 @@ async function main() {
|
||||
await runBootstrap(app);
|
||||
startCentralServicesHeartbeat(app);
|
||||
startDocumentImportWorker(app);
|
||||
startScannerInboxWorker(app);
|
||||
|
||||
app.addHook('preHandler', (req, reply, done) => {
|
||||
console.log(req.method)
|
||||
|
||||
70
backend/src/modules/scanner-inbox-assignments.ts
Normal file
70
backend/src/modules/scanner-inbox-assignments.ts
Normal file
@@ -0,0 +1,70 @@
|
||||
import { and, asc, eq, ilike, isNull, sql, type SQL } from "drizzle-orm"
|
||||
import type { AnyPgColumn, AnyPgTable } from "drizzle-orm/pg-core"
|
||||
import type { FastifyInstance } from "fastify"
|
||||
import { authProfiles, checks, contracts, createddocuments, customers, incominginvoices, inventoryitems, plants, products, projects, vehicles, vendors } from "../../db/schema"
|
||||
|
||||
type Target = { label: string; table: AnyPgTable; id: AnyPgColumn; tenant: AnyPgColumn; name: AnyPgColumn; available: SQL; uuid?: boolean }
|
||||
export const assignmentTargets: Record<string, Target> = {
|
||||
project: { label: "Projekt", table: projects, id: projects.id, tenant: projects.tenant, name: projects.name, available: eq(projects.archived, false) },
|
||||
customer: { label: "Kunde", table: customers, id: customers.id, tenant: customers.tenant, name: customers.name, available: eq(customers.archived, false) },
|
||||
vendor: { label: "Lieferant", table: vendors, id: vendors.id, tenant: vendors.tenant, name: vendors.name, available: eq(vendors.archived, false) },
|
||||
vehicle: { label: "Fahrzeug", table: vehicles, id: vehicles.id, tenant: vehicles.tenant, name: vehicles.license_plate, available: eq(vehicles.archived, false) },
|
||||
plant: { label: "Objekt", table: plants, id: plants.id, tenant: plants.tenant, name: plants.name, available: eq(plants.archived, false) },
|
||||
contract: { label: "Vertrag", table: contracts, id: contracts.id, tenant: contracts.tenant, name: contracts.name, available: eq(contracts.archived, false) },
|
||||
product: { label: "Produkt", table: products, id: products.id, tenant: products.tenant, name: products.name, available: eq(products.archived, false) },
|
||||
createddocument: { label: "Ausgangsbeleg", table: createddocuments, id: createddocuments.id, tenant: createddocuments.tenant, name: createddocuments.documentNumber, available: eq(createddocuments.archived, false) },
|
||||
incominginvoice: { label: "Eingangsrechnung", table: incominginvoices, id: incominginvoices.id, tenant: incominginvoices.tenant, name: incominginvoices.reference, available: eq(incominginvoices.archived, false) },
|
||||
inventoryitem: { label: "Inventarartikel", table: inventoryitems, id: inventoryitems.id, tenant: inventoryitems.tenant, name: inventoryitems.name, available: eq(inventoryitems.archived, false) },
|
||||
check: { label: "Überprüfung", table: checks, id: checks.id, tenant: checks.tenant, name: checks.name, available: eq(checks.archived, false), uuid: true },
|
||||
authProfile: { label: "Mitarbeiter", table: authProfiles, id: authProfiles.id, tenant: authProfiles.tenant_id, name: authProfiles.full_name,
|
||||
available: and(eq(authProfiles.active, true), isNull(authProfiles.customer_for_portal)), uuid: true },
|
||||
}
|
||||
export const assignmentKinds = Object.entries(assignmentTargets).map(([value, target]) => ({ value, label: target.label }))
|
||||
export type FileAssignments = Record<string, string | number | null>
|
||||
const invalidAssignment = () => Object.assign(new Error("Die gewählte Zuordnung ist nicht verfügbar."), { statusCode: 400 })
|
||||
const targetFor = (kind: string) => {
|
||||
if (!Object.prototype.hasOwnProperty.call(assignmentTargets, kind)) throw invalidAssignment()
|
||||
return assignmentTargets[kind]
|
||||
}
|
||||
export function assignmentId(kind: string, id: unknown) {
|
||||
const target = targetFor(kind)
|
||||
if (target.uuid) {
|
||||
if (typeof id !== "string" || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id)) throw invalidAssignment()
|
||||
return id
|
||||
}
|
||||
if (!/^[1-9]\d*$/.test(String(id)) || !Number.isSafeInteger(Number(id))) throw invalidAssignment()
|
||||
return Number(id)
|
||||
}
|
||||
type Reader = Pick<FastifyInstance["db"], "select">
|
||||
export async function assignmentOptions(db: Reader, tenantId: number, kind: string, search = "") {
|
||||
const target = targetFor(kind)
|
||||
const name = sql<string>`coalesce(nullif(${target.name}, ''), '#' || ${target.id}::text)`
|
||||
const rows = await db.select({ id: target.id, name }).from(target.table)
|
||||
.where(and(eq(target.tenant, tenantId), target.available,
|
||||
search ? ilike(name, `%${search.replace(/[\\%_]/g, "\\$&")}%`) : undefined))
|
||||
.orderBy(asc(target.name), asc(target.id)).limit(100)
|
||||
return rows.map(row => ({ id: String(row.id), name: row.name }))
|
||||
}
|
||||
export async function currentAssignments(db: Reader, tenantId: number, file: Record<string, unknown>) {
|
||||
const assignments = []
|
||||
for (const [kind, target] of Object.entries(assignmentTargets)) {
|
||||
if (file[kind] == null) continue
|
||||
const [entry] = await db.select({ name: target.name }).from(target.table)
|
||||
.where(and(eq(target.id, file[kind]), eq(target.tenant, tenantId), target.available)).limit(1)
|
||||
assignments.push({ kind, id: String(file[kind]), name: entry?.name || (entry ? `#${file[kind]}` : "Nicht mehr verfügbar"), available: Boolean(entry) })
|
||||
}
|
||||
return assignments
|
||||
}
|
||||
export async function validateAssignments(tx: Reader, tenantId: number, assignments: FileAssignments) {
|
||||
const changes: FileAssignments = {}
|
||||
for (const [kind, value] of Object.entries(assignments)) {
|
||||
const target = targetFor(kind)
|
||||
if (value === null) { changes[kind] = null; continue }
|
||||
const id = assignmentId(kind, value)
|
||||
const [row] = await tx.select({ id: target.id }).from(target.table)
|
||||
.where(and(eq(target.id, id), eq(target.tenant, tenantId), target.available)).for("share").limit(1)
|
||||
if (!row) throw invalidAssignment()
|
||||
changes[kind] = id
|
||||
}
|
||||
return changes
|
||||
}
|
||||
@@ -1,12 +1,13 @@
|
||||
import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto"
|
||||
import { and, asc, count, desc, eq, ilike, isNull, sql } from "drizzle-orm"
|
||||
import { and, asc, count, desc, eq, ilike, inArray, isNull, sql } from "drizzle-orm"
|
||||
import type { FastifyInstance } from "fastify"
|
||||
import { DeleteObjectCommand, PutObjectCommand } from "@aws-sdk/client-s3"
|
||||
import { files, filetags, folders, scannerInboxConnections, scannerInboxDocuments, tenants } from "../../db/schema"
|
||||
import { sanitizeFilename } from "../utils/filename"
|
||||
import { s3 } from "../utils/s3"
|
||||
import { secrets } from "../utils/secrets"
|
||||
import { suggestDocumentFiling, validateFilingSuggestion, type FilingSuggestionResult } from "./scanner-inbox-suggestions"
|
||||
import { suggestDocumentFiling, validateFilingSuggestion } from "./scanner-inbox-suggestions"
|
||||
import { assignmentKinds, assignmentOptions, currentAssignments, validateAssignments, type FileAssignments } from "./scanner-inbox-assignments"
|
||||
|
||||
export const SCANNER_UPLOAD_LIMIT = 100 * 1024 * 1024
|
||||
export const SCANNER_DAV_PATH = "/scanner-inbox/"
|
||||
@@ -47,7 +48,6 @@ export function validateScannerFile(filename: string, body: Buffer) {
|
||||
}
|
||||
|
||||
export function createScannerInboxService(db: FastifyInstance["db"], storage: ScannerStorage = objectStorage, analyze = suggestDocumentFiling) {
|
||||
const pendingSuggestions = new Map<string, Promise<FilingSuggestionResult>>()
|
||||
const publicConnection = {
|
||||
username: scannerInboxConnections.username,
|
||||
active: scannerInboxConnections.active,
|
||||
@@ -93,13 +93,19 @@ export function createScannerInboxService(db: FastifyInstance["db"], storage: Sc
|
||||
isNull(scannerInboxDocuments.filedAt), eq(files.archived, false),
|
||||
search ? ilike(scannerInboxDocuments.remoteFilename, `%${search.replace(/[\\%_]/g, "\\$&")}%`) : undefined)
|
||||
const documents = await db.select({ id: files.id, name: scannerInboxDocuments.remoteFilename,
|
||||
mimeType: files.mimeType, size: files.size, receivedAt: scannerInboxDocuments.receivedAt })
|
||||
mimeType: files.mimeType, size: files.size, receivedAt: scannerInboxDocuments.receivedAt, suggestionStatus: scannerInboxDocuments.suggestionStatus })
|
||||
.from(scannerInboxDocuments).innerJoin(files, eq(files.id, scannerInboxDocuments.fileId))
|
||||
.where(condition).orderBy(desc(scannerInboxDocuments.receivedAt), desc(files.id)).limit(limit).offset(offset)
|
||||
const [total] = await db.select({ value: count() }).from(scannerInboxDocuments)
|
||||
.innerJoin(files, eq(files.id, scannerInboxDocuments.fileId)).where(condition)
|
||||
return { documents, total: total.value }
|
||||
}
|
||||
const openCount = async (tenantId: number) => {
|
||||
const [row] = await db.select({ total: count() }).from(scannerInboxDocuments)
|
||||
.innerJoin(files, eq(files.id, scannerInboxDocuments.fileId))
|
||||
.where(and(eq(scannerInboxDocuments.tenantId, tenantId), eq(files.tenant, tenantId), isNull(scannerInboxDocuments.filedAt), eq(files.archived, false)))
|
||||
return row
|
||||
}
|
||||
const filingOptions = async (tenantId: number) => {
|
||||
const [availableFolders, types] = await Promise.all([
|
||||
db.select({ id: folders.id, name: folders.name, parent: folders.parent,
|
||||
@@ -108,33 +114,77 @@ export function createScannerInboxService(db: FastifyInstance["db"], storage: Sc
|
||||
db.select({ id: filetags.id, name: filetags.name }).from(filetags)
|
||||
.where(and(eq(filetags.tenant, tenantId), eq(filetags.archived, false))).orderBy(asc(filetags.name)),
|
||||
])
|
||||
return { folders: availableFolders, types }
|
||||
return { folders: availableFolders, types, assignmentKinds }
|
||||
}
|
||||
const suggestionDocument = async (tenantId: number, fileId: string) => {
|
||||
const [document] = await db.select({ path: files.path, name: scannerInboxDocuments.remoteFilename, mimeType: files.mimeType, size: files.size })
|
||||
const [document] = await db.select({ path: files.path, name: scannerInboxDocuments.remoteFilename, mimeType: files.mimeType, size: files.size,
|
||||
status: scannerInboxDocuments.suggestionStatus, suggestion: scannerInboxDocuments.suggestion, message: scannerInboxDocuments.suggestionMessage })
|
||||
.from(scannerInboxDocuments).innerJoin(files, eq(files.id, scannerInboxDocuments.fileId))
|
||||
.where(and(eq(scannerInboxDocuments.tenantId, tenantId), eq(files.tenant, tenantId), eq(files.id, fileId),
|
||||
isNull(scannerInboxDocuments.filedAt), eq(files.archived, false))).limit(1)
|
||||
if (!document?.path) throw scannerError(404, "Dokument nicht in der Ablage gefunden.")
|
||||
return document
|
||||
}
|
||||
const suggestFiling = async (tenantId: number, fileId: string): Promise<FilingSuggestionResult> => {
|
||||
// Check tenant ownership before reading storage or submitting anything to the AI provider.
|
||||
const getSuggestion = async (tenantId: number, fileId: string) => {
|
||||
const document = await suggestionDocument(tenantId, fileId)
|
||||
const key = `${tenantId}:${fileId}`
|
||||
if (pendingSuggestions.has(key)) return pendingSuggestions.get(key)!
|
||||
if (pendingSuggestions.size >= 4) throw scannerError(429, "Die KI verarbeitet gerade weitere Dokumente. Bitte gleich erneut versuchen.")
|
||||
const operation = (async () => {
|
||||
const result = await analyze(document, await filingOptions(tenantId))
|
||||
await suggestionDocument(tenantId, fileId)
|
||||
const suggestion = validateFilingSuggestion(result, await filingOptions(tenantId))
|
||||
return { suggestion, message: suggestion ? undefined : result.message || "Keine passende Zuordnung verfügbar. Bitte manuell auswählen." }
|
||||
})()
|
||||
pendingSuggestions.set(key, operation)
|
||||
try { return await operation }
|
||||
finally { pendingSuggestions.delete(key) }
|
||||
const suggestion = document.status === "ready"
|
||||
? validateFilingSuggestion({ suggestion: document.suggestion }, await filingOptions(tenantId)) : null
|
||||
return { status: document.status, suggestion, message: document.status === "ready" && !suggestion
|
||||
? document.message || "Keine passende Zuordnung verfügbar. Bitte manuell auswählen." : document.message }
|
||||
}
|
||||
const fileDocument = async (tenantId: number, userId: string, fileId: string, folderId: string | null, typeId: string) => db.transaction(async tx => {
|
||||
const queueSuggestion = async (tenantId: number, fileId: string) => {
|
||||
await suggestionDocument(tenantId, fileId)
|
||||
await db.update(scannerInboxDocuments).set({ suggestionStatus: "pending", suggestion: null, suggestionMessage: null,
|
||||
suggestionClaim: null, suggestionUpdatedAt: new Date() })
|
||||
.where(and(eq(scannerInboxDocuments.tenantId, tenantId), eq(scannerInboxDocuments.fileId, fileId),
|
||||
isNull(scannerInboxDocuments.filedAt), inArray(scannerInboxDocuments.suggestionStatus, ["ready", "failed"])))
|
||||
return getSuggestion(tenantId, fileId)
|
||||
}
|
||||
const processNextSuggestion = async () => {
|
||||
const claim = randomUUID()
|
||||
// Claim without holding a transaction open while OCR/the provider runs. Expired claims survive restarts.
|
||||
const claimed = await db.execute<{ fileId: string; tenantId: string }>(sql`
|
||||
UPDATE scanner_inbox_documents AS job
|
||||
SET suggestion_status = 'processing', suggestion_claim = ${claim}, suggestion_updated_at = now()
|
||||
WHERE job.file_id = (
|
||||
SELECT pending.file_id FROM scanner_inbox_documents AS pending
|
||||
JOIN files ON files.id = pending.file_id AND files.tenant = pending.tenant_id
|
||||
JOIN tenants ON tenants.id = pending.tenant_id
|
||||
WHERE pending.filed_at IS NULL AND files.archived = false
|
||||
AND tenants.locked IS DISTINCT FROM 'maintenance_tenant'
|
||||
AND (pending.suggestion_status = 'pending' OR
|
||||
(pending.suggestion_status = 'processing' AND pending.suggestion_updated_at < now() - interval '5 minutes'))
|
||||
ORDER BY pending.received_at, pending.file_id FOR UPDATE OF pending SKIP LOCKED LIMIT 1
|
||||
) RETURNING job.file_id AS "fileId", job.tenant_id AS "tenantId"`)
|
||||
const job = claimed.rows[0]
|
||||
if (!job) return false
|
||||
const tenantId = Number(job.tenantId)
|
||||
const condition = and(eq(scannerInboxDocuments.fileId, job.fileId), eq(scannerInboxDocuments.tenantId, tenantId),
|
||||
eq(scannerInboxDocuments.suggestionClaim, claim), isNull(scannerInboxDocuments.filedAt))
|
||||
try {
|
||||
const document = await suggestionDocument(tenantId, job.fileId)
|
||||
const { path, name, mimeType, size } = document
|
||||
const result = await analyze({ path, name, mimeType, size }, await filingOptions(tenantId))
|
||||
await suggestionDocument(tenantId, job.fileId)
|
||||
const suggestion = validateFilingSuggestion(result, await filingOptions(tenantId))
|
||||
await db.update(scannerInboxDocuments).set({ suggestionStatus: "ready", suggestion,
|
||||
suggestionMessage: suggestion ? null : result.message || "Keine passende Zuordnung gefunden. Bitte manuell auswählen.",
|
||||
suggestionClaim: null, suggestionUpdatedAt: new Date() }).where(condition)
|
||||
} catch (error: any) {
|
||||
const message = error?.statusCode === 503 ? "Die KI-Erkennung ist noch nicht konfiguriert. Bitte manuell zuordnen oder später erneut prüfen."
|
||||
: "Die KI-Vorbereitung ist fehlgeschlagen. Bitte erneut prüfen oder manuell zuordnen."
|
||||
await db.update(scannerInboxDocuments).set({ suggestionStatus: "failed", suggestion: null, suggestionMessage: message,
|
||||
suggestionClaim: null, suggestionUpdatedAt: new Date() }).where(condition)
|
||||
}
|
||||
return true
|
||||
}
|
||||
const getAssignments = async (tenantId: number, fileId: string) => {
|
||||
await suggestionDocument(tenantId, fileId)
|
||||
const [file] = await db.select().from(files).where(and(eq(files.id, fileId), eq(files.tenant, tenantId), eq(files.archived, false))).limit(1)
|
||||
if (!file) throw scannerError(404, "Dokument nicht gefunden.")
|
||||
return currentAssignments(db, tenantId, file)
|
||||
}
|
||||
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")
|
||||
if (!tenant) throw scannerError(404, "Mandant nicht gefunden.")
|
||||
@@ -157,11 +207,12 @@ export function createScannerInboxService(db: FastifyInstance["db"], storage: Sc
|
||||
const [type] = await tx.select({ id: filetags.id }).from(filetags)
|
||||
.where(and(eq(filetags.id, typeId), eq(filetags.tenant, tenantId), eq(filetags.archived, false))).for("share")
|
||||
if (!type) throw scannerError(400, "Der gewählte Dokumenttyp ist nicht verfügbar.")
|
||||
const assignmentChanges = await validateAssignments(tx, tenantId, assignments)
|
||||
const now = new Date()
|
||||
await tx.update(files).set({ folder: folderId, type: typeId, updatedAt: now, updatedBy: userId })
|
||||
await tx.update(files).set({ ...assignmentChanges, folder: folderId, type: typeId, updatedAt: now, updatedBy: userId })
|
||||
.where(and(eq(files.id, fileId), eq(files.tenant, tenantId)))
|
||||
// Keep the receipt so a scanner retry cannot recreate a document after filing.
|
||||
await tx.update(scannerInboxDocuments).set({ filedAt: now })
|
||||
await tx.update(scannerInboxDocuments).set({ filedAt: now, suggestionClaim: null })
|
||||
.where(and(eq(scannerInboxDocuments.fileId, fileId), eq(scannerInboxDocuments.tenantId, tenantId)))
|
||||
return { id: fileId, folder: folderId, type: typeId }
|
||||
})
|
||||
@@ -225,7 +276,8 @@ export function createScannerInboxService(db: FastifyInstance["db"], storage: Sc
|
||||
throw error
|
||||
}
|
||||
}
|
||||
return { connection, credentials, disable, authenticate, find, list, filingOptions, suggestFiling, fileDocument, probe, accept }
|
||||
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 }
|
||||
}
|
||||
|
||||
export type ScannerInboxService = ReturnType<typeof createScannerInboxService>
|
||||
|
||||
27
backend/src/modules/scanner-inbox.worker.ts
Normal file
27
backend/src/modules/scanner-inbox.worker.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
import type { FastifyInstance } from "fastify"
|
||||
import { createScannerInboxService, type ScannerInboxService } from "./scanner-inbox.service"
|
||||
|
||||
export function startScannerInboxWorker(server: FastifyInstance, service: Pick<ScannerInboxService, "processNextSuggestion"> = createScannerInboxService(server.db)) {
|
||||
let stopped = false
|
||||
let timer: ReturnType<typeof setTimeout> | undefined
|
||||
let running: Promise<void> | undefined
|
||||
const run = async () => {
|
||||
try {
|
||||
// One analysis per process; database claims coordinate multiple backend instances.
|
||||
while (!stopped && await service.processNextSuggestion()) { /* drain the durable queue */ }
|
||||
} catch {
|
||||
server.log.error("KI-Vorbereitung der Dokumentenablage unterbrochen; erneuter Versuch folgt.")
|
||||
} finally {
|
||||
if (!stopped) {
|
||||
timer = setTimeout(() => { running = run() }, 2000)
|
||||
timer.unref()
|
||||
}
|
||||
}
|
||||
}
|
||||
server.addHook("onReady", async () => { running = run() })
|
||||
server.addHook("onClose", async () => {
|
||||
stopped = true
|
||||
clearTimeout(timer)
|
||||
await running
|
||||
})
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import { and, eq } from "drizzle-orm"
|
||||
import type { FastifyInstance } from "fastify"
|
||||
import { authProfiles } from "../../db/schema"
|
||||
import { createScannerInboxService, SCANNER_DAV_PATH, SCANNER_UPLOAD_LIMIT, type ScannerInboxService } from "../modules/scanner-inbox.service"
|
||||
import { assignmentTargets, type FileAssignments } from "../modules/scanner-inbox-assignments"
|
||||
|
||||
export default async function documentInboxRoutes(server: FastifyInstance, options: { service?: ScannerInboxService }) {
|
||||
const service = options.service || createScannerInboxService(server.db)
|
||||
@@ -25,18 +26,32 @@ export default async function documentInboxRoutes(server: FastifyInstance, optio
|
||||
return service.list(req.user.tenant_id!, limit, offset, query.search?.trim() || "")
|
||||
})
|
||||
server.get("/document-inbox/filing-options", async req => service.filingOptions(req.user.tenant_id!))
|
||||
server.get("/document-inbox/count", async req => service.openCount(req.user.tenant_id!))
|
||||
server.get<{ Querystring: { kind: string; search?: string } }>("/document-inbox/assignment-options", {
|
||||
schema: { querystring: { type: "object", required: ["kind"], properties: {
|
||||
kind: { type: "string", enum: Object.keys(assignmentTargets) }, search: { type: "string", maxLength: 200 },
|
||||
} } },
|
||||
}, async req => service.assignmentOptions(req.user.tenant_id!, req.query.kind, req.query.search?.trim() || ""))
|
||||
server.get<{ Params: { id: string } }>("/document-inbox/:id/assignments", {
|
||||
schema: { params: { type: "object", required: ["id"], properties: { id: { type: "string", format: "uuid" } } } },
|
||||
}, async req => service.getAssignments(req.user.tenant_id!, req.params.id))
|
||||
server.get<{ Params: { id: string } }>("/document-inbox/:id/suggestion", {
|
||||
schema: { params: { type: "object", required: ["id"], properties: { id: { type: "string", format: "uuid" } } } },
|
||||
}, async req => service.getSuggestion(req.user.tenant_id!, req.params.id))
|
||||
server.post<{ Params: { id: string } }>("/document-inbox/:id/suggestion", {
|
||||
schema: { params: { type: "object", required: ["id"], properties: { id: { type: "string", format: "uuid" } } } },
|
||||
}, async req => service.suggestFiling(req.user.tenant_id!, req.params.id))
|
||||
server.post<{ Params: { id: string }; Body: { folder: string | null; type: string } }>("/document-inbox/:id/file", {
|
||||
}, async (req, reply) => reply.code(202).send(await service.queueSuggestion(req.user.tenant_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" } } },
|
||||
body: { type: "object", required: ["folder", "type"], additionalProperties: false, properties: {
|
||||
folder: { anyOf: [{ type: "string", format: "uuid" }, { type: "null" }] },
|
||||
type: { type: "string", format: "uuid" },
|
||||
assignments: { type: "object", additionalProperties: false, properties: Object.fromEntries(Object.keys(assignmentTargets).map(kind =>
|
||||
[kind, { anyOf: [{ type: "null" }, { type: "integer", minimum: 1, maximum: Number.MAX_SAFE_INTEGER }, { type: "string", minLength: 1, maxLength: 36 }] }])) },
|
||||
} },
|
||||
},
|
||||
}, async req => service.fileDocument(req.user.tenant_id!, req.user.user_id, req.params.id, req.body.folder, req.body.type))
|
||||
}, async req => service.fileDocument(req.user.tenant_id!, req.user.user_id, req.params.id, req.body.folder, req.body.type, req.body.assignments))
|
||||
server.get("/document-inbox/scanner", async req => ({
|
||||
connection: await service.connection(req.user.tenant_id!), path: SCANNER_DAV_PATH, maxFileSize: SCANNER_UPLOAD_LIMIT,
|
||||
}))
|
||||
|
||||
@@ -193,10 +193,14 @@ test("scanner inbox integration: migration, persistence, isolation, retries and
|
||||
CREATE TABLE filetags (id uuid PRIMARY KEY, tenant bigint, name text, archived boolean DEFAULT false);
|
||||
CREATE TABLE folders (id uuid PRIMARY KEY, tenant bigint, name text, parent uuid, "standardFiletype" uuid,
|
||||
"standardFiletypeIsOptional" boolean DEFAULT true, archived boolean DEFAULT false);
|
||||
CREATE TABLE auth_profiles (tenant_id bigint, user_id uuid, customer_for_portal bigint);`)
|
||||
CREATE TABLE projects (id bigint PRIMARY KEY, tenant bigint, name text, archived boolean DEFAULT false);
|
||||
CREATE TABLE customers (id bigint PRIMARY KEY, tenant bigint, name text, archived boolean DEFAULT false);
|
||||
CREATE TABLE checks (id uuid PRIMARY KEY, tenant bigint, name text, archived boolean DEFAULT false);
|
||||
CREATE TABLE auth_profiles (id uuid DEFAULT gen_random_uuid(), tenant_id bigint, user_id uuid, customer_for_portal bigint,
|
||||
full_name text, active boolean DEFAULT true);`)
|
||||
const migrationRoot = path.resolve(__dirname, "../db/migrations")
|
||||
const journal = JSON.parse(await readFile(path.join(migrationRoot, "meta/_journal.json"), "utf8"))
|
||||
const entries = ["0073_scanner_document_inbox", "0074_scanner_inbox_filing"].map(tag => journal.entries.find((item: any) => item.tag === tag))
|
||||
const entries = ["0073_scanner_document_inbox", "0074_scanner_inbox_filing", "0077_scanner_inbox_preparation"].map(tag => journal.entries.find((item: any) => item.tag === tag))
|
||||
await mkdir(path.join(tempMigrations, "meta"))
|
||||
for (const entry of entries) {
|
||||
assert.ok(entry)
|
||||
@@ -213,14 +217,17 @@ test("scanner inbox integration: migration, persistence, isolation, retries and
|
||||
const analyses: any[] = []
|
||||
let analysisGate: Promise<void> | undefined
|
||||
let analysisStarted: (() => void) | undefined
|
||||
let analysisFailure = false
|
||||
const service = createScannerInboxService(db, {
|
||||
async put(key, body) { stored.set(key, Buffer.from(body)); if (storageFailure) throw new Error("Simulated object store failure") },
|
||||
async remove(key) { stored.delete(key) },
|
||||
}, async (document, candidates) => {
|
||||
analyses.push({ document, candidates })
|
||||
const result = aiResult
|
||||
analysisStarted?.()
|
||||
await analysisGate
|
||||
return aiResult
|
||||
if (analysisFailure) throw new Error("Simulated AI failure")
|
||||
return result
|
||||
})
|
||||
const first = await service.credentials(1)
|
||||
const second = await service.credentials(2)
|
||||
@@ -265,6 +272,8 @@ test("scanner inbox integration: migration, persistence, isolation, retries and
|
||||
assert.equal(row.tenant, "1")
|
||||
assert.equal(row.mimeType, "application/pdf")
|
||||
assert.equal(row.extracted_text, null)
|
||||
assert.equal((await pool.query("SELECT suggestion_status FROM scanner_inbox_documents WHERE file_id=$1", [row.id])).rows[0].suggestion_status, "pending")
|
||||
assert.equal(analyses.length, 0, "the upload only queues preparation; it does not wait for OCR/AI")
|
||||
assert.deepEqual(stored.get(row.path), pdf)
|
||||
assert.equal((await PDFDocument.load(stored.get(row.path)!)).getPageCount(), 2)
|
||||
const listing = await app.inject({ method: "GET", url: "/api/document-inbox" })
|
||||
@@ -332,17 +341,21 @@ test("scanner inbox integration: migration, persistence, isolation, retries and
|
||||
[targetFolder, targetType, foreignFolder, archivedFolder])
|
||||
const fileInto = (id: string, folder: string | null = targetFolder, type: string = targetType, headers = {}) =>
|
||||
app.inject({ method: "POST", url: `/api/document-inbox/${id}/file`, payload: { folder, type }, headers })
|
||||
const suggest = (id: string, headers = {}) => app.inject({ method: "POST", url: `/api/document-inbox/${id}/suggestion`, headers })
|
||||
const suggest = (id: string, headers = {}) => app.inject({ method: "GET", url: `/api/document-inbox/${id}/suggestion`, headers })
|
||||
const queue = (id: string, headers = {}) => app.inject({ method: "POST", url: `/api/document-inbox/${id}/suggestion`, headers })
|
||||
await t.test("AI analysis is tenant scoped, validates destinations and never files a document", async () => {
|
||||
const id = (await service.list(1, 50, 0, "scan.pdf")).documents[0].id
|
||||
const before = (await pool.query("SELECT folder, type, extracted_text FROM files WHERE id=$1", [id])).rows[0]
|
||||
aiResult = { suggestion: { folderId: targetFolder, typeId: targetType, confidence: "high", reason: "Rechnung erkannt." } }
|
||||
assert.equal((await suggest(id, { "x-test-tenant": "2" })).statusCode, 404)
|
||||
assert.equal((await suggest("invalid")).statusCode, 400)
|
||||
await pool.query("INSERT INTO auth_profiles VALUES (1, $1, 123)", [userId])
|
||||
await pool.query("INSERT INTO auth_profiles (tenant_id, user_id, customer_for_portal) VALUES (1, $1, 123)", [userId])
|
||||
assert.equal((await suggest(id)).statusCode, 403)
|
||||
await pool.query("DELETE FROM auth_profiles")
|
||||
assert.equal(analyses.length, 0)
|
||||
assert.equal((await suggest(id)).json().status, "pending")
|
||||
assert.equal(analyses.length, 0, "reading the preview never starts analysis")
|
||||
assert.equal(await service.processNextSuggestion(), true)
|
||||
const result = await suggest(id, { "x-test-admin": "false" })
|
||||
assert.equal(result.statusCode, 200, result.body)
|
||||
assert.deepEqual(result.json().suggestion, aiResult.suggestion)
|
||||
@@ -352,6 +365,8 @@ test("scanner inbox integration: migration, persistence, isolation, retries and
|
||||
assert.deepEqual((await pool.query("SELECT folder, type, extracted_text FROM files WHERE id=$1", [id])).rows[0], before)
|
||||
assert.equal((await service.list(1, 50, 0, "scan.pdf")).total, 1)
|
||||
aiResult = { suggestion: { ...aiResult.suggestion!, folderId: foreignFolder } }
|
||||
assert.equal((await queue(id)).statusCode, 202)
|
||||
await service.processNextSuggestion()
|
||||
assert.equal((await suggest(id)).json().suggestion, null)
|
||||
})
|
||||
await t.test("AI results are checked again if destination availability changes during analysis", async () => {
|
||||
@@ -360,15 +375,93 @@ test("scanner inbox integration: migration, persistence, isolation, retries and
|
||||
let finish!: () => void
|
||||
analysisGate = new Promise(resolve => { finish = resolve })
|
||||
const started = new Promise<void>(resolve => { analysisStarted = resolve })
|
||||
const pending = suggest(id).then(response => response)
|
||||
await queue(id)
|
||||
const pending = service.processNextSuggestion()
|
||||
await started
|
||||
await pool.query("UPDATE folders SET archived=true WHERE id=$1", [targetFolder])
|
||||
finish()
|
||||
assert.equal((await pending).json().suggestion, null)
|
||||
await pending
|
||||
assert.equal((await suggest(id)).json().suggestion, null)
|
||||
await pool.query("UPDATE folders SET archived=false WHERE id=$1", [targetFolder])
|
||||
analysisGate = undefined
|
||||
analysisStarted = undefined
|
||||
})
|
||||
await t.test("prepared results persist, failed jobs wait for explicit retry and expired claims resume", async () => {
|
||||
const id = (await service.list(1, 50, 0, "scan.pdf")).documents[0].id
|
||||
const otherService = createScannerInboxService(db, undefined, async () => aiResult)
|
||||
const before = analyses.length
|
||||
assert.equal((await otherService.getSuggestion(1, id)).status, "ready")
|
||||
assert.equal(analyses.length, before)
|
||||
await queue(id)
|
||||
analysisFailure = true
|
||||
await service.processNextSuggestion()
|
||||
analysisFailure = false
|
||||
assert.equal((await suggest(id)).json().status, "failed")
|
||||
assert.equal((await suggest(id)).json().suggestion, null)
|
||||
const failedCount = analyses.length
|
||||
await suggest(id)
|
||||
assert.equal(analyses.length, failedCount)
|
||||
await queue(id)
|
||||
await pool.query("UPDATE scanner_inbox_documents SET suggestion_status='processing', suggestion_claim=$2, suggestion_updated_at=now()-interval '6 minutes' WHERE file_id=$1", [id, randomUUID()])
|
||||
aiResult = { suggestion: { folderId: targetFolder, typeId: targetType, confidence: "high", reason: "Vorbereitet nach Neustart." } }
|
||||
await otherService.processNextSuggestion()
|
||||
assert.equal((await suggest(id)).json().suggestion.reason, "Vorbereitet nach Neustart.")
|
||||
})
|
||||
await t.test("an expired worker cannot overwrite a newer completed suggestion", async () => {
|
||||
const id = (await service.list(1, 50, 0, "scan.pdf")).documents[0].id
|
||||
await queue(id)
|
||||
aiResult = { suggestion: { folderId: targetFolder, typeId: targetType, confidence: "high", reason: "Alter Vorschlag." } }
|
||||
let finish!: () => void
|
||||
analysisGate = new Promise(resolve => { finish = resolve })
|
||||
const started = new Promise<void>(resolve => { analysisStarted = resolve })
|
||||
const pending = service.processNextSuggestion()
|
||||
await started
|
||||
await pool.query("UPDATE scanner_inbox_documents SET suggestion_updated_at=now()-interval '6 minutes' WHERE file_id=$1", [id])
|
||||
const otherService = createScannerInboxService(db, undefined, async () => ({ suggestion: {
|
||||
folderId: null, typeId: alternativeType, confidence: "medium", reason: "Neuer Vorschlag.",
|
||||
} }))
|
||||
await otherService.processNextSuggestion()
|
||||
finish()
|
||||
await pending
|
||||
assert.equal((await suggest(id)).json().suggestion.reason, "Neuer Vorschlag.")
|
||||
analysisGate = undefined
|
||||
analysisStarted = undefined
|
||||
})
|
||||
await t.test("entity choices and filing reject foreign, archived and wrong-type IDs atomically", async () => {
|
||||
await pool.query("INSERT INTO projects VALUES (11, 1, 'Umbau', false), (12, 2, 'Fremdes Projekt', false), (13, 1, 'Archiv', true)")
|
||||
await pool.query("INSERT INTO customers VALUES (21, 1, 'Musterkunde', false), (22, 2, 'Fremder Kunde', false)")
|
||||
const checkId = randomUUID()
|
||||
const profileId = randomUUID()
|
||||
await pool.query("INSERT INTO checks VALUES ($1, 1, 'Prüfung', false)", [checkId])
|
||||
await pool.query("INSERT INTO auth_profiles (id, tenant_id, full_name) VALUES ($1, 1, 'Test Mitarbeiter')", [profileId])
|
||||
const choices = await app.inject({ method: "GET", url: "/api/document-inbox/assignment-options?kind=project&search=Umbau" })
|
||||
assert.deepEqual(choices.json(), [{ id: "11", name: "Umbau" }])
|
||||
assert.equal((await app.inject({ method: "GET", url: "/api/document-inbox/assignment-options?kind=unknown" })).statusCode, 400)
|
||||
const id = (await service.list(1, 50, 0, "scan.pdf")).documents[0].id
|
||||
for (const assignments of [{ project: "12" }, { project: "13" }, { project: randomUUID() }, { project: "11", customer: "22" }, { check: 11 }, { authProfile: randomUUID() }]) {
|
||||
const res = await app.inject({ method: "POST", url: `/api/document-inbox/${id}/file`, payload: { folder: targetFolder, type: targetType, assignments } })
|
||||
assert.equal(res.statusCode, 400, res.body)
|
||||
}
|
||||
assert.deepEqual((await pool.query("SELECT folder, type, project, customer FROM files WHERE id=$1", [id])).rows[0], { folder: null, type: null, project: null, customer: null })
|
||||
await pool.query("UPDATE files SET project=11 WHERE id=$1", [id])
|
||||
assert.deepEqual((await app.inject({ method: "GET", url: `/api/document-inbox/${id}/assignments` })).json(), [{ kind: "project", id: "11", name: "Umbau", available: true }])
|
||||
assert.equal((await app.inject({ method: "GET", url: `/api/document-inbox/${id}/assignments`, headers: { "x-test-tenant": "2" } })).statusCode, 404)
|
||||
await service.fileDocument(1, userId, id, targetFolder, targetType, { project: null, customer: "21", check: checkId, authProfile: profileId })
|
||||
assert.deepEqual((await pool.query('SELECT project, customer, "check", auth_profile FROM files WHERE id=$1', [id])).rows[0], { project: null, customer: '21', check: checkId, auth_profile: profileId })
|
||||
// Restore the fixture so existing retry/filing tests can exercise this same original document.
|
||||
await pool.query('UPDATE files SET folder=null, type=null, customer=null, "check"=null, auth_profile=null WHERE id=$1', [id])
|
||||
await pool.query("UPDATE scanner_inbox_documents SET filed_at=null WHERE file_id=$1", [id])
|
||||
})
|
||||
await t.test("menu count includes only this tenant's open, unarchived documents", async () => {
|
||||
const res = await app.inject({ method: "GET", url: "/api/document-inbox/count" })
|
||||
assert.equal(res.json().total, (await service.list(1, 50, 0, "")).total)
|
||||
const other = await app.inject({ method: "GET", url: "/api/document-inbox/count", headers: { "x-test-tenant": "2" } })
|
||||
assert.equal(other.json().total, 1)
|
||||
const id = (await service.list(1, 50, 0, "failed.pdf")).documents[0].id
|
||||
await pool.query("UPDATE files SET archived=true WHERE id=$1", [id])
|
||||
assert.equal((await service.openCount(1)).total, res.json().total - 1)
|
||||
await pool.query("UPDATE files SET archived=false WHERE id=$1", [id])
|
||||
})
|
||||
await t.test("filing options and destinations exclude other tenants and archived entries", async () => {
|
||||
const options = await app.inject({ method: "GET", url: "/api/document-inbox/filing-options" })
|
||||
assert.equal(options.statusCode, 200)
|
||||
@@ -388,7 +481,7 @@ test("scanner inbox integration: migration, persistence, isolation, retries and
|
||||
await pool.query("UPDATE tenants SET locked='maintenance_tenant' WHERE id=1")
|
||||
assert.equal((await fileInto(id)).statusCode, 423)
|
||||
await pool.query("UPDATE tenants SET locked=null WHERE id=1")
|
||||
await pool.query("INSERT INTO auth_profiles VALUES (1, $1, 123)", [userId])
|
||||
await pool.query("INSERT INTO auth_profiles (tenant_id, user_id, customer_for_portal) VALUES (1, $1, 123)", [userId])
|
||||
assert.equal((await fileInto(id)).statusCode, 403)
|
||||
assert.equal((await app.inject({ method: "GET", url: "/api/document-inbox/filing-options" })).statusCode, 403)
|
||||
await pool.query("DELETE FROM auth_profiles")
|
||||
@@ -444,7 +537,7 @@ test("scanner inbox integration: migration, persistence, isolation, retries and
|
||||
assert.equal((await app.inject({ method, url, headers: { "x-test-admin": "false" } })).statusCode, 403)
|
||||
}
|
||||
assert.equal((await app.inject({ method: "GET", url: "/api/document-inbox", headers: { "x-test-admin": "false" } })).statusCode, 200)
|
||||
await pool.query("INSERT INTO auth_profiles VALUES (1, $1, 123)", [userId])
|
||||
await pool.query("INSERT INTO auth_profiles (tenant_id, user_id, customer_for_portal) VALUES (1, $1, 123)", [userId])
|
||||
assert.equal((await app.inject({ method: "GET", url: "/api/document-inbox" })).statusCode, 403)
|
||||
await pool.query("DELETE FROM auth_profiles")
|
||||
})
|
||||
|
||||
@@ -1,15 +1,16 @@
|
||||
# Epson-Scanner und Dokumentenablage
|
||||
|
||||
Unter **Organisation → Dokumentenablage** erscheinen noch nicht abgelegte Scanner-Dateien des aktiven Mandanten, neueste zuerst. Die Seite aktualisiert sich alle zehn Sekunden; Suche, Vorschau und Herunterladen sind verfügbar. Jede übertragene Datei wird unverändert als ein Dokument gespeichert. Ein mehrseitiges PDF bleibt ein Dokument. Der Empfang führt keine Texterkennung, Seitentrennung oder Rechnungsverarbeitung aus.
|
||||
Unter **Organisation → Dokumentenablage** erscheinen noch nicht abgelegte Scanner-Dateien des aktiven Mandanten, neueste zuerst. Die Seite aktualisiert sich alle zehn Sekunden; Suche, Vorschau und Herunterladen sind verfügbar. Ein Badge am Menüeintrag zählt die offenen, nicht archivierten Dokumente unabhängig von der aktuellen Suche. Es aktualisiert sich alle zehn Sekunden und unmittelbar nach dem Ablegen. Jede übertragene Datei wird unverändert als ein Dokument gespeichert. Ein mehrseitiges PDF bleibt ein Dokument. Nach dem erfolgreichen Empfang wird die KI-Zuordnung im Hintergrund vorbereitet; der Scanner muss darauf nicht warten. Seitentrennung und Rechnungsverarbeitung werden nicht ausgelöst.
|
||||
|
||||
## In Dateien ablegen
|
||||
|
||||
1. Auf den Dateinamen, **Vorschau** oder **Ablegen** klicken. Das Modal zeigt das Original und rechts die Zuordnung.
|
||||
2. Beim Öffnen wird ein KI-Vorschlag für Ordner und Dokumenttyp aus dem Dokumentinhalt angefordert. Ein gültiger Vorschlag füllt die Auswahlfelder vor und zeigt eine kurze Begründung. Bereits manuell geänderte Werte werden nicht überschrieben. **KI-Vorschlag einsetzen** übernimmt ihn bei Bedarf wieder in die Felder; **Erneut prüfen** fordert eine neue Analyse an.
|
||||
2. Das Modal lädt den bereits vorbereiteten KI-Vorschlag für Ordner und Dokumenttyp. Läuft die Vorbereitung noch, zeigt es den Fortschritt und lädt das Ergebnis automatisch nach. Ein gültiger Vorschlag füllt die Auswahlfelder vor und zeigt eine kurze Begründung. Bereits manuell geänderte Werte werden nicht überschrieben. **KI-Vorschlag einsetzen** übernimmt ihn bei Bedarf wieder in die Felder; **Erneut prüfen** stellt eine abgeschlossene oder fehlgeschlagene Analyse erneut in die Warteschlange.
|
||||
3. Den vorgeschlagenen vorhandenen FEDEO-Dateiordner oder **Dateien (Hauptebene)** und **Dokumenttyp** prüfen und bei Bedarf ändern. Unterordner erscheinen mit ihrem vollständigen Pfad. Neue Typen lassen sich unter **Stammdaten → Dateitypen** anlegen. Ein vorgeschriebener Ordnertyp ist nicht änderbar.
|
||||
4. Erst **Übernehmen und ablegen** speichert Ordner und Typ am bestehenden Original. Danach verschwindet das Dokument aus dem Eingang und ist unter **Dateien** im gewählten Ordner verfügbar. Es wird keine Kopie erzeugt und keine Rechnungsverarbeitung ausgelöst.
|
||||
4. Optional unter **Zuordnungen** einen Bereich und einen Eintrag auswählen und mit **Zuordnung hinzufügen** vormerken. Wie auf der Dateiseite stehen Projekt, Kunde, Lieferant, Fahrzeug, Objekt, Vertrag, Produkt, Ausgangsbeleg, Eingangsrechnung, Inventarartikel, Überprüfung und Mitarbeiter zur Verfügung. Mehrere Bereiche können gleichzeitig zugeordnet werden, jeweils ein Eintrag pro Bereich. Die Einträge lassen sich nach Namen suchen; bestehende Zuordnungen werden angezeigt und können entfernt werden.
|
||||
5. Erst **Übernehmen und ablegen** speichert Ordner, Typ und vorgemerkte Zuordnungen gemeinsam am bestehenden Original. Danach verschwindet das Dokument aus dem Eingang und ist unter **Dateien** im gewählten Ordner und mit den gewählten Verknüpfungen verfügbar. Es wird keine Kopie erzeugt und keine Rechnungsverarbeitung ausgelöst.
|
||||
|
||||
Nur aktive Ordner und Typen desselben Mandanten sind zulässig. Bei einem Fehler bleibt das Dokument im Eingang. Ein erneuter Scanner-Upload mit demselben Namen und Inhalt bestätigt weiterhin den ursprünglichen Empfang, ohne einen neuen Eingangseintrag anzulegen.
|
||||
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
|
||||
|
||||
@@ -17,7 +18,9 @@ Die Analyse nutzt die bestehende zentrale FEDEO-KI-Anbindung oder den konfigurie
|
||||
|
||||
Für die Analyse werden höchstens die ersten fünf PDF-Seiten bzw. die erste Bildseite lokal gelesen (Poppler/Tesseract; JPEG, PNG und TIFF werden für die OCR aufbereitet). Diese Werkzeuge sind im Backend-Image enthalten. Es werden maximal 24.000 Textzeichen und eine begrenzte Auswahl passender Ordner und Typen an die KI geschickt. Die Analyse ist auf Dateien bis 25 MiB begrenzt; die Texterkennung und die einzelnen KI-Anfragen haben Zeitlimits von jeweils 45 Sekunden. Fehlen lesbarer Text, passende Stammdaten oder eine KI-Konfiguration, bleibt die manuelle Zuordnung verfügbar.
|
||||
|
||||
Vorschläge und erkannter Text verändern weder das Original noch dessen Klassifizierung. Die Vorschau hält Ergebnisse während des Seitenbesuchs im Speicher, um erneute Analysen beim Wiederöffnen zu vermeiden; ein Mandantenwechsel verwirft sie. Gleichzeitige Analysen desselben Dokuments werden im Backend zusammengefasst, maximal vier Analysen laufen gleichzeitig pro Backend-Prozess. Die fachliche Qualität der KI-Vorschläge sollte bei der Inbetriebnahme mit eigenen Beispieldokumenten geprüft werden.
|
||||
Vorschläge und erkannter Text verändern weder das Original noch dessen Klassifizierung. Der Auftrag entsteht zusammen mit dem Eingangseintrag in der Datenbank. Das Backend verarbeitet offene Aufträge automatisch, auch ohne geöffnete Dokumentenablage. Vorschlag, Status und eine gegebenenfalls nötige Fehlermeldung werden dauerhaft am Eingangseintrag gespeichert; beim Wiederöffnen wird keine neue Analyse ausgelöst. Erkannter Volltext wird hierfür nicht gespeichert. Vorhandene offene Dokumente werden nach der Migration ebenfalls vorbereitet.
|
||||
|
||||
Pro Backend-Prozess läuft eine Analyse gleichzeitig. Datenbanksperren und Auftragskennungen koordinieren mehrere Instanzen. Neue Aufträge werden spätestens beim nächsten Durchlauf nach zwei Sekunden berücksichtigt, wenn kein älterer Auftrag mehr läuft. Nach einem Prozessabbruch werden seit fünf Minuten nicht abgeschlossene Aufträge erneut übernommen; verspätete Ergebnisse eines alten Auftrags können das neuere Ergebnis nicht überschreiben. Abgelegte, archivierte und Dokumente von Mandanten im Wartungsmodus werden nicht neu gestartet. Fehlgeschlagene Analysen lassen sich im Modal erneut anfordern; die manuelle Ablage bleibt möglich. Die fachliche Qualität der KI-Vorschläge sollte bei der Inbetriebnahme mit eigenen Beispieldokumenten geprüft werden.
|
||||
|
||||
## Einrichtung
|
||||
|
||||
@@ -36,7 +39,7 @@ Nach der Dateinamenprüfung sendet der ES-580W zunächst einen leeren `PUT` mit
|
||||
|
||||
## Schnittstelle und Betrieb
|
||||
|
||||
- Datenbankmigrationen `0073_scanner_document_inbox` und `0074_scanner_inbox_filing` werden über die reguläre Drizzle-Migration eingespielt. Keine neuen Umgebungsvariablen oder zusätzlichen Dienste sind erforderlich; der vorhandene S3-kompatible Dateispeicher wird genutzt.
|
||||
- Datenbankmigrationen `0073_scanner_document_inbox`, `0074_scanner_inbox_filing` und `0077_scanner_inbox_preparation` werden über die reguläre Drizzle-Migration eingespielt. Keine neuen Umgebungsvariablen oder zusätzlichen Dienste sind erforderlich; der vorhandene S3-kompatible Dateispeicher wird genutzt. Die Hintergrundverarbeitung startet mit dem Backend.
|
||||
- Der Scanner-Endpunkt liegt außerhalb der Browser-JWT-Anmeldung unter `/scanner-inbox/` und verwendet HTTP Basic mit eigenen zufälligen Zugangsdaten. Ausschließlich über HTTPS veröffentlichen. Passwörter werden nur als SHA-256-Hash gespeichert.
|
||||
- Unterstützt werden `OPTIONS`, `PROPFIND` (Depth 0/1), `HEAD` und `PUT /scanner-inbox/<Dateiname>`. Ein authentifiziertes `GET` auf den Empfangsordner (mit oder ohne abschließenden Schrägstrich) liefert für die Epson-Vorprüfung `200` mit leerem Inhalt. Dokumente lassen sich damit nicht herunterladen. Der Empfangsordner existiert bereits; Unterordner, Lesen von Dateien, Löschen, Umbenennen und Überschreiben über den Scanner-Zugang sind nicht vorgesehen. Dies ist ein begrenzter WebDAV-Upload-Eingang, kein allgemeines Netzlaufwerk. Ein PROPFIND des Ordners gibt keine Dokumentenliste preis.
|
||||
- `PUT` enthält genau eine vollständige Datei als Rohdaten, ohne Multipart-Formular. PDF, JPEG, PNG und TIFF werden anhand von Dateiendung und Signatur geprüft, maximal 100 MiB. Keine Prüfung der gesamten Dokumentstruktur auf Beschädigungen.
|
||||
@@ -44,8 +47,9 @@ Nach der Dateinamenprüfung sendet der ES-580W zunächst einen leeren `PUT` mit
|
||||
- Fehlende/ungültige/deaktivierte Zugangsdaten: `401`; ungültiger Pfad oder leerer Upload ohne explizite Schreibprobe (`Content-Length: 0`): `400`; zu groß: `413`; falsches Format: `415`; Mandantenwartung: `423`. Bei Speicherfehlern gibt es keine Erfolgsbestätigung und keinen unvollständigen Ablageeintrag. Der Scanner kann erneut senden.
|
||||
- Der Reverse Proxy muss die genannten HTTP-Methoden, den Authorization-Header und Uploads bis 100 MiB zulassen. Bei einem abgeschnittenen Pfadpräfix sollte er `X-Forwarded-Prefix` setzen (Traefik StripPrefix erledigt dies). HTTPS endet üblicherweise am bestehenden Proxy.
|
||||
- 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/filing-options` liefert verfügbare Ordner und Typen. `POST /api/document-inbox/:id/file` mit JSON `{ "folder": "<Ordner-UUID oder null>", "type": "<Dateityp-UUID>" }` klassifiziert das Original und markiert den Eingang atomar als abgelegt. 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/suggestion` liefert `{ "suggestion": { "folderId": "<UUID oder null>", "typeId": "<UUID>", "confidence": "high|medium", "reason": "…" } }` oder einen leeren Vorschlag mit Erklärung. Nur offene, nicht archivierte Dokumente des aktiven Mandanten sind analysierbar. Die Anfrage legt nichts ab; dafür bleibt der separate `/file`-Aufruf erforderlich.
|
||||
- `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": "<Ordner-UUID oder null>", "type": "<Dateityp-UUID>", "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.
|
||||
- `GET /api/document-inbox/:id/suggestion` liest den gespeicherten Status `pending`, `processing`, `ready` oder `failed` und liefert bei Erfolg beispielsweise `{ "status": "ready", "suggestion": { "folderId": "<UUID oder null>", "typeId": "<UUID>", "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
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ const props = defineProps({
|
||||
|
||||
const route = useRoute()
|
||||
const auth = useAuthStore()
|
||||
const { count: inboxCount } = useDocumentInboxCount()
|
||||
const { has } = usePermission()
|
||||
const tenantExtraModules = computed(() => {
|
||||
const modules = auth.activeTenantData?.extraModules
|
||||
@@ -55,7 +56,8 @@ const links = computed(() => {
|
||||
featureEnabled("files") ? {
|
||||
label: "Dokumentenablage",
|
||||
to: "/organisation/dokumentenablage",
|
||||
icon: "i-heroicons-inbox-arrow-down"
|
||||
icon: "i-heroicons-inbox-arrow-down",
|
||||
badge: inboxCount.value > 0 ? String(inboxCount.value) : undefined,
|
||||
} : null,
|
||||
featureEnabled("files") ? {
|
||||
label: "Dateien",
|
||||
|
||||
31
frontend/composables/useDocumentInboxCount.ts
Normal file
31
frontend/composables/useDocumentInboxCount.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
import { createSharedComposable } from "@vueuse/core"
|
||||
|
||||
export const useDocumentInboxCount = createSharedComposable(() => {
|
||||
const auth = useAuthStore()
|
||||
const { $api } = useNuxtApp()
|
||||
const count = ref(0)
|
||||
const scope = computed(() => auth.user?.id && auth.activeTenant && !auth.profile?.customer_for_portal && auth.activeTenantData?.features?.files !== false
|
||||
? `${auth.user.id}:${auth.activeTenant}` : "")
|
||||
let version = 0
|
||||
let disposed = false
|
||||
let controller: AbortController | undefined
|
||||
let timer: ReturnType<typeof setTimeout> | undefined
|
||||
const refresh = async () => {
|
||||
const request = ++version
|
||||
clearTimeout(timer)
|
||||
controller?.abort()
|
||||
if (!scope.value || disposed) { count.value = 0; return }
|
||||
controller = new AbortController()
|
||||
try {
|
||||
const result = await $api<{ total: number }>("/api/document-inbox/count", { signal: controller.signal })
|
||||
if (!disposed && request === version) count.value = Math.max(0, Number(result.total) || 0)
|
||||
} catch {
|
||||
if (request === version) count.value = 0
|
||||
} finally {
|
||||
if (!disposed && request === version && scope.value) timer = setTimeout(refresh, 10000)
|
||||
}
|
||||
}
|
||||
watch(scope, () => { count.value = 0; void refresh() }, { immediate: true, flush: "sync" })
|
||||
onScopeDispose(() => { disposed = true; version++; controller?.abort(); clearTimeout(timer) })
|
||||
return { count, refresh }
|
||||
})
|
||||
@@ -1,18 +1,21 @@
|
||||
<script setup lang="ts">
|
||||
import dayjs from "dayjs"
|
||||
|
||||
type InboxDocument = { id: string; name: string; mimeType: string; size: number; receivedAt: string }
|
||||
type InboxDocument = { id: string; name: string; mimeType: string; size: number; receivedAt: string; suggestionStatus?: string }
|
||||
type ScannerConnection = { username: string; active: boolean; password?: string }
|
||||
type FilingFolder = { id: string; name: string; parent: string | null; standardFiletype: string | null; standardFiletypeIsOptional: boolean }
|
||||
type FilingType = { id: string; name: string }
|
||||
type FilingSuggestion = { folderId: string | null; typeId: string; confidence: "high" | "medium"; reason: string }
|
||||
type SuggestionResult = { suggestion: FilingSuggestion | null; message?: string }
|
||||
type SuggestionResult = { status: "pending" | "processing" | "ready" | "failed"; suggestion: FilingSuggestion | null; message?: string }
|
||||
type AssignmentKind = { value: string; label: string }
|
||||
type Assignment = { kind: string; id: string; name: string; available?: boolean }
|
||||
|
||||
const { $api } = useNuxtApp()
|
||||
const auth = useAuthStore()
|
||||
const config = useRuntimeConfig()
|
||||
const fileActions = useFiles()
|
||||
const toast = useToast()
|
||||
const inboxCount = useDocumentInboxCount()
|
||||
const documents = ref<InboxDocument[]>([])
|
||||
const total = ref(0)
|
||||
const page = ref(1)
|
||||
@@ -43,9 +46,22 @@ const suggestionLoading = ref(false)
|
||||
const suggestionError = ref("")
|
||||
const suggestionMessage = ref("")
|
||||
const selectionTouched = ref(false)
|
||||
const suggestionCache = new Map<string, SuggestionResult>()
|
||||
const suggestionStatus = ref("")
|
||||
let suggestionTimer: ReturnType<typeof setTimeout> | undefined
|
||||
let suggestionController: AbortController | undefined
|
||||
let suggestionVersion = 0
|
||||
const assignmentKinds = ref<AssignmentKind[]>([])
|
||||
const assignments = ref<Assignment[]>([])
|
||||
const assignmentChanges = ref<Record<string, string | null>>({})
|
||||
const assignmentKind = ref("project")
|
||||
const assignmentSearch = ref("")
|
||||
const assignmentOptions = ref<{ id: string; name: string }[]>([])
|
||||
const assignmentId = ref<string | null>(null)
|
||||
const assignmentLoading = ref(false)
|
||||
const assignmentError = ref("")
|
||||
let assignmentVersion = 0
|
||||
let assignmentTimer: ReturnType<typeof setTimeout> | undefined
|
||||
let assignmentController: AbortController | undefined
|
||||
const selectedFolder = computed(() => filingFolders.value.find(folder => folder.id === filingFolder.value))
|
||||
const fixedType = computed(() => Boolean(selectedFolder.value?.standardFiletype && !selectedFolder.value.standardFiletypeIsOptional))
|
||||
const folderOptions = computed(() => {
|
||||
@@ -125,8 +141,14 @@ const applySuggestion = () => {
|
||||
|
||||
const loadFilingSuggestion = async (refresh = false) => {
|
||||
const entry = filingDocument.value
|
||||
if (!entry || filingLoading.value || filingSaving.value || suggestionLoading.value) return
|
||||
if (!entry || disposed || filingLoading.value || suggestionLoading.value) return
|
||||
if (filingSaving.value) {
|
||||
clearTimeout(suggestionTimer)
|
||||
suggestionTimer = setTimeout(() => loadFilingSuggestion(), 2000)
|
||||
return
|
||||
}
|
||||
const version = ++suggestionVersion
|
||||
clearTimeout(suggestionTimer)
|
||||
const filingRequest = filingVersion
|
||||
suggestionController?.abort()
|
||||
suggestionController = new AbortController()
|
||||
@@ -134,18 +156,28 @@ const loadFilingSuggestion = async (refresh = false) => {
|
||||
suggestionError.value = ""
|
||||
suggestionMessage.value = ""
|
||||
try {
|
||||
const result = (!refresh && suggestionCache.get(entry.id)) || await $api<SuggestionResult>(`/api/document-inbox/${entry.id}/suggestion`, {
|
||||
method: "POST", signal: suggestionController.signal,
|
||||
const result = await $api<SuggestionResult>(`/api/document-inbox/${entry.id}/suggestion`, {
|
||||
method: refresh ? "POST" : "GET", signal: suggestionController.signal,
|
||||
})
|
||||
if (disposed || version !== suggestionVersion || filingRequest !== filingVersion) return
|
||||
suggestionStatus.value = result.status
|
||||
if (["pending", "processing"].includes(result.status)) {
|
||||
suggestion.value = null
|
||||
suggestionMessage.value = result.status === "pending" ? "KI-Vorschlag wird im Hintergrund vorbereitet …" : "Der Dokumentinhalt wird geprüft …"
|
||||
suggestionTimer = setTimeout(() => loadFilingSuggestion(), 2000)
|
||||
return
|
||||
}
|
||||
if (result.status === "failed") {
|
||||
suggestion.value = null
|
||||
suggestionError.value = result.message || "Die KI-Vorbereitung ist fehlgeschlagen. Bitte erneut prüfen oder manuell zuordnen."
|
||||
return
|
||||
}
|
||||
const proposed = result.suggestion
|
||||
const folder = filingFolders.value.find(folder => folder.id === proposed?.folderId)
|
||||
const valid = proposed && filingTypes.value.some(type => type.id === proposed.typeId)
|
||||
&& (proposed.folderId === null || (folder && (!folder.standardFiletype || folder.standardFiletypeIsOptional || folder.standardFiletype === proposed.typeId)))
|
||||
suggestion.value = valid ? proposed : null
|
||||
suggestionMessage.value = valid ? "" : result.message || "Keine passende Zuordnung gefunden. Du kannst Ordner und Typ selbst auswählen."
|
||||
if (suggestionCache.size >= 50) suggestionCache.delete(suggestionCache.keys().next().value!)
|
||||
suggestionCache.set(entry.id, { suggestion: suggestion.value, message: suggestionMessage.value })
|
||||
// A delayed AI response must not replace choices the user has already made.
|
||||
if (!selectionTouched.value) applySuggestion()
|
||||
} catch (cause: any) {
|
||||
@@ -156,15 +188,63 @@ const loadFilingSuggestion = async (refresh = false) => {
|
||||
}
|
||||
}
|
||||
|
||||
const loadAssignmentOptions = async () => {
|
||||
if (!previewOpen.value || !assignmentKinds.value.some(kind => kind.value === assignmentKind.value)) return
|
||||
const version = ++assignmentVersion
|
||||
assignmentController?.abort()
|
||||
assignmentController = new AbortController()
|
||||
assignmentLoading.value = true
|
||||
assignmentError.value = ""
|
||||
assignmentId.value = null
|
||||
assignmentOptions.value = []
|
||||
try {
|
||||
const options = await $api<{ id: string; name: string }[]>("/api/document-inbox/assignment-options", {
|
||||
query: { kind: assignmentKind.value, search: assignmentSearch.value.trim() }, signal: assignmentController.signal,
|
||||
})
|
||||
if (!disposed && version === assignmentVersion) assignmentOptions.value = options
|
||||
} catch {
|
||||
if (!disposed && version === assignmentVersion) assignmentError.value = "Zuordnungen konnten nicht geladen werden. Bitte erneut versuchen."
|
||||
} finally {
|
||||
if (version === assignmentVersion) assignmentLoading.value = false
|
||||
}
|
||||
}
|
||||
const addAssignment = () => {
|
||||
if (filingSaving.value || assignmentLoading.value) return
|
||||
const entry = assignmentOptions.value.find(option => option.id === assignmentId.value)
|
||||
if (!entry) return
|
||||
assignments.value = [...assignments.value.filter(item => item.kind !== assignmentKind.value), { kind: assignmentKind.value, ...entry }]
|
||||
assignmentChanges.value[assignmentKind.value] = entry.id
|
||||
assignmentId.value = null
|
||||
}
|
||||
const removeAssignment = (kind: string) => {
|
||||
if (filingSaving.value) return
|
||||
assignments.value = assignments.value.filter(item => item.kind !== kind)
|
||||
assignmentChanges.value[kind] = null
|
||||
}
|
||||
|
||||
const openPreview = (entry: InboxDocument) => openFiling(entry)
|
||||
|
||||
const openFiling = async (entry: InboxDocument) => {
|
||||
suggestionVersion++
|
||||
clearTimeout(suggestionTimer)
|
||||
suggestionController?.abort()
|
||||
suggestion.value = null
|
||||
suggestionLoading.value = false
|
||||
suggestionError.value = ""
|
||||
suggestionMessage.value = ""
|
||||
suggestionStatus.value = ""
|
||||
assignmentVersion++
|
||||
assignmentController?.abort()
|
||||
clearTimeout(assignmentTimer)
|
||||
assignments.value = []
|
||||
assignmentChanges.value = {}
|
||||
assignmentKinds.value = []
|
||||
assignmentOptions.value = []
|
||||
assignmentId.value = null
|
||||
assignmentLoading.value = false
|
||||
assignmentKind.value = "project"
|
||||
assignmentSearch.value = ""
|
||||
assignmentError.value = ""
|
||||
selectionTouched.value = false
|
||||
previewOpen.value = true
|
||||
previewDocument.value = entry
|
||||
@@ -178,10 +258,16 @@ const openFiling = async (entry: InboxDocument) => {
|
||||
filingSaving.value = false
|
||||
const version = ++filingVersion
|
||||
try {
|
||||
const result = await $api<{ folders: FilingFolder[]; types: FilingType[] }>("/api/document-inbox/filing-options")
|
||||
const [result, current] = await Promise.all([
|
||||
$api<{ folders: FilingFolder[]; types: FilingType[]; assignmentKinds: AssignmentKind[] }>("/api/document-inbox/filing-options"),
|
||||
$api<Assignment[]>(`/api/document-inbox/${entry.id}/assignments`),
|
||||
])
|
||||
if (disposed || version !== filingVersion) return
|
||||
filingFolders.value = result.folders
|
||||
filingTypes.value = result.types
|
||||
assignmentKinds.value = result.assignmentKinds || []
|
||||
assignments.value = current
|
||||
void loadAssignmentOptions()
|
||||
} catch (cause: any) {
|
||||
if (version === filingVersion) filingError.value = cause?.data?.error || cause?.data?.message || "Ordner und Dokumenttypen konnten nicht geladen werden."
|
||||
} finally {
|
||||
@@ -200,7 +286,7 @@ const fileDocument = async () => {
|
||||
filingSaving.value = true
|
||||
filingError.value = ""
|
||||
try {
|
||||
await $api(`/api/document-inbox/${entry.id}/file`, { method: "POST", body: { folder, type: filingType.value } })
|
||||
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++
|
||||
@@ -208,7 +294,7 @@ const fileDocument = async () => {
|
||||
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)))
|
||||
suggestionCache.delete(entry.id)
|
||||
void inboxCount.refresh()
|
||||
previewOpen.value = false
|
||||
toast.add({ title: "Dokument abgelegt", description: `${entry.name} ist unter Dateien verfügbar.`, color: "success" })
|
||||
await load(true)
|
||||
@@ -304,14 +390,35 @@ watch(filingFolder, () => {
|
||||
const defaultType = selectedFolder.value?.standardFiletype
|
||||
if (defaultType) filingType.value = defaultType
|
||||
}, { flush: "sync" })
|
||||
watch([assignmentKind, assignmentSearch], ([kind, search], [previousKind]) => {
|
||||
// SelectMenu clears its search after choosing an item; keep that selection available for adding.
|
||||
if (kind === previousKind && !search && assignmentId.value) return
|
||||
assignmentVersion++
|
||||
assignmentController?.abort()
|
||||
assignmentId.value = null
|
||||
assignmentOptions.value = []
|
||||
clearTimeout(assignmentTimer)
|
||||
if (previewOpen.value) assignmentTimer = setTimeout(loadAssignmentOptions, 250)
|
||||
})
|
||||
watch(previewOpen, open => {
|
||||
if (!open) {
|
||||
suggestionVersion++
|
||||
clearTimeout(suggestionTimer)
|
||||
suggestionController?.abort()
|
||||
suggestion.value = null
|
||||
suggestionLoading.value = false
|
||||
suggestionError.value = ""
|
||||
suggestionMessage.value = ""
|
||||
suggestionStatus.value = ""
|
||||
assignmentVersion++
|
||||
assignmentController?.abort()
|
||||
clearTimeout(assignmentTimer)
|
||||
assignments.value = []
|
||||
assignmentChanges.value = {}
|
||||
assignmentKinds.value = []
|
||||
assignmentOptions.value = []
|
||||
assignmentLoading.value = false
|
||||
assignmentError.value = ""
|
||||
previewDocument.value = null
|
||||
filingVersion++
|
||||
filingDocument.value = null
|
||||
@@ -328,7 +435,10 @@ watch(() => auth.activeTenant, () => {
|
||||
filingVersion++
|
||||
suggestionVersion++
|
||||
suggestionController?.abort()
|
||||
suggestionCache.clear()
|
||||
clearTimeout(suggestionTimer)
|
||||
assignmentVersion++
|
||||
assignmentController?.abort()
|
||||
clearTimeout(assignmentTimer)
|
||||
previewOpen.value = false
|
||||
previewDocument.value = null
|
||||
clearTimeout(searchTimer)
|
||||
@@ -350,7 +460,10 @@ onBeforeUnmount(() => {
|
||||
filingVersion++
|
||||
suggestionVersion++
|
||||
suggestionController?.abort()
|
||||
suggestionCache.clear()
|
||||
clearTimeout(suggestionTimer)
|
||||
assignmentVersion++
|
||||
assignmentController?.abort()
|
||||
clearTimeout(assignmentTimer)
|
||||
clearTimeout(searchTimer)
|
||||
clearTimeout(pollTimer)
|
||||
})
|
||||
@@ -388,7 +501,10 @@ onBeforeUnmount(() => {
|
||||
</thead>
|
||||
<tbody class="divide-y divide-default">
|
||||
<tr v-for="entry in documents" :key="entry.id" class="hover:bg-elevated/30">
|
||||
<td class="max-w-sm px-4 py-4"><button class="flex items-center gap-3 text-left font-medium text-highlighted hover:text-primary" :aria-label="`${entry.name} als Vorschau anzeigen`" @click="openPreview(entry)"><UIcon name="i-heroicons-document-text" class="h-5 w-5 shrink-0 text-muted" /><span class="break-all">{{ entry.name }}</span></button></td>
|
||||
<td class="max-w-sm px-4 py-4">
|
||||
<button class="flex items-center gap-3 text-left font-medium text-highlighted hover:text-primary" :aria-label="`${entry.name} als Vorschau anzeigen`" @click="openPreview(entry)"><UIcon name="i-heroicons-document-text" class="h-5 w-5 shrink-0 text-muted" /><span class="break-all">{{ entry.name }}</span></button>
|
||||
<UBadge v-if="entry.suggestionStatus" class="mt-2" size="xs" variant="subtle" :color="entry.suggestionStatus === 'failed' ? 'warning' : 'neutral'">{{ entry.suggestionStatus === 'ready' ? 'KI-Prüfung abgeschlossen' : entry.suggestionStatus === 'failed' ? 'KI-Prüfung fehlgeschlagen' : 'KI wird vorbereitet' }}</UBadge>
|
||||
</td>
|
||||
<td class="whitespace-nowrap px-4 py-4 text-muted">{{ dayjs(entry.receivedAt).format('DD.MM.YYYY HH:mm') }}</td>
|
||||
<td class="whitespace-nowrap px-4 py-4 text-muted">{{ formatSize(entry.size) }}</td>
|
||||
<td class="px-4 py-4"><div class="flex justify-end gap-1"><UButton icon="i-heroicons-folder-arrow-down" variant="soft" :aria-label="`${entry.name} ablegen`" @click="openFiling(entry)">Ablegen</UButton><UButton icon="i-heroicons-eye" color="neutral" variant="ghost" :aria-label="`${entry.name} als Vorschau anzeigen`" @click="openPreview(entry)">Vorschau</UButton><UButton icon="i-heroicons-arrow-down-tray" color="neutral" variant="ghost" :aria-label="`${entry.name} herunterladen`" @click="fileAction(entry, true)" /></div></td>
|
||||
@@ -425,9 +541,9 @@ onBeforeUnmount(() => {
|
||||
<UButton size="xs" color="neutral" variant="ghost" :disabled="filingLoading || filingSaving || suggestionLoading" @click="loadFilingSuggestion(true)">Erneut prüfen</UButton>
|
||||
</div>
|
||||
<div aria-live="polite" class="space-y-3">
|
||||
<div v-if="suggestionLoading" class="space-y-2 text-sm text-muted">
|
||||
<div v-if="suggestionLoading || (['pending', 'processing'].includes(suggestionStatus) && !suggestionError)" class="space-y-2 text-sm text-muted">
|
||||
<UProgress />
|
||||
<p>Der Dokumentinhalt wird geprüft …</p>
|
||||
<p>{{ suggestionMessage || 'Vorbereiteten KI-Vorschlag laden …' }}</p>
|
||||
</div>
|
||||
<UAlert v-if="suggestionError" :title="suggestionError" color="warning" variant="subtle" />
|
||||
<div v-else-if="suggestion" class="space-y-2 rounded-lg bg-elevated/50 p-3 text-sm">
|
||||
@@ -439,7 +555,7 @@ onBeforeUnmount(() => {
|
||||
<p class="text-muted">{{ suggestion.reason }}</p>
|
||||
<UButton v-if="!suggestionSelected" size="sm" variant="soft" :disabled="filingSaving" @click="applySuggestion">KI-Vorschlag einsetzen</UButton>
|
||||
</div>
|
||||
<p v-else-if="suggestionMessage" class="text-sm text-muted">{{ suggestionMessage }}</p>
|
||||
<p v-else-if="suggestionMessage && !['pending', 'processing'].includes(suggestionStatus)" class="text-sm text-muted">{{ suggestionMessage }}</p>
|
||||
</div>
|
||||
<UAlert v-if="filingError" :title="filingError" color="error" variant="subtle" />
|
||||
<USkeleton v-if="filingLoading" class="h-32 w-full" />
|
||||
@@ -452,8 +568,29 @@ onBeforeUnmount(() => {
|
||||
</UFormField>
|
||||
<UAlert v-if="!filingTypes.length && !filingError" title="Noch keine Dokumenttypen vorhanden" description="Lege zuerst unter Stammdaten → Dateitypen einen Typ an." color="warning" variant="subtle" />
|
||||
<UAlert v-else-if="fixedType && !filingTypes.some(type => type.id === filingType)" title="Der vorgegebene Dokumenttyp ist nicht verfügbar." description="Bitte die Ordnereinstellungen korrigieren oder einen anderen Zielordner wählen." color="warning" variant="subtle" />
|
||||
<USeparator label="Zuordnungen" />
|
||||
<div v-if="assignments.length" class="space-y-2">
|
||||
<div v-for="assignment in assignments" :key="assignment.kind" class="flex items-center justify-between gap-2 rounded-lg border border-default p-2 text-sm">
|
||||
<div class="min-w-0">
|
||||
<p class="text-xs text-muted">{{ assignmentKinds.find(kind => kind.value === assignment.kind)?.label }}</p>
|
||||
<p class="break-words" :class="{ 'text-warning': assignment.available === false }">{{ assignment.name }}</p>
|
||||
</div>
|
||||
<UButton icon="i-heroicons-x-mark" color="neutral" variant="ghost" :aria-label="`${assignment.name} entfernen`" :disabled="filingSaving" @click="removeAssignment(assignment.kind)" />
|
||||
</div>
|
||||
</div>
|
||||
<UFormField label="Bereich zuordnen">
|
||||
<USelectMenu v-model="assignmentKind" :items="assignmentKinds" value-key="value" label-key="label" :disabled="filingSaving" class="w-full" />
|
||||
</UFormField>
|
||||
<UFormField label="Eintrag auswählen">
|
||||
<USelectMenu v-model="assignmentId" v-model:search-term="assignmentSearch" :items="assignmentOptions" value-key="id" label-key="name" placeholder="Eintrag suchen …" :search-input="{ placeholder: 'Name suchen …' }" ignore-filter :loading="assignmentLoading" :disabled="filingSaving" class="w-full" />
|
||||
</UFormField>
|
||||
<div v-if="assignmentError" class="text-sm text-error" role="status">
|
||||
{{ assignmentError }}
|
||||
<UButton size="xs" color="neutral" variant="ghost" @click="loadAssignmentOptions">Erneut versuchen</UButton>
|
||||
</div>
|
||||
<UButton icon="i-heroicons-link" variant="soft" :disabled="!assignmentId || assignmentLoading || filingSaving" @click="addAssignment">Zuordnung hinzufügen</UButton>
|
||||
</template>
|
||||
<p class="text-xs text-muted">Die KI berücksichtigt bis zu fünf PDF-Seiten bzw. die erste Bildseite. Erst mit „Übernehmen und ablegen“ wird das Dokument unter Dateien gespeichert und aus dem Eingang entfernt.</p>
|
||||
<p class="text-xs text-muted">Die KI berücksichtigt bis zu fünf PDF-Seiten bzw. die erste Bildseite. „Übernehmen und ablegen“ speichert Ordner, Typ und Zuordnungen gemeinsam und entfernt das Dokument aus dem Eingang.</p>
|
||||
</form>
|
||||
</aside>
|
||||
</div>
|
||||
|
||||
62
frontend/tests/document-inbox-count.test.cjs
Normal file
62
frontend/tests/document-inbox-count.test.cjs
Normal file
@@ -0,0 +1,62 @@
|
||||
const { test } = require('node:test')
|
||||
const assert = require('node:assert/strict')
|
||||
const fs = require('node:fs')
|
||||
const vm = require('node:vm')
|
||||
const vue = require('vue')
|
||||
const ts = require('../../backend/node_modules/typescript')
|
||||
const settle = () => new Promise(setImmediate)
|
||||
|
||||
function setup(api) {
|
||||
const auth = vue.reactive({ user: { id: 'user-1' }, activeTenant: '1', profile: null, activeTenantData: {} })
|
||||
const timers = new Map()
|
||||
let nextTimer = 0
|
||||
const scope = vue.effectScope()
|
||||
const context = vm.createContext({
|
||||
exports: {}, AbortController,
|
||||
require: name => name === '@vueuse/core' ? { createSharedComposable: fn => fn } : require(name),
|
||||
ref: vue.ref, computed: vue.computed, watch: vue.watch, onScopeDispose: vue.onScopeDispose,
|
||||
useAuthStore: () => auth, useNuxtApp: () => ({ $api: api }),
|
||||
setTimeout: fn => { timers.set(++nextTimer, fn); return nextTimer }, clearTimeout: id => timers.delete(id),
|
||||
})
|
||||
const source = fs.readFileSync(`${__dirname}/../composables/useDocumentInboxCount.ts`, 'utf8')
|
||||
vm.runInContext(ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 } }).outputText, context)
|
||||
const counter = scope.run(() => context.exports.useDocumentInboxCount())
|
||||
return { auth, counter, timers, close: () => scope.stop() }
|
||||
}
|
||||
|
||||
test('menu count refreshes after filing and cancels its timer when navigation is unmounted', async () => {
|
||||
let count = 3
|
||||
const ui = setup(async () => ({ total: count }))
|
||||
await settle()
|
||||
assert.equal(ui.counter.count.value, 3)
|
||||
assert.equal(ui.timers.size, 1)
|
||||
count = 2
|
||||
await ui.counter.refresh()
|
||||
assert.equal(ui.counter.count.value, 2)
|
||||
assert.equal(ui.timers.size, 1)
|
||||
ui.close()
|
||||
assert.equal(ui.timers.size, 0)
|
||||
})
|
||||
|
||||
test('previous tenant responses cannot replace the current badge; portal and logout clear it', async t => {
|
||||
let finish
|
||||
let requests = 0
|
||||
const ui = setup(() => ++requests === 1 ? new Promise(resolve => { finish = resolve }) : Promise.resolve({ total: 2 }))
|
||||
t.after(ui.close)
|
||||
ui.auth.activeTenant = '2'
|
||||
assert.equal(ui.counter.count.value, 0)
|
||||
await settle()
|
||||
finish({ total: 999 })
|
||||
await settle()
|
||||
assert.equal(ui.counter.count.value, 2)
|
||||
ui.auth.profile = { customer_for_portal: 15 }
|
||||
await settle()
|
||||
assert.equal(ui.counter.count.value, 0)
|
||||
assert.equal(ui.timers.size, 0)
|
||||
ui.auth.profile = null
|
||||
await settle()
|
||||
assert.equal(ui.counter.count.value, 2)
|
||||
ui.auth.user = null
|
||||
await settle()
|
||||
assert.equal(ui.counter.count.value, 0)
|
||||
})
|
||||
@@ -18,13 +18,15 @@ function setup(api, apiBase = 'https://fedeo.example/backend') {
|
||||
let timerId = 0
|
||||
let mount
|
||||
let unmount
|
||||
let countRefreshes = 0
|
||||
const context = vm.createContext({
|
||||
require, exports: {}, URL, AbortController,
|
||||
ref: vue.ref, computed: vue.computed, watch: vue.watch,
|
||||
useAuthStore: () => auth,
|
||||
useDocumentInboxCount: () => ({ refresh: async () => { countRefreshes++ } }),
|
||||
useRuntimeConfig: () => ({ public: { apiBase } }),
|
||||
useFiles: () => ({}), useToast: () => ({ add() {} }),
|
||||
useNuxtApp: () => ({ $api: api }),
|
||||
useNuxtApp: () => ({ $api: (url, options) => /\/assignments$/.test(url) ? Promise.resolve([]) : api(url, options) }),
|
||||
window: { location: { origin: 'https://fedeo.example' } },
|
||||
onMounted: handler => { mount = handler },
|
||||
onBeforeUnmount: handler => { unmount = handler },
|
||||
@@ -33,7 +35,7 @@ function setup(api, apiBase = 'https://fedeo.example/backend') {
|
||||
})
|
||||
const source = fs.readFileSync(`${__dirname}/../pages/organisation/dokumentenablage.vue`, 'utf8').match(/<script setup lang="ts">([\s\S]*?)<\/script>/)[1]
|
||||
vm.runInContext(ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022, esModuleInterop: true } }).outputText, context)
|
||||
return { auth, timers, mount, close: () => unmount(), run: code => vm.runInContext(code, context) }
|
||||
return { auth, timers, mount, countRefreshes: () => countRefreshes, close: () => unmount(), run: code => vm.runInContext(code, context) }
|
||||
}
|
||||
|
||||
test('scanner setup preserves absolute and relative backend prefixes', async t => {
|
||||
@@ -193,12 +195,12 @@ test('tenant switching discards pending folder options and filing responses', as
|
||||
|
||||
const aiSuggestion = { folderId: 'folder', typeId: 'invoice', confidence: 'high', reason: 'Rechnung erkannt.' }
|
||||
|
||||
test('AI preselection only files the document after confirmation and reuses its preview result', async t => {
|
||||
test('AI preselection only files the document after confirmation and reads the prepared result without triggering AI', async t => {
|
||||
const requests = []
|
||||
const ui = setup(async (url, options) => {
|
||||
requests.push({ url, options })
|
||||
if (url.endsWith('/filing-options')) return filingOptions
|
||||
if (url.endsWith('/suggestion')) return { suggestion: aiSuggestion }
|
||||
if (url.endsWith('/suggestion')) return { status: 'ready', suggestion: aiSuggestion }
|
||||
if (url.endsWith('/file')) return { id: 'scan' }
|
||||
return { documents: [], total: 0 }
|
||||
})
|
||||
@@ -213,12 +215,14 @@ test('AI preselection only files the document after confirmation and reuses its
|
||||
await settle()
|
||||
await ui.run('openPreview({ id: "scan", name: "scan.pdf" })')
|
||||
await settle()
|
||||
assert.equal(requests.filter(request => request.url.endsWith('/suggestion')).length, 1)
|
||||
assert.equal(requests.filter(request => request.url.endsWith('/suggestion')).length, 2)
|
||||
assert.ok(requests.filter(request => request.url.endsWith('/suggestion')).every(request => request.options.method === 'GET'))
|
||||
await ui.run('fileDocument()')
|
||||
const save = requests.find(request => request.url.endsWith('/file'))
|
||||
assert.equal(save.options.body.folder, 'folder')
|
||||
assert.equal(save.options.body.type, 'invoice')
|
||||
assert.equal(ui.run('previewOpen.value'), false)
|
||||
assert.equal(ui.countRefreshes(), 1)
|
||||
})
|
||||
|
||||
test('late AI results preserve manual choices, and can still be explicitly applied', async t => {
|
||||
@@ -227,7 +231,7 @@ test('late AI results preserve manual choices, and can still be explicitly appli
|
||||
t.after(ui.close)
|
||||
await ui.run('openPreview({ id: "scan", name: "scan.pdf" })')
|
||||
ui.run('filingType.value = "other"; selectionTouched.value = true')
|
||||
pending.resolve({ suggestion: aiSuggestion })
|
||||
pending.resolve({ status: 'ready', suggestion: aiSuggestion })
|
||||
await settle()
|
||||
assert.equal(ui.run('filingFolder.value'), 'root')
|
||||
assert.equal(ui.run('filingType.value'), 'other')
|
||||
@@ -257,10 +261,9 @@ test('closing, changing documents or switching tenant cancels and discards pendi
|
||||
// Keep the replacement document's request separate from the stale first result.
|
||||
if (action === 'document') ui.run('previewOpen.value = false')
|
||||
await settle()
|
||||
pending.resolve({ suggestion: aiSuggestion })
|
||||
pending.resolve({ status: 'ready', suggestion: aiSuggestion })
|
||||
await settle()
|
||||
assert.equal(ui.run('suggestion.value'), null)
|
||||
assert.equal(ui.run('suggestionCache.size'), 0)
|
||||
}
|
||||
})
|
||||
|
||||
@@ -279,3 +282,113 @@ test('AI failures leave manual filing available and optional folder defaults do
|
||||
await settle()
|
||||
assert.equal(ui.run('filingType.value'), 'other')
|
||||
})
|
||||
|
||||
test('pending preparation is polled, preserves manual choices and only explicit refresh queues work', async t => {
|
||||
const requests = []
|
||||
let state = 'pending'
|
||||
const ui = setup(async (url, options) => {
|
||||
if (url.endsWith('/filing-options')) return filingOptions
|
||||
requests.push(options.method)
|
||||
return { status: state, suggestion: state === 'ready' ? aiSuggestion : null }
|
||||
})
|
||||
t.after(ui.close)
|
||||
await ui.run('openPreview({ id: "scan", name: "scan.pdf" })')
|
||||
await settle()
|
||||
assert.equal(ui.run('suggestionStatus.value'), 'pending')
|
||||
assert.equal(ui.run('suggestion.value'), null)
|
||||
assert.equal(ui.timers.size, 1)
|
||||
ui.run('filingType.value = "other"; selectionTouched.value = true')
|
||||
state = 'ready'
|
||||
await ui.run('loadFilingSuggestion()')
|
||||
assert.equal(ui.run('filingType.value'), 'other')
|
||||
assert.equal(ui.run('suggestion.value.typeId'), 'invoice')
|
||||
assert.equal(ui.timers.size, 0)
|
||||
await ui.run('loadFilingSuggestion(true)')
|
||||
assert.deepEqual(requests, ['GET', 'GET', 'POST'])
|
||||
})
|
||||
|
||||
test('preparation polling resumes when a concurrent manual filing attempt fails', async t => {
|
||||
const save = deferred()
|
||||
let state = 'processing'
|
||||
const ui = setup(async url => {
|
||||
if (url.endsWith('/filing-options')) return filingOptions
|
||||
if (url.endsWith('/suggestion')) return { status: state, suggestion: state === 'ready' ? aiSuggestion : null }
|
||||
if (url.endsWith('/file')) { await save.promise; throw { data: { error: 'Bitte erneut versuchen' } } }
|
||||
})
|
||||
t.after(ui.close)
|
||||
const tick = async () => {
|
||||
assert.equal(ui.timers.size, 1)
|
||||
const [id, callback] = [...ui.timers][0]
|
||||
ui.timers.delete(id)
|
||||
await callback()
|
||||
}
|
||||
await ui.run('openPreview({ id: "scan", name: "scan.pdf" })')
|
||||
await settle()
|
||||
ui.run('filingType.value = "other"; selectionTouched.value = true')
|
||||
const filing = ui.run('fileDocument()')
|
||||
await tick()
|
||||
assert.equal(ui.timers.size, 1, 'polling remains scheduled while filing is in progress')
|
||||
save.resolve()
|
||||
await filing
|
||||
assert.equal(ui.run('previewOpen.value'), true)
|
||||
state = 'ready'
|
||||
await tick()
|
||||
assert.equal(ui.run('suggestion.value.typeId'), 'invoice')
|
||||
assert.equal(ui.run('filingType.value'), 'other')
|
||||
assert.equal(ui.timers.size, 0)
|
||||
})
|
||||
|
||||
test('entity assignments are submitted together with filing and search reset preserves a selected item', async t => {
|
||||
const requests = []
|
||||
const ui = setup(async (url, options) => {
|
||||
requests.push({ url, options })
|
||||
if (url.endsWith('/filing-options')) return { ...filingOptions, assignmentKinds: [{ value: 'project', label: 'Projekt' }, { value: 'customer', label: 'Kunde' }] }
|
||||
if (url.endsWith('/assignment-options')) return [{ id: '11', name: 'Umbau' }]
|
||||
if (url.endsWith('/suggestion')) return { status: 'ready', suggestion: aiSuggestion }
|
||||
if (url.endsWith('/file')) return { id: 'scan' }
|
||||
return { documents: [], total: 0 }
|
||||
})
|
||||
t.after(ui.close)
|
||||
await ui.run('openPreview({ id: "scan", name: "scan.pdf" })')
|
||||
await settle()
|
||||
ui.run('assignmentSearch.value = "Umbau"')
|
||||
await settle()
|
||||
await ui.run('loadAssignmentOptions()')
|
||||
ui.run('assignmentId.value = "11"; assignmentSearch.value = ""')
|
||||
await settle()
|
||||
assert.equal(ui.run('assignmentId.value'), '11')
|
||||
ui.run('addAssignment()')
|
||||
assert.equal(ui.run('assignments.value[0].name'), 'Umbau')
|
||||
assert.equal(requests.some(request => request.url.endsWith('/file')), false)
|
||||
ui.run('assignmentKind.value = "customer"')
|
||||
await settle()
|
||||
ui.run('assignmentOptions.value = [{ id: "21", name: "Kunde" }]; assignmentId.value = "21"; assignmentLoading.value = false; addAssignment(); removeAssignment("project")')
|
||||
await ui.run('fileDocument()')
|
||||
const saved = requests.find(request => request.url.endsWith('/file'))
|
||||
assert.equal(saved.options.body.assignments.project, null)
|
||||
assert.equal(saved.options.body.assignments.customer, '21')
|
||||
assert.equal(saved.options.body.folder, 'folder')
|
||||
assert.equal(saved.options.body.type, 'invoice')
|
||||
assert.equal(ui.countRefreshes(), 1)
|
||||
})
|
||||
|
||||
test('old entity search responses are discarded on category and tenant changes', async t => {
|
||||
const pending = deferred()
|
||||
const ui = setup(url => {
|
||||
if (url.endsWith('/filing-options')) return Promise.resolve({ ...filingOptions, assignmentKinds: [{ value: 'project', label: 'Projekt' }, { value: 'customer', label: 'Kunde' }] })
|
||||
if (url.endsWith('/assignment-options')) return pending.promise
|
||||
if (url.endsWith('/suggestion')) return Promise.resolve({ status: 'ready', suggestion: null })
|
||||
return Promise.resolve({ documents: [], total: 0 })
|
||||
})
|
||||
t.after(ui.close)
|
||||
await ui.run('openPreview({ id: "scan", name: "scan.pdf" })')
|
||||
ui.run('assignmentKind.value = "customer"')
|
||||
await settle()
|
||||
ui.auth.activeTenant = '2'
|
||||
await settle()
|
||||
pending.resolve([{ id: 'foreign', name: 'Previous tenant project' }])
|
||||
await settle()
|
||||
assert.equal(ui.run('assignmentOptions.value.length'), 0)
|
||||
assert.equal(ui.run('assignments.value.length'), 0)
|
||||
assert.equal(ui.timers.size, 1, 'only the inbox list polling remains')
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user