import { beforeEach, describe, expect, it, vi } from "vitest"; const mocks = vi.hoisted(() => ({ tx: { automationExecution: { findFirst: vi.fn(), update: vi.fn(), updateMany: vi.fn() }, task: { updateMany: vi.fn() }, kontakt: { findFirst: vi.fn(), updateMany: vi.fn() }, tag: { findFirst: vi.fn() }, tagAssignment: { deleteMany: vi.fn(), upsert: vi.fn() }, inboxLead: { updateMany: vi.fn() }, activity: { create: vi.fn() }, }, })); vi.mock("~/utils/db/.server/tenantRls.server", () => ({ withTenantRLS: async (_tenantId: string, callback: (tx: typeof mocks.tx) => Promise) => callback(mocks.tx), })); import { executeAutomationReverse } from "./automation.server"; describe("automation reverse executor", () => { beforeEach(() => { vi.clearAllMocks(); mocks.tx.task.updateMany.mockResolvedValue({ count: 1 }); mocks.tx.kontakt.findFirst.mockResolvedValue({ id: "k-1" }); mocks.tx.kontakt.updateMany.mockResolvedValue({ count: 1 }); mocks.tx.tag.findFirst.mockResolvedValue({ id: "tag-1" }); mocks.tx.tagAssignment.deleteMany.mockResolvedValue({ count: 1 }); mocks.tx.tagAssignment.upsert.mockResolvedValue({ id: "tag-assignment-1" }); mocks.tx.inboxLead.updateMany.mockResolvedValue({ count: 1 }); mocks.tx.activity.create.mockResolvedValue({ id: "activity-1" }); mocks.tx.automationExecution.update.mockResolvedValue({ id: "execution-1" }); mocks.tx.automationExecution.updateMany.mockResolvedValue({ count: 1 }); }); it("archives a task from the persisted step output and closes the reverse window", async () => { mocks.tx.automationExecution.findFirst.mockResolvedValue({ reverseWindowExpiresAt: new Date("2026-07-12T12:00:00.000Z"), stepExecutions: [{ stepKey: "create-task", nodeType: "task.create", output: { taskId: "task-1" } }], }); await expect( executeAutomationReverse({ tenantId: "tenant-1", actorUserId: "user-1", ruleId: "rule-1", executionId: "execution-1", now: new Date("2026-07-11T12:00:00.000Z"), }) ).resolves.toBe(1); expect(mocks.tx.task.updateMany).toHaveBeenCalledWith({ where: { id: "task-1", tenantId: "tenant-1", archivedAt: null }, data: { archivedAt: new Date("2026-07-11T12:00:00.000Z") }, }); expect(mocks.tx.automationExecution.updateMany).toHaveBeenCalledWith({ where: { id: "execution-1", tenantId: "tenant-1", ruleId: "rule-1", reverseWindowExpiresAt: { gt: new Date("2026-07-11T12:00:00.000Z") }, }, data: { reverseWindowExpiresAt: null }, }); expect(mocks.tx.activity.create).toHaveBeenCalledWith(expect.objectContaining({ data: expect.objectContaining({ activityType: "automation_reversed", subjectId: "task-1" }) })); expect(mocks.tx.automationExecution.update).toHaveBeenCalledWith({ where: { id: "execution-1" }, data: { summaryText: "automation.execution.reversed" }, }); }); it("fails closed when a reversible step has no persisted target", async () => { mocks.tx.automationExecution.findFirst.mockResolvedValue({ reverseWindowExpiresAt: new Date("2026-07-12T12:00:00.000Z"), stepExecutions: [{ stepKey: "create-task", nodeType: "task.create", output: {} }], }); await expect( executeAutomationReverse({ tenantId: "tenant-1", actorUserId: "user-1", ruleId: "rule-1", executionId: "execution-1", now: new Date("2026-07-11T12:00:00.000Z"), }) ).rejects.toThrow("automation.detail.reverse.missingOutput"); expect(mocks.tx.automationExecution.update).not.toHaveBeenCalled(); }); it("restores a previously unassigned task", async () => { mocks.tx.automationExecution.findFirst.mockResolvedValue({ reverseWindowExpiresAt: new Date("2026-07-12T12:00:00.000Z"), stepExecutions: [ { stepKey: "assign-task", nodeType: "task.assign", output: { taskId: "task-1", before: { assignedToUserId: null, assignedToGroupId: null } }, }, ], }); await expect( executeAutomationReverse({ tenantId: "tenant-1", actorUserId: "user-1", ruleId: "rule-1", executionId: "execution-1", now: new Date("2026-07-11T12:00:00.000Z"), }) ).resolves.toBe(1); expect(mocks.tx.task.updateMany).toHaveBeenCalledWith({ where: { id: "task-1", tenantId: "tenant-1", archivedAt: null }, data: { assignedToUserId: null, assignedToGroupId: null }, }); }); it("removes a contact tag that the automation added", async () => { mocks.tx.automationExecution.findFirst.mockResolvedValue({ reverseWindowExpiresAt: new Date("2026-07-12T12:00:00.000Z"), stepExecutions: [ { stepKey: "add-tag", nodeType: "crm.add_tag", output: { kontaktId: "k-1", tagId: "tag-1", changed: true, beforeAssigned: false }, }, ], }); await expect(executeAutomationReverse(baseInput)).resolves.toBe(1); expect(mocks.tx.tagAssignment.deleteMany).toHaveBeenCalledWith({ where: { tenantId: "tenant-1", tagId: "tag-1", entityType: "kontakt", entityId: "k-1" }, }); }); it("restores a contact tag that the automation removed", async () => { mocks.tx.automationExecution.findFirst.mockResolvedValue({ reverseWindowExpiresAt: new Date("2026-07-12T12:00:00.000Z"), stepExecutions: [ { stepKey: "remove-tag", nodeType: "crm.remove_tag", output: { kontaktId: "k-1", tagId: "tag-1", changed: true, beforeAssigned: true }, }, ], }); await expect(executeAutomationReverse(baseInput)).resolves.toBe(1); expect(mocks.tx.kontakt.findFirst).toHaveBeenCalledWith({ where: { id: "k-1", tenantId: "tenant-1", archivedAt: null }, select: { id: true }, }); expect(mocks.tx.tag.findFirst).toHaveBeenCalledWith({ where: { id: "tag-1", tenantId: "tenant-1" }, select: { id: true } }); expect(mocks.tx.tagAssignment.upsert).toHaveBeenCalledWith({ where: { tagId_entityId_entityType: { tagId: "tag-1", entityId: "k-1", entityType: "kontakt" } }, update: {}, create: { tenantId: "tenant-1", tagId: "tag-1", entityType: "kontakt", entityId: "k-1" }, }); }); it("restores the previous contact owner", async () => { mocks.tx.automationExecution.findFirst.mockResolvedValue({ reverseWindowExpiresAt: new Date("2026-07-12T12:00:00.000Z"), stepExecutions: [ { stepKey: "assign-contact", nodeType: "crm.assign_kontakt", output: { kontaktId: "k-1", assignedToUserId: "user-new", changed: true, before: { zustaendigerUserId: null }, }, }, ], }); await expect(executeAutomationReverse(baseInput)).resolves.toBe(1); expect(mocks.tx.kontakt.updateMany).toHaveBeenCalledWith({ where: { id: "k-1", tenantId: "tenant-1", archivedAt: null }, data: { zustaendigerUserId: null }, }); }); it("fails closed when a changed tag output contradicts its before snapshot", async () => { mocks.tx.automationExecution.findFirst.mockResolvedValue({ reverseWindowExpiresAt: new Date("2026-07-12T12:00:00.000Z"), stepExecutions: [ { stepKey: "add-tag", nodeType: "crm.add_tag", output: { kontaktId: "k-1", tagId: "tag-1", changed: true, beforeAssigned: true }, }, ], }); await expect(executeAutomationReverse(baseInput)).rejects.toThrow("automation.detail.reverse.missingOutput"); expect(mocks.tx.tagAssignment.deleteMany).not.toHaveBeenCalled(); }); it("restores the previous lead owner", async () => { mocks.tx.automationExecution.findFirst.mockResolvedValue({ reverseWindowExpiresAt: new Date("2026-07-12T12:00:00.000Z"), stepExecutions: [ { stepKey: "assign-lead", nodeType: "lead.assign", output: { leadId: "lead-1", assignedToUserId: "user-new", changed: true, before: { zustaendigerUserId: null } }, }, ], }); await expect(executeAutomationReverse(baseInput)).resolves.toBe(1); expect(mocks.tx.inboxLead.updateMany).toHaveBeenCalledWith({ where: { id: "lead-1", tenantId: "tenant-1", archivedAt: null }, data: { zustaendigerUserId: null }, }); }); it("restores every field changed by a lead status transition", async () => { mocks.tx.automationExecution.findFirst.mockResolvedValue({ reverseWindowExpiresAt: new Date("2026-07-12T12:00:00.000Z"), stepExecutions: [ { stepKey: "qualify-lead", nodeType: "lead.set_status", output: { leadId: "lead-1", status: "qualified", changed: true, before: { status: "new", weiterverarbeitungFreigabe: "unklar", convertedAt: null, lostAt: "2026-07-01T10:00:00.000Z", spamMarkedAt: null, autoDeleteAt: null, }, }, }, ], }); await expect(executeAutomationReverse(baseInput)).resolves.toBe(1); expect(mocks.tx.inboxLead.updateMany).toHaveBeenCalledWith({ where: { id: "lead-1", tenantId: "tenant-1", archivedAt: null }, data: { status: "new", weiterverarbeitungFreigabe: "unklar", convertedAt: null, lostAt: new Date("2026-07-01T10:00:00.000Z"), spamMarkedAt: null, autoDeleteAt: null, }, }); }); // Fail-closed guard matrix (R-P12b DoD 4 / Audit-Nachzug): notFound, // expired (both variants), targetUnavailable, nothingReversible, and the // kontakt before-snapshot guard. const baseInput = { tenantId: "tenant-1", actorUserId: "user-1", ruleId: "rule-1", executionId: "execution-1", now: new Date("2026-07-11T12:00:00.000Z"), }; it("fails closed when the execution does not exist for this tenant/rule", async () => { mocks.tx.automationExecution.findFirst.mockResolvedValue(null); await expect(executeAutomationReverse(baseInput)).rejects.toThrow("automation.detail.reverse.notFound"); expect(mocks.tx.task.updateMany).not.toHaveBeenCalled(); }); it("fails closed when the 24h window has already expired", async () => { mocks.tx.automationExecution.findFirst.mockResolvedValue({ reverseWindowExpiresAt: new Date("2026-07-11T11:00:00.000Z"), stepExecutions: [{ stepKey: "create-task", nodeType: "task.create", output: { taskId: "task-1" } }], }); await expect(executeAutomationReverse(baseInput)).rejects.toThrow("automation.detail.reverse.expired"); expect(mocks.tx.task.updateMany).not.toHaveBeenCalled(); }); it("fails closed when a concurrent reverse already claimed the window (atomic close)", async () => { mocks.tx.automationExecution.findFirst.mockResolvedValue({ reverseWindowExpiresAt: new Date("2026-07-12T12:00:00.000Z"), stepExecutions: [{ stepKey: "create-task", nodeType: "task.create", output: { taskId: "task-1" } }], }); mocks.tx.automationExecution.updateMany.mockResolvedValue({ count: 0 }); await expect(executeAutomationReverse(baseInput)).rejects.toThrow("automation.detail.reverse.expired"); expect(mocks.tx.task.updateMany).not.toHaveBeenCalled(); }); it("fails closed when the reverse target is archived or gone (targetUnavailable)", async () => { mocks.tx.automationExecution.findFirst.mockResolvedValue({ reverseWindowExpiresAt: new Date("2026-07-12T12:00:00.000Z"), stepExecutions: [{ stepKey: "create-task", nodeType: "task.create", output: { taskId: "task-1" } }], }); mocks.tx.task.updateMany.mockResolvedValue({ count: 0 }); await expect(executeAutomationReverse(baseInput)).rejects.toThrow("automation.detail.reverse.targetUnavailable"); expect(mocks.tx.automationExecution.update).not.toHaveBeenCalled(); }); it("fails closed when no step of the run is reversible (nothingReversible)", async () => { mocks.tx.automationExecution.findFirst.mockResolvedValue({ reverseWindowExpiresAt: new Date("2026-07-12T12:00:00.000Z"), stepExecutions: [{ stepKey: "notify", nodeType: "notification.send", output: { recipients: [{ email: "a@b.de" }] } }], }); await expect(executeAutomationReverse(baseInput)).rejects.toThrow("automation.detail.reverse.nothingReversible"); }); it("fails closed when the kontakt before-snapshot carries no allowed fields", async () => { mocks.tx.automationExecution.findFirst.mockResolvedValue({ reverseWindowExpiresAt: new Date("2026-07-12T12:00:00.000Z"), stepExecutions: [{ stepKey: "update", nodeType: "crm.update_kontakt", output: { kontaktId: "k-1", before: { notAllowed: "x" } } }], }); await expect(executeAutomationReverse(baseInput)).rejects.toThrow("automation.detail.reverse.missingOutput"); expect(mocks.tx.kontakt.updateMany).not.toHaveBeenCalled(); }); });