Refresh HiveGrid Cloud reference snapshot

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

No files matched your search

@@ -4,7 +4,25 @@ export const AUTOMATION_MANAGE_PERMISSION = "automation.manage";
export const AUTOMATION_RUN_PERMISSION = "automation.run";
export const AUTOMATION_ADMIN_PERMISSION = "automation.admin";
export type AutomationNodeGroup = "crm" | "lead" | "sales" | "projects" | "email" | "forms" | "booking" | "calendar" | "time" | "webhook" | "notification" | "http" | "task" | "flow_control" | "kwp";
export type 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";
@@ -23,6 +41,13 @@ 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 {
@@ -31,42 +56,30 @@ export interface AutomationTemplateDefinition {
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>>;
}[];
}
export interface AutomationGraphStep {
readonly stepKey: string;
readonly nodeType: string;
readonly parentStepIds: readonly string[];
}
type AutomationTemplateTranslator = (key: string) => string;
export interface AutomationLoopGuardResult {
readonly ok: boolean;
readonly summaryKey: string;
readonly cycleStepKeys: readonly string[];
readonly dependencyEdges: readonly { readonly from: string; readonly to: string }[];
}
export interface AutomationTriggerVolumeInput {
readonly triggerKey: string;
readonly countInWindow: number;
readonly windowMinutes: number;
readonly typicalDailyMin: number;
readonly typicalDailyMax: number;
readonly hardLimitInWindow: number;
}
export interface AutomationTriggerVolumeResult {
readonly action: "allow" | "pause";
readonly summaryText: string;
}
export interface AutomationRetryPlan {
readonly shouldRetry: boolean;
readonly nextRetryAt: Date | null;
readonly nextAttempt: number;
readonly summaryKey: string;
}
// 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"]),
@@ -85,58 +98,216 @@ export const automationTriggerCatalog = Object.freeze([
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("loop.for_each", "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" },
{ stepKey: "create-task", kind: "action", nodeType: "task.create", parentStepIds: ["trigger"], summaryKey: "automation.steps.createSalesTask" },
{ stepKey: "notify-office", kind: "action", nodeType: "notification.send", parentStepIds: ["create-task"], summaryKey: "automation.steps.notifyOffice" },
{
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" },
{ stepKey: "notify-project-lead", kind: "action", nodeType: "notification.send", parentStepIds: ["trigger"], summaryKey: "automation.steps.notifyProjectLead" },
{
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" },
{ stepKey: "create-task", kind: "action", nodeType: "task.create", parentStepIds: ["trigger"], summaryKey: "automation.steps.createBackofficeTask" },
{
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[] {
@@ -147,6 +318,37 @@ export function getAutomationNode(key: string): AutomationNodeDefinition | undef
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) {
@@ -155,94 +357,6 @@ export function assertAutomationNodeExists(key: string): AutomationNodeDefinitio
return node;
}
export function evaluateLoopGuard(steps: readonly AutomationGraphStep[]): AutomationLoopGuardResult {
const stepKeys = new Set(steps.map((step) => step.stepKey));
const dependencyEdges = steps.flatMap((step) =>
step.parentStepIds.filter((parentStepId) => stepKeys.has(parentStepId)).map((parentStepId) => ({ from: parentStepId, to: step.stepKey }))
);
const outgoing = new Map<string, string[]>();
for (const edge of dependencyEdges) {
outgoing.set(edge.from, [...(outgoing.get(edge.from) ?? []), edge.to]);
}
const visiting = new Set<string>();
const visited = new Set<string>();
const path: string[] = [];
function visit(stepKey: string): string[] | null {
if (visiting.has(stepKey)) {
const start = path.indexOf(stepKey);
return start >= 0 ? path.slice(start).concat(stepKey) : [stepKey];
}
if (visited.has(stepKey)) return null;
visiting.add(stepKey);
path.push(stepKey);
for (const next of outgoing.get(stepKey) ?? []) {
const cycle = visit(next);
if (cycle) return cycle;
}
path.pop();
visiting.delete(stepKey);
visited.add(stepKey);
return null;
}
for (const step of steps) {
const cycle = visit(step.stepKey);
if (cycle) {
return {
ok: false,
summaryKey: "automation.guards.loopDetected",
cycleStepKeys: cycle,
dependencyEdges,
};
}
}
return {
ok: true,
summaryKey: "automation.guards.loopClear",
cycleStepKeys: [],
dependencyEdges,
};
}
export function evaluateTriggerVolume(input: AutomationTriggerVolumeInput): AutomationTriggerVolumeResult {
if (input.countInWindow >= input.hardLimitInWindow) {
return {
action: "pause",
summaryText: `${input.countInWindow} automation triggers in ${input.windowMinutes} minutes for ${input.triggerKey}; typical volume is ${input.typicalDailyMin}-${input.typicalDailyMax} per day. Rule paused for review.`,
};
}
return {
action: "allow",
summaryText: `${input.countInWindow} automation triggers in ${input.windowMinutes} minutes for ${input.triggerKey}; guard within limit.`,
};
}
export function buildAutomationIdempotencyKey(input: { tenantId: string; ruleId: string; triggerKey: string; sourceEventId?: string | null; payloadHash?: string | null }): string {
return [input.tenantId, input.ruleId, input.triggerKey, input.sourceEventId || input.payloadHash || "manual"].join(":");
}
export function planAutomationRetry(input: { attempt: number; maxAttempts?: number; baseDelayMs?: number; now?: Date }): AutomationRetryPlan {
const maxAttempts = input.maxAttempts ?? 3;
const nextAttempt = input.attempt + 1;
if (nextAttempt > maxAttempts) {
return { shouldRetry: false, nextRetryAt: null, nextAttempt, summaryKey: "automation.guards.retryExhausted" };
}
const delayMs = (input.baseDelayMs ?? 60_000) * 2 ** Math.max(input.attempt - 1, 0);
return {
shouldRetry: true,
nextRetryAt: new Date((input.now ?? new Date()).getTime() + delayMs),
nextAttempt,
summaryKey: "automation.guards.retryScheduled",
};
}
export function buildReverseWindowExpiresAt(now = new Date()): Date {
return new Date(now.getTime() + 24 * 60 * 60 * 1000);
}
function trigger(key: string, group: AutomationNodeGroup, requiredAnyPermission: readonly string[]): AutomationNodeDefinition {
return node("trigger", key, group, requiredAnyPermission, "active");
}
@@ -259,7 +373,17 @@ function extension(key: string, group: AutomationNodeGroup, requiredAnyPermissio
return node("action", key, group, requiredAnyPermission, "extension_slot");
}
function node(kind: AutomationNodeKind, key: string, group: AutomationNodeGroup, requiredAnyPermission: readonly string[], availability: AutomationNodeAvailability): AutomationNodeDefinition {
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,
@@ -269,6 +393,41 @@ function node(kind: AutomationNodeKind, key: string, group: AutomationNodeGroup,
descriptionKey: `automation.nodes.${i18nKey}.description`,
requiredAnyPermission,
availability,
defaultConfig: {},
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 {};
}