781 lines
33 KiB
TypeScript
781 lines
33 KiB
TypeScript
import {
|
|
AUTOMATION_TRIGGERS_WITHOUT_EMITTER,
|
|
automationExecutionFamily,
|
|
evaluateLoopGuard,
|
|
getAutomationNode,
|
|
isAutomationNodeRunnable,
|
|
type AutomationGraphStep,
|
|
type AutomationNodeDefinition,
|
|
type AutomationNodeKind,
|
|
} from "./automation.registry";
|
|
import {
|
|
AUTOMATION_CONDITION_BRANCHES_CONFIG_KEY,
|
|
automationConditionBranches,
|
|
withAutomationConditionBranch,
|
|
type AutomationConditionBranch,
|
|
} from "@hivegrid/db/automation-graph";
|
|
|
|
export type AutomationEditorIssueCode =
|
|
| "missing_trigger"
|
|
| "multiple_triggers"
|
|
| "unknown_node"
|
|
| "unconnected_step"
|
|
| "missing_parent"
|
|
| "loop_detected"
|
|
| "empty_flow"
|
|
| "node_without_executor"
|
|
| "executor_family_mismatch"
|
|
| "trigger_without_emitter"
|
|
| "incomplete_configuration";
|
|
|
|
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: "delete-nodes"; readonly stepKeys: readonly string[] }
|
|
| { readonly type: "duplicate-node"; readonly stepKey: string }
|
|
| { readonly type: "paste-steps"; readonly steps: readonly AutomationEditorStepInput[] }
|
|
| { readonly type: "connect"; readonly fromStepKey: string; readonly toStepKey: string; readonly branch?: AutomationConditionBranch }
|
|
| { readonly type: "disconnect"; readonly fromStepKey: string; readonly toStepKey: string }
|
|
| { readonly type: "auto-layout" }
|
|
| { readonly type: "undo" }
|
|
| { readonly type: "redo" };
|
|
|
|
export interface AutomationDryRunPreview {
|
|
readonly requiresConfirmation: boolean;
|
|
readonly confirmationPhrase: string;
|
|
readonly matchedRecords: number;
|
|
readonly inspectedEvents: number;
|
|
readonly sampleLimitReached: boolean;
|
|
readonly examples: readonly string[];
|
|
readonly steps: readonly {
|
|
readonly stepKey: string;
|
|
readonly nodeType: string;
|
|
readonly summaryKey: string;
|
|
readonly effectKey: string;
|
|
}[];
|
|
readonly warnings: readonly string[];
|
|
}
|
|
|
|
export interface AutomationReverseRecipient {
|
|
readonly name: string | null;
|
|
readonly email: string | null;
|
|
}
|
|
|
|
export interface AutomationReversePlan {
|
|
readonly canReverse: boolean;
|
|
readonly confirmationPhrase: string;
|
|
readonly items: readonly {
|
|
readonly stepKey: string;
|
|
readonly nodeType: string;
|
|
readonly actionKey: string;
|
|
readonly reversible: boolean;
|
|
/** Delivered-to list for send-type steps; shown as "not retractable" evidence. */
|
|
readonly recipients: readonly AutomationReverseRecipient[];
|
|
}[];
|
|
readonly warnings: readonly string[];
|
|
}
|
|
|
|
const DRY_RUN_CONFIRMATION_THRESHOLD = 100;
|
|
const MAX_HISTORY = 20;
|
|
/**
|
|
* Canvas grid for placed nodes. The step card renders at 288px wide (w-72), so
|
|
* the column pitch has to clear that plus a gutter - a narrower grid drops each
|
|
* new node on top of its neighbour.
|
|
*/
|
|
const CANVAS_COLUMN_WIDTH = 340;
|
|
const CANVAS_ROW_HEIGHT = 160;
|
|
const CANVAS_COLUMNS = 3;
|
|
|
|
/** Grid slot for the n-th node, left to right and then wrapping downwards. */
|
|
function gridPosition(index: number): { x: number; y: number } {
|
|
return { x: CANVAS_COLUMN_WIDTH * (index % CANVAS_COLUMNS), y: CANVAS_ROW_HEIGHT * Math.floor(index / CANVAS_COLUMNS) };
|
|
}
|
|
|
|
export function buildAutomationEditorFlow(input: { readonly flowData: unknown; readonly steps: readonly AutomationEditorStepInput[] }): AutomationEditorFlow {
|
|
const rawFlow = objectOrEmpty(input.flowData);
|
|
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(", ")));
|
|
}
|
|
|
|
// The trigger decides which executor picks the rule up, so every action has
|
|
// to belong to the same family (see automationExecutionFamily).
|
|
const triggerFamily = triggerSteps.length === 1 ? automationExecutionFamily(triggerSteps[0]!.nodeType) : null;
|
|
if (triggerSteps.length === 1 && AUTOMATION_TRIGGERS_WITHOUT_EMITTER.has(triggerSteps[0]!.nodeType)) {
|
|
issues.push(issue("trigger_without_emitter", triggerSteps[0]!.stepKey, "automation.editor.validation.triggerWithoutEmitter", triggerSteps[0]!.nodeType));
|
|
}
|
|
|
|
const stepKeys = new Set(flow.steps.map((step) => step.stepKey));
|
|
for (const step of flow.steps) {
|
|
const node = getAutomationNode(step.nodeType);
|
|
if (!node) {
|
|
issues.push(issue("unknown_node", step.stepKey, "automation.editor.validation.unknownNode", step.nodeType));
|
|
} else if (!isAutomationNodeRunnable(node)) {
|
|
issues.push(issue("node_without_executor", step.stepKey, "automation.editor.validation.nodeWithoutExecutor", step.nodeType));
|
|
} else if (triggerFamily && step.kind !== "trigger" && automationExecutionFamily(step.nodeType) !== triggerFamily) {
|
|
issues.push(issue("executor_family_mismatch", step.stepKey, "automation.editor.validation.executorFamilyMismatch", step.nodeType));
|
|
}
|
|
if (node && incompleteAutomationNodeConfigKeys(step.nodeType, step.config).length > 0) {
|
|
issues.push(issue("incomplete_configuration", step.stepKey, "automation.editor.validation.incompleteConfiguration", step.nodeType));
|
|
}
|
|
for (const parentStepId of step.parentStepIds) {
|
|
if (!stepKeys.has(parentStepId)) {
|
|
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,
|
|
};
|
|
}
|
|
|
|
type AutomationConfigRequirement = {
|
|
readonly required?: readonly string[];
|
|
readonly allowed?: Readonly<Record<string, readonly string[]>>;
|
|
readonly requiredWhen?: readonly { readonly key: string; readonly whenKey: string; readonly equals: string }[];
|
|
};
|
|
|
|
const AUTOMATION_CONFIG_REQUIREMENTS: Readonly<Record<string, AutomationConfigRequirement>> = {
|
|
"projects.deadline_soon": {
|
|
required: ["fristtyp", "leadTime", "leadTimeUnit"],
|
|
allowed: {
|
|
fristtyp: ["aufgabenFaelligkeit", "projektDeadline", "zahlungsziel"],
|
|
leadTimeUnit: ["stunden", "tage", "wochen"],
|
|
},
|
|
},
|
|
"time.schedule": {
|
|
required: ["wiederholung", "uhrzeit"],
|
|
allowed: {
|
|
wiederholung: ["taeglich", "woechentlich", "monatlich"],
|
|
wochentag: ["montag", "dienstag", "mittwoch", "donnerstag", "freitag", "samstag", "sonntag"],
|
|
},
|
|
requiredWhen: [
|
|
{ key: "wochentag", whenKey: "wiederholung", equals: "woechentlich" },
|
|
{ key: "monatstag", whenKey: "wiederholung", equals: "monatlich" },
|
|
],
|
|
},
|
|
"crm.update_kontakt": {
|
|
required: ["kontakt", "feld", "wert"],
|
|
allowed: {
|
|
kontakt: ["ausloeser", "manuell"],
|
|
feld: ["kontaktStatus", "vorname", "nachname", "orgName", "primaerEmail", "primaerTelefon", "language"],
|
|
},
|
|
requiredWhen: [{ key: "kontaktId", whenKey: "kontakt", equals: "manuell" }],
|
|
},
|
|
"crm.add_tag": {
|
|
required: ["kontakt", "tagId"],
|
|
allowed: { kontakt: ["ausloeser", "manuell"] },
|
|
requiredWhen: [{ key: "kontaktId", whenKey: "kontakt", equals: "manuell" }],
|
|
},
|
|
"crm.remove_tag": {
|
|
required: ["kontakt", "tagId"],
|
|
allowed: { kontakt: ["ausloeser", "manuell"] },
|
|
requiredWhen: [{ key: "kontaktId", whenKey: "kontakt", equals: "manuell" }],
|
|
},
|
|
"crm.assign_kontakt": {
|
|
required: ["kontakt", "userId"],
|
|
allowed: { kontakt: ["ausloeser", "manuell"] },
|
|
requiredWhen: [{ key: "kontaktId", whenKey: "kontakt", equals: "manuell" }],
|
|
},
|
|
"lead.assign": {
|
|
required: ["lead", "userId"],
|
|
allowed: { lead: ["ausloeser", "manuell"] },
|
|
requiredWhen: [{ key: "leadId", whenKey: "lead", equals: "manuell" }],
|
|
},
|
|
"lead.set_status": {
|
|
required: ["lead", "status"],
|
|
allowed: { lead: ["ausloeser", "manuell"], status: ["new", "qualified", "converted", "lost", "spam"] },
|
|
requiredWhen: [{ key: "leadId", whenKey: "lead", equals: "manuell" }],
|
|
},
|
|
"crm.create_note": {
|
|
required: ["datensatz", "notiztext"],
|
|
allowed: { datensatz: ["kontaktAusAusloeser", "auftragAusAusloeser", "projektAusAusloeser"] },
|
|
},
|
|
"notification.send": {
|
|
required: ["kanal", "empfaenger", "betreff", "nachricht"],
|
|
allowed: { kanal: ["intern"], empfaenger: ["besitzerDerAutomation", "bestimmtePerson"] },
|
|
requiredWhen: [{ key: "userId", whenKey: "empfaenger", equals: "bestimmtePerson" }],
|
|
},
|
|
"email.send_transactional": { required: ["an", "betreff", "nachricht"] },
|
|
"chat.post_message": { required: ["chatId", "nachricht"] },
|
|
"http.request": {
|
|
required: ["url", "methode"],
|
|
allowed: { methode: ["get", "post", "put", "delete"] },
|
|
},
|
|
"task.create": {
|
|
required: ["titel", "zustaendig", "prioritaet"],
|
|
allowed: { zustaendig: ["besitzerDerAutomation"], prioritaet: ["niedrig", "normal", "hoch"] },
|
|
},
|
|
"task.assign": {
|
|
required: ["aufgabe", "zustaendig", "benachrichtigungAn"],
|
|
allowed: {
|
|
aufgabe: ["ausVorherigemSchritt", "bestimmteAufgabe"],
|
|
zustaendig: ["erstellerDerAufgabe"],
|
|
benachrichtigungAn: ["neueVerantwortung", "bisherigeVerantwortung", "beide", "niemand"],
|
|
},
|
|
requiredWhen: [{ key: "taskId", whenKey: "aufgabe", equals: "bestimmteAufgabe" }],
|
|
},
|
|
"condition.if_else": {
|
|
required: ["feld", "vergleich", "wert"],
|
|
allowed: { vergleich: ["istGroesserAls", "istGleich", "istKleinerAls", "enthaelt"] },
|
|
},
|
|
"delay.wait": {
|
|
required: ["dauer", "dauerEinheit"],
|
|
allowed: { dauerEinheit: ["minuten", "stunden", "tage", "wochen"] },
|
|
},
|
|
"loop.for_each": {
|
|
required: ["liste", "maxDurchlaeufe"],
|
|
allowed: { liste: ["offeneAufgabenDesProjekts", "kontakteDesProjekts", "positionenDesAngebots", "termineDieserWoche"] },
|
|
},
|
|
"portal.invite_user": { required: ["kind", "email", "firstName", "lastName"], allowed: { kind: ["customer", "subcontractor"] } },
|
|
"portal.grant_access": { required: ["portalUserId", "projectId"] },
|
|
"portal.revoke_access": { required: ["portalUserId", "projectId"] },
|
|
"portal.release_document": { required: ["projectId", "fileId"] },
|
|
"portal.send_status_mail": { required: ["projectId", "stageChangeId"] },
|
|
"portal.disable_user": { required: ["portalUserId"] },
|
|
};
|
|
|
|
export function incompleteAutomationNodeConfigKeys(nodeType: string, config: Record<string, unknown>): readonly string[] {
|
|
const contract = AUTOMATION_CONFIG_REQUIREMENTS[nodeType];
|
|
if (!contract) return [];
|
|
const invalid = new Set<string>();
|
|
for (const key of contract.required ?? []) {
|
|
if (!hasAutomationConfigValue(config[key])) invalid.add(key);
|
|
}
|
|
for (const [key, allowedValues] of Object.entries(contract.allowed ?? {})) {
|
|
const value = config[key];
|
|
if (hasAutomationConfigValue(value) && (typeof value !== "string" || !allowedValues.includes(value))) invalid.add(key);
|
|
}
|
|
for (const conditional of contract.requiredWhen ?? []) {
|
|
if (config[conditional.whenKey] === conditional.equals && !hasAutomationConfigValue(config[conditional.key])) invalid.add(conditional.key);
|
|
}
|
|
if (nodeType === "delay.wait" && hasAutomationConfigValue(config.dauer)) {
|
|
const amount = Number(config.dauer);
|
|
if (!Number.isFinite(amount) || amount <= 0) invalid.add("dauer");
|
|
}
|
|
if (nodeType === "loop.for_each" && hasAutomationConfigValue(config.maxDurchlaeufe)) {
|
|
const count = Number(config.maxDurchlaeufe);
|
|
if (!Number.isInteger(count) || count < 1 || count > 100) invalid.add("maxDurchlaeufe");
|
|
}
|
|
if (nodeType === "projects.deadline_soon" && hasAutomationConfigValue(config.leadTime)) {
|
|
const leadTime = Number(config.leadTime);
|
|
if (!Number.isFinite(leadTime) || leadTime <= 0) invalid.add("leadTime");
|
|
}
|
|
if (nodeType === "time.schedule" && hasAutomationConfigValue(config.uhrzeit)) {
|
|
if (typeof config.uhrzeit !== "string" || !/^(?:[01]\d|2[0-3]):[0-5]\d$/u.test(config.uhrzeit.trim())) invalid.add("uhrzeit");
|
|
}
|
|
if (nodeType === "time.schedule" && hasAutomationConfigValue(config.monatstag)) {
|
|
const day = Number(config.monatstag);
|
|
if (!Number.isInteger(day) || day < 1 || day > 31) invalid.add("monatstag");
|
|
}
|
|
return [...invalid];
|
|
}
|
|
|
|
function hasAutomationConfigValue(value: unknown): boolean {
|
|
if (typeof value === "string") return value.trim().length > 0;
|
|
return typeof value === "number" ? Number.isFinite(value) : typeof value === "boolean";
|
|
}
|
|
|
|
export function applyAutomationEditorOperation(
|
|
flow: AutomationEditorFlow,
|
|
operation: AutomationEditorOperation,
|
|
catalog: readonly AutomationNodeDefinition[]
|
|
): AutomationEditorFlow {
|
|
if (operation.type === "undo") return undoFlow(flow);
|
|
if (operation.type === "redo") return redoFlow(flow);
|
|
|
|
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: gridPosition(nextSteps.length),
|
|
sortOrder: nextSteps.length,
|
|
summaryKey: node.titleKey,
|
|
});
|
|
}
|
|
if (operation.type === "delete-node" || operation.type === "delete-nodes") {
|
|
const removed = new Set(operation.type === "delete-node" ? [operation.stepKey] : operation.stepKeys);
|
|
nextSteps = nextSteps
|
|
.filter((step) => !removed.has(step.stepKey))
|
|
.map((step, index) => ({ ...step, parentStepIds: step.parentStepIds.filter((parent) => !removed.has(parent)), sortOrder: index }));
|
|
}
|
|
if (operation.type === "duplicate-node") {
|
|
const source = nextSteps.find((step) => step.stepKey === operation.stepKey);
|
|
if (!source) return flow;
|
|
nextSteps.push({
|
|
...source,
|
|
stepKey: uniqueStepKey(nextSteps, source.nodeType),
|
|
sortOrder: nextSteps.length,
|
|
position: { x: source.position.x + 48, y: source.position.y + 48 },
|
|
});
|
|
}
|
|
if (operation.type === "paste-steps") {
|
|
const pasted = operation.steps
|
|
.map((raw, index) => normalizeStep(raw, nextSteps.length + index))
|
|
.filter(
|
|
(step): step is AutomationEditorStep => step !== null && Boolean(catalog.find((item) => item.key === step.nodeType) ?? getAutomationNode(step.nodeType))
|
|
);
|
|
if (pasted.length === 0) return flow;
|
|
const keyMap = new Map<string, string>();
|
|
const accumulated = [...nextSteps];
|
|
for (const step of pasted) {
|
|
const freshKey = uniqueStepKey(accumulated, step.nodeType);
|
|
keyMap.set(step.stepKey, freshKey);
|
|
accumulated.push({ ...step, stepKey: freshKey });
|
|
}
|
|
const existingKeys = new Set(nextSteps.map((step) => step.stepKey));
|
|
for (const step of pasted) {
|
|
nextSteps.push({
|
|
...step,
|
|
stepKey: keyMap.get(step.stepKey) ?? step.stepKey,
|
|
parentStepIds: step.parentStepIds
|
|
.map((parent) => keyMap.get(parent) ?? (existingKeys.has(parent) ? parent : null))
|
|
.filter((parent): parent is string => parent !== null),
|
|
config: remapConditionBranchParents(step.config, keyMap, existingKeys),
|
|
position: { x: step.position.x + 48, y: step.position.y + 48 },
|
|
sortOrder: nextSteps.length,
|
|
});
|
|
}
|
|
}
|
|
if (operation.type === "connect") {
|
|
const source = nextSteps.find((step) => step.stepKey === operation.fromStepKey);
|
|
nextSteps = nextSteps.map((step) =>
|
|
step.stepKey === operation.toStepKey && step.stepKey !== operation.fromStepKey
|
|
? {
|
|
...step,
|
|
parentStepIds: uniqueStrings([...step.parentStepIds, operation.fromStepKey]),
|
|
config:
|
|
source?.nodeType === "condition.if_else"
|
|
? withAutomationConditionBranch(step.config, operation.fromStepKey, operation.branch ?? "true")
|
|
: step.config,
|
|
}
|
|
: step
|
|
);
|
|
}
|
|
if (operation.type === "disconnect") {
|
|
nextSteps = nextSteps.map((step) =>
|
|
step.stepKey === operation.toStepKey
|
|
? {
|
|
...step,
|
|
parentStepIds: step.parentStepIds.filter((parent) => parent !== operation.fromStepKey),
|
|
config: withAutomationConditionBranch(step.config, operation.fromStepKey, null),
|
|
}
|
|
: step
|
|
);
|
|
}
|
|
if (operation.type === "auto-layout") {
|
|
nextSteps = nextSteps.map((step, index) => ({ ...step, position: gridPosition(index), sortOrder: index }));
|
|
}
|
|
|
|
return withHistory(
|
|
{ triggerKey: nextSteps.find((step) => step.kind === "trigger")?.nodeType ?? flow.triggerKey, steps: nextSteps, history: flow.history },
|
|
before
|
|
);
|
|
}
|
|
|
|
function remapConditionBranchParents(
|
|
config: Record<string, unknown>,
|
|
keyMap: ReadonlyMap<string, string>,
|
|
existingKeys: ReadonlySet<string>
|
|
): Record<string, unknown> {
|
|
const next = { ...config };
|
|
delete next[AUTOMATION_CONDITION_BRANCHES_CONFIG_KEY];
|
|
for (const [parentStepKey, branch] of Object.entries(automationConditionBranches(config))) {
|
|
const remappedParent = keyMap.get(parentStepKey) ?? (existingKeys.has(parentStepKey) ? parentStepKey : null);
|
|
if (remappedParent) Object.assign(next, withAutomationConditionBranch(next, remappedParent, branch));
|
|
}
|
|
return next;
|
|
}
|
|
|
|
/**
|
|
* Extracts the given steps as serializable clipboard payload. Parent references
|
|
* pointing outside the selection are kept so a paste into the same flow can
|
|
* re-attach to still-existing steps; `applyAutomationEditorOperation` drops
|
|
* references that no longer resolve.
|
|
*/
|
|
export function extractAutomationClipboardSteps(flow: AutomationEditorFlow, stepKeys: readonly string[]): readonly AutomationEditorStepInput[] {
|
|
const wanted = new Set(stepKeys);
|
|
return flow.steps
|
|
.filter((step) => wanted.has(step.stepKey))
|
|
.map((step) => ({
|
|
stepKey: step.stepKey,
|
|
kind: step.kind,
|
|
nodeType: step.nodeType,
|
|
parentStepIds: [...step.parentStepIds],
|
|
config: { ...step.config },
|
|
position: { ...step.position },
|
|
sortOrder: step.sortOrder,
|
|
summaryKey: step.summaryKey,
|
|
}));
|
|
}
|
|
|
|
export function buildAutomationDryRunPreview(input: {
|
|
readonly flow: AutomationEditorFlow;
|
|
readonly confirmationPhrase: string;
|
|
readonly matchedRecords?: number;
|
|
readonly inspectedEvents?: number;
|
|
readonly sampleLimitReached?: boolean;
|
|
readonly examples?: readonly string[];
|
|
}): AutomationDryRunPreview {
|
|
const matchedRecords = Math.max(0, input.matchedRecords ?? 0);
|
|
const validation = validateAutomationEditorFlow(input.flow);
|
|
return {
|
|
requiresConfirmation: matchedRecords > DRY_RUN_CONFIRMATION_THRESHOLD,
|
|
confirmationPhrase: input.confirmationPhrase,
|
|
matchedRecords,
|
|
inspectedEvents: Math.max(0, input.inspectedEvents ?? matchedRecords),
|
|
sampleLimitReached: input.sampleLimitReached ?? false,
|
|
examples: (input.examples ?? []).slice(0, 5),
|
|
steps: input.flow.steps.map((step) => ({
|
|
stepKey: step.stepKey,
|
|
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;
|
|
readonly expectedConfirmationPhrase: string;
|
|
}): boolean {
|
|
return input.matchedRecords <= DRY_RUN_CONFIRMATION_THRESHOLD || input.confirmationPhrase?.trim() === input.expectedConfirmationPhrase;
|
|
}
|
|
|
|
export function buildAutomationReversePlan(input: {
|
|
readonly reverseWindowExpiresAt: string | Date | null;
|
|
readonly steps: readonly { readonly stepKey: string; readonly nodeType: string; readonly output?: unknown }[];
|
|
readonly confirmationPhrase: string;
|
|
readonly now?: Date;
|
|
}): AutomationReversePlan {
|
|
const expiresAt = typeof input.reverseWindowExpiresAt === "string" ? new Date(input.reverseWindowExpiresAt) : input.reverseWindowExpiresAt;
|
|
const canReverse = !!expiresAt && expiresAt.getTime() > (input.now ?? new Date()).getTime();
|
|
const items = input.steps.map((step) => {
|
|
const action = reverseActionForNode(step.nodeType);
|
|
return {
|
|
stepKey: step.stepKey,
|
|
nodeType: step.nodeType,
|
|
actionKey: action.actionKey,
|
|
reversible: action.reversible,
|
|
recipients: extractAutomationReverseRecipients(step.nodeType, step.output),
|
|
};
|
|
});
|
|
return {
|
|
canReverse,
|
|
confirmationPhrase: input.confirmationPhrase,
|
|
items,
|
|
warnings: items.filter((item) => !item.reversible).map((item) => item.actionKey),
|
|
};
|
|
}
|
|
|
|
export function canConfirmAutomationReverse(input: {
|
|
readonly confirmationPhrase: string | null | undefined;
|
|
readonly expectedConfirmationPhrase: string;
|
|
}): boolean {
|
|
return input.confirmationPhrase?.trim().toLocaleUpperCase() === input.expectedConfirmationPhrase.trim().toLocaleUpperCase();
|
|
}
|
|
|
|
function normalizeStep(raw: AutomationEditorStepInput, index: number): AutomationEditorStep | null {
|
|
const object = objectOrEmpty(raw);
|
|
const nodeType = typeof object.nodeType === "string" ? object.nodeType : "";
|
|
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);
|
|
const fallback = gridPosition(index);
|
|
return {
|
|
x: typeof raw.x === "number" ? raw.x : fallback.x,
|
|
y: typeof raw.y === "number" ? raw.y : fallback.y,
|
|
};
|
|
}
|
|
|
|
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))];
|
|
}
|
|
|
|
/**
|
|
* Reads the delivered-recipient list from a persisted send-step output.
|
|
* Contract: `output.recipients` is an array of strings (email) or objects with
|
|
* `name`/`email`. Tolerates missing or malformed outputs (returns empty list)
|
|
* because forward outputs are only available once the executor persisted them.
|
|
*/
|
|
export function extractAutomationReverseRecipients(nodeType: string, output: unknown): readonly AutomationReverseRecipient[] {
|
|
if (nodeType !== "notification.send" && !nodeType.startsWith("email.")) return [];
|
|
const record = objectOrEmpty(output);
|
|
const raw = Array.isArray(record.recipients) ? record.recipients : [];
|
|
return raw
|
|
.map((entry): AutomationReverseRecipient => {
|
|
if (typeof entry === "string") return { name: null, email: entry };
|
|
const item = objectOrEmpty(entry);
|
|
return {
|
|
name: typeof item.name === "string" && item.name.trim() ? item.name : null,
|
|
email: typeof item.email === "string" && item.email.trim() ? item.email : null,
|
|
};
|
|
})
|
|
.filter((entry) => entry.name !== null || entry.email !== null);
|
|
}
|
|
|
|
function reverseActionForNode(nodeType: string): { actionKey: string; reversible: boolean } {
|
|
if (nodeType === "task.create") return { actionKey: "automation.editor.reverse.actions.deleteTask", reversible: true };
|
|
if (nodeType === "crm.update_kontakt") return { actionKey: "automation.editor.reverse.actions.revertCrmStatus", reversible: true };
|
|
if (nodeType === "crm.add_tag") return { actionKey: "automation.editor.reverse.actions.removeContactTag", reversible: true };
|
|
if (nodeType === "crm.remove_tag") return { actionKey: "automation.editor.reverse.actions.restoreContactTag", reversible: true };
|
|
if (nodeType === "crm.assign_kontakt") return { actionKey: "automation.editor.reverse.actions.restoreContactAssignment", reversible: true };
|
|
if (nodeType === "lead.assign") return { actionKey: "automation.editor.reverse.actions.restoreLeadAssignment", reversible: true };
|
|
if (nodeType === "lead.set_status") return { actionKey: "automation.editor.reverse.actions.restoreLeadStatus", reversible: true };
|
|
// CRM notes are append-only Activity entries in the current typed model. They
|
|
// stay visible for auditability and therefore cannot be destructively undone.
|
|
if (nodeType === "crm.create_note") return { actionKey: "automation.editor.reverse.actions.deleteCrmNote", reversible: false };
|
|
if (nodeType === "task.assign") return { actionKey: "automation.editor.reverse.actions.restoreTaskAssignment", reversible: true };
|
|
if (nodeType === "notification.send" || nodeType.startsWith("email.") || nodeType === "chat.post_message")
|
|
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 };
|
|
}
|