feat(documents): allow archiving inbox documents
This commit is contained in:
@@ -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<typeof createScannerInboxService>
|
||||
|
||||
@@ -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" } } },
|
||||
|
||||
@@ -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<void>(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)
|
||||
|
||||
Reference in New Issue
Block a user