Compare commits
7 Commits
v3.9.0
...
daaed01d02
| Author | SHA1 | Date | |
|---|---|---|---|
| daaed01d02 | |||
| 7e6c2fbac5 | |||
| 0887863981 | |||
| 6ff9971ff9 | |||
| e7d6c482ad | |||
| 1885bfc521 | |||
| 09a002d600 |
12
.env.example
12
.env.example
@@ -51,11 +51,13 @@ SEAFILE_ADMIN_PASSWORD=change-this-seafile-admin-password
|
||||
|
||||
M2M_API_KEY=change-this-m2m-key
|
||||
API_BASE_URL=https://app.example.com/backend
|
||||
# Collaboration: public browser URL and canonical HTTPS API address (including reverse-proxy prefix).
|
||||
FEDEO_PUBLIC_URL=https://app.example.com
|
||||
FEDEO_FEDERATION_URL=https://app.example.com/backend
|
||||
# Requires mutual tenant partner approval under Zusammenarbeit.
|
||||
FEDEO_FEDERATION_ENABLED=false
|
||||
# Collaboration uses API_BASE_URL for federation and its origin for guest links.
|
||||
# Optional overrides only, e.g. when using a separate federation gateway.
|
||||
FEDEO_PUBLIC_URL=
|
||||
FEDEO_FEDERATION_URL=
|
||||
# auto: enabled with a valid HTTPS API address and ENCRYPTION_KEY; false: opt out.
|
||||
# Partners still require mutual tenant approval under Zusammenarbeit.
|
||||
FEDEO_FEDERATION_ENABLED=auto
|
||||
GOCARDLESS_BASE_URL=https://api.gocardless.com
|
||||
GOCARDLESS_SECRET_ID=replace-this
|
||||
GOCARDLESS_SECRET_KEY=replace-this
|
||||
|
||||
@@ -87,6 +87,8 @@ Minimal wichtige Werte fur den ersten Start:
|
||||
- `DATABASE_URL=postgres://fedeo:<starkes-passwort>@db:5432/fedeo`
|
||||
- `API_BASE_URL=https://app.example.com/backend`
|
||||
|
||||
Die Chat-Föderation verwendet ebenfalls `API_BASE_URL`; Gastlinks übernehmen deren Ursprung. Mit gültiger öffentlicher HTTPS-Adresse auf Port 443 und vorhandenem gültigem `ENCRYPTION_KEY` ist sie automatisch verfügbar. Zusätzliche URLs sind nur bei abweichender Infrastruktur nötig (`FEDEO_FEDERATION_URL`, `FEDEO_PUBLIC_URL`). `FEDEO_FEDERATION_ENABLED=false` schaltet sie ausdrücklich ab; der Standard ist `auto`. Der Updater übernimmt die passenden Compose-Einträge aus dem Release. Partner müssen anschließend weiterhin je Mandant freigegeben werden; siehe [Föderation einrichten](docs/chat-foederation-konzept.md#15-implementierter-stand-und-pilotbetrieb).
|
||||
|
||||
Wenn du MinIO verwendest, setze zusatzlich:
|
||||
|
||||
- `S3_ENDPOINT=http://minio:9000`
|
||||
|
||||
8
backend/db/migrations/0078_chat_visibility.sql
Normal file
8
backend/db/migrations/0078_chat_visibility.sql
Normal file
@@ -0,0 +1,8 @@
|
||||
ALTER TABLE "projects" ADD COLUMN IF NOT EXISTS "chat_enabled" boolean NOT NULL DEFAULT true;
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "communication_hidden_rooms" (
|
||||
"tenant_id" bigint NOT NULL REFERENCES "tenants"("id") ON DELETE CASCADE,
|
||||
"user_id" uuid NOT NULL REFERENCES "auth_users"("id") ON DELETE CASCADE,
|
||||
"room_key" text NOT NULL,
|
||||
PRIMARY KEY ("tenant_id", "user_id", "room_key")
|
||||
);
|
||||
@@ -526,6 +526,13 @@
|
||||
"when": 1790899200000,
|
||||
"tag": "0077_scanner_inbox_preparation",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 75,
|
||||
"version": "7",
|
||||
"when": 1790985600000,
|
||||
"tag": "0078_chat_visibility",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
10
backend/db/schema/communication_hidden_rooms.ts
Normal file
10
backend/db/schema/communication_hidden_rooms.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
import { bigint, pgTable, primaryKey, text, uuid } from "drizzle-orm/pg-core"
|
||||
import { authUsers } from "./auth_users"
|
||||
import { tenants } from "./tenants"
|
||||
|
||||
// Room keys also cover collaboration bindings and not-yet-provisioned chats.
|
||||
export const communicationHiddenRooms = pgTable("communication_hidden_rooms", {
|
||||
tenantId: bigint("tenant_id", { mode: "number" }).notNull().references(() => tenants.id, { onDelete: "cascade" }),
|
||||
userId: uuid("user_id").notNull().references(() => authUsers.id, { onDelete: "cascade" }),
|
||||
roomKey: text("room_key").notNull(),
|
||||
}, table => ({ pk: primaryKey({ columns: [table.tenantId, table.userId, table.roomKey] }) }))
|
||||
@@ -19,6 +19,7 @@ export * from "./communication_rooms"
|
||||
export * from "./communication_room_members"
|
||||
export * from "./communication_messages"
|
||||
export * from "./communication_room_reads"
|
||||
export * from "./communication_hidden_rooms"
|
||||
export * from "./contacts"
|
||||
export * from "./contracts"
|
||||
export * from "./contracttypes"
|
||||
|
||||
@@ -66,6 +66,8 @@ export const projects = pgTable("projects", {
|
||||
|
||||
archived: boolean("archived").notNull().default(false),
|
||||
|
||||
chatEnabled: boolean("chat_enabled").notNull().default(true),
|
||||
|
||||
customerRef: text("customerRef"),
|
||||
|
||||
updatedAt: timestamp("updated_at", { withTimezone: true }),
|
||||
|
||||
30
backend/src/modules/collaboration/config.ts
Normal file
30
backend/src/modules/collaboration/config.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import { instanceUrl } from "./transport"
|
||||
|
||||
type Settings = {
|
||||
API_BASE_URL?: string;
|
||||
ENCRYPTION_KEY?: string;
|
||||
FEDEO_PUBLIC_URL?: string;
|
||||
FEDEO_FEDERATION_URL?: string;
|
||||
FEDEO_FEDERATION_ENABLED?: string;
|
||||
}
|
||||
|
||||
/** Existing deployment settings are sufficient; extra URLs are optional overrides. */
|
||||
export function collaborationConfig(settings: Settings) {
|
||||
const configuredApi = settings.API_BASE_URL?.trim() || ""
|
||||
let apiUrl = (settings.FEDEO_FEDERATION_URL?.trim() || configuredApi).replace(/\/+$/, "")
|
||||
let publicUrl = settings.FEDEO_PUBLIC_URL?.trim().replace(/\/+$/, "") || ""
|
||||
if (!publicUrl) {
|
||||
try { publicUrl = new URL(configuredApi || apiUrl).origin } catch { /* Local development may have no public URL. */ }
|
||||
}
|
||||
const mode = settings.FEDEO_FEDERATION_ENABLED?.trim().toLowerCase() || "auto"
|
||||
if (!["auto", "true", "false"].includes(mode)) throw new Error("FEDEO_FEDERATION_ENABLED muss auto, true oder false sein")
|
||||
if (mode === "false") return { apiUrl, publicUrl, enabled: false, disabledReason: "Die Föderation wurde vom Betreiber deaktiviert." }
|
||||
|
||||
let disabledReason: string | undefined
|
||||
try { apiUrl = instanceUrl(apiUrl) }
|
||||
catch { disabledReason = "Föderation benötigt eine gültige öffentliche HTTPS-API_BASE_URL auf Port 443." }
|
||||
if (!disabledReason && !/^[a-f0-9]{64}$/i.test(settings.ENCRYPTION_KEY || "")) {
|
||||
disabledReason = "Föderation benötigt einen gültigen ENCRYPTION_KEY mit 64 Hex-Zeichen." }
|
||||
if (mode === "true" && disabledReason) throw new Error(disabledReason)
|
||||
return { apiUrl, publicUrl, enabled: !disabledReason, disabledReason }
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import { FederationKey, Headers, instanceUrl, safeTransport, signedHeaders, Tran
|
||||
|
||||
type Options = {
|
||||
apiUrl: string; enabled: boolean;
|
||||
disabledReason?: string;
|
||||
seal: (value: string) => any; unseal: (value: any) => string;
|
||||
transport?: Transport;
|
||||
}
|
||||
@@ -22,7 +23,7 @@ export class FederationService {
|
||||
this.transport = options.transport || safeTransport
|
||||
}
|
||||
enabled() {
|
||||
if (!this.options.enabled) fail("Der Betreiber muss die Föderation zuerst aktivieren", 503)
|
||||
if (!this.options.enabled) fail(this.options.disabledReason || "Der Betreiber muss die Föderation zuerst aktivieren", 503)
|
||||
instanceUrl(this.origin)
|
||||
}
|
||||
async keys() {
|
||||
@@ -71,7 +72,7 @@ export class FederationService {
|
||||
VALUES (${ctx.tenantId},${origin},${instanceId},${keyId},${publicKey}) ON CONFLICT(tenant_id,origin) DO UPDATE SET active=true,updated_at=now()`)
|
||||
}
|
||||
}
|
||||
return { enabled: this.options.enabled, origin: this.origin, partners: (await rows(this.service.db,
|
||||
return { enabled: this.options.enabled, disabledReason: this.options.disabledReason, origin: this.origin, partners: (await rows(this.service.db,
|
||||
sql`SELECT origin,active,public_key FROM collaboration_partners WHERE tenant_id=${ctx.tenantId} ORDER BY origin`)).map(p => ({ origin: p.origin, active: p.active, fingerprint: hash(p.public_key) })) }
|
||||
}
|
||||
async call(tenantId: number, origin: string, action: string, payload: any) {
|
||||
|
||||
@@ -4,16 +4,18 @@ import { sendMail } from "../../utils/mailer"
|
||||
import { CollaborationService } from "./service"
|
||||
import { FederationService } from "./federation"
|
||||
import { encrypt, decrypt } from "../../utils/crypt"
|
||||
import { collaborationConfig } from "./config"
|
||||
|
||||
export function collaborationRuntime(server: FastifyInstance) {
|
||||
const apiUrl = String(process.env.FEDEO_FEDERATION_URL || secrets.API_BASE_URL || "").replace(/\/$/, "")
|
||||
const publicUrl = String(process.env.FEDEO_PUBLIC_URL || (apiUrl ? new URL(apiUrl).origin : "")).replace(/\/$/, "")
|
||||
const { apiUrl, publicUrl, enabled, disabledReason } = collaborationConfig({
|
||||
...process.env, API_BASE_URL: secrets.API_BASE_URL, ENCRYPTION_KEY: secrets.ENCRYPTION_KEY,
|
||||
})
|
||||
const service = new CollaborationService(server.db, {
|
||||
publicUrl,
|
||||
guestPepper: () => secrets.ENCRYPTION_KEY || "",
|
||||
sendMail,
|
||||
})
|
||||
const federation = new FederationService(service, { apiUrl, enabled: process.env.FEDEO_FEDERATION_ENABLED === "true", seal: encrypt, unseal: decrypt })
|
||||
const federation = new FederationService(service, { apiUrl, enabled, disabledReason, seal: encrypt, unseal: decrypt })
|
||||
service.options.changed = (roomId, db) => federation.changed(roomId, db)
|
||||
service.options.invited = (ctx, roomId, target, invitationId, db) => federation.invite(ctx, roomId, target, invitationId, db)
|
||||
let timer: ReturnType<typeof setInterval>
|
||||
|
||||
@@ -15,9 +15,18 @@ export function managesProjects(req: any): boolean {
|
||||
return Boolean(req.user?.is_admin || req.hasPermission?.("organisation.projects.write"))
|
||||
}
|
||||
|
||||
export function projectChatSettingError(req: any, body: Record<string, unknown>, previous = true) {
|
||||
if (!Object.prototype.hasOwnProperty.call(body, "chatEnabled")) return null
|
||||
if (typeof body.chatEnabled !== "boolean") return { statusCode: 400, error: "Projektchat aktiviert muss ein Wahrheitswert sein" }
|
||||
if (body.chatEnabled !== previous && !managesProjects(req)) {
|
||||
return { statusCode: 403, error: "Keine Berechtigung zum Ändern des Projektchats" }
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
export async function projectChatAccess(db: any, req: any, projectId?: number) {
|
||||
const tenantId = Number(req.user?.tenant_id)
|
||||
const conditions = [eq(projects.tenant, tenantId), eq(projects.archived, false)]
|
||||
const conditions = [eq(projects.tenant, tenantId), eq(projects.archived, false), eq(projects.chatEnabled, true)]
|
||||
if (projectId !== undefined) conditions.push(eq(projects.id, projectId))
|
||||
const rows = await db.select().from(projects).where(and(...conditions))
|
||||
if (managesProjects(req)) return rows
|
||||
|
||||
@@ -184,6 +184,29 @@ export function createScannerInboxService(db: FastifyInstance["db"], storage: Sc
|
||||
if (!file) throw scannerError(404, "Dokument nicht gefunden.")
|
||||
return currentAssignments(db, tenantId, file)
|
||||
}
|
||||
const archiveDocument = async (tenantId: number, userId: string, fileId: string) => db.transaction(async tx => {
|
||||
const [tenant] = await tx.select({ locked: tenants.locked }).from(tenants)
|
||||
.where(eq(tenants.id, tenantId)).for("share")
|
||||
if (!tenant) throw scannerError(404, "Mandant nicht gefunden.")
|
||||
if (tenant.locked === "maintenance_tenant") throw scannerError(423, "Der Mandant wird gerade gewartet.")
|
||||
// Use the same lock order as filing so both actions cannot succeed concurrently.
|
||||
const [entry] = await tx.select({ filedAt: scannerInboxDocuments.filedAt }).from(scannerInboxDocuments)
|
||||
.where(and(eq(scannerInboxDocuments.tenantId, tenantId), eq(scannerInboxDocuments.fileId, fileId))).for("update")
|
||||
if (!entry) throw scannerError(404, "Dokument nicht in der Ablage gefunden.")
|
||||
if (entry.filedAt) throw scannerError(409, "Dieses Dokument wurde bereits abgelegt. Bitte den Eingang aktualisieren.")
|
||||
const [file] = await tx.select({ archived: files.archived }).from(files)
|
||||
.where(and(eq(files.id, fileId), eq(files.tenant, tenantId))).for("update")
|
||||
if (!file) throw scannerError(404, "Dokument nicht gefunden.")
|
||||
if (!file.archived) {
|
||||
await tx.update(files).set({ archived: true, updatedAt: new Date(), updatedBy: userId })
|
||||
.where(and(eq(files.id, fileId), eq(files.tenant, tenantId)))
|
||||
}
|
||||
// Keep the receipt for scanner retries; invalidate any analysis already in flight.
|
||||
await tx.update(scannerInboxDocuments).set({ suggestionClaim: null,
|
||||
suggestionStatus: sql`CASE WHEN ${scannerInboxDocuments.suggestionStatus} = 'processing' THEN 'pending' ELSE ${scannerInboxDocuments.suggestionStatus} END` })
|
||||
.where(and(eq(scannerInboxDocuments.fileId, fileId), eq(scannerInboxDocuments.tenantId, tenantId)))
|
||||
return { id: fileId, archived: true }
|
||||
})
|
||||
const fileDocument = async (tenantId: number, userId: string, fileId: string, folderId: string | null, typeId: string, assignments: FileAssignments = {}) => db.transaction(async tx => {
|
||||
const [tenant] = await tx.select({ locked: tenants.locked }).from(tenants)
|
||||
.where(eq(tenants.id, tenantId)).for("share")
|
||||
@@ -277,7 +300,7 @@ export function createScannerInboxService(db: FastifyInstance["db"], storage: Sc
|
||||
}
|
||||
}
|
||||
return { connection, credentials, disable, authenticate, find, list, openCount, filingOptions, getSuggestion, queueSuggestion, processNextSuggestion,
|
||||
getAssignments, assignmentOptions: (tenantId: number, kind: string, search: string) => assignmentOptions(db, tenantId, kind, search), fileDocument, probe, accept }
|
||||
getAssignments, assignmentOptions: (tenantId: number, kind: string, search: string) => assignmentOptions(db, tenantId, kind, search), archiveDocument, fileDocument, probe, accept }
|
||||
}
|
||||
|
||||
export type ScannerInboxService = ReturnType<typeof createScannerInboxService>
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
communicationRoomMembers,
|
||||
communicationRoomReads,
|
||||
communicationRooms,
|
||||
communicationHiddenRooms,
|
||||
notificationsItems,
|
||||
projects,
|
||||
} from "../../db/schema"
|
||||
@@ -244,6 +245,28 @@ export default async function communicationRoutes(server: FastifyInstance) {
|
||||
|
||||
server.get("/communication/chat/status", async () => ({ ready: true, provider: "fedeo" }))
|
||||
|
||||
server.get("/communication/chat/room-preferences", async (req: any) => {
|
||||
const tenantId = await requireTenant(req)
|
||||
const hidden = await server.db.select({ key: communicationHiddenRooms.roomKey }).from(communicationHiddenRooms)
|
||||
.where(and(eq(communicationHiddenRooms.tenantId, tenantId), eq(communicationHiddenRooms.userId, req.user.user_id)))
|
||||
return { hiddenRoomKeys: hidden.map(room => room.key) }
|
||||
})
|
||||
|
||||
server.put("/communication/chat/room-preferences", async (req: any, reply) => {
|
||||
const tenantId = await requireTenant(req)
|
||||
const { roomKey, hidden } = req.body || {}
|
||||
if (typeof hidden !== "boolean" || typeof roomKey !== "string" || roomKey.length > 200
|
||||
|| !/^(?:[a-z0-9._=-]+|collaboration:[a-f0-9-]{36})$/.test(roomKey)) {
|
||||
return reply.code(400).send({ error: "Ungültige Raumeinstellung" })
|
||||
}
|
||||
const value = { tenantId, userId: req.user.user_id, roomKey }
|
||||
if (hidden) await server.db.insert(communicationHiddenRooms).values(value).onConflictDoNothing()
|
||||
else await server.db.delete(communicationHiddenRooms).where(and(
|
||||
eq(communicationHiddenRooms.tenantId, tenantId), eq(communicationHiddenRooms.userId, req.user.user_id),
|
||||
eq(communicationHiddenRooms.roomKey, roomKey)))
|
||||
return { roomKey, hidden }
|
||||
})
|
||||
|
||||
server.get("/communication/chat/users", async (req: any) => {
|
||||
const tenantId = await requireTenant(req)
|
||||
return { users: (await tenantUsers(tenantId)).map((user) => ({
|
||||
|
||||
@@ -41,6 +41,9 @@ export default async function documentInboxRoutes(server: FastifyInstance, optio
|
||||
server.post<{ Params: { id: string } }>("/document-inbox/:id/suggestion", {
|
||||
schema: { params: { type: "object", required: ["id"], properties: { id: { type: "string", format: "uuid" } } } },
|
||||
}, async (req, reply) => reply.code(202).send(await service.queueSuggestion(req.user.tenant_id!, req.params.id)))
|
||||
server.post<{ Params: { id: string } }>("/document-inbox/:id/archive", {
|
||||
schema: { params: { type: "object", required: ["id"], properties: { id: { type: "string", format: "uuid" } } } },
|
||||
}, async req => service.archiveDocument(req.user.tenant_id!, req.user.user_id, req.params.id))
|
||||
server.post<{ Params: { id: string }; Body: { folder: string | null; type: string; assignments?: FileAssignments } }>("/document-inbox/:id/file", {
|
||||
schema: {
|
||||
params: { type: "object", required: ["id"], properties: { id: { type: "string", format: "uuid" } } },
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { validateCostCentreParent } from "../../modules/cost-centre-hierarchy.service"
|
||||
import { projectChatSettingError } from "../../modules/communication-access"
|
||||
import { FastifyInstance } from "fastify"
|
||||
import {
|
||||
eq,
|
||||
@@ -942,6 +943,10 @@ export default async function resourceRoutes(server: FastifyInstance) {
|
||||
const table = config.table;
|
||||
|
||||
let createData: Record<string, any> = { ...body, tenant: req.user.tenant_id, archived: false };
|
||||
if (resource === "projects") {
|
||||
const error = projectChatSettingError(req, createData)
|
||||
if (error) return reply.code(error.statusCode).send({ error: error.error })
|
||||
}
|
||||
|
||||
if (resource === "members") {
|
||||
createData = normalizeMemberPayload(createData)
|
||||
@@ -1095,6 +1100,11 @@ export default async function resourceRoutes(server: FastifyInstance) {
|
||||
return reply.code(404).send({ error: "Resource not found" })
|
||||
}
|
||||
|
||||
if (resource === "projects") {
|
||||
const error = projectChatSettingError(req, body, oldRecord.chatEnabled)
|
||||
if (error) return reply.code(error.statusCode).send({ error: error.error })
|
||||
}
|
||||
|
||||
let data: Record<string, any> = { ...body }
|
||||
delete data.updatedAt
|
||||
delete data.updated_at
|
||||
|
||||
110
backend/tests/chatVisibility.test.ts
Normal file
110
backend/tests/chatVisibility.test.ts
Normal file
@@ -0,0 +1,110 @@
|
||||
import assert from "node:assert/strict"
|
||||
import test from "node:test"
|
||||
import { randomUUID } from "node:crypto"
|
||||
import { readFile } from "node:fs/promises"
|
||||
import Fastify from "fastify"
|
||||
import communicationRoutes from "../src/routes/communication"
|
||||
import resourceRoutes from "../src/routes/resources/main"
|
||||
import { projectChatSettingError } from "../src/modules/communication-access"
|
||||
import { collaborationDatabase, testDatabaseUrl } from "./helpers/collaboration-db"
|
||||
|
||||
test("changing the project chat switch requires project management permission and a boolean", () => {
|
||||
const member = { user: {}, hasPermission: () => false }
|
||||
const manager = { user: {}, hasPermission: (permission: string) => permission === "organisation.projects.write" }
|
||||
assert.equal(projectChatSettingError(member, {}), null)
|
||||
assert.equal(projectChatSettingError(member, { chatEnabled: true }), null)
|
||||
assert.equal(projectChatSettingError(member, { chatEnabled: false }, false), null)
|
||||
assert.equal(projectChatSettingError(member, { chatEnabled: false })?.statusCode, 403)
|
||||
assert.equal(projectChatSettingError(member, { chatEnabled: true }, false)?.statusCode, 403)
|
||||
assert.equal(projectChatSettingError(manager, { chatEnabled: false }), null)
|
||||
assert.equal(projectChatSettingError({ user: { is_admin: true } }, { chatEnabled: true }, false), null)
|
||||
for (const invalid of [null, "false", 0, {}]) assert.equal(projectChatSettingError(manager, { chatEnabled: invalid })?.statusCode, 400)
|
||||
})
|
||||
|
||||
test("migration keeps existing and newly created project chats enabled", { skip: !testDatabaseUrl }, async () => {
|
||||
const fixture = await collaborationDatabase()
|
||||
try {
|
||||
await fixture.pool.query("ALTER TABLE projects DROP COLUMN chat_enabled")
|
||||
await fixture.pool.query("INSERT INTO projects (id,tenant,name) VALUES (1,1,'Existing')")
|
||||
await fixture.pool.query(await readFile(new URL("../db/migrations/0078_chat_visibility.sql", import.meta.url), "utf8"))
|
||||
await fixture.pool.query("INSERT INTO projects (id,tenant,name) VALUES (2,1,'New')")
|
||||
assert.deepEqual((await fixture.pool.query("SELECT chat_enabled FROM projects ORDER BY id")).rows, [{ chat_enabled: true }, { chat_enabled: true }])
|
||||
} finally { await fixture.close() }
|
||||
})
|
||||
|
||||
test("hidden rooms persist per user and tenant without changing room memberships", { skip: !testDatabaseUrl }, async () => {
|
||||
const fixture = await collaborationDatabase(["0078_chat_visibility.sql"]), app = Fastify()
|
||||
const user = randomUUID(), other = randomUUID(), collaborationKey = `collaboration:${randomUUID()}`
|
||||
try {
|
||||
await fixture.pool.query("INSERT INTO tenants(id,name) VALUES (1,'A'),(2,'B')")
|
||||
await fixture.pool.query("INSERT INTO auth_users(id,email) VALUES ($1,'a@example.test'),($2,'b@example.test')", [user, other])
|
||||
await fixture.pool.query("INSERT INTO auth_tenant_users(tenant_id,user_id) VALUES (1,$1),(2,$1),(1,$2)", [user, other])
|
||||
app.decorate("db", fixture.db)
|
||||
app.addHook("preHandler", async (req: any) => {
|
||||
req.user = { tenant_id: Number(req.headers["x-tenant"] || 1), user_id: req.headers["x-user"] || user }
|
||||
req.hasPermission = () => false
|
||||
})
|
||||
await app.register(communicationRoutes)
|
||||
const url = "/communication/chat/room-preferences"
|
||||
for (const roomKey of ["allgemein", "project_1", collaborationKey, collaborationKey]) {
|
||||
const result = await app.inject({ method: "PUT", url, payload: { roomKey, hidden: true, userId: other, tenantId: 2 } })
|
||||
assert.equal(result.statusCode, 200, result.body)
|
||||
}
|
||||
assert.deepEqual((await app.inject(url)).json().hiddenRoomKeys.sort(), ["allgemein", "project_1", collaborationKey].sort())
|
||||
assert.deepEqual((await app.inject({ url, headers: { "x-user": other } })).json().hiddenRoomKeys, [])
|
||||
assert.deepEqual((await app.inject({ url, headers: { "x-tenant": "2" } })).json().hiddenRoomKeys, [])
|
||||
assert.equal((await fixture.pool.query("SELECT count(*) FROM communication_room_members")).rows[0].count, "0")
|
||||
await app.inject({ method: "PUT", url, payload: { roomKey: collaborationKey, hidden: false } })
|
||||
assert.deepEqual((await app.inject(url)).json().hiddenRoomKeys.sort(), ["allgemein", "project_1"])
|
||||
for (const payload of [{ roomKey: "allgemein", hidden: "false" }, { roomKey: "../secret", hidden: true }, { roomKey: "", hidden: true }]) {
|
||||
assert.equal((await app.inject({ method: "PUT", url, payload })).statusCode, 400)
|
||||
}
|
||||
await fixture.pool.query("DELETE FROM auth_tenant_users WHERE tenant_id=1 AND user_id=$1", [user])
|
||||
assert.equal((await app.inject(url)).statusCode, 403)
|
||||
assert.equal((await app.inject({ method: "PUT", url, payload: { roomKey: "allgemein", hidden: false } })).statusCode, 403)
|
||||
} finally { await app.close(); await fixture.close() }
|
||||
})
|
||||
|
||||
test("disabling in the project form blocks list, provision, reads and writes until re-enabled", { skip: !testDatabaseUrl }, async () => {
|
||||
const fixture = await collaborationDatabase(), app = Fastify()
|
||||
const user = randomUUID(), profile = randomUUID()
|
||||
try {
|
||||
await fixture.pool.query("INSERT INTO tenants(id,name) VALUES (1,'A'),(2,'B')")
|
||||
await fixture.pool.query("INSERT INTO auth_users(id,email) VALUES ($1,'a@example.test')", [user])
|
||||
await fixture.pool.query("INSERT INTO auth_tenant_users(tenant_id,user_id) VALUES (1,$1)", [user])
|
||||
await fixture.pool.query("INSERT INTO auth_profiles(id,tenant_id,user_id) VALUES ($1,1,$2)", [profile, user])
|
||||
await fixture.pool.query("INSERT INTO projects(id,tenant,name,profiles) VALUES (1,1,'Project',ARRAY[$1]::uuid[]),(2,2,'Other tenant','{}')", [profile])
|
||||
app.decorate("db", fixture.db)
|
||||
app.addHook("preHandler", async (req: any) => {
|
||||
req.user = { tenant_id: 1, user_id: user, is_admin: req.headers["x-admin"] === "true" }
|
||||
req.hasPermission = (permission: string) => permission === "organisation.projects.write" && req.headers["x-manager"] === "true"
|
||||
})
|
||||
await app.register(communicationRoutes)
|
||||
await app.register(resourceRoutes)
|
||||
const update = (chatEnabled: unknown, headers = { "x-manager": "true" }) => app.inject({ method: "PUT", url: "/resource/projects/1", headers, payload: { chatEnabled } })
|
||||
const provision = await app.inject({ method: "POST", url: "/communication/chat/project-rooms/1/provision" })
|
||||
assert.equal(provision.statusCode, 200, provision.body)
|
||||
const roomId = provision.json().id
|
||||
await fixture.pool.query("INSERT INTO communication_messages(tenant_id,room_id,author_user_id,body) VALUES (1,$1,$2,'Preserved history')", [roomId, user])
|
||||
assert.equal((await update(false, { "x-manager": "false" })).statusCode, 403)
|
||||
assert.equal((await update("false")).statusCode, 400)
|
||||
assert.equal((await app.inject({ method: "PUT", url: "/resource/projects/2", headers: { "x-manager": "true" }, payload: { chatEnabled: false } })).statusCode, 404)
|
||||
assert.equal((await update(false)).statusCode, 200)
|
||||
assert.deepEqual((await app.inject("/communication/chat/project-rooms")).json().rooms, [])
|
||||
assert.equal((await app.inject({ method: "POST", url: "/communication/chat/project-rooms/1/provision" })).statusCode, 404)
|
||||
for (const suffix of ["messages", "sync", "members"]) {
|
||||
assert.equal((await app.inject(`/communication/chat/rooms/project_1/${suffix}`)).statusCode, 404)
|
||||
assert.equal((await app.inject({ url: `/communication/chat/rooms/project_1/${suffix}`, headers: { "x-admin": "true" } })).statusCode, 404)
|
||||
}
|
||||
for (const suffix of ["messages", "read"]) assert.equal((await app.inject({ method: "POST", url: `/communication/chat/rooms/project_1/${suffix}`, payload: { text: "Rejected", messageId: 1 } })).statusCode, 404)
|
||||
assert.deepEqual((await app.inject("/communication/chat/unread")).json().rooms, {})
|
||||
assert.equal((await update(true, { "x-manager": "false" })).statusCode, 403)
|
||||
assert.equal((await update(true)).statusCode, 200)
|
||||
const history = await app.inject("/communication/chat/rooms/project_1/messages")
|
||||
assert.equal(history.statusCode, 200, history.body)
|
||||
assert.deepEqual(history.json().messages.map(message => message.body), ["Preserved history"])
|
||||
assert.equal((await app.inject("/communication/chat/project-rooms")).json().rooms.length, 1)
|
||||
const create = await app.inject({ method: "POST", url: "/resource/projects", payload: { id: 3, name: "Disabled", projectNumber: "P-3", chatEnabled: false } })
|
||||
assert.equal(create.statusCode, 403)
|
||||
} finally { await app.close(); await fixture.close() }
|
||||
})
|
||||
54
backend/tests/collaborationConfig.test.ts
Normal file
54
backend/tests/collaborationConfig.test.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
import assert from "node:assert/strict"
|
||||
import test from "node:test"
|
||||
import { collaborationConfig } from "../src/modules/collaboration/config"
|
||||
|
||||
const deployment = { API_BASE_URL: "https://fedeo.example/backend", ENCRYPTION_KEY: "a".repeat(64) }
|
||||
|
||||
test("existing HTTPS deployment enables federation without additional environment values", () => {
|
||||
const config = collaborationConfig(deployment)
|
||||
assert.equal(config.enabled, true)
|
||||
assert.equal(config.apiUrl, deployment.API_BASE_URL)
|
||||
assert.equal(config.publicUrl, "https://fedeo.example")
|
||||
assert.equal(config.disabledReason, undefined)
|
||||
assert.equal(collaborationConfig({ ...deployment, FEDEO_FEDERATION_ENABLED: "auto", FEDEO_FEDERATION_URL: "", FEDEO_PUBLIC_URL: "" }).enabled, true)
|
||||
})
|
||||
|
||||
test("custom API paths are retained and instance addresses are canonicalized", () => {
|
||||
const config = collaborationConfig({ ...deployment, API_BASE_URL: "https://FEDEO.example:443/application/api/" })
|
||||
assert.equal(config.apiUrl, "https://fedeo.example/application/api")
|
||||
assert.equal(config.publicUrl, "https://fedeo.example")
|
||||
assert.equal(config.enabled, true)
|
||||
})
|
||||
|
||||
test("explicit opt-out stays disabled even on a correctly configured deployment", () => {
|
||||
const config = collaborationConfig({ ...deployment, FEDEO_FEDERATION_ENABLED: "false" })
|
||||
assert.equal(config.enabled, false)
|
||||
assert.match(config.disabledReason!, /Betreiber deaktiviert/)
|
||||
})
|
||||
|
||||
test("optional gateway override does not move guest links away from the web application", () => {
|
||||
const config = collaborationConfig({ ...deployment, FEDEO_FEDERATION_URL: "https://gateway.example/federation-api/" })
|
||||
assert.equal(config.apiUrl, "https://gateway.example/federation-api")
|
||||
assert.equal(config.publicUrl, "https://fedeo.example")
|
||||
assert.equal(collaborationConfig({ ...deployment, FEDEO_PUBLIC_URL: "https://portal.example/app/" }).publicUrl, "https://portal.example/app")
|
||||
})
|
||||
|
||||
test("local and incomplete deployments keep local collaboration available without federation", () => {
|
||||
for (const API_BASE_URL of [undefined, "", "invalid", "http://localhost:3100", "https://fedeo.example:8443/backend", "https://user:password@fedeo.example/backend"]) {
|
||||
const config = collaborationConfig({ ...deployment, API_BASE_URL })
|
||||
assert.equal(config.enabled, false, API_BASE_URL)
|
||||
assert.match(config.disabledReason!, /HTTPS-API_BASE_URL/)
|
||||
}
|
||||
for (const ENCRYPTION_KEY of [undefined, "", "invalid", "x".repeat(64)]) {
|
||||
const config = collaborationConfig({ ...deployment, ENCRYPTION_KEY })
|
||||
assert.equal(config.enabled, false)
|
||||
assert.match(config.disabledReason!, /ENCRYPTION_KEY/)
|
||||
}
|
||||
})
|
||||
|
||||
test("forced activation reports invalid configuration instead of silently ignoring it", () => {
|
||||
assert.throws(() => collaborationConfig({ ...deployment, FEDEO_FEDERATION_ENABLED: "true", API_BASE_URL: "http://localhost" }), /HTTPS/)
|
||||
assert.throws(() => collaborationConfig({ ...deployment, FEDEO_FEDERATION_ENABLED: "true", ENCRYPTION_KEY: "invalid" }), /ENCRYPTION_KEY/)
|
||||
assert.throws(() => collaborationConfig({ ...deployment, FEDEO_FEDERATION_ENABLED: "typo" }), /auto, true oder false/)
|
||||
assert.equal(collaborationConfig({ ...deployment, FEDEO_FEDERATION_ENABLED: "true" }).enabled, true)
|
||||
})
|
||||
@@ -25,7 +25,7 @@ export async function collaborationDatabase(migrations: string[] = []) {
|
||||
let suffix = column.primary ? " PRIMARY KEY" : ""
|
||||
if (column.name === "id" && column.getSQLType() === "uuid") suffix += " DEFAULT gen_random_uuid()"
|
||||
if (column.columnType === "PgTimestamp") suffix += " DEFAULT now()"
|
||||
if (column.getSQLType() === "boolean") suffix += " DEFAULT false"
|
||||
if (column.getSQLType() === "boolean") suffix += ` DEFAULT ${column.default === true ? "true" : "false"}`
|
||||
return `"${column.name}" ${column.getSQLType()}${suffix}`
|
||||
})
|
||||
await pool.query(`CREATE TABLE "${getTableName(table)}" (${columns.join(",")})`)
|
||||
|
||||
@@ -527,6 +527,61 @@ test("scanner inbox integration: migration, persistence, isolation, retries and
|
||||
assert.equal((await fileInto(id)).statusCode, 404)
|
||||
await pool.query("UPDATE files SET archived=false WHERE id=$1", [id])
|
||||
})
|
||||
await t.test("archiving is tenant scoped, preserves the original and invalidates an ongoing analysis", async () => {
|
||||
assert.equal((await send("archive.pdf")).statusCode, 201)
|
||||
const id = (await service.list(1, 50, 0, "archive.pdf")).documents[0].id
|
||||
const archive = (fileId = id, headers = {}) => app.inject({ method: "POST", url: `/api/document-inbox/${fileId}/archive`, headers })
|
||||
assert.equal((await archive(id, { "x-test-tenant": "2" })).statusCode, 404)
|
||||
assert.equal((await archive(randomUUID())).statusCode, 404)
|
||||
assert.equal((await archive("invalid")).statusCode, 400)
|
||||
const filedId = (await pool.query("SELECT file_id FROM scanner_inbox_documents WHERE tenant_id=1 AND remote_filename='scan.pdf'")).rows[0].file_id
|
||||
assert.equal((await archive(filedId)).statusCode, 409)
|
||||
await pool.query("UPDATE tenants SET locked='maintenance_tenant' WHERE id=1")
|
||||
assert.equal((await archive()).statusCode, 423)
|
||||
await pool.query("UPDATE tenants SET locked=null WHERE id=1")
|
||||
await pool.query("INSERT INTO auth_profiles (tenant_id, user_id, customer_for_portal) VALUES (1, $1, 123)", [userId])
|
||||
assert.equal((await archive()).statusCode, 403)
|
||||
await pool.query("DELETE FROM auth_profiles")
|
||||
const before = (await pool.query("SELECT * FROM files WHERE id=$1", [id])).rows[0]
|
||||
const countBefore = (await service.openCount(1)).total
|
||||
const storedBefore = stored.size
|
||||
// Run this document first, then archive it while its provider response is still pending.
|
||||
await pool.query("UPDATE scanner_inbox_documents SET received_at=now()-interval '1 day' WHERE file_id=$1", [id])
|
||||
let finish!: () => void
|
||||
analysisGate = new Promise(resolve => { finish = resolve })
|
||||
const started = new Promise<void>(resolve => { analysisStarted = resolve })
|
||||
const pending = service.processNextSuggestion()
|
||||
await started
|
||||
assert.equal(analyses.at(-1).document.name, "archive.pdf")
|
||||
const result = await archive(id, { "x-test-admin": "false" })
|
||||
finish()
|
||||
await pending
|
||||
analysisGate = undefined
|
||||
analysisStarted = undefined
|
||||
assert.equal(result.statusCode, 200, result.body)
|
||||
assert.deepEqual(result.json(), { id, archived: true })
|
||||
const row = (await pool.query("SELECT * FROM files WHERE id=$1", [id])).rows[0]
|
||||
assert.equal(row.archived, true)
|
||||
assert.equal(row.updated_by, userId)
|
||||
assert.ok(row.updated_at)
|
||||
assert.equal(row.path, before.path)
|
||||
assert.equal(row.folder, before.folder)
|
||||
assert.equal(row.type, before.type)
|
||||
assert.deepEqual(stored.get(row.path), pdf)
|
||||
const receipt = (await pool.query("SELECT filed_at, suggestion_claim, suggestion_status FROM scanner_inbox_documents WHERE file_id=$1", [id])).rows[0]
|
||||
assert.deepEqual(receipt, { filed_at: null, suggestion_claim: null, suggestion_status: "pending" })
|
||||
assert.equal((await service.list(1, 50, 0, "archive.pdf")).total, 0)
|
||||
assert.equal((await service.openCount(1)).total, countBefore - 1)
|
||||
assert.equal((await suggest(id)).statusCode, 404)
|
||||
assert.equal((await fileInto(id)).statusCode, 404)
|
||||
assert.equal((await archive()).statusCode, 200, "repeated requests remain successful")
|
||||
assert.equal((await pool.query("SELECT updated_at FROM files WHERE id=$1", [id])).rows[0].updated_at.getTime(), row.updated_at.getTime())
|
||||
assert.equal((await send("archive.pdf")).statusCode, 204)
|
||||
assert.equal((await service.list(1, 50, 0, "archive.pdf")).total, 0)
|
||||
assert.equal(stored.size, storedBefore)
|
||||
while (await service.processNextSuggestion()) { /* drain the remaining fixtures */ }
|
||||
assert.equal(analyses.filter(item => item.document.name === "archive.pdf").length, 1)
|
||||
})
|
||||
await t.test("maintenance, portal access and administrator-only settings are enforced", async () => {
|
||||
await pool.query("UPDATE tenants SET locked='maintenance_tenant' WHERE id=1")
|
||||
assert.equal((await send("maintenance.pdf")).statusCode, 423)
|
||||
|
||||
@@ -125,7 +125,7 @@ services:
|
||||
API_BASE_URL: ${API_BASE_URL}
|
||||
FEDEO_PUBLIC_URL: ${FEDEO_PUBLIC_URL:-}
|
||||
FEDEO_FEDERATION_URL: ${FEDEO_FEDERATION_URL:-}
|
||||
FEDEO_FEDERATION_ENABLED: ${FEDEO_FEDERATION_ENABLED:-false}
|
||||
FEDEO_FEDERATION_ENABLED: ${FEDEO_FEDERATION_ENABLED:-auto}
|
||||
GOCARDLESS_BASE_URL: ${GOCARDLESS_BASE_URL}
|
||||
GOCARDLESS_SECRET_ID: ${GOCARDLESS_SECRET_ID}
|
||||
GOCARDLESS_SECRET_KEY: ${GOCARDLESS_SECRET_KEY}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Konzept: Föderierte Chats und externe Projektteilnehmer
|
||||
|
||||
Stand: 30. September 2026. Das ursprüngliche Zielbild basiert auf Commit `df48c976`. Die Schritte 0, 1a, 1b und ein föderierter Web-Pilot aus Schritt 2 sind inzwischen implementiert (`21fe4723`, `ea641bb4`, `7b5696ed`). Die folgenden Architekturkapitel enthalten weiterhin spätere Ausbaustufen; den tatsächlichen Lieferumfang, die Einrichtung und verbleibende Grenzen beschreibt Abschnitt 15. Es wurden keine produktiven Instanzen verändert oder echten Einladungen versendet.
|
||||
Stand: 2. Oktober 2026. Das ursprüngliche Zielbild basiert auf Commit `df48c976`. Die Schritte 0, 1a, 1b und ein föderierter Web-Pilot aus Schritt 2 sind inzwischen implementiert (`21fe4723`, `ea641bb4`, `7b5696ed`). Die folgenden Architekturkapitel enthalten weiterhin spätere Ausbaustufen; den tatsächlichen Lieferumfang, die Einrichtung und verbleibende Grenzen beschreibt Abschnitt 15. Es wurden keine produktiven Instanzen verändert oder echten Einladungen versendet.
|
||||
|
||||
## 1. Empfehlung
|
||||
|
||||
@@ -285,6 +285,10 @@ Als erster nutzbarer Meilenstein wird **ein abgegrenzter Projekt-Unterraum mit e
|
||||
|
||||
Unter **Kommunikation → Zusammenarbeit** können interne Teilnehmer ihre eigenen Unterräume und Einladungen öffnen. Projektverantwortliche mit `organisation.projects.write` beziehungsweise Administratoren können Unterräume verwalten und freie Partnerchats anlegen. Der Projektkopf verlinkt ebenfalls auf die Zusammenarbeit. Die Verwaltung eines Raums berechtigt weiterhin nicht zum Lesen seiner Nachrichten; nur der Ersteller wird bei der Anlage automatisch Teilnehmer.
|
||||
|
||||
Unter **Kommunikation → Chat** erscheinen diese Unterräume ebenfalls in der Raumgruppe **Zusammenarbeit**, einschließlich instanzübergreifender Räume und Ungelesen-Zähler. Einladungen lassen sich dort direkt annehmen oder ablehnen; nach der Annahme öffnet sich der Raum. Nachrichten, Teilnehmer und ausdrücklich freigegebene Projektinformationen werden direkt im normalen Chat angezeigt. **Details und Freigaben** öffnet die bestehende Verwaltungsansicht für den ausgewählten Raum; **Im Chat öffnen** führt zurück. Sichtbar sind ausschließlich Räume mit eigener Teilnahme, keine lediglich verwaltbaren Räume. Interne Chaträume und Unterräume behalten ihre getrennten Berechtigungsprüfungen.
|
||||
|
||||
Die Chatansicht nutzt die volle verfügbare Fläche. Über das Augensymbol lassen sich beliebige Räume persönlich ausblenden und unter **Ausgeblendete Räume** wieder einblenden. Diese Auswahl wird pro Benutzer und Mandant gespeichert und bleibt auf anderen Geräten erhalten; Teilnahme, Nachrichten und Benachrichtigungseinstellungen werden dadurch nicht geändert. Unter **Projekt → Bearbeiten → Projektchat aktiviert** können Projektverantwortliche den internen Projektchat für alle Teilnehmer deaktivieren. Er verschwindet aus der Chatliste und ist auch über direkte Aufrufe nicht mehr les- oder beschreibbar. Beim erneuten Aktivieren bleibt der bisherige Verlauf erhalten. Bestehende und neue Projekte starten mit aktiviertem Projektchat. Separat freigegebene Unterräume bleiben unabhängig davon verwaltbar.
|
||||
|
||||
Einladungen unterstützen eigene Mitarbeiter, persönliche FEDEO-Kontaktadressen und Gäste ohne FEDEO-Konto. Eine Kontaktadresse bezeichnet immer genau einen Benutzer in einem Heimatmandanten. Sie lässt sich in der Zusammenarbeit kopieren. Kontakte anderer Mandanten derselben Instanz benötigen keinen Server-Server-Transport. Fremde Instanzen müssen auf beiden Seiten im jeweiligen Mandanten unter **Partnerinstanzen** freigegeben sein. Beim Empfänger erscheint ein Angebot, das ausdrücklich angenommen oder abgelehnt wird.
|
||||
|
||||
Gäste erhalten ausschließlich einen Projekt-Unterraum. Der Link öffnet `/guest`; ein achtstelliger, zehn Minuten gültiger Einmalcode wird an die eingeladene Adresse geschickt. Nach fünf falschen Versuchen ist der Code gesperrt. Die eigene Gastsitzung gilt zwölf Stunden und wird nicht als reguläres FEDEO-Token akzeptiert. Für spätere Anmeldungen bietet die Gastoberfläche eine als Lesezeichen speicherbare Adresse mit öffentlicher Workspace-ID an. Ohne gewähltes Ablaufdatum gilt die Teilnahme eines Gasts 30 Tage. Der Einladungslink allein erlaubt keinen Inhaltszugriff.
|
||||
@@ -297,13 +301,15 @@ Bei einem vorübergehend nicht erreichbaren Eigentümer sind bereits geladene Na
|
||||
|
||||
### Einrichtung
|
||||
|
||||
1. Vor dem Backendstart die additiven Migrationen `0075_project_collaboration.sql` und `0076_collaboration_federation.sql` über den bestehenden Migrationslauf einspielen. Der Selfhost-Container führt standardmäßig `npm run migrate` aus. Bestehende interne Chats bleiben getrennt; kein vorhandener Chat wird automatisch freigegeben.
|
||||
2. `FEDEO_PUBLIC_URL` auf die öffentliche Webadresse setzen. Für Gastcodes und optional versendete Einladungs-E-Mails muss der bestehende SMTP-Versand funktionieren. `ENCRYPTION_KEY` muss wie für die übrige Backend-Verschlüsselung ein stabiler 64-stelliger Hex-Schlüssel sein.
|
||||
3. Für den instanzübergreifenden Pilotbetrieb `FEDEO_FEDERATION_URL` auf die kanonische öffentliche HTTPS-API-Adresse setzen, einschließlich des Reverse-Proxy-Präfixes, etwa `https://fedeo.example/backend`. Anschließend `FEDEO_FEDERATION_ENABLED=true` setzen. Die Variablen sind in `.env.example` und `docker-compose.selfhost.yml` aufgenommen. Föderation ist standardmäßig deaktiviert; lokale Unterräume und Gäste funktionieren unabhängig davon.
|
||||
1. Vor dem Backendstart die additiven Migrationen `0075_project_collaboration.sql`, `0076_collaboration_federation.sql` und `0078_chat_visibility.sql` über den bestehenden Migrationslauf einspielen. Der Selfhost-Container führt standardmäßig `npm run migrate` aus. Bestehende interne Chats bleiben getrennt; kein vorhandener Chat wird automatisch freigegeben.
|
||||
2. Die vorhandene `API_BASE_URL` wird als Föderationsadresse verwendet, einschließlich des Reverse-Proxy-Präfixes, etwa `https://fedeo.example/backend`. Gastlinks werden aus deren Ursprung `https://fedeo.example` abgeleitet. Zusätzliche URL-Variablen sind im Standardbetrieb nicht nötig. Für Gastcodes und optional versendete Einladungs-E-Mails muss der bestehende SMTP-Versand funktionieren. Den vorhandenen `ENCRYPTION_KEY` beibehalten; er muss ein stabiler 64-stelliger Hex-Schlüssel sein.
|
||||
3. Der Standard ist jetzt `FEDEO_FEDERATION_ENABLED=auto`, auch wenn die Variable nicht gesetzt ist. Mit gültiger HTTPS-API-Adresse auf Port 443 und gültigem Verschlüsselungsschlüssel wird Föderation automatisch bereitgestellt. Lokale HTTP-Entwicklungsumgebungen oder unvollständige Konfigurationen bleiben ohne Föderation startfähig; die Partnerverwaltung nennt den fehlenden Konfigurationswert. `false` schaltet Föderation ausdrücklich ab. `true` erzwingt die Aktivierung und meldet eine ungültige Konfiguration bereits beim Start. Nur bei abweichender Infrastruktur `FEDEO_FEDERATION_URL` oder `FEDEO_PUBLIC_URL` setzen; beide überschreiben die automatisch abgeleiteten Werte. Ein separates Föderationsgateway verändert die Gast-Webadresse nicht automatisch.
|
||||
4. Der Proxy muss `GET <API-Adresse>/.well-known/fedeo-federation` und `POST <API-Adresse>/federation/v1/rpc` durchreichen und darf JSON-Body oder Signaturheader nicht verändern. Externe Ziele benötigen öffentlich auflösbare HTTPS-Adressen auf Port 443. Private/reservierte IPv4- und IPv6-Ziele sowie Weiterleitungen werden abgewiesen; die geprüfte DNS-Adresse wird für die TLS-Verbindung festgehalten.
|
||||
5. In beiden beteiligten Mandanten die jeweils andere API-Adresse unter **Partnerinstanzen** freigeben. Discovery ermittelt Instanz-ID und öffentlichen Schlüssel über HTTPS. Die erste Freigabe pinnt diese Identität. Ein später abweichender Schlüssel wird abgelehnt und braucht eine gesonderte Betreiberprüfung; eine automatische Schlüsselrotation ist noch nicht vorhanden.
|
||||
6. Persönliche Kontaktadresse des Empfängers verwenden, gezielt in einen Unterraum einladen und beim Empfänger annehmen. Für einen ersten Pilotversuch anschließend Rechteänderung, Widerruf und eine vorübergehend unterbrochene Verbindung prüfen.
|
||||
|
||||
Der normale Selfhost-Updater übernimmt die Compose-Datei und Migrationen aus dem Zielrelease; ein manuelles Nachtragen der Föderationsvariablen ist bei verwalteten Installationen nicht erforderlich. Die vorhandene `.env` wird bis auf die Release-Version beibehalten. Eine darin oder in der Override-Datei gesetzte Abschaltung bleibt wirksam. Wurde `FEDEO_FEDERATION_ENABLED=false` aus der früheren Beispielkonfiguration übernommen, muss dieser Wert einmal entfernt oder auf `auto` gesetzt werden, wenn Föderation gewünscht ist. Die automatische Bereitstellung gibt keine Partner oder vorhandenen Chats frei; dafür bleiben die gegenseitige Mandantenfreigabe und explizite Einladung erforderlich.
|
||||
|
||||
Das feste Signaturprofil verwendet Ed25519 mit HTTP Message Signatures und Content-Digest. Signiert werden Methode, vollständige Zieladresse, Inhaltstyp, Inhaltsdigest und Herkunft; Zeitfenster und gespeicherte Nonces verhindern Replay. Das RPC-Protokoll ist Version 1 und ausschließlich für diese FEDEO-Implementierung bestimmt. Es ersetzt weder Matrix-Kompatibilität noch Ende-zu-Ende-Verschlüsselung.
|
||||
|
||||
### Speicherung, Betrieb und Wiederaufnahme
|
||||
@@ -329,3 +335,5 @@ COLLABORATION_TEST_DATABASE_URL=postgresql://USER:PASSWORD@127.0.0.1:PORT/collab
|
||||
Jeder Datenbanktest erzeugt ein eigenes Schema und räumt es anschließend auf. Ohne gesetzte Testadresse werden die Datenbanktests bewusst übersprungen; der Datenbankname wird vor dem Anlegen geprüft. Backend-Typprüfung und Nuxt-Produktionsbuild waren erfolgreich, die abschließenden Vue-Komponenten lassen sich kompilieren. Eine visuelle Browserabnahme war in der Arbeitsumgebung mangels verbundenem Browser nicht möglich.
|
||||
|
||||
Die nächste Ausbaustufe aus Schritt 3 umfasst insbesondere native Mobile-Parität, Push-Benachrichtigungen, Moderation, feinere Kontingente sowie Schlüsselrotation und abgestimmte Wiederherstellung. Dateifreigaben, Aufgabenfreigaben und E2EE sind weiterhin Erweiterungen. Der hier implementierte Stand ist ein nutzbarer Web-Pilot für Chats und ausdrücklich begrenzte Projektzusammenarbeit; ein produktiver Rollout ist damit noch nicht erfolgt.
|
||||
|
||||
Die automatische Einrichtung wurde zusätzlich mit sechs Konfigurationstests und 58 Updater-Tests geprüft. Die Update-Regressionen verwenden echte Compose-Auswertung mit simuliertem Containerbetrieb und prüfen sowohl Installationen ohne Föderationsvariablen als auch den Erhalt einer ausdrücklichen Abschaltung und eigener URL-Vorgaben.
|
||||
|
||||
@@ -12,7 +12,13 @@ Unter **Organisation → Dokumentenablage** erscheinen noch nicht abgelegte Scan
|
||||
|
||||
Nur aktive Ordner, Typen und Zuordnungsziele desselben Mandanten sind zulässig. Mitarbeiter müssen aktiv und interne Benutzer sein. Bei einem Fehler bleibt das Dokument im Eingang; auch die übrigen Änderungen werden nicht teilweise gespeichert. Ein erneuter Scanner-Upload mit demselben Namen und Inhalt bestätigt weiterhin den ursprünglichen Empfang, ohne einen neuen Eingangseintrag oder Analyseauftrag anzulegen.
|
||||
|
||||
### KI-Vorschläge
|
||||
## Archivieren
|
||||
|
||||
**Archivieren** steht sowohl in jeder Listenzeile als auch im Vorschaufenster zur Verfügung. Nach Bestätigung wird die bestehende Datei als archiviert markiert, ohne sie zu löschen. Ordner und Dokumenttyp müssen dafür nicht ausgewählt sein; ungespeicherte Zuordnungen aus der Vorschau werden nicht übernommen. Das Dokument verschwindet aus der Ablage und der Menüzähler wird sofort aktualisiert. Bei einem Fehler bleibt es sichtbar und der Vorgang kann erneut versucht werden.
|
||||
|
||||
Das Original und sein Empfangseintrag bleiben erhalten. Eine identische Wiederholung durch den Scanner aktiviert die Datei nicht erneut. Wartende KI-Aufträge werden für archivierte Dateien übersprungen und Ergebnisse bereits laufender Analysen verworfen. Die Änderung hält Zeitpunkt und Benutzer fest. Bereits unter Dateien abgelegte Dokumente können nicht mehr über die Ablage archiviert werden.
|
||||
|
||||
## KI-Vorschläge
|
||||
|
||||
Die Analyse nutzt die bestehende zentrale FEDEO-KI-Anbindung oder den konfigurierten `OPENAI_API_KEY`, entsprechend den E-Mail-Zuordnungsvorschlägen. Die Antwort verwendet [Structured Outputs](https://developers.openai.com/api/docs/guides/structured-outputs) und `store: false`. Dokumentinhalt, Dateiname und Kandidatennamen gelten als Daten, nicht als Anweisungen. Das Backend prüft vorgeschlagene IDs und verpflichtende Ordnertypen gegen die aktiven Stammdaten des Mandanten, auch noch einmal nach der Analyse. Der Scanner-Zugang kann diese API nicht nutzen.
|
||||
|
||||
@@ -49,6 +55,7 @@ Nach der Dateinamenprüfung sendet der ES-580W zunächst einen leeren `PUT` mit
|
||||
- Die Browser-API unter `/api/document-inbox` erfordert die normale FEDEO-Anmeldung und einen aktiven Mandanten. Portalbenutzer sind ausgeschlossen. Scanner-Zugänge verwalten nur Administratoren. Die Originale sind außerdem über die bestehende Dateiverwaltung zugänglich.
|
||||
- `GET /api/document-inbox/count` liefert `{ "total": 3 }` für den aktiven Mandanten. `GET /api/document-inbox/filing-options` liefert verfügbare Ordner, Typen und `assignmentKinds`. `GET /api/document-inbox/assignment-options?kind=project&search=Beispiel` liefert bis zu 100 passende Ziele mit `id` und `name`; `GET /api/document-inbox/:id/assignments` die bereits bestehenden Verknüpfungen des Dokuments.
|
||||
- `POST /api/document-inbox/:id/file` mit JSON `{ "folder": "<Ordner-UUID oder null>", "type": "<Dateityp-UUID>", "assignments": { "project": 123, "customer": 456 } }` klassifiziert das Original, speichert die optionalen Verknüpfungen und markiert den Eingang atomar als abgelegt. Weggelassene Zuordnungen bleiben erhalten; JSON-`null` entfernt eine vorhandene Zuordnung. Die Schlüssel entsprechen den Dateifeldern; `check` und `authProfile` verwenden UUIDs, die übrigen Bereiche numerische IDs. Für die Hauptebene ist `folder` als JSON-`null` zu senden. Ein bereits abgelegtes Dokument ergibt `409`; zwischenzeitlich archivierte oder fremde Ziele werden abgewiesen. Dateiänderungen enthalten Zeitpunkt und Benutzer.
|
||||
- `POST /api/document-inbox/:id/archive` archiviert eine Eingangsdatei des aktiven Mandanten ohne weitere Pflichtangaben und antwortet mit `{ "id": "<Datei-UUID>", "archived": true }`. Wiederholte Aufrufe sind erfolgreich, ohne den ursprünglichen Archivierungszeitpunkt zu ändern. Bereits abgelegte Dokumente ergeben `409`, fremde oder nicht im Eingang registrierte Dateien `404` und Mandantenwartung `423`. Archivieren und Ablegen sind gegeneinander abgesichert.
|
||||
- `GET /api/document-inbox/:id/suggestion` liest den gespeicherten Status `pending`, `processing`, `ready` oder `failed` und liefert bei Erfolg beispielsweise `{ "status": "ready", "suggestion": { "folderId": "<UUID oder null>", "typeId": "<UUID>", "confidence": "high|medium", "reason": "…" } }`. Ohne passende Zuordnung ist `suggestion` gleich `null` und `message` erklärt den Grund. `POST /api/document-inbox/:id/suggestion` fordert eine erneute Vorbereitung an und antwortet mit `202` und demselben Statusformat, ohne auf die Analyse zu warten. Ein bereits wartender oder laufender Auftrag wird nicht dupliziert. Nur offene, nicht archivierte Dokumente des aktiven Mandanten sind zugänglich. Diese Anfragen legen nichts ab; dafür bleibt der separate `/file`-Aufruf erforderlich.
|
||||
|
||||
## Lokaler Funktionstest
|
||||
|
||||
@@ -13,6 +13,8 @@
|
||||
|
||||
Der Updater verweigert externe Datenbanken, externen S3-/Seafile-Speicher, zusätzliche Dienste, Compose-Profile, geänderte Datenpfade und PostgreSQL-Imagewechsel. Dafür braucht es zunächst passende Backup-/Migrationsadapter. Eigene Einstellungen innerhalb der unterstützten Dienste können in `docker-compose.override.yml` **oder** `docker-compose.override.yaml` bleiben; der Updater verwendet diese Datei bei jedem Compose-Aufruf. Änderungen an dieser Override-Datei werden nicht überschrieben.
|
||||
|
||||
Für die Chat-Föderation übernimmt der Updater die neuen Backend-Einträge aus der Release-Compose-Datei automatisch. Zusätzliche Einträge in der bestehenden `.env` sind nicht nötig: Die Föderationsadresse folgt `API_BASE_URL`, Gastlinks verwenden deren Ursprung. Der Standard `FEDEO_FEDERATION_ENABLED=auto` aktiviert die Funktion bei gültiger HTTPS-Adresse auf Port 443 und gültigem `ENCRYPTION_KEY`. Ein vorhandenes `false` und eigene URL-Vorgaben bleiben erhalten. Partnerfreigaben und Einladungen werden weiterhin ausdrücklich je Mandant erteilt. Details stehen in der [Föderationsanleitung](chat-foederation-konzept.md#15-implementierter-stand-und-pilotbetrieb).
|
||||
|
||||
Eine gezielte Ausnahme ist die Stilllegung des **entfernten alten Matrix-Stacks**: `matrix-db`, `matrix-synapse`, `matrix-redis`, `matrix-element`, `matrix-livekit`, `matrix-rtc-jwt`, `matrix-turn` und `matrix-well-known` dürfen in der bestehenden Konfiguration vorkommen. Die Zielkonfiguration muss ausschließlich die FEDEO-Dienste des jeweiligen Speicherproviders enthalten, auch nach Zusammenführung mit einer Override-Datei. Matrix wird nicht in den neuen Stack übernommen. Bereits stillgelegte Matrix-Container bleiben erhalten und ihre lokalen Bind-Verzeichnisse werden weiter gesichert. Andere Zusatzdienste bleiben gesperrt; die Fehlermeldung nennt die konkreten Abweichungen. Ein Abbruch mit `mutationStarted: false` und `recoveryRequired: false` benötigt keine Wiederherstellung und keinen `resolve`-Aufruf.
|
||||
|
||||
Für diesen Übergang müssen die Matrix-Daten lokal unter `matrix/` liegen, insbesondere `matrix/postgres` und `matrix/synapse`; symbolische Links, andere konfigurierte Datenpfade, benannte Volumes und spezielle Compose-Konfigurationen benötigen eine manuelle Stilllegung. Die tatsächlichen Bind-Mounts der alten Container müssen zur Compose-Datei passen. Der Plan nennt `retiredServices` und `retainedDataPaths` und berücksichtigt den zusätzlichen Backup-Platz. Alle Matrix-Container werden vor dem Backup gestoppt. Das komplette lokale `matrix/`-Verzeichnis wird bei gestoppter Matrix-Datenbank in `files.tar` gesichert. Erst nach erfolgreichem Backup setzt der Updater die Neustartrichtlinie der alten Matrix-Container auf `no`, damit sie auch nach einem Host-Neustart stillgelegt bleiben. Er löscht weder diese Container noch ihre Daten oder Volumes. Image-seitig angelegte anonyme Volumes und schreibbare Container-Schichten bleiben an den alten Containern erhalten; sie sind nicht Bestandteil von `files.tar`. Die alten Container daher für die Wiederherstellung behalten und nicht mit `--remove-orphans` oder einem Docker-Prune entfernen.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<script setup>
|
||||
const props = defineProps({ roomId: { type: String, required: true }, api: { type: Function, required: true }, base: { type: String, default: '/api/collaboration' } })
|
||||
const props = defineProps({ roomId: { type: String, required: true }, api: { type: Function, required: true }, base: { type: String, default: '/api/collaboration' }, embedded: { type: Boolean, default: false } })
|
||||
const emit = defineEmits(['changed', 'unauthorized'])
|
||||
const room = ref(null), messages = ref([]), members = ref([]), draft = ref(''), error = ref('')
|
||||
const loading = ref(false), sending = ref(false), olderLoading = ref(false), hasMore = ref(false), viewport = ref(null)
|
||||
@@ -95,9 +95,9 @@ onBeforeUnmount(() => { ++generation; clearInterval(timer) })
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="flex min-h-[32rem] min-w-0 flex-col rounded-xl border border-gray-200 bg-white dark:border-gray-700 dark:bg-gray-900">
|
||||
<section class="flex min-w-0 flex-col bg-white dark:bg-gray-900" :class="embedded ? 'min-h-0 overflow-hidden' : 'min-h-[32rem] rounded-xl border border-gray-200 dark:border-gray-700'">
|
||||
<header class="border-b border-gray-200 p-4 dark:border-gray-700">
|
||||
<h2 class="text-lg font-semibold">{{ room?.name || 'Unterraum' }}</h2>
|
||||
<div class="flex flex-wrap items-center justify-between gap-2"><h2 class="text-lg font-semibold">{{ room?.name || 'Unterraum' }}</h2><slot name="actions" /></div>
|
||||
<p v-if="room?.topic" class="mt-1 text-sm text-gray-500">{{ room.topic }}</p>
|
||||
<p v-if="members.length" class="mt-2 text-xs text-gray-500">{{ members.map(m => `${m.name}${m.kind === 'guest' ? ' (Gast)' : ''}`).join(' · ') }}</p>
|
||||
</header>
|
||||
@@ -110,7 +110,7 @@ onBeforeUnmount(() => { ++generation; clearInterval(timer) })
|
||||
<p v-if="room.overview.date">Termin: {{ room.overview.date }}</p>
|
||||
<p v-if="room.overview.description" class="mt-1 whitespace-pre-wrap">{{ room.overview.description }}</p>
|
||||
</div>
|
||||
<div ref="viewport" class="max-h-[60vh] min-h-[18rem] flex-1 space-y-3 overflow-y-auto p-4" aria-live="polite">
|
||||
<div ref="viewport" class="flex-1 space-y-3 overflow-y-auto p-4" :class="embedded ? 'min-h-0' : 'max-h-[60vh] min-h-[18rem]'" aria-live="polite">
|
||||
<p v-if="loading" class="text-sm text-gray-500">Nachrichten werden geladen …</p>
|
||||
<button v-if="hasMore" class="block w-full text-center text-sm text-green-700 underline" :disabled="olderLoading" @click="older">{{ olderLoading ? 'Wird geladen …' : 'Ältere Nachrichten laden' }}</button>
|
||||
<p v-if="room && !loading && !messages.length" class="py-12 text-center text-sm text-gray-500">Hier beginnt eure Unterhaltung. Du siehst Nachrichten ab deinem Beitritt.</p>
|
||||
|
||||
@@ -1,219 +1,274 @@
|
||||
<script setup>
|
||||
const toast = useToast()
|
||||
const { $api } = useNuxtApp()
|
||||
const auth = useAuthStore()
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
|
||||
const baseRooms = ref([])
|
||||
const projectRooms = ref([])
|
||||
const directRooms = ref([])
|
||||
const unreadRooms = ref({})
|
||||
const messages = ref([])
|
||||
const members = ref([])
|
||||
const draft = ref("")
|
||||
const activeRoomKey = ref(typeof route.query.room === "string" ? route.query.room : "allgemein")
|
||||
const loading = ref(true)
|
||||
const roomLoading = ref(false)
|
||||
const sending = ref(false)
|
||||
const creating = ref(false)
|
||||
const showRoomForm = ref(false)
|
||||
const messagesViewport = ref(null)
|
||||
const roomForm = reactive({ name: "", key: "", topic: "" })
|
||||
let pollTimer = null
|
||||
let pollBusy = false
|
||||
let syncAfterId = 0
|
||||
|
||||
const normalizeRoomKey = (value) => String(value || "")
|
||||
.toLowerCase()
|
||||
.normalize("NFKD")
|
||||
.replace(/[\u0300-\u036f]/g, "")
|
||||
.replace(/ß/g, "ss")
|
||||
.replace(/[^a-z0-9._=-]+/g, "_")
|
||||
.replace(/_+/g, "_")
|
||||
.replace(/^[._=-]+|[._=-]+$/g, "")
|
||||
const baseRooms = ref([]), projectRooms = ref([]), directRooms = ref([]), collaborationRooms = ref([])
|
||||
const invitations = ref([]), invitationBusy = ref(''), collaborationError = ref(''), listError = ref('')
|
||||
const unreadRooms = ref({}), messages = ref([]), members = ref([]), draft = ref('')
|
||||
const requestedRoom = () => typeof route.query.room === 'string' ? route.query.room : 'allgemein'
|
||||
const activeRoomKey = ref(requestedRoom())
|
||||
const loading = ref(true), roomLoading = ref(false), sending = ref(false), creating = ref(false)
|
||||
const showRoomForm = ref(false), messagesViewport = ref(null)
|
||||
const hiddenRoomKeys = ref([]), showHiddenRooms = ref(false), preferenceBusy = ref(''), preferenceError = ref('')
|
||||
const preferencesReady = ref(false)
|
||||
const roomForm = reactive({ name: '', key: '', topic: '' })
|
||||
const session = computed(() => `${auth.user?.id || auth.user?.user_id || ''}:${auth.activeTenant || ''}`)
|
||||
const hasSession = computed(() => !!auth.user && !!auth.activeTenant)
|
||||
let pollTimer, listTimer, pollBusy = false, mounted = false, disposed = false
|
||||
let scopeVersion = 0, roomVersion = 0, collaborationRequest = 0, nativeListRequest = 0, syncAfterId = 0
|
||||
const currentScope = version => !disposed && version === scopeVersion
|
||||
const selection = () => ({ scope: scopeVersion, version: roomVersion, key: activeRoomKey.value })
|
||||
const currentSelection = request => currentScope(request.scope) && request.version === roomVersion && request.key === activeRoomKey.value
|
||||
const errorMessage = error => error?.data?.message || error?.data?.error || 'Die Anfrage konnte nicht ausgeführt werden.'
|
||||
// Colons cannot occur in normalized internal room keys, so both room types stay unambiguous.
|
||||
const collaborationKey = id => `collaboration:${id}`
|
||||
const nativeEndpoint = (key, suffix = '') => `/api/communication/chat/rooms/${encodeURIComponent(key)}${suffix}`
|
||||
|
||||
const normalizeRoomKey = value => String(value || '')
|
||||
.toLowerCase().normalize('NFKD').replace(/[\u0300-\u036f]/g, '').replace(/ß/g, 'ss')
|
||||
.replace(/[^a-z0-9._=-]+/g, '_').replace(/_+/g, '_').replace(/^[._=-]+|[._=-]+$/g, '')
|
||||
const roomKeyPreview = computed(() => normalizeRoomKey(roomForm.key || roomForm.name))
|
||||
const decoratedRooms = computed(() => [
|
||||
...baseRooms.value.map((room) => ({ ...room, group: "Räume", icon: "i-heroicons-chat-bubble-left-right" })),
|
||||
...projectRooms.value.map((room) => ({ ...room, group: "Projekte", icon: "i-heroicons-briefcase" })),
|
||||
...directRooms.value.map((room) => ({ ...room, group: "Direktnachrichten", icon: "i-heroicons-user-circle" }))
|
||||
].map((room) => ({ ...room, unread: unreadRooms.value[room.key]?.count || 0 })))
|
||||
const groupedRooms = computed(() => ["Räume", "Projekte", "Direktnachrichten"]
|
||||
.map((label) => ({ label, rooms: decoratedRooms.value.filter((room) => room.group === label) }))
|
||||
.filter((group) => group.rooms.length))
|
||||
const activeRoom = computed(() => decoratedRooms.value.find((room) => room.key === activeRoomKey.value) || null)
|
||||
const roomEndpoint = computed(() => `/api/communication/chat/rooms/${encodeURIComponent(activeRoomKey.value)}`)
|
||||
...[
|
||||
...baseRooms.value.map(room => ({ ...room, group: 'Räume', icon: 'i-heroicons-chat-bubble-left-right' })),
|
||||
...projectRooms.value.map(room => ({ ...room, group: 'Projekte', icon: 'i-heroicons-briefcase' })),
|
||||
...directRooms.value.map(room => ({ ...room, group: 'Direktnachrichten', icon: 'i-heroicons-user-circle' }))
|
||||
].map(room => ({ ...room, source: 'internal', unread: unreadRooms.value[room.key]?.count || 0 })),
|
||||
...collaborationRooms.value.map(room => ({ ...room, key: collaborationKey(room.id), source: 'collaboration', exists: true,
|
||||
group: 'Zusammenarbeit', icon: 'i-heroicons-user-group', unread: room.unread || 0 }))
|
||||
])
|
||||
const visibleRooms = computed(() => decoratedRooms.value.filter(room => !hiddenRoomKeys.value.includes(room.key)))
|
||||
const hiddenRooms = computed(() => decoratedRooms.value.filter(room => hiddenRoomKeys.value.includes(room.key)))
|
||||
const groupedRooms = computed(() => ['Räume', 'Projekte', 'Direktnachrichten', 'Zusammenarbeit']
|
||||
.map(label => ({ label, rooms: visibleRooms.value.filter(room => room.group === label) }))
|
||||
.filter(group => group.rooms.length))
|
||||
const activeRoom = computed(() => visibleRooms.value.find(room => room.key === activeRoomKey.value) || null)
|
||||
const isCollaboration = computed(() => activeRoom.value?.source === 'collaboration')
|
||||
const isInternal = computed(() => activeRoom.value?.source === 'internal')
|
||||
|
||||
const mergeMessages = (incoming) => {
|
||||
const byId = new Map(messages.value.map((message) => [message.id, message]))
|
||||
function clearMessages() { messages.value = []; members.value = []; draft.value = ''; syncAfterId = 0; roomLoading.value = false; sending.value = false }
|
||||
function mergeMessages(incoming) {
|
||||
const byId = new Map(messages.value.map(message => [message.id, message]))
|
||||
for (const message of incoming || []) byId.set(message.id, message)
|
||||
messages.value = Array.from(byId.values()).sort((a, b) => Number(a.id) - Number(b.id))
|
||||
syncAfterId = Number(messages.value.at(-1)?.id || syncAfterId)
|
||||
messages.value = [...byId.values()].sort((a, b) => Number(a.id) - Number(b.id))
|
||||
syncAfterId = Number(messages.value.at(-1)?.id || 0)
|
||||
}
|
||||
|
||||
const scrollToBottom = async () => {
|
||||
const scrollToBottom = async request => {
|
||||
await nextTick()
|
||||
if (messagesViewport.value) messagesViewport.value.scrollTop = messagesViewport.value.scrollHeight
|
||||
if (currentSelection(request) && messagesViewport.value) messagesViewport.value.scrollTop = messagesViewport.value.scrollHeight
|
||||
}
|
||||
|
||||
const loadUnread = async () => {
|
||||
async function loadUnread(scope = scopeVersion) {
|
||||
if (!hasSession.value || !currentScope(scope)) return
|
||||
try {
|
||||
unreadRooms.value = (await $api("/api/communication/chat/unread")).rooms || {}
|
||||
} catch {
|
||||
unreadRooms.value = {}
|
||||
}
|
||||
const result = await $api('/api/communication/chat/unread')
|
||||
if (currentScope(scope)) unreadRooms.value = result.rooms || {}
|
||||
} catch { /* A count failure must not interrupt an open conversation. */ }
|
||||
}
|
||||
|
||||
const loadRoomLists = async () => {
|
||||
const [rooms, projects, directs] = await Promise.all([
|
||||
$api("/api/communication/chat/rooms"),
|
||||
$api("/api/communication/chat/project-rooms"),
|
||||
$api("/api/communication/chat/direct-rooms")
|
||||
])
|
||||
baseRooms.value = rooms.rooms || []
|
||||
projectRooms.value = projects.rooms || []
|
||||
directRooms.value = directs.rooms || []
|
||||
}
|
||||
|
||||
const markRead = async () => {
|
||||
if (!activeRoom.value?.exists) return
|
||||
async function loadRoomLists(scope = scopeVersion) {
|
||||
if (!hasSession.value || !currentScope(scope)) return
|
||||
const request = ++nativeListRequest
|
||||
try {
|
||||
await $api(`${roomEndpoint.value}/read`, {
|
||||
method: "POST",
|
||||
body: { messageId: Number(messages.value.at(-1)?.id || 0) }
|
||||
})
|
||||
unreadRooms.value = { ...unreadRooms.value, [activeRoomKey.value]: { count: 0, mentions: 0 } }
|
||||
} catch {
|
||||
// Der Lesestatus darf die Unterhaltung nicht blockieren.
|
||||
}
|
||||
}
|
||||
|
||||
const loadActiveRoom = async () => {
|
||||
if (!activeRoom.value?.exists) return
|
||||
roomLoading.value = true
|
||||
syncAfterId = 0
|
||||
try {
|
||||
const [messageResult, memberResult] = await Promise.all([
|
||||
$api(`${roomEndpoint.value}/messages`),
|
||||
$api(`${roomEndpoint.value}/members`)
|
||||
const [rooms, projects, directs] = await Promise.all([
|
||||
$api('/api/communication/chat/rooms'), $api('/api/communication/chat/project-rooms'), $api('/api/communication/chat/direct-rooms')
|
||||
])
|
||||
messages.value = []
|
||||
mergeMessages(messageResult.messages || [])
|
||||
members.value = memberResult.members || []
|
||||
await markRead()
|
||||
await scrollToBottom()
|
||||
} catch (error) {
|
||||
toast.add({ title: error?.data?.error || "Chatraum konnte nicht geladen werden", color: "error" })
|
||||
} finally {
|
||||
roomLoading.value = false
|
||||
}
|
||||
if (!currentScope(scope) || request !== nativeListRequest) return
|
||||
baseRooms.value = rooms.rooms || []; projectRooms.value = projects.rooms || []; directRooms.value = directs.rooms || []
|
||||
listError.value = ''
|
||||
} catch (error) { if (currentScope(scope) && request === nativeListRequest) listError.value = errorMessage(error) }
|
||||
}
|
||||
|
||||
const provisionRoom = async (room) => {
|
||||
const endpoint = room.type === "project"
|
||||
? `/api/communication/chat/project-rooms/${room.projectId}/provision`
|
||||
: `/api/communication/chat/direct-rooms/${encodeURIComponent(room.userId)}/provision`
|
||||
const created = await $api(endpoint, { method: "POST" })
|
||||
await loadRoomLists()
|
||||
activeRoomKey.value = created.key
|
||||
await router.replace({ query: { ...route.query, room: created.key } })
|
||||
}
|
||||
|
||||
const selectRoom = async (room) => {
|
||||
async function loadCollaboration(scope = scopeVersion) {
|
||||
if (!hasSession.value || !currentScope(scope)) return
|
||||
const request = ++collaborationRequest
|
||||
try {
|
||||
if (!room.exists) await provisionRoom(room)
|
||||
else {
|
||||
activeRoomKey.value = room.key
|
||||
await router.replace({ query: { ...route.query, room: room.key } })
|
||||
}
|
||||
messages.value = []
|
||||
members.value = []
|
||||
await loadActiveRoom()
|
||||
const result = await $api('/api/collaboration')
|
||||
if (!currentScope(scope) || request !== collaborationRequest) return
|
||||
// Managed rooms alone never grant chat access. Only explicit memberships enter this list.
|
||||
collaborationRooms.value = result.rooms || []; invitations.value = result.invitations || []
|
||||
collaborationError.value = ''
|
||||
} catch (error) {
|
||||
toast.add({ title: error?.data?.error || "Chatraum konnte nicht geöffnet werden", color: "error" })
|
||||
if (!currentScope(scope) || request !== collaborationRequest) return
|
||||
collaborationError.value = errorMessage(error)
|
||||
if ([401, 403].includes(error?.statusCode || error?.status)) { collaborationRooms.value = []; invitations.value = [] }
|
||||
}
|
||||
}
|
||||
async function refreshLists() {
|
||||
const scope = scopeVersion
|
||||
await Promise.all([loadRoomLists(scope), loadUnread(scope), loadCollaboration(scope)])
|
||||
}
|
||||
|
||||
const createRoom = async () => {
|
||||
if (!roomForm.name.trim()) return
|
||||
async function loadRoomPreferences(scope = scopeVersion) {
|
||||
if (!hasSession.value || !currentScope(scope)) return
|
||||
try {
|
||||
const result = await $api('/api/communication/chat/room-preferences')
|
||||
if (!currentScope(scope)) return
|
||||
hiddenRoomKeys.value = result.hiddenRoomKeys || []
|
||||
preferencesReady.value = true; preferenceError.value = ''
|
||||
} catch (error) {
|
||||
if (currentScope(scope)) preferenceError.value = errorMessage(error)
|
||||
}
|
||||
}
|
||||
async function setRoomHidden(room, hidden) {
|
||||
if (preferenceBusy.value || !preferencesReady.value) return
|
||||
const scope = scopeVersion
|
||||
preferenceBusy.value = room.key
|
||||
try {
|
||||
await $api('/api/communication/chat/room-preferences', { method: 'PUT', body: { roomKey: room.key, hidden } })
|
||||
if (!currentScope(scope)) return
|
||||
hiddenRoomKeys.value = hidden
|
||||
? [...new Set([...hiddenRoomKeys.value, room.key])]
|
||||
: hiddenRoomKeys.value.filter(key => key !== room.key)
|
||||
if (hidden && activeRoomKey.value === room.key) {
|
||||
++roomVersion; activeRoomKey.value = ''; clearMessages()
|
||||
const next = visibleRooms.value.find(candidate => candidate.exists)
|
||||
if (next) await selectRoom(next)
|
||||
else await router.replace({ query: { ...route.query, room: undefined } })
|
||||
} else if (!hidden) {
|
||||
const restored = visibleRooms.value.find(candidate => candidate.key === room.key)
|
||||
if (restored) await selectRoom(restored)
|
||||
}
|
||||
} catch (error) { if (currentScope(scope)) toast.add({ title: errorMessage(error), color: 'error' }) }
|
||||
finally { if (currentScope(scope)) preferenceBusy.value = '' }
|
||||
}
|
||||
|
||||
async function markRead(request) {
|
||||
if (!currentSelection(request) || !isInternal.value || !activeRoom.value?.exists) return
|
||||
const messageId = Number(messages.value.at(-1)?.id || 0)
|
||||
try {
|
||||
await $api(nativeEndpoint(request.key, '/read'), { method: 'POST', body: { messageId } })
|
||||
if (currentSelection(request)) unreadRooms.value = { ...unreadRooms.value, [request.key]: { count: 0, mentions: 0 } }
|
||||
} catch { /* Read receipts must not interrupt the conversation. */ }
|
||||
}
|
||||
async function loadActiveRoom(request = selection()) {
|
||||
if (!currentSelection(request) || !isInternal.value || !activeRoom.value?.exists) return
|
||||
roomLoading.value = true
|
||||
try {
|
||||
const [result, people] = await Promise.all([
|
||||
$api(nativeEndpoint(request.key, '/messages')), $api(nativeEndpoint(request.key, '/members'))
|
||||
])
|
||||
if (!currentSelection(request)) return
|
||||
messages.value = []; mergeMessages(result.messages); members.value = people.members || []
|
||||
await markRead(request); await scrollToBottom(request)
|
||||
} catch (error) {
|
||||
if (currentSelection(request)) toast.add({ title: errorMessage(error), color: 'error' })
|
||||
} finally { if (currentSelection(request)) roomLoading.value = false }
|
||||
}
|
||||
async function selectRoom(room) {
|
||||
if (hiddenRoomKeys.value.includes(room.key)) return
|
||||
++roomVersion; activeRoomKey.value = room.key; clearMessages()
|
||||
let request = selection()
|
||||
try {
|
||||
if (room.source !== 'collaboration' && !room.exists) {
|
||||
const endpoint = room.type === 'project'
|
||||
? `/api/communication/chat/project-rooms/${room.projectId}/provision`
|
||||
: `/api/communication/chat/direct-rooms/${encodeURIComponent(room.userId)}/provision`
|
||||
const created = await $api(endpoint, { method: 'POST' })
|
||||
if (!currentSelection(request)) return
|
||||
await loadRoomLists(request.scope)
|
||||
if (!currentSelection(request)) return
|
||||
activeRoomKey.value = created.key; request = selection()
|
||||
}
|
||||
await router.replace({ query: { ...route.query, room: request.key } })
|
||||
if (currentSelection(request)) await loadActiveRoom(request)
|
||||
} catch (error) { if (currentSelection(request)) toast.add({ title: errorMessage(error), color: 'error' }) }
|
||||
}
|
||||
async function createRoom() {
|
||||
if (!roomForm.name.trim() || creating.value) return
|
||||
const scope = scopeVersion
|
||||
creating.value = true
|
||||
try {
|
||||
const created = await $api("/api/communication/chat/rooms", {
|
||||
method: "POST",
|
||||
body: { name: roomForm.name, key: roomKeyPreview.value, topic: roomForm.topic }
|
||||
const created = await $api('/api/communication/chat/rooms', {
|
||||
method: 'POST', body: { name: roomForm.name, key: roomKeyPreview.value, topic: roomForm.topic }
|
||||
})
|
||||
Object.assign(roomForm, { name: "", key: "", topic: "" })
|
||||
showRoomForm.value = false
|
||||
await loadRoomLists()
|
||||
await selectRoom(created)
|
||||
} catch (error) {
|
||||
toast.add({ title: error?.data?.error || "Chatraum konnte nicht erstellt werden", color: "error" })
|
||||
} finally {
|
||||
creating.value = false
|
||||
}
|
||||
if (!currentScope(scope)) return
|
||||
Object.assign(roomForm, { name: '', key: '', topic: '' }); showRoomForm.value = false
|
||||
await loadRoomLists(scope)
|
||||
if (currentScope(scope)) await selectRoom(created)
|
||||
} catch (error) { if (currentScope(scope)) toast.add({ title: errorMessage(error), color: 'error' }) }
|
||||
finally { if (currentScope(scope)) creating.value = false }
|
||||
}
|
||||
|
||||
const sendMessage = async () => {
|
||||
const text = draft.value.trim()
|
||||
if (!text || sending.value || !activeRoom.value?.exists) return
|
||||
sending.value = true
|
||||
draft.value = ""
|
||||
async function respondToInvitation(id, accept) {
|
||||
if (invitationBusy.value) return
|
||||
const scope = scopeVersion
|
||||
invitationBusy.value = id
|
||||
try {
|
||||
const message = await $api(`${roomEndpoint.value}/messages`, { method: "POST", body: { text } })
|
||||
mergeMessages([message])
|
||||
await markRead()
|
||||
await scrollToBottom()
|
||||
} catch (error) {
|
||||
draft.value = text
|
||||
toast.add({ title: error?.data?.error || "Nachricht konnte nicht gesendet werden", color: "error" })
|
||||
} finally {
|
||||
sending.value = false
|
||||
}
|
||||
const result = await $api(`/api/collaboration/invitations/${encodeURIComponent(id)}/${accept ? 'accept' : 'decline'}`, { method: 'POST' })
|
||||
if (!currentScope(scope)) return
|
||||
await loadCollaboration(scope)
|
||||
if (!currentScope(scope)) return
|
||||
const room = decoratedRooms.value.find(room => room.key === collaborationKey(result.roomId))
|
||||
if (accept && room) await selectRoom(room)
|
||||
} catch (error) { if (currentScope(scope)) toast.add({ title: errorMessage(error), color: 'error' }) }
|
||||
finally { if (currentScope(scope)) invitationBusy.value = '' }
|
||||
}
|
||||
|
||||
const pollMessages = async () => {
|
||||
if (pollBusy || document.hidden || !activeRoom.value?.exists) return
|
||||
async function sendMessage() {
|
||||
const text = draft.value.trim(), request = selection()
|
||||
if (!text || sending.value || !isInternal.value || !activeRoom.value?.exists) return
|
||||
sending.value = true; draft.value = ''
|
||||
try {
|
||||
const message = await $api(nativeEndpoint(request.key, '/messages'), { method: 'POST', body: { text } })
|
||||
if (!currentSelection(request)) return
|
||||
mergeMessages([message]); await markRead(request); await scrollToBottom(request)
|
||||
} catch (error) {
|
||||
if (currentSelection(request)) { draft.value = text; toast.add({ title: errorMessage(error), color: 'error' }) }
|
||||
} finally { if (currentSelection(request)) sending.value = false }
|
||||
}
|
||||
async function pollMessages() {
|
||||
if (pollBusy || loading.value || roomLoading.value || document.hidden || !isInternal.value || !activeRoom.value?.exists) return
|
||||
const request = selection()
|
||||
pollBusy = true
|
||||
try {
|
||||
const result = await $api(`${roomEndpoint.value}/sync?afterId=${syncAfterId}`)
|
||||
if (result.messages?.length) {
|
||||
mergeMessages(result.messages)
|
||||
await markRead()
|
||||
await scrollToBottom()
|
||||
}
|
||||
await loadUnread()
|
||||
} catch {
|
||||
// Beim nächsten Intervall erneut versuchen.
|
||||
} finally {
|
||||
pollBusy = false
|
||||
}
|
||||
}
|
||||
|
||||
const formatMessageTime = (timestamp) => new Intl.DateTimeFormat("de-DE", {
|
||||
day: "2-digit", month: "2-digit", hour: "2-digit", minute: "2-digit"
|
||||
}).format(new Date(timestamp))
|
||||
|
||||
onMounted(async () => {
|
||||
try {
|
||||
await Promise.all([loadRoomLists(), loadUnread()])
|
||||
if (!activeRoom.value) activeRoomKey.value = "allgemein"
|
||||
await loadActiveRoom()
|
||||
pollTimer = window.setInterval(pollMessages, 2500)
|
||||
const result = await $api(nativeEndpoint(request.key, `/sync?afterId=${syncAfterId}`))
|
||||
if (!currentSelection(request)) return
|
||||
if (result.messages?.length) { mergeMessages(result.messages); await markRead(request); await scrollToBottom(request) }
|
||||
await loadUnread(request.scope)
|
||||
} catch (error) {
|
||||
toast.add({ title: error?.data?.error || "Chat konnte nicht geladen werden", color: "error" })
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
})
|
||||
if (currentSelection(request) && [401, 403, 404, 410].includes(error?.statusCode || error?.status)) {
|
||||
++roomVersion; clearMessages(); void loadRoomLists(request.scope)
|
||||
}
|
||||
} finally { pollBusy = false }
|
||||
}
|
||||
const formatMessageTime = timestamp => new Intl.DateTimeFormat('de-DE', { day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit' }).format(new Date(timestamp))
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
if (pollTimer) window.clearInterval(pollTimer)
|
||||
async function initialize() {
|
||||
const scope = ++scopeVersion
|
||||
++roomVersion; clearMessages()
|
||||
baseRooms.value = []; projectRooms.value = []; directRooms.value = []; collaborationRooms.value = []; invitations.value = []
|
||||
unreadRooms.value = {}; invitationBusy.value = ''; collaborationError.value = ''; listError.value = ''; creating.value = false
|
||||
hiddenRoomKeys.value = []; showHiddenRooms.value = false; preferenceBusy.value = ''; preferenceError.value = ''; preferencesReady.value = false
|
||||
showRoomForm.value = false; Object.assign(roomForm, { name: '', key: '', topic: '' })
|
||||
activeRoomKey.value = requestedRoom(); loading.value = true
|
||||
await Promise.all([refreshLists(), loadRoomPreferences(scope)])
|
||||
if (!currentScope(scope)) return
|
||||
loading.value = false
|
||||
const room = activeRoom.value || (activeRoomKey.value === 'allgemein' ? visibleRooms.value.find(room => room.exists) : null)
|
||||
if (room) await selectRoom(room)
|
||||
}
|
||||
watch(session, () => { if (mounted) void initialize() }, { flush: 'sync' })
|
||||
watch(() => activeRoom.value?.key, (key, previous) => {
|
||||
if (!key && previous && !loading.value) { ++roomVersion; clearMessages() }
|
||||
})
|
||||
watch(() => route.query.room, () => {
|
||||
if (!mounted || loading.value || requestedRoom() === activeRoomKey.value) return
|
||||
const room = visibleRooms.value.find(room => room.key === requestedRoom())
|
||||
if (room) void selectRoom(room)
|
||||
else { ++roomVersion; activeRoomKey.value = requestedRoom(); clearMessages() }
|
||||
})
|
||||
onMounted(() => {
|
||||
mounted = true; void initialize()
|
||||
pollTimer = window.setInterval(pollMessages, 2500)
|
||||
listTimer = window.setInterval(() => { if (!document.hidden && !loading.value) void refreshLists() }, 15000)
|
||||
})
|
||||
onBeforeUnmount(() => { disposed = true; ++scopeVersion; ++roomVersion; clearInterval(pollTimer); clearInterval(listTimer) })
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex min-h-0 flex-1 bg-gray-50 p-4 sm:p-6">
|
||||
<div class="mx-auto grid h-[calc(100vh-8rem)] w-full max-w-7xl grid-cols-1 overflow-hidden rounded-xl border border-gray-200 bg-white shadow-sm lg:grid-cols-[19rem_minmax(0,1fr)_15rem]">
|
||||
<div class="flex h-full min-h-0 min-w-0 w-full flex-1 overflow-hidden bg-white">
|
||||
<div class="grid h-full min-h-0 w-full flex-1 grid-cols-1 grid-rows-[minmax(8rem,30%)_minmax(0,1fr)] overflow-hidden lg:grid-rows-1"
|
||||
:class="isCollaboration ? 'lg:grid-cols-[19rem_minmax(0,1fr)]' : 'lg:grid-cols-[19rem_minmax(0,1fr)_15rem]'">
|
||||
<aside class="min-h-0 overflow-y-auto border-r border-gray-200 p-4">
|
||||
<div class="mb-4 flex items-center justify-between">
|
||||
<div>
|
||||
@@ -233,30 +288,67 @@ onBeforeUnmount(() => {
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<UButton to="/communication/collaboration" icon="i-heroicons-user-group" color="neutral" variant="outline" size="xs" class="mb-4 w-full justify-center">Unterräume und Freigaben</UButton>
|
||||
<p v-if="listError" role="alert" class="mb-3 text-xs text-red-700">{{ listError }} <button class="underline" @click="loadRoomLists()">Erneut laden</button></p>
|
||||
<p v-if="collaborationError" role="alert" class="mb-3 text-xs text-red-700">Zusammenarbeit: {{ collaborationError }} <button class="underline" @click="loadCollaboration()">Erneut laden</button></p>
|
||||
<p v-if="preferenceError" role="alert" class="mb-3 text-xs text-red-700">Raumeinstellungen: {{ preferenceError }} <button class="underline" @click="loadRoomPreferences()">Erneut laden</button></p>
|
||||
<section v-if="invitations.length" class="mb-5 space-y-2" aria-label="Einladungen">
|
||||
<h2 class="px-2 text-xs font-semibold uppercase tracking-wide text-gray-400">Einladungen</h2>
|
||||
<div v-for="invitation in invitations" :key="invitation.id" class="rounded-lg border border-primary-200 bg-primary-50 p-3">
|
||||
<p class="text-sm font-medium">{{ invitation.name }}</p>
|
||||
<p class="text-xs text-gray-500">{{ invitation.ownerName }} · {{ invitation.role === 'reader' ? 'Nur lesen' : 'Lesen und schreiben' }}</p>
|
||||
<p v-if="invitation.overviewAllowed" class="mt-1 text-xs text-gray-500">Projektübersicht freigegeben</p>
|
||||
<div class="mt-2 flex gap-2">
|
||||
<UButton size="xs" :disabled="!!invitationBusy" @click="respondToInvitation(invitation.id, true)">Annehmen</UButton>
|
||||
<UButton size="xs" variant="ghost" color="neutral" :disabled="!!invitationBusy" @click="respondToInvitation(invitation.id, false)">Ablehnen</UButton>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<div v-if="loading" class="py-8 text-center text-sm text-gray-500">Chat wird geladen …</div>
|
||||
<div v-else class="space-y-5">
|
||||
<section v-for="group in groupedRooms" :key="group.label">
|
||||
<h2 class="mb-1 px-2 text-xs font-semibold uppercase tracking-wide text-gray-400">{{ group.label }}</h2>
|
||||
<button
|
||||
<div
|
||||
v-for="room in group.rooms"
|
||||
:key="room.key"
|
||||
type="button"
|
||||
class="mb-1 flex w-full items-center gap-3 rounded-lg px-2 py-2 text-left transition hover:bg-gray-100"
|
||||
class="mb-1 flex w-full items-center rounded-lg transition hover:bg-gray-100"
|
||||
:class="room.key === activeRoomKey ? 'bg-primary-50 text-primary-700' : 'text-gray-700'"
|
||||
@click="selectRoom(room)"
|
||||
>
|
||||
<UIcon :name="room.icon" class="size-5 shrink-0" />
|
||||
<span class="min-w-0 flex-1">
|
||||
<span class="block truncate text-sm font-medium">{{ room.name }}</span>
|
||||
<span class="block truncate text-xs text-gray-400">{{ room.topic }}</span>
|
||||
</span>
|
||||
<UBadge v-if="room.unread" color="primary" size="xs">{{ room.unread }}</UBadge>
|
||||
<button
|
||||
type="button"
|
||||
class="flex min-w-0 flex-1 items-center gap-3 px-2 py-2 text-left"
|
||||
@click="selectRoom(room)"
|
||||
>
|
||||
<UIcon :name="room.icon" class="size-5 shrink-0" />
|
||||
<span class="min-w-0 flex-1">
|
||||
<span class="block truncate text-sm font-medium">{{ room.name }}</span>
|
||||
<span class="block truncate text-xs text-gray-400">{{ room.source === 'collaboration' ? room.ownerName || 'Projekt-Unterraum' : room.topic }}{{ room.remote ? ' · Extern' : '' }}{{ room.status === 'archived' ? ' · Archiviert' : '' }}</span>
|
||||
</span>
|
||||
<UBadge v-if="room.unread" color="primary" size="xs">{{ room.unread }}</UBadge>
|
||||
</button>
|
||||
<UButton icon="i-heroicons-eye-slash" color="neutral" variant="ghost" size="xs" class="mr-1 shrink-0" :aria-label="`${room.name} ausblenden`" title="Für mich ausblenden" :disabled="!preferencesReady || !!preferenceBusy" @click="setRoomHidden(room, true)" />
|
||||
</div>
|
||||
</section>
|
||||
<p v-if="!visibleRooms.length" class="px-2 text-sm text-gray-500">Keine sichtbaren Räume. Du kannst ausgeblendete Räume unten wieder einblenden.</p>
|
||||
<section v-if="hiddenRooms.length" aria-label="Ausgeblendete Räume">
|
||||
<button type="button" class="flex w-full items-center justify-between px-2 py-2 text-left text-xs font-semibold text-gray-500" :aria-expanded="showHiddenRooms" @click="showHiddenRooms = !showHiddenRooms">
|
||||
<span>Ausgeblendete Räume ({{ hiddenRooms.length }})</span><UIcon :name="showHiddenRooms ? 'i-heroicons-chevron-up' : 'i-heroicons-chevron-down'" />
|
||||
</button>
|
||||
<div v-if="showHiddenRooms" class="space-y-1">
|
||||
<div v-for="room in hiddenRooms" :key="room.key" class="flex items-center gap-2 px-2 py-1">
|
||||
<span class="min-w-0 flex-1 truncate text-sm text-gray-500">{{ room.name }}</span>
|
||||
<UButton icon="i-heroicons-eye" variant="ghost" color="neutral" size="xs" :aria-label="`${room.name} einblenden`" :disabled="!!preferenceBusy" @click="setRoomHidden(room, false)">Einblenden</UButton>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<main class="flex min-h-0 flex-col">
|
||||
<CollaborationRoom v-if="!loading && isCollaboration" :key="`${session}:${activeRoom.id}`" :room-id="activeRoom.id" :api="$api" embedded @changed="loadCollaboration()" @unauthorized="loadCollaboration()">
|
||||
<template #actions><UButton :to="{ path: '/communication/collaboration', query: { room: activeRoom.id } }" color="neutral" variant="outline" size="xs">Details und Freigaben</UButton></template>
|
||||
</CollaborationRoom>
|
||||
<main v-else class="flex min-h-0 flex-col">
|
||||
<header class="border-b border-gray-200 px-5 py-4">
|
||||
<h2 class="font-semibold text-gray-900">{{ activeRoom?.name || "Chat" }}</h2>
|
||||
<p class="truncate text-sm text-gray-500">{{ activeRoom?.topic || "Wähle links einen Chatraum aus." }}</p>
|
||||
@@ -264,6 +356,7 @@ onBeforeUnmount(() => {
|
||||
|
||||
<div ref="messagesViewport" class="min-h-0 flex-1 overflow-y-auto px-4 py-5 sm:px-6">
|
||||
<div v-if="roomLoading" class="py-10 text-center text-sm text-gray-500">Nachrichten werden geladen …</div>
|
||||
<div v-else-if="!activeRoom" class="py-10 text-center text-sm text-gray-500">Dieser Chatraum ist nicht verfügbar. Wähle links einen anderen Raum.</div>
|
||||
<div v-else-if="!messages.length" class="flex h-full flex-col items-center justify-center text-center text-gray-400">
|
||||
<UIcon name="i-heroicons-chat-bubble-oval-left-ellipsis" class="mb-3 size-10" />
|
||||
<p class="font-medium">Noch keine Nachrichten</p>
|
||||
@@ -286,7 +379,7 @@ onBeforeUnmount(() => {
|
||||
</form>
|
||||
</main>
|
||||
|
||||
<aside class="hidden min-h-0 overflow-y-auto border-l border-gray-200 p-4 lg:block">
|
||||
<aside v-if="!isCollaboration" class="hidden min-h-0 overflow-y-auto border-l border-gray-200 p-4 lg:block">
|
||||
<h2 class="mb-3 text-sm font-semibold text-gray-900">Teilnehmer</h2>
|
||||
<div class="space-y-3">
|
||||
<div v-for="member in members" :key="member.userId" class="flex items-center gap-3">
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
const { $api } = useNuxtApp()
|
||||
const route = useRoute()
|
||||
const state = ref({ rooms: [], invitations: [], managedRooms: [], projects: [], canManage: false, contact: '' })
|
||||
const contacts = ref([]), selected = ref(''), error = ref(''), busy = ref(false), showCreate = ref(false), showManagement = ref(false)
|
||||
const contacts = ref([]), selected = ref(typeof route.query.room === 'string' ? route.query.room : ''), error = ref(''), busy = ref(false), showCreate = ref(false), showManagement = ref(false)
|
||||
const management = ref({ members: [], invitations: [] }), inviteResult = ref(null)
|
||||
const create = reactive({ name: '', topic: '', projectId: String(route.query.project || '') })
|
||||
const invite = reactive({ kind: 'user', userId: '', name: '', email: '', contact: '', role: 'participant', overviewAllowed: false, expiresAt: '', sendEmail: true })
|
||||
@@ -73,6 +73,7 @@ async function savePartner(origin, active = true) {
|
||||
})
|
||||
}
|
||||
watch(selected, () => { showManagement.value = false; inviteResult.value = null; management.value = { members: [], invitations: [] } })
|
||||
watch(() => route.query.room, id => { if (typeof id === 'string') selected.value = id })
|
||||
let timer
|
||||
onMounted(async () => { await refresh(); timer = setInterval(() => { if (!document.hidden && !busy.value) void refresh() }, 15000) })
|
||||
onBeforeUnmount(() => clearInterval(timer))
|
||||
@@ -92,7 +93,7 @@ onBeforeUnmount(() => clearInterval(timer))
|
||||
<section v-if="federation" class="rounded-xl border border-gray-200 p-4 dark:border-gray-700">
|
||||
<div class="flex justify-between"><h2 class="font-semibold">Freigegebene Partnerinstanzen</h2><button @click="federation = null">Schließen</button></div>
|
||||
<p class="my-2 text-sm text-gray-500">Beide Firmen geben die jeweils andere Instanz frei. Einzelne Personen erhalten anschließend eine eigene Einladung.</p>
|
||||
<p v-if="!federation.enabled" class="my-2 text-sm text-amber-700">Die Föderation muss zuerst vom Betreiber aktiviert werden.</p>
|
||||
<p v-if="!federation.enabled" class="my-2 text-sm text-amber-700">{{ federation.disabledReason || 'Die Föderation muss zuerst vom Betreiber aktiviert werden.' }}</p>
|
||||
<form v-if="federation.enabled" class="flex flex-wrap gap-2" @submit.prevent="savePartner(partnerUrl)"><label class="flex-1"><span class="sr-only">Adresse der Partnerinstanz</span><input v-model="partnerUrl" type="url" required placeholder="https://partner.example/backend" class="field" /></label><UButton type="submit" :loading="busy">Partner freigeben</UButton></form>
|
||||
<div v-for="partner in federation.partners" :key="partner.origin" class="mt-3 flex items-center justify-between gap-3 text-sm"><span>{{ partner.origin }} · {{ partner.active ? 'Freigegeben' : 'Gesperrt' }}</span><UButton variant="outline" size="xs" :disabled="busy" @click="savePartner(partner.origin, !partner.active)">{{ partner.active ? 'Sperren' : 'Freigeben' }}</UButton></div>
|
||||
</section>
|
||||
@@ -120,7 +121,10 @@ onBeforeUnmount(() => clearInterval(timer))
|
||||
</button>
|
||||
</aside>
|
||||
<div class="min-w-0 space-y-4">
|
||||
<UButton v-if="selectedManaged" variant="outline" :disabled="busy" @click="run(async () => { await loadManagement(); showManagement = !showManagement })">Teilnehmer und Freigaben verwalten</UButton>
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<UButton v-if="readable" :to="{ path: '/communication/chat', query: { room: `collaboration:${selected}` } }" variant="outline">Im Chat öffnen</UButton>
|
||||
<UButton v-if="selectedManaged" variant="outline" :disabled="busy" @click="run(async () => { await loadManagement(); showManagement = !showManagement })">Teilnehmer und Freigaben verwalten</UButton>
|
||||
</div>
|
||||
<section v-if="showManagement && selectedManaged" class="space-y-5 rounded-xl border border-gray-200 p-4 dark:border-gray-700">
|
||||
<form class="space-y-3" @submit.prevent="invitePerson">
|
||||
<h2 class="font-semibold">Person in diesen Unterraum einladen</h2>
|
||||
|
||||
@@ -36,6 +36,12 @@ const previewDocument = ref<InboxDocument | null>(null)
|
||||
const filingDocument = ref<InboxDocument | null>(null)
|
||||
const filingLoading = ref(false)
|
||||
const filingSaving = ref(false)
|
||||
const archiveOpen = ref(false)
|
||||
const archiveTarget = ref<InboxDocument | null>(null)
|
||||
const archiveSaving = ref(false)
|
||||
const archiveError = ref("")
|
||||
let archiveVersion = 0
|
||||
const documentBusy = computed(() => filingSaving.value || archiveSaving.value)
|
||||
const filingError = ref("")
|
||||
const filingFolders = ref<FilingFolder[]>([])
|
||||
const filingTypes = ref<FilingType[]>([])
|
||||
@@ -80,7 +86,7 @@ const folderOptions = computed(() => {
|
||||
return [{ id: "root", name: "Dateien (Hauptebene)" }, ...filingFolders.value
|
||||
.map(folder => ({ id: folder.id, name: path(folder) })).sort((a, b) => a.name.localeCompare(b.name, "de"))]
|
||||
})
|
||||
const canFile = computed(() => Boolean(filingDocument.value && !filingLoading.value && !filingSaving.value
|
||||
const canFile = computed(() => Boolean(filingDocument.value && !filingLoading.value && !documentBusy.value
|
||||
&& (filingFolder.value === "root" || selectedFolder.value)
|
||||
&& filingTypes.value.some(type => type.id === filingType.value)
|
||||
&& (!fixedType.value || filingType.value === selectedFolder.value?.standardFiletype)))
|
||||
@@ -225,6 +231,7 @@ const removeAssignment = (kind: string) => {
|
||||
const openPreview = (entry: InboxDocument) => openFiling(entry)
|
||||
|
||||
const openFiling = async (entry: InboxDocument) => {
|
||||
if (disposed || documentBusy.value) return
|
||||
suggestionVersion++
|
||||
clearTimeout(suggestionTimer)
|
||||
suggestionController?.abort()
|
||||
@@ -278,6 +285,44 @@ const openFiling = async (entry: InboxDocument) => {
|
||||
}
|
||||
}
|
||||
|
||||
const removeInboxEntry = (id: string) => {
|
||||
// Discard older list responses that still contain the completed document.
|
||||
requestVersion++
|
||||
clearTimeout(pollTimer)
|
||||
if (documents.value.some(document => document.id === id)) total.value = Math.max(0, total.value - 1)
|
||||
documents.value = documents.value.filter(document => document.id !== id)
|
||||
page.value = Math.min(page.value, Math.max(1, Math.ceil(total.value / pageSize)))
|
||||
void inboxCount.refresh()
|
||||
if (previewDocument.value?.id === id) previewOpen.value = false
|
||||
}
|
||||
|
||||
const openArchive = (entry: InboxDocument) => {
|
||||
if (disposed || documentBusy.value || !auth.activeTenant) return
|
||||
archiveTarget.value = entry
|
||||
archiveError.value = ""
|
||||
archiveOpen.value = true
|
||||
}
|
||||
|
||||
const archiveDocument = async () => {
|
||||
const entry = archiveTarget.value
|
||||
if (!entry || !archiveOpen.value || disposed || documentBusy.value || !auth.activeTenant) return
|
||||
const version = ++archiveVersion
|
||||
archiveSaving.value = true
|
||||
archiveError.value = ""
|
||||
try {
|
||||
await $api(`/api/document-inbox/${entry.id}/archive`, { method: "POST" })
|
||||
if (disposed || version !== archiveVersion) return
|
||||
removeInboxEntry(entry.id)
|
||||
archiveOpen.value = false
|
||||
toast.add({ title: "Dokument archiviert", description: `${entry.name} wurde aus der Ablage entfernt.`, color: "success" })
|
||||
await load(true)
|
||||
} catch (cause: any) {
|
||||
if (!disposed && version === archiveVersion) archiveError.value = cause?.data?.error || cause?.data?.message || "Das Dokument konnte nicht archiviert werden."
|
||||
} finally {
|
||||
if (version === archiveVersion) archiveSaving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const fileDocument = async () => {
|
||||
if (!canFile.value) return
|
||||
const entry = filingDocument.value!
|
||||
@@ -288,14 +333,7 @@ const fileDocument = async () => {
|
||||
try {
|
||||
await $api(`/api/document-inbox/${entry.id}/file`, { method: "POST", body: { folder, type: filingType.value, assignments: { ...assignmentChanges.value } } })
|
||||
if (disposed || version !== filingVersion) return
|
||||
// Cancel pending polling responses before removing the successfully filed entry.
|
||||
requestVersion++
|
||||
clearTimeout(pollTimer)
|
||||
documents.value = documents.value.filter(document => document.id !== entry.id)
|
||||
total.value = Math.max(0, total.value - 1)
|
||||
page.value = Math.min(page.value, Math.max(1, Math.ceil(total.value / pageSize)))
|
||||
void inboxCount.refresh()
|
||||
previewOpen.value = false
|
||||
removeInboxEntry(entry.id)
|
||||
toast.add({ title: "Dokument abgelegt", description: `${entry.name} ist unter Dateien verfügbar.`, color: "success" })
|
||||
await load(true)
|
||||
} catch (cause: any) {
|
||||
@@ -429,7 +467,15 @@ watch(previewOpen, open => {
|
||||
filingLoading.value = false
|
||||
}
|
||||
})
|
||||
watch(archiveOpen, open => {
|
||||
if (!open) { archiveTarget.value = null; archiveError.value = "" }
|
||||
})
|
||||
watch(() => auth.activeTenant, () => {
|
||||
archiveVersion++
|
||||
archiveOpen.value = false
|
||||
archiveTarget.value = null
|
||||
archiveError.value = ""
|
||||
archiveSaving.value = false
|
||||
requestVersion++
|
||||
setupVersion++
|
||||
filingVersion++
|
||||
@@ -455,6 +501,7 @@ watch(() => auth.activeTenant, () => {
|
||||
onMounted(() => { origin.value = window.location.origin; load() })
|
||||
onBeforeUnmount(() => {
|
||||
disposed = true
|
||||
archiveVersion++
|
||||
requestVersion++
|
||||
setupVersion++
|
||||
filingVersion++
|
||||
@@ -507,7 +554,12 @@ onBeforeUnmount(() => {
|
||||
</td>
|
||||
<td class="whitespace-nowrap px-4 py-4 text-muted">{{ dayjs(entry.receivedAt).format('DD.MM.YYYY HH:mm') }}</td>
|
||||
<td class="whitespace-nowrap px-4 py-4 text-muted">{{ formatSize(entry.size) }}</td>
|
||||
<td class="px-4 py-4"><div class="flex justify-end gap-1"><UButton icon="i-heroicons-folder-arrow-down" variant="soft" :aria-label="`${entry.name} ablegen`" @click="openFiling(entry)">Ablegen</UButton><UButton icon="i-heroicons-eye" color="neutral" variant="ghost" :aria-label="`${entry.name} als Vorschau anzeigen`" @click="openPreview(entry)">Vorschau</UButton><UButton icon="i-heroicons-arrow-down-tray" color="neutral" variant="ghost" :aria-label="`${entry.name} herunterladen`" @click="fileAction(entry, true)" /></div></td>
|
||||
<td class="px-4 py-4"><div class="flex justify-end gap-1">
|
||||
<UButton icon="i-heroicons-folder-arrow-down" variant="soft" :aria-label="`${entry.name} ablegen`" :disabled="documentBusy" @click="openFiling(entry)">Ablegen</UButton>
|
||||
<UButton icon="i-heroicons-eye" color="neutral" variant="ghost" :aria-label="`${entry.name} als Vorschau anzeigen`" :disabled="documentBusy" @click="openPreview(entry)">Vorschau</UButton>
|
||||
<UButton icon="i-heroicons-arrow-down-tray" color="neutral" variant="ghost" :aria-label="`${entry.name} herunterladen`" @click="fileAction(entry, true)" />
|
||||
<UButton icon="i-heroicons-archive-box" color="neutral" variant="ghost" :aria-label="`${entry.name} archivieren`" :disabled="documentBusy" @click="openArchive(entry)">Archivieren</UButton>
|
||||
</div></td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
@@ -522,7 +574,7 @@ onBeforeUnmount(() => {
|
||||
</div>
|
||||
</UDashboardPanelContent>
|
||||
|
||||
<UModal v-model:open="previewOpen" :title="previewDocument?.name || 'Dokumentvorschau'" description="Dokument prüfen und mit Ordner und Typ ablegen." :dismissible="!filingSaving" :close="!filingSaving" :ui="{ content: 'w-[calc(100vw-2rem)] max-w-7xl h-[90dvh]', body: 'min-h-0 flex-1 overflow-y-auto lg:overflow-hidden p-0 sm:p-0', title: 'break-all pr-8', footer: 'flex-wrap justify-end' }">
|
||||
<UModal v-model:open="previewOpen" :title="previewDocument?.name || 'Dokumentvorschau'" description="Dokument prüfen und mit Ordner und Typ ablegen." :dismissible="!documentBusy" :close="!documentBusy" :ui="{ content: 'w-[calc(100vw-2rem)] max-w-7xl h-[90dvh]', body: 'min-h-0 flex-1 overflow-y-auto lg:overflow-hidden p-0 sm:p-0', title: 'break-all pr-8', footer: 'flex-wrap justify-end' }">
|
||||
<template #body>
|
||||
<div class="lg:flex lg:h-full lg:min-h-0">
|
||||
<div class="h-[50dvh] min-w-0 lg:h-full lg:flex-1">
|
||||
@@ -597,6 +649,7 @@ onBeforeUnmount(() => {
|
||||
</template>
|
||||
<template #footer>
|
||||
<template v-if="previewDocument">
|
||||
<UButton icon="i-heroicons-archive-box" color="neutral" variant="ghost" :disabled="documentBusy" @click="openArchive(previewDocument)">Archivieren</UButton>
|
||||
<UButton icon="i-heroicons-arrow-top-right-on-square" color="neutral" variant="ghost" @click="fileAction(previewDocument, false)">In neuem Tab öffnen</UButton>
|
||||
<UButton icon="i-heroicons-arrow-down-tray" color="neutral" variant="outline" @click="fileAction(previewDocument, true)">Herunterladen</UButton>
|
||||
<UButton type="submit" form="inbox-preview-filing" icon="i-heroicons-folder-arrow-down" :loading="filingSaving" :disabled="!canFile">Übernehmen und ablegen</UButton>
|
||||
@@ -604,6 +657,17 @@ onBeforeUnmount(() => {
|
||||
</template>
|
||||
</UModal>
|
||||
|
||||
<UModal v-model:open="archiveOpen" title="Dokument archivieren" description="Das Dokument verschwindet aus der Ablage. Die Originaldatei bleibt im Archiv erhalten." :dismissible="!archiveSaving" :close="!archiveSaving">
|
||||
<template #body>
|
||||
<p class="break-all font-medium">{{ archiveTarget?.name }}</p>
|
||||
<UAlert v-if="archiveError" class="mt-4" :title="archiveError" color="error" variant="subtle" />
|
||||
</template>
|
||||
<template #footer>
|
||||
<UButton color="neutral" variant="outline" :disabled="archiveSaving" @click="archiveOpen = false">Abbrechen</UButton>
|
||||
<UButton icon="i-heroicons-archive-box" :loading="archiveSaving" :disabled="!archiveTarget || filingSaving" @click="archiveDocument">Archivieren</UButton>
|
||||
</template>
|
||||
</UModal>
|
||||
|
||||
<UModal v-model:open="setupOpen" title="Scanner einrichten" description="Verbinde deinen Epson-Scanner mit der Dokumentenablage dieses Mandanten.">
|
||||
<template #body>
|
||||
<div class="space-y-5">
|
||||
|
||||
@@ -1717,6 +1717,16 @@ export const useDataStore = defineStore('data', () => {
|
||||
key: "customerRef",
|
||||
label: "Referenz des Kunden",
|
||||
inputType: "text"
|
||||
},{
|
||||
key: "chatEnabled",
|
||||
label: "Projektchat aktiviert",
|
||||
inputType: "bool",
|
||||
component: active,
|
||||
defaultValue: true,
|
||||
disabledFunction: () => {
|
||||
const auth = useAuthStore()
|
||||
return !auth.user?.is_admin && !auth.hasPermission('organisation.projects.write')
|
||||
}
|
||||
},{
|
||||
key: "notes",
|
||||
label: "Notizen",
|
||||
|
||||
329
frontend/tests/chat-collaboration.test.cjs
Normal file
329
frontend/tests/chat-collaboration.test.cjs
Normal file
@@ -0,0 +1,329 @@
|
||||
const { test } = require('node:test')
|
||||
const assert = require('node:assert/strict')
|
||||
const fs = require('node:fs')
|
||||
const vm = require('node:vm')
|
||||
const vue = require('vue')
|
||||
|
||||
const settle = () => new Promise(setImmediate)
|
||||
const deferred = () => {
|
||||
let resolve
|
||||
const promise = new Promise(done => { resolve = done })
|
||||
return { promise, resolve }
|
||||
}
|
||||
const source = fs.readFileSync(`${__dirname}/../pages/communication/chat.vue`, 'utf8').match(/<script setup>([\s\S]*?)<\/script>/)[1]
|
||||
const nativeRoom = { key: 'allgemein', name: 'Allgemein', exists: true, type: 'general' }
|
||||
const sharedRoom = { id: 'shared-room', name: 'Partnerchat', remote: true, unread: 3 }
|
||||
|
||||
function fixture(override = () => undefined) {
|
||||
return async (url, options) => {
|
||||
const result = override(url, options)
|
||||
if (result !== undefined) return result
|
||||
if (url === '/api/collaboration') return { rooms: [sharedRoom], invitations: [], managedRooms: [{ id: 'admin-only' }] }
|
||||
if (url === '/api/communication/chat/room-preferences') return { hiddenRoomKeys: [] }
|
||||
if (url === '/api/communication/chat/rooms') return { rooms: [nativeRoom] }
|
||||
if (url.endsWith('/project-rooms') || url.endsWith('/direct-rooms')) return { rooms: [] }
|
||||
if (url.endsWith('/unread')) return { rooms: { allgemein: { count: 2 } } }
|
||||
if (url.endsWith('/members')) return { members: [{ userId: 'member', displayName: 'Kollege' }] }
|
||||
if (url.includes('/sync?')) return { messages: [] }
|
||||
if (url.endsWith('/messages')) return { messages: [{ id: 1, body: 'Interne Nachricht' }] }
|
||||
if (url.endsWith('/read')) return {}
|
||||
throw new Error(`Unexpected request: ${url}`)
|
||||
}
|
||||
}
|
||||
|
||||
function setup(api = fixture(), query = {}) {
|
||||
const auth = vue.reactive({ user: { id: 'user-1' }, activeTenant: '1' })
|
||||
const route = vue.reactive({ query })
|
||||
const calls = [], toasts = [], timers = new Map()
|
||||
let mount, unmount, timerId = 0
|
||||
const scope = vue.effectScope()
|
||||
const context = vm.createContext({
|
||||
ref: vue.ref, reactive: vue.reactive, computed: vue.computed, watch: vue.watch, nextTick: vue.nextTick,
|
||||
useToast: () => ({ add: item => toasts.push(item) }),
|
||||
useAuthStore: () => auth, useRoute: () => route,
|
||||
useRouter: () => ({ replace: async location => { route.query = location.query } }),
|
||||
useNuxtApp: () => ({ $api: (url, options) => { calls.push({ url, options }); return api(url, options) } }),
|
||||
onMounted: handler => { mount = handler }, onBeforeUnmount: handler => { unmount = handler },
|
||||
window: { setInterval: handler => { timers.set(++timerId, handler); return timerId } },
|
||||
clearInterval: id => timers.delete(id), document: { hidden: false },
|
||||
})
|
||||
scope.run(() => vm.runInContext(source, context))
|
||||
return { auth, route, calls, toasts, timers, mount, close: () => { unmount(); scope.stop() }, run: code => vm.runInContext(code, context) }
|
||||
}
|
||||
|
||||
test('only member rooms enter normal chat, with separate keys, groups and unread counts', async t => {
|
||||
const ui = setup()
|
||||
t.after(ui.close)
|
||||
await ui.run('refreshLists()')
|
||||
assert.equal(ui.run('decoratedRooms.value.length'), 2)
|
||||
assert.equal(ui.run('decoratedRooms.value.find(r => r.source === "collaboration").key'), 'collaboration:shared-room')
|
||||
assert.equal(ui.run('groupedRooms.value.at(-1).label'), 'Zusammenarbeit')
|
||||
assert.equal(ui.run('decoratedRooms.value.at(-1).unread'), 3)
|
||||
assert.equal(ui.run('decoratedRooms.value[0].unread'), 2)
|
||||
assert.equal(ui.run('decoratedRooms.value.some(r => r.id === "admin-only")'), false)
|
||||
})
|
||||
|
||||
test('opening a collaboration deep link never provisions, reads or sends through native chat APIs', async t => {
|
||||
const ui = setup(fixture(), { room: 'collaboration:shared-room' })
|
||||
t.after(ui.close)
|
||||
ui.mount()
|
||||
await settle()
|
||||
assert.equal(ui.run('isCollaboration.value'), true)
|
||||
assert.equal(ui.route.query.room, 'collaboration:shared-room')
|
||||
ui.run('draft.value = "Partnernachricht"')
|
||||
await ui.run('pollMessages()')
|
||||
await ui.run('sendMessage()')
|
||||
assert.equal(ui.calls.some(({ url }) => url.startsWith('/api/communication/chat/rooms/')), false)
|
||||
ui.route.query = { room: 'allgemein' }
|
||||
await settle()
|
||||
assert.equal(ui.run('isInternal.value'), true)
|
||||
assert.equal(ui.run('messages.value[0].body'), 'Interne Nachricht')
|
||||
ui.route.query = { room: 'collaboration:shared-room' }
|
||||
await settle()
|
||||
assert.equal(ui.run('isCollaboration.value'), true)
|
||||
assert.equal(ui.run('messages.value.length'), 0)
|
||||
})
|
||||
|
||||
test('accepting an invitation opens the returned local binding and clears the invitation', async t => {
|
||||
let accepted = false
|
||||
const ui = setup(fixture(url => {
|
||||
if (url === '/api/collaboration/invitations/invite/accept') { accepted = true; return { roomId: sharedRoom.id } }
|
||||
if (url === '/api/collaboration') return { rooms: accepted ? [sharedRoom] : [], invitations: accepted ? [] : [{ id: 'invite' }] }
|
||||
}))
|
||||
t.after(ui.close)
|
||||
ui.mount()
|
||||
await settle()
|
||||
assert.equal(ui.run('invitations.value.length'), 1)
|
||||
await ui.run('respondToInvitation("invite", true)')
|
||||
assert.equal(ui.run('invitations.value.length'), 0)
|
||||
assert.equal(ui.run('isCollaboration.value'), true)
|
||||
assert.equal(ui.route.query.room, 'collaboration:shared-room')
|
||||
assert.equal(ui.calls.find(({ url }) => url.endsWith('/accept')).options.method, 'POST')
|
||||
})
|
||||
|
||||
test('declining an invitation keeps the current chat open', async t => {
|
||||
let declined = false
|
||||
const ui = setup(fixture(url => {
|
||||
if (url.endsWith('/invite/decline')) { declined = true; return { ok: true } }
|
||||
if (url === '/api/collaboration') return { rooms: [], invitations: declined ? [] : [{ id: 'invite' }] }
|
||||
}))
|
||||
t.after(ui.close)
|
||||
ui.mount()
|
||||
await settle()
|
||||
await ui.run('respondToInvitation("invite", false)')
|
||||
assert.equal(ui.run('invitations.value.length'), 0)
|
||||
assert.equal(ui.run('activeRoomKey.value'), 'allgemein')
|
||||
assert.equal(ui.run('messages.value[0].body'), 'Interne Nachricht')
|
||||
})
|
||||
|
||||
test('a late native room load cannot populate a collaboration room or mark it read', async t => {
|
||||
const pending = deferred()
|
||||
const ui = setup(fixture(url => url.endsWith('/allgemein/messages') ? pending.promise : undefined))
|
||||
t.after(ui.close)
|
||||
ui.mount()
|
||||
await settle()
|
||||
await ui.run('selectRoom(decoratedRooms.value.find(r => r.source === "collaboration"))')
|
||||
pending.resolve({ messages: [{ id: 99, body: 'Late private content' }] })
|
||||
await settle()
|
||||
assert.equal(ui.run('messages.value.length'), 0)
|
||||
assert.equal(ui.run('members.value.length'), 0)
|
||||
assert.equal(ui.run('roomLoading.value'), false)
|
||||
assert.equal(ui.calls.some(({ url }) => url.endsWith('/read')), false)
|
||||
})
|
||||
|
||||
test('late sync and send results cannot overwrite the selected collaboration room', async t => {
|
||||
const sync = deferred(), send = deferred()
|
||||
const ui = setup(fixture((url, options) => {
|
||||
if (url.includes('/sync?')) return sync.promise
|
||||
if (url.endsWith('/messages') && options?.method === 'POST') return send.promise
|
||||
}))
|
||||
t.after(ui.close)
|
||||
ui.mount()
|
||||
await settle()
|
||||
const polling = ui.run('pollMessages()')
|
||||
ui.run('draft.value = "Internal draft"')
|
||||
const sending = ui.run('sendMessage()')
|
||||
await ui.run('selectRoom(decoratedRooms.value.find(r => r.source === "collaboration"))')
|
||||
const reads = ui.calls.filter(({ url }) => url.endsWith('/read')).length
|
||||
sync.resolve({ messages: [{ id: 2, body: 'Late sync' }] })
|
||||
send.resolve({ id: 3, body: 'Late sent message' })
|
||||
await Promise.all([polling, sending])
|
||||
assert.equal(ui.run('messages.value.length'), 0)
|
||||
assert.equal(ui.run('draft.value'), '')
|
||||
assert.equal(ui.run('sending.value'), false)
|
||||
assert.equal(ui.calls.filter(({ url }) => url.endsWith('/read')).length, reads)
|
||||
})
|
||||
|
||||
test('switching tenants clears visible content immediately and ignores older room lists', async t => {
|
||||
const stale = deferred(), fresh = deferred()
|
||||
let lists = 0
|
||||
const ui = setup(fixture(url => {
|
||||
if (url === '/api/collaboration') return ++lists === 1 ? stale.promise : fresh.promise
|
||||
}))
|
||||
t.after(ui.close)
|
||||
ui.mount()
|
||||
ui.run('messages.value = [{ id: 1, body: "Previous tenant" }]; draft.value = "Private draft"')
|
||||
ui.auth.activeTenant = '2'
|
||||
assert.equal(ui.run('messages.value.length'), 0)
|
||||
assert.equal(ui.run('collaborationRooms.value.length'), 0)
|
||||
assert.equal(ui.run('draft.value'), '')
|
||||
assert.equal(ui.run('session.value'), 'user-1:2')
|
||||
fresh.resolve({ rooms: [{ id: 'tenant-2' }], invitations: [] })
|
||||
await settle()
|
||||
stale.resolve({ rooms: [{ id: 'tenant-1-secret' }], invitations: [{ id: 'private-invite' }] })
|
||||
await settle()
|
||||
assert.equal(ui.run('collaborationRooms.value[0].id'), 'tenant-2')
|
||||
assert.equal(ui.run('invitations.value.length'), 0)
|
||||
})
|
||||
|
||||
test('collaboration and internal service failures do not block the other room type', async t => {
|
||||
const ui = setup(fixture(url => {
|
||||
if (url === '/api/collaboration') throw { statusCode: 503, data: { message: 'Unterräume nicht erreichbar' } }
|
||||
}))
|
||||
t.after(ui.close)
|
||||
ui.mount()
|
||||
await settle()
|
||||
assert.equal(ui.run('isInternal.value'), true)
|
||||
assert.equal(ui.run('messages.value.length'), 1)
|
||||
assert.equal(ui.run('collaborationError.value'), 'Unterräume nicht erreichbar')
|
||||
const other = setup(fixture(url => {
|
||||
if (url === '/api/communication/chat/rooms') throw { statusCode: 409, data: { message: 'Chat nicht verfügbar' } }
|
||||
}), { room: 'collaboration:shared-room' })
|
||||
t.after(other.close)
|
||||
other.mount()
|
||||
await settle()
|
||||
assert.equal(other.run('isCollaboration.value'), true)
|
||||
assert.equal(other.run('listError.value'), 'Chat nicht verfügbar')
|
||||
})
|
||||
|
||||
test('revoked membership removes the active collaboration room instead of exposing managed rooms', async t => {
|
||||
let revoked = false
|
||||
const ui = setup(fixture(url => {
|
||||
if (url === '/api/collaboration' && revoked) return { rooms: [], invitations: [], managedRooms: [sharedRoom] }
|
||||
}), { room: 'collaboration:shared-room' })
|
||||
t.after(ui.close)
|
||||
ui.mount()
|
||||
await settle()
|
||||
assert.equal(ui.run('isCollaboration.value'), true)
|
||||
revoked = true
|
||||
await ui.run('loadCollaboration()')
|
||||
assert.equal(ui.run('activeRoom.value'), null)
|
||||
assert.equal(ui.run('isCollaboration.value'), false)
|
||||
assert.equal(ui.run('isInternal.value'), false)
|
||||
})
|
||||
|
||||
test('logout clears the room and invitations without starting requests with the previous credentials', async t => {
|
||||
const ui = setup(fixture(), { room: 'collaboration:shared-room' })
|
||||
t.after(ui.close)
|
||||
ui.mount()
|
||||
await settle()
|
||||
const calls = ui.calls.length
|
||||
ui.auth.user = null
|
||||
await settle()
|
||||
await ui.run('refreshLists()')
|
||||
assert.equal(ui.run('activeRoom.value'), null)
|
||||
assert.equal(ui.run('invitations.value.length'), 0)
|
||||
assert.equal(ui.calls.length, calls)
|
||||
})
|
||||
|
||||
test('unmount cancels both polling timers and ignores pending lists', async () => {
|
||||
const pending = deferred()
|
||||
const ui = setup(fixture(url => url === '/api/collaboration' ? pending.promise : undefined))
|
||||
ui.mount()
|
||||
assert.equal(ui.timers.size, 2)
|
||||
ui.close()
|
||||
pending.resolve({ rooms: [sharedRoom], invitations: [] })
|
||||
await settle()
|
||||
assert.equal(ui.timers.size, 0)
|
||||
assert.equal(ui.run('collaborationRooms.value.length'), 0)
|
||||
assert.equal(ui.run('messages.value.length'), 0)
|
||||
})
|
||||
|
||||
test('hiding the active room persists the preference, switches away and allows restoring it', async t => {
|
||||
const ui = setup()
|
||||
t.after(ui.close)
|
||||
ui.mount()
|
||||
await settle()
|
||||
await ui.run('setRoomHidden(activeRoom.value, true)')
|
||||
assert.equal(ui.run('hiddenRooms.value[0].key'), 'allgemein')
|
||||
assert.equal(ui.run('visibleRooms.value.some(room => room.key === "allgemein")'), false)
|
||||
assert.equal(ui.run('isCollaboration.value'), true)
|
||||
assert.equal(ui.run('messages.value.length'), 0)
|
||||
const save = ui.calls.find(call => call.url.endsWith('/room-preferences') && call.options?.method === 'PUT')
|
||||
assert.equal(save.options.body.roomKey, 'allgemein')
|
||||
assert.equal(save.options.body.hidden, true)
|
||||
await ui.run('setRoomHidden(hiddenRooms.value[0], false)')
|
||||
assert.equal(ui.run('hiddenRooms.value.length'), 0)
|
||||
assert.equal(ui.run('activeRoomKey.value'), 'allgemein')
|
||||
assert.equal(ui.run('messages.value[0].body'), 'Interne Nachricht')
|
||||
})
|
||||
|
||||
test('saved hidden rooms stay hidden on reload, including federated room deep links', async t => {
|
||||
const ui = setup(fixture(url => url.endsWith('/room-preferences') ? { hiddenRoomKeys: ['collaboration:shared-room', 'allgemein'] } : undefined), { room: 'collaboration:shared-room' })
|
||||
t.after(ui.close)
|
||||
ui.mount()
|
||||
await settle()
|
||||
assert.equal(ui.run('visibleRooms.value.length'), 0)
|
||||
assert.equal(ui.run('activeRoom.value'), null)
|
||||
assert.equal(ui.calls.some(({ url }) => /\/rooms\/.+\/(messages|read)/.test(url)), false)
|
||||
await ui.run('selectRoom(decoratedRooms.value[0])')
|
||||
assert.equal(ui.run('activeRoom.value'), null)
|
||||
await ui.run('setRoomHidden(hiddenRooms.value.find(r => r.source === "collaboration"), false)')
|
||||
assert.equal(ui.run('isCollaboration.value'), true)
|
||||
})
|
||||
|
||||
test('preference save failure leaves the active conversation and list unchanged', async t => {
|
||||
const ui = setup(fixture((url, options) => {
|
||||
if (url.endsWith('/room-preferences') && options?.method === 'PUT') throw { data: { message: 'Speichern fehlgeschlagen' } }
|
||||
}))
|
||||
t.after(ui.close)
|
||||
ui.mount()
|
||||
await settle()
|
||||
await ui.run('setRoomHidden(activeRoom.value, true)')
|
||||
assert.equal(ui.run('hiddenRooms.value.length'), 0)
|
||||
assert.equal(ui.run('activeRoomKey.value'), 'allgemein')
|
||||
assert.equal(ui.run('messages.value[0].body'), 'Interne Nachricht')
|
||||
assert.equal(ui.toasts.at(-1).title, 'Speichern fehlgeschlagen')
|
||||
})
|
||||
|
||||
test('pending hide operations cannot change a new tenant, and hiding the last room clears its content', async t => {
|
||||
const pending = deferred()
|
||||
const ui = setup(fixture((url, options) => {
|
||||
if (url.endsWith('/room-preferences') && options?.method === 'PUT') return pending.promise
|
||||
}))
|
||||
t.after(ui.close)
|
||||
ui.mount()
|
||||
await settle()
|
||||
const hiding = ui.run('setRoomHidden(activeRoom.value, true)')
|
||||
ui.auth.activeTenant = '2'
|
||||
await settle()
|
||||
pending.resolve({ hidden: true, roomKey: 'allgemein' })
|
||||
await hiding
|
||||
assert.equal(ui.run('hiddenRoomKeys.value.length'), 0)
|
||||
assert.equal(ui.run('activeRoomKey.value'), 'allgemein')
|
||||
const single = setup(fixture(url => url === '/api/collaboration' ? { rooms: [], invitations: [] } : undefined))
|
||||
t.after(single.close)
|
||||
single.mount()
|
||||
await settle()
|
||||
await single.run('setRoomHidden(activeRoom.value, true)')
|
||||
await settle()
|
||||
assert.equal(single.run('activeRoom.value'), null)
|
||||
assert.equal(single.run('messages.value.length'), 0)
|
||||
assert.equal(single.run('members.value.length'), 0)
|
||||
assert.equal(single.run('visibleRooms.value.length'), 0)
|
||||
})
|
||||
|
||||
test('removing an active project from the permitted room list clears its messages and members', async t => {
|
||||
let disabled = false
|
||||
const ui = setup(fixture(url => url.endsWith('/project-rooms') ? { rooms: disabled ? [] : [{ key: 'project_1', exists: true, type: 'project' }] } : undefined), { room: 'project_1' })
|
||||
t.after(ui.close)
|
||||
ui.mount()
|
||||
await settle()
|
||||
assert.equal(ui.run('messages.value.length'), 1)
|
||||
disabled = true
|
||||
await ui.run('loadRoomLists()')
|
||||
await settle()
|
||||
assert.equal(ui.run('activeRoom.value'), null)
|
||||
assert.equal(ui.run('messages.value.length'), 0)
|
||||
assert.equal(ui.run('members.value.length'), 0)
|
||||
})
|
||||
@@ -167,6 +167,84 @@ test('filing failure preserves the document and selected values for retry', asyn
|
||||
assert.equal(ui.run('canFile.value'), true)
|
||||
})
|
||||
|
||||
test('archiving needs no classification, waits for confirmation and updates the list, preview and badge', async t => {
|
||||
const pending = deferred()
|
||||
const staleList = deferred()
|
||||
const requests = []
|
||||
let listings = 0
|
||||
const ui = setup((url, options) => {
|
||||
requests.push({ url, options })
|
||||
if (url.endsWith('/archive')) return pending.promise
|
||||
if (url.endsWith('/filing-options')) return Promise.resolve({ folders: [], types: [] })
|
||||
if (url.endsWith('/suggestion')) return Promise.resolve({ status: 'pending', suggestion: null })
|
||||
if (++listings === 1) return staleList.promise
|
||||
return Promise.resolve({ documents: [{ id: 'remaining' }], total: 50 })
|
||||
})
|
||||
t.after(ui.close)
|
||||
ui.run('documents.value = [{ id: "scan", name: "scan.pdf" }]; total.value = 51; page.value = 2')
|
||||
await ui.run('openPreview(documents.value[0])')
|
||||
await settle()
|
||||
assert.equal(ui.run('canFile.value'), false)
|
||||
ui.run('openArchive(documents.value[0])')
|
||||
assert.equal(requests.some(request => request.url.endsWith('/archive')), false)
|
||||
const listing = ui.run('load(true)')
|
||||
const saving = ui.run('archiveDocument()')
|
||||
await ui.run('archiveDocument()')
|
||||
await ui.run('fileDocument()')
|
||||
assert.equal(requests.filter(request => request.url.endsWith('/archive')).length, 1)
|
||||
assert.equal(requests.some(request => request.url.endsWith('/file')), false)
|
||||
assert.equal(ui.run('documents.value.length'), 1)
|
||||
pending.resolve({ id: 'scan', archived: true })
|
||||
await saving
|
||||
staleList.resolve({ documents: [{ id: 'scan' }], total: 51 })
|
||||
await listing
|
||||
assert.equal(requests.find(request => request.url.endsWith('/archive')).options.method, 'POST')
|
||||
assert.equal(ui.run('archiveOpen.value'), false)
|
||||
assert.equal(ui.run('previewOpen.value'), false)
|
||||
assert.equal(ui.run('documents.value[0].id'), 'remaining')
|
||||
assert.equal(ui.run('total.value'), 50)
|
||||
assert.equal(ui.run('page.value'), 1)
|
||||
assert.equal(ui.countRefreshes(), 1)
|
||||
})
|
||||
|
||||
test('archive cancellation and failure preserve the document and allow a retry from the list', async t => {
|
||||
let calls = 0
|
||||
const ui = setup(async () => { calls++; throw { data: { message: 'Archivieren fehlgeschlagen' } } })
|
||||
t.after(ui.close)
|
||||
ui.run('documents.value = [{ id: "scan", name: "scan.pdf" }]; total.value = 1; openArchive(documents.value[0])')
|
||||
await settle()
|
||||
ui.run('archiveOpen.value = false')
|
||||
await settle()
|
||||
assert.equal(ui.run('archiveTarget.value'), null)
|
||||
assert.equal(calls, 0)
|
||||
ui.run('openArchive(documents.value[0])')
|
||||
await ui.run('archiveDocument()')
|
||||
assert.equal(ui.run('archiveError.value'), 'Archivieren fehlgeschlagen')
|
||||
assert.equal(ui.run('archiveOpen.value'), true)
|
||||
assert.equal(ui.run('archiveSaving.value'), false)
|
||||
assert.equal(ui.run('documents.value[0].id'), 'scan')
|
||||
assert.equal(ui.run('total.value'), 1)
|
||||
assert.equal(ui.countRefreshes(), 0)
|
||||
})
|
||||
|
||||
test('archive responses from a previous tenant or unmounted page cannot update the current view', async t => {
|
||||
for (const action of ['tenant', 'unmount']) {
|
||||
const pending = deferred()
|
||||
const ui = setup(url => url.endsWith('/archive') ? pending.promise : Promise.resolve({ documents: [{ id: 'tenant-2' }], total: 1 }))
|
||||
t.after(ui.close)
|
||||
ui.run('documents.value = [{ id: "scan", name: "scan.pdf" }]; total.value = 1; openArchive(documents.value[0])')
|
||||
const saving = ui.run('archiveDocument()')
|
||||
if (action === 'tenant') ui.auth.activeTenant = '2'
|
||||
else ui.close()
|
||||
await settle()
|
||||
pending.resolve({ id: 'scan', archived: true })
|
||||
await saving
|
||||
assert.equal(ui.run('documents.value[0].id'), action === 'tenant' ? 'tenant-2' : 'scan')
|
||||
assert.equal(ui.countRefreshes(), 0)
|
||||
if (action === 'tenant') assert.equal(ui.run('archiveOpen.value'), false)
|
||||
}
|
||||
})
|
||||
|
||||
test('tenant switching discards pending folder options and filing responses', async t => {
|
||||
for (const stage of ['options', 'save']) {
|
||||
const pending = deferred()
|
||||
|
||||
@@ -82,14 +82,14 @@ async function sendTestPush() {
|
||||
});
|
||||
await Promise.all([refreshInstance(), refreshJobs(), refreshDevices()]);
|
||||
toast.add({
|
||||
title: "Test-Push gesendet",
|
||||
description: `${result.sent ?? 0} gesendet, ${result.failed ?? 0} fehlgeschlagen`,
|
||||
color: result.failed ? "warning" : "success",
|
||||
title: result.failed ? (result.sent ? "Test-Push teilweise fehlgeschlagen" : "Test-Push fehlgeschlagen") : "Test-Push gesendet",
|
||||
description: [`${result.sent ?? 0} gesendet, ${result.failed ?? 0} fehlgeschlagen`, result.lastErrorCode, result.lastErrorMessage].filter(Boolean).join(" · "),
|
||||
color: result.failed ? (result.sent ? "warning" : "error") : "success",
|
||||
});
|
||||
} catch (error: any) {
|
||||
toast.add({
|
||||
title: "Test-Push fehlgeschlagen",
|
||||
description: error?.data?.message || error?.message || "Die Testnachricht konnte nicht gesendet werden.",
|
||||
description: error?.data?.message || error?.data?.error || error?.message || "Die Testnachricht konnte nicht gesendet werden.",
|
||||
color: "error",
|
||||
});
|
||||
} finally {
|
||||
@@ -246,6 +246,7 @@ async function sendTestPush() {
|
||||
<th>Angenommen</th>
|
||||
<th>Gesendet</th>
|
||||
<th>Fehler</th>
|
||||
<th>Letzter Fehler</th>
|
||||
<th>Erstellt</th>
|
||||
</tr>
|
||||
</thead>
|
||||
@@ -256,6 +257,10 @@ async function sendTestPush() {
|
||||
<td>{{ job.acceptedCount }}</td>
|
||||
<td>{{ job.sentCount }}</td>
|
||||
<td>{{ job.failedCount }}</td>
|
||||
<td>
|
||||
<div>{{ job.lastErrorCode || "-" }}</div>
|
||||
<div v-if="job.lastErrorMessage" class="text-sm text-gray-500">{{ job.lastErrorMessage }}</div>
|
||||
</td>
|
||||
<td>{{ new Date(job.createdAt).toLocaleString() }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
|
||||
@@ -420,6 +420,40 @@ class UpdateTests(unittest.TestCase):
|
||||
self.assertLess(next(i for i, a in enumerate(calls) if 'pull' in a), next(i for i, a in enumerate(calls) if 'stop' in a))
|
||||
self.assertLess(next(i for i, a in enumerate(calls) if 'pg_restore' in a), next(i for i, a in enumerate(calls) if 'migrate' in a))
|
||||
|
||||
def use_pre_federation_installation(self, extra_env=b''):
|
||||
keys = (b'FEDEO_PUBLIC_URL', b'FEDEO_FEDERATION_URL', b'FEDEO_FEDERATION_ENABLED')
|
||||
self.original_env = b''.join(line for line in self.original_env.splitlines(True)
|
||||
if not line.startswith(keys)) + extra_env
|
||||
self.original_compose = b''.join(line for line in self.original_compose.splitlines(True)
|
||||
if not line.lstrip().startswith(keys))
|
||||
(self.root / '.env').write_bytes(self.original_env)
|
||||
(self.root / 'docker-compose.yml').write_bytes(self.original_compose)
|
||||
|
||||
def test_update_adds_federation_compose_defaults_without_requiring_new_env_settings(self):
|
||||
self.use_pre_federation_installation()
|
||||
result = self.run_update()
|
||||
self.assertEqual(result['status'], 'succeeded')
|
||||
env = self.updater.candidate['services']['backend']['environment']
|
||||
self.assertEqual(env['FEDEO_FEDERATION_ENABLED'], 'auto')
|
||||
self.assertEqual(env['API_BASE_URL'], 'https://app.example.com/backend')
|
||||
self.assertEqual(env['FEDEO_FEDERATION_URL'], '')
|
||||
self.assertEqual(env['FEDEO_PUBLIC_URL'], '')
|
||||
self.assertEqual((self.root / '.env').read_bytes(), u.set_version(self.original_env, '3.1.0'))
|
||||
self.assertIn(b'FEDEO_FEDERATION_ENABLED', (self.root / 'docker-compose.yml').read_bytes())
|
||||
|
||||
def test_update_preserves_explicit_federation_opt_out_and_url_overrides(self):
|
||||
self.use_pre_federation_installation(
|
||||
b'\nFEDEO_FEDERATION_ENABLED=false\n'
|
||||
b'FEDEO_FEDERATION_URL=https://gateway.example/backend\n'
|
||||
b'FEDEO_PUBLIC_URL=https://portal.example\n')
|
||||
result = self.run_update()
|
||||
self.assertEqual(result['status'], 'succeeded')
|
||||
env = self.updater.candidate['services']['backend']['environment']
|
||||
self.assertEqual(env['FEDEO_FEDERATION_ENABLED'], 'false')
|
||||
self.assertEqual(env['FEDEO_FEDERATION_URL'], 'https://gateway.example/backend')
|
||||
self.assertEqual(env['FEDEO_PUBLIC_URL'], 'https://portal.example')
|
||||
self.assertEqual((self.root / '.env').read_bytes(), u.set_version(self.original_env, '3.1.0'))
|
||||
|
||||
def test_check_only_creates_a_plan_and_ignores_unpublished_releases(self):
|
||||
result = self.updater.execute('check')
|
||||
self.assertEqual(result['version'], '3.1.0')
|
||||
|
||||
Reference in New Issue
Block a user