Merge pull request 'dev' (#242) from dev into main
Reviewed-on: #242
This commit was merged in pull request #242.
This commit is contained in:
@@ -71,7 +71,7 @@ export async function createMcpContext(
|
||||
}
|
||||
}
|
||||
|
||||
export function assertToolPermission(context: McpContext, tool: McpTool) {
|
||||
export function assertToolPermission(context: McpContext, tool: Pick<McpTool, "name" | "requiredPermissions">) {
|
||||
if (context.isAdmin) return
|
||||
|
||||
const allowed = tool.requiredPermissions.every((permission) =>
|
||||
@@ -85,4 +85,3 @@ export function assertToolPermission(context: McpContext, tool: McpTool) {
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
44
backend/src/mcp/documentFiles.ts
Normal file
44
backend/src/mcp/documentFiles.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
import { and, eq, getTableColumns } from "drizzle-orm"
|
||||
import { authProfiles, files } from "../../db/schema"
|
||||
import { McpContext } from "./types"
|
||||
import { validateScannerFile } from "../modules/scanner-inbox.service"
|
||||
import { secrets } from "../utils/secrets"
|
||||
|
||||
export const MCP_FILE_LIMIT = 20 * 1024 * 1024
|
||||
export const MCP_BODY_LIMIT = Math.ceil(MCP_FILE_LIMIT / 3) * 4 + 64 * 1024
|
||||
export const MCP_FILE_PERMISSION = "documents.read"
|
||||
|
||||
// Storage paths and potentially large extracted text do not belong in list responses.
|
||||
const { path: _path, extractedText: _text, ...metadata } = getTableColumns(files)
|
||||
export const fileMetadataColumns = metadata
|
||||
|
||||
export async function assertInternalDocumentAccess(context: McpContext) {
|
||||
const [profile] = await context.server.db.select({ portal: authProfiles.customer_for_portal }).from(authProfiles)
|
||||
.where(and(eq(authProfiles.tenant_id, context.tenantId), eq(authProfiles.user_id, context.userId))).limit(1)
|
||||
if (profile?.portal) throw Object.assign(new Error("Die Dokumentenablage ist nur intern verfügbar."), { statusCode: 403 })
|
||||
}
|
||||
|
||||
export async function loadDocumentFile(context: McpContext, id: string) {
|
||||
const [file] = await context.server.db.select().from(files)
|
||||
.where(and(eq(files.id, id), eq(files.tenant, context.tenantId), eq(files.archived, false))).limit(1)
|
||||
if (!file) throw Object.assign(new Error("Datei nicht gefunden oder archiviert."), { statusCode: 404 })
|
||||
return file
|
||||
}
|
||||
|
||||
export function decodeDocumentUpload(filename: string, value: unknown) {
|
||||
if (typeof value !== "string" || !value.length) throw new Error("contentBase64 ist erforderlich.")
|
||||
if (value.length > Math.ceil(MCP_FILE_LIMIT / 3) * 4) throw new Error("MCP-Uploads sind auf 20 MiB begrenzt.")
|
||||
// Buffer.from silently accepts invalid characters; require canonical, padded Base64.
|
||||
if (value.length % 4 !== 0 || /[^A-Za-z0-9+/=]/.test(value)) throw new Error("contentBase64 muss gültiges Base64 ohne Data-URL-Präfix sein.")
|
||||
const body = Buffer.from(value, "base64")
|
||||
if (body.toString("base64") !== value) throw new Error("contentBase64 muss gültiges Base64 sein.")
|
||||
if (body.length > MCP_FILE_LIMIT) throw new Error("MCP-Uploads sind auf 20 MiB begrenzt.")
|
||||
const mimeType = validateScannerFile(filename, body)
|
||||
return { body, mimeType }
|
||||
}
|
||||
|
||||
export function documentDownloadUrl(id: string) {
|
||||
const path = `/api/mcp/files/${id}/content`
|
||||
const base = secrets.API_BASE_URL?.replace(/\/+$/, "")
|
||||
return base ? `${base}${path}` : path
|
||||
}
|
||||
@@ -2,12 +2,14 @@ import { accountingTools } from "./tools/accounting"
|
||||
import { masterdataTools } from "./tools/masterdata"
|
||||
import { organisationTools } from "./tools/organisation"
|
||||
import { wikiTools } from "./tools/wiki"
|
||||
import { documentTools } from "./tools/documents"
|
||||
|
||||
export const mcpTools = [
|
||||
...accountingTools,
|
||||
...masterdataTools,
|
||||
...organisationTools,
|
||||
...wikiTools,
|
||||
...documentTools,
|
||||
]
|
||||
|
||||
export const mcpToolMap = new Map(mcpTools.map((tool) => [tool.name, tool]))
|
||||
|
||||
@@ -27,6 +27,7 @@ import {
|
||||
statementAllocationUuidArg,
|
||||
} from "../statementAllocations"
|
||||
import { McpTool } from "../types"
|
||||
import { outgoingStatusTools } from "./outgoingStatus"
|
||||
|
||||
export { prepareStatementAllocationInput } from "../statementAllocations"
|
||||
|
||||
@@ -423,6 +424,7 @@ const assertStatementAllocationReferences = async (context: any, payload: Record
|
||||
}
|
||||
|
||||
export const accountingTools: McpTool[] = [
|
||||
...outgoingStatusTools,
|
||||
{
|
||||
name: "accounting.outgoing_documents.tax_types.list",
|
||||
title: "Steuertypen für Ausgangsbelege auflisten",
|
||||
|
||||
166
backend/src/mcp/tools/calendar.ts
Normal file
166
backend/src/mcp/tools/calendar.ts
Normal file
@@ -0,0 +1,166 @@
|
||||
import { and, desc, eq, ilike, inArray, isNull, lt, or, sql } from "drizzle-orm"
|
||||
import { authProfiles, customers, events, inventoryitemgroups, inventoryitems, projects, tenants, vehicles, vendors } from "../../../db/schema"
|
||||
import { insertHistoryItem } from "../../utils/history"
|
||||
import { arrayField, booleanField, dateField, idField, InputField, nullable, objectField, textField, uuidField } from "../masterdataFields"
|
||||
import { limitFromArgs, offsetFromArgs, paginatedResult, paginationProperties } from "../pagination"
|
||||
import { McpContext, McpTool } from "../types"
|
||||
|
||||
export const eventStates = ["Entwurf", "Final"]
|
||||
export const eventRepeatIntervals = ["Keine Wiederholung", "Täglich", "Wöchentlich", "2-wöchentlich", "Monatlich", "Jährlich"]
|
||||
const enumField = (values: string[]): InputField => ({
|
||||
schema: { type: "string", enum: values },
|
||||
parse(value, path) {
|
||||
if (typeof value !== "string" || !values.includes(value)) throw new Error(`${path}: ungültiger Wert`)
|
||||
return value
|
||||
},
|
||||
})
|
||||
export const eventDateTimeField: InputField = {
|
||||
schema: { type: "string", format: "date-time", description: "ISO-Zeitpunkt mit Zeitzone, z. B. 2026-10-15T09:00:00+02:00." },
|
||||
parse(value, path) {
|
||||
if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?(?:Z|[+-]\d{2}:\d{2})$/.test(value)) {
|
||||
throw new Error(`${path}: ISO-Zeitpunkt mit Zeitzone erwartet`)
|
||||
}
|
||||
dateField.parse(value.slice(0, 10), path)
|
||||
if (Number(value.slice(11, 13)) > 23 || Number(value.slice(14, 16)) > 59 || Number(value.slice(17, 19)) > 59
|
||||
|| !Number.isFinite(Date.parse(value))) throw new Error(`${path}: ungültiger Zeitpunkt`)
|
||||
return new Date(value)
|
||||
},
|
||||
}
|
||||
const idsField = (field: InputField): InputField => ({
|
||||
schema: { ...arrayField(field).schema, maxItems: 1000, uniqueItems: true },
|
||||
parse(value, path) {
|
||||
if (!Array.isArray(value) || value.length > 1000) throw new Error(`${path}: maximal 1000 IDs erwartet`)
|
||||
return [...new Set(arrayField(field).parse(value, path))]
|
||||
},
|
||||
})
|
||||
const eventFields = {
|
||||
name: textField(true), startDate: eventDateTimeField, endDate: nullable(eventDateTimeField),
|
||||
eventtype: nullable(textField(true)), quick: booleanField, state: enumField(eventStates), color: nullable(textField()),
|
||||
repeatInterval: enumField(eventRepeatIntervals), notes: nullable(textField()), link: nullable(textField()),
|
||||
project: nullable(idField), customer: nullable(idField), vendor: nullable(idField),
|
||||
profiles: idsField(uuidField), vehicles: idsField(idField), inventoryitems: idsField(idField), inventoryitemgroups: idsField(uuidField),
|
||||
}
|
||||
const listFields = {
|
||||
query: textField(), project: idField, customer: idField, vendor: idField, eventtype: textField(true),
|
||||
from: eventDateTimeField, to: eventDateTimeField, state: enumField(eventStates), quick: booleanField,
|
||||
repeatInterval: enumField(eventRepeatIntervals), profile: uuidField, vehicle: idField, inventoryitem: idField, inventoryitemgroup: uuidField,
|
||||
includeRecurring: { ...booleanField, schema: { type: "boolean", default: true, description: "Bei from auch früher begonnene Wiederholungsserien liefern. Das Ergebnis enthält Serien-Stammsätze, keine einzelnen Vorkommen." } },
|
||||
limit: { schema: paginationProperties.limit, parse: value => limitFromArgs({ limit: value }) },
|
||||
offset: { schema: paginationProperties.offset, parse: value => offsetFromArgs({ offset: value }) },
|
||||
}
|
||||
const eventScope = (tenantId: number, id: number) => and(eq(events.id, id), eq(events.tenant, tenantId), eq(events.archived, false))
|
||||
|
||||
export function prepareEventInput(action: "create" | "update" | "archive", args: Record<string, unknown>) {
|
||||
const input = objectField({ ...(action === "archive" ? {} : eventFields), ...(action === "create" ? {} : { id: idField }) }).parse(args, "arguments")
|
||||
for (const key of action === "create" ? ["name", "startDate"] : ["id"]) {
|
||||
if (input[key] === undefined) throw new Error(`${key} ist erforderlich`)
|
||||
}
|
||||
if (action === "update" && Object.keys(input).length === 1) throw new Error("Mindestens ein bearbeitbares Feld ist erforderlich")
|
||||
return input
|
||||
}
|
||||
|
||||
async function validateEventReferences(db: any, tenantId: number, input: Record<string, any>) {
|
||||
const references = [
|
||||
["project", projects], ["customer", customers], ["vendor", vendors], ["profiles", authProfiles],
|
||||
["vehicles", vehicles], ["inventoryitems", inventoryitems], ["inventoryitemgroups", inventoryitemgroups],
|
||||
] as const
|
||||
for (const [field, table] of references) {
|
||||
const value = input[field]
|
||||
const ids = value == null ? [] : Array.isArray(value) ? value : [value]
|
||||
if (!ids.length) continue
|
||||
const scope = table === authProfiles
|
||||
? and(eq(authProfiles.tenant_id, tenantId), eq(authProfiles.active, true), isNull(authProfiles.customer_for_portal))
|
||||
: and(eq((table as any).tenant, tenantId), eq((table as any).archived, false))
|
||||
const found = await db.select({ id: table.id }).from(table).where(and(inArray(table.id, ids), scope)).for("share")
|
||||
if (found.length !== ids.length) throw new Error(`${field}: verknüpfter Datensatz im aktiven Mandanten nicht verfügbar`)
|
||||
}
|
||||
}
|
||||
|
||||
async function mutateEvent(context: McpContext, action: "create" | "update" | "archive", args: Record<string, unknown>) {
|
||||
const { id, ...input } = prepareEventInput(action, args)
|
||||
return context.server.db.transaction(async tx => {
|
||||
let existing: typeof events.$inferSelect | undefined
|
||||
if (action !== "create") {
|
||||
;[existing] = await tx.select().from(events).where(eventScope(context.tenantId, id)).limit(1).for("update")
|
||||
if (!existing) throw new Error("Termin nicht gefunden oder archiviert")
|
||||
}
|
||||
const merged = { ...existing, ...input }
|
||||
if (action !== "archive") {
|
||||
if (merged.endDate && new Date(merged.endDate).getTime() < new Date(merged.startDate).getTime()) {
|
||||
throw new Error("endDate darf nicht vor startDate liegen")
|
||||
}
|
||||
await validateEventReferences(tx, context.tenantId, input)
|
||||
}
|
||||
const change = { ...(action === "archive" ? { archived: true } : input), updatedAt: new Date(), updatedBy: context.userId }
|
||||
const [event] = action === "create"
|
||||
? await tx.insert(events).values({ ...change, tenant: context.tenantId, name: input.name, startDate: input.startDate }).returning()
|
||||
: await tx.update(events).set(change).where(eventScope(context.tenantId, id)).returning()
|
||||
await insertHistoryItem({ ...context.server, db: tx } as any, { tenant_id: context.tenantId, created_by: context.userId,
|
||||
entity: "events", entityId: event.id, action: action === "create" ? "created" : action === "archive" ? "archived" : "updated",
|
||||
oldVal: existing, newVal: event })
|
||||
return action === "archive" ? { id: event.id, success: true, action: "archived" } : { event }
|
||||
})
|
||||
}
|
||||
|
||||
export const calendarTools: McpTool[] = [
|
||||
{
|
||||
name: "organisation.calendar.options", title: "Kalenderoptionen laden",
|
||||
description: "Lädt die konfigurierten Terminarten des Mandanten sowie erlaubte Status und Wiederholungen.",
|
||||
requiredPermissions: ["organisation.events.read"], inputSchema: objectField({}).schema,
|
||||
async handler(context, args) {
|
||||
objectField({}).parse(args, "arguments")
|
||||
const [tenant] = await context.server.db.select({ calendarConfig: tenants.calendarConfig }).from(tenants).where(eq(tenants.id, context.tenantId)).limit(1)
|
||||
if (!tenant) throw new Error("Mandant nicht gefunden")
|
||||
return { calendarConfig: tenant.calendarConfig, states: eventStates, repeatIntervals: eventRepeatIntervals }
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "organisation.events.list", title: "Kalendertermine auflisten",
|
||||
description: "Listet aktive Termine und Serien-Stammsätze mit Text-, Zeitraum-, Status- und Ressourcenfiltern. from/to begrenzen Überlappungen (to exklusiv); früher begonnene Serien werden standardmäßig mitgeliefert, ohne einzelne Wiederholungen auszurechnen.",
|
||||
requiredPermissions: ["organisation.events.read"], inputSchema: objectField(listFields).schema,
|
||||
async handler(context, args) {
|
||||
const input = objectField(listFields).parse(args, "arguments")
|
||||
if (input.from && input.to && input.from >= input.to) throw new Error("from muss vor to liegen")
|
||||
const conditions = [eq(events.tenant, context.tenantId), eq(events.archived, false)]
|
||||
if (input.query) {
|
||||
const query = `%${input.query.replace(/[\\%_]/g, "\\$&")}%`
|
||||
conditions.push(or(ilike(events.name, query), ilike(events.notes, query), ilike(events.link, query)))
|
||||
}
|
||||
for (const key of ["project", "customer", "vendor", "eventtype", "state", "quick", "repeatInterval"]) {
|
||||
if (input[key] !== undefined) conditions.push(eq(events[key], input[key]))
|
||||
}
|
||||
for (const [key, column] of [["profile", events.profiles], ["vehicle", events.vehicles], ["inventoryitem", events.inventoryitems], ["inventoryitemgroup", events.inventoryitemgroups]] as const) {
|
||||
if (input[key] !== undefined) conditions.push(sql`${column} @> ${JSON.stringify([input[key]])}::jsonb`)
|
||||
}
|
||||
if (input.to) conditions.push(lt(events.startDate, input.to))
|
||||
if (input.from) conditions.push(or(
|
||||
sql`${events.endDate} > ${input.from.toISOString()}::timestamptz`,
|
||||
sql`${events.startDate} >= ${input.from.toISOString()}::timestamptz`,
|
||||
input.includeRecurring !== false ? inArray(events.repeatInterval, eventRepeatIntervals.slice(1)) : undefined,
|
||||
))
|
||||
const rows = await context.server.db.select().from(events).where(and(...conditions)).orderBy(desc(events.startDate), events.id)
|
||||
.limit(limitFromArgs(input) + 1).offset(offsetFromArgs(input))
|
||||
return paginatedResult(rows, input)
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "organisation.events.get", title: "Kalendertermin laden", description: "Lädt einen aktiven Termin einschließlich Wiederholung und Ressourcenzuordnungen.",
|
||||
requiredPermissions: ["organisation.events.read"], inputSchema: { ...objectField({ id: idField }).schema, required: ["id"] },
|
||||
async handler(context, args) {
|
||||
const input = prepareEventInput("archive", args)
|
||||
const [event] = await context.server.db.select().from(events).where(eventScope(context.tenantId, input.id)).limit(1)
|
||||
if (!event) throw new Error("Termin nicht gefunden oder archiviert")
|
||||
return { event }
|
||||
},
|
||||
},
|
||||
...(["create", "update", "archive"] as const).map(action => ({
|
||||
name: `organisation.events.${action}`, title: action === "create" ? "Kalendertermin erstellen" : action === "update" ? "Kalendertermin bearbeiten" : "Kalendertermin archivieren",
|
||||
description: action === "create" ? "Erstellt einen Termin, standardmäßig Final und ohne Wiederholung. Zeitpunkte benötigen eine explizite Zeitzone."
|
||||
: action === "update" ? "Ändert nur angegebene Felder. Ressourcenlisten werden ersetzt; null leert optionale Felder. Bei Wiederholungen wird die gesamte Serie geändert."
|
||||
: "Archiviert einen Termin bzw. seine gesamte Wiederholungsserie.",
|
||||
requiredPermissions: ["organisation.events.write"],
|
||||
inputSchema: { ...objectField({ ...(action === "archive" ? {} : eventFields), ...(action === "create" ? {} : { id: idField }) }).schema,
|
||||
required: action === "create" ? ["name", "startDate"] : ["id"] },
|
||||
handler: (context: McpContext, args: Record<string, unknown>) => mutateEvent(context, action, args),
|
||||
})),
|
||||
]
|
||||
148
backend/src/mcp/tools/documents.ts
Normal file
148
backend/src/mcp/tools/documents.ts
Normal file
@@ -0,0 +1,148 @@
|
||||
import { and, asc, desc, eq, ilike, isNull, or } from "drizzle-orm"
|
||||
import { files, filetags, folders, scannerInboxDocuments } from "../../../db/schema"
|
||||
import { assignmentKinds, assignmentOptions, assignmentTargets, FileAssignments } from "../../modules/scanner-inbox-assignments"
|
||||
import { createScannerInboxService, ScannerInboxService } from "../../modules/scanner-inbox.service"
|
||||
import { loadFileBuffer } from "../../utils/fileBuffer"
|
||||
import { assertInternalDocumentAccess, decodeDocumentUpload, documentDownloadUrl, fileMetadataColumns, loadDocumentFile, MCP_FILE_LIMIT } from "../documentFiles"
|
||||
import { InputField, idField, nullable, numericField, objectField, textField, uuidField } from "../masterdataFields"
|
||||
import { limitFromArgs, offsetFromArgs, paginatedResult, paginationProperties } from "../pagination"
|
||||
import { McpContext, McpTool } from "../types"
|
||||
|
||||
const searchField: InputField = {
|
||||
schema: { type: "string", maxLength: 200, description: "Suchtext im Dateinamen bzw. Namen." },
|
||||
parse(value, path) {
|
||||
const text = textField().parse(value, path)
|
||||
if (text.length > 200) throw new Error(`${path}: maximal 200 Zeichen`)
|
||||
return text
|
||||
},
|
||||
}
|
||||
const filenameField: InputField = {
|
||||
schema: { type: "string", minLength: 1, maxLength: 200 },
|
||||
parse: (value, path) => textField(true).parse(value, path),
|
||||
}
|
||||
const paginationFields = {
|
||||
limit: { ...numericField(true, 1, 100), schema: paginationProperties.limit },
|
||||
offset: { ...numericField(true, 0), schema: paginationProperties.offset },
|
||||
}
|
||||
const assignmentFields = Object.fromEntries(Object.entries(assignmentTargets).map(([key, target]) =>
|
||||
[key, nullable(target.uuid ? uuidField : idField)]))
|
||||
const assignmentsField = objectField(assignmentFields)
|
||||
const kindField: InputField = {
|
||||
schema: { type: "string", enum: Object.keys(assignmentTargets) },
|
||||
parse(value) {
|
||||
if (typeof value !== "string" || !Object.prototype.hasOwnProperty.call(assignmentTargets, value)) throw new Error("Unbekannte Zuordnungsart.")
|
||||
return value
|
||||
},
|
||||
}
|
||||
const formatField: InputField = {
|
||||
schema: { type: "string", enum: ["url", "base64"], default: "url" },
|
||||
parse(value) {
|
||||
if (value !== "url" && value !== "base64") throw new Error("format muss url oder base64 sein.")
|
||||
return value
|
||||
},
|
||||
}
|
||||
const like = (value: string) => `%${value.replace(/[\\%_]/g, "\\$&")}%`
|
||||
|
||||
type Dependencies = {
|
||||
inbox?: (context: McpContext) => ScannerInboxService
|
||||
readFile?: typeof loadFileBuffer
|
||||
}
|
||||
|
||||
export function createDocumentTools(dependencies: Dependencies = {}): McpTool[] {
|
||||
const inbox = dependencies.inbox || ((context: McpContext) => createScannerInboxService(context.server.db))
|
||||
const readFile = dependencies.readFile || loadFileBuffer
|
||||
const tool = (name: string, title: string, description: string, write: boolean, fields: Record<string, InputField>,
|
||||
required: string[], handler: McpTool["handler"]): McpTool => ({
|
||||
name: `documents.${name}`, title, description,
|
||||
requiredPermissions: [write ? "documents.write" : "documents.read"],
|
||||
inputSchema: { ...objectField(fields).schema, required },
|
||||
async handler(context, args) {
|
||||
const input = objectField(fields).parse(args, "arguments")
|
||||
for (const key of required) if (input[key] === undefined) throw new Error(`${key} ist erforderlich.`)
|
||||
await assertInternalDocumentAccess(context)
|
||||
return handler(context, input)
|
||||
},
|
||||
})
|
||||
return [
|
||||
tool("inbox.list", "Dokumentenablage auflisten", "Listet offene Dokumente der Dokumentenablage mit Status der KI-Ablagevorschläge. id ist die Datei-UUID.", false,
|
||||
{ search: searchField, ...paginationFields }, [], async (context, args) => {
|
||||
const rows = await context.server.db.select({ id: files.id, name: scannerInboxDocuments.remoteFilename,
|
||||
mimeType: files.mimeType, size: files.size, receivedAt: scannerInboxDocuments.receivedAt,
|
||||
suggestionStatus: scannerInboxDocuments.suggestionStatus })
|
||||
.from(scannerInboxDocuments).innerJoin(files, eq(files.id, scannerInboxDocuments.fileId))
|
||||
.where(and(eq(scannerInboxDocuments.tenantId, context.tenantId), eq(files.tenant, context.tenantId),
|
||||
isNull(scannerInboxDocuments.filedAt), eq(files.archived, false),
|
||||
args.search ? ilike(scannerInboxDocuments.remoteFilename, like(args.search as string)) : undefined))
|
||||
.orderBy(desc(scannerInboxDocuments.receivedAt), desc(files.id)).limit(limitFromArgs(args) + 1).offset(offsetFromArgs(args))
|
||||
return paginatedResult(rows, args)
|
||||
}),
|
||||
tool("inbox.count", "Offene Dokumente zählen", "Zählt nicht archivierte, noch nicht abgelegte Dokumente des Mandanten.", false, {}, [],
|
||||
context => inbox(context).openCount(context.tenantId)),
|
||||
...([ ["folders", folders], ["types", filetags] ] as const).map(([name, table]) =>
|
||||
tool(`${name}.list`, name === "folders" ? "Ablageordner auflisten" : "Dokumenttypen auflisten",
|
||||
"Listet verfügbare Ablageziele. Ordner enthalten parent, standardFiletype und standardFiletypeIsOptional.", false,
|
||||
{ search: searchField, ...paginationFields }, [], async (context, args) => {
|
||||
const rows = await context.server.db.select().from(table)
|
||||
.where(and(eq(table.tenant, context.tenantId), eq(table.archived, false), args.search ? ilike(table.name, like(args.search as string)) : undefined))
|
||||
.orderBy(asc(table.name), asc(table.id)).limit(limitFromArgs(args) + 1).offset(offsetFromArgs(args))
|
||||
return paginatedResult(rows, args)
|
||||
})),
|
||||
tool("assignment_kinds.list", "Zuordnungsarten auflisten", "Zeigt die unterstützten Zuordnungsarten, beispielsweise Projekt, Kunde, Eingangsrechnung oder Ausgangsbeleg.", false, {}, [],
|
||||
async () => ({ kinds: assignmentKinds })),
|
||||
tool("assignments.search", "Zuordnungsziele suchen", "Sucht verfügbare Datensätze einer Zuordnungsart im aktiven Mandanten.", false,
|
||||
{ kind: kindField, search: searchField, ...paginationFields }, ["kind"], async (context, args) =>
|
||||
paginatedResult(await assignmentOptions(context.server.db, context.tenantId, args.kind as string, args.search as string || "",
|
||||
limitFromArgs(args) + 1, offsetFromArgs(args)), args)),
|
||||
tool("inbox.assignments.get", "Dokumentzuordnungen laden", "Lädt bestehende Zuordnungen eines offenen Dokuments aus der Dokumentenablage.", false,
|
||||
{ id: uuidField }, ["id"], async (context, args) => ({ assignments: await inbox(context).getAssignments(context.tenantId, args.id as string) })),
|
||||
tool("inbox.suggestion.get", "Ablagevorschlag laden", "Lädt Status und Vorschlag der KI-Erkennung. Ein Vorschlag legt das Dokument noch nicht ab.", false,
|
||||
{ id: uuidField }, ["id"], (context, args) => inbox(context).getSuggestion(context.tenantId, args.id as string)),
|
||||
tool("inbox.suggestion.refresh", "Ablagevorschlag neu anfordern", "Stellt die KI-Erkennung erneut in die Warteschlange. Den Status anschließend mit documents.inbox.suggestion.get abfragen.", true,
|
||||
{ id: uuidField }, ["id"], (context, args) => inbox(context).queueSuggestion(context.tenantId, args.id as string)),
|
||||
tool("inbox.file", "Dokument ablegen", "Legt ein offenes Dokument in einem Ordner (folder: null für Hauptebene) mit Dokumenttyp ab. Optionale Zuordnungen ändern nur angegebene Felder; null entfernt eine Zuordnung. Feste Ordnertypen werden geprüft.", true,
|
||||
{ id: uuidField, folder: nullable(uuidField), type: uuidField, assignments: assignmentsField }, ["id", "folder", "type"],
|
||||
(context, args) => inbox(context).fileDocument(context.tenantId, context.userId, args.id as string, args.folder as string | null,
|
||||
args.type as string, args.assignments as FileAssignments)),
|
||||
tool("inbox.archive", "Dokument archivieren", "Archiviert ein offenes Dokument aus der Dokumentenablage. Bereits abgelegte Dokumente werden abgewiesen.", true,
|
||||
{ id: uuidField }, ["id"], async (context, args) => {
|
||||
await inbox(context).archiveDocument(context.tenantId, context.userId, args.id as string)
|
||||
return { id: args.id, success: true, action: "archived" }
|
||||
}),
|
||||
tool("files.list", "Gespeicherte Dateien suchen", "Listet nicht archivierte Dateien einschließlich PDFs zu Eingangsrechnungen und Ausgangsbelegen. Filter werden kombiniert; folder: null sucht auf der Hauptebene.", false,
|
||||
{ search: searchField, folder: nullable(uuidField), type: uuidField, mimeType: textField(true), ...assignmentFields, ...paginationFields }, [],
|
||||
async (context, args) => {
|
||||
const conditions = [eq(files.tenant, context.tenantId), eq(files.archived, false)]
|
||||
if (args.search) conditions.push(or(ilike(files.name, like(args.search as string)), ilike(files.extractedText, like(args.search as string))))
|
||||
for (const key of ["folder", "type", "mimeType", ...Object.keys(assignmentFields)]) {
|
||||
if (args[key] !== undefined) conditions.push(args[key] === null ? isNull(files[key]) : eq(files[key], args[key]))
|
||||
}
|
||||
const rows = await context.server.db.select(fileMetadataColumns).from(files).where(and(...conditions))
|
||||
.orderBy(desc(files.createdAt), files.id).limit(limitFromArgs(args) + 1).offset(offsetFromArgs(args))
|
||||
return paginatedResult(rows, args)
|
||||
}),
|
||||
tool("files.get", "Dateidetails laden", "Lädt Metadaten, Zuordnungs-IDs und bereits extrahierten Text einer Datei. Binärinhalt über documents.files.download abrufen.", false,
|
||||
{ id: uuidField }, ["id"], async (context, args) => {
|
||||
const { path, ...file } = await loadDocumentFile(context, args.id as string)
|
||||
return { file }
|
||||
}),
|
||||
tool("files.download", "PDF oder Datei herunterladen", "Liefert standardmäßig eine Download-URL für die Originaldatei. GET benötigt denselben Authorization: Bearer MCP-Token. Alternativ format: base64 für Dateiinhalt bis 20 MiB direkt im Ergebnis; keine PDF-Konvertierung.", false,
|
||||
{ id: uuidField, format: formatField }, ["id"], async (context, args) => {
|
||||
const file = await loadDocumentFile(context, args.id as string)
|
||||
if (!file.path) throw new Error("Kein Dateiinhalt verfügbar.")
|
||||
const metadata = { id: file.id, filename: file.name, mimeType: file.mimeType, size: file.size }
|
||||
if (args.format !== "base64") return { ...metadata, url: documentDownloadUrl(file.id), method: "GET", authentication: "Bearer" }
|
||||
if (file.size > MCP_FILE_LIMIT) throw new Error("Die Datei ist für Base64 zu groß. Bitte format: url verwenden.")
|
||||
const body = await readFile(file.path, MCP_FILE_LIMIT)
|
||||
return { ...metadata, size: body.length, contentBase64: body.toString("base64") }
|
||||
}),
|
||||
tool("files.upload", "PDF oder Scan hochladen", "Lädt eine vollständige PDF-, JPEG-, PNG- oder TIFF-Datei als Base64 (maximal 20 MiB, ohne Data-URL-Präfix) in die Dokumentenablage. Danach documents.inbox.file verwenden. Gleicher Dateiname und Inhalt werden nicht erneut angelegt; anderer Inhalt unter demselben Namen wird abgewiesen.", true,
|
||||
{ filename: filenameField, contentBase64: { schema: { type: "string", minLength: 1, maxLength: Math.ceil(MCP_FILE_LIMIT / 3) * 4 }, parse: value => value } },
|
||||
["filename", "contentBase64"], async (context, args) => {
|
||||
const { body, mimeType } = decodeDocumentUpload(args.filename as string, args.contentBase64)
|
||||
const result = await inbox(context).upload(context.tenantId, context.userId, args.filename as string, body)
|
||||
return { ...result, filename: args.filename, mimeType, size: body.length }
|
||||
}),
|
||||
]
|
||||
}
|
||||
|
||||
export const documentTools = createDocumentTools()
|
||||
@@ -1,9 +1,10 @@
|
||||
import { limitFromArgs, offsetFromArgs, paginatedResult, paginationProperties } from "../pagination"
|
||||
import { and, desc, eq, ilike, or } from "drizzle-orm"
|
||||
import { customers, events, plants, projects, tasks } from "../../../db/schema"
|
||||
import { customers, plants, projects, tasks } from "../../../db/schema"
|
||||
import { insertHistoryItem } from "../../utils/history"
|
||||
import { activateProjectPhase } from "../projectPhases"
|
||||
import { McpTool } from "../types"
|
||||
import { calendarTools } from "./calendar"
|
||||
|
||||
|
||||
const stringArg = (args: Record<string, unknown>, key: string) => {
|
||||
@@ -17,6 +18,7 @@ const numberArg = (args: Record<string, unknown>, key: string) => {
|
||||
}
|
||||
|
||||
export const organisationTools: McpTool[] = [
|
||||
...calendarTools,
|
||||
{
|
||||
name: "organisation.customers.search",
|
||||
title: "Kunden suchen",
|
||||
@@ -238,51 +240,6 @@ export const organisationTools: McpTool[] = [
|
||||
return paginatedResult(rows, args)
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "organisation.events.list",
|
||||
title: "Termine auflisten",
|
||||
description: "Listet Termine des aktiven Mandanten mit optionalen Projekt- oder Kundenfiltern.",
|
||||
requiredPermissions: ["organisation.events.read"],
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
query: { type: "string", description: "Suchtext für Name, Notizen oder Link." },
|
||||
project: { type: "number" },
|
||||
customer: { type: "number" },
|
||||
eventtype: { type: "string" },
|
||||
...paginationProperties,
|
||||
},
|
||||
},
|
||||
async handler(context, args) {
|
||||
const conditions = [eq(events.tenant, context.tenantId)]
|
||||
const query = stringArg(args, "query")
|
||||
const project = numberArg(args, "project")
|
||||
const customer = numberArg(args, "customer")
|
||||
const eventtype = stringArg(args, "eventtype")
|
||||
|
||||
if (query) {
|
||||
conditions.push(or(
|
||||
ilike(events.name, `%${query}%`),
|
||||
ilike(events.notes, `%${query}%`),
|
||||
ilike(events.link, `%${query}%`)
|
||||
))
|
||||
}
|
||||
if (project) conditions.push(eq(events.project, project))
|
||||
if (customer) conditions.push(eq(events.customer, customer))
|
||||
if (eventtype) conditions.push(eq(events.eventtype, eventtype))
|
||||
conditions.push(eq(events.archived, false))
|
||||
|
||||
const rows = await context.server.db
|
||||
.select()
|
||||
.from(events)
|
||||
.where(and(...conditions))
|
||||
.orderBy(desc(events.startDate), events.id)
|
||||
.limit(limitFromArgs(args) + 1)
|
||||
.offset(offsetFromArgs(args))
|
||||
|
||||
return paginatedResult(rows, args)
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "organisation.tasks.list",
|
||||
title: "Aufgaben auflisten",
|
||||
|
||||
130
backend/src/mcp/tools/outgoingStatus.ts
Normal file
130
backend/src/mcp/tools/outgoingStatus.ts
Normal file
@@ -0,0 +1,130 @@
|
||||
import { and, desc, eq, inArray, ne } from "drizzle-orm"
|
||||
import { createddocuments, statementallocations } from "../../../db/schema"
|
||||
import { booleanField, idField, InputField, objectField, textField } from "../masterdataFields"
|
||||
import { limitFromArgs, offsetFromArgs, paginatedResult, paginationProperties } from "../pagination"
|
||||
import { McpContext, McpTool } from "../types"
|
||||
|
||||
const paymentStates = ["Offen", "Teilbezahlt", "Bezahlt", "Überbezahlt"]
|
||||
const paymentField: InputField = {
|
||||
schema: { type: "string", enum: paymentStates },
|
||||
parse(value) {
|
||||
if (typeof value !== "string" || !paymentStates.includes(value)) throw new Error("Unbekannter Zahlungsstatus")
|
||||
return value
|
||||
},
|
||||
}
|
||||
const listFields = {
|
||||
state: textField(true), type: textField(true), customer: idField, project: idField,
|
||||
cancelled: booleanField, paymentStatus: paymentField,
|
||||
limit: { schema: paginationProperties.limit, parse: value => limitFromArgs({ limit: value }) },
|
||||
offset: { schema: paginationProperties.offset, parse: value => offsetFromArgs({ offset: value }) },
|
||||
}
|
||||
const money = (value: number) => Number(value.toFixed(2))
|
||||
|
||||
function documentAmount(document: any, advanceInvoices: any[]) {
|
||||
let net = 0, tax19 = 0, tax7 = 0, advanceAmount = 0
|
||||
for (const row of document.rows || []) {
|
||||
if (["pagebreak", "title", "text"].includes(row.mode)) continue
|
||||
const values = [row.quantity, row.price, row.discountPercent, row.taxPercent].map(value => Number(value ?? 0))
|
||||
if (!values.every(Number.isFinite)) throw new Error(`Beleg ${document.id}: ungültiger Positionsbetrag`)
|
||||
const [quantity, price, discount, tax] = values
|
||||
const rowNet = Number((quantity * price * (1 - discount / 100)).toFixed(3))
|
||||
net += rowNet
|
||||
if (tax === 19) tax19 += rowNet * 0.19
|
||||
if (tax === 7) tax7 += rowNet * 0.07
|
||||
}
|
||||
for (const id of document.usedAdvanceInvoices || []) {
|
||||
const row = advanceInvoices.find(invoice => invoice.id === id)?.rows?.find(row => row.advanceInvoiceData)
|
||||
if (row) advanceAmount += Number(row.price) * ((100 + Number(row.taxPercent)) / 100)
|
||||
}
|
||||
// Match the outgoing-document screen (useSum): round net, 19% and 7% separately.
|
||||
// Aggregating both tax buckets before rounding can falsely report a one-cent debt.
|
||||
return money(money(net) + money(tax19) + money(tax7) - advanceAmount)
|
||||
}
|
||||
|
||||
export function outgoingDocumentStatus(document: any, paidAmount: number, cancellations: any[], advanceInvoices: any[]) {
|
||||
const amount = documentAmount(document, advanceInvoices)
|
||||
if (![amount, paidAmount].every(Number.isFinite)) throw new Error(`Beleg ${document.id}: Betrag kann nicht berechnet werden`)
|
||||
const openAmount = money(amount - paidAmount)
|
||||
const cancelled = cancellations.length > 0
|
||||
const applicable = document.state === "Gebucht" && ["invoices", "advanceInvoices"].includes(document.type) && !cancelled
|
||||
// Signed invoices and refunds use the same payment-direction comparison.
|
||||
const direction = Math.sign(amount) || 1
|
||||
const paymentStatus = !applicable ? null : openAmount === 0 ? "Bezahlt"
|
||||
: openAmount * direction < 0 ? "Überbezahlt" : paidAmount * direction > 0 ? "Teilbezahlt" : "Offen"
|
||||
return {
|
||||
id: document.id, type: document.type, documentNumber: document.documentNumber, documentDate: document.documentDate,
|
||||
state: document.state, customer: document.customer, project: document.project,
|
||||
cancelled, cancellationDocuments: cancellations.map(({ id, documentNumber }) => ({ id, documentNumber })),
|
||||
paymentStatus, amount, paidAmount: money(paidAmount), openAmount,
|
||||
}
|
||||
}
|
||||
|
||||
async function statusesFor(context: McpContext, documents: Array<typeof createddocuments.$inferSelect>) {
|
||||
if (!documents.length) return []
|
||||
const ids = documents.map(document => document.id)
|
||||
const advanceIds = [...new Set(documents.flatMap(document => Array.isArray(document.usedAdvanceInvoices)
|
||||
? document.usedAdvanceInvoices.filter(id => typeof id === "number" && Number.isSafeInteger(id) && id > 0) as number[] : []))]
|
||||
const [allocations, cancellations, advances] = await Promise.all([
|
||||
context.server.db.select({ createddocument: statementallocations.createddocument, amount: statementallocations.amount }).from(statementallocations)
|
||||
.where(and(eq(statementallocations.tenant, context.tenantId), eq(statementallocations.archived, false), inArray(statementallocations.createddocument, ids))),
|
||||
context.server.db.select({ id: createddocuments.id, createddocument: createddocuments.createddocument, documentNumber: createddocuments.documentNumber }).from(createddocuments)
|
||||
.where(and(eq(createddocuments.tenant, context.tenantId), eq(createddocuments.archived, false), eq(createddocuments.type, "cancellationInvoices"),
|
||||
ne(createddocuments.state, "Entwurf"), inArray(createddocuments.createddocument, ids))).orderBy(createddocuments.id),
|
||||
advanceIds.length ? context.server.db.select().from(createddocuments)
|
||||
.where(and(eq(createddocuments.tenant, context.tenantId), eq(createddocuments.archived, false), inArray(createddocuments.id, advanceIds))) : [],
|
||||
])
|
||||
return documents.map(document => outgoingDocumentStatus(document,
|
||||
allocations.filter(allocation => allocation.createddocument === document.id).reduce((sum, allocation) => sum + Number(allocation.amount), 0),
|
||||
cancellations.filter(cancellation => cancellation.createddocument === document.id), advances))
|
||||
}
|
||||
|
||||
export const outgoingStatusTools: McpTool[] = [
|
||||
{
|
||||
name: "accounting.outgoing_documents.status.get", title: "Ausgangsbelegstatus laden",
|
||||
description: "Lädt Buchungs-, Zahlungs- und Stornostatus mit Gesamtbetrag, zugeordneten Zahlungen und offenem Betrag. Zahlungsstatus gilt für gebuchte, nicht stornierte Rechnungen und Abschlagsrechnungen; sonst null. Ändert keine Belege oder Buchungen.",
|
||||
requiredPermissions: ["accounting.outgoing_documents.read"],
|
||||
inputSchema: { ...objectField({ id: idField }).schema, required: ["id"] },
|
||||
async handler(context, args) {
|
||||
const { id } = objectField({ id: idField }).parse(args, "arguments")
|
||||
if (id === undefined) throw new Error("id ist erforderlich")
|
||||
const documents = await context.server.db.select().from(createddocuments)
|
||||
.where(and(eq(createddocuments.id, id), eq(createddocuments.tenant, context.tenantId), eq(createddocuments.archived, false))).limit(1)
|
||||
if (!documents.length) throw new Error("Ausgangsbeleg nicht gefunden oder archiviert")
|
||||
const [status] = await statusesFor(context, documents)
|
||||
return { status }
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "accounting.outgoing_documents.status.list", title: "Ausgangsbelege nach Status filtern",
|
||||
description: "Listet Status und Beträge aktiver Ausgangsbelege. Kombinierbare Filter: state (z. B. Entwurf/Gebucht), paymentStatus, cancelled, type, customer und project. Statusfilter werden vor der Pagination angewendet. Archivierte Zahlungen und Stornos zählen nicht.",
|
||||
requiredPermissions: ["accounting.outgoing_documents.read"], inputSchema: objectField(listFields).schema,
|
||||
async handler(context, args) {
|
||||
const input = objectField(listFields).parse(args, "arguments")
|
||||
const conditions = [eq(createddocuments.tenant, context.tenantId), eq(createddocuments.archived, false)]
|
||||
for (const key of ["state", "type", "customer", "project"]) {
|
||||
if (input[key] !== undefined) conditions.push(eq(createddocuments[key], input[key]))
|
||||
}
|
||||
const limit = limitFromArgs(input)
|
||||
const offset = offsetFromArgs(input)
|
||||
const query = (size: number, start: number) => context.server.db.select().from(createddocuments).where(and(...conditions))
|
||||
.orderBy(desc(createddocuments.createdAt), createddocuments.id).limit(size).offset(start)
|
||||
if (input.paymentStatus === undefined && input.cancelled === undefined) {
|
||||
return paginatedResult(await statusesFor(context, await query(limit + 1, offset)), input)
|
||||
}
|
||||
// Derived statuses need related payments/credit documents. Scan bounded batches so filtering
|
||||
// happens before pagination without loading an entire tenant's documents into memory.
|
||||
const rows: Awaited<ReturnType<typeof statusesFor>> = []
|
||||
let matched = 0
|
||||
for (let start = 0; ; start += 100) {
|
||||
const documents = await query(100, start)
|
||||
for (const status of await statusesFor(context, documents)) {
|
||||
if (input.paymentStatus !== undefined && status.paymentStatus !== input.paymentStatus) continue
|
||||
if (input.cancelled !== undefined && status.cancelled !== input.cancelled) continue
|
||||
if (matched++ >= offset) rows.push(status)
|
||||
if (rows.length > limit) return paginatedResult(rows, input)
|
||||
}
|
||||
if (documents.length < 100) return paginatedResult(rows, input)
|
||||
}
|
||||
},
|
||||
},
|
||||
]
|
||||
@@ -57,10 +57,13 @@ const adminPermissions = [
|
||||
"organisation.projects.write",
|
||||
"organisation.plants.read",
|
||||
"organisation.events.read",
|
||||
"organisation.events.write",
|
||||
"organisation.tasks.read",
|
||||
"organisation.tasks.write",
|
||||
"wiki.read",
|
||||
"wiki.write",
|
||||
"documents.read",
|
||||
"documents.write",
|
||||
]
|
||||
|
||||
const defaultTaxTypes = [
|
||||
|
||||
@@ -36,13 +36,13 @@ export function assignmentId(kind: string, id: unknown) {
|
||||
return Number(id)
|
||||
}
|
||||
type Reader = Pick<FastifyInstance["db"], "select">
|
||||
export async function assignmentOptions(db: Reader, tenantId: number, kind: string, search = "") {
|
||||
export async function assignmentOptions(db: Reader, tenantId: number, kind: string, search = "", limit = 100, offset = 0) {
|
||||
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)
|
||||
.orderBy(asc(target.name), asc(target.id)).limit(limit).offset(offset)
|
||||
return rows.map(row => ({ id: String(row.id), name: row.name }))
|
||||
}
|
||||
export async function currentAssignments(db: Reader, tenantId: number, file: Record<string, unknown>) {
|
||||
|
||||
@@ -264,32 +264,34 @@ export function createScannerInboxService(db: FastifyInstance["db"], storage: Sc
|
||||
// Epson probes writability with an empty PUT. No file, receipt or reservation is stored.
|
||||
})
|
||||
}
|
||||
const accept = async (identity: ScannerIdentity, filename: string, body: Buffer, onlyIfNew = false) => {
|
||||
const storeDocument = async (tenantId: number, filename: string, body: Buffer,
|
||||
authorize: (tx: Pick<FastifyInstance["db"], "select">) => Promise<void>, onlyIfNew = false, userId?: string) => {
|
||||
const contentType = validateScannerFile(filename, body)
|
||||
const checksum = digest(body)
|
||||
let uploadedKey: string | undefined
|
||||
try {
|
||||
return await db.transaction(async tx => {
|
||||
await assertWritable(tx, identity)
|
||||
await authorize(tx)
|
||||
|
||||
// Serialise retries across processes; a lost HTTP response must not duplicate a document.
|
||||
await tx.execute(sql`SELECT pg_advisory_xact_lock(hashtextextended(${`${identity.tenantId}:${filename}`}, 0))`)
|
||||
await tx.execute(sql`SELECT pg_advisory_xact_lock(hashtextextended(${`${tenantId}:${filename}`}, 0))`)
|
||||
const [existing] = await tx.select().from(scannerInboxDocuments).where(and(
|
||||
eq(scannerInboxDocuments.tenantId, identity.tenantId), eq(scannerInboxDocuments.remoteFilename, filename),
|
||||
eq(scannerInboxDocuments.tenantId, tenantId), eq(scannerInboxDocuments.remoteFilename, filename),
|
||||
)).limit(1)
|
||||
if (existing) {
|
||||
if (onlyIfNew) throw scannerError(412, "Der Dateiname ist bereits vorhanden.")
|
||||
if (existing.checksum !== checksum) throw scannerError(409, "Der Dateiname ist bereits vergeben. Bitte einen eindeutigen Dateinamen verwenden.")
|
||||
return { created: false, checksum }
|
||||
return { id: existing.fileId, created: false, checksum }
|
||||
}
|
||||
const id = randomUUID()
|
||||
const key = `${identity.tenantId}/filesbyid/${id}/${sanitizeFilename(filename)}`
|
||||
const key = `${tenantId}/filesbyid/${id}/${sanitizeFilename(filename)}`
|
||||
uploadedKey = key
|
||||
await storage.put(key, body, contentType)
|
||||
// Bypass saveFile's text extraction: the inbox only stores the original document.
|
||||
await tx.insert(files).values({ id, tenant: identity.tenantId, name: filename, path: key, mimeType: contentType, size: body.length })
|
||||
await tx.insert(scannerInboxDocuments).values({ fileId: id, tenantId: identity.tenantId, remoteFilename: filename, checksum })
|
||||
return { created: true, checksum }
|
||||
await tx.insert(files).values({ id, tenant: tenantId, name: filename, path: key, mimeType: contentType, size: body.length,
|
||||
...(userId ? { createdBy: userId } : {}) })
|
||||
await tx.insert(scannerInboxDocuments).values({ fileId: id, tenantId, remoteFilename: filename, checksum })
|
||||
return { id, created: true, checksum }
|
||||
})
|
||||
} catch (error) {
|
||||
if (uploadedKey) {
|
||||
@@ -299,8 +301,17 @@ export function createScannerInboxService(db: FastifyInstance["db"], storage: Sc
|
||||
throw error
|
||||
}
|
||||
}
|
||||
const accept = (identity: ScannerIdentity, filename: string, body: Buffer, onlyIfNew = false) =>
|
||||
storeDocument(identity.tenantId, filename, body, tx => assertWritable(tx, identity), onlyIfNew)
|
||||
// Internal callers authorize the user before invoking this method; scanner credentials remain separate.
|
||||
const upload = (tenantId: number, userId: string, filename: string, body: Buffer) =>
|
||||
storeDocument(tenantId, filename, body, 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.")
|
||||
}, false, userId)
|
||||
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), archiveDocument, fileDocument, probe, accept }
|
||||
getAssignments, assignmentOptions: (tenantId: number, kind: string, search: string) => assignmentOptions(db, tenantId, kind, search), archiveDocument, fileDocument, probe, accept, upload }
|
||||
}
|
||||
|
||||
export type ScannerInboxService = ReturnType<typeof createScannerInboxService>
|
||||
|
||||
@@ -33,6 +33,7 @@ import { requireSystemAdmin } from "../utils/requireSystemAdmin";
|
||||
import { buildSystemStatus } from "../modules/system-status.service";
|
||||
import { s3 } from "../utils/s3";
|
||||
import { secrets } from "../utils/secrets";
|
||||
import { getPortalLoginUrl } from "../utils/portalUrl";
|
||||
|
||||
export default async function adminRoutes(server: FastifyInstance) {
|
||||
await server.register(multipart, {
|
||||
@@ -931,6 +932,17 @@ export default async function adminRoutes(server: FastifyInstance) {
|
||||
return reply.code(400).send({ error: "Customer has no email address" });
|
||||
}
|
||||
|
||||
let portalUrl: string;
|
||||
try {
|
||||
portalUrl = getPortalLoginUrl({
|
||||
portalDomain: tenantRecord?.portalDomain,
|
||||
publicUrl: process.env.FEDEO_PUBLIC_URL,
|
||||
apiBaseUrl: secrets.API_BASE_URL,
|
||||
});
|
||||
} catch (err: any) {
|
||||
return reply.code(503).send({ error: err.message });
|
||||
}
|
||||
|
||||
const generatedPassword = generateRandomPassword(14);
|
||||
const passwordHash = await hashPassword(generatedPassword);
|
||||
|
||||
@@ -1086,8 +1098,6 @@ export default async function adminRoutes(server: FastifyInstance) {
|
||||
});
|
||||
}
|
||||
|
||||
const portalUrl = tenantRecord?.portalDomain ? `https://${tenantRecord.portalDomain}/login` : null;
|
||||
|
||||
const mailResult = await sendMail(
|
||||
email,
|
||||
`FEDEO | Einladung ins Kundenportal`,
|
||||
@@ -1097,7 +1107,8 @@ export default async function adminRoutes(server: FastifyInstance) {
|
||||
<p><strong>E-Mail:</strong> ${email}</p>
|
||||
<p><strong>Initialpasswort:</strong> ${generatedPassword}</p>
|
||||
<p>Bitte ändern Sie dieses Passwort direkt nach dem ersten Login.</p>
|
||||
${portalUrl ? `<p><strong>Login:</strong> <a href="${portalUrl}">${portalUrl}</a></p>` : ""}
|
||||
<p><a href="${portalUrl}">Zum Kundenportal anmelden</a></p>
|
||||
<p>Ihre Login-Adresse: ${portalUrl}</p>
|
||||
<p>Viele Grüße<br>${tenantRecord?.name || "FEDEO"}</p>
|
||||
`
|
||||
);
|
||||
|
||||
@@ -7,6 +7,7 @@ import { authUsers } from "../../../db/schema";
|
||||
import { authTenantUsers } from "../../../db/schema";
|
||||
import { tenants } from "../../../db/schema";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { resolveLoginTenant } from "../../utils/loginTenant";
|
||||
import {
|
||||
createAccessToken,
|
||||
issueRefreshToken,
|
||||
@@ -127,7 +128,7 @@ export default async function authRoutes(server: FastifyInstance) {
|
||||
return reply.code(401).send({ error: "Invalid credentials" });
|
||||
}
|
||||
|
||||
const tenantId = req.tenant?.id ? Number(req.tenant.id) : null;
|
||||
const tenantId = await resolveLoginTenant(server, user.id, req.tenant?.id ? Number(req.tenant.id) : null);
|
||||
const token = createAccessToken(user, tenantId);
|
||||
const refreshToken = await issueRefreshToken(server, user.id, tenantId);
|
||||
|
||||
|
||||
@@ -6,6 +6,11 @@ import { assertToolPermission, createMcpContext } from "../mcp/authz"
|
||||
import { mcpToolMap, mcpTools } from "../mcp/registry"
|
||||
import { asToolError, asToolResult } from "../mcp/result"
|
||||
import { JsonRpcRequest } from "../mcp/types"
|
||||
import { assertInternalDocumentAccess, loadDocumentFile, MCP_BODY_LIMIT, MCP_FILE_PERMISSION } from "../mcp/documentFiles"
|
||||
import { s3 } from "../utils/s3"
|
||||
import { secrets } from "../utils/secrets"
|
||||
import { GetObjectCommand } from "@aws-sdk/client-s3"
|
||||
import { sanitizeFilename } from "../utils/filename"
|
||||
|
||||
const SUPPORTED_PROTOCOL_VERSIONS = [
|
||||
"2025-11-25",
|
||||
@@ -195,7 +200,28 @@ export default async function mcpRoutes(server: FastifyInstance) {
|
||||
}
|
||||
})
|
||||
|
||||
server.post("/mcp", async (req, reply) => {
|
||||
server.get<{ Params: { id: string } }>("/mcp/files/:id/content", {
|
||||
schema: { params: { type: "object", required: ["id"], properties: { id: { type: "string", format: "uuid" } } } },
|
||||
}, async (req, reply) => {
|
||||
try {
|
||||
const context = await createMcpContext(server, req)
|
||||
assertToolPermission(context, { name: "documents.files.download", requiredPermissions: [MCP_FILE_PERMISSION] })
|
||||
await assertInternalDocumentAccess(context)
|
||||
const file = await loadDocumentFile(context, req.params.id)
|
||||
if (!file.path) return reply.code(404).send({ error: "Kein Dateiinhalt verfügbar." })
|
||||
const { Body } = await s3.send(new GetObjectCommand({ Bucket: secrets.S3_BUCKET, Key: file.path }))
|
||||
if (!Body) return reply.code(404).send({ error: "Kein Dateiinhalt verfügbar." })
|
||||
reply.header("Content-Type", file.mimeType || "application/octet-stream")
|
||||
reply.header("Content-Disposition", `attachment; filename="${sanitizeFilename(file.name)}"`)
|
||||
reply.header("Cache-Control", "no-store")
|
||||
reply.header("X-Content-Type-Options", "nosniff")
|
||||
return reply.send(Body)
|
||||
} catch (error) {
|
||||
return reply.code((error as any)?.statusCode || 500).send({ error: error instanceof Error ? error.message : "Download fehlgeschlagen." })
|
||||
}
|
||||
})
|
||||
|
||||
server.post("/mcp", { bodyLimit: MCP_BODY_LIMIT }, async (req, reply) => {
|
||||
const body = req.body as JsonRpcRequest | JsonRpcRequest[]
|
||||
const requests = Array.isArray(body) ? body : [body]
|
||||
const responses = []
|
||||
@@ -226,7 +252,7 @@ export default async function mcpRoutes(server: FastifyInstance) {
|
||||
name: "fedeo-mcp",
|
||||
version: "1.0.0",
|
||||
},
|
||||
instructions: "FEDEO MCP-Server für mandantenbezogene Buchhaltungs- und Organisationswerkzeuge. Alle Tools prüfen Rollenberechtigungen und arbeiten im aktiven Mandanten.",
|
||||
instructions: "FEDEO MCP-Server für mandantenbezogene Buchhaltungs-, Organisations- und Dokumentenwerkzeuge. Alle Tools prüfen Rollenberechtigungen und arbeiten im aktiven Mandanten. Dokumentenuploads erscheinen in der Dokumentenablage; Download-URLs benötigen denselben Bearer-Token wie MCP.",
|
||||
}))
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -2,17 +2,21 @@ import { GetObjectCommand } from "@aws-sdk/client-s3"
|
||||
import { s3 } from "./s3"
|
||||
import { secrets } from "./secrets"
|
||||
|
||||
export const streamToBuffer = async (stream: any): Promise<Buffer> => {
|
||||
export const streamToBuffer = async (stream: any, maxBytes = Infinity): Promise<Buffer> => {
|
||||
const chunks: Buffer[] = []
|
||||
let size = 0
|
||||
|
||||
for await (const chunk of stream) {
|
||||
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk))
|
||||
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)
|
||||
size += buffer.length
|
||||
if (size > maxBytes) throw new Error("Die Datei ist für Base64 zu groß. Bitte den Download mit format: url verwenden.")
|
||||
chunks.push(buffer)
|
||||
}
|
||||
|
||||
return Buffer.concat(chunks)
|
||||
}
|
||||
|
||||
export const loadFileBuffer = async (path: string): Promise<Buffer> => {
|
||||
export const loadFileBuffer = async (path: string, maxBytes = Infinity): Promise<Buffer> => {
|
||||
const response = await s3.send(new GetObjectCommand({
|
||||
Bucket: secrets.S3_BUCKET,
|
||||
Key: path,
|
||||
@@ -22,5 +26,5 @@ export const loadFileBuffer = async (path: string): Promise<Buffer> => {
|
||||
throw new Error(`S3-Datei '${path}' enthält keinen lesbaren Inhalt.`)
|
||||
}
|
||||
|
||||
return streamToBuffer(response.Body)
|
||||
return streamToBuffer(response.Body, maxBytes)
|
||||
}
|
||||
|
||||
33
backend/src/utils/loginTenant.ts
Normal file
33
backend/src/utils/loginTenant.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
import type { FastifyInstance } from "fastify"
|
||||
import { and, eq } from "drizzle-orm"
|
||||
import { authProfiles, authTenantUsers } from "../../db/schema"
|
||||
|
||||
export async function resolveLoginTenant(server: FastifyInstance, userId: string, domainTenantId: number | null) {
|
||||
const memberships = await server.db
|
||||
.selectDistinct({
|
||||
tenantId: authTenantUsers.tenant_id,
|
||||
portalCustomerId: authProfiles.customer_for_portal,
|
||||
})
|
||||
.from(authTenantUsers)
|
||||
.leftJoin(authProfiles, and(
|
||||
eq(authProfiles.user_id, authTenantUsers.user_id),
|
||||
eq(authProfiles.tenant_id, authTenantUsers.tenant_id),
|
||||
eq(authProfiles.active, true)
|
||||
))
|
||||
.where(eq(authTenantUsers.user_id, userId))
|
||||
|
||||
if (domainTenantId) {
|
||||
if (!memberships.some((membership) => membership.tenantId === domainTenantId)) {
|
||||
throw Object.assign(new Error("Not a member of this tenant"), { statusCode: 403 })
|
||||
}
|
||||
return domainTenantId
|
||||
}
|
||||
|
||||
// Portal invitations assign one customer account. Load its profile immediately,
|
||||
// even when the customer signs in through the shared FEDEO address.
|
||||
if (memberships.length === 1 && memberships[0].portalCustomerId) {
|
||||
return memberships[0].tenantId
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
@@ -488,6 +488,8 @@ export const createInvoicePDF = async (server:FastifyInstance, returnMode, invoi
|
||||
|
||||
const getTitleKey = (row) => `${row.pos} - ${row.text}`
|
||||
const getTransferSumText = (row) => {
|
||||
if (deliveryNoteLikeDocumentTypes.includes(invoiceData.type)) return null
|
||||
|
||||
const transferSum = invoiceData.total.titleSumsTransfer[getTitleKey(row)]
|
||||
|
||||
return transferSum ? `Übertrag: ${transferSum}` : null
|
||||
|
||||
29
backend/src/utils/portalUrl.ts
Normal file
29
backend/src/utils/portalUrl.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
type PortalUrlSettings = {
|
||||
portalDomain?: string | null
|
||||
publicUrl?: string
|
||||
apiBaseUrl?: string
|
||||
}
|
||||
|
||||
/** Use deployment configuration, never request headers, for links sent by email. */
|
||||
export function getPortalLoginUrl({ portalDomain, publicUrl, apiBaseUrl }: PortalUrlSettings) {
|
||||
const domain = portalDomain?.trim()
|
||||
const candidates = [
|
||||
{ value: domain ? (/^https?:\/\//i.test(domain) ? domain : `https://${domain}`) : undefined },
|
||||
{ value: publicUrl?.trim() },
|
||||
{ value: apiBaseUrl?.trim(), originOnly: true },
|
||||
]
|
||||
|
||||
for (const { value, originOnly } of candidates) {
|
||||
if (!value) continue
|
||||
try {
|
||||
const url = new URL(value)
|
||||
if (!["http:", "https:"].includes(url.protocol) || url.username || url.password) continue
|
||||
url.pathname = `${originOnly ? "" : url.pathname.replace(/\/+$/, "")}/login`
|
||||
url.search = ""
|
||||
url.hash = ""
|
||||
return url.toString()
|
||||
} catch { /* Try the next configured address. */ }
|
||||
}
|
||||
|
||||
throw new Error("Für die Portal-Einladung fehlt eine gültige öffentliche FEDEO-Adresse.")
|
||||
}
|
||||
126
backend/tests/customerPortalLogin.test.ts
Normal file
126
backend/tests/customerPortalLogin.test.ts
Normal file
@@ -0,0 +1,126 @@
|
||||
import assert from "node:assert/strict"
|
||||
import test from "node:test"
|
||||
import Fastify from "fastify"
|
||||
import cookie from "@fastify/cookie"
|
||||
import bcrypt from "bcrypt"
|
||||
import jwt from "jsonwebtoken"
|
||||
import { drizzle } from "drizzle-orm/pg-proxy"
|
||||
import authRoutes from "../src/routes/auth/auth"
|
||||
import meRoutes from "../src/routes/auth/me"
|
||||
import { secrets } from "../src/utils/secrets"
|
||||
import { getPortalLoginUrl } from "../src/utils/portalUrl"
|
||||
|
||||
test("portal invitations always use a configured frontend login URL", () => {
|
||||
const defaults = { apiBaseUrl: "https://fedeo.example/backend" }
|
||||
assert.equal(getPortalLoginUrl(defaults), "https://fedeo.example/login")
|
||||
assert.equal(getPortalLoginUrl({ ...defaults, portalDomain: " kunden.example " }), "https://kunden.example/login")
|
||||
assert.equal(getPortalLoginUrl({ ...defaults, portalDomain: "https://kunden.example/" }), "https://kunden.example/login")
|
||||
assert.equal(getPortalLoginUrl({ ...defaults, publicUrl: "https://web.example/fedeo/" }), "https://web.example/fedeo/login")
|
||||
assert.equal(getPortalLoginUrl({ ...defaults, publicUrl: "http://localhost:3000/" }), "http://localhost:3000/login")
|
||||
assert.equal(getPortalLoginUrl({ ...defaults, publicUrl: "javascript:alert(1)" }), "https://fedeo.example/login")
|
||||
assert.equal(getPortalLoginUrl({ ...defaults, publicUrl: "https://user:password@web.example/" }), "https://fedeo.example/login")
|
||||
assert.throws(() => getPortalLoginUrl({}), /öffentliche FEDEO-Adresse/)
|
||||
})
|
||||
|
||||
const userId = "00000000-0000-4000-8000-000000000001"
|
||||
const profileId = "00000000-0000-4000-8000-000000000002"
|
||||
const passwordHash = bcrypt.hashSync("portal-password", 4)
|
||||
|
||||
function selectedRow(sql: string, values: Record<string, any>) {
|
||||
return sql.slice(7, sql.indexOf(" from ")).split(", ").map(column => {
|
||||
const name = [...column.matchAll(/"([^"]+)"/g)].at(-1)?.[1]
|
||||
return values[name!] ?? null
|
||||
})
|
||||
}
|
||||
|
||||
async function fixture(t: any, memberships: Array<[number, number | null]>, domainTenantId?: number) {
|
||||
const refreshTenants: Array<number | null> = []
|
||||
const db = drizzle(async (sql, params) => {
|
||||
if (sql.includes('from "auth_users"')) {
|
||||
return { rows: [selectedRow(sql, {
|
||||
id: userId, email: "customer@example.com", password_hash: passwordHash,
|
||||
must_change_password: true, is_admin: false,
|
||||
})] }
|
||||
}
|
||||
if (sql.includes('from "auth_tenant_users"') && sql.includes('"auth_profiles"')) {
|
||||
assert.ok(params.includes(userId))
|
||||
assert.match(sql, /"auth_profiles"\."tenant_id" = "auth_tenant_users"\."tenant_id"/)
|
||||
assert.match(sql, /"auth_profiles"\."active" =/)
|
||||
assert.ok(params.includes(true))
|
||||
return { rows: memberships }
|
||||
}
|
||||
if (sql.startsWith('insert into "auth_refresh_tokens"')) {
|
||||
refreshTenants.push(params[1] as number | null)
|
||||
return { rows: [] }
|
||||
}
|
||||
if (sql.includes('from "auth_tenant_users"')) {
|
||||
return { rows: memberships.map(([id]) => selectedRow(sql, { id, name: "Test tenant" })) }
|
||||
}
|
||||
if (sql.includes('from "auth_profiles"')) {
|
||||
const membership = memberships.find(([id]) => params.includes(id))
|
||||
return { rows: membership ? [selectedRow(sql, {
|
||||
id: profileId, user_id: userId, tenant_id: membership[0],
|
||||
customer_for_portal: membership[1], active: true,
|
||||
})] : [] }
|
||||
}
|
||||
if (sql.includes('from "auth_profile_branches"') || sql.includes('from "auth_user_roles"')) return { rows: [] }
|
||||
throw new Error(`Unexpected query: ${sql}`)
|
||||
})
|
||||
secrets.JWT_SECRET = "customer-portal-test-secret"
|
||||
const app = Fastify()
|
||||
app.decorate("db", db as any)
|
||||
app.addHook("preHandler", async (req: any) => {
|
||||
if (domainTenantId) req.tenant = { id: String(domainTenantId) }
|
||||
if (req.headers.authorization) req.user = jwt.verify(req.headers.authorization.slice(7), secrets.JWT_SECRET)
|
||||
})
|
||||
await app.register(cookie)
|
||||
await app.register(authRoutes)
|
||||
await app.register(meRoutes)
|
||||
t.after(() => app.close())
|
||||
const login = (password = "portal-password") => app.inject({
|
||||
method: "POST", url: "/auth/login", payload: { email: "customer@example.com", password },
|
||||
})
|
||||
return { app, login, refreshTenants }
|
||||
}
|
||||
|
||||
test("shared-address login scopes both tokens and loads the customer's portal profile", async t => {
|
||||
const f = await fixture(t, [[7, 123]])
|
||||
const response = await f.login()
|
||||
assert.equal(response.statusCode, 200, response.body)
|
||||
const session = response.json()
|
||||
assert.equal((jwt.verify(session.token, secrets.JWT_SECRET) as any).tenant_id, 7)
|
||||
assert.deepEqual(f.refreshTenants, [7])
|
||||
assert.ok(session.refreshToken)
|
||||
const me = await f.app.inject({ url: "/me", headers: { authorization: `Bearer ${session.token}` } })
|
||||
assert.equal(me.statusCode, 200, me.body)
|
||||
assert.equal(me.json().activeTenant, 7)
|
||||
assert.equal(me.json().profile.customer_for_portal, 123)
|
||||
assert.equal(me.json().user.must_change_password, true)
|
||||
})
|
||||
|
||||
test("internal and ambiguous accounts retain tenant selection", async t => {
|
||||
for (const memberships of [[], [[7, null]], [[7, 123], [8, 456]]] as Array<Array<[number, number | null]>>) {
|
||||
const f = await fixture(t, memberships)
|
||||
const response = await f.login()
|
||||
assert.equal(response.statusCode, 200, response.body)
|
||||
assert.equal((jwt.verify(response.json().token, secrets.JWT_SECRET) as any).tenant_id, null)
|
||||
assert.deepEqual(f.refreshTenants, [null])
|
||||
}
|
||||
})
|
||||
|
||||
test("a portal domain selects only a tenant the user belongs to", async t => {
|
||||
const f = await fixture(t, [[7, 123], [8, 456]], 8)
|
||||
const response = await f.login()
|
||||
assert.equal(response.statusCode, 200, response.body)
|
||||
assert.equal((jwt.verify(response.json().token, secrets.JWT_SECRET) as any).tenant_id, 8)
|
||||
assert.deepEqual(f.refreshTenants, [8])
|
||||
const other = await fixture(t, [[7, 123]], 99)
|
||||
assert.equal((await other.login()).statusCode, 403)
|
||||
assert.deepEqual(other.refreshTenants, [])
|
||||
})
|
||||
|
||||
test("invalid credentials never create a portal session", async t => {
|
||||
const f = await fixture(t, [[7, 123]])
|
||||
assert.equal((await f.login("wrong-password")).statusCode, 401)
|
||||
assert.deepEqual(f.refreshTenants, [])
|
||||
})
|
||||
219
backend/tests/mcpCalendarStatus.test.ts
Normal file
219
backend/tests/mcpCalendarStatus.test.ts
Normal file
@@ -0,0 +1,219 @@
|
||||
import assert from "node:assert/strict"
|
||||
import test from "node:test"
|
||||
import { randomUUID } from "node:crypto"
|
||||
import { execFile } from "node:child_process"
|
||||
import { promisify } from "node:util"
|
||||
import { Pool } from "pg"
|
||||
import { drizzle } from "drizzle-orm/node-postgres"
|
||||
import { eq, getTableColumns, getTableName } from "drizzle-orm"
|
||||
import * as schema from "../db/schema"
|
||||
import { mcpToolMap, mcpTools } from "../src/mcp/registry"
|
||||
import { assertToolPermission } from "../src/mcp/authz"
|
||||
import { asToolResult } from "../src/mcp/result"
|
||||
import { eventDateTimeField, prepareEventInput, calendarTools } from "../src/mcp/tools/calendar"
|
||||
import { outgoingDocumentStatus, outgoingStatusTools } from "../src/mcp/tools/outgoingStatus"
|
||||
|
||||
const execute = promisify(execFile)
|
||||
const userId = "00000000-0000-4000-8000-000000000001"
|
||||
const invoice = { id: 1, state: "Gebucht", type: "invoices", rows: [{ quantity: 1, price: 100, taxPercent: 19 }], usedAdvanceInvoices: [] }
|
||||
|
||||
test("registers read-only document status and permission-protected calendar tools", () => {
|
||||
assert.equal(new Set(mcpTools.map(tool => tool.name)).size, mcpTools.length)
|
||||
for (const tool of [...calendarTools, ...outgoingStatusTools]) {
|
||||
assert.equal(mcpToolMap.get(tool.name), tool)
|
||||
assert.throws(() => assertToolPermission({ isAdmin: false, permissions: [] } as any, tool), { statusCode: 403 })
|
||||
assert.doesNotThrow(() => assertToolPermission({ isAdmin: false, permissions: tool.requiredPermissions } as any, tool))
|
||||
}
|
||||
for (const tool of outgoingStatusTools) assert.deepEqual(tool.requiredPermissions, ["accounting.outgoing_documents.read"])
|
||||
for (const action of ["create", "update", "archive"]) {
|
||||
assert.deepEqual(mcpToolMap.get(`organisation.events.${action}`)!.requiredPermissions, ["organisation.events.write"])
|
||||
}
|
||||
})
|
||||
|
||||
test("payment status handles drafts, partial payments, credits and advance invoices", () => {
|
||||
const status = (document: any, paid: number, cancellations: any[] = [], advances: any[] = []) => outgoingDocumentStatus(document, paid, cancellations, advances)
|
||||
assert.equal(status(invoice, 0).paymentStatus, "Offen")
|
||||
assert.equal(status(invoice, 50).paymentStatus, "Teilbezahlt")
|
||||
assert.equal(status(invoice, 119).paymentStatus, "Bezahlt")
|
||||
assert.equal(status(invoice, 120).paymentStatus, "Überbezahlt")
|
||||
assert.equal(status({ ...invoice, state: "Entwurf" }, 119).paymentStatus, null)
|
||||
assert.equal(status({ ...invoice, type: "quotes" }, 0).paymentStatus, null)
|
||||
const cancelled = status(invoice, 0, [{ id: 2, documentNumber: "ST-2" }])
|
||||
assert.equal(cancelled.cancelled, true)
|
||||
assert.equal(cancelled.paymentStatus, null)
|
||||
assert.deepEqual(cancelled.cancellationDocuments, [{ id: 2, documentNumber: "ST-2" }])
|
||||
const advance = { id: 3, rows: [{ price: 20, taxPercent: 19, advanceInvoiceData: {} }] }
|
||||
assert.equal(status({ ...invoice, usedAdvanceInvoices: [3] }, 95.2, [], [advance]).paymentStatus, "Bezahlt")
|
||||
assert.equal(status({ ...invoice, rows: [{ quantity: 1, price: -100, taxPercent: 19 }] }, -50).paymentStatus, "Teilbezahlt")
|
||||
assert.equal(status({ ...invoice, rows: [{ quantity: 1, price: -100, taxPercent: 19 }] }, -120).paymentStatus, "Überbezahlt")
|
||||
assert.equal(status({ ...invoice, rows: [] }, 0).paymentStatus, "Bezahlt")
|
||||
const mixedTax = { ...invoice, rows: [{ quantity: 1, price: 0.03, taxPercent: 7 }, { quantity: 1, price: 0.02, taxPercent: 19 }] }
|
||||
assert.equal(status(mixedTax, 0.05).paymentStatus, "Bezahlt", "separate tax buckets must match the outgoing-document UI")
|
||||
assert.throws(() => status({ ...invoice, rows: [{ quantity: 1, price: "invalid" }] }, 0), /Positionsbetrag/)
|
||||
assert.throws(() => status(invoice, NaN), /Betrag kann nicht berechnet/)
|
||||
})
|
||||
|
||||
test("calendar validates explicit timezones, dates, editable fields and typed resources", () => {
|
||||
assert.equal(eventDateTimeField.parse("2026-10-15T09:00:00+02:00", "startDate").toISOString(), "2026-10-15T07:00:00.000Z")
|
||||
for (const value of ["2026-10-15", "2026-10-15T09:00:00", "2026-02-30T09:00:00Z", "2026-10-15T24:00:00Z", "2026-10-15T09:60:00Z", "bad", null]) {
|
||||
assert.throws(() => eventDateTimeField.parse(value, "startDate"))
|
||||
}
|
||||
for (const args of [
|
||||
{ id: 1 }, { id: -1, name: "Test" }, { id: 1, tenant: 2 }, { id: 1, updatedBy: userId },
|
||||
{ id: 1, state: "Bezahlt" }, { id: 1, repeatInterval: "irgendwann" },
|
||||
{ id: 1, profiles: [1] }, { id: 1, vehicles: ["1"] }, { id: 1, name: " " }, { id: 1, resources: [] },
|
||||
]) assert.throws(() => prepareEventInput("update", args))
|
||||
assert.throws(() => prepareEventInput("create", { name: "Test" }), /startDate/)
|
||||
assert.deepEqual(prepareEventInput("update", { id: 1, endDate: null, profiles: [], vehicles: [1, 1] }), { id: 1, endDate: null, profiles: [], vehicles: [1] })
|
||||
})
|
||||
|
||||
// An isolated database and local fixtures only; no production configuration is loaded.
|
||||
test("calendar and outgoing status integration", { skip: !process.env.FEDEO_TEST_POSTGRES_IMAGE }, async t => {
|
||||
const container = "fedeo-mcp-calendar-" + randomUUID()
|
||||
const password = randomUUID()
|
||||
await execute("docker", ["run", "--rm", "-d", "--name", container, "-e", `POSTGRES_PASSWORD=${password}`, "-p", "127.0.0.1::5432", process.env.FEDEO_TEST_POSTGRES_IMAGE!])
|
||||
let pool: Pool | undefined
|
||||
t.after(async () => { await pool?.end(); await execute("docker", ["rm", "-f", container]) })
|
||||
const { stdout } = await execute("docker", ["port", container, "5432/tcp"])
|
||||
pool = new Pool({ host: "127.0.0.1", port: Number(stdout.trim().split(":").at(-1)), user: "postgres", password, database: "postgres", connectionTimeoutMillis: 1000 })
|
||||
for (let attempt = 0; ; attempt++) {
|
||||
try { await pool.query("SELECT 1"); break } catch (error) {
|
||||
if (attempt >= 80) throw error
|
||||
await new Promise(resolve => setTimeout(resolve, 100))
|
||||
}
|
||||
}
|
||||
const tables = [schema.events, schema.createddocuments, schema.statementallocations, schema.historyitems, schema.tenants,
|
||||
schema.projects, schema.customers, schema.vendors, schema.authProfiles, schema.vehicles, schema.inventoryitems, schema.inventoryitemgroups]
|
||||
for (const table of tables) {
|
||||
const columns = Object.entries(getTableColumns(table)).map(([key, column]) => {
|
||||
let suffix = ""
|
||||
if (key === "id") suffix = column.getSQLType() === "uuid" ? " PRIMARY KEY DEFAULT gen_random_uuid()" : " GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY"
|
||||
else if (key === "archived" || key === "quick") suffix = " DEFAULT false"
|
||||
else if (key === "active") suffix = " DEFAULT true"
|
||||
else if (key === "createdAt") suffix = " DEFAULT now()"
|
||||
else if (["profiles", "vehicles", "inventoryitems", "inventoryitemgroups", "resources", "rows", "usedAdvanceInvoices"].includes(key)) {
|
||||
suffix = column.getSQLType().endsWith("[]") ? ` DEFAULT '{}'::${column.getSQLType()}` : " DEFAULT '[]'::jsonb"
|
||||
}
|
||||
else if (table === schema.events && key === "state") suffix = " DEFAULT 'Final'"
|
||||
else if (table === schema.events && key === "repeatInterval") suffix = " DEFAULT 'Keine Wiederholung'"
|
||||
else if (table === schema.events && key === "eventtype") suffix = " DEFAULT 'Umsetzung'"
|
||||
return `"${column.name}" ${column.columnType === "PgEnumColumn" ? "text" : column.getSQLType()}${suffix}`
|
||||
})
|
||||
await pool.query(`CREATE TABLE "${getTableName(table)}" (${columns.join(", ")})`)
|
||||
}
|
||||
const db = drizzle(pool) as any
|
||||
const call = async (name: string, args: any = {}, tenantId = 1) => {
|
||||
const context = { server: { db }, tenantId, userId, isAdmin: false,
|
||||
permissions: ["organisation.events.read", "organisation.events.write", "accounting.outgoing_documents.read"] } as any
|
||||
const tool = mcpToolMap.get(name)!
|
||||
assert.ok(tool, name)
|
||||
assertToolPermission(context, tool)
|
||||
return await tool.handler(context, args) as any
|
||||
}
|
||||
const calendar = (name: string, args: any = {}, tenant = 1) => call(`organisation.events.${name}`, args, tenant)
|
||||
const status = (name: string, args: any, tenant = 1) => call(`accounting.outgoing_documents.status.${name}`, args, tenant)
|
||||
await db.insert(schema.tenants).values([{ id: 1, calendarConfig: { eventTypes: [{ label: "Büro", color: "blue" }] } }, { id: 2 }])
|
||||
await db.insert(schema.projects).values([{ id: 1, tenant: 1, name: "Own" }, { id: 2, tenant: 2, name: "Foreign" }, { id: 3, tenant: 1, name: "Archived", archived: true }])
|
||||
await db.insert(schema.vehicles).values([{ id: 1, tenant: 1 }, { id: 2, tenant: 2 }])
|
||||
const ownProfile = randomUUID(), portalProfile = randomUUID(), group = randomUUID()
|
||||
await db.insert(schema.authProfiles).values([{ id: ownProfile, tenant_id: 1 }, { id: portalProfile, tenant_id: 1, customer_for_portal: 5 }])
|
||||
await db.insert(schema.inventoryitemgroups).values({ id: group, tenant: 1 })
|
||||
|
||||
await t.test("create, update and archive preserve metadata, history and tenant isolation", async () => {
|
||||
const options = await call("organisation.calendar.options")
|
||||
assert.equal(options.calendarConfig.eventTypes[0].label, "Büro")
|
||||
const { event } = await calendar("create", { name: "Besprechung", startDate: "2026-10-15T09:00:00+02:00", endDate: "2026-10-15T10:00:00+02:00",
|
||||
project: 1, profiles: [ownProfile], vehicles: [1], inventoryitemgroups: [group], repeatInterval: "Wöchentlich" })
|
||||
assert.equal(event.state, "Final")
|
||||
assert.equal(event.updatedBy, userId)
|
||||
assert.equal(event.tenant, 1)
|
||||
assert.equal(event.startDate.toISOString(), "2026-10-15T07:00:00.000Z")
|
||||
await assert.rejects(calendar("get", { id: event.id }, 2), /nicht gefunden/)
|
||||
await assert.rejects(calendar("update", { id: event.id, name: "wrong" }, 2), /nicht gefunden/)
|
||||
await assert.rejects(calendar("archive", { id: event.id }, 2), /nicht gefunden/)
|
||||
for (const patch of [{ project: 2 }, { project: 3 }, { profiles: [portalProfile] }, { vehicles: [2] }, { inventoryitemgroups: [randomUUID()] }]) {
|
||||
await assert.rejects(calendar("update", { id: event.id, ...patch }), /nicht verfügbar/)
|
||||
}
|
||||
await assert.rejects(calendar("update", { id: event.id, startDate: "2026-10-15T11:00:00+02:00" }), /endDate/)
|
||||
const changed = await calendar("update", { id: event.id, name: "Planung", endDate: null, profiles: [], project: null, state: "Entwurf" })
|
||||
assert.equal(changed.event.endDate, null)
|
||||
assert.deepEqual(changed.event.profiles, [])
|
||||
assert.equal(changed.event.repeatInterval, "Wöchentlich")
|
||||
assert.equal(changed.event.project, null)
|
||||
const history = await db.select().from(schema.historyitems).where(eq(schema.historyitems.event, event.id))
|
||||
assert.deepEqual(history.map(row => row.action), ["created", "updated"])
|
||||
assert.ok(history.every(row => row.tenant === 1 && row.createdBy === userId))
|
||||
await pool!.query("ALTER TABLE historyitems ADD CONSTRAINT reject_new_history CHECK (false) NOT VALID")
|
||||
await assert.rejects(calendar("update", { id: event.id, name: "Must roll back" }))
|
||||
assert.equal((await calendar("get", { id: event.id })).event.name, "Planung")
|
||||
await pool!.query("ALTER TABLE historyitems DROP CONSTRAINT reject_new_history")
|
||||
assert.deepEqual(asToolResult(await calendar("archive", { id: event.id })).structuredContent, { id: event.id, success: true, action: "archived" })
|
||||
await assert.rejects(calendar("get", { id: event.id }), /archiviert/)
|
||||
assert.equal((await calendar("list", {})).rows.length, 0)
|
||||
})
|
||||
|
||||
await t.test("calendar range and resource filters handle overlaps and older recurring series", async () => {
|
||||
const create = async (name: string, startDate: string, endDate: string | null, extra: any = {}, tenant = 1) =>
|
||||
(await calendar("create", { name, startDate, endDate, ...extra }, tenant)).event
|
||||
await create("Before", "2026-10-10T09:00:00Z", "2026-10-10T10:00:00Z")
|
||||
await create("Ends at boundary", "2026-10-10T09:00:00Z", "2026-10-15T00:00:00Z")
|
||||
const spanning = await create("Overlapping", "2026-10-14T23:00:00Z", "2026-10-15T01:00:00Z", { profiles: [ownProfile], vehicles: [1], state: "Entwurf", quick: true })
|
||||
const inside = await create("Inside", "2026-10-15T10:00:00Z", null)
|
||||
await create("End excluded", "2026-10-16T00:00:00Z", null)
|
||||
const recurring = await create("Older series", "2020-10-01T09:00:00Z", "2020-10-01T10:00:00Z", { repeatInterval: "Wöchentlich" })
|
||||
await create("Foreign", "2026-10-15T10:00:00Z", null, {}, 2)
|
||||
const range = { from: "2026-10-15T00:00:00Z", to: "2026-10-16T00:00:00Z" }
|
||||
const listed = await calendar("list", range)
|
||||
assert.deepEqual(listed.rows.map(row => row.id), [inside.id, spanning.id, recurring.id])
|
||||
assert.deepEqual((await calendar("list", { ...range, includeRecurring: false })).rows.map(row => row.id), [inside.id, spanning.id])
|
||||
assert.deepEqual((await calendar("list", { ...range, profile: ownProfile, vehicle: 1, state: "Entwurf", quick: true })).rows.map(row => row.id), [spanning.id])
|
||||
await assert.rejects(calendar("list", { from: range.to, to: range.from }), /from/)
|
||||
})
|
||||
|
||||
await t.test("status ignores foreign/archived payments and draft cancellations and applies advances", async () => {
|
||||
await db.insert(schema.createddocuments).values([
|
||||
{ ...invoice, id: 100, tenant: 1, documentNumber: "RE-100", usedAdvanceInvoices: [103] },
|
||||
{ ...invoice, id: 101, tenant: 2 }, { ...invoice, id: 102, tenant: 1, archived: true },
|
||||
{ ...invoice, id: 103, tenant: 1, type: "advanceInvoices", rows: [{ price: 20, taxPercent: 19, advanceInvoiceData: {} }] },
|
||||
{ ...invoice, id: 104, tenant: 1, type: "cancellationInvoices", state: "Entwurf", createddocument: 100 },
|
||||
{ ...invoice, id: 105, tenant: 2, type: "cancellationInvoices", createddocument: 100 },
|
||||
{ ...invoice, id: 106, tenant: 1, type: "cancellationInvoices", createddocument: 100, archived: true },
|
||||
])
|
||||
await db.insert(schema.statementallocations).values([
|
||||
{ tenant: 1, createddocument: 100, amount: 95.2 }, { tenant: 1, createddocument: 100, amount: 500, archived: true },
|
||||
{ tenant: 2, createddocument: 100, amount: 700 },
|
||||
])
|
||||
const result = (await status("get", { id: 100 })).status
|
||||
assert.equal(result.paymentStatus, "Bezahlt")
|
||||
assert.equal(result.amount, 95.2)
|
||||
assert.equal(result.paidAmount, 95.2)
|
||||
assert.equal(result.openAmount, 0)
|
||||
assert.equal(result.cancelled, false)
|
||||
await assert.rejects(status("get", { id: 101 }), /nicht gefunden/)
|
||||
await assert.rejects(status("get", { id: 102 }), /archiviert/)
|
||||
await db.insert(schema.createddocuments).values({ ...invoice, id: 107, tenant: 1, documentNumber: "ST-107", type: "cancellationInvoices", createddocument: 100 })
|
||||
const cancelled = (await status("get", { id: 100 })).status
|
||||
assert.equal(cancelled.paymentStatus, null)
|
||||
assert.deepEqual(cancelled.cancellationDocuments, [{ id: 107, documentNumber: "ST-107" }])
|
||||
assert.deepEqual((await status("list", { cancelled: true })).rows.map(row => row.id), [100])
|
||||
})
|
||||
|
||||
await t.test("computed status filters precede pagination across several database batches", async () => {
|
||||
const documents = Array.from({ length: 410 }, (_, index) => ({ ...invoice, id: 1000 + index, tenant: 1, project: 999,
|
||||
createdAt: new Date("2026-10-01T00:00:00Z") }))
|
||||
await db.insert(schema.createddocuments).values(documents)
|
||||
await db.insert(schema.statementallocations).values(documents.filter((_, i) => i % 2 === 0).map(document => ({ tenant: 1, createddocument: document.id, amount: 119 })))
|
||||
const ids: number[] = []
|
||||
for (const offset of [0, 100, 200]) {
|
||||
const result = await status("list", { state: "Gebucht", paymentStatus: "Bezahlt", cancelled: false, project: 999, limit: 100, offset })
|
||||
assert.equal(result.rows.length, offset < 200 ? 100 : 5)
|
||||
assert.equal(result.pagination.nextOffset, offset < 200 ? offset + 100 : null)
|
||||
ids.push(...result.rows.map(row => row.id))
|
||||
}
|
||||
assert.deepEqual(ids, documents.filter((_, i) => i % 2 === 0).map(document => document.id))
|
||||
assert.equal((await status("list", { project: 999, paymentStatus: "Teilbezahlt" })).rows.length, 0)
|
||||
assert.equal((await status("list", { project: 999, offset: 400, limit: 100 })).rows.length, 10)
|
||||
await assert.rejects(status("list", { paymentStatus: "unknown" }), /Zahlungsstatus/)
|
||||
await assert.rejects(status("get", { id: 100, state: "Entwurf" }), /unbekanntes Feld/)
|
||||
})
|
||||
})
|
||||
212
backend/tests/mcpDocuments.test.ts
Normal file
212
backend/tests/mcpDocuments.test.ts
Normal file
@@ -0,0 +1,212 @@
|
||||
import assert from "node:assert/strict"
|
||||
import test from "node:test"
|
||||
import { Readable } from "node:stream"
|
||||
import Fastify from "fastify"
|
||||
import { getTableColumns } from "drizzle-orm"
|
||||
import { drizzle } from "drizzle-orm/pg-proxy"
|
||||
import { files } from "../db/schema"
|
||||
import { mcpToolMap } from "../src/mcp/registry"
|
||||
import { createDocumentTools, documentTools } from "../src/mcp/tools/documents"
|
||||
import { assertToolPermission } from "../src/mcp/authz"
|
||||
import { asToolResult } from "../src/mcp/result"
|
||||
import { decodeDocumentUpload, MCP_BODY_LIMIT, MCP_FILE_LIMIT } from "../src/mcp/documentFiles"
|
||||
import { streamToBuffer } from "../src/utils/fileBuffer"
|
||||
import { secrets } from "../src/utils/secrets"
|
||||
import { initS3, s3 } from "../src/utils/s3"
|
||||
import mcpRoutes from "../src/routes/mcp"
|
||||
import authPlugin from "../src/plugins/auth"
|
||||
import { createHash } from "node:crypto"
|
||||
|
||||
const id = "00000000-0000-4000-8000-000000000001"
|
||||
const pdf = Buffer.from("%PDF-1.7\nMCP fixture\n%%EOF")
|
||||
const contextFor = (db: any) => ({ server: { db }, tenantId: 7, userId: id, isAdmin: false, permissions: ["documents.read", "documents.write"] }) as any
|
||||
const tool = (name: string) => mcpToolMap.get(`documents.${name}`)!
|
||||
const profileDb = (portal: number | null = null) => drizzle(async () => ({ rows: portal ? [[portal]] : [] }))
|
||||
|
||||
test("document tools are registered with read/write permissions and reject insufficient permissions", () => {
|
||||
assert.equal(documentTools.length, 15)
|
||||
for (const entry of documentTools) {
|
||||
assert.equal(mcpToolMap.get(entry.name), entry)
|
||||
assert.equal(entry.inputSchema.additionalProperties, false)
|
||||
const context = contextFor(profileDb())
|
||||
assert.doesNotThrow(() => assertToolPermission(context, entry))
|
||||
assert.throws(() => assertToolPermission({ ...context, permissions: [] }, entry), { statusCode: 403 })
|
||||
assert.doesNotThrow(() => assertToolPermission({ ...context, permissions: [], isAdmin: true }, entry))
|
||||
}
|
||||
for (const name of ["files.upload", "inbox.file", "inbox.archive", "inbox.suggestion.refresh"]) {
|
||||
assert.deepEqual(tool(name).requiredPermissions, ["documents.write"])
|
||||
}
|
||||
assert.deepEqual(tool("files.download").requiredPermissions, ["documents.read"])
|
||||
})
|
||||
|
||||
test("validates actual upload bytes, strict Base64, filename and size before storage", () => {
|
||||
assert.deepEqual(decodeDocumentUpload("scan.pdf", pdf.toString("base64")), { body: pdf, mimeType: "application/pdf" })
|
||||
for (const value of ["", null, 42, "!!!!", "Zg==junk", "Zh==", "data:application/pdf;base64," + pdf.toString("base64")]) {
|
||||
assert.throws(() => decodeDocumentUpload("scan.pdf", value), /Base64/)
|
||||
}
|
||||
for (const filename of ["../scan.pdf", "sub/scan.pdf", ".hidden.pdf", "x".repeat(201) + ".pdf", "scan.exe"]) {
|
||||
assert.throws(() => decodeDocumentUpload(filename, pdf.toString("base64")))
|
||||
}
|
||||
assert.throws(() => decodeDocumentUpload("scan.pdf", Buffer.from("not a PDF").toString("base64")), /vollständige PDF/)
|
||||
assert.throws(() => decodeDocumentUpload("scan.pdf", Buffer.from("%PDF-1.7 truncated").toString("base64")), /vollständige PDF/)
|
||||
assert.throws(() => decodeDocumentUpload("scan.pdf", "A".repeat(Math.ceil(MCP_FILE_LIMIT / 3) * 4 + 4)), /20 MiB/)
|
||||
const boundary = Buffer.alloc(MCP_FILE_LIMIT, 32)
|
||||
boundary.write("%PDF-1.7\n")
|
||||
boundary.write("%%EOF", boundary.length - 5)
|
||||
assert.equal(decodeDocumentUpload("scan.pdf", boundary.toString("base64")).body.length, MCP_FILE_LIMIT)
|
||||
assert.throws(() => decodeDocumentUpload("scan.pdf", Buffer.concat([boundary, Buffer.from("\n")]).toString("base64")), /20 MiB/)
|
||||
})
|
||||
|
||||
test("rejects unknown system fields, invalid filters, missing IDs and portal access", async () => {
|
||||
const context = contextFor(profileDb())
|
||||
for (const [name, args] of [
|
||||
["files.upload", { filename: "scan.pdf", contentBase64: pdf.toString("base64"), tenant: 9 }],
|
||||
["files.get", {}], ["files.get", { id: "bad" }], ["files.list", { folder: "bad" }],
|
||||
["files.list", { project: -1 }], ["files.list", { limit: 101 }], ["inbox.list", { search: "x".repeat(201) }],
|
||||
["inbox.file", { id, folder: null, type: id, assignments: { tenant: 9 } }],
|
||||
["inbox.file", { id, folder: null, type: id, assignments: { project: "12" } }],
|
||||
["assignments.search", { kind: "__proto__" }], ["files.download", { id, format: "pdf" }],
|
||||
] as const) await assert.rejects(tool(name).handler(context, args))
|
||||
await assert.rejects(tool("inbox.count").handler(contextFor(profileDb(123)), {}), { statusCode: 403 })
|
||||
await assert.rejects(tool("files.download").handler(contextFor(profileDb(123)), { id }), { statusCode: 403 })
|
||||
await assert.rejects(tool("files.upload").handler(contextFor(profileDb(123)), { filename: "scan.pdf", contentBase64: pdf.toString("base64") }), { statusCode: 403 })
|
||||
})
|
||||
|
||||
for (const name of ["inbox.list", "files.list", "folders.list", "types.list", "assignments.search"]) {
|
||||
test(`${name}: retrieves 205 records with tenant filters and stable pagination`, async () => {
|
||||
const db = drizzle(async (sql, params) => {
|
||||
if (sql.includes('from "auth_profiles"')) return { rows: [] }
|
||||
assert.match(sql, /"tenant(?:_id)?" = \$\d+/)
|
||||
assert.ok(params.includes(7))
|
||||
assert.match(sql, /"archived" = \$\d+/)
|
||||
assert.match(sql, /order by .*"id"/)
|
||||
if (name === "inbox.list") {
|
||||
assert.match(sql, /"filed_at" is null/)
|
||||
assert.match(sql, /"files"\."tenant" =/)
|
||||
}
|
||||
if (name === "files.list") {
|
||||
assert.match(sql, /"folder" is null/)
|
||||
assert.match(sql, /"createddocument" =/)
|
||||
assert.ok(params.includes(42))
|
||||
}
|
||||
const limit = Number(params[Number(sql.match(/limit \$(\d+)/)![1]) - 1])
|
||||
const offset = Number(params[Number(sql.match(/offset \$(\d+)/)?.[1]) - 1] || 0)
|
||||
assert.equal(limit, 101)
|
||||
const selected = sql.slice(7, sql.indexOf(" from ")).split(", ")
|
||||
const idIndex = selected.findIndex(column => /"id"$/.test(column))
|
||||
return { rows: Array.from({ length: Math.min(limit, 205 - offset) }, (_, i) => {
|
||||
const values = selected.map(() => null as any)
|
||||
values[idIndex] = String(i + offset + 1)
|
||||
return values
|
||||
}) }
|
||||
})
|
||||
const ids: string[] = []
|
||||
for (const offset of [0, 100, 200]) {
|
||||
const args = { limit: 100, offset, ...(name === "assignments.search" ? { kind: "project" } : {}),
|
||||
...(name === "files.list" ? { folder: null, createddocument: 42 } : {}) }
|
||||
const result: any = await tool(name).handler(contextFor(db), args)
|
||||
ids.push(...result.rows.map((row: any) => String(row.id)))
|
||||
assert.equal(result.pagination.hasMore, offset < 200)
|
||||
assert.equal(result.pagination.nextOffset, offset < 200 ? offset + 100 : null)
|
||||
}
|
||||
assert.deepEqual(ids, Array.from({ length: 205 }, (_, i) => String(i + 1)))
|
||||
})
|
||||
}
|
||||
|
||||
test("archive confirmation survives MCP's archived-record filter and upload forwards the active user", async () => {
|
||||
const calls: any[] = []
|
||||
const tools = createDocumentTools({ inbox: () => ({
|
||||
archiveDocument: async (...args: any[]) => { calls.push(args); return { id, archived: true } },
|
||||
upload: async (...args: any[]) => { calls.push(args); return { id, created: true, checksum: "hash" } },
|
||||
}) as any })
|
||||
const context = contextFor(profileDb())
|
||||
const archived = await tools.find(t => t.name.endsWith("inbox.archive"))!.handler(context, { id })
|
||||
assert.deepEqual(asToolResult(archived).structuredContent, { id, success: true, action: "archived" })
|
||||
assert.deepEqual(calls[0], [7, id, id])
|
||||
await tools.find(t => t.name.endsWith("files.upload"))!.handler(context, { filename: "scan.pdf", contentBase64: pdf.toString("base64") })
|
||||
assert.deepEqual(calls[1], [7, id, "scan.pdf", pdf])
|
||||
})
|
||||
|
||||
test("bounded downloads stop a stream even when persisted size is missing or incorrect", async () => {
|
||||
let closed = false
|
||||
async function* chunks() { try { yield Buffer.alloc(4); yield Buffer.alloc(4); yield Buffer.alloc(4) } finally { closed = true } }
|
||||
await assert.rejects(streamToBuffer(chunks(), 5), /zu groß/)
|
||||
assert.equal(closed, true)
|
||||
assert.deepEqual(await streamToBuffer(Readable.from([pdf]), pdf.length), pdf)
|
||||
})
|
||||
|
||||
test("HTTP MCP accepts uploads above 1 MiB and streams authorized PDFs without exposing storage paths", async t => {
|
||||
const apiBase = secrets.API_BASE_URL
|
||||
secrets.API_BASE_URL = "https://app.fedeo.test/backend/"
|
||||
t.after(() => { secrets.API_BASE_URL = apiBase })
|
||||
const row = { id, tenant: 7, name: "scan.pdf", mimeType: "application/pdf", size: pdf.length, archived: false, path: `7/filesbyid/${id}/scan.pdf` }
|
||||
let visible = true
|
||||
let portal = false
|
||||
let admin = true
|
||||
const bearer = "fedeo_mcp_test_documents_token"
|
||||
const headers = { authorization: `Bearer ${bearer}` }
|
||||
const db = drizzle(async (sql, params) => {
|
||||
if (sql.includes('from "m2m_api_keys"')) {
|
||||
assert.ok(params.includes(createHash("sha256").update(bearer).digest("hex")))
|
||||
return { rows: [[id, 7, id, true, null, "test@example.invalid", admin]] }
|
||||
}
|
||||
if (sql.startsWith('update "m2m_api_keys"')) return { rows: [] }
|
||||
if (sql.includes('from "tenants"')) return { rows: [[null, null]] }
|
||||
if (sql.includes('from "auth_user_roles"')) return { rows: [[id]] }
|
||||
if (sql.includes('from "auth_role_permissions"')) return { rows: [] }
|
||||
if (sql.includes('from "auth_profiles"')) return { rows: portal ? [[123]] : [] }
|
||||
assert.match(sql, /from "files"/)
|
||||
assert.match(sql, /"tenant" =/)
|
||||
assert.match(sql, /"archived" =/)
|
||||
assert.ok(params.includes(7))
|
||||
const selected = sql.slice(7, sql.indexOf(" from ")).split(", ")
|
||||
const columns = getTableColumns(files)
|
||||
return { rows: visible ? [selected.map(column => {
|
||||
const name = column.match(/"([^"]+)"$/)![1]
|
||||
const key = Object.keys(columns).find(key => columns[key].name === name)!
|
||||
return row[key] ?? null
|
||||
})] : [] }
|
||||
})
|
||||
const app = Fastify()
|
||||
t.after(() => app.close())
|
||||
app.decorate("db", db as any)
|
||||
await app.register(authPlugin)
|
||||
await app.register(mcpRoutes, { prefix: "/api" })
|
||||
await initS3()
|
||||
t.mock.method(s3, "send", async command => {
|
||||
assert.equal(command.input.Key, row.path)
|
||||
return { Body: Readable.from([pdf]) }
|
||||
})
|
||||
const call = (name: string, args: any) => app.inject({ method: "POST", url: "/api/mcp", headers,
|
||||
payload: { jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: args } } })
|
||||
const download = await call("documents.files.download", { id })
|
||||
assert.equal(download.statusCode, 200)
|
||||
assert.equal(download.json().result.structuredContent.authentication, "Bearer")
|
||||
assert.equal(download.json().result.structuredContent.url, `https://app.fedeo.test/backend/api/mcp/files/${id}/content`)
|
||||
assert.ok(!download.body.includes("filesbyid"))
|
||||
const url = `/api/mcp/files/${id}/content`
|
||||
assert.equal((await app.inject(url)).statusCode, 401)
|
||||
const binary = await app.inject({ url, headers })
|
||||
assert.equal(binary.statusCode, 200, binary.body)
|
||||
assert.deepEqual(binary.rawPayload, pdf)
|
||||
assert.equal(binary.headers["content-type"], "application/pdf")
|
||||
assert.match(binary.headers["content-disposition"] as string, /attachment; filename="scan.pdf"/)
|
||||
assert.equal(binary.headers["cache-control"], "no-store")
|
||||
const base64 = await call("documents.files.download", { id, format: "base64" })
|
||||
assert.deepEqual(Buffer.from(base64.json().result.structuredContent.contentBase64, "base64"), pdf)
|
||||
admin = false
|
||||
assert.equal((await app.inject({ url, headers })).statusCode, 403)
|
||||
assert.equal((await call("documents.files.upload", { filename: "scan.pdf", contentBase64: pdf.toString("base64") })).json().error.code, -32003)
|
||||
admin = true
|
||||
portal = true
|
||||
assert.equal((await app.inject({ url, headers })).statusCode, 403)
|
||||
portal = false
|
||||
visible = false
|
||||
assert.equal((await app.inject({ url, headers })).statusCode, 404)
|
||||
assert.equal((await call("documents.files.download", { id })).json().result.isError, true)
|
||||
const largeInvalidUpload = await call("documents.files.upload", { filename: "scan.pdf", contentBase64: "A".repeat(2 * 1024 * 1024) })
|
||||
assert.equal(largeInvalidUpload.statusCode, 200, "the request must reach file validation, not Fastify's default 1 MiB limit")
|
||||
assert.equal(largeInvalidUpload.json().result.isError, true)
|
||||
const oversized = await app.inject({ method: "POST", url: "/api/mcp", headers: { "content-type": "application/json", "content-length": String(MCP_BODY_LIMIT + 1) }, payload: "{}" })
|
||||
assert.equal(oversized.statusCode, 413)
|
||||
})
|
||||
@@ -10,7 +10,9 @@ const tables = Object.values(schema).filter((value: any) => {
|
||||
try { return typeof getTableName(value) === "string" } catch { return false }
|
||||
})
|
||||
|
||||
for (const tool of mcpTools.filter((tool) => (tool.inputSchema.properties as any)?.offset)) {
|
||||
// Document/status tools load related records; their dedicated tests cover filtered pagination.
|
||||
for (const tool of mcpTools.filter((tool) => (tool.inputSchema.properties as any)?.offset && !tool.name.startsWith("documents.")
|
||||
&& tool.name !== "accounting.outgoing_documents.status.list")) {
|
||||
test(`${tool.name}: retrieves 205 records across stable, bounded pages`, async () => {
|
||||
const db = drizzle(async (sql, params) => {
|
||||
if (sql.includes('from "tenants"')) return { rows: [["skr03"]] }
|
||||
@@ -42,7 +44,7 @@ for (const tool of mcpTools.filter((tool) => (tool.inputSchema.properties as any
|
||||
const ids: unknown[] = []
|
||||
let offset = 0
|
||||
for (let page = 0; page < 3; page++) {
|
||||
const result: any = await tool.handler(context, { id: 1, limit: 100, offset })
|
||||
const result: any = await tool.handler(context, { ...((tool.inputSchema.properties as any).id ? { id: 1 } : {}), limit: 100, offset })
|
||||
assert.equal(result.rows.length, page < 2 ? 100 : 5)
|
||||
assert.equal(result.pagination.hasMore, page < 2)
|
||||
assert.equal(result.pagination.nextOffset, page < 2 ? offset + 100 : null)
|
||||
|
||||
88
backend/tests/pdfTransferSums.test.ts
Normal file
88
backend/tests/pdfTransferSums.test.ts
Normal file
@@ -0,0 +1,88 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { Readable } from "node:stream"
|
||||
import test from "node:test"
|
||||
import { PDFDocument, PDFPage } from "pdf-lib"
|
||||
import { createInvoicePDF } from "../src/utils/pdf"
|
||||
import { initS3, s3 } from "../src/utils/s3"
|
||||
|
||||
const createDocumentData = (type: string) => {
|
||||
const item = (pos: string) => ({
|
||||
mode: "normal",
|
||||
pos,
|
||||
text: `Artikel ${pos}`,
|
||||
quantity: "1",
|
||||
unit: "Stk",
|
||||
taxPercent: 19,
|
||||
price: "25,00 €",
|
||||
rowAmount: "25,00 €",
|
||||
})
|
||||
|
||||
return {
|
||||
type,
|
||||
adressLine: "Musterfirma, Musterweg 1, 12345 Musterstadt",
|
||||
recipient: ["Musterkunde"],
|
||||
info: [],
|
||||
title: type === "packingSlips" ? "Packschein" : type === "deliveryNotes" ? "Lieferschein" : "Rechnung",
|
||||
description: "Abschnitte mit Seitenumbruch",
|
||||
startText: "Ihre Artikel:",
|
||||
endText: "Vielen Dank.",
|
||||
rows: [
|
||||
{ mode: "title", pos: "1", text: "Abschnitt A" },
|
||||
item("1.1"),
|
||||
{ mode: "title", pos: "2", text: "Abschnitt B" },
|
||||
item("2.1"),
|
||||
{ mode: "pagebreak" },
|
||||
{ mode: "title", pos: "3", text: "Abschnitt C" },
|
||||
item("3.1"),
|
||||
],
|
||||
total: {
|
||||
titleSums: {
|
||||
"1 - Abschnitt A": "25,00 €",
|
||||
"2 - Abschnitt B": "25,00 €",
|
||||
"3 - Abschnitt C": "25,00 €",
|
||||
},
|
||||
titleSumsTransfer: {
|
||||
"2 - Abschnitt B": "25,00 €",
|
||||
"3 - Abschnitt C": "50,00 €",
|
||||
},
|
||||
},
|
||||
totalArray: [{ label: "Nettobetrag", content: "75,00 €" }],
|
||||
}
|
||||
}
|
||||
|
||||
for (const type of ["packingSlips", "deliveryNotes", "invoices"]) {
|
||||
test(`${type}: renders transfers only for priced documents, including before page breaks`, async t => {
|
||||
const background = await PDFDocument.create()
|
||||
background.addPage().drawText("Musterfirma", { x: 60, y: 800, size: 12 })
|
||||
const backgroundBytes = await background.save()
|
||||
|
||||
await initS3()
|
||||
t.mock.method(s3, "send", async () => ({ Body: Readable.from([backgroundBytes]) }))
|
||||
const drawText = t.mock.method(PDFPage.prototype, "drawText")
|
||||
|
||||
const result = await createInvoicePDF(null, "base64", createDocumentData(type), "test-letterhead.pdf")
|
||||
assert.equal(result?.mimeType, "application/pdf")
|
||||
const pdf = await PDFDocument.load(Buffer.from(result!.base64, "base64"))
|
||||
assert.equal(pdf.getPageCount(), 2)
|
||||
|
||||
const texts = drawText.mock.calls.map(call => call.arguments[0])
|
||||
for (const text of ["Abschnitt A", "Abschnitt B", "Abschnitt C", "Artikel 1.1", "Artikel 2.1", "Artikel 3.1"]) {
|
||||
assert.ok(texts.includes(text), `Missing document content: ${text}`)
|
||||
}
|
||||
assert.equal(texts.filter(text => text === "1 Stk").length, 3)
|
||||
assert.equal(texts.filter(text => text === "Check").length, type === "packingSlips" ? 2 : 0)
|
||||
|
||||
const transfers = texts.filter(text => text.startsWith("Übertrag:"))
|
||||
if (type === "invoices") {
|
||||
assert.deepEqual(transfers, ["Übertrag: 25,00 €", "Übertrag: 50,00 €"])
|
||||
assert.ok(texts.includes("75,00 €"))
|
||||
assert.equal(texts.filter(text => text === "Einheitspreis").length, 2)
|
||||
} else {
|
||||
assert.deepEqual(transfers, [])
|
||||
assert.ok(texts.every(text => !text.includes("€")), "Delivery documents must not display monetary amounts")
|
||||
for (const label of ["Steuer", "Einheitspreis", "Gesamt", "Nettobetrag"]) {
|
||||
assert.ok(!texts.includes(label), `Unexpected price label: ${label}`)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -18,6 +18,8 @@ import inboxRoutes from "../src/routes/documentInbox"
|
||||
import corsPlugin from "../src/plugins/cors"
|
||||
import { createScannerInboxService, SCANNER_UPLOAD_LIMIT, validateScannerFile, type ScannerInboxService } from "../src/modules/scanner-inbox.service"
|
||||
import type { FilingSuggestionResult } from "../src/modules/scanner-inbox-suggestions"
|
||||
import { createDocumentTools } from "../src/mcp/tools/documents"
|
||||
import { assertToolPermission } from "../src/mcp/authz"
|
||||
|
||||
const execute = promisify(execFile)
|
||||
const basic = (username = "scanner", password = "secret") => ({ authorization: `Basic ${Buffer.from(`${username}:${password}`).toString("base64")}` })
|
||||
@@ -611,4 +613,64 @@ test("scanner inbox integration: migration, persistence, isolation, retries and
|
||||
assert.equal((await send("new.pdf", pdf, basic(first.username, rotated.json().connection.password))).statusCode, 201)
|
||||
assert.equal((await service.list(1, 50, 0, "")).total, 2)
|
||||
})
|
||||
await t.test("MCP uploads, downloads and filing use the same tenant-scoped document lifecycle", async () => {
|
||||
const tools = createDocumentTools({ inbox: () => service, readFile: async key => {
|
||||
assert.ok(stored.has(key))
|
||||
return stored.get(key)!
|
||||
} })
|
||||
const call = async (name: string, args: any = {}, tenantId = 1) => {
|
||||
const tool = tools.find(tool => tool.name === `documents.${name}`)!
|
||||
const context = { server: { db }, userId, tenantId, isAdmin: false, permissions: ["documents.read", "documents.write"] } as any
|
||||
assertToolPermission(context, tool)
|
||||
return await tool.handler(context, args) as any
|
||||
}
|
||||
const upload = (filename: string, body = pdf, tenant = 1) => call("files.upload", { filename, contentBase64: body.toString("base64") }, tenant)
|
||||
await service.disable(1)
|
||||
const created = await upload("mcp.pdf")
|
||||
assert.equal(created.created, true, "MCP uploads do not require scanner credentials")
|
||||
assert.equal((await upload("mcp.pdf")).id, created.id)
|
||||
assert.equal((await upload("mcp.pdf")).created, false)
|
||||
await assert.rejects(upload("mcp.pdf", samplePdf), { statusCode: 409 })
|
||||
assert.notEqual((await upload("mcp.pdf", pdf, 2)).id, created.id)
|
||||
const row = (await pool.query("SELECT * FROM files WHERE id=$1", [created.id])).rows[0]
|
||||
assert.equal(row.created_by, userId)
|
||||
assert.deepEqual(stored.get(row.path), pdf)
|
||||
assert.equal(row.extracted_text, null)
|
||||
const list = await call("inbox.list", { search: "mcp.pdf", limit: 1 })
|
||||
assert.equal(list.rows[0].id, created.id)
|
||||
assert.equal(list.rows[0].suggestionStatus, "pending")
|
||||
assert.equal((await call("inbox.suggestion.get", { id: created.id })).status, "pending")
|
||||
const downloaded = await call("files.download", { id: created.id, format: "base64" })
|
||||
assert.deepEqual(Buffer.from(downloaded.contentBase64, "base64"), pdf)
|
||||
await assert.rejects(call("files.download", { id: created.id }, 2), { statusCode: 404 })
|
||||
await assert.rejects(call("inbox.archive", { id: created.id }, 2), { statusCode: 404 })
|
||||
await assert.rejects(call("inbox.file", { id: created.id, folder: foreignFolder, type: targetType }), { statusCode: 400 })
|
||||
await assert.rejects(call("inbox.file", { id: created.id, folder: targetFolder, type: alternativeType }), { statusCode: 400 })
|
||||
await pool.query("INSERT INTO projects (id, tenant, name) VALUES (901, 1, 'MCP project'), (902, 2, 'Foreign MCP project')")
|
||||
await assert.rejects(call("inbox.file", { id: created.id, folder: targetFolder, type: targetType, assignments: { project: 902 } }), { statusCode: 400 })
|
||||
const filed = await call("inbox.file", { id: created.id, folder: targetFolder, type: targetType, assignments: { project: 901 } })
|
||||
assert.equal(filed.id, created.id)
|
||||
assert.equal((await call("inbox.list", { search: "mcp.pdf" })).rows.length, 0)
|
||||
assert.equal((await call("files.list", { project: 901 })).rows[0].id, created.id)
|
||||
assert.equal((await call("files.get", { id: created.id })).file.path, undefined)
|
||||
await assert.rejects(call("inbox.archive", { id: created.id }), { statusCode: 409 })
|
||||
const archived = await upload("mcp-archive.pdf")
|
||||
await call("inbox.archive", { id: archived.id })
|
||||
await assert.rejects(call("files.download", { id: archived.id }), { statusCode: 404 })
|
||||
assert.equal((await call("files.list", { search: "mcp-archive.pdf" })).rows.length, 0)
|
||||
const before = stored.size
|
||||
storageFailure = true
|
||||
await assert.rejects(upload("mcp-storage-error.pdf"), /Simulated object store failure/)
|
||||
storageFailure = false
|
||||
await assert.rejects(upload("reject.pdf"))
|
||||
assert.equal(stored.size, before)
|
||||
assert.equal((await pool.query("SELECT count(*) FROM files WHERE name IN ('mcp-storage-error.pdf', 'reject.pdf')")).rows[0].count, "0")
|
||||
await pool.query("UPDATE tenants SET locked='maintenance_tenant' WHERE id=1")
|
||||
await assert.rejects(upload("mcp-maintenance.pdf"), { 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])
|
||||
await assert.rejects(upload("mcp-portal.pdf"), { statusCode: 403 })
|
||||
await assert.rejects(call("files.download", { id: created.id }), { statusCode: 403 })
|
||||
await pool.query("DELETE FROM auth_profiles")
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,5 +1,116 @@
|
||||
# FEDEO MCP
|
||||
|
||||
## Status der Ausgangsbelege
|
||||
|
||||
`accounting.outgoing_documents.status.get` lädt den Status eines Belegs anhand seiner numerischen `id`. `accounting.outgoing_documents.status.list` liefert dieselben Statusdaten mit kombinierbaren Filtern und Pagination:
|
||||
|
||||
| Filter | Bedeutung |
|
||||
| --- | --- |
|
||||
| `state` | Gespeicherter Buchungsstatus, z. B. `Entwurf` oder `Gebucht` |
|
||||
| `paymentStatus` | `Offen`, `Teilbezahlt`, `Bezahlt` oder `Überbezahlt` |
|
||||
| `cancelled` | Ob ein aktiver, fertiggestellter Stornobeleg verknüpft ist |
|
||||
| `type`, `customer`, `project` | Belegart, Kunden-ID und Projekt-ID |
|
||||
| `limit`, `offset` | Seitengröße und Startposition innerhalb der gefilterten Ergebnisse |
|
||||
|
||||
Beispiele für die Parameter von `tools/call`:
|
||||
|
||||
```json
|
||||
{"name":"accounting.outgoing_documents.status.get","arguments":{"id":42}}
|
||||
```
|
||||
|
||||
```json
|
||||
{"name":"accounting.outgoing_documents.status.list","arguments":{"state":"Gebucht","paymentStatus":"Teilbezahlt","cancelled":false,"limit":25,"offset":0}}
|
||||
```
|
||||
|
||||
Das Ergebnis enthält `state`, `cancelled`, `cancellationDocuments`, `paymentStatus`, `amount`, `paidAmount` und `openAmount` sowie Belegnummer, Belegart, Datum, Kunden- und Projekt-ID. Der Zahlungsstatus gilt für gebuchte, nicht stornierte Rechnungen und Abschlagsrechnungen. Bei Entwürfen, Angeboten, anderen Belegarten und stornierten Rechnungen ist `paymentStatus` gleich `null`.
|
||||
|
||||
Die Beträge folgen der Ausgangsbeleganzeige: Positionsnetto auf drei Nachkommastellen, Nettosumme und Steuergruppen (19 % / 7 %) separat auf zwei Nachkommastellen, anschließend Abzug verknüpfter Abschlagsrechnungen. Zahlungen und Stornobelege müssen zum aktiven Mandanten gehören und dürfen nicht archiviert sein; Stornoentwürfe zählen nicht. `openAmount` ist Belegbetrag abzüglich zugeordneter Zahlungen, auch wenn der Beleg storniert wurde. Es ist kein um den Stornobeleg saldierter Kontostand. Bei negativen Rechnungsbeträgen werden Rückzahlungen in der passenden Zahlungsrichtung ausgewertet.
|
||||
|
||||
Beide Werkzeuge benötigen `accounting.outgoing_documents.read` und verändern keine Belege oder Buchungen. Die berechneten Statusfilter werden vor `limit`/`offset` angewendet. Dafür liest das Backend bei Bedarf mehrere Stapel von jeweils 100 Belegen; große Filter-Offsets können entsprechend mehr Abfragen benötigen.
|
||||
|
||||
## Kalender und Termine
|
||||
|
||||
| Werkzeug | Funktion |
|
||||
| --- | --- |
|
||||
| `organisation.calendar.options` | Konfigurierte Terminarten, Status und Wiederholungsintervalle laden |
|
||||
| `organisation.events.list` | Termine und Serien mit Such-, Zeitraum-, Status- und Ressourcenfiltern auflisten |
|
||||
| `organisation.events.get` | Einen Termin anhand seiner numerischen `id` laden |
|
||||
| `organisation.events.create` | Termin anlegen; `name` und `startDate` sind Pflichtfelder |
|
||||
| `organisation.events.update` | Nur angegebene Felder eines Termins ändern |
|
||||
| `organisation.events.archive` | Termin oder gesamte Wiederholungsserie archivieren |
|
||||
|
||||
Lesende Werkzeuge benötigen `organisation.events.read`. Die Schreibwerkzeuge benötigen `organisation.events.write`; dieses Recht ist in den Bootstrap-Administratorrechten enthalten und muss anderen Rollen ausdrücklich zugewiesen werden. Schreibvorgänge protokollieren Benutzer, Zeitpunkt und Änderung in der Historie. Referenzen auf Projekte, Kunden, Lieferanten, Mitarbeiter, Fahrzeuge und Inventar werden auf Verfügbarkeit im aktiven Mandanten geprüft.
|
||||
|
||||
```json
|
||||
{"name":"organisation.events.create","arguments":{"name":"Projektbesprechung","startDate":"2026-10-15T09:00:00+02:00","endDate":"2026-10-15T10:00:00+02:00","state":"Final","repeatInterval":"Wöchentlich","project":42}}
|
||||
```
|
||||
|
||||
Zeitpunkte erfordern ISO-8601 mit `Z` oder explizitem Offset. Das Ende darf nicht vor dem Start liegen; `endDate: null` ist erlaubt. Statuswerte sind `Entwurf` und `Final` (Standard). Wiederholungen sind `Keine Wiederholung` (Standard), `Täglich`, `Wöchentlich`, `2-wöchentlich`, `Monatlich` und `Jährlich`. Weitere bearbeitbare Felder sind `eventtype`, `quick`, `color`, `notes`, `link`, `customer`, `vendor`, `profiles`, `vehicles`, `inventoryitems` und `inventoryitemgroups`.
|
||||
|
||||
`profiles` und `inventoryitemgroups` sind Listen von UUIDs; `vehicles` und `inventoryitems` enthalten numerische IDs. Beim Update ersetzen übergebene Listen die bisherigen Zuordnungen; `[]` leert eine Liste, `null` leert nullable Einzelfelder. Wiederholungsänderungen und Archivierung betreffen die gesamte Serie.
|
||||
|
||||
```json
|
||||
{"name":"organisation.events.list","arguments":{"from":"2026-10-12T00:00:00+02:00","to":"2026-10-19T00:00:00+02:00","state":"Final","limit":25}}
|
||||
```
|
||||
|
||||
`from`/`to` filtern überlappende Termine, wobei `to` exklusiv ist. Mit `profile`, `vehicle`, `inventoryitem` oder `inventoryitemgroup` lässt sich nach einzelnen Ressourcenzuordnungen filtern. Weitere Filter sind `query`, `project`, `customer`, `vendor`, `eventtype`, `state`, `quick` und `repeatInterval`.
|
||||
|
||||
Die Terminliste liefert gespeicherte Serien-Stammsätze, keine berechneten Einzelvorkommen. Bei gesetztem `from` liefert sie standardmäßig auch früher begonnene Wiederholungsserien als Kandidaten mit. `includeRecurring: false` beschränkt die Zeitraumprüfung auf den gespeicherten Start und das Ende. Auch bei Serien gelten `limit`/`offset` für Stammsätze. Abwesenheiten und Kalender-Abonnementlinks gehören nicht zu diesen Werkzeugen.
|
||||
|
||||
## Dokumentenablage und Dateiübertragung
|
||||
|
||||
Die Werkzeuge unter `documents.*` stellen die Dokumentenablage und den Zugriff auf gespeicherte Dateien bereit. Alle arbeiten im aktiven Mandanten und schließen archivierte Dateien aus. Portalbenutzer haben keinen Zugriff, auch wenn ihrer Rolle Dokumentenrechte zugewiesen wurden.
|
||||
|
||||
| Werkzeug | Funktion |
|
||||
| --- | --- |
|
||||
| `documents.inbox.list` / `.count` | Offene Dokumente suchen bzw. zählen |
|
||||
| `documents.folders.list` / `documents.types.list` | Verfügbare Ordner und Dokumenttypen laden |
|
||||
| `documents.assignment_kinds.list` | Unterstützte Zuordnungsarten anzeigen |
|
||||
| `documents.assignments.search` | Zuordnungsziele nach `kind` und optional `search` suchen |
|
||||
| `documents.inbox.assignments.get` | Bestehende Zuordnungen eines offenen Dokuments laden |
|
||||
| `documents.inbox.suggestion.get` / `.refresh` | KI-Ablagevorschlag abrufen bzw. erneut anfordern |
|
||||
| `documents.inbox.file` | Dokument mit Ordner, Typ und optionalen Zuordnungen ablegen |
|
||||
| `documents.inbox.archive` | Offenes Dokument archivieren |
|
||||
| `documents.files.list` / `.get` | Gespeicherte Dateien suchen bzw. Details und vorhandenen extrahierten Text laden |
|
||||
| `documents.files.download` | Originaldatei als Download-URL oder Base64 abrufen |
|
||||
| `documents.files.upload` | PDF oder Scan in die Dokumentenablage hochladen |
|
||||
|
||||
Listen und Suchwerkzeuge verwenden `limit` und `offset` wie unten beschrieben. `search` ist auf 200 Zeichen begrenzt. `documents.files.list` unterstützt zusätzlich `folder`, `type`, `mimeType` sowie Zuordnungsfilter wie `project`, `customer`, `incominginvoice` und `createddocument`. `folder: null` filtert Dateien auf der Hauptebene; ohne `folder` werden alle Ordner durchsucht. Die `id` eines Dokuments ist immer die Datei-UUID, keine Rechnungs- oder Belegnummer.
|
||||
|
||||
Lesende Werkzeuge und Downloads benötigen `documents.read`; Upload, Ablegen, Archivieren und erneute KI-Erkennung benötigen `documents.write`. Beide Rechte sind in den Bootstrap-Administratorrechten enthalten. Anderen Rollen müssen sie ausdrücklich zugewiesen werden. Scanner-Zugangsdaten werden für MCP-Uploads nicht benötigt.
|
||||
|
||||
### PDF-Download
|
||||
|
||||
Zunächst die Datei-UUID beispielsweise über `documents.files.list` mit `createddocument` oder `incominginvoice` ermitteln. Der Aufruf erfolgt über `tools/call` mit diesen Parametern:
|
||||
|
||||
```json
|
||||
{"name":"documents.files.download","arguments":{"id":"00000000-0000-4000-8000-000000000001"}}
|
||||
```
|
||||
|
||||
Standardmäßig enthält das Ergebnis `url`, `method: "GET"`, `authentication: "Bearer"`, Dateiname, MIME-Type und Größe. Die URL verwendet `API_BASE_URL` und den Pfad `/api/mcp/files/<id>/content`; ohne konfigurierte Basis ist sie relativ. Bei `https://app.fedeo.de/backend` lautet der Pfad somit `https://app.fedeo.de/backend/api/mcp/files/<id>/content`.
|
||||
|
||||
Die URL ist kein öffentlicher Freigabelink: Der GET-Aufruf benötigt denselben `Authorization: Bearer <MCP-Token>`-Header wie der MCP-Aufruf. Berechtigung, Mandant, Portalzugang und Archivstatus werden beim Download erneut geprüft. Der Inhalt wird als Attachment gestreamt; interne Speicherpfade und Tokens erscheinen nicht im Werkzeugergebnis.
|
||||
|
||||
Mit `"format":"base64"` liefert das Werkzeug stattdessen `contentBase64` direkt im Ergebnis, begrenzt auf 20 MiB. Für größere Dateien den URL-Abruf verwenden. Der Download gibt die gespeicherte Originaldatei unverändert zurück; er erzeugt oder konvertiert keine PDFs.
|
||||
|
||||
### Upload und Ablage
|
||||
|
||||
```json
|
||||
{"name":"documents.files.upload","arguments":{"filename":"rechnung.pdf","contentBase64":"<Base64-Dateiinhalt>"}}
|
||||
```
|
||||
|
||||
Uploads unterstützen vollständige PDF-, JPEG-, PNG- und TIFF-Dateien bis **20 MiB**. `contentBase64` muss normales, gepaddetes Base64 ohne Data-URL-Präfix enthalten. Dateiname, Dateisignatur und bei PDFs die Abschlussmarkierung werden geprüft. Die Größenbegrenzung des MCP-JSON-Endpunkts berücksichtigt den Base64-Aufschlag; sie gilt für den gesamten Request einschließlich etwaiger Batch-Aufrufe.
|
||||
|
||||
Der Upload liefert `id`, `created`, `checksum`, `filename`, `mimeType` und `size`. Er speichert das Original in der Dokumentenablage und stellt die bestehende KI-Vorbereitung in die Warteschlange. Gleicher Dateiname und gleicher Inhalt liefern bei Wiederholung dieselbe ID mit `created: false`, auch nach Ablage oder Archivierung. Ein anderer Inhalt unter demselben Namen wird abgewiesen. Fehlgeschlagene Uploads rollen die Datenbankänderungen zurück und bereinigen das Speicherobjekt.
|
||||
|
||||
Anschließend Ordner und Dokumenttyp auswählen und die zurückgegebene UUID ablegen:
|
||||
|
||||
```json
|
||||
{"name":"documents.inbox.file","arguments":{"id":"00000000-0000-4000-8000-000000000001","folder":null,"type":"00000000-0000-4000-8000-000000000002","assignments":{"project":42}}}
|
||||
```
|
||||
|
||||
`folder: null` steht für die Hauptebene. `type` ist erforderlich. Zuordnungen verwenden numerische IDs, außer `check` und `authProfile` (UUIDs). Nur angegebene Zuordnungen werden geändert; `null` entfernt eine Zuordnung. Ordner, Dokumenttyp und Zuordnungsziele müssen im aktiven Mandanten verfügbar sein. Ein fester Dokumenttyp des Ordners wird berücksichtigt. Nach erfolgreicher Ablage verschwindet das Dokument aus `inbox.list`, bleibt aber über `files.list`, `.get` und `.download` erreichbar.
|
||||
|
||||
## Listen und Pagination
|
||||
|
||||
Alle datensatzbasierten MCP-Listen und Suchwerkzeuge unterstützen `limit` (ganze Zahl 1–100, Standard 25) und `offset` (ganze Zahl ab 0). Das Wiki behält Standard 50. Die statische Liste der Beleg-Steuertypen benötigt keine Pagination.
|
||||
|
||||
@@ -45,10 +45,7 @@ export default defineNuxtRouteMiddleware(async (to, from) => {
|
||||
|
||||
// 3. Wenn eingeloggt
|
||||
if (to.path === "/login") {
|
||||
if (auth.user.must_change_password) {
|
||||
return navigateTo("/password-change")
|
||||
}
|
||||
return navigateTo(isPortalUser ? "/customer-portal" : "/")
|
||||
return navigateTo(auth.getLandingPath())
|
||||
}
|
||||
|
||||
if (auth.user.must_change_password && to.path !== "/password-change") {
|
||||
|
||||
@@ -7,7 +7,6 @@ definePageMeta({
|
||||
|
||||
const auth = useAuthStore()
|
||||
const toast = useToast()
|
||||
const router = useRouter()
|
||||
|
||||
const state = reactive({
|
||||
email: '',
|
||||
@@ -22,7 +21,6 @@ const doLogin = async (event: FormSubmitEvent<typeof state>) => {
|
||||
try {
|
||||
await auth.login(event.data.email, event.data.password, event.data.rememberMe)
|
||||
toast.add({title:"Einloggen erfolgreich"})
|
||||
await router.push("/")
|
||||
} catch (err: any) {
|
||||
toast.add({title:"Zugangsdaten falsch. Bitte überprüfen Sie Ihre Eingaben",color:"error"})
|
||||
} finally {
|
||||
|
||||
@@ -27,8 +27,8 @@ const doChange = async (event: FormSubmitEvent<typeof state>) => {
|
||||
})
|
||||
|
||||
toast.add({title:"Ändern erfolgreich"})
|
||||
await auth.logout()
|
||||
return navigateTo("/login")
|
||||
await auth.fetchMe()
|
||||
return navigateTo(auth.getLandingPath(), { replace: true })
|
||||
} catch (err: any) {
|
||||
toast.add({title:"Es gab ein Problem beim ändern",color:"error"})
|
||||
} finally {
|
||||
|
||||
@@ -31,6 +31,11 @@ export const useAuthStore = defineStore("auth", {
|
||||
}),
|
||||
|
||||
actions: {
|
||||
getLandingPath() {
|
||||
if (this.user?.must_change_password) return "/password-change"
|
||||
return this.profile?.customer_for_portal ? "/customer-portal" : "/"
|
||||
},
|
||||
|
||||
tokenCookie() {
|
||||
return useCookie<string | null>("token", { path: "/" })
|
||||
},
|
||||
@@ -265,14 +270,14 @@ export const useAuthStore = defineStore("auth", {
|
||||
const tempStore = useTempStore()
|
||||
|
||||
if(this.profile?.temp_config) tempStore.setStoredTempConfig(this.profile.temp_config)
|
||||
if(this.activeTenant > 0) {
|
||||
this.loading = false
|
||||
|
||||
navigateTo("/")
|
||||
if(this.activeTenant > 0) {
|
||||
return navigateTo(this.getLandingPath())
|
||||
}
|
||||
},
|
||||
|
||||
async login(email: string, password: string, rememberMe = false) {
|
||||
this.loading = true
|
||||
try {
|
||||
console.log("Auth login")
|
||||
const { token, refreshToken } = await useNuxtApp().$api("/auth/login", {
|
||||
@@ -289,21 +294,15 @@ export const useAuthStore = defineStore("auth", {
|
||||
await this.fetchMe(token)
|
||||
|
||||
|
||||
// 3. WICHTIG: Jetzt explizit weiterleiten!
|
||||
// Prüfen, ob der User geladen wurde
|
||||
if (this.user) {
|
||||
// Falls Passwort-Änderung erzwungen wird (passend zu deiner Middleware)
|
||||
if (this.user.must_change_password) {
|
||||
return navigateTo("/password-change")
|
||||
}
|
||||
|
||||
// Normaler Login -> Dashboard
|
||||
return navigateTo("/")
|
||||
}
|
||||
if (!this.user) throw new Error("Die Sitzung konnte nicht geladen werden.")
|
||||
this.loading = false
|
||||
return await navigateTo(this.getLandingPath(), { replace: true })
|
||||
|
||||
} catch (e) {
|
||||
console.log("login error:" + e)
|
||||
throw e
|
||||
} finally {
|
||||
this.loading = false
|
||||
}
|
||||
},
|
||||
|
||||
|
||||
@@ -80,7 +80,7 @@ test('an account without assigned tenants receives an explanation without loadin
|
||||
})
|
||||
|
||||
function authFixture() {
|
||||
const logs = [], calls = [], sessions = []
|
||||
const logs = [], calls = [], sessions = [], navigations = []
|
||||
const token = 'test-access-token'
|
||||
const refreshToken = 'test-refresh-token'
|
||||
let me = { user: { email: 'test@example.com' }, activeTenant: null, tenants: [], permissions: [], profile: null }
|
||||
@@ -89,10 +89,15 @@ function authFixture() {
|
||||
defineStore: (_, definition) => definition,
|
||||
console: { log: (...args) => logs.push(args), error: (...args) => logs.push(args) },
|
||||
useTempStore: () => ({ setStoredTempConfig() {} }),
|
||||
navigateTo() {},
|
||||
navigateTo: path => { navigations.push(path) },
|
||||
useNuxtApp: () => ({ $api: async (url, options) => {
|
||||
calls.push({ url, options })
|
||||
if (url === '/api/me') return me
|
||||
if (url === '/api/tenant') return { id: me.activeTenant }
|
||||
if (url === '/api/auth/password/change') {
|
||||
me = { ...me, user: { ...me.user, must_change_password: false } }
|
||||
return { success: true }
|
||||
}
|
||||
if (url === '/auth/login' || url === '/api/tenant/switch') return { token, refreshToken }
|
||||
throw Error('Unexpected API request: ' + url)
|
||||
} }),
|
||||
@@ -106,7 +111,7 @@ function authFixture() {
|
||||
store.getStoredRefreshToken = () => refreshToken
|
||||
store.scheduleSessionTimers = () => {}
|
||||
store.setSession = (...args) => sessions.push(args)
|
||||
return { store, logs, calls, sessions, token, refreshToken, setMe: value => { me = value } }
|
||||
return { store, context, logs, calls, sessions, navigations, token, refreshToken, setMe: value => { me = value } }
|
||||
}
|
||||
|
||||
test('refreshing a session without an active tenant clears the previous tenant state', async () => {
|
||||
@@ -130,3 +135,77 @@ test('login and tenant switching store credentials without writing them to the c
|
||||
assert.ok(!output.includes(f.token))
|
||||
assert.ok(!output.includes(f.refreshToken))
|
||||
})
|
||||
|
||||
function portalSession(mustChangePassword = false) {
|
||||
return {
|
||||
user: { email: 'customer@example.com', must_change_password: mustChangePassword },
|
||||
activeTenant: 7, tenants: [{ id: 7, name: 'Test tenant' }], permissions: [],
|
||||
profile: { customer_for_portal: 123 },
|
||||
}
|
||||
}
|
||||
|
||||
function runPage(f, name, action, data) {
|
||||
const { descriptor } = parse(fs.readFileSync(__dirname + `/../pages/${name}.vue`, 'utf8'))
|
||||
Object.assign(f.context, {
|
||||
useAuthStore: () => f.store, useToast: () => ({ add() {} }), definePageMeta() {},
|
||||
useRouter: () => ({ push: path => { f.navigations.push(path) } }),
|
||||
reactive: vue.reactive, ref: vue.ref, formData: data,
|
||||
})
|
||||
const source = descriptor.scriptSetup.content.replace(/^import .*$/gm, '')
|
||||
vm.runInContext(ts.transpile(source, { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS }), f.context)
|
||||
return vm.runInContext(`${action}({ data: formData })`, f.context)
|
||||
}
|
||||
|
||||
test('the login form navigates portal customers once, directly to their portal', async () => {
|
||||
const f = authFixture()
|
||||
f.setMe(portalSession())
|
||||
await runPage(f, 'login', 'doLogin', { email: 'customer@example.com', password: 'password', rememberMe: true })
|
||||
assert.deepEqual(f.navigations, ['/customer-portal'])
|
||||
assert.equal(f.store.loading, false)
|
||||
assert.equal(f.store.profile.customer_for_portal, 123)
|
||||
assert.equal(f.store.activeTenant, '7')
|
||||
})
|
||||
|
||||
test('first login opens password change and continues into the portal after saving', async () => {
|
||||
const f = authFixture()
|
||||
f.setMe(portalSession(true))
|
||||
await f.store.login('customer@example.com', 'initial-password')
|
||||
assert.deepEqual(f.navigations, ['/password-change'])
|
||||
await runPage(f, 'password-change', 'doChange', { oldPassword: 'initial-password', newPassword: 'new-password' })
|
||||
assert.deepEqual(f.navigations, ['/password-change', '/customer-portal'])
|
||||
assert.equal(f.store.user.must_change_password, false)
|
||||
assert.equal(f.calls.some(call => call.url === '/auth/logout'), false)
|
||||
})
|
||||
|
||||
test('internal users still land on the dashboard', async () => {
|
||||
const f = authFixture()
|
||||
await runPage(f, 'login', 'doLogin', { email: 'staff@example.com', password: 'password' })
|
||||
assert.deepEqual(f.navigations, ['/'])
|
||||
assert.equal(f.store.loading, false)
|
||||
})
|
||||
|
||||
test('restoring a portal session keeps portal routing and password-change precedence', async () => {
|
||||
const f = authFixture()
|
||||
f.setMe(portalSession())
|
||||
Object.assign(f.context, { defineNuxtRouteMiddleware: fn => fn, useAuthStore: () => f.store })
|
||||
const middleware = fs.readFileSync(__dirname + '/../middleware/auth.global.ts', 'utf8')
|
||||
vm.runInContext(ts.transpile(middleware, { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS }), f.context)
|
||||
const route = f.context.exports.default
|
||||
await route({ path: '/' })
|
||||
assert.deepEqual(f.navigations, ['/customer-portal'])
|
||||
await route({ path: '/customer-portal' })
|
||||
assert.equal(f.navigations.length, 1)
|
||||
await route({ path: '/login' })
|
||||
assert.equal(f.navigations.at(-1), '/customer-portal')
|
||||
f.store.user.must_change_password = true
|
||||
await route({ path: '/customer-portal' })
|
||||
assert.equal(f.navigations.at(-1), '/password-change')
|
||||
})
|
||||
|
||||
test('selecting a portal tenant also opens its portal', async () => {
|
||||
const f = authFixture()
|
||||
f.setMe(portalSession())
|
||||
await f.store.switchTenant('7')
|
||||
assert.deepEqual(f.navigations, ['/customer-portal'])
|
||||
assert.equal(f.store.loading, false)
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user