Update hivegrid-cloud reference to latest main
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e98d38e716
commit
7b21524c86
3781 files changed
+373484
-225607
No files matched your search
+82
@@ -0,0 +1,82 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { automationActionCatalog, automationTriggerCatalog } from "./automation.registry";
|
||||
import {
|
||||
applyAutomationEditorOperation,
|
||||
buildAutomationDryRunPreview,
|
||||
buildAutomationEditorFlow,
|
||||
buildAutomationReversePlan,
|
||||
canConfirmAutomationDryRun,
|
||||
serializeAutomationEditorFlow,
|
||||
validateAutomationEditorFlow,
|
||||
} from "./automation.editor";
|
||||
|
||||
const catalog = [...automationTriggerCatalog, ...automationActionCatalog];
|
||||
|
||||
describe("automation editor contract", () => {
|
||||
it("validates missing triggers, missing parents, and loops with Klartext keys", () => {
|
||||
const missingTrigger = buildAutomationEditorFlow({
|
||||
flowData: {},
|
||||
steps: [{ stepKey: "task", stepKind: "action", nodeType: "task.create", parentStepIds: [] }],
|
||||
});
|
||||
expect(validateAutomationEditorFlow(missingTrigger).issues.map((issue) => issue.code)).toContain("missing_trigger");
|
||||
expect(validateAutomationEditorFlow(missingTrigger).issues.map((issue) => issue.code)).toContain("unconnected_step");
|
||||
|
||||
const loop = buildAutomationEditorFlow({
|
||||
flowData: {},
|
||||
steps: [
|
||||
{ stepKey: "trigger", stepKind: "trigger", nodeType: "lead.qualified", parentStepIds: ["task"] },
|
||||
{ stepKey: "task", stepKind: "action", nodeType: "task.create", parentStepIds: ["trigger"] },
|
||||
],
|
||||
});
|
||||
expect(validateAutomationEditorFlow(loop).issues).toContainEqual(expect.objectContaining({ code: "loop_detected", messageKey: "automation.editor.validation.loopDetected" }));
|
||||
});
|
||||
|
||||
it("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);
|
||||
|
||||
expect(validateAutomationEditorFlow(connected).canActivate).toBe(true);
|
||||
expect(serializeAutomationEditorFlow(connected).steps).toHaveLength(2);
|
||||
|
||||
const undone = applyAutomationEditorOperation(connected, { type: "undo" }, catalog);
|
||||
expect(undone.history.future).toHaveLength(1);
|
||||
|
||||
const redone = applyAutomationEditorOperation(undone, { type: "redo" }, catalog);
|
||||
expect(redone.steps).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("builds dry-run previews with confirmation threshold", () => {
|
||||
const flow = buildAutomationEditorFlow({
|
||||
flowData: {},
|
||||
steps: [
|
||||
{ stepKey: "trigger", stepKind: "trigger", nodeType: "lead.qualified", parentStepIds: [] },
|
||||
{ stepKey: "task", stepKind: "action", nodeType: "task.create", parentStepIds: ["trigger"] },
|
||||
],
|
||||
});
|
||||
const preview = buildAutomationDryRunPreview({ flow, matchedRecords: 101, examples: ["Lead A", "Lead B", "Lead C", "Lead D", "Lead E", "Lead F"] });
|
||||
|
||||
expect(preview.requiresConfirmation).toBe(true);
|
||||
expect(preview.examples).toHaveLength(5);
|
||||
expect(canConfirmAutomationDryRun({ matchedRecords: 101, confirmationPhrase: "falsch" })).toBe(false);
|
||||
expect(canConfirmAutomationDryRun({ matchedRecords: 101, confirmationPhrase: preview.confirmationPhrase })).toBe(true);
|
||||
});
|
||||
|
||||
it("builds 24h reverse plans and marks deliveries as not reversible", () => {
|
||||
const plan = buildAutomationReversePlan({
|
||||
reverseWindowExpiresAt: "2026-07-02T10:00:00.000Z",
|
||||
now: new Date("2026-07-02T09:00:00.000Z"),
|
||||
steps: [
|
||||
{ stepKey: "task", nodeType: "task.create" },
|
||||
{ stepKey: "notify", nodeType: "notification.send" },
|
||||
],
|
||||
});
|
||||
|
||||
expect(plan.canReverse).toBe(true);
|
||||
expect(plan.items).toEqual([
|
||||
expect.objectContaining({ actionKey: "automation.editor.reverse.actions.deleteTask", reversible: true }),
|
||||
expect.objectContaining({ actionKey: "automation.editor.reverse.actions.deliveryNotReversible", reversible: false }),
|
||||
]);
|
||||
});
|
||||
});
|
||||
+408
@@ -0,0 +1,408 @@
|
||||
import {
|
||||
evaluateLoopGuard,
|
||||
getAutomationNode,
|
||||
type AutomationGraphStep,
|
||||
type AutomationNodeDefinition,
|
||||
type AutomationNodeKind,
|
||||
} from "./automation.registry";
|
||||
|
||||
export type AutomationEditorIssueCode = "missing_trigger" | "multiple_triggers" | "unknown_node" | "unconnected_step" | "missing_parent" | "loop_detected" | "empty_flow";
|
||||
|
||||
export interface AutomationEditorStep {
|
||||
readonly stepKey: string;
|
||||
readonly kind: AutomationNodeKind;
|
||||
readonly nodeType: string;
|
||||
readonly parentStepIds: readonly string[];
|
||||
readonly config: Record<string, unknown>;
|
||||
readonly position: { readonly x: number; readonly y: number };
|
||||
readonly sortOrder: number;
|
||||
readonly summaryKey: string;
|
||||
}
|
||||
|
||||
export interface AutomationEditorSnapshot {
|
||||
readonly triggerKey: string;
|
||||
readonly steps: readonly AutomationEditorStep[];
|
||||
}
|
||||
|
||||
export interface AutomationEditorFlow extends AutomationEditorSnapshot {
|
||||
readonly history: {
|
||||
readonly past: readonly AutomationEditorSnapshot[];
|
||||
readonly future: readonly AutomationEditorSnapshot[];
|
||||
};
|
||||
}
|
||||
|
||||
export interface AutomationEditorValidationIssue {
|
||||
readonly code: AutomationEditorIssueCode;
|
||||
readonly severity: "error" | "warning";
|
||||
readonly stepKey: string | null;
|
||||
readonly messageKey: string;
|
||||
readonly detail: string | null;
|
||||
}
|
||||
|
||||
export interface AutomationEditorValidationResult {
|
||||
readonly issues: readonly AutomationEditorValidationIssue[];
|
||||
readonly canActivate: boolean;
|
||||
readonly dependencyEdges: readonly { readonly from: string; readonly to: string }[];
|
||||
}
|
||||
|
||||
export interface AutomationEditorStepInput {
|
||||
readonly stepKey?: unknown;
|
||||
readonly kind?: unknown;
|
||||
readonly stepKind?: unknown;
|
||||
readonly nodeType?: unknown;
|
||||
readonly parentStepIds?: unknown;
|
||||
readonly config?: unknown;
|
||||
readonly position?: unknown;
|
||||
readonly sortOrder?: unknown;
|
||||
readonly summaryKey?: unknown;
|
||||
readonly summaryText?: unknown;
|
||||
}
|
||||
|
||||
export type AutomationEditorOperation =
|
||||
| { readonly type: "add-node"; readonly nodeType: string; readonly parentStepKey?: string | null }
|
||||
| { readonly type: "delete-node"; readonly stepKey: string }
|
||||
| { readonly type: "duplicate-node"; readonly stepKey: string }
|
||||
| { readonly type: "connect"; readonly fromStepKey: string; readonly toStepKey: string }
|
||||
| { readonly type: "disconnect"; readonly fromStepKey: string; readonly toStepKey: string }
|
||||
| { readonly type: "auto-layout" }
|
||||
| { readonly type: "undo" }
|
||||
| { readonly type: "redo" };
|
||||
|
||||
export interface AutomationDryRunPreview {
|
||||
readonly requiresConfirmation: boolean;
|
||||
readonly confirmationPhrase: string;
|
||||
readonly matchedRecords: number;
|
||||
readonly examples: readonly string[];
|
||||
readonly steps: readonly {
|
||||
readonly stepKey: string;
|
||||
readonly nodeType: string;
|
||||
readonly summaryKey: string;
|
||||
readonly effectKey: string;
|
||||
}[];
|
||||
readonly warnings: readonly string[];
|
||||
}
|
||||
|
||||
export interface AutomationReversePlan {
|
||||
readonly canReverse: boolean;
|
||||
readonly confirmationPhrase: string;
|
||||
readonly items: readonly {
|
||||
readonly stepKey: string;
|
||||
readonly nodeType: string;
|
||||
readonly actionKey: string;
|
||||
readonly reversible: boolean;
|
||||
}[];
|
||||
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;
|
||||
|
||||
export function buildAutomationEditorFlow(input: { readonly flowData: unknown; readonly steps: readonly AutomationEditorStepInput[] }): AutomationEditorFlow {
|
||||
const rawFlow = objectOrEmpty(input.flowData);
|
||||
const rawSteps = input.steps.length > 0 ? input.steps : Array.isArray(rawFlow.steps) ? (rawFlow.steps as AutomationEditorStepInput[]) : [];
|
||||
const steps = rawSteps
|
||||
.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 history = normalizeHistory(rawFlow.history);
|
||||
return { triggerKey, steps, history };
|
||||
}
|
||||
|
||||
export function serializeAutomationEditorFlow(flow: AutomationEditorFlow): Record<string, unknown> {
|
||||
return {
|
||||
triggerKey: flow.steps.find((step) => step.kind === "trigger")?.nodeType ?? flow.triggerKey,
|
||||
steps: flow.steps.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,
|
||||
})),
|
||||
history: flow.history,
|
||||
};
|
||||
}
|
||||
|
||||
export function validateAutomationEditorFlow(flow: AutomationEditorFlow): AutomationEditorValidationResult {
|
||||
const issues: AutomationEditorValidationIssue[] = [];
|
||||
if (flow.steps.length === 0) {
|
||||
issues.push(issue("empty_flow", null, "automation.editor.validation.emptyFlow"));
|
||||
}
|
||||
const triggerSteps = flow.steps.filter((step) => step.kind === "trigger");
|
||||
if (triggerSteps.length === 0) {
|
||||
issues.push(issue("missing_trigger", null, "automation.editor.validation.missingTrigger"));
|
||||
}
|
||||
if (triggerSteps.length > 1) {
|
||||
issues.push(issue("multiple_triggers", null, "automation.editor.validation.multipleTriggers", triggerSteps.map((step) => step.stepKey).join(", ")));
|
||||
}
|
||||
|
||||
const stepKeys = new Set(flow.steps.map((step) => step.stepKey));
|
||||
for (const step of flow.steps) {
|
||||
if (!getAutomationNode(step.nodeType)) {
|
||||
issues.push(issue("unknown_node", step.stepKey, "automation.editor.validation.unknownNode", step.nodeType));
|
||||
}
|
||||
for (const parentStepId of step.parentStepIds) {
|
||||
if (!stepKeys.has(parentStepId)) {
|
||||
issues.push(issue("missing_parent", step.stepKey, "automation.editor.validation.missingParent", parentStepId));
|
||||
}
|
||||
}
|
||||
if (step.kind !== "trigger" && step.parentStepIds.length === 0) {
|
||||
issues.push(issue("unconnected_step", step.stepKey, "automation.editor.validation.unconnectedStep"));
|
||||
}
|
||||
}
|
||||
|
||||
const loop = evaluateLoopGuard(toGraphSteps(flow.steps));
|
||||
if (!loop.ok) {
|
||||
issues.push(issue("loop_detected", null, "automation.editor.validation.loopDetected", loop.cycleStepKeys.join(" -> ")));
|
||||
}
|
||||
|
||||
const reachable = reachableStepKeys(flow.steps, triggerSteps[0]?.stepKey ?? null);
|
||||
for (const step of flow.steps) {
|
||||
if (triggerSteps.length > 0 && !reachable.has(step.stepKey)) {
|
||||
issues.push(issue("unconnected_step", step.stepKey, "automation.editor.validation.unreachableStep"));
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
issues,
|
||||
canActivate: !issues.some((item) => item.severity === "error"),
|
||||
dependencyEdges: loop.dependencyEdges,
|
||||
};
|
||||
}
|
||||
|
||||
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);
|
||||
|
||||
const before = snapshot(flow);
|
||||
let nextSteps = [...flow.steps];
|
||||
if (operation.type === "add-node") {
|
||||
const node = catalog.find((item) => item.key === operation.nodeType) ?? getAutomationNode(operation.nodeType);
|
||||
if (!node) return flow;
|
||||
const stepKey = uniqueStepKey(nextSteps, operation.nodeType);
|
||||
const parentStepIds = node.kind === "trigger" ? [] : [operation.parentStepKey || nextSteps.at(-1)?.stepKey || ""].filter(Boolean);
|
||||
nextSteps.push({
|
||||
stepKey,
|
||||
kind: node.kind,
|
||||
nodeType: node.key,
|
||||
parentStepIds,
|
||||
config: node.defaultConfig,
|
||||
position: { x: 160 * (nextSteps.length % 4), y: 120 * Math.floor(nextSteps.length / 4) },
|
||||
sortOrder: nextSteps.length,
|
||||
summaryKey: node.titleKey,
|
||||
});
|
||||
}
|
||||
if (operation.type === "delete-node") {
|
||||
nextSteps = nextSteps
|
||||
.filter((step) => step.stepKey !== operation.stepKey)
|
||||
.map((step, index) => ({ ...step, parentStepIds: step.parentStepIds.filter((parent) => parent !== operation.stepKey), 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 } });
|
||||
}
|
||||
if (operation.type === "connect") {
|
||||
nextSteps = nextSteps.map((step) =>
|
||||
step.stepKey === operation.toStepKey && step.stepKey !== operation.fromStepKey
|
||||
? { ...step, parentStepIds: uniqueStrings([...step.parentStepIds, operation.fromStepKey]) }
|
||||
: step
|
||||
);
|
||||
}
|
||||
if (operation.type === "disconnect") {
|
||||
nextSteps = nextSteps.map((step) => (step.stepKey === operation.toStepKey ? { ...step, parentStepIds: step.parentStepIds.filter((parent) => parent !== operation.fromStepKey) } : 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 }));
|
||||
}
|
||||
|
||||
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 {
|
||||
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,
|
||||
matchedRecords,
|
||||
examples: (input.examples ?? []).slice(0, 5),
|
||||
steps: input.flow.steps.map((step) => ({
|
||||
stepKey: step.stepKey,
|
||||
nodeType: step.nodeType,
|
||||
summaryKey: step.summaryKey,
|
||||
effectKey: step.kind === "trigger" ? "automation.editor.dryRun.effects.trigger" : "automation.editor.dryRun.effects.noSideEffect",
|
||||
})),
|
||||
warnings: validation.issues.map((item) => item.messageKey),
|
||||
};
|
||||
}
|
||||
|
||||
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 buildAutomationReversePlan(input: {
|
||||
readonly reverseWindowExpiresAt: string | Date | null;
|
||||
readonly steps: readonly { readonly stepKey: string; readonly nodeType: 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 {
|
||||
canReverse,
|
||||
confirmationPhrase: REVERSE_CONFIRMATION_PHRASE,
|
||||
items,
|
||||
warnings: items.filter((item) => !item.reversible).map((item) => item.actionKey),
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeStep(raw: AutomationEditorStepInput, index: number): AutomationEditorStep | null {
|
||||
const object = objectOrEmpty(raw);
|
||||
const nodeType = typeof object.nodeType === "string" ? object.nodeType : "";
|
||||
const node = getAutomationNode(nodeType);
|
||||
const kind = normalizeKind(object.kind ?? object.stepKind, node?.kind ?? "action");
|
||||
const stepKey = typeof object.stepKey === "string" && object.stepKey.trim() ? object.stepKey.trim() : uniqueFallbackStepKey(nodeType, index);
|
||||
return {
|
||||
stepKey,
|
||||
kind,
|
||||
nodeType,
|
||||
parentStepIds: Array.isArray(object.parentStepIds) ? object.parentStepIds.filter((item): item is string => typeof item === "string") : [],
|
||||
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",
|
||||
};
|
||||
}
|
||||
|
||||
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) : [],
|
||||
};
|
||||
}
|
||||
|
||||
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) : [];
|
||||
if (steps.length === 0) return null;
|
||||
return { triggerKey: typeof raw.triggerKey === "string" ? raw.triggerKey : steps.find((step) => step.kind === "trigger")?.nodeType ?? "", steps };
|
||||
}
|
||||
|
||||
function normalizeKind(value: unknown, fallback: AutomationNodeKind): AutomationNodeKind {
|
||||
return value === "trigger" || value === "condition" || value === "action" || value === "flow_control" ? value : fallback;
|
||||
}
|
||||
|
||||
function normalizePosition(value: unknown, index: number): AutomationEditorStep["position"] {
|
||||
const raw = objectOrEmpty(value);
|
||||
return {
|
||||
x: typeof raw.x === "number" ? raw.x : 220 * (index % 3),
|
||||
y: typeof raw.y === "number" ? raw.y : 140 * Math.floor(index / 3),
|
||||
};
|
||||
}
|
||||
|
||||
function withHistory(flow: AutomationEditorFlow, before: AutomationEditorSnapshot): AutomationEditorFlow {
|
||||
return {
|
||||
...flow,
|
||||
history: {
|
||||
past: [...flow.history.past, before].slice(-MAX_HISTORY),
|
||||
future: [],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function undoFlow(flow: AutomationEditorFlow): AutomationEditorFlow {
|
||||
const previous = flow.history.past.at(-1);
|
||||
if (!previous) return flow;
|
||||
return {
|
||||
...previous,
|
||||
history: {
|
||||
past: flow.history.past.slice(0, -1),
|
||||
future: [snapshot(flow), ...flow.history.future].slice(0, MAX_HISTORY),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function redoFlow(flow: AutomationEditorFlow): AutomationEditorFlow {
|
||||
const next = flow.history.future[0];
|
||||
if (!next) return flow;
|
||||
return {
|
||||
...next,
|
||||
history: {
|
||||
past: [...flow.history.past, snapshot(flow)].slice(-MAX_HISTORY),
|
||||
future: flow.history.future.slice(1),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function snapshot(flow: AutomationEditorFlow): AutomationEditorSnapshot {
|
||||
return { triggerKey: flow.triggerKey, steps: flow.steps };
|
||||
}
|
||||
|
||||
function toGraphSteps(steps: readonly AutomationEditorStep[]): readonly AutomationGraphStep[] {
|
||||
return steps.map((step) => ({ stepKey: step.stepKey, nodeType: step.nodeType, parentStepIds: step.parentStepIds }));
|
||||
}
|
||||
|
||||
function reachableStepKeys(steps: readonly AutomationEditorStep[], triggerStepKey: string | null): Set<string> {
|
||||
const reachable = new Set<string>();
|
||||
if (!triggerStepKey) return reachable;
|
||||
reachable.add(triggerStepKey);
|
||||
let changed = true;
|
||||
while (changed) {
|
||||
changed = false;
|
||||
for (const step of steps) {
|
||||
if (!reachable.has(step.stepKey) && step.parentStepIds.some((parent) => reachable.has(parent))) {
|
||||
reachable.add(step.stepKey);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return reachable;
|
||||
}
|
||||
|
||||
function uniqueStepKey(steps: readonly AutomationEditorStep[], nodeType: string): string {
|
||||
const base = nodeType.replace(/[^a-zA-Z0-9]+/g, "-").replace(/^-|-$/g, "") || "step";
|
||||
const existing = new Set(steps.map((step) => step.stepKey));
|
||||
let candidate = base;
|
||||
let counter = 2;
|
||||
while (existing.has(candidate)) {
|
||||
candidate = `${base}-${counter}`;
|
||||
counter += 1;
|
||||
}
|
||||
return candidate;
|
||||
}
|
||||
|
||||
function uniqueFallbackStepKey(nodeType: string, index: number): string {
|
||||
const base = nodeType.replace(/[^a-zA-Z0-9]+/g, "-").replace(/^-|-$/g, "") || "step";
|
||||
return `${base}-${index + 1}`;
|
||||
}
|
||||
|
||||
function uniqueStrings(values: readonly string[]): readonly string[] {
|
||||
return [...new Set(values.filter(Boolean))];
|
||||
}
|
||||
|
||||
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 === "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 };
|
||||
return { actionKey: "automation.editor.reverse.actions.noop", reversible: false };
|
||||
}
|
||||
|
||||
function objectOrEmpty(value: unknown): Record<string, unknown> {
|
||||
return value && typeof value === "object" && !Array.isArray(value) ? (value as Record<string, unknown>) : {};
|
||||
}
|
||||
|
||||
function issue(code: AutomationEditorIssueCode, stepKey: string | null, messageKey: string, detail: string | null = null): AutomationEditorValidationIssue {
|
||||
return { code, severity: "error", stepKey, messageKey, detail };
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
AUTOMATION_MODULE_KEY,
|
||||
AUTOMATION_READ_PERMISSION,
|
||||
automationActionCatalog,
|
||||
automationTemplateCatalog,
|
||||
automationTriggerCatalog,
|
||||
buildAutomationIdempotencyKey,
|
||||
buildReverseWindowExpiresAt,
|
||||
evaluateLoopGuard,
|
||||
evaluateTriggerVolume,
|
||||
listAutomationNodes,
|
||||
planAutomationRetry,
|
||||
} from "./automation.registry";
|
||||
|
||||
describe("automation registry contract", () => {
|
||||
it("uses the R-P12a module and permission keys", () => {
|
||||
expect(AUTOMATION_MODULE_KEY).toBe("automation");
|
||||
expect(AUTOMATION_READ_PERMISSION).toBe("automation.read");
|
||||
});
|
||||
|
||||
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(automationActionCatalog.find((node) => node.key === "kwp.push_project")?.availability).toBe("extension_slot");
|
||||
expect(listAutomationNodes()).toHaveLength(automationTriggerCatalog.length + automationActionCatalog.length);
|
||||
});
|
||||
|
||||
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"]);
|
||||
for (const template of automationTemplateCatalog) {
|
||||
expect(template.steps[0]?.kind).toBe("trigger");
|
||||
expect(template.steps.map((step) => step.stepKey)).toContain("trigger");
|
||||
}
|
||||
});
|
||||
|
||||
it("detects dependency cycles for loop guard warnings", () => {
|
||||
expect(
|
||||
evaluateLoopGuard([
|
||||
{ stepKey: "a", nodeType: "trigger", parentStepIds: ["c"] },
|
||||
{ stepKey: "b", nodeType: "task.create", parentStepIds: ["a"] },
|
||||
{ stepKey: "c", nodeType: "notification.send", parentStepIds: ["b"] },
|
||||
])
|
||||
).toMatchObject({ ok: false, cycleStepKeys: ["a", "b", "c", "a"] });
|
||||
|
||||
expect(
|
||||
evaluateLoopGuard([
|
||||
{ stepKey: "trigger", nodeType: "lead.qualified", parentStepIds: [] },
|
||||
{ stepKey: "task", nodeType: "task.create", parentStepIds: ["trigger"] },
|
||||
]).ok
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
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(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 });
|
||||
|
||||
expect(result.action).toBe("pause");
|
||||
expect(result.summaryText).toContain("2000 automation triggers in 5 minutes");
|
||||
expect(result.summaryText).toContain("typical volume is 5-10 per day");
|
||||
});
|
||||
|
||||
it("plans bounded auto retries for resumable executions", () => {
|
||||
const retry = planAutomationRetry({ attempt: 1, baseDelayMs: 1_000, now: new Date("2026-07-01T10:00:00.000Z") });
|
||||
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" });
|
||||
});
|
||||
});
|
||||
+274
@@ -0,0 +1,274 @@
|
||||
export const AUTOMATION_MODULE_KEY = "automation";
|
||||
export const AUTOMATION_READ_PERMISSION = "automation.read";
|
||||
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 AutomationNodeKind = "trigger" | "condition" | "action" | "flow_control";
|
||||
export type AutomationNodeAvailability = "active" | "extension_slot";
|
||||
|
||||
export interface AutomationNodeDefinition {
|
||||
readonly key: string;
|
||||
readonly kind: AutomationNodeKind;
|
||||
readonly group: AutomationNodeGroup;
|
||||
readonly titleKey: string;
|
||||
readonly descriptionKey: string;
|
||||
readonly requiredAnyPermission: readonly string[];
|
||||
readonly availability: AutomationNodeAvailability;
|
||||
readonly defaultConfig: Record<string, string | number | boolean>;
|
||||
}
|
||||
|
||||
export interface AutomationTemplateDefinition {
|
||||
readonly key: string;
|
||||
readonly nameKey: string;
|
||||
readonly descriptionKey: string;
|
||||
readonly category: "crm" | "sales" | "projects" | "operations";
|
||||
readonly triggerKey: string;
|
||||
readonly steps: readonly {
|
||||
readonly stepKey: string;
|
||||
readonly kind: AutomationNodeKind;
|
||||
readonly nodeType: string;
|
||||
readonly parentStepIds: readonly string[];
|
||||
readonly summaryKey: string;
|
||||
}[];
|
||||
}
|
||||
|
||||
export interface AutomationGraphStep {
|
||||
readonly stepKey: string;
|
||||
readonly nodeType: string;
|
||||
readonly parentStepIds: readonly 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;
|
||||
}
|
||||
|
||||
export const automationTriggerCatalog = Object.freeze([
|
||||
trigger("crm.kontakt_created", "crm", ["crm.read_all", "crm.write"]),
|
||||
trigger("crm.kontakt_updated", "crm", ["crm.read_all", "crm.write"]),
|
||||
trigger("lead.captured", "lead", ["leads.read_all", "leads.write"]),
|
||||
trigger("lead.qualified", "lead", ["leads.read_all", "leads.write"]),
|
||||
trigger("sales.project_won", "sales", ["projects.read_all", "deals.read_aggregates"]),
|
||||
trigger("sales.stage_changed", "sales", ["projects.read_all", "projects.change_stage"]),
|
||||
trigger("projects.project_created", "projects", ["projects.read_all", "projects.write"]),
|
||||
trigger("projects.deadline_soon", "projects", ["projects.read_all", "projects.read_own_pl"]),
|
||||
trigger("email.inbound_received", "email", ["email.domain.view", "emailMarketing.view"]),
|
||||
trigger("email.campaign_bounced", "email", ["emailMarketing.view"]),
|
||||
trigger("forms.submitted", "forms", ["forms.basic", "forms.builder"]),
|
||||
trigger("booking.appointment_booked", "booking", ["bookings.read_all", "bookings.read_own"]),
|
||||
trigger("booking.appointment_cancelled", "booking", ["bookings.read_all", "bookings.read_own"]),
|
||||
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]),
|
||||
] as const satisfies readonly AutomationNodeDefinition[]);
|
||||
|
||||
export const automationActionCatalog = Object.freeze([
|
||||
action("crm.update_kontakt", "crm", ["crm.write"]),
|
||||
action("crm.create_note", "crm", ["crm.write"]),
|
||||
action("notification.send", "notification", [AUTOMATION_RUN_PERMISSION]),
|
||||
action("http.request", "http", [AUTOMATION_RUN_PERMISSION]),
|
||||
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]),
|
||||
extension("kwp.push_project", "kwp", ["integrations.manual_sync", AUTOMATION_MANAGE_PERMISSION]),
|
||||
] as const satisfies readonly AutomationNodeDefinition[]);
|
||||
|
||||
export const automationTemplateCatalog = Object.freeze([
|
||||
{
|
||||
key: "lead-qualified-follow-up",
|
||||
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" },
|
||||
],
|
||||
},
|
||||
{
|
||||
key: "project-deadline-warning",
|
||||
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" },
|
||||
],
|
||||
},
|
||||
{
|
||||
key: "form-submission-create-task",
|
||||
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" },
|
||||
],
|
||||
},
|
||||
] as const satisfies readonly AutomationTemplateDefinition[]);
|
||||
|
||||
const nodeByKey = new Map([...automationTriggerCatalog, ...automationActionCatalog].map((node) => [node.key, node]));
|
||||
|
||||
export function listAutomationNodes(): readonly AutomationNodeDefinition[] {
|
||||
return [...automationTriggerCatalog, ...automationActionCatalog];
|
||||
}
|
||||
|
||||
export function getAutomationNode(key: string): AutomationNodeDefinition | undefined {
|
||||
return nodeByKey.get(key);
|
||||
}
|
||||
|
||||
export function assertAutomationNodeExists(key: string): AutomationNodeDefinition {
|
||||
const node = getAutomationNode(key);
|
||||
if (!node) {
|
||||
throw new Error(`Unknown automation node: ${key}`);
|
||||
}
|
||||
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");
|
||||
}
|
||||
|
||||
function action(key: string, group: AutomationNodeGroup, requiredAnyPermission: readonly string[]): AutomationNodeDefinition {
|
||||
return node("action", key, group, requiredAnyPermission, "active");
|
||||
}
|
||||
|
||||
function flow(key: string, group: AutomationNodeGroup, requiredAnyPermission: readonly string[]): AutomationNodeDefinition {
|
||||
return node("flow_control", key, group, requiredAnyPermission, "active");
|
||||
}
|
||||
|
||||
function extension(key: string, group: AutomationNodeGroup, requiredAnyPermission: readonly string[]): AutomationNodeDefinition {
|
||||
return node("action", 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,
|
||||
kind,
|
||||
group,
|
||||
titleKey: `automation.nodes.${i18nKey}.title`,
|
||||
descriptionKey: `automation.nodes.${i18nKey}.description`,
|
||||
requiredAnyPermission,
|
||||
availability,
|
||||
defaultConfig: {},
|
||||
};
|
||||
}
|
||||
+863
@@ -0,0 +1,863 @@
|
||||
import { encryptTenantField } from "@hivegrid/db/crypto/tenant-envelope.server";
|
||||
import type { Prisma } from "@hivegrid/db/prisma-browser";
|
||||
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
|
||||
import type { Params } from "react-router";
|
||||
import { appPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { tenantHasModule } from "~/utils/connector/tenantConnector.server";
|
||||
import { withTenantRLS } from "~/utils/db/.server/tenantRls.server";
|
||||
import { getPermissionsByUser } from "~/utils/db/permissions/userRoles.db.server";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
import { getUserInfo } from "~/utils/session.server";
|
||||
import {
|
||||
applyAutomationEditorOperation,
|
||||
buildAutomationReversePlan,
|
||||
buildAutomationDryRunPreview,
|
||||
buildAutomationEditorFlow,
|
||||
canConfirmAutomationDryRun,
|
||||
serializeAutomationEditorFlow,
|
||||
validateAutomationEditorFlow,
|
||||
type AutomationDryRunPreview,
|
||||
type AutomationEditorFlow,
|
||||
type AutomationEditorOperation,
|
||||
type AutomationEditorValidationResult,
|
||||
type AutomationReversePlan,
|
||||
} from "./automation.editor";
|
||||
import {
|
||||
AUTOMATION_ADMIN_PERMISSION,
|
||||
AUTOMATION_MANAGE_PERMISSION,
|
||||
AUTOMATION_MODULE_KEY,
|
||||
AUTOMATION_READ_PERMISSION,
|
||||
AUTOMATION_RUN_PERMISSION,
|
||||
automationActionCatalog,
|
||||
automationTemplateCatalog,
|
||||
automationTriggerCatalog,
|
||||
buildAutomationIdempotencyKey,
|
||||
buildReverseWindowExpiresAt,
|
||||
evaluateLoopGuard,
|
||||
evaluateTriggerVolume,
|
||||
getAutomationNode,
|
||||
listAutomationNodes,
|
||||
type AutomationGraphStep,
|
||||
type AutomationNodeDefinition,
|
||||
} from "./automation.registry";
|
||||
|
||||
export interface AutomationContext {
|
||||
readonly tenantId: string;
|
||||
readonly tenantSlug: string;
|
||||
readonly userId: string;
|
||||
readonly permissions: readonly string[];
|
||||
readonly canManage: boolean;
|
||||
readonly canRun: boolean;
|
||||
readonly canAdmin: boolean;
|
||||
}
|
||||
|
||||
export interface AutomationListItemVM {
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
readonly description: string | null;
|
||||
readonly status: string;
|
||||
readonly enabled: boolean;
|
||||
readonly triggerKey: string | null;
|
||||
readonly runs30d: number;
|
||||
readonly lastExecutionAt: string | null;
|
||||
readonly executionsUrl: string;
|
||||
readonly editUrl: string;
|
||||
}
|
||||
|
||||
export interface AutomationListVM {
|
||||
readonly tenantSlug: string;
|
||||
readonly rules: readonly AutomationListItemVM[];
|
||||
readonly triggers: readonly AutomationNodeDefinition[];
|
||||
readonly actions: readonly AutomationNodeDefinition[];
|
||||
readonly templates: readonly { readonly id: string; readonly name: string; readonly category: string; readonly isPublished: boolean }[];
|
||||
readonly canManage: boolean;
|
||||
readonly canRun: boolean;
|
||||
}
|
||||
|
||||
export interface AutomationExecutionListVM {
|
||||
readonly rule: { readonly id: string; readonly name: string; readonly triggerKey: string | null };
|
||||
readonly executions: readonly {
|
||||
readonly id: string;
|
||||
readonly status: string;
|
||||
readonly dryRun: boolean;
|
||||
readonly triggerKey: string;
|
||||
readonly summaryText: string;
|
||||
readonly createdAt: string;
|
||||
readonly durationMs: number | null;
|
||||
readonly detailUrl: string;
|
||||
}[];
|
||||
}
|
||||
|
||||
export interface AutomationExecutionDetailVM {
|
||||
readonly rule: { readonly id: string; readonly name: string };
|
||||
readonly execution: {
|
||||
readonly id: string;
|
||||
readonly status: string;
|
||||
readonly dryRun: boolean;
|
||||
readonly triggerKey: string;
|
||||
readonly summaryText: string;
|
||||
readonly errorText: string | null;
|
||||
readonly reverseWindowExpiresAt: string | null;
|
||||
readonly canReverse: boolean;
|
||||
};
|
||||
readonly steps: readonly {
|
||||
readonly id: string;
|
||||
readonly stepKey: string;
|
||||
readonly nodeType: string;
|
||||
readonly status: string;
|
||||
readonly summaryText: string;
|
||||
readonly durationMs: number | null;
|
||||
readonly errorText: string | null;
|
||||
}[];
|
||||
readonly reversePlan: AutomationReversePlan;
|
||||
}
|
||||
|
||||
export interface AutomationEditorVM {
|
||||
readonly rule: {
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
readonly description: string | null;
|
||||
readonly status: string;
|
||||
readonly enabled: boolean;
|
||||
readonly triggerKey: string | null;
|
||||
readonly executionsUrl: string;
|
||||
};
|
||||
readonly flow: AutomationEditorFlow;
|
||||
readonly validation: AutomationEditorValidationResult;
|
||||
readonly catalog: readonly AutomationNodeDefinition[];
|
||||
readonly canManage: boolean;
|
||||
readonly canRun: boolean;
|
||||
readonly templatesUrl: string;
|
||||
}
|
||||
|
||||
export interface AutomationTemplateCatalogVM {
|
||||
readonly templates: readonly {
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
readonly description: string | null;
|
||||
readonly category: string;
|
||||
readonly isTenantTemplate: boolean;
|
||||
readonly useCount: number;
|
||||
}[];
|
||||
readonly rules: readonly { readonly id: string; readonly name: string }[];
|
||||
readonly canManage: boolean;
|
||||
}
|
||||
|
||||
export type AutomationEditorActionData =
|
||||
| { readonly ok: true; readonly messageKey: string; readonly dryRunPreview?: AutomationDryRunPreview }
|
||||
| { readonly ok: false; readonly errorKey: string; readonly detail?: string | null; readonly dryRunPreview?: AutomationDryRunPreview };
|
||||
|
||||
function hasAnyPermission(permissions: readonly string[], requiredAnyPermission: readonly string[]): boolean {
|
||||
return requiredAnyPermission.some((permission) => permissions.includes(permission));
|
||||
}
|
||||
|
||||
function assertAutomationRead(permissions: readonly string[]): void {
|
||||
if (!permissions.includes(AUTOMATION_READ_PERMISSION) && !permissions.includes(AUTOMATION_ADMIN_PERMISSION)) {
|
||||
throw new CatalogError(foundationErrors.notFound, { permission: AUTOMATION_READ_PERMISSION });
|
||||
}
|
||||
}
|
||||
|
||||
export async function loadAutomationContext({ request, params }: { request: Request; params: Params }): Promise<AutomationContext> {
|
||||
await requireAuth({ request, params });
|
||||
const [tenantId, userInfo] = await Promise.all([getTenantIdFromUrl(params), getUserInfo(request)]);
|
||||
if (!tenantId || !userInfo.userId) {
|
||||
throw new CatalogError(foundationErrors.notFound);
|
||||
}
|
||||
const [hasModule, permissions] = await Promise.all([
|
||||
tenantHasModule({ tenantId, userId: userInfo.userId, moduleKey: AUTOMATION_MODULE_KEY }),
|
||||
getPermissionsByUser(userInfo.userId, tenantId),
|
||||
]);
|
||||
if (!hasModule) {
|
||||
throw new CatalogError(foundationErrors.notFound, { module: AUTOMATION_MODULE_KEY });
|
||||
}
|
||||
assertAutomationRead(permissions);
|
||||
return {
|
||||
tenantId,
|
||||
tenantSlug: params.tenant ?? tenantId,
|
||||
userId: userInfo.userId,
|
||||
permissions,
|
||||
canManage: hasAnyPermission(permissions, [AUTOMATION_MANAGE_PERMISSION, AUTOMATION_ADMIN_PERMISSION]),
|
||||
canRun: hasAnyPermission(permissions, [AUTOMATION_RUN_PERMISSION, AUTOMATION_ADMIN_PERMISSION]),
|
||||
canAdmin: permissions.includes(AUTOMATION_ADMIN_PERMISSION),
|
||||
};
|
||||
}
|
||||
|
||||
export async function ensureDefaultAutomationTemplates(ctx: Pick<AutomationContext, "tenantId">): Promise<void> {
|
||||
await withTenantRLS(ctx.tenantId, async (tx) => {
|
||||
for (const template of automationTemplateCatalog) {
|
||||
const flowData = toPrismaJson(templateToFlowData(template));
|
||||
const existing = await tx.automationTemplate.findFirst({
|
||||
where: { tenantId: null, name: template.nameKey, archivedAt: null },
|
||||
select: { id: true },
|
||||
});
|
||||
if (existing) {
|
||||
await tx.automationTemplate.update({
|
||||
where: { id: existing.id },
|
||||
data: { description: template.descriptionKey, category: template.category, flowData, isPublished: true, isDemoData: true },
|
||||
});
|
||||
} else {
|
||||
await tx.automationTemplate.create({
|
||||
data: { tenantId: null, name: template.nameKey, description: template.descriptionKey, category: template.category, flowData, isPublished: true, isDemoData: true },
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export async function loadAutomationListVM({ request, params }: { request: Request; params: Params }): Promise<AutomationListVM> {
|
||||
const ctx = await loadAutomationContext({ request, params });
|
||||
await ensureDefaultAutomationTemplates(ctx);
|
||||
const since30d = new Date();
|
||||
since30d.setDate(since30d.getDate() - 30);
|
||||
return withTenantRLS(ctx.tenantId, async (tx) => {
|
||||
const [rules, templates] = await Promise.all([
|
||||
tx.automationRule.findMany({
|
||||
where: { tenantId: ctx.tenantId, archivedAt: null },
|
||||
orderBy: { updatedAt: "desc" },
|
||||
take: 50,
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
description: true,
|
||||
status: true,
|
||||
enabled: true,
|
||||
triggerKey: true,
|
||||
executions: {
|
||||
where: { createdAt: { gte: since30d } },
|
||||
orderBy: { createdAt: "desc" },
|
||||
select: { createdAt: true },
|
||||
take: 30,
|
||||
},
|
||||
},
|
||||
}),
|
||||
tx.automationTemplate.findMany({
|
||||
where: { OR: [{ tenantId: null }, { tenantId: ctx.tenantId }], isPublished: true, archivedAt: null },
|
||||
orderBy: [{ tenantId: "asc" }, { category: "asc" }, { name: "asc" }],
|
||||
select: { id: true, name: true, category: true, isPublished: true },
|
||||
}),
|
||||
]);
|
||||
return {
|
||||
tenantSlug: ctx.tenantSlug,
|
||||
rules: rules.map((rule) => ({
|
||||
id: rule.id,
|
||||
name: rule.name,
|
||||
description: rule.description,
|
||||
status: rule.status,
|
||||
enabled: rule.enabled,
|
||||
triggerKey: rule.triggerKey,
|
||||
runs30d: rule.executions.length,
|
||||
lastExecutionAt: rule.executions[0]?.createdAt.toISOString() ?? null,
|
||||
executionsUrl: appPath({ tenantSlug: ctx.tenantSlug, path: `automations/${rule.id}/executions`, mode: "host-aware" }),
|
||||
editUrl: appPath({ tenantSlug: ctx.tenantSlug, path: `automations/${rule.id}/edit`, mode: "host-aware" }),
|
||||
})),
|
||||
triggers: filterNodesForPermissions(automationTriggerCatalog, ctx.permissions),
|
||||
actions: filterNodesForPermissions(automationActionCatalog, ctx.permissions),
|
||||
templates,
|
||||
canManage: ctx.canManage,
|
||||
canRun: ctx.canRun,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export async function loadAutomationExecutionsVM({ request, params }: { request: Request; params: Params & { id?: string } }): Promise<AutomationExecutionListVM> {
|
||||
const ctx = await loadAutomationContext({ request, params });
|
||||
const ruleId = params.id;
|
||||
if (!ruleId) throw new CatalogError(foundationErrors.notFound);
|
||||
return withTenantRLS(ctx.tenantId, async (tx) => {
|
||||
const rule = await tx.automationRule.findFirst({
|
||||
where: { id: ruleId, tenantId: ctx.tenantId, archivedAt: null },
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
triggerKey: true,
|
||||
executions: {
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: 50,
|
||||
select: { id: true, status: true, dryRun: true, triggerKey: true, summaryText: true, createdAt: true, durationMs: true },
|
||||
},
|
||||
},
|
||||
});
|
||||
if (!rule) throw new CatalogError(foundationErrors.notFound);
|
||||
return {
|
||||
rule: { id: rule.id, name: rule.name, triggerKey: rule.triggerKey },
|
||||
executions: rule.executions.map((execution) => ({
|
||||
id: execution.id,
|
||||
status: execution.status,
|
||||
dryRun: execution.dryRun,
|
||||
triggerKey: execution.triggerKey,
|
||||
summaryText: execution.summaryText,
|
||||
createdAt: execution.createdAt.toISOString(),
|
||||
durationMs: execution.durationMs,
|
||||
detailUrl: appPath({ tenantSlug: ctx.tenantSlug, path: `automations/${rule.id}/executions/${execution.id}`, mode: "host-aware" }),
|
||||
})),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export async function loadAutomationExecutionDetailVM({
|
||||
request,
|
||||
params,
|
||||
}: {
|
||||
request: Request;
|
||||
params: Params & { id?: string; executionId?: string };
|
||||
}): Promise<AutomationExecutionDetailVM> {
|
||||
const ctx = await loadAutomationContext({ request, params });
|
||||
const { id: ruleId, executionId } = params;
|
||||
if (!ruleId || !executionId) throw new CatalogError(foundationErrors.notFound);
|
||||
return withTenantRLS(ctx.tenantId, async (tx) => {
|
||||
const execution = await tx.automationExecution.findFirst({
|
||||
where: { id: executionId, ruleId, tenantId: ctx.tenantId },
|
||||
select: {
|
||||
id: true,
|
||||
status: true,
|
||||
dryRun: true,
|
||||
triggerKey: true,
|
||||
summaryText: true,
|
||||
errorText: true,
|
||||
reverseWindowExpiresAt: true,
|
||||
rule: { select: { id: true, name: true } },
|
||||
stepExecutions: {
|
||||
orderBy: { sortOrder: "asc" },
|
||||
select: { id: true, stepKey: true, nodeType: true, status: true, summaryText: true, durationMs: true, errorText: true },
|
||||
},
|
||||
},
|
||||
});
|
||||
if (!execution) throw new CatalogError(foundationErrors.notFound);
|
||||
const reverseWindowExpiresAt = execution.reverseWindowExpiresAt?.toISOString() ?? null;
|
||||
const steps = execution.stepExecutions;
|
||||
return {
|
||||
rule: execution.rule,
|
||||
execution: {
|
||||
id: execution.id,
|
||||
status: execution.status,
|
||||
dryRun: execution.dryRun,
|
||||
triggerKey: execution.triggerKey,
|
||||
summaryText: execution.summaryText,
|
||||
errorText: execution.errorText,
|
||||
reverseWindowExpiresAt,
|
||||
canReverse: !!execution.reverseWindowExpiresAt && execution.reverseWindowExpiresAt.getTime() > Date.now(),
|
||||
},
|
||||
steps,
|
||||
reversePlan: buildAutomationReversePlan({ reverseWindowExpiresAt, steps }),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export async function loadAutomationEditorVM({ request, params }: { request: Request; params: Params & { id?: string } }): Promise<AutomationEditorVM> {
|
||||
const ctx = await loadAutomationContext({ request, params });
|
||||
const ruleId = params.id;
|
||||
if (!ruleId) throw new CatalogError(foundationErrors.notFound);
|
||||
return withTenantRLS(ctx.tenantId, async (tx) => {
|
||||
const rule = await tx.automationRule.findFirst({
|
||||
where: { id: ruleId, tenantId: ctx.tenantId, archivedAt: null },
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
description: true,
|
||||
status: true,
|
||||
enabled: true,
|
||||
triggerKey: true,
|
||||
flowData: true,
|
||||
steps: {
|
||||
orderBy: { sortOrder: "asc" },
|
||||
select: { stepKey: true, stepKind: true, nodeType: true, parentStepIds: true, config: true, position: true, sortOrder: true, summaryText: true },
|
||||
},
|
||||
},
|
||||
});
|
||||
if (!rule) throw new CatalogError(foundationErrors.notFound);
|
||||
const flow = buildAutomationEditorFlow({
|
||||
flowData: rule.flowData,
|
||||
steps: rule.steps.map((step) => ({
|
||||
stepKey: step.stepKey,
|
||||
stepKind: step.stepKind,
|
||||
nodeType: step.nodeType,
|
||||
parentStepIds: step.parentStepIds,
|
||||
config: step.config,
|
||||
position: step.position,
|
||||
sortOrder: step.sortOrder,
|
||||
summaryText: step.summaryText,
|
||||
})),
|
||||
});
|
||||
return {
|
||||
rule: {
|
||||
id: rule.id,
|
||||
name: rule.name,
|
||||
description: rule.description,
|
||||
status: rule.status,
|
||||
enabled: rule.enabled,
|
||||
triggerKey: rule.triggerKey,
|
||||
executionsUrl: appPath({ tenantSlug: ctx.tenantSlug, path: `automations/${rule.id}/executions`, mode: "host-aware" }),
|
||||
},
|
||||
flow,
|
||||
validation: validateAutomationEditorFlow(flow),
|
||||
catalog: filterNodesForPermissions(listAutomationNodes(), ctx.permissions),
|
||||
canManage: ctx.canManage,
|
||||
canRun: ctx.canRun,
|
||||
templatesUrl: appPath({ tenantSlug: ctx.tenantSlug, path: "automations/templates", mode: "host-aware" }),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export async function loadAutomationTemplateCatalogVM({ request, params }: { request: Request; params: Params }): Promise<AutomationTemplateCatalogVM> {
|
||||
const ctx = await loadAutomationContext({ request, params });
|
||||
await ensureDefaultAutomationTemplates(ctx);
|
||||
return withTenantRLS(ctx.tenantId, async (tx) => {
|
||||
const [templates, rules] = await Promise.all([
|
||||
tx.automationTemplate.findMany({
|
||||
where: { OR: [{ tenantId: null }, { tenantId: ctx.tenantId }], isPublished: true, archivedAt: null },
|
||||
orderBy: [{ tenantId: "asc" }, { category: "asc" }, { name: "asc" }],
|
||||
select: { id: true, tenantId: true, name: true, description: true, category: true, createdFromRuleId: true },
|
||||
}),
|
||||
tx.automationRule.findMany({
|
||||
where: { tenantId: ctx.tenantId, archivedAt: null },
|
||||
orderBy: { updatedAt: "desc" },
|
||||
take: 50,
|
||||
select: { id: true, name: true },
|
||||
}),
|
||||
]);
|
||||
const useCounts = new Map<string, number>();
|
||||
for (const template of templates) {
|
||||
if (template.createdFromRuleId) useCounts.set(template.createdFromRuleId, (useCounts.get(template.createdFromRuleId) ?? 0) + 1);
|
||||
}
|
||||
return {
|
||||
templates: templates.map((template) => ({
|
||||
id: template.id,
|
||||
name: template.name,
|
||||
description: template.description,
|
||||
category: template.category,
|
||||
isTenantTemplate: template.tenantId === ctx.tenantId,
|
||||
useCount: template.createdFromRuleId ? useCounts.get(template.createdFromRuleId) ?? 0 : 0,
|
||||
})),
|
||||
rules,
|
||||
canManage: ctx.canManage,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export async function handleAutomationEditorAction({ request, params }: { request: Request; params: Params & { id?: string } }): Promise<AutomationEditorActionData> {
|
||||
const ctx = await loadAutomationContext({ request, params });
|
||||
if (!ctx.canManage) throw new CatalogError(foundationErrors.notFound, { permission: AUTOMATION_MANAGE_PERMISSION });
|
||||
const ruleId = params.id;
|
||||
if (!ruleId) throw new CatalogError(foundationErrors.notFound);
|
||||
const formData = await request.formData();
|
||||
const intent = String(formData.get("intent") ?? "");
|
||||
|
||||
if (intent === "dry-run") {
|
||||
const flow = await loadAutomationEditorFlowForAction(ctx.tenantId, ruleId);
|
||||
const matchedRecords = Number(formData.get("matchedRecords") ?? 0);
|
||||
const dryRunPreview = buildAutomationDryRunPreview({
|
||||
flow,
|
||||
matchedRecords: Number.isFinite(matchedRecords) ? matchedRecords : 0,
|
||||
examples: String(formData.get("examples") ?? "")
|
||||
.split("\n")
|
||||
.map((item) => item.trim())
|
||||
.filter(Boolean),
|
||||
});
|
||||
if (!canConfirmAutomationDryRun({ matchedRecords: dryRunPreview.matchedRecords, confirmationPhrase: formData.get("confirmationPhrase")?.toString() })) {
|
||||
return { ok: false, errorKey: "automation.editor.dryRun.confirmationRequired", dryRunPreview };
|
||||
}
|
||||
return { ok: true, messageKey: "automation.editor.dryRun.previewReady", dryRunPreview };
|
||||
}
|
||||
|
||||
if (intent === "activate") {
|
||||
const flow = await loadAutomationEditorFlowForAction(ctx.tenantId, ruleId);
|
||||
const validation = validateAutomationEditorFlow(flow);
|
||||
if (!validation.canActivate) {
|
||||
return { ok: false, errorKey: "automation.editor.actions.activateBlocked", detail: validation.issues[0]?.messageKey ?? null };
|
||||
}
|
||||
await withTenantRLS(ctx.tenantId, (tx) => tx.automationRule.update({ where: { id: ruleId }, data: { status: "active", enabled: true } }));
|
||||
return { ok: true, messageKey: "automation.editor.actions.activated" };
|
||||
}
|
||||
|
||||
if (intent === "pause") {
|
||||
await withTenantRLS(ctx.tenantId, (tx) => tx.automationRule.update({ where: { id: ruleId }, data: { status: "paused", enabled: false } }));
|
||||
return { ok: true, messageKey: "automation.editor.actions.paused" };
|
||||
}
|
||||
|
||||
if (intent === "create-template") {
|
||||
await createAutomationTemplateFromRule({
|
||||
request,
|
||||
params,
|
||||
ruleId,
|
||||
name: String(formData.get("templateName") ?? "").trim() || `automation.template.${ruleId}`,
|
||||
category: String(formData.get("category") ?? "operations"),
|
||||
publish: true,
|
||||
});
|
||||
return { ok: true, messageKey: "automation.editor.actions.templateCreated" };
|
||||
}
|
||||
|
||||
const currentFlow = await loadAutomationEditorFlowForAction(ctx.tenantId, ruleId);
|
||||
const nextFlow = intent === "save-json" ? parseFlowJson(formData.get("flowJson"), currentFlow) : applyAutomationEditorOperation(currentFlow, operationFromFormData(intent, formData), listAutomationNodes());
|
||||
const validation = validateAutomationEditorFlow(nextFlow);
|
||||
await persistAutomationEditorFlow(ctx.tenantId, ruleId, nextFlow);
|
||||
return { ok: true, messageKey: validation.canActivate ? "automation.editor.actions.saved" : "automation.editor.actions.savedWithWarnings" };
|
||||
}
|
||||
|
||||
export async function createAutomationRuleFromTemplate(input: {
|
||||
request: Request;
|
||||
params: Params;
|
||||
templateId: string;
|
||||
name?: string;
|
||||
}): Promise<{ id: string }> {
|
||||
const ctx = await loadAutomationContext({ request: input.request, params: input.params });
|
||||
if (!ctx.canManage) throw new CatalogError(foundationErrors.notFound, { permission: AUTOMATION_MANAGE_PERMISSION });
|
||||
return withTenantRLS(ctx.tenantId, async (tx) => {
|
||||
const template = await tx.automationTemplate.findFirst({
|
||||
where: { id: input.templateId, OR: [{ tenantId: null }, { tenantId: ctx.tenantId }], isPublished: true, archivedAt: null },
|
||||
select: { name: true, description: true, flowData: true },
|
||||
});
|
||||
if (!template) throw new CatalogError(foundationErrors.notFound);
|
||||
const flowData = normalizeFlowData(template.flowData);
|
||||
const guard = evaluateLoopGuard(flowData.steps);
|
||||
if (!guard.ok) {
|
||||
throw new Error(`Automation loop guard blocked template: ${guard.cycleStepKeys.join(" -> ")}`);
|
||||
}
|
||||
const rule = await tx.automationRule.create({
|
||||
data: {
|
||||
tenantId: ctx.tenantId,
|
||||
name: input.name?.trim() || template.name,
|
||||
description: template.description,
|
||||
status: "draft",
|
||||
enabled: false,
|
||||
createdVia: "template",
|
||||
triggerKey: flowData.triggerKey,
|
||||
flowData: toPrismaJson(template.flowData),
|
||||
createdByUserId: ctx.userId,
|
||||
steps: {
|
||||
create: flowData.steps.map((step, index) => ({
|
||||
tenantId: ctx.tenantId,
|
||||
stepKey: step.stepKey,
|
||||
stepKind: nodeKindToStepKind(step.kind),
|
||||
nodeType: step.nodeType,
|
||||
config: {},
|
||||
parentStepIds: [...step.parentStepIds],
|
||||
sortOrder: index,
|
||||
summaryText: step.summaryKey,
|
||||
isDemoData: true,
|
||||
})),
|
||||
},
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
return rule;
|
||||
});
|
||||
}
|
||||
|
||||
export async function createAutomationRuleFromTemplateForRoute(input: { request: Request; params: Params; templateId: string; name?: string }): Promise<{ id: string; editUrl: string }> {
|
||||
const rule = await createAutomationRuleFromTemplate(input);
|
||||
return {
|
||||
id: rule.id,
|
||||
editUrl: appPath({ tenantSlug: input.params.tenant ?? "", path: `automations/${rule.id}/edit`, mode: "host-aware" }),
|
||||
};
|
||||
}
|
||||
|
||||
export async function createAutomationTemplateFromRule(input: {
|
||||
request: Request;
|
||||
params: Params;
|
||||
ruleId: string;
|
||||
name: string;
|
||||
category: string;
|
||||
publish?: boolean;
|
||||
}): Promise<{ id: string }> {
|
||||
const ctx = await loadAutomationContext({ request: input.request, params: input.params });
|
||||
if (!ctx.canManage) throw new CatalogError(foundationErrors.notFound, { permission: AUTOMATION_MANAGE_PERMISSION });
|
||||
return withTenantRLS(ctx.tenantId, async (tx) => {
|
||||
const rule = await tx.automationRule.findFirst({
|
||||
where: { id: input.ruleId, tenantId: ctx.tenantId, archivedAt: null },
|
||||
select: {
|
||||
id: true,
|
||||
description: true,
|
||||
triggerKey: true,
|
||||
steps: {
|
||||
orderBy: { sortOrder: "asc" },
|
||||
select: { stepKey: true, stepKind: true, nodeType: true, parentStepIds: true, summaryText: true },
|
||||
},
|
||||
},
|
||||
});
|
||||
if (!rule) throw new CatalogError(foundationErrors.notFound);
|
||||
const flowData = {
|
||||
createdFromRuleId: rule.id,
|
||||
triggerKey: rule.triggerKey ?? "",
|
||||
steps: rule.steps.map((step) => ({
|
||||
stepKey: step.stepKey,
|
||||
kind: step.stepKind,
|
||||
nodeType: step.nodeType,
|
||||
parentStepIds: step.parentStepIds,
|
||||
summaryKey: step.summaryText,
|
||||
})),
|
||||
};
|
||||
return tx.automationTemplate.create({
|
||||
data: {
|
||||
tenantId: ctx.tenantId,
|
||||
name: input.name.trim(),
|
||||
description: rule.description,
|
||||
category: input.category,
|
||||
flowData: toPrismaJson(flowData),
|
||||
isPublished: input.publish === true,
|
||||
createdByUserId: ctx.userId,
|
||||
createdFromRuleId: rule.id,
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export async function startAutomationExecutionForRule(input: {
|
||||
tenantId: string;
|
||||
tenantSlug: string;
|
||||
userId: string | null;
|
||||
ruleId: string;
|
||||
triggerKey: string;
|
||||
triggerPayload: Record<string, unknown>;
|
||||
sourceEventId?: string | null;
|
||||
dryRun?: boolean;
|
||||
resumeFromStepId?: string | null;
|
||||
}): Promise<{ id: string; deduplicated: boolean; status: string }> {
|
||||
return withTenantRLS(input.tenantId, async (tx) => {
|
||||
const rule = await tx.automationRule.findFirst({
|
||||
where: { id: input.ruleId, tenantId: input.tenantId, archivedAt: null },
|
||||
select: {
|
||||
id: true,
|
||||
enabled: true,
|
||||
status: true,
|
||||
triggerKey: true,
|
||||
steps: { orderBy: { sortOrder: "asc" }, select: { id: true, stepKey: true, nodeType: true, stepKind: true, parentStepIds: true, sortOrder: true, summaryText: true } },
|
||||
},
|
||||
});
|
||||
if (!rule || !rule.enabled || rule.status !== "active") {
|
||||
throw new CatalogError(foundationErrors.notFound);
|
||||
}
|
||||
const idempotencyKey = buildAutomationIdempotencyKey({
|
||||
tenantId: input.tenantId,
|
||||
ruleId: rule.id,
|
||||
triggerKey: input.triggerKey,
|
||||
sourceEventId: input.sourceEventId,
|
||||
payloadHash: JSON.stringify(input.triggerPayload).slice(0, 128),
|
||||
});
|
||||
const existing = await tx.automationExecution.findFirst({
|
||||
where: { tenantId: input.tenantId, idempotencyKey },
|
||||
select: { id: true, status: true },
|
||||
});
|
||||
if (existing) {
|
||||
return { id: existing.id, status: existing.status, deduplicated: true };
|
||||
}
|
||||
|
||||
const meter = await recordTriggerVolume({ tenantId: input.tenantId, triggerKey: input.triggerKey });
|
||||
if (meter.action === "pause") {
|
||||
await tx.automationRule.update({ where: { id: rule.id }, data: { status: "paused", enabled: false } });
|
||||
}
|
||||
const guard = evaluateLoopGuard(
|
||||
rule.steps.map((step) => ({ stepKey: step.stepKey, nodeType: step.nodeType, parentStepIds: step.parentStepIds }))
|
||||
);
|
||||
if (!guard.ok) {
|
||||
await tx.automationRule.update({ where: { id: rule.id }, data: { status: "paused", enabled: false } });
|
||||
}
|
||||
|
||||
const execution = await tx.automationExecution.create({
|
||||
data: {
|
||||
tenantId: input.tenantId,
|
||||
ruleId: rule.id,
|
||||
triggerKey: input.triggerKey,
|
||||
triggerPayload: toPrismaJsonObject(input.triggerPayload),
|
||||
status: meter.action === "pause" || !guard.ok ? "paused" : "queued",
|
||||
dryRun: input.dryRun === true,
|
||||
idempotencyKey,
|
||||
reverseWindowExpiresAt: buildReverseWindowExpiresAt(),
|
||||
resumeFromStepId: input.resumeFromStepId ?? null,
|
||||
summaryText: !guard.ok ? "automation.execution.loopGuardPaused" : meter.summaryText,
|
||||
createdByUserId: input.userId,
|
||||
stepExecutions: {
|
||||
create: rule.steps.map((step) => ({
|
||||
tenantId: input.tenantId,
|
||||
ruleStepId: step.id,
|
||||
stepKey: step.stepKey,
|
||||
stepKind: step.stepKind,
|
||||
nodeType: step.nodeType,
|
||||
status: "queued",
|
||||
input: toPrismaJsonObject({}),
|
||||
output: toPrismaJsonObject({}),
|
||||
summaryText: step.summaryText || "automation.execution.stepQueued",
|
||||
sortOrder: step.sortOrder,
|
||||
})),
|
||||
},
|
||||
},
|
||||
select: { id: true, status: true },
|
||||
});
|
||||
return { id: execution.id, status: execution.status, deduplicated: false };
|
||||
});
|
||||
}
|
||||
|
||||
export async function createAutomationCredential(input: {
|
||||
request: Request;
|
||||
params: Params;
|
||||
name: string;
|
||||
kind: string;
|
||||
value: string;
|
||||
metadata?: Record<string, unknown>;
|
||||
}): Promise<{ id: string }> {
|
||||
const ctx = await loadAutomationContext({ request: input.request, params: input.params });
|
||||
if (!ctx.canAdmin) throw new CatalogError(foundationErrors.notFound, { permission: AUTOMATION_ADMIN_PERMISSION });
|
||||
const encryptedValue = await encryptTenantField(ctx.tenantId, input.value);
|
||||
return withTenantRLS(ctx.tenantId, async (tx) =>
|
||||
tx.automationCredential.create({
|
||||
data: {
|
||||
tenantId: ctx.tenantId,
|
||||
name: input.name,
|
||||
kind: input.kind,
|
||||
encryptedValue,
|
||||
metadata: toPrismaJsonObject(input.metadata ?? {}),
|
||||
createdByUserId: ctx.userId,
|
||||
},
|
||||
select: { id: true },
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
async function recordTriggerVolume(input: { tenantId: string; triggerKey: string }): Promise<{ action: "allow" | "pause"; summaryText: string }> {
|
||||
const now = new Date();
|
||||
const windowMinutes = 5;
|
||||
const windowStart = new Date(Math.floor(now.getTime() / (windowMinutes * 60_000)) * windowMinutes * 60_000);
|
||||
return withTenantRLS(input.tenantId, async (tx) => {
|
||||
const row = await tx.automationTriggerMeter.upsert({
|
||||
where: { tenantId_triggerKey_windowStart_windowMinutes: { tenantId: input.tenantId, triggerKey: input.triggerKey, windowStart, windowMinutes } },
|
||||
update: { count: { increment: 1 } },
|
||||
create: { tenantId: input.tenantId, triggerKey: input.triggerKey, windowStart, windowMinutes, count: 1 },
|
||||
select: { count: true },
|
||||
});
|
||||
const result = evaluateTriggerVolume({
|
||||
triggerKey: input.triggerKey,
|
||||
countInWindow: row.count,
|
||||
windowMinutes,
|
||||
typicalDailyMin: 5,
|
||||
typicalDailyMax: 10,
|
||||
hardLimitInWindow: 2000,
|
||||
});
|
||||
if (result.action === "pause") {
|
||||
const pausedUntil = new Date(now.getTime() + 60 * 60_000);
|
||||
await tx.automationTriggerMeter.update({
|
||||
where: { tenantId_triggerKey_windowStart_windowMinutes: { tenantId: input.tenantId, triggerKey: input.triggerKey, windowStart, windowMinutes } },
|
||||
data: { pausedUntil, anomalyText: result.summaryText },
|
||||
});
|
||||
}
|
||||
return result;
|
||||
});
|
||||
}
|
||||
|
||||
function filterNodesForPermissions(nodes: readonly AutomationNodeDefinition[], permissions: readonly string[]): readonly AutomationNodeDefinition[] {
|
||||
return nodes.filter((node) => hasAnyPermission(permissions, node.requiredAnyPermission));
|
||||
}
|
||||
|
||||
async function loadAutomationEditorFlowForAction(tenantId: string, ruleId: string): Promise<AutomationEditorFlow> {
|
||||
return withTenantRLS(tenantId, async (tx) => {
|
||||
const rule = await tx.automationRule.findFirst({
|
||||
where: { id: ruleId, tenantId, archivedAt: null },
|
||||
select: {
|
||||
flowData: true,
|
||||
steps: { orderBy: { sortOrder: "asc" }, select: { stepKey: true, stepKind: true, nodeType: true, parentStepIds: true, config: true, position: true, sortOrder: true, summaryText: true } },
|
||||
},
|
||||
});
|
||||
if (!rule) throw new CatalogError(foundationErrors.notFound);
|
||||
return buildAutomationEditorFlow({
|
||||
flowData: rule.flowData,
|
||||
steps: rule.steps.map((step) => ({
|
||||
stepKey: step.stepKey,
|
||||
stepKind: step.stepKind,
|
||||
nodeType: step.nodeType,
|
||||
parentStepIds: step.parentStepIds,
|
||||
config: step.config,
|
||||
position: step.position,
|
||||
sortOrder: step.sortOrder,
|
||||
summaryText: step.summaryText,
|
||||
})),
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function persistAutomationEditorFlow(tenantId: string, ruleId: string, flow: AutomationEditorFlow): Promise<void> {
|
||||
const triggerKey = flow.steps.find((step) => step.kind === "trigger")?.nodeType ?? null;
|
||||
await withTenantRLS(tenantId, async (tx) => {
|
||||
await tx.automationRuleStep.deleteMany({ where: { tenantId, ruleId } });
|
||||
await tx.automationRule.update({
|
||||
where: { id: ruleId },
|
||||
data: {
|
||||
triggerKey,
|
||||
flowData: toPrismaJson(serializeAutomationEditorFlow(flow)),
|
||||
steps: {
|
||||
create: flow.steps.map((step, index) => ({
|
||||
tenantId,
|
||||
stepKey: step.stepKey,
|
||||
stepKind: nodeKindToStepKind(step.kind),
|
||||
nodeType: step.nodeType,
|
||||
config: toPrismaJsonObject(step.config),
|
||||
parentStepIds: [...step.parentStepIds],
|
||||
position: toPrismaJsonObject(step.position),
|
||||
sortOrder: index,
|
||||
summaryText: step.summaryKey,
|
||||
})),
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function operationFromFormData(intent: string, formData: FormData): AutomationEditorOperation {
|
||||
if (intent === "add-node") return { type: "add-node", nodeType: String(formData.get("nodeType") ?? ""), parentStepKey: formData.get("parentStepKey")?.toString() ?? null };
|
||||
if (intent === "delete-node") return { type: "delete-node", stepKey: String(formData.get("stepKey") ?? "") };
|
||||
if (intent === "duplicate-node") return { type: "duplicate-node", stepKey: String(formData.get("stepKey") ?? "") };
|
||||
if (intent === "connect") return { type: "connect", fromStepKey: String(formData.get("fromStepKey") ?? ""), toStepKey: String(formData.get("toStepKey") ?? "") };
|
||||
if (intent === "disconnect") return { type: "disconnect", fromStepKey: String(formData.get("fromStepKey") ?? ""), toStepKey: String(formData.get("toStepKey") ?? "") };
|
||||
if (intent === "undo") return { type: "undo" };
|
||||
if (intent === "redo") return { type: "redo" };
|
||||
return { type: "auto-layout" };
|
||||
}
|
||||
|
||||
function parseFlowJson(value: FormDataEntryValue | null, fallback: AutomationEditorFlow): AutomationEditorFlow {
|
||||
if (typeof value !== "string") return fallback;
|
||||
try {
|
||||
return buildAutomationEditorFlow({ flowData: JSON.parse(value), steps: [] });
|
||||
} catch {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
function templateToFlowData(template: (typeof automationTemplateCatalog)[number]) {
|
||||
return {
|
||||
templateKey: template.key,
|
||||
triggerKey: template.triggerKey,
|
||||
steps: template.steps,
|
||||
};
|
||||
}
|
||||
|
||||
function toPrismaJson(value: unknown): Prisma.InputJsonValue {
|
||||
return JSON.parse(JSON.stringify(value ?? {})) as Prisma.InputJsonValue;
|
||||
}
|
||||
|
||||
function toPrismaJsonObject(value: Record<string, unknown>): Prisma.InputJsonObject {
|
||||
return toPrismaJson(value) as Prisma.InputJsonObject;
|
||||
}
|
||||
|
||||
function normalizeFlowData(value: unknown): { triggerKey: string; steps: (AutomationGraphStep & { kind: string; summaryKey: string })[] } {
|
||||
const data = value && typeof value === "object" ? (value as { triggerKey?: unknown; steps?: unknown }) : {};
|
||||
const steps = Array.isArray(data.steps) ? data.steps : [];
|
||||
return {
|
||||
triggerKey: typeof data.triggerKey === "string" ? data.triggerKey : "",
|
||||
steps: steps.map((raw, index) => {
|
||||
const step = raw && typeof raw === "object" ? (raw as Record<string, unknown>) : {};
|
||||
const nodeType = typeof step.nodeType === "string" ? step.nodeType : "";
|
||||
const node = getAutomationNode(nodeType);
|
||||
return {
|
||||
stepKey: typeof step.stepKey === "string" ? step.stepKey : `step-${index + 1}`,
|
||||
kind: typeof step.kind === "string" ? step.kind : node?.kind ?? "action",
|
||||
nodeType,
|
||||
parentStepIds: Array.isArray(step.parentStepIds) ? step.parentStepIds.filter((item): item is string => typeof item === "string") : [],
|
||||
summaryKey: typeof step.summaryKey === "string" ? step.summaryKey : "automation.execution.stepQueued",
|
||||
};
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
function nodeKindToStepKind(kind: string): "trigger" | "condition" | "action" | "flow_control" {
|
||||
if (kind === "trigger" || kind === "condition" || kind === "flow_control") return kind;
|
||||
return "action";
|
||||
}
|
||||
Reference in new issue
Block a user