import { describe, expect, it } from "vitest"; import { automationConditionBranchForParent } from "@hivegrid/db/automation-graph"; import { AUTOMATION_TRIGGERS_WITHOUT_EMITTER, automationActionCatalog, automationTriggerCatalog } from "./automation.registry"; import { applyAutomationEditorOperation, buildAutomationDryRunPreview, buildAutomationEditorFlow, buildAutomationReversePlan, canConfirmAutomationReverse, canConfirmAutomationDryRun, extractAutomationClipboardSteps, extractAutomationReverseRecipients, incompleteAutomationNodeConfigKeys, serializeAutomationEditorFlow, validateAutomationEditorFlow, } from "./automation.editor"; const catalog = [...automationTriggerCatalog, ...automationActionCatalog]; describe("automation editor contract", () => { it("validates missing triggers, missing parents, and loops with Klartext keys", () => { const missingTrigger = buildAutomationEditorFlow({ flowData: {}, steps: [{ stepKey: "task", stepKind: "action", nodeType: "task.create", parentStepIds: [] }], }); expect(validateAutomationEditorFlow(missingTrigger).issues.map((issue) => issue.code)).toContain("missing_trigger"); expect(validateAutomationEditorFlow(missingTrigger).issues.map((issue) => issue.code)).toContain("unconnected_step"); const loop = buildAutomationEditorFlow({ flowData: {}, steps: [ { stepKey: "trigger", stepKind: "trigger", nodeType: "lead.qualified", parentStepIds: ["task"] }, { stepKey: "task", stepKind: "action", nodeType: "task.create", parentStepIds: ["trigger"] }, ], }); expect(validateAutomationEditorFlow(loop).issues).toContainEqual( expect.objectContaining({ code: "loop_detected", messageKey: "automation.editor.validation.loopDetected" }) ); }); it("blocks flows the runtime could not execute", () => { // A portal action under a CRM trigger reaches the generic executor, which // has no portal handler and ends the run as unsupportedNode. const mixedFamilies = buildAutomationEditorFlow({ flowData: {}, steps: [ { stepKey: "trigger", stepKind: "trigger", nodeType: "crm.kontakt_created", parentStepIds: [] }, { stepKey: "invite", stepKind: "action", nodeType: "portal.invite_user", parentStepIds: ["trigger"] }, ], }); const mixed = validateAutomationEditorFlow(mixedFamilies); expect(mixed.issues).toContainEqual(expect.objectContaining({ code: "executor_family_mismatch", stepKey: "invite" })); expect(mixed.canActivate).toBe(false); // Same flow with a portal trigger is fine - it runs in the portal consumer. const portalOnly = buildAutomationEditorFlow({ flowData: {}, steps: [ { stepKey: "trigger", stepKind: "trigger", nodeType: "portal.user_created", parentStepIds: [] }, { stepKey: "invite", stepKind: "action", nodeType: "portal.invite_user", parentStepIds: ["trigger"] }, ], }); expect(validateAutomationEditorFlow(portalOnly).issues).not.toContainEqual(expect.objectContaining({ code: "executor_family_mismatch" })); const loop = buildAutomationEditorFlow({ flowData: {}, steps: [ { stepKey: "trigger", stepKind: "trigger", nodeType: "lead.qualified", parentStepIds: [] }, { stepKey: "loop", stepKind: "flow_control", nodeType: "loop.for_each", parentStepIds: ["trigger"], config: { liste: "offeneAufgabenDesProjekts", maxDurchlaeufe: "100" }, }, ], }); expect(validateAutomationEditorFlow(loop).issues).toContainEqual(expect.objectContaining({ code: "node_without_executor", stepKey: "loop" })); expect(validateAutomationEditorFlow(loop).canActivate).toBe(false); for (const triggerKey of AUTOMATION_TRIGGERS_WITHOUT_EMITTER) { const dormant = buildAutomationEditorFlow({ flowData: {}, steps: [{ stepKey: "trigger", stepKind: "trigger", nodeType: triggerKey, parentStepIds: [] }], }); const dormantResult = validateAutomationEditorFlow(dormant); expect(dormantResult.issues).toContainEqual(expect.objectContaining({ code: "trigger_without_emitter", severity: "error", detail: triggerKey })); expect(dormantResult.canActivate).toBe(false); } const webhook = buildAutomationEditorFlow({ flowData: {}, steps: [{ stepKey: "trigger", stepKind: "trigger", nodeType: "webhook.received", parentStepIds: [] }], }); expect(validateAutomationEditorFlow(webhook).canActivate).toBe(true); }); it("blocks incomplete action configuration before activation", () => { const flow = buildAutomationEditorFlow({ flowData: {}, steps: [ { stepKey: "trigger", stepKind: "trigger", nodeType: "webhook.received", parentStepIds: [] }, { stepKey: "notify", stepKind: "action", nodeType: "notification.send", parentStepIds: ["trigger"], config: {} }, ], }); const validation = validateAutomationEditorFlow(flow); expect(validation.issues).toContainEqual(expect.objectContaining({ code: "incomplete_configuration", stepKey: "notify", detail: "notification.send" })); expect(validation.canActivate).toBe(false); expect(incompleteAutomationNodeConfigKeys("notification.send", {})).toEqual(["kanal", "empfaenger", "betreff", "nachricht"]); expect( incompleteAutomationNodeConfigKeys("notification.send", { kanal: "intern", empfaenger: "besitzerDerAutomation", betreff: "Neuer Vorgang", nachricht: "Bitte prüfen.", }) ).toEqual([]); expect(incompleteAutomationNodeConfigKeys("email.send_transactional", { betreff: "Hallo", nachricht: "Text" })).toEqual(["an"]); expect( incompleteAutomationNodeConfigKeys("email.send_transactional", { an: "{{email}}", betreff: "Hallo", nachricht: "Text" }) ).toEqual([]); expect(incompleteAutomationNodeConfigKeys("chat.post_message", { chatId: "chat-1" })).toEqual(["nachricht"]); expect(incompleteAutomationNodeConfigKeys("chat.post_message", { chatId: "{{chatId}}", nachricht: "Hallo {{name}}" })).toEqual([]); expect( incompleteAutomationNodeConfigKeys("task.assign", { aufgabe: "bestimmteAufgabe", zustaendig: "erstellerDerAufgabe", benachrichtigungAn: "niemand" }) ).toContain("taskId"); expect(incompleteAutomationNodeConfigKeys("loop.for_each", { liste: "offeneAufgabenDesProjekts", maxDurchlaeufe: "101" })).toEqual(["maxDurchlaeufe"]); }); it("places added nodes without overlapping the neighbouring card", () => { const catalogNodes = catalog; let flow = buildAutomationEditorFlow({ flowData: {}, steps: [] }); flow = applyAutomationEditorOperation(flow, { type: "add-node", nodeType: "lead.qualified" }, catalogNodes); flow = applyAutomationEditorOperation(flow, { type: "add-node", nodeType: "task.create", parentStepKey: flow.steps[0]?.stepKey }, catalogNodes); // The card renders 288px wide; a narrower pitch dropped every second node // on top of its neighbour. const [first, second] = flow.steps; expect(Math.abs(second!.position.x - first!.position.x)).toBeGreaterThanOrEqual(288); }); it("applies graph operations with undo and redo history", () => { const initial = buildAutomationEditorFlow({ flowData: {}, steps: [] }); const withTrigger = applyAutomationEditorOperation(initial, { type: "add-node", nodeType: "lead.qualified" }, catalog); const withTaskUnconfigured = applyAutomationEditorOperation( withTrigger, { type: "add-node", nodeType: "task.create", parentStepKey: withTrigger.steps[0]?.stepKey }, catalog ); const withTask = { ...withTaskUnconfigured, steps: withTaskUnconfigured.steps.map((step) => step.nodeType === "task.create" ? { ...step, config: { ...step.config, titel: "Lead nachfassen" } } : step ), }; const connected = applyAutomationEditorOperation( withTask, { type: "connect", fromStepKey: withTrigger.steps[0]!.stepKey, toStepKey: withTask.steps[1]!.stepKey }, catalog ); expect(validateAutomationEditorFlow(connected).canActivate).toBe(true); expect(serializeAutomationEditorFlow(connected).steps).toHaveLength(2); const undone = applyAutomationEditorOperation(connected, { type: "undo" }, catalog); expect(undone.history.future).toHaveLength(1); const redone = applyAutomationEditorOperation(undone, { type: "redo" }, catalog); expect(redone.steps).toHaveLength(2); }); it("persists and removes explicit condition edge branches", () => { const flow = buildAutomationEditorFlow({ flowData: {}, steps: [ { stepKey: "trigger", stepKind: "trigger", nodeType: "lead.qualified", parentStepIds: [] }, { stepKey: "condition", stepKind: "condition", nodeType: "condition.if_else", parentStepIds: ["trigger"], config: { feld: "status", vergleich: "istGleich", wert: "gewonnen" }, }, { stepKey: "fallback", stepKind: "action", nodeType: "task.create", parentStepIds: [], config: { titel: "Nachbearbeiten", zustaendig: "besitzerDerAutomation", prioritaet: "normal" }, }, ], }); const connected = applyAutomationEditorOperation( flow, { type: "connect", fromStepKey: "condition", toStepKey: "fallback", branch: "false" }, catalog ); const fallback = connected.steps.find((step) => step.stepKey === "fallback")!; expect(automationConditionBranchForParent(fallback.config, "condition")).toBe("false"); const disconnected = applyAutomationEditorOperation( connected, { type: "disconnect", fromStepKey: "condition", toStepKey: "fallback" }, catalog ); expect(disconnected.steps.find((step) => step.stepKey === "fallback")?.config).toEqual({ titel: "Nachbearbeiten", zustaendig: "besitzerDerAutomation", prioritaet: "normal", }); }); it("builds dry-run previews with confirmation threshold", () => { const flow = buildAutomationEditorFlow({ flowData: {}, steps: [ { stepKey: "trigger", stepKind: "trigger", nodeType: "lead.qualified", parentStepIds: [] }, { stepKey: "task", stepKind: "action", nodeType: "task.create", parentStepIds: ["trigger"] }, ], }); const preview = buildAutomationDryRunPreview({ flow, confirmationPhrase: "START DRY RUN", matchedRecords: 101, inspectedEvents: 500, sampleLimitReached: true, examples: ["Lead A", "Lead B", "Lead C", "Lead D", "Lead E", "Lead F"], }); expect(preview.requiresConfirmation).toBe(true); expect(preview.inspectedEvents).toBe(500); expect(preview.sampleLimitReached).toBe(true); expect(preview.examples).toHaveLength(5); expect(preview.confirmationPhrase).toBe("START DRY RUN"); expect( canConfirmAutomationDryRun({ matchedRecords: 101, confirmationPhrase: "DRY RUN STARTEN", expectedConfirmationPhrase: preview.confirmationPhrase }) ).toBe(false); expect( canConfirmAutomationDryRun({ matchedRecords: 101, confirmationPhrase: preview.confirmationPhrase, expectedConfirmationPhrase: preview.confirmationPhrase }) ).toBe(true); }); it("rejects scheduler configs that the minute sweep cannot execute", () => { expect(incompleteAutomationNodeConfigKeys("time.schedule", { wiederholung: "taeglich", uhrzeit: "morgen" })).toContain("uhrzeit"); expect(incompleteAutomationNodeConfigKeys("time.schedule", { wiederholung: "taeglich", uhrzeit: "08:00" })).toEqual([]); expect(incompleteAutomationNodeConfigKeys("time.schedule", { wiederholung: "woechentlich", uhrzeit: "08:00" })).toEqual(["wochentag"]); expect(incompleteAutomationNodeConfigKeys("time.schedule", { wiederholung: "monatlich", uhrzeit: "08:00", monatstag: "32" })).toEqual(["monatstag"]); expect(incompleteAutomationNodeConfigKeys("time.schedule", { wiederholung: "woechentlich", uhrzeit: "08:00", wochentag: "freitag" })).toEqual([]); expect( incompleteAutomationNodeConfigKeys("projects.deadline_soon", { fristtyp: "projektDeadline", leadTime: 0, leadTimeUnit: "tage", }) ).toContain("leadTime"); }); it("builds 24h reverse plans and marks deliveries as not reversible", () => { const plan = buildAutomationReversePlan({ reverseWindowExpiresAt: "2026-07-02T10:00:00.000Z", confirmationPhrase: "REVERSE AUTOMATION", now: new Date("2026-07-02T09:00:00.000Z"), steps: [ { stepKey: "task", nodeType: "task.create" }, { stepKey: "notify", nodeType: "notification.send" }, ], }); expect(plan.canReverse).toBe(true); expect(plan.items).toEqual([ expect.objectContaining({ actionKey: "automation.editor.reverse.actions.deleteTask", reversible: true }), expect.objectContaining({ actionKey: "automation.editor.reverse.actions.deliveryNotReversible", reversible: false }), ]); }); it("requires the exact reverse confirmation phrase", () => { expect(canConfirmAutomationReverse({ confirmationPhrase: "REVERSE AUTOMATION", expectedConfirmationPhrase: "REVERSE AUTOMATION" })).toBe(true); expect(canConfirmAutomationReverse({ confirmationPhrase: "reverse automation", expectedConfirmationPhrase: "REVERSE AUTOMATION" })).toBe(true); expect(canConfirmAutomationReverse({ confirmationPhrase: "AUTOMATION RÜCKGÄNGIG", expectedConfirmationPhrase: "REVERSE AUTOMATION" })).toBe(false); }); it("copies and pastes steps with fresh keys and remapped parents", () => { const flow = buildAutomationEditorFlow({ flowData: {}, steps: [ { stepKey: "trigger", stepKind: "trigger", nodeType: "lead.qualified", parentStepIds: [] }, { stepKey: "task", stepKind: "action", nodeType: "task.create", parentStepIds: ["trigger"], config: { titel: "Angebot" } }, { stepKey: "notify", stepKind: "action", nodeType: "notification.send", parentStepIds: ["task"] }, ], }); const clipboard = extractAutomationClipboardSteps(flow, ["task", "notify"]); expect(clipboard).toHaveLength(2); const pasted = applyAutomationEditorOperation(flow, { type: "paste-steps", steps: clipboard }, catalog); expect(pasted.steps).toHaveLength(5); const pastedTask = pasted.steps.find((step) => step.nodeType === "task.create" && step.stepKey !== "task"); const pastedNotify = pasted.steps.find((step) => step.nodeType === "notification.send" && step.stepKey !== "notify"); // Intra-clipboard parent is remapped to the fresh key; the parent link to // the still-existing trigger survives the paste. expect(pastedNotify?.parentStepIds).toEqual([pastedTask?.stepKey]); expect(pastedTask?.parentStepIds).toEqual(["trigger"]); expect(pastedTask?.config).toEqual({ titel: "Angebot" }); expect(pasted.history.past.length).toBeGreaterThan(0); }); it("drops unknown node types on paste and deletes multiple steps at once", () => { const flow = buildAutomationEditorFlow({ flowData: {}, steps: [ { stepKey: "trigger", stepKind: "trigger", nodeType: "lead.qualified", parentStepIds: [] }, { stepKey: "task", stepKind: "action", nodeType: "task.create", parentStepIds: ["trigger"] }, { stepKey: "notify", stepKind: "action", nodeType: "notification.send", parentStepIds: ["task"] }, ], }); const unknownPaste = applyAutomationEditorOperation(flow, { type: "paste-steps", steps: [{ stepKey: "x", nodeType: "tags.add" }] }, catalog); expect(unknownPaste.steps).toHaveLength(3); const deleted = applyAutomationEditorOperation(flow, { type: "delete-nodes", stepKeys: ["task", "notify"] }, catalog); expect(deleted.steps.map((step) => step.stepKey)).toEqual(["trigger"]); expect(deleted.steps[0]?.parentStepIds).toEqual([]); }); it("extracts persisted send recipients for the reverse plan", () => { expect( extractAutomationReverseRecipients("notification.send", { recipients: [{ name: "Sandra Vogel", email: "buero@example.com" }, "chef@example.com"] }) ).toEqual([ { name: "Sandra Vogel", email: "buero@example.com" }, { name: null, email: "chef@example.com" }, ]); // Fail-tolerant: missing/malformed outputs yield an empty list instead of throwing. expect(extractAutomationReverseRecipients("notification.send", null)).toEqual([]); expect(extractAutomationReverseRecipients("notification.send", { recipients: [{}, 42] })).toEqual([]); expect(extractAutomationReverseRecipients("task.create", { recipients: ["a@b.c"] })).toEqual([]); const plan = buildAutomationReversePlan({ reverseWindowExpiresAt: "2026-07-02T10:00:00.000Z", confirmationPhrase: "REVERSE AUTOMATION", now: new Date("2026-07-02T09:00:00.000Z"), steps: [{ stepKey: "notify", nodeType: "notification.send", output: { recipients: ["buero@example.com"] } }], }); expect(plan.items[0]?.recipients).toEqual([{ name: null, email: "buero@example.com" }]); expect(plan.items[0]?.reversible).toBe(false); }); it("describes the reversible CRM tag and assignment actions", () => { const plan = buildAutomationReversePlan({ reverseWindowExpiresAt: "2026-07-02T10:00:00.000Z", confirmationPhrase: "REVERSE AUTOMATION", now: new Date("2026-07-02T09:00:00.000Z"), steps: [ { stepKey: "add-tag", nodeType: "crm.add_tag", output: {} }, { stepKey: "remove-tag", nodeType: "crm.remove_tag", output: {} }, { stepKey: "assign-contact", nodeType: "crm.assign_kontakt", output: {} }, { stepKey: "assign-lead", nodeType: "lead.assign", output: {} }, { stepKey: "status-lead", nodeType: "lead.set_status", output: {} }, ], }); expect(plan.items).toEqual([ expect.objectContaining({ actionKey: "automation.editor.reverse.actions.removeContactTag", reversible: true }), expect.objectContaining({ actionKey: "automation.editor.reverse.actions.restoreContactTag", reversible: true }), expect.objectContaining({ actionKey: "automation.editor.reverse.actions.restoreContactAssignment", reversible: true }), expect.objectContaining({ actionKey: "automation.editor.reverse.actions.restoreLeadAssignment", reversible: true }), expect.objectContaining({ actionKey: "automation.editor.reverse.actions.restoreLeadStatus", reversible: true }), ]); }); });