import { createHash } from "node:crypto"; import { z } from "zod"; import { DEFAULT_SALES_LOST_REASONS, DEFAULT_SALES_PIPELINE_STAGES } from "~/utils/integrations/projects/salesPipelineDefaults"; const CONFIG_VALIDATION_MESSAGE = { permissionKeysUnique: "Permission keys must be unique", pipelineStageNamesUnique: "Pipeline stage names must be unique", pipelineWonStageRequired: "A pipeline needs exactly one won stage", pipelineLostStageRequired: "A pipeline needs exactly one lost stage", pipelineOpenStageRequired: "A pipeline needs at least one open stage", activationGatesUnique: "Activation gates must be unique", tenantRoleNamesUnique: "Tenant role names must be unique", salesPipelineNamesUnique: "Pipeline names must be unique", defaultSalesPipelineInvalid: "Vertrieb Wärmepumpe must be the only default pipeline", lostReasonsUnique: "Lost reasons must be unique", automationTemplateKeysUnique: "Automation template keys must be unique", } as const; const permissionKeySchema = z .string() .trim() .min(1) .refine((key) => !key.startsWith("admin."), "Tenant roles cannot reference operator permissions"); const tenantRoleSchema = z .object({ name: z.enum(["Vertrieb", "Marketing", "Innendienst", "Buchhaltung/Verwaltung", "Monteur"]), descriptionKey: z.string().regex(/^tenantBootstrap\.roles\.[a-z][A-Za-z]*\.description$/), type: z.literal("app"), assignToNewUsers: z.literal(false), isDefault: z.literal(false), order: z.number().int().min(100), seatCategory: z.enum(["office", "field"]), isTemplateOrigin: z.literal(true), permissionKeys: z.array(permissionKeySchema).min(1), }) .strict() .superRefine((role, context) => { if (new Set(role.permissionKeys).size !== role.permissionKeys.length) { context.addIssue({ code: z.ZodIssueCode.custom, path: ["permissionKeys"], message: CONFIG_VALIDATION_MESSAGE.permissionKeysUnique }); } }); const pipelineStageSchema = z .object({ name: z.enum(["Neu", "Qualifiziert", "Angebot", "Gewonnen", "Verloren"]), stageKind: z.enum(["offen", "gewonnen", "verloren"]), winProbability: z.number().int().min(0).max(100), color: z.string().regex(/^#[0-9a-f]{6}$/i), position: z.number().int().positive(), }) .strict(); const salesPipelineSchema = z .object({ name: z.enum(["Vertrieb Wärmepumpe", "Vertrieb Photovoltaik", "Vertrieb Badezimmer"]), typHint: z.literal("sales"), position: z.number().int().positive(), isDefault: z.boolean(), isDemoData: z.literal(false), stages: z.array(pipelineStageSchema).length(5), }) .strict() .superRefine((pipeline, context) => { if (new Set(pipeline.stages.map((stage) => stage.name)).size !== pipeline.stages.length) { context.addIssue({ code: z.ZodIssueCode.custom, path: ["stages"], message: CONFIG_VALIDATION_MESSAGE.pipelineStageNamesUnique }); } if (pipeline.stages.filter((stage) => stage.stageKind === "gewonnen").length !== 1) { context.addIssue({ code: z.ZodIssueCode.custom, path: ["stages"], message: CONFIG_VALIDATION_MESSAGE.pipelineWonStageRequired }); } if (pipeline.stages.filter((stage) => stage.stageKind === "verloren").length !== 1) { context.addIssue({ code: z.ZodIssueCode.custom, path: ["stages"], message: CONFIG_VALIDATION_MESSAGE.pipelineLostStageRequired }); } if (!pipeline.stages.some((stage) => stage.stageKind === "offen")) { context.addIssue({ code: z.ZodIssueCode.custom, path: ["stages"], message: CONFIG_VALIDATION_MESSAGE.pipelineOpenStageRequired }); } }); const automationPlaceholderSchema = z .object({ templateKey: z.enum(["shk.order-thank-you.v1", "shk.kwp-project-routing.v1", "shk.follow-up-reminder.v1"]), category: z.literal("shk"), isPublished: z.literal(false), isExecutable: z.literal(false), nodes: z.array(z.never()).length(0), activationGates: z.array(z.string().regex(/^[a-z][a-z0-9.-]+$/)).min(1), }) .strict() .superRefine((placeholder, context) => { if (new Set(placeholder.activationGates).size !== placeholder.activationGates.length) { context.addIssue({ code: z.ZodIssueCode.custom, path: ["activationGates"], message: CONFIG_VALIDATION_MESSAGE.activationGatesUnique }); } }); export const shkV2TenantBootstrapConfigSchema = z .object({ templateKey: z.literal("shk-v2"), schemaVersion: z.literal(1), ownerRole: z .object({ name: z.literal("Admin"), type: z.literal("app"), ownership: z.literal("global"), }) .strict(), tenantRoles: z.array(tenantRoleSchema).length(5), salesPipelines: z.array(salesPipelineSchema).length(3), salesLostReasons: z.array(z.string().trim().min(1)).length(5), automationPlaceholders: z.array(automationPlaceholderSchema).length(3), }) .strict() .superRefine((config, context) => { if (new Set(config.tenantRoles.map((role) => role.name)).size !== config.tenantRoles.length) { context.addIssue({ code: z.ZodIssueCode.custom, path: ["tenantRoles"], message: CONFIG_VALIDATION_MESSAGE.tenantRoleNamesUnique }); } if (new Set(config.salesPipelines.map((pipeline) => pipeline.name)).size !== config.salesPipelines.length) { context.addIssue({ code: z.ZodIssueCode.custom, path: ["salesPipelines"], message: CONFIG_VALIDATION_MESSAGE.salesPipelineNamesUnique }); } const defaultPipelines = config.salesPipelines.filter((pipeline) => pipeline.isDefault); if (defaultPipelines.length !== 1 || defaultPipelines[0]?.name !== "Vertrieb Wärmepumpe") { context.addIssue({ code: z.ZodIssueCode.custom, path: ["salesPipelines"], message: CONFIG_VALIDATION_MESSAGE.defaultSalesPipelineInvalid, }); } if (new Set(config.salesLostReasons).size !== config.salesLostReasons.length) { context.addIssue({ code: z.ZodIssueCode.custom, path: ["salesLostReasons"], message: CONFIG_VALIDATION_MESSAGE.lostReasonsUnique }); } if (new Set(config.automationPlaceholders.map((template) => template.templateKey)).size !== config.automationPlaceholders.length) { context.addIssue({ code: z.ZodIssueCode.custom, path: ["automationPlaceholders"], message: CONFIG_VALIDATION_MESSAGE.automationTemplateKeysUnique, }); } }); export type ShkV2TenantBootstrapConfig = z.infer; export type ShkV2TenantRole = ShkV2TenantBootstrapConfig["tenantRoles"][number]; export type ShkV2SalesPipeline = ShkV2TenantBootstrapConfig["salesPipelines"][number]; export type ShkV2PipelineStage = ShkV2SalesPipeline["stages"][number]; export type ShkV2AutomationPlaceholder = ShkV2TenantBootstrapConfig["automationPlaceholders"][number]; const rawShkV2TenantBootstrapConfig = { templateKey: "shk-v2", schemaVersion: 1, ownerRole: { name: "Admin", type: "app", ownership: "global", }, tenantRoles: [ { name: "Vertrieb", descriptionKey: "tenantBootstrap.roles.sales.description", type: "app", assignToNewUsers: false, isDefault: false, order: 100, seatCategory: "office", isTemplateOrigin: true, permissionKeys: [ "crm.read_own", "crm.read_all", "crm.write", "leads.read_own", "leads.write", "projects.read_own", "projects.read_all", "projects.write", "projects.change_stage", "bookings.read_own", "bookings.write", "calendar.connect_own", "chat.read_own_channels", "chat.write", "chat.create_dm", "dashboard.read", ], }, { name: "Marketing", descriptionKey: "tenantBootstrap.roles.marketing.description", type: "app", assignToNewUsers: false, isDefault: false, order: 101, seatCategory: "office", isTemplateOrigin: true, permissionKeys: [ "crm.read_own", "crm.read_all", "emailMarketing.manage", "forms.basic", "forms.builder", "forms.publisher", "leads.read_own", "leads.write", "bookings.read_own", "chat.read_own_channels", "chat.write", "chat.create_dm", "dashboard.read", ], }, { name: "Innendienst", descriptionKey: "tenantBootstrap.roles.insideSales.description", type: "app", assignToNewUsers: false, isDefault: false, order: 102, seatCategory: "office", isTemplateOrigin: true, permissionKeys: [ "crm.read_own", "crm.read_all", "projects.read_own", "projects.read_all", "projects.write", "files.read_own", "files.write", "hr.read_own", "hr.read_all", "hr.write", "hr.admin", "bookings.read_own", "bookings.write", "bookings.admin", "email.read_own", "email.read_all", "tasks.read_own", "tasks.write", "chat.read_own_channels", "chat.write", "chat.create_dm", "chat.create_channel", "dashboard.read", ], }, { name: "Buchhaltung/Verwaltung", descriptionKey: "tenantBootstrap.roles.accounting.description", type: "app", assignToNewUsers: false, isDefault: false, order: 103, seatCategory: "office", isTemplateOrigin: true, permissionKeys: [ "app.settings.members.view", "app.settings.account.view", "app.settings.subscription.view", "app.settings.subscription.invoices.view", "dashboard.read", ], }, { name: "Monteur", descriptionKey: "tenantBootstrap.roles.technician.description", type: "app", assignToNewUsers: false, isDefault: false, order: 104, seatCategory: "field", isTemplateOrigin: true, permissionKeys: [ "projects.read_own", "projects.read_own_member", "tasks.read_own", "tasks.write", "acceptance.write", "forms.basic", "files.read_own", "files.write", "hr.read_own", "search.use", "chat.read_own_channels", "chat.write", "chat.create_dm", "dashboard.read", ], }, ], salesPipelines: [ { name: "Vertrieb Wärmepumpe", typHint: "sales", position: 10, isDefault: true, isDemoData: false, stages: DEFAULT_SALES_PIPELINE_STAGES, }, { name: "Vertrieb Photovoltaik", typHint: "sales", position: 20, isDefault: false, isDemoData: false, stages: DEFAULT_SALES_PIPELINE_STAGES, }, { name: "Vertrieb Badezimmer", typHint: "sales", position: 30, isDefault: false, isDemoData: false, stages: DEFAULT_SALES_PIPELINE_STAGES, }, ], salesLostReasons: DEFAULT_SALES_LOST_REASONS, automationPlaceholders: [ { templateKey: "shk.order-thank-you.v1", category: "shk", isPublished: false, isExecutable: false, nodes: [], activationGates: ["mail-content.approved", "mail-sender.approved", "mail-recipient.approved"], }, { templateKey: "shk.kwp-project-routing.v1", category: "shk", isPublished: false, isExecutable: false, nodes: [], activationGates: ["kwp-target-pipeline.approved"], }, { templateKey: "shk.follow-up-reminder.v1", category: "shk", isPublished: false, isExecutable: false, nodes: [], activationGates: ["follow-up-timing.approved", "trigger-stage.approved"], }, ], } as const; export const SHK_V2_TENANT_BOOTSTRAP_CONFIG: ShkV2TenantBootstrapConfig = shkV2TenantBootstrapConfigSchema.parse(rawShkV2TenantBootstrapConfig); function canonicalStringify(value: unknown): string { if (value === null || typeof value !== "object") { const serialized = JSON.stringify(value); if (serialized === undefined) { throw new TypeError("Bootstrap config contains a non-JSON value"); } return serialized; } if (Array.isArray(value)) { return `[${value.map(canonicalStringify).join(",")}]`; } const entries = Object.entries(value as Record).sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0)); return `{${entries.map(([key, entry]) => `${JSON.stringify(key)}:${canonicalStringify(entry)}`).join(",")}}`; } export function digestShkV2TenantBootstrapConfig(config: ShkV2TenantBootstrapConfig = SHK_V2_TENANT_BOOTSTRAP_CONFIG): string { const validated = shkV2TenantBootstrapConfigSchema.parse(config); return createHash("sha256").update(canonicalStringify(validated), "utf8").digest("hex"); } /** Validated once at module load so interactive bootstrap transactions do no schema or hashing work. */ export const SHK_V2_TENANT_BOOTSTRAP_CONFIG_DIGEST = digestShkV2TenantBootstrapConfig(SHK_V2_TENANT_BOOTSTRAP_CONFIG);