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; } 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(); for (const edge of dependencyEdges) { outgoing.set(edge.from, [...(outgoing.get(edge.from) ?? []), edge.to]); } const visiting = new Set(); const visited = new Set(); 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: {}, }; }