434 lines
20 KiB
TypeScript
434 lines
20 KiB
TypeScript
export const AUTOMATION_MODULE_KEY = "automation";
|
|
export const AUTOMATION_READ_PERMISSION = "automation.read";
|
|
export const AUTOMATION_MANAGE_PERMISSION = "automation.manage";
|
|
export const AUTOMATION_RUN_PERMISSION = "automation.run";
|
|
export const AUTOMATION_ADMIN_PERMISSION = "automation.admin";
|
|
|
|
export type AutomationNodeGroup =
|
|
| "crm"
|
|
| "lead"
|
|
| "sales"
|
|
| "projects"
|
|
| "email"
|
|
| "forms"
|
|
| "booking"
|
|
| "calendar"
|
|
| "chat"
|
|
| "files"
|
|
| "time"
|
|
| "webhook"
|
|
| "notification"
|
|
| "http"
|
|
| "task"
|
|
| "flow_control"
|
|
| "kwp"
|
|
| "portal";
|
|
export type AutomationNodeKind = "trigger" | "condition" | "action" | "flow_control";
|
|
export type AutomationNodeAvailability = "active" | "extension_slot";
|
|
|
|
export interface AutomationNodeDefinition {
|
|
readonly key: string;
|
|
readonly kind: AutomationNodeKind;
|
|
readonly group: AutomationNodeGroup;
|
|
readonly titleKey: string;
|
|
readonly descriptionKey: string;
|
|
readonly requiredAnyPermission: readonly string[];
|
|
readonly availability: AutomationNodeAvailability;
|
|
readonly defaultConfig: Record<string, string | number | boolean>;
|
|
}
|
|
|
|
export interface AutomationTemplateDefinition {
|
|
readonly key: string;
|
|
readonly nameKey: string;
|
|
readonly descriptionKey: string;
|
|
/**
|
|
* Legacy seed copy used only by the locale-free deployment seed and to match
|
|
* rows written by older revisions. Request paths resolve `nameKey` and
|
|
* `descriptionKey` instead, so this fallback must never become tenant copy.
|
|
*/
|
|
readonly defaultName: string;
|
|
readonly defaultDescription: string;
|
|
readonly category: "crm" | "sales" | "projects" | "operations";
|
|
readonly triggerKey: string;
|
|
readonly steps: readonly {
|
|
readonly stepKey: string;
|
|
readonly kind: AutomationNodeKind;
|
|
readonly nodeType: string;
|
|
readonly parentStepIds: readonly string[];
|
|
readonly summaryKey: string;
|
|
readonly config: Readonly<Record<string, string | number | boolean>>;
|
|
/** Config fields whose code-owned copy is translated per request. */
|
|
readonly configTranslationKeys?: Readonly<Record<string, string>>;
|
|
}[];
|
|
}
|
|
|
|
type AutomationTemplateTranslator = (key: string) => string;
|
|
|
|
// R-P12c: the pure guard functions moved to @hivegrid/db/automation-guards so
|
|
// the worker-side forward executor can share them. Re-exported here so all
|
|
// existing web consumers keep importing from the registry unchanged.
|
|
export {
|
|
AUTOMATION_TRIGGER_VOLUME_ANOMALY_KEY,
|
|
buildAutomationIdempotencyKey,
|
|
buildReverseWindowExpiresAt,
|
|
evaluateLoopGuard,
|
|
evaluateTriggerVolume,
|
|
planAutomationRetry,
|
|
type AutomationGraphStep,
|
|
type AutomationLoopGuardResult,
|
|
type AutomationRetryPlan,
|
|
type AutomationTriggerVolumeInput,
|
|
type AutomationTriggerVolumeResult,
|
|
} from "@hivegrid/db/automation-guards";
|
|
|
|
export const automationTriggerCatalog = Object.freeze([
|
|
trigger("crm.kontakt_created", "crm", ["crm.read_all", "crm.write"]),
|
|
trigger("crm.kontakt_updated", "crm", ["crm.read_all", "crm.write"]),
|
|
trigger("lead.captured", "lead", ["leads.read_all", "leads.write"]),
|
|
trigger("lead.qualified", "lead", ["leads.read_all", "leads.write"]),
|
|
trigger("sales.project_won", "sales", ["projects.read_all", "deals.read_aggregates"]),
|
|
trigger("sales.stage_changed", "sales", ["projects.read_all", "projects.change_stage"]),
|
|
trigger("projects.project_created", "projects", ["projects.read_all", "projects.write"]),
|
|
trigger("projects.deadline_soon", "projects", ["projects.read_all", "projects.read_own_pl"]),
|
|
trigger("email.inbound_received", "email", ["email.domain.view", "emailMarketing.view"]),
|
|
trigger("email.campaign_bounced", "email", ["emailMarketing.view"]),
|
|
trigger("forms.submitted", "forms", ["forms.basic", "forms.builder"]),
|
|
trigger("booking.appointment_booked", "booking", ["bookings.read_all", "bookings.read_own"]),
|
|
trigger("booking.appointment_cancelled", "booking", ["bookings.read_all", "bookings.read_own"]),
|
|
trigger("calendar.event_created", "calendar", ["calendar.connect_own", "calendar.admin"]),
|
|
trigger("time.schedule", "time", [AUTOMATION_MANAGE_PERMISSION]),
|
|
trigger("webhook.received", "webhook", [AUTOMATION_RUN_PERMISSION, AUTOMATION_MANAGE_PERMISSION]),
|
|
trigger("portal.user_created", "portal", ["portal.read", "portal.manage_users"]),
|
|
trigger("portal.setup_completed", "portal", ["portal.activity.read", "portal.manage_users"]),
|
|
trigger("portal.logged_in", "portal", ["portal.activity.read"]),
|
|
trigger("portal.upload_completed", "portal", ["portal.activity.read"]),
|
|
trigger("portal.complaint_submitted", "portal", ["portal.activity.read"]),
|
|
trigger("portal.access_granted", "portal", ["portal.activity.read", "portal.manage_access"]),
|
|
trigger("portal.access_revoked", "portal", ["portal.activity.read", "portal.manage_access"]),
|
|
trigger("portal.document_released", "portal", ["portal.activity.read", "portal.manage_access"]),
|
|
trigger("portal.document_downloaded", "portal", ["portal.activity.read"]),
|
|
trigger("portal.status_mail_sent", "portal", ["portal.activity.read"]),
|
|
trigger("portal.lifecycle_changed", "portal", ["portal.activity.read", "portal.manage_users"]),
|
|
] as const satisfies readonly AutomationNodeDefinition[]);
|
|
|
|
export const automationActionCatalog = Object.freeze([
|
|
action("crm.update_kontakt", "crm", ["crm.write"]),
|
|
action("crm.add_tag", "crm", ["crm.write"]),
|
|
action("crm.remove_tag", "crm", ["crm.write"]),
|
|
action("crm.assign_kontakt", "crm", ["crm.write"]),
|
|
action("crm.create_note", "crm", ["crm.write"]),
|
|
action("lead.assign", "lead", ["leads.write"]),
|
|
action("lead.set_status", "lead", ["leads.write"]),
|
|
extension("lead.convert_to_project", "lead", ["leads.write", "projects.write"]),
|
|
extension("sales.create_project", "sales", ["projects.write"]),
|
|
extension("sales.change_stage", "sales", ["projects.change_stage"]),
|
|
extension("sales.change_volume", "sales", ["projects.write"]),
|
|
extension("sales.assign_project", "sales", ["projects.write"]),
|
|
extension("sales.add_project_tag", "sales", ["projects.write"]),
|
|
extension("sales.move_pipeline", "sales", ["projects.change_stage"]),
|
|
extension("projects.create_project", "projects", ["projects.write"]),
|
|
extension("projects.create_from_won_sales", "projects", ["projects.write"]),
|
|
extension("projects.change_stage", "projects", ["projects.change_stage"]),
|
|
extension("projects.add_member", "projects", ["projects.write"]),
|
|
extension("projects.create_task", "projects", ["projects.write", "tasks.write"]),
|
|
extension("projects.create_appointment", "projects", ["projects.write"]),
|
|
extension("projects.start_acceptance", "projects", ["projects.write"]),
|
|
extension("projects.move_pipeline", "projects", ["projects.change_stage"]),
|
|
action("notification.send", "notification", [AUTOMATION_RUN_PERMISSION]),
|
|
extension("notification.send_push", "notification", [AUTOMATION_RUN_PERMISSION]),
|
|
action("chat.post_message", "chat", ["chat.write"]),
|
|
// R-P12c: external transactional mail via the durable mail outbox (K-A2
|
|
// "E-Mail senden" — was design-only until the forward executor existed).
|
|
action("email.send_transactional", "email", [AUTOMATION_RUN_PERMISSION]),
|
|
action("http.request", "http", [AUTOMATION_RUN_PERMISSION]),
|
|
extension("webhook.send_signed", "webhook", [AUTOMATION_RUN_PERMISSION]),
|
|
extension("calendar.create_event", "calendar", ["calendar.connect_own", "calendar.admin"]),
|
|
extension("calendar.update_event", "calendar", ["calendar.connect_own", "calendar.admin"]),
|
|
extension("files.create_from_url", "files", ["files.write"]),
|
|
action("task.create", "task", ["tasks.write"]),
|
|
action("task.assign", "task", ["tasks.write"]),
|
|
flow("condition.if_else", "flow_control", [AUTOMATION_MANAGE_PERMISSION]),
|
|
flow("delay.wait", "flow_control", [AUTOMATION_MANAGE_PERMISSION]),
|
|
flow("flow.parallel", "flow_control", [AUTOMATION_MANAGE_PERMISSION]),
|
|
flow("flow.merge", "flow_control", [AUTOMATION_MANAGE_PERMISSION]),
|
|
flowExtension("loop.for_each", "flow_control", [AUTOMATION_MANAGE_PERMISSION]),
|
|
extension("kwp.push_project", "kwp", ["integrations.manual_sync", AUTOMATION_MANAGE_PERMISSION]),
|
|
action("portal.invite_user", "portal", ["portal.manage_users"]),
|
|
action("portal.grant_access", "portal", ["portal.manage_access"]),
|
|
action("portal.revoke_access", "portal", ["portal.manage_access"]),
|
|
action("portal.release_document", "portal", ["portal.manage_access"]),
|
|
action("portal.send_status_mail", "portal", ["portal.activity.manage"]),
|
|
action("portal.disable_user", "portal", ["portal.manage_users"]),
|
|
] as const satisfies readonly AutomationNodeDefinition[]);
|
|
|
|
export const automationTemplateCatalog = Object.freeze([
|
|
{
|
|
key: "lead-qualified-follow-up",
|
|
defaultName: "Qualifizierter Lead: Nachfassen",
|
|
defaultDescription: "Legt nach einer Lead-Qualifizierung eine Vertriebsaufgabe an und benachrichtigt das Büro.",
|
|
nameKey: "automation.templates.leadQualifiedFollowUp.name",
|
|
descriptionKey: "automation.templates.leadQualifiedFollowUp.description",
|
|
category: "sales",
|
|
triggerKey: "lead.qualified",
|
|
steps: [
|
|
{
|
|
stepKey: "trigger",
|
|
kind: "trigger",
|
|
nodeType: "lead.qualified",
|
|
parentStepIds: [],
|
|
summaryKey: "automation.steps.triggerLeadQualified",
|
|
config: {},
|
|
},
|
|
{
|
|
stepKey: "create-task",
|
|
kind: "action",
|
|
nodeType: "task.create",
|
|
parentStepIds: ["trigger"],
|
|
summaryKey: "automation.steps.createSalesTask",
|
|
config: { titel: "Qualifizierten Lead nachfassen", zustaendig: "besitzerDerAutomation", faelligkeit: "einTag", prioritaet: "hoch" },
|
|
configTranslationKeys: { titel: "automation.templates.leadQualifiedFollowUp.taskTitle" },
|
|
},
|
|
{
|
|
stepKey: "notify-office",
|
|
kind: "action",
|
|
nodeType: "notification.send",
|
|
parentStepIds: ["create-task"],
|
|
summaryKey: "automation.steps.notifyOffice",
|
|
config: {
|
|
kanal: "intern",
|
|
empfaenger: "besitzerDerAutomation",
|
|
betreff: "Qualifizierter Lead",
|
|
nachricht: "Ein qualifizierter Lead wartet auf Nachverfolgung.",
|
|
},
|
|
configTranslationKeys: {
|
|
betreff: "automation.templates.leadQualifiedFollowUp.notificationSubject",
|
|
nachricht: "automation.templates.leadQualifiedFollowUp.notificationMessage",
|
|
},
|
|
},
|
|
],
|
|
},
|
|
{
|
|
key: "project-deadline-warning",
|
|
defaultName: "Projektfrist früh warnen",
|
|
defaultDescription: "Benachrichtigt die Projektleitung vor kritischen Fristen.",
|
|
nameKey: "automation.templates.projectDeadlineWarning.name",
|
|
descriptionKey: "automation.templates.projectDeadlineWarning.description",
|
|
category: "projects",
|
|
triggerKey: "projects.deadline_soon",
|
|
steps: [
|
|
{
|
|
stepKey: "trigger",
|
|
kind: "trigger",
|
|
nodeType: "projects.deadline_soon",
|
|
parentStepIds: [],
|
|
summaryKey: "automation.steps.triggerProjectDeadline",
|
|
config: { fristtyp: "projektDeadline", leadTime: "3", leadTimeUnit: "tage" },
|
|
},
|
|
{
|
|
stepKey: "notify-project-lead",
|
|
kind: "action",
|
|
nodeType: "notification.send",
|
|
parentStepIds: ["trigger"],
|
|
summaryKey: "automation.steps.notifyProjectLead",
|
|
config: {
|
|
kanal: "intern",
|
|
empfaenger: "besitzerDerAutomation",
|
|
betreff: "Projektfrist naht",
|
|
nachricht: "Eine Projektfrist wird in Kürze erreicht.",
|
|
},
|
|
configTranslationKeys: {
|
|
betreff: "automation.templates.projectDeadlineWarning.notificationSubject",
|
|
nachricht: "automation.templates.projectDeadlineWarning.notificationMessage",
|
|
},
|
|
},
|
|
],
|
|
},
|
|
{
|
|
key: "form-submission-create-task",
|
|
defaultName: "Formularantwort als Aufgabe",
|
|
defaultDescription: "Erstellt aus einer Formularantwort eine Backoffice-Aufgabe.",
|
|
nameKey: "automation.templates.formSubmissionCreateTask.name",
|
|
descriptionKey: "automation.templates.formSubmissionCreateTask.description",
|
|
category: "operations",
|
|
triggerKey: "forms.submitted",
|
|
steps: [
|
|
{
|
|
stepKey: "trigger",
|
|
kind: "trigger",
|
|
nodeType: "forms.submitted",
|
|
parentStepIds: [],
|
|
summaryKey: "automation.steps.triggerFormSubmitted",
|
|
config: {},
|
|
},
|
|
{
|
|
stepKey: "create-task",
|
|
kind: "action",
|
|
nodeType: "task.create",
|
|
parentStepIds: ["trigger"],
|
|
summaryKey: "automation.steps.createBackofficeTask",
|
|
config: { titel: "Formularantwort prüfen", zustaendig: "besitzerDerAutomation", faelligkeit: "einTag", prioritaet: "normal" },
|
|
configTranslationKeys: { titel: "automation.templates.formSubmissionCreateTask.taskTitle" },
|
|
},
|
|
],
|
|
},
|
|
] as const satisfies readonly AutomationTemplateDefinition[]);
|
|
|
|
export function automationTemplateFlowData(template: (typeof automationTemplateCatalog)[number], translate?: AutomationTemplateTranslator) {
|
|
return {
|
|
templateKey: template.key,
|
|
triggerKey: template.triggerKey,
|
|
steps: template.steps.map((step) => ({
|
|
stepKey: step.stepKey,
|
|
kind: step.kind,
|
|
nodeType: step.nodeType,
|
|
parentStepIds: step.parentStepIds,
|
|
summaryKey: step.summaryKey,
|
|
config: Object.fromEntries(
|
|
Object.entries(step.config).map(([field, value]) => {
|
|
const configTranslationKeys =
|
|
"configTranslationKeys" in step ? (step.configTranslationKeys as Readonly<Record<string, string>>) : undefined;
|
|
const translationKey = configTranslationKeys?.[field];
|
|
return [field, translate && translationKey ? translate(translationKey) : value];
|
|
})
|
|
),
|
|
})),
|
|
};
|
|
}
|
|
|
|
export function translateAutomationPlatformTemplate(template: (typeof automationTemplateCatalog)[number], translate: AutomationTemplateTranslator) {
|
|
return {
|
|
name: translate(template.nameKey),
|
|
description: translate(template.descriptionKey),
|
|
flowData: automationTemplateFlowData(template, translate),
|
|
};
|
|
}
|
|
|
|
/** Resolves code-owned platform templates even when a persisted row is from an older seed revision. */
|
|
export function getAutomationPlatformTemplateByStoredName(name: string): (typeof automationTemplateCatalog)[number] | undefined {
|
|
return automationTemplateCatalog.find((template) => template.defaultName === name || template.nameKey === name);
|
|
}
|
|
|
|
const nodeByKey = new Map([...automationTriggerCatalog, ...automationActionCatalog].map((node) => [node.key, node]));
|
|
|
|
export function listAutomationNodes(): readonly AutomationNodeDefinition[] {
|
|
return [...automationTriggerCatalog, ...automationActionCatalog];
|
|
}
|
|
|
|
export function getAutomationNode(key: string): AutomationNodeDefinition | undefined {
|
|
return nodeByKey.get(key);
|
|
}
|
|
|
|
/**
|
|
* Which executor can run a node. `portal.*` nodes are served exclusively by the
|
|
* portal-automation consumer (apps/worker/src/jobs/portal-automation.ts), every
|
|
* other node by the generic forward executor. The two never meet: a portal
|
|
* action in a core flow ends the run as `unsupportedNode`, and the portal
|
|
* consumer rejects a rule whose actions are not all portal actions. Mixing them
|
|
* therefore has to be caught while building, not at runtime.
|
|
*/
|
|
export type AutomationExecutionFamily = "portal" | "core";
|
|
|
|
export function automationExecutionFamily(nodeKey: string): AutomationExecutionFamily {
|
|
return nodeKey.startsWith("portal.") ? "portal" : "core";
|
|
}
|
|
|
|
/**
|
|
* Nodes the catalog lists but no executor implements yet. Active core and
|
|
* portal nodes are backed by their corresponding executor; extension slots
|
|
* remain non-runnable until their provider handler exists (AD-32 / KWP).
|
|
*/
|
|
const NODES_WITHOUT_EXECUTOR = new Set<string>();
|
|
|
|
export function isAutomationNodeRunnable(node: AutomationNodeDefinition): boolean {
|
|
return node.availability === "active" && !NODES_WITHOUT_EXECUTOR.has(node.key);
|
|
}
|
|
|
|
/**
|
|
* Triggers the catalog offers that no emitter publishes yet, so a rule built on
|
|
* them would sit active and never start.
|
|
*/
|
|
export const AUTOMATION_TRIGGERS_WITHOUT_EMITTER: ReadonlySet<string> = new Set();
|
|
|
|
export function assertAutomationNodeExists(key: string): AutomationNodeDefinition {
|
|
const node = getAutomationNode(key);
|
|
if (!node) {
|
|
throw new Error(`Unknown automation node: ${key}`);
|
|
}
|
|
return node;
|
|
}
|
|
|
|
function trigger(key: string, group: AutomationNodeGroup, requiredAnyPermission: readonly string[]): AutomationNodeDefinition {
|
|
return node("trigger", key, group, requiredAnyPermission, "active");
|
|
}
|
|
|
|
function action(key: string, group: AutomationNodeGroup, requiredAnyPermission: readonly string[]): AutomationNodeDefinition {
|
|
return node("action", key, group, requiredAnyPermission, "active");
|
|
}
|
|
|
|
function flow(key: string, group: AutomationNodeGroup, requiredAnyPermission: readonly string[]): AutomationNodeDefinition {
|
|
return node("flow_control", key, group, requiredAnyPermission, "active");
|
|
}
|
|
|
|
function extension(key: string, group: AutomationNodeGroup, requiredAnyPermission: readonly string[]): AutomationNodeDefinition {
|
|
return node("action", key, group, requiredAnyPermission, "extension_slot");
|
|
}
|
|
|
|
function flowExtension(key: string, group: AutomationNodeGroup, requiredAnyPermission: readonly string[]): AutomationNodeDefinition {
|
|
return node("flow_control", key, group, requiredAnyPermission, "extension_slot");
|
|
}
|
|
|
|
function node(
|
|
kind: AutomationNodeKind,
|
|
key: string,
|
|
group: AutomationNodeGroup,
|
|
requiredAnyPermission: readonly string[],
|
|
availability: AutomationNodeAvailability
|
|
): AutomationNodeDefinition {
|
|
const i18nKey = key.replaceAll(".", "_");
|
|
return {
|
|
key,
|
|
kind,
|
|
group,
|
|
titleKey: `automation.nodes.${i18nKey}.title`,
|
|
descriptionKey: `automation.nodes.${i18nKey}.description`,
|
|
requiredAnyPermission,
|
|
availability,
|
|
defaultConfig: automationNodeDefaultConfig(key),
|
|
};
|
|
}
|
|
|
|
function automationNodeDefaultConfig(key: string): Record<string, string | number | boolean> {
|
|
if (key === "crm.update_kontakt") return { kontakt: "ausloeser" };
|
|
if (key === "crm.add_tag" || key === "crm.remove_tag" || key === "crm.assign_kontakt") return { kontakt: "ausloeser" };
|
|
if (key === "lead.assign" || key === "lead.set_status") return { lead: "ausloeser" };
|
|
if (key === "lead.convert_to_project") return { lead: "ausloeser", targetPipelineId: "", targetStageId: "" };
|
|
if (key === "sales.create_project" || key === "projects.create_project") return { pipelineId: "", stageId: "", titel: "" };
|
|
if (key === "sales.change_stage" || key === "projects.change_stage") return { project: "ausloeser", stageId: "" };
|
|
if (key === "sales.change_volume") return { project: "ausloeser", volume: "" };
|
|
if (key === "sales.assign_project" || key === "projects.add_member") return { project: "ausloeser", userId: "" };
|
|
if (key === "sales.add_project_tag") return { project: "ausloeser", tagId: "" };
|
|
if (key === "sales.move_pipeline" || key === "projects.move_pipeline") return { project: "ausloeser", pipelineId: "", stageId: "" };
|
|
if (key === "projects.create_from_won_sales") return { salesProject: "ausloeser", mappingId: "" };
|
|
if (key === "projects.create_task") return { project: "ausloeser", titel: "" };
|
|
if (key === "projects.create_appointment") return { project: "ausloeser", titel: "", startsAt: "", endsAt: "" };
|
|
if (key === "projects.start_acceptance") return { project: "ausloeser" };
|
|
if (key === "crm.create_note") return { datensatz: "kontaktAusAusloeser" };
|
|
if (key === "notification.send") return { kanal: "intern", empfaenger: "besitzerDerAutomation" };
|
|
if (key === "notification.send_push") return { recipient: "besitzerDerAutomation", title: "", message: "" };
|
|
if (key === "chat.post_message") return {};
|
|
if (key === "task.create") return { zustaendig: "besitzerDerAutomation", prioritaet: "normal" };
|
|
if (key === "task.assign") {
|
|
return { aufgabe: "ausVorherigemSchritt", zustaendig: "erstellerDerAufgabe", benachrichtigungAn: "niemand" };
|
|
}
|
|
if (key === "condition.if_else") return { vergleich: "istGleich" };
|
|
if (key === "delay.wait") return { dauer: "2", dauerEinheit: "minuten" };
|
|
if (key === "loop.for_each") return { maxDurchlaeufe: "100" };
|
|
if (key === "http.request") return { methode: "post" };
|
|
if (key === "webhook.send_signed") return { url: "", credentialId: "", body: "" };
|
|
if (key === "calendar.create_event") return { connectionId: "", title: "", startsAt: "", endsAt: "" };
|
|
if (key === "calendar.update_event") return { connectionId: "", eventId: "", title: "", startsAt: "", endsAt: "" };
|
|
if (key === "files.create_from_url") return { url: "", fileName: "" };
|
|
if (key === "portal.invite_user") return { kind: "customer" };
|
|
return {};
|
|
}
|