// @vitest-environment node import { notify, type NotificationClient } from "@hivegrid/foundation"; import { afterAll, beforeAll, describe, expect, test } from "vitest"; import { runAutomationExecutionJob, type AutomationExecutorDeps } from "./automation-executor.server.js"; import { createDbClient, type DbClient } from "./client.server.js"; const DATABASE_URL = process.env.AUTOMATION_EXECUTOR_E2E_DATABASE_URL; const describeIfDatabase = DATABASE_URL ? describe : describe.skip; const RUN_ID = `automation-e2e-${process.pid}`; const TENANT_ID = `${RUN_ID}-tenant`; const USER_ID = `${RUN_ID}-user`; type RuleStepSeed = { readonly stepKey: string; readonly stepKind: "trigger" | "condition" | "action" | "flow_control"; readonly nodeType: string; readonly parentStepIds: readonly string[]; readonly config?: Record; }; describeIfDatabase("automation executor real PostgreSQL", () => { let client: DbClient; beforeAll(async () => { client = createDbClient({ connectionString: DATABASE_URL!, poolMax: 2 }); await client.tenant.create({ data: { id: TENANT_ID, slug: RUN_ID, name: "Automation E2E", active: true } }); await client.user.create({ data: { id: USER_ID, email: `${RUN_ID}@example.test`, firstName: "Automation", lastName: "Owner", active: true, }, }); await client.tenantUser.create({ data: { tenantId: TENANT_ID, userId: USER_ID, type: 0, joined: 1, status: 2 } }); }); afterAll(async () => { if (!client) return; await client.notificationDelivery.deleteMany({ where: { tenantId: TENANT_ID } }); await client.activity.deleteMany({ where: { tenantId: TENANT_ID } }); await client.tagAssignment.deleteMany({ where: { tenantId: TENANT_ID } }); await client.tag.deleteMany({ where: { tenantId: TENANT_ID } }); await client.task.deleteMany({ where: { tenantId: TENANT_ID } }); await client.kwpMaterialPosition.deleteMany({ where: { tenantId: TENANT_ID } }); await client.projektTermin.deleteMany({ where: { tenantId: TENANT_ID } }); await client.projektKontakt.deleteMany({ where: { tenantId: TENANT_ID } }); await client.projekt.deleteMany({ where: { tenantId: TENANT_ID } }); await client.pipelineStage.deleteMany({ where: { tenantId: TENANT_ID } }); await client.pipeline.deleteMany({ where: { tenantId: TENANT_ID } }); await client.kontakt.deleteMany({ where: { tenantId: TENANT_ID } }); await client.inboxLead.deleteMany({ where: { tenantId: TENANT_ID } }); await client.leadAntiSpamConfig.deleteMany({ where: { tenantId: TENANT_ID } }); await client.automationRule.deleteMany({ where: { tenantId: TENANT_ID } }); await client.outboxEvent.deleteMany({ where: { tenantId: TENANT_ID } }); await client.tenantUser.deleteMany({ where: { tenantId: TENANT_ID } }); await client.tenant.deleteMany({ where: { id: TENANT_ID } }); await client.user.deleteMany({ where: { id: USER_ID } }); await client.$disconnect(); }); test("persists condition, CRM, loop, task, notification, mail and HTTP effects", async () => { const kontakt = await client.kontakt.create({ data: { tenantId: TENANT_ID, createdByUserId: USER_ID, kontaktTyp: "privatperson", kontaktStatus: "kontakt", vorname: "Klara", nachname: "Kern", primaerEmail: "klara@example.test", }, }); const tag = await client.tag.create({ data: { tenantId: TENANT_ID, name: "Automation VIP", farbe: "#2563EB" } }); const projectId = `${RUN_ID}-project`; await client.task.createMany({ data: [ { tenantId: TENANT_ID, createdByUserId: USER_ID, title: "Heizung prüfen", status: "open", priority: "normal", assignedToUserId: USER_ID, linkedEntityType: "project", linkedEntityId: projectId, }, { tenantId: TENANT_ID, createdByUserId: USER_ID, title: "Material klären", status: "blocked", priority: "high", assignedToUserId: USER_ID, linkedEntityType: "project", linkedEntityId: projectId, }, ], }); const loopSourceIds = ( await client.task.findMany({ where: { tenantId: TENANT_ID, linkedEntityType: "project", linkedEntityId: projectId }, select: { id: true }, }) ).map((task) => task.id); const { executionId } = await seedExecution(client, "core", "webhook.received", { projectId, kontaktId: kontakt.id, status: "aktiv" }, [ { stepKey: "trigger", stepKind: "trigger", nodeType: "webhook.received", parentStepIds: [] }, { stepKey: "condition", stepKind: "condition", nodeType: "condition.if_else", parentStepIds: ["trigger"], config: { feld: "status", vergleich: "istGleich", wert: "aktiv" }, }, { stepKey: "update-contact", stepKind: "action", nodeType: "crm.update_kontakt", parentStepIds: ["condition"], config: { kontakt: "ausloeser", feld: "kontaktStatus", wert: "kunde" }, }, { stepKey: "note", stepKind: "action", nodeType: "crm.create_note", parentStepIds: ["update-contact"], config: { datensatz: "kontaktAusAusloeser", notiztext: "Automation geprüft" }, }, { stepKey: "add-tag", stepKind: "action", nodeType: "crm.add_tag", parentStepIds: ["note"], config: { kontakt: "ausloeser", tagId: tag.id }, }, { stepKey: "assign-contact", stepKind: "action", nodeType: "crm.assign_kontakt", parentStepIds: ["add-tag"], config: { kontakt: "ausloeser", userId: USER_ID }, }, { stepKey: "remove-tag", stepKind: "action", nodeType: "crm.remove_tag", parentStepIds: ["assign-contact"], config: { kontakt: "ausloeser", tagId: tag.id }, }, { stepKey: "loop", stepKind: "flow_control", nodeType: "loop.for_each", parentStepIds: ["remove-tag"], config: { liste: "offeneAufgabenDesProjekts", maxDurchlaeufe: "10" }, }, { stepKey: "create-task", stepKind: "action", nodeType: "task.create", parentStepIds: ["loop"], config: { titel: "Nachfassen: {{loop.item.title}}", zustaendig: "besitzerDerAutomation", prioritaet: "normal" }, }, { stepKey: "assign-task", stepKind: "action", nodeType: "task.assign", parentStepIds: ["create-task"], config: { aufgabe: "ausVorherigemSchritt", zustaendig: "erstellerDerAufgabe", benachrichtigungAn: "niemand" }, }, { stepKey: "notify", stepKind: "action", nodeType: "notification.send", parentStepIds: ["assign-task"], config: { kanal: "intern", empfaenger: "besitzerDerAutomation", betreff: "Element {{loop.position}}", nachricht: "{{loop.item.title}}" }, }, { stepKey: "mail", stepKind: "action", nodeType: "email.send_transactional", parentStepIds: ["notify"], config: { an: "klara@example.test", betreff: "Element {{loop.position}}", nachricht: "{{loop.item.title}}" }, }, { stepKey: "http", stepKind: "action", nodeType: "http.request", parentStepIds: ["mail"], config: { url: "https://hooks.example.test/items/{{loop.item.id}}", methode: "post", koerper: '{"position":{{loop.position}}}' }, }, ]); const httpCalls: Array<{ url: string; method: string; body?: string }> = []; const result = await runAutomationExecutionJob( { tenantId: TENANT_ID, executionId }, executorDeps(client, { fetchOutboundHttp: async (input) => { httpCalls.push(input); return { status: 202, ok: true }; }, }) ); expect(result.status).toBe("completed"); expect(await client.automationExecution.findUnique({ where: { id: executionId }, select: { status: true } })).toEqual({ status: "success" }); expect(await client.kontakt.findUnique({ where: { id: kontakt.id }, select: { kontaktStatus: true, zustaendigerUserId: true } })).toEqual({ kontaktStatus: "kunde", zustaendigerUserId: USER_ID, }); expect(await client.tagAssignment.count({ where: { tenantId: TENANT_ID, tagId: tag.id, entityId: kontakt.id, entityType: "kontakt" } })).toBe(0); expect( await client.automationStepExecution.findMany({ where: { tenantId: TENANT_ID, executionId, stepKey: { in: ["add-tag", "assign-contact", "remove-tag"] } }, orderBy: { sortOrder: "asc" }, select: { stepKey: true, status: true, output: true }, }) ).toEqual([ { stepKey: "add-tag", status: "success", output: expect.objectContaining({ tagId: tag.id, changed: true }) }, { stepKey: "assign-contact", status: "success", output: expect.objectContaining({ assignedToUserId: USER_ID, changed: true }) }, { stepKey: "remove-tag", status: "success", output: expect.objectContaining({ tagId: tag.id, changed: true }) }, ]); expect(await client.activity.count({ where: { tenantId: TENANT_ID, subjectId: kontakt.id, activityType: "note" } })).toBe(1); expect( await client.task.findMany({ where: { tenantId: TENANT_ID, source: "automation", sourceRef: executionId }, orderBy: { title: "asc" }, select: { title: true, assignedToUserId: true }, }) ).toEqual([ { title: "Nachfassen: Heizung prüfen", assignedToUserId: USER_ID }, { title: "Nachfassen: Material klären", assignedToUserId: USER_ID }, ]); expect(await client.notificationDelivery.count({ where: { tenantId: TENANT_ID, category: "automation" } })).toBe(2); expect(await client.outboxEvent.count({ where: { tenantId: TENANT_ID, eventType: "mail.transactional.send" } })).toBe(2); expect(httpCalls).toHaveLength(2); expect(httpCalls.map((call) => call.url).sort()).toEqual(loopSourceIds.map((id) => `https://hooks.example.test/items/${id}`).sort()); expect(await client.automationStepExecution.count({ where: { tenantId: TENANT_ID, executionId, status: "failed" } })).toBe(0); }); test("assigns and qualifies a typed lead with reverse-compatible outputs", async () => { const lead = await client.inboxLead.create({ data: { tenantId: TENANT_ID, createdByUserId: USER_ID, quelle: "form", status: "new", weiterverarbeitungFreigabe: "unklar", vorname: "Lena", nachname: "Lead", email: "lena@example.test", }, }); const { executionId } = await seedExecution(client, "lead-actions", "lead.captured", { leadId: lead.id }, [ { stepKey: "trigger", stepKind: "trigger", nodeType: "lead.captured", parentStepIds: [] }, { stepKey: "assign-lead", stepKind: "action", nodeType: "lead.assign", parentStepIds: ["trigger"], config: { lead: "ausloeser", userId: USER_ID }, }, { stepKey: "qualify-lead", stepKind: "action", nodeType: "lead.set_status", parentStepIds: ["assign-lead"], config: { lead: "ausloeser", status: "qualified" }, }, ]); expect((await runAutomationExecutionJob({ tenantId: TENANT_ID, executionId }, executorDeps(client))).status).toBe("completed"); expect( await client.inboxLead.findUnique({ where: { id: lead.id }, select: { zustaendigerUserId: true, status: true, weiterverarbeitungFreigabe: true }, }) ).toEqual({ zustaendigerUserId: USER_ID, status: "qualified", weiterverarbeitungFreigabe: "ja" }); expect( await client.automationStepExecution.findMany({ where: { tenantId: TENANT_ID, executionId, stepKey: { in: ["assign-lead", "qualify-lead"] } }, orderBy: { sortOrder: "asc" }, select: { stepKey: true, status: true, output: true }, }) ).toEqual([ { stepKey: "assign-lead", status: "success", output: expect.objectContaining({ leadId: lead.id, assignedToUserId: USER_ID, changed: true, before: { zustaendigerUserId: null } }), }, { stepKey: "qualify-lead", status: "success", output: expect.objectContaining({ leadId: lead.id, status: "qualified", changed: true, before: expect.objectContaining({ status: "new" }) }), }, ]); const workflowEvents = await client.outboxEvent.findMany({ where: { tenantId: TENANT_ID, eventType: "workflow.trigger.event", dispatchKey: { contains: "automation:" } }, select: { payload: true }, orderBy: { createdAt: "asc" }, }); expect(workflowEvents.slice(-2).map((row) => (row.payload as Record).event)).toEqual(["lead.assigned", "lead.qualified"]); expect(await client.activity.count({ where: { tenantId: TENANT_ID, subjectType: "lead", subjectId: lead.id } })).toBe(2); }); test("persists a delay continuation and resumes it exactly once", async () => { const startedAt = new Date("2026-08-01T10:00:00.000Z"); const clock = { now: startedAt }; const { executionId } = await seedExecution(client, "delay", "time.schedule", {}, [ { stepKey: "trigger", stepKind: "trigger", nodeType: "time.schedule", parentStepIds: [] }, { stepKey: "delay", stepKind: "flow_control", nodeType: "delay.wait", parentStepIds: ["trigger"], config: { dauer: "1", dauerEinheit: "minuten" }, }, { stepKey: "notify", stepKind: "action", nodeType: "notification.send", parentStepIds: ["delay"], config: { kanal: "intern", empfaenger: "besitzerDerAutomation", betreff: "Weiter", nachricht: "Wartezeit beendet" }, }, ]); const deps = executorDeps(client, { now: () => clock.now }); expect((await runAutomationExecutionJob({ tenantId: TENANT_ID, executionId }, deps)).status).toBe("waiting"); expect( await client.outboxEvent.count({ where: { tenantId: TENANT_ID, eventType: "automation.execution.requested", payload: { path: ["executionId"], equals: executionId } }, }) ).toBe(1); clock.now = new Date(startedAt.getTime() + 61_000); expect((await runAutomationExecutionJob({ tenantId: TENANT_ID, executionId }, deps)).status).toBe("completed"); expect( await client.notificationDelivery.count({ where: { tenantId: TENANT_ID, payloadMetadata: { path: ["executionId"], equals: executionId } }, }) ).toBe(1); }); test("reads project contacts, quote positions and weekly appointments from PostgreSQL loop sources", async () => { const pipeline = await client.pipeline.create({ data: { tenantId: TENANT_ID, name: `${RUN_ID}-pipeline`, typHint: "sales", createdByUserId: USER_ID }, }); const stage = await client.pipelineStage.create({ data: { tenantId: TENANT_ID, pipelineId: pipeline.id, name: "Offen", stageKind: "offen" }, }); const project = await client.projekt.create({ data: { id: `${RUN_ID}-loop-project`, tenantId: TENANT_ID, createdByUserId: USER_ID, projektNummer: `${RUN_ID}-001`, projektname: "Loop-Quellen", pipelineId: pipeline.id, stageId: stage.id, }, }); await client.projektKontakt.create({ data: { tenantId: TENANT_ID, projektId: project.id, kontaktId: `${RUN_ID}-linked-contact`, rolle: "ansprechpartner", primaer: true }, }); await client.kwpMaterialPosition.create({ data: { tenantId: TENANT_ID, dataConnectionId: `${RUN_ID}-connection`, projektId: project.id, externalId: `${RUN_ID}-position`, positionNumber: "1", text: "Wärmepumpe", quantity: "1", unit: "Stk", positionMarker: 1, normalizedFingerprint: `${RUN_ID}-fingerprint`, lastSeenAt: new Date("2026-08-01T08:00:00.000Z"), lastSyncedAt: new Date("2026-08-01T08:00:00.000Z"), }, }); await client.projektTermin.create({ data: { tenantId: TENANT_ID, projektId: project.id, createdByUserId: USER_ID, titel: "Montage", startAt: new Date("2026-07-31T08:00:00.000Z"), endAt: new Date("2026-07-31T10:00:00.000Z"), status: "bestaetigt", typ: "vor_ort", }, }); const cases = [ { suffix: "contacts-loop", collection: "kontakteDesProjekts", title: "Kontakt {{loop.item.kontaktId}}", expected: `Kontakt ${RUN_ID}-linked-contact` }, { suffix: "positions-loop", collection: "positionenDesAngebots", title: "Position {{loop.item.text}}", expected: "Position Wärmepumpe" }, { suffix: "appointments-loop", collection: "termineDieserWoche", title: "Termin {{loop.item.titel}}", expected: "Termin Montage" }, ] as const; for (const item of cases) { const { executionId } = await seedExecution(client, item.suffix, "webhook.received", { projectId: project.id }, [ { stepKey: "trigger", stepKind: "trigger", nodeType: "webhook.received", parentStepIds: [] }, { stepKey: "loop", stepKind: "flow_control", nodeType: "loop.for_each", parentStepIds: ["trigger"], config: { liste: item.collection, maxDurchlaeufe: "10" }, }, { stepKey: "create-task", stepKind: "action", nodeType: "task.create", parentStepIds: ["loop"], config: { titel: item.title, zustaendig: "besitzerDerAutomation", prioritaet: "normal" }, }, ]); const now = new Date("2026-08-01T12:00:00.000Z"); expect((await runAutomationExecutionJob({ tenantId: TENANT_ID, executionId }, executorDeps(client, { now: () => now }))).status).toBe("completed"); expect( await client.task.findFirst({ where: { tenantId: TENANT_ID, source: "automation", sourceRef: executionId }, select: { title: true } }) ).toEqual({ title: item.expected }); } }); }); async function seedExecution( client: DbClient, nameSuffix: string, triggerKey: string, triggerPayload: Record, steps: readonly RuleStepSeed[] ): Promise<{ readonly executionId: string }> { const rule = await client.automationRule.create({ data: { tenantId: TENANT_ID, name: `${RUN_ID}-${nameSuffix}`, status: "active", enabled: true, triggerKey, createdByUserId: USER_ID, steps: { create: steps.map((step, sortOrder) => ({ tenantId: TENANT_ID, stepKey: step.stepKey, stepKind: step.stepKind, nodeType: step.nodeType, parentStepIds: [...step.parentStepIds], config: (step.config ?? {}) as never, position: {} as never, sortOrder, summaryText: "automation.execution.stepQueued", })), }, }, include: { steps: { orderBy: { sortOrder: "asc" } } }, }); const execution = await client.automationExecution.create({ data: { tenantId: TENANT_ID, ruleId: rule.id, triggerKey, triggerPayload: triggerPayload as never, status: "queued", summaryText: "automation.execution.queued", createdByUserId: USER_ID, stepExecutions: { create: rule.steps.map((step) => ({ tenantId: TENANT_ID, ruleStepId: step.id, stepKey: step.stepKey, stepKind: step.stepKind, nodeType: step.nodeType, status: "queued", input: {} as never, output: {} as never, summaryText: step.summaryText || "automation.execution.stepQueued", sortOrder: step.sortOrder, })), }, }, }); return { executionId: execution.id }; } function executorDeps(client: DbClient, overrides: Partial> = {}): AutomationExecutorDeps { return { runInTenantTx: (fn) => client.$transaction((tx) => fn(tx as never)), notify: (input, txClient) => notify(input as never, txClient as NotificationClient), logActivity: async (input, opts) => { const data = input as Record; const tx = opts.client as DbClient; return tx.activity.create({ data: { tenantId: String(data.tenantId), actorUserId: typeof data.actorUserId === "string" ? data.actorUserId : null, actorKind: "automation", activityType: String(data.activityType), subjectType: String(data.subjectType), subjectId: String(data.subjectId), summaryText: String(data.summaryText), metadata: (data.metadata ?? {}) as never, }, }); }, fetchOutboundHttp: overrides.fetchOutboundHttp ?? (async () => ({ status: 204, ok: true })), sendChatMessage: async () => ({ messageId: "chat-message-integration", replayed: false }), ...(overrides.now ? { now: overrides.now } : {}), }; }