Compare commits
22 Commits
v3.14.0
...
d4c4a2b9c1
| Author | SHA1 | Date | |
|---|---|---|---|
| d4c4a2b9c1 | |||
| 6ae8b7ad9e | |||
| 544d607088 | |||
| c10bfac23b | |||
| 1b617c7910 | |||
| 9e003125c2 | |||
| 76e82eae4f | |||
| f814689ddd | |||
| 755f1b7e0d | |||
| c6fd53307c | |||
| 0777315d1d | |||
| 9676a270da | |||
| 36dffc057a | |||
| ea31a15eac | |||
| f0775ad52a | |||
| e0a94f5e29 | |||
| da84e98b8a | |||
| bfba29b15e | |||
| 7a1986bbb8 | |||
| 89185b4b08 | |||
| aa08f5c358 | |||
| 2c1047e624 |
@@ -17,7 +17,8 @@ export const outgoingRowsSchema = {
|
||||
pos: { type: "string", description: "Positionsnummer, z. B. 1.1; wird sonst erzeugt." },
|
||||
mode: { type: "string", enum: ["free", "normal", "service", "title", "text", "pagebreak"], default: "free" },
|
||||
text: { type: "string" },
|
||||
descriptionText: { type: "string" },
|
||||
description: { type: "string", description: "Positionsbeschreibung. Ohne Angabe wird sie bei mode=normal/service aus Artikel bzw. Leistung übernommen, ebenso fehlender Name, Einheit, Preis und USt-Satz." },
|
||||
descriptionText: { type: "string", description: "Veraltet; wird als description übernommen, wenn description fehlt." },
|
||||
product: { type: "integer", minimum: 1, description: "Artikel-ID bei mode=normal." },
|
||||
service: { type: "integer", minimum: 1, description: "Leistungs-ID bei mode=service." },
|
||||
quantity: { type: "number", default: 1 },
|
||||
|
||||
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"`,
|
||||
],
|
||||
}
|
||||
},
|
||||
}
|
||||
95
backend/src/mcp/outgoingDocumentLayout.ts
Normal file
95
backend/src/mcp/outgoingDocumentLayout.ts
Normal file
@@ -0,0 +1,95 @@
|
||||
import { InvoicePdfLayout } from "../utils/pdf"
|
||||
|
||||
/** Typical letterheads reserve the bottom ~35 mm of A4 for their footer. */
|
||||
export const DEFAULT_CONTENT_BOTTOM_MM = 262
|
||||
|
||||
type Warning = { type: string, page: number, message: string, insertPagebreakBeforeIndex?: number }
|
||||
|
||||
const round = (value: number) => Math.round(value * 10) / 10
|
||||
|
||||
/**
|
||||
* Summarises where rows land and suggests page breaks. FEDEO never breaks pages automatically,
|
||||
* so content below the usable area runs into the letterhead footer or off the page.
|
||||
*/
|
||||
export function analyzeOutgoingDocumentLayout(layout: InvoicePdfLayout, maxContentBottomMm = DEFAULT_CONTENT_BOTTOM_MM) {
|
||||
const warnings: Warning[] = []
|
||||
const blocks = [
|
||||
...layout.rows.filter((row) => row.mode !== "pagebreak").map((row) => ({ page: row.page, bottomMm: row.bottomMm })),
|
||||
...(layout.totals ? [layout.totals] : []),
|
||||
...(layout.endText ? [layout.endText] : []),
|
||||
]
|
||||
|
||||
const pages = Array.from({ length: layout.pageCount }, (_, offset) => {
|
||||
const page = offset + 1
|
||||
const rows = layout.rows.filter((row) => row.page === page && row.mode !== "pagebreak")
|
||||
const contentBottomMm = Math.max(0, ...blocks.filter((block) => block.page === page).map((block) => block.bottomMm))
|
||||
return {
|
||||
page,
|
||||
rows: rows.map((row) => ({ index: row.index, pos: row.pos, mode: row.mode, text: row.text, topMm: round(row.topMm), bottomMm: round(row.bottomMm) })),
|
||||
contentBottomMm: round(contentBottomMm),
|
||||
freeMm: round(maxContentBottomMm - contentBottomMm),
|
||||
}
|
||||
})
|
||||
|
||||
for (const page of pages) {
|
||||
const overflowing = page.rows.find((row) => row.bottomMm > maxContentBottomMm)
|
||||
if (overflowing) {
|
||||
// Keep headings with their first position instead of leaving them at the page end.
|
||||
let before = page.rows.indexOf(overflowing)
|
||||
while (before > 0 && page.rows[before - 1].mode === "title") before -= 1
|
||||
const target = page.rows[before]
|
||||
warnings.push({
|
||||
type: "overflow",
|
||||
page: page.page,
|
||||
message: `Position ${overflowing.pos || overflowing.index + 1} reicht bis ${overflowing.bottomMm} mm und damit über den nutzbaren Bereich (${maxContentBottomMm} mm).`,
|
||||
...(target.index > 0 ? { insertPagebreakBeforeIndex: target.index } : {}),
|
||||
})
|
||||
}
|
||||
const last = page.rows[page.rows.length - 1]
|
||||
if (last?.mode === "title" && page.page < layout.pageCount) {
|
||||
warnings.push({ type: "orphanTitle", page: page.page, message: `Überschrift ${last.pos || last.index + 1} steht allein am Seitenende.`, insertPagebreakBeforeIndex: last.index })
|
||||
}
|
||||
if (!page.rows.length && page.page > 1 && page.page !== layout.paymentQr?.page && !blocks.some((block) => block.page === page.page)) {
|
||||
warnings.push({ type: "emptyPage", page: page.page, message: "Die Seite ist leer, vermutlich durch doppelte oder abschließende Seitenumbrüche." })
|
||||
}
|
||||
}
|
||||
|
||||
// The renderer moves the payment QR code to an extra page when the amounts reach its spot.
|
||||
const qr = layout.paymentQr
|
||||
const qrAlone = qr && !blocks.some((block) => block.page === qr.page)
|
||||
if (qr && qrAlone) {
|
||||
const previous = pages[qr.page - 2]
|
||||
const reaching = previous?.rows.find((row) => row.bottomMm > qr.topMm)
|
||||
let before = reaching ? previous.rows.indexOf(reaching) : -1
|
||||
while (before > 0 && previous.rows[before - 1].mode === "title") before -= 1
|
||||
warnings.push({
|
||||
type: "paymentQrOwnPage",
|
||||
page: qr.page,
|
||||
message: `Der Überweisungs-QR-Code steht allein auf Seite ${qr.page}, weil Positionen oder Summen auf Seite ${qr.page - 1} tiefer als ${round(qr.topMm)} mm reichen. Ein früherer Seitenumbruch hält ihn bei den Summen.`,
|
||||
insertPagebreakBeforeIndex: before > 0 ? previous.rows[before].index : layout.rows.length,
|
||||
})
|
||||
}
|
||||
|
||||
for (const [name, block] of [["Summenblock", layout.totals], ["Schlusstext", layout.endText]] as const) {
|
||||
if (!block || block.bottomMm <= maxContentBottomMm || pages[block.page - 1]?.rows.some((row) => row.bottomMm > maxContentBottomMm)) continue
|
||||
warnings.push({
|
||||
type: "overflow",
|
||||
page: block.page,
|
||||
message: `${name} reicht bis ${round(block.bottomMm)} mm und damit über den nutzbaren Bereich (${maxContentBottomMm} mm).`,
|
||||
insertPagebreakBeforeIndex: layout.rows.length,
|
||||
})
|
||||
}
|
||||
|
||||
return {
|
||||
layout: {
|
||||
pageHeightMm: round(layout.pageHeightMm),
|
||||
maxContentBottomMm,
|
||||
pages,
|
||||
totals: layout.totals && { page: layout.totals.page, topMm: round(layout.totals.topMm), bottomMm: round(layout.totals.bottomMm) },
|
||||
endText: layout.endText && { page: layout.endText.page, topMm: round(layout.endText.topMm), bottomMm: round(layout.endText.bottomMm) },
|
||||
paymentQr: layout.paymentQr && { page: layout.paymentQr.page, topMm: round(layout.paymentQr.topMm), leftMm: round(layout.paymentQr.leftMm) },
|
||||
},
|
||||
warnings,
|
||||
hint: "Seitenumbruch setzen: an der Stelle insertPagebreakBeforeIndex ein Objekt {\"mode\":\"pagebreak\"} in rows einfügen (Index 0-basiert; rows.length = vor Summenblock). Zuerst mit rows in dieser Vorschau prüfen, dann mit accounting.outgoing_documents.update speichern. Die Bilder sind maßgeblich; die mm-Werte sind Schätzungen des Renderers.",
|
||||
}
|
||||
}
|
||||
62
backend/src/mcp/outgoingRowDefaults.ts
Normal file
62
backend/src/mcp/outgoingRowDefaults.ts
Normal file
@@ -0,0 +1,62 @@
|
||||
import { and, eq, inArray } from "drizzle-orm"
|
||||
import { products, services } from "../../db/schema"
|
||||
import { McpContext } from "./types"
|
||||
|
||||
const isMissing = (value: unknown) => value === undefined || value === null || value === ""
|
||||
const ids = (rows: Record<string, any>[], mode: string, key: string) =>
|
||||
[...new Set(rows.filter((row) => row.mode === mode && Number.isSafeInteger(Number(row[key])) && Number(row[key]) > 0).map((row) => Number(row[key])))]
|
||||
|
||||
const parseRow = (row: unknown) => {
|
||||
if (typeof row !== "string") return row
|
||||
try { return JSON.parse(row) } catch { return row }
|
||||
}
|
||||
|
||||
/**
|
||||
* Mirrors the document editor: selecting a product or service fills name, description, unit,
|
||||
* price, tax rate and (for services) cost centre. Values passed by the caller always win.
|
||||
*/
|
||||
export async function applyOutgoingRowCatalogDefaults(context: Pick<McpContext, "server" | "tenantId">, rows: unknown) {
|
||||
if (!Array.isArray(rows)) return rows
|
||||
const parsed = rows.map(parseRow)
|
||||
const objects = parsed.filter((row): row is Record<string, any> => !!row && typeof row === "object" && !Array.isArray(row))
|
||||
const productIds = ids(objects, "normal", "product")
|
||||
const serviceIds = ids(objects, "service", "service")
|
||||
const [productRows, serviceRows] = await Promise.all([
|
||||
productIds.length ? context.server.db.select().from(products)
|
||||
.where(and(eq(products.tenant, context.tenantId), eq(products.archived, false), inArray(products.id, productIds))) : [],
|
||||
serviceIds.length ? context.server.db.select().from(services)
|
||||
.where(and(eq(services.tenant, context.tenantId), eq(services.archived, false), inArray(services.id, serviceIds))) : [],
|
||||
])
|
||||
const productMap = new Map<number, any>(productRows.map((row: any) => [row.id, row] as const))
|
||||
const serviceMap = new Map<number, any>(serviceRows.map((row: any) => [row.id, row] as const))
|
||||
|
||||
return parsed.map((row, index) => {
|
||||
if (!row || typeof row !== "object" || Array.isArray(row)) return row
|
||||
const result = { ...(row as Record<string, any>) }
|
||||
let defaults: Record<string, unknown> | null = null
|
||||
if (result.mode === "normal" && !isMissing(result.product)) {
|
||||
const product = productMap.get(Number(result.product))
|
||||
if (!product) throw new Error(`Position ${index + 1}: Artikel ${result.product} nicht gefunden oder archiviert`)
|
||||
defaults = { text: product.name, description: product.description, unit: product.unit, price: product.selling_price, taxPercent: product.tax_percentage }
|
||||
} else if (result.mode === "service" && !isMissing(result.service)) {
|
||||
const service = serviceMap.get(Number(result.service))
|
||||
if (!service) throw new Error(`Position ${index + 1}: Leistung ${result.service} nicht gefunden oder archiviert`)
|
||||
defaults = {
|
||||
text: service.name, description: service.description, unit: service.unit,
|
||||
price: service.sellingPriceComposed?.total || service.sellingPrice, taxPercent: service.taxPercentage, costCentre: service.costcentre,
|
||||
}
|
||||
}
|
||||
// The editor stores the position text in description; descriptionText is only derived for the PDF.
|
||||
if (isMissing(result.description) && !isMissing(result.descriptionText)) result.description = result.descriptionText
|
||||
if (!defaults) return result
|
||||
for (const key of ["text", "description", "unit", "costCentre"]) {
|
||||
if (isMissing(result[key]) && !isMissing(defaults[key])) result[key] = defaults[key]
|
||||
}
|
||||
if (isMissing(result.price) && isMissing(result.inputPrice) && !isMissing(defaults.price)) {
|
||||
result.inputPrice = Number(defaults.price)
|
||||
result.price = Number(defaults.price)
|
||||
}
|
||||
if (isMissing(result.taxPercent) && !isMissing(defaults.taxPercent)) result.taxPercent = Number(defaults.taxPercent)
|
||||
return result
|
||||
})
|
||||
}
|
||||
@@ -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]))
|
||||
|
||||
@@ -2,6 +2,12 @@ import { McpToolResult } from "./types"
|
||||
|
||||
const OMIT_ARCHIVED = Symbol("omit-archived")
|
||||
|
||||
/** Attach images to a tool payload; they become MCP image content next to the JSON text. */
|
||||
export const MCP_IMAGES = Symbol("mcp-images")
|
||||
export type McpImage = { data: string, mimeType: string }
|
||||
export const withImages = <T extends Record<string, unknown>>(payload: T, images: McpImage[]) =>
|
||||
Object.assign(payload, { [MCP_IMAGES]: images })
|
||||
|
||||
function omitArchivedRecords(value: unknown): unknown | typeof OMIT_ARCHIVED {
|
||||
if (Array.isArray(value)) {
|
||||
return value
|
||||
@@ -32,12 +38,15 @@ export function asToolResult(payload: unknown): McpToolResult {
|
||||
? resultPayload as Record<string, unknown>
|
||||
: { result: resultPayload }
|
||||
|
||||
const images: McpImage[] = (payload as any)?.[MCP_IMAGES] || []
|
||||
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: JSON.stringify(resultPayload, null, 2),
|
||||
},
|
||||
...images.map((image) => ({ type: "image" as const, data: image.data, mimeType: image.mimeType })),
|
||||
],
|
||||
structuredContent,
|
||||
}
|
||||
|
||||
@@ -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,19 @@ 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 { applyOutgoingRowCatalogDefaults } from "../outgoingRowDefaults"
|
||||
import { analyzeOutgoingDocumentLayout, DEFAULT_CONTENT_BOTTOM_MM } from "../outgoingDocumentLayout"
|
||||
import { withImages } from "../result"
|
||||
import { renderOutgoingDocumentPdf } from "../../modules/outgoing-document-pdf.service"
|
||||
import { renderPdfPagesAsPng } from "../../utils/pdfPreview"
|
||||
import { outgoingStatusTools } from "./outgoingStatus"
|
||||
|
||||
export { prepareStatementAllocationInput } from "../statementAllocations"
|
||||
@@ -309,6 +317,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,
|
||||
@@ -555,6 +655,7 @@ export const accountingTools: McpTool[] = [
|
||||
},
|
||||
async handler(context, args) {
|
||||
assertNoManualDocumentNumber(args)
|
||||
if (args.rows !== undefined) args = { ...args, rows: await applyOutgoingRowCatalogDefaults(context, args.rows) }
|
||||
const payload = buildOutgoingDocumentPayload(args, context.userId, context.tenantId, true)
|
||||
payload.state = "Entwurf"
|
||||
applyOutgoingDocumentTaxType(payload, args, String(payload.type))
|
||||
@@ -623,6 +724,7 @@ export const accountingTools: McpTool[] = [
|
||||
if (!existing) throw new Error("Ausgangsbeleg nicht gefunden")
|
||||
if (existing.state !== "Entwurf") throw new Error("Finalisierte Ausgangsbelege können nicht über update geändert werden")
|
||||
|
||||
if (args.rows !== undefined) args = { ...args, rows: await applyOutgoingRowCatalogDefaults(context, args.rows) }
|
||||
const payload = buildOutgoingDocumentPayload(args, context.userId, context.tenantId)
|
||||
payload.state = "Entwurf"
|
||||
applyOutgoingDocumentTaxType(payload, args, String(payload.type || existing.type), existing.taxType, existing.rows)
|
||||
@@ -702,6 +804,69 @@ export const accountingTools: McpTool[] = [
|
||||
return { document }
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "accounting.outgoing_documents.preview",
|
||||
title: "Ausgangsbeleg-Vorschau",
|
||||
description: "Erzeugt die PDF-Vorschau eines Ausgangsbelegs wie im Belegeditor und liefert die Seiten als Bilder sowie das Seitenlayout (welche Position auf welcher Seite in welcher Höhe in mm landet) mit Warnungen zu übervollen Seiten. FEDEO bricht Positionen nicht automatisch um: Seitenumbrüche sind Positionen mit mode=pagebreak. Mit rows lässt sich eine geänderte Positionsliste testen, ohne zu speichern; anschließend mit accounting.outgoing_documents.update übernehmen.",
|
||||
requiredPermissions: ["accounting.outgoing_documents.read"],
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
required: ["id"],
|
||||
properties: {
|
||||
id: { type: "number" },
|
||||
rows: { ...outgoingRowsSchema, description: "Optional: Positionsliste nur für diese Vorschau, z. B. mit zusätzlichen {\"mode\":\"pagebreak\"}-Einträgen. Wird nicht gespeichert." },
|
||||
pages: { type: "array", items: { type: "integer", minimum: 1 }, maxItems: 10, description: "Seiten (ab 1), die als Bild geliefert werden. Standard: die ersten 10 Seiten." },
|
||||
dpi: { type: "integer", minimum: 50, maximum: 150, default: 80, description: "Auflösung der Seitenbilder." },
|
||||
images: { type: "boolean", default: true, description: "false liefert nur Layout und Warnungen ohne Bilder." },
|
||||
maxContentBottomMm: { type: "number", minimum: 150, maximum: 297, default: DEFAULT_CONTENT_BOTTOM_MM, description: "Unterkante des nutzbaren Bereichs ab Blattoberkante; darunter beginnt meist die Fußzeile des Briefpapiers." },
|
||||
includePdf: { type: "boolean", default: false, description: "PDF zusätzlich als Base64 liefern." },
|
||||
},
|
||||
additionalProperties: false,
|
||||
},
|
||||
async handler(context, args) {
|
||||
const id = numberArg(args, "id")
|
||||
if (!id) throw new Error("id ist erforderlich")
|
||||
const dpi = args.dpi === undefined ? 80 : Number(args.dpi)
|
||||
if (!Number.isSafeInteger(dpi) || dpi < 50 || dpi > 150) throw new Error("dpi muss zwischen 50 und 150 liegen")
|
||||
const maxContentBottomMm = args.maxContentBottomMm === undefined ? DEFAULT_CONTENT_BOTTOM_MM : Number(args.maxContentBottomMm)
|
||||
if (!Number.isFinite(maxContentBottomMm) || maxContentBottomMm < 150 || maxContentBottomMm > 297) throw new Error("maxContentBottomMm muss zwischen 150 und 297 liegen")
|
||||
if (args.pages !== undefined && (!Array.isArray(args.pages) || args.pages.length > 10
|
||||
|| args.pages.some((page) => !Number.isSafeInteger(page) || (page as number) < 1))) {
|
||||
throw new Error("pages muss bis zu 10 Seitenzahlen ab 1 enthalten")
|
||||
}
|
||||
|
||||
const [existing] = await context.server.db
|
||||
.select()
|
||||
.from(createddocuments)
|
||||
.where(and(eq(createddocuments.id, id), eq(createddocuments.tenant, context.tenantId)))
|
||||
.limit(1)
|
||||
if (!existing) throw new Error("Ausgangsbeleg nicht gefunden")
|
||||
|
||||
const document: Record<string, any> = { ...existing }
|
||||
if (args.rows !== undefined) {
|
||||
const payload: Record<string, unknown> = {
|
||||
rows: normalizeOutgoingDocumentRows(await applyOutgoingRowCatalogDefaults(context, optionalArrayArg(args, "rows") || [])),
|
||||
}
|
||||
applyOutgoingDocumentTaxType(payload, {}, existing.type, existing.taxType, existing.rows)
|
||||
document.rows = payload.rows
|
||||
}
|
||||
|
||||
const { pdf, layout } = await renderOutgoingDocumentPdf(context.server, context.tenantId, document)
|
||||
const analysis = analyzeOutgoingDocumentLayout(layout, maxContentBottomMm)
|
||||
const requestedPages = (args.pages as number[] | undefined) || Array.from({ length: Math.min(layout.pageCount, 10) }, (_, index) => index + 1)
|
||||
const pages = [...new Set(requestedPages)].filter((page) => page <= layout.pageCount)
|
||||
const images = args.images === false ? [] : await renderPdfPagesAsPng(pdf, pages, dpi)
|
||||
|
||||
return withImages({
|
||||
document: { id: existing.id, type: existing.type, state: existing.state, documentNumber: existing.documentNumber, title: existing.title },
|
||||
previewOnly: args.rows !== undefined,
|
||||
pageCount: layout.pageCount,
|
||||
imagePages: images.map((image) => image.page),
|
||||
...analysis,
|
||||
...(args.includePdf === true ? { pdfBase64: pdf.toString("base64") } : {}),
|
||||
}, images.map((image) => ({ data: image.png.toString("base64"), mimeType: "image/png" })))
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "accounting.outgoing_documents.finalize",
|
||||
title: "Ausgangsbeleg finalisieren",
|
||||
@@ -741,6 +906,7 @@ export const accountingTools: McpTool[] = [
|
||||
if (!existing) throw new Error("Ausgangsbeleg nicht gefunden")
|
||||
if (existing.documentNumber) throw new Error("Ausgangsbeleg wurde bereits finalisiert")
|
||||
|
||||
if (args.rows !== undefined) args = { ...args, rows: await applyOutgoingRowCatalogDefaults(context, args.rows) }
|
||||
const payload = buildOutgoingDocumentPayload(args, context.userId, context.tenantId)
|
||||
const result = await useNextNumberRangeNumber(context.server, context.tenantId, existing.type)
|
||||
|
||||
@@ -1011,7 +1177,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 +1213,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 +1249,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 +1382,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 +1501,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)
|
||||
|
||||
@@ -13,6 +13,10 @@ export type McpToolResult = {
|
||||
content: Array<{
|
||||
type: "text"
|
||||
text: string
|
||||
} | {
|
||||
type: "image"
|
||||
data: string
|
||||
mimeType: string
|
||||
}>
|
||||
structuredContent?: Record<string, unknown>
|
||||
isError?: boolean
|
||||
@@ -23,6 +27,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.",
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -242,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
|
||||
|
||||
@@ -144,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())
|
||||
|
||||
@@ -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
|
||||
}
|
||||
276
backend/src/modules/outgoing-document-pdf.service.ts
Normal file
276
backend/src/modules/outgoing-document-pdf.service.ts
Normal file
@@ -0,0 +1,276 @@
|
||||
import { FastifyInstance } from "fastify"
|
||||
import dayjs from "dayjs"
|
||||
import { and, eq, inArray } from "drizzle-orm"
|
||||
import {
|
||||
authProfiles,
|
||||
bankaccounts,
|
||||
contacts,
|
||||
contracts,
|
||||
createddocuments,
|
||||
customers,
|
||||
letterheads,
|
||||
plants,
|
||||
products,
|
||||
projects,
|
||||
services,
|
||||
tenants,
|
||||
units,
|
||||
} from "../../db/schema"
|
||||
import { documentTemplateHandlebars } from "../utils/handlebars"
|
||||
import { createInvoicePDF, InvoicePdfLayout } from "../utils/pdf"
|
||||
|
||||
const quoteLikeDocumentTypes = ["quotes", "costEstimates"]
|
||||
const deliveryNoteLikeDocumentTypes = ["deliveryNotes", "packingSlips"]
|
||||
const invoiceLikeDocumentTypes = ["invoices", "advanceInvoices", "serialInvoices", "cancellationInvoices"]
|
||||
|
||||
/** Same format as useCurrency in the frontend. */
|
||||
export const renderCurrency = (value: any, currency = "€") =>
|
||||
`${Number(value).toFixed(2).replace(".", ",")} ${currency}`.replace(/\B(?=(\d{3})+(?!\d))/g, ".")
|
||||
|
||||
const rowSum = (row: any) => Number(row.quantity) * Number(row.price) * (1 - Number(row.discountPercent) / 100)
|
||||
|
||||
export function documentNumberTitle(type: string) {
|
||||
if (invoiceLikeDocumentTypes.includes(type)) return "Rechnungsnummer"
|
||||
if (quoteLikeDocumentTypes.includes(type)) return type === "costEstimates" ? "Kostenschätzungsnummer" : "Angebotsnummer"
|
||||
if (deliveryNoteLikeDocumentTypes.includes(type)) return type === "packingSlips" ? "Packscheinnummer" : "Lieferscheinnummer"
|
||||
if (type === "confirmationOrders") return "Auftragsbestätigungsnr."
|
||||
return "Belegnummer"
|
||||
}
|
||||
|
||||
const formatNumberLikeValue = (value: any) => {
|
||||
if (value === null || value === undefined || value === "") return "-"
|
||||
if (typeof value === "string" || typeof value === "number") return String(value)
|
||||
const directValue = value.value ?? value.number ?? value.currentNumber ?? value.customerNumber ?? value.id
|
||||
if (directValue !== null && directValue !== undefined && directValue !== "") return String(directValue)
|
||||
if (value.prefix !== undefined || value.nextNumber !== undefined || value.suffix !== undefined) {
|
||||
return `${value.prefix || ""}${value.nextNumber || ""}${value.suffix || ""}` || "-"
|
||||
}
|
||||
return "-"
|
||||
}
|
||||
|
||||
/** Port of documentTotal from the document editor. */
|
||||
export function calculateOutgoingDocumentTotals(document: any, advanceInvoices: any[]) {
|
||||
let totalNet = 0, total19 = 0, totalNet19 = 0, total7 = 0, totalNet7 = 0, totalNet0 = 0
|
||||
const rows = document.rows || []
|
||||
rows.filter((row: any) => !row.optional && !row.alternative).forEach((row: any) => {
|
||||
if (["pagebreak", "title", "text"].includes(row.mode)) return
|
||||
const rowPrice = Number(rowSum(row).toFixed(3))
|
||||
totalNet += rowPrice
|
||||
if (row.taxPercent === 19) { total19 += rowPrice * 0.19; totalNet19 += rowPrice }
|
||||
else if (row.taxPercent === 7) { total7 += rowPrice * 0.07; totalNet7 += rowPrice }
|
||||
else if (row.taxPercent === 0) totalNet0 += rowPrice
|
||||
})
|
||||
|
||||
const titleSums: Record<string, number> = {}
|
||||
const titleSumsTransfer: Record<string, number> = {}
|
||||
let activeTitleKeys: string[] = []
|
||||
let transferCounter = 0
|
||||
rows.forEach((row: any) => {
|
||||
if (row.mode === "title") {
|
||||
const title = `${row.pos} - ${row.text}`
|
||||
const titleLevel = Math.min(Math.max(Number(row.titleLevel) || 1, 1), 3)
|
||||
titleSums[title] = 0
|
||||
if (activeTitleKeys.some(Boolean)) titleSumsTransfer[title] = transferCounter
|
||||
activeTitleKeys = activeTitleKeys.slice(0, titleLevel - 1)
|
||||
activeTitleKeys[titleLevel - 1] = title
|
||||
activeTitleKeys = activeTitleKeys.slice(0, titleLevel)
|
||||
} else if (!["pagebreak", "text"].includes(row.mode) && activeTitleKeys.some(Boolean) && !row.optional && !row.alternative) {
|
||||
const sum = rowSum(row)
|
||||
activeTitleKeys.forEach((key) => { if (key) titleSums[key] = Number(titleSums[key]) + sum })
|
||||
transferCounter += sum
|
||||
}
|
||||
})
|
||||
|
||||
const totalGross = Number(totalNet.toFixed(2)) + Number(total19.toFixed(2)) + Number(total7.toFixed(2))
|
||||
const totalGrossAlreadyPaid = advanceInvoices.reduce((sum, invoice) => {
|
||||
const advanceRow = (invoice?.rows || []).find((row: any) => row.advanceInvoiceData)
|
||||
return advanceRow ? sum + advanceRow.price * ((100 + advanceRow.taxPercent) / 100) : sum
|
||||
}, 0)
|
||||
const totalSumToPay = document.type === "invoices" ? totalGross - totalGrossAlreadyPaid
|
||||
: document.type === "cancellationInvoices" ? totalGross + totalGrossAlreadyPaid : 0
|
||||
|
||||
return { titleSums, titleSumsTransfer, totalNet, total19, totalNet19, total7, totalNet7, total0: 0, totalNet0, totalGross, totalGrossAlreadyPaid, totalSumToPay }
|
||||
}
|
||||
|
||||
export type OutgoingDocumentPdfContext = {
|
||||
tenant: any
|
||||
customer: any
|
||||
contact?: any
|
||||
contactPerson?: any
|
||||
plant?: any
|
||||
project?: any
|
||||
contract?: any
|
||||
units: any[]
|
||||
products: any[]
|
||||
services: any[]
|
||||
bankAccounts: any[]
|
||||
advanceInvoices: any[]
|
||||
}
|
||||
|
||||
/** Port of getDocumentData from the document editor, so MCP previews match the UI preview. */
|
||||
export function buildOutgoingDocumentPdfData(source: any, data: OutgoingDocumentPdfContext) {
|
||||
const document = structuredClone(source)
|
||||
document.rows = document.rows || []
|
||||
const address = document.address || {}
|
||||
const customer = data.customer || {}
|
||||
const contact = data.contact || null
|
||||
const contactPerson = data.contactPerson || {}
|
||||
const businessInfo = data.tenant.businessInfo || {}
|
||||
const paymentQrBankAccount = data.bankAccounts.find((account) => !account.archived && !account.expired && account.iban)
|
||||
const paymentQrIban = businessInfo.iban || paymentQrBankAccount?.iban
|
||||
const paymentQrBic = businessInfo.bic || paymentQrBankAccount?.bic
|
||||
const paymentQrRecipient = businessInfo.bankAccountOwner || paymentQrBankAccount?.ownerName || businessInfo.name || data.tenant.name
|
||||
|
||||
if ((data.tenant.extraModules || []).includes("agriculture")) {
|
||||
document.rows.forEach((row: any) => {
|
||||
if (row.agriculture?.dieselUsage) {
|
||||
row.agriculture.description = `${row.agriculture.dieselUsage} L Diesel zu ${renderCurrency(row.agriculture.dieselPrice)}/L verbraucht ${row.description ? "\n" + row.description : ""}`
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const totals = calculateOutgoingDocumentTotals(document, data.advanceInvoices)
|
||||
const rows = document.rows.map((row: any) => {
|
||||
if (!["pagebreak", "title"].includes(row.mode)) {
|
||||
if (row.agriculture?.description) row.descriptionText = row.agriculture.description
|
||||
else if (row.description) row.descriptionText = row.description
|
||||
else delete row.descriptionText
|
||||
}
|
||||
if (["pagebreak", "title", "text"].includes(row.mode)) return row
|
||||
if (row.mode === "normal") row.text = data.products.find((item) => item.id === row.product)?.name || ""
|
||||
if (row.mode === "service") row.text = data.services.find((item) => item.id === row.service)?.name || ""
|
||||
return {
|
||||
...row,
|
||||
rowAmount: renderCurrency(rowSum(row)),
|
||||
quantity: String(row.quantity).replace(".", ","),
|
||||
unit: data.units.find((item) => item.id === row.unit)?.short || "",
|
||||
pos: String(row.pos),
|
||||
price: renderCurrency(row.price),
|
||||
discountText: `(Rabatt: ${row.discountPercent} %)`,
|
||||
}
|
||||
})
|
||||
|
||||
const context = {
|
||||
lohnkosten: document.report?.totalHoursSellingPrice ? renderCurrency(document.report.totalHoursSellingPrice) : null,
|
||||
anrede: contact?.salutation || customer.salutation,
|
||||
titel: contact?.title || customer.title,
|
||||
vorname: contact?.firstName || customer.firstname,
|
||||
nachname: contact?.lastName || customer.lastname,
|
||||
kundenname: customer.name,
|
||||
zahlungsziel_in_tagen: document.paymentDays,
|
||||
zahlungsart: document.payment_type === "transfer" ? "Überweisung" : "Lastschrift",
|
||||
diesel_gesamtverbrauch: document.agriculture?.dieselUsageTotal,
|
||||
}
|
||||
const formatDate = (value: any) => value ? dayjs(value).format("DD.MM.YYYY") : "XXXX"
|
||||
const formatSums = (sums: Record<string, number>) => Object.fromEntries(Object.entries(sums).map(([key, value]) => [key, renderCurrency(value)]))
|
||||
const recipientCountry = String(address.country ?? customer.infoData?.country ?? "").trim()
|
||||
const contactTel = document.contactTel || contactPerson.fixed_tel || contactPerson.mobile_tel
|
||||
|
||||
return {
|
||||
type: document.type,
|
||||
taxType: document.taxType,
|
||||
adressLine: `${businessInfo.name}, ${businessInfo.street}, ${businessInfo.zip} ${businessInfo.city}`,
|
||||
recipient: [
|
||||
customer.name,
|
||||
...(customer.nameAddition ? [customer.nameAddition] : []),
|
||||
...(contact ? [`${contact.firstName} ${contact.lastName}`] : []),
|
||||
address.street,
|
||||
...(address.special ? [address.special] : []),
|
||||
`${address.zip} ${address.city}`,
|
||||
...(recipientCountry && recipientCountry.toLocaleLowerCase("de") !== "deutschland" ? [recipientCountry] : []),
|
||||
],
|
||||
info: [
|
||||
{ label: documentNumberTitle(document.type), content: document.documentNumber || "XXXX" },
|
||||
{ label: "Kundennummer", content: formatNumberLikeValue(customer.customerNumber) },
|
||||
{ label: "Belegdatum", content: formatDate(document.documentDate) },
|
||||
...(document.deliveryDateType !== "Kein Lieferdatum anzeigen" ? [{
|
||||
label: document.deliveryDateType,
|
||||
content: !["Lieferzeitraum", "Leistungszeitraum"].includes(document.deliveryDateType)
|
||||
? formatDate(document.deliveryDate)
|
||||
: `${formatDate(document.deliveryDate)} - ${formatDate(document.deliveryDateEnd)}`,
|
||||
}] : []),
|
||||
{ label: "Ansprechpartner", content: contactPerson.full_name },
|
||||
...(contactTel ? [{ label: "Telefon", content: contactTel }] : []),
|
||||
...(contactPerson.email ? [{ label: "E-Mail", content: contactPerson.email }] : []),
|
||||
...(document.plant ? [{ label: "Objekt", content: data.plant?.name || "Objekt nicht gefunden" }] : []),
|
||||
...(document.project ? [{ label: "Projekt", content: data.project?.name || "Projekt nicht gefunden" }] : []),
|
||||
...(document.contract ? [{ label: "Vertrag", content: data.contract?.contractNumber || "Vertrag nicht gefunden" }] : []),
|
||||
],
|
||||
title: document.title,
|
||||
description: document.description,
|
||||
endText: documentTemplateHandlebars.compile(document.endText || "")(context),
|
||||
startText: documentTemplateHandlebars.compile(document.startText || "")(context),
|
||||
rows,
|
||||
totalArray: [
|
||||
{ label: "Nettobetrag", content: renderCurrency(totals.totalNet) },
|
||||
...[19, 7, 0].flatMap((rate) => rows.find((row: any) => row.taxPercent === rate) && document.taxType !== "13b UStG" ? [{
|
||||
label: `zzgl. ${rate}% USt auf ${renderCurrency((totals as any)[`totalNet${rate}`])}`,
|
||||
content: renderCurrency((totals as any)[`total${rate}`]),
|
||||
}] : []),
|
||||
{ label: "Gesamtbetrag", content: renderCurrency(totals.totalGross) },
|
||||
],
|
||||
total: {
|
||||
totalNet: renderCurrency(totals.totalNet),
|
||||
total19: renderCurrency(totals.total19),
|
||||
total0: renderCurrency(totals.total0),
|
||||
totalGross: renderCurrency(totals.totalGross),
|
||||
totalGrossAlreadyPaid: renderCurrency(totals.totalGrossAlreadyPaid),
|
||||
totalSumToPay: renderCurrency(totals.totalSumToPay),
|
||||
titleSums: formatSums(totals.titleSums),
|
||||
titleSumsTransfer: formatSums(totals.titleSumsTransfer),
|
||||
},
|
||||
agriculture: document.agriculture,
|
||||
usedAdvanceInvoices: data.advanceInvoices,
|
||||
paymentQr: paymentQrIban && document.payment_type === "transfer" ? {
|
||||
iban: paymentQrIban,
|
||||
bic: paymentQrBic,
|
||||
recipientName: paymentQrRecipient,
|
||||
amount: totals.totalSumToPay,
|
||||
remittance: document.documentNumber || document.title,
|
||||
} : null,
|
||||
}
|
||||
}
|
||||
|
||||
const one = async (server: FastifyInstance, table: any, id: unknown, tenantId: number) => {
|
||||
if (id === null || id === undefined) return null
|
||||
const [row] = await server.db.select().from(table).where(and(eq(table.id, id as any), eq(table.tenant, tenantId))).limit(1)
|
||||
return row || null
|
||||
}
|
||||
|
||||
export async function renderOutgoingDocumentPdf(server: FastifyInstance, tenantId: number, document: any) {
|
||||
if (!document.letterhead) throw Object.assign(new Error("Es ist kein Briefpapier ausgewählt"), { statusCode: 400 })
|
||||
if (!document.customer) throw Object.assign(new Error("Es ist kein Kunde ausgewählt"), { statusCode: 400 })
|
||||
const rows = document.rows || []
|
||||
const productIds = [...new Set(rows.filter((row: any) => row.product).map((row: any) => Number(row.product)))] as number[]
|
||||
const serviceIds = [...new Set(rows.filter((row: any) => row.service).map((row: any) => Number(row.service)))] as number[]
|
||||
const advanceIds = (Array.isArray(document.usedAdvanceInvoices) ? document.usedAdvanceInvoices : []).map(Number) as number[]
|
||||
|
||||
const [[tenant], letterhead, customer, contact, plant, project, contract, unitRows, productRows, serviceRows, bankAccountRows, advanceInvoices, [contactPerson]] = await Promise.all([
|
||||
server.db.select().from(tenants).where(eq(tenants.id, tenantId)).limit(1),
|
||||
one(server, letterheads, document.letterhead, tenantId),
|
||||
one(server, customers, document.customer, tenantId),
|
||||
one(server, contacts, document.contact, tenantId),
|
||||
one(server, plants, document.plant, tenantId),
|
||||
one(server, projects, document.project, tenantId),
|
||||
one(server, contracts, document.contract, tenantId),
|
||||
server.db.select().from(units),
|
||||
productIds.length ? server.db.select().from(products).where(and(eq(products.tenant, tenantId), inArray(products.id, productIds))) : [],
|
||||
serviceIds.length ? server.db.select().from(services).where(and(eq(services.tenant, tenantId), inArray(services.id, serviceIds))) : [],
|
||||
server.db.select().from(bankaccounts).where(and(eq(bankaccounts.tenant, tenantId), eq(bankaccounts.archived, false))),
|
||||
advanceIds.length ? server.db.select().from(createddocuments).where(and(eq(createddocuments.tenant, tenantId), inArray(createddocuments.id, advanceIds))) : [],
|
||||
document.created_by
|
||||
? server.db.select().from(authProfiles).where(and(eq(authProfiles.user_id, document.created_by), eq(authProfiles.tenant_id, tenantId))).limit(1)
|
||||
: [null],
|
||||
])
|
||||
if (!letterhead?.path) throw Object.assign(new Error("Briefpapier nicht gefunden"), { statusCode: 400 })
|
||||
if (!customer) throw Object.assign(new Error("Kunde nicht gefunden"), { statusCode: 400 })
|
||||
|
||||
const pdfData = buildOutgoingDocumentPdfData(document, {
|
||||
tenant, customer, contact, contactPerson, plant, project, contract,
|
||||
units: unitRows, products: productRows, services: serviceRows, bankAccounts: bankAccountRows,
|
||||
advanceInvoices: advanceIds.map((id) => advanceInvoices.find((invoice: any) => invoice.id === id)).filter(Boolean),
|
||||
})
|
||||
const layout: InvoicePdfLayout = { pageHeightMm: 297, rows: [], pageCount: 0 }
|
||||
const pdf: any = await createInvoicePDF(server, "base64", pdfData, letterhead.path, layout)
|
||||
return { pdf: Buffer.from(pdf.base64, "base64"), layout }
|
||||
}
|
||||
@@ -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")
|
||||
|
||||
@@ -158,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)]
|
||||
@@ -295,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) => {
|
||||
@@ -335,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}`,
|
||||
@@ -387,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,
|
||||
|
||||
@@ -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) => {
|
||||
|
||||
@@ -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")),
|
||||
},
|
||||
})),
|
||||
}))
|
||||
|
||||
@@ -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`
|
||||
}
|
||||
|
||||
|
||||
@@ -117,7 +117,17 @@ const getDuration = (time) => {
|
||||
}
|
||||
|
||||
|
||||
export const createInvoicePDF = async (server:FastifyInstance, returnMode, invoiceData, backgroundPath:string) => {
|
||||
/** Positions in mm from the top edge, recorded while rendering for layout checks (e.g. page breaks). */
|
||||
export type InvoicePdfLayout = {
|
||||
pageHeightMm: number
|
||||
rows: Array<{ index: number, id?: string, pos?: string, mode: string, text: string, page: number, topMm: number, bottomMm: number }>
|
||||
totals?: { page: number, topMm: number, bottomMm: number }
|
||||
endText?: { page: number, topMm: number, bottomMm: number }
|
||||
paymentQr?: { page: number, topMm: number, leftMm: number }
|
||||
pageCount: number
|
||||
}
|
||||
|
||||
export const createInvoicePDF = async (server:FastifyInstance, returnMode, invoiceData, backgroundPath:string, layout?: InvoicePdfLayout) => {
|
||||
const deliveryNoteLikeDocumentTypes = ["deliveryNotes", "packingSlips"]
|
||||
const isPackingSlip = invoiceData?.type === "packingSlips"
|
||||
|
||||
@@ -153,8 +163,14 @@ export const createInvoicePDF = async (server:FastifyInstance, returnMode, invoi
|
||||
- paymentQrLayout.sizeMm * mm
|
||||
}
|
||||
|
||||
// Top edge (mm from the top) of the QR label at its fixed bottom-right spot.
|
||||
const getPaymentQrTopMm = (page: any) => page.getHeight() / mm
|
||||
- (paymentQrLayout.bottomMarginMm + paymentQrLayout.sizeMm + paymentQrLayout.labelGapMm) - 8 / mm
|
||||
// Set once the amounts are placed: the QR moves to its own page if it would cover them.
|
||||
let paymentQrOnNewPage = false
|
||||
|
||||
const getTextWidthBeforePaymentQr = (page: any, startX: number) => {
|
||||
if (!paymentQrCode) return 500
|
||||
if (!paymentQrCode || paymentQrOnNewPage) return 500
|
||||
|
||||
return Math.max(
|
||||
240,
|
||||
@@ -496,6 +512,7 @@ export const createInvoicePDF = async (server:FastifyInstance, returnMode, invoi
|
||||
}
|
||||
|
||||
invoiceData.rows.forEach((row, index) => {
|
||||
const layoutTop = rowHeight
|
||||
|
||||
if (!["pagebreak", "title", "text"].includes(row.mode)) {
|
||||
|
||||
@@ -881,10 +898,18 @@ export const createInvoicePDF = async (server:FastifyInstance, returnMode, invoi
|
||||
}
|
||||
}
|
||||
console.log(rowHeight)
|
||||
layout?.rows.push({
|
||||
index, id: row.id, pos: row.pos, mode: row.mode, text: String(row.text || "").slice(0, 80),
|
||||
// rowHeight is the baseline of the first text line; shift to the visible cap height.
|
||||
page: pageCounter, topMm: row.mode === "pagebreak" ? 30 : layoutTop - 3, bottomMm: row.mode === "pagebreak" ? 30 : rowHeight - 3,
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
let endTextDiff = 35
|
||||
const layoutContentEnd = rowHeight
|
||||
// Visible bottom of the last row (rowHeight is the next baseline); totals extend it below.
|
||||
let amountsBottomMm = rowHeight - 3
|
||||
|
||||
if (!deliveryNoteLikeDocumentTypes.includes(invoiceData.type)) {
|
||||
pages[pageCounter - 1].drawLine({
|
||||
@@ -999,8 +1024,23 @@ export const createInvoicePDF = async (server:FastifyInstance, returnMode, invoi
|
||||
|
||||
}
|
||||
|
||||
// Totals are baselines 8 mm apart; tax notes (13b/19/12.3) add one more line below.
|
||||
const totalLines = invoiceData.totalArray.length + (["13b UStG", "19 UStG", "12.3 UStG"].includes(invoiceData.taxType) ? 1 : 0)
|
||||
amountsBottomMm = rowHeight + (totalLines - 1) * 8 + 1
|
||||
paymentQrOnNewPage = Boolean(paymentQrCode) && amountsBottomMm + 2 > getPaymentQrTopMm(pages[pageCounter - 1])
|
||||
|
||||
const endTextPosition = getCoordinatesForPDFLib(21, rowHeight + endTextDiff + (invoiceData.totalArray.length - 3) * 8, page1)
|
||||
|
||||
if (layout) {
|
||||
const maxWidth = getTextWidthBeforePaymentQr(pages[pageCounter - 1], endTextPosition.x)
|
||||
const lines = String(invoiceData.endText || "").split("\n")
|
||||
.reduce((sum, line) => sum + Math.max(1, Math.ceil(font.widthOfTextAtSize(line, 10) / maxWidth)), 0)
|
||||
const topMm = rowHeight + endTextDiff + (invoiceData.totalArray.length - 3) * 8
|
||||
layout.totals = { page: pageCounter, topMm: layoutContentEnd, bottomMm: amountsBottomMm }
|
||||
// drawText places the baseline of the first line; 10 pt line height ≈ 3.53 mm.
|
||||
layout.endText = { page: pageCounter, topMm: topMm - 3.53, bottomMm: topMm + (lines - 1) * 3.53 + 1 }
|
||||
}
|
||||
|
||||
pages[pageCounter - 1].drawText(invoiceData.endText, {
|
||||
...endTextPosition,
|
||||
size: 10,
|
||||
@@ -1012,6 +1052,16 @@ export const createInvoicePDF = async (server:FastifyInstance, returnMode, invoi
|
||||
}
|
||||
|
||||
if (paymentQrCode) {
|
||||
// Invoice-like documents decide this before placing the end text.
|
||||
if (deliveryNoteLikeDocumentTypes.includes(invoiceData.type)) {
|
||||
paymentQrOnNewPage = amountsBottomMm + 2 > getPaymentQrTopMm(pages[pages.length - 1])
|
||||
}
|
||||
if (paymentQrOnNewPage) {
|
||||
// Positions or totals reach the QR area; never draw the code over amounts.
|
||||
const qrPage = pdfDoc.addPage()
|
||||
qrPage.drawPage(secondPageBackground, { x: 0, y: 0 })
|
||||
pages.push(qrPage)
|
||||
}
|
||||
const lastPage = pages[pages.length - 1]
|
||||
const qrSize = paymentQrLayout.sizeMm * mm
|
||||
const bottomMargin = paymentQrLayout.bottomMarginMm * mm
|
||||
@@ -1030,6 +1080,12 @@ export const createInvoicePDF = async (server:FastifyInstance, returnMode, invoi
|
||||
font: fontBold,
|
||||
})
|
||||
|
||||
if (layout) layout.paymentQr = {
|
||||
page: pages.length,
|
||||
topMm: (lastPage.getHeight() - (qrY + qrSize + labelGap + 8)) / mm,
|
||||
leftMm: qrX / mm,
|
||||
}
|
||||
|
||||
lastPage.drawImage(paymentQrCode, {
|
||||
x: qrX,
|
||||
y: qrY,
|
||||
@@ -1038,6 +1094,11 @@ export const createInvoicePDF = async (server:FastifyInstance, returnMode, invoi
|
||||
})
|
||||
}
|
||||
|
||||
if (layout) {
|
||||
layout.pageCount = pages.length
|
||||
layout.pageHeightMm = page1.getHeight() / mm
|
||||
}
|
||||
|
||||
return await pdfDoc.saveAsBase64()
|
||||
|
||||
}
|
||||
|
||||
30
backend/src/utils/pdfPreview.ts
Normal file
30
backend/src/utils/pdfPreview.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import fs from "node:fs/promises"
|
||||
import os from "node:os"
|
||||
import path from "node:path"
|
||||
import { execFile } from "node:child_process"
|
||||
import { promisify } from "node:util"
|
||||
|
||||
const execFileAsync = promisify(execFile)
|
||||
|
||||
/** Renders selected PDF pages (1-based) to PNG with poppler's pdftoppm. */
|
||||
export async function renderPdfPagesAsPng(pdf: Buffer, pages: number[], dpi: number) {
|
||||
const dir = await fs.mkdtemp(path.join(os.tmpdir(), "fedeo-preview-"))
|
||||
try {
|
||||
const input = path.join(dir, "document.pdf")
|
||||
await fs.writeFile(input, pdf)
|
||||
const images: Array<{ page: number, png: Buffer }> = []
|
||||
for (const page of pages) {
|
||||
const prefix = path.join(dir, `page-${page}`)
|
||||
try {
|
||||
await execFileAsync("pdftoppm", ["-png", "-r", String(dpi), "-f", String(page), "-l", String(page), "-singlefile", input, prefix], { timeout: 30_000 })
|
||||
} catch (error: any) {
|
||||
if (error?.code === "ENOENT") throw Object.assign(new Error("Die Seitenvorschau benötigt pdftoppm (poppler-utils) auf dem Server."), { statusCode: 501 })
|
||||
throw error
|
||||
}
|
||||
images.push({ page, png: await fs.readFile(`${prefix}.png`) })
|
||||
}
|
||||
return images
|
||||
} finally {
|
||||
await fs.rm(dir, { recursive: true, force: true })
|
||||
}
|
||||
}
|
||||
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)
|
||||
})
|
||||
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)
|
||||
})
|
||||
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"])
|
||||
})
|
||||
125
backend/tests/mcpOutgoingDocumentPreview.test.ts
Normal file
125
backend/tests/mcpOutgoingDocumentPreview.test.ts
Normal file
@@ -0,0 +1,125 @@
|
||||
import assert from "node:assert/strict"
|
||||
import test from "node:test"
|
||||
import { execFileSync } from "node:child_process"
|
||||
import { Readable } from "node:stream"
|
||||
import { PDFDocument } from "pdf-lib"
|
||||
import { initS3, s3 } from "../src/utils/s3"
|
||||
import { createInvoicePDF, InvoicePdfLayout } from "../src/utils/pdf"
|
||||
import { buildOutgoingDocumentPdfData, calculateOutgoingDocumentTotals } from "../src/modules/outgoing-document-pdf.service"
|
||||
import { analyzeOutgoingDocumentLayout } from "../src/mcp/outgoingDocumentLayout"
|
||||
import { renderPdfPagesAsPng } from "../src/utils/pdfPreview"
|
||||
import { asToolResult, withImages } from "../src/mcp/result"
|
||||
import { mcpToolMap } from "../src/mcp/registry"
|
||||
|
||||
const hasPdftoppm = (() => { try { execFileSync("pdftoppm", ["-v"], { stdio: "ignore" }); return true } catch { return false } })()
|
||||
|
||||
const document = (rows: any[]) => ({
|
||||
id: 1, type: "invoices", taxType: "Standard", state: "Entwurf", title: "Rechnung-Nr. XXXX", documentDate: "2026-10-28",
|
||||
deliveryDateType: "Lieferdatum", deliveryDate: "2026-10-27", address: { street: "Weg 1", zip: "12345", city: "Ort" },
|
||||
startText: "Hallo {{vorname}},", endText: "Zahlbar in {{zahlungsziel_in_tagen}} Tagen.", paymentDays: 14, payment_type: "transfer",
|
||||
usedAdvanceInvoices: [], report: {}, rows,
|
||||
})
|
||||
const context = {
|
||||
tenant: { name: "Firma", businessInfo: { name: "Firma", street: "Str. 1", zip: "1", city: "Stadt", iban: "DE02120300000000202051" }, extraModules: [] },
|
||||
customer: { name: "Kunde", customerNumber: "K-1", firstname: "Ada" },
|
||||
contactPerson: { full_name: "Bea Beispiel", email: "bea@example.invalid" },
|
||||
units: [{ id: 1, short: "Stk" }], products: [{ id: 3, name: "Kabel" }], services: [], bankAccounts: [], advanceInvoices: [],
|
||||
}
|
||||
const positions = (count: number) => Array.from({ length: count }, (_, index) => ({
|
||||
id: `r${index}`, pos: String(index + 1), mode: index % 2 ? "normal" : "free", product: 3, text: `Position ${index + 1}`,
|
||||
description: "Zweizeilige\nBeschreibung", quantity: 2, unit: 1, price: 10.5, taxPercent: 19, discountPercent: 0,
|
||||
}))
|
||||
|
||||
test("pdf data matches the editor: title sums, transfers, optional rows and handlebars", () => {
|
||||
const rows = [
|
||||
{ pos: "1", mode: "title", text: "Bau", titleLevel: 1 },
|
||||
{ pos: "1.1", mode: "free", text: "A", quantity: 2, price: 10, discountPercent: 0, taxPercent: 19 },
|
||||
{ pos: "1.2", mode: "free", text: "B", quantity: 1, price: 5, discountPercent: 0, taxPercent: 19, optional: true },
|
||||
{ mode: "pagebreak" },
|
||||
{ pos: "2", mode: "title", text: "Elektro", titleLevel: 1 },
|
||||
{ pos: "2.1", mode: "normal", product: 3, quantity: 1, price: 100, discountPercent: 10, taxPercent: 7, unit: 1 },
|
||||
]
|
||||
const totals = calculateOutgoingDocumentTotals({ type: "invoices", rows }, [])
|
||||
assert.equal(totals.totalNet, 110)
|
||||
assert.deepEqual(totals.titleSums, { "1 - Bau": 20, "2 - Elektro": 90 })
|
||||
assert.deepEqual(totals.titleSumsTransfer, { "2 - Elektro": 20 })
|
||||
const data: any = buildOutgoingDocumentPdfData(document(rows), context)
|
||||
assert.equal(data.startText, "Hallo Ada,")
|
||||
assert.equal(data.endText, "Zahlbar in 14 Tagen.")
|
||||
assert.equal(data.rows[5].text, "Kabel")
|
||||
assert.equal(data.rows[5].unit, "Stk")
|
||||
assert.equal(data.total.titleSumsTransfer["2 - Elektro"], "20,00 €")
|
||||
assert.deepEqual(data.totalArray.map((item: any) => item.label), ["Nettobetrag", "zzgl. 19% USt auf 20,00 €", "zzgl. 7% USt auf 90,00 €", "Gesamtbetrag"])
|
||||
assert.equal(data.info[0].label, "Rechnungsnummer")
|
||||
})
|
||||
|
||||
test("layout analysis flags overflowing rows and suggests a page break that keeps titles", () => {
|
||||
const layout: InvoicePdfLayout = { pageHeightMm: 297, pageCount: 1, rows: [
|
||||
{ index: 0, pos: "1", mode: "free", text: "A", page: 1, topMm: 200, bottomMm: 240 },
|
||||
{ index: 1, pos: "2", mode: "title", text: "T", page: 1, topMm: 240, bottomMm: 250 },
|
||||
{ index: 2, pos: "2.1", mode: "free", text: "B", page: 1, topMm: 250, bottomMm: 270 },
|
||||
], totals: { page: 1, topMm: 270, bottomMm: 300 } }
|
||||
const { warnings, layout: summary } = analyzeOutgoingDocumentLayout(layout, 262)
|
||||
assert.equal(warnings.length, 1)
|
||||
assert.equal(warnings[0].insertPagebreakBeforeIndex, 1)
|
||||
assert.equal(summary.pages[0].freeMm, -38)
|
||||
})
|
||||
|
||||
test("rendered preview records rows per page and rasterizes pages", { skip: !hasPdftoppm && "pdftoppm fehlt" }, async (t) => {
|
||||
const letterhead = await PDFDocument.create()
|
||||
letterhead.addPage([595.28, 841.89]).drawText("Briefpapier", { x: 40, y: 40, size: 8 })
|
||||
const background = Buffer.from(await letterhead.save())
|
||||
await initS3()
|
||||
t.mock.method(s3, "send", async () => ({ Body: Readable.from([background]) }))
|
||||
|
||||
const rows: any[] = positions(30)
|
||||
rows.splice(12, 0, { mode: "pagebreak" })
|
||||
const data = buildOutgoingDocumentPdfData(document(rows), context)
|
||||
const layout: InvoicePdfLayout = { pageHeightMm: 0, rows: [], pageCount: 0 }
|
||||
const pdf: any = await createInvoicePDF({} as any, "base64", data, "letterhead.pdf", layout)
|
||||
// Rows overflow page 2, so the payment QR code gets an extra third page.
|
||||
assert.equal(layout.pageCount, 3)
|
||||
assert.equal(layout.paymentQr!.page, 3)
|
||||
assert.equal(layout.rows.find((row) => row.index === 13)!.page, 2)
|
||||
assert.ok(layout.endText && layout.totals)
|
||||
const analysis = analyzeOutgoingDocumentLayout(layout)
|
||||
assert.ok(analysis.warnings.some((warning) => warning.type === "overflow" && warning.page === 2), JSON.stringify(analysis.warnings))
|
||||
|
||||
const images = await renderPdfPagesAsPng(Buffer.from(pdf.base64, "base64"), [1, 2], 50)
|
||||
assert.deepEqual(images.map((image) => image.page), [1, 2])
|
||||
assert.ok(images[0].png.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])))
|
||||
const result = asToolResult(withImages({ pageCount: 2 }, images.map((image) => ({ data: image.png.toString("base64"), mimeType: "image/png" }))))
|
||||
assert.deepEqual(result.content.map((item) => item.type), ["text", "image", "image"])
|
||||
assert.deepEqual(result.structuredContent, { pageCount: 2 })
|
||||
})
|
||||
|
||||
test("preview tool is read-only for outgoing documents", () => {
|
||||
assert.deepEqual(mcpToolMap.get("accounting.outgoing_documents.preview")!.requiredPermissions, ["accounting.outgoing_documents.read"])
|
||||
})
|
||||
|
||||
test("payment QR code moves to its own page instead of covering amounts", { skip: !hasPdftoppm && "pdftoppm fehlt" }, async (t) => {
|
||||
const letterhead = await PDFDocument.create()
|
||||
letterhead.addPage([595.28, 841.89]).drawText("Briefpapier", { x: 40, y: 40, size: 8 })
|
||||
const background = Buffer.from(await letterhead.save())
|
||||
await initS3()
|
||||
t.mock.method(s3, "send", async () => ({ Body: Readable.from([background]) }))
|
||||
const render = async (count: number) => {
|
||||
const layout: InvoicePdfLayout = { pageHeightMm: 0, rows: [], pageCount: 0 }
|
||||
await createInvoicePDF({} as any, "base64", buildOutgoingDocumentPdfData(document(positions(count)), context), "letterhead.pdf", layout)
|
||||
return layout
|
||||
}
|
||||
|
||||
const short = await render(3)
|
||||
assert.equal(short.pageCount, 1)
|
||||
assert.equal(short.paymentQr!.page, 1)
|
||||
assert.ok(short.totals!.bottomMm < short.paymentQr!.topMm)
|
||||
|
||||
const long = await render(6)
|
||||
assert.equal(long.pageCount, 2)
|
||||
assert.equal(long.paymentQr!.page, 2)
|
||||
assert.ok(long.rows.every((row) => row.page === 1))
|
||||
const analysis = analyzeOutgoingDocumentLayout(long)
|
||||
const warning = analysis.warnings.find((item) => item.type === "paymentQrOwnPage")
|
||||
assert.ok(warning, JSON.stringify(analysis.warnings))
|
||||
assert.ok(!analysis.warnings.some((item) => item.type === "emptyPage"))
|
||||
})
|
||||
31
backend/tests/mcpOutgoingRowDefaults.test.ts
Normal file
31
backend/tests/mcpOutgoingRowDefaults.test.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
import assert from "node:assert/strict"
|
||||
import test from "node:test"
|
||||
import { getTableName } from "drizzle-orm"
|
||||
import { applyOutgoingRowCatalogDefaults } from "../src/mcp/outgoingRowDefaults"
|
||||
|
||||
const catalog: Record<string, any[]> = {
|
||||
products: [{ id: 1, name: "Kabel", description: "NYM-J 3x1,5", unit: 2, selling_price: 1.25, tax_percentage: 19 }],
|
||||
services: [{ id: 5, name: "Montage", description: "Montage vor Ort", unit: 3, sellingPrice: 50, sellingPriceComposed: { total: 55 }, taxPercentage: 7, costcentre: "cc" }],
|
||||
}
|
||||
const context: any = { tenantId: 7, server: { db: { select: () => ({ from: (table: any) => ({ where: async () => catalog[getTableName(table)] }) }) } } }
|
||||
|
||||
test("selected products and services bring their description and editor defaults", async () => {
|
||||
const rows: any = await applyOutgoingRowCatalogDefaults(context, [
|
||||
{ mode: "normal", product: 1, quantity: 3 },
|
||||
JSON.stringify({ mode: "service", service: 5 }),
|
||||
{ mode: "free", text: "Frei", descriptionText: "Alt" },
|
||||
])
|
||||
assert.deepEqual(rows[0], { mode: "normal", product: 1, quantity: 3, text: "Kabel", description: "NYM-J 3x1,5", unit: 2, inputPrice: 1.25, price: 1.25, taxPercent: 19 })
|
||||
assert.equal(rows[1].description, "Montage vor Ort")
|
||||
assert.equal(rows[1].price, 55)
|
||||
assert.equal(rows[1].costCentre, "cc")
|
||||
assert.equal(rows[2].description, "Alt")
|
||||
})
|
||||
|
||||
test("caller values win and unknown catalog entries are rejected", async () => {
|
||||
const [row]: any = await applyOutgoingRowCatalogDefaults(context, [{ mode: "normal", product: 1, description: "Eigene", price: 2, taxPercent: 7 }])
|
||||
assert.equal(row.description, "Eigene")
|
||||
assert.equal(row.price, 2)
|
||||
assert.equal(row.taxPercent, 7)
|
||||
await assert.rejects(applyOutgoingRowCatalogDefaults(context, [{ mode: "normal", product: 9 }]), /Artikel 9 nicht gefunden/)
|
||||
})
|
||||
@@ -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)
|
||||
|
||||
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)
|
||||
@@ -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.
|
||||
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -730,6 +730,12 @@ const setupPage = async () => {
|
||||
await router.replace('/createDocument')
|
||||
return
|
||||
}
|
||||
|
||||
if (route.query.regeneratePdf && route.params.id) {
|
||||
await regenerateMissingPdf()
|
||||
return
|
||||
}
|
||||
|
||||
loaded.value = true
|
||||
|
||||
}
|
||||
@@ -1980,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
|
||||
|
||||
@@ -2021,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"
|
||||
|
||||
@@ -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)) {
|
||||
|
||||
@@ -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',
|
||||
|
||||
149
mobile/hooks/use-chat-conversation.ts
Normal file
149
mobile/hooks/use-chat-conversation.ts
Normal file
@@ -0,0 +1,149 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
|
||||
import { chatApi } from '@/src/lib/chat-api';
|
||||
import {
|
||||
applyChatAccess, chatCursor, isChatAccessError, mergeChatMessages,
|
||||
type ChatAttachment, type ChatDetail, type ChatPerson, type ChatReactions,
|
||||
type MobileChatMessage, type MobileChatRoom,
|
||||
} from '@/src/lib/chat';
|
||||
|
||||
const errorText = (error: unknown) => error instanceof Error ? error.message : 'Chat konnte nicht geladen werden.';
|
||||
|
||||
// Each mounted conversation belongs to one session and one room. Late responses cannot
|
||||
// repopulate an unmounted conversation or a conversation whose access was revoked.
|
||||
export function useChatConversation(token: string, room: MobileChatRoom, enabled: boolean) {
|
||||
const [detail, setDetail] = useState<ChatDetail | null>(null);
|
||||
const [messages, setMessages] = useState<MobileChatMessage[]>([]);
|
||||
const [members, setMembers] = useState<ChatPerson[]>([]);
|
||||
const [reactions, setReactions] = useState<ChatReactions>({});
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [olderLoading, setOlderLoading] = useState(false);
|
||||
const [hasMore, setHasMore] = useState(false);
|
||||
const [sending, setSending] = useState(false);
|
||||
const [reacting, setReacting] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [reload, setReload] = useState(0);
|
||||
const generation = useRef(0);
|
||||
const state = useRef<{ detail: ChatDetail | null; messages: MobileChatMessage[] }>({ detail: null, messages: [] });
|
||||
const busy = useRef({ send: false, reaction: false, older: false });
|
||||
const reactionRevision = useRef(0);
|
||||
const roomRef = useRef(room);
|
||||
roomRef.current = room;
|
||||
const current = useCallback((version: number) => generation.current === version, []);
|
||||
const update = useCallback((next: typeof state.current) => {
|
||||
state.current = next; setDetail(next.detail); setMessages(next.messages);
|
||||
}, []);
|
||||
const fail = useCallback((err: unknown, version: number) => {
|
||||
if (!current(version)) return;
|
||||
setError(errorText(err));
|
||||
if (isChatAccessError(err)) {
|
||||
++generation.current; ++reactionRevision.current;
|
||||
update({ detail: null, messages: [] }); setMembers([]); setReactions({});
|
||||
setLoading(false); setSending(false); setReacting(false); setOlderLoading(false); setHasMore(false);
|
||||
}
|
||||
}, [current, update]);
|
||||
|
||||
useEffect(() => {
|
||||
const version = ++generation.current;
|
||||
const target = roomRef.current;
|
||||
busy.current = { send: false, reaction: false, older: false };
|
||||
setSending(false); setReacting(false); setOlderLoading(false);
|
||||
if (!enabled) return;
|
||||
let polling = false;
|
||||
async function read(nextMessages: MobileChatMessage[]) {
|
||||
const cursor = chatCursor(target, nextMessages);
|
||||
if (current(version) && cursor) {
|
||||
try { await chatApi.read(token, target, cursor); } catch { /* Read receipts do not block the chat. */ }
|
||||
}
|
||||
}
|
||||
async function refreshReactions(nextMessages: MobileChatMessage[]) {
|
||||
if (busy.current.reaction) return;
|
||||
const revision = ++reactionRevision.current;
|
||||
try {
|
||||
const result = await chatApi.reactions(token, target, nextMessages);
|
||||
if (current(version) && reactionRevision.current === revision) setReactions(result);
|
||||
} catch { /* A temporary reaction failure must not hide the conversation. */ }
|
||||
}
|
||||
async function load() {
|
||||
setLoading(true); setError(''); setHasMore(false);
|
||||
update({ detail: null, messages: [] }); setMembers([]); setReactions({});
|
||||
try {
|
||||
const [nextDetail, page, people] = await Promise.all([
|
||||
chatApi.detail(token, target), chatApi.messages(token, target), chatApi.members(token, target),
|
||||
]);
|
||||
if (!current(version)) return;
|
||||
const nextMessages = target.source === 'collaboration' ? applyChatAccess(page.messages, nextDetail) : page.messages;
|
||||
update({ detail: nextDetail, messages: nextMessages }); setMembers(people); setHasMore(!!page.hasMore);
|
||||
await Promise.all([read(nextMessages), refreshReactions(nextMessages)]);
|
||||
} catch (err) { fail(err, version); }
|
||||
finally { if (current(version)) setLoading(false); }
|
||||
}
|
||||
async function poll() {
|
||||
if (!current(version) || polling || !state.current.detail || busy.current.older) return;
|
||||
polling = true;
|
||||
try {
|
||||
const [nextDetail, page, people] = await Promise.all([
|
||||
chatApi.detail(token, target), chatApi.messages(token, target, { after: chatCursor(target, state.current.messages) }),
|
||||
chatApi.members(token, target),
|
||||
]);
|
||||
if (!current(version)) return;
|
||||
const collaboration = target.source === 'collaboration';
|
||||
const retained = collaboration ? applyChatAccess(state.current.messages, nextDetail, state.current.detail) : state.current.messages;
|
||||
let nextMessages = mergeChatMessages(retained, page.messages, collaboration);
|
||||
if (collaboration) nextMessages = applyChatAccess(nextMessages, nextDetail);
|
||||
update({ detail: nextDetail, messages: nextMessages }); setMembers(people); setError('');
|
||||
await Promise.all([read(nextMessages), refreshReactions(nextMessages)]);
|
||||
} catch (err) { fail(err, version); }
|
||||
finally { polling = false; }
|
||||
}
|
||||
void load();
|
||||
const timer = setInterval(() => void poll(), 3000);
|
||||
return () => { ++generation.current; ++reactionRevision.current; clearInterval(timer); };
|
||||
}, [current, enabled, fail, reload, room.key, token, update]);
|
||||
|
||||
async function send(text: string, image: ChatAttachment | null, clientId: string) {
|
||||
if (!enabled || !state.current.detail?.canSend || busy.current.send) return false;
|
||||
const version = generation.current;
|
||||
const membershipRevision = state.current.detail.revision;
|
||||
busy.current.send = true; setSending(true); setError('');
|
||||
try {
|
||||
const message = await chatApi.send(token, room, text, image, clientId);
|
||||
// Clear the matching draft after a successful delivery, even if its room is no
|
||||
// longer open. Never append a late message after access/history has changed.
|
||||
if (!current(version) || state.current.detail?.revision !== membershipRevision) return true;
|
||||
const next = mergeChatMessages(state.current.messages, [message], room.source === 'collaboration');
|
||||
update({ ...state.current, messages: next });
|
||||
// The send is complete even if the read receipt cannot be delivered.
|
||||
const cursor = chatCursor(room, next);
|
||||
if (cursor) void chatApi.read(token, room, cursor).catch(() => undefined);
|
||||
return true;
|
||||
} catch (err) { fail(err, version); return false; }
|
||||
finally { if (current(version)) { busy.current.send = false; setSending(false); } }
|
||||
}
|
||||
async function older() {
|
||||
const before = state.current.messages.find(message => message.seq)?.seq;
|
||||
if (!enabled || !before || !hasMore || busy.current.older) return;
|
||||
const version = generation.current;
|
||||
busy.current.older = true; setOlderLoading(true);
|
||||
try {
|
||||
const page = await chatApi.messages(token, room, { before });
|
||||
if (!current(version) || !state.current.detail) return;
|
||||
const next = applyChatAccess(mergeChatMessages(state.current.messages, page.messages, true), state.current.detail);
|
||||
update({ ...state.current, messages: next }); setHasMore(!!page.hasMore);
|
||||
} catch (err) { fail(err, version); }
|
||||
finally { if (current(version)) { busy.current.older = false; setOlderLoading(false); } }
|
||||
}
|
||||
async function react(message: MobileChatMessage, emoji: string) {
|
||||
if (!enabled || !state.current.detail?.canSend || state.current.detail.offline || message.pending || message.failed || busy.current.reaction) return;
|
||||
const version = generation.current;
|
||||
++reactionRevision.current; busy.current.reaction = true; setReacting(true);
|
||||
try {
|
||||
const active = !(reactions[message.id] || []).some(item => item.emoji === emoji && item.own);
|
||||
const result = await chatApi.react(token, room, message.id, emoji, active);
|
||||
if (current(version)) setReactions(previous => ({ ...previous, [message.id]: result.reactions[message.id] || [] }));
|
||||
} catch (err) { if (current(version)) setError(errorText(err)); }
|
||||
finally { if (current(version)) { busy.current.reaction = false; setReacting(false); } }
|
||||
}
|
||||
return { detail, messages, members, reactions, loading, olderLoading, hasMore, sending, reacting, error,
|
||||
send, older, react, retry: () => setReload(value => value + 1) };
|
||||
}
|
||||
51
mobile/package-lock.json
generated
51
mobile/package-lock.json
generated
@@ -16,17 +16,20 @@
|
||||
"expo": "~54.0.37",
|
||||
"expo-camera": "~17.0.10",
|
||||
"expo-constants": "~18.0.14",
|
||||
"expo-crypto": "~15.0.9",
|
||||
"expo-document-picker": "^14.0.8",
|
||||
"expo-file-system": "~19.0.24",
|
||||
"expo-font": "~14.0.12",
|
||||
"expo-haptics": "~15.0.8",
|
||||
"expo-image": "~3.0.11",
|
||||
"expo-image-manipulator": "~14.0.8",
|
||||
"expo-image-picker": "~17.0.11",
|
||||
"expo-linking": "~8.0.12",
|
||||
"expo-notifications": "~0.32.17",
|
||||
"expo-router": "~6.0.24",
|
||||
"expo-secure-store": "^15.0.8",
|
||||
"expo-share-intent": "^5.1.1",
|
||||
"expo-sharing": "~14.0.8",
|
||||
"expo-splash-screen": "~31.0.13",
|
||||
"expo-status-bar": "~3.0.9",
|
||||
"expo-symbols": "~1.0.8",
|
||||
@@ -48,6 +51,7 @@
|
||||
"@types/react": "~19.1.0",
|
||||
"eslint": "^9.25.0",
|
||||
"eslint-config-expo": "~10.0.0",
|
||||
"react-test-renderer": "19.1.0",
|
||||
"typescript": "~5.9.2"
|
||||
},
|
||||
"engines": {
|
||||
@@ -6249,6 +6253,18 @@
|
||||
"react-native": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/expo-crypto": {
|
||||
"version": "15.0.9",
|
||||
"resolved": "https://registry.npmjs.org/expo-crypto/-/expo-crypto-15.0.9.tgz",
|
||||
"integrity": "sha512-SNWKa2fXx7v9gkp1h/7nqXY5XN7qgNDn3yRc2aO0gWGbeMbvob/haMxxsPFe9f51aqH5NjNCqHf2kvLhvAd8KQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"base64-js": "^1.3.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"expo": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/expo-document-picker": {
|
||||
"version": "14.0.8",
|
||||
"resolved": "https://registry.npmjs.org/expo-document-picker/-/expo-document-picker-14.0.8.tgz",
|
||||
@@ -6317,6 +6333,18 @@
|
||||
"expo": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/expo-image-manipulator": {
|
||||
"version": "14.0.8",
|
||||
"resolved": "https://registry.npmjs.org/expo-image-manipulator/-/expo-image-manipulator-14.0.8.tgz",
|
||||
"integrity": "sha512-sXsXjm7rIxLWZe0j2A41J/Ph53PpFJRdyzJ3EQ/qetxLUvS2m3K1sP5xy37px43qCf0l79N/i6XgFgenFV36/Q==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"expo-image-loader": "~6.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"expo": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/expo-image-picker": {
|
||||
"version": "17.0.11",
|
||||
"resolved": "https://registry.npmjs.org/expo-image-picker/-/expo-image-picker-17.0.11.tgz",
|
||||
@@ -6835,6 +6863,15 @@
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/expo-sharing": {
|
||||
"version": "14.0.8",
|
||||
"resolved": "https://registry.npmjs.org/expo-sharing/-/expo-sharing-14.0.8.tgz",
|
||||
"integrity": "sha512-A1pPr2iBrxypFDCWVAESk532HK+db7MFXbvO2sCV9ienaFXAk7lIBm6bkqgE6vzRd9O3RGdEGzYx80cYlc089Q==",
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"expo": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/expo-splash-screen": {
|
||||
"version": "31.0.13",
|
||||
"resolved": "https://registry.npmjs.org/expo-splash-screen/-/expo-splash-screen-31.0.13.tgz",
|
||||
@@ -11178,6 +11215,20 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/react-test-renderer": {
|
||||
"version": "19.1.0",
|
||||
"resolved": "https://registry.npmjs.org/react-test-renderer/-/react-test-renderer-19.1.0.tgz",
|
||||
"integrity": "sha512-jXkSl3CpvPYEF+p/eGDLB4sPoDX8pKkYvRl9+rR8HxLY0X04vW7hCm1/0zHoUSjPZ3bDa+wXWNTDVIw/R8aDVw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"react-is": "^19.1.0",
|
||||
"scheduler": "^0.26.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": "^19.1.0"
|
||||
}
|
||||
},
|
||||
"node_modules/reflect.getprototypeof": {
|
||||
"version": "1.0.10",
|
||||
"resolved": "https://registry.npmjs.org/reflect.getprototypeof/-/reflect.getprototypeof-1.0.10.tgz",
|
||||
|
||||
@@ -14,7 +14,8 @@
|
||||
"web": "expo start --web",
|
||||
"lint": "expo lint",
|
||||
"doctor": "npx expo-doctor",
|
||||
"preflight:testflight": "npm run lint && npm run doctor",
|
||||
"test": "node --experimental-strip-types --test tests/*.test.mjs",
|
||||
"preflight:testflight": "npm run lint && npm test && npm run doctor",
|
||||
"build:ios:dev": "eas build --profile development --platform ios",
|
||||
"build:ios:preview": "eas build --profile preview --platform ios",
|
||||
"build:ios:testflight": "eas build --profile testflight --platform ios",
|
||||
@@ -29,17 +30,20 @@
|
||||
"expo": "~54.0.37",
|
||||
"expo-camera": "~17.0.10",
|
||||
"expo-constants": "~18.0.14",
|
||||
"expo-crypto": "~15.0.9",
|
||||
"expo-document-picker": "^14.0.8",
|
||||
"expo-file-system": "~19.0.24",
|
||||
"expo-font": "~14.0.12",
|
||||
"expo-haptics": "~15.0.8",
|
||||
"expo-image": "~3.0.11",
|
||||
"expo-image-manipulator": "~14.0.8",
|
||||
"expo-image-picker": "~17.0.11",
|
||||
"expo-linking": "~8.0.12",
|
||||
"expo-notifications": "~0.32.17",
|
||||
"expo-router": "~6.0.24",
|
||||
"expo-secure-store": "^15.0.8",
|
||||
"expo-share-intent": "^5.1.1",
|
||||
"expo-sharing": "~14.0.8",
|
||||
"expo-splash-screen": "~31.0.13",
|
||||
"expo-status-bar": "~3.0.9",
|
||||
"expo-symbols": "~1.0.8",
|
||||
@@ -61,6 +65,7 @@
|
||||
"@types/react": "~19.1.0",
|
||||
"eslint": "^9.25.0",
|
||||
"eslint-config-expo": "~10.0.0",
|
||||
"react-test-renderer": "19.1.0",
|
||||
"typescript": "~5.9.2"
|
||||
},
|
||||
"private": true
|
||||
|
||||
@@ -56,13 +56,15 @@ export type Project = {
|
||||
[key: string]: unknown;
|
||||
};
|
||||
|
||||
export type EventState = 'Entwurf' | 'Final';
|
||||
|
||||
export type CalendarEvent = {
|
||||
id: number;
|
||||
name: string;
|
||||
startDate: string;
|
||||
endDate?: string | null;
|
||||
eventtype?: string | null;
|
||||
state?: string | null;
|
||||
state?: EventState | null;
|
||||
repeatInterval?: string | null;
|
||||
project?: number | { id?: number; name?: string } | null;
|
||||
customer?: number | { id?: number; name?: string } | null;
|
||||
@@ -740,7 +742,7 @@ export async function createEvent(
|
||||
notes?: string | null;
|
||||
link?: string | null;
|
||||
eventtype?: string;
|
||||
state?: 'Entwurf' | 'Final';
|
||||
state?: EventState;
|
||||
repeatInterval?: string;
|
||||
}
|
||||
): Promise<CalendarEvent> {
|
||||
@@ -751,6 +753,18 @@ export async function createEvent(
|
||||
});
|
||||
}
|
||||
|
||||
export async function updateEvent(
|
||||
token: string,
|
||||
eventId: number,
|
||||
payload: Partial<Pick<CalendarEvent, 'name' | 'startDate' | 'endDate' | 'project' | 'customer' | 'notes' | 'link' | 'eventtype' | 'state' | 'repeatInterval'>>
|
||||
): Promise<CalendarEvent> {
|
||||
return apiRequest<CalendarEvent>(`/api/resource/events/${eventId}`, {
|
||||
method: 'PUT',
|
||||
token,
|
||||
body: payload,
|
||||
});
|
||||
}
|
||||
|
||||
export async function fetchEventById(token: string, eventId: number): Promise<CalendarEvent> {
|
||||
return apiRequest<CalendarEvent>(`/api/resource/events/${eventId}`, { token });
|
||||
}
|
||||
|
||||
4
mobile/src/lib/chat-api.ts
Normal file
4
mobile/src/lib/chat-api.ts
Normal file
@@ -0,0 +1,4 @@
|
||||
import { apiRequest } from '@/src/lib/api';
|
||||
import { createChatApi } from '@/src/lib/chat';
|
||||
|
||||
export const chatApi = createChatApi(apiRequest);
|
||||
30
mobile/src/lib/chat-image.ts
Normal file
30
mobile/src/lib/chat-image.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import { deleteAsync } from 'expo-file-system/legacy';
|
||||
import { ImageManipulator, SaveFormat } from 'expo-image-manipulator';
|
||||
import type { ImagePickerAsset } from 'expo-image-picker';
|
||||
|
||||
import type { ChatAttachment } from '@/src/lib/chat';
|
||||
|
||||
export async function prepareMobileChatImage(asset: ImagePickerAsset): Promise<ChatAttachment> {
|
||||
if ((asset.fileSize || 0) > 10 * 1024 * 1024) throw new Error('Das Originalbild darf höchstens 10 MB groß sein.');
|
||||
if (!asset.width || !asset.height) throw new Error('Das Bild konnte nicht gelesen werden.');
|
||||
// Convert camera formats such as HEIC to a bounded raster before sending to FEDEO.
|
||||
for (const limit of [1600, 1000]) {
|
||||
const context = ImageManipulator.manipulate(asset.uri);
|
||||
const scale = Math.min(1, limit / Math.max(asset.width, asset.height));
|
||||
context.resize({ width: Math.max(1, Math.round(asset.width * scale)), height: Math.max(1, Math.round(asset.height * scale)) });
|
||||
try {
|
||||
const image = await context.renderAsync();
|
||||
try {
|
||||
for (const compress of [0.8, 0.55, 0.35]) {
|
||||
const result = await image.saveAsync({ format: SaveFormat.JPEG, compress, base64: true });
|
||||
await deleteAsync(result.uri, { idempotent: true }).catch(() => undefined);
|
||||
if (result.base64 && result.base64.length <= 480_000) return {
|
||||
dataUrl: `data:image/jpeg;base64,${result.base64}`,
|
||||
name: `${(asset.fileName || 'Bild').replace(/\.[^.]+$/, '').slice(0, 195)}.jpg`,
|
||||
};
|
||||
}
|
||||
} finally { image.release(); }
|
||||
} finally { context.release(); }
|
||||
}
|
||||
throw new Error('Dieses Bild ist zu groß. Bitte einen kleineren Ausschnitt auswählen.');
|
||||
}
|
||||
169
mobile/src/lib/chat.ts
Normal file
169
mobile/src/lib/chat.ts
Normal file
@@ -0,0 +1,169 @@
|
||||
export type ChatImage = { name: string; width: number; height: number };
|
||||
export type ChatAttachment = { name: string; dataUrl: string };
|
||||
export type ChatReaction = { emoji: string; count: number; own: boolean };
|
||||
export type ChatReactions = Record<string, ChatReaction[]>;
|
||||
export type MobileChatRoom = {
|
||||
key: string; id?: string; name: string; topic?: string | null;
|
||||
source: 'internal' | 'collaboration'; group: string; exists: boolean;
|
||||
type?: string; projectId?: number; projectNumber?: string | null; userId?: string; email?: string | null;
|
||||
ownerName?: string; remote?: boolean; status?: string; unread?: number; lastActivityAt?: string | null;
|
||||
};
|
||||
export type ChatInvitation = {
|
||||
id: string; name: string; ownerName?: string; role: string;
|
||||
overviewAllowed?: boolean; remote?: boolean; expiresAt?: string;
|
||||
};
|
||||
export type ChatDetail = {
|
||||
name: string; topic?: string | null; canSend: boolean; status?: string;
|
||||
offline?: boolean; historyFromSeq?: number; revision?: number;
|
||||
overview?: { title?: string; status?: string; date?: string; description?: string } | null;
|
||||
};
|
||||
export type MobileChatMessage = {
|
||||
id: string | number; clientId?: string; seq?: number | null; body?: string | null;
|
||||
own?: boolean; senderDisplayName?: string | null; senderName?: string;
|
||||
timestamp?: string | number | null; createdAt?: string;
|
||||
image?: ChatImage | null; pending?: boolean; failed?: boolean;
|
||||
};
|
||||
export type ChatPerson = { name: string; own?: boolean; kind?: string };
|
||||
export type ChatPage = { messages: MobileChatMessage[]; hasMore?: boolean };
|
||||
export type ChatDirectory = {
|
||||
rooms: MobileChatRoom[]; hiddenRoomKeys: string[]; invitations: ChatInvitation[];
|
||||
canManage: boolean; projects: { id: number; name: string }[];
|
||||
};
|
||||
type NativeRoom = Omit<MobileChatRoom, 'source' | 'group'>;
|
||||
type CollaborationRoom = Omit<MobileChatRoom, 'key' | 'source' | 'group' | 'exists'> & { id: string };
|
||||
type CollaborationList = {
|
||||
rooms: CollaborationRoom[]; invitations: ChatInvitation[];
|
||||
canManage?: boolean; projects?: ChatDirectory['projects'];
|
||||
};
|
||||
type Request = <T>(path: string, options: {
|
||||
token: string; method?: 'GET' | 'POST' | 'PUT'; body?: unknown;
|
||||
}) => Promise<T>;
|
||||
|
||||
export const reactionEmojis = ['👍', '❤️', '😂', '🎉', '😮', '😢', '🙏', '🔥', '✅', '👎'];
|
||||
export const collaborationKey = (id: string) => `collaboration:${id}`;
|
||||
export const chatEndpoint = (room: MobileChatRoom, suffix = '') => room.source === 'collaboration'
|
||||
? `/api/collaboration/rooms/${encodeURIComponent(room.id!)}${suffix}`
|
||||
: `/api/communication/chat/rooms/${encodeURIComponent(room.key)}${suffix}`;
|
||||
export const visibleChatRooms = (directory: ChatDirectory) => directory.rooms.filter(room => !directory.hiddenRoomKeys.includes(room.key));
|
||||
const activity = (room: MobileChatRoom) => (room.lastActivityAt && Date.parse(room.lastActivityAt)) || 0;
|
||||
// Most recently used chats first; rooms without activity keep their server order at the end.
|
||||
export const sortChatRooms = (rooms: MobileChatRoom[]) => [...rooms].sort((a, b) => activity(b) - activity(a));
|
||||
export const touchChatRoom = (rooms: MobileChatRoom[], key: string, at = new Date().toISOString()) =>
|
||||
sortChatRooms(rooms.map(room => room.key === key ? { ...room, lastActivityAt: at } : room));
|
||||
export const chatCursor = (room: MobileChatRoom, messages: MobileChatMessage[]) => Math.max(0,
|
||||
...messages.map(message => room.source === 'collaboration' ? message.seq || 0 : Number(message.id)));
|
||||
export function mergeChatMessages(current: MobileChatMessage[], incoming: MobileChatMessage[], collaboration: boolean) {
|
||||
const byId = new Map(current.map(message => [message.id, message]));
|
||||
for (const message of incoming) {
|
||||
// A federation acknowledgement replaces its queued copy even when the server ID changes.
|
||||
if (collaboration && message.own && message.clientId) {
|
||||
if (!message.seq && [...byId.values()].some(old => old.own && old.seq && old.clientId === message.clientId)) continue;
|
||||
if (message.seq) for (const [id, old] of byId) {
|
||||
if (old.own && !old.seq && old.clientId === message.clientId) byId.delete(id);
|
||||
}
|
||||
}
|
||||
byId.set(message.id, message);
|
||||
}
|
||||
return [...byId.values()].sort((a, b) => collaboration
|
||||
? (a.seq || Number.MAX_SAFE_INTEGER) - (b.seq || Number.MAX_SAFE_INTEGER)
|
||||
: Number(a.id) - Number(b.id));
|
||||
}
|
||||
export function applyChatAccess(messages: MobileChatMessage[], detail: ChatDetail, previous?: ChatDetail | null) {
|
||||
return messages.filter(message => message.seq
|
||||
? message.seq >= (detail.historyFromSeq || 0)
|
||||
: !previous || previous.revision === detail.revision);
|
||||
}
|
||||
export function isChatAccessError(error: unknown) {
|
||||
return typeof error === 'object' && error !== null && 'status' in error && [401, 403, 404, 410].includes(Number(error.status));
|
||||
}
|
||||
export function validChatImage(dataUrl: unknown): dataUrl is string {
|
||||
return typeof dataUrl === 'string' && dataUrl.length <= 700_000
|
||||
&& /^data:image\/(webp|png|jpeg);base64,[A-Za-z0-9+/]+={0,2}$/.test(dataUrl);
|
||||
}
|
||||
export function matchesChatSearch(room: MobileChatRoom, search: string) {
|
||||
const normalize = (text: string) => text.toLowerCase().normalize('NFKD').replace(/[\u0300-\u036f]/g, '').replace(/ß/g, 'ss');
|
||||
const text = normalize([room.name, room.topic, room.projectNumber, room.email, room.ownerName].filter(Boolean).join(' '));
|
||||
return normalize(search).trim().split(/\s+/).every(term => text.includes(term));
|
||||
}
|
||||
|
||||
export function createChatApi(request: Request) {
|
||||
const preferences = '/api/communication/chat/room-preferences';
|
||||
return {
|
||||
async directory(token: string): Promise<ChatDirectory> {
|
||||
// Do not expose any rooms before the server's visibility preferences are available.
|
||||
const [base, projects, direct, unread, hidden, collaboration] = await Promise.all([
|
||||
request<{ rooms: NativeRoom[] }>('/api/communication/chat/rooms', { token }),
|
||||
request<{ rooms: NativeRoom[] }>('/api/communication/chat/project-rooms', { token }),
|
||||
request<{ rooms: NativeRoom[] }>('/api/communication/chat/direct-rooms', { token }),
|
||||
request<{ rooms: Record<string, { count?: number }> }>('/api/communication/chat/unread', { token }),
|
||||
request<{ hiddenRoomKeys: string[] }>(preferences, { token }),
|
||||
request<CollaborationList>('/api/collaboration', { token }),
|
||||
]);
|
||||
const decorate = (rooms: NativeRoom[], group: string): MobileChatRoom[] => rooms.map(room => ({
|
||||
...room, source: 'internal', group, unread: unread.rooms?.[room.key]?.count || 0,
|
||||
}));
|
||||
return {
|
||||
rooms: sortChatRooms([...decorate(base.rooms, 'Räume'), ...decorate(projects.rooms, 'Projekte'), ...decorate(direct.rooms, 'Direkt'),
|
||||
...collaboration.rooms.map(room => ({ ...room, key: collaborationKey(room.id),
|
||||
source: 'collaboration' as const, group: 'Zusammenarbeit', exists: true }))]),
|
||||
hiddenRoomKeys: hidden.hiddenRoomKeys, invitations: collaboration.invitations,
|
||||
canManage: collaboration.canManage === true, projects: collaboration.projects || [],
|
||||
};
|
||||
},
|
||||
async unread(token: string) {
|
||||
const [native, hidden, collaboration] = await Promise.all([
|
||||
request<{ rooms: Record<string, { count?: number }> }>('/api/communication/chat/unread', { token }),
|
||||
request<{ hiddenRoomKeys: string[] }>(preferences, { token }),
|
||||
request<CollaborationList>('/api/collaboration', { token }),
|
||||
]);
|
||||
const counts = [...Object.entries(native.rooms).map(([key, value]) => ({ key, count: value.count || 0 })),
|
||||
...collaboration.rooms.map(room => ({ key: collaborationKey(room.id), count: room.unread || 0 }))];
|
||||
return counts.filter(room => !hidden.hiddenRoomKeys.includes(room.key)).reduce((sum, room) => sum + room.count, 0);
|
||||
},
|
||||
hide: (token: string, roomKey: string, hidden: boolean) => request(preferences, { token, method: 'PUT', body: { roomKey, hidden } }),
|
||||
respond: (token: string, id: string, accept: boolean) => request<{ roomId?: string }>(
|
||||
`/api/collaboration/invitations/${encodeURIComponent(id)}/${accept ? 'accept' : 'decline'}`, { token, method: 'POST' }),
|
||||
async provision(token: string, room: MobileChatRoom): Promise<MobileChatRoom> {
|
||||
if (room.exists || room.source === 'collaboration') return room;
|
||||
const path = room.type === 'project' ? `/api/communication/chat/project-rooms/${room.projectId}/provision`
|
||||
: `/api/communication/chat/direct-rooms/${encodeURIComponent(room.userId!)}/provision`;
|
||||
return { ...room, ...await request<NativeRoom>(path, { token, method: 'POST' }), source: 'internal' };
|
||||
},
|
||||
detail: (token: string, room: MobileChatRoom) => room.source === 'collaboration'
|
||||
? request<ChatDetail>(chatEndpoint(room), { token })
|
||||
: Promise.resolve<ChatDetail>({ name: room.name, topic: room.topic, canSend: true }),
|
||||
async members(token: string, room: MobileChatRoom): Promise<ChatPerson[]> {
|
||||
const result = await request<{ members: (ChatPerson & { displayName?: string })[] }>(chatEndpoint(room, '/members'), { token });
|
||||
return result.members.map(member => ({ ...member, name: member.name || member.displayName || 'Benutzer' }));
|
||||
},
|
||||
messages(token: string, room: MobileChatRoom, cursor?: { after?: number; before?: number }) {
|
||||
const suffix = room.source === 'collaboration'
|
||||
? `/messages${cursor?.before ? `?before=${cursor.before}` : cursor?.after ? `?after=${cursor.after}` : ''}`
|
||||
: cursor?.after ? `/sync?afterId=${cursor.after}` : '/messages';
|
||||
return request<ChatPage>(chatEndpoint(room, suffix), { token });
|
||||
},
|
||||
send: (token: string, room: MobileChatRoom, text: string, image: ChatAttachment | null, clientId: string) => request<MobileChatMessage>(
|
||||
chatEndpoint(room, '/messages'), { token, method: 'POST', body: { text, ...(image ? { image } : {}),
|
||||
...(room.source === 'collaboration' ? { clientId } : {}) } }),
|
||||
read: (token: string, room: MobileChatRoom, cursor: number) => request(chatEndpoint(room, '/read'), {
|
||||
token, method: 'POST', body: room.source === 'collaboration' ? { seq: cursor } : { messageId: cursor },
|
||||
}),
|
||||
async image(token: string, room: MobileChatRoom, id: MobileChatMessage['id']) {
|
||||
const result = await request<{ dataUrl: string }>(chatEndpoint(room, `/image?messageId=${encodeURIComponent(id)}`), { token });
|
||||
if (!validChatImage(result.dataUrl)) throw new Error('Ungültiges Chatbild.');
|
||||
return result.dataUrl;
|
||||
},
|
||||
async reactions(token: string, room: MobileChatRoom, messages: MobileChatMessage[]): Promise<ChatReactions> {
|
||||
const ids = messages.filter(message => !message.pending && !message.failed).map(message => message.id);
|
||||
const reactions: ChatReactions = {};
|
||||
for (let index = 0; index < ids.length; index += 100) {
|
||||
const result = await request<{ reactions: ChatReactions }>(chatEndpoint(room,
|
||||
`/reactions?ids=${encodeURIComponent(ids.slice(index, index + 100).join(','))}`), { token });
|
||||
Object.assign(reactions, result.reactions);
|
||||
}
|
||||
return reactions;
|
||||
},
|
||||
react: (token: string, room: MobileChatRoom, messageId: MobileChatMessage['id'], emoji: string, active: boolean) => request<{ reactions: ChatReactions }>(
|
||||
chatEndpoint(room, '/reactions'), { token, method: 'PUT', body: { messageId, emoji, active } }),
|
||||
};
|
||||
}
|
||||
@@ -1,3 +1,7 @@
|
||||
import { File, Paths } from 'expo-file-system';
|
||||
import * as Sharing from 'expo-sharing';
|
||||
|
||||
import type { ProjectFile } from '@/src/lib/api';
|
||||
import { getApiBaseUrlSync } from '@/src/lib/server-config';
|
||||
|
||||
export function getOpenableFileUrl(rawUrl: string): string {
|
||||
@@ -7,3 +11,28 @@ export function getOpenableFileUrl(rawUrl: string): string {
|
||||
const path = rawUrl.startsWith('/') ? rawUrl : `/${rawUrl}`;
|
||||
return `${apiBaseUrl}${path}`;
|
||||
}
|
||||
|
||||
function safeFilename(file: ProjectFile): string {
|
||||
const fallback = `dokument-${file.id}`;
|
||||
const rawName = String(file.name || file.path?.split('/').pop() || fallback);
|
||||
return rawName.replace(/[^a-zA-Z0-9äöüÄÖÜß._-]/g, '_');
|
||||
}
|
||||
|
||||
export async function openAuthenticatedFile(file: ProjectFile, token: string): Promise<void> {
|
||||
if (!file.url) throw new Error('Für dieses Dokument ist kein Download verfügbar.');
|
||||
|
||||
const target = new File(Paths.cache, `${file.id}-${safeFilename(file)}`);
|
||||
const downloaded = await File.downloadFileAsync(getOpenableFileUrl(file.url), target, {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
idempotent: true,
|
||||
});
|
||||
|
||||
if (!(await Sharing.isAvailableAsync())) {
|
||||
throw new Error('Die Dokumentvorschau ist auf diesem Gerät nicht verfügbar.');
|
||||
}
|
||||
|
||||
await Sharing.shareAsync(downloaded.uri, {
|
||||
mimeType: file.mimeType || undefined,
|
||||
dialogTitle: safeFilename(file),
|
||||
});
|
||||
}
|
||||
|
||||
121
mobile/tests/chat-conversation.test.mjs
Normal file
121
mobile/tests/chat-conversation.test.mjs
Normal file
@@ -0,0 +1,121 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { createRequire } from 'node:module';
|
||||
import { test } from 'node:test';
|
||||
import React from 'react';
|
||||
import { act, create } from 'react-test-renderer';
|
||||
import ts from 'typescript';
|
||||
import * as chatModel from '../src/lib/chat.ts';
|
||||
|
||||
globalThis.IS_REACT_ACT_ENVIRONMENT = true;
|
||||
const require = createRequire(import.meta.url);
|
||||
const remote = { key: 'collaboration:a', id: 'a', source: 'collaboration', name: 'A', exists: true };
|
||||
const detail = { name: 'A', canSend: true, historyFromSeq: 1, revision: 1 };
|
||||
const deferred = () => { let resolve, reject; const promise = new Promise((yes, no) => { resolve = yes; reject = no; }); return { promise, resolve, reject }; };
|
||||
|
||||
function harness(overrides = {}) {
|
||||
const reads = [], sends = [], timers = new Map();
|
||||
const api = {
|
||||
detail: async () => detail, messages: async () => ({ messages: [{ id: 'first', seq: 1, body: 'Start' }] }),
|
||||
members: async () => [{ name: 'Partner' }], reactions: async () => ({}),
|
||||
read: async (...args) => { reads.push(args); },
|
||||
send: async (...args) => { sends.push(args); return { id: 'sent', seq: 2, own: true }; },
|
||||
react: async () => ({ reactions: {} }), ...overrides,
|
||||
};
|
||||
const output = ts.transpileModule(readFileSync(new URL('../hooks/use-chat-conversation.ts', import.meta.url), 'utf8'), {
|
||||
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 },
|
||||
}).outputText;
|
||||
const exports = {};
|
||||
new Function('require', 'exports', 'setInterval', 'clearInterval', output)(name => {
|
||||
if (name === '@/src/lib/chat-api') return { chatApi: api };
|
||||
if (name === '@/src/lib/chat') return chatModel;
|
||||
return require(name);
|
||||
}, exports, callback => { const id = Symbol(); timers.set(id, callback); return id; }, id => timers.delete(id));
|
||||
let latest, root;
|
||||
function Probe(props) { latest = exports.useChatConversation(props.token || 'token', props.room, props.enabled ?? true); return null; }
|
||||
return {
|
||||
api, reads, sends, get state() { return latest; },
|
||||
async render(room = remote, enabled = true, token = 'token') {
|
||||
await act(async () => {
|
||||
const element = React.createElement(Probe, { key: `${token}:${room.key}`, room, enabled, token });
|
||||
if (root) root.update(element); else root = create(element);
|
||||
});
|
||||
},
|
||||
async poll() { await act(async () => { for (const callback of timers.values()) callback(); }); },
|
||||
async dispose() { await act(async () => root?.unmount()); },
|
||||
};
|
||||
}
|
||||
|
||||
test('Verspätete Antworten des vorherigen Raums werden nach Raumwechsel verworfen', async () => {
|
||||
const pending = deferred();
|
||||
const h = harness({ detail: async (_token, room) => room.id === 'a' ? pending.promise : { ...detail, name: 'B' },
|
||||
messages: async (_token, room) => ({ messages: [{ id: room.id, seq: 1, body: room.name }] }) });
|
||||
try {
|
||||
await h.render();
|
||||
await h.render({ ...remote, key: 'collaboration:b', id: 'b', name: 'B' });
|
||||
await act(async () => pending.resolve(detail));
|
||||
assert.equal(h.state.detail.name, 'B');
|
||||
assert.equal(h.state.messages[0].body, 'B');
|
||||
assert.ok(h.reads.every(([, room]) => room.id === 'b'));
|
||||
} finally { await h.dispose(); }
|
||||
});
|
||||
test('Mandantenwechsel verwirft laufende Antworten der alten Sitzung', async () => {
|
||||
const pending = deferred();
|
||||
const h = harness({ messages: async token => token === 'old' ? pending.promise : { messages: [{ id: 'new', seq: 3 }] } });
|
||||
try {
|
||||
await h.render(remote, true, 'old');
|
||||
await h.render(remote, true, 'new');
|
||||
await act(async () => pending.resolve({ messages: [{ id: 'private-old', seq: 9 }] }));
|
||||
assert.deepEqual(h.state.messages.map(message => message.id), ['new']);
|
||||
assert.ok(h.reads.every(([token]) => token === 'new'));
|
||||
} finally { await h.dispose(); }
|
||||
});
|
||||
test('Entzogener Zugriff entfernt Inhalt und ignoriert danach eintreffende Sendeantworten', async () => {
|
||||
const pending = deferred(); let forbidden = false;
|
||||
const h = harness({ detail: async () => { if (forbidden) throw Object.assign(new Error('Zugriff entzogen'), { status: 403 }); return detail; }, send: () => pending.promise });
|
||||
try {
|
||||
await h.render();
|
||||
let send;
|
||||
await act(async () => { send = h.state.send('Hallo', null, 'stable'); });
|
||||
forbidden = true; await h.poll();
|
||||
assert.equal(h.state.detail, null);
|
||||
assert.deepEqual(h.state.messages, []); assert.deepEqual(h.state.members, []);
|
||||
await act(async () => pending.resolve({ id: 'late', seq: 7 }));
|
||||
assert.equal(await send, true); // The old draft can be cleared, but no content reappears.
|
||||
assert.deepEqual(h.state.messages, []);
|
||||
assert.equal(await h.state.send('Nicht erlaubt', null, 'blocked'), false);
|
||||
} finally { await h.dispose(); }
|
||||
});
|
||||
test('Neue Leserechte und Historiengrenzen werden während des Pollings übernommen', async () => {
|
||||
let revision = 1;
|
||||
const h = harness({ detail: async () => ({ ...detail, revision, canSend: revision === 1, historyFromSeq: revision === 1 ? 1 : 5 }),
|
||||
messages: async () => ({ messages: revision === 1 ? [{ id: 'old', seq: 1 }, { id: 'allowed', seq: 5 }, { id: 'queued', seq: null, pending: true }] : [] }) });
|
||||
try {
|
||||
await h.render(); revision = 2; await h.poll();
|
||||
assert.deepEqual(h.state.messages.map(message => message.id), ['allowed']);
|
||||
assert.equal(h.state.detail.canSend, false);
|
||||
assert.equal(await h.state.send('Gesperrt', null, 'no-send'), false);
|
||||
assert.equal(h.sends.length, 0);
|
||||
} finally { await h.dispose(); }
|
||||
});
|
||||
test('Doppelklick sendet nur einmal; fehlgeschlagene Nachrichten können mit derselben ID wiederholt werden', async () => {
|
||||
const pending = deferred(), ids = []; let attempt = 0;
|
||||
const h = harness({ send: (_token, _room, _text, _image, clientId) => { ids.push(clientId); return ++attempt === 1 ? pending.promise : Promise.resolve({ id: 'sent', seq: 2 }); } });
|
||||
try {
|
||||
await h.render(); let first, second;
|
||||
await act(async () => { first = h.state.send('Hallo', null, 'same-id'); second = h.state.send('Hallo', null, 'same-id'); });
|
||||
assert.equal(await second, false); assert.equal(ids.length, 1);
|
||||
await act(async () => pending.reject(new Error('Netzwerkfehler')));
|
||||
assert.equal(await first, false);
|
||||
await act(async () => assert.equal(await h.state.send('Hallo', null, 'same-id'), true));
|
||||
assert.deepEqual(ids, ['same-id', 'same-id']);
|
||||
} finally { await h.dispose(); }
|
||||
});
|
||||
test('Im Hintergrund werden keine Nachrichten abgefragt oder als gelesen markiert', async () => {
|
||||
const h = harness();
|
||||
try {
|
||||
await h.render(remote, false); await h.poll(); assert.equal(h.reads.length, 0);
|
||||
await h.render(remote, true); assert.equal(h.reads.length, 1);
|
||||
await h.render(remote, false); await h.poll(); assert.equal(h.reads.length, 1);
|
||||
} finally { await h.dispose(); }
|
||||
});
|
||||
53
mobile/tests/chat-directory.test.mjs
Normal file
53
mobile/tests/chat-directory.test.mjs
Normal file
@@ -0,0 +1,53 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { createRequire } from 'node:module';
|
||||
import { test } from 'node:test';
|
||||
import React from 'react';
|
||||
import { act, create } from 'react-test-renderer';
|
||||
import ts from 'typescript';
|
||||
import * as chatModel from '../src/lib/chat.ts';
|
||||
|
||||
globalThis.IS_REACT_ACT_ENVIRONMENT = true;
|
||||
const require = createRequire(import.meta.url);
|
||||
const deferred = () => { let resolve; const promise = new Promise(yes => { resolve = yes; }); return { promise, resolve }; };
|
||||
|
||||
test('Eine verspätete Raumliste verdrängt keinen gerade angelegten Projektchat', async () => {
|
||||
const project = { key: 'project_42', name: 'Projekt', source: 'internal', type: 'project', exists: false, projectId: 42 };
|
||||
const directory = { rooms: [{ key: 'allgemein', name: 'Allgemein', source: 'internal', exists: true }, project], hiddenRoomKeys: [], invitations: [], projects: [] };
|
||||
const provision = deferred(), list = deferred(), timers = new Map();
|
||||
let directoryCalls = 0;
|
||||
const api = { directory: () => ++directoryCalls === 1 ? Promise.resolve(directory) : list.promise, provision: () => provision.promise };
|
||||
const output = ts.transpileModule(readFileSync(new URL('../app/(tabs)/communication.tsx', import.meta.url), 'utf8'), {
|
||||
compilerOptions: { module: ts.ModuleKind.CommonJS, jsx: ts.JsxEmit.ReactJSX, target: ts.ScriptTarget.ES2022 },
|
||||
}).outputText;
|
||||
const exports = {};
|
||||
new Function('require', 'exports', 'setInterval', 'clearInterval', output)(name => {
|
||||
if (name === 'react-native') return {
|
||||
...Object.fromEntries(['ActivityIndicator', 'FlatList', 'KeyboardAvoidingView', 'Modal', 'Pressable', 'ScrollView', 'Text', 'TextInput', 'View'].map(key => [key, key])),
|
||||
StyleSheet: { create: value => value }, Platform: { OS: 'ios' }, DeviceEventEmitter: { emit() {} },
|
||||
AppState: { currentState: 'active', addEventListener: () => ({ remove() {} }) },
|
||||
};
|
||||
if (name === '@expo/vector-icons') return { Ionicons: 'Icon' };
|
||||
if (name === '@react-navigation/native') return { useIsFocused: () => true };
|
||||
if (name === 'expo-crypto') return { randomUUID: () => 'draft-id' };
|
||||
if (name === '@/components/chat-conversation') return { ChatConversation: 'Conversation' };
|
||||
if (name === '@/src/lib/api') return {};
|
||||
if (name === '@/src/lib/chat-api') return { chatApi: api };
|
||||
if (name === '@/src/lib/chat') return chatModel;
|
||||
if (name === '@/src/lib/server-config') return { getApiBaseUrlSync: () => 'https://test.invalid' };
|
||||
if (name === '@/src/providers/auth-provider') return { useAuth: () => ({ token: 'test', activeTenantId: 1 }) };
|
||||
return require(name);
|
||||
}, exports, callback => { const id = Symbol(); timers.set(id, callback); return id; }, id => timers.delete(id));
|
||||
let root;
|
||||
try {
|
||||
await act(async () => { root = create(React.createElement(exports.default)); });
|
||||
const roomList = root.root.findAllByType('FlatList').find(node => node.props.horizontal);
|
||||
await act(async () => roomList.props.renderItem({ item: project }).props.onPress());
|
||||
await act(async () => { for (const callback of timers.values()) callback(); });
|
||||
assert.equal(directoryCalls, 2);
|
||||
await act(async () => provision.resolve({ ...project, exists: true }));
|
||||
assert.equal(root.root.findByType('Conversation').props.room.key, 'project_42');
|
||||
await act(async () => list.resolve(directory));
|
||||
assert.equal(root.root.findByType('Conversation').props.room.key, 'project_42');
|
||||
} finally { await act(async () => root?.unmount()); }
|
||||
});
|
||||
56
mobile/tests/chat-picker.test.mjs
Normal file
56
mobile/tests/chat-picker.test.mjs
Normal file
@@ -0,0 +1,56 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { createRequire } from 'node:module';
|
||||
import { test } from 'node:test';
|
||||
import React from 'react';
|
||||
import { act, create } from 'react-test-renderer';
|
||||
import ts from 'typescript';
|
||||
import * as chatModel from '../src/lib/chat.ts';
|
||||
|
||||
globalThis.IS_REACT_ACT_ENVIRONMENT = true;
|
||||
const require = createRequire(import.meta.url);
|
||||
function harness() {
|
||||
let resolvePicker;
|
||||
const picker = new Promise(resolve => { resolvePicker = resolve; });
|
||||
const drafts = [];
|
||||
const chat = { detail: { name: 'Test', canSend: true }, messages: [], members: [], reactions: {}, loading: false };
|
||||
const output = ts.transpileModule(readFileSync(new URL('../components/chat-conversation.tsx', import.meta.url), 'utf8'), {
|
||||
compilerOptions: { module: ts.ModuleKind.CommonJS, jsx: ts.JsxEmit.ReactJSX, target: ts.ScriptTarget.ES2022 },
|
||||
}).outputText;
|
||||
const exports = {};
|
||||
new Function('require', 'exports', output)(name => {
|
||||
if (name === 'react-native') return { ...Object.fromEntries(['ActivityIndicator', 'FlatList', 'Modal', 'Pressable', 'ScrollView', 'Text', 'TextInput', 'View'].map(key => [key, key])), StyleSheet: { create: value => value } };
|
||||
if (name === '@expo/vector-icons') return { Ionicons: 'Icon' };
|
||||
if (name === 'expo-image') return { Image: 'Image' };
|
||||
if (name === 'expo-image-picker') return { launchImageLibraryAsync: () => picker };
|
||||
if (name === '@/hooks/use-chat-conversation') return { useChatConversation: () => chat };
|
||||
if (name === '@/src/lib/chat-api') return { chatApi: {} };
|
||||
if (name === '@/src/lib/chat-image') return { prepareMobileChatImage: async () => ({ name: 'Bild.jpg', dataUrl: 'data:image/jpeg;base64,YQ==' }) };
|
||||
if (name === '@/src/lib/chat') return chatModel;
|
||||
return require(name);
|
||||
}, exports);
|
||||
const props = { token: 't', room: { key: 'test', name: 'Test' }, enabled: true,
|
||||
draft: { text: 'Bild dazu', image: null, clientId: 'draft' }, onDraft: draft => drafts.push(draft) };
|
||||
let root;
|
||||
return {
|
||||
drafts,
|
||||
async render(enabled) { await act(async () => { const element = React.createElement(exports.ChatConversation, { ...props, enabled }); if (root) root.update(element); else root = create(element); }); },
|
||||
async pick() { await act(async () => root.root.findByProps({ accessibilityLabel: 'Bild anhängen' }).props.onPress()); },
|
||||
async finish() { await act(async () => resolvePicker({ canceled: false, assets: [{ uri: 'file:///test.jpg' }] })); },
|
||||
async dispose() { await act(async () => root.unmount()); },
|
||||
};
|
||||
}
|
||||
test('System-Fotoauswahl darf die App vorübergehend in den Hintergrund versetzen', async () => {
|
||||
const h = harness();
|
||||
try {
|
||||
await h.render(true); await h.pick(); await h.render(false); await h.finish();
|
||||
assert.equal(h.drafts.length, 1);
|
||||
assert.equal(h.drafts[0].text, 'Bild dazu');
|
||||
assert.equal(h.drafts[0].image.name, 'Bild.jpg');
|
||||
} finally { await h.dispose(); }
|
||||
});
|
||||
test('Eine verspätete Fotoauswahl verändert nach Raumwechsel keinen anderen Entwurf', async () => {
|
||||
const h = harness();
|
||||
await h.render(true); await h.pick(); await h.dispose(); await h.finish();
|
||||
assert.equal(h.drafts.length, 0);
|
||||
});
|
||||
152
mobile/tests/chat.test.mjs
Normal file
152
mobile/tests/chat.test.mjs
Normal file
@@ -0,0 +1,152 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { test } from 'node:test';
|
||||
import {
|
||||
applyChatAccess, chatCursor, chatEndpoint, collaborationKey, createChatApi, matchesChatSearch,
|
||||
mergeChatMessages, sortChatRooms, touchChatRoom, validChatImage, visibleChatRooms,
|
||||
} from '../src/lib/chat.ts';
|
||||
|
||||
const id = '11111111-1111-4111-8111-111111111111';
|
||||
const internal = { key: 'allgemein', name: 'Allgemein', source: 'internal', exists: true };
|
||||
const remote = { key: collaborationKey(id), id, name: 'Partner', source: 'collaboration', exists: true };
|
||||
function fixture(overrides = {}) {
|
||||
const responses = {
|
||||
'/api/communication/chat/rooms': { rooms: [internal] },
|
||||
'/api/communication/chat/project-rooms': { rooms: [{ key: 'project_42', name: 'Projekt', exists: true }] },
|
||||
'/api/communication/chat/direct-rooms': { rooms: [] },
|
||||
'/api/communication/chat/unread': { rooms: { allgemein: { count: 7 }, project_42: { count: 2 } } },
|
||||
'/api/communication/chat/room-preferences': { hiddenRoomKeys: ['allgemein', collaborationKey(id)] },
|
||||
'/api/collaboration': { rooms: [{ id, name: 'Partner', remote: true, unread: 11 }], invitations: [{ id: 'invite', name: 'Team' }],
|
||||
managedRooms: [{ id: 'not-a-member', name: 'Verwalteter Raum ohne Teilnahme' }], canManage: true, projects: [{ id: 42, name: 'Projekt' }] },
|
||||
...overrides,
|
||||
};
|
||||
const calls = [];
|
||||
return { calls, api: createChatApi(async (path, options) => {
|
||||
calls.push({ path, ...options });
|
||||
if (!(path in responses)) throw new Error(`Unexpected request: ${path}`);
|
||||
if (responses[path] instanceof Error) throw responses[path];
|
||||
return structuredClone(responses[path]);
|
||||
}) };
|
||||
}
|
||||
|
||||
test('Web-Sichtbarkeit gilt auch für föderierte Räume und den Ungelesen-Zähler', async () => {
|
||||
const { api, calls } = fixture();
|
||||
const directory = await api.directory('tenant-token');
|
||||
assert.deepEqual(visibleChatRooms(directory).map(room => room.key), ['project_42']);
|
||||
assert.equal(directory.rooms.length, 3); // No implicit access via managedRooms.
|
||||
assert.equal(directory.rooms[2].source, 'collaboration');
|
||||
assert.equal(directory.rooms[2].remote, true);
|
||||
assert.equal(directory.invitations[0].id, 'invite');
|
||||
assert.equal(await api.unread('tenant-token'), 2);
|
||||
assert.ok(calls.every(call => call.token === 'tenant-token'));
|
||||
});
|
||||
test('Fehlende Sichtbarkeitseinstellungen zeigen keine ungefilterte Chatliste', async () => {
|
||||
const { api } = fixture({ '/api/communication/chat/room-preferences': new Error('offline') });
|
||||
await assert.rejects(api.directory('token'), /offline/);
|
||||
await assert.rejects(api.unread('token'), /offline/);
|
||||
});
|
||||
test('Föderierte Endpunkte, Cursor und Lesebestätigungen verwenden Raum-ID und Sequenz', async () => {
|
||||
const calls = [];
|
||||
const api = createChatApi(async (path, options) => { calls.push({ path, ...options }); return { messages: [] }; });
|
||||
await api.messages('t', remote, { after: 50 });
|
||||
await api.messages('t', remote, { before: 20 });
|
||||
await api.read('t', remote, 60);
|
||||
await api.messages('t', internal, { after: 12 });
|
||||
await api.read('t', internal, 14);
|
||||
assert.equal(calls[0].path, `/api/collaboration/rooms/${id}/messages?after=50`);
|
||||
assert.equal(calls[1].path, `/api/collaboration/rooms/${id}/messages?before=20`);
|
||||
assert.deepEqual(calls[2].body, { seq: 60 });
|
||||
assert.equal(calls[3].path, '/api/communication/chat/rooms/allgemein/sync?afterId=12');
|
||||
assert.deepEqual(calls[4].body, { messageId: 14 });
|
||||
assert.equal(chatCursor(remote, [{ id: 'pending', seq: null }, { id: 'uuid', seq: 7 }]), 7);
|
||||
});
|
||||
test('Bestätigungen ersetzen wartende Nachrichten ohne doppelte oder verspätete Kopien', () => {
|
||||
const pending = { id: 'client-1', clientId: 'client-1', own: true, pending: true, seq: null };
|
||||
const delivered = { id: 'server-1', clientId: 'client-1', own: true, seq: 9 };
|
||||
const first = mergeChatMessages([pending], [delivered], true);
|
||||
assert.deepEqual(first, [delivered]);
|
||||
assert.deepEqual(mergeChatMessages(first, [pending], true), [delivered]);
|
||||
assert.deepEqual(mergeChatMessages([], [delivered, pending], true), [delivered]);
|
||||
assert.deepEqual(mergeChatMessages([{ id: 2 }], [{ id: 1 }, { id: 2, body: 'aktualisiert' }], false), [{ id: 1 }, { id: 2, body: 'aktualisiert' }]);
|
||||
});
|
||||
test('Geänderte Teilnahmerechte entfernen frühere Historie und alte ausstehende Nachrichten', () => {
|
||||
const messages = [{ id: 'old', seq: 1 }, { id: 'new', seq: 8 }, { id: 'pending', seq: null }];
|
||||
assert.deepEqual(applyChatAccess(messages, { historyFromSeq: 5, revision: 2 }, { revision: 1 }), [{ id: 'new', seq: 8 }]);
|
||||
assert.equal(applyChatAccess(messages, { historyFromSeq: 5, revision: 1 }, { revision: 1 }).length, 2);
|
||||
});
|
||||
test('Senden behält die Idempotenz-ID und überträgt Bilder an die passende Schnittstelle', async () => {
|
||||
const calls = [];
|
||||
const api = createChatApi(async (path, options) => { calls.push({ path, ...options }); return {}; });
|
||||
const image = { name: 'Foto.jpg', dataUrl: 'data:image/jpeg;base64,YQ==' };
|
||||
await api.send('t', remote, '', image, 'same-client-id');
|
||||
await api.send('t', remote, '', image, 'same-client-id');
|
||||
await api.send('t', internal, 'Hallo', null, 'unused');
|
||||
assert.deepEqual(calls[0], calls[1]);
|
||||
assert.deepEqual(calls[0].body, { text: '', image, clientId: 'same-client-id' });
|
||||
assert.deepEqual(calls[2].body, { text: 'Hallo' });
|
||||
});
|
||||
test('Einladungen und ausgeblendete Räume verwenden dieselben Schlüssel wie das Web', async () => {
|
||||
const calls = [];
|
||||
const api = createChatApi(async (path, options) => { calls.push({ path, ...options }); return {}; });
|
||||
await api.respond('t', id, true); await api.respond('t', id, false);
|
||||
await api.hide('t', remote.key, true); await api.hide('t', remote.key, false);
|
||||
assert.equal(calls[0].path, `/api/collaboration/invitations/${id}/accept`);
|
||||
assert.equal(calls[1].path, `/api/collaboration/invitations/${id}/decline`);
|
||||
assert.deepEqual(calls[2].body, { roomKey: collaborationKey(id), hidden: true });
|
||||
assert.equal(calls[3].body.hidden, false);
|
||||
});
|
||||
test('Reaktionen werden begrenzt geladen; wartende Nachrichten bleiben ausgeschlossen', async () => {
|
||||
const calls = [];
|
||||
const api = createChatApi(async (path, options) => { calls.push({ path, ...options }); return { reactions: {} }; });
|
||||
const messages = Array.from({ length: 205 }, (_, index) => ({ id: index + 1 }));
|
||||
messages.push({ id: 'pending', pending: true }, { id: 'failed', failed: true });
|
||||
await api.reactions('t', remote, messages);
|
||||
assert.equal(calls.length, 3);
|
||||
for (const call of calls) {
|
||||
const ids = new URL(call.path, 'https://example.invalid').searchParams.get('ids').split(',');
|
||||
assert.ok(ids.length <= 100); assert.ok(ids.every(value => /^\d+$/.test(value)));
|
||||
}
|
||||
await api.react('t', remote, id, '👍', false);
|
||||
assert.deepEqual(calls[3].body, { messageId: id, emoji: '👍', active: false });
|
||||
});
|
||||
test('Chatbilder akzeptieren keine externen URLs, SVGs oder übergroßen Inhalte', async () => {
|
||||
for (const value of ['https://tracker.invalid/image.png', 'data:image/svg+xml;base64,YQ==', `data:image/png;base64,${'a'.repeat(700_000)}`]) {
|
||||
assert.equal(validChatImage(value), false);
|
||||
const api = createChatApi(async () => ({ dataUrl: value }));
|
||||
await assert.rejects(api.image('t', remote, id), /Ungültiges Chatbild/);
|
||||
}
|
||||
assert.equal(validChatImage('data:image/webp;base64,YQ=='), true);
|
||||
});
|
||||
test('Suche berücksichtigt mehrere Begriffe, Umlaute und Partnernamen', () => {
|
||||
assert.equal(matchesChatSearch({ name: 'Büro Süd', ownerName: 'Straße GmbH' }, 'buro strasse'), true);
|
||||
assert.equal(matchesChatSearch({ name: 'Büro Süd', ownerName: 'Straße GmbH' }, 'buro nord'), false);
|
||||
});
|
||||
test('Noch nicht angelegte Direkt- und Projektchats werden gezielt provisioniert', async () => {
|
||||
const calls = [];
|
||||
const api = createChatApi(async (path, options) => { calls.push({ path, ...options }); return { exists: true }; });
|
||||
await api.provision('t', { ...internal, exists: false, type: 'project', projectId: 42 });
|
||||
await api.provision('t', { ...internal, exists: false, type: 'direct', userId: 'user/id' });
|
||||
await api.provision('t', remote);
|
||||
assert.equal(calls.length, 2);
|
||||
assert.equal(calls[0].path, '/api/communication/chat/project-rooms/42/provision');
|
||||
assert.equal(calls[1].path, '/api/communication/chat/direct-rooms/user%2Fid/provision');
|
||||
assert.equal(chatEndpoint(remote), `/api/collaboration/rooms/${id}`);
|
||||
});
|
||||
|
||||
test('Chats werden nach letzter Aktivität sortiert, neue Nachrichten rücken nach oben', () => {
|
||||
const rooms = [
|
||||
{ key: 'ohne', name: 'Ohne Aktivität', source: 'internal', exists: false },
|
||||
{ key: 'alt', name: 'Alt', source: 'internal', exists: true, lastActivityAt: '2026-01-01T10:00:00.000Z' },
|
||||
{ key: 'neu', name: 'Neu', source: 'collaboration', exists: true, lastActivityAt: '2026-03-01T10:00:00.000Z' },
|
||||
];
|
||||
assert.deepEqual(sortChatRooms(rooms).map(room => room.key), ['neu', 'alt', 'ohne']);
|
||||
assert.deepEqual(touchChatRoom(rooms, 'alt', '2026-04-01T10:00:00.000Z').map(room => room.key), ['alt', 'neu', 'ohne']);
|
||||
assert.equal(rooms[1].lastActivityAt, '2026-01-01T10:00:00.000Z');
|
||||
});
|
||||
test('Verzeichnis sortiert Räume aller Gruppen gemeinsam nach Aktivität', async () => {
|
||||
const { api } = fixture({
|
||||
'/api/communication/chat/rooms': { rooms: [{ ...internal, lastActivityAt: '2026-01-01T00:00:00.000Z' }] },
|
||||
'/api/collaboration': { rooms: [{ id, name: 'Partner', lastActivityAt: '2026-02-01T00:00:00.000Z' }], invitations: [] },
|
||||
});
|
||||
const result = await api.directory('token');
|
||||
assert.deepEqual(result.rooms.map(room => room.key), [collaborationKey(id), 'allgemein', 'project_42']);
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"initialVersion": "3.0.0",
|
||||
"bootstrapCommit": "cfef07b96d97f8dffdfc32c74f8f32b62fe43b18",
|
||||
"legacyHistoryHeads": ["e7554fa2cc649f69dce4880abe76c6fab0f82700"],
|
||||
"legacyHistoryHeads": ["e7554fa2cc649f69dce4880abe76c6fab0f82700", "89185b4b086d782b59146c9c7cf45392b0078cc7"],
|
||||
"branch": "main",
|
||||
"repositoryUrl": "https://git.federspiel.tech/flfeders/FEDEO",
|
||||
"registry": "git.federspiel.tech/flfeders/fedeo",
|
||||
|
||||
Reference in New Issue
Block a user