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; 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 { 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 { const reachable = new Set(); 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 { return value && typeof value === "object" && !Array.isArray(value) ? (value as Record) : {}; } function issue(code: AutomationEditorIssueCode, stepKey: string | null, messageKey: string, detail: string | null = null): AutomationEditorValidationIssue { return { code, severity: "error", stepKey, messageKey, detail }; }