Refresh HiveGrid Cloud reference snapshot

This commit is contained in:
david committed 2026-08-03 15:31:14 +02:00
1 parent 5e99e14772
commit 7f88026f79
5955 files changed
+1177325 -188362

No files matched your search

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