Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/apps/web/app/services/automation/automation.registry.test.ts
T

257 lines
11 KiB
TypeScript

import { describe, expect, it } from "vitest";
import { AUTOMATION_CORE_EXECUTOR_NODE_TYPES } from "@hivegrid/db/automation-executor.server";
import {
AUTOMATION_MODULE_KEY,
AUTOMATION_READ_PERMISSION,
AUTOMATION_TRIGGERS_WITHOUT_EMITTER,
automationActionCatalog,
automationTemplateCatalog,
automationTemplateFlowData,
automationTriggerCatalog,
buildAutomationIdempotencyKey,
buildReverseWindowExpiresAt,
evaluateLoopGuard,
evaluateTriggerVolume,
getAutomationPlatformTemplateByStoredName,
listAutomationNodes,
planAutomationRetry,
translateAutomationPlatformTemplate,
} from "./automation.registry";
import { buildAutomationEditorFlow, validateAutomationEditorFlow } from "./automation.editor";
describe("automation registry contract", () => {
it("uses the R-P12a module and permission keys", () => {
expect(AUTOMATION_MODULE_KEY).toBe("automation");
expect(AUTOMATION_READ_PERMISSION).toBe("automation.read");
});
it("covers the required trigger and action groups", () => {
expect(new Set(automationTriggerCatalog.map((node) => node.group))).toEqual(
new Set(["crm", "lead", "sales", "projects", "email", "forms", "booking", "calendar", "time", "webhook", "portal"])
);
expect(new Set(automationActionCatalog.map((node) => node.group))).toEqual(
new Set([
"crm",
"lead",
"sales",
"projects",
"notification",
"chat",
"email",
"webhook",
"calendar",
"files",
"http",
"task",
"flow_control",
"kwp",
"portal",
])
);
expect(automationActionCatalog.find((node) => node.key === "kwp.push_project")?.availability).toBe("extension_slot");
expect(
automationActionCatalog
.filter((node) => ["crm.add_tag", "crm.remove_tag", "crm.assign_kontakt"].includes(node.key))
.every((node) => node.availability === "active")
).toBe(true);
expect(
automationActionCatalog.filter((node) => ["lead.assign", "lead.set_status"].includes(node.key)).every((node) => node.availability === "active")
).toBe(true);
expect(automationActionCatalog.find((node) => node.key === "chat.post_message")?.availability).toBe("active");
expect(automationActionCatalog.filter((node) => ["flow.parallel", "flow.merge"].includes(node.key)).every((node) => node.availability === "active")).toBe(
true
);
expect(automationActionCatalog.find((node) => node.key === "loop.for_each")).toMatchObject({ kind: "flow_control", availability: "extension_slot" });
expect(listAutomationNodes()).toHaveLength(automationTriggerCatalog.length + automationActionCatalog.length);
});
it("prepares every still-missing Phase-1 action without making it runnable", () => {
expect(automationActionCatalog.filter((node) => node.availability === "extension_slot").map((node) => node.key)).toEqual([
"lead.convert_to_project",
"sales.create_project",
"sales.change_stage",
"sales.change_volume",
"sales.assign_project",
"sales.add_project_tag",
"sales.move_pipeline",
"projects.create_project",
"projects.create_from_won_sales",
"projects.change_stage",
"projects.add_member",
"projects.create_task",
"projects.create_appointment",
"projects.start_acceptance",
"projects.move_pipeline",
"notification.send_push",
"webhook.send_signed",
"calendar.create_event",
"calendar.update_event",
"files.create_from_url",
"loop.for_each",
"kwp.push_project",
]);
});
it("never exposes an active core action without a real executor handler", () => {
const activeCoreNodes = automationActionCatalog.filter((node) => node.availability === "active" && node.group !== "portal");
expect(activeCoreNodes.map((node) => node.key).filter((key) => !AUTOMATION_CORE_EXECUTOR_NODE_TYPES.has(key))).toEqual([]);
});
it("registers the complete P26b portal trigger and action contracts", () => {
expect(automationTriggerCatalog.filter((node) => node.group === "portal").map((node) => node.key)).toEqual([
"portal.user_created",
"portal.setup_completed",
"portal.logged_in",
"portal.upload_completed",
"portal.complaint_submitted",
"portal.access_granted",
"portal.access_revoked",
"portal.document_released",
"portal.document_downloaded",
"portal.status_mail_sent",
"portal.lifecycle_changed",
]);
expect(automationActionCatalog.filter((node) => node.group === "portal").map((node) => node.key)).toEqual([
"portal.invite_user",
"portal.grant_access",
"portal.revoke_access",
"portal.release_document",
"portal.send_status_mail",
"portal.disable_user",
]);
for (const node of [...automationTriggerCatalog, ...automationActionCatalog].filter((entry) => entry.group === "portal")) {
expect(node.availability).toBe("active");
expect(node.requiredAnyPermission.every((permission) => permission.startsWith("portal."))).toBe(true);
}
});
it("tracks every catalog trigger that has no production emitter", () => {
expect([...AUTOMATION_TRIGGERS_WITHOUT_EMITTER].sort()).toEqual([]);
expect(AUTOMATION_TRIGGERS_WITHOUT_EMITTER.has("webhook.received")).toBe(false);
});
it("ships platform templates that can become rules", () => {
expect(automationTemplateCatalog.map((template) => template.key)).toEqual([
"lead-qualified-follow-up",
"project-deadline-warning",
"form-submission-create-task",
]);
for (const template of automationTemplateCatalog) {
expect(template.steps[0]?.kind).toBe("trigger");
expect(template.steps.map((step) => step.stepKey)).toContain("trigger");
const flowData = automationTemplateFlowData(template);
const flow = buildAutomationEditorFlow({ flowData, steps: flowData.steps });
expect(validateAutomationEditorFlow(flow).issues).toEqual([]);
expect(validateAutomationEditorFlow(flow).canActivate).toBe(true);
expect(getAutomationPlatformTemplateByStoredName(template.defaultName)?.key).toBe(template.key);
expect(getAutomationPlatformTemplateByStoredName(template.nameKey)?.key).toBe(template.key);
}
});
it("translates all code-owned template copy without changing config semantics", () => {
const translationKeys: string[] = [];
const translate = (key: string) => {
translationKeys.push(key);
return `translated:${key}`;
};
const [leadTemplate, deadlineTemplate, formTemplate] = automationTemplateCatalog;
const translatedLead = translateAutomationPlatformTemplate(leadTemplate, translate);
const translatedDeadline = translateAutomationPlatformTemplate(deadlineTemplate, translate);
const translatedForm = translateAutomationPlatformTemplate(formTemplate, translate);
expect(translatedLead.name).toBe("translated:automation.templates.leadQualifiedFollowUp.name");
expect(translatedLead.description).toBe("translated:automation.templates.leadQualifiedFollowUp.description");
expect(translatedLead.flowData.steps.find((step) => step.stepKey === "create-task")?.config).toMatchObject({
titel: "translated:automation.templates.leadQualifiedFollowUp.taskTitle",
zustaendig: "besitzerDerAutomation",
faelligkeit: "einTag",
prioritaet: "hoch",
});
expect(translatedLead.flowData.steps.find((step) => step.stepKey === "notify-office")?.config).toMatchObject({
betreff: "translated:automation.templates.leadQualifiedFollowUp.notificationSubject",
nachricht: "translated:automation.templates.leadQualifiedFollowUp.notificationMessage",
});
expect(translatedDeadline.flowData.steps.find((step) => step.stepKey === "notify-project-lead")?.config).toMatchObject({
betreff: "translated:automation.templates.projectDeadlineWarning.notificationSubject",
nachricht: "translated:automation.templates.projectDeadlineWarning.notificationMessage",
});
expect(translatedForm.flowData.steps.find((step) => step.stepKey === "create-task")?.config.titel).toBe(
"translated:automation.templates.formSubmissionCreateTask.taskTitle"
);
expect(translationKeys).toEqual([
"automation.templates.leadQualifiedFollowUp.name",
"automation.templates.leadQualifiedFollowUp.description",
"automation.templates.leadQualifiedFollowUp.taskTitle",
"automation.templates.leadQualifiedFollowUp.notificationSubject",
"automation.templates.leadQualifiedFollowUp.notificationMessage",
"automation.templates.projectDeadlineWarning.name",
"automation.templates.projectDeadlineWarning.description",
"automation.templates.projectDeadlineWarning.notificationSubject",
"automation.templates.projectDeadlineWarning.notificationMessage",
"automation.templates.formSubmissionCreateTask.name",
"automation.templates.formSubmissionCreateTask.description",
"automation.templates.formSubmissionCreateTask.taskTitle",
]);
});
it("keeps locale-free seed copy stable and excludes translation metadata", () => {
const [template] = automationTemplateCatalog;
const flowData = automationTemplateFlowData(template);
expect(flowData.steps.find((step) => step.stepKey === "create-task")?.config.titel).toBe("Qualifizierten Lead nachfassen");
expect(flowData.steps.every((step) => !("configTranslationKeys" in step))).toBe(true);
});
it("detects dependency cycles for loop guard warnings", () => {
expect(
evaluateLoopGuard([
{ stepKey: "a", nodeType: "trigger", parentStepIds: ["c"] },
{ stepKey: "b", nodeType: "task.create", parentStepIds: ["a"] },
{ stepKey: "c", nodeType: "notification.send", parentStepIds: ["b"] },
])
).toMatchObject({ ok: false, cycleStepKeys: ["a", "b", "c", "a"] });
expect(
evaluateLoopGuard([
{ stepKey: "trigger", nodeType: "lead.qualified", parentStepIds: [] },
{ stepKey: "task", nodeType: "task.create", parentStepIds: ["trigger"] },
]).ok
).toBe(true);
});
it("builds idempotency keys and 24h reverse windows deterministically", () => {
expect(buildAutomationIdempotencyKey({ tenantId: "t1", ruleId: "r1", triggerKey: "lead.qualified", sourceEventId: "evt1" })).toBe(
"t1:r1:lead.qualified:evt1"
);
expect(buildReverseWindowExpiresAt(new Date("2026-07-01T10:00:00.000Z")).toISOString()).toBe("2026-07-02T10:00:00.000Z");
});
it("pauses anomalous trigger volumes with Klartext diagnostics", () => {
const result = evaluateTriggerVolume({
triggerKey: "lead.qualified",
countInWindow: 2000,
windowMinutes: 5,
typicalDailyMin: 5,
typicalDailyMax: 10,
hardLimitInWindow: 2000,
});
expect(result.action).toBe("pause");
expect(result.summaryText).toContain("2000 automation triggers in 5 minutes");
expect(result.summaryText).toContain("typical volume is 5-10 per day");
});
it("plans bounded auto retries for resumable executions", () => {
const retry = planAutomationRetry({ attempt: 1, baseDelayMs: 1_000, now: new Date("2026-07-01T10:00:00.000Z") });
expect(retry).toMatchObject({ shouldRetry: true, nextAttempt: 2, summaryKey: "automation.guards.retryScheduled" });
expect(retry.nextRetryAt?.toISOString()).toBe("2026-07-01T10:00:01.000Z");
expect(planAutomationRetry({ attempt: 3, maxAttempts: 3 })).toMatchObject({
shouldRetry: false,
nextAttempt: 4,
summaryKey: "automation.guards.retryExhausted",
});
});
});