Compare commits
29 Commits
a8c6c2625c
...
v3.16.0
| Author | SHA1 | Date | |
|---|---|---|---|
| 1b617c7910 | |||
| 9e003125c2 | |||
| 76e82eae4f | |||
| f814689ddd | |||
| 755f1b7e0d | |||
| c6fd53307c | |||
| 0777315d1d | |||
| 9676a270da | |||
| 36dffc057a | |||
| ea31a15eac | |||
| f0775ad52a | |||
| e0a94f5e29 | |||
| da84e98b8a | |||
| bfba29b15e | |||
| 7a1986bbb8 | |||
| f3b4fac4c0 | |||
| f56a07f8e3 | |||
| 7b61857fb8 | |||
| 697f538b6e | |||
| e933782731 | |||
| ee8f16056f | |||
| 683be7761d | |||
| 42242390f3 | |||
| 4ffafef3f1 | |||
| 5dc9e686fc | |||
| 6eea3c0687 | |||
| 89185b4b08 | |||
| aa08f5c358 | |||
| 2c1047e624 |
3
backend/db/migrations/0082_archive_users.sql
Normal file
3
backend/db/migrations/0082_archive_users.sql
Normal file
@@ -0,0 +1,3 @@
|
||||
ALTER TABLE "auth_users" ADD COLUMN "archived_at" timestamp with time zone;
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE "auth_profiles" ADD COLUMN "archived_at" timestamp with time zone;
|
||||
@@ -0,0 +1,7 @@
|
||||
INSERT INTO notifications_event_types (event_key, display_name, description, category, allowed_channels) VALUES
|
||||
('collaboration.message.new', 'Zusammenarbeit: Chatnachrichten', 'Neue Nachrichten in freigegebenen Unterräumen und föderierten Chats.', 'collaboration', '["inapp","email","push"]'),
|
||||
('collaboration.room.invited', 'Zusammenarbeit: Einladungen', 'Persönliche Einladungen in freigegebene Unterräume und föderierte Chats.', 'collaboration', '["inapp","email","push"]')
|
||||
ON CONFLICT (event_key) DO NOTHING;
|
||||
--> statement-breakpoint
|
||||
CREATE INDEX notifications_collaboration_queued ON notifications_items(created_at)
|
||||
WHERE status='queued' AND event_type IN ('collaboration.message.new','collaboration.room.invited');
|
||||
@@ -554,6 +554,20 @@
|
||||
"when": 1791244800000,
|
||||
"tag": "0081_chat_media_reactions",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 79,
|
||||
"version": "7",
|
||||
"when": 1792022400000,
|
||||
"tag": "0082_archive_users",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 80,
|
||||
"version": "7",
|
||||
"when": 1792022400001,
|
||||
"tag": "0083_collaboration_notifications",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -82,6 +82,7 @@ export const authProfiles = pgTable("auth_profiles", {
|
||||
address_city: text("address_city"),
|
||||
|
||||
active: boolean("active").notNull().default(true),
|
||||
archived_at: timestamp("archived_at", { withTimezone: true }),
|
||||
})
|
||||
|
||||
export type AuthProfile = typeof authProfiles.$inferSelect
|
||||
|
||||
@@ -13,6 +13,7 @@ export const authUsers = pgTable("auth_users", {
|
||||
multiTenant: boolean("multi_tenant").notNull().default(true),
|
||||
must_change_password: boolean("must_change_password").notNull().default(false),
|
||||
is_admin: boolean("is_admin").notNull().default(false),
|
||||
archived_at: timestamp("archived_at", { withTimezone: true }),
|
||||
|
||||
updatedAt: timestamp("updated_at", { withTimezone: true }),
|
||||
|
||||
|
||||
@@ -5,7 +5,9 @@ import {
|
||||
text,
|
||||
jsonb,
|
||||
timestamp,
|
||||
index,
|
||||
} from "drizzle-orm/pg-core"
|
||||
import { sql } from "drizzle-orm"
|
||||
|
||||
import { tenants } from "./tenants"
|
||||
import { authUsers } from "./auth_users"
|
||||
@@ -48,7 +50,8 @@ export const notificationsItems = pgTable("notifications_items", {
|
||||
|
||||
sentAt: timestamp("sent_at", { withTimezone: true }),
|
||||
readAt: timestamp("read_at", { withTimezone: true }),
|
||||
})
|
||||
}, t => ({ collaborationQueued: index("notifications_collaboration_queued").on(t.createdAt)
|
||||
.where(sql`${t.status}='queued' AND ${t.eventType} IN ('collaboration.message.new','collaboration.room.invited')`) }))
|
||||
|
||||
export type NotificationItem = typeof notificationsItems.$inferSelect
|
||||
export type NewNotificationItem = typeof notificationsItems.$inferInsert
|
||||
|
||||
93
backend/src/mcp/fileUploads.ts
Normal file
93
backend/src/mcp/fileUploads.ts
Normal file
@@ -0,0 +1,93 @@
|
||||
import { assertToolPermission } from "./authz"
|
||||
import { assertInternalDocumentAccess, MCP_FILE_LIMIT } from "./documentFiles"
|
||||
import { McpContext, McpTool } from "./types"
|
||||
import { createScannerInboxService, validateScannerFile } from "../modules/scanner-inbox.service"
|
||||
import { uploadIncomingInvoiceFile } from "./tools/accounting"
|
||||
import { secrets } from "../utils/secrets"
|
||||
|
||||
export const MCP_UPLOAD_PATH = "/api/mcp/files"
|
||||
export const uploadTargets = ["inbox", "incoming_invoice"] as const
|
||||
export type UploadTarget = typeof uploadTargets[number]
|
||||
|
||||
export type McpFileUpload = {
|
||||
target: UploadTarget
|
||||
filename: string
|
||||
body: Buffer
|
||||
mimeType?: string | null
|
||||
invoiceId?: number | null
|
||||
prepare?: boolean
|
||||
}
|
||||
|
||||
export function mcpUploadUrl() {
|
||||
const base = secrets.API_BASE_URL?.replace(/\/+$/, "")
|
||||
return base ? `${base}${MCP_UPLOAD_PATH}` : MCP_UPLOAD_PATH
|
||||
}
|
||||
|
||||
const badRequest = (message: string, statusCode = 400) => Object.assign(new Error(message), { statusCode })
|
||||
|
||||
/** Reads the query options of the binary upload endpoint. */
|
||||
export function parseUploadQuery(query: Record<string, unknown>) {
|
||||
const target = (query.target ?? "inbox") as UploadTarget
|
||||
if (!uploadTargets.includes(target)) throw badRequest(`target muss ${uploadTargets.join(" oder ")} sein.`)
|
||||
let invoiceId: number | null = null
|
||||
if (query.invoiceId !== undefined && query.invoiceId !== "") {
|
||||
invoiceId = Number(query.invoiceId)
|
||||
if (!Number.isSafeInteger(invoiceId) || invoiceId < 1) throw badRequest("invoiceId muss eine positive ganze Zahl sein.")
|
||||
}
|
||||
if (query.prepare !== undefined && !["true", "false"].includes(String(query.prepare))) throw badRequest("prepare muss true oder false sein.")
|
||||
if (target === "inbox" && (invoiceId || query.prepare !== undefined)) throw badRequest("invoiceId und prepare gelten nur für target=incoming_invoice.")
|
||||
const filename = typeof query.filename === "string" && query.filename.trim() ? query.filename.trim() : null
|
||||
return { target, invoiceId, prepare: String(query.prepare) !== "false", filename }
|
||||
}
|
||||
|
||||
export async function storeMcpFileUpload(context: McpContext, upload: McpFileUpload) {
|
||||
if (!upload.body.length) throw badRequest("Die Datei ist leer.")
|
||||
if (upload.body.length > MCP_FILE_LIMIT) throw badRequest("MCP-Uploads sind auf 20 MiB begrenzt.", 413)
|
||||
if (upload.target === "inbox") {
|
||||
assertToolPermission(context, { name: "documents.files.upload", requiredPermissions: ["documents.write"] })
|
||||
await assertInternalDocumentAccess(context)
|
||||
const mimeType = validateScannerFile(upload.filename, upload.body)
|
||||
const result = await createScannerInboxService(context.server.db).upload(context.tenantId, context.userId, upload.filename, upload.body)
|
||||
return { ...result, filename: upload.filename, mimeType, size: upload.body.length }
|
||||
}
|
||||
assertToolPermission(context, { name: "accounting.incoming_invoices.files.upload", requiredPermissions: ["accounting.incoming_invoices.write"] })
|
||||
return uploadIncomingInvoiceFile(context, {
|
||||
filename: upload.filename,
|
||||
buffer: upload.body,
|
||||
mimeType: upload.mimeType || "application/octet-stream",
|
||||
invoiceId: upload.invoiceId,
|
||||
prepare: upload.prepare,
|
||||
})
|
||||
}
|
||||
|
||||
export const uploadUrlTool: McpTool = {
|
||||
name: "documents.files.upload_url",
|
||||
title: "Upload-Adresse für Dateien",
|
||||
description: "Liefert die HTTP-Adresse, über die Dateien ohne Base64 direkt hochgeladen werden (multipart/form-data oder Rohdaten, maximal 20 MiB). Für Uploads mit Dateizugriff, z. B. per curl, statt documents.files.upload oder accounting.incoming_invoices.files.upload verwenden.",
|
||||
// Informational only; the endpoint checks the permission of the chosen target.
|
||||
requiredPermissions: [],
|
||||
inputSchema: { type: "object", properties: {}, additionalProperties: false },
|
||||
async handler() {
|
||||
const url = mcpUploadUrl()
|
||||
return {
|
||||
url,
|
||||
method: "POST",
|
||||
authentication: "Authorization: Bearer <derselbe MCP-Token>",
|
||||
bodies: {
|
||||
multipart: "multipart/form-data mit dem Dateifeld file; der Dateiname wird aus dem Upload übernommen.",
|
||||
raw: "Dateiinhalt als Body mit passendem Content-Type (application/pdf, image/jpeg, image/png, image/tiff, application/xml oder application/octet-stream) und Query-Parameter filename.",
|
||||
},
|
||||
query: {
|
||||
target: "inbox (Standard, Dokumentenablage, benötigt documents.write) oder incoming_invoice (Eingangsrechnung, benötigt accounting.incoming_invoices.write).",
|
||||
filename: "Dateiname; bei Rohdaten erforderlich, bei multipart optional zum Überschreiben.",
|
||||
invoiceId: "Nur incoming_invoice: vorhandenen Eingangsbeleg verknüpfen.",
|
||||
prepare: "Nur incoming_invoice: false unterdrückt die automatische Belegvorbereitung (Standard true).",
|
||||
},
|
||||
response: "JSON wie beim entsprechenden Base64-Werkzeug.",
|
||||
examples: [
|
||||
`curl -H "Authorization: Bearer $FEDEO_MCP_TOKEN" -F "file=@rechnung.pdf" "${url}?target=incoming_invoice"`,
|
||||
`curl -H "Authorization: Bearer $FEDEO_MCP_TOKEN" -H "Content-Type: application/pdf" --data-binary @scan.pdf "${url}?filename=scan.pdf"`,
|
||||
],
|
||||
}
|
||||
},
|
||||
}
|
||||
@@ -3,6 +3,8 @@ import { masterdataTools } from "./tools/masterdata"
|
||||
import { organisationTools } from "./tools/organisation"
|
||||
import { wikiTools } from "./tools/wiki"
|
||||
import { documentTools } from "./tools/documents"
|
||||
import { archiveTools } from "./tools/archive"
|
||||
import { uploadUrlTool } from "./fileUploads"
|
||||
|
||||
export const mcpTools = [
|
||||
...accountingTools,
|
||||
@@ -10,6 +12,8 @@ export const mcpTools = [
|
||||
...organisationTools,
|
||||
...wikiTools,
|
||||
...documentTools,
|
||||
...archiveTools,
|
||||
uploadUrlTool,
|
||||
]
|
||||
|
||||
export const mcpToolMap = new Map(mcpTools.map((tool) => [tool.name, tool]))
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { outgoingAddressSchema, outgoingRowsSchema, outgoingReportSchema } from "../documentSchemas"
|
||||
import { limitFromArgs, offsetFromArgs, paginatedResult, paginationProperties } from "../pagination"
|
||||
import { and, desc, eq, ilike, or } from "drizzle-orm"
|
||||
import { and, desc, eq, ilike, inArray, or } from "drizzle-orm"
|
||||
import { randomUUID } from "node:crypto"
|
||||
import { validateBankAllocationCostCentre } from "../../modules/bank-allocation-details"
|
||||
import {
|
||||
@@ -22,11 +22,14 @@ import { saveFile } from "../../utils/files"
|
||||
import { insertHistoryItem } from "../../utils/history"
|
||||
import { executeManualGeneration, finishManualGeneration } from "../../modules/serialexecution.service"
|
||||
import { updateOutgoingDocumentCostCentres } from "../../modules/outgoing-document-cost-centres.service"
|
||||
import { updateIncomingInvoiceCostCentres } from "../../modules/incoming-invoice-cost-centres.service"
|
||||
import { loadBankBalances } from "../../modules/bank-balances.service"
|
||||
import { dateField } from "../masterdataFields"
|
||||
import {
|
||||
prepareStatementAllocationInput,
|
||||
statementAllocationUuidArg,
|
||||
} from "../statementAllocations"
|
||||
import { McpTool } from "../types"
|
||||
import { McpContext, McpTool } from "../types"
|
||||
import { outgoingStatusTools } from "./outgoingStatus"
|
||||
|
||||
export { prepareStatementAllocationInput } from "../statementAllocations"
|
||||
@@ -309,6 +312,98 @@ const loadIncomingInvoiceFileDefaults = async (context: { server: any; tenantId:
|
||||
}
|
||||
}
|
||||
|
||||
export type IncomingInvoiceFileUpload = {
|
||||
filename: string
|
||||
buffer: Buffer
|
||||
mimeType: string
|
||||
invoiceId?: number | null
|
||||
invoiceArgs?: Record<string, unknown> | null
|
||||
prepare?: boolean
|
||||
}
|
||||
|
||||
/** Shared by the Base64 tool and the binary MCP upload endpoint. */
|
||||
export async function uploadIncomingInvoiceFile(context: McpContext, upload: IncomingInvoiceFileUpload) {
|
||||
const { filename, buffer, mimeType } = upload
|
||||
const invoiceId = upload.invoiceId || null
|
||||
const invoiceArgs = upload.invoiceArgs || null
|
||||
const shouldPrepare = upload.prepare !== false && !invoiceId && !invoiceArgs
|
||||
if (!buffer.length) throw new Error("Datei ist leer")
|
||||
if (buffer.length > MAX_MCP_UPLOAD_BYTES) throw new Error("Datei ist größer als 20 MB")
|
||||
|
||||
let linkedInvoice: any = null
|
||||
|
||||
if (invoiceId) {
|
||||
const [existing] = await context.server.db
|
||||
.select()
|
||||
.from(incominginvoices)
|
||||
.where(and(eq(incominginvoices.id, invoiceId), eq(incominginvoices.tenant, context.tenantId)))
|
||||
.limit(1)
|
||||
|
||||
if (!existing) throw new Error("Eingangsbeleg nicht gefunden")
|
||||
linkedInvoice = existing
|
||||
} else if (invoiceArgs) {
|
||||
const payload = buildIncomingInvoicePayload(invoiceArgs, context.userId, context.tenantId, true)
|
||||
payload.state = "Entwurf"
|
||||
|
||||
const [createdInvoice] = await context.server.db
|
||||
.insert(incominginvoices)
|
||||
.values(payload as any)
|
||||
.returning()
|
||||
|
||||
linkedInvoice = createdInvoice
|
||||
}
|
||||
|
||||
const defaults = await loadIncomingInvoiceFileDefaults(context)
|
||||
const saved = await saveFile(
|
||||
context.server,
|
||||
context.tenantId,
|
||||
null,
|
||||
{
|
||||
filename,
|
||||
content: buffer,
|
||||
contentType: mimeType,
|
||||
},
|
||||
defaults.folderId,
|
||||
defaults.fileTagId,
|
||||
{
|
||||
incominginvoice: linkedInvoice?.id || null,
|
||||
createdBy: context.userId,
|
||||
updatedBy: context.userId,
|
||||
updatedAt: new Date(),
|
||||
}
|
||||
)
|
||||
|
||||
if (!saved) throw new Error("Datei konnte nicht gespeichert werden")
|
||||
|
||||
if (shouldPrepare) {
|
||||
// Only the uploaded file; other open invoice files stay for an explicit preparation run.
|
||||
await context.server.services.prepareIncomingInvoices.run(context.tenantId, { fileIds: [saved.id] })
|
||||
}
|
||||
|
||||
const [file] = await context.server.db
|
||||
.select()
|
||||
.from(files)
|
||||
.where(and(eq(files.id, saved.id), eq(files.tenant, context.tenantId)))
|
||||
.limit(1)
|
||||
|
||||
if (file?.incominginvoice && !linkedInvoice) {
|
||||
const [preparedInvoice] = await context.server.db
|
||||
.select()
|
||||
.from(incominginvoices)
|
||||
.where(and(eq(incominginvoices.id, file.incominginvoice), eq(incominginvoices.tenant, context.tenantId)))
|
||||
.limit(1)
|
||||
|
||||
linkedInvoice = preparedInvoice || null
|
||||
}
|
||||
|
||||
return {
|
||||
file,
|
||||
invoice: linkedInvoice,
|
||||
validation: linkedInvoice ? validateIncomingInvoiceData(linkedInvoice as Record<string, any>) : null,
|
||||
prepared: Boolean(shouldPrepare && linkedInvoice),
|
||||
}
|
||||
}
|
||||
|
||||
const buildIncomingInvoicePayload = (
|
||||
args: Record<string, unknown>,
|
||||
userId: string,
|
||||
@@ -1011,7 +1106,7 @@ export const accountingTools: McpTool[] = [
|
||||
{
|
||||
name: "accounting.incoming_invoices.files.upload",
|
||||
title: "Datei für Eingangsbeleg hochladen",
|
||||
description: "Lädt eine PDF- oder Bilddatei als Base64 hoch, verknüpft sie optional mit einem Eingangsbeleg oder stößt die automatische Vorbereitung an.",
|
||||
description: "Lädt eine PDF- oder Bilddatei als Base64 hoch, verknüpft sie optional mit einem Eingangsbeleg oder stößt die automatische Vorbereitung dieser Datei an. Mit Dateizugriff besser ohne Base64 über die Adresse aus documents.files.upload_url (target=incoming_invoice) hochladen.",
|
||||
requiredPermissions: ["accounting.incoming_invoices.write"],
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
@@ -1047,83 +1142,14 @@ export const accountingTools: McpTool[] = [
|
||||
const filename = stringArg(args, "filename")
|
||||
if (!filename) throw new Error("filename ist erforderlich")
|
||||
|
||||
const buffer = base64BufferArg(args, "contentBase64")
|
||||
const mimeType = stringArg(args, "mimeType") || "application/octet-stream"
|
||||
const invoiceId = numberArg(args, "invoiceId")
|
||||
const invoiceArgs = optionalObjectArg(args, "invoice") as Record<string, unknown> | null
|
||||
const shouldPrepare = args.prepare !== false && !invoiceId && !invoiceArgs
|
||||
|
||||
let linkedInvoice: any = null
|
||||
|
||||
if (invoiceId) {
|
||||
const [existing] = await context.server.db
|
||||
.select()
|
||||
.from(incominginvoices)
|
||||
.where(and(eq(incominginvoices.id, invoiceId), eq(incominginvoices.tenant, context.tenantId)))
|
||||
.limit(1)
|
||||
|
||||
if (!existing) throw new Error("Eingangsbeleg nicht gefunden")
|
||||
linkedInvoice = existing
|
||||
} else if (invoiceArgs) {
|
||||
const payload = buildIncomingInvoicePayload(invoiceArgs, context.userId, context.tenantId, true)
|
||||
payload.state = "Entwurf"
|
||||
|
||||
const [createdInvoice] = await context.server.db
|
||||
.insert(incominginvoices)
|
||||
.values(payload as any)
|
||||
.returning()
|
||||
|
||||
linkedInvoice = createdInvoice
|
||||
}
|
||||
|
||||
const defaults = await loadIncomingInvoiceFileDefaults(context)
|
||||
const saved = await saveFile(
|
||||
context.server,
|
||||
context.tenantId,
|
||||
null,
|
||||
{
|
||||
filename,
|
||||
content: buffer,
|
||||
contentType: mimeType,
|
||||
},
|
||||
defaults.folderId,
|
||||
defaults.fileTagId,
|
||||
{
|
||||
incominginvoice: linkedInvoice?.id || null,
|
||||
createdBy: context.userId,
|
||||
updatedBy: context.userId,
|
||||
updatedAt: new Date(),
|
||||
}
|
||||
)
|
||||
|
||||
if (!saved) throw new Error("Datei konnte nicht gespeichert werden")
|
||||
|
||||
if (shouldPrepare) {
|
||||
await context.server.services.prepareIncomingInvoices.run(context.tenantId)
|
||||
}
|
||||
|
||||
const [file] = await context.server.db
|
||||
.select()
|
||||
.from(files)
|
||||
.where(and(eq(files.id, saved.id), eq(files.tenant, context.tenantId)))
|
||||
.limit(1)
|
||||
|
||||
if (file?.incominginvoice && !linkedInvoice) {
|
||||
const [preparedInvoice] = await context.server.db
|
||||
.select()
|
||||
.from(incominginvoices)
|
||||
.where(and(eq(incominginvoices.id, file.incominginvoice), eq(incominginvoices.tenant, context.tenantId)))
|
||||
.limit(1)
|
||||
|
||||
linkedInvoice = preparedInvoice || null
|
||||
}
|
||||
|
||||
return {
|
||||
file,
|
||||
invoice: linkedInvoice,
|
||||
validation: linkedInvoice ? validateIncomingInvoiceData(linkedInvoice as Record<string, any>) : null,
|
||||
prepared: Boolean(shouldPrepare && linkedInvoice),
|
||||
}
|
||||
return uploadIncomingInvoiceFile(context, {
|
||||
filename,
|
||||
buffer: base64BufferArg(args, "contentBase64"),
|
||||
mimeType: stringArg(args, "mimeType") || "application/octet-stream",
|
||||
invoiceId: numberArg(args, "invoiceId"),
|
||||
invoiceArgs: optionalObjectArg(args, "invoice") as Record<string, unknown> | null,
|
||||
prepare: args.prepare !== false,
|
||||
})
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -1152,6 +1178,62 @@ export const accountingTools: McpTool[] = [
|
||||
return validateIncomingInvoiceData(rows[0] as Record<string, any>)
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "accounting.incoming_invoices.prepare",
|
||||
title: "Belegvorbereitung starten",
|
||||
description: "Startet die Belegvorbereitung wie der Button „Belege vorbereiten“: Dateien vom Typ Eingangsrechnung ohne verknüpften Beleg werden ausgelesen (strukturierte E-Rechnung, sonst KI) und als Eingangsbeleg-Entwurf angelegt. Optional nur für bestimmte Datei-IDs. Kann je Datei einige Sekunden dauern.",
|
||||
requiredPermissions: ["accounting.incoming_invoices.write"],
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
fileIds: {
|
||||
type: "array",
|
||||
items: { type: "string", format: "uuid" },
|
||||
minItems: 1,
|
||||
maxItems: 50,
|
||||
description: "Optionale Datei-IDs; ohne Angabe alle offenen Eingangsrechnungsdateien.",
|
||||
},
|
||||
},
|
||||
additionalProperties: false,
|
||||
},
|
||||
async handler(context, args) {
|
||||
let fileIds: string[] | undefined
|
||||
if (args.fileIds !== undefined) {
|
||||
if (!Array.isArray(args.fileIds) || !args.fileIds.length || args.fileIds.length > 50) {
|
||||
throw new Error("fileIds muss 1 bis 50 Datei-IDs enthalten")
|
||||
}
|
||||
if (args.fileIds.some((id) => typeof id !== "string" || !UUID_PATTERN.test(id))) {
|
||||
throw new Error("fileIds darf nur gültige UUIDs enthalten")
|
||||
}
|
||||
fileIds = [...new Set((args.fileIds as string[]).map((id) => id.toLowerCase()))]
|
||||
}
|
||||
|
||||
const result = await context.server.services.prepareIncomingInvoices.run(context.tenantId, { fileIds })
|
||||
if (result.error && !result.filesFound) throw new Error(result.error)
|
||||
|
||||
const invoiceIds = result.created.map((entry) => entry.invoiceId)
|
||||
const invoices = invoiceIds.length
|
||||
? await context.server.db
|
||||
.select()
|
||||
.from(incominginvoices)
|
||||
.where(and(eq(incominginvoices.tenant, context.tenantId), inArray(incominginvoices.id, invoiceIds)))
|
||||
: []
|
||||
const handled = new Set([...result.created, ...result.skipped].map((entry) => entry.fileId))
|
||||
|
||||
return {
|
||||
filesFound: result.filesFound,
|
||||
created: result.created.map((entry) => {
|
||||
const invoice = invoices.find((row) => row.id === entry.invoiceId) || null
|
||||
return { ...entry, invoice, validation: invoice ? validateIncomingInvoiceData(invoice as Record<string, any>) : null }
|
||||
}),
|
||||
skipped: [
|
||||
...result.skipped,
|
||||
...(fileIds || []).filter((id) => !handled.has(id))
|
||||
.map((fileId) => ({ fileId, reason: "Keine offene Eingangsrechnungsdatei (nicht gefunden, archiviert, anderer Dateityp oder bereits vorbereitet)" })),
|
||||
],
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "accounting.incoming_invoices.create",
|
||||
title: "Eingangsbeleg erstellen",
|
||||
@@ -1229,6 +1311,44 @@ export const accountingTools: McpTool[] = [
|
||||
return { invoice: updated, validation: validateIncomingInvoiceData(updated as Record<string, any>) }
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "accounting.incoming_invoices.cost_centres.update",
|
||||
title: "Kostenstellen eines Eingangsbelegs ändern",
|
||||
description: "Ändert ausschließlich die Positionskostenstellen eines Eingangsbelegs, auch wenn er gebucht oder einer Bankbuchung zugewiesen ist.",
|
||||
requiredPermissions: ["accounting.incoming_invoices.write"],
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
required: ["id", "accountCostCentres"],
|
||||
properties: {
|
||||
id: { type: "number" },
|
||||
accountCostCentres: {
|
||||
type: "array",
|
||||
minItems: 1,
|
||||
items: {
|
||||
type: "object",
|
||||
required: ["index", "costcentre"],
|
||||
properties: {
|
||||
index: { type: "integer", minimum: 0, description: "Nullbasierter Index der Position in accounts." },
|
||||
costcentre: { type: ["string", "null"], description: "UUID der Positionskostenstelle oder null." },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
async handler(context, args) {
|
||||
const id = numberArg(args, "id")
|
||||
if (!id) throw new Error("id ist erforderlich")
|
||||
|
||||
const invoice = await updateIncomingInvoiceCostCentres(
|
||||
context.server,
|
||||
context.tenantId,
|
||||
context.userId,
|
||||
id,
|
||||
{ accountCostCentres: args.accountCostCentres as any },
|
||||
)
|
||||
return { invoice }
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "accounting.incoming_invoices.book",
|
||||
title: "Eingangsbeleg buchen",
|
||||
@@ -1310,6 +1430,26 @@ export const accountingTools: McpTool[] = [
|
||||
return { invoice: updated }
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "accounting.bank_accounts.balances",
|
||||
title: "Kontostände abfragen",
|
||||
description: "Liefert die Kontostände der Bankkonten und Kassenbücher des aktiven Mandanten samt Summe. Bankkonten zeigen den zuletzt synchronisierten Buchungssaldo; mit asOf wird der Stand zu einem vergangenen Datum aus den Bankumsätzen zurückgerechnet. Kassenbücher ergeben sich aus Anfangsbestand und Buchungen.",
|
||||
requiredPermissions: ["accounting.bank.read"],
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
account: { type: "number", description: "Optionale Bankkonto-ID; ohne Angabe alle Konten." },
|
||||
asOf: { ...dateField.schema, description: "Optionaler Stichtag YYYY-MM-DD (Stand zum Tagesende)." },
|
||||
},
|
||||
},
|
||||
async handler(context, args) {
|
||||
const account = numberArg(args, "account")
|
||||
const asOf = args.asOf === undefined || args.asOf === null ? null : dateField.parse(args.asOf, "asOf")
|
||||
const result = await loadBankBalances(context.server, context.tenantId, { account, asOf })
|
||||
if (account && !result.accounts.length) throw new Error("Bankkonto nicht gefunden")
|
||||
return result
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "accounting.bank_statements.list",
|
||||
title: "Bankumsätze auflisten",
|
||||
|
||||
150
backend/src/mcp/tools/archive.ts
Normal file
150
backend/src/mcp/tools/archive.ts
Normal file
@@ -0,0 +1,150 @@
|
||||
import { and, desc, eq, getTableColumns, ilike, or } from "drizzle-orm"
|
||||
import * as tables from "../../../db/schema"
|
||||
import { assertToolPermission } from "../authz"
|
||||
import { assertInternalDocumentAccess } from "../documentFiles"
|
||||
import { idField, InputField, numericField, objectField, textField, uuidField } from "../masterdataFields"
|
||||
import { limitFromArgs, offsetFromArgs, paginatedResult, paginationProperties } from "../pagination"
|
||||
import { McpContext, McpTool } from "../types"
|
||||
import { insertHistoryItem } from "../../utils/history"
|
||||
import { recalculateServicePricesForTenant } from "../../modules/service-price-recalculation.service"
|
||||
|
||||
type ArchiveEntity = {
|
||||
label: string
|
||||
table: any
|
||||
/** Key used by the history log and the generic resource routes. */
|
||||
resource: string
|
||||
permission: string
|
||||
searchColumns: string[]
|
||||
uuid?: boolean
|
||||
internalDocuments?: boolean
|
||||
}
|
||||
|
||||
const masterdata = (label: string, table: any, resource: string, namespace: string, searchColumns: string[], uuid = false): ArchiveEntity =>
|
||||
({ label, table, resource, permission: `masterdata.${namespace}`, searchColumns, uuid })
|
||||
|
||||
/** Every entity the MCP can archive; restore checks the matching write permission. */
|
||||
export const archiveEntities: Record<string, ArchiveEntity> = {
|
||||
customers: masterdata("Kunde", tables.customers, "customers", "customers", ["name", "customerNumber"]),
|
||||
vendors: masterdata("Lieferant", tables.vendors, "vendors", "vendors", ["name", "vendorNumber"]),
|
||||
contacts: masterdata("Kontakt", tables.contacts, "contacts", "contacts", ["fullName", "email"]),
|
||||
products: masterdata("Artikel", tables.products, "products", "products", ["name", "article_number"]),
|
||||
services: masterdata("Leistung", tables.services, "services", "services", ["name"]),
|
||||
cost_centres: masterdata("Kostenstelle", tables.costcentres, "costcentres", "cost_centres", ["name", "number"], true),
|
||||
branches: masterdata("Niederlassung", tables.branches, "branches", "branches", ["name", "number"]),
|
||||
teams: masterdata("Team", tables.teams, "teams", "teams", ["name"]),
|
||||
vehicles: masterdata("Fahrzeug", tables.vehicles, "vehicles", "vehicles", ["name", "license_plate"]),
|
||||
inventory_items: masterdata("Inventar", tables.inventoryitems, "inventoryitems", "inventory_items", ["name", "articleNumber"]),
|
||||
projects: { label: "Projekt", table: tables.projects, resource: "projects", permission: "organisation.projects", searchColumns: ["name", "projectNumber"] },
|
||||
events: { label: "Termin", table: tables.events, resource: "events", permission: "organisation.events", searchColumns: ["name"] },
|
||||
tasks: { label: "Aufgabe", table: tables.tasks, resource: "tasks", permission: "organisation.tasks", searchColumns: ["name"] },
|
||||
outgoing_documents: { label: "Ausgangsbeleg", table: tables.createddocuments, resource: "createddocuments", permission: "accounting.outgoing_documents", searchColumns: ["documentNumber", "title"] },
|
||||
incoming_invoices: { label: "Eingangsbeleg", table: tables.incominginvoices, resource: "incominginvoices", permission: "accounting.incoming_invoices", searchColumns: ["reference", "description"] },
|
||||
files: { label: "Datei", table: tables.files, resource: "files", permission: "documents", searchColumns: ["name"], uuid: true, internalDocuments: true },
|
||||
}
|
||||
|
||||
const entityField: InputField = {
|
||||
schema: { type: "string", enum: Object.keys(archiveEntities), description: "Art des archivierten Datensatzes." },
|
||||
parse(value, path) {
|
||||
if (typeof value !== "string" || !Object.prototype.hasOwnProperty.call(archiveEntities, value)) throw new Error(`${path}: unbekannte Entität`)
|
||||
return value
|
||||
},
|
||||
}
|
||||
const entityIdField: InputField = {
|
||||
schema: { type: ["integer", "string"], description: "ID des Datensatzes; UUID bei cost_centres und files, sonst ganze Zahl." },
|
||||
parse: (value) => value,
|
||||
}
|
||||
const searchField: InputField = {
|
||||
schema: { type: "string", maxLength: 200, description: "Optionaler Suchtext, z. B. Name oder Nummer." },
|
||||
parse(value, path) {
|
||||
const text = textField().parse(value, path)
|
||||
if (text.length > 200) throw new Error(`${path}: maximal 200 Zeichen`)
|
||||
return text
|
||||
},
|
||||
}
|
||||
const listInput = objectField({
|
||||
entity: entityField,
|
||||
search: searchField,
|
||||
limit: { ...numericField(true, 1, 100), schema: paginationProperties.limit },
|
||||
offset: { ...numericField(true, 0), schema: paginationProperties.offset },
|
||||
})
|
||||
const restoreInput = objectField({ entity: entityField, id: entityIdField })
|
||||
|
||||
const columnKey = (table: any, ...names: string[]) => names.find((name) => name in getTableColumns(table))
|
||||
|
||||
/** asToolResult hides records flagged archived; archived rows are marked explicitly instead. */
|
||||
const withoutArchivedFlag = ({ archived: _archived, path: _path, extractedText: _text, ...row }: Record<string, any>) => row
|
||||
|
||||
async function authorize(context: McpContext, tool: McpTool, entity: ArchiveEntity, access: "read" | "write") {
|
||||
assertToolPermission(context, { name: tool.name, requiredPermissions: [`${entity.permission}.${access}`] })
|
||||
if (entity.internalDocuments) await assertInternalDocumentAccess(context)
|
||||
}
|
||||
|
||||
export function prepareArchiveRestoreInput(args: Record<string, unknown>) {
|
||||
const input = restoreInput.parse(args, "arguments")
|
||||
if (!input.entity) throw new Error("entity ist erforderlich")
|
||||
if (input.id === undefined || input.id === null) throw new Error("id ist erforderlich")
|
||||
const entity = archiveEntities[input.entity]
|
||||
return { key: input.entity as string, entity, id: (entity.uuid ? uuidField : idField).parse(input.id, "id") }
|
||||
}
|
||||
|
||||
const listTool: McpTool = {
|
||||
name: "archive.entities.list",
|
||||
title: "Archivierte Einträge auflisten",
|
||||
description: "Listet archivierte Datensätze einer Entitätsart im aktiven Mandanten, zuletzt geänderte zuerst. IDs anschließend mit archive.entities.restore wiederherstellen.",
|
||||
// Checked per entity in the handler.
|
||||
requiredPermissions: [],
|
||||
inputSchema: { ...listInput.schema, required: ["entity"] },
|
||||
async handler(context, args) {
|
||||
const input = listInput.parse(args, "arguments")
|
||||
if (!input.entity) throw new Error("entity ist erforderlich")
|
||||
const entity = archiveEntities[input.entity]
|
||||
await authorize(context, listTool, entity, "read")
|
||||
const table = entity.table
|
||||
const conditions: any[] = [eq(table.tenant, context.tenantId), eq(table.archived, true)]
|
||||
if (input.search) {
|
||||
const pattern = `%${input.search.replace(/[\\%_]/g, "\\$&")}%`
|
||||
conditions.push(or(...entity.searchColumns.map((column) => ilike(table[column], pattern))))
|
||||
}
|
||||
const updatedAt = columnKey(table, "updatedAt", "updated_at")!
|
||||
const rows = await context.server.db.select().from(table).where(and(...conditions))
|
||||
.orderBy(desc(table[updatedAt]), desc(table.id)).limit(limitFromArgs(input) + 1).offset(offsetFromArgs(input))
|
||||
const result = paginatedResult(rows, input)
|
||||
return { ...result, entity: input.entity, rows: result.rows.map((row: any) => ({ ...withoutArchivedFlag(row), isArchived: true })) }
|
||||
},
|
||||
}
|
||||
|
||||
const restoreTool: McpTool = {
|
||||
name: "archive.entities.restore",
|
||||
title: "Archivierten Eintrag wiederherstellen",
|
||||
description: `Stellt einen archivierten Datensatz im aktiven Mandanten wieder her (entity: ${Object.keys(archiveEntities).join(", ")}). Benötigt die Schreibberechtigung der jeweiligen Entität.`,
|
||||
requiredPermissions: [],
|
||||
readOnly: false,
|
||||
inputSchema: { ...restoreInput.schema, required: ["entity", "id"] },
|
||||
async handler(context, args) {
|
||||
const { key, entity, id } = prepareArchiveRestoreInput(args)
|
||||
await authorize(context, restoreTool, entity, "write")
|
||||
const table = entity.table
|
||||
return context.server.db.transaction(async (tx) => {
|
||||
const server = { ...context.server, db: tx } as unknown as McpContext["server"]
|
||||
const scope = and(eq(table.id, id), eq(table.tenant, context.tenantId))
|
||||
const [existing] = await tx.select().from(table).where(scope).limit(1).for("update")
|
||||
if (!existing) throw new Error(`${entity.label} nicht gefunden`)
|
||||
if (!existing.archived) throw new Error(`${entity.label} ist nicht archiviert`)
|
||||
const [result] = await tx.update(table).set({
|
||||
archived: false,
|
||||
[columnKey(table, "updatedAt", "updated_at")!]: new Date(),
|
||||
[columnKey(table, "updatedBy", "updated_by")!]: context.userId,
|
||||
}).where(scope).returning()
|
||||
if (["products", "services"].includes(entity.resource)) {
|
||||
await recalculateServicePricesForTenant(server, context.tenantId, context.userId)
|
||||
}
|
||||
await insertHistoryItem(server, {
|
||||
tenant_id: context.tenantId, created_by: context.userId, entity: entity.resource, entityId: result.id,
|
||||
action: "restored", oldVal: existing, newVal: result,
|
||||
})
|
||||
return { entity: key, id: result.id, success: true, action: "restored", record: withoutArchivedFlag(result) }
|
||||
})
|
||||
},
|
||||
}
|
||||
|
||||
export const archiveTools: McpTool[] = [listTool, restoreTool]
|
||||
@@ -135,7 +135,7 @@ export function createDocumentTools(dependencies: Dependencies = {}): McpTool[]
|
||||
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,
|
||||
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. Mit Dateizugriff besser ohne Base64 über die Adresse aus documents.files.upload_url hochladen. 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)
|
||||
|
||||
@@ -23,6 +23,8 @@ export type McpTool = {
|
||||
title: string
|
||||
description: string
|
||||
requiredPermissions: string[]
|
||||
/** Overrides the readOnlyHint derived from requiredPermissions, e.g. for per-entity checks. */
|
||||
readOnly?: boolean
|
||||
inputSchema: Record<string, unknown>
|
||||
handler: (context: McpContext, args: Record<string, unknown>) => Promise<unknown>
|
||||
}
|
||||
|
||||
71
backend/src/modules/bank-balances.service.ts
Normal file
71
backend/src/modules/bank-balances.service.ts
Normal file
@@ -0,0 +1,71 @@
|
||||
import { FastifyInstance } from "fastify"
|
||||
import { and, eq, sql } from "drizzle-orm"
|
||||
import { bankaccounts, bankstatements } from "../../db/schema"
|
||||
|
||||
export const CASHBOOK_BANK_ID = "fedeo-cashbook"
|
||||
|
||||
type BalanceAccount = Pick<typeof bankaccounts.$inferSelect, "id" | "name" | "iban" | "ownerName" | "bankId" | "datevNumber" | "balance" | "expired" | "syncedAt">
|
||||
|
||||
const roundMoney = (value: number) => Math.round(value * 100) / 100
|
||||
|
||||
/**
|
||||
* Bank accounts store the last synced booked balance; cashbooks store their opening balance
|
||||
* and derive the current balance from their bookings. For a past date, bank balances are
|
||||
* reconstructed by reverting the statements booked after that date.
|
||||
*/
|
||||
export function calculateAccountBalance(account: BalanceAccount, statementSum: number, asOf: string | null) {
|
||||
const cashbook = account.bankId === CASHBOOK_BANK_ID
|
||||
const stored = Number(account.balance || 0)
|
||||
const balance = cashbook ? stored + statementSum : stored - statementSum
|
||||
return {
|
||||
id: account.id,
|
||||
type: cashbook ? "cashbook" : "bank",
|
||||
name: account.name || account.ownerName || (cashbook ? "Kassenbuch" : "Bankkonto"),
|
||||
iban: cashbook ? null : account.iban,
|
||||
datevNumber: account.datevNumber,
|
||||
expired: account.expired,
|
||||
balance: roundMoney(balance),
|
||||
currency: "EUR",
|
||||
...(cashbook ? { openingBalance: roundMoney(stored) } : { syncedBalance: roundMoney(stored), syncedAt: account.syncedAt }),
|
||||
source: cashbook ? "cashbook_bookings" : asOf ? "bank_sync_reconstructed" : "bank_sync",
|
||||
}
|
||||
}
|
||||
|
||||
export async function loadBankBalances(server: FastifyInstance, tenantId: number, options: { account?: number | null; asOf?: string | null } = {}) {
|
||||
const asOf = options.asOf || null
|
||||
const conditions = [eq(bankaccounts.tenant, tenantId), eq(bankaccounts.archived, false)]
|
||||
if (options.account) conditions.push(eq(bankaccounts.id, options.account))
|
||||
const accounts = await server.db.select().from(bankaccounts).where(and(...conditions)).orderBy(bankaccounts.name, bankaccounts.id)
|
||||
|
||||
const sums = async (dateCondition: any) => {
|
||||
const rows = await server.db
|
||||
.select({ account: bankstatements.account, total: sql<string>`coalesce(sum(${bankstatements.amount}), 0)` })
|
||||
.from(bankstatements)
|
||||
.where(and(eq(bankstatements.tenant, tenantId), eq(bankstatements.archived, false), ...(dateCondition ? [dateCondition] : [])))
|
||||
.groupBy(bankstatements.account)
|
||||
return new Map(rows.map((row) => [row.account, Number(row.total)]))
|
||||
}
|
||||
// Synced statements may carry a full timestamp; compare the calendar day only.
|
||||
const bookingDay = sql`left(${bankstatements.date}, 10)`
|
||||
// Cashbooks need bookings up to the date, bank accounts only those after it.
|
||||
const cashbookSums = await sums(asOf ? sql`${bookingDay} <= ${asOf}` : null)
|
||||
const bankSums = asOf ? await sums(sql`${bookingDay} > ${asOf}`) : new Map<number, number>()
|
||||
|
||||
const balances = accounts.map((account) => calculateAccountBalance(
|
||||
account,
|
||||
(account.bankId === CASHBOOK_BANK_ID ? cashbookSums : bankSums).get(account.id) || 0,
|
||||
asOf,
|
||||
))
|
||||
const active = balances.filter((account) => !account.expired)
|
||||
return {
|
||||
asOf,
|
||||
accounts: balances,
|
||||
totals: {
|
||||
balance: roundMoney(active.reduce((sum, account) => sum + account.balance, 0)),
|
||||
bank: roundMoney(active.filter((account) => account.type === "bank").reduce((sum, account) => sum + account.balance, 0)),
|
||||
cashbook: roundMoney(active.filter((account) => account.type === "cashbook").reduce((sum, account) => sum + account.balance, 0)),
|
||||
currency: "EUR",
|
||||
note: "Summen ohne abgelaufene Bankverbindungen.",
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -207,6 +207,7 @@ export class FederationService {
|
||||
if (updated) {
|
||||
await db.execute(sql`DELETE FROM collaboration_remote_messages WHERE binding_id=${updated.id}`)
|
||||
await db.execute(sql`UPDATE collaboration_outbox SET status='failed',last_error='Neue Teilnahme erforderlich' WHERE binding_id=${updated.id} AND status='pending'`)
|
||||
await this.service.options.notifications?.remoteInvitation(db, principal, updated.id, invitationId, snapshot.name)
|
||||
}
|
||||
})
|
||||
return { received: true }
|
||||
@@ -241,9 +242,11 @@ export class FederationService {
|
||||
for (const b of bindings) {
|
||||
if (b.status === "pending" && new Date(b.invitation.expiresAt).getTime() > Date.now()) result.invitations.push({ ...b.invitation, id: b.id, remote: true })
|
||||
if (b.status === "active") {
|
||||
const [unread] = await rows(this.service.db, sql`SELECT count(*)::int AS count FROM collaboration_remote_messages WHERE binding_id=${b.id} AND seq>${b.last_read_seq} AND (payload->>'own')='false'`)
|
||||
const [unread] = await rows(this.service.db, sql`SELECT count(*)::int AS count,
|
||||
(SELECT payload->>'createdAt' FROM collaboration_remote_messages WHERE binding_id=${b.id} ORDER BY seq DESC LIMIT 1) AS "lastActivityAt"
|
||||
FROM collaboration_remote_messages WHERE binding_id=${b.id} AND seq>${b.last_read_seq} AND (payload->>'own')='false'`)
|
||||
result.rooms.push({ id: b.id, name: b.snapshot?.name || b.invitation.name, topic: b.snapshot?.topic || b.invitation.topic,
|
||||
ownerName: b.invitation.ownerName, status: b.snapshot?.status || 'active', remote: true, unread: unread.count })
|
||||
ownerName: b.invitation.ownerName, status: b.snapshot?.status || 'active', remote: true, unread: unread.count, lastActivityAt: unread.lastActivityAt || null })
|
||||
}
|
||||
}
|
||||
return result
|
||||
@@ -322,6 +325,11 @@ export class FederationService {
|
||||
for (const message of projected.filter(m => m.seq >= from)) await db.execute(sql`INSERT INTO collaboration_remote_messages(binding_id,id,seq,payload)
|
||||
VALUES (${binding.id},${message.id},${message.seq},${JSON.stringify(message)}::jsonb)
|
||||
ON CONFLICT(binding_id,id) DO UPDATE SET payload=excluded.payload`)
|
||||
if (snapshot) {
|
||||
const unreadAfter = Math.max(Number(current.sync_seq), Number(current.last_read_seq), snapshot.lastReadSeq)
|
||||
const incoming = projected.filter(m => !m.own && m.seq >= from && m.seq > unreadAfter)
|
||||
await this.service.options.notifications?.remoteMessages(db, current, snapshot.name, incoming)
|
||||
}
|
||||
})
|
||||
}
|
||||
async memberRequest(ctx: UserContext, id: string, action: string, input: any = {}) {
|
||||
|
||||
139
backend/src/modules/collaboration/notifications.ts
Normal file
139
backend/src/modules/collaboration/notifications.ts
Normal file
@@ -0,0 +1,139 @@
|
||||
import type { FastifyInstance } from "fastify"
|
||||
import { and, asc, eq, inArray, notInArray, sql } from "drizzle-orm"
|
||||
import { authUsers, notificationsItems } from "../../../db/schema"
|
||||
import { NotificationService } from "../notification.service"
|
||||
import { CollaborationService, rows } from "./service"
|
||||
import type { FederationService } from "./federation"
|
||||
import type { Principal } from "./types"
|
||||
|
||||
const MESSAGE = "collaboration.message.new"
|
||||
const INVITATION = "collaboration.room.invited"
|
||||
|
||||
/** Queue inside the source transaction; external delivery never holds up a chat command. */
|
||||
export class CollaborationNotifications {
|
||||
private working = false
|
||||
private deferredUntil = new Map<string, number>()
|
||||
constructor(readonly server: FastifyInstance, readonly service: CollaborationService, readonly federation: FederationService) {}
|
||||
|
||||
delivery(db: any) {
|
||||
return new NotificationService({ db, log: this.server.log } as FastifyInstance, async (server, userId) => {
|
||||
const [user] = await server.db.select({ email: authUsers.email }).from(authUsers).where(eq(authUsers.id, userId)).limit(1)
|
||||
return user || null
|
||||
})
|
||||
}
|
||||
|
||||
async enqueue(db: any, principal: Principal, name: string, payload: Record<string, unknown>, message?: { body: string; senderName: string }) {
|
||||
if (principal.kind !== "user" || principal.disabled) return
|
||||
try { await this.service.assertPrincipal(principal, db) }
|
||||
catch (error: any) { if ([403, 404].includes(error.statusCode)) return; throw error }
|
||||
await this.delivery(db).enqueue({
|
||||
tenantId: Number(principal.tenant_id), userId: principal.user_id!,
|
||||
eventType: message ? MESSAGE : INVITATION,
|
||||
title: message ? `Neue Nachricht in ${name}` : "Einladung zur Zusammenarbeit",
|
||||
message: message ? `${message.senderName}: ${message.body || "Bild gesendet"}` : `Du wurdest in den Chat „${name}“ eingeladen.`,
|
||||
channels: ["inapp", "email", "push"],
|
||||
payload: { ...payload, principalId: principal.id,
|
||||
link: message ? `/communication/chat?room=${encodeURIComponent(`collaboration:${payload.bindingId || payload.roomId}`)}` : "/communication/chat" },
|
||||
})
|
||||
}
|
||||
|
||||
async localMessage(db: any, room: any, sender: Principal, message: any) {
|
||||
const recipients = await rows(db, sql`SELECT p.* FROM collaboration_members m JOIN collaboration_principals p ON p.id=m.principal_id
|
||||
WHERE m.room_id=${room.id} AND m.status='active' AND (m.expires_at IS NULL OR m.expires_at>now())
|
||||
AND m.history_from_seq<=${message.seq} AND m.last_read_seq<${message.seq}
|
||||
AND p.kind='user' AND NOT p.disabled AND p.id<>${sender.id}`)
|
||||
for (const principal of recipients) await this.enqueue(db, principal, room.name,
|
||||
{ roomId: room.id, messageId: message.id, seq: message.seq }, { body: message.body, senderName: sender.display_name })
|
||||
}
|
||||
|
||||
async localInvitation(db: any, room: any, target: Principal, invitationId: string) {
|
||||
await this.enqueue(db, target, room.name, { roomId: room.id, invitationId })
|
||||
}
|
||||
|
||||
async remoteInvitation(db: any, principal: Principal, bindingId: string, invitationId: string, name: string) {
|
||||
await this.enqueue(db, principal, name, { bindingId, invitationId })
|
||||
}
|
||||
|
||||
async remoteMessages(db: any, binding: any, name: string, messages: any[]) {
|
||||
if (!messages.length) return
|
||||
const [principal] = await rows(db, sql`SELECT * FROM collaboration_principals WHERE id=${binding.principal_id}`)
|
||||
if (!principal) return
|
||||
for (const message of new Map(messages.map(message => [message.id, message])).values()) await this.enqueue(db, principal, name,
|
||||
{ bindingId: binding.id, invitationId: binding.invitation_id, messageId: message.id, seq: message.seq }, message)
|
||||
}
|
||||
|
||||
async eligible(db: any, item: typeof notificationsItems.$inferSelect): Promise<boolean | "defer"> {
|
||||
const payload = item.payload as any
|
||||
const [principal] = await rows(db, sql`SELECT * FROM collaboration_principals WHERE id=${payload.principalId}`)
|
||||
if (!principal || principal.kind !== "user" || principal.user_id !== item.userId || Number(principal.tenant_id) !== item.tenantId) return false
|
||||
try {
|
||||
await this.service.assertPrincipal(principal, db)
|
||||
if (payload.bindingId) {
|
||||
if (!this.federation.options.enabled) return "defer"
|
||||
const ctx = { principal, userId: item.userId, tenantId: item.tenantId, manage: false }
|
||||
const binding = await this.federation.binding(ctx, payload.bindingId)
|
||||
if (!binding || binding.invitation_id !== payload.invitationId) return false
|
||||
await this.federation.allowed(item.tenantId, binding.origin, db)
|
||||
if (item.eventType === INVITATION) return binding.status === "pending" && new Date(binding.invitation.expiresAt).getTime() > Date.now()
|
||||
if (binding.status !== "active") return false
|
||||
// Do not send cached content while current access cannot be confirmed by its owner.
|
||||
const detail = await this.federation.sync(ctx, binding)
|
||||
if (detail.offline) return "defer"
|
||||
const current = await this.federation.binding(ctx, binding.id)
|
||||
return current?.status === "active" && current.invitation_id === payload.invitationId
|
||||
&& payload.seq >= detail.historyFromSeq && (item.channel === "inapp" || payload.seq > Number(current.last_read_seq))
|
||||
}
|
||||
const room = await this.service.roomRow(db, payload.roomId)
|
||||
if (item.eventType === INVITATION) {
|
||||
this.service.assertOpen(room, true)
|
||||
const [invite] = await rows(db, sql`SELECT id FROM collaboration_invitations
|
||||
WHERE id=${payload.invitationId} AND room_id=${room.id} AND target_principal_id=${principal.id}
|
||||
AND status='pending' AND expires_at>now() AND (access_expires_at IS NULL OR access_expires_at>now())`)
|
||||
return Boolean(invite)
|
||||
}
|
||||
const member = await this.service.membership(db, room, principal)
|
||||
return payload.seq >= Number(member.history_from_seq) && (item.channel === "inapp" || payload.seq > Number(member.last_read_seq))
|
||||
} catch (error: any) {
|
||||
if ([401, 403, 404, 409, 410].includes(error.statusCode)) return false
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
async tick() {
|
||||
if (this.working) return
|
||||
this.working = true
|
||||
try {
|
||||
for (const [id, until] of this.deferredUntil) if (until <= Date.now()) this.deferredUntil.delete(id)
|
||||
const pending = await this.server.db.select({ id: notificationsItems.id }).from(notificationsItems)
|
||||
.where(and(eq(notificationsItems.status, "queued"), inArray(notificationsItems.eventType, [MESSAGE, INVITATION]),
|
||||
this.deferredUntil.size ? notInArray(notificationsItems.id, [...this.deferredUntil.keys()]) : undefined))
|
||||
.orderBy(asc(notificationsItems.createdAt)).limit(20)
|
||||
for (const { id } of pending) {
|
||||
try {
|
||||
await this.server.db.transaction(async db => {
|
||||
const [item] = await db.select().from(notificationsItems)
|
||||
.where(and(eq(notificationsItems.id, id), eq(notificationsItems.status, "queued")))
|
||||
.for("update", { skipLocked: true })
|
||||
if (!item) return
|
||||
const eligible = await this.eligible(db, item)
|
||||
if (eligible === "defer") {
|
||||
this.deferredUntil.set(id, Date.now() + 30000)
|
||||
return
|
||||
}
|
||||
const delivery = this.delivery(db)
|
||||
const enabled = item.channel === "inapp" || (await delivery.preferences(item.tenantId, item.userId)).events
|
||||
.some(event => event.eventKey === item.eventType && event.channels[item.channel] === true)
|
||||
if (!eligible || !enabled) {
|
||||
await db.delete(notificationsItems).where(eq(notificationsItems.id, item.id))
|
||||
return
|
||||
}
|
||||
await delivery.deliver(item)
|
||||
})
|
||||
} catch (error) {
|
||||
this.deferredUntil.set(id, Date.now() + 30000)
|
||||
this.server.log.error({ err: error, notificationId: id }, "Collaboration notification failed")
|
||||
}
|
||||
}
|
||||
} finally { this.working = false }
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import { CollaborationService } from "./service"
|
||||
import { FederationService } from "./federation"
|
||||
import { encrypt, decrypt } from "../../utils/crypt"
|
||||
import { collaborationConfig } from "./config"
|
||||
import { CollaborationNotifications } from "./notifications"
|
||||
|
||||
export function collaborationRuntime(server: FastifyInstance) {
|
||||
const { apiUrl, publicUrl, enabled, disabledReason } = collaborationConfig({
|
||||
@@ -16,12 +17,17 @@ export function collaborationRuntime(server: FastifyInstance) {
|
||||
sendMail,
|
||||
})
|
||||
const federation = new FederationService(service, { apiUrl, enabled, disabledReason, seal: encrypt, unseal: decrypt })
|
||||
const notifications = new CollaborationNotifications(server, service, federation)
|
||||
service.options.notifications = notifications
|
||||
service.options.changed = (roomId, db) => federation.changed(roomId, db)
|
||||
service.options.invited = (ctx, roomId, target, invitationId, db) => federation.invite(ctx, roomId, target, invitationId, db)
|
||||
let timer: ReturnType<typeof setInterval>
|
||||
server.addHook("onReady", async () => {
|
||||
if (federation.options.enabled) await federation.keys()
|
||||
timer = setInterval(() => federation.tick().catch(error => server.log.error({ err: error }, "Collaboration worker failed")), 5000)
|
||||
timer = setInterval(() => {
|
||||
void federation.tick().catch(error => server.log.error({ err: error }, "Collaboration worker failed"))
|
||||
void notifications.tick().catch(error => server.log.error({ err: error }, "Collaboration notification worker failed"))
|
||||
}, 5000)
|
||||
timer.unref()
|
||||
})
|
||||
server.addHook("onClose", async () => { clearInterval(timer) })
|
||||
|
||||
@@ -4,6 +4,7 @@ import type { NodePgDatabase } from "drizzle-orm/node-postgres"
|
||||
import { email, fail, futureDate, hash, overview, Principal, sequence, text, UserContext, uuid } from "./types"
|
||||
|
||||
import { chatContent, chatImage, chatReactions, imageMetadata, setChatReaction } from "../chat-content"
|
||||
import type { CollaborationNotifications } from "./notifications"
|
||||
|
||||
type Db = Pick<NodePgDatabase<any>, "execute" | "transaction">
|
||||
export const rows = async (db: Pick<Db, "execute">, query: any): Promise<any[]> => (await db.execute(query)).rows
|
||||
@@ -13,6 +14,7 @@ export type CollaborationOptions = {
|
||||
sendMail: (to: string, subject: string, html: string) => Promise<{ success: boolean }>;
|
||||
changed?: (roomId: string, db: any) => Promise<void>;
|
||||
invited?: (ctx: UserContext, roomId: string, target: Principal, invitationId: string, db: any) => Promise<void>;
|
||||
notifications?: CollaborationNotifications;
|
||||
}
|
||||
|
||||
/** Owner-side authority. All membership changes and sends serialize on the room row. */
|
||||
@@ -142,6 +144,8 @@ export class CollaborationService {
|
||||
t.name AS "ownerName", m.overview_allowed AS "overviewAllowed",
|
||||
(SELECT count(*)::int FROM collaboration_messages cm WHERE cm.room_id=r.id
|
||||
AND cm.seq>=m.history_from_seq AND cm.seq>m.last_read_seq AND cm.principal_id<>${principal.id}) AS unread
|
||||
,coalesce((SELECT max(cm.created_at) FROM collaboration_messages cm WHERE cm.room_id=r.id
|
||||
AND cm.seq>=m.history_from_seq), r.created_at) AS "lastActivityAt"
|
||||
FROM collaboration_members m JOIN collaboration_rooms r ON r.id=m.room_id JOIN tenants t ON t.id=r.tenant_id
|
||||
LEFT JOIN projects p ON p.id=r.project_id
|
||||
WHERE m.principal_id=${principal.id} AND m.status='active' AND (m.expires_at IS NULL OR m.expires_at>now())
|
||||
@@ -201,6 +205,7 @@ export class CollaborationService {
|
||||
const [message] = await rows(db, sql`INSERT INTO collaboration_messages(room_id,seq,principal_id,client_id,body,image)
|
||||
VALUES (${room.id},${next.sequence},${principal.id},${clientId},${body},${image ? JSON.stringify(image) : null}::jsonb) RETURNING id,client_id AS "clientId",seq::float8 AS seq,body,created_at AS "createdAt"`)
|
||||
await this.options.changed?.(room.id, db)
|
||||
await this.options.notifications?.localMessage(db, room, principal, message)
|
||||
return { ...message, image: imageMetadata(image), own: true, senderName: principal.display_name, senderKind: principal.kind }
|
||||
})
|
||||
}
|
||||
@@ -302,6 +307,7 @@ export class CollaborationService {
|
||||
if (!this.options.invited) fail("Föderation ist nicht konfiguriert", 503)
|
||||
await this.options.invited(ctx, room.id, target, invite.id, db)
|
||||
}
|
||||
await this.options.notifications?.localInvitation(db, room, target, invite.id)
|
||||
return invite
|
||||
})
|
||||
return { ...result, token }
|
||||
|
||||
@@ -17,7 +17,7 @@ import {
|
||||
incominginvoices,
|
||||
} from "../../../db/schema"
|
||||
|
||||
import { eq, and, isNull, not } from "drizzle-orm"
|
||||
import { eq, and, inArray, isNull, not } from "drizzle-orm"
|
||||
|
||||
const formatInvoiceItemDescription = (item: any) => {
|
||||
const parts = [
|
||||
@@ -86,8 +86,25 @@ const mapGptDataToIncomingInvoice = (data: any, tenantId: number) => {
|
||||
return itemInfo
|
||||
}
|
||||
|
||||
export type IncomingInvoicePreparationResult = {
|
||||
filesFound: number
|
||||
created: Array<{ fileId: string, invoiceId: number, source: string | null }>
|
||||
skipped: Array<{ fileId: string, reason: string }>
|
||||
error?: string
|
||||
}
|
||||
|
||||
export type IncomingInvoicePreparationStatus = {
|
||||
running: boolean
|
||||
startedAt: string | null
|
||||
finishedAt: string | null
|
||||
result: IncomingInvoicePreparationResult | null
|
||||
}
|
||||
|
||||
class FileAlreadyPreparedError extends Error {}
|
||||
|
||||
export function prepareIncomingInvoices(server: FastifyInstance) {
|
||||
const processInvoices = async (tenantId:number) => {
|
||||
const processInvoices = async (tenantId:number, fileIds?: string[]) => {
|
||||
const result: IncomingInvoicePreparationResult = { filesFound: 0, created: [], skipped: [] }
|
||||
console.log("▶ Starting Incoming Invoice Preparation")
|
||||
|
||||
const tenantsRes = await server.db
|
||||
@@ -98,7 +115,7 @@ export function prepareIncomingInvoices(server: FastifyInstance) {
|
||||
|
||||
if (!tenantsRes.length) {
|
||||
console.log("No tenants with autoPrepareIncomingInvoices = true")
|
||||
return
|
||||
return { ...result, error: "Mandant nicht gefunden" }
|
||||
}
|
||||
|
||||
console.log(`Processing tenants: ${tenantsRes.map(t => t.id).join(", ")}`)
|
||||
@@ -124,6 +141,7 @@ export function prepareIncomingInvoices(server: FastifyInstance) {
|
||||
const invoiceFileTag = tagRes?.[0]?.id
|
||||
if (!invoiceFileTag) {
|
||||
server.log.error(`❌ Missing filetag 'invoices' for tenant ${tenantId}`)
|
||||
result.error = "Dateityp für Eingangsrechnungen fehlt"
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -137,10 +155,13 @@ export function prepareIncomingInvoices(server: FastifyInstance) {
|
||||
eq(files.type, invoiceFileTag),
|
||||
isNull(files.incominginvoice),
|
||||
eq(files.archived, false),
|
||||
not(isNull(files.path))
|
||||
not(isNull(files.path)),
|
||||
...(fileIds ? [inArray(files.id, fileIds)] : [])
|
||||
)
|
||||
)
|
||||
|
||||
result.filesFound += filesRes.length
|
||||
|
||||
if (!filesRes.length) {
|
||||
console.log(`No invoice files for tenant ${tenantId}`)
|
||||
continue
|
||||
@@ -150,95 +171,152 @@ export function prepareIncomingInvoices(server: FastifyInstance) {
|
||||
// 3️⃣ Strukturierte E-Rechnung bevorzugen, GPT als PDF-Fallback verwenden
|
||||
// -------------------------------------------------------------
|
||||
for (const file of filesRes) {
|
||||
console.log(`Processing file ${file.id} for tenant ${tenantId}`)
|
||||
|
||||
let fileData: Buffer
|
||||
|
||||
try {
|
||||
fileData = await loadFileBuffer(file.path!)
|
||||
await processFile(tenantId, file, result)
|
||||
} catch (error) {
|
||||
server.log.error(error, `Datei ${file.id} konnte nicht aus S3 geladen werden.`)
|
||||
continue
|
||||
}
|
||||
|
||||
const electronicInvoice = await detectElectronicInvoice(fileData, file)
|
||||
|
||||
let itemInfo: any = null
|
||||
|
||||
if (electronicInvoice) {
|
||||
server.log.info({
|
||||
fileId: file.id,
|
||||
container: electronicInvoice.container,
|
||||
syntax: electronicInvoice.syntax,
|
||||
attachmentName: electronicInvoice.attachmentName,
|
||||
}, "Strukturierte E-Rechnung erkannt.")
|
||||
|
||||
try {
|
||||
const parsedInvoice = parseElectronicInvoice(electronicInvoice.xml, electronicInvoice.syntax)
|
||||
const vendor = await findElectronicInvoiceVendor(server, tenantId, parsedInvoice)
|
||||
itemInfo = mapElectronicInvoiceToIncomingInvoice(
|
||||
parsedInvoice,
|
||||
tenantId,
|
||||
vendor?.id || null,
|
||||
electronicInvoice.container,
|
||||
electronicInvoice.attachmentName,
|
||||
)
|
||||
} catch (error) {
|
||||
server.log.error(error, `E-Rechnung aus Datei ${file.id} konnte nicht verarbeitet werden.`)
|
||||
|
||||
if (electronicInvoice.container === "xml") continue
|
||||
}
|
||||
}
|
||||
|
||||
if (!itemInfo) {
|
||||
const data = await getInvoiceDataFromGPT(server, file, tenantId, fileData)
|
||||
|
||||
if (!data) {
|
||||
server.log.warn(`GPT returned no data for file ${file.id}`)
|
||||
if (error instanceof FileAlreadyPreparedError) {
|
||||
result.skipped.push({ fileId: file.id, reason: "Datei wurde bereits vorbereitet" })
|
||||
continue
|
||||
}
|
||||
|
||||
itemInfo = mapGptDataToIncomingInvoice(data, tenantId)
|
||||
server.log.error(error, `Datei ${file.id} konnte nicht vorbereitet werden.`)
|
||||
result.skipped.push({ fileId: file.id, reason: "Eingangsbeleg konnte nicht angelegt werden" })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------
|
||||
// 4️⃣ IncomingInvoice erstellen
|
||||
// ---------------------------------------------------------
|
||||
const inserted = await server.db
|
||||
.insert(incominginvoices)
|
||||
.values(itemInfo)
|
||||
.returning()
|
||||
return result
|
||||
}
|
||||
|
||||
const newInvoice = inserted?.[0]
|
||||
const processFile = async (tenantId: number, file: typeof files.$inferSelect, result: IncomingInvoicePreparationResult) => {
|
||||
console.log(`Processing file ${file.id} for tenant ${tenantId}`)
|
||||
|
||||
if (!newInvoice) {
|
||||
server.log.error(`Failed to insert incoming invoice for file ${file.id}`)
|
||||
continue
|
||||
let fileData: Buffer
|
||||
|
||||
try {
|
||||
fileData = await loadFileBuffer(file.path!)
|
||||
} catch (error) {
|
||||
server.log.error(error, `Datei ${file.id} konnte nicht aus S3 geladen werden.`)
|
||||
result.skipped.push({ fileId: file.id, reason: "Datei konnte nicht geladen werden" })
|
||||
return
|
||||
}
|
||||
|
||||
const electronicInvoice = await detectElectronicInvoice(fileData, file)
|
||||
|
||||
let itemInfo: any = null
|
||||
|
||||
if (electronicInvoice) {
|
||||
server.log.info({
|
||||
fileId: file.id,
|
||||
container: electronicInvoice.container,
|
||||
syntax: electronicInvoice.syntax,
|
||||
attachmentName: electronicInvoice.attachmentName,
|
||||
}, "Strukturierte E-Rechnung erkannt.")
|
||||
|
||||
try {
|
||||
const parsedInvoice = parseElectronicInvoice(electronicInvoice.xml, electronicInvoice.syntax)
|
||||
const vendor = await findElectronicInvoiceVendor(server, tenantId, parsedInvoice)
|
||||
itemInfo = mapElectronicInvoiceToIncomingInvoice(
|
||||
parsedInvoice,
|
||||
tenantId,
|
||||
vendor?.id || null,
|
||||
electronicInvoice.container,
|
||||
electronicInvoice.attachmentName,
|
||||
)
|
||||
} catch (error) {
|
||||
server.log.error(error, `E-Rechnung aus Datei ${file.id} konnte nicht verarbeitet werden.`)
|
||||
|
||||
if (electronicInvoice.container === "xml") {
|
||||
result.skipped.push({ fileId: file.id, reason: "E-Rechnung konnte nicht verarbeitet werden" })
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------
|
||||
// 5️⃣ Datei mit incominginvoice-ID verbinden
|
||||
// ---------------------------------------------------------
|
||||
await server.db
|
||||
.update(files)
|
||||
.set({ incominginvoice: newInvoice.id })
|
||||
.where(eq(files.id, file.id))
|
||||
if (!itemInfo) {
|
||||
const data = await getInvoiceDataFromGPT(server, file, tenantId, fileData)
|
||||
|
||||
console.log(`IncomingInvoice ${newInvoice.id} created for file ${file.id}`)
|
||||
if (!data) {
|
||||
server.log.warn(`GPT returned no data for file ${file.id}`)
|
||||
result.skipped.push({ fileId: file.id, reason: "Keine Belegdaten erkannt" })
|
||||
return
|
||||
}
|
||||
|
||||
itemInfo = mapGptDataToIncomingInvoice(data, tenantId)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------
|
||||
// 4️⃣ IncomingInvoice anlegen und Datei atomar verknüpfen.
|
||||
// Die Verknüpfung greift nur, solange die Datei noch frei ist;
|
||||
// sonst wird der Beleg verworfen, damit keine Dubletten entstehen.
|
||||
// ---------------------------------------------------------
|
||||
const newInvoice = await server.db.transaction(async (tx) => {
|
||||
const [invoice] = await tx
|
||||
.insert(incominginvoices)
|
||||
.values(itemInfo)
|
||||
.returning()
|
||||
|
||||
return
|
||||
if (!invoice) throw new Error("Eingangsbeleg konnte nicht angelegt werden")
|
||||
|
||||
const linked = await tx
|
||||
.update(files)
|
||||
.set({ incominginvoice: invoice.id })
|
||||
.where(and(eq(files.id, file.id), isNull(files.incominginvoice)))
|
||||
.returning({ id: files.id })
|
||||
|
||||
if (!linked.length) throw new FileAlreadyPreparedError()
|
||||
|
||||
return invoice
|
||||
})
|
||||
|
||||
result.created.push({ fileId: file.id, invoiceId: newInvoice.id, source: newInvoice.preparationSource ?? null })
|
||||
console.log(`IncomingInvoice ${newInvoice.id} created for file ${file.id}`)
|
||||
}
|
||||
|
||||
return {
|
||||
run: async (tenant:number) => {
|
||||
await processInvoices(tenant)
|
||||
// Serialize runs per tenant so concurrent triggers cannot prepare the same file twice.
|
||||
const running = new Map<number, Promise<unknown>>()
|
||||
const backgroundRuns = new Map<number, IncomingInvoicePreparationStatus>()
|
||||
|
||||
const run = async (tenant:number, options: { fileIds?: string[] } = {}) => {
|
||||
const previous = running.get(tenant) || Promise.resolve()
|
||||
const current = previous.catch(() => undefined).then(() => processInvoices(tenant, options.fileIds))
|
||||
running.set(tenant, current)
|
||||
try {
|
||||
const result = await current
|
||||
console.log("Incoming Invoice Preparation Completed.")
|
||||
|
||||
return result
|
||||
} finally {
|
||||
if (running.get(tenant) === current) running.delete(tenant)
|
||||
}
|
||||
}
|
||||
|
||||
const status = (tenant: number): IncomingInvoicePreparationStatus =>
|
||||
backgroundRuns.get(tenant) || { running: false, startedAt: null, finishedAt: null, result: null }
|
||||
|
||||
// Startet die Vorbereitung losgelöst von der Anfrage; ein laufender Vorgang wird nicht erneut gestartet.
|
||||
const start = (tenant: number): IncomingInvoicePreparationStatus => {
|
||||
const current = status(tenant)
|
||||
if (current.running) return current
|
||||
|
||||
const next: IncomingInvoicePreparationStatus = { running: true, startedAt: new Date().toISOString(), finishedAt: null, result: null }
|
||||
backgroundRuns.set(tenant, next)
|
||||
|
||||
run(tenant)
|
||||
.then((result) => {
|
||||
backgroundRuns.set(tenant, { ...next, running: false, finishedAt: new Date().toISOString(), result })
|
||||
})
|
||||
.catch((error) => {
|
||||
server.log.error(error, `Belegvorbereitung für Mandant ${tenant} fehlgeschlagen.`)
|
||||
backgroundRuns.set(tenant, {
|
||||
...next,
|
||||
running: false,
|
||||
finishedAt: new Date().toISOString(),
|
||||
result: { filesFound: 0, created: [], skipped: [], error: "Belegvorbereitung fehlgeschlagen" },
|
||||
})
|
||||
})
|
||||
|
||||
return next
|
||||
}
|
||||
|
||||
return { run, start, status }
|
||||
|
||||
}
|
||||
|
||||
126
backend/src/modules/incoming-invoice-cost-centres.service.ts
Normal file
126
backend/src/modules/incoming-invoice-cost-centres.service.ts
Normal file
@@ -0,0 +1,126 @@
|
||||
import { and, eq, inArray } from "drizzle-orm"
|
||||
import { FastifyInstance } from "fastify"
|
||||
import { costcentres, incominginvoices } from "../../db/schema"
|
||||
import { insertHistoryItem } from "../utils/history"
|
||||
|
||||
export type AccountCostCentreAssignment = {
|
||||
index: number
|
||||
costcentre: string | null
|
||||
}
|
||||
|
||||
export type IncomingInvoiceCostCentreUpdate = {
|
||||
accountCostCentres?: AccountCostCentreAssignment[]
|
||||
}
|
||||
|
||||
const serviceError = (message: string, statusCode = 400) =>
|
||||
Object.assign(new Error(message), { statusCode })
|
||||
const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
|
||||
|
||||
export function normalizeAccountCostCentreAssignments(input: unknown): AccountCostCentreAssignment[] {
|
||||
if (!Array.isArray(input)) throw serviceError("accountCostCentres muss ein Array sein")
|
||||
if (!input.length) throw serviceError("Mindestens eine Positionskostenstelle ist erforderlich")
|
||||
|
||||
const seen = new Set<number>()
|
||||
return input.map((assignment) => {
|
||||
const index = assignment?.index
|
||||
const costcentre = assignment?.costcentre
|
||||
if (!Number.isInteger(index) || index < 0) throw serviceError("Jede Positionszuordnung benötigt einen gültigen index")
|
||||
if (seen.has(index)) throw serviceError(`Position ${index + 1} ist mehrfach angegeben`)
|
||||
seen.add(index)
|
||||
if (costcentre !== null && (typeof costcentre !== "string" || !UUID_PATTERN.test(costcentre))) {
|
||||
throw serviceError(`Ungültige Kostenstelle für Position ${index + 1}`)
|
||||
}
|
||||
return { index, costcentre }
|
||||
})
|
||||
}
|
||||
|
||||
export function applyAccountCostCentreAssignments(
|
||||
accounts: unknown,
|
||||
assignments: AccountCostCentreAssignment[] = [],
|
||||
) {
|
||||
if (!Array.isArray(accounts)) throw serviceError("Der Eingangsbeleg enthält keine Positionen")
|
||||
|
||||
for (const { index } of assignments) {
|
||||
const account = accounts[index]
|
||||
if (!account || typeof account !== "object" || Array.isArray(account)) {
|
||||
throw serviceError(`Position ${index + 1} wurde im Eingangsbeleg nicht gefunden`)
|
||||
}
|
||||
}
|
||||
|
||||
const assignmentMap = new Map(assignments.map((assignment) => [assignment.index, assignment.costcentre]))
|
||||
return accounts.map((account, index) => {
|
||||
if (!assignmentMap.has(index)) return account
|
||||
const { costcentre: _legacyCostCentre, ...rest } = account as Record<string, unknown>
|
||||
return { ...rest, costCentre: assignmentMap.get(index) ?? null }
|
||||
})
|
||||
}
|
||||
|
||||
export async function updateIncomingInvoiceCostCentres(
|
||||
server: FastifyInstance,
|
||||
tenantId: number,
|
||||
userId: string,
|
||||
invoiceId: number,
|
||||
input: IncomingInvoiceCostCentreUpdate,
|
||||
) {
|
||||
const assignments = normalizeAccountCostCentreAssignments(input?.accountCostCentres)
|
||||
|
||||
const [existing] = await server.db
|
||||
.select()
|
||||
.from(incominginvoices)
|
||||
.where(and(
|
||||
eq(incominginvoices.id, invoiceId),
|
||||
eq(incominginvoices.tenant, tenantId),
|
||||
eq(incominginvoices.archived, false),
|
||||
))
|
||||
.limit(1)
|
||||
|
||||
if (!existing) throw serviceError("Eingangsbeleg nicht gefunden", 404)
|
||||
|
||||
const referencedCostCentreIds = [...new Set(
|
||||
assignments.map((assignment) => assignment.costcentre).filter((id): id is string => Boolean(id)),
|
||||
)]
|
||||
|
||||
if (referencedCostCentreIds.length) {
|
||||
const validCostCentres = await server.db
|
||||
.select({ id: costcentres.id })
|
||||
.from(costcentres)
|
||||
.where(and(
|
||||
eq(costcentres.tenant, tenantId),
|
||||
eq(costcentres.archived, false),
|
||||
inArray(costcentres.id, referencedCostCentreIds),
|
||||
))
|
||||
|
||||
if (validCostCentres.length !== referencedCostCentreIds.length) {
|
||||
throw serviceError("Mindestens eine Kostenstelle wurde nicht gefunden oder ist archiviert")
|
||||
}
|
||||
}
|
||||
|
||||
const [updated] = await server.db
|
||||
.update(incominginvoices)
|
||||
.set({
|
||||
accounts: applyAccountCostCentreAssignments(existing.accounts, assignments),
|
||||
updatedAt: new Date(),
|
||||
updatedBy: userId,
|
||||
})
|
||||
.where(and(
|
||||
eq(incominginvoices.id, invoiceId),
|
||||
eq(incominginvoices.tenant, tenantId),
|
||||
eq(incominginvoices.archived, false),
|
||||
))
|
||||
.returning()
|
||||
|
||||
if (!updated) throw serviceError("Eingangsbeleg nicht gefunden", 404)
|
||||
|
||||
await insertHistoryItem(server, {
|
||||
tenant_id: tenantId,
|
||||
created_by: userId,
|
||||
entity: "incominginvoices",
|
||||
entityId: invoiceId,
|
||||
action: "updated",
|
||||
oldVal: existing,
|
||||
newVal: updated,
|
||||
text: "Kostenstellen des Eingangsbelegs geändert",
|
||||
})
|
||||
|
||||
return updated
|
||||
}
|
||||
@@ -56,6 +56,24 @@ export class NotificationService {
|
||||
) {}
|
||||
|
||||
async trigger(input: TriggerInput) {
|
||||
const { items, skipped } = await this.createItems(input)
|
||||
if (skipped !== undefined) return { success: true, created: 0, delivered: 0, skipped }
|
||||
const results = []
|
||||
for (const item of items) results.push(await this.deliver(item))
|
||||
return {
|
||||
success: results.every((result) => result.success),
|
||||
created: results.length,
|
||||
delivered: results.filter((result) => result.success).length,
|
||||
failed: results.filter((result) => !result.success).length,
|
||||
}
|
||||
}
|
||||
|
||||
/** Persist first; callers using a transaction can deliver after it commits. */
|
||||
async enqueue(input: TriggerInput) {
|
||||
return (await this.createItems(input)).items
|
||||
}
|
||||
|
||||
private async createItems(input: TriggerInput): Promise<{ items: (typeof notificationsItems.$inferSelect)[]; skipped?: number }> {
|
||||
const tenantId = input.tenantId
|
||||
const userIds = Array.from(new Set([...(input.userIds || []), input.userId].filter(Boolean))) as string[]
|
||||
|
||||
@@ -68,7 +86,7 @@ export class NotificationService {
|
||||
const channels = requestedChannels.filter((channel) => allowedChannels.includes(channel))
|
||||
|
||||
if (!channels.length) {
|
||||
return { success: true, created: 0, delivered: 0, skipped: userIds.length }
|
||||
return { items: [], skipped: userIds.length }
|
||||
}
|
||||
|
||||
const results = []
|
||||
@@ -99,16 +117,11 @@ export class NotificationService {
|
||||
const item = itemRows[0]
|
||||
if (!item) continue
|
||||
|
||||
results.push(await this.deliver(item))
|
||||
results.push(item)
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
success: results.every((result) => result.success),
|
||||
created: results.length,
|
||||
delivered: results.filter((result) => result.success).length,
|
||||
failed: results.filter((result) => !result.success).length,
|
||||
}
|
||||
return { items: results }
|
||||
}
|
||||
|
||||
async preferences(tenantId: number, userId: string) {
|
||||
@@ -295,11 +308,12 @@ export class NotificationService {
|
||||
const defaultPref = defaults.find((pref) => pref.channel === channel)
|
||||
if (defaultPref) return defaultPref.enabled
|
||||
|
||||
if (input.eventType === "collaboration.message.new") return channel === "inapp"
|
||||
return channel !== "email" && input.eventType !== "communication.message.room" && input.eventType !== "communication.room.invited"
|
||||
})
|
||||
}
|
||||
|
||||
private async deliver(item: typeof notificationsItems.$inferSelect) {
|
||||
async deliver(item: typeof notificationsItems.$inferSelect) {
|
||||
if (item.channel === "inapp") {
|
||||
await this.markSent(item.id)
|
||||
return { success: true, id: item.id, channel: item.channel }
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { FastifyInstance } from "fastify";
|
||||
import fp from "fastify-plugin";
|
||||
import { secrets } from "../utils/secrets";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { and, eq, isNull } from "drizzle-orm";
|
||||
import { authUsers, m2mApiKeys } from "../../db/schema";
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
@@ -44,7 +44,8 @@ export default fp(async (server: FastifyInstance, opts: { allowedPrefix?: string
|
||||
.innerJoin(authUsers, eq(authUsers.id, m2mApiKeys.userId))
|
||||
.where(and(
|
||||
eq(m2mApiKeys.keyHash, keyHash),
|
||||
eq(m2mApiKeys.active, true)
|
||||
eq(m2mApiKeys.active, true),
|
||||
isNull(authUsers.archived_at)
|
||||
))
|
||||
.limit(1)
|
||||
|
||||
@@ -70,7 +71,7 @@ export default fp(async (server: FastifyInstance, opts: { allowedPrefix?: string
|
||||
const users = await server.db
|
||||
.select({ email: authUsers.email })
|
||||
.from(authUsers)
|
||||
.where(eq(authUsers.id, userId))
|
||||
.where(and(eq(authUsers.id, userId), isNull(authUsers.archived_at)))
|
||||
.limit(1)
|
||||
|
||||
if (!users[0]) {
|
||||
|
||||
@@ -12,7 +12,7 @@ import {
|
||||
tenants,
|
||||
} from "../../db/schema"
|
||||
|
||||
import { eq, and, inArray } from "drizzle-orm"
|
||||
import { eq, and, inArray, isNull } from "drizzle-orm"
|
||||
|
||||
export default fp(async (server: FastifyInstance) => {
|
||||
const hashApiKey = (apiKey: string) =>
|
||||
@@ -56,7 +56,8 @@ export default fp(async (server: FastifyInstance) => {
|
||||
.innerJoin(authUsers, eq(authUsers.id, m2mApiKeys.userId))
|
||||
.where(and(
|
||||
eq(m2mApiKeys.keyHash, keyHash),
|
||||
eq(m2mApiKeys.active, true)
|
||||
eq(m2mApiKeys.active, true),
|
||||
isNull(authUsers.archived_at)
|
||||
))
|
||||
.limit(1)
|
||||
|
||||
@@ -141,22 +142,16 @@ export default fp(async (server: FastifyInstance) => {
|
||||
return reply.code(401).send({ error: "Invalid token" })
|
||||
}
|
||||
|
||||
// Payload an Request hängen
|
||||
req.user = payload
|
||||
|
||||
if (typeof payload.is_admin === "boolean") {
|
||||
req.user.is_admin = payload.is_admin
|
||||
} else {
|
||||
const [currentUser] = await server.db
|
||||
.select({
|
||||
is_admin: authUsers.is_admin,
|
||||
})
|
||||
.from(authUsers)
|
||||
.where(eq(authUsers.id, payload.user_id))
|
||||
.limit(1)
|
||||
|
||||
req.user.is_admin = Boolean(currentUser?.is_admin)
|
||||
// Check current account state even when a JWT carries cached admin claims.
|
||||
const [currentUser] = await server.db
|
||||
.select({ is_admin: authUsers.is_admin })
|
||||
.from(authUsers)
|
||||
.where(and(eq(authUsers.id, payload.user_id), isNull(authUsers.archived_at)))
|
||||
.limit(1)
|
||||
if (!currentUser) {
|
||||
return reply.code(401).send({ error: "Invalid or expired token" })
|
||||
}
|
||||
req.user = { ...payload, is_admin: Boolean(currentUser.is_admin) }
|
||||
|
||||
// Multi-Tenant Modus ohne ausgewählten Tenant → keine Rollenprüfung
|
||||
if (!req.user.tenant_id) {
|
||||
|
||||
@@ -33,9 +33,12 @@ import { requireSystemAdmin } from "../utils/requireSystemAdmin";
|
||||
import { buildSystemStatus } from "../modules/system-status.service";
|
||||
import { s3 } from "../utils/s3";
|
||||
import { secrets } from "../utils/secrets";
|
||||
import adminUserArchiveRoutes from "./adminUserArchive";
|
||||
import { getPortalLoginUrl } from "../utils/portalUrl";
|
||||
|
||||
export default async function adminRoutes(server: FastifyInstance) {
|
||||
await adminUserArchiveRoutes(server);
|
||||
|
||||
await server.register(multipart, {
|
||||
limits: { fileSize: 1024 * 1024 * 1024 }
|
||||
});
|
||||
@@ -602,6 +605,7 @@ export default async function adminRoutes(server: FastifyInstance) {
|
||||
const currentUser = await requireAdmin(req, reply);
|
||||
if (!currentUser) return;
|
||||
|
||||
const includeArchived = (req.query as { includeArchived?: string }).includeArchived === "true";
|
||||
const [tenantRows, userRows, profileRows, membershipRows, roleRows, roleAssignmentRows] = await Promise.all([
|
||||
server.db
|
||||
.select({
|
||||
@@ -621,8 +625,9 @@ export default async function adminRoutes(server: FastifyInstance) {
|
||||
multiTenant: authUsers.multiTenant,
|
||||
must_change_password: authUsers.must_change_password,
|
||||
is_admin: authUsers.is_admin,
|
||||
archived_at: authUsers.archived_at,
|
||||
})
|
||||
.from(authUsers),
|
||||
.from(authUsers).where(includeArchived ? undefined : isNull(authUsers.archived_at)),
|
||||
server.db
|
||||
.select({
|
||||
id: authProfiles.id,
|
||||
@@ -633,6 +638,7 @@ export default async function adminRoutes(server: FastifyInstance) {
|
||||
full_name: authProfiles.full_name,
|
||||
email: authProfiles.email,
|
||||
active: authProfiles.active,
|
||||
archived_at: authProfiles.archived_at,
|
||||
})
|
||||
.from(authProfiles),
|
||||
server.db
|
||||
@@ -681,16 +687,17 @@ export default async function adminRoutes(server: FastifyInstance) {
|
||||
};
|
||||
});
|
||||
|
||||
const activeUserIds = new Set(userRows.filter((user) => !user.archived_at).map((user) => user.id));
|
||||
const tenantsWithCounts = tenantRows.map((tenant) => ({
|
||||
...tenant,
|
||||
user_count: uniqueMembershipRows.filter((membership) => membership.tenant_id === tenant.id).length,
|
||||
user_count: uniqueMembershipRows.filter((membership) => membership.tenant_id === tenant.id && activeUserIds.has(membership.user_id)).length,
|
||||
}));
|
||||
|
||||
return {
|
||||
users,
|
||||
tenants: tenantsWithCounts,
|
||||
roles: roleRows,
|
||||
unassignedProfiles: profileRows.filter((profile) => !profile.user_id),
|
||||
unassignedProfiles: profileRows.filter((profile) => !profile.user_id && !profile.archived_at && profile.active),
|
||||
memberships: uniqueMembershipRows,
|
||||
roleAssignments: roleAssignmentRows,
|
||||
};
|
||||
@@ -809,7 +816,7 @@ export default async function adminRoutes(server: FastifyInstance) {
|
||||
email: authProfiles.email,
|
||||
})
|
||||
.from(authProfiles)
|
||||
.where(eq(authProfiles.id, profileId))
|
||||
.where(and(eq(authProfiles.id, profileId), isNull(authProfiles.archived_at)))
|
||||
.limit(1);
|
||||
|
||||
if (!profile) {
|
||||
@@ -951,11 +958,16 @@ export default async function adminRoutes(server: FastifyInstance) {
|
||||
id: authUsers.id,
|
||||
email: authUsers.email,
|
||||
is_admin: authUsers.is_admin,
|
||||
archived_at: authUsers.archived_at,
|
||||
})
|
||||
.from(authUsers)
|
||||
.where(eq(authUsers.email, email))
|
||||
.limit(1);
|
||||
|
||||
if (existingUser?.archived_at) {
|
||||
return reply.code(409).send({ error: "Dieses Benutzerkonto ist dauerhaft archiviert." });
|
||||
}
|
||||
|
||||
const derivedName = deriveNameFromEmail(email);
|
||||
const firstName = customerRecord.firstname?.trim() || derivedName.first_name;
|
||||
const lastName = customerRecord.lastname?.trim() || derivedName.last_name;
|
||||
@@ -1187,6 +1199,12 @@ export default async function adminRoutes(server: FastifyInstance) {
|
||||
if (!currentUser) return;
|
||||
|
||||
const { user_id } = req.params as { user_id: string };
|
||||
const [account] = await server.db.select({ archived_at: authUsers.archived_at })
|
||||
.from(authUsers).where(eq(authUsers.id, user_id)).limit(1);
|
||||
if (!account) return reply.code(404).send({ error: "User not found" });
|
||||
if (account.archived_at) {
|
||||
return reply.code(409).send({ error: "Archivierte Benutzer können nicht mehr bearbeitet werden." });
|
||||
}
|
||||
const body = req.body as {
|
||||
email?: string;
|
||||
multiTenant?: boolean;
|
||||
@@ -1236,6 +1254,12 @@ export default async function adminRoutes(server: FastifyInstance) {
|
||||
if (!currentUser) return;
|
||||
|
||||
const { user_id } = req.params as { user_id: string };
|
||||
const [account] = await server.db.select({ archived_at: authUsers.archived_at })
|
||||
.from(authUsers).where(eq(authUsers.id, user_id)).limit(1);
|
||||
if (!account) return reply.code(404).send({ error: "User not found" });
|
||||
if (account.archived_at) {
|
||||
return reply.code(409).send({ error: "Archivierte Benutzer können nicht mehr bearbeitet werden." });
|
||||
}
|
||||
const body = (req.body || {}) as { password?: string };
|
||||
const requestedPassword = body.password?.trim();
|
||||
|
||||
@@ -1636,6 +1660,12 @@ export default async function adminRoutes(server: FastifyInstance) {
|
||||
if (!currentUser) return;
|
||||
|
||||
const { user_id } = req.params as { user_id: string };
|
||||
const [account] = await server.db.select({ archived_at: authUsers.archived_at })
|
||||
.from(authUsers).where(eq(authUsers.id, user_id)).limit(1);
|
||||
if (!account) return reply.code(404).send({ error: "User not found" });
|
||||
if (account.archived_at) {
|
||||
return reply.code(409).send({ error: "Archivierte Benutzer können nicht mehr bearbeitet werden." });
|
||||
}
|
||||
const body = req.body as {
|
||||
tenant_ids?: number[];
|
||||
role_assignments?: { tenant_id: number; role_id: string }[];
|
||||
@@ -1712,7 +1742,9 @@ export default async function adminRoutes(server: FastifyInstance) {
|
||||
.where(
|
||||
and(
|
||||
inArray(authProfiles.tenant_id, tenantIds),
|
||||
isNull(authProfiles.user_id)
|
||||
isNull(authProfiles.user_id),
|
||||
isNull(authProfiles.archived_at),
|
||||
eq(authProfiles.active, true)
|
||||
)
|
||||
)
|
||||
: [];
|
||||
@@ -1835,6 +1867,10 @@ export default async function adminRoutes(server: FastifyInstance) {
|
||||
});
|
||||
}
|
||||
|
||||
const [targetUser] = await server.db.select({ id: authUsers.id })
|
||||
.from(authUsers).where(and(eq(authUsers.id, body.user_id), isNull(authUsers.archived_at))).limit(1);
|
||||
if (!targetUser) return reply.code(404).send({ error: "Aktiver Benutzer nicht gefunden." });
|
||||
|
||||
const mode = body.mode ?? "multi";
|
||||
|
||||
// ----------------------------
|
||||
|
||||
51
backend/src/routes/adminUserArchive.ts
Normal file
51
backend/src/routes/adminUserArchive.ts
Normal file
@@ -0,0 +1,51 @@
|
||||
import type { FastifyInstance } from "fastify"
|
||||
import { eq } from "drizzle-orm"
|
||||
import { authProfiles, authRefreshTokens, authUsers, m2mApiKeys } from "../../db/schema"
|
||||
import { requireSystemAdmin } from "../utils/requireSystemAdmin"
|
||||
|
||||
export default async function adminUserArchiveRoutes(server: FastifyInstance) {
|
||||
server.post("/admin/users/:user_id/archive", {
|
||||
schema: {
|
||||
params: {
|
||||
type: "object",
|
||||
required: ["user_id"],
|
||||
properties: { user_id: { type: "string", format: "uuid" } },
|
||||
},
|
||||
},
|
||||
}, async (req, reply) => {
|
||||
const currentUser = await requireSystemAdmin(server, req, reply)
|
||||
if (!currentUser) return
|
||||
|
||||
const { user_id } = req.params as { user_id: string }
|
||||
if (user_id === currentUser.id) {
|
||||
return reply.code(409).send({ error: "Das eigene Benutzerkonto kann nicht archiviert werden." })
|
||||
}
|
||||
|
||||
const user = await server.db.transaction(async (tx) => {
|
||||
// Serialize repeated archive requests and keep the original archive date.
|
||||
const [target] = await tx.select({ id: authUsers.id, archived_at: authUsers.archived_at })
|
||||
.from(authUsers).where(eq(authUsers.id, user_id)).limit(1).for("update")
|
||||
if (!target) return null
|
||||
|
||||
const archivedAt = target.archived_at || new Date()
|
||||
const [archivedUser] = await tx.update(authUsers)
|
||||
.set({ archived_at: archivedAt, updatedAt: archivedAt })
|
||||
.where(eq(authUsers.id, user_id))
|
||||
.returning({ id: authUsers.id, archived_at: authUsers.archived_at })
|
||||
|
||||
// Keep links intact so existing documents and time records retain their authors.
|
||||
await tx.update(authProfiles)
|
||||
.set({ active: false, archived_at: archivedAt, token_id: null, calendar_subscription_token: null })
|
||||
.where(eq(authProfiles.user_id, user_id))
|
||||
await tx.update(authRefreshTokens).set({ revokedAt: archivedAt })
|
||||
.where(eq(authRefreshTokens.userId, user_id))
|
||||
await tx.update(m2mApiKeys).set({ active: false, updatedAt: archivedAt })
|
||||
.where(eq(m2mApiKeys.userId, user_id))
|
||||
|
||||
return archivedUser
|
||||
})
|
||||
|
||||
if (!user) return reply.code(404).send({ error: "Benutzer nicht gefunden." })
|
||||
return { user }
|
||||
})
|
||||
}
|
||||
@@ -6,7 +6,7 @@ import { sendMail } from "../../utils/mailer";
|
||||
import { authUsers } from "../../../db/schema";
|
||||
import { authTenantUsers } from "../../../db/schema";
|
||||
import { tenants } from "../../../db/schema";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { and, eq, isNull } from "drizzle-orm";
|
||||
import { resolveLoginTenant } from "../../utils/loginTenant";
|
||||
import {
|
||||
createAccessToken,
|
||||
@@ -112,7 +112,7 @@ export default async function authRoutes(server: FastifyInstance) {
|
||||
const [found] = await server.db
|
||||
.select()
|
||||
.from(authUsers)
|
||||
.where(eq(authUsers.email, body.email.toLowerCase()))
|
||||
.where(and(eq(authUsers.email, body.email.toLowerCase()), isNull(authUsers.archived_at)))
|
||||
.limit(1);
|
||||
|
||||
if (!found) {
|
||||
@@ -216,7 +216,7 @@ export default async function authRoutes(server: FastifyInstance) {
|
||||
mustChangePassword: authUsers.must_change_password,
|
||||
})
|
||||
.from(authUsers)
|
||||
.where(eq(authUsers.email, email.toLowerCase()))
|
||||
.where(and(eq(authUsers.email, email.toLowerCase()), isNull(authUsers.archived_at)))
|
||||
.limit(1);
|
||||
|
||||
if (!user) {
|
||||
|
||||
@@ -58,6 +58,7 @@ export default async function meRoutes(server: FastifyInstance) {
|
||||
features: tenants.features,
|
||||
extraModules: tenants.extraModules,
|
||||
businessInfo: tenants.businessInfo,
|
||||
portalConfig: tenants.portalConfig,
|
||||
numberRanges: tenants.numberRanges,
|
||||
accountChart: tenants.accountChart,
|
||||
taxEvaluationPeriod: tenants.taxEvaluationPeriod,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { FastifyInstance } from "fastify"
|
||||
import { eq, and } from "drizzle-orm"
|
||||
import { eq, and, isNull } from "drizzle-orm"
|
||||
|
||||
import {
|
||||
authUsers,
|
||||
@@ -83,7 +83,8 @@ export default async function userRoutes(server: FastifyInstance) {
|
||||
.where(
|
||||
and(
|
||||
eq(authProfiles.user_id, id),
|
||||
eq(authProfiles.tenant_id, req.user.tenant_id)
|
||||
eq(authProfiles.tenant_id, req.user.tenant_id),
|
||||
isNull(authProfiles.archived_at)
|
||||
)
|
||||
)
|
||||
|
||||
@@ -99,6 +100,7 @@ export default async function userRoutes(server: FastifyInstance) {
|
||||
}
|
||||
|
||||
const updateData: any = { ...data }
|
||||
for (const key of ["archived_at", "user_id", "tenant_id", "id"]) delete updateData[key]
|
||||
|
||||
// bekannte Date-Felder prüfen
|
||||
if (data.entry_date !== undefined)
|
||||
@@ -116,9 +118,10 @@ export default async function userRoutes(server: FastifyInstance) {
|
||||
const [updatedProfile] = await server.db
|
||||
.update(authProfiles)
|
||||
.set(updateData)
|
||||
.where(eq(authProfiles.id, profile.id))
|
||||
.where(and(eq(authProfiles.id, profile.id), isNull(authProfiles.archived_at)))
|
||||
.returning()
|
||||
|
||||
if (!updatedProfile) return reply.code(404).send({ error: "Profile not found in tenant" })
|
||||
return { profile: updatedProfile }
|
||||
|
||||
} catch (err: any) {
|
||||
|
||||
@@ -10,6 +10,7 @@ import { DE_BANK_CODE_TO_BIC } from "../utils/deBankBics"
|
||||
import { centralServicesClient } from "../modules/push-server.client"
|
||||
import { findBankInstitutionByBic } from "../modules/banking-institution"
|
||||
import { normalizeBankAllocationDetails, validateBankAllocationCostCentre } from "../modules/bank-allocation-details"
|
||||
import { CASHBOOK_BANK_ID } from "../modules/bank-balances.service"
|
||||
|
||||
import {
|
||||
bankrequisitions,
|
||||
@@ -33,9 +34,7 @@ import {
|
||||
desc,
|
||||
} from "drizzle-orm"
|
||||
|
||||
|
||||
export default async function bankingRoutes(server: FastifyInstance) {
|
||||
const CASHBOOK_BANK_ID = "fedeo-cashbook"
|
||||
const ContraAccounts = aliasedTable(accounts, "contra_accounts")
|
||||
const ContraCustomers = aliasedTable(customers, "contra_customers")
|
||||
const ContraVendors = aliasedTable(vendors, "contra_vendors")
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { createHash } from "node:crypto"
|
||||
import { FastifyInstance } from "fastify"
|
||||
import { and, asc, desc, eq, gt, inArray, ne, sql } from "drizzle-orm"
|
||||
import { and, asc, desc, eq, gt, inArray, isNull, ne, sql } from "drizzle-orm"
|
||||
import {
|
||||
authProfiles,
|
||||
authTenantUsers,
|
||||
@@ -80,7 +80,7 @@ export default async function communicationRoutes(server: FastifyInstance) {
|
||||
eq(authProfiles.user_id, authTenantUsers.user_id),
|
||||
eq(authProfiles.tenant_id, tenantId)
|
||||
))
|
||||
.where(eq(authTenantUsers.tenant_id, tenantId))
|
||||
.where(and(eq(authTenantUsers.tenant_id, tenantId), isNull(authUsers.archived_at)))
|
||||
|
||||
const addMembers = async (roomId: string, userIds: string[]) => {
|
||||
const uniqueUserIds = Array.from(new Set(userIds.filter(Boolean)))
|
||||
@@ -122,7 +122,8 @@ export default async function communicationRoutes(server: FastifyInstance) {
|
||||
.where(eq(communicationRooms.id, room.id)).returning()
|
||||
}
|
||||
const users = await tx.select({ userId: authTenantUsers.user_id }).from(authTenantUsers)
|
||||
.where(eq(authTenantUsers.tenant_id, tenantId))
|
||||
.innerJoin(authUsers, eq(authUsers.id, authTenantUsers.user_id))
|
||||
.where(and(eq(authTenantUsers.tenant_id, tenantId), isNull(authUsers.archived_at)))
|
||||
if (users.length) await tx.insert(communicationRoomMembers)
|
||||
.values([...new Set(users.map(user => user.userId))].map(userId => ({ roomId: room.id, userId })))
|
||||
.onConflictDoNothing()
|
||||
@@ -157,6 +158,16 @@ export default async function communicationRoutes(server: FastifyInstance) {
|
||||
entityUuid: room.entityUuid,
|
||||
exists: true,
|
||||
})
|
||||
// Rooms without messages fall back to their creation date so new rooms still sort by recency.
|
||||
const withActivity = async <T extends { room: typeof communicationRooms.$inferSelect }>(rows: T[]) => {
|
||||
const ids = rows.map(({ room }) => room.id)
|
||||
const latest = ids.length ? await server.db.select({
|
||||
roomId: communicationMessages.roomId,
|
||||
at: sql<Date>`max(${communicationMessages.createdAt})`.mapWith(communicationMessages.createdAt),
|
||||
}).from(communicationMessages).where(inArray(communicationMessages.roomId, ids)).groupBy(communicationMessages.roomId) : []
|
||||
const byRoom = new Map(latest.map((row) => [row.roomId, row.at]))
|
||||
return (room: typeof communicationRooms.$inferSelect) => (byRoom.get(room.id) || room.createdAt).toISOString()
|
||||
}
|
||||
|
||||
const messagesForRoom = async (roomId: string, currentUserId: string, tenantId: number, afterId = 0, limit = 50) => {
|
||||
const conditions = [eq(communicationMessages.roomId, roomId)]
|
||||
@@ -294,7 +305,8 @@ export default async function communicationRoutes(server: FastifyInstance) {
|
||||
eq(communicationRooms.archived, false),
|
||||
eq(communicationRoomMembers.userId, req.user.user_id)
|
||||
)).orderBy(asc(communicationRooms.name))
|
||||
return { rooms: rows.map(({ room }) => roomToApi(room)) }
|
||||
const activity = await withActivity(rows)
|
||||
return { rooms: rows.map(({ room }) => ({ ...roomToApi(room), lastActivityAt: activity(room) })) }
|
||||
})
|
||||
|
||||
server.post("/communication/chat/rooms", async (req: any, reply) => {
|
||||
@@ -334,9 +346,10 @@ export default async function communicationRoutes(server: FastifyInstance) {
|
||||
projectChatAccess(server.db, req),
|
||||
])
|
||||
const roomsByProject = new Map(roomRows.map(({ room }) => [room.entityId, room]))
|
||||
const activity = await withActivity(roomRows)
|
||||
return { rooms: projectRows.map((project) => {
|
||||
const room = roomsByProject.get(project.id)
|
||||
return room ? { ...roomToApi(room), projectId: project.id, projectNumber: project.projectNumber } : {
|
||||
return room ? { ...roomToApi(room), lastActivityAt: activity(room), projectId: project.id, projectNumber: project.projectNumber } : {
|
||||
key: `project_${project.id}`,
|
||||
name: project.projectNumber ? `${project.projectNumber} · ${project.name}` : project.name,
|
||||
topic: `Projektkommunikation zu ${project.name}`,
|
||||
@@ -372,7 +385,7 @@ export default async function communicationRoutes(server: FastifyInstance) {
|
||||
const profileIds = (project.profiles || []) as string[]
|
||||
const memberProfiles = profileIds.length
|
||||
? await server.db.select({ userId: authProfiles.user_id }).from(authProfiles)
|
||||
.where(and(eq(authProfiles.tenant_id, tenantId), inArray(authProfiles.id, profileIds)))
|
||||
.where(and(eq(authProfiles.tenant_id, tenantId), inArray(authProfiles.id, profileIds), eq(authProfiles.active, true)))
|
||||
: []
|
||||
const projectMemberIds = memberProfiles.map((profile) => profile.userId).filter(Boolean) as string[]
|
||||
await addMembers(room.id, [req.user.user_id, ...projectMemberIds])
|
||||
@@ -386,11 +399,13 @@ export default async function communicationRoutes(server: FastifyInstance) {
|
||||
.innerJoin(communicationRoomMembers, eq(communicationRoomMembers.roomId, communicationRooms.id))
|
||||
.where(and(eq(communicationRooms.tenantId, tenantId), eq(communicationRooms.type, "direct"), eq(communicationRoomMembers.userId, req.user.user_id)))
|
||||
const roomsByKey = new Map(existingRows.map(({ room }) => [room.key, room]))
|
||||
const activity = await withActivity(existingRows)
|
||||
return { rooms: users.map((user) => {
|
||||
const key = directRoomKey(req.user.user_id, user.userId)
|
||||
const room = roomsByKey.get(key)
|
||||
return room ? {
|
||||
...roomToApi(room),
|
||||
lastActivityAt: activity(room),
|
||||
name: displayName(user),
|
||||
topic: `Direktnachricht mit ${displayName(user)}`,
|
||||
entityUuid: user.userId,
|
||||
|
||||
@@ -44,7 +44,8 @@ export default async function devicesRFIDRoutes(server: FastifyInstance) {
|
||||
.where(
|
||||
and(
|
||||
eq(authProfiles.tenant_id, device.tenant),
|
||||
eq(authProfiles.token_id, rfid_id)
|
||||
eq(authProfiles.token_id, rfid_id),
|
||||
eq(authProfiles.active, true)
|
||||
)
|
||||
)
|
||||
.limit(1)
|
||||
|
||||
@@ -22,6 +22,7 @@ import {citys, files} from "../../db/schema";
|
||||
import {and, eq, isNull, not} from "drizzle-orm";
|
||||
import {cancelManualGeneration, executeManualGeneration, finishManualGeneration} from "../modules/serialexecution.service";
|
||||
import { updateOutgoingDocumentCostCentres } from "../modules/outgoing-document-cost-centres.service";
|
||||
import { updateIncomingInvoiceCostCentres } from "../modules/incoming-invoice-cost-centres.service";
|
||||
import { s3 } from "../utils/s3";
|
||||
import { secrets } from "../utils/secrets";
|
||||
import { storeExtractedTextForFile } from "../utils/documentText";
|
||||
@@ -334,6 +335,26 @@ export default async function functionRoutes(server: FastifyInstance) {
|
||||
}
|
||||
})
|
||||
|
||||
server.put('/functions/incoming-invoices/:id/cost-centres', async (req, reply) => {
|
||||
try {
|
||||
const { id } = req.params as { id: string }
|
||||
const invoiceId = Number(id)
|
||||
if (!Number.isFinite(invoiceId)) return reply.code(400).send({ error: "Ungültige Eingangsbeleg-ID" })
|
||||
|
||||
const invoice = await updateIncomingInvoiceCostCentres(
|
||||
server,
|
||||
req.user.tenant_id,
|
||||
req.user.user_id,
|
||||
invoiceId,
|
||||
req.body as any,
|
||||
)
|
||||
return { invoice }
|
||||
} catch (error) {
|
||||
const statusCode = (error as any)?.statusCode || 500
|
||||
return reply.code(statusCode).send({ error: error instanceof Error ? error.message : "Kostenstellen konnten nicht geändert werden" })
|
||||
}
|
||||
})
|
||||
|
||||
server.post('/functions/services/bankstatementsync', async (req, reply) => {
|
||||
const result = await server.services.bankStatements.run(req.user.tenant_id);
|
||||
if (result.errors.length > 0) {
|
||||
@@ -348,8 +369,11 @@ export default async function functionRoutes(server: FastifyInstance) {
|
||||
})
|
||||
|
||||
server.post('/functions/services/prepareincominginvoices', async (req, reply) => {
|
||||
return reply.code(202).send(server.services.prepareIncomingInvoices.start(req.user.tenant_id))
|
||||
})
|
||||
|
||||
await server.services.prepareIncomingInvoices.run(req.user.tenant_id)
|
||||
server.get('/functions/services/prepareincominginvoices', async (req) => {
|
||||
return server.services.prepareIncomingInvoices.status(req.user.tenant_id)
|
||||
})
|
||||
|
||||
server.get('/functions/liquidity-forecast', async (req, reply) => {
|
||||
|
||||
@@ -7,7 +7,7 @@ import {
|
||||
tenants
|
||||
} from "../../../db/schema"
|
||||
|
||||
import {and, eq, inArray} from "drizzle-orm"
|
||||
import {and, eq, inArray, isNull} from "drizzle-orm"
|
||||
import { enrichProfilesWithBranches } from "../../utils/profileBranches"
|
||||
import { enrichProfilesWithTeams } from "../../utils/profileTeams"
|
||||
|
||||
@@ -52,7 +52,7 @@ export default async function tenantRoutesInternal(server: FastifyInstance) {
|
||||
const users = await server.db
|
||||
.select()
|
||||
.from(authUsers)
|
||||
.where(inArray(authUsers.id, userIds))
|
||||
.where(and(inArray(authUsers.id, userIds), isNull(authUsers.archived_at)))
|
||||
|
||||
// 3) auth_profiles pro Tenant laden
|
||||
const profileRows = await server.db
|
||||
@@ -61,7 +61,9 @@ export default async function tenantRoutesInternal(server: FastifyInstance) {
|
||||
.where(
|
||||
and(
|
||||
eq(authProfiles.tenant_id, tenantId),
|
||||
inArray(authProfiles.user_id, userIds)
|
||||
inArray(authProfiles.user_id, userIds),
|
||||
eq(authProfiles.active, true),
|
||||
isNull(authProfiles.archived_at)
|
||||
))
|
||||
const profilesWithBranches = await enrichProfilesWithBranches(server, profileRows)
|
||||
const profiles = await enrichProfilesWithTeams(server, profilesWithBranches)
|
||||
@@ -98,7 +100,7 @@ export default async function tenantRoutesInternal(server: FastifyInstance) {
|
||||
const profileRows = await server.db
|
||||
.select()
|
||||
.from(authProfiles)
|
||||
.where(eq(authProfiles.tenant_id, tenantId))
|
||||
.where(and(eq(authProfiles.tenant_id, tenantId), eq(authProfiles.active, true), isNull(authProfiles.archived_at)))
|
||||
|
||||
const profilesWithBranches = await enrichProfilesWithBranches(server, profileRows)
|
||||
return await enrichProfilesWithTeams(server, profilesWithBranches)
|
||||
|
||||
@@ -11,6 +11,11 @@ import { s3 } from "../utils/s3"
|
||||
import { secrets } from "../utils/secrets"
|
||||
import { GetObjectCommand } from "@aws-sdk/client-s3"
|
||||
import { sanitizeFilename } from "../utils/filename"
|
||||
import multipart from "@fastify/multipart"
|
||||
import { MCP_FILE_LIMIT } from "../mcp/documentFiles"
|
||||
import { parseUploadQuery, storeMcpFileUpload } from "../mcp/fileUploads"
|
||||
|
||||
const RAW_UPLOAD_TYPES = ["application/pdf", "application/octet-stream", "application/xml", "text/xml", "image/jpeg", "image/png", "image/tiff"]
|
||||
|
||||
const SUPPORTED_PROTOCOL_VERSIONS = [
|
||||
"2025-11-25",
|
||||
@@ -62,7 +67,13 @@ const requireMcpTokenManagementPermission = (req: any) => {
|
||||
throw Object.assign(new Error("Fehlende Berechtigung: mcp.tokens.write"), { statusCode: 403 })
|
||||
}
|
||||
|
||||
export default async function mcpRoutes(server: FastifyInstance) {
|
||||
type McpRouteOptions = {
|
||||
/** Replaceable in tests to avoid object storage. */
|
||||
storeUpload?: typeof storeMcpFileUpload
|
||||
}
|
||||
|
||||
export default async function mcpRoutes(server: FastifyInstance, options: McpRouteOptions = {}) {
|
||||
const storeUpload = options.storeUpload || storeMcpFileUpload
|
||||
server.get("/mcp/tokens", async (req, reply) => {
|
||||
try {
|
||||
requireMcpTokenManagementPermission(req)
|
||||
@@ -221,6 +232,37 @@ export default async function mcpRoutes(server: FastifyInstance) {
|
||||
}
|
||||
})
|
||||
|
||||
// Binary uploads without Base64; parsers stay scoped so JSON-RPC parsing is unaffected.
|
||||
await server.register(async (uploads) => {
|
||||
await uploads.register(multipart, { limits: { fileSize: MCP_FILE_LIMIT, files: 1 } })
|
||||
uploads.addContentTypeParser(RAW_UPLOAD_TYPES, { parseAs: "buffer", bodyLimit: MCP_FILE_LIMIT }, (_req, body, done) => done(null, body))
|
||||
|
||||
uploads.post("/mcp/files", async (req, reply) => {
|
||||
try {
|
||||
const context = await createMcpContext(server, req)
|
||||
const query = parseUploadQuery(req.query as Record<string, unknown>)
|
||||
let body: Buffer
|
||||
let filename = query.filename
|
||||
let mimeType = req.headers["content-type"]?.split(";")[0].trim() || null
|
||||
if (req.isMultipart()) {
|
||||
const part = await req.file()
|
||||
if (!part || part.fieldname !== "file") return reply.code(400).send({ error: "Bitte die Datei im Feld file übertragen." })
|
||||
body = await part.toBuffer()
|
||||
filename ||= part.filename
|
||||
mimeType = part.mimetype
|
||||
} else if (Buffer.isBuffer(req.body)) {
|
||||
body = req.body
|
||||
} else {
|
||||
return reply.code(415).send({ error: `Bitte multipart/form-data oder einen der Content-Types ${RAW_UPLOAD_TYPES.join(", ")} verwenden.` })
|
||||
}
|
||||
if (!filename) return reply.code(400).send({ error: "filename ist erforderlich." })
|
||||
return await storeUpload(context, { ...query, filename, body, mimeType })
|
||||
} catch (error) {
|
||||
return reply.code((error as any)?.statusCode || 400).send({ error: error instanceof Error ? error.message : "Upload 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]
|
||||
@@ -270,7 +312,7 @@ export default async function mcpRoutes(server: FastifyInstance) {
|
||||
description: tool.description,
|
||||
inputSchema: tool.inputSchema,
|
||||
annotations: {
|
||||
readOnlyHint: !tool.requiredPermissions.some((permission) => permission.endsWith(".write")),
|
||||
readOnlyHint: tool.readOnly ?? !tool.requiredPermissions.some((permission) => permission.endsWith(".write")),
|
||||
},
|
||||
})),
|
||||
}))
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { FastifyInstance } from "fastify";
|
||||
import { eq, and } from "drizzle-orm";
|
||||
import { eq, and, isNull } from "drizzle-orm";
|
||||
|
||||
import {
|
||||
authProfiles,
|
||||
@@ -57,7 +57,7 @@ export default async function authProfilesRoutes(server: FastifyInstance) {
|
||||
const forbidden = [
|
||||
"id", "user_id", "tenant_id", "created_at", "updated_at",
|
||||
"updatedAt", "updatedBy", "old_profile_id", "full_name",
|
||||
"branch", "calendar_subscription_token",
|
||||
"branch", "archived_at", "calendar_subscription_token",
|
||||
"calendar_subscription_path", "calendar_subscription_url"
|
||||
]
|
||||
forbidden.forEach(f => delete cleaned[f])
|
||||
@@ -135,7 +135,8 @@ export default async function authProfilesRoutes(server: FastifyInstance) {
|
||||
.where(
|
||||
and(
|
||||
eq(authProfiles.id, id),
|
||||
eq(authProfiles.tenant_id, tenantId)
|
||||
eq(authProfiles.tenant_id, tenantId),
|
||||
isNull(authProfiles.archived_at)
|
||||
)
|
||||
)
|
||||
.returning()
|
||||
|
||||
@@ -9,12 +9,14 @@ import {
|
||||
and,
|
||||
count,
|
||||
inArray,
|
||||
isNull,
|
||||
or,
|
||||
sql,
|
||||
} from "drizzle-orm"
|
||||
|
||||
import {
|
||||
authProfiles,
|
||||
authUsers,
|
||||
createddocuments,
|
||||
customers,
|
||||
entitybankaccounts,
|
||||
@@ -138,7 +140,10 @@ function buildFieldUpdateHistoryText(resource: string, label: string, oldValue:
|
||||
return `${resourceLabel}: ${label} geändert von "${formatDiffValue(oldValue)}" zu "${formatDiffValue(newValue)}"`
|
||||
}
|
||||
|
||||
function applyResourceWhereFilters(resource: string, table: any, whereCond: any) {
|
||||
function applyResourceWhereFilters(resource: string, table: any, whereCond: any, list = false) {
|
||||
if (list && table === authProfiles) {
|
||||
return and(whereCond, eq(authProfiles.active, true), isNull(authProfiles.archived_at))
|
||||
}
|
||||
if (resource === "members") {
|
||||
return and(whereCond, eq(table.type, "Mitglied"))
|
||||
}
|
||||
@@ -570,7 +575,7 @@ export default async function resourceRoutes(server: FastifyInstance) {
|
||||
|
||||
const tenantColumn = getTenantColumn(resource, table)
|
||||
let whereCond: any = tenantColumn ? eq(tenantColumn, tenantId) : undefined
|
||||
whereCond = applyResourceWhereFilters(resource, table, whereCond)
|
||||
whereCond = applyResourceWhereFilters(resource, table, whereCond, true)
|
||||
whereCond = applyPortalScope(resource, table, whereCond, portalCustomerId)
|
||||
let q = server.db.select().from(table).$dynamic()
|
||||
|
||||
@@ -688,7 +693,7 @@ export default async function resourceRoutes(server: FastifyInstance) {
|
||||
|
||||
const tenantColumn = getTenantColumn(resource, table);
|
||||
let whereCond: any = tenantColumn ? eq(tenantColumn, tenantId) : undefined;
|
||||
whereCond = applyResourceWhereFilters(resource, table, whereCond)
|
||||
whereCond = applyResourceWhereFilters(resource, table, whereCond, true)
|
||||
whereCond = applyPortalScope(resource, table, whereCond, portalCustomerId)
|
||||
const searchCols: any[] = (config.searchColumns || []).map(c => table[c]);
|
||||
const debugSearchColumnNames: string[] = [...(config.searchColumns || [])];
|
||||
@@ -789,7 +794,7 @@ export default async function resourceRoutes(server: FastifyInstance) {
|
||||
});
|
||||
}
|
||||
let distinctWhereCond: any = tenantColumn ? eq(tenantColumn, tenantId) : undefined
|
||||
distinctWhereCond = applyResourceWhereFilters(resource, table, distinctWhereCond)
|
||||
distinctWhereCond = applyResourceWhereFilters(resource, table, distinctWhereCond, true)
|
||||
distinctWhereCond = applyPortalScope(resource, table, distinctWhereCond, portalCustomerId)
|
||||
|
||||
if (search) {
|
||||
@@ -878,7 +883,7 @@ export default async function resourceRoutes(server: FastifyInstance) {
|
||||
}
|
||||
const table = resourceConfig[resource].table
|
||||
|
||||
let whereCond: any = and(eq(table.id, id), eq(table.tenant, tenantId))
|
||||
let whereCond: any = and(eq(table.id, id), eq(getTenantColumn(resource, table), tenantId))
|
||||
whereCond = applyResourceWhereFilters(resource, table, whereCond)
|
||||
whereCond = applyPortalScope(resource, table, whereCond, portalCustomerId)
|
||||
|
||||
@@ -943,6 +948,15 @@ export default async function resourceRoutes(server: FastifyInstance) {
|
||||
const table = config.table;
|
||||
|
||||
let createData: Record<string, any> = { ...body, tenant: req.user.tenant_id, archived: false };
|
||||
if (table === authProfiles) {
|
||||
delete createData.archived_at;
|
||||
createData.tenant_id = req.user.tenant_id;
|
||||
if (createData.user_id) {
|
||||
const [owner] = await server.db.select({ id: authUsers.id }).from(authUsers)
|
||||
.where(and(eq(authUsers.id, createData.user_id), isNull(authUsers.archived_at))).limit(1);
|
||||
if (!owner) return reply.code(409).send({ error: "Aktiver Benutzer nicht gefunden." });
|
||||
}
|
||||
}
|
||||
if (resource === "projects") {
|
||||
const error = projectChatSettingError(req, createData)
|
||||
if (error) return reply.code(error.statusCode).send({ error: error.error })
|
||||
@@ -1093,7 +1107,7 @@ export default async function resourceRoutes(server: FastifyInstance) {
|
||||
const [oldRecord] = await server.db
|
||||
.select()
|
||||
.from(table)
|
||||
.where(applyPortalScope(resource, table, and(eq(table.id, id), eq(table.tenant, tenantId)), portalCustomerId))
|
||||
.where(applyPortalScope(resource, table, and(eq(table.id, id), eq(getTenantColumn(resource, table), tenantId)), portalCustomerId))
|
||||
.limit(1)
|
||||
|
||||
if (!oldRecord) {
|
||||
@@ -1105,7 +1119,13 @@ export default async function resourceRoutes(server: FastifyInstance) {
|
||||
if (error) return reply.code(error.statusCode).send({ error: error.error })
|
||||
}
|
||||
|
||||
if (table === authProfiles && oldRecord.archived_at) {
|
||||
return reply.code(409).send({ error: "Archivierte Profile können nicht mehr bearbeitet werden." })
|
||||
}
|
||||
let data: Record<string, any> = { ...body }
|
||||
if (table === authProfiles) {
|
||||
for (const key of ["archived_at", "user_id", "tenant_id", "id"]) delete data[key]
|
||||
}
|
||||
delete data.updatedAt
|
||||
delete data.updated_at
|
||||
delete data.updatedBy
|
||||
@@ -1194,7 +1214,8 @@ export default async function resourceRoutes(server: FastifyInstance) {
|
||||
}
|
||||
})
|
||||
|
||||
let updateWhereCond: any = and(eq(table.id, id), eq(table.tenant, tenantId))
|
||||
let updateWhereCond: any = and(eq(table.id, id), eq(getTenantColumn(resource, table), tenantId))
|
||||
if (table === authProfiles) updateWhereCond = and(updateWhereCond, isNull(authProfiles.archived_at))
|
||||
updateWhereCond = applyResourceWhereFilters(resource, table, updateWhereCond)
|
||||
const [updated] = await server.db.update(table).set(data).where(updateWhereCond).returning()
|
||||
|
||||
@@ -1203,7 +1224,7 @@ export default async function resourceRoutes(server: FastifyInstance) {
|
||||
.update(table)
|
||||
.set({ defaultMandate: false })
|
||||
.where(and(
|
||||
eq(table.tenant, tenantId),
|
||||
eq(getTenantColumn(resource, table), tenantId),
|
||||
eq(table.customer, updated.customer),
|
||||
sql`${table.id} <> ${updated.id}`
|
||||
))
|
||||
|
||||
@@ -11,7 +11,7 @@ import {
|
||||
m2mApiKeys
|
||||
} from "../../db/schema"
|
||||
|
||||
import {and, desc, eq, inArray} from "drizzle-orm"
|
||||
import {and, desc, eq, inArray, isNull} from "drizzle-orm"
|
||||
import { enrichProfilesWithBranches } from "../utils/profileBranches"
|
||||
import { enrichProfilesWithTeams } from "../utils/profileTeams"
|
||||
import { rotateRefreshToken } from "../utils/authTokens"
|
||||
@@ -152,7 +152,7 @@ export default async function tenantRoutes(server: FastifyInstance) {
|
||||
const users = await server.db
|
||||
.select()
|
||||
.from(authUsers)
|
||||
.where(inArray(authUsers.id, userIds))
|
||||
.where(and(inArray(authUsers.id, userIds), isNull(authUsers.archived_at)))
|
||||
|
||||
// 3) auth_profiles pro Tenant laden
|
||||
const profileRows = await server.db
|
||||
@@ -161,7 +161,9 @@ export default async function tenantRoutes(server: FastifyInstance) {
|
||||
.where(
|
||||
and(
|
||||
eq(authProfiles.tenant_id, tenantId),
|
||||
inArray(authProfiles.user_id, userIds)
|
||||
inArray(authProfiles.user_id, userIds),
|
||||
eq(authProfiles.active, true),
|
||||
isNull(authProfiles.archived_at)
|
||||
))
|
||||
const profilesWithBranches = await enrichProfilesWithBranches(server, profileRows)
|
||||
const profiles = await enrichProfilesWithTeams(server, profilesWithBranches)
|
||||
@@ -194,10 +196,14 @@ export default async function tenantRoutes(server: FastifyInstance) {
|
||||
const tenantId = req.user?.tenant_id
|
||||
if (!tenantId) return reply.code(401).send({ error: "Unauthorized" })
|
||||
|
||||
const includeArchived = (req.query as { includeArchived?: string }).includeArchived === "true"
|
||||
const profileRows = await server.db
|
||||
.select()
|
||||
.from(authProfiles)
|
||||
.where(eq(authProfiles.tenant_id, tenantId))
|
||||
.where(and(
|
||||
eq(authProfiles.tenant_id, tenantId),
|
||||
...(includeArchived ? [] : [eq(authProfiles.active, true), isNull(authProfiles.archived_at)])
|
||||
))
|
||||
|
||||
const profilesWithBranches = await enrichProfilesWithBranches(server, profileRows)
|
||||
const data = await enrichProfilesWithTeams(server, profilesWithBranches)
|
||||
@@ -271,6 +277,16 @@ export default async function tenantRoutes(server: FastifyInstance) {
|
||||
|
||||
if (!data) return reply.code(400).send({ error: "data required" })
|
||||
|
||||
if (Object.prototype.hasOwnProperty.call(data, "portalConfig")) {
|
||||
const config = data.portalConfig
|
||||
if (!config || typeof config !== "object" || Array.isArray(config)
|
||||
|| typeof config.primaryColor !== "string" || !/^#[0-9a-f]{6}$/i.test(config.primaryColor.trim())) {
|
||||
return reply.code(400).send({ error: "Die Portal-Akzentfarbe muss ein Hex-Farbwert wie #69c350 sein." })
|
||||
}
|
||||
data.portalConfig = { ...config, primaryColor: config.primaryColor.trim().toLowerCase() }
|
||||
delete data.portalConfig.primayColor
|
||||
}
|
||||
|
||||
const updated = await server.db
|
||||
.update(tenants)
|
||||
.set(data)
|
||||
|
||||
@@ -70,7 +70,7 @@ export async function rotateRefreshToken(
|
||||
const [user] = await server.db
|
||||
.select({ id: authUsers.id, email: authUsers.email })
|
||||
.from(authUsers)
|
||||
.where(eq(authUsers.id, session.userId))
|
||||
.where(and(eq(authUsers.id, session.userId), isNull(authUsers.archived_at)))
|
||||
.limit(1)
|
||||
|
||||
if (!user) return null
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import crypto from "crypto"
|
||||
import { and, asc, eq, sql } from "drizzle-orm"
|
||||
import { and, asc, eq, isNull, sql } from "drizzle-orm"
|
||||
import { FastifyInstance } from "fastify"
|
||||
|
||||
import { authProfiles, events } from "../../db/schema"
|
||||
@@ -105,7 +105,8 @@ export async function generateProfileCalendarSubscriptionToken(server: FastifyIn
|
||||
.where(
|
||||
and(
|
||||
eq(authProfiles.id, profileId),
|
||||
eq(authProfiles.tenant_id, tenantId)
|
||||
eq(authProfiles.tenant_id, tenantId),
|
||||
isNull(authProfiles.archived_at)
|
||||
)
|
||||
)
|
||||
.returning()
|
||||
|
||||
@@ -50,7 +50,7 @@ export async function insertHistoryItem(
|
||||
created_by: string | null
|
||||
entity: string
|
||||
entityId: string | number
|
||||
action: "created" | "updated" | "unchanged" | "deleted" | "archived"
|
||||
action: "created" | "updated" | "unchanged" | "deleted" | "archived" | "restored"
|
||||
oldVal?: any
|
||||
newVal?: any
|
||||
text?: string
|
||||
@@ -62,6 +62,7 @@ export async function insertHistoryItem(
|
||||
updated: `Eintrag in ${entityLabel} geändert`,
|
||||
unchanged: `Eintrag in ${entityLabel} unverändert`,
|
||||
archived: `Eintrag in ${entityLabel} archiviert`,
|
||||
restored: `Eintrag in ${entityLabel} wiederhergestellt`,
|
||||
deleted: `Eintrag in ${entityLabel} gelöscht`
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { and, eq, isNull } from "drizzle-orm";
|
||||
import { authUsers } from "../../db/schema/auth_users";
|
||||
|
||||
export async function requireSystemAdmin(server: FastifyInstance, req: FastifyRequest, reply: FastifyReply) {
|
||||
@@ -9,7 +9,7 @@ export async function requireSystemAdmin(server: FastifyInstance, req: FastifyRe
|
||||
}
|
||||
// Read the current global role; tenant roles and stale JWT claims do not grant access.
|
||||
const [user] = await server.db.select({ id: authUsers.id, email: authUsers.email, is_admin: authUsers.is_admin })
|
||||
.from(authUsers).where(eq(authUsers.id, req.user.user_id)).limit(1);
|
||||
.from(authUsers).where(and(eq(authUsers.id, req.user.user_id), isNull(authUsers.archived_at))).limit(1);
|
||||
if (!user?.is_admin) {
|
||||
reply.code(403).send({ error: "Admin access required" });
|
||||
return null;
|
||||
|
||||
24
backend/tests/bankBalances.test.ts
Normal file
24
backend/tests/bankBalances.test.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import assert from "node:assert/strict"
|
||||
import test from "node:test"
|
||||
import { calculateAccountBalance, CASHBOOK_BANK_ID } from "../src/modules/bank-balances.service"
|
||||
|
||||
const syncedAt = new Date("2026-10-20T08:00:00Z")
|
||||
const bank = { id: 1, name: "Giro", iban: "DE00", ownerName: null, bankId: "bank", datevNumber: "1200", balance: 1000.1, expired: false, syncedAt }
|
||||
const cashbook = { ...bank, id: 2, name: "Kasse", iban: "CASH-1", bankId: CASHBOOK_BANK_ID, datevNumber: "1000", balance: 50 }
|
||||
|
||||
test("bank accounts report the synced balance and revert later statements for a past date", () => {
|
||||
assert.equal(calculateAccountBalance(bank, 0, null).balance, 1000.1)
|
||||
assert.equal(calculateAccountBalance(bank, 0, null).source, "bank_sync")
|
||||
const past = calculateAccountBalance(bank, -200.05, "2026-10-01")
|
||||
assert.equal(past.balance, 1200.15)
|
||||
assert.equal(past.syncedBalance, 1000.1)
|
||||
assert.equal(past.source, "bank_sync_reconstructed")
|
||||
})
|
||||
|
||||
test("cashbooks add their bookings to the opening balance", () => {
|
||||
const result = calculateAccountBalance(cashbook, 12.345, null)
|
||||
assert.equal(result.type, "cashbook")
|
||||
assert.equal(result.balance, 62.35)
|
||||
assert.equal(result.openingBalance, 50)
|
||||
assert.equal(result.iban, null)
|
||||
})
|
||||
201
backend/tests/collaborationNotifications.test.ts
Normal file
201
backend/tests/collaborationNotifications.test.ts
Normal file
@@ -0,0 +1,201 @@
|
||||
import assert from "node:assert/strict"
|
||||
import test from "node:test"
|
||||
import { randomUUID } from "node:crypto"
|
||||
import { readFile } from "node:fs/promises"
|
||||
import Fastify from "fastify"
|
||||
import { eq } from "drizzle-orm"
|
||||
import { notificationsItems } from "../db/schema"
|
||||
import { CollaborationService } from "../src/modules/collaboration/service"
|
||||
import { FederationService, federationRoutes } from "../src/modules/collaboration/federation"
|
||||
import { CollaborationNotifications } from "../src/modules/collaboration/notifications"
|
||||
import type { Transport } from "../src/modules/collaboration/transport"
|
||||
import { collaborationDatabase, testDatabaseUrl } from "./helpers/collaboration-db"
|
||||
|
||||
const MESSAGE = "collaboration.message.new", INVITATION = "collaboration.room.invited"
|
||||
|
||||
test("collaboration notifications use real preferences, transactions and signed federation routes", { skip: !testDatabaseUrl }, async t => {
|
||||
const servers = new Map<string, ReturnType<typeof Fastify>>()
|
||||
let offline = false
|
||||
const transport: Transport = async (url, method, headers, body) => {
|
||||
if (offline) throw Object.assign(new Error("Offline"), { statusCode: 503 })
|
||||
const origin = [...servers.keys()].find(value => url.startsWith(value + "/"))!
|
||||
const response = await servers.get(origin)!.inject({ method, url: url.slice(origin.length), headers, ...(body ? { payload: body } : {}) })
|
||||
if (response.statusCode >= 400) throw Object.assign(new Error(response.json().message), { statusCode: response.statusCode })
|
||||
return response.json()
|
||||
}
|
||||
const make = async (name: string) => {
|
||||
const fixture = await collaborationDatabase(["0075_project_collaboration.sql", "0076_collaboration_federation.sql"])
|
||||
const original = await readFile(new URL("../db/migrations/0000_brief_dark_beast.sql", import.meta.url), "utf8")
|
||||
for (const type of ["notification_channel", "notification_status", "notification_severity"]) {
|
||||
const definition = original.match(new RegExp(`CREATE TYPE "public"\\."${type}" AS ENUM\\([^;]+;`))![0]
|
||||
await fixture.pool.query(definition.replace('"public".', ""))
|
||||
}
|
||||
for (const table of ["notifications_event_types", "notifications_items", "notifications_preferences", "notifications_preferences_defaults"]) {
|
||||
await fixture.pool.query(original.match(new RegExp(`CREATE TABLE "${table}" \\([\\s\\S]*?\\n\\);`))![0])
|
||||
}
|
||||
await fixture.pool.query("CREATE UNIQUE INDEX ON notifications_preferences(tenant_id,user_id,event_type,channel)")
|
||||
await fixture.pool.query("CREATE UNIQUE INDEX ON notifications_preferences_defaults(tenant_id,event_key,channel)")
|
||||
await fixture.pool.query(await readFile(new URL("../db/migrations/0083_collaboration_notifications.sql", import.meta.url), "utf8"))
|
||||
const userId = randomUUID()
|
||||
await fixture.pool.query("INSERT INTO tenants VALUES (1,$1,null,null),(2,'Other tenant',null,null)", [name])
|
||||
await fixture.pool.query("INSERT INTO auth_users(id,email,is_admin) VALUES ($1,$2,true)", [userId, `${name}@example.test`])
|
||||
await fixture.pool.query("INSERT INTO auth_tenant_users(tenant_id,user_id) VALUES (1,$1),(2,$1)", [userId])
|
||||
const service = new CollaborationService(fixture.db, { publicUrl: `https://${name}.example`, guestPepper: () => "a".repeat(64), sendMail: async () => ({ success: true }) })
|
||||
const federation = new FederationService(service, { apiUrl: `https://${name}.example/backend`, enabled: true, transport,
|
||||
seal: value => ({ key: value }), unseal: value => value.key })
|
||||
service.options.changed = (id, db) => federation.changed(id, db)
|
||||
service.options.invited = (ctx, roomId, target, invitationId, db) => federation.invite(ctx, roomId, target, invitationId, db)
|
||||
const app = Fastify()
|
||||
app.decorate("db", fixture.db)
|
||||
const notifications = new CollaborationNotifications(app, service, federation)
|
||||
service.options.notifications = notifications
|
||||
const delivered: any[] = []
|
||||
const delivery = notifications.delivery.bind(notifications)
|
||||
// Keep persistence and preference resolution real; replace only external channel delivery.
|
||||
notifications.delivery = db => {
|
||||
const sender = delivery(db)
|
||||
sender.deliver = async item => {
|
||||
delivered.push(item)
|
||||
await db.update(notificationsItems).set({ status: "sent", sentAt: new Date() }).where(eq(notificationsItems.id, item.id))
|
||||
return { success: true, id: item.id, channel: item.channel }
|
||||
}
|
||||
return sender
|
||||
}
|
||||
await app.register(federationRoutes, { federation })
|
||||
await app.ready()
|
||||
servers.set(federation.origin, app)
|
||||
return { ...fixture, service, federation, notifications, app, delivered, ctx: await service.userContext(userId, 1), other: await service.userContext(userId, 2),
|
||||
items: async () => (await fixture.pool.query("SELECT * FROM notifications_items ORDER BY created_at,id")).rows }
|
||||
}
|
||||
const a = await make("alpha"), b = await make("beta")
|
||||
try {
|
||||
await a.federation.settings(a.ctx, { origin: b.federation.origin, active: true })
|
||||
await b.federation.settings(b.ctx, { origin: a.federation.origin, active: true })
|
||||
const contact = await a.federation.resolveContact(a.ctx, b.federation.contact(b.ctx.principal))
|
||||
const room = await a.service.createRoom(a.ctx, { name: "Gemeinsamer Chat" })
|
||||
const before = await a.service.send(a.ctx.principal, room.id, { clientId: randomUUID(), text: "Private history" })
|
||||
let bindingId: string
|
||||
const jobFor = async (invitationId: string) => (await a.pool.query("SELECT * FROM collaboration_outbox WHERE dedup_key=$1", [`invite:${invitationId}`])).rows[0]
|
||||
const itemsFor = async (instance: typeof a, id: string) => (await instance.items()).filter(item => item.payload.messageId === id)
|
||||
const enable = async (instance: typeof a, tenantId = 1, enabled = true) => instance.notifications.delivery(instance.db).savePreferences(tenantId, instance.ctx.userId,
|
||||
["email", "push"].map(channel => ({ eventType: MESSAGE, channel, enabled })))
|
||||
|
||||
await t.test("new matrix events have quiet message defaults and per-tenant overrides", async () => {
|
||||
const preferences = await b.notifications.delivery(b.db).preferences(1, b.ctx.userId)
|
||||
assert.deepEqual(preferences.events.find(e => e.eventKey === MESSAGE)!.channels, { email: false, push: false })
|
||||
assert.deepEqual(preferences.events.find(e => e.eventKey === INVITATION)!.channels, { email: false, push: true })
|
||||
await enable(a); await enable(b)
|
||||
assert.deepEqual((await b.notifications.delivery(b.db).preferences(2, b.ctx.userId)).events.find(e => e.eventKey === MESSAGE)!.channels, { email: false, push: false })
|
||||
})
|
||||
await t.test("signed invitations notify only their named recipient, once despite redelivery", async () => {
|
||||
const invitation = await a.service.invite(a.ctx, room.id, contact, {})
|
||||
const job = await jobFor(invitation.id)
|
||||
await a.federation.deliver(job)
|
||||
bindingId = (await b.federation.list(b.ctx)).invitations[0].id
|
||||
await a.pool.query("UPDATE collaboration_outbox SET status='pending' WHERE id=$1", [job.id])
|
||||
await a.federation.deliver(job)
|
||||
const items = await b.items()
|
||||
assert.equal(items.length, 2)
|
||||
assert.deepEqual(items.map(i => i.channel).sort(), ["inapp", "push"])
|
||||
assert.ok(items.every(i => i.user_id === b.ctx.userId && Number(i.tenant_id) === 1 && i.event_type === INVITATION))
|
||||
assert.equal((await a.items()).length, 0)
|
||||
await b.notifications.tick()
|
||||
assert.equal(b.delivered.length, 2)
|
||||
await b.federation.accept(b.ctx, bindingId)
|
||||
assert.equal((await itemsFor(b, before.id)).length, 0)
|
||||
})
|
||||
await t.test("new remote messages notify once with the local room link, including simultaneous syncs", async () => {
|
||||
const message = await a.service.send(a.ctx.principal, room.id, { clientId: randomUUID(), text: "Hallo Beta" })
|
||||
await Promise.all([b.federation.memberRequest(b.ctx, bindingId, "messages"), b.federation.memberRequest(b.ctx, bindingId, "messages")])
|
||||
const items = await itemsFor(b, message.id)
|
||||
assert.equal(items.length, 3)
|
||||
assert.ok(items.every(i => i.message.includes("Hallo Beta") && i.payload.link === `/communication/chat?room=collaboration%3A${bindingId}`))
|
||||
assert.equal((await itemsFor(a, message.id)).length, 0)
|
||||
await b.federation.memberRequest(b.ctx, bindingId, "messages", { before: message.seq + 1 })
|
||||
assert.equal((await itemsFor(b, message.id)).length, 3)
|
||||
await b.notifications.tick()
|
||||
assert.equal(b.delivered.filter(i => i.payload.messageId === message.id).length, 3)
|
||||
})
|
||||
await t.test("remote replies notify the owner's local members, never the sender or retry twice", async () => {
|
||||
const input = { clientId: randomUUID(), text: "Hallo Alpha" }
|
||||
const reply = (await b.federation.memberRequest(b.ctx, bindingId, "send", input)).result
|
||||
await b.federation.memberRequest(b.ctx, bindingId, "send", input)
|
||||
await b.federation.memberRequest(b.ctx, bindingId, "messages")
|
||||
assert.equal((await itemsFor(a, reply.id)).length, 3)
|
||||
assert.equal((await itemsFor(b, reply.id)).length, 0)
|
||||
assert.ok((await itemsFor(a, reply.id)).every(i => Number(i.tenant_id) === 1 && i.user_id === a.ctx.userId))
|
||||
await a.notifications.tick()
|
||||
})
|
||||
await t.test("reading before delivery suppresses email and push, and new preferences take effect", async () => {
|
||||
const read = await a.service.send(a.ctx.principal, room.id, { clientId: randomUUID(), text: "Already read" })
|
||||
await b.federation.memberRequest(b.ctx, bindingId, "messages")
|
||||
await b.federation.memberRequest(b.ctx, bindingId, "read", { seq: read.seq })
|
||||
await b.notifications.tick()
|
||||
assert.deepEqual(b.delivered.filter(i => i.payload.messageId === read.id).map(i => i.channel), ["inapp"])
|
||||
const muted = await a.service.send(a.ctx.principal, room.id, { clientId: randomUUID(), text: "Muted before delivery" })
|
||||
await b.federation.memberRequest(b.ctx, bindingId, "messages")
|
||||
await enable(b, 1, false)
|
||||
await b.notifications.tick()
|
||||
assert.deepEqual(b.delivered.filter(i => i.payload.messageId === muted.id).map(i => i.channel), ["inapp"])
|
||||
await enable(b)
|
||||
})
|
||||
await t.test("offline jobs survive a worker restart and concurrent workers deliver each item once", async () => {
|
||||
const message = await a.service.send(a.ctx.principal, room.id, { clientId: randomUUID(), text: "Wait for access confirmation" })
|
||||
await b.federation.memberRequest(b.ctx, bindingId, "messages")
|
||||
offline = true
|
||||
await b.notifications.tick()
|
||||
assert.equal(b.delivered.filter(i => i.payload.messageId === message.id).length, 0)
|
||||
assert.ok((await itemsFor(b, message.id)).every(i => i.status === "queued"))
|
||||
offline = false
|
||||
const restarted = new CollaborationNotifications(b.app, b.service, b.federation)
|
||||
restarted.delivery = b.notifications.delivery
|
||||
await Promise.all([b.notifications.tick(), restarted.tick()])
|
||||
const delivered = b.delivered.filter(i => i.payload.messageId === message.id)
|
||||
assert.equal(delivered.length, 3)
|
||||
assert.equal(new Set(delivered.map(i => i.id)).size, 3)
|
||||
})
|
||||
await t.test("revoked access cancels queued remote messages and reinvitation cannot replay old ones", async () => {
|
||||
const message = await a.service.send(a.ctx.principal, room.id, { clientId: randomUUID(), text: "Revoked before delivery" })
|
||||
await b.federation.memberRequest(b.ctx, bindingId, "messages")
|
||||
const member = (await a.service.management(a.ctx, room.id)).members.find(m => m.principalId === contact.id)
|
||||
await a.service.revoke(a.ctx, room.id, member.id)
|
||||
await b.notifications.tick()
|
||||
assert.equal(b.delivered.filter(i => i.payload.messageId === message.id).length, 0)
|
||||
assert.equal((await itemsFor(b, message.id)).length, 0)
|
||||
const invitation = await a.service.invite(a.ctx, room.id, contact, {})
|
||||
await a.federation.deliver(await jobFor(invitation.id))
|
||||
await b.federation.accept(b.ctx, bindingId)
|
||||
await b.notifications.tick()
|
||||
assert.equal((await itemsFor(b, message.id)).length, 0)
|
||||
})
|
||||
await t.test("local cross-tenant invitations and messages use recipient scope and honor expiry", async () => {
|
||||
const local = await a.service.createRoom(a.ctx, { name: "Tenant exchange" })
|
||||
const invitation = await a.service.invite(a.ctx, local.id, a.other.principal, {})
|
||||
const invites = (await a.items()).filter(i => i.payload.invitationId === invitation.id)
|
||||
assert.equal(invites.length, 2)
|
||||
assert.ok(invites.every(i => Number(i.tenant_id) === 2))
|
||||
await a.service.accept(a.other.principal, invitation.id)
|
||||
const first = await a.service.send(a.ctx.principal, local.id, { clientId: randomUUID(), text: "Only tenant two" })
|
||||
assert.deepEqual((await itemsFor(a, first.id)).map(i => [Number(i.tenant_id), i.channel]), [[2, "inapp"]])
|
||||
await a.pool.query("UPDATE collaboration_members SET expires_at=now()-interval '1 second' WHERE room_id=$1 AND principal_id=$2", [local.id, a.other.principal.id])
|
||||
await a.notifications.tick()
|
||||
assert.equal(a.delivered.filter(i => i.payload.messageId === first.id).length, 0)
|
||||
const second = await a.service.send(a.ctx.principal, local.id, { clientId: randomUUID(), text: "Expired member" })
|
||||
assert.equal((await itemsFor(a, second.id)).length, 0)
|
||||
})
|
||||
await t.test("message and notification records roll back together", async () => {
|
||||
const hook = a.notifications.localMessage.bind(a.notifications)
|
||||
a.notifications.localMessage = async (...args) => { await hook(...args); throw new Error("Rollback after enqueue") }
|
||||
const clientId = randomUUID(), count = (await a.items()).length
|
||||
try {
|
||||
await assert.rejects(b.federation.call(1, a.federation.origin, "messages.send", { actorId: b.ctx.principal.id, roomId: room.id,
|
||||
input: { clientId, text: "Must roll back", revision: Number((await b.federation.binding(b.ctx, bindingId)).revision) } }), /Rollback/)
|
||||
} finally { a.notifications.localMessage = hook }
|
||||
assert.equal((await a.items()).length, count)
|
||||
assert.equal((await a.pool.query("SELECT id FROM collaboration_messages WHERE client_id=$1", [clientId])).rowCount, 0)
|
||||
})
|
||||
} finally {
|
||||
await a.app.close(); await b.app.close()
|
||||
await a.close(); await b.close()
|
||||
}
|
||||
})
|
||||
@@ -24,7 +24,7 @@ export async function collaborationDatabase(migrations: string[] = []) {
|
||||
const columns = Object.values(getTableColumns(table)).map((column: any) => {
|
||||
let suffix = column.primary ? " PRIMARY KEY" : ""
|
||||
if (column.name === "id" && column.getSQLType() === "uuid") suffix += " DEFAULT gen_random_uuid()"
|
||||
if (column.columnType === "PgTimestamp") suffix += " DEFAULT now()"
|
||||
if (column.columnType === "PgTimestamp" && column.hasDefault) suffix += " DEFAULT now()"
|
||||
if (column.getSQLType() === "boolean") suffix += ` DEFAULT ${column.default === true ? "true" : "false"}`
|
||||
return `"${column.name}" ${column.getSQLType()}${suffix}`
|
||||
})
|
||||
|
||||
48
backend/tests/incomingInvoiceCostCentres.test.ts
Normal file
48
backend/tests/incomingInvoiceCostCentres.test.ts
Normal file
@@ -0,0 +1,48 @@
|
||||
import assert from "node:assert/strict"
|
||||
import test from "node:test"
|
||||
import {
|
||||
applyAccountCostCentreAssignments,
|
||||
normalizeAccountCostCentreAssignments,
|
||||
} from "../src/modules/incoming-invoice-cost-centres.service"
|
||||
import { mcpToolMap } from "../src/mcp/registry"
|
||||
|
||||
const CENTRE = "8f1c2b3a-4d5e-4f60-8a7b-9c0d1e2f3a4b"
|
||||
|
||||
test("changes only requested account cost centres", () => {
|
||||
const accounts = [
|
||||
{ account: 1, amountNet: 100, taxType: "19", costCentre: "old-1" },
|
||||
{ account: 2, amountNet: 50, taxType: "7", costCentre: "old-2" },
|
||||
]
|
||||
|
||||
assert.deepEqual(applyAccountCostCentreAssignments(accounts, [
|
||||
{ index: 1, costcentre: CENTRE },
|
||||
]), [
|
||||
accounts[0],
|
||||
{ account: 2, amountNet: 50, taxType: "7", costCentre: CENTRE },
|
||||
])
|
||||
})
|
||||
|
||||
test("rejects assignments for unknown invoice positions", () => {
|
||||
assert.throws(
|
||||
() => applyAccountCostCentreAssignments([{ account: 1 }], [{ index: 3, costcentre: null }]),
|
||||
/Position 4.*nicht gefunden/,
|
||||
)
|
||||
})
|
||||
|
||||
test("validates cost centre assignments", () => {
|
||||
assert.throws(() => normalizeAccountCostCentreAssignments([]), /Mindestens eine/)
|
||||
assert.throws(() => normalizeAccountCostCentreAssignments([{ index: -1, costcentre: null }]), /gültigen index/)
|
||||
assert.throws(() => normalizeAccountCostCentreAssignments([{ index: 0, costcentre: "x" }]), /Ungültige Kostenstelle/)
|
||||
assert.throws(
|
||||
() => normalizeAccountCostCentreAssignments([{ index: 0, costcentre: null }, { index: 0, costcentre: CENTRE }]),
|
||||
/mehrfach/,
|
||||
)
|
||||
assert.deepEqual(normalizeAccountCostCentreAssignments([{ index: 0, costcentre: CENTRE }]), [{ index: 0, costcentre: CENTRE }])
|
||||
})
|
||||
|
||||
test("registers a dedicated incoming invoice cost centre tool", () => {
|
||||
const tool = mcpToolMap.get("accounting.incoming_invoices.cost_centres.update")
|
||||
|
||||
assert.deepEqual(tool?.requiredPermissions, ["accounting.incoming_invoices.write"])
|
||||
assert.deepEqual(tool?.inputSchema.required, ["id", "accountCostCentres"])
|
||||
})
|
||||
45
backend/tests/incomingInvoicePreparation.test.ts
Normal file
45
backend/tests/incomingInvoicePreparation.test.ts
Normal file
@@ -0,0 +1,45 @@
|
||||
import assert from "node:assert/strict"
|
||||
import test from "node:test"
|
||||
import { prepareIncomingInvoices } from "../src/modules/cron/prepareIncomingInvoices"
|
||||
|
||||
function server(tenantLookups: { count: number }) {
|
||||
let release: () => void = () => undefined
|
||||
const gate = new Promise<void>((resolve) => { release = resolve })
|
||||
const db: any = {
|
||||
select: () => ({
|
||||
from: () => ({
|
||||
where: () => ({
|
||||
orderBy: async () => {
|
||||
tenantLookups.count += 1
|
||||
await gate
|
||||
return []
|
||||
},
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
}
|
||||
const log = { error: () => undefined, info: () => undefined, warn: () => undefined }
|
||||
return { server: { db, log } as any, release: () => release() }
|
||||
}
|
||||
|
||||
test("start runs the preparation in the background and does not start a second run", async () => {
|
||||
const lookups = { count: 0 }
|
||||
const { server: srv, release } = server(lookups)
|
||||
const service = prepareIncomingInvoices(srv)
|
||||
|
||||
const first = service.start(7)
|
||||
const second = service.start(7)
|
||||
assert.equal(first.running, true)
|
||||
assert.equal(second.startedAt, first.startedAt)
|
||||
assert.equal(service.status(8).running, false)
|
||||
|
||||
release()
|
||||
await new Promise((resolve) => setImmediate(resolve))
|
||||
await new Promise((resolve) => setImmediate(resolve))
|
||||
|
||||
const status = service.status(7)
|
||||
assert.equal(lookups.count, 1)
|
||||
assert.equal(status.running, false)
|
||||
assert.ok(status.finishedAt)
|
||||
assert.equal(status.result?.error, "Mandant nicht gefunden")
|
||||
})
|
||||
99
backend/tests/mcpArchiveRestore.test.ts
Normal file
99
backend/tests/mcpArchiveRestore.test.ts
Normal file
@@ -0,0 +1,99 @@
|
||||
import assert from "node:assert/strict"
|
||||
import test from "node:test"
|
||||
import { getTableColumns, getTableName } from "drizzle-orm"
|
||||
import { PgDialect } from "drizzle-orm/pg-core"
|
||||
import * as schema from "../db/schema"
|
||||
import { mcpToolMap } from "../src/mcp/registry"
|
||||
import { archiveEntities, prepareArchiveRestoreInput } from "../src/mcp/tools/archive"
|
||||
import { asToolResult } from "../src/mcp/result"
|
||||
|
||||
const tenantId = 7
|
||||
const userId = "00000000-0000-4000-8000-000000000001"
|
||||
const uuid = "00000000-0000-4000-8000-000000000002"
|
||||
const dialect = new PgDialect()
|
||||
|
||||
/** Minimal Drizzle stand-in which evaluates equality predicates, including tenant filters. */
|
||||
function fixture(initial: Record<string, any[]> = {}, listRows: any[] = []) {
|
||||
const state = structuredClone(initial)
|
||||
const rowsFor = (table: any) => state[getTableName(table)] ||= []
|
||||
const matches = (table: any, where: any, row: any) => {
|
||||
const query = dialect.sqlToQuery(where)
|
||||
const columns = getTableColumns(table) as Record<string, any>
|
||||
const keyFor = (name: string) => Object.keys(columns).find((key) => columns[key].name === name)!
|
||||
return [...query.sql.matchAll(/"\w+"\."(\w+)" = \$(\d+)/g)]
|
||||
.every((match) => row[keyFor(match[1])] === query.params[Number(match[2]) - 1])
|
||||
}
|
||||
const listed: string[] = []
|
||||
const db: any = {
|
||||
transaction: async (callback: any) => callback(db),
|
||||
select: () => ({ from: (table: any) => {
|
||||
let condition: any
|
||||
const query: any = {
|
||||
where: (where: any) => { condition = where; return query },
|
||||
orderBy: () => query,
|
||||
offset: () => query,
|
||||
limit: () => query,
|
||||
for: () => query,
|
||||
then: (resolve: any, reject: any) => Promise.resolve().then(() => {
|
||||
if (listRows.length) { listed.push(dialect.sqlToQuery(condition).sql); return listRows }
|
||||
return rowsFor(table).filter((row) => matches(table, condition, row)).map((row) => ({ ...row }))
|
||||
}).then(resolve, reject),
|
||||
}
|
||||
return query
|
||||
} }),
|
||||
insert: (table: any) => ({ values: async (data: any) => { rowsFor(table).push(data) } }),
|
||||
update: (table: any) => ({ set: (data: any) => ({ where: (where: any) => ({
|
||||
returning: async () => rowsFor(table).filter((row) => matches(table, where, row)).map((row) => ({ ...Object.assign(row, data) })),
|
||||
}) }) }),
|
||||
}
|
||||
const context: any = { server: { db, log: { warn: () => undefined } }, tenantId, userId, isAdmin: true, permissions: [] }
|
||||
return { context, rows: rowsFor, listed }
|
||||
}
|
||||
const call = async (context: any, name: string, args: Record<string, any>) => await mcpToolMap.get(`archive.entities.${name}`)!.handler(context, args) as any
|
||||
|
||||
for (const [key, entity] of Object.entries(archiveEntities)) {
|
||||
test(`${key}: restore unarchives within the tenant and records history`, async () => {
|
||||
const id = entity.uuid ? uuid : 1
|
||||
const f = fixture({
|
||||
[getTableName(entity.table)]: [{ id, tenant: tenantId, archived: true }],
|
||||
// Restoring documents requires an internal (non-portal) profile.
|
||||
auth_profiles: [{ tenant_id: tenantId, user_id: userId, customer_for_portal: null }],
|
||||
})
|
||||
const result = await call(f.context, "restore", { entity: key, id })
|
||||
assert.deepEqual(asToolResult(result).structuredContent?.success, true)
|
||||
assert.equal(result.record.archived, undefined)
|
||||
const [row] = f.rows(entity.table)
|
||||
assert.equal(row.archived, false)
|
||||
assert.equal(row.updatedBy ?? row.updated_by, userId)
|
||||
await assert.rejects(call(f.context, "restore", { entity: key, id }), /nicht archiviert/)
|
||||
})
|
||||
}
|
||||
|
||||
test("restore rejects foreign tenants, unknown entities, invalid IDs and missing write permission", async () => {
|
||||
const f = fixture({ customers: [{ id: 1, tenant: 8, archived: true }], tasks: [{ id: 2, tenant: tenantId, archived: true }] })
|
||||
await assert.rejects(call(f.context, "restore", { entity: "customers", id: 1 }), /nicht gefunden/)
|
||||
assert.equal(f.rows(schema.customers)[0].archived, true)
|
||||
await assert.rejects(call(f.context, "restore", { entity: "accounts", id: 1 }), /unbekannte Entität/)
|
||||
assert.throws(() => prepareArchiveRestoreInput({ entity: "cost_centres", id: 1 }), /UUID/)
|
||||
assert.throws(() => prepareArchiveRestoreInput({ entity: "tasks", id: "abc" }), /ganze Zahl/)
|
||||
f.context.isAdmin = false
|
||||
f.context.permissions = ["organisation.tasks.read"]
|
||||
await assert.rejects(call(f.context, "restore", { entity: "tasks", id: 2 }), /Fehlende Berechtigung.*organisation\.tasks\.write/)
|
||||
f.context.permissions.push("organisation.tasks.write")
|
||||
await call(f.context, "restore", { entity: "tasks", id: 2 })
|
||||
assert.equal(f.rows(schema.tasks)[0].archived, false)
|
||||
})
|
||||
|
||||
test("list returns archived rows visibly and requires the read permission", async () => {
|
||||
const f = fixture({}, [{ id: 1, tenant: tenantId, archived: true, name: "Alt" }])
|
||||
const result = asToolResult(await call(f.context, "list", { entity: "customers", search: "Al" }))
|
||||
assert.deepEqual(result.structuredContent?.rows, [{ id: 1, tenant: tenantId, name: "Alt", isArchived: true }])
|
||||
assert.match(f.listed[0], /"customers"\."archived" = \$2/)
|
||||
f.context.isAdmin = false
|
||||
f.context.permissions = []
|
||||
await assert.rejects(call(f.context, "list", { entity: "customers" }), /masterdata\.customers\.read/)
|
||||
})
|
||||
|
||||
test("restore is advertised as a write tool", () => {
|
||||
assert.equal(mcpToolMap.get("archive.entities.restore")!.readOnly, false)
|
||||
})
|
||||
@@ -151,6 +151,7 @@ test("HTTP MCP accepts uploads above 1 MiB and streams authorized PDFs without e
|
||||
return { rows: [[id, 7, id, true, null, "test@example.invalid", admin]] }
|
||||
}
|
||||
if (sql.startsWith('update "m2m_api_keys"')) return { rows: [] }
|
||||
if (sql.includes('from "auth_users"')) return { rows: [[admin]] }
|
||||
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: [] }
|
||||
|
||||
106
backend/tests/mcpFileUploads.test.ts
Normal file
106
backend/tests/mcpFileUploads.test.ts
Normal file
@@ -0,0 +1,106 @@
|
||||
import assert from "node:assert/strict"
|
||||
import test from "node:test"
|
||||
import { createHash } from "node:crypto"
|
||||
import Fastify from "fastify"
|
||||
import { drizzle } from "drizzle-orm/pg-proxy"
|
||||
import mcpRoutes from "../src/routes/mcp"
|
||||
import authPlugin from "../src/plugins/auth"
|
||||
import { mcpToolMap } from "../src/mcp/registry"
|
||||
import { parseUploadQuery, storeMcpFileUpload } from "../src/mcp/fileUploads"
|
||||
import { MCP_FILE_LIMIT } from "../src/mcp/documentFiles"
|
||||
import { secrets } from "../src/utils/secrets"
|
||||
|
||||
const id = "00000000-0000-4000-8000-000000000001"
|
||||
const pdf = Buffer.from("%PDF-1.7\nMCP fixture\n%%EOF")
|
||||
const bearer = "fedeo_mcp_test_upload_token"
|
||||
const headers = { authorization: `Bearer ${bearer}` }
|
||||
|
||||
async function app(t: any) {
|
||||
const uploads: any[] = []
|
||||
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", true]] }
|
||||
}
|
||||
if (sql.startsWith('update "m2m_api_keys"')) return { rows: [] }
|
||||
if (sql.includes('from "auth_users"')) return { rows: [[true]] }
|
||||
if (sql.includes('from "tenants"')) return { rows: [[null, null]] }
|
||||
return { rows: [] }
|
||||
})
|
||||
const server = Fastify()
|
||||
t.after(() => server.close())
|
||||
server.decorate("db", db as any)
|
||||
await server.register(authPlugin)
|
||||
await server.register(mcpRoutes, {
|
||||
prefix: "/api",
|
||||
storeUpload: async (context: any, upload: any) => { uploads.push({ tenantId: context.tenantId, ...upload }); return { stored: true } },
|
||||
})
|
||||
return { server, uploads }
|
||||
}
|
||||
|
||||
const multipartBody = (filename: string, content: Buffer, field = "file") => {
|
||||
const boundary = "----fedeo-test"
|
||||
const payload = Buffer.concat([
|
||||
Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="${field}"; filename="${filename}"\r\nContent-Type: application/pdf\r\n\r\n`),
|
||||
content,
|
||||
Buffer.from(`\r\n--${boundary}--\r\n`),
|
||||
])
|
||||
return { payload, headers: { ...headers, "content-type": `multipart/form-data; boundary=${boundary}` } }
|
||||
}
|
||||
|
||||
test("binary endpoint accepts multipart and raw uploads without Base64", async (t) => {
|
||||
const { server, uploads } = await app(t)
|
||||
const multipart = multipartBody("rechnung.pdf", pdf)
|
||||
const first = await server.inject({ method: "POST", url: "/api/mcp/files?target=incoming_invoice&invoiceId=5&prepare=false", ...multipart })
|
||||
assert.equal(first.statusCode, 200, first.body)
|
||||
assert.deepEqual(first.json(), { stored: true })
|
||||
assert.equal(uploads[0].tenantId, 7)
|
||||
assert.equal(uploads[0].target, "incoming_invoice")
|
||||
assert.equal(uploads[0].filename, "rechnung.pdf")
|
||||
assert.equal(uploads[0].invoiceId, 5)
|
||||
assert.equal(uploads[0].prepare, false)
|
||||
assert.deepEqual(uploads[0].body, pdf)
|
||||
|
||||
const raw = await server.inject({ method: "POST", url: "/api/mcp/files?filename=scan.pdf", headers: { ...headers, "content-type": "application/pdf" }, payload: pdf })
|
||||
assert.equal(raw.statusCode, 200, raw.body)
|
||||
assert.equal(uploads[1].target, "inbox")
|
||||
assert.equal(uploads[1].mimeType, "application/pdf")
|
||||
assert.deepEqual(uploads[1].body, pdf)
|
||||
})
|
||||
|
||||
test("binary endpoint rejects missing auth, filenames, wrong fields, types and oversized files", async (t) => {
|
||||
const { server, uploads } = await app(t)
|
||||
const raw = { "content-type": "application/pdf" }
|
||||
assert.equal((await server.inject({ method: "POST", url: "/api/mcp/files?filename=a.pdf", headers: raw, payload: pdf })).statusCode, 401)
|
||||
assert.equal((await server.inject({ method: "POST", url: "/api/mcp/files", headers: { ...headers, ...raw }, payload: pdf })).statusCode, 400)
|
||||
assert.equal((await server.inject({ method: "POST", url: "/api/mcp/files?filename=a.pdf", ...multipartBody("a.pdf", pdf, "other") })).statusCode, 400)
|
||||
assert.equal((await server.inject({ method: "POST", url: "/api/mcp/files?filename=a.pdf", headers: { ...headers, "content-type": "text/html" }, payload: "<p>" })).statusCode, 415)
|
||||
assert.equal((await server.inject({ method: "POST", url: "/api/mcp/files?filename=a.pdf&target=wiki", headers: { ...headers, ...raw }, payload: pdf })).statusCode, 400)
|
||||
const tooLarge = Buffer.alloc(MCP_FILE_LIMIT + 1)
|
||||
assert.equal((await server.inject({ method: "POST", url: "/api/mcp/files?filename=a.pdf", headers: { ...headers, ...raw }, payload: tooLarge })).statusCode, 413)
|
||||
assert.equal((await server.inject({ method: "POST", url: "/api/mcp/files", ...multipartBody("a.pdf", tooLarge) })).statusCode, 413)
|
||||
assert.equal(uploads.length, 0)
|
||||
})
|
||||
|
||||
test("query parsing keeps invoice options to the incoming invoice target", () => {
|
||||
assert.deepEqual(parseUploadQuery({}), { target: "inbox", invoiceId: null, prepare: true, filename: null })
|
||||
assert.throws(() => parseUploadQuery({ invoiceId: "3" }), /nur für target=incoming_invoice/)
|
||||
assert.throws(() => parseUploadQuery({ target: "incoming_invoice", invoiceId: "x" }), /positive ganze Zahl/)
|
||||
assert.throws(() => parseUploadQuery({ target: "incoming_invoice", prepare: "ja" }), /true oder false/)
|
||||
})
|
||||
|
||||
test("stored uploads require the permission of the chosen target", async () => {
|
||||
const context: any = { server: { db: null }, tenantId: 7, userId: id, isAdmin: false, permissions: ["documents.read"] }
|
||||
await assert.rejects(storeMcpFileUpload(context, { target: "inbox", filename: "a.pdf", body: pdf }), /documents\.write/)
|
||||
await assert.rejects(storeMcpFileUpload(context, { target: "incoming_invoice", filename: "a.pdf", body: pdf }), /accounting\.incoming_invoices\.write/)
|
||||
await assert.rejects(storeMcpFileUpload(context, { target: "inbox", filename: "a.pdf", body: Buffer.alloc(0) }), /leer/)
|
||||
})
|
||||
|
||||
test("upload_url tool returns the absolute endpoint with examples", 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 result: any = await mcpToolMap.get("documents.files.upload_url")!.handler({} as any, {})
|
||||
assert.equal(result.url, "https://app.fedeo.test/backend/api/mcp/files")
|
||||
assert.match(result.examples[0], /-F "file=@rechnung\.pdf"/)
|
||||
})
|
||||
41
backend/tests/mcpIncomingInvoicePreparation.test.ts
Normal file
41
backend/tests/mcpIncomingInvoicePreparation.test.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
import assert from "node:assert/strict"
|
||||
import test from "node:test"
|
||||
import { mcpToolMap } from "../src/mcp/registry"
|
||||
|
||||
const fileA = "00000000-0000-4000-8000-00000000000a"
|
||||
const fileB = "00000000-0000-4000-8000-00000000000b"
|
||||
const tool = mcpToolMap.get("accounting.incoming_invoices.prepare")!
|
||||
|
||||
function context(result: any, invoices: any[] = []) {
|
||||
const calls: any[] = []
|
||||
const db: any = {
|
||||
select: () => ({ from: () => ({ where: async () => invoices }) }),
|
||||
}
|
||||
const services = { prepareIncomingInvoices: { run: async (tenantId: number, options: any) => { calls.push({ tenantId, options }); return result } } }
|
||||
return { calls, context: { server: { db, services }, tenantId: 7, userId: "user", isAdmin: true, permissions: [] } as any }
|
||||
}
|
||||
|
||||
test("prepare runs for the active tenant and returns created drafts with validation", async () => {
|
||||
const invoice = { id: 11, tenant: 7, state: "Entwurf", archived: false }
|
||||
const { calls, context: ctx } = context({ filesFound: 1, created: [{ fileId: fileA, invoiceId: 11, source: "gpt" }], skipped: [] }, [invoice])
|
||||
const result: any = await tool.handler(ctx, {})
|
||||
assert.deepEqual(calls, [{ tenantId: 7, options: { fileIds: undefined } }])
|
||||
assert.equal(result.created[0].invoice.id, 11)
|
||||
assert.ok(result.created[0].validation)
|
||||
assert.deepEqual(result.skipped, [])
|
||||
})
|
||||
|
||||
test("prepare limits to given files and reports files it could not handle", async () => {
|
||||
const { calls, context: ctx } = context({ filesFound: 1, created: [], skipped: [{ fileId: fileA, reason: "Keine Belegdaten erkannt" }] })
|
||||
const result: any = await tool.handler(ctx, { fileIds: [fileA, fileB.toUpperCase(), fileB] })
|
||||
assert.deepEqual(calls[0].options.fileIds, [fileA, fileB])
|
||||
assert.deepEqual(result.skipped.map((entry: any) => entry.fileId), [fileA, fileB])
|
||||
})
|
||||
|
||||
test("prepare validates input and surfaces tenant configuration errors", async () => {
|
||||
const { context: ctx } = context({ filesFound: 0, created: [], skipped: [], error: "Dateityp für Eingangsrechnungen fehlt" })
|
||||
await assert.rejects(tool.handler(ctx, { fileIds: [] }), /1 bis 50/)
|
||||
await assert.rejects(tool.handler(ctx, { fileIds: ["abc"] }), /UUID/)
|
||||
await assert.rejects(tool.handler(ctx, {}), /Dateityp für Eingangsrechnungen fehlt/)
|
||||
assert.deepEqual(tool.requiredPermissions, ["accounting.incoming_invoices.write"])
|
||||
})
|
||||
@@ -40,11 +40,12 @@ for (const tool of mcpTools.filter((tool) => (tool.inputSchema.properties as any
|
||||
return values
|
||||
}) }
|
||||
}, { schema })
|
||||
const context = { server: { db }, tenantId: 7, userId: "test" } as any
|
||||
const context = { server: { db }, tenantId: 7, userId: "test", isAdmin: true } as any
|
||||
const properties = 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, { ...((tool.inputSchema.properties as any).id ? { id: 1 } : {}), limit: 100, offset })
|
||||
const result: any = await tool.handler(context, { ...(properties.id ? { id: 1 } : {}), ...(properties.entity ? { entity: properties.entity.enum[0] } : {}), 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)
|
||||
|
||||
233
backend/tests/userArchive.test.ts
Normal file
233
backend/tests/userArchive.test.ts
Normal file
@@ -0,0 +1,233 @@
|
||||
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 { Pool } from "pg"
|
||||
import { createHash } from "node:crypto"
|
||||
import authRoutes from "../src/routes/auth/auth"
|
||||
import userRoutes from "../src/routes/auth/user"
|
||||
import authPlugin from "../src/plugins/auth"
|
||||
import m2mAuthPlugin from "../src/plugins/auth.m2m"
|
||||
import tenantRoutes from "../src/routes/tenant"
|
||||
import internalTenantRoutes from "../src/routes/internal/tenant"
|
||||
import profileRoutes from "../src/routes/profiles"
|
||||
import resourceRoutes from "../src/routes/resources/main"
|
||||
import { secrets } from "../src/utils/secrets"
|
||||
|
||||
const adminId = "00000000-0000-4000-8000-000000000001"
|
||||
const userId = "00000000-0000-4000-8000-000000000002"
|
||||
const profileId = "00000000-0000-4000-8000-000000000003"
|
||||
const otherProfileId = "00000000-0000-4000-8000-000000000004"
|
||||
const passwordHash = bcrypt.hashSync("archive-test-password", 4)
|
||||
type Row = Record<string, any>
|
||||
|
||||
// Execute the generated SQL against a small fixture, including its archive filters.
|
||||
// This keeps the HTTP/authentication tests independent of a configured production DB.
|
||||
function matches(where: string, params: any[], row: Row) {
|
||||
for (const match of where.matchAll(/(?:"\w+"\.)?"(\w+)" = \$(\d+)/g)) {
|
||||
if (String(row[match[1]]) !== String(params[Number(match[2]) - 1])) return false
|
||||
}
|
||||
for (const match of where.matchAll(/(?:"\w+"\.)?"(\w+)" is null/g)) {
|
||||
if (row[match[1]] != null) return false
|
||||
}
|
||||
for (const match of where.matchAll(/(?:"\w+"\.)?"(\w+)" in \(([^)]+)\)/g)) {
|
||||
const values = [...match[2].matchAll(/\$(\d+)/g)].map(value => params[Number(value[1]) - 1])
|
||||
if (!values.includes(row[match[1]])) return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
function selected(columns: string, row: Row) {
|
||||
return columns.split(", ").map(column => {
|
||||
const name = [...column.matchAll(/"([^"]+)"/g)].at(-1)?.[1]
|
||||
return row[name!] ?? null
|
||||
})
|
||||
}
|
||||
|
||||
async function fixture(t: any) {
|
||||
const data: Record<string, Row[]> = {
|
||||
auth_users: [
|
||||
{ id: adminId, email: "admin@example.test", is_admin: true, archived_at: null },
|
||||
{ id: userId, email: "former@example.test", password_hash: passwordHash, is_admin: false, archived_at: null },
|
||||
],
|
||||
auth_profiles: [
|
||||
{ id: profileId, user_id: userId, tenant_id: 7, active: true, archived_at: null, first_name: "Former", last_name: "User", full_name: "Former User", token_id: "rfid", calendar_subscription_token: "calendar" },
|
||||
{ id: otherProfileId, user_id: userId, tenant_id: 8, active: false, archived_at: null },
|
||||
{ id: adminId, user_id: adminId, tenant_id: 7, active: true, archived_at: null },
|
||||
],
|
||||
auth_tenant_users: [{ tenant_id: 7, user_id: userId }, { tenant_id: 8, user_id: userId }, { tenant_id: 7, user_id: adminId }],
|
||||
auth_refresh_tokens: [{ id: userId, user_id: userId, tenant_id: 7, token_hash: "old", revoked_at: null }],
|
||||
m2m_api_keys: [{ id: userId, user_id: userId, tenant_id: 7, active: true, key_hash: createHash("sha256").update("fedeo_mcp_archive_test").digest("hex") }],
|
||||
tenants: [{ id: 7, name: "First" }, { id: 8, name: "Second" }],
|
||||
}
|
||||
const queries: string[] = []
|
||||
let inTransaction = false
|
||||
const db = drizzle(async (sql, params) => {
|
||||
queries.push(sql)
|
||||
if (sql.startsWith("select ")) {
|
||||
const table = sql.match(/from "([^"]+)"/)![1]
|
||||
const source = table === "m2m_api_keys"
|
||||
? data[table].map(row => ({ ...row, ...data.auth_users.find(user => user.id === row.user_id) }))
|
||||
: data[table] || []
|
||||
const rows = source.filter(row => matches(sql.split(" where ")[1] || "", params, row))
|
||||
if (sql.startsWith("select count(")) return { rows: [[rows.length]] }
|
||||
return { rows: rows.map(row => selected(sql.slice(7, sql.indexOf(" from ")), row)) }
|
||||
}
|
||||
if (sql.startsWith("update ")) {
|
||||
const table = sql.match(/update "([^"]+)"/)![1]
|
||||
const rows = (data[table] || []).filter(row => matches(sql.split(" where ")[1] || "", params, row))
|
||||
if (sql.includes('"archived_at" =')) assert.ok(inTransaction, "Archiving must be atomic")
|
||||
const assignments = sql.slice(sql.indexOf(" set "), sql.indexOf(" where "))
|
||||
for (const row of rows) {
|
||||
for (const match of assignments.matchAll(/"(\w+)" = \$(\d+)/g)) row[match[1]] = params[Number(match[2]) - 1]
|
||||
}
|
||||
return { rows: sql.includes(" returning ") ? rows.map(row => selected(sql.split(" returning ")[1], row)) : [] }
|
||||
}
|
||||
throw new Error(`Unexpected mutation: ${sql}`)
|
||||
})
|
||||
;(db as any).transaction = async (fn: any) => {
|
||||
inTransaction = true
|
||||
try { return await fn(db) } finally { inTransaction = false }
|
||||
}
|
||||
const app = Fastify()
|
||||
app.decorate("db", db as any)
|
||||
app.addHook("preHandler", async (req: any) => {
|
||||
req.user = { user_id: req.headers["x-test-user"] || adminId, tenant_id: 7 }
|
||||
req.queryConfig = { pagination: { limit: 100, offset: 0 }, filters: {}, sort: [] }
|
||||
})
|
||||
// adminRoutes imports the export utility, whose legacy DB module probes on import.
|
||||
const queryMock = t.mock.method(Pool.prototype, "query", async () => ({ rows: [{ now: "test" }] }))
|
||||
const { default: adminRoutes } = await import("../src/routes/admin")
|
||||
queryMock.mock.restore()
|
||||
await app.register(adminRoutes)
|
||||
await app.register(tenantRoutes)
|
||||
await app.register(profileRoutes)
|
||||
await app.register(userRoutes)
|
||||
await app.register(resourceRoutes)
|
||||
await app.register(internalTenantRoutes, { prefix: "/internal" })
|
||||
t.after(() => app.close())
|
||||
const archive = (id = userId, caller = adminId) => app.inject({ method: "POST", url: `/admin/users/${id}/archive`, headers: { "x-test-user": caller } })
|
||||
return { app, db, data, queries, archive }
|
||||
}
|
||||
|
||||
test("archiving preserves history, archives every tenant profile and revokes credentials atomically", async t => {
|
||||
const f = await fixture(t)
|
||||
const memberships = structuredClone(f.data.auth_tenant_users)
|
||||
const response = await f.archive()
|
||||
assert.equal(response.statusCode, 200, response.body)
|
||||
const archivedAt = response.json().user.archived_at
|
||||
assert.ok(archivedAt)
|
||||
for (const profile of f.data.auth_profiles.filter(profile => profile.user_id === userId)) {
|
||||
assert.equal(profile.active, false)
|
||||
assert.equal(profile.archived_at, archivedAt)
|
||||
assert.equal(profile.token_id, null)
|
||||
assert.equal(profile.calendar_subscription_token, null)
|
||||
}
|
||||
assert.equal(f.data.auth_profiles[2].active, true)
|
||||
assert.equal(f.data.auth_users[0].archived_at, null)
|
||||
assert.equal(f.data.auth_refresh_tokens[0].revoked_at, archivedAt)
|
||||
assert.equal(f.data.m2m_api_keys[0].active, false)
|
||||
assert.deepEqual(f.data.auth_tenant_users, memberships)
|
||||
assert.equal((await f.archive()).json().user.archived_at, archivedAt)
|
||||
assert.ok(f.queries.some(sql => sql.endsWith("for update")))
|
||||
})
|
||||
|
||||
test("only an active system admin can archive another existing user", async t => {
|
||||
const f = await fixture(t)
|
||||
assert.equal((await f.archive(adminId, userId)).statusCode, 403)
|
||||
assert.equal((await f.archive(adminId)).statusCode, 409)
|
||||
assert.equal((await f.archive(profileId)).statusCode, 404)
|
||||
assert.equal((await f.archive("invalid-id")).statusCode, 400)
|
||||
f.data.auth_users[0].archived_at = new Date().toISOString()
|
||||
assert.equal((await f.archive()).statusCode, 403)
|
||||
assert.equal(f.data.auth_users[1].archived_at, null)
|
||||
})
|
||||
|
||||
test("archived users disappear from active administration and tenant lists but retain a readable archive", async t => {
|
||||
const f = await fixture(t)
|
||||
await f.archive()
|
||||
const overview = (await f.app.inject("/admin/overview")).json()
|
||||
assert.deepEqual(overview.users.map((row: Row) => row.id), [adminId])
|
||||
assert.equal(overview.tenants.find((row: Row) => row.id === 7).user_count, 1)
|
||||
const archived = (await f.app.inject("/admin/overview?includeArchived=true")).json().users.find((row: Row) => row.id === userId)
|
||||
assert.ok(archived.archived_at)
|
||||
assert.equal(archived.profiles.length, 2)
|
||||
for (const url of ["/tenant/users", "/internal/tenant/users"]) {
|
||||
const response = await f.app.inject(url)
|
||||
assert.equal(response.statusCode, 200, response.body)
|
||||
assert.deepEqual(response.json().users.map((row: Row) => row.id), [adminId])
|
||||
}
|
||||
for (const url of ["/tenant/profiles", "/internal/tenant/7/profiles", "/resource/profiles", "/resource/authProfile", "/resource/profiles/paginated"]) {
|
||||
const response = await f.app.inject(url)
|
||||
assert.equal(response.statusCode, 200, response.body)
|
||||
const body = response.json()
|
||||
assert.deepEqual((body.data || body).map((row: Row) => row.id), [adminId], url)
|
||||
}
|
||||
const historic = (await f.app.inject("/tenant/profiles?includeArchived=true")).json().data
|
||||
assert.equal(historic.find((row: Row) => row.id === profileId).full_name, "Former User")
|
||||
const detail = await f.app.inject(`/resource/profiles/${profileId}`)
|
||||
assert.equal(detail.statusCode, 200, detail.body)
|
||||
assert.equal(detail.json().full_name, "Former User")
|
||||
})
|
||||
|
||||
test("archived accounts and profiles cannot be edited, reassigned or reactivated", async t => {
|
||||
const f = await fixture(t)
|
||||
await f.archive()
|
||||
for (const [method, url, payload, status] of [
|
||||
["PUT", `/admin/users/${userId}`, { archived_at: null, is_admin: true }, 409],
|
||||
["PUT", `/admin/users/${userId}/access`, { tenant_ids: [9] }, 409],
|
||||
["POST", `/admin/users/${userId}/reset-password`, {}, 409],
|
||||
["POST", "/admin/add-user-to-tenant", { user_id: userId, tenant_id: 9 }, 404],
|
||||
["PUT", `/user/${userId}/profile`, { data: { active: true, archived_at: null, user_id: adminId } }, 404],
|
||||
["PUT", `/profiles/${profileId}`, { active: true, archived_at: null }, 404],
|
||||
["PUT", `/resource/profiles/${profileId}`, { active: true, archived_at: null, user_id: adminId }, 409],
|
||||
["POST", `/profiles/${profileId}/calendar-subscription-token`, {}, 404],
|
||||
["POST", "/resource/profiles", { user_id: userId, first_name: "New", last_name: "Profile" }, 409],
|
||||
] as const) {
|
||||
const response = await f.app.inject({ method, url, payload })
|
||||
assert.equal(response.statusCode, status, `${url}: ${response.body}`)
|
||||
}
|
||||
assert.equal(f.data.auth_profiles[0].active, false)
|
||||
assert.equal(f.data.auth_profiles[0].user_id, userId)
|
||||
})
|
||||
|
||||
test("archiving blocks password login, refresh, existing JWTs and legacy API keys", async t => {
|
||||
const f = await fixture(t)
|
||||
const oldSecret = secrets.JWT_SECRET, oldM2mKey = secrets.M2M_API_KEY
|
||||
secrets.JWT_SECRET = "archive-test-secret"
|
||||
secrets.M2M_API_KEY = "archive-test-legacy-key"
|
||||
t.after(() => { secrets.JWT_SECRET = oldSecret; secrets.M2M_API_KEY = oldM2mKey })
|
||||
const app = Fastify()
|
||||
app.decorate("db", f.db as any)
|
||||
await app.register(cookie)
|
||||
await app.register(authRoutes)
|
||||
await app.register(async protectedApp => {
|
||||
await protectedApp.register(authPlugin)
|
||||
protectedApp.get("/check", async () => ({ success: true }))
|
||||
protectedApp.get("/mcp", async () => ({ success: true }))
|
||||
}, { prefix: "/api" })
|
||||
await app.register(async internal => {
|
||||
await internal.register(m2mAuthPlugin)
|
||||
internal.get("/check", async () => ({ success: true }))
|
||||
}, { prefix: "/internal" })
|
||||
t.after(() => app.close())
|
||||
const token = jwt.sign({ user_id: userId, tenant_id: null, is_admin: true }, secrets.JWT_SECRET)
|
||||
const headers = { authorization: `Bearer ${token}` }
|
||||
assert.equal((await app.inject({ url: "/api/check", headers })).statusCode, 200)
|
||||
await f.archive()
|
||||
assert.equal((await app.inject({ url: "/api/check", headers })).statusCode, 401)
|
||||
assert.equal((await app.inject({ method: "POST", url: "/auth/login", payload: { email: "former@example.test", password: "archive-test-password" } })).statusCode, 401)
|
||||
assert.equal((await app.inject({ method: "POST", url: "/auth/password/reset", payload: { email: "former@example.test" } })).statusCode, 404)
|
||||
// Even a session issued concurrently with archiving must fail the current-user check.
|
||||
f.data.auth_refresh_tokens[0].revoked_at = null
|
||||
const { hashRefreshToken } = await import("../src/utils/authTokens")
|
||||
f.data.auth_refresh_tokens[0].token_hash = hashRefreshToken("old-refresh-token")
|
||||
assert.equal((await app.inject({ method: "POST", url: "/auth/refresh", payload: { refreshToken: "old-refresh-token" } })).statusCode, 401)
|
||||
f.data.m2m_api_keys[0].active = true
|
||||
assert.equal((await app.inject({ url: "/api/mcp", headers: { authorization: "Bearer fedeo_mcp_archive_test" } })).statusCode, 401)
|
||||
assert.equal((await app.inject({ url: "/internal/check", headers: { "x-api-key": "fedeo_mcp_archive_test" } })).statusCode, 401)
|
||||
assert.equal((await app.inject({ url: "/internal/check", headers: { "x-api-key": secrets.M2M_API_KEY, "x-user-id": userId, "x-tenant-id": "7" } })).statusCode, 401)
|
||||
})
|
||||
@@ -328,18 +328,21 @@ Datenbank und `ENCRYPTION_KEY` gemeinsam sichern; der private Instanzschlüssel
|
||||
|
||||
### Prüfung und verbleibender Ausbau
|
||||
|
||||
Geprüft wurden 21 Tests ohne Überspringen auf einer isolierten PostgreSQL-17-Testdatenbank. Darunter sind die Absicherung bestehender Chatgrenzen, die Trennung von Gast- und regulären Sitzungen, benachbarte Unterräume, der Historienbeginn, abgelaufene und widerrufene Einladungen sowie zwei unabhängige Instanzdatenbanken mit echten Fastify-Routen und Signaturprüfung. Der Transport zwischen diesen Instanzen ist im Test simuliert: Verbindungsfehler, verlorene Bestätigungen, doppelte Zustellung, veraltete Teilnahmeversionen, verspätete Widerrufe und erneute Einladungen werden gezielt erzeugt. HTTPS/DNS-Einschränkungen und Signaturmanipulationen besitzen zusätzliche Tests. Eine Verbindung zwischen zwei produktiven HTTPS-Installationen wurde nicht ausgeführt.
|
||||
Geprüft wurden 50 Tests ohne Überspringen auf einer isolierten PostgreSQL-17-Testdatenbank. Darunter sind die Absicherung bestehender Chatgrenzen, die Trennung von Gast- und regulären Sitzungen, benachbarte Unterräume, der Historienbeginn, abgelaufene und widerrufene Einladungen sowie zwei unabhängige Instanzdatenbanken mit echten Fastify-Routen und Signaturprüfung. Die Benachrichtigungstests prüfen zusätzlich Empfängermandanten, persönliche Kanalwahl, Lesestatus, wiederholte Synchronisation, konkurrierende Worker, Neustarts und gemeinsame Transaktions-Rollbacks. Der Transport zwischen diesen Instanzen und die externe Benachrichtigungszustellung sind im Test simuliert: Verbindungsfehler, verlorene Bestätigungen, doppelte Zustellung, veraltete Teilnahmeversionen, verspätete Widerrufe und erneute Einladungen werden gezielt erzeugt. HTTPS/DNS-Einschränkungen und Signaturmanipulationen besitzen zusätzliche Tests. Eine Verbindung zwischen zwei produktiven HTTPS-Installationen wurde nicht ausgeführt.
|
||||
|
||||
Reproduzierbar aus `backend/` mit einer ausdrücklich bereitgestellten, entbehrlichen Datenbank namens `collaboration_test`:
|
||||
|
||||
```sh
|
||||
COLLABORATION_TEST_DATABASE_URL=postgresql://USER:PASSWORD@127.0.0.1:PORT/collaboration_test \
|
||||
node --import tsx --test tests/communicationAccess.test.ts tests/collaboration.test.ts \
|
||||
tests/collaborationRoutes.test.ts tests/collaborationFederation.test.ts tests/chatContent.test.ts
|
||||
tests/collaborationRoutes.test.ts tests/collaborationFederation.test.ts tests/chatContent.test.ts \
|
||||
tests/collaborationNotifications.test.ts tests/notificationPreferences.test.ts
|
||||
```
|
||||
|
||||
Jeder Datenbanktest erzeugt ein eigenes Schema und räumt es anschließend auf. Ohne gesetzte Testadresse werden die Datenbanktests bewusst übersprungen; der Datenbankname wird vor dem Anlegen geprüft. Backend-Typprüfung und Nuxt-Produktionsbuild waren erfolgreich, die abschließenden Vue-Komponenten lassen sich kompilieren. Die spätere Erweiterung um Emojis, Bilder und Reaktionen wurde zusätzlich mit einer lokalen Browser-Vorschau der tatsächlichen Vue-Komponenten und simulierten API-Antworten geprüft. Die automatisierten Medientests prüfen unter anderem Bildvalidierung, Bildnachrichten ohne Text, Reaktionszähler, Historiengrenzen, Gastrechte, deaktivierte Projektchats und signierte Zustellung zwischen zwei Instanzen.
|
||||
|
||||
Die nächste Ausbaustufe aus Schritt 3 umfasst insbesondere native Mobile-Parität, Push-Benachrichtigungen, Moderation, feinere Kontingente sowie Schlüsselrotation und abgestimmte Wiederherstellung. Dateifreigaben, Aufgabenfreigaben und E2EE sind weiterhin Erweiterungen. Der hier implementierte Stand ist ein nutzbarer Web-Pilot für Chats und ausdrücklich begrenzte Projektzusammenarbeit; ein produktiver Rollout ist damit noch nicht erfolgt.
|
||||
Nachrichten und persönliche Einladungen aus der Zusammenarbeit unterstützen jetzt In-App-, E-Mail- und Push-Benachrichtigungen. Die Einstellungen gelten im Heimatmandanten des Empfängers. Die Migration `0083_collaboration_notifications.sql` muss dafür eingespielt sein. Der Versand erfolgt nach dem Speichern über den Hintergrundworker und prüft die aktuellen Zugriffsrechte; wiederholte Synchronisationen erzeugen keine doppelten Benachrichtigungen. Details und Standardwerte stehen in [Persönliche Benachrichtigungen](notification-preferences.md). Die Zustellung auf realen Endgeräten hängt weiterhin von der jeweiligen Push-Konfiguration ab.
|
||||
|
||||
Die nächste Ausbaustufe aus Schritt 3 umfasst insbesondere native Mobile-Parität, Moderation, feinere Kontingente sowie Schlüsselrotation und abgestimmte Wiederherstellung. Dateifreigaben, Aufgabenfreigaben und E2EE sind weiterhin Erweiterungen. Der hier implementierte Stand ist ein nutzbarer Web-Pilot für Chats und ausdrücklich begrenzte Projektzusammenarbeit; ein produktiver Rollout ist damit noch nicht erfolgt.
|
||||
|
||||
Die automatische Einrichtung wurde zusätzlich mit sechs Konfigurationstests und 58 Updater-Tests geprüft. Die Update-Regressionen verwenden echte Compose-Auswertung mit simuliertem Containerbetrieb und prüfen sowohl Installationen ohne Föderationsvariablen als auch den Erhalt einer ausdrücklichen Abschaltung und eigener URL-Vorgaben.
|
||||
|
||||
309
docs/fahrtenbuch-konzept.md
Normal file
309
docs/fahrtenbuch-konzept.md
Normal file
@@ -0,0 +1,309 @@
|
||||
# Konzept: Fahrtenbuch mit direkter Teltonika-Anbindung
|
||||
|
||||
## Zielbild
|
||||
|
||||
Die Teltonika-OBD-II-Tracker senden ihre AVL-Daten direkt an FEDEO. Traccar entfällt vollständig aus der produktiven Kette.
|
||||
|
||||
```text
|
||||
Teltonika-Tracker
|
||||
│ TCP/TLS, Codec 8 Extended
|
||||
▼
|
||||
FEDEO Tracking-Ingest
|
||||
│ atomare Speicherung, danach ACK
|
||||
▼
|
||||
PostgreSQL ──► Fahrtbildungs-Worker ──► Fahrtenbuch-API ──► Nuxt-Oberfläche/PDF-Export
|
||||
```
|
||||
|
||||
Die empfohlene Lösung besteht aus einem kleinen, eigenständigen Dienst `tracking-server`, den bestehenden FEDEO-Diensten und PostgreSQL. Der Empfangsdienst darf nicht Teil des HTTP-Prozesses sein: Teltonika verwendet langlebige TCP-Verbindungen und ein Binärprotokoll, während das bestehende Backend Fastify/HTTP bedient. Die getrennten Prozesse können unabhängig neu gestartet und skaliert werden.
|
||||
|
||||
Ein zusätzlicher Message-Broker ist für die derzeit erkennbare Größenordnung nicht nötig. Der Tracker puffert Daten bei Verbindungsproblemen; PostgreSQL übernimmt die dauerhafte Übergabe an den Fahrtbildungs-Worker.
|
||||
|
||||
## Annahmen und noch zu bestätigende Angaben
|
||||
|
||||
- Mit „Teltonika OBD2“ ist voraussichtlich ein Gerät der FMx003-Familie gemeint, zum Beispiel FMB003, FMC003 oder FMM003. Vor der Implementierung müssen exaktes Modell, Firmwarestand und Mobilfunkvariante feststehen.
|
||||
- Die Geräte werden auf **Codec 8 Extended über TCP/TLS** eingestellt. Teltonika empfiehlt Codec 8 Extended, weil nur damit auch AVL-IDs oberhalb von 255 und variable I/O-Werte vollständig übertragen werden können.
|
||||
- Das Fahrtenbuch soll nicht nur eine Streckenübersicht, sondern bei Bedarf ein steuerlich nutzbares elektronisches Fahrtenbuch für Deutschland sein.
|
||||
- Ein OBD-Tracker erkennt das Fahrzeug, aber nicht automatisch die fahrende Person. Ohne zusätzlichen BLE-/iButton-Fahrerschlüssel wird der im Fahrzeug hinterlegte Standardfahrer vorgeschlagen und muss gegebenenfalls geändert werden.
|
||||
|
||||
## 1. Tracking-Ingest
|
||||
|
||||
### Aufgabe
|
||||
|
||||
Ein neues Paket beziehungsweise ein neuer Dienst `tracking-server/` wird in TypeScript implementiert. Er verwendet `node:tls` beziehungsweise während der lokalen Entwicklung `node:net` und übernimmt ausschließlich:
|
||||
|
||||
1. TCP-Verbindung und IMEI-Handshake,
|
||||
2. Prüfung, ob die IMEI einem aktiven FEDEO-Fahrzeug zugeordnet ist,
|
||||
3. Framing und Parsen von Codec 8 (`0x08`) und Codec 8 Extended (`0x8E`),
|
||||
4. Prüfung von Paketlänge, doppelter Datensatzanzahl und CRC-16/IBM,
|
||||
5. normalisierte Speicherung aller AVL-Datensätze in einer Datenbanktransaktion,
|
||||
6. Teltonika-ACK erst nach erfolgreichem Commit,
|
||||
7. Aktualisierung von `last_seen_at` und einfachen Betriebsmetriken.
|
||||
|
||||
Der produktive Gerätevertrag ist Codec 8 Extended. Codec 8 sollte der Parser trotzdem beherrschen, damit ein falsch oder noch nicht umkonfiguriertes Gerät sichtbar diagnostiziert werden kann.
|
||||
|
||||
Bei Datenbankfehlern wird **kein** positiver ACK gesendet. Das Gerät behält die Datensätze und versucht die Übertragung erneut. Doppelte Zustellungen müssen durch einen fachlichen Idempotenzschlüssel wirkungslos bleiben. Unbekannte IMEIs werden abgewiesen und nur als begrenztes Sicherheitsereignis protokolliert.
|
||||
|
||||
### Parser-Grenzen
|
||||
|
||||
Der Binärparser darf nicht mit Fachlogik vermischt werden. Sein Ergebnis ist ein neutrales Objekt:
|
||||
|
||||
```ts
|
||||
type AvlRecord = {
|
||||
recordedAt: Date
|
||||
priority: number
|
||||
longitude: number
|
||||
latitude: number
|
||||
altitude: number
|
||||
angle: number
|
||||
satellites: number
|
||||
speedKmh: number
|
||||
eventIoId: number
|
||||
io: Record<number, bigint | Buffer>
|
||||
}
|
||||
```
|
||||
|
||||
Für die Fachlogik gibt es danach ein modell- und firmwareabhängiges I/O-Mapping. Relevante Standardwerte sind typischerweise:
|
||||
|
||||
- AVL 239: Zündung,
|
||||
- AVL 240: Bewegung,
|
||||
- AVL 16: Teltonika-Gesamtkilometerzähler,
|
||||
- AVL 389: OEM-Gesamtkilometerstand,
|
||||
- AVL 256: VIN,
|
||||
- AVL 134: Fahrtdistanz.
|
||||
|
||||
Einheiten und Verfügbarkeit werden nicht im Parser fest verdrahtet, sondern über getestete Definitionen je Gerätefamilie normalisiert. Insbesondere der OEM-Kilometerstand ist vom unterstützten Fahrzeug und der auf das Gerät geladenen OBD-Konfiguration abhängig.
|
||||
|
||||
### Sicherheit und Betrieb
|
||||
|
||||
- Eigener TCP-Port, zum Beispiel `5027`, mit TLS 1.2; die konkrete TLS-Unterstützung muss für Modell und Firmware geprüft werden.
|
||||
- IMEI-Zulassungsliste aus der Datenbank, Rate-Limit pro Quell-IP und harte Grenzen für Paketgröße und Verbindungsdauer.
|
||||
- Keine Befehlssteuerung in Version 1. Codec 12/14 kann später getrennt ergänzt werden.
|
||||
- Metriken: aktive Verbindungen, akzeptierte/abgelehnte Pakete, CRC-Fehler, unbekannte IMEIs, Verzögerung `received_at - recorded_at`, letzter Datensatz je Tracker und offene Fahrten.
|
||||
- Alarm, wenn ein aktiver Tracker länger als eine konfigurierbare Zeit keine Daten liefert.
|
||||
|
||||
## 2. Datenmodell
|
||||
|
||||
Die vorhandene Tabelle `vehicles` bleibt die fachliche Fahrzeugquelle. Die generische Tabelle `devices` sollte nicht mit GPS-Sonderfeldern überladen werden.
|
||||
|
||||
### `vehicle_trackers`
|
||||
|
||||
Zuordnung und Gerätekonfiguration:
|
||||
|
||||
- `id uuid`, `tenant bigint`, `vehicle bigint`
|
||||
- `imei text unique`, `model text`, `firmware text`
|
||||
- `protocol text`, `enabled boolean`
|
||||
- `installed_at`, `removed_at`, `last_seen_at`
|
||||
- `io_profile_version text`
|
||||
- eindeutige aktive Zuordnung eines Trackers zu einem Fahrzeug
|
||||
|
||||
Eine zeitliche Zuordnung ist wichtig: Beim Umbau eines Trackers dürfen alte Positionen nicht nachträglich dem neuen Fahrzeug zugerechnet werden.
|
||||
|
||||
### `tracking_packets`
|
||||
|
||||
Technische Nachvollziehbarkeit und gezielte Fehleranalyse:
|
||||
|
||||
- Tracker, Empfangszeit, Codec, CRC, Datensatzanzahl
|
||||
- SHA-256 des vollständigen Frames als Idempotenzschlüssel
|
||||
- optionaler Rohframe als `bytea` mit kurzer, konfigurierbarer Aufbewahrung, zum Beispiel 30 oder 90 Tage
|
||||
- Parse-Status und Fehlercode
|
||||
|
||||
### `tracking_positions`
|
||||
|
||||
Unveränderliche normalisierte Messpunkte:
|
||||
|
||||
- Mandant, Tracker und die zum Messzeitpunkt gültige Fahrzeugzuordnung
|
||||
- Gerätezeit `recorded_at` und Serverzeit `received_at`
|
||||
- Koordinaten, Höhe, Richtung, Geschwindigkeit, Satelliten, Priorität
|
||||
- normalisierte Werte `ignition`, `movement`, `odometer_m`, `oem_odometer_m`
|
||||
- `event_io_id` und vollständige I/O-Werte als `jsonb`
|
||||
- Qualitätsmerkmale wie `valid_gnss`, Zeitabweichung und Kilometerstandsquelle
|
||||
|
||||
Eindeutigkeit entsteht aus Tracker, Gerätezeit und einem stabilen Datensatz-Fingerabdruck. Für größere Datenmengen kann die Tabelle später monatsweise nach `recorded_at` partitioniert werden. Indizes werden mindestens auf `(vehicle, recorded_at)` und `(tracker, recorded_at)` benötigt.
|
||||
|
||||
### `tracking_trips`
|
||||
|
||||
Das fachliche Fahrtenbuch:
|
||||
|
||||
- Fahrzeug, Fahrer, Start/Ende und Start-/Zielkoordinaten
|
||||
- Start-/Zieladresse als zum Abschlusszeitpunkt gespeicherter Text
|
||||
- Kilometerstand Beginn/Ende, berechnete Distanz und jeweilige Quelle
|
||||
- Klassifizierung `betrieblich`, `privat` oder `wohnung_erste_taetigkeitsstaette`
|
||||
- Reisezweck, Kunde/Geschäftspartner sowie optionale FEDEO-Verknüpfungen zu Kunde, Projekt und Termin
|
||||
- Status `offen`, `zu_pruefen`, `bestaetigt`, `gesperrt`
|
||||
- Qualitätsstatus mit konkreten Hinweisen, zum Beispiel fehlender OEM-Kilometerstand, GPS-Lücke oder unplausibler Sprung
|
||||
- Referenzen auf ersten und letzten Messpunkt
|
||||
|
||||
### `tracking_trip_revisions` und `tracking_logbook_exports`
|
||||
|
||||
Fahrten werden nie unbemerkt überschrieben. Jede Änderung erzeugt eine unveränderliche Revision mit altem und neuem Wert, Benutzer, Zeit, Änderungsgrund sowie einer Hash-Verkettung zur vorherigen Revision. Auch Zusammenführen, Teilen und Löschen sind fachliche Revisionen; ein physisches Löschen bestätigter Fahrten ist nicht erlaubt.
|
||||
|
||||
Ein abgeschlossener Monats- oder Jahresexport speichert PDF, maschinenlesbare CSV/JSON-Daten und ein Manifest mit SHA-256-Prüfsummen. Der Export enthält die Änderungshistorie in gewöhnlich einsehbarer Form. „Gesperrt“ bedeutet: weitere Korrekturen erzeugen eine sichtbare Folgerevision und gegebenenfalls eine neue Exportversion.
|
||||
|
||||
## 3. Fahrtbildung
|
||||
|
||||
Die Fahrtbildung läuft als wiederholbarer Worker auf Ereigniszeit, nicht auf Empfangszeit. Das ist wichtig, weil Tracker bei Funklöchern ältere Datensätze nachliefern.
|
||||
|
||||
### Zustandsautomat je Tracker
|
||||
|
||||
```text
|
||||
STEHT
|
||||
└─ Zündung an + Bewegung/Geschwindigkeit ─► FÄHRT
|
||||
|
||||
FÄHRT
|
||||
├─ weitere Punkte ────────────────────────► FÄHRT
|
||||
└─ Zündung aus + Nachlaufzeit ────────────► STEHT + Fahrt abschließen
|
||||
```
|
||||
|
||||
- Primäres Start-/Endesignal ist AVL 239 (Zündung), plausibilisiert mit Bewegung und Geschwindigkeit.
|
||||
- Eine konfigurierbare Nachlaufzeit von zunächst 120 Sekunden verhindert Fahrtteilungen an Ampeln oder bei kurzen Signalwechseln.
|
||||
- Eine Fahrt wird nicht sofort endgültig: Ein Watermark, zum Beispiel zehn Minuten nach dem letzten bekannten Gerätezeitpunkt, erlaubt verspätete Datensätze. Betroffene offene Zeitfenster werden deterministisch neu berechnet.
|
||||
- Bei fehlendem Zündungssignal greift ein klar markierter Fallback aus Bewegung, Geschwindigkeit und Stillstandszeit.
|
||||
- Kilometerstandsquelle in absteigender Qualität: OEM-Gesamtkilometerstand (AVL 389), kalibrierter Teltonika-Gesamtkilometerzähler (AVL 16), Fahrtdistanz/Positionssumme. FEDEO speichert Quelle und Abweichung, statt Werte still zu vermischen.
|
||||
- Unplausible GNSS-Punkte werden nicht für die Distanz verwendet, bleiben aber unverändert gespeichert.
|
||||
- Zeitrücksprünge, Kilometerzählersprünge, GPS-Lücken und Tracker-Ausbau erzeugen Prüffälle und niemals stillschweigend „saubere“ Fahrten.
|
||||
|
||||
Die Zählerwerte müssen im Pilotfahrzeug gegen den Tachostand geprüft werden. Liefert ein Fahrzeug keinen OEM-Gesamtkilometerstand, wird einmalig ein dokumentierter Tachostand mit dem Teltonika-Zähler verknüpft. Der daraus entstehende Offset bleibt versioniert.
|
||||
|
||||
## 4. Bedienung in FEDEO
|
||||
|
||||
Der vorhandene, bislang nur konfigurierte Ressourcenschlüssel `trackingtrips` kann weiterverwendet werden. Für das Fahrtenbuch ist dennoch eine eigene Seite sinnvoller als die generische Standard-Entity-Maske.
|
||||
|
||||
### Ansichten
|
||||
|
||||
- **Fahrten:** chronologische Liste mit Fahrzeug, Fahrer, Start/Ziel, Zeit, Kilometerständen, Distanz, Klassifizierung, Zweck und Prüfstatus.
|
||||
- **Prüfen:** schnelle Stapelbearbeitung aller offenen Fahrten; Vorschläge aus Kalender, Kunde/Projekt und wiederkehrenden Zielen.
|
||||
- **Karte:** Route einer ausgewählten Fahrt, nicht standardmäßig die vollständige Mitarbeiterhistorie.
|
||||
- **Fahrzeug:** Trackerstatus, letzter Empfang, Kilometerstandsqualität und offene Warnungen.
|
||||
- **Export:** Monats-/Jahresabschluss, PDF-Vorschau und Prüfdateien.
|
||||
|
||||
Eine betriebliche Fahrt verlangt Ziel, Reisezweck und Geschäftspartner beziehungsweise einen konkreten betrieblichen Vorgang. Privatfahrten speichern für normale Benutzer nur die steuerlich erforderlichen Werte; die Sichtbarkeit genauer Privat-Routen sollte über eine eigene Berechtigung begrenzt werden.
|
||||
|
||||
### API-Schnittstellen
|
||||
|
||||
Spezialisierte, mandantengeprüfte Routen sind der generischen Ressourcen-API vorzuziehen:
|
||||
|
||||
- `GET /api/tracking/trips`
|
||||
- `GET /api/tracking/trips/:id`
|
||||
- `PATCH /api/tracking/trips/:id/classification`
|
||||
- `POST /api/tracking/trips/:id/confirm`
|
||||
- `POST /api/tracking/trips/:id/split`
|
||||
- `POST /api/tracking/trips/merge`
|
||||
- `GET /api/tracking/vehicles/:id/status`
|
||||
- `POST /api/tracking/exports`
|
||||
- `GET /api/tracking/exports/:id`
|
||||
|
||||
Ändernde Aufrufe verlangen einen Änderungsgrund, sobald eine Fahrt bereits bestätigt war. Berechtigungen sollten mindestens `tracking.view`, `tracking.edit_own`, `tracking.edit_all`, `tracking.view_private_routes`, `tracking.manage_devices`, `tracking.lock` und `tracking.export` unterscheiden.
|
||||
|
||||
## 5. Steuerliche Nachvollziehbarkeit und Datenschutz
|
||||
|
||||
Für ein deutsches elektronisches Fahrtenbuch reichen GPS-Punkte allein nicht. Nach der Rechtsprechung müssen die Aufzeichnungen zeitnah, fortlaufend und in geschlossener Form vorliegen. Änderungen müssen technisch ausgeschlossen oder in ihrer Reichweite direkt im Fahrtenbuch erkennbar sein. Für betriebliche Fahrten gehören grundsätzlich Datum, Kilometerstand zu Beginn und Ende, Reiseziel, Reisezweck und aufgesuchte Geschäftspartner dazu.
|
||||
|
||||
Deshalb sind folgende Punkte keine spätere Zusatzfunktion, sondern Bestandteil der ersten fachlich nutzbaren Version:
|
||||
|
||||
- append-only Messdaten und Änderungshistorie,
|
||||
- sichtbare Revisionsangaben im Fahrtenbuch und im Export,
|
||||
- Erinnerung und Eskalation für zeitnahe Klassifizierung,
|
||||
- Vollständigkeits- und Plausibilitätsprüfung pro Fahrzeug,
|
||||
- reproduzierbare, versionierte Monatsabschlüsse,
|
||||
- dokumentierte Verfahrensbeschreibung und Wiederherstellungstests.
|
||||
|
||||
Das Konzept ist eine technische Auslegung, keine Zusicherung der steuerlichen Anerkennung. Export und Verfahrensdokumentation sollten vor dem produktiven steuerlichen Einsatz mit der Steuerberatung abgestimmt werden.
|
||||
|
||||
Standortdaten von Beschäftigten erfordern zudem ein Rollen- und Löschkonzept, Zweckbindung, transparente Information und gegebenenfalls Beteiligung des Betriebsrats. Rohpunkte sollten nur so lange wie fachlich und rechtlich erforderlich gespeichert werden. Reverse-Geocoding erfolgt nur für Start und Ziel, asynchron und mit Cache; ein selbst betriebener Dienst oder ein vertraglich geprüfter Anbieter vermeidet unnötige Weitergabe vollständiger Bewegungsprofile.
|
||||
|
||||
## 6. Gerätekonfiguration
|
||||
|
||||
Für einen Pilot-Tracker wird ein versioniertes Teltonika-Konfigurationsprofil erstellt:
|
||||
|
||||
- Hauptserver: FEDEO-Domain und Tracking-Port
|
||||
- Transport: TCP mit TLS, sofern Modell/Firmware dies unterstützen
|
||||
- Datenprotokoll: Codec 8 Extended
|
||||
- Datenerfassung in Bewegung zunächst alle 30 Sekunden oder 100 Meter sowie bei relevanter Richtungsänderung
|
||||
- Ereignisdatensatz bei Zündung an/aus
|
||||
- AVL 239, 240, 16, 389, 256 und 134 aktivieren, soweit vom Gerät unterstützt
|
||||
- lokale Pufferung und älteste Datensätze zuerst senden
|
||||
- Serverbestätigung auf AVL-Ebene
|
||||
|
||||
Das Standardintervall von mehreren Minuten ist für belastbare Start-/Zielpunkte und Routen zu grob. Die endgültigen Intervalle werden im Pilot gegen Datenvolumen, SIM-Tarif und Fahrzeugbatterie getestet.
|
||||
|
||||
## 7. Einführung ohne Datenverlust
|
||||
|
||||
### Phase 0 – Geräte-Spike
|
||||
|
||||
Ein reales Gerät und Fahrzeug werden festgelegt. Modell, Firmware, IMEI, empfangene AVL-IDs, Zündungslogik und Kilometerstandsquellen werden dokumentiert. Ein aufgezeichneter Binärdatenbestand aus definierten Testfahrten bildet anschließend einen dauerhaft nutzbaren Parser- und Fahrtbildungs-Testvektor.
|
||||
|
||||
### Phase 1 – Shadow-Ingest
|
||||
|
||||
Teltonika unterstützt einen zweiten Server und einen Duplikatmodus. Während der Pilotphase sendet das Gerät an Traccar **und** FEDEO. FEDEO bestätigt und speichert Daten, beeinflusst aber noch kein produktives Fahrtenbuch. Über mehrere Wochen werden Paketvollständigkeit, Kilometerstände und erkannte Fahrten verglichen.
|
||||
|
||||
### Phase 2 – Fahrtenbuch-Pilot
|
||||
|
||||
Fahrtbildung, Prüfansicht, Klassifizierung, Revisionen und Export werden für wenige Fahrzeuge aktiviert. Kriterien für die Freigabe:
|
||||
|
||||
- kein Paketverlust bei Neustart oder Datenbankunterbrechung,
|
||||
- idempotente Verarbeitung wiederholter Pakete,
|
||||
- reproduzierbare Fahrtbildung bei ungeordneter Zustellung,
|
||||
- Kilometerstandsabweichungen erklärt und sichtbar,
|
||||
- vollständiger Export inklusive Änderungen,
|
||||
- Rechte- und Mandantentrennung getestet.
|
||||
|
||||
### Phase 3 – Umschaltung
|
||||
|
||||
Nach erfolgreichem Parallelbetrieb wird FEDEO Hauptserver. Traccar bleibt zunächst als Teltonika-Backupserver konfiguriert, anschließend wird es entfernt. Der Rückfall besteht in der ersten Zeit lediglich aus dem Zurückschalten des Geräteprofils; ein Datenbank-Rollback ist nicht erforderlich.
|
||||
|
||||
## 8. Empfohlener Implementierungsumfang
|
||||
|
||||
### Iteration 1: belastbarer Empfang
|
||||
|
||||
- Schemata `vehicle_trackers`, `tracking_packets`, `tracking_positions`
|
||||
- Codec-8/8E-Parser mit CRC- und offiziellen Beispielvektoren
|
||||
- TCP/TLS-Dienst, IMEI-Zuordnung, ACK nach Commit
|
||||
- Trackerstatus im Backend und technische Metriken
|
||||
- Docker-Compose-Erweiterung und Betriebsdokumentation
|
||||
|
||||
### Iteration 2: Fahrten
|
||||
|
||||
- Schemata `tracking_trips` und Qualitätsmeldungen
|
||||
- deterministischer Fahrtbildungs-Worker
|
||||
- Listen-, Detail- und Kartenansicht
|
||||
- manuelle Klassifizierung und Fahrerzuordnung
|
||||
|
||||
### Iteration 3: belastbares Fahrtenbuch
|
||||
|
||||
- unveränderliche Revisionen und Hash-Verkettung
|
||||
- zeitnahe Erinnerungen, Bestätigung und Monatsabschluss
|
||||
- PDF/CSV/JSON-Export mit Prüfmanifest
|
||||
- Projekt-/Kunden-/Kalender-Vorschläge
|
||||
- Rechte-, Datenschutz- und Verfahrensdokumentation
|
||||
|
||||
## 9. Tests, die vor Abschaltung von Traccar bestehen müssen
|
||||
|
||||
- fragmentierte und zusammengefasste TCP-Frames
|
||||
- ungültige Länge, CRC, Codec-ID, IMEI und Datensatzanzahl
|
||||
- Disconnect vor und nach ACK
|
||||
- dasselbe Paket mehrfach und gleichzeitig zugestellt
|
||||
- mehrere AVL-Datensätze pro Paket
|
||||
- negative Koordinaten und variable I/O-Felder aus Codec 8 Extended
|
||||
- Offline-Nachlieferung über mehrere Stunden in falscher Empfangsreihenfolge
|
||||
- Zündung an ohne Bewegung, kurze Stopps, Tunnel, GPS-Sprung und Mitternacht
|
||||
- fehlender oder zurückgesetzter Kilometerzähler
|
||||
- Trackerwechsel zwischen Fahrzeugen
|
||||
- Mandantentrennung jeder API-Route
|
||||
- Änderung einer bestätigten und einer gesperrten Fahrt
|
||||
- Export-Reproduzierbarkeit und Prüfung der Hash-Kette
|
||||
|
||||
## Empfehlung
|
||||
|
||||
Zuerst sollte **nicht** die Oberfläche gebaut werden, sondern ein zwei- bis dreitägiger Geräte-Spike mit einem konkreten Tracker. Danach ist Iteration 1 überschaubar und risikoarm. Der direkte Teltonika-Empfang selbst ist technisch klar definiert; die eigentliche Sorgfalt liegt in verspäteten Daten, Kilometerstandsqualität, Fahreridentität und der unveränderlich sichtbaren Bearbeitungshistorie.
|
||||
|
||||
## Quellen
|
||||
|
||||
- [Teltonika: Codec 8 und Codec 8 Extended](https://wiki.teltonika-gps.com/view/Teltonika_Data_Sending_Protocols)
|
||||
- [Teltonika: Empfehlung für Codec 8 Extended](https://wiki.teltonika-gps.com/view/Which_data_protocol_to_choose_Codec_8_or_Codec_8_Extended)
|
||||
- [Teltonika: FMC003 Data Sending Parameters](https://wiki.teltonika-gps.com/view/FMC003_Teltonika_Data_Sending_Parameters_ID)
|
||||
- [Teltonika: FMB003 Trip-/Odometer-Einstellungen](https://wiki.teltonika-gps.com/view/FMB003_Trip/Odometer_settings)
|
||||
- [Teltonika: FMB003 GPRS-, Zweitserver- und TLS-Einstellungen](https://wiki.teltonika-gps.com/view/FMB003_GPRS_settings)
|
||||
- [Teltonika: OEM-Gesamtkilometerstand und Fahrzeugkompatibilität](https://wiki.teltonika-gps.com/view/Pay_as_You_Drive)
|
||||
- [Bundesfinanzhof: Anforderungen an ein elektronisches Fahrtenbuch, VI B 37/23](https://www.bundesfinanzhof.de/de/entscheidung/entscheidungen-online/detail/STRE202450011/)
|
||||
- [Bundesfinanzhof: Inhalt und geschlossene Form des Fahrtenbuchs, VI R 33/10](https://www.bundesfinanzhof.de/de/entscheidung/entscheidungen-online/detail/STRE201210116/)
|
||||
- [BMF: Einkommensteuer-Handbuch 2025, Anhang 16 III](https://lsth.bundesfinanzministerium.de/esth/2025/B-Anhaenge/Anhang-16/III/inhalt.html)
|
||||
@@ -1,6 +1,6 @@
|
||||
# Persönliche Benachrichtigungen
|
||||
|
||||
Unter Einstellungen → Benachrichtigungen im Web und Mehr → Einstellungen in der mobilen App kann jeder Benutzer E-Mail und Push für sein Profil im aktiven Tenant einstellen. Für ein anderes Profil wird zuerst der Tenant gewechselt. Die E-Mail-Adresse stammt aktuell vom Benutzerkonto, nicht vom Mitarbeiterprofil.
|
||||
Unter Einstellungen → Benachrichtigungen (`/settings/notifications`) im Web und Mehr → Einstellungen in der mobilen App kann jeder Benutzer E-Mail und Push für sein Profil im aktiven Tenant einstellen. Der Web-Menüeintrag ist für alle angemeldeten Mitarbeiter unabhängig von Administrationsrechten sichtbar. Für ein anderes Profil wird zuerst der Tenant gewechselt. Die E-Mail-Adresse stammt aktuell vom Benutzerkonto, nicht vom Mitarbeiterprofil.
|
||||
|
||||
## Ereignisse
|
||||
|
||||
@@ -10,16 +10,23 @@ Unter Einstellungen → Benachrichtigungen im Web und Mehr → Einstellungen in
|
||||
| `communication.message.mentioned` | Persönliche @-Erwähnung im Raum oder Projektchat | aus | an |
|
||||
| `communication.message.room` | Sonstige Nachricht in einem Raum oder Projektchat mit Mitgliedschaft | aus | aus |
|
||||
| `communication.room.invited` | Aufnahme in einen neu angelegten allgemeinen Chatraum | aus | aus |
|
||||
| `collaboration.message.new` | Neue Nachricht in einem freigegebenen Unterraum oder föderierten Chat, ohne Absender | aus | aus |
|
||||
| `collaboration.room.invited` | Persönliche Einladung in einen Unterraum oder föderierten Chat | aus | an |
|
||||
|
||||
Erwähnte Empfänger erhalten nur das Erwähnungsereignis, nicht zusätzlich das normale Raumereignis. Projektchats sind die nativen FEDEO-Chaträume; föderierte Zusammenarbeit wird hier noch nicht erfasst.
|
||||
Erwähnte Empfänger erhalten nur das Erwähnungsereignis, nicht zusätzlich das normale Raumereignis. Projektchats sind die nativen FEDEO-Chaträume. Die beiden Ereignisse unter „Zusammenarbeit“ gelten für lokale Unterräume, mandantenübergreifende Teilnahmen und föderierte Chats. Sie erscheinen automatisch in den Einstellungen im Web und in der App.
|
||||
|
||||
Persönliche Einstellungen haben Vorrang vor Tenant-Standardwerten. Ohne beide Einträge gelten die obigen Standardwerte. In-App bleibt für Direktnachrichten und Erwähnungen aktiv; die neuen optionalen Raumereignisse sind auch In-App standardmäßig aus. Technische Testnachrichten sind nicht Teil der Matrix.
|
||||
Persönliche Einstellungen haben Vorrang vor Tenant-Standardwerten. Ohne beide Einträge gelten die obigen Standardwerte. In-App bleibt für Direktnachrichten, Erwähnungen und die Zusammenarbeit aktiv; die optionalen nativen Raumereignisse sind auch In-App standardmäßig aus. Technische Testnachrichten sind nicht Teil der Matrix.
|
||||
|
||||
Für die Zusammenarbeit zählt immer der Heimatmandant des empfangenden Benutzers, auch wenn der Raum einem anderen Mandanten oder einer Partnerinstanz gehört. Benachrichtigt werden nur aktive, berechtigte FEDEO-Benutzer. Gäste ohne Benutzerkonto behalten ihren gesonderten Einladungsversand und ihre Anmeldung per E-Mail-Code.
|
||||
|
||||
Nachrichten und Einladungen werden mit ihren Benachrichtigungen atomar gespeichert. Ein Worker verarbeitet die vorgemerkten Kanäle alle fünf Sekunden unabhängig von einem geöffneten Browser. Wiederholte Nachrichtenbefehle, Einladungslieferungen und Synchronisationen erzeugen keine zusätzlichen Einträge; eigene Nachrichten und rückwärts nachgeladener Verlauf lösen keine Benachrichtigung aus. Bei Partnerausfällen wartet der Versand auf eine erneute Zugriffsprüfung. Widerrufene oder abgelaufene Teilnahmen und erledigte Einladungen werden vor dem Versand verworfen. Bereits gelesene Nachrichten lösen keine ausstehenden E-Mails oder Pushs mehr aus. Die persönlichen Einstellungen werden vor dem Versand erneut geprüft. Fehler des eigentlichen E-Mail-/Push-Zustellers werden wie bisher als fehlgeschlagen gespeichert; dafür gibt es noch keinen automatischen Wiederholungsversand.
|
||||
|
||||
## API und Migration
|
||||
|
||||
- `GET /api/notifications/preferences`: wirksame Einstellungen für den Benutzer und Tenant der authentifizierten Session.
|
||||
- `PUT /api/notifications/preferences`: Array aus `{eventType, channel, enabled}`; Kanäle `email` und `push`. Unbekannte Ereignisse, nicht erlaubte Kanäle, nicht-boolsche Werte und Duplikate werden mit 400 abgewiesen. Änderungen werden atomar gespeichert. Benutzer- oder Tenant-IDs im Body ändern den Geltungsbereich nicht.
|
||||
- Migration `0079_notification_matrix` registriert die neuen Ereignisse und übernimmt persönliche Einstellungen und Tenant-Standards von `communication.message.new` für Direktnachrichten und Erwähnungen. Sie deaktiviert den alten Sammelauslöser sowie die bisher nicht angebundenen Anrufereignisse. Historische Benachrichtigungen bleiben erhalten.
|
||||
- Migration `0083_collaboration_notifications` registriert die beiden Zusammenarbeitsereignisse und indiziert deren wartende Zustellungen. Es werden keine historischen lokalen Nachrichten oder Einladungen nachträglich verschickt. Bei der nächsten Synchronisation können bisher noch nicht abgeholte, ungelesene Partnernachrichten Benachrichtigungen auslösen.
|
||||
- E-Mail verwendet den SMTP-Versand der Instanz, mobiles Push den zentralen Service, Browser-Push die Web-Push-Konfiguration der Instanz. Ein aktivierter Kanal setzt eine funktionierende Zustellkonfiguration voraus.
|
||||
|
||||
## Sinnvolle nächste Auslöser
|
||||
|
||||
@@ -41,7 +41,7 @@ Die Pipeline nutzt die fest gepinnten Pakete `@semantic-release/commit-analyzer`
|
||||
|
||||
Es zählt der höchste erforderliche Sprung seit dem letzten stabilen Tag `vMAJOR.MINOR.PATCH`. Eine Änderung und ihr vollständiger Git-Revert innerhalb desselben Release-Bereichs heben sich auf. Selbst verfasste Nachrichten müssen dem Schema entsprechen; echte Merge-Commits und automatisch generierte Git-Reverts werden gesondert behandelt.
|
||||
|
||||
Der erste Release heißt `3.0.0`. `bootstrapCommit` in `release.config.json` begrenzt die Prüfung und die erste Änderungsliste auf die Einführung dieser Versionierung auf `dev`. `legacyHistoryHeads` hält zusätzlich den letzten alten `main`-Stand fest (`e7554fa2…` vor der ersten Übernahme von `dev`). Dessen Historie enthält ältere Änderungen an Issue-Vorlagen, die nicht vom `dev`-Ausgangscommit erreichbar sind. Beide festgelegten Historien werden aus Commit-Prüfung, Versionsberechnung und Release Notes ausgeschlossen. Neue Commits zählen auch dann, wenn ihr Zweig von einem dieser alten Stände abzweigt.
|
||||
Der erste Release heißt `3.0.0`. `bootstrapCommit` in `release.config.json` begrenzt die Prüfung und die erste Änderungsliste auf die Einführung dieser Versionierung auf `dev`. `legacyHistoryHeads` hält zusätzlich den letzten alten `main`-Stand fest (`e7554fa2…` vor der ersten Übernahme von `dev`). Dessen Historie enthält ältere Änderungen an Issue-Vorlagen, die nicht vom `dev`-Ausgangscommit erreichbar sind. Außerdem ist der alte Mobile-Zweig (`89185b4b…`, Stand vor dem Ausgangscommit) eingetragen, der mit `7a1986bb` nach `dev` übernommen wurde. Alle festgelegten Historien werden aus Commit-Prüfung, Versionsberechnung und Release Notes ausgeschlossen. Neue Commits zählen auch dann, wenn ihr Zweig von einem dieser alten Stände abzweigt.
|
||||
|
||||
Ältere Commits werden weder umgeschrieben noch nachträglich klassifiziert. Diese festen Ausgangscommits nach Einführung nicht verschieben und keine späteren Änderungen hinzufügen, um die Commit-Prüfung zu umgehen. Der vollständige Checkout muss auch die alten Branch-Historien enthalten; ein fehlender Ausgangscommit führt zum Abbruch.
|
||||
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
<script setup>
|
||||
const props = defineProps({ roomId: { type: String, required: true }, api: { type: Function, required: true }, base: { type: String, default: '/api/collaboration' }, embedded: { type: Boolean, default: false } })
|
||||
const emit = defineEmits(['changed', 'unauthorized'])
|
||||
const room = ref(null), messages = ref([]), members = ref([]), draft = ref(''), draftImage = ref(null), error = ref('')
|
||||
const room = ref(null), messages = ref([]), members = ref([]), error = ref('')
|
||||
// Guest access has separate credentials and must never reuse an internal user's drafts.
|
||||
const { draft, draftImage, draftSending, clearDraft, startDraftSend, finishDraftSend } = useChatDraft(() => `collaboration:${props.roomId}`, { persist: () => props.base === '/api/collaboration' })
|
||||
const loading = ref(false), sending = ref(false), olderLoading = ref(false), hasMore = ref(false), viewport = ref(null)
|
||||
let generation = 0, timer, polling = false, pending = null
|
||||
let generation = 0, timer, polling = false
|
||||
const endpoint = (id, suffix = '') => `${props.base}/rooms/${encodeURIComponent(id)}${suffix}`
|
||||
const merge = (incoming) => {
|
||||
const byId = new Map(messages.value.map(m => [m.id, m]))
|
||||
@@ -20,7 +22,7 @@ const scroll = async () => { await nextTick(); if (viewport.value) viewport.valu
|
||||
function failed(e) {
|
||||
error.value = messageError(e)
|
||||
if ([401, 403, 404, 410].includes(e?.statusCode || e?.status)) {
|
||||
room.value = null; messages.value = []; members.value = []; draftImage.value = null
|
||||
room.value = null; messages.value = []; members.value = []
|
||||
if ((e?.statusCode || e?.status) === 401) emit('unauthorized')
|
||||
}
|
||||
}
|
||||
@@ -32,7 +34,7 @@ async function read(id, version) {
|
||||
}
|
||||
async function load() {
|
||||
const version = ++generation, id = props.roomId
|
||||
room.value = null; messages.value = []; members.value = []; draft.value = ''; draftImage.value = null; error.value = ''; pending = null
|
||||
room.value = null; messages.value = []; members.value = []; error.value = ''
|
||||
loading.value = true; sending.value = false; olderLoading.value = false
|
||||
try {
|
||||
const [detail, result, people] = await Promise.all([props.api(endpoint(id)), props.api(endpoint(id, '/messages')), props.api(endpoint(id, '/members'))])
|
||||
@@ -78,15 +80,18 @@ async function send() {
|
||||
const text = draft.value.trim(), image = draftImage.value
|
||||
if ((!text && !image) || sending.value || !room.value?.canSend) return
|
||||
const version = generation, id = props.roomId
|
||||
if (!pending || pending.text !== text || pending.image !== image) pending = { text, image, clientId: crypto.randomUUID() }
|
||||
const savedDraft = startDraftSend()
|
||||
if (!savedDraft) return
|
||||
const pending = { text, image, clientId: savedDraft.value.clientId }
|
||||
sending.value = true; error.value = ''
|
||||
try {
|
||||
const message = await props.api(endpoint(id, '/messages'), { method: 'POST', body: pending })
|
||||
clearDraft(savedDraft)
|
||||
if (version !== generation) return
|
||||
merge([message]); draft.value = ''; draftImage.value = null; pending = null
|
||||
merge([message])
|
||||
await scroll(); await read(id, version)
|
||||
} catch (e) { if (version === generation) failed(e) }
|
||||
finally { if (version === generation) sending.value = false }
|
||||
finally { finishDraftSend(savedDraft); if (version === generation) sending.value = false }
|
||||
}
|
||||
const time = value => new Date(value).toLocaleString('de-DE', { dateStyle: 'short', timeStyle: 'short' })
|
||||
watch(() => props.roomId, load, { immediate: true })
|
||||
@@ -126,6 +131,6 @@ onBeforeUnmount(() => { ++generation; clearInterval(timer) })
|
||||
</div>
|
||||
</ChatReactions>
|
||||
</div>
|
||||
<ChatComposer v-if="room" :key="roomId" v-model="draft" v-model:image="draftImage" :busy="sending" :disabled="!room.canSend" :placeholder="room.canSend ? 'Nachricht schreiben …' : 'Dieser Unterraum ist nur lesbar'" @send="send" />
|
||||
<ChatComposer v-if="room" :key="roomId" v-model="draft" v-model:image="draftImage" :busy="sending || draftSending" :disabled="!room.canSend" :placeholder="room.canSend ? 'Nachricht schreiben …' : 'Dieser Unterraum ist nur lesbar'" @send="send" />
|
||||
</section>
|
||||
</template>
|
||||
|
||||
57
frontend/components/ColorInput.vue
Normal file
57
frontend/components/ColorInput.vue
Normal file
@@ -0,0 +1,57 @@
|
||||
<script setup>
|
||||
const props = defineProps({
|
||||
modelValue: {
|
||||
type: String,
|
||||
default: null
|
||||
},
|
||||
disabled: {
|
||||
type: Boolean,
|
||||
default: false
|
||||
},
|
||||
label: {
|
||||
type: String,
|
||||
default: 'Farbe'
|
||||
}
|
||||
})
|
||||
|
||||
const emit = defineEmits(['update:modelValue'])
|
||||
|
||||
const pickerValue = computed(() => {
|
||||
const value = props.modelValue?.trim() || ''
|
||||
if (/^#[\da-f]{6}$/i.test(value)) return value
|
||||
if (/^#[\da-f]{3}$/i.test(value)) {
|
||||
return `#${value.slice(1).split('').map(character => character.repeat(2)).join('')}`
|
||||
}
|
||||
return '#2563eb'
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<InputGroup class="w-full">
|
||||
<input
|
||||
type="color"
|
||||
:value="pickerValue"
|
||||
:disabled="disabled"
|
||||
:aria-label="`${label} auswählen`"
|
||||
class="h-9 w-14 shrink-0 cursor-pointer rounded border border-default bg-transparent p-1 disabled:cursor-not-allowed disabled:opacity-50"
|
||||
@input="emit('update:modelValue', $event.target.value)"
|
||||
>
|
||||
<UInput
|
||||
:model-value="modelValue"
|
||||
:disabled="disabled"
|
||||
:aria-label="`${label} als Farbwert`"
|
||||
class="min-w-0 flex-1"
|
||||
placeholder="Standardfarbe"
|
||||
@update:model-value="emit('update:modelValue', $event || null)"
|
||||
/>
|
||||
<UButton
|
||||
type="button"
|
||||
:disabled="disabled || !modelValue"
|
||||
:aria-label="`${label} zurücksetzen`"
|
||||
variant="outline"
|
||||
color="neutral"
|
||||
icon="i-heroicons-x-mark"
|
||||
@click="emit('update:modelValue', null)"
|
||||
/>
|
||||
</InputGroup>
|
||||
</template>
|
||||
@@ -385,6 +385,8 @@ const getEntityModalCreateQuery = (datapoint) => {
|
||||
const getPostSaveRoute = () => {
|
||||
if (type !== "events") return null
|
||||
|
||||
if (route.query.returnTo === "events") return "/events"
|
||||
|
||||
if (route.query.returnTo === "plantafel") {
|
||||
return {
|
||||
path: "/organisation/plantafel",
|
||||
@@ -475,25 +477,21 @@ const updateItem = async () => {
|
||||
<template>
|
||||
<UDashboardNavbar
|
||||
v-if="!props.inModal"
|
||||
:title="item.id ? `${dataType.labelSingle} bearbeiten` : `${dataType.labelSingle} erstellen`"
|
||||
:ui="{center: 'flex items-stretch gap-1.5 min-w-0'}"
|
||||
>
|
||||
<template #toggle>
|
||||
<div v-if="platform === 'mobile'"></div>
|
||||
</template>
|
||||
<template #left>
|
||||
<template #leading>
|
||||
<UButton
|
||||
icon="i-heroicons-chevron-left"
|
||||
variant="outline"
|
||||
aria-label="Zurück"
|
||||
@click="router.back()"
|
||||
>
|
||||
</UButton>
|
||||
</template>
|
||||
<template #center>
|
||||
<h1
|
||||
v-if="item"
|
||||
:class="['text-xl','font-medium', 'text-center']"
|
||||
>{{ item.id ? `${dataType.labelSingle} bearbeiten` : `${dataType.labelSingle} erstellen` }}</h1>
|
||||
</template>
|
||||
<template #right>
|
||||
<ArchiveButton
|
||||
color="error"
|
||||
@@ -517,7 +515,7 @@ const updateItem = async () => {
|
||||
Erstellen
|
||||
</UButton>
|
||||
<UButton
|
||||
@click="router.push(item.id ? `/standardEntity/${type}/show/${item.id}` : `/standardEntity/${type}`)"
|
||||
@click="router.push(getPostSaveRoute() || (item.id ? `/standardEntity/${type}/show/${item.id}` : `/standardEntity/${type}`))"
|
||||
color="red"
|
||||
class="ml-1"
|
||||
>
|
||||
@@ -527,14 +525,9 @@ const updateItem = async () => {
|
||||
</UDashboardNavbar>
|
||||
<UDashboardNavbar
|
||||
v-else
|
||||
:title="props.floatingWindow ? '' : (item.id ? `${dataType.labelSingle} bearbeiten` : `${dataType.labelSingle} erstellen`)"
|
||||
:ui="{center: 'flex items-stretch gap-1.5 min-w-0'}"
|
||||
>
|
||||
<template #center>
|
||||
<h1
|
||||
v-if="item && !props.floatingWindow"
|
||||
:class="['text-xl', 'font-medium']"
|
||||
>{{ item.id ? `${dataType.labelSingle} bearbeiten` : `${dataType.labelSingle} erstellen` }}</h1>
|
||||
</template>
|
||||
<template #right>
|
||||
<UButton
|
||||
v-if="item.id"
|
||||
@@ -586,7 +579,14 @@ const updateItem = async () => {
|
||||
:item="item"
|
||||
/>
|
||||
</template>
|
||||
<InputGroup class="w-full" v-if="datapoint.key.includes('.')">
|
||||
<ColorInput
|
||||
v-if="datapoint.inputType === 'color'"
|
||||
:model-value="getDatapointValue(datapoint)"
|
||||
:label="datapoint.label"
|
||||
:disabled="datapoint.disabledFunction ? datapoint.disabledFunction(item) : false"
|
||||
@update:model-value="(value) => setDatapointValue(datapoint, value)"
|
||||
/>
|
||||
<InputGroup class="w-full" v-else-if="datapoint.key.includes('.')">
|
||||
<UInput
|
||||
:color="datapoint.required ? (item[datapoint.key.split('.')[0]][datapoint.key.split('.')[1]] ? 'primary' : 'error') : 'white'"
|
||||
class="flex-auto"
|
||||
@@ -833,7 +833,14 @@ const updateItem = async () => {
|
||||
:item="item"
|
||||
/>
|
||||
</template>
|
||||
<InputGroup class="w-full" v-if="datapoint.key.includes('.')">
|
||||
<ColorInput
|
||||
v-if="datapoint.inputType === 'color'"
|
||||
:model-value="getDatapointValue(datapoint)"
|
||||
:label="datapoint.label"
|
||||
:disabled="datapoint.disabledFunction ? datapoint.disabledFunction(item) : false"
|
||||
@update:model-value="(value) => setDatapointValue(datapoint, value)"
|
||||
/>
|
||||
<InputGroup class="w-full" v-else-if="datapoint.key.includes('.')">
|
||||
<UInput
|
||||
:color="datapoint.required ? (item[datapoint.key.split('.')[0]][datapoint.key.split('.')[1]] ? 'primary' : 'error') : 'white'"
|
||||
class="flex-auto"
|
||||
|
||||
@@ -124,6 +124,16 @@ const invoiceDeliveryNotes = () => {
|
||||
router.push(`/createDocument/edit?type=invoices&loadMode=deliveryNotes&linkedDocuments=[${props.item.createddocuments.filter(i => deliveryNoteLikeDocumentTypes.includes(i.type)).map(i => i.id)}]`)
|
||||
}
|
||||
|
||||
const createAdvanceInvoice = () => {
|
||||
if (props.topLevelType !== 'projects' || !props.item.id) return
|
||||
|
||||
const query = new URLSearchParams(props.queryStringData)
|
||||
query.set('type', 'advanceInvoices')
|
||||
query.set('loadMode', 'advanceInvoice')
|
||||
query.set('project', props.item.id)
|
||||
router.push(`/createDocument/edit?${query.toString()}`)
|
||||
}
|
||||
|
||||
const showFinalInvoiceConfig = ref(false)
|
||||
const referenceDocument = ref(null)
|
||||
const advanceInvoicesToAdd = ref([])
|
||||
@@ -169,6 +179,13 @@ const selectItem = (item) => {
|
||||
>
|
||||
Dokument aus Vorlage
|
||||
</UButton>
|
||||
<UButton
|
||||
v-if="props.topLevelType === 'projects'"
|
||||
icon="i-heroicons-plus"
|
||||
@click="createAdvanceInvoice"
|
||||
>
|
||||
Abschlagsrechnung
|
||||
</UButton>
|
||||
<UButton
|
||||
@click="showFinalInvoiceConfig = true"
|
||||
v-if="props.topLevelType === 'projects'"
|
||||
|
||||
@@ -38,6 +38,12 @@ const isRouteActive = (to) => {
|
||||
|
||||
const links = computed(() => {
|
||||
const organisationChildren = [
|
||||
has("events") && featureEnabled("calendar") ? {
|
||||
label: "Termine",
|
||||
to: "/events",
|
||||
icon: "i-heroicons-calendar-days",
|
||||
active: route.path.startsWith("/standardEntity/events")
|
||||
} : null,
|
||||
has("tasks") && featureEnabled("tasks") ? {
|
||||
label: "Aufgaben",
|
||||
to: "/tasks",
|
||||
@@ -318,6 +324,11 @@ const links = computed(() => {
|
||||
]
|
||||
|
||||
const settingsChildren = [
|
||||
{
|
||||
label: "Benachrichtigungen",
|
||||
to: "/settings/notifications",
|
||||
icon: "i-heroicons-bell",
|
||||
},
|
||||
featureEnabled("settingsNumberRanges") ? {
|
||||
label: "Nummernkreise",
|
||||
to: "/settings/numberRanges",
|
||||
|
||||
@@ -18,9 +18,9 @@ const props = defineProps({
|
||||
|
||||
const emit = defineEmits(["updateNeeded","returnData"])
|
||||
|
||||
const documentTypeToUse = ref(props.type)
|
||||
const documentTypeToUse = ref(props.type === 'advanceInvoices' ? null : props.type)
|
||||
const documentTypeItems = computed(() => {
|
||||
return Object.keys(dataStore.documentTypesForCreation).map((key) => ({
|
||||
return Object.keys(dataStore.documentTypesForCreation).filter(key => key !== 'advanceInvoices').map((key) => ({
|
||||
...dataStore.documentTypesForCreation[key],
|
||||
key
|
||||
}))
|
||||
@@ -83,6 +83,8 @@ const mappings = ref({
|
||||
})
|
||||
|
||||
const startImport = () => {
|
||||
if (!selectedDocumentType.value) return
|
||||
|
||||
router.push(`/createDocument/edit/?createddocument=${props.id}&type=${documentTypeToUse.value}&optionsToImport=${encodeURIComponent(JSON.stringify(optionsToImport.value))}`)
|
||||
modal.close()
|
||||
}
|
||||
@@ -147,7 +149,7 @@ const startImport = () => {
|
||||
<UButton color="neutral" variant="ghost" @click="modal.close()">
|
||||
Abbrechen
|
||||
</UButton>
|
||||
<UButton @click="startImport">
|
||||
<UButton :disabled="!selectedDocumentType" @click="startImport">
|
||||
Kopieren
|
||||
</UButton>
|
||||
</div>
|
||||
|
||||
@@ -119,10 +119,13 @@ const reportRows = computed(() => {
|
||||
relevantCostCentreIds.value.has(account.costCentre)
|
||||
)
|
||||
|
||||
// Expenses reduce the cost centre result; incoming documents marked as income increase it.
|
||||
const sign = invoice.expense === false ? 1 : -1
|
||||
|
||||
return matchingAccounts.map((account, index) => {
|
||||
const amountNet = Number(account.amountNet || 0)
|
||||
const amountTax = Number(account.amountTax || 0)
|
||||
const amountGross = Number(account.amountGross || amountNet + amountTax || 0)
|
||||
const amountNet = Number(account.amountNet || 0) * sign
|
||||
const amountTax = Number(account.amountTax || 0) * sign
|
||||
const amountGross = Number(account.amountGross || Number(account.amountNet || 0) + Number(account.amountTax || 0) || 0) * sign
|
||||
const accountCostCentre = costCentreMap.value.get(getCostCentreId(account.costCentre))
|
||||
|
||||
return {
|
||||
@@ -196,8 +199,7 @@ const reportRows = computed(() => {
|
||||
const centre = costCentreMap.value.get(getCostCentreId(allocation.costcentre))
|
||||
const account = accounts.value.find(account => account.id === (allocation.account?.id || allocation.account)) || allocation.ownaccount
|
||||
const amounts = getBankAllocationAmounts(allocation)
|
||||
// As for incoming documents, expenses are positive and refunds negative.
|
||||
const sign = amounts.kind === "input" || (amounts.kind === "none" && amounts.amountGross < 0) ? -1 : 1
|
||||
// The bank amount is already signed: outflows (expenses) negative, inflows positive.
|
||||
return [{
|
||||
id: `bank-${allocation.id}`,
|
||||
sourceLabel: "Bankbuchung",
|
||||
@@ -209,9 +211,9 @@ const reportRows = computed(() => {
|
||||
accountLabel: `${account?.number || ""} ${account?.label || account?.name || ""}`.trim() || "-",
|
||||
costCentreName: centre ? `${centre.number} - ${centre.name}` : "-",
|
||||
description: allocation.description || statement.text || "-",
|
||||
amountNet: amounts.amountNet * sign,
|
||||
amountTax: amounts.amountTax * sign,
|
||||
amountGross: amounts.amountGross * sign,
|
||||
amountNet: amounts.amountNet,
|
||||
amountTax: amounts.amountTax,
|
||||
amountGross: amounts.amountGross,
|
||||
}]
|
||||
})
|
||||
return [...incomingRows, ...outgoingRows, ...bankRows]
|
||||
|
||||
@@ -10,10 +10,11 @@ const props = defineProps({
|
||||
})
|
||||
|
||||
const documentTypes = computed(() => Object.entries(dataStore.documentTypesForCreation || {})
|
||||
.filter(([key]) => key !== 'serialInvoices')
|
||||
.filter(([key]) => !['serialInvoices', 'advanceInvoices'].includes(key))
|
||||
.map(([key, value]) => ({ key, ...value })))
|
||||
const visibleTemplates = computed(() => templates.value.filter(template => {
|
||||
return !selectedType.value || template.documentType === selectedType.value
|
||||
return template.documentType !== 'advanceInvoices'
|
||||
&& (!selectedType.value || template.documentType === selectedType.value)
|
||||
}))
|
||||
|
||||
const loadTemplates = async () => {
|
||||
@@ -25,6 +26,8 @@ const loadTemplates = async () => {
|
||||
}
|
||||
|
||||
const selectTemplate = (template) => {
|
||||
if (template.documentType === 'advanceInvoices') return
|
||||
|
||||
const query = new URLSearchParams(props.queryStringData)
|
||||
query.set('templateId', template.id)
|
||||
query.set('type', template.documentType)
|
||||
|
||||
@@ -9,10 +9,12 @@ const props = defineProps({
|
||||
})
|
||||
|
||||
const documentTypes = computed(() => Object.entries(dataStore.documentTypesForCreation || {})
|
||||
.filter(([key]) => key !== 'serialInvoices')
|
||||
.filter(([key]) => !['serialInvoices', 'advanceInvoices'].includes(key))
|
||||
.map(([key, value]) => ({ key, ...value })))
|
||||
|
||||
const createDocument = (type) => {
|
||||
if (!documentTypes.value.some(documentType => documentType.key === type)) return
|
||||
|
||||
const query = new URLSearchParams(props.queryStringData)
|
||||
query.set('type', type)
|
||||
if (props.projectId) query.set('project', props.projectId)
|
||||
|
||||
@@ -23,11 +23,13 @@ export type AdminUserProfile = {
|
||||
last_name: string
|
||||
email?: string | null
|
||||
active: boolean
|
||||
archived_at: string | null
|
||||
}
|
||||
|
||||
export type AdminUser = {
|
||||
id: string
|
||||
email: string
|
||||
archived_at: string | null
|
||||
display_name: string
|
||||
multiTenant: boolean
|
||||
must_change_password: boolean
|
||||
@@ -161,8 +163,8 @@ export type CreateInstanceAgentResult = {
|
||||
export const useAdmin = () => {
|
||||
const { $api } = useNuxtApp()
|
||||
|
||||
const getOverview = async (): Promise<AdminOverview> => {
|
||||
const response = await $api("/api/admin/overview") as any
|
||||
const getOverview = async (includeArchived = false): Promise<AdminOverview> => {
|
||||
const response = await $api("/api/admin/overview", { query: { includeArchived } }) as any
|
||||
|
||||
return {
|
||||
users: response?.users || [],
|
||||
@@ -193,6 +195,10 @@ export const useAdmin = () => {
|
||||
})
|
||||
}
|
||||
|
||||
const archiveUser = async (id: string) => {
|
||||
return await $api(`/api/admin/users/${id}/archive`, { method: "POST" })
|
||||
}
|
||||
|
||||
const resetUserPassword = async (id: string, password?: string) => {
|
||||
return await $api(`/api/admin/users/${id}/reset-password`, {
|
||||
method: "POST",
|
||||
@@ -294,6 +300,7 @@ export const useAdmin = () => {
|
||||
createUserForProfile,
|
||||
updateUser,
|
||||
resetUserPassword,
|
||||
archiveUser,
|
||||
updateUserAccess,
|
||||
createTenant,
|
||||
invitePortalUser,
|
||||
|
||||
43
frontend/composables/useChatDraft.js
Normal file
43
frontend/composables/useChatDraft.js
Normal file
@@ -0,0 +1,43 @@
|
||||
export function useChatDraft(roomKey, { persist = true } = {}) {
|
||||
const auth = useAuthStore()
|
||||
const temp = useTempStore()
|
||||
const apiBase = useRuntimeConfig().public.apiBase
|
||||
const localDraft = ref(null)
|
||||
const key = computed(() => {
|
||||
const room = toValue(roomKey), user = auth.user?.id || auth.user?.user_id
|
||||
return toValue(persist) && room && user && auth.activeTenant
|
||||
? JSON.stringify([apiBase, user, String(auth.activeTenant), auth.profile?.id || '', room])
|
||||
: null
|
||||
})
|
||||
watch([key, () => toValue(roomKey), () => auth.user?.id || auth.user?.user_id,
|
||||
() => auth.activeTenant, () => auth.profile?.id], () => { localDraft.value = null }, { flush: 'sync' })
|
||||
const current = () => key.value ? temp.getChatDraft(key.value) : localDraft.value
|
||||
function update(patch) {
|
||||
const value = { text: '', image: null, ...current(), ...patch, clientId: crypto.randomUUID() }
|
||||
const next = value.text || value.image ? value : null
|
||||
if (key.value) temp.setChatDraft(key.value, next)
|
||||
else localDraft.value = next
|
||||
}
|
||||
const draft = computed({ get: () => current()?.text || '', set: text => update({ text }) })
|
||||
const draftImage = computed({ get: () => current()?.image || null, set: image => update({ image }) })
|
||||
const draftSending = computed(() => !!key.value && temp.isChatDraftSending(key.value))
|
||||
const captureDraft = () => ({ key: key.value, value: current() })
|
||||
function startDraftSend() {
|
||||
if (draftSending.value) return null
|
||||
const snapshot = captureDraft()
|
||||
if (!snapshot.value) return null
|
||||
if (snapshot.key) temp.startChatDraftSend(snapshot.key, snapshot.value.clientId)
|
||||
return snapshot
|
||||
}
|
||||
function finishDraftSend(snapshot) {
|
||||
if (snapshot.key) temp.finishChatDraftSend(snapshot.key, snapshot.value.clientId)
|
||||
}
|
||||
function clearDraft(snapshot) {
|
||||
const saved = snapshot.key ? temp.getChatDraft(snapshot.key) : localDraft.value
|
||||
// A late send response must only remove the draft that was actually sent.
|
||||
if (!snapshot.value || saved?.clientId !== snapshot.value.clientId) return
|
||||
if (snapshot.key) temp.setChatDraft(snapshot.key, null)
|
||||
else localDraft.value = null
|
||||
}
|
||||
return { draft, draftImage, draftSending, captureDraft, clearDraft, startDraftSend, finishDraftSend }
|
||||
}
|
||||
@@ -11,6 +11,10 @@ const userId = route.params.id as string
|
||||
const loading = ref(true)
|
||||
const saving = ref(false)
|
||||
const resettingPassword = ref(false)
|
||||
const archiving = ref(false)
|
||||
const archiveModalOpen = ref(false)
|
||||
const profileStore = useProfileStore()
|
||||
const isOwnUser = computed(() => userId === (auth.user?.id || auth.user?.user_id))
|
||||
const resetPasswordModalOpen = ref(false)
|
||||
const resetPasswordInput = ref("")
|
||||
const resetPasswordResult = ref("")
|
||||
@@ -102,7 +106,7 @@ const fetchUser = async () => {
|
||||
loading.value = true
|
||||
|
||||
try {
|
||||
const overview = await admin.getOverview()
|
||||
const overview = await admin.getOverview(true)
|
||||
roles.value = overview.roles
|
||||
tenants.value = overview.tenants
|
||||
unassignedProfiles.value = overview.unassignedProfiles
|
||||
@@ -136,7 +140,7 @@ const fetchUser = async () => {
|
||||
}
|
||||
|
||||
const saveUser = async () => {
|
||||
if (!userForm.value || saving.value) return
|
||||
if (!userForm.value || userForm.value.archived_at || saving.value || archiving.value) return
|
||||
|
||||
saving.value = true
|
||||
normalizeUserAssignments()
|
||||
@@ -172,8 +176,24 @@ const saveUser = async () => {
|
||||
}
|
||||
}
|
||||
|
||||
const archiveUser = async () => {
|
||||
if (!userForm.value || userForm.value.archived_at || archiving.value || isOwnUser.value) return
|
||||
archiving.value = true
|
||||
try {
|
||||
await admin.archiveUser(userForm.value.id)
|
||||
archiveModalOpen.value = false
|
||||
await fetchUser()
|
||||
if (auth.activeTenant) await profileStore.fetchData()
|
||||
toast.add({ title: "Benutzer dauerhaft archiviert", description: "Alle zugehörigen Profile wurden archiviert und ausgeblendet.", color: "success" })
|
||||
} catch (err: any) {
|
||||
toast.add({ title: "Benutzer konnte nicht archiviert werden", description: err?.data?.error || err?.message || "Unbekannter Fehler", color: "error" })
|
||||
} finally {
|
||||
archiving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const resetPassword = async () => {
|
||||
if (!userForm.value || resettingPassword.value) return
|
||||
if (!userForm.value || userForm.value.archived_at || resettingPassword.value || archiving.value) return
|
||||
|
||||
const password = resetPasswordInput.value.trim()
|
||||
if (password && password.length < 8) {
|
||||
@@ -248,21 +268,40 @@ onMounted(async () => {
|
||||
</UButton>
|
||||
</template>
|
||||
<template #right>
|
||||
<UButton
|
||||
v-if="userForm && !userForm.archived_at && !isOwnUser"
|
||||
color="error"
|
||||
variant="soft"
|
||||
icon="i-heroicons-archive-box"
|
||||
:disabled="saving || resettingPassword || archiving"
|
||||
@click="archiveModalOpen = true"
|
||||
>
|
||||
Dauerhaft archivieren
|
||||
</UButton>
|
||||
<UButton
|
||||
color="warning"
|
||||
variant="soft"
|
||||
icon="i-heroicons-key"
|
||||
:disabled="loading || !userForm || !!userForm.archived_at || archiving || saving"
|
||||
@click="openResetPasswordModal"
|
||||
>
|
||||
Passwort zurücksetzen
|
||||
</UButton>
|
||||
<UButton color="primary" :loading="saving" @click="saveUser">
|
||||
<UButton color="primary" :loading="saving" :disabled="loading || !userForm || !!userForm.archived_at || archiving || resettingPassword" @click="saveUser">
|
||||
Speichern
|
||||
</UButton>
|
||||
</template>
|
||||
</UDashboardNavbar>
|
||||
|
||||
<UDashboardPanelContent>
|
||||
<UAlert
|
||||
v-if="userForm?.archived_at"
|
||||
title="Benutzer dauerhaft archiviert"
|
||||
:description="`Archiviert am ${new Date(userForm.archived_at).toLocaleString('de-DE')}. Die Anmeldung ist gesperrt. Alle zugehörigen Profile sind archiviert und ausgeblendet.`"
|
||||
color="warning"
|
||||
variant="soft"
|
||||
class="mb-4"
|
||||
/>
|
||||
<UCard v-if="!loading && userForm">
|
||||
<div class="flex items-start justify-between gap-4 mb-6">
|
||||
<div>
|
||||
@@ -273,7 +312,7 @@ onMounted(async () => {
|
||||
|
||||
<USeparator label="Benutzer" />
|
||||
|
||||
<UForm :state="userForm" class="grid grid-cols-1 md:grid-cols-2 gap-6 mt-4">
|
||||
<UForm :disabled="!!userForm.archived_at || archiving" :state="userForm" class="grid grid-cols-1 md:grid-cols-2 gap-6 mt-4">
|
||||
<UFormField label="E-Mail">
|
||||
<UInput v-model="userForm.email" />
|
||||
</UFormField>
|
||||
@@ -341,6 +380,7 @@ onMounted(async () => {
|
||||
|
||||
<UFormField label="Rolle">
|
||||
<USelectMenu
|
||||
:disabled="!!userForm.archived_at || archiving"
|
||||
:model-value="getRoleForTenant(tenantId)"
|
||||
:items="getRoleOptionsForTenant(tenantId)"
|
||||
value-key="value"
|
||||
@@ -352,6 +392,7 @@ onMounted(async () => {
|
||||
|
||||
<UFormField label="Freies Profil">
|
||||
<USelectMenu
|
||||
:disabled="!!userForm.archived_at || archiving"
|
||||
:model-value="getProfileAssignmentForTenant(tenantId)"
|
||||
:items="[
|
||||
{ label: 'Neues Profil erzeugen', value: null },
|
||||
@@ -390,7 +431,7 @@ onMounted(async () => {
|
||||
variant="subtle"
|
||||
color="gray"
|
||||
>
|
||||
{{ profile.full_name || `${profile.first_name} ${profile.last_name}` }} · Tenant {{ profile.tenant_id }}
|
||||
{{ profile.full_name || `${profile.first_name} ${profile.last_name}` }} · Tenant {{ profile.tenant_id }}{{ profile.archived_at ? " · Archiviert" : "" }}
|
||||
</UBadge>
|
||||
</div>
|
||||
</UCard>
|
||||
@@ -398,6 +439,27 @@ onMounted(async () => {
|
||||
<USkeleton v-if="loading" class="h-80" />
|
||||
</UDashboardPanelContent>
|
||||
|
||||
<UModal v-model:open="archiveModalOpen" :dismissible="!archiving">
|
||||
<template #content>
|
||||
<UCard>
|
||||
<template #header>
|
||||
<div class="text-lg font-semibold">Benutzer dauerhaft archivieren</div>
|
||||
</template>
|
||||
<div class="space-y-3 text-sm">
|
||||
<p><strong>{{ userForm?.display_name }}</strong> ({{ userForm?.email }}) wird dauerhaft archiviert.</p>
|
||||
<p>Die Anmeldung wird gesperrt, bestehende Sitzungen und API-Schlüssel werden ungültig. Alle {{ userForm?.profiles.length || 0 }} zugehörigen Profile werden in sämtlichen Tenants archiviert und aus Listen und Auswahllisten ausgeblendet.</p>
|
||||
<p>Bestehende Dokumente, Zeiterfassungen und Zuordnungen bleiben erhalten. Die Archivierung kann nicht rückgängig gemacht werden.</p>
|
||||
</div>
|
||||
<template #footer>
|
||||
<div class="flex justify-end gap-3">
|
||||
<UButton variant="soft" color="neutral" :disabled="archiving" @click="archiveModalOpen = false">Abbrechen</UButton>
|
||||
<UButton color="error" icon="i-heroicons-archive-box" :loading="archiving" @click="archiveUser">Dauerhaft archivieren</UButton>
|
||||
</div>
|
||||
</template>
|
||||
</UCard>
|
||||
</template>
|
||||
</UModal>
|
||||
|
||||
<UModal v-model:open="resetPasswordModalOpen">
|
||||
<template #content>
|
||||
<UCard>
|
||||
|
||||
@@ -12,6 +12,7 @@ const createUserModalOpen = ref(false)
|
||||
const createdUserPassword = ref("")
|
||||
const users = ref<AdminUser[]>([])
|
||||
const searchString = ref("")
|
||||
const showArchived = ref(false)
|
||||
|
||||
const createUserForm = ref({
|
||||
email: "",
|
||||
@@ -27,13 +28,15 @@ const templateColumns = [
|
||||
{ key: "email", label: "E-Mail" },
|
||||
{ key: "tenant_count", label: "Tenants" },
|
||||
{ key: "is_admin", label: "Admin" },
|
||||
{ key: "status", label: "Status" },
|
||||
]
|
||||
|
||||
const filteredRows = computed(() => {
|
||||
const search = searchString.value.trim().toLowerCase()
|
||||
const rows = users.value.map((user) => ({
|
||||
const rows = users.value.filter((user) => showArchived.value || !user.archived_at).map((user) => ({
|
||||
...user,
|
||||
tenant_count: user.tenant_ids.length,
|
||||
status: user.archived_at ? "Archiviert" : "Aktiv",
|
||||
is_admin: user.is_admin ? "Ja" : "Nein",
|
||||
}))
|
||||
|
||||
@@ -50,7 +53,7 @@ const fetchUsers = async () => {
|
||||
loading.value = true
|
||||
|
||||
try {
|
||||
const overview = await admin.getOverview()
|
||||
const overview = await admin.getOverview(true)
|
||||
users.value = overview.users
|
||||
} catch (err: any) {
|
||||
console.error("[administration/users/index]", err)
|
||||
@@ -119,6 +122,7 @@ onMounted(async () => {
|
||||
<template>
|
||||
<UDashboardNavbar title="Administration: Benutzer" :badge="filteredRows.length">
|
||||
<template #right>
|
||||
<UCheckbox v-model="showArchived" label="Archivierte anzeigen" />
|
||||
<UInput
|
||||
v-model="searchString"
|
||||
icon="i-heroicons-magnifying-glass"
|
||||
|
||||
@@ -7,12 +7,13 @@ const router = useRouter()
|
||||
|
||||
const baseRooms = ref([]), projectRooms = ref([]), directRooms = ref([]), collaborationRooms = ref([])
|
||||
const invitations = ref([]), invitationBusy = ref(''), collaborationError = ref(''), listError = ref('')
|
||||
const unreadRooms = ref({}), messages = ref([]), members = ref([]), draft = ref(''), draftImage = ref(null)
|
||||
const unreadRooms = ref({}), messages = ref([]), members = ref([])
|
||||
const requestedRoom = () => typeof route.query.room === 'string' ? route.query.room : 'allgemein'
|
||||
const activeRoomKey = ref(requestedRoom())
|
||||
const loading = ref(true), roomLoading = ref(false), sending = ref(false), creating = ref(false)
|
||||
const showRoomForm = ref(false), messagesViewport = ref(null)
|
||||
const hiddenRoomKeys = ref([]), showHiddenRooms = ref(false), preferenceBusy = ref(''), preferenceError = ref('')
|
||||
const roomSearch = ref('')
|
||||
const preferencesReady = ref(false)
|
||||
const roomForm = reactive({ name: '', key: '', topic: '' })
|
||||
const session = computed(() => `${auth.user?.id || auth.user?.user_id || ''}:${auth.activeTenant || ''}`)
|
||||
@@ -42,14 +43,24 @@ const decoratedRooms = computed(() => [
|
||||
])
|
||||
const visibleRooms = computed(() => decoratedRooms.value.filter(room => !hiddenRoomKeys.value.includes(room.key)))
|
||||
const hiddenRooms = computed(() => decoratedRooms.value.filter(room => hiddenRoomKeys.value.includes(room.key)))
|
||||
const normalizeRoomSearch = value => String(value || '').toLowerCase().normalize('NFKD').replace(/[\u0300-\u036f]/g, '').replace(/ß/g, 'ss')
|
||||
const roomSearchTerms = computed(() => normalizeRoomSearch(roomSearch.value).trim().split(/\s+/).filter(Boolean))
|
||||
function matchesRoomSearch(room) {
|
||||
const text = normalizeRoomSearch([room.name, room.topic, room.projectNumber, room.email, room.ownerName].filter(value => value != null).join(' '))
|
||||
return roomSearchTerms.value.every(term => text.includes(term))
|
||||
}
|
||||
// Filter only the sidebar; the open conversation and its draft keep their selection.
|
||||
const filteredRooms = computed(() => visibleRooms.value.filter(matchesRoomSearch))
|
||||
const filteredHiddenRooms = computed(() => hiddenRooms.value.filter(matchesRoomSearch))
|
||||
const groupedRooms = computed(() => ['Räume', 'Projekte', 'Direktnachrichten', 'Zusammenarbeit']
|
||||
.map(label => ({ label, rooms: visibleRooms.value.filter(room => room.group === label) }))
|
||||
.map(label => ({ label, rooms: filteredRooms.value.filter(room => room.group === label) }))
|
||||
.filter(group => group.rooms.length))
|
||||
const activeRoom = computed(() => visibleRooms.value.find(room => room.key === activeRoomKey.value) || null)
|
||||
const isCollaboration = computed(() => activeRoom.value?.source === 'collaboration')
|
||||
const isInternal = computed(() => activeRoom.value?.source === 'internal')
|
||||
const { draft, draftImage, draftSending, clearDraft, startDraftSend, finishDraftSend } = useChatDraft(() => isInternal.value ? activeRoomKey.value : '')
|
||||
|
||||
function clearMessages() { messages.value = []; members.value = []; draft.value = ''; draftImage.value = null; syncAfterId = 0; roomLoading.value = false; sending.value = false }
|
||||
function clearMessages() { messages.value = []; members.value = []; syncAfterId = 0; roomLoading.value = false; sending.value = false }
|
||||
function mergeMessages(incoming) {
|
||||
const byId = new Map(messages.value.map(message => [message.id, message]))
|
||||
for (const message of incoming || []) byId.set(message.id, message)
|
||||
@@ -210,14 +221,17 @@ async function respondToInvitation(id, accept) {
|
||||
async function sendMessage() {
|
||||
const text = draft.value.trim(), image = draftImage.value, request = selection()
|
||||
if ((!text && !image) || sending.value || !isInternal.value || !activeRoom.value?.exists) return
|
||||
sending.value = true; draft.value = ''
|
||||
const savedDraft = startDraftSend()
|
||||
if (!savedDraft) return
|
||||
sending.value = true
|
||||
try {
|
||||
const message = await $api(nativeEndpoint(request.key, '/messages'), { method: 'POST', body: { text, ...(image ? { image } : {}) } })
|
||||
clearDraft(savedDraft)
|
||||
if (!currentSelection(request)) return
|
||||
draftImage.value = null; mergeMessages([message]); await markRead(request); await scrollToBottom(request)
|
||||
mergeMessages([message]); await markRead(request); await scrollToBottom(request)
|
||||
} catch (error) {
|
||||
if (currentSelection(request)) { draft.value = text; toast.add({ title: errorMessage(error), color: 'error' }) }
|
||||
} finally { if (currentSelection(request)) sending.value = false }
|
||||
if (currentSelection(request)) toast.add({ title: errorMessage(error), color: 'error' })
|
||||
} finally { finishDraftSend(savedDraft); if (currentSelection(request)) sending.value = false }
|
||||
}
|
||||
async function pollMessages() {
|
||||
if (pollBusy || loading.value || roomLoading.value || document.hidden || !isInternal.value || !activeRoom.value?.exists) return
|
||||
@@ -242,6 +256,7 @@ async function initialize() {
|
||||
baseRooms.value = []; projectRooms.value = []; directRooms.value = []; collaborationRooms.value = []; invitations.value = []
|
||||
unreadRooms.value = {}; invitationBusy.value = ''; collaborationError.value = ''; listError.value = ''; creating.value = false
|
||||
hiddenRoomKeys.value = []; showHiddenRooms.value = false; preferenceBusy.value = ''; preferenceError.value = ''; preferencesReady.value = false
|
||||
roomSearch.value = ''
|
||||
showRoomForm.value = false; Object.assign(roomForm, { name: '', key: '', topic: '' })
|
||||
activeRoomKey.value = requestedRoom(); loading.value = true
|
||||
await Promise.all([refreshLists(), loadRoomPreferences(scope)])
|
||||
@@ -287,6 +302,12 @@ onBeforeUnmount(() => {
|
||||
<UButton icon="i-heroicons-plus" color="neutral" variant="ghost" size="sm" @click="showRoomForm = !showRoomForm" />
|
||||
</div>
|
||||
|
||||
<UInput v-model="roomSearch" icon="i-heroicons-magnifying-glass" placeholder="Chats suchen …" aria-label="Chats suchen" class="mb-4 w-full" @keydown.esc="roomSearch = ''">
|
||||
<template v-if="roomSearch" #trailing>
|
||||
<UButton icon="i-heroicons-x-mark" color="neutral" variant="link" size="xs" aria-label="Chatsuche löschen" @click="roomSearch = ''" />
|
||||
</template>
|
||||
</UInput>
|
||||
|
||||
<form v-if="showRoomForm" class="mb-4 space-y-2 rounded-lg bg-gray-50 p-3" @submit.prevent="createRoom">
|
||||
<UInput v-model="roomForm.name" placeholder="Raumname" autofocus />
|
||||
<UInput v-model="roomForm.key" :placeholder="roomKeyPreview || 'raumschluessel'" />
|
||||
@@ -339,13 +360,14 @@ onBeforeUnmount(() => {
|
||||
<UButton icon="i-heroicons-eye-slash" color="neutral" variant="ghost" size="xs" class="mr-1 shrink-0" :aria-label="`${room.name} ausblenden`" title="Für mich ausblenden" :disabled="!preferencesReady || !!preferenceBusy" @click="setRoomHidden(room, true)" />
|
||||
</div>
|
||||
</section>
|
||||
<p v-if="!visibleRooms.length" class="px-2 text-sm text-gray-500">Keine sichtbaren Räume. Du kannst ausgeblendete Räume unten wieder einblenden.</p>
|
||||
<section v-if="hiddenRooms.length" aria-label="Ausgeblendete Räume">
|
||||
<p v-if="roomSearchTerms.length && !filteredRooms.length && !filteredHiddenRooms.length" role="status" class="px-2 text-sm text-gray-500">Keine Chats für diese Suche gefunden.</p>
|
||||
<p v-else-if="!roomSearchTerms.length && !visibleRooms.length" class="px-2 text-sm text-gray-500">Keine sichtbaren Räume. Du kannst ausgeblendete Räume unten wieder einblenden.</p>
|
||||
<section v-if="filteredHiddenRooms.length" aria-label="Ausgeblendete Räume">
|
||||
<button type="button" class="flex w-full items-center justify-between px-2 py-2 text-left text-xs font-semibold text-gray-500" :aria-expanded="showHiddenRooms" @click="showHiddenRooms = !showHiddenRooms">
|
||||
<span>Ausgeblendete Räume ({{ hiddenRooms.length }})</span><UIcon :name="showHiddenRooms ? 'i-heroicons-chevron-up' : 'i-heroicons-chevron-down'" />
|
||||
<span>Ausgeblendete Räume ({{ filteredHiddenRooms.length }})</span><UIcon :name="showHiddenRooms ? 'i-heroicons-chevron-up' : 'i-heroicons-chevron-down'" />
|
||||
</button>
|
||||
<div v-if="showHiddenRooms" class="space-y-1">
|
||||
<div v-for="room in hiddenRooms" :key="room.key" class="flex items-center gap-2 px-2 py-1">
|
||||
<div v-for="room in filteredHiddenRooms" :key="room.key" class="flex items-center gap-2 px-2 py-1">
|
||||
<span class="min-w-0 flex-1 truncate text-sm text-gray-500">{{ room.name }}</span>
|
||||
<UButton icon="i-heroicons-eye" variant="ghost" color="neutral" size="xs" :aria-label="`${room.name} einblenden`" :disabled="!!preferenceBusy" @click="setRoomHidden(room, false)">Einblenden</UButton>
|
||||
</div>
|
||||
@@ -386,7 +408,7 @@ onBeforeUnmount(() => {
|
||||
</ChatReactions>
|
||||
</div>
|
||||
|
||||
<ChatComposer :key="`${session}:${activeRoomKey}`" v-model="draft" v-model:image="draftImage" :busy="sending" :disabled="!activeRoom?.exists || roomLoading" @send="sendMessage" />
|
||||
<ChatComposer :key="`${session}:${activeRoomKey}`" v-model="draft" v-model:image="draftImage" :busy="sending || draftSending" :disabled="!activeRoom?.exists || roomLoading" @send="sendMessage" />
|
||||
</main>
|
||||
|
||||
<aside v-if="!isCollaboration" class="hidden min-h-0 overflow-y-auto border-l border-gray-200 p-4 lg:block">
|
||||
|
||||
@@ -104,10 +104,36 @@ const bankaccounts = ref([])
|
||||
const texttemplates = ref([])
|
||||
const units = ref([])
|
||||
const tenantUsers = ref([])
|
||||
const documentTypeItems = computed(() => Object.keys(dataStore.documentTypesForCreation).map((key) => ({
|
||||
label: dataStore.documentTypesForCreation[key].labelSingle,
|
||||
type: key
|
||||
})))
|
||||
const originalDocumentType = ref(null)
|
||||
const canUseAdvanceInvoice = computed(() => originalDocumentType.value === 'advanceInvoices' || (
|
||||
route.query.type === 'advanceInvoices'
|
||||
&& route.query.loadMode === 'advanceInvoice'
|
||||
&& Number.isSafeInteger(Number(route.query.project))
|
||||
&& Number(route.query.project) > 0
|
||||
&& !route.params.id
|
||||
&& !route.query.createddocument
|
||||
&& !route.query.optionsToImport
|
||||
&& !route.query.linkedDocuments
|
||||
&& !route.query.templateId
|
||||
&& !isTemplateMode.value
|
||||
))
|
||||
const documentTypeItems = computed(() => Object.keys(dataStore.documentTypesForCreation)
|
||||
.filter(key => key !== 'advanceInvoices' || canUseAdvanceInvoice.value)
|
||||
.map((key) => ({
|
||||
label: dataStore.documentTypesForCreation[key].labelSingle,
|
||||
type: key
|
||||
})))
|
||||
const validateAdvanceInvoiceCreation = () => {
|
||||
if (itemInfo.value.type !== 'advanceInvoices' || isTemplateMode.value) return true
|
||||
if (canUseAdvanceInvoice.value && (route.params.id || normalizeEntityId(itemInfo.value.project))) return true
|
||||
|
||||
toast.add({
|
||||
title: 'Abschlagsrechnung nur im Projekt erstellen',
|
||||
description: 'Bitte den Button „Abschlagsrechnung“ innerhalb eines Projekts verwenden.',
|
||||
color: 'error'
|
||||
})
|
||||
return false
|
||||
}
|
||||
const taxTypeItems = [
|
||||
{ key: 'Standard', label: 'Standard' },
|
||||
{ key: '13b UStG', label: '13b UStG' },
|
||||
@@ -391,6 +417,7 @@ const setupPage = async () => {
|
||||
if (route.params.id) {
|
||||
console.log(route.params)
|
||||
itemInfo.value = await useEntities("createddocuments").selectSingle(route.params.id,'',false)
|
||||
originalDocumentType.value = itemInfo.value.type
|
||||
itemInfo.value.rows = normalizeCreatedDocumentRows(itemInfo.value.rows)
|
||||
itemInfo.value.taxType = normalizeTaxTypeValue(itemInfo.value.taxType)
|
||||
await setContactPersonData()
|
||||
@@ -699,6 +726,16 @@ const setupPage = async () => {
|
||||
|
||||
|
||||
itemInfo.value.rows = normalizeCreatedDocumentRows(itemInfo.value.rows)
|
||||
if (!validateAdvanceInvoiceCreation()) {
|
||||
await router.replace('/createDocument')
|
||||
return
|
||||
}
|
||||
|
||||
if (route.query.regeneratePdf && route.params.id) {
|
||||
await regenerateMissingPdf()
|
||||
return
|
||||
}
|
||||
|
||||
loaded.value = true
|
||||
|
||||
}
|
||||
@@ -1817,6 +1854,7 @@ const saveDocumentTemplate = async () => {
|
||||
}
|
||||
|
||||
const saveDocument = async (state, resetup = false) => {
|
||||
if (!validateAdvanceInvoiceCreation()) return
|
||||
|
||||
itemInfo.value.state = state
|
||||
normalizeCustomSurchargePercentage()
|
||||
@@ -1948,38 +1986,7 @@ const closeDocument = async () => {
|
||||
|
||||
await saveDocument("Gebucht")
|
||||
|
||||
await generateDocument()
|
||||
|
||||
let fileData = {}
|
||||
|
||||
fileData.project = itemInfo.value.project
|
||||
fileData.createddocument = itemInfo.value.id
|
||||
|
||||
let mappedType = documentStorageFallbackTypes[itemInfo.value.type] || itemInfo.value.type
|
||||
|
||||
const folders = await useEntities("folders").select()
|
||||
console.log(folders)
|
||||
fileData.folder = folders.find(i => i.function === mappedType && i.year === Number(dayjs().format("YYYY"))).id
|
||||
|
||||
const tags = await useEntities("filetags").select()
|
||||
console.log(tags)
|
||||
fileData.type = tags.find(i => i.createdDocumentType === mappedType).id
|
||||
|
||||
function dataURLtoFile(dataurl, filename) {
|
||||
var arr = dataurl.split(","),
|
||||
mime = arr[0].match(/:(.*?);/)[1],
|
||||
bstr = atob(arr[arr.length - 1]),
|
||||
n = bstr.length,
|
||||
u8arr = new Uint8Array(n);
|
||||
while (n--) {
|
||||
u8arr[n] = bstr.charCodeAt(n);
|
||||
}
|
||||
return new File([u8arr], filename, {type: mime});
|
||||
}
|
||||
|
||||
let file = dataURLtoFile(uri.value, `${itemInfo.value.documentNumber}.pdf`)
|
||||
|
||||
await useFiles().uploadFiles(fileData, [file])
|
||||
await uploadGeneratedDocument()
|
||||
|
||||
guard.value = false
|
||||
|
||||
@@ -1989,6 +1996,77 @@ const closeDocument = async () => {
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
// Erzeugt die PDF aus dem aktuellen Stand und hängt sie an den Beleg an, ohne den Datensatz zu speichern
|
||||
const uploadGeneratedDocument = async () => {
|
||||
await generateDocument()
|
||||
|
||||
if (!uri.value) throw new Error("PDF konnte nicht erzeugt werden")
|
||||
|
||||
let fileData = {}
|
||||
|
||||
fileData.project = itemInfo.value.project
|
||||
fileData.createddocument = itemInfo.value.id
|
||||
|
||||
let mappedType = documentStorageFallbackTypes[itemInfo.value.type] || itemInfo.value.type
|
||||
|
||||
const folders = await useEntities("folders").select()
|
||||
console.log(folders)
|
||||
fileData.folder = folders.find(i => i.function === mappedType && i.year === Number(dayjs().format("YYYY"))).id
|
||||
|
||||
const tags = await useEntities("filetags").select()
|
||||
console.log(tags)
|
||||
fileData.type = tags.find(i => i.createdDocumentType === mappedType).id
|
||||
|
||||
function dataURLtoFile(dataurl, filename) {
|
||||
var arr = dataurl.split(","),
|
||||
mime = arr[0].match(/:(.*?);/)[1],
|
||||
bstr = atob(arr[arr.length - 1]),
|
||||
n = bstr.length,
|
||||
u8arr = new Uint8Array(n);
|
||||
while (n--) {
|
||||
u8arr[n] = bstr.charCodeAt(n);
|
||||
}
|
||||
return new File([u8arr], filename, {type: mime});
|
||||
}
|
||||
|
||||
let file = dataURLtoFile(uri.value, `${itemInfo.value.documentNumber}.pdf`)
|
||||
|
||||
await useFiles().uploadFiles(fileData, [file])
|
||||
}
|
||||
|
||||
const regenerateMissingPdf = async () => {
|
||||
guard.value = false
|
||||
const showPath = `/createDocument/show/${route.params.id}`
|
||||
|
||||
try {
|
||||
const document = await useEntities("createddocuments").selectSingle(route.params.id, "*,files(*)")
|
||||
|
||||
if (document?.state === "Entwurf" || document?.type === "serialInvoices") {
|
||||
toast.add({ title: "PDF kann nur für fertiggestellte Belege nacherzeugt werden", color: "error" })
|
||||
} else if ((document?.files || []).length > 0) {
|
||||
toast.add({ title: "Am Beleg ist bereits ein Dokument angehängt", color: "warning" })
|
||||
} else {
|
||||
// Vertrags- und Mandats-Watcher überschreiben beim Laden die Zahlungsdaten, für die PDF gilt der gespeicherte Stand
|
||||
const restoreStoredPaymentData = () => {
|
||||
itemInfo.value.payment_type = document.payment_type
|
||||
itemInfo.value.outgoingsepamandate = normalizeEntityId(document.outgoingsepamandate)
|
||||
}
|
||||
await nextTick()
|
||||
restoreStoredPaymentData()
|
||||
await nextTick()
|
||||
restoreStoredPaymentData()
|
||||
|
||||
await uploadGeneratedDocument()
|
||||
toast.add({ title: "PDF nacherzeugt", color: "success" })
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(error)
|
||||
toast.add({ title: "PDF konnte nicht nacherzeugt werden", description: error?.data?.error || error?.message, color: "error" })
|
||||
}
|
||||
|
||||
await router.replace(showPath)
|
||||
}
|
||||
|
||||
const getTextTemplateByType = (type, pos) => {
|
||||
|
||||
@@ -110,10 +110,18 @@ const setupPage = async () => {
|
||||
links.value = createddocuments.filter(i => i.createddocument?.id === itemInfo.value.id)
|
||||
}
|
||||
|
||||
linkedDocument.value = await useFiles().selectDocument(itemInfo.value.files[0].id)
|
||||
if (itemInfo.value.files?.length > 0) {
|
||||
linkedDocument.value = await useFiles().selectDocument(itemInfo.value.files[0].id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const canRegeneratePdf = computed(() => itemInfo.value.id
|
||||
&& itemInfo.value.state !== 'Entwurf'
|
||||
&& itemInfo.value.type !== 'serialInvoices'
|
||||
&& Array.isArray(itemInfo.value.files)
|
||||
&& itemInfo.value.files.length === 0)
|
||||
|
||||
setupPage()
|
||||
|
||||
const getStatementLike = (allocation) => allocation?.bankstatement || (typeof allocation?.bs_id === "object" ? allocation.bs_id : null)
|
||||
@@ -282,6 +290,12 @@ const togglePortalRelease = async () => {
|
||||
:loading="costCentresLoading"
|
||||
@click="openCostCentres"
|
||||
>Kostenstellen bearbeiten</UButton>
|
||||
<UButton
|
||||
v-if="canRegeneratePdf"
|
||||
icon="i-heroicons-document-arrow-down"
|
||||
variant="outline"
|
||||
@click="router.push(`/createDocument/edit/${itemInfo.id}?regeneratePdf=1`)"
|
||||
>PDF nacherzeugen</UButton>
|
||||
<!-- <UButton
|
||||
:to="dataStore.documents.find(i => i.createdDocument === itemInfo.id) ? dataStore.documents.find(i => i.createdDocument === itemInfo.id).url : ''"
|
||||
target="_blank"
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
<script setup lang="ts">
|
||||
import dayjs from "dayjs"
|
||||
import { getPortalColor, portalThemeStyle } from "~/utils/portalTheme"
|
||||
|
||||
definePageMeta({
|
||||
layout: "notLoggedIn"
|
||||
@@ -7,6 +8,7 @@ definePageMeta({
|
||||
|
||||
const auth = useAuthStore()
|
||||
const toast = useToast()
|
||||
const portalTheme = computed(() => portalThemeStyle(getPortalColor(auth.activeTenantData?.portalConfig)))
|
||||
|
||||
const customer = ref<any | null>(null)
|
||||
const contracts = ref<any[]>([])
|
||||
@@ -337,7 +339,7 @@ onMounted(async () => {
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="min-h-screen bg-gradient-to-b from-neutral-50 via-white to-neutral-100">
|
||||
<div :style="portalTheme" class="min-h-screen bg-gradient-to-b from-neutral-50 via-white to-neutral-100">
|
||||
<UContainer class="py-8 lg:py-12">
|
||||
<div class="flex flex-col gap-6">
|
||||
<div class="rounded-3xl border border-neutral-200 bg-white/90 p-6 shadow-sm lg:p-8">
|
||||
@@ -392,7 +394,7 @@ onMounted(async () => {
|
||||
</div>
|
||||
|
||||
<UCard v-else :ui="{ body: 'p-4 sm:p-6' }">
|
||||
<UTabs v-model="activeTab" :items="portalTabs" class="portal-tabs">
|
||||
<UTabs v-model="activeTab" :items="portalTabs" :ui="{ trigger: 'data-[state=active]:text-[var(--portal-accent-contrast)]' }" class="portal-tabs">
|
||||
<template #customer>
|
||||
<div class="pt-4">
|
||||
<div class="mb-4 flex items-center justify-between gap-4">
|
||||
@@ -470,7 +472,7 @@ onMounted(async () => {
|
||||
</div>
|
||||
|
||||
<div class="mt-6 flex justify-end">
|
||||
<UButton icon="i-heroicons-check" :loading="saving" @click="saveCustomerData">
|
||||
<UButton icon="i-heroicons-check" class="text-[var(--portal-accent-contrast)]" :loading="saving" @click="saveCustomerData">
|
||||
Kundendaten speichern
|
||||
</UButton>
|
||||
</div>
|
||||
@@ -770,7 +772,7 @@ onMounted(async () => {
|
||||
</div>
|
||||
</UContainer>
|
||||
|
||||
<UModal v-model:open="contractChangeModalOpen">
|
||||
<UModal v-model:open="contractChangeModalOpen" :content="{ style: portalTheme }">
|
||||
<template #content>
|
||||
<div class="space-y-5 p-6">
|
||||
<div>
|
||||
@@ -787,6 +789,7 @@ onMounted(async () => {
|
||||
<USelectMenu
|
||||
v-model="contractChangeForm.contracttype"
|
||||
:items="selectedContractAllowedContracttypes"
|
||||
:content="{ style: portalTheme }"
|
||||
value-key="id"
|
||||
label-key="name"
|
||||
class="w-full"
|
||||
@@ -813,6 +816,7 @@ onMounted(async () => {
|
||||
</UButton>
|
||||
<UButton
|
||||
color="primary"
|
||||
class="text-[var(--portal-accent-contrast)]"
|
||||
:loading="submittingContractRequest"
|
||||
:disabled="!contractChangeForm.contracttype"
|
||||
@click="submitContractChangeRequest"
|
||||
@@ -824,7 +828,7 @@ onMounted(async () => {
|
||||
</template>
|
||||
</UModal>
|
||||
|
||||
<UModal v-model:open="cancellationModalOpen">
|
||||
<UModal v-model:open="cancellationModalOpen" :content="{ style: portalTheme }">
|
||||
<template #content>
|
||||
<div class="space-y-5 p-6">
|
||||
<div>
|
||||
|
||||
206
frontend/pages/events/index.vue
Normal file
206
frontend/pages/events/index.vue
Normal file
@@ -0,0 +1,206 @@
|
||||
<script setup>
|
||||
import dayjs from 'dayjs'
|
||||
|
||||
definePageMeta({ alias: ['/standardEntity/events'] })
|
||||
useHead({ title: 'Termine · FEDEO' })
|
||||
|
||||
const auth = useAuthStore()
|
||||
const { has } = usePermission()
|
||||
const eventEntities = useEntities('events')
|
||||
const canView = computed(() => has('events') && auth.activeTenantData?.features?.calendar !== false)
|
||||
const canCreate = computed(() => canView.value && has('events-create'))
|
||||
const events = ref([])
|
||||
const total = ref(0)
|
||||
const loading = ref(false)
|
||||
const error = ref('')
|
||||
const search = ref('')
|
||||
const status = ref('all')
|
||||
const page = ref(1)
|
||||
const pageSize = 25
|
||||
const sortDirection = ref('desc')
|
||||
const createRoute = { path: '/standardEntity/events/create', query: { returnTo: 'events' } }
|
||||
const statusOptions = [
|
||||
{ label: 'Alle Status', value: 'all' },
|
||||
{ label: 'Entwurf', value: 'Entwurf' },
|
||||
{ label: 'Final', value: 'Final' }
|
||||
]
|
||||
const sortOptions = [
|
||||
{ label: 'Beginn: neueste zuerst', value: 'desc' },
|
||||
{ label: 'Beginn: älteste zuerst', value: 'asc' }
|
||||
]
|
||||
const columns = [
|
||||
{ accessorKey: 'name', header: 'Termin' },
|
||||
{ accessorKey: 'startDate', header: 'Zeitraum' },
|
||||
{ accessorKey: 'project', header: 'Projekt' },
|
||||
{ accessorKey: 'state', header: 'Status' },
|
||||
{ id: 'actions', header: '' }
|
||||
]
|
||||
let requestVersion = 0
|
||||
let searchTimer
|
||||
|
||||
const editRoute = (event) => ({
|
||||
path: `/standardEntity/events/edit/${event.id}`,
|
||||
query: { returnTo: 'events' }
|
||||
})
|
||||
const eventTitle = (event) => event.name || event.project?.name || 'Termin ohne Titel'
|
||||
const projectLabel = (event) => {
|
||||
const project = event.project
|
||||
if (!project) return 'Ohne Projekt'
|
||||
if (typeof project !== 'object') return `Projekt ${project}`
|
||||
return [project.projectNumber, project.name].filter(Boolean).join(' · ') || 'Ohne Projekt'
|
||||
}
|
||||
const formatDate = (value) => value && dayjs(value).isValid() ? dayjs(value).format('DD.MM.YYYY HH:mm') : 'Nicht angegeben'
|
||||
const eventColor = (event) => event.color
|
||||
|| (event.quick ? auth.activeTenantData?.calendarConfig?.quickEntry?.color : null)
|
||||
|| auth.activeTenantData?.calendarConfig?.eventTypes?.find((type) => type.label === event.eventtype)?.color
|
||||
|| '#2563eb'
|
||||
|
||||
async function loadEvents() {
|
||||
const version = ++requestVersion
|
||||
if (!canView.value) {
|
||||
events.value = []
|
||||
total.value = 0
|
||||
loading.value = false
|
||||
return
|
||||
}
|
||||
|
||||
loading.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
const result = await eventEntities.selectPaginated({
|
||||
select: '*, project(id,name,projectNumber)',
|
||||
filters: { archived: false, ...(status.value === 'all' ? {} : { state: status.value }) },
|
||||
search: search.value.trim(),
|
||||
sort: [{ field: 'startDate', direction: sortDirection.value }],
|
||||
page: page.value,
|
||||
limit: pageSize
|
||||
})
|
||||
if (version !== requestVersion) return
|
||||
events.value = result.data
|
||||
total.value = result.meta?.total || 0
|
||||
} catch {
|
||||
if (version !== requestVersion) return
|
||||
events.value = []
|
||||
total.value = 0
|
||||
error.value = 'Die Termine konnten nicht geladen werden. Bitte versuche es erneut.'
|
||||
} finally {
|
||||
if (version === requestVersion) loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function reloadFromFirstPage() {
|
||||
clearTimeout(searchTimer)
|
||||
if (page.value !== 1) page.value = 1
|
||||
else loadEvents()
|
||||
}
|
||||
|
||||
function resetFilters() {
|
||||
search.value = ''
|
||||
status.value = 'all'
|
||||
}
|
||||
|
||||
watch(search, () => {
|
||||
++requestVersion
|
||||
loading.value = true
|
||||
clearTimeout(searchTimer)
|
||||
searchTimer = setTimeout(reloadFromFirstPage, 250)
|
||||
})
|
||||
watch([status, sortDirection, canView, () => auth.activeTenant], reloadFromFirstPage)
|
||||
watch(page, loadEvents)
|
||||
onBeforeUnmount(() => {
|
||||
clearTimeout(searchTimer)
|
||||
++requestVersion
|
||||
})
|
||||
loadEvents()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<UDashboardNavbar title="Termine" :badge="total">
|
||||
<template #right>
|
||||
<UButton v-if="canCreate" :to="createRoute" icon="i-heroicons-plus" label="Neuer Termin" />
|
||||
</template>
|
||||
</UDashboardNavbar>
|
||||
|
||||
<UDashboardPanelContent class="space-y-4">
|
||||
<UAlert v-if="!canView" color="neutral" variant="subtle" title="Termine sind für deinen Zugang nicht verfügbar." />
|
||||
<template v-else>
|
||||
<div class="flex flex-col gap-3 lg:flex-row lg:items-center">
|
||||
<UInput
|
||||
v-model="search"
|
||||
icon="i-heroicons-magnifying-glass"
|
||||
placeholder="Termin, Projekt oder Projektnummer suchen …"
|
||||
aria-label="Termine durchsuchen"
|
||||
class="w-full lg:flex-1"
|
||||
/>
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<USelect v-model="status" :items="statusOptions" aria-label="Status filtern" class="min-w-36 flex-1 lg:flex-none" />
|
||||
<USelect v-model="sortDirection" :items="sortOptions" aria-label="Termine sortieren" class="min-w-48 flex-1 lg:flex-none" />
|
||||
<UButton color="neutral" variant="outline" icon="i-heroicons-arrow-path" aria-label="Termine aktualisieren" :loading="loading" @click="loadEvents" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<UAlert v-if="error" color="error" variant="subtle" title="Laden fehlgeschlagen" :description="error">
|
||||
<template #actions>
|
||||
<UButton color="error" variant="outline" label="Erneut versuchen" @click="loadEvents" />
|
||||
</template>
|
||||
</UAlert>
|
||||
<div v-else-if="loading" class="space-y-3 py-4" role="status" aria-label="Termine werden geladen">
|
||||
<USkeleton v-for="index in 5" :key="index" class="h-20 w-full rounded-lg" />
|
||||
</div>
|
||||
<div v-else-if="!events.length" class="rounded-xl border border-dashed border-default px-4 py-14 text-center">
|
||||
<UIcon name="i-heroicons-calendar-days" class="mx-auto mb-3 size-10 text-muted" />
|
||||
<h2 class="text-lg font-semibold">{{ search || status !== 'all' ? 'Keine passenden Termine' : 'Noch keine Termine' }}</h2>
|
||||
<p class="mt-1 text-sm text-muted">{{ search || status !== 'all' ? 'Passe deine Suche oder den Statusfilter an.' : 'Erstelle deinen ersten Termin direkt über diese Übersicht.' }}</p>
|
||||
<UButton v-if="search || status !== 'all'" class="mt-4" color="neutral" variant="outline" label="Filter zurücksetzen" @click="resetFilters" />
|
||||
<UButton v-else-if="canCreate" class="mt-4" :to="createRoute" icon="i-heroicons-plus" label="Neuer Termin" />
|
||||
</div>
|
||||
<template v-else>
|
||||
<UTable :data="events" :columns="columns" class="hidden rounded-xl border border-default md:block" :ui="{ td: 'align-top' }">
|
||||
<template #name-cell="{ row }">
|
||||
<div class="flex items-start gap-3">
|
||||
<span class="mt-1 size-3 shrink-0 rounded-full" :style="{ backgroundColor: eventColor(row.original) }" aria-hidden="true" />
|
||||
<div class="min-w-0">
|
||||
<NuxtLink :to="editRoute(row.original)" class="block max-w-sm whitespace-normal break-words font-medium text-highlighted hover:text-primary">{{ eventTitle(row.original) }}</NuxtLink>
|
||||
<p v-if="row.original.repeatInterval && row.original.repeatInterval !== 'Keine Wiederholung'" class="mt-1 text-xs text-muted">{{ row.original.repeatInterval }}</p>
|
||||
<p v-if="row.original.quick" class="mt-1 text-xs text-muted">Quick-Eintrag</p>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
<template #startDate-cell="{ row }">
|
||||
<div>{{ formatDate(row.original.startDate) }}</div>
|
||||
<div v-if="row.original.endDate" class="mt-1 text-xs text-muted">bis {{ formatDate(row.original.endDate) }}</div>
|
||||
</template>
|
||||
<template #project-cell="{ row }">
|
||||
<span class="block max-w-xs whitespace-normal break-words">{{ projectLabel(row.original) }}</span>
|
||||
</template>
|
||||
<template #state-cell="{ row }">
|
||||
<UBadge :color="row.original.state === 'Entwurf' ? 'warning' : 'success'" variant="subtle">{{ row.original.state || 'Final' }}</UBadge>
|
||||
</template>
|
||||
<template #actions-cell="{ row }">
|
||||
<UButton :to="editRoute(row.original)" color="neutral" variant="ghost" icon="i-heroicons-pencil-square" :aria-label="`${eventTitle(row.original)} bearbeiten`" />
|
||||
</template>
|
||||
</UTable>
|
||||
|
||||
<div class="space-y-3 md:hidden">
|
||||
<NuxtLink v-for="event in events" :key="event.id" :to="editRoute(event)" class="block rounded-xl border border-default p-4 hover:border-primary">
|
||||
<div class="flex items-start gap-3">
|
||||
<span class="mt-1 size-3 shrink-0 rounded-full" :style="{ backgroundColor: eventColor(event) }" aria-hidden="true" />
|
||||
<h2 class="min-w-0 flex-1 break-words font-semibold text-highlighted">{{ eventTitle(event) }}</h2>
|
||||
<UBadge :color="event.state === 'Entwurf' ? 'warning' : 'success'" variant="subtle" class="shrink-0">{{ event.state || 'Final' }}</UBadge>
|
||||
</div>
|
||||
<p class="mt-3 text-sm">{{ formatDate(event.startDate) }}</p>
|
||||
<p v-if="event.endDate" class="text-sm text-muted">bis {{ formatDate(event.endDate) }}</p>
|
||||
<p class="mt-2 break-words text-sm text-muted">{{ projectLabel(event) }}</p>
|
||||
<p v-if="event.repeatInterval && event.repeatInterval !== 'Keine Wiederholung'" class="mt-2 text-xs text-muted">{{ event.repeatInterval }}</p>
|
||||
<p v-if="event.quick" class="mt-1 text-xs text-muted">Quick-Eintrag</p>
|
||||
</NuxtLink>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-wrap items-center justify-between gap-3 border-t border-default pt-4">
|
||||
<p class="text-sm text-muted">{{ total }} {{ total === 1 ? 'Termin' : 'Termine' }}</p>
|
||||
<UPagination v-model:page="page" :total="total" :items-per-page="pageSize" :sibling-count="0" />
|
||||
</div>
|
||||
</template>
|
||||
</template>
|
||||
</UDashboardPanelContent>
|
||||
</template>
|
||||
@@ -200,6 +200,47 @@ const getAccountLabel = (item) => {
|
||||
return account ? `${account.number || ""} ${account.label || ""}`.trim() : "-"
|
||||
}
|
||||
const getCostCentreLabel = (item) => costcentres.value.find((costcentre) => costcentre.id === item.costCentre)?.name || "-"
|
||||
|
||||
const canEditCostCentres = computed(() => mode.value === "show" && Boolean(itemInfo.value.id) && !itemInfo.value.archived)
|
||||
const costCentresOpen = ref(false)
|
||||
const costCentresSaving = ref(false)
|
||||
const costCentreDraft = ref([])
|
||||
const costCentreOptionLabel = (id) => {
|
||||
const centre = costcentres.value.find((item) => item.id === id)
|
||||
return centre ? [centre.number, centre.name].filter(Boolean).join(" - ") : (id ? "Bisherige Kostenstelle" : "Keine Kostenstelle")
|
||||
}
|
||||
|
||||
const openCostCentres = () => {
|
||||
costCentreDraft.value = (itemInfo.value.accounts || []).map((account, index) => ({
|
||||
index,
|
||||
label: `${index + 1}. ${account.description || getAccountLabel(account)}`,
|
||||
costcentre: account.costCentre || null,
|
||||
}))
|
||||
costCentresOpen.value = true
|
||||
}
|
||||
|
||||
const saveCostCentres = async () => {
|
||||
if (costCentresSaving.value) return
|
||||
costCentresSaving.value = true
|
||||
try {
|
||||
const accountCostCentres = costCentreDraft.value
|
||||
.filter((row) => row.costcentre !== (itemInfo.value.accounts[row.index]?.costCentre || null))
|
||||
.map(({ index, costcentre }) => ({ index, costcentre }))
|
||||
if (accountCostCentres.length) {
|
||||
const { invoice } = await useNuxtApp().$api(`/api/functions/incoming-invoices/${itemInfo.value.id}/cost-centres`, {
|
||||
method: "PUT",
|
||||
body: { accountCostCentres },
|
||||
})
|
||||
itemInfo.value.accounts = normalizeIncomingInvoiceAccounts(invoice.accounts || [], invoice.date)
|
||||
toast.add({ title: "Kostenstellen gespeichert", color: "success" })
|
||||
}
|
||||
costCentresOpen.value = false
|
||||
} catch (error) {
|
||||
toast.add({ title: "Kostenstellen konnten nicht gespeichert werden", description: error?.data?.error || "Bitte versuche es erneut.", color: "error" })
|
||||
} finally {
|
||||
costCentresSaving.value = false
|
||||
}
|
||||
}
|
||||
const getBookingModeLabel = (item) => EXPENSE_BOOKING_MODE_ITEMS.find((mode) => mode.value === item.bookingMode)?.label || "-"
|
||||
const getTaxLabel = (item) => taxOptions.value.find((tax) => tax.key === item.taxType)?.label || "-"
|
||||
|
||||
@@ -362,6 +403,14 @@ const hasBlockingIncomingInvoiceErrors = computed(() => blockingIncomingInvoiceE
|
||||
>
|
||||
Bearbeiten
|
||||
</UButton>
|
||||
<UButton
|
||||
v-if="canEditCostCentres"
|
||||
icon="i-heroicons-tag"
|
||||
variant="outline"
|
||||
@click="openCostCentres"
|
||||
>
|
||||
Kostenstellen bearbeiten
|
||||
</UButton>
|
||||
<ArchiveButton
|
||||
v-if="canArchiveIncomingInvoice"
|
||||
color="error"
|
||||
@@ -1060,6 +1109,27 @@ const hasBlockingIncomingInvoiceErrors = computed(() => blockingIncomingInvoiceE
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<UModal v-model:open="costCentresOpen" title="Kostenstellen bearbeiten" :dismissible="!costCentresSaving" :close="!costCentresSaving" :ui="{ content: 'sm:max-w-2xl' }">
|
||||
<template #body>
|
||||
<p class="mb-4 text-sm text-muted">Die Kostenstellen der Positionen können jederzeit geändert werden, auch bei gebuchten oder zugewiesenen Belegen. Alle anderen Angaben bleiben unverändert.</p>
|
||||
<div class="space-y-4">
|
||||
<UFormField v-for="row in costCentreDraft" :key="row.index" :label="row.label">
|
||||
<InputGroup>
|
||||
<USelectMenu v-model="row.costcentre" :items="costcentres" value-key="id" label-key="name" :filter-fields="['name', 'number']" class="w-full" :disabled="costCentresSaving">
|
||||
<template #default>{{ costCentreOptionLabel(row.costcentre) }}</template>
|
||||
<template #item="{ item }">{{ [item.number, item.name].filter(Boolean).join(' - ') }}</template>
|
||||
</USelectMenu>
|
||||
<UButton icon="i-heroicons-x-mark" variant="outline" :aria-label="`Kostenstelle für ${row.label} entfernen`" :disabled="costCentresSaving || !row.costcentre" @click="row.costcentre = null" />
|
||||
</InputGroup>
|
||||
</UFormField>
|
||||
</div>
|
||||
</template>
|
||||
<template #footer>
|
||||
<UButton variant="outline" :disabled="costCentresSaving" @click="costCentresOpen = false">Abbrechen</UButton>
|
||||
<UButton :loading="costCentresSaving" @click="saveCostCentres">Kostenstellen speichern</UButton>
|
||||
</template>
|
||||
</UModal>
|
||||
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
|
||||
@@ -64,35 +64,89 @@ const setupPage = async () => {
|
||||
items.value = await useEntities(type).select("*, vendor(id,name), statementallocations(id,amount)",sort.value.column,sort.value.direction === "asc")
|
||||
}
|
||||
|
||||
// Funktion zum Vorbereiten der Belege
|
||||
const prepareInvoices = async () => {
|
||||
isPreparing.value = true
|
||||
try {
|
||||
await $api('/api/functions/services/prepareincominginvoices', { method: 'POST' })
|
||||
// Die Belegvorbereitung läuft im Backend im Hintergrund; hier wird nur der Status abgefragt.
|
||||
const preparationEndpoint = '/api/functions/services/prepareincominginvoices'
|
||||
let preparationPollTimer = null
|
||||
|
||||
toast.add({
|
||||
title: 'Erfolg',
|
||||
description: 'Eingangsbelege wurden vorbereitet.',
|
||||
icon: 'i-heroicons-check-circle',
|
||||
color: 'green'
|
||||
})
|
||||
|
||||
// Liste neu laden
|
||||
await setupPage()
|
||||
} catch (error) {
|
||||
console.error(error)
|
||||
const showPreparationResult = (status) => {
|
||||
const result = status?.result
|
||||
if (result?.error && !result.created?.length) {
|
||||
toast.add({
|
||||
title: 'Fehler',
|
||||
description: 'Beim Vorbereiten der Belege ist ein Fehler aufgetreten.',
|
||||
description: result.error,
|
||||
icon: 'i-heroicons-exclamation-circle',
|
||||
color: 'red'
|
||||
})
|
||||
} finally {
|
||||
return
|
||||
}
|
||||
|
||||
const created = result?.created?.length || 0
|
||||
const skipped = result?.skipped?.length || 0
|
||||
toast.add({
|
||||
title: 'Belegvorbereitung abgeschlossen',
|
||||
description: `${created} Eingangsbeleg(e) vorbereitet${skipped ? `, ${skipped} Datei(en) übersprungen` : ''}.`,
|
||||
icon: 'i-heroicons-check-circle',
|
||||
color: 'green'
|
||||
})
|
||||
}
|
||||
|
||||
const pollPreparation = (notify) => {
|
||||
clearTimeout(preparationPollTimer)
|
||||
preparationPollTimer = setTimeout(async () => {
|
||||
try {
|
||||
const status = await $api(preparationEndpoint)
|
||||
if (status?.running) {
|
||||
pollPreparation(notify)
|
||||
return
|
||||
}
|
||||
isPreparing.value = false
|
||||
if (notify) showPreparationResult(status)
|
||||
await setupPage()
|
||||
} catch (error) {
|
||||
console.error(error)
|
||||
pollPreparation(notify)
|
||||
}
|
||||
}, 3000)
|
||||
}
|
||||
|
||||
const prepareInvoices = async () => {
|
||||
isPreparing.value = true
|
||||
try {
|
||||
await $api(preparationEndpoint, { method: 'POST' })
|
||||
toast.add({
|
||||
title: 'Belegvorbereitung gestartet',
|
||||
description: 'Die Belege werden im Hintergrund vorbereitet.',
|
||||
icon: 'i-heroicons-sparkles'
|
||||
})
|
||||
pollPreparation(true)
|
||||
} catch (error) {
|
||||
console.error(error)
|
||||
isPreparing.value = false
|
||||
toast.add({
|
||||
title: 'Fehler',
|
||||
description: 'Die Belegvorbereitung konnte nicht gestartet werden.',
|
||||
icon: 'i-heroicons-exclamation-circle',
|
||||
color: 'red'
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const resumePreparationStatus = async () => {
|
||||
try {
|
||||
const status = await $api(preparationEndpoint)
|
||||
if (status?.running) {
|
||||
isPreparing.value = true
|
||||
pollPreparation(true)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(error)
|
||||
}
|
||||
}
|
||||
|
||||
onBeforeUnmount(() => clearTimeout(preparationPollTimer))
|
||||
|
||||
setupPage()
|
||||
resumePreparationStatus()
|
||||
|
||||
const selectedColumns = ref(tempStore.columns[type] ? [...tempStore.columns[type]] : dataType.templateColumns.filter(i => !i.disabledInTable))
|
||||
if (!selectedColumns.value.find((column) => column.key === openAmountColumnKey)) {
|
||||
|
||||
9
frontend/pages/settings/notifications.vue
Normal file
9
frontend/pages/settings/notifications.vue
Normal file
@@ -0,0 +1,9 @@
|
||||
<template>
|
||||
<UDashboardNavbar title="Benachrichtigungen" />
|
||||
|
||||
<div class="min-h-0 flex-1 overflow-y-auto p-4 sm:p-6">
|
||||
<UCard class="mx-auto w-full max-w-4xl">
|
||||
<NotificationPreferences />
|
||||
</UCard>
|
||||
</div>
|
||||
</template>
|
||||
@@ -3,6 +3,7 @@ import {
|
||||
TAX_EVALUATION_PERIOD_OPTIONS,
|
||||
normalizeTaxEvaluationPeriod
|
||||
} from "~/composables/useTaxEvaluation"
|
||||
import { DEFAULT_PORTAL_COLOR, getPortalColor, normalizePortalColor, portalThemeStyle } from "~/utils/portalTheme"
|
||||
|
||||
const auth = useAuthStore()
|
||||
const toast = useToast()
|
||||
@@ -260,6 +261,16 @@ const setupPage = async () => {
|
||||
|
||||
const features = ref({ ...defaultFeatures, ...(auth.activeTenantData?.features || {}) })
|
||||
const businessInfo = ref(normalizeBusinessInfo(auth.activeTenantData?.businessInfo))
|
||||
const portalColor = ref(getPortalColor(auth.activeTenantData?.portalConfig))
|
||||
const portalColorSaving = ref(false)
|
||||
const validPortalColor = computed(() => normalizePortalColor(portalColor.value))
|
||||
const portalPreviewStyle = computed(() => portalThemeStyle(portalColor.value))
|
||||
watch(() => auth.activeTenant, () => {
|
||||
portalColor.value = getPortalColor(auth.activeTenantData?.portalConfig)
|
||||
})
|
||||
watch(() => auth.activeTenantData?.portalConfig, (config) => {
|
||||
portalColor.value = getPortalColor(config)
|
||||
})
|
||||
const accountChart = ref(auth.activeTenantData.accountChart || "skr03")
|
||||
const taxEvaluationPeriod = ref(normalizeTaxEvaluationPeriod(auth.activeTenantData.taxEvaluationPeriod))
|
||||
const accountChartOptions = [
|
||||
@@ -288,6 +299,18 @@ const saveFeatures = async () => {
|
||||
await updateTenant({features: features.value})
|
||||
}
|
||||
|
||||
const savePortalColor = async () => {
|
||||
if (!validPortalColor.value || portalColorSaving.value) return
|
||||
portalColorSaving.value = true
|
||||
try {
|
||||
const { primayColor, ...portalConfig } = auth.activeTenantData?.portalConfig || {}
|
||||
await updateTenant({ portalConfig: { ...portalConfig, primaryColor: validPortalColor.value } })
|
||||
toast.add({ title: "Akzentfarbe für das Kundenportal gespeichert", color: "success" })
|
||||
} finally {
|
||||
portalColorSaving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const formatMcpTokenDate = (value) => {
|
||||
if (!value) return "Nie"
|
||||
|
||||
@@ -614,6 +637,8 @@ onMounted(() => {
|
||||
label: 'Dokubox'
|
||||
},{
|
||||
label: 'Rechnung & Kontakt'
|
||||
},{
|
||||
label: 'Kundenportal'
|
||||
},{
|
||||
label: 'Plantafel'
|
||||
},{
|
||||
@@ -755,6 +780,43 @@ onMounted(() => {
|
||||
</UCard>
|
||||
|
||||
</div>
|
||||
<div v-else-if="item.label === 'Kundenportal'">
|
||||
<UCard class="mt-5">
|
||||
<div class="max-w-xl space-y-6">
|
||||
<div>
|
||||
<h2 class="text-lg font-semibold">Akzentfarbe im Kundenportal</h2>
|
||||
<p class="mt-1 text-sm text-muted">Wähle die Farbe für Schaltflächen, Reiter und Hervorhebungen im Kundenportal deiner Firma.</p>
|
||||
</div>
|
||||
<UFormField
|
||||
label="Akzentfarbe"
|
||||
help="Hex-Farbwert mit sechs Zeichen, zum Beispiel #69c350."
|
||||
:error="!validPortalColor ? 'Bitte einen gültigen Hex-Farbwert eingeben.' : undefined"
|
||||
>
|
||||
<div class="flex items-center gap-3">
|
||||
<input
|
||||
type="color"
|
||||
:value="validPortalColor || DEFAULT_PORTAL_COLOR"
|
||||
aria-label="Akzentfarbe auswählen"
|
||||
class="h-10 w-14 shrink-0 cursor-pointer rounded border border-default bg-default p-1"
|
||||
@input="portalColor = $event.target.value"
|
||||
>
|
||||
<UInput v-model="portalColor" aria-label="Akzentfarbe als Hex-Wert" placeholder="#69c350" class="w-40" maxlength="7" />
|
||||
</div>
|
||||
</UFormField>
|
||||
<div :style="portalPreviewStyle" class="rounded-xl border border-default p-5" aria-label="Vorschau der Portal-Akzentfarbe">
|
||||
<p class="mb-3 text-sm font-medium text-primary-600">Vorschau Kundenportal</p>
|
||||
<div class="flex flex-wrap items-center gap-3">
|
||||
<UButton class="text-[var(--portal-accent-contrast)]" tabindex="-1">Kundendaten speichern</UButton>
|
||||
<UBadge color="primary" variant="subtle">Rechnung</UBadge>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex flex-wrap gap-3">
|
||||
<UButton :loading="portalColorSaving" :disabled="!validPortalColor" @click="savePortalColor">Akzentfarbe speichern</UButton>
|
||||
<UButton color="neutral" variant="outline" :disabled="portalColorSaving" @click="portalColor = DEFAULT_PORTAL_COLOR">FEDEO-Grün verwenden</UButton>
|
||||
</div>
|
||||
</div>
|
||||
</UCard>
|
||||
</div>
|
||||
<div v-else-if="item.label === 'Plantafel'">
|
||||
<UCard class="mt-5">
|
||||
<UForm class="w-1/2">
|
||||
|
||||
@@ -3231,7 +3231,7 @@ export const useDataStore = defineStore('data', () => {
|
||||
{
|
||||
key: "color",
|
||||
label: "Farbe",
|
||||
inputType: "text",
|
||||
inputType: "color",
|
||||
sortable: true
|
||||
},
|
||||
{
|
||||
@@ -3270,7 +3270,7 @@ export const useDataStore = defineStore('data', () => {
|
||||
inputType: "select",
|
||||
selectDataType: "projects",
|
||||
selectOptionAttribute: "name",
|
||||
selectSearchAttributes: ['name'],
|
||||
selectSearchAttributes: ['name', 'projectNumber'],
|
||||
},{
|
||||
key: "vehicles",
|
||||
label: "Fahrzeuge",
|
||||
|
||||
@@ -19,6 +19,7 @@ export const useProfileStore = defineStore("profile", () => {
|
||||
})
|
||||
|
||||
const profiles = ref([])
|
||||
const allProfiles = ref([])
|
||||
const ownProfiles = ref([])
|
||||
const activeProfile = ref(null)
|
||||
const tenants = ref([])
|
||||
@@ -60,8 +61,8 @@ export const useProfileStore = defineStore("profile", () => {
|
||||
}
|
||||
|
||||
async function fetchData() {
|
||||
await fetchOwnProfiles()
|
||||
await fetchProfiles()
|
||||
await fetchOwnProfiles()
|
||||
await fetchTenants()
|
||||
await fetchOwnTenant()
|
||||
loaded.value = true
|
||||
@@ -71,6 +72,7 @@ export const useProfileStore = defineStore("profile", () => {
|
||||
loaded.value = false
|
||||
ownTenant.value = {}
|
||||
profiles.value = []
|
||||
allProfiles.value = []
|
||||
ownProfiles.value = []
|
||||
tenants.value = []
|
||||
}
|
||||
@@ -92,10 +94,13 @@ export const useProfileStore = defineStore("profile", () => {
|
||||
|
||||
async function fetchProfiles() {
|
||||
try {
|
||||
const res = await useNuxtApp().$api("/api/tenant/profiles")
|
||||
profiles.value = res?.data || []
|
||||
const res = await useNuxtApp().$api("/api/tenant/profiles", { query: { includeArchived: true } })
|
||||
// Retain historical names while keeping archived profiles out of selections.
|
||||
allProfiles.value = res?.data || []
|
||||
profiles.value = allProfiles.value.filter(profile => profile.active && !profile.archived_at)
|
||||
} catch (e) {
|
||||
profiles.value = activeProfile.value ? [activeProfile.value] : []
|
||||
allProfiles.value = profiles.value
|
||||
}
|
||||
}
|
||||
|
||||
@@ -112,7 +117,8 @@ export const useProfileStore = defineStore("profile", () => {
|
||||
})
|
||||
|
||||
const getProfileById = computed(() => (itemId) => {
|
||||
return profiles.value.find((item) => item.id === itemId || item.user_id === itemId)
|
||||
const profile = allProfiles.value.find((item) => item.id === itemId || item.user_id === itemId)
|
||||
return profile ? { ...profile, fullName: profile.full_name || profile.fullName } : { fullName: "Unbekanntes Profil" }
|
||||
})
|
||||
|
||||
return {
|
||||
|
||||
@@ -10,6 +10,71 @@ export const useTempStore = defineStore('temp', () => {
|
||||
const pages = ref({})
|
||||
const settings = ref({})
|
||||
|
||||
// Drafts stay local: temp_config is also returned in tenant profile lists.
|
||||
const chatDrafts = ref({})
|
||||
const sendingChatDrafts = ref({})
|
||||
const loadedChatDrafts = new Set()
|
||||
const draftStoragePrefix = 'fedeo:chat-draft:v1:'
|
||||
const toast = useToast()
|
||||
let draftStorageWarningShown = false
|
||||
|
||||
function getChatDraft(key) {
|
||||
if (!loadedChatDrafts.has(key)) {
|
||||
loadedChatDrafts.add(key)
|
||||
try {
|
||||
const saved = JSON.parse(sessionStorage.getItem(draftStoragePrefix + key) || 'null')
|
||||
if (saved && typeof saved.text === 'string' && typeof saved.clientId === 'string'
|
||||
&& saved.text.length <= 10000 && (!saved.image || (
|
||||
typeof saved.image.name === 'string' && typeof saved.image.dataUrl === 'string'
|
||||
&& saved.image.dataUrl.length <= 480000
|
||||
&& /^data:image\/(jpeg|png|webp);base64,[A-Za-z0-9+/=]+$/.test(saved.image.dataUrl)
|
||||
))) chatDrafts.value[key] = saved
|
||||
} catch { /* Disabled storage or an invalid entry must not block the chat. */ }
|
||||
}
|
||||
return chatDrafts.value[key] || null
|
||||
}
|
||||
|
||||
function setChatDraft(key, draft) {
|
||||
loadedChatDrafts.add(key)
|
||||
if (draft) chatDrafts.value[key] = draft
|
||||
else delete chatDrafts.value[key]
|
||||
try {
|
||||
if (draft) sessionStorage.setItem(draftStoragePrefix + key, JSON.stringify(draft))
|
||||
else sessionStorage.removeItem(draftStoragePrefix + key)
|
||||
} catch {
|
||||
// Do not restore an older version after a failed storage update.
|
||||
try { sessionStorage.removeItem(draftStoragePrefix + key) } catch {}
|
||||
if (!draftStorageWarningShown) {
|
||||
draftStorageWarningShown = true
|
||||
toast.add({ title: 'Entwurf nur vorübergehend gespeichert', description: 'Der Browserspeicher ist voll oder gesperrt. Bis zum Neuladen bleibt dein Entwurf im Chat erhalten.', color: 'warning' })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function isChatDraftSending(key) {
|
||||
return !!sendingChatDrafts.value[key]
|
||||
}
|
||||
|
||||
function startChatDraftSend(key, clientId) {
|
||||
sendingChatDrafts.value[key] = clientId
|
||||
}
|
||||
|
||||
function finishChatDraftSend(key, clientId) {
|
||||
if (sendingChatDrafts.value[key] === clientId) delete sendingChatDrafts.value[key]
|
||||
}
|
||||
|
||||
watch(() => auth.user?.id || auth.user?.user_id, (user, previous) => {
|
||||
if (!previous || user === previous) return
|
||||
chatDrafts.value = {}
|
||||
sendingChatDrafts.value = {}
|
||||
loadedChatDrafts.clear()
|
||||
try {
|
||||
for (const key of Object.keys(sessionStorage)) {
|
||||
if (key.startsWith(draftStoragePrefix)) sessionStorage.removeItem(key)
|
||||
}
|
||||
} catch { /* Storage may be unavailable. In-memory drafts are still cleared. */ }
|
||||
}, { flush: 'sync' })
|
||||
|
||||
const storeTempConfig = async () => {
|
||||
const config = {
|
||||
searchStrings: searchStrings.value,
|
||||
@@ -92,6 +157,11 @@ export const useTempStore = defineStore('temp', () => {
|
||||
}
|
||||
|
||||
return {
|
||||
getChatDraft,
|
||||
setChatDraft,
|
||||
isChatDraftSending,
|
||||
startChatDraftSend,
|
||||
finishChatDraftSend,
|
||||
setStoredTempConfig,
|
||||
searchStrings,
|
||||
modifySearchString,
|
||||
|
||||
131
frontend/tests/advance-invoice-creation.test.cjs
Normal file
131
frontend/tests/advance-invoice-creation.test.cjs
Normal file
@@ -0,0 +1,131 @@
|
||||
const { test } = require('node:test')
|
||||
const assert = require('node:assert/strict')
|
||||
const fs = require('node:fs')
|
||||
const vm = require('node:vm')
|
||||
const ts = require('typescript')
|
||||
const { parse, compileScript } = require('@vue/compiler-sfc')
|
||||
|
||||
const documentTypesForCreation = Object.fromEntries([
|
||||
'invoices', 'advanceInvoices', 'serialInvoices', 'quotes', 'costEstimates',
|
||||
'deliveryNotes', 'packingSlips', 'confirmationOrders', 'cancellationInvoices',
|
||||
].map(key => [key, { labelSingle: key }]))
|
||||
|
||||
function fixture(filename, names, globals = {}) {
|
||||
const { descriptor } = parse(fs.readFileSync(`${__dirname}/../${filename}`, 'utf8'))
|
||||
compileScript(descriptor, { id: filename, inlineTemplate: true })
|
||||
const script = ts.createSourceFile(filename, descriptor.scriptSetup.content, ts.ScriptTarget.Latest, true, ts.ScriptKind.JS)
|
||||
const source = script.statements.filter(statement => ts.isVariableStatement(statement)
|
||||
&& statement.declarationList.declarations.some(declaration => names.includes(declaration.name.getText(script))))
|
||||
.map(statement => statement.getText(script)).join('\n')
|
||||
const navigations = []
|
||||
const notices = []
|
||||
const context = vm.createContext({
|
||||
ref: value => ({ value }), computed: getter => ({ get value() { return getter() } }),
|
||||
dataStore: { documentTypesForCreation }, URLSearchParams,
|
||||
router: { push: url => navigations.push(url), replace: url => navigations.push(url) },
|
||||
modal: { close() {} }, toast: { add: notice => notices.push(notice) },
|
||||
...globals,
|
||||
})
|
||||
vm.runInContext(source, context)
|
||||
return { context, navigations, notices, run: code => vm.runInContext(code, context) }
|
||||
}
|
||||
|
||||
test('copying any document excludes advance invoices and requires an allowed target', () => {
|
||||
for (const type of Object.keys(documentTypesForCreation)) {
|
||||
const { run, navigations } = fixture('components/copyCreatedDocumentModal.vue', [
|
||||
'documentTypeToUse', 'documentTypeItems', 'selectedDocumentType', 'optionsToImport', 'startImport',
|
||||
], { props: { id: '12', type } })
|
||||
assert.equal(run("documentTypeItems.value.some(item => item.key === 'advanceInvoices')"), false)
|
||||
assert.equal(run('documentTypeToUse.value'), type === 'advanceInvoices' ? null : type)
|
||||
run("documentTypeToUse.value = 'advanceInvoices'; startImport()")
|
||||
assert.equal(navigations.length, 0)
|
||||
run("documentTypeToUse.value = 'invoices'; startImport()")
|
||||
const query = new URL(navigations[0], 'http://localhost').searchParams
|
||||
assert.equal(query.get('type'), 'invoices')
|
||||
assert.equal(query.get('createddocument'), '12')
|
||||
}
|
||||
})
|
||||
|
||||
test('+ Dokument excludes advance invoices even when opened inside a project', () => {
|
||||
for (const queryStringData of ['', 'project=7&customer=8']) {
|
||||
const { run, navigations } = fixture('components/createDocumentModal.vue', ['documentTypes', 'createDocument'], {
|
||||
props: { queryStringData },
|
||||
})
|
||||
assert.equal(run("documentTypes.value.some(item => item.key === 'advanceInvoices')"), false)
|
||||
run("createDocument('advanceInvoices')")
|
||||
assert.equal(navigations.length, 0)
|
||||
run("createDocument('quotes')")
|
||||
assert.equal(new URL(navigations[0], 'http://localhost').searchParams.get('type'), 'quotes')
|
||||
}
|
||||
})
|
||||
|
||||
test('advance invoice templates cannot create outgoing documents', () => {
|
||||
const { run, navigations } = fixture('components/createDocumentFromTemplateModal.vue', [
|
||||
'templates', 'selectedType', 'documentTypes', 'visibleTemplates', 'selectTemplate',
|
||||
], { props: { queryStringData: 'project=7' } })
|
||||
run("templates.value = [{ id: 1, documentType: 'advanceInvoices' }, { id: 2, documentType: 'quotes' }]")
|
||||
assert.equal(run("documentTypes.value.some(item => item.key === 'advanceInvoices')"), false)
|
||||
assert.equal(run('visibleTemplates.value.length'), 1)
|
||||
assert.equal(run('visibleTemplates.value[0].id'), 2)
|
||||
run('selectTemplate(templates.value[0])')
|
||||
assert.equal(navigations.length, 0)
|
||||
run('selectTemplate(templates.value[1])')
|
||||
assert.equal(new URL(navigations[0], 'http://localhost').searchParams.get('templateId'), '2')
|
||||
})
|
||||
|
||||
function editorFixture(query = {}, id) {
|
||||
return fixture('pages/createDocument/edit/[[id]].vue', [
|
||||
'originalDocumentType', 'canUseAdvanceInvoice', 'documentTypeItems', 'normalizeEntityId',
|
||||
'validateAdvanceInvoiceCreation', 'saveDocument',
|
||||
], {
|
||||
route: { params: { id }, query }, isTemplateMode: { value: false },
|
||||
itemInfo: { value: { type: 'advanceInvoices', project: 7 } },
|
||||
})
|
||||
}
|
||||
|
||||
test('only the project action opens a new advance invoice with its project and customer', () => {
|
||||
const { run, navigations, context } = fixture('components/EntityShowSubCreatedDocuments.vue', ['createAdvanceInvoice'], {
|
||||
props: { topLevelType: 'projects', item: { id: 7 }, queryStringData: 'customer=8&project=99' },
|
||||
})
|
||||
run('createAdvanceInvoice()')
|
||||
const query = Object.fromEntries(new URL(navigations[0], 'http://localhost').searchParams)
|
||||
assert.equal(query.project, '7')
|
||||
assert.equal(query.customer, '8')
|
||||
const editor = editorFixture(query)
|
||||
assert.equal(editor.run('validateAdvanceInvoiceCreation()'), true)
|
||||
assert.equal(editor.run("documentTypeItems.value.some(item => item.type === 'advanceInvoices')"), true)
|
||||
context.props.topLevelType = 'customers'
|
||||
run('createAdvanceInvoice()')
|
||||
assert.equal(navigations.length, 1)
|
||||
})
|
||||
|
||||
test('editor rejects alternate creation routes and saving a switched document type', async () => {
|
||||
const projectQuery = { type: 'advanceInvoices', loadMode: 'advanceInvoice', project: '7' }
|
||||
for (const query of [
|
||||
{}, { type: 'advanceInvoices' }, { type: 'advanceInvoices', project: '7' },
|
||||
{ ...projectQuery, project: '' }, { ...projectQuery, project: 'invalid' },
|
||||
{ ...projectQuery, createddocument: '12' }, { ...projectQuery, optionsToImport: '{}' },
|
||||
{ ...projectQuery, linkedDocuments: '[12]' }, { ...projectQuery, templateId: '5' },
|
||||
]) {
|
||||
const { run, notices, navigations } = editorFixture(query)
|
||||
assert.equal(run("documentTypeItems.value.some(item => item.type === 'advanceInvoices')"), false)
|
||||
assert.equal(run('validateAdvanceInvoiceCreation()'), false)
|
||||
await run("saveDocument('Entwurf')")
|
||||
assert.equal(notices.length, 2)
|
||||
assert.equal(navigations.length, 0)
|
||||
}
|
||||
})
|
||||
|
||||
test('new advance invoices require a project; existing advance invoices remain editable', () => {
|
||||
const fresh = editorFixture({ type: 'advanceInvoices', loadMode: 'advanceInvoice', project: '7' })
|
||||
fresh.run('itemInfo.value.project = null')
|
||||
assert.equal(fresh.run('validateAdvanceInvoiceCreation()'), false)
|
||||
const existing = editorFixture({}, '12')
|
||||
existing.run("originalDocumentType.value = 'advanceInvoices'; itemInfo.value.project = null")
|
||||
assert.equal(existing.run('validateAdvanceInvoiceCreation()'), true)
|
||||
assert.equal(existing.run("documentTypeItems.value.some(item => item.type === 'advanceInvoices')"), true)
|
||||
existing.run("originalDocumentType.value = 'invoices'")
|
||||
assert.equal(existing.run('validateAdvanceInvoiceCreation()'), false)
|
||||
existing.run("itemInfo.value.type = 'invoices'")
|
||||
assert.equal(existing.run('validateAdvanceInvoiceCreation()'), true)
|
||||
})
|
||||
@@ -3,6 +3,7 @@ const assert = require('node:assert/strict')
|
||||
const fs = require('node:fs')
|
||||
const vm = require('node:vm')
|
||||
const vue = require('vue')
|
||||
const { createDraftHarness } = require('./helpers/chat-drafts.cjs')
|
||||
|
||||
const settle = () => new Promise(setImmediate)
|
||||
const deferred = () => {
|
||||
@@ -33,6 +34,7 @@ function fixture(override = () => undefined) {
|
||||
|
||||
function setup(api = fixture(), query = {}) {
|
||||
const auth = vue.reactive({ user: { id: 'user-1' }, activeTenant: '1' })
|
||||
const drafts = createDraftHarness({ auth })
|
||||
const route = vue.reactive({ query })
|
||||
const calls = [], toasts = [], timers = new Map()
|
||||
const listeners = new Map()
|
||||
@@ -47,6 +49,7 @@ function setup(api = fixture(), query = {}) {
|
||||
ref: vue.ref, reactive: vue.reactive, computed: vue.computed, watch: vue.watch, nextTick: vue.nextTick,
|
||||
useToast: () => ({ add: item => toasts.push(item) }),
|
||||
useAuthStore: () => auth, useRoute: () => route,
|
||||
useChatDraft: drafts.useChatDraft,
|
||||
useRouter: () => ({ replace: async location => { route.query = location.query } }),
|
||||
useNuxtApp: () => ({ $api: (url, options) => { calls.push({ url, options }); return api(url, options) } }),
|
||||
onMounted: handler => { mount = handler }, onBeforeUnmount: handler => { unmount = handler },
|
||||
@@ -54,7 +57,7 @@ function setup(api = fixture(), query = {}) {
|
||||
clearInterval: id => timers.delete(id), document,
|
||||
})
|
||||
scope.run(() => vm.runInContext(source, context))
|
||||
return { auth, route, calls, toasts, timers, listeners, document, mount, close: () => { unmount(); scope.stop() }, run: code => vm.runInContext(code, context) }
|
||||
return { auth, route, calls, toasts, timers, listeners, document, mount, drafts, close: () => { unmount(); scope.stop(); drafts.close() }, run: code => vm.runInContext(code, context) }
|
||||
}
|
||||
|
||||
test('only member rooms enter normal chat, with separate keys, groups and unread counts', async t => {
|
||||
@@ -69,6 +72,34 @@ test('only member rooms enter normal chat, with separate keys, groups and unread
|
||||
assert.equal(ui.run('decoratedRooms.value.some(r => r.id === "admin-only")'), false)
|
||||
})
|
||||
|
||||
test('searching the sidebar preserves the open conversation and draft, including hidden-room matches', async t => {
|
||||
const ui = setup(fixture(url => {
|
||||
if (url.endsWith('/project-rooms')) return { rooms: [{ key: 'project_1', name: 'Büro Süd', projectNumber: 'P-2026-42', exists: true, type: 'project' }] }
|
||||
if (url.endsWith('/direct-rooms')) return { rooms: [{ key: 'direct_1', name: 'Anna Müller', email: 'anna@example.test', exists: true, type: 'direct' }] }
|
||||
}))
|
||||
t.after(ui.close)
|
||||
ui.mount()
|
||||
await settle()
|
||||
ui.run('draft.value = "Noch nicht gesendet"; roomSearch.value = " BÜRO 2026-42 "')
|
||||
assert.equal(ui.run('groupedRooms.value.length'), 1)
|
||||
assert.equal(ui.run('groupedRooms.value[0].rooms[0].key'), 'project_1')
|
||||
ui.run('roomSearch.value = "muller ANNA@"')
|
||||
assert.equal(ui.run('groupedRooms.value[0].rooms[0].key'), 'direct_1')
|
||||
await ui.run('setRoomHidden(decoratedRooms.value.find(room => room.key === "direct_1"), true)')
|
||||
assert.equal(ui.run('groupedRooms.value.length'), 0)
|
||||
assert.equal(ui.run('filteredHiddenRooms.value[0].key'), 'direct_1')
|
||||
ui.run('roomSearch.value = "kein Treffer"')
|
||||
await settle()
|
||||
assert.equal(ui.run('filteredRooms.value.length'), 0)
|
||||
assert.equal(ui.run('filteredHiddenRooms.value.length'), 0)
|
||||
assert.equal(ui.run('activeRoom.value.key'), 'allgemein')
|
||||
assert.equal(ui.run('messages.value[0].body'), 'Interne Nachricht')
|
||||
assert.equal(ui.run('draft.value'), 'Noch nicht gesendet')
|
||||
ui.run('roomSearch.value = ""')
|
||||
assert.equal(ui.run('groupedRooms.value.length'), 3)
|
||||
assert.equal(ui.run('hiddenRooms.value[0].key'), 'direct_1')
|
||||
})
|
||||
|
||||
test('opening a collaboration deep link never provisions, reads or sends through native chat APIs', async t => {
|
||||
const ui = setup(fixture(), { room: 'collaboration:shared-room' })
|
||||
t.after(ui.close)
|
||||
@@ -377,3 +408,69 @@ test('native image-only sends retain the draft after an error and clear it after
|
||||
assert.equal(ui.run('draftImage.value'), null)
|
||||
assert.ok(ui.calls.some(c => c.options?.body?.image?.name === 'Bild'))
|
||||
})
|
||||
|
||||
test('native drafts survive switching chats, hiding a room and reloading its history', async t => {
|
||||
const ui = setup(fixture(url => url.endsWith('/project-rooms') ? { rooms: [{ key: 'project_1', exists: true, type: 'project' }] } : undefined))
|
||||
t.after(ui.close)
|
||||
ui.mount()
|
||||
await settle()
|
||||
ui.run('draft.value = " Hallo\\nWelt 👋 "; draftImage.value = { dataUrl: "data:image/webp;base64,AAAA", name: "Skizze" }')
|
||||
await ui.run('selectRoom(decoratedRooms.value.find(r => r.key === "project_1"))')
|
||||
assert.equal(ui.run('draft.value'), '')
|
||||
assert.equal(ui.run('draftImage.value'), null)
|
||||
ui.run('draft.value = "Projektentwurf"')
|
||||
await ui.run('selectRoom(decoratedRooms.value.find(r => r.key === "allgemein"))')
|
||||
assert.equal(ui.run('draft.value'), ' Hallo\nWelt 👋 ')
|
||||
assert.equal(ui.run('draftImage.value.name'), 'Skizze')
|
||||
await ui.run('loadActiveRoom()')
|
||||
assert.equal(ui.run('draft.value'), ' Hallo\nWelt 👋 ')
|
||||
await ui.run('setRoomHidden(activeRoom.value, true)')
|
||||
assert.equal(ui.run('draft.value'), 'Projektentwurf')
|
||||
await ui.run('setRoomHidden(hiddenRooms.value[0], false)')
|
||||
assert.equal(ui.run('draft.value'), ' Hallo\nWelt 👋 ')
|
||||
})
|
||||
|
||||
test('failed sends retain the exact draft after switching away, and late success clears only the sent room', async t => {
|
||||
const pending = deferred()
|
||||
let fail = true
|
||||
const ui = setup(fixture((url, options) => {
|
||||
if (url.endsWith('/messages') && options?.method === 'POST') {
|
||||
if (fail) throw { data: { message: 'Offline' } }
|
||||
return pending.promise
|
||||
}
|
||||
}))
|
||||
t.after(ui.close)
|
||||
ui.mount()
|
||||
await settle()
|
||||
ui.run('draft.value = " Noch nicht fertig\\n "')
|
||||
await ui.run('sendMessage()')
|
||||
assert.equal(ui.run('draft.value'), ' Noch nicht fertig\n ')
|
||||
fail = false
|
||||
const sending = ui.run('sendMessage()')
|
||||
await ui.run('selectRoom(decoratedRooms.value.find(r => r.source === "collaboration"))')
|
||||
pending.resolve({ id: 2, body: 'Noch nicht fertig' })
|
||||
await sending
|
||||
await ui.run('selectRoom(decoratedRooms.value.find(r => r.key === "allgemein"))')
|
||||
assert.equal(ui.run('draft.value'), '')
|
||||
assert.equal(Object.keys(ui.drafts.storage).length, 0)
|
||||
})
|
||||
|
||||
test('editing a room after returning to a pending send preserves the new draft', async t => {
|
||||
const pending = deferred()
|
||||
const ui = setup(fixture((url, options) => url.endsWith('/messages') && options?.method === 'POST' ? pending.promise : undefined))
|
||||
t.after(ui.close)
|
||||
ui.mount()
|
||||
await settle()
|
||||
ui.run('draft.value = "Vorheriger Entwurf"')
|
||||
const sending = ui.run('sendMessage()')
|
||||
await ui.run('selectRoom(decoratedRooms.value.find(r => r.source === "collaboration"))')
|
||||
await ui.run('selectRoom(decoratedRooms.value.find(r => r.key === "allgemein"))')
|
||||
assert.equal(ui.run('draftSending.value'), true)
|
||||
await ui.run('sendMessage()')
|
||||
assert.equal(ui.calls.filter(({ url, options }) => url.endsWith('/messages') && options?.method === 'POST').length, 1)
|
||||
ui.run('draft.value = "Weitergeschrieben"')
|
||||
pending.resolve({ id: 2, body: 'Vorheriger Entwurf' })
|
||||
await sending
|
||||
assert.equal(ui.run('draft.value'), 'Weitergeschrieben')
|
||||
assert.equal(ui.run('draftSending.value'), false)
|
||||
})
|
||||
|
||||
123
frontend/tests/chat-drafts.test.cjs
Normal file
123
frontend/tests/chat-drafts.test.cjs
Normal file
@@ -0,0 +1,123 @@
|
||||
const { test } = require('node:test')
|
||||
const assert = require('node:assert/strict')
|
||||
const vue = require('vue')
|
||||
const { createDraftHarness, memoryStorage } = require('./helpers/chat-drafts.cjs')
|
||||
const image = { dataUrl: 'data:image/webp;base64,AAAA', name: 'Skizze.webp' }
|
||||
|
||||
test('text and image drafts survive room changes and a browser reload in the same session', t => {
|
||||
const storage = memoryStorage(), first = createDraftHarness({ storage })
|
||||
t.after(first.close)
|
||||
const room = vue.ref('allgemein'), composer = first.useChatDraft(room)
|
||||
composer.draft.value = ' Hallo\nWelt 👋 '
|
||||
composer.draftImage.value = image
|
||||
room.value = 'project_1'
|
||||
assert.equal(composer.draft.value, '')
|
||||
assert.equal(composer.draftImage.value, null)
|
||||
composer.draft.value = 'Projektentwurf'
|
||||
room.value = 'allgemein'
|
||||
assert.equal(composer.draft.value, ' Hallo\nWelt 👋 ')
|
||||
assert.equal(composer.draftImage.value.name, image.name)
|
||||
|
||||
const reloaded = createDraftHarness({ storage })
|
||||
t.after(reloaded.close)
|
||||
const restored = reloaded.useChatDraft('allgemein')
|
||||
assert.equal(restored.draft.value, composer.draft.value)
|
||||
assert.equal(restored.draftImage.value.dataUrl, image.dataUrl)
|
||||
assert.equal(restored.captureDraft().value.clientId, composer.captureDraft().value.clientId)
|
||||
assert.equal(reloaded.useChatDraft('project_1').draft.value, 'Projektentwurf')
|
||||
assert.equal(first.calls.length, 0)
|
||||
})
|
||||
|
||||
test('tenant and profile scopes cannot read each other; logout removes the session drafts', t => {
|
||||
const ui = createDraftHarness()
|
||||
t.after(ui.close)
|
||||
const composer = ui.useChatDraft('allgemein')
|
||||
composer.draft.value = 'Privater Entwurf'
|
||||
ui.auth.activeTenant = '2'
|
||||
assert.equal(composer.draft.value, '')
|
||||
composer.draft.value = 'Mandant 2'
|
||||
ui.auth.activeTenant = '1'
|
||||
assert.equal(composer.draft.value, 'Privater Entwurf')
|
||||
ui.auth.profile = { id: 'other-profile' }
|
||||
assert.equal(composer.draft.value, '')
|
||||
ui.auth.profile = { id: 'profile-1' }
|
||||
assert.equal(composer.draft.value, 'Privater Entwurf')
|
||||
ui.auth.user = { id: 'another-user' }
|
||||
assert.equal(composer.draft.value, '')
|
||||
assert.equal(Object.keys(ui.storage).length, 0)
|
||||
composer.draft.value = 'Neuer Benutzer'
|
||||
ui.auth.user = null
|
||||
assert.equal(composer.draft.value, '')
|
||||
assert.equal(Object.keys(ui.storage).length, 0)
|
||||
})
|
||||
|
||||
test('successful sends remove only the captured version, even after changing rooms', t => {
|
||||
const ui = createDraftHarness()
|
||||
t.after(ui.close)
|
||||
const room = vue.ref('allgemein'), composer = ui.useChatDraft(room)
|
||||
composer.draft.value = 'Gesendet'
|
||||
const sent = composer.captureDraft()
|
||||
room.value = 'project_1'
|
||||
composer.draft.value = 'Noch nicht gesendet'
|
||||
composer.clearDraft(sent)
|
||||
assert.equal(composer.draft.value, 'Noch nicht gesendet')
|
||||
room.value = 'allgemein'
|
||||
assert.equal(composer.draft.value, '')
|
||||
composer.draftImage.value = image
|
||||
const older = composer.captureDraft()
|
||||
composer.draft.value = 'Neuer Text zum Bild'
|
||||
composer.clearDraft(older)
|
||||
assert.equal(composer.draft.value, 'Neuer Text zum Bild')
|
||||
assert.equal(composer.draftImage.value.name, image.name)
|
||||
composer.clearDraft(composer.captureDraft())
|
||||
assert.equal(composer.draft.value, '')
|
||||
assert.equal(composer.draftImage.value, null)
|
||||
})
|
||||
|
||||
test('empty drafts are removed and never enter the shared profile temp_config', async t => {
|
||||
const ui = createDraftHarness()
|
||||
t.after(ui.close)
|
||||
const composer = ui.useChatDraft('direct_user-2')
|
||||
composer.draft.value = 'Geheim'
|
||||
ui.store.modifySearchString('contacts', 'Beispiel')
|
||||
assert.equal(JSON.stringify(ui.calls).includes('Geheim'), false)
|
||||
ui.store.setStoredTempConfig({ settings: { density: 'compact' } })
|
||||
assert.equal(composer.draft.value, 'Geheim')
|
||||
composer.draft.value = ''
|
||||
assert.equal(Object.keys(ui.storage).length, 0)
|
||||
})
|
||||
|
||||
test('guest conversations never reuse internal drafts and keep temporary text through a retry', t => {
|
||||
const ui = createDraftHarness()
|
||||
t.after(ui.close)
|
||||
ui.useChatDraft('collaboration:one').draft.value = 'Interner Entwurf'
|
||||
const room = vue.ref('collaboration:one'), guest = ui.useChatDraft(room, { persist: false })
|
||||
assert.equal(guest.draft.value, '')
|
||||
guest.draft.value = 'Gastentwurf'
|
||||
assert.equal(guest.draft.value, 'Gastentwurf')
|
||||
room.value = 'collaboration:two'
|
||||
assert.equal(guest.draft.value, '')
|
||||
assert.equal(Object.values(ui.storage).some(value => value.includes('Gastentwurf')), false)
|
||||
})
|
||||
|
||||
test('corrupt or unavailable browser storage does not prevent writing or sending', t => {
|
||||
const storage = memoryStorage(), initial = createDraftHarness({ storage })
|
||||
t.after(initial.close)
|
||||
initial.useChatDraft('allgemein').draft.value = 'Alt'
|
||||
storage[Object.keys(storage)[0]] = 'invalid json'
|
||||
const corrupt = createDraftHarness({ storage })
|
||||
t.after(corrupt.close)
|
||||
assert.equal(corrupt.useChatDraft('allgemein').draft.value, '')
|
||||
const blocked = createDraftHarness({ storage: {
|
||||
getItem() { throw Error('Blocked') }, setItem() { throw Error('Quota exceeded') }, removeItem() { throw Error('Blocked') },
|
||||
} })
|
||||
t.after(blocked.close)
|
||||
const composer = blocked.useChatDraft('allgemein')
|
||||
composer.draft.value = 'Im Speicher'
|
||||
composer.draftImage.value = image
|
||||
assert.equal(composer.draft.value, 'Im Speicher')
|
||||
assert.equal(composer.draftImage.value.name, image.name)
|
||||
assert.equal(blocked.toasts.length, 1)
|
||||
composer.clearDraft(composer.captureDraft())
|
||||
assert.equal(composer.draft.value, '')
|
||||
})
|
||||
@@ -3,6 +3,7 @@ const assert = require('node:assert/strict')
|
||||
const fs = require('node:fs')
|
||||
const vm = require('node:vm')
|
||||
const vue = require('vue')
|
||||
const { createDraftHarness } = require('./helpers/chat-drafts.cjs')
|
||||
const settle = () => new Promise(setImmediate)
|
||||
const deferred = () => { let resolve; return { promise: new Promise(done => { resolve = done }), resolve: value => resolve(value) } }
|
||||
|
||||
@@ -89,3 +90,62 @@ test('image display rejects external URLs and ignores responses after a room cha
|
||||
await ui.run('load()')
|
||||
assert.equal(ui.run('dataUrl.value'), 'data:image/webp;base64,AAAA')
|
||||
})
|
||||
|
||||
function collaborationApi(onSend) {
|
||||
return async (url, options) => {
|
||||
if (options?.method === 'POST' && url.endsWith('/messages')) return onSend(options.body)
|
||||
if (url.endsWith('/messages')) return { messages: [], hasMore: false }
|
||||
if (url.endsWith('/members')) return { members: [] }
|
||||
if (url.endsWith('/read')) return {}
|
||||
return { canSend: true, name: 'Partnerchat' }
|
||||
}
|
||||
}
|
||||
|
||||
test('collaboration drafts retain text, images and the retry ID when reopening after a failed send', async t => {
|
||||
const drafts = createDraftHarness(), attempts = []
|
||||
t.after(drafts.close)
|
||||
let fail = true
|
||||
const props = { roomId: 'shared', base: '/api/collaboration', api: collaborationApi(body => {
|
||||
attempts.push(body)
|
||||
if (fail) throw { data: { message: 'Offline' } }
|
||||
return { id: 'message-1', seq: 1, own: true, clientId: body.clientId, body: body.text }
|
||||
}) }
|
||||
const first = setup('CollaborationRoom', props, { useChatDraft: drafts.useChatDraft })
|
||||
await settle()
|
||||
first.run('draft.value = " Partnerentwurf\\n "; draftImage.value = { dataUrl: "data:image/webp;base64,AAAA", name: "Plan" }')
|
||||
await first.run('send()')
|
||||
assert.equal(first.run('draft.value'), ' Partnerentwurf\n ')
|
||||
assert.equal(first.run('draftImage.value.name'), 'Plan')
|
||||
await first.run('load()')
|
||||
assert.equal(first.run('draft.value'), ' Partnerentwurf\n ')
|
||||
first.close()
|
||||
const second = setup('CollaborationRoom', props, { useChatDraft: drafts.useChatDraft })
|
||||
t.after(second.close)
|
||||
await settle()
|
||||
assert.equal(second.run('draft.value'), ' Partnerentwurf\n ')
|
||||
fail = false
|
||||
await second.run('send()')
|
||||
assert.equal(attempts[0].clientId, attempts[1].clientId)
|
||||
assert.equal(second.run('draft.value'), '')
|
||||
assert.equal(second.run('draftImage.value'), null)
|
||||
assert.equal(Object.keys(drafts.storage).length, 0)
|
||||
})
|
||||
|
||||
test('collaboration send completion after unmount does not erase a newer draft in the same room', async t => {
|
||||
const drafts = createDraftHarness(), pending = deferred()
|
||||
t.after(drafts.close)
|
||||
const props = { roomId: 'shared', base: '/api/collaboration', api: collaborationApi(() => pending.promise) }
|
||||
const first = setup('CollaborationRoom', props, { useChatDraft: drafts.useChatDraft })
|
||||
await settle()
|
||||
first.run('draft.value = "Gesendet"')
|
||||
const sending = first.run('send()')
|
||||
first.close()
|
||||
const second = setup('CollaborationRoom', props, { useChatDraft: drafts.useChatDraft })
|
||||
t.after(second.close)
|
||||
await settle()
|
||||
second.run('draft.value = "Neuer Entwurf"')
|
||||
pending.resolve({ id: 'message-1', seq: 1, body: 'Gesendet' })
|
||||
await sending
|
||||
assert.equal(second.run('draft.value'), 'Neuer Entwurf')
|
||||
assert.equal(second.run('messages.value.length'), 0)
|
||||
})
|
||||
|
||||
@@ -8,7 +8,7 @@ const { parse } = require('@vue/compiler-sfc')
|
||||
|
||||
const { descriptor } = parse(fs.readFileSync(`${__dirname}/../pages/createDocument/edit/[[id]].vue`, 'utf8'))
|
||||
const script = ts.createSourceFile('document-editor.js', descriptor.scriptSetup.content, ts.ScriptTarget.Latest, true, ts.ScriptKind.JS)
|
||||
const handlers = new Set(['normalizeEntityId', 'normalizeUnitId', 'normalizeCreatedDocumentRow', 'normalizeCreatedDocumentRows', 'normalizeTaxTypeValue', 'setupPage', 'setRowData'])
|
||||
const handlers = new Set(['normalizeEntityId', 'normalizeUnitId', 'normalizeCreatedDocumentRow', 'normalizeCreatedDocumentRows', 'normalizeTaxTypeValue', 'originalDocumentType', 'canUseAdvanceInvoice', 'validateAdvanceInvoiceCreation', 'setupPage', 'setRowData'])
|
||||
const source = script.statements
|
||||
.filter(statement => ts.isVariableStatement(statement) && statement.declarationList.declarations.some(declaration => handlers.has(declaration.name.getText(script))))
|
||||
.map(statement => statement.getText(script)).join('\n')
|
||||
@@ -18,6 +18,8 @@ function fixture(unit) {
|
||||
const product = { id: 20, name: 'Artikel', unit, selling_price: 10, tax_percentage: 19 }
|
||||
const service = { id: 30, name: 'Leistung', unit, sellingPrice: 20, sellingPriceComposed: {}, taxPercentage: 19 }
|
||||
const context = vm.createContext({
|
||||
ref, computed: getter => ({ get value() { return getter() } }),
|
||||
isTemplateMode: ref(false),
|
||||
dayjs, uuidv4: () => 'row-id', console: { log() {} },
|
||||
products: ref([product]), services: ref([service]),
|
||||
productcategories: ref([]), servicecategories: ref([]),
|
||||
|
||||
166
frontend/tests/events.browser.mjs
Normal file
166
frontend/tests/events.browser.mjs
Normal file
@@ -0,0 +1,166 @@
|
||||
// Run against a built frontend with PLAYWRIGHT_MODULE pointing to an installed Playwright package.
|
||||
// Requests use isolated fixtures; no real account or application data is changed.
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFile, writeFile } from 'node:fs/promises'
|
||||
|
||||
const { chromium } = await import(process.env.PLAYWRIGHT_MODULE || 'playwright')
|
||||
const base = process.env.EVENTS_FRONTEND_URL || 'http://127.0.0.1:3157'
|
||||
const browser = await chromium.launch({ headless: true })
|
||||
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } })
|
||||
page.setDefaultTimeout(10000)
|
||||
const errors = []
|
||||
const writes = []
|
||||
const listRequests = []
|
||||
const iconCollections = Object.fromEntries(await Promise.all(['heroicons', 'lucide'].map(async prefix => [
|
||||
prefix, JSON.parse(await readFile(new URL(`../node_modules/@iconify/json/json/${prefix}.json`, import.meta.url), 'utf8'))
|
||||
])))
|
||||
let failList = false
|
||||
let allowCreate = true
|
||||
const project = { id: 42, name: 'Umbau Hafenstraße', projectNumber: 'P-2026-042' }
|
||||
const profile = { id: '11111111-1111-4111-8111-111111111111', full_name: 'Anna Beispiel', pinned_on_navigation: [], temp_config: {}, role: { rights: [] } }
|
||||
const tenant = { id: 1, name: 'Testbetrieb', extraModules: [], features: {}, locked: 'none' }
|
||||
let events = Array.from({ length: 26 }, (_, index) => ({
|
||||
id: index + 1, name: index ? `Termin ${index + 1}` : 'Baubesprechung Hafen',
|
||||
startDate: `2026-10-${String(index + 1).padStart(2, '0')}T08:00:00.000Z`,
|
||||
endDate: index ? null : '2026-10-01T09:30:00.000Z',
|
||||
project: index ? null : project, state: index ? 'Final' : 'Entwurf',
|
||||
color: '#2563eb', quick: false, archived: false, profiles: null,
|
||||
repeatInterval: index ? 'Keine Wiederholung' : 'Wöchentlich'
|
||||
}))
|
||||
|
||||
page.on('pageerror', error => errors.push(error.message))
|
||||
await page.addInitScript(() => localStorage.setItem('token', 'fixture-only'))
|
||||
await page.route('**/*', async route => {
|
||||
const url = new URL(route.request().url())
|
||||
if (url.hostname === 'api.iconify.design') {
|
||||
const collection = iconCollections[url.pathname.slice(1).replace('.json', '')]
|
||||
if (collection) return route.fulfill({ contentType: 'application/json', body: JSON.stringify(collection) })
|
||||
}
|
||||
if (url.origin !== new URL(base).origin) return route.abort()
|
||||
if (url.pathname.startsWith('/api/_nuxt_icon/')) return route.continue()
|
||||
if (!url.pathname.startsWith('/api/') && !url.pathname.startsWith('/auth/')) return route.continue()
|
||||
let body = []
|
||||
if (url.pathname === '/api/me') body = {
|
||||
user: { id: profile.id, email: 'anna@example.test', is_admin: false }, profile, tenants: [tenant], activeTenant: 1,
|
||||
permissions: ['events', 'projects', ...(allowCreate ? ['events-create'] : [])]
|
||||
}
|
||||
else if (url.pathname === '/api/tenant') body = tenant
|
||||
else if (url.pathname === '/api/tenant/profiles') body = { data: [profile] }
|
||||
else if (url.pathname === '/api/resource/projects') body = [project]
|
||||
else if (url.pathname === '/api/resource/events/paginated') {
|
||||
if (failList) return route.fulfill({ status: 503, contentType: 'application/json', body: '{"error":"Fixture unavailable"}' })
|
||||
const search = (url.searchParams.get('search') || '').toLowerCase()
|
||||
const state = url.searchParams.get('filter[state]')
|
||||
const limit = Number(url.searchParams.get('limit'))
|
||||
const currentPage = Number(url.searchParams.get('page'))
|
||||
listRequests.push(Object.fromEntries(url.searchParams))
|
||||
const matches = events.filter(event => !event.archived && (!state || state === event.state)
|
||||
&& [event.name, event.project?.name, event.project?.projectNumber].some(value => String(value || '').toLowerCase().includes(search)))
|
||||
matches.sort((a, b) => url.searchParams.get('sort')?.endsWith(':asc')
|
||||
? a.startDate.localeCompare(b.startDate) : b.startDate.localeCompare(a.startDate))
|
||||
body = { data: matches.slice((currentPage - 1) * limit, currentPage * limit), queryConfig: { total: matches.length } }
|
||||
}
|
||||
else if (url.pathname === '/api/resource/events' && route.request().method() === 'POST') {
|
||||
const payload = route.request().postDataJSON()
|
||||
writes.push(payload)
|
||||
body = { id: 100, state: 'Final', repeatInterval: 'Keine Wiederholung', ...payload, archived: false }
|
||||
events.push({ ...body, project: payload.project === project.id ? project : null })
|
||||
}
|
||||
else if (/^\/api\/resource\/events\/\d+(\/true)?$/.test(url.pathname)) {
|
||||
const event = events.find(item => item.id === Number(url.pathname.split('/')[4]))
|
||||
body = { ...event, project: event?.project?.id || null }
|
||||
if (route.request().method() === 'PUT') {
|
||||
Object.assign(event, route.request().postDataJSON())
|
||||
writes.push(route.request().postDataJSON())
|
||||
body = event
|
||||
}
|
||||
}
|
||||
await route.fulfill({ contentType: 'application/json', body: JSON.stringify(body) })
|
||||
})
|
||||
|
||||
const searchInput = () => page.getByRole('textbox', { name: 'Termine durchsuchen' })
|
||||
const waitForList = () => page.getByRole('table').waitFor()
|
||||
|
||||
try {
|
||||
await page.goto(`${base}/events`, { waitUntil: 'networkidle' })
|
||||
await waitForList()
|
||||
assert.equal(await page.getByRole('columnheader').count(), 5)
|
||||
assert.equal(await page.locator('tbody tr').count(), 25)
|
||||
await page.getByRole('button', { name: 'Next Page', exact: true }).click()
|
||||
await page.getByRole('link', { name: 'Baubesprechung Hafen', exact: true }).first().waitFor()
|
||||
assert.equal(listRequests.at(-1).page, '2')
|
||||
await searchInput().fill('P-2026-042')
|
||||
await page.getByText('P-2026-042 · Umbau Hafenstraße', { exact: true }).first().waitFor()
|
||||
await waitForList()
|
||||
assert.equal(listRequests.at(-1).page, '1')
|
||||
assert.equal(await page.locator('tbody tr').count(), 1)
|
||||
await page.screenshot({ path: '/tmp/fedeo-events-desktop.png', fullPage: true })
|
||||
|
||||
await page.getByRole('combobox', { name: 'Status filtern' }).click()
|
||||
await page.getByRole('option', { name: 'Final', exact: true }).click()
|
||||
await page.getByRole('heading', { name: 'Keine passenden Termine' }).waitFor()
|
||||
await page.getByRole('button', { name: 'Filter zurücksetzen' }).click()
|
||||
await waitForList()
|
||||
|
||||
await page.getByRole('link', { name: 'Neuer Termin', exact: true }).click()
|
||||
await page.getByRole('heading', { name: 'Termin erstellen' }).waitFor()
|
||||
await page.getByLabel('Name', { exact: true }).fill('Neu aus Terminübersicht')
|
||||
for (let index = 0; index < 2; index++) {
|
||||
await page.getByRole('button', { name: 'Datum auswählen', exact: true }).first().click()
|
||||
await page.getByRole('button', { name: 'Heute', exact: true }).click()
|
||||
await page.keyboard.press('Escape')
|
||||
}
|
||||
await page.getByLabel('Farbe auswählen', { exact: true }).fill('#f43f5e')
|
||||
const projectInputId = await page.locator('label').filter({ hasText: /^Projekt$/ }).getAttribute('for')
|
||||
await page.locator(`[id="${projectInputId}"]`).click()
|
||||
await page.getByPlaceholder('Suche...', { exact: true }).fill('2026-042')
|
||||
await page.getByRole('option', { name: project.name, exact: true }).click()
|
||||
await page.getByRole('button', { name: 'Erstellen', exact: true }).click()
|
||||
await page.waitForURL(`${base}/events`)
|
||||
await searchInput().fill('Neu aus Terminübersicht')
|
||||
await page.getByRole('link', { name: 'Neu aus Terminübersicht', exact: true }).first().waitFor()
|
||||
assert.equal(writes[0].project, 42)
|
||||
assert.equal(writes[0].color, '#f43f5e')
|
||||
assert.ok(writes[0].startDate && writes[0].endDate)
|
||||
|
||||
await page.getByRole('link', { name: 'Neu aus Terminübersicht', exact: true }).first().click()
|
||||
await page.getByRole('heading', { name: 'Termin bearbeiten' }).waitFor()
|
||||
await page.getByLabel('Name', { exact: true }).fill('Bearbeiteter Termin')
|
||||
await page.getByRole('button', { name: 'Speichern', exact: true }).click()
|
||||
await page.waitForURL(`${base}/events`)
|
||||
await waitForList()
|
||||
|
||||
await page.setViewportSize({ width: 390, height: 844 })
|
||||
await searchInput().fill('P-2026-042')
|
||||
await page.getByRole('heading', { name: 'Baubesprechung Hafen' }).waitFor()
|
||||
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false)
|
||||
await page.getByRole('link', { name: 'Neuer Termin', exact: true }).waitFor()
|
||||
await page.screenshot({ path: '/tmp/fedeo-events-mobile.png', fullPage: true })
|
||||
|
||||
await page.setViewportSize({ width: 1440, height: 1000 })
|
||||
await page.goto(`${base}/standardEntity/events`, { waitUntil: 'networkidle' })
|
||||
await searchInput().waitFor()
|
||||
failList = true
|
||||
await page.getByRole('button', { name: 'Termine aktualisieren' }).click()
|
||||
await page.getByText('Laden fehlgeschlagen', { exact: true }).waitFor()
|
||||
failList = false
|
||||
await page.getByRole('button', { name: 'Erneut versuchen' }).click()
|
||||
await waitForList()
|
||||
|
||||
events = []
|
||||
await page.getByRole('button', { name: 'Termine aktualisieren' }).click()
|
||||
await page.getByRole('heading', { name: 'Noch keine Termine' }).waitFor()
|
||||
assert.equal(await page.getByRole('link', { name: 'Neuer Termin', exact: true }).count(), 2)
|
||||
allowCreate = false
|
||||
await page.reload({ waitUntil: 'networkidle' })
|
||||
await page.getByRole('heading', { name: 'Noch keine Termine' }).waitFor()
|
||||
assert.equal(await page.getByRole('link', { name: 'Neuer Termin', exact: true }).count(), 0)
|
||||
assert.deepEqual(errors, [], 'Browser runtime errors')
|
||||
console.log('Events browser checks passed: pagination, project-number search, status filter, create and edit with return to list, mobile layout, legacy URL, errors, empty state and create permission.')
|
||||
} catch (error) {
|
||||
await writeFile('/tmp/fedeo-events-error.html', await page.content())
|
||||
await page.screenshot({ path: '/tmp/fedeo-events-error.png', fullPage: true })
|
||||
throw error
|
||||
} finally {
|
||||
await browser.close()
|
||||
}
|
||||
36
frontend/tests/helpers/chat-drafts.cjs
Normal file
36
frontend/tests/helpers/chat-drafts.cjs
Normal file
@@ -0,0 +1,36 @@
|
||||
const fs = require('node:fs')
|
||||
const vm = require('node:vm')
|
||||
const { randomUUID } = require('node:crypto')
|
||||
const vue = require('vue')
|
||||
|
||||
function memoryStorage() {
|
||||
const storage = Object.create(null)
|
||||
Object.defineProperties(storage, {
|
||||
getItem: { value: key => storage[key] ?? null },
|
||||
setItem: { value: (key, value) => { storage[key] = value } },
|
||||
removeItem: { value: key => { delete storage[key] } },
|
||||
})
|
||||
return storage
|
||||
}
|
||||
|
||||
function createDraftHarness({ auth = vue.reactive({ user: { id: 'user-1' }, activeTenant: '1', profile: { id: 'profile-1' } }), storage = memoryStorage() } = {}) {
|
||||
const scope = vue.effectScope(), toasts = [], calls = []
|
||||
const context = vm.createContext({ ...vue, crypto: { randomUUID }, sessionStorage: storage,
|
||||
defineStore: (_, setup) => setup,
|
||||
useAuthStore: () => auth,
|
||||
useRuntimeConfig: () => ({ public: { apiBase: 'https://api.example.test' } }),
|
||||
useToast: () => ({ add: toast => toasts.push(toast) }),
|
||||
useNuxtApp: () => ({ $api: async (url, options) => { calls.push({ url, options }) } }),
|
||||
})
|
||||
const storeSource = fs.readFileSync(`${__dirname}/../../stores/temp.js`, 'utf8').replace(/^import .*$/mg, '').replace('export const', 'const')
|
||||
const store = scope.run(() => vm.runInContext(`${storeSource}\nuseTempStore()`, context))
|
||||
context.useTempStore = () => store
|
||||
const composable = fs.readFileSync(`${__dirname}/../../composables/useChatDraft.js`, 'utf8').replace('export function', 'function')
|
||||
vm.runInContext(composable, context)
|
||||
return { auth, storage, store, calls, toasts,
|
||||
useChatDraft: (key, options) => scope.run(() => context.useChatDraft(key, options)),
|
||||
close: () => scope.stop(),
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { createDraftHarness, memoryStorage }
|
||||
32
frontend/utils/portalTheme.ts
Normal file
32
frontend/utils/portalTheme.ts
Normal file
@@ -0,0 +1,32 @@
|
||||
export const DEFAULT_PORTAL_COLOR = "#69c350"
|
||||
|
||||
export function normalizePortalColor(value: unknown): string | null {
|
||||
if (typeof value !== "string") return null
|
||||
const color = value.trim().toLowerCase()
|
||||
return /^#[0-9a-f]{6}$/.test(color) ? color : null
|
||||
}
|
||||
|
||||
export function getPortalColor(config: any): string {
|
||||
// Older tenant records contain the misspelled key from the original schema.
|
||||
return normalizePortalColor(config?.primaryColor)
|
||||
|| normalizePortalColor(config?.primayColor)
|
||||
|| DEFAULT_PORTAL_COLOR
|
||||
}
|
||||
|
||||
export function portalThemeStyle(value: unknown): Record<string, string> {
|
||||
const color = normalizePortalColor(value) || DEFAULT_PORTAL_COLOR
|
||||
const rgb = [1, 3, 5].map(offset => parseInt(color.slice(offset, offset + 2), 16) / 255)
|
||||
const linear = rgb.map(channel => channel <= 0.04045 ? channel / 12.92 : ((channel + 0.055) / 1.055) ** 2.4)
|
||||
const luminance = linear[0] * 0.2126 + linear[1] * 0.7152 + linear[2] * 0.0722
|
||||
const style: Record<string, string> = {
|
||||
"--ui-primary": color,
|
||||
"--portal-accent-contrast": luminance > 0.179 ? "#000000" : "#ffffff",
|
||||
}
|
||||
const shades = { 50: 5, 100: 10, 200: 25, 300: 45, 400: 70, 500: 100, 600: 80, 700: 65, 800: 50, 900: 35, 950: 20 }
|
||||
for (const [shade, percent] of Object.entries(shades)) {
|
||||
style[`--ui-color-primary-${shade}`] = Number(shade) === 500
|
||||
? color
|
||||
: `color-mix(in srgb, ${color} ${percent}%, ${Number(shade) < 500 ? "white" : "black"})`
|
||||
}
|
||||
return style
|
||||
}
|
||||
@@ -23,6 +23,8 @@ xcrun simctl launch booted software.federspiel.fedeo
|
||||
|
||||
## TestFlight vorbereiten
|
||||
|
||||
Der Preflight prüft Lint, die mobilen Chat-Regressionstests und Expo Doctor. Für eine separate Typprüfung: `npx tsc --noEmit`.
|
||||
|
||||
```bash
|
||||
npm run preflight:testflight
|
||||
npm run build:ios:testflight
|
||||
@@ -35,3 +37,9 @@ npm run submit:ios:testflight
|
||||
```
|
||||
|
||||
Der TestFlight-Build nutzt das EAS-Profil `testflight` aus `eas.json` mit Store-Distribution und automatischer Buildnummer-Erhöhung.
|
||||
|
||||
## Mobile Chats
|
||||
|
||||
Die Kommunikation zeigt interne Gruppen-, Projekt- und Direktchats sowie lokale und föderierte Unterräume mit bestehender Mitgliedschaft. Einladungen können angenommen oder abgelehnt werden. Leserechte, freigegebene Projektinformationen und wartende beziehungsweise fehlgeschlagene Zustellungen werden berücksichtigt. Bilder werden vor dem Senden verkleinert; Reaktionen funktionieren in beiden Chatarten.
|
||||
|
||||
Ausgeblendete Chats verwenden dieselben benutzer- und mandantenbezogenen Einstellungen wie das Web. Die App lädt sie beim Öffnen, beim Zurückkehren in den Vordergrund und während der Nutzung regelmäßig neu. Ausgeblendete Räume zählen nicht zum Chat-Badge und können über das Augensymbol wieder eingeblendet werden. Nachrichtenentwürfe bleiben beim Raumwechsel innerhalb derselben Sitzung erhalten und werden bei einem Sitzungswechsel verworfen.
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
"ios": {
|
||||
"supportsTablet": true,
|
||||
"bundleIdentifier": "software.federspiel.fedeo",
|
||||
"buildNumber": "13",
|
||||
"buildNumber": "16",
|
||||
"infoPlist": {
|
||||
"NSCameraUsageDescription": "Die Kamera wird benötigt, um Fotos zu Projekten und Objekten als Dokumente hochzuladen.",
|
||||
"NSPhotoLibraryUsageDescription": "Der Zugriff auf Fotos wird benötigt, um Bilder als Dokumente hochzuladen.",
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
import * as Notifications from 'expo-notifications';
|
||||
import { Redirect, Tabs } from 'expo-router';
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { AppState, DeviceEventEmitter } from 'react-native';
|
||||
|
||||
import { HapticTab } from '@/components/haptic-tab';
|
||||
import { IconSymbol } from '@/components/ui/icon-symbol';
|
||||
import { Colors } from '@/constants/theme';
|
||||
import { useColorScheme } from '@/hooks/use-color-scheme';
|
||||
import { fetchChatUnreadCounts } from '@/src/lib/api';
|
||||
import { chatApi } from '@/src/lib/chat-api';
|
||||
import { useAuth } from '@/src/providers/auth-provider';
|
||||
|
||||
export default function TabLayout() {
|
||||
@@ -14,31 +15,27 @@ export default function TabLayout() {
|
||||
const { activeTenantId, isBootstrapping, token, requiresTenantSelection } = useAuth();
|
||||
const [communicationUnread, setCommunicationUnread] = useState(0);
|
||||
|
||||
const refreshCommunicationUnread = useCallback(async () => {
|
||||
if (!token || requiresTenantSelection) {
|
||||
setCommunicationUnread(0);
|
||||
await Notifications.setBadgeCountAsync(0);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const unread = await fetchChatUnreadCounts(token);
|
||||
const total = Object.values(unread).reduce((sum, room) => sum + (room.count || 0), 0);
|
||||
setCommunicationUnread(total);
|
||||
await Notifications.setBadgeCountAsync(total);
|
||||
} catch {
|
||||
// Badge loading must not block tab navigation.
|
||||
}
|
||||
}, [requiresTenantSelection, token]);
|
||||
|
||||
useEffect(() => {
|
||||
void refreshCommunicationUnread();
|
||||
|
||||
if (!token || requiresTenantSelection) return undefined;
|
||||
|
||||
const id = setInterval(() => void refreshCommunicationUnread(), 30000);
|
||||
return () => clearInterval(id);
|
||||
}, [activeTenantId, refreshCommunicationUnread, requiresTenantSelection, token]);
|
||||
let active = true;
|
||||
let revision = 0;
|
||||
setCommunicationUnread(0);
|
||||
void Notifications.setBadgeCountAsync(0).catch(() => undefined);
|
||||
async function refresh() {
|
||||
if (!token || !activeTenantId || requiresTenantSelection || AppState.currentState !== 'active') return;
|
||||
const request = ++revision;
|
||||
try {
|
||||
const total = await chatApi.unread(token);
|
||||
if (!active || request !== revision) return;
|
||||
setCommunicationUnread(total);
|
||||
await Notifications.setBadgeCountAsync(total);
|
||||
} catch { /* Badge loading must not block tab navigation. */ }
|
||||
}
|
||||
void refresh();
|
||||
const timer = setInterval(() => void refresh(), 30000);
|
||||
const foreground = AppState.addEventListener('change', state => { if (state === 'active') void refresh(); });
|
||||
const changed = DeviceEventEmitter.addListener('fedeo:chat-changed', () => void refresh());
|
||||
return () => { active = false; ++revision; clearInterval(timer); foreground.remove(); changed.remove(); };
|
||||
}, [activeTenantId, requiresTenantSelection, token]);
|
||||
|
||||
const communicationBadge = useMemo(() => {
|
||||
if (!communicationUnread) return undefined;
|
||||
|
||||
@@ -1,294 +1,229 @@
|
||||
import { Ionicons } from '@expo/vector-icons';
|
||||
import { useIsFocused } from '@react-navigation/native';
|
||||
import { randomUUID } from 'expo-crypto';
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import {
|
||||
ActivityIndicator,
|
||||
FlatList,
|
||||
KeyboardAvoidingView,
|
||||
Modal,
|
||||
Platform,
|
||||
Pressable,
|
||||
RefreshControl,
|
||||
StyleSheet,
|
||||
Text,
|
||||
TextInput,
|
||||
View,
|
||||
ActivityIndicator, AppState, DeviceEventEmitter, FlatList, KeyboardAvoidingView, Modal, Platform,
|
||||
Pressable, ScrollView, StyleSheet, Text, TextInput, View,
|
||||
} from 'react-native';
|
||||
|
||||
import {
|
||||
ChatMember,
|
||||
ChatMessage,
|
||||
ChatRoom,
|
||||
createChatRoom,
|
||||
fetchChatMembers,
|
||||
fetchChatMessages,
|
||||
fetchChatRooms,
|
||||
markChatRoomRead,
|
||||
provisionChatRoom,
|
||||
sendChatMessage,
|
||||
syncChatRoom,
|
||||
} from '@/src/lib/api';
|
||||
import { ChatConversation, type ChatDraft } from '@/components/chat-conversation';
|
||||
import { apiRequest } from '@/src/lib/api';
|
||||
import { chatApi } from '@/src/lib/chat-api';
|
||||
import { collaborationKey, isChatAccessError, matchesChatSearch, touchChatRoom, visibleChatRooms, type ChatDirectory, type MobileChatRoom } from '@/src/lib/chat';
|
||||
import { getApiBaseUrlSync } from '@/src/lib/server-config';
|
||||
import { useAuth } from '@/src/providers/auth-provider';
|
||||
|
||||
const PRIMARY = '#69c350';
|
||||
|
||||
function normalizeRoomKey(value: string): string {
|
||||
return value.trim().toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g, '')
|
||||
.replace(/ß/g, 'ss').replace(/[^a-z0-9._=-]+/g, '_').replace(/^_+|_+$/g, '').slice(0, 48);
|
||||
}
|
||||
|
||||
function messageTime(value: ChatMessage['timestamp']): string {
|
||||
if (!value) return '';
|
||||
return new Date(value).toLocaleString('de-DE', { day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit' });
|
||||
}
|
||||
|
||||
function mergeMessages(current: ChatMessage[], incoming: ChatMessage[]): ChatMessage[] {
|
||||
const byId = new Map<number, ChatMessage>();
|
||||
for (const message of current) byId.set(message.id, message);
|
||||
for (const message of incoming) byId.set(message.id, message);
|
||||
return Array.from(byId.values()).sort((a, b) => a.id - b.id);
|
||||
}
|
||||
|
||||
export default function CommunicationScreen() {
|
||||
const { token } = useAuth();
|
||||
const listRef = useRef<FlatList<ChatMessage>>(null);
|
||||
const [rooms, setRooms] = useState<ChatRoom[]>([]);
|
||||
const [members, setMembers] = useState<ChatMember[]>([]);
|
||||
const [messages, setMessages] = useState<ChatMessage[]>([]);
|
||||
const [activeRoomKey, setActiveRoomKey] = useState('allgemein');
|
||||
const [draft, setDraft] = useState('');
|
||||
const { token, activeTenantId } = useAuth();
|
||||
if (!token || !activeTenantId) return null;
|
||||
return <ChatScreen key={`${getApiBaseUrlSync()}:${activeTenantId}:${token}`} token={token} />;
|
||||
}
|
||||
|
||||
function ChatScreen({ token }: { token: string }) {
|
||||
const focused = useIsFocused();
|
||||
const [foreground, setForeground] = useState(AppState.currentState === 'active');
|
||||
const enabled = focused && foreground;
|
||||
const [directory, setDirectory] = useState<ChatDirectory | null>(null);
|
||||
const [activeKey, setActiveKey] = useState('');
|
||||
const [search, setSearch] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [refreshing, setRefreshing] = useState(false);
|
||||
const [sending, setSending] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [membersOpen, setMembersOpen] = useState(false);
|
||||
const [busy, setBusy] = useState('');
|
||||
const [showHidden, setShowHidden] = useState(false);
|
||||
const [createOpen, setCreateOpen] = useState(false);
|
||||
const [roomName, setRoomName] = useState('');
|
||||
const [roomTopic, setRoomTopic] = useState('');
|
||||
const [roomKey, setRoomKey] = useState('');
|
||||
const afterIdRef = useRef(0);
|
||||
|
||||
const activeRoom = useMemo(
|
||||
() => rooms.find((room) => room.key === activeRoomKey) || rooms[0] || null,
|
||||
[activeRoomKey, rooms]
|
||||
);
|
||||
|
||||
const visibleRooms = useMemo(() => {
|
||||
const query = search.trim().toLowerCase();
|
||||
return rooms.filter((room) => !query || [room.name, room.topic, room.email, room.projectNumber]
|
||||
.filter(Boolean).some((value) => String(value).toLowerCase().includes(query)));
|
||||
}, [rooms, search]);
|
||||
|
||||
const loadRooms = useCallback(async () => {
|
||||
if (!token) return [];
|
||||
const result = await fetchChatRooms(token);
|
||||
setRooms(result);
|
||||
return result;
|
||||
}, [token]);
|
||||
|
||||
const loadRoom = useCallback(async (key: string) => {
|
||||
if (!token) return;
|
||||
const [nextMessages, nextMembers] = await Promise.all([
|
||||
fetchChatMessages(token, key),
|
||||
fetchChatMembers(token, key),
|
||||
]);
|
||||
setMessages(nextMessages);
|
||||
setMembers(nextMembers);
|
||||
afterIdRef.current = nextMessages[nextMessages.length - 1]?.id || 0;
|
||||
await markChatRoomRead(token, key, afterIdRef.current);
|
||||
}, [token]);
|
||||
const [roomType, setRoomType] = useState<'internal' | 'collaboration'>('internal');
|
||||
const [projectId, setProjectId] = useState<number | null>(null);
|
||||
const [drafts, setDrafts] = useState<Record<string, ChatDraft>>({});
|
||||
const alive = useRef(true);
|
||||
const directoryRevision = useRef(0);
|
||||
const selectionRevision = useRef(0);
|
||||
const operation = useRef(false);
|
||||
const loadingDirectory = useRef(false);
|
||||
const directoryRef = useRef(directory);
|
||||
directoryRef.current = directory;
|
||||
const [emptyDraft] = useState<ChatDraft>(() => ({ text: '', image: null, clientId: randomUUID() }));
|
||||
const rooms = useMemo(() => directory ? visibleChatRooms(directory) : [], [directory]);
|
||||
const filteredRooms = useMemo(() => rooms.filter(room => matchesChatSearch(room, search)), [rooms, search]);
|
||||
const hiddenRooms = useMemo(() => directory?.rooms.filter(room => directory.hiddenRoomKeys.includes(room.key)) || [], [directory]);
|
||||
const activeRoom = rooms.find(room => room.key === activeKey && room.exists);
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
if (!token) return;
|
||||
if (loadingDirectory.current || operation.current) return;
|
||||
const version = ++directoryRevision.current;
|
||||
loadingDirectory.current = true;
|
||||
try {
|
||||
setError(null);
|
||||
const nextRooms = await loadRooms();
|
||||
const selected = nextRooms.find((room) => room.key === activeRoomKey) || nextRooms[0];
|
||||
if (selected?.exists) {
|
||||
setActiveRoomKey(selected.key);
|
||||
await loadRoom(selected.key);
|
||||
}
|
||||
} catch (nextError) {
|
||||
setError(nextError instanceof Error ? nextError.message : 'Chat konnte nicht geladen werden.');
|
||||
const result = await chatApi.directory(token);
|
||||
if (!alive.current || version !== directoryRevision.current) return;
|
||||
directoryRef.current = result; setDirectory(result); setError('');
|
||||
const available = visibleChatRooms(result);
|
||||
setActiveKey(previous => available.some(room => room.key === previous && room.exists)
|
||||
? previous : available.find(room => room.exists)?.key || '');
|
||||
} catch (err) {
|
||||
if (!alive.current || version !== directoryRevision.current) return;
|
||||
setError(err instanceof Error ? err.message : 'Chats konnten nicht geladen werden.');
|
||||
if (isChatAccessError(err)) { directoryRef.current = null; setDirectory(null); setActiveKey(''); setDrafts({}); }
|
||||
} finally {
|
||||
setLoading(false);
|
||||
setRefreshing(false);
|
||||
loadingDirectory.current = false;
|
||||
if (alive.current && version === directoryRevision.current) setLoading(false);
|
||||
}
|
||||
}, [activeRoomKey, loadRoom, loadRooms, token]);
|
||||
|
||||
useEffect(() => { void refresh(); }, [refresh]);
|
||||
}, [token]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!token || !activeRoom?.exists) return undefined;
|
||||
const id = setInterval(async () => {
|
||||
try {
|
||||
const result = await syncChatRoom(token, activeRoom.key, afterIdRef.current);
|
||||
if (!result.messages?.length) return;
|
||||
setMessages((current) => mergeMessages(current, result.messages || []));
|
||||
afterIdRef.current = result.nextId || afterIdRef.current;
|
||||
await markChatRoomRead(token, activeRoom.key, afterIdRef.current);
|
||||
} catch {
|
||||
// Beim nächsten Intervall erneut versuchen.
|
||||
}
|
||||
}, 3000);
|
||||
return () => clearInterval(id);
|
||||
}, [activeRoom, token]);
|
||||
alive.current = true;
|
||||
const listener = AppState.addEventListener('change', state => setForeground(state === 'active'));
|
||||
return () => { alive.current = false; listener.remove(); };
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
if (!enabled) return;
|
||||
void refresh();
|
||||
const timer = setInterval(() => void refresh(), 15000);
|
||||
return () => clearInterval(timer);
|
||||
}, [enabled, refresh]);
|
||||
|
||||
async function selectRoom(room: ChatRoom) {
|
||||
if (!token) return;
|
||||
async function select(room: MobileChatRoom) {
|
||||
if (directoryRef.current?.hiddenRoomKeys.includes(room.key)) return;
|
||||
const version = ++selectionRevision.current;
|
||||
setError('');
|
||||
if (room.exists) { setActiveKey(room.key); return; }
|
||||
try {
|
||||
setLoading(true);
|
||||
const readyRoom = room.exists ? room : await provisionChatRoom(token, room);
|
||||
setActiveRoomKey(readyRoom.key);
|
||||
await loadRooms();
|
||||
await loadRoom(readyRoom.key);
|
||||
} catch (nextError) {
|
||||
setError(nextError instanceof Error ? nextError.message : 'Chatraum konnte nicht geöffnet werden.');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
setBusy(room.key);
|
||||
const ready = await chatApi.provision(token, room);
|
||||
if (!alive.current || version !== selectionRevision.current || directoryRef.current?.hiddenRoomKeys.includes(room.key)) return;
|
||||
// A list requested before provisioning must not replace the new room with its placeholder.
|
||||
++directoryRevision.current;
|
||||
setDirectory(previous => previous && ({ ...previous, rooms: previous.rooms.map(item => item.key === room.key ? ready : item) }));
|
||||
setActiveKey(ready.key);
|
||||
} catch (err) { if (alive.current && version === selectionRevision.current) setError(err instanceof Error ? err.message : 'Chat konnte nicht geöffnet werden.'); }
|
||||
finally { if (alive.current && version === selectionRevision.current) setBusy(''); }
|
||||
}
|
||||
|
||||
async function submitMessage() {
|
||||
if (!token || !activeRoom?.exists || !draft.trim() || sending) return;
|
||||
const text = draft.trim();
|
||||
setDraft('');
|
||||
setSending(true);
|
||||
async function mutate(label: string, action: () => Promise<string | void>) {
|
||||
if (operation.current) return;
|
||||
operation.current = true; ++directoryRevision.current;
|
||||
setBusy(label); setError('');
|
||||
try {
|
||||
const message = await sendChatMessage(token, activeRoom.key, text);
|
||||
setMessages((current) => mergeMessages(current, [message]));
|
||||
afterIdRef.current = Math.max(afterIdRef.current, message.id);
|
||||
await markChatRoomRead(token, activeRoom.key, message.id);
|
||||
} catch (nextError) {
|
||||
setDraft(text);
|
||||
setError(nextError instanceof Error ? nextError.message : 'Nachricht konnte nicht gesendet werden.');
|
||||
} finally {
|
||||
setSending(false);
|
||||
}
|
||||
const selectKey = await action();
|
||||
if (!alive.current) return;
|
||||
DeviceEventEmitter.emit('fedeo:chat-changed');
|
||||
const result = await chatApi.directory(token);
|
||||
if (!alive.current) return;
|
||||
directoryRef.current = result; setDirectory(result);
|
||||
const available = visibleChatRooms(result);
|
||||
setActiveKey(previous => available.find(room => room.key === (selectKey || previous) && room.exists)?.key
|
||||
|| available.find(room => room.exists)?.key || '');
|
||||
} catch (err) { if (alive.current) setError(err instanceof Error ? err.message : 'Änderung konnte nicht gespeichert werden.'); }
|
||||
finally { operation.current = false; if (alive.current) { setBusy(''); setLoading(false); } }
|
||||
}
|
||||
|
||||
async function submitRoom() {
|
||||
if (!token || !roomName.trim()) return;
|
||||
try {
|
||||
const created = await createChatRoom(token, {
|
||||
key: normalizeRoomKey(roomKey || roomName),
|
||||
name: roomName.trim(),
|
||||
topic: roomTopic.trim() || null,
|
||||
async function hide(room: MobileChatRoom, hidden: boolean) {
|
||||
await mutate(room.key, async () => {
|
||||
await chatApi.hide(token, room.key, hidden);
|
||||
if (!alive.current) return;
|
||||
// Update immediately after success, even if refreshing the directory subsequently fails.
|
||||
setDirectory(previous => {
|
||||
if (!previous) return previous;
|
||||
const next = { ...previous, hiddenRoomKeys: hidden ? [...new Set([...previous.hiddenRoomKeys, room.key])]
|
||||
: previous.hiddenRoomKeys.filter(key => key !== room.key) };
|
||||
directoryRef.current = next;
|
||||
return next;
|
||||
});
|
||||
setCreateOpen(false);
|
||||
setRoomName('');
|
||||
setRoomKey('');
|
||||
setRoomTopic('');
|
||||
await loadRooms();
|
||||
await selectRoom(created);
|
||||
} catch (nextError) {
|
||||
setError(nextError instanceof Error ? nextError.message : 'Chatraum konnte nicht erstellt werden.');
|
||||
}
|
||||
if (hidden) setActiveKey(previous => previous === room.key ? '' : previous);
|
||||
else { setShowHidden(false); return room.key; }
|
||||
});
|
||||
}
|
||||
|
||||
function renderRoom({ item }: { item: ChatRoom }) {
|
||||
const active = item.key === activeRoom?.key;
|
||||
return (
|
||||
<Pressable style={[styles.roomChip, active && styles.roomChipActive]} onPress={() => void selectRoom(item)}>
|
||||
<Text style={styles.roomGroup}>{item.group || 'Räume'}</Text>
|
||||
<Text style={[styles.roomName, active && styles.roomTextActive]} numberOfLines={1}>{item.name}</Text>
|
||||
{item.unread ? <Text style={styles.roomBadge}>{item.unread}</Text> : null}
|
||||
</Pressable>
|
||||
);
|
||||
async function respond(id: string, accept: boolean) {
|
||||
await mutate(id, async () => {
|
||||
const result = await chatApi.respond(token, id, accept);
|
||||
return accept && result.roomId ? collaborationKey(result.roomId) : undefined;
|
||||
});
|
||||
}
|
||||
|
||||
function renderMessage({ item }: { item: ChatMessage }) {
|
||||
return (
|
||||
<View style={[styles.messageRow, item.own && styles.messageRowOwn]}>
|
||||
<View style={[styles.messageBubble, item.own && styles.messageBubbleOwn]}>
|
||||
{!item.own ? <Text style={styles.messageAuthor}>{item.senderDisplayName || 'Benutzer'}</Text> : null}
|
||||
<Text style={[styles.messageBody, item.own && styles.messageBodyOwn]}>{item.body}</Text>
|
||||
<Text style={[styles.messageTime, item.own && styles.messageTimeOwn]}>{messageTime(item.timestamp)}</Text>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
async function create() {
|
||||
if (!roomName.trim()) return;
|
||||
await mutate('create', async () => {
|
||||
let key: string;
|
||||
if (roomType === 'collaboration') {
|
||||
const created = await apiRequest<{ id: string }>('/api/collaboration/rooms', { token, method: 'POST', body: { name: roomName.trim(), topic: roomTopic.trim(), projectId } });
|
||||
key = collaborationKey(created.id);
|
||||
} else {
|
||||
const normalized = roomName.toLowerCase().normalize('NFKD').replace(/[\u0300-\u036f]/g, '').replace(/ß/g, 'ss').replace(/[^a-z0-9._=-]+/g, '_').replace(/^[._=-]+|[._=-]+$/g, '').slice(0, 48);
|
||||
const created = await apiRequest<{ key: string }>('/api/communication/chat/rooms', { token, method: 'POST', body: { name: roomName.trim(), topic: roomTopic.trim(), key: normalized } });
|
||||
key = created.key;
|
||||
}
|
||||
if (alive.current) { setCreateOpen(false); setRoomName(''); setRoomTopic(''); }
|
||||
return key;
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<KeyboardAvoidingView behavior={Platform.OS === 'ios' ? 'padding' : undefined} style={styles.screen}>
|
||||
<View style={styles.header}>
|
||||
<View style={styles.headerMain}>
|
||||
<Text style={styles.title}>Chat</Text>
|
||||
<Text style={styles.subtitle} numberOfLines={1}>{activeRoom?.name || 'FEDEO Kommunikation'}</Text>
|
||||
</View>
|
||||
<Pressable style={styles.headerButton} onPress={() => setCreateOpen(true)}><Text style={styles.headerButtonText}>+</Text></Pressable>
|
||||
<Pressable style={styles.headerButton} onPress={() => setMembersOpen((value) => !value)}><Text style={styles.headerButtonText}>☰</Text></Pressable>
|
||||
</View>
|
||||
|
||||
{error ? <Text style={styles.error}>{error}</Text> : null}
|
||||
|
||||
<View style={styles.roomPanel}>
|
||||
<TextInput style={styles.searchInput} placeholder="Räume, Projekte oder Personen suchen" value={search} onChangeText={setSearch} />
|
||||
<FlatList data={visibleRooms} horizontal keyExtractor={(item) => item.key} renderItem={renderRoom}
|
||||
showsHorizontalScrollIndicator={false} contentContainerStyle={styles.roomList} />
|
||||
</View>
|
||||
|
||||
{membersOpen ? (
|
||||
<View style={styles.membersPanel}>
|
||||
<Text style={styles.membersTitle}>Teilnehmer · {members.length}</Text>
|
||||
<Text style={styles.membersText} numberOfLines={2}>{members.map((member) => member.own ? 'Du' : member.displayName).join(' · ')}</Text>
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
{loading ? (
|
||||
<View style={styles.loading}><ActivityIndicator /><Text style={styles.loadingText}>Nachrichten werden geladen …</Text></View>
|
||||
) : (
|
||||
<FlatList ref={listRef} data={messages} keyExtractor={(item) => String(item.id)} renderItem={renderMessage}
|
||||
contentContainerStyle={styles.messageList}
|
||||
refreshControl={<RefreshControl refreshing={refreshing} onRefresh={() => { setRefreshing(true); void refresh(); }} />}
|
||||
ListEmptyComponent={<Text style={styles.emptyText}>Noch keine Nachrichten in diesem Raum.</Text>}
|
||||
onContentSizeChange={() => listRef.current?.scrollToEnd({ animated: true })} />
|
||||
)}
|
||||
|
||||
<View style={styles.composer}>
|
||||
<TextInput style={styles.composerInput} placeholder="Nachricht schreiben" value={draft} onChangeText={setDraft} multiline />
|
||||
<Pressable style={[styles.sendButton, (!draft.trim() || sending) && styles.sendButtonDisabled]} onPress={() => void submitMessage()}>
|
||||
<Text style={styles.sendButtonText}>{sending ? '…' : 'Senden'}</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
|
||||
<Modal transparent visible={createOpen} animationType="fade" onRequestClose={() => setCreateOpen(false)}>
|
||||
<View style={styles.modalBackdrop}><View style={styles.modalCard}>
|
||||
<Text style={styles.modalTitle}>Chatraum erstellen</Text>
|
||||
<TextInput style={styles.modalInput} placeholder="Name" value={roomName} onChangeText={setRoomName} />
|
||||
<TextInput style={styles.modalInput} placeholder="Schlüssel, optional" value={roomKey} onChangeText={setRoomKey} autoCapitalize="none" />
|
||||
<TextInput style={styles.modalInput} placeholder="Beschreibung, optional" value={roomTopic} onChangeText={setRoomTopic} />
|
||||
<View style={styles.modalActions}>
|
||||
<Pressable onPress={() => setCreateOpen(false)}><Text style={styles.linkText}>Abbrechen</Text></Pressable>
|
||||
<Pressable style={styles.primaryButton} onPress={() => void submitRoom()}><Text style={styles.primaryButtonText}>Erstellen</Text></Pressable>
|
||||
</View>
|
||||
</View></View>
|
||||
</Modal>
|
||||
</KeyboardAvoidingView>
|
||||
);
|
||||
return <KeyboardAvoidingView behavior={Platform.OS === 'ios' ? 'padding' : undefined} keyboardVerticalOffset={Platform.OS === 'ios' ? 95 : 0} style={styles.screen}>
|
||||
<View style={styles.toolbar}>
|
||||
<TextInput style={styles.search} accessibilityLabel="Chats durchsuchen" placeholder="Räume, Projekte oder Personen suchen" value={search} onChangeText={setSearch} />
|
||||
<Pressable accessibilityRole="button" accessibilityLabel="Chat erstellen" onPress={() => setCreateOpen(true)} disabled={!directory || !!busy} style={styles.icon}><Ionicons name="add" size={25} /></Pressable>
|
||||
<Pressable accessibilityRole="button" accessibilityLabel={`Ausgeblendete Chats (${hiddenRooms.length})`} onPress={() => setShowHidden(true)} style={styles.icon}><Ionicons name="eye-off-outline" size={23} /></Pressable>
|
||||
</View>
|
||||
{!!error && <View style={styles.errorBox}><Text accessibilityRole="alert" style={styles.error}>{error}</Text><Pressable onPress={() => void refresh()}><Text style={styles.link}>Erneut laden</Text></Pressable></View>}
|
||||
{!!directory?.invitations.length && <ScrollView style={styles.invitations} contentContainerStyle={{ gap: 8 }}>
|
||||
{directory.invitations.map(invitation => <View key={invitation.id} style={styles.invitation}>
|
||||
<Text style={styles.bold}>Einladung: {invitation.name}</Text>
|
||||
<Text style={styles.hint}>{invitation.ownerName}{invitation.remote ? ' · Extern' : ''} · {invitation.role === 'reader' ? 'Nur lesen' : 'Lesen und schreiben'}</Text>
|
||||
{invitation.overviewAllowed && <Text style={styles.hint}>Projektübersicht freigegeben</Text>}
|
||||
<View style={styles.actions}><Pressable accessibilityRole="button" disabled={!!busy} onPress={() => void respond(invitation.id, true)} style={styles.button}><Text style={styles.white}>{busy === invitation.id ? 'Bitte warten …' : 'Annehmen'}</Text></Pressable>
|
||||
<Pressable accessibilityRole="button" disabled={!!busy} onPress={() => void respond(invitation.id, false)} style={styles.secondary}><Text>Ablehnen</Text></Pressable></View>
|
||||
</View>)}
|
||||
</ScrollView>}
|
||||
<View style={styles.roomPanel}><FlatList horizontal data={filteredRooms} keyExtractor={room => room.key} showsHorizontalScrollIndicator={false} contentContainerStyle={styles.roomList}
|
||||
ListEmptyComponent={!loading ? <Text style={styles.hint}>{search ? 'Keine passenden Chats.' : 'Keine sichtbaren Chats.'}</Text> : null}
|
||||
renderItem={({ item }) => <Pressable accessibilityRole="button" accessibilityState={{ selected: activeKey === item.key }} disabled={!!busy} onPress={() => void select(item)} style={[styles.room, activeKey === item.key && styles.selectedRoom]}>
|
||||
<Text style={styles.group}>{item.group}{item.remote ? ' · EXTERN' : ''}</Text><Text style={styles.bold} numberOfLines={1}>{item.name}</Text>
|
||||
{!!item.unread && <Text style={styles.badge}>{item.unread}</Text>}
|
||||
</Pressable>} /></View>
|
||||
{loading ? <View style={styles.empty}><ActivityIndicator /><Text>Chats werden geladen …</Text></View> : activeRoom ?
|
||||
<ChatConversation key={activeRoom.key} token={token} room={activeRoom} enabled={enabled} hiding={!!busy}
|
||||
draft={drafts[activeKey] || emptyDraft} onHide={() => void hide(activeRoom, true)}
|
||||
onDraft={value => setDrafts(previous => ({ ...previous, [activeKey]: { ...value, clientId: randomUUID() } }))}
|
||||
onSent={clientId => {
|
||||
setDirectory(previous => { const next = previous && { ...previous, rooms: touchChatRoom(previous.rooms, activeRoom.key) }; directoryRef.current = next; return next; });
|
||||
setDrafts(previous => { if (previous[activeKey]?.clientId !== clientId) return previous; const next = { ...previous }; delete next[activeKey]; return next; });
|
||||
}} />
|
||||
: <View style={styles.empty}><Ionicons name="chatbubbles-outline" size={36} color="#69c350" /><Text>Wähle einen Chat aus.</Text></View>}
|
||||
<Modal transparent visible={showHidden} animationType="slide" onRequestClose={() => setShowHidden(false)}>
|
||||
<View style={styles.overlay}><View style={styles.modal}><Text style={styles.title}>Ausgeblendete Chats</Text><Text style={styles.hint}>Diese Einstellung gilt auch im Web.</Text>
|
||||
<FlatList data={hiddenRooms.filter(room => matchesChatSearch(room, search))} keyExtractor={room => room.key} style={{ maxHeight: 380 }}
|
||||
ListEmptyComponent={<Text style={styles.hint}>Keine ausgeblendeten Chats gefunden.</Text>}
|
||||
renderItem={({ item }) => <View style={styles.hiddenRow}><View style={{ flex: 1 }}><Text style={styles.bold}>{item.name}</Text><Text style={styles.hint}>{item.group}</Text></View>
|
||||
<Pressable accessibilityRole="button" accessibilityLabel={`${item.name} einblenden`} disabled={!!busy} onPress={() => void hide(item, false)} style={styles.secondary}><Text style={styles.link}>Einblenden</Text></Pressable></View>} />
|
||||
<Pressable onPress={() => setShowHidden(false)} style={styles.secondary}><Text>Schließen</Text></Pressable>
|
||||
</View></View>
|
||||
</Modal>
|
||||
<Modal transparent visible={createOpen} animationType="slide" onRequestClose={() => setCreateOpen(false)}>
|
||||
<KeyboardAvoidingView behavior={Platform.OS === 'ios' ? 'padding' : undefined} style={styles.overlay}><View style={styles.modal}>
|
||||
<Text style={styles.title}>Chat erstellen</Text>
|
||||
{directory?.canManage && <View style={styles.actions}>{(['internal', 'collaboration'] as const).map(type => <Pressable key={type} onPress={() => setRoomType(type)} style={[styles.secondary, roomType === type && styles.selectedRoom]}><Text>{type === 'internal' ? 'Gruppenchat' : 'Unterraum'}</Text></Pressable>)}</View>}
|
||||
<TextInput style={styles.input} accessibilityLabel="Chatname" placeholder="Name" value={roomName} onChangeText={setRoomName} maxLength={200} />
|
||||
<TextInput style={styles.input} accessibilityLabel="Chatbeschreibung" placeholder="Beschreibung, optional" value={roomTopic} onChangeText={setRoomTopic} maxLength={1000} />
|
||||
{roomType === 'collaboration' && <><Text style={styles.hint}>Projekt zuordnen (optional)</Text><ScrollView style={{ maxHeight: 150 }}>
|
||||
<Pressable onPress={() => setProjectId(null)} style={styles.secondary}><Text>{projectId === null ? '✓ ' : ''}Ohne Projekt</Text></Pressable>
|
||||
{directory?.projects.map(project => <Pressable key={project.id} onPress={() => setProjectId(project.id)} style={styles.secondary}><Text>{projectId === project.id ? '✓ ' : ''}{project.name}</Text></Pressable>)}
|
||||
</ScrollView></>}
|
||||
{!!error && <Text accessibilityRole="alert" style={styles.error}>{error}</Text>}
|
||||
<View style={styles.actions}><Pressable disabled={!!busy} onPress={() => setCreateOpen(false)} style={styles.secondary}><Text>Abbrechen</Text></Pressable>
|
||||
<Pressable disabled={!!busy || !roomName.trim()} onPress={() => void create()} style={styles.button}><Text style={styles.white}>{busy === 'create' ? 'Wird erstellt …' : 'Erstellen'}</Text></Pressable></View>
|
||||
</View></KeyboardAvoidingView>
|
||||
</Modal>
|
||||
</KeyboardAvoidingView>;
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
screen: { flex: 1, backgroundColor: '#f9fafb' },
|
||||
header: { flexDirection: 'row', alignItems: 'center', gap: 8, padding: 16, backgroundColor: '#fff', borderBottomWidth: 1, borderBottomColor: '#e5e7eb' },
|
||||
headerMain: { flex: 1 }, title: { fontSize: 20, fontWeight: '800', color: '#111827' }, subtitle: { color: '#6b7280', marginTop: 2 },
|
||||
headerButton: { width: 36, height: 36, borderRadius: 18, alignItems: 'center', justifyContent: 'center', borderWidth: 1, borderColor: '#d1d5db' },
|
||||
headerButtonText: { fontSize: 20, fontWeight: '700' }, error: { margin: 10, padding: 10, borderRadius: 8, color: '#991b1b', backgroundColor: '#fee2e2' },
|
||||
roomPanel: { paddingVertical: 10, backgroundColor: '#fff', borderBottomWidth: 1, borderBottomColor: '#e5e7eb' },
|
||||
searchInput: { marginHorizontal: 16, padding: 9, borderWidth: 1, borderColor: '#d1d5db', borderRadius: 10 },
|
||||
roomList: { paddingHorizontal: 12, paddingTop: 10, gap: 8 }, roomChip: { width: 150, padding: 10, borderWidth: 1, borderColor: '#e5e7eb', borderRadius: 10 },
|
||||
roomChipActive: { backgroundColor: '#eff9ea', borderColor: PRIMARY }, roomGroup: { color: '#6b7280', fontSize: 10, textTransform: 'uppercase' },
|
||||
roomName: { color: '#111827', fontSize: 14, fontWeight: '700', marginTop: 2 }, roomTextActive: { color: '#2f6f25' },
|
||||
roomBadge: { position: 'absolute', right: 6, top: 6, backgroundColor: PRIMARY, color: '#fff', borderRadius: 9, paddingHorizontal: 6, overflow: 'hidden', fontSize: 11 },
|
||||
membersPanel: { padding: 12, backgroundColor: '#fff', borderBottomWidth: 1, borderBottomColor: '#e5e7eb' }, membersTitle: { fontWeight: '700', color: '#111827' }, membersText: { marginTop: 4, color: '#6b7280', fontSize: 12 },
|
||||
loading: { flex: 1, alignItems: 'center', justifyContent: 'center', gap: 8 }, loadingText: { color: '#6b7280' },
|
||||
messageList: { flexGrow: 1, padding: 14, gap: 10 }, emptyText: { marginTop: 40, textAlign: 'center', color: '#9ca3af' },
|
||||
messageRow: { flexDirection: 'row' }, messageRowOwn: { justifyContent: 'flex-end' }, messageBubble: { maxWidth: '82%', padding: 11, borderRadius: 16, backgroundColor: '#f3f4f6' },
|
||||
messageBubbleOwn: { backgroundColor: PRIMARY }, messageAuthor: { color: '#2f6f25', fontSize: 12, fontWeight: '700', marginBottom: 3 }, messageBody: { color: '#111827', fontSize: 15 }, messageBodyOwn: { color: '#fff' },
|
||||
messageTime: { marginTop: 4, color: '#9ca3af', fontSize: 10, textAlign: 'right' }, messageTimeOwn: { color: '#e7f7e2' },
|
||||
composer: { flexDirection: 'row', alignItems: 'flex-end', gap: 8, padding: 12, backgroundColor: '#fff', borderTopWidth: 1, borderTopColor: '#e5e7eb' },
|
||||
composerInput: { flex: 1, maxHeight: 120, borderWidth: 1, borderColor: '#d1d5db', borderRadius: 18, paddingHorizontal: 13, paddingVertical: 9 },
|
||||
sendButton: { backgroundColor: PRIMARY, borderRadius: 18, paddingHorizontal: 15, paddingVertical: 10 }, sendButtonDisabled: { opacity: 0.45 }, sendButtonText: { color: '#fff', fontWeight: '700' },
|
||||
modalBackdrop: { flex: 1, justifyContent: 'center', padding: 24, backgroundColor: 'rgba(0,0,0,0.45)' }, modalCard: { padding: 18, gap: 12, borderRadius: 14, backgroundColor: '#fff' },
|
||||
modalTitle: { fontSize: 18, fontWeight: '800', color: '#111827' }, modalInput: { borderWidth: 1, borderColor: '#d1d5db', borderRadius: 9, padding: 10 },
|
||||
modalActions: { flexDirection: 'row', justifyContent: 'flex-end', alignItems: 'center', gap: 18 }, linkText: { color: '#2f6f25', fontWeight: '700' }, primaryButton: { paddingHorizontal: 14, paddingVertical: 10, borderRadius: 9, backgroundColor: PRIMARY }, primaryButtonText: { color: '#fff', fontWeight: '700' },
|
||||
screen: { flex: 1, backgroundColor: '#f9fafb' }, toolbar: { flexDirection: 'row', alignItems: 'center', padding: 10, gap: 5, backgroundColor: '#fff' },
|
||||
search: { flex: 1, minWidth: 0, minHeight: 42, padding: 9, borderWidth: 1, borderColor: '#d1d5db', borderRadius: 10, fontSize: 13, color: '#111827' },
|
||||
icon: { padding: 8, minWidth: 40, minHeight: 44, justifyContent: 'center', alignItems: 'center' }, roomPanel: { backgroundColor: '#fff', borderBottomWidth: 1, borderColor: '#e5e7eb' },
|
||||
roomList: { paddingHorizontal: 12, paddingBottom: 10, gap: 8 }, room: { width: 165, padding: 10, borderWidth: 1, borderColor: '#e5e7eb', borderRadius: 10 },
|
||||
selectedRoom: { backgroundColor: '#eff9ea', borderColor: '#69c350', borderWidth: 1 }, group: { fontSize: 10, color: '#6b7280', textTransform: 'uppercase', marginBottom: 4 },
|
||||
bold: { fontWeight: '700', color: '#111827', fontSize: 13 }, badge: { marginTop: 4, alignSelf: 'flex-start', paddingHorizontal: 6, borderRadius: 8, backgroundColor: '#dcfce7', color: '#166534', fontSize: 11 },
|
||||
empty: { flex: 1, justifyContent: 'center', alignItems: 'center', gap: 10 }, hint: { fontSize: 12, color: '#6b7280' }, error: { fontSize: 12, color: '#991b1b' }, errorBox: { backgroundColor: '#fef2f2', padding: 10, gap: 4 },
|
||||
link: { color: '#2f6f25', fontWeight: '600' }, invitations: { maxHeight: 170, flexGrow: 0, padding: 10, backgroundColor: '#f0fdf4' }, invitation: { gap: 5, paddingBottom: 8 },
|
||||
actions: { flexDirection: 'row', alignItems: 'center', gap: 8 }, button: { paddingVertical: 11, paddingHorizontal: 16, borderRadius: 8, backgroundColor: '#438b30' },
|
||||
white: { color: '#fff', fontWeight: '600' }, secondary: { padding: 11, borderRadius: 8 }, overlay: { flex: 1, backgroundColor: 'rgba(0,0,0,0.4)', justifyContent: 'center', padding: 20 },
|
||||
modal: { maxHeight: '85%', backgroundColor: '#fff', borderRadius: 16, padding: 18, gap: 12 }, title: { fontSize: 18, fontWeight: '700', color: '#111827' },
|
||||
hiddenRow: { flexDirection: 'row', alignItems: 'center', gap: 8, paddingVertical: 9, borderBottomWidth: 1, borderColor: '#e5e7eb' }, input: { borderWidth: 1, borderColor: '#d1d5db', borderRadius: 8, padding: 12, color: '#111827' },
|
||||
});
|
||||
|
||||
@@ -2,7 +2,8 @@ import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { ActivityIndicator, Pressable, RefreshControl, ScrollView, StyleSheet, Text, View } from 'react-native';
|
||||
import { router } from 'expo-router';
|
||||
|
||||
import { fetchStaffTimeSpans, fetchTasks, Task } from '@/src/lib/api';
|
||||
import { EventCreateModal } from '@/components/event-create-modal';
|
||||
import { CalendarEvent, fetchEvents, fetchProjects, fetchStaffTimeSpans, fetchTasks, Project, Task } from '@/src/lib/api';
|
||||
import { useAuth } from '@/src/providers/auth-provider';
|
||||
|
||||
const PRIMARY = '#69c350';
|
||||
@@ -38,12 +39,25 @@ function formatDateTime(value: string | null): string {
|
||||
});
|
||||
}
|
||||
|
||||
function dateKey(date: Date): string {
|
||||
return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
function formatEventTime(value: string): string {
|
||||
const date = new Date(value);
|
||||
return Number.isNaN(date.getTime()) ? '-' : date.toLocaleTimeString('de-DE', { hour: '2-digit', minute: '2-digit' });
|
||||
}
|
||||
|
||||
export default function DashboardScreen() {
|
||||
const { token, user } = useAuth();
|
||||
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [refreshing, setRefreshing] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [events, setEvents] = useState<CalendarEvent[]>([]);
|
||||
const [projects, setProjects] = useState<Project[]>([]);
|
||||
const [createEventOpen, setCreateEventOpen] = useState(false);
|
||||
const [selectedCalendarDate, setSelectedCalendarDate] = useState(() => new Date());
|
||||
const [data, setData] = useState<DashboardData>({
|
||||
tasks: [],
|
||||
openTasks: 0,
|
||||
@@ -62,9 +76,11 @@ export default function DashboardScreen() {
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const [taskRows, spans] = await Promise.all([
|
||||
const [taskRows, spans, eventRows, projectRows] = await Promise.all([
|
||||
fetchTasks(token),
|
||||
fetchStaffTimeSpans(token, currentUserId),
|
||||
fetchEvents(token),
|
||||
fetchProjects(token),
|
||||
]);
|
||||
|
||||
const tasks = taskRows || [];
|
||||
@@ -92,6 +108,8 @@ export default function DashboardScreen() {
|
||||
pendingSubmissions,
|
||||
todayMinutes,
|
||||
});
|
||||
setEvents(eventRows);
|
||||
setProjects(projectRows);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Dashboard konnte nicht geladen werden.');
|
||||
} finally {
|
||||
@@ -112,6 +130,26 @@ export default function DashboardScreen() {
|
||||
await loadDashboard(false);
|
||||
}
|
||||
|
||||
const calendarDays = useMemo(() => {
|
||||
const start = new Date();
|
||||
start.setHours(0, 0, 0, 0);
|
||||
return Array.from({ length: 7 }, (_, index) => {
|
||||
const date = new Date(start);
|
||||
date.setDate(start.getDate() + index);
|
||||
return date;
|
||||
});
|
||||
}, []);
|
||||
|
||||
const selectedEvents = useMemo(() => {
|
||||
const selectedKey = dateKey(selectedCalendarDate);
|
||||
return events
|
||||
.filter((event) => {
|
||||
const start = new Date(event.startDate);
|
||||
return !Number.isNaN(start.getTime()) && dateKey(start) === selectedKey;
|
||||
})
|
||||
.sort((a, b) => new Date(a.startDate).getTime() - new Date(b.startDate).getTime());
|
||||
}, [events, selectedCalendarDate]);
|
||||
|
||||
return (
|
||||
<ScrollView
|
||||
contentContainerStyle={styles.container}
|
||||
@@ -158,6 +196,60 @@ export default function DashboardScreen() {
|
||||
</View>
|
||||
</View>
|
||||
|
||||
<View style={styles.calendarCard}>
|
||||
<View style={styles.calendarHeader}>
|
||||
<View>
|
||||
<Text style={styles.calendarTitle}>Kalender</Text>
|
||||
<Text style={styles.calendarSubtitle}>
|
||||
{selectedCalendarDate.toLocaleDateString('de-DE', { weekday: 'long', day: '2-digit', month: 'long' })}
|
||||
</Text>
|
||||
</View>
|
||||
<Pressable onPress={() => router.push('/more/calendar' as any)}>
|
||||
<Text style={styles.calendarLink}>Monat öffnen</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
|
||||
<View style={styles.calendarDays}>
|
||||
{calendarDays.map((date) => {
|
||||
const key = dateKey(date);
|
||||
const selected = key === dateKey(selectedCalendarDate);
|
||||
const count = events.filter((event) => {
|
||||
const start = new Date(event.startDate);
|
||||
return !Number.isNaN(start.getTime()) && dateKey(start) === key;
|
||||
}).length;
|
||||
return (
|
||||
<Pressable
|
||||
key={key}
|
||||
style={[styles.calendarDay, selected ? styles.calendarDaySelected : null]}
|
||||
onPress={() => setSelectedCalendarDate(date)}>
|
||||
<Text style={[styles.calendarWeekday, selected ? styles.calendarDayTextSelected : null]}>
|
||||
{date.toLocaleDateString('de-DE', { weekday: 'short' }).replace('.', '')}
|
||||
</Text>
|
||||
<Text style={[styles.calendarDayNumber, selected ? styles.calendarDayTextSelected : null]}>{date.getDate()}</Text>
|
||||
<View style={[styles.calendarDot, count > 0 ? styles.calendarDotActive : null]} />
|
||||
</Pressable>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
|
||||
{selectedEvents.length === 0 ? <Text style={styles.calendarEmpty}>Keine Termine an diesem Tag.</Text> : null}
|
||||
{selectedEvents.slice(0, 3).map((event) => (
|
||||
<Pressable
|
||||
key={String(event.id)}
|
||||
style={styles.calendarEvent}
|
||||
onPress={() => router.push(`/more/event/${event.id}` as any)}>
|
||||
<View style={[styles.calendarEventMark, { backgroundColor: event.color || PRIMARY }]} />
|
||||
<Text style={styles.calendarEventTime}>{formatEventTime(event.startDate)}</Text>
|
||||
<Text style={styles.calendarEventName} numberOfLines={1}>{event.name}</Text>
|
||||
{event.state === 'Entwurf' ? <Text style={styles.calendarEventDraft}>Entwurf</Text> : null}
|
||||
<Text style={styles.calendarEventArrow}>›</Text>
|
||||
</Pressable>
|
||||
))}
|
||||
<Pressable style={styles.calendarAddButton} onPress={() => setCreateEventOpen(true)}>
|
||||
<Text style={styles.calendarAddButtonText}>+ Termin eintragen</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
|
||||
<View style={styles.quickActionsCard}>
|
||||
<Text style={styles.quickActionsTitle}>Schnellzugriff</Text>
|
||||
<View style={styles.quickActionsRow}>
|
||||
@@ -175,6 +267,14 @@ export default function DashboardScreen() {
|
||||
</Pressable>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
<EventCreateModal
|
||||
visible={createEventOpen}
|
||||
projects={projects}
|
||||
initialDate={selectedCalendarDate}
|
||||
onClose={() => setCreateEventOpen(false)}
|
||||
onCreated={() => loadDashboard(false)}
|
||||
/>
|
||||
</>
|
||||
) : null}
|
||||
</ScrollView>
|
||||
@@ -232,6 +332,35 @@ const styles = StyleSheet.create({
|
||||
padding: 12,
|
||||
gap: 10,
|
||||
},
|
||||
calendarCard: {
|
||||
backgroundColor: '#ffffff',
|
||||
borderRadius: 12,
|
||||
borderWidth: 1,
|
||||
borderColor: '#e5e7eb',
|
||||
padding: 12,
|
||||
gap: 10,
|
||||
},
|
||||
calendarHeader: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', gap: 8 },
|
||||
calendarTitle: { color: '#111827', fontSize: 16, fontWeight: '700' },
|
||||
calendarSubtitle: { color: '#6b7280', fontSize: 12, marginTop: 2 },
|
||||
calendarLink: { color: '#3d7a30', fontSize: 12, fontWeight: '700' },
|
||||
calendarDays: { flexDirection: 'row', gap: 4 },
|
||||
calendarDay: { flex: 1, minHeight: 62, borderRadius: 9, alignItems: 'center', justifyContent: 'center', gap: 2 },
|
||||
calendarDaySelected: { backgroundColor: PRIMARY },
|
||||
calendarWeekday: { color: '#6b7280', fontSize: 10, fontWeight: '600', textTransform: 'uppercase' },
|
||||
calendarDayNumber: { color: '#111827', fontSize: 16, fontWeight: '700' },
|
||||
calendarDayTextSelected: { color: '#ffffff' },
|
||||
calendarDot: { width: 5, height: 5, borderRadius: 3, backgroundColor: 'transparent' },
|
||||
calendarDotActive: { backgroundColor: '#f59e0b' },
|
||||
calendarEmpty: { color: '#6b7280', fontSize: 13, paddingVertical: 4 },
|
||||
calendarEvent: { minHeight: 44, flexDirection: 'row', alignItems: 'center', borderWidth: 1, borderColor: '#e5e7eb', borderRadius: 9, overflow: 'hidden' },
|
||||
calendarEventMark: { width: 4, alignSelf: 'stretch' },
|
||||
calendarEventTime: { color: '#3d7a30', fontSize: 12, fontWeight: '700', paddingHorizontal: 8 },
|
||||
calendarEventName: { flex: 1, color: '#111827', fontSize: 13, fontWeight: '600' },
|
||||
calendarEventDraft: { color: '#92400e', backgroundColor: '#fef3c7', borderRadius: 999, paddingHorizontal: 7, paddingVertical: 3, fontSize: 10, fontWeight: '700' },
|
||||
calendarEventArrow: { color: '#9ca3af', fontSize: 21, paddingHorizontal: 7 },
|
||||
calendarAddButton: { minHeight: 40, borderRadius: 9, backgroundColor: PRIMARY, alignItems: 'center', justifyContent: 'center' },
|
||||
calendarAddButtonText: { color: '#ffffff', fontSize: 13, fontWeight: '700' },
|
||||
quickActionsTitle: {
|
||||
color: '#111827',
|
||||
fontSize: 15,
|
||||
|
||||
@@ -14,7 +14,6 @@ import {
|
||||
} from 'react-native';
|
||||
import { router, useLocalSearchParams } from 'expo-router';
|
||||
import * as DocumentPicker from 'expo-document-picker';
|
||||
import * as WebBrowser from 'expo-web-browser';
|
||||
import { BarcodeScanningResult, BarcodeType, CameraView, useCameraPermissions } from 'expo-camera';
|
||||
|
||||
import { HistorySection } from '@/components/history-section';
|
||||
@@ -32,7 +31,7 @@ import {
|
||||
uploadCustomerFile,
|
||||
} from '@/src/lib/api';
|
||||
import { useAuth } from '@/src/providers/auth-provider';
|
||||
import { getOpenableFileUrl } from '@/src/lib/file-opening';
|
||||
import { openAuthenticatedFile } from '@/src/lib/file-opening';
|
||||
|
||||
const PRIMARY = '#69c350';
|
||||
|
||||
@@ -276,13 +275,13 @@ export default function CustomerDetailScreen() {
|
||||
}
|
||||
|
||||
async function onOpenFile(file: ProjectFile) {
|
||||
if (!file.url) return;
|
||||
await WebBrowser.openBrowserAsync(getOpenableFileUrl(file.url), {
|
||||
presentationStyle: WebBrowser.WebBrowserPresentationStyle.FORM_SHEET,
|
||||
controlsColor: PRIMARY,
|
||||
showTitle: true,
|
||||
enableDefaultShareMenuItem: true,
|
||||
});
|
||||
if (!token || !file.url) return;
|
||||
setError(null);
|
||||
try {
|
||||
await openAuthenticatedFile(file, token);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Das Dokument konnte nicht geöffnet werden.');
|
||||
}
|
||||
}
|
||||
|
||||
async function onPickAndUpload() {
|
||||
|
||||
@@ -3,8 +3,9 @@ import { ActivityIndicator, Pressable, RefreshControl, ScrollView, StyleSheet, T
|
||||
import { useLocalSearchParams } from 'expo-router';
|
||||
import * as WebBrowser from 'expo-web-browser';
|
||||
|
||||
import { EventCreateModal } from '@/components/event-create-modal';
|
||||
import { HistorySection } from '@/components/history-section';
|
||||
import { CalendarEvent, fetchEventById } from '@/src/lib/api';
|
||||
import { CalendarEvent, EventState, fetchEventById, fetchProjects, Project, updateEvent } from '@/src/lib/api';
|
||||
import { useAuth } from '@/src/providers/auth-provider';
|
||||
|
||||
const PRIMARY = '#69c350';
|
||||
@@ -37,6 +38,9 @@ export default function EventDetailScreen() {
|
||||
const eventId = Number(params.id);
|
||||
const { token } = useAuth();
|
||||
const [event, setEvent] = useState<CalendarEvent | null>(null);
|
||||
const [projects, setProjects] = useState<Project[]>([]);
|
||||
const [editOpen, setEditOpen] = useState(false);
|
||||
const [updatingState, setUpdatingState] = useState(false);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [refreshing, setRefreshing] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
@@ -47,7 +51,12 @@ export default function EventDetailScreen() {
|
||||
if (showSpinner) setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
setEvent(await fetchEventById(token, eventId));
|
||||
const [eventRow, projectRows] = await Promise.all([
|
||||
fetchEventById(token, eventId),
|
||||
fetchProjects(token),
|
||||
]);
|
||||
setEvent(eventRow);
|
||||
setProjects(projectRows);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Der Termin konnte nicht geladen werden.');
|
||||
} finally {
|
||||
@@ -72,13 +81,26 @@ export default function EventDetailScreen() {
|
||||
await WebBrowser.openBrowserAsync(url, { controlsColor: PRIMARY, showTitle: true });
|
||||
}
|
||||
|
||||
async function changeState(nextState: EventState) {
|
||||
if (!token || !event || updatingState || event.state === nextState) return;
|
||||
setUpdatingState(true);
|
||||
setError(null);
|
||||
try {
|
||||
const updated = await updateEvent(token, eventId, { state: nextState });
|
||||
setEvent((current) => current ? { ...current, state: updated.state } : updated);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Der Status konnte nicht geändert werden.');
|
||||
} finally {
|
||||
setUpdatingState(false);
|
||||
}
|
||||
}
|
||||
|
||||
const rows = event
|
||||
? [
|
||||
{ label: 'Beginn', value: formatDateTime(event.startDate) },
|
||||
{ label: 'Ende', value: formatDateTime(event.endDate) },
|
||||
{ label: 'Projekt', value: relationName(event.project) },
|
||||
{ label: 'Kunde', value: relationName(event.customer) },
|
||||
{ label: 'Status', value: String(event.state || '-') },
|
||||
{ label: 'Wiederholung', value: String(event.repeatInterval || '-') },
|
||||
]
|
||||
: [];
|
||||
@@ -97,6 +119,25 @@ export default function EventDetailScreen() {
|
||||
<View style={styles.headingRow}>
|
||||
<View style={[styles.colorMark, { backgroundColor: event.color || PRIMARY }]} />
|
||||
<Text style={styles.title}>{event.name}</Text>
|
||||
<Pressable style={styles.editButton} onPress={() => setEditOpen(true)}>
|
||||
<Text style={styles.editButtonText}>Bearbeiten</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
<View style={styles.statusSection}>
|
||||
<Text style={styles.statusLabel}>Status</Text>
|
||||
<View style={styles.statusRow}>
|
||||
{(['Entwurf', 'Final'] as EventState[]).map((option) => (
|
||||
<Pressable
|
||||
key={option}
|
||||
disabled={updatingState}
|
||||
style={[styles.statusButton, event.state === option ? styles.statusButtonActive : null]}
|
||||
onPress={() => changeState(option)}>
|
||||
<Text style={[styles.statusButtonText, event.state === option ? styles.statusButtonTextActive : null]}>
|
||||
{option}
|
||||
</Text>
|
||||
</Pressable>
|
||||
))}
|
||||
</View>
|
||||
</View>
|
||||
<View style={styles.table}>
|
||||
{rows.map((row) => (
|
||||
@@ -110,6 +151,13 @@ export default function EventDetailScreen() {
|
||||
{event.link ? <Pressable style={styles.linkButton} onPress={openLink}><Text style={styles.linkButtonText}>Link öffnen</Text></Pressable> : null}
|
||||
</View>
|
||||
<HistorySection resource="events" resourceId={eventId} />
|
||||
<EventCreateModal
|
||||
visible={editOpen}
|
||||
event={event}
|
||||
projects={projects}
|
||||
onClose={() => setEditOpen(false)}
|
||||
onUpdated={() => load(false)}
|
||||
/>
|
||||
</>
|
||||
) : null}
|
||||
</ScrollView>
|
||||
@@ -122,6 +170,15 @@ const styles = StyleSheet.create({
|
||||
headingRow: { flexDirection: 'row', alignItems: 'center', gap: 9 },
|
||||
colorMark: { width: 6, height: 28, borderRadius: 3 },
|
||||
title: { flex: 1, color: '#111827', fontSize: 19, fontWeight: '700' },
|
||||
editButton: { borderRadius: 8, backgroundColor: PRIMARY, paddingHorizontal: 10, paddingVertical: 7 },
|
||||
editButtonText: { color: '#ffffff', fontSize: 12, fontWeight: '700' },
|
||||
statusSection: { gap: 6 },
|
||||
statusLabel: { color: '#6b7280', fontSize: 12, textTransform: 'uppercase', fontWeight: '600' },
|
||||
statusRow: { flexDirection: 'row', gap: 8 },
|
||||
statusButton: { flex: 1, minHeight: 40, borderRadius: 9, borderWidth: 1, borderColor: '#d1d5db', alignItems: 'center', justifyContent: 'center' },
|
||||
statusButtonActive: { borderColor: PRIMARY, backgroundColor: '#eff9ea' },
|
||||
statusButtonText: { color: '#6b7280', fontSize: 13, fontWeight: '700' },
|
||||
statusButtonTextActive: { color: '#3d7a30' },
|
||||
table: { borderWidth: 1, borderColor: '#e5e7eb', borderRadius: 10, overflow: 'hidden' },
|
||||
row: { borderBottomWidth: 1, borderBottomColor: '#e5e7eb', paddingHorizontal: 10, paddingVertical: 8, gap: 2 },
|
||||
label: { color: '#6b7280', fontSize: 12, textTransform: 'uppercase', fontWeight: '600' },
|
||||
|
||||
@@ -134,6 +134,7 @@ export default function EventsScreen() {
|
||||
{projectName(event) ? <Text style={styles.eventProject}>{projectName(event)}</Text> : null}
|
||||
{event.notes ? <Text style={styles.eventNotes} numberOfLines={2}>{String(event.notes)}</Text> : null}
|
||||
</View>
|
||||
{event.state === 'Entwurf' ? <Text style={styles.eventDraft}>Entwurf</Text> : null}
|
||||
<Text style={styles.arrow}>›</Text>
|
||||
</Pressable>
|
||||
))
|
||||
@@ -183,6 +184,7 @@ const styles = StyleSheet.create({
|
||||
eventDate: { color: '#374151', fontSize: 13 },
|
||||
eventProject: { color: '#3d7a30', fontSize: 12, fontWeight: '600' },
|
||||
eventNotes: { color: '#6b7280', fontSize: 12 },
|
||||
eventDraft: { alignSelf: 'center', color: '#92400e', backgroundColor: '#fef3c7', borderRadius: 999, paddingHorizontal: 8, paddingVertical: 4, fontSize: 10, fontWeight: '700' },
|
||||
arrow: { alignSelf: 'center', color: '#9ca3af', fontSize: 25, paddingRight: 12 },
|
||||
loadingBox: { paddingVertical: 24, alignItems: 'center', gap: 8 },
|
||||
loadingText: { color: '#6b7280' },
|
||||
|
||||
@@ -3,12 +3,11 @@ import { ActivityIndicator, Pressable, RefreshControl, ScrollView, StyleSheet, T
|
||||
import { router, useLocalSearchParams } from 'expo-router';
|
||||
import * as DocumentPicker from 'expo-document-picker';
|
||||
import * as ImagePicker from 'expo-image-picker';
|
||||
import * as WebBrowser from 'expo-web-browser';
|
||||
|
||||
import { HistorySection } from '@/components/history-section';
|
||||
import { fetchPlantById, fetchPlantFiles, Plant, ProjectFile, uploadPlantFile } from '@/src/lib/api';
|
||||
import { useAuth } from '@/src/providers/auth-provider';
|
||||
import { getOpenableFileUrl } from '@/src/lib/file-opening';
|
||||
import { openAuthenticatedFile } from '@/src/lib/file-opening';
|
||||
|
||||
const PRIMARY = '#69c350';
|
||||
|
||||
@@ -90,13 +89,13 @@ export default function PlantDetailScreen() {
|
||||
}
|
||||
|
||||
async function onOpenFile(file: ProjectFile) {
|
||||
if (!file.url) return;
|
||||
await WebBrowser.openBrowserAsync(getOpenableFileUrl(file.url), {
|
||||
presentationStyle: WebBrowser.WebBrowserPresentationStyle.FORM_SHEET,
|
||||
controlsColor: PRIMARY,
|
||||
showTitle: true,
|
||||
enableDefaultShareMenuItem: true,
|
||||
});
|
||||
if (!token || !file.url) return;
|
||||
setError(null);
|
||||
try {
|
||||
await openAuthenticatedFile(file, token);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Das Dokument konnte nicht geöffnet werden.');
|
||||
}
|
||||
}
|
||||
|
||||
async function onPickAndUpload() {
|
||||
|
||||
@@ -15,7 +15,6 @@ import {
|
||||
import { router, useLocalSearchParams } from 'expo-router';
|
||||
import * as DocumentPicker from 'expo-document-picker';
|
||||
import * as ImagePicker from 'expo-image-picker';
|
||||
import * as WebBrowser from 'expo-web-browser';
|
||||
|
||||
import { EventCreateModal } from '@/components/event-create-modal';
|
||||
import { HistorySection } from '@/components/history-section';
|
||||
@@ -34,7 +33,7 @@ import {
|
||||
updateTask,
|
||||
} from '@/src/lib/api';
|
||||
import { useAuth } from '@/src/providers/auth-provider';
|
||||
import { getOpenableFileUrl } from '@/src/lib/file-opening';
|
||||
import { openAuthenticatedFile } from '@/src/lib/file-opening';
|
||||
|
||||
const PRIMARY = '#69c350';
|
||||
const TASK_STATUS_ORDER: TaskStatus[] = ['Offen', 'In Bearbeitung', 'Abgeschlossen'];
|
||||
@@ -193,13 +192,13 @@ export default function ProjectDetailScreen() {
|
||||
}
|
||||
|
||||
async function onOpenFile(file: ProjectFile) {
|
||||
if (!file.url) return;
|
||||
await WebBrowser.openBrowserAsync(getOpenableFileUrl(file.url), {
|
||||
presentationStyle: WebBrowser.WebBrowserPresentationStyle.FORM_SHEET,
|
||||
controlsColor: PRIMARY,
|
||||
showTitle: true,
|
||||
enableDefaultShareMenuItem: true,
|
||||
});
|
||||
if (!token || !file.url) return;
|
||||
setError(null);
|
||||
try {
|
||||
await openAuthenticatedFile(file, token);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Das Dokument konnte nicht geöffnet werden.');
|
||||
}
|
||||
}
|
||||
|
||||
async function onCompleteTask(task: Task) {
|
||||
|
||||
179
mobile/components/chat-conversation.tsx
Normal file
179
mobile/components/chat-conversation.tsx
Normal file
@@ -0,0 +1,179 @@
|
||||
import { Ionicons } from '@expo/vector-icons';
|
||||
import { Image } from 'expo-image';
|
||||
import * as ImagePicker from 'expo-image-picker';
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { ActivityIndicator, FlatList, Modal, Pressable, ScrollView, StyleSheet, Text, TextInput, View } from 'react-native';
|
||||
|
||||
import { useChatConversation } from '@/hooks/use-chat-conversation';
|
||||
import { chatApi } from '@/src/lib/chat-api';
|
||||
import { prepareMobileChatImage } from '@/src/lib/chat-image';
|
||||
import { reactionEmojis, type ChatAttachment, type MobileChatMessage, type MobileChatRoom } from '@/src/lib/chat';
|
||||
|
||||
export type ChatDraft = { text: string; image: ChatAttachment | null; clientId: string };
|
||||
type Props = {
|
||||
token: string; room: MobileChatRoom; enabled: boolean; draft: ChatDraft;
|
||||
onDraft: (value: Pick<ChatDraft, 'text' | 'image'>) => void;
|
||||
onSent: (clientId: string) => void; onHide: () => void; hiding: boolean;
|
||||
};
|
||||
|
||||
function MessageImage({ token, room, message }: { token: string; room: MobileChatRoom; message: MobileChatMessage }) {
|
||||
const [uri, setUri] = useState('');
|
||||
const [error, setError] = useState(false);
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
const [retry, setRetry] = useState(0);
|
||||
const roomRef = useRef(room);
|
||||
roomRef.current = room;
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
setUri(''); setError(false); setExpanded(false);
|
||||
if (message.pending || message.failed) return;
|
||||
chatApi.image(token, roomRef.current, message.id).then(value => { if (active) setUri(value); })
|
||||
.catch(() => { if (active) setError(true); });
|
||||
return () => { active = false; };
|
||||
}, [message.failed, message.id, message.pending, retry, room.key, token]);
|
||||
const image = message.image!;
|
||||
const width = Math.min(260, image.width);
|
||||
const height = Math.min(220, width * image.height / image.width);
|
||||
if (message.pending || message.failed) return <Text style={styles.hint}>📷 {image.name}</Text>;
|
||||
return <View style={{ marginVertical: 8 }}>
|
||||
{uri ? <Pressable accessibilityRole="button" accessibilityLabel={`Bild öffnen: ${image.name}`} onPress={() => setExpanded(true)}>
|
||||
<Image source={{ uri }} cachePolicy="none" contentFit="contain" style={{ width, height }} accessibilityLabel={image.name} />
|
||||
</Pressable> : error ? <Pressable accessibilityRole="button" onPress={() => setRetry(value => value + 1)}>
|
||||
<Text style={styles.link}>Bild erneut laden</Text>
|
||||
</Pressable> : <ActivityIndicator accessibilityLabel="Bild wird geladen" />}
|
||||
<Modal visible={expanded} animationType="fade" onRequestClose={() => setExpanded(false)}>
|
||||
<View style={styles.imageModal}>
|
||||
<Pressable accessibilityRole="button" onPress={() => setExpanded(false)} style={styles.closeImage}><Text style={styles.white}>Schließen</Text></Pressable>
|
||||
<Image source={{ uri }} cachePolicy="none" contentFit="contain" style={styles.fullImage} accessibilityLabel={image.name} />
|
||||
</View>
|
||||
</Modal>
|
||||
</View>;
|
||||
}
|
||||
|
||||
export function ChatConversation({ token, room, enabled, draft, onDraft, onSent, onHide, hiding }: Props) {
|
||||
const chat = useChatConversation(token, room, enabled);
|
||||
const [membersOpen, setMembersOpen] = useState(false);
|
||||
const [reactionMessage, setReactionMessage] = useState<MobileChatMessage | null>(null);
|
||||
const [preparing, setPreparing] = useState(false);
|
||||
const [imageError, setImageError] = useState('');
|
||||
const list = useRef<FlatList<MobileChatMessage>>(null);
|
||||
const alive = useRef(true);
|
||||
const pickerGeneration = useRef(0);
|
||||
const allowed = enabled && !!chat.detail?.canSend && !chat.loading;
|
||||
useEffect(() => { alive.current = true; return () => { alive.current = false; }; }, []);
|
||||
useEffect(() => { if (!allowed) setReactionMessage(null); }, [allowed]);
|
||||
|
||||
const attach = async () => {
|
||||
if (!allowed || preparing || chat.sending) return;
|
||||
const version = ++pickerGeneration.current;
|
||||
setPreparing(true); setImageError('');
|
||||
try {
|
||||
const result = await ImagePicker.launchImageLibraryAsync({ mediaTypes: ['images'], quality: 1 });
|
||||
if (result.canceled || !alive.current || version !== pickerGeneration.current) return;
|
||||
const image = await prepareMobileChatImage(result.assets[0]);
|
||||
// The system photo picker can temporarily background the app. Keep the local
|
||||
// attachment; sending still requires refreshed room permissions afterwards.
|
||||
if (alive.current && version === pickerGeneration.current) onDraft({ text: draft.text, image });
|
||||
} catch (error) {
|
||||
if (alive.current && version === pickerGeneration.current) setImageError(error instanceof Error ? error.message : 'Bild konnte nicht geöffnet werden.');
|
||||
} finally { if (alive.current && version === pickerGeneration.current) setPreparing(false); }
|
||||
};
|
||||
const send = async () => {
|
||||
if (!allowed || preparing || (!draft.text.trim() && !draft.image)) return;
|
||||
const sent = await chat.send(draft.text.trim(), draft.image, draft.clientId);
|
||||
if (sent) { onSent(draft.clientId); list.current?.scrollToOffset({ offset: 0, animated: true }); }
|
||||
};
|
||||
const time = (message: MobileChatMessage) => {
|
||||
const value = message.createdAt || message.timestamp;
|
||||
return value ? new Date(value).toLocaleString('de-DE', { day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit' }) : '';
|
||||
};
|
||||
const older = () => void chat.older();
|
||||
const renderMessage = ({ item }: { item: MobileChatMessage }) => {
|
||||
const canReact = allowed && !chat.detail?.offline && !item.pending && !item.failed;
|
||||
return <View style={[styles.messageRow, item.own && styles.ownRow]}>
|
||||
<View style={[styles.bubble, item.own && styles.ownBubble]}>
|
||||
<Text style={styles.author}>{item.own ? 'Du' : item.senderName || item.senderDisplayName || 'Benutzer'}</Text>
|
||||
{item.image && <MessageImage key={`${chat.detail?.revision || 0}:${item.id}`} token={token} room={room} message={item} />}
|
||||
{!!item.body && <Text selectable style={styles.body}>{item.body}</Text>}
|
||||
<Text style={styles.time}>{time(item)}{item.pending ? ' · Wartet auf Zustellung' : item.failed ? ' · Zustellung fehlgeschlagen' : ''}</Text>
|
||||
<View style={styles.reactions}>
|
||||
{(chat.reactions[item.id] || []).map(reaction => <Pressable key={reaction.emoji} accessibilityRole="button"
|
||||
accessibilityLabel={`${reaction.emoji}: ${reaction.count}${reaction.own ? ', eigene Reaktion entfernen' : ', reagieren'}`}
|
||||
accessibilityState={{ selected: reaction.own, disabled: !canReact || chat.reacting }} disabled={!canReact || chat.reacting}
|
||||
onPress={() => void chat.react(item, reaction.emoji)} style={[styles.reaction, reaction.own && styles.ownReaction]}>
|
||||
<Text>{reaction.emoji} {reaction.count}</Text>
|
||||
</Pressable>)}
|
||||
{canReact && <Pressable accessibilityRole="button" accessibilityLabel="Reaktion hinzufügen" disabled={chat.reacting}
|
||||
onPress={() => setReactionMessage(item)} style={styles.reaction}><Text>☺ +</Text></Pressable>}
|
||||
</View>
|
||||
</View>
|
||||
</View>;
|
||||
};
|
||||
// The inverted list renders the newest message at the bottom and always opens there.
|
||||
const newestFirst = useMemo(() => [...chat.messages].reverse(), [chat.messages]);
|
||||
return <View style={styles.container}>
|
||||
<View style={styles.header}>
|
||||
<View style={styles.grow}><Text style={styles.title} numberOfLines={1}>{chat.detail?.name || room.name}</Text>
|
||||
<Text style={styles.hint} numberOfLines={1}>{room.remote ? 'Extern · ' : ''}{room.ownerName || room.group}{chat.detail?.status === 'archived' ? ' · Archiviert' : ''}</Text></View>
|
||||
<Pressable accessibilityRole="button" accessibilityLabel="Teilnehmer anzeigen" onPress={() => setMembersOpen(value => !value)} style={styles.iconButton}><Ionicons name="people-outline" size={23} /></Pressable>
|
||||
<Pressable accessibilityRole="button" accessibilityLabel="Chat ausblenden" disabled={hiding} onPress={onHide} style={styles.iconButton}><Ionicons name="eye-off-outline" size={23} /></Pressable>
|
||||
</View>
|
||||
{membersOpen && <View style={styles.info}><Text style={styles.author}>Teilnehmer · {chat.members.length}</Text>
|
||||
<Text>{chat.members.map(member => `${member.own ? 'Du' : member.name}${member.kind === 'guest' ? ' (Gast)' : ''}`).join(' · ') || 'Keine Teilnehmer verfügbar.'}</Text></View>}
|
||||
{!!chat.error && <View style={styles.errorBox}><Text accessibilityRole="alert" style={styles.error}>{chat.error}</Text><Pressable onPress={chat.retry}><Text style={styles.link}>Erneut laden</Text></Pressable></View>}
|
||||
{chat.detail?.offline && <Text style={styles.notice}>Die Partnerinstanz ist nicht erreichbar. Neue Nachrichten warten auf Zustellung.</Text>}
|
||||
{!!chat.detail?.overview && <View style={styles.info}><Text style={styles.author}>Freigegebene Projektinformationen</Text>
|
||||
{Object.entries(chat.detail.overview).filter(([, value]) => !!value).map(([key, value]) => <Text key={key}>{key === 'status' ? 'Status: ' : key === 'date' ? 'Termin: ' : ''}{value}</Text>)}
|
||||
</View>}
|
||||
{chat.loading ? <View style={styles.empty}><ActivityIndicator /><Text>Nachrichten werden geladen …</Text></View> :
|
||||
!chat.messages.length ? <View style={styles.grow}><Text style={[styles.hint, styles.messages]}>Noch keine Nachrichten in diesem Chat.</Text></View> :
|
||||
<FlatList ref={list} inverted data={newestFirst} keyExtractor={item => String(item.id)} renderItem={renderMessage}
|
||||
style={styles.grow} contentContainerStyle={styles.messages} keyboardShouldPersistTaps="handled"
|
||||
maintainVisibleContentPosition={{ minIndexForVisible: 1, autoscrollToTopThreshold: 100 }}
|
||||
ListFooterComponent={chat.hasMore ? <Pressable disabled={chat.olderLoading} onPress={older} style={styles.loadOlder}><Text style={styles.link}>{chat.olderLoading ? 'Wird geladen …' : 'Ältere Nachrichten laden'}</Text></Pressable> : null} />}
|
||||
{chat.detail && <View style={styles.composer}>
|
||||
{!chat.detail.canSend && <Text style={styles.hint}>Dieser Chat ist nur lesbar.</Text>}
|
||||
{!!imageError && <Text accessibilityRole="alert" style={styles.error}>{imageError}</Text>}
|
||||
{draft.image && <View style={styles.attachment}><Image source={{ uri: draft.image.dataUrl }} cachePolicy="none" style={styles.thumbnail} contentFit="contain" />
|
||||
<Text numberOfLines={1} style={styles.grow}>{draft.image.name}</Text>
|
||||
<Pressable accessibilityLabel="Bild entfernen" disabled={chat.sending || preparing} onPress={() => onDraft({ text: draft.text, image: null })} style={styles.iconButton}><Ionicons name="close" size={23} /></Pressable></View>}
|
||||
<View style={styles.composerRow}>
|
||||
<Pressable accessibilityRole="button" accessibilityLabel="Bild anhängen" disabled={!allowed || preparing || chat.sending} onPress={() => void attach()} style={styles.iconButton}>
|
||||
{preparing ? <ActivityIndicator /> : <Ionicons name="image-outline" size={25} color={allowed ? '#2f6f25' : '#9ca3af'} />}</Pressable>
|
||||
<TextInput accessibilityLabel="Nachricht" placeholder={allowed ? 'Nachricht schreiben …' : 'Nur lesbar'} style={styles.input} multiline maxLength={10000}
|
||||
editable={allowed && !preparing && !chat.sending} value={draft.text} onChangeText={text => onDraft({ text, image: draft.image })} />
|
||||
<Pressable accessibilityRole="button" accessibilityLabel="Nachricht senden" disabled={!allowed || preparing || chat.sending || (!draft.text.trim() && !draft.image)} onPress={() => void send()}
|
||||
style={[styles.send, (!allowed || preparing || chat.sending || (!draft.text.trim() && !draft.image)) && styles.disabled]}>
|
||||
{chat.sending ? <ActivityIndicator color="#fff" /> : <Ionicons name="send" size={21} color="#fff" />}</Pressable>
|
||||
</View>
|
||||
</View>}
|
||||
<Modal transparent visible={!!reactionMessage && allowed} animationType="fade" onRequestClose={() => setReactionMessage(null)}>
|
||||
<Pressable style={styles.overlay} onPress={() => setReactionMessage(null)}><View style={styles.reactionPicker}>
|
||||
<Text style={styles.title}>Reaktion auswählen</Text><ScrollView horizontal contentContainerStyle={styles.reactions}>
|
||||
{reactionEmojis.map(emoji => <Pressable key={emoji} accessibilityRole="button" accessibilityLabel={`Mit ${emoji} reagieren`} style={styles.emoji}
|
||||
onPress={() => { if (reactionMessage) void chat.react(reactionMessage, emoji); setReactionMessage(null); }}><Text style={{ fontSize: 28 }}>{emoji}</Text></Pressable>)}
|
||||
</ScrollView></View></Pressable>
|
||||
</Modal>
|
||||
</View>;
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
container: { flex: 1, minHeight: 0 }, grow: { flex: 1 },
|
||||
header: { flexDirection: 'row', alignItems: 'center', padding: 12, gap: 8, backgroundColor: '#fff', borderBottomWidth: 1, borderColor: '#e5e7eb' },
|
||||
title: { fontSize: 16, fontWeight: '700', color: '#111827' }, hint: { color: '#6b7280', fontSize: 12 },
|
||||
iconButton: { padding: 10, minHeight: 44, minWidth: 44, alignItems: 'center', justifyContent: 'center' },
|
||||
messages: { padding: 12, gap: 12 }, messageRow: { flexDirection: 'row' }, ownRow: { justifyContent: 'flex-end' },
|
||||
bubble: { maxWidth: '90%', padding: 12, borderRadius: 14, backgroundColor: '#fff', borderWidth: 1, borderColor: '#e5e7eb' },
|
||||
ownBubble: { backgroundColor: '#eff9ea', borderColor: '#c7e6bb' }, author: { fontWeight: '700', fontSize: 12, color: '#374151', marginBottom: 4 },
|
||||
body: { color: '#111827', fontSize: 15, lineHeight: 21 }, time: { color: '#6b7280', fontSize: 10, marginTop: 6, textAlign: 'right' },
|
||||
reactions: { flexDirection: 'row', flexWrap: 'wrap', gap: 6, marginTop: 8 }, reaction: { paddingHorizontal: 9, paddingVertical: 5, borderWidth: 1, borderColor: '#d1d5db', borderRadius: 16, backgroundColor: '#fff' },
|
||||
ownReaction: { backgroundColor: '#dcfce7', borderColor: '#69c350' }, info: { padding: 12, gap: 3, backgroundColor: '#f0fdf4' },
|
||||
notice: { padding: 12, backgroundColor: '#fffbeb', color: '#92400e', fontSize: 12 }, errorBox: { padding: 10, backgroundColor: '#fef2f2', gap: 5 }, error: { color: '#991b1b', fontSize: 12 },
|
||||
link: { color: '#2f6f25', fontWeight: '600', paddingVertical: 5 }, empty: { flex: 1, alignItems: 'center', justifyContent: 'center', gap: 10 },
|
||||
composer: { padding: 10, backgroundColor: '#fff', borderTopWidth: 1, borderColor: '#e5e7eb', gap: 8 }, composerRow: { flexDirection: 'row', alignItems: 'flex-end', gap: 6 },
|
||||
input: { flex: 1, minHeight: 44, maxHeight: 120, borderWidth: 1, borderColor: '#d1d5db', borderRadius: 12, padding: 10, fontSize: 15, color: '#111827' },
|
||||
send: { width: 44, height: 44, borderRadius: 12, backgroundColor: '#438b30', alignItems: 'center', justifyContent: 'center' }, disabled: { opacity: 0.4 },
|
||||
attachment: { flexDirection: 'row', alignItems: 'center', gap: 8 }, thumbnail: { width: 52, height: 52 }, loadOlder: { alignItems: 'center', padding: 10 },
|
||||
overlay: { flex: 1, justifyContent: 'center', padding: 20, backgroundColor: 'rgba(0,0,0,0.4)' }, reactionPicker: { backgroundColor: '#fff', borderRadius: 16, padding: 16 }, emoji: { padding: 9 },
|
||||
imageModal: { flex: 1, backgroundColor: '#111827', paddingTop: 60, paddingBottom: 30 }, closeImage: { alignSelf: 'flex-end', padding: 20 }, white: { color: '#fff' }, fullImage: { flex: 1 },
|
||||
});
|
||||
@@ -2,6 +2,7 @@ import { useEffect, useMemo, useState } from 'react';
|
||||
import DateTimePicker, { DateTimePickerEvent } from '@react-native-community/datetimepicker';
|
||||
import {
|
||||
KeyboardAvoidingView,
|
||||
Keyboard,
|
||||
Modal,
|
||||
Platform,
|
||||
Pressable,
|
||||
@@ -12,7 +13,7 @@ import {
|
||||
View,
|
||||
} from 'react-native';
|
||||
|
||||
import { CalendarEvent, createEvent, Project } from '@/src/lib/api';
|
||||
import { CalendarEvent, createEvent, EventState, Project, updateEvent } from '@/src/lib/api';
|
||||
import { useAuth } from '@/src/providers/auth-provider';
|
||||
|
||||
const PRIMARY = '#69c350';
|
||||
@@ -22,8 +23,10 @@ type EventCreateModalProps = {
|
||||
projects?: Project[];
|
||||
initialProjectId?: number | null;
|
||||
initialDate?: Date | null;
|
||||
event?: CalendarEvent | null;
|
||||
onClose: () => void;
|
||||
onCreated: (event: CalendarEvent) => void | Promise<void>;
|
||||
onCreated?: (event: CalendarEvent) => void | Promise<void>;
|
||||
onUpdated?: (event: CalendarEvent) => void | Promise<void>;
|
||||
};
|
||||
|
||||
function pad(value: number): string {
|
||||
@@ -64,13 +67,16 @@ export function EventCreateModal({
|
||||
projects = [],
|
||||
initialProjectId = null,
|
||||
initialDate = null,
|
||||
event = null,
|
||||
onClose,
|
||||
onCreated,
|
||||
onUpdated,
|
||||
}: EventCreateModalProps) {
|
||||
const { token } = useAuth();
|
||||
const [name, setName] = useState('');
|
||||
const [notes, setNotes] = useState('');
|
||||
const [link, setLink] = useState('');
|
||||
const [state, setState] = useState<EventState>('Final');
|
||||
const [start, setStart] = useState(() => createDefaults(initialDate).start);
|
||||
const [end, setEnd] = useState(() => createDefaults(initialDate).end);
|
||||
const [activePicker, setActivePicker] = useState<'startDate' | 'startTime' | 'endDate' | 'endTime' | null>(null);
|
||||
@@ -82,16 +88,19 @@ export function EventCreateModal({
|
||||
useEffect(() => {
|
||||
if (!visible) return;
|
||||
const defaults = createDefaults(initialDate);
|
||||
setName('');
|
||||
setNotes('');
|
||||
setLink('');
|
||||
setStart(defaults.start);
|
||||
setEnd(defaults.end);
|
||||
const eventStart = event?.startDate ? new Date(event.startDate) : null;
|
||||
const eventEnd = event?.endDate ? new Date(event.endDate) : null;
|
||||
setName(event?.name || '');
|
||||
setNotes(String(event?.notes || ''));
|
||||
setLink(String(event?.link || ''));
|
||||
setState(event?.state === 'Entwurf' ? 'Entwurf' : 'Final');
|
||||
setStart(eventStart && !Number.isNaN(eventStart.getTime()) ? eventStart : defaults.start);
|
||||
setEnd(eventEnd && !Number.isNaN(eventEnd.getTime()) ? eventEnd : defaults.end);
|
||||
setActivePicker(null);
|
||||
setSelectedProjectId(initialProjectId);
|
||||
setSelectedProjectId(relationId(event?.project) ?? initialProjectId);
|
||||
setProjectSearch('');
|
||||
setError(null);
|
||||
}, [initialDate, initialProjectId, visible]);
|
||||
}, [event, initialDate, initialProjectId, visible]);
|
||||
|
||||
const selectedProject = useMemo(
|
||||
() => projects.find((project) => Number(project.id) === selectedProjectId) || null,
|
||||
@@ -130,6 +139,11 @@ export function EventCreateModal({
|
||||
}
|
||||
}
|
||||
|
||||
function openPicker(picker: 'startDate' | 'startTime' | 'endDate' | 'endTime') {
|
||||
Keyboard.dismiss();
|
||||
setActivePicker(picker);
|
||||
}
|
||||
|
||||
async function save() {
|
||||
if (!token || saving) return;
|
||||
const title = name.trim();
|
||||
@@ -146,18 +160,22 @@ export function EventCreateModal({
|
||||
setSaving(true);
|
||||
setError(null);
|
||||
try {
|
||||
const event = await createEvent(token, {
|
||||
const payload = {
|
||||
name: title,
|
||||
startDate: start.toISOString(),
|
||||
endDate: end.toISOString(),
|
||||
project: selectedProjectId,
|
||||
customer: relationId(selectedProject?.customer),
|
||||
customer: relationId(selectedProject?.customer) ?? relationId(event?.customer),
|
||||
notes: notes.trim() || null,
|
||||
link: link.trim() || null,
|
||||
state: 'Final',
|
||||
repeatInterval: 'Keine Wiederholung',
|
||||
});
|
||||
await onCreated(event);
|
||||
state,
|
||||
repeatInterval: event?.repeatInterval || 'Keine Wiederholung',
|
||||
};
|
||||
const savedEvent = event
|
||||
? await updateEvent(token, Number(event.id), payload)
|
||||
: await createEvent(token, payload);
|
||||
if (event) await onUpdated?.(savedEvent);
|
||||
else await onCreated?.(savedEvent);
|
||||
onClose();
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Der Termin konnte nicht gespeichert werden.');
|
||||
@@ -171,7 +189,7 @@ export function EventCreateModal({
|
||||
<View style={styles.overlay}>
|
||||
<KeyboardAvoidingView behavior={Platform.OS === 'ios' ? 'padding' : undefined} style={styles.keyboardWrap}>
|
||||
<View style={styles.card}>
|
||||
<Text style={styles.title}>Neuer Termin</Text>
|
||||
<Text style={styles.title}>{event ? 'Termin bearbeiten' : 'Neuer Termin'}</Text>
|
||||
<ScrollView style={styles.scroll} contentContainerStyle={styles.form} keyboardShouldPersistTaps="handled">
|
||||
<TextInput
|
||||
autoFocus
|
||||
@@ -184,41 +202,37 @@ export function EventCreateModal({
|
||||
|
||||
<Text style={styles.label}>Beginn</Text>
|
||||
<View style={styles.row}>
|
||||
<Pressable style={[styles.pickerButton, styles.dateInput]} onPress={() => setActivePicker('startDate')}>
|
||||
<Pressable style={[styles.pickerButton, styles.dateInput]} onPress={() => openPicker('startDate')}>
|
||||
<Text style={styles.pickerButtonText}>{formatDate(start)}</Text>
|
||||
</Pressable>
|
||||
<Pressable style={[styles.pickerButton, styles.timeInput]} onPress={() => setActivePicker('startTime')}>
|
||||
<Pressable style={[styles.pickerButton, styles.timeInput]} onPress={() => openPicker('startTime')}>
|
||||
<Text style={styles.pickerButtonText}>{formatTime(start)}</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
|
||||
<Text style={styles.label}>Ende</Text>
|
||||
<View style={styles.row}>
|
||||
<Pressable style={[styles.pickerButton, styles.dateInput]} onPress={() => setActivePicker('endDate')}>
|
||||
<Pressable style={[styles.pickerButton, styles.dateInput]} onPress={() => openPicker('endDate')}>
|
||||
<Text style={styles.pickerButtonText}>{formatDate(end)}</Text>
|
||||
</Pressable>
|
||||
<Pressable style={[styles.pickerButton, styles.timeInput]} onPress={() => setActivePicker('endTime')}>
|
||||
<Pressable style={[styles.pickerButton, styles.timeInput]} onPress={() => openPicker('endTime')}>
|
||||
<Text style={styles.pickerButtonText}>{formatTime(end)}</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
|
||||
{activePicker ? (
|
||||
<View style={styles.pickerWrap}>
|
||||
<DateTimePicker
|
||||
value={activePicker.startsWith('start') ? start : end}
|
||||
mode={activePicker.endsWith('Date') ? 'date' : 'time'}
|
||||
display={Platform.OS === 'ios' ? 'spinner' : 'default'}
|
||||
locale="de-DE"
|
||||
minuteInterval={5}
|
||||
onChange={updatePicker}
|
||||
/>
|
||||
{Platform.OS === 'ios' ? (
|
||||
<Pressable style={styles.pickerDoneButton} onPress={() => setActivePicker(null)}>
|
||||
<Text style={styles.pickerDoneText}>Übernehmen</Text>
|
||||
</Pressable>
|
||||
) : null}
|
||||
</View>
|
||||
) : null}
|
||||
<Text style={styles.label}>Status</Text>
|
||||
<View style={styles.statusRow}>
|
||||
{(['Entwurf', 'Final'] as EventState[]).map((option) => (
|
||||
<Pressable
|
||||
key={option}
|
||||
style={[styles.statusButton, state === option ? styles.statusButtonActive : null]}
|
||||
onPress={() => setState(option)}>
|
||||
<Text style={[styles.statusButtonText, state === option ? styles.statusButtonTextActive : null]}>
|
||||
{option}
|
||||
</Text>
|
||||
</Pressable>
|
||||
))}
|
||||
</View>
|
||||
|
||||
<Text style={styles.label}>Projekt</Text>
|
||||
{selectedProject ? (
|
||||
@@ -279,11 +293,45 @@ export function EventCreateModal({
|
||||
<Text style={styles.secondaryButtonText}>Abbrechen</Text>
|
||||
</Pressable>
|
||||
<Pressable style={[styles.primaryButton, saving ? styles.disabled : null]} onPress={save} disabled={saving}>
|
||||
<Text style={styles.primaryButtonText}>{saving ? 'Speichere...' : 'Anlegen'}</Text>
|
||||
<Text style={styles.primaryButtonText}>{saving ? 'Speichere...' : event ? 'Speichern' : 'Anlegen'}</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
</View>
|
||||
</KeyboardAvoidingView>
|
||||
|
||||
{activePicker && Platform.OS === 'ios' ? (
|
||||
<View style={styles.pickerOverlay}>
|
||||
<Pressable style={styles.pickerBackdrop} onPress={() => setActivePicker(null)} />
|
||||
<View style={styles.pickerSheet}>
|
||||
<View style={styles.pickerHeader}>
|
||||
<Text style={styles.pickerTitle}>
|
||||
{activePicker.startsWith('start') ? 'Beginn' : 'Ende'} · {activePicker.endsWith('Date') ? 'Datum' : 'Uhrzeit'}
|
||||
</Text>
|
||||
<Pressable style={styles.pickerDoneButton} onPress={() => setActivePicker(null)}>
|
||||
<Text style={styles.pickerDoneText}>Fertig</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
<DateTimePicker
|
||||
value={activePicker.startsWith('start') ? start : end}
|
||||
mode={activePicker.endsWith('Date') ? 'date' : 'time'}
|
||||
display="spinner"
|
||||
locale="de-DE"
|
||||
minuteInterval={5}
|
||||
onChange={updatePicker}
|
||||
/>
|
||||
</View>
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
{activePicker && Platform.OS === 'android' ? (
|
||||
<DateTimePicker
|
||||
value={activePicker.startsWith('start') ? start : end}
|
||||
mode={activePicker.endsWith('Date') ? 'date' : 'time'}
|
||||
display="default"
|
||||
minuteInterval={5}
|
||||
onChange={updatePicker}
|
||||
/>
|
||||
) : null}
|
||||
</View>
|
||||
</Modal>
|
||||
);
|
||||
@@ -321,9 +369,38 @@ const styles = StyleSheet.create({
|
||||
pickerButtonText: { color: '#111827', fontSize: 15, fontWeight: '600' },
|
||||
dateInput: { flex: 1 },
|
||||
timeInput: { width: 92 },
|
||||
pickerWrap: { borderWidth: 1, borderColor: '#e5e7eb', borderRadius: 10, padding: 8 },
|
||||
pickerDoneButton: { alignSelf: 'flex-end', paddingHorizontal: 10, paddingVertical: 7 },
|
||||
pickerOverlay: { ...StyleSheet.absoluteFillObject, justifyContent: 'flex-end', zIndex: 10 },
|
||||
pickerBackdrop: { ...StyleSheet.absoluteFillObject, backgroundColor: 'rgba(17, 24, 39, 0.25)' },
|
||||
pickerSheet: {
|
||||
backgroundColor: '#ffffff',
|
||||
borderTopLeftRadius: 18,
|
||||
borderTopRightRadius: 18,
|
||||
paddingHorizontal: 12,
|
||||
paddingTop: 8,
|
||||
paddingBottom: 22,
|
||||
shadowColor: '#111827',
|
||||
shadowOpacity: 0.2,
|
||||
shadowRadius: 10,
|
||||
shadowOffset: { width: 0, height: -4 },
|
||||
},
|
||||
pickerHeader: { minHeight: 42, flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' },
|
||||
pickerTitle: { color: '#374151', fontSize: 14, fontWeight: '700' },
|
||||
pickerDoneButton: { paddingHorizontal: 10, paddingVertical: 7 },
|
||||
pickerDoneText: { color: '#3d7a30', fontSize: 14, fontWeight: '700' },
|
||||
statusRow: { flexDirection: 'row', gap: 8 },
|
||||
statusButton: {
|
||||
flex: 1,
|
||||
minHeight: 42,
|
||||
borderWidth: 1,
|
||||
borderColor: '#d1d5db',
|
||||
borderRadius: 10,
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
backgroundColor: '#ffffff',
|
||||
},
|
||||
statusButtonActive: { borderColor: PRIMARY, backgroundColor: '#eff9ea' },
|
||||
statusButtonText: { color: '#6b7280', fontSize: 14, fontWeight: '700' },
|
||||
statusButtonTextActive: { color: '#3d7a30' },
|
||||
multiline: { minHeight: 90, textAlignVertical: 'top' },
|
||||
selectedProject: {
|
||||
flexDirection: 'row',
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user