Refresh HiveGrid Cloud reference snapshot
This commit is contained in:
1 parent
5e99e14772
commit
7f88026f79
5955 files changed
+1177325
-188362
No files matched your search
+294
-7
@@ -1,11 +1,16 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { automationActionCatalog, automationTriggerCatalog } from "./automation.registry";
|
||||
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";
|
||||
@@ -28,14 +33,130 @@ describe("automation editor contract", () => {
|
||||
{ stepKey: "task", stepKind: "action", nodeType: "task.create", parentStepIds: ["trigger"] },
|
||||
],
|
||||
});
|
||||
expect(validateAutomationEditorFlow(loop).issues).toContainEqual(expect.objectContaining({ code: "loop_detected", messageKey: "automation.editor.validation.loopDetected" }));
|
||||
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 withTask = applyAutomationEditorOperation(withTrigger, { type: "add-node", nodeType: "task.create", parentStepKey: withTrigger.steps[0]?.stepKey }, catalog);
|
||||
const connected = applyAutomationEditorOperation(withTask, { type: "connect", fromStepKey: withTrigger.steps[0]!.stepKey, toStepKey: withTask.steps[1]!.stepKey }, 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);
|
||||
@@ -47,6 +168,48 @@ describe("automation editor contract", () => {
|
||||
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: {},
|
||||
@@ -55,17 +218,47 @@ describe("automation editor contract", () => {
|
||||
{ stepKey: "task", stepKind: "action", nodeType: "task.create", parentStepIds: ["trigger"] },
|
||||
],
|
||||
});
|
||||
const preview = buildAutomationDryRunPreview({ flow, matchedRecords: 101, examples: ["Lead A", "Lead B", "Lead C", "Lead D", "Lead E", "Lead F"] });
|
||||
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(canConfirmAutomationDryRun({ matchedRecords: 101, confirmationPhrase: "falsch" })).toBe(false);
|
||||
expect(canConfirmAutomationDryRun({ matchedRecords: 101, confirmationPhrase: preview.confirmationPhrase })).toBe(true);
|
||||
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" },
|
||||
@@ -79,4 +272,98 @@ describe("automation editor contract", () => {
|
||||
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 }),
|
||||
]);
|
||||
});
|
||||
});
|
||||
+404
-32
@@ -1,12 +1,32 @@
|
||||
import {
|
||||
AUTOMATION_TRIGGERS_WITHOUT_EMITTER,
|
||||
automationExecutionFamily,
|
||||
evaluateLoopGuard,
|
||||
getAutomationNode,
|
||||
isAutomationNodeRunnable,
|
||||
type AutomationGraphStep,
|
||||
type AutomationNodeDefinition,
|
||||
type AutomationNodeKind,
|
||||
} from "./automation.registry";
|
||||
import {
|
||||
AUTOMATION_CONDITION_BRANCHES_CONFIG_KEY,
|
||||
automationConditionBranches,
|
||||
withAutomationConditionBranch,
|
||||
type AutomationConditionBranch,
|
||||
} from "@hivegrid/db/automation-graph";
|
||||
|
||||
export type AutomationEditorIssueCode = "missing_trigger" | "multiple_triggers" | "unknown_node" | "unconnected_step" | "missing_parent" | "loop_detected" | "empty_flow";
|
||||
export type AutomationEditorIssueCode =
|
||||
| "missing_trigger"
|
||||
| "multiple_triggers"
|
||||
| "unknown_node"
|
||||
| "unconnected_step"
|
||||
| "missing_parent"
|
||||
| "loop_detected"
|
||||
| "empty_flow"
|
||||
| "node_without_executor"
|
||||
| "executor_family_mismatch"
|
||||
| "trigger_without_emitter"
|
||||
| "incomplete_configuration";
|
||||
|
||||
export interface AutomationEditorStep {
|
||||
readonly stepKey: string;
|
||||
@@ -61,8 +81,10 @@ export interface AutomationEditorStepInput {
|
||||
export type AutomationEditorOperation =
|
||||
| { readonly type: "add-node"; readonly nodeType: string; readonly parentStepKey?: string | null }
|
||||
| { readonly type: "delete-node"; readonly stepKey: string }
|
||||
| { readonly type: "delete-nodes"; readonly stepKeys: readonly string[] }
|
||||
| { readonly type: "duplicate-node"; readonly stepKey: string }
|
||||
| { readonly type: "connect"; readonly fromStepKey: string; readonly toStepKey: string }
|
||||
| { readonly type: "paste-steps"; readonly steps: readonly AutomationEditorStepInput[] }
|
||||
| { readonly type: "connect"; readonly fromStepKey: string; readonly toStepKey: string; readonly branch?: AutomationConditionBranch }
|
||||
| { readonly type: "disconnect"; readonly fromStepKey: string; readonly toStepKey: string }
|
||||
| { readonly type: "auto-layout" }
|
||||
| { readonly type: "undo" }
|
||||
@@ -72,6 +94,8 @@ export interface AutomationDryRunPreview {
|
||||
readonly requiresConfirmation: boolean;
|
||||
readonly confirmationPhrase: string;
|
||||
readonly matchedRecords: number;
|
||||
readonly inspectedEvents: number;
|
||||
readonly sampleLimitReached: boolean;
|
||||
readonly examples: readonly string[];
|
||||
readonly steps: readonly {
|
||||
readonly stepKey: string;
|
||||
@@ -82,6 +106,11 @@ export interface AutomationDryRunPreview {
|
||||
readonly warnings: readonly string[];
|
||||
}
|
||||
|
||||
export interface AutomationReverseRecipient {
|
||||
readonly name: string | null;
|
||||
readonly email: string | null;
|
||||
}
|
||||
|
||||
export interface AutomationReversePlan {
|
||||
readonly canReverse: boolean;
|
||||
readonly confirmationPhrase: string;
|
||||
@@ -90,14 +119,27 @@ export interface AutomationReversePlan {
|
||||
readonly nodeType: string;
|
||||
readonly actionKey: string;
|
||||
readonly reversible: boolean;
|
||||
/** Delivered-to list for send-type steps; shown as "not retractable" evidence. */
|
||||
readonly recipients: readonly AutomationReverseRecipient[];
|
||||
}[];
|
||||
readonly warnings: readonly string[];
|
||||
}
|
||||
|
||||
const DRY_RUN_CONFIRMATION_PHRASE = "DRY RUN STARTEN";
|
||||
const DRY_RUN_CONFIRMATION_THRESHOLD = 100;
|
||||
const REVERSE_CONFIRMATION_PHRASE = "AUTOMATION RUECKGAENGIG";
|
||||
const MAX_HISTORY = 20;
|
||||
/**
|
||||
* Canvas grid for placed nodes. The step card renders at 288px wide (w-72), so
|
||||
* the column pitch has to clear that plus a gutter - a narrower grid drops each
|
||||
* new node on top of its neighbour.
|
||||
*/
|
||||
const CANVAS_COLUMN_WIDTH = 340;
|
||||
const CANVAS_ROW_HEIGHT = 160;
|
||||
const CANVAS_COLUMNS = 3;
|
||||
|
||||
/** Grid slot for the n-th node, left to right and then wrapping downwards. */
|
||||
function gridPosition(index: number): { x: number; y: number } {
|
||||
return { x: CANVAS_COLUMN_WIDTH * (index % CANVAS_COLUMNS), y: CANVAS_ROW_HEIGHT * Math.floor(index / CANVAS_COLUMNS) };
|
||||
}
|
||||
|
||||
export function buildAutomationEditorFlow(input: { readonly flowData: unknown; readonly steps: readonly AutomationEditorStepInput[] }): AutomationEditorFlow {
|
||||
const rawFlow = objectOrEmpty(input.flowData);
|
||||
@@ -106,7 +148,7 @@ export function buildAutomationEditorFlow(input: { readonly flowData: unknown; r
|
||||
.map((raw, index) => normalizeStep(raw, index))
|
||||
.filter((step): step is AutomationEditorStep => step !== null)
|
||||
.sort((a, b) => a.sortOrder - b.sortOrder || a.stepKey.localeCompare(b.stepKey));
|
||||
const triggerKey = typeof rawFlow.triggerKey === "string" ? rawFlow.triggerKey : steps.find((step) => step.kind === "trigger")?.nodeType ?? "";
|
||||
const triggerKey = typeof rawFlow.triggerKey === "string" ? rawFlow.triggerKey : (steps.find((step) => step.kind === "trigger")?.nodeType ?? "");
|
||||
const history = normalizeHistory(rawFlow.history);
|
||||
return { triggerKey, steps, history };
|
||||
}
|
||||
@@ -141,10 +183,25 @@ export function validateAutomationEditorFlow(flow: AutomationEditorFlow): Automa
|
||||
issues.push(issue("multiple_triggers", null, "automation.editor.validation.multipleTriggers", triggerSteps.map((step) => step.stepKey).join(", ")));
|
||||
}
|
||||
|
||||
// The trigger decides which executor picks the rule up, so every action has
|
||||
// to belong to the same family (see automationExecutionFamily).
|
||||
const triggerFamily = triggerSteps.length === 1 ? automationExecutionFamily(triggerSteps[0]!.nodeType) : null;
|
||||
if (triggerSteps.length === 1 && AUTOMATION_TRIGGERS_WITHOUT_EMITTER.has(triggerSteps[0]!.nodeType)) {
|
||||
issues.push(issue("trigger_without_emitter", triggerSteps[0]!.stepKey, "automation.editor.validation.triggerWithoutEmitter", triggerSteps[0]!.nodeType));
|
||||
}
|
||||
|
||||
const stepKeys = new Set(flow.steps.map((step) => step.stepKey));
|
||||
for (const step of flow.steps) {
|
||||
if (!getAutomationNode(step.nodeType)) {
|
||||
const node = getAutomationNode(step.nodeType);
|
||||
if (!node) {
|
||||
issues.push(issue("unknown_node", step.stepKey, "automation.editor.validation.unknownNode", step.nodeType));
|
||||
} else if (!isAutomationNodeRunnable(node)) {
|
||||
issues.push(issue("node_without_executor", step.stepKey, "automation.editor.validation.nodeWithoutExecutor", step.nodeType));
|
||||
} else if (triggerFamily && step.kind !== "trigger" && automationExecutionFamily(step.nodeType) !== triggerFamily) {
|
||||
issues.push(issue("executor_family_mismatch", step.stepKey, "automation.editor.validation.executorFamilyMismatch", step.nodeType));
|
||||
}
|
||||
if (node && incompleteAutomationNodeConfigKeys(step.nodeType, step.config).length > 0) {
|
||||
issues.push(issue("incomplete_configuration", step.stepKey, "automation.editor.validation.incompleteConfiguration", step.nodeType));
|
||||
}
|
||||
for (const parentStepId of step.parentStepIds) {
|
||||
if (!stepKeys.has(parentStepId)) {
|
||||
@@ -175,7 +232,158 @@ export function validateAutomationEditorFlow(flow: AutomationEditorFlow): Automa
|
||||
};
|
||||
}
|
||||
|
||||
export function applyAutomationEditorOperation(flow: AutomationEditorFlow, operation: AutomationEditorOperation, catalog: readonly AutomationNodeDefinition[]): AutomationEditorFlow {
|
||||
type AutomationConfigRequirement = {
|
||||
readonly required?: readonly string[];
|
||||
readonly allowed?: Readonly<Record<string, readonly string[]>>;
|
||||
readonly requiredWhen?: readonly { readonly key: string; readonly whenKey: string; readonly equals: string }[];
|
||||
};
|
||||
|
||||
const AUTOMATION_CONFIG_REQUIREMENTS: Readonly<Record<string, AutomationConfigRequirement>> = {
|
||||
"projects.deadline_soon": {
|
||||
required: ["fristtyp", "leadTime", "leadTimeUnit"],
|
||||
allowed: {
|
||||
fristtyp: ["aufgabenFaelligkeit", "projektDeadline", "zahlungsziel"],
|
||||
leadTimeUnit: ["stunden", "tage", "wochen"],
|
||||
},
|
||||
},
|
||||
"time.schedule": {
|
||||
required: ["wiederholung", "uhrzeit"],
|
||||
allowed: {
|
||||
wiederholung: ["taeglich", "woechentlich", "monatlich"],
|
||||
wochentag: ["montag", "dienstag", "mittwoch", "donnerstag", "freitag", "samstag", "sonntag"],
|
||||
},
|
||||
requiredWhen: [
|
||||
{ key: "wochentag", whenKey: "wiederholung", equals: "woechentlich" },
|
||||
{ key: "monatstag", whenKey: "wiederholung", equals: "monatlich" },
|
||||
],
|
||||
},
|
||||
"crm.update_kontakt": {
|
||||
required: ["kontakt", "feld", "wert"],
|
||||
allowed: {
|
||||
kontakt: ["ausloeser", "manuell"],
|
||||
feld: ["kontaktStatus", "vorname", "nachname", "orgName", "primaerEmail", "primaerTelefon", "language"],
|
||||
},
|
||||
requiredWhen: [{ key: "kontaktId", whenKey: "kontakt", equals: "manuell" }],
|
||||
},
|
||||
"crm.add_tag": {
|
||||
required: ["kontakt", "tagId"],
|
||||
allowed: { kontakt: ["ausloeser", "manuell"] },
|
||||
requiredWhen: [{ key: "kontaktId", whenKey: "kontakt", equals: "manuell" }],
|
||||
},
|
||||
"crm.remove_tag": {
|
||||
required: ["kontakt", "tagId"],
|
||||
allowed: { kontakt: ["ausloeser", "manuell"] },
|
||||
requiredWhen: [{ key: "kontaktId", whenKey: "kontakt", equals: "manuell" }],
|
||||
},
|
||||
"crm.assign_kontakt": {
|
||||
required: ["kontakt", "userId"],
|
||||
allowed: { kontakt: ["ausloeser", "manuell"] },
|
||||
requiredWhen: [{ key: "kontaktId", whenKey: "kontakt", equals: "manuell" }],
|
||||
},
|
||||
"lead.assign": {
|
||||
required: ["lead", "userId"],
|
||||
allowed: { lead: ["ausloeser", "manuell"] },
|
||||
requiredWhen: [{ key: "leadId", whenKey: "lead", equals: "manuell" }],
|
||||
},
|
||||
"lead.set_status": {
|
||||
required: ["lead", "status"],
|
||||
allowed: { lead: ["ausloeser", "manuell"], status: ["new", "qualified", "converted", "lost", "spam"] },
|
||||
requiredWhen: [{ key: "leadId", whenKey: "lead", equals: "manuell" }],
|
||||
},
|
||||
"crm.create_note": {
|
||||
required: ["datensatz", "notiztext"],
|
||||
allowed: { datensatz: ["kontaktAusAusloeser", "auftragAusAusloeser", "projektAusAusloeser"] },
|
||||
},
|
||||
"notification.send": {
|
||||
required: ["kanal", "empfaenger", "betreff", "nachricht"],
|
||||
allowed: { kanal: ["intern"], empfaenger: ["besitzerDerAutomation", "bestimmtePerson"] },
|
||||
requiredWhen: [{ key: "userId", whenKey: "empfaenger", equals: "bestimmtePerson" }],
|
||||
},
|
||||
"email.send_transactional": { required: ["an", "betreff", "nachricht"] },
|
||||
"chat.post_message": { required: ["chatId", "nachricht"] },
|
||||
"http.request": {
|
||||
required: ["url", "methode"],
|
||||
allowed: { methode: ["get", "post", "put", "delete"] },
|
||||
},
|
||||
"task.create": {
|
||||
required: ["titel", "zustaendig", "prioritaet"],
|
||||
allowed: { zustaendig: ["besitzerDerAutomation"], prioritaet: ["niedrig", "normal", "hoch"] },
|
||||
},
|
||||
"task.assign": {
|
||||
required: ["aufgabe", "zustaendig", "benachrichtigungAn"],
|
||||
allowed: {
|
||||
aufgabe: ["ausVorherigemSchritt", "bestimmteAufgabe"],
|
||||
zustaendig: ["erstellerDerAufgabe"],
|
||||
benachrichtigungAn: ["neueVerantwortung", "bisherigeVerantwortung", "beide", "niemand"],
|
||||
},
|
||||
requiredWhen: [{ key: "taskId", whenKey: "aufgabe", equals: "bestimmteAufgabe" }],
|
||||
},
|
||||
"condition.if_else": {
|
||||
required: ["feld", "vergleich", "wert"],
|
||||
allowed: { vergleich: ["istGroesserAls", "istGleich", "istKleinerAls", "enthaelt"] },
|
||||
},
|
||||
"delay.wait": {
|
||||
required: ["dauer", "dauerEinheit"],
|
||||
allowed: { dauerEinheit: ["minuten", "stunden", "tage", "wochen"] },
|
||||
},
|
||||
"loop.for_each": {
|
||||
required: ["liste", "maxDurchlaeufe"],
|
||||
allowed: { liste: ["offeneAufgabenDesProjekts", "kontakteDesProjekts", "positionenDesAngebots", "termineDieserWoche"] },
|
||||
},
|
||||
"portal.invite_user": { required: ["kind", "email", "firstName", "lastName"], allowed: { kind: ["customer", "subcontractor"] } },
|
||||
"portal.grant_access": { required: ["portalUserId", "projectId"] },
|
||||
"portal.revoke_access": { required: ["portalUserId", "projectId"] },
|
||||
"portal.release_document": { required: ["projectId", "fileId"] },
|
||||
"portal.send_status_mail": { required: ["projectId", "stageChangeId"] },
|
||||
"portal.disable_user": { required: ["portalUserId"] },
|
||||
};
|
||||
|
||||
export function incompleteAutomationNodeConfigKeys(nodeType: string, config: Record<string, unknown>): readonly string[] {
|
||||
const contract = AUTOMATION_CONFIG_REQUIREMENTS[nodeType];
|
||||
if (!contract) return [];
|
||||
const invalid = new Set<string>();
|
||||
for (const key of contract.required ?? []) {
|
||||
if (!hasAutomationConfigValue(config[key])) invalid.add(key);
|
||||
}
|
||||
for (const [key, allowedValues] of Object.entries(contract.allowed ?? {})) {
|
||||
const value = config[key];
|
||||
if (hasAutomationConfigValue(value) && (typeof value !== "string" || !allowedValues.includes(value))) invalid.add(key);
|
||||
}
|
||||
for (const conditional of contract.requiredWhen ?? []) {
|
||||
if (config[conditional.whenKey] === conditional.equals && !hasAutomationConfigValue(config[conditional.key])) invalid.add(conditional.key);
|
||||
}
|
||||
if (nodeType === "delay.wait" && hasAutomationConfigValue(config.dauer)) {
|
||||
const amount = Number(config.dauer);
|
||||
if (!Number.isFinite(amount) || amount <= 0) invalid.add("dauer");
|
||||
}
|
||||
if (nodeType === "loop.for_each" && hasAutomationConfigValue(config.maxDurchlaeufe)) {
|
||||
const count = Number(config.maxDurchlaeufe);
|
||||
if (!Number.isInteger(count) || count < 1 || count > 100) invalid.add("maxDurchlaeufe");
|
||||
}
|
||||
if (nodeType === "projects.deadline_soon" && hasAutomationConfigValue(config.leadTime)) {
|
||||
const leadTime = Number(config.leadTime);
|
||||
if (!Number.isFinite(leadTime) || leadTime <= 0) invalid.add("leadTime");
|
||||
}
|
||||
if (nodeType === "time.schedule" && hasAutomationConfigValue(config.uhrzeit)) {
|
||||
if (typeof config.uhrzeit !== "string" || !/^(?:[01]\d|2[0-3]):[0-5]\d$/u.test(config.uhrzeit.trim())) invalid.add("uhrzeit");
|
||||
}
|
||||
if (nodeType === "time.schedule" && hasAutomationConfigValue(config.monatstag)) {
|
||||
const day = Number(config.monatstag);
|
||||
if (!Number.isInteger(day) || day < 1 || day > 31) invalid.add("monatstag");
|
||||
}
|
||||
return [...invalid];
|
||||
}
|
||||
|
||||
function hasAutomationConfigValue(value: unknown): boolean {
|
||||
if (typeof value === "string") return value.trim().length > 0;
|
||||
return typeof value === "number" ? Number.isFinite(value) : typeof value === "boolean";
|
||||
}
|
||||
|
||||
export function applyAutomationEditorOperation(
|
||||
flow: AutomationEditorFlow,
|
||||
operation: AutomationEditorOperation,
|
||||
catalog: readonly AutomationNodeDefinition[]
|
||||
): AutomationEditorFlow {
|
||||
if (operation.type === "undo") return undoFlow(flow);
|
||||
if (operation.type === "redo") return redoFlow(flow);
|
||||
|
||||
@@ -192,45 +400,143 @@ export function applyAutomationEditorOperation(flow: AutomationEditorFlow, opera
|
||||
nodeType: node.key,
|
||||
parentStepIds,
|
||||
config: node.defaultConfig,
|
||||
position: { x: 160 * (nextSteps.length % 4), y: 120 * Math.floor(nextSteps.length / 4) },
|
||||
position: gridPosition(nextSteps.length),
|
||||
sortOrder: nextSteps.length,
|
||||
summaryKey: node.titleKey,
|
||||
});
|
||||
}
|
||||
if (operation.type === "delete-node") {
|
||||
if (operation.type === "delete-node" || operation.type === "delete-nodes") {
|
||||
const removed = new Set(operation.type === "delete-node" ? [operation.stepKey] : operation.stepKeys);
|
||||
nextSteps = nextSteps
|
||||
.filter((step) => step.stepKey !== operation.stepKey)
|
||||
.map((step, index) => ({ ...step, parentStepIds: step.parentStepIds.filter((parent) => parent !== operation.stepKey), sortOrder: index }));
|
||||
.filter((step) => !removed.has(step.stepKey))
|
||||
.map((step, index) => ({ ...step, parentStepIds: step.parentStepIds.filter((parent) => !removed.has(parent)), sortOrder: index }));
|
||||
}
|
||||
if (operation.type === "duplicate-node") {
|
||||
const source = nextSteps.find((step) => step.stepKey === operation.stepKey);
|
||||
if (!source) return flow;
|
||||
nextSteps.push({ ...source, stepKey: uniqueStepKey(nextSteps, source.nodeType), sortOrder: nextSteps.length, position: { x: source.position.x + 48, y: source.position.y + 48 } });
|
||||
nextSteps.push({
|
||||
...source,
|
||||
stepKey: uniqueStepKey(nextSteps, source.nodeType),
|
||||
sortOrder: nextSteps.length,
|
||||
position: { x: source.position.x + 48, y: source.position.y + 48 },
|
||||
});
|
||||
}
|
||||
if (operation.type === "paste-steps") {
|
||||
const pasted = operation.steps
|
||||
.map((raw, index) => normalizeStep(raw, nextSteps.length + index))
|
||||
.filter(
|
||||
(step): step is AutomationEditorStep => step !== null && Boolean(catalog.find((item) => item.key === step.nodeType) ?? getAutomationNode(step.nodeType))
|
||||
);
|
||||
if (pasted.length === 0) return flow;
|
||||
const keyMap = new Map<string, string>();
|
||||
const accumulated = [...nextSteps];
|
||||
for (const step of pasted) {
|
||||
const freshKey = uniqueStepKey(accumulated, step.nodeType);
|
||||
keyMap.set(step.stepKey, freshKey);
|
||||
accumulated.push({ ...step, stepKey: freshKey });
|
||||
}
|
||||
const existingKeys = new Set(nextSteps.map((step) => step.stepKey));
|
||||
for (const step of pasted) {
|
||||
nextSteps.push({
|
||||
...step,
|
||||
stepKey: keyMap.get(step.stepKey) ?? step.stepKey,
|
||||
parentStepIds: step.parentStepIds
|
||||
.map((parent) => keyMap.get(parent) ?? (existingKeys.has(parent) ? parent : null))
|
||||
.filter((parent): parent is string => parent !== null),
|
||||
config: remapConditionBranchParents(step.config, keyMap, existingKeys),
|
||||
position: { x: step.position.x + 48, y: step.position.y + 48 },
|
||||
sortOrder: nextSteps.length,
|
||||
});
|
||||
}
|
||||
}
|
||||
if (operation.type === "connect") {
|
||||
const source = nextSteps.find((step) => step.stepKey === operation.fromStepKey);
|
||||
nextSteps = nextSteps.map((step) =>
|
||||
step.stepKey === operation.toStepKey && step.stepKey !== operation.fromStepKey
|
||||
? { ...step, parentStepIds: uniqueStrings([...step.parentStepIds, operation.fromStepKey]) }
|
||||
? {
|
||||
...step,
|
||||
parentStepIds: uniqueStrings([...step.parentStepIds, operation.fromStepKey]),
|
||||
config:
|
||||
source?.nodeType === "condition.if_else"
|
||||
? withAutomationConditionBranch(step.config, operation.fromStepKey, operation.branch ?? "true")
|
||||
: step.config,
|
||||
}
|
||||
: step
|
||||
);
|
||||
}
|
||||
if (operation.type === "disconnect") {
|
||||
nextSteps = nextSteps.map((step) => (step.stepKey === operation.toStepKey ? { ...step, parentStepIds: step.parentStepIds.filter((parent) => parent !== operation.fromStepKey) } : step));
|
||||
nextSteps = nextSteps.map((step) =>
|
||||
step.stepKey === operation.toStepKey
|
||||
? {
|
||||
...step,
|
||||
parentStepIds: step.parentStepIds.filter((parent) => parent !== operation.fromStepKey),
|
||||
config: withAutomationConditionBranch(step.config, operation.fromStepKey, null),
|
||||
}
|
||||
: step
|
||||
);
|
||||
}
|
||||
if (operation.type === "auto-layout") {
|
||||
nextSteps = nextSteps.map((step, index) => ({ ...step, position: { x: 220 * (index % 3), y: 140 * Math.floor(index / 3) }, sortOrder: index }));
|
||||
nextSteps = nextSteps.map((step, index) => ({ ...step, position: gridPosition(index), sortOrder: index }));
|
||||
}
|
||||
|
||||
return withHistory({ triggerKey: nextSteps.find((step) => step.kind === "trigger")?.nodeType ?? flow.triggerKey, steps: nextSteps, history: flow.history }, before);
|
||||
return withHistory(
|
||||
{ triggerKey: nextSteps.find((step) => step.kind === "trigger")?.nodeType ?? flow.triggerKey, steps: nextSteps, history: flow.history },
|
||||
before
|
||||
);
|
||||
}
|
||||
|
||||
export function buildAutomationDryRunPreview(input: { readonly flow: AutomationEditorFlow; readonly matchedRecords?: number; readonly examples?: readonly string[] }): AutomationDryRunPreview {
|
||||
function remapConditionBranchParents(
|
||||
config: Record<string, unknown>,
|
||||
keyMap: ReadonlyMap<string, string>,
|
||||
existingKeys: ReadonlySet<string>
|
||||
): Record<string, unknown> {
|
||||
const next = { ...config };
|
||||
delete next[AUTOMATION_CONDITION_BRANCHES_CONFIG_KEY];
|
||||
for (const [parentStepKey, branch] of Object.entries(automationConditionBranches(config))) {
|
||||
const remappedParent = keyMap.get(parentStepKey) ?? (existingKeys.has(parentStepKey) ? parentStepKey : null);
|
||||
if (remappedParent) Object.assign(next, withAutomationConditionBranch(next, remappedParent, branch));
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts the given steps as serializable clipboard payload. Parent references
|
||||
* pointing outside the selection are kept so a paste into the same flow can
|
||||
* re-attach to still-existing steps; `applyAutomationEditorOperation` drops
|
||||
* references that no longer resolve.
|
||||
*/
|
||||
export function extractAutomationClipboardSteps(flow: AutomationEditorFlow, stepKeys: readonly string[]): readonly AutomationEditorStepInput[] {
|
||||
const wanted = new Set(stepKeys);
|
||||
return flow.steps
|
||||
.filter((step) => wanted.has(step.stepKey))
|
||||
.map((step) => ({
|
||||
stepKey: step.stepKey,
|
||||
kind: step.kind,
|
||||
nodeType: step.nodeType,
|
||||
parentStepIds: [...step.parentStepIds],
|
||||
config: { ...step.config },
|
||||
position: { ...step.position },
|
||||
sortOrder: step.sortOrder,
|
||||
summaryKey: step.summaryKey,
|
||||
}));
|
||||
}
|
||||
|
||||
export function buildAutomationDryRunPreview(input: {
|
||||
readonly flow: AutomationEditorFlow;
|
||||
readonly confirmationPhrase: string;
|
||||
readonly matchedRecords?: number;
|
||||
readonly inspectedEvents?: number;
|
||||
readonly sampleLimitReached?: boolean;
|
||||
readonly examples?: readonly string[];
|
||||
}): AutomationDryRunPreview {
|
||||
const matchedRecords = Math.max(0, input.matchedRecords ?? 0);
|
||||
const validation = validateAutomationEditorFlow(input.flow);
|
||||
return {
|
||||
requiresConfirmation: matchedRecords > DRY_RUN_CONFIRMATION_THRESHOLD,
|
||||
confirmationPhrase: DRY_RUN_CONFIRMATION_PHRASE,
|
||||
confirmationPhrase: input.confirmationPhrase,
|
||||
matchedRecords,
|
||||
inspectedEvents: Math.max(0, input.inspectedEvents ?? matchedRecords),
|
||||
sampleLimitReached: input.sampleLimitReached ?? false,
|
||||
examples: (input.examples ?? []).slice(0, 5),
|
||||
steps: input.flow.steps.map((step) => ({
|
||||
stepKey: step.stepKey,
|
||||
@@ -242,29 +548,47 @@ export function buildAutomationDryRunPreview(input: { readonly flow: AutomationE
|
||||
};
|
||||
}
|
||||
|
||||
export function canConfirmAutomationDryRun(input: { readonly matchedRecords: number; readonly confirmationPhrase?: string | null }): boolean {
|
||||
return input.matchedRecords <= DRY_RUN_CONFIRMATION_THRESHOLD || input.confirmationPhrase === DRY_RUN_CONFIRMATION_PHRASE;
|
||||
export function canConfirmAutomationDryRun(input: {
|
||||
readonly matchedRecords: number;
|
||||
readonly confirmationPhrase?: string | null;
|
||||
readonly expectedConfirmationPhrase: string;
|
||||
}): boolean {
|
||||
return input.matchedRecords <= DRY_RUN_CONFIRMATION_THRESHOLD || input.confirmationPhrase?.trim() === input.expectedConfirmationPhrase;
|
||||
}
|
||||
|
||||
export function buildAutomationReversePlan(input: {
|
||||
readonly reverseWindowExpiresAt: string | Date | null;
|
||||
readonly steps: readonly { readonly stepKey: string; readonly nodeType: string }[];
|
||||
readonly steps: readonly { readonly stepKey: string; readonly nodeType: string; readonly output?: unknown }[];
|
||||
readonly confirmationPhrase: string;
|
||||
readonly now?: Date;
|
||||
}): AutomationReversePlan {
|
||||
const expiresAt = typeof input.reverseWindowExpiresAt === "string" ? new Date(input.reverseWindowExpiresAt) : input.reverseWindowExpiresAt;
|
||||
const canReverse = !!expiresAt && expiresAt.getTime() > (input.now ?? new Date()).getTime();
|
||||
const items = input.steps.map((step) => {
|
||||
const action = reverseActionForNode(step.nodeType);
|
||||
return { stepKey: step.stepKey, nodeType: step.nodeType, actionKey: action.actionKey, reversible: action.reversible };
|
||||
return {
|
||||
stepKey: step.stepKey,
|
||||
nodeType: step.nodeType,
|
||||
actionKey: action.actionKey,
|
||||
reversible: action.reversible,
|
||||
recipients: extractAutomationReverseRecipients(step.nodeType, step.output),
|
||||
};
|
||||
});
|
||||
return {
|
||||
canReverse,
|
||||
confirmationPhrase: REVERSE_CONFIRMATION_PHRASE,
|
||||
confirmationPhrase: input.confirmationPhrase,
|
||||
items,
|
||||
warnings: items.filter((item) => !item.reversible).map((item) => item.actionKey),
|
||||
};
|
||||
}
|
||||
|
||||
export function canConfirmAutomationReverse(input: {
|
||||
readonly confirmationPhrase: string | null | undefined;
|
||||
readonly expectedConfirmationPhrase: string;
|
||||
}): boolean {
|
||||
return input.confirmationPhrase?.trim().toLocaleUpperCase() === input.expectedConfirmationPhrase.trim().toLocaleUpperCase();
|
||||
}
|
||||
|
||||
function normalizeStep(raw: AutomationEditorStepInput, index: number): AutomationEditorStep | null {
|
||||
const object = objectOrEmpty(raw);
|
||||
const nodeType = typeof object.nodeType === "string" ? object.nodeType : "";
|
||||
@@ -279,23 +603,40 @@ function normalizeStep(raw: AutomationEditorStepInput, index: number): Automatio
|
||||
config: objectOrEmpty(object.config),
|
||||
position: normalizePosition(object.position, index),
|
||||
sortOrder: typeof object.sortOrder === "number" ? object.sortOrder : index,
|
||||
summaryKey: typeof object.summaryKey === "string" ? object.summaryKey : typeof object.summaryText === "string" ? object.summaryText : node?.titleKey ?? "automation.execution.stepQueued",
|
||||
summaryKey:
|
||||
typeof object.summaryKey === "string"
|
||||
? object.summaryKey
|
||||
: typeof object.summaryText === "string"
|
||||
? object.summaryText
|
||||
: (node?.titleKey ?? "automation.execution.stepQueued"),
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeHistory(value: unknown): AutomationEditorFlow["history"] {
|
||||
const raw = objectOrEmpty(value);
|
||||
return {
|
||||
past: Array.isArray(raw.past) ? raw.past.map(normalizeSnapshot).filter((item): item is AutomationEditorSnapshot => item !== null).slice(-MAX_HISTORY) : [],
|
||||
future: Array.isArray(raw.future) ? raw.future.map(normalizeSnapshot).filter((item): item is AutomationEditorSnapshot => item !== null).slice(-MAX_HISTORY) : [],
|
||||
past: Array.isArray(raw.past)
|
||||
? raw.past
|
||||
.map(normalizeSnapshot)
|
||||
.filter((item): item is AutomationEditorSnapshot => item !== null)
|
||||
.slice(-MAX_HISTORY)
|
||||
: [],
|
||||
future: Array.isArray(raw.future)
|
||||
? raw.future
|
||||
.map(normalizeSnapshot)
|
||||
.filter((item): item is AutomationEditorSnapshot => item !== null)
|
||||
.slice(-MAX_HISTORY)
|
||||
: [],
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeSnapshot(value: unknown): AutomationEditorSnapshot | null {
|
||||
const raw = objectOrEmpty(value);
|
||||
const steps = Array.isArray(raw.steps) ? raw.steps.map((step, index) => normalizeStep(step as AutomationEditorStepInput, index)).filter((step): step is AutomationEditorStep => step !== null) : [];
|
||||
const steps = Array.isArray(raw.steps)
|
||||
? raw.steps.map((step, index) => normalizeStep(step as AutomationEditorStepInput, index)).filter((step): step is AutomationEditorStep => step !== null)
|
||||
: [];
|
||||
if (steps.length === 0) return null;
|
||||
return { triggerKey: typeof raw.triggerKey === "string" ? raw.triggerKey : steps.find((step) => step.kind === "trigger")?.nodeType ?? "", steps };
|
||||
return { triggerKey: typeof raw.triggerKey === "string" ? raw.triggerKey : (steps.find((step) => step.kind === "trigger")?.nodeType ?? ""), steps };
|
||||
}
|
||||
|
||||
function normalizeKind(value: unknown, fallback: AutomationNodeKind): AutomationNodeKind {
|
||||
@@ -304,9 +645,10 @@ function normalizeKind(value: unknown, fallback: AutomationNodeKind): Automation
|
||||
|
||||
function normalizePosition(value: unknown, index: number): AutomationEditorStep["position"] {
|
||||
const raw = objectOrEmpty(value);
|
||||
const fallback = gridPosition(index);
|
||||
return {
|
||||
x: typeof raw.x === "number" ? raw.x : 220 * (index % 3),
|
||||
y: typeof raw.y === "number" ? raw.y : 140 * Math.floor(index / 3),
|
||||
x: typeof raw.x === "number" ? raw.x : fallback.x,
|
||||
y: typeof raw.y === "number" ? raw.y : fallback.y,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -390,12 +732,42 @@ function uniqueStrings(values: readonly string[]): readonly string[] {
|
||||
return [...new Set(values.filter(Boolean))];
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the delivered-recipient list from a persisted send-step output.
|
||||
* Contract: `output.recipients` is an array of strings (email) or objects with
|
||||
* `name`/`email`. Tolerates missing or malformed outputs (returns empty list)
|
||||
* because forward outputs are only available once the executor persisted them.
|
||||
*/
|
||||
export function extractAutomationReverseRecipients(nodeType: string, output: unknown): readonly AutomationReverseRecipient[] {
|
||||
if (nodeType !== "notification.send" && !nodeType.startsWith("email.")) return [];
|
||||
const record = objectOrEmpty(output);
|
||||
const raw = Array.isArray(record.recipients) ? record.recipients : [];
|
||||
return raw
|
||||
.map((entry): AutomationReverseRecipient => {
|
||||
if (typeof entry === "string") return { name: null, email: entry };
|
||||
const item = objectOrEmpty(entry);
|
||||
return {
|
||||
name: typeof item.name === "string" && item.name.trim() ? item.name : null,
|
||||
email: typeof item.email === "string" && item.email.trim() ? item.email : null,
|
||||
};
|
||||
})
|
||||
.filter((entry) => entry.name !== null || entry.email !== null);
|
||||
}
|
||||
|
||||
function reverseActionForNode(nodeType: string): { actionKey: string; reversible: boolean } {
|
||||
if (nodeType === "task.create") return { actionKey: "automation.editor.reverse.actions.deleteTask", reversible: true };
|
||||
if (nodeType === "crm.update_kontakt") return { actionKey: "automation.editor.reverse.actions.revertCrmStatus", reversible: true };
|
||||
if (nodeType === "crm.create_note") return { actionKey: "automation.editor.reverse.actions.deleteCrmNote", reversible: true };
|
||||
if (nodeType === "crm.add_tag") return { actionKey: "automation.editor.reverse.actions.removeContactTag", reversible: true };
|
||||
if (nodeType === "crm.remove_tag") return { actionKey: "automation.editor.reverse.actions.restoreContactTag", reversible: true };
|
||||
if (nodeType === "crm.assign_kontakt") return { actionKey: "automation.editor.reverse.actions.restoreContactAssignment", reversible: true };
|
||||
if (nodeType === "lead.assign") return { actionKey: "automation.editor.reverse.actions.restoreLeadAssignment", reversible: true };
|
||||
if (nodeType === "lead.set_status") return { actionKey: "automation.editor.reverse.actions.restoreLeadStatus", reversible: true };
|
||||
// CRM notes are append-only Activity entries in the current typed model. They
|
||||
// stay visible for auditability and therefore cannot be destructively undone.
|
||||
if (nodeType === "crm.create_note") return { actionKey: "automation.editor.reverse.actions.deleteCrmNote", reversible: false };
|
||||
if (nodeType === "task.assign") return { actionKey: "automation.editor.reverse.actions.restoreTaskAssignment", reversible: true };
|
||||
if (nodeType === "notification.send" || nodeType.startsWith("email.")) return { actionKey: "automation.editor.reverse.actions.deliveryNotReversible", reversible: false };
|
||||
if (nodeType === "notification.send" || nodeType.startsWith("email.") || nodeType === "chat.post_message")
|
||||
return { actionKey: "automation.editor.reverse.actions.deliveryNotReversible", reversible: false };
|
||||
return { actionKey: "automation.editor.reverse.actions.noop", reversible: false };
|
||||
}
|
||||
|
||||
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
import { buildWorkflowTriggerOutboxEvent } from "@hivegrid/queue";
|
||||
|
||||
export function buildCalendarCreatedWorkflowEvent(input: {
|
||||
readonly tenantId: string;
|
||||
readonly calendarEventId: string;
|
||||
readonly userId: string | null;
|
||||
readonly calendarKey: string;
|
||||
readonly eventKind: string;
|
||||
readonly source: string;
|
||||
readonly sourceEntityId: string;
|
||||
readonly startsAt: Date;
|
||||
readonly endsAt: Date;
|
||||
}) {
|
||||
return buildWorkflowTriggerOutboxEvent({
|
||||
tenantId: input.tenantId,
|
||||
event: "calendar.event_created",
|
||||
data: {
|
||||
calendarEventId: input.calendarEventId,
|
||||
calendarKey: input.calendarKey,
|
||||
kalender: input.calendarKey,
|
||||
eventKind: input.eventKind,
|
||||
ereignisart: input.eventKind,
|
||||
source: input.source,
|
||||
sourceEntityId: input.sourceEntityId,
|
||||
startsAt: input.startsAt.toISOString(),
|
||||
endsAt: input.endsAt.toISOString(),
|
||||
},
|
||||
userId: input.userId,
|
||||
sourceId: `calendar:${input.calendarEventId}:created`,
|
||||
});
|
||||
}
|
||||
+188
-6
@@ -1,17 +1,23 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { AUTOMATION_CORE_EXECUTOR_NODE_TYPES } from "@hivegrid/db/automation-executor.server";
|
||||
import {
|
||||
AUTOMATION_MODULE_KEY,
|
||||
AUTOMATION_READ_PERMISSION,
|
||||
AUTOMATION_TRIGGERS_WITHOUT_EMITTER,
|
||||
automationActionCatalog,
|
||||
automationTemplateCatalog,
|
||||
automationTemplateFlowData,
|
||||
automationTriggerCatalog,
|
||||
buildAutomationIdempotencyKey,
|
||||
buildReverseWindowExpiresAt,
|
||||
evaluateLoopGuard,
|
||||
evaluateTriggerVolume,
|
||||
getAutomationPlatformTemplateByStoredName,
|
||||
listAutomationNodes,
|
||||
planAutomationRetry,
|
||||
translateAutomationPlatformTemplate,
|
||||
} from "./automation.registry";
|
||||
import { buildAutomationEditorFlow, validateAutomationEditorFlow } from "./automation.editor";
|
||||
|
||||
describe("automation registry contract", () => {
|
||||
it("uses the R-P12a module and permission keys", () => {
|
||||
@@ -20,20 +26,183 @@ describe("automation registry contract", () => {
|
||||
});
|
||||
|
||||
it("covers the required trigger and action groups", () => {
|
||||
expect(new Set(automationTriggerCatalog.map((node) => node.group))).toEqual(new Set(["crm", "lead", "sales", "projects", "email", "forms", "booking", "calendar", "time", "webhook"]));
|
||||
expect(new Set(automationActionCatalog.map((node) => node.group))).toEqual(new Set(["crm", "notification", "http", "task", "flow_control", "kwp"]));
|
||||
expect(new Set(automationTriggerCatalog.map((node) => node.group))).toEqual(
|
||||
new Set(["crm", "lead", "sales", "projects", "email", "forms", "booking", "calendar", "time", "webhook", "portal"])
|
||||
);
|
||||
expect(new Set(automationActionCatalog.map((node) => node.group))).toEqual(
|
||||
new Set([
|
||||
"crm",
|
||||
"lead",
|
||||
"sales",
|
||||
"projects",
|
||||
"notification",
|
||||
"chat",
|
||||
"email",
|
||||
"webhook",
|
||||
"calendar",
|
||||
"files",
|
||||
"http",
|
||||
"task",
|
||||
"flow_control",
|
||||
"kwp",
|
||||
"portal",
|
||||
])
|
||||
);
|
||||
expect(automationActionCatalog.find((node) => node.key === "kwp.push_project")?.availability).toBe("extension_slot");
|
||||
expect(
|
||||
automationActionCatalog
|
||||
.filter((node) => ["crm.add_tag", "crm.remove_tag", "crm.assign_kontakt"].includes(node.key))
|
||||
.every((node) => node.availability === "active")
|
||||
).toBe(true);
|
||||
expect(
|
||||
automationActionCatalog.filter((node) => ["lead.assign", "lead.set_status"].includes(node.key)).every((node) => node.availability === "active")
|
||||
).toBe(true);
|
||||
expect(automationActionCatalog.find((node) => node.key === "chat.post_message")?.availability).toBe("active");
|
||||
expect(automationActionCatalog.filter((node) => ["flow.parallel", "flow.merge"].includes(node.key)).every((node) => node.availability === "active")).toBe(
|
||||
true
|
||||
);
|
||||
expect(automationActionCatalog.find((node) => node.key === "loop.for_each")).toMatchObject({ kind: "flow_control", availability: "extension_slot" });
|
||||
expect(listAutomationNodes()).toHaveLength(automationTriggerCatalog.length + automationActionCatalog.length);
|
||||
});
|
||||
|
||||
it("prepares every still-missing Phase-1 action without making it runnable", () => {
|
||||
expect(automationActionCatalog.filter((node) => node.availability === "extension_slot").map((node) => node.key)).toEqual([
|
||||
"lead.convert_to_project",
|
||||
"sales.create_project",
|
||||
"sales.change_stage",
|
||||
"sales.change_volume",
|
||||
"sales.assign_project",
|
||||
"sales.add_project_tag",
|
||||
"sales.move_pipeline",
|
||||
"projects.create_project",
|
||||
"projects.create_from_won_sales",
|
||||
"projects.change_stage",
|
||||
"projects.add_member",
|
||||
"projects.create_task",
|
||||
"projects.create_appointment",
|
||||
"projects.start_acceptance",
|
||||
"projects.move_pipeline",
|
||||
"notification.send_push",
|
||||
"webhook.send_signed",
|
||||
"calendar.create_event",
|
||||
"calendar.update_event",
|
||||
"files.create_from_url",
|
||||
"loop.for_each",
|
||||
"kwp.push_project",
|
||||
]);
|
||||
});
|
||||
|
||||
it("never exposes an active core action without a real executor handler", () => {
|
||||
const activeCoreNodes = automationActionCatalog.filter((node) => node.availability === "active" && node.group !== "portal");
|
||||
expect(activeCoreNodes.map((node) => node.key).filter((key) => !AUTOMATION_CORE_EXECUTOR_NODE_TYPES.has(key))).toEqual([]);
|
||||
});
|
||||
|
||||
it("registers the complete P26b portal trigger and action contracts", () => {
|
||||
expect(automationTriggerCatalog.filter((node) => node.group === "portal").map((node) => node.key)).toEqual([
|
||||
"portal.user_created",
|
||||
"portal.setup_completed",
|
||||
"portal.logged_in",
|
||||
"portal.upload_completed",
|
||||
"portal.complaint_submitted",
|
||||
"portal.access_granted",
|
||||
"portal.access_revoked",
|
||||
"portal.document_released",
|
||||
"portal.document_downloaded",
|
||||
"portal.status_mail_sent",
|
||||
"portal.lifecycle_changed",
|
||||
]);
|
||||
expect(automationActionCatalog.filter((node) => node.group === "portal").map((node) => node.key)).toEqual([
|
||||
"portal.invite_user",
|
||||
"portal.grant_access",
|
||||
"portal.revoke_access",
|
||||
"portal.release_document",
|
||||
"portal.send_status_mail",
|
||||
"portal.disable_user",
|
||||
]);
|
||||
for (const node of [...automationTriggerCatalog, ...automationActionCatalog].filter((entry) => entry.group === "portal")) {
|
||||
expect(node.availability).toBe("active");
|
||||
expect(node.requiredAnyPermission.every((permission) => permission.startsWith("portal."))).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it("tracks every catalog trigger that has no production emitter", () => {
|
||||
expect([...AUTOMATION_TRIGGERS_WITHOUT_EMITTER].sort()).toEqual([]);
|
||||
expect(AUTOMATION_TRIGGERS_WITHOUT_EMITTER.has("webhook.received")).toBe(false);
|
||||
});
|
||||
|
||||
it("ships platform templates that can become rules", () => {
|
||||
expect(automationTemplateCatalog.map((template) => template.key)).toEqual(["lead-qualified-follow-up", "project-deadline-warning", "form-submission-create-task"]);
|
||||
expect(automationTemplateCatalog.map((template) => template.key)).toEqual([
|
||||
"lead-qualified-follow-up",
|
||||
"project-deadline-warning",
|
||||
"form-submission-create-task",
|
||||
]);
|
||||
for (const template of automationTemplateCatalog) {
|
||||
expect(template.steps[0]?.kind).toBe("trigger");
|
||||
expect(template.steps.map((step) => step.stepKey)).toContain("trigger");
|
||||
const flowData = automationTemplateFlowData(template);
|
||||
const flow = buildAutomationEditorFlow({ flowData, steps: flowData.steps });
|
||||
expect(validateAutomationEditorFlow(flow).issues).toEqual([]);
|
||||
expect(validateAutomationEditorFlow(flow).canActivate).toBe(true);
|
||||
expect(getAutomationPlatformTemplateByStoredName(template.defaultName)?.key).toBe(template.key);
|
||||
expect(getAutomationPlatformTemplateByStoredName(template.nameKey)?.key).toBe(template.key);
|
||||
}
|
||||
});
|
||||
|
||||
it("translates all code-owned template copy without changing config semantics", () => {
|
||||
const translationKeys: string[] = [];
|
||||
const translate = (key: string) => {
|
||||
translationKeys.push(key);
|
||||
return `translated:${key}`;
|
||||
};
|
||||
|
||||
const [leadTemplate, deadlineTemplate, formTemplate] = automationTemplateCatalog;
|
||||
const translatedLead = translateAutomationPlatformTemplate(leadTemplate, translate);
|
||||
const translatedDeadline = translateAutomationPlatformTemplate(deadlineTemplate, translate);
|
||||
const translatedForm = translateAutomationPlatformTemplate(formTemplate, translate);
|
||||
|
||||
expect(translatedLead.name).toBe("translated:automation.templates.leadQualifiedFollowUp.name");
|
||||
expect(translatedLead.description).toBe("translated:automation.templates.leadQualifiedFollowUp.description");
|
||||
expect(translatedLead.flowData.steps.find((step) => step.stepKey === "create-task")?.config).toMatchObject({
|
||||
titel: "translated:automation.templates.leadQualifiedFollowUp.taskTitle",
|
||||
zustaendig: "besitzerDerAutomation",
|
||||
faelligkeit: "einTag",
|
||||
prioritaet: "hoch",
|
||||
});
|
||||
expect(translatedLead.flowData.steps.find((step) => step.stepKey === "notify-office")?.config).toMatchObject({
|
||||
betreff: "translated:automation.templates.leadQualifiedFollowUp.notificationSubject",
|
||||
nachricht: "translated:automation.templates.leadQualifiedFollowUp.notificationMessage",
|
||||
});
|
||||
expect(translatedDeadline.flowData.steps.find((step) => step.stepKey === "notify-project-lead")?.config).toMatchObject({
|
||||
betreff: "translated:automation.templates.projectDeadlineWarning.notificationSubject",
|
||||
nachricht: "translated:automation.templates.projectDeadlineWarning.notificationMessage",
|
||||
});
|
||||
expect(translatedForm.flowData.steps.find((step) => step.stepKey === "create-task")?.config.titel).toBe(
|
||||
"translated:automation.templates.formSubmissionCreateTask.taskTitle"
|
||||
);
|
||||
expect(translationKeys).toEqual([
|
||||
"automation.templates.leadQualifiedFollowUp.name",
|
||||
"automation.templates.leadQualifiedFollowUp.description",
|
||||
"automation.templates.leadQualifiedFollowUp.taskTitle",
|
||||
"automation.templates.leadQualifiedFollowUp.notificationSubject",
|
||||
"automation.templates.leadQualifiedFollowUp.notificationMessage",
|
||||
"automation.templates.projectDeadlineWarning.name",
|
||||
"automation.templates.projectDeadlineWarning.description",
|
||||
"automation.templates.projectDeadlineWarning.notificationSubject",
|
||||
"automation.templates.projectDeadlineWarning.notificationMessage",
|
||||
"automation.templates.formSubmissionCreateTask.name",
|
||||
"automation.templates.formSubmissionCreateTask.description",
|
||||
"automation.templates.formSubmissionCreateTask.taskTitle",
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps locale-free seed copy stable and excludes translation metadata", () => {
|
||||
const [template] = automationTemplateCatalog;
|
||||
const flowData = automationTemplateFlowData(template);
|
||||
|
||||
expect(flowData.steps.find((step) => step.stepKey === "create-task")?.config.titel).toBe("Qualifizierten Lead nachfassen");
|
||||
expect(flowData.steps.every((step) => !("configTranslationKeys" in step))).toBe(true);
|
||||
});
|
||||
|
||||
it("detects dependency cycles for loop guard warnings", () => {
|
||||
expect(
|
||||
evaluateLoopGuard([
|
||||
@@ -52,12 +221,21 @@ describe("automation registry contract", () => {
|
||||
});
|
||||
|
||||
it("builds idempotency keys and 24h reverse windows deterministically", () => {
|
||||
expect(buildAutomationIdempotencyKey({ tenantId: "t1", ruleId: "r1", triggerKey: "lead.qualified", sourceEventId: "evt1" })).toBe("t1:r1:lead.qualified:evt1");
|
||||
expect(buildAutomationIdempotencyKey({ tenantId: "t1", ruleId: "r1", triggerKey: "lead.qualified", sourceEventId: "evt1" })).toBe(
|
||||
"t1:r1:lead.qualified:evt1"
|
||||
);
|
||||
expect(buildReverseWindowExpiresAt(new Date("2026-07-01T10:00:00.000Z")).toISOString()).toBe("2026-07-02T10:00:00.000Z");
|
||||
});
|
||||
|
||||
it("pauses anomalous trigger volumes with Klartext diagnostics", () => {
|
||||
const result = evaluateTriggerVolume({ triggerKey: "lead.qualified", countInWindow: 2000, windowMinutes: 5, typicalDailyMin: 5, typicalDailyMax: 10, hardLimitInWindow: 2000 });
|
||||
const result = evaluateTriggerVolume({
|
||||
triggerKey: "lead.qualified",
|
||||
countInWindow: 2000,
|
||||
windowMinutes: 5,
|
||||
typicalDailyMin: 5,
|
||||
typicalDailyMax: 10,
|
||||
hardLimitInWindow: 2000,
|
||||
});
|
||||
|
||||
expect(result.action).toBe("pause");
|
||||
expect(result.summaryText).toContain("2000 automation triggers in 5 minutes");
|
||||
@@ -69,6 +247,10 @@ describe("automation registry contract", () => {
|
||||
expect(retry).toMatchObject({ shouldRetry: true, nextAttempt: 2, summaryKey: "automation.guards.retryScheduled" });
|
||||
expect(retry.nextRetryAt?.toISOString()).toBe("2026-07-01T10:00:01.000Z");
|
||||
|
||||
expect(planAutomationRetry({ attempt: 3, maxAttempts: 3 })).toMatchObject({ shouldRetry: false, nextAttempt: 4, summaryKey: "automation.guards.retryExhausted" });
|
||||
expect(planAutomationRetry({ attempt: 3, maxAttempts: 3 })).toMatchObject({
|
||||
shouldRetry: false,
|
||||
nextAttempt: 4,
|
||||
summaryKey: "automation.guards.retryExhausted",
|
||||
});
|
||||
});
|
||||
});
|
||||
+290
-131
@@ -4,7 +4,25 @@ export const AUTOMATION_MANAGE_PERMISSION = "automation.manage";
|
||||
export const AUTOMATION_RUN_PERMISSION = "automation.run";
|
||||
export const AUTOMATION_ADMIN_PERMISSION = "automation.admin";
|
||||
|
||||
export type AutomationNodeGroup = "crm" | "lead" | "sales" | "projects" | "email" | "forms" | "booking" | "calendar" | "time" | "webhook" | "notification" | "http" | "task" | "flow_control" | "kwp";
|
||||
export type AutomationNodeGroup =
|
||||
| "crm"
|
||||
| "lead"
|
||||
| "sales"
|
||||
| "projects"
|
||||
| "email"
|
||||
| "forms"
|
||||
| "booking"
|
||||
| "calendar"
|
||||
| "chat"
|
||||
| "files"
|
||||
| "time"
|
||||
| "webhook"
|
||||
| "notification"
|
||||
| "http"
|
||||
| "task"
|
||||
| "flow_control"
|
||||
| "kwp"
|
||||
| "portal";
|
||||
export type AutomationNodeKind = "trigger" | "condition" | "action" | "flow_control";
|
||||
export type AutomationNodeAvailability = "active" | "extension_slot";
|
||||
|
||||
@@ -23,6 +41,13 @@ export interface AutomationTemplateDefinition {
|
||||
readonly key: string;
|
||||
readonly nameKey: string;
|
||||
readonly descriptionKey: string;
|
||||
/**
|
||||
* Legacy seed copy used only by the locale-free deployment seed and to match
|
||||
* rows written by older revisions. Request paths resolve `nameKey` and
|
||||
* `descriptionKey` instead, so this fallback must never become tenant copy.
|
||||
*/
|
||||
readonly defaultName: string;
|
||||
readonly defaultDescription: string;
|
||||
readonly category: "crm" | "sales" | "projects" | "operations";
|
||||
readonly triggerKey: string;
|
||||
readonly steps: readonly {
|
||||
@@ -31,42 +56,30 @@ export interface AutomationTemplateDefinition {
|
||||
readonly nodeType: string;
|
||||
readonly parentStepIds: readonly string[];
|
||||
readonly summaryKey: string;
|
||||
readonly config: Readonly<Record<string, string | number | boolean>>;
|
||||
/** Config fields whose code-owned copy is translated per request. */
|
||||
readonly configTranslationKeys?: Readonly<Record<string, string>>;
|
||||
}[];
|
||||
}
|
||||
|
||||
export interface AutomationGraphStep {
|
||||
readonly stepKey: string;
|
||||
readonly nodeType: string;
|
||||
readonly parentStepIds: readonly string[];
|
||||
}
|
||||
type AutomationTemplateTranslator = (key: string) => string;
|
||||
|
||||
export interface AutomationLoopGuardResult {
|
||||
readonly ok: boolean;
|
||||
readonly summaryKey: string;
|
||||
readonly cycleStepKeys: readonly string[];
|
||||
readonly dependencyEdges: readonly { readonly from: string; readonly to: string }[];
|
||||
}
|
||||
|
||||
export interface AutomationTriggerVolumeInput {
|
||||
readonly triggerKey: string;
|
||||
readonly countInWindow: number;
|
||||
readonly windowMinutes: number;
|
||||
readonly typicalDailyMin: number;
|
||||
readonly typicalDailyMax: number;
|
||||
readonly hardLimitInWindow: number;
|
||||
}
|
||||
|
||||
export interface AutomationTriggerVolumeResult {
|
||||
readonly action: "allow" | "pause";
|
||||
readonly summaryText: string;
|
||||
}
|
||||
|
||||
export interface AutomationRetryPlan {
|
||||
readonly shouldRetry: boolean;
|
||||
readonly nextRetryAt: Date | null;
|
||||
readonly nextAttempt: number;
|
||||
readonly summaryKey: string;
|
||||
}
|
||||
// R-P12c: the pure guard functions moved to @hivegrid/db/automation-guards so
|
||||
// the worker-side forward executor can share them. Re-exported here so all
|
||||
// existing web consumers keep importing from the registry unchanged.
|
||||
export {
|
||||
AUTOMATION_TRIGGER_VOLUME_ANOMALY_KEY,
|
||||
buildAutomationIdempotencyKey,
|
||||
buildReverseWindowExpiresAt,
|
||||
evaluateLoopGuard,
|
||||
evaluateTriggerVolume,
|
||||
planAutomationRetry,
|
||||
type AutomationGraphStep,
|
||||
type AutomationLoopGuardResult,
|
||||
type AutomationRetryPlan,
|
||||
type AutomationTriggerVolumeInput,
|
||||
type AutomationTriggerVolumeResult,
|
||||
} from "@hivegrid/db/automation-guards";
|
||||
|
||||
export const automationTriggerCatalog = Object.freeze([
|
||||
trigger("crm.kontakt_created", "crm", ["crm.read_all", "crm.write"]),
|
||||
@@ -85,58 +98,216 @@ export const automationTriggerCatalog = Object.freeze([
|
||||
trigger("calendar.event_created", "calendar", ["calendar.connect_own", "calendar.admin"]),
|
||||
trigger("time.schedule", "time", [AUTOMATION_MANAGE_PERMISSION]),
|
||||
trigger("webhook.received", "webhook", [AUTOMATION_RUN_PERMISSION, AUTOMATION_MANAGE_PERMISSION]),
|
||||
trigger("portal.user_created", "portal", ["portal.read", "portal.manage_users"]),
|
||||
trigger("portal.setup_completed", "portal", ["portal.activity.read", "portal.manage_users"]),
|
||||
trigger("portal.logged_in", "portal", ["portal.activity.read"]),
|
||||
trigger("portal.upload_completed", "portal", ["portal.activity.read"]),
|
||||
trigger("portal.complaint_submitted", "portal", ["portal.activity.read"]),
|
||||
trigger("portal.access_granted", "portal", ["portal.activity.read", "portal.manage_access"]),
|
||||
trigger("portal.access_revoked", "portal", ["portal.activity.read", "portal.manage_access"]),
|
||||
trigger("portal.document_released", "portal", ["portal.activity.read", "portal.manage_access"]),
|
||||
trigger("portal.document_downloaded", "portal", ["portal.activity.read"]),
|
||||
trigger("portal.status_mail_sent", "portal", ["portal.activity.read"]),
|
||||
trigger("portal.lifecycle_changed", "portal", ["portal.activity.read", "portal.manage_users"]),
|
||||
] as const satisfies readonly AutomationNodeDefinition[]);
|
||||
|
||||
export const automationActionCatalog = Object.freeze([
|
||||
action("crm.update_kontakt", "crm", ["crm.write"]),
|
||||
action("crm.add_tag", "crm", ["crm.write"]),
|
||||
action("crm.remove_tag", "crm", ["crm.write"]),
|
||||
action("crm.assign_kontakt", "crm", ["crm.write"]),
|
||||
action("crm.create_note", "crm", ["crm.write"]),
|
||||
action("lead.assign", "lead", ["leads.write"]),
|
||||
action("lead.set_status", "lead", ["leads.write"]),
|
||||
extension("lead.convert_to_project", "lead", ["leads.write", "projects.write"]),
|
||||
extension("sales.create_project", "sales", ["projects.write"]),
|
||||
extension("sales.change_stage", "sales", ["projects.change_stage"]),
|
||||
extension("sales.change_volume", "sales", ["projects.write"]),
|
||||
extension("sales.assign_project", "sales", ["projects.write"]),
|
||||
extension("sales.add_project_tag", "sales", ["projects.write"]),
|
||||
extension("sales.move_pipeline", "sales", ["projects.change_stage"]),
|
||||
extension("projects.create_project", "projects", ["projects.write"]),
|
||||
extension("projects.create_from_won_sales", "projects", ["projects.write"]),
|
||||
extension("projects.change_stage", "projects", ["projects.change_stage"]),
|
||||
extension("projects.add_member", "projects", ["projects.write"]),
|
||||
extension("projects.create_task", "projects", ["projects.write", "tasks.write"]),
|
||||
extension("projects.create_appointment", "projects", ["projects.write"]),
|
||||
extension("projects.start_acceptance", "projects", ["projects.write"]),
|
||||
extension("projects.move_pipeline", "projects", ["projects.change_stage"]),
|
||||
action("notification.send", "notification", [AUTOMATION_RUN_PERMISSION]),
|
||||
extension("notification.send_push", "notification", [AUTOMATION_RUN_PERMISSION]),
|
||||
action("chat.post_message", "chat", ["chat.write"]),
|
||||
// R-P12c: external transactional mail via the durable mail outbox (K-A2
|
||||
// "E-Mail senden" — was design-only until the forward executor existed).
|
||||
action("email.send_transactional", "email", [AUTOMATION_RUN_PERMISSION]),
|
||||
action("http.request", "http", [AUTOMATION_RUN_PERMISSION]),
|
||||
extension("webhook.send_signed", "webhook", [AUTOMATION_RUN_PERMISSION]),
|
||||
extension("calendar.create_event", "calendar", ["calendar.connect_own", "calendar.admin"]),
|
||||
extension("calendar.update_event", "calendar", ["calendar.connect_own", "calendar.admin"]),
|
||||
extension("files.create_from_url", "files", ["files.write"]),
|
||||
action("task.create", "task", ["tasks.write"]),
|
||||
action("task.assign", "task", ["tasks.write"]),
|
||||
flow("condition.if_else", "flow_control", [AUTOMATION_MANAGE_PERMISSION]),
|
||||
flow("delay.wait", "flow_control", [AUTOMATION_MANAGE_PERMISSION]),
|
||||
flow("loop.for_each", "flow_control", [AUTOMATION_MANAGE_PERMISSION]),
|
||||
flow("flow.parallel", "flow_control", [AUTOMATION_MANAGE_PERMISSION]),
|
||||
flow("flow.merge", "flow_control", [AUTOMATION_MANAGE_PERMISSION]),
|
||||
flowExtension("loop.for_each", "flow_control", [AUTOMATION_MANAGE_PERMISSION]),
|
||||
extension("kwp.push_project", "kwp", ["integrations.manual_sync", AUTOMATION_MANAGE_PERMISSION]),
|
||||
action("portal.invite_user", "portal", ["portal.manage_users"]),
|
||||
action("portal.grant_access", "portal", ["portal.manage_access"]),
|
||||
action("portal.revoke_access", "portal", ["portal.manage_access"]),
|
||||
action("portal.release_document", "portal", ["portal.manage_access"]),
|
||||
action("portal.send_status_mail", "portal", ["portal.activity.manage"]),
|
||||
action("portal.disable_user", "portal", ["portal.manage_users"]),
|
||||
] as const satisfies readonly AutomationNodeDefinition[]);
|
||||
|
||||
export const automationTemplateCatalog = Object.freeze([
|
||||
{
|
||||
key: "lead-qualified-follow-up",
|
||||
defaultName: "Qualifizierter Lead: Nachfassen",
|
||||
defaultDescription: "Legt nach einer Lead-Qualifizierung eine Vertriebsaufgabe an und benachrichtigt das Büro.",
|
||||
nameKey: "automation.templates.leadQualifiedFollowUp.name",
|
||||
descriptionKey: "automation.templates.leadQualifiedFollowUp.description",
|
||||
category: "sales",
|
||||
triggerKey: "lead.qualified",
|
||||
steps: [
|
||||
{ stepKey: "trigger", kind: "trigger", nodeType: "lead.qualified", parentStepIds: [], summaryKey: "automation.steps.triggerLeadQualified" },
|
||||
{ stepKey: "create-task", kind: "action", nodeType: "task.create", parentStepIds: ["trigger"], summaryKey: "automation.steps.createSalesTask" },
|
||||
{ stepKey: "notify-office", kind: "action", nodeType: "notification.send", parentStepIds: ["create-task"], summaryKey: "automation.steps.notifyOffice" },
|
||||
{
|
||||
stepKey: "trigger",
|
||||
kind: "trigger",
|
||||
nodeType: "lead.qualified",
|
||||
parentStepIds: [],
|
||||
summaryKey: "automation.steps.triggerLeadQualified",
|
||||
config: {},
|
||||
},
|
||||
{
|
||||
stepKey: "create-task",
|
||||
kind: "action",
|
||||
nodeType: "task.create",
|
||||
parentStepIds: ["trigger"],
|
||||
summaryKey: "automation.steps.createSalesTask",
|
||||
config: { titel: "Qualifizierten Lead nachfassen", zustaendig: "besitzerDerAutomation", faelligkeit: "einTag", prioritaet: "hoch" },
|
||||
configTranslationKeys: { titel: "automation.templates.leadQualifiedFollowUp.taskTitle" },
|
||||
},
|
||||
{
|
||||
stepKey: "notify-office",
|
||||
kind: "action",
|
||||
nodeType: "notification.send",
|
||||
parentStepIds: ["create-task"],
|
||||
summaryKey: "automation.steps.notifyOffice",
|
||||
config: {
|
||||
kanal: "intern",
|
||||
empfaenger: "besitzerDerAutomation",
|
||||
betreff: "Qualifizierter Lead",
|
||||
nachricht: "Ein qualifizierter Lead wartet auf Nachverfolgung.",
|
||||
},
|
||||
configTranslationKeys: {
|
||||
betreff: "automation.templates.leadQualifiedFollowUp.notificationSubject",
|
||||
nachricht: "automation.templates.leadQualifiedFollowUp.notificationMessage",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
key: "project-deadline-warning",
|
||||
defaultName: "Projektfrist früh warnen",
|
||||
defaultDescription: "Benachrichtigt die Projektleitung vor kritischen Fristen.",
|
||||
nameKey: "automation.templates.projectDeadlineWarning.name",
|
||||
descriptionKey: "automation.templates.projectDeadlineWarning.description",
|
||||
category: "projects",
|
||||
triggerKey: "projects.deadline_soon",
|
||||
steps: [
|
||||
{ stepKey: "trigger", kind: "trigger", nodeType: "projects.deadline_soon", parentStepIds: [], summaryKey: "automation.steps.triggerProjectDeadline" },
|
||||
{ stepKey: "notify-project-lead", kind: "action", nodeType: "notification.send", parentStepIds: ["trigger"], summaryKey: "automation.steps.notifyProjectLead" },
|
||||
{
|
||||
stepKey: "trigger",
|
||||
kind: "trigger",
|
||||
nodeType: "projects.deadline_soon",
|
||||
parentStepIds: [],
|
||||
summaryKey: "automation.steps.triggerProjectDeadline",
|
||||
config: { fristtyp: "projektDeadline", leadTime: "3", leadTimeUnit: "tage" },
|
||||
},
|
||||
{
|
||||
stepKey: "notify-project-lead",
|
||||
kind: "action",
|
||||
nodeType: "notification.send",
|
||||
parentStepIds: ["trigger"],
|
||||
summaryKey: "automation.steps.notifyProjectLead",
|
||||
config: {
|
||||
kanal: "intern",
|
||||
empfaenger: "besitzerDerAutomation",
|
||||
betreff: "Projektfrist naht",
|
||||
nachricht: "Eine Projektfrist wird in Kürze erreicht.",
|
||||
},
|
||||
configTranslationKeys: {
|
||||
betreff: "automation.templates.projectDeadlineWarning.notificationSubject",
|
||||
nachricht: "automation.templates.projectDeadlineWarning.notificationMessage",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
key: "form-submission-create-task",
|
||||
defaultName: "Formularantwort als Aufgabe",
|
||||
defaultDescription: "Erstellt aus einer Formularantwort eine Backoffice-Aufgabe.",
|
||||
nameKey: "automation.templates.formSubmissionCreateTask.name",
|
||||
descriptionKey: "automation.templates.formSubmissionCreateTask.description",
|
||||
category: "operations",
|
||||
triggerKey: "forms.submitted",
|
||||
steps: [
|
||||
{ stepKey: "trigger", kind: "trigger", nodeType: "forms.submitted", parentStepIds: [], summaryKey: "automation.steps.triggerFormSubmitted" },
|
||||
{ stepKey: "create-task", kind: "action", nodeType: "task.create", parentStepIds: ["trigger"], summaryKey: "automation.steps.createBackofficeTask" },
|
||||
{
|
||||
stepKey: "trigger",
|
||||
kind: "trigger",
|
||||
nodeType: "forms.submitted",
|
||||
parentStepIds: [],
|
||||
summaryKey: "automation.steps.triggerFormSubmitted",
|
||||
config: {},
|
||||
},
|
||||
{
|
||||
stepKey: "create-task",
|
||||
kind: "action",
|
||||
nodeType: "task.create",
|
||||
parentStepIds: ["trigger"],
|
||||
summaryKey: "automation.steps.createBackofficeTask",
|
||||
config: { titel: "Formularantwort prüfen", zustaendig: "besitzerDerAutomation", faelligkeit: "einTag", prioritaet: "normal" },
|
||||
configTranslationKeys: { titel: "automation.templates.formSubmissionCreateTask.taskTitle" },
|
||||
},
|
||||
],
|
||||
},
|
||||
] as const satisfies readonly AutomationTemplateDefinition[]);
|
||||
|
||||
export function automationTemplateFlowData(template: (typeof automationTemplateCatalog)[number], translate?: AutomationTemplateTranslator) {
|
||||
return {
|
||||
templateKey: template.key,
|
||||
triggerKey: template.triggerKey,
|
||||
steps: template.steps.map((step) => ({
|
||||
stepKey: step.stepKey,
|
||||
kind: step.kind,
|
||||
nodeType: step.nodeType,
|
||||
parentStepIds: step.parentStepIds,
|
||||
summaryKey: step.summaryKey,
|
||||
config: Object.fromEntries(
|
||||
Object.entries(step.config).map(([field, value]) => {
|
||||
const configTranslationKeys =
|
||||
"configTranslationKeys" in step ? (step.configTranslationKeys as Readonly<Record<string, string>>) : undefined;
|
||||
const translationKey = configTranslationKeys?.[field];
|
||||
return [field, translate && translationKey ? translate(translationKey) : value];
|
||||
})
|
||||
),
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
export function translateAutomationPlatformTemplate(template: (typeof automationTemplateCatalog)[number], translate: AutomationTemplateTranslator) {
|
||||
return {
|
||||
name: translate(template.nameKey),
|
||||
description: translate(template.descriptionKey),
|
||||
flowData: automationTemplateFlowData(template, translate),
|
||||
};
|
||||
}
|
||||
|
||||
/** Resolves code-owned platform templates even when a persisted row is from an older seed revision. */
|
||||
export function getAutomationPlatformTemplateByStoredName(name: string): (typeof automationTemplateCatalog)[number] | undefined {
|
||||
return automationTemplateCatalog.find((template) => template.defaultName === name || template.nameKey === name);
|
||||
}
|
||||
|
||||
const nodeByKey = new Map([...automationTriggerCatalog, ...automationActionCatalog].map((node) => [node.key, node]));
|
||||
|
||||
export function listAutomationNodes(): readonly AutomationNodeDefinition[] {
|
||||
@@ -147,6 +318,37 @@ export function getAutomationNode(key: string): AutomationNodeDefinition | undef
|
||||
return nodeByKey.get(key);
|
||||
}
|
||||
|
||||
/**
|
||||
* Which executor can run a node. `portal.*` nodes are served exclusively by the
|
||||
* portal-automation consumer (apps/worker/src/jobs/portal-automation.ts), every
|
||||
* other node by the generic forward executor. The two never meet: a portal
|
||||
* action in a core flow ends the run as `unsupportedNode`, and the portal
|
||||
* consumer rejects a rule whose actions are not all portal actions. Mixing them
|
||||
* therefore has to be caught while building, not at runtime.
|
||||
*/
|
||||
export type AutomationExecutionFamily = "portal" | "core";
|
||||
|
||||
export function automationExecutionFamily(nodeKey: string): AutomationExecutionFamily {
|
||||
return nodeKey.startsWith("portal.") ? "portal" : "core";
|
||||
}
|
||||
|
||||
/**
|
||||
* Nodes the catalog lists but no executor implements yet. Active core and
|
||||
* portal nodes are backed by their corresponding executor; extension slots
|
||||
* remain non-runnable until their provider handler exists (AD-32 / KWP).
|
||||
*/
|
||||
const NODES_WITHOUT_EXECUTOR = new Set<string>();
|
||||
|
||||
export function isAutomationNodeRunnable(node: AutomationNodeDefinition): boolean {
|
||||
return node.availability === "active" && !NODES_WITHOUT_EXECUTOR.has(node.key);
|
||||
}
|
||||
|
||||
/**
|
||||
* Triggers the catalog offers that no emitter publishes yet, so a rule built on
|
||||
* them would sit active and never start.
|
||||
*/
|
||||
export const AUTOMATION_TRIGGERS_WITHOUT_EMITTER: ReadonlySet<string> = new Set();
|
||||
|
||||
export function assertAutomationNodeExists(key: string): AutomationNodeDefinition {
|
||||
const node = getAutomationNode(key);
|
||||
if (!node) {
|
||||
@@ -155,94 +357,6 @@ export function assertAutomationNodeExists(key: string): AutomationNodeDefinitio
|
||||
return node;
|
||||
}
|
||||
|
||||
export function evaluateLoopGuard(steps: readonly AutomationGraphStep[]): AutomationLoopGuardResult {
|
||||
const stepKeys = new Set(steps.map((step) => step.stepKey));
|
||||
const dependencyEdges = steps.flatMap((step) =>
|
||||
step.parentStepIds.filter((parentStepId) => stepKeys.has(parentStepId)).map((parentStepId) => ({ from: parentStepId, to: step.stepKey }))
|
||||
);
|
||||
const outgoing = new Map<string, string[]>();
|
||||
for (const edge of dependencyEdges) {
|
||||
outgoing.set(edge.from, [...(outgoing.get(edge.from) ?? []), edge.to]);
|
||||
}
|
||||
|
||||
const visiting = new Set<string>();
|
||||
const visited = new Set<string>();
|
||||
const path: string[] = [];
|
||||
|
||||
function visit(stepKey: string): string[] | null {
|
||||
if (visiting.has(stepKey)) {
|
||||
const start = path.indexOf(stepKey);
|
||||
return start >= 0 ? path.slice(start).concat(stepKey) : [stepKey];
|
||||
}
|
||||
if (visited.has(stepKey)) return null;
|
||||
visiting.add(stepKey);
|
||||
path.push(stepKey);
|
||||
for (const next of outgoing.get(stepKey) ?? []) {
|
||||
const cycle = visit(next);
|
||||
if (cycle) return cycle;
|
||||
}
|
||||
path.pop();
|
||||
visiting.delete(stepKey);
|
||||
visited.add(stepKey);
|
||||
return null;
|
||||
}
|
||||
|
||||
for (const step of steps) {
|
||||
const cycle = visit(step.stepKey);
|
||||
if (cycle) {
|
||||
return {
|
||||
ok: false,
|
||||
summaryKey: "automation.guards.loopDetected",
|
||||
cycleStepKeys: cycle,
|
||||
dependencyEdges,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
ok: true,
|
||||
summaryKey: "automation.guards.loopClear",
|
||||
cycleStepKeys: [],
|
||||
dependencyEdges,
|
||||
};
|
||||
}
|
||||
|
||||
export function evaluateTriggerVolume(input: AutomationTriggerVolumeInput): AutomationTriggerVolumeResult {
|
||||
if (input.countInWindow >= input.hardLimitInWindow) {
|
||||
return {
|
||||
action: "pause",
|
||||
summaryText: `${input.countInWindow} automation triggers in ${input.windowMinutes} minutes for ${input.triggerKey}; typical volume is ${input.typicalDailyMin}-${input.typicalDailyMax} per day. Rule paused for review.`,
|
||||
};
|
||||
}
|
||||
return {
|
||||
action: "allow",
|
||||
summaryText: `${input.countInWindow} automation triggers in ${input.windowMinutes} minutes for ${input.triggerKey}; guard within limit.`,
|
||||
};
|
||||
}
|
||||
|
||||
export function buildAutomationIdempotencyKey(input: { tenantId: string; ruleId: string; triggerKey: string; sourceEventId?: string | null; payloadHash?: string | null }): string {
|
||||
return [input.tenantId, input.ruleId, input.triggerKey, input.sourceEventId || input.payloadHash || "manual"].join(":");
|
||||
}
|
||||
|
||||
export function planAutomationRetry(input: { attempt: number; maxAttempts?: number; baseDelayMs?: number; now?: Date }): AutomationRetryPlan {
|
||||
const maxAttempts = input.maxAttempts ?? 3;
|
||||
const nextAttempt = input.attempt + 1;
|
||||
if (nextAttempt > maxAttempts) {
|
||||
return { shouldRetry: false, nextRetryAt: null, nextAttempt, summaryKey: "automation.guards.retryExhausted" };
|
||||
}
|
||||
const delayMs = (input.baseDelayMs ?? 60_000) * 2 ** Math.max(input.attempt - 1, 0);
|
||||
return {
|
||||
shouldRetry: true,
|
||||
nextRetryAt: new Date((input.now ?? new Date()).getTime() + delayMs),
|
||||
nextAttempt,
|
||||
summaryKey: "automation.guards.retryScheduled",
|
||||
};
|
||||
}
|
||||
|
||||
export function buildReverseWindowExpiresAt(now = new Date()): Date {
|
||||
return new Date(now.getTime() + 24 * 60 * 60 * 1000);
|
||||
}
|
||||
|
||||
function trigger(key: string, group: AutomationNodeGroup, requiredAnyPermission: readonly string[]): AutomationNodeDefinition {
|
||||
return node("trigger", key, group, requiredAnyPermission, "active");
|
||||
}
|
||||
@@ -259,7 +373,17 @@ function extension(key: string, group: AutomationNodeGroup, requiredAnyPermissio
|
||||
return node("action", key, group, requiredAnyPermission, "extension_slot");
|
||||
}
|
||||
|
||||
function node(kind: AutomationNodeKind, key: string, group: AutomationNodeGroup, requiredAnyPermission: readonly string[], availability: AutomationNodeAvailability): AutomationNodeDefinition {
|
||||
function flowExtension(key: string, group: AutomationNodeGroup, requiredAnyPermission: readonly string[]): AutomationNodeDefinition {
|
||||
return node("flow_control", key, group, requiredAnyPermission, "extension_slot");
|
||||
}
|
||||
|
||||
function node(
|
||||
kind: AutomationNodeKind,
|
||||
key: string,
|
||||
group: AutomationNodeGroup,
|
||||
requiredAnyPermission: readonly string[],
|
||||
availability: AutomationNodeAvailability
|
||||
): AutomationNodeDefinition {
|
||||
const i18nKey = key.replaceAll(".", "_");
|
||||
return {
|
||||
key,
|
||||
@@ -269,6 +393,41 @@ function node(kind: AutomationNodeKind, key: string, group: AutomationNodeGroup,
|
||||
descriptionKey: `automation.nodes.${i18nKey}.description`,
|
||||
requiredAnyPermission,
|
||||
availability,
|
||||
defaultConfig: {},
|
||||
defaultConfig: automationNodeDefaultConfig(key),
|
||||
};
|
||||
}
|
||||
|
||||
function automationNodeDefaultConfig(key: string): Record<string, string | number | boolean> {
|
||||
if (key === "crm.update_kontakt") return { kontakt: "ausloeser" };
|
||||
if (key === "crm.add_tag" || key === "crm.remove_tag" || key === "crm.assign_kontakt") return { kontakt: "ausloeser" };
|
||||
if (key === "lead.assign" || key === "lead.set_status") return { lead: "ausloeser" };
|
||||
if (key === "lead.convert_to_project") return { lead: "ausloeser", targetPipelineId: "", targetStageId: "" };
|
||||
if (key === "sales.create_project" || key === "projects.create_project") return { pipelineId: "", stageId: "", titel: "" };
|
||||
if (key === "sales.change_stage" || key === "projects.change_stage") return { project: "ausloeser", stageId: "" };
|
||||
if (key === "sales.change_volume") return { project: "ausloeser", volume: "" };
|
||||
if (key === "sales.assign_project" || key === "projects.add_member") return { project: "ausloeser", userId: "" };
|
||||
if (key === "sales.add_project_tag") return { project: "ausloeser", tagId: "" };
|
||||
if (key === "sales.move_pipeline" || key === "projects.move_pipeline") return { project: "ausloeser", pipelineId: "", stageId: "" };
|
||||
if (key === "projects.create_from_won_sales") return { salesProject: "ausloeser", mappingId: "" };
|
||||
if (key === "projects.create_task") return { project: "ausloeser", titel: "" };
|
||||
if (key === "projects.create_appointment") return { project: "ausloeser", titel: "", startsAt: "", endsAt: "" };
|
||||
if (key === "projects.start_acceptance") return { project: "ausloeser" };
|
||||
if (key === "crm.create_note") return { datensatz: "kontaktAusAusloeser" };
|
||||
if (key === "notification.send") return { kanal: "intern", empfaenger: "besitzerDerAutomation" };
|
||||
if (key === "notification.send_push") return { recipient: "besitzerDerAutomation", title: "", message: "" };
|
||||
if (key === "chat.post_message") return {};
|
||||
if (key === "task.create") return { zustaendig: "besitzerDerAutomation", prioritaet: "normal" };
|
||||
if (key === "task.assign") {
|
||||
return { aufgabe: "ausVorherigemSchritt", zustaendig: "erstellerDerAufgabe", benachrichtigungAn: "niemand" };
|
||||
}
|
||||
if (key === "condition.if_else") return { vergleich: "istGleich" };
|
||||
if (key === "delay.wait") return { dauer: "2", dauerEinheit: "minuten" };
|
||||
if (key === "loop.for_each") return { maxDurchlaeufe: "100" };
|
||||
if (key === "http.request") return { methode: "post" };
|
||||
if (key === "webhook.send_signed") return { url: "", credentialId: "", body: "" };
|
||||
if (key === "calendar.create_event") return { connectionId: "", title: "", startsAt: "", endsAt: "" };
|
||||
if (key === "calendar.update_event") return { connectionId: "", eventId: "", title: "", startsAt: "", endsAt: "" };
|
||||
if (key === "files.create_from_url") return { url: "", fileName: "" };
|
||||
if (key === "portal.invite_user") return { kind: "customer" };
|
||||
return {};
|
||||
}
|
||||
+320
@@ -0,0 +1,320 @@
|
||||
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<unknown>) => 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();
|
||||
});
|
||||
});
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
// R-P12c / R-P12b DoD 4 — manual run path: startAutomationExecutionForRule
|
||||
// dispatches queued live runs durably to the forward executor (outbox row in
|
||||
// the same transaction), dedups on the idempotency key and falls back to the
|
||||
// rule's own trigger key for run-now/retry/resume.
|
||||
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
tx: {
|
||||
automationRule: { findFirst: vi.fn(), update: vi.fn() },
|
||||
automationExecution: { findFirst: vi.fn(), create: vi.fn() },
|
||||
automationTriggerMeter: { upsert: vi.fn(), update: vi.fn() },
|
||||
outboxEvent: { create: vi.fn(), findUnique: vi.fn() },
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/db/.server/tenantRls.server", () => ({
|
||||
withTenantRLS: async (_tenantId: string, callback: (tx: typeof mocks.tx) => Promise<unknown>) => callback(mocks.tx),
|
||||
}));
|
||||
|
||||
import { startAutomationExecutionForRule } from "./automation.server";
|
||||
|
||||
const RULE = {
|
||||
id: "rule-1",
|
||||
enabled: true,
|
||||
status: "active",
|
||||
triggerKey: "forms.submitted",
|
||||
steps: [
|
||||
{ id: "rs-1", stepKey: "trigger", nodeType: "forms.submitted", stepKind: "trigger", parentStepIds: [], sortOrder: 0, summaryText: "t" },
|
||||
{ id: "rs-2", stepKey: "create-task", nodeType: "task.create", stepKind: "action", parentStepIds: ["trigger"], sortOrder: 1, summaryText: "a" },
|
||||
],
|
||||
};
|
||||
|
||||
describe("startAutomationExecutionForRule", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.tx.automationRule.findFirst.mockResolvedValue(RULE);
|
||||
mocks.tx.automationExecution.findFirst.mockResolvedValue(null);
|
||||
mocks.tx.automationExecution.create.mockResolvedValue({ id: "exec-1", status: "queued" });
|
||||
mocks.tx.automationTriggerMeter.upsert.mockResolvedValue({ count: 1 });
|
||||
mocks.tx.outboxEvent.create.mockImplementation(async (args: { data: unknown }) => args.data);
|
||||
});
|
||||
|
||||
it("queues a run with the rule's own trigger key and publishes the executor dispatch in the same tx", async () => {
|
||||
const result = await startAutomationExecutionForRule({
|
||||
tenantId: "tenant-1",
|
||||
tenantSlug: "tenant-1",
|
||||
userId: "user-1",
|
||||
ruleId: "rule-1",
|
||||
triggerPayload: { source: "manual" },
|
||||
sourceEventId: "manual:abc",
|
||||
});
|
||||
|
||||
expect(result).toEqual({ id: "exec-1", status: "queued", deduplicated: false });
|
||||
expect(mocks.tx.automationExecution.create).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ data: expect.objectContaining({ triggerKey: "forms.submitted" }) })
|
||||
);
|
||||
expect(mocks.tx.outboxEvent.create).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
data: expect.objectContaining({ eventType: "automation.execution.requested", dispatchKey: "automation-exec:exec-1:initial" }),
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("does not dispatch dry runs or deduplicated runs", async () => {
|
||||
await startAutomationExecutionForRule({
|
||||
tenantId: "tenant-1",
|
||||
tenantSlug: "tenant-1",
|
||||
userId: "user-1",
|
||||
ruleId: "rule-1",
|
||||
triggerPayload: {},
|
||||
dryRun: true,
|
||||
});
|
||||
expect(mocks.tx.outboxEvent.create).not.toHaveBeenCalled();
|
||||
|
||||
mocks.tx.automationExecution.findFirst.mockResolvedValue({ id: "exec-0", status: "success" });
|
||||
const result = await startAutomationExecutionForRule({
|
||||
tenantId: "tenant-1",
|
||||
tenantSlug: "tenant-1",
|
||||
userId: "user-1",
|
||||
ruleId: "rule-1",
|
||||
triggerPayload: {},
|
||||
sourceEventId: "manual:abc",
|
||||
});
|
||||
expect(result.deduplicated).toBe(true);
|
||||
expect(mocks.tx.outboxEvent.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("passes resumeFromStepId through to the new execution", async () => {
|
||||
await startAutomationExecutionForRule({
|
||||
tenantId: "tenant-1",
|
||||
tenantSlug: "tenant-1",
|
||||
userId: "user-1",
|
||||
ruleId: "rule-1",
|
||||
triggerPayload: {},
|
||||
sourceEventId: "resume:exec-0:xyz",
|
||||
resumeFromStepId: "rs-2",
|
||||
});
|
||||
expect(mocks.tx.automationExecution.create).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ data: expect.objectContaining({ resumeFromStepId: "rs-2" }) })
|
||||
);
|
||||
});
|
||||
|
||||
it("fails closed when the rule has no trigger key", async () => {
|
||||
mocks.tx.automationRule.findFirst.mockResolvedValue({ ...RULE, triggerKey: null });
|
||||
await expect(
|
||||
startAutomationExecutionForRule({ tenantId: "tenant-1", tenantSlug: "tenant-1", userId: "user-1", ruleId: "rule-1", triggerPayload: {} })
|
||||
).rejects.toThrow();
|
||||
});
|
||||
});
|
||||
+926
-102
File diff suppressed because it is too large.
Load diff
+198
@@ -0,0 +1,198 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
t: vi.fn((key: string) => `en:${key}`),
|
||||
tx: {
|
||||
automationTemplate: { findMany: vi.fn(), findFirst: vi.fn() },
|
||||
automationRule: { findMany: vi.fn(), findFirst: vi.fn(), create: vi.fn() },
|
||||
automationExecution: { findFirst: vi.fn(), updateMany: vi.fn() },
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("~/locale/i18next.server", () => ({
|
||||
getTranslations: async () => ({ t: mocks.t, translations: {}, locale: "en" }),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/loaders.middleware", () => ({
|
||||
requireAuth: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/services/.server/urlService", () => ({
|
||||
getTenantIdFromUrl: async () => "tenant-1",
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/session.server", () => ({
|
||||
getUserInfo: async () => ({ userId: "user-1" }),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/connector/tenantConnector.server", () => ({
|
||||
tenantHasModule: async () => true,
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/db/permissions/userRoles.db.server", () => ({
|
||||
getPermissionsByUser: async () => ["automation.read", "automation.manage"],
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/db/.server/tenantRls.server", () => ({
|
||||
withTenantRLS: async (_tenantId: string, callback: (tx: typeof mocks.tx) => Promise<unknown>) => callback(mocks.tx),
|
||||
}));
|
||||
|
||||
import { automationTemplateCatalog, automationTemplateFlowData } from "./automation.registry";
|
||||
import {
|
||||
createAutomationRuleFromTemplate,
|
||||
handleAutomationExecutionDetailAction,
|
||||
loadAutomationExecutionDetailVM,
|
||||
loadAutomationTemplateCatalogVM,
|
||||
} from "./automation.server";
|
||||
|
||||
const platformTemplate = automationTemplateCatalog[0];
|
||||
const platformFlowData = automationTemplateFlowData(platformTemplate);
|
||||
|
||||
describe("automation platform template i18n", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.tx.automationRule.findMany.mockResolvedValue([]);
|
||||
mocks.tx.automationRule.create.mockResolvedValue({ id: "rule-1" });
|
||||
mocks.tx.automationExecution.updateMany.mockResolvedValue({ count: 1 });
|
||||
});
|
||||
|
||||
it("localizes platform cards while preserving tenant-authored copy", async () => {
|
||||
mocks.tx.automationTemplate.findMany.mockResolvedValue([
|
||||
{
|
||||
id: "platform-template",
|
||||
tenantId: null,
|
||||
name: platformTemplate.defaultName,
|
||||
description: platformTemplate.defaultDescription,
|
||||
category: platformTemplate.category,
|
||||
createdFromRuleId: null,
|
||||
flowData: platformFlowData,
|
||||
},
|
||||
{
|
||||
id: "tenant-template",
|
||||
tenantId: "tenant-1",
|
||||
name: "Customer-authored template.key",
|
||||
description: "Customer-authored description.key",
|
||||
category: "operations",
|
||||
createdFromRuleId: null,
|
||||
flowData: platformFlowData,
|
||||
},
|
||||
]);
|
||||
|
||||
const vm = await loadAutomationTemplateCatalogVM({ request: new Request("http://app.localhost/templates"), params: { tenant: "demo" } });
|
||||
|
||||
expect(vm.templates[0]).toMatchObject({
|
||||
name: `en:${platformTemplate.nameKey}`,
|
||||
description: `en:${platformTemplate.descriptionKey}`,
|
||||
isTenantTemplate: false,
|
||||
});
|
||||
expect(vm.templates[1]).toMatchObject({
|
||||
name: "Customer-authored template.key",
|
||||
description: "Customer-authored description.key",
|
||||
isTenantTemplate: true,
|
||||
});
|
||||
expect(mocks.t).not.toHaveBeenCalledWith("Customer-authored template.key");
|
||||
expect(mocks.t).not.toHaveBeenCalledWith("Customer-authored description.key");
|
||||
});
|
||||
|
||||
it("localizes platform rule names, descriptions and executable config", async () => {
|
||||
mocks.tx.automationTemplate.findFirst.mockResolvedValue({
|
||||
tenantId: null,
|
||||
name: platformTemplate.defaultName,
|
||||
description: platformTemplate.defaultDescription,
|
||||
flowData: platformFlowData,
|
||||
});
|
||||
|
||||
await createAutomationRuleFromTemplate({
|
||||
request: new Request("http://app.localhost/templates"),
|
||||
params: { tenant: "demo" },
|
||||
templateId: "platform-template",
|
||||
});
|
||||
|
||||
const createInput = mocks.tx.automationRule.create.mock.calls[0]?.[0];
|
||||
expect(createInput.data).toMatchObject({
|
||||
name: `en:${platformTemplate.nameKey}`,
|
||||
description: `en:${platformTemplate.descriptionKey}`,
|
||||
});
|
||||
expect(createInput.data.steps.create.find((step: { stepKey: string }) => step.stepKey === "create-task")?.config).toMatchObject({
|
||||
titel: "en:automation.templates.leadQualifiedFollowUp.taskTitle",
|
||||
zustaendig: "besitzerDerAutomation",
|
||||
});
|
||||
expect(createInput.data.steps.create.find((step: { stepKey: string }) => step.stepKey === "notify-office")?.config).toMatchObject({
|
||||
betreff: "en:automation.templates.leadQualifiedFollowUp.notificationSubject",
|
||||
nachricht: "en:automation.templates.leadQualifiedFollowUp.notificationMessage",
|
||||
});
|
||||
});
|
||||
|
||||
it("copies tenant-authored templates byte-for-byte instead of translating key-like text", async () => {
|
||||
mocks.tx.automationTemplate.findFirst.mockResolvedValue({
|
||||
tenantId: "tenant-1",
|
||||
name: "Customer-authored template.key",
|
||||
description: "Customer-authored description.key",
|
||||
flowData: platformFlowData,
|
||||
});
|
||||
|
||||
await createAutomationRuleFromTemplate({
|
||||
request: new Request("http://app.localhost/templates"),
|
||||
params: { tenant: "demo" },
|
||||
templateId: "tenant-template",
|
||||
});
|
||||
|
||||
expect(mocks.tx.automationRule.create.mock.calls[0]?.[0].data).toMatchObject({
|
||||
name: "Customer-authored template.key",
|
||||
description: "Customer-authored description.key",
|
||||
});
|
||||
expect(mocks.t).not.toHaveBeenCalledWith("Customer-authored template.key");
|
||||
expect(mocks.t).not.toHaveBeenCalledWith("Customer-authored description.key");
|
||||
});
|
||||
|
||||
it("returns the reverse confirmation phrase in the request locale", async () => {
|
||||
mocks.tx.automationExecution.findFirst.mockResolvedValue({
|
||||
id: "execution-1",
|
||||
status: "success",
|
||||
dryRun: false,
|
||||
triggerKey: "forms.submitted",
|
||||
summaryText: null,
|
||||
errorText: null,
|
||||
createdAt: new Date("2026-07-02T09:00:00.000Z"),
|
||||
startedAt: new Date("2026-07-02T09:00:00.000Z"),
|
||||
endedAt: new Date("2026-07-02T09:01:00.000Z"),
|
||||
durationMs: 60_000,
|
||||
reverseWindowExpiresAt: new Date("2099-07-03T09:00:00.000Z"),
|
||||
rule: { id: "rule-1", name: "Follow-up" },
|
||||
stepExecutions: [],
|
||||
});
|
||||
|
||||
const vm = await loadAutomationExecutionDetailVM({
|
||||
request: new Request("http://app.localhost/demo/automations/rule-1/executions/execution-1"),
|
||||
params: { tenant: "demo", id: "rule-1", executionId: "execution-1" },
|
||||
});
|
||||
|
||||
expect(vm.reversePlan.confirmationPhrase).toBe("en:automation.detail.reverse.confirmationPhrase");
|
||||
});
|
||||
|
||||
it("validates reverse confirmation against the same request-localized phrase", async () => {
|
||||
const params = { tenant: "demo", id: "rule-1", executionId: "execution-1" };
|
||||
const submit = (confirmationPhrase: string) =>
|
||||
handleAutomationExecutionDetailAction({
|
||||
request: new Request("http://app.localhost/demo/automations/rule-1/executions/execution-1", {
|
||||
method: "POST",
|
||||
body: new URLSearchParams({ intent: "reverse", confirmationPhrase }),
|
||||
}),
|
||||
params,
|
||||
});
|
||||
|
||||
await expect(submit("AUTOMATION RUECKGAENGIG")).resolves.toEqual({
|
||||
ok: false,
|
||||
errorKey: "automation.detail.reverse.confirmationRequired",
|
||||
});
|
||||
|
||||
mocks.tx.automationExecution.findFirst.mockResolvedValue({
|
||||
reverseWindowExpiresAt: new Date("2099-07-03T09:00:00.000Z"),
|
||||
stepExecutions: [],
|
||||
});
|
||||
await expect(submit("en:automation.detail.reverse.confirmationPhrase")).resolves.toEqual({
|
||||
ok: false,
|
||||
errorKey: "automation.detail.reverse.nothingReversible",
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user