import { buildAutomationExecutionRequestedOutboxEvent } from "@hivegrid/db/automation-forward.server"; import { loadAutomationDryRunEventSampleWithTx } from "@hivegrid/db/automation-dry-run.server"; import { encryptTenantField } from "@hivegrid/db/crypto/tenant-envelope.server"; import { publishOutboxEvent, type OutboxPublisherTransaction } from "@hivegrid/db/outbox"; import type { Prisma } from "@hivegrid/db/prisma-browser"; import { CatalogError, foundationErrors } from "@hivegrid/foundation"; import { logActivity } from "@hivegrid/activity"; import type { Params } from "react-router"; import { getTranslations } from "~/locale/i18next.server"; 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, canConfirmAutomationReverse, canConfirmAutomationDryRun, serializeAutomationEditorFlow, validateAutomationEditorFlow, type AutomationDryRunPreview, type AutomationEditorFlow, type AutomationEditorOperation, type AutomationEditorStepInput, type AutomationEditorValidationResult, type AutomationReversePlan, } from "./automation.editor"; import { AUTOMATION_ADMIN_PERMISSION, AUTOMATION_MANAGE_PERMISSION, AUTOMATION_MODULE_KEY, AUTOMATION_READ_PERMISSION, AUTOMATION_RUN_PERMISSION, AUTOMATION_TRIGGER_VOLUME_ANOMALY_KEY, buildAutomationIdempotencyKey, buildReverseWindowExpiresAt, evaluateLoopGuard, evaluateTriggerVolume, getAutomationPlatformTemplateByStoredName, getAutomationNode, listAutomationNodes, translateAutomationPlatformTemplate, 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 failed24h: number; readonly lastExecutionAt: string | null; readonly updatedAt: string; readonly createdByUserId: string | null; readonly ownerName: string | null; /** * i18n key of the guard that auto-paused the rule (WF-P12 M02), plus the * meter numbers the screen interpolates into it. */ readonly anomalyText: string | null; readonly anomalyCount: number | null; readonly anomalyWindowMinutes: number | null; readonly anomalyPausedUntil: string | null; readonly executionsUrl: string; readonly editUrl: string; } export interface AutomationListVM { readonly tenantSlug: string; readonly currentUserId: string; readonly rules: readonly AutomationListItemVM[]; readonly templates: readonly { readonly id: string; readonly name: string; readonly category: string; readonly isPublished: boolean }[]; readonly templatesUrl: string; readonly canManage: boolean; readonly canRun: boolean; } export interface AutomationExecutionListVM { readonly rule: { readonly id: string; readonly name: string; readonly triggerKey: string | null; readonly status: string; readonly editUrl: string; }; readonly listUrl: string; readonly stats: { readonly lastExecutionAt: string | null; readonly lastExecutionStatus: string | null; readonly successRate30d: number | null; readonly failed30d: number; readonly avgDurationMs: number | null; }; readonly executions: readonly { readonly id: string; readonly status: string; readonly dryRun: boolean; readonly triggerKey: string; readonly summaryText: string; readonly errorText: string | null; readonly createdAt: string; readonly durationMs: number | null; readonly detailUrl: string; }[]; readonly canManage: boolean; readonly canRun: boolean; } export interface AutomationExecutionDetailVM { readonly rule: { readonly id: string; readonly name: string; readonly executionsUrl: string; readonly editUrl: string }; readonly listUrl: string; readonly execution: { readonly id: string; readonly status: string; readonly dryRun: boolean; readonly triggerKey: string; readonly summaryText: string; readonly errorText: string | null; readonly createdAt: string; readonly startedAt: string | null; readonly endedAt: string | null; readonly durationMs: number | 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 input: unknown; readonly output: unknown; }[]; readonly reversePlan: AutomationReversePlan; readonly canRun: boolean; } 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; /** Trigger -> action chain (i18n summary keys) for the S04 card preview. */ readonly chain: readonly { readonly kind: string; readonly summaryKey: string; readonly nodeType: string }[]; }[]; readonly rules: readonly { readonly id: string; readonly name: string }[]; readonly listUrl: 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 }; export type AutomationExecutionDetailActionData = | { readonly ok: true; readonly messageKey: string; readonly reversedCount?: number } | { readonly ok: false; readonly errorKey: string }; 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 loadAutomationListVM({ request, params }: { request: Request; params: Params }): Promise { const ctx = await loadAutomationContext({ request, params }); const now = new Date(); const since30d = new Date(now); since30d.setDate(since30d.getDate() - 30); const since24h = new Date(now.getTime() - 24 * 60 * 60_000); return withTenantRLS(ctx.tenantId, async (tx) => { const [rules, templates, failed24hGroups, activeAnomalies] = 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, updatedAt: true, createdByUserId: 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 }, }), tx.automationExecution.groupBy({ by: ["ruleId"], where: { tenantId: ctx.tenantId, status: "failed", createdAt: { gte: since24h } }, _count: { _all: true }, }), tx.automationTriggerMeter.findMany({ where: { tenantId: ctx.tenantId, pausedUntil: { gt: now } }, orderBy: { pausedUntil: "desc" }, select: { triggerKey: true, pausedUntil: true, anomalyText: true, count: true, windowMinutes: true }, }), ]); // The User table carries no tenant RLS policy, so owner names resolve inside the tx. const ownerIds = [...new Set(rules.map((rule) => rule.createdByUserId).filter((id): id is string => !!id))]; const owners = ownerIds.length ? await tx.user.findMany({ where: { id: { in: ownerIds } }, select: { id: true, firstName: true, lastName: true } }) : []; const ownerNameById = new Map(owners.map((user) => [user.id, `${user.firstName} ${user.lastName}`.trim()])); const failed24hByRuleId = new Map(failed24hGroups.map((group) => [group.ruleId, group._count._all])); const anomalyByTriggerKey = new Map(activeAnomalies.map((meter) => [meter.triggerKey, meter])); return { tenantSlug: ctx.tenantSlug, currentUserId: ctx.userId, rules: rules.map((rule) => { const anomaly = rule.triggerKey ? anomalyByTriggerKey.get(rule.triggerKey) : undefined; // Only surface the anomaly on rules the meter actually paused. const showAnomaly = !!anomaly && rule.status === "paused"; return { id: rule.id, name: rule.name, description: rule.description, status: rule.status, enabled: rule.enabled, triggerKey: rule.triggerKey, runs30d: rule.executions.length, failed24h: failed24hByRuleId.get(rule.id) ?? 0, lastExecutionAt: rule.executions[0]?.createdAt.toISOString() ?? null, updatedAt: rule.updatedAt.toISOString(), createdByUserId: rule.createdByUserId, ownerName: rule.createdByUserId ? ownerNameById.get(rule.createdByUserId) ?? null : null, anomalyText: showAnomaly ? anomaly.anomalyText : null, anomalyCount: showAnomaly ? anomaly.count : null, anomalyWindowMinutes: showAnomaly ? anomaly.windowMinutes : null, anomalyPausedUntil: showAnomaly ? anomaly.pausedUntil?.toISOString() ?? null : 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" }), }; }), templates, templatesUrl: appPath({ tenantSlug: ctx.tenantSlug, path: "automations/templates", mode: "host-aware" }), 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); const since30d = new Date(); since30d.setDate(since30d.getDate() - 30); 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, status: true, executions: { orderBy: { createdAt: "desc" }, take: 50, select: { id: true, status: true, dryRun: true, triggerKey: true, summaryText: true, errorText: true, createdAt: true, durationMs: true }, }, }, }); if (!rule) throw new CatalogError(foundationErrors.notFound); const [total30d, success30d, failed30d, durationAgg] = await Promise.all([ tx.automationExecution.count({ where: { tenantId: ctx.tenantId, ruleId, createdAt: { gte: since30d } } }), tx.automationExecution.count({ where: { tenantId: ctx.tenantId, ruleId, status: "success", createdAt: { gte: since30d } } }), tx.automationExecution.count({ where: { tenantId: ctx.tenantId, ruleId, status: "failed", createdAt: { gte: since30d } } }), tx.automationExecution.aggregate({ where: { tenantId: ctx.tenantId, ruleId, createdAt: { gte: since30d }, durationMs: { not: null } }, _avg: { durationMs: true }, }), ]); return { rule: { id: rule.id, name: rule.name, triggerKey: rule.triggerKey, status: rule.status, editUrl: appPath({ tenantSlug: ctx.tenantSlug, path: `automations/${rule.id}/edit`, mode: "host-aware" }), }, listUrl: appPath({ tenantSlug: ctx.tenantSlug, path: "automations", mode: "host-aware" }), stats: { lastExecutionAt: rule.executions[0]?.createdAt.toISOString() ?? null, lastExecutionStatus: rule.executions[0]?.status ?? null, successRate30d: total30d > 0 ? Math.round((success30d / total30d) * 1000) / 10 : null, failed30d, avgDurationMs: durationAgg._avg.durationMs == null ? null : Math.round(durationAgg._avg.durationMs), }, executions: rule.executions.map((execution) => ({ id: execution.id, status: execution.status, dryRun: execution.dryRun, triggerKey: execution.triggerKey, summaryText: execution.summaryText, errorText: execution.errorText, createdAt: execution.createdAt.toISOString(), durationMs: execution.durationMs, detailUrl: appPath({ tenantSlug: ctx.tenantSlug, path: `automations/${rule.id}/executions/${execution.id}`, mode: "host-aware" }), })), canManage: ctx.canManage, canRun: ctx.canRun, }; }); } export async function loadAutomationExecutionDetailVM({ request, params, }: { request: Request; params: Params & { id?: string; executionId?: string }; }): Promise { const ctx = await loadAutomationContext({ request, params }); const { t } = await getTranslations(request); 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, createdAt: true, startedAt: true, endedAt: true, durationMs: 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, input: true, output: true }, }, }, }); if (!execution) throw new CatalogError(foundationErrors.notFound); const reverseWindowExpiresAt = execution.reverseWindowExpiresAt?.toISOString() ?? null; const steps = execution.stepExecutions; return { rule: { id: execution.rule.id, name: execution.rule.name, executionsUrl: appPath({ tenantSlug: ctx.tenantSlug, path: `automations/${execution.rule.id}/executions`, mode: "host-aware" }), editUrl: appPath({ tenantSlug: ctx.tenantSlug, path: `automations/${execution.rule.id}/edit`, mode: "host-aware" }), }, listUrl: appPath({ tenantSlug: ctx.tenantSlug, path: "automations", mode: "host-aware" }), execution: { id: execution.id, status: execution.status, dryRun: execution.dryRun, triggerKey: execution.triggerKey, summaryText: execution.summaryText, errorText: execution.errorText, createdAt: execution.createdAt.toISOString(), startedAt: execution.startedAt?.toISOString() ?? null, endedAt: execution.endedAt?.toISOString() ?? null, durationMs: execution.durationMs, reverseWindowExpiresAt, canReverse: !!execution.reverseWindowExpiresAt && execution.reverseWindowExpiresAt.getTime() > Date.now(), }, steps, reversePlan: buildAutomationReversePlan({ reverseWindowExpiresAt, steps, confirmationPhrase: String(t("automation.detail.reverse.confirmationPhrase")), }), canRun: ctx.canRun || ctx.canManage, }; }); } 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 }); const { t } = await getTranslations(request); 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, flowData: 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) => { const codeTemplate = template.tenantId === null ? getAutomationPlatformTemplateByStoredName(template.name) : undefined; const translatedTemplate = codeTemplate ? translateAutomationPlatformTemplate(codeTemplate, (key) => String(t(key))) : undefined; return { id: template.id, name: translatedTemplate?.name ?? template.name, description: translatedTemplate?.description ?? template.description, category: template.category, isTenantTemplate: template.tenantId === ctx.tenantId, useCount: template.createdFromRuleId ? useCounts.get(template.createdFromRuleId) ?? 0 : 0, chain: normalizeFlowData(template.flowData).steps.map((step) => ({ kind: step.kind, summaryKey: step.summaryKey, nodeType: step.nodeType })), }; }), rules, listUrl: appPath({ tenantSlug: ctx.tenantSlug, path: "automations", mode: "host-aware" }), 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 { t } = await getTranslations(request); const confirmationPhrase = String(t("automation.editor.dryRun.confirmationPhrase")); const dryRunPreview = await buildRealAutomationDryRunPreview(ctx.tenantId, ruleId, confirmationPhrase); if ( !canConfirmAutomationDryRun({ matchedRecords: dryRunPreview.matchedRecords, confirmationPhrase: formData.get("confirmationPhrase")?.toString(), expectedConfirmationPhrase: confirmationPhrase, }) ) { 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 === "rename") { const name = String(formData.get("name") ?? "").trim(); if (!name) return { ok: false, errorKey: "automation.editor.actions.renameEmpty" }; await withTenantRLS(ctx.tenantId, (tx) => tx.automationRule.update({ where: { id: ruleId }, data: { name } })); return { ok: true, messageKey: "automation.editor.actions.renamed" }; } 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 handleAutomationExecutionDetailAction({ request, params, }: { request: Request; params: Params & { id?: string; executionId?: string }; }): Promise { const ctx = await loadAutomationContext({ request, params }); const ruleId = params.id; const executionId = params.executionId; if (!ruleId || !executionId) throw new CatalogError(foundationErrors.notFound); const formData = await request.formData(); const intent = String(formData.get("intent") ?? ""); // R-P12c: manual retry / resume-from-step create a NEW execution over the // same rule graph and dispatch it durably to the forward executor. if (intent === "retry" || intent === "resume") { if (!ctx.canRun && !ctx.canManage) throw new CatalogError(foundationErrors.notFound, { permission: AUTOMATION_RUN_PERMISSION }); const source = await withTenantRLS(ctx.tenantId, (tx) => tx.automationExecution.findFirst({ where: { id: executionId, tenantId: ctx.tenantId, ruleId }, select: { triggerKey: true, triggerPayload: true, stepExecutions: { select: { id: true, ruleStepId: true } }, }, }) ); if (!source) throw new CatalogError(foundationErrors.notFound); let resumeFromStepId: string | null = null; if (intent === "resume") { const stepExecutionId = String(formData.get("stepExecutionId") ?? ""); const step = source.stepExecutions.find((candidate) => candidate.id === stepExecutionId); if (!step?.ruleStepId) { return { ok: false, errorKey: "automation.detail.resume.unknownStep" }; } resumeFromStepId = step.ruleStepId; } const result = await startAutomationExecutionForRule({ tenantId: ctx.tenantId, tenantSlug: ctx.tenantSlug, userId: ctx.userId, ruleId, triggerKey: source.triggerKey, triggerPayload: jsonRecord(source.triggerPayload), sourceEventId: `${intent}:${executionId}:${crypto.randomUUID()}`, resumeFromStepId, }); return result.status === "queued" ? { ok: true, messageKey: intent === "retry" ? "automation.detail.retry.started" : "automation.detail.resume.started" } : { ok: false, errorKey: "automation.executions.runNow.notStarted" }; } if (!ctx.canManage) throw new CatalogError(foundationErrors.notFound, { permission: AUTOMATION_MANAGE_PERMISSION }); if (intent !== "reverse") { return { ok: false, errorKey: "automation.detail.reverse.unsupportedAction" }; } const { t } = await getTranslations(request); const expectedConfirmationPhrase = String(t("automation.detail.reverse.confirmationPhrase")); if ( !canConfirmAutomationReverse({ confirmationPhrase: formData.get("confirmationPhrase")?.toString(), expectedConfirmationPhrase, }) ) { return { ok: false, errorKey: "automation.detail.reverse.confirmationRequired" }; } try { const reversedCount = await executeAutomationReverse({ tenantId: ctx.tenantId, actorUserId: ctx.userId, ruleId, executionId, }); return { ok: true, messageKey: "automation.detail.reverse.completed", reversedCount }; } catch (error) { if (error instanceof AutomationReverseError) return { ok: false, errorKey: error.errorKey }; throw error; } } export async function executeAutomationReverse(input: { tenantId: string; actorUserId: string; ruleId: string; executionId: string; now?: Date; }): Promise { const now = input.now ?? new Date(); return withTenantRLS(input.tenantId, async (tx) => { const execution = await tx.automationExecution.findFirst({ where: { id: input.executionId, tenantId: input.tenantId, ruleId: input.ruleId }, select: { reverseWindowExpiresAt: true, stepExecutions: { where: { status: "success" }, orderBy: { sortOrder: "desc" }, select: { stepKey: true, nodeType: true, output: true }, }, }, }); if (!execution) throw new AutomationReverseError("automation.detail.reverse.notFound"); if (!execution.reverseWindowExpiresAt || execution.reverseWindowExpiresAt.getTime() <= now.getTime()) { throw new AutomationReverseError("automation.detail.reverse.expired"); } const claim = await tx.automationExecution.updateMany({ where: { id: input.executionId, tenantId: input.tenantId, ruleId: input.ruleId, reverseWindowExpiresAt: { gt: now } }, data: { reverseWindowExpiresAt: null }, }); if (claim.count !== 1) throw new AutomationReverseError("automation.detail.reverse.expired"); let reversedCount = 0; for (const step of execution.stepExecutions) { const output = jsonRecord(step.output); if (step.nodeType === "task.create") { const taskId = outputEntityId(output, "taskId", "createdTaskId", "task"); if (!taskId) throw new AutomationReverseError("automation.detail.reverse.missingOutput"); const result = await tx.task.updateMany({ where: { id: taskId, tenantId: input.tenantId, archivedAt: null }, data: { archivedAt: now } }); if (result.count !== 1) throw new AutomationReverseError("automation.detail.reverse.targetUnavailable"); await logActivity( { tenantId: input.tenantId, actorUserId: input.actorUserId, actorKind: "user", activityType: "automation_reversed", subjectType: "task", subjectId: taskId, summaryText: "automation.activity.reverseTaskCreated", metadata: { executionId: input.executionId, stepKey: step.stepKey }, }, { client: tx } ); reversedCount += 1; continue; } if (step.nodeType === "task.assign") { const taskId = outputEntityId(output, "taskId", "updatedTaskId", "task"); const before = jsonRecord(output.before); const assignedToUserId = nullableString(before.assignedToUserId); const assignedToGroupId = nullableString(before.assignedToGroupId); const hasPreviousAssignment = Object.prototype.hasOwnProperty.call(before, "assignedToUserId") && Object.prototype.hasOwnProperty.call(before, "assignedToGroupId"); if (!taskId || !hasPreviousAssignment || (assignedToUserId !== null && assignedToGroupId !== null)) { throw new AutomationReverseError("automation.detail.reverse.missingOutput"); } const result = await tx.task.updateMany({ where: { id: taskId, tenantId: input.tenantId, archivedAt: null }, data: { assignedToUserId, assignedToGroupId }, }); if (result.count !== 1) throw new AutomationReverseError("automation.detail.reverse.targetUnavailable"); await logActivity( { tenantId: input.tenantId, actorUserId: input.actorUserId, actorKind: "user", activityType: "automation_reversed", subjectType: "task", subjectId: taskId, summaryText: "automation.activity.reverseTaskAssignment", metadata: { executionId: input.executionId, stepKey: step.stepKey }, }, { client: tx } ); reversedCount += 1; continue; } if (step.nodeType === "crm.update_kontakt") { const kontaktId = outputEntityId(output, "kontaktId", "updatedKontaktId", "kontakt"); const before = pickKontaktReverseFields(jsonRecord(output.before)); if (!kontaktId || Object.keys(before).length === 0) throw new AutomationReverseError("automation.detail.reverse.missingOutput"); const result = await tx.kontakt.updateMany({ where: { id: kontaktId, tenantId: input.tenantId, archivedAt: null }, data: before as Prisma.KontaktUpdateManyMutationInput, }); if (result.count !== 1) throw new AutomationReverseError("automation.detail.reverse.targetUnavailable"); await logActivity( { tenantId: input.tenantId, actorUserId: input.actorUserId, actorKind: "user", activityType: "automation_reversed", subjectType: "contact", subjectId: kontaktId, summaryText: "automation.activity.reverseContactUpdate", metadata: { executionId: input.executionId, stepKey: step.stepKey }, }, { client: tx } ); reversedCount += 1; continue; } if (step.nodeType === "crm.add_tag" || step.nodeType === "crm.remove_tag") { const kontaktId = outputEntityId(output, "kontaktId", "updatedKontaktId", "kontakt"); const tagId = outputEntityId(output, "tagId", "updatedTagId", "tag"); const changed = output.changed === true; const beforeAssigned = output.beforeAssigned; if (!kontaktId || !tagId || typeof beforeAssigned !== "boolean") { throw new AutomationReverseError("automation.detail.reverse.missingOutput"); } if (!changed) continue; if ((step.nodeType === "crm.add_tag" && beforeAssigned) || (step.nodeType === "crm.remove_tag" && !beforeAssigned)) { throw new AutomationReverseError("automation.detail.reverse.missingOutput"); } if (step.nodeType === "crm.add_tag") { const result = await tx.tagAssignment.deleteMany({ where: { tenantId: input.tenantId, tagId, entityType: "kontakt", entityId: kontaktId }, }); if (result.count !== 1) throw new AutomationReverseError("automation.detail.reverse.targetUnavailable"); } else { const [kontakt, tag] = await Promise.all([ tx.kontakt.findFirst({ where: { id: kontaktId, tenantId: input.tenantId, archivedAt: null }, select: { id: true } }), tx.tag.findFirst({ where: { id: tagId, tenantId: input.tenantId }, select: { id: true } }), ]); if (!kontakt || !tag) throw new AutomationReverseError("automation.detail.reverse.targetUnavailable"); await tx.tagAssignment.upsert({ where: { tagId_entityId_entityType: { tagId, entityId: kontaktId, entityType: "kontakt" } }, update: {}, create: { tenantId: input.tenantId, tagId, entityType: "kontakt", entityId: kontaktId }, }); } await logActivity( { tenantId: input.tenantId, actorUserId: input.actorUserId, actorKind: "user", activityType: "automation_reversed", subjectType: "contact", subjectId: kontaktId, summaryText: step.nodeType === "crm.add_tag" ? "automation.activity.reverseContactTagAddition" : "automation.activity.reverseContactTagRemoval", metadata: { executionId: input.executionId, stepKey: step.stepKey, tagId }, }, { client: tx } ); reversedCount += 1; continue; } if (step.nodeType === "crm.assign_kontakt") { const kontaktId = outputEntityId(output, "kontaktId", "updatedKontaktId", "kontakt"); const before = jsonRecord(output.before); const hasPreviousAssignment = Object.prototype.hasOwnProperty.call(before, "zustaendigerUserId"); const previousUserId = nullableString(before.zustaendigerUserId); if (!kontaktId || !hasPreviousAssignment || typeof output.changed !== "boolean") { throw new AutomationReverseError("automation.detail.reverse.missingOutput"); } if (output.changed !== true) continue; const result = await tx.kontakt.updateMany({ where: { id: kontaktId, tenantId: input.tenantId, archivedAt: null }, data: { zustaendigerUserId: previousUserId }, }); if (result.count !== 1) throw new AutomationReverseError("automation.detail.reverse.targetUnavailable"); await logActivity( { tenantId: input.tenantId, actorUserId: input.actorUserId, actorKind: "user", activityType: "automation_reversed", subjectType: "contact", subjectId: kontaktId, summaryText: "automation.activity.reverseContactAssignment", metadata: { executionId: input.executionId, stepKey: step.stepKey }, }, { client: tx } ); reversedCount += 1; continue; } if (step.nodeType === "lead.assign") { const leadId = outputEntityId(output, "leadId", "updatedLeadId", "lead"); const before = jsonRecord(output.before); const hasPreviousAssignment = Object.prototype.hasOwnProperty.call(before, "zustaendigerUserId"); const previousUserId = nullableString(before.zustaendigerUserId); if (!leadId || !hasPreviousAssignment || typeof output.changed !== "boolean") { throw new AutomationReverseError("automation.detail.reverse.missingOutput"); } if (output.changed !== true) continue; const result = await tx.inboxLead.updateMany({ where: { id: leadId, tenantId: input.tenantId, archivedAt: null }, data: { zustaendigerUserId: previousUserId }, }); if (result.count !== 1) throw new AutomationReverseError("automation.detail.reverse.targetUnavailable"); await logActivity( { tenantId: input.tenantId, actorUserId: input.actorUserId, actorKind: "user", activityType: "automation_reversed", subjectType: "lead", subjectId: leadId, summaryText: "automation.activity.reverseLeadAssignment", metadata: { executionId: input.executionId, stepKey: step.stepKey }, }, { client: tx } ); reversedCount += 1; continue; } if (step.nodeType === "lead.set_status") { const leadId = outputEntityId(output, "leadId", "updatedLeadId", "lead"); const before = jsonRecord(output.before); const status = nullableString(before.status); const weiterverarbeitungFreigabe = nullableString(before.weiterverarbeitungFreigabe); const convertedAt = nullableDateSnapshot(before.convertedAt); const lostAt = nullableDateSnapshot(before.lostAt); const spamMarkedAt = nullableDateSnapshot(before.spamMarkedAt); const autoDeleteAt = nullableDateSnapshot(before.autoDeleteAt); if ( !leadId || !status || !["new", "qualified", "converted", "lost", "spam"].includes(status) || !weiterverarbeitungFreigabe || !["ja", "nein", "unklar"].includes(weiterverarbeitungFreigabe) || convertedAt === undefined || lostAt === undefined || spamMarkedAt === undefined || autoDeleteAt === undefined || typeof output.changed !== "boolean" ) { throw new AutomationReverseError("automation.detail.reverse.missingOutput"); } if (output.changed !== true) continue; const result = await tx.inboxLead.updateMany({ where: { id: leadId, tenantId: input.tenantId, archivedAt: null }, data: { status: status as never, weiterverarbeitungFreigabe: weiterverarbeitungFreigabe as never, convertedAt, lostAt, spamMarkedAt, autoDeleteAt }, }); if (result.count !== 1) throw new AutomationReverseError("automation.detail.reverse.targetUnavailable"); await logActivity( { tenantId: input.tenantId, actorUserId: input.actorUserId, actorKind: "user", activityType: "automation_reversed", subjectType: "lead", subjectId: leadId, summaryText: "automation.activity.reverseLeadStatus", metadata: { executionId: input.executionId, stepKey: step.stepKey }, }, { client: tx } ); reversedCount += 1; } } if (reversedCount === 0) throw new AutomationReverseError("automation.detail.reverse.nothingReversible"); await tx.automationExecution.update({ where: { id: input.executionId }, data: { summaryText: "automation.execution.reversed" }, }); return reversedCount; }); } export type AutomationListActionData = | { readonly ok: true; readonly messageKey: string; readonly redirectTo?: string } | { readonly ok: false; readonly errorKey: string; readonly detail?: string | null }; export type AutomationExecutionsActionData = | { readonly ok: true; readonly messageKey: string; readonly dryRunPreview?: AutomationDryRunPreview } | { readonly ok: false; readonly errorKey: string; readonly dryRunPreview?: AutomationDryRunPreview }; /** * List-level intents for the S01 automation list (WF-P12 Subframe catch-up): * create / duplicate / archive / activate / pause / create-template. All are * plain web-layer writes on existing models; the execution engine (R-P12b) * stays untouched. */ export async function handleAutomationListAction({ request, params, }: { request: Request; params: Params; }): Promise { const ctx = await loadAutomationContext({ request, params }); if (!ctx.canManage) throw new CatalogError(foundationErrors.notFound, { permission: AUTOMATION_MANAGE_PERMISSION }); const formData = await request.formData(); const intent = String(formData.get("intent") ?? ""); if (intent === "create") { // The M03 dialog always submits a (pre-filled, localized) name — the server // must not invent display strings, so a missing name is a client bug. const requestedName = String(formData.get("ruleName") ?? "").trim(); if (!requestedName) { return { ok: false, errorKey: "automation.list.actions.missingName" }; } // "Leer starten" (M03) submits no triggerKey and opens an empty flow in the // editor; a provided triggerKey pre-seeds the trigger step. const triggerKey = String(formData.get("triggerKey") ?? "").trim(); const trigger = triggerKey ? getAutomationNode(triggerKey) : null; if (triggerKey && (!trigger || trigger.kind !== "trigger")) { return { ok: false, errorKey: "automation.list.actions.invalidTrigger" }; } const rule = await withTenantRLS(ctx.tenantId, async (tx) => { const name = await uniqueAutomationRuleName(tx, ctx.tenantId, requestedName); return tx.automationRule.create({ data: { tenantId: ctx.tenantId, name, status: "draft", enabled: false, createdVia: "manual", triggerKey: triggerKey || null, flowData: toPrismaJson({ triggerKey, steps: trigger ? [{ stepKey: "trigger", kind: "trigger", nodeType: triggerKey, parentStepIds: [], summaryKey: trigger.titleKey }] : [], }), createdByUserId: ctx.userId, steps: trigger ? { create: [ { tenantId: ctx.tenantId, stepKey: "trigger", stepKind: "trigger", nodeType: triggerKey, config: {}, parentStepIds: [], sortOrder: 0, summaryText: trigger.titleKey, }, ], } : undefined, }, select: { id: true }, }); }); return { ok: true, messageKey: "automation.list.actions.created", redirectTo: appPath({ tenantSlug: ctx.tenantSlug, path: `automations/${rule.id}/edit`, mode: "host-aware" }), }; } const ruleId = String(formData.get("ruleId") ?? ""); if (!ruleId) return { ok: false, errorKey: "automation.list.actions.missingRule" }; if (intent === "duplicate") { const created = await withTenantRLS(ctx.tenantId, async (tx) => { const source = await tx.automationRule.findFirst({ where: { id: ruleId, tenantId: ctx.tenantId, archivedAt: null }, select: { name: true, description: true, triggerKey: true, flowData: true, steps: { orderBy: { sortOrder: "asc" }, select: { stepKey: true, stepKind: true, nodeType: true, config: true, parentStepIds: true, position: true, sortOrder: true, summaryText: true }, }, }, }); if (!source) return null; const name = await uniqueAutomationRuleName(tx, ctx.tenantId, `${source.name} (Kopie)`); return tx.automationRule.create({ data: { tenantId: ctx.tenantId, name, description: source.description, status: "draft", enabled: false, createdVia: "duplicate", triggerKey: source.triggerKey, flowData: toPrismaJson(source.flowData), createdByUserId: ctx.userId, steps: { create: source.steps.map((step) => ({ tenantId: ctx.tenantId, stepKey: step.stepKey, stepKind: step.stepKind, nodeType: step.nodeType, config: toPrismaJsonObject(step.config as Record), parentStepIds: [...step.parentStepIds], position: toPrismaJsonObject(step.position as Record), sortOrder: step.sortOrder, summaryText: step.summaryText, })), }, }, select: { id: true }, }); }); if (!created) return { ok: false, errorKey: "automation.list.actions.missingRule" }; return { ok: true, messageKey: "automation.list.actions.duplicated", redirectTo: appPath({ tenantSlug: ctx.tenantSlug, path: `automations/${created.id}/edit`, mode: "host-aware" }), }; } if (intent === "archive") { const result = await withTenantRLS(ctx.tenantId, (tx) => tx.automationRule.updateMany({ where: { id: ruleId, tenantId: ctx.tenantId, archivedAt: null }, data: { archivedAt: new Date(), status: "archived", enabled: false }, }) ); if (result.count === 0) return { ok: false, errorKey: "automation.list.actions.missingRule" }; return { ok: true, messageKey: "automation.list.actions.deletedToast" }; } 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" }; } return { ok: false, errorKey: "automation.list.actions.unknownIntent" }; } /** Dry-run preview from the S02 executions page (M01 dialog); read-only, gated on canRun. */ export async function handleAutomationExecutionsAction({ request, params, }: { request: Request; params: Params & { id?: string }; }): Promise { const ctx = await loadAutomationContext({ request, params }); if (!ctx.canRun && !ctx.canManage) throw new CatalogError(foundationErrors.notFound, { permission: AUTOMATION_RUN_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 === "run-now") { // R-P12c: manual live run — queues an execution and dispatches it durably // to the forward executor. const result = await startAutomationExecutionForRule({ tenantId: ctx.tenantId, tenantSlug: ctx.tenantSlug, userId: ctx.userId, ruleId, triggerPayload: { source: "manual" }, sourceEventId: `manual:${crypto.randomUUID()}`, }); return result.status === "queued" ? { ok: true, messageKey: "automation.executions.runNow.started" } : { ok: false, errorKey: "automation.executions.runNow.notStarted" }; } if (intent !== "dry-run") { throw new CatalogError(foundationErrors.notFound); } const { t } = await getTranslations(request); const confirmationPhrase = String(t("automation.editor.dryRun.confirmationPhrase")); const dryRunPreview = await buildRealAutomationDryRunPreview(ctx.tenantId, ruleId, confirmationPhrase); if ( !canConfirmAutomationDryRun({ matchedRecords: dryRunPreview.matchedRecords, confirmationPhrase: formData.get("confirmationPhrase")?.toString(), expectedConfirmationPhrase: confirmationPhrase, }) ) { return { ok: false, errorKey: "automation.editor.dryRun.confirmationRequired", dryRunPreview }; } return { ok: true, messageKey: "automation.editor.dryRun.previewReady", dryRunPreview }; } async function uniqueAutomationRuleName( tx: { automationRule: { findFirst: (args: { where: { tenantId: string; name: string }; select: { id: true } }) => Promise<{ id: string } | null> } }, tenantId: string, base: string ): Promise { // AutomationRule has @@unique([tenantId, name]) — probe until free. let candidate = base; for (let suffix = 2; suffix < 100; suffix++) { const existing = await tx.automationRule.findFirst({ where: { tenantId, name: candidate }, select: { id: true } }); if (!existing) return candidate; candidate = `${base} ${suffix}`; } return `${base} ${Date.now()}`; } 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 }); // Platform templates have existed both with key-shaped and German seed copy. // Resolve the code-owned definition first, then translate its copy using the // current request. Tenant-authored template text always remains untouched. const { t } = await getTranslations(input.request); 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: { tenantId: true, name: true, description: true, flowData: true }, }); if (!template) throw new CatalogError(foundationErrors.notFound); const codeTemplate = template.tenantId === null ? getAutomationPlatformTemplateByStoredName(template.name) : undefined; const translatedTemplate = codeTemplate ? translateAutomationPlatformTemplate(codeTemplate, (key) => String(t(key))) : undefined; const flowData = normalizeFlowData(translatedTemplate?.flowData ?? 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() || translatedTemplate?.name || template.name, description: translatedTemplate?.description ?? template.description, status: "draft", enabled: false, createdVia: "template", triggerKey: flowData.triggerKey, flowData: toPrismaJson(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: toPrismaJsonObject(step.config), parentStepIds: [...step.parentStepIds], sortOrder: index, summaryText: step.summaryKey, isDemoData: false, })), }, }, 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, config: 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, config: jsonRecord(step.config), 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; /** Defaults to the rule's own trigger key (manual run-now/retry/resume). */ 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 triggerKey = input.triggerKey ?? rule.triggerKey; if (!triggerKey) { throw new CatalogError(foundationErrors.notFound, { ruleId: rule.id, reason: "missing trigger" }); } const idempotencyKey = buildAutomationIdempotencyKey({ tenantId: input.tenantId, ruleId: rule.id, 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 }); 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, 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.summaryKey, 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 }, }); // R-P12c: queued live executions dispatch durably to the forward executor // (outbox row commits atomically with the execution). if (execution.status === "queued" && input.dryRun !== true) { await publishOutboxEvent( tx as unknown as OutboxPublisherTransaction, buildAutomationExecutionRequestedOutboxEvent({ tenantId: input.tenantId, executionId: execution.id }) ); } 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"; summaryKey: 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 } }, // The banner interpolates the concrete numbers from the meter row, so // only the translatable key is persisted here. data: { pausedUntil, anomalyText: AUTOMATION_TRIGGER_VOLUME_ANOMALY_KEY }, }); } return result; }); } function filterNodesForPermissions(nodes: readonly AutomationNodeDefinition[], permissions: readonly string[]): readonly AutomationNodeDefinition[] { return nodes.filter((node) => hasAnyPermission(permissions, node.requiredAnyPermission)); } class AutomationReverseError extends Error { constructor(readonly errorKey: string) { super(errorKey); this.name = "AutomationReverseError"; } } function jsonRecord(value: unknown): Record { return value && typeof value === "object" && !Array.isArray(value) ? (value as Record) : {}; } function nullableString(value: unknown): string | null { return typeof value === "string" && value.length > 0 ? value : null; } function nullableDateSnapshot(value: unknown): Date | null | undefined { if (value === null) return null; if (typeof value !== "string") return undefined; const parsed = new Date(value); return Number.isNaN(parsed.getTime()) ? undefined : parsed; } function outputEntityId(output: Record, directKey: string, alternateKey: string, nestedKey: string): string | null { const direct = nullableString(output[directKey]) ?? nullableString(output[alternateKey]); if (direct) return direct; return nullableString(jsonRecord(output[nestedKey]).id) ?? nullableString(jsonRecord(output.target).id); } function pickKontaktReverseFields(before: Record): Record { const allowed = ["kontaktStatus", "vorname", "nachname", "orgName", "orgMerkmal", "primaerEmail", "primaerTelefon", "zustaendigerUserId", "language"] as const; const result: Record = {}; for (const key of allowed) { if (!Object.prototype.hasOwnProperty.call(before, key)) continue; const value = before[key]; if (typeof value === "string" || value === null) result[key] = value; } return result; } 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 buildRealAutomationDryRunPreview(tenantId: string, ruleId: string, confirmationPhrase: string): Promise { const flow = await loadAutomationEditorFlowForAction(tenantId, ruleId); const trigger = flow.steps.find((step) => step.kind === "trigger"); if (!trigger) return buildAutomationDryRunPreview({ flow, confirmationPhrase }); const sample = await withTenantRLS(tenantId, (tx) => loadAutomationDryRunEventSampleWithTx(tx, { tenantId, ruleId, triggerKey: trigger.nodeType, triggerConfig: trigger.config, }) ); return buildAutomationDryRunPreview({ flow, confirmationPhrase, ...sample }); } 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 === "delete-nodes") { return { type: "delete-nodes", stepKeys: String(formData.get("stepKeys") ?? "") .split(",") .map((key) => key.trim()) .filter(Boolean), }; } if (intent === "paste-steps") return { type: "paste-steps", steps: parseClipboardSteps(formData.get("clipboardJson")) }; if (intent === "duplicate-node") return { type: "duplicate-node", stepKey: String(formData.get("stepKey") ?? "") }; if (intent === "connect") { const branch = formData.get("branch") === "false" ? "false" : formData.get("branch") === "true" ? "true" : undefined; return { type: "connect", fromStepKey: String(formData.get("fromStepKey") ?? ""), toStepKey: String(formData.get("toStepKey") ?? ""), ...(branch ? { branch } : {}), }; } 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 parseClipboardSteps(value: FormDataEntryValue | null): readonly AutomationEditorStepInput[] { if (typeof value !== "string") return []; try { const parsed: unknown = JSON.parse(value); return Array.isArray(parsed) ? (parsed as AutomationEditorStepInput[]) : []; } catch { return []; } } 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 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; config: Record })[] } { 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") : [], config: jsonRecord(step.config), 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"; }