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 { 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): Promise { 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 { 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 { 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 { 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 { 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 { 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(); 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 { 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; 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; }): 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 { 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 { 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): 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) : {}; 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"; }